@sage-rsc/talking-head-react 1.2.2 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const re=require("react/jsx-runtime"),R=require("react"),Ge=require("three"),Ze=require("three/addons/controls/OrbitControls.js"),Xe=require("three/addons/loaders/GLTFLoader.js"),je=require("three/addons/loaders/DRACOLoader.js"),Pe=require("three/addons/loaders/FBXLoader.js"),Ye=require("three/addons/environments/RoomEnvironment.js"),Qe=require("three/addons/libs/stats.module.js");var He=typeof document<"u"?document.currentScript:null;function qe(O){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(O){for(const e in O)if(e!=="default"){const n=Object.getOwnPropertyDescriptor(O,e);Object.defineProperty(t,e,n.get?n:{enumerable:!0,get:()=>O[e]})}}return t.default=O,Object.freeze(t)}const f=qe(Ge);let m,ae,ue;const C=[0,0,0,0],M=new f.Vector3,Se=new f.Vector3,ne=new f.Vector3,we=new f.Vector3;new f.Plane;new f.Ray;new f.Euler;const ie=new f.Quaternion,Be=new f.Quaternion,pe=new f.Matrix4,ge=new f.Matrix4;new f.Vector3;const Ce=new f.Vector3(0,0,1),_e=new f.Vector3(1,0,0),Ke=new f.Vector3(0,1,0),Je=new f.Vector3(0,0,1);class $e{constructor(t=null){this.opt=Object.assign({warmupMs:2e3,sensitivityFactor:1,movementFactor:1,isExcludes:!0,isPivots:!0,isLimits:!0,helperBoneColor1:16711680,helperBoneColor2:16238028,helperLinkColor1:16711680,helperLinkColor2:255,helperExcludesColor:11184895},t||{}),this.scene=null,this.armature=null,this.config=[],this.data=[],this.dict={},this.objectsUpdate=[],this.helpers={isActive:!1,isShowAll:!1,points:{bones:[],pivots:[],object:null},lines:{bones:[],object:null},excludes:{bones:[],deltaLocals:[],radii:[],objects:[]}},this.running=!1,this.timerMs=0}getOptionValue(t){return this.opt[t]}setOptionValue(t,e){this.opt[t]=e,this.helpers.isActive&&this.showHelpers()}getBoneNames(){return this.data.map(t=>t.name)}getValue(t,e){if(this.scene===null)throw new Error("Dynamic bones has not been setup yet.");if(!this.dict.hasOwnProperty(t))throw new Error("Dynamic bone '"+t+"' not found.");const n=this.dict[t];let i;if(e==="type")i=n.type;else if(e==="stiffness")i=n.k.every(s=>s===n.k[0])?n.k[0]:[...n.k];else if(e==="damping")i=n.c.every(s=>s===n.c[0])?n.c[0]:[...n.c];else if(e==="external")i=n.ext<1?n.ext:null;else if(e==="limits")i=n.limits?.map(s=>s===null?null:[...s]);else if(e==="deltaLocal")i=n.dl?[...n.dl]:null;else if(e==="excludes")i=n.excludes?[...n.excludes.map(s=>{const o={bone:s.bone.name.slice(),radius:s.radius};return s.deltaLocal&&(o.deltaLocal=[...s.deltaLocal]),o})]:null;else if(e==="deltaWorld")i=n.dw?[...n.dw]:null;else if(e==="pivot")i=n.pivot;else if(e==="helper")i=n.helper;else throw new Error("Unsupported property '"+e+"'.");return i}setValue(t,e,n){if(this.scene===null)throw new Error("Dynamic bones has not been setup yet.");if(!this.dict.hasOwnProperty(t))throw new Error("Dynamic bone '"+t+"' not found.");const i=this.dict[t];if(e==="type"){if(!n)throw new Error("Parameter 'type' not set.");if(typeof n!="string")throw new Error("Type must be a string.");switch(n){case"point":i.isPoint=!0,i.isX=!0,i.isY=!0,i.isZ=!0,i.isT=!1;break;case"link":i.isPoint=!1,i.isX=!0,i.isY=!1,i.isZ=!0,i.isT=!1;break;case"mix1":i.isPoint=!1,i.isX=!0,i.isY=!0,i.isZ=!0,i.isT=!1;break;case"mix2":i.isPoint=!1,i.isX=!0,i.isY=!1,i.isZ=!0,i.isT=!0;break;case"full":i.isPoint=!1,i.isX=!0,i.isY=!0,i.isZ=!0,i.isT=!0;break;default:throw new Error("Unknown type'"+n+"'.")}i.type=n.slice()}else if(e==="stiffness"){if(!n)throw new Error("Parameter 'stiffness' not set.");if(!Number.isNaN(n)&&n>=0)i.k=Array(4).fill(n);else if(Array.isArray(n)&&n.length===4&&n.every(s=>s>=0))i.k=[...n];else throw new Error("Stiffness must be a non-negative number or an array of four non-negative numbers.")}else if(e==="damping"){if(!n)throw new Error("Parameter 'damping' not set.");if(!Number.isNaN(n)&&n>=0)i.c=Array(4).fill(n);else if(Array.isArray(n)&&n.length===4&&n.every(s=>s>=0))i.c=[...n];else throw new Error("Damping must be a non-negative number or an array of four non-negative numbers.")}else if(e==="external")if(n==null)i.ext=1;else if(!Number.isNaN(n)&&n>=0&&n<=1)i.ext=n;else throw new Error("External (if set) must be a number between [0,1].");else if(e==="limits")if(n==null)i.limits=null;else{if(!Array.isArray(n)||n.length!==4)throw new Error("Limits (if set) must null, or an array of four arrays.");if(!n.every(s=>s===null||Array.isArray(s)&&s.length===2&&(s[0]===null||!Number.isNaN(s[0]))&&(s[1]===null||!Number.isNaN(s))))throw new Error("Limit values must be null or numbers.");i.limits=[n[0]?[...n[0]]:null,n[1]?[...n[1]]:null,n[2]?[...n[2]]:null,n[3]?[...n[3]]:null]}else if(e==="excludes"){if(n==null)i.excludes=null;else{if(!Array.isArray(n))throw new Error("Excludes (if set) must null, or an array.");i.excludes=[],n.forEach((s,o)=>{if(!s.bone)throw new Error("Bone not specified in #"+o+" exclude.");if(typeof s.bone!="string"||s.bone.length===0)throw new Error("Bone name must be a non-empty string in #"+o+" exclude.");const l=this.armature.getObjectByName(s.bone);if(!l)throw new Error("Bone '"+s.bone+"' not found in #"+o+" exclude.");if(Number.isNaN(s.radius)&&s.radius>=0)throw new Error("Radius must be a non-negative number in #"+o+" exclude.");const h={bone:l,radius:s.radius,radiusSq:s.radius*s.radius,deltaLocal:null};if(s.deltaLocal){if(!Array.isArray(s.deltaLocal)||s.deltaLocal.length!==3||s.deltaLocal.some(r=>Number.isNaN(r)))throw new Error("deltaLocal must be an array of three numbers in #"+o+" exclude.");h.deltaLocal=[...s.deltaLocal]}i.excludes.push(h)})}this.showHelpers()}else if(e==="helper"){if(n==null)i.helper=null;else{if(n!==!1&&n!==!0)throw new Error("Helper, if set, must be false or true.");i.helper=n}this.showHelpers()}else if(e==="pivot")if(n==null)i.pivot=null;else{if(n!==!1&&n!==!0)throw new Error("Pivot, if set, must be false or true.");if(n===!0&&i.type===0)throw new Error("Point type bone can't be a pivot.");i.pivot=n}else if(e==="deltaLocal")if(n==null)i.dl=null;else{if(!Array.isArray(n)||n.length!==3)throw new Error("deltaLocal, is set, must be an array of three numbers.");if(!n.every(s=>!Number.isNaN(s)))throw new Error("deltaLocal values must be numbers.");i.dl=[...n]}else if(e==="deltaWorld")if(n==null)i.dw=null;else{if(!Array.isArray(n)||n.length!==3)throw new Error("deltaWorld, is set, must be an array of three values.");if(!n.every(s=>!Number.isNaN(s)))throw new Error("deltaWorld values must be numbers.");i.dw=[...n]}else throw new Error("Unsupported property "+e)}getConfig(){return this.data.map(t=>{const e={bone:t.name.slice()};return["type","stiffness","damping","external","deltaLocal","deltaWorld","limits","excludes","pivot","helper"].forEach(n=>{m=this.getValue(t.name,n),m&&(e[n]=m)}),e})}sortBones(){if(this.scene===null)throw new Error("Dynamic bones has not been setup yet.");let t=0;const e=new WeakMap;this.armature.traverse(o=>{e.has(o)||(e.set(o,t),t++)}),this.data.sort((o,l)=>e.get(o.bone)-e.get(l.bone)),this.data.forEach(o=>{m=this.dict[o.boneParent.name],m&&(m.children||(m.children=[]),m.children.push(o))}),this.objectsUpdate=[];const n=new WeakSet,i=o=>o.parent?.isBone?[o,...i(o.parent)]:[o],s=o=>{i(o).forEach(h=>{n.has(h)||(this.objectsUpdate.push(h),n.add(h))})};this.data.forEach(o=>{s(o.bone),o.excludes&&o.excludes.forEach(l=>{s(l.bone)})}),this.objectsUpdate.sort((o,l)=>e.get(o)-e.get(l))}setup(t,e,n){this.dispose();const i=(s,o)=>{if(!s)throw this.dispose(),new Error(o)};i(t?.isScene,"First parameter must be Scene."),this.scene=t,i(e?.isObject3D,"Second parameter must be the armature Object3D."),this.armature=e,i(Array.isArray(n),"Third parameter must be an array of bone configs."),this.config=n,this.config.forEach((s,o)=>{const l="Config item #"+o+": ";i(s.bone,l+"Bone not specified.");const h=s.bone;i(typeof h=="string"&&h.length>0,l+"Bone name must be a non-empty string.");const r=this.armature.getObjectByName(h);i(r,l+"Bone '"+h+"' not found."),i(r.parent?.isBone,l+"Bone must have a parent bone."),i(this.data.every(a=>a.bone!==r),l+"Bone '"+h+"' already exists."),r.updateMatrixWorld(!0);const u={name:h,bone:r,boneParent:r.parent,vBasis:r.position.clone(),vWorld:r.parent.getWorldPosition(M).clone(),qBasis:r.parent.quaternion.clone(),l:r.position.length(),p:[0,0,0,0],v:[0,0,0,0],a:[0,0,0,0],ev:[0,0,0,0],ea:[0,0,0,0]};u.boneParent.matrixWorld.decompose(M,ie,ne),M.copy(Ce).applyQuaternion(ie).setY(0).normalize(),ie.premultiply(Be.setFromUnitVectors(Ce,M).invert()).normalize(),u.qWorldInverseYaw=ie.clone().normalize(),this.data.push(u),this.dict[h]=u;try{this.setValue(h,"type",s.type),this.setValue(h,"stiffness",s.stiffness),this.setValue(h,"damping",s.damping),this.setValue(h,"external",s.external),this.setValue(h,"limits",s.limits),this.setValue(h,"excludes",s.excludes),this.setValue(h,"deltaLocal",s.deltaLocal),this.setValue(h,"deltaWorld",s.deltaWorld),this.setValue(h,"pivot",s.pivot),this.setValue(h,"helper",s.helper)}catch(a){i(!1,l+a)}}),this.sortBones(),this.start()}update(t){if(!this.running)return;let e,n,i,s,o;for(this.timerMs+=t,t>1e3&&(this.timerMs=0),t/=1e3,e=0,i=this.objectsUpdate.length;e<i;e++)o=this.objectsUpdate[e],o.updateMatrix(),o.parent===null?o.matrixWorld.copy(o.matrix):o.matrixWorld.multiplyMatrices(o.parent.matrixWorld,o.matrix),o.matrixWorldNeedsUpdate=!1;for(e=0,i=this.data.length;e<i;e++){if(o=this.data[e],M.copy(o.vWorld),pe.copy(o.boneParent.matrixWorld),ge.copy(pe).invert(),o.vWorld.setFromMatrixPosition(pe),M.applyMatrix4(ge),M.length()>.5&&(console.info("Info: Unrealistic jump of "+M.length().toFixed(2)+" meters."),M.setLength(.5)),M.applyQuaternion(o.bone.quaternion),C[0]=M.x,C[1]=M.y,C[2]=-M.z,C[3]=M.length()/3,o.children)for(n=0,s=o.children.length;n<s;n++)m=o.children[n],C[0]-=m.v[0]*t/3,C[1]-=m.v[1]*t/3,C[2]+=m.v[2]*t/3,C[3]-=m.v[3]*t/3;if(m=this.opt.sensitivityFactor,C[0]*=o.ext*m,C[1]*=o.ext*m,C[2]*=o.ext*m,C[3]*=o.ext*m,o.isX&&(m=C[0]/t,o.ea[0]=(m-o.ev[0])/t,o.ev[0]=m,o.a[0]=-o.k[0]*o.p[0]-o.c[0]*o.v[0]-o.ea[0],o.p[0]+=o.v[0]*t+o.a[0]*t*t/2+C[0],m=o.v[0]+o.a[0]*t/2,m=-o.k[0]*o.p[0]-o.c[0]*m-o.ea[0],o.v[0]=o.v[0]+(m+o.a[0])*t/2),o.isY&&(m=C[1]/t,o.ea[1]=(m-o.ev[1])/t,o.ev[1]=m,o.a[1]=-o.k[1]*o.p[1]-o.c[1]*o.v[1]-o.ea[1],o.p[1]+=o.v[1]*t+o.a[1]*t*t/2+C[1],m=o.v[1]+o.a[1]*t/2,m=-o.k[1]*o.p[1]-o.c[1]*m-o.ea[1],o.v[1]=o.v[1]+(m+o.a[1])*t/2),o.isZ&&(m=C[2]/t,o.ea[2]=(m-o.ev[2])/t,o.ev[2]=m,o.a[2]=-o.k[2]*o.p[2]-o.c[2]*o.v[2]-o.ea[2],o.p[2]+=o.v[2]*t+o.a[2]*t*t/2+C[2],m=o.v[2]+o.a[2]*t/2,m=-o.k[2]*o.p[2]-o.c[2]*m-o.ea[2],o.v[2]=o.v[2]+(m+o.a[2])*t/2),o.isT&&(m=C[3]/t,o.ea[3]=(m-o.ev[3])/t,o.ev[3]=m,o.a[3]=-o.k[3]*o.p[3]-o.c[3]*o.v[3]-o.ea[3],o.p[3]+=o.v[3]*t+o.a[3]*t*t/2+C[3],m=o.v[3]+o.a[3]*t/2,m=-o.k[3]*o.p[3]-o.c[3]*m-o.ea[3],o.v[3]=o.v[3]+(m+o.a[3])*t/2),this.timerMs<this.opt.warmupMs&&(o.v[0]*=1e-4,o.p[0]*=1e-4,o.v[1]*=1e-4,o.p[1]*=1e-4,o.v[2]*=1e-4,o.p[2]*=1e-4,o.v[3]*=1e-4,o.p[3]*=1e-4),C[0]=o.p[0],C[1]=o.p[1],C[2]=o.p[2],C[3]=o.p[3],m=this.opt.movementFactor,C[0]*=m,C[1]*=m,C[2]*=m,C[3]*=m,o.dl&&(m=o.dl,C[0]+=m[0],C[1]+=m[1],C[2]+=m[2]),o.dw&&(m=o.dw,M.set(o.vBasis.x+C[0],o.vBasis.y+C[1],o.vBasis.z+C[2]),M.applyMatrix4(pe),M.x+=m[0],M.y+=m[1],M.z+=m[2],M.applyMatrix4(ge),C[0]+=M.x-o.vBasis.x,C[1]+=M.y-o.vBasis.y,C[2]+=M.z-o.vBasis.z),o.limits&&this.opt.isLimits&&(m=o.limits,m[0]&&(m[0][0]!==null&&C[0]<m[0][0]&&(C[0]=m[0][0]),m[0][1]!==null&&C[0]>m[0][1]&&(C[0]=m[0][1])),m[1]&&(m[1][0]!==null&&C[1]<m[1][0]&&(C[1]=m[1][0]),m[1][1]!==null&&C[1]>m[1][1]&&(C[1]=m[1][1])),m[2]&&(m[2][0]!==null&&C[2]<m[2][0]&&(C[2]=m[2][0]),m[2][1]!==null&&C[2]>m[2][1]&&(C[2]=m[2][1])),m[3]&&(m[3][0]!==null&&C[3]<m[3][0]&&(C[3]=m[3][0]),m[3][1]!==null&&C[3]>m[3][1]&&(C[3]=m[3][1]))),o.isPoint)o.bone.position.set(o.vBasis.x+C[0],o.vBasis.y+C[1],o.vBasis.z-C[2]);else if(o.boneParent.quaternion.copy(o.qBasis),o.pivot&&this.opt.isPivots&&(o.boneParent.updateWorldMatrix(!1,!1),o.boneParent.matrixWorld.decompose(M,ie,ne),M.copy(Ce).applyQuaternion(ie).setY(0).normalize(),ie.premultiply(Be.setFromUnitVectors(Ce,M).invert()).normalize(),o.boneParent.quaternion.multiply(ie.invert()),o.boneParent.quaternion.multiply(o.qWorldInverseYaw)),o.isZ&&(m=Math.atan(C[0]/o.l),ie.setFromAxisAngle(Je,-m),o.boneParent.quaternion.multiply(ie)),o.isY&&(m=o.l/3,m=m*Math.tanh(C[1]/m),o.bone.position.setLength(o.l+m)),o.isX&&(m=Math.atan(C[2]/o.l),ie.setFromAxisAngle(_e,-m),o.boneParent.quaternion.multiply(ie)),o.isT&&(m=1.5*Math.tanh(C[3]*1.5),ie.setFromAxisAngle(Ke,-m),o.boneParent.quaternion.multiply(ie)),o.boneParent.updateWorldMatrix(!1,!0),o.excludes&&this.opt.isExcludes)for(n=0,s=o.excludes.length;n<s;n++)m=o.excludes[n],ne.set(0,0,0),m.deltaLocal&&(ne.x+=m.deltaLocal[0],ne.y+=m.deltaLocal[1],ne.z+=m.deltaLocal[2]),ne.applyMatrix4(m.bone.matrixWorld),ge.copy(o.boneParent.matrixWorld).invert(),ne.applyMatrix4(ge),M.copy(o.bone.position),!(M.distanceToSquared(ne)>=m.radiusSq)&&(ue=M.length(),ae=ne.length(),!(ae>m.radius+ue)&&(ae<Math.abs(m.radius-ue)||(ae=(ae*ae+ue*ue-m.radiusSq)/(2*ae),ne.normalize(),we.copy(ne).multiplyScalar(ae),ae=Math.sqrt(ue*ue-ae*ae),M.subVectors(M,we).projectOnPlane(ne).normalize().multiplyScalar(ae),Se.subVectors(o.vBasis,we).projectOnPlane(ne).normalize(),ue=Se.dot(M),ue<0&&(ue=Math.sqrt(ae*ae-ue*ue),Se.multiplyScalar(ue),M.add(Se)),M.add(we).normalize(),ne.copy(o.bone.position).normalize(),ie.setFromUnitVectors(ne,M),o.boneParent.quaternion.premultiply(ie),o.boneParent.updateWorldMatrix(!1,!0))))}this.helpers.isActive&&this.updateHelpers()}showHelpers(t){if(this.hideHelpers(),this.helpers.isShowAll=t===void 0?this.helpers.isShowAll:t===!0,m=this.helpers,this.data.forEach(e=>{(this.helpers.isShowAll||e.helper===!0)&&(m.points.bones.push(e.bone),m.points.pivots.push(e.pivot),e.type!==0&&m.lines.bones.push(e.bone),e.excludes&&e.excludes.forEach(n=>{let i=!1;for(let s=0;s<m.excludes.bones.length;s++)if(m.excludes.bones[s]===n.bone&&m.excludes.radii[s]===n.radius&&!(m.excludes.deltaLocals[s]===null&&n.deltaLocal!==null)&&!(m.excludes.deltaLocals[s]!==null&&n.deltaLocal===null)&&!(m.excludes.deltaLocals[s]!==null&&m.excludes.deltaLocals[s].some((o,l)=>o!==n.deltaLocal[l]))){i=!0;break}i||(m.excludes.bones.push(n.bone),m.excludes.radii.push(n.radius),m.excludes.deltaLocals.push(n.deltaLocal?[...n.deltaLocal]:null),m.excludes.objects.push(null))}))}),m=this.helpers.excludes,this.opt.isExcludes&&m.bones.length&&m.bones.forEach((e,n)=>{const i=new f.SphereGeometry(m.radii[n],6,6),s=new f.MeshBasicMaterial({depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0,wireframe:!0,color:this.opt.helperExcludesColor});m.objects[n]=new f.Mesh(i,s),m.objects[n].renderOrder=997,e.add(m.objects[n]),m.deltaLocals[n]&&m.objects[n].position.set(m.deltaLocals[n][0],m.deltaLocals[n][1],m.deltaLocals[n][2])}),m=this.helpers.points,m.bones.length){this.helpers.isActive=!0;const e=new f.BufferGeometry,n=m.bones.map(h=>[0,0,0]).flat();e.setAttribute("position",new f.Float32BufferAttribute(n,3));const i=new f.Color(this.opt.helperBoneColor1),s=new f.Color(this.opt.helperBoneColor2),o=m.pivots.map(h=>h&&this.opt.isPivots?[s.r,s.g,s.b]:[i.r,i.g,i.b]).flat();e.setAttribute("color",new f.Float32BufferAttribute(o,3));const l=new f.PointsMaterial({depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0,size:.2,vertexColors:!0});m.object=new f.Points(e,l),m.object.renderOrder=998,m.object.matrix=this.armature.matrixWorld,m.object.matrixAutoUpdate=!1,this.scene.add(m.object)}if(m=this.helpers.lines,m.bones.length){const e=new f.BufferGeometry,n=m.bones.map(h=>[0,0,0,0,0,0]).flat();e.setAttribute("position",new f.Float32BufferAttribute(n,3));const i=new f.Color(this.opt.helperLinkColor1),s=new f.Color(this.opt.helperLinkColor2),o=m.bones.map(h=>[i.r,i.g,i.b,s.r,s.g,s.b]).flat();e.setAttribute("color",new f.Float32BufferAttribute(o,3));const l=new f.LineBasicMaterial({vertexColors:!0,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0});m.object=new f.LineSegments(e,l),m.object.renderOrder=999,m.object.matrix=this.armature.matrixWorld,m.object.matrixAutoUpdate=!1,this.scene.add(m.object)}}updateHelpers(){if(m=this.helpers.points,m.bones.length){ge.copy(this.armature.matrixWorld).invert();const t=m.object.geometry.getAttribute("position");for(let e=0,n=m.bones.length;e<n;e++)pe.multiplyMatrices(ge,m.bones[e].matrixWorld),M.setFromMatrixPosition(pe),t.setXYZ(e,M.x,M.y,M.z);t.needsUpdate=!0,m.object.updateMatrixWorld()}if(m=this.helpers.lines,m.bones.length){ge.copy(this.armature.matrixWorld).invert();const t=m.object.geometry.getAttribute("position");for(let e=0,n=0,i=m.bones.length;e<i;e++,n+=2)pe.multiplyMatrices(ge,m.bones[e].matrixWorld),M.setFromMatrixPosition(pe),t.setXYZ(n,M.x,M.y,M.z),pe.multiplyMatrices(ge,m.bones[e].parent.matrixWorld),M.setFromMatrixPosition(pe),t.setXYZ(n+1,M.x,M.y,M.z);t.needsUpdate=!0,m.object.updateMatrixWorld()}}hideHelpers(){[this.helpers.points,this.helpers.lines].forEach(t=>{t.bones=[],t.object&&(this.scene.remove(t.object),t.object.geometry.dispose(),t.object.material.dispose(),t.object=null)}),m=this.helpers.excludes,m.objects.forEach((t,e)=>{t&&(m.bones[e].remove(t),t.geometry.dispose(),t.material.dispose())}),m.bones=[],m.deltaLocals=[],m.radii=[],m.objects=[],this.helpers.isActive=!1}start(){this.data.length&&(this.running=!0,this.timerMs=0,this.showHelpers())}stop(){this.running=!1,this.hideHelpers();for(let t=0,e=this.data.length;t<e;t++){const n=this.data[t];n.bone.position.copy(n.vBasis),n.boneParent.quaternion.copy(n.qBasis)}}dispose(){this.stop(),this.scene=null,this.armature=null,this.config=[],this.data=[],this.dict={},this.objectsUpdate=[],this.timerMs=0}}class et{constructor(t){this.audioContext=t,this.analyzer=null,this.dataArray=null,this.bufferLength=0}async analyzeAudio(t,e){const n=t.sampleRate,i=t.duration,s=t.getChannelData(0),o=this.extractAudioFeatures(s,n);return this.generateTimingData(o,e,i)}extractAudioFeatures(t,e){const n={energy:[],spectralCentroid:[],zeroCrossingRate:[],mfcc:[],onsets:[],phonemeBoundaries:[]},i=1024,s=512,o=Math.floor((t.length-i)/s)+1;for(let l=0;l<o;l++){const h=l*s,r=Math.min(h+i,t.length),u=t.slice(h,r),a=this.calculateEnergy(u);n.energy.push(a);const d=this.calculateSpectralCentroid(u);n.spectralCentroid.push(d);const c=this.calculateZeroCrossingRate(u);n.zeroCrossingRate.push(c);const g=this.calculateMFCC(u);n.mfcc.push(g)}return n.onsets=this.detectOnsets(n.energy),n.phonemeBoundaries=this.detectPhonemeBoundaries(n),n}calculateEnergy(t){let e=0;for(let n=0;n<t.length;n++)e+=t[n]*t[n];return e/t.length}calculateSpectralCentroid(t){const e=this.fft(t);let n=0,i=0;for(let s=0;s<e.length/2;s++){const o=Math.sqrt(e[s*2]*e[s*2]+e[s*2+1]*e[s*2+1]);n+=s*o,i+=o}return i>0?n/i:0}calculateZeroCrossingRate(t){let e=0;for(let n=1;n<t.length;n++)t[n]>=0!=t[n-1]>=0&&e++;return e/(t.length-1)}calculateMFCC(t){const e=this.fft(t),n=[];for(let i=0;i<13;i++){let s=0;for(let o=0;o<e.length/2;o++){const l=Math.sqrt(e[o*2]*e[o*2]+e[o*2+1]*e[o*2+1]);s+=l*Math.cos(Math.PI*i*(o+.5)/(e.length/2))}n.push(s)}return n}fft(t){const e=t.length,n=new Float32Array(e*2);for(let i=0;i<e;i++)n[i*2]=t[i],n[i*2+1]=0;for(let i=1,s=0;i<e;i++){let o=e>>1;for(;s&o;)s^=o,o>>=1;if(s^=o,i<s){const l=n[i*2],h=n[i*2+1];n[i*2]=n[s*2],n[i*2+1]=n[s*2+1],n[s*2]=l,n[s*2+1]=h}}for(let i=2;i<=e;i<<=1){const s=-2*Math.PI/i,o=Math.cos(s),l=Math.sin(s);for(let h=0;h<e;h+=i){let r=1,u=0;for(let a=0;a<i/2;a++){const d=n[(h+a)*2],c=n[(h+a)*2+1],g=n[(h+a+i/2)*2]*r-n[(h+a+i/2)*2+1]*u,b=n[(h+a+i/2)*2]*u+n[(h+a+i/2)*2+1]*r;n[(h+a)*2]=d+g,n[(h+a)*2+1]=c+b,n[(h+a+i/2)*2]=d-g,n[(h+a+i/2)*2+1]=c-b;const x=r*o-u*l,S=r*l+u*o;r=x,u=S}}}return n}detectOnsets(t){const e=[];let s=-.1;for(let o=1;o<t.length;o++){const l=t[o]-t[o-1],h=o*.023;l>.1&&h-s>.1&&(e.push(h),s=h)}return e}detectPhonemeBoundaries(t){const e=[],{energy:n,spectralCentroid:i,zeroCrossingRate:s}=t;for(let o=1;o<n.length;o++){const l=o*.023,h=Math.abs(n[o]-n[o-1]),r=Math.abs(i[o]-i[o-1]),u=Math.abs(s[o]-s[o-1]);h+r*.1+u*.5>.2&&e.push(l)}return e}generateTimingData(t,e,n){const i=e.toLowerCase().split(/\s+/);t.phonemeBoundaries,t.onsets;const s=[];let o=0;for(let h=0;h<i.length;h++){const r=i[h],u=this.estimateWordDuration(r,n/i.length);s.push({word:r,startTime:o,endTime:o+u,duration:u}),o+=u}const l=this.generateVisemeTimings(t,e,n);return{words:s,visemes:l,duration:n,features:t}}estimateWordDuration(t,e){const n=Math.max(.5,Math.min(2,t.length/5)),i=this.getWordComplexity(t);return e*n*i}getWordComplexity(t){const e=(t.match(/[bcdfghjklmnpqrstvwxyz]{2,}/g)||[]).length,n=(t.match(/[aeiou]{2,}/g)||[]).length;return 1+e*.2+n*.1}generateVisemeTimings(t,e,n){const i=[],s=t.phonemeBoundaries;t.onsets;const o=this.textToVisemes(e);let l=0,h=0;for(let r=0;r<s.length&&l<o.length;r++){const u=s[r],a=o[l],d=t.energy[Math.floor(u/.023)]||0,c=this.calculateVisemeDuration(a,d);i.push({viseme:a,startTime:h,endTime:h+c,duration:c,intensity:Math.min(1,d*2)}),h+=c,l++}for(;l<o.length;){const r=o[l],u=this.calculateVisemeDuration(r,.5);i.push({viseme:r,startTime:h,endTime:h+u,duration:u,intensity:.6}),h+=u,l++}return i}textToVisemes(t){const e={a:"aa",e:"E",i:"I",o:"O",u:"U",ae:"aa",ai:"aa",au:"O",ea:"E",ee:"E",ei:"E",ie:"I",oa:"O",oo:"U",ou:"U",b:"PP",p:"PP",m:"PP",f:"FF",v:"FF",th:"SS",s:"SS",z:"SS",sh:"SS",ch:"SS",d:"DD",t:"DD",n:"nn",l:"nn",k:"kk",g:"kk",ng:"kk",r:"RR",w:"RR",y:"I",h:"kk"},n=[],i=t.toLowerCase().replace(/[^a-z\s]/g,"").split(/\s+/);for(const s of i){let o=0;for(;o<s.length;){let l=!1;for(let h=3;h>=2;h--){const r=s.substr(o,h);if(e[r]){n.push(e[r]),o+=h,l=!0;break}}if(!l){const h=s[o];e[h]&&n.push(e[h]),o++}}}return n}calculateVisemeDuration(t,e){const i={aa:.15,E:.12,I:.1,O:.14,U:.13,PP:.08,FF:.1,SS:.12,DD:.11,kk:.09,nn:.1,RR:.11}[t]||.1,s=.5+e*.5;return i*s}}class tt{constructor(){this.rules={A:["[A] =aa"," [ARE] =aa RR"," [AR]O=aa RR","[AR]#=E RR"," ^[AS]#=E SS","[A]WA=aa","[AW]=aa"," :[ANY]=E nn I","[A]^+#=E","#:[ALLY]=aa nn I"," [AL]#=aa nn","[AGAIN]=aa kk E nn","#:[AG]E=I kk","[A]^+:#=aa",":[A]^+ =E","[A]^%=E"," [ARR]=aa RR","[ARR]=aa RR"," :[AR] =aa RR","[AR] =E","[AR]=aa RR","[AIR]=E RR","[AI]=E","[AY]=E","[AU]=aa","#:[AL] =aa nn","#:[ALS] =aa nn SS","[ALK]=aa kk","[AL]^=aa nn"," :[ABLE]=E PP aa nn","[ABLE]=aa PP aa nn","[ANG]+=E nn kk","[A]=aa"],B:[" [BE]^#=PP I","[BEING]=PP I I nn"," [BOTH] =PP O TH"," [BUS]#=PP I SS","[BUIL]=PP I nn","[B]=PP"],C:[" [CH]^=kk","^E[CH]=kk","[CH]=CH"," S[CI]#=SS aa","[CI]A=SS","[CI]O=SS","[CI]EN=SS","[C]+=SS","[CK]=kk","[COM]%=kk aa PP","[C]=kk"],D:["#:[DED] =DD I DD",".E[D] =DD","#^:E[D] =DD"," [DE]^#=DD I"," [DO] =DD U"," [DOES]=DD aa SS"," [DOING]=DD U I nn"," [DOW]=DD aa","[DU]A=kk U","[D]=DD"],E:["#:[E] =","'^:[E] ="," :[E] =I","#[ED] =DD","#:[E]D =","[EV]ER=E FF","[E]^%=I","[ERI]#=I RR I","[ERI]=E RR I","#:[ER]#=E","[ER]#=E RR","[ER]=E"," [EVEN]=I FF E nn","#:[E]W=","@[EW]=U","[EW]=I U","[E]O=I","#:&[ES] =I SS","#:[E]S =","#:[ELY] =nn I","#:[EMENT]=PP E nn DD","[EFUL]=FF U nn","[EE]=I","[EARN]=E nn"," [EAR]^=E","[EAD]=E DD","#:[EA] =I aa","[EA]SU=E","[EA]=I","[EIGH]=E","[EI]=I"," [EYE]=aa","[EY]=I","[EU]=I U","[E]=E"],F:["[FUL]=FF U nn","[F]=FF"],G:["[GIV]=kk I FF"," [G]I^=kk","[GE]T=kk E","SU[GGES]=kk kk E SS","[GG]=kk"," B#[G]=kk","[G]+=kk","[GREAT]=kk RR E DD","#[GH]=","[G]=kk"],H:[" [HAV]=I aa FF"," [HERE]=I I RR"," [HOUR]=aa EE","[HOW]=I aa","[H]#=I","[H]="],I:[" [IN]=I nn"," [I] =aa","[IN]D=aa nn","[IER]=I E","#:R[IED] =I DD","[IED] =aa DD","[IEN]=I E nn","[IE]T=aa E"," :[I]%=aa","[I]%=I","[IE]=I","[I]^+:#=I","[IR]#=aa RR","[IZ]%=aa SS","[IS]%=aa SS","[I]D%=aa","+^[I]^+=I","[I]T%=aa","#^:[I]^+=I","[I]^+=aa","[IR]=E","[IGH]=aa","[ILD]=aa nn DD","[IGN] =aa nn","[IGN]^=aa nn","[IGN]%=aa nn","[IQUE]=I kk","[I]=I"],J:["[J]=kk"],K:[" [K]N=","[K]=kk"],L:["[LO]C#=nn O","L[L]=","#^:[L]%=aa nn","[LEAD]=nn I DD","[L]=nn"],M:["[MOV]=PP U FF","[M]=PP"],N:["E[NG]+=nn kk","[NG]R=nn kk","[NG]#=nn kk","[NGL]%=nn kk aa nn","[NG]=nn","[NK]=nn kk"," [NOW] =nn aa","[N]=nn"],O:["[OF] =aa FF","[OROUGH]=E O","#:[OR] =E","#:[ORS] =E SS","[OR]=aa RR"," [ONE]=FF aa nn","[OW]=O"," [OVER]=O FF E","[OV]=aa FF","[O]^%=O","[O]^EN=O","[O]^I#=O","[OL]D=O nn","[OUGHT]=aa DD","[OUGH]=aa FF"," [OU]=aa","H[OU]S#=aa","[OUS]=aa SS","[OUR]=aa RR","[OULD]=U DD","^[OU]^L=aa","[OUP]=U OO","[OU]=aa","[OY]=O","[OING]=O I nn","[OI]=O","[OOR]=aa RR","[OOK]=U kk","[OOD]=U DD","[OO]=U","[O]E=O","[O] =O","[OA]=O"," [ONLY]=O nn nn I"," [ONCE]=FF aa nn SS","[ON'T]=O nn DD","C[O]N=aa","[O]NG=aa"," ^:[O]N=aa","I[ON]=aa nn","#:[ON] =aa nn","#^[ON]=aa nn","[O]ST =O","[OF]^=aa FF","[OTHER]=aa TH E","[OSS] =aa SS","#^:[OM]=aa PP","[O]=aa"],P:["[PH]=FF","[PEOP]=PP I PP","[POW]=PP aa","[PUT] =PP U DD","[P]=PP"],Q:["[QUAR]=kk FF aa RR","[QU]=kk FF","[Q]=kk"],R:[" [RE]^#=RR I","[R]=RR"],S:["[SH]=SS","#[SION]=SS aa nn","[SOME]=SS aa PP","#[SUR]#=SS E","[SUR]#=SS E","#[SU]#=SS U","#[SSU]#=SS U","#[SED] =SS DD","#[S]#=SS","[SAID]=SS E DD","^[SION]=SS aa nn","[S]S=",".[S] =SS","#:.E[S] =SS","#^:##[S] =SS","#^:#[S] =SS","U[S] =SS"," :#[S] =SS"," [SCH]=SS kk","[S]C+=","#[SM]=SS PP","#[SN]'=SS aa nn","[S]=SS"],T:[" [THE] =TH aa","[TO] =DD U","[THAT] =TH aa DD"," [THIS] =TH I SS"," [THEY]=TH E"," [THERE]=TH E RR","[THER]=TH E","[THEIR]=TH E RR"," [THAN] =TH aa nn"," [THEM] =TH E PP","[THESE] =TH I SS"," [THEN]=TH E nn","[THROUGH]=TH RR U","[THOSE]=TH O SS","[THOUGH] =TH O"," [THUS]=TH aa SS","[TH]=TH","#:[TED] =DD I DD","S[TI]#N=CH","[TI]O=SS","[TI]A=SS","[TIEN]=SS aa nn","[TUR]#=CH E","[TU]A=CH U"," [TWO]=DD U","[T]=DD"],U:[" [UN]I=I U nn"," [UN]=aa nn"," [UPON]=aa PP aa nn","@[UR]#=U RR","[UR]#=I U RR","[UR]=E","[U]^ =aa","[U]^^=aa","[UY]=aa"," G[U]#=","G[U]%=","G[U]#=FF","#N[U]=I U","@[U]=I","[U]=I U"],V:["[VIEW]=FF I U","[V]=FF"],W:[" [WERE]=FF E","[WA]S=FF aa","[WA]T=FF aa","[WHERE]=FF E RR","[WHAT]=FF aa DD","[WHOL]=I O nn","[WHO]=I U","[WH]=FF","[WAR]=FF aa RR","[WOR]^=FF E","[WR]=RR","[W]=FF"],X:[" [X]=SS","[X]=kk SS"],Y:["[YOUNG]=I aa nn"," [YOU]=I U"," [YES]=I E SS"," [Y]=I","#^:[Y] =I","#^:[Y]I=I"," :[Y] =aa"," :[Y]#=aa"," :[Y]^+:#=I"," :[Y]^#=I","[Y]=I"],Z:["[Z]=SS"]};const t={"#":"[AEIOUY]+",".":"[BDVGJLMNRWZ]","%":"(?:ER|E|ES|ED|ING|ELY)","&":"(?:[SCGZXJ]|CH|SH)","@":"(?:[TSRDLZNJ]|TH|CH|SH)","^":"[BCDFGHJKLMNPQRSTVWXZ]","+":"[EIY]",":":"[BCDFGHJKLMNPQRSTVWXZ]*"," ":"\\b"};Object.keys(this.rules).forEach(e=>{this.rules[e]=this.rules[e].map(n=>{const i=n.indexOf("["),s=n.indexOf("]"),o=n.indexOf("="),l=n.substring(0,i),h=n.substring(i+1,s),r=n.substring(s+1,o),u=n.substring(o+1),a={regex:"",move:0,visemes:[]};let d="";d+=[...l].map(g=>t[g]||g).join("");const c=[...h];return c[0]=c[0].toLowerCase(),d+=c.join(""),a.move=c.length,d+=[...r].map(g=>t[g]||g).join(""),a.regex=new RegExp(d),u.length&&u.split(" ").forEach(g=>{a.visemes.push(g)}),a})}),this.visemeDurations={aa:.95,E:.9,I:.92,O:.96,U:.95,PP:1.08,SS:1.23,TH:1,DD:1.05,FF:1,kk:1.21,nn:.88,RR:.88,DD:1.05,sil:1},this.specialDurations={" ":1,",":3,"-":.5,"'":.5},this.digits=["oh","one","two","three","four","five","six","seven","eight","nine"],this.ones=["","one","two","three","four","five","six","seven","eight","nine"],this.tens=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"],this.teens=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],this.decades={20:"twenties",30:"thirties",40:"forties",50:"fifties",60:"sixties",70:"seventies",80:"eighties",90:"nineties"},this.ordinals={1:"first",2:"second",3:"third",4:"fourth",5:"fifth",6:"sixth",7:"seventh",8:"eighth",9:"ninth",10:"tenth",11:"eleventh",12:"twelfth",13:"thirteenth",14:"fourteenth",15:"fifteenth",16:"sixteenth",17:"seventeeth",18:"eighteenth",19:"nineteenth",20:"twentieth",30:"thirtieth",40:"fortieth",50:"fiftieth",60:"sixtieth",70:"seventieth",80:"eightieth",90:"ninetieth"},this.symbols={"%":"percent","€":"euros","&":"and","+":"plus",$:"dollars"},this.symbolsReg=/[%€&\+\$]/g}convert_digit_by_digit(t){t=String(t).split("");let e="";for(let n=0;n<t.length;n++)e+=this.digits[t[n]]+" ";return e=e.substring(0,e.length-1),e}convert_sets_of_two(t){let e=String(t).substring(0,2),n=String(t).substring(2,4),i=this.convert_tens(e);return i+=" "+this.convert_tens(n),i}convert_millions(t){return t>=1e6?this.convert_millions(Math.floor(t/1e6))+" million "+this.convert_thousands(t%1e6):this.convert_thousands(t)}convert_thousands(t){return t>=1e3?this.convert_hundreds(Math.floor(t/1e3))+" thousand "+this.convert_hundreds(t%1e3):this.convert_hundreds(t)}convert_hundreds(t){return t>99?this.ones[Math.floor(t/100)]+" hundred "+this.convert_tens(t%100):this.convert_tens(t)}convert_tens(t){return t<10?(Number(t)!=0&&t.toString().startsWith("0")?"oh ":"")+this.ones[Number(t)]:t>=10&&t<20?this.teens[t-10]:(this.tens[Math.floor(t/10)]+" "+this.ones[t%10]).trim()}convertNumberToWords(t,e=!1){const n=parseFloat(t);if(t=="0")return"zero";if(t<0)return" minus "+this.convertNumberToWords(Math.abs(t).toString(),e).trim();if(n&&!Number.isInteger(n)){const i=n.toString().split(".");return this.convertNumberToWords(i[0],e).trim()+" point "+this.convert_digit_by_digit(i[1]).trim()}else return t.toString().startsWith("0")?this.convert_digit_by_digit(t).trim():!e&&(t<1e3&&t>99&&t%100!==0||t>1e4&&t<1e6)?this.convert_digit_by_digit(t).trim():!e&&(t>1e3&&t<2e3||t>2009&&t<3e3)?t%100!=0?this.convert_sets_of_two(t).trim():this.convert_tens(t.toString().substring(0,2)).trim()+" hundred":this.convert_millions(t).trim()}convertDecade(t){const e=parseInt(t),n=!isNaN(e)&&t.length===2,i=!isNaN(e)&&t.length>2&&e>0&&e<=3e3,s=i&&e%1e3===0?Math.floor(e/1e3):null,o=i&&!s?Math.floor(e/100):null,l=n||i?Math.floor(e%100/10)*10:null;let h=[];return s?h.push(this.convertNumberToWords(s).trim(),"thousands"):(o&&h.push(this.convertNumberToWords(o).trim()),l?h.push(this.decades[l]||this.convertNumberToWords(l).trim()+"s"):o?h.push("hundreds"):h.push(t)),h.join(" ")}convertOrdinal(t){if(this.ordinals.hasOwnProperty(t))return this.ordinals[t];const e=Math.floor(t/100),n=Math.floor(t%100/10)*10,i=t%10;let s=[];return e&&(s.push(this.convertNumberToWords(e).trim()),n||i?s.push("hundred"):s.push("hundredth")),n&&(i?s.push(this.convertNumberToWords(n).trim()):s.push(this.ordinals[n])),i&&s.push(this.ordinals[i]),s.join(" ")}preProcessText(t){let e=t.replace('/[#_*":;]/g',"");return e=e.replace(this.symbolsReg,n=>" "+this.symbols[n]+" "),/\d/.test(e)&&(e=e.replace(/\b(\d{2,4})[''']?\s?[sS](?=\s|[.,!?;:]|$)/g,(n,i)=>{const s=this.convertDecade(i);return s===i?n:s}),e=e.replace(/\b(\d+)\s*(st|nd|rd|th)(?=\s|[.,!?;:]|$)/gi,(n,i)=>this.convertOrdinal(Number(i))),e=e.replace(/\b(\w*?)(\d+)([A-Za-z]+)\b/g,(n,i,s,o)=>{const l=this.convertNumberToWords(s);return`${i}${l} ${o}`}).replace(/\b([A-Za-z]+)(\d+)(\w*?)\b/g,(n,i,s,o)=>{const l=this.convertNumberToWords(s);return`${i} ${l}${o}`}),e=e.replace(/-?(?:\d{1,3}(?:,\d{3})+|\d+)(\.\d+)?/g,(n,i)=>{let s=n,o=!1;return/,/.test(s)&&(s=s.replace(/,/g,""),o=!0),i&&(o=!0),this.convertNumberToWords(s,o)})),e=e.replace(/(\D)\1\1+/g,"$1$1").replaceAll(" "," ").normalize("NFD").replace(/[\u0300-\u036f]/g,"").normalize("NFC").trim(),e}wordsToVisemes(t){let e={words:t.toUpperCase(),visemes:[],times:[],durations:[],i:0},n=0;const i=[...e.words];for(;e.i<i.length;){const s=i[e.i],o=this.rules[s];if(o)for(let l=0;l<o.length;l++){const h=o[l];if((e.words.substring(0,e.i)+s.toLowerCase()+e.words.substring(e.i+1)).match(h.regex)){h.visemes.forEach(a=>{if(e.visemes.length&&e.visemes[e.visemes.length-1]===a){const d=.7*(this.visemeDurations[a]||1);e.durations[e.durations.length-1]+=d,n+=d}else{const d=this.visemeDurations[a]||1;e.visemes.push(a),e.times.push(n),e.durations.push(d),n+=d}}),e.i+=h.move;break}}else e.i++,n+=this.specialDurations[s]||0}return e}}const nt=Object.freeze(Object.defineProperty({__proto__:null,LipsyncEn:tt},Symbol.toStringTag,{value:"Module"}));class it{constructor(){this.rules={A:["[AH]=aa","[AU]=aa U","[AI]=aa I","[AE]=E","[A]H=aa","[A]U=aa U","[A]I=aa I"," [AN] =aa nn"," [AM] =aa PP","[ARR]=aa RR","[AR]=aa RR"," [ALS]=aa nn SS","[AL]=aa nn","[AUCH]=aa U kk","[ABER]=aa PP E RR","[A]=aa"],Ä:["[Ä]H=E","[ÄU]=O","[Ä]=E"],B:["[B]=PP"],C:["[CH]S=kk SS","[CH]=kk"," [CH]=kk","#[CH]=kk","[CK]=kk","[C]H=kk","[C]=kk"],D:[" [DAS] =DD aa SS"," [DEN] =DD E nn"," [DER] =DD E RR"," [DIE] =DD I"," [DU] =DD U"," [DURCH]=DD U RR kk","[D]=DD"],E:["[EI]=aa I","[EU]=O","[EH]=E"," [ER] =E RR"," [ES] =E SS"," [EIN] =aa I nn"," [EINE]=aa I nn aa","[ER]#=E","[ER]=E RR","[EN]#=aa nn","[E]=E"],F:["[F]=FF"],G:["[G]=kk"],H:[" [HAT] =I aa DD"," [HABEN]=I aa PP aa nn"," [HIER]=I I RR"," [HEUTE]=I O DD aa","[H]="],I:[" [ICH] =I kk"," [IHR] =I RR"," [IN] =I nn"," [IST] =I SS DD"," [IM] =I PP","[IE]=I","[IH]=I","[I]=I"],J:["[J]=I"],K:["[K]=kk"],L:["[L]=nn"],M:[" [MIT] =PP I DD"," [MAN] =PP aa nn"," [MEHR]=PP E RR"," [MICH]=PP I kk","[M]=PP"],N:[" [NICHT]=nn I kk DD"," [NUR] =nn U RR"," [NACH]=nn aa kk"," [NOCH]=nn aa kk","[NG]=nn kk","[N]=nn"],O:["[OO]=U","[OH]=O","[OU]=aa U"," [ODER]=O DD E RR"," [OHNE]=O nn aa","[Ö]=E","[O]=aa"],Ö:["[ÖH]=E","[Ö]=E"],P:["[PF]=FF FF","[PH]=FF","[P]=PP"],Q:["[QU]=kk FF","[Q]=kk"],R:["[R]=RR"],S:["[SCH]=SS","[SP]=SS PP","[ST]=SS DD","[SS]=SS","[S]=SS"],ß:["[ß]=SS"],T:["[TZ]=DD SS","[TH]=DD","[T]=DD"],U:[" [UND] =U nn DD"," [UM] =U PP"," [UNTER]=U nn DD E RR"," [UNS] =U nn SS","[UH]=U","[ÜH]=I U","[Ü]=I U","[U]=U"],Ü:["[ÜH]=I U","[Ü]=I U"],V:[" [VON] =FF aa nn"," [VOR] =FF aa RR"," [VIEL]=FF I nn","[V]=FF"],W:[" [WAS] =FF aa SS"," [WIR] =FF I RR"," [WIE] =FF I"," [WENN]=FF E nn"," [WILL]=FF I nn"," [WO] =FF aa"," [WIEDER]=FF I DD E RR","[W]=FF"],X:["[X]=kk SS"],Y:["[Y]=I"],Z:[" [ZU] =DD SS U"," [ZUM] =DD SS U PP"," [ZUR] =DD SS U RR"," [ZEIT]=DD SS aa I DD","[Z]=DD SS"]};const t={"#":"[AEIOUÄÖÜ]+",".":"[BDVGJLMNRWZ]","%":"(?:ER|E|ES|ED|ING|ELY|EN|TE|ST)","&":"(?:[SCGZXJ]|CH|SCH|TZ)","@":"(?:[TSRDLZNJ]|TH|CH|SCH)","^":"[BCDFGHJKLMNPQRSTVWXYZß]","+":"[EIY]",":":"[BCDFGHJKLMNPQRSTVWXYZß]*"," ":"\\b"};Object.keys(this.rules).forEach(e=>{this.rules[e]=this.rules[e].map(n=>{const i=n.indexOf("["),s=n.indexOf("]"),o=n.indexOf("="),l=n.substring(0,i),h=n.substring(i+1,s),r=n.substring(s+1,o),u=n.substring(o+1),a={regex:"",move:0,visemes:[]};let d="";d+=[...l].map(g=>t[g]||g).join("");const c=[...h];return c[0]=c[0].toLowerCase(),d+=c.join(""),a.move=c.length,d+=[...r].map(g=>t[g]||g).join(""),a.regex=new RegExp(d),u.length&&u.split(" ").forEach(g=>{a.visemes.push(g)}),a})}),this.visemeDurations={aa:1,E:.85,I:.9,O:1.05,U:1,PP:1.15,SS:1.2,TH:1,DD:1.1,FF:1.05,kk:1.25,nn:.85,RR:.9,sil:1},this.specialDurations={" ":1,",":3,"-":.5,"'":.5,".":4,"!":3,"?":3},this.digits=["null","eins","zwei","drei","vier","fünf","sechs","sieben","acht","neun"],this.ones=["","ein","zwei","drei","vier","fünf","sechs","sieben","acht","neun"],this.tens=["","","zwanzig","dreißig","vierzig","fünfzig","sechzig","siebzig","achtzig","neunzig"],this.teens=["zehn","elf","zwölf","dreizehn","vierzehn","fünfzehn","sechzehn","siebzehn","achtzehn","neunzehn"],this.symbols={"%":"prozent","€":"euro","&":"und","+":"plus",$:"dollar","=":"gleich","@":"at","#":"hashtag"},this.symbolsReg=/[%€&\+\$=@#]/g}convert_digit_by_digit(t){t=String(t).split("");let e="";for(let n=0;n<t.length;n++)e+=this.digits[t[n]]+" ";return e=e.substring(0,e.length-1),e}convert_millions(t){if(t>=1e6){const e=Math.floor(t/1e6),n=t%1e6;let i=this.convert_thousands(e);return i+=e===1?" million ":" millionen ",n>0&&(i+=this.convert_thousands(n)),i}else return this.convert_thousands(t)}convert_thousands(t){if(t>=1e3){const e=Math.floor(t/1e3),n=t%1e3;let i="";return e===1?i="eintausend":i=this.convert_hundreds(e)+"tausend",n>0&&(i+=this.convert_hundreds(n)),i}else return this.convert_hundreds(t)}convert_hundreds(t){if(t>99){const e=Math.floor(t/100),n=t%100;let i="";return e===1?i="einhundert":i=this.ones[e]+"hundert",n>0&&(i+=this.convert_tens(n)),i}else return this.convert_tens(t)}convert_tens(t){if(t<10)return this.ones[Number(t)]||"";if(t>=10&&t<20)return this.teens[t-10];{const e=Math.floor(t/10),n=t%10;return n===0?this.tens[e]:this.ones[n]+"und"+this.tens[e]}}convertNumberToWords(t){const e=String(t);return t=="0"?"null":e.startsWith("0")?this.convert_digit_by_digit(t):e.length===4&&(t<1e3||t>2100)?this.convert_digit_by_digit(t):this.convert_millions(Number(t))}preProcessText(t){return t.replace(/[#_*\":;]/g,"").replace(this.symbolsReg,e=>" "+this.symbols[e]+" ").replace(/(\d)\.(\d)/g,"$1 komma $2").replace(/(\d),(\d)/g,"$1 komma $2").replace(/\d+/g,this.convertNumberToWords.bind(this)).replace(/(\D)\1\1+/g,"$1$1").replace(/\s+/g," ").toLowerCase().trim()}wordsToVisemes(t){let e={words:t.toUpperCase(),visemes:[],times:[],durations:[],i:0},n=0;const i=[...e.words];for(;e.i<i.length;){const s=i[e.i],o=this.rules[s];if(o){let l=!1;for(let h=0;h<o.length;h++){const r=o[h];if((e.words.substring(0,e.i)+s.toLowerCase()+e.words.substring(e.i+1)).match(r.regex)){r.visemes.forEach(d=>{if(e.visemes.length&&e.visemes[e.visemes.length-1]===d){const c=.7*(this.visemeDurations[d]||1);e.durations[e.durations.length-1]+=c,n+=c}else{const c=this.visemeDurations[d]||1;e.visemes.push(d),e.times.push(n),e.durations.push(c),n+=c}}),e.i+=r.move,l=!0;break}}l||(e.i++,n+=this.specialDurations[s]||0)}else e.i++,n+=this.specialDurations[s]||0}return e}}const ot=Object.freeze(Object.defineProperty({__proto__:null,LipsyncDe:it},Symbol.toStringTag,{value:"Module"}));class st{constructor(){this.rules={A:["[AN]C=aa nn","[AN]G=aa nn","[AN]T=aa nn","[AN]D=aa nn","[AN] =aa nn","[AN]$=aa nn","[AM]P=aa nn","[AM]B=aa nn","[AM] =aa nn","[AM]$=aa nn","[AI]N=E nn","[AIM]=E nn","[AIN]=E nn","[AU]=O","[AUX]=O","[AUT]=O","[AI]=E","[AY]=E","[A]=aa"],À:["[À]=aa"],Â:["[Â]=aa"],B:[" [B] =PP","[BB]=PP","[B]=PP"],C:["[C]E=SS","[C]I=SS","[C]Y=SS","[C]È=SS","[C]É=SS","[C]Ê=SS","[CH]=SS","[C]A=kk","[C]O=kk","[C]U=kk","[C]L=kk","[C]R=kk","[CK]=kk","[C]=kk"],Ç:["[Ç]=SS"],D:["[D]=DD"],E:["[EN]C=aa nn","[EN]T=aa nn","[EN]D=aa nn","[EN] =aa nn","[EN]$=aa nn","[EM]P=aa nn","[EM]B=aa nn","[EM] =aa nn","[EM]$=aa nn","[EAU]=O","[EAU]X=O","[EU]=U","[EUX]=U","[EUR]=U RR","[EI]=E","[EIN]=E nn","[ER] =E","[ER]$=E","[EZ] =E","[EZ]$=E","[ED] =E","[ED]$=E"," [E] =","[E] =","[E]$=","[E]S =","[E]S$=","[E]NT =","[E]NT$=","[È]=E","[É]=E","[Ê]=E","[Ë]=E","[E]=E"],È:["[È]=E"],É:["[É]=E"],Ê:["[Ê]=E"],Ë:["[Ë]=E"],F:["[FF]=FF","[F]=FF","[PH]=FF"],G:["[G]E=SS","[G]I=SS","[G]Y=SS","[G]È=SS","[G]É=SS","[G]Ê=SS","[GN]=nn I","[GN]E=nn","[GN]A=nn aa","[GN]O=nn O","[GU]E=kk","[GU]I=kk","[GU]A=kk FF aa","[GU]O=kk FF O","[G]A=kk","[G]O=kk","[G]U=kk","[G]L=kk","[G]R=kk","[GG]=kk","[G]=kk"],H:["[H]="],I:["[IN]C=E nn","[IN]T=E nn","[IN]D=E nn","[IN] =E nn","[IN]$=E nn","[IM]P=E nn","[IM]B=E nn","[IM] =E nn","[IM]$=E nn","[IEN]=I E nn","[IER]=I E","[IEU]=I U","[IEZ]=I E","[ILL]E=I","[ILLE]=I","[ILL]=I","[Î]=I","[Ï]=I","[I]=I"],Î:["[Î]=I"],Ï:["[Ï]=I"],J:["[J]=SS"],K:["[K]=kk"],L:["[LL]E=","[LLE]=","[LL]A=I aa","[LL]O=I O","[LL]U=I U","[LL]I=I","[LL]=I","[L]=nn"],M:["[MM]=PP","[M]=PP"],N:["[NN]=nn","[N]=nn"],O:["[ON]C=O nn","[ON]T=O nn","[ON]D=O nn","[ON] =O nn","[ON]$=O nn","[OM]P=O nn","[OM]B=O nn","[OM] =O nn","[OM]$=O nn","[OI]N=FF E nn","[OI]G=FF aa","[OI]S=FF aa","[OI]T=FF aa","[OI]X=FF aa","[OI]=FF aa","[OU]=U","[OÙ]=U","[OÛ]=U","[OEU]=U","[OEUR]=U RR","[OUGH]=U FF","[OUGH]T=U","[Ô]=O","[O]=O"],Ô:["[Ô]=O"],Ù:["[Ù]=U"],Û:["[Û]=U"],P:["[PH]=FF","[PP]=PP","[P]=PP"],Q:["[QU]=kk","[Q]=kk"],R:["[RR]=RR","[R]=RR"],S:["#[S]#=SS"," [S]=SS","[SS]=SS","[S] =","[S]$=","[SC]E=SS","[SC]I=SS","[SC]Y=SS","[S]=SS"],T:["[TI]A=SS I aa","[TI]E=SS I E","[TI]O=SS I O","[TI]ON=SS I O nn","[TH]=DD","[TT]=DD","[T] =","[T]$=","[T]=DD"],U:["[UN]C=U nn","[UN]T=U nn","[UN]D=U nn","[UN] =U nn","[UN]$=U nn","[UM]=U nn","[UE]=I","[UEI]=I E","[UEIL]=I I","[UILL]=I","[Ù]=U","[Û]=U","[Ü]=I U","[U]=I U"],Ü:["[Ü]=I U"],V:["[V]=FF"],W:["[W]=FF"],X:["[X] =","[X]$=","#[X]#=kk SS"," [X]=kk SS","[X]=kk SS"],Y:["[Y]=I"," [Y]=I","[YE]=I E","[YA]=I aa","[YO]=I O","[YU]=I U"],Z:["[Z]=SS"]};const t={"#":"[AEIOUYÀÂÈÉÊËÎÏÔÙÛÜ]+",".":"[BDVGJLMNRWZ]","%":"(?:ER|E|ES|ÉS|ÈS|ÊS|ENT|MENT|TION|SION)","&":"(?:[SCGZXJ]|CH|SH|GN)","@":"(?:[TSRDLZNJ]|TH|CH|SH|GN)","^":"[BCDFGHJKLMNPQRSTVWXZÇ]+","+":"[EIYÈÉÊËÎÏ]",":":"[BCDFGHJKLMNPQRSTVWXZÇ]*"," ":"\\b",$:"$"};Object.keys(this.rules).forEach(e=>{this.rules[e]=this.rules[e].map(n=>{const i=n.indexOf("["),s=n.indexOf("]"),o=n.indexOf("="),l=n.substring(0,i),h=n.substring(i+1,s),r=n.substring(s+1,o),u=n.substring(o+1),a={regex:"",move:0,visemes:[]};let d="";d+=[...l].map(g=>t[g]||g).join("");const c=[...h];return c[0]=c[0].toLowerCase(),d+=c.join(""),a.move=c.length,d+=[...r].map(g=>t[g]||g).join(""),a.regex=new RegExp(d,"i"),u.length&&u.split(" ").forEach(g=>{g&&a.visemes.push(g)}),a})}),this.visemeDurations={aa:1,E:.95,I:.9,O:1.05,U:.95,PP:1.1,SS:1.25,TH:1,DD:1.05,FF:1,kk:1.2,nn:.88,RR:1.15,sil:1},this.specialDurations={" ":1,",":2.5,".":3.5,";":2.8,":":2.2,"!":3.2,"?":3.2,"-":.8,"'":.3,'"':.3,"(":1.5,")":1.5},this.digits=["zéro","un","deux","trois","quatre","cinq","six","sept","huit","neuf"],this.ones=["","un","deux","trois","quatre","cinq","six","sept","huit","neuf"],this.teens=["dix","onze","douze","treize","quatorze","quinze","seize","dix-sept","dix-huit","dix-neuf"],this.tens=["","dix","vingt","trente","quarante","cinquante","soixante","soixante-dix","quatre-vingts","quatre-vingt-dix"],this.symbols={"%":"pourcent","€":"euros","&":"et","+":"plus",$:"dollars","=":"égale","@":"arobase","#":"dièse","°":"degrés"},this.symbolsReg=/[%€&\+\$=@#°]/g}convert_digit_by_digit(t){t=String(t).split("");let e="";for(let n=0;n<t.length;n++)e+=this.digits[t[n]]+" ";return e=e.substring(0,e.length-1),e}convert_tens(t){if(t<10)return this.ones[t]||"";if(t>=10&&t<20)return this.teens[t-10];if(t>=70&&t<80){const e=t-60;return e===11?"soixante et onze":"soixante-"+this.teens[e-10]}else if(t>=90){const e=t-80;return e===11?"quatre-vingt-onze":"quatre-vingt-"+this.teens[e-10]}else{const e=Math.floor(t/10),n=t%10;return e===8&&n===0?"quatre-vingts":e===8?"quatre-vingt-"+this.ones[n]:(e===2||e===3||e===4||e===5||e===6)&&n===1?this.tens[e]+" et un":n===0?this.tens[e]:this.tens[e]+"-"+this.ones[n]}}convert_hundreds(t){if(t>=100){const e=Math.floor(t/100),n=t%100;let i="";return e===1?i="cent":(i=this.ones[e]+" cent",n===0&&(i+="s")),n>0&&(i+=" "+this.convert_tens(n)),i}else return this.convert_tens(t)}convert_thousands(t){if(t>=1e3){const e=Math.floor(t/1e3),n=t%1e3;let i="";return e===1?i="mille":i=this.convert_hundreds(e)+" mille",n>0&&(i+=" "+this.convert_hundreds(n)),i}else return this.convert_hundreds(t)}convert_millions(t){if(t>=1e6){const e=Math.floor(t/1e6),n=t%1e6;let i="";return e===1?i="un million":i=this.convert_hundreds(e)+" millions",n>0&&(i+=" "+this.convert_thousands(n)),i}else return this.convert_thousands(t)}convertNumberToWords(t){const e=String(t);return t==="0"||t===0?"zéro":e.startsWith("0")?this.convert_digit_by_digit(t):this.convert_millions(Number(t))}preProcessText(t){return t.replace(/[#_*\":;]/g,"").replace(this.symbolsReg,e=>" "+this.symbols[e]+" ").replace(/(\d)[,.](\d)/g,"$1 virgule $2").replace(/\d+/g,this.convertNumberToWords.bind(this)).replace(/(\D)\1\1+/g,"$1$1").replace(/\s+/g," ").replace(/'/g,"'").trim()}wordsToVisemes(t){let e={words:t.toUpperCase(),visemes:[],times:[],durations:[],i:0},n=0;const i=[...e.words];for(;e.i<i.length;){const s=i[e.i],o=this.rules[s];if(o){let l=!1;for(let h=0;h<o.length;h++){const r=o[h];if((e.words.substring(0,e.i)+s.toLowerCase()+e.words.substring(e.i+1)).match(r.regex)){r.visemes.forEach(d=>{if(e.visemes.length&&e.visemes[e.visemes.length-1]===d){const c=.7*(this.visemeDurations[d]||1);e.durations[e.durations.length-1]+=c,n+=c}else{const c=this.visemeDurations[d]||1;e.visemes.push(d),e.times.push(n),e.durations.push(c),n+=c}}),e.i+=r.move,l=!0;break}}l||(e.i++,n+=this.specialDurations[s]||0)}else e.i++,n+=this.specialDurations[s]||0}return e}}const at=Object.freeze(Object.defineProperty({__proto__:null,LipsyncFr:st},Symbol.toStringTag,{value:"Module"}));class rt{constructor(){this.visemes={a:"aa",e:"E",i:"I",o:"O",u:"U",y:"U",ä:"aa",ö:"O",å:"O",b:"PP",c:"SS",d:"DD",f:"FF",g:"kk",h:"kk",j:"I",k:"kk",l:"nn",m:"PP",n:"nn",p:"PP",q:"kk",r:"RR",s:"SS",t:"DD",v:"FF",w:"FF",x:"SS",z:"SS"},this.visemeDurations={aa:.95,E:.9,I:.92,O:.96,U:.95,PP:1.08,SS:1.23,DD:1.05,FF:1,kk:1.21,nn:.88,RR:.88,DD:1.05,sil:1},this.specialDurations={" ":1,",":3,"-":.5},this.numbers=["nolla","yksi","kaksi","kolme","neljä","viisi","kuusi","seitsemän","kahdeksan","yhdeksän","kymmenen","yksitoista","kaksitoista","kolmetoista","neljätoista","viisitoista","kuusitoista","seitsemäntoista","kahdeksantoista","yhdeksäntoista"],this.symbols={"%":"prosenttia","€":"euroa","&":"ja","+":"plus",$:"dollaria"},this.symbolsReg=/[%€&\+\$]/g}numberToFinnishWords(t){const e=[];let n=parseFloat(t);if(n===void 0)return t;let i=(s,o,l,h,r)=>{if(s<o)return s;const u=Math.floor(s/o);return e.push(l+(u===1?h:this.numberToFinnishWords(u.toString())+r)),s-u*o};if(n<0&&(e.push("miinus "),n=Math.abs(n)),n=i(n,1e9," ","miljardi"," miljardia"),n=i(n,1e6," ","miljoona"," miljoonaa"),n=i(n,1e3,"","tuhat","tuhatta"),n=i(n,100," ","sata","sataa"),n>20&&(n=i(n,10,"","","kymmentä")),n>=1){let s=Math.floor(n);e.push(this.numbers[s]),n-=s}if(n>=0&&Math.abs(parseFloat(t))<1&&e.push("nolla"),n>0){let s=t.split(".");if(s.length>1){e.push(" pilkku");let o=[...s[s.length-1]];for(let l=0;l<o.length;l++)e.push(" "+this.numbers[o[l]])}}return e.join("").trim()}preProcessText(t){return t.replace(/[#_*\'\":;]/g,"").replace(this.symbolsReg,e=>" "+this.symbols[e]+" ").replace(/(\d)\,(\d)/g,"$1 pilkku $2").replace(/\d+/g,this.numberToFinnishWords.bind(this)).replaceAll(" "," ").normalize("NFD").replace(/[\u0300-\u0307\u0309\u030b-\u036f]/g,"").normalize("NFC").trim()}wordsToVisemes(t){let e={words:t,visemes:[],times:[],durations:[]},n=0;const i=[...t];for(let s=0;s<i.length;s++){const o=this.visemes[i[s].toLowerCase()];if(o)if(e.visemes.length&&e.visemes[e.visemes.length-1]===o){const l=.7*(this.visemeDurations[o]||1);e.durations[e.durations.length-1]+=l,n+=l}else{const l=this.visemeDurations[o]||1;e.visemes.push(o),e.times.push(n),e.durations.push(l),n+=l}else n+=this.specialDurations[i[s]]||0}return e}}const lt=Object.freeze(Object.defineProperty({__proto__:null,LipsyncFi:rt},Symbol.toStringTag,{value:"Module"}));class ut{constructor(){this.visemes={a:"aa",ą:"O",e:"E",ę:"E",ė:"E",i:"I",į:"I",o:"O",u:"U",ū:"U",ų:"U",y:"I",b:"PP",c:"SS",č:"SS",d:"DD",f:"FF",g:"kk",h:"kk",j:"I",k:"kk",l:"nn",m:"PP",n:"nn",p:"PP",q:"kk",r:"RR",s:"SS",š:"CH",t:"DD",v:"FF",w:"FF",x:"SS",z:"SS",ž:"SS"},this.durations={a:.95,ą:1.5,e:.9,ę:1.5,ė:1.5,i:.92,į:1.5,o:.96,u:.95,ū:1.5,ų:1.5,y:1.5,b:1.08,c:1.23,d:1.05,f:1,g:1.21,h:1.21,j:.92,k:1.21,l:.88,m:1.08,n:.88,p:1.08,q:1.21,r:.88,s:1.23,š:1.23,t:1.05,v:1,w:1,x:1.23,z:1.23,ž:1.23},this.pauses={" ":1,",":3,"-":.5},this.numbers=["nulis","vienas","du","trys","keturi","penki","šeši","septyni","aštuoni","devyni","dešimt","vienuolika","dvylika","trylika","keturiolika","penkiolika","šešiolika","septyniolika","aštuoniolika","devyniolika"],this.tens=[this.numbers[0],this.numbers[10],"dvidešimt","trisdešimt","keturiasdešimt","penkiasdešimt","šešiasdešimt","septyniasdešimt","aštuoniasdešimt","devyniasdešimt"]}numberToLithuanianWords(t){const e=[];let n=parseFloat(t);if(n===void 0)return t;let i=(s,o,l,h,r)=>{if(s<o)return s;const u=Math.floor(s/o);return u===1?e.push(this.numbers[1]):e.push(this.numberToLithuanianWords(u.toString())),u%10===1?e.push(l):u%10===0||u%100>10&&u%100<20?e.push(r):e.push(h),s-u*o};n<0&&(e.push("minus"),n=Math.abs(n)),n=i(n,1e9,"milijardas","milijardai","milijardų"),n=i(n,1e6,"milijonas","milijonai","milijonų"),n=i(n,1e3,"tūkstantis","tūkstančiai","tūkstančių"),n=i(n,100,"šimtas","šimtai","šimtų");for(let s=this.tens.length-1;s>=1;s--)if(n>=10*s){e.push(this.tens[s]),n=n-10*s;break}if(n>=1){let s=Math.floor(n);e.push(this.numbers[s]),n-=s}if(n>=0&&Math.abs(parseFloat(t))<1&&e.push(this.numbers[0]),n>0){let s=t.split(".");if(s.length>1){e.push("kablelis");let o=[...s[s.length-1]];for(let l=0;l<o.length;l++)e.push(this.numbers[o[l]])}}return e.join(" ").trim()}preProcessText(t){return t.replace(`/[#_*'":;]/g`,"").replaceAll("0 %","0 procentų ").replaceAll("1 %","1 procentas ").replaceAll("%"," procentai ").replaceAll("0 €","0 eurų ").replaceAll("1 €","1 euras ").replaceAll("€"," eurai ").replaceAll("0 $","0 dolerių ").replaceAll("1 $","1 doleris ").replaceAll("$"," doleriai ").replaceAll("&"," ir ").replaceAll("+"," pliusas ").replace(/(\d)\,(\d)/g,"$1 kablelis $2").replace(/\d+/g,this.numberToLithuanianWords.bind(this)).replace(/(\D)\1\1+/g,"$1$1").replaceAll(" "," ").normalize("NFD").replace(/[\u0300-\u0303\u0305\u0306\u0308-\u0327\u0329-\u036f]/g,"").normalize("NFC").trim()}wordsToVisemes(t){let e={words:t,visemes:[],times:[],durations:[]},n=0;const i=[...t];for(let s=0;s<i.length;s++){const o=i[s].toLowerCase(),l=this.visemes[o];if(l)if(e.visemes.length&&e.visemes[e.visemes.length-1]===l){const h=.7*(this.durations[o]||1);e.durations[e.durations.length-1]+=h,n+=h}else{const h=this.durations[o]||1;e.visemes.push(l),e.times.push(n),e.durations.push(h),n+=h}else n+=this.pauses[i[s]]||0}return e}}const ht=Object.freeze(Object.defineProperty({__proto__:null,LipsyncLt:ut},Symbol.toStringTag,{value:"Module"})),ct=new URL("data:text/javascript;base64,Y2xhc3MgUGxheWJhY2tXb3JrbGV0IGV4dGVuZHMgQXVkaW9Xb3JrbGV0UHJvY2Vzc29yIHsKICBzdGF0aWMgRlNNID0gewogICAgSURMRTogMCwKICAgIFBMQVlJTkc6IDEsCiAgfTsKCiAgY29uc3RydWN0b3Iob3B0aW9ucykgewogICAgc3VwZXIoKTsKICAgIHRoaXMucG9ydC5vbm1lc3NhZ2UgPSB0aGlzLmhhbmRsZU1lc3NhZ2UuYmluZCh0aGlzKTsKCiAgICB0aGlzLl9zYW1wbGVSYXRlID0gb3B0aW9ucz8ucHJvY2Vzc29yT3B0aW9ucz8uc2FtcGxlUmF0ZSB8fCBzYW1wbGVSYXRlOwogICAgdGhpcy5fc2NhbGUgPSAxIC8gMzI3Njg7IC8vIFBDTTE2IC0+IGZsb2F0CgogICAgLy8gU2lsZW5jZSBkZXRlY3Rpb24gdGhyZXNob2xkICgxIHNlY29uZCkgYXMgYSBmYWxsYmFjayBzYWZldHkgbmV0CiAgICBjb25zdCBzaWxlbmNlRHVyYXRpb25TZWNvbmRzID0gMS4wOwogICAgdGhpcy5fc2lsZW5jZVRocmVzaG9sZEJsb2NrcyA9IE1hdGguY2VpbCgodGhpcy5fc2FtcGxlUmF0ZSAqIHNpbGVuY2VEdXJhdGlvblNlY29uZHMpIC8gMTI4KTsKCiAgICAvLyBNZXRyaWNzIGNvbmZpZ3VyYXRpb24gdmlhIG9wdGlvbnMKICAgIGNvbnN0IG1ldHJpY3NDZmcgPSBvcHRpb25zPy5wcm9jZXNzb3JPcHRpb25zPy5tZXRyaWNzIHx8IHt9OwogICAgdGhpcy5fbWV0cmljc0VuYWJsZWQgPSBtZXRyaWNzQ2ZnLmVuYWJsZWQgIT09IGZhbHNlOwogICAgY29uc3QgaW50ZXJ2YWxIeiA9ICh0eXBlb2YgbWV0cmljc0NmZy5pbnRlcnZhbEh6ID09PSAibnVtYmVyIiAmJiBtZXRyaWNzQ2ZnLmludGVydmFsSHogPiAwKQogICAgICA/IG1ldHJpY3NDZmcuaW50ZXJ2YWxIeiA6IDI7CiAgICAvLyBNZXRyaWNzIHN0YXRlIChsb3ctb3ZlcmhlYWQpCiAgICB0aGlzLl9mcmFtZXNQcm9jZXNzZWQgPSAwOwogICAgdGhpcy5fdW5kZXJydW5CbG9ja3MgPSAwOwogICAgdGhpcy5fbWF4UXVldWVTYW1wbGVzID0gMDsKICAgIHRoaXMuX2xhc3RNZXRyaWNzU2VudEF0RnJhbWUgPSAwOwogICAgLy8gQ29udmVydCB0byBmcmFtZXMgYmV0d2VlbiByZXBvcnRzCiAgICB0aGlzLl9tZXRyaWNzSW50ZXJ2YWxGcmFtZXMgPSBNYXRoLm1heCgxMjgsIE1hdGgucm91bmQodGhpcy5fc2FtcGxlUmF0ZSAvIGludGVydmFsSHopKTsKCiAgICB0aGlzLnJlc2V0KCk7CiAgfQoKICAvKioKICAgKiBSZXNldHMgdGhlIHdvcmtsZXQgdG8gaXRzIGluaXRpYWwgSURMRSBzdGF0ZS4KICAgKi8KICByZXNldCgpIHsKICAgIHRoaXMuX2J1ZmZlclF1ZXVlID0gW107CiAgICB0aGlzLl9jdXJyZW50Q2h1bmsgPSBudWxsOwogICAgdGhpcy5fY3VycmVudENodW5rT2Zmc2V0ID0gMDsKICAgIHRoaXMuX3N0YXRlID0gUGxheWJhY2tXb3JrbGV0LkZTTS5JRExFOwoKICAgIHRoaXMuX25vTW9yZURhdGFSZWNlaXZlZCA9IGZhbHNlOwogICAgdGhpcy5fc2lsZW5jZUZyYW1lc0NvdW50ID0gMDsKICAgIHRoaXMuX2hhc1NlbnRFbmRlZCA9IGZhbHNlOwogICAgLy8gUmVzZXQgbWF4IHF1ZXVlIHRyYWNrZXIgb25seSB3aGVuIGdvaW5nIGlkbGUKICAgIHRoaXMuX21heFF1ZXVlU2FtcGxlcyA9IDA7CiAgfQoKICBoYW5kbGVNZXNzYWdlKGV2ZW50KSB7CiAgICBjb25zdCB7IHR5cGUsIGRhdGEgfSA9IGV2ZW50LmRhdGE7CgogICAgLy8gSU5URVJSVVBUOiBUaGUgbWFpbiB0aHJlYWQgd2FudHMgdG8gc3RvcCBpbW1lZGlhdGVseS4KICAgIGlmICh0eXBlID09PSAic3RvcCIpIHsKICAgICAgdGhpcy5yZXNldCgpOwogICAgICAvLyBTZW5kIGZpbmFsIG1ldHJpY3Mgc2hvd2luZyBjbGVhcmVkIHN0YXRlCiAgICAgIGlmICh0aGlzLl9tZXRyaWNzRW5hYmxlZCkgewogICAgICAgIHRyeSB7CiAgICAgICAgICB0aGlzLnBvcnQucG9zdE1lc3NhZ2UoewogICAgICAgICAgICB0eXBlOiAibWV0cmljcyIsCiAgICAgICAgICAgIGRhdGE6IHsKICAgICAgICAgICAgICBzdGF0ZTogUGxheWJhY2tXb3JrbGV0LkZTTS5JRExFLAogICAgICAgICAgICAgIHF1ZXVlZFNhbXBsZXM6IDAsCiAgICAgICAgICAgICAgcXVldWVkTXM6IDAsCiAgICAgICAgICAgICAgbWF4UXVldWVkTXM6IE1hdGgucm91bmQoKHRoaXMuX21heFF1ZXVlU2FtcGxlcyAvIHRoaXMuX3NhbXBsZVJhdGUpICogMTAwMCksCiAgICAgICAgICAgICAgdW5kZXJydW5CbG9ja3M6IHRoaXMuX3VuZGVycnVuQmxvY2tzLAogICAgICAgICAgICAgIGZyYW1lc1Byb2Nlc3NlZDogdGhpcy5fZnJhbWVzUHJvY2Vzc2VkCiAgICAgICAgICAgIH0KICAgICAgICAgIH0pOwogICAgICAgIH0gY2F0Y2ggKF8pIHsgfQogICAgICB9CiAgICAgIHJldHVybjsKICAgIH0KCiAgICAvLyBNYWluIHRocmVhZCBoYXMgc2lnbmFsZWQgdGhhdCBubyBtb3JlIGF1ZGlvIGNodW5rcyB3aWxsIGJlIHNlbnQgZm9yIHRoaXMgdXR0ZXJhbmNlLgogICAgaWYgKHR5cGUgPT09ICJuby1tb3JlLWRhdGEiKSB7CiAgICAgIHRoaXMuX25vTW9yZURhdGFSZWNlaXZlZCA9IHRydWU7CiAgICAgIHJldHVybjsKICAgIH0KCiAgICAvLyBVcGRhdGUgbWV0cmljcyBjb25maWd1cmF0aW9uIGF0IHJ1bnRpbWUKICAgIGlmICh0eXBlID09PSAiY29uZmlnLW1ldHJpY3MiICYmIGRhdGEgJiYgdHlwZW9mIGRhdGEgPT09ICJvYmplY3QiKSB7CiAgICAgIGlmICgiZW5hYmxlZCIgaW4gZGF0YSkgdGhpcy5fbWV0cmljc0VuYWJsZWQgPSAhIWRhdGEuZW5hYmxlZDsKICAgICAgaWYgKHR5cGVvZiBkYXRhLmludGVydmFsSHogPT09ICJudW1iZXIiICYmIGRhdGEuaW50ZXJ2YWxIeiA+IDApIHsKICAgICAgICBjb25zdCBpbnRlcnZhbEh6ID0gZGF0YS5pbnRlcnZhbEh6OwogICAgICAgIHRoaXMuX21ldHJpY3NJbnRlcnZhbEZyYW1lcyA9IE1hdGgubWF4KDEyOCwgTWF0aC5yb3VuZCh0aGlzLl9zYW1wbGVSYXRlIC8gaW50ZXJ2YWxIeikpOwogICAgICB9CiAgICAgIC8vIFJlc2V0IHBhY2luZyBzbyB0aGUgbmV4dCByZXBvcnQgYWxpZ25zIHdpdGggbmV3IGludGVydmFsCiAgICAgIHRoaXMuX2xhc3RNZXRyaWNzU2VudEF0RnJhbWUgPSB0aGlzLl9mcmFtZXNQcm9jZXNzZWQ7CiAgICAgIHJldHVybjsKICAgIH0KCiAgICAvLyBOZXcgYXVkaW8gZGF0YSBoYXMgYXJyaXZlZC4KICAgIGlmICh0eXBlID09PSAiYXVkaW9EYXRhIiAmJiBkYXRhIGluc3RhbmNlb2YgQXJyYXlCdWZmZXIpIHsKICAgICAgdGhpcy5fbm9Nb3JlRGF0YVJlY2VpdmVkID0gZmFsc2U7CiAgICAgIC8vIElmIHdlIHdlcmUgaWRsZSwgdGhpcyBuZXcgZGF0YSBraWNrcyBvZmYgdGhlIHBsYXliYWNrLgogICAgICBpZiAodGhpcy5fc3RhdGUgPT09IFBsYXliYWNrV29ya2xldC5GU00uSURMRSkgewogICAgICAgIHRoaXMuX3N0YXRlID0gUGxheWJhY2tXb3JrbGV0LkZTTS5QTEFZSU5HOwogICAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZSh7IHR5cGU6ICJwbGF5YmFjay1zdGFydGVkIiB9KTsKICAgICAgfQoKICAgICAgLy8gV2Ugb25seSBxdWV1ZSBkYXRhIGlmIHdlIGFyZSBpbiB0aGUgUExBWUlORyBzdGF0ZS4gVGhpcyBwcmV2ZW50cwogICAgICAvLyBkYXRhIGZyb20gYSBwcmV2aW91cywgaW50ZXJydXB0ZWQgc3RyZWFtIGZyb20gbGluZ2VyaW5nLgogICAgICBpZiAodGhpcy5fc3RhdGUgPT09IFBsYXliYWNrV29ya2xldC5GU00uUExBWUlORykgewogICAgICAgIC8vIFN0b3JlIGFzIEludDE2QXJyYXkgdmlldyB0byBhdm9pZCBjb25zdHJ1Y3RpbmcgaXQgaW4gcHJvY2VzcygpCiAgICAgICAgdGhpcy5fYnVmZmVyUXVldWUucHVzaChuZXcgSW50MTZBcnJheShkYXRhKSk7CiAgICAgICAgdGhpcy5fc2lsZW5jZUZyYW1lc0NvdW50ID0gMDsgLy8gUmVzZXQgc2lsZW5jZSBjb3VudGVyIG9uIG5ldyBkYXRhCiAgICAgIH0KICAgIH0KICB9CgogIHByb2Nlc3MoaW5wdXRzLCBvdXRwdXRzLCBwYXJhbWV0ZXJzKSB7CiAgICBjb25zdCBvdXRwdXRDaGFubmVsID0gb3V0cHV0c1swXT8uWzBdOwogICAgaWYgKCFvdXRwdXRDaGFubmVsKSB7CiAgICAgIHJldHVybiB0cnVlOyAvLyBLZWVwIGFsaXZlIGV2ZW4gaWYgb3V0cHV0IGlzIHRlbXBvcmFyaWx5IGRpc2Nvbm5lY3RlZAogICAgfQoKICAgIC8vIElmIHdlIGFyZSBub3QgcGxheWluZywganVzdCBvdXRwdXQgc2lsZW5jZSBhbmQgd2FpdC4KICAgIGlmICh0aGlzLl9zdGF0ZSAhPT0gUGxheWJhY2tXb3JrbGV0LkZTTS5QTEFZSU5HKSB7CiAgICAgIG91dHB1dENoYW5uZWwuZmlsbCgwKTsKICAgICAgcmV0dXJuIHRydWU7IC8vIEFsd2F5cyByZXR1cm4gdHJ1ZSB0byBrZWVwIHRoZSBwcm9jZXNzb3IgYWxpdmUKICAgIH0KCiAgICAvLyBDb3JlIFBMQVlJTkcgTG9naWMKICAgIGNvbnN0IGJsb2NrU2l6ZSA9IG91dHB1dENoYW5uZWwubGVuZ3RoOwogICAgbGV0IHNhbXBsZXNDb3BpZWQgPSAwOwoKICAgIHdoaWxlIChzYW1wbGVzQ29waWVkIDwgYmxvY2tTaXplKSB7CiAgICAgIGlmICghdGhpcy5fY3VycmVudENodW5rIHx8IHRoaXMuX2N1cnJlbnRDaHVua09mZnNldCA+PSB0aGlzLl9jdXJyZW50Q2h1bmsubGVuZ3RoKSB7CiAgICAgICAgaWYgKHRoaXMuX2J1ZmZlclF1ZXVlLmxlbmd0aCA+IDApIHsKICAgICAgICAgIHRoaXMuX2N1cnJlbnRDaHVuayA9IHRoaXMuX2J1ZmZlclF1ZXVlLnNoaWZ0KCk7CiAgICAgICAgICB0aGlzLl9jdXJyZW50Q2h1bmtPZmZzZXQgPSAwOwogICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAvLyBCdWZmZXIgaXMgZW1wdHkuIENoZWNrIGZvciBlbmQgY29uZGl0aW9ucy4KICAgICAgICAgIGNvbnN0IGlzVGltZWRPdXQgPSB0aGlzLl9zaWxlbmNlRnJhbWVzQ291bnQgPiB0aGlzLl9zaWxlbmNlVGhyZXNob2xkQmxvY2tzOwoKICAgICAgICAgIGlmICh0aGlzLl9ub01vcmVEYXRhUmVjZWl2ZWQgfHwgaXNUaW1lZE91dCkgewogICAgICAgICAgICAvLyBFTkQgT0YgUExBWUJBQ0s6IEVpdGhlciBleHBsaWNpdGx5IHNpZ25hbGVkIG9yIHRpbWVkIG91dC4KICAgICAgICAgICAgaWYgKCF0aGlzLl9oYXNTZW50RW5kZWQpIHsKICAgICAgICAgICAgICB0aGlzLnBvcnQucG9zdE1lc3NhZ2UoeyB0eXBlOiAicGxheWJhY2stZW5kZWQiIH0pOwogICAgICAgICAgICAgIHRoaXMuX2hhc1NlbnRFbmRlZCA9IHRydWU7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgLy8gU2VuZCBmaW5hbCBtZXRyaWNzIHNob3dpbmcgY2xlYXJlZCBzdGF0ZQogICAgICAgICAgICBpZiAodGhpcy5fbWV0cmljc0VuYWJsZWQpIHsKICAgICAgICAgICAgICB0cnkgewogICAgICAgICAgICAgICAgdGhpcy5wb3J0LnBvc3RNZXNzYWdlKHsKICAgICAgICAgICAgICAgICAgdHlwZTogIm1ldHJpY3MiLAogICAgICAgICAgICAgICAgICBkYXRhOiB7CiAgICAgICAgICAgICAgICAgICAgc3RhdGU6IFBsYXliYWNrV29ya2xldC5GU00uSURMRSwKICAgICAgICAgICAgICAgICAgICBxdWV1ZWRTYW1wbGVzOiAwLAogICAgICAgICAgICAgICAgICAgIHF1ZXVlZE1zOiAwLAogICAgICAgICAgICAgICAgICAgIG1heFF1ZXVlZE1zOiBNYXRoLnJvdW5kKCh0aGlzLl9tYXhRdWV1ZVNhbXBsZXMgLyB0aGlzLl9zYW1wbGVSYXRlKSAqIDEwMDApLAogICAgICAgICAgICAgICAgICAgIHVuZGVycnVuQmxvY2tzOiB0aGlzLl91bmRlcnJ1bkJsb2NrcywKICAgICAgICAgICAgICAgICAgICBmcmFtZXNQcm9jZXNzZWQ6IHRoaXMuX2ZyYW1lc1Byb2Nlc3NlZAogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICB9KTsKICAgICAgICAgICAgICB9IGNhdGNoIChfKSB7IH0KICAgICAgICAgICAgfQogICAgICAgICAgICB0aGlzLnJlc2V0KCk7IC8vIFJlc2V0IHRvIElETEUgc3RhdGUgZm9yIHJldXNlCiAgICAgICAgICAgIGJyZWFrOyAvLyBFeGl0IHdoaWxlIGxvb3AKICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgIC8vIEJVRkZFUiBVTkRFUlJVTiAoTEFHKTogUGxheSBzaWxlbmNlIGFuZCB3YWl0IGZvciBtb3JlIGRhdGEuCiAgICAgICAgICAgIHRoaXMuX3NpbGVuY2VGcmFtZXNDb3VudCsrOwogICAgICAgICAgICBpZiAodGhpcy5fbWV0cmljc0VuYWJsZWQpIHRoaXMuX3VuZGVycnVuQmxvY2tzKys7CiAgICAgICAgICAgIGJyZWFrOyAvLyBFeGl0IHdoaWxlIGxvb3AKICAgICAgICAgIH0KICAgICAgICB9CiAgICAgIH0KCiAgICAgIC8vIElmIHdlIGhhdmUgYSBjaHVuayAoY291bGQgYmUgYSBuZXcgb25lIGZyb20gdGhlIGxvZ2ljIGFib3ZlKSwgcHJvY2VzcyBpdC4KICAgICAgaWYgKHRoaXMuX2N1cnJlbnRDaHVuaykgewogICAgICAgIGNvbnN0IHNhbXBsZXNUb0NvcHkgPSBNYXRoLm1pbigKICAgICAgICAgIGJsb2NrU2l6ZSAtIHNhbXBsZXNDb3BpZWQsCiAgICAgICAgICB0aGlzLl9jdXJyZW50Q2h1bmsubGVuZ3RoIC0gdGhpcy5fY3VycmVudENodW5rT2Zmc2V0CiAgICAgICAgKTsKICAgICAgICAvLyBEaXJlY3RseSB3cml0ZSB0byBvdXRwdXRDaGFubmVsIHRvIGF2b2lkIGV4dHJhIGNvcHkKICAgICAgICBjb25zdCBzcmMgPSB0aGlzLl9jdXJyZW50Q2h1bms7CiAgICAgICAgY29uc3QgYmFzZVNyYyA9IHRoaXMuX2N1cnJlbnRDaHVua09mZnNldDsKICAgICAgICBjb25zdCBiYXNlRHN0ID0gc2FtcGxlc0NvcGllZDsKICAgICAgICBjb25zdCBzY2FsZSA9IHRoaXMuX3NjYWxlOwogICAgICAgIGZvciAobGV0IGkgPSAwOyBpIDwgc2FtcGxlc1RvQ29weTsgaSsrKSB7CiAgICAgICAgICBvdXRwdXRDaGFubmVsW2Jhc2VEc3QgKyBpXSA9IHNyY1tiYXNlU3JjICsgaV0gKiBzY2FsZTsKICAgICAgICB9CgogICAgICAgIHRoaXMuX2N1cnJlbnRDaHVua09mZnNldCArPSBzYW1wbGVzVG9Db3B5OwogICAgICAgIHNhbXBsZXNDb3BpZWQgKz0gc2FtcGxlc1RvQ29weTsKICAgICAgfQogICAgfQoKICAgIC8vIFplcm8tZmlsbCB0aGUgcmVtYWluZGVyLCBpZiBhbnksIG9uY2UgcGVyIGJsb2NrCiAgICBpZiAoc2FtcGxlc0NvcGllZCA8IGJsb2NrU2l6ZSkgewogICAgICBvdXRwdXRDaGFubmVsLmZpbGwoMCwgc2FtcGxlc0NvcGllZCk7CiAgICB9CgogICAgLy8gVXBkYXRlIG1ldHJpY3MgKG9wdGlvbmFsKQogICAgaWYgKHRoaXMuX21ldHJpY3NFbmFibGVkKSB7CiAgICAgIHRoaXMuX2ZyYW1lc1Byb2Nlc3NlZCArPSBibG9ja1NpemU7CgogICAgICAvLyBUcmFjayBxdWV1ZSBkZXB0aCBpbiBzYW1wbGVzIChhcHByb3hpbWF0ZSkKICAgICAgbGV0IHF1ZXVlZFNhbXBsZXMgPSAwOwogICAgICBpZiAodGhpcy5fY3VycmVudENodW5rKSBxdWV1ZWRTYW1wbGVzICs9IE1hdGgubWF4KDAsIHRoaXMuX2N1cnJlbnRDaHVuay5sZW5ndGggLSB0aGlzLl9jdXJyZW50Q2h1bmtPZmZzZXQpOwogICAgICBmb3IgKGxldCBpID0gMDsgaSA8IHRoaXMuX2J1ZmZlclF1ZXVlLmxlbmd0aDsgaSsrKSBxdWV1ZWRTYW1wbGVzICs9IHRoaXMuX2J1ZmZlclF1ZXVlW2ldLmxlbmd0aDsKICAgICAgaWYgKHF1ZXVlZFNhbXBsZXMgPiB0aGlzLl9tYXhRdWV1ZVNhbXBsZXMpIHRoaXMuX21heFF1ZXVlU2FtcGxlcyA9IHF1ZXVlZFNhbXBsZXM7CgogICAgICAvLyBQZXJpb2RpY2FsbHkgc2VuZCBtZXRyaWNzIHRvIG1haW4gdGhyZWFkCiAgICAgIGlmICh0aGlzLl9mcmFtZXNQcm9jZXNzZWQgLSB0aGlzLl9sYXN0TWV0cmljc1NlbnRBdEZyYW1lID49IHRoaXMuX21ldHJpY3NJbnRlcnZhbEZyYW1lcykgewogICAgICAgIHRoaXMuX2xhc3RNZXRyaWNzU2VudEF0RnJhbWUgPSB0aGlzLl9mcmFtZXNQcm9jZXNzZWQ7CiAgICAgICAgdHJ5IHsKICAgICAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZSh7CiAgICAgICAgICAgIHR5cGU6ICJtZXRyaWNzIiwKICAgICAgICAgICAgZGF0YTogewogICAgICAgICAgICAgIHN0YXRlOiB0aGlzLl9zdGF0ZSwKICAgICAgICAgICAgICBxdWV1ZWRTYW1wbGVzLAogICAgICAgICAgICAgIHF1ZXVlZE1zOiBNYXRoLnJvdW5kKChxdWV1ZWRTYW1wbGVzIC8gdGhpcy5fc2FtcGxlUmF0ZSkgKiAxMDAwKSwKICAgICAgICAgICAgICBtYXhRdWV1ZWRNczogTWF0aC5yb3VuZCgodGhpcy5fbWF4UXVldWVTYW1wbGVzIC8gdGhpcy5fc2FtcGxlUmF0ZSkgKiAxMDAwKSwKICAgICAgICAgICAgICB1bmRlcnJ1bkJsb2NrczogdGhpcy5fdW5kZXJydW5CbG9ja3MsCiAgICAgICAgICAgICAgZnJhbWVzUHJvY2Vzc2VkOiB0aGlzLl9mcmFtZXNQcm9jZXNzZWQKICAgICAgICAgICAgfQogICAgICAgICAgfSk7CiAgICAgICAgfSBjYXRjaCAoXykgeyB9CiAgICAgICAgLy8gRG9uJ3QgcmVzZXQgbWF4IHRyYWNrZXIgLSBrZWVwIHNlc3Npb24gcGVhayB1bnRpbCBpZGxlCiAgICAgIH0KICAgIH0KCiAgICAvLyBBTFdBWVMgcmV0dXJuIHRydWUgdG8ga2VlcCB0aGUgcHJvY2Vzc29yIGFsaXZlIGZvciByZXVzZS4KICAgIHJldHVybiB0cnVlOwogIH0KfQoKcmVnaXN0ZXJQcm9jZXNzb3IoInBsYXliYWNrLXdvcmtsZXQiLCBQbGF5YmFja1dvcmtsZXQpOwo=",typeof document>"u"?require("url").pathToFileURL(__filename).href:He&&He.tagName.toUpperCase()==="SCRIPT"&&He.src||new URL("index.cjs",document.baseURI).href),Ne={en:nt,de:ot,fr:at,fi:lt,lt:ht},q=new f.Quaternion,Z=new f.Euler,fe=new f.Vector3,xe=new f.Vector3,Oe=new f.Box3;new f.Matrix4;new f.Matrix4;new f.Vector3;new f.Vector3(0,0,1);const dt=new f.Vector3(1,0,0);new f.Vector3(0,1,0);new f.Vector3(0,0,1);class Te{constructor(t,e=null){this.nodeAvatar=t,this.opt={jwtGet:null,ttsEndpoint:"",ttsApikey:null,ttsTrimStart:0,ttsTrimEnd:400,ttsLang:"fi-FI",ttsVoice:"fi-FI-Standard-A",ttsRate:1,ttsPitch:0,ttsVolume:.3,mixerGainSpeech:1.2,mixerGainBackground:null,lipsyncLang:"fi",lipsyncModules:["fi","en","lt"],pcmSampleRate:22050,modelRoot:"Armature",modelPixelRatio:1,modelFPS:30,modelMovementFactor:1,cameraView:"full",dracoEnabled:!1,dracoDecoderPath:"https://www.gstatic.com/draco/v1/decoders/",cameraDistance:0,cameraX:0,cameraY:0,cameraRotateX:0,cameraRotateY:0,cameraRotateEnable:!0,cameraPanEnable:!1,cameraZoomEnable:!1,lightAmbientColor:16777215,lightAmbientIntensity:1.25,lightDirectColor:8947882,lightDirectIntensity:12,lightDirectPhi:1,lightDirectTheta:2,lightSpotIntensity:0,lightSpotColor:3377407,lightSpotPhi:.1,lightSpotTheta:4,lightSpotDispersion:1,avatarMood:"neutral",avatarMute:!1,avatarIdleEyeContact:.6,avatarIdleHeadMove:.5,avatarSpeakingEyeContact:.8,avatarSpeakingHeadMove:.5,avatarIgnoreCamera:!1,listeningSilenceThresholdLevel:40,listeningSilenceThresholdMs:2e3,listeningSilenceDurationMax:1e4,listeningActiveThresholdLevel:75,listeningActiveThresholdMs:300,listeningActiveDurationMax:24e4,update:null,avatarOnly:!1,avatarOnlyScene:null,avatarOnlyCamera:null,statsNode:null,statsStyle:null},Object.assign(this.opt,e||{}),this.opt.statsNode&&(this.stats=new Qe,this.opt.statsStyle&&(this.stats.dom.style.cssText=this.opt.statsStyle),this.opt.statsNode.appendChild(this.stats.dom)),this.poseTemplates={side:{standing:!0,props:{"Hips.position":{x:0,y:1,z:0},"Hips.rotation":{x:-.003,y:-.017,z:.1},"Spine.rotation":{x:-.103,y:-.002,z:-.063},"Spine1.rotation":{x:.042,y:-.02,z:-.069},"Spine2.rotation":{x:.131,y:-.012,z:-.065},"Neck.rotation":{x:.027,y:.006,z:0},"Head.rotation":{x:.077,y:-.065,z:0},"LeftShoulder.rotation":{x:1.599,y:.084,z:-1.77},"LeftArm.rotation":{x:1.364,y:.052,z:-.044},"LeftForeArm.rotation":{x:.002,y:-.007,z:.331},"LeftHand.rotation":{x:.104,y:-.067,z:-.174},"LeftHandThumb1.rotation":{x:.231,y:.258,z:.355},"LeftHandThumb2.rotation":{x:-.106,y:-.339,z:-.454},"LeftHandThumb3.rotation":{x:-.02,y:-.142,z:-.004},"LeftHandIndex1.rotation":{x:.148,y:.032,z:-.069},"LeftHandIndex2.rotation":{x:.326,y:-.049,z:-.029},"LeftHandIndex3.rotation":{x:.247,y:-.053,z:-.073},"LeftHandMiddle1.rotation":{x:.238,y:-.057,z:-.089},"LeftHandMiddle2.rotation":{x:.469,y:-.036,z:-.081},"LeftHandMiddle3.rotation":{x:.206,y:-.015,z:-.017},"LeftHandRing1.rotation":{x:.187,y:-.118,z:-.157},"LeftHandRing2.rotation":{x:.579,y:.02,z:-.097},"LeftHandRing3.rotation":{x:.272,y:.021,z:-.063},"LeftHandPinky1.rotation":{x:.405,y:-.182,z:-.138},"LeftHandPinky2.rotation":{x:.613,y:.128,z:-.144},"LeftHandPinky3.rotation":{x:.268,y:.094,z:-.081},"RightShoulder.rotation":{x:1.541,y:.192,z:1.775},"RightArm.rotation":{x:1.273,y:-.352,z:-.067},"RightForeArm.rotation":{x:-.011,y:-.031,z:-.357},"RightHand.rotation":{x:-.008,y:.312,z:-.028},"RightHandThumb1.rotation":{x:.23,y:-.258,z:-.355},"RightHandThumb2.rotation":{x:-.107,y:.339,z:.454},"RightHandThumb3.rotation":{x:-.02,y:.142,z:.004},"RightHandIndex1.rotation":{x:.148,y:-.031,z:.069},"RightHandIndex2.rotation":{x:.326,y:.049,z:.029},"RightHandIndex3.rotation":{x:.247,y:.053,z:.073},"RightHandMiddle1.rotation":{x:.237,y:.057,z:.089},"RightHandMiddle2.rotation":{x:.469,y:.036,z:.081},"RightHandMiddle3.rotation":{x:.206,y:.015,z:.017},"RightHandRing1.rotation":{x:.204,y:.086,z:.135},"RightHandRing2.rotation":{x:.579,y:-.02,z:.098},"RightHandRing3.rotation":{x:.272,y:-.021,z:.063},"RightHandPinky1.rotation":{x:.404,y:.182,z:.137},"RightHandPinky2.rotation":{x:.613,y:-.128,z:.144},"RightHandPinky3.rotation":{x:.268,y:-.094,z:.081},"LeftUpLeg.rotation":{x:.096,y:.209,z:2.983},"LeftLeg.rotation":{x:-.053,y:.042,z:-.017},"LeftFoot.rotation":{x:1.091,y:.15,z:.026},"LeftToeBase.rotation":{x:.469,y:-.07,z:-.015},"RightUpLeg.rotation":{x:-.307,y:-.219,z:2.912},"RightLeg.rotation":{x:-.359,y:.164,z:.015},"RightFoot.rotation":{x:1.035,y:.11,z:.005},"RightToeBase.rotation":{x:.467,y:.07,z:.015}}},hip:{standing:!0,props:{"Hips.position":{x:0,y:1,z:0},"Hips.rotation":{x:-.036,y:.09,z:.135},"Spine.rotation":{x:.076,y:-.035,z:.01},"Spine1.rotation":{x:-.096,y:.013,z:-.094},"Spine2.rotation":{x:-.014,y:.002,z:-.097},"Neck.rotation":{x:.034,y:-.051,z:-.075},"Head.rotation":{x:.298,y:-.1,z:.154},"LeftShoulder.rotation":{x:1.694,y:.011,z:-1.68},"LeftArm.rotation":{x:1.343,y:.177,z:-.153},"LeftForeArm.rotation":{x:-.049,y:.134,z:.351},"LeftHand.rotation":{x:.057,y:-.189,z:-.026},"LeftHandThumb1.rotation":{x:.368,y:-.066,z:.438},"LeftHandThumb2.rotation":{x:-.156,y:.029,z:-.369},"LeftHandThumb3.rotation":{x:.034,y:-.009,z:.016},"LeftHandIndex1.rotation":{x:.157,y:-.002,z:-.171},"LeftHandIndex2.rotation":{x:.099,y:0,z:0},"LeftHandIndex3.rotation":{x:.1,y:0,z:0},"LeftHandMiddle1.rotation":{x:.222,y:-.019,z:-.16},"LeftHandMiddle2.rotation":{x:.142,y:0,z:0},"LeftHandMiddle3.rotation":{x:.141,y:0,z:0},"LeftHandRing1.rotation":{x:.333,y:-.039,z:-.174},"LeftHandRing2.rotation":{x:.214,y:0,z:0},"LeftHandRing3.rotation":{x:.213,y:0,z:0},"LeftHandPinky1.rotation":{x:.483,y:-.069,z:-.189},"LeftHandPinky2.rotation":{x:.312,y:0,z:0},"LeftHandPinky3.rotation":{x:.309,y:0,z:0},"RightShoulder.rotation":{x:1.597,y:.012,z:1.816},"RightArm.rotation":{x:.618,y:-1.274,z:-.266},"RightForeArm.rotation":{x:-.395,y:-.097,z:-1.342},"RightHand.rotation":{x:-.816,y:-.057,z:-.976},"RightHandThumb1.rotation":{x:.42,y:.23,z:-1.172},"RightHandThumb2.rotation":{x:-.027,y:.361,z:.122},"RightHandThumb3.rotation":{x:.076,y:.125,z:-.371},"RightHandIndex1.rotation":{x:-.158,y:-.045,z:.033},"RightHandIndex2.rotation":{x:.391,y:.051,z:.025},"RightHandIndex3.rotation":{x:.317,y:.058,z:.07},"RightHandMiddle1.rotation":{x:.486,y:.066,z:.014},"RightHandMiddle2.rotation":{x:.718,y:.055,z:.07},"RightHandMiddle3.rotation":{x:.453,y:.019,z:.013},"RightHandRing1.rotation":{x:.591,y:.241,z:.11},"RightHandRing2.rotation":{x:1.014,y:.023,z:.097},"RightHandRing3.rotation":{x:.708,y:.008,z:.066},"RightHandPinky1.rotation":{x:1.02,y:.305,z:.051},"RightHandPinky2.rotation":{x:1.187,y:-.028,z:.191},"RightHandPinky3.rotation":{x:.872,y:-.031,z:.121},"LeftUpLeg.rotation":{x:-.095,y:-.058,z:-3.338},"LeftLeg.rotation":{x:-.366,y:.287,z:-.021},"LeftFoot.rotation":{x:1.131,y:.21,z:.176},"LeftToeBase.rotation":{x:.739,y:-.068,z:-.001},"RightUpLeg.rotation":{x:-.502,y:.362,z:3.153},"RightLeg.rotation":{x:-1.002,y:.109,z:.008},"RightFoot.rotation":{x:.626,y:-.097,z:-.194},"RightToeBase.rotation":{x:1.33,y:.288,z:-.078}}},turn:{standing:!0,props:{"Hips.position":{x:0,y:1,z:0},"Hips.rotation":{x:-.07,y:-.604,z:-.004},"Spine.rotation":{x:-.007,y:.003,z:.071},"Spine1.rotation":{x:-.053,y:.024,z:-.06},"Spine2.rotation":{x:.074,y:.013,z:-.068},"Neck.rotation":{x:.03,y:.186,z:-.077},"Head.rotation":{x:.045,y:.243,z:-.086},"LeftShoulder.rotation":{x:1.717,y:-.085,z:-1.761},"LeftArm.rotation":{x:1.314,y:.07,z:-.057},"LeftForeArm.rotation":{x:-.151,y:.714,z:.302},"LeftHand.rotation":{x:-.069,y:.003,z:-.118},"LeftHandThumb1.rotation":{x:.23,y:.258,z:.354},"LeftHandThumb2.rotation":{x:-.107,y:-.338,z:-.455},"LeftHandThumb3.rotation":{x:-.015,y:-.142,z:.002},"LeftHandIndex1.rotation":{x:.145,y:.032,z:-.069},"LeftHandIndex2.rotation":{x:.323,y:-.049,z:-.028},"LeftHandIndex3.rotation":{x:.249,y:-.053,z:-.074},"LeftHandMiddle1.rotation":{x:.235,y:-.057,z:-.088},"LeftHandMiddle2.rotation":{x:.468,y:-.036,z:-.081},"LeftHandMiddle3.rotation":{x:.203,y:-.015,z:-.017},"LeftHandRing1.rotation":{x:.185,y:-.118,z:-.157},"LeftHandRing2.rotation":{x:.578,y:.02,z:-.097},"LeftHandRing3.rotation":{x:.27,y:.021,z:-.063},"LeftHandPinky1.rotation":{x:.404,y:-.182,z:-.138},"LeftHandPinky2.rotation":{x:.612,y:.128,z:-.144},"LeftHandPinky3.rotation":{x:.267,y:.094,z:-.081},"RightShoulder.rotation":{x:1.605,y:.17,z:1.625},"RightArm.rotation":{x:1.574,y:-.655,z:.388},"RightForeArm.rotation":{x:-.36,y:-.849,z:-.465},"RightHand.rotation":{x:.114,y:.416,z:-.069},"RightHandThumb1.rotation":{x:.486,y:.009,z:-.492},"RightHandThumb2.rotation":{x:-.073,y:-.01,z:.284},"RightHandThumb3.rotation":{x:-.054,y:-.006,z:.209},"RightHandIndex1.rotation":{x:.245,y:-.014,z:.052},"RightHandIndex2.rotation":{x:.155,y:0,z:0},"RightHandIndex3.rotation":{x:.153,y:0,z:0},"RightHandMiddle1.rotation":{x:.238,y:.004,z:.028},"RightHandMiddle2.rotation":{x:.15,y:0,z:0},"RightHandMiddle3.rotation":{x:.149,y:0,z:0},"RightHandRing1.rotation":{x:.267,y:.012,z:.007},"RightHandRing2.rotation":{x:.169,y:0,z:0},"RightHandRing3.rotation":{x:.167,y:0,z:0},"RightHandPinky1.rotation":{x:.304,y:.018,z:-.021},"RightHandPinky2.rotation":{x:.192,y:0,z:0},"RightHandPinky3.rotation":{x:.19,y:0,z:0},"LeftUpLeg.rotation":{x:-.001,y:-.058,z:-3.238},"LeftLeg.rotation":{x:-.29,y:.058,z:-.021},"LeftFoot.rotation":{x:1.288,y:.168,z:.183},"LeftToeBase.rotation":{x:.363,y:-.09,z:-.01},"RightUpLeg.rotation":{x:-.1,y:.36,z:3.062},"RightLeg.rotation":{x:-.67,y:-.304,z:.043},"RightFoot.rotation":{x:1.195,y:-.159,z:-.294},"RightToeBase.rotation":{x:.737,y:.164,z:-.002}}},bend:{bend:!0,standing:!0,props:{"Hips.position":{x:-.007,y:.943,z:-.001},"Hips.rotation":{x:1.488,y:-.633,z:1.435},"Spine.rotation":{x:-.126,y:.007,z:-.057},"Spine1.rotation":{x:-.134,y:.009,z:.01},"Spine2.rotation":{x:-.019,y:0,z:-.002},"Neck.rotation":{x:-.159,y:.572,z:-.108},"Head.rotation":{x:-.064,y:.716,z:-.257},"RightShoulder.rotation":{x:1.625,y:-.043,z:1.382},"RightArm.rotation":{x:.746,y:-.96,z:-1.009},"RightForeArm.rotation":{x:-.199,y:-.528,z:-.38},"RightHand.rotation":{x:-.261,y:-.043,z:-.027},"RightHandThumb1.rotation":{x:.172,y:-.138,z:-.445},"RightHandThumb2.rotation":{x:-.158,y:.327,z:.545},"RightHandThumb3.rotation":{x:-.062,y:.138,z:.152},"RightHandIndex1.rotation":{x:.328,y:-.005,z:.132},"RightHandIndex2.rotation":{x:.303,y:.049,z:.028},"RightHandIndex3.rotation":{x:.241,y:.046,z:.077},"RightHandMiddle1.rotation":{x:.309,y:.074,z:.089},"RightHandMiddle2.rotation":{x:.392,y:.036,z:.081},"RightHandMiddle3.rotation":{x:.199,y:.014,z:.019},"RightHandRing1.rotation":{x:.239,y:.143,z:.091},"RightHandRing2.rotation":{x:.275,y:-.02,z:.097},"RightHandRing3.rotation":{x:.248,y:-.023,z:.061},"RightHandPinky1.rotation":{x:.211,y:.154,z:.029},"RightHandPinky2.rotation":{x:.348,y:-.128,z:.144},"RightHandPinky3.rotation":{x:.21,y:-.091,z:.065},"LeftShoulder.rotation":{x:1.626,y:-.027,z:-1.367},"LeftArm.rotation":{x:1.048,y:.737,z:.712},"LeftForeArm.rotation":{x:-.508,y:.879,z:.625},"LeftHand.rotation":{x:.06,y:-.243,z:-.079},"LeftHandThumb1.rotation":{x:.187,y:-.072,z:.346},"LeftHandThumb2.rotation":{x:-.066,y:.008,z:-.256},"LeftHandThumb3.rotation":{x:-.085,y:.014,z:-.334},"LeftHandIndex1.rotation":{x:-.1,y:.016,z:-.058},"LeftHandIndex2.rotation":{x:.334,y:0,z:0},"LeftHandIndex3.rotation":{x:.281,y:0,z:0},"LeftHandMiddle1.rotation":{x:-.056,y:0,z:0},"LeftHandMiddle2.rotation":{x:.258,y:0,z:0},"LeftHandMiddle3.rotation":{x:.26,y:0,z:0},"LeftHandRing1.rotation":{x:-.067,y:-.002,z:.008},"LeftHandRing2.rotation":{x:.259,y:0,z:0},"LeftHandRing3.rotation":{x:.276,y:0,z:0},"LeftHandPinky1.rotation":{x:-.128,y:-.007,z:.042},"LeftHandPinky2.rotation":{x:.227,y:0,z:0},"LeftHandPinky3.rotation":{x:.145,y:0,z:0},"RightUpLeg.rotation":{x:-1.507,y:.2,z:-3.043},"RightLeg.rotation":{x:-.689,y:-.124,z:.017},"RightFoot.rotation":{x:.909,y:.008,z:-.093},"RightToeBase.rotation":{x:.842,y:.075,z:-.008},"LeftUpLeg.rotation":{x:-1.449,y:-.2,z:3.018},"LeftLeg.rotation":{x:-.74,y:-.115,z:-.008},"LeftFoot.rotation":{x:1.048,y:-.058,z:.117},"LeftToeBase.rotation":{x:.807,y:-.067,z:.003}}},back:{standing:!0,props:{"Hips.position":{x:0,y:1,z:0},"Hips.rotation":{x:-.732,y:-1.463,z:-.637},"Spine.rotation":{x:-.171,y:.106,z:.157},"Spine1.rotation":{x:-.044,y:.138,z:-.059},"Spine2.rotation":{x:.082,y:.133,z:-.074},"Neck.rotation":{x:.39,y:.591,z:-.248},"Head.rotation":{x:-.001,y:.596,z:-.057},"LeftShoulder.rotation":{x:1.676,y:.007,z:-1.892},"LeftArm.rotation":{x:-5.566,y:1.188,z:-.173},"LeftForeArm.rotation":{x:-.673,y:-.105,z:1.702},"LeftHand.rotation":{x:-.469,y:-.739,z:.003},"LeftHandThumb1.rotation":{x:.876,y:.274,z:.793},"LeftHandThumb2.rotation":{x:.161,y:-.23,z:-.172},"LeftHandThumb3.rotation":{x:.078,y:.027,z:.156},"LeftHandIndex1.rotation":{x:-.085,y:-.002,z:.009},"LeftHandIndex2.rotation":{x:.176,y:0,z:-.002},"LeftHandIndex3.rotation":{x:-.036,y:.001,z:-.035},"LeftHandMiddle1.rotation":{x:.015,y:.144,z:-.076},"LeftHandMiddle2.rotation":{x:.378,y:-.007,z:-.077},"LeftHandMiddle3.rotation":{x:-.141,y:-.001,z:.031},"LeftHandRing1.rotation":{x:.039,y:.02,z:-.2},"LeftHandRing2.rotation":{x:.25,y:-.002,z:-.073},"LeftHandRing3.rotation":{x:.236,y:.006,z:-.075},"LeftHandPinky1.rotation":{x:.172,y:-.033,z:-.275},"LeftHandPinky2.rotation":{x:.216,y:.043,z:-.054},"LeftHandPinky3.rotation":{x:.325,y:.078,z:-.13},"RightShoulder.rotation":{x:2.015,y:-.168,z:1.706},"RightArm.rotation":{x:.203,y:-1.258,z:-.782},"RightForeArm.rotation":{x:-.658,y:-.133,z:-1.401},"RightHand.rotation":{x:-1.504,y:.375,z:-.005},"RightHandThumb1.rotation":{x:.413,y:-.158,z:-1.121},"RightHandThumb2.rotation":{x:-.142,y:-.008,z:.209},"RightHandThumb3.rotation":{x:-.091,y:.021,z:.142},"RightHandIndex1.rotation":{x:-.167,y:.014,z:-.072},"RightHandIndex2.rotation":{x:.474,y:.009,z:.051},"RightHandIndex3.rotation":{x:.115,y:.006,z:.047},"RightHandMiddle1.rotation":{x:.385,y:.019,z:.144},"RightHandMiddle2.rotation":{x:.559,y:.035,z:.101},"RightHandMiddle3.rotation":{x:.229,y:0,z:.027},"RightHandRing1.rotation":{x:.48,y:.026,z:.23},"RightHandRing2.rotation":{x:.772,y:.038,z:.109},"RightHandRing3.rotation":{x:.622,y:.039,z:.106},"RightHandPinky1.rotation":{x:.767,y:.288,z:.353},"RightHandPinky2.rotation":{x:.886,y:.049,z:.122},"RightHandPinky3.rotation":{x:.662,y:.044,z:.113},"LeftUpLeg.rotation":{x:-.206,y:-.268,z:-3.343},"LeftLeg.rotation":{x:-.333,y:.757,z:-.043},"LeftFoot.rotation":{x:1.049,y:.167,z:.287},"LeftToeBase.rotation":{x:.672,y:-.069,z:-.004},"RightUpLeg.rotation":{x:.055,y:-.226,z:3.037},"RightLeg.rotation":{x:-.559,y:.39,z:-.001},"RightFoot.rotation":{x:1.2,y:.133,z:.085},"RightToeBase.rotation":{x:.92,y:.093,z:-.013}}},straight:{standing:!0,props:{"Hips.position":{x:0,y:.989,z:.001},"Hips.rotation":{x:.047,y:.007,z:-.007},"Spine.rotation":{x:-.143,y:-.007,z:.005},"Spine1.rotation":{x:-.043,y:-.014,z:.012},"Spine2.rotation":{x:.072,y:-.013,z:.013},"Neck.rotation":{x:.048,y:-.003,z:.012},"Head.rotation":{x:.05,y:-.02,z:-.017},"LeftShoulder.rotation":{x:1.62,y:-.166,z:-1.605},"LeftArm.rotation":{x:1.275,y:.544,z:-.092},"LeftForeArm.rotation":{x:0,y:0,z:.302},"LeftHand.rotation":{x:-.225,y:-.154,z:.11},"LeftHandThumb1.rotation":{x:.435,y:-.044,z:.457},"LeftHandThumb2.rotation":{x:-.028,y:.002,z:-.246},"LeftHandThumb3.rotation":{x:-.236,y:-.025,z:.113},"LeftHandIndex1.rotation":{x:.218,y:.008,z:-.081},"LeftHandIndex2.rotation":{x:.165,y:-.001,z:-.017},"LeftHandIndex3.rotation":{x:.165,y:-.001,z:-.017},"LeftHandMiddle1.rotation":{x:.235,y:-.011,z:-.065},"LeftHandMiddle2.rotation":{x:.182,y:-.002,z:-.019},"LeftHandMiddle3.rotation":{x:.182,y:-.002,z:-.019},"LeftHandRing1.rotation":{x:.316,y:-.017,z:.008},"LeftHandRing2.rotation":{x:.253,y:-.003,z:-.026},"LeftHandRing3.rotation":{x:.255,y:-.003,z:-.026},"LeftHandPinky1.rotation":{x:.336,y:-.062,z:.088},"LeftHandPinky2.rotation":{x:.276,y:-.004,z:-.028},"LeftHandPinky3.rotation":{x:.276,y:-.004,z:-.028},"RightShoulder.rotation":{x:1.615,y:.064,z:1.53},"RightArm.rotation":{x:1.313,y:-.424,z:.131},"RightForeArm.rotation":{x:0,y:0,z:-.317},"RightHand.rotation":{x:-.158,y:-.639,z:-.196},"RightHandThumb1.rotation":{x:.44,y:.048,z:-.549},"RightHandThumb2.rotation":{x:-.056,y:-.008,z:.274},"RightHandThumb3.rotation":{x:-.258,y:.031,z:-.095},"RightHandIndex1.rotation":{x:.169,y:-.011,z:.105},"RightHandIndex2.rotation":{x:.134,y:.001,z:.011},"RightHandIndex3.rotation":{x:.134,y:.001,z:.011},"RightHandMiddle1.rotation":{x:.288,y:.014,z:.092},"RightHandMiddle2.rotation":{x:.248,y:.003,z:.02},"RightHandMiddle3.rotation":{x:.249,y:.003,z:.02},"RightHandRing1.rotation":{x:.369,y:.019,z:.006},"RightHandRing2.rotation":{x:.321,y:.004,z:.026},"RightHandRing3.rotation":{x:.323,y:.004,z:.026},"RightHandPinky1.rotation":{x:.468,y:.085,z:-.03},"RightHandPinky2.rotation":{x:.427,y:.007,z:.034},"RightHandPinky3.rotation":{x:.142,y:.001,z:.012},"LeftUpLeg.rotation":{x:-.077,y:-.058,z:3.126},"LeftLeg.rotation":{x:-.252,y:.001,z:-.018},"LeftFoot.rotation":{x:1.315,y:-.064,z:.315},"LeftToeBase.rotation":{x:.577,y:-.07,z:-.009},"RightUpLeg.rotation":{x:-.083,y:-.032,z:3.124},"RightLeg.rotation":{x:-.272,y:-.003,z:.021},"RightFoot.rotation":{x:1.342,y:.076,z:-.222},"RightToeBase.rotation":{x:.44,y:.069,z:.016}}},wide:{standing:!0,props:{"Hips.position":{x:0,y:1.017,z:.016},"Hips.rotation":{x:.064,y:-.048,z:.059},"Spine.rotation":{x:-.123,y:0,z:-.018},"Spine1.rotation":{x:.014,y:.003,z:-.006},"Spine2.rotation":{x:.04,y:.003,z:-.007},"Neck.rotation":{x:.101,y:.007,z:-.035},"Head.rotation":{x:-.091,y:-.049,z:.105},"RightShoulder.rotation":{x:1.831,y:.017,z:1.731},"RightArm.rotation":{x:-1.673,y:-1.102,z:-3.132},"RightForeArm.rotation":{x:.265,y:.23,z:-.824},"RightHand.rotation":{x:-.52,y:.345,z:-.061},"RightHandThumb1.rotation":{x:.291,y:.056,z:-.428},"RightHandThumb2.rotation":{x:.025,y:.005,z:.166},"RightHandThumb3.rotation":{x:-.089,y:.009,z:.068},"RightHandIndex1.rotation":{x:.392,y:-.015,z:.11},"RightHandIndex2.rotation":{x:.391,y:.001,z:.004},"RightHandIndex3.rotation":{x:.326,y:0,z:.003},"RightHandMiddle1.rotation":{x:.285,y:.068,z:.081},"RightHandMiddle2.rotation":{x:.519,y:.004,z:.011},"RightHandMiddle3.rotation":{x:.252,y:0,z:.001},"RightHandRing1.rotation":{x:.207,y:.133,z:.146},"RightHandRing2.rotation":{x:.597,y:.004,z:.004},"RightHandRing3.rotation":{x:.292,y:.002,z:.012},"RightHandPinky1.rotation":{x:.338,y:.182,z:.136},"RightHandPinky2.rotation":{x:.533,y:.002,z:.004},"RightHandPinky3.rotation":{x:.194,y:0,z:.002},"LeftShoulder.rotation":{x:1.83,y:-.063,z:-1.808},"LeftArm.rotation":{x:-1.907,y:1.228,z:-2.959},"LeftForeArm.rotation":{x:-.159,y:.268,z:.572},"LeftHand.rotation":{x:.069,y:-.498,z:-.025},"LeftHandThumb1.rotation":{x:.738,y:.123,z:.178},"LeftHandThumb2.rotation":{x:-.26,y:.028,z:-.477},"LeftHandThumb3.rotation":{x:-.448,y:.093,z:-.661},"LeftHandIndex1.rotation":{x:1.064,y:.005,z:-.13},"LeftHandIndex2.rotation":{x:1.55,y:-.143,z:-.136},"LeftHandIndex3.rotation":{x:.722,y:-.076,z:-.127},"LeftHandMiddle1.rotation":{x:1.095,y:-.091,z:.006},"LeftHandMiddle2.rotation":{x:1.493,y:-.174,z:-.151},"LeftHandMiddle3.rotation":{x:.651,y:-.031,z:-.087},"LeftHandRing1.rotation":{x:1.083,y:-.224,z:.072},"LeftHandRing2.rotation":{x:1.145,y:-.107,z:-.195},"LeftHandRing3.rotation":{x:1.208,y:-.134,z:-.158},"LeftHandPinky1.rotation":{x:.964,y:-.383,z:.128},"LeftHandPinky2.rotation":{x:1.457,y:-.146,z:-.159},"LeftHandPinky3.rotation":{x:1.019,y:-.102,z:-.141},"RightUpLeg.rotation":{x:-.221,y:-.233,z:2.87},"RightLeg.rotation":{x:-.339,y:-.043,z:-.041},"RightFoot.rotation":{x:1.081,y:.177,z:.114},"RightToeBase.rotation":{x:.775,y:0,z:0},"LeftUpLeg.rotation":{x:-.185,y:.184,z:3.131},"LeftLeg.rotation":{x:-.408,y:.129,z:.02},"LeftFoot.rotation":{x:1.167,y:-.002,z:-.007},"LeftToeBase.rotation":{x:.723,y:0,z:0}}},oneknee:{kneeling:!0,props:{"Hips.position":{x:-.005,y:.415,z:-.017},"Hips.rotation":{x:-.25,y:.04,z:-.238},"Spine.rotation":{x:.037,y:.043,z:.047},"Spine1.rotation":{x:.317,y:.103,z:.066},"Spine2.rotation":{x:.433,y:.109,z:.054},"Neck.rotation":{x:-.156,y:-.092,z:.059},"Head.rotation":{x:-.398,y:-.032,z:.018},"RightShoulder.rotation":{x:1.546,y:.119,z:1.528},"RightArm.rotation":{x:.896,y:-.247,z:-.512},"RightForeArm.rotation":{x:.007,y:0,z:-1.622},"RightHand.rotation":{x:1.139,y:-.853,z:.874},"RightHandThumb1.rotation":{x:.176,y:.107,z:-.311},"RightHandThumb2.rotation":{x:-.047,y:-.003,z:.12},"RightHandThumb3.rotation":{x:0,y:0,z:0},"RightHandIndex1.rotation":{x:.186,y:.005,z:.125},"RightHandIndex2.rotation":{x:.454,y:.005,z:.015},"RightHandIndex3.rotation":{x:0,y:0,z:0},"RightHandMiddle1.rotation":{x:.444,y:.035,z:.127},"RightHandMiddle2.rotation":{x:.403,y:-.006,z:-.04},"RightHandMiddle3.rotation":{x:0,y:0,z:0},"RightHandRing1.rotation":{x:.543,y:.074,z:.121},"RightHandRing2.rotation":{x:.48,y:-.018,z:-.063},"RightHandRing3.rotation":{x:0,y:0,z:0},"RightHandPinky1.rotation":{x:.464,y:.086,z:.113},"RightHandPinky2.rotation":{x:.667,y:-.06,z:-.128},"RightHandPinky3.rotation":{x:0,y:0,z:0},"LeftShoulder.rotation":{x:1.545,y:-.116,z:-1.529},"LeftArm.rotation":{x:.799,y:.631,z:.556},"LeftForeArm.rotation":{x:-.002,y:.007,z:.926},"LeftHand.rotation":{x:-.508,y:.439,z:.502},"LeftHandThumb1.rotation":{x:.651,y:-.035,z:.308},"LeftHandThumb2.rotation":{x:-.053,y:.008,z:-.11},"LeftHandThumb3.rotation":{x:0,y:0,z:0},"LeftHandIndex1.rotation":{x:.662,y:-.053,z:-.116},"LeftHandIndex2.rotation":{x:.309,y:-.004,z:-.02},"LeftHandIndex3.rotation":{x:0,y:0,z:0},"LeftHandMiddle1.rotation":{x:.501,y:-.062,z:-.12},"LeftHandMiddle2.rotation":{x:.144,y:-.002,z:.016},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:.397,y:-.029,z:-.143},"LeftHandRing2.rotation":{x:.328,y:.01,z:.059},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:.194,y:.008,z:-.164},"LeftHandPinky2.rotation":{x:.38,y:.031,z:.128},"LeftHandPinky3.rotation":{x:0,y:0,z:0},"RightUpLeg.rotation":{x:-1.594,y:-.251,z:2.792},"RightLeg.rotation":{x:-2.301,y:-.073,z:.055},"RightFoot.rotation":{x:1.553,y:-.207,z:-.094},"RightToeBase.rotation":{x:.459,y:.069,z:.016},"LeftUpLeg.rotation":{x:-.788,y:-.236,z:-2.881},"LeftLeg.rotation":{x:-2.703,y:.012,z:-.047},"LeftFoot.rotation":{x:2.191,y:-.102,z:.019},"LeftToeBase.rotation":{x:1.215,y:-.027,z:.01}}},kneel:{kneeling:!0,lying:!0,props:{"Hips.position":{x:0,y:.532,z:-.002},"Hips.rotation":{x:.018,y:-.008,z:-.017},"Spine.rotation":{x:-.139,y:-.01,z:.002},"Spine1.rotation":{x:.002,y:-.002,z:.001},"Spine2.rotation":{x:.028,y:-.002,z:.001},"Neck.rotation":{x:-.007,y:0,z:-.002},"Head.rotation":{x:-.02,y:-.008,z:-.004},"LeftShoulder.rotation":{x:1.77,y:-.428,z:-1.588},"LeftArm.rotation":{x:.911,y:.343,z:.083},"LeftForeArm.rotation":{x:0,y:0,z:.347},"LeftHand.rotation":{x:.033,y:-.052,z:-.105},"LeftHandThumb1.rotation":{x:.508,y:-.22,z:.708},"LeftHandThumb2.rotation":{x:-.323,y:-.139,z:-.56},"LeftHandThumb3.rotation":{x:-.328,y:.16,z:-.301},"LeftHandIndex1.rotation":{x:.178,y:.248,z:.045},"LeftHandIndex2.rotation":{x:.236,y:-.002,z:-.019},"LeftHandIndex3.rotation":{x:-.062,y:0,z:.005},"LeftHandMiddle1.rotation":{x:.123,y:-.005,z:-.019},"LeftHandMiddle2.rotation":{x:.589,y:-.014,z:-.045},"LeftHandMiddle3.rotation":{x:.231,y:-.002,z:-.019},"LeftHandRing1.rotation":{x:.196,y:-.008,z:-.091},"LeftHandRing2.rotation":{x:.483,y:-.009,z:-.038},"LeftHandRing3.rotation":{x:.367,y:-.005,z:-.029},"LeftHandPinky1.rotation":{x:.191,y:-.269,z:-.246},"LeftHandPinky2.rotation":{x:.37,y:-.006,z:-.029},"LeftHandPinky3.rotation":{x:.368,y:-.005,z:-.029},"RightShoulder.rotation":{x:1.73,y:.434,z:1.715},"RightArm.rotation":{x:.841,y:-.508,z:-.155},"RightForeArm.rotation":{x:0,y:0,z:-.355},"RightHand.rotation":{x:.091,y:.137,z:.197},"RightHandThumb1.rotation":{x:.33,y:.051,z:-.753},"RightHandThumb2.rotation":{x:-.113,y:.075,z:.612},"RightHandThumb3.rotation":{x:-.271,y:-.166,z:.164},"RightHandIndex1.rotation":{x:.073,y:.001,z:-.093},"RightHandIndex2.rotation":{x:.338,y:.006,z:.034},"RightHandIndex3.rotation":{x:.131,y:.001,z:.013},"RightHandMiddle1.rotation":{x:.13,y:.005,z:-.017},"RightHandMiddle2.rotation":{x:.602,y:.018,z:.058},"RightHandMiddle3.rotation":{x:-.031,y:0,z:-.003},"RightHandRing1.rotation":{x:.351,y:.019,z:.045},"RightHandRing2.rotation":{x:.19,y:.002,z:.019},"RightHandRing3.rotation":{x:.21,y:.002,z:.021},"RightHandPinky1.rotation":{x:.256,y:.17,z:.118},"RightHandPinky2.rotation":{x:.451,y:.01,z:.045},"RightHandPinky3.rotation":{x:.346,y:.006,z:.035},"LeftUpLeg.rotation":{x:-.06,y:.1,z:-2.918},"LeftLeg.rotation":{x:-1.933,y:-.01,z:.011},"LeftFoot.rotation":{x:.774,y:-.162,z:-.144},"LeftToeBase.rotation":{x:1.188,y:0,z:0},"RightUpLeg.rotation":{x:-.099,y:-.057,z:2.922},"RightLeg.rotation":{x:-1.93,y:.172,z:-.02},"RightFoot.rotation":{x:.644,y:.251,z:.212},"RightToeBase.rotation":{x:.638,y:-.034,z:-.001}}},sitting:{sitting:!0,lying:!0,props:{"Hips.position":{x:0,y:.117,z:.005},"Hips.rotation":{x:-.411,y:-.049,z:.056},"Spine.rotation":{x:.45,y:-.039,z:-.116},"Spine1.rotation":{x:.092,y:-.076,z:.08},"Spine2.rotation":{x:.073,y:.035,z:.066},"Neck.rotation":{x:.051,y:.053,z:-.079},"Head.rotation":{x:-.169,y:.009,z:.034},"LeftShoulder.rotation":{x:1.756,y:-.037,z:-1.301},"LeftArm.rotation":{x:-.098,y:.016,z:1.006},"LeftForeArm.rotation":{x:-.089,y:.08,z:.837},"LeftHand.rotation":{x:.262,y:-.399,z:.3},"LeftHandThumb1.rotation":{x:.149,y:-.043,z:.452},"LeftHandThumb2.rotation":{x:.032,y:.006,z:-.162},"LeftHandThumb3.rotation":{x:-.086,y:-.005,z:-.069},"LeftHandIndex1.rotation":{x:.145,y:.032,z:-.069},"LeftHandIndex2.rotation":{x:.325,y:-.001,z:-.004},"LeftHandIndex3.rotation":{x:.253,y:0,z:-.003},"LeftHandMiddle1.rotation":{x:.186,y:-.051,z:-.091},"LeftHandMiddle2.rotation":{x:.42,y:-.003,z:-.011},"LeftHandMiddle3.rotation":{x:.153,y:.001,z:-.001},"LeftHandRing1.rotation":{x:.087,y:-.19,z:-.078},"LeftHandRing2.rotation":{x:.488,y:-.004,z:-.005},"LeftHandRing3.rotation":{x:.183,y:-.001,z:-.012},"LeftHandPinky1.rotation":{x:.205,y:-.262,z:.051},"LeftHandPinky2.rotation":{x:.407,y:-.002,z:-.004},"LeftHandPinky3.rotation":{x:.068,y:0,z:-.002},"RightShoulder.rotation":{x:1.619,y:-.139,z:1.179},"RightArm.rotation":{x:.17,y:-.037,z:-1.07},"RightForeArm.rotation":{x:-.044,y:-.056,z:-.665},"RightHand.rotation":{x:.278,y:.454,z:-.253},"RightHandThumb1.rotation":{x:.173,y:.089,z:-.584},"RightHandThumb2.rotation":{x:-.003,y:-.004,z:.299},"RightHandThumb3.rotation":{x:-.133,y:-.002,z:.235},"RightHandIndex1.rotation":{x:.393,y:-.023,z:.108},"RightHandIndex2.rotation":{x:.391,y:.001,z:.004},"RightHandIndex3.rotation":{x:.326,y:0,z:.003},"RightHandMiddle1.rotation":{x:.285,y:.062,z:.086},"RightHandMiddle2.rotation":{x:.519,y:.003,z:.011},"RightHandMiddle3.rotation":{x:.252,y:-.001,z:.001},"RightHandRing1.rotation":{x:.207,y:.122,z:.155},"RightHandRing2.rotation":{x:.597,y:.004,z:.005},"RightHandRing3.rotation":{x:.292,y:.001,z:.012},"RightHandPinky1.rotation":{x:.338,y:.171,z:.149},"RightHandPinky2.rotation":{x:.533,y:.002,z:.004},"RightHandPinky3.rotation":{x:.194,y:0,z:.002},"LeftUpLeg.rotation":{x:-1.957,y:.083,z:-2.886},"LeftLeg.rotation":{x:-1.46,y:.123,z:.005},"LeftFoot.rotation":{x:-.013,y:.016,z:.09},"LeftToeBase.rotation":{x:.744,y:0,z:0},"RightUpLeg.rotation":{x:-1.994,y:.125,z:2.905},"RightLeg.rotation":{x:-1.5,y:-.202,z:-.006},"RightFoot.rotation":{x:-.012,y:-.065,z:.081},"RightToeBase.rotation":{x:.758,y:0,z:0}}}},this.gestureTemplates={handup:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,2],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-.815,y:[-.4,0,1,2],z:1.575},"LeftHand.rotation":{x:-.529,y:-.2,z:.022},"LeftHandThumb1.rotation":{x:.745,y:-.526,z:.604},"LeftHandThumb2.rotation":{x:-.107,y:-.01,z:-.142},"LeftHandThumb3.rotation":{x:0,y:.001,z:0},"LeftHandIndex1.rotation":{x:-.126,y:-.035,z:-.087},"LeftHandIndex2.rotation":{x:.255,y:.007,z:-.085},"LeftHandIndex3.rotation":{x:0,y:0,z:0},"LeftHandMiddle1.rotation":{x:-.019,y:-.128,z:-.082},"LeftHandMiddle2.rotation":{x:.233,y:.019,z:-.074},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:.005,y:-.241,z:-.122},"LeftHandRing2.rotation":{x:.261,y:.021,z:-.076},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:.059,y:-.336,z:-.2},"LeftHandPinky2.rotation":{x:.153,y:.019,z:.001},"LeftHandPinky3.rotation":{x:0,y:0,z:0}},index:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,2],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-.815,y:[-.4,0,1,2],z:1.575},"LeftHand.rotation":{x:-.276,y:-.506,z:-.208},"LeftHandThumb1.rotation":{x:.579,y:.228,z:.363},"LeftHandThumb2.rotation":{x:-.027,y:-.04,z:-.662},"LeftHandThumb3.rotation":{x:0,y:.001,z:0},"LeftHandIndex1.rotation":{x:0,y:-.105,z:.225},"LeftHandIndex2.rotation":{x:.256,y:-.103,z:-.213},"LeftHandIndex3.rotation":{x:0,y:0,z:0},"LeftHandMiddle1.rotation":{x:1.453,y:.07,z:.021},"LeftHandMiddle2.rotation":{x:1.599,y:.062,z:.07},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:1.528,y:-.073,z:.052},"LeftHandRing2.rotation":{x:1.386,y:.044,z:.053},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:1.65,y:-.204,z:.031},"LeftHandPinky2.rotation":{x:1.302,y:.071,z:.085},"LeftHandPinky3.rotation":{x:0,y:0,z:0}},ok:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,1],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-.415,y:[-.4,0,1,2],z:1.575},"LeftHand.rotation":{x:-.476,y:-.506,z:-.208},"LeftHandThumb1.rotation":{x:.703,y:.445,z:.899},"LeftHandThumb2.rotation":{x:-.312,y:-.04,z:-.938},"LeftHandThumb3.rotation":{x:-.37,y:.024,z:-.393},"LeftHandIndex1.rotation":{x:.8,y:-.086,z:-.091},"LeftHandIndex2.rotation":{x:1.123,y:-.046,z:-.074},"LeftHandIndex3.rotation":{x:.562,y:-.013,z:-.043},"LeftHandMiddle1.rotation":{x:-.019,y:-.128,z:-.082},"LeftHandMiddle2.rotation":{x:.233,y:.019,z:-.074},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:.005,y:-.241,z:-.122},"LeftHandRing2.rotation":{x:.261,y:.021,z:-.076},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:.059,y:-.336,z:-.2},"LeftHandPinky2.rotation":{x:.153,y:.019,z:.001},"LeftHandPinky3.rotation":{x:0,y:0,z:0}},thumbup:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,2],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-.415,y:.206,z:1.575},"LeftHand.rotation":{x:-.276,y:-.506,z:-.208},"LeftHandThumb1.rotation":{x:.208,y:-.189,z:.685},"LeftHandThumb2.rotation":{x:.129,y:-.285,z:-.163},"LeftHandThumb3.rotation":{x:-.047,y:.068,z:.401},"LeftHandIndex1.rotation":{x:1.412,y:-.102,z:-.152},"LeftHandIndex2.rotation":{x:1.903,y:-.16,z:-.114},"LeftHandIndex3.rotation":{x:.535,y:-.017,z:-.062},"LeftHandMiddle1.rotation":{x:1.424,y:-.103,z:-.12},"LeftHandMiddle2.rotation":{x:1.919,y:-.162,z:-.114},"LeftHandMiddle3.rotation":{x:.44,y:-.012,z:-.051},"LeftHandRing1.rotation":{x:1.619,y:-.127,z:-.053},"LeftHandRing2.rotation":{x:1.898,y:-.16,z:-.115},"LeftHandRing3.rotation":{x:.262,y:-.004,z:-.031},"LeftHandPinky1.rotation":{x:1.661,y:-.131,z:-.016},"LeftHandPinky2.rotation":{x:1.715,y:-.067,z:-.13},"LeftHandPinky3.rotation":{x:.627,y:-.023,z:-.071}},thumbdown:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,2],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-2.015,y:.406,z:1.575},"LeftHand.rotation":{x:-.176,y:-.206,z:-.208},"LeftHandThumb1.rotation":{x:.208,y:-.189,z:.685},"LeftHandThumb2.rotation":{x:.129,y:-.285,z:-.163},"LeftHandThumb3.rotation":{x:-.047,y:.068,z:.401},"LeftHandIndex1.rotation":{x:1.412,y:-.102,z:-.152},"LeftHandIndex2.rotation":{x:1.903,y:-.16,z:-.114},"LeftHandIndex3.rotation":{x:.535,y:-.017,z:-.062},"LeftHandMiddle1.rotation":{x:1.424,y:-.103,z:-.12},"LeftHandMiddle2.rotation":{x:1.919,y:-.162,z:-.114},"LeftHandMiddle3.rotation":{x:.44,y:-.012,z:-.051},"LeftHandRing1.rotation":{x:1.619,y:-.127,z:-.053},"LeftHandRing2.rotation":{x:1.898,y:-.16,z:-.115},"LeftHandRing3.rotation":{x:.262,y:-.004,z:-.031},"LeftHandPinky1.rotation":{x:1.661,y:-.131,z:-.016},"LeftHandPinky2.rotation":{x:1.715,y:-.067,z:-.13},"LeftHandPinky3.rotation":{x:.627,y:-.023,z:-.071}},side:{"LeftShoulder.rotation":{x:1.755,y:-.035,z:-1.63},"LeftArm.rotation":{x:1.263,y:-.955,z:1.024},"LeftForeArm.rotation":{x:0,y:0,z:.8},"LeftHand.rotation":{x:-.36,y:-1.353,z:-.184},"LeftHandThumb1.rotation":{x:.137,y:-.049,z:.863},"LeftHandThumb2.rotation":{x:-.293,y:.153,z:-.193},"LeftHandThumb3.rotation":{x:-.271,y:-.17,z:.18},"LeftHandIndex1.rotation":{x:-.018,y:.007,z:.28},"LeftHandIndex2.rotation":{x:.247,y:-.003,z:-.025},"LeftHandIndex3.rotation":{x:.13,y:-.001,z:-.013},"LeftHandMiddle1.rotation":{x:.333,y:-.015,z:.182},"LeftHandMiddle2.rotation":{x:.313,y:-.005,z:-.032},"LeftHandMiddle3.rotation":{x:.294,y:-.004,z:-.03},"LeftHandRing1.rotation":{x:.456,y:-.028,z:-.092},"LeftHandRing2.rotation":{x:.53,y:-.014,z:-.052},"LeftHandRing3.rotation":{x:.478,y:-.012,z:-.047},"LeftHandPinky1.rotation":{x:.647,y:-.049,z:-.184},"LeftHandPinky2.rotation":{x:.29,y:-.004,z:-.029},"LeftHandPinky3.rotation":{x:.501,y:-.013,z:-.049}},shrug:{"Neck.rotation":{x:[-.3,.3,1,2],y:[-.3,.3,1,2],z:[-.1,.1]},"Head.rotation":{x:[-.3,.3],y:[-.3,.3],z:[-.1,.1]},"RightShoulder.rotation":{x:1.732,y:-.058,z:1.407},"RightArm.rotation":{x:1.305,y:.46,z:.118},"RightForeArm.rotation":{x:[0,2],y:[-1,.2],z:-1.637},"RightHand.rotation":{x:-.048,y:.165,z:-.39},"RightHandThumb1.rotation":{x:1.467,y:.599,z:-1.315},"RightHandThumb2.rotation":{x:-.255,y:-.123,z:.119},"RightHandThumb3.rotation":{x:0,y:-.002,z:0},"RightHandIndex1.rotation":{x:-.293,y:-.066,z:-.112},"RightHandIndex2.rotation":{x:.181,y:.007,z:.069},"RightHandIndex3.rotation":{x:0,y:0,z:0},"RightHandMiddle1.rotation":{x:-.063,y:-.041,z:.032},"RightHandMiddle2.rotation":{x:.149,y:.005,z:.05},"RightHandMiddle3.rotation":{x:0,y:0,z:0},"RightHandRing1.rotation":{x:.152,y:-.03,z:.132},"RightHandRing2.rotation":{x:.194,y:.007,z:.058},"RightHandRing3.rotation":{x:0,y:0,z:0},"RightHandPinky1.rotation":{x:.306,y:-.015,z:.257},"RightHandPinky2.rotation":{x:.15,y:-.003,z:-.003},"RightHandPinky3.rotation":{x:0,y:0,z:0},"LeftShoulder.rotation":{x:1.713,y:.141,z:-1.433},"LeftArm.rotation":{x:1.136,y:-.422,z:-.416},"LeftForeArm.rotation":{x:1.42,y:.123,z:1.506},"LeftHand.rotation":{x:.073,y:-.138,z:.064},"LeftHandThumb1.rotation":{x:1.467,y:-.599,z:1.314},"LeftHandThumb2.rotation":{x:-.255,y:.123,z:-.119},"LeftHandThumb3.rotation":{x:0,y:.001,z:0},"LeftHandIndex1.rotation":{x:-.293,y:.066,z:.112},"LeftHandIndex2.rotation":{x:.181,y:-.007,z:-.069},"LeftHandIndex3.rotation":{x:0,y:0,z:0},"LeftHandMiddle1.rotation":{x:-.062,y:.041,z:-.032},"LeftHandMiddle2.rotation":{x:.149,y:-.005,z:-.05},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:.152,y:.03,z:-.132},"LeftHandRing2.rotation":{x:.194,y:-.007,z:-.058},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:.306,y:.015,z:-.257},"LeftHandPinky2.rotation":{x:.15,y:.003,z:.003},"LeftHandPinky3.rotation":{x:0,y:0,z:0}},namaste:{"RightShoulder.rotation":{x:1.758,y:.099,z:1.604},"RightArm.rotation":{x:.862,y:-.292,z:-.932},"RightForeArm.rotation":{x:.083,y:.066,z:-1.791},"RightHand.rotation":{x:-.52,y:-.001,z:-.176},"RightHandThumb1.rotation":{x:.227,y:.418,z:-.776},"RightHandThumb2.rotation":{x:-.011,y:-.003,z:.171},"RightHandThumb3.rotation":{x:-.041,y:-.001,z:-.013},"RightHandIndex1.rotation":{x:-.236,y:.003,z:-.028},"RightHandIndex2.rotation":{x:.004,y:0,z:.001},"RightHandIndex3.rotation":{x:.002,y:0,z:0},"RightHandMiddle1.rotation":{x:-.236,y:.003,z:-.028},"RightHandMiddle2.rotation":{x:.004,y:0,z:.001},"RightHandMiddle3.rotation":{x:.002,y:0,z:0},"RightHandRing1.rotation":{x:-.236,y:.003,z:-.028},"RightHandRing2.rotation":{x:.004,y:0,z:.001},"RightHandRing3.rotation":{x:.002,y:0,z:0},"RightHandPinky1.rotation":{x:-.236,y:.003,z:-.028},"RightHandPinky2.rotation":{x:.004,y:0,z:.001},"RightHandPinky3.rotation":{x:.002,y:0,z:0},"LeftShoulder.rotation":{x:1.711,y:-.002,z:-1.625},"LeftArm.rotation":{x:.683,y:.334,z:.977},"LeftForeArm.rotation":{x:.086,y:-.066,z:1.843},"LeftHand.rotation":{x:-.595,y:-.229,z:.096},"LeftHandThumb1.rotation":{x:.404,y:-.05,z:.537},"LeftHandThumb2.rotation":{x:-.02,y:.004,z:-.154},"LeftHandThumb3.rotation":{x:-.049,y:.002,z:-.019},"LeftHandIndex1.rotation":{x:-.113,y:-.001,z:.014},"LeftHandIndex2.rotation":{x:.003,y:0,z:0},"LeftHandIndex3.rotation":{x:.002,y:0,z:0},"LeftHandMiddle1.rotation":{x:-.113,y:-.001,z:.014},"LeftHandMiddle2.rotation":{x:.004,y:0,z:0},"LeftHandMiddle3.rotation":{x:.002,y:0,z:0},"LeftHandRing1.rotation":{x:-.113,y:-.001,z:.014},"LeftHandRing2.rotation":{x:.003,y:0,z:0},"LeftHandRing3.rotation":{x:.002,y:0,z:0},"LeftHandPinky1.rotation":{x:-.122,y:-.001,z:-.057},"LeftHandPinky2.rotation":{x:.012,y:.001,z:.07},"LeftHandPinky3.rotation":{x:.002,y:0,z:0}}},this.poseDelta={props:{"Hips.quaternion":{x:0,y:0,z:0},"Spine.quaternion":{x:0,y:0,z:0},"Spine1.quaternion":{x:0,y:0,z:0},"Neck.quaternion":{x:0,y:0,z:0},"Head.quaternion":{x:0,y:0,z:0},"Spine1.scale":{x:0,y:0,z:0},"Neck.scale":{x:0,y:0,z:0},"LeftArm.scale":{x:0,y:0,z:0},"RightArm.scale":{x:0,y:0,z:0}}},["Left","Right"].forEach(l=>{["Leg","UpLeg","Arm","ForeArm","Hand"].forEach(h=>{this.poseDelta.props[l+h+".quaternion"]={x:0,y:0,z:0}}),["HandThumb","HandIndex","HandMiddle","HandRing","HandPinky"].forEach(h=>{this.poseDelta.props[l+h+"1.quaternion"]={x:0,y:0,z:0},this.poseDelta.props[l+h+"2.quaternion"]={x:0,y:0,z:0},this.poseDelta.props[l+h+"3.quaternion"]={x:0,y:0,z:0}})});const n=new Set;Object.values(this.poseTemplates).forEach(l=>{Object.keys(this.propsToThreeObjects(l.props)).forEach(h=>n.add(h))}),Object.keys(this.poseDelta.props).forEach(l=>{n.add(l)}),this.posePropNames=[...n],this.poseName="side",this.poseWeightOnLeft=!0,this.gesture=null,this.poseCurrentTemplate=this.poseTemplates[this.poseName],this.poseStraight=this.propsToThreeObjects(this.poseTemplates.straight.props),this.poseBase=this.poseFactory(this.poseCurrentTemplate),this.poseTarget=this.poseFactory(this.poseCurrentTemplate),this.poseAvatar=null,this.avatarHeight=1.7,this.animTemplateEyes={name:"eyes",idle:{alt:[{p:()=>this.avatar?.hasOwnProperty("avatarIdleEyeContact")?this.avatar.avatarIdleEyeContact:this.opt.avatarIdleEyeContact,delay:[200,5e3],dt:[200,[2e3,5e3],[3e3,1e4,1,2]],vs:{headMove:[this.avatar?.hasOwnProperty("avatarIdleHeadMove")?this.avatar.avatarIdleHeadMove:this.opt.avatarIdleHeadMove],eyesRotateY:[[-.6,.6]],eyesRotateX:[[-.2,.6]],eyeContact:[null,1]}},{delay:[200,5e3],dt:[200,[2e3,5e3,1,2]],vs:{headMove:[this.avatar?.hasOwnProperty("avatarIdleHeadMove")?this.avatar.avatarIdleHeadMove:this.opt.avatarIdleHeadMove],eyesRotateY:[[-.6,.6]],eyesRotateX:[[-.2,.6]]}}]},speaking:{alt:[{p:()=>this.avatar?.hasOwnProperty("avatarSpeakingEyeContact")?this.avatar.avatarSpeakingEyeContact:this.opt.avatarSpeakingEyeContact,delay:[200,5e3],dt:[0,[3e3,1e4,1,2],[2e3,5e3]],vs:{eyeContact:[1,null],headMove:[null,this.avatar?.hasOwnProperty("avatarSpeakingHeadMove")?this.avatar.avatarSpeakingHeadMove:this.opt.avatarSpeakingHeadMove,null],eyesRotateY:[null,[-.6,.6]],eyesRotateX:[null,[-.2,.6]]}},{delay:[200,5e3],dt:[200,[2e3,5e3,1,2]],vs:{headMove:[this.avatar?.hasOwnProperty("avatarSpeakingHeadMove")?this.avatar.avatarSpeakingHeadMove:this.opt.avatarSpeakingHeadMove,null],eyesRotateY:[[-.6,.6]],eyesRotateX:[[-.2,.6]]}}]}},this.animTemplateBlink={name:"blink",alt:[{p:.85,delay:[1e3,8e3,1,2],dt:[50,[100,300],100],vs:{eyeBlinkLeft:[1,1,0],eyeBlinkRight:[1,1,0]}},{delay:[1e3,4e3,1,2],dt:[50,[100,200],100,[10,400,0],50,[100,200],100],vs:{eyeBlinkLeft:[1,1,0,0,1,1,0],eyeBlinkRight:[1,1,0,0,1,1,0]}}]},this.animMoods={neutral:{baseline:{eyesLookDown:0},speech:{deltaRate:0,deltaPitch:0,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1200,500,1e3],vs:{chestInhale:[.5,.5,0]}},{name:"pose",alt:[{p:.5,delay:[5e3,3e4],vs:{pose:["side"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{p:.3,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{delay:[5e3,3e4],vs:{pose:["straight"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}}]},{name:"head",idle:{delay:[0,1e3],dt:[[200,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.3,.3]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},happy:{baseline:{mouthSmile:.2,eyesLookDown:0},speech:{deltaRate:0,deltaPitch:.1,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1200,500,1e3],vs:{chestInhale:[.5,.5,0]}},{name:"pose",idle:{alt:[{p:.6,delay:[5e3,3e4],vs:{pose:["side"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{p:.2,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{p:.1,delay:[5e3,3e4],vs:{pose:["straight"]}},{delay:[5e3,1e4],vs:{pose:["wide"]}},{delay:[1e3,3e3],vs:{pose:["turn"]}}]},speaking:{alt:[{p:.4,delay:[5e3,3e4],vs:{pose:["side"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{p:.4,delay:[5e3,3e4],vs:{pose:["straight"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{delay:[5e3,2e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}}]}},{name:"head",idle:{dt:[[1e3,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.3,.3]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthLeft:[[0,.3,2]],mouthSmile:[[0,.2,3]],mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},angry:{baseline:{eyesLookDown:.1,browDownLeft:.6,browDownRight:.6,jawForward:.3,mouthFrownLeft:.7,mouthFrownRight:.7,mouthRollLower:.2,mouthShrugLower:.3,handFistLeft:1,handFistRight:1},speech:{deltaRate:-.2,deltaPitch:.2,deltaVolume:0},anims:[{name:"breathing",delay:500,dt:[1e3,500,1e3],vs:{chestInhale:[.7,.7,0]}},{name:"pose",alt:[{p:.4,delay:[5e3,3e4],vs:{pose:["side"]}},{p:.4,delay:[5e3,3e4],vs:{pose:["straight"]}},{p:.2,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}}]},{name:"head",idle:{delay:[100,500],dt:[[200,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.2,.2]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},sad:{baseline:{eyesLookDown:.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},speech:{deltaRate:-.2,deltaPitch:-.2,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1e3,500,1e3],vs:{chestInhale:[.3,.3,0]}},{name:"pose",alt:[{p:.4,delay:[5e3,3e4],vs:{pose:["side"]}},{p:.4,delay:[5e3,3e4],vs:{pose:["straight"]}},{delay:[5e3,2e4],vs:{pose:["side"]},full:{delay:[5e3,2e4],vs:{pose:["oneknee"]}}}]},{name:"head",idle:{delay:[100,500],dt:[[200,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.2,.2]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},fear:{baseline:{browInnerUp:.7,eyeSquintLeft:.5,eyeSquintRight:.5,eyeWideLeft:.6,eyeWideRight:.6,mouthClose:.1,mouthFunnel:.3,mouthShrugLower:.5,mouthShrugUpper:.5},speech:{deltaRate:-.2,deltaPitch:0,deltaVolume:0},anims:[{name:"breathing",delay:500,dt:[1e3,500,1e3],vs:{chestInhale:[.7,.7,0]}},{name:"pose",alt:[{p:.8,delay:[5e3,3e4],vs:{pose:["side"]}},{delay:[5e3,3e4],vs:{pose:["straight"]}},{delay:[5e3,2e4],vs:{pose:["wide"]}},{delay:[5e3,2e4],vs:{pose:["side"]},full:{delay:[5e3,2e4],vs:{pose:["oneknee"]}}}]},{name:"head",idle:{delay:[100,500],dt:[[200,3e3]],vs:{bodyRotateX:[[-.06,.12]],bodyRotateY:[[-.7,.7]],bodyRotateZ:[[-.1,.1]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},disgust:{baseline:{browDownLeft:.7,browDownRight:.1,browInnerUp:.3,eyeSquintLeft:1,eyeSquintRight:1,eyeWideLeft:.5,eyeWideRight:.5,eyesRotateX:.05,mouthLeft:.4,mouthPressLeft:.3,mouthRollLower:.3,mouthShrugLower:.3,mouthShrugUpper:.8,mouthUpperUpLeft:.3,noseSneerLeft:1,noseSneerRight:.7},speech:{deltaRate:-.2,deltaPitch:0,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1e3,500,1e3],vs:{chestInhale:[.5,.5,0]}},{name:"pose",alt:[{delay:[5e3,2e4],vs:{pose:["side"]}}]},{name:"head",idle:{delay:[100,500],dt:[[200,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.2,.2]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},love:{baseline:{browInnerUp:.4,browOuterUpLeft:.2,browOuterUpRight:.2,mouthSmile:.2,eyeBlinkLeft:.6,eyeBlinkRight:.6,eyeWideLeft:.7,eyeWideRight:.7,bodyRotateX:.1,mouthDimpleLeft:.1,mouthDimpleRight:.1,mouthPressLeft:.2,mouthShrugUpper:.2,mouthUpperUpLeft:.1,mouthUpperUpRight:.1},speech:{deltaRate:-.1,deltaPitch:-.7,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1500,500,1500],vs:{chestInhale:[.8,.8,0]}},{name:"pose",alt:[{p:.4,delay:[5e3,3e4],vs:{pose:["side"]}},{p:.2,delay:[5e3,3e4],vs:{pose:["straight"]}},{p:.2,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["side"]}}},{delay:[5e3,1e4],vs:{pose:["side"]},full:{delay:[5e3,1e4],vs:{pose:["kneel"]}}},{delay:[1e3,3e3],vs:{pose:["turn"]},M:{delay:[1e3,3e3],vs:{pose:["wide"]}}},{delay:[1e3,3e3],vs:{pose:["back"]},M:{delay:[1e3,3e3],vs:{pose:["wide"]}}},{delay:[5e3,2e4],vs:{pose:["side"]},M:{delay:[5e3,2e4],vs:{pose:["side"]}},full:{delay:[5e3,2e4],vs:{pose:["bend"]}}},{delay:[1e3,3e3],vs:{pose:["side"]},full:{delay:[5e3,1e4],vs:{pose:["oneknee"]}}}]},{name:"head",idle:{dt:[[1e3,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.3,.3]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.deepCopy(this.animTemplateBlink,l=>{l.alt[0].delay[0]=l.alt[1].delay[0]=2e3}),{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthLeft:[[0,.3,2]],mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[500,1e3],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[.3,.6,2]],browOuterUpLeft:[[.1,.3,2]],browOuterUpRight:[[.1,.3,2]]}}]},sleep:{baseline:{eyeBlinkLeft:1,eyeBlinkRight:1,eyesClosed:.6},speech:{deltaRate:0,deltaPitch:-.2,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1e3,500,1e3],vs:{chestInhale:[.6,.6,0]}},{name:"pose",alt:[{delay:[5e3,2e4],vs:{pose:["side"]}}]},{name:"head",delay:[1e3,5e3],dt:[[2e3,1e4]],vs:{bodyRotateX:[[0,.4]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.04,.04]]}},{name:"eyes",delay:10010,dt:[],vs:{}},{name:"blink",delay:10020,dt:[],vs:{}},{name:"mouth",delay:10030,dt:[],vs:{}},{name:"misc",delay:10040,dt:[],vs:{}}]}},this.moodName=this.opt.avatarMood||"neutral",this.mood=this.animMoods[this.moodName],this.mood||(this.moodName="neutral",this.mood=this.animMoods.neutral),this.animEmojis={"😐":{dt:[300,2e3],rescale:[0,1],vs:{pose:["straight"],browInnerUp:[.4],eyeWideLeft:[.7],eyeWideRight:[.7],mouthPressLeft:[.6],mouthPressRight:[.6],mouthRollLower:[.3],mouthStretchLeft:[1],mouthStretchRight:[1]}},"😶":{link:"😐"},"😏":{dt:[300,2e3],rescale:[0,1],vs:{eyeContact:[0],browDownRight:[.1],browInnerUp:[.7],browOuterUpRight:[.2],eyeLookInRight:[.7],eyeLookOutLeft:[.7],eyeSquintLeft:[1],eyeSquintRight:[.8],eyesRotateY:[.7],mouthLeft:[.4],mouthPucker:[.4],mouthShrugLower:[.3],mouthShrugUpper:[.2],mouthSmile:[.2],mouthSmileLeft:[.4],mouthSmileRight:[.2],mouthStretchLeft:[.5],mouthUpperUpLeft:[.6],noseSneerLeft:[.7]}},"🙂":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5]}},"🙃":{link:"🙂"},"😊":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.6],eyeSquintLeft:[1],eyeSquintRight:[1],mouthSmile:[.7],noseSneerLeft:[.7],noseSneerRight:[.7]}},"😇":{link:"😊"},"😀":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.6],jawOpen:[.1],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthOpen:[.3],mouthPressLeft:[.3],mouthPressRight:[.3],mouthRollLower:[.4],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"😃":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.6],eyeWideLeft:[.7],eyeWideRight:[.7],jawOpen:[.1],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthOpen:[.3],mouthPressLeft:[.3],mouthPressRight:[.3],mouthRollLower:[.4],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"😄":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.3],eyeSquintLeft:[1],eyeSquintRight:[1],jawOpen:[.2],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthOpen:[.3],mouthPressLeft:[.3],mouthPressRight:[.3],mouthRollLower:[.4],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"😁":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.3],eyeSquintLeft:[1],eyeSquintRight:[1],jawOpen:[.3],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthPressLeft:[.5],mouthPressRight:[.5],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"😆":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.3],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.6],jawOpen:[.3],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthPressLeft:[.5],mouthPressRight:[.5],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"😝":{dt:[300,100,1500,500,500],rescale:[0,0,1,0,0],vs:{browInnerUp:[.8],eyesClosed:[1],jawOpen:[.7],mouthFunnel:[.5],mouthSmile:[1],tongueOut:[0,1,1,0]}},"😋":{link:"😝"},"😛":{link:"😝"},"😛":{link:"😝"},"😜":{link:"😝"},"🤪":{link:"😝"},"😂":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.3],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.6],jawOpen:[.3],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthPressLeft:[.5],mouthPressRight:[.5],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"🤣":{link:"😂"},"😅":{link:"😂"},"😉":{dt:[500,200,500,500],rescale:[0,0,0,1],vs:{mouthSmile:[.5],mouthOpen:[.2],mouthSmileLeft:[0,.5,0],eyeBlinkLeft:[0,.7,0],eyeBlinkRight:[0,0,0],bodyRotateX:[.05,.05,.05,0],bodyRotateZ:[-.05,-.05,-.05,0],browDownLeft:[0,.7,0],cheekSquintLeft:[0,.7,0],eyeSquintLeft:[0,1,0],eyesClosed:[0]}},"😭":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[1],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.1],jawOpen:[0],mouthFrownLeft:[1],mouthFrownRight:[1],mouthOpen:[.5],mouthPucker:[.5],mouthUpperUpLeft:[.6],mouthUpperUpRight:[.6]}},"🥺":{dt:[1e3,1e3],rescale:[0,1],vs:{browDownLeft:[.2],browDownRight:[.2],browInnerUp:[1],eyeWideLeft:[.9],eyeWideRight:[.9],eyesClosed:[.1],mouthClose:[.2],mouthFrownLeft:[1],mouthFrownRight:[1],mouthPressLeft:[.4],mouthPressRight:[.4],mouthPucker:[1],mouthRollLower:[.6],mouthRollUpper:[.2],mouthUpperUpLeft:[.8],mouthUpperUpRight:[.8]}},"😞":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[.7],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.5],bodyRotateX:[.3],mouthClose:[.2],mouthFrownLeft:[1],mouthFrownRight:[1],mouthPucker:[1],mouthRollLower:[1],mouthShrugLower:[.2],mouthUpperUpLeft:[.8],mouthUpperUpRight:[.8]}},"😔":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[1],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.5],bodyRotateX:[.3],mouthClose:[.2],mouthFrownLeft:[1],mouthFrownRight:[1],mouthPressLeft:[.4],mouthPressRight:[.4],mouthPucker:[1],mouthRollLower:[.6],mouthRollUpper:[.2],mouthUpperUpLeft:[.8],mouthUpperUpRight:[.8]}},"😳":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[1],eyeWideLeft:[.5],eyeWideRight:[.5],eyesRotateY:[.05],eyesRotateX:[.05],mouthClose:[.2],mouthFunnel:[.5],mouthPucker:[.4],mouthRollLower:[.4],mouthRollUpper:[.4]}},"☹️":{dt:[500,1500],rescale:[0,1],vs:{mouthFrownLeft:[1],mouthFrownRight:[1],mouthPucker:[.1],mouthRollLower:[.8]}},"😚":{dt:[500,1e3,1e3],rescale:[0,1,0],vs:{browInnerUp:[.6],eyeBlinkLeft:[1],eyeBlinkRight:[1],eyeSquintLeft:[1],eyeSquintRight:[1],mouthPucker:[0,.5],noseSneerLeft:[0,.7],noseSneerRight:[0,.7],viseme_U:[0,1]}},"😘":{dt:[500,500,200,500],rescale:[0,0,0,1],vs:{browInnerUp:[.6],eyeBlinkLeft:[0,0,1,0],eyeBlinkRight:[0],eyesRotateY:[0],bodyRotateY:[0],bodyRotateX:[0,.05,.05,0],bodyRotateZ:[0,-.05,-.05,0],eyeSquintLeft:[1],eyeSquintRight:[1],mouthPucker:[0,.5,0],noseSneerLeft:[0,.7],noseSneerRight:[.7],viseme_U:[0,1]}},"🥰":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[.6],eyeSquintLeft:[1],eyeSquintRight:[1],mouthSmile:[.7],noseSneerLeft:[.7],noseSneerRight:[.7]}},"😍":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[.6],jawOpen:[.1],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthOpen:[.3],mouthPressLeft:[.3],mouthPressRight:[.3],mouthRollLower:[.4],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"🤩":{link:"😍"},"😡":{dt:[1e3,1500],rescale:[0,1],vs:{browDownLeft:[1],browDownRight:[1],eyesLookUp:[.2],jawForward:[.3],mouthFrownLeft:[1],mouthFrownRight:[1],bodyRotateX:[.15]}},"😠":{dt:[1e3,1500],rescale:[0,1],vs:{browDownLeft:[1],browDownRight:[1],eyesLookUp:[.2],jawForward:[.3],mouthFrownLeft:[1],mouthFrownRight:[1],bodyRotateX:[.15]}},"🤬":{link:"😠"},"😒":{dt:[1e3,1e3],rescale:[0,1],vs:{eyeContact:[0],browDownRight:[.1],browInnerUp:[.7],browOuterUpRight:[.2],eyeLookInRight:[.7],eyeLookOutLeft:[.7],eyeSquintLeft:[1],eyeSquintRight:[.8],eyesRotateY:[.7],mouthFrownLeft:[1],mouthFrownRight:[1],mouthLeft:[.2],mouthPucker:[.5],mouthRollLower:[.2],mouthRollUpper:[.2],mouthShrugLower:[.2],mouthShrugUpper:[.2],mouthStretchLeft:[.5]}},"😱":{dt:[500,1500],rescale:[0,1],vs:{browInnerUp:[.8],eyeWideLeft:[.5],eyeWideRight:[.5],jawOpen:[.7],mouthFunnel:[.5]}},"😬":{dt:[500,1500],rescale:[0,1],vs:{browDownLeft:[1],browDownRight:[1],browInnerUp:[1],mouthDimpleLeft:[.5],mouthDimpleRight:[.5],mouthLowerDownLeft:[1],mouthLowerDownRight:[1],mouthPressLeft:[.4],mouthPressRight:[.4],mouthPucker:[.5],mouthSmile:[.1],mouthSmileLeft:[.2],mouthSmileRight:[.2],mouthStretchLeft:[1],mouthStretchRight:[1],mouthUpperUpLeft:[1],mouthUpperUpRight:[1]}},"🙄":{dt:[500,1500],rescale:[0,1],vs:{browInnerUp:[.8],eyeWideLeft:[1],eyeWideRight:[1],eyesRotateX:[-.8],bodyRotateX:[.15],mouthPucker:[.5],mouthRollLower:[.6],mouthRollUpper:[.5],mouthShrugLower:[0],mouthSmile:[0]}},"🤔":{dt:[500,1500],rescale:[0,1],vs:{browDownLeft:[1],browOuterUpRight:[1],eyeSquintLeft:[.6],mouthFrownLeft:[.7],mouthFrownRight:[.7],mouthLowerDownLeft:[.3],mouthPressRight:[.4],mouthPucker:[.1],mouthRight:[.5],mouthRollLower:[.5],mouthRollUpper:[.2],handRight:[{x:.1,y:.1,z:.1,d:1e3},{d:1e3}],handFistRight:[.1]}},"👀":{dt:[500,1500],rescale:[0,1],vs:{eyesRotateY:[-.8]}},"😴":{dt:[5e3,5e3],rescale:[0,1],vs:{eyeBlinkLeft:[1],eyeBlinkRight:[1],bodyRotateX:[.2],bodyRotateZ:[.1]}},"✋":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5],gesture:[["handup",2,!0],null]}},"🤚":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5],gesture:[["handup",2],null]}},"👋":{link:"✋"},"👍":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5],gesture:[["thumbup",2],null]}},"👎":{dt:[300,2e3],rescale:[0,1],vs:{browDownLeft:[1],browDownRight:[1],eyesLookUp:[.2],jawForward:[.3],mouthFrownLeft:[1],mouthFrownRight:[1],bodyRotateX:[.15],gesture:[["thumbdown",2],null]}},"👌":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5],gesture:[["ok",2],null]}},"🤷‍♂️":{dt:[1e3,1500],rescale:[0,1],vs:{gesture:[["shrug",2],null]}},"🤷‍♀️":{link:"🤷‍♂️"},"🤷":{link:"🤷‍♂️"},"🙏":{dt:[1500,300,1e3],rescale:[0,1,0],vs:{eyeBlinkLeft:[0,1],eyeBlinkRight:[0,1],bodyRotateX:[0],bodyRotateZ:[.1],gesture:[["namaste",2],null]}},yes:{dt:[[200,500],[200,500],[200,500],[200,500]],vs:{headMove:[0],headRotateX:[[.1,.2],.1,[.1,.2],0],headRotateZ:[[-.2,.2]]}},no:{dt:[[200,500],[200,500],[200,500],[200,500],[200,500]],vs:{headMove:[0],headRotateY:[[-.1,-.05],[.05,.1],[-.1,-.05],[.05,.1],0],headRotateZ:[[-.2,.2]]}}},this.mtAvatar={},this.mtCustoms=["handFistLeft","handFistRight","bodyRotateX","bodyRotateY","bodyRotateZ","headRotateX","headRotateY","headRotateZ","chestInhale"],this.mtEasingDefault=this.sigmoidFactory(5),this.mtAccDefault=.01,this.mtAccExceptions={eyeBlinkLeft:.1,eyeBlinkRight:.1,eyeLookOutLeft:.1,eyeLookInLeft:.1,eyeLookOutRight:.1,eyeLookInRight:.1},this.mtMaxVDefault=5,this.mtMaxVExceptions={bodyRotateX:1,bodyRotateY:1,bodyRotateZ:1},this.mtBaselineDefault=0,this.mtBaselineExceptions={bodyRotateX:null,bodyRotateY:null,bodyRotateZ:null,eyeLookOutLeft:null,eyeLookInLeft:null,eyeLookOutRight:null,eyeLookInRight:null,eyesLookDown:null,eyesLookUp:null},this.mtMinDefault=0,this.mtMinExceptions={bodyRotateX:-1,bodyRotateY:-1,bodyRotateZ:-1,headRotateX:-1,headRotateY:-1,headRotateZ:-1},this.mtMaxDefault=1,this.mtMaxExceptions={},this.mtLimits={eyeBlinkLeft:l=>Math.max(l,(this.mtAvatar.eyesLookDown.value+this.mtAvatar.browDownLeft.value)/2),eyeBlinkRight:l=>Math.max(l,(this.mtAvatar.eyesLookDown.value+this.mtAvatar.browDownRight.value)/2)},this.mtOnchange={eyesLookDown:()=>{this.mtAvatar.eyeBlinkLeft.needsUpdate=!0,this.mtAvatar.eyeBlinkRight.needsUpdate=!0},browDownLeft:()=>{this.mtAvatar.eyeBlinkLeft.needsUpdate=!0},browDownRight:()=>{this.mtAvatar.eyeBlinkRight.needsUpdate=!0}},this.mtRandomized=["mouthDimpleLeft","mouthDimpleRight","mouthLeft","mouthPressLeft","mouthPressRight","mouthStretchLeft","mouthStretchRight","mouthShrugLower","mouthShrugUpper","noseSneerLeft","noseSneerRight","mouthRollLower","mouthRollUpper","browDownLeft","browDownRight","browOuterUpLeft","browOuterUpRight","cheekPuff","cheekSquintLeft","cheekSquintRight"],this.mtExtras=[{key:"mouthOpen",mix:{jawOpen:.5}},{key:"mouthSmile",mix:{mouthSmileLeft:.8,mouthSmileRight:.8}},{key:"eyesClosed",mix:{eyeBlinkLeft:1,eyeBlinkRight:1}},{key:"eyesLookUp",mix:{eyeLookUpLeft:1,eyeLookUpRight:1}},{key:"eyesLookDown",mix:{eyeLookDownLeft:1,eyeLookDownRight:1}}],this.animQueue=[],this.animClips=[],this.animPoses=[],this.animFrameDur=1e3/this.opt.modelFPS,this.animClock=0,this.animSlowdownRate=1,this.animTimeLast=0,this.easing=this.sigmoidFactory(5),this.lipsync={},this.opt.lipsyncModules.forEach(l=>{this.lipsyncGetProcessor(l)}),this.visemeNames=["aa","E","I","O","U","PP","SS","TH","DD","FF","kk","nn","RR","CH","sil"],this.segmenter=new Intl.Segmenter("en",{granularity:"grapheme"}),this.initAudioGraph(),this.audioPlaylist=[],this.volumeFrequencyData=new Uint8Array(16),this.volumeMax=0,this.volumeHeadBase=0,this.volumeHeadTarget=0,this.volumeHeadCurrent=0,this.volumeHeadVelocity=.15,this.volumeHeadEasing=this.sigmoidFactory(3),this.isListening=!1,this.listeningAnalyzer=null,this.listeningActive=!1,this.listeningVolume=0,this.listeningSilenceThresholdLevel=this.opt.listeningSilenceThresholdLevel,this.listeningSilenceThresholdMs=this.opt.listeningSilenceThresholdMs,this.listeningSilenceDurationMax=this.opt.listeningSilenceDurationMax,this.listeningActiveThresholdLevel=this.opt.listeningActiveThresholdLevel,this.listeningActiveThresholdMs=this.opt.listeningActiveThresholdMs,this.listeningActiveDurationMax=this.opt.listeningActiveDurationMax,this.listeningTimer=0,this.listeningTimerTotal=0,this.dracoEnabled=this.opt.dracoEnabled,this.dracoDecoderPath=this.opt.dracoDecoderPath;const i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";this.b64Lookup=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let l=0;l<i.length;l++)this.b64Lookup[i.charCodeAt(l)]=l;if(this.stateName="idle",this.speechQueue=[],this.isSpeaking=!1,this.isListening=!1,this.opt.ttsEndpoint){let l=new Audio;if(l.canPlayType("audio/ogg"))this.ttsAudioEncoding="OGG-OPUS";else if(l.canPlayType("audio/mp3"))this.ttsAudioEncoding="MP3";else throw new Error("There was no support for either OGG or MP3 audio.")}if(this.isAvatarOnly=this.opt.avatarOnly,this.isAvatarOnly)this.scene=this.opt.avatarOnlyScene,this.camera=this.opt.avatarOnlyCamera;else{this.renderer=new f.WebGLRenderer({antialias:!0,alpha:!0}),this.renderer.setPixelRatio(this.opt.modelPixelRatio*window.devicePixelRatio),this.renderer.setSize(this.nodeAvatar.clientWidth,this.nodeAvatar.clientHeight),this.renderer.outputColorSpace=f.SRGBColorSpace,this.renderer.toneMapping=f.ACESFilmicToneMapping,this.renderer.shadowMap.enabled=!1,this.nodeAvatar.appendChild(this.renderer.domElement),this.camera=new f.PerspectiveCamera(10,this.nodeAvatar.clientWidth/this.nodeAvatar.clientHeight,.1,2e3),this.scene=new f.Scene,this.lightAmbient=new f.AmbientLight(new f.Color(this.opt.lightAmbientColor),this.opt.lightAmbientIntensity),this.lightDirect=new f.DirectionalLight(new f.Color(this.opt.lightDirectColor),this.opt.lightDirectIntensity),this.lightSpot=new f.SpotLight(new f.Color(this.opt.lightSpotColor),this.opt.lightSpotIntensity,0,this.opt.lightSpotDispersion),this.setLighting(this.opt);const l=new f.PMREMGenerator(this.renderer);l.compileEquirectangularShader(),this.scene.environment=l.fromScene(new Ye.RoomEnvironment).texture,this.resizeobserver=new ResizeObserver(this.onResize.bind(this)),this.resizeobserver.observe(this.nodeAvatar),this.controls=new Ze.OrbitControls(this.camera,this.renderer.domElement),this.controls.enableZoom=this.opt.cameraZoomEnable,this.controls.enableRotate=this.opt.cameraRotateEnable,this.controls.enablePan=this.opt.cameraPanEnable,this.controls.minDistance=2,this.controls.maxDistance=2e3,this.controls.autoRotateSpeed=0,this.controls.autoRotate=!1,this.controls.update(),this.cameraClock=null}this.ikMesh=new f.SkinnedMesh;const s={LeftShoulder:null,LeftArm:"LeftShoulder",LeftForeArm:"LeftArm",LeftHand:"LeftForeArm",LeftHandMiddle1:"LeftHand",RightShoulder:null,RightArm:"RightShoulder",RightForeArm:"RightArm",RightHand:"RightForeArm",RightHandMiddle1:"RightHand"},o=[];Object.entries(s).forEach((l,h)=>{const r=new f.Bone;r.name=l[0],l[1]?this.ikMesh.getObjectByName(l[1]).add(r):this.ikMesh.add(r),o.push(r)}),this.ikMesh.bind(new f.Skeleton(o)),this.dynamicbones=new $e,this.isStreaming=!1,this.streamWorkletNode=null,this.streamAudioStartTime=null,this.streamWaitForAudioChunks=!0,this.streamLipsyncLang=null,this.streamLipsyncType="visemes",this.streamLipsyncQueue=[]}initAudioGraph(t=null){if(this.audioCtx&&this.audioCtx.state!=="closed"&&this.audioCtx.close(),t?this.audioCtx=new AudioContext({sampleRate:t}):this.audioCtx=new AudioContext,this.audioSpeechSource=this.audioCtx.createBufferSource(),this.audioBackgroundSource=this.audioCtx.createBufferSource(),this.audioBackgroundGainNode=this.audioCtx.createGain(),this.audioSpeechGainNode=this.audioCtx.createGain(),this.audioStreamGainNode=this.audioCtx.createGain(),this.audioAnalyzerNode=this.audioCtx.createAnalyser(),this.audioAnalyzerNode.fftSize=256,this.audioAnalyzerNode.smoothingTimeConstant=.1,this.audioAnalyzerNode.minDecibels=-70,this.audioAnalyzerNode.maxDecibels=-10,this.audioAnalyzer=new et(this.audioCtx),this.audioReverbNode=this.audioCtx.createConvolver(),this.audioBackgroundGainNode.connect(this.audioReverbNode),this.audioAnalyzerNode.connect(this.audioSpeechGainNode),this.audioSpeechGainNode.connect(this.audioReverbNode),this.audioStreamGainNode.connect(this.audioReverbNode),this.audioReverbNode.connect(this.audioCtx.destination),this.setReverb(this.currentReverb||null),this.setMixerGain(this.opt.mixerGainSpeech,this.opt.mixerGainBackground),this.workletLoaded=!1,this.streamWorkletNode){try{this.streamWorkletNode.port.postMessage({type:"stop"}),this.streamWorkletNode.disconnect(),this.isStreaming=!1}catch(e){console.error("Error disconnecting streamWorkletNode:",e)}this.streamWorkletNode=null}}valueFn(t){return typeof t=="function"?t():t}deepCopy(t,e=null){const n=JSON.parse(JSON.stringify(t));return e&&typeof e=="function"&&e(n),n}b64ToArrayBuffer(t){let e=3*t.length/4;t[t.length-1]==="="&&(e--,t[t.length-2]==="="&&e--);const n=new ArrayBuffer(e),i=new Uint8Array(n);let s,o=0,l,h,r,u;for(s=0;s<t.length;s+=4)l=this.b64Lookup[t.charCodeAt(s)],h=this.b64Lookup[t.charCodeAt(s+1)],r=this.b64Lookup[t.charCodeAt(s+2)],u=this.b64Lookup[t.charCodeAt(s+3)],i[o++]=l<<2|h>>4,i[o++]=(h&15)<<4|r>>2,i[o++]=(r&3)<<6|u&63;return n}concatArrayBuffers(t){if(t.length===1)return t[0];let e=0;for(let o=0;o<t.length;o++)e+=t[o].byteLength;let n=new ArrayBuffer(e),i=new Uint8Array(n),s=0;for(let o=0;o<t.length;o++)i.set(new Uint8Array(t[o]),s),s+=t[o].byteLength;return n}pcmToAudioBuffer(t){const e=new Int16Array(t),n=new Float32Array(e.length);for(let s=0;s<e.length;s++)n[s]=e[s]>=32768?-(65536-e[s])/32768:e[s]/32767;const i=this.audioCtx.createBuffer(1,n.length,this.opt.pcmSampleRate);return i.copyToChannel(n,0,0),i}propsToThreeObjects(t){const e={};for(let[n,i]of Object.entries(t)){const s=n.split(".");let o=Array.isArray(i.x)?this.gaussianRandom(...i.x):i.x,l=Array.isArray(i.y)?this.gaussianRandom(...i.y):i.y,h=Array.isArray(i.z)?this.gaussianRandom(...i.z):i.z;s[1]==="position"||s[1]==="scale"?e[n]=new f.Vector3(o,l,h):s[1]==="rotation"?(n=s[0]+".quaternion",e[n]=new f.Quaternion().setFromEuler(new f.Euler(o,l,h,"XYZ")).normalize()):s[1]==="quaternion"&&(e[n]=new f.Quaternion(o,l,h,i.w).normalize())}return e}clearThree(t){for(;t.children.length;)this.clearThree(t.children[0]),t.remove(t.children[0]);t.geometry&&t.geometry.dispose(),t.material&&(Object.keys(t.material).forEach(e=>{t.material[e]&&t.material[e]!==null&&typeof t.material[e].dispose=="function"&&t.material[e].dispose()}),t.material.dispose())}addMixedMorphTarget(t,e,n,i=!1){t.forEach(s=>{if(!i&&s.morphTargetDictionary.hasOwnProperty(e))return;const o=s.geometry;let l=null,h=null;for(const[r,u]of Object.entries(n))if(s.morphTargetDictionary.hasOwnProperty(r)){const a=s.morphTargetDictionary[r],d=o.morphAttributes.position[a],c=o.morphAttributes.normal?.[a];l||(l=new f.Float32BufferAttribute(d.count*3,3),c&&(h=new f.Float32BufferAttribute(d.count*3,3)));for(let g=0;g<d.count;g++){const b=l.getX(g)+d.getX(g)*u,x=l.getY(g)+d.getY(g)*u,S=l.getZ(g)+d.getZ(g)*u;l.setXYZ(g,b,x,S)}if(c)for(let g=0;g<d.count;g++){const b=h.getX(g)+c.getX(g)*u,x=h.getY(g)+c.getY(g)*u,S=h.getZ(g)+c.getZ(g)*u;h.setXYZ(g,b,x,S)}}if(l){o.morphAttributes.position.push(l),h&&o.morphAttributes.normal.push(h);const r=o.morphAttributes.position.length-1;s.morphTargetInfluences[r]=0,s.morphTargetDictionary[e]=r}})}async showAvatar(t,e=null){if(!t||!t.hasOwnProperty("url"))throw new Error("Invalid parameter. The avatar must have at least 'url' specified.");const n=new Xe.GLTFLoader;if(this.dracoEnabled){const r=new je.DRACOLoader;r.setDecoderPath(this.dracoDecoderPath),n.setDRACOLoader(r)}let i=await n.loadAsync(t.url,e);const s=[this.opt.modelRoot];if(this.posePropNames.forEach(r=>s.push(r.split(".")[0])),s.forEach(r=>{if(!i.scene.getObjectByName(r))throw new Error("Avatar object "+r+" not found")}),this.stop(),this.avatar=t,this.bodyMovement=t.bodyMovement||"idle",this.movementIntensity=t.movementIntensity||.5,this.showFullAvatar=t.showFullAvatar||!1,this.fbxAnimationLoader=null,this.dynamicbones.dispose(),this.mixer=null,this.isAvatarOnly?this.armature&&this.clearThree(this.armature):this.armature&&this.clearThree(this.scene),this.armature=i.scene.getObjectByName(this.opt.modelRoot),this.armature.scale.setScalar(1),this.animations=i.animations,this.userData=i.userData,this.morphs=[],this.armature.traverse(r=>{r.morphTargetInfluences&&r.morphTargetInfluences.length&&r.morphTargetDictionary&&this.morphs.push(r),r.frustumCulled=!1}),this.morphs.length===0)throw new Error("Blend shapes not found");const o=new Set(this.mtCustoms);this.morphs.forEach(r=>{Object.keys(r.morphTargetDictionary).forEach(u=>o.add(u))}),this.mtExtras.forEach(r=>{o.has(r.key)||(this.addMixedMorphTarget(this.morphs,r.key,r.mix),o.add(r.key))});const l={};if(o.forEach(r=>{l[r]={fixed:null,realtime:null,system:null,systemd:null,newvalue:null,ref:null,min:this.mtMinExceptions.hasOwnProperty(r)?this.mtMinExceptions[r]:this.mtMinDefault,max:this.mtMaxExceptions.hasOwnProperty(r)?this.mtMaxExceptions[r]:this.mtMaxDefault,easing:this.mtEasingDefault,base:null,v:0,needsUpdate:!0,acc:(this.mtAccExceptions.hasOwnProperty(r)?this.mtAccExceptions[r]:this.mtAccDefault)/1e3,maxv:(this.mtMaxVExceptions.hasOwnProperty(r)?this.mtMaxVExceptions[r]:this.mtMaxVDefault)/1e3,limit:this.mtLimits.hasOwnProperty(r)?this.mtLimits[r]:null,onchange:this.mtOnchange.hasOwnProperty(r)?this.mtOnchange[r]:null,baseline:this.avatar.baseline?.hasOwnProperty(r)?this.avatar.baseline[r]:this.mtBaselineExceptions.hasOwnProperty(r)?this.mtBaselineExceptions[r]:this.mtBaselineDefault,ms:[],is:[]},l[r].value=l[r].baseline,l[r].applied=l[r].baseline;const u=this.mtAvatar[r];u&&["fixed","system","systemd","realtime","base","v","value","applied"].forEach(a=>{l[r][a]=u[a]}),this.morphs.forEach(a=>{const d=a.morphTargetDictionary[r];d!==void 0&&(l[r].ms.push(a.morphTargetInfluences),l[r].is.push(d),a.morphTargetInfluences[d]=l[r].applied)})}),this.mtAvatar=l,this.poseAvatar={props:{}},this.posePropNames.forEach(r=>{const u=r.split("."),a=this.armature.getObjectByName(u[0]);this.poseAvatar.props[r]=a[u[1]],this.poseBase.props.hasOwnProperty(r)?this.poseAvatar.props[r].copy(this.poseBase.props[r]):this.poseBase.props[r]=this.poseAvatar.props[r].clone(),this.poseDelta.props.hasOwnProperty(r)&&!this.poseTarget.props.hasOwnProperty(r)&&(this.poseTarget.props[r]=this.poseAvatar.props[r].clone()),this.poseTarget.props[r].t=this.animClock,this.poseTarget.props[r].d=2e3}),this.ikMesh.traverse(r=>{r.isBone&&r.position.copy(this.armature.getObjectByName(r.name).position)}),this.isAvatarOnly?this.scene&&this.scene.add(this.armature):(this.scene.add(i.scene),this.scene.add(this.lightAmbient),this.scene.add(this.lightDirect),this.scene.add(this.lightSpot),this.lightSpot.target=this.armature.getObjectByName("Head")),t.hasOwnProperty("modelDynamicBones"))try{this.dynamicbones.setup(this.scene,this.armature,t.modelDynamicBones)}catch(r){console.error("Dynamic bones setup failed: "+r)}this.objectLeftToeBase=this.armature.getObjectByName("LeftToeBase"),this.objectRightToeBase=this.armature.getObjectByName("RightToeBase"),this.objectLeftEye=this.armature.getObjectByName("LeftEye"),this.objectRightEye=this.armature.getObjectByName("RightEye"),this.objectLeftArm=this.armature.getObjectByName("LeftArm"),this.objectRightArm=this.armature.getObjectByName("RightArm"),this.objectHips=this.armature.getObjectByName("Hips"),this.objectHead=this.armature.getObjectByName("Head"),this.objectNeck=this.armature.getObjectByName("Neck");const h=new f.Vector3;this.objectLeftEye.getWorldPosition(h),this.avatarHeight=h.y+.2,this.viewName||this.setView(this.opt.cameraView),this.setMood(this.avatar.avatarMood||this.moodName||this.opt.avatarMood),this.avatar.body==="M"&&this.poseTemplates.wide&&(this.poseName="wide",this.setPoseFromTemplate(this.poseTemplates.wide,0),console.log("Set initial male-appropriate pose: wide")),this.initializeFBXAnimationLoader(),this.bodyMovement&&this.bodyMovement!=="idle"&&this.applyBodyMovementAnimation(),this.start()}getViewNames(){return["full","mid","upper","head"]}getView(){return this.viewName}setView(t,e=null){if(t=t||this.viewName,t!=="full"&&t!=="upper"&&t!=="head"&&t!=="mid")return;if(!this.armature){this.opt.cameraView=t;return}if(this.viewName=t||this.viewName,e=e||{},this.isAvatarOnly)return;const n=e.hasOwnProperty("cameraX")?e.cameraX:this.opt.cameraX,i=e.hasOwnProperty("cameraY")?e.cameraY:this.opt.cameraY,s=e.hasOwnProperty("cameraDistance")?e.cameraDistance:this.opt.cameraDistance,o=e.hasOwnProperty("cameraRotateX")?e.cameraRotateX:this.opt.cameraRotateX,l=e.hasOwnProperty("cameraRotateY")?e.cameraRotateY:this.opt.cameraRotateY,h=this.camera.fov*(Math.PI/180);let r=-n*Math.tan(h/2),u=(1-i)*Math.tan(h/2),a=s;switch(this.viewName){case"head":a+=2,u=u*a+4*this.avatarHeight/5;break;case"upper":a+=4.5,u=u*a+2*this.avatarHeight/3;break;case"mid":a+=8,u=u*a+this.avatarHeight/3;break;default:a+=12,u=u*a}r=r*a,this.controlsEnd=new f.Vector3(r,u,0),this.cameraEnd=new f.Vector3(r,u,a).applyEuler(new f.Euler(o,l,0)),this.cameraClock===null&&(this.controls.target.copy(this.controlsEnd),this.camera.position.copy(this.cameraEnd)),this.controlsStart=this.controls.target.clone(),this.cameraStart=this.camera.position.clone(),this.cameraClock=0}setLighting(t){this.isAvatarOnly||(t=t||{},t.hasOwnProperty("lightAmbientColor")&&this.lightAmbient.color.set(new f.Color(t.lightAmbientColor)),t.hasOwnProperty("lightAmbientIntensity")&&(this.lightAmbient.intensity=t.lightAmbientIntensity,this.lightAmbient.visible=t.lightAmbientIntensity!==0),t.hasOwnProperty("lightDirectColor")&&this.lightDirect.color.set(new f.Color(t.lightDirectColor)),t.hasOwnProperty("lightDirectIntensity")&&(this.lightDirect.intensity=t.lightDirectIntensity,this.lightDirect.visible=t.lightDirectIntensity!==0),t.hasOwnProperty("lightDirectPhi")&&t.hasOwnProperty("lightDirectTheta")&&this.lightDirect.position.setFromSphericalCoords(2,t.lightDirectPhi,t.lightDirectTheta),t.hasOwnProperty("lightSpotColor")&&this.lightSpot.color.set(new f.Color(t.lightSpotColor)),t.hasOwnProperty("lightSpotIntensity")&&(this.lightSpot.intensity=t.lightSpotIntensity,this.lightSpot.visible=t.lightSpotIntensity!==0),t.hasOwnProperty("lightSpotPhi")&&t.hasOwnProperty("lightSpotTheta")&&(this.lightSpot.position.setFromSphericalCoords(2,t.lightSpotPhi,t.lightSpotTheta),this.lightSpot.position.add(new f.Vector3(0,1.5,0))),t.hasOwnProperty("lightSpotDispersion")&&(this.lightSpot.angle=t.lightSpotDispersion))}render(){this.isRunning&&!this.isAvatarOnly&&this.renderer&&this.renderer.render(this.scene,this.camera)}onResize(){!this.isAvatarOnly&&this.renderer&&(this.camera.aspect=this.nodeAvatar.clientWidth/this.nodeAvatar.clientHeight,this.camera.updateProjectionMatrix(),this.renderer.setSize(this.nodeAvatar.clientWidth,this.nodeAvatar.clientHeight),this.controls.update(),this.render())}updatePoseBase(t){for(const[e,n]of Object.entries(this.poseTarget.props)){const i=this.poseAvatar.props[e];if(i){let s=(t-n.t)/n.d;s>1||!this.poseBase.props.hasOwnProperty(e)?i.copy(n):i.isQuaternion?i.copy(this.poseBase.props[e].slerp(n,this.easing(s))):i.isVector3&&i.copy(this.poseBase.props[e].lerp(n,this.easing(s)))}}}updatePoseDelta(){for(const[t,e]of Object.entries(this.poseDelta.props)){if(e.x===0&&e.y===0&&e.z===0)continue;Z.set(e.x,e.y,e.z);const n=this.poseAvatar.props[t];n.isQuaternion?(q.setFromEuler(Z),n.multiply(q)):n.isVector3&&n.add(Z)}}updateMorphTargets(t){for(let[e,n]of Object.entries(this.mtAvatar)){if(!n.needsUpdate)continue;let i=null,s=null;if(n.fixed!==null){if(i=n.fixed,n.system=null,n.systemd=null,n.newvalue=null,n.ref&&n.ref.hasOwnProperty(e)&&delete n.ref[e],n.ref=null,n.base=null,n.value===i){n.needsUpdate=!1;continue}}else n.realtime!==null?(n.ref=null,n.base=null,s=n.realtime):n.system!==null?(i=n.system,n.newvalue=null,n.ref&&n.ref.hasOwnProperty(e)&&delete n.ref[e],n.ref=null,n.base=null,n.systemd!==null?n.systemd===0?(i=null,n.system=null,n.systemd=null):(n.systemd-=t,n.systemd<0&&(n.systemd=0),n.value===i&&(i=null)):n.value===i&&(i=null,n.system=null)):n.newvalue!==null?(n.ref=null,n.base=null,s=n.newvalue,n.newvalue=null):n.base!==null?(i=n.base,n.ref=null,n.value===i&&(i=null,n.base=null,n.needsUpdate=!1)):(n.ref=null,n.baseline!==null&&n.value!==n.baseline?(i=n.baseline,n.base=n.baseline):n.needsUpdate=!1);if(i!==null){let o=i-n.value;o>=0?o<.005?(s=i,n.v=0):(n.v<n.maxv&&(n.v+=n.acc*t),n.v>=0?s=n.value+o*(1-Math.exp(-n.v*t)):s=n.value+n.v*t*(1-Math.exp(n.v*t))):o>-.005?(s=i,n.v=0):(n.v>-n.maxv&&(n.v-=n.acc*t),n.v>=0?s=n.value+n.v*t*(1-Math.exp(-n.v*t)):s=n.value+o*(1-Math.exp(n.v*t)))}if(n.limit!==null){if(s!==null&&s!==n.value&&(n.value=s,n.onchange!==null&&n.onchange(s)),s=n.limit(n.value),s===n.applied)continue}else{if(s===null||s===n.value)continue;n.value=s,n.onchange!==null&&n.onchange(s)}switch(n.applied=s,n.applied<n.min&&(n.applied=n.min),n.applied>n.max&&(n.applied=n.max),e){case"headRotateX":this.poseDelta.props["Head.quaternion"].x=n.applied+this.mtAvatar.bodyRotateX.applied;break;case"headRotateY":this.poseDelta.props["Head.quaternion"].y=n.applied+this.mtAvatar.bodyRotateY.applied;break;case"headRotateZ":this.poseDelta.props["Head.quaternion"].z=n.applied+this.mtAvatar.bodyRotateZ.applied;break;case"bodyRotateX":this.poseDelta.props["Head.quaternion"].x=n.applied+this.mtAvatar.headRotateX.applied,this.poseDelta.props["Spine1.quaternion"].x=n.applied/2,this.poseDelta.props["Spine.quaternion"].x=n.applied/8,this.poseDelta.props["Hips.quaternion"].x=n.applied/24;break;case"bodyRotateY":this.poseDelta.props["Head.quaternion"].y=n.applied+this.mtAvatar.headRotateY.applied,this.poseDelta.props["Spine1.quaternion"].y=n.applied/2,this.poseDelta.props["Spine.quaternion"].y=n.applied/2,this.poseDelta.props["Hips.quaternion"].y=n.applied/4,this.poseDelta.props["LeftUpLeg.quaternion"].y=n.applied/2,this.poseDelta.props["RightUpLeg.quaternion"].y=n.applied/2,this.poseDelta.props["LeftLeg.quaternion"].y=n.applied/4,this.poseDelta.props["RightLeg.quaternion"].y=n.applied/4;break;case"bodyRotateZ":this.poseDelta.props["Head.quaternion"].z=n.applied+this.mtAvatar.headRotateZ.applied,this.poseDelta.props["Spine1.quaternion"].z=n.applied/12,this.poseDelta.props["Spine.quaternion"].z=n.applied/12,this.poseDelta.props["Hips.quaternion"].z=n.applied/24;break;case"handFistLeft":case"handFistRight":const o=e.substring(8);["HandThumb","HandIndex","HandMiddle","HandRing","HandPinky"].forEach((u,a)=>{a===0?(this.poseDelta.props[o+u+"1.quaternion"].x=0,this.poseDelta.props[o+u+"2.quaternion"].z=(o==="Left"?-1:1)*n.applied,this.poseDelta.props[o+u+"3.quaternion"].z=(o==="Left"?-1:1)*n.applied):(this.poseDelta.props[o+u+"1.quaternion"].x=n.applied,this.poseDelta.props[o+u+"2.quaternion"].x=1.5*n.applied,this.poseDelta.props[o+u+"3.quaternion"].x=1.5*n.applied)});break;case"chestInhale":const l=n.applied/20,h={x:l,y:l/2,z:3*l},r={x:1/(1+l)-1,y:1/(1+l/2)-1,z:1/(1+3*l)-1};this.poseDelta.props["Spine1.scale"]=h,this.poseDelta.props["Neck.scale"]=r,this.poseDelta.props["LeftArm.scale"]=r,this.poseDelta.props["RightArm.scale"]=r;break;default:for(let u=0,a=n.ms.length;u<a;u++)n.ms[u][n.is[u]]=n.applied}}}getPoseString(t,e=1e3){let n="{";return Object.entries(t).forEach((i,s)=>{const o=i[0].split(".");if(o[1]==="position"||o[1]==="rotation"||o[1]==="quaternion"){const l=o[1]==="quaternion"?o[0]+".rotation":i[0],h=i[1].isQuaternion?new f.Euler().setFromQuaternion(i[1]):i[1];n+=(s?", ":"")+"'"+l+"':{",n+="x:"+Math.round(h.x*e)/e,n+=", y:"+Math.round(h.y*e)/e,n+=", z:"+Math.round(h.z*e)/e,n+="}"}}),n+="}",n}getPoseTemplateProp(t){const e=t.split(".");let n=e[0]+"."+(e[1]==="rotation"?"quaternion":e[1]);if(this.gesture&&this.gesture.hasOwnProperty(n))return this.gesture[n].clone();{let i=e[0]+"."+(e[1]==="quaternion"?"rotation":e[1]);this.poseWeightOnLeft||(i.startsWith("Left")?(i="Right"+i.substring(4),n="Right"+n.substring(4)):i.startsWith("Right")&&(i="Left"+i.substring(5),n="Left"+n.substring(5)));let s;if(this.poseTarget.template.props.hasOwnProperty(n)){const o={};o[n]=this.poseTarget.template.props[n],s=this.propsToThreeObjects(o)[n]}else if(this.poseTarget.template.props.hasOwnProperty(i)){const o={};o[i]=this.poseTarget.template.props[i],s=this.propsToThreeObjects(o)[n]}return s&&!this.poseWeightOnLeft&&s.isQuaternion&&(s.x*=-1,s.w*=-1),s}}mirrorPose(t){const e={};for(let[n,i]of Object.entries(t))i.isQuaternion&&(n.startsWith("Left")?n="Right"+n.substring(4):n.startsWith("Right")&&(n="Left"+n.substring(5)),i.x*=-1,i.w*=-1),e[n]=i.clone(),e[n].t=i.t,e[n].d=i.d;return e}poseFactory(t,e=2e3){const n={template:t,props:this.propsToThreeObjects(t.props)};for(const[i,s]of Object.entries(n.props)){if(this.opt.modelMovementFactor<1&&t.standing&&(i==="Hips.quaternion"||i==="Spine.quaternion"||i==="Spine1.quaternion"||i==="Spine2.quaternion"||i==="Neck.quaternion"||i==="LeftUpLeg.quaternion"||i==="LeftLeg.quaternion"||i==="RightUpLeg.quaternion"||i==="RightLeg.quaternion")){const o=this.poseStraight[i],l=s.angleTo(o);s.rotateTowards(o,(1-this.opt.modelMovementFactor)*l)}s.t=this.animClock,s.d=e}return n}setPoseFromTemplate(t,e=2e3){const n=t&&this.poseTarget&&this.poseTarget.template&&(this.poseTarget.template.standing&&t.lying||this.poseTarget.template.lying&&t.standing),i=t&&t===this.poseCurrentTemplate,s=this.poseWeightOnLeft;let o=n?1e3:e;if(n?(this.poseCurrentTemplate=this.poseTemplates.oneknee,setTimeout(()=>{this.setPoseFromTemplate(t,e)},o)):this.poseCurrentTemplate=t||this.poseCurrentTemplate,this.poseTarget=this.poseFactory(this.poseCurrentTemplate,o),this.poseWeightOnLeft=!0,(!i&&!s||i&&s)&&(this.poseTarget.props=this.mirrorPose(this.poseTarget.props),this.poseWeightOnLeft=!this.poseWeightOnLeft),this.gesture)for(let[l,h]of Object.entries(this.gesture))this.poseTarget.props.hasOwnProperty(l)&&(this.poseTarget.props[l].copy(h),this.poseTarget.props[l].t=h.t,this.poseTarget.props[l].d=h.d);Object.keys(this.poseDelta.props).forEach(l=>{this.poseTarget.props.hasOwnProperty(l)||(this.poseTarget.props[l]=this.poseBase.props[l].clone(),this.poseTarget.props[l].t=this.animClock,this.poseTarget.props[l].d=o)})}getValue(t){return this.mtAvatar[t]?.value}setValue(t,e,n=null){this.mtAvatar.hasOwnProperty(t)&&Object.assign(this.mtAvatar[t],{system:e,systemd:n,needsUpdate:!0})}getMoodNames(){return Object.keys(this.animMoods)}getMood(){return this.opt.avatarMood}setMood(t){if(t=(t||"").trim().toLowerCase(),!this.animMoods.hasOwnProperty(t))throw new Error("Unknown mood.");this.moodName=t,this.mood=this.animMoods[this.moodName];for(let e of Object.keys(this.mtAvatar)){let n=this.mtBaselineExceptions.hasOwnProperty(e)?this.mtBaselineExceptions[e]:this.mtBaselineDefault;this.mood.baseline.hasOwnProperty(e)?n=this.mood.baseline[e]:this.avatar.baseline?.hasOwnProperty(e)&&(n=this.avatar.baseline[e]),this.setBaselineValue(e,n)}this.mood.anims.forEach(e=>{let n=this.animQueue.findIndex(i=>i.template.name===e.name);n!==-1&&this.animQueue.splice(n,1),this.animQueue.push(this.animFactory(e,-1))})}async initializeFBXAnimationLoader(){try{const{FBXAnimationLoader:t}=await Promise.resolve().then(()=>require("./fbxAnimationLoader-CNrfhJRz.cjs"));this.fbxAnimationLoader=new t(this.armature),console.log("FBX Animation Loader initialized")}catch(t){console.warn("FBX Animation Loader not available:",t),this.fbxAnimationLoader=null}}setBodyMovement(t){this.bodyMovement=t,this.avatar&&(this.avatar.bodyMovement=t),console.log("Body movement set to:",t),t==="idle"&&this.unlockAvatarPosition(),this.applyBodyMovementAnimation()}async applyBodyMovementAnimation(){if(!this.armature||!this.animQueue){console.log("Avatar not ready for body movement animations");return}console.log("Avatar is running:",this.isRunning),console.log("Animation queue exists:",!!this.animQueue);const t=this.animQueue.length;this.animQueue=this.animQueue.filter(i=>!i.template.name.startsWith("bodyMovement"));const e=this.animQueue.length;if(console.log(`Filtered animation queue: ${t} -> ${e} animations`),this.bodyMovement==="idle"){this.fbxAnimationLoader&&this.fbxAnimationLoader.stopCurrentAnimation();return}if(this.fbxAnimationLoader)try{await this.fbxAnimationLoader.playGestureAnimation(this.bodyMovement,this.movementIntensity),console.log("Applied FBX body movement animation:",this.bodyMovement);return}catch(i){console.warn("FBX animation failed, falling back to code animation:",i)}const n=this.createBodyMovementAnimation(this.bodyMovement);if(console.log("Created movement animation:",n),n)try{const i=this.animFactory(n,!0);i&&i.ts&&i.ts.length>0?(this.animQueue.push(i),console.log("Applied code-based body movement animation:",this.bodyMovement),console.log("Animation queue length:",this.animQueue.length),console.log("Animation object:",i)):(console.error("Invalid animation object created for:",this.bodyMovement),console.error("Animation object:",i))}catch(i){console.error("Error creating body movement animation:",i)}}lockAvatarPosition(){if(!this.armature){console.warn("Cannot lock position: armature not available");return}this.originalPosition||(this.originalPosition={x:this.armature.position.x,y:this.armature.position.y,z:this.armature.position.z},console.log("Original position stored:",this.originalPosition)),this.lockedPosition={x:this.armature.position.x,y:this.armature.position.y,z:this.armature.position.z},console.log("Avatar position locked at current position:",this.lockedPosition)}unlockAvatarPosition(){this.armature&&this.originalPosition?(this.armature.position.set(this.originalPosition.x,this.originalPosition.y,this.originalPosition.z),console.log("Avatar position restored to original:",this.originalPosition)):this.armature&&(this.armature.position.set(0,0,0),console.log("Avatar position reset to center (0,0,0)")),this.lockedPosition=null,this.originalPosition=null,console.log("Avatar position unlocked")}maintainLockedPosition(){this.lockedPosition&&this.armature&&this.armature.position.set(this.lockedPosition.x,this.lockedPosition.y,this.lockedPosition.z)}createBodyMovementAnimation(t){const e=this.movementIntensity||.5,n={walking:{name:"bodyMovement_walking",delay:[500,2e3],dt:[800,1200],vs:{bodyRotateY:[-.1*e,.1*e,0],bodyRotateZ:[-.05*e,.05*e,0],bodyRotateX:[-.02*e,.02*e,0]}},prancing:{name:"bodyMovement_prancing",delay:[300,1e3],dt:[400,800],vs:{bodyRotateY:[-.15*e,.15*e,0],bodyRotateZ:[-.08*e,.08*e,0],bodyRotateX:[-.05*e,.05*e,0]}},gesturing:{name:"bodyMovement_gesturing",delay:[400,1500],dt:[600,1e3],vs:{bodyRotateY:[-.08*e,.08*e,0],bodyRotateZ:[-.03*e,.03*e,0]}},dancing:{name:"bodyMovement_dancing",delay:[200,600],dt:[400,800],vs:{bodyRotateY:[-.25*e,.25*e,0],bodyRotateZ:[-.15*e,.15*e,0],bodyRotateX:[-.1*e,.1*e,0]}},dancing2:{name:"bodyMovement_dancing2",delay:[150,500],dt:[300,700],vs:{bodyRotateY:[-.3*e,.3*e,0],bodyRotateZ:[-.2*e,.2*e,0],bodyRotateX:[-.12*e,.12*e,0]}},dancing3:{name:"bodyMovement_dancing3",delay:[100,400],dt:[200,600],vs:{bodyRotateY:[-.35*e,.35*e,0],bodyRotateZ:[-.25*e,.25*e,0],bodyRotateX:[-.15*e,.15*e,0]}},excited:{name:"bodyMovement_excited",delay:[200,600],dt:[300,700],vs:{bodyRotateY:[-.12*e,.12*e,0],bodyRotateZ:[-.06*e,.06*e,0],bodyRotateX:[-.04*e,.04*e,0]}},happy:{name:"bodyMovement_happy",delay:[300,800],dt:[500,1e3],vs:{bodyRotateY:[-.08*e,.08*e,0],bodyRotateZ:[-.04*e,.04*e,0],bodyRotateX:[-.02*e,.02*e,0]}},surprised:{name:"bodyMovement_surprised",delay:[100,300],dt:[200,500],vs:{bodyRotateY:[-.05*e,.05*e,0],bodyRotateZ:[-.03*e,.03*e,0],bodyRotateX:[-.01*e,.01*e,0]}},thinking:{name:"bodyMovement_thinking",delay:[800,2e3],dt:[1e3,1500],vs:{bodyRotateY:[-.06*e,.06*e,0],bodyRotateZ:[-.03*e,.03*e,0],bodyRotateX:[-.02*e,.02*e,0]}},nodding:{name:"bodyMovement_nodding",delay:[400,800],dt:[300,600],vs:{bodyRotateX:[-.1*e,.1*e,0],bodyRotateY:[-.02*e,.02*e,0]}},shaking:{name:"bodyMovement_shaking",delay:[200,400],dt:[150,300],vs:{bodyRotateY:[-.15*e,.15*e,0],bodyRotateZ:[-.05*e,.05*e,0]}},celebration:{name:"bodyMovement_celebration",delay:[100,300],dt:[200,500],vs:{bodyRotateY:[-.2*e,.2*e,0],bodyRotateZ:[-.1*e,.1*e,0],bodyRotateX:[-.08*e,.08*e,0]}},energetic:{name:"bodyMovement_energetic",delay:[150,400],dt:[250,500],vs:{bodyRotateY:[-.18*e,.18*e,0],bodyRotateZ:[-.12*e,.12*e,0],bodyRotateX:[-.08*e,.08*e,0]}},swaying:{name:"bodyMovement_swaying",delay:[600,1200],dt:[800,1e3],vs:{bodyRotateY:[-.1*e,.1*e,0],bodyRotateZ:[-.05*e,.05*e,0]}},bouncing:{name:"bodyMovement_bouncing",delay:[300,600],dt:[400,700],vs:{bodyRotateY:[-.05*e,.05*e,0]}}};if(t==="dancing"){const i=["dancing","dancing2","dancing3"],s=i[Math.floor(Math.random()*i.length)];return n[s]||n.dancing}return n[t]||null}playRandomDance(){const t=["dancing","dancing2","dancing3"],e=t[Math.floor(Math.random()*t.length)];this.setBodyMovement(e)}playReaction(t){["happy","surprised","thinking","nodding","shaking","celebration","energetic","swaying","bouncing"].includes(t)?(this.setBodyMovement(t),["surprised","nodding","shaking","celebration"].includes(t)&&setTimeout(()=>{this.setBodyMovement("idle")},3e3)):console.warn("Invalid reaction type:",t)}playCelebration(){this.playReaction("celebration"),setTimeout(()=>{this.playRandomDance()},2e3)}setMovementIntensity(t){this.movementIntensity=Math.max(0,Math.min(1,t)),this.avatar&&(this.avatar.movementIntensity=this.movementIntensity),console.log("Movement intensity set to:",this.movementIntensity),this.fbxAnimationLoader&&this.fbxAnimationLoader.setIntensity(this.movementIntensity),this.applyBodyMovementAnimation()}setShowFullAvatar(t){this.showFullAvatar=t,this.avatar&&(this.avatar.showFullAvatar=t),console.log("Show full avatar set to:",t),t&&this.viewName!=="full"?(console.log("Changing camera view to full"),this.setView("full")):!t&&this.viewName!=="upper"?(console.log("Changing camera view to upper"),this.setView("upper")):console.log("Camera view already set to:",this.viewName)}getMorphTargetNames(){return["eyesRotateX","eyesRotateY",...Object.keys(this.mtAvatar)].sort()}getBaselineValue(t){if(t==="eyesRotateY"){const e=this.getBaselineValue("eyeLookOutLeft");if(e===void 0)return;const n=this.getBaselineValue("eyeLookInLeft");return n===void 0||this.getBaselineValue("eyeLookOutRight")===void 0||this.getBaselineValue("eyeLookInRight")===void 0?void 0:e-n}else if(t==="eyesRotateX"){const e=this.getBaselineValue("eyesLookDown");if(e===void 0)return;const n=this.getBaselineValue("eyesLookUp");return n===void 0?void 0:e-n}else return this.mtAvatar[t]?.baseline}setBaselineValue(t,e){t==="eyesRotateY"?(this.setBaselineValue("eyeLookOutLeft",e===null?null:e>0?e:0),this.setBaselineValue("eyeLookInLeft",e===null?null:e>0?0:-e),this.setBaselineValue("eyeLookOutRight",e===null?null:e>0?0:-e),this.setBaselineValue("eyeLookInRight",e===null?null:e>0?e:0)):t==="eyesRotateX"?(this.setBaselineValue("eyesLookDown",e===null?null:e>0?e:0),this.setBaselineValue("eyesLookUp",e===null?null:e>0?0:-e)):this.mtAvatar.hasOwnProperty(t)&&Object.assign(this.mtAvatar[t],{base:null,baseline:e,needsUpdate:!0})}getFixedValue(t){if(t==="eyesRotateY"){const e=this.getFixedValue("eyeLookOutLeft");if(e===null)return null;const n=this.getFixedValue("eyeLookInLeft");return n===null||this.getFixedValue("eyeLookOutRight")===null||this.getFixedValue("eyeLookInRight")===null?null:e-n}else if(t==="eyesRotateX"){const e=this.getFixedValue("eyesLookDown");if(e===null)return null;const n=this.getFixedValue("eyesLookUp");return n===null?null:e-n}else return this.mtAvatar[t]?.fixed}setFixedValue(t,e,n=null){t==="eyesRotateY"?(this.setFixedValue("eyeLookOutLeft",e===null?null:e>0?e:0,n),this.setFixedValue("eyeLookInLeft",e===null?null:e>0?0:-e,n),this.setFixedValue("eyeLookOutRight",e===null?null:e>0?0:-e,n),this.setFixedValue("eyeLookInRight",e===null?null:e>0?e:0,n)):t==="eyesRotateX"?(this.setFixedValue("eyesLookDown",e===null?null:e>0?e:0,n),this.setFixedValue("eyesLookUp",e===null?null:e>0?0:-e,n)):this.mtAvatar.hasOwnProperty(t)&&Object.assign(this.mtAvatar[t],{fixed:e,needsUpdate:!0})}animFactory(t,e=!1,n=1,i=1,s=!1){const o={template:t,ts:[0],vs:{}};let l=t;for(;;)if(l.hasOwnProperty(this.stateName))(this.stateName==="speaking"||this.stateName==="idle")&&console.log("Selected state:",this.stateName,"for avatar body:",this.avatar?.body),l=l[this.stateName];else if(l.hasOwnProperty(this.moodName))l=l[this.moodName];else if(l.hasOwnProperty(this.poseName))l=l[this.poseName];else if(l.hasOwnProperty(this.viewName))l=l[this.viewName];else if(this.avatar&&this.avatar.body&&l.hasOwnProperty(this.avatar.body))console.log("Applying gender-specific override:",this.avatar.body,"for state:",this.stateName,"keys:",Object.keys(l)),l=l[this.avatar.body];else if(l.hasOwnProperty("alt")){let r=l.alt[0];if(l.alt.length>1){const u=Math.random();let a=0;for(let d=0;d<l.alt.length;d++){let c=this.valueFn(l.alt[d].p);if(a+=c===void 0?(1-a)/(l.alt.length-1-d):c,u<a){r=l.alt[d];break}}}l=r,this.avatar&&this.avatar.body&&l.hasOwnProperty(this.avatar.body)&&console.log("Found gender override in selected alternative:",this.avatar.body,"keys:",Object.keys(l));continue}else break;let h=this.valueFn(l.delay)||0;if(Array.isArray(h)&&(h=this.gaussianRandom(...h)),l.hasOwnProperty("dt"))l.dt.forEach((r,u)=>{let a=this.valueFn(r);Array.isArray(a)&&(a=this.gaussianRandom(...a)),o.ts[u+1]=o.ts[u]+a});else{let r=Object.values(l.vs).reduce((u,a)=>a.length>u?a.length:u,0);o.ts=Array(r+1).fill(0)}s?o.ts=o.ts.map(r=>h+r*n):o.ts=o.ts.map(r=>this.animClock+h+r*n),l.vs&&l.vs.pose&&console.log("Pose being selected from vs.pose:",l.vs.pose,"for avatar body:",this.avatar?.body);for(let[r,u]of Object.entries(l.vs)){const a=this.getBaselineValue(r),d=u.map(c=>(c=this.valueFn(c),c===null?null:typeof c=="function"?c:typeof c=="string"||c instanceof String?r==="pose"&&this.avatar&&this.avatar.body==="M"&&(c==="hip"||c==="side")?(console.log("Intercepting pose",c,"in animation factory, overriding to wide for male avatar"),"wide"):c.slice():Array.isArray(c)?r==="gesture"?c.slice():(a===void 0?0:a)+i*this.gaussianRandom(...c):typeof c=="boolean"?c:c instanceof Object&&c.constructor===Object?Object.assign({},c):(a===void 0?0:a)+i*c));r==="eyesRotateY"?(o.vs.eyeLookOutLeft=[null,...d.map(c=>c>0?c:0)],o.vs.eyeLookInLeft=[null,...d.map(c=>c>0?0:-c)],o.vs.eyeLookOutRight=[null,...d.map(c=>c>0?0:-c)],o.vs.eyeLookInRight=[null,...d.map(c=>c>0?c:0)]):r==="eyesRotateX"?(o.vs.eyesLookDown=[null,...d.map(c=>c>0?c:0)],o.vs.eyesLookUp=[null,...d.map(c=>c>0?0:-c)]):o.vs[r]=[null,...d]}for(let r of Object.keys(o.vs))for(;o.vs[r].length<=o.ts.length;)o.vs[r].push(o.vs[r][o.vs[r].length-1]);return t.hasOwnProperty("mood")&&(o.mood=this.valueFn(t.mood).slice()),e&&(o.loop=e),o}valueAnimationSeq(t,e,n,i,s,o=null){t=this.valueFn(t),e=this.valueFn(e),s<n&&(s=n),s>i&&(s=i);let l=(e-t)/(i-n);return o&&(l*=o((s-n)/(i-n))),l*s+(t-l*n)}gaussianRandom(t,e,n=1,i=5){let s=0;for(let o=0;o<i;o++)s+=Math.random();return t+Math.pow(s/i,n)*(e-t)}sigmoidFactory(t){function e(i){return 1/(1+Math.exp(-t*i))-.5}var n=.5/e(1);return function(i){return n*e(2*Math.max(Math.min(i,1),0)-1)+.5}}convertRange(t,e,n){return(t-e[0])*(n[1]-n[0])/(e[1]-e[0])+n[0]}animate(t){if(!this.isRunning)return;let e;if(this.isAvatarOnly)e=t;else{if(requestAnimationFrame(this.animate.bind(this)),e=t-this.animTimeLast,e<this.animFrameDur)return;this.animTimeLast=t}e=e/this.animSlowdownRate,this.animClock+=e,this.maintainLockedPosition();let n,i,s,o,l=0;if(this.stats&&this.stats.begin(),this.isListening){for(this.listeningAnalyzer.getByteFrequencyData(this.volumeFrequencyData),n=2,s=10;n<s;n++)this.volumeFrequencyData[n]>l&&(l=this.volumeFrequencyData[n]);this.listeningVolume=(this.listeningVolume+l)/2,this.listeningActive?(this.listeningTimerTotal+=e,this.listeningVolume<this.listeningSilenceThresholdLevel?(this.listeningTimer+=e,this.listeningTimer>this.listeningSilenceThresholdMs&&(this.listeningOnchange&&this.listeningOnchange("stop",this.listeningTimer),this.listeningActive=!1,this.listeningTimer=0,this.listeningTimerTotal=0)):this.listeningTimer*=.5,this.listeningTimerTotal>this.listeningActiveDurationMax&&(this.listeningOnchange&&this.listeningOnchange("maxactive"),this.listeningTimerTotal=0)):(this.listeningTimerTotal+=e,this.listeningVolume>this.listeningActiveThresholdLevel?(this.listeningTimer+=e,this.listeningTimer>this.listeningActiveThresholdMs&&(this.listeningOnchange&&this.listeningOnchange("start"),this.listeningActive=!0,this.listeningTimer=0,this.listeningTimerTotal=0)):this.listeningTimer*=.5,this.listeningTimerTotal>this.listeningSilenceDurationMax&&(this.listeningOnchange&&this.listeningOnchange("maxsilence"),this.listeningTimerTotal=0))}if(this.isSpeaking)for(l=0,this.audioAnalyzerNode.getByteFrequencyData(this.volumeFrequencyData),n=2,s=10;n<s;n++)this.volumeFrequencyData[n]>l&&(l=this.volumeFrequencyData[n]);let h=null,r=null;const u=[];for(n=0,s=this.animQueue.length;n<s;n++){const a=this.animQueue[n];if(!(!a||!a.ts||!a.ts.length||this.animClock<a.ts[0])){for(i=a.ndx||0,o=a.ts.length;i<o&&!(this.animClock<a.ts[i]);i++)for(let[d,c]of Object.entries(a.vs))if(this.mtAvatar.hasOwnProperty(d)){if(c[i+1]===null)continue;const g=this.mtAvatar[d];if(c[i]===null&&(c[i]=g.value),i===o-1)g.newvalue=c[i];else{g.newvalue=c[i+1];const b=a.ts[i+1]-a.ts[i];let x=1;b>1e-4&&(x=(this.animClock-a.ts[i])/b),x<1&&(g.easing&&(x=g.easing(x)),g.newvalue=(1-x)*c[i]+x*g.newvalue),g.ref&&g.ref!==a.vs&&g.ref.hasOwnProperty(d)&&delete g.ref[d],g.ref=a.vs}if(l)switch(d){case"viseme_aa":case"viseme_E":case"viseme_I":case"viseme_O":case"viseme_U":g.newvalue*=1+l/255-.5}g.needsUpdate=!0}else d==="eyeContact"&&c[i]!==null&&h!==!1?h=!!c[i]:d==="headMove"&&c[i]!==null&&r!==!1?c[i]===0?r=!1:(Math.random()<c[i]&&(r=!0),c[i]=null):c[i]!==null&&(u.push({mt:d,val:c[i]}),c[i]=null);i===o?(a.hasOwnProperty("mood")&&this.setMood(a.mood),a.loop?(o=this.isSpeaking&&(a.template.name==="head"||a.template.name==="eyes")?4:1,this.animQueue[n]=this.animFactory(a.template,a.loop>0?a.loop-1:a.loop,1,1/o)):(this.animQueue.splice(n--,1),s--)):a.ndx=i-1}}for(let a=0,d=u.length;a<d;a++)switch(i=u[a].val,u[a].mt){case"speak":this.speakText(i);break;case"subtitles":this.onSubtitles&&typeof this.onSubtitles=="function"&&this.onSubtitles(i);break;case"pose":this.avatar&&this.avatar.body==="M"&&(i==="hip"||i==="side")&&this.poseTemplates.wide&&(i="wide",console.log("Overriding pose",i==="hip"?"hip":"side","to wide for male avatar")),this.poseName=i,console.log("Setting pose to:",this.poseName,"for avatar body:",this.avatar?.body,"state:",this.stateName),this.setPoseFromTemplate(this.poseTemplates[this.poseName]);break;case"gesture":this.playGesture(...i);break;case"function":i&&typeof i=="function"&&i();break;case"moveto":Object.entries(i.props).forEach(c=>{c[1]?this.poseTarget.props[c[0]].copy(c[1]):this.poseTarget.props[c[0]].copy(this.getPoseTemplateProp(c[0])),this.poseTarget.props[c[0]].t=this.animClock,this.poseTarget.props[c[0]].d=c[1]&&c[1].d?c[1].d:c.duration||2e3});break;case"handLeft":this.ikSolve({iterations:20,root:"LeftShoulder",effector:"LeftHandMiddle1",links:[{link:"LeftHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5},{link:"LeftForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-.5,maxz:3},{link:"LeftArm",minx:-1.5,maxx:1.5,miny:0,maxy:0,minz:-1,maxz:3}]},i.x?new f.Vector3(i.x,i.y,i.z):null,!0,i.d);break;case"handRight":this.ikSolve({iterations:20,root:"RightShoulder",effector:"RightHandMiddle1",links:[{link:"RightHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5,maxAngle:.1},{link:"RightForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-3,maxz:.5,maxAngle:.2},{link:"RightArm",minx:-1.5,maxx:1.5,miny:0,maxy:0,minz:-1,maxz:3}]},i.x?new f.Vector3(i.x,i.y,i.z):null,!0,i.d);break}if((h||r)&&(Z.setFromQuaternion(this.poseAvatar.props["Head.quaternion"]),Z.x=Math.max(-.9,Math.min(.9,2*Z.x-.5)),Z.y=Math.max(-.9,Math.min(.9,-2.5*Z.y)),h?(Object.assign(this.mtAvatar.eyesLookDown,{system:Z.x<0?-Z.x:0,needsUpdate:!0}),Object.assign(this.mtAvatar.eyesLookUp,{system:Z.x<0?0:Z.x,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookInLeft,{system:Z.y<0?-Z.y:0,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookOutLeft,{system:Z.y<0?0:Z.y,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookInRight,{system:Z.y<0?0:Z.y,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookOutRight,{system:Z.y<0?-Z.y:0,needsUpdate:!0}),r&&(n=-this.mtAvatar.bodyRotateY.value,i=this.gaussianRandom(-.2,.2),this.animQueue.push(this.animFactory({name:"headmove",dt:[[1e3,2e3],[1e3,2e3,1,2],[1e3,2e3],[1e3,2e3,1,2]],vs:{headRotateY:[n,n,0],headRotateX:[i,i,0],headRotateZ:[-n/4,-n/4,0]}})))):(n=this.mtAvatar.eyeLookInLeft.value-this.mtAvatar.eyeLookOutLeft.value,i=this.gaussianRandom(-.2,.2),this.animQueue.push(this.animFactory({name:"headmove",dt:[[1e3,2e3],[1e3,2e3,1,2],[1e3,2e3],[1e3,2e3,1,2]],vs:{headRotateY:[null,n,n,0],headRotateX:[null,i,i,0],headRotateZ:[null,-n/4,-n/4,0],eyeLookInLeft:[null,0],eyeLookOutLeft:[null,0],eyeLookInRight:[null,0],eyeLookOutRight:[null,0],eyeContact:[0]}})))),e>2*this.animFrameDur&&(e=2*this.animFrameDur),(this.viewName!=="full"||this.isAvatarOnly)&&(n=this.mtRandomized[Math.floor(Math.random()*this.mtRandomized.length)],i=this.mtAvatar[n],i.needsUpdate||Object.assign(i,{base:(this.mood.baseline[n]||0)+(1+l/255)*Math.random()/5,needsUpdate:!0})),this.updatePoseBase(this.animClock),this.mixer&&this.mixer.update(e/1e3*this.mixer.timeScale),this.updatePoseDelta(),(this.isSpeaking||this.isListening)&&h?l>this.volumeMax?(this.volumeHeadBase=.05,Math.random()>.6&&(this.volumeHeadTarget=-.05-Math.random()/15),this.volumeMax=l):(this.volumeMax*=.92,this.volumeHeadTarget=this.volumeHeadBase-.9*(this.volumeHeadBase-this.volumeHeadTarget)):(this.volumeHeadTarget=0,this.volumeMax=0),n=this.volumeHeadTarget-this.volumeHeadCurrent,i=Math.abs(n),i>1e-4&&(o=i*(this.volumeHeadEasing(Math.min(1,this.volumeHeadVelocity*e/1e3/i)/2+.5)-.5),this.volumeHeadCurrent+=Math.sign(n)*Math.min(i,o)),Math.abs(this.volumeHeadCurrent)>1e-4&&(q.setFromAxisAngle(dt,this.volumeHeadCurrent),this.objectNeck.quaternion.multiply(q)),Oe.setFromObject(this.armature),this.objectLeftToeBase.getWorldPosition(fe),fe.sub(this.armature.position),this.objectRightToeBase.getWorldPosition(xe),xe.sub(this.armature.position),this.objectHips.position.y-=Oe.min.y/2,this.objectHips.position.x-=(fe.x+xe.x)/4,this.objectHips.position.z-=(fe.z+xe.z)/2,this.dynamicbones.update(e),this.fbxAnimationLoader&&this.fbxAnimationLoader.update(),this.opt.update&&this.opt.update(e),this.updateMorphTargets(e),this.isAvatarOnly)this.stats&&this.stats.end();else{if(this.cameraClock!==null&&this.cameraClock<1e3){this.cameraClock+=e,this.cameraClock>1e3&&(this.cameraClock=1e3);let a=new f.Spherical().setFromVector3(this.cameraStart),d=new f.Spherical().setFromVector3(this.cameraEnd);a.phi+=this.easing(this.cameraClock/1e3)*(d.phi-a.phi),a.theta+=this.easing(this.cameraClock/1e3)*(d.theta-a.theta),a.radius+=this.easing(this.cameraClock/1e3)*(d.radius-a.radius),a.makeSafe(),this.camera.position.setFromSpherical(a),this.controlsStart.x!==this.controlsEnd.x?this.controls.target.copy(this.controlsStart.lerp(this.controlsEnd,this.easing(this.cameraClock/1e3))):(a.setFromVector3(this.controlsStart),d.setFromVector3(this.controlsEnd),a.phi+=this.easing(this.cameraClock/1e3)*(d.phi-a.phi),a.theta+=this.easing(this.cameraClock/1e3)*(d.theta-a.theta),a.radius+=this.easing(this.cameraClock/1e3)*(d.radius-a.radius),a.makeSafe(),this.controls.target.setFromSpherical(a)),this.controls.update()}this.controls.autoRotate&&this.controls.update(),this.stats&&this.stats.end(),this.render()}}resetLips(){this.visemeNames.forEach(t=>{this.morphs.forEach(e=>{const n=e.morphTargetDictionary["viseme_"+t];n!==void 0&&(e.morphTargetInfluences[n]=0)})})}lipsyncGetProcessor(t,e="./"){if(!this.lipsync.hasOwnProperty(t)){const n=t.toLowerCase(),i="Lipsync"+t.charAt(0).toUpperCase()+t.slice(1);try{const s=Ne[n];s&&s[i]?(this.lipsync[t]=new s[i],console.log(`Loaded lip-sync module for ${t}`)):console.warn(`Lip-sync module for ${t} not found. Available modules:`,Object.keys(Ne))}catch(s){console.warn(`Failed to load lip-sync module for ${t}:`,s)}}}lipsyncPreProcessText(t,e){return(this.lipsync[e]||Object.values(this.lipsync)[0]).preProcessText(t)}lipsyncWordsToVisemes(t,e){return(this.lipsync[e]||Object.values(this.lipsync)[0]).wordsToVisemes(t)}speakText(t,e=null,n=null,i=null){e=e||{};const s=/[!\.\?\n\p{Extended_Pictographic}]/ug,o=/[ ]/ug,l=/[\p{L}\p{N},\.\p{Quotation_Mark}!€\$\+\p{Dash_Punctuation}%&\?]/ug,h=/[\p{Extended_Pictographic}]/ug,r=e.lipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang;let u="",a="",d=0,c=[],g=[];const b=Array.from(this.segmenter.segment(t),x=>x.segment);for(let x=0;x<b.length;x++){const S=x===b.length-1,U=b[x].match(l);let p=b[x].match(s);const F=b[x].match(h),H=b[x].match(o);if(p&&!S&&!F&&b[x+1].match(s)&&(p=!1),n&&(u+=b[x]),U&&(!i||i.every(y=>x<y[0]||x>y[1]))&&(a+=b[x]),(H||p||S)&&(a.length&&(a=this.lipsyncPreProcessText(a,r),a.length&&c.push({mark:d,word:a})),u.length&&(g.push({mark:d,template:{name:"subtitles"},ts:[0],vs:{subtitles:[u]}}),u=""),a.length)){const y=this.lipsyncWordsToVisemes(a,r);if(y&&y.visemes&&y.visemes.length){const A=y.times[y.visemes.length-1]+y.durations[y.visemes.length-1];for(let z=0;z<y.visemes.length;z++)g.push({mark:d,template:{name:"viseme"},ts:[(y.times[z]-.6)/A,(y.times[z]+.5)/A,(y.times[z]+y.durations[z]+.5)/A],vs:{["viseme_"+y.visemes[z]]:[null,y.visemes[z]==="PP"||y.visemes[z]==="FF"?.9:.6,0]}})}a="",d++}if(p||S){if(c.length||S&&g.length){const y={anim:g};n&&(y.onSubtitles=n),c.length&&!e.avatarMute&&(y.text=c,e.avatarMood&&(y.mood=e.avatarMood),e.ttsLang&&(y.lang=e.ttsLang),e.ttsVoice&&(y.voice=e.ttsVoice),e.ttsRate&&(y.rate=e.ttsRate),e.ttsVoice&&(y.pitch=e.ttsPitch),e.ttsVolume&&(y.volume=e.ttsVolume)),this.speechQueue.push(y),c=[],a="",d=0,g=[]}if(F){let y=this.animEmojis[b[x]];y&&y.link&&(y=this.animEmojis[y.link]),y&&this.speechQueue.push({emoji:y})}this.speechQueue.push({break:100})}}this.speechQueue.push({break:1e3}),this.startSpeaking()}async speakEmoji(t){let e=this.animEmojis[t];e&&e.link&&(e=this.animEmojis[e.link]),e&&this.speechQueue.push({emoji:e}),this.startSpeaking()}async speakBreak(t){this.speechQueue.push({break:t}),this.startSpeaking()}async speakMarker(t){this.speechQueue.push({marker:t}),this.startSpeaking()}async playBackgroundAudio(t){let n=await(await fetch(t)).arrayBuffer();this.stopBackgroundAudio(),this.audioBackgroundSource=this.audioCtx.createBufferSource(),this.audioBackgroundSource.loop=!0,this.audioBackgroundSource.buffer=await this.audioCtx.decodeAudioData(n),this.audioBackgroundSource.playbackRate.value=1/this.animSlowdownRate,this.audioBackgroundSource.connect(this.audioBackgroundGainNode),this.audioBackgroundSource.start(0)}stopBackgroundAudio(){try{this.audioBackgroundSource.stop()}catch{}this.audioBackgroundSource.disconnect()}async setReverb(t=null){if(t){let n=await(await fetch(t)).arrayBuffer();this.audioReverbNode.buffer=await this.audioCtx.decodeAudioData(n)}else{const e=this.audioCtx.sampleRate,n=this.audioCtx.createBuffer(2,e,e);n.getChannelData(0)[0]=1,n.getChannelData(1)[0]=1,this.audioReverbNode.buffer=n}}setMixerGain(t,e=null,n=0){t!==null&&(this.audioSpeechGainNode.gain.cancelScheduledValues(this.audioCtx.currentTime),n?(this.audioSpeechGainNode.gain.setValueAtTime(Math.max(this.audioSpeechGainNode.gain.value,1e-4),this.audioCtx.currentTime),this.audioSpeechGainNode.gain.exponentialRampToValueAtTime(Math.max(t,1e-4),this.audioCtx.currentTime+n)):this.audioSpeechGainNode.gain.setValueAtTime(t,this.audioCtx.currentTime)),e!==null&&(this.audioBackgroundGainNode.gain.cancelScheduledValues(this.audioCtx.currentTime),n?(this.audioBackgroundGainNode.gain.setValueAtTime(Math.max(this.audioBackgroundGainNode.gain.value,1e-4),this.audioCtx.currentTime),this.audioBackgroundGainNode.gain.exponentialRampToValueAtTime(Math.max(e,1e-4),this.audioCtx.currentTime+n)):this.audioBackgroundGainNode.gain.setValueAtTime(e,this.audioCtx.currentTime))}speakAudio(t,e=null,n=null){e=e||{};const i=e.lipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang,s={};if(t.words){let o=[];for(let l=0;l<t.words.length;l++){const h=t.words[l],r=t.wtimes[l];let u=t.wdurations[l];if(h.length&&(n&&o.push({template:{name:"subtitles"},ts:[r],vs:{subtitles:[" "+h]}}),!t.visemes)){const a=this.lipsyncPreProcessText(h,i),d=this.lipsyncWordsToVisemes(a,i);if(d&&d.visemes&&d.visemes.length){const c=d.times[d.visemes.length-1]+d.durations[d.visemes.length-1],g=Math.min(u,Math.max(0,u-d.visemes.length*150));let b=.6+this.convertRange(g,[0,u],[0,.4]);if(u=Math.min(u,d.visemes.length*200),c>0)for(let x=0;x<d.visemes.length;x++){const S=r+d.times[x]/c*u,U=d.durations[x]/c*u;o.push({template:{name:"viseme"},ts:[S-Math.min(60,2*U/3),S+Math.min(25,U/2),S+U+Math.min(60,U/2)],vs:{["viseme_"+d.visemes[x]]:[null,d.visemes[x]==="PP"||d.visemes[x]==="FF"?.9:b,0]}})}}}}if(t.visemes)for(let l=0;l<t.visemes.length;l++){const h=t.visemes[l],r=t.vtimes[l],u=t.vdurations[l];o.push({template:{name:"viseme"},ts:[r-2*u/3,r+u/2,r+u+u/2],vs:{["viseme_"+h]:[null,h==="PP"||h==="FF"?.9:.6,0]}})}if(t.markers)for(let l=0;l<t.markers.length;l++){const h=t.markers[l],r=t.mtimes[l];o.push({template:{name:"markers"},ts:[r],vs:{function:[h]}})}o.length&&(s.anim=o)}if(t.audio&&(s.audio=t.audio),t.anim?.name){let o=this.animFactory(t.anim,!1,1,1,!0);s.anim?s.anim.push(o):s.anim=[o]}n&&(s.onSubtitles=n),e.isRaw&&(s.isRaw=!0),Object.keys(s).length&&(this.speechQueue.push(s),s.isRaw||this.speechQueue.push({break:300}),this.startSpeaking())}async playAudio(t=!1){if(!(!this.armature||this.isAudioPlaying&&!t))if(this.isAudioPlaying=!0,this.audioPlaylist.length){const e=this.audioPlaylist.shift();if(this.audioCtx.state==="suspended"||this.audioCtx.state==="interrupted"){const s=this.audioCtx.resume(),o=new Promise((l,h)=>setTimeout(()=>h("p2"),1e3));try{await Promise.race([s,o])}catch{console.log("Can't play audio. Web Audio API suspended. This is often due to calling some speak method before the first user action, which is typically prevented by the browser."),this.playAudio(!0);return}}let n;if(Array.isArray(e.audio)){let s=this.concatArrayBuffers(e.audio);n=this.pcmToAudioBuffer(s)}else n=e.audio;this.audioSpeechSource=this.audioCtx.createBufferSource(),this.audioSpeechSource.buffer=n,this.audioSpeechSource.playbackRate.value=1/this.animSlowdownRate,this.audioSpeechSource.connect(this.audioAnalyzerNode),this.audioSpeechSource.addEventListener("ended",()=>{this.audioSpeechSource.disconnect(),this.playAudio(!0)},{once:!0});let i=0;e.anim&&(e.isRaw||(i=Math.abs(Math.min(0,...e.anim.map(s=>Math.min(...s.ts))))),e.anim.forEach(s=>{for(let o=0;o<s.ts.length;o++)s.ts[o]=this.animClock+s.ts[o]+i;this.animQueue.push(s)})),this.audioSpeechSource.start(i/1e3)}else this.isAudioPlaying=!1,this.startSpeaking(!0)}async synthesizeWithBrowserTTS(t){return new Promise((e,n)=>{const i=t.text.map(p=>p.word).join(" "),s=new SpeechSynthesisUtterance(i),o=t.lang||this.avatar.ttsLang||this.opt.ttsLang||"en-US",l=(t.rate||this.avatar.ttsRate||this.opt.ttsRate||1)+this.mood.speech.deltaRate,h=(t.pitch||this.avatar.ttsPitch||this.opt.ttsPitch||1)+this.mood.speech.deltaPitch,r=(t.volume||this.avatar.ttsVolume||this.opt.ttsVolume||1)+this.mood.speech.deltaVolume;s.lang=o,s.rate=Math.max(.1,Math.min(10,l)),s.pitch=Math.max(0,Math.min(2,h)),s.volume=Math.max(0,Math.min(1,r));const u=speechSynthesis.getVoices(),a=t.voice||this.avatar.ttsVoice||this.opt.ttsVoice;if(a&&u.length>0){const p=u.find(F=>F.name.includes(a)||F.lang===o);p&&(s.voice=p)}const d=i.length*100/s.rate,c=this.audioCtx.createBuffer(1,this.audioCtx.sampleRate*(d/1e3),this.audioCtx.sampleRate),g=this.avatar.lipsyncLang||this.opt.lipsyncLang||"en",b=this.lipsyncPreProcessText(i,g),x=this.lipsyncWordsToVisemes(b,g);console.log("Browser TTS Lip-sync Debug:",{text:i,lipsyncLang:g,processedText:b,lipsyncData:x,hasVisemes:x&&x.visemes&&x.visemes.length>0,estimatedDuration:d});const S=[];if(x&&x.visemes&&x.visemes.length>0){const p=x.times[x.visemes.length-1]+x.durations[x.visemes.length-1];for(let F=0;F<x.visemes.length;F++){const H=x.visemes[F],y=x.times[F]/p,A=x.durations[F]/p,z=y*d,L=A*d;S.push({template:{name:"viseme"},ts:[z-Math.min(60,2*L/3),z+Math.min(25,L/2),z+L+Math.min(60,L/2)],vs:{["viseme_"+H]:[null,H==="PP"||H==="FF"?.9:.6,0]}})}}const U=[...t.anim,...S];this.audioPlaylist.push({anim:U,audio:c}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio(),s.onend=()=>{e()},s.onerror=p=>{console.error("Speech synthesis error:",p.error),n(p.error)},speechSynthesis.speak(s)})}async synthesizeWithElevenLabsTTS(t){const e=t.text.map(d=>d.word).join(" "),n=t.voice||this.avatar.ttsVoice||this.opt.ttsVoice||"21m00Tcm4TlvDq8ikWAM",i={text:e,model_id:"eleven_monolingual_v1",voice_settings:{stability:.5,similarity_boost:.5,style:0,use_speaker_boost:!0}},s=await fetch(`${this.opt.ttsEndpoint}/${n}`,{method:"POST",headers:{Accept:"audio/mpeg","Content-Type":"application/json","xi-api-key":this.opt.ttsApikey},body:JSON.stringify(i)});if(!s.ok)throw new Error(`ElevenLabs TTS error: ${s.status} ${s.statusText}`);const o=await s.arrayBuffer(),l=await this.audioCtx.decodeAudioData(o);console.log("Using text-based lip-sync for debugging...");const h=this.avatar.lipsyncLang||this.opt.lipsyncLang||"en";let r;try{console.log("Lip-sync modules available:",{hasLipsync:!!this.lipsync,lipsyncKeys:this.lipsync?Object.keys(this.lipsync):[],lipsyncLang:h});const d=this.lipsyncPreProcessText(e,h),c=this.lipsyncWordsToVisemes(d,h);if(console.log("Lip-sync data:",{processedText:d,lipsyncData:c,hasVisemes:c&&c.visemes&&c.visemes.length>0}),c&&c.visemes&&c.visemes.length>0)r={visemes:c.visemes.map((g,b)=>({viseme:g,startTime:b*l.duration/c.visemes.length,endTime:(b+1)*l.duration/c.visemes.length,duration:l.duration/c.visemes.length,intensity:.7})),words:[],duration:l.duration,features:{onsets:[],boundaries:[]}};else throw new Error("No visemes generated from text")}catch(d){console.error("Text-based lip-sync failed, using fallback:",d);const c=e.toLowerCase().split(/\s+/),g=[];for(const b of c)for(const x of b){let S="aa";"aeiou".includes(x)?S="aa":"bp".includes(x)?S="PP":"fv".includes(x)?S="FF":"st".includes(x)?S="SS":"dln".includes(x)?S="DD":"kg".includes(x)?S="kk":"rw".includes(x)&&(S="RR"),g.push(S)}r={visemes:g.map((b,x)=>({viseme:b,startTime:x*l.duration/g.length,endTime:(x+1)*l.duration/g.length,duration:l.duration/g.length,intensity:.6})),words:[],duration:l.duration,features:{onsets:[],boundaries:[]}}}console.log("ElevenLabs TTS Audio Analysis:",{text:e,audioDuration:l.duration,visemeCount:r.visemes?r.visemes.length:0,wordCount:r.words?r.words.length:0,features:{onsets:r.features&&r.features.onsets?r.features.onsets.length:0,boundaries:r.features&&r.features.phonemeBoundaries?r.features.phonemeBoundaries.length:0},visemes:r.visemes?r.visemes.slice(0,3):[]});const u=[];if(r.visemes&&r.visemes.length>0){console.log("ElevenLabs: Generating lip-sync animation from",r.visemes.length,"visemes");for(let d=0;d<r.visemes.length;d++){const c=r.visemes[d],g=c.startTime*1e3,b=c.duration*1e3,x=c.intensity;u.push({template:{name:"viseme"},ts:[g-Math.min(60,2*b/3),g+Math.min(25,b/2),g+b+Math.min(60,b/2)],vs:{["viseme_"+c.viseme]:[null,x,0]}})}console.log("ElevenLabs: Generated",u.length,"lip-sync animation frames")}else console.warn("ElevenLabs: No visemes available for lip-sync animation");const a=[...t.anim,...u];console.log("ElevenLabs: Combined animation frames:",a.length,"(original:",t.anim.length,"+ lipsync:",u.length,")"),this.audioPlaylist.push({anim:a,audio:l}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio()}async synthesizeWithDeepgramTTS(t){const e=t.text.map(d=>d.word).join(" "),n=t.voice||this.avatar.ttsVoice||this.opt.ttsVoice||"aura-2-thalia-en",i=`${this.opt.ttsEndpoint}?model=${n}`,s=await fetch(i,{method:"POST",headers:{Authorization:`Token ${this.opt.ttsApikey}`,"Content-Type":"text/plain",Accept:"audio/mpeg"},body:e});if(!s.ok)throw new Error(`Deepgram TTS error: ${s.status} ${s.statusText}`);const o=await s.arrayBuffer(),l=await this.audioCtx.decodeAudioData(o);console.log("Using text-based lip-sync for Deepgram...");const h=this.avatar.lipsyncLang||this.opt.lipsyncLang||"en";let r;try{console.log("Lip-sync modules available:",{hasLipsync:!!this.lipsync,lipsyncKeys:this.lipsync?Object.keys(this.lipsync):[],lipsyncLang:h});const d=this.lipsyncPreProcessText(e,h),c=this.lipsyncWordsToVisemes(d,h);if(console.log("Lip-sync data:",{processedText:d,lipsyncData:c,hasVisemes:c&&c.visemes&&c.visemes.length>0}),c&&c.visemes&&c.visemes.length>0)r={visemes:c.visemes.map((g,b)=>({viseme:g,startTime:b*l.duration/c.visemes.length,endTime:(b+1)*l.duration/c.visemes.length,duration:l.duration/c.visemes.length,intensity:.7})),words:[],duration:l.duration,features:{onsets:[],boundaries:[]}};else throw new Error("No visemes generated from text")}catch(d){console.error("Text-based lip-sync failed, using fallback:",d);const c=e.toLowerCase().split(/\s+/),g=[];for(const b of c)for(const x of b){let S="aa";"aeiou".includes(x)?S="aa":"bp".includes(x)?S="PP":"fv".includes(x)?S="FF":"st".includes(x)?S="SS":"dln".includes(x)?S="DD":"kg".includes(x)?S="kk":"rw".includes(x)&&(S="RR"),g.push(S)}r={visemes:g.map((b,x)=>({viseme:b,startTime:x*l.duration/g.length,endTime:(x+1)*l.duration/g.length,duration:l.duration/g.length,intensity:.6})),words:[],duration:l.duration,features:{onsets:[],boundaries:[]}}}console.log("Deepgram TTS Audio Analysis:",{text:e,audioDuration:l.duration,visemeCount:r.visemes?r.visemes.length:0,wordCount:r.words?r.words.length:0,features:{onsets:r.features&&r.features.onsets?r.features.onsets.length:0,boundaries:r.features&&r.features.phonemeBoundaries?r.features.phonemeBoundaries.length:0},visemes:r.visemes?r.visemes.slice(0,3):[]});const u=[];if(r.visemes&&r.visemes.length>0){console.log("Deepgram: Generating lip-sync animation from",r.visemes.length,"visemes");for(let d=0;d<r.visemes.length;d++){const c=r.visemes[d],g=c.startTime*1e3,b=c.duration*1e3,x=c.intensity;u.push({template:{name:"viseme"},ts:[g-Math.min(60,2*b/3),g+Math.min(25,b/2),g+b+Math.min(60,b/2)],vs:{["viseme_"+c.viseme]:[null,x,0]}})}console.log("Deepgram: Generated",u.length,"lip-sync animation frames")}else console.warn("Deepgram: No visemes available for lip-sync animation");const a=[...t.anim,...u];console.log("Deepgram: Combined animation frames:",a.length,"(original:",t.anim.length,"+ lipsync:",u.length,")"),this.audioPlaylist.push({anim:a,audio:l}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio()}async synthesizeWithAzureTTS(t){const e=t.text.map(a=>a.word).join(" "),i=`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ue=require("react/jsx-runtime"),v=require("react"),Ge=require("three"),Ze=require("three/addons/controls/OrbitControls.js"),Xe=require("three/addons/loaders/GLTFLoader.js"),je=require("three/addons/loaders/DRACOLoader.js"),Pe=require("three/addons/loaders/FBXLoader.js"),Ye=require("three/addons/environments/RoomEnvironment.js"),Qe=require("three/addons/libs/stats.module.js");var He=typeof document<"u"?document.currentScript:null;function qe(U){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(U){for(const e in U)if(e!=="default"){const n=Object.getOwnPropertyDescriptor(U,e);Object.defineProperty(t,e,n.get?n:{enumerable:!0,get:()=>U[e]})}}return t.default=U,Object.freeze(t)}const y=qe(Ge);let m,le,ce;const H=[0,0,0,0],M=new y.Vector3,Se=new y.Vector3,se=new y.Vector3,we=new y.Vector3;new y.Plane;new y.Ray;new y.Euler;const ae=new y.Quaternion,Be=new y.Quaternion,pe=new y.Matrix4,ge=new y.Matrix4;new y.Vector3;const Ce=new y.Vector3(0,0,1),_e=new y.Vector3(1,0,0),Ke=new y.Vector3(0,1,0),Je=new y.Vector3(0,0,1);class $e{constructor(t=null){this.opt=Object.assign({warmupMs:2e3,sensitivityFactor:1,movementFactor:1,isExcludes:!0,isPivots:!0,isLimits:!0,helperBoneColor1:16711680,helperBoneColor2:16238028,helperLinkColor1:16711680,helperLinkColor2:255,helperExcludesColor:11184895},t||{}),this.scene=null,this.armature=null,this.config=[],this.data=[],this.dict={},this.objectsUpdate=[],this.helpers={isActive:!1,isShowAll:!1,points:{bones:[],pivots:[],object:null},lines:{bones:[],object:null},excludes:{bones:[],deltaLocals:[],radii:[],objects:[]}},this.running=!1,this.timerMs=0}getOptionValue(t){return this.opt[t]}setOptionValue(t,e){this.opt[t]=e,this.helpers.isActive&&this.showHelpers()}getBoneNames(){return this.data.map(t=>t.name)}getValue(t,e){if(this.scene===null)throw new Error("Dynamic bones has not been setup yet.");if(!this.dict.hasOwnProperty(t))throw new Error("Dynamic bone '"+t+"' not found.");const n=this.dict[t];let i;if(e==="type")i=n.type;else if(e==="stiffness")i=n.k.every(s=>s===n.k[0])?n.k[0]:[...n.k];else if(e==="damping")i=n.c.every(s=>s===n.c[0])?n.c[0]:[...n.c];else if(e==="external")i=n.ext<1?n.ext:null;else if(e==="limits")i=n.limits?.map(s=>s===null?null:[...s]);else if(e==="deltaLocal")i=n.dl?[...n.dl]:null;else if(e==="excludes")i=n.excludes?[...n.excludes.map(s=>{const o={bone:s.bone.name.slice(),radius:s.radius};return s.deltaLocal&&(o.deltaLocal=[...s.deltaLocal]),o})]:null;else if(e==="deltaWorld")i=n.dw?[...n.dw]:null;else if(e==="pivot")i=n.pivot;else if(e==="helper")i=n.helper;else throw new Error("Unsupported property '"+e+"'.");return i}setValue(t,e,n){if(this.scene===null)throw new Error("Dynamic bones has not been setup yet.");if(!this.dict.hasOwnProperty(t))throw new Error("Dynamic bone '"+t+"' not found.");const i=this.dict[t];if(e==="type"){if(!n)throw new Error("Parameter 'type' not set.");if(typeof n!="string")throw new Error("Type must be a string.");switch(n){case"point":i.isPoint=!0,i.isX=!0,i.isY=!0,i.isZ=!0,i.isT=!1;break;case"link":i.isPoint=!1,i.isX=!0,i.isY=!1,i.isZ=!0,i.isT=!1;break;case"mix1":i.isPoint=!1,i.isX=!0,i.isY=!0,i.isZ=!0,i.isT=!1;break;case"mix2":i.isPoint=!1,i.isX=!0,i.isY=!1,i.isZ=!0,i.isT=!0;break;case"full":i.isPoint=!1,i.isX=!0,i.isY=!0,i.isZ=!0,i.isT=!0;break;default:throw new Error("Unknown type'"+n+"'.")}i.type=n.slice()}else if(e==="stiffness"){if(!n)throw new Error("Parameter 'stiffness' not set.");if(!Number.isNaN(n)&&n>=0)i.k=Array(4).fill(n);else if(Array.isArray(n)&&n.length===4&&n.every(s=>s>=0))i.k=[...n];else throw new Error("Stiffness must be a non-negative number or an array of four non-negative numbers.")}else if(e==="damping"){if(!n)throw new Error("Parameter 'damping' not set.");if(!Number.isNaN(n)&&n>=0)i.c=Array(4).fill(n);else if(Array.isArray(n)&&n.length===4&&n.every(s=>s>=0))i.c=[...n];else throw new Error("Damping must be a non-negative number or an array of four non-negative numbers.")}else if(e==="external")if(n==null)i.ext=1;else if(!Number.isNaN(n)&&n>=0&&n<=1)i.ext=n;else throw new Error("External (if set) must be a number between [0,1].");else if(e==="limits")if(n==null)i.limits=null;else{if(!Array.isArray(n)||n.length!==4)throw new Error("Limits (if set) must null, or an array of four arrays.");if(!n.every(s=>s===null||Array.isArray(s)&&s.length===2&&(s[0]===null||!Number.isNaN(s[0]))&&(s[1]===null||!Number.isNaN(s))))throw new Error("Limit values must be null or numbers.");i.limits=[n[0]?[...n[0]]:null,n[1]?[...n[1]]:null,n[2]?[...n[2]]:null,n[3]?[...n[3]]:null]}else if(e==="excludes"){if(n==null)i.excludes=null;else{if(!Array.isArray(n))throw new Error("Excludes (if set) must null, or an array.");i.excludes=[],n.forEach((s,o)=>{if(!s.bone)throw new Error("Bone not specified in #"+o+" exclude.");if(typeof s.bone!="string"||s.bone.length===0)throw new Error("Bone name must be a non-empty string in #"+o+" exclude.");const l=this.armature.getObjectByName(s.bone);if(!l)throw new Error("Bone '"+s.bone+"' not found in #"+o+" exclude.");if(Number.isNaN(s.radius)&&s.radius>=0)throw new Error("Radius must be a non-negative number in #"+o+" exclude.");const c={bone:l,radius:s.radius,radiusSq:s.radius*s.radius,deltaLocal:null};if(s.deltaLocal){if(!Array.isArray(s.deltaLocal)||s.deltaLocal.length!==3||s.deltaLocal.some(r=>Number.isNaN(r)))throw new Error("deltaLocal must be an array of three numbers in #"+o+" exclude.");c.deltaLocal=[...s.deltaLocal]}i.excludes.push(c)})}this.showHelpers()}else if(e==="helper"){if(n==null)i.helper=null;else{if(n!==!1&&n!==!0)throw new Error("Helper, if set, must be false or true.");i.helper=n}this.showHelpers()}else if(e==="pivot")if(n==null)i.pivot=null;else{if(n!==!1&&n!==!0)throw new Error("Pivot, if set, must be false or true.");if(n===!0&&i.type===0)throw new Error("Point type bone can't be a pivot.");i.pivot=n}else if(e==="deltaLocal")if(n==null)i.dl=null;else{if(!Array.isArray(n)||n.length!==3)throw new Error("deltaLocal, is set, must be an array of three numbers.");if(!n.every(s=>!Number.isNaN(s)))throw new Error("deltaLocal values must be numbers.");i.dl=[...n]}else if(e==="deltaWorld")if(n==null)i.dw=null;else{if(!Array.isArray(n)||n.length!==3)throw new Error("deltaWorld, is set, must be an array of three values.");if(!n.every(s=>!Number.isNaN(s)))throw new Error("deltaWorld values must be numbers.");i.dw=[...n]}else throw new Error("Unsupported property "+e)}getConfig(){return this.data.map(t=>{const e={bone:t.name.slice()};return["type","stiffness","damping","external","deltaLocal","deltaWorld","limits","excludes","pivot","helper"].forEach(n=>{m=this.getValue(t.name,n),m&&(e[n]=m)}),e})}sortBones(){if(this.scene===null)throw new Error("Dynamic bones has not been setup yet.");let t=0;const e=new WeakMap;this.armature.traverse(o=>{e.has(o)||(e.set(o,t),t++)}),this.data.sort((o,l)=>e.get(o.bone)-e.get(l.bone)),this.data.forEach(o=>{m=this.dict[o.boneParent.name],m&&(m.children||(m.children=[]),m.children.push(o))}),this.objectsUpdate=[];const n=new WeakSet,i=o=>o.parent?.isBone?[o,...i(o.parent)]:[o],s=o=>{i(o).forEach(c=>{n.has(c)||(this.objectsUpdate.push(c),n.add(c))})};this.data.forEach(o=>{s(o.bone),o.excludes&&o.excludes.forEach(l=>{s(l.bone)})}),this.objectsUpdate.sort((o,l)=>e.get(o)-e.get(l))}setup(t,e,n){this.dispose();const i=(s,o)=>{if(!s)throw this.dispose(),new Error(o)};i(t?.isScene,"First parameter must be Scene."),this.scene=t,i(e?.isObject3D,"Second parameter must be the armature Object3D."),this.armature=e,i(Array.isArray(n),"Third parameter must be an array of bone configs."),this.config=n,this.config.forEach((s,o)=>{const l="Config item #"+o+": ";i(s.bone,l+"Bone not specified.");const c=s.bone;i(typeof c=="string"&&c.length>0,l+"Bone name must be a non-empty string.");const r=this.armature.getObjectByName(c);i(r,l+"Bone '"+c+"' not found."),i(r.parent?.isBone,l+"Bone must have a parent bone."),i(this.data.every(a=>a.bone!==r),l+"Bone '"+c+"' already exists."),r.updateMatrixWorld(!0);const u={name:c,bone:r,boneParent:r.parent,vBasis:r.position.clone(),vWorld:r.parent.getWorldPosition(M).clone(),qBasis:r.parent.quaternion.clone(),l:r.position.length(),p:[0,0,0,0],v:[0,0,0,0],a:[0,0,0,0],ev:[0,0,0,0],ea:[0,0,0,0]};u.boneParent.matrixWorld.decompose(M,ae,se),M.copy(Ce).applyQuaternion(ae).setY(0).normalize(),ae.premultiply(Be.setFromUnitVectors(Ce,M).invert()).normalize(),u.qWorldInverseYaw=ae.clone().normalize(),this.data.push(u),this.dict[c]=u;try{this.setValue(c,"type",s.type),this.setValue(c,"stiffness",s.stiffness),this.setValue(c,"damping",s.damping),this.setValue(c,"external",s.external),this.setValue(c,"limits",s.limits),this.setValue(c,"excludes",s.excludes),this.setValue(c,"deltaLocal",s.deltaLocal),this.setValue(c,"deltaWorld",s.deltaWorld),this.setValue(c,"pivot",s.pivot),this.setValue(c,"helper",s.helper)}catch(a){i(!1,l+a)}}),this.sortBones(),this.start()}update(t){if(!this.running)return;let e,n,i,s,o;for(this.timerMs+=t,t>1e3&&(this.timerMs=0),t/=1e3,e=0,i=this.objectsUpdate.length;e<i;e++)o=this.objectsUpdate[e],o.updateMatrix(),o.parent===null?o.matrixWorld.copy(o.matrix):o.matrixWorld.multiplyMatrices(o.parent.matrixWorld,o.matrix),o.matrixWorldNeedsUpdate=!1;for(e=0,i=this.data.length;e<i;e++){if(o=this.data[e],M.copy(o.vWorld),pe.copy(o.boneParent.matrixWorld),ge.copy(pe).invert(),o.vWorld.setFromMatrixPosition(pe),M.applyMatrix4(ge),M.length()>.5&&(console.info("Info: Unrealistic jump of "+M.length().toFixed(2)+" meters."),M.setLength(.5)),M.applyQuaternion(o.bone.quaternion),H[0]=M.x,H[1]=M.y,H[2]=-M.z,H[3]=M.length()/3,o.children)for(n=0,s=o.children.length;n<s;n++)m=o.children[n],H[0]-=m.v[0]*t/3,H[1]-=m.v[1]*t/3,H[2]+=m.v[2]*t/3,H[3]-=m.v[3]*t/3;if(m=this.opt.sensitivityFactor,H[0]*=o.ext*m,H[1]*=o.ext*m,H[2]*=o.ext*m,H[3]*=o.ext*m,o.isX&&(m=H[0]/t,o.ea[0]=(m-o.ev[0])/t,o.ev[0]=m,o.a[0]=-o.k[0]*o.p[0]-o.c[0]*o.v[0]-o.ea[0],o.p[0]+=o.v[0]*t+o.a[0]*t*t/2+H[0],m=o.v[0]+o.a[0]*t/2,m=-o.k[0]*o.p[0]-o.c[0]*m-o.ea[0],o.v[0]=o.v[0]+(m+o.a[0])*t/2),o.isY&&(m=H[1]/t,o.ea[1]=(m-o.ev[1])/t,o.ev[1]=m,o.a[1]=-o.k[1]*o.p[1]-o.c[1]*o.v[1]-o.ea[1],o.p[1]+=o.v[1]*t+o.a[1]*t*t/2+H[1],m=o.v[1]+o.a[1]*t/2,m=-o.k[1]*o.p[1]-o.c[1]*m-o.ea[1],o.v[1]=o.v[1]+(m+o.a[1])*t/2),o.isZ&&(m=H[2]/t,o.ea[2]=(m-o.ev[2])/t,o.ev[2]=m,o.a[2]=-o.k[2]*o.p[2]-o.c[2]*o.v[2]-o.ea[2],o.p[2]+=o.v[2]*t+o.a[2]*t*t/2+H[2],m=o.v[2]+o.a[2]*t/2,m=-o.k[2]*o.p[2]-o.c[2]*m-o.ea[2],o.v[2]=o.v[2]+(m+o.a[2])*t/2),o.isT&&(m=H[3]/t,o.ea[3]=(m-o.ev[3])/t,o.ev[3]=m,o.a[3]=-o.k[3]*o.p[3]-o.c[3]*o.v[3]-o.ea[3],o.p[3]+=o.v[3]*t+o.a[3]*t*t/2+H[3],m=o.v[3]+o.a[3]*t/2,m=-o.k[3]*o.p[3]-o.c[3]*m-o.ea[3],o.v[3]=o.v[3]+(m+o.a[3])*t/2),this.timerMs<this.opt.warmupMs&&(o.v[0]*=1e-4,o.p[0]*=1e-4,o.v[1]*=1e-4,o.p[1]*=1e-4,o.v[2]*=1e-4,o.p[2]*=1e-4,o.v[3]*=1e-4,o.p[3]*=1e-4),H[0]=o.p[0],H[1]=o.p[1],H[2]=o.p[2],H[3]=o.p[3],m=this.opt.movementFactor,H[0]*=m,H[1]*=m,H[2]*=m,H[3]*=m,o.dl&&(m=o.dl,H[0]+=m[0],H[1]+=m[1],H[2]+=m[2]),o.dw&&(m=o.dw,M.set(o.vBasis.x+H[0],o.vBasis.y+H[1],o.vBasis.z+H[2]),M.applyMatrix4(pe),M.x+=m[0],M.y+=m[1],M.z+=m[2],M.applyMatrix4(ge),H[0]+=M.x-o.vBasis.x,H[1]+=M.y-o.vBasis.y,H[2]+=M.z-o.vBasis.z),o.limits&&this.opt.isLimits&&(m=o.limits,m[0]&&(m[0][0]!==null&&H[0]<m[0][0]&&(H[0]=m[0][0]),m[0][1]!==null&&H[0]>m[0][1]&&(H[0]=m[0][1])),m[1]&&(m[1][0]!==null&&H[1]<m[1][0]&&(H[1]=m[1][0]),m[1][1]!==null&&H[1]>m[1][1]&&(H[1]=m[1][1])),m[2]&&(m[2][0]!==null&&H[2]<m[2][0]&&(H[2]=m[2][0]),m[2][1]!==null&&H[2]>m[2][1]&&(H[2]=m[2][1])),m[3]&&(m[3][0]!==null&&H[3]<m[3][0]&&(H[3]=m[3][0]),m[3][1]!==null&&H[3]>m[3][1]&&(H[3]=m[3][1]))),o.isPoint)o.bone.position.set(o.vBasis.x+H[0],o.vBasis.y+H[1],o.vBasis.z-H[2]);else if(o.boneParent.quaternion.copy(o.qBasis),o.pivot&&this.opt.isPivots&&(o.boneParent.updateWorldMatrix(!1,!1),o.boneParent.matrixWorld.decompose(M,ae,se),M.copy(Ce).applyQuaternion(ae).setY(0).normalize(),ae.premultiply(Be.setFromUnitVectors(Ce,M).invert()).normalize(),o.boneParent.quaternion.multiply(ae.invert()),o.boneParent.quaternion.multiply(o.qWorldInverseYaw)),o.isZ&&(m=Math.atan(H[0]/o.l),ae.setFromAxisAngle(Je,-m),o.boneParent.quaternion.multiply(ae)),o.isY&&(m=o.l/3,m=m*Math.tanh(H[1]/m),o.bone.position.setLength(o.l+m)),o.isX&&(m=Math.atan(H[2]/o.l),ae.setFromAxisAngle(_e,-m),o.boneParent.quaternion.multiply(ae)),o.isT&&(m=1.5*Math.tanh(H[3]*1.5),ae.setFromAxisAngle(Ke,-m),o.boneParent.quaternion.multiply(ae)),o.boneParent.updateWorldMatrix(!1,!0),o.excludes&&this.opt.isExcludes)for(n=0,s=o.excludes.length;n<s;n++)m=o.excludes[n],se.set(0,0,0),m.deltaLocal&&(se.x+=m.deltaLocal[0],se.y+=m.deltaLocal[1],se.z+=m.deltaLocal[2]),se.applyMatrix4(m.bone.matrixWorld),ge.copy(o.boneParent.matrixWorld).invert(),se.applyMatrix4(ge),M.copy(o.bone.position),!(M.distanceToSquared(se)>=m.radiusSq)&&(ce=M.length(),le=se.length(),!(le>m.radius+ce)&&(le<Math.abs(m.radius-ce)||(le=(le*le+ce*ce-m.radiusSq)/(2*le),se.normalize(),we.copy(se).multiplyScalar(le),le=Math.sqrt(ce*ce-le*le),M.subVectors(M,we).projectOnPlane(se).normalize().multiplyScalar(le),Se.subVectors(o.vBasis,we).projectOnPlane(se).normalize(),ce=Se.dot(M),ce<0&&(ce=Math.sqrt(le*le-ce*ce),Se.multiplyScalar(ce),M.add(Se)),M.add(we).normalize(),se.copy(o.bone.position).normalize(),ae.setFromUnitVectors(se,M),o.boneParent.quaternion.premultiply(ae),o.boneParent.updateWorldMatrix(!1,!0))))}this.helpers.isActive&&this.updateHelpers()}showHelpers(t){if(this.hideHelpers(),this.helpers.isShowAll=t===void 0?this.helpers.isShowAll:t===!0,m=this.helpers,this.data.forEach(e=>{(this.helpers.isShowAll||e.helper===!0)&&(m.points.bones.push(e.bone),m.points.pivots.push(e.pivot),e.type!==0&&m.lines.bones.push(e.bone),e.excludes&&e.excludes.forEach(n=>{let i=!1;for(let s=0;s<m.excludes.bones.length;s++)if(m.excludes.bones[s]===n.bone&&m.excludes.radii[s]===n.radius&&!(m.excludes.deltaLocals[s]===null&&n.deltaLocal!==null)&&!(m.excludes.deltaLocals[s]!==null&&n.deltaLocal===null)&&!(m.excludes.deltaLocals[s]!==null&&m.excludes.deltaLocals[s].some((o,l)=>o!==n.deltaLocal[l]))){i=!0;break}i||(m.excludes.bones.push(n.bone),m.excludes.radii.push(n.radius),m.excludes.deltaLocals.push(n.deltaLocal?[...n.deltaLocal]:null),m.excludes.objects.push(null))}))}),m=this.helpers.excludes,this.opt.isExcludes&&m.bones.length&&m.bones.forEach((e,n)=>{const i=new y.SphereGeometry(m.radii[n],6,6),s=new y.MeshBasicMaterial({depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0,wireframe:!0,color:this.opt.helperExcludesColor});m.objects[n]=new y.Mesh(i,s),m.objects[n].renderOrder=997,e.add(m.objects[n]),m.deltaLocals[n]&&m.objects[n].position.set(m.deltaLocals[n][0],m.deltaLocals[n][1],m.deltaLocals[n][2])}),m=this.helpers.points,m.bones.length){this.helpers.isActive=!0;const e=new y.BufferGeometry,n=m.bones.map(c=>[0,0,0]).flat();e.setAttribute("position",new y.Float32BufferAttribute(n,3));const i=new y.Color(this.opt.helperBoneColor1),s=new y.Color(this.opt.helperBoneColor2),o=m.pivots.map(c=>c&&this.opt.isPivots?[s.r,s.g,s.b]:[i.r,i.g,i.b]).flat();e.setAttribute("color",new y.Float32BufferAttribute(o,3));const l=new y.PointsMaterial({depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0,size:.2,vertexColors:!0});m.object=new y.Points(e,l),m.object.renderOrder=998,m.object.matrix=this.armature.matrixWorld,m.object.matrixAutoUpdate=!1,this.scene.add(m.object)}if(m=this.helpers.lines,m.bones.length){const e=new y.BufferGeometry,n=m.bones.map(c=>[0,0,0,0,0,0]).flat();e.setAttribute("position",new y.Float32BufferAttribute(n,3));const i=new y.Color(this.opt.helperLinkColor1),s=new y.Color(this.opt.helperLinkColor2),o=m.bones.map(c=>[i.r,i.g,i.b,s.r,s.g,s.b]).flat();e.setAttribute("color",new y.Float32BufferAttribute(o,3));const l=new y.LineBasicMaterial({vertexColors:!0,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0});m.object=new y.LineSegments(e,l),m.object.renderOrder=999,m.object.matrix=this.armature.matrixWorld,m.object.matrixAutoUpdate=!1,this.scene.add(m.object)}}updateHelpers(){if(m=this.helpers.points,m.bones.length){ge.copy(this.armature.matrixWorld).invert();const t=m.object.geometry.getAttribute("position");for(let e=0,n=m.bones.length;e<n;e++)pe.multiplyMatrices(ge,m.bones[e].matrixWorld),M.setFromMatrixPosition(pe),t.setXYZ(e,M.x,M.y,M.z);t.needsUpdate=!0,m.object.updateMatrixWorld()}if(m=this.helpers.lines,m.bones.length){ge.copy(this.armature.matrixWorld).invert();const t=m.object.geometry.getAttribute("position");for(let e=0,n=0,i=m.bones.length;e<i;e++,n+=2)pe.multiplyMatrices(ge,m.bones[e].matrixWorld),M.setFromMatrixPosition(pe),t.setXYZ(n,M.x,M.y,M.z),pe.multiplyMatrices(ge,m.bones[e].parent.matrixWorld),M.setFromMatrixPosition(pe),t.setXYZ(n+1,M.x,M.y,M.z);t.needsUpdate=!0,m.object.updateMatrixWorld()}}hideHelpers(){[this.helpers.points,this.helpers.lines].forEach(t=>{t.bones=[],t.object&&(this.scene.remove(t.object),t.object.geometry.dispose(),t.object.material.dispose(),t.object=null)}),m=this.helpers.excludes,m.objects.forEach((t,e)=>{t&&(m.bones[e].remove(t),t.geometry.dispose(),t.material.dispose())}),m.bones=[],m.deltaLocals=[],m.radii=[],m.objects=[],this.helpers.isActive=!1}start(){this.data.length&&(this.running=!0,this.timerMs=0,this.showHelpers())}stop(){this.running=!1,this.hideHelpers();for(let t=0,e=this.data.length;t<e;t++){const n=this.data[t];n.bone.position.copy(n.vBasis),n.boneParent.quaternion.copy(n.qBasis)}}dispose(){this.stop(),this.scene=null,this.armature=null,this.config=[],this.data=[],this.dict={},this.objectsUpdate=[],this.timerMs=0}}class et{constructor(t){this.audioContext=t,this.analyzer=null,this.dataArray=null,this.bufferLength=0}async analyzeAudio(t,e){const n=t.sampleRate,i=t.duration,s=t.getChannelData(0),o=this.extractAudioFeatures(s,n);return this.generateTimingData(o,e,i)}extractAudioFeatures(t,e){const n={energy:[],spectralCentroid:[],zeroCrossingRate:[],mfcc:[],onsets:[],phonemeBoundaries:[]},i=1024,s=512,o=Math.floor((t.length-i)/s)+1;for(let l=0;l<o;l++){const c=l*s,r=Math.min(c+i,t.length),u=t.slice(c,r),a=this.calculateEnergy(u);n.energy.push(a);const d=this.calculateSpectralCentroid(u);n.spectralCentroid.push(d);const h=this.calculateZeroCrossingRate(u);n.zeroCrossingRate.push(h);const g=this.calculateMFCC(u);n.mfcc.push(g)}return n.onsets=this.detectOnsets(n.energy),n.phonemeBoundaries=this.detectPhonemeBoundaries(n),n}calculateEnergy(t){let e=0;for(let n=0;n<t.length;n++)e+=t[n]*t[n];return e/t.length}calculateSpectralCentroid(t){const e=this.fft(t);let n=0,i=0;for(let s=0;s<e.length/2;s++){const o=Math.sqrt(e[s*2]*e[s*2]+e[s*2+1]*e[s*2+1]);n+=s*o,i+=o}return i>0?n/i:0}calculateZeroCrossingRate(t){let e=0;for(let n=1;n<t.length;n++)t[n]>=0!=t[n-1]>=0&&e++;return e/(t.length-1)}calculateMFCC(t){const e=this.fft(t),n=[];for(let i=0;i<13;i++){let s=0;for(let o=0;o<e.length/2;o++){const l=Math.sqrt(e[o*2]*e[o*2]+e[o*2+1]*e[o*2+1]);s+=l*Math.cos(Math.PI*i*(o+.5)/(e.length/2))}n.push(s)}return n}fft(t){const e=t.length,n=new Float32Array(e*2);for(let i=0;i<e;i++)n[i*2]=t[i],n[i*2+1]=0;for(let i=1,s=0;i<e;i++){let o=e>>1;for(;s&o;)s^=o,o>>=1;if(s^=o,i<s){const l=n[i*2],c=n[i*2+1];n[i*2]=n[s*2],n[i*2+1]=n[s*2+1],n[s*2]=l,n[s*2+1]=c}}for(let i=2;i<=e;i<<=1){const s=-2*Math.PI/i,o=Math.cos(s),l=Math.sin(s);for(let c=0;c<e;c+=i){let r=1,u=0;for(let a=0;a<i/2;a++){const d=n[(c+a)*2],h=n[(c+a)*2+1],g=n[(c+a+i/2)*2]*r-n[(c+a+i/2)*2+1]*u,x=n[(c+a+i/2)*2]*u+n[(c+a+i/2)*2+1]*r;n[(c+a)*2]=d+g,n[(c+a)*2+1]=h+x,n[(c+a+i/2)*2]=d-g,n[(c+a+i/2)*2+1]=h-x;const f=r*o-u*l,w=r*l+u*o;r=f,u=w}}}return n}detectOnsets(t){const e=[];let s=-.1;for(let o=1;o<t.length;o++){const l=t[o]-t[o-1],c=o*.023;l>.1&&c-s>.1&&(e.push(c),s=c)}return e}detectPhonemeBoundaries(t){const e=[],{energy:n,spectralCentroid:i,zeroCrossingRate:s}=t;for(let o=1;o<n.length;o++){const l=o*.023,c=Math.abs(n[o]-n[o-1]),r=Math.abs(i[o]-i[o-1]),u=Math.abs(s[o]-s[o-1]);c+r*.1+u*.5>.2&&e.push(l)}return e}generateTimingData(t,e,n){const i=e.toLowerCase().split(/\s+/);t.phonemeBoundaries,t.onsets;const s=[];let o=0;for(let c=0;c<i.length;c++){const r=i[c],u=this.estimateWordDuration(r,n/i.length);s.push({word:r,startTime:o,endTime:o+u,duration:u}),o+=u}const l=this.generateVisemeTimings(t,e,n);return{words:s,visemes:l,duration:n,features:t}}estimateWordDuration(t,e){const n=Math.max(.5,Math.min(2,t.length/5)),i=this.getWordComplexity(t);return e*n*i}getWordComplexity(t){const e=(t.match(/[bcdfghjklmnpqrstvwxyz]{2,}/g)||[]).length,n=(t.match(/[aeiou]{2,}/g)||[]).length;return 1+e*.2+n*.1}generateVisemeTimings(t,e,n){const i=[],s=t.phonemeBoundaries;t.onsets;const o=this.textToVisemes(e);let l=0,c=0;for(let r=0;r<s.length&&l<o.length;r++){const u=s[r],a=o[l],d=t.energy[Math.floor(u/.023)]||0,h=this.calculateVisemeDuration(a,d);i.push({viseme:a,startTime:c,endTime:c+h,duration:h,intensity:Math.min(1,d*2)}),c+=h,l++}for(;l<o.length;){const r=o[l],u=this.calculateVisemeDuration(r,.5);i.push({viseme:r,startTime:c,endTime:c+u,duration:u,intensity:.6}),c+=u,l++}return i}textToVisemes(t){const e={a:"aa",e:"E",i:"I",o:"O",u:"U",ae:"aa",ai:"aa",au:"O",ea:"E",ee:"E",ei:"E",ie:"I",oa:"O",oo:"U",ou:"U",b:"PP",p:"PP",m:"PP",f:"FF",v:"FF",th:"SS",s:"SS",z:"SS",sh:"SS",ch:"SS",d:"DD",t:"DD",n:"nn",l:"nn",k:"kk",g:"kk",ng:"kk",r:"RR",w:"RR",y:"I",h:"kk"},n=[],i=t.toLowerCase().replace(/[^a-z\s]/g,"").split(/\s+/);for(const s of i){let o=0;for(;o<s.length;){let l=!1;for(let c=3;c>=2;c--){const r=s.substr(o,c);if(e[r]){n.push(e[r]),o+=c,l=!0;break}}if(!l){const c=s[o];e[c]&&n.push(e[c]),o++}}}return n}calculateVisemeDuration(t,e){const i={aa:.15,E:.12,I:.1,O:.14,U:.13,PP:.08,FF:.1,SS:.12,DD:.11,kk:.09,nn:.1,RR:.11}[t]||.1,s=.5+e*.5;return i*s}}class tt{constructor(){this.rules={A:["[A] =aa"," [ARE] =aa RR"," [AR]O=aa RR","[AR]#=E RR"," ^[AS]#=E SS","[A]WA=aa","[AW]=aa"," :[ANY]=E nn I","[A]^+#=E","#:[ALLY]=aa nn I"," [AL]#=aa nn","[AGAIN]=aa kk E nn","#:[AG]E=I kk","[A]^+:#=aa",":[A]^+ =E","[A]^%=E"," [ARR]=aa RR","[ARR]=aa RR"," :[AR] =aa RR","[AR] =E","[AR]=aa RR","[AIR]=E RR","[AI]=E","[AY]=E","[AU]=aa","#:[AL] =aa nn","#:[ALS] =aa nn SS","[ALK]=aa kk","[AL]^=aa nn"," :[ABLE]=E PP aa nn","[ABLE]=aa PP aa nn","[ANG]+=E nn kk","[A]=aa"],B:[" [BE]^#=PP I","[BEING]=PP I I nn"," [BOTH] =PP O TH"," [BUS]#=PP I SS","[BUIL]=PP I nn","[B]=PP"],C:[" [CH]^=kk","^E[CH]=kk","[CH]=CH"," S[CI]#=SS aa","[CI]A=SS","[CI]O=SS","[CI]EN=SS","[C]+=SS","[CK]=kk","[COM]%=kk aa PP","[C]=kk"],D:["#:[DED] =DD I DD",".E[D] =DD","#^:E[D] =DD"," [DE]^#=DD I"," [DO] =DD U"," [DOES]=DD aa SS"," [DOING]=DD U I nn"," [DOW]=DD aa","[DU]A=kk U","[D]=DD"],E:["#:[E] =","'^:[E] ="," :[E] =I","#[ED] =DD","#:[E]D =","[EV]ER=E FF","[E]^%=I","[ERI]#=I RR I","[ERI]=E RR I","#:[ER]#=E","[ER]#=E RR","[ER]=E"," [EVEN]=I FF E nn","#:[E]W=","@[EW]=U","[EW]=I U","[E]O=I","#:&[ES] =I SS","#:[E]S =","#:[ELY] =nn I","#:[EMENT]=PP E nn DD","[EFUL]=FF U nn","[EE]=I","[EARN]=E nn"," [EAR]^=E","[EAD]=E DD","#:[EA] =I aa","[EA]SU=E","[EA]=I","[EIGH]=E","[EI]=I"," [EYE]=aa","[EY]=I","[EU]=I U","[E]=E"],F:["[FUL]=FF U nn","[F]=FF"],G:["[GIV]=kk I FF"," [G]I^=kk","[GE]T=kk E","SU[GGES]=kk kk E SS","[GG]=kk"," B#[G]=kk","[G]+=kk","[GREAT]=kk RR E DD","#[GH]=","[G]=kk"],H:[" [HAV]=I aa FF"," [HERE]=I I RR"," [HOUR]=aa EE","[HOW]=I aa","[H]#=I","[H]="],I:[" [IN]=I nn"," [I] =aa","[IN]D=aa nn","[IER]=I E","#:R[IED] =I DD","[IED] =aa DD","[IEN]=I E nn","[IE]T=aa E"," :[I]%=aa","[I]%=I","[IE]=I","[I]^+:#=I","[IR]#=aa RR","[IZ]%=aa SS","[IS]%=aa SS","[I]D%=aa","+^[I]^+=I","[I]T%=aa","#^:[I]^+=I","[I]^+=aa","[IR]=E","[IGH]=aa","[ILD]=aa nn DD","[IGN] =aa nn","[IGN]^=aa nn","[IGN]%=aa nn","[IQUE]=I kk","[I]=I"],J:["[J]=kk"],K:[" [K]N=","[K]=kk"],L:["[LO]C#=nn O","L[L]=","#^:[L]%=aa nn","[LEAD]=nn I DD","[L]=nn"],M:["[MOV]=PP U FF","[M]=PP"],N:["E[NG]+=nn kk","[NG]R=nn kk","[NG]#=nn kk","[NGL]%=nn kk aa nn","[NG]=nn","[NK]=nn kk"," [NOW] =nn aa","[N]=nn"],O:["[OF] =aa FF","[OROUGH]=E O","#:[OR] =E","#:[ORS] =E SS","[OR]=aa RR"," [ONE]=FF aa nn","[OW]=O"," [OVER]=O FF E","[OV]=aa FF","[O]^%=O","[O]^EN=O","[O]^I#=O","[OL]D=O nn","[OUGHT]=aa DD","[OUGH]=aa FF"," [OU]=aa","H[OU]S#=aa","[OUS]=aa SS","[OUR]=aa RR","[OULD]=U DD","^[OU]^L=aa","[OUP]=U OO","[OU]=aa","[OY]=O","[OING]=O I nn","[OI]=O","[OOR]=aa RR","[OOK]=U kk","[OOD]=U DD","[OO]=U","[O]E=O","[O] =O","[OA]=O"," [ONLY]=O nn nn I"," [ONCE]=FF aa nn SS","[ON'T]=O nn DD","C[O]N=aa","[O]NG=aa"," ^:[O]N=aa","I[ON]=aa nn","#:[ON] =aa nn","#^[ON]=aa nn","[O]ST =O","[OF]^=aa FF","[OTHER]=aa TH E","[OSS] =aa SS","#^:[OM]=aa PP","[O]=aa"],P:["[PH]=FF","[PEOP]=PP I PP","[POW]=PP aa","[PUT] =PP U DD","[P]=PP"],Q:["[QUAR]=kk FF aa RR","[QU]=kk FF","[Q]=kk"],R:[" [RE]^#=RR I","[R]=RR"],S:["[SH]=SS","#[SION]=SS aa nn","[SOME]=SS aa PP","#[SUR]#=SS E","[SUR]#=SS E","#[SU]#=SS U","#[SSU]#=SS U","#[SED] =SS DD","#[S]#=SS","[SAID]=SS E DD","^[SION]=SS aa nn","[S]S=",".[S] =SS","#:.E[S] =SS","#^:##[S] =SS","#^:#[S] =SS","U[S] =SS"," :#[S] =SS"," [SCH]=SS kk","[S]C+=","#[SM]=SS PP","#[SN]'=SS aa nn","[S]=SS"],T:[" [THE] =TH aa","[TO] =DD U","[THAT] =TH aa DD"," [THIS] =TH I SS"," [THEY]=TH E"," [THERE]=TH E RR","[THER]=TH E","[THEIR]=TH E RR"," [THAN] =TH aa nn"," [THEM] =TH E PP","[THESE] =TH I SS"," [THEN]=TH E nn","[THROUGH]=TH RR U","[THOSE]=TH O SS","[THOUGH] =TH O"," [THUS]=TH aa SS","[TH]=TH","#:[TED] =DD I DD","S[TI]#N=CH","[TI]O=SS","[TI]A=SS","[TIEN]=SS aa nn","[TUR]#=CH E","[TU]A=CH U"," [TWO]=DD U","[T]=DD"],U:[" [UN]I=I U nn"," [UN]=aa nn"," [UPON]=aa PP aa nn","@[UR]#=U RR","[UR]#=I U RR","[UR]=E","[U]^ =aa","[U]^^=aa","[UY]=aa"," G[U]#=","G[U]%=","G[U]#=FF","#N[U]=I U","@[U]=I","[U]=I U"],V:["[VIEW]=FF I U","[V]=FF"],W:[" [WERE]=FF E","[WA]S=FF aa","[WA]T=FF aa","[WHERE]=FF E RR","[WHAT]=FF aa DD","[WHOL]=I O nn","[WHO]=I U","[WH]=FF","[WAR]=FF aa RR","[WOR]^=FF E","[WR]=RR","[W]=FF"],X:[" [X]=SS","[X]=kk SS"],Y:["[YOUNG]=I aa nn"," [YOU]=I U"," [YES]=I E SS"," [Y]=I","#^:[Y] =I","#^:[Y]I=I"," :[Y] =aa"," :[Y]#=aa"," :[Y]^+:#=I"," :[Y]^#=I","[Y]=I"],Z:["[Z]=SS"]};const t={"#":"[AEIOUY]+",".":"[BDVGJLMNRWZ]","%":"(?:ER|E|ES|ED|ING|ELY)","&":"(?:[SCGZXJ]|CH|SH)","@":"(?:[TSRDLZNJ]|TH|CH|SH)","^":"[BCDFGHJKLMNPQRSTVWXZ]","+":"[EIY]",":":"[BCDFGHJKLMNPQRSTVWXZ]*"," ":"\\b"};Object.keys(this.rules).forEach(e=>{this.rules[e]=this.rules[e].map(n=>{const i=n.indexOf("["),s=n.indexOf("]"),o=n.indexOf("="),l=n.substring(0,i),c=n.substring(i+1,s),r=n.substring(s+1,o),u=n.substring(o+1),a={regex:"",move:0,visemes:[]};let d="";d+=[...l].map(g=>t[g]||g).join("");const h=[...c];return h[0]=h[0].toLowerCase(),d+=h.join(""),a.move=h.length,d+=[...r].map(g=>t[g]||g).join(""),a.regex=new RegExp(d),u.length&&u.split(" ").forEach(g=>{a.visemes.push(g)}),a})}),this.visemeDurations={aa:.95,E:.9,I:.92,O:.96,U:.95,PP:1.08,SS:1.23,TH:1,DD:1.05,FF:1,kk:1.21,nn:.88,RR:.88,DD:1.05,sil:1},this.specialDurations={" ":1,",":3,"-":.5,"'":.5},this.digits=["oh","one","two","three","four","five","six","seven","eight","nine"],this.ones=["","one","two","three","four","five","six","seven","eight","nine"],this.tens=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"],this.teens=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],this.decades={20:"twenties",30:"thirties",40:"forties",50:"fifties",60:"sixties",70:"seventies",80:"eighties",90:"nineties"},this.ordinals={1:"first",2:"second",3:"third",4:"fourth",5:"fifth",6:"sixth",7:"seventh",8:"eighth",9:"ninth",10:"tenth",11:"eleventh",12:"twelfth",13:"thirteenth",14:"fourteenth",15:"fifteenth",16:"sixteenth",17:"seventeeth",18:"eighteenth",19:"nineteenth",20:"twentieth",30:"thirtieth",40:"fortieth",50:"fiftieth",60:"sixtieth",70:"seventieth",80:"eightieth",90:"ninetieth"},this.symbols={"%":"percent","€":"euros","&":"and","+":"plus",$:"dollars"},this.symbolsReg=/[%€&\+\$]/g}convert_digit_by_digit(t){t=String(t).split("");let e="";for(let n=0;n<t.length;n++)e+=this.digits[t[n]]+" ";return e=e.substring(0,e.length-1),e}convert_sets_of_two(t){let e=String(t).substring(0,2),n=String(t).substring(2,4),i=this.convert_tens(e);return i+=" "+this.convert_tens(n),i}convert_millions(t){return t>=1e6?this.convert_millions(Math.floor(t/1e6))+" million "+this.convert_thousands(t%1e6):this.convert_thousands(t)}convert_thousands(t){return t>=1e3?this.convert_hundreds(Math.floor(t/1e3))+" thousand "+this.convert_hundreds(t%1e3):this.convert_hundreds(t)}convert_hundreds(t){return t>99?this.ones[Math.floor(t/100)]+" hundred "+this.convert_tens(t%100):this.convert_tens(t)}convert_tens(t){return t<10?(Number(t)!=0&&t.toString().startsWith("0")?"oh ":"")+this.ones[Number(t)]:t>=10&&t<20?this.teens[t-10]:(this.tens[Math.floor(t/10)]+" "+this.ones[t%10]).trim()}convertNumberToWords(t,e=!1){const n=parseFloat(t);if(t=="0")return"zero";if(t<0)return" minus "+this.convertNumberToWords(Math.abs(t).toString(),e).trim();if(n&&!Number.isInteger(n)){const i=n.toString().split(".");return this.convertNumberToWords(i[0],e).trim()+" point "+this.convert_digit_by_digit(i[1]).trim()}else return t.toString().startsWith("0")?this.convert_digit_by_digit(t).trim():!e&&(t<1e3&&t>99&&t%100!==0||t>1e4&&t<1e6)?this.convert_digit_by_digit(t).trim():!e&&(t>1e3&&t<2e3||t>2009&&t<3e3)?t%100!=0?this.convert_sets_of_two(t).trim():this.convert_tens(t.toString().substring(0,2)).trim()+" hundred":this.convert_millions(t).trim()}convertDecade(t){const e=parseInt(t),n=!isNaN(e)&&t.length===2,i=!isNaN(e)&&t.length>2&&e>0&&e<=3e3,s=i&&e%1e3===0?Math.floor(e/1e3):null,o=i&&!s?Math.floor(e/100):null,l=n||i?Math.floor(e%100/10)*10:null;let c=[];return s?c.push(this.convertNumberToWords(s).trim(),"thousands"):(o&&c.push(this.convertNumberToWords(o).trim()),l?c.push(this.decades[l]||this.convertNumberToWords(l).trim()+"s"):o?c.push("hundreds"):c.push(t)),c.join(" ")}convertOrdinal(t){if(this.ordinals.hasOwnProperty(t))return this.ordinals[t];const e=Math.floor(t/100),n=Math.floor(t%100/10)*10,i=t%10;let s=[];return e&&(s.push(this.convertNumberToWords(e).trim()),n||i?s.push("hundred"):s.push("hundredth")),n&&(i?s.push(this.convertNumberToWords(n).trim()):s.push(this.ordinals[n])),i&&s.push(this.ordinals[i]),s.join(" ")}preProcessText(t){let e=t.replace('/[#_*":;]/g',"");return e=e.replace(this.symbolsReg,n=>" "+this.symbols[n]+" "),/\d/.test(e)&&(e=e.replace(/\b(\d{2,4})[''']?\s?[sS](?=\s|[.,!?;:]|$)/g,(n,i)=>{const s=this.convertDecade(i);return s===i?n:s}),e=e.replace(/\b(\d+)\s*(st|nd|rd|th)(?=\s|[.,!?;:]|$)/gi,(n,i)=>this.convertOrdinal(Number(i))),e=e.replace(/\b(\w*?)(\d+)([A-Za-z]+)\b/g,(n,i,s,o)=>{const l=this.convertNumberToWords(s);return`${i}${l} ${o}`}).replace(/\b([A-Za-z]+)(\d+)(\w*?)\b/g,(n,i,s,o)=>{const l=this.convertNumberToWords(s);return`${i} ${l}${o}`}),e=e.replace(/-?(?:\d{1,3}(?:,\d{3})+|\d+)(\.\d+)?/g,(n,i)=>{let s=n,o=!1;return/,/.test(s)&&(s=s.replace(/,/g,""),o=!0),i&&(o=!0),this.convertNumberToWords(s,o)})),e=e.replace(/(\D)\1\1+/g,"$1$1").replaceAll(" "," ").normalize("NFD").replace(/[\u0300-\u036f]/g,"").normalize("NFC").trim(),e}wordsToVisemes(t){let e={words:t.toUpperCase(),visemes:[],times:[],durations:[],i:0},n=0;const i=[...e.words];for(;e.i<i.length;){const s=i[e.i],o=this.rules[s];if(o)for(let l=0;l<o.length;l++){const c=o[l];if((e.words.substring(0,e.i)+s.toLowerCase()+e.words.substring(e.i+1)).match(c.regex)){c.visemes.forEach(a=>{if(e.visemes.length&&e.visemes[e.visemes.length-1]===a){const d=.7*(this.visemeDurations[a]||1);e.durations[e.durations.length-1]+=d,n+=d}else{const d=this.visemeDurations[a]||1;e.visemes.push(a),e.times.push(n),e.durations.push(d),n+=d}}),e.i+=c.move;break}}else e.i++,n+=this.specialDurations[s]||0}return e}}const nt=Object.freeze(Object.defineProperty({__proto__:null,LipsyncEn:tt},Symbol.toStringTag,{value:"Module"}));class it{constructor(){this.rules={A:["[AH]=aa","[AU]=aa U","[AI]=aa I","[AE]=E","[A]H=aa","[A]U=aa U","[A]I=aa I"," [AN] =aa nn"," [AM] =aa PP","[ARR]=aa RR","[AR]=aa RR"," [ALS]=aa nn SS","[AL]=aa nn","[AUCH]=aa U kk","[ABER]=aa PP E RR","[A]=aa"],Ä:["[Ä]H=E","[ÄU]=O","[Ä]=E"],B:["[B]=PP"],C:["[CH]S=kk SS","[CH]=kk"," [CH]=kk","#[CH]=kk","[CK]=kk","[C]H=kk","[C]=kk"],D:[" [DAS] =DD aa SS"," [DEN] =DD E nn"," [DER] =DD E RR"," [DIE] =DD I"," [DU] =DD U"," [DURCH]=DD U RR kk","[D]=DD"],E:["[EI]=aa I","[EU]=O","[EH]=E"," [ER] =E RR"," [ES] =E SS"," [EIN] =aa I nn"," [EINE]=aa I nn aa","[ER]#=E","[ER]=E RR","[EN]#=aa nn","[E]=E"],F:["[F]=FF"],G:["[G]=kk"],H:[" [HAT] =I aa DD"," [HABEN]=I aa PP aa nn"," [HIER]=I I RR"," [HEUTE]=I O DD aa","[H]="],I:[" [ICH] =I kk"," [IHR] =I RR"," [IN] =I nn"," [IST] =I SS DD"," [IM] =I PP","[IE]=I","[IH]=I","[I]=I"],J:["[J]=I"],K:["[K]=kk"],L:["[L]=nn"],M:[" [MIT] =PP I DD"," [MAN] =PP aa nn"," [MEHR]=PP E RR"," [MICH]=PP I kk","[M]=PP"],N:[" [NICHT]=nn I kk DD"," [NUR] =nn U RR"," [NACH]=nn aa kk"," [NOCH]=nn aa kk","[NG]=nn kk","[N]=nn"],O:["[OO]=U","[OH]=O","[OU]=aa U"," [ODER]=O DD E RR"," [OHNE]=O nn aa","[Ö]=E","[O]=aa"],Ö:["[ÖH]=E","[Ö]=E"],P:["[PF]=FF FF","[PH]=FF","[P]=PP"],Q:["[QU]=kk FF","[Q]=kk"],R:["[R]=RR"],S:["[SCH]=SS","[SP]=SS PP","[ST]=SS DD","[SS]=SS","[S]=SS"],ß:["[ß]=SS"],T:["[TZ]=DD SS","[TH]=DD","[T]=DD"],U:[" [UND] =U nn DD"," [UM] =U PP"," [UNTER]=U nn DD E RR"," [UNS] =U nn SS","[UH]=U","[ÜH]=I U","[Ü]=I U","[U]=U"],Ü:["[ÜH]=I U","[Ü]=I U"],V:[" [VON] =FF aa nn"," [VOR] =FF aa RR"," [VIEL]=FF I nn","[V]=FF"],W:[" [WAS] =FF aa SS"," [WIR] =FF I RR"," [WIE] =FF I"," [WENN]=FF E nn"," [WILL]=FF I nn"," [WO] =FF aa"," [WIEDER]=FF I DD E RR","[W]=FF"],X:["[X]=kk SS"],Y:["[Y]=I"],Z:[" [ZU] =DD SS U"," [ZUM] =DD SS U PP"," [ZUR] =DD SS U RR"," [ZEIT]=DD SS aa I DD","[Z]=DD SS"]};const t={"#":"[AEIOUÄÖÜ]+",".":"[BDVGJLMNRWZ]","%":"(?:ER|E|ES|ED|ING|ELY|EN|TE|ST)","&":"(?:[SCGZXJ]|CH|SCH|TZ)","@":"(?:[TSRDLZNJ]|TH|CH|SCH)","^":"[BCDFGHJKLMNPQRSTVWXYZß]","+":"[EIY]",":":"[BCDFGHJKLMNPQRSTVWXYZß]*"," ":"\\b"};Object.keys(this.rules).forEach(e=>{this.rules[e]=this.rules[e].map(n=>{const i=n.indexOf("["),s=n.indexOf("]"),o=n.indexOf("="),l=n.substring(0,i),c=n.substring(i+1,s),r=n.substring(s+1,o),u=n.substring(o+1),a={regex:"",move:0,visemes:[]};let d="";d+=[...l].map(g=>t[g]||g).join("");const h=[...c];return h[0]=h[0].toLowerCase(),d+=h.join(""),a.move=h.length,d+=[...r].map(g=>t[g]||g).join(""),a.regex=new RegExp(d),u.length&&u.split(" ").forEach(g=>{a.visemes.push(g)}),a})}),this.visemeDurations={aa:1,E:.85,I:.9,O:1.05,U:1,PP:1.15,SS:1.2,TH:1,DD:1.1,FF:1.05,kk:1.25,nn:.85,RR:.9,sil:1},this.specialDurations={" ":1,",":3,"-":.5,"'":.5,".":4,"!":3,"?":3},this.digits=["null","eins","zwei","drei","vier","fünf","sechs","sieben","acht","neun"],this.ones=["","ein","zwei","drei","vier","fünf","sechs","sieben","acht","neun"],this.tens=["","","zwanzig","dreißig","vierzig","fünfzig","sechzig","siebzig","achtzig","neunzig"],this.teens=["zehn","elf","zwölf","dreizehn","vierzehn","fünfzehn","sechzehn","siebzehn","achtzehn","neunzehn"],this.symbols={"%":"prozent","€":"euro","&":"und","+":"plus",$:"dollar","=":"gleich","@":"at","#":"hashtag"},this.symbolsReg=/[%€&\+\$=@#]/g}convert_digit_by_digit(t){t=String(t).split("");let e="";for(let n=0;n<t.length;n++)e+=this.digits[t[n]]+" ";return e=e.substring(0,e.length-1),e}convert_millions(t){if(t>=1e6){const e=Math.floor(t/1e6),n=t%1e6;let i=this.convert_thousands(e);return i+=e===1?" million ":" millionen ",n>0&&(i+=this.convert_thousands(n)),i}else return this.convert_thousands(t)}convert_thousands(t){if(t>=1e3){const e=Math.floor(t/1e3),n=t%1e3;let i="";return e===1?i="eintausend":i=this.convert_hundreds(e)+"tausend",n>0&&(i+=this.convert_hundreds(n)),i}else return this.convert_hundreds(t)}convert_hundreds(t){if(t>99){const e=Math.floor(t/100),n=t%100;let i="";return e===1?i="einhundert":i=this.ones[e]+"hundert",n>0&&(i+=this.convert_tens(n)),i}else return this.convert_tens(t)}convert_tens(t){if(t<10)return this.ones[Number(t)]||"";if(t>=10&&t<20)return this.teens[t-10];{const e=Math.floor(t/10),n=t%10;return n===0?this.tens[e]:this.ones[n]+"und"+this.tens[e]}}convertNumberToWords(t){const e=String(t);return t=="0"?"null":e.startsWith("0")?this.convert_digit_by_digit(t):e.length===4&&(t<1e3||t>2100)?this.convert_digit_by_digit(t):this.convert_millions(Number(t))}preProcessText(t){return t.replace(/[#_*\":;]/g,"").replace(this.symbolsReg,e=>" "+this.symbols[e]+" ").replace(/(\d)\.(\d)/g,"$1 komma $2").replace(/(\d),(\d)/g,"$1 komma $2").replace(/\d+/g,this.convertNumberToWords.bind(this)).replace(/(\D)\1\1+/g,"$1$1").replace(/\s+/g," ").toLowerCase().trim()}wordsToVisemes(t){let e={words:t.toUpperCase(),visemes:[],times:[],durations:[],i:0},n=0;const i=[...e.words];for(;e.i<i.length;){const s=i[e.i],o=this.rules[s];if(o){let l=!1;for(let c=0;c<o.length;c++){const r=o[c];if((e.words.substring(0,e.i)+s.toLowerCase()+e.words.substring(e.i+1)).match(r.regex)){r.visemes.forEach(d=>{if(e.visemes.length&&e.visemes[e.visemes.length-1]===d){const h=.7*(this.visemeDurations[d]||1);e.durations[e.durations.length-1]+=h,n+=h}else{const h=this.visemeDurations[d]||1;e.visemes.push(d),e.times.push(n),e.durations.push(h),n+=h}}),e.i+=r.move,l=!0;break}}l||(e.i++,n+=this.specialDurations[s]||0)}else e.i++,n+=this.specialDurations[s]||0}return e}}const ot=Object.freeze(Object.defineProperty({__proto__:null,LipsyncDe:it},Symbol.toStringTag,{value:"Module"}));class st{constructor(){this.rules={A:["[AN]C=aa nn","[AN]G=aa nn","[AN]T=aa nn","[AN]D=aa nn","[AN] =aa nn","[AN]$=aa nn","[AM]P=aa nn","[AM]B=aa nn","[AM] =aa nn","[AM]$=aa nn","[AI]N=E nn","[AIM]=E nn","[AIN]=E nn","[AU]=O","[AUX]=O","[AUT]=O","[AI]=E","[AY]=E","[A]=aa"],À:["[À]=aa"],Â:["[Â]=aa"],B:[" [B] =PP","[BB]=PP","[B]=PP"],C:["[C]E=SS","[C]I=SS","[C]Y=SS","[C]È=SS","[C]É=SS","[C]Ê=SS","[CH]=SS","[C]A=kk","[C]O=kk","[C]U=kk","[C]L=kk","[C]R=kk","[CK]=kk","[C]=kk"],Ç:["[Ç]=SS"],D:["[D]=DD"],E:["[EN]C=aa nn","[EN]T=aa nn","[EN]D=aa nn","[EN] =aa nn","[EN]$=aa nn","[EM]P=aa nn","[EM]B=aa nn","[EM] =aa nn","[EM]$=aa nn","[EAU]=O","[EAU]X=O","[EU]=U","[EUX]=U","[EUR]=U RR","[EI]=E","[EIN]=E nn","[ER] =E","[ER]$=E","[EZ] =E","[EZ]$=E","[ED] =E","[ED]$=E"," [E] =","[E] =","[E]$=","[E]S =","[E]S$=","[E]NT =","[E]NT$=","[È]=E","[É]=E","[Ê]=E","[Ë]=E","[E]=E"],È:["[È]=E"],É:["[É]=E"],Ê:["[Ê]=E"],Ë:["[Ë]=E"],F:["[FF]=FF","[F]=FF","[PH]=FF"],G:["[G]E=SS","[G]I=SS","[G]Y=SS","[G]È=SS","[G]É=SS","[G]Ê=SS","[GN]=nn I","[GN]E=nn","[GN]A=nn aa","[GN]O=nn O","[GU]E=kk","[GU]I=kk","[GU]A=kk FF aa","[GU]O=kk FF O","[G]A=kk","[G]O=kk","[G]U=kk","[G]L=kk","[G]R=kk","[GG]=kk","[G]=kk"],H:["[H]="],I:["[IN]C=E nn","[IN]T=E nn","[IN]D=E nn","[IN] =E nn","[IN]$=E nn","[IM]P=E nn","[IM]B=E nn","[IM] =E nn","[IM]$=E nn","[IEN]=I E nn","[IER]=I E","[IEU]=I U","[IEZ]=I E","[ILL]E=I","[ILLE]=I","[ILL]=I","[Î]=I","[Ï]=I","[I]=I"],Î:["[Î]=I"],Ï:["[Ï]=I"],J:["[J]=SS"],K:["[K]=kk"],L:["[LL]E=","[LLE]=","[LL]A=I aa","[LL]O=I O","[LL]U=I U","[LL]I=I","[LL]=I","[L]=nn"],M:["[MM]=PP","[M]=PP"],N:["[NN]=nn","[N]=nn"],O:["[ON]C=O nn","[ON]T=O nn","[ON]D=O nn","[ON] =O nn","[ON]$=O nn","[OM]P=O nn","[OM]B=O nn","[OM] =O nn","[OM]$=O nn","[OI]N=FF E nn","[OI]G=FF aa","[OI]S=FF aa","[OI]T=FF aa","[OI]X=FF aa","[OI]=FF aa","[OU]=U","[OÙ]=U","[OÛ]=U","[OEU]=U","[OEUR]=U RR","[OUGH]=U FF","[OUGH]T=U","[Ô]=O","[O]=O"],Ô:["[Ô]=O"],Ù:["[Ù]=U"],Û:["[Û]=U"],P:["[PH]=FF","[PP]=PP","[P]=PP"],Q:["[QU]=kk","[Q]=kk"],R:["[RR]=RR","[R]=RR"],S:["#[S]#=SS"," [S]=SS","[SS]=SS","[S] =","[S]$=","[SC]E=SS","[SC]I=SS","[SC]Y=SS","[S]=SS"],T:["[TI]A=SS I aa","[TI]E=SS I E","[TI]O=SS I O","[TI]ON=SS I O nn","[TH]=DD","[TT]=DD","[T] =","[T]$=","[T]=DD"],U:["[UN]C=U nn","[UN]T=U nn","[UN]D=U nn","[UN] =U nn","[UN]$=U nn","[UM]=U nn","[UE]=I","[UEI]=I E","[UEIL]=I I","[UILL]=I","[Ù]=U","[Û]=U","[Ü]=I U","[U]=I U"],Ü:["[Ü]=I U"],V:["[V]=FF"],W:["[W]=FF"],X:["[X] =","[X]$=","#[X]#=kk SS"," [X]=kk SS","[X]=kk SS"],Y:["[Y]=I"," [Y]=I","[YE]=I E","[YA]=I aa","[YO]=I O","[YU]=I U"],Z:["[Z]=SS"]};const t={"#":"[AEIOUYÀÂÈÉÊËÎÏÔÙÛÜ]+",".":"[BDVGJLMNRWZ]","%":"(?:ER|E|ES|ÉS|ÈS|ÊS|ENT|MENT|TION|SION)","&":"(?:[SCGZXJ]|CH|SH|GN)","@":"(?:[TSRDLZNJ]|TH|CH|SH|GN)","^":"[BCDFGHJKLMNPQRSTVWXZÇ]+","+":"[EIYÈÉÊËÎÏ]",":":"[BCDFGHJKLMNPQRSTVWXZÇ]*"," ":"\\b",$:"$"};Object.keys(this.rules).forEach(e=>{this.rules[e]=this.rules[e].map(n=>{const i=n.indexOf("["),s=n.indexOf("]"),o=n.indexOf("="),l=n.substring(0,i),c=n.substring(i+1,s),r=n.substring(s+1,o),u=n.substring(o+1),a={regex:"",move:0,visemes:[]};let d="";d+=[...l].map(g=>t[g]||g).join("");const h=[...c];return h[0]=h[0].toLowerCase(),d+=h.join(""),a.move=h.length,d+=[...r].map(g=>t[g]||g).join(""),a.regex=new RegExp(d,"i"),u.length&&u.split(" ").forEach(g=>{g&&a.visemes.push(g)}),a})}),this.visemeDurations={aa:1,E:.95,I:.9,O:1.05,U:.95,PP:1.1,SS:1.25,TH:1,DD:1.05,FF:1,kk:1.2,nn:.88,RR:1.15,sil:1},this.specialDurations={" ":1,",":2.5,".":3.5,";":2.8,":":2.2,"!":3.2,"?":3.2,"-":.8,"'":.3,'"':.3,"(":1.5,")":1.5},this.digits=["zéro","un","deux","trois","quatre","cinq","six","sept","huit","neuf"],this.ones=["","un","deux","trois","quatre","cinq","six","sept","huit","neuf"],this.teens=["dix","onze","douze","treize","quatorze","quinze","seize","dix-sept","dix-huit","dix-neuf"],this.tens=["","dix","vingt","trente","quarante","cinquante","soixante","soixante-dix","quatre-vingts","quatre-vingt-dix"],this.symbols={"%":"pourcent","€":"euros","&":"et","+":"plus",$:"dollars","=":"égale","@":"arobase","#":"dièse","°":"degrés"},this.symbolsReg=/[%€&\+\$=@#°]/g}convert_digit_by_digit(t){t=String(t).split("");let e="";for(let n=0;n<t.length;n++)e+=this.digits[t[n]]+" ";return e=e.substring(0,e.length-1),e}convert_tens(t){if(t<10)return this.ones[t]||"";if(t>=10&&t<20)return this.teens[t-10];if(t>=70&&t<80){const e=t-60;return e===11?"soixante et onze":"soixante-"+this.teens[e-10]}else if(t>=90){const e=t-80;return e===11?"quatre-vingt-onze":"quatre-vingt-"+this.teens[e-10]}else{const e=Math.floor(t/10),n=t%10;return e===8&&n===0?"quatre-vingts":e===8?"quatre-vingt-"+this.ones[n]:(e===2||e===3||e===4||e===5||e===6)&&n===1?this.tens[e]+" et un":n===0?this.tens[e]:this.tens[e]+"-"+this.ones[n]}}convert_hundreds(t){if(t>=100){const e=Math.floor(t/100),n=t%100;let i="";return e===1?i="cent":(i=this.ones[e]+" cent",n===0&&(i+="s")),n>0&&(i+=" "+this.convert_tens(n)),i}else return this.convert_tens(t)}convert_thousands(t){if(t>=1e3){const e=Math.floor(t/1e3),n=t%1e3;let i="";return e===1?i="mille":i=this.convert_hundreds(e)+" mille",n>0&&(i+=" "+this.convert_hundreds(n)),i}else return this.convert_hundreds(t)}convert_millions(t){if(t>=1e6){const e=Math.floor(t/1e6),n=t%1e6;let i="";return e===1?i="un million":i=this.convert_hundreds(e)+" millions",n>0&&(i+=" "+this.convert_thousands(n)),i}else return this.convert_thousands(t)}convertNumberToWords(t){const e=String(t);return t==="0"||t===0?"zéro":e.startsWith("0")?this.convert_digit_by_digit(t):this.convert_millions(Number(t))}preProcessText(t){return t.replace(/[#_*\":;]/g,"").replace(this.symbolsReg,e=>" "+this.symbols[e]+" ").replace(/(\d)[,.](\d)/g,"$1 virgule $2").replace(/\d+/g,this.convertNumberToWords.bind(this)).replace(/(\D)\1\1+/g,"$1$1").replace(/\s+/g," ").replace(/'/g,"'").trim()}wordsToVisemes(t){let e={words:t.toUpperCase(),visemes:[],times:[],durations:[],i:0},n=0;const i=[...e.words];for(;e.i<i.length;){const s=i[e.i],o=this.rules[s];if(o){let l=!1;for(let c=0;c<o.length;c++){const r=o[c];if((e.words.substring(0,e.i)+s.toLowerCase()+e.words.substring(e.i+1)).match(r.regex)){r.visemes.forEach(d=>{if(e.visemes.length&&e.visemes[e.visemes.length-1]===d){const h=.7*(this.visemeDurations[d]||1);e.durations[e.durations.length-1]+=h,n+=h}else{const h=this.visemeDurations[d]||1;e.visemes.push(d),e.times.push(n),e.durations.push(h),n+=h}}),e.i+=r.move,l=!0;break}}l||(e.i++,n+=this.specialDurations[s]||0)}else e.i++,n+=this.specialDurations[s]||0}return e}}const at=Object.freeze(Object.defineProperty({__proto__:null,LipsyncFr:st},Symbol.toStringTag,{value:"Module"}));class rt{constructor(){this.visemes={a:"aa",e:"E",i:"I",o:"O",u:"U",y:"U",ä:"aa",ö:"O",å:"O",b:"PP",c:"SS",d:"DD",f:"FF",g:"kk",h:"kk",j:"I",k:"kk",l:"nn",m:"PP",n:"nn",p:"PP",q:"kk",r:"RR",s:"SS",t:"DD",v:"FF",w:"FF",x:"SS",z:"SS"},this.visemeDurations={aa:.95,E:.9,I:.92,O:.96,U:.95,PP:1.08,SS:1.23,DD:1.05,FF:1,kk:1.21,nn:.88,RR:.88,DD:1.05,sil:1},this.specialDurations={" ":1,",":3,"-":.5},this.numbers=["nolla","yksi","kaksi","kolme","neljä","viisi","kuusi","seitsemän","kahdeksan","yhdeksän","kymmenen","yksitoista","kaksitoista","kolmetoista","neljätoista","viisitoista","kuusitoista","seitsemäntoista","kahdeksantoista","yhdeksäntoista"],this.symbols={"%":"prosenttia","€":"euroa","&":"ja","+":"plus",$:"dollaria"},this.symbolsReg=/[%€&\+\$]/g}numberToFinnishWords(t){const e=[];let n=parseFloat(t);if(n===void 0)return t;let i=(s,o,l,c,r)=>{if(s<o)return s;const u=Math.floor(s/o);return e.push(l+(u===1?c:this.numberToFinnishWords(u.toString())+r)),s-u*o};if(n<0&&(e.push("miinus "),n=Math.abs(n)),n=i(n,1e9," ","miljardi"," miljardia"),n=i(n,1e6," ","miljoona"," miljoonaa"),n=i(n,1e3,"","tuhat","tuhatta"),n=i(n,100," ","sata","sataa"),n>20&&(n=i(n,10,"","","kymmentä")),n>=1){let s=Math.floor(n);e.push(this.numbers[s]),n-=s}if(n>=0&&Math.abs(parseFloat(t))<1&&e.push("nolla"),n>0){let s=t.split(".");if(s.length>1){e.push(" pilkku");let o=[...s[s.length-1]];for(let l=0;l<o.length;l++)e.push(" "+this.numbers[o[l]])}}return e.join("").trim()}preProcessText(t){return t.replace(/[#_*\'\":;]/g,"").replace(this.symbolsReg,e=>" "+this.symbols[e]+" ").replace(/(\d)\,(\d)/g,"$1 pilkku $2").replace(/\d+/g,this.numberToFinnishWords.bind(this)).replaceAll(" "," ").normalize("NFD").replace(/[\u0300-\u0307\u0309\u030b-\u036f]/g,"").normalize("NFC").trim()}wordsToVisemes(t){let e={words:t,visemes:[],times:[],durations:[]},n=0;const i=[...t];for(let s=0;s<i.length;s++){const o=this.visemes[i[s].toLowerCase()];if(o)if(e.visemes.length&&e.visemes[e.visemes.length-1]===o){const l=.7*(this.visemeDurations[o]||1);e.durations[e.durations.length-1]+=l,n+=l}else{const l=this.visemeDurations[o]||1;e.visemes.push(o),e.times.push(n),e.durations.push(l),n+=l}else n+=this.specialDurations[i[s]]||0}return e}}const lt=Object.freeze(Object.defineProperty({__proto__:null,LipsyncFi:rt},Symbol.toStringTag,{value:"Module"}));class ut{constructor(){this.visemes={a:"aa",ą:"O",e:"E",ę:"E",ė:"E",i:"I",į:"I",o:"O",u:"U",ū:"U",ų:"U",y:"I",b:"PP",c:"SS",č:"SS",d:"DD",f:"FF",g:"kk",h:"kk",j:"I",k:"kk",l:"nn",m:"PP",n:"nn",p:"PP",q:"kk",r:"RR",s:"SS",š:"CH",t:"DD",v:"FF",w:"FF",x:"SS",z:"SS",ž:"SS"},this.durations={a:.95,ą:1.5,e:.9,ę:1.5,ė:1.5,i:.92,į:1.5,o:.96,u:.95,ū:1.5,ų:1.5,y:1.5,b:1.08,c:1.23,d:1.05,f:1,g:1.21,h:1.21,j:.92,k:1.21,l:.88,m:1.08,n:.88,p:1.08,q:1.21,r:.88,s:1.23,š:1.23,t:1.05,v:1,w:1,x:1.23,z:1.23,ž:1.23},this.pauses={" ":1,",":3,"-":.5},this.numbers=["nulis","vienas","du","trys","keturi","penki","šeši","septyni","aštuoni","devyni","dešimt","vienuolika","dvylika","trylika","keturiolika","penkiolika","šešiolika","septyniolika","aštuoniolika","devyniolika"],this.tens=[this.numbers[0],this.numbers[10],"dvidešimt","trisdešimt","keturiasdešimt","penkiasdešimt","šešiasdešimt","septyniasdešimt","aštuoniasdešimt","devyniasdešimt"]}numberToLithuanianWords(t){const e=[];let n=parseFloat(t);if(n===void 0)return t;let i=(s,o,l,c,r)=>{if(s<o)return s;const u=Math.floor(s/o);return u===1?e.push(this.numbers[1]):e.push(this.numberToLithuanianWords(u.toString())),u%10===1?e.push(l):u%10===0||u%100>10&&u%100<20?e.push(r):e.push(c),s-u*o};n<0&&(e.push("minus"),n=Math.abs(n)),n=i(n,1e9,"milijardas","milijardai","milijardų"),n=i(n,1e6,"milijonas","milijonai","milijonų"),n=i(n,1e3,"tūkstantis","tūkstančiai","tūkstančių"),n=i(n,100,"šimtas","šimtai","šimtų");for(let s=this.tens.length-1;s>=1;s--)if(n>=10*s){e.push(this.tens[s]),n=n-10*s;break}if(n>=1){let s=Math.floor(n);e.push(this.numbers[s]),n-=s}if(n>=0&&Math.abs(parseFloat(t))<1&&e.push(this.numbers[0]),n>0){let s=t.split(".");if(s.length>1){e.push("kablelis");let o=[...s[s.length-1]];for(let l=0;l<o.length;l++)e.push(this.numbers[o[l]])}}return e.join(" ").trim()}preProcessText(t){return t.replace(`/[#_*'":;]/g`,"").replaceAll("0 %","0 procentų ").replaceAll("1 %","1 procentas ").replaceAll("%"," procentai ").replaceAll("0 €","0 eurų ").replaceAll("1 €","1 euras ").replaceAll("€"," eurai ").replaceAll("0 $","0 dolerių ").replaceAll("1 $","1 doleris ").replaceAll("$"," doleriai ").replaceAll("&"," ir ").replaceAll("+"," pliusas ").replace(/(\d)\,(\d)/g,"$1 kablelis $2").replace(/\d+/g,this.numberToLithuanianWords.bind(this)).replace(/(\D)\1\1+/g,"$1$1").replaceAll(" "," ").normalize("NFD").replace(/[\u0300-\u0303\u0305\u0306\u0308-\u0327\u0329-\u036f]/g,"").normalize("NFC").trim()}wordsToVisemes(t){let e={words:t,visemes:[],times:[],durations:[]},n=0;const i=[...t];for(let s=0;s<i.length;s++){const o=i[s].toLowerCase(),l=this.visemes[o];if(l)if(e.visemes.length&&e.visemes[e.visemes.length-1]===l){const c=.7*(this.durations[o]||1);e.durations[e.durations.length-1]+=c,n+=c}else{const c=this.durations[o]||1;e.visemes.push(l),e.times.push(n),e.durations.push(c),n+=c}else n+=this.pauses[i[s]]||0}return e}}const ct=Object.freeze(Object.defineProperty({__proto__:null,LipsyncLt:ut},Symbol.toStringTag,{value:"Module"})),ht=new URL("data:text/javascript;base64,Y2xhc3MgUGxheWJhY2tXb3JrbGV0IGV4dGVuZHMgQXVkaW9Xb3JrbGV0UHJvY2Vzc29yIHsKICBzdGF0aWMgRlNNID0gewogICAgSURMRTogMCwKICAgIFBMQVlJTkc6IDEsCiAgfTsKCiAgY29uc3RydWN0b3Iob3B0aW9ucykgewogICAgc3VwZXIoKTsKICAgIHRoaXMucG9ydC5vbm1lc3NhZ2UgPSB0aGlzLmhhbmRsZU1lc3NhZ2UuYmluZCh0aGlzKTsKCiAgICB0aGlzLl9zYW1wbGVSYXRlID0gb3B0aW9ucz8ucHJvY2Vzc29yT3B0aW9ucz8uc2FtcGxlUmF0ZSB8fCBzYW1wbGVSYXRlOwogICAgdGhpcy5fc2NhbGUgPSAxIC8gMzI3Njg7IC8vIFBDTTE2IC0+IGZsb2F0CgogICAgLy8gU2lsZW5jZSBkZXRlY3Rpb24gdGhyZXNob2xkICgxIHNlY29uZCkgYXMgYSBmYWxsYmFjayBzYWZldHkgbmV0CiAgICBjb25zdCBzaWxlbmNlRHVyYXRpb25TZWNvbmRzID0gMS4wOwogICAgdGhpcy5fc2lsZW5jZVRocmVzaG9sZEJsb2NrcyA9IE1hdGguY2VpbCgodGhpcy5fc2FtcGxlUmF0ZSAqIHNpbGVuY2VEdXJhdGlvblNlY29uZHMpIC8gMTI4KTsKCiAgICAvLyBNZXRyaWNzIGNvbmZpZ3VyYXRpb24gdmlhIG9wdGlvbnMKICAgIGNvbnN0IG1ldHJpY3NDZmcgPSBvcHRpb25zPy5wcm9jZXNzb3JPcHRpb25zPy5tZXRyaWNzIHx8IHt9OwogICAgdGhpcy5fbWV0cmljc0VuYWJsZWQgPSBtZXRyaWNzQ2ZnLmVuYWJsZWQgIT09IGZhbHNlOwogICAgY29uc3QgaW50ZXJ2YWxIeiA9ICh0eXBlb2YgbWV0cmljc0NmZy5pbnRlcnZhbEh6ID09PSAibnVtYmVyIiAmJiBtZXRyaWNzQ2ZnLmludGVydmFsSHogPiAwKQogICAgICA/IG1ldHJpY3NDZmcuaW50ZXJ2YWxIeiA6IDI7CiAgICAvLyBNZXRyaWNzIHN0YXRlIChsb3ctb3ZlcmhlYWQpCiAgICB0aGlzLl9mcmFtZXNQcm9jZXNzZWQgPSAwOwogICAgdGhpcy5fdW5kZXJydW5CbG9ja3MgPSAwOwogICAgdGhpcy5fbWF4UXVldWVTYW1wbGVzID0gMDsKICAgIHRoaXMuX2xhc3RNZXRyaWNzU2VudEF0RnJhbWUgPSAwOwogICAgLy8gQ29udmVydCB0byBmcmFtZXMgYmV0d2VlbiByZXBvcnRzCiAgICB0aGlzLl9tZXRyaWNzSW50ZXJ2YWxGcmFtZXMgPSBNYXRoLm1heCgxMjgsIE1hdGgucm91bmQodGhpcy5fc2FtcGxlUmF0ZSAvIGludGVydmFsSHopKTsKCiAgICB0aGlzLnJlc2V0KCk7CiAgfQoKICAvKioKICAgKiBSZXNldHMgdGhlIHdvcmtsZXQgdG8gaXRzIGluaXRpYWwgSURMRSBzdGF0ZS4KICAgKi8KICByZXNldCgpIHsKICAgIHRoaXMuX2J1ZmZlclF1ZXVlID0gW107CiAgICB0aGlzLl9jdXJyZW50Q2h1bmsgPSBudWxsOwogICAgdGhpcy5fY3VycmVudENodW5rT2Zmc2V0ID0gMDsKICAgIHRoaXMuX3N0YXRlID0gUGxheWJhY2tXb3JrbGV0LkZTTS5JRExFOwoKICAgIHRoaXMuX25vTW9yZURhdGFSZWNlaXZlZCA9IGZhbHNlOwogICAgdGhpcy5fc2lsZW5jZUZyYW1lc0NvdW50ID0gMDsKICAgIHRoaXMuX2hhc1NlbnRFbmRlZCA9IGZhbHNlOwogICAgLy8gUmVzZXQgbWF4IHF1ZXVlIHRyYWNrZXIgb25seSB3aGVuIGdvaW5nIGlkbGUKICAgIHRoaXMuX21heFF1ZXVlU2FtcGxlcyA9IDA7CiAgfQoKICBoYW5kbGVNZXNzYWdlKGV2ZW50KSB7CiAgICBjb25zdCB7IHR5cGUsIGRhdGEgfSA9IGV2ZW50LmRhdGE7CgogICAgLy8gSU5URVJSVVBUOiBUaGUgbWFpbiB0aHJlYWQgd2FudHMgdG8gc3RvcCBpbW1lZGlhdGVseS4KICAgIGlmICh0eXBlID09PSAic3RvcCIpIHsKICAgICAgdGhpcy5yZXNldCgpOwogICAgICAvLyBTZW5kIGZpbmFsIG1ldHJpY3Mgc2hvd2luZyBjbGVhcmVkIHN0YXRlCiAgICAgIGlmICh0aGlzLl9tZXRyaWNzRW5hYmxlZCkgewogICAgICAgIHRyeSB7CiAgICAgICAgICB0aGlzLnBvcnQucG9zdE1lc3NhZ2UoewogICAgICAgICAgICB0eXBlOiAibWV0cmljcyIsCiAgICAgICAgICAgIGRhdGE6IHsKICAgICAgICAgICAgICBzdGF0ZTogUGxheWJhY2tXb3JrbGV0LkZTTS5JRExFLAogICAgICAgICAgICAgIHF1ZXVlZFNhbXBsZXM6IDAsCiAgICAgICAgICAgICAgcXVldWVkTXM6IDAsCiAgICAgICAgICAgICAgbWF4UXVldWVkTXM6IE1hdGgucm91bmQoKHRoaXMuX21heFF1ZXVlU2FtcGxlcyAvIHRoaXMuX3NhbXBsZVJhdGUpICogMTAwMCksCiAgICAgICAgICAgICAgdW5kZXJydW5CbG9ja3M6IHRoaXMuX3VuZGVycnVuQmxvY2tzLAogICAgICAgICAgICAgIGZyYW1lc1Byb2Nlc3NlZDogdGhpcy5fZnJhbWVzUHJvY2Vzc2VkCiAgICAgICAgICAgIH0KICAgICAgICAgIH0pOwogICAgICAgIH0gY2F0Y2ggKF8pIHsgfQogICAgICB9CiAgICAgIHJldHVybjsKICAgIH0KCiAgICAvLyBNYWluIHRocmVhZCBoYXMgc2lnbmFsZWQgdGhhdCBubyBtb3JlIGF1ZGlvIGNodW5rcyB3aWxsIGJlIHNlbnQgZm9yIHRoaXMgdXR0ZXJhbmNlLgogICAgaWYgKHR5cGUgPT09ICJuby1tb3JlLWRhdGEiKSB7CiAgICAgIHRoaXMuX25vTW9yZURhdGFSZWNlaXZlZCA9IHRydWU7CiAgICAgIHJldHVybjsKICAgIH0KCiAgICAvLyBVcGRhdGUgbWV0cmljcyBjb25maWd1cmF0aW9uIGF0IHJ1bnRpbWUKICAgIGlmICh0eXBlID09PSAiY29uZmlnLW1ldHJpY3MiICYmIGRhdGEgJiYgdHlwZW9mIGRhdGEgPT09ICJvYmplY3QiKSB7CiAgICAgIGlmICgiZW5hYmxlZCIgaW4gZGF0YSkgdGhpcy5fbWV0cmljc0VuYWJsZWQgPSAhIWRhdGEuZW5hYmxlZDsKICAgICAgaWYgKHR5cGVvZiBkYXRhLmludGVydmFsSHogPT09ICJudW1iZXIiICYmIGRhdGEuaW50ZXJ2YWxIeiA+IDApIHsKICAgICAgICBjb25zdCBpbnRlcnZhbEh6ID0gZGF0YS5pbnRlcnZhbEh6OwogICAgICAgIHRoaXMuX21ldHJpY3NJbnRlcnZhbEZyYW1lcyA9IE1hdGgubWF4KDEyOCwgTWF0aC5yb3VuZCh0aGlzLl9zYW1wbGVSYXRlIC8gaW50ZXJ2YWxIeikpOwogICAgICB9CiAgICAgIC8vIFJlc2V0IHBhY2luZyBzbyB0aGUgbmV4dCByZXBvcnQgYWxpZ25zIHdpdGggbmV3IGludGVydmFsCiAgICAgIHRoaXMuX2xhc3RNZXRyaWNzU2VudEF0RnJhbWUgPSB0aGlzLl9mcmFtZXNQcm9jZXNzZWQ7CiAgICAgIHJldHVybjsKICAgIH0KCiAgICAvLyBOZXcgYXVkaW8gZGF0YSBoYXMgYXJyaXZlZC4KICAgIGlmICh0eXBlID09PSAiYXVkaW9EYXRhIiAmJiBkYXRhIGluc3RhbmNlb2YgQXJyYXlCdWZmZXIpIHsKICAgICAgdGhpcy5fbm9Nb3JlRGF0YVJlY2VpdmVkID0gZmFsc2U7CiAgICAgIC8vIElmIHdlIHdlcmUgaWRsZSwgdGhpcyBuZXcgZGF0YSBraWNrcyBvZmYgdGhlIHBsYXliYWNrLgogICAgICBpZiAodGhpcy5fc3RhdGUgPT09IFBsYXliYWNrV29ya2xldC5GU00uSURMRSkgewogICAgICAgIHRoaXMuX3N0YXRlID0gUGxheWJhY2tXb3JrbGV0LkZTTS5QTEFZSU5HOwogICAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZSh7IHR5cGU6ICJwbGF5YmFjay1zdGFydGVkIiB9KTsKICAgICAgfQoKICAgICAgLy8gV2Ugb25seSBxdWV1ZSBkYXRhIGlmIHdlIGFyZSBpbiB0aGUgUExBWUlORyBzdGF0ZS4gVGhpcyBwcmV2ZW50cwogICAgICAvLyBkYXRhIGZyb20gYSBwcmV2aW91cywgaW50ZXJydXB0ZWQgc3RyZWFtIGZyb20gbGluZ2VyaW5nLgogICAgICBpZiAodGhpcy5fc3RhdGUgPT09IFBsYXliYWNrV29ya2xldC5GU00uUExBWUlORykgewogICAgICAgIC8vIFN0b3JlIGFzIEludDE2QXJyYXkgdmlldyB0byBhdm9pZCBjb25zdHJ1Y3RpbmcgaXQgaW4gcHJvY2VzcygpCiAgICAgICAgdGhpcy5fYnVmZmVyUXVldWUucHVzaChuZXcgSW50MTZBcnJheShkYXRhKSk7CiAgICAgICAgdGhpcy5fc2lsZW5jZUZyYW1lc0NvdW50ID0gMDsgLy8gUmVzZXQgc2lsZW5jZSBjb3VudGVyIG9uIG5ldyBkYXRhCiAgICAgIH0KICAgIH0KICB9CgogIHByb2Nlc3MoaW5wdXRzLCBvdXRwdXRzLCBwYXJhbWV0ZXJzKSB7CiAgICBjb25zdCBvdXRwdXRDaGFubmVsID0gb3V0cHV0c1swXT8uWzBdOwogICAgaWYgKCFvdXRwdXRDaGFubmVsKSB7CiAgICAgIHJldHVybiB0cnVlOyAvLyBLZWVwIGFsaXZlIGV2ZW4gaWYgb3V0cHV0IGlzIHRlbXBvcmFyaWx5IGRpc2Nvbm5lY3RlZAogICAgfQoKICAgIC8vIElmIHdlIGFyZSBub3QgcGxheWluZywganVzdCBvdXRwdXQgc2lsZW5jZSBhbmQgd2FpdC4KICAgIGlmICh0aGlzLl9zdGF0ZSAhPT0gUGxheWJhY2tXb3JrbGV0LkZTTS5QTEFZSU5HKSB7CiAgICAgIG91dHB1dENoYW5uZWwuZmlsbCgwKTsKICAgICAgcmV0dXJuIHRydWU7IC8vIEFsd2F5cyByZXR1cm4gdHJ1ZSB0byBrZWVwIHRoZSBwcm9jZXNzb3IgYWxpdmUKICAgIH0KCiAgICAvLyBDb3JlIFBMQVlJTkcgTG9naWMKICAgIGNvbnN0IGJsb2NrU2l6ZSA9IG91dHB1dENoYW5uZWwubGVuZ3RoOwogICAgbGV0IHNhbXBsZXNDb3BpZWQgPSAwOwoKICAgIHdoaWxlIChzYW1wbGVzQ29waWVkIDwgYmxvY2tTaXplKSB7CiAgICAgIGlmICghdGhpcy5fY3VycmVudENodW5rIHx8IHRoaXMuX2N1cnJlbnRDaHVua09mZnNldCA+PSB0aGlzLl9jdXJyZW50Q2h1bmsubGVuZ3RoKSB7CiAgICAgICAgaWYgKHRoaXMuX2J1ZmZlclF1ZXVlLmxlbmd0aCA+IDApIHsKICAgICAgICAgIHRoaXMuX2N1cnJlbnRDaHVuayA9IHRoaXMuX2J1ZmZlclF1ZXVlLnNoaWZ0KCk7CiAgICAgICAgICB0aGlzLl9jdXJyZW50Q2h1bmtPZmZzZXQgPSAwOwogICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAvLyBCdWZmZXIgaXMgZW1wdHkuIENoZWNrIGZvciBlbmQgY29uZGl0aW9ucy4KICAgICAgICAgIGNvbnN0IGlzVGltZWRPdXQgPSB0aGlzLl9zaWxlbmNlRnJhbWVzQ291bnQgPiB0aGlzLl9zaWxlbmNlVGhyZXNob2xkQmxvY2tzOwoKICAgICAgICAgIGlmICh0aGlzLl9ub01vcmVEYXRhUmVjZWl2ZWQgfHwgaXNUaW1lZE91dCkgewogICAgICAgICAgICAvLyBFTkQgT0YgUExBWUJBQ0s6IEVpdGhlciBleHBsaWNpdGx5IHNpZ25hbGVkIG9yIHRpbWVkIG91dC4KICAgICAgICAgICAgaWYgKCF0aGlzLl9oYXNTZW50RW5kZWQpIHsKICAgICAgICAgICAgICB0aGlzLnBvcnQucG9zdE1lc3NhZ2UoeyB0eXBlOiAicGxheWJhY2stZW5kZWQiIH0pOwogICAgICAgICAgICAgIHRoaXMuX2hhc1NlbnRFbmRlZCA9IHRydWU7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgLy8gU2VuZCBmaW5hbCBtZXRyaWNzIHNob3dpbmcgY2xlYXJlZCBzdGF0ZQogICAgICAgICAgICBpZiAodGhpcy5fbWV0cmljc0VuYWJsZWQpIHsKICAgICAgICAgICAgICB0cnkgewogICAgICAgICAgICAgICAgdGhpcy5wb3J0LnBvc3RNZXNzYWdlKHsKICAgICAgICAgICAgICAgICAgdHlwZTogIm1ldHJpY3MiLAogICAgICAgICAgICAgICAgICBkYXRhOiB7CiAgICAgICAgICAgICAgICAgICAgc3RhdGU6IFBsYXliYWNrV29ya2xldC5GU00uSURMRSwKICAgICAgICAgICAgICAgICAgICBxdWV1ZWRTYW1wbGVzOiAwLAogICAgICAgICAgICAgICAgICAgIHF1ZXVlZE1zOiAwLAogICAgICAgICAgICAgICAgICAgIG1heFF1ZXVlZE1zOiBNYXRoLnJvdW5kKCh0aGlzLl9tYXhRdWV1ZVNhbXBsZXMgLyB0aGlzLl9zYW1wbGVSYXRlKSAqIDEwMDApLAogICAgICAgICAgICAgICAgICAgIHVuZGVycnVuQmxvY2tzOiB0aGlzLl91bmRlcnJ1bkJsb2NrcywKICAgICAgICAgICAgICAgICAgICBmcmFtZXNQcm9jZXNzZWQ6IHRoaXMuX2ZyYW1lc1Byb2Nlc3NlZAogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICB9KTsKICAgICAgICAgICAgICB9IGNhdGNoIChfKSB7IH0KICAgICAgICAgICAgfQogICAgICAgICAgICB0aGlzLnJlc2V0KCk7IC8vIFJlc2V0IHRvIElETEUgc3RhdGUgZm9yIHJldXNlCiAgICAgICAgICAgIGJyZWFrOyAvLyBFeGl0IHdoaWxlIGxvb3AKICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgIC8vIEJVRkZFUiBVTkRFUlJVTiAoTEFHKTogUGxheSBzaWxlbmNlIGFuZCB3YWl0IGZvciBtb3JlIGRhdGEuCiAgICAgICAgICAgIHRoaXMuX3NpbGVuY2VGcmFtZXNDb3VudCsrOwogICAgICAgICAgICBpZiAodGhpcy5fbWV0cmljc0VuYWJsZWQpIHRoaXMuX3VuZGVycnVuQmxvY2tzKys7CiAgICAgICAgICAgIGJyZWFrOyAvLyBFeGl0IHdoaWxlIGxvb3AKICAgICAgICAgIH0KICAgICAgICB9CiAgICAgIH0KCiAgICAgIC8vIElmIHdlIGhhdmUgYSBjaHVuayAoY291bGQgYmUgYSBuZXcgb25lIGZyb20gdGhlIGxvZ2ljIGFib3ZlKSwgcHJvY2VzcyBpdC4KICAgICAgaWYgKHRoaXMuX2N1cnJlbnRDaHVuaykgewogICAgICAgIGNvbnN0IHNhbXBsZXNUb0NvcHkgPSBNYXRoLm1pbigKICAgICAgICAgIGJsb2NrU2l6ZSAtIHNhbXBsZXNDb3BpZWQsCiAgICAgICAgICB0aGlzLl9jdXJyZW50Q2h1bmsubGVuZ3RoIC0gdGhpcy5fY3VycmVudENodW5rT2Zmc2V0CiAgICAgICAgKTsKICAgICAgICAvLyBEaXJlY3RseSB3cml0ZSB0byBvdXRwdXRDaGFubmVsIHRvIGF2b2lkIGV4dHJhIGNvcHkKICAgICAgICBjb25zdCBzcmMgPSB0aGlzLl9jdXJyZW50Q2h1bms7CiAgICAgICAgY29uc3QgYmFzZVNyYyA9IHRoaXMuX2N1cnJlbnRDaHVua09mZnNldDsKICAgICAgICBjb25zdCBiYXNlRHN0ID0gc2FtcGxlc0NvcGllZDsKICAgICAgICBjb25zdCBzY2FsZSA9IHRoaXMuX3NjYWxlOwogICAgICAgIGZvciAobGV0IGkgPSAwOyBpIDwgc2FtcGxlc1RvQ29weTsgaSsrKSB7CiAgICAgICAgICBvdXRwdXRDaGFubmVsW2Jhc2VEc3QgKyBpXSA9IHNyY1tiYXNlU3JjICsgaV0gKiBzY2FsZTsKICAgICAgICB9CgogICAgICAgIHRoaXMuX2N1cnJlbnRDaHVua09mZnNldCArPSBzYW1wbGVzVG9Db3B5OwogICAgICAgIHNhbXBsZXNDb3BpZWQgKz0gc2FtcGxlc1RvQ29weTsKICAgICAgfQogICAgfQoKICAgIC8vIFplcm8tZmlsbCB0aGUgcmVtYWluZGVyLCBpZiBhbnksIG9uY2UgcGVyIGJsb2NrCiAgICBpZiAoc2FtcGxlc0NvcGllZCA8IGJsb2NrU2l6ZSkgewogICAgICBvdXRwdXRDaGFubmVsLmZpbGwoMCwgc2FtcGxlc0NvcGllZCk7CiAgICB9CgogICAgLy8gVXBkYXRlIG1ldHJpY3MgKG9wdGlvbmFsKQogICAgaWYgKHRoaXMuX21ldHJpY3NFbmFibGVkKSB7CiAgICAgIHRoaXMuX2ZyYW1lc1Byb2Nlc3NlZCArPSBibG9ja1NpemU7CgogICAgICAvLyBUcmFjayBxdWV1ZSBkZXB0aCBpbiBzYW1wbGVzIChhcHByb3hpbWF0ZSkKICAgICAgbGV0IHF1ZXVlZFNhbXBsZXMgPSAwOwogICAgICBpZiAodGhpcy5fY3VycmVudENodW5rKSBxdWV1ZWRTYW1wbGVzICs9IE1hdGgubWF4KDAsIHRoaXMuX2N1cnJlbnRDaHVuay5sZW5ndGggLSB0aGlzLl9jdXJyZW50Q2h1bmtPZmZzZXQpOwogICAgICBmb3IgKGxldCBpID0gMDsgaSA8IHRoaXMuX2J1ZmZlclF1ZXVlLmxlbmd0aDsgaSsrKSBxdWV1ZWRTYW1wbGVzICs9IHRoaXMuX2J1ZmZlclF1ZXVlW2ldLmxlbmd0aDsKICAgICAgaWYgKHF1ZXVlZFNhbXBsZXMgPiB0aGlzLl9tYXhRdWV1ZVNhbXBsZXMpIHRoaXMuX21heFF1ZXVlU2FtcGxlcyA9IHF1ZXVlZFNhbXBsZXM7CgogICAgICAvLyBQZXJpb2RpY2FsbHkgc2VuZCBtZXRyaWNzIHRvIG1haW4gdGhyZWFkCiAgICAgIGlmICh0aGlzLl9mcmFtZXNQcm9jZXNzZWQgLSB0aGlzLl9sYXN0TWV0cmljc1NlbnRBdEZyYW1lID49IHRoaXMuX21ldHJpY3NJbnRlcnZhbEZyYW1lcykgewogICAgICAgIHRoaXMuX2xhc3RNZXRyaWNzU2VudEF0RnJhbWUgPSB0aGlzLl9mcmFtZXNQcm9jZXNzZWQ7CiAgICAgICAgdHJ5IHsKICAgICAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZSh7CiAgICAgICAgICAgIHR5cGU6ICJtZXRyaWNzIiwKICAgICAgICAgICAgZGF0YTogewogICAgICAgICAgICAgIHN0YXRlOiB0aGlzLl9zdGF0ZSwKICAgICAgICAgICAgICBxdWV1ZWRTYW1wbGVzLAogICAgICAgICAgICAgIHF1ZXVlZE1zOiBNYXRoLnJvdW5kKChxdWV1ZWRTYW1wbGVzIC8gdGhpcy5fc2FtcGxlUmF0ZSkgKiAxMDAwKSwKICAgICAgICAgICAgICBtYXhRdWV1ZWRNczogTWF0aC5yb3VuZCgodGhpcy5fbWF4UXVldWVTYW1wbGVzIC8gdGhpcy5fc2FtcGxlUmF0ZSkgKiAxMDAwKSwKICAgICAgICAgICAgICB1bmRlcnJ1bkJsb2NrczogdGhpcy5fdW5kZXJydW5CbG9ja3MsCiAgICAgICAgICAgICAgZnJhbWVzUHJvY2Vzc2VkOiB0aGlzLl9mcmFtZXNQcm9jZXNzZWQKICAgICAgICAgICAgfQogICAgICAgICAgfSk7CiAgICAgICAgfSBjYXRjaCAoXykgeyB9CiAgICAgICAgLy8gRG9uJ3QgcmVzZXQgbWF4IHRyYWNrZXIgLSBrZWVwIHNlc3Npb24gcGVhayB1bnRpbCBpZGxlCiAgICAgIH0KICAgIH0KCiAgICAvLyBBTFdBWVMgcmV0dXJuIHRydWUgdG8ga2VlcCB0aGUgcHJvY2Vzc29yIGFsaXZlIGZvciByZXVzZS4KICAgIHJldHVybiB0cnVlOwogIH0KfQoKcmVnaXN0ZXJQcm9jZXNzb3IoInBsYXliYWNrLXdvcmtsZXQiLCBQbGF5YmFja1dvcmtsZXQpOwo=",typeof document>"u"?require("url").pathToFileURL(__filename).href:He&&He.tagName.toUpperCase()==="SCRIPT"&&He.src||new URL("index.cjs",document.baseURI).href),Oe={en:nt,de:ot,fr:at,fi:lt,lt:ct},K=new y.Quaternion,V=new y.Euler,fe=new y.Vector3,xe=new y.Vector3,Ne=new y.Box3;new y.Matrix4;new y.Matrix4;new y.Vector3;new y.Vector3(0,0,1);const dt=new y.Vector3(1,0,0);new y.Vector3(0,1,0);new y.Vector3(0,0,1);class Te{constructor(t,e=null){this.nodeAvatar=t,this.opt={jwtGet:null,ttsEndpoint:"",ttsApikey:null,ttsTrimStart:0,ttsTrimEnd:400,ttsLang:"fi-FI",ttsVoice:"fi-FI-Standard-A",ttsRate:1,ttsPitch:0,ttsVolume:.3,mixerGainSpeech:1.2,mixerGainBackground:null,lipsyncLang:"fi",lipsyncModules:["fi","en","lt"],pcmSampleRate:22050,modelRoot:"Armature",modelPixelRatio:1,modelFPS:30,modelMovementFactor:1,cameraView:"full",dracoEnabled:!1,dracoDecoderPath:"https://www.gstatic.com/draco/v1/decoders/",cameraDistance:0,cameraX:0,cameraY:0,cameraRotateX:0,cameraRotateY:0,cameraRotateEnable:!0,cameraPanEnable:!1,cameraZoomEnable:!1,lightAmbientColor:16777215,lightAmbientIntensity:1.25,lightDirectColor:8947882,lightDirectIntensity:12,lightDirectPhi:1,lightDirectTheta:2,lightSpotIntensity:0,lightSpotColor:3377407,lightSpotPhi:.1,lightSpotTheta:4,lightSpotDispersion:1,avatarMood:"neutral",avatarMute:!1,avatarIdleEyeContact:.6,avatarIdleHeadMove:.5,avatarSpeakingEyeContact:.8,avatarSpeakingHeadMove:.5,avatarIgnoreCamera:!1,listeningSilenceThresholdLevel:40,listeningSilenceThresholdMs:2e3,listeningSilenceDurationMax:1e4,listeningActiveThresholdLevel:75,listeningActiveThresholdMs:300,listeningActiveDurationMax:24e4,update:null,avatarOnly:!1,avatarOnlyScene:null,avatarOnlyCamera:null,statsNode:null,statsStyle:null},Object.assign(this.opt,e||{}),this.opt.statsNode&&(this.stats=new Qe,this.opt.statsStyle&&(this.stats.dom.style.cssText=this.opt.statsStyle),this.opt.statsNode.appendChild(this.stats.dom)),this.poseTemplates={side:{standing:!0,props:{"Hips.position":{x:0,y:1,z:0},"Hips.rotation":{x:-.003,y:-.017,z:.1},"Spine.rotation":{x:-.103,y:-.002,z:-.063},"Spine1.rotation":{x:.042,y:-.02,z:-.069},"Spine2.rotation":{x:.131,y:-.012,z:-.065},"Neck.rotation":{x:.027,y:.006,z:0},"Head.rotation":{x:.077,y:-.065,z:0},"LeftShoulder.rotation":{x:1.599,y:.084,z:-1.77},"LeftArm.rotation":{x:1.364,y:.052,z:-.044},"LeftForeArm.rotation":{x:.002,y:-.007,z:.331},"LeftHand.rotation":{x:.104,y:-.067,z:-.174},"LeftHandThumb1.rotation":{x:.231,y:.258,z:.355},"LeftHandThumb2.rotation":{x:-.106,y:-.339,z:-.454},"LeftHandThumb3.rotation":{x:-.02,y:-.142,z:-.004},"LeftHandIndex1.rotation":{x:.148,y:.032,z:-.069},"LeftHandIndex2.rotation":{x:.326,y:-.049,z:-.029},"LeftHandIndex3.rotation":{x:.247,y:-.053,z:-.073},"LeftHandMiddle1.rotation":{x:.238,y:-.057,z:-.089},"LeftHandMiddle2.rotation":{x:.469,y:-.036,z:-.081},"LeftHandMiddle3.rotation":{x:.206,y:-.015,z:-.017},"LeftHandRing1.rotation":{x:.187,y:-.118,z:-.157},"LeftHandRing2.rotation":{x:.579,y:.02,z:-.097},"LeftHandRing3.rotation":{x:.272,y:.021,z:-.063},"LeftHandPinky1.rotation":{x:.405,y:-.182,z:-.138},"LeftHandPinky2.rotation":{x:.613,y:.128,z:-.144},"LeftHandPinky3.rotation":{x:.268,y:.094,z:-.081},"RightShoulder.rotation":{x:1.541,y:.192,z:1.775},"RightArm.rotation":{x:1.273,y:-.352,z:-.067},"RightForeArm.rotation":{x:-.011,y:-.031,z:-.357},"RightHand.rotation":{x:-.008,y:.312,z:-.028},"RightHandThumb1.rotation":{x:.23,y:-.258,z:-.355},"RightHandThumb2.rotation":{x:-.107,y:.339,z:.454},"RightHandThumb3.rotation":{x:-.02,y:.142,z:.004},"RightHandIndex1.rotation":{x:.148,y:-.031,z:.069},"RightHandIndex2.rotation":{x:.326,y:.049,z:.029},"RightHandIndex3.rotation":{x:.247,y:.053,z:.073},"RightHandMiddle1.rotation":{x:.237,y:.057,z:.089},"RightHandMiddle2.rotation":{x:.469,y:.036,z:.081},"RightHandMiddle3.rotation":{x:.206,y:.015,z:.017},"RightHandRing1.rotation":{x:.204,y:.086,z:.135},"RightHandRing2.rotation":{x:.579,y:-.02,z:.098},"RightHandRing3.rotation":{x:.272,y:-.021,z:.063},"RightHandPinky1.rotation":{x:.404,y:.182,z:.137},"RightHandPinky2.rotation":{x:.613,y:-.128,z:.144},"RightHandPinky3.rotation":{x:.268,y:-.094,z:.081},"LeftUpLeg.rotation":{x:.096,y:.209,z:2.983},"LeftLeg.rotation":{x:-.053,y:.042,z:-.017},"LeftFoot.rotation":{x:1.091,y:.15,z:.026},"LeftToeBase.rotation":{x:.469,y:-.07,z:-.015},"RightUpLeg.rotation":{x:-.307,y:-.219,z:2.912},"RightLeg.rotation":{x:-.359,y:.164,z:.015},"RightFoot.rotation":{x:1.035,y:.11,z:.005},"RightToeBase.rotation":{x:.467,y:.07,z:.015}}},hip:{standing:!0,props:{"Hips.position":{x:0,y:1,z:0},"Hips.rotation":{x:-.036,y:.09,z:.135},"Spine.rotation":{x:.076,y:-.035,z:.01},"Spine1.rotation":{x:-.096,y:.013,z:-.094},"Spine2.rotation":{x:-.014,y:.002,z:-.097},"Neck.rotation":{x:.034,y:-.051,z:-.075},"Head.rotation":{x:.298,y:-.1,z:.154},"LeftShoulder.rotation":{x:1.694,y:.011,z:-1.68},"LeftArm.rotation":{x:1.343,y:.177,z:-.153},"LeftForeArm.rotation":{x:-.049,y:.134,z:.351},"LeftHand.rotation":{x:.057,y:-.189,z:-.026},"LeftHandThumb1.rotation":{x:.368,y:-.066,z:.438},"LeftHandThumb2.rotation":{x:-.156,y:.029,z:-.369},"LeftHandThumb3.rotation":{x:.034,y:-.009,z:.016},"LeftHandIndex1.rotation":{x:.157,y:-.002,z:-.171},"LeftHandIndex2.rotation":{x:.099,y:0,z:0},"LeftHandIndex3.rotation":{x:.1,y:0,z:0},"LeftHandMiddle1.rotation":{x:.222,y:-.019,z:-.16},"LeftHandMiddle2.rotation":{x:.142,y:0,z:0},"LeftHandMiddle3.rotation":{x:.141,y:0,z:0},"LeftHandRing1.rotation":{x:.333,y:-.039,z:-.174},"LeftHandRing2.rotation":{x:.214,y:0,z:0},"LeftHandRing3.rotation":{x:.213,y:0,z:0},"LeftHandPinky1.rotation":{x:.483,y:-.069,z:-.189},"LeftHandPinky2.rotation":{x:.312,y:0,z:0},"LeftHandPinky3.rotation":{x:.309,y:0,z:0},"RightShoulder.rotation":{x:1.597,y:.012,z:1.816},"RightArm.rotation":{x:.618,y:-1.274,z:-.266},"RightForeArm.rotation":{x:-.395,y:-.097,z:-1.342},"RightHand.rotation":{x:-.816,y:-.057,z:-.976},"RightHandThumb1.rotation":{x:.42,y:.23,z:-1.172},"RightHandThumb2.rotation":{x:-.027,y:.361,z:.122},"RightHandThumb3.rotation":{x:.076,y:.125,z:-.371},"RightHandIndex1.rotation":{x:-.158,y:-.045,z:.033},"RightHandIndex2.rotation":{x:.391,y:.051,z:.025},"RightHandIndex3.rotation":{x:.317,y:.058,z:.07},"RightHandMiddle1.rotation":{x:.486,y:.066,z:.014},"RightHandMiddle2.rotation":{x:.718,y:.055,z:.07},"RightHandMiddle3.rotation":{x:.453,y:.019,z:.013},"RightHandRing1.rotation":{x:.591,y:.241,z:.11},"RightHandRing2.rotation":{x:1.014,y:.023,z:.097},"RightHandRing3.rotation":{x:.708,y:.008,z:.066},"RightHandPinky1.rotation":{x:1.02,y:.305,z:.051},"RightHandPinky2.rotation":{x:1.187,y:-.028,z:.191},"RightHandPinky3.rotation":{x:.872,y:-.031,z:.121},"LeftUpLeg.rotation":{x:-.095,y:-.058,z:-3.338},"LeftLeg.rotation":{x:-.366,y:.287,z:-.021},"LeftFoot.rotation":{x:1.131,y:.21,z:.176},"LeftToeBase.rotation":{x:.739,y:-.068,z:-.001},"RightUpLeg.rotation":{x:-.502,y:.362,z:3.153},"RightLeg.rotation":{x:-1.002,y:.109,z:.008},"RightFoot.rotation":{x:.626,y:-.097,z:-.194},"RightToeBase.rotation":{x:1.33,y:.288,z:-.078}}},turn:{standing:!0,props:{"Hips.position":{x:0,y:1,z:0},"Hips.rotation":{x:-.07,y:-.604,z:-.004},"Spine.rotation":{x:-.007,y:.003,z:.071},"Spine1.rotation":{x:-.053,y:.024,z:-.06},"Spine2.rotation":{x:.074,y:.013,z:-.068},"Neck.rotation":{x:.03,y:.186,z:-.077},"Head.rotation":{x:.045,y:.243,z:-.086},"LeftShoulder.rotation":{x:1.717,y:-.085,z:-1.761},"LeftArm.rotation":{x:1.314,y:.07,z:-.057},"LeftForeArm.rotation":{x:-.151,y:.714,z:.302},"LeftHand.rotation":{x:-.069,y:.003,z:-.118},"LeftHandThumb1.rotation":{x:.23,y:.258,z:.354},"LeftHandThumb2.rotation":{x:-.107,y:-.338,z:-.455},"LeftHandThumb3.rotation":{x:-.015,y:-.142,z:.002},"LeftHandIndex1.rotation":{x:.145,y:.032,z:-.069},"LeftHandIndex2.rotation":{x:.323,y:-.049,z:-.028},"LeftHandIndex3.rotation":{x:.249,y:-.053,z:-.074},"LeftHandMiddle1.rotation":{x:.235,y:-.057,z:-.088},"LeftHandMiddle2.rotation":{x:.468,y:-.036,z:-.081},"LeftHandMiddle3.rotation":{x:.203,y:-.015,z:-.017},"LeftHandRing1.rotation":{x:.185,y:-.118,z:-.157},"LeftHandRing2.rotation":{x:.578,y:.02,z:-.097},"LeftHandRing3.rotation":{x:.27,y:.021,z:-.063},"LeftHandPinky1.rotation":{x:.404,y:-.182,z:-.138},"LeftHandPinky2.rotation":{x:.612,y:.128,z:-.144},"LeftHandPinky3.rotation":{x:.267,y:.094,z:-.081},"RightShoulder.rotation":{x:1.605,y:.17,z:1.625},"RightArm.rotation":{x:1.574,y:-.655,z:.388},"RightForeArm.rotation":{x:-.36,y:-.849,z:-.465},"RightHand.rotation":{x:.114,y:.416,z:-.069},"RightHandThumb1.rotation":{x:.486,y:.009,z:-.492},"RightHandThumb2.rotation":{x:-.073,y:-.01,z:.284},"RightHandThumb3.rotation":{x:-.054,y:-.006,z:.209},"RightHandIndex1.rotation":{x:.245,y:-.014,z:.052},"RightHandIndex2.rotation":{x:.155,y:0,z:0},"RightHandIndex3.rotation":{x:.153,y:0,z:0},"RightHandMiddle1.rotation":{x:.238,y:.004,z:.028},"RightHandMiddle2.rotation":{x:.15,y:0,z:0},"RightHandMiddle3.rotation":{x:.149,y:0,z:0},"RightHandRing1.rotation":{x:.267,y:.012,z:.007},"RightHandRing2.rotation":{x:.169,y:0,z:0},"RightHandRing3.rotation":{x:.167,y:0,z:0},"RightHandPinky1.rotation":{x:.304,y:.018,z:-.021},"RightHandPinky2.rotation":{x:.192,y:0,z:0},"RightHandPinky3.rotation":{x:.19,y:0,z:0},"LeftUpLeg.rotation":{x:-.001,y:-.058,z:-3.238},"LeftLeg.rotation":{x:-.29,y:.058,z:-.021},"LeftFoot.rotation":{x:1.288,y:.168,z:.183},"LeftToeBase.rotation":{x:.363,y:-.09,z:-.01},"RightUpLeg.rotation":{x:-.1,y:.36,z:3.062},"RightLeg.rotation":{x:-.67,y:-.304,z:.043},"RightFoot.rotation":{x:1.195,y:-.159,z:-.294},"RightToeBase.rotation":{x:.737,y:.164,z:-.002}}},bend:{bend:!0,standing:!0,props:{"Hips.position":{x:-.007,y:.943,z:-.001},"Hips.rotation":{x:1.488,y:-.633,z:1.435},"Spine.rotation":{x:-.126,y:.007,z:-.057},"Spine1.rotation":{x:-.134,y:.009,z:.01},"Spine2.rotation":{x:-.019,y:0,z:-.002},"Neck.rotation":{x:-.159,y:.572,z:-.108},"Head.rotation":{x:-.064,y:.716,z:-.257},"RightShoulder.rotation":{x:1.625,y:-.043,z:1.382},"RightArm.rotation":{x:.746,y:-.96,z:-1.009},"RightForeArm.rotation":{x:-.199,y:-.528,z:-.38},"RightHand.rotation":{x:-.261,y:-.043,z:-.027},"RightHandThumb1.rotation":{x:.172,y:-.138,z:-.445},"RightHandThumb2.rotation":{x:-.158,y:.327,z:.545},"RightHandThumb3.rotation":{x:-.062,y:.138,z:.152},"RightHandIndex1.rotation":{x:.328,y:-.005,z:.132},"RightHandIndex2.rotation":{x:.303,y:.049,z:.028},"RightHandIndex3.rotation":{x:.241,y:.046,z:.077},"RightHandMiddle1.rotation":{x:.309,y:.074,z:.089},"RightHandMiddle2.rotation":{x:.392,y:.036,z:.081},"RightHandMiddle3.rotation":{x:.199,y:.014,z:.019},"RightHandRing1.rotation":{x:.239,y:.143,z:.091},"RightHandRing2.rotation":{x:.275,y:-.02,z:.097},"RightHandRing3.rotation":{x:.248,y:-.023,z:.061},"RightHandPinky1.rotation":{x:.211,y:.154,z:.029},"RightHandPinky2.rotation":{x:.348,y:-.128,z:.144},"RightHandPinky3.rotation":{x:.21,y:-.091,z:.065},"LeftShoulder.rotation":{x:1.626,y:-.027,z:-1.367},"LeftArm.rotation":{x:1.048,y:.737,z:.712},"LeftForeArm.rotation":{x:-.508,y:.879,z:.625},"LeftHand.rotation":{x:.06,y:-.243,z:-.079},"LeftHandThumb1.rotation":{x:.187,y:-.072,z:.346},"LeftHandThumb2.rotation":{x:-.066,y:.008,z:-.256},"LeftHandThumb3.rotation":{x:-.085,y:.014,z:-.334},"LeftHandIndex1.rotation":{x:-.1,y:.016,z:-.058},"LeftHandIndex2.rotation":{x:.334,y:0,z:0},"LeftHandIndex3.rotation":{x:.281,y:0,z:0},"LeftHandMiddle1.rotation":{x:-.056,y:0,z:0},"LeftHandMiddle2.rotation":{x:.258,y:0,z:0},"LeftHandMiddle3.rotation":{x:.26,y:0,z:0},"LeftHandRing1.rotation":{x:-.067,y:-.002,z:.008},"LeftHandRing2.rotation":{x:.259,y:0,z:0},"LeftHandRing3.rotation":{x:.276,y:0,z:0},"LeftHandPinky1.rotation":{x:-.128,y:-.007,z:.042},"LeftHandPinky2.rotation":{x:.227,y:0,z:0},"LeftHandPinky3.rotation":{x:.145,y:0,z:0},"RightUpLeg.rotation":{x:-1.507,y:.2,z:-3.043},"RightLeg.rotation":{x:-.689,y:-.124,z:.017},"RightFoot.rotation":{x:.909,y:.008,z:-.093},"RightToeBase.rotation":{x:.842,y:.075,z:-.008},"LeftUpLeg.rotation":{x:-1.449,y:-.2,z:3.018},"LeftLeg.rotation":{x:-.74,y:-.115,z:-.008},"LeftFoot.rotation":{x:1.048,y:-.058,z:.117},"LeftToeBase.rotation":{x:.807,y:-.067,z:.003}}},back:{standing:!0,props:{"Hips.position":{x:0,y:1,z:0},"Hips.rotation":{x:-.732,y:-1.463,z:-.637},"Spine.rotation":{x:-.171,y:.106,z:.157},"Spine1.rotation":{x:-.044,y:.138,z:-.059},"Spine2.rotation":{x:.082,y:.133,z:-.074},"Neck.rotation":{x:.39,y:.591,z:-.248},"Head.rotation":{x:-.001,y:.596,z:-.057},"LeftShoulder.rotation":{x:1.676,y:.007,z:-1.892},"LeftArm.rotation":{x:-5.566,y:1.188,z:-.173},"LeftForeArm.rotation":{x:-.673,y:-.105,z:1.702},"LeftHand.rotation":{x:-.469,y:-.739,z:.003},"LeftHandThumb1.rotation":{x:.876,y:.274,z:.793},"LeftHandThumb2.rotation":{x:.161,y:-.23,z:-.172},"LeftHandThumb3.rotation":{x:.078,y:.027,z:.156},"LeftHandIndex1.rotation":{x:-.085,y:-.002,z:.009},"LeftHandIndex2.rotation":{x:.176,y:0,z:-.002},"LeftHandIndex3.rotation":{x:-.036,y:.001,z:-.035},"LeftHandMiddle1.rotation":{x:.015,y:.144,z:-.076},"LeftHandMiddle2.rotation":{x:.378,y:-.007,z:-.077},"LeftHandMiddle3.rotation":{x:-.141,y:-.001,z:.031},"LeftHandRing1.rotation":{x:.039,y:.02,z:-.2},"LeftHandRing2.rotation":{x:.25,y:-.002,z:-.073},"LeftHandRing3.rotation":{x:.236,y:.006,z:-.075},"LeftHandPinky1.rotation":{x:.172,y:-.033,z:-.275},"LeftHandPinky2.rotation":{x:.216,y:.043,z:-.054},"LeftHandPinky3.rotation":{x:.325,y:.078,z:-.13},"RightShoulder.rotation":{x:2.015,y:-.168,z:1.706},"RightArm.rotation":{x:.203,y:-1.258,z:-.782},"RightForeArm.rotation":{x:-.658,y:-.133,z:-1.401},"RightHand.rotation":{x:-1.504,y:.375,z:-.005},"RightHandThumb1.rotation":{x:.413,y:-.158,z:-1.121},"RightHandThumb2.rotation":{x:-.142,y:-.008,z:.209},"RightHandThumb3.rotation":{x:-.091,y:.021,z:.142},"RightHandIndex1.rotation":{x:-.167,y:.014,z:-.072},"RightHandIndex2.rotation":{x:.474,y:.009,z:.051},"RightHandIndex3.rotation":{x:.115,y:.006,z:.047},"RightHandMiddle1.rotation":{x:.385,y:.019,z:.144},"RightHandMiddle2.rotation":{x:.559,y:.035,z:.101},"RightHandMiddle3.rotation":{x:.229,y:0,z:.027},"RightHandRing1.rotation":{x:.48,y:.026,z:.23},"RightHandRing2.rotation":{x:.772,y:.038,z:.109},"RightHandRing3.rotation":{x:.622,y:.039,z:.106},"RightHandPinky1.rotation":{x:.767,y:.288,z:.353},"RightHandPinky2.rotation":{x:.886,y:.049,z:.122},"RightHandPinky3.rotation":{x:.662,y:.044,z:.113},"LeftUpLeg.rotation":{x:-.206,y:-.268,z:-3.343},"LeftLeg.rotation":{x:-.333,y:.757,z:-.043},"LeftFoot.rotation":{x:1.049,y:.167,z:.287},"LeftToeBase.rotation":{x:.672,y:-.069,z:-.004},"RightUpLeg.rotation":{x:.055,y:-.226,z:3.037},"RightLeg.rotation":{x:-.559,y:.39,z:-.001},"RightFoot.rotation":{x:1.2,y:.133,z:.085},"RightToeBase.rotation":{x:.92,y:.093,z:-.013}}},straight:{standing:!0,props:{"Hips.position":{x:0,y:.989,z:.001},"Hips.rotation":{x:.047,y:.007,z:-.007},"Spine.rotation":{x:-.143,y:-.007,z:.005},"Spine1.rotation":{x:-.043,y:-.014,z:.012},"Spine2.rotation":{x:.072,y:-.013,z:.013},"Neck.rotation":{x:.048,y:-.003,z:.012},"Head.rotation":{x:.05,y:-.02,z:-.017},"LeftShoulder.rotation":{x:1.62,y:-.166,z:-1.605},"LeftArm.rotation":{x:1.275,y:.544,z:-.092},"LeftForeArm.rotation":{x:0,y:0,z:.302},"LeftHand.rotation":{x:-.225,y:-.154,z:.11},"LeftHandThumb1.rotation":{x:.435,y:-.044,z:.457},"LeftHandThumb2.rotation":{x:-.028,y:.002,z:-.246},"LeftHandThumb3.rotation":{x:-.236,y:-.025,z:.113},"LeftHandIndex1.rotation":{x:.218,y:.008,z:-.081},"LeftHandIndex2.rotation":{x:.165,y:-.001,z:-.017},"LeftHandIndex3.rotation":{x:.165,y:-.001,z:-.017},"LeftHandMiddle1.rotation":{x:.235,y:-.011,z:-.065},"LeftHandMiddle2.rotation":{x:.182,y:-.002,z:-.019},"LeftHandMiddle3.rotation":{x:.182,y:-.002,z:-.019},"LeftHandRing1.rotation":{x:.316,y:-.017,z:.008},"LeftHandRing2.rotation":{x:.253,y:-.003,z:-.026},"LeftHandRing3.rotation":{x:.255,y:-.003,z:-.026},"LeftHandPinky1.rotation":{x:.336,y:-.062,z:.088},"LeftHandPinky2.rotation":{x:.276,y:-.004,z:-.028},"LeftHandPinky3.rotation":{x:.276,y:-.004,z:-.028},"RightShoulder.rotation":{x:1.615,y:.064,z:1.53},"RightArm.rotation":{x:1.313,y:-.424,z:.131},"RightForeArm.rotation":{x:0,y:0,z:-.317},"RightHand.rotation":{x:-.158,y:-.639,z:-.196},"RightHandThumb1.rotation":{x:.44,y:.048,z:-.549},"RightHandThumb2.rotation":{x:-.056,y:-.008,z:.274},"RightHandThumb3.rotation":{x:-.258,y:.031,z:-.095},"RightHandIndex1.rotation":{x:.169,y:-.011,z:.105},"RightHandIndex2.rotation":{x:.134,y:.001,z:.011},"RightHandIndex3.rotation":{x:.134,y:.001,z:.011},"RightHandMiddle1.rotation":{x:.288,y:.014,z:.092},"RightHandMiddle2.rotation":{x:.248,y:.003,z:.02},"RightHandMiddle3.rotation":{x:.249,y:.003,z:.02},"RightHandRing1.rotation":{x:.369,y:.019,z:.006},"RightHandRing2.rotation":{x:.321,y:.004,z:.026},"RightHandRing3.rotation":{x:.323,y:.004,z:.026},"RightHandPinky1.rotation":{x:.468,y:.085,z:-.03},"RightHandPinky2.rotation":{x:.427,y:.007,z:.034},"RightHandPinky3.rotation":{x:.142,y:.001,z:.012},"LeftUpLeg.rotation":{x:-.077,y:-.058,z:3.126},"LeftLeg.rotation":{x:-.252,y:.001,z:-.018},"LeftFoot.rotation":{x:1.315,y:-.064,z:.315},"LeftToeBase.rotation":{x:.577,y:-.07,z:-.009},"RightUpLeg.rotation":{x:-.083,y:-.032,z:3.124},"RightLeg.rotation":{x:-.272,y:-.003,z:.021},"RightFoot.rotation":{x:1.342,y:.076,z:-.222},"RightToeBase.rotation":{x:.44,y:.069,z:.016}}},wide:{standing:!0,props:{"Hips.position":{x:0,y:1.017,z:.016},"Hips.rotation":{x:.064,y:-.048,z:.059},"Spine.rotation":{x:-.123,y:0,z:-.018},"Spine1.rotation":{x:.014,y:.003,z:-.006},"Spine2.rotation":{x:.04,y:.003,z:-.007},"Neck.rotation":{x:.101,y:.007,z:-.035},"Head.rotation":{x:-.091,y:-.049,z:.105},"RightShoulder.rotation":{x:1.831,y:.017,z:1.731},"RightArm.rotation":{x:-1.673,y:-1.102,z:-3.132},"RightForeArm.rotation":{x:.265,y:.23,z:-.824},"RightHand.rotation":{x:-.52,y:.345,z:-.061},"RightHandThumb1.rotation":{x:.291,y:.056,z:-.428},"RightHandThumb2.rotation":{x:.025,y:.005,z:.166},"RightHandThumb3.rotation":{x:-.089,y:.009,z:.068},"RightHandIndex1.rotation":{x:.392,y:-.015,z:.11},"RightHandIndex2.rotation":{x:.391,y:.001,z:.004},"RightHandIndex3.rotation":{x:.326,y:0,z:.003},"RightHandMiddle1.rotation":{x:.285,y:.068,z:.081},"RightHandMiddle2.rotation":{x:.519,y:.004,z:.011},"RightHandMiddle3.rotation":{x:.252,y:0,z:.001},"RightHandRing1.rotation":{x:.207,y:.133,z:.146},"RightHandRing2.rotation":{x:.597,y:.004,z:.004},"RightHandRing3.rotation":{x:.292,y:.002,z:.012},"RightHandPinky1.rotation":{x:.338,y:.182,z:.136},"RightHandPinky2.rotation":{x:.533,y:.002,z:.004},"RightHandPinky3.rotation":{x:.194,y:0,z:.002},"LeftShoulder.rotation":{x:1.83,y:-.063,z:-1.808},"LeftArm.rotation":{x:-1.907,y:1.228,z:-2.959},"LeftForeArm.rotation":{x:-.159,y:.268,z:.572},"LeftHand.rotation":{x:.069,y:-.498,z:-.025},"LeftHandThumb1.rotation":{x:.738,y:.123,z:.178},"LeftHandThumb2.rotation":{x:-.26,y:.028,z:-.477},"LeftHandThumb3.rotation":{x:-.448,y:.093,z:-.661},"LeftHandIndex1.rotation":{x:1.064,y:.005,z:-.13},"LeftHandIndex2.rotation":{x:1.55,y:-.143,z:-.136},"LeftHandIndex3.rotation":{x:.722,y:-.076,z:-.127},"LeftHandMiddle1.rotation":{x:1.095,y:-.091,z:.006},"LeftHandMiddle2.rotation":{x:1.493,y:-.174,z:-.151},"LeftHandMiddle3.rotation":{x:.651,y:-.031,z:-.087},"LeftHandRing1.rotation":{x:1.083,y:-.224,z:.072},"LeftHandRing2.rotation":{x:1.145,y:-.107,z:-.195},"LeftHandRing3.rotation":{x:1.208,y:-.134,z:-.158},"LeftHandPinky1.rotation":{x:.964,y:-.383,z:.128},"LeftHandPinky2.rotation":{x:1.457,y:-.146,z:-.159},"LeftHandPinky3.rotation":{x:1.019,y:-.102,z:-.141},"RightUpLeg.rotation":{x:-.221,y:-.233,z:2.87},"RightLeg.rotation":{x:-.339,y:-.043,z:-.041},"RightFoot.rotation":{x:1.081,y:.177,z:.114},"RightToeBase.rotation":{x:.775,y:0,z:0},"LeftUpLeg.rotation":{x:-.185,y:.184,z:3.131},"LeftLeg.rotation":{x:-.408,y:.129,z:.02},"LeftFoot.rotation":{x:1.167,y:-.002,z:-.007},"LeftToeBase.rotation":{x:.723,y:0,z:0}}},oneknee:{kneeling:!0,props:{"Hips.position":{x:-.005,y:.415,z:-.017},"Hips.rotation":{x:-.25,y:.04,z:-.238},"Spine.rotation":{x:.037,y:.043,z:.047},"Spine1.rotation":{x:.317,y:.103,z:.066},"Spine2.rotation":{x:.433,y:.109,z:.054},"Neck.rotation":{x:-.156,y:-.092,z:.059},"Head.rotation":{x:-.398,y:-.032,z:.018},"RightShoulder.rotation":{x:1.546,y:.119,z:1.528},"RightArm.rotation":{x:.896,y:-.247,z:-.512},"RightForeArm.rotation":{x:.007,y:0,z:-1.622},"RightHand.rotation":{x:1.139,y:-.853,z:.874},"RightHandThumb1.rotation":{x:.176,y:.107,z:-.311},"RightHandThumb2.rotation":{x:-.047,y:-.003,z:.12},"RightHandThumb3.rotation":{x:0,y:0,z:0},"RightHandIndex1.rotation":{x:.186,y:.005,z:.125},"RightHandIndex2.rotation":{x:.454,y:.005,z:.015},"RightHandIndex3.rotation":{x:0,y:0,z:0},"RightHandMiddle1.rotation":{x:.444,y:.035,z:.127},"RightHandMiddle2.rotation":{x:.403,y:-.006,z:-.04},"RightHandMiddle3.rotation":{x:0,y:0,z:0},"RightHandRing1.rotation":{x:.543,y:.074,z:.121},"RightHandRing2.rotation":{x:.48,y:-.018,z:-.063},"RightHandRing3.rotation":{x:0,y:0,z:0},"RightHandPinky1.rotation":{x:.464,y:.086,z:.113},"RightHandPinky2.rotation":{x:.667,y:-.06,z:-.128},"RightHandPinky3.rotation":{x:0,y:0,z:0},"LeftShoulder.rotation":{x:1.545,y:-.116,z:-1.529},"LeftArm.rotation":{x:.799,y:.631,z:.556},"LeftForeArm.rotation":{x:-.002,y:.007,z:.926},"LeftHand.rotation":{x:-.508,y:.439,z:.502},"LeftHandThumb1.rotation":{x:.651,y:-.035,z:.308},"LeftHandThumb2.rotation":{x:-.053,y:.008,z:-.11},"LeftHandThumb3.rotation":{x:0,y:0,z:0},"LeftHandIndex1.rotation":{x:.662,y:-.053,z:-.116},"LeftHandIndex2.rotation":{x:.309,y:-.004,z:-.02},"LeftHandIndex3.rotation":{x:0,y:0,z:0},"LeftHandMiddle1.rotation":{x:.501,y:-.062,z:-.12},"LeftHandMiddle2.rotation":{x:.144,y:-.002,z:.016},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:.397,y:-.029,z:-.143},"LeftHandRing2.rotation":{x:.328,y:.01,z:.059},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:.194,y:.008,z:-.164},"LeftHandPinky2.rotation":{x:.38,y:.031,z:.128},"LeftHandPinky3.rotation":{x:0,y:0,z:0},"RightUpLeg.rotation":{x:-1.594,y:-.251,z:2.792},"RightLeg.rotation":{x:-2.301,y:-.073,z:.055},"RightFoot.rotation":{x:1.553,y:-.207,z:-.094},"RightToeBase.rotation":{x:.459,y:.069,z:.016},"LeftUpLeg.rotation":{x:-.788,y:-.236,z:-2.881},"LeftLeg.rotation":{x:-2.703,y:.012,z:-.047},"LeftFoot.rotation":{x:2.191,y:-.102,z:.019},"LeftToeBase.rotation":{x:1.215,y:-.027,z:.01}}},kneel:{kneeling:!0,lying:!0,props:{"Hips.position":{x:0,y:.532,z:-.002},"Hips.rotation":{x:.018,y:-.008,z:-.017},"Spine.rotation":{x:-.139,y:-.01,z:.002},"Spine1.rotation":{x:.002,y:-.002,z:.001},"Spine2.rotation":{x:.028,y:-.002,z:.001},"Neck.rotation":{x:-.007,y:0,z:-.002},"Head.rotation":{x:-.02,y:-.008,z:-.004},"LeftShoulder.rotation":{x:1.77,y:-.428,z:-1.588},"LeftArm.rotation":{x:.911,y:.343,z:.083},"LeftForeArm.rotation":{x:0,y:0,z:.347},"LeftHand.rotation":{x:.033,y:-.052,z:-.105},"LeftHandThumb1.rotation":{x:.508,y:-.22,z:.708},"LeftHandThumb2.rotation":{x:-.323,y:-.139,z:-.56},"LeftHandThumb3.rotation":{x:-.328,y:.16,z:-.301},"LeftHandIndex1.rotation":{x:.178,y:.248,z:.045},"LeftHandIndex2.rotation":{x:.236,y:-.002,z:-.019},"LeftHandIndex3.rotation":{x:-.062,y:0,z:.005},"LeftHandMiddle1.rotation":{x:.123,y:-.005,z:-.019},"LeftHandMiddle2.rotation":{x:.589,y:-.014,z:-.045},"LeftHandMiddle3.rotation":{x:.231,y:-.002,z:-.019},"LeftHandRing1.rotation":{x:.196,y:-.008,z:-.091},"LeftHandRing2.rotation":{x:.483,y:-.009,z:-.038},"LeftHandRing3.rotation":{x:.367,y:-.005,z:-.029},"LeftHandPinky1.rotation":{x:.191,y:-.269,z:-.246},"LeftHandPinky2.rotation":{x:.37,y:-.006,z:-.029},"LeftHandPinky3.rotation":{x:.368,y:-.005,z:-.029},"RightShoulder.rotation":{x:1.73,y:.434,z:1.715},"RightArm.rotation":{x:.841,y:-.508,z:-.155},"RightForeArm.rotation":{x:0,y:0,z:-.355},"RightHand.rotation":{x:.091,y:.137,z:.197},"RightHandThumb1.rotation":{x:.33,y:.051,z:-.753},"RightHandThumb2.rotation":{x:-.113,y:.075,z:.612},"RightHandThumb3.rotation":{x:-.271,y:-.166,z:.164},"RightHandIndex1.rotation":{x:.073,y:.001,z:-.093},"RightHandIndex2.rotation":{x:.338,y:.006,z:.034},"RightHandIndex3.rotation":{x:.131,y:.001,z:.013},"RightHandMiddle1.rotation":{x:.13,y:.005,z:-.017},"RightHandMiddle2.rotation":{x:.602,y:.018,z:.058},"RightHandMiddle3.rotation":{x:-.031,y:0,z:-.003},"RightHandRing1.rotation":{x:.351,y:.019,z:.045},"RightHandRing2.rotation":{x:.19,y:.002,z:.019},"RightHandRing3.rotation":{x:.21,y:.002,z:.021},"RightHandPinky1.rotation":{x:.256,y:.17,z:.118},"RightHandPinky2.rotation":{x:.451,y:.01,z:.045},"RightHandPinky3.rotation":{x:.346,y:.006,z:.035},"LeftUpLeg.rotation":{x:-.06,y:.1,z:-2.918},"LeftLeg.rotation":{x:-1.933,y:-.01,z:.011},"LeftFoot.rotation":{x:.774,y:-.162,z:-.144},"LeftToeBase.rotation":{x:1.188,y:0,z:0},"RightUpLeg.rotation":{x:-.099,y:-.057,z:2.922},"RightLeg.rotation":{x:-1.93,y:.172,z:-.02},"RightFoot.rotation":{x:.644,y:.251,z:.212},"RightToeBase.rotation":{x:.638,y:-.034,z:-.001}}},sitting:{sitting:!0,lying:!0,props:{"Hips.position":{x:0,y:.117,z:.005},"Hips.rotation":{x:-.411,y:-.049,z:.056},"Spine.rotation":{x:.45,y:-.039,z:-.116},"Spine1.rotation":{x:.092,y:-.076,z:.08},"Spine2.rotation":{x:.073,y:.035,z:.066},"Neck.rotation":{x:.051,y:.053,z:-.079},"Head.rotation":{x:-.169,y:.009,z:.034},"LeftShoulder.rotation":{x:1.756,y:-.037,z:-1.301},"LeftArm.rotation":{x:-.098,y:.016,z:1.006},"LeftForeArm.rotation":{x:-.089,y:.08,z:.837},"LeftHand.rotation":{x:.262,y:-.399,z:.3},"LeftHandThumb1.rotation":{x:.149,y:-.043,z:.452},"LeftHandThumb2.rotation":{x:.032,y:.006,z:-.162},"LeftHandThumb3.rotation":{x:-.086,y:-.005,z:-.069},"LeftHandIndex1.rotation":{x:.145,y:.032,z:-.069},"LeftHandIndex2.rotation":{x:.325,y:-.001,z:-.004},"LeftHandIndex3.rotation":{x:.253,y:0,z:-.003},"LeftHandMiddle1.rotation":{x:.186,y:-.051,z:-.091},"LeftHandMiddle2.rotation":{x:.42,y:-.003,z:-.011},"LeftHandMiddle3.rotation":{x:.153,y:.001,z:-.001},"LeftHandRing1.rotation":{x:.087,y:-.19,z:-.078},"LeftHandRing2.rotation":{x:.488,y:-.004,z:-.005},"LeftHandRing3.rotation":{x:.183,y:-.001,z:-.012},"LeftHandPinky1.rotation":{x:.205,y:-.262,z:.051},"LeftHandPinky2.rotation":{x:.407,y:-.002,z:-.004},"LeftHandPinky3.rotation":{x:.068,y:0,z:-.002},"RightShoulder.rotation":{x:1.619,y:-.139,z:1.179},"RightArm.rotation":{x:.17,y:-.037,z:-1.07},"RightForeArm.rotation":{x:-.044,y:-.056,z:-.665},"RightHand.rotation":{x:.278,y:.454,z:-.253},"RightHandThumb1.rotation":{x:.173,y:.089,z:-.584},"RightHandThumb2.rotation":{x:-.003,y:-.004,z:.299},"RightHandThumb3.rotation":{x:-.133,y:-.002,z:.235},"RightHandIndex1.rotation":{x:.393,y:-.023,z:.108},"RightHandIndex2.rotation":{x:.391,y:.001,z:.004},"RightHandIndex3.rotation":{x:.326,y:0,z:.003},"RightHandMiddle1.rotation":{x:.285,y:.062,z:.086},"RightHandMiddle2.rotation":{x:.519,y:.003,z:.011},"RightHandMiddle3.rotation":{x:.252,y:-.001,z:.001},"RightHandRing1.rotation":{x:.207,y:.122,z:.155},"RightHandRing2.rotation":{x:.597,y:.004,z:.005},"RightHandRing3.rotation":{x:.292,y:.001,z:.012},"RightHandPinky1.rotation":{x:.338,y:.171,z:.149},"RightHandPinky2.rotation":{x:.533,y:.002,z:.004},"RightHandPinky3.rotation":{x:.194,y:0,z:.002},"LeftUpLeg.rotation":{x:-1.957,y:.083,z:-2.886},"LeftLeg.rotation":{x:-1.46,y:.123,z:.005},"LeftFoot.rotation":{x:-.013,y:.016,z:.09},"LeftToeBase.rotation":{x:.744,y:0,z:0},"RightUpLeg.rotation":{x:-1.994,y:.125,z:2.905},"RightLeg.rotation":{x:-1.5,y:-.202,z:-.006},"RightFoot.rotation":{x:-.012,y:-.065,z:.081},"RightToeBase.rotation":{x:.758,y:0,z:0}}}},this.gestureTemplates={handup:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,2],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-.815,y:[-.4,0,1,2],z:1.575},"LeftHand.rotation":{x:-.529,y:-.2,z:.022},"LeftHandThumb1.rotation":{x:.745,y:-.526,z:.604},"LeftHandThumb2.rotation":{x:-.107,y:-.01,z:-.142},"LeftHandThumb3.rotation":{x:0,y:.001,z:0},"LeftHandIndex1.rotation":{x:-.126,y:-.035,z:-.087},"LeftHandIndex2.rotation":{x:.255,y:.007,z:-.085},"LeftHandIndex3.rotation":{x:0,y:0,z:0},"LeftHandMiddle1.rotation":{x:-.019,y:-.128,z:-.082},"LeftHandMiddle2.rotation":{x:.233,y:.019,z:-.074},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:.005,y:-.241,z:-.122},"LeftHandRing2.rotation":{x:.261,y:.021,z:-.076},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:.059,y:-.336,z:-.2},"LeftHandPinky2.rotation":{x:.153,y:.019,z:.001},"LeftHandPinky3.rotation":{x:0,y:0,z:0}},index:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,2],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-.815,y:[-.4,0,1,2],z:1.575},"LeftHand.rotation":{x:-.276,y:-.506,z:-.208},"LeftHandThumb1.rotation":{x:.579,y:.228,z:.363},"LeftHandThumb2.rotation":{x:-.027,y:-.04,z:-.662},"LeftHandThumb3.rotation":{x:0,y:.001,z:0},"LeftHandIndex1.rotation":{x:0,y:-.105,z:.225},"LeftHandIndex2.rotation":{x:.256,y:-.103,z:-.213},"LeftHandIndex3.rotation":{x:0,y:0,z:0},"LeftHandMiddle1.rotation":{x:1.453,y:.07,z:.021},"LeftHandMiddle2.rotation":{x:1.599,y:.062,z:.07},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:1.528,y:-.073,z:.052},"LeftHandRing2.rotation":{x:1.386,y:.044,z:.053},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:1.65,y:-.204,z:.031},"LeftHandPinky2.rotation":{x:1.302,y:.071,z:.085},"LeftHandPinky3.rotation":{x:0,y:0,z:0}},ok:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,1],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-.415,y:[-.4,0,1,2],z:1.575},"LeftHand.rotation":{x:-.476,y:-.506,z:-.208},"LeftHandThumb1.rotation":{x:.703,y:.445,z:.899},"LeftHandThumb2.rotation":{x:-.312,y:-.04,z:-.938},"LeftHandThumb3.rotation":{x:-.37,y:.024,z:-.393},"LeftHandIndex1.rotation":{x:.8,y:-.086,z:-.091},"LeftHandIndex2.rotation":{x:1.123,y:-.046,z:-.074},"LeftHandIndex3.rotation":{x:.562,y:-.013,z:-.043},"LeftHandMiddle1.rotation":{x:-.019,y:-.128,z:-.082},"LeftHandMiddle2.rotation":{x:.233,y:.019,z:-.074},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:.005,y:-.241,z:-.122},"LeftHandRing2.rotation":{x:.261,y:.021,z:-.076},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:.059,y:-.336,z:-.2},"LeftHandPinky2.rotation":{x:.153,y:.019,z:.001},"LeftHandPinky3.rotation":{x:0,y:0,z:0}},thumbup:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,2],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-.415,y:.206,z:1.575},"LeftHand.rotation":{x:-.276,y:-.506,z:-.208},"LeftHandThumb1.rotation":{x:.208,y:-.189,z:.685},"LeftHandThumb2.rotation":{x:.129,y:-.285,z:-.163},"LeftHandThumb3.rotation":{x:-.047,y:.068,z:.401},"LeftHandIndex1.rotation":{x:1.412,y:-.102,z:-.152},"LeftHandIndex2.rotation":{x:1.903,y:-.16,z:-.114},"LeftHandIndex3.rotation":{x:.535,y:-.017,z:-.062},"LeftHandMiddle1.rotation":{x:1.424,y:-.103,z:-.12},"LeftHandMiddle2.rotation":{x:1.919,y:-.162,z:-.114},"LeftHandMiddle3.rotation":{x:.44,y:-.012,z:-.051},"LeftHandRing1.rotation":{x:1.619,y:-.127,z:-.053},"LeftHandRing2.rotation":{x:1.898,y:-.16,z:-.115},"LeftHandRing3.rotation":{x:.262,y:-.004,z:-.031},"LeftHandPinky1.rotation":{x:1.661,y:-.131,z:-.016},"LeftHandPinky2.rotation":{x:1.715,y:-.067,z:-.13},"LeftHandPinky3.rotation":{x:.627,y:-.023,z:-.071}},thumbdown:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,2],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-2.015,y:.406,z:1.575},"LeftHand.rotation":{x:-.176,y:-.206,z:-.208},"LeftHandThumb1.rotation":{x:.208,y:-.189,z:.685},"LeftHandThumb2.rotation":{x:.129,y:-.285,z:-.163},"LeftHandThumb3.rotation":{x:-.047,y:.068,z:.401},"LeftHandIndex1.rotation":{x:1.412,y:-.102,z:-.152},"LeftHandIndex2.rotation":{x:1.903,y:-.16,z:-.114},"LeftHandIndex3.rotation":{x:.535,y:-.017,z:-.062},"LeftHandMiddle1.rotation":{x:1.424,y:-.103,z:-.12},"LeftHandMiddle2.rotation":{x:1.919,y:-.162,z:-.114},"LeftHandMiddle3.rotation":{x:.44,y:-.012,z:-.051},"LeftHandRing1.rotation":{x:1.619,y:-.127,z:-.053},"LeftHandRing2.rotation":{x:1.898,y:-.16,z:-.115},"LeftHandRing3.rotation":{x:.262,y:-.004,z:-.031},"LeftHandPinky1.rotation":{x:1.661,y:-.131,z:-.016},"LeftHandPinky2.rotation":{x:1.715,y:-.067,z:-.13},"LeftHandPinky3.rotation":{x:.627,y:-.023,z:-.071}},side:{"LeftShoulder.rotation":{x:1.755,y:-.035,z:-1.63},"LeftArm.rotation":{x:1.263,y:-.955,z:1.024},"LeftForeArm.rotation":{x:0,y:0,z:.8},"LeftHand.rotation":{x:-.36,y:-1.353,z:-.184},"LeftHandThumb1.rotation":{x:.137,y:-.049,z:.863},"LeftHandThumb2.rotation":{x:-.293,y:.153,z:-.193},"LeftHandThumb3.rotation":{x:-.271,y:-.17,z:.18},"LeftHandIndex1.rotation":{x:-.018,y:.007,z:.28},"LeftHandIndex2.rotation":{x:.247,y:-.003,z:-.025},"LeftHandIndex3.rotation":{x:.13,y:-.001,z:-.013},"LeftHandMiddle1.rotation":{x:.333,y:-.015,z:.182},"LeftHandMiddle2.rotation":{x:.313,y:-.005,z:-.032},"LeftHandMiddle3.rotation":{x:.294,y:-.004,z:-.03},"LeftHandRing1.rotation":{x:.456,y:-.028,z:-.092},"LeftHandRing2.rotation":{x:.53,y:-.014,z:-.052},"LeftHandRing3.rotation":{x:.478,y:-.012,z:-.047},"LeftHandPinky1.rotation":{x:.647,y:-.049,z:-.184},"LeftHandPinky2.rotation":{x:.29,y:-.004,z:-.029},"LeftHandPinky3.rotation":{x:.501,y:-.013,z:-.049}},shrug:{"Neck.rotation":{x:[-.3,.3,1,2],y:[-.3,.3,1,2],z:[-.1,.1]},"Head.rotation":{x:[-.3,.3],y:[-.3,.3],z:[-.1,.1]},"RightShoulder.rotation":{x:1.732,y:-.058,z:1.407},"RightArm.rotation":{x:1.305,y:.46,z:.118},"RightForeArm.rotation":{x:[0,2],y:[-1,.2],z:-1.637},"RightHand.rotation":{x:-.048,y:.165,z:-.39},"RightHandThumb1.rotation":{x:1.467,y:.599,z:-1.315},"RightHandThumb2.rotation":{x:-.255,y:-.123,z:.119},"RightHandThumb3.rotation":{x:0,y:-.002,z:0},"RightHandIndex1.rotation":{x:-.293,y:-.066,z:-.112},"RightHandIndex2.rotation":{x:.181,y:.007,z:.069},"RightHandIndex3.rotation":{x:0,y:0,z:0},"RightHandMiddle1.rotation":{x:-.063,y:-.041,z:.032},"RightHandMiddle2.rotation":{x:.149,y:.005,z:.05},"RightHandMiddle3.rotation":{x:0,y:0,z:0},"RightHandRing1.rotation":{x:.152,y:-.03,z:.132},"RightHandRing2.rotation":{x:.194,y:.007,z:.058},"RightHandRing3.rotation":{x:0,y:0,z:0},"RightHandPinky1.rotation":{x:.306,y:-.015,z:.257},"RightHandPinky2.rotation":{x:.15,y:-.003,z:-.003},"RightHandPinky3.rotation":{x:0,y:0,z:0},"LeftShoulder.rotation":{x:1.713,y:.141,z:-1.433},"LeftArm.rotation":{x:1.136,y:-.422,z:-.416},"LeftForeArm.rotation":{x:1.42,y:.123,z:1.506},"LeftHand.rotation":{x:.073,y:-.138,z:.064},"LeftHandThumb1.rotation":{x:1.467,y:-.599,z:1.314},"LeftHandThumb2.rotation":{x:-.255,y:.123,z:-.119},"LeftHandThumb3.rotation":{x:0,y:.001,z:0},"LeftHandIndex1.rotation":{x:-.293,y:.066,z:.112},"LeftHandIndex2.rotation":{x:.181,y:-.007,z:-.069},"LeftHandIndex3.rotation":{x:0,y:0,z:0},"LeftHandMiddle1.rotation":{x:-.062,y:.041,z:-.032},"LeftHandMiddle2.rotation":{x:.149,y:-.005,z:-.05},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:.152,y:.03,z:-.132},"LeftHandRing2.rotation":{x:.194,y:-.007,z:-.058},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:.306,y:.015,z:-.257},"LeftHandPinky2.rotation":{x:.15,y:.003,z:.003},"LeftHandPinky3.rotation":{x:0,y:0,z:0}},namaste:{"RightShoulder.rotation":{x:1.758,y:.099,z:1.604},"RightArm.rotation":{x:.862,y:-.292,z:-.932},"RightForeArm.rotation":{x:.083,y:.066,z:-1.791},"RightHand.rotation":{x:-.52,y:-.001,z:-.176},"RightHandThumb1.rotation":{x:.227,y:.418,z:-.776},"RightHandThumb2.rotation":{x:-.011,y:-.003,z:.171},"RightHandThumb3.rotation":{x:-.041,y:-.001,z:-.013},"RightHandIndex1.rotation":{x:-.236,y:.003,z:-.028},"RightHandIndex2.rotation":{x:.004,y:0,z:.001},"RightHandIndex3.rotation":{x:.002,y:0,z:0},"RightHandMiddle1.rotation":{x:-.236,y:.003,z:-.028},"RightHandMiddle2.rotation":{x:.004,y:0,z:.001},"RightHandMiddle3.rotation":{x:.002,y:0,z:0},"RightHandRing1.rotation":{x:-.236,y:.003,z:-.028},"RightHandRing2.rotation":{x:.004,y:0,z:.001},"RightHandRing3.rotation":{x:.002,y:0,z:0},"RightHandPinky1.rotation":{x:-.236,y:.003,z:-.028},"RightHandPinky2.rotation":{x:.004,y:0,z:.001},"RightHandPinky3.rotation":{x:.002,y:0,z:0},"LeftShoulder.rotation":{x:1.711,y:-.002,z:-1.625},"LeftArm.rotation":{x:.683,y:.334,z:.977},"LeftForeArm.rotation":{x:.086,y:-.066,z:1.843},"LeftHand.rotation":{x:-.595,y:-.229,z:.096},"LeftHandThumb1.rotation":{x:.404,y:-.05,z:.537},"LeftHandThumb2.rotation":{x:-.02,y:.004,z:-.154},"LeftHandThumb3.rotation":{x:-.049,y:.002,z:-.019},"LeftHandIndex1.rotation":{x:-.113,y:-.001,z:.014},"LeftHandIndex2.rotation":{x:.003,y:0,z:0},"LeftHandIndex3.rotation":{x:.002,y:0,z:0},"LeftHandMiddle1.rotation":{x:-.113,y:-.001,z:.014},"LeftHandMiddle2.rotation":{x:.004,y:0,z:0},"LeftHandMiddle3.rotation":{x:.002,y:0,z:0},"LeftHandRing1.rotation":{x:-.113,y:-.001,z:.014},"LeftHandRing2.rotation":{x:.003,y:0,z:0},"LeftHandRing3.rotation":{x:.002,y:0,z:0},"LeftHandPinky1.rotation":{x:-.122,y:-.001,z:-.057},"LeftHandPinky2.rotation":{x:.012,y:.001,z:.07},"LeftHandPinky3.rotation":{x:.002,y:0,z:0}}},this.poseDelta={props:{"Hips.quaternion":{x:0,y:0,z:0},"Spine.quaternion":{x:0,y:0,z:0},"Spine1.quaternion":{x:0,y:0,z:0},"Neck.quaternion":{x:0,y:0,z:0},"Head.quaternion":{x:0,y:0,z:0},"Spine1.scale":{x:0,y:0,z:0},"Neck.scale":{x:0,y:0,z:0},"LeftArm.scale":{x:0,y:0,z:0},"RightArm.scale":{x:0,y:0,z:0}}},["Left","Right"].forEach(l=>{["Leg","UpLeg","Arm","ForeArm","Hand"].forEach(c=>{this.poseDelta.props[l+c+".quaternion"]={x:0,y:0,z:0}}),["HandThumb","HandIndex","HandMiddle","HandRing","HandPinky"].forEach(c=>{this.poseDelta.props[l+c+"1.quaternion"]={x:0,y:0,z:0},this.poseDelta.props[l+c+"2.quaternion"]={x:0,y:0,z:0},this.poseDelta.props[l+c+"3.quaternion"]={x:0,y:0,z:0}})});const n=new Set;Object.values(this.poseTemplates).forEach(l=>{Object.keys(this.propsToThreeObjects(l.props)).forEach(c=>n.add(c))}),Object.keys(this.poseDelta.props).forEach(l=>{n.add(l)}),this.posePropNames=[...n],this.poseName="side",this.poseWeightOnLeft=!0,this.gesture=null,this.poseCurrentTemplate=this.poseTemplates[this.poseName],this.poseStraight=this.propsToThreeObjects(this.poseTemplates.straight.props),this.poseBase=this.poseFactory(this.poseCurrentTemplate),this.poseTarget=this.poseFactory(this.poseCurrentTemplate),this.poseAvatar=null,this.avatarHeight=1.7,this.animTemplateEyes={name:"eyes",idle:{alt:[{p:()=>this.avatar?.hasOwnProperty("avatarIdleEyeContact")?this.avatar.avatarIdleEyeContact:this.opt.avatarIdleEyeContact,delay:[200,5e3],dt:[200,[2e3,5e3],[3e3,1e4,1,2]],vs:{headMove:[this.avatar?.hasOwnProperty("avatarIdleHeadMove")?this.avatar.avatarIdleHeadMove:this.opt.avatarIdleHeadMove],eyesRotateY:[[-.6,.6]],eyesRotateX:[[-.2,.6]],eyeContact:[null,1]}},{delay:[200,5e3],dt:[200,[2e3,5e3,1,2]],vs:{headMove:[this.avatar?.hasOwnProperty("avatarIdleHeadMove")?this.avatar.avatarIdleHeadMove:this.opt.avatarIdleHeadMove],eyesRotateY:[[-.6,.6]],eyesRotateX:[[-.2,.6]]}}]},speaking:{alt:[{p:()=>this.avatar?.hasOwnProperty("avatarSpeakingEyeContact")?this.avatar.avatarSpeakingEyeContact:this.opt.avatarSpeakingEyeContact,delay:[200,5e3],dt:[0,[3e3,1e4,1,2],[2e3,5e3]],vs:{eyeContact:[1,null],headMove:[null,this.avatar?.hasOwnProperty("avatarSpeakingHeadMove")?this.avatar.avatarSpeakingHeadMove:this.opt.avatarSpeakingHeadMove,null],eyesRotateY:[null,[-.6,.6]],eyesRotateX:[null,[-.2,.6]]}},{delay:[200,5e3],dt:[200,[2e3,5e3,1,2]],vs:{headMove:[this.avatar?.hasOwnProperty("avatarSpeakingHeadMove")?this.avatar.avatarSpeakingHeadMove:this.opt.avatarSpeakingHeadMove,null],eyesRotateY:[[-.6,.6]],eyesRotateX:[[-.2,.6]]}}]}},this.animTemplateBlink={name:"blink",alt:[{p:.85,delay:[1e3,8e3,1,2],dt:[50,[100,300],100],vs:{eyeBlinkLeft:[1,1,0],eyeBlinkRight:[1,1,0]}},{delay:[1e3,4e3,1,2],dt:[50,[100,200],100,[10,400,0],50,[100,200],100],vs:{eyeBlinkLeft:[1,1,0,0,1,1,0],eyeBlinkRight:[1,1,0,0,1,1,0]}}]},this.animMoods={neutral:{baseline:{eyesLookDown:0},speech:{deltaRate:0,deltaPitch:0,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1200,500,1e3],vs:{chestInhale:[.5,.5,0]}},{name:"pose",alt:[{p:.5,delay:[5e3,3e4],vs:{pose:["side"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{p:.3,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{delay:[5e3,3e4],vs:{pose:["straight"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}}]},{name:"head",idle:{delay:[0,1e3],dt:[[200,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.3,.3]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},happy:{baseline:{mouthSmile:.2,eyesLookDown:0},speech:{deltaRate:0,deltaPitch:.1,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1200,500,1e3],vs:{chestInhale:[.5,.5,0]}},{name:"pose",idle:{alt:[{p:.6,delay:[5e3,3e4],vs:{pose:["side"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{p:.2,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{p:.1,delay:[5e3,3e4],vs:{pose:["straight"]}},{delay:[5e3,1e4],vs:{pose:["wide"]}},{delay:[1e3,3e3],vs:{pose:["turn"]}}]},speaking:{alt:[{p:.4,delay:[5e3,3e4],vs:{pose:["side"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{p:.4,delay:[5e3,3e4],vs:{pose:["straight"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{delay:[5e3,2e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}}]}},{name:"head",idle:{dt:[[1e3,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.3,.3]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthLeft:[[0,.3,2]],mouthSmile:[[0,.2,3]],mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},angry:{baseline:{eyesLookDown:.1,browDownLeft:.6,browDownRight:.6,jawForward:.3,mouthFrownLeft:.7,mouthFrownRight:.7,mouthRollLower:.2,mouthShrugLower:.3,handFistLeft:1,handFistRight:1},speech:{deltaRate:-.2,deltaPitch:.2,deltaVolume:0},anims:[{name:"breathing",delay:500,dt:[1e3,500,1e3],vs:{chestInhale:[.7,.7,0]}},{name:"pose",alt:[{p:.4,delay:[5e3,3e4],vs:{pose:["side"]}},{p:.4,delay:[5e3,3e4],vs:{pose:["straight"]}},{p:.2,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}}]},{name:"head",idle:{delay:[100,500],dt:[[200,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.2,.2]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},sad:{baseline:{eyesLookDown:.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},speech:{deltaRate:-.2,deltaPitch:-.2,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1e3,500,1e3],vs:{chestInhale:[.3,.3,0]}},{name:"pose",alt:[{p:.4,delay:[5e3,3e4],vs:{pose:["side"]}},{p:.4,delay:[5e3,3e4],vs:{pose:["straight"]}},{delay:[5e3,2e4],vs:{pose:["side"]},full:{delay:[5e3,2e4],vs:{pose:["oneknee"]}}}]},{name:"head",idle:{delay:[100,500],dt:[[200,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.2,.2]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},fear:{baseline:{browInnerUp:.7,eyeSquintLeft:.5,eyeSquintRight:.5,eyeWideLeft:.6,eyeWideRight:.6,mouthClose:.1,mouthFunnel:.3,mouthShrugLower:.5,mouthShrugUpper:.5},speech:{deltaRate:-.2,deltaPitch:0,deltaVolume:0},anims:[{name:"breathing",delay:500,dt:[1e3,500,1e3],vs:{chestInhale:[.7,.7,0]}},{name:"pose",alt:[{p:.8,delay:[5e3,3e4],vs:{pose:["side"]}},{delay:[5e3,3e4],vs:{pose:["straight"]}},{delay:[5e3,2e4],vs:{pose:["wide"]}},{delay:[5e3,2e4],vs:{pose:["side"]},full:{delay:[5e3,2e4],vs:{pose:["oneknee"]}}}]},{name:"head",idle:{delay:[100,500],dt:[[200,3e3]],vs:{bodyRotateX:[[-.06,.12]],bodyRotateY:[[-.7,.7]],bodyRotateZ:[[-.1,.1]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},disgust:{baseline:{browDownLeft:.7,browDownRight:.1,browInnerUp:.3,eyeSquintLeft:1,eyeSquintRight:1,eyeWideLeft:.5,eyeWideRight:.5,eyesRotateX:.05,mouthLeft:.4,mouthPressLeft:.3,mouthRollLower:.3,mouthShrugLower:.3,mouthShrugUpper:.8,mouthUpperUpLeft:.3,noseSneerLeft:1,noseSneerRight:.7},speech:{deltaRate:-.2,deltaPitch:0,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1e3,500,1e3],vs:{chestInhale:[.5,.5,0]}},{name:"pose",alt:[{delay:[5e3,2e4],vs:{pose:["side"]}}]},{name:"head",idle:{delay:[100,500],dt:[[200,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.2,.2]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},love:{baseline:{browInnerUp:.4,browOuterUpLeft:.2,browOuterUpRight:.2,mouthSmile:.2,eyeBlinkLeft:.6,eyeBlinkRight:.6,eyeWideLeft:.7,eyeWideRight:.7,bodyRotateX:.1,mouthDimpleLeft:.1,mouthDimpleRight:.1,mouthPressLeft:.2,mouthShrugUpper:.2,mouthUpperUpLeft:.1,mouthUpperUpRight:.1},speech:{deltaRate:-.1,deltaPitch:-.7,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1500,500,1500],vs:{chestInhale:[.8,.8,0]}},{name:"pose",alt:[{p:.4,delay:[5e3,3e4],vs:{pose:["side"]}},{p:.2,delay:[5e3,3e4],vs:{pose:["straight"]}},{p:.2,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["side"]}}},{delay:[5e3,1e4],vs:{pose:["side"]},full:{delay:[5e3,1e4],vs:{pose:["kneel"]}}},{delay:[1e3,3e3],vs:{pose:["turn"]},M:{delay:[1e3,3e3],vs:{pose:["wide"]}}},{delay:[1e3,3e3],vs:{pose:["back"]},M:{delay:[1e3,3e3],vs:{pose:["wide"]}}},{delay:[5e3,2e4],vs:{pose:["side"]},M:{delay:[5e3,2e4],vs:{pose:["side"]}},full:{delay:[5e3,2e4],vs:{pose:["bend"]}}},{delay:[1e3,3e3],vs:{pose:["side"]},full:{delay:[5e3,1e4],vs:{pose:["oneknee"]}}}]},{name:"head",idle:{dt:[[1e3,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.3,.3]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.deepCopy(this.animTemplateBlink,l=>{l.alt[0].delay[0]=l.alt[1].delay[0]=2e3}),{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthLeft:[[0,.3,2]],mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[500,1e3],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[.3,.6,2]],browOuterUpLeft:[[.1,.3,2]],browOuterUpRight:[[.1,.3,2]]}}]},sleep:{baseline:{eyeBlinkLeft:1,eyeBlinkRight:1,eyesClosed:.6},speech:{deltaRate:0,deltaPitch:-.2,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1e3,500,1e3],vs:{chestInhale:[.6,.6,0]}},{name:"pose",alt:[{delay:[5e3,2e4],vs:{pose:["side"]}}]},{name:"head",delay:[1e3,5e3],dt:[[2e3,1e4]],vs:{bodyRotateX:[[0,.4]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.04,.04]]}},{name:"eyes",delay:10010,dt:[],vs:{}},{name:"blink",delay:10020,dt:[],vs:{}},{name:"mouth",delay:10030,dt:[],vs:{}},{name:"misc",delay:10040,dt:[],vs:{}}]}},this.moodName=this.opt.avatarMood||"neutral",this.mood=this.animMoods[this.moodName],this.mood||(this.moodName="neutral",this.mood=this.animMoods.neutral),this.animEmojis={"😐":{dt:[300,2e3],rescale:[0,1],vs:{pose:["straight"],browInnerUp:[.4],eyeWideLeft:[.7],eyeWideRight:[.7],mouthPressLeft:[.6],mouthPressRight:[.6],mouthRollLower:[.3],mouthStretchLeft:[1],mouthStretchRight:[1]}},"😶":{link:"😐"},"😏":{dt:[300,2e3],rescale:[0,1],vs:{eyeContact:[0],browDownRight:[.1],browInnerUp:[.7],browOuterUpRight:[.2],eyeLookInRight:[.7],eyeLookOutLeft:[.7],eyeSquintLeft:[1],eyeSquintRight:[.8],eyesRotateY:[.7],mouthLeft:[.4],mouthPucker:[.4],mouthShrugLower:[.3],mouthShrugUpper:[.2],mouthSmile:[.2],mouthSmileLeft:[.4],mouthSmileRight:[.2],mouthStretchLeft:[.5],mouthUpperUpLeft:[.6],noseSneerLeft:[.7]}},"🙂":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5]}},"🙃":{link:"🙂"},"😊":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.6],eyeSquintLeft:[1],eyeSquintRight:[1],mouthSmile:[.7],noseSneerLeft:[.7],noseSneerRight:[.7]}},"😇":{link:"😊"},"😀":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.6],jawOpen:[.1],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthOpen:[.3],mouthPressLeft:[.3],mouthPressRight:[.3],mouthRollLower:[.4],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"😃":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.6],eyeWideLeft:[.7],eyeWideRight:[.7],jawOpen:[.1],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthOpen:[.3],mouthPressLeft:[.3],mouthPressRight:[.3],mouthRollLower:[.4],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"😄":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.3],eyeSquintLeft:[1],eyeSquintRight:[1],jawOpen:[.2],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthOpen:[.3],mouthPressLeft:[.3],mouthPressRight:[.3],mouthRollLower:[.4],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"😁":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.3],eyeSquintLeft:[1],eyeSquintRight:[1],jawOpen:[.3],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthPressLeft:[.5],mouthPressRight:[.5],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"😆":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.3],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.6],jawOpen:[.3],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthPressLeft:[.5],mouthPressRight:[.5],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"😝":{dt:[300,100,1500,500,500],rescale:[0,0,1,0,0],vs:{browInnerUp:[.8],eyesClosed:[1],jawOpen:[.7],mouthFunnel:[.5],mouthSmile:[1],tongueOut:[0,1,1,0]}},"😋":{link:"😝"},"😛":{link:"😝"},"😛":{link:"😝"},"😜":{link:"😝"},"🤪":{link:"😝"},"😂":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.3],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.6],jawOpen:[.3],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthPressLeft:[.5],mouthPressRight:[.5],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"🤣":{link:"😂"},"😅":{link:"😂"},"😉":{dt:[500,200,500,500],rescale:[0,0,0,1],vs:{mouthSmile:[.5],mouthOpen:[.2],mouthSmileLeft:[0,.5,0],eyeBlinkLeft:[0,.7,0],eyeBlinkRight:[0,0,0],bodyRotateX:[.05,.05,.05,0],bodyRotateZ:[-.05,-.05,-.05,0],browDownLeft:[0,.7,0],cheekSquintLeft:[0,.7,0],eyeSquintLeft:[0,1,0],eyesClosed:[0]}},"😭":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[1],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.1],jawOpen:[0],mouthFrownLeft:[1],mouthFrownRight:[1],mouthOpen:[.5],mouthPucker:[.5],mouthUpperUpLeft:[.6],mouthUpperUpRight:[.6]}},"🥺":{dt:[1e3,1e3],rescale:[0,1],vs:{browDownLeft:[.2],browDownRight:[.2],browInnerUp:[1],eyeWideLeft:[.9],eyeWideRight:[.9],eyesClosed:[.1],mouthClose:[.2],mouthFrownLeft:[1],mouthFrownRight:[1],mouthPressLeft:[.4],mouthPressRight:[.4],mouthPucker:[1],mouthRollLower:[.6],mouthRollUpper:[.2],mouthUpperUpLeft:[.8],mouthUpperUpRight:[.8]}},"😞":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[.7],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.5],bodyRotateX:[.3],mouthClose:[.2],mouthFrownLeft:[1],mouthFrownRight:[1],mouthPucker:[1],mouthRollLower:[1],mouthShrugLower:[.2],mouthUpperUpLeft:[.8],mouthUpperUpRight:[.8]}},"😔":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[1],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.5],bodyRotateX:[.3],mouthClose:[.2],mouthFrownLeft:[1],mouthFrownRight:[1],mouthPressLeft:[.4],mouthPressRight:[.4],mouthPucker:[1],mouthRollLower:[.6],mouthRollUpper:[.2],mouthUpperUpLeft:[.8],mouthUpperUpRight:[.8]}},"😳":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[1],eyeWideLeft:[.5],eyeWideRight:[.5],eyesRotateY:[.05],eyesRotateX:[.05],mouthClose:[.2],mouthFunnel:[.5],mouthPucker:[.4],mouthRollLower:[.4],mouthRollUpper:[.4]}},"☹️":{dt:[500,1500],rescale:[0,1],vs:{mouthFrownLeft:[1],mouthFrownRight:[1],mouthPucker:[.1],mouthRollLower:[.8]}},"😚":{dt:[500,1e3,1e3],rescale:[0,1,0],vs:{browInnerUp:[.6],eyeBlinkLeft:[1],eyeBlinkRight:[1],eyeSquintLeft:[1],eyeSquintRight:[1],mouthPucker:[0,.5],noseSneerLeft:[0,.7],noseSneerRight:[0,.7],viseme_U:[0,1]}},"😘":{dt:[500,500,200,500],rescale:[0,0,0,1],vs:{browInnerUp:[.6],eyeBlinkLeft:[0,0,1,0],eyeBlinkRight:[0],eyesRotateY:[0],bodyRotateY:[0],bodyRotateX:[0,.05,.05,0],bodyRotateZ:[0,-.05,-.05,0],eyeSquintLeft:[1],eyeSquintRight:[1],mouthPucker:[0,.5,0],noseSneerLeft:[0,.7],noseSneerRight:[.7],viseme_U:[0,1]}},"🥰":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[.6],eyeSquintLeft:[1],eyeSquintRight:[1],mouthSmile:[.7],noseSneerLeft:[.7],noseSneerRight:[.7]}},"😍":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[.6],jawOpen:[.1],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthOpen:[.3],mouthPressLeft:[.3],mouthPressRight:[.3],mouthRollLower:[.4],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"🤩":{link:"😍"},"😡":{dt:[1e3,1500],rescale:[0,1],vs:{browDownLeft:[1],browDownRight:[1],eyesLookUp:[.2],jawForward:[.3],mouthFrownLeft:[1],mouthFrownRight:[1],bodyRotateX:[.15]}},"😠":{dt:[1e3,1500],rescale:[0,1],vs:{browDownLeft:[1],browDownRight:[1],eyesLookUp:[.2],jawForward:[.3],mouthFrownLeft:[1],mouthFrownRight:[1],bodyRotateX:[.15]}},"🤬":{link:"😠"},"😒":{dt:[1e3,1e3],rescale:[0,1],vs:{eyeContact:[0],browDownRight:[.1],browInnerUp:[.7],browOuterUpRight:[.2],eyeLookInRight:[.7],eyeLookOutLeft:[.7],eyeSquintLeft:[1],eyeSquintRight:[.8],eyesRotateY:[.7],mouthFrownLeft:[1],mouthFrownRight:[1],mouthLeft:[.2],mouthPucker:[.5],mouthRollLower:[.2],mouthRollUpper:[.2],mouthShrugLower:[.2],mouthShrugUpper:[.2],mouthStretchLeft:[.5]}},"😱":{dt:[500,1500],rescale:[0,1],vs:{browInnerUp:[.8],eyeWideLeft:[.5],eyeWideRight:[.5],jawOpen:[.7],mouthFunnel:[.5]}},"😬":{dt:[500,1500],rescale:[0,1],vs:{browDownLeft:[1],browDownRight:[1],browInnerUp:[1],mouthDimpleLeft:[.5],mouthDimpleRight:[.5],mouthLowerDownLeft:[1],mouthLowerDownRight:[1],mouthPressLeft:[.4],mouthPressRight:[.4],mouthPucker:[.5],mouthSmile:[.1],mouthSmileLeft:[.2],mouthSmileRight:[.2],mouthStretchLeft:[1],mouthStretchRight:[1],mouthUpperUpLeft:[1],mouthUpperUpRight:[1]}},"🙄":{dt:[500,1500],rescale:[0,1],vs:{browInnerUp:[.8],eyeWideLeft:[1],eyeWideRight:[1],eyesRotateX:[-.8],bodyRotateX:[.15],mouthPucker:[.5],mouthRollLower:[.6],mouthRollUpper:[.5],mouthShrugLower:[0],mouthSmile:[0]}},"🤔":{dt:[500,1500],rescale:[0,1],vs:{browDownLeft:[1],browOuterUpRight:[1],eyeSquintLeft:[.6],mouthFrownLeft:[.7],mouthFrownRight:[.7],mouthLowerDownLeft:[.3],mouthPressRight:[.4],mouthPucker:[.1],mouthRight:[.5],mouthRollLower:[.5],mouthRollUpper:[.2],handRight:[{x:.1,y:.1,z:.1,d:1e3},{d:1e3}],handFistRight:[.1]}},"👀":{dt:[500,1500],rescale:[0,1],vs:{eyesRotateY:[-.8]}},"😴":{dt:[5e3,5e3],rescale:[0,1],vs:{eyeBlinkLeft:[1],eyeBlinkRight:[1],bodyRotateX:[.2],bodyRotateZ:[.1]}},"✋":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5],gesture:[["handup",2,!0],null]}},"🤚":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5],gesture:[["handup",2],null]}},"👋":{link:"✋"},"👍":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5],gesture:[["thumbup",2],null]}},"👎":{dt:[300,2e3],rescale:[0,1],vs:{browDownLeft:[1],browDownRight:[1],eyesLookUp:[.2],jawForward:[.3],mouthFrownLeft:[1],mouthFrownRight:[1],bodyRotateX:[.15],gesture:[["thumbdown",2],null]}},"👌":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5],gesture:[["ok",2],null]}},"🤷‍♂️":{dt:[1e3,1500],rescale:[0,1],vs:{gesture:[["shrug",2],null]}},"🤷‍♀️":{link:"🤷‍♂️"},"🤷":{link:"🤷‍♂️"},"🙏":{dt:[1500,300,1e3],rescale:[0,1,0],vs:{eyeBlinkLeft:[0,1],eyeBlinkRight:[0,1],bodyRotateX:[0],bodyRotateZ:[.1],gesture:[["namaste",2],null]}},yes:{dt:[[200,500],[200,500],[200,500],[200,500]],vs:{headMove:[0],headRotateX:[[.1,.2],.1,[.1,.2],0],headRotateZ:[[-.2,.2]]}},no:{dt:[[200,500],[200,500],[200,500],[200,500],[200,500]],vs:{headMove:[0],headRotateY:[[-.1,-.05],[.05,.1],[-.1,-.05],[.05,.1],0],headRotateZ:[[-.2,.2]]}}},this.mtAvatar={},this.mtCustoms=["handFistLeft","handFistRight","bodyRotateX","bodyRotateY","bodyRotateZ","headRotateX","headRotateY","headRotateZ","chestInhale"],this.mtEasingDefault=this.sigmoidFactory(5),this.mtAccDefault=.01,this.mtAccExceptions={eyeBlinkLeft:.1,eyeBlinkRight:.1,eyeLookOutLeft:.1,eyeLookInLeft:.1,eyeLookOutRight:.1,eyeLookInRight:.1},this.mtMaxVDefault=5,this.mtMaxVExceptions={bodyRotateX:1,bodyRotateY:1,bodyRotateZ:1},this.mtBaselineDefault=0,this.mtBaselineExceptions={bodyRotateX:null,bodyRotateY:null,bodyRotateZ:null,eyeLookOutLeft:null,eyeLookInLeft:null,eyeLookOutRight:null,eyeLookInRight:null,eyesLookDown:null,eyesLookUp:null},this.mtMinDefault=0,this.mtMinExceptions={bodyRotateX:-1,bodyRotateY:-1,bodyRotateZ:-1,headRotateX:-1,headRotateY:-1,headRotateZ:-1},this.mtMaxDefault=1,this.mtMaxExceptions={},this.mtLimits={eyeBlinkLeft:l=>Math.max(l,(this.mtAvatar.eyesLookDown.value+this.mtAvatar.browDownLeft.value)/2),eyeBlinkRight:l=>Math.max(l,(this.mtAvatar.eyesLookDown.value+this.mtAvatar.browDownRight.value)/2)},this.mtOnchange={eyesLookDown:()=>{this.mtAvatar.eyeBlinkLeft.needsUpdate=!0,this.mtAvatar.eyeBlinkRight.needsUpdate=!0},browDownLeft:()=>{this.mtAvatar.eyeBlinkLeft.needsUpdate=!0},browDownRight:()=>{this.mtAvatar.eyeBlinkRight.needsUpdate=!0}},this.mtRandomized=["mouthDimpleLeft","mouthDimpleRight","mouthLeft","mouthPressLeft","mouthPressRight","mouthStretchLeft","mouthStretchRight","mouthShrugLower","mouthShrugUpper","noseSneerLeft","noseSneerRight","mouthRollLower","mouthRollUpper","browDownLeft","browDownRight","browOuterUpLeft","browOuterUpRight","cheekPuff","cheekSquintLeft","cheekSquintRight"],this.mtExtras=[{key:"mouthOpen",mix:{jawOpen:.5}},{key:"mouthSmile",mix:{mouthSmileLeft:.8,mouthSmileRight:.8}},{key:"eyesClosed",mix:{eyeBlinkLeft:1,eyeBlinkRight:1}},{key:"eyesLookUp",mix:{eyeLookUpLeft:1,eyeLookUpRight:1}},{key:"eyesLookDown",mix:{eyeLookDownLeft:1,eyeLookDownRight:1}}],this.animQueue=[],this.animClips=[],this.animPoses=[],this.animFrameDur=1e3/this.opt.modelFPS,this.animClock=0,this.animSlowdownRate=1,this.animTimeLast=0,this.easing=this.sigmoidFactory(5),this.lipsync={},this.opt.lipsyncModules.forEach(l=>{this.lipsyncGetProcessor(l)}),this.visemeNames=["aa","E","I","O","U","PP","SS","TH","DD","FF","kk","nn","RR","CH","sil"],this.segmenter=new Intl.Segmenter("en",{granularity:"grapheme"}),this.initAudioGraph(),this.audioPlaylist=[],this.volumeFrequencyData=new Uint8Array(16),this.volumeMax=0,this.volumeHeadBase=0,this.volumeHeadTarget=0,this.volumeHeadCurrent=0,this.volumeHeadVelocity=.15,this.volumeHeadEasing=this.sigmoidFactory(3),this.isListening=!1,this.listeningAnalyzer=null,this.listeningActive=!1,this.listeningVolume=0,this.listeningSilenceThresholdLevel=this.opt.listeningSilenceThresholdLevel,this.listeningSilenceThresholdMs=this.opt.listeningSilenceThresholdMs,this.listeningSilenceDurationMax=this.opt.listeningSilenceDurationMax,this.listeningActiveThresholdLevel=this.opt.listeningActiveThresholdLevel,this.listeningActiveThresholdMs=this.opt.listeningActiveThresholdMs,this.listeningActiveDurationMax=this.opt.listeningActiveDurationMax,this.listeningTimer=0,this.listeningTimerTotal=0,this.dracoEnabled=this.opt.dracoEnabled,this.dracoDecoderPath=this.opt.dracoDecoderPath;const i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";this.b64Lookup=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let l=0;l<i.length;l++)this.b64Lookup[i.charCodeAt(l)]=l;if(this.stateName="idle",this.speechQueue=[],this.isSpeaking=!1,this.isListening=!1,this.opt.ttsEndpoint){let l=new Audio;if(l.canPlayType("audio/ogg"))this.ttsAudioEncoding="OGG-OPUS";else if(l.canPlayType("audio/mp3"))this.ttsAudioEncoding="MP3";else throw new Error("There was no support for either OGG or MP3 audio.")}if(this.isAvatarOnly=this.opt.avatarOnly,this.isAvatarOnly)this.scene=this.opt.avatarOnlyScene,this.camera=this.opt.avatarOnlyCamera;else{this.renderer=new y.WebGLRenderer({antialias:!0,alpha:!0}),this.renderer.setPixelRatio(this.opt.modelPixelRatio*window.devicePixelRatio),this.renderer.setSize(this.nodeAvatar.clientWidth,this.nodeAvatar.clientHeight),this.renderer.outputColorSpace=y.SRGBColorSpace,this.renderer.toneMapping=y.ACESFilmicToneMapping,this.renderer.shadowMap.enabled=!1,this.nodeAvatar.appendChild(this.renderer.domElement),this.camera=new y.PerspectiveCamera(10,this.nodeAvatar.clientWidth/this.nodeAvatar.clientHeight,.1,2e3),this.scene=new y.Scene,this.lightAmbient=new y.AmbientLight(new y.Color(this.opt.lightAmbientColor),this.opt.lightAmbientIntensity),this.lightDirect=new y.DirectionalLight(new y.Color(this.opt.lightDirectColor),this.opt.lightDirectIntensity),this.lightSpot=new y.SpotLight(new y.Color(this.opt.lightSpotColor),this.opt.lightSpotIntensity,0,this.opt.lightSpotDispersion),this.setLighting(this.opt);const l=new y.PMREMGenerator(this.renderer);l.compileEquirectangularShader(),this.scene.environment=l.fromScene(new Ye.RoomEnvironment).texture,this.resizeobserver=new ResizeObserver(this.onResize.bind(this)),this.resizeobserver.observe(this.nodeAvatar),this.controls=new Ze.OrbitControls(this.camera,this.renderer.domElement),this.controls.enableZoom=this.opt.cameraZoomEnable,this.controls.enableRotate=this.opt.cameraRotateEnable,this.controls.enablePan=this.opt.cameraPanEnable,this.controls.minDistance=2,this.controls.maxDistance=2e3,this.controls.autoRotateSpeed=0,this.controls.autoRotate=!1,this.controls.update(),this.cameraClock=null}this.ikMesh=new y.SkinnedMesh;const s={LeftShoulder:null,LeftArm:"LeftShoulder",LeftForeArm:"LeftArm",LeftHand:"LeftForeArm",LeftHandMiddle1:"LeftHand",RightShoulder:null,RightArm:"RightShoulder",RightForeArm:"RightArm",RightHand:"RightForeArm",RightHandMiddle1:"RightHand"},o=[];Object.entries(s).forEach((l,c)=>{const r=new y.Bone;r.name=l[0],l[1]?this.ikMesh.getObjectByName(l[1]).add(r):this.ikMesh.add(r),o.push(r)}),this.ikMesh.bind(new y.Skeleton(o)),this.dynamicbones=new $e,this.isStreaming=!1,this.streamWorkletNode=null,this.streamAudioStartTime=null,this.streamWaitForAudioChunks=!0,this.streamLipsyncLang=null,this.streamLipsyncType="visemes",this.streamLipsyncQueue=[]}initAudioGraph(t=null){if(this.audioCtx&&this.audioCtx.state!=="closed"&&this.audioCtx.close(),t?this.audioCtx=new AudioContext({sampleRate:t}):this.audioCtx=new AudioContext,this.audioSpeechSource=this.audioCtx.createBufferSource(),this.audioBackgroundSource=this.audioCtx.createBufferSource(),this.audioBackgroundGainNode=this.audioCtx.createGain(),this.audioSpeechGainNode=this.audioCtx.createGain(),this.audioStreamGainNode=this.audioCtx.createGain(),this.audioAnalyzerNode=this.audioCtx.createAnalyser(),this.audioAnalyzerNode.fftSize=256,this.audioAnalyzerNode.smoothingTimeConstant=.1,this.audioAnalyzerNode.minDecibels=-70,this.audioAnalyzerNode.maxDecibels=-10,this.audioAnalyzer=new et(this.audioCtx),this.audioReverbNode=this.audioCtx.createConvolver(),this.audioBackgroundGainNode.connect(this.audioReverbNode),this.audioAnalyzerNode.connect(this.audioSpeechGainNode),this.audioSpeechGainNode.connect(this.audioReverbNode),this.audioStreamGainNode.connect(this.audioReverbNode),this.audioReverbNode.connect(this.audioCtx.destination),this.setReverb(this.currentReverb||null),this.setMixerGain(this.opt.mixerGainSpeech,this.opt.mixerGainBackground),this.workletLoaded=!1,this.streamWorkletNode){try{this.streamWorkletNode.port.postMessage({type:"stop"}),this.streamWorkletNode.disconnect(),this.isStreaming=!1}catch(e){console.error("Error disconnecting streamWorkletNode:",e)}this.streamWorkletNode=null}}valueFn(t){return typeof t=="function"?t():t}deepCopy(t,e=null){const n=JSON.parse(JSON.stringify(t));return e&&typeof e=="function"&&e(n),n}b64ToArrayBuffer(t){let e=3*t.length/4;t[t.length-1]==="="&&(e--,t[t.length-2]==="="&&e--);const n=new ArrayBuffer(e),i=new Uint8Array(n);let s,o=0,l,c,r,u;for(s=0;s<t.length;s+=4)l=this.b64Lookup[t.charCodeAt(s)],c=this.b64Lookup[t.charCodeAt(s+1)],r=this.b64Lookup[t.charCodeAt(s+2)],u=this.b64Lookup[t.charCodeAt(s+3)],i[o++]=l<<2|c>>4,i[o++]=(c&15)<<4|r>>2,i[o++]=(r&3)<<6|u&63;return n}concatArrayBuffers(t){if(t.length===1)return t[0];let e=0;for(let o=0;o<t.length;o++)e+=t[o].byteLength;let n=new ArrayBuffer(e),i=new Uint8Array(n),s=0;for(let o=0;o<t.length;o++)i.set(new Uint8Array(t[o]),s),s+=t[o].byteLength;return n}pcmToAudioBuffer(t){const e=new Int16Array(t),n=new Float32Array(e.length);for(let s=0;s<e.length;s++)n[s]=e[s]>=32768?-(65536-e[s])/32768:e[s]/32767;const i=this.audioCtx.createBuffer(1,n.length,this.opt.pcmSampleRate);return i.copyToChannel(n,0,0),i}propsToThreeObjects(t){const e={};for(let[n,i]of Object.entries(t)){const s=n.split(".");let o=Array.isArray(i.x)?this.gaussianRandom(...i.x):i.x,l=Array.isArray(i.y)?this.gaussianRandom(...i.y):i.y,c=Array.isArray(i.z)?this.gaussianRandom(...i.z):i.z;s[1]==="position"||s[1]==="scale"?e[n]=new y.Vector3(o,l,c):s[1]==="rotation"?(n=s[0]+".quaternion",e[n]=new y.Quaternion().setFromEuler(new y.Euler(o,l,c,"XYZ")).normalize()):s[1]==="quaternion"&&(e[n]=new y.Quaternion(o,l,c,i.w).normalize())}return e}clearThree(t){for(;t.children.length;)this.clearThree(t.children[0]),t.remove(t.children[0]);t.geometry&&t.geometry.dispose(),t.material&&(Object.keys(t.material).forEach(e=>{t.material[e]&&t.material[e]!==null&&typeof t.material[e].dispose=="function"&&t.material[e].dispose()}),t.material.dispose())}addMixedMorphTarget(t,e,n,i=!1){t.forEach(s=>{if(!i&&s.morphTargetDictionary.hasOwnProperty(e))return;const o=s.geometry;let l=null,c=null;for(const[r,u]of Object.entries(n))if(s.morphTargetDictionary.hasOwnProperty(r)){const a=s.morphTargetDictionary[r],d=o.morphAttributes.position[a],h=o.morphAttributes.normal?.[a];l||(l=new y.Float32BufferAttribute(d.count*3,3),h&&(c=new y.Float32BufferAttribute(d.count*3,3)));for(let g=0;g<d.count;g++){const x=l.getX(g)+d.getX(g)*u,f=l.getY(g)+d.getY(g)*u,w=l.getZ(g)+d.getZ(g)*u;l.setXYZ(g,x,f,w)}if(h)for(let g=0;g<d.count;g++){const x=c.getX(g)+h.getX(g)*u,f=c.getY(g)+h.getY(g)*u,w=c.getZ(g)+h.getZ(g)*u;c.setXYZ(g,x,f,w)}}if(l){o.morphAttributes.position.push(l),c&&o.morphAttributes.normal.push(c);const r=o.morphAttributes.position.length-1;s.morphTargetInfluences[r]=0,s.morphTargetDictionary[e]=r}})}async showAvatar(t,e=null){if(!t||!t.hasOwnProperty("url"))throw new Error("Invalid parameter. The avatar must have at least 'url' specified.");const n=new Xe.GLTFLoader;if(this.dracoEnabled){const r=new je.DRACOLoader;r.setDecoderPath(this.dracoDecoderPath),n.setDRACOLoader(r)}let i=await n.loadAsync(t.url,e);const s=[this.opt.modelRoot];if(this.posePropNames.forEach(r=>s.push(r.split(".")[0])),s.forEach(r=>{if(!i.scene.getObjectByName(r))throw new Error("Avatar object "+r+" not found")}),this.stop(),this.avatar=t,this.bodyMovement=t.bodyMovement||"idle",this.movementIntensity=t.movementIntensity||.5,this.showFullAvatar=t.showFullAvatar||!1,this.fbxAnimationLoader=null,this.dynamicbones.dispose(),this.mixer=null,this.isAvatarOnly?this.armature&&this.clearThree(this.armature):this.armature&&this.clearThree(this.scene),this.armature=i.scene.getObjectByName(this.opt.modelRoot),this.armature.scale.setScalar(1),this.animations=i.animations,this.userData=i.userData,this.morphs=[],this.armature.traverse(r=>{r.morphTargetInfluences&&r.morphTargetInfluences.length&&r.morphTargetDictionary&&this.morphs.push(r),r.frustumCulled=!1}),this.morphs.length===0)throw new Error("Blend shapes not found");const o=new Set(this.mtCustoms);this.morphs.forEach(r=>{Object.keys(r.morphTargetDictionary).forEach(u=>o.add(u))}),this.mtExtras.forEach(r=>{o.has(r.key)||(this.addMixedMorphTarget(this.morphs,r.key,r.mix),o.add(r.key))});const l={};if(o.forEach(r=>{l[r]={fixed:null,realtime:null,system:null,systemd:null,newvalue:null,ref:null,min:this.mtMinExceptions.hasOwnProperty(r)?this.mtMinExceptions[r]:this.mtMinDefault,max:this.mtMaxExceptions.hasOwnProperty(r)?this.mtMaxExceptions[r]:this.mtMaxDefault,easing:this.mtEasingDefault,base:null,v:0,needsUpdate:!0,acc:(this.mtAccExceptions.hasOwnProperty(r)?this.mtAccExceptions[r]:this.mtAccDefault)/1e3,maxv:(this.mtMaxVExceptions.hasOwnProperty(r)?this.mtMaxVExceptions[r]:this.mtMaxVDefault)/1e3,limit:this.mtLimits.hasOwnProperty(r)?this.mtLimits[r]:null,onchange:this.mtOnchange.hasOwnProperty(r)?this.mtOnchange[r]:null,baseline:this.avatar.baseline?.hasOwnProperty(r)?this.avatar.baseline[r]:this.mtBaselineExceptions.hasOwnProperty(r)?this.mtBaselineExceptions[r]:this.mtBaselineDefault,ms:[],is:[]},l[r].value=l[r].baseline,l[r].applied=l[r].baseline;const u=this.mtAvatar[r];u&&["fixed","system","systemd","realtime","base","v","value","applied"].forEach(a=>{l[r][a]=u[a]}),this.morphs.forEach(a=>{const d=a.morphTargetDictionary[r];d!==void 0&&(l[r].ms.push(a.morphTargetInfluences),l[r].is.push(d),a.morphTargetInfluences[d]=l[r].applied)})}),this.mtAvatar=l,this.poseAvatar={props:{}},this.posePropNames.forEach(r=>{const u=r.split("."),a=this.armature.getObjectByName(u[0]);this.poseAvatar.props[r]=a[u[1]],this.poseBase.props.hasOwnProperty(r)?this.poseAvatar.props[r].copy(this.poseBase.props[r]):this.poseBase.props[r]=this.poseAvatar.props[r].clone(),this.poseDelta.props.hasOwnProperty(r)&&!this.poseTarget.props.hasOwnProperty(r)&&(this.poseTarget.props[r]=this.poseAvatar.props[r].clone()),this.poseTarget.props[r].t=this.animClock,this.poseTarget.props[r].d=2e3}),this.ikMesh.traverse(r=>{r.isBone&&r.position.copy(this.armature.getObjectByName(r.name).position)}),this.isAvatarOnly?this.scene&&this.scene.add(this.armature):(this.scene.add(i.scene),this.scene.add(this.lightAmbient),this.scene.add(this.lightDirect),this.scene.add(this.lightSpot),this.lightSpot.target=this.armature.getObjectByName("Head")),t.hasOwnProperty("modelDynamicBones"))try{this.dynamicbones.setup(this.scene,this.armature,t.modelDynamicBones)}catch(r){console.error("Dynamic bones setup failed: "+r)}this.objectLeftToeBase=this.armature.getObjectByName("LeftToeBase"),this.objectRightToeBase=this.armature.getObjectByName("RightToeBase"),this.objectLeftEye=this.armature.getObjectByName("LeftEye"),this.objectRightEye=this.armature.getObjectByName("RightEye"),this.objectLeftArm=this.armature.getObjectByName("LeftArm"),this.objectRightArm=this.armature.getObjectByName("RightArm"),this.objectHips=this.armature.getObjectByName("Hips"),this.objectHead=this.armature.getObjectByName("Head"),this.objectNeck=this.armature.getObjectByName("Neck");const c=new y.Vector3;this.objectLeftEye.getWorldPosition(c),this.avatarHeight=c.y+.2,this.viewName||this.setView(this.opt.cameraView),this.setMood(this.avatar.avatarMood||this.moodName||this.opt.avatarMood),this.avatar.body==="M"&&this.poseTemplates.wide&&(this.poseName="wide",this.setPoseFromTemplate(this.poseTemplates.wide,0),console.log("Set initial male-appropriate pose: wide")),this.initializeFBXAnimationLoader(),this.bodyMovement&&this.bodyMovement!=="idle"&&this.applyBodyMovementAnimation(),this.start()}getViewNames(){return["full","mid","upper","head"]}getView(){return this.viewName}setView(t,e=null){if(t=t||this.viewName,t!=="full"&&t!=="upper"&&t!=="head"&&t!=="mid")return;if(!this.armature){this.opt.cameraView=t;return}if(this.viewName=t||this.viewName,e=e||{},this.isAvatarOnly)return;const n=e.hasOwnProperty("cameraX")?e.cameraX:this.opt.cameraX,i=e.hasOwnProperty("cameraY")?e.cameraY:this.opt.cameraY,s=e.hasOwnProperty("cameraDistance")?e.cameraDistance:this.opt.cameraDistance,o=e.hasOwnProperty("cameraRotateX")?e.cameraRotateX:this.opt.cameraRotateX,l=e.hasOwnProperty("cameraRotateY")?e.cameraRotateY:this.opt.cameraRotateY,c=this.camera.fov*(Math.PI/180);let r=-n*Math.tan(c/2),u=(1-i)*Math.tan(c/2),a=s;switch(this.viewName){case"head":a+=2,u=u*a+4*this.avatarHeight/5;break;case"upper":a+=4.5,u=u*a+2*this.avatarHeight/3;break;case"mid":a+=8,u=u*a+this.avatarHeight/3;break;default:a+=12,u=u*a}r=r*a,this.controlsEnd=new y.Vector3(r,u,0),this.cameraEnd=new y.Vector3(r,u,a).applyEuler(new y.Euler(o,l,0)),this.cameraClock===null&&(this.controls.target.copy(this.controlsEnd),this.camera.position.copy(this.cameraEnd)),this.controlsStart=this.controls.target.clone(),this.cameraStart=this.camera.position.clone(),this.cameraClock=0}setLighting(t){this.isAvatarOnly||(t=t||{},t.hasOwnProperty("lightAmbientColor")&&this.lightAmbient.color.set(new y.Color(t.lightAmbientColor)),t.hasOwnProperty("lightAmbientIntensity")&&(this.lightAmbient.intensity=t.lightAmbientIntensity,this.lightAmbient.visible=t.lightAmbientIntensity!==0),t.hasOwnProperty("lightDirectColor")&&this.lightDirect.color.set(new y.Color(t.lightDirectColor)),t.hasOwnProperty("lightDirectIntensity")&&(this.lightDirect.intensity=t.lightDirectIntensity,this.lightDirect.visible=t.lightDirectIntensity!==0),t.hasOwnProperty("lightDirectPhi")&&t.hasOwnProperty("lightDirectTheta")&&this.lightDirect.position.setFromSphericalCoords(2,t.lightDirectPhi,t.lightDirectTheta),t.hasOwnProperty("lightSpotColor")&&this.lightSpot.color.set(new y.Color(t.lightSpotColor)),t.hasOwnProperty("lightSpotIntensity")&&(this.lightSpot.intensity=t.lightSpotIntensity,this.lightSpot.visible=t.lightSpotIntensity!==0),t.hasOwnProperty("lightSpotPhi")&&t.hasOwnProperty("lightSpotTheta")&&(this.lightSpot.position.setFromSphericalCoords(2,t.lightSpotPhi,t.lightSpotTheta),this.lightSpot.position.add(new y.Vector3(0,1.5,0))),t.hasOwnProperty("lightSpotDispersion")&&(this.lightSpot.angle=t.lightSpotDispersion))}render(){this.isRunning&&!this.isAvatarOnly&&this.renderer&&this.renderer.render(this.scene,this.camera)}onResize(){!this.isAvatarOnly&&this.renderer&&(this.camera.aspect=this.nodeAvatar.clientWidth/this.nodeAvatar.clientHeight,this.camera.updateProjectionMatrix(),this.renderer.setSize(this.nodeAvatar.clientWidth,this.nodeAvatar.clientHeight),this.controls.update(),this.render())}updatePoseBase(t){for(const[e,n]of Object.entries(this.poseTarget.props)){const i=this.poseAvatar.props[e];if(i){let s=(t-n.t)/n.d;s>1||!this.poseBase.props.hasOwnProperty(e)?i.copy(n):i.isQuaternion?i.copy(this.poseBase.props[e].slerp(n,this.easing(s))):i.isVector3&&i.copy(this.poseBase.props[e].lerp(n,this.easing(s)))}}}updatePoseDelta(){for(const[t,e]of Object.entries(this.poseDelta.props)){if(e.x===0&&e.y===0&&e.z===0)continue;V.set(e.x,e.y,e.z);const n=this.poseAvatar.props[t];n.isQuaternion?(K.setFromEuler(V),n.multiply(K)):n.isVector3&&n.add(V)}}updateMorphTargets(t){for(let[e,n]of Object.entries(this.mtAvatar)){if(!n.needsUpdate)continue;let i=null,s=null;if(n.fixed!==null){if(i=n.fixed,n.system=null,n.systemd=null,n.newvalue=null,n.ref&&n.ref.hasOwnProperty(e)&&delete n.ref[e],n.ref=null,n.base=null,n.value===i){n.needsUpdate=!1;continue}}else n.realtime!==null?(n.ref=null,n.base=null,s=n.realtime):n.system!==null?(i=n.system,n.newvalue=null,n.ref&&n.ref.hasOwnProperty(e)&&delete n.ref[e],n.ref=null,n.base=null,n.systemd!==null?n.systemd===0?(i=null,n.system=null,n.systemd=null):(n.systemd-=t,n.systemd<0&&(n.systemd=0),n.value===i&&(i=null)):n.value===i&&(i=null,n.system=null)):n.newvalue!==null?(n.ref=null,n.base=null,s=n.newvalue,n.newvalue=null):n.base!==null?(i=n.base,n.ref=null,n.value===i&&(i=null,n.base=null,n.needsUpdate=!1)):(n.ref=null,n.baseline!==null&&n.value!==n.baseline?(i=n.baseline,n.base=n.baseline):n.needsUpdate=!1);if(i!==null){let o=i-n.value;o>=0?o<.005?(s=i,n.v=0):(n.v<n.maxv&&(n.v+=n.acc*t),n.v>=0?s=n.value+o*(1-Math.exp(-n.v*t)):s=n.value+n.v*t*(1-Math.exp(n.v*t))):o>-.005?(s=i,n.v=0):(n.v>-n.maxv&&(n.v-=n.acc*t),n.v>=0?s=n.value+n.v*t*(1-Math.exp(-n.v*t)):s=n.value+o*(1-Math.exp(n.v*t)))}if(n.limit!==null){if(s!==null&&s!==n.value&&(n.value=s,n.onchange!==null&&n.onchange(s)),s=n.limit(n.value),s===n.applied)continue}else{if(s===null||s===n.value)continue;n.value=s,n.onchange!==null&&n.onchange(s)}switch(n.applied=s,n.applied<n.min&&(n.applied=n.min),n.applied>n.max&&(n.applied=n.max),e){case"headRotateX":this.poseDelta.props["Head.quaternion"].x=n.applied+this.mtAvatar.bodyRotateX.applied;break;case"headRotateY":this.poseDelta.props["Head.quaternion"].y=n.applied+this.mtAvatar.bodyRotateY.applied;break;case"headRotateZ":this.poseDelta.props["Head.quaternion"].z=n.applied+this.mtAvatar.bodyRotateZ.applied;break;case"bodyRotateX":this.poseDelta.props["Head.quaternion"].x=n.applied+this.mtAvatar.headRotateX.applied,this.poseDelta.props["Spine1.quaternion"].x=n.applied/2,this.poseDelta.props["Spine.quaternion"].x=n.applied/8,this.poseDelta.props["Hips.quaternion"].x=n.applied/24;break;case"bodyRotateY":this.poseDelta.props["Head.quaternion"].y=n.applied+this.mtAvatar.headRotateY.applied,this.poseDelta.props["Spine1.quaternion"].y=n.applied/2,this.poseDelta.props["Spine.quaternion"].y=n.applied/2,this.poseDelta.props["Hips.quaternion"].y=n.applied/4,this.poseDelta.props["LeftUpLeg.quaternion"].y=n.applied/2,this.poseDelta.props["RightUpLeg.quaternion"].y=n.applied/2,this.poseDelta.props["LeftLeg.quaternion"].y=n.applied/4,this.poseDelta.props["RightLeg.quaternion"].y=n.applied/4;break;case"bodyRotateZ":this.poseDelta.props["Head.quaternion"].z=n.applied+this.mtAvatar.headRotateZ.applied,this.poseDelta.props["Spine1.quaternion"].z=n.applied/12,this.poseDelta.props["Spine.quaternion"].z=n.applied/12,this.poseDelta.props["Hips.quaternion"].z=n.applied/24;break;case"handFistLeft":case"handFistRight":const o=e.substring(8);["HandThumb","HandIndex","HandMiddle","HandRing","HandPinky"].forEach((u,a)=>{a===0?(this.poseDelta.props[o+u+"1.quaternion"].x=0,this.poseDelta.props[o+u+"2.quaternion"].z=(o==="Left"?-1:1)*n.applied,this.poseDelta.props[o+u+"3.quaternion"].z=(o==="Left"?-1:1)*n.applied):(this.poseDelta.props[o+u+"1.quaternion"].x=n.applied,this.poseDelta.props[o+u+"2.quaternion"].x=1.5*n.applied,this.poseDelta.props[o+u+"3.quaternion"].x=1.5*n.applied)});break;case"chestInhale":const l=n.applied/20,c={x:l,y:l/2,z:3*l},r={x:1/(1+l)-1,y:1/(1+l/2)-1,z:1/(1+3*l)-1};this.poseDelta.props["Spine1.scale"]=c,this.poseDelta.props["Neck.scale"]=r,this.poseDelta.props["LeftArm.scale"]=r,this.poseDelta.props["RightArm.scale"]=r;break;default:for(let u=0,a=n.ms.length;u<a;u++)n.ms[u][n.is[u]]=n.applied}}}getPoseString(t,e=1e3){let n="{";return Object.entries(t).forEach((i,s)=>{const o=i[0].split(".");if(o[1]==="position"||o[1]==="rotation"||o[1]==="quaternion"){const l=o[1]==="quaternion"?o[0]+".rotation":i[0],c=i[1].isQuaternion?new y.Euler().setFromQuaternion(i[1]):i[1];n+=(s?", ":"")+"'"+l+"':{",n+="x:"+Math.round(c.x*e)/e,n+=", y:"+Math.round(c.y*e)/e,n+=", z:"+Math.round(c.z*e)/e,n+="}"}}),n+="}",n}getPoseTemplateProp(t){const e=t.split(".");let n=e[0]+"."+(e[1]==="rotation"?"quaternion":e[1]);if(this.gesture&&this.gesture.hasOwnProperty(n))return this.gesture[n].clone();{let i=e[0]+"."+(e[1]==="quaternion"?"rotation":e[1]);this.poseWeightOnLeft||(i.startsWith("Left")?(i="Right"+i.substring(4),n="Right"+n.substring(4)):i.startsWith("Right")&&(i="Left"+i.substring(5),n="Left"+n.substring(5)));let s;if(this.poseTarget.template.props.hasOwnProperty(n)){const o={};o[n]=this.poseTarget.template.props[n],s=this.propsToThreeObjects(o)[n]}else if(this.poseTarget.template.props.hasOwnProperty(i)){const o={};o[i]=this.poseTarget.template.props[i],s=this.propsToThreeObjects(o)[n]}return s&&!this.poseWeightOnLeft&&s.isQuaternion&&(s.x*=-1,s.w*=-1),s}}mirrorPose(t){const e={};for(let[n,i]of Object.entries(t))i.isQuaternion&&(n.startsWith("Left")?n="Right"+n.substring(4):n.startsWith("Right")&&(n="Left"+n.substring(5)),i.x*=-1,i.w*=-1),e[n]=i.clone(),e[n].t=i.t,e[n].d=i.d;return e}poseFactory(t,e=2e3){const n={template:t,props:this.propsToThreeObjects(t.props)};for(const[i,s]of Object.entries(n.props)){if(this.opt.modelMovementFactor<1&&t.standing&&(i==="Hips.quaternion"||i==="Spine.quaternion"||i==="Spine1.quaternion"||i==="Spine2.quaternion"||i==="Neck.quaternion"||i==="LeftUpLeg.quaternion"||i==="LeftLeg.quaternion"||i==="RightUpLeg.quaternion"||i==="RightLeg.quaternion")){const o=this.poseStraight[i],l=s.angleTo(o);s.rotateTowards(o,(1-this.opt.modelMovementFactor)*l)}s.t=this.animClock,s.d=e}return n}setPoseFromTemplate(t,e=2e3){const n=t&&this.poseTarget&&this.poseTarget.template&&(this.poseTarget.template.standing&&t.lying||this.poseTarget.template.lying&&t.standing),i=t&&t===this.poseCurrentTemplate,s=this.poseWeightOnLeft;let o=n?1e3:e;if(n?(this.poseCurrentTemplate=this.poseTemplates.oneknee,setTimeout(()=>{this.setPoseFromTemplate(t,e)},o)):this.poseCurrentTemplate=t||this.poseCurrentTemplate,this.poseTarget=this.poseFactory(this.poseCurrentTemplate,o),this.poseWeightOnLeft=!0,(!i&&!s||i&&s)&&(this.poseTarget.props=this.mirrorPose(this.poseTarget.props),this.poseWeightOnLeft=!this.poseWeightOnLeft),this.gesture)for(let[l,c]of Object.entries(this.gesture))this.poseTarget.props.hasOwnProperty(l)&&(this.poseTarget.props[l].copy(c),this.poseTarget.props[l].t=c.t,this.poseTarget.props[l].d=c.d);Object.keys(this.poseDelta.props).forEach(l=>{this.poseTarget.props.hasOwnProperty(l)||(this.poseTarget.props[l]=this.poseBase.props[l].clone(),this.poseTarget.props[l].t=this.animClock,this.poseTarget.props[l].d=o)})}getValue(t){return this.mtAvatar[t]?.value}setValue(t,e,n=null){this.mtAvatar.hasOwnProperty(t)&&Object.assign(this.mtAvatar[t],{system:e,systemd:n,needsUpdate:!0})}getMoodNames(){return Object.keys(this.animMoods)}getMood(){return this.opt.avatarMood}setMood(t){if(t=(t||"").trim().toLowerCase(),!this.animMoods.hasOwnProperty(t))throw new Error("Unknown mood.");this.moodName=t,this.mood=this.animMoods[this.moodName];for(let e of Object.keys(this.mtAvatar)){let n=this.mtBaselineExceptions.hasOwnProperty(e)?this.mtBaselineExceptions[e]:this.mtBaselineDefault;this.mood.baseline.hasOwnProperty(e)?n=this.mood.baseline[e]:this.avatar.baseline?.hasOwnProperty(e)&&(n=this.avatar.baseline[e]),this.setBaselineValue(e,n)}this.mood.anims.forEach(e=>{let n=this.animQueue.findIndex(i=>i.template.name===e.name);n!==-1&&this.animQueue.splice(n,1),this.animQueue.push(this.animFactory(e,-1))})}async initializeFBXAnimationLoader(){try{const{FBXAnimationLoader:t}=await Promise.resolve().then(()=>require("./fbxAnimationLoader-CNrfhJRz.cjs"));this.fbxAnimationLoader=new t(this.armature),console.log("FBX Animation Loader initialized")}catch(t){console.warn("FBX Animation Loader not available:",t),this.fbxAnimationLoader=null}}setBodyMovement(t){this.bodyMovement=t,this.avatar&&(this.avatar.bodyMovement=t),console.log("Body movement set to:",t),t==="idle"&&this.unlockAvatarPosition(),this.applyBodyMovementAnimation()}async applyBodyMovementAnimation(){if(!this.armature||!this.animQueue){console.log("Avatar not ready for body movement animations");return}console.log("Avatar is running:",this.isRunning),console.log("Animation queue exists:",!!this.animQueue);const t=this.animQueue.length;this.animQueue=this.animQueue.filter(i=>!i.template.name.startsWith("bodyMovement"));const e=this.animQueue.length;if(console.log(`Filtered animation queue: ${t} -> ${e} animations`),this.bodyMovement==="idle"){this.fbxAnimationLoader&&this.fbxAnimationLoader.stopCurrentAnimation();return}if(this.fbxAnimationLoader)try{await this.fbxAnimationLoader.playGestureAnimation(this.bodyMovement,this.movementIntensity),console.log("Applied FBX body movement animation:",this.bodyMovement);return}catch(i){console.warn("FBX animation failed, falling back to code animation:",i)}const n=this.createBodyMovementAnimation(this.bodyMovement);if(console.log("Created movement animation:",n),n)try{const i=this.animFactory(n,!0);i&&i.ts&&i.ts.length>0?(this.animQueue.push(i),console.log("Applied code-based body movement animation:",this.bodyMovement),console.log("Animation queue length:",this.animQueue.length),console.log("Animation object:",i)):(console.error("Invalid animation object created for:",this.bodyMovement),console.error("Animation object:",i))}catch(i){console.error("Error creating body movement animation:",i)}}lockAvatarPosition(){if(!this.armature){console.warn("Cannot lock position: armature not available");return}this.originalPosition||(this.originalPosition={x:this.armature.position.x,y:this.armature.position.y,z:this.armature.position.z},console.log("Original position stored:",this.originalPosition)),this.lockedPosition={x:this.armature.position.x,y:this.armature.position.y,z:this.armature.position.z},console.log("Avatar position locked at current position:",this.lockedPosition)}unlockAvatarPosition(){this.armature&&this.originalPosition?(this.armature.position.set(this.originalPosition.x,this.originalPosition.y,this.originalPosition.z),console.log("Avatar position restored to original:",this.originalPosition)):this.armature&&(this.armature.position.set(0,0,0),console.log("Avatar position reset to center (0,0,0)")),this.lockedPosition=null,this.originalPosition=null,console.log("Avatar position unlocked")}maintainLockedPosition(){this.lockedPosition&&this.armature&&this.armature.position.set(this.lockedPosition.x,this.lockedPosition.y,this.lockedPosition.z)}createBodyMovementAnimation(t){const e=this.movementIntensity||.5,n={walking:{name:"bodyMovement_walking",delay:[500,2e3],dt:[800,1200],vs:{bodyRotateY:[-.1*e,.1*e,0],bodyRotateZ:[-.05*e,.05*e,0],bodyRotateX:[-.02*e,.02*e,0]}},prancing:{name:"bodyMovement_prancing",delay:[300,1e3],dt:[400,800],vs:{bodyRotateY:[-.15*e,.15*e,0],bodyRotateZ:[-.08*e,.08*e,0],bodyRotateX:[-.05*e,.05*e,0]}},gesturing:{name:"bodyMovement_gesturing",delay:[400,1500],dt:[600,1e3],vs:{bodyRotateY:[-.08*e,.08*e,0],bodyRotateZ:[-.03*e,.03*e,0]}},dancing:{name:"bodyMovement_dancing",delay:[200,600],dt:[400,800],vs:{bodyRotateY:[-.25*e,.25*e,0],bodyRotateZ:[-.15*e,.15*e,0],bodyRotateX:[-.1*e,.1*e,0]}},dancing2:{name:"bodyMovement_dancing2",delay:[150,500],dt:[300,700],vs:{bodyRotateY:[-.3*e,.3*e,0],bodyRotateZ:[-.2*e,.2*e,0],bodyRotateX:[-.12*e,.12*e,0]}},dancing3:{name:"bodyMovement_dancing3",delay:[100,400],dt:[200,600],vs:{bodyRotateY:[-.35*e,.35*e,0],bodyRotateZ:[-.25*e,.25*e,0],bodyRotateX:[-.15*e,.15*e,0]}},excited:{name:"bodyMovement_excited",delay:[200,600],dt:[300,700],vs:{bodyRotateY:[-.12*e,.12*e,0],bodyRotateZ:[-.06*e,.06*e,0],bodyRotateX:[-.04*e,.04*e,0]}},happy:{name:"bodyMovement_happy",delay:[300,800],dt:[500,1e3],vs:{bodyRotateY:[-.08*e,.08*e,0],bodyRotateZ:[-.04*e,.04*e,0],bodyRotateX:[-.02*e,.02*e,0]}},surprised:{name:"bodyMovement_surprised",delay:[100,300],dt:[200,500],vs:{bodyRotateY:[-.05*e,.05*e,0],bodyRotateZ:[-.03*e,.03*e,0],bodyRotateX:[-.01*e,.01*e,0]}},thinking:{name:"bodyMovement_thinking",delay:[800,2e3],dt:[1e3,1500],vs:{bodyRotateY:[-.06*e,.06*e,0],bodyRotateZ:[-.03*e,.03*e,0],bodyRotateX:[-.02*e,.02*e,0]}},nodding:{name:"bodyMovement_nodding",delay:[400,800],dt:[300,600],vs:{bodyRotateX:[-.1*e,.1*e,0],bodyRotateY:[-.02*e,.02*e,0]}},shaking:{name:"bodyMovement_shaking",delay:[200,400],dt:[150,300],vs:{bodyRotateY:[-.15*e,.15*e,0],bodyRotateZ:[-.05*e,.05*e,0]}},celebration:{name:"bodyMovement_celebration",delay:[100,300],dt:[200,500],vs:{bodyRotateY:[-.2*e,.2*e,0],bodyRotateZ:[-.1*e,.1*e,0],bodyRotateX:[-.08*e,.08*e,0]}},energetic:{name:"bodyMovement_energetic",delay:[150,400],dt:[250,500],vs:{bodyRotateY:[-.18*e,.18*e,0],bodyRotateZ:[-.12*e,.12*e,0],bodyRotateX:[-.08*e,.08*e,0]}},swaying:{name:"bodyMovement_swaying",delay:[600,1200],dt:[800,1e3],vs:{bodyRotateY:[-.1*e,.1*e,0],bodyRotateZ:[-.05*e,.05*e,0]}},bouncing:{name:"bodyMovement_bouncing",delay:[300,600],dt:[400,700],vs:{bodyRotateY:[-.05*e,.05*e,0]}}};if(t==="dancing"){const i=["dancing","dancing2","dancing3"],s=i[Math.floor(Math.random()*i.length)];return n[s]||n.dancing}return n[t]||null}playRandomDance(){const t=["dancing","dancing2","dancing3"],e=t[Math.floor(Math.random()*t.length)];this.setBodyMovement(e)}playReaction(t){["happy","surprised","thinking","nodding","shaking","celebration","energetic","swaying","bouncing"].includes(t)?(this.setBodyMovement(t),["surprised","nodding","shaking","celebration"].includes(t)&&setTimeout(()=>{this.setBodyMovement("idle")},3e3)):console.warn("Invalid reaction type:",t)}playCelebration(){this.playReaction("celebration"),setTimeout(()=>{this.playRandomDance()},2e3)}setMovementIntensity(t){this.movementIntensity=Math.max(0,Math.min(1,t)),this.avatar&&(this.avatar.movementIntensity=this.movementIntensity),console.log("Movement intensity set to:",this.movementIntensity),this.fbxAnimationLoader&&this.fbxAnimationLoader.setIntensity(this.movementIntensity),this.applyBodyMovementAnimation()}setShowFullAvatar(t){this.showFullAvatar=t,this.avatar&&(this.avatar.showFullAvatar=t),console.log("Show full avatar set to:",t),t&&this.viewName!=="full"?(console.log("Changing camera view to full"),this.setView("full")):!t&&this.viewName!=="upper"?(console.log("Changing camera view to upper"),this.setView("upper")):console.log("Camera view already set to:",this.viewName)}getMorphTargetNames(){return["eyesRotateX","eyesRotateY",...Object.keys(this.mtAvatar)].sort()}getBaselineValue(t){if(t==="eyesRotateY"){const e=this.getBaselineValue("eyeLookOutLeft");if(e===void 0)return;const n=this.getBaselineValue("eyeLookInLeft");return n===void 0||this.getBaselineValue("eyeLookOutRight")===void 0||this.getBaselineValue("eyeLookInRight")===void 0?void 0:e-n}else if(t==="eyesRotateX"){const e=this.getBaselineValue("eyesLookDown");if(e===void 0)return;const n=this.getBaselineValue("eyesLookUp");return n===void 0?void 0:e-n}else return this.mtAvatar[t]?.baseline}setBaselineValue(t,e){t==="eyesRotateY"?(this.setBaselineValue("eyeLookOutLeft",e===null?null:e>0?e:0),this.setBaselineValue("eyeLookInLeft",e===null?null:e>0?0:-e),this.setBaselineValue("eyeLookOutRight",e===null?null:e>0?0:-e),this.setBaselineValue("eyeLookInRight",e===null?null:e>0?e:0)):t==="eyesRotateX"?(this.setBaselineValue("eyesLookDown",e===null?null:e>0?e:0),this.setBaselineValue("eyesLookUp",e===null?null:e>0?0:-e)):this.mtAvatar.hasOwnProperty(t)&&Object.assign(this.mtAvatar[t],{base:null,baseline:e,needsUpdate:!0})}getFixedValue(t){if(t==="eyesRotateY"){const e=this.getFixedValue("eyeLookOutLeft");if(e===null)return null;const n=this.getFixedValue("eyeLookInLeft");return n===null||this.getFixedValue("eyeLookOutRight")===null||this.getFixedValue("eyeLookInRight")===null?null:e-n}else if(t==="eyesRotateX"){const e=this.getFixedValue("eyesLookDown");if(e===null)return null;const n=this.getFixedValue("eyesLookUp");return n===null?null:e-n}else return this.mtAvatar[t]?.fixed}setFixedValue(t,e,n=null){t==="eyesRotateY"?(this.setFixedValue("eyeLookOutLeft",e===null?null:e>0?e:0,n),this.setFixedValue("eyeLookInLeft",e===null?null:e>0?0:-e,n),this.setFixedValue("eyeLookOutRight",e===null?null:e>0?0:-e,n),this.setFixedValue("eyeLookInRight",e===null?null:e>0?e:0,n)):t==="eyesRotateX"?(this.setFixedValue("eyesLookDown",e===null?null:e>0?e:0,n),this.setFixedValue("eyesLookUp",e===null?null:e>0?0:-e,n)):this.mtAvatar.hasOwnProperty(t)&&Object.assign(this.mtAvatar[t],{fixed:e,needsUpdate:!0})}animFactory(t,e=!1,n=1,i=1,s=!1){const o={template:t,ts:[0],vs:{}};let l=t;for(;;)if(l.hasOwnProperty(this.stateName))(this.stateName==="speaking"||this.stateName==="idle")&&console.log("Selected state:",this.stateName,"for avatar body:",this.avatar?.body),l=l[this.stateName];else if(l.hasOwnProperty(this.moodName))l=l[this.moodName];else if(l.hasOwnProperty(this.poseName))l=l[this.poseName];else if(l.hasOwnProperty(this.viewName))l=l[this.viewName];else if(this.avatar&&this.avatar.body&&l.hasOwnProperty(this.avatar.body))console.log("Applying gender-specific override:",this.avatar.body,"for state:",this.stateName,"keys:",Object.keys(l)),l=l[this.avatar.body];else if(l.hasOwnProperty("alt")){let r=l.alt[0];if(l.alt.length>1){const u=Math.random();let a=0;for(let d=0;d<l.alt.length;d++){let h=this.valueFn(l.alt[d].p);if(a+=h===void 0?(1-a)/(l.alt.length-1-d):h,u<a){r=l.alt[d];break}}}l=r,this.avatar&&this.avatar.body&&l.hasOwnProperty(this.avatar.body)&&console.log("Found gender override in selected alternative:",this.avatar.body,"keys:",Object.keys(l));continue}else break;let c=this.valueFn(l.delay)||0;if(Array.isArray(c)&&(c=this.gaussianRandom(...c)),l.hasOwnProperty("dt"))l.dt.forEach((r,u)=>{let a=this.valueFn(r);Array.isArray(a)&&(a=this.gaussianRandom(...a)),o.ts[u+1]=o.ts[u]+a});else{let r=Object.values(l.vs).reduce((u,a)=>a.length>u?a.length:u,0);o.ts=Array(r+1).fill(0)}s?o.ts=o.ts.map(r=>c+r*n):o.ts=o.ts.map(r=>this.animClock+c+r*n),l.vs&&l.vs.pose&&console.log("Pose being selected from vs.pose:",l.vs.pose,"for avatar body:",this.avatar?.body);for(let[r,u]of Object.entries(l.vs)){const a=this.getBaselineValue(r),d=u.map(h=>(h=this.valueFn(h),h===null?null:typeof h=="function"?h:typeof h=="string"||h instanceof String?r==="pose"&&this.avatar&&this.avatar.body==="M"&&(h==="hip"||h==="side")?(console.log("Intercepting pose",h,"in animation factory, overriding to wide for male avatar"),"wide"):h.slice():Array.isArray(h)?r==="gesture"?h.slice():(a===void 0?0:a)+i*this.gaussianRandom(...h):typeof h=="boolean"?h:h instanceof Object&&h.constructor===Object?Object.assign({},h):(a===void 0?0:a)+i*h));r==="eyesRotateY"?(o.vs.eyeLookOutLeft=[null,...d.map(h=>h>0?h:0)],o.vs.eyeLookInLeft=[null,...d.map(h=>h>0?0:-h)],o.vs.eyeLookOutRight=[null,...d.map(h=>h>0?0:-h)],o.vs.eyeLookInRight=[null,...d.map(h=>h>0?h:0)]):r==="eyesRotateX"?(o.vs.eyesLookDown=[null,...d.map(h=>h>0?h:0)],o.vs.eyesLookUp=[null,...d.map(h=>h>0?0:-h)]):o.vs[r]=[null,...d]}for(let r of Object.keys(o.vs))for(;o.vs[r].length<=o.ts.length;)o.vs[r].push(o.vs[r][o.vs[r].length-1]);return t.hasOwnProperty("mood")&&(o.mood=this.valueFn(t.mood).slice()),e&&(o.loop=e),o}valueAnimationSeq(t,e,n,i,s,o=null){t=this.valueFn(t),e=this.valueFn(e),s<n&&(s=n),s>i&&(s=i);let l=(e-t)/(i-n);return o&&(l*=o((s-n)/(i-n))),l*s+(t-l*n)}gaussianRandom(t,e,n=1,i=5){let s=0;for(let o=0;o<i;o++)s+=Math.random();return t+Math.pow(s/i,n)*(e-t)}sigmoidFactory(t){function e(i){return 1/(1+Math.exp(-t*i))-.5}var n=.5/e(1);return function(i){return n*e(2*Math.max(Math.min(i,1),0)-1)+.5}}convertRange(t,e,n){return(t-e[0])*(n[1]-n[0])/(e[1]-e[0])+n[0]}animate(t){if(!this.isRunning)return;let e;if(this.isAvatarOnly)e=t;else{if(requestAnimationFrame(this.animate.bind(this)),e=t-this.animTimeLast,e<this.animFrameDur)return;this.animTimeLast=t}e=e/this.animSlowdownRate,this.animClock+=e,this.maintainLockedPosition();let n,i,s,o,l=0;if(this.stats&&this.stats.begin(),this.isListening){for(this.listeningAnalyzer.getByteFrequencyData(this.volumeFrequencyData),n=2,s=10;n<s;n++)this.volumeFrequencyData[n]>l&&(l=this.volumeFrequencyData[n]);this.listeningVolume=(this.listeningVolume+l)/2,this.listeningActive?(this.listeningTimerTotal+=e,this.listeningVolume<this.listeningSilenceThresholdLevel?(this.listeningTimer+=e,this.listeningTimer>this.listeningSilenceThresholdMs&&(this.listeningOnchange&&this.listeningOnchange("stop",this.listeningTimer),this.listeningActive=!1,this.listeningTimer=0,this.listeningTimerTotal=0)):this.listeningTimer*=.5,this.listeningTimerTotal>this.listeningActiveDurationMax&&(this.listeningOnchange&&this.listeningOnchange("maxactive"),this.listeningTimerTotal=0)):(this.listeningTimerTotal+=e,this.listeningVolume>this.listeningActiveThresholdLevel?(this.listeningTimer+=e,this.listeningTimer>this.listeningActiveThresholdMs&&(this.listeningOnchange&&this.listeningOnchange("start"),this.listeningActive=!0,this.listeningTimer=0,this.listeningTimerTotal=0)):this.listeningTimer*=.5,this.listeningTimerTotal>this.listeningSilenceDurationMax&&(this.listeningOnchange&&this.listeningOnchange("maxsilence"),this.listeningTimerTotal=0))}if(this.isSpeaking)for(l=0,this.audioAnalyzerNode.getByteFrequencyData(this.volumeFrequencyData),n=2,s=10;n<s;n++)this.volumeFrequencyData[n]>l&&(l=this.volumeFrequencyData[n]);let c=null,r=null;const u=[];for(n=0,s=this.animQueue.length;n<s;n++){const a=this.animQueue[n];if(!(!a||!a.ts||!a.ts.length||this.animClock<a.ts[0])){for(i=a.ndx||0,o=a.ts.length;i<o&&!(this.animClock<a.ts[i]);i++)for(let[d,h]of Object.entries(a.vs))if(this.mtAvatar.hasOwnProperty(d)){if(h[i+1]===null)continue;const g=this.mtAvatar[d];if(h[i]===null&&(h[i]=g.value),i===o-1)g.newvalue=h[i];else{g.newvalue=h[i+1];const x=a.ts[i+1]-a.ts[i];let f=1;x>1e-4&&(f=(this.animClock-a.ts[i])/x),f<1&&(g.easing&&(f=g.easing(f)),g.newvalue=(1-f)*h[i]+f*g.newvalue),g.ref&&g.ref!==a.vs&&g.ref.hasOwnProperty(d)&&delete g.ref[d],g.ref=a.vs}if(l)switch(d){case"viseme_aa":case"viseme_E":case"viseme_I":case"viseme_O":case"viseme_U":g.newvalue*=1+l/255-.5}g.needsUpdate=!0}else d==="eyeContact"&&h[i]!==null&&c!==!1?c=!!h[i]:d==="headMove"&&h[i]!==null&&r!==!1?h[i]===0?r=!1:(Math.random()<h[i]&&(r=!0),h[i]=null):h[i]!==null&&(u.push({mt:d,val:h[i]}),h[i]=null);i===o?(a.hasOwnProperty("mood")&&this.setMood(a.mood),a.loop?(o=this.isSpeaking&&(a.template.name==="head"||a.template.name==="eyes")?4:1,this.animQueue[n]=this.animFactory(a.template,a.loop>0?a.loop-1:a.loop,1,1/o)):(this.animQueue.splice(n--,1),s--)):a.ndx=i-1}}for(let a=0,d=u.length;a<d;a++)switch(i=u[a].val,u[a].mt){case"speak":this.speakText(i);break;case"subtitles":this.onSubtitles&&typeof this.onSubtitles=="function"&&this.onSubtitles(i);break;case"pose":this.avatar&&this.avatar.body==="M"&&(i==="hip"||i==="side")&&this.poseTemplates.wide&&(i="wide",console.log("Overriding pose",i==="hip"?"hip":"side","to wide for male avatar")),this.poseName=i,console.log("Setting pose to:",this.poseName,"for avatar body:",this.avatar?.body,"state:",this.stateName),this.setPoseFromTemplate(this.poseTemplates[this.poseName]);break;case"gesture":this.playGesture(...i);break;case"function":i&&typeof i=="function"&&i();break;case"moveto":Object.entries(i.props).forEach(h=>{h[1]?this.poseTarget.props[h[0]].copy(h[1]):this.poseTarget.props[h[0]].copy(this.getPoseTemplateProp(h[0])),this.poseTarget.props[h[0]].t=this.animClock,this.poseTarget.props[h[0]].d=h[1]&&h[1].d?h[1].d:h.duration||2e3});break;case"handLeft":this.ikSolve({iterations:20,root:"LeftShoulder",effector:"LeftHandMiddle1",links:[{link:"LeftHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5},{link:"LeftForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-.5,maxz:3},{link:"LeftArm",minx:-1.5,maxx:1.5,miny:0,maxy:0,minz:-1,maxz:3}]},i.x?new y.Vector3(i.x,i.y,i.z):null,!0,i.d);break;case"handRight":this.ikSolve({iterations:20,root:"RightShoulder",effector:"RightHandMiddle1",links:[{link:"RightHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5,maxAngle:.1},{link:"RightForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-3,maxz:.5,maxAngle:.2},{link:"RightArm",minx:-1.5,maxx:1.5,miny:0,maxy:0,minz:-1,maxz:3}]},i.x?new y.Vector3(i.x,i.y,i.z):null,!0,i.d);break}if((c||r)&&(V.setFromQuaternion(this.poseAvatar.props["Head.quaternion"]),V.x=Math.max(-.9,Math.min(.9,2*V.x-.5)),V.y=Math.max(-.9,Math.min(.9,-2.5*V.y)),c?(Object.assign(this.mtAvatar.eyesLookDown,{system:V.x<0?-V.x:0,needsUpdate:!0}),Object.assign(this.mtAvatar.eyesLookUp,{system:V.x<0?0:V.x,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookInLeft,{system:V.y<0?-V.y:0,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookOutLeft,{system:V.y<0?0:V.y,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookInRight,{system:V.y<0?0:V.y,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookOutRight,{system:V.y<0?-V.y:0,needsUpdate:!0}),r&&(n=-this.mtAvatar.bodyRotateY.value,i=this.gaussianRandom(-.2,.2),this.animQueue.push(this.animFactory({name:"headmove",dt:[[1e3,2e3],[1e3,2e3,1,2],[1e3,2e3],[1e3,2e3,1,2]],vs:{headRotateY:[n,n,0],headRotateX:[i,i,0],headRotateZ:[-n/4,-n/4,0]}})))):(n=this.mtAvatar.eyeLookInLeft.value-this.mtAvatar.eyeLookOutLeft.value,i=this.gaussianRandom(-.2,.2),this.animQueue.push(this.animFactory({name:"headmove",dt:[[1e3,2e3],[1e3,2e3,1,2],[1e3,2e3],[1e3,2e3,1,2]],vs:{headRotateY:[null,n,n,0],headRotateX:[null,i,i,0],headRotateZ:[null,-n/4,-n/4,0],eyeLookInLeft:[null,0],eyeLookOutLeft:[null,0],eyeLookInRight:[null,0],eyeLookOutRight:[null,0],eyeContact:[0]}})))),e>2*this.animFrameDur&&(e=2*this.animFrameDur),(this.viewName!=="full"||this.isAvatarOnly)&&(n=this.mtRandomized[Math.floor(Math.random()*this.mtRandomized.length)],i=this.mtAvatar[n],i.needsUpdate||Object.assign(i,{base:(this.mood.baseline[n]||0)+(1+l/255)*Math.random()/5,needsUpdate:!0})),this.updatePoseBase(this.animClock),this.mixer&&this.mixer.update(e/1e3*this.mixer.timeScale),this.updatePoseDelta(),(this.isSpeaking||this.isListening)&&c?l>this.volumeMax?(this.volumeHeadBase=.05,Math.random()>.6&&(this.volumeHeadTarget=-.05-Math.random()/15),this.volumeMax=l):(this.volumeMax*=.92,this.volumeHeadTarget=this.volumeHeadBase-.9*(this.volumeHeadBase-this.volumeHeadTarget)):(this.volumeHeadTarget=0,this.volumeMax=0),n=this.volumeHeadTarget-this.volumeHeadCurrent,i=Math.abs(n),i>1e-4&&(o=i*(this.volumeHeadEasing(Math.min(1,this.volumeHeadVelocity*e/1e3/i)/2+.5)-.5),this.volumeHeadCurrent+=Math.sign(n)*Math.min(i,o)),Math.abs(this.volumeHeadCurrent)>1e-4&&(K.setFromAxisAngle(dt,this.volumeHeadCurrent),this.objectNeck.quaternion.multiply(K)),Ne.setFromObject(this.armature),this.objectLeftToeBase.getWorldPosition(fe),fe.sub(this.armature.position),this.objectRightToeBase.getWorldPosition(xe),xe.sub(this.armature.position),this.objectHips.position.y-=Ne.min.y/2,this.objectHips.position.x-=(fe.x+xe.x)/4,this.objectHips.position.z-=(fe.z+xe.z)/2,this.dynamicbones.update(e),this.fbxAnimationLoader&&this.fbxAnimationLoader.update(),this.opt.update&&this.opt.update(e),this.updateMorphTargets(e),this.isAvatarOnly)this.stats&&this.stats.end();else{if(this.cameraClock!==null&&this.cameraClock<1e3){this.cameraClock+=e,this.cameraClock>1e3&&(this.cameraClock=1e3);let a=new y.Spherical().setFromVector3(this.cameraStart),d=new y.Spherical().setFromVector3(this.cameraEnd);a.phi+=this.easing(this.cameraClock/1e3)*(d.phi-a.phi),a.theta+=this.easing(this.cameraClock/1e3)*(d.theta-a.theta),a.radius+=this.easing(this.cameraClock/1e3)*(d.radius-a.radius),a.makeSafe(),this.camera.position.setFromSpherical(a),this.controlsStart.x!==this.controlsEnd.x?this.controls.target.copy(this.controlsStart.lerp(this.controlsEnd,this.easing(this.cameraClock/1e3))):(a.setFromVector3(this.controlsStart),d.setFromVector3(this.controlsEnd),a.phi+=this.easing(this.cameraClock/1e3)*(d.phi-a.phi),a.theta+=this.easing(this.cameraClock/1e3)*(d.theta-a.theta),a.radius+=this.easing(this.cameraClock/1e3)*(d.radius-a.radius),a.makeSafe(),this.controls.target.setFromSpherical(a)),this.controls.update()}this.controls.autoRotate&&this.controls.update(),this.stats&&this.stats.end(),this.render()}}resetLips(){this.visemeNames.forEach(t=>{this.morphs.forEach(e=>{const n=e.morphTargetDictionary["viseme_"+t];n!==void 0&&(e.morphTargetInfluences[n]=0)})})}lipsyncGetProcessor(t,e="./"){if(!this.lipsync.hasOwnProperty(t)){const n=t.toLowerCase(),i="Lipsync"+t.charAt(0).toUpperCase()+t.slice(1);try{const s=Oe[n];s&&s[i]?(this.lipsync[t]=new s[i],console.log(`Loaded lip-sync module for ${t}`)):console.warn(`Lip-sync module for ${t} not found. Available modules:`,Object.keys(Oe))}catch(s){console.warn(`Failed to load lip-sync module for ${t}:`,s)}}}lipsyncPreProcessText(t,e){return(this.lipsync[e]||Object.values(this.lipsync)[0]).preProcessText(t)}lipsyncWordsToVisemes(t,e){return(this.lipsync[e]||Object.values(this.lipsync)[0]).wordsToVisemes(t)}speakText(t,e=null,n=null,i=null){e=e||{};const s=/[!\.\?\n\p{Extended_Pictographic}]/ug,o=/[ ]/ug,l=/[\p{L}\p{N},\.\p{Quotation_Mark}!€\$\+\p{Dash_Punctuation}%&\?]/ug,c=/[\p{Extended_Pictographic}]/ug,r=e.lipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang;let u="",a="",d=0,h=[],g=[];const x=Array.from(this.segmenter.segment(t),f=>f.segment);for(let f=0;f<x.length;f++){const w=f===x.length-1,D=x[f].match(l);let p=x[f].match(s);const O=x[f].match(c),T=x[f].match(o);if(p&&!w&&!O&&x[f+1].match(s)&&(p=!1),n&&(u+=x[f]),D&&(!i||i.every(R=>f<R[0]||f>R[1]))&&(a+=x[f]),(T||p||w)&&(a.length&&(a=this.lipsyncPreProcessText(a,r),a.length&&h.push({mark:d,word:a})),u.length&&(g.push({mark:d,template:{name:"subtitles"},ts:[0],vs:{subtitles:[u]}}),u=""),a.length)){const R=this.lipsyncWordsToVisemes(a,r);if(R&&R.visemes&&R.visemes.length){const k=R.times[R.visemes.length-1]+R.durations[R.visemes.length-1];for(let A=0;A<R.visemes.length;A++)g.push({mark:d,template:{name:"viseme"},ts:[(R.times[A]-.6)/k,(R.times[A]+.5)/k,(R.times[A]+R.durations[A]+.5)/k],vs:{["viseme_"+R.visemes[A]]:[null,R.visemes[A]==="PP"||R.visemes[A]==="FF"?.9:.6,0]}})}a="",d++}if(p||w){if(h.length||w&&g.length){const R={anim:g};n&&(R.onSubtitles=n),h.length&&!e.avatarMute&&(R.text=h,e.avatarMood&&(R.mood=e.avatarMood),e.ttsLang&&(R.lang=e.ttsLang),e.ttsVoice&&(R.voice=e.ttsVoice),e.ttsRate&&(R.rate=e.ttsRate),e.ttsVoice&&(R.pitch=e.ttsPitch),e.ttsVolume&&(R.volume=e.ttsVolume)),this.speechQueue.push(R),h=[],a="",d=0,g=[]}if(O){let R=this.animEmojis[x[f]];R&&R.link&&(R=this.animEmojis[R.link]),R&&this.speechQueue.push({emoji:R})}this.speechQueue.push({break:100})}}this.speechQueue.push({break:1e3}),this.startSpeaking()}async speakEmoji(t){let e=this.animEmojis[t];e&&e.link&&(e=this.animEmojis[e.link]),e&&this.speechQueue.push({emoji:e}),this.startSpeaking()}async speakBreak(t){this.speechQueue.push({break:t}),this.startSpeaking()}async speakMarker(t){this.speechQueue.push({marker:t}),this.startSpeaking()}async playBackgroundAudio(t){let n=await(await fetch(t)).arrayBuffer();this.stopBackgroundAudio(),this.audioBackgroundSource=this.audioCtx.createBufferSource(),this.audioBackgroundSource.loop=!0,this.audioBackgroundSource.buffer=await this.audioCtx.decodeAudioData(n),this.audioBackgroundSource.playbackRate.value=1/this.animSlowdownRate,this.audioBackgroundSource.connect(this.audioBackgroundGainNode),this.audioBackgroundSource.start(0)}stopBackgroundAudio(){try{this.audioBackgroundSource.stop()}catch{}this.audioBackgroundSource.disconnect()}async setReverb(t=null){if(t){let n=await(await fetch(t)).arrayBuffer();this.audioReverbNode.buffer=await this.audioCtx.decodeAudioData(n)}else{const e=this.audioCtx.sampleRate,n=this.audioCtx.createBuffer(2,e,e);n.getChannelData(0)[0]=1,n.getChannelData(1)[0]=1,this.audioReverbNode.buffer=n}}setMixerGain(t,e=null,n=0){t!==null&&(this.audioSpeechGainNode.gain.cancelScheduledValues(this.audioCtx.currentTime),n?(this.audioSpeechGainNode.gain.setValueAtTime(Math.max(this.audioSpeechGainNode.gain.value,1e-4),this.audioCtx.currentTime),this.audioSpeechGainNode.gain.exponentialRampToValueAtTime(Math.max(t,1e-4),this.audioCtx.currentTime+n)):this.audioSpeechGainNode.gain.setValueAtTime(t,this.audioCtx.currentTime)),e!==null&&(this.audioBackgroundGainNode.gain.cancelScheduledValues(this.audioCtx.currentTime),n?(this.audioBackgroundGainNode.gain.setValueAtTime(Math.max(this.audioBackgroundGainNode.gain.value,1e-4),this.audioCtx.currentTime),this.audioBackgroundGainNode.gain.exponentialRampToValueAtTime(Math.max(e,1e-4),this.audioCtx.currentTime+n)):this.audioBackgroundGainNode.gain.setValueAtTime(e,this.audioCtx.currentTime))}speakAudio(t,e=null,n=null){e=e||{};const i=e.lipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang,s={};if(t.words){let o=[];for(let l=0;l<t.words.length;l++){const c=t.words[l],r=t.wtimes[l];let u=t.wdurations[l];if(c.length&&(n&&o.push({template:{name:"subtitles"},ts:[r],vs:{subtitles:[" "+c]}}),!t.visemes)){const a=this.lipsyncPreProcessText(c,i),d=this.lipsyncWordsToVisemes(a,i);if(d&&d.visemes&&d.visemes.length){const h=d.times[d.visemes.length-1]+d.durations[d.visemes.length-1],g=Math.min(u,Math.max(0,u-d.visemes.length*150));let x=.6+this.convertRange(g,[0,u],[0,.4]);if(u=Math.min(u,d.visemes.length*200),h>0)for(let f=0;f<d.visemes.length;f++){const w=r+d.times[f]/h*u,D=d.durations[f]/h*u;o.push({template:{name:"viseme"},ts:[w-Math.min(60,2*D/3),w+Math.min(25,D/2),w+D+Math.min(60,D/2)],vs:{["viseme_"+d.visemes[f]]:[null,d.visemes[f]==="PP"||d.visemes[f]==="FF"?.9:x,0]}})}}}}if(t.visemes)for(let l=0;l<t.visemes.length;l++){const c=t.visemes[l],r=t.vtimes[l],u=t.vdurations[l];o.push({template:{name:"viseme"},ts:[r-2*u/3,r+u/2,r+u+u/2],vs:{["viseme_"+c]:[null,c==="PP"||c==="FF"?.9:.6,0]}})}if(t.markers)for(let l=0;l<t.markers.length;l++){const c=t.markers[l],r=t.mtimes[l];o.push({template:{name:"markers"},ts:[r],vs:{function:[c]}})}o.length&&(s.anim=o)}if(t.audio&&(s.audio=t.audio),t.anim?.name){let o=this.animFactory(t.anim,!1,1,1,!0);s.anim?s.anim.push(o):s.anim=[o]}n&&(s.onSubtitles=n),e.isRaw&&(s.isRaw=!0),Object.keys(s).length&&(this.speechQueue.push(s),s.isRaw||this.speechQueue.push({break:300}),this.startSpeaking())}async playAudio(t=!1){if(!(!this.armature||this.isAudioPlaying&&!t))if(this.isAudioPlaying=!0,this.audioPlaylist.length){const e=this.audioPlaylist.shift();if(this.audioCtx.state==="suspended"||this.audioCtx.state==="interrupted"){const s=this.audioCtx.resume(),o=new Promise((l,c)=>setTimeout(()=>c("p2"),1e3));try{await Promise.race([s,o])}catch{console.log("Can't play audio. Web Audio API suspended. This is often due to calling some speak method before the first user action, which is typically prevented by the browser."),this.playAudio(!0);return}}let n;if(Array.isArray(e.audio)){let s=this.concatArrayBuffers(e.audio);n=this.pcmToAudioBuffer(s)}else n=e.audio;this.audioSpeechSource=this.audioCtx.createBufferSource(),this.audioSpeechSource.buffer=n,this.audioSpeechSource.playbackRate.value=1/this.animSlowdownRate,this.audioSpeechSource.connect(this.audioAnalyzerNode),this.audioSpeechSource.addEventListener("ended",()=>{this.audioSpeechSource.disconnect(),this.playAudio(!0)},{once:!0});let i=0;e.anim&&(e.isRaw||(i=Math.abs(Math.min(0,...e.anim.map(s=>Math.min(...s.ts))))),e.anim.forEach(s=>{for(let o=0;o<s.ts.length;o++)s.ts[o]=this.animClock+s.ts[o]+i;this.animQueue.push(s)})),this.audioSpeechSource.start(i/1e3)}else this.isAudioPlaying=!1,this.startSpeaking(!0)}async synthesizeWithBrowserTTS(t){return new Promise((e,n)=>{const i=t.text.map(p=>p.word).join(" "),s=new SpeechSynthesisUtterance(i),o=t.lang||this.avatar.ttsLang||this.opt.ttsLang||"en-US",l=(t.rate||this.avatar.ttsRate||this.opt.ttsRate||1)+this.mood.speech.deltaRate,c=(t.pitch||this.avatar.ttsPitch||this.opt.ttsPitch||1)+this.mood.speech.deltaPitch,r=(t.volume||this.avatar.ttsVolume||this.opt.ttsVolume||1)+this.mood.speech.deltaVolume;s.lang=o,s.rate=Math.max(.1,Math.min(10,l)),s.pitch=Math.max(0,Math.min(2,c)),s.volume=Math.max(0,Math.min(1,r));const u=speechSynthesis.getVoices(),a=t.voice||this.avatar.ttsVoice||this.opt.ttsVoice;if(a&&u.length>0){const p=u.find(O=>O.name.includes(a)||O.lang===o);p&&(s.voice=p)}const d=i.length*100/s.rate,h=this.audioCtx.createBuffer(1,this.audioCtx.sampleRate*(d/1e3),this.audioCtx.sampleRate),g=this.avatar.lipsyncLang||this.opt.lipsyncLang||"en",x=this.lipsyncPreProcessText(i,g),f=this.lipsyncWordsToVisemes(x,g);console.log("Browser TTS Lip-sync Debug:",{text:i,lipsyncLang:g,processedText:x,lipsyncData:f,hasVisemes:f&&f.visemes&&f.visemes.length>0,estimatedDuration:d});const w=[];if(f&&f.visemes&&f.visemes.length>0){const p=f.times[f.visemes.length-1]+f.durations[f.visemes.length-1];for(let O=0;O<f.visemes.length;O++){const T=f.visemes[O],R=f.times[O]/p,k=f.durations[O]/p,A=R*d,z=k*d;w.push({template:{name:"viseme"},ts:[A-Math.min(60,2*z/3),A+Math.min(25,z/2),A+z+Math.min(60,z/2)],vs:{["viseme_"+T]:[null,T==="PP"||T==="FF"?.9:.6,0]}})}}const D=[...t.anim,...w];this.audioPlaylist.push({anim:D,audio:h}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio(),s.onend=()=>{e()},s.onerror=p=>{console.error("Speech synthesis error:",p.error),n(p.error)},speechSynthesis.speak(s)})}async synthesizeWithElevenLabsTTS(t){const e=t.text.map(d=>d.word).join(" "),n=t.voice||this.avatar.ttsVoice||this.opt.ttsVoice||"21m00Tcm4TlvDq8ikWAM",i={text:e,model_id:"eleven_monolingual_v1",voice_settings:{stability:.5,similarity_boost:.5,style:0,use_speaker_boost:!0}},s=await fetch(`${this.opt.ttsEndpoint}/${n}`,{method:"POST",headers:{Accept:"audio/mpeg","Content-Type":"application/json","xi-api-key":this.opt.ttsApikey},body:JSON.stringify(i)});if(!s.ok)throw new Error(`ElevenLabs TTS error: ${s.status} ${s.statusText}`);const o=await s.arrayBuffer(),l=await this.audioCtx.decodeAudioData(o);console.log("Using text-based lip-sync for debugging...");const c=this.avatar.lipsyncLang||this.opt.lipsyncLang||"en";let r;try{console.log("Lip-sync modules available:",{hasLipsync:!!this.lipsync,lipsyncKeys:this.lipsync?Object.keys(this.lipsync):[],lipsyncLang:c});const d=this.lipsyncPreProcessText(e,c),h=this.lipsyncWordsToVisemes(d,c);if(console.log("Lip-sync data:",{processedText:d,lipsyncData:h,hasVisemes:h&&h.visemes&&h.visemes.length>0}),h&&h.visemes&&h.visemes.length>0)r={visemes:h.visemes.map((g,x)=>({viseme:g,startTime:x*l.duration/h.visemes.length,endTime:(x+1)*l.duration/h.visemes.length,duration:l.duration/h.visemes.length,intensity:.7})),words:[],duration:l.duration,features:{onsets:[],boundaries:[]}};else throw new Error("No visemes generated from text")}catch(d){console.error("Text-based lip-sync failed, using fallback:",d);const h=e.toLowerCase().split(/\s+/),g=[];for(const x of h)for(const f of x){let w="aa";"aeiou".includes(f)?w="aa":"bp".includes(f)?w="PP":"fv".includes(f)?w="FF":"st".includes(f)?w="SS":"dln".includes(f)?w="DD":"kg".includes(f)?w="kk":"rw".includes(f)&&(w="RR"),g.push(w)}r={visemes:g.map((x,f)=>({viseme:x,startTime:f*l.duration/g.length,endTime:(f+1)*l.duration/g.length,duration:l.duration/g.length,intensity:.6})),words:[],duration:l.duration,features:{onsets:[],boundaries:[]}}}console.log("ElevenLabs TTS Audio Analysis:",{text:e,audioDuration:l.duration,visemeCount:r.visemes?r.visemes.length:0,wordCount:r.words?r.words.length:0,features:{onsets:r.features&&r.features.onsets?r.features.onsets.length:0,boundaries:r.features&&r.features.phonemeBoundaries?r.features.phonemeBoundaries.length:0},visemes:r.visemes?r.visemes.slice(0,3):[]});const u=[];if(r.visemes&&r.visemes.length>0){console.log("ElevenLabs: Generating lip-sync animation from",r.visemes.length,"visemes");for(let d=0;d<r.visemes.length;d++){const h=r.visemes[d],g=h.startTime*1e3,x=h.duration*1e3,f=h.intensity;u.push({template:{name:"viseme"},ts:[g-Math.min(60,2*x/3),g+Math.min(25,x/2),g+x+Math.min(60,x/2)],vs:{["viseme_"+h.viseme]:[null,f,0]}})}console.log("ElevenLabs: Generated",u.length,"lip-sync animation frames")}else console.warn("ElevenLabs: No visemes available for lip-sync animation");const a=[...t.anim,...u];console.log("ElevenLabs: Combined animation frames:",a.length,"(original:",t.anim.length,"+ lipsync:",u.length,")"),this.audioPlaylist.push({anim:a,audio:l}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio()}async synthesizeWithDeepgramTTS(t){const e=t.text.map(d=>d.word).join(" "),n=t.voice||this.avatar.ttsVoice||this.opt.ttsVoice||"aura-2-thalia-en",i=`${this.opt.ttsEndpoint}?model=${n}`,s=await fetch(i,{method:"POST",headers:{Authorization:`Token ${this.opt.ttsApikey}`,"Content-Type":"text/plain",Accept:"audio/mpeg"},body:e});if(!s.ok)throw new Error(`Deepgram TTS error: ${s.status} ${s.statusText}`);const o=await s.arrayBuffer(),l=await this.audioCtx.decodeAudioData(o);console.log("Using text-based lip-sync for Deepgram...");const c=this.avatar.lipsyncLang||this.opt.lipsyncLang||"en";let r;try{console.log("Lip-sync modules available:",{hasLipsync:!!this.lipsync,lipsyncKeys:this.lipsync?Object.keys(this.lipsync):[],lipsyncLang:c});const d=this.lipsyncPreProcessText(e,c),h=this.lipsyncWordsToVisemes(d,c);if(console.log("Lip-sync data:",{processedText:d,lipsyncData:h,hasVisemes:h&&h.visemes&&h.visemes.length>0}),h&&h.visemes&&h.visemes.length>0)r={visemes:h.visemes.map((g,x)=>({viseme:g,startTime:x*l.duration/h.visemes.length,endTime:(x+1)*l.duration/h.visemes.length,duration:l.duration/h.visemes.length,intensity:.7})),words:[],duration:l.duration,features:{onsets:[],boundaries:[]}};else throw new Error("No visemes generated from text")}catch(d){console.error("Text-based lip-sync failed, using fallback:",d);const h=e.toLowerCase().split(/\s+/),g=[];for(const x of h)for(const f of x){let w="aa";"aeiou".includes(f)?w="aa":"bp".includes(f)?w="PP":"fv".includes(f)?w="FF":"st".includes(f)?w="SS":"dln".includes(f)?w="DD":"kg".includes(f)?w="kk":"rw".includes(f)&&(w="RR"),g.push(w)}r={visemes:g.map((x,f)=>({viseme:x,startTime:f*l.duration/g.length,endTime:(f+1)*l.duration/g.length,duration:l.duration/g.length,intensity:.6})),words:[],duration:l.duration,features:{onsets:[],boundaries:[]}}}console.log("Deepgram TTS Audio Analysis:",{text:e,audioDuration:l.duration,visemeCount:r.visemes?r.visemes.length:0,wordCount:r.words?r.words.length:0,features:{onsets:r.features&&r.features.onsets?r.features.onsets.length:0,boundaries:r.features&&r.features.phonemeBoundaries?r.features.phonemeBoundaries.length:0},visemes:r.visemes?r.visemes.slice(0,3):[]});const u=[];if(r.visemes&&r.visemes.length>0){console.log("Deepgram: Generating lip-sync animation from",r.visemes.length,"visemes");for(let d=0;d<r.visemes.length;d++){const h=r.visemes[d],g=h.startTime*1e3,x=h.duration*1e3,f=h.intensity;u.push({template:{name:"viseme"},ts:[g-Math.min(60,2*x/3),g+Math.min(25,x/2),g+x+Math.min(60,x/2)],vs:{["viseme_"+h.viseme]:[null,f,0]}})}console.log("Deepgram: Generated",u.length,"lip-sync animation frames")}else console.warn("Deepgram: No visemes available for lip-sync animation");const a=[...t.anim,...u];console.log("Deepgram: Combined animation frames:",a.length,"(original:",t.anim.length,"+ lipsync:",u.length,")"),this.audioPlaylist.push({anim:a,audio:l}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio()}async synthesizeWithAzureTTS(t){const e=t.text.map(a=>a.word).join(" "),i=`
2
2
  <speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="en-US">
3
3
  <voice name="${t.voice||this.avatar.ttsVoice||this.opt.ttsVoice||"en-US-AriaNeural"}">
4
4
  ${e}
5
5
  </voice>
6
6
  </speak>
7
- `,s=await fetch(this.opt.ttsEndpoint,{method:"POST",headers:{"Ocp-Apim-Subscription-Key":this.opt.ttsApikey,"Content-Type":"application/ssml+xml","X-Microsoft-OutputFormat":"audio-16khz-128kbitrate-mono-mp3"},body:i});if(!s.ok)throw new Error(`Azure TTS error: ${s.status} ${s.statusText}`);const o=await s.arrayBuffer(),l=await this.audioCtx.decodeAudioData(o);console.log("Analyzing audio for precise lip-sync...");const h=await this.audioAnalyzer.analyzeAudio(l,e);console.log("Azure TTS Audio Analysis:",{text:e,audioDuration:l.duration,visemeCount:h.visemes.length,wordCount:h.words.length,features:{onsets:h.features.onsets.length,boundaries:h.features.phonemeBoundaries.length}});const r=[];for(let a=0;a<h.visemes.length;a++){const d=h.visemes[a],c=d.startTime*1e3,g=d.duration*1e3,b=d.intensity;r.push({template:{name:"viseme"},ts:[c-Math.min(60,2*g/3),c+Math.min(25,g/2),c+g+Math.min(60,g/2)],vs:{["viseme_"+d.viseme]:[null,b,0]}})}const u=[...t.anim,...r];this.audioPlaylist.push({anim:u,audio:l}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio()}async synthesizeWithExternalTTS(t){let e="<speak>";t.text.forEach((o,l)=>{l>0&&(e+=" <mark name='"+o.mark+"'/>"),e+=o.word.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;").replace(new RegExp("^\\p{Dash_Punctuation}$","ug"),'<break time="750ms"/>')}),e+="</speak>";const n={method:"POST",headers:{"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify({input:{ssml:e},voice:{languageCode:t.lang||this.avatar.ttsLang||this.opt.ttsLang,name:t.voice||this.avatar.ttsVoice||this.opt.ttsVoice},audioConfig:{audioEncoding:this.ttsAudioEncoding,speakingRate:(t.rate||this.avatar.ttsRate||this.opt.ttsRate)+this.mood.speech.deltaRate,pitch:(t.pitch||this.avatar.ttsPitch||this.opt.ttsPitch)+this.mood.speech.deltaPitch,volumeGainDb:(t.volume||this.avatar.ttsVolume||this.opt.ttsVolume)+this.mood.speech.deltaVolume},enableTimePointing:[1]})};this.opt.jwtGet&&typeof this.opt.jwtGet=="function"&&(n.headers.Authorization="Bearer "+await this.opt.jwtGet());const i=await fetch(this.opt.ttsEndpoint+(this.opt.ttsApikey?"?key="+this.opt.ttsApikey:""),n),s=await i.json();if(i.status===200&&s&&s.audioContent){const o=this.b64ToArrayBuffer(s.audioContent),l=await this.audioCtx.decodeAudioData(o);this.speakWithHands();const h=[0];let r=0;t.text.forEach((d,c)=>{if(c>0){let g=h[h.length-1];s.timepoints[r]&&(g=s.timepoints[r].timeSeconds*1e3,s.timepoints[r].markName===""+d.mark&&r++),h.push(g)}});const u=[{mark:0,time:0}];h.forEach((d,c)=>{if(c>0){let g=d-h[c-1];u[c-1].duration=g,u.push({mark:c,time:d})}});let a=1e3*l.duration;a>this.opt.ttsTrimEnd&&(a=a-this.opt.ttsTrimEnd),u[u.length-1].duration=a-u[u.length-1].time,t.anim.forEach(d=>{const c=u[d.mark];if(c)for(let g=0;g<d.ts.length;g++)d.ts[g]=c.time+d.ts[g]*c.duration+this.opt.ttsTrimStart}),this.audioPlaylist.push({anim:t.anim,audio:l}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio()}else this.startSpeaking(!0)}async startSpeaking(t=!1){if(!(!this.armature||this.isSpeaking&&!t))if(this.stateName="speaking",this.isSpeaking=!0,this.speechQueue.length){let e=this.speechQueue.shift();if(e.emoji){this.lookAtCamera(500);let n=e.emoji.dt.reduce((i,s)=>i+s,0);this.animQueue.push(this.animFactory(e.emoji)),setTimeout(this.startSpeaking.bind(this),n,!0)}else if(e.break)setTimeout(this.startSpeaking.bind(this),e.break,!0);else if(e.audio)e.isRaw||(this.lookAtCamera(500),this.speakWithHands(),this.resetLips()),this.audioPlaylist.push({anim:e.anim,audio:e.audio,isRaw:e.isRaw}),this.onSubtitles=e.onSubtitles||null,e.mood&&this.setMood(e.mood),this.playAudio();else if(e.text){this.lookAtCamera(500);try{!this.opt.ttsEndpoint||this.opt.ttsEndpoint===""?await this.synthesizeWithBrowserTTS(e):this.opt.ttsService==="elevenlabs"?await this.synthesizeWithElevenLabsTTS(e):this.opt.ttsService==="deepgram"?await this.synthesizeWithDeepgramTTS(e):this.opt.ttsService==="azure"?await this.synthesizeWithAzureTTS(e):await this.synthesizeWithExternalTTS(e)}catch(n){console.error("Error:",n),this.startSpeaking(!0)}}else e.anim?(this.onSubtitles=e.onSubtitles||null,this.resetLips(),e.mood&&this.setMood(e.mood),e.anim.forEach((n,i)=>{for(let s=0;s<n.ts.length;s++)n.ts[s]=this.animClock+10*i;this.animQueue.push(n)}),setTimeout(this.startSpeaking.bind(this),10*e.anim.length,!0)):e.marker?(typeof e.marker=="function"&&e.marker(),this.startSpeaking(!0)):this.startSpeaking(!0)}else this.stateName="idle",this.isSpeaking=!1}pauseSpeaking(){try{this.audioSpeechSource.stop()}catch{}this.audioPlaylist.length=0,this.stateName="idle",this.isSpeaking=!1,this.isAudioPlaying=!1,this.animQueue=this.animQueue.filter(t=>t.template.name!=="viseme"&&t.template.name!=="subtitles"&&t.template.name!=="blendshapes"),this.armature&&(this.resetLips(),this.render())}stopSpeaking(){try{this.audioSpeechSource.stop()}catch{}this.audioPlaylist.length=0,this.speechQueue.length=0,this.animQueue=this.animQueue.filter(t=>t.template.name!=="viseme"&&t.template.name!=="subtitles"&&t.template.name!=="blendshapes"),this.stateName="idle",this.isSpeaking=!1,this.isAudioPlaying=!1,this.armature&&(this.resetLips(),this.render())}async streamStart(t={},e=null,n=null,i=null,s=null){if(this.stopSpeaking(),this.isStreaming=!0,t.waitForAudioChunks!==void 0&&(this.streamWaitForAudioChunks=t.waitForAudioChunks),this.streamWaitForAudioChunks||(this.streamAudioStartTime=this.animClock),this.streamLipsyncQueue=[],this.streamLipsyncType=t.lipsyncType||this.streamLipsyncType||"visemes",this.streamLipsyncLang=t.lipsyncLang||this.streamLipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang,this.onAudioStart=e,this.onAudioEnd=n,this.onMetrics=s,t.sampleRate!==void 0){const l=t.sampleRate;typeof l=="number"&&l>=8e3&&l<=96e3?l!==this.audioCtx.sampleRate&&this.initAudioGraph(l):console.warn("Invalid sampleRate provided. It must be a number between 8000 and 96000 Hz.")}if(t.gain!==void 0&&(this.audioStreamGainNode.gain.value=t.gain),!this.streamWorkletNode||!this.streamWorkletNode.port||this.streamWorkletNode.numberOfOutputs===0||this.streamWorkletNode.context!==this.audioCtx){if(this.streamWorkletNode)try{this.streamWorkletNode.disconnect(),this.streamWorkletNode=null}catch{}if(!this.workletLoaded)try{const l=this.audioCtx.audioWorklet.addModule(ct.href),h=new Promise((r,u)=>setTimeout(()=>u(new Error("Worklet loading timed out")),5e3));await Promise.race([l,h]),this.workletLoaded=!0}catch(l){throw console.error("Failed to load audio worklet:",l),new Error("Failed to initialize streaming speech")}this.streamWorkletNode=new AudioWorkletNode(this.audioCtx,"playback-worklet",{processorOptions:{sampleRate:this.audioCtx.sampleRate,metrics:t.metrics||{enabled:!1}}}),this.streamWorkletNode.connect(this.audioStreamGainNode),this.streamWorkletNode.connect(this.audioAnalyzerNode),this.streamWorkletNode.port.onmessage=l=>{if(l.data.type==="playback-started"&&(this.isSpeaking=!0,this.stateName="speaking",this.streamWaitForAudioChunks&&(this.streamAudioStartTime=this.animClock),this._processStreamLipsyncQueue(),this.speakWithHands(),this.onAudioStart))try{this.onAudioStart?.()}catch(h){console.error(h)}if(l.data.type==="playback-ended"&&(this._streamPause(),this.onAudioEnd))try{this.onAudioEnd()}catch{}if(this.onMetrics&&l.data.type==="metrics")try{this.onMetrics(l.data)}catch{}}}if(t.metrics)try{this.streamWorkletNode.port.postMessage({type:"config-metrics",data:t.metrics})}catch{}if(this.resetLips(),this.lookAtCamera(500),t.mood&&this.setMood(t.mood),this.onSubtitles=i||null,this.audioCtx.state==="suspended"||this.audioCtx.state==="interrupted"){const l=this.audioCtx.resume(),h=new Promise((r,u)=>setTimeout(()=>u("p2"),1e3));try{await Promise.race([l,h])}catch{console.warn("Can't play audio. Web Audio API suspended. This is often due to calling some speak method before the first user action, which is typically prevented by the browser.");return}}}streamNotifyEnd(){!this.isStreaming||!this.streamWorkletNode||this.streamWorkletNode.port.postMessage({type:"no-more-data"})}streamInterrupt(){if(!this.isStreaming)return;const t=this.isSpeaking;if(this.streamWorkletNode)try{this.streamWorkletNode.port.postMessage({type:"stop"})}catch{}if(this._streamPause(!0),t&&this.onAudioEnd)try{this.onAudioEnd()}catch{}}streamStop(){if(this.isStreaming){if(this.streamInterrupt(),this.streamWorkletNode){try{this.streamWorkletNode.disconnect()}catch{}this.streamWorkletNode=null}this.isStreaming=!1}}_streamPause(t=!1){this.isSpeaking=!1,this.stateName="idle",t&&(this.streamWaitForAudioChunks&&(this.streamAudioStartTime=null),this.streamLipsyncQueue=[],this.animQueue=this.animQueue.filter(e=>e.template.name!=="viseme"&&e.template.name!=="subtitles"&&e.template.name!=="blendshapes"),this.armature&&(this.resetLips(),this.render()))}_processStreamLipsyncQueue(){if(this.isStreaming)for(;this.streamLipsyncQueue.length>0;){const t=this.streamLipsyncQueue.shift();this._processLipsyncData(t,this.streamAudioStartTime)}}_processLipsyncData(t,e){if(this.isStreaming){if(t.visemes&&this.streamLipsyncType=="visemes")for(let n=0;n<t.visemes.length;n++){const i=t.visemes[n],s=e+t.vtimes[n],o=t.vdurations[n],l={template:{name:"viseme"},ts:[s-2*o/3,s+o/2,s+o+o/2],vs:{["viseme_"+i]:[null,i==="PP"||i==="FF"?.9:.6,0]}};this.animQueue.push(l)}if(t.words&&(this.onSubtitles||this.streamLipsyncType=="words"))for(let n=0;n<t.words.length;n++){const i=t.words[n],s=t.wtimes[n];let o=t.wdurations[n];if(i.length&&(this.onSubtitles&&this.animQueue.push({template:{name:"subtitles"},ts:[e+s],vs:{subtitles:[" "+i]}}),this.streamLipsyncType=="words")){const l=this.streamLipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang,h=this.lipsyncPreProcessText(i,l),r=this.lipsyncWordsToVisemes(h,l);if(r&&r.visemes&&r.visemes.length){const u=r.times[r.visemes.length-1]+r.durations[r.visemes.length-1],a=Math.min(o,Math.max(0,o-r.visemes.length*150));let d=.6+this.convertRange(a,[0,o],[0,.4]);if(o=Math.min(o,r.visemes.length*200),u>0)for(let c=0;c<r.visemes.length;c++){const g=e+s+r.times[c]/u*o,b=r.durations[c]/u*o;this.animQueue.push({template:{name:"viseme"},ts:[g-Math.min(60,2*b/3),g+Math.min(25,b/2),g+b+Math.min(60,b/2)],vs:{["viseme_"+r.visemes[c]]:[null,r.visemes[c]==="PP"||r.visemes[c]==="FF"?.9:d,0]}})}}}}if(t.anims&&this.streamLipsyncType=="blendshapes")for(let n=0;n<t.anims.length;n++){let i=t.anims[n];i.delay+=e;let s=this.animFactory(i,!1,1,1,!0);this.animQueue.push(s)}}}streamAudio(t){if(!(!this.isStreaming||!this.streamWorkletNode)){if(this.isSpeaking||(this.streamLipsyncQueue=[],this.streamAudioStartTime=null),this.isSpeaking=!0,this.stateName="speaking",t.audio!==void 0){const e={type:"audioData",data:null};if(t.audio instanceof ArrayBuffer)e.data=t.audio,this.streamWorkletNode.port.postMessage(e,[e.data]);else if(t.audio instanceof Int16Array||t.audio instanceof Uint8Array){const n=t.audio.buffer.slice(t.audio.byteOffset,t.audio.byteOffset+t.audio.byteLength);e.data=n,this.streamWorkletNode.port.postMessage(e,[e.data])}else if(t.audio instanceof Float32Array){const n=new Int16Array(t.audio.length);for(let i=0;i<t.audio.length;i++){let s=Math.max(-1,Math.min(1,t.audio[i]));n[i]=s<0?s*32768:s*32767}e.data=n.buffer,this.streamWorkletNode.port.postMessage(e,[e.data])}else console.error("r.audio is not a supported type. Must be ArrayBuffer, Int16Array, Uint8Array, or Float32Array:",t.audio)}if(t.visemes||t.anims||t.words){if(this.streamWaitForAudioChunks&&!this.streamAudioStartTime){this.streamLipsyncQueue.length>=200&&this.streamLipsyncQueue.shift(),this.streamLipsyncQueue.push(t);return}else!this.streamWaitForAudioChunks&&!this.streamAudioStartTime&&(this.streamAudioStartTime=this.animClock);this._processLipsyncData(t,this.streamAudioStartTime)}}}makeEyeContact(t){this.animQueue.push(this.animFactory({name:"eyecontact",dt:[0,t],vs:{eyeContact:[1]}}))}lookAhead(t){if(t){let e=(Math.random()-.5)/4,n=(Math.random()-.5)/4,i=this.animQueue.findIndex(o=>o.template.name==="lookat");i!==-1&&this.animQueue.splice(i,1);const s={name:"lookat",dt:[750,t],vs:{bodyRotateX:[e],bodyRotateY:[n],eyesRotateX:[-3*e+.1],eyesRotateY:[-5*n],browInnerUp:[[0,.7]],mouthLeft:[[0,.7]],mouthRight:[[0,.7]],eyeContact:[0],headMove:[0]}};this.animQueue.push(this.animFactory(s))}}lookAtCamera(t){let e;if(this.speakTo&&(e=new f.Vector3,this.speakTo.objectLeftEye?.isObject3D?(this.speakTo.armature.objectHead,this.speakTo.objectLeftEye.updateMatrixWorld(!0),this.speakTo.objectRightEye.updateMatrixWorld(!0),fe.setFromMatrixPosition(this.speakTo.objectLeftEye.matrixWorld),xe.setFromMatrixPosition(this.speakTo.objectRightEye.matrixWorld),e.addVectors(fe,xe).divideScalar(2)):this.speakTo.isObject3D?this.speakTo.getWorldPosition(e):this.speakTo.isVector3?e.set(this.speakTo):this.speakTo.x&&this.speakTo.y&&this.speakTo.z&&e.set(this.speakTo.x,this.speakTo.y,this.speakTo.z)),!e){if(this.avatar.hasOwnProperty("avatarIgnoreCamera")){if(this.avatar.avatarIgnoreCamera){this.lookAhead(t);return}}else if(this.opt.avatarIgnoreCamera){this.lookAhead(t);return}this.lookAt(null,null,t);return}this.objectLeftEye.updateMatrixWorld(!0),this.objectRightEye.updateMatrixWorld(!0),fe.setFromMatrixPosition(this.objectLeftEye.matrixWorld),xe.setFromMatrixPosition(this.objectRightEye.matrixWorld),fe.add(xe).divideScalar(2),q.copy(this.armature.quaternion),q.multiply(this.poseTarget.props["Hips.quaternion"]),q.multiply(this.poseTarget.props["Spine.quaternion"]),q.multiply(this.poseTarget.props["Spine1.quaternion"]),q.multiply(this.poseTarget.props["Spine2.quaternion"]),q.multiply(this.poseTarget.props["Neck.quaternion"]),q.multiply(this.poseTarget.props["Head.quaternion"]);const n=new f.Vector3().subVectors(e,fe).normalize(),i=Math.atan2(n.x,n.z),s=Math.asin(-n.y);Z.set(s,i,0,"YXZ");const l=new f.Quaternion().setFromEuler(Z),h=new f.Quaternion().copy(l).multiply(q.clone().invert());Z.setFromQuaternion(h,"YXZ");let r=Z.x/(40/24)+.2,u=Z.y/(9/4),a=Math.min(.6,Math.max(-.3,r)),d=Math.min(.8,Math.max(-.8,u)),c=(Math.random()-.5)/4,g=(Math.random()-.5)/4;if(t){let b=this.animQueue.findIndex(S=>S.template.name==="lookat");b!==-1&&this.animQueue.splice(b,1);const x={name:"lookat",dt:[750,t],vs:{bodyRotateX:[a+c],bodyRotateY:[d+g],eyesRotateX:[-3*c+.1],eyesRotateY:[-5*g],browInnerUp:[[0,.7]],mouthLeft:[[0,.7]],mouthRight:[[0,.7]],eyeContact:[0],headMove:[0]}};this.animQueue.push(this.animFactory(x))}}lookAt(t,e,n){if(!this.camera)return;const i=this.nodeAvatar.getBoundingClientRect();this.objectLeftEye.updateMatrixWorld(!0),this.objectRightEye.updateMatrixWorld(!0);const s=new f.Vector3().setFromMatrixPosition(this.objectLeftEye.matrixWorld),o=new f.Vector3().setFromMatrixPosition(this.objectRightEye.matrixWorld),l=new f.Vector3().addVectors(s,o).divideScalar(2);l.project(this.camera);let h=(l.x+1)/2*i.width+i.left,r=-(l.y-1)/2*i.height+i.top;t===null&&(t=h),e===null&&(e=r),q.copy(this.armature.quaternion),q.multiply(this.poseTarget.props["Hips.quaternion"]),q.multiply(this.poseTarget.props["Spine.quaternion"]),q.multiply(this.poseTarget.props["Spine1.quaternion"]),q.multiply(this.poseTarget.props["Spine2.quaternion"]),q.multiply(this.poseTarget.props["Neck.quaternion"]),q.multiply(this.poseTarget.props["Head.quaternion"]),Z.setFromQuaternion(q);let u=Z.x/(40/24),a=Z.y/(9/4),d=Math.min(.4,Math.max(-.4,this.camera.rotation.x)),c=Math.min(.4,Math.max(-.4,this.camera.rotation.y)),g=Math.max(window.innerWidth-h,h),b=Math.max(window.innerHeight-r,r),x=this.convertRange(e,[r-b,r+b],[-.3,.6])-u+d,S=this.convertRange(t,[h-g,h+g],[-.8,.8])-a+c;x=Math.min(.6,Math.max(-.3,x)),S=Math.min(.8,Math.max(-.8,S));let U=(Math.random()-.5)/4,p=(Math.random()-.5)/4;if(n){let F=this.animQueue.findIndex(y=>y.template.name==="lookat");F!==-1&&this.animQueue.splice(F,1);const H={name:"lookat",dt:[750,n],vs:{bodyRotateX:[x+U],bodyRotateY:[S+p],eyesRotateX:[-3*U+.1],eyesRotateY:[-5*p],browInnerUp:[[0,.7]],mouthLeft:[[0,.7]],mouthRight:[[0,.7]],eyeContact:[0],headMove:[0]}};this.animQueue.push(this.animFactory(H))}}touchAt(t,e){if(!this.camera)return;const n=this.nodeAvatar.getBoundingClientRect(),i=new f.Vector2((t-n.left)/n.width*2-1,-((e-n.top)/n.height)*2+1),s=new f.Raycaster;s.setFromCamera(i,this.camera);const o=s.intersectObject(this.armature);if(o.length>0){const l=o[0].point,h=new f.Vector3,r=new f.Vector3;this.objectLeftArm.getWorldPosition(h),this.objectRightArm.getWorldPosition(r);const u=h.distanceToSquared(l),a=r.distanceToSquared(l);u<a?(this.ikSolve({iterations:20,root:"LeftShoulder",effector:"LeftHandMiddle1",links:[{link:"LeftHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5,maxAngle:.1},{link:"LeftForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-.5,maxz:3,maxAngle:.2},{link:"LeftArm",minx:-1.5,maxx:1.5,miny:0,maxy:0,minz:-1,maxz:3}]},l,!1,1e3),this.setValue("handFistLeft",0)):(this.ikSolve({iterations:20,root:"RightShoulder",effector:"RightHandMiddle1",links:[{link:"RightHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5,maxAngle:.1},{link:"RightForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-3,maxz:.5,maxAngle:.2},{link:"RightArm",minx:-1.5,maxx:1.5,miny:0,maxy:0,minz:-1,maxz:3}]},l,!1,1e3),this.setValue("handFistRight",0))}else["LeftArm","LeftForeArm","LeftHand","RightArm","RightForeArm","RightHand"].forEach(l=>{let h=l+".quaternion";this.poseTarget.props[h].copy(this.getPoseTemplateProp(h)),this.poseTarget.props[h].t=this.animClock,this.poseTarget.props[h].d=1e3});return o.length>0}speakWithHands(t=0,e=.5){if(this.mixer||this.gesture||!this.poseTarget.template.standing||this.poseTarget.template.bend||Math.random()>e)return;this.ikSolve({root:"LeftShoulder",effector:"LeftHandMiddle1",links:[{link:"LeftHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5},{link:"LeftForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-.5,maxz:3},{link:"LeftArm",minx:-1.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-1,maxz:3}]},new f.Vector3(this.gaussianRandom(0,.5),this.gaussianRandom(-.8,-.2),this.gaussianRandom(0,.5)),!0),this.ikSolve({root:"RightShoulder",effector:"RightHandMiddle1",links:[{link:"RightHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5},{link:"RightForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-3,maxz:.5},{link:"RightArm"}]},new f.Vector3(this.gaussianRandom(-.5,0),this.gaussianRandom(-.8,-.2),this.gaussianRandom(0,.5)),!0);const n=[],i=[];n.push(100+Math.round(Math.random()*500)),i.push({duration:1e3,props:{"LeftHand.quaternion":new f.Quaternion().setFromEuler(new f.Euler(0,-1-Math.random(),0)),"RightHand.quaternion":new f.Quaternion().setFromEuler(new f.Euler(0,1+Math.random(),0))}}),["LeftArm","LeftForeArm","RightArm","RightForeArm"].forEach(o=>{i[0].props[o+".quaternion"]=this.ikMesh.getObjectByName(o).quaternion.clone()}),n.push(1e3+Math.round(Math.random()*500)),i.push({duration:2e3,props:{}}),["LeftArm","LeftForeArm","RightArm","RightForeArm","LeftHand","RightHand"].forEach(o=>{i[1].props[o+".quaternion"]=null});const s=this.animFactory({name:"talkinghands",delay:t,dt:n,vs:{moveto:i}});this.animQueue.push(s)}getSlowdownRate(t){return this.animSlowdownRate}setSlowdownRate(t){this.animSlowdownRate=t,this.audioSpeechSource.playbackRate.value=1/this.animSlowdownRate,this.audioBackgroundSource.playbackRate.value=1/this.animSlowdownRate}getAutoRotateSpeed(t){return this.controls.autoRotateSpeed}setAutoRotateSpeed(t){this.controls.autoRotateSpeed=t,this.controls.autoRotate=t>0}start(){this.armature&&this.isRunning===!1&&(this.audioCtx.resume(),this.animTimeLast=performance.now(),this.isRunning=!0,this.isAvatarOnly||requestAnimationFrame(this.animate.bind(this)))}stop(){this.isRunning=!1,this.audioCtx.suspend()}startListening(t,e={},n=null){this.listeningAnalyzer=t,this.listeningAnalyzer.fftSize=256,this.listeningAnalyzer.smoothingTimeConstant=.1,this.listeningAnalyzer.minDecibels=-70,this.listeningAnalyzer.maxDecibels=-10,this.listeningOnchange=n&&typeof n=="function"?n:null,this.listeningSilenceThresholdLevel=e?.hasOwnProperty("listeningSilenceThresholdLevel")?e.listeningSilenceThresholdLevel:this.opt.listeningSilenceThresholdLevel,this.listeningSilenceThresholdMs=e?.hasOwnProperty("listeningSilenceThresholdMs")?e.listeningSilenceThresholdMs:this.opt.listeningSilenceThresholdMs,this.listeningSilenceDurationMax=e?.hasOwnProperty("listeningSilenceDurationMax")?e.listeningSilenceDurationMax:this.opt.listeningSilenceDurationMax,this.listeningActiveThresholdLevel=e?.hasOwnProperty("listeningActiveThresholdLevel")?e.listeningActiveThresholdLevel:this.opt.listeningActiveThresholdLevel,this.listeningActiveThresholdMs=e?.hasOwnProperty("listeningActiveThresholdMs")?e.listeningActiveThresholdMs:this.opt.listeningActiveThresholdMs,this.listeningActiveDurationMax=e?.hasOwnProperty("listeningActiveDurationMax")?e.listeningActiveDurationMax:this.opt.listeningActiveDurationMax,this.listeningActive=!1,this.listeningVolume=0,this.listeningTimer=0,this.listeningTimerTotal=0,this.isListening=!0}stopListening(){this.isListening=!1}async playAnimation(t,e=null,n=10,i=0,s=.01,o=!1){if(!this.armature)return;this.positionWasLocked=!o,o?console.log("Position locking disabled for FBX animation:",t):(this.lockAvatarPosition(),console.log("Position locked immediately before FBX animation:",t));let l=this.animClips.find(h=>h.url===t+"-"+i);if(l){let h=this.animQueue.find(a=>a.template.name==="pose");h&&(h.ts[0]=1/0),Object.entries(l.pose.props).forEach(a=>{this.poseBase.props[a[0]]=a[1].clone(),this.poseTarget.props[a[0]]=a[1].clone(),this.poseTarget.props[a[0]].t=0,this.poseTarget.props[a[0]].d=1e3}),this.mixer?console.log("Using existing mixer for FBX animation, preserving morph targets"):(this.mixer=new f.AnimationMixer(this.armature),console.log("Created new mixer for FBX animation")),this.mixer.addEventListener("finished",this.stopAnimation.bind(this),{once:!0});const r=Math.ceil(n/l.clip.duration),u=this.mixer.clipAction(l.clip);u.setLoop(f.LoopRepeat,r),u.clampWhenFinished=!0,this.currentFBXAction=u;try{u.fadeIn(.5).play(),console.log("FBX animation started successfully:",t)}catch(a){console.warn("FBX animation failed to start:",a),this.stopAnimation();return}if(u.getClip().tracks.length===0){console.warn("FBX animation has no valid tracks, stopping"),this.stopAnimation();return}}else{if(t.split(".").pop().toLowerCase()!=="fbx"){console.error(`Invalid file type for FBX animation: ${t}. Expected .fbx file.`);return}let r=!1;try{const d=await fetch(t,{method:"HEAD"});if(r=d.ok,!r){console.error(`FBX file not found at ${t}. Status: ${d.status}`),console.error("Please check:"),console.error("1. File path is correct (note: path is case-sensitive)"),console.error("2. File exists in your public folder"),console.error("3. File is accessible (not blocked by server)");return}}catch(d){console.warn(`Could not verify file existence for ${t}, attempting to load anyway:`,d)}const u=new Pe.FBXLoader;let a;try{a=await u.loadAsync(t,e)}catch(d){console.error(`Failed to load FBX animation from ${t}:`,d),console.error("Error details:",{message:d.message,url:t,suggestion:"Make sure the file is a valid FBX file and the path is correct"}),d.message&&d.message.includes("version number")&&(console.error("FBX Loader Error: Cannot find version number"),console.error("This error usually means:"),console.error("1. The file is not a valid FBX file (might be GLB, corrupted, or wrong format)"),console.error("2. The file might be corrupted"),console.error("3. The file path might be incorrect"),console.error("4. The server returned an HTML error page instead of the FBX file"),console.error("5. The file might not exist at that path"),console.error(""),console.error("Solution: Please verify:"),console.error(` - File exists at: ${t}`),console.error(" - File is a valid FBX binary file"),console.error(" - File path matches your public folder structure"),console.error(" - File is not corrupted"));try{const c=await fetch(t),g=c.headers.get("content-type"),b=await c.text();console.error("Response details:",{status:c.status,contentType:g,firstBytes:b.substring(0,100),isHTML:b.trim().startsWith("<!DOCTYPE")||b.trim().startsWith("<html")}),(b.trim().startsWith("<!DOCTYPE")||b.trim().startsWith("<html"))&&console.error("The server returned an HTML page instead of an FBX file. The file path is likely incorrect.")}catch(c){console.error("Could not fetch file for debugging:",c)}return}if(a&&a.animations&&a.animations[i]){let d=a.animations[i];const c=new Set;this.armature&&this.armature.traverse(A=>{(A.isBone||A.type==="Bone")&&c.add(A.name)});const g=new Map,b=A=>{if(c.has(A))return A;let z=A.replace(/^mixamorig/i,"").replace(/^CC_Base_/i,"").replace(/^RPM_/i,"");if(c.has(z))return z;const L=z.toLowerCase();if(L.includes("left")&&L.includes("arm")){if(L.includes("fore")||L.includes("lower")){if(c.has("LeftForeArm"))return"LeftForeArm";if(c.has("LeftForearm"))return"LeftForearm"}else if(!L.includes("fore")&&!L.includes("hand")&&c.has("LeftArm"))return"LeftArm"}if(L.includes("right")&&L.includes("arm")){if(L.includes("fore")||L.includes("lower")){if(c.has("RightForeArm"))return"RightForeArm";if(c.has("RightForearm"))return"RightForearm"}else if(!L.includes("fore")&&!L.includes("hand")&&c.has("RightArm"))return"RightArm"}if(L.includes("left")&&L.includes("hand")&&!L.includes("index")&&!L.includes("thumb")&&!L.includes("middle")&&!L.includes("ring")&&!L.includes("pinky")&&c.has("LeftHand"))return"LeftHand";if(L.includes("right")&&L.includes("hand")&&!L.includes("index")&&!L.includes("thumb")&&!L.includes("middle")&&!L.includes("ring")&&!L.includes("pinky")&&c.has("RightHand"))return"RightHand";if(L.includes("left")&&(L.includes("shoulder")||L.includes("clavicle"))&&c.has("LeftShoulder"))return"LeftShoulder";if(L.includes("right")&&(L.includes("shoulder")||L.includes("clavicle"))&&c.has("RightShoulder"))return"RightShoulder";const X={LeftArm:"LeftArm",leftArm:"LeftArm",LEFTARM:"LeftArm",RightArm:"RightArm",rightArm:"RightArm",RIGHTARM:"RightArm",LeftForeArm:"LeftForeArm",leftForeArm:"LeftForeArm",leftForearm:"LeftForeArm",LeftForearm:"LeftForeArm",RightForeArm:"RightForeArm",rightForeArm:"RightForeArm",rightForearm:"RightForeArm",RightForearm:"RightForeArm",LeftHand:"LeftHand",leftHand:"LeftHand",RightHand:"RightHand",rightHand:"RightHand",LeftShoulder:"LeftShoulder",leftShoulder:"LeftShoulder",RightShoulder:"RightShoulder",rightShoulder:"RightShoulder",Spine:"Spine1",spine:"Spine1",Spine1:"Spine1",Spine2:"Spine2",Head:"Head",head:"Head",Neck:"Neck",neck:"Neck",Hips:"Hips",hips:"Hips",Root:"Hips",root:"Hips"};if(X[z]){const w=X[z];if(c.has(w))return w}for(const w of c)if(w.toLowerCase()===L)return w;for(const w of c){const P=w.toLowerCase();if((L.includes("left")&&P.includes("left")||L.includes("right")&&P.includes("right"))&&(L.includes("arm")&&P.includes("arm")&&!P.includes("fore")||L.includes("forearm")&&P.includes("forearm")||L.includes("hand")&&P.includes("hand")&&!P.includes("index")&&!P.includes("thumb")||L.includes("shoulder")&&P.includes("shoulder")))return w}return null},x=new Set;d.tracks.forEach(A=>{const z=A.name.split(".");x.add(z[0])}),console.log("=== Ready Player Me Animation Bone Analysis ==="),console.log("FBX bone names:",Array.from(x).sort().join(", ")),console.log("Avatar skeleton bone names:",Array.from(c).sort().join(", "));const S=Array.from(x).filter(A=>A.toLowerCase().includes("arm")||A.toLowerCase().includes("hand")||A.toLowerCase().includes("shoulder")),U=Array.from(c).filter(A=>A.includes("Arm")||A.includes("Hand")||A.includes("Shoulder"));console.log("FBX arm/hand/shoulder bones:",S.sort().join(", ")),console.log("Avatar arm/hand/shoulder bones:",U.sort().join(", "));const p=[],F=new Set;if(d.tracks.forEach(A=>{const L=A.name.replaceAll("mixamorig","").split("."),X=L[0],w=L[1],P=b(X);if(P&&w){const Q=`${P}.${w}`,G=A.clone();G.name=Q,p.push(G),X!==P&&g.set(X,P)}else F.add(X),(X.toLowerCase().includes("arm")||X.toLowerCase().includes("hand")||X.toLowerCase().includes("shoulder"))&&console.warn(`⚠️ Arm bone "${X}" could not be mapped to avatar skeleton`)}),F.size>0&&console.warn(`⚠️ ${F.size} bone(s) could not be mapped:`,Array.from(F).sort().join(", ")),p.length>0){d=new f.AnimationClip(d.name,d.duration,p),console.log(`✓ Created animation with ${p.length} mapped tracks (from ${d.tracks.length} original tracks)`),g.size>0&&console.log(`✓ Mapped ${g.size} bone(s):`,Array.from(g.entries()).map(([z,L])=>`${z}→${L}`).join(", "));const A=Array.from(g.values()).filter(z=>z.includes("Arm")||z.includes("Hand")||z.includes("Shoulder"));A.length>0?console.log(`✓ Arm bones mapped: ${A.join(", ")}`):console.warn("⚠️ No arm bones were mapped! This may cause arm rigging issues.")}else console.error("❌ No tracks could be mapped! Animation may not work correctly.");const H={};d.tracks.forEach(A=>{A.name=A.name.replaceAll("mixamorig","");const z=A.name.split(".");if(z[1]==="position"){for(let L=0;L<A.values.length;L++)A.values[L]=A.values[L]*s;H[A.name]=new f.Vector3(A.values[0],A.values[1],A.values[2])}else z[1]==="quaternion"?H[A.name]=new f.Quaternion(A.values[0],A.values[1],A.values[2],A.values[3]):z[1]==="rotation"&&(H[z[0]+".quaternion"]=new f.Quaternion().setFromEuler(new f.Euler(A.values[0],A.values[1],A.values[2],"XYZ")).normalize())});const y={props:H};H["Hips.position"]&&(H["Hips.position"].y<.5?y.lying=!0:y.standing=!0),this.animClips.push({url:t+"-"+i,clip:d,pose:y}),this.playAnimation(t,e,n,i,s)}else{const d="Animation "+t+" (ndx="+i+") not found";console.error(d),a&&a.animations?console.error(`FBX file loaded but has ${a.animations.length} animation(s), requested index ${i}`):console.error(a?"FBX file loaded but contains no animations":"FBX file failed to load or is invalid")}}}stopAnimation(){if(this.currentFBXAction&&(this.currentFBXAction.stop(),this.currentFBXAction=null,console.log("FBX animation action stopped, mixer preserved for lip-sync")),this.mixer&&this.mixer._actions.length===0&&(this.mixer=null,console.log("Mixer destroyed as no actions remain")),this.positionWasLocked?(this.unlockAvatarPosition(),console.log("Position unlocked after FBX animation stopped")):console.log("Position was not locked, no unlock needed"),this.gesture)for(let[e,n]of Object.entries(this.gesture))n.t=this.animClock,n.d=1e3,this.poseTarget.props.hasOwnProperty(e)&&(this.poseTarget.props[e].copy(n),this.poseTarget.props[e].t=this.animClock,this.poseTarget.props[e].d=1e3);let t=this.animQueue.find(e=>e.template.name==="pose");t&&(t.ts[0]=this.animClock),this.setPoseFromTemplate(null)}async playPose(t,e=null,n=5,i=0,s=.01){if(!this.armature)return;let o=this.poseTemplates[t];if(!o){const l=this.animPoses.find(h=>h.url===t+"-"+i);l&&(o=l.pose)}if(o){this.poseName=t,this.mixer=null;let l=this.animQueue.find(h=>h.template.name==="pose");l&&(l.ts[0]=this.animClock+n*1e3+2e3),this.setPoseFromTemplate(o)}else{let h=await new Pe.FBXLoader().loadAsync(t,e);if(h&&h.animations&&h.animations[i]){let r=h.animations[i];const u={};r.tracks.forEach(d=>{d.name=d.name.replaceAll("mixamorig","");const c=d.name.split(".");c[1]==="position"?u[d.name]=new f.Vector3(d.values[0]*s,d.values[1]*s,d.values[2]*s):c[1]==="quaternion"?u[d.name]=new f.Quaternion(d.values[0],d.values[1],d.values[2],d.values[3]):c[1]==="rotation"&&(u[c[0]+".quaternion"]=new f.Quaternion().setFromEuler(new f.Euler(d.values[0],d.values[1],d.values[2],"XYZ")).normalize())});const a={props:u};u["Hips.position"]&&(u["Hips.position"].y<.5?a.lying=!0:a.standing=!0),this.animPoses.push({url:t+"-"+i,pose:a}),this.playPose(t,e,n,i,s)}else{const r="Pose "+t+" (ndx="+i+") not found";console.error(r)}}}stopPose(){this.stopAnimation()}playGesture(t,e=3,n=!1,i=1e3){if(!this.armature)return;let s=this.gestureTemplates[t];if(s){this.gestureTimeout&&(clearTimeout(this.gestureTimeout),this.gestureTimeout=null);let l=this.animQueue.findIndex(h=>h.template.name==="talkinghands");l!==-1&&(this.animQueue[l].ts=this.animQueue[l].ts.map(h=>0)),this.gesture=this.propsToThreeObjects(s),n&&(this.gesture=this.mirrorPose(this.gesture)),t==="namaste"&&this.avatar.body==="M"&&(this.gesture["RightArm.quaternion"].rotateTowards(new f.Quaternion(0,1,0,0),-.25),this.gesture["LeftArm.quaternion"].rotateTowards(new f.Quaternion(0,1,0,0),-.25));for(let[h,r]of Object.entries(this.gesture))r.t=this.animClock,r.d=i,this.poseTarget.props.hasOwnProperty(h)&&(this.poseTarget.props[h].copy(r),this.poseTarget.props[h].t=this.animClock,this.poseTarget.props[h].d=i);e&&Number.isFinite(e)&&(this.gestureTimeout=setTimeout(this.stopGesture.bind(this,i),1e3*e))}let o=this.animEmojis[t];if(o&&(o&&o.link&&(o=this.animEmojis[o.link]),o)){this.lookAtCamera(500);const l=this.animFactory(o);if(l.gesture=!0,e&&Number.isFinite(e)){const h=l.ts[0],u=l.ts[l.ts.length-1]-h;if(e*1e3-u>0){const d=[];for(let b=1;b<l.ts.length;b++)d.push(l.ts[b]-l.ts[b-1]);const c=o.template?.rescale||d.map(b=>b/u),g=e*1e3-u;l.ts=l.ts.map((b,x,S)=>x===0?h:S[x-1]+d[x-1]+c[x-1]*g)}else{const d=e*1e3/u;l.ts=l.ts.map(c=>h+d*(c-h))}}this.animQueue.push(l)}}stopGesture(t=1e3){if(this.gestureTimeout&&(clearTimeout(this.gestureTimeout),this.gestureTimeout=null),this.gesture){const n=Object.entries(this.gesture);this.gesture=null;for(const[i,s]of n)this.poseTarget.props.hasOwnProperty(i)&&(this.poseTarget.props[i].copy(this.getPoseTemplateProp(i)),this.poseTarget.props[i].t=this.animClock,this.poseTarget.props[i].d=t)}let e=this.animQueue.findIndex(n=>n.gesture);e!==-1&&this.animQueue.splice(e,1)}ikSolve(t,e=null,n=!1,i=null){const s=new f.Vector3,o=new f.Vector3,l=new f.Vector3,h=new f.Vector3,r=new f.Quaternion,u=new f.Vector3,a=new f.Vector3,d=new f.Vector3,c=this.ikMesh.getObjectByName(t.root);c.position.setFromMatrixPosition(this.armature.getObjectByName(t.root).matrixWorld),c.quaternion.setFromRotationMatrix(this.armature.getObjectByName(t.root).matrixWorld),e&&n&&e.applyQuaternion(this.armature.quaternion).add(c.position);const g=this.ikMesh.getObjectByName(t.effector),b=t.links;b.forEach(S=>{S.bone=this.ikMesh.getObjectByName(S.link),S.bone.quaternion.copy(this.getPoseTemplateProp(S.link+".quaternion"))}),c.updateMatrixWorld(!0);const x=t.iterations||10;if(e)for(let S=0;S<x;S++){let U=!1;for(let p=0,F=b.length;p<F;p++){const H=b[p].bone;H.matrixWorld.decompose(h,r,u),r.invert(),o.setFromMatrixPosition(g.matrixWorld),l.subVectors(o,h),l.applyQuaternion(r),l.normalize(),s.subVectors(e,h),s.applyQuaternion(r),s.normalize();let y=s.dot(l);y>1?y=1:y<-1&&(y=-1),y=Math.acos(y),!(y<1e-5)&&(b[p].minAngle!==void 0&&y<b[p].minAngle&&(y=b[p].minAngle),b[p].maxAngle!==void 0&&y>b[p].maxAngle&&(y=b[p].maxAngle),a.crossVectors(l,s),a.normalize(),q.setFromAxisAngle(a,y),H.quaternion.multiply(q),H.rotation.setFromVector3(d.setFromEuler(H.rotation).clamp(new f.Vector3(b[p].minx!==void 0?b[p].minx:-1/0,b[p].miny!==void 0?b[p].miny:-1/0,b[p].minz!==void 0?b[p].minz:-1/0),new f.Vector3(b[p].maxx!==void 0?b[p].maxx:1/0,b[p].maxy!==void 0?b[p].maxy:1/0,b[p].maxz!==void 0?b[p].maxz:1/0))),H.updateMatrixWorld(!0),U=!0)}if(!U)break}i&&b.forEach(S=>{this.poseTarget.props[S.link+".quaternion"].copy(S.bone.quaternion),this.poseTarget.props[S.link+".quaternion"].t=this.animClock,this.poseTarget.props[S.link+".quaternion"].d=i})}dispose(){this.isRunning=!1,this.stop(),this.stopSpeaking(),this.streamStop(),this.isAvatarOnly?this.armature&&(this.armature.parent&&this.armature.parent.remove(this.armature),this.clearThree(this.armature)):(this.clearThree(this.scene),this.resizeobserver.disconnect(),this.renderer&&(this.renderer.dispose(),this.renderer.domElement&&this.renderer.domElement.parentNode&&this.renderer.domElement.parentNode.removeChild(this.renderer.domElement),this.renderer=null)),this.clearThree(this.ikMesh),this.dynamicbones.dispose()}}const be={apiKey:"sk_ace57ef3ef65a92b9d3bee2a00183b78ca790bc3e10964f2",endpoint:"https://api.elevenlabs.io/v1/text-to-speech",defaultVoice:"21m00Tcm4TlvDq8ikWAM",voices:{rachel:"21m00Tcm4TlvDq8ikWAM",drew:"29vD33N1CtxCmqQRPOHJ",bella:"EXAVITQu4vr4xnSDxMaL",antoni:"ErXwobaYiN019PkySvjV",elli:"MF3mGyEYCl7XYWbV9V6O",josh:"VR6AewLTigWG4xSOukaG"}},ze={defaultVoice:"aura-2-thalia-en",voices:{thalia:"aura-2-thalia-en",asteria:"aura-2-asteria-en",orion:"aura-2-orion-en",stella:"aura-2-stella-en",athena:"aura-2-athena-en",hera:"aura-2-hera-en",zeus:"aura-2-zeus-en"}};function Le(){return{service:"elevenlabs",endpoint:be.endpoint,apiKey:be.apiKey,defaultVoice:be.defaultVoice,voices:be.voices}}function mt(){const O=Le(),t=[];return Object.entries(O.voices).forEach(([e,n])=>{t.push({value:n,label:`${e.charAt(0).toUpperCase()+e.slice(1)} (${O.service})`})}),t}const Me=R.forwardRef(({avatarUrl:O="/avatars/brunette.glb",avatarBody:t="F",mood:e="neutral",ttsLang:n="en",ttsService:i=null,ttsVoice:s=null,ttsApiKey:o=null,bodyMovement:l="idle",movementIntensity:h=.5,showFullAvatar:r=!0,cameraView:u="upper",onReady:a=()=>{},onLoading:d=()=>{},onError:c=()=>{},className:g="",style:b={},animations:x={}},S)=>{const U=R.useRef(null),p=R.useRef(null),F=R.useRef(r),H=R.useRef(null),y=R.useRef(null),A=R.useRef(!1),z=R.useRef({remainingText:null,originalText:null,options:null}),L=R.useRef([]),X=R.useRef(0),[w,P]=R.useState(!0),[Q,G]=R.useState(null),[$,oe]=R.useState(!1),[se,ce]=R.useState(!1);R.useEffect(()=>{A.current=se},[se]),R.useEffect(()=>{F.current=r},[r]);const ee=Le(),le=i||ee.service;let W;le==="browser"?W={service:"browser",endpoint:"",apiKey:null,defaultVoice:"Google US English"}:le==="elevenlabs"?W={service:"elevenlabs",endpoint:"https://api.elevenlabs.io/v1/text-to-speech",apiKey:o||ee.apiKey,defaultVoice:s||ee.defaultVoice||be.defaultVoice,voices:ee.voices||be.voices}:le==="deepgram"?W={service:"deepgram",endpoint:"https://api.deepgram.com/v1/speak",apiKey:o||ee.apiKey,defaultVoice:s||ee.defaultVoice||ze.defaultVoice,voices:ee.voices||ze.voices}:W={...ee,apiKey:o!==null?o:ee.apiKey};const v={url:O,body:t,avatarMood:e,ttsLang:le==="browser"?"en-US":n,ttsVoice:s||W.defaultVoice,lipsyncLang:"en",showFullAvatar:r,bodyMovement:l,movementIntensity:h},I={ttsEndpoint:W.endpoint,ttsApikey:W.apiKey,ttsService:le,lipsyncModules:["en"],cameraView:u},T=R.useCallback(async()=>{if(!(!U.current||p.current))try{if(P(!0),G(null),p.current=new Te(U.current,I),p.current.controls&&(p.current.controls.enableRotate=!1,p.current.controls.enableZoom=!1,p.current.controls.enablePan=!1,p.current.controls.enableDamping=!1),x&&Object.keys(x).length>0&&(p.current.customAnimations=x),await p.current.showAvatar(v,D=>{if(D.lengthComputable){const J=Math.min(100,Math.round(D.loaded/D.total*100));d(J)}}),await new Promise(D=>{const J=()=>{p.current.lipsync&&Object.keys(p.current.lipsync).length>0?D():setTimeout(J,100)};J()}),p.current&&p.current.setShowFullAvatar)try{p.current.setShowFullAvatar(r)}catch(D){console.warn("Error setting full body mode on initialization:",D)}p.current&&p.current.controls&&(p.current.controls.enableRotate=!1,p.current.controls.enableZoom=!1,p.current.controls.enablePan=!1,p.current.controls.enableDamping=!1,p.current.controls.update()),P(!1),oe(!0),a(p.current);const N=()=>{document.visibilityState==="visible"?p.current?.start():p.current?.stop()};return document.addEventListener("visibilitychange",N),()=>{document.removeEventListener("visibilitychange",N)}}catch(k){console.error("Error initializing TalkingHead:",k),G(k.message||"Failed to initialize avatar"),P(!1),c(k)}},[O,t,e,n,i,s,o,r,l,h,u]);R.useEffect(()=>(T(),()=>{p.current&&(p.current.stop(),p.current.dispose(),p.current=null)}),[T]),R.useEffect(()=>{if(!U.current||!p.current)return;const k=new ResizeObserver(D=>{for(const J of D)p.current&&p.current.onResize&&p.current.onResize()});k.observe(U.current);const N=()=>{p.current&&p.current.onResize&&p.current.onResize()};return window.addEventListener("resize",N),()=>{k.disconnect(),window.removeEventListener("resize",N)}},[$]);const B=R.useCallback(async()=>{if(p.current&&p.current.audioCtx)try{(p.current.audioCtx.state==="suspended"||p.current.audioCtx.state==="interrupted")&&(await p.current.audioCtx.resume(),console.log("Audio context resumed"))}catch(k){console.warn("Failed to resume audio context:",k)}},[]),V=R.useCallback(async(k,N={})=>{if(p.current&&$)try{y.current&&(clearInterval(y.current),y.current=null),H.current={text:k,options:N},z.current={remainingText:null,originalText:null,options:null};const D=/[!\.\?\n\p{Extended_Pictographic}]/ug,J=k.split(D).map(j=>j.trim()).filter(j=>j.length>0);L.current=J,X.current=0,ce(!1),A.current=!1,await B();const de={...N,lipsyncLang:N.lipsyncLang||v.lipsyncLang||"en"};if(N.onSpeechEnd&&p.current){const j=p.current;let he=null,Ie=0;const Re=1200;let ye=!1;he=setInterval(()=>{if(Ie++,A.current)return;if(Ie>Re){if(he&&(clearInterval(he),he=null,y.current=null),!ye&&!A.current){ye=!0;try{N.onSpeechEnd()}catch(Fe){console.error("Error in onSpeechEnd callback (timeout):",Fe)}}return}const me=!j.speechQueue||j.speechQueue.length===0,Ae=!j.audioPlaylist||j.audioPlaylist.length===0;j&&j.isSpeaking===!1&&me&&Ae&&j.isAudioPlaying===!1&&!ye&&!A.current&&setTimeout(()=>{if(j&&!A.current&&j.isSpeaking===!1&&(!j.speechQueue||j.speechQueue.length===0)&&(!j.audioPlaylist||j.audioPlaylist.length===0)&&j.isAudioPlaying===!1&&!ye&&!A.current){ye=!0,he&&(clearInterval(he),he=null,y.current=null);try{N.onSpeechEnd()}catch(Ve){console.error("Error in onSpeechEnd callback:",Ve)}}},100)},100),y.current=he}p.current.lipsync&&Object.keys(p.current.lipsync).length>0?(p.current.setSlowdownRate&&p.current.setSlowdownRate(1.05),p.current.speakText(k,de)):setTimeout(async()=>{await B(),p.current&&p.current.lipsync&&(p.current.setSlowdownRate&&p.current.setSlowdownRate(1.05),p.current.speakText(k,de))},100)}catch(D){console.error("Error speaking text:",D),G(D.message||"Failed to speak text")}},[$,B,v.lipsyncLang]),K=R.useCallback(()=>{p.current&&(p.current.stopSpeaking(),p.current.setSlowdownRate&&p.current.setSlowdownRate(1),H.current=null,ce(!1))},[]),Y=R.useCallback(()=>{if(p.current&&p.current.pauseSpeaking){const k=p.current;if(k.isSpeaking||k.audioPlaylist&&k.audioPlaylist.length>0||k.speechQueue&&k.speechQueue.length>0){y.current&&(clearInterval(y.current),y.current=null);let D="";if(H.current&&L.current.length>0){const J=L.current.length,de=k.speechQueue?k.speechQueue.filter(Re=>Re&&Re.text&&Array.isArray(Re.text)&&Re.text.length>0).length:0,j=k.audioPlaylist&&k.audioPlaylist.length>0,he=de+(j?1:0),Ie=J-he;if(he>0&&Ie<J&&(D=L.current.slice(Ie).join(". ").trim(),!D&&de>0&&k.speechQueue)){const ye=k.speechQueue.filter(me=>me&&me.text&&Array.isArray(me.text)&&me.text.length>0).map(me=>me.text.map(Ae=>Ae.word||"").filter(Ae=>Ae.length>0).join(" ")).filter(me=>me.length>0).join(" ");ye&&ye.trim()&&(D=ye.trim())}}H.current&&(z.current={remainingText:D||null,originalText:H.current.text,options:H.current.options}),k.speechQueue&&(k.speechQueue.length=0),p.current.pauseSpeaking(),A.current=!0,ce(!0)}}},[]),_=R.useCallback(async()=>{if(!p.current||!se)return;let k="",N={};if(z.current&&z.current.remainingText)k=z.current.remainingText,N=z.current.options||{},z.current={remainingText:null,originalText:null,options:null};else if(H.current&&H.current.text)k=H.current.text,N=H.current.options||{};else{console.warn("Resume called but no paused speech found"),ce(!1),A.current=!1;return}ce(!1),A.current=!1,await B();const D={...N,lipsyncLang:N.lipsyncLang||v.lipsyncLang||"en"};try{await V(k,D)}catch(J){console.error("Error resuming speech:",J),ce(!1),A.current=!1}},[B,se,V,v]),ve=R.useCallback(k=>{p.current&&p.current.setMood(k)},[]),ke=R.useCallback(k=>{p.current&&p.current.setSlowdownRate&&p.current.setSlowdownRate(k)},[]),E=R.useCallback((k,N=!1)=>{if(p.current&&p.current.playAnimation){if(x&&x[k]&&(k=x[k]),p.current.setShowFullAvatar)try{p.current.setShowFullAvatar(F.current)}catch(J){console.warn("Error setting full body mode:",J)}if(k.includes("."))try{p.current.playAnimation(k,null,10,0,.01,N)}catch(J){console.warn(`Failed to play ${k}:`,J);try{p.current.setBodyMovement("idle")}catch(de){console.warn("Fallback animation also failed:",de)}}else{const J=[".fbx",".glb",".gltf"];let de=!1;for(const j of J)try{p.current.playAnimation(k+j,null,10,0,.01,N),de=!0;break}catch{}if(!de){console.warn("Animation not found:",k);try{p.current.setBodyMovement("idle")}catch(j){console.warn("Fallback animation also failed:",j)}}}}},[x]),te=R.useCallback(()=>{p.current&&p.current.onResize&&p.current.onResize()},[]);return R.useImperativeHandle(S,()=>({speakText:V,stopSpeaking:K,pauseSpeaking:Y,resumeSpeaking:_,resumeAudioContext:B,setMood:ve,setTimingAdjustment:ke,playAnimation:E,isReady:$,isPaused:se,talkingHead:p.current,handleResize:te,setBodyMovement:k=>{if(p.current&&p.current.setShowFullAvatar&&p.current.setBodyMovement)try{p.current.setShowFullAvatar(F.current),p.current.setBodyMovement(k)}catch(N){console.warn("Error setting body movement:",N)}},setMovementIntensity:k=>p.current?.setMovementIntensity(k),playRandomDance:()=>{if(p.current&&p.current.setShowFullAvatar&&p.current.playRandomDance)try{p.current.setShowFullAvatar(F.current),p.current.playRandomDance()}catch(k){console.warn("Error playing random dance:",k)}},playReaction:k=>{if(p.current&&p.current.setShowFullAvatar&&p.current.playReaction)try{p.current.setShowFullAvatar(F.current),p.current.playReaction(k)}catch(N){console.warn("Error playing reaction:",N)}},playCelebration:()=>{if(p.current&&p.current.setShowFullAvatar&&p.current.playCelebration)try{p.current.setShowFullAvatar(F.current),p.current.playCelebration()}catch(k){console.warn("Error playing celebration:",k)}},setShowFullAvatar:k=>{if(p.current&&p.current.setShowFullAvatar)try{F.current=k,p.current.setShowFullAvatar(k)}catch(N){console.warn("Error setting showFullAvatar:",N)}},lockAvatarPosition:()=>{if(p.current&&p.current.lockAvatarPosition)try{p.current.lockAvatarPosition()}catch(k){console.warn("Error locking avatar position:",k)}},unlockAvatarPosition:()=>{if(p.current&&p.current.unlockAvatarPosition)try{p.current.unlockAvatarPosition()}catch(k){console.warn("Error unlocking avatar position:",k)}}})),re.jsxs("div",{className:`talking-head-avatar ${g}`,style:{width:"100%",height:"100%",position:"relative",...b},children:[re.jsx("div",{ref:U,className:"talking-head-viewer",style:{width:"100%",height:"100%",minHeight:"400px"}}),w&&re.jsx("div",{className:"loading-overlay",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"white",fontSize:"18px",zIndex:10},children:"Loading avatar..."}),Q&&re.jsx("div",{className:"error-overlay",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"#ff6b6b",fontSize:"16px",textAlign:"center",zIndex:10,padding:"20px",borderRadius:"8px"},children:Q})]})});Me.displayName="TalkingHeadAvatar";const De=R.forwardRef(({text:O="Hello! I'm a talking avatar. How are you today?",onLoading:t=()=>{},onError:e=()=>{},onReady:n=()=>{},className:i="",style:s={},avatarConfig:o={}},l)=>{const h=R.useRef(null),r=R.useRef(null),[u,a]=R.useState(!0),[d,c]=R.useState(null),[g,b]=R.useState(!1),x=Le(),S=o.ttsService||x.service,U=S==="browser"?{endpoint:"",apiKey:null,defaultVoice:"Google US English"}:{...x,apiKey:o.ttsApiKey!==void 0&&o.ttsApiKey!==null?o.ttsApiKey:x.apiKey,endpoint:S==="elevenlabs"&&o.ttsApiKey?"https://api.elevenlabs.io/v1/text-to-speech":x.endpoint},p={url:"/avatars/brunette.glb",body:"F",avatarMood:"neutral",ttsLang:S==="browser"?"en-US":"en",ttsVoice:o.ttsVoice||U.defaultVoice,lipsyncLang:"en",showFullAvatar:!0,bodyMovement:"idle",movementIntensity:.5,...o},F={ttsEndpoint:U.endpoint,ttsApikey:U.apiKey,ttsService:S,lipsyncModules:["en"],cameraView:"upper"},H=R.useCallback(async()=>{if(!(!h.current||r.current))try{if(a(!0),c(null),r.current=new Te(h.current,F),await r.current.showAvatar(p,Q=>{if(Q.lengthComputable){const G=Math.min(100,Math.round(Q.loaded/Q.total*100));t(G)}}),r.current.morphs&&r.current.morphs.length>0){const Q=r.current.morphs[0].morphTargetDictionary;console.log("Available morph targets:",Object.keys(Q));const G=Object.keys(Q).filter($=>$.startsWith("viseme_"));console.log("Viseme morph targets found:",G),G.length===0&&(console.warn("No viseme morph targets found! Lip-sync will not work properly."),console.log("Expected viseme targets: viseme_aa, viseme_E, viseme_I, viseme_O, viseme_U, viseme_PP, viseme_SS, viseme_TH, viseme_DD, viseme_FF, viseme_kk, viseme_nn, viseme_RR, viseme_CH, viseme_sil"))}if(await new Promise(Q=>{const G=()=>{r.current.lipsync&&Object.keys(r.current.lipsync).length>0?(console.log("Lip-sync modules loaded:",Object.keys(r.current.lipsync)),Q()):(console.log("Waiting for lip-sync modules to load..."),setTimeout(G,100))};G()}),r.current&&r.current.setShowFullAvatar)try{r.current.setShowFullAvatar(!0),console.log("Avatar initialized in full body mode")}catch(Q){console.warn("Error setting full body mode on initialization:",Q)}a(!1),b(!0),n(r.current);const P=()=>{document.visibilityState==="visible"?r.current?.start():r.current?.stop()};return document.addEventListener("visibilitychange",P),()=>{document.removeEventListener("visibilitychange",P)}}catch(w){console.error("Error initializing TalkingHead:",w),c(w.message||"Failed to initialize avatar"),a(!1),e(w)}},[]);R.useEffect(()=>(H(),()=>{r.current&&(r.current.stop(),r.current.dispose(),r.current=null)}),[H]);const y=R.useCallback(w=>{if(r.current&&g)try{console.log("Speaking text:",w),console.log("Avatar config:",p),console.log("TalkingHead instance:",r.current),r.current.lipsync&&Object.keys(r.current.lipsync).length>0?(console.log("Lip-sync modules loaded:",Object.keys(r.current.lipsync)),r.current.setSlowdownRate&&(r.current.setSlowdownRate(1.05),console.log("Applied timing adjustment for better lip-sync")),r.current.speakText(w)):(console.warn("Lip-sync modules not ready, waiting..."),setTimeout(()=>{r.current&&r.current.lipsync?(console.log("Lip-sync now ready, speaking..."),r.current.setSlowdownRate&&(r.current.setSlowdownRate(1.05),console.log("Applied timing adjustment for better lip-sync")),r.current.speakText(w)):console.error("Lip-sync still not ready after waiting")},500))}catch(P){console.error("Error speaking text:",P),c(P.message||"Failed to speak text")}else console.warn("Avatar not ready for speaking. isReady:",g,"talkingHeadRef:",!!r.current)},[g,p]),A=R.useCallback(()=>{r.current&&(r.current.stopSpeaking(),r.current.setSlowdownRate&&(r.current.setSlowdownRate(1),console.log("Reset timing to normal")))},[]),z=R.useCallback(w=>{r.current&&r.current.setMood(w)},[]),L=R.useCallback(w=>{r.current&&r.current.setSlowdownRate&&(r.current.setSlowdownRate(w),console.log("Timing adjustment set to:",w))},[]),X=R.useCallback((w,P=!1)=>{if(r.current&&r.current.playAnimation){if(r.current.setShowFullAvatar)try{r.current.setShowFullAvatar(!0)}catch(G){console.warn("Error setting full body mode:",G)}if(w.includes("."))try{r.current.playAnimation(w,null,10,0,.01,P),console.log("Playing animation:",w)}catch(G){console.log(`Failed to play ${w}:`,G);try{r.current.setBodyMovement("idle"),console.log("Fallback to idle animation")}catch($){console.warn("Fallback animation also failed:",$)}}else{const G=[".fbx",".glb",".gltf"];let $=!1;for(const oe of G)try{r.current.playAnimation(w+oe,null,10,0,.01,P),console.log("Playing animation:",w+oe),$=!0;break}catch{console.log(`Failed to play ${w}${oe}, trying next format...`)}if(!$){console.warn("Animation system not available or animation not found:",w);try{r.current.setBodyMovement("idle"),console.log("Fallback to idle animation")}catch(oe){console.warn("Fallback animation also failed:",oe)}}}}else console.warn("Animation system not available or animation not found:",w)},[]);return R.useImperativeHandle(l,()=>({speakText:y,stopSpeaking:A,setMood:z,setTimingAdjustment:L,playAnimation:X,isReady:g,talkingHead:r.current,setBodyMovement:w=>{if(r.current&&r.current.setShowFullAvatar&&r.current.setBodyMovement)try{r.current.setShowFullAvatar(!0),r.current.setBodyMovement(w),console.log("Body movement set with full body mode:",w)}catch(P){console.warn("Error setting body movement:",P)}},setMovementIntensity:w=>r.current?.setMovementIntensity(w),playRandomDance:()=>{if(r.current&&r.current.setShowFullAvatar&&r.current.playRandomDance)try{r.current.setShowFullAvatar(!0),r.current.playRandomDance(),console.log("Random dance played with full body mode")}catch(w){console.warn("Error playing random dance:",w)}},playReaction:w=>{if(r.current&&r.current.setShowFullAvatar&&r.current.playReaction)try{r.current.setShowFullAvatar(!0),r.current.playReaction(w),console.log("Reaction played with full body mode:",w)}catch(P){console.warn("Error playing reaction:",P)}},playCelebration:()=>{if(r.current&&r.current.setShowFullAvatar&&r.current.playCelebration)try{r.current.setShowFullAvatar(!0),r.current.playCelebration(),console.log("Celebration played with full body mode")}catch(w){console.warn("Error playing celebration:",w)}},setShowFullAvatar:w=>{if(r.current&&r.current.setShowFullAvatar)try{r.current.setShowFullAvatar(w),console.log("Show full avatar set to:",w)}catch(P){console.warn("Error setting showFullAvatar:",P)}},lockAvatarPosition:()=>{if(r.current&&r.current.lockAvatarPosition)try{r.current.lockAvatarPosition()}catch(w){console.warn("Error locking avatar position:",w)}},unlockAvatarPosition:()=>{if(r.current&&r.current.unlockAvatarPosition)try{r.current.unlockAvatarPosition()}catch(w){console.warn("Error unlocking avatar position:",w)}}})),re.jsxs("div",{className:`talking-head-container ${i}`,style:s,children:[re.jsx("div",{ref:h,className:"talking-head-viewer",style:{width:"100%",height:"100%",minHeight:"400px"}}),u&&re.jsx("div",{className:"loading-overlay",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"white",fontSize:"18px",zIndex:10},children:"Loading avatar..."}),d&&re.jsx("div",{className:"error-overlay",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"#ff6b6b",fontSize:"16px",textAlign:"center",zIndex:10,padding:"20px",borderRadius:"8px"},children:d})]})});De.displayName="TalkingHeadComponent";const Ue=R.forwardRef(({text:O=null,avatarUrl:t="/avatars/brunette.glb",avatarBody:e="F",mood:n="neutral",ttsLang:i="en",ttsService:s=null,ttsVoice:o=null,ttsApiKey:l=null,bodyMovement:h="idle",movementIntensity:r=.5,showFullAvatar:u=!1,cameraView:a="upper",onReady:d=()=>{},onLoading:c=()=>{},onError:g=()=>{},onSpeechEnd:b=()=>{},className:x="",style:S={},animations:U={},autoSpeak:p=!1},F)=>{const H=R.useRef(null),y=R.useRef(null),A=R.useRef(u),z=R.useRef(null),L=R.useRef(null),X=R.useRef(!1),w=R.useRef({remainingText:null,originalText:null,options:null}),P=R.useRef([]),[Q,G]=R.useState(!0),[$,oe]=R.useState(null),[se,ce]=R.useState(!1),[ee,le]=R.useState(!1);R.useEffect(()=>{X.current=ee},[ee]),R.useEffect(()=>{A.current=u},[u]);const W=Le(),v=s||W.service;let I;v==="browser"?I={service:"browser",endpoint:"",apiKey:null,defaultVoice:"Google US English"}:v==="elevenlabs"?I={service:"elevenlabs",endpoint:"https://api.elevenlabs.io/v1/text-to-speech",apiKey:l||W.apiKey,defaultVoice:o||W.defaultVoice||be.defaultVoice,voices:W.voices||be.voices}:v==="deepgram"?I={service:"deepgram",endpoint:"https://api.deepgram.com/v1/speak",apiKey:l||W.apiKey,defaultVoice:o||W.defaultVoice||ze.defaultVoice,voices:W.voices||ze.voices}:I={...W,apiKey:l!==null?l:W.apiKey};const T={url:t,body:e,avatarMood:n,ttsLang:v==="browser"?"en-US":i,ttsVoice:o||I.defaultVoice,lipsyncLang:"en",showFullAvatar:u,bodyMovement:h,movementIntensity:r},B={ttsEndpoint:I.endpoint,ttsApikey:I.apiKey,ttsService:v,lipsyncModules:["en"],cameraView:a},V=R.useCallback(async()=>{if(!(!H.current||y.current))try{G(!0),oe(null),y.current=new Te(H.current,B),console.log("Avatar config being passed:",{url:T.url,body:T.body,avatarMood:T.avatarMood}),await y.current.showAvatar(T,te=>{if(te.lengthComputable){const k=Math.min(100,Math.round(te.loaded/te.total*100));c(k)}}),y.current?.avatar&&console.log("Avatar body after initialization:",y.current.avatar.body),G(!1),ce(!0),d(y.current);const E=()=>{document.visibilityState==="visible"?y.current?.start():y.current?.stop()};return document.addEventListener("visibilitychange",E),()=>{document.removeEventListener("visibilitychange",E)}}catch(E){console.error("Error initializing TalkingHead:",E),oe(E.message||"Failed to initialize avatar"),G(!1),g(E)}},[]);R.useEffect(()=>(V(),()=>{y.current&&(y.current.stop(),y.current.dispose(),y.current=null)}),[V]);const K=R.useCallback(async()=>{if(y.current)try{const E=y.current.audioCtx||y.current.audioContext;E&&(E.state==="suspended"||E.state==="interrupted")&&(await E.resume(),console.log("Audio context resumed"))}catch(E){console.warn("Failed to resume audio context:",E)}},[]),Y=R.useCallback(async(E,te={})=>{if(!y.current||!se){console.warn("Avatar not ready for speaking");return}if(!E||E.trim()===""){console.warn("No text provided to speak");return}await K(),w.current={remainingText:null,originalText:null,options:null},P.current=[],z.current={text:E,options:te},L.current&&(clearInterval(L.current),L.current=null),le(!1),X.current=!1;const k=E.split(/[.!?]+/).filter(D=>D.trim().length>0);P.current=k;const N={lipsyncLang:te.lipsyncLang||"en",onSpeechEnd:()=>{L.current&&(clearInterval(L.current),L.current=null),te.onSpeechEnd&&te.onSpeechEnd(),b()}};try{y.current.speakText(E,N)}catch(D){console.error("Error speaking text:",D),oe(D.message||"Failed to speak text")}},[se,b,K]);R.useEffect(()=>{se&&O&&p&&y.current&&Y(O)},[se,O,p,Y]);const _=R.useCallback(()=>{if(y.current)try{const E=y.current.isSpeaking||!1,te=y.current.audioPlaylist||[],k=y.current.speechQueue||[];if(E||te.length>0||k.length>0){L.current&&(clearInterval(L.current),L.current=null);let N="";k.length>0&&(N=k.map(D=>D.text&&Array.isArray(D.text)?D.text.map(J=>J.word).join(" "):D.text||"").join(" ")),w.current={remainingText:N||null,originalText:z.current?.text||null,options:z.current?.options||null},y.current.speechQueue.length=0,y.current.pauseSpeaking(),le(!0),X.current=!0}}catch(E){console.warn("Error pausing speech:",E)}},[]),ve=R.useCallback(async()=>{if(!(!y.current||!ee))try{await K(),le(!1),X.current=!1;const E=w.current?.remainingText,te=w.current?.originalText||z.current?.text,k=w.current?.options||z.current?.options||{},N=E||te;N&&Y(N,k)}catch(E){console.warn("Error resuming speech:",E),le(!1),X.current=!1}},[ee,Y,K]),ke=R.useCallback(()=>{y.current&&(y.current.stopSpeaking(),L.current&&(clearInterval(L.current),L.current=null),le(!1),X.current=!1)},[]);return R.useImperativeHandle(F,()=>({speakText:Y,pauseSpeaking:_,resumeSpeaking:ve,stopSpeaking:ke,resumeAudioContext:K,isPaused:()=>ee,setMood:E=>y.current?.setMood(E),setBodyMovement:E=>{y.current&&y.current.setBodyMovement(E)},playAnimation:(E,te=!1)=>{y.current&&y.current.playAnimation&&y.current.playAnimation(E,null,10,0,.01,te)},playReaction:E=>y.current?.playReaction(E),playCelebration:()=>y.current?.playCelebration(),setShowFullAvatar:E=>{y.current&&(A.current=E,y.current.setShowFullAvatar(E))},isReady:se,talkingHead:y.current})),re.jsxs("div",{className:`simple-talking-avatar-container ${x}`,style:S,children:[re.jsx("div",{ref:H,className:"talking-head-viewer",style:{width:"100%",height:"100%",minHeight:"400px"}}),Q&&re.jsx("div",{className:"loading-overlay",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"white",fontSize:"18px",zIndex:10},children:"Loading avatar..."}),$&&re.jsx("div",{className:"error-overlay",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"#ff6b6b",fontSize:"16px",textAlign:"center",zIndex:10,padding:"20px",borderRadius:"8px"},children:$})]})});Ue.displayName="SimpleTalkingAvatar";const We=R.forwardRef(({curriculumData:O=null,avatarConfig:t={},animations:e={},onLessonStart:n=()=>{},onLessonComplete:i=()=>{},onQuestionAnswer:s=()=>{},onCurriculumComplete:o=()=>{},onCustomAction:l=()=>{},autoStart:h=!1},r)=>{const u=R.useRef(null),a=R.useRef({currentModuleIndex:0,currentLessonIndex:0,currentQuestionIndex:0,isTeaching:!1,isQuestionMode:!1,lessonCompleted:!1,curriculumCompleted:!1,score:0,totalQuestions:0}),d=R.useRef({onLessonStart:n,onLessonComplete:i,onQuestionAnswer:s,onCurriculumComplete:o,onCustomAction:l}),c=R.useRef(null),g=R.useRef(null),b=R.useRef(null),x=R.useRef(null),S=R.useRef(null),U=R.useRef(null),p=R.useRef(null),F=R.useRef(O?.curriculum||{title:"Default Curriculum",description:"No curriculum data provided",language:"en",modules:[]}),H=R.useRef({avatarUrl:t.avatarUrl||"/avatars/brunette.glb",avatarBody:t.avatarBody||"F",mood:t.mood||"happy",ttsLang:t.ttsLang||"en",ttsService:t.ttsService||null,ttsVoice:t.ttsVoice||null,ttsApiKey:t.ttsApiKey||null,bodyMovement:t.bodyMovement||"gesturing",movementIntensity:t.movementIntensity||.7,showFullAvatar:t.showFullAvatar!==void 0?t.showFullAvatar:!1,animations:e,lipsyncLang:"en"});R.useEffect(()=>{d.current={onLessonStart:n,onLessonComplete:i,onQuestionAnswer:s,onCurriculumComplete:o,onCustomAction:l}},[n,i,s,o,l]),R.useEffect(()=>{F.current=O?.curriculum||{title:"Default Curriculum",description:"No curriculum data provided",language:"en",modules:[]},H.current={avatarUrl:t.avatarUrl||"/avatars/brunette.glb",avatarBody:t.avatarBody||"F",mood:t.mood||"happy",ttsLang:t.ttsLang||"en",ttsService:t.ttsService||null,ttsVoice:t.ttsVoice||null,ttsApiKey:t.ttsApiKey||null,bodyMovement:t.bodyMovement||"gesturing",movementIntensity:t.movementIntensity||.7,showFullAvatar:t.showFullAvatar!==void 0?t.showFullAvatar:!1,animations:e,lipsyncLang:"en"}},[O,t,e]);const y=R.useCallback(()=>(F.current||{modules:[]}).modules[a.current.currentModuleIndex]?.lessons[a.current.currentLessonIndex],[]),A=R.useCallback(()=>y()?.questions[a.current.currentQuestionIndex],[y]),z=R.useCallback((v,I)=>I.type==="multiple_choice"||I.type==="true_false"?v===I.answer:I.type==="code_test"&&typeof v=="object"&&v!==null?v.passed===!0:!1,[]),L=R.useCallback(()=>{a.current.lessonCompleted=!0,a.current.isQuestionMode=!1;const v=a.current.totalQuestions>0?Math.round(a.current.score/a.current.totalQuestions*100):100;let I="Congratulations! You've completed this lesson";if(a.current.totalQuestions>0?I+=` You got ${a.current.score} correct out of ${a.current.totalQuestions} question${a.current.totalQuestions===1?"":"s"}, achieving a score of ${v} percent. `:I+="! ",v>=80?I+="Excellent work! You have a great understanding of this topic.":v>=60?I+="Good job! You understand most of the concepts.":I+="Keep practicing! You're making progress.",d.current.onLessonComplete({moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,score:a.current.score,totalQuestions:a.current.totalQuestions,percentage:v}),d.current.onCustomAction({type:"lessonComplete",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,score:a.current.score,totalQuestions:a.current.totalQuestions,percentage:v}),u.current){if(u.current.setMood("happy"),e.lessonComplete)try{u.current.playAnimation(e.lessonComplete,!0)}catch{u.current.playCelebration()}const T=F.current||{modules:[]},B=T.modules[a.current.currentModuleIndex],V=a.current.currentLessonIndex<(B?.lessons?.length||0)-1,K=a.current.currentModuleIndex<(T.modules?.length||0)-1,Y=V||K,_=H.current||{lipsyncLang:"en"};u.current.speakText(I,{lipsyncLang:_.lipsyncLang,onSpeechEnd:()=>{d.current.onCustomAction({type:"lessonCompleteFeedbackDone",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,score:a.current.score,totalQuestions:a.current.totalQuestions,percentage:v,hasNextLesson:Y})}})}},[e.lessonComplete]),X=R.useCallback(()=>{a.current.curriculumCompleted=!0;const v=F.current||{modules:[]};if(d.current.onCurriculumComplete({modules:v.modules.length,totalLessons:v.modules.reduce((I,T)=>I+T.lessons.length,0)}),u.current){if(u.current.setMood("celebrating"),e.curriculumComplete)try{u.current.playAnimation(e.curriculumComplete,!0)}catch{u.current.playCelebration()}const I=H.current||{lipsyncLang:"en"};u.current.speakText("Amazing! You've completed the entire curriculum! You're now ready to move on to more advanced topics. Well done!",{lipsyncLang:I.lipsyncLang})}},[e.curriculumComplete]),w=R.useCallback(()=>{const v=y();a.current.isQuestionMode=!0,a.current.currentQuestionIndex=0,a.current.totalQuestions=v?.questions?.length||0,a.current.score=0;const I=A();I&&d.current.onCustomAction({type:"questionStart",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,questionIndex:a.current.currentQuestionIndex,totalQuestions:a.current.totalQuestions,question:I,score:a.current.score});const T=()=>{if(!u.current||!I)return;if(u.current.setMood("happy"),e.questionStart)try{u.current.playAnimation(e.questionStart,!0)}catch(V){console.warn("Failed to play questionStart animation:",V)}const B=H.current||{lipsyncLang:"en"};I.type==="code_test"?u.current.speakText(`Let's test your coding skills! Here's your first challenge: ${I.question}`,{lipsyncLang:B.lipsyncLang}):I.type==="multiple_choice"?u.current.speakText(`Now let me ask you some questions. Here's the first one: ${I.question}`,{lipsyncLang:B.lipsyncLang}):I.type==="true_false"?u.current.speakText(`Let's start with some true or false questions. First question: ${I.question}`,{lipsyncLang:B.lipsyncLang}):u.current.speakText(`Now let me ask you some questions. Here's the first one: ${I.question}`,{lipsyncLang:B.lipsyncLang})};if(u.current&&u.current.isReady&&I)T();else if(u.current&&u.current.isReady){const B=H.current||{lipsyncLang:"en"};u.current.speakText("Now let me ask you some questions to test your understanding.",{lipsyncLang:B.lipsyncLang})}else{const B=setInterval(()=>{u.current&&u.current.isReady&&(clearInterval(B),I&&T())},100);setTimeout(()=>{clearInterval(B)},5e3)}},[e.questionStart,y,A]),P=R.useCallback(()=>{const v=y();if(a.current.currentQuestionIndex<(v?.questions?.length||0)-1){u.current&&u.current.stopSpeaking&&u.current.stopSpeaking(),a.current.currentQuestionIndex+=1;const I=A();I&&d.current.onCustomAction({type:"nextQuestion",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,questionIndex:a.current.currentQuestionIndex,totalQuestions:a.current.totalQuestions,question:I,score:a.current.score});const T=()=>{if(!u.current||!I)return;if(u.current.setMood("happy"),u.current.setBodyMovement("idle"),e.nextQuestion)try{u.current.playAnimation(e.nextQuestion,!0)}catch(_){console.warn("Failed to play nextQuestion animation:",_)}const B=H.current||{lipsyncLang:"en"},K=y()?.questions?.length||0,Y=a.current.currentQuestionIndex>=K-1;if(I.type==="code_test"){const _=Y?`Great! Here's your final coding challenge: ${I.question}`:`Great! Now let's move on to your next coding challenge: ${I.question}`;u.current.speakText(_,{lipsyncLang:B.lipsyncLang})}else if(I.type==="multiple_choice"){const _=Y?`Alright! Here's your final question: ${I.question}`:`Alright! Here's your next question: ${I.question}`;u.current.speakText(_,{lipsyncLang:B.lipsyncLang})}else if(I.type==="true_false"){const _=Y?`Now let's try this final one: ${I.question}`:`Now let's try this one: ${I.question}`;u.current.speakText(_,{lipsyncLang:B.lipsyncLang})}else{const _=Y?`Here's your final question: ${I.question}`:`Here's the next question: ${I.question}`;u.current.speakText(_,{lipsyncLang:B.lipsyncLang})}};if(u.current&&u.current.isReady&&I)T();else if(I){const B=setInterval(()=>{u.current&&u.current.isReady&&(clearInterval(B),T())},100);setTimeout(()=>{clearInterval(B)},5e3)}}else d.current.onCustomAction({type:"allQuestionsComplete",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,totalQuestions:a.current.totalQuestions,score:a.current.score})},[e.nextQuestion,y,A]),Q=R.useCallback(()=>{const v=F.current||{modules:[]},I=v.modules[a.current.currentModuleIndex];if(a.current.currentLessonIndex<(I?.lessons?.length||0)-1){a.current.currentLessonIndex+=1,a.current.currentQuestionIndex=0,a.current.lessonCompleted=!1,a.current.isQuestionMode=!1,a.current.isTeaching=!1,a.current.score=0,a.current.totalQuestions=0;const B=v.modules[a.current.currentModuleIndex],V=a.current.currentLessonIndex<(B?.lessons?.length||0)-1,K=a.current.currentModuleIndex<(v.modules?.length||0)-1,Y=V||K;d.current.onCustomAction({type:"lessonStart",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,hasNextLesson:Y}),d.current.onLessonStart({moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,lesson:y()}),u.current&&(u.current.setMood("happy"),u.current.setBodyMovement("idle"))}else if(a.current.currentModuleIndex<(v.modules?.length||0)-1){a.current.currentModuleIndex+=1,a.current.currentLessonIndex=0,a.current.currentQuestionIndex=0,a.current.lessonCompleted=!1,a.current.isQuestionMode=!1,a.current.isTeaching=!1,a.current.score=0,a.current.totalQuestions=0;const V=v.modules[a.current.currentModuleIndex],K=a.current.currentLessonIndex<(V?.lessons?.length||0)-1,Y=a.current.currentModuleIndex<(v.modules?.length||0)-1,_=K||Y;d.current.onCustomAction({type:"lessonStart",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,hasNextLesson:_}),d.current.onLessonStart({moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,lesson:y()}),u.current&&(u.current.setMood("happy"),u.current.setBodyMovement("idle"))}else S.current&&S.current()},[]),G=R.useCallback(()=>{const v=y();let I=null;if(v?.avatar_script&&v?.body){const T=v.avatar_script.trim(),B=v.body.trim(),V=T.match(/[.!?]$/)?" ":". ";I=`${T}${V}${B}`}else I=v?.avatar_script||v?.body||null;if(u.current&&u.current.isReady&&I){a.current.isTeaching=!0,a.current.isQuestionMode=!1,a.current.score=0,a.current.totalQuestions=0,u.current.setMood("happy");let T=!1;if(e.teaching)try{u.current.playAnimation(e.teaching,!0),T=!0}catch(V){console.warn("Failed to play teaching animation:",V)}T||u.current.setBodyMovement("gesturing");const B=H.current||{lipsyncLang:"en"};d.current.onLessonStart({moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,lesson:v}),d.current.onCustomAction({type:"teachingStart",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,lesson:v}),u.current.speakText(I,{lipsyncLang:B.lipsyncLang,onSpeechEnd:()=>{a.current.isTeaching=!1,d.current.onCustomAction({type:"teachingComplete",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,lesson:v,hasQuestions:v.questions&&v.questions.length>0}),v?.code_example&&d.current.onCustomAction({type:"codeExampleReady",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,lesson:v,codeExample:v.code_example})}})}},[e.teaching,y]),$=R.useCallback(v=>{const I=A(),T=z(v,I);if(T&&(a.current.score+=1),d.current.onQuestionAnswer({moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,questionIndex:a.current.currentQuestionIndex,answer:v,isCorrect:T,question:I}),u.current)if(T){if(u.current.setMood("happy"),e.correct)try{u.current.playReaction("happy")}catch{u.current.setBodyMovement("happy")}u.current.setBodyMovement("gesturing");const V=y()?.questions?.length||0;a.current.currentQuestionIndex>=V-1;const K=a.current.currentQuestionIndex<V-1;console.log("[CurriculumLearning] Answer feedback - questionIndex:",a.current.currentQuestionIndex,"totalQuestions:",V,"hasNextQuestion:",K);const Y=I.type==="code_test"?`Great job! Your code passed all the tests! ${I.explanation||""}`:`Excellent! That's correct! ${I.explanation||""}`,_=H.current||{lipsyncLang:"en"};u.current.speakText(Y,{lipsyncLang:_.lipsyncLang,onSpeechEnd:()=>{d.current.onCustomAction({type:"answerFeedbackComplete",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,questionIndex:a.current.currentQuestionIndex,isCorrect:!0,hasNextQuestion:K,score:a.current.score,totalQuestions:a.current.totalQuestions})}})}else{if(u.current.setMood("sad"),e.incorrect)try{u.current.playAnimation(e.incorrect,!0)}catch{u.current.setBodyMovement("idle")}u.current.setBodyMovement("gesturing");const V=y()?.questions?.length||0,K=a.current.currentQuestionIndex>=V-1,Y=a.current.currentQuestionIndex<V-1;console.log("[CurriculumLearning] Answer feedback (incorrect) - questionIndex:",a.current.currentQuestionIndex,"totalQuestions:",V,"hasNextQuestion:",Y);const _=I.type==="code_test"?`Your code didn't pass all the tests. ${I.explanation||"Try again!"}`:`Not quite right, but don't worry! ${I.explanation||""}${K?"":" Let's move on to the next question."}`,ve=H.current||{lipsyncLang:"en"};u.current.speakText(_,{lipsyncLang:ve.lipsyncLang,onSpeechEnd:()=>{d.current.onCustomAction({type:"answerFeedbackComplete",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,questionIndex:a.current.currentQuestionIndex,isCorrect:!1,hasNextQuestion:Y,score:a.current.score,totalQuestions:a.current.totalQuestions})}})}else{const V=y()?.questions?.length||0;d.current.onCustomAction({type:"answerFeedbackComplete",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,questionIndex:a.current.currentQuestionIndex,isCorrect:T,hasNextQuestion:a.current.currentQuestionIndex<V-1,score:a.current.score,totalQuestions:a.current.totalQuestions,avatarNotReady:!0})}},[e.correct,e.incorrect,A,y,z]),oe=R.useCallback(v=>{const I=A();if(!v||typeof v!="object"){console.error("Invalid code test result format. Expected object with {passed: boolean, ...}");return}if(I?.type!=="code_test"){console.warn("Current question is not a code test. Use handleAnswerSelect for other question types.");return}const T={passed:v.passed===!0,results:v.results||[],output:v.output||"",error:v.error||null,executionTime:v.executionTime||null,testCount:v.testCount||0,passedCount:v.passedCount||0,failedCount:v.failedCount||0};d.current.onCustomAction({type:"codeTestSubmitted",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,questionIndex:a.current.currentQuestionIndex,testResult:T,question:I}),p.current&&p.current(T)},[A,z]),se=R.useCallback(()=>{if(a.current.currentQuestionIndex>0){a.current.currentQuestionIndex-=1;const v=A();v&&d.current.onCustomAction({type:"questionStart",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,questionIndex:a.current.currentQuestionIndex,totalQuestions:a.current.totalQuestions,question:v,score:a.current.score});const I=()=>{if(!u.current||!v)return;u.current.setMood("happy"),u.current.setBodyMovement("idle");const T=H.current||{lipsyncLang:"en"};v.type==="code_test"?u.current.speakText(`Let's go back to this coding challenge: ${v.question}`,{lipsyncLang:T.lipsyncLang}):u.current.speakText(`Going back to: ${v.question}`,{lipsyncLang:T.lipsyncLang})};if(u.current&&u.current.isReady&&v)I();else if(v){const T=setInterval(()=>{u.current&&u.current.isReady&&(clearInterval(T),I())},100);setTimeout(()=>{clearInterval(T)},5e3)}}},[A]),ce=R.useCallback(()=>{const v=F.current||{modules:[]};if(v.modules[a.current.currentModuleIndex],a.current.currentLessonIndex>0)a.current.currentLessonIndex-=1,a.current.currentQuestionIndex=0,a.current.lessonCompleted=!1,a.current.isQuestionMode=!1,a.current.isTeaching=!1,a.current.score=0,a.current.totalQuestions=0,d.current.onCustomAction({type:"lessonStart",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex}),d.current.onLessonStart({moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,lesson:y()}),u.current&&(u.current.setMood("happy"),u.current.setBodyMovement("idle"));else if(a.current.currentModuleIndex>0){const B=v.modules[a.current.currentModuleIndex-1];a.current.currentModuleIndex-=1,a.current.currentLessonIndex=(B?.lessons?.length||1)-1,a.current.currentQuestionIndex=0,a.current.lessonCompleted=!1,a.current.isQuestionMode=!1,a.current.isTeaching=!1,a.current.score=0,a.current.totalQuestions=0,d.current.onCustomAction({type:"lessonStart",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex}),d.current.onLessonStart({moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,lesson:y()}),u.current&&(u.current.setMood("happy"),u.current.setBodyMovement("idle"))}},[y]),ee=R.useCallback(()=>{a.current.currentModuleIndex=0,a.current.currentLessonIndex=0,a.current.currentQuestionIndex=0,a.current.isTeaching=!1,a.current.isQuestionMode=!1,a.current.lessonCompleted=!1,a.current.curriculumCompleted=!1,a.current.score=0,a.current.totalQuestions=0},[]),le=R.useCallback(v=>{console.log("Avatar is ready!",v);const I=y(),T=I?.avatar_script||I?.body;h&&T&&setTimeout(()=>{c.current&&c.current()},10)},[h,y]);R.useLayoutEffect(()=>{c.current=G,g.current=Q,b.current=L,x.current=P,S.current=X,U.current=w,p.current=$}),R.useImperativeHandle(r,()=>({startTeaching:G,startQuestions:w,handleAnswerSelect:$,handleCodeTestResult:oe,nextQuestion:P,previousQuestion:se,nextLesson:Q,previousLesson:ce,completeLesson:L,completeCurriculum:X,resetCurriculum:ee,getState:()=>({...a.current}),getCurrentQuestion:()=>A(),getCurrentLesson:()=>y(),getAvatarRef:()=>u.current,speakText:async(v,I={})=>{await u.current?.resumeAudioContext?.();const T=H.current||{lipsyncLang:"en"};u.current?.speakText(v,{...I,lipsyncLang:I.lipsyncLang||T.lipsyncLang})},resumeAudioContext:async()=>{if(u.current?.resumeAudioContext)return await u.current.resumeAudioContext();const v=u.current?.talkingHead;if(v?.audioCtx){const I=v.audioCtx;if(I.state==="suspended"||I.state==="interrupted")try{await I.resume(),console.log("Audio context resumed via talkingHead")}catch(T){console.warn("Failed to resume audio context:",T)}}else console.warn("Audio context not available yet")},stopSpeaking:()=>u.current?.stopSpeaking(),pauseSpeaking:()=>u.current?.pauseSpeaking(),resumeSpeaking:async()=>await u.current?.resumeSpeaking(),isPaused:()=>u.current&&typeof u.current.isPaused<"u"?u.current.isPaused:!1,setMood:v=>u.current?.setMood(v),playAnimation:(v,I)=>u.current?.playAnimation(v,I),setBodyMovement:v=>u.current?.setBodyMovement(v),setMovementIntensity:v=>u.current?.setMovementIntensity(v),playRandomDance:()=>u.current?.playRandomDance(),playReaction:v=>u.current?.playReaction(v),playCelebration:()=>u.current?.playCelebration(),setShowFullAvatar:v=>u.current?.setShowFullAvatar(v),setTimingAdjustment:v=>u.current?.setTimingAdjustment(v),lockAvatarPosition:()=>u.current?.lockAvatarPosition(),unlockAvatarPosition:()=>u.current?.unlockAvatarPosition(),triggerCustomAction:(v,I)=>{d.current.onCustomAction({type:v,...I,state:{...a.current}})},handleResize:()=>u.current?.handleResize(),isAvatarReady:()=>u.current?.isReady||!1}),[G,w,$,oe,P,Q,L,X,ee,A,y]);const W=H.current||{avatarUrl:"/avatars/brunette.glb",avatarBody:"F",mood:"happy",ttsLang:"en",ttsService:null,ttsVoice:null,ttsApiKey:null,bodyMovement:"gesturing",movementIntensity:.7,showFullAvatar:!1,animations:e};return re.jsx("div",{style:{width:"100%",height:"100%"},children:re.jsx(Me,{ref:u,avatarUrl:W.avatarUrl,avatarBody:W.avatarBody,mood:W.mood,ttsLang:W.ttsLang,ttsService:W.ttsService,ttsVoice:W.ttsVoice,ttsApiKey:W.ttsApiKey,bodyMovement:W.bodyMovement,movementIntensity:W.movementIntensity,showFullAvatar:W.showFullAvatar,cameraView:"upper",animations:W.animations,onReady:le,onLoading:()=>{},onError:v=>{console.error("Avatar error:",v)}})})});We.displayName="CurriculumLearning";const Ee={dance:{name:"dance",type:"code-based",variations:["dancing","dancing2","dancing3"],loop:!0,duration:1e4,description:"Celebration dance animation with multiple variations"},happy:{name:"happy",type:"code-based",loop:!0,duration:5e3,description:"Happy, upbeat body movement"},surprised:{name:"surprised",type:"code-based",loop:!1,duration:3e3,description:"Surprised reaction with quick movements"},thinking:{name:"thinking",type:"code-based",loop:!0,duration:8e3,description:"Thoughtful, contemplative movement"},nodding:{name:"nodding",type:"code-based",loop:!1,duration:2e3,description:"Nodding agreement gesture"},shaking:{name:"shaking",type:"code-based",loop:!1,duration:2e3,description:"Shaking head disagreement gesture"},celebration:{name:"celebration",type:"code-based",loop:!1,duration:3e3,description:"Celebration animation for achievements"},energetic:{name:"energetic",type:"code-based",loop:!0,duration:6e3,description:"High-energy, enthusiastic movement"},swaying:{name:"swaying",type:"code-based",loop:!0,duration:8e3,description:"Gentle swaying motion"},bouncing:{name:"bouncing",type:"code-based",loop:!0,duration:4e3,description:"Bouncy, playful movement"},gesturing:{name:"gesturing",type:"code-based",loop:!0,duration:5e3,description:"Teaching gesture animation"},walking:{name:"walking",type:"code-based",loop:!0,duration:6e3,description:"Walking motion"},prancing:{name:"prancing",type:"code-based",loop:!0,duration:4e3,description:"Playful prancing movement"},excited:{name:"excited",type:"code-based",loop:!0,duration:5e3,description:"Excited, energetic movement"}},pt=O=>Ee[O]||null,gt=O=>Ee.hasOwnProperty(O);exports.CurriculumLearning=We;exports.SimpleTalkingAvatar=Ue;exports.TalkingHeadAvatar=Me;exports.TalkingHeadComponent=De;exports.animations=Ee;exports.getActiveTTSConfig=Le;exports.getAnimation=pt;exports.getVoiceOptions=mt;exports.hasAnimation=gt;
7
+ `,s=await fetch(this.opt.ttsEndpoint,{method:"POST",headers:{"Ocp-Apim-Subscription-Key":this.opt.ttsApikey,"Content-Type":"application/ssml+xml","X-Microsoft-OutputFormat":"audio-16khz-128kbitrate-mono-mp3"},body:i});if(!s.ok)throw new Error(`Azure TTS error: ${s.status} ${s.statusText}`);const o=await s.arrayBuffer(),l=await this.audioCtx.decodeAudioData(o);console.log("Analyzing audio for precise lip-sync...");const c=await this.audioAnalyzer.analyzeAudio(l,e);console.log("Azure TTS Audio Analysis:",{text:e,audioDuration:l.duration,visemeCount:c.visemes.length,wordCount:c.words.length,features:{onsets:c.features.onsets.length,boundaries:c.features.phonemeBoundaries.length}});const r=[];for(let a=0;a<c.visemes.length;a++){const d=c.visemes[a],h=d.startTime*1e3,g=d.duration*1e3,x=d.intensity;r.push({template:{name:"viseme"},ts:[h-Math.min(60,2*g/3),h+Math.min(25,g/2),h+g+Math.min(60,g/2)],vs:{["viseme_"+d.viseme]:[null,x,0]}})}const u=[...t.anim,...r];this.audioPlaylist.push({anim:u,audio:l}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio()}async synthesizeWithExternalTTS(t){let e="<speak>";t.text.forEach((o,l)=>{l>0&&(e+=" <mark name='"+o.mark+"'/>"),e+=o.word.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;").replace(new RegExp("^\\p{Dash_Punctuation}$","ug"),'<break time="750ms"/>')}),e+="</speak>";const n={method:"POST",headers:{"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify({input:{ssml:e},voice:{languageCode:t.lang||this.avatar.ttsLang||this.opt.ttsLang,name:t.voice||this.avatar.ttsVoice||this.opt.ttsVoice},audioConfig:{audioEncoding:this.ttsAudioEncoding,speakingRate:(t.rate||this.avatar.ttsRate||this.opt.ttsRate)+this.mood.speech.deltaRate,pitch:(t.pitch||this.avatar.ttsPitch||this.opt.ttsPitch)+this.mood.speech.deltaPitch,volumeGainDb:(t.volume||this.avatar.ttsVolume||this.opt.ttsVolume)+this.mood.speech.deltaVolume},enableTimePointing:[1]})};this.opt.jwtGet&&typeof this.opt.jwtGet=="function"&&(n.headers.Authorization="Bearer "+await this.opt.jwtGet());const i=await fetch(this.opt.ttsEndpoint+(this.opt.ttsApikey?"?key="+this.opt.ttsApikey:""),n),s=await i.json();if(i.status===200&&s&&s.audioContent){const o=this.b64ToArrayBuffer(s.audioContent),l=await this.audioCtx.decodeAudioData(o);this.speakWithHands();const c=[0];let r=0;t.text.forEach((d,h)=>{if(h>0){let g=c[c.length-1];s.timepoints[r]&&(g=s.timepoints[r].timeSeconds*1e3,s.timepoints[r].markName===""+d.mark&&r++),c.push(g)}});const u=[{mark:0,time:0}];c.forEach((d,h)=>{if(h>0){let g=d-c[h-1];u[h-1].duration=g,u.push({mark:h,time:d})}});let a=1e3*l.duration;a>this.opt.ttsTrimEnd&&(a=a-this.opt.ttsTrimEnd),u[u.length-1].duration=a-u[u.length-1].time,t.anim.forEach(d=>{const h=u[d.mark];if(h)for(let g=0;g<d.ts.length;g++)d.ts[g]=h.time+d.ts[g]*h.duration+this.opt.ttsTrimStart}),this.audioPlaylist.push({anim:t.anim,audio:l}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio()}else this.startSpeaking(!0)}async startSpeaking(t=!1){if(!(!this.armature||this.isSpeaking&&!t))if(this.stateName="speaking",this.isSpeaking=!0,this.speechQueue.length){let e=this.speechQueue.shift();if(e.emoji){this.lookAtCamera(500);let n=e.emoji.dt.reduce((i,s)=>i+s,0);this.animQueue.push(this.animFactory(e.emoji)),setTimeout(this.startSpeaking.bind(this),n,!0)}else if(e.break)setTimeout(this.startSpeaking.bind(this),e.break,!0);else if(e.audio)e.isRaw||(this.lookAtCamera(500),this.speakWithHands(),this.resetLips()),this.audioPlaylist.push({anim:e.anim,audio:e.audio,isRaw:e.isRaw}),this.onSubtitles=e.onSubtitles||null,e.mood&&this.setMood(e.mood),this.playAudio();else if(e.text){this.lookAtCamera(500);try{!this.opt.ttsEndpoint||this.opt.ttsEndpoint===""?await this.synthesizeWithBrowserTTS(e):this.opt.ttsService==="elevenlabs"?await this.synthesizeWithElevenLabsTTS(e):this.opt.ttsService==="deepgram"?await this.synthesizeWithDeepgramTTS(e):this.opt.ttsService==="azure"?await this.synthesizeWithAzureTTS(e):await this.synthesizeWithExternalTTS(e)}catch(n){console.error("Error:",n),this.startSpeaking(!0)}}else e.anim?(this.onSubtitles=e.onSubtitles||null,this.resetLips(),e.mood&&this.setMood(e.mood),e.anim.forEach((n,i)=>{for(let s=0;s<n.ts.length;s++)n.ts[s]=this.animClock+10*i;this.animQueue.push(n)}),setTimeout(this.startSpeaking.bind(this),10*e.anim.length,!0)):e.marker?(typeof e.marker=="function"&&e.marker(),this.startSpeaking(!0)):this.startSpeaking(!0)}else this.stateName="idle",this.isSpeaking=!1}pauseSpeaking(){try{this.audioSpeechSource.stop()}catch{}this.audioPlaylist.length=0,this.stateName="idle",this.isSpeaking=!1,this.isAudioPlaying=!1,this.animQueue=this.animQueue.filter(t=>t.template.name!=="viseme"&&t.template.name!=="subtitles"&&t.template.name!=="blendshapes"),this.armature&&(this.resetLips(),this.render())}stopSpeaking(){try{this.audioSpeechSource.stop()}catch{}this.audioPlaylist.length=0,this.speechQueue.length=0,this.animQueue=this.animQueue.filter(t=>t.template.name!=="viseme"&&t.template.name!=="subtitles"&&t.template.name!=="blendshapes"),this.stateName="idle",this.isSpeaking=!1,this.isAudioPlaying=!1,this.armature&&(this.resetLips(),this.render())}async streamStart(t={},e=null,n=null,i=null,s=null){if(this.stopSpeaking(),this.isStreaming=!0,t.waitForAudioChunks!==void 0&&(this.streamWaitForAudioChunks=t.waitForAudioChunks),this.streamWaitForAudioChunks||(this.streamAudioStartTime=this.animClock),this.streamLipsyncQueue=[],this.streamLipsyncType=t.lipsyncType||this.streamLipsyncType||"visemes",this.streamLipsyncLang=t.lipsyncLang||this.streamLipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang,this.onAudioStart=e,this.onAudioEnd=n,this.onMetrics=s,t.sampleRate!==void 0){const l=t.sampleRate;typeof l=="number"&&l>=8e3&&l<=96e3?l!==this.audioCtx.sampleRate&&this.initAudioGraph(l):console.warn("Invalid sampleRate provided. It must be a number between 8000 and 96000 Hz.")}if(t.gain!==void 0&&(this.audioStreamGainNode.gain.value=t.gain),!this.streamWorkletNode||!this.streamWorkletNode.port||this.streamWorkletNode.numberOfOutputs===0||this.streamWorkletNode.context!==this.audioCtx){if(this.streamWorkletNode)try{this.streamWorkletNode.disconnect(),this.streamWorkletNode=null}catch{}if(!this.workletLoaded)try{const l=this.audioCtx.audioWorklet.addModule(ht.href),c=new Promise((r,u)=>setTimeout(()=>u(new Error("Worklet loading timed out")),5e3));await Promise.race([l,c]),this.workletLoaded=!0}catch(l){throw console.error("Failed to load audio worklet:",l),new Error("Failed to initialize streaming speech")}this.streamWorkletNode=new AudioWorkletNode(this.audioCtx,"playback-worklet",{processorOptions:{sampleRate:this.audioCtx.sampleRate,metrics:t.metrics||{enabled:!1}}}),this.streamWorkletNode.connect(this.audioStreamGainNode),this.streamWorkletNode.connect(this.audioAnalyzerNode),this.streamWorkletNode.port.onmessage=l=>{if(l.data.type==="playback-started"&&(this.isSpeaking=!0,this.stateName="speaking",this.streamWaitForAudioChunks&&(this.streamAudioStartTime=this.animClock),this._processStreamLipsyncQueue(),this.speakWithHands(),this.onAudioStart))try{this.onAudioStart?.()}catch(c){console.error(c)}if(l.data.type==="playback-ended"&&(this._streamPause(),this.onAudioEnd))try{this.onAudioEnd()}catch{}if(this.onMetrics&&l.data.type==="metrics")try{this.onMetrics(l.data)}catch{}}}if(t.metrics)try{this.streamWorkletNode.port.postMessage({type:"config-metrics",data:t.metrics})}catch{}if(this.resetLips(),this.lookAtCamera(500),t.mood&&this.setMood(t.mood),this.onSubtitles=i||null,this.audioCtx.state==="suspended"||this.audioCtx.state==="interrupted"){const l=this.audioCtx.resume(),c=new Promise((r,u)=>setTimeout(()=>u("p2"),1e3));try{await Promise.race([l,c])}catch{console.warn("Can't play audio. Web Audio API suspended. This is often due to calling some speak method before the first user action, which is typically prevented by the browser.");return}}}streamNotifyEnd(){!this.isStreaming||!this.streamWorkletNode||this.streamWorkletNode.port.postMessage({type:"no-more-data"})}streamInterrupt(){if(!this.isStreaming)return;const t=this.isSpeaking;if(this.streamWorkletNode)try{this.streamWorkletNode.port.postMessage({type:"stop"})}catch{}if(this._streamPause(!0),t&&this.onAudioEnd)try{this.onAudioEnd()}catch{}}streamStop(){if(this.isStreaming){if(this.streamInterrupt(),this.streamWorkletNode){try{this.streamWorkletNode.disconnect()}catch{}this.streamWorkletNode=null}this.isStreaming=!1}}_streamPause(t=!1){this.isSpeaking=!1,this.stateName="idle",t&&(this.streamWaitForAudioChunks&&(this.streamAudioStartTime=null),this.streamLipsyncQueue=[],this.animQueue=this.animQueue.filter(e=>e.template.name!=="viseme"&&e.template.name!=="subtitles"&&e.template.name!=="blendshapes"),this.armature&&(this.resetLips(),this.render()))}_processStreamLipsyncQueue(){if(this.isStreaming)for(;this.streamLipsyncQueue.length>0;){const t=this.streamLipsyncQueue.shift();this._processLipsyncData(t,this.streamAudioStartTime)}}_processLipsyncData(t,e){if(this.isStreaming){if(t.visemes&&this.streamLipsyncType=="visemes")for(let n=0;n<t.visemes.length;n++){const i=t.visemes[n],s=e+t.vtimes[n],o=t.vdurations[n],l={template:{name:"viseme"},ts:[s-2*o/3,s+o/2,s+o+o/2],vs:{["viseme_"+i]:[null,i==="PP"||i==="FF"?.9:.6,0]}};this.animQueue.push(l)}if(t.words&&(this.onSubtitles||this.streamLipsyncType=="words"))for(let n=0;n<t.words.length;n++){const i=t.words[n],s=t.wtimes[n];let o=t.wdurations[n];if(i.length&&(this.onSubtitles&&this.animQueue.push({template:{name:"subtitles"},ts:[e+s],vs:{subtitles:[" "+i]}}),this.streamLipsyncType=="words")){const l=this.streamLipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang,c=this.lipsyncPreProcessText(i,l),r=this.lipsyncWordsToVisemes(c,l);if(r&&r.visemes&&r.visemes.length){const u=r.times[r.visemes.length-1]+r.durations[r.visemes.length-1],a=Math.min(o,Math.max(0,o-r.visemes.length*150));let d=.6+this.convertRange(a,[0,o],[0,.4]);if(o=Math.min(o,r.visemes.length*200),u>0)for(let h=0;h<r.visemes.length;h++){const g=e+s+r.times[h]/u*o,x=r.durations[h]/u*o;this.animQueue.push({template:{name:"viseme"},ts:[g-Math.min(60,2*x/3),g+Math.min(25,x/2),g+x+Math.min(60,x/2)],vs:{["viseme_"+r.visemes[h]]:[null,r.visemes[h]==="PP"||r.visemes[h]==="FF"?.9:d,0]}})}}}}if(t.anims&&this.streamLipsyncType=="blendshapes")for(let n=0;n<t.anims.length;n++){let i=t.anims[n];i.delay+=e;let s=this.animFactory(i,!1,1,1,!0);this.animQueue.push(s)}}}streamAudio(t){if(!(!this.isStreaming||!this.streamWorkletNode)){if(this.isSpeaking||(this.streamLipsyncQueue=[],this.streamAudioStartTime=null),this.isSpeaking=!0,this.stateName="speaking",t.audio!==void 0){const e={type:"audioData",data:null};if(t.audio instanceof ArrayBuffer)e.data=t.audio,this.streamWorkletNode.port.postMessage(e,[e.data]);else if(t.audio instanceof Int16Array||t.audio instanceof Uint8Array){const n=t.audio.buffer.slice(t.audio.byteOffset,t.audio.byteOffset+t.audio.byteLength);e.data=n,this.streamWorkletNode.port.postMessage(e,[e.data])}else if(t.audio instanceof Float32Array){const n=new Int16Array(t.audio.length);for(let i=0;i<t.audio.length;i++){let s=Math.max(-1,Math.min(1,t.audio[i]));n[i]=s<0?s*32768:s*32767}e.data=n.buffer,this.streamWorkletNode.port.postMessage(e,[e.data])}else console.error("r.audio is not a supported type. Must be ArrayBuffer, Int16Array, Uint8Array, or Float32Array:",t.audio)}if(t.visemes||t.anims||t.words){if(this.streamWaitForAudioChunks&&!this.streamAudioStartTime){this.streamLipsyncQueue.length>=200&&this.streamLipsyncQueue.shift(),this.streamLipsyncQueue.push(t);return}else!this.streamWaitForAudioChunks&&!this.streamAudioStartTime&&(this.streamAudioStartTime=this.animClock);this._processLipsyncData(t,this.streamAudioStartTime)}}}makeEyeContact(t){this.animQueue.push(this.animFactory({name:"eyecontact",dt:[0,t],vs:{eyeContact:[1]}}))}lookAhead(t){if(t){let e=(Math.random()-.5)/4,n=(Math.random()-.5)/4,i=this.animQueue.findIndex(o=>o.template.name==="lookat");i!==-1&&this.animQueue.splice(i,1);const s={name:"lookat",dt:[750,t],vs:{bodyRotateX:[e],bodyRotateY:[n],eyesRotateX:[-3*e+.1],eyesRotateY:[-5*n],browInnerUp:[[0,.7]],mouthLeft:[[0,.7]],mouthRight:[[0,.7]],eyeContact:[0],headMove:[0]}};this.animQueue.push(this.animFactory(s))}}lookAtCamera(t){let e;if(this.speakTo&&(e=new y.Vector3,this.speakTo.objectLeftEye?.isObject3D?(this.speakTo.armature.objectHead,this.speakTo.objectLeftEye.updateMatrixWorld(!0),this.speakTo.objectRightEye.updateMatrixWorld(!0),fe.setFromMatrixPosition(this.speakTo.objectLeftEye.matrixWorld),xe.setFromMatrixPosition(this.speakTo.objectRightEye.matrixWorld),e.addVectors(fe,xe).divideScalar(2)):this.speakTo.isObject3D?this.speakTo.getWorldPosition(e):this.speakTo.isVector3?e.set(this.speakTo):this.speakTo.x&&this.speakTo.y&&this.speakTo.z&&e.set(this.speakTo.x,this.speakTo.y,this.speakTo.z)),!e){if(this.avatar.hasOwnProperty("avatarIgnoreCamera")){if(this.avatar.avatarIgnoreCamera){this.lookAhead(t);return}}else if(this.opt.avatarIgnoreCamera){this.lookAhead(t);return}this.lookAt(null,null,t);return}this.objectLeftEye.updateMatrixWorld(!0),this.objectRightEye.updateMatrixWorld(!0),fe.setFromMatrixPosition(this.objectLeftEye.matrixWorld),xe.setFromMatrixPosition(this.objectRightEye.matrixWorld),fe.add(xe).divideScalar(2),K.copy(this.armature.quaternion),K.multiply(this.poseTarget.props["Hips.quaternion"]),K.multiply(this.poseTarget.props["Spine.quaternion"]),K.multiply(this.poseTarget.props["Spine1.quaternion"]),K.multiply(this.poseTarget.props["Spine2.quaternion"]),K.multiply(this.poseTarget.props["Neck.quaternion"]),K.multiply(this.poseTarget.props["Head.quaternion"]);const n=new y.Vector3().subVectors(e,fe).normalize(),i=Math.atan2(n.x,n.z),s=Math.asin(-n.y);V.set(s,i,0,"YXZ");const l=new y.Quaternion().setFromEuler(V),c=new y.Quaternion().copy(l).multiply(K.clone().invert());V.setFromQuaternion(c,"YXZ");let r=V.x/(40/24)+.2,u=V.y/(9/4),a=Math.min(.6,Math.max(-.3,r)),d=Math.min(.8,Math.max(-.8,u)),h=(Math.random()-.5)/4,g=(Math.random()-.5)/4;if(t){let x=this.animQueue.findIndex(w=>w.template.name==="lookat");x!==-1&&this.animQueue.splice(x,1);const f={name:"lookat",dt:[750,t],vs:{bodyRotateX:[a+h],bodyRotateY:[d+g],eyesRotateX:[-3*h+.1],eyesRotateY:[-5*g],browInnerUp:[[0,.7]],mouthLeft:[[0,.7]],mouthRight:[[0,.7]],eyeContact:[0],headMove:[0]}};this.animQueue.push(this.animFactory(f))}}lookAt(t,e,n){if(!this.camera)return;const i=this.nodeAvatar.getBoundingClientRect();this.objectLeftEye.updateMatrixWorld(!0),this.objectRightEye.updateMatrixWorld(!0);const s=new y.Vector3().setFromMatrixPosition(this.objectLeftEye.matrixWorld),o=new y.Vector3().setFromMatrixPosition(this.objectRightEye.matrixWorld),l=new y.Vector3().addVectors(s,o).divideScalar(2);l.project(this.camera);let c=(l.x+1)/2*i.width+i.left,r=-(l.y-1)/2*i.height+i.top;t===null&&(t=c),e===null&&(e=r),K.copy(this.armature.quaternion),K.multiply(this.poseTarget.props["Hips.quaternion"]),K.multiply(this.poseTarget.props["Spine.quaternion"]),K.multiply(this.poseTarget.props["Spine1.quaternion"]),K.multiply(this.poseTarget.props["Spine2.quaternion"]),K.multiply(this.poseTarget.props["Neck.quaternion"]),K.multiply(this.poseTarget.props["Head.quaternion"]),V.setFromQuaternion(K);let u=V.x/(40/24),a=V.y/(9/4),d=Math.min(.4,Math.max(-.4,this.camera.rotation.x)),h=Math.min(.4,Math.max(-.4,this.camera.rotation.y)),g=Math.max(window.innerWidth-c,c),x=Math.max(window.innerHeight-r,r),f=this.convertRange(e,[r-x,r+x],[-.3,.6])-u+d,w=this.convertRange(t,[c-g,c+g],[-.8,.8])-a+h;f=Math.min(.6,Math.max(-.3,f)),w=Math.min(.8,Math.max(-.8,w));let D=(Math.random()-.5)/4,p=(Math.random()-.5)/4;if(n){let O=this.animQueue.findIndex(R=>R.template.name==="lookat");O!==-1&&this.animQueue.splice(O,1);const T={name:"lookat",dt:[750,n],vs:{bodyRotateX:[f+D],bodyRotateY:[w+p],eyesRotateX:[-3*D+.1],eyesRotateY:[-5*p],browInnerUp:[[0,.7]],mouthLeft:[[0,.7]],mouthRight:[[0,.7]],eyeContact:[0],headMove:[0]}};this.animQueue.push(this.animFactory(T))}}touchAt(t,e){if(!this.camera)return;const n=this.nodeAvatar.getBoundingClientRect(),i=new y.Vector2((t-n.left)/n.width*2-1,-((e-n.top)/n.height)*2+1),s=new y.Raycaster;s.setFromCamera(i,this.camera);const o=s.intersectObject(this.armature);if(o.length>0){const l=o[0].point,c=new y.Vector3,r=new y.Vector3;this.objectLeftArm.getWorldPosition(c),this.objectRightArm.getWorldPosition(r);const u=c.distanceToSquared(l),a=r.distanceToSquared(l);u<a?(this.ikSolve({iterations:20,root:"LeftShoulder",effector:"LeftHandMiddle1",links:[{link:"LeftHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5,maxAngle:.1},{link:"LeftForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-.5,maxz:3,maxAngle:.2},{link:"LeftArm",minx:-1.5,maxx:1.5,miny:0,maxy:0,minz:-1,maxz:3}]},l,!1,1e3),this.setValue("handFistLeft",0)):(this.ikSolve({iterations:20,root:"RightShoulder",effector:"RightHandMiddle1",links:[{link:"RightHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5,maxAngle:.1},{link:"RightForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-3,maxz:.5,maxAngle:.2},{link:"RightArm",minx:-1.5,maxx:1.5,miny:0,maxy:0,minz:-1,maxz:3}]},l,!1,1e3),this.setValue("handFistRight",0))}else["LeftArm","LeftForeArm","LeftHand","RightArm","RightForeArm","RightHand"].forEach(l=>{let c=l+".quaternion";this.poseTarget.props[c].copy(this.getPoseTemplateProp(c)),this.poseTarget.props[c].t=this.animClock,this.poseTarget.props[c].d=1e3});return o.length>0}speakWithHands(t=0,e=.5){if(this.mixer||this.gesture||!this.poseTarget.template.standing||this.poseTarget.template.bend||Math.random()>e)return;this.ikSolve({root:"LeftShoulder",effector:"LeftHandMiddle1",links:[{link:"LeftHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5},{link:"LeftForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-.5,maxz:3},{link:"LeftArm",minx:-1.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-1,maxz:3}]},new y.Vector3(this.gaussianRandom(0,.5),this.gaussianRandom(-.8,-.2),this.gaussianRandom(0,.5)),!0),this.ikSolve({root:"RightShoulder",effector:"RightHandMiddle1",links:[{link:"RightHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5},{link:"RightForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-3,maxz:.5},{link:"RightArm"}]},new y.Vector3(this.gaussianRandom(-.5,0),this.gaussianRandom(-.8,-.2),this.gaussianRandom(0,.5)),!0);const n=[],i=[];n.push(100+Math.round(Math.random()*500)),i.push({duration:1e3,props:{"LeftHand.quaternion":new y.Quaternion().setFromEuler(new y.Euler(0,-1-Math.random(),0)),"RightHand.quaternion":new y.Quaternion().setFromEuler(new y.Euler(0,1+Math.random(),0))}}),["LeftArm","LeftForeArm","RightArm","RightForeArm"].forEach(o=>{i[0].props[o+".quaternion"]=this.ikMesh.getObjectByName(o).quaternion.clone()}),n.push(1e3+Math.round(Math.random()*500)),i.push({duration:2e3,props:{}}),["LeftArm","LeftForeArm","RightArm","RightForeArm","LeftHand","RightHand"].forEach(o=>{i[1].props[o+".quaternion"]=null});const s=this.animFactory({name:"talkinghands",delay:t,dt:n,vs:{moveto:i}});this.animQueue.push(s)}getSlowdownRate(t){return this.animSlowdownRate}setSlowdownRate(t){this.animSlowdownRate=t,this.audioSpeechSource.playbackRate.value=1/this.animSlowdownRate,this.audioBackgroundSource.playbackRate.value=1/this.animSlowdownRate}getAutoRotateSpeed(t){return this.controls.autoRotateSpeed}setAutoRotateSpeed(t){this.controls.autoRotateSpeed=t,this.controls.autoRotate=t>0}start(){this.armature&&this.isRunning===!1&&(this.audioCtx.resume(),this.animTimeLast=performance.now(),this.isRunning=!0,this.isAvatarOnly||requestAnimationFrame(this.animate.bind(this)))}stop(){this.isRunning=!1,this.audioCtx.suspend()}startListening(t,e={},n=null){this.listeningAnalyzer=t,this.listeningAnalyzer.fftSize=256,this.listeningAnalyzer.smoothingTimeConstant=.1,this.listeningAnalyzer.minDecibels=-70,this.listeningAnalyzer.maxDecibels=-10,this.listeningOnchange=n&&typeof n=="function"?n:null,this.listeningSilenceThresholdLevel=e?.hasOwnProperty("listeningSilenceThresholdLevel")?e.listeningSilenceThresholdLevel:this.opt.listeningSilenceThresholdLevel,this.listeningSilenceThresholdMs=e?.hasOwnProperty("listeningSilenceThresholdMs")?e.listeningSilenceThresholdMs:this.opt.listeningSilenceThresholdMs,this.listeningSilenceDurationMax=e?.hasOwnProperty("listeningSilenceDurationMax")?e.listeningSilenceDurationMax:this.opt.listeningSilenceDurationMax,this.listeningActiveThresholdLevel=e?.hasOwnProperty("listeningActiveThresholdLevel")?e.listeningActiveThresholdLevel:this.opt.listeningActiveThresholdLevel,this.listeningActiveThresholdMs=e?.hasOwnProperty("listeningActiveThresholdMs")?e.listeningActiveThresholdMs:this.opt.listeningActiveThresholdMs,this.listeningActiveDurationMax=e?.hasOwnProperty("listeningActiveDurationMax")?e.listeningActiveDurationMax:this.opt.listeningActiveDurationMax,this.listeningActive=!1,this.listeningVolume=0,this.listeningTimer=0,this.listeningTimerTotal=0,this.isListening=!0}stopListening(){this.isListening=!1}async playAnimation(t,e=null,n=10,i=0,s=.01,o=!1){if(!this.armature)return;this.positionWasLocked=!o,o?console.log("Position locking disabled for FBX animation:",t):(this.lockAvatarPosition(),console.log("Position locked immediately before FBX animation:",t));let l=this.animClips.find(c=>c.url===t+"-"+i);if(l){let c=this.animQueue.find(a=>a.template.name==="pose");c&&(c.ts[0]=1/0),Object.entries(l.pose.props).forEach(a=>{this.poseBase.props[a[0]]=a[1].clone(),this.poseTarget.props[a[0]]=a[1].clone(),this.poseTarget.props[a[0]].t=0,this.poseTarget.props[a[0]].d=1e3}),this.mixer?console.log("Using existing mixer for FBX animation, preserving morph targets"):(this.mixer=new y.AnimationMixer(this.armature),console.log("Created new mixer for FBX animation")),this.mixer.addEventListener("finished",this.stopAnimation.bind(this),{once:!0});const r=Math.ceil(n/l.clip.duration),u=this.mixer.clipAction(l.clip);u.setLoop(y.LoopRepeat,r),u.clampWhenFinished=!0,this.currentFBXAction=u;try{u.fadeIn(.5).play(),console.log("FBX animation started successfully:",t)}catch(a){console.warn("FBX animation failed to start:",a),this.stopAnimation();return}if(u.getClip().tracks.length===0){console.warn("FBX animation has no valid tracks, stopping"),this.stopAnimation();return}}else{if(t.split(".").pop().toLowerCase()!=="fbx"){console.error(`Invalid file type for FBX animation: ${t}. Expected .fbx file.`);return}let r=!1;try{const d=await fetch(t,{method:"HEAD"});if(r=d.ok,!r){console.error(`FBX file not found at ${t}. Status: ${d.status}`),console.error("Please check:"),console.error("1. File path is correct (note: path is case-sensitive)"),console.error("2. File exists in your public folder"),console.error("3. File is accessible (not blocked by server)");return}}catch(d){console.warn(`Could not verify file existence for ${t}, attempting to load anyway:`,d)}const u=new Pe.FBXLoader;let a;try{a=await u.loadAsync(t,e)}catch(d){console.error(`Failed to load FBX animation from ${t}:`,d),console.error("Error details:",{message:d.message,url:t,suggestion:"Make sure the file is a valid FBX file and the path is correct"}),d.message&&d.message.includes("version number")&&(console.error("FBX Loader Error: Cannot find version number"),console.error("This error usually means:"),console.error("1. The file is not a valid FBX file (might be GLB, corrupted, or wrong format)"),console.error("2. The file might be corrupted"),console.error("3. The file path might be incorrect"),console.error("4. The server returned an HTML error page instead of the FBX file"),console.error("5. The file might not exist at that path"),console.error(""),console.error("Solution: Please verify:"),console.error(` - File exists at: ${t}`),console.error(" - File is a valid FBX binary file"),console.error(" - File path matches your public folder structure"),console.error(" - File is not corrupted"));try{const h=await fetch(t),g=h.headers.get("content-type"),x=await h.text();console.error("Response details:",{status:h.status,contentType:g,firstBytes:x.substring(0,100),isHTML:x.trim().startsWith("<!DOCTYPE")||x.trim().startsWith("<html")}),(x.trim().startsWith("<!DOCTYPE")||x.trim().startsWith("<html"))&&console.error("The server returned an HTML page instead of an FBX file. The file path is likely incorrect.")}catch(h){console.error("Could not fetch file for debugging:",h)}return}if(a&&a.animations&&a.animations[i]){let d=a.animations[i];const h=new Set;this.armature&&this.armature.traverse(k=>{(k.isBone||k.type==="Bone")&&h.add(k.name)});const g=new Map,x=k=>{if(h.has(k))return k;let A=k.replace(/^mixamorig/i,"").replace(/^CC_Base_/i,"").replace(/^RPM_/i,"");if(h.has(A))return A;const z=A.toLowerCase();if(z.includes("left")&&z.includes("arm")){if(z.includes("fore")||z.includes("lower")){if(h.has("LeftForeArm"))return"LeftForeArm";if(h.has("LeftForearm"))return"LeftForearm"}else if(!z.includes("fore")&&!z.includes("hand")&&h.has("LeftArm"))return"LeftArm"}if(z.includes("right")&&z.includes("arm")){if(z.includes("fore")||z.includes("lower")){if(h.has("RightForeArm"))return"RightForeArm";if(h.has("RightForearm"))return"RightForearm"}else if(!z.includes("fore")&&!z.includes("hand")&&h.has("RightArm"))return"RightArm"}if(z.includes("left")&&z.includes("hand")&&!z.includes("index")&&!z.includes("thumb")&&!z.includes("middle")&&!z.includes("ring")&&!z.includes("pinky")&&h.has("LeftHand"))return"LeftHand";if(z.includes("right")&&z.includes("hand")&&!z.includes("index")&&!z.includes("thumb")&&!z.includes("middle")&&!z.includes("ring")&&!z.includes("pinky")&&h.has("RightHand"))return"RightHand";if(z.includes("left")&&(z.includes("shoulder")||z.includes("clavicle"))&&h.has("LeftShoulder"))return"LeftShoulder";if(z.includes("right")&&(z.includes("shoulder")||z.includes("clavicle"))&&h.has("RightShoulder"))return"RightShoulder";const X={LeftArm:"LeftArm",leftArm:"LeftArm",LEFTARM:"LeftArm",RightArm:"RightArm",rightArm:"RightArm",RIGHTARM:"RightArm",LeftForeArm:"LeftForeArm",leftForeArm:"LeftForeArm",leftForearm:"LeftForeArm",LeftForearm:"LeftForeArm",RightForeArm:"RightForeArm",rightForeArm:"RightForeArm",rightForearm:"RightForeArm",RightForearm:"RightForeArm",LeftHand:"LeftHand",leftHand:"LeftHand",RightHand:"RightHand",rightHand:"RightHand",LeftShoulder:"LeftShoulder",leftShoulder:"LeftShoulder",RightShoulder:"RightShoulder",rightShoulder:"RightShoulder",Spine:"Spine1",spine:"Spine1",Spine1:"Spine1",Spine2:"Spine2",Head:"Head",head:"Head",Neck:"Neck",neck:"Neck",Hips:"Hips",hips:"Hips",Root:"Hips",root:"Hips"};if(X[A]){const S=X[A];if(h.has(S))return S}for(const S of h)if(S.toLowerCase()===z)return S;for(const S of h){const F=S.toLowerCase();if((z.includes("left")&&F.includes("left")||z.includes("right")&&F.includes("right"))&&(z.includes("arm")&&F.includes("arm")&&!F.includes("fore")||z.includes("forearm")&&F.includes("forearm")||z.includes("hand")&&F.includes("hand")&&!F.includes("index")&&!F.includes("thumb")||z.includes("shoulder")&&F.includes("shoulder")))return S}return null},f=new Set;d.tracks.forEach(k=>{const A=k.name.split(".");f.add(A[0])}),console.log("=== Ready Player Me Animation Bone Analysis ==="),console.log("FBX bone names:",Array.from(f).sort().join(", ")),console.log("Avatar skeleton bone names:",Array.from(h).sort().join(", "));const w=Array.from(f).filter(k=>k.toLowerCase().includes("arm")||k.toLowerCase().includes("hand")||k.toLowerCase().includes("shoulder")),D=Array.from(h).filter(k=>k.includes("Arm")||k.includes("Hand")||k.includes("Shoulder"));console.log("FBX arm/hand/shoulder bones:",w.sort().join(", ")),console.log("Avatar arm/hand/shoulder bones:",D.sort().join(", "));const p=[],O=new Set;if(d.tracks.forEach(k=>{const z=k.name.replaceAll("mixamorig","").split("."),X=z[0],S=z[1],F=x(X);if(F&&S){const Z=`${F}.${S}`,G=k.clone();G.name=Z,p.push(G),X!==F&&g.set(X,F)}else O.add(X),(X.toLowerCase().includes("arm")||X.toLowerCase().includes("hand")||X.toLowerCase().includes("shoulder"))&&console.warn(`⚠️ Arm bone "${X}" could not be mapped to avatar skeleton`)}),O.size>0&&console.warn(`⚠️ ${O.size} bone(s) could not be mapped:`,Array.from(O).sort().join(", ")),p.length>0){d=new y.AnimationClip(d.name,d.duration,p),console.log(`✓ Created animation with ${p.length} mapped tracks (from ${d.tracks.length} original tracks)`),g.size>0&&console.log(`✓ Mapped ${g.size} bone(s):`,Array.from(g.entries()).map(([A,z])=>`${A}→${z}`).join(", "));const k=Array.from(g.values()).filter(A=>A.includes("Arm")||A.includes("Hand")||A.includes("Shoulder"));k.length>0?console.log(`✓ Arm bones mapped: ${k.join(", ")}`):console.warn("⚠️ No arm bones were mapped! This may cause arm rigging issues.")}else console.error("❌ No tracks could be mapped! Animation may not work correctly.");const T={};d.tracks.forEach(k=>{k.name=k.name.replaceAll("mixamorig","");const A=k.name.split(".");if(A[1]==="position"){for(let z=0;z<k.values.length;z++)k.values[z]=k.values[z]*s;T[k.name]=new y.Vector3(k.values[0],k.values[1],k.values[2])}else A[1]==="quaternion"?T[k.name]=new y.Quaternion(k.values[0],k.values[1],k.values[2],k.values[3]):A[1]==="rotation"&&(T[A[0]+".quaternion"]=new y.Quaternion().setFromEuler(new y.Euler(k.values[0],k.values[1],k.values[2],"XYZ")).normalize())});const R={props:T};T["Hips.position"]&&(T["Hips.position"].y<.5?R.lying=!0:R.standing=!0),this.animClips.push({url:t+"-"+i,clip:d,pose:R}),this.playAnimation(t,e,n,i,s)}else{const d="Animation "+t+" (ndx="+i+") not found";console.error(d),a&&a.animations?console.error(`FBX file loaded but has ${a.animations.length} animation(s), requested index ${i}`):console.error(a?"FBX file loaded but contains no animations":"FBX file failed to load or is invalid")}}}stopAnimation(){if(this.currentFBXAction&&(this.currentFBXAction.stop(),this.currentFBXAction=null,console.log("FBX animation action stopped, mixer preserved for lip-sync")),this.mixer&&this.mixer._actions.length===0&&(this.mixer=null,console.log("Mixer destroyed as no actions remain")),this.positionWasLocked?(this.unlockAvatarPosition(),console.log("Position unlocked after FBX animation stopped")):console.log("Position was not locked, no unlock needed"),this.gesture)for(let[e,n]of Object.entries(this.gesture))n.t=this.animClock,n.d=1e3,this.poseTarget.props.hasOwnProperty(e)&&(this.poseTarget.props[e].copy(n),this.poseTarget.props[e].t=this.animClock,this.poseTarget.props[e].d=1e3);let t=this.animQueue.find(e=>e.template.name==="pose");t&&(t.ts[0]=this.animClock),this.setPoseFromTemplate(null)}async playPose(t,e=null,n=5,i=0,s=.01){if(!this.armature)return;let o=this.poseTemplates[t];if(!o){const l=this.animPoses.find(c=>c.url===t+"-"+i);l&&(o=l.pose)}if(o){this.poseName=t,this.mixer=null;let l=this.animQueue.find(c=>c.template.name==="pose");l&&(l.ts[0]=this.animClock+n*1e3+2e3),this.setPoseFromTemplate(o)}else{let c=await new Pe.FBXLoader().loadAsync(t,e);if(c&&c.animations&&c.animations[i]){let r=c.animations[i];const u={};r.tracks.forEach(d=>{d.name=d.name.replaceAll("mixamorig","");const h=d.name.split(".");h[1]==="position"?u[d.name]=new y.Vector3(d.values[0]*s,d.values[1]*s,d.values[2]*s):h[1]==="quaternion"?u[d.name]=new y.Quaternion(d.values[0],d.values[1],d.values[2],d.values[3]):h[1]==="rotation"&&(u[h[0]+".quaternion"]=new y.Quaternion().setFromEuler(new y.Euler(d.values[0],d.values[1],d.values[2],"XYZ")).normalize())});const a={props:u};u["Hips.position"]&&(u["Hips.position"].y<.5?a.lying=!0:a.standing=!0),this.animPoses.push({url:t+"-"+i,pose:a}),this.playPose(t,e,n,i,s)}else{const r="Pose "+t+" (ndx="+i+") not found";console.error(r)}}}stopPose(){this.stopAnimation()}playGesture(t,e=3,n=!1,i=1e3){if(!this.armature)return;let s=this.gestureTemplates[t];if(s){this.gestureTimeout&&(clearTimeout(this.gestureTimeout),this.gestureTimeout=null);let l=this.animQueue.findIndex(c=>c.template.name==="talkinghands");l!==-1&&(this.animQueue[l].ts=this.animQueue[l].ts.map(c=>0)),this.gesture=this.propsToThreeObjects(s),n&&(this.gesture=this.mirrorPose(this.gesture)),t==="namaste"&&this.avatar.body==="M"&&(this.gesture["RightArm.quaternion"].rotateTowards(new y.Quaternion(0,1,0,0),-.25),this.gesture["LeftArm.quaternion"].rotateTowards(new y.Quaternion(0,1,0,0),-.25));for(let[c,r]of Object.entries(this.gesture))r.t=this.animClock,r.d=i,this.poseTarget.props.hasOwnProperty(c)&&(this.poseTarget.props[c].copy(r),this.poseTarget.props[c].t=this.animClock,this.poseTarget.props[c].d=i);e&&Number.isFinite(e)&&(this.gestureTimeout=setTimeout(this.stopGesture.bind(this,i),1e3*e))}let o=this.animEmojis[t];if(o&&(o&&o.link&&(o=this.animEmojis[o.link]),o)){this.lookAtCamera(500);const l=this.animFactory(o);if(l.gesture=!0,e&&Number.isFinite(e)){const c=l.ts[0],u=l.ts[l.ts.length-1]-c;if(e*1e3-u>0){const d=[];for(let x=1;x<l.ts.length;x++)d.push(l.ts[x]-l.ts[x-1]);const h=o.template?.rescale||d.map(x=>x/u),g=e*1e3-u;l.ts=l.ts.map((x,f,w)=>f===0?c:w[f-1]+d[f-1]+h[f-1]*g)}else{const d=e*1e3/u;l.ts=l.ts.map(h=>c+d*(h-c))}}this.animQueue.push(l)}}stopGesture(t=1e3){if(this.gestureTimeout&&(clearTimeout(this.gestureTimeout),this.gestureTimeout=null),this.gesture){const n=Object.entries(this.gesture);this.gesture=null;for(const[i,s]of n)this.poseTarget.props.hasOwnProperty(i)&&(this.poseTarget.props[i].copy(this.getPoseTemplateProp(i)),this.poseTarget.props[i].t=this.animClock,this.poseTarget.props[i].d=t)}let e=this.animQueue.findIndex(n=>n.gesture);e!==-1&&this.animQueue.splice(e,1)}ikSolve(t,e=null,n=!1,i=null){const s=new y.Vector3,o=new y.Vector3,l=new y.Vector3,c=new y.Vector3,r=new y.Quaternion,u=new y.Vector3,a=new y.Vector3,d=new y.Vector3,h=this.ikMesh.getObjectByName(t.root);h.position.setFromMatrixPosition(this.armature.getObjectByName(t.root).matrixWorld),h.quaternion.setFromRotationMatrix(this.armature.getObjectByName(t.root).matrixWorld),e&&n&&e.applyQuaternion(this.armature.quaternion).add(h.position);const g=this.ikMesh.getObjectByName(t.effector),x=t.links;x.forEach(w=>{w.bone=this.ikMesh.getObjectByName(w.link),w.bone.quaternion.copy(this.getPoseTemplateProp(w.link+".quaternion"))}),h.updateMatrixWorld(!0);const f=t.iterations||10;if(e)for(let w=0;w<f;w++){let D=!1;for(let p=0,O=x.length;p<O;p++){const T=x[p].bone;T.matrixWorld.decompose(c,r,u),r.invert(),o.setFromMatrixPosition(g.matrixWorld),l.subVectors(o,c),l.applyQuaternion(r),l.normalize(),s.subVectors(e,c),s.applyQuaternion(r),s.normalize();let R=s.dot(l);R>1?R=1:R<-1&&(R=-1),R=Math.acos(R),!(R<1e-5)&&(x[p].minAngle!==void 0&&R<x[p].minAngle&&(R=x[p].minAngle),x[p].maxAngle!==void 0&&R>x[p].maxAngle&&(R=x[p].maxAngle),a.crossVectors(l,s),a.normalize(),K.setFromAxisAngle(a,R),T.quaternion.multiply(K),T.rotation.setFromVector3(d.setFromEuler(T.rotation).clamp(new y.Vector3(x[p].minx!==void 0?x[p].minx:-1/0,x[p].miny!==void 0?x[p].miny:-1/0,x[p].minz!==void 0?x[p].minz:-1/0),new y.Vector3(x[p].maxx!==void 0?x[p].maxx:1/0,x[p].maxy!==void 0?x[p].maxy:1/0,x[p].maxz!==void 0?x[p].maxz:1/0))),T.updateMatrixWorld(!0),D=!0)}if(!D)break}i&&x.forEach(w=>{this.poseTarget.props[w.link+".quaternion"].copy(w.bone.quaternion),this.poseTarget.props[w.link+".quaternion"].t=this.animClock,this.poseTarget.props[w.link+".quaternion"].d=i})}dispose(){this.isRunning=!1,this.stop(),this.stopSpeaking(),this.streamStop(),this.isAvatarOnly?this.armature&&(this.armature.parent&&this.armature.parent.remove(this.armature),this.clearThree(this.armature)):(this.clearThree(this.scene),this.resizeobserver.disconnect(),this.renderer&&(this.renderer.dispose(),this.renderer.domElement&&this.renderer.domElement.parentNode&&this.renderer.domElement.parentNode.removeChild(this.renderer.domElement),this.renderer=null)),this.clearThree(this.ikMesh),this.dynamicbones.dispose()}}const be={apiKey:"sk_ace57ef3ef65a92b9d3bee2a00183b78ca790bc3e10964f2",endpoint:"https://api.elevenlabs.io/v1/text-to-speech",defaultVoice:"21m00Tcm4TlvDq8ikWAM",voices:{rachel:"21m00Tcm4TlvDq8ikWAM",drew:"29vD33N1CtxCmqQRPOHJ",bella:"EXAVITQu4vr4xnSDxMaL",antoni:"ErXwobaYiN019PkySvjV",elli:"MF3mGyEYCl7XYWbV9V6O",josh:"VR6AewLTigWG4xSOukaG"}},ze={defaultVoice:"aura-2-thalia-en",voices:{thalia:"aura-2-thalia-en",asteria:"aura-2-asteria-en",orion:"aura-2-orion-en",stella:"aura-2-stella-en",athena:"aura-2-athena-en",hera:"aura-2-hera-en",zeus:"aura-2-zeus-en"}};function ke(){return{service:"elevenlabs",endpoint:be.endpoint,apiKey:be.apiKey,defaultVoice:be.defaultVoice,voices:be.voices}}function mt(){const U=ke(),t=[];return Object.entries(U.voices).forEach(([e,n])=>{t.push({value:n,label:`${e.charAt(0).toUpperCase()+e.slice(1)} (${U.service})`})}),t}const Me=v.forwardRef(({avatarUrl:U="/avatars/brunette.glb",avatarBody:t="F",mood:e="neutral",ttsLang:n="en",ttsService:i=null,ttsVoice:s=null,ttsApiKey:o=null,bodyMovement:l="idle",movementIntensity:c=.5,showFullAvatar:r=!0,cameraView:u="upper",onReady:a=()=>{},onLoading:d=()=>{},onError:h=()=>{},className:g="",style:x={},animations:f={}},w)=>{const D=v.useRef(null),p=v.useRef(null),O=v.useRef(r),T=v.useRef(null),R=v.useRef(null),k=v.useRef(!1),A=v.useRef({remainingText:null,originalText:null,options:null}),z=v.useRef([]),X=v.useRef(0),[S,F]=v.useState(!0),[Z,G]=v.useState(null),[te,re]=v.useState(!1),[me,he]=v.useState(!1);v.useEffect(()=>{k.current=me},[me]),v.useEffect(()=>{O.current=r},[r]);const J=ke(),ye=i||J.service;let j;ye==="browser"?j={service:"browser",endpoint:"",apiKey:null,defaultVoice:"Google US English"}:ye==="elevenlabs"?j={service:"elevenlabs",endpoint:"https://api.elevenlabs.io/v1/text-to-speech",apiKey:o||J.apiKey,defaultVoice:s||J.defaultVoice||be.defaultVoice,voices:J.voices||be.voices}:ye==="deepgram"?j={service:"deepgram",endpoint:"https://api.deepgram.com/v1/speak",apiKey:o||J.apiKey,defaultVoice:s||J.defaultVoice||ze.defaultVoice,voices:J.voices||ze.voices}:j={...J,apiKey:o!==null?o:J.apiKey};const b={url:U,body:t,avatarMood:e,ttsLang:ye==="browser"?"en-US":n,ttsVoice:s||j.defaultVoice,lipsyncLang:"en",showFullAvatar:r,bodyMovement:l,movementIntensity:c},I={ttsEndpoint:j.endpoint,ttsApikey:j.apiKey,ttsService:ye,lipsyncModules:["en"],cameraView:u},E=v.useCallback(async()=>{if(!(!D.current||p.current))try{if(F(!0),G(null),p.current=new Te(D.current,I),p.current.controls&&(p.current.controls.enableRotate=!1,p.current.controls.enableZoom=!1,p.current.controls.enablePan=!1,p.current.controls.enableDamping=!1),f&&Object.keys(f).length>0&&(p.current.customAnimations=f),await p.current.showAvatar(b,q=>{if(q.lengthComputable){const ee=Math.min(100,Math.round(q.loaded/q.total*100));d(ee)}}),await new Promise(q=>{const ee=()=>{p.current.lipsync&&Object.keys(p.current.lipsync).length>0?q():setTimeout(ee,100)};ee()}),p.current&&p.current.setShowFullAvatar)try{p.current.setShowFullAvatar(r)}catch(q){console.warn("Error setting full body mode on initialization:",q)}p.current&&p.current.controls&&(p.current.controls.enableRotate=!1,p.current.controls.enableZoom=!1,p.current.controls.enablePan=!1,p.current.controls.enableDamping=!1,p.current.controls.update()),F(!1),re(!0),a(p.current);const W=()=>{document.visibilityState==="visible"?p.current?.start():p.current?.stop()};return document.addEventListener("visibilitychange",W),()=>{document.removeEventListener("visibilitychange",W)}}catch(C){console.error("Error initializing TalkingHead:",C),G(C.message||"Failed to initialize avatar"),F(!1),h(C)}},[U,t,e,n,i,s,o,r,l,c,u]);v.useEffect(()=>(E(),()=>{p.current&&(p.current.stop(),p.current.dispose(),p.current=null)}),[E]),v.useEffect(()=>{if(!D.current||!p.current)return;const C=new ResizeObserver(q=>{for(const ee of q)p.current&&p.current.onResize&&p.current.onResize()});C.observe(D.current);const W=()=>{p.current&&p.current.onResize&&p.current.onResize()};return window.addEventListener("resize",W),()=>{C.disconnect(),window.removeEventListener("resize",W)}},[te]);const P=v.useCallback(async()=>{if(p.current&&p.current.audioCtx)try{(p.current.audioCtx.state==="suspended"||p.current.audioCtx.state==="interrupted")&&(await p.current.audioCtx.resume(),console.log("Audio context resumed"))}catch(C){console.warn("Failed to resume audio context:",C)}},[]),N=v.useCallback(async(C,W={})=>{if(p.current&&te)try{R.current&&(clearInterval(R.current),R.current=null),T.current={text:C,options:W},A.current={remainingText:null,originalText:null,options:null};const q=/[!\.\?\n\p{Extended_Pictographic}]/ug,ee=C.split(q).map(L=>L.trim()).filter(L=>L.length>0);z.current=ee,X.current=0,he(!1),k.current=!1,await P();const de={...W,lipsyncLang:W.lipsyncLang||b.lipsyncLang||"en"};if(W.onSpeechEnd&&p.current){const L=p.current;let B=null,_=0;const ne=1200;let oe=!1;B=setInterval(()=>{if(_++,k.current)return;if(_>ne){if(B&&(clearInterval(B),B=null,R.current=null),!oe&&!k.current){oe=!0;try{W.onSpeechEnd()}catch(Fe){console.error("Error in onSpeechEnd callback (timeout):",Fe)}}return}const ie=!L.speechQueue||L.speechQueue.length===0,Le=!L.audioPlaylist||L.audioPlaylist.length===0;L&&L.isSpeaking===!1&&ie&&Le&&L.isAudioPlaying===!1&&!oe&&!k.current&&setTimeout(()=>{if(L&&!k.current&&L.isSpeaking===!1&&(!L.speechQueue||L.speechQueue.length===0)&&(!L.audioPlaylist||L.audioPlaylist.length===0)&&L.isAudioPlaying===!1&&!oe&&!k.current){oe=!0,B&&(clearInterval(B),B=null,R.current=null);try{W.onSpeechEnd()}catch(Ve){console.error("Error in onSpeechEnd callback:",Ve)}}},100)},100),R.current=B}p.current.lipsync&&Object.keys(p.current.lipsync).length>0?(p.current.setSlowdownRate&&p.current.setSlowdownRate(1.05),p.current.speakText(C,de)):setTimeout(async()=>{await P(),p.current&&p.current.lipsync&&(p.current.setSlowdownRate&&p.current.setSlowdownRate(1.05),p.current.speakText(C,de))},100)}catch(q){console.error("Error speaking text:",q),G(q.message||"Failed to speak text")}},[te,P,b.lipsyncLang]),$=v.useCallback(()=>{p.current&&(p.current.stopSpeaking(),p.current.setSlowdownRate&&p.current.setSlowdownRate(1),T.current=null,he(!1))},[]),Y=v.useCallback(()=>{if(p.current&&p.current.pauseSpeaking){const C=p.current;if(C.isSpeaking||C.audioPlaylist&&C.audioPlaylist.length>0||C.speechQueue&&C.speechQueue.length>0){R.current&&(clearInterval(R.current),R.current=null);let q="";if(T.current&&z.current.length>0){const ee=z.current.length,de=C.speechQueue?C.speechQueue.filter(ne=>ne&&ne.text&&Array.isArray(ne.text)&&ne.text.length>0).length:0,L=C.audioPlaylist&&C.audioPlaylist.length>0,B=de+(L?1:0),_=ee-B;if(B>0&&_<ee&&(q=z.current.slice(_).join(". ").trim(),!q&&de>0&&C.speechQueue)){const oe=C.speechQueue.filter(ie=>ie&&ie.text&&Array.isArray(ie.text)&&ie.text.length>0).map(ie=>ie.text.map(Le=>Le.word||"").filter(Le=>Le.length>0).join(" ")).filter(ie=>ie.length>0).join(" ");oe&&oe.trim()&&(q=oe.trim())}}T.current&&(A.current={remainingText:q||null,originalText:T.current.text,options:T.current.options}),C.speechQueue&&(C.speechQueue.length=0),p.current.pauseSpeaking(),k.current=!0,he(!0)}}},[]),Q=v.useCallback(async()=>{if(!p.current||!me)return;let C="",W={};if(A.current&&A.current.remainingText)C=A.current.remainingText,W=A.current.options||{},A.current={remainingText:null,originalText:null,options:null};else if(T.current&&T.current.text)C=T.current.text,W=T.current.options||{};else{console.warn("Resume called but no paused speech found"),he(!1),k.current=!1;return}he(!1),k.current=!1,await P();const q={...W,lipsyncLang:W.lipsyncLang||b.lipsyncLang||"en"};try{await N(C,q)}catch(ee){console.error("Error resuming speech:",ee),he(!1),k.current=!1}},[P,me,N,b]),ve=v.useCallback(C=>{p.current&&p.current.setMood(C)},[]),Ie=v.useCallback(C=>{p.current&&p.current.setSlowdownRate&&p.current.setSlowdownRate(C)},[]),Re=v.useCallback((C,W=!1)=>{if(p.current&&p.current.playAnimation){if(f&&f[C]&&(C=f[C]),p.current.setShowFullAvatar)try{p.current.setShowFullAvatar(O.current)}catch(ee){console.warn("Error setting full body mode:",ee)}if(C.includes("."))try{p.current.playAnimation(C,null,10,0,.01,W)}catch(ee){console.warn(`Failed to play ${C}:`,ee);try{p.current.setBodyMovement("idle")}catch(de){console.warn("Fallback animation also failed:",de)}}else{const ee=[".fbx",".glb",".gltf"];let de=!1;for(const L of ee)try{p.current.playAnimation(C+L,null,10,0,.01,W),de=!0;break}catch{}if(!de){console.warn("Animation not found:",C);try{p.current.setBodyMovement("idle")}catch(L){console.warn("Fallback animation also failed:",L)}}}}},[f]),Ae=v.useCallback(()=>{p.current&&p.current.onResize&&p.current.onResize()},[]);return v.useImperativeHandle(w,()=>({speakText:N,stopSpeaking:$,pauseSpeaking:Y,resumeSpeaking:Q,resumeAudioContext:P,setMood:ve,setTimingAdjustment:Ie,playAnimation:Re,isReady:te,isPaused:me,talkingHead:p.current,handleResize:Ae,setBodyMovement:C=>{if(p.current&&p.current.setShowFullAvatar&&p.current.setBodyMovement)try{p.current.setShowFullAvatar(O.current),p.current.setBodyMovement(C)}catch(W){console.warn("Error setting body movement:",W)}},setMovementIntensity:C=>p.current?.setMovementIntensity(C),playRandomDance:()=>{if(p.current&&p.current.setShowFullAvatar&&p.current.playRandomDance)try{p.current.setShowFullAvatar(O.current),p.current.playRandomDance()}catch(C){console.warn("Error playing random dance:",C)}},playReaction:C=>{if(p.current&&p.current.setShowFullAvatar&&p.current.playReaction)try{p.current.setShowFullAvatar(O.current),p.current.playReaction(C)}catch(W){console.warn("Error playing reaction:",W)}},playCelebration:()=>{if(p.current&&p.current.setShowFullAvatar&&p.current.playCelebration)try{p.current.setShowFullAvatar(O.current),p.current.playCelebration()}catch(C){console.warn("Error playing celebration:",C)}},setShowFullAvatar:C=>{if(p.current&&p.current.setShowFullAvatar)try{O.current=C,p.current.setShowFullAvatar(C)}catch(W){console.warn("Error setting showFullAvatar:",W)}},lockAvatarPosition:()=>{if(p.current&&p.current.lockAvatarPosition)try{p.current.lockAvatarPosition()}catch(C){console.warn("Error locking avatar position:",C)}},unlockAvatarPosition:()=>{if(p.current&&p.current.unlockAvatarPosition)try{p.current.unlockAvatarPosition()}catch(C){console.warn("Error unlocking avatar position:",C)}}})),ue.jsxs("div",{className:`talking-head-avatar ${g}`,style:{width:"100%",height:"100%",position:"relative",...x},children:[ue.jsx("div",{ref:D,className:"talking-head-viewer",style:{width:"100%",height:"100%",minHeight:"400px"}}),S&&ue.jsx("div",{className:"loading-overlay",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"white",fontSize:"18px",zIndex:10},children:"Loading avatar..."}),Z&&ue.jsx("div",{className:"error-overlay",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"#ff6b6b",fontSize:"16px",textAlign:"center",zIndex:10,padding:"20px",borderRadius:"8px"},children:Z})]})});Me.displayName="TalkingHeadAvatar";const De=v.forwardRef(({text:U="Hello! I'm a talking avatar. How are you today?",onLoading:t=()=>{},onError:e=()=>{},onReady:n=()=>{},className:i="",style:s={},avatarConfig:o={}},l)=>{const c=v.useRef(null),r=v.useRef(null),[u,a]=v.useState(!0),[d,h]=v.useState(null),[g,x]=v.useState(!1),f=ke(),w=o.ttsService||f.service,D=w==="browser"?{endpoint:"",apiKey:null,defaultVoice:"Google US English"}:{...f,apiKey:o.ttsApiKey!==void 0&&o.ttsApiKey!==null?o.ttsApiKey:f.apiKey,endpoint:w==="elevenlabs"&&o.ttsApiKey?"https://api.elevenlabs.io/v1/text-to-speech":f.endpoint},p={url:"/avatars/brunette.glb",body:"F",avatarMood:"neutral",ttsLang:w==="browser"?"en-US":"en",ttsVoice:o.ttsVoice||D.defaultVoice,lipsyncLang:"en",showFullAvatar:!0,bodyMovement:"idle",movementIntensity:.5,...o},O={ttsEndpoint:D.endpoint,ttsApikey:D.apiKey,ttsService:w,lipsyncModules:["en"],cameraView:"upper"},T=v.useCallback(async()=>{if(!(!c.current||r.current))try{if(a(!0),h(null),r.current=new Te(c.current,O),await r.current.showAvatar(p,Z=>{if(Z.lengthComputable){const G=Math.min(100,Math.round(Z.loaded/Z.total*100));t(G)}}),r.current.morphs&&r.current.morphs.length>0){const Z=r.current.morphs[0].morphTargetDictionary;console.log("Available morph targets:",Object.keys(Z));const G=Object.keys(Z).filter(te=>te.startsWith("viseme_"));console.log("Viseme morph targets found:",G),G.length===0&&(console.warn("No viseme morph targets found! Lip-sync will not work properly."),console.log("Expected viseme targets: viseme_aa, viseme_E, viseme_I, viseme_O, viseme_U, viseme_PP, viseme_SS, viseme_TH, viseme_DD, viseme_FF, viseme_kk, viseme_nn, viseme_RR, viseme_CH, viseme_sil"))}if(await new Promise(Z=>{const G=()=>{r.current.lipsync&&Object.keys(r.current.lipsync).length>0?(console.log("Lip-sync modules loaded:",Object.keys(r.current.lipsync)),Z()):(console.log("Waiting for lip-sync modules to load..."),setTimeout(G,100))};G()}),r.current&&r.current.setShowFullAvatar)try{r.current.setShowFullAvatar(!0),console.log("Avatar initialized in full body mode")}catch(Z){console.warn("Error setting full body mode on initialization:",Z)}a(!1),x(!0),n(r.current);const F=()=>{document.visibilityState==="visible"?r.current?.start():r.current?.stop()};return document.addEventListener("visibilitychange",F),()=>{document.removeEventListener("visibilitychange",F)}}catch(S){console.error("Error initializing TalkingHead:",S),h(S.message||"Failed to initialize avatar"),a(!1),e(S)}},[]);v.useEffect(()=>(T(),()=>{r.current&&(r.current.stop(),r.current.dispose(),r.current=null)}),[T]);const R=v.useCallback(S=>{if(r.current&&g)try{console.log("Speaking text:",S),console.log("Avatar config:",p),console.log("TalkingHead instance:",r.current),r.current.lipsync&&Object.keys(r.current.lipsync).length>0?(console.log("Lip-sync modules loaded:",Object.keys(r.current.lipsync)),r.current.setSlowdownRate&&(r.current.setSlowdownRate(1.05),console.log("Applied timing adjustment for better lip-sync")),r.current.speakText(S)):(console.warn("Lip-sync modules not ready, waiting..."),setTimeout(()=>{r.current&&r.current.lipsync?(console.log("Lip-sync now ready, speaking..."),r.current.setSlowdownRate&&(r.current.setSlowdownRate(1.05),console.log("Applied timing adjustment for better lip-sync")),r.current.speakText(S)):console.error("Lip-sync still not ready after waiting")},500))}catch(F){console.error("Error speaking text:",F),h(F.message||"Failed to speak text")}else console.warn("Avatar not ready for speaking. isReady:",g,"talkingHeadRef:",!!r.current)},[g,p]),k=v.useCallback(()=>{r.current&&(r.current.stopSpeaking(),r.current.setSlowdownRate&&(r.current.setSlowdownRate(1),console.log("Reset timing to normal")))},[]),A=v.useCallback(S=>{r.current&&r.current.setMood(S)},[]),z=v.useCallback(S=>{r.current&&r.current.setSlowdownRate&&(r.current.setSlowdownRate(S),console.log("Timing adjustment set to:",S))},[]),X=v.useCallback((S,F=!1)=>{if(r.current&&r.current.playAnimation){if(r.current.setShowFullAvatar)try{r.current.setShowFullAvatar(!0)}catch(G){console.warn("Error setting full body mode:",G)}if(S.includes("."))try{r.current.playAnimation(S,null,10,0,.01,F),console.log("Playing animation:",S)}catch(G){console.log(`Failed to play ${S}:`,G);try{r.current.setBodyMovement("idle"),console.log("Fallback to idle animation")}catch(te){console.warn("Fallback animation also failed:",te)}}else{const G=[".fbx",".glb",".gltf"];let te=!1;for(const re of G)try{r.current.playAnimation(S+re,null,10,0,.01,F),console.log("Playing animation:",S+re),te=!0;break}catch{console.log(`Failed to play ${S}${re}, trying next format...`)}if(!te){console.warn("Animation system not available or animation not found:",S);try{r.current.setBodyMovement("idle"),console.log("Fallback to idle animation")}catch(re){console.warn("Fallback animation also failed:",re)}}}}else console.warn("Animation system not available or animation not found:",S)},[]);return v.useImperativeHandle(l,()=>({speakText:R,stopSpeaking:k,setMood:A,setTimingAdjustment:z,playAnimation:X,isReady:g,talkingHead:r.current,setBodyMovement:S=>{if(r.current&&r.current.setShowFullAvatar&&r.current.setBodyMovement)try{r.current.setShowFullAvatar(!0),r.current.setBodyMovement(S),console.log("Body movement set with full body mode:",S)}catch(F){console.warn("Error setting body movement:",F)}},setMovementIntensity:S=>r.current?.setMovementIntensity(S),playRandomDance:()=>{if(r.current&&r.current.setShowFullAvatar&&r.current.playRandomDance)try{r.current.setShowFullAvatar(!0),r.current.playRandomDance(),console.log("Random dance played with full body mode")}catch(S){console.warn("Error playing random dance:",S)}},playReaction:S=>{if(r.current&&r.current.setShowFullAvatar&&r.current.playReaction)try{r.current.setShowFullAvatar(!0),r.current.playReaction(S),console.log("Reaction played with full body mode:",S)}catch(F){console.warn("Error playing reaction:",F)}},playCelebration:()=>{if(r.current&&r.current.setShowFullAvatar&&r.current.playCelebration)try{r.current.setShowFullAvatar(!0),r.current.playCelebration(),console.log("Celebration played with full body mode")}catch(S){console.warn("Error playing celebration:",S)}},setShowFullAvatar:S=>{if(r.current&&r.current.setShowFullAvatar)try{r.current.setShowFullAvatar(S),console.log("Show full avatar set to:",S)}catch(F){console.warn("Error setting showFullAvatar:",F)}},lockAvatarPosition:()=>{if(r.current&&r.current.lockAvatarPosition)try{r.current.lockAvatarPosition()}catch(S){console.warn("Error locking avatar position:",S)}},unlockAvatarPosition:()=>{if(r.current&&r.current.unlockAvatarPosition)try{r.current.unlockAvatarPosition()}catch(S){console.warn("Error unlocking avatar position:",S)}}})),ue.jsxs("div",{className:`talking-head-container ${i}`,style:s,children:[ue.jsx("div",{ref:c,className:"talking-head-viewer",style:{width:"100%",height:"100%",minHeight:"400px"}}),u&&ue.jsx("div",{className:"loading-overlay",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"white",fontSize:"18px",zIndex:10},children:"Loading avatar..."}),d&&ue.jsx("div",{className:"error-overlay",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"#ff6b6b",fontSize:"16px",textAlign:"center",zIndex:10,padding:"20px",borderRadius:"8px"},children:d})]})});De.displayName="TalkingHeadComponent";async function pt(U){try{return(await(await fetch(U)).json()).animations||{}}catch(t){return console.error("Failed to load animation manifest:",t),{}}}const Ue=v.forwardRef(({text:U=null,avatarUrl:t="/avatars/brunette.glb",avatarBody:e="F",mood:n="neutral",ttsLang:i="en",ttsService:s=null,ttsVoice:o=null,ttsApiKey:l=null,bodyMovement:c="idle",movementIntensity:r=.5,showFullAvatar:u=!1,cameraView:a="upper",onReady:d=()=>{},onLoading:h=()=>{},onError:g=()=>{},onSpeechEnd:x=()=>{},className:f="",style:w={},animations:D={},autoAnimationGroup:p=null,autoIdleGroup:O=null,autoSpeak:T=!1},R)=>{const k=v.useRef(null),A=v.useRef(null),z=v.useRef(u),X=v.useRef(null),S=v.useRef(null),F=v.useRef(!1),Z=v.useRef({remainingText:null,originalText:null,options:null}),G=v.useRef([]),[te,re]=v.useState(!0),[me,he]=v.useState(null),[J,ye]=v.useState(!1),[j,b]=v.useState(!1),[I,E]=v.useState(D),P=v.useRef(null);v.useEffect(()=>{F.current=j},[j]),v.useEffect(()=>{(async()=>{if(D.manifest)try{const B=await pt(D.manifest);E(B),console.log("Loaded animations from manifest:",B)}catch(B){console.error("Failed to load animation manifest:",B),E(D)}else E(D)})()},[D]),v.useEffect(()=>{z.current=u},[u]);const N=ke(),$=s||N.service;let Y;$==="browser"?Y={service:"browser",endpoint:"",apiKey:null,defaultVoice:"Google US English"}:$==="elevenlabs"?Y={service:"elevenlabs",endpoint:"https://api.elevenlabs.io/v1/text-to-speech",apiKey:l||N.apiKey,defaultVoice:o||N.defaultVoice||be.defaultVoice,voices:N.voices||be.voices}:$==="deepgram"?Y={service:"deepgram",endpoint:"https://api.deepgram.com/v1/speak",apiKey:l||N.apiKey,defaultVoice:o||N.defaultVoice||ze.defaultVoice,voices:N.voices||ze.voices}:Y={...N,apiKey:l!==null?l:N.apiKey};const Q={url:t,body:e,avatarMood:n,ttsLang:$==="browser"?"en-US":i,ttsVoice:o||Y.defaultVoice,lipsyncLang:"en",showFullAvatar:u,bodyMovement:c,movementIntensity:r},ve={ttsEndpoint:Y.endpoint,ttsApikey:Y.apiKey,ttsService:$,lipsyncModules:["en"],cameraView:a},Ie=v.useCallback(async()=>{if(!(!k.current||A.current))try{re(!0),he(null),A.current=new Te(k.current,ve),console.log("Avatar config being passed:",{url:Q.url,body:Q.body,avatarMood:Q.avatarMood}),await A.current.showAvatar(Q,B=>{if(B.lengthComputable){const _=Math.min(100,Math.round(B.loaded/B.total*100));h(_)}}),A.current?.avatar&&console.log("Avatar body after initialization:",A.current.avatar.body),re(!1),ye(!0),d(A.current);const L=()=>{document.visibilityState==="visible"?A.current?.start():A.current?.stop()};return document.addEventListener("visibilitychange",L),()=>{document.removeEventListener("visibilitychange",L)}}catch(L){console.error("Error initializing TalkingHead:",L),he(L.message||"Failed to initialize avatar"),re(!1),g(L)}},[]);v.useEffect(()=>(Ie(),()=>{A.current&&(A.current.stop(),A.current.dispose(),A.current=null)}),[Ie]);const Re=v.useCallback(async()=>{if(A.current)try{const L=A.current.audioCtx||A.current.audioContext;L&&(L.state==="suspended"||L.state==="interrupted")&&(await L.resume(),console.log("Audio context resumed"))}catch(L){console.warn("Failed to resume audio context:",L)}},[]),Ae=v.useCallback(L=>{if(!I||!I[L])return null;const B=I[L];if(Array.isArray(B)&&B.length>0){const _=Math.floor(Math.random()*B.length);return B[_]}return typeof B=="string"?B:null},[I]),C=v.useCallback((L,B=!1)=>{const _=Ae(L);if(_&&A.current)try{return A.current.playAnimation(_,null,10,0,.01,B),console.log(`Playing random animation from "${L}" group:`,_),_}catch(ne){return console.warn(`Failed to play random animation from "${L}" group:`,ne),null}return null},[Ae]),W=v.useCallback(async(L,B={})=>{if(!A.current||!J){console.warn("Avatar not ready for speaking");return}if(!L||L.trim()===""){console.warn("No text provided to speak");return}await Re();const _=B.animationGroup||p;_&&!B.skipAnimation&&C(_),Z.current={remainingText:null,originalText:null,options:null},G.current=[],X.current={text:L,options:B},S.current&&(clearInterval(S.current),S.current=null),b(!1),F.current=!1;const ne=L.split(/[.!?]+/).filter(ie=>ie.trim().length>0);G.current=ne;const oe={lipsyncLang:B.lipsyncLang||"en",onSpeechEnd:()=>{S.current&&(clearInterval(S.current),S.current=null),B.onSpeechEnd&&B.onSpeechEnd(),x()}};try{A.current.speakText(L,oe)}catch(ie){console.error("Error speaking text:",ie),he(ie.message||"Failed to speak text")}},[J,x,Re,p,C]);v.useEffect(()=>{if(!J||!O||!A.current)return;P.current&&clearInterval(P.current);const L=()=>{A.current&&!F.current&&C(O)};return L(),P.current=setInterval(()=>{L()},12e3+Math.random()*3e3),()=>{P.current&&(clearInterval(P.current),P.current=null)}},[J,O,C]),v.useEffect(()=>{J&&U&&T&&A.current&&W(U)},[J,U,T,W]);const q=v.useCallback(()=>{if(A.current)try{const L=A.current.isSpeaking||!1,B=A.current.audioPlaylist||[],_=A.current.speechQueue||[];if(L||B.length>0||_.length>0){S.current&&(clearInterval(S.current),S.current=null);let ne="";_.length>0&&(ne=_.map(oe=>oe.text&&Array.isArray(oe.text)?oe.text.map(ie=>ie.word).join(" "):oe.text||"").join(" ")),Z.current={remainingText:ne||null,originalText:X.current?.text||null,options:X.current?.options||null},A.current.speechQueue.length=0,A.current.pauseSpeaking(),b(!0),F.current=!0}}catch(L){console.warn("Error pausing speech:",L)}},[]),ee=v.useCallback(async()=>{if(!(!A.current||!j))try{await Re(),b(!1),F.current=!1;const L=Z.current?.remainingText,B=Z.current?.originalText||X.current?.text,_=Z.current?.options||X.current?.options||{},ne=L||B;ne&&W(ne,_)}catch(L){console.warn("Error resuming speech:",L),b(!1),F.current=!1}},[j,W,Re]),de=v.useCallback(()=>{A.current&&(A.current.stopSpeaking(),S.current&&(clearInterval(S.current),S.current=null),b(!1),F.current=!1)},[]);return v.useImperativeHandle(R,()=>({speakText:W,pauseSpeaking:q,resumeSpeaking:ee,stopSpeaking:de,resumeAudioContext:Re,isPaused:()=>j,setMood:L=>A.current?.setMood(L),setBodyMovement:L=>{A.current&&A.current.setBodyMovement(L)},playAnimation:(L,B=!1)=>{A.current&&A.current.playAnimation&&A.current.playAnimation(L,null,10,0,.01,B)},playRandomAnimation:(L,B=!1)=>C(L,B),getRandomAnimation:L=>Ae(L),playReaction:L=>A.current?.playReaction(L),playCelebration:()=>A.current?.playCelebration(),setShowFullAvatar:L=>{A.current&&(z.current=L,A.current.setShowFullAvatar(L))},isReady:J,talkingHead:A.current})),ue.jsxs("div",{className:`simple-talking-avatar-container ${f}`,style:w,children:[ue.jsx("div",{ref:k,className:"talking-head-viewer",style:{width:"100%",height:"100%",minHeight:"400px"}}),te&&ue.jsx("div",{className:"loading-overlay",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"white",fontSize:"18px",zIndex:10},children:"Loading avatar..."}),me&&ue.jsx("div",{className:"error-overlay",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"#ff6b6b",fontSize:"16px",textAlign:"center",zIndex:10,padding:"20px",borderRadius:"8px"},children:me})]})});Ue.displayName="SimpleTalkingAvatar";const We=v.forwardRef(({curriculumData:U=null,avatarConfig:t={},animations:e={},onLessonStart:n=()=>{},onLessonComplete:i=()=>{},onQuestionAnswer:s=()=>{},onCurriculumComplete:o=()=>{},onCustomAction:l=()=>{},autoStart:c=!1},r)=>{const u=v.useRef(null),a=v.useRef({currentModuleIndex:0,currentLessonIndex:0,currentQuestionIndex:0,isTeaching:!1,isQuestionMode:!1,lessonCompleted:!1,curriculumCompleted:!1,score:0,totalQuestions:0}),d=v.useRef({onLessonStart:n,onLessonComplete:i,onQuestionAnswer:s,onCurriculumComplete:o,onCustomAction:l}),h=v.useRef(null),g=v.useRef(null),x=v.useRef(null),f=v.useRef(null),w=v.useRef(null),D=v.useRef(null),p=v.useRef(null),O=v.useRef(U?.curriculum||{title:"Default Curriculum",description:"No curriculum data provided",language:"en",modules:[]}),T=v.useRef({avatarUrl:t.avatarUrl||"/avatars/brunette.glb",avatarBody:t.avatarBody||"F",mood:t.mood||"happy",ttsLang:t.ttsLang||"en",ttsService:t.ttsService||null,ttsVoice:t.ttsVoice||null,ttsApiKey:t.ttsApiKey||null,bodyMovement:t.bodyMovement||"gesturing",movementIntensity:t.movementIntensity||.7,showFullAvatar:t.showFullAvatar!==void 0?t.showFullAvatar:!1,animations:e,lipsyncLang:"en"});v.useEffect(()=>{d.current={onLessonStart:n,onLessonComplete:i,onQuestionAnswer:s,onCurriculumComplete:o,onCustomAction:l}},[n,i,s,o,l]),v.useEffect(()=>{O.current=U?.curriculum||{title:"Default Curriculum",description:"No curriculum data provided",language:"en",modules:[]},T.current={avatarUrl:t.avatarUrl||"/avatars/brunette.glb",avatarBody:t.avatarBody||"F",mood:t.mood||"happy",ttsLang:t.ttsLang||"en",ttsService:t.ttsService||null,ttsVoice:t.ttsVoice||null,ttsApiKey:t.ttsApiKey||null,bodyMovement:t.bodyMovement||"gesturing",movementIntensity:t.movementIntensity||.7,showFullAvatar:t.showFullAvatar!==void 0?t.showFullAvatar:!1,animations:e,lipsyncLang:"en"}},[U,t,e]);const R=v.useCallback(()=>(O.current||{modules:[]}).modules[a.current.currentModuleIndex]?.lessons[a.current.currentLessonIndex],[]),k=v.useCallback(()=>R()?.questions[a.current.currentQuestionIndex],[R]),A=v.useCallback((b,I)=>I.type==="multiple_choice"||I.type==="true_false"?b===I.answer:I.type==="code_test"&&typeof b=="object"&&b!==null?b.passed===!0:!1,[]),z=v.useCallback(()=>{a.current.lessonCompleted=!0,a.current.isQuestionMode=!1;const b=a.current.totalQuestions>0?Math.round(a.current.score/a.current.totalQuestions*100):100;let I="Congratulations! You've completed this lesson";if(a.current.totalQuestions>0?I+=` You got ${a.current.score} correct out of ${a.current.totalQuestions} question${a.current.totalQuestions===1?"":"s"}, achieving a score of ${b} percent. `:I+="! ",b>=80?I+="Excellent work! You have a great understanding of this topic.":b>=60?I+="Good job! You understand most of the concepts.":I+="Keep practicing! You're making progress.",d.current.onLessonComplete({moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,score:a.current.score,totalQuestions:a.current.totalQuestions,percentage:b}),d.current.onCustomAction({type:"lessonComplete",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,score:a.current.score,totalQuestions:a.current.totalQuestions,percentage:b}),u.current){if(u.current.setMood("happy"),e.lessonComplete)try{u.current.playAnimation(e.lessonComplete,!0)}catch{u.current.playCelebration()}const E=O.current||{modules:[]},P=E.modules[a.current.currentModuleIndex],N=a.current.currentLessonIndex<(P?.lessons?.length||0)-1,$=a.current.currentModuleIndex<(E.modules?.length||0)-1,Y=N||$,Q=T.current||{lipsyncLang:"en"};u.current.speakText(I,{lipsyncLang:Q.lipsyncLang,onSpeechEnd:()=>{d.current.onCustomAction({type:"lessonCompleteFeedbackDone",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,score:a.current.score,totalQuestions:a.current.totalQuestions,percentage:b,hasNextLesson:Y})}})}},[e.lessonComplete]),X=v.useCallback(()=>{a.current.curriculumCompleted=!0;const b=O.current||{modules:[]};if(d.current.onCurriculumComplete({modules:b.modules.length,totalLessons:b.modules.reduce((I,E)=>I+E.lessons.length,0)}),u.current){if(u.current.setMood("celebrating"),e.curriculumComplete)try{u.current.playAnimation(e.curriculumComplete,!0)}catch{u.current.playCelebration()}const I=T.current||{lipsyncLang:"en"};u.current.speakText("Amazing! You've completed the entire curriculum! You're now ready to move on to more advanced topics. Well done!",{lipsyncLang:I.lipsyncLang})}},[e.curriculumComplete]),S=v.useCallback(()=>{const b=R();a.current.isQuestionMode=!0,a.current.currentQuestionIndex=0,a.current.totalQuestions=b?.questions?.length||0,a.current.score=0;const I=k();I&&d.current.onCustomAction({type:"questionStart",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,questionIndex:a.current.currentQuestionIndex,totalQuestions:a.current.totalQuestions,question:I,score:a.current.score});const E=()=>{if(!u.current||!I)return;if(u.current.setMood("happy"),e.questionStart)try{u.current.playAnimation(e.questionStart,!0)}catch(N){console.warn("Failed to play questionStart animation:",N)}const P=T.current||{lipsyncLang:"en"};I.type==="code_test"?u.current.speakText(`Let's test your coding skills! Here's your first challenge: ${I.question}`,{lipsyncLang:P.lipsyncLang}):I.type==="multiple_choice"?u.current.speakText(`Now let me ask you some questions. Here's the first one: ${I.question}`,{lipsyncLang:P.lipsyncLang}):I.type==="true_false"?u.current.speakText(`Let's start with some true or false questions. First question: ${I.question}`,{lipsyncLang:P.lipsyncLang}):u.current.speakText(`Now let me ask you some questions. Here's the first one: ${I.question}`,{lipsyncLang:P.lipsyncLang})};if(u.current&&u.current.isReady&&I)E();else if(u.current&&u.current.isReady){const P=T.current||{lipsyncLang:"en"};u.current.speakText("Now let me ask you some questions to test your understanding.",{lipsyncLang:P.lipsyncLang})}else{const P=setInterval(()=>{u.current&&u.current.isReady&&(clearInterval(P),I&&E())},100);setTimeout(()=>{clearInterval(P)},5e3)}},[e.questionStart,R,k]),F=v.useCallback(()=>{const b=R();if(a.current.currentQuestionIndex<(b?.questions?.length||0)-1){u.current&&u.current.stopSpeaking&&u.current.stopSpeaking(),a.current.currentQuestionIndex+=1;const I=k();I&&d.current.onCustomAction({type:"nextQuestion",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,questionIndex:a.current.currentQuestionIndex,totalQuestions:a.current.totalQuestions,question:I,score:a.current.score});const E=()=>{if(!u.current||!I)return;if(u.current.setMood("happy"),u.current.setBodyMovement("idle"),e.nextQuestion)try{u.current.playAnimation(e.nextQuestion,!0)}catch(Q){console.warn("Failed to play nextQuestion animation:",Q)}const P=T.current||{lipsyncLang:"en"},$=R()?.questions?.length||0,Y=a.current.currentQuestionIndex>=$-1;if(I.type==="code_test"){const Q=Y?`Great! Here's your final coding challenge: ${I.question}`:`Great! Now let's move on to your next coding challenge: ${I.question}`;u.current.speakText(Q,{lipsyncLang:P.lipsyncLang})}else if(I.type==="multiple_choice"){const Q=Y?`Alright! Here's your final question: ${I.question}`:`Alright! Here's your next question: ${I.question}`;u.current.speakText(Q,{lipsyncLang:P.lipsyncLang})}else if(I.type==="true_false"){const Q=Y?`Now let's try this final one: ${I.question}`:`Now let's try this one: ${I.question}`;u.current.speakText(Q,{lipsyncLang:P.lipsyncLang})}else{const Q=Y?`Here's your final question: ${I.question}`:`Here's the next question: ${I.question}`;u.current.speakText(Q,{lipsyncLang:P.lipsyncLang})}};if(u.current&&u.current.isReady&&I)E();else if(I){const P=setInterval(()=>{u.current&&u.current.isReady&&(clearInterval(P),E())},100);setTimeout(()=>{clearInterval(P)},5e3)}}else d.current.onCustomAction({type:"allQuestionsComplete",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,totalQuestions:a.current.totalQuestions,score:a.current.score})},[e.nextQuestion,R,k]),Z=v.useCallback(()=>{const b=O.current||{modules:[]},I=b.modules[a.current.currentModuleIndex];if(a.current.currentLessonIndex<(I?.lessons?.length||0)-1){a.current.currentLessonIndex+=1,a.current.currentQuestionIndex=0,a.current.lessonCompleted=!1,a.current.isQuestionMode=!1,a.current.isTeaching=!1,a.current.score=0,a.current.totalQuestions=0;const P=b.modules[a.current.currentModuleIndex],N=a.current.currentLessonIndex<(P?.lessons?.length||0)-1,$=a.current.currentModuleIndex<(b.modules?.length||0)-1,Y=N||$;d.current.onCustomAction({type:"lessonStart",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,hasNextLesson:Y}),d.current.onLessonStart({moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,lesson:R()}),u.current&&(u.current.setMood("happy"),u.current.setBodyMovement("idle"))}else if(a.current.currentModuleIndex<(b.modules?.length||0)-1){a.current.currentModuleIndex+=1,a.current.currentLessonIndex=0,a.current.currentQuestionIndex=0,a.current.lessonCompleted=!1,a.current.isQuestionMode=!1,a.current.isTeaching=!1,a.current.score=0,a.current.totalQuestions=0;const N=b.modules[a.current.currentModuleIndex],$=a.current.currentLessonIndex<(N?.lessons?.length||0)-1,Y=a.current.currentModuleIndex<(b.modules?.length||0)-1,Q=$||Y;d.current.onCustomAction({type:"lessonStart",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,hasNextLesson:Q}),d.current.onLessonStart({moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,lesson:R()}),u.current&&(u.current.setMood("happy"),u.current.setBodyMovement("idle"))}else w.current&&w.current()},[]),G=v.useCallback(()=>{const b=R();let I=null;if(b?.avatar_script&&b?.body){const E=b.avatar_script.trim(),P=b.body.trim(),N=E.match(/[.!?]$/)?" ":". ";I=`${E}${N}${P}`}else I=b?.avatar_script||b?.body||null;if(u.current&&u.current.isReady&&I){a.current.isTeaching=!0,a.current.isQuestionMode=!1,a.current.score=0,a.current.totalQuestions=0,u.current.setMood("happy");let E=!1;if(e.teaching)try{u.current.playAnimation(e.teaching,!0),E=!0}catch(N){console.warn("Failed to play teaching animation:",N)}E||u.current.setBodyMovement("gesturing");const P=T.current||{lipsyncLang:"en"};d.current.onLessonStart({moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,lesson:b}),d.current.onCustomAction({type:"teachingStart",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,lesson:b}),u.current.speakText(I,{lipsyncLang:P.lipsyncLang,onSpeechEnd:()=>{a.current.isTeaching=!1,d.current.onCustomAction({type:"teachingComplete",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,lesson:b,hasQuestions:b.questions&&b.questions.length>0}),b?.code_example&&d.current.onCustomAction({type:"codeExampleReady",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,lesson:b,codeExample:b.code_example})}})}},[e.teaching,R]),te=v.useCallback(b=>{const I=k(),E=A(b,I);if(E&&(a.current.score+=1),d.current.onQuestionAnswer({moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,questionIndex:a.current.currentQuestionIndex,answer:b,isCorrect:E,question:I}),u.current)if(E){if(u.current.setMood("happy"),e.correct)try{u.current.playReaction("happy")}catch{u.current.setBodyMovement("happy")}u.current.setBodyMovement("gesturing");const N=R()?.questions?.length||0;a.current.currentQuestionIndex>=N-1;const $=a.current.currentQuestionIndex<N-1;console.log("[CurriculumLearning] Answer feedback - questionIndex:",a.current.currentQuestionIndex,"totalQuestions:",N,"hasNextQuestion:",$);const Y=I.type==="code_test"?`Great job! Your code passed all the tests! ${I.explanation||""}`:`Excellent! That's correct! ${I.explanation||""}`,Q=T.current||{lipsyncLang:"en"};u.current.speakText(Y,{lipsyncLang:Q.lipsyncLang,onSpeechEnd:()=>{d.current.onCustomAction({type:"answerFeedbackComplete",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,questionIndex:a.current.currentQuestionIndex,isCorrect:!0,hasNextQuestion:$,score:a.current.score,totalQuestions:a.current.totalQuestions})}})}else{if(u.current.setMood("sad"),e.incorrect)try{u.current.playAnimation(e.incorrect,!0)}catch{u.current.setBodyMovement("idle")}u.current.setBodyMovement("gesturing");const N=R()?.questions?.length||0,$=a.current.currentQuestionIndex>=N-1,Y=a.current.currentQuestionIndex<N-1;console.log("[CurriculumLearning] Answer feedback (incorrect) - questionIndex:",a.current.currentQuestionIndex,"totalQuestions:",N,"hasNextQuestion:",Y);const Q=I.type==="code_test"?`Your code didn't pass all the tests. ${I.explanation||"Try again!"}`:`Not quite right, but don't worry! ${I.explanation||""}${$?"":" Let's move on to the next question."}`,ve=T.current||{lipsyncLang:"en"};u.current.speakText(Q,{lipsyncLang:ve.lipsyncLang,onSpeechEnd:()=>{d.current.onCustomAction({type:"answerFeedbackComplete",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,questionIndex:a.current.currentQuestionIndex,isCorrect:!1,hasNextQuestion:Y,score:a.current.score,totalQuestions:a.current.totalQuestions})}})}else{const N=R()?.questions?.length||0;d.current.onCustomAction({type:"answerFeedbackComplete",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,questionIndex:a.current.currentQuestionIndex,isCorrect:E,hasNextQuestion:a.current.currentQuestionIndex<N-1,score:a.current.score,totalQuestions:a.current.totalQuestions,avatarNotReady:!0})}},[e.correct,e.incorrect,k,R,A]),re=v.useCallback(b=>{const I=k();if(!b||typeof b!="object"){console.error("Invalid code test result format. Expected object with {passed: boolean, ...}");return}if(I?.type!=="code_test"){console.warn("Current question is not a code test. Use handleAnswerSelect for other question types.");return}const E={passed:b.passed===!0,results:b.results||[],output:b.output||"",error:b.error||null,executionTime:b.executionTime||null,testCount:b.testCount||0,passedCount:b.passedCount||0,failedCount:b.failedCount||0};d.current.onCustomAction({type:"codeTestSubmitted",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,questionIndex:a.current.currentQuestionIndex,testResult:E,question:I}),p.current&&p.current(E)},[k,A]),me=v.useCallback(()=>{if(a.current.currentQuestionIndex>0){a.current.currentQuestionIndex-=1;const b=k();b&&d.current.onCustomAction({type:"questionStart",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,questionIndex:a.current.currentQuestionIndex,totalQuestions:a.current.totalQuestions,question:b,score:a.current.score});const I=()=>{if(!u.current||!b)return;u.current.setMood("happy"),u.current.setBodyMovement("idle");const E=T.current||{lipsyncLang:"en"};b.type==="code_test"?u.current.speakText(`Let's go back to this coding challenge: ${b.question}`,{lipsyncLang:E.lipsyncLang}):u.current.speakText(`Going back to: ${b.question}`,{lipsyncLang:E.lipsyncLang})};if(u.current&&u.current.isReady&&b)I();else if(b){const E=setInterval(()=>{u.current&&u.current.isReady&&(clearInterval(E),I())},100);setTimeout(()=>{clearInterval(E)},5e3)}}},[k]),he=v.useCallback(()=>{const b=O.current||{modules:[]};if(b.modules[a.current.currentModuleIndex],a.current.currentLessonIndex>0)a.current.currentLessonIndex-=1,a.current.currentQuestionIndex=0,a.current.lessonCompleted=!1,a.current.isQuestionMode=!1,a.current.isTeaching=!1,a.current.score=0,a.current.totalQuestions=0,d.current.onCustomAction({type:"lessonStart",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex}),d.current.onLessonStart({moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,lesson:R()}),u.current&&(u.current.setMood("happy"),u.current.setBodyMovement("idle"));else if(a.current.currentModuleIndex>0){const P=b.modules[a.current.currentModuleIndex-1];a.current.currentModuleIndex-=1,a.current.currentLessonIndex=(P?.lessons?.length||1)-1,a.current.currentQuestionIndex=0,a.current.lessonCompleted=!1,a.current.isQuestionMode=!1,a.current.isTeaching=!1,a.current.score=0,a.current.totalQuestions=0,d.current.onCustomAction({type:"lessonStart",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex}),d.current.onLessonStart({moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,lesson:R()}),u.current&&(u.current.setMood("happy"),u.current.setBodyMovement("idle"))}},[R]),J=v.useCallback(()=>{a.current.currentModuleIndex=0,a.current.currentLessonIndex=0,a.current.currentQuestionIndex=0,a.current.isTeaching=!1,a.current.isQuestionMode=!1,a.current.lessonCompleted=!1,a.current.curriculumCompleted=!1,a.current.score=0,a.current.totalQuestions=0},[]),ye=v.useCallback(b=>{console.log("Avatar is ready!",b);const I=R(),E=I?.avatar_script||I?.body;c&&E&&setTimeout(()=>{h.current&&h.current()},10)},[c,R]);v.useLayoutEffect(()=>{h.current=G,g.current=Z,x.current=z,f.current=F,w.current=X,D.current=S,p.current=te}),v.useImperativeHandle(r,()=>({startTeaching:G,startQuestions:S,handleAnswerSelect:te,handleCodeTestResult:re,nextQuestion:F,previousQuestion:me,nextLesson:Z,previousLesson:he,completeLesson:z,completeCurriculum:X,resetCurriculum:J,getState:()=>({...a.current}),getCurrentQuestion:()=>k(),getCurrentLesson:()=>R(),getAvatarRef:()=>u.current,speakText:async(b,I={})=>{await u.current?.resumeAudioContext?.();const E=T.current||{lipsyncLang:"en"};u.current?.speakText(b,{...I,lipsyncLang:I.lipsyncLang||E.lipsyncLang})},resumeAudioContext:async()=>{if(u.current?.resumeAudioContext)return await u.current.resumeAudioContext();const b=u.current?.talkingHead;if(b?.audioCtx){const I=b.audioCtx;if(I.state==="suspended"||I.state==="interrupted")try{await I.resume(),console.log("Audio context resumed via talkingHead")}catch(E){console.warn("Failed to resume audio context:",E)}}else console.warn("Audio context not available yet")},stopSpeaking:()=>u.current?.stopSpeaking(),pauseSpeaking:()=>u.current?.pauseSpeaking(),resumeSpeaking:async()=>await u.current?.resumeSpeaking(),isPaused:()=>u.current&&typeof u.current.isPaused<"u"?u.current.isPaused:!1,setMood:b=>u.current?.setMood(b),playAnimation:(b,I)=>u.current?.playAnimation(b,I),setBodyMovement:b=>u.current?.setBodyMovement(b),setMovementIntensity:b=>u.current?.setMovementIntensity(b),playRandomDance:()=>u.current?.playRandomDance(),playReaction:b=>u.current?.playReaction(b),playCelebration:()=>u.current?.playCelebration(),setShowFullAvatar:b=>u.current?.setShowFullAvatar(b),setTimingAdjustment:b=>u.current?.setTimingAdjustment(b),lockAvatarPosition:()=>u.current?.lockAvatarPosition(),unlockAvatarPosition:()=>u.current?.unlockAvatarPosition(),triggerCustomAction:(b,I)=>{d.current.onCustomAction({type:b,...I,state:{...a.current}})},handleResize:()=>u.current?.handleResize(),isAvatarReady:()=>u.current?.isReady||!1}),[G,S,te,re,F,Z,z,X,J,k,R]);const j=T.current||{avatarUrl:"/avatars/brunette.glb",avatarBody:"F",mood:"happy",ttsLang:"en",ttsService:null,ttsVoice:null,ttsApiKey:null,bodyMovement:"gesturing",movementIntensity:.7,showFullAvatar:!1,animations:e};return ue.jsx("div",{style:{width:"100%",height:"100%"},children:ue.jsx(Me,{ref:u,avatarUrl:j.avatarUrl,avatarBody:j.avatarBody,mood:j.mood,ttsLang:j.ttsLang,ttsService:j.ttsService,ttsVoice:j.ttsVoice,ttsApiKey:j.ttsApiKey,bodyMovement:j.bodyMovement,movementIntensity:j.movementIntensity,showFullAvatar:j.showFullAvatar,cameraView:"upper",animations:j.animations,onReady:ye,onLoading:()=>{},onError:b=>{console.error("Avatar error:",b)}})})});We.displayName="CurriculumLearning";const Ee={dance:{name:"dance",type:"code-based",variations:["dancing","dancing2","dancing3"],loop:!0,duration:1e4,description:"Celebration dance animation with multiple variations"},happy:{name:"happy",type:"code-based",loop:!0,duration:5e3,description:"Happy, upbeat body movement"},surprised:{name:"surprised",type:"code-based",loop:!1,duration:3e3,description:"Surprised reaction with quick movements"},thinking:{name:"thinking",type:"code-based",loop:!0,duration:8e3,description:"Thoughtful, contemplative movement"},nodding:{name:"nodding",type:"code-based",loop:!1,duration:2e3,description:"Nodding agreement gesture"},shaking:{name:"shaking",type:"code-based",loop:!1,duration:2e3,description:"Shaking head disagreement gesture"},celebration:{name:"celebration",type:"code-based",loop:!1,duration:3e3,description:"Celebration animation for achievements"},energetic:{name:"energetic",type:"code-based",loop:!0,duration:6e3,description:"High-energy, enthusiastic movement"},swaying:{name:"swaying",type:"code-based",loop:!0,duration:8e3,description:"Gentle swaying motion"},bouncing:{name:"bouncing",type:"code-based",loop:!0,duration:4e3,description:"Bouncy, playful movement"},gesturing:{name:"gesturing",type:"code-based",loop:!0,duration:5e3,description:"Teaching gesture animation"},walking:{name:"walking",type:"code-based",loop:!0,duration:6e3,description:"Walking motion"},prancing:{name:"prancing",type:"code-based",loop:!0,duration:4e3,description:"Playful prancing movement"},excited:{name:"excited",type:"code-based",loop:!0,duration:5e3,description:"Excited, energetic movement"}},gt=U=>Ee[U]||null,yt=U=>Ee.hasOwnProperty(U);exports.CurriculumLearning=We;exports.SimpleTalkingAvatar=Ue;exports.TalkingHeadAvatar=Me;exports.TalkingHeadComponent=De;exports.animations=Ee;exports.getActiveTTSConfig=ke;exports.getAnimation=gt;exports.getVoiceOptions=mt;exports.hasAnimation=yt;