@algorisys/tinyfly 0.97.0 → 0.98.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/README.md +7 -7
- package/docs/character-appearance.md +281 -0
- package/docs/editor-guide.md +14 -6
- package/docs/examples.md +1 -1
- package/docs/getting-started.md +1 -1
- package/docs/gsap-compat.md +1 -1
- package/docs/llm-guide.md +21 -1
- package/docs/maps.md +2 -2
- package/docs/props.md +8 -6
- package/docs/teaching.md +1 -1
- package/lib/addons/characters.js +5720 -4476
- package/lib/browser/tinyfly.iife.js +15 -15
- package/lib/browser/tinyfly.js +7928 -6684
- package/lib/browser/tinyfly.umd.js +15 -15
- package/lib/types/characters/capabilities.d.ts +15 -0
- package/lib/types/characters/cast.d.ts +284 -0
- package/lib/types/characters/character.d.ts +22 -4
- package/lib/types/characters/hands/held-items.d.ts +88 -0
- package/lib/types/characters/hands/index.d.ts +1 -0
- package/lib/types/characters/head/ears.d.ts +10 -0
- package/lib/types/characters/head/facial-hair.d.ts +118 -0
- package/lib/types/characters/head/glasses.d.ts +24 -0
- package/lib/types/characters/head/hair.d.ts +560 -0
- package/lib/types/characters/head/hats.d.ts +58 -0
- package/lib/types/characters/head/head-look.d.ts +53 -0
- package/lib/types/characters/head/index.d.ts +5 -0
- package/lib/types/characters/head/shell.d.ts +64 -0
- package/lib/types/characters/index.d.ts +4 -1
- package/lib/types/characters/interactions.d.ts +69 -0
- package/lib/types/characters/props/families/animals.d.ts +6 -0
- package/lib/types/characters/species/human-motion.d.ts +5 -2
- package/lib/types/characters/species/human.d.ts +111 -4
- package/lib/types/characters/wardrobe/basic-outfit.d.ts +19 -5
- package/llms-full.txt +355 -27
- package/llms.txt +29 -28
- package/package.json +1 -1
- package/skills/tinyfly/SKILL.md +10 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
(function(w){"use strict";function xa(t){return typeof t=="object"&&t!==null&&t.type==="cubic-bezier"}function En(t){return typeof t=="object"&&t!==null&&t.type!=="cubic-bezier"}const Bi=2;function Wi(t){return t.some(e=>e.interpolation!==void 0)?2:1}function fs(t){return t.property==="text"&&"textConfig"in t}function re(t){return t.kind==="inertia"&&"inertia"in t}function ae(t){return t.kind==="spring"&&"spring"in t}function qi(t){return t.property==="motionPath"&&"motionPathConfig"in t}function Cf(t){return typeof t=="object"&&t!==null&&"x"in t&&"y"in t&&"angle"in t}function Ia(t){return"keyframes"in t}class Hf{_currentTime=0;_isRunning=!1;onTick=null;get currentTime(){return this._currentTime}get isRunning(){return this._isRunning}start(){this._isRunning=!0}stop(){this._isRunning=!1}tick(e){this._currentTime+=e,this.onTick?.(e,this._currentTime)}reset(){this._currentTime=0}seek(e){this._currentTime=e}}class Rf{_currentTime=0;_isRunning=!1;_lastFrameTime=null;_rafId=null;_speed;onTick=null;constructor(e={}){this._speed=e.speed??1}get currentTime(){return this._currentTime}get isRunning(){return this._isRunning}get speed(){return this._speed}set speed(e){this._speed=e}start(){this._isRunning||(this._isRunning=!0,this._lastFrameTime=null,this._scheduleFrame())}stop(){this._isRunning=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}reset(){this._currentTime=0,this._lastFrameTime=null}seek(e){this._currentTime=e}_scheduleFrame(){this._rafId=requestAnimationFrame(this._onFrame.bind(this))}_onFrame(e){if(this._isRunning){if(this._lastFrameTime!==null){const s=(e-this._lastFrameTime)*this._speed;this._currentTime+=s,this.onTick?.(s,this._currentTime)}this._lastFrameTime=e,this._scheduleFrame()}}}function Oa(t,e){if(!(e>0))return t;const n=1e3/e;return Math.floor(t/n+1e-9)*n}function Ki(t,e,n="start"){if(e<=1)return 0;if(typeof n=="number"){const s=Math.max(0,Math.min(e-1,n));return Math.abs(t-s)}switch(n){case"end":return e-1-t;case"center":return Math.abs(t-(e-1)/2);case"edges":return(e-1)/2-Math.abs(t-(e-1)/2);default:return t}}function Yi(t,e="start"){if(t<=1)return 0;let n=0;for(let s=0;s<t;s++)n=Math.max(n,Ki(s,t,e));return n}function ps(t,e,n){if(n.offsets)return n.offsets[t]??0;const s=n.from??"start",i=Ki(t,e,s);if(n.amount!==void 0){const o=Yi(e,s);return o===0?0:n.amount*i/o}return n.each!==void 0?n.each*i:0}function gs(t,e){return Array.from({length:t},(n,s)=>ps(s,t,e))}function An(t,e){return t<=1?0:Math.max(...gs(t,e))}const Ye=1,zi=6e4,ms=zi/Ye,Bt={stiffness:180,damping:12,mass:1,velocity:0,restDelta:.01,restSpeed:.1},ys={gentle:{stiffness:120,damping:18,mass:1},default:{stiffness:180,damping:12,mass:1},snappy:{stiffness:280,damping:20,mass:1},bouncy:{stiffness:220,damping:8,mass:1},wobbly:{stiffness:180,damping:5,mass:1},stiff:{stiffness:400,damping:30,mass:1}};class $n{from;to;stiffness;damping;mass;restDelta;restSpeed;distance;samples;velocity;settledStep=null;constructor(e){this.from=e.from,this.to=e.to,this.stiffness=e.stiffness??Bt.stiffness,this.damping=e.damping??Bt.damping,this.mass=e.mass??Bt.mass,this.restDelta=e.restDelta??Bt.restDelta,this.restSpeed=e.restSpeed??Bt.restSpeed,this.distance=Math.abs(this.to-this.from)||1,this.samples=[this.from],this.velocity=e.velocity??Bt.velocity,this.isAtRest(this.from)&&(this.settledStep=0)}isAtRest(e){return Math.abs(e-this.to)<this.restDelta*this.distance&&Math.abs(this.velocity)<this.restSpeed*this.distance}valueAt(e){if(e<=0)return this.from;const n=Math.floor(e/Ye);if(this.simulateTo(n+1),this.settledStep!==null&&n>=this.settledStep)return this.to;const s=this.samples[Math.min(n,this.samples.length-1)],i=this.samples[Math.min(n+1,this.samples.length-1)],o=e/Ye-n;return s+(i-s)*o}settleTime(){return this.simulateTo(ms+1),this.settledStep!==null?this.settledStep*Ye:zi}simulateTo(e){if(this.settledStep!==null)return;const n=Math.min(e,ms+1),s=Ye/1e3;for(;this.samples.length<n;){const i=this.samples[this.samples.length-1],o=i-this.to,r=-this.stiffness*o,a=-this.damping*this.velocity,l=(r+a)/this.mass;this.velocity+=l*s;const c=i+this.velocity*s;if(this.samples.push(c),this.isAtRest(c)){this.settledStep=this.samples.length-1;return}}this.samples.length>ms&&(this.settledStep=ms)}}function Lf(t,e){return new $n(t).valueAt(e)}function _a(t){return new $n(t).settleTime()}function Nf(t){const e=t.stiffness??Bt.stiffness,n=t.damping??Bt.damping,s=t.mass??Bt.mass;return n<2*Math.sqrt(e*s)}function Df(t){const e=t.stiffness??Bt.stiffness,n=t.mass??Bt.mass;return 2*Math.sqrt(e*n)}const Xi=4,Ff=.002,jf=1e-4,Ca=6e4;function bs(t){const e=t.friction??Xi;return e>0?e:Xi}function Pn(t){return t.from+t.velocity/bs(t)}function Bf(t,e){if(e===void 0)return t;if(typeof e=="number")return e>0?Math.round(t/e)*e:t;if(e.length===0)return t;let n=e[0];for(const s of e)Math.abs(s-t)<Math.abs(n-t)&&(n=s);return n}function ze(t){let e=Bf(Pn(t),t.end);return t.min!==void 0&&(e=Math.max(t.min,e)),t.max!==void 0&&(e=Math.min(t.max,e)),e}function Xe(t){const e=Math.abs(ze(t)-t.from);if(e===0)return 0;const n=t.restDelta??Math.max(jf,e*Ff);if(n>=e)return 0;const s=Math.log(e/n)/bs(t);return Math.min(Ca,s*1e3)}function ws(t,e){if(e<=0)return t.from;const n=ze(t);if(e>=Xe(t))return n;const s=bs(t);return t.from+(n-t.from)*(1-Math.exp(-s*e/1e3))}function Wf(t,e){const n=bs(t),s=ze(t);return e>=Xe(t)?0:(s-t.from)*n*Math.exp(-n*Math.max(0,e)/1e3)}const ks=t=>t,Ha=t=>t*t,Ra=t=>1-(1-t)*(1-t),La=t=>t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2,Ui=t=>t*t*t,Gi=t=>1-Math.pow(1-t,3),xn=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,Na=Ui,Da=Gi,Fa=xn,qf={linear:ks,"ease-in":Na,"ease-out":Da,"ease-in-out":Fa,"ease-in-quad":Ha,"ease-out-quad":Ra,"ease-in-out-quad":La,"ease-in-cubic":Ui,"ease-out-cubic":Gi,"ease-in-out-cubic":xn};function ja(t){const[e,n,s,i]=t,o=3*e,r=3*(s-e)-o,a=1-o-r,l=3*n,c=3*(i-n)-l,h=1-l-c,d=p=>((a*p+r)*p+o)*p,u=p=>((h*p+c)*p+l)*p,f=p=>(3*a*p+2*r)*p+o,g=p=>{let m=p;for(let k=0;k<8;k++){const y=d(m)-p;if(Math.abs(y)<1e-7)return m;const M=f(m);if(Math.abs(M)<1e-7)break;m-=y/M}let b=0,S=1;for(m=p;b<S;){const k=d(m);if(Math.abs(k-p)<1e-7)return m;p>k?b=m:S=m,m=(b+S)/2}return m};return p=>{if(p<=0)return 0;if(p>=1)return 1;const m=g(p);return u(m)}}function Vi(t,e="out"){if(e==="out")return t;const n=s=>1-t(1-s);return e==="in"?n:s=>s<.5?n(s*2)/2:t(s*2-1)/2+.5}function Ba(t=1,e=.3){const n=Math.max(1,t),s=e/(2*Math.PI)*Math.asin(1/n);return i=>i<=0?0:i>=1?1:n*Math.pow(2,-10*i)*Math.sin((i-s)*(2*Math.PI)/e)+1}const Wa=t=>{if(t<=0)return 0;if(t>=1)return 1;if(t<1/2.75)return 7.5625*t*t;if(t<2/2.75){const i=t-.5454545454545454;return 7.5625*i*i+.75}if(t<2.5/2.75){const i=t-.8181818181818182;return 7.5625*i*i+.9375}const s=t-2.625/2.75;return 7.5625*s*s+.984375};function qa(t=1.70158){return e=>{if(e<=0)return 0;if(e>=1)return 1;const n=e-1;return n*n*((t+1)*n+t)+1}}function Ka(t,e="end"){const n=Math.max(1,Math.floor(t));return s=>{if(s>=1)return 1;if(s<=0)return e==="start"||e==="both"?e==="start"?1/n:1/(n+1):0;const i=Math.floor(s*n);switch(e){case"start":return Math.min(1,(i+1)/n);case"both":return(i+1)/(n+1);case"none":return n===1?0:Math.min(1,i/(n-1));default:return i/n}}}function Ya(t){switch(t.type){case"steps":return Ka(t.count,t.position);case"elastic":return Vi(Ba(t.amplitude,t.period),t.mode);case"bounce":return Vi(Wa,t.mode);case"back":return Vi(qa(t.overshoot),t.mode)}}function xt(t){return t===void 0?ks:xa(t)?ja(t.points):En(t)?Ya(t):qf[t]??ks}const za=32,Kf=256,Ue=new Map,Yf=/[MmLlHhVvCcSsQqTtAaZz]/,zf=/^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/,Xf={M:2,L:2,H:1,V:1,C:6,S:4,Q:4,T:2,A:7,Z:0};function Uf(t){const e=[];let n=0,s=null;const i=()=>{for(;n<t.length&&/[\s,]/.test(t[n]);)n++};for(;n<t.length&&(i(),!(n>=t.length));){const o=t[n];if(Yf.test(o)){s={type:o,args:[]},e.push(s),n++;continue}if(!s)break;const r=s.type==="A"||s.type==="a",a=s.args.length%7;if(r&&(a===3||a===4)){if(o!=="0"&&o!=="1")break;s.args.push(o==="1"?1:0),n++;continue}const l=zf.exec(t.slice(n));if(!l)break;s.args.push(parseFloat(l[0])),n+=l[0].length}return e}function Gf(t,e,n,s,i,o,r,a,l){if(t===a&&e===l)return[];let c=Math.abs(n),h=Math.abs(s);if(c===0||h===0)return[[t,e,a,l,a,l]];const d=i*Math.PI/180,u=Math.cos(d),f=Math.sin(d),g=(t-a)/2,p=(e-l)/2,m=u*g+f*p,b=-f*g+u*p,S=m*m/(c*c)+b*b/(h*h);if(S>1){const _=Math.sqrt(S);c*=_,h*=_}const k=o===r?-1:1,y=c*c*h*h-c*c*b*b-h*h*m*m,M=c*c*b*b+h*h*m*m,$=k*Math.sqrt(Math.max(0,y/M)),E=$*c*b/h,A=-$*h*m/c,T=u*E-f*A+(t+a)/2,I=f*E+u*A+(e+l)/2,v=(_,L,N,x)=>{const R=_*N+L*x,q=Math.sqrt((_*_+L*L)*(N*N+x*x)),U=Math.acos(Math.max(-1,Math.min(1,R/q)));return _*x-L*N<0?-U:U},P=v(1,0,(m-E)/c,(b-A)/h);let H=v((m-E)/c,(b-A)/h,(-m-E)/c,(-b-A)/h);!r&&H>0&&(H-=2*Math.PI),r&&H<0&&(H+=2*Math.PI);const O=Math.max(1,Math.ceil(Math.abs(H)/(Math.PI/2))),C=H/O,j=4/3*Math.tan(C/4),D=_=>{const L=c*Math.cos(_),N=h*Math.sin(_);return[u*L-f*N+T,f*L+u*N+I]},W=_=>{const L=-c*Math.sin(_),N=h*Math.cos(_);return[u*L-f*N,f*L+u*N]},B=[];for(let _=0;_<O;_++){const L=P+_*C,N=L+C,[x,R]=D(L),[q,U]=_===O-1?[a,l]:D(N),[Y,Z]=W(L),[nt,F]=W(N);B.push([x+j*Y,R+j*Z,q-j*nt,U-j*F,q,U])}return B}function le(t,e,n,s,i){const o=1-i;return o*o*o*t+3*o*o*i*e+3*o*i*i*n+i*i*i*s}function Xa(t,e,n,s,i){const o=1-i;return 3*o*o*(e-t)+6*o*i*(n-e)+3*i*i*(s-n)}function In(t,e,n,s){return{subpath:0,type:"L",points:[n,s],startX:t,startY:e,endX:n,endY:s,length:Math.hypot(n-t,s-e)}}function vs(t,e,n){const[s,i,o,r,a,l]=n,c=[0];let h=t,d=e,u=0;for(let f=1;f<=za;f++){const g=f/za,p=le(t,s,o,a,g),m=le(e,i,r,l,g);u+=Math.hypot(p-h,m-d),c.push(u),h=p,d=m}return{subpath:0,type:"C",points:[s,i,o,r,a,l],startX:t,startY:e,endX:a,endY:l,length:u,lengths:c}}function Ae(t){const e=Ue.get(t);if(e)return e;const n=[];let s=0,i=0,o=0,r=0,a=null,l=null,c=-1;const h=new Set,d=p=>{c<0&&(c=0),p.subpath=c,n.push(p)};for(const{type:p,args:m}of Uf(t)){const b=p.toUpperCase(),S=p!==b,k=Xf[b];if(b==="Z"){(s!==o||i!==r)&&d(In(s,i,o,r)),c>=0&&h.add(c),s=o,i=r,a=l=null;continue}for(let y=0;y+k<=m.length;y+=k){const M=m.slice(y,y+k),$=S?s:0,E=S?i:0;let A=null,T=null;switch(b){case"M":y===0?(s=M[0]+$,i=M[1]+E,o=s,r=i,(c<0||n[n.length-1]?.subpath===c)&&c++):(d(In(s,i,M[0]+$,M[1]+E)),s=M[0]+$,i=M[1]+E);break;case"L":d(In(s,i,M[0]+$,M[1]+E)),s=M[0]+$,i=M[1]+E;break;case"H":d(In(s,i,M[0]+$,i)),s=M[0]+$;break;case"V":d(In(s,i,s,M[0]+E)),i=M[0]+E;break;case"C":{const I=[M[0]+$,M[1]+E,M[2]+$,M[3]+E,M[4]+$,M[5]+E];d(vs(s,i,I)),A=[I[2],I[3]],s=I[4],i=I[5];break}case"S":{const[I,v]=a?[2*s-a[0],2*i-a[1]]:[s,i],P=[I,v,M[0]+$,M[1]+E,M[2]+$,M[3]+E];d(vs(s,i,P)),A=[P[2],P[3]],s=P[4],i=P[5];break}case"Q":case"T":{let I=s,v=i;b==="Q"?(I=M[0]+$,v=M[1]+E):l&&(I=2*s-l[0],v=2*i-l[1]);const P=b==="Q"?M[2]+$:M[0]+$,H=b==="Q"?M[3]+E:M[1]+E;d(vs(s,i,[s+2/3*(I-s),i+2/3*(v-i),P+2/3*(I-P),H+2/3*(v-H),P,H])),T=[I,v],s=P,i=H;break}case"A":{const I=M[5]+$,v=M[6]+E;let P=s,H=i;for(const O of Gf(s,i,M[0],M[1],M[2],M[3],M[4],I,v))d(vs(P,H,O)),P=O[4],H=O[5];s=I,i=v;break}}a=A,l=T}}const u=n.reduce((p,m)=>p+m.length,0),f=[];for(let p=0;p<n.length;){const m=n[p].subpath;let b=p,S=0;for(;b<n.length&&n[b].subpath===m;)S+=n[b++].length;const k=n[p],y=n[b-1],M=h.has(m)||Math.abs(y.endX-k.startX)<1e-9&&Math.abs(y.endY-k.startY)<1e-9;f.push({start:p,end:b,length:S,closed:M}),p=b}const g={segments:n,totalLength:u,subpaths:f};return Ue.size>=Kf&&Ue.delete(Ue.keys().next().value),Ue.set(t,g),g}function Vf(t,e){const n=t.lengths;if(e<=0)return 0;if(e>=t.length)return 1;let s=0,i=n.length-1;for(;s<i-1;){const a=s+i>>1;n[a]<e?s=a:i=a}const o=n[i]-n[s],r=o>0?(e-n[s])/o:0;return(s+r)/(n.length-1)}function Jf(t,e){if(t.type==="L"){const d=t.length>0?Math.max(0,Math.min(1,e/t.length)):0;return{x:t.startX+(t.endX-t.startX)*d,y:t.startY+(t.endY-t.startY)*d,angle:Math.atan2(t.endY-t.startY,t.endX-t.startX)*180/Math.PI}}const[n,s,i,o,r,a]=t.points,l=Vf(t,e);let c=Xa(t.startX,n,i,r,l),h=Xa(t.startY,s,o,a,l);if(Math.hypot(c,h)<1e-9){const d=l<.5?Math.min(1,l+.001):Math.max(0,l-.001),u=le(t.startX,n,i,r,d),f=le(t.startY,s,o,a,d),g=le(t.startX,n,i,r,l),p=le(t.startY,s,o,a,l);c=l<.5?u-g:g-u,h=l<.5?f-p:p-f}return{x:le(t.startX,n,i,r,l),y:le(t.startY,s,o,a,l),angle:Math.atan2(h,c)*180/Math.PI}}function Ji(t,e,n=0,s=t.length){if(s<=n)return{x:0,y:0,angle:0};let i=0;for(let o=n;o<s;o++){const r=t[o];if(i+r.length>=e||o===s-1)return Jf(r,e-i);i+=r.length}return{x:0,y:0,angle:0}}function Ua(t,e){const{segments:n,totalLength:s}=Ae(t);return Ji(n,Math.max(0,Math.min(1,e))*s)}function Zf(){Ue.clear()}function Qf(t){return Ae(t).totalLength}const t0=24,e0=320,n0=2.5,On=72,s0=64,i0=.2,o0=128,_n=new Map;let Ms=0,ce;const Ga=t=>Math.round(t*100)/100;function Va(t,e){const{segments:n,subpaths:s,totalLength:i}=Ae(t);if(n.length===0)return[];if(e){const o=s.every(r=>r.closed);return[{segments:n,start:0,end:n.length,length:i,closed:o}]}return s.filter(o=>o.length>0).map(o=>({segments:n,start:o.start,end:o.end,length:o.length,closed:o.closed}))}function Zi(t,e){const n=t.closed?(e%1+1)%1:Math.max(0,Math.min(1,e)),s=Ji(t.segments,n*t.length,t.start,t.end);return[s.x,s.y]}function Ja(t){const e=[];let n=0;for(let s=t.start;s<t.end;s++)n+=t.segments[s].length,t.length>0&&e.push(n/t.length);return e}function Za(t,e){const n=[];for(let s=0;s<e;s++)n.push(Zi(t,t.closed?s/e:s/(e-1)));return n}function Qa(t){let e=0,n=0;for(const[s,i]of t)e+=s,n+=i;return e/=t.length,n/=t.length,t.map(([s,i])=>[s-e,i-n])}function r0(t,e,n){const s=t.closed&&e.closed;if(n!==void 0)return{offset:s?Math.abs(n)%On/On:0,reversed:n<0};const i=Qa(Za(t,On)),o=Qa(Za(e,On)),r=On;let a={offset:0,reversed:!1},l=1/0;for(const c of[!1,!0]){const h=s?r:1;for(let d=0;d<h;d++){let u=0;for(let f=0;f<r&&u<l;f++){const g=s?c?(d-f+r)%r:(f+d)%r:c?r-1-f:f,p=i[f][0]-o[g][0],m=i[f][1]-o[g][1];u+=p*p+m*m}u<l&&(l=u,a={offset:s?d/r:0,reversed:c})}}return a}function a0(t,e,n){return n?((e.reversed?e.offset-t:t+e.offset)%1+1)%1:e.reversed?1-t:t}function l0(t,e,n){return n?((e.reversed?e.offset-t:t-e.offset)%1+1)%1:e.reversed?1-t:t}function c0(t,e,n){const s=t.closed&&e.closed,i=r0(t,e,n.shapeIndex),o=Math.max(t0,Math.min(e0,Math.ceil(Math.max(t.length,e.length)/n0))),r=new Set,a=d=>r.add(Math.round(d*1e7)/1e7);for(let d=0;d<=o;d++)a(d/o);for(const d of Ja(t))a(d);for(const d of Ja(e))a(l0(d,i,s));let l=[...r].sort((d,u)=>d-u);s&&(l=l.filter(d=>d<1));const c=[],h=[];for(const d of l)c.push(...Zi(t,d)),h.push(...Zi(e,a0(d,i,s)));return h0({from:c,to:h,closed:s})}function h0(t){const e=t.from.length/2;if(e<=3)return t;const n=new Uint8Array(e);n[0]=1,n[e-1]=1;const s=[[0,e-1]];for(;s.length>0;){const[r,a]=s.pop();let l=-1,c=i0;for(let h=r+1;h<a;h++){const d=Math.max(tl(t.from,r,a,h),tl(t.to,r,a,h));d>c&&(c=d,l=h)}l!==-1&&(n[l]=1,s.push([r,l],[l,a]))}const i=[],o=[];for(let r=0;r<e;r++)n[r]&&(i.push(t.from[r*2],t.from[r*2+1]),o.push(t.to[r*2],t.to[r*2+1]));return{from:i,to:o,closed:t.closed}}function tl(t,e,n,s){const i=t[e*2],o=t[e*2+1],r=t[n*2]-i,a=t[n*2+1]-o,l=t[s*2]-i,c=t[s*2+1]-o,h=r*r+a*a,d=h===0?0:Math.max(0,Math.min(1,(l*r+c*a)/h));return Math.hypot(l-d*r,c-d*a)}function d0(t,e,n){const s=n.shapeIndex;if(ce&&ce.from===t&&ce.to===e&&ce.shapeIndex===s)return ce.plan;const o=_n.get(String(s??"auto"))?.get(t)?.get(e);if(o)return ce={from:t,to:e,shapeIndex:s,plan:o},o;const r=Ae(t).subpaths.filter(f=>f.length>0).length===Ae(e).subpaths.filter(f=>f.length>0).length,a=Va(t,!r),l=Va(e,!r),c={pairs:a.map((f,g)=>c0(f,l[g],n))};Ms>=o0&&(_n.clear(),Ms=0);const h=String(s??"auto"),d=_n.get(h)??new Map;_n.set(h,d);const u=d.get(t)??new Map;return d.set(t,u),u.set(e,c),Ms++,ce={from:t,to:e,shapeIndex:s,plan:c},c}function el(t,e,n,s={}){if(!t)return e;if(!e)return t;const i=Math.max(0,Math.min(1,n));if(i===0)return t;if(i===1)return e;const o=d0(t,e,s);if(o.pairs.length===0)return i<.5?t:e;let r="";for(const a of o.pairs){for(let l=0;l<a.from.length;l+=2){const c=Ga(a.from[l]+(a.to[l]-a.from[l])*i),h=Ga(a.from[l+1]+(a.to[l+1]-a.from[l+1])*i);r+=`${l===0?r?" M":"M":" L"}${c} ${h}`}a.closed&&(r+=" Z")}return r}function u0(){_n.clear(),Ms=0,ce=void 0}function Ge(t){return/^\s*[Mm]\s*[-+]?(?:\d|\.\d)/.test(t)}const Ve=Math.PI/180,f0=.9995;function Qi(){return[0,0,0,1]}function Wt(t,e){const n=Math.hypot(t[0],t[1],t[2]);if(n===0)return Qi();const s=e*Ve/2,i=Math.sin(s)/n;return[t[0]*i,t[1]*i,t[2]*i,Math.cos(s)]}function p0(t,e,n){return to(to(Wt([0,1,0],e),Wt([1,0,0],t)),Wt([0,0,1],n))}function g0(t){const[e,n,s,i]=he(t),o=2*(e*s+n*i),r=2*(e*n+s*i),a=1-2*(e*e+s*s),l=2*(n*s-e*i),c=1-2*(n*n+s*s),h=2*(e*s-n*i),d=1-2*(e*e+n*n),u=Math.asin(Math.max(-1,Math.min(1,-l)));return Math.abs(l)<.9999999?[u/Ve,Math.atan2(o,d)/Ve,Math.atan2(r,a)/Ve]:[u/Ve,Math.atan2(-h,c)/Ve,0]}function to(t,e){const[n,s,i,o]=t,[r,a,l,c]=e;return[o*r+n*c+s*l-i*a,o*a-n*l+s*c+i*r,o*l+n*a-s*r+i*c,o*c-n*r-s*a-i*l]}function nl(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]}function sl(t){return Math.hypot(t[0],t[1],t[2],t[3])}function he(t){const e=sl(t);return e===0?Qi():[t[0]/e,t[1]/e,t[2]/e,t[3]/e]}function m0(t){return[-t[0],-t[1],-t[2],t[3]]}function il(t,e,n){const s=he(t);let i=he(e),o=nl(s,i);if(o<0&&(i=[-i[0],-i[1],-i[2],-i[3]],o=-o),o>f0)return he([s[0]+(i[0]-s[0])*n,s[1]+(i[1]-s[1])*n,s[2]+(i[2]-s[2])*n,s[3]+(i[3]-s[3])*n]);const r=Math.acos(o),a=Math.sin(r),l=Math.sin((1-n)*r)/a,c=Math.sin(n*r)/a;return he([s[0]*l+i[0]*c,s[1]*l+i[1]*c,s[2]*l+i[2]*c,s[3]*l+i[3]*c])}function y0(t,e){const[n,s,i,o]=he(t),r=2*(s*e[2]-i*e[1]),a=2*(i*e[0]-n*e[2]),l=2*(n*e[1]-s*e[0]);return[e[0]+o*r+(s*l-i*a),e[1]+o*a+(i*r-n*l),e[2]+o*l+(n*a-s*r)]}const b0=Object.freeze(Object.defineProperty({__proto__:null,conjugate:m0,dot:nl,fromAxisAngle:Wt,fromEuler:p0,identity:Qi,length:sl,multiply:to,normalize:he,rotateVec3:y0,slerp:il,toEuler:g0},Symbol.toStringTag,{value:"Module"})),Gt=(t,e,n)=>t+(e-t)*n,ol=512,eo=new Map,no=new Map;function rl(t){const e=eo.get(t);if(e)return e;const n=t.replace("#",""),s=[parseInt(n.slice(0,2),16),parseInt(n.slice(2,4),16),parseInt(n.slice(4,6),16)];return eo.size<ol&&eo.set(t,s),s}const al=t=>t.charCodeAt(0)===35,ll=t=>t.startsWith("rgb"),cl=t=>t.startsWith("rgba"),w0=/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/,so=t=>Math.round(t).toString(16).padStart(2,"0");function k0(t,e,n){return`#${so(t)}${so(e)}${so(n)}`}function hl(t){const e=no.get(t);if(e)return e;const n=t.match(w0);if(!n)throw new Error(`Invalid rgb color: ${t}`);const s=parseInt(n[1],10),i=parseInt(n[2],10),o=parseInt(n[3],10),r=n[4]!==void 0?[s,i,o,parseFloat(n[4])]:[s,i,o];return no.size<ol&&no.set(t,r),r}const dl=(t,e,n)=>{if(al(t)&&al(e)){const[s,i,o]=rl(t),[r,a,l]=rl(e),c=Gt(s,r,n),h=Gt(i,a,n),d=Gt(o,l,n);return k0(c,h,d)}if((ll(t)||cl(t))&&(ll(e)||cl(e))){const s=hl(t),i=hl(e),o=Math.round(Gt(s[0],i[0],n)),r=Math.round(Gt(s[1],i[1],n)),a=Math.round(Gt(s[2],i[2],n));if(s.length===4||i.length===4){const l=s[3]??1,c=i[3]??1,h=Gt(l,c,n);return`rgba(${o}, ${r}, ${a}, ${h})`}return`rgb(${o}, ${r}, ${a})`}return n<1?t:e},ul=(t,e,n)=>{const s=Math.min(t.length,e.length),i=[];for(let o=0;o<s;o++)i.push(Gt(t[o],e[o],n));return i},fl=(t,e,n)=>il(t,e,n),io=(t,e,n)=>n<1?t:e,pl=(t,e,n)=>el(t,e,n);function Cn(t,e){return e==="slerp"?fl:typeof t=="number"?Gt:Array.isArray(t)?ul:typeof t=="string"?t.startsWith("#")||t.startsWith("rgb")?dl:Ge(t)?pl:io:io}const oo=1e3/60;function ro(t,e={}){if(!ae(t))throw new Error(`bakeSpringTrack: track "${t.id}" is not a spring track`);const n=new $n(t.spring);return gl(t,s=>n.valueAt(s),n.settleTime(),t.spring.from,t.spring.to,e)}function ao(t,e={}){if(!re(t))throw new Error(`bakeInertiaTrack: track "${t.id}" is not an inertia track`);const n=t.inertia;return gl(t,s=>ws(n,s),Xe(n),n.from,ze(n),e)}function gl(t,e,n,s,i,o){const r=o.intervalMs??oo,a=o.tolerance??.01,l=t.delay??0,c=[];for(let d=0;d<=n;d+=r)c.push({time:d+l,value:e(d),easing:"linear"});const h=c[c.length-1];return!h||h.time<n+l?c.push({time:n+l,value:i,easing:"linear"}):h.value=i,l>0&&c.unshift({time:0,value:s,easing:"linear"}),{id:t.id,target:t.target,property:t.property,keyframes:a>0?yl(c,a):c,...t.targets&&{targets:[...t.targets]},...t.stagger&&{stagger:{...t.stagger}}}}function lo(t,e,n,s={}){const i=s.intervalMs??oo,o=typeof n=="function"?n:xt(n),r=Cn(t.value,s.interpolation),a=e.time-t.time;if(a<=0)return[e];const l=[];for(let h=i;h<a;h+=i){const d=h/a;l.push({time:t.time+h,value:r(t.value,e.value,o(d)),easing:"linear"})}const c=o(1);return l.push({...e,...c!==1&&{value:r(t.value,e.value,c)},easing:"linear"}),l}function v0(t,e){return ae(t)?ro(t,e):re(t)?ao(t,e):t}function ml(t,e={}){const n=t.keyframes;if(!n.some(o=>En(o.easing)))return t;const s=n.length>0?[n[0]]:[],i={...e,interpolation:t.interpolation??e.interpolation};for(let o=1;o<n.length;o++){const r=n[o];En(r.easing)?s.push(...lo(n[o-1],r,r.easing,i)):s.push(r)}return{...t,keyframes:s}}function M0(t,e){return t.filter(Ia).map(n=>ml(n,e)).concat(t.filter(ae).map(n=>ro(n,e)),t.filter(re).map(n=>ao(n,e)))}function yl(t,e){if(t.length<=2)return t;const n=[t[0]];for(let s=1;s<t.length-1;s++){const i=n[n.length-1],o=t[s],r=t[s+1],a=r.time-i.time;if(a<=0)continue;const l=(o.time-i.time)/a,c=i.value+(r.value-i.value)*l;Math.abs(o.value-c)>e&&n.push(o)}return n.push(t[t.length-1]),n}function Ss(t){const e=[...t.keyframes].sort((n,s)=>n.time-s.time);return{...t,keyframes:e}}function de(t){return t.targets&&t.targets.length>0?t.targets:[t.target]}function Je(t,e,n,s){const i=n??0;return!s||e<=1?i:i+ps(t,e,s)}class Ts{track;targets;constructor(e){this.track=e,this.targets=de(e)}getValueAtTime(e){return this.valueForOffset(e-Je(0,this.targets.length,this.track.delay,this.track.stagger))}getTargetValues(e){const n=this.targets.length,s=[];for(let i=0;i<n;i++){const o=Je(i,n,this.track.delay,this.track.stagger),r=this.valueForOffset(e-o);r!==void 0&&s.push({target:this.targets[i],value:r,start:o+this.track.keyframes[0].time})}return s}getDuration(){const{keyframes:e}=this.track;if(e.length===0)return 0;const n=e[e.length-1].time,s=this.track.stagger?An(this.targets.length,this.track.stagger):0;return n+(this.track.delay??0)+s+(this.track.endDelay??0)}getTrack(){return this.track}valueForOffset(e){const{keyframes:n}=this.track;if(n.length===0)return;if(n.length===1||e<=n[0].time)return n[0].value;if(e>=n[n.length-1].time)return n[n.length-1].value;const{from:s,to:i}=this.findSurroundingKeyframes(e);if(!s||!i)return;if(s.time===e)return s.value;const o=i.time-s.time,r=(e-s.time)/o,l=xt(i.easing)(r);return Cn(s.value,this.track.interpolation)(s.value,i.value,l)}findSurroundingKeyframes(e){const{keyframes:n}=this.track;for(let s=0;s<n.length-1;s++)if(e>=n[s].time&&e<=n[s+1].time)return{from:n[s],to:n[s+1]};return{from:null,to:null}}}class bl{track;targets;sampler;constructor(e){this.track=e,this.targets=de(e),this.sampler=new $n(e.spring)}getValueAtTime(e){return this.sampler.valueAt(e-Je(0,this.targets.length,this.track.delay,this.track.stagger))}getTargetValues(e){const n=this.targets.length,s=[];for(let i=0;i<n;i++){const o=Je(i,n,this.track.delay,this.track.stagger);s.push({target:this.targets[i],value:this.sampler.valueAt(e-o),start:o})}return s}getDuration(){const e=this.track.stagger?An(this.targets.length,this.track.stagger):0;return this.sampler.settleTime()+(this.track.delay??0)+e}getTrack(){return this.track}}class wl{track;targets;duration;constructor(e){this.track=e,this.targets=de(e),this.duration=Xe(e.inertia)}getValueAtTime(e){return ws(this.track.inertia,e-Je(0,this.targets.length,this.track.delay,this.track.stagger))}getTargetValues(e){const n=this.targets.length,s=[];for(let i=0;i<n;i++){const o=Je(i,n,this.track.delay,this.track.stagger);s.push({target:this.targets[i],value:ws(this.track.inertia,e-o),start:o})}return s}getDuration(){const e=this.track.stagger?An(this.targets.length,this.track.stagger):0;return this.duration+(this.track.delay??0)+e}getTrack(){return this.track}}function co(t,e){const n={...Ua(t.pathData,e)};if(t.matrix){const[s,i,o,r,a,l]=t.matrix,{x:c,y:h}=n;n.x=s*c+o*h+a,n.y=i*c+r*h+l;const d=n.angle*Math.PI/180,u=Math.cos(d),f=Math.sin(d);n.angle=Math.atan2(i*u+r*f,s*u+o*f)*180/Math.PI}return t.autoRotate&&t.rotateOffset&&(n.angle+=t.rotateOffset),n}function S0(t,e,n,s){const i=e+(n-e)*s;return co(t,i)}const ho={upperCase:"ABCDEFGHIJKLMNOPQRSTUVWXYZ",lowerCase:"abcdefghijklmnopqrstuvwxyz",upperAndLowerCase:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",numbers:"0123456789"},T0=20;function kl(t){const e=ho[t??"upperCase"]??t??ho.upperCase,n=Array.from(e);return n.length>0?n:Array.from(ho.upperCase)}function E0(t,e,n){let s=(t|0)^Math.imul(e+1,2654435761)^Math.imul(n+1,2246822507);return s=Math.imul(s^s>>>16,2146121005),s=Math.imul(s^s>>>15,2221713035),(s^s>>>16)>>>0}function vl(t,e,n=0){const s=t.from??"",i=t.to,o=Math.max(0,Math.min(1,e));if(o<=0)return s;if(o>=1)return i;const r=Array.from(s),a=Array.from(i),l=t.rightToLeft??!1;if(t.mode==="type"){const S=Math.round(o*Math.max(r.length,a.length));return l?r.slice(0,Math.max(0,r.length-S)).join("")+a.slice(Math.max(0,a.length-S)).join(""):a.slice(0,S).join("")+r.slice(S).join("")}const c=Math.max(0,Math.min(.999,t.revealDelay??0)),h=Math.max(0,(o-c)/(1-c)),d=Math.floor(h*a.length),u=t.tweenLength===!1?a.length:Math.round(r.length+(a.length-r.length)*o),f=kl(t.chars),g=t.refreshRate??T0,p=g>0?Math.floor(n*g/1e3):0,m=t.seed??1;let b="";for(let S=0;S<u;S++){const k=l?S>=u-d:S<d,y=l?a[a.length-(u-S)]:a[S];k&&y!==void 0||y===" "||y===`
|
|
2
|
-
`?b+=y:b+=f[E0(m,S,p)%f.length]}return b}class Ht{id;name;_captions;_tracks=[];_trackPlayers=new Map;_motionPathTracks=new Map;_springTracks=new Map;_textTracks=new Map;_config;_currentTime=0;_playbackState="idle";_direction="forward";_loopIteration=0;_explicitDuration;_repeatDelayRemaining=0;_wrapAfterDelay=!1;onUpdate=null;onComplete=null;constructor(e){if(this.id=e.id,this.name=e.name,this._captions=e.captions,this._config=e.config??{},this._explicitDuration=e.config?.duration,e.tracks)for(const n of e.tracks)this.addTrack(n)}get tracks(){return[...this._tracks]}get duration(){return this._explicitDuration!==void 0?this._explicitDuration:this._calculateDuration()}setDuration(e){if(this._explicitDuration=e,e!==void 0)this._config={...this._config,duration:e};else if(this._config.duration!==void 0){const n={...this._config};delete n.duration,this._config=n}}get currentTime(){return this._currentTime}get playbackState(){return this._playbackState}get direction(){return this._direction}get loopIteration(){return this._loopIteration}get repeatDelayRemaining(){return this._repeatDelayRemaining}get speed(){return this._config.speed??1}set speed(e){this._config.speed=e}get drawingRate(){return this._config.drawingRate??0}set drawingRate(e){const n={...this._config};e>0?n.drawingRate=e:delete n.drawingRate,this._config=n}play(){const e=this.duration;this._direction==="forward"&&this._currentTime>=e&&e>0?(this._currentTime=0,this._loopIteration=0):this._direction==="reverse"&&this._currentTime<=0&&e>0&&(this._currentTime=e,this._loopIteration=0),this._playbackState="playing"}pause(){this._playbackState="paused"}stop(){this._playbackState="idle",this._repeatDelayRemaining=0,this._wrapAfterDelay=!1,this._currentTime=0,this._loopIteration=0,this._direction="forward"}seek(e){const n=this.duration>0?this.duration:1/0;this._currentTime=Math.max(0,Math.min(e,n)),this._repeatDelayRemaining=0,this._wrapAfterDelay=!1}reverse(){this._direction=this._direction==="forward"?"reverse":"forward"}tick(e){if(this._playbackState!=="playing")return;const n=this.duration;if(n<=0)return;let i=e*this.speed;if(this._repeatDelayRemaining>0){const a=Math.min(this._repeatDelayRemaining,i);if(this._repeatDelayRemaining-=a,i-=a,this._repeatDelayRemaining>0){this.onUpdate?.(this.getStateAtTime(this._currentTime));return}this._wrapAfterDelay&&(this._wrapAfterDelay=!1,this._currentTime=0)}const o=1e3;for(let a=0;a<o&&i>0&&this._playbackState==="playing";a++)if(this._direction==="forward"){const l=n-this._currentTime;if(i>=l){if(i-=l,this._currentTime=n,!this._handleEndReached())break}else this._currentTime+=i,i=0}else{const l=this._currentTime;if(i>=l){if(i-=l,this._currentTime=0,!this._handleStartReached())break}else this._currentTime-=i,i=0}const r=this.getStateAtTime(this._currentTime);this.onUpdate?.(r)}getStateAtTime(e){const n=new Map;if(e=Oa(e,this._config.drawingRate??0),this._hasSharedWrites())this._resolveShared(e,n);else for(const[s,i]of this._trackPlayers){const o=i.getTrack().property;for(const{target:r,value:a,start:l}of i.getTargetValues(e))this._write(n,s,r,o,a,e-l)}return{values:n,currentTime:this._currentTime,playbackState:this._playbackState,direction:this._direction,loopIteration:this._loopIteration}}_resolveShared(e,n){const s=new Map;for(const[i,o]of this._trackPlayers){const r=o.getTrack().property;for(const{target:a,value:l,start:c}of o.getTargetValues(e)){const h=`${a}\0${r}`,d=c<=e,u=s.get(h);(!u||(d!==u.started?d:d?c>=u.start:c<=u.start))&&s.set(h,{trackId:i,target:a,property:r,value:l,start:c,started:d})}}for(const{trackId:i,target:o,property:r,value:a,start:l}of s.values())this._write(n,i,o,r,a,e-l)}_write(e,n,s,i,o,r){if(o===void 0)return;let a=e.get(s);a||(a=new Map,e.set(s,a));const l=this._textTracks.get(n);if(l&&typeof o=="number"){a.set("text",vl(l.textConfig,o,Math.max(0,r)));return}const c=this._motionPathTracks.get(n);if(c&&typeof o=="number"){const h=co(c.motionPathConfig,o);a.set("motionPathX",h.x),a.set("motionPathY",h.y),c.motionPathConfig.autoRotate&&a.set("motionPathRotate",h.angle)}else a.set(i,o)}_sharedWrites=null;_hasSharedWrites(){if(this._sharedWrites===null){const e=new Set;this._sharedWrites=!1;t:for(const n of this._tracks)for(const s of de(n)){const i=`${s}\0${n.property}`;if(e.has(i)){this._sharedWrites=!0;break t}e.add(i)}}return this._sharedWrites}addTrack(e){if(this._tracks.push(e),this._sharedWrites=null,re(e)){this._trackPlayers.set(e.id,new wl(e));return}if(ae(e)){this._trackPlayers.set(e.id,new bl(e)),this._springTracks.set(e.id,e);return}if(fs(e))this._trackPlayers.set(e.id,new Ts(e)),this._textTracks.set(e.id,e);else if(qi(e)){const n={id:e.id,target:e.target,property:e.property,keyframes:e.keyframes,delay:e.delay,endDelay:e.endDelay,targets:e.targets,stagger:e.stagger};this._trackPlayers.set(e.id,new Ts(n)),this._motionPathTracks.set(e.id,e)}else this._trackPlayers.set(e.id,new Ts(e))}replaceTrack(e,n){const s=this._tracks.findIndex(o=>o.id===e);if(s<0)return;const i=this._tracks.slice(s+1);this.removeTrack(e);for(const o of i)this.removeTrack(o.id);this.addTrack(n);for(const o of i)this.addTrack(o)}removeTrack(e){this._tracks=this._tracks.filter(n=>n.id!==e),this._sharedWrites=null,this._trackPlayers.delete(e),this._motionPathTracks.delete(e),this._springTracks.delete(e),this._textTracks.delete(e)}getTracks(e={}){return this._tracks.filter(n=>this._matches(n,e))}removeTracks(e={}){const n=this.getTracks(e).map(s=>s.id);for(const s of n)this.removeTrack(s);return n}getTrackSpan(e){const n=this._trackPlayers.get(e);if(!n)return;const s=n.getTrack(),i=s.delay??0;if(ae(s)||re(s))return{from:i,to:n.getDuration()};const o=s.keyframes;if(!(!o||o.length===0))return{from:o[0].time+i,to:n.getDuration()}}findConflicts(){const e=[];for(let n=0;n<this._tracks.length;n++){const s=this._tracks[n],i=this.getTrackSpan(s.id);if(i)for(let o=0;o<n;o++){const r=this._tracks[o];if(r.property!==s.property)continue;const a=de(r).filter(d=>de(s).includes(d));if(a.length===0)continue;const l=this.getTrackSpan(r.id);if(!l||!(l.from<=i.to&&i.from<=l.to))continue;const h=i.from>=l.from;for(const d of a)e.push({target:d,property:s.property,losingTrackId:h?r.id:s.id,winningTrackId:h?s.id:r.id})}}return e}_matches(e,n){if(n.id!==void 0&&e.id!==n.id||n.property!==void 0&&e.property!==n.property||n.target!==void 0&&!de(e).includes(n.target))return!1;if(n.timeRange){const s=this.getTrackSpan(e.id);if(!s||s.to<n.timeRange.from||s.from>n.timeRange.to)return!1}return!0}toDefinition(){return{formatVersion:Wi(this._tracks),id:this.id,name:this.name,config:{...this._config},tracks:[...this._tracks],...this.captions&&{captions:this.captions}}}get config(){return this._config}get markers(){return[...this._config.markers??[]].sort((e,n)=>e.time-n.time)}setMarkers(e){const n=e&&e.length>0?[...e].sort((i,o)=>i.time-o.time).map(i=>({...i})):void 0,s={...this._config};n?s.markers=n:delete s.markers,this._config=s}get captions(){return this._captions}setCaptions(e){const n={};for(const[s,i]of Object.entries(e??{}))n[s]={...i};this._captions=Object.keys(n).length>0?n:void 0}_armRepeatDelay(){this._repeatDelayRemaining=this._config.repeatDelay??0}_calculateDuration(){let e=0;for(const[,n]of this._trackPlayers)e=Math.max(e,n.getDuration());return e}_handleEndReached(){const e=this._config.loop??0;return e===-1||this._loopIteration<e?(this._loopIteration++,this._armRepeatDelay(),this._config.alternate?this._direction="reverse":this._repeatDelayRemaining>0?this._wrapAfterDelay=!0:this._currentTime=0,this._repeatDelayRemaining===0):(this._playbackState="idle",this.onComplete?.(),!1)}_handleStartReached(){const e=this._config.loop??0;return this._config.alternate&&(e===-1||this._loopIteration<e)?(this._loopIteration++,this._armRepeatDelay(),this._direction="forward",this._repeatDelayRemaining===0):(this._playbackState="idle",this.onComplete?.(),!1)}}const A0=100;function uo(t,e,n,s){const i=[],o=[],{duration:r,alternate:a}=s,l=(f,g,p,m)=>{o.push([f,g]);const b=[];t.forEach((S,k)=>{(p==="forward"?(m?S>=f:S>f)&&S<=g:(m?S<=f:S<f)&&S>=g)&&b.push(k)}),b.sort((S,k)=>(p==="forward"?t[S]-t[k]:t[k]-t[S])||S-k);for(const S of b)i.push({kind:"event",index:S,direction:p})};let c=e.time,h=e.direction,d=e.fresh===!0;const u=Math.min(A0,Math.max(0,n.iteration-e.iteration));for(let f=0;f<u;f++){const g=h==="forward"?r:0;l(c,g,h,d),i.push({kind:"repeat"}),a?(h=h==="forward"?"reverse":"forward",c=g,d=!1):(c=h==="forward"?0:r,d=!0)}return u>0&&s.holding&&!a?{crossings:i,passes:o}:(l(c,n.time,h,d),{crossings:i,passes:o})}function Ml(t){return re(t)?{id:t.id,target:t.target,property:t.property,kind:"inertia",inertia:Sl(t.inertia),...Vt(t)}:ae(t)?{id:t.id,target:t.target,property:t.property,kind:"spring",spring:{...t.spring},...Vt(t)}:fs(t)?{id:t.id,target:t.target,property:"text",textConfig:{...t.textConfig},keyframes:t.keyframes.map(fo),...Vt(t)}:qi(t)?{id:t.id,target:t.target,property:"motionPath",motionPathConfig:{...t.motionPathConfig},keyframes:t.keyframes.map(fo),...Vt(t)}:{id:t.id,target:t.target,property:t.property,keyframes:t.keyframes.map(fo),...t.interpolation!==void 0&&{interpolation:t.interpolation},...Vt(t)}}function Sl(t){return{...t,...Array.isArray(t.end)&&{end:[...t.end]}}}function fo(t){return{time:t.time,value:t.value,...t.easing&&{easing:t.easing}}}function Vt(t){const e=t.endDelay;return{...t.delay!==void 0&&{delay:t.delay},...e!==void 0&&{endDelay:e},...t.targets!==void 0&&{targets:[...t.targets]},...t.stagger!==void 0&&{stagger:{...t.stagger}}}}function Tl(t){if(re(t)){const e=t;return{id:e.id,target:e.target,property:e.property,kind:"inertia",inertia:Sl(e.inertia),...Vt(e)}}if(ae(t)){const e=t;return{id:e.id,target:e.target,property:e.property,kind:"spring",spring:{...e.spring},...Vt(e)}}if(fs(t)){const e=t;return{id:e.id,target:e.target,property:"text",textConfig:{...e.textConfig},keyframes:[...e.keyframes].sort((n,s)=>n.time-s.time),...Vt(e)}}if(t.property==="motionPath"&&"motionPathConfig"in t){const e=t,n=[...e.keyframes].sort((s,i)=>s.time-i.time);return{id:e.id,target:e.target,property:"motionPath",motionPathConfig:{...e.motionPathConfig},keyframes:n,...Vt(e)}}return Ss({id:t.id,target:t.target,property:t.property,keyframes:t.keyframes,...t.interpolation!==void 0&&{interpolation:t.interpolation},...Vt(t)})}function El(t){const e=t._config.markers;return{formatVersion:Wi(t.tracks),id:t.id,name:t.name,config:{duration:t.duration>0?t.duration:void 0,loop:t._config.loop,speed:t._config.speed,alternate:t._config.alternate,repeatDelay:t._config.repeatDelay,...t._config.drawingRate?{drawingRate:t._config.drawingRate}:{},...e&&{markers:e.map(n=>({...n}))}},tracks:t.tracks.map(Ml),...t.captions&&{captions:JSON.parse(JSON.stringify(t.captions))}}}function Ze(t){const e=t.formatVersion??1;if(e>Bi)throw new Error(`tinyfly: this animation uses format version ${e}, but this tinyfly reads up to version ${Bi}. Update tinyfly to play it.`);return new Ht({id:t.id,name:t.name,config:t.config,tracks:t.tracks.map(Tl),captions:t.captions})}function $0(t){return JSON.stringify(El(t))}function P0(t){const e=JSON.parse(t);return Ze(e)}function qt(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619);return e>>>0}function $e(t){let e=t>>>0||2654435769;return{seed:t>>>0,next(){return e^=e<<13,e>>>=0,e^=e>>17,e^=e<<5,e>>>=0,e/4294967296}}}function po(t,e,n){return e+t.next()*(n-e)}function Al(t,e,n,s){if(s<=0)return po(t,e,n);const i=Math.floor((n-e)/s),o=Math.round(t.next()*i);return e+o*s}function x0(t,e){if(e.length!==0)return e[Math.floor(t.next()*e.length)]}const $l=/^([+\-*/])=\s*(-?[\d.]+)$/,Pl=/^random\(\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*(?:,\s*(-?[\d.]+)\s*)?\)$/i;function I0(t){return typeof t!="string"?!1:$l.test(t.trim())||Pl.test(t.trim())}function go(t,e={}){if(typeof t!="string")return t;const n=t.trim(),s=$l.exec(n);if(s){const[,o,r]=s,a=e.base??0,l=Number.parseFloat(r);switch(o){case"+":return a+l;case"-":return a-l;case"*":return a*l;case"/":return l===0?a:a/l}}const i=Pl.exec(n);if(i){if(!e.random)throw new Error(`resolveValue: "${n}" needs a random source — pass one via context.random`);const o=Number.parseFloat(i[1]),r=Number.parseFloat(i[2]),a=i[3]!==void 0?Number.parseFloat(i[3]):void 0;return a!==void 0?Al(e.random,o,r,a):po(e.random,o,r)}return t}function xl(t,e=0,n){const s=[];let i=e;for(const o of t){const r=go(o,{base:i,random:n});s.push(r),typeof r=="number"&&(i=r)}return s}class O0{random;constructor(e){this.random=$e(e)}get seed(){return this.random.seed}resolve(e,n=0){return go(e,{base:n,random:this.random})}resolveSequence(e,n=0){return xl(e,n,this.random)}}const _0=600;function Il(t){if(Array.isArray(t)){const[u,f,g,p]=t;return{fn:Cl(u,f,g,p),bezier:[u,f,g,p]}}const{segments:e}=Ae(t);if(e.length===0)throw new Error(`customEase: no curve in "${t}"`);const n=e[0].startX,s=e[0].startY,i=e[e.length-1],o=i.endX-n,r=i.endY-s;if(o===0||r===0)throw new Error(`customEase: "${t}" must move along both axes`);const a=u=>(u-n)/o,l=u=>(u-s)/r;if(e.length===1&&i.type==="C"){const[u,f,g,p]=i.points,m=[a(u),l(f),a(g),l(p)];return{fn:Cl(...m),bezier:m}}const c=[],h=[],d=Math.max(8,Math.ceil(_0/e.length));for(const u of e)for(let f=c.length===0?0:1;f<=d;f++){const[g,p]=C0(u,f/d);c.push(a(g)),h.push(l(p))}return{fn:H0(c,h)}}function Ol(t={}){const n=.1+Math.max(0,Math.min(1,t.strength??.7))*.7,s=[1];for(let o=n;o>.002;o*=n)s.push(2*Math.sqrt(o));const i=s.reduce((o,r)=>o+r,0);return o=>{if(o<=0)return 0;if(o>=1)return 1;let r=o*i;for(let a=0;a<s.length;a++){if(r<=s[a]){if(a===0)return(r/s[0])**2;const l=s[a]/2,c=l*l,h=r-l;return 1-(c-h*h)}r-=s[a]}return 1}}function _l(t={}){const e=Math.max(1,t.wiggles??10),n=t.type??"easeOut",s=i=>n==="uniform"?1:n==="easeInOut"?Math.sin(Math.PI*i):(1-i)**2;return i=>i<=0||i>=1?0:Math.sin(i*e*Math.PI*2)*s(i)}function C0(t,e){if(t.type==="L"){const[c,h]=t.points;return[t.startX+(c-t.startX)*e,t.startY+(h-t.startY)*e]}const[n,s,i,o,r,a]=t.points,l=1-e;return[l*l*l*t.startX+3*l*l*e*n+3*l*e*e*i+e*e*e*r,l*l*l*t.startY+3*l*l*e*s+3*l*e*e*o+e*e*e*a]}function H0(t,e){return n=>{if(n<=t[0])return e[0];if(n>=t[t.length-1])return e[e.length-1];let s=0,i=t.length-1;for(;i-s>1;){const r=s+i>>1;t[r]<=n?s=r:i=r}const o=t[i]-t[s];return o===0?e[i]:e[s]+(n-t[s])/o*(e[i]-e[s])}}function Cl(t,e,n,s){const i=(r,a,l)=>3*(1-r)*(1-r)*r*a+3*(1-r)*r*r*l+r*r*r,o=(r,a,l)=>3*(1-r)*(1-r)*a+6*(1-r)*r*(l-a)+3*r*r*(1-l);return r=>{if(r<=0)return 0;if(r>=1)return 1;let a=r;for(let h=0;h<8;h++){const d=i(a,t,n)-r,u=o(a,t,n);if(Math.abs(d)<1e-6)return i(a,e,s);if(Math.abs(u)<1e-6)break;a-=d/u}let l=0,c=1;a=r;for(let h=0;h<40;h++)i(a,t,n)<r?l=a:c=a,a=(l+c)/2;return i(a,e,s)}}const R0=350,L0=300,N0=550;function D0(t,e={}){const n=e.lead??R0,s=e.gap??L0,i=e.tail??N0,o=[];let r=0;return t.forEach((a,l)=>{const c=[];let h=r+n;a.lines.forEach((u,f)=>{if(!(u.duration>=0))throw new Error(`narration: scene ${l} line ${f} has an invalid duration (${u.duration})`);f>0&&(h+=s),c.push({id:u.id??`s${l}-l${f}`,scene:l,line:f,start:h,end:h+u.duration,text:u.text}),h+=u.duration});const d=h+i+(a.tail??0);o.push({id:a.id??`s${l}`,start:r,duration:d-r,cues:c}),r=d}),{duration:r,scenes:o,cues:o.flatMap(a=>a.cues)}}function F0(t){return t.cues.map(e=>({id:e.id,time:e.start,label:e.text}))}function j0(t,e){let n=t.scenes[0];for(const s of t.scenes)if(e>=s.start)n=s;else break;return n}const mo=t=>6e4/t.bpm;function Es(t,e){return t.offset+e*mo(t)}function As(t,e){return(e-t.offset)/mo(t)}function B0(t,e){return Es(t,Math.round(As(t,e)))}function W0(t,e){return Es(t,Math.ceil(As(t,e)-1e-9))}function q0(t,e,n){const s=Math.max(1,Math.round(t.beatsPerBar??4)),i=[];if(!(t.bpm>0)||n<e)return i;for(let o=Math.ceil(As(t,e)-1e-9);;o++){const r=Es(t,o);if(r>n+1e-9)break;i.push({time:r,bar:(o%s+s)%s===0,n:o})}return i}const Qe=100;function K0(t,e,n={}){const s=n.minBpm??70,i=n.maxBpm??180,o=Math.max(1,Math.round(e/Qe)),r=Math.min(t.length,Math.round((n.maxSeconds??60)*e)),a=Math.floor(r/o);if(a<4)return{bpm:120,offset:0,confidence:0};const l=new Float64Array(a);for(let T=0;T<a;T++){let I=0;for(let v=T*o;v<(T+1)*o;v++)I+=t[v]*t[v];l[T]=Math.log(1e-6+I/o)}const c=new Float64Array(a);for(let T=1;T<a;T++)c[T]=Math.max(0,l[T]-l[T-1]);const h=c.reduce((T,I)=>T+I,0)/a;for(let T=0;T<a;T++)c[T]=Math.max(0,c[T]-h);const d=Math.max(1,Math.floor(60*Qe/i)),u=Math.min(a-1,Math.ceil(60*Qe/s)),f=T=>{let I=0;for(let v=T;v<a;v++)I+=c[v]*c[v-T];return I/(a-T)};let g=0;for(let T=0;T<a;T++)g+=c[T]*c[T];g/=a;let p=d,m=-1/0;for(let T=d;T<=u;T++){const I=60*Qe/T,v=Math.exp(-.5*(Math.log2(I/120)/.9)**2),P=f(T)*v;P>m&&(m=P,p=T)}const b=T=>{const I=Math.floor(T);return I<0||I+1>=a?0:c[I]+(c[I+1]-c[I])*(T-I)},S=(T,I)=>{let v=0;for(let P=I;P<a;P+=T)v+=b(P);return v};let k=p,y=0,M=-1/0;for(let T=p-.6;T<=p+.6+1e-9;T+=.02){if(T<1)continue;const I=Math.max(1,Math.round(T*4));for(let v=0;v<I;v++){const P=v/I*T,H=S(T,P);H>M&&(M=H,y=P,k=T)}}const $=60*Qe/k,E=g>0?Math.max(0,Math.min(1,f(p)/g)):0,A=(y+.5)*1e3/Qe;return{bpm:Math.round($*100)/100,offset:Math.round(A%(6e4/$)),confidence:E}}const Y0=600,z0=250,Hl=1;function X0(t,e){const n=e.target??"Camera",s={x:e.stage.width/2,y:e.stage.height/2},i={},o=(d,u,f,g)=>{const p=i[d]??=[];for(;p.length>0&&p[p.length-1].time>=u;)p.pop();p.push({time:u,value:f,...g?{easing:g}:{}})},r=d=>{const u=d.rotate*Math.PI/180,f=(d.focusX-s.x)*d.scale,g=(d.focusY-s.y)*d.scale;return{x:-(f*Math.cos(u)-g*Math.sin(u)),y:-(f*Math.sin(u)+g*Math.cos(u)),scale:d.scale,rotate:d.rotate}},a=(d,u,f)=>{const g=r(u);for(const p of["x","y","scale","rotate"])o(p,d,g[p],f)};let l={focusX:s.x,focusY:s.y,scale:1,rotate:0};const c=[...t].sort((d,u)=>d.at-u.at),h=c.filter(d=>!("shake"in d));h.length>0&&a(0,l);for(const d of h)if("frame"in d){const u=Math.max(Hl,d.duration??Y0);a(d.at,l),l={focusX:d.frame.focus?.x??s.x,focusY:d.frame.focus?.y??s.y,scale:d.frame.scale??1,rotate:d.frame.rotate??0},a(d.at+u,l,d.easing??(u>Hl?"ease-in-out":void 0))}else{const{follow:u}=d,f=u.lag??z0,g=new Ht({id:"follow",tracks:[{id:"x",target:"s",property:"x",keyframes:u.x}]}),p=S=>g.getStateAtTime(S).values.get("s")?.get("x")??l.focusX,m=[d.at,...u.x.map(S=>S.time).filter(S=>S>d.at&&S<d.until),d.until];a(d.at,l);const b=S=>({focusX:p(S)+(u.lead??0),focusY:u.y??l.focusY,scale:u.scale??l.scale,rotate:l.rotate});for(const S of m){const k=u.x.find(y=>y.time===S)?.easing;a(S+f,b(S),S===d.at?"ease-in-out":k)}l=b(d.until)}for(const d of c.filter(u=>"shake"in u)){const u=d.shake.strength??12,f=d.shake.roll??1.5,g=1e3/(d.shake.frequency??24),p=$e(d.shake.seed??Math.round(d.at)+1),m=()=>p.next()*2-1;for(const b of["shakeX","shakeY","shakeRotate"])o(b,d.at,0);for(let b=d.at+g;b<d.at+d.duration;b+=g){const S=1-(b-d.at)/d.duration;o("shakeX",b,m()*u*S),o("shakeY",b,m()*u*S),o("shakeRotate",b,m()*f*S)}for(const b of["shakeX","shakeY","shakeRotate"])o(b,d.at+d.duration,0,"ease-out")}return Object.entries(i).map(([d,u])=>({id:`${n}-${d}`,target:n,property:d,keyframes:u}))}function Rl(t,e){const n=t.toLowerCase(),s=e.toLowerCase();let i=Array.from({length:s.length+1},(o,r)=>r);for(let o=1;o<=n.length;o++){const r=[o];for(let a=1;a<=s.length;a++)r[a]=Math.min(i[a]+1,r[a-1]+1,i[a-1]+(n[o-1]===s[a-1]?0:1));i=r}return i[s.length]}function Hn(t,e){const n=t.toLowerCase(),s=e.find(r=>r.toLowerCase().includes(n)||n.includes(r.toLowerCase()));if(s&&Math.min(t.length,s.length)>=3)return s;let i,o=1/0;for(const r of e){const a=Rl(t,r);a<o&&(o=a,i=r)}return i!==void 0&&o<=Math.max(2,Math.floor(t.length/3))?i:void 0}function ot(t,e,n,s){const i=typeof e=="string"?s??Hn(e,n):void 0;return`Unknown ${t} ${JSON.stringify(e)}${i?`: did you mean "${i}"?`:"."} Known: ${n.join(", ")}`}function Ll(t,e){const n=e.step??33,s=e.stiffness??120,i=e.damping??9,o=e.mass??1;let r=t(e.start),a=0;const l=[{time:e.start,value:r}];let c=e.start+n;for(let h=e.start+1;h<=e.end;h++){const u=s*(t(h)-r)-i*a;a+=u/o*.001,r+=a*.001,(h>=c||h===e.end)&&(l.push({time:h,value:r}),c+=n)}return l}const Jt=t=>Math.round(t*1e3)/1e3;function Nl(t,e={}){if(t.length===0)return"";const n=e.curviness??1,s=e.closed??!1,i=t.length;let o=`M${Jt(t[0].x)} ${Jt(t[0].y)}`;if(i===1)return o;const r=l=>s?t[(l%i+i)%i]:t[Math.max(0,Math.min(i-1,l))],a=s?i:i-1;for(let l=0;l<a;l++){const c=r(l-1),h=r(l),d=r(l+1),u=r(l+2);if(n===0){o+=` L${Jt(d.x)} ${Jt(d.y)}`;continue}const f=n/6,g=h.x+(d.x-c.x)*f,p=h.y+(d.y-c.y)*f,m=d.x-(u.x-h.x)*f,b=d.y-(u.y-h.y)*f;o+=` C${Jt(g)} ${Jt(p)} ${Jt(m)} ${Jt(b)} ${Jt(d.x)} ${Jt(d.y)}`}return s?`${o} Z`:o}const $t=(t,e=0)=>{const n=parseFloat(t??"");return Number.isFinite(n)?n:e};function U0(t){const e=(t??"").trim().split(/[\s,]+/).filter(Boolean).map(Number),n=[];for(let s=0;s+1<e.length;s+=2)n.push({x:e[s],y:e[s+1]});return n}function $s(t){const e=t.attributes;switch(t.tag.toLowerCase()){case"path":return e.d??null;case"circle":case"ellipse":{const n=$t(e.cx),s=$t(e.cy),i=t.tag.toLowerCase()==="circle"?$t(e.r):$t(e.rx),o=t.tag.toLowerCase()==="circle"?$t(e.r):$t(e.ry);return`M${n+i} ${s} A${i} ${o} 0 1 1 ${n-i} ${s} A${i} ${o} 0 1 1 ${n+i} ${s} Z`}case"rect":{const n=$t(e.x),s=$t(e.y),i=$t(e.width),o=$t(e.height);let r=e.rx!=null?$t(e.rx):e.ry!=null?$t(e.ry):0,a=e.ry!=null?$t(e.ry):r;return r=Math.min(r,i/2),a=Math.min(a,o/2),r===0||a===0?`M${n} ${s} H${n+i} V${s+o} H${n} Z`:`M${n+r} ${s} H${n+i-r} A${r} ${a} 0 0 1 ${n+i} ${s+a} V${s+o-a} A${r} ${a} 0 0 1 ${n+i-r} ${s+o} H${n+r} A${r} ${a} 0 0 1 ${n} ${s+o-a} V${s+a} A${r} ${a} 0 0 1 ${n+r} ${s} Z`}case"line":return`M${$t(e.x1)} ${$t(e.y1)} L${$t(e.x2)} ${$t(e.y2)}`;case"polyline":case"polygon":{const n=U0(e.points);if(n.length===0)return null;const s=n.map((i,o)=>`${o===0?"M":"L"}${i.x} ${i.y}`).join(" ");return t.tag.toLowerCase()==="polygon"?`${s} Z`:s}default:return null}}function G0(t,e,n){const s=Math.max(2,Math.round(n.samples??32)),i=Math.max(0,n.length),o=n.since!==void 0?Math.max(e-i,n.since):e-i;if(o>=e)return[];const r=n.period,a=[];for(let l=0;l<s;l++){const c=o+(e-o)*l/(s-1),h=r&&r>0&&l<s-1?(c%r+r)%r:c;a.push({at:t(h),time:c,age:i>0?(e-c)/i:0})}return a}const V0=2.5;function Dl(t){const e=[],n=[],s=t.length,i=(o,r)=>{for(let a=o+r;a>=0&&a<s;a+=r){const l=(t[a].x-t[o].x)*r,c=(t[a].y-t[o].y)*r,h=Math.hypot(l,c);if(h>1e-9)return[l/h,c/h]}return null};for(let o=0;o<s;o++){const r=t[o],a=i(o,-1),l=i(o,1),c=a??l??[1,0],h=l??a??[1,0];let d=c[0]+h[0],u=c[1]+h[1];const f=Math.hypot(d,u);f<1e-9?(d=c[0],u=c[1]):(d/=f,u/=f);const g=d*c[0]+u*c[1],p=Math.min(V0,1/Math.max(g,1e-6)),m=r.width/2*p;e.push({x:r.x-u*m,y:r.y+d*m}),n.push({x:r.x+u*m,y:r.y-d*m})}return{left:e,right:n}}function Fl(t){const e=t.length;if(e<2)return null;const n=t[e-1];for(let s=e-2;s>=0;s--){const i=n.x-t[s].x,o=n.y-t[s].y,r=Math.hypot(i,o);if(r>1e-9)return{x:n.x,y:n.y,radius:n.width/2,start:Math.atan2(i/r,-o/r)}}return null}function Ps(t,e){return[t[0]+e[0],t[1]+e[1],t[2]+e[2]]}function tn(t,e){return[t[0]-e[0],t[1]-e[1],t[2]-e[2]]}function en(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function ue(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function xs(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function Is(t){return Math.hypot(t[0],t[1],t[2])}function yo(t,e){return Is(tn(t,e))}function Pe(t){const e=Is(t);return e===0?[0,0,0]:en(t,1/e)}function jl(t,e,n){return[t[0]+(e[0]-t[0])*n,t[1]+(e[1]-t[1])*n,t[2]+(e[2]-t[2])*n]}const J0=Object.freeze(Object.defineProperty({__proto__:null,add:Ps,cross:xs,distance:yo,dot:ue,length:Is,lerp:jl,normalize:Pe,scale:en,subtract:tn},Symbol.toStringTag,{value:"Module"})),Z0=Math.PI/180;function Os(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function mt(t,e){const n=new Array(16);for(let s=0;s<4;s++)for(let i=0;i<4;i++){let o=0;for(let r=0;r<4;r++)o+=t[r*4+i]*e[s*4+r];n[s*4+i]=o}return n}function xe(t){return[1,0,0,0,0,1,0,0,0,0,1,0,t[0],t[1],t[2],1]}function Ie(t){return[t[0],0,0,0,0,t[1],0,0,0,0,t[2],0,0,0,0,1]}function zt(t){const[e,n,s,i]=t;return[1-2*(n*n+s*s),2*(e*n+s*i),2*(e*s-n*i),0,2*(e*n-s*i),1-2*(e*e+s*s),2*(n*s+e*i),0,2*(e*s+n*i),2*(n*s-e*i),1-2*(e*e+n*n),0,0,0,0,1]}function bo(t,e,n){const s=zt(e);for(let i=0;i<3;i++)s[i]*=n[0],s[4+i]*=n[1],s[8+i]*=n[2];return s[12]=t[0],s[13]=t[1],s[14]=t[2],s}function Q0(t){const e=new Array(16);for(let n=0;n<4;n++)for(let s=0;s<4;s++)e[s*4+n]=t[n*4+s];return e}function wo(t){const[e,n,s,i,o,r,a,l,c,h,d,u,f,g,p,m]=t,b=e*r-n*o,S=e*a-s*o,k=e*l-i*o,y=n*a-s*r,M=n*l-i*r,$=s*l-i*a,E=c*g-h*f,A=c*p-d*f,T=c*m-u*f,I=h*p-d*g,v=h*m-u*g,P=d*m-u*p,H=b*P-S*v+k*I+y*T-M*A+$*E;if(Math.abs(H)<1e-12)return null;const O=1/H;return[(r*P-a*v+l*I)*O,(s*v-n*P-i*I)*O,(g*$-p*M+m*y)*O,(d*M-h*$-u*y)*O,(a*T-o*P-l*A)*O,(e*P-s*T+i*A)*O,(p*k-f*$-m*S)*O,(c*$-d*k+u*S)*O,(o*v-r*T+l*E)*O,(n*T-e*v-i*E)*O,(f*M-g*k+m*b)*O,(h*k-c*M-u*b)*O,(r*A-o*I-a*E)*O,(e*I-n*A+s*E)*O,(g*S-f*y-p*b)*O,(c*y-h*S+d*b)*O]}function tp(t,e,n,s){const i=1/Math.tan(t*Z0/2),o=1/(n-s);return[i/e,0,0,0,0,i,0,0,0,0,(s+n)*o,-1,0,0,2*s*n*o,0]}function ep(t,e,n,s,i,o){const r=1/(e-t),a=1/(s-n),l=1/(o-i);return[2*r,0,0,0,0,2*a,0,0,0,0,-2*l,0,-(e+t)*r,-(s+n)*a,-(o+i)*l,1]}function np(t,e,n=[0,1,0]){const s=Pe(tn(t,e)),i=Pe(xs(n,s)),o=xs(s,i);return[i[0],o[0],s[0],0,i[1],o[1],s[1],0,i[2],o[2],s[2],0,-ue(i,t),-ue(o,t),-ue(s,t),1]}function Rt(t,e){const n=t[0]*e[0]+t[4]*e[1]+t[8]*e[2]+t[12],s=t[1]*e[0]+t[5]*e[1]+t[9]*e[2]+t[13],i=t[2]*e[0]+t[6]*e[1]+t[10]*e[2]+t[14],o=t[3]*e[0]+t[7]*e[1]+t[11]*e[2]+t[15];return o===1||o===0?[n,s,i]:[n/o,s/o,i/o]}const sp=Object.freeze(Object.defineProperty({__proto__:null,compose:bo,fromQuat:zt,identity:Os,invert:wo,lookAt:np,multiply:mt,orthographic:ep,perspective:tp,scaling:Ie,transformPoint:Rt,translation:xe,transpose:Q0},Symbol.toStringTag,{value:"Module"})),_s={"power1.in":[.55,.085,.68,.53],"power1.out":[.25,.46,.45,.94],"power1.inout":[.455,.03,.515,.955],"power2.in":[.55,.055,.675,.19],"power2.out":[.215,.61,.355,1],"power2.inout":[.645,.045,.355,1],"power3.in":[.895,.03,.685,.22],"power3.out":[.165,.84,.44,1],"power3.inout":[.77,0,.175,1],"power4.in":[.755,.05,.855,.06],"power4.out":[.23,1,.32,1],"power4.inout":[.86,0,.07,1],"sine.in":[.47,0,.745,.715],"sine.out":[.39,.575,.565,1],"sine.inout":[.445,.05,.55,.95],"expo.in":[.95,.05,.795,.035],"expo.out":[.19,1,.22,1],"expo.inout":[1,0,0,1],"circ.in":[.6,.04,.98,.335],"circ.out":[.075,.82,.165,1],"circ.inout":[.785,.135,.15,.86],"back.in":[.6,-.28,.735,.045],"back.out":[.175,.885,.32,1.275],"back.inout":[.68,-.55,.265,1.55]},Bl={none:"linear",linear:"linear","linear.none":"linear","power1.in":"ease-in-quad","power1.out":"ease-out-quad","power1.inout":"ease-in-out-quad","power2.in":"ease-in-cubic","power2.out":"ease-out-cubic","power2.inout":"ease-in-out-cubic"};function ip(t){let e=t.trim().toLowerCase();e=e.replace(/\.ease(in|out|inout)$/,".$1");const n=/^([a-z]+\d?)(\(.*\))?$/.exec(e);return n&&n[1]!=="steps"&&e!=="none"&&e!=="linear"&&(e=`${n[1]}.out${n[2]??""}`),e}xt({type:"bounce",mode:"in"}),xt({type:"bounce",mode:"in-out"});function Rn(t){const e=Wl.get(t.trim().toLowerCase());if(e)return e;const n=ip(t),s=/^steps\(\s*(\d+)\s*\)$/.exec(n);if(s){const r={type:"steps",count:Math.max(1,Number.parseInt(s[1],10))+1,position:"none"};return{easing:r,fn:xt(r)}}const i=/^(elastic|bounce|back)\.(in|out|inout)(?:\(([^)]*)\))?$/.exec(n);if(i){const[,o,r,a]=i,l=(a??"").split(",").map(d=>Number.parseFloat(d)).filter(d=>Number.isFinite(d)),c=r==="inout"?"in-out":r;if(o==="back"&&l.length===0&&n in _s)return{easing:{type:"cubic-bezier",points:_s[n]}};const h=o==="elastic"?{type:"elastic",mode:c,...l[0]!==void 0&&{amplitude:l[0]},...l[1]!==void 0&&{period:l[1]}}:o==="bounce"?{type:"bounce",mode:c}:{type:"back",mode:c,...l[0]!==void 0&&{overshoot:l[0]}};return{easing:h,fn:xt(h)}}return n in Bl?{easing:Bl[n]}:n in _s?{easing:{type:"cubic-bezier",points:_s[n]}}:{easing:"ease-out"}}const Wl=new Map;function ko(t,e){return Wl.set(t.trim().toLowerCase(),e.bezier?{easing:{type:"cubic-bezier",points:e.bezier},fn:e.fn}:{fn:e.fn,requiresBaking:"custom"}),t}function vo(t){let e=t>>>0;return()=>{e=e+1831565813>>>0;let n=e;return n=Math.imul(n^n>>>15,n|1),n^=n+Math.imul(n^n>>>7,n|61),((n^n>>>14)>>>0)/4294967296}}const ql=/^\s*random\(\s*(\[.*\]|[^)]*)\s*\)\s*$/;function Kl(t){return typeof t=="string"&&ql.test(t)}function op(t=1){let e=vo(t);const n=(l,c)=>((...h)=>h.length>=l?c(...h):d=>c(...h,d)),s=(l,c,h)=>Math.min(Math.max(h,Math.min(l,c)),Math.max(l,c)),i=(l,c,h,d,u)=>c===l?h:h+(u-l)/(c-l)*(d-h),o=(l,c)=>{if(typeof l=="number")return l===0?c:Math.round(c/l)*l;if(Array.isArray(l))return Yl(l,c,1/0);if("values"in l)return Yl(l.values,c,l.radius??1/0);const h=Math.round(c/l.increment)*l.increment;return Math.abs(h-c)<=(l.radius??1/0)?h:c},r=(l,c,h)=>{const d=l+e()*(c-l);return h?Math.round(d/h)*h:d};return{clamp:n(3,s),mapRange:n(5,i),normalize:n(3,(l,c,h)=>i(l,c,0,1,h)),interpolate:n(3,(l,c,h)=>{if(typeof l=="object"&&!Array.isArray(l)){const d={};for(const u of Object.keys(l))d[u]=Cn(l[u])(l[u],c[u],h);return d}return Cn(l)(l,c,h)}),wrap:((l,c,h)=>{if(Array.isArray(l)){const p=l,m=b=>p[(Math.round(b)%p.length+p.length)%p.length];return c===void 0?m:m(c)}const d=l,f=c-d,g=p=>f===0?d:((p-d)%f+f)%f+d;return h===void 0?g:g(h)}),wrapYoyo:n(3,(l,c,h)=>{const d=c-l;if(d===0)return l;const u=((h-l)%(d*2)+d*2)%(d*2);return l+(u>d?d*2-u:u)}),snap:n(2,o),random:((l,c,h,d)=>{if(Array.isArray(l)){const f=()=>l[Math.floor(e()*l.length)];return c===!0?f:f()}const u=()=>r(l,c,h);return d?u:u()}),shuffle:l=>{for(let c=l.length-1;c>0;c--){const h=Math.floor(e()*(c+1));[l[c],l[h]]=[l[h],l[c]]}return l},distribute:({base:l=0,amount:c,each:h,from:d="start",ease:u})=>(f,g,p)=>{const m=p.length,S=ps(f,m,{...c!==void 0?{amount:c}:{each:h??1},from:d}),k=c!==void 0?c:(h??1)*Yi(m,d),y=u&&k>0?u(S/k)*k:S;return l+y},pipe:(...l)=>c=>l.reduce((h,d)=>d(h),c),splitColor:l=>rp(l),getUnit:l=>typeof l=="number"?"":/^-?[\d.]+(?:e[-+]?\d+)?([a-z%]*)$/i.exec(l.trim())?.[1]??"",seed:l=>{e=vo(l)},resolveRandomString:l=>{const c=ql.exec(l)?.[1]??"";if(c.startsWith("[")){const g=c.slice(1,-1).split(",").map(p=>p.trim()).filter(Boolean).map(p=>Number.isFinite(Number(p))?Number(p):p.replace(/^['"]|['"]$/g,""));return g[Math.floor(e()*g.length)]}const[h,d,u]=c.split(",").map(f=>Number.parseFloat(f));return r(h,d,Number.isFinite(u)?u:void 0)}}}function Yl(t,e,n){let s=e,i=1/0;for(const o of t){const r=Math.abs(o-e);r<i&&(i=r,s=o)}return i<=n?s:e}function rp(t){const e=t.trim(),n=/^#([0-9a-f]{3,8})$/i.exec(e)?.[1];if(n){const o=(n.length<=4?[...n].map(r=>r+r).join(""):n).match(/../g).map(r=>Number.parseInt(r,16));return o.length>=4?[o[0],o[1],o[2],Math.round(o[3]/255*1e3)/1e3]:[o[0],o[1],o[2]]}const s=(/rgba?\(([^)]+)\)/i.exec(e)?.[1]??"0,0,0").split(/[\s,/]+/).filter(Boolean).map(i=>Number.parseFloat(i));return s.length>=4?[s[0],s[1],s[2],s[3]]:[s[0]??0,s[1]??0,s[2]??0]}const ap=/^([+-])=\s*(-?[\d.]+)$/,lp=/^([<>])\s*(?:([+-])?=?\s*(-?[\d.]+))?$/;function Ln(t,e){const n=e.scale??1,s=c=>Number.parseFloat(c)*n;if(t===void 0)return e.cursor;if(typeof t=="number")return t*n;const i=t.trim();if(i==="")return e.cursor;const o=ap.exec(i);if(o){const c=s(o[2]);return e.cursor+(o[1]==="-"?-c:c)}const r=lp.exec(i);if(r){const c=r[1]==="<"?e.previousStart:e.previousEnd;if(r[3]===void 0)return c;const h=s(r[3]);return c+(r[2]==="-"?-h:h)}const a=/^(.+?)([+-])=\s*(-?[\d.]+)$/.exec(i);if(a){const c=e.labels.get(a[1].trim());if(c!==void 0){const h=s(a[3]);return c+(a[2]==="-"?-h:h)}}const l=e.labels.get(i);return l!==void 0?l:/^-?[\d.]+$/.test(i)?s(i):e.cursor}function cp(t){if(typeof t!="object"||t===null)return!1;const e=t;return e.grid!==void 0||e.from==="random"||Array.isArray(e.from)||e.ease!==void 0||e.axis!==void 0}function hp(t,e,n={}){if(t===0)return[];const s=e.grid==="auto"?Math.max(1,Math.min(t,n.columnsFromLayout?.()??t)):Array.isArray(e.grid)?Math.max(1,e.grid[1]):t,i=Array.isArray(e.grid)?Math.max(1,e.grid[0]):Math.ceil(t/s),o=g=>({x:g%s,y:Math.floor(g/s)}),r=e.from??"start",a=Array.isArray(r)?{x:r[0]*(s-1),y:r[1]*(i-1)}:typeof r=="number"?o(Math.max(0,Math.min(t-1,r))):r==="end"?o(t-1):r==="center"||r==="edges"?{x:(s-1)/2,y:(i-1)/2}:{x:0,y:0},l=g=>{const{x:p,y:m}=o(g),b=Math.abs(p-a.x),S=Math.abs(m-a.y);return e.axis==="x"?b:e.axis==="y"?S:Math.hypot(b,S)};let c=Array.from({length:t},(g,p)=>l(p));const h=Math.max(...c);if(r==="edges"&&(c=c.map(g=>h-g)),r==="random"){const g=n.random??Math.random;c=c.map(()=>g()*h)}const d=e.amount!==void 0?e.amount:(e.each??0)*h,u=e.ease?Rn(e.ease):void 0,f=u?u.fn??xt(u.easing):void 0;return c.map(g=>{const p=h===0?0:g/h;return(f?f(p):p)*d})}const Mo=new Set(["duration","delay","ease","repeat","repeatDelay","yoyo","stagger","onComplete","onUpdate","onStart","onRepeat","onReverseComplete","repeatRefresh","keyframes","easeEach","scrollTo","id","immediateRender","overwrite","paused","scrollTrigger","spring"]),dp={rotation:"rotate",rotationZ:"rotate",rotationX:"rotateX",rotationY:"rotateY",transformPerspective:"perspective",perspective:"childPerspective"};function Cs(t){const e={},n={};for(const[s,i]of Object.entries(t))Mo.has(s)?e[s]=i:n[dp[s]??s]=i;return{config:e,properties:n}}function Hs(t,e){return t===void 0?e:t*1e3}function So(t,e){if(t!==void 0)return typeof t=="number"?{each:t*1e3}:cp(t)?{offsets:hp(e?.count??0,t,e??{}).map(s=>s*1e3)}:{...t.each!==void 0&&{each:t.each*1e3},...t.amount!==void 0&&{amount:t.amount*1e3},...t.from!==void 0&&{from:t.from}}}const up={opacity:1,x:0,y:0,z:0,rotate:0,rotateX:0,rotateY:0,rotateZ:0,scale:1,scaleX:1,scaleY:1,scaleZ:1,skewX:0,skewY:0,originX:50,originY:50,perspective:0,blur:0,glow:0,clipTop:0,clipRight:0,clipBottom:0,clipLeft:0};function zl(t){return up[t]}function fp(t){const e=typeof t=="string"||Array.isArray(t)?{path:t}:t;if(!e||typeof e.path!="string"&&!Array.isArray(e.path))throw new Error("gsap-compat: motionPath needs a path — SVG path data or an array of { x, y } points.");let n;if(Array.isArray(e.path))n=Nl(e.path,{curviness:e.curviness});else if(Ge(e.path))n=e.path;else throw new Error(`gsap-compat: motionPath "${e.path}" is not path data. Selectors and elements are resolved by live.to(); timeline() and tf need the path data itself.`);const s={pathData:n};return e.autoRotate!==void 0&&e.autoRotate!==!1&&(s.autoRotate=!0,typeof e.autoRotate=="number"&&(s.rotateOffset=e.autoRotate)),e.matrix&&(s.matrix=e.matrix),{config:s,start:e.start??0,end:e.end??1}}function pp(t){const e=typeof t=="string"||Array.isArray(t)?{path:t}:{...t};return{...e,start:e.end??1,end:e.start??0}}function Xl(t){return typeof t=="object"&&t!==null&&"shape"in t?t.shape:t}function gp(t){if(t.morphSVG===void 0)return t;const{morphSVG:e,...n}=t,s=Xl(e);if(typeof s!="string"||!Ge(s))throw new Error(`gsap-compat: morphSVG "${String(s)}" is not path data. Selectors and elements are resolved by live.to(); timeline() and tf need the path data itself.`);return{...n,d:s}}function mp(t,e){if(t===!0)return[0,e];if(t===!1)return[0,0];if(typeof t=="number")return[0,Ul(t,e)];const n=t.trim().split(/[\s,]+/).filter(Boolean),s=r=>{const a=Number.parseFloat(r);if(Number.isNaN(a))throw new Error(`gsap-compat: drawSVG "${t}" is not a length or percentage`);return Ul(r.endsWith("%")?e*a/100:a,e)};if(n.length===0)return[0,e];if(n.length===1)return[0,s(n[0])];const i=s(n[0]),o=s(n[1]);return i<=o?[i,o]:[o,i]}function yp(t,e){const[n,s]=mp(t,e);return{strokeDasharray:[s-n,e],strokeDashoffset:-n}}function bp(t,e){if(t.drawSVG===void 0)return t;const{drawSVG:n,...s}=t;return{...s,...yp(n,e)}}function wp(t){if(t.drawSVG!==void 0)throw new Error("gsap-compat: drawSVG needs the stroke length from the page. Use live.to(), or animate strokeDasharray / strokeDashoffset directly (see drawSvgProperties).");return t}function Ul(t,e){return Math.max(0,Math.min(e,t))}function kp(t){let e=2166136261;for(let n=0;n<t.length;n++)e=Math.imul(e^t.charCodeAt(n),16777619);return e>>>0}function vp(t,e,n){if(t.scrambleText!==void 0){const s=t.scrambleText,i=typeof s=="string"?{text:s}:s;if(typeof i?.text!="string")throw new Error("gsap-compat: scrambleText needs the text to end on — a string, or { text }.");const o=i.revealDelay&&n>0?i.revealDelay*1e3/n:void 0;return{to:i.text,mode:"scramble",...i.chars!==void 0&&{chars:i.chars},...i.speed!==void 0&&{refreshRate:20*i.speed},...o!==void 0&&{revealDelay:Math.min(o,.999)},...i.tweenLength!==void 0&&{tweenLength:i.tweenLength},...i.rightToLeft!==void 0&&{rightToLeft:i.rightToLeft},seed:i.seed??kp(`${e}|${i.text}`)}}if(t.text!==void 0){const s=t.text,i=typeof s=="string"?{value:s}:s;if(typeof i?.value!="string")throw new Error("gsap-compat: text needs the text to end on — a string, or { value }.");return{to:i.value,mode:"type",...i.rightToLeft!==void 0&&{rightToLeft:i.rightToLeft}}}}function To(t){return Math.max(.1,t/25)}function Mp(t,e){const n=typeof e=="number"?{velocity:e}:e;if(typeof n?.velocity!="number"||!Number.isFinite(n.velocity))throw new Error("gsap-compat: inertia needs a velocity for each property — a number, or { velocity }.");const s=n.friction??(n.resistance!==void 0?To(n.resistance):void 0),i={from:t,velocity:n.velocity,...s!==void 0&&{friction:s},...n.min!==void 0&&{min:n.min},...n.max!==void 0&&{max:n.max}};return typeof n.end=="function"?i.end=[n.end(Pn(i))]:n.end!==void 0&&(i.end=Array.isArray(n.end)?[...n.end]:n.end),i}function Sp(t){const e=t===!0?{}:typeof t=="string"?{preset:t}:t;if(e.preset!==void 0&&!(e.preset in ys))throw new Error(`gsap-compat: unknown spring preset "${e.preset}" — use one of ${Object.keys(ys).join(", ")}`);return{...e.preset?ys[e.preset]:{},...e.stiffness!==void 0&&{stiffness:e.stiffness},...e.damping!==void 0&&{damping:e.damping},...e.mass!==void 0&&{mass:e.mass},...e.restDelta!==void 0&&{restDelta:e.restDelta}}}function Tp(t,e){if(t===!0||typeof t=="string")return;const n=t.velocity;return typeof n=="number"?n:n?.[e]}class Oe{timeline;options;cursor=0;fallbackRandom=vo(1);previousStart=0;previousEnd=0;labels=new Map;trackCounter=0;lastValues=new Map;constructor(e={}){this.options=e,this.timeline=new Ht({id:e.id??"gsap-compat",name:e.name,config:{...e.repeat!==void 0&&{loop:e.repeat},...e.yoyo!==void 0&&{alternate:e.yoyo},...e.repeatDelay!==void 0&&{repeatDelay:e.repeatDelay*1e3},...e.timeScale!==void 0&&{speed:e.timeScale}}})}to(e,n,s){return this.build(e,void 0,Nn(n),s)}from(e,n,s){const{config:i,properties:o}=Cs(Nn(n)),{motionPath:r,text:a,scrambleText:l,...c}=o,h=this.targetsOf(e)[0],d={...i};for(const g of Object.keys(c))d[g]=this.resolveStart(h,g);r!==void 0&&(d.motionPath=pp(r));const u={},f=String(this.resolveStart(h,"text"));return a!==void 0&&(u.text=Eo(a),d.text=typeof a=="object"?{...a,value:f}:f),l!==void 0&&(u.text=Eo(l),d.scrambleText=typeof l=="object"?{...l,text:f}:f),this.build(e,{...c,...u},d,s)}fromTo(e,n,s,i){const{properties:o}=Cs(Nn(n));return this.build(e,o,Nn(s),i)}set(e,n,s){return this.build(e,void 0,{...Nn(n),duration:0},s)}get lastStart(){return this.previousStart}get lastEnd(){return this.previousEnd}addEvent(e){const n=Math.max(0,Ln(e,this.context()));return this.previousStart=n,this.previousEnd=n,this.cursor=Math.max(this.cursor,n),n}timeOf(e){return Ln(e,this.context())}addLabel(e,n){return this.labels.set(e,Ln(n,this.context())),this}labelTimes(){return[...this.labels.values()].sort((e,n)=>e-n)}labelTime(e){return this.labels.get(e)}add(e,n){const s=Ln(n,this.context());for(const o of e.timeline.tracks){if(!("keyframes"in o))continue;const r=Ss({...o,id:this.nextTrackId(`nested-${o.id}`),keyframes:o.keyframes.map(a=>({...a,time:a.time+s}))});this.timeline.addTrack(r)}const i=s+e.timeline.duration;return this.previousStart=s,this.previousEnd=i,this.cursor=Math.max(this.cursor,i),this}play(){return this.timeline.play(),this}pause(){return this.timeline.pause(),this}restart(){return this.timeline.stop(),this.timeline.play(),this}reverse(){return this.timeline.reverse(),this}kill(){return this.timeline.removeTracks(),this}reset(){return this.timeline.removeTracks(),this.cursor=0,this.previousStart=0,this.previousEnd=0,this.labels.clear(),this.lastValues.clear(),this.trackCounter=0,this}seek(e){if(typeof e=="string"){const n=this.labels.get(e);return n!==void 0&&this.timeline.seek(n),this}return this.timeline.seek(e*1e3),this}progress(e){const n=this.timeline.duration;return e!==void 0&&n>0&&this.timeline.seek(e*n),n>0?this.timeline.currentTime/n:0}timeScale(e){return e!==void 0&&(this.timeline.speed=e),this.timeline.speed}duration(){return this.timeline.duration/1e3}tick(e){return this.timeline.tick(e),this}toDefinition(){return this.timeline.toDefinition()}build(e,n,s,i){const{config:o,properties:r}=Cs(s),{motionPath:a,text:l,scrambleText:c,inertia:h,...d}=r,u=this.targetsOf(e),f=Ln(i,this.context()),g=Hs(o.delay,0),p=Hs(o.duration,500),m=So(o.stagger,{count:u.length,columnsFromLayout:this.options.layoutColumns?()=>this.options.layoutColumns(u):void 0,random:this.options.random??this.fallbackRandom}),b=this.easingFor(o.ease),S=[],k=o.spring;let y=0,M=!1;for(const[v,P]of Object.entries(d)){const H=P;let O=n?.[v]!==void 0?n[v]:this.resolveStart(u[0],v);if(typeof O!=typeof H&&(this.warn(`no usable start value for "${v}" on "${u[0]}" — it will snap to ${String(H)}. Use fromTo() to animate it.`),O=H),k!==void 0&&(typeof O!="number"||typeof H!="number")&&this.warn(`spring works on numbers, so "${v}" on "${u[0]}" eases instead`),k!==void 0&&typeof O=="number"&&typeof H=="number"){const D={...Sp(k),from:O,to:H,velocity:Tp(k,v)??this.options.startVelocity?.(u[0],v)??0},W=this.nextTrackId(`${u[0]}-${v}-spring`),B={id:W,target:u[0],...u.length>1&&{targets:u},...m&&u.length>1&&{stagger:m},property:v,kind:"spring",spring:D,delay:f+g};this.timeline.addTrack(B),S.push(W),y=Math.max(y,_a(D));for(const _ of u)this.lastValues.set(`${_}|${v}`,H);continue}M=!0;const C=this.keyframesFor(O,H,p,b,o.ease),j=this.nextTrackId(`${u[0]}-${v}`);this.timeline.addTrack(Ss({id:j,target:u[0],...u.length>1&&{targets:u},...m&&u.length>1&&{stagger:m},property:v,delay:f+g,keyframes:C,...v==="quaternion"&&{interpolation:"slerp"}})),S.push(j);for(const D of u)this.lastValues.set(`${D}|${v}`,H)}const $=vp({text:l,scrambleText:c},u[0],p);if($){const v=n?.text??n?.scrambleText,P=v!==void 0?Eo(v):this.resolveStart(u[0],"text"),H=this.nextTrackId(`${u[0]}-text`),O={id:H,target:u[0],...u.length>1&&{targets:u},...m&&u.length>1&&{stagger:m},property:"text",textConfig:{from:typeof P=="string"?P:String(P??""),...$},delay:f+g,keyframes:this.keyframesFor(0,1,p,b,o.ease)};this.timeline.addTrack(O),S.push(H);for(const C of u)this.lastValues.set(`${C}|text`,$.to)}if(a!==void 0){const{config:v,start:P,end:H}=fp(a),O=this.nextTrackId(`${u[0]}-motionPath`),C={id:O,target:u[0],...u.length>1&&{targets:u},...m&&u.length>1&&{stagger:m},property:"motionPath",motionPathConfig:v,delay:f+g,keyframes:this.keyframesFor(P,H,p,b,o.ease)};this.timeline.addTrack(C),S.push(O)}if(h!==void 0)for(const[v,P]of Object.entries(h)){const H=this.resolveStart(u[0],v);if(typeof H!="number"){this.warn(`inertia on "${v}" needs a numeric start value; skipped`);continue}const O=Mp(H,P),C=this.nextTrackId(`${u[0]}-${v}-inertia`),j={id:C,target:u[0],...u.length>1&&{targets:u},...m&&u.length>1&&{stagger:m},property:v,kind:"inertia",inertia:O,delay:f+g};this.timeline.addTrack(j),S.push(C),y=Math.max(y,Xe(O));for(const D of u)this.lastValues.set(`${D}|${v}`,ze(O))}const T=((h!==void 0||k!==void 0)&&!M&&!$&&a===void 0?y:Math.max(p,y))+(m&&u.length>1?An(u.length,m):0),I=f+g+T;return this.previousStart=f+g,this.previousEnd=I,this.cursor=Math.max(this.cursor,I),{trackIds:S,start:f+g,end:I,kill:()=>{for(const v of S)this.timeline.removeTrack(v)}}}keyframesFor(e,n,s,i,o){const r={time:0,value:e};if(s<=0)return[{time:0,value:n}];const a=typeof o=="string"?Rn(o):void 0;if(a?.requiresBaking==="custom"||this.options.bakeEases&&En(i)){const c=a?.fn??xt(i);return[r,...lo(r,{time:s,value:n},c,{intervalMs:this.options.bakeIntervalMs})]}return[r,{time:s,value:n,...i&&{easing:i}}]}resolveStart(e,n){const s=this.lastValues.get(`${e}|${n}`);if(s!==void 0)return s;const i=this.options.startValue?.(e,n);if(i!==void 0)return i;const o=this.options.defaults?.[n];if(o!==void 0)return o;if(n==="text")return"";if(n==="quaternion")return[0,0,0,1];if(n==="d")throw new Error(`gsap-compat: no starting shape for "${e}". Use fromTo({ d: … }, { morphSVG: … }), or live.to(), which reads the element's current shape.`);const r=zl(n);return r!==void 0?(this.warn(`no start value for "${n}" on "${e}" — using the static default ${r}. GSAP would read the live DOM here; tinyfly cannot, so pass an explicit fromTo() or a defaults map.`),r):(this.warn(`no start value or default for "${n}" on "${e}" — using 0`),0)}easingFor(e){if(e!==void 0){if(typeof e=="string")return Rn(e).easing;if(typeof e=="function")throw new Error('gsap-compat: function eases cannot be serialized. Use a named ease, or a cubic-bezier via { type: "cubic-bezier", points: [...] }.');return e}}targetsOf(e){return Array.isArray(e)?e:[e]}context(){return{cursor:this.cursor,previousStart:this.previousStart,previousEnd:this.previousEnd,labels:this.labels,scale:1e3}}nextTrackId(e){return this.trackCounter+=1,`${e}-${this.trackCounter}`}warn(e){this.options.onWarning?.(`gsap-compat: ${e}`)}}function Eo(t){if(typeof t=="string")return t;if(t&&typeof t=="object"){const e=t;return String(e.value??e.text??"")}return String(t??"")}function Ep(t){return new Oe(t)}function Nn(t){return wp(gp(t))}function Ap(t){return!Array.isArray(t)||t.length!==4?null:`matrix3d(${zt(he(t)).map(n=>Math.round(n*1e6)/1e6+0).join(", ")})`}const $p=new Set(["blur","brightness","glow","glowColor","shadowX","shadowY","shadowBlur","shadowColor"]),Pp="#ffffff",xp="rgba(0, 0, 0, 0.5)";function Ip(t){const e=[];if(t.blur!==void 0&&e.push(`blur(${Math.max(0,t.blur)}px)`),t.brightness!==void 0&&e.push(`brightness(${Math.max(0,t.brightness)})`),t.glow!==void 0&&e.push(`drop-shadow(0 0 ${Math.max(0,t.glow)}px ${t.glowColor??Pp})`),t.shadowX!==void 0||t.shadowY!==void 0||t.shadowBlur!==void 0){const n=t.shadowX??0,s=t.shadowY??0,i=Math.max(0,t.shadowBlur??0);e.push(`drop-shadow(${n}px ${s}px ${i}px ${t.shadowColor??xp})`)}return e.length>0?e.join(" "):null}function Op(t,e){const n=t.childNodes.length===1?t.firstChild:null;if(n&&n.nodeType===3){const s=n;s.data!==e&&(s.data=e);return}t.textContent!==e&&(t.textContent=e)}function _p(t){if(!("ownerSVGElement"in t))return;const e=t.style;!e||e.transformBox||(e.transformBox="fill-box",e.transformOrigin||(e.transformOrigin="50% 50%"))}const Gl=new Set(["width","height","top","right","bottom","left","margin","marginTop","marginRight","marginBottom","marginLeft","padding","paddingTop","paddingRight","paddingBottom","paddingLeft","borderRadius","borderWidth","fontSize","lineHeight","letterSpacing","outlineWidth","gap","rowGap","columnGap"]),Cp=new Set(["x","y","z","rotate","rotateX","rotateY","rotateZ","scale","scaleX","scaleY","scaleZ","skewX","skewY","quaternion","motionPathX","motionPathY","motionPathRotate"]),Hp=["x","motionPathX","y","motionPathY","z","rotate","rotateZ","motionPathRotate","rotateX","rotateY","quaternion","scale","scaleX","scaleY","scaleZ","skewX","skewY"],Rp=new Set(["childPerspective","perspectiveOriginX","perspectiveOriginY"]),Lp=new Set(["originX","originY"]),Np=new Set(["clipTop","clipRight","clipBottom","clipLeft"]),Dp=new Set(["drawOn"]),Fp={fill:"backgroundColor",stroke:"borderColor",strokeWidth:"borderWidth",color:"color",backgroundColor:"backgroundColor",borderColor:"borderColor"},Vl={fill:"fill",stroke:"stroke",strokeWidth:"strokeWidth",strokeDasharray:"strokeDasharray",strokeDashoffset:"strokeDashoffset",fillOpacity:"fillOpacity",strokeOpacity:"strokeOpacity"},jp="http://www.w3.org/2000/svg";class _e{targets=new Map;registerTarget(e,n){this.targets.set(e,n)}unregisterTarget(e){this.targets.delete(e)}getTarget(e){return this.targets.get(e)}clearTargets(){this.targets.clear()}applyState(e){for(const[n,s]of e.values){const i=this.targets.get(n);i&&this.applyProperties(i,s)}}applyProperties(e,n){let s=null,i=null,o=null,r=null,a=null;const l=n.has("motionPathX"),c=n.has("motionPathY"),h=n.has("motionPathRotate");for(const[g,p]of n)if(!(g==="x"&&l)&&!(g==="y"&&c)&&!((g==="rotate"||g==="rotateZ")&&h)&&!Dp.has(g)){if(Cp.has(g))(s??={})[g]=p;else if(Rp.has(g))typeof p=="number"&&((i??={})[g]=p);else if(Lp.has(g))typeof p=="number"&&((o??={})[g]=p);else if(Np.has(g))typeof p=="number"&&((r??={})[g]=p);else if($p.has(g))(a??={})[g]=p;else if(g!=="perspective"){if(g!=="shine")if(g==="text"&&typeof p=="string")Op(e,p);else if(g==="d"&&typeof p=="string"){const m=e;(m.tagName?.toLowerCase()==="path"?m:m.querySelector?.("path"))?.setAttribute?.("d",p)}else this.applyStyleProperty(e,g,p)}}const d=n.get("shine");typeof d=="number"&&this.applyShine(e,d);const u=[],f=n.get("perspective");if(typeof f=="number"&&f>0&&u.push(`perspective(${f}px)`),s)for(const g of Hp){const p=s[g];if(p===void 0)continue;const m=this.buildTransformPart(g,p);m&&u.push(m)}if(u.length>0&&(e.style.transform=u.join(" "),_p(e)),i&&(i.childPerspective!==void 0&&(e.style.perspective=`${i.childPerspective}px`),(i.perspectiveOriginX!==void 0||i.perspectiveOriginY!==void 0)&&(e.style.perspectiveOrigin=`${i.perspectiveOriginX??50}% ${i.perspectiveOriginY??50}%`)),o){const g=o.originX??50,p=o.originY??50;e.style.transformOrigin=`${g}% ${p}%`}if(r){const g=r.clipTop??0,p=r.clipRight??0,m=r.clipBottom??0,b=r.clipLeft??0;e.style.clipPath=`inset(${g}% ${p}% ${m}% ${b}%)`}if(a){const g=Ip(a);g&&(e.style.filter=g)}}buildTransformPart(e,n){if(e==="quaternion")return Ap(n);if(typeof n!="number")return null;switch(e){case"x":case"motionPathX":return`translateX(${n}px)`;case"y":case"motionPathY":return`translateY(${n}px)`;case"z":return`translateZ(${n}px)`;case"rotate":case"rotateZ":case"motionPathRotate":return`rotate(${n}deg)`;case"rotateX":return`rotateX(${n}deg)`;case"rotateY":return`rotateY(${n}deg)`;case"scale":return`scale(${n})`;case"scaleX":return`scaleX(${n})`;case"scaleY":return`scaleY(${n})`;case"scaleZ":return`scaleZ(${n})`;case"skewX":return`skewX(${n}deg)`;case"skewY":return`skewY(${n}deg)`;default:return null}}applyShine(e,n){e.dataset.shineBase||(e.dataset.shineBase=e.style.color||"currentColor");const s=e.dataset.shineBase,i=-20+n*140,o=e.style;o.color="transparent",o.backgroundImage=`linear-gradient(105deg, transparent 40%, rgba(255, 255, 255, 0.9) 50%, transparent 60%), linear-gradient(${s}, ${s})`,o.backgroundSize="250% 100%, 100% 100%",o.backgroundPosition=`${i}% 0, 0 0`,o.backgroundRepeat="no-repeat",o.webkitBackgroundClip="text",o.backgroundClip="text"}applyStyleProperty(e,n,s){let i;if(e.namespaceURI===jp&&n in Vl){const a=Array.isArray(s)?s.join(", "):String(s);e.style[Vl[n]]=a;return}else n==="fill"&&e.dataset?.elementType==="text"?i="color":i=Fp[n]??n;let r;typeof s=="number"?Gl.has(n)||Gl.has(i)?r=`${s}px`:r=String(s):Array.isArray(s)?r=s.join(", "):r=s,e.style[i]=r}}const Bp={request:t=>requestAnimationFrame(t),cancel:t=>cancelAnimationFrame(t)};class Jl{adapter=new _e;scheduler;rootOption;onWarning;names=new WeakMap;elements=new Map;nameCounter=0;objectNames=new WeakMap;objects=new Map;owned=new Set;currentCollector;tickerCallbacks=new Set;tickerTime=0;tickerFrame=0;liveTimelines=new Set;utils=op();active=new Map;applied=new Map;dirty=new Set;frameId=null;lastTimestamp=null;destroyed=!1;constructor(e={}){this.scheduler=e.scheduler??Bp,this.rootOption=e.root,this.onWarning=e.onWarning}get root(){return this.rootOption??document}resolveTargets(e){const n=[];for(const s of this.targetsOf(e)){const i=this.nameFor(s);Ao(s)&&this.currentCollector?.touch(s,i),n.push(i)}return n}query(e){return this.selectorRoot.querySelector(e)}get collector(){return this.currentCollector}setCollector(e){this.currentCollector=e}forget(e){this.applied.delete(e),this.dirty.delete(e)}get selectorRoot(){return this.currentCollector?.scope??this.root}elementFor(e){return this.elements.get(e)}objectFor(e){return this.objects.get(e)}appliedValue(e,n){return this.applied.get(e)?.get(n)}velocityOf(e,n){for(const i of[...this.active.keys()].reverse()){if(i.getTracks({target:e,property:n}).length===0)continue;const o=i.currentTime;if(o<4)return 0;const r=i.getStateAtTime(o).values.get(e)?.get(n),a=i.getStateAtTime(o-4).values.get(e)?.get(n);if(typeof r!="number"||typeof a!="number")return;const l=(r-a)/4;return(i.direction==="reverse"?-l:l)*1e3}}ticker={add:e=>{this.destroyed||(this.tickerCallbacks.size===0&&(this.tickerTime=0,this.tickerFrame=0),this.tickerCallbacks.add(e),this.currentCollector?.track({revert:()=>this.ticker.remove(e)}),this.startLoop())},remove:e=>{this.tickerCallbacks.delete(e),this.running||this.stopLoop()}};activate(e,n={}){this.destroyed||(e.onUpdate=s=>this.write(s),this.active.delete(e),this.active.set(e,n),this.startLoop())}deactivate(e){this.active.delete(e),this.running||this.stopLoop()}own(e){return this.destroyed?e.destroy():this.owned.add(e),e}destroy(){this.destroyed=!0;for(const e of this.owned)e.destroy();this.owned.clear();for(const e of this.active.keys())e.stop();this.active.clear(),this.stopLoop(),this.adapter.clearTargets(),this.elements.clear(),this.names=new WeakMap,this.objects.clear(),this.objectNames=new WeakMap,this.tickerCallbacks.clear(),this.liveTimelines.clear(),this.applied.clear(),this.dirty.clear()}apply(e,n){if(this.destroyed)return;const s=new Map(Object.entries(n));this.write({values:new Map([[e,s]]),currentTime:0,playbackState:"idle",direction:"forward",loopIteration:0}),this.flush()}render(e){this.destroyed||(this.write(e.getStateAtTime(e.currentTime)),this.flush())}tick(e){const n=[...this.active];for(const[s]of n)s.duration<=0?(this.write(s.getStateAtTime(0)),s.stop()):s.tick(e);this.flush();for(const[s,i]of n)i.onUpdate?.(),s.playbackState!=="playing"&&this.active.get(s)===i&&this.active.delete(s);this.flush(),this.runTicker(e),this.running||this.stopLoop()}get running(){return this.active.size>0||this.tickerCallbacks.size>0}runTicker(e){if(this.tickerCallbacks.size!==0){this.tickerTime+=e,this.tickerFrame+=1;for(const n of[...this.tickerCallbacks])n(this.tickerTime/1e3,e,this.tickerFrame)}}write(e){for(const[n,s]of e.values){let i=this.applied.get(n);i||(i=new Map,this.applied.set(n,i));for(const[o,r]of s)i.set(o,r);this.dirty.add(n)}}flush(){if(this.dirty.size===0)return;const e=new Map;for(const n of this.dirty){const s=this.applied.get(n),i=this.objects.get(n);if(i)for(const[o,r]of s)i[o]=r;else e.set(n,s)}this.dirty.clear(),e.size!==0&&this.adapter.applyState({values:e,currentTime:0,playbackState:"playing",direction:"forward",loopIteration:0})}frame=e=>{this.frameId=null;const n=this.lastTimestamp===null?0:e-this.lastTimestamp;this.lastTimestamp=e,n>0&&this.tick(n),this.running&&this.frameId===null&&(this.frameId=this.scheduler.request(this.frame))};startLoop(){this.frameId===null&&(this.lastTimestamp=null,this.frameId=this.scheduler.request(this.frame))}stopLoop(){this.frameId!==null&&this.scheduler.cancel(this.frameId),this.frameId=null,this.lastTimestamp=null}targetsOf(e){if(typeof e=="string")return Array.from(this.selectorRoot.querySelectorAll(e));if(Ao(e))return[e];if(!Wp(e))return[e];const n=[];for(const s of Array.from(e))n.push(...this.targetsOf(s));return n}nameFor(e){return Ao(e)?this.elementName(e):this.objectName(e)}objectName(e){const n=this.objectNames.get(e);if(n)return n;let s;do this.nameCounter+=1,s=`obj-${this.nameCounter}`;while(this.objects.has(s)||this.elements.has(s));return this.objectNames.set(e,s),this.objects.set(s,e),s}elementName(e){const n=this.names.get(e);if(n)return n;let s=e.id?`#${e.id}`:"";if(!s||this.elements.has(s))do this.nameCounter+=1,s=`el-${this.nameCounter}`;while(this.elements.has(s));return this.names.set(e,s),this.elements.set(s,e),this.adapter.registerTarget(s,e),s}}function Ao(t){return typeof t=="object"&&t!==null&&t.nodeType===1}function Wp(t){if(Array.isArray(t))return!0;const e=t;return typeof e.length=="number"&&typeof e.item=="function"}function Rs(t){const e=t.style;if(!e)return t.getBoundingClientRect();const n=e.transform;e.transform="none";const s=t.getBoundingClientRect();return e.transform=n,s}const Zl=t=>typeof t=="object"&&t!==null&&t.nodeType===1;function qp(t){const e={};for(const n of Array.from(t.attributes))e[n.name]=n.value;return e}function Kp(t){const e=t.getScreenCTM?.();if(e)return[e.a,e.b,e.c,e.d,e.e,e.f];const n=t.getBoundingClientRect();return[1,0,0,1,n.left,n.top]}function Yp(t,e){const n=typeof t=="string"||Array.isArray(t)||Zl(t)?{path:t}:t,{align:s,alignOrigin:i,path:o,...r}=n,a=$=>{const E=Zl($)?$:e.query($);return E||e.warn(`gsap-compat: motionPath could not find "${String($)}"`),E};let l=null,c="";if(Array.isArray(o)||typeof o=="string"&&Ge(o))c=o;else{l=a(o);const $=l&&$s({tag:l.localName,attributes:qp(l)});l&&!$&&e.warn(`gsap-compat: motionPath element <${l.localName}> has no path geometry`),c=$??""}const h={...r,path:c};if(s===void 0||s===!1)return h;const d=s===!0?l:a(s);if(!d)return s===!0&&e.warn("gsap-compat: motionPath align: true needs the path to be an element"),h;const u=e.targets[0];if(!u)return h;const[f,g,p,m,b,S]=Kp(d),k=Rs(u),[y,M]=i??[.5,.5];for(const $ of e.targets.slice(1)){const E=Rs($);if(Math.abs(E.left-k.left)>.5||Math.abs(E.top-k.top)>.5){e.warn("gsap-compat: motionPath align measures the first target; the others are laid out elsewhere");break}}return h.matrix=[f,g,p,m,b-k.left-y*k.width,S-k.top-M*k.height],h}const Ql=t=>typeof t=="object"&&t!==null&&t.nodeType===1;function tc(t){const e={};for(const n of Array.from(t.attributes))e[n.name]=n.value;return e}function ec(t){if(!t)return null;const e=$s({tag:t.localName,attributes:tc(t)});return e||(t.querySelector("path")?.getAttribute("d")??null)}function zp(t,e,n){const s=Xl(t);if(typeof s=="string"&&Ge(s))return s;const i=Ql(s)?s:typeof s=="string"?e(s):null,o=ec(i);return o||(n(`gsap-compat: morphSVG could not find a shape for "${String(s)}"`),"")}const Xp=new Set(["cx","cy","r","rx","ry","x","y","width","height","x1","y1","x2","y2","points"]);function Up(t,e=document){return(typeof t=="string"?Array.from(e.querySelectorAll(t)):Ql(t)?[t]:Array.from(t)).map(s=>{if(s.localName==="path")return s;const i=$s({tag:s.localName,attributes:tc(s)});if(!i||!s.parentNode)return s;const o=s.ownerDocument.createElementNS("http://www.w3.org/2000/svg","path");for(const r of Array.from(s.attributes))Xp.has(r.name)||o.setAttribute(r.name,r.value);return o.setAttribute("d",i),s.parentNode.replaceChild(o,s),o})}const nc=.3;class sc{options;target;running=!1;dragging=!1;passedTolerance=!1;lastX=0;lastY=0;startX=0;startY=0;velocityX=0;velocityY=0;lastTime=0;constructor(e){this.options=e,this.target=e.target}start(){if(this.running)return;this.running=!0;const e=this.options.type??["pointer","touch"];e.includes("pointer")&&(this.target.addEventListener("pointerdown",this.onPointerDown),this.target.addEventListener("pointermove",this.onPointerMove),this.target.addEventListener("pointerup",this.onPointerUp),this.target.addEventListener("pointercancel",this.onPointerUp)),e.includes("touch")&&(this.target.addEventListener("touchstart",this.onTouchStart,{passive:!1}),this.target.addEventListener("touchmove",this.onTouchMove,{passive:!1}),this.target.addEventListener("touchend",this.onTouchEnd)),e.includes("wheel")&&this.target.addEventListener("wheel",this.onWheel,{passive:!1})}stop(){this.running&&(this.running=!1,this.target.removeEventListener("pointerdown",this.onPointerDown),this.target.removeEventListener("pointermove",this.onPointerMove),this.target.removeEventListener("pointerup",this.onPointerUp),this.target.removeEventListener("pointercancel",this.onPointerUp),this.target.removeEventListener("touchstart",this.onTouchStart),this.target.removeEventListener("touchmove",this.onTouchMove),this.target.removeEventListener("touchend",this.onTouchEnd),this.target.removeEventListener("wheel",this.onWheel))}destroy(){this.stop()}get velocity(){return{x:this.velocityX,y:this.velocityY}}begin(e,n,s){this.dragging=!0,this.passedTolerance=!1,this.startX=e,this.startY=n,this.lastX=e,this.lastY=n,this.velocityX=0,this.velocityY=0,this.lastTime=ic(),this.options.onPress?.(this.stateFrom(0,0,s))}move(e,n,s){if(!this.dragging)return;const i=e-this.lastX,o=n-this.lastY;this.lastX=e,this.lastY=n;const r=e-this.startX,a=n-this.startY,l=this.options.tolerance??3;if(!this.passedTolerance){if(Math.hypot(r,a)<l)return;this.passedTolerance=!0}this.updateVelocity(i,o),this.options.preventDefault!==!1&&s.cancelable&&s.preventDefault(),this.options.onMove?.(this.stateFrom(i,o,s))}end(e){this.dragging&&(this.dragging=!1,this.options.onRelease?.(this.stateFrom(0,0,e)))}updateVelocity(e,n){const s=ic(),i=Math.max(1,s-this.lastTime);this.lastTime=s;const o=e/i*1e3,r=n/i*1e3;this.velocityX+=(o-this.velocityX)*nc,this.velocityY+=(r-this.velocityY)*nc}stateFrom(e,n,s){return{deltaX:e,deltaY:n,velocityX:this.velocityX,velocityY:this.velocityY,totalX:this.lastX-this.startX,totalY:this.lastY-this.startY,isDragging:this.dragging,event:s}}onPointerDown=e=>{const n=e,s=this.target;if(typeof n.pointerId=="number"&&typeof s.setPointerCapture=="function")try{s.setPointerCapture(n.pointerId)}catch{}this.begin(n.clientX,n.clientY,e)};onPointerMove=e=>{const n=e;this.move(n.clientX,n.clientY,e)};onPointerUp=e=>this.end(e);onTouchStart=e=>{const n=e.touches[0];n&&this.begin(n.clientX,n.clientY,e)};onTouchMove=e=>{const n=e.touches[0];n&&this.move(n.clientX,n.clientY,e)};onTouchEnd=e=>this.end(e);onWheel=e=>{const n=e;this.options.preventDefault!==!1&&n.cancelable&&n.preventDefault(),this.updateVelocity(n.deltaX,n.deltaY),this.options.onMove?.({deltaX:n.deltaX,deltaY:n.deltaY,velocityX:this.velocityX,velocityY:this.velocityY,totalX:0,totalY:0,isDragging:!1,event:e})}}function ic(){return typeof performance<"u"?performance.now():Date.now()}function oc(t,e,n){let s={delta:0,line:null},i=n;for(const o of t)for(const r of e){const a=Math.abs(r-o);a<=i&&(i=a,s={delta:r-o,line:r})}return s}function rc(t,e){return e<=0?[]:t.map(n=>Math.round(n/e)*e)}class $o{options;observer;x;y;originX=0;originY=0;snappedX=null;snappedY=null;constructor(e){this.options=e,this.x=e.initialX??0,this.y=e.initialY??0,this.observer=new sc({target:e.target,onPress:n=>{const s=e.getPosition?.();s&&(this.x=s.x,this.y=s.y),this.originX=this.x,this.originY=this.y,e.onPress?.(n)},onMove:n=>this.handleMove(n),onRelease:n=>e.onRelease?.(n)})}start(){this.observer.start()}stop(){this.observer.stop()}destroy(){this.observer.destroy()}get position(){return{x:this.x,y:this.y}}get velocity(){return this.observer.velocity}setPosition(e,n){const s=this.options.axis??"both";this.x=s==="y"?this.x:this.applyConstraints(e,"x"),this.y=s==="x"?this.y:this.applyConstraints(n,"y")}get snapLines(){return{x:this.snappedX,y:this.snappedY}}snapThreshold(){if(this.options.snapThreshold!==void 0)return this.options.snapThreshold;const e=this.options.snap??0;return e>0?e/2:8}handleMove(e){this.setPosition(this.originX+e.totalX,this.originY+e.totalY),this.options.mode==="scrub"&&this.scrub(),this.options.onDrag?.(this.position,e),this.options.onSnap?.(this.snapLines)}scrub(){const e=this.options.timeline;if(!e)return;const n=e.duration;if(n<=0)return;const s=this.options.scrubDistance??500;if(s===0)return;const i=(this.options.axis??"both")==="y"?this.y:this.x,o=Gp(i/s);e.pause(),e.seek(o*n)}applyConstraints(e,n){let s=e;const i=[...rc([s],this.options.snap??0),...(n==="x"?this.options.snapLinesX:this.options.snapLinesY)??[]],o=oc([s],i,this.snapThreshold());s+=o.delta,n==="x"?this.snappedX=o.line:this.snappedY=o.line;const r=this.options.bounds;if(r){const a=n==="x"?r.minX:r.minY,l=n==="x"?r.maxX:r.maxY;a!==void 0&&(s=Math.max(a,s)),l!==void 0&&(s=Math.min(l,s))}return s}}function Gp(t){return t<0?0:t>1?1:t}function Vp(t){const e=new $o(t);return e.start(),e}const Jp={x:"x",y:"y","x,y":"both"},Po=t=>typeof t=="object"&&t!==null&&t.nodeType===1;function ac(t,e){const n=Rs(t),s=e.getBoundingClientRect();return{minX:s.left-n.left,maxX:s.right-n.right,minY:s.top-n.top,maxY:s.bottom-n.bottom}}function lc(t){return Array.isArray(t)?[...t]:t}function Zp(t,e,n,s={}){const[i]=e.resolveTargets(n),o=i?e.elementFor(i):void 0;if(!i||!o)throw new Error(`gsap-compat: live.draggable could not find ${String(n)}`);if(s.type==="rotation")return Qp(t,e,i,o,s);const r=Jp[s.type??"x,y"],a=()=>{const p=e.appliedValue(i,"x"),m=e.appliedValue(i,"y");return{x:typeof p=="number"?p:0,y:typeof m=="number"?m:0}},l=typeof s.bounds=="string"?e.query(s.bounds):Po(s.bounds)?s.bounds:null,h={bounds:(!l&&s.bounds&&!Po(s.bounds)?s.bounds:void 0)??(l?ac(o,l):void 0)};let d=null;const u=()=>{d?.kill(),d=null},f=p=>{const m=s.inertia===!0?{}:s.inertia,b=m.friction??(m.resistance!==void 0?To(m.resistance):4),S=a(),k=h.bounds??{};let y,M;const $=m.end;if(Array.isArray($)){const A=Pn({from:S.x,velocity:r==="y"?0:p.x,friction:b}),T=Pn({from:S.y,velocity:r==="x"?0:p.y,friction:b});let I=$[0];for(const v of $)Math.hypot(v.x-A,v.y-T)<Math.hypot(I.x-A,I.y-T)&&(I=v);I&&(y=[I.x],M=[I.y])}else typeof $=="number"?(y=$,M=$):$&&(y=lc($.x),M=lc($.y));const E={};r!=="y"&&(E.x={velocity:p.x,friction:b,min:k.minX,max:k.maxX,end:y}),r!=="x"&&(E.y={velocity:p.y,friction:b,min:k.minY,max:k.maxY,end:M}),d=t.to(o,{inertia:E,onComplete:()=>s.onThrowComplete?.()})},g=new $o({target:o,axis:r,snap:s.snap,get bounds(){return h.bounds},getPosition:a,onPress:()=>{u(),l&&(h.bounds=ac(o,l)),s.onPress?.()},onDrag:p=>{e.apply(i,r==="x"?{x:p.x}:r==="y"?{y:p.y}:{x:p.x,y:p.y}),s.onDrag?.(p)},onRelease:()=>{const p=g.velocity;s.onRelease?.(p),s.inertia&&f(p)}});return g.start(),{draggable:g,get position(){return a()},get rotation(){const p=e.appliedValue(i,"rotate");return typeof p=="number"?p:0},destroy(){u(),g.destroy()}}}function Qp(t,e,n,s,i){const o=typeof i.bounds=="object"&&i.bounds!==null&&!Po(i.bounds)?i.bounds:{},r=()=>{const k=e.appliedValue(n,"rotate");return typeof k=="number"?k:0},a=k=>Math.min(o.maxRotation??1/0,Math.max(o.minRotation??-1/0,k));let l=null,c=!1,h,d={x:0,y:0},u=0,f=0,g=[];const p=k=>Math.atan2(k.clientY-d.y,k.clientX-d.x)*180/Math.PI,m=k=>{if(c)return;l?.kill(),l=null,c=!0,h=k.pointerId,s.setPointerCapture?.(k.pointerId);const y=s.getBoundingClientRect();d={x:y.left+y.width/2,y:y.top+y.height/2},u=p(k),f=r(),g=[{time:performance.now(),rotation:f}],i.onPress?.()},b=k=>{if(!c||k.pointerId!==h)return;const y=p(k);let M=y-u;M>180&&(M-=360),M<-180&&(M+=360),u=y,f+=M;let $=a(f);i.snap&&($=a(Math.round($/i.snap)*i.snap)),e.apply(n,{rotate:$});const E=performance.now();for(g.push({time:E,rotation:$});g.length>2&&E-g[0].time>100;)g.shift();const A={x:0,y:0};i.onDrag?.(A)},S=k=>{if(!c||k.pointerId!==h)return;c=!1;const y=g[0],M=g[g.length-1],$=y&&M?(M.time-y.time)/1e3:0,E=$>0?(M.rotation-y.rotation)/$:0;if(i.onRelease?.({x:E,y:0}),!i.inertia)return;const A=i.inertia===!0?{}:i.inertia,T=A.friction??(A.resistance!==void 0?To(A.resistance):4),I=typeof A.end=="number"||Array.isArray(A.end)?A.end:void 0;l=t.to(s,{inertia:{rotate:{velocity:E,friction:T,min:o.minRotation,max:o.maxRotation,end:Array.isArray(I)?I.filter(v=>typeof v=="number"):I}},onComplete:()=>i.onThrowComplete?.()})};return s.addEventListener("pointerdown",m),s.addEventListener("pointermove",b),s.addEventListener("pointerup",S),s.addEventListener("pointercancel",S),s.style.touchAction="none",{draggable:void 0,position:{x:0,y:0},get rotation(){return r()},destroy(){l?.kill(),s.removeEventListener("pointerdown",m),s.removeEventListener("pointermove",b),s.removeEventListener("pointerup",S),s.removeEventListener("pointercancel",S)}}}const tg={opacity:0,scale:.6};function eg(t){const e=t.getBoundingClientRect();return e.width===0&&e.height===0?null:{cx:e.left+e.width/2,cy:e.top+e.height/2,width:e.width,height:e.height}}function cc(t){const e=Rs(t);return e.width===0&&e.height===0?null:{cx:e.left+e.width/2,cy:e.top+e.height/2,width:e.width,height:e.height}}function xo(t,e){const s=t.resolveTargets(e).map(r=>t.elementFor(r)).filter(r=>!!r),i=new Map,o=new Map;for(const r of s){const a=eg(r);i.set(r,a);const l=hc(r);a&&l!==void 0&&!o.has(l)&&o.set(l,{element:r,box:a})}return{elements:s,boxes:i,ids:o}}const Io=new WeakMap;function Oo(t,e,n,s={}){const i=s.duration??.6,o=s.ease??"power2.inOut",r=s.stagger??0,a=s.scale!==!1,l=s.enter===void 0?tg:s.enter,c=new Set(n.elements);if(s.targets!==void 0)for(const f of t.resolveTargets(s.targets)){const g=t.elementFor(f);g&&c.add(g)}const h=[...c].sort((f,g)=>f===g?0:f.compareDocumentPosition(g)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1),d=e({onComplete:s.onComplete});let u=0;for(const f of h){const g=cc(f);if(!g)continue;let p=n.boxes.get(f)??null,m;const b=hc(f),S=!p&&b!==void 0?n.ids.get(b):void 0;S&&S.element!==f&&(p=S.box,m=S.element);const[k]=t.resolveTargets(f);Io.get(f)?.timeline.removeTracks({target:k});const y=u*r;if(!p){if(l===!1)continue;d.fromTo(f,{x:0,y:0,scaleX:1,scaleY:1,...l},{...dc(l),x:0,y:0,scaleX:1,scaleY:1,duration:i,ease:o,delay:y},0),Io.set(f,d),u++;continue}const M=p.cx-g.cx,$=p.cy-g.cy,E=a?p.width/g.width:1,A=a?p.height/g.height:1;if(!(Math.abs(M)>.5||Math.abs($)>.5||Math.abs(E-1)>.001||Math.abs(A-1)>.001)){const v=(P,H)=>{const O=t.appliedValue(k,P);return typeof O=="number"&&Math.abs(O-H)>1e-6};(v("x",0)||v("y",0)||v("scaleX",1)||v("scaleY",1))&&d.set(f,{x:0,y:0,scaleX:1,scaleY:1},0);continue}const I=s.fade===!0&&m!==void 0;d.fromTo(f,{x:M,y:$,scaleX:E,scaleY:A,...I&&{opacity:0}},{x:0,y:0,scaleX:1,scaleY:1,...I&&{opacity:1},duration:i,ease:o,delay:y},0),I&&m&&cc(m)&&d.fromTo(m,{opacity:1},{opacity:0,duration:i,ease:o,delay:y},0),Io.set(f,d),u++}return d}function hc(t){return t.dataset?.flipId}function dc(t){const e={};for(const n of Object.keys(t))e[n]=n==="opacity"||n.startsWith("scale")?1:0;return e}function ng(t,e={}){const n=new Set((e.type??"chars,words,lines").split(",").map(p=>p.trim())),s={chars:e.charsClass??"char",words:e.wordsClass??"word",lines:e.linesClass??"line"},i=e.aria!==!1,o=t.map(p=>({element:p,html:p.innerHTML,ariaLabel:p.getAttribute("aria-label")}));let r={chars:[],words:[],lines:[],masks:[]},a,l,c=!1;const h=()=>{for(const{element:p,html:m,ariaLabel:b}of o)p.innerHTML=m,b===null?p.removeAttribute("aria-label"):p.setAttribute("aria-label",b)},d=()=>{a&&(a.revert?a.revert():a.kill?.(),a=void 0)},u=()=>{const p={chars:[],words:[],lines:[],masks:[]};for(const{element:m}of o){const b=(m.textContent??"").replace(/\s+/g," ").trim(),S=sg(m,s.words),k=n.has("chars")?S.flatMap($=>ig($,s.chars)):[],y=n.has("lines")?rg(m,S,s.lines):[];if(i){!m.hasAttribute("aria-label")&&b&&m.setAttribute("aria-label",b);for(const $ of S)$.setAttribute("aria-hidden","true")}if(n.has("words"))p.words.push(...S);else for(const $ of S)$.removeAttribute("class");p.chars.push(...k),p.lines.push(...y);const M=e.mask==="lines"?y:e.mask==="words"?S:e.mask==="chars"?k:[];for(const $ of M)p.masks.push(ag($,`${s[e.mask]}-mask`))}r=p},f={elements:t,get chars(){return r.chars},get words(){return r.words},get lines(){return r.lines},get masks(){return r.masks},split(){c||(d(),h(),u(),a=e.onSplit?.(f))},revert(){c=!0,l?.disconnect(),d(),h()}};u(),a=e.onSplit?.(f),e.autoSplit&&g();function g(){const p=new Map;let m=!1;const b=()=>{if(m)return;m=!0;const k=()=>{m=!1,f.split()};typeof requestAnimationFrame=="function"?requestAnimationFrame(k):setTimeout(k,0)};if(typeof ResizeObserver=="function"){l=new ResizeObserver(k=>{let y=!1;for(const M of k){const $=Math.round(M.contentRect.width),E=p.get(M.target);p.set(M.target,$),E!==void 0&&E!==$&&(y=!0)}y&&b()});for(const k of t)l.observe(k)}const S=t[0]?.ownerDocument?.fonts;S&&S.status!=="loaded"&&S.ready.then(()=>b())}return f}function sg(t,e){const n=t.ownerDocument,s=[],i=n.createTreeWalker(t,4),o=[];for(let r=i.nextNode();r;r=i.nextNode())o.push(r);for(const r of o){const a=r.data.match(/\s+|\S+/g)??[];if(a.length===0)continue;const l=n.createDocumentFragment();for(const c of a){if(/^\s/.test(c)){l.appendChild(n.createTextNode(c));continue}const h=n.createElement("span");h.className=e,h.style.display="inline-block",h.textContent=c,l.appendChild(h),s.push(h)}r.replaceWith(l)}return s}function ig(t,e){const n=t.ownerDocument,s=og(t.textContent??"").map(i=>{const o=n.createElement("span");return o.className=e,o.style.display="inline-block",o.textContent=i,o});return t.replaceChildren(...s),s}function og(t){const e=Intl.Segmenter;return e?Array.from(new e(void 0,{granularity:"grapheme"}).segment(t),n=>n.segment):Array.from(t)}function rg(t,e,n){const s=t.ownerDocument,i=new Map(e.map(g=>[g,g.getBoundingClientRect()])),o=[],r=g=>{for(const p of Array.from(g.childNodes))p.nodeType===3||i.has(p)||p.tagName==="BR"?o.push(p):r(p)};r(t);const a=[];let l=null,c=0,h=0,d=!1,u=[];const f=()=>{l=s.createElement("span"),l.className=n,l.style.display="block",a.push(l),u=[]};for(const g of o){if(g.tagName==="BR"){d=!0;continue}const p=i.get(g);if(p&&(!l||d||p.top>c+h)&&(f(),c=p.top,h=p.height/2,d=!1),!l)continue;const m=[];for(let k=g.parentNode;k&&k!==t;k=k.parentNode)m.unshift(k);let b=0;for(;b<u.length&&b<m.length&&u[b].original===m[b];)b++;u.length=b;let S=b===0?l:u[b-1].clone;for(const k of m.slice(b)){const y=k.cloneNode(!1);S.appendChild(y),u.push({original:k,clone:y}),S=y}S.appendChild(g)}return t.replaceChildren(...a),a}function ag(t,e){const n=t.ownerDocument.createElement("span");return n.className=e,n.style.display=t.style.display==="block"?"block":"inline-block",n.style.overflow="clip",n.style.paddingBottom="0.12em",n.style.marginBottom="-0.12em",t.replaceWith(n),n.appendChild(t),n}const uc={top:0,left:0,start:0,center:.5,centre:.5,middle:.5,bottom:1,right:1,end:1};function _o(t){const e=t.trim().toLowerCase();if(e in uc)return uc[e];if(e.endsWith("%")){const n=Number.parseFloat(e.slice(0,-1));return Number.isNaN(n)?void 0:n/100}}function Co(t){if(typeof t=="number")return{elementFraction:0,viewportFraction:0,offsetPx:0,absolutePx:t};let e=0;const s=t.replace(/([+-])=\s*(-?[\d.]+)/g,(r,a,l)=>(e+=(a==="-"?-1:1)*Number.parseFloat(l),"")).trim().split(/\s+/).filter(Boolean);if(s.length===1&&/^-?[\d.]+$/.test(s[0]))return{elementFraction:0,viewportFraction:0,offsetPx:0,absolutePx:Number.parseFloat(s[0])+e};const i=s[0]!==void 0?_o(s[0]):void 0,o=s[1]!==void 0?_o(s[1]):void 0;return{elementFraction:i??0,viewportFraction:o??0,offsetPx:e}}function nn(t,e,n){const s=Co(n),i=s.absolutePx!==void 0?t.top+s.absolutePx:t.top+t.height*s.elementFraction,o=e*s.viewportFraction;return i-o+s.offsetPx}function lg(t,e,n,s){const i=nn(t,e,n),r=nn(t,e,s)-i;return r<=0?i<=0?1:0:Ho(-i/r)}function Ho(t){return t<0?0:t>1?1:t===0?0:t}function fc(t,e,n,s){if(n<=0)return e;const i=1-Math.exp(-(s/1e3)/n);return t+(e-t)*i}function Ro(t,e,n,s,i){const o=h=>nn({top:t+i(h),bottom:t+i(h)+e,height:e},n,s),r=o(0),a=o(1);if(Math.sign(r)===Math.sign(a)||r===0||a===0)return r===0?0:a===0?1:Math.abs(r)<Math.abs(a)?0:1;let l=0,c=1;for(let h=0;h<40;h++){const d=(l+c)/2;Math.sign(o(d))===Math.sign(r)?l=d:c=d}return(l+c)/2}class pc{timeline;trigger;behaviour;options;observer=null;hasPlayed=!1;running=!1;constructor(e){this.timeline=e.timeline,this.trigger=e.trigger,this.behaviour=e.behaviour??"once",this.options=e}start(){if(!this.running){if(this.running=!0,typeof IntersectionObserver>"u"){this.enter();return}this.observer=new IntersectionObserver(e=>{for(const n of e)n.isIntersecting?this.enter():this.leave()},{threshold:this.options.threshold??.15,rootMargin:this.options.rootMargin,root:this.options.root??null}),this.observer.observe(this.trigger)}}stop(){this.running=!1,this.observer?.disconnect(),this.observer=null}destroy(){this.stop()}reset(){this.hasPlayed=!1,this.timeline.stop()}enter(){this.options.onEnter?.(),!(this.behaviour==="once"&&this.hasPlayed)&&(this.hasPlayed=!0,this.behaviour!=="once"&&this.timeline.seek(0),this.timeline.play())}leave(){this.options.onLeave?.(),this.behaviour==="reset"&&this.timeline.stop()}}function cg(t){const e=new pc(t);return e.start(),e}class gc{element;spacer;saved;axis;spacing;constructor(e,n={}){this.element=e,this.axis=n.axis??"y",this.spacing=n.spacing??!0;const s=e.ownerDocument;this.spacer=s.createElement("div"),this.spacer.className="pin-spacer",this.saved={position:e.style.position,top:e.style.top,left:e.style.left},this.axis==="x"&&(this.spacer.style.flexShrink="0"),e.replaceWith(this.spacer),this.spacer.appendChild(e)}release(){this.element.style.position=this.saved.position,this.element.style.top=this.saved.top,this.element.style.left=this.saved.left}apply(e,n){const s=Math.max(0,n);this.element.style.position="sticky",this.axis==="x"?(this.spacer.style.width=`${this.element.offsetWidth+s}px`,this.spacer.style.marginRight=this.spacing?"":`-${s}px`,this.element.style.left=`${e}px`):(this.spacer.style.height=`${this.element.offsetHeight+s}px`,this.spacer.style.marginBottom=this.spacing?"":`-${s}px`,this.element.style.top=`${e}px`)}destroy(){this.element.style.position=this.saved.position,this.element.style.top=this.saved.top,this.element.style.left=this.saved.left,this.spacer.parentNode&&this.spacer.replaceWith(this.element)}}const hg=.15;function mc(t){return typeof t=="object"&&!Array.isArray(t)?t:{snapTo:t}}function yc(t,e,n){const s=Ls(t+e*hg);if(typeof n=="function")return Ls(n(s));if(typeof n=="number")return n<=0?t:Ls(Math.round(s/n)*n);if(n.length===0)return t;let i=n[0];for(const o of n)Math.abs(o-s)<Math.abs(i-s)&&(i=o);return Ls(i)}function bc(t,e,n){const s=t.duration??{min:.2,max:.8};if(typeof s=="number")return s;const i=Math.min(1,Math.abs(e)/Math.max(1,n));return s.min+(s.max-s.min)*i}class wc{rafId=null;cancelEvents=["wheel","touchstart","pointerdown","keydown"];onInterrupt=()=>this.cancel();write;eventTarget;constructor(e,n){this.write=e,this.eventTarget=n}get active(){return this.rafId!==null}animate(e,n,s,i=xn,o){if(this.cancel(),typeof requestAnimationFrame>"u"||s<=0){this.write(n),o?.();return}for(const l of this.cancelEvents)this.eventTarget?.addEventListener(l,this.onInterrupt,{passive:!0});let r=null;const a=l=>{r??=l;const c=Math.min(1,(l-r)/(s*1e3));this.write(e+(n-e)*i(c)),c<1?this.rafId=requestAnimationFrame(a):(this.rafId=null,this.detach(),o?.())};this.rafId=requestAnimationFrame(a)}cancel(){this.rafId!==null&&typeof cancelAnimationFrame<"u"&&cancelAnimationFrame(this.rafId),this.rafId=null,this.detach()}detach(){for(const e of this.cancelEvents)this.eventTarget?.removeEventListener(e,this.onInterrupt)}}function Ls(t){return Math.max(0,Math.min(1,t))}class kc{options;scroller;nodes=[];scrollerStart;scrollerEnd;start;end;constructor(e,n,s){this.options=s===!0?{}:s,this.scroller=n;const{startColor:i="#3ecf7a",endColor:o="#ff5a5a",id:r}=this.options,a=r?`${r} `:"",l=(c,h,d)=>{const u=e.createElement("div");return u.textContent=`${a}${c}`,u.setAttribute("aria-hidden","true"),u.className="scroll-marker",Object.assign(u.style,{position:d?"fixed":"absolute",right:`${this.options.indent??0}px`,zIndex:"2147483646",pointerEvents:"none",borderTop:`1px solid ${h}`,color:h,font:`${this.options.fontSize??"11px"} ui-monospace, monospace`,padding:"2px 6px",whiteSpace:"nowrap",background:"rgba(0, 0, 0, 0.35)"}),(n??e.body).appendChild(u),this.nodes.push(u),u};this.scrollerStart=l("scroller-start",i,!n),this.scrollerEnd=l("scroller-end",o,!n),this.start=l("start",i,!1),this.end=l("end",o,!1),n&&getComputedStyle(n).position==="static"&&(n.style.position="relative")}place(e,n){this.start.style.top=`${e.startPage}px`,this.end.style.top=`${e.endPage}px`;const s=this.scroller?n:0;this.scrollerStart.style.top=`${s+e.startViewport}px`,this.scrollerEnd.style.top=`${s+e.endViewport}px`}follow(e,n){this.scroller&&this.place(e,n)}destroy(){for(const e of this.nodes.splice(0))e.remove()}}const dg=120,sn=[],on=new Set;let Lo=!1;const ug=()=>{Lo||on.size===0||(Lo=!0,queueMicrotask(()=>{Lo=!1;for(const t of on)t.afterRefresh()}))},vc=()=>{for(const t of on)t.beforeRefresh();for(const t of sn)t.refresh();for(const t of on)t.afterRefresh()};let rn={width:0,height:0};const Mc=()=>{const t=window.innerWidth,e=window.innerHeight,n=t===rn.width&&e!==rn.height,s=Math.abs(e-rn.height)<rn.height*.25,i=typeof navigator<"u"&&(navigator.maxTouchPoints??0)>0;n&&s&&i||(rn={width:t,height:e},vc())};class Dn{timeline;options;running=!1;pin=null;startPx=0;endPx=0;targetProgress=0;displayProgress=0;zone="before";measured=!1;lastScroll=null;lastScrollTime=0;velocityPxPerSecond=0;idleTimer=null;lastEmitted=null;rafId=null;lastFrameTime=null;onScroll=()=>this.update();releaseVelocity=0;snapper;snapTimer=null;markers=null;markerGeometry=null;constructor(e){this.timeline=e.timeline,this.options=e,this.snapper=new wc(n=>this.scrollTo(n),typeof window<"u"?window:null)}start(){if(this.running)return;this.running=!0,this.timeline?.pause();const e=this.options.pin===!0?this.options.trigger:this.options.pin||null;e&&!this.options.container&&(this.pin=new gc(e,{axis:this.options.horizontal?"x":"y",spacing:this.options.pinSpacing!==!1})),this.options.markers&&!this.options.horizontal&&typeof document<"u"&&(this.markers=new kc(document,this.options.scroller??null,this.options.markers)),this.scrollTarget()?.addEventListener("scroll",this.onScroll,{passive:!0}),sn.length===0&&typeof window<"u"&&(rn={width:window.innerWidth,height:window.innerHeight},window.addEventListener("resize",Mc,{passive:!0})),sn.push(this),this.refresh()}stop(){this.running&&(this.running=!1,this.scrollTarget()?.removeEventListener("scroll",this.onScroll),sn.splice(sn.indexOf(this),1),sn.length===0&&typeof window<"u"&&window.removeEventListener("resize",Mc),this.stopSmoothing(),this.idleTimer!==null&&clearTimeout(this.idleTimer),this.idleTimer=null,this.snapTimer!==null&&clearTimeout(this.snapTimer),this.snapTimer=null,this.snapper.cancel())}destroy(){this.stop(),this.pin?.destroy(),this.pin=null,this.markers?.destroy(),this.markers=null}get startOffset(){return this.startPx}get endOffset(){return this.endPx}static refreshAll(){vc()}static onRefresh(e){return on.add(e),()=>on.delete(e)}get progress(){return this.targetProgress}get velocity(){return this.velocityPxPerSecond}refresh(){if(!this.running)return;this.measured&&this.options.onRefresh?.();const e=this.scrollPosition();this.pin?.release();const n=this.triggerRect();if(n&&this.options.container)this.measureInContainer(this.options.container);else if(n){const s=this.viewportHeight();if(this.startPx=e+nn(n,s,Fn(this.options.start)??"top bottom"),this.endPx=this.resolveEnd(n,s,e),this.pin){const i=this.relativeRect(this.pin.element.getBoundingClientRect());this.pin.apply(i.top-(this.startPx-e),this.endPx-this.startPx)}this.markerGeometry=this.markers?this.markersFor(s):null}this.markers&&this.markerGeometry&&this.markers.place(this.markerGeometry,e),this.lastScroll=null,this.updateFrom(e,!this.measured),this.measured=!0,ug()}sample(){this.refresh()}update(e){this.running&&this.updateFrom(e??this.scrollPosition(),!1)}updateFrom(e,n){this.trackVelocity(e),this.markers&&this.markerGeometry&&this.markers.follow(this.markerGeometry,e);const s=this.endPx-this.startPx,i=this.zone;this.targetProgress=s>0?Ho((e-this.startPx)/s):e>=this.startPx?1:0,this.zone=s>0?e<=this.startPx?"before":e>=this.endPx?"after":"active":e>=this.startPx?"after":"before",this.fireBoundaryCallbacks(i,this.zone),n||this.smoothing()<=0?(this.displayProgress=this.targetProgress,this.applyProgress()):(this.emitUpdate(),this.startSmoothing())}smoothing(){const e=this.options.scrub;return typeof e=="number"?Math.max(0,e):0}resolveEnd(e,n,s){const i=Fn(this.options.end)??"bottom top",o=typeof i=="string"?i.trim().match(/^\+=\s*(-?[\d.]+)\s*(%|px)?$/):null;if(o){const r=Number.parseFloat(o[1]);return this.startPx+(o[2]==="%"?n*r/100:r)}return s+nn(e,n,i)}applyProgress(){const e=this.timeline?.duration??0;this.timeline&&e>0&&this.timeline.seek(this.displayProgress*e),this.emitUpdate()}emitUpdate(){if(!this.options.onUpdate)return;const e=[this.displayProgress,this.velocityPxPerSecond];this.lastEmitted&&this.lastEmitted[0]===e[0]&&this.lastEmitted[1]===e[1]||(this.lastEmitted=e,this.options.onUpdate(e[0],e[1]))}trackVelocity(e){const n=typeof performance<"u"?performance.now():Date.now();this.lastScroll!==null&&n>this.lastScrollTime&&e!==this.lastScroll&&(this.velocityPxPerSecond=(e-this.lastScroll)/(n-this.lastScrollTime)*1e3),(this.lastScroll===null||e!==this.lastScroll)&&(this.lastScroll=e,this.lastScrollTime=n),!(this.velocityPxPerSecond===0||typeof setTimeout>"u")&&(this.idleTimer!==null&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{this.idleTimer=null,this.releaseVelocity=this.velocityPxPerSecond,this.velocityPxPerSecond=0,this.emitUpdate(),this.scheduleSnap()},dg))}fireBoundaryCallbacks(e,n){if(e===n)return;const{onEnter:s,onLeave:i,onEnterBack:o,onLeaveBack:r}=this.options;e==="before"?(s?.(),n==="after"&&i?.()):e==="after"?(o?.(),n==="before"&&r?.()):n==="after"?i?.():r?.()}scheduleSnap(){const e=this.options.snap;if(e===void 0||this.snapper.active)return;const n=mc(e),s=()=>{this.snapTimer=null;const i=this.endPx-this.startPx,o=this.scrollPosition();if(!this.running||i<=0||o<=this.startPx||o>=this.endPx)return;const r=(o-this.startPx)/i,a=this.startPx+yc(r,this.releaseVelocity/i,n.snapTo)*i;Math.abs(a-o)<1||this.snapper.animate(o,a,bc(n,a-o,this.viewportHeight()),n.ease)};n.delay?this.snapTimer=setTimeout(s,n.delay*1e3):s()}scrollTo(e){const n=this.options.scroller,s=this.options.horizontal?{left:e}:{top:e};n?typeof n.scrollTo=="function"?n.scrollTo({...s,behavior:"instant"}):this.options.horizontal?n.scrollLeft=e:n.scrollTop=e:typeof window<"u"&&window.scrollTo({...s,behavior:"instant"})}measureInContainer(e){const n=this.options.trigger;if(typeof n?.getBoundingClientRect!="function")return;const s=n.getBoundingClientRect(),i=this.options.scroller?.getBoundingClientRect?.().left??0,o=this.options.scroller?this.options.scroller.clientWidth:typeof window<"u"?window.innerWidth:0,r=s.left-i-e.shiftAt(e.progress()),{start:a,end:l}=e.range(),c=f=>a+f*(l-a),h=Ro(r,s.width,o,Fn(this.options.start)??"left right",e.shiftAt);this.startPx=c(h);const d=Fn(this.options.end)??"right left",u=typeof d=="string"?d.trim().match(/^\+=\s*(-?[\d.]+)\s*(px)?$/):null;this.endPx=u?this.startPx+Number.parseFloat(u[1]):c(Ro(r,s.width,o,d,e.shiftAt)),this.markerGeometry=null}markersFor(e){const n=(o,r)=>{const a=Fn(o)??r;if(typeof a=="number")return 0;if(/^\s*\+=/.test(a))return;const l=Co(a);return e*l.viewportFraction-l.offsetPx},s=n(this.options.start,"top bottom")??0,i=n(this.options.end,"bottom top")??s;return{startViewport:s,endViewport:i,startPage:this.startPx+s,endPage:this.endPx+i}}startSmoothing(){if(this.rafId!==null||typeof requestAnimationFrame>"u")return;const e=n=>{if(this.rafId=null,!this.running)return;const s=this.lastFrameTime===null?16.67:n-this.lastFrameTime;this.lastFrameTime=n,this.displayProgress=fc(this.displayProgress,this.targetProgress,this.smoothing(),s);const i=Math.abs(this.targetProgress-this.displayProgress)<1e-4;i&&(this.displayProgress=this.targetProgress),this.applyProgress(),i?this.lastFrameTime=null:this.rafId=requestAnimationFrame(e)};this.rafId=requestAnimationFrame(e)}stopSmoothing(){this.rafId!==null&&typeof cancelAnimationFrame<"u"&&cancelAnimationFrame(this.rafId),this.rafId=null,this.lastFrameTime=null}scrollTarget(){return this.options.scroller??(typeof window<"u"?window:null)}scrollPosition(){const e=this.options.scroller,n=this.options.horizontal;return e?(n?e.scrollLeft:e.scrollTop)??0:typeof window<"u"?(n?window.scrollX:window.scrollY)??0:0}triggerRect(){const e=this.options.trigger;return typeof e?.getBoundingClientRect!="function"?null:this.relativeRect(e.getBoundingClientRect())}relativeRect(e){const n=this.options.horizontal,s=n?e.left??0:e.top,i=n?e.right??0:e.bottom,o=n?e.width??0:e.height,r=this.options.scroller;if(r&&typeof r.getBoundingClientRect=="function"){const a=r.getBoundingClientRect(),l=n?a.left:a.top;return{top:s-l,bottom:i-l,height:o}}return{top:s,bottom:i,height:o}}viewportHeight(){const e=this.options.scroller,n=this.options.horizontal;return e?n?e.clientWidth:e.clientHeight:typeof window<"u"?n?window.innerWidth:window.innerHeight:0}}function Fn(t){return typeof t=="function"?t():t}function fg(t){const e=new Dn(t);return e.start(),e}const No=new Set,pg=16,Sc=.5,gg=2;class Do{options;frames;running=!1;reduced=!1;current=0;target=0;written=null;velocityPxPerSecond=0;frameId=null;lastTime=null;journey=null;pausedState=!1;effects=[];onWheel=e=>this.wheel(e);onScroll=()=>this.nativeScroll();onResize=()=>this.refresh();onLoad=()=>this.refresh();stopListening=null;constructor(e={}){this.options=e,this.frames=e.frames??{request:n=>requestAnimationFrame(n),cancel:n=>cancelAnimationFrame(n)}}start(){if(this.running||typeof window>"u")return this;this.running=!0,this.reduced=this.options.reducedMotion??(typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches),this.current=this.target=this.position();const e=this.options.scroller??window;return e.addEventListener("wheel",this.onWheel,{passive:!1}),e.addEventListener("scroll",this.onScroll,{passive:!0}),window.addEventListener("resize",this.onResize,{passive:!0}),window.addEventListener("load",this.onLoad),No.add(this),this.stopListening=Dn.onRefresh({beforeRefresh:()=>this.rest(),afterRefresh:()=>this.refresh()}),this.refresh(),this}static refreshAll(){for(const e of No)e.refresh()}stop(){if(!this.running)return this;this.running=!1;const e=this.options.scroller??window;return e.removeEventListener("wheel",this.onWheel),e.removeEventListener("scroll",this.onScroll),window.removeEventListener("resize",this.onResize),window.removeEventListener("load",this.onLoad),No.delete(this),this.stopListening?.(),this.stopListening=null,this.cancelFrame(),this.journey=null,this}destroy(){this.stop();for(const e of this.effects)Fo(e.element,e.saved);this.effects=[]}kill(){this.destroy()}get state(){const e=this.limit();return{scroll:this.current,target:this.target,progress:e>0?this.current/e:0,velocity:this.velocityPxPerSecond}}paused(e){return e!==void 0&&(this.pausedState=e,e&&(this.target=this.current,this.journey=null)),this.pausedState}scrollTo(e,n={}){if(!this.running)return;const s=this.clamp(this.resolve(e)+(n.offset??0)),i=Math.abs(s-this.current),o=this.reduced?0:n.duration??Math.min(1.2,Math.max(.4,i/2500));if(o<=0){this.journey=null,this.current=this.target=s,this.write(s),this.applyEffects(0);return}this.target=s,this.journey={from:this.current,to:s,ms:o*1e3,ease:n.ease??xn,elapsed:0},this.requestFrame()}refresh(){if(!this.running)return;this.rest(),this.effects=[];const e=this.options.effects===!0?"[data-speed], [data-lag]":this.options.effects||"";if(e&&!this.reduced){const n=this.options.scroller??document,s=this.position(),i=this.viewportHeight(),o=this.options.scroller?.getBoundingClientRect().top??0;for(const r of n.querySelectorAll(e)){const a=Number.parseFloat(r.dataset.speed??""),l=Number.parseFloat(r.dataset.lag??""),c=r.getBoundingClientRect(),h=c.top-o+s;this.effects.push({element:r,speed:Number.isFinite(a)?a:void 0,lag:Number.isFinite(l)&&l>0?l:void 0,centre:h+c.height/2-i/2,lagged:s,shift:0,saved:r.style.getPropertyValue("translate")})}}this.current=this.target=this.clamp(this.position()),this.applyEffects(0)}rest(){for(const e of this.effects)Fo(e.element,e.saved)}wheel(e){if(this.pausedState||this.reduced||(this.options.smooth??.8)<=0||e.ctrlKey||Math.abs(e.deltaX)>Math.abs(e.deltaY)||this.nestedScrollerTakes(e))return;const n=e.deltaMode===1?pg:e.deltaMode===2?this.viewportHeight():1,s=e.deltaY*n*(this.options.wheelMultiplier??1),i=this.clamp(this.target+s);i===this.target&&i===this.current||(e.preventDefault(),this.journey=null,this.target=i,this.requestFrame())}nativeScroll(){const e=this.position();this.written!==null&&Math.abs(e-this.written)<=gg||(this.written=null,this.journey=null,this.cancelFrame(),this.current=this.target=e,this.requestFrame())}nestedScrollerTakes(e){const n=this.options.scroller??document.documentElement;for(let s=e.target;s&&s!==n&&s!==document.body;s=s.parentElement){if(s.hasAttribute?.("data-smooth-ignore"))return!0;const i=getComputedStyle(s);if(!/(auto|scroll)/.test(i.overflowY)||s.scrollHeight<=s.clientHeight)continue;if(e.deltaY<0?s.scrollTop>0:s.scrollTop+s.clientHeight<s.scrollHeight-1)return!0}return!1}requestFrame(){this.frameId!==null||!this.running||(this.frameId=this.frames.request(e=>this.frame(e)))}cancelFrame(){this.frameId!==null&&this.frames.cancel(this.frameId),this.frameId=null,this.lastTime=null}frame(e){this.frameId=null;const n=this.lastTime===null?1e3/60:Math.min(100,e-this.lastTime);this.lastTime=e;const s=this.current;if(this.journey){const o=this.journey;o.elapsed+=n;const r=Math.min(1,o.elapsed/o.ms);this.current=o.from+(o.to-o.from)*o.ease(r),r>=1&&(this.journey=null)}else if(this.current!==this.target){const o=(this.options.smooth??.8)*1e3/3;this.current+=(this.target-this.current)*(1-Math.exp(-n/o)),Math.abs(this.target-this.current)<Sc&&(this.current=this.target)}this.current!==s&&this.write(this.current),this.velocityPxPerSecond=n>0?(this.current-s)*1e3/n:0;const i=this.applyEffects(n);this.current!==s&&this.options.onUpdate?.(this.state),this.journey||this.current!==this.target||i?this.requestFrame():(this.lastTime=null,this.velocityPxPerSecond=0)}applyEffects(e){let n=!1;const s=this.current;for(const i of this.effects){let o=0;if(i.speed!==void 0&&(o+=(s-i.centre)*(1-i.speed)),i.lag!==void 0){const r=i.lag*1e3/3;i.lagged=e===0?s:i.lagged+(s-i.lagged)*(1-Math.exp(-e/r)),Math.abs(s-i.lagged)<Sc?i.lagged=s:n=!0,o+=s-i.lagged}Fo(i.element,o===0?i.saved:`0 ${mg(o)}px`),i.shift=o}return n}write(e){const n=Math.round(e);this.written=n;const s=this.options.scroller;s?s.scrollTop=n:window.scrollTo({top:n,behavior:"instant"})}position(){const e=this.options.scroller;return e?e.scrollTop:window.scrollY}viewportHeight(){const e=this.options.scroller;return e?e.clientHeight:window.innerHeight}limit(){const e=this.options.scroller??document.documentElement;return Math.max(0,e.scrollHeight-this.viewportHeight())}clamp(e){return Math.max(0,Math.min(this.limit(),e))}resolve(e){if(typeof e=="number")return e;const n=this.options.scroller??document,s=typeof e=="string"?n.querySelector(e):e;if(!s)return this.current;const i=this.options.scroller?.getBoundingClientRect().top??0,o=this.effects.find(r=>r.element===s)?.shift??0;return s.getBoundingClientRect().top-i+this.position()-o}}function Fo(t,e){e?t.style.setProperty("translate",e):t.style.removeProperty("translate")}function mg(t){return Math.round(t*100)/100}function yg(t,e){switch(e){case"play":if(t.progress()>=1)break;t.reversed()?t.reverse():t.play();break;case"reverse":if(t.progress()<=0)break;t.reversed()?t.play():t.reverse();break;case"pause":t.pause();break;case"resume":t.resume();break;case"restart":t.restart();break;case"reset":t.pause(),t.progress(0);break;case"complete":t.pause(),t.progress(1);break}}function jo(t,e,n,s,i=()=>{}){const o=f=>typeof f=="string"?t.query(f)??void 0:f,r=o(e.trigger)??s;if(!r){i(`gsap-compat: scrollTrigger has no trigger element${typeof e.trigger=="string"?` for "${e.trigger}"`:""}`);return}const a=e.scrub===void 0||e.scrub===!1?!1:e.scrub,l=(e.toggleActions??"play none none none").trim().split(/\s+/);let c=0,h;const d=(f,g)=>()=>{g?.(),n&&!a&&yg(n,l[f]??"none"),e.once&&f===0&&queueMicrotask(()=>h.destroy())},u=e.containerAnimation?kg(t,e.containerAnimation,r,i):void 0;return h=new Dn({trigger:r,start:e.start,end:e.end,scrub:a===!1?void 0:a,pin:e.pin===!0?!0:o(e.pin),scroller:o(e.scroller),horizontal:e.horizontal,pinSpacing:e.pinSpacing,onRefresh:e.invalidateOnRefresh&&n?.invalidate?()=>n.invalidate():void 0,snap:e.snap===void 0?void 0:bg(e.snap,n),markers:e.markers,container:u,onUpdate:(f,g)=>{if(n&&a!==!1&&n.progress(f),e.onUpdate){const p=f<c||g<0?-1:1;e.onUpdate({progress:f,velocity:g,direction:p})}c=f},onEnter:d(0,e.onEnter),onLeave:d(1,e.onLeave),onEnterBack:d(2,e.onEnterBack),onLeaveBack:d(3,e.onLeaveBack)}),n&&a===!1&&n.progress(0),h.start(),t.own(h)}function bg(t,e){const n=i=>i==="labels"?o=>wg(o,e?.labelProgresses?.()??[]):i;if(typeof t!="object"||Array.isArray(t))return n(t);const s=t.ease?Rn(t.ease):void 0;return{snapTo:n(t.snapTo),duration:t.duration,delay:t.delay,ease:s?s.fn??xt(s.easing):void 0}}function wg(t,e){return e.reduce((n,s)=>Math.abs(s-t)<Math.abs(n-t)?s:n,e[0]??t)}function kg(t,e,n,s){const i=()=>e.timeline.getTracks({property:"x"}).map(o=>o.target).filter(o=>{const r=t.elementFor(o);return!!r&&r!==n&&r.contains(n)});return i().length===0&&s("gsap-compat: containerAnimation does not move an ancestor of the trigger along x"),{range:()=>{const o=e.scrollTrigger;return o||s("gsap-compat: containerAnimation needs its own scrollTrigger (created before this one)"),{start:o?.startOffset??0,end:o?.endOffset??0}},progress:()=>e.progress(),shiftAt:o=>{const r=e.timeline.getStateAtTime(o*e.timeline.duration);let a=0;for(const l of i()){const c=r.values.get(l)?.get("x");typeof c=="number"&&(a+=c)}return a}}}class Tc{conditions={};scope;host;items=[];snapshots=new Map;constructor(e,n){this.host=e,this.scope=n}add(e){const n=this.host.collector;this.host.setCollector(this);try{const s=e();return typeof s=="function"&&this.items.push({revert:s}),s}finally{this.host.setCollector(n)}}track(e){this.items.push(e)}touch(e,n){this.snapshots.has(e)||this.snapshots.set(e,{name:n,style:e.getAttribute("style"),d:e.getAttribute("d")})}revert(){for(const e of this.items.splice(0).reverse())e.revert?e.revert():e.kill?e.kill():e.destroy?.();for(const[e,{name:n,style:s,d:i}]of this.snapshots)s===null?e.removeAttribute("style"):e.setAttribute("style",s),i!==null&&e.setAttribute("d",i),this.host.forget(n);this.snapshots.clear()}kill(){this.revert()}}class vg{host;scope;entries=[];listeners=[];scheduled=!1;constructor(e,n){this.host=e,this.scope=n}add(e,n){const s={conditions:e,setup:n,queries:new Map},i=typeof e=="string"?{matches:e}:e;if(typeof window<"u"&&typeof window.matchMedia=="function")for(const[o,r]of Object.entries(i)){const a=window.matchMedia(r);s.queries.set(o,a);const l=()=>this.scheduleUpdate();a.addEventListener("change",l),this.listeners.push(()=>a.removeEventListener("change",l))}return this.entries.push(s),this.update(s),this}revert(){for(const e of this.listeners.splice(0))e();for(const e of this.entries.splice(0))e.context?.revert()}kill(){this.revert()}scheduleUpdate(){this.scheduled||(this.scheduled=!0,queueMicrotask(()=>{this.scheduled=!1;for(const e of this.entries)this.update(e)}))}update(e){const n={};for(const[r,a]of e.queries)n[r]=a.matches;const s=Object.values(n).some(Boolean),i=s?JSON.stringify(n):void 0;if(i===e.key||(e.context?.revert(),e.context=void 0,e.key=i,!s))return;const o=new Tc(this.host,this.scope);o.conditions=n,o.add(()=>e.setup(o)),e.context=o}}class Mg{frames;canvas;context;options;images;ready;current=0;drawn=-1;loadedCount=0;inFlight=0;destroyed=!1;onResize=()=>this.resize();constructor(e,n){this.canvas=e,this.context=e.getContext("2d"),this.options=n,this.frames=Math.max(1,Math.floor(n.frames)),this.images=new Array(this.frames),this.ready=new Array(this.frames).fill(!1),typeof window<"u"&&window.addEventListener("resize",this.onResize,{passive:!0}),this.resize(),this.pump()}get frame(){return this.current}set frame(e){this.current=Math.max(0,Math.min(this.frames-1,e)),this.draw()}get loaded(){return this.loadedCount}destroy(){this.destroyed=!0,typeof window<"u"&&window.removeEventListener("resize",this.onResize);for(const e of this.images)e&&(e.src="")}resize(){const e=typeof window<"u"?Math.min(window.devicePixelRatio||1,2):1,n=Math.round(this.canvas.clientWidth*e),s=Math.round(this.canvas.clientHeight*e);n>0&&s>0&&(this.canvas.width!==n||this.canvas.height!==s)&&(this.canvas.width=n,this.canvas.height=s),this.drawn=-1,this.draw()}draw(){const e=Math.round(this.current),n=this.nearestReady(e);if(n===-1||n===this.drawn||!this.context)return;const s=this.images[n],{width:i,height:o}=this.canvas,r=(this.options.fit??"cover")==="cover"?Math.max(i/s.naturalWidth,o/s.naturalHeight):Math.min(i/s.naturalWidth,o/s.naturalHeight),a=s.naturalWidth*r,l=s.naturalHeight*r;this.context.clearRect(0,0,i,o),this.context.drawImage(s,(i-a)/2,(o-l)/2,a,l),this.drawn=n,this.pump()}nearestReady(e){for(let n=0;n<this.frames;n++){if(e-n>=0&&this.ready[e-n])return e-n;if(e+n<this.frames&&this.ready[e+n])return e+n}return-1}pump(){const e=this.options.concurrency??6,n=Math.round(this.current);for(let s=0;s<this.frames&&this.inFlight<e;s++)for(const i of s===0?[n]:[n+s,n-s])i<0||i>=this.frames||this.images[i]||this.inFlight>=e||this.load(i)}load(e){const n=new Image;n.decoding="async",this.images[e]=n,this.inFlight++;const s=i=>{if(!this.destroyed){if(this.inFlight--,i){this.ready[e]=!0,this.loadedCount++,this.options.onProgress?.(this.loadedCount,this.frames);const o=Math.round(this.current);(Math.abs(e-o)<Math.abs(this.drawn-o)||this.drawn===-1)&&(this.drawn=-1,this.draw())}this.pump()}};n.onload=()=>s(!0),n.onerror=()=>s(!1),n.src=this.options.url(e)}}const Sg={opacity:0,y:-16},Tg={opacity:0,y:16};async function Eg(t,e,n,s){const i=e.collector?.scope??e.root,o=i.ownerDocument??i,r=()=>s.shared?[...i.querySelectorAll(s.shared)]:[];if(s.native&&typeof o.startViewTransition=="function")return Ag(o,s,r);const a=s.duration??.35,l=s.ease??"power2.inOut",c=m=>new Promise(b=>{m(b)||b()}),h=r(),d=h.length?xo(e,h):void 0,u=s.from!==void 0?Ec(e,s.from,s.shared):[];if(u.length&&s.leave!==!1){const m=s.leave??Sg;await c(b=>t.to(u,{...m,duration:a,ease:l,onComplete:b}))}await s.update();const f=[],g=typeof s.to=="function"?s.to():s.to,p=g!==void 0?Ec(e,g,s.shared):[];if(p.length&&s.enter!==!1){const m=s.enter??Tg;f.push(c(b=>t.fromTo(p,m,{...dc(m),duration:a,ease:l,onComplete:b})))}if(d){const m=r().filter(b=>!h.includes(b));m.length&&f.push(c(b=>Oo(e,n,d,{targets:m,duration:a*1.4,ease:l,enter:!1,onComplete:b})))}await Promise.all(f)}function Ec(t,e,n){const s=t.resolveTargets(e).map(i=>t.elementFor(i)).filter(i=>!!i);return n?s.flatMap(i=>!i.querySelector(n)&&!i.matches(n)?[i]:[...i.children].filter(o=>!o.matches(n)&&!o.querySelector(n))):s}async function Ag(t,e,n){const s=(a,l)=>{const c=a.dataset?.flipId;c&&a.style.setProperty("view-transition-name",l?`tf-${c.replace(/[^\w-]/g,"-")}`:"")},i=n();i.forEach(a=>s(a,!0));let o=[];await t.startViewTransition(async()=>{i.forEach(a=>s(a,!1)),await e.update(),o=n(),o.forEach(a=>s(a,!0))}).finished,o.forEach(a=>s(a,!1))}const Ac={create:(t,e)=>ko(t,Il(e))},$c={create:(t,e)=>ko(t,{fn:Ol(e)})},Pc={create:(t,e)=>ko(t,{fn:_l(e)})},$g=new Set(["keyframes","duration","delay","ease","easeEach","stagger","repeat","repeatDelay","yoyo","repeatRefresh","paused","id","onStart","onUpdate","onComplete","onRepeat","onReverseComplete","scrollTrigger"]),xc=.5,Pg="power1.inOut";function xg(t){return t.keyframes!==void 0&&t.keyframes!==null}function Ig(t){const e=t.keyframes,n={};for(const[c,h]of Object.entries(t))$g.has(c)||(n[c]=h);if(Array.isArray(e))return e.map(c=>({...n,...c,duration:c.duration??t.duration??xc}));const s=Object.entries(e),i=t.duration??xc,o=e.easeEach??t.easeEach??Pg;if(s.length>0&&s.every(([c])=>/^\s*-?\d+(\.\d+)?\s*%\s*$/.test(c)||c==="easeEach")){const c=s.filter(([u])=>u!=="easeEach").map(([u,f])=>({at:Number.parseFloat(u)/100,step:f})).sort((u,f)=>u.at-f.at),h=[];let d=0;for(const{at:u,step:f}of c){const g=Math.max(0,u-d);h.push({...n,ease:o,...f,duration:g*i}),d=u}return h}const r=s.filter(([c,h])=>c!=="easeEach"&&Array.isArray(h)),a=Math.max(0,...r.map(([,c])=>c.length)),l=[];for(let c=0;c<a;c++){const h={...n,ease:o,duration:i/a};for(const[d,u]of r)c<u.length&&(h[d]=u[c]);l.push(h)}return l}function Ic(t,e,n,s={}){const i=e.collector?.scope??e.root,o=typeof s.scroller=="string"?i.querySelector(s.scroller):s.scroller??null,r={x:o?o.scrollLeft:window.scrollX,y:o?o.scrollTop:window.scrollY},a={x:o?o.scrollWidth-o.clientWidth:document.documentElement.scrollWidth-window.innerWidth,y:o?o.scrollHeight-o.clientHeight:document.documentElement.scrollHeight-window.innerHeight},l=(S,k)=>{if(k===void 0)return r[S];if(typeof k=="number")return k;if(k==="max")return a[S];const y=typeof k=="string"?i.querySelector(k):k;if(!y)return r[S];const M=y.getBoundingClientRect(),$=o?.getBoundingClientRect(),E=(S==="x"?s.offsetX:s.offsetY)??s.offset??0;return S==="x"?M.left-($?.left??0)+r.x-E:M.top-($?.top??0)+r.y-E},c=typeof n=="object"&&n!==null&&!("nodeType"in n)?{x:l("x",n.x),y:l("y",n.y)}:{x:r.x,y:l("y",n)},h={x:Math.max(0,Math.min(a.x,c.x)),y:Math.max(0,Math.min(a.y,c.y))},d={...r},u=()=>{o?(o.scrollLeft=d.x,o.scrollTop=d.y):window.scrollTo({left:d.x,top:d.y,behavior:"instant"})},f=["wheel","touchstart","keydown"],g=o??window,p=()=>{b.kill(),m()},m=()=>{for(const S of f)g.removeEventListener(S,p)},b=t.to(d,{x:h.x,y:h.y,duration:s.duration??1,ease:s.ease??"power2.inOut",onStart:s.onStart,onUpdate:()=>{u(),s.onUpdate?.()},onComplete:()=>{m(),s.onComplete?.()}});if(s.autoKill!==!1)for(const S of f)g.addEventListener(S,p,{passive:!0});return b}function Og(t,e,n){const s=t.collector?.scope??t.root,i=typeof e=="string"?[...s.querySelectorAll(e)]:"nodeType"in e?[e]:Array.from(e),{interval:o=.1,batchMax:r,onEnter:a,onLeave:l,onEnterBack:c,onLeaveBack:h,...d}=n,u={onEnter:a,onLeave:l,onEnterBack:c,onLeaveBack:h},f={onEnter:[],onLeave:[],onEnterBack:[],onLeaveBack:[]},g={},p=b=>{g[b]!==void 0&&clearTimeout(g[b]),g[b]=void 0;const S=f[b].splice(0);S.length>0&&u[b]?.(S)},m=(b,S)=>{if(u[b]){if(f[b].push(S),r!==void 0&&f[b].length>=r)return p(b);g[b]===void 0&&(g[b]=setTimeout(()=>p(b),o*1e3))}};return i.map(b=>jo(t,{...d,trigger:b,onEnter:()=>m("onEnter",b),onLeave:()=>m("onLeave",b),onEnterBack:()=>m("onEnterBack",b),onLeaveBack:()=>m("onLeaveBack",b)})).filter(b=>b!==void 0)}class Zt{compat;stage;options;autoplayPending;started=!1;killed=!1;recipe=[];firstElement;scrollDriver;events=[];ranges=[];playhead={time:0,iteration:0,direction:"forward",fresh:!0};waitingToWrap=!1;finishedThisFrame=!1;backwards=!1;constructor(e,n={}){this.stage=e;const s={...n,onWarning:n.onWarning??e.onWarning};if(this.options=s,this.compat=new Oe({...s,startValue:(i,o)=>{const r=e.objectFor(i);if(r)return Hg(r[o]);const a=e.appliedValue(i,o);if(a!==void 0)return a;if(o==="d")return ec(e.elementFor(i))??void 0;if(o==="text")return e.elementFor(i)?.textContent??void 0;if(o==="strokeDasharray"||o==="strokeDashoffset"){const l=Rc(e.elementFor(i));if(l!==void 0)return o==="strokeDasharray"?[l,l]:0}},startVelocity:(i,o)=>e.velocityOf(i,o),layoutColumns:i=>Hc(i.map(o=>e.elementFor(o))),random:()=>e.utils.random(0,1)}),this.compat.timeline.onComplete=()=>{this.finishedThisFrame=!0},e.collector?.track(this),e.liveTimelines.add(this),this.autoplayPending=!s.paused&&!s.scrollTrigger,s.scrollTrigger){const i=s.scrollTrigger;queueMicrotask(()=>{this.killed||(this.scrollDriver=jo(e,i,this,this.firstElement,o=>s.onWarning?.(o)))})}this.autoplayPending&&queueMicrotask(()=>{this.autoplayPending&&this.play()})}get timeline(){return this.compat.timeline}get scrollTrigger(){return this.scrollDriver}to(e,n,s){return xg(n)?this.record(()=>this.keyframed(e,n,s)):this.record(()=>this.tween(e,[n],s,([i],o,r)=>this.compat.to(o,i,r)))}from(e,n,s){return this.record(()=>this.tween(e,[n],s,([i],o,r)=>this.compat.from(o,i,r)))}fromTo(e,n,s,i){return this.record(()=>this.tween(e,[n,s],i,([o,r],a,l)=>this.compat.fromTo(a,o,r,l)))}set(e,n,s){return this.record(()=>this.tween(e,[n],s,([i],o,r)=>this.compat.set(o,i,r)))}addLabel(e,n){return this.record(()=>this.compat.addLabel(e,n))}add(e,n){return this.record(()=>{e.autoplayPending=!1,e.timeline.stop(),e.stage.deactivate(e.timeline),this.compat.add(e.compat,n)})}invalidate(){const e=this.compat.progress();this.compat.progress(0),this.stage.render(this.timeline),this.compat.reset(),this.events=[],this.ranges=[];for(const n of this.recipe)n();return this.syncDuration(),this.compat.progress(e),this.stage.render(this.timeline),this}call(e,n=[],s){return this.record(()=>{const i=this.compat.addEvent(s);this.events.push({time:i,run:()=>e(...n)})})}addPause(e,n,s=[]){return this.record(()=>{const i=this.compat.addEvent(e);this.events.push({time:i,pause:!0,run:()=>n?.(...s)})})}tweenTo(e,n={}){return this.tweenFromTo(this.timeline.currentTime/1e3,e,n)}tweenFromTo(e,n,s={}){this.pause(),this.seek(e);const i=this.timeline.currentTime,o=Math.max(0,Math.min(this.timeline.duration,this.compat.timeOf(n))),r={time:i},a=s.duration??Math.abs(o-i)/1e3/(this.timeScale()||1),l=new Zt(this.stage,{onStart:s.onStart,onComplete:s.onComplete});return l.to(r,{time:o,duration:a,ease:s.ease??"none",onUpdate:()=>{this.moveTo(r.time),s.onUpdate?.()}}),l}play(){this.autoplayPending=!1,this.started||(this.started=!0,this.options.onStart?.());const e=this.timeline.playbackState==="playing",n=this.timeline.playbackState==="paused";if(this.timeline.play(),!e){const s=this.timeline,i=s.direction==="forward"?s.currentTime===0:s.currentTime===s.duration;this.playhead={...this.readPlayhead(),fresh:i&&!n},this.waitingToWrap=!1}return this.stage.liveTimelines.add(this),this.stage.render(this.timeline),this.stage.activate(this.timeline,{onUpdate:()=>this.afterFrame()}),this}pause(){return this.autoplayPending=!1,this.timeline.pause(),this.stage.deactivate(this.timeline),this}resume(){return this.play()}restart(){return this.timeline.stop(),this.backwards=!1,this.play()}reverse(){this.backwards=!this.backwards;const e=this.timeline.playbackState==="idle"&&this.timeline.direction==="forward";return this.timeline.reverse(),e&&this.timeline.currentTime===0&&this.timeline.seek(this.timeline.duration),this.play()}labelProgresses(){const e=this.timeline.duration;return e>0?this.compat.labelTimes().map(n=>n/e):[]}reversed(){return this.timeline.direction==="reverse"}seek(e){return this.autoplayPending=!1,this.compat.seek(e),this.stage.render(this.timeline),this.playhead=this.readPlayhead(),this.waitingToWrap=!1,this.options.onUpdate?.(),this}progress(e){return e===void 0?this.compat.progress():(this.autoplayPending=!1,this.moveTo(Math.max(0,Math.min(1,e))*this.timeline.duration),this.compat.progress())}timeScale(e){return this.compat.timeScale(e)}duration(){return this.compat.duration()}isActive(){return this.timeline.playbackState==="playing"}kill(){return this.killed=!0,this.stage.liveTimelines.delete(this),this.scrollDriver?.destroy(),this.scrollDriver=void 0,this.autoplayPending=!1,this.timeline.stop(),this.stage.deactivate(this.timeline),this.compat.kill(),this}toDefinition(){return this.compat.toDefinition()}killTweensOf(e,n){for(const s of e)for(const i of n??[void 0])this.timeline.removeTracks({target:s,...i!==void 0&&{property:i}});this.timeline.tracks.length===0&&this.events.length===0&&this.kill()}record(e){return this.recipe.push(e),e(),this.syncDuration(),this}syncDuration(){if(this.events.length===0)return;this.timeline.setDuration(void 0);const e=Math.max(...this.events.map(n=>n.time));e>this.timeline.duration&&this.timeline.setDuration(e)}readPlayhead(){const e=this.timeline;return{time:e.currentTime,iteration:e.loopIteration,direction:e.direction}}moveTo(e){const n=this.playhead;this.timeline.seek(e),this.stage.render(this.timeline);const s={time:this.timeline.currentTime,iteration:this.timeline.loopIteration,direction:e>=n.time?"forward":"reverse"},i={...n,iteration:s.iteration,direction:s.direction};this.playhead={...this.readPlayhead()},this.waitingToWrap=!1,this.runCrossings(i,s,!1),this.options.onUpdate?.()}refreshForRepeat(){const e=this.timeline.currentTime;this.compat.reset(),this.events=[],this.ranges=[];for(const n of this.recipe)n();this.syncDuration(),this.timeline.seek(Math.min(e,this.timeline.duration))}afterFrame(){const e=this.timeline,n=e.repeatDelayRemaining>0;if(this.waitingToWrap&&n){this.options.onUpdate?.();return}this.waitingToWrap=!1;const s=this.playhead,i=this.readPlayhead();this.playhead=i;const o=this.options.yoyo===!0;n&&!o&&i.iteration>s.iteration&&(this.playhead={time:0,iteration:i.iteration,direction:"forward",fresh:!0},this.waitingToWrap=!0);const r=this.runCrossings(s,i,n);if(this.options.onUpdate?.(),this.finishedThisFrame&&!r){this.finishedThisFrame=!1;const a=e.currentTime===0&&e.direction==="reverse";!this.scrollDriver&&!o&&this.stage.liveTimelines.delete(this),a&&this.backwards?this.options.onReverseComplete?.():this.options.onComplete?.()}this.finishedThisFrame=!1}runCrossings(e,n,s){if(this.events.length===0&&this.ranges.length===0&&!this.options.onRepeat&&!this.options.repeatRefresh)return!1;const i=this.events,{crossings:o,passes:r}=uo(i.map(a=>a.time),e,n,{duration:this.timeline.duration,alternate:this.options.yoyo===!0,holding:s});for(const a of o){if(this.killed)return!0;if(a.kind==="repeat"){this.options.repeatRefresh&&this.refreshForRepeat(),this.options.onRepeat?.();continue}const l=i[a.index];if(!(l.direction&&l.direction!==a.direction)){if(l.pause)return this.timeline.seek(l.time),this.stage.render(this.timeline),this.pause(),this.playhead=this.readPlayhead(),this.waitingToWrap=!1,l.run(),!0;l.run()}}for(const a of this.ranges)r.some(([c,h])=>c!==h&&Math.max(c,h)>=a.start&&Math.min(c,h)<=a.end)&&a.run();return!1}tween(e,n,s,i){const o=this.resolve(e);if(!o)return;const{onStart:r,onUpdate:a,onComplete:l}=n[n.length-1];if(r||a||l){let c=1/0,h=-1/0;const d=(u,f,g)=>{i(u,f,g),c=Math.min(c,this.compat.lastStart),h=Math.max(h,this.compat.lastEnd)};if(this.buildTween(o,n,s,d),c===1/0)return;r&&this.events.push({time:c,direction:"forward",run:r}),a&&this.ranges.push({start:c,end:h,run:a}),l&&this.events.push({time:h,direction:"forward",run:l});return}this.buildTween(o,n,s,i)}keyframed(e,n,s){const i=this.resolve(e);if(!i)return;const o=Ig(n);if(o.length===0)return;const r=i.length>1?So(n.stagger,this.staggerContext(i)):void 0,a=i.map(m=>this.targetFor(m)).filter(m=>m!==void 0),l=r?a.map(m=>[m]):[a],c=r?gs(i.length,r).map(m=>m/1e3):[0],h=this.compat.timeOf(s)/1e3+Hs(n.delay,0)/1e3;let d=1/0,u=-1/0;if(l.forEach((m,b)=>{o.forEach((S,k)=>{const y=k===0?h+c[b]:">";this.tween(m,[S],y,([M],$,E)=>this.compat.to($,M,E)),d=Math.min(d,this.compat.lastStart),u=Math.max(u,this.compat.lastEnd)})}),d===1/0)return;const{onStart:f,onUpdate:g,onComplete:p}=n;f&&this.events.push({time:d,direction:"forward",run:f}),g&&this.ranges.push({start:d,end:u,run:g}),p&&this.events.push({time:u,direction:"forward",run:p})}staggerContext(e){return{count:e.length,columnsFromLayout:()=>Hc(e.map(n=>this.stage.elementFor(n))),random:()=>this.stage.utils.random(0,1)}}buildTween(e,n,s,i){const o=e.map(u=>this.targetFor(u));if(!(e.length>1&&(n.some(Cg)||e.some(u=>this.stage.objectFor(u)!==void 0)))){const u=this.targetFor(e[0]);i(n.map(f=>this.prepare(Cc(f,0,u,this.stage.utils,o),e)),e,s);return}const a=n.length-1,{stagger:l,...c}=n[a],h=So(l,this.staggerContext(e)),d=h?gs(e.length,h).map(u=>u/1e3):e.map(()=>0);e.forEach((u,f)=>{const g=f===0?Hs(c.delay,0)/1e3+d[0]:0,p=f===0?0:d[f]-d[f-1],m=f===0?s:`<${p<0?"-":"+"}${Math.abs(p).toFixed(6)}`,S=n.map((k,y)=>y===a?{...c,delay:g}:k).map(k=>this.prepare(Cc(k,f,this.targetFor(u),this.stage.utils,o),[u]));i(S,[u],m)})}targetFor(e){return this.stage.elementFor(e)??this.stage.objectFor(e)}prepare(e,n){const s=r=>this.options.onWarning?.(r),i=r=>this.stage.query(r);let o=e;if(e.motionPath!==void 0){const r=Yp(e.motionPath,{query:i,targets:n.map(a=>this.stage.elementFor(a)).filter(a=>!!a),warn:s});o={...o,motionPath:r}}if(e.morphSVG!==void 0){const r=zp(e.morphSVG,i,s),{morphSVG:a,...l}=o;o=r?{...o,morphSVG:r}:l}if(e.drawSVG!==void 0){const r=Rc(this.stage.elementFor(n[0]));if(r===void 0){s("gsap-compat: drawSVG needs an SVG shape with a stroke (path, line, circle…)");const{drawSVG:a,...l}=o;o=l}else o=bp(o,r)}return o}resolve(e){const n=this.stage.resolveTargets(e);if(n.length===0){this.options.onWarning?.(`gsap-compat: no elements found for target ${Rg(e)}`);return}return this.firstElement??=n.map(s=>this.stage.elementFor(s)).find(s=>s!==void 0),n}}function Oc(t=new Jl){const e=o=>{const{config:r}=Cs(o);return new Zt(t,{repeat:r.repeat,yoyo:r.yoyo,repeatDelay:r.repeatDelay,paused:r.paused,onStart:r.onStart,onUpdate:r.onUpdate,onComplete:r.onComplete,onRepeat:r.onRepeat,onReverseComplete:r.onReverseComplete,repeatRefresh:r.repeatRefresh,scrollTrigger:r.scrollTrigger})},n=o=>{const{onStart:r,onUpdate:a,onComplete:l,onRepeat:c,onReverseComplete:h,repeatRefresh:d,...u}=o;return u},s=o=>(o&&t.collector?.track(o),o),i={stage:t,ticker:t.ticker,utils:t.utils,getProperty:(o,r)=>{const[a]=t.resolveTargets(o);if(a===void 0)return;const l=t.objectFor(a);return l?l[r]:t.appliedValue(a,r)??zl(r)},scrollTrigger:o=>s(jo(t,o)),scrollBatch:(o,r)=>Og(t,o,r).map(a=>s(a)),scrollTo:(o,r)=>Ic(i,t,o,r),refreshScroll:()=>{Dn.refreshAll(),Do.refreshAll()},smoothScroll:(o={})=>{const r=typeof o.scroller=="string"?(t.collector?.scope??t.root).querySelector(o.scroller):o.scroller;return s(new Do({...o,scroller:r}).start())},context:(o,r)=>{const a=new Tc(t,r);return o&&a.add(()=>o(a)),a},matchMedia:o=>new vg(t,o),customEase:Ac.create,customBounce:$c.create,customWiggle:Pc.create,pageTransition:o=>Eg(i,t,r=>new Zt(t,r),o),imageSequence:(o,r)=>{const a=typeof o=="string"?(t.collector?.scope??t.root).querySelector(o):o;if(!(a instanceof HTMLCanvasElement))throw new Error(`gsap-compat: imageSequence needs a <canvas>, got ${String(o)}`);return s(new Mg(a,r))},quickTo:(o,r,a={})=>{const l=new Zt(t,{paused:!0}),[c]=t.resolveTargets(o);return Object.assign(d=>{if(!c)return;const u=a.spring!==void 0?t.velocityOf(c,r)??0:0;l.compat.reset(),l.compat.to(c,{[r]:d,duration:a.duration??.4,ease:a.ease??"power3.out",...a.spring!==void 0&&{spring:_g(a.spring,r,u)}}),l.timeline.stop(),l.timeline.play(),t.activate(l.timeline)},{tween:l,kill:()=>l.kill()})},timeline:o=>new Zt(t,o),to:(o,r)=>{if(r.scrollTo!==void 0){const{scrollTo:a,...l}=r,c=typeof a=="object"&&a!==null&&!("nodeType"in a)?a:{},h=typeof o!="string"&&o!==window&&o.nodeType===1;return Ic(i,t,a,{...l,offsetX:c.offsetX,offsetY:c.offsetY,scroller:h?o:void 0})}return e(r).to(o,n(r))},from:(o,r)=>e(r).from(o,n(r)),fromTo:(o,r,a)=>e(a).fromTo(o,r,n(a)),set:(o,r)=>e(r).set(o,n(r)),delayedCall:(o,r,a)=>new Zt(t).call(r,a,o),killTweensOf:(o,r)=>{const a=t.resolveTargets(o),l=typeof r=="string"?r.split(",").map(c=>c.trim()).filter(Boolean):r;for(const c of[...t.liveTimelines])c.killTweensOf(a,l)},convertToPath:o=>Up(o,t.root),splitText:(o,r)=>{const a=t.collector?.scope??t.root,l=typeof o=="string"?Array.from(a.querySelectorAll(o)):"nodeType"in o?[o]:Array.from(o);return s(ng(l,r))},draggable:(o,r)=>s(Zp(i,t,o,r)),getFlipState:o=>xo(t,o),flipFrom:(o,r)=>Oo(t,a=>new Zt(t,a),o,r),flip:(o,r,a)=>{const l=xo(t,o);return r(),Oo(t,c=>new Zt(t,c),l,{targets:o,...a})}};return i}const Lt=Oc();function _g(t,e,n){return t===!0?{velocity:{[e]:n}}:typeof t=="string"?{preset:t,velocity:{[e]:n}}:{...t,velocity:{[e]:n}}}function Cg(t){return t.morphSVG!==void 0||t.drawSVG!==void 0||t.text!==void 0||t.scrambleText!==void 0||_c(t)}function _c(t){return Object.entries(t).some(([e,n])=>(typeof n=="function"||Kl(n))&&!Mo.has(e))}function Cc(t,e,n,s,i){if(!_c(t))return t;const o={};for(const[r,a]of Object.entries(t))Mo.has(r)?o[r]=a:typeof a=="function"?o[r]=a(e,n,i):Kl(a)?o[r]=s.resolveRandomString(a):o[r]=a;return o}function Hc(t){const e=t.map(s=>s?.getBoundingClientRect().top);if(e[0]===void 0)return t.length;let n=0;for(const s of e){if(s===void 0||Math.abs(s-e[0])>1)break;n++}return Math.max(1,n)}function Rc(t){const e=t;if(typeof e?.getTotalLength=="function")return e.getTotalLength()}function Hg(t){if(typeof t=="number"||typeof t=="string"||Array.isArray(t)&&t.every(e=>typeof e=="number"))return t}function Rg(t){return typeof t=="string"?`"${t}"`:String(t)}class Bo{media;offset;driftTolerance;constructor(e,n={}){this.media=e,this.offset=n.offset??0,this.driftTolerance=Math.max(0,n.driftTolerance??.15)}targetTime(e){return Math.max(0,e/1e3+this.offset)}update(e,n){const s=this.targetTime(e);n?(this.media.paused&&this.safePlay(),Math.abs(this.media.currentTime-s)>this.driftTolerance&&(this.media.currentTime=s)):(this.media.paused||this.media.pause(),this.media.currentTime!==s&&(this.media.currentTime=s))}seek(e){this.media.currentTime=this.targetTime(e)}setRate(e){this.media.playbackRate=e}dispose(){this.media.paused||this.media.pause()}safePlay(){const e=this.media.play();e&&typeof e.catch=="function"&&e.catch(()=>{})}}function Lc(t,e,n,s,i){const o=n-i;if(o<0){e.paused||e.pause(),e.currentTime=0;return}t.update(o,s)}class Ns{container;timeline=null;adapter;animationFrameId;lastTime;options;targets={};isDestroyed=!1;mediaSync;mediaTargets=[];symbolInstances=[];scenarioList=[];scenarioId;authored=new Map;markerList=[];listeners=new Set;playhead={time:0,iteration:0,direction:"forward"};stepping=!1;lastMarkerId=null;reducedQuery;onReducedChange=()=>this.applyReducedMotion();visibilityObserver;onScreen=!0;pausedByVisibility=!1;autoplayWhenSeen=!1;onDocumentVisibility=()=>this.updateVisibility();constructor(e,n={}){if(typeof e=="string"){const s=document.querySelector(e);if(!s)throw new Error(`Container not found: ${e}`);this.container=s}else this.container=e;this.options=n,this.adapter=new _e}async load(e){this.scenarioList=[],this.scenarioId=void 0,await this.loadSource(e)}async loadSource(e){let n;if(typeof e=="string"){const s=await fetch(e);if(!s.ok)throw new Error(`Failed to load animation: ${s.statusText}`);n=await s.json()}else n=e;this.useDefinition(n),this.showInitialFrame(),this.watchReducedMotion(),this.watchVisibility(),this.options.autoplay&&!this.reducedMotion&&(this.options.playWhenVisible&&!this.onScreen?this.autoplayWhenSeen=!0:this.play())}useDefinition(e){const n={...e.config};this.options.speed!==void 0&&(n.speed=this.options.speed),this.options.loop!==void 0&&(n.loop=this.options.loop),this.options.alternate!==void 0&&(n.alternate=this.options.alternate),this.timeline=Ze({...e,config:n}),this.markerList=this.timeline.markers,this.lastMarkerId=null,this.options.onComplete&&(this.timeline.onComplete=this.options.onComplete),this.options.onUpdate&&(this.timeline.onUpdate=this.options.onUpdate),this.autoRegisterTargets(),this.setupSymbolInstances(),this.scanMedia()}async loadScenarios(e,n={}){if(e.length===0)throw new Error("tinyfly: loadScenarios needs at least one scenario");const s=new Set;for(const o of e){if(s.has(o.id))throw new Error(`tinyfly: scenario id "${o.id}" is used more than once`);s.add(o.id)}const i=n.initial===void 0?e[0]:e.find(o=>o.id===n.initial);if(!i)throw new Error(`tinyfly: there is no scenario "${n.initial}"`);this.scenarioList=[...e],this.scenarioId=i.id,await this.loadSource(i.timeline)}get scenarios(){return this.scenarioList.map(e=>({id:e.id,label:e.label??e.id}))}get scenario(){return this.scenarioId}setScenario(e){const n=this.scenarioList.find(a=>a.id===e);if(!n||!this.timeline)return!1;if(e===this.scenarioId)return!0;const s=this.isPlaying,i=this.currentTime>=this.duration-.5,o=this.currentMarker?.id;this.stopAnimationLoop(),this.stepping=!1,this.pausedByVisibility=!1,this.restoreAuthored(),this.scenarioId=e,this.useDefinition(n.timeline),this.lastMarkerId=null;let r=0;return this.reducedMotion||i?r=this.duration:o!==void 0&&(r=this.markers.find(a=>a.id===o)?.time??0),this.seek(r),s&&!this.reducedMotion?(this.stepping=this.options.stepMode===!0,this.startPlaying()):this.notify(),!0}rememberAuthored(e){if(this.authored.has(e))return;const n={style:e.getAttribute("style")};e.children.length===0&&(n.text=e.textContent??"");const s=e.tagName.toLowerCase()==="path"?e:e.querySelector("path");s&&(n.path={element:s,d:s.getAttribute("d")}),this.authored.set(e,n)}restoreAuthored(){for(const[e,n]of this.authored){n.style===null?e.removeAttribute("style"):e.setAttribute("style",n.style),n.text!==void 0&&e.textContent!==n.text&&(e.textContent=n.text),n.path&&(n.path.d===null?n.path.element.removeAttribute("d"):n.path.element.setAttribute("d",n.path.d));const s=e.dataset;s&&delete s.shineBase}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notify(){for(const e of this.listeners)e()}get reducedMotion(){return this.reducedQuery?.matches===!0}get markers(){return this.markerList}get currentMarker(){const e=this.currentTime;let n;for(const s of this.markers)if(s.time<=e+.5)n=s;else break;return n}caption(e,n){const s=e?this.markers.find(r=>r.id===e):this.currentMarker;if(!s)return;const i=n??this.language(),o=r=>r?.[i]?.[s.id]??r?.[i.split("-")[0]]?.[s.id];return o(this.options.captions)??o(this.timeline?.captions)??s.label}next(){if(!this.timeline)return;const e=this.currentTime,n=this.markers.find(s=>s.time>e+.5);if(this.reducedMotion){this.seek(n?n.time:this.duration);return}e>=this.duration-.5||(this.stepping=n!==void 0,this.startPlaying())}prev(){if(!this.timeline)return;const e=this.currentTime,n=[...this.markers].reverse().find(s=>s.time<e-.5);this.pause(),this.seek(n?n.time:0)}goToMarker(e){const n=this.markers.find(s=>s.id===e);n&&(this.pause(),this.seek(n.time))}language(){return this.container.closest("[lang]")?.getAttribute("lang")||(typeof document<"u"?document.documentElement.lang:"")||"en"}showInitialFrame(){if(!this.timeline)return;const e=this.options.initialFrame??"start";if(e==="none")return;const n=e==="end"?this.timeline.duration:e==="start"?0:e;this.timeline.seek(Math.max(0,Math.min(this.timeline.duration,n))),this.applyState()}watchReducedMotion(){this.options.respectReducedMotion===!1||typeof window>"u"||typeof window.matchMedia!="function"||(this.reducedQuery??=window.matchMedia("(prefers-reduced-motion: reduce)"),this.reducedQuery.addEventListener?.("change",this.onReducedChange),this.reducedQuery.matches&&this.applyReducedMotion())}applyReducedMotion(){!this.reducedMotion||!this.timeline||(this.autoplayWhenSeen=!1,this.pause(),this.seek(this.timeline.duration))}watchVisibility(){if(!(!this.options.playWhenVisible||typeof window>"u")){if(typeof IntersectionObserver=="function"){this.visibilityObserver?.disconnect(),this.visibilityObserver=new IntersectionObserver(n=>{for(const s of n)this.onScreen=s.isIntersecting;this.updateVisibility()}),this.visibilityObserver.observe(this.container);const e=this.container.getBoundingClientRect?.();e&&(e.width>0||e.height>0)&&(this.onScreen=e.bottom>0&&e.top<window.innerHeight&&e.right>0&&e.left<window.innerWidth)}document.addEventListener("visibilitychange",this.onDocumentVisibility)}}updateVisibility(){const e=this.onScreen&&document.visibilityState!=="hidden";!e&&this.isPlaying?(this.pausedByVisibility=!0,this.pause()):e&&(this.pausedByVisibility||this.autoplayWhenSeen)&&!this.reducedMotion&&(this.pausedByVisibility=!1,this.autoplayWhenSeen=!1,this.startPlaying())}announceMarker(){if(!this.options.onMarker)return;const e=this.currentMarker,n=e?.id;n!==this.lastMarkerId&&(this.lastMarkerId=n,this.options.onMarker(e))}scanMedia(){this.mediaTargets=[],this.container.querySelectorAll("[data-tinyfly-media]").forEach(n=>{const s=n,i=Number(s.getAttribute("data-tinyfly-start")??"0")||0,o=s.getAttribute("data-volume");o!==null&&(s.volume=Math.max(0,Math.min(1,Number(o)||0))),this.mediaTargets.push({el:s,startTime:i,sync:new Bo(s)})})}syncAllMedia(e,n){for(const s of this.mediaTargets)Lc(s.sync,s.el,e,n,s.startTime)}loadFromString(e){const n=JSON.parse(e);this.load(n)}registerTarget(e,n){if(typeof n=="string"){const s=this.container.querySelector(n);s&&(this.rememberAuthored(s),this.targets[e]=s,this.adapter.registerTarget(e,s))}else this.rememberAuthored(n),this.targets[e]=n,this.adapter.registerTarget(e,n)}autoRegisterTargets(){this.container.querySelectorAll("[data-tinyfly]").forEach(n=>{const s=n.closest("[data-tinyfly-symbol]");if(s&&s!==n)return;const i=n.getAttribute("data-tinyfly");i&&this.registerTarget(i,n)}),this.timeline&&new Set(this.timeline.tracks.map(s=>s.target)).forEach(s=>{if(!this.targets[s]){const i=this.container.querySelector(`[data-tinyfly="${s}"]`)||this.container.querySelector(`.${s}`)||this.container.querySelector(`#${s}`);i&&this.registerTarget(s,i)}})}setupSymbolInstances(){this.symbolInstances=[];const e=this.options.symbols;if(!e||e.length===0)return;const n=new Map(e.map(s=>[s.id,s]));this.container.querySelectorAll("[data-tinyfly-symbol]").forEach(s=>{const i=s.getAttribute("data-tinyfly-symbol");if(!i)return;const o=n.get(i);if(!o||!o.timeline.tracks?.length)return;const r=new _e;s.querySelectorAll("[data-tinyfly]").forEach(a=>{const l=a.getAttribute("data-tinyfly");l&&r.registerTarget(l,a)}),this.symbolInstances.push({adapter:r,timeline:Ze(o.timeline)})})}attachMedia(e,n){this.mediaSync=new Bo(e,n),this.timeline&&(this.mediaSync.setRate(this.timeline.speed),this.mediaSync.update(this.timeline.currentTime,this.isPlaying))}detachMedia(){this.mediaSync?.dispose(),this.mediaSync=void 0}play(){!this.timeline||this.isDestroyed||(this.autoplayWhenSeen=!1,this.stepping=this.options.stepMode===!0,this.startPlaying())}startPlaying(){if(!this.timeline||this.isDestroyed)return;const e=this.timeline.playbackState==="idle";this.timeline.play(),e&&this.timeline.currentTime===0&&this.applyState(),this.playhead={time:this.timeline.currentTime,iteration:this.timeline.loopIteration,direction:this.timeline.direction},this.mediaSync?.update(this.timeline.currentTime,!0),this.syncAllMedia(this.timeline.currentTime,!0),this.startAnimationLoop(),this.notify()}pause(){this.timeline&&(this.stepping=!1,this.timeline.pause(),this.notify(),this.mediaSync?.update(this.timeline.currentTime,!1),this.syncAllMedia(this.timeline.currentTime,!1),this.stopAnimationLoop())}stop(){this.timeline&&(this.timeline.stop(),this.stopAnimationLoop(),this.applyState(),this.mediaSync?.update(this.timeline.currentTime,!1),this.syncAllMedia(this.timeline.currentTime,!1))}seek(e){this.timeline&&(this.timeline.seek(e),this.applyState(),this.playhead={time:this.timeline.currentTime,iteration:this.timeline.loopIteration,direction:this.timeline.direction},this.mediaSync?.seek(this.timeline.currentTime),this.syncAllMedia(this.timeline.currentTime,this.isPlaying))}setSpeed(e){this.timeline&&(this.timeline.speed=e,this.mediaSync?.setRate(e))}reverse(){this.timeline&&this.timeline.reverse()}get currentTime(){return this.timeline?.currentTime??0}get duration(){return this.timeline?.duration??0}get isPlaying(){return this.timeline?.playbackState==="playing"}destroy(){this.isDestroyed=!0,this.stopAnimationLoop(),this.reducedQuery?.removeEventListener?.("change",this.onReducedChange),this.visibilityObserver?.disconnect(),typeof document<"u"&&document.removeEventListener("visibilitychange",this.onDocumentVisibility),this.mediaSync?.dispose(),this.mediaSync=void 0;for(const e of this.mediaTargets)e.el.paused||e.el.pause();this.mediaTargets=[],this.adapter.clearTargets();for(const e of this.symbolInstances)e.adapter.clearTargets();this.symbolInstances=[],this.authored.clear(),this.timeline=null}startAnimationLoop(){if(this.animationFrameId!==void 0)return;this.lastTime=performance.now();const e=n=>{if(this.isDestroyed||!this.timeline)return;const s=n-(this.lastTime??n);this.lastTime=n;const i=this.playhead;this.timeline.tick(s),this.stopAtMarker(i),this.applyState();const o=this.timeline.playbackState==="playing";this.mediaSync?.update(this.timeline.currentTime,o),this.syncAllMedia(this.timeline.currentTime,o),this.timeline.playbackState==="playing"?this.animationFrameId=requestAnimationFrame(e):(this.animationFrameId=void 0,this.notify())};this.animationFrameId=requestAnimationFrame(e)}stopAtMarker(e){const n=this.timeline,s={time:n.currentTime,iteration:n.loopIteration,direction:n.direction};this.playhead=s;const i=this.markers;if(i.length===0)return;const{crossings:o}=uo(i.map(r=>r.time),e,s,{duration:n.duration,alternate:n.config.alternate===!0,holding:n.repeatDelayRemaining>0});for(const r of o){if(r.kind!=="event")continue;const a=i[r.index];if(this.stepping||a.pause){this.stepping=!1,n.pause(),n.seek(a.time),this.playhead={time:a.time,iteration:n.loopIteration,direction:n.direction};return}}}stopAnimationLoop(){this.animationFrameId!==void 0&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0)}applyState(){if(!this.timeline)return;const e=this.timeline.currentTime;this.adapter.applyState(this.timeline.getStateAtTime(e)),this.announceMarker(),this.notify();for(const n of this.symbolInstances){const s=n.timeline.duration;n.adapter.applyState(n.timeline.getStateAtTime(s>0?e%s:e))}}}async function Lg(t,e,n={}){const s=new Ns(t,{...n,autoplay:!0});return await s.load(e),s}function Ng(t,e={}){return new Ns(t,e)}const Nc={play:"Play",pause:"Pause",prev:"Previous step",next:"Next step",restart:"Restart",scrub:"Position",speed:"Speed",reveal:"Reveal",step:"Step",of:"of",stepFormat:"{index} / {total}",scenario:"Scenario",fullscreen:"Full screen",exitFullscreen:"Exit full screen"},Dc="tinyfly-controls-style",Dg=`
|
|
1
|
+
(function(w){"use strict";function ml(t){return typeof t=="object"&&t!==null&&t.type==="cubic-bezier"}function Ln(t){return typeof t=="object"&&t!==null&&t.type!=="cubic-bezier"}const fo=2;function go(t){return t.some(e=>e.interpolation!==void 0)?2:1}function Is(t){return t.property==="text"&&"textConfig"in t}function me(t){return t.kind==="inertia"&&"inertia"in t}function ye(t){return t.kind==="spring"&&"spring"in t}function po(t){return t.property==="motionPath"&&"motionPathConfig"in t}function ig(t){return typeof t=="object"&&t!==null&&"x"in t&&"y"in t&&"angle"in t}function yl(t){return"keyframes"in t}class og{_currentTime=0;_isRunning=!1;onTick=null;get currentTime(){return this._currentTime}get isRunning(){return this._isRunning}start(){this._isRunning=!0}stop(){this._isRunning=!1}tick(e){this._currentTime+=e,this.onTick?.(e,this._currentTime)}reset(){this._currentTime=0}seek(e){this._currentTime=e}}class rg{_currentTime=0;_isRunning=!1;_lastFrameTime=null;_rafId=null;_speed;onTick=null;constructor(e={}){this._speed=e.speed??1}get currentTime(){return this._currentTime}get isRunning(){return this._isRunning}get speed(){return this._speed}set speed(e){this._speed=e}start(){this._isRunning||(this._isRunning=!0,this._lastFrameTime=null,this._scheduleFrame())}stop(){this._isRunning=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}reset(){this._currentTime=0,this._lastFrameTime=null}seek(e){this._currentTime=e}_scheduleFrame(){this._rafId=requestAnimationFrame(this._onFrame.bind(this))}_onFrame(e){if(this._isRunning){if(this._lastFrameTime!==null){const s=(e-this._lastFrameTime)*this._speed;this._currentTime+=s,this.onTick?.(s,this._currentTime)}this._lastFrameTime=e,this._scheduleFrame()}}}function bl(t,e){if(!(e>0))return t;const n=1e3/e;return Math.floor(t/n+1e-9)*n}function mo(t,e,n="start"){if(e<=1)return 0;if(typeof n=="number"){const s=Math.max(0,Math.min(e-1,n));return Math.abs(t-s)}switch(n){case"end":return e-1-t;case"center":return Math.abs(t-(e-1)/2);case"edges":return(e-1)/2-Math.abs(t-(e-1)/2);default:return t}}function yo(t,e="start"){if(t<=1)return 0;let n=0;for(let s=0;s<t;s++)n=Math.max(n,mo(s,t,e));return n}function Os(t,e,n){if(n.offsets)return n.offsets[t]??0;const s=n.from??"start",i=mo(t,e,s);if(n.amount!==void 0){const o=yo(e,s);return o===0?0:n.amount*i/o}return n.each!==void 0?n.each*i:0}function _s(t,e){return Array.from({length:t},(n,s)=>Os(s,t,e))}function Fn(t,e){return t<=1?0:Math.max(..._s(t,e))}const nn=1,bo=6e4,Cs=bo/nn,Yt={stiffness:180,damping:12,mass:1,velocity:0,restDelta:.01,restSpeed:.1},Hs={gentle:{stiffness:120,damping:18,mass:1},default:{stiffness:180,damping:12,mass:1},snappy:{stiffness:280,damping:20,mass:1},bouncy:{stiffness:220,damping:8,mass:1},wobbly:{stiffness:180,damping:5,mass:1},stiff:{stiffness:400,damping:30,mass:1}};class Nn{from;to;stiffness;damping;mass;restDelta;restSpeed;distance;samples;velocity;settledStep=null;constructor(e){this.from=e.from,this.to=e.to,this.stiffness=e.stiffness??Yt.stiffness,this.damping=e.damping??Yt.damping,this.mass=e.mass??Yt.mass,this.restDelta=e.restDelta??Yt.restDelta,this.restSpeed=e.restSpeed??Yt.restSpeed,this.distance=Math.abs(this.to-this.from)||1,this.samples=[this.from],this.velocity=e.velocity??Yt.velocity,this.isAtRest(this.from)&&(this.settledStep=0)}isAtRest(e){return Math.abs(e-this.to)<this.restDelta*this.distance&&Math.abs(this.velocity)<this.restSpeed*this.distance}valueAt(e){if(e<=0)return this.from;const n=Math.floor(e/nn);if(this.simulateTo(n+1),this.settledStep!==null&&n>=this.settledStep)return this.to;const s=this.samples[Math.min(n,this.samples.length-1)],i=this.samples[Math.min(n+1,this.samples.length-1)],o=e/nn-n;return s+(i-s)*o}settleTime(){return this.simulateTo(Cs+1),this.settledStep!==null?this.settledStep*nn:bo}simulateTo(e){if(this.settledStep!==null)return;const n=Math.min(e,Cs+1),s=nn/1e3;for(;this.samples.length<n;){const i=this.samples[this.samples.length-1],o=i-this.to,r=-this.stiffness*o,a=-this.damping*this.velocity,l=(r+a)/this.mass;this.velocity+=l*s;const c=i+this.velocity*s;if(this.samples.push(c),this.isAtRest(c)){this.settledStep=this.samples.length-1;return}}this.samples.length>Cs&&(this.settledStep=Cs)}}function ag(t,e){return new Nn(t).valueAt(e)}function wl(t){return new Nn(t).settleTime()}function lg(t){const e=t.stiffness??Yt.stiffness,n=t.damping??Yt.damping,s=t.mass??Yt.mass;return n<2*Math.sqrt(e*s)}function cg(t){const e=t.stiffness??Yt.stiffness,n=t.mass??Yt.mass;return 2*Math.sqrt(e*n)}const wo=4,hg=.002,ug=1e-4,kl=6e4;function Rs(t){const e=t.friction??wo;return e>0?e:wo}function Dn(t){return t.from+t.velocity/Rs(t)}function dg(t,e){if(e===void 0)return t;if(typeof e=="number")return e>0?Math.round(t/e)*e:t;if(e.length===0)return t;let n=e[0];for(const s of e)Math.abs(s-t)<Math.abs(n-t)&&(n=s);return n}function sn(t){let e=dg(Dn(t),t.end);return t.min!==void 0&&(e=Math.max(t.min,e)),t.max!==void 0&&(e=Math.min(t.max,e)),e}function on(t){const e=Math.abs(sn(t)-t.from);if(e===0)return 0;const n=t.restDelta??Math.max(ug,e*hg);if(n>=e)return 0;const s=Math.log(e/n)/Rs(t);return Math.min(kl,s*1e3)}function Ls(t,e){if(e<=0)return t.from;const n=sn(t);if(e>=on(t))return n;const s=Rs(t);return t.from+(n-t.from)*(1-Math.exp(-s*e/1e3))}function fg(t,e){const n=Rs(t),s=sn(t);return e>=on(t)?0:(s-t.from)*n*Math.exp(-n*Math.max(0,e)/1e3)}const Fs=t=>t,vl=t=>t*t,Ml=t=>1-(1-t)*(1-t),Sl=t=>t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2,ko=t=>t*t*t,vo=t=>1-Math.pow(1-t,3),Wn=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,Tl=ko,El=vo,Al=Wn,gg={linear:Fs,"ease-in":Tl,"ease-out":El,"ease-in-out":Al,"ease-in-quad":vl,"ease-out-quad":Ml,"ease-in-out-quad":Sl,"ease-in-cubic":ko,"ease-out-cubic":vo,"ease-in-out-cubic":Wn};function xl(t){const[e,n,s,i]=t,o=3*e,r=3*(s-e)-o,a=1-o-r,l=3*n,c=3*(i-n)-l,h=1-l-c,u=g=>((a*g+r)*g+o)*g,d=g=>((h*g+c)*g+l)*g,f=g=>(3*a*g+2*r)*g+o,p=g=>{let m=g;for(let k=0;k<8;k++){const b=u(m)-g;if(Math.abs(b)<1e-7)return m;const A=f(m);if(Math.abs(A)<1e-7)break;m-=b/A}let y=0,T=1;for(m=g;y<T;){const k=u(m);if(Math.abs(k-g)<1e-7)return m;g>k?y=m:T=m,m=(y+T)/2}return m};return g=>{if(g<=0)return 0;if(g>=1)return 1;const m=p(g);return d(m)}}function Mo(t,e="out"){if(e==="out")return t;const n=s=>1-t(1-s);return e==="in"?n:s=>s<.5?n(s*2)/2:t(s*2-1)/2+.5}function $l(t=1,e=.3){const n=Math.max(1,t),s=e/(2*Math.PI)*Math.asin(1/n);return i=>i<=0?0:i>=1?1:n*Math.pow(2,-10*i)*Math.sin((i-s)*(2*Math.PI)/e)+1}const Pl=t=>{if(t<=0)return 0;if(t>=1)return 1;if(t<1/2.75)return 7.5625*t*t;if(t<2/2.75){const i=t-.5454545454545454;return 7.5625*i*i+.75}if(t<2.5/2.75){const i=t-.8181818181818182;return 7.5625*i*i+.9375}const s=t-2.625/2.75;return 7.5625*s*s+.984375};function Il(t=1.70158){return e=>{if(e<=0)return 0;if(e>=1)return 1;const n=e-1;return n*n*((t+1)*n+t)+1}}function Ol(t,e="end"){const n=Math.max(1,Math.floor(t));return s=>{if(s>=1)return 1;if(s<=0)return e==="start"||e==="both"?e==="start"?1/n:1/(n+1):0;const i=Math.floor(s*n);switch(e){case"start":return Math.min(1,(i+1)/n);case"both":return(i+1)/(n+1);case"none":return n===1?0:Math.min(1,i/(n-1));default:return i/n}}}function _l(t){switch(t.type){case"steps":return Ol(t.count,t.position);case"elastic":return Mo($l(t.amplitude,t.period),t.mode);case"bounce":return Mo(Pl,t.mode);case"back":return Mo(Il(t.overshoot),t.mode)}}function Ct(t){return t===void 0?Fs:ml(t)?xl(t.points):Ln(t)?_l(t):gg[t]??Fs}const Cl=32,pg=256,rn=new Map,mg=/[MmLlHhVvCcSsQqTtAaZz]/,yg=/^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/,bg={M:2,L:2,H:1,V:1,C:6,S:4,Q:4,T:2,A:7,Z:0};function wg(t){const e=[];let n=0,s=null;const i=()=>{for(;n<t.length&&/[\s,]/.test(t[n]);)n++};for(;n<t.length&&(i(),!(n>=t.length));){const o=t[n];if(mg.test(o)){s={type:o,args:[]},e.push(s),n++;continue}if(!s)break;const r=s.type==="A"||s.type==="a",a=s.args.length%7;if(r&&(a===3||a===4)){if(o!=="0"&&o!=="1")break;s.args.push(o==="1"?1:0),n++;continue}const l=yg.exec(t.slice(n));if(!l)break;s.args.push(parseFloat(l[0])),n+=l[0].length}return e}function kg(t,e,n,s,i,o,r,a,l){if(t===a&&e===l)return[];let c=Math.abs(n),h=Math.abs(s);if(c===0||h===0)return[[t,e,a,l,a,l]];const u=i*Math.PI/180,d=Math.cos(u),f=Math.sin(u),p=(t-a)/2,g=(e-l)/2,m=d*p+f*g,y=-f*p+d*g,T=m*m/(c*c)+y*y/(h*h);if(T>1){const H=Math.sqrt(T);c*=H,h*=H}const k=o===r?-1:1,b=c*c*h*h-c*c*y*y-h*h*m*m,A=c*c*y*y+h*h*m*m,M=k*Math.sqrt(Math.max(0,b/A)),E=M*c*y/h,x=-M*h*m/c,S=d*E-f*x+(t+a)/2,I=f*E+d*x+(e+l)/2,v=(H,N,D,O)=>{const L=H*D+N*O,q=Math.sqrt((H*H+N*N)*(D*D+O*O)),G=Math.acos(Math.max(-1,Math.min(1,L/q)));return H*O-N*D<0?-G:G},$=v(1,0,(m-E)/c,(y-x)/h);let _=v((m-E)/c,(y-x)/h,(-m-E)/c,(-y-x)/h);!r&&_>0&&(_-=2*Math.PI),r&&_<0&&(_+=2*Math.PI);const P=Math.max(1,Math.ceil(Math.abs(_)/(Math.PI/2))),C=_/P,F=4/3*Math.tan(C/4),R=H=>{const N=c*Math.cos(H),D=h*Math.sin(H);return[d*N-f*D+S,f*N+d*D+I]},B=H=>{const N=-c*Math.sin(H),D=h*Math.cos(H);return[d*N-f*D,f*N+d*D]},j=[];for(let H=0;H<P;H++){const N=$+H*C,D=N+C,[O,L]=R(N),[q,G]=H===P-1?[a,l]:R(D),[K,Z]=B(N),[nt,W]=B(D);j.push([O+F*K,L+F*Z,q-F*nt,G-F*W,q,G])}return j}function be(t,e,n,s,i){const o=1-i;return o*o*o*t+3*o*o*i*e+3*o*i*i*n+i*i*i*s}function Hl(t,e,n,s,i){const o=1-i;return 3*o*o*(e-t)+6*o*i*(n-e)+3*i*i*(s-n)}function Bn(t,e,n,s){return{subpath:0,type:"L",points:[n,s],startX:t,startY:e,endX:n,endY:s,length:Math.hypot(n-t,s-e)}}function Ns(t,e,n){const[s,i,o,r,a,l]=n,c=[0];let h=t,u=e,d=0;for(let f=1;f<=Cl;f++){const p=f/Cl,g=be(t,s,o,a,p),m=be(e,i,r,l,p);d+=Math.hypot(g-h,m-u),c.push(d),h=g,u=m}return{subpath:0,type:"C",points:[s,i,o,r,a,l],startX:t,startY:e,endX:a,endY:l,length:d,lengths:c}}function Fe(t){const e=rn.get(t);if(e)return e;const n=[];let s=0,i=0,o=0,r=0,a=null,l=null,c=-1;const h=new Set,u=g=>{c<0&&(c=0),g.subpath=c,n.push(g)};for(const{type:g,args:m}of wg(t)){const y=g.toUpperCase(),T=g!==y,k=bg[y];if(y==="Z"){(s!==o||i!==r)&&u(Bn(s,i,o,r)),c>=0&&h.add(c),s=o,i=r,a=l=null;continue}for(let b=0;b+k<=m.length;b+=k){const A=m.slice(b,b+k),M=T?s:0,E=T?i:0;let x=null,S=null;switch(y){case"M":b===0?(s=A[0]+M,i=A[1]+E,o=s,r=i,(c<0||n[n.length-1]?.subpath===c)&&c++):(u(Bn(s,i,A[0]+M,A[1]+E)),s=A[0]+M,i=A[1]+E);break;case"L":u(Bn(s,i,A[0]+M,A[1]+E)),s=A[0]+M,i=A[1]+E;break;case"H":u(Bn(s,i,A[0]+M,i)),s=A[0]+M;break;case"V":u(Bn(s,i,s,A[0]+E)),i=A[0]+E;break;case"C":{const I=[A[0]+M,A[1]+E,A[2]+M,A[3]+E,A[4]+M,A[5]+E];u(Ns(s,i,I)),x=[I[2],I[3]],s=I[4],i=I[5];break}case"S":{const[I,v]=a?[2*s-a[0],2*i-a[1]]:[s,i],$=[I,v,A[0]+M,A[1]+E,A[2]+M,A[3]+E];u(Ns(s,i,$)),x=[$[2],$[3]],s=$[4],i=$[5];break}case"Q":case"T":{let I=s,v=i;y==="Q"?(I=A[0]+M,v=A[1]+E):l&&(I=2*s-l[0],v=2*i-l[1]);const $=y==="Q"?A[2]+M:A[0]+M,_=y==="Q"?A[3]+E:A[1]+E;u(Ns(s,i,[s+2/3*(I-s),i+2/3*(v-i),$+2/3*(I-$),_+2/3*(v-_),$,_])),S=[I,v],s=$,i=_;break}case"A":{const I=A[5]+M,v=A[6]+E;let $=s,_=i;for(const P of kg(s,i,A[0],A[1],A[2],A[3],A[4],I,v))u(Ns($,_,P)),$=P[4],_=P[5];s=I,i=v;break}}a=x,l=S}}const d=n.reduce((g,m)=>g+m.length,0),f=[];for(let g=0;g<n.length;){const m=n[g].subpath;let y=g,T=0;for(;y<n.length&&n[y].subpath===m;)T+=n[y++].length;const k=n[g],b=n[y-1],A=h.has(m)||Math.abs(b.endX-k.startX)<1e-9&&Math.abs(b.endY-k.startY)<1e-9;f.push({start:g,end:y,length:T,closed:A}),g=y}const p={segments:n,totalLength:d,subpaths:f};return rn.size>=pg&&rn.delete(rn.keys().next().value),rn.set(t,p),p}function vg(t,e){const n=t.lengths;if(e<=0)return 0;if(e>=t.length)return 1;let s=0,i=n.length-1;for(;s<i-1;){const a=s+i>>1;n[a]<e?s=a:i=a}const o=n[i]-n[s],r=o>0?(e-n[s])/o:0;return(s+r)/(n.length-1)}function Mg(t,e){if(t.type==="L"){const u=t.length>0?Math.max(0,Math.min(1,e/t.length)):0;return{x:t.startX+(t.endX-t.startX)*u,y:t.startY+(t.endY-t.startY)*u,angle:Math.atan2(t.endY-t.startY,t.endX-t.startX)*180/Math.PI}}const[n,s,i,o,r,a]=t.points,l=vg(t,e);let c=Hl(t.startX,n,i,r,l),h=Hl(t.startY,s,o,a,l);if(Math.hypot(c,h)<1e-9){const u=l<.5?Math.min(1,l+.001):Math.max(0,l-.001),d=be(t.startX,n,i,r,u),f=be(t.startY,s,o,a,u),p=be(t.startX,n,i,r,l),g=be(t.startY,s,o,a,l);c=l<.5?d-p:p-d,h=l<.5?f-g:g-f}return{x:be(t.startX,n,i,r,l),y:be(t.startY,s,o,a,l),angle:Math.atan2(h,c)*180/Math.PI}}function So(t,e,n=0,s=t.length){if(s<=n)return{x:0,y:0,angle:0};let i=0;for(let o=n;o<s;o++){const r=t[o];if(i+r.length>=e||o===s-1)return Mg(r,e-i);i+=r.length}return{x:0,y:0,angle:0}}function Rl(t,e){const{segments:n,totalLength:s}=Fe(t);return So(n,Math.max(0,Math.min(1,e))*s)}function Sg(){rn.clear()}function Tg(t){return Fe(t).totalLength}const Eg=24,Ag=320,xg=2.5,jn=72,$g=64,Pg=.2,Ig=128,qn=new Map;let Ds=0,we;const Ll=t=>Math.round(t*100)/100;function Fl(t,e){const{segments:n,subpaths:s,totalLength:i}=Fe(t);if(n.length===0)return[];if(e){const o=s.every(r=>r.closed);return[{segments:n,start:0,end:n.length,length:i,closed:o}]}return s.filter(o=>o.length>0).map(o=>({segments:n,start:o.start,end:o.end,length:o.length,closed:o.closed}))}function To(t,e){const n=t.closed?(e%1+1)%1:Math.max(0,Math.min(1,e)),s=So(t.segments,n*t.length,t.start,t.end);return[s.x,s.y]}function Nl(t){const e=[];let n=0;for(let s=t.start;s<t.end;s++)n+=t.segments[s].length,t.length>0&&e.push(n/t.length);return e}function Dl(t,e){const n=[];for(let s=0;s<e;s++)n.push(To(t,t.closed?s/e:s/(e-1)));return n}function Wl(t){let e=0,n=0;for(const[s,i]of t)e+=s,n+=i;return e/=t.length,n/=t.length,t.map(([s,i])=>[s-e,i-n])}function Og(t,e,n){const s=t.closed&&e.closed;if(n!==void 0)return{offset:s?Math.abs(n)%jn/jn:0,reversed:n<0};const i=Wl(Dl(t,jn)),o=Wl(Dl(e,jn)),r=jn;let a={offset:0,reversed:!1},l=1/0;for(const c of[!1,!0]){const h=s?r:1;for(let u=0;u<h;u++){let d=0;for(let f=0;f<r&&d<l;f++){const p=s?c?(u-f+r)%r:(f+u)%r:c?r-1-f:f,g=i[f][0]-o[p][0],m=i[f][1]-o[p][1];d+=g*g+m*m}d<l&&(l=d,a={offset:s?u/r:0,reversed:c})}}return a}function _g(t,e,n){return n?((e.reversed?e.offset-t:t+e.offset)%1+1)%1:e.reversed?1-t:t}function Cg(t,e,n){return n?((e.reversed?e.offset-t:t-e.offset)%1+1)%1:e.reversed?1-t:t}function Hg(t,e,n){const s=t.closed&&e.closed,i=Og(t,e,n.shapeIndex),o=Math.max(Eg,Math.min(Ag,Math.ceil(Math.max(t.length,e.length)/xg))),r=new Set,a=u=>r.add(Math.round(u*1e7)/1e7);for(let u=0;u<=o;u++)a(u/o);for(const u of Nl(t))a(u);for(const u of Nl(e))a(Cg(u,i,s));let l=[...r].sort((u,d)=>u-d);s&&(l=l.filter(u=>u<1));const c=[],h=[];for(const u of l)c.push(...To(t,u)),h.push(...To(e,_g(u,i,s)));return Rg({from:c,to:h,closed:s})}function Rg(t){const e=t.from.length/2;if(e<=3)return t;const n=new Uint8Array(e);n[0]=1,n[e-1]=1;const s=[[0,e-1]];for(;s.length>0;){const[r,a]=s.pop();let l=-1,c=Pg;for(let h=r+1;h<a;h++){const u=Math.max(Bl(t.from,r,a,h),Bl(t.to,r,a,h));u>c&&(c=u,l=h)}l!==-1&&(n[l]=1,s.push([r,l],[l,a]))}const i=[],o=[];for(let r=0;r<e;r++)n[r]&&(i.push(t.from[r*2],t.from[r*2+1]),o.push(t.to[r*2],t.to[r*2+1]));return{from:i,to:o,closed:t.closed}}function Bl(t,e,n,s){const i=t[e*2],o=t[e*2+1],r=t[n*2]-i,a=t[n*2+1]-o,l=t[s*2]-i,c=t[s*2+1]-o,h=r*r+a*a,u=h===0?0:Math.max(0,Math.min(1,(l*r+c*a)/h));return Math.hypot(l-u*r,c-u*a)}function Lg(t,e,n){const s=n.shapeIndex;if(we&&we.from===t&&we.to===e&&we.shapeIndex===s)return we.plan;const o=qn.get(String(s??"auto"))?.get(t)?.get(e);if(o)return we={from:t,to:e,shapeIndex:s,plan:o},o;const r=Fe(t).subpaths.filter(f=>f.length>0).length===Fe(e).subpaths.filter(f=>f.length>0).length,a=Fl(t,!r),l=Fl(e,!r),c={pairs:a.map((f,p)=>Hg(f,l[p],n))};Ds>=Ig&&(qn.clear(),Ds=0);const h=String(s??"auto"),u=qn.get(h)??new Map;qn.set(h,u);const d=u.get(t)??new Map;return u.set(t,d),d.set(e,c),Ds++,we={from:t,to:e,shapeIndex:s,plan:c},c}function jl(t,e,n,s={}){if(!t)return e;if(!e)return t;const i=Math.max(0,Math.min(1,n));if(i===0)return t;if(i===1)return e;const o=Lg(t,e,s);if(o.pairs.length===0)return i<.5?t:e;let r="";for(const a of o.pairs){for(let l=0;l<a.from.length;l+=2){const c=Ll(a.from[l]+(a.to[l]-a.from[l])*i),h=Ll(a.from[l+1]+(a.to[l+1]-a.from[l+1])*i);r+=`${l===0?r?" M":"M":" L"}${c} ${h}`}a.closed&&(r+=" Z")}return r}function Fg(){qn.clear(),Ds=0,we=void 0}function an(t){return/^\s*[Mm]\s*[-+]?(?:\d|\.\d)/.test(t)}const ln=Math.PI/180,Ng=.9995;function Eo(){return[0,0,0,1]}function Kt(t,e){const n=Math.hypot(t[0],t[1],t[2]);if(n===0)return Eo();const s=e*ln/2,i=Math.sin(s)/n;return[t[0]*i,t[1]*i,t[2]*i,Math.cos(s)]}function Dg(t,e,n){return Ao(Ao(Kt([0,1,0],e),Kt([1,0,0],t)),Kt([0,0,1],n))}function Wg(t){const[e,n,s,i]=ke(t),o=2*(e*s+n*i),r=2*(e*n+s*i),a=1-2*(e*e+s*s),l=2*(n*s-e*i),c=1-2*(n*n+s*s),h=2*(e*s-n*i),u=1-2*(e*e+n*n),d=Math.asin(Math.max(-1,Math.min(1,-l)));return Math.abs(l)<.9999999?[d/ln,Math.atan2(o,u)/ln,Math.atan2(r,a)/ln]:[d/ln,Math.atan2(-h,c)/ln,0]}function Ao(t,e){const[n,s,i,o]=t,[r,a,l,c]=e;return[o*r+n*c+s*l-i*a,o*a-n*l+s*c+i*r,o*l+n*a-s*r+i*c,o*c-n*r-s*a-i*l]}function ql(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]}function Yl(t){return Math.hypot(t[0],t[1],t[2],t[3])}function ke(t){const e=Yl(t);return e===0?Eo():[t[0]/e,t[1]/e,t[2]/e,t[3]/e]}function Bg(t){return[-t[0],-t[1],-t[2],t[3]]}function Kl(t,e,n){const s=ke(t);let i=ke(e),o=ql(s,i);if(o<0&&(i=[-i[0],-i[1],-i[2],-i[3]],o=-o),o>Ng)return ke([s[0]+(i[0]-s[0])*n,s[1]+(i[1]-s[1])*n,s[2]+(i[2]-s[2])*n,s[3]+(i[3]-s[3])*n]);const r=Math.acos(o),a=Math.sin(r),l=Math.sin((1-n)*r)/a,c=Math.sin(n*r)/a;return ke([s[0]*l+i[0]*c,s[1]*l+i[1]*c,s[2]*l+i[2]*c,s[3]*l+i[3]*c])}function jg(t,e){const[n,s,i,o]=ke(t),r=2*(s*e[2]-i*e[1]),a=2*(i*e[0]-n*e[2]),l=2*(n*e[1]-s*e[0]);return[e[0]+o*r+(s*l-i*a),e[1]+o*a+(i*r-n*l),e[2]+o*l+(n*a-s*r)]}const qg=Object.freeze(Object.defineProperty({__proto__:null,conjugate:Bg,dot:ql,fromAxisAngle:Kt,fromEuler:Dg,identity:Eo,length:Yl,multiply:Ao,normalize:ke,rotateVec3:jg,slerp:Kl,toEuler:Wg},Symbol.toStringTag,{value:"Module"})),ee=(t,e,n)=>t+(e-t)*n,zl=512,xo=new Map,$o=new Map;function Xl(t){const e=xo.get(t);if(e)return e;const n=t.replace("#",""),s=[parseInt(n.slice(0,2),16),parseInt(n.slice(2,4),16),parseInt(n.slice(4,6),16)];return xo.size<zl&&xo.set(t,s),s}const Gl=t=>t.charCodeAt(0)===35,Ul=t=>t.startsWith("rgb"),Vl=t=>t.startsWith("rgba"),Yg=/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/,Po=t=>Math.round(t).toString(16).padStart(2,"0");function Kg(t,e,n){return`#${Po(t)}${Po(e)}${Po(n)}`}function Jl(t){const e=$o.get(t);if(e)return e;const n=t.match(Yg);if(!n)throw new Error(`Invalid rgb color: ${t}`);const s=parseInt(n[1],10),i=parseInt(n[2],10),o=parseInt(n[3],10),r=n[4]!==void 0?[s,i,o,parseFloat(n[4])]:[s,i,o];return $o.size<zl&&$o.set(t,r),r}const Zl=(t,e,n)=>{if(Gl(t)&&Gl(e)){const[s,i,o]=Xl(t),[r,a,l]=Xl(e),c=ee(s,r,n),h=ee(i,a,n),u=ee(o,l,n);return Kg(c,h,u)}if((Ul(t)||Vl(t))&&(Ul(e)||Vl(e))){const s=Jl(t),i=Jl(e),o=Math.round(ee(s[0],i[0],n)),r=Math.round(ee(s[1],i[1],n)),a=Math.round(ee(s[2],i[2],n));if(s.length===4||i.length===4){const l=s[3]??1,c=i[3]??1,h=ee(l,c,n);return`rgba(${o}, ${r}, ${a}, ${h})`}return`rgb(${o}, ${r}, ${a})`}return n<1?t:e},Ql=(t,e,n)=>{const s=Math.min(t.length,e.length),i=[];for(let o=0;o<s;o++)i.push(ee(t[o],e[o],n));return i},tc=(t,e,n)=>Kl(t,e,n),Io=(t,e,n)=>n<1?t:e,ec=(t,e,n)=>jl(t,e,n);function Yn(t,e){return e==="slerp"?tc:typeof t=="number"?ee:Array.isArray(t)?Ql:typeof t=="string"?t.startsWith("#")||t.startsWith("rgb")?Zl:an(t)?ec:Io:Io}const Oo=1e3/60;function _o(t,e={}){if(!ye(t))throw new Error(`bakeSpringTrack: track "${t.id}" is not a spring track`);const n=new Nn(t.spring);return nc(t,s=>n.valueAt(s),n.settleTime(),t.spring.from,t.spring.to,e)}function Co(t,e={}){if(!me(t))throw new Error(`bakeInertiaTrack: track "${t.id}" is not an inertia track`);const n=t.inertia;return nc(t,s=>Ls(n,s),on(n),n.from,sn(n),e)}function nc(t,e,n,s,i,o){const r=o.intervalMs??Oo,a=o.tolerance??.01,l=t.delay??0,c=[];for(let u=0;u<=n;u+=r)c.push({time:u+l,value:e(u),easing:"linear"});const h=c[c.length-1];return!h||h.time<n+l?c.push({time:n+l,value:i,easing:"linear"}):h.value=i,l>0&&c.unshift({time:0,value:s,easing:"linear"}),{id:t.id,target:t.target,property:t.property,keyframes:a>0?ic(c,a):c,...t.targets&&{targets:[...t.targets]},...t.stagger&&{stagger:{...t.stagger}}}}function Ho(t,e,n,s={}){const i=s.intervalMs??Oo,o=typeof n=="function"?n:Ct(n),r=Yn(t.value,s.interpolation),a=e.time-t.time;if(a<=0)return[e];const l=[];for(let h=i;h<a;h+=i){const u=h/a;l.push({time:t.time+h,value:r(t.value,e.value,o(u)),easing:"linear"})}const c=o(1);return l.push({...e,...c!==1&&{value:r(t.value,e.value,c)},easing:"linear"}),l}function zg(t,e){return ye(t)?_o(t,e):me(t)?Co(t,e):t}function sc(t,e={}){const n=t.keyframes;if(!n.some(o=>Ln(o.easing)))return t;const s=n.length>0?[n[0]]:[],i={...e,interpolation:t.interpolation??e.interpolation};for(let o=1;o<n.length;o++){const r=n[o];Ln(r.easing)?s.push(...Ho(n[o-1],r,r.easing,i)):s.push(r)}return{...t,keyframes:s}}function Xg(t,e){return t.filter(yl).map(n=>sc(n,e)).concat(t.filter(ye).map(n=>_o(n,e)),t.filter(me).map(n=>Co(n,e)))}function ic(t,e){if(t.length<=2)return t;const n=[t[0]];for(let s=1;s<t.length-1;s++){const i=n[n.length-1],o=t[s],r=t[s+1],a=r.time-i.time;if(a<=0)continue;const l=(o.time-i.time)/a,c=i.value+(r.value-i.value)*l;Math.abs(o.value-c)>e&&n.push(o)}return n.push(t[t.length-1]),n}function Ws(t){const e=[...t.keyframes].sort((n,s)=>n.time-s.time);return{...t,keyframes:e}}function ve(t){return t.targets&&t.targets.length>0?t.targets:[t.target]}function cn(t,e,n,s){const i=n??0;return!s||e<=1?i:i+Os(t,e,s)}class Bs{track;targets;constructor(e){this.track=e,this.targets=ve(e)}getValueAtTime(e){return this.valueForOffset(e-cn(0,this.targets.length,this.track.delay,this.track.stagger))}getTargetValues(e){const n=this.targets.length,s=[];for(let i=0;i<n;i++){const o=cn(i,n,this.track.delay,this.track.stagger),r=this.valueForOffset(e-o);r!==void 0&&s.push({target:this.targets[i],value:r,start:o+this.track.keyframes[0].time})}return s}getDuration(){const{keyframes:e}=this.track;if(e.length===0)return 0;const n=e[e.length-1].time,s=this.track.stagger?Fn(this.targets.length,this.track.stagger):0;return n+(this.track.delay??0)+s+(this.track.endDelay??0)}getTrack(){return this.track}valueForOffset(e){const{keyframes:n}=this.track;if(n.length===0)return;if(n.length===1||e<=n[0].time)return n[0].value;if(e>=n[n.length-1].time)return n[n.length-1].value;const{from:s,to:i}=this.findSurroundingKeyframes(e);if(!s||!i)return;if(s.time===e)return s.value;const o=i.time-s.time,r=(e-s.time)/o,l=Ct(i.easing)(r);return Yn(s.value,this.track.interpolation)(s.value,i.value,l)}findSurroundingKeyframes(e){const{keyframes:n}=this.track;for(let s=0;s<n.length-1;s++)if(e>=n[s].time&&e<=n[s+1].time)return{from:n[s],to:n[s+1]};return{from:null,to:null}}}class oc{track;targets;sampler;constructor(e){this.track=e,this.targets=ve(e),this.sampler=new Nn(e.spring)}getValueAtTime(e){return this.sampler.valueAt(e-cn(0,this.targets.length,this.track.delay,this.track.stagger))}getTargetValues(e){const n=this.targets.length,s=[];for(let i=0;i<n;i++){const o=cn(i,n,this.track.delay,this.track.stagger);s.push({target:this.targets[i],value:this.sampler.valueAt(e-o),start:o})}return s}getDuration(){const e=this.track.stagger?Fn(this.targets.length,this.track.stagger):0;return this.sampler.settleTime()+(this.track.delay??0)+e}getTrack(){return this.track}}class rc{track;targets;duration;constructor(e){this.track=e,this.targets=ve(e),this.duration=on(e.inertia)}getValueAtTime(e){return Ls(this.track.inertia,e-cn(0,this.targets.length,this.track.delay,this.track.stagger))}getTargetValues(e){const n=this.targets.length,s=[];for(let i=0;i<n;i++){const o=cn(i,n,this.track.delay,this.track.stagger);s.push({target:this.targets[i],value:Ls(this.track.inertia,e-o),start:o})}return s}getDuration(){const e=this.track.stagger?Fn(this.targets.length,this.track.stagger):0;return this.duration+(this.track.delay??0)+e}getTrack(){return this.track}}function Ro(t,e){const n={...Rl(t.pathData,e)};if(t.matrix){const[s,i,o,r,a,l]=t.matrix,{x:c,y:h}=n;n.x=s*c+o*h+a,n.y=i*c+r*h+l;const u=n.angle*Math.PI/180,d=Math.cos(u),f=Math.sin(u);n.angle=Math.atan2(i*d+r*f,s*d+o*f)*180/Math.PI}return t.autoRotate&&t.rotateOffset&&(n.angle+=t.rotateOffset),n}function Gg(t,e,n,s){const i=e+(n-e)*s;return Ro(t,i)}const Lo={upperCase:"ABCDEFGHIJKLMNOPQRSTUVWXYZ",lowerCase:"abcdefghijklmnopqrstuvwxyz",upperAndLowerCase:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",numbers:"0123456789"},Ug=20;function ac(t){const e=Lo[t??"upperCase"]??t??Lo.upperCase,n=Array.from(e);return n.length>0?n:Array.from(Lo.upperCase)}function Vg(t,e,n){let s=(t|0)^Math.imul(e+1,2654435761)^Math.imul(n+1,2246822507);return s=Math.imul(s^s>>>16,2146121005),s=Math.imul(s^s>>>15,2221713035),(s^s>>>16)>>>0}function lc(t,e,n=0){const s=t.from??"",i=t.to,o=Math.max(0,Math.min(1,e));if(o<=0)return s;if(o>=1)return i;const r=Array.from(s),a=Array.from(i),l=t.rightToLeft??!1;if(t.mode==="type"){const T=Math.round(o*Math.max(r.length,a.length));return l?r.slice(0,Math.max(0,r.length-T)).join("")+a.slice(Math.max(0,a.length-T)).join(""):a.slice(0,T).join("")+r.slice(T).join("")}const c=Math.max(0,Math.min(.999,t.revealDelay??0)),h=Math.max(0,(o-c)/(1-c)),u=Math.floor(h*a.length),d=t.tweenLength===!1?a.length:Math.round(r.length+(a.length-r.length)*o),f=ac(t.chars),p=t.refreshRate??Ug,g=p>0?Math.floor(n*p/1e3):0,m=t.seed??1;let y="";for(let T=0;T<d;T++){const k=l?T>=d-u:T<u,b=l?a[a.length-(d-T)]:a[T];k&&b!==void 0||b===" "||b===`
|
|
2
|
+
`?y+=b:y+=f[Vg(m,T,g)%f.length]}return y}class Nt{id;name;_captions;_tracks=[];_trackPlayers=new Map;_motionPathTracks=new Map;_springTracks=new Map;_textTracks=new Map;_config;_currentTime=0;_playbackState="idle";_direction="forward";_loopIteration=0;_explicitDuration;_repeatDelayRemaining=0;_wrapAfterDelay=!1;onUpdate=null;onComplete=null;constructor(e){if(this.id=e.id,this.name=e.name,this._captions=e.captions,this._config=e.config??{},this._explicitDuration=e.config?.duration,e.tracks)for(const n of e.tracks)this.addTrack(n)}get tracks(){return[...this._tracks]}get duration(){return this._explicitDuration!==void 0?this._explicitDuration:this._calculateDuration()}setDuration(e){if(this._explicitDuration=e,e!==void 0)this._config={...this._config,duration:e};else if(this._config.duration!==void 0){const n={...this._config};delete n.duration,this._config=n}}get currentTime(){return this._currentTime}get playbackState(){return this._playbackState}get direction(){return this._direction}get loopIteration(){return this._loopIteration}get repeatDelayRemaining(){return this._repeatDelayRemaining}get speed(){return this._config.speed??1}set speed(e){this._config.speed=e}get drawingRate(){return this._config.drawingRate??0}set drawingRate(e){const n={...this._config};e>0?n.drawingRate=e:delete n.drawingRate,this._config=n}play(){const e=this.duration;this._direction==="forward"&&this._currentTime>=e&&e>0?(this._currentTime=0,this._loopIteration=0):this._direction==="reverse"&&this._currentTime<=0&&e>0&&(this._currentTime=e,this._loopIteration=0),this._playbackState="playing"}pause(){this._playbackState="paused"}stop(){this._playbackState="idle",this._repeatDelayRemaining=0,this._wrapAfterDelay=!1,this._currentTime=0,this._loopIteration=0,this._direction="forward"}seek(e){const n=this.duration>0?this.duration:1/0;this._currentTime=Math.max(0,Math.min(e,n)),this._repeatDelayRemaining=0,this._wrapAfterDelay=!1}reverse(){this._direction=this._direction==="forward"?"reverse":"forward"}tick(e){if(this._playbackState!=="playing")return;const n=this.duration;if(n<=0)return;let i=e*this.speed;if(this._repeatDelayRemaining>0){const a=Math.min(this._repeatDelayRemaining,i);if(this._repeatDelayRemaining-=a,i-=a,this._repeatDelayRemaining>0){this.onUpdate?.(this.getStateAtTime(this._currentTime));return}this._wrapAfterDelay&&(this._wrapAfterDelay=!1,this._currentTime=0)}const o=1e3;for(let a=0;a<o&&i>0&&this._playbackState==="playing";a++)if(this._direction==="forward"){const l=n-this._currentTime;if(i>=l){if(i-=l,this._currentTime=n,!this._handleEndReached())break}else this._currentTime+=i,i=0}else{const l=this._currentTime;if(i>=l){if(i-=l,this._currentTime=0,!this._handleStartReached())break}else this._currentTime-=i,i=0}const r=this.getStateAtTime(this._currentTime);this.onUpdate?.(r)}getStateAtTime(e){const n=new Map;if(e=bl(e,this._config.drawingRate??0),this._hasSharedWrites())this._resolveShared(e,n);else for(const[s,i]of this._trackPlayers){const o=i.getTrack().property;for(const{target:r,value:a,start:l}of i.getTargetValues(e))this._write(n,s,r,o,a,e-l)}return{values:n,currentTime:this._currentTime,playbackState:this._playbackState,direction:this._direction,loopIteration:this._loopIteration}}_resolveShared(e,n){const s=new Map;for(const[i,o]of this._trackPlayers){const r=o.getTrack().property;for(const{target:a,value:l,start:c}of o.getTargetValues(e)){const h=`${a}\0${r}`,u=c<=e,d=s.get(h);(!d||(u!==d.started?u:u?c>=d.start:c<=d.start))&&s.set(h,{trackId:i,target:a,property:r,value:l,start:c,started:u})}}for(const{trackId:i,target:o,property:r,value:a,start:l}of s.values())this._write(n,i,o,r,a,e-l)}_write(e,n,s,i,o,r){if(o===void 0)return;let a=e.get(s);a||(a=new Map,e.set(s,a));const l=this._textTracks.get(n);if(l&&typeof o=="number"){a.set("text",lc(l.textConfig,o,Math.max(0,r)));return}const c=this._motionPathTracks.get(n);if(c&&typeof o=="number"){const h=Ro(c.motionPathConfig,o);a.set("motionPathX",h.x),a.set("motionPathY",h.y),c.motionPathConfig.autoRotate&&a.set("motionPathRotate",h.angle)}else a.set(i,o)}_sharedWrites=null;_hasSharedWrites(){if(this._sharedWrites===null){const e=new Set;this._sharedWrites=!1;t:for(const n of this._tracks)for(const s of ve(n)){const i=`${s}\0${n.property}`;if(e.has(i)){this._sharedWrites=!0;break t}e.add(i)}}return this._sharedWrites}addTrack(e){if(this._tracks.push(e),this._sharedWrites=null,me(e)){this._trackPlayers.set(e.id,new rc(e));return}if(ye(e)){this._trackPlayers.set(e.id,new oc(e)),this._springTracks.set(e.id,e);return}if(Is(e))this._trackPlayers.set(e.id,new Bs(e)),this._textTracks.set(e.id,e);else if(po(e)){const n={id:e.id,target:e.target,property:e.property,keyframes:e.keyframes,delay:e.delay,endDelay:e.endDelay,targets:e.targets,stagger:e.stagger};this._trackPlayers.set(e.id,new Bs(n)),this._motionPathTracks.set(e.id,e)}else this._trackPlayers.set(e.id,new Bs(e))}replaceTrack(e,n){const s=this._tracks.findIndex(o=>o.id===e);if(s<0)return;const i=this._tracks.slice(s+1);this.removeTrack(e);for(const o of i)this.removeTrack(o.id);this.addTrack(n);for(const o of i)this.addTrack(o)}removeTrack(e){this._tracks=this._tracks.filter(n=>n.id!==e),this._sharedWrites=null,this._trackPlayers.delete(e),this._motionPathTracks.delete(e),this._springTracks.delete(e),this._textTracks.delete(e)}getTracks(e={}){return this._tracks.filter(n=>this._matches(n,e))}removeTracks(e={}){const n=this.getTracks(e).map(s=>s.id);for(const s of n)this.removeTrack(s);return n}getTrackSpan(e){const n=this._trackPlayers.get(e);if(!n)return;const s=n.getTrack(),i=s.delay??0;if(ye(s)||me(s))return{from:i,to:n.getDuration()};const o=s.keyframes;if(!(!o||o.length===0))return{from:o[0].time+i,to:n.getDuration()}}findConflicts(){const e=[];for(let n=0;n<this._tracks.length;n++){const s=this._tracks[n],i=this.getTrackSpan(s.id);if(i)for(let o=0;o<n;o++){const r=this._tracks[o];if(r.property!==s.property)continue;const a=ve(r).filter(u=>ve(s).includes(u));if(a.length===0)continue;const l=this.getTrackSpan(r.id);if(!l||!(l.from<=i.to&&i.from<=l.to))continue;const h=i.from>=l.from;for(const u of a)e.push({target:u,property:s.property,losingTrackId:h?r.id:s.id,winningTrackId:h?s.id:r.id})}}return e}_matches(e,n){if(n.id!==void 0&&e.id!==n.id||n.property!==void 0&&e.property!==n.property||n.target!==void 0&&!ve(e).includes(n.target))return!1;if(n.timeRange){const s=this.getTrackSpan(e.id);if(!s||s.to<n.timeRange.from||s.from>n.timeRange.to)return!1}return!0}toDefinition(){return{formatVersion:go(this._tracks),id:this.id,name:this.name,config:{...this._config},tracks:[...this._tracks],...this.captions&&{captions:this.captions}}}get config(){return this._config}get markers(){return[...this._config.markers??[]].sort((e,n)=>e.time-n.time)}setMarkers(e){const n=e&&e.length>0?[...e].sort((i,o)=>i.time-o.time).map(i=>({...i})):void 0,s={...this._config};n?s.markers=n:delete s.markers,this._config=s}get captions(){return this._captions}setCaptions(e){const n={};for(const[s,i]of Object.entries(e??{}))n[s]={...i};this._captions=Object.keys(n).length>0?n:void 0}_armRepeatDelay(){this._repeatDelayRemaining=this._config.repeatDelay??0}_calculateDuration(){let e=0;for(const[,n]of this._trackPlayers)e=Math.max(e,n.getDuration());return e}_handleEndReached(){const e=this._config.loop??0;return e===-1||this._loopIteration<e?(this._loopIteration++,this._armRepeatDelay(),this._config.alternate?this._direction="reverse":this._repeatDelayRemaining>0?this._wrapAfterDelay=!0:this._currentTime=0,this._repeatDelayRemaining===0):(this._playbackState="idle",this.onComplete?.(),!1)}_handleStartReached(){const e=this._config.loop??0;return this._config.alternate&&(e===-1||this._loopIteration<e)?(this._loopIteration++,this._armRepeatDelay(),this._direction="forward",this._repeatDelayRemaining===0):(this._playbackState="idle",this.onComplete?.(),!1)}}const Jg=100;function Fo(t,e,n,s){const i=[],o=[],{duration:r,alternate:a}=s,l=(f,p,g,m)=>{o.push([f,p]);const y=[];t.forEach((T,k)=>{(g==="forward"?(m?T>=f:T>f)&&T<=p:(m?T<=f:T<f)&&T>=p)&&y.push(k)}),y.sort((T,k)=>(g==="forward"?t[T]-t[k]:t[k]-t[T])||T-k);for(const T of y)i.push({kind:"event",index:T,direction:g})};let c=e.time,h=e.direction,u=e.fresh===!0;const d=Math.min(Jg,Math.max(0,n.iteration-e.iteration));for(let f=0;f<d;f++){const p=h==="forward"?r:0;l(c,p,h,u),i.push({kind:"repeat"}),a?(h=h==="forward"?"reverse":"forward",c=p,u=!1):(c=h==="forward"?0:r,u=!0)}return d>0&&s.holding&&!a?{crossings:i,passes:o}:(l(c,n.time,h,u),{crossings:i,passes:o})}function cc(t){return me(t)?{id:t.id,target:t.target,property:t.property,kind:"inertia",inertia:hc(t.inertia),...ne(t)}:ye(t)?{id:t.id,target:t.target,property:t.property,kind:"spring",spring:{...t.spring},...ne(t)}:Is(t)?{id:t.id,target:t.target,property:"text",textConfig:{...t.textConfig},keyframes:t.keyframes.map(No),...ne(t)}:po(t)?{id:t.id,target:t.target,property:"motionPath",motionPathConfig:{...t.motionPathConfig},keyframes:t.keyframes.map(No),...ne(t)}:{id:t.id,target:t.target,property:t.property,keyframes:t.keyframes.map(No),...t.interpolation!==void 0&&{interpolation:t.interpolation},...ne(t)}}function hc(t){return{...t,...Array.isArray(t.end)&&{end:[...t.end]}}}function No(t){return{time:t.time,value:t.value,...t.easing&&{easing:t.easing}}}function ne(t){const e=t.endDelay;return{...t.delay!==void 0&&{delay:t.delay},...e!==void 0&&{endDelay:e},...t.targets!==void 0&&{targets:[...t.targets]},...t.stagger!==void 0&&{stagger:{...t.stagger}}}}function uc(t){if(me(t)){const e=t;return{id:e.id,target:e.target,property:e.property,kind:"inertia",inertia:hc(e.inertia),...ne(e)}}if(ye(t)){const e=t;return{id:e.id,target:e.target,property:e.property,kind:"spring",spring:{...e.spring},...ne(e)}}if(Is(t)){const e=t;return{id:e.id,target:e.target,property:"text",textConfig:{...e.textConfig},keyframes:[...e.keyframes].sort((n,s)=>n.time-s.time),...ne(e)}}if(t.property==="motionPath"&&"motionPathConfig"in t){const e=t,n=[...e.keyframes].sort((s,i)=>s.time-i.time);return{id:e.id,target:e.target,property:"motionPath",motionPathConfig:{...e.motionPathConfig},keyframes:n,...ne(e)}}return Ws({id:t.id,target:t.target,property:t.property,keyframes:t.keyframes,...t.interpolation!==void 0&&{interpolation:t.interpolation},...ne(t)})}function dc(t){const e=t._config.markers;return{formatVersion:go(t.tracks),id:t.id,name:t.name,config:{duration:t.duration>0?t.duration:void 0,loop:t._config.loop,speed:t._config.speed,alternate:t._config.alternate,repeatDelay:t._config.repeatDelay,...t._config.drawingRate?{drawingRate:t._config.drawingRate}:{},...e&&{markers:e.map(n=>({...n}))}},tracks:t.tracks.map(cc),...t.captions&&{captions:JSON.parse(JSON.stringify(t.captions))}}}function hn(t){const e=t.formatVersion??1;if(e>fo)throw new Error(`tinyfly: this animation uses format version ${e}, but this tinyfly reads up to version ${fo}. Update tinyfly to play it.`);return new Nt({id:t.id,name:t.name,config:t.config,tracks:t.tracks.map(uc),captions:t.captions})}function Zg(t){return JSON.stringify(dc(t))}function Qg(t){const e=JSON.parse(t);return hn(e)}function zt(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619);return e>>>0}function Ne(t){let e=t>>>0||2654435769;return{seed:t>>>0,next(){return e^=e<<13,e>>>=0,e^=e>>17,e^=e<<5,e>>>=0,e/4294967296}}}function Do(t,e,n){return e+t.next()*(n-e)}function fc(t,e,n,s){if(s<=0)return Do(t,e,n);const i=Math.floor((n-e)/s),o=Math.round(t.next()*i);return e+o*s}function tp(t,e){if(e.length!==0)return e[Math.floor(t.next()*e.length)]}const gc=/^([+\-*/])=\s*(-?[\d.]+)$/,pc=/^random\(\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*(?:,\s*(-?[\d.]+)\s*)?\)$/i;function ep(t){return typeof t!="string"?!1:gc.test(t.trim())||pc.test(t.trim())}function Wo(t,e={}){if(typeof t!="string")return t;const n=t.trim(),s=gc.exec(n);if(s){const[,o,r]=s,a=e.base??0,l=Number.parseFloat(r);switch(o){case"+":return a+l;case"-":return a-l;case"*":return a*l;case"/":return l===0?a:a/l}}const i=pc.exec(n);if(i){if(!e.random)throw new Error(`resolveValue: "${n}" needs a random source — pass one via context.random`);const o=Number.parseFloat(i[1]),r=Number.parseFloat(i[2]),a=i[3]!==void 0?Number.parseFloat(i[3]):void 0;return a!==void 0?fc(e.random,o,r,a):Do(e.random,o,r)}return t}function mc(t,e=0,n){const s=[];let i=e;for(const o of t){const r=Wo(o,{base:i,random:n});s.push(r),typeof r=="number"&&(i=r)}return s}class np{random;constructor(e){this.random=Ne(e)}get seed(){return this.random.seed}resolve(e,n=0){return Wo(e,{base:n,random:this.random})}resolveSequence(e,n=0){return mc(e,n,this.random)}}const sp=600;function yc(t){if(Array.isArray(t)){const[d,f,p,g]=t;return{fn:kc(d,f,p,g),bezier:[d,f,p,g]}}const{segments:e}=Fe(t);if(e.length===0)throw new Error(`customEase: no curve in "${t}"`);const n=e[0].startX,s=e[0].startY,i=e[e.length-1],o=i.endX-n,r=i.endY-s;if(o===0||r===0)throw new Error(`customEase: "${t}" must move along both axes`);const a=d=>(d-n)/o,l=d=>(d-s)/r;if(e.length===1&&i.type==="C"){const[d,f,p,g]=i.points,m=[a(d),l(f),a(p),l(g)];return{fn:kc(...m),bezier:m}}const c=[],h=[],u=Math.max(8,Math.ceil(sp/e.length));for(const d of e)for(let f=c.length===0?0:1;f<=u;f++){const[p,g]=ip(d,f/u);c.push(a(p)),h.push(l(g))}return{fn:op(c,h)}}function bc(t={}){const n=.1+Math.max(0,Math.min(1,t.strength??.7))*.7,s=[1];for(let o=n;o>.002;o*=n)s.push(2*Math.sqrt(o));const i=s.reduce((o,r)=>o+r,0);return o=>{if(o<=0)return 0;if(o>=1)return 1;let r=o*i;for(let a=0;a<s.length;a++){if(r<=s[a]){if(a===0)return(r/s[0])**2;const l=s[a]/2,c=l*l,h=r-l;return 1-(c-h*h)}r-=s[a]}return 1}}function wc(t={}){const e=Math.max(1,t.wiggles??10),n=t.type??"easeOut",s=i=>n==="uniform"?1:n==="easeInOut"?Math.sin(Math.PI*i):(1-i)**2;return i=>i<=0||i>=1?0:Math.sin(i*e*Math.PI*2)*s(i)}function ip(t,e){if(t.type==="L"){const[c,h]=t.points;return[t.startX+(c-t.startX)*e,t.startY+(h-t.startY)*e]}const[n,s,i,o,r,a]=t.points,l=1-e;return[l*l*l*t.startX+3*l*l*e*n+3*l*e*e*i+e*e*e*r,l*l*l*t.startY+3*l*l*e*s+3*l*e*e*o+e*e*e*a]}function op(t,e){return n=>{if(n<=t[0])return e[0];if(n>=t[t.length-1])return e[e.length-1];let s=0,i=t.length-1;for(;i-s>1;){const r=s+i>>1;t[r]<=n?s=r:i=r}const o=t[i]-t[s];return o===0?e[i]:e[s]+(n-t[s])/o*(e[i]-e[s])}}function kc(t,e,n,s){const i=(r,a,l)=>3*(1-r)*(1-r)*r*a+3*(1-r)*r*r*l+r*r*r,o=(r,a,l)=>3*(1-r)*(1-r)*a+6*(1-r)*r*(l-a)+3*r*r*(1-l);return r=>{if(r<=0)return 0;if(r>=1)return 1;let a=r;for(let h=0;h<8;h++){const u=i(a,t,n)-r,d=o(a,t,n);if(Math.abs(u)<1e-6)return i(a,e,s);if(Math.abs(d)<1e-6)break;a-=u/d}let l=0,c=1;a=r;for(let h=0;h<40;h++)i(a,t,n)<r?l=a:c=a,a=(l+c)/2;return i(a,e,s)}}const rp=350,ap=300,lp=550;function cp(t,e={}){const n=e.lead??rp,s=e.gap??ap,i=e.tail??lp,o=[];let r=0;return t.forEach((a,l)=>{const c=[];let h=r+n;a.lines.forEach((d,f)=>{if(!(d.duration>=0))throw new Error(`narration: scene ${l} line ${f} has an invalid duration (${d.duration})`);f>0&&(h+=s),c.push({id:d.id??`s${l}-l${f}`,scene:l,line:f,start:h,end:h+d.duration,text:d.text}),h+=d.duration});const u=h+i+(a.tail??0);o.push({id:a.id??`s${l}`,start:r,duration:u-r,cues:c}),r=u}),{duration:r,scenes:o,cues:o.flatMap(a=>a.cues)}}function hp(t){return t.cues.map(e=>({id:e.id,time:e.start,label:e.text}))}function up(t,e){let n=t.scenes[0];for(const s of t.scenes)if(e>=s.start)n=s;else break;return n}const Bo=t=>6e4/t.bpm;function js(t,e){return t.offset+e*Bo(t)}function qs(t,e){return(e-t.offset)/Bo(t)}function dp(t,e){return js(t,Math.round(qs(t,e)))}function fp(t,e){return js(t,Math.ceil(qs(t,e)-1e-9))}function gp(t,e,n){const s=Math.max(1,Math.round(t.beatsPerBar??4)),i=[];if(!(t.bpm>0)||n<e)return i;for(let o=Math.ceil(qs(t,e)-1e-9);;o++){const r=js(t,o);if(r>n+1e-9)break;i.push({time:r,bar:(o%s+s)%s===0,n:o})}return i}const un=100;function pp(t,e,n={}){const s=n.minBpm??70,i=n.maxBpm??180,o=Math.max(1,Math.round(e/un)),r=Math.min(t.length,Math.round((n.maxSeconds??60)*e)),a=Math.floor(r/o);if(a<4)return{bpm:120,offset:0,confidence:0};const l=new Float64Array(a);for(let S=0;S<a;S++){let I=0;for(let v=S*o;v<(S+1)*o;v++)I+=t[v]*t[v];l[S]=Math.log(1e-6+I/o)}const c=new Float64Array(a);for(let S=1;S<a;S++)c[S]=Math.max(0,l[S]-l[S-1]);const h=c.reduce((S,I)=>S+I,0)/a;for(let S=0;S<a;S++)c[S]=Math.max(0,c[S]-h);const u=Math.max(1,Math.floor(60*un/i)),d=Math.min(a-1,Math.ceil(60*un/s)),f=S=>{let I=0;for(let v=S;v<a;v++)I+=c[v]*c[v-S];return I/(a-S)};let p=0;for(let S=0;S<a;S++)p+=c[S]*c[S];p/=a;let g=u,m=-1/0;for(let S=u;S<=d;S++){const I=60*un/S,v=Math.exp(-.5*(Math.log2(I/120)/.9)**2),$=f(S)*v;$>m&&(m=$,g=S)}const y=S=>{const I=Math.floor(S);return I<0||I+1>=a?0:c[I]+(c[I+1]-c[I])*(S-I)},T=(S,I)=>{let v=0;for(let $=I;$<a;$+=S)v+=y($);return v};let k=g,b=0,A=-1/0;for(let S=g-.6;S<=g+.6+1e-9;S+=.02){if(S<1)continue;const I=Math.max(1,Math.round(S*4));for(let v=0;v<I;v++){const $=v/I*S,_=T(S,$);_>A&&(A=_,b=$,k=S)}}const M=60*un/k,E=p>0?Math.max(0,Math.min(1,f(g)/p)):0,x=(b+.5)*1e3/un;return{bpm:Math.round(M*100)/100,offset:Math.round(x%(6e4/M)),confidence:E}}const mp=600,yp=250,vc=1;function bp(t,e){const n=e.target??"Camera",s={x:e.stage.width/2,y:e.stage.height/2},i={},o=(u,d,f,p)=>{const g=i[u]??=[];for(;g.length>0&&g[g.length-1].time>=d;)g.pop();g.push({time:d,value:f,...p?{easing:p}:{}})},r=u=>{const d=u.rotate*Math.PI/180,f=(u.focusX-s.x)*u.scale,p=(u.focusY-s.y)*u.scale;return{x:-(f*Math.cos(d)-p*Math.sin(d)),y:-(f*Math.sin(d)+p*Math.cos(d)),scale:u.scale,rotate:u.rotate}},a=(u,d,f)=>{const p=r(d);for(const g of["x","y","scale","rotate"])o(g,u,p[g],f)};let l={focusX:s.x,focusY:s.y,scale:1,rotate:0};const c=[...t].sort((u,d)=>u.at-d.at),h=c.filter(u=>!("shake"in u));h.length>0&&a(0,l);for(const u of h)if("frame"in u){const d=Math.max(vc,u.duration??mp);a(u.at,l),l={focusX:u.frame.focus?.x??s.x,focusY:u.frame.focus?.y??s.y,scale:u.frame.scale??1,rotate:u.frame.rotate??0},a(u.at+d,l,u.easing??(d>vc?"ease-in-out":void 0))}else{const{follow:d}=u,f=d.lag??yp,p=new Nt({id:"follow",tracks:[{id:"x",target:"s",property:"x",keyframes:d.x}]}),g=T=>p.getStateAtTime(T).values.get("s")?.get("x")??l.focusX,m=[u.at,...d.x.map(T=>T.time).filter(T=>T>u.at&&T<u.until),u.until];a(u.at,l);const y=T=>({focusX:g(T)+(d.lead??0),focusY:d.y??l.focusY,scale:d.scale??l.scale,rotate:l.rotate});for(const T of m){const k=d.x.find(b=>b.time===T)?.easing;a(T+f,y(T),T===u.at?"ease-in-out":k)}l=y(u.until)}for(const u of c.filter(d=>"shake"in d)){const d=u.shake.strength??12,f=u.shake.roll??1.5,p=1e3/(u.shake.frequency??24),g=Ne(u.shake.seed??Math.round(u.at)+1),m=()=>g.next()*2-1;for(const y of["shakeX","shakeY","shakeRotate"])o(y,u.at,0);for(let y=u.at+p;y<u.at+u.duration;y+=p){const T=1-(y-u.at)/u.duration;o("shakeX",y,m()*d*T),o("shakeY",y,m()*d*T),o("shakeRotate",y,m()*f*T)}for(const y of["shakeX","shakeY","shakeRotate"])o(y,u.at+u.duration,0,"ease-out")}return Object.entries(i).map(([u,d])=>({id:`${n}-${u}`,target:n,property:u,keyframes:d}))}function Mc(t,e){const n=t.toLowerCase(),s=e.toLowerCase();let i=Array.from({length:s.length+1},(o,r)=>r);for(let o=1;o<=n.length;o++){const r=[o];for(let a=1;a<=s.length;a++)r[a]=Math.min(i[a]+1,r[a-1]+1,i[a-1]+(n[o-1]===s[a-1]?0:1));i=r}return i[s.length]}function Kn(t,e){const n=t.toLowerCase(),s=e.find(r=>r.toLowerCase().includes(n)||n.includes(r.toLowerCase()));if(s&&Math.min(t.length,s.length)>=3)return s;let i,o=1/0;for(const r of e){const a=Mc(t,r);a<o&&(o=a,i=r)}return i!==void 0&&o<=Math.max(2,Math.floor(t.length/3))?i:void 0}function ot(t,e,n,s){const i=typeof e=="string"?s??Kn(e,n):void 0;return`Unknown ${t} ${JSON.stringify(e)}${i?`: did you mean "${i}"?`:"."} Known: ${n.join(", ")}`}function Sc(t,e){const n=e.step??33,s=e.stiffness??120,i=e.damping??9,o=e.mass??1;let r=t(e.start),a=0;const l=[{time:e.start,value:r}];let c=e.start+n;for(let h=e.start+1;h<=e.end;h++){const d=s*(t(h)-r)-i*a;a+=d/o*.001,r+=a*.001,(h>=c||h===e.end)&&(l.push({time:h,value:r}),c+=n)}return l}const se=t=>Math.round(t*1e3)/1e3;function Tc(t,e={}){if(t.length===0)return"";const n=e.curviness??1,s=e.closed??!1,i=t.length;let o=`M${se(t[0].x)} ${se(t[0].y)}`;if(i===1)return o;const r=l=>s?t[(l%i+i)%i]:t[Math.max(0,Math.min(i-1,l))],a=s?i:i-1;for(let l=0;l<a;l++){const c=r(l-1),h=r(l),u=r(l+1),d=r(l+2);if(n===0){o+=` L${se(u.x)} ${se(u.y)}`;continue}const f=n/6,p=h.x+(u.x-c.x)*f,g=h.y+(u.y-c.y)*f,m=u.x-(d.x-h.x)*f,y=u.y-(d.y-h.y)*f;o+=` C${se(p)} ${se(g)} ${se(m)} ${se(y)} ${se(u.x)} ${se(u.y)}`}return s?`${o} Z`:o}const Ot=(t,e=0)=>{const n=parseFloat(t??"");return Number.isFinite(n)?n:e};function wp(t){const e=(t??"").trim().split(/[\s,]+/).filter(Boolean).map(Number),n=[];for(let s=0;s+1<e.length;s+=2)n.push({x:e[s],y:e[s+1]});return n}function Ys(t){const e=t.attributes;switch(t.tag.toLowerCase()){case"path":return e.d??null;case"circle":case"ellipse":{const n=Ot(e.cx),s=Ot(e.cy),i=t.tag.toLowerCase()==="circle"?Ot(e.r):Ot(e.rx),o=t.tag.toLowerCase()==="circle"?Ot(e.r):Ot(e.ry);return`M${n+i} ${s} A${i} ${o} 0 1 1 ${n-i} ${s} A${i} ${o} 0 1 1 ${n+i} ${s} Z`}case"rect":{const n=Ot(e.x),s=Ot(e.y),i=Ot(e.width),o=Ot(e.height);let r=e.rx!=null?Ot(e.rx):e.ry!=null?Ot(e.ry):0,a=e.ry!=null?Ot(e.ry):r;return r=Math.min(r,i/2),a=Math.min(a,o/2),r===0||a===0?`M${n} ${s} H${n+i} V${s+o} H${n} Z`:`M${n+r} ${s} H${n+i-r} A${r} ${a} 0 0 1 ${n+i} ${s+a} V${s+o-a} A${r} ${a} 0 0 1 ${n+i-r} ${s+o} H${n+r} A${r} ${a} 0 0 1 ${n} ${s+o-a} V${s+a} A${r} ${a} 0 0 1 ${n+r} ${s} Z`}case"line":return`M${Ot(e.x1)} ${Ot(e.y1)} L${Ot(e.x2)} ${Ot(e.y2)}`;case"polyline":case"polygon":{const n=wp(e.points);if(n.length===0)return null;const s=n.map((i,o)=>`${o===0?"M":"L"}${i.x} ${i.y}`).join(" ");return t.tag.toLowerCase()==="polygon"?`${s} Z`:s}default:return null}}function kp(t,e,n){const s=Math.max(2,Math.round(n.samples??32)),i=Math.max(0,n.length),o=n.since!==void 0?Math.max(e-i,n.since):e-i;if(o>=e)return[];const r=n.period,a=[];for(let l=0;l<s;l++){const c=o+(e-o)*l/(s-1),h=r&&r>0&&l<s-1?(c%r+r)%r:c;a.push({at:t(h),time:c,age:i>0?(e-c)/i:0})}return a}const vp=2.5;function Ec(t){const e=[],n=[],s=t.length,i=(o,r)=>{for(let a=o+r;a>=0&&a<s;a+=r){const l=(t[a].x-t[o].x)*r,c=(t[a].y-t[o].y)*r,h=Math.hypot(l,c);if(h>1e-9)return[l/h,c/h]}return null};for(let o=0;o<s;o++){const r=t[o],a=i(o,-1),l=i(o,1),c=a??l??[1,0],h=l??a??[1,0];let u=c[0]+h[0],d=c[1]+h[1];const f=Math.hypot(u,d);f<1e-9?(u=c[0],d=c[1]):(u/=f,d/=f);const p=u*c[0]+d*c[1],g=Math.min(vp,1/Math.max(p,1e-6)),m=r.width/2*g;e.push({x:r.x-d*m,y:r.y+u*m}),n.push({x:r.x+d*m,y:r.y-u*m})}return{left:e,right:n}}function Ac(t){const e=t.length;if(e<2)return null;const n=t[e-1];for(let s=e-2;s>=0;s--){const i=n.x-t[s].x,o=n.y-t[s].y,r=Math.hypot(i,o);if(r>1e-9)return{x:n.x,y:n.y,radius:n.width/2,start:Math.atan2(i/r,-o/r)}}return null}function Ks(t,e){return[t[0]+e[0],t[1]+e[1],t[2]+e[2]]}function dn(t,e){return[t[0]-e[0],t[1]-e[1],t[2]-e[2]]}function fn(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function Me(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function zs(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function Xs(t){return Math.hypot(t[0],t[1],t[2])}function jo(t,e){return Xs(dn(t,e))}function De(t){const e=Xs(t);return e===0?[0,0,0]:fn(t,1/e)}function xc(t,e,n){return[t[0]+(e[0]-t[0])*n,t[1]+(e[1]-t[1])*n,t[2]+(e[2]-t[2])*n]}const Mp=Object.freeze(Object.defineProperty({__proto__:null,add:Ks,cross:zs,distance:jo,dot:Me,length:Xs,lerp:xc,normalize:De,scale:fn,subtract:dn},Symbol.toStringTag,{value:"Module"})),Sp=Math.PI/180;function Gs(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function wt(t,e){const n=new Array(16);for(let s=0;s<4;s++)for(let i=0;i<4;i++){let o=0;for(let r=0;r<4;r++)o+=t[r*4+i]*e[s*4+r];n[s*4+i]=o}return n}function We(t){return[1,0,0,0,0,1,0,0,0,0,1,0,t[0],t[1],t[2],1]}function Be(t){return[t[0],0,0,0,0,t[1],0,0,0,0,t[2],0,0,0,0,1]}function Jt(t){const[e,n,s,i]=t;return[1-2*(n*n+s*s),2*(e*n+s*i),2*(e*s-n*i),0,2*(e*n-s*i),1-2*(e*e+s*s),2*(n*s+e*i),0,2*(e*s+n*i),2*(n*s-e*i),1-2*(e*e+n*n),0,0,0,0,1]}function qo(t,e,n){const s=Jt(e);for(let i=0;i<3;i++)s[i]*=n[0],s[4+i]*=n[1],s[8+i]*=n[2];return s[12]=t[0],s[13]=t[1],s[14]=t[2],s}function Tp(t){const e=new Array(16);for(let n=0;n<4;n++)for(let s=0;s<4;s++)e[s*4+n]=t[n*4+s];return e}function Yo(t){const[e,n,s,i,o,r,a,l,c,h,u,d,f,p,g,m]=t,y=e*r-n*o,T=e*a-s*o,k=e*l-i*o,b=n*a-s*r,A=n*l-i*r,M=s*l-i*a,E=c*p-h*f,x=c*g-u*f,S=c*m-d*f,I=h*g-u*p,v=h*m-d*p,$=u*m-d*g,_=y*$-T*v+k*I+b*S-A*x+M*E;if(Math.abs(_)<1e-12)return null;const P=1/_;return[(r*$-a*v+l*I)*P,(s*v-n*$-i*I)*P,(p*M-g*A+m*b)*P,(u*A-h*M-d*b)*P,(a*S-o*$-l*x)*P,(e*$-s*S+i*x)*P,(g*k-f*M-m*T)*P,(c*M-u*k+d*T)*P,(o*v-r*S+l*E)*P,(n*S-e*v-i*E)*P,(f*A-p*k+m*y)*P,(h*k-c*A-d*y)*P,(r*x-o*I-a*E)*P,(e*I-n*x+s*E)*P,(p*T-f*b-g*y)*P,(c*b-h*T+u*y)*P]}function Ep(t,e,n,s){const i=1/Math.tan(t*Sp/2),o=1/(n-s);return[i/e,0,0,0,0,i,0,0,0,0,(s+n)*o,-1,0,0,2*s*n*o,0]}function Ap(t,e,n,s,i,o){const r=1/(e-t),a=1/(s-n),l=1/(o-i);return[2*r,0,0,0,0,2*a,0,0,0,0,-2*l,0,-(e+t)*r,-(s+n)*a,-(o+i)*l,1]}function xp(t,e,n=[0,1,0]){const s=De(dn(t,e)),i=De(zs(n,s)),o=zs(s,i);return[i[0],o[0],s[0],0,i[1],o[1],s[1],0,i[2],o[2],s[2],0,-Me(i,t),-Me(o,t),-Me(s,t),1]}function Dt(t,e){const n=t[0]*e[0]+t[4]*e[1]+t[8]*e[2]+t[12],s=t[1]*e[0]+t[5]*e[1]+t[9]*e[2]+t[13],i=t[2]*e[0]+t[6]*e[1]+t[10]*e[2]+t[14],o=t[3]*e[0]+t[7]*e[1]+t[11]*e[2]+t[15];return o===1||o===0?[n,s,i]:[n/o,s/o,i/o]}const $p=Object.freeze(Object.defineProperty({__proto__:null,compose:qo,fromQuat:Jt,identity:Gs,invert:Yo,lookAt:xp,multiply:wt,orthographic:Ap,perspective:Ep,scaling:Be,transformPoint:Dt,translation:We,transpose:Tp},Symbol.toStringTag,{value:"Module"})),Us={"power1.in":[.55,.085,.68,.53],"power1.out":[.25,.46,.45,.94],"power1.inout":[.455,.03,.515,.955],"power2.in":[.55,.055,.675,.19],"power2.out":[.215,.61,.355,1],"power2.inout":[.645,.045,.355,1],"power3.in":[.895,.03,.685,.22],"power3.out":[.165,.84,.44,1],"power3.inout":[.77,0,.175,1],"power4.in":[.755,.05,.855,.06],"power4.out":[.23,1,.32,1],"power4.inout":[.86,0,.07,1],"sine.in":[.47,0,.745,.715],"sine.out":[.39,.575,.565,1],"sine.inout":[.445,.05,.55,.95],"expo.in":[.95,.05,.795,.035],"expo.out":[.19,1,.22,1],"expo.inout":[1,0,0,1],"circ.in":[.6,.04,.98,.335],"circ.out":[.075,.82,.165,1],"circ.inout":[.785,.135,.15,.86],"back.in":[.6,-.28,.735,.045],"back.out":[.175,.885,.32,1.275],"back.inout":[.68,-.55,.265,1.55]},$c={none:"linear",linear:"linear","linear.none":"linear","power1.in":"ease-in-quad","power1.out":"ease-out-quad","power1.inout":"ease-in-out-quad","power2.in":"ease-in-cubic","power2.out":"ease-out-cubic","power2.inout":"ease-in-out-cubic"};function Pp(t){let e=t.trim().toLowerCase();e=e.replace(/\.ease(in|out|inout)$/,".$1");const n=/^([a-z]+\d?)(\(.*\))?$/.exec(e);return n&&n[1]!=="steps"&&e!=="none"&&e!=="linear"&&(e=`${n[1]}.out${n[2]??""}`),e}Ct({type:"bounce",mode:"in"}),Ct({type:"bounce",mode:"in-out"});function zn(t){const e=Pc.get(t.trim().toLowerCase());if(e)return e;const n=Pp(t),s=/^steps\(\s*(\d+)\s*\)$/.exec(n);if(s){const r={type:"steps",count:Math.max(1,Number.parseInt(s[1],10))+1,position:"none"};return{easing:r,fn:Ct(r)}}const i=/^(elastic|bounce|back)\.(in|out|inout)(?:\(([^)]*)\))?$/.exec(n);if(i){const[,o,r,a]=i,l=(a??"").split(",").map(u=>Number.parseFloat(u)).filter(u=>Number.isFinite(u)),c=r==="inout"?"in-out":r;if(o==="back"&&l.length===0&&n in Us)return{easing:{type:"cubic-bezier",points:Us[n]}};const h=o==="elastic"?{type:"elastic",mode:c,...l[0]!==void 0&&{amplitude:l[0]},...l[1]!==void 0&&{period:l[1]}}:o==="bounce"?{type:"bounce",mode:c}:{type:"back",mode:c,...l[0]!==void 0&&{overshoot:l[0]}};return{easing:h,fn:Ct(h)}}return n in $c?{easing:$c[n]}:n in Us?{easing:{type:"cubic-bezier",points:Us[n]}}:{easing:"ease-out"}}const Pc=new Map;function Ko(t,e){return Pc.set(t.trim().toLowerCase(),e.bezier?{easing:{type:"cubic-bezier",points:e.bezier},fn:e.fn}:{fn:e.fn,requiresBaking:"custom"}),t}function zo(t){let e=t>>>0;return()=>{e=e+1831565813>>>0;let n=e;return n=Math.imul(n^n>>>15,n|1),n^=n+Math.imul(n^n>>>7,n|61),((n^n>>>14)>>>0)/4294967296}}const Ic=/^\s*random\(\s*(\[.*\]|[^)]*)\s*\)\s*$/;function Oc(t){return typeof t=="string"&&Ic.test(t)}function Ip(t=1){let e=zo(t);const n=(l,c)=>((...h)=>h.length>=l?c(...h):u=>c(...h,u)),s=(l,c,h)=>Math.min(Math.max(h,Math.min(l,c)),Math.max(l,c)),i=(l,c,h,u,d)=>c===l?h:h+(d-l)/(c-l)*(u-h),o=(l,c)=>{if(typeof l=="number")return l===0?c:Math.round(c/l)*l;if(Array.isArray(l))return _c(l,c,1/0);if("values"in l)return _c(l.values,c,l.radius??1/0);const h=Math.round(c/l.increment)*l.increment;return Math.abs(h-c)<=(l.radius??1/0)?h:c},r=(l,c,h)=>{const u=l+e()*(c-l);return h?Math.round(u/h)*h:u};return{clamp:n(3,s),mapRange:n(5,i),normalize:n(3,(l,c,h)=>i(l,c,0,1,h)),interpolate:n(3,(l,c,h)=>{if(typeof l=="object"&&!Array.isArray(l)){const u={};for(const d of Object.keys(l))u[d]=Yn(l[d])(l[d],c[d],h);return u}return Yn(l)(l,c,h)}),wrap:((l,c,h)=>{if(Array.isArray(l)){const g=l,m=y=>g[(Math.round(y)%g.length+g.length)%g.length];return c===void 0?m:m(c)}const u=l,f=c-u,p=g=>f===0?u:((g-u)%f+f)%f+u;return h===void 0?p:p(h)}),wrapYoyo:n(3,(l,c,h)=>{const u=c-l;if(u===0)return l;const d=((h-l)%(u*2)+u*2)%(u*2);return l+(d>u?u*2-d:d)}),snap:n(2,o),random:((l,c,h,u)=>{if(Array.isArray(l)){const f=()=>l[Math.floor(e()*l.length)];return c===!0?f:f()}const d=()=>r(l,c,h);return u?d:d()}),shuffle:l=>{for(let c=l.length-1;c>0;c--){const h=Math.floor(e()*(c+1));[l[c],l[h]]=[l[h],l[c]]}return l},distribute:({base:l=0,amount:c,each:h,from:u="start",ease:d})=>(f,p,g)=>{const m=g.length,T=Os(f,m,{...c!==void 0?{amount:c}:{each:h??1},from:u}),k=c!==void 0?c:(h??1)*yo(m,u),b=d&&k>0?d(T/k)*k:T;return l+b},pipe:(...l)=>c=>l.reduce((h,u)=>u(h),c),splitColor:l=>Op(l),getUnit:l=>typeof l=="number"?"":/^-?[\d.]+(?:e[-+]?\d+)?([a-z%]*)$/i.exec(l.trim())?.[1]??"",seed:l=>{e=zo(l)},resolveRandomString:l=>{const c=Ic.exec(l)?.[1]??"";if(c.startsWith("[")){const p=c.slice(1,-1).split(",").map(g=>g.trim()).filter(Boolean).map(g=>Number.isFinite(Number(g))?Number(g):g.replace(/^['"]|['"]$/g,""));return p[Math.floor(e()*p.length)]}const[h,u,d]=c.split(",").map(f=>Number.parseFloat(f));return r(h,u,Number.isFinite(d)?d:void 0)}}}function _c(t,e,n){let s=e,i=1/0;for(const o of t){const r=Math.abs(o-e);r<i&&(i=r,s=o)}return i<=n?s:e}function Op(t){const e=t.trim(),n=/^#([0-9a-f]{3,8})$/i.exec(e)?.[1];if(n){const o=(n.length<=4?[...n].map(r=>r+r).join(""):n).match(/../g).map(r=>Number.parseInt(r,16));return o.length>=4?[o[0],o[1],o[2],Math.round(o[3]/255*1e3)/1e3]:[o[0],o[1],o[2]]}const s=(/rgba?\(([^)]+)\)/i.exec(e)?.[1]??"0,0,0").split(/[\s,/]+/).filter(Boolean).map(i=>Number.parseFloat(i));return s.length>=4?[s[0],s[1],s[2],s[3]]:[s[0]??0,s[1]??0,s[2]??0]}const _p=/^([+-])=\s*(-?[\d.]+)$/,Cp=/^([<>])\s*(?:([+-])?=?\s*(-?[\d.]+))?$/;function Xn(t,e){const n=e.scale??1,s=c=>Number.parseFloat(c)*n;if(t===void 0)return e.cursor;if(typeof t=="number")return t*n;const i=t.trim();if(i==="")return e.cursor;const o=_p.exec(i);if(o){const c=s(o[2]);return e.cursor+(o[1]==="-"?-c:c)}const r=Cp.exec(i);if(r){const c=r[1]==="<"?e.previousStart:e.previousEnd;if(r[3]===void 0)return c;const h=s(r[3]);return c+(r[2]==="-"?-h:h)}const a=/^(.+?)([+-])=\s*(-?[\d.]+)$/.exec(i);if(a){const c=e.labels.get(a[1].trim());if(c!==void 0){const h=s(a[3]);return c+(a[2]==="-"?-h:h)}}const l=e.labels.get(i);return l!==void 0?l:/^-?[\d.]+$/.test(i)?s(i):e.cursor}function Hp(t){if(typeof t!="object"||t===null)return!1;const e=t;return e.grid!==void 0||e.from==="random"||Array.isArray(e.from)||e.ease!==void 0||e.axis!==void 0}function Rp(t,e,n={}){if(t===0)return[];const s=e.grid==="auto"?Math.max(1,Math.min(t,n.columnsFromLayout?.()??t)):Array.isArray(e.grid)?Math.max(1,e.grid[1]):t,i=Array.isArray(e.grid)?Math.max(1,e.grid[0]):Math.ceil(t/s),o=p=>({x:p%s,y:Math.floor(p/s)}),r=e.from??"start",a=Array.isArray(r)?{x:r[0]*(s-1),y:r[1]*(i-1)}:typeof r=="number"?o(Math.max(0,Math.min(t-1,r))):r==="end"?o(t-1):r==="center"||r==="edges"?{x:(s-1)/2,y:(i-1)/2}:{x:0,y:0},l=p=>{const{x:g,y:m}=o(p),y=Math.abs(g-a.x),T=Math.abs(m-a.y);return e.axis==="x"?y:e.axis==="y"?T:Math.hypot(y,T)};let c=Array.from({length:t},(p,g)=>l(g));const h=Math.max(...c);if(r==="edges"&&(c=c.map(p=>h-p)),r==="random"){const p=n.random??Math.random;c=c.map(()=>p()*h)}const u=e.amount!==void 0?e.amount:(e.each??0)*h,d=e.ease?zn(e.ease):void 0,f=d?d.fn??Ct(d.easing):void 0;return c.map(p=>{const g=h===0?0:p/h;return(f?f(g):g)*u})}const Xo=new Set(["duration","delay","ease","repeat","repeatDelay","yoyo","stagger","onComplete","onUpdate","onStart","onRepeat","onReverseComplete","repeatRefresh","keyframes","easeEach","scrollTo","id","immediateRender","overwrite","paused","scrollTrigger","spring"]),Lp={rotation:"rotate",rotationZ:"rotate",rotationX:"rotateX",rotationY:"rotateY",transformPerspective:"perspective",perspective:"childPerspective"};function Vs(t){const e={},n={};for(const[s,i]of Object.entries(t))Xo.has(s)?e[s]=i:n[Lp[s]??s]=i;return{config:e,properties:n}}function Js(t,e){return t===void 0?e:t*1e3}function Go(t,e){if(t!==void 0)return typeof t=="number"?{each:t*1e3}:Hp(t)?{offsets:Rp(e?.count??0,t,e??{}).map(s=>s*1e3)}:{...t.each!==void 0&&{each:t.each*1e3},...t.amount!==void 0&&{amount:t.amount*1e3},...t.from!==void 0&&{from:t.from}}}const Fp={opacity:1,x:0,y:0,z:0,rotate:0,rotateX:0,rotateY:0,rotateZ:0,scale:1,scaleX:1,scaleY:1,scaleZ:1,skewX:0,skewY:0,originX:50,originY:50,perspective:0,blur:0,glow:0,clipTop:0,clipRight:0,clipBottom:0,clipLeft:0};function Cc(t){return Fp[t]}function Np(t){const e=typeof t=="string"||Array.isArray(t)?{path:t}:t;if(!e||typeof e.path!="string"&&!Array.isArray(e.path))throw new Error("gsap-compat: motionPath needs a path — SVG path data or an array of { x, y } points.");let n;if(Array.isArray(e.path))n=Tc(e.path,{curviness:e.curviness});else if(an(e.path))n=e.path;else throw new Error(`gsap-compat: motionPath "${e.path}" is not path data. Selectors and elements are resolved by live.to(); timeline() and tf need the path data itself.`);const s={pathData:n};return e.autoRotate!==void 0&&e.autoRotate!==!1&&(s.autoRotate=!0,typeof e.autoRotate=="number"&&(s.rotateOffset=e.autoRotate)),e.matrix&&(s.matrix=e.matrix),{config:s,start:e.start??0,end:e.end??1}}function Dp(t){const e=typeof t=="string"||Array.isArray(t)?{path:t}:{...t};return{...e,start:e.end??1,end:e.start??0}}function Hc(t){return typeof t=="object"&&t!==null&&"shape"in t?t.shape:t}function Wp(t){if(t.morphSVG===void 0)return t;const{morphSVG:e,...n}=t,s=Hc(e);if(typeof s!="string"||!an(s))throw new Error(`gsap-compat: morphSVG "${String(s)}" is not path data. Selectors and elements are resolved by live.to(); timeline() and tf need the path data itself.`);return{...n,d:s}}function Bp(t,e){if(t===!0)return[0,e];if(t===!1)return[0,0];if(typeof t=="number")return[0,Rc(t,e)];const n=t.trim().split(/[\s,]+/).filter(Boolean),s=r=>{const a=Number.parseFloat(r);if(Number.isNaN(a))throw new Error(`gsap-compat: drawSVG "${t}" is not a length or percentage`);return Rc(r.endsWith("%")?e*a/100:a,e)};if(n.length===0)return[0,e];if(n.length===1)return[0,s(n[0])];const i=s(n[0]),o=s(n[1]);return i<=o?[i,o]:[o,i]}function jp(t,e){const[n,s]=Bp(t,e);return{strokeDasharray:[s-n,e],strokeDashoffset:-n}}function qp(t,e){if(t.drawSVG===void 0)return t;const{drawSVG:n,...s}=t;return{...s,...jp(n,e)}}function Yp(t){if(t.drawSVG!==void 0)throw new Error("gsap-compat: drawSVG needs the stroke length from the page. Use live.to(), or animate strokeDasharray / strokeDashoffset directly (see drawSvgProperties).");return t}function Rc(t,e){return Math.max(0,Math.min(e,t))}function Kp(t){let e=2166136261;for(let n=0;n<t.length;n++)e=Math.imul(e^t.charCodeAt(n),16777619);return e>>>0}function zp(t,e,n){if(t.scrambleText!==void 0){const s=t.scrambleText,i=typeof s=="string"?{text:s}:s;if(typeof i?.text!="string")throw new Error("gsap-compat: scrambleText needs the text to end on — a string, or { text }.");const o=i.revealDelay&&n>0?i.revealDelay*1e3/n:void 0;return{to:i.text,mode:"scramble",...i.chars!==void 0&&{chars:i.chars},...i.speed!==void 0&&{refreshRate:20*i.speed},...o!==void 0&&{revealDelay:Math.min(o,.999)},...i.tweenLength!==void 0&&{tweenLength:i.tweenLength},...i.rightToLeft!==void 0&&{rightToLeft:i.rightToLeft},seed:i.seed??Kp(`${e}|${i.text}`)}}if(t.text!==void 0){const s=t.text,i=typeof s=="string"?{value:s}:s;if(typeof i?.value!="string")throw new Error("gsap-compat: text needs the text to end on — a string, or { value }.");return{to:i.value,mode:"type",...i.rightToLeft!==void 0&&{rightToLeft:i.rightToLeft}}}}function Uo(t){return Math.max(.1,t/25)}function Xp(t,e){const n=typeof e=="number"?{velocity:e}:e;if(typeof n?.velocity!="number"||!Number.isFinite(n.velocity))throw new Error("gsap-compat: inertia needs a velocity for each property — a number, or { velocity }.");const s=n.friction??(n.resistance!==void 0?Uo(n.resistance):void 0),i={from:t,velocity:n.velocity,...s!==void 0&&{friction:s},...n.min!==void 0&&{min:n.min},...n.max!==void 0&&{max:n.max}};return typeof n.end=="function"?i.end=[n.end(Dn(i))]:n.end!==void 0&&(i.end=Array.isArray(n.end)?[...n.end]:n.end),i}function Gp(t){const e=t===!0?{}:typeof t=="string"?{preset:t}:t;if(e.preset!==void 0&&!(e.preset in Hs))throw new Error(`gsap-compat: unknown spring preset "${e.preset}" — use one of ${Object.keys(Hs).join(", ")}`);return{...e.preset?Hs[e.preset]:{},...e.stiffness!==void 0&&{stiffness:e.stiffness},...e.damping!==void 0&&{damping:e.damping},...e.mass!==void 0&&{mass:e.mass},...e.restDelta!==void 0&&{restDelta:e.restDelta}}}function Up(t,e){if(t===!0||typeof t=="string")return;const n=t.velocity;return typeof n=="number"?n:n?.[e]}class je{timeline;options;cursor=0;fallbackRandom=zo(1);previousStart=0;previousEnd=0;labels=new Map;trackCounter=0;lastValues=new Map;constructor(e={}){this.options=e,this.timeline=new Nt({id:e.id??"gsap-compat",name:e.name,config:{...e.repeat!==void 0&&{loop:e.repeat},...e.yoyo!==void 0&&{alternate:e.yoyo},...e.repeatDelay!==void 0&&{repeatDelay:e.repeatDelay*1e3},...e.timeScale!==void 0&&{speed:e.timeScale}}})}to(e,n,s){return this.build(e,void 0,Gn(n),s)}from(e,n,s){const{config:i,properties:o}=Vs(Gn(n)),{motionPath:r,text:a,scrambleText:l,...c}=o,h=this.targetsOf(e)[0],u={...i};for(const p of Object.keys(c))u[p]=this.resolveStart(h,p);r!==void 0&&(u.motionPath=Dp(r));const d={},f=String(this.resolveStart(h,"text"));return a!==void 0&&(d.text=Vo(a),u.text=typeof a=="object"?{...a,value:f}:f),l!==void 0&&(d.text=Vo(l),u.scrambleText=typeof l=="object"?{...l,text:f}:f),this.build(e,{...c,...d},u,s)}fromTo(e,n,s,i){const{properties:o}=Vs(Gn(n));return this.build(e,o,Gn(s),i)}set(e,n,s){return this.build(e,void 0,{...Gn(n),duration:0},s)}get lastStart(){return this.previousStart}get lastEnd(){return this.previousEnd}addEvent(e){const n=Math.max(0,Xn(e,this.context()));return this.previousStart=n,this.previousEnd=n,this.cursor=Math.max(this.cursor,n),n}timeOf(e){return Xn(e,this.context())}addLabel(e,n){return this.labels.set(e,Xn(n,this.context())),this}labelTimes(){return[...this.labels.values()].sort((e,n)=>e-n)}labelTime(e){return this.labels.get(e)}add(e,n){const s=Xn(n,this.context());for(const o of e.timeline.tracks){if(!("keyframes"in o))continue;const r=Ws({...o,id:this.nextTrackId(`nested-${o.id}`),keyframes:o.keyframes.map(a=>({...a,time:a.time+s}))});this.timeline.addTrack(r)}const i=s+e.timeline.duration;return this.previousStart=s,this.previousEnd=i,this.cursor=Math.max(this.cursor,i),this}play(){return this.timeline.play(),this}pause(){return this.timeline.pause(),this}restart(){return this.timeline.stop(),this.timeline.play(),this}reverse(){return this.timeline.reverse(),this}kill(){return this.timeline.removeTracks(),this}reset(){return this.timeline.removeTracks(),this.cursor=0,this.previousStart=0,this.previousEnd=0,this.labels.clear(),this.lastValues.clear(),this.trackCounter=0,this}seek(e){if(typeof e=="string"){const n=this.labels.get(e);return n!==void 0&&this.timeline.seek(n),this}return this.timeline.seek(e*1e3),this}progress(e){const n=this.timeline.duration;return e!==void 0&&n>0&&this.timeline.seek(e*n),n>0?this.timeline.currentTime/n:0}timeScale(e){return e!==void 0&&(this.timeline.speed=e),this.timeline.speed}duration(){return this.timeline.duration/1e3}tick(e){return this.timeline.tick(e),this}toDefinition(){return this.timeline.toDefinition()}build(e,n,s,i){const{config:o,properties:r}=Vs(s),{motionPath:a,text:l,scrambleText:c,inertia:h,...u}=r,d=this.targetsOf(e),f=Xn(i,this.context()),p=Js(o.delay,0),g=Js(o.duration,500),m=Go(o.stagger,{count:d.length,columnsFromLayout:this.options.layoutColumns?()=>this.options.layoutColumns(d):void 0,random:this.options.random??this.fallbackRandom}),y=this.easingFor(o.ease),T=[],k=o.spring;let b=0,A=!1;for(const[v,$]of Object.entries(u)){const _=$;let P=n?.[v]!==void 0?n[v]:this.resolveStart(d[0],v);if(typeof P!=typeof _&&(this.warn(`no usable start value for "${v}" on "${d[0]}" — it will snap to ${String(_)}. Use fromTo() to animate it.`),P=_),k!==void 0&&(typeof P!="number"||typeof _!="number")&&this.warn(`spring works on numbers, so "${v}" on "${d[0]}" eases instead`),k!==void 0&&typeof P=="number"&&typeof _=="number"){const R={...Gp(k),from:P,to:_,velocity:Up(k,v)??this.options.startVelocity?.(d[0],v)??0},B=this.nextTrackId(`${d[0]}-${v}-spring`),j={id:B,target:d[0],...d.length>1&&{targets:d},...m&&d.length>1&&{stagger:m},property:v,kind:"spring",spring:R,delay:f+p};this.timeline.addTrack(j),T.push(B),b=Math.max(b,wl(R));for(const H of d)this.lastValues.set(`${H}|${v}`,_);continue}A=!0;const C=this.keyframesFor(P,_,g,y,o.ease),F=this.nextTrackId(`${d[0]}-${v}`);this.timeline.addTrack(Ws({id:F,target:d[0],...d.length>1&&{targets:d},...m&&d.length>1&&{stagger:m},property:v,delay:f+p,keyframes:C,...v==="quaternion"&&{interpolation:"slerp"}})),T.push(F);for(const R of d)this.lastValues.set(`${R}|${v}`,_)}const M=zp({text:l,scrambleText:c},d[0],g);if(M){const v=n?.text??n?.scrambleText,$=v!==void 0?Vo(v):this.resolveStart(d[0],"text"),_=this.nextTrackId(`${d[0]}-text`),P={id:_,target:d[0],...d.length>1&&{targets:d},...m&&d.length>1&&{stagger:m},property:"text",textConfig:{from:typeof $=="string"?$:String($??""),...M},delay:f+p,keyframes:this.keyframesFor(0,1,g,y,o.ease)};this.timeline.addTrack(P),T.push(_);for(const C of d)this.lastValues.set(`${C}|text`,M.to)}if(a!==void 0){const{config:v,start:$,end:_}=Np(a),P=this.nextTrackId(`${d[0]}-motionPath`),C={id:P,target:d[0],...d.length>1&&{targets:d},...m&&d.length>1&&{stagger:m},property:"motionPath",motionPathConfig:v,delay:f+p,keyframes:this.keyframesFor($,_,g,y,o.ease)};this.timeline.addTrack(C),T.push(P)}if(h!==void 0)for(const[v,$]of Object.entries(h)){const _=this.resolveStart(d[0],v);if(typeof _!="number"){this.warn(`inertia on "${v}" needs a numeric start value; skipped`);continue}const P=Xp(_,$),C=this.nextTrackId(`${d[0]}-${v}-inertia`),F={id:C,target:d[0],...d.length>1&&{targets:d},...m&&d.length>1&&{stagger:m},property:v,kind:"inertia",inertia:P,delay:f+p};this.timeline.addTrack(F),T.push(C),b=Math.max(b,on(P));for(const R of d)this.lastValues.set(`${R}|${v}`,sn(P))}const S=((h!==void 0||k!==void 0)&&!A&&!M&&a===void 0?b:Math.max(g,b))+(m&&d.length>1?Fn(d.length,m):0),I=f+p+S;return this.previousStart=f+p,this.previousEnd=I,this.cursor=Math.max(this.cursor,I),{trackIds:T,start:f+p,end:I,kill:()=>{for(const v of T)this.timeline.removeTrack(v)}}}keyframesFor(e,n,s,i,o){const r={time:0,value:e};if(s<=0)return[{time:0,value:n}];const a=typeof o=="string"?zn(o):void 0;if(a?.requiresBaking==="custom"||this.options.bakeEases&&Ln(i)){const c=a?.fn??Ct(i);return[r,...Ho(r,{time:s,value:n},c,{intervalMs:this.options.bakeIntervalMs})]}return[r,{time:s,value:n,...i&&{easing:i}}]}resolveStart(e,n){const s=this.lastValues.get(`${e}|${n}`);if(s!==void 0)return s;const i=this.options.startValue?.(e,n);if(i!==void 0)return i;const o=this.options.defaults?.[n];if(o!==void 0)return o;if(n==="text")return"";if(n==="quaternion")return[0,0,0,1];if(n==="d")throw new Error(`gsap-compat: no starting shape for "${e}". Use fromTo({ d: … }, { morphSVG: … }), or live.to(), which reads the element's current shape.`);const r=Cc(n);return r!==void 0?(this.warn(`no start value for "${n}" on "${e}" — using the static default ${r}. GSAP would read the live DOM here; tinyfly cannot, so pass an explicit fromTo() or a defaults map.`),r):(this.warn(`no start value or default for "${n}" on "${e}" — using 0`),0)}easingFor(e){if(e!==void 0){if(typeof e=="string")return zn(e).easing;if(typeof e=="function")throw new Error('gsap-compat: function eases cannot be serialized. Use a named ease, or a cubic-bezier via { type: "cubic-bezier", points: [...] }.');return e}}targetsOf(e){return Array.isArray(e)?e:[e]}context(){return{cursor:this.cursor,previousStart:this.previousStart,previousEnd:this.previousEnd,labels:this.labels,scale:1e3}}nextTrackId(e){return this.trackCounter+=1,`${e}-${this.trackCounter}`}warn(e){this.options.onWarning?.(`gsap-compat: ${e}`)}}function Vo(t){if(typeof t=="string")return t;if(t&&typeof t=="object"){const e=t;return String(e.value??e.text??"")}return String(t??"")}function Vp(t){return new je(t)}function Gn(t){return Yp(Wp(t))}function Jp(t){return!Array.isArray(t)||t.length!==4?null:`matrix3d(${Jt(ke(t)).map(n=>Math.round(n*1e6)/1e6+0).join(", ")})`}const Zp=new Set(["blur","brightness","glow","glowColor","shadowX","shadowY","shadowBlur","shadowColor"]),Qp="#ffffff",tm="rgba(0, 0, 0, 0.5)";function em(t){const e=[];if(t.blur!==void 0&&e.push(`blur(${Math.max(0,t.blur)}px)`),t.brightness!==void 0&&e.push(`brightness(${Math.max(0,t.brightness)})`),t.glow!==void 0&&e.push(`drop-shadow(0 0 ${Math.max(0,t.glow)}px ${t.glowColor??Qp})`),t.shadowX!==void 0||t.shadowY!==void 0||t.shadowBlur!==void 0){const n=t.shadowX??0,s=t.shadowY??0,i=Math.max(0,t.shadowBlur??0);e.push(`drop-shadow(${n}px ${s}px ${i}px ${t.shadowColor??tm})`)}return e.length>0?e.join(" "):null}function nm(t,e){const n=t.childNodes.length===1?t.firstChild:null;if(n&&n.nodeType===3){const s=n;s.data!==e&&(s.data=e);return}t.textContent!==e&&(t.textContent=e)}function sm(t){if(!("ownerSVGElement"in t))return;const e=t.style;!e||e.transformBox||(e.transformBox="fill-box",e.transformOrigin||(e.transformOrigin="50% 50%"))}const Lc=new Set(["width","height","top","right","bottom","left","margin","marginTop","marginRight","marginBottom","marginLeft","padding","paddingTop","paddingRight","paddingBottom","paddingLeft","borderRadius","borderWidth","fontSize","lineHeight","letterSpacing","outlineWidth","gap","rowGap","columnGap"]),im=new Set(["x","y","z","rotate","rotateX","rotateY","rotateZ","scale","scaleX","scaleY","scaleZ","skewX","skewY","quaternion","motionPathX","motionPathY","motionPathRotate"]),om=["x","motionPathX","y","motionPathY","z","rotate","rotateZ","motionPathRotate","rotateX","rotateY","quaternion","scale","scaleX","scaleY","scaleZ","skewX","skewY"],rm=new Set(["childPerspective","perspectiveOriginX","perspectiveOriginY"]),am=new Set(["originX","originY"]),lm=new Set(["clipTop","clipRight","clipBottom","clipLeft"]),cm=new Set(["drawOn"]),hm={fill:"backgroundColor",stroke:"borderColor",strokeWidth:"borderWidth",color:"color",backgroundColor:"backgroundColor",borderColor:"borderColor"},Fc={fill:"fill",stroke:"stroke",strokeWidth:"strokeWidth",strokeDasharray:"strokeDasharray",strokeDashoffset:"strokeDashoffset",fillOpacity:"fillOpacity",strokeOpacity:"strokeOpacity"},um="http://www.w3.org/2000/svg";class qe{targets=new Map;registerTarget(e,n){this.targets.set(e,n)}unregisterTarget(e){this.targets.delete(e)}getTarget(e){return this.targets.get(e)}clearTargets(){this.targets.clear()}applyState(e){for(const[n,s]of e.values){const i=this.targets.get(n);i&&this.applyProperties(i,s)}}applyProperties(e,n){let s=null,i=null,o=null,r=null,a=null;const l=n.has("motionPathX"),c=n.has("motionPathY"),h=n.has("motionPathRotate");for(const[p,g]of n)if(!(p==="x"&&l)&&!(p==="y"&&c)&&!((p==="rotate"||p==="rotateZ")&&h)&&!cm.has(p)){if(im.has(p))(s??={})[p]=g;else if(rm.has(p))typeof g=="number"&&((i??={})[p]=g);else if(am.has(p))typeof g=="number"&&((o??={})[p]=g);else if(lm.has(p))typeof g=="number"&&((r??={})[p]=g);else if(Zp.has(p))(a??={})[p]=g;else if(p!=="perspective"){if(p!=="shine")if(p==="text"&&typeof g=="string")nm(e,g);else if(p==="d"&&typeof g=="string"){const m=e;(m.tagName?.toLowerCase()==="path"?m:m.querySelector?.("path"))?.setAttribute?.("d",g)}else this.applyStyleProperty(e,p,g)}}const u=n.get("shine");typeof u=="number"&&this.applyShine(e,u);const d=[],f=n.get("perspective");if(typeof f=="number"&&f>0&&d.push(`perspective(${f}px)`),s)for(const p of om){const g=s[p];if(g===void 0)continue;const m=this.buildTransformPart(p,g);m&&d.push(m)}if(d.length>0&&(e.style.transform=d.join(" "),sm(e)),i&&(i.childPerspective!==void 0&&(e.style.perspective=`${i.childPerspective}px`),(i.perspectiveOriginX!==void 0||i.perspectiveOriginY!==void 0)&&(e.style.perspectiveOrigin=`${i.perspectiveOriginX??50}% ${i.perspectiveOriginY??50}%`)),o){const p=o.originX??50,g=o.originY??50;e.style.transformOrigin=`${p}% ${g}%`}if(r){const p=r.clipTop??0,g=r.clipRight??0,m=r.clipBottom??0,y=r.clipLeft??0;e.style.clipPath=`inset(${p}% ${g}% ${m}% ${y}%)`}if(a){const p=em(a);p&&(e.style.filter=p)}}buildTransformPart(e,n){if(e==="quaternion")return Jp(n);if(typeof n!="number")return null;switch(e){case"x":case"motionPathX":return`translateX(${n}px)`;case"y":case"motionPathY":return`translateY(${n}px)`;case"z":return`translateZ(${n}px)`;case"rotate":case"rotateZ":case"motionPathRotate":return`rotate(${n}deg)`;case"rotateX":return`rotateX(${n}deg)`;case"rotateY":return`rotateY(${n}deg)`;case"scale":return`scale(${n})`;case"scaleX":return`scaleX(${n})`;case"scaleY":return`scaleY(${n})`;case"scaleZ":return`scaleZ(${n})`;case"skewX":return`skewX(${n}deg)`;case"skewY":return`skewY(${n}deg)`;default:return null}}applyShine(e,n){e.dataset.shineBase||(e.dataset.shineBase=e.style.color||"currentColor");const s=e.dataset.shineBase,i=-20+n*140,o=e.style;o.color="transparent",o.backgroundImage=`linear-gradient(105deg, transparent 40%, rgba(255, 255, 255, 0.9) 50%, transparent 60%), linear-gradient(${s}, ${s})`,o.backgroundSize="250% 100%, 100% 100%",o.backgroundPosition=`${i}% 0, 0 0`,o.backgroundRepeat="no-repeat",o.webkitBackgroundClip="text",o.backgroundClip="text"}applyStyleProperty(e,n,s){let i;if(e.namespaceURI===um&&n in Fc){const a=Array.isArray(s)?s.join(", "):String(s);e.style[Fc[n]]=a;return}else n==="fill"&&e.dataset?.elementType==="text"?i="color":i=hm[n]??n;let r;typeof s=="number"?Lc.has(n)||Lc.has(i)?r=`${s}px`:r=String(s):Array.isArray(s)?r=s.join(", "):r=s,e.style[i]=r}}const dm={request:t=>requestAnimationFrame(t),cancel:t=>cancelAnimationFrame(t)};class Nc{adapter=new qe;scheduler;rootOption;onWarning;names=new WeakMap;elements=new Map;nameCounter=0;objectNames=new WeakMap;objects=new Map;owned=new Set;currentCollector;tickerCallbacks=new Set;tickerTime=0;tickerFrame=0;liveTimelines=new Set;utils=Ip();active=new Map;applied=new Map;dirty=new Set;frameId=null;lastTimestamp=null;destroyed=!1;constructor(e={}){this.scheduler=e.scheduler??dm,this.rootOption=e.root,this.onWarning=e.onWarning}get root(){return this.rootOption??document}resolveTargets(e){const n=[];for(const s of this.targetsOf(e)){const i=this.nameFor(s);Jo(s)&&this.currentCollector?.touch(s,i),n.push(i)}return n}query(e){return this.selectorRoot.querySelector(e)}get collector(){return this.currentCollector}setCollector(e){this.currentCollector=e}forget(e){this.applied.delete(e),this.dirty.delete(e)}get selectorRoot(){return this.currentCollector?.scope??this.root}elementFor(e){return this.elements.get(e)}objectFor(e){return this.objects.get(e)}appliedValue(e,n){return this.applied.get(e)?.get(n)}velocityOf(e,n){for(const i of[...this.active.keys()].reverse()){if(i.getTracks({target:e,property:n}).length===0)continue;const o=i.currentTime;if(o<4)return 0;const r=i.getStateAtTime(o).values.get(e)?.get(n),a=i.getStateAtTime(o-4).values.get(e)?.get(n);if(typeof r!="number"||typeof a!="number")return;const l=(r-a)/4;return(i.direction==="reverse"?-l:l)*1e3}}ticker={add:e=>{this.destroyed||(this.tickerCallbacks.size===0&&(this.tickerTime=0,this.tickerFrame=0),this.tickerCallbacks.add(e),this.currentCollector?.track({revert:()=>this.ticker.remove(e)}),this.startLoop())},remove:e=>{this.tickerCallbacks.delete(e),this.running||this.stopLoop()}};activate(e,n={}){this.destroyed||(e.onUpdate=s=>this.write(s),this.active.delete(e),this.active.set(e,n),this.startLoop())}deactivate(e){this.active.delete(e),this.running||this.stopLoop()}own(e){return this.destroyed?e.destroy():this.owned.add(e),e}destroy(){this.destroyed=!0;for(const e of this.owned)e.destroy();this.owned.clear();for(const e of this.active.keys())e.stop();this.active.clear(),this.stopLoop(),this.adapter.clearTargets(),this.elements.clear(),this.names=new WeakMap,this.objects.clear(),this.objectNames=new WeakMap,this.tickerCallbacks.clear(),this.liveTimelines.clear(),this.applied.clear(),this.dirty.clear()}apply(e,n){if(this.destroyed)return;const s=new Map(Object.entries(n));this.write({values:new Map([[e,s]]),currentTime:0,playbackState:"idle",direction:"forward",loopIteration:0}),this.flush()}render(e){this.destroyed||(this.write(e.getStateAtTime(e.currentTime)),this.flush())}tick(e){const n=[...this.active];for(const[s]of n)s.duration<=0?(this.write(s.getStateAtTime(0)),s.stop()):s.tick(e);this.flush();for(const[s,i]of n)i.onUpdate?.(),s.playbackState!=="playing"&&this.active.get(s)===i&&this.active.delete(s);this.flush(),this.runTicker(e),this.running||this.stopLoop()}get running(){return this.active.size>0||this.tickerCallbacks.size>0}runTicker(e){if(this.tickerCallbacks.size!==0){this.tickerTime+=e,this.tickerFrame+=1;for(const n of[...this.tickerCallbacks])n(this.tickerTime/1e3,e,this.tickerFrame)}}write(e){for(const[n,s]of e.values){let i=this.applied.get(n);i||(i=new Map,this.applied.set(n,i));for(const[o,r]of s)i.set(o,r);this.dirty.add(n)}}flush(){if(this.dirty.size===0)return;const e=new Map;for(const n of this.dirty){const s=this.applied.get(n),i=this.objects.get(n);if(i)for(const[o,r]of s)i[o]=r;else e.set(n,s)}this.dirty.clear(),e.size!==0&&this.adapter.applyState({values:e,currentTime:0,playbackState:"playing",direction:"forward",loopIteration:0})}frame=e=>{this.frameId=null;const n=this.lastTimestamp===null?0:e-this.lastTimestamp;this.lastTimestamp=e,n>0&&this.tick(n),this.running&&this.frameId===null&&(this.frameId=this.scheduler.request(this.frame))};startLoop(){this.frameId===null&&(this.lastTimestamp=null,this.frameId=this.scheduler.request(this.frame))}stopLoop(){this.frameId!==null&&this.scheduler.cancel(this.frameId),this.frameId=null,this.lastTimestamp=null}targetsOf(e){if(typeof e=="string")return Array.from(this.selectorRoot.querySelectorAll(e));if(Jo(e))return[e];if(!fm(e))return[e];const n=[];for(const s of Array.from(e))n.push(...this.targetsOf(s));return n}nameFor(e){return Jo(e)?this.elementName(e):this.objectName(e)}objectName(e){const n=this.objectNames.get(e);if(n)return n;let s;do this.nameCounter+=1,s=`obj-${this.nameCounter}`;while(this.objects.has(s)||this.elements.has(s));return this.objectNames.set(e,s),this.objects.set(s,e),s}elementName(e){const n=this.names.get(e);if(n)return n;let s=e.id?`#${e.id}`:"";if(!s||this.elements.has(s))do this.nameCounter+=1,s=`el-${this.nameCounter}`;while(this.elements.has(s));return this.names.set(e,s),this.elements.set(s,e),this.adapter.registerTarget(s,e),s}}function Jo(t){return typeof t=="object"&&t!==null&&t.nodeType===1}function fm(t){if(Array.isArray(t))return!0;const e=t;return typeof e.length=="number"&&typeof e.item=="function"}function Zs(t){const e=t.style;if(!e)return t.getBoundingClientRect();const n=e.transform;e.transform="none";const s=t.getBoundingClientRect();return e.transform=n,s}const Dc=t=>typeof t=="object"&&t!==null&&t.nodeType===1;function gm(t){const e={};for(const n of Array.from(t.attributes))e[n.name]=n.value;return e}function pm(t){const e=t.getScreenCTM?.();if(e)return[e.a,e.b,e.c,e.d,e.e,e.f];const n=t.getBoundingClientRect();return[1,0,0,1,n.left,n.top]}function mm(t,e){const n=typeof t=="string"||Array.isArray(t)||Dc(t)?{path:t}:t,{align:s,alignOrigin:i,path:o,...r}=n,a=M=>{const E=Dc(M)?M:e.query(M);return E||e.warn(`gsap-compat: motionPath could not find "${String(M)}"`),E};let l=null,c="";if(Array.isArray(o)||typeof o=="string"&&an(o))c=o;else{l=a(o);const M=l&&Ys({tag:l.localName,attributes:gm(l)});l&&!M&&e.warn(`gsap-compat: motionPath element <${l.localName}> has no path geometry`),c=M??""}const h={...r,path:c};if(s===void 0||s===!1)return h;const u=s===!0?l:a(s);if(!u)return s===!0&&e.warn("gsap-compat: motionPath align: true needs the path to be an element"),h;const d=e.targets[0];if(!d)return h;const[f,p,g,m,y,T]=pm(u),k=Zs(d),[b,A]=i??[.5,.5];for(const M of e.targets.slice(1)){const E=Zs(M);if(Math.abs(E.left-k.left)>.5||Math.abs(E.top-k.top)>.5){e.warn("gsap-compat: motionPath align measures the first target; the others are laid out elsewhere");break}}return h.matrix=[f,p,g,m,y-k.left-b*k.width,T-k.top-A*k.height],h}const Wc=t=>typeof t=="object"&&t!==null&&t.nodeType===1;function Bc(t){const e={};for(const n of Array.from(t.attributes))e[n.name]=n.value;return e}function jc(t){if(!t)return null;const e=Ys({tag:t.localName,attributes:Bc(t)});return e||(t.querySelector("path")?.getAttribute("d")??null)}function ym(t,e,n){const s=Hc(t);if(typeof s=="string"&&an(s))return s;const i=Wc(s)?s:typeof s=="string"?e(s):null,o=jc(i);return o||(n(`gsap-compat: morphSVG could not find a shape for "${String(s)}"`),"")}const bm=new Set(["cx","cy","r","rx","ry","x","y","width","height","x1","y1","x2","y2","points"]);function wm(t,e=document){return(typeof t=="string"?Array.from(e.querySelectorAll(t)):Wc(t)?[t]:Array.from(t)).map(s=>{if(s.localName==="path")return s;const i=Ys({tag:s.localName,attributes:Bc(s)});if(!i||!s.parentNode)return s;const o=s.ownerDocument.createElementNS("http://www.w3.org/2000/svg","path");for(const r of Array.from(s.attributes))bm.has(r.name)||o.setAttribute(r.name,r.value);return o.setAttribute("d",i),s.parentNode.replaceChild(o,s),o})}const qc=.3;class Yc{options;target;running=!1;dragging=!1;passedTolerance=!1;lastX=0;lastY=0;startX=0;startY=0;velocityX=0;velocityY=0;lastTime=0;constructor(e){this.options=e,this.target=e.target}start(){if(this.running)return;this.running=!0;const e=this.options.type??["pointer","touch"];e.includes("pointer")&&(this.target.addEventListener("pointerdown",this.onPointerDown),this.target.addEventListener("pointermove",this.onPointerMove),this.target.addEventListener("pointerup",this.onPointerUp),this.target.addEventListener("pointercancel",this.onPointerUp)),e.includes("touch")&&(this.target.addEventListener("touchstart",this.onTouchStart,{passive:!1}),this.target.addEventListener("touchmove",this.onTouchMove,{passive:!1}),this.target.addEventListener("touchend",this.onTouchEnd)),e.includes("wheel")&&this.target.addEventListener("wheel",this.onWheel,{passive:!1})}stop(){this.running&&(this.running=!1,this.target.removeEventListener("pointerdown",this.onPointerDown),this.target.removeEventListener("pointermove",this.onPointerMove),this.target.removeEventListener("pointerup",this.onPointerUp),this.target.removeEventListener("pointercancel",this.onPointerUp),this.target.removeEventListener("touchstart",this.onTouchStart),this.target.removeEventListener("touchmove",this.onTouchMove),this.target.removeEventListener("touchend",this.onTouchEnd),this.target.removeEventListener("wheel",this.onWheel))}destroy(){this.stop()}get velocity(){return{x:this.velocityX,y:this.velocityY}}begin(e,n,s){this.dragging=!0,this.passedTolerance=!1,this.startX=e,this.startY=n,this.lastX=e,this.lastY=n,this.velocityX=0,this.velocityY=0,this.lastTime=Kc(),this.options.onPress?.(this.stateFrom(0,0,s))}move(e,n,s){if(!this.dragging)return;const i=e-this.lastX,o=n-this.lastY;this.lastX=e,this.lastY=n;const r=e-this.startX,a=n-this.startY,l=this.options.tolerance??3;if(!this.passedTolerance){if(Math.hypot(r,a)<l)return;this.passedTolerance=!0}this.updateVelocity(i,o),this.options.preventDefault!==!1&&s.cancelable&&s.preventDefault(),this.options.onMove?.(this.stateFrom(i,o,s))}end(e){this.dragging&&(this.dragging=!1,this.options.onRelease?.(this.stateFrom(0,0,e)))}updateVelocity(e,n){const s=Kc(),i=Math.max(1,s-this.lastTime);this.lastTime=s;const o=e/i*1e3,r=n/i*1e3;this.velocityX+=(o-this.velocityX)*qc,this.velocityY+=(r-this.velocityY)*qc}stateFrom(e,n,s){return{deltaX:e,deltaY:n,velocityX:this.velocityX,velocityY:this.velocityY,totalX:this.lastX-this.startX,totalY:this.lastY-this.startY,isDragging:this.dragging,event:s}}onPointerDown=e=>{const n=e,s=this.target;if(typeof n.pointerId=="number"&&typeof s.setPointerCapture=="function")try{s.setPointerCapture(n.pointerId)}catch{}this.begin(n.clientX,n.clientY,e)};onPointerMove=e=>{const n=e;this.move(n.clientX,n.clientY,e)};onPointerUp=e=>this.end(e);onTouchStart=e=>{const n=e.touches[0];n&&this.begin(n.clientX,n.clientY,e)};onTouchMove=e=>{const n=e.touches[0];n&&this.move(n.clientX,n.clientY,e)};onTouchEnd=e=>this.end(e);onWheel=e=>{const n=e;this.options.preventDefault!==!1&&n.cancelable&&n.preventDefault(),this.updateVelocity(n.deltaX,n.deltaY),this.options.onMove?.({deltaX:n.deltaX,deltaY:n.deltaY,velocityX:this.velocityX,velocityY:this.velocityY,totalX:0,totalY:0,isDragging:!1,event:e})}}function Kc(){return typeof performance<"u"?performance.now():Date.now()}function zc(t,e,n){let s={delta:0,line:null},i=n;for(const o of t)for(const r of e){const a=Math.abs(r-o);a<=i&&(i=a,s={delta:r-o,line:r})}return s}function Xc(t,e){return e<=0?[]:t.map(n=>Math.round(n/e)*e)}class Zo{options;observer;x;y;originX=0;originY=0;snappedX=null;snappedY=null;constructor(e){this.options=e,this.x=e.initialX??0,this.y=e.initialY??0,this.observer=new Yc({target:e.target,onPress:n=>{const s=e.getPosition?.();s&&(this.x=s.x,this.y=s.y),this.originX=this.x,this.originY=this.y,e.onPress?.(n)},onMove:n=>this.handleMove(n),onRelease:n=>e.onRelease?.(n)})}start(){this.observer.start()}stop(){this.observer.stop()}destroy(){this.observer.destroy()}get position(){return{x:this.x,y:this.y}}get velocity(){return this.observer.velocity}setPosition(e,n){const s=this.options.axis??"both";this.x=s==="y"?this.x:this.applyConstraints(e,"x"),this.y=s==="x"?this.y:this.applyConstraints(n,"y")}get snapLines(){return{x:this.snappedX,y:this.snappedY}}snapThreshold(){if(this.options.snapThreshold!==void 0)return this.options.snapThreshold;const e=this.options.snap??0;return e>0?e/2:8}handleMove(e){this.setPosition(this.originX+e.totalX,this.originY+e.totalY),this.options.mode==="scrub"&&this.scrub(),this.options.onDrag?.(this.position,e),this.options.onSnap?.(this.snapLines)}scrub(){const e=this.options.timeline;if(!e)return;const n=e.duration;if(n<=0)return;const s=this.options.scrubDistance??500;if(s===0)return;const i=(this.options.axis??"both")==="y"?this.y:this.x,o=km(i/s);e.pause(),e.seek(o*n)}applyConstraints(e,n){let s=e;const i=[...Xc([s],this.options.snap??0),...(n==="x"?this.options.snapLinesX:this.options.snapLinesY)??[]],o=zc([s],i,this.snapThreshold());s+=o.delta,n==="x"?this.snappedX=o.line:this.snappedY=o.line;const r=this.options.bounds;if(r){const a=n==="x"?r.minX:r.minY,l=n==="x"?r.maxX:r.maxY;a!==void 0&&(s=Math.max(a,s)),l!==void 0&&(s=Math.min(l,s))}return s}}function km(t){return t<0?0:t>1?1:t}function vm(t){const e=new Zo(t);return e.start(),e}const Mm={x:"x",y:"y","x,y":"both"},Qo=t=>typeof t=="object"&&t!==null&&t.nodeType===1;function Gc(t,e){const n=Zs(t),s=e.getBoundingClientRect();return{minX:s.left-n.left,maxX:s.right-n.right,minY:s.top-n.top,maxY:s.bottom-n.bottom}}function Uc(t){return Array.isArray(t)?[...t]:t}function Sm(t,e,n,s={}){const[i]=e.resolveTargets(n),o=i?e.elementFor(i):void 0;if(!i||!o)throw new Error(`gsap-compat: live.draggable could not find ${String(n)}`);if(s.type==="rotation")return Tm(t,e,i,o,s);const r=Mm[s.type??"x,y"],a=()=>{const g=e.appliedValue(i,"x"),m=e.appliedValue(i,"y");return{x:typeof g=="number"?g:0,y:typeof m=="number"?m:0}},l=typeof s.bounds=="string"?e.query(s.bounds):Qo(s.bounds)?s.bounds:null,h={bounds:(!l&&s.bounds&&!Qo(s.bounds)?s.bounds:void 0)??(l?Gc(o,l):void 0)};let u=null;const d=()=>{u?.kill(),u=null},f=g=>{const m=s.inertia===!0?{}:s.inertia,y=m.friction??(m.resistance!==void 0?Uo(m.resistance):4),T=a(),k=h.bounds??{};let b,A;const M=m.end;if(Array.isArray(M)){const x=Dn({from:T.x,velocity:r==="y"?0:g.x,friction:y}),S=Dn({from:T.y,velocity:r==="x"?0:g.y,friction:y});let I=M[0];for(const v of M)Math.hypot(v.x-x,v.y-S)<Math.hypot(I.x-x,I.y-S)&&(I=v);I&&(b=[I.x],A=[I.y])}else typeof M=="number"?(b=M,A=M):M&&(b=Uc(M.x),A=Uc(M.y));const E={};r!=="y"&&(E.x={velocity:g.x,friction:y,min:k.minX,max:k.maxX,end:b}),r!=="x"&&(E.y={velocity:g.y,friction:y,min:k.minY,max:k.maxY,end:A}),u=t.to(o,{inertia:E,onComplete:()=>s.onThrowComplete?.()})},p=new Zo({target:o,axis:r,snap:s.snap,get bounds(){return h.bounds},getPosition:a,onPress:()=>{d(),l&&(h.bounds=Gc(o,l)),s.onPress?.()},onDrag:g=>{e.apply(i,r==="x"?{x:g.x}:r==="y"?{y:g.y}:{x:g.x,y:g.y}),s.onDrag?.(g)},onRelease:()=>{const g=p.velocity;s.onRelease?.(g),s.inertia&&f(g)}});return p.start(),{draggable:p,get position(){return a()},get rotation(){const g=e.appliedValue(i,"rotate");return typeof g=="number"?g:0},destroy(){d(),p.destroy()}}}function Tm(t,e,n,s,i){const o=typeof i.bounds=="object"&&i.bounds!==null&&!Qo(i.bounds)?i.bounds:{},r=()=>{const k=e.appliedValue(n,"rotate");return typeof k=="number"?k:0},a=k=>Math.min(o.maxRotation??1/0,Math.max(o.minRotation??-1/0,k));let l=null,c=!1,h,u={x:0,y:0},d=0,f=0,p=[];const g=k=>Math.atan2(k.clientY-u.y,k.clientX-u.x)*180/Math.PI,m=k=>{if(c)return;l?.kill(),l=null,c=!0,h=k.pointerId,s.setPointerCapture?.(k.pointerId);const b=s.getBoundingClientRect();u={x:b.left+b.width/2,y:b.top+b.height/2},d=g(k),f=r(),p=[{time:performance.now(),rotation:f}],i.onPress?.()},y=k=>{if(!c||k.pointerId!==h)return;const b=g(k);let A=b-d;A>180&&(A-=360),A<-180&&(A+=360),d=b,f+=A;let M=a(f);i.snap&&(M=a(Math.round(M/i.snap)*i.snap)),e.apply(n,{rotate:M});const E=performance.now();for(p.push({time:E,rotation:M});p.length>2&&E-p[0].time>100;)p.shift();const x={x:0,y:0};i.onDrag?.(x)},T=k=>{if(!c||k.pointerId!==h)return;c=!1;const b=p[0],A=p[p.length-1],M=b&&A?(A.time-b.time)/1e3:0,E=M>0?(A.rotation-b.rotation)/M:0;if(i.onRelease?.({x:E,y:0}),!i.inertia)return;const x=i.inertia===!0?{}:i.inertia,S=x.friction??(x.resistance!==void 0?Uo(x.resistance):4),I=typeof x.end=="number"||Array.isArray(x.end)?x.end:void 0;l=t.to(s,{inertia:{rotate:{velocity:E,friction:S,min:o.minRotation,max:o.maxRotation,end:Array.isArray(I)?I.filter(v=>typeof v=="number"):I}},onComplete:()=>i.onThrowComplete?.()})};return s.addEventListener("pointerdown",m),s.addEventListener("pointermove",y),s.addEventListener("pointerup",T),s.addEventListener("pointercancel",T),s.style.touchAction="none",{draggable:void 0,position:{x:0,y:0},get rotation(){return r()},destroy(){l?.kill(),s.removeEventListener("pointerdown",m),s.removeEventListener("pointermove",y),s.removeEventListener("pointerup",T),s.removeEventListener("pointercancel",T)}}}const Em={opacity:0,scale:.6};function Am(t){const e=t.getBoundingClientRect();return e.width===0&&e.height===0?null:{cx:e.left+e.width/2,cy:e.top+e.height/2,width:e.width,height:e.height}}function Vc(t){const e=Zs(t);return e.width===0&&e.height===0?null:{cx:e.left+e.width/2,cy:e.top+e.height/2,width:e.width,height:e.height}}function tr(t,e){const s=t.resolveTargets(e).map(r=>t.elementFor(r)).filter(r=>!!r),i=new Map,o=new Map;for(const r of s){const a=Am(r);i.set(r,a);const l=Jc(r);a&&l!==void 0&&!o.has(l)&&o.set(l,{element:r,box:a})}return{elements:s,boxes:i,ids:o}}const er=new WeakMap;function nr(t,e,n,s={}){const i=s.duration??.6,o=s.ease??"power2.inOut",r=s.stagger??0,a=s.scale!==!1,l=s.enter===void 0?Em:s.enter,c=new Set(n.elements);if(s.targets!==void 0)for(const f of t.resolveTargets(s.targets)){const p=t.elementFor(f);p&&c.add(p)}const h=[...c].sort((f,p)=>f===p?0:f.compareDocumentPosition(p)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1),u=e({onComplete:s.onComplete});let d=0;for(const f of h){const p=Vc(f);if(!p)continue;let g=n.boxes.get(f)??null,m;const y=Jc(f),T=!g&&y!==void 0?n.ids.get(y):void 0;T&&T.element!==f&&(g=T.box,m=T.element);const[k]=t.resolveTargets(f);er.get(f)?.timeline.removeTracks({target:k});const b=d*r;if(!g){if(l===!1)continue;u.fromTo(f,{x:0,y:0,scaleX:1,scaleY:1,...l},{...Zc(l),x:0,y:0,scaleX:1,scaleY:1,duration:i,ease:o,delay:b},0),er.set(f,u),d++;continue}const A=g.cx-p.cx,M=g.cy-p.cy,E=a?g.width/p.width:1,x=a?g.height/p.height:1;if(!(Math.abs(A)>.5||Math.abs(M)>.5||Math.abs(E-1)>.001||Math.abs(x-1)>.001)){const v=($,_)=>{const P=t.appliedValue(k,$);return typeof P=="number"&&Math.abs(P-_)>1e-6};(v("x",0)||v("y",0)||v("scaleX",1)||v("scaleY",1))&&u.set(f,{x:0,y:0,scaleX:1,scaleY:1},0);continue}const I=s.fade===!0&&m!==void 0;u.fromTo(f,{x:A,y:M,scaleX:E,scaleY:x,...I&&{opacity:0}},{x:0,y:0,scaleX:1,scaleY:1,...I&&{opacity:1},duration:i,ease:o,delay:b},0),I&&m&&Vc(m)&&u.fromTo(m,{opacity:1},{opacity:0,duration:i,ease:o,delay:b},0),er.set(f,u),d++}return u}function Jc(t){return t.dataset?.flipId}function Zc(t){const e={};for(const n of Object.keys(t))e[n]=n==="opacity"||n.startsWith("scale")?1:0;return e}function xm(t,e={}){const n=new Set((e.type??"chars,words,lines").split(",").map(g=>g.trim())),s={chars:e.charsClass??"char",words:e.wordsClass??"word",lines:e.linesClass??"line"},i=e.aria!==!1,o=t.map(g=>({element:g,html:g.innerHTML,ariaLabel:g.getAttribute("aria-label")}));let r={chars:[],words:[],lines:[],masks:[]},a,l,c=!1;const h=()=>{for(const{element:g,html:m,ariaLabel:y}of o)g.innerHTML=m,y===null?g.removeAttribute("aria-label"):g.setAttribute("aria-label",y)},u=()=>{a&&(a.revert?a.revert():a.kill?.(),a=void 0)},d=()=>{const g={chars:[],words:[],lines:[],masks:[]};for(const{element:m}of o){const y=(m.textContent??"").replace(/\s+/g," ").trim(),T=$m(m,s.words),k=n.has("chars")?T.flatMap(M=>Pm(M,s.chars)):[],b=n.has("lines")?Om(m,T,s.lines):[];if(i){!m.hasAttribute("aria-label")&&y&&m.setAttribute("aria-label",y);for(const M of T)M.setAttribute("aria-hidden","true")}if(n.has("words"))g.words.push(...T);else for(const M of T)M.removeAttribute("class");g.chars.push(...k),g.lines.push(...b);const A=e.mask==="lines"?b:e.mask==="words"?T:e.mask==="chars"?k:[];for(const M of A)g.masks.push(_m(M,`${s[e.mask]}-mask`))}r=g},f={elements:t,get chars(){return r.chars},get words(){return r.words},get lines(){return r.lines},get masks(){return r.masks},split(){c||(u(),h(),d(),a=e.onSplit?.(f))},revert(){c=!0,l?.disconnect(),u(),h()}};d(),a=e.onSplit?.(f),e.autoSplit&&p();function p(){const g=new Map;let m=!1;const y=()=>{if(m)return;m=!0;const k=()=>{m=!1,f.split()};typeof requestAnimationFrame=="function"?requestAnimationFrame(k):setTimeout(k,0)};if(typeof ResizeObserver=="function"){l=new ResizeObserver(k=>{let b=!1;for(const A of k){const M=Math.round(A.contentRect.width),E=g.get(A.target);g.set(A.target,M),E!==void 0&&E!==M&&(b=!0)}b&&y()});for(const k of t)l.observe(k)}const T=t[0]?.ownerDocument?.fonts;T&&T.status!=="loaded"&&T.ready.then(()=>y())}return f}function $m(t,e){const n=t.ownerDocument,s=[],i=n.createTreeWalker(t,4),o=[];for(let r=i.nextNode();r;r=i.nextNode())o.push(r);for(const r of o){const a=r.data.match(/\s+|\S+/g)??[];if(a.length===0)continue;const l=n.createDocumentFragment();for(const c of a){if(/^\s/.test(c)){l.appendChild(n.createTextNode(c));continue}const h=n.createElement("span");h.className=e,h.style.display="inline-block",h.textContent=c,l.appendChild(h),s.push(h)}r.replaceWith(l)}return s}function Pm(t,e){const n=t.ownerDocument,s=Im(t.textContent??"").map(i=>{const o=n.createElement("span");return o.className=e,o.style.display="inline-block",o.textContent=i,o});return t.replaceChildren(...s),s}function Im(t){const e=Intl.Segmenter;return e?Array.from(new e(void 0,{granularity:"grapheme"}).segment(t),n=>n.segment):Array.from(t)}function Om(t,e,n){const s=t.ownerDocument,i=new Map(e.map(p=>[p,p.getBoundingClientRect()])),o=[],r=p=>{for(const g of Array.from(p.childNodes))g.nodeType===3||i.has(g)||g.tagName==="BR"?o.push(g):r(g)};r(t);const a=[];let l=null,c=0,h=0,u=!1,d=[];const f=()=>{l=s.createElement("span"),l.className=n,l.style.display="block",a.push(l),d=[]};for(const p of o){if(p.tagName==="BR"){u=!0;continue}const g=i.get(p);if(g&&(!l||u||g.top>c+h)&&(f(),c=g.top,h=g.height/2,u=!1),!l)continue;const m=[];for(let k=p.parentNode;k&&k!==t;k=k.parentNode)m.unshift(k);let y=0;for(;y<d.length&&y<m.length&&d[y].original===m[y];)y++;d.length=y;let T=y===0?l:d[y-1].clone;for(const k of m.slice(y)){const b=k.cloneNode(!1);T.appendChild(b),d.push({original:k,clone:b}),T=b}T.appendChild(p)}return t.replaceChildren(...a),a}function _m(t,e){const n=t.ownerDocument.createElement("span");return n.className=e,n.style.display=t.style.display==="block"?"block":"inline-block",n.style.overflow="clip",n.style.paddingBottom="0.12em",n.style.marginBottom="-0.12em",t.replaceWith(n),n.appendChild(t),n}const Qc={top:0,left:0,start:0,center:.5,centre:.5,middle:.5,bottom:1,right:1,end:1};function sr(t){const e=t.trim().toLowerCase();if(e in Qc)return Qc[e];if(e.endsWith("%")){const n=Number.parseFloat(e.slice(0,-1));return Number.isNaN(n)?void 0:n/100}}function ir(t){if(typeof t=="number")return{elementFraction:0,viewportFraction:0,offsetPx:0,absolutePx:t};let e=0;const s=t.replace(/([+-])=\s*(-?[\d.]+)/g,(r,a,l)=>(e+=(a==="-"?-1:1)*Number.parseFloat(l),"")).trim().split(/\s+/).filter(Boolean);if(s.length===1&&/^-?[\d.]+$/.test(s[0]))return{elementFraction:0,viewportFraction:0,offsetPx:0,absolutePx:Number.parseFloat(s[0])+e};const i=s[0]!==void 0?sr(s[0]):void 0,o=s[1]!==void 0?sr(s[1]):void 0;return{elementFraction:i??0,viewportFraction:o??0,offsetPx:e}}function gn(t,e,n){const s=ir(n),i=s.absolutePx!==void 0?t.top+s.absolutePx:t.top+t.height*s.elementFraction,o=e*s.viewportFraction;return i-o+s.offsetPx}function Cm(t,e,n,s){const i=gn(t,e,n),r=gn(t,e,s)-i;return r<=0?i<=0?1:0:or(-i/r)}function or(t){return t<0?0:t>1?1:t===0?0:t}function th(t,e,n,s){if(n<=0)return e;const i=1-Math.exp(-(s/1e3)/n);return t+(e-t)*i}function rr(t,e,n,s,i){const o=h=>gn({top:t+i(h),bottom:t+i(h)+e,height:e},n,s),r=o(0),a=o(1);if(Math.sign(r)===Math.sign(a)||r===0||a===0)return r===0?0:a===0?1:Math.abs(r)<Math.abs(a)?0:1;let l=0,c=1;for(let h=0;h<40;h++){const u=(l+c)/2;Math.sign(o(u))===Math.sign(r)?l=u:c=u}return(l+c)/2}class eh{timeline;trigger;behaviour;options;observer=null;hasPlayed=!1;running=!1;constructor(e){this.timeline=e.timeline,this.trigger=e.trigger,this.behaviour=e.behaviour??"once",this.options=e}start(){if(!this.running){if(this.running=!0,typeof IntersectionObserver>"u"){this.enter();return}this.observer=new IntersectionObserver(e=>{for(const n of e)n.isIntersecting?this.enter():this.leave()},{threshold:this.options.threshold??.15,rootMargin:this.options.rootMargin,root:this.options.root??null}),this.observer.observe(this.trigger)}}stop(){this.running=!1,this.observer?.disconnect(),this.observer=null}destroy(){this.stop()}reset(){this.hasPlayed=!1,this.timeline.stop()}enter(){this.options.onEnter?.(),!(this.behaviour==="once"&&this.hasPlayed)&&(this.hasPlayed=!0,this.behaviour!=="once"&&this.timeline.seek(0),this.timeline.play())}leave(){this.options.onLeave?.(),this.behaviour==="reset"&&this.timeline.stop()}}function Hm(t){const e=new eh(t);return e.start(),e}class nh{element;spacer;saved;axis;spacing;constructor(e,n={}){this.element=e,this.axis=n.axis??"y",this.spacing=n.spacing??!0;const s=e.ownerDocument;this.spacer=s.createElement("div"),this.spacer.className="pin-spacer",this.saved={position:e.style.position,top:e.style.top,left:e.style.left},this.axis==="x"&&(this.spacer.style.flexShrink="0"),e.replaceWith(this.spacer),this.spacer.appendChild(e)}release(){this.element.style.position=this.saved.position,this.element.style.top=this.saved.top,this.element.style.left=this.saved.left}apply(e,n){const s=Math.max(0,n);this.element.style.position="sticky",this.axis==="x"?(this.spacer.style.width=`${this.element.offsetWidth+s}px`,this.spacer.style.marginRight=this.spacing?"":`-${s}px`,this.element.style.left=`${e}px`):(this.spacer.style.height=`${this.element.offsetHeight+s}px`,this.spacer.style.marginBottom=this.spacing?"":`-${s}px`,this.element.style.top=`${e}px`)}destroy(){this.element.style.position=this.saved.position,this.element.style.top=this.saved.top,this.element.style.left=this.saved.left,this.spacer.parentNode&&this.spacer.replaceWith(this.element)}}const Rm=.15;function sh(t){return typeof t=="object"&&!Array.isArray(t)?t:{snapTo:t}}function ih(t,e,n){const s=Qs(t+e*Rm);if(typeof n=="function")return Qs(n(s));if(typeof n=="number")return n<=0?t:Qs(Math.round(s/n)*n);if(n.length===0)return t;let i=n[0];for(const o of n)Math.abs(o-s)<Math.abs(i-s)&&(i=o);return Qs(i)}function oh(t,e,n){const s=t.duration??{min:.2,max:.8};if(typeof s=="number")return s;const i=Math.min(1,Math.abs(e)/Math.max(1,n));return s.min+(s.max-s.min)*i}class rh{rafId=null;cancelEvents=["wheel","touchstart","pointerdown","keydown"];onInterrupt=()=>this.cancel();write;eventTarget;constructor(e,n){this.write=e,this.eventTarget=n}get active(){return this.rafId!==null}animate(e,n,s,i=Wn,o){if(this.cancel(),typeof requestAnimationFrame>"u"||s<=0){this.write(n),o?.();return}for(const l of this.cancelEvents)this.eventTarget?.addEventListener(l,this.onInterrupt,{passive:!0});let r=null;const a=l=>{r??=l;const c=Math.min(1,(l-r)/(s*1e3));this.write(e+(n-e)*i(c)),c<1?this.rafId=requestAnimationFrame(a):(this.rafId=null,this.detach(),o?.())};this.rafId=requestAnimationFrame(a)}cancel(){this.rafId!==null&&typeof cancelAnimationFrame<"u"&&cancelAnimationFrame(this.rafId),this.rafId=null,this.detach()}detach(){for(const e of this.cancelEvents)this.eventTarget?.removeEventListener(e,this.onInterrupt)}}function Qs(t){return Math.max(0,Math.min(1,t))}class ah{options;scroller;nodes=[];scrollerStart;scrollerEnd;start;end;constructor(e,n,s){this.options=s===!0?{}:s,this.scroller=n;const{startColor:i="#3ecf7a",endColor:o="#ff5a5a",id:r}=this.options,a=r?`${r} `:"",l=(c,h,u)=>{const d=e.createElement("div");return d.textContent=`${a}${c}`,d.setAttribute("aria-hidden","true"),d.className="scroll-marker",Object.assign(d.style,{position:u?"fixed":"absolute",right:`${this.options.indent??0}px`,zIndex:"2147483646",pointerEvents:"none",borderTop:`1px solid ${h}`,color:h,font:`${this.options.fontSize??"11px"} ui-monospace, monospace`,padding:"2px 6px",whiteSpace:"nowrap",background:"rgba(0, 0, 0, 0.35)"}),(n??e.body).appendChild(d),this.nodes.push(d),d};this.scrollerStart=l("scroller-start",i,!n),this.scrollerEnd=l("scroller-end",o,!n),this.start=l("start",i,!1),this.end=l("end",o,!1),n&&getComputedStyle(n).position==="static"&&(n.style.position="relative")}place(e,n){this.start.style.top=`${e.startPage}px`,this.end.style.top=`${e.endPage}px`;const s=this.scroller?n:0;this.scrollerStart.style.top=`${s+e.startViewport}px`,this.scrollerEnd.style.top=`${s+e.endViewport}px`}follow(e,n){this.scroller&&this.place(e,n)}destroy(){for(const e of this.nodes.splice(0))e.remove()}}const Lm=120,pn=[],mn=new Set;let ar=!1;const Fm=()=>{ar||mn.size===0||(ar=!0,queueMicrotask(()=>{ar=!1;for(const t of mn)t.afterRefresh()}))},lh=()=>{for(const t of mn)t.beforeRefresh();for(const t of pn)t.refresh();for(const t of mn)t.afterRefresh()};let yn={width:0,height:0};const ch=()=>{const t=window.innerWidth,e=window.innerHeight,n=t===yn.width&&e!==yn.height,s=Math.abs(e-yn.height)<yn.height*.25,i=typeof navigator<"u"&&(navigator.maxTouchPoints??0)>0;n&&s&&i||(yn={width:t,height:e},lh())};class Un{timeline;options;running=!1;pin=null;startPx=0;endPx=0;targetProgress=0;displayProgress=0;zone="before";measured=!1;lastScroll=null;lastScrollTime=0;velocityPxPerSecond=0;idleTimer=null;lastEmitted=null;rafId=null;lastFrameTime=null;onScroll=()=>this.update();releaseVelocity=0;snapper;snapTimer=null;markers=null;markerGeometry=null;constructor(e){this.timeline=e.timeline,this.options=e,this.snapper=new rh(n=>this.scrollTo(n),typeof window<"u"?window:null)}start(){if(this.running)return;this.running=!0,this.timeline?.pause();const e=this.options.pin===!0?this.options.trigger:this.options.pin||null;e&&!this.options.container&&(this.pin=new nh(e,{axis:this.options.horizontal?"x":"y",spacing:this.options.pinSpacing!==!1})),this.options.markers&&!this.options.horizontal&&typeof document<"u"&&(this.markers=new ah(document,this.options.scroller??null,this.options.markers)),this.scrollTarget()?.addEventListener("scroll",this.onScroll,{passive:!0}),pn.length===0&&typeof window<"u"&&(yn={width:window.innerWidth,height:window.innerHeight},window.addEventListener("resize",ch,{passive:!0})),pn.push(this),this.refresh()}stop(){this.running&&(this.running=!1,this.scrollTarget()?.removeEventListener("scroll",this.onScroll),pn.splice(pn.indexOf(this),1),pn.length===0&&typeof window<"u"&&window.removeEventListener("resize",ch),this.stopSmoothing(),this.idleTimer!==null&&clearTimeout(this.idleTimer),this.idleTimer=null,this.snapTimer!==null&&clearTimeout(this.snapTimer),this.snapTimer=null,this.snapper.cancel())}destroy(){this.stop(),this.pin?.destroy(),this.pin=null,this.markers?.destroy(),this.markers=null}get startOffset(){return this.startPx}get endOffset(){return this.endPx}static refreshAll(){lh()}static onRefresh(e){return mn.add(e),()=>mn.delete(e)}get progress(){return this.targetProgress}get velocity(){return this.velocityPxPerSecond}refresh(){if(!this.running)return;this.measured&&this.options.onRefresh?.();const e=this.scrollPosition();this.pin?.release();const n=this.triggerRect();if(n&&this.options.container)this.measureInContainer(this.options.container);else if(n){const s=this.viewportHeight();if(this.startPx=e+gn(n,s,Vn(this.options.start)??"top bottom"),this.endPx=this.resolveEnd(n,s,e),this.pin){const i=this.relativeRect(this.pin.element.getBoundingClientRect());this.pin.apply(i.top-(this.startPx-e),this.endPx-this.startPx)}this.markerGeometry=this.markers?this.markersFor(s):null}this.markers&&this.markerGeometry&&this.markers.place(this.markerGeometry,e),this.lastScroll=null,this.updateFrom(e,!this.measured),this.measured=!0,Fm()}sample(){this.refresh()}update(e){this.running&&this.updateFrom(e??this.scrollPosition(),!1)}updateFrom(e,n){this.trackVelocity(e),this.markers&&this.markerGeometry&&this.markers.follow(this.markerGeometry,e);const s=this.endPx-this.startPx,i=this.zone;this.targetProgress=s>0?or((e-this.startPx)/s):e>=this.startPx?1:0,this.zone=s>0?e<=this.startPx?"before":e>=this.endPx?"after":"active":e>=this.startPx?"after":"before",this.fireBoundaryCallbacks(i,this.zone),n||this.smoothing()<=0?(this.displayProgress=this.targetProgress,this.applyProgress()):(this.emitUpdate(),this.startSmoothing())}smoothing(){const e=this.options.scrub;return typeof e=="number"?Math.max(0,e):0}resolveEnd(e,n,s){const i=Vn(this.options.end)??"bottom top",o=typeof i=="string"?i.trim().match(/^\+=\s*(-?[\d.]+)\s*(%|px)?$/):null;if(o){const r=Number.parseFloat(o[1]);return this.startPx+(o[2]==="%"?n*r/100:r)}return s+gn(e,n,i)}applyProgress(){const e=this.timeline?.duration??0;this.timeline&&e>0&&this.timeline.seek(this.displayProgress*e),this.emitUpdate()}emitUpdate(){if(!this.options.onUpdate)return;const e=[this.displayProgress,this.velocityPxPerSecond];this.lastEmitted&&this.lastEmitted[0]===e[0]&&this.lastEmitted[1]===e[1]||(this.lastEmitted=e,this.options.onUpdate(e[0],e[1]))}trackVelocity(e){const n=typeof performance<"u"?performance.now():Date.now();this.lastScroll!==null&&n>this.lastScrollTime&&e!==this.lastScroll&&(this.velocityPxPerSecond=(e-this.lastScroll)/(n-this.lastScrollTime)*1e3),(this.lastScroll===null||e!==this.lastScroll)&&(this.lastScroll=e,this.lastScrollTime=n),!(this.velocityPxPerSecond===0||typeof setTimeout>"u")&&(this.idleTimer!==null&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{this.idleTimer=null,this.releaseVelocity=this.velocityPxPerSecond,this.velocityPxPerSecond=0,this.emitUpdate(),this.scheduleSnap()},Lm))}fireBoundaryCallbacks(e,n){if(e===n)return;const{onEnter:s,onLeave:i,onEnterBack:o,onLeaveBack:r}=this.options;e==="before"?(s?.(),n==="after"&&i?.()):e==="after"?(o?.(),n==="before"&&r?.()):n==="after"?i?.():r?.()}scheduleSnap(){const e=this.options.snap;if(e===void 0||this.snapper.active)return;const n=sh(e),s=()=>{this.snapTimer=null;const i=this.endPx-this.startPx,o=this.scrollPosition();if(!this.running||i<=0||o<=this.startPx||o>=this.endPx)return;const r=(o-this.startPx)/i,a=this.startPx+ih(r,this.releaseVelocity/i,n.snapTo)*i;Math.abs(a-o)<1||this.snapper.animate(o,a,oh(n,a-o,this.viewportHeight()),n.ease)};n.delay?this.snapTimer=setTimeout(s,n.delay*1e3):s()}scrollTo(e){const n=this.options.scroller,s=this.options.horizontal?{left:e}:{top:e};n?typeof n.scrollTo=="function"?n.scrollTo({...s,behavior:"instant"}):this.options.horizontal?n.scrollLeft=e:n.scrollTop=e:typeof window<"u"&&window.scrollTo({...s,behavior:"instant"})}measureInContainer(e){const n=this.options.trigger;if(typeof n?.getBoundingClientRect!="function")return;const s=n.getBoundingClientRect(),i=this.options.scroller?.getBoundingClientRect?.().left??0,o=this.options.scroller?this.options.scroller.clientWidth:typeof window<"u"?window.innerWidth:0,r=s.left-i-e.shiftAt(e.progress()),{start:a,end:l}=e.range(),c=f=>a+f*(l-a),h=rr(r,s.width,o,Vn(this.options.start)??"left right",e.shiftAt);this.startPx=c(h);const u=Vn(this.options.end)??"right left",d=typeof u=="string"?u.trim().match(/^\+=\s*(-?[\d.]+)\s*(px)?$/):null;this.endPx=d?this.startPx+Number.parseFloat(d[1]):c(rr(r,s.width,o,u,e.shiftAt)),this.markerGeometry=null}markersFor(e){const n=(o,r)=>{const a=Vn(o)??r;if(typeof a=="number")return 0;if(/^\s*\+=/.test(a))return;const l=ir(a);return e*l.viewportFraction-l.offsetPx},s=n(this.options.start,"top bottom")??0,i=n(this.options.end,"bottom top")??s;return{startViewport:s,endViewport:i,startPage:this.startPx+s,endPage:this.endPx+i}}startSmoothing(){if(this.rafId!==null||typeof requestAnimationFrame>"u")return;const e=n=>{if(this.rafId=null,!this.running)return;const s=this.lastFrameTime===null?16.67:n-this.lastFrameTime;this.lastFrameTime=n,this.displayProgress=th(this.displayProgress,this.targetProgress,this.smoothing(),s);const i=Math.abs(this.targetProgress-this.displayProgress)<1e-4;i&&(this.displayProgress=this.targetProgress),this.applyProgress(),i?this.lastFrameTime=null:this.rafId=requestAnimationFrame(e)};this.rafId=requestAnimationFrame(e)}stopSmoothing(){this.rafId!==null&&typeof cancelAnimationFrame<"u"&&cancelAnimationFrame(this.rafId),this.rafId=null,this.lastFrameTime=null}scrollTarget(){return this.options.scroller??(typeof window<"u"?window:null)}scrollPosition(){const e=this.options.scroller,n=this.options.horizontal;return e?(n?e.scrollLeft:e.scrollTop)??0:typeof window<"u"?(n?window.scrollX:window.scrollY)??0:0}triggerRect(){const e=this.options.trigger;return typeof e?.getBoundingClientRect!="function"?null:this.relativeRect(e.getBoundingClientRect())}relativeRect(e){const n=this.options.horizontal,s=n?e.left??0:e.top,i=n?e.right??0:e.bottom,o=n?e.width??0:e.height,r=this.options.scroller;if(r&&typeof r.getBoundingClientRect=="function"){const a=r.getBoundingClientRect(),l=n?a.left:a.top;return{top:s-l,bottom:i-l,height:o}}return{top:s,bottom:i,height:o}}viewportHeight(){const e=this.options.scroller,n=this.options.horizontal;return e?n?e.clientWidth:e.clientHeight:typeof window<"u"?n?window.innerWidth:window.innerHeight:0}}function Vn(t){return typeof t=="function"?t():t}function Nm(t){const e=new Un(t);return e.start(),e}const lr=new Set,Dm=16,hh=.5,Wm=2;class cr{options;frames;running=!1;reduced=!1;current=0;target=0;written=null;velocityPxPerSecond=0;frameId=null;lastTime=null;journey=null;pausedState=!1;effects=[];onWheel=e=>this.wheel(e);onScroll=()=>this.nativeScroll();onResize=()=>this.refresh();onLoad=()=>this.refresh();stopListening=null;constructor(e={}){this.options=e,this.frames=e.frames??{request:n=>requestAnimationFrame(n),cancel:n=>cancelAnimationFrame(n)}}start(){if(this.running||typeof window>"u")return this;this.running=!0,this.reduced=this.options.reducedMotion??(typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches),this.current=this.target=this.position();const e=this.options.scroller??window;return e.addEventListener("wheel",this.onWheel,{passive:!1}),e.addEventListener("scroll",this.onScroll,{passive:!0}),window.addEventListener("resize",this.onResize,{passive:!0}),window.addEventListener("load",this.onLoad),lr.add(this),this.stopListening=Un.onRefresh({beforeRefresh:()=>this.rest(),afterRefresh:()=>this.refresh()}),this.refresh(),this}static refreshAll(){for(const e of lr)e.refresh()}stop(){if(!this.running)return this;this.running=!1;const e=this.options.scroller??window;return e.removeEventListener("wheel",this.onWheel),e.removeEventListener("scroll",this.onScroll),window.removeEventListener("resize",this.onResize),window.removeEventListener("load",this.onLoad),lr.delete(this),this.stopListening?.(),this.stopListening=null,this.cancelFrame(),this.journey=null,this}destroy(){this.stop();for(const e of this.effects)hr(e.element,e.saved);this.effects=[]}kill(){this.destroy()}get state(){const e=this.limit();return{scroll:this.current,target:this.target,progress:e>0?this.current/e:0,velocity:this.velocityPxPerSecond}}paused(e){return e!==void 0&&(this.pausedState=e,e&&(this.target=this.current,this.journey=null)),this.pausedState}scrollTo(e,n={}){if(!this.running)return;const s=this.clamp(this.resolve(e)+(n.offset??0)),i=Math.abs(s-this.current),o=this.reduced?0:n.duration??Math.min(1.2,Math.max(.4,i/2500));if(o<=0){this.journey=null,this.current=this.target=s,this.write(s),this.applyEffects(0);return}this.target=s,this.journey={from:this.current,to:s,ms:o*1e3,ease:n.ease??Wn,elapsed:0},this.requestFrame()}refresh(){if(!this.running)return;this.rest(),this.effects=[];const e=this.options.effects===!0?"[data-speed], [data-lag]":this.options.effects||"";if(e&&!this.reduced){const n=this.options.scroller??document,s=this.position(),i=this.viewportHeight(),o=this.options.scroller?.getBoundingClientRect().top??0;for(const r of n.querySelectorAll(e)){const a=Number.parseFloat(r.dataset.speed??""),l=Number.parseFloat(r.dataset.lag??""),c=r.getBoundingClientRect(),h=c.top-o+s;this.effects.push({element:r,speed:Number.isFinite(a)?a:void 0,lag:Number.isFinite(l)&&l>0?l:void 0,centre:h+c.height/2-i/2,lagged:s,shift:0,saved:r.style.getPropertyValue("translate")})}}this.current=this.target=this.clamp(this.position()),this.applyEffects(0)}rest(){for(const e of this.effects)hr(e.element,e.saved)}wheel(e){if(this.pausedState||this.reduced||(this.options.smooth??.8)<=0||e.ctrlKey||Math.abs(e.deltaX)>Math.abs(e.deltaY)||this.nestedScrollerTakes(e))return;const n=e.deltaMode===1?Dm:e.deltaMode===2?this.viewportHeight():1,s=e.deltaY*n*(this.options.wheelMultiplier??1),i=this.clamp(this.target+s);i===this.target&&i===this.current||(e.preventDefault(),this.journey=null,this.target=i,this.requestFrame())}nativeScroll(){const e=this.position();this.written!==null&&Math.abs(e-this.written)<=Wm||(this.written=null,this.journey=null,this.cancelFrame(),this.current=this.target=e,this.requestFrame())}nestedScrollerTakes(e){const n=this.options.scroller??document.documentElement;for(let s=e.target;s&&s!==n&&s!==document.body;s=s.parentElement){if(s.hasAttribute?.("data-smooth-ignore"))return!0;const i=getComputedStyle(s);if(!/(auto|scroll)/.test(i.overflowY)||s.scrollHeight<=s.clientHeight)continue;if(e.deltaY<0?s.scrollTop>0:s.scrollTop+s.clientHeight<s.scrollHeight-1)return!0}return!1}requestFrame(){this.frameId!==null||!this.running||(this.frameId=this.frames.request(e=>this.frame(e)))}cancelFrame(){this.frameId!==null&&this.frames.cancel(this.frameId),this.frameId=null,this.lastTime=null}frame(e){this.frameId=null;const n=this.lastTime===null?1e3/60:Math.min(100,e-this.lastTime);this.lastTime=e;const s=this.current;if(this.journey){const o=this.journey;o.elapsed+=n;const r=Math.min(1,o.elapsed/o.ms);this.current=o.from+(o.to-o.from)*o.ease(r),r>=1&&(this.journey=null)}else if(this.current!==this.target){const o=(this.options.smooth??.8)*1e3/3;this.current+=(this.target-this.current)*(1-Math.exp(-n/o)),Math.abs(this.target-this.current)<hh&&(this.current=this.target)}this.current!==s&&this.write(this.current),this.velocityPxPerSecond=n>0?(this.current-s)*1e3/n:0;const i=this.applyEffects(n);this.current!==s&&this.options.onUpdate?.(this.state),this.journey||this.current!==this.target||i?this.requestFrame():(this.lastTime=null,this.velocityPxPerSecond=0)}applyEffects(e){let n=!1;const s=this.current;for(const i of this.effects){let o=0;if(i.speed!==void 0&&(o+=(s-i.centre)*(1-i.speed)),i.lag!==void 0){const r=i.lag*1e3/3;i.lagged=e===0?s:i.lagged+(s-i.lagged)*(1-Math.exp(-e/r)),Math.abs(s-i.lagged)<hh?i.lagged=s:n=!0,o+=s-i.lagged}hr(i.element,o===0?i.saved:`0 ${Bm(o)}px`),i.shift=o}return n}write(e){const n=Math.round(e);this.written=n;const s=this.options.scroller;s?s.scrollTop=n:window.scrollTo({top:n,behavior:"instant"})}position(){const e=this.options.scroller;return e?e.scrollTop:window.scrollY}viewportHeight(){const e=this.options.scroller;return e?e.clientHeight:window.innerHeight}limit(){const e=this.options.scroller??document.documentElement;return Math.max(0,e.scrollHeight-this.viewportHeight())}clamp(e){return Math.max(0,Math.min(this.limit(),e))}resolve(e){if(typeof e=="number")return e;const n=this.options.scroller??document,s=typeof e=="string"?n.querySelector(e):e;if(!s)return this.current;const i=this.options.scroller?.getBoundingClientRect().top??0,o=this.effects.find(r=>r.element===s)?.shift??0;return s.getBoundingClientRect().top-i+this.position()-o}}function hr(t,e){e?t.style.setProperty("translate",e):t.style.removeProperty("translate")}function Bm(t){return Math.round(t*100)/100}function jm(t,e){switch(e){case"play":if(t.progress()>=1)break;t.reversed()?t.reverse():t.play();break;case"reverse":if(t.progress()<=0)break;t.reversed()?t.play():t.reverse();break;case"pause":t.pause();break;case"resume":t.resume();break;case"restart":t.restart();break;case"reset":t.pause(),t.progress(0);break;case"complete":t.pause(),t.progress(1);break}}function ur(t,e,n,s,i=()=>{}){const o=f=>typeof f=="string"?t.query(f)??void 0:f,r=o(e.trigger)??s;if(!r){i(`gsap-compat: scrollTrigger has no trigger element${typeof e.trigger=="string"?` for "${e.trigger}"`:""}`);return}const a=e.scrub===void 0||e.scrub===!1?!1:e.scrub,l=(e.toggleActions??"play none none none").trim().split(/\s+/);let c=0,h;const u=(f,p)=>()=>{p?.(),n&&!a&&jm(n,l[f]??"none"),e.once&&f===0&&queueMicrotask(()=>h.destroy())},d=e.containerAnimation?Km(t,e.containerAnimation,r,i):void 0;return h=new Un({trigger:r,start:e.start,end:e.end,scrub:a===!1?void 0:a,pin:e.pin===!0?!0:o(e.pin),scroller:o(e.scroller),horizontal:e.horizontal,pinSpacing:e.pinSpacing,onRefresh:e.invalidateOnRefresh&&n?.invalidate?()=>n.invalidate():void 0,snap:e.snap===void 0?void 0:qm(e.snap,n),markers:e.markers,container:d,onUpdate:(f,p)=>{if(n&&a!==!1&&n.progress(f),e.onUpdate){const g=f<c||p<0?-1:1;e.onUpdate({progress:f,velocity:p,direction:g})}c=f},onEnter:u(0,e.onEnter),onLeave:u(1,e.onLeave),onEnterBack:u(2,e.onEnterBack),onLeaveBack:u(3,e.onLeaveBack)}),n&&a===!1&&n.progress(0),h.start(),t.own(h)}function qm(t,e){const n=i=>i==="labels"?o=>Ym(o,e?.labelProgresses?.()??[]):i;if(typeof t!="object"||Array.isArray(t))return n(t);const s=t.ease?zn(t.ease):void 0;return{snapTo:n(t.snapTo),duration:t.duration,delay:t.delay,ease:s?s.fn??Ct(s.easing):void 0}}function Ym(t,e){return e.reduce((n,s)=>Math.abs(s-t)<Math.abs(n-t)?s:n,e[0]??t)}function Km(t,e,n,s){const i=()=>e.timeline.getTracks({property:"x"}).map(o=>o.target).filter(o=>{const r=t.elementFor(o);return!!r&&r!==n&&r.contains(n)});return i().length===0&&s("gsap-compat: containerAnimation does not move an ancestor of the trigger along x"),{range:()=>{const o=e.scrollTrigger;return o||s("gsap-compat: containerAnimation needs its own scrollTrigger (created before this one)"),{start:o?.startOffset??0,end:o?.endOffset??0}},progress:()=>e.progress(),shiftAt:o=>{const r=e.timeline.getStateAtTime(o*e.timeline.duration);let a=0;for(const l of i()){const c=r.values.get(l)?.get("x");typeof c=="number"&&(a+=c)}return a}}}class uh{conditions={};scope;host;items=[];snapshots=new Map;constructor(e,n){this.host=e,this.scope=n}add(e){const n=this.host.collector;this.host.setCollector(this);try{const s=e();return typeof s=="function"&&this.items.push({revert:s}),s}finally{this.host.setCollector(n)}}track(e){this.items.push(e)}touch(e,n){this.snapshots.has(e)||this.snapshots.set(e,{name:n,style:e.getAttribute("style"),d:e.getAttribute("d")})}revert(){for(const e of this.items.splice(0).reverse())e.revert?e.revert():e.kill?e.kill():e.destroy?.();for(const[e,{name:n,style:s,d:i}]of this.snapshots)s===null?e.removeAttribute("style"):e.setAttribute("style",s),i!==null&&e.setAttribute("d",i),this.host.forget(n);this.snapshots.clear()}kill(){this.revert()}}class zm{host;scope;entries=[];listeners=[];scheduled=!1;constructor(e,n){this.host=e,this.scope=n}add(e,n){const s={conditions:e,setup:n,queries:new Map},i=typeof e=="string"?{matches:e}:e;if(typeof window<"u"&&typeof window.matchMedia=="function")for(const[o,r]of Object.entries(i)){const a=window.matchMedia(r);s.queries.set(o,a);const l=()=>this.scheduleUpdate();a.addEventListener("change",l),this.listeners.push(()=>a.removeEventListener("change",l))}return this.entries.push(s),this.update(s),this}revert(){for(const e of this.listeners.splice(0))e();for(const e of this.entries.splice(0))e.context?.revert()}kill(){this.revert()}scheduleUpdate(){this.scheduled||(this.scheduled=!0,queueMicrotask(()=>{this.scheduled=!1;for(const e of this.entries)this.update(e)}))}update(e){const n={};for(const[r,a]of e.queries)n[r]=a.matches;const s=Object.values(n).some(Boolean),i=s?JSON.stringify(n):void 0;if(i===e.key||(e.context?.revert(),e.context=void 0,e.key=i,!s))return;const o=new uh(this.host,this.scope);o.conditions=n,o.add(()=>e.setup(o)),e.context=o}}class Xm{frames;canvas;context;options;images;ready;current=0;drawn=-1;loadedCount=0;inFlight=0;destroyed=!1;onResize=()=>this.resize();constructor(e,n){this.canvas=e,this.context=e.getContext("2d"),this.options=n,this.frames=Math.max(1,Math.floor(n.frames)),this.images=new Array(this.frames),this.ready=new Array(this.frames).fill(!1),typeof window<"u"&&window.addEventListener("resize",this.onResize,{passive:!0}),this.resize(),this.pump()}get frame(){return this.current}set frame(e){this.current=Math.max(0,Math.min(this.frames-1,e)),this.draw()}get loaded(){return this.loadedCount}destroy(){this.destroyed=!0,typeof window<"u"&&window.removeEventListener("resize",this.onResize);for(const e of this.images)e&&(e.src="")}resize(){const e=typeof window<"u"?Math.min(window.devicePixelRatio||1,2):1,n=Math.round(this.canvas.clientWidth*e),s=Math.round(this.canvas.clientHeight*e);n>0&&s>0&&(this.canvas.width!==n||this.canvas.height!==s)&&(this.canvas.width=n,this.canvas.height=s),this.drawn=-1,this.draw()}draw(){const e=Math.round(this.current),n=this.nearestReady(e);if(n===-1||n===this.drawn||!this.context)return;const s=this.images[n],{width:i,height:o}=this.canvas,r=(this.options.fit??"cover")==="cover"?Math.max(i/s.naturalWidth,o/s.naturalHeight):Math.min(i/s.naturalWidth,o/s.naturalHeight),a=s.naturalWidth*r,l=s.naturalHeight*r;this.context.clearRect(0,0,i,o),this.context.drawImage(s,(i-a)/2,(o-l)/2,a,l),this.drawn=n,this.pump()}nearestReady(e){for(let n=0;n<this.frames;n++){if(e-n>=0&&this.ready[e-n])return e-n;if(e+n<this.frames&&this.ready[e+n])return e+n}return-1}pump(){const e=this.options.concurrency??6,n=Math.round(this.current);for(let s=0;s<this.frames&&this.inFlight<e;s++)for(const i of s===0?[n]:[n+s,n-s])i<0||i>=this.frames||this.images[i]||this.inFlight>=e||this.load(i)}load(e){const n=new Image;n.decoding="async",this.images[e]=n,this.inFlight++;const s=i=>{if(!this.destroyed){if(this.inFlight--,i){this.ready[e]=!0,this.loadedCount++,this.options.onProgress?.(this.loadedCount,this.frames);const o=Math.round(this.current);(Math.abs(e-o)<Math.abs(this.drawn-o)||this.drawn===-1)&&(this.drawn=-1,this.draw())}this.pump()}};n.onload=()=>s(!0),n.onerror=()=>s(!1),n.src=this.options.url(e)}}const Gm={opacity:0,y:-16},Um={opacity:0,y:16};async function Vm(t,e,n,s){const i=e.collector?.scope??e.root,o=i.ownerDocument??i,r=()=>s.shared?[...i.querySelectorAll(s.shared)]:[];if(s.native&&typeof o.startViewTransition=="function")return Jm(o,s,r);const a=s.duration??.35,l=s.ease??"power2.inOut",c=m=>new Promise(y=>{m(y)||y()}),h=r(),u=h.length?tr(e,h):void 0,d=s.from!==void 0?dh(e,s.from,s.shared):[];if(d.length&&s.leave!==!1){const m=s.leave??Gm;await c(y=>t.to(d,{...m,duration:a,ease:l,onComplete:y}))}await s.update();const f=[],p=typeof s.to=="function"?s.to():s.to,g=p!==void 0?dh(e,p,s.shared):[];if(g.length&&s.enter!==!1){const m=s.enter??Um;f.push(c(y=>t.fromTo(g,m,{...Zc(m),duration:a,ease:l,onComplete:y})))}if(u){const m=r().filter(y=>!h.includes(y));m.length&&f.push(c(y=>nr(e,n,u,{targets:m,duration:a*1.4,ease:l,enter:!1,onComplete:y})))}await Promise.all(f)}function dh(t,e,n){const s=t.resolveTargets(e).map(i=>t.elementFor(i)).filter(i=>!!i);return n?s.flatMap(i=>!i.querySelector(n)&&!i.matches(n)?[i]:[...i.children].filter(o=>!o.matches(n)&&!o.querySelector(n))):s}async function Jm(t,e,n){const s=(a,l)=>{const c=a.dataset?.flipId;c&&a.style.setProperty("view-transition-name",l?`tf-${c.replace(/[^\w-]/g,"-")}`:"")},i=n();i.forEach(a=>s(a,!0));let o=[];await t.startViewTransition(async()=>{i.forEach(a=>s(a,!1)),await e.update(),o=n(),o.forEach(a=>s(a,!0))}).finished,o.forEach(a=>s(a,!1))}const fh={create:(t,e)=>Ko(t,yc(e))},gh={create:(t,e)=>Ko(t,{fn:bc(e)})},ph={create:(t,e)=>Ko(t,{fn:wc(e)})},Zm=new Set(["keyframes","duration","delay","ease","easeEach","stagger","repeat","repeatDelay","yoyo","repeatRefresh","paused","id","onStart","onUpdate","onComplete","onRepeat","onReverseComplete","scrollTrigger"]),mh=.5,Qm="power1.inOut";function t1(t){return t.keyframes!==void 0&&t.keyframes!==null}function e1(t){const e=t.keyframes,n={};for(const[c,h]of Object.entries(t))Zm.has(c)||(n[c]=h);if(Array.isArray(e))return e.map(c=>({...n,...c,duration:c.duration??t.duration??mh}));const s=Object.entries(e),i=t.duration??mh,o=e.easeEach??t.easeEach??Qm;if(s.length>0&&s.every(([c])=>/^\s*-?\d+(\.\d+)?\s*%\s*$/.test(c)||c==="easeEach")){const c=s.filter(([d])=>d!=="easeEach").map(([d,f])=>({at:Number.parseFloat(d)/100,step:f})).sort((d,f)=>d.at-f.at),h=[];let u=0;for(const{at:d,step:f}of c){const p=Math.max(0,d-u);h.push({...n,ease:o,...f,duration:p*i}),u=d}return h}const r=s.filter(([c,h])=>c!=="easeEach"&&Array.isArray(h)),a=Math.max(0,...r.map(([,c])=>c.length)),l=[];for(let c=0;c<a;c++){const h={...n,ease:o,duration:i/a};for(const[u,d]of r)c<d.length&&(h[u]=d[c]);l.push(h)}return l}function yh(t,e,n,s={}){const i=e.collector?.scope??e.root,o=typeof s.scroller=="string"?i.querySelector(s.scroller):s.scroller??null,r={x:o?o.scrollLeft:window.scrollX,y:o?o.scrollTop:window.scrollY},a={x:o?o.scrollWidth-o.clientWidth:document.documentElement.scrollWidth-window.innerWidth,y:o?o.scrollHeight-o.clientHeight:document.documentElement.scrollHeight-window.innerHeight},l=(T,k)=>{if(k===void 0)return r[T];if(typeof k=="number")return k;if(k==="max")return a[T];const b=typeof k=="string"?i.querySelector(k):k;if(!b)return r[T];const A=b.getBoundingClientRect(),M=o?.getBoundingClientRect(),E=(T==="x"?s.offsetX:s.offsetY)??s.offset??0;return T==="x"?A.left-(M?.left??0)+r.x-E:A.top-(M?.top??0)+r.y-E},c=typeof n=="object"&&n!==null&&!("nodeType"in n)?{x:l("x",n.x),y:l("y",n.y)}:{x:r.x,y:l("y",n)},h={x:Math.max(0,Math.min(a.x,c.x)),y:Math.max(0,Math.min(a.y,c.y))},u={...r},d=()=>{o?(o.scrollLeft=u.x,o.scrollTop=u.y):window.scrollTo({left:u.x,top:u.y,behavior:"instant"})},f=["wheel","touchstart","keydown"],p=o??window,g=()=>{y.kill(),m()},m=()=>{for(const T of f)p.removeEventListener(T,g)},y=t.to(u,{x:h.x,y:h.y,duration:s.duration??1,ease:s.ease??"power2.inOut",onStart:s.onStart,onUpdate:()=>{d(),s.onUpdate?.()},onComplete:()=>{m(),s.onComplete?.()}});if(s.autoKill!==!1)for(const T of f)p.addEventListener(T,g,{passive:!0});return y}function n1(t,e,n){const s=t.collector?.scope??t.root,i=typeof e=="string"?[...s.querySelectorAll(e)]:"nodeType"in e?[e]:Array.from(e),{interval:o=.1,batchMax:r,onEnter:a,onLeave:l,onEnterBack:c,onLeaveBack:h,...u}=n,d={onEnter:a,onLeave:l,onEnterBack:c,onLeaveBack:h},f={onEnter:[],onLeave:[],onEnterBack:[],onLeaveBack:[]},p={},g=y=>{p[y]!==void 0&&clearTimeout(p[y]),p[y]=void 0;const T=f[y].splice(0);T.length>0&&d[y]?.(T)},m=(y,T)=>{if(d[y]){if(f[y].push(T),r!==void 0&&f[y].length>=r)return g(y);p[y]===void 0&&(p[y]=setTimeout(()=>g(y),o*1e3))}};return i.map(y=>ur(t,{...u,trigger:y,onEnter:()=>m("onEnter",y),onLeave:()=>m("onLeave",y),onEnterBack:()=>m("onEnterBack",y),onLeaveBack:()=>m("onLeaveBack",y)})).filter(y=>y!==void 0)}class ie{compat;stage;options;autoplayPending;started=!1;killed=!1;recipe=[];firstElement;scrollDriver;events=[];ranges=[];playhead={time:0,iteration:0,direction:"forward",fresh:!0};waitingToWrap=!1;finishedThisFrame=!1;backwards=!1;constructor(e,n={}){this.stage=e;const s={...n,onWarning:n.onWarning??e.onWarning};if(this.options=s,this.compat=new je({...s,startValue:(i,o)=>{const r=e.objectFor(i);if(r)return o1(r[o]);const a=e.appliedValue(i,o);if(a!==void 0)return a;if(o==="d")return jc(e.elementFor(i))??void 0;if(o==="text")return e.elementFor(i)?.textContent??void 0;if(o==="strokeDasharray"||o==="strokeDashoffset"){const l=Mh(e.elementFor(i));if(l!==void 0)return o==="strokeDasharray"?[l,l]:0}},startVelocity:(i,o)=>e.velocityOf(i,o),layoutColumns:i=>vh(i.map(o=>e.elementFor(o))),random:()=>e.utils.random(0,1)}),this.compat.timeline.onComplete=()=>{this.finishedThisFrame=!0},e.collector?.track(this),e.liveTimelines.add(this),this.autoplayPending=!s.paused&&!s.scrollTrigger,s.scrollTrigger){const i=s.scrollTrigger;queueMicrotask(()=>{this.killed||(this.scrollDriver=ur(e,i,this,this.firstElement,o=>s.onWarning?.(o)))})}this.autoplayPending&&queueMicrotask(()=>{this.autoplayPending&&this.play()})}get timeline(){return this.compat.timeline}get scrollTrigger(){return this.scrollDriver}to(e,n,s){return t1(n)?this.record(()=>this.keyframed(e,n,s)):this.record(()=>this.tween(e,[n],s,([i],o,r)=>this.compat.to(o,i,r)))}from(e,n,s){return this.record(()=>this.tween(e,[n],s,([i],o,r)=>this.compat.from(o,i,r)))}fromTo(e,n,s,i){return this.record(()=>this.tween(e,[n,s],i,([o,r],a,l)=>this.compat.fromTo(a,o,r,l)))}set(e,n,s){return this.record(()=>this.tween(e,[n],s,([i],o,r)=>this.compat.set(o,i,r)))}addLabel(e,n){return this.record(()=>this.compat.addLabel(e,n))}add(e,n){return this.record(()=>{e.autoplayPending=!1,e.timeline.stop(),e.stage.deactivate(e.timeline),this.compat.add(e.compat,n)})}invalidate(){const e=this.compat.progress();this.compat.progress(0),this.stage.render(this.timeline),this.compat.reset(),this.events=[],this.ranges=[];for(const n of this.recipe)n();return this.syncDuration(),this.compat.progress(e),this.stage.render(this.timeline),this}call(e,n=[],s){return this.record(()=>{const i=this.compat.addEvent(s);this.events.push({time:i,run:()=>e(...n)})})}addPause(e,n,s=[]){return this.record(()=>{const i=this.compat.addEvent(e);this.events.push({time:i,pause:!0,run:()=>n?.(...s)})})}tweenTo(e,n={}){return this.tweenFromTo(this.timeline.currentTime/1e3,e,n)}tweenFromTo(e,n,s={}){this.pause(),this.seek(e);const i=this.timeline.currentTime,o=Math.max(0,Math.min(this.timeline.duration,this.compat.timeOf(n))),r={time:i},a=s.duration??Math.abs(o-i)/1e3/(this.timeScale()||1),l=new ie(this.stage,{onStart:s.onStart,onComplete:s.onComplete});return l.to(r,{time:o,duration:a,ease:s.ease??"none",onUpdate:()=>{this.moveTo(r.time),s.onUpdate?.()}}),l}play(){this.autoplayPending=!1,this.started||(this.started=!0,this.options.onStart?.());const e=this.timeline.playbackState==="playing",n=this.timeline.playbackState==="paused";if(this.timeline.play(),!e){const s=this.timeline,i=s.direction==="forward"?s.currentTime===0:s.currentTime===s.duration;this.playhead={...this.readPlayhead(),fresh:i&&!n},this.waitingToWrap=!1}return this.stage.liveTimelines.add(this),this.stage.render(this.timeline),this.stage.activate(this.timeline,{onUpdate:()=>this.afterFrame()}),this}pause(){return this.autoplayPending=!1,this.timeline.pause(),this.stage.deactivate(this.timeline),this}resume(){return this.play()}restart(){return this.timeline.stop(),this.backwards=!1,this.play()}reverse(){this.backwards=!this.backwards;const e=this.timeline.playbackState==="idle"&&this.timeline.direction==="forward";return this.timeline.reverse(),e&&this.timeline.currentTime===0&&this.timeline.seek(this.timeline.duration),this.play()}labelProgresses(){const e=this.timeline.duration;return e>0?this.compat.labelTimes().map(n=>n/e):[]}reversed(){return this.timeline.direction==="reverse"}seek(e){return this.autoplayPending=!1,this.compat.seek(e),this.stage.render(this.timeline),this.playhead=this.readPlayhead(),this.waitingToWrap=!1,this.options.onUpdate?.(),this}progress(e){return e===void 0?this.compat.progress():(this.autoplayPending=!1,this.moveTo(Math.max(0,Math.min(1,e))*this.timeline.duration),this.compat.progress())}timeScale(e){return this.compat.timeScale(e)}duration(){return this.compat.duration()}isActive(){return this.timeline.playbackState==="playing"}kill(){return this.killed=!0,this.stage.liveTimelines.delete(this),this.scrollDriver?.destroy(),this.scrollDriver=void 0,this.autoplayPending=!1,this.timeline.stop(),this.stage.deactivate(this.timeline),this.compat.kill(),this}toDefinition(){return this.compat.toDefinition()}killTweensOf(e,n){for(const s of e)for(const i of n??[void 0])this.timeline.removeTracks({target:s,...i!==void 0&&{property:i}});this.timeline.tracks.length===0&&this.events.length===0&&this.kill()}record(e){return this.recipe.push(e),e(),this.syncDuration(),this}syncDuration(){if(this.events.length===0)return;this.timeline.setDuration(void 0);const e=Math.max(...this.events.map(n=>n.time));e>this.timeline.duration&&this.timeline.setDuration(e)}readPlayhead(){const e=this.timeline;return{time:e.currentTime,iteration:e.loopIteration,direction:e.direction}}moveTo(e){const n=this.playhead;this.timeline.seek(e),this.stage.render(this.timeline);const s={time:this.timeline.currentTime,iteration:this.timeline.loopIteration,direction:e>=n.time?"forward":"reverse"},i={...n,iteration:s.iteration,direction:s.direction};this.playhead={...this.readPlayhead()},this.waitingToWrap=!1,this.runCrossings(i,s,!1),this.options.onUpdate?.()}refreshForRepeat(){const e=this.timeline.currentTime;this.compat.reset(),this.events=[],this.ranges=[];for(const n of this.recipe)n();this.syncDuration(),this.timeline.seek(Math.min(e,this.timeline.duration))}afterFrame(){const e=this.timeline,n=e.repeatDelayRemaining>0;if(this.waitingToWrap&&n){this.options.onUpdate?.();return}this.waitingToWrap=!1;const s=this.playhead,i=this.readPlayhead();this.playhead=i;const o=this.options.yoyo===!0;n&&!o&&i.iteration>s.iteration&&(this.playhead={time:0,iteration:i.iteration,direction:"forward",fresh:!0},this.waitingToWrap=!0);const r=this.runCrossings(s,i,n);if(this.options.onUpdate?.(),this.finishedThisFrame&&!r){this.finishedThisFrame=!1;const a=e.currentTime===0&&e.direction==="reverse";!this.scrollDriver&&!o&&this.stage.liveTimelines.delete(this),a&&this.backwards?this.options.onReverseComplete?.():this.options.onComplete?.()}this.finishedThisFrame=!1}runCrossings(e,n,s){if(this.events.length===0&&this.ranges.length===0&&!this.options.onRepeat&&!this.options.repeatRefresh)return!1;const i=this.events,{crossings:o,passes:r}=Fo(i.map(a=>a.time),e,n,{duration:this.timeline.duration,alternate:this.options.yoyo===!0,holding:s});for(const a of o){if(this.killed)return!0;if(a.kind==="repeat"){this.options.repeatRefresh&&this.refreshForRepeat(),this.options.onRepeat?.();continue}const l=i[a.index];if(!(l.direction&&l.direction!==a.direction)){if(l.pause)return this.timeline.seek(l.time),this.stage.render(this.timeline),this.pause(),this.playhead=this.readPlayhead(),this.waitingToWrap=!1,l.run(),!0;l.run()}}for(const a of this.ranges)r.some(([c,h])=>c!==h&&Math.max(c,h)>=a.start&&Math.min(c,h)<=a.end)&&a.run();return!1}tween(e,n,s,i){const o=this.resolve(e);if(!o)return;const{onStart:r,onUpdate:a,onComplete:l}=n[n.length-1];if(r||a||l){let c=1/0,h=-1/0;const u=(d,f,p)=>{i(d,f,p),c=Math.min(c,this.compat.lastStart),h=Math.max(h,this.compat.lastEnd)};if(this.buildTween(o,n,s,u),c===1/0)return;r&&this.events.push({time:c,direction:"forward",run:r}),a&&this.ranges.push({start:c,end:h,run:a}),l&&this.events.push({time:h,direction:"forward",run:l});return}this.buildTween(o,n,s,i)}keyframed(e,n,s){const i=this.resolve(e);if(!i)return;const o=e1(n);if(o.length===0)return;const r=i.length>1?Go(n.stagger,this.staggerContext(i)):void 0,a=i.map(m=>this.targetFor(m)).filter(m=>m!==void 0),l=r?a.map(m=>[m]):[a],c=r?_s(i.length,r).map(m=>m/1e3):[0],h=this.compat.timeOf(s)/1e3+Js(n.delay,0)/1e3;let u=1/0,d=-1/0;if(l.forEach((m,y)=>{o.forEach((T,k)=>{const b=k===0?h+c[y]:">";this.tween(m,[T],b,([A],M,E)=>this.compat.to(M,A,E)),u=Math.min(u,this.compat.lastStart),d=Math.max(d,this.compat.lastEnd)})}),u===1/0)return;const{onStart:f,onUpdate:p,onComplete:g}=n;f&&this.events.push({time:u,direction:"forward",run:f}),p&&this.ranges.push({start:u,end:d,run:p}),g&&this.events.push({time:d,direction:"forward",run:g})}staggerContext(e){return{count:e.length,columnsFromLayout:()=>vh(e.map(n=>this.stage.elementFor(n))),random:()=>this.stage.utils.random(0,1)}}buildTween(e,n,s,i){const o=e.map(d=>this.targetFor(d));if(!(e.length>1&&(n.some(i1)||e.some(d=>this.stage.objectFor(d)!==void 0)))){const d=this.targetFor(e[0]);i(n.map(f=>this.prepare(kh(f,0,d,this.stage.utils,o),e)),e,s);return}const a=n.length-1,{stagger:l,...c}=n[a],h=Go(l,this.staggerContext(e)),u=h?_s(e.length,h).map(d=>d/1e3):e.map(()=>0);e.forEach((d,f)=>{const p=f===0?Js(c.delay,0)/1e3+u[0]:0,g=f===0?0:u[f]-u[f-1],m=f===0?s:`<${g<0?"-":"+"}${Math.abs(g).toFixed(6)}`,T=n.map((k,b)=>b===a?{...c,delay:p}:k).map(k=>this.prepare(kh(k,f,this.targetFor(d),this.stage.utils,o),[d]));i(T,[d],m)})}targetFor(e){return this.stage.elementFor(e)??this.stage.objectFor(e)}prepare(e,n){const s=r=>this.options.onWarning?.(r),i=r=>this.stage.query(r);let o=e;if(e.motionPath!==void 0){const r=mm(e.motionPath,{query:i,targets:n.map(a=>this.stage.elementFor(a)).filter(a=>!!a),warn:s});o={...o,motionPath:r}}if(e.morphSVG!==void 0){const r=ym(e.morphSVG,i,s),{morphSVG:a,...l}=o;o=r?{...o,morphSVG:r}:l}if(e.drawSVG!==void 0){const r=Mh(this.stage.elementFor(n[0]));if(r===void 0){s("gsap-compat: drawSVG needs an SVG shape with a stroke (path, line, circle…)");const{drawSVG:a,...l}=o;o=l}else o=qp(o,r)}return o}resolve(e){const n=this.stage.resolveTargets(e);if(n.length===0){this.options.onWarning?.(`gsap-compat: no elements found for target ${r1(e)}`);return}return this.firstElement??=n.map(s=>this.stage.elementFor(s)).find(s=>s!==void 0),n}}function bh(t=new Nc){const e=o=>{const{config:r}=Vs(o);return new ie(t,{repeat:r.repeat,yoyo:r.yoyo,repeatDelay:r.repeatDelay,paused:r.paused,onStart:r.onStart,onUpdate:r.onUpdate,onComplete:r.onComplete,onRepeat:r.onRepeat,onReverseComplete:r.onReverseComplete,repeatRefresh:r.repeatRefresh,scrollTrigger:r.scrollTrigger})},n=o=>{const{onStart:r,onUpdate:a,onComplete:l,onRepeat:c,onReverseComplete:h,repeatRefresh:u,...d}=o;return d},s=o=>(o&&t.collector?.track(o),o),i={stage:t,ticker:t.ticker,utils:t.utils,getProperty:(o,r)=>{const[a]=t.resolveTargets(o);if(a===void 0)return;const l=t.objectFor(a);return l?l[r]:t.appliedValue(a,r)??Cc(r)},scrollTrigger:o=>s(ur(t,o)),scrollBatch:(o,r)=>n1(t,o,r).map(a=>s(a)),scrollTo:(o,r)=>yh(i,t,o,r),refreshScroll:()=>{Un.refreshAll(),cr.refreshAll()},smoothScroll:(o={})=>{const r=typeof o.scroller=="string"?(t.collector?.scope??t.root).querySelector(o.scroller):o.scroller;return s(new cr({...o,scroller:r}).start())},context:(o,r)=>{const a=new uh(t,r);return o&&a.add(()=>o(a)),a},matchMedia:o=>new zm(t,o),customEase:fh.create,customBounce:gh.create,customWiggle:ph.create,pageTransition:o=>Vm(i,t,r=>new ie(t,r),o),imageSequence:(o,r)=>{const a=typeof o=="string"?(t.collector?.scope??t.root).querySelector(o):o;if(!(a instanceof HTMLCanvasElement))throw new Error(`gsap-compat: imageSequence needs a <canvas>, got ${String(o)}`);return s(new Xm(a,r))},quickTo:(o,r,a={})=>{const l=new ie(t,{paused:!0}),[c]=t.resolveTargets(o);return Object.assign(u=>{if(!c)return;const d=a.spring!==void 0?t.velocityOf(c,r)??0:0;l.compat.reset(),l.compat.to(c,{[r]:u,duration:a.duration??.4,ease:a.ease??"power3.out",...a.spring!==void 0&&{spring:s1(a.spring,r,d)}}),l.timeline.stop(),l.timeline.play(),t.activate(l.timeline)},{tween:l,kill:()=>l.kill()})},timeline:o=>new ie(t,o),to:(o,r)=>{if(r.scrollTo!==void 0){const{scrollTo:a,...l}=r,c=typeof a=="object"&&a!==null&&!("nodeType"in a)?a:{},h=typeof o!="string"&&o!==window&&o.nodeType===1;return yh(i,t,a,{...l,offsetX:c.offsetX,offsetY:c.offsetY,scroller:h?o:void 0})}return e(r).to(o,n(r))},from:(o,r)=>e(r).from(o,n(r)),fromTo:(o,r,a)=>e(a).fromTo(o,r,n(a)),set:(o,r)=>e(r).set(o,n(r)),delayedCall:(o,r,a)=>new ie(t).call(r,a,o),killTweensOf:(o,r)=>{const a=t.resolveTargets(o),l=typeof r=="string"?r.split(",").map(c=>c.trim()).filter(Boolean):r;for(const c of[...t.liveTimelines])c.killTweensOf(a,l)},convertToPath:o=>wm(o,t.root),splitText:(o,r)=>{const a=t.collector?.scope??t.root,l=typeof o=="string"?Array.from(a.querySelectorAll(o)):"nodeType"in o?[o]:Array.from(o);return s(xm(l,r))},draggable:(o,r)=>s(Sm(i,t,o,r)),getFlipState:o=>tr(t,o),flipFrom:(o,r)=>nr(t,a=>new ie(t,a),o,r),flip:(o,r,a)=>{const l=tr(t,o);return r(),nr(t,c=>new ie(t,c),l,{targets:o,...a})}};return i}const Wt=bh();function s1(t,e,n){return t===!0?{velocity:{[e]:n}}:typeof t=="string"?{preset:t,velocity:{[e]:n}}:{...t,velocity:{[e]:n}}}function i1(t){return t.morphSVG!==void 0||t.drawSVG!==void 0||t.text!==void 0||t.scrambleText!==void 0||wh(t)}function wh(t){return Object.entries(t).some(([e,n])=>(typeof n=="function"||Oc(n))&&!Xo.has(e))}function kh(t,e,n,s,i){if(!wh(t))return t;const o={};for(const[r,a]of Object.entries(t))Xo.has(r)?o[r]=a:typeof a=="function"?o[r]=a(e,n,i):Oc(a)?o[r]=s.resolveRandomString(a):o[r]=a;return o}function vh(t){const e=t.map(s=>s?.getBoundingClientRect().top);if(e[0]===void 0)return t.length;let n=0;for(const s of e){if(s===void 0||Math.abs(s-e[0])>1)break;n++}return Math.max(1,n)}function Mh(t){const e=t;if(typeof e?.getTotalLength=="function")return e.getTotalLength()}function o1(t){if(typeof t=="number"||typeof t=="string"||Array.isArray(t)&&t.every(e=>typeof e=="number"))return t}function r1(t){return typeof t=="string"?`"${t}"`:String(t)}class dr{media;offset;driftTolerance;constructor(e,n={}){this.media=e,this.offset=n.offset??0,this.driftTolerance=Math.max(0,n.driftTolerance??.15)}targetTime(e){return Math.max(0,e/1e3+this.offset)}update(e,n){const s=this.targetTime(e);n?(this.media.paused&&this.safePlay(),Math.abs(this.media.currentTime-s)>this.driftTolerance&&(this.media.currentTime=s)):(this.media.paused||this.media.pause(),this.media.currentTime!==s&&(this.media.currentTime=s))}seek(e){this.media.currentTime=this.targetTime(e)}setRate(e){this.media.playbackRate=e}dispose(){this.media.paused||this.media.pause()}safePlay(){const e=this.media.play();e&&typeof e.catch=="function"&&e.catch(()=>{})}}function Sh(t,e,n,s,i){const o=n-i;if(o<0){e.paused||e.pause(),e.currentTime=0;return}t.update(o,s)}class ti{container;timeline=null;adapter;animationFrameId;lastTime;options;targets={};isDestroyed=!1;mediaSync;mediaTargets=[];symbolInstances=[];scenarioList=[];scenarioId;authored=new Map;markerList=[];listeners=new Set;playhead={time:0,iteration:0,direction:"forward"};stepping=!1;lastMarkerId=null;reducedQuery;onReducedChange=()=>this.applyReducedMotion();visibilityObserver;onScreen=!0;pausedByVisibility=!1;autoplayWhenSeen=!1;onDocumentVisibility=()=>this.updateVisibility();constructor(e,n={}){if(typeof e=="string"){const s=document.querySelector(e);if(!s)throw new Error(`Container not found: ${e}`);this.container=s}else this.container=e;this.options=n,this.adapter=new qe}async load(e){this.scenarioList=[],this.scenarioId=void 0,await this.loadSource(e)}async loadSource(e){let n;if(typeof e=="string"){const s=await fetch(e);if(!s.ok)throw new Error(`Failed to load animation: ${s.statusText}`);n=await s.json()}else n=e;this.useDefinition(n),this.showInitialFrame(),this.watchReducedMotion(),this.watchVisibility(),this.options.autoplay&&!this.reducedMotion&&(this.options.playWhenVisible&&!this.onScreen?this.autoplayWhenSeen=!0:this.play())}useDefinition(e){const n={...e.config};this.options.speed!==void 0&&(n.speed=this.options.speed),this.options.loop!==void 0&&(n.loop=this.options.loop),this.options.alternate!==void 0&&(n.alternate=this.options.alternate),this.timeline=hn({...e,config:n}),this.markerList=this.timeline.markers,this.lastMarkerId=null,this.options.onComplete&&(this.timeline.onComplete=this.options.onComplete),this.options.onUpdate&&(this.timeline.onUpdate=this.options.onUpdate),this.autoRegisterTargets(),this.setupSymbolInstances(),this.scanMedia()}async loadScenarios(e,n={}){if(e.length===0)throw new Error("tinyfly: loadScenarios needs at least one scenario");const s=new Set;for(const o of e){if(s.has(o.id))throw new Error(`tinyfly: scenario id "${o.id}" is used more than once`);s.add(o.id)}const i=n.initial===void 0?e[0]:e.find(o=>o.id===n.initial);if(!i)throw new Error(`tinyfly: there is no scenario "${n.initial}"`);this.scenarioList=[...e],this.scenarioId=i.id,await this.loadSource(i.timeline)}get scenarios(){return this.scenarioList.map(e=>({id:e.id,label:e.label??e.id}))}get scenario(){return this.scenarioId}setScenario(e){const n=this.scenarioList.find(a=>a.id===e);if(!n||!this.timeline)return!1;if(e===this.scenarioId)return!0;const s=this.isPlaying,i=this.currentTime>=this.duration-.5,o=this.currentMarker?.id;this.stopAnimationLoop(),this.stepping=!1,this.pausedByVisibility=!1,this.restoreAuthored(),this.scenarioId=e,this.useDefinition(n.timeline),this.lastMarkerId=null;let r=0;return this.reducedMotion||i?r=this.duration:o!==void 0&&(r=this.markers.find(a=>a.id===o)?.time??0),this.seek(r),s&&!this.reducedMotion?(this.stepping=this.options.stepMode===!0,this.startPlaying()):this.notify(),!0}rememberAuthored(e){if(this.authored.has(e))return;const n={style:e.getAttribute("style")};e.children.length===0&&(n.text=e.textContent??"");const s=e.tagName.toLowerCase()==="path"?e:e.querySelector("path");s&&(n.path={element:s,d:s.getAttribute("d")}),this.authored.set(e,n)}restoreAuthored(){for(const[e,n]of this.authored){n.style===null?e.removeAttribute("style"):e.setAttribute("style",n.style),n.text!==void 0&&e.textContent!==n.text&&(e.textContent=n.text),n.path&&(n.path.d===null?n.path.element.removeAttribute("d"):n.path.element.setAttribute("d",n.path.d));const s=e.dataset;s&&delete s.shineBase}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notify(){for(const e of this.listeners)e()}get reducedMotion(){return this.reducedQuery?.matches===!0}get markers(){return this.markerList}get currentMarker(){const e=this.currentTime;let n;for(const s of this.markers)if(s.time<=e+.5)n=s;else break;return n}caption(e,n){const s=e?this.markers.find(r=>r.id===e):this.currentMarker;if(!s)return;const i=n??this.language(),o=r=>r?.[i]?.[s.id]??r?.[i.split("-")[0]]?.[s.id];return o(this.options.captions)??o(this.timeline?.captions)??s.label}next(){if(!this.timeline)return;const e=this.currentTime,n=this.markers.find(s=>s.time>e+.5);if(this.reducedMotion){this.seek(n?n.time:this.duration);return}e>=this.duration-.5||(this.stepping=n!==void 0,this.startPlaying())}prev(){if(!this.timeline)return;const e=this.currentTime,n=[...this.markers].reverse().find(s=>s.time<e-.5);this.pause(),this.seek(n?n.time:0)}goToMarker(e){const n=this.markers.find(s=>s.id===e);n&&(this.pause(),this.seek(n.time))}language(){return this.container.closest("[lang]")?.getAttribute("lang")||(typeof document<"u"?document.documentElement.lang:"")||"en"}showInitialFrame(){if(!this.timeline)return;const e=this.options.initialFrame??"start";if(e==="none")return;const n=e==="end"?this.timeline.duration:e==="start"?0:e;this.timeline.seek(Math.max(0,Math.min(this.timeline.duration,n))),this.applyState()}watchReducedMotion(){this.options.respectReducedMotion===!1||typeof window>"u"||typeof window.matchMedia!="function"||(this.reducedQuery??=window.matchMedia("(prefers-reduced-motion: reduce)"),this.reducedQuery.addEventListener?.("change",this.onReducedChange),this.reducedQuery.matches&&this.applyReducedMotion())}applyReducedMotion(){!this.reducedMotion||!this.timeline||(this.autoplayWhenSeen=!1,this.pause(),this.seek(this.timeline.duration))}watchVisibility(){if(!(!this.options.playWhenVisible||typeof window>"u")){if(typeof IntersectionObserver=="function"){this.visibilityObserver?.disconnect(),this.visibilityObserver=new IntersectionObserver(n=>{for(const s of n)this.onScreen=s.isIntersecting;this.updateVisibility()}),this.visibilityObserver.observe(this.container);const e=this.container.getBoundingClientRect?.();e&&(e.width>0||e.height>0)&&(this.onScreen=e.bottom>0&&e.top<window.innerHeight&&e.right>0&&e.left<window.innerWidth)}document.addEventListener("visibilitychange",this.onDocumentVisibility)}}updateVisibility(){const e=this.onScreen&&document.visibilityState!=="hidden";!e&&this.isPlaying?(this.pausedByVisibility=!0,this.pause()):e&&(this.pausedByVisibility||this.autoplayWhenSeen)&&!this.reducedMotion&&(this.pausedByVisibility=!1,this.autoplayWhenSeen=!1,this.startPlaying())}announceMarker(){if(!this.options.onMarker)return;const e=this.currentMarker,n=e?.id;n!==this.lastMarkerId&&(this.lastMarkerId=n,this.options.onMarker(e))}scanMedia(){this.mediaTargets=[],this.container.querySelectorAll("[data-tinyfly-media]").forEach(n=>{const s=n,i=Number(s.getAttribute("data-tinyfly-start")??"0")||0,o=s.getAttribute("data-volume");o!==null&&(s.volume=Math.max(0,Math.min(1,Number(o)||0))),this.mediaTargets.push({el:s,startTime:i,sync:new dr(s)})})}syncAllMedia(e,n){for(const s of this.mediaTargets)Sh(s.sync,s.el,e,n,s.startTime)}loadFromString(e){const n=JSON.parse(e);this.load(n)}registerTarget(e,n){if(typeof n=="string"){const s=this.container.querySelector(n);s&&(this.rememberAuthored(s),this.targets[e]=s,this.adapter.registerTarget(e,s))}else this.rememberAuthored(n),this.targets[e]=n,this.adapter.registerTarget(e,n)}autoRegisterTargets(){this.container.querySelectorAll("[data-tinyfly]").forEach(n=>{const s=n.closest("[data-tinyfly-symbol]");if(s&&s!==n)return;const i=n.getAttribute("data-tinyfly");i&&this.registerTarget(i,n)}),this.timeline&&new Set(this.timeline.tracks.map(s=>s.target)).forEach(s=>{if(!this.targets[s]){const i=this.container.querySelector(`[data-tinyfly="${s}"]`)||this.container.querySelector(`.${s}`)||this.container.querySelector(`#${s}`);i&&this.registerTarget(s,i)}})}setupSymbolInstances(){this.symbolInstances=[];const e=this.options.symbols;if(!e||e.length===0)return;const n=new Map(e.map(s=>[s.id,s]));this.container.querySelectorAll("[data-tinyfly-symbol]").forEach(s=>{const i=s.getAttribute("data-tinyfly-symbol");if(!i)return;const o=n.get(i);if(!o||!o.timeline.tracks?.length)return;const r=new qe;s.querySelectorAll("[data-tinyfly]").forEach(a=>{const l=a.getAttribute("data-tinyfly");l&&r.registerTarget(l,a)}),this.symbolInstances.push({adapter:r,timeline:hn(o.timeline)})})}attachMedia(e,n){this.mediaSync=new dr(e,n),this.timeline&&(this.mediaSync.setRate(this.timeline.speed),this.mediaSync.update(this.timeline.currentTime,this.isPlaying))}detachMedia(){this.mediaSync?.dispose(),this.mediaSync=void 0}play(){!this.timeline||this.isDestroyed||(this.autoplayWhenSeen=!1,this.stepping=this.options.stepMode===!0,this.startPlaying())}startPlaying(){if(!this.timeline||this.isDestroyed)return;const e=this.timeline.playbackState==="idle";this.timeline.play(),e&&this.timeline.currentTime===0&&this.applyState(),this.playhead={time:this.timeline.currentTime,iteration:this.timeline.loopIteration,direction:this.timeline.direction},this.mediaSync?.update(this.timeline.currentTime,!0),this.syncAllMedia(this.timeline.currentTime,!0),this.startAnimationLoop(),this.notify()}pause(){this.timeline&&(this.stepping=!1,this.timeline.pause(),this.notify(),this.mediaSync?.update(this.timeline.currentTime,!1),this.syncAllMedia(this.timeline.currentTime,!1),this.stopAnimationLoop())}stop(){this.timeline&&(this.timeline.stop(),this.stopAnimationLoop(),this.applyState(),this.mediaSync?.update(this.timeline.currentTime,!1),this.syncAllMedia(this.timeline.currentTime,!1))}seek(e){this.timeline&&(this.timeline.seek(e),this.applyState(),this.playhead={time:this.timeline.currentTime,iteration:this.timeline.loopIteration,direction:this.timeline.direction},this.mediaSync?.seek(this.timeline.currentTime),this.syncAllMedia(this.timeline.currentTime,this.isPlaying))}setSpeed(e){this.timeline&&(this.timeline.speed=e,this.mediaSync?.setRate(e))}reverse(){this.timeline&&this.timeline.reverse()}get currentTime(){return this.timeline?.currentTime??0}get duration(){return this.timeline?.duration??0}get isPlaying(){return this.timeline?.playbackState==="playing"}destroy(){this.isDestroyed=!0,this.stopAnimationLoop(),this.reducedQuery?.removeEventListener?.("change",this.onReducedChange),this.visibilityObserver?.disconnect(),typeof document<"u"&&document.removeEventListener("visibilitychange",this.onDocumentVisibility),this.mediaSync?.dispose(),this.mediaSync=void 0;for(const e of this.mediaTargets)e.el.paused||e.el.pause();this.mediaTargets=[],this.adapter.clearTargets();for(const e of this.symbolInstances)e.adapter.clearTargets();this.symbolInstances=[],this.authored.clear(),this.timeline=null}startAnimationLoop(){if(this.animationFrameId!==void 0)return;this.lastTime=performance.now();const e=n=>{if(this.isDestroyed||!this.timeline)return;const s=n-(this.lastTime??n);this.lastTime=n;const i=this.playhead;this.timeline.tick(s),this.stopAtMarker(i),this.applyState();const o=this.timeline.playbackState==="playing";this.mediaSync?.update(this.timeline.currentTime,o),this.syncAllMedia(this.timeline.currentTime,o),this.timeline.playbackState==="playing"?this.animationFrameId=requestAnimationFrame(e):(this.animationFrameId=void 0,this.notify())};this.animationFrameId=requestAnimationFrame(e)}stopAtMarker(e){const n=this.timeline,s={time:n.currentTime,iteration:n.loopIteration,direction:n.direction};this.playhead=s;const i=this.markers;if(i.length===0)return;const{crossings:o}=Fo(i.map(r=>r.time),e,s,{duration:n.duration,alternate:n.config.alternate===!0,holding:n.repeatDelayRemaining>0});for(const r of o){if(r.kind!=="event")continue;const a=i[r.index];if(this.stepping||a.pause){this.stepping=!1,n.pause(),n.seek(a.time),this.playhead={time:a.time,iteration:n.loopIteration,direction:n.direction};return}}}stopAnimationLoop(){this.animationFrameId!==void 0&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0)}applyState(){if(!this.timeline)return;const e=this.timeline.currentTime;this.adapter.applyState(this.timeline.getStateAtTime(e)),this.announceMarker(),this.notify();for(const n of this.symbolInstances){const s=n.timeline.duration;n.adapter.applyState(n.timeline.getStateAtTime(s>0?e%s:e))}}}async function a1(t,e,n={}){const s=new ti(t,{...n,autoplay:!0});return await s.load(e),s}function l1(t,e={}){return new ti(t,e)}const Th={play:"Play",pause:"Pause",prev:"Previous step",next:"Next step",restart:"Restart",scrub:"Position",speed:"Speed",reveal:"Reveal",step:"Step",of:"of",stepFormat:"{index} / {total}",scenario:"Scenario",fullscreen:"Full screen",exitFullscreen:"Exit full screen"},Eh="tinyfly-controls-style",c1=`
|
|
3
3
|
.tf-ctl { --tf-ctl-fg: #1d1d1f; --tf-ctl-bg: #f4f2ee; --tf-ctl-accent: #c2410c; --tf-ctl-radius: 8px;
|
|
4
4
|
font: 14px/1.4 var(--tf-ctl-font, system-ui, sans-serif); color: var(--tf-ctl-fg); margin-top: 8px; }
|
|
5
5
|
.tf-ctl-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; padding: 6px; border-radius: var(--tf-ctl-radius); background: var(--tf-ctl-bg); }
|
|
@@ -47,20 +47,20 @@
|
|
|
47
47
|
.tf-fullscreen > svg, .tf-fullscreen > canvas { grid-column: 1; grid-row: 1 / span 12; height: calc(100vh - 24px) !important; height: calc(100dvh - 24px) !important; }
|
|
48
48
|
.tf-fullscreen > :not(svg):not(canvas) { grid-column: 2; }
|
|
49
49
|
}
|
|
50
|
-
`;let
|
|
50
|
+
`;let h1=0;function u1(t){if(t.getElementById(Eh))return;const e=t.createElement("style");e.id=Eh,e.textContent=c1,t.head.appendChild(e)}function Ah(t,e,n={}){const s=e.ownerDocument;u1(s);const i={...Th,...n.labels},o=n.speeds??[.5,1,2],r=()=>t.markers.length>0,a=()=>t.markers.some(C=>C.label!==void 0||t.caption(C.id)!==void 0),l=s.createElement("div");l.className="tf-ctl";const c=s.createElement("div");c.className="tf-ctl-bar",c.setAttribute("role","group");const h=(C,F,R,B="")=>{const j=s.createElement("button");return j.type="button",j.className=`tf-ctl-btn ${B}`.trim(),j.setAttribute("aria-label",C),j.title=C,j.textContent=F,j.addEventListener("click",R),j},u=h(i.restart,"⟲",()=>{t.pause(),t.seek(0)}),d=h(i.prev,"|◀",()=>t.prev()),f=h(i.play,"▶",()=>t.isPlaying?t.pause():g(),"tf-ctl-primary"),p=h(i.next,"▶|",()=>t.next()),g=()=>{t.currentTime>=t.duration-.5&&t.seek(0),t.play()},m=s.createElement("input");m.type="range",m.className="tf-ctl-scrub",m.min="0",m.max="1000",m.step="1",m.setAttribute("aria-label",i.scrub),m.addEventListener("input",()=>{t.pause(),t.seek(Number(m.value)/1e3*t.duration)});const y=s.createElement("span");y.className="tf-ctl-step";const T=s.createElement("select");T.className="tf-ctl-speed",T.setAttribute("aria-label",i.speed);for(const C of o){const F=s.createElement("option");F.value=String(C),F.textContent=`${C}×`,C===1&&(F.selected=!0),T.appendChild(F)}T.addEventListener("change",()=>t.setSpeed(Number(T.value))),c.append(u,d,f,p,m,y),o.length>0&&c.append(T),l.append(c);const k=n.fullscreen?p1(e,s,i):void 0;k&&c.append(k.button);const b=s.createElement("p");b.className="tf-ctl-caption",b.setAttribute("aria-live","polite"),n.captions!==!1&&l.append(b);const A=s.createElement("div");A.className="tf-ctl-question",A.hidden=!0;const M=s.createElement("span"),E=h(i.reveal,i.reveal,()=>t.play(),"tf-ctl-primary");A.append(M,E),l.append(A);const x=d1(t,s,i.scenario,n.scenarioControl??"buttons");x&&l.append(x.element);const S=n.mount;S?S.appendChild(l):e.insertAdjacentElement("afterend",l);const I=()=>{const C=t.isPlaying;f.textContent=C?"❚❚":"▶",f.setAttribute("aria-label",C?i.pause:i.play),f.title=C?i.pause:i.play;const F=t.duration;s.activeElement!==m&&(m.value=String(F>0?Math.round(t.currentTime/F*1e3):0));const R=t.markers;if(d.hidden=p.hidden=y.hidden=R.length===0,R.length>0){const B=t.currentMarker,j=B?R.indexOf(B)+1:0;y.textContent=i.stepFormat.replace("{index}",String(j)).replace("{total}",String(R.length)),y.setAttribute("aria-label",`${i.step} ${j} ${i.of} ${R.length}`),d.disabled=t.currentTime<=.5,p.disabled=t.currentTime>=F-.5;const H=t.caption()??"";b.textContent!==H&&(b.textContent=H),b.hidden=!a();const N=!C&&B?.question!==void 0&&Math.abs(t.currentTime-B.time)<1;A.hidden=!N,N&&M.textContent!==B.question&&(M.textContent=B.question)}else A.hidden=!0,b.hidden=!0;x?.update()},v=t.subscribe(I);I();const $=n.keyboardScope??e;!$.hasAttribute("tabindex")&&$.tabIndex<0&&($.tabIndex=0);const _=new WeakSet,P=C=>{if(_.has(C)||(_.add(C),C.defaultPrevented||C.altKey||C.ctrlKey||C.metaKey))return;const F=C.target;if(!(F.tagName==="INPUT"||F.tagName==="SELECT")&&!(C.key===" "&&F.tagName==="BUTTON"))switch(C.key){case" ":C.preventDefault(),t.isPlaying?t.pause():g();break;case"ArrowRight":if(!r())return;C.preventDefault(),t.next();break;case"ArrowLeft":if(!r())return;C.preventDefault(),t.prev();break;case"Home":C.preventDefault(),t.pause(),t.seek(0);break;case"f":case"F":if(!k)return;C.preventDefault(),k.active?k.exit():k.enter();break}};return $.addEventListener("keydown",P),l.addEventListener("keydown",P),{element:l,fullscreen:k&&{get active(){return k.active},enter:k.enter,exit:k.exit},destroy(){k?.destroy(),v(),$.removeEventListener("keydown",P),l.removeEventListener("keydown",P),l.remove()}}}function d1(t,e,n,s){const i=t.scenarios;if(i.length<2)return;if(s==="slider"){const h=e.createElement("div");h.className="tf-ctl-choice-slider";const u=e.createElement("span");u.textContent=n,u.setAttribute("aria-hidden","true");const d=e.createElement("input");d.type="range",d.min="0",d.max=String(i.length-1),d.step="1",d.setAttribute("aria-label",n);const f=e.createElement("output");return f.setAttribute("aria-hidden","true"),d.addEventListener("input",()=>{const g=i[Number(d.value)];g&&t.setScenario(g.id)}),h.append(u,d,f),{element:h,update:()=>{const g=Math.max(0,i.findIndex(y=>y.id===t.scenario));e.activeElement!==d&&(d.value=String(g));const m=i[g].label;f.textContent!==m&&(f.textContent=m),d.setAttribute("aria-valuetext",m)}}}const o=e.createElement("fieldset");o.className="tf-ctl-choices";const r=e.createElement("legend");r.textContent=n,o.append(r);const a=`tf-ctl-scenario-${++h1}`,l=i.map(h=>{const u=e.createElement("label");u.className="tf-ctl-choice";const d=e.createElement("input");d.type="radio",d.name=a,d.value=h.id,d.addEventListener("change",()=>{d.checked&&t.setScenario(h.id)});const f=e.createElement("span");return f.textContent=h.label,u.append(d,f),o.append(u),d});return{element:o,update:()=>{for(const h of l){const u=h.value===t.scenario;h.checked!==u&&(h.checked=u)}}}}const f1='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/></svg>',g1='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5"/></svg>';function p1(t,e,n){const s=e,i=t,o=e.createElement("button");o.type="button",o.className="tf-ctl-btn tf-ctl-fullscreen";let r,a="";const l=()=>{const g=r!==void 0;o.innerHTML=g?g1:f1;const m=g?n.exitFullscreen:n.fullscreen;o.setAttribute("aria-label",m),o.title=m,o.setAttribute("aria-pressed",String(g)),t.classList.toggle("tf-fullscreen",g),t.classList.toggle("tf-fullscreen-overlay",r==="overlay")},c=()=>s.fullscreenElement??s.webkitFullscreenElement??null,h=()=>{c()===t?r="native":r==="native"&&(r=void 0),l()},u=g=>{g.key==="Escape"&&p()},d=()=>{r="overlay",a=e.documentElement.style.overflow,e.documentElement.style.overflow="hidden",e.addEventListener("keydown",u),l()};async function f(){if(r)return;const g=i.requestFullscreen?.bind(i)??i.webkitRequestFullscreen?.bind(i),m=s.fullscreenEnabled??s.webkitFullscreenEnabled??!1;if(g&&m)try{if(await g(),c()===t){r="native",l();return}}catch{}d()}async function p(){if(r==="overlay")e.removeEventListener("keydown",u),e.documentElement.style.overflow=a,r=void 0,l();else if(r==="native"){r=void 0,l();const g=s.exitFullscreen?.bind(s)??s.webkitExitFullscreen?.bind(s);c()===t&&g&&await g()}}return o.addEventListener("click",()=>{r?p():f()}),e.addEventListener("fullscreenchange",h),e.addEventListener("webkitfullscreenchange",h),l(),{button:o,get active(){return r!==void 0},enter:f,exit:p,destroy(){p(),e.removeEventListener("fullscreenchange",h),e.removeEventListener("webkitfullscreenchange",h),o.remove()}}}const xh="tinyfly-choices-style",m1=`
|
|
51
51
|
[data-tinyfly-choose] { cursor: pointer; }
|
|
52
52
|
[data-tinyfly-choose]:focus-visible { outline: 2px solid var(--tf-ctl-accent, #c2410c); outline-offset: 2px; }
|
|
53
|
-
`;function zg(t){if(t.getElementById(jc))return;const e=t.createElement("style");e.id=jc,e.textContent=Yg,t.head.appendChild(e)}function Bc(t,e){const n=Array.from(e.querySelectorAll("[data-tinyfly-choose]"));if(n.length===0)return()=>{};zg(e.ownerDocument);const s=[],i=[];for(const a of n){const l=a.getAttribute("data-tinyfly-choose")??"",c=[],h=(g,p)=>{a.hasAttribute(g)||(a.setAttribute(g,p),c.push(g))};h("role","button"),h("tabindex","0");const d=t.scenarios.find(g=>g.id===l)?.label;d!==void 0&&h("aria-label",d),a.setAttribute("aria-pressed","false"),c.push("aria-pressed"),s.push({element:a,attributes:c});const u=()=>t.setScenario(l),f=g=>{const p=g.key;p!=="Enter"&&p!==" "||(g.preventDefault(),u())};a.addEventListener("click",u),a.addEventListener("keydown",f),i.push(()=>{a.removeEventListener("click",u),a.removeEventListener("keydown",f)})}const o=()=>{for(const{element:a}of s)a.setAttribute("aria-pressed",String(a.getAttribute("data-tinyfly-choose")===t.scenario))},r=t.subscribe(o);return o(),()=>{r();for(const a of i)a();for(const{element:a,attributes:l}of s)for(const c of l)a.removeAttribute(c)}}const Ds=new WeakMap,Wo=new WeakMap;let Xg=0;function jn(t,e,n){if(t)try{return JSON.parse(t)}catch(s){console.warn(`tinyfly: invalid ${e} JSON on`,n,s);return}}async function Wc(t,e={}){const n=Ds.get(t);if(n)return n;const s=Array.from(t.querySelectorAll("script[data-tinyfly-timeline]")),i=s[0],o=t.getAttribute("data-src"),r=Gg(t.getAttribute("data-markers")),a=s.length>1||i?.hasAttribute("data-scenario")?Ug(s,r,t):void 0;if(a&&a.length===0)return;let l=i&&!a?jn(i.textContent,"timeline",t):void 0;if(!l&&o&&r){const f=await fetch(o);f.ok&&(l=await f.json())}if(l&&r&&(l=qc(l,r)),!l&&!o&&!a){console.warn('tinyfly: embed has no timeline (a <script type="application/json" data-tinyfly-timeline> or data-src)',t);return}const c=jn(t.querySelector("script[data-tinyfly-captions]")?.textContent,"captions",t),h={playWhenVisible:!0,...e.player,...c&&{captions:c},...jn(t.getAttribute("data-options"),"data-options",t)};Jg(t);const d=new Ns(t,h),u={element:t,player:d};if(Ds.set(t,u),t.setAttribute("data-tinyfly-mounted",""),a){const f=t.getAttribute("data-scenario")??void 0;await d.loadScenarios(a,{initial:a.some(g=>g.id===f)?f:void 0}),Wo.set(t,Bc(d,t))}else await d.load(l??o);if(t.getAttribute("data-controls")!=="false"){const f=jn(t.getAttribute("data-labels"),"data-labels",t),g=t.querySelector("figcaption"),p=t.getAttribute("data-scenario-legend"),m=t.getAttribute("data-scenario-control");u.controls=Fc(d,t,{...e.controls,...t.getAttribute("data-fullscreen")==="true"?{fullscreen:!0}:{},...m==="slider"||m==="buttons"?{scenarioControl:m}:{},labels:{...e.controls?.labels,...f,...p?{scenario:p}:{}},mount:void 0}),g?t.insertBefore(u.controls.element,g):t.appendChild(u.controls.element)}return u}function Ug(t,e,n){const s=[];return t.forEach((i,o)=>{const r=jn(i.textContent,"timeline",n);if(!r)return;const a=i.getAttribute("data-scenario")||`scenario-${o+1}`;if(s.some(c=>c.id===a)){console.warn(`tinyfly: scenario id "${a}" is used more than once; the later one is skipped`,n);return}const l=i.getAttribute("data-scenario-label")??void 0;s.push({id:a,label:l,timeline:e?qc(r,e):r})}),s}function qc(t,e){return t.config.markers?.length?t:{...t,config:{...t.config,markers:e.map((n,s)=>({id:`step-${s+1}`,time:n}))}}}function Gg(t){if(!t)return;const e=t.split(/[\s,]+/).filter(Boolean).map(Number).filter(n=>Number.isFinite(n)&&n>=0).sort((n,s)=>n-s);return e.length>0?e:void 0}async function Kc(t=document,e={}){const n=Array.from(t.querySelectorAll("[data-tinyfly-embed]"));return(await Promise.all(n.map(i=>Wc(i,e)))).filter(i=>i!==void 0)}function Vg(t){const e=Ds.get(t);e&&(Wo.get(t)?.(),Wo.delete(t),e.controls?.destroy(),e.player.destroy(),Ds.delete(t),t.removeAttribute("data-tinyfly-mounted"))}function Jg(t){const e=t.querySelector("svg");if(!e||e.hasAttribute("role")||e.hasAttribute("aria-hidden"))return;const n=t.getAttribute("data-alt"),s=t.querySelector("figcaption");e.setAttribute("role","img"),n?e.setAttribute("aria-label",n):s&&(s.id||=`tinyfly-caption-${++Xg}`,e.setAttribute("aria-labelledby",s.id))}function Zg(){if(!(typeof document<"u"?document.currentScript:null)?.hasAttribute("data-tinyfly-auto"))return;const e=()=>{Kc()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e,{once:!0}):e()}class Yc{container;containerA;containerB;adapterA;adapterB;timelineA=null;timelineB=null;symbolDefs=new Map;nestedByAdapter=new Map;sequence=null;options;_currentSceneIndex=0;_state="idle";_isPlaying=!1;_isDestroyed=!1;loopIteration=0;animationFrameId;lastTime;transitionTimer;constructor(e,n={}){if(typeof e=="string"){const s=document.querySelector(e);if(!s)throw new Error(`Container not found: ${e}`);this.container=s}else this.container=e;this.options=n,this.container.style.position="relative",this.container.style.overflow="hidden",this.containerA=this.createSceneContainer(),this.containerB=this.createSceneContainer(),this.container.appendChild(this.containerA),this.container.appendChild(this.containerB),this.containerB.style.visibility="hidden",this.adapterA=new _e,this.adapterB=new _e}async load(e){let n;if(typeof e=="string"){const s=await fetch(e);if(!s.ok)throw new Error(`Failed to load sequence: ${s.statusText}`);n=await s.json()}else n=e;this.sequence=n,this.symbolDefs.clear();for(const s of n.symbols??[])s.timeline?.tracks?.length&&this.symbolDefs.set(s.id,s.timeline);this.container.style.width=`${n.canvas.width}px`,this.container.style.height=`${n.canvas.height}px`,n.scenes.length>0&&(this.renderScene(n.scenes[0],this.containerA,this.adapterA),this.timelineA=this.createTimeline(n.scenes[0])),this.options.autoplay&&this.play()}play(){if(!(!this.sequence||this._isDestroyed)&&this.sequence.scenes.length!==0){if(this._isPlaying=!0,this._state==="idle"){if(this._state="playing-scene",this._currentSceneIndex=0,this.timelineA)this.timelineA.onComplete=()=>this.onSceneComplete(),this.timelineA.play();else{this.onSceneComplete();return}this.options.onSceneChange?.(0)}else this._state==="playing-scene"&&this.timelineA&&this.timelineA.play();this.startAnimationLoop()}}pause(){this._isPlaying&&(this._isPlaying=!1,this.timelineA&&this.timelineA.pause(),this.timelineB&&this.timelineB.pause(),this.stopAnimationLoop())}stop(){if(this._isPlaying=!1,this._state="idle",this._currentSceneIndex=0,this.loopIteration=0,this.transitionTimer!==void 0&&(clearTimeout(this.transitionTimer),this.transitionTimer=void 0),this.timelineA&&this.timelineA.stop(),this.timelineB&&this.timelineB.stop(),this.stopAnimationLoop(),this.sequence&&this.sequence.scenes.length>0&&(this.clearContainer(this.containerA),this.clearContainer(this.containerB),this.adapterA.clearTargets(),this.adapterB.clearTargets(),this.containerB.style.visibility="hidden",this.resetTransitionStyles(this.containerA),this.resetTransitionStyles(this.containerB),this.renderScene(this.sequence.scenes[0],this.containerA,this.adapterA),this.timelineA=this.createTimeline(this.sequence.scenes[0]),this.timelineA)){const e=this.timelineA.getStateAtTime(0);this.adapterA.applyState(e),this.applyNested(this.adapterA,0)}}goToScene(e){if(!this.sequence||e<0||e>=this.sequence.scenes.length)return;const n=this._isPlaying;this.transitionTimer!==void 0&&(clearTimeout(this.transitionTimer),this.transitionTimer=void 0),this.stopAnimationLoop(),this.timelineA&&this.timelineA.stop(),this.timelineB&&this.timelineB.stop(),this._currentSceneIndex=e,this._state=n?"playing-scene":"idle",this.clearContainer(this.containerA),this.clearContainer(this.containerB),this.adapterA.clearTargets(),this.adapterB.clearTargets(),this.containerB.style.visibility="hidden",this.resetTransitionStyles(this.containerA),this.resetTransitionStyles(this.containerB);const s=this.sequence.scenes[e];if(this.renderScene(s,this.containerA,this.adapterA),this.timelineA=this.createTimeline(s),this.options.onSceneChange?.(e),n)this.timelineA?(this.timelineA.onComplete=()=>this.onSceneComplete(),this.timelineA.play(),this.startAnimationLoop()):this.onSceneComplete();else if(this.timelineA){const i=this.timelineA.getStateAtTime(0);this.adapterA.applyState(i),this.applyNested(this.adapterA,0)}}destroy(){this._isDestroyed=!0,this._isPlaying=!1,this.transitionTimer!==void 0&&(clearTimeout(this.transitionTimer),this.transitionTimer=void 0),this.stopAnimationLoop(),this.adapterA.clearTargets(),this.adapterB.clearTargets();for(const e of this.nestedByAdapter.values())for(const n of e)n.adapter.clearTargets();this.nestedByAdapter.clear(),this.timelineA&&this.timelineA.stop(),this.timelineB&&this.timelineB.stop(),this.timelineA=null,this.timelineB=null,this.containerA.parentNode&&this.containerA.remove(),this.containerB.parentNode&&this.containerB.remove(),this.sequence=null}get currentSceneIndex(){return this._currentSceneIndex}get sceneCount(){return this.sequence?.scenes.length??0}get isPlaying(){return this._isPlaying}get state(){return this._state}createSceneContainer(){const e=document.createElement("div");return e.style.position="absolute",e.style.top="0",e.style.left="0",e.style.width="100%",e.style.height="100%",e}renderScene(e,n,s){n.innerHTML="",s.clearTargets();const i=document.createElement("div");i.style.cssText="position:absolute;inset:0;transform-origin:center center",i.setAttribute("data-tinyfly","Camera"),n.appendChild(i),s.registerTarget("Camera",i);for(const o of e.elements){if(!o.html)continue;const r=document.createElement("div");r.innerHTML=o.html.trim();const a=r.firstElementChild;if(a){i.appendChild(a);const l=a.getAttribute("data-tinyfly");l&&s.registerTarget(l,a)}}this.setupNested(i,s)}setupNested(e,n){const s=[];e.querySelectorAll("[data-tinyfly-symbol]").forEach(i=>{const o=i.getAttribute("data-tinyfly-symbol");if(!o)return;const r=this.symbolDefs.get(o);if(!r)return;const a=new _e;i.querySelectorAll("[data-tinyfly]").forEach(l=>{const c=l.getAttribute("data-tinyfly");c&&a.registerTarget(c,l)}),s.push({adapter:a,timeline:Ze(r)})}),s.length?this.nestedByAdapter.set(n,s):this.nestedByAdapter.delete(n)}applyNested(e,n){const s=this.nestedByAdapter.get(e);if(s)for(const i of s){const o=i.timeline.duration;i.adapter.applyState(i.timeline.getStateAtTime(o>0?n%o:n))}}clearContainer(e){e.innerHTML=""}createTimeline(e){return e.timeline?Ze(e.timeline):null}onSceneComplete(){if(this._isDestroyed||!this.sequence)return;const e=this._currentSceneIndex+1;if(e>=this.sequence.scenes.length){const n=this.options.loop??this.sequence.loop??0;n===-1||n>0&&this.loopIteration<n-1?(this.loopIteration++,this.beginTransitionTo(0)):(this._isPlaying=!1,this._state="idle",this.stopAnimationLoop(),this.options.onComplete?.())}else this.beginTransitionTo(e)}beginTransitionTo(e){if(!this.sequence||this._isDestroyed)return;const n=this.sequence.scenes[e],s=n.transition;if(s.type==="none"||s.duration<=0){this.switchToScene(e);return}this._state="transitioning",this.containerB.style.visibility="visible",this.renderScene(n,this.containerB,this.adapterB),this.timelineB=this.createTimeline(n),this.timelineB&&this.timelineB.play(),this.applyTransition(s.type,s.duration),this.transitionTimer=window.setTimeout(()=>{this.finishTransition(e)},s.duration)}applyTransition(e,n){const s=`${n}ms`,i="ease-in-out";switch(this.resetTransitionStyles(this.containerA),this.resetTransitionStyles(this.containerB),e){case"fade":this.containerB.style.opacity="0";break;case"slide-left":this.containerB.style.transform="translateX(100%)";break;case"slide-right":this.containerB.style.transform="translateX(-100%)";break;case"slide-up":this.containerB.style.transform="translateY(100%)";break;case"slide-down":this.containerB.style.transform="translateY(-100%)";break}switch(this.containerB.offsetHeight,this.containerA.style.transition=`opacity ${s} ${i}, transform ${s} ${i}`,this.containerB.style.transition=`opacity ${s} ${i}, transform ${s} ${i}`,e){case"fade":this.containerA.style.opacity="0",this.containerB.style.opacity="1";break;case"slide-left":this.containerA.style.transform="translateX(-100%)",this.containerB.style.transform="translateX(0)";break;case"slide-right":this.containerA.style.transform="translateX(100%)",this.containerB.style.transform="translateX(0)";break;case"slide-up":this.containerA.style.transform="translateY(-100%)",this.containerB.style.transform="translateY(0)";break;case"slide-down":this.containerA.style.transform="translateY(100%)",this.containerB.style.transform="translateY(0)";break}}resetTransitionStyles(e){e.style.transition="",e.style.opacity="1",e.style.transform=""}finishTransition(e){this.transitionTimer=void 0,this.timelineA&&(this.timelineA.stop(),this.timelineA=null),this.adapterA.clearTargets(),this.clearContainer(this.containerA);const n=this.containerA;this.containerA=this.containerB,this.containerB=n;const s=this.adapterA;this.adapterA=this.adapterB,this.adapterB=s,this.timelineA=this.timelineB,this.timelineB=null,this.containerB.style.visibility="hidden",this.resetTransitionStyles(this.containerA),this.resetTransitionStyles(this.containerB),this._currentSceneIndex=e,this._state="playing-scene",this.options.onSceneChange?.(e),this.timelineA?(this.timelineA.onComplete=()=>this.onSceneComplete(),this.timelineA.playbackState!=="playing"&&this.timelineA.play()):this.onSceneComplete()}switchToScene(e){if(!this.sequence||this._isDestroyed)return;this.timelineA&&this.timelineA.stop(),this.adapterA.clearTargets(),this.clearContainer(this.containerA);const n=this.sequence.scenes[e];this.renderScene(n,this.containerA,this.adapterA),this.timelineA=this.createTimeline(n),this._currentSceneIndex=e,this._state="playing-scene",this.options.onSceneChange?.(e),this.timelineA?(this.timelineA.onComplete=()=>this.onSceneComplete(),this.timelineA.play()):this.onSceneComplete()}startAnimationLoop(){if(this.animationFrameId!==void 0)return;this.lastTime=performance.now();const e=n=>{if(this._isDestroyed||!this._isPlaying)return;const s=n-(this.lastTime??n);if(this.lastTime=n,this.timelineA&&this.timelineA.playbackState==="playing"){this.timelineA.tick(s);const i=this.timelineA.getStateAtTime(this.timelineA.currentTime);this.adapterA.applyState(i),this.applyNested(this.adapterA,this.timelineA.currentTime)}if(this._state==="transitioning"&&this.timelineB&&this.timelineB.playbackState==="playing"){this.timelineB.tick(s);const i=this.timelineB.getStateAtTime(this.timelineB.currentTime);this.adapterB.applyState(i),this.applyNested(this.adapterB,this.timelineB.currentTime)}this._isPlaying?this.animationFrameId=requestAnimationFrame(e):this.animationFrameId=void 0};this.animationFrameId=requestAnimationFrame(e)}stopAnimationLoop(){this.animationFrameId!==void 0&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0)}}async function Qg(t,e,n={}){const s=new Yc(t,{...n,autoplay:!0});return await s.load(e),s}const tm={type:"none",duration:0},yt=t=>({description:t,unit:"degrees"}),dt=(t,e=0,n=1)=>({description:t,unit:`${e}..${n}`,min:e,max:n}),zc={lean:yt("Upper body tipped about the hips (+ toward the way it faces)"),bend:yt("Line of action: the spine curved (+ curls forward, − arches back)"),headTilt:yt("Head tilt"),leftShoulder:yt("Left upper arm: 0 hangs down, 90 straight out to its side, 180 straight up; in profile, forward is negative for the left arm"),rightShoulder:yt("Right upper arm: 0 hangs down, 90 straight out (forward, in profile), 180 straight up"),leftElbow:yt("Left elbow bend, added to the upper arm"),rightElbow:yt("Right elbow bend, added to the upper arm"),leftHip:yt("Left thigh: 0 straight down; in profile negative is forward"),rightHip:yt("Right thigh: 0 straight down; in profile positive is forward"),leftKnee:yt("Left knee bend (negative folds the shin back)"),rightKnee:yt("Right knee bend (positive folds the shin back)"),leftWrist:yt("Left wrist bend, added to the forearm"),rightWrist:yt("Right wrist bend, added to the forearm"),leftAnkle:yt("Left ankle: + points the toe down (tiptoe), − onto the heel"),rightAnkle:yt("Right ankle: + points the toe down (tiptoe), − onto the heel"),leftFootOut:dt("Left foot turned out (seen from the front): 0 natural, 1 sideways, negative turned in",-1,1),rightFootOut:dt("Right foot turned out (seen from the front): 0 natural, 1 sideways, negative turned in",-1,1),mouth:dt("Mouth open: 0 closed, 1 wide open"),smile:dt("−1 frown, 0 flat, 1 smile",-1,1),mouthWidth:{description:"Mouth width: 1 normal, 0.5 pursed, 1.5 wide",unit:"factor",min:.3,max:2},blink:dt("Eyes closed by a blink: 0 open, 1 shut"),leftEye:{description:"Left eye openness: 0 shut, 1 normal, 1.6 wide",unit:"factor",min:0,max:2},rightEye:{description:"Right eye openness: 0 shut, 1 normal, 1.6 wide",unit:"factor",min:0,max:2},leftBrow:dt("Left eyebrow: −1 lowered, 0 rest, 1 raised",-1,1),rightBrow:dt("Right eyebrow: −1 lowered, 0 rest, 1 raised",-1,1),browTilt:dt("Eyebrow slant: −1 angry, 1 worried",-1,1),lookX:dt("Eyes look across: + the way it faces",-1,1),lookY:dt("Eyes look down (+) or up (−)",-1,1),stretch:{description:"Squash and stretch: 1 normal, above taller (a jump), below squashed (a landing)",unit:"factor",min:.3,max:3},turn:dt("0 front-on, 1 in profile, turned the way it faces"),sit:dt("0 standing, 1 seated"),spin:yt("Whole body turned about the hips: + rolls forward (a front flip), 360 a full turn"),rise:{description:"Lift off the ground, as a fraction of its height (the arc of a jump)",unit:"× height"}},Xc={walk:{description:"Walk-cycle phase, in strides: animate 0 → n for n strides",unit:"strides"},walking:dt("How much of the walk cycle is applied (0 standing)"),gait:{description:"How it walks: a gait name (walk, bouncy, doubleBounce, sneak, strut, tired, run, shove); a string track switches it",kind:"string"},talk:dt("How much the mouth chatters"),rubber:dt("Limbs from jointed (0) to rubber hose (1)"),facing:{description:"Which way it faces: 1 right, −1 left (key the flip while turn is near 0)",unit:"±1",min:-1,max:1},beat:{description:"Beats into its dance (with a dance)",unit:"beats"},dancing:dt("How much of the dance is applied")},Uc={"thumb.curl":dt("Thumb curled in"),"thumb.across":dt("Thumb across the palm"),"index.curl":dt("Index finger curled"),"middle.curl":dt("Middle finger curled"),"ring.curl":dt("Ring finger curled"),"pinky.curl":dt("Little finger curled"),spread:dt("Fingers spread apart"),turn:yt("Hand turned about the forearm"),bend:yt("Hand bent at the wrist, palm-ward"),tilt:yt("Hand tilted sideways"),roll:yt("Hand rolled to show the back or the palm")};let Gc;function em(t){Gc=t}function nm(t){return Gc?.(t)??{}}function Vc(t){let e=0;for(let n=1;n<t.length;n++)e+=Math.hypot(t[n].x-t[n-1].x,t[n].y-t[n-1].y);return e}function an(t,e){const n=Math.min(1,Math.max(0,e));if(t.length<2||n===1)return t.slice();if(n===0)return t.slice(0,1);let s=Vc(t)*n;const i=[t[0]];for(let o=1;o<t.length;o++){const r=t[o-1],a=t[o],l=Math.hypot(a.x-r.x,a.y-r.y);if(l>=s){const c=l===0?0:s/l;return i.push({x:r.x+(a.x-r.x)*c,y:r.y+(a.y-r.y)*c}),i}i.push(a),s-=l}return i}function Fs(t,e){const n=an(t,e);return n[n.length-1]}function qo(t,e){return e>0?Math.floor(Math.max(0,t)*e/1e3):0}function js(t,e,n){const s=e.roughness??2,i=Math.max(1,Math.round(e.passes??2)),o=qo(n,e.boil??8);let r=0;const a=()=>{const u=r++;return f=>$e(qt(`${e.seed??1}:${o}:${u}:${f}`))},l=(u,f)=>(u.next()*2-1)*f,c=u=>{const f=a(),g=t.lineWidth,p=t.globalAlpha;for(let m=0;m<i;m++)t.lineWidth=m===0?g:g*.55,t.globalAlpha=m===0?p:p*.6,u(f(m));t.lineWidth=g,t.globalAlpha=p},h=(u,f=1)=>{if(u.length<2)return;const g=u.slice(1).map((m,b)=>Math.hypot(m.x-u[b].x,m.y-u[b].y)),p=g.reduce((m,b)=>m+b,0)*Math.min(1,Math.max(0,f));c(m=>{const b=[],S=[];if(u.forEach((y,M)=>{b.push({x:y.x+l(m,s*.5),y:y.y+l(m,s*.5)}),M>0&&S.push([m.next()*2-1,m.next()*2-1])}),p<=0)return;t.beginPath(),t.moveTo(b[0].x,b[0].y);let k=0;for(let y=1;y<b.length;y++){const M=sm(b[y-1],b[y],s,S[y-1]),$=g[y-1];if(k+$<=p){t.bezierCurveTo(M[1].x,M[1].y,M[2].x,M[2].y,M[3].x,M[3].y),k+=$;continue}const E=im(M,$===0?1:(p-k)/$);t.bezierCurveTo(E[1].x,E[1].y,E[2].x,E[2].y,E[3].x,E[3].y);break}t.stroke()})},d=(u,f,g,p,m=1)=>{c(b=>{const k=b.next()*Math.PI*2,y=Math.PI*2+.15+b.next()*.3,M=[];for(let E=0;E<=14;E++){const A=k+y*E/14,T=l(b,s*.6);M.push({x:u+Math.cos(A)*(g+T),y:f+Math.sin(A)*(p+T)})}const $=an(M,m);$.length<2||(Jc(t,$),t.stroke())})};return{line:h,curve(u,f=1){if(u.length<2)return;const g=u[0],p=u[u.length-1],m=Math.hypot(p.x-g.x,p.y-g.y)||1,b=-(p.y-g.y)/m,S=(p.x-g.x)/m;c(k=>{const y={x:l(k,s*.5),y:l(k,s*.5)},M={x:l(k,s*.5),y:l(k,s*.5)},$=l(k,s*Math.min(1.5,Math.max(.3,m/80))),E=u.map((T,I)=>{const v=I/(u.length-1),P=Math.sin(Math.PI*v)*$;return{x:T.x+y.x+(M.x-y.x)*v+b*P,y:T.y+y.y+(M.y-y.y)*v+S*P}}),A=an(E,f);A.length<2||(Jc(t,A),t.stroke())})},circle(u,f,g,p=1){d(u,f,g,g,p)},ellipse:d,nudge(u=.5){const f=a()(0);return{x:l(f,s*u),y:l(f,s*u)}}}}function sm(t,e,n,s){const i=e.x-t.x,o=e.y-t.y,r=Math.hypot(i,o)||1,a=n*Math.min(1.5,Math.max(.3,r/80)),l=-o/r,c=i/r;return[t,{x:t.x+i/3+l*s[0]*a,y:t.y+o/3+c*s[0]*a},{x:t.x+2*i/3+l*s[1]*a,y:t.y+2*o/3+c*s[1]*a},e]}function im([t,e,n,s],i){const o=(d,u)=>({x:d.x+(u.x-d.x)*i,y:d.y+(u.y-d.y)*i}),r=o(t,e),a=o(e,n),l=o(n,s),c=o(r,a),h=o(a,l);return[t,r,c,o(c,h)]}function Jc(t,e){t.beginPath(),t.moveTo(e[0].x,e[0].y);for(let s=1;s<e.length-1;s++){const i={x:(e[s].x+e[s+1].x)/2,y:(e[s].y+e[s+1].y)/2};t.quadraticCurveTo(e[s].x,e[s].y,i.x,i.y)}const n=e[e.length-1];t.lineTo(n.x,n.y)}function Bn(t,e,n){const s=t.length;if(s<2)return[];const i=[],o=[],r=a=>e+(n-e)*a/(s-1);return t.forEach((a,l)=>{const c=t[Math.max(0,l-1)],h=t[Math.min(s-1,l+1)],d=Math.hypot(h.x-c.x,h.y-c.y)||1,u=r(l)/2,f=-(h.y-c.y)/d*u,g=(h.x-c.x)/d*u;i.push({x:a.x+f,y:a.y+g}),o.push({x:a.x-f,y:a.y-g})}),[...i,...o.reverse()]}function Bs(t,e,n,s){const i=e.length;if(i<2)return;const o=Bn(e,n,s),r=a=>n+(s-n)*a/(i-1);t.beginPath(),t.moveTo(o[0].x,o[0].y);for(const a of o.slice(1))t.lineTo(a.x,a.y);t.closePath(),t.fill(),e.forEach((a,l)=>{l!==0&&l!==i-1&&i>3||(t.beginPath(),t.arc(a.x,a.y,r(l)/2,0,Math.PI*2),t.fill())})}function Ce(t,e,n,s,i=16){const o={x:2*e.x-(t.x+n.x)/2,y:2*e.y-(t.y+n.y)/2},r=[];for(let a=0;a<=i;a++){const l=a/i,c=l<.5?{x:t.x+(e.x-t.x)*2*l,y:t.y+(e.y-t.y)*2*l}:{x:e.x+(n.x-e.x)*(2*l-1),y:e.y+(n.y-e.y)*(2*l-1)},h=1-l,d={x:h*h*t.x+2*h*l*o.x+l*l*n.x,y:h*h*t.y+2*h*l*o.y+l*l*n.y};r.push({x:c.x+(d.x-c.x)*s,y:c.y+(d.y-c.y)*s})}return r}function Ko(t,e,n,s,i,o=0,r=1,a=40){const l=Math.cos(i),c=Math.sin(i);return Array.from({length:a+1},(h,d)=>{const u=o+Math.PI*2*r*d/a,f=Math.cos(u)*n,g=Math.sin(u)*s;return{x:t+f*l-g*c,y:e+f*c+g*l}})}function Wn(t,e){return e.look==="pencil"?lm(t,e):om(t,e.ink,e.look)}function Ws(t,e,n=!1){t.beginPath(),t.moveTo(e[0].x,e[0].y);for(const s of e.slice(1))t.lineTo(s.x,s.y);n&&t.closePath()}function om(t,e,n){const s=n==="silhouette",i=s?1.25:1;return{look:n,ink:e,limb(o,r,a){t.fillStyle=e,Bs(t,o,r*i,a*i)},line(o,r){o.length<2||(t.strokeStyle=e,t.lineWidth=r*i,t.lineCap="round",t.lineJoin="round",Ws(t,o),t.stroke())},shape(o,r,a){Ws(t,o,!0),(r!==null||s)&&(t.fillStyle=s?e:r,t.fill()),!(a<=0)&&(t.strokeStyle=e,t.lineWidth=a*i,t.lineJoin="round",t.stroke())},ellipse(o,r,a,l,c,h,d){t.beginPath(),t.ellipse(o,r,a,l,c,0,Math.PI*2),(h!==null||s)&&(t.fillStyle=s?e:h,t.fill()),!(d<=0)&&(t.strokeStyle=e,t.lineWidth=d*i,t.stroke())},dot(o,r,a){t.fillStyle=e,t.beginPath(),t.arc(o,r,a*i,0,Math.PI*2),t.fill()},guide(){},guideEllipse(){}}}function rm(t,e){const n=[t[0]];let s=0;for(let r=1;r<t.length;r++){const a=t[r-1],l=t[r],c=Math.hypot(l.x-a.x,l.y-a.y);let h=e-s;for(;h<c;){const d=h/c;n.push({x:a.x+(l.x-a.x)*d,y:a.y+(l.y-a.y)*d}),h+=e}s=c-(h-e)}const i=t[t.length-1],o=n[n.length-1];return Math.hypot(i.x-o.x,i.y-o.y)>e*.25?n.push(i):n[n.length-1]=i,n}function am(t,e){const n=t.length;return t.map((s,i)=>{const o=t[Math.max(0,i-1)],r=t[Math.min(n-1,i+1)],a=Math.hypot(r.x-o.x,r.y-o.y)||1,l=e(n===1?0:i/(n-1));return{x:s.x-(r.y-o.y)/a*l,y:s.y+(r.x-o.x)/a*l}})}function Zc(t){const e=[.6,1.4,2.9].map(s=>({frequency:s*(.8+t.next()*.4),phase:t.next()*Math.PI*2,amount:.5+t.next()*.5})),n=e.reduce((s,i)=>s+i.amount,0);return s=>e.reduce((i,o)=>i+o.amount*Math.sin(Math.PI*2*o.frequency*s+o.phase),0)/n}function lm(t,e){const n=e.pencil??{},s=e.ink,i=n.roughness??Math.max(1,e.lineWidth*.12),o=Math.max(1,Math.round(n.passes??2)),r=Math.min(1,Math.max(0,n.pressure??.25)),a=Math.min(1,Math.max(0,n.rubbedOut??.15)),l=qo(e.time,n.boil??8);let c=0;const h=(g,p,m=!1)=>$e(qt(`${e.seed}:${m?"paper":l}:${g}:${p}`)),d=(g,p,m,b,S,k=0)=>{if(g.length<2)return;const y=g.slice(1).reduce((v,P,H)=>v+Math.hypot(P.x-g[H].x,P.y-g[H].y),0);let M=rm(g,Math.max(1.5,Math.min(e.lineWidth*.8,y/24)));if(k>0&&M.length>=2){const[v,P]=[M[M.length-2],M[M.length-1]],H=Math.hypot(P.x-v.x,P.y-v.y)||1;M=[...M,{x:P.x+(P.x-v.x)/H*k,y:P.y+(P.y-v.y)/H*k}]}const $=Zc(m),E=Zc(m),A=M.length,T=[],I=[];M.forEach((v,P)=>{const H=A===1?0:P/(A-1),O=M[Math.max(0,P-1)],C=M[Math.min(A-1,P+1)],j=Math.hypot(C.x-O.x,C.y-O.y)||1,D=-(C.y-O.y)/j,W=(C.x-O.x)/j,B=$(H)*S,_=Math.min(1,H/.08,(1-H)/.08),L=(.55+.45*Math.sqrt(Math.max(0,_)))*(1+r*E(H)),N=Math.max(.3,p(H)*L/2),x=v.x+D*B,R=v.y+W*B;T.push({x:x+D*N,y:R+W*N}),I.push({x:x-D*N,y:R-W*N})}),t.save(),t.globalAlpha*=b,t.fillStyle=s,Ws(t,[...T,...I.reverse()],!0),t.fill(),t.restore()},u=(g,p)=>{const m=c++,b=h(m,99,!0);if(b.next()<a){const M=(b.next()*2-1)*e.lineWidth*1.4,$=(b.next()*2-1)*e.lineWidth*1.4,E=g.map(A=>({x:A.x+M,y:A.y+$}));d(E,A=>p(A)*1.8,h(m,98,!0),.035,i),d(E,A=>p(A)*.45,h(m,97,!0),.12,i*1.5)}const S=g.slice(1).reduce((M,$,E)=>M+Math.hypot($.x-g[E].x,$.y-g[E].y),0),k=p(.5)>4&&S>p(.5)*6,y=k?[-.3,.3,0]:[0];for(let M=0;M<o;M++){const $=M===0;y.forEach((E,A)=>{const T=h(m,M*10+A),I=E===0?g:am(g,P=>p(P)*E*Math.sqrt(Math.sin(Math.PI*P))),v=!$&&E===0?e.lineWidth*(.3+T.next()*.8):0;d(I,P=>p(P)*(k?.5:1)*($?1:.6),T,$?.85:.45,i*($?.6:1),v)})}},f=(g,p,m,b,S,k)=>{const M=h(c,50).next()*Math.PI*2;u(Ko(g,p,m,b,S,M,1.08,48),()=>k)};return{look:"pencil",ink:s,limb(g,p,m){u(g,b=>p+(m-p)*b)},line(g,p){u(g,()=>p)},shape(g,p,m){p!==null&&(t.save(),t.globalAlpha*=.88,t.fillStyle=p,Ws(t,g,!0),t.fill(),t.restore()),m>0&&u([...g,g[0]],()=>m)},ellipse(g,p,m,b,S,k,y){k!==null&&(t.save(),t.globalAlpha*=.9,t.fillStyle=k,t.beginPath(),t.ellipse(g,p,m,b,S,0,Math.PI*2),t.fill(),t.restore()),f(g,p,m,b,S,y)},dot(g,p,m){t.save(),t.globalAlpha*=.9,t.fillStyle=s,t.beginPath(),t.arc(g,p,m,0,Math.PI*2),t.fill(),t.restore()},guide(g){if(n.construction===!1||g.length<2)return;const p=c++;d(g,()=>Math.max(.6,e.lineWidth*.18),h(p,0),.28,i*1.2,e.lineWidth)},guideEllipse(g,p,m,b,S){if(n.construction===!1)return;const k=c++,y=h(k,0),M=Ko(g,p,m,b,S,y.next()*Math.PI*2,1.12,48);d(M,()=>Math.max(.6,e.lineWidth*.18),y,.28,i*1.5)}}}const Qc=["thumb","index","middle","ring","pinky"],vt={"thumb.curl":.15,"thumb.across":.15,"index.curl":.12,"middle.curl":.16,"ring.curl":.2,"pinky.curl":.25,spread:.25,turn:0,bend:0,tilt:0,roll:0};function Mt(t={}){return{...vt,...t}}const Nt=(t,e,n,s,i)=>({"thumb.curl":t,"index.curl":e,"middle.curl":n,"ring.curl":s,"pinky.curl":i}),Tt={relaxed:vt,open:Mt({...Nt(0,0,0,0,0),"thumb.across":0,spread:.55}),spread:Mt({...Nt(0,0,0,0,0),"thumb.across":0,spread:1}),flat:Mt({...Nt(0,0,0,0,0),"thumb.across":.35,spread:0}),fist:Mt({...Nt(.7,1,1,1,1),"thumb.across":.9,spread:0}),point:Mt({...Nt(.75,0,1,1,1),"thumb.across":.9,spread:0}),thumbsUp:Mt({...Nt(0,1,1,1,1),"thumb.across":0,spread:0,roll:70}),peace:Mt({...Nt(.75,0,0,1,1),"thumb.across":.9,spread:1}),ok:Mt({...Nt(.12,.6,.1,.15,.2),"thumb.across":.55,spread:.6}),pinch:Mt({...Nt(.1,.65,.75,.85,.9),"thumb.across":.55,spread:0}),cupped:Mt({...Nt(.25,.4,.4,.4,.4),"thumb.across":.4,spread:.05,turn:2}),wave:Mt({...Nt(0,.05,.05,.1,.12),"thumb.across":0,spread:.7,turn:2}),pencilGrip:Mt({...Nt(.1,.6,.72,.88,.95),"thumb.across":.5,spread:0,turn:.8,bend:10}),hold:Mt({...Nt(.5,.7,.72,.74,.76),"thumb.across":.75,spread:0,turn:1})};function ln(t,e,n){const s={...t};for(const[i,o]of Object.entries(e)){const r=t[i]??o;s[i]=r+(o-r)*n}return s}const cm={index:{knuckle:[-.16,.47,-.02],bones:[.2,.125,.1],width:.125,fan:-1},middle:{knuckle:[-.055,.49,-.02],bones:[.22,.135,.1],width:.13,fan:-.2},ring:{knuckle:[.05,.475,-.02],bones:[.2,.125,.1],width:.122,fan:.55},pinky:{knuckle:[.15,.43,-.02],bones:[.16,.1,.085],width:.108,fan:1.25}},hm={index:{knuckle:[-.14,.47,-.02],bones:[.2,.125,.1],width:.15,fan:-1},middle:{knuckle:[0,.49,-.02],bones:[.22,.135,.1],width:.155,fan:0},pinky:{knuckle:[.14,.45,-.02],bones:[.19,.115,.095],width:.145,fan:1}},te={base:[-.11,.1,-.05],bones:[.2,.15,.12],widths:[.2,.145,.135],out:[-.7,.68,-.22],across:[.35,.5,-.8]},dm=[82,100,62],um=[48,72],fm=3,pm=13,gm=.035,mm=-.075,ym=[[-.17,0],[-.215,.12],[-.235,.26],[-.225,.4],[-.185,.49],[-.075,.525],[.05,.51],[.16,.465],[.215,.4],[.225,.26],[.2,.1],[.16,0]],fe=t=>t*Math.PI/180,Yo=(t,e)=>[t[0]+e[0],t[1]+e[1],t[2]+e[2]],qs=(t,e)=>[t[0]*e,t[1]*e,t[2]*e],zo=(t,e)=>[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]],qn=t=>{const e=Math.hypot(t[0],t[1],t[2])||1;return[t[0]/e,t[1]/e,t[2]/e]};function pe(t,e,n){const s=Math.cos(n),i=Math.sin(n),o=zo(e,t),r=e[0]*t[0]+e[1]*t[1]+e[2]*t[2];return[t[0]*s+o[0]*i+e[0]*r*(1-s),t[1]*s+o[1]*i+e[1]*r*(1-s),t[2]*s+o[2]*i+e[2]*r*(1-s)]}const th=[1,0,0],eh=[0,1,0],Kn=[0,0,1];function bm(t,e,n){const s=fe(t.fan*(fm+pm*n)),i=[Math.sin(s),Math.cos(s),0],o=[Math.cos(s),-Math.sin(s),0],r=[t.knuckle];let a=0;t.bones.forEach((h,d)=>{a+=fe(dm[d]*e),r.push(Yo(r[d],qs(pe(i,o,-a),h)))});const l=pe(Kn,o,-a),c=r.map((h,d)=>t.width*(1-.14*(d/(r.length-1))));return{joints:r,back:l,widths:c}}function wm(t,e,n=1,s=1){const i=Math.min(1,Math.max(0,e)),o=qn(Yo(qs(qn(te.out),1-i),qs(qn(te.across),i))),r=qn(zo(Kn,o)),a=qn(zo(o,r)),l=[[te.base[0]*s,te.base[1],te.base[2]]];let c=0;te.bones.forEach((u,f)=>{f>0&&(c+=fe(um[f-1]*t)),l.push(Yo(l[f],qs(pe(o,r,c),u)))});const h=pe(a,r,c),d=[...te.widths,te.widths[te.widths.length-1]*.92].map(u=>u*n);return{joints:l,back:h,widths:d}}function Ks(t,e={}){const n={...vt,...t},s=e.size??100,i=e.side??"right",o=i==="left"?-1:1,r=fe(e.angle??0),a=e.fingers===4,l=Math.max(.5,e.plump??1),c=1+(l-1)*.7,h=P=>({...P,knuckle:[P.knuckle[0]*c,P.knuckle[1],P.knuckle[2]],width:P.width*l}),d=fe(n.bend??0),u=fe(n.tilt??0),f=fe(90*(n.turn??0)),g=P=>pe(pe(pe(P,th,-d),Kn,-u),eh,f),p=Math.cos(r),m=Math.sin(r),b=fe(n.roll??0),S=Math.cos(b),k=Math.sin(b),y=P=>{const H=P[0]*s,O=-P[1]*s,C=(H*S-O*k)*o,j=H*k+O*S;return{x:C*p-j*m,y:C*m+j*p}},M=P=>{const H=y(P),O=Math.hypot(H.x,H.y);return O>1e-6*s?{x:H.x/O,y:H.y/O}:{x:0,y:0}},$={thumb:wm(n["thumb.curl"]??0,n["thumb.across"]??0,l,c)},E=a?hm:cm;for(const P of Qc){const H=E[P];H&&($[P]=bm(h(H),n[`${P}.curl`]??0,n.spread??0))}const A={};for(const[P,H]of Object.entries($)){const O=H.joints.map(g),C=g(H.back);A[P]={points:O.map(y),depths:O.map(j=>j[2]*s),widths:H.widths.map(j=>j*s),nail:C[2],back:M(C)}}const T=ym.flatMap(([P,H])=>[g([P*c,H,gm]),g([P*c,H,mm])]),I=km(T.map(y)),v=T.reduce((P,H)=>P+H[2],0)/T.length*s;return{size:s,side:i,wrist:{x:0,y:0},palm:I,palmDepth:v,palmFacing:-g(Kn)[2],fingers:A,axes:{up:M(g(eh)),across:M(g(th)),out:M(g(Kn))},curls:Object.fromEntries(Object.keys(A).map(P=>[P,n[`${P}.curl`]??0]))}}function nh(t,e){const n=i=>({x:i.x+e.x-t.wrist.x,y:i.y+e.y-t.wrist.y}),s={};for(const[i,o]of Object.entries(t.fingers))s[i]={...o,points:o.points.map(n)};return{...t,wrist:n(t.wrist),palm:t.palm.map(n),fingers:s}}function km(t){const e=[...t].sort((o,r)=>o.x-r.x||o.y-r.y);if(e.length<3)return e;const n=(o,r,a)=>(r.x-o.x)*(a.y-o.y)-(r.y-o.y)*(a.x-o.x),s=[];for(const o of e){for(;s.length>=2&&n(s[s.length-2],s[s.length-1],o)<=0;)s.pop();s.push(o)}const i=[];for(const o of[...e].reverse()){for(;i.length>=2&&n(i[i.length-2],i[i.length-1],o)<=0;)i.pop();i.push(o)}return[...s.slice(0,-1),...i.slice(0,-1)]}const vm="#f1c9a5",Mm="#2f2f33";function Ys(t,e,n,s={},i=0){const o=nh(Ks(n,s),e),r=s.ink??Mm,a=s.lineWidth??o.size*.035,l=s.pen??Wn(t,{look:s.look??"clean",ink:r,lineWidth:a,seed:s.seed??1,time:i,pencil:{construction:!1,...s.pencil}}),c=s.skin??vm,h=s.nails??!0,d=[{depth:o.palmDepth,draw:()=>Sm(l,o,c,a)}];for(const u of Object.values(o.fingers)){const f=u.depths.reduce((g,p)=>g+p,0)/u.depths.length;d.push({depth:f,draw:()=>Tm(t,l,u,c,a,h)})}if(s.prop){const u=s.prop;d.push({depth:u.depth,draw:()=>u.draw(l)})}t.save(),t.lineCap="round",t.lineJoin="round";for(const u of[...d].sort((f,g)=>f.depth-g.depth))u.draw();return t.restore(),o}function Sm(t,e,n,s){if(t.shape(e.palm,n,s),e.palmFacing<-.3&&t.look!=="silhouette"){const{up:i}=e.axes;for(const[o,r]of Object.entries(e.fingers)){const a=e.curls[o]??0;if(o==="thumb"||a<.5)continue;const l=r.points[0],c=r.widths[0]*.42,h={x:l.x-i.x*c*.2,y:l.y-i.y*c*.2},d=Math.atan2(i.y,i.x),u=Array.from({length:7},(f,g)=>{const p=d-Math.PI/2+Math.PI*g/6;return{x:h.x+Math.cos(p)*c,y:h.y+Math.sin(p)*c}});t.line(u,s*.6)}}if(e.palmFacing>.45&&t.look!=="silhouette"){const{up:i,across:o}=e.axes,r=e.size,a=e.wrist,l=(h,d)=>({x:a.x+(o.x*h+i.x*d)*r,y:a.y+(o.y*h+i.y*d)*r}),c=e.side==="left"?-1:1;t.line([l(-.15*c,.36),l(-.04*c,.3),l(.1*c,.33)],s*.5)}}function Tm(t,e,n,s,i,o){const{widths:r}=n,a=Em(n.points,2),l=n.points[0],c=a[a.length-1],h=r[0],d=r[r.length-1];if(t.save(),e.look!=="silhouette"){t.beginPath(),t.rect(l.x-1e5,l.y-1e5,2e5,2e5);const p=h/2+i*1.6;t.moveTo(l.x+p,l.y),t.arc(l.x,l.y,p,0,Math.PI*2),t.clip("evenodd")}if(e.limb(a,h+2*i,d+2*i),t.restore(),e.look!=="silhouette"&&(t.fillStyle=s,Bs(t,a,h,d)),e.look==="silhouette"||!o||n.nail<.25)return;const u=a[a.length-2],f=Am({x:c.x-u.x,y:c.y-u.y})??{x:0,y:-1},g={x:c.x-f.x*d*.22+n.back.x*d*.1,y:c.y-f.y*d*.22+n.back.y*d*.1};e.ellipse(g.x,g.y,d*.24*Math.max(.35,n.nail),d*.19,Math.atan2(f.y,f.x),"#f8e3d3",i*.45)}function Em(t,e){let n=t;for(let s=0;s<e;s++){if(n.length<3)return n;const i=[n[0]];for(let o=0;o<n.length-1;o++){const r=n[o],a=n[o+1];o>0&&i.push({x:r.x*.75+a.x*.25,y:r.y*.75+a.y*.25}),o<n.length-2&&i.push({x:r.x*.25+a.x*.75,y:r.y*.25+a.y*.75})}i.push(n[n.length-1]),n=i}return n}const Am=t=>{const e=Math.hypot(t.x,t.y);return e>1e-6?{x:t.x/e,y:t.y/e}:null},Ot={walk:{swing:24,knee:30,arm:22,elbow:28,lean:4},bouncy:{swing:26,knee:45,arm:34,elbow:30,lean:2,bend:-4,bounce:.035,squash:.06},doubleBounce:{swing:22,knee:40,arm:26,elbow:24,lean:3,bounce:.02,bounces:2,squash:.04},sneak:{swing:28,knee:70,arm:6,elbow:0,forearm:110,shoulder:55,lean:16,bend:14,headTilt:-8,crouch:50,tiptoe:25},strut:{swing:26,knee:30,arm:30,elbow:20,lean:-4,bend:-10,headTilt:-6,sway:4,bounce:.01},tired:{swing:14,knee:14,arm:6,elbow:6,lean:10,bend:16,headTilt:12},run:{swing:40,knee:95,arm:45,elbow:0,forearm:90,lean:16,bend:6,bounce:.05,squash:.06},shove:{swing:18,knee:28,arm:0,elbow:0,lean:0}},$m=40;function Yn(t){return t===void 0?Ot.walk:typeof t=="string"?Ot[t]??Ot.walk:t}function sh(t,e,n=et,s=1){const i=Yn(t);if(i===Ot.walk)return lh(e,n,s);const o=e*Math.PI*2,r=Math.sin(o)*s,a=Math.cos(o)*s,l=b=>Math.abs(b)<=$m,c=i.shoulder??0,h=(b,S)=>l(b)?S*c+i.arm*r:b,d=i.forearm??0,u=l(n.leftShoulder)?n.leftElbow-d-i.elbow*Math.max(0,-r):n.leftElbow,f=l(n.rightShoulder)?n.rightElbow+d+i.elbow*Math.max(0,r):n.rightElbow,g=i.bounces??1,p=(1+Math.cos(o*2*g))/2,m=i.crouch??0;return{...n,lean:n.lean+i.lean*s+(i.sway??0)*Math.sin(o)*(1-(n.turn??0)),bend:(n.bend??0)+(i.bend??0),headTilt:n.headTilt-i.lean*.5*s+(i.headTilt??0),leftElbow:u,rightElbow:f,leftHip:-i.swing*r-m*.5,rightHip:-i.swing*r+m*.5,leftKnee:-i.knee*Math.max(0,a)-m,rightKnee:i.knee*Math.max(0,-a)+m,leftAnkle:(n.leftAnkle??0)+(i.tiptoe??0),rightAnkle:(n.rightAnkle??0)+(i.tiptoe??0),leftShoulder:h(n.leftShoulder,-1),rightShoulder:h(n.rightShoulder,1),rise:(n.rise??0)+(i.bounce??0)*s*p,stretch:n.stretch*(1+(i.squash??0)*(p-.5))}}function Xo(t,e,n=1){const s=Yn(t),i=Ot.walk.swing,o=r=>Math.sin(r*Math.PI/180);return ch(e,n)*o(s.swing*n)/o(i*n)}const et={lean:0,bend:0,headTilt:0,leftShoulder:18,rightShoulder:18,leftElbow:-6,rightElbow:-6,leftHip:8,rightHip:8,leftKnee:0,rightKnee:0,leftWrist:0,rightWrist:0,leftAnkle:0,rightAnkle:0,leftFootOut:0,rightFootOut:0,mouth:0,smile:.6,mouthWidth:1,blink:0,leftEye:1,rightEye:1,leftBrow:0,rightBrow:0,browTilt:0,lookX:0,lookY:0,stretch:1,turn:0,sit:0,spin:0,rise:0};function Et(t){return{...et,...t}}const ih={mouth:0,smile:0,mouthWidth:1,leftEye:1,rightEye:1,leftBrow:0,rightBrow:0,browTilt:0,lookX:0,lookY:0},Pt=t=>({...ih,...t}),ct={neutral:ih,happy:Pt({smile:.9,leftBrow:.2,rightBrow:.2}),joyful:Pt({mouth:.6,smile:1,mouthWidth:1.2,leftEye:0,rightEye:0,leftBrow:.4,rightBrow:.4}),sad:Pt({smile:-.8,leftEye:.8,rightEye:.8,browTilt:.9,leftBrow:-.1,rightBrow:-.1,lookY:.6}),crying:Pt({mouth:.45,smile:-1,leftEye:0,rightEye:0,browTilt:1,lookY:.4}),surprised:Pt({mouth:.7,mouthWidth:.7,leftEye:1.5,rightEye:1.5,leftBrow:1,rightBrow:1}),shocked:Pt({mouth:1,mouthWidth:.8,leftEye:1.6,rightEye:1.6,leftBrow:1,rightBrow:1,browTilt:.4}),angry:Pt({smile:-.6,mouthWidth:.9,leftEye:.8,rightEye:.8,leftBrow:-.6,rightBrow:-.6,browTilt:-1}),furious:Pt({mouth:.5,smile:-1,mouthWidth:1.3,leftEye:.9,rightEye:.9,leftBrow:-.9,rightBrow:-.9,browTilt:-1}),worried:Pt({smile:-.3,mouthWidth:.8,leftEye:1.1,rightEye:1.1,leftBrow:.3,rightBrow:.3,browTilt:.8,lookX:-.5}),scared:Pt({mouth:.35,smile:-.5,mouthWidth:.8,leftEye:1.45,rightEye:1.45,leftBrow:.8,rightBrow:.8,browTilt:.9}),confused:Pt({smile:-.2,mouthWidth:.8,leftEye:.9,rightEye:1.15,leftBrow:-.3,rightBrow:.8,lookX:.5,lookY:-.4}),skeptical:Pt({smile:-.1,leftEye:.6,rightEye:1,leftBrow:-.4,rightBrow:.7,lookX:.4}),thinking:Pt({smile:0,mouthWidth:.7,leftBrow:.3,rightBrow:.5,lookX:.6,lookY:-.8}),sleepy:Pt({smile:.1,leftEye:.25,rightEye:.25,leftBrow:-.3,rightBrow:-.3,lookY:.5}),disgusted:Pt({smile:-.7,mouthWidth:.9,leftEye:.6,rightEye:.75,leftBrow:-.5,rightBrow:-.2,browTilt:-.4,lookX:-.6}),smug:Pt({smile:.6,mouthWidth:.9,leftEye:.6,rightEye:.6,leftBrow:.1,rightBrow:.5,lookX:.5}),wink:Pt({smile:.9,leftEye:0,rightEye:1,leftBrow:-.2,rightBrow:.3})};function ge(t,e){return{...t,...typeof e=="string"?ct[e]:e}}const Dt={rest:et,wave:Et({rightShoulder:135,rightElbow:30,headTilt:6,...ct.happy}),cheer:Et({leftShoulder:125,leftElbow:20,rightShoulder:125,rightElbow:20,...ct.joyful}),shrug:Et({leftShoulder:30,leftElbow:85,rightShoulder:30,rightElbow:85,headTilt:-10,...ct.confused,lookX:0,lookY:0}),point:Et({rightShoulder:90,rightElbow:0,lean:4,smile:.4}),think:Et({rightShoulder:60,rightElbow:150,headTilt:10,...ct.thinking}),handsOnHips:Et({leftShoulder:45,leftElbow:-100,rightShoulder:45,rightElbow:-100,leftHip:14,rightHip:14,smile:.8}),sad:Et({leftShoulder:14,rightShoulder:14,leftElbow:-4,rightElbow:-4,headTilt:-14,lean:-3,...ct.sad}),surprised:Et({leftShoulder:70,leftElbow:60,rightShoulder:70,rightElbow:60,...ct.surprised}),crouch:Et({stretch:.72,leftShoulder:35,rightShoulder:35,leftElbow:-50,rightElbow:-50,leftHip:22,rightHip:22,headTilt:-4}),sit:Et({sit:1,turn:.5,leftShoulder:-25,rightShoulder:25,leftElbow:-55,rightElbow:55}),jump:Et({stretch:1.22,leftShoulder:140,rightShoulder:140,leftElbow:20,rightElbow:20,leftHip:4,rightHip:4,...ct.joyful}),duck:Et({stretch:.62,bend:28,headTilt:-8,leftShoulder:150,rightShoulder:150,leftElbow:130,rightElbow:130,leftHip:25,rightHip:25,...ct.scared}),lie:Et({spin:-90,rise:-.42,leftShoulder:165,rightShoulder:165,leftElbow:150,rightElbow:150,...ct.sleepy}),sideSplit:Et({leftHip:90,rightHip:90,leftAnkle:-45,rightAnkle:-45,leftShoulder:120,rightShoulder:120,leftElbow:10,rightElbow:10,...ct.happy}),frontSplit:Et({turn:1,leftHip:-90,rightHip:-90,leftAnkle:-45,rightAnkle:-45,leftShoulder:-150,rightShoulder:150,leftElbow:10,rightElbow:-10,...ct.happy})},oh=Object.keys(et);function cn(t,e,n){const s={...t};for(const i of oh)s[i]=t[i]+(e[i]-t[i])*n;return s}const Uo=24,rh=4,ah=28,Pm=40;function lh(t,e=et,n=1){const s=Math.sin(t*Math.PI*2)*n,i=Math.cos(t*Math.PI*2)*n,o=c=>Math.abs(c)<=Pm,r=c=>o(c)?22*s:c,a=o(e.leftShoulder)?e.leftElbow-ah*Math.max(0,-s):e.leftElbow,l=o(e.rightShoulder)?e.rightElbow+ah*Math.max(0,s):e.rightElbow;return{...e,lean:e.lean+rh*n,headTilt:e.headTilt-rh*.5*n,leftElbow:a,rightElbow:l,leftHip:-Uo*s,rightHip:-Uo*s,leftKnee:-30*Math.max(0,i),rightKnee:30*Math.max(0,-i),leftShoulder:r(e.leftShoulder),rightShoulder:r(e.rightShoulder)}}function ch(t,e=1){return 4*((Go+zs)*t)*Math.sin(Uo*e*Math.PI/180)}function hh(t){const e=Math.abs(Math.sin(t/65)),n=.55+.45*Math.sin(t/310);return e*n}const dh=.12,uh=.46,xm=1-2*dh,Im=.1,Om=.21,_m=.19,Go=.24,zs=.22,fh=.12,Cm=.14,ph=.33,gh=.7,mh=.3,Hm=.35,Rm=[1.7,1.05],Lm=[1.3,.75],yh=[1.45,.85],Nm=[1.15,.75],bh=.06,Dm=.7,Fm=.65,wh=.075,jm=.3,Bm=.02,Wm=.012,qm=12,Km=.25,Xs=90,Ym=.25,zm=.04,kh=.01,He=t=>Math.min(1,Math.max(0,t??0));function Xm(t,e=1){return zs*t*e}const Vo=-.12,vh=.4,Kt=t=>t*Math.PI/180,Um=(t,e)=>({x:e*Math.sin(Kt(t)),y:Math.cos(Kt(t))}),Mh=(t,e)=>Math.max(0,t)*(1-Math.min(1,Math.max(0,e))),Sh=(t,e,n,s)=>t-.3*e-n*.14*e-Math.max(0,s-1)*.12*e;function Gm(t,e,n,s,i,o){const r=Math.max(1,Math.min(o*.6,Cm*n)),a=He(e.turn),l=(fh+ph*a)*n,c=s+Vo*n,h=l+e.lookX*.08*n,d=e.lookY*.07*n,u=[{x:-.34*n*(1-gh*a),squeeze:1-gh*a,open:e.leftEye,brow:e.leftBrow,side:-1},{x:.34*n*(1-mh*a),squeeze:1-mh*a,open:e.rightEye,brow:e.rightBrow,side:1}];t.fillStyle=i,t.strokeStyle=i,t.lineWidth=r;for(const b of u){const S=Mh(b.open,e.blink);if(S<.2){const $=e.smile>.5?-.12*n:.06*n;t.beginPath(),t.moveTo(b.x+l-.12*n,c),t.quadraticCurveTo(b.x+l,c+$,b.x+l+.12*n,c),t.stroke()}else{if(S>1.2){const E=.13*n*S;t.beginPath(),t.ellipse(b.x+l,c,E*.85,E,0,0,Math.PI*2),t.fillStyle="#ffffff",t.fill(),t.stroke(),t.fillStyle=i}const $=S>1.2?.075*n:.1*n;t.beginPath(),t.ellipse(b.x+h,c+d,$,$*1.1*Math.min(S,1),0,0,Math.PI*2),t.fill()}const k=Sh(c,n,b.brow,S),y=b.x+l-b.side*.13*n*b.squeeze,M=b.x+l+b.side*.13*n*b.squeeze;t.beginPath(),t.moveTo(M,k),t.lineTo(y,k-e.browTilt*.1*n),t.stroke()}const f=s+vh*n,g=.25*n*Math.max(.3,e.mouthWidth)*(1-Hm*a),p=Math.min(1,Math.max(0,e.mouth));if(t.beginPath(),p<=.05){t.moveTo(l-g,f),t.quadraticCurveTo(l,f+e.smile*.25*n,l+g,f),t.stroke();return}const m=.3*n*p;e.smile>.3?(t.moveTo(l-g,f-.05*n),t.lineTo(l+g,f-.05*n),t.quadraticCurveTo(l,f+m*2,l-g,f-.05*n)):e.smile<-.3?(t.moveTo(l-g,f+m*.6),t.lineTo(l+g,f+m*.6),t.quadraticCurveTo(l,f-m*1.4,l-g,f+m*.6)):t.ellipse(l,f,g*.8,m,0,0,Math.PI*2),t.fill()}function Th(t,e){const n=e.height??300,s=Math.min(3,Math.max(.3,t.stretch??1)),i=Math.sqrt(s),o=(e.headSize??2*dh)/2,r=e.headSize===void 0?xm:1-2*o,a=o*n,l=He(t.sit),c=t.leftHip+(-Xs-t.leftHip)*l,h=t.leftKnee+(-Xs-t.leftKnee)*l,d=t.rightHip+(Xs-t.rightHip)*l,u=t.rightKnee+(Xs-t.rightKnee)*l,f=e.classic===!0,g=He(t.turn),p=(W,B,_,L,N)=>{const x=Math.max(-Math.PI/2,Math.min(Math.PI/2,Math.abs(Kt(B-_)/2)+Kt(L))),R=Math.max(-1,Math.min(1,Dm+N)),q=g+(1-g)*W*R;return f?{x:0,y:0}:{x:Math.cos(x)*bh*q,y:Math.sin(x)*bh}},m={left:t.leftAnkle??0,right:t.rightAnkle??0},b={left:t.leftFootOut??0,right:t.rightFootOut??0};let S=0;if(l>0||!f){const W=(N,x,R,q,U)=>Go*Math.cos(Kt(x))+zs*Math.cos(Kt(x-R))+Math.max(0,p(N,x,R,q,U).y),B=Math.max(W(-1,c,h,m.left,b.left),W(1,d,u,m.right,b.right)),_=1-He((t.rise??0)/zm),L=(f?Math.min(1,l/Ym):1)*_;S=(uh-B)*L*n*s}const k=-uh*n*s+S,y=-r*n*s+S,M=f?0:(Bm*He(t.turn)+Wm*l)*n*s,$=Kt(t.bend??0),E={end:Ah(k,y,$,1),bend:$};let A;if($!==0){A=[];for(let W=0;W<=Eh;W++){const B=W/Eh,_=Ah(k,y,$,B);A.push({x:_.x-M*Math.sin(Math.PI*B),y:_.y})}}else A=M===0?[{x:0,y:k},{x:0,y}]:Ce({x:0,y:k},{x:-M,y:(k+y)/2},{x:0,y},1,8);const T=y+Im*n*s,I=(e.shoulderWidth??0)*n*Math.cos(g*Math.PI/2),v=(W,B,_,L,N)=>{const x=Um(_,L);return{x:W+x.x*N*n,y:B+x.y*N*n}},P=(W,B,_)=>{const L=v(0,k,B,W,Go*s);return{root:{x:0,y:k},joint:L,end:v(L.x,L.y,B-_,W,zs*s)}},H=(W,B,_)=>{const L={x:W*I,y:T},N=v(L.x,L.y,B,W,Om*i);return{root:L,joint:N,end:v(N.x,N.y,B+_,W,_m*i)}},O={left:P(-1,c,h),right:P(1,d,u)},C=(W,B,_,L,N,x)=>{const R=p(W,_,L,N,x);return{x:B.end.x+R.x*n*s,y:B.end.y+R.y*n*s}},j=(W,B,_,L,N)=>v(B.end.x,B.end.y,_+L+N,W,wh*i),D={left:H(-1,t.leftShoulder,t.leftElbow),right:H(1,t.rightShoulder,t.rightElbow)};return{height:n,facing:(e.facing??1)<0?-1:1,stretch:s,lineWidth:e.lineWidth??n*.025,rubber:Math.min(1,Math.max(f?0:jm,e.rubber??0)),r:a,headRx:a/Math.sqrt(s),headRy:a*Math.sqrt(s),hipY:k,neckY:y,drop:S,lean:f?t.lean:t.lean+qm*Math.sin(Math.PI*l),classic:f,legs:O,toes:{left:C(-1,O.left,c,h,m.left,b.left),right:C(1,O.right,d,u,m.right,b.right)},spine:A,chest:E,arms:D,handTips:{left:j(-1,D.left,t.leftShoulder,t.leftElbow,t.leftWrist??0),right:j(1,D.right,t.rightShoulder,t.rightElbow,t.rightWrist??0)}}}const Eh=10;function Ah(t,e,n,s){const i=t-e,o=n*s;if(Math.abs(n)<1e-9)return{x:0,y:t-i*s};const r=i/n;return{x:r*(1-Math.cos(o)),y:t-r*Math.sin(o)}}function Vm(t,e){if(t.chest.bend===0)return e;const n=Xn(e,{x:0,y:t.neckY},t.chest.bend);return{x:n.x+t.chest.end.x,y:n.y+t.chest.end.y-t.neckY}}const zn=(t,e)=>e===0?[t.root,t.joint,t.end]:Ce(t.root,t.joint,t.end,e);function Xn(t,e,n){const s=Math.cos(n),i=Math.sin(n),o=t.x-e.x,r=t.y-e.y;return{x:e.x+o*s-r*i,y:e.y+o*i+r*s}}function $h(t,e,n=!0){const s=Zm(t,e),i=e.spin??0,o=e.rise??0;return n&&(i!==0||o!==0)?Jm(s,t,i,o):s}function Ph(t,e,n){return{pivot:{x:0,y:t.hipY},angle:t.facing*Kt(e),lift:n*t.height}}function Jm(t,e,n,s){const{pivot:i,angle:o,lift:r}=Ph(e,n,s),a=u=>{const f=Xn(u,i,o);return{x:f.x,y:f.y-r}},l=u=>({left:a(u.left),right:a(u.right)}),c={left:Math.max(a(t.feet.left).y,a(t.toes.left).y),right:Math.max(a(t.feet.right).y,a(t.toes.right).y)},h=Math.max(c.left,c.right),d=kh*e.height;return{...t,hip:a(t.hip),neck:a(t.neck),shoulders:l(t.shoulders),elbows:l(t.elbows),hands:l(t.hands),fingertips:l(t.fingertips),knees:l(t.knees),feet:l(t.feet),toes:l(t.toes),feetY:h,grounded:{left:c.left>=h-d,right:c.right>=h-d},handAngle:{left:t.handAngle.left+o,right:t.handAngle.right+o},limbs:{leftArm:t.limbs.leftArm.map(a),rightArm:t.limbs.rightArm.map(a),leftLeg:t.limbs.leftLeg.map(a),rightLeg:t.limbs.rightLeg.map(a),spine:t.limbs.spine.map(a)},head:{...t.head,center:a(t.head.center),angle:t.head.angle+o}}}function Zm(t,e){const n=Kt(t.lean),s=Kt(e.headTilt),i={x:0,y:t.hipY},o=y=>({x:t.facing*y.x,y:y.y}),r=y=>o(Xn(y,i,n)),a=y=>r(Vm(t,y)),l=y=>a(Xn({x:y.x,y:y.y+t.neckY},{x:0,y:t.neckY},s)),c=zn(t.arms.left,t.rubber).map(a),h=zn(t.arms.right,t.rubber).map(a),d=(y,M)=>Math.atan2(M.y-y.y,M.x-y.x),u={left:a(t.handTips.left),right:a(t.handTips.right)},f=(y,M)=>{const[$,E]=y.slice(-2),A=t.arms[M],T=d(a(A.end),u[M])-d(a(A.joint),a(A.end));return d($,E)+T};let g=1/0;for(const[y,M]of[[e.leftBrow,e.leftEye],[e.rightBrow,e.rightEye]]){const $=Sh(Vo,1,y,Mh(M,e.blink));g=Math.min(g,$,$-e.browTilt*.1)}const p={left:o(t.legs.left.end),right:o(t.legs.right.end)},m={left:o(t.toes.left),right:o(t.toes.right)},b={left:Math.max(p.left.y,m.left.y),right:Math.max(p.right.y,m.right.y)},S=Math.max(b.left,b.right),k=kh*t.height;return{facing:t.facing,height:t.height,stretch:t.stretch,lineWidth:t.lineWidth,hip:i,neck:a({x:0,y:t.neckY}),shoulders:{left:a(t.arms.left.root),right:a(t.arms.right.root)},elbows:{left:a(t.arms.left.joint),right:a(t.arms.right.joint)},hands:{left:a(t.arms.left.end),right:a(t.arms.right.end)},knees:{left:o(t.legs.left.joint),right:o(t.legs.right.joint)},feet:p,toes:m,feetY:S,grounded:{left:b.left>=S-k,right:b.right>=S-k},fingertips:u,handAngle:{left:f(c,"left"),right:f(h,"right")},limbs:{leftArm:c,rightArm:h,leftLeg:zn(t.legs.left,t.rubber).map(o),rightLeg:zn(t.legs.right,t.rubber).map(o),spine:t.spine.map(r)},head:{center:l({x:0,y:-t.headRy}),rx:t.headRx,ry:t.headRy,angle:t.facing*(n+t.chest.bend+s),eyeY:Vo,browTopY:g,mouthY:vh,faceX:t.facing*(fh+ph*He(e.turn))}}}function me(t,e={}){return $h(Th(t,e),t)}function Qm(t,e,n){return Xn({x:t.center.x+e*t.rx,y:t.center.y+n*t.ry},t.center,t.angle)}function xh(t,e,n){const s=o=>({x:o.x+e,y:o.y+n}),i=o=>({left:s(o.left),right:s(o.right)});return{...t,hip:s(t.hip),neck:s(t.neck),shoulders:i(t.shoulders),elbows:i(t.elbows),hands:i(t.hands),fingertips:i(t.fingertips),knees:i(t.knees),feet:i(t.feet),toes:i(t.toes),feetY:t.feetY+n,grounded:{...t.grounded},handAngle:{...t.handAngle},limbs:{leftArm:t.limbs.leftArm.map(s),rightArm:t.limbs.rightArm.map(s),leftLeg:t.limbs.leftLeg.map(s),rightLeg:t.limbs.rightLeg.map(s),spine:t.limbs.spine.map(s)},head:{...t.head,center:s(t.head.center)}}}function Ih(t,e,n={},s=0){const i=Th(e,n),o=n.color??"#1e293b",r=n.layers??{},a=n.layers?$h(i,e,!1):void 0,l=n.sketch?js(t,n.sketch,s):void 0,c=n.sketch&&n.layers?js(t,n.sketch,s):void 0,h=E=>{t.save(),E(),t.restore()},d=E=>{E&&a&&h(()=>E(t,a,s,c))},u=()=>t.scale(i.facing,1),f=()=>{u(),t.translate(0,i.hipY),t.rotate(Kt(i.lean)),t.translate(0,-i.hipY)},g=()=>{f(),i.chest.bend!==0&&(t.translate(i.chest.end.x,i.chest.end.y),t.rotate(i.chest.bend),t.translate(0,-i.neckY))},p=(E,A,T)=>{if(l)return A?l.curve(E):l.line(E);if(i.classic){t.beginPath(),t.moveTo(E[0].x,E[0].y);for(const I of E.slice(1))t.lineTo(I.x,I.y);t.stroke();return}Bs(t,E,T[0]*i.lineWidth,T[1]*i.lineWidth)},m=(E,A)=>p(zn(E,i.rubber),i.rubber>0,A),b=E=>{i.classic||p([i.legs[E].end,i.toes[E]],!1,Nm)},S=E=>{if(n.hands&&!i.classic)return y(E);if(i.classic||l)return;const A=i.arms[E].end;t.beginPath(),t.arc(A.x,A.y,Fm*i.lineWidth,0,Math.PI*2),t.fill()};t.save(),t.strokeStyle=o,t.fillStyle=o,t.lineWidth=i.lineWidth,t.lineCap="round",t.lineJoin="round";const k=Ph(i,e.spin??0,e.rise??0);(k.angle!==0||k.lift!==0)&&(t.translate(0,-k.lift),t.translate(k.pivot.x,k.pivot.y),t.rotate(k.angle),t.translate(-k.pivot.x,-k.pivot.y));function y(E){const A=n.hands??{},T=i.arms[E].end,I=i.handTips[E],v=n.headFill??"#ffffff";Ys(t,T,A[E]??vt,{side:E,angle:Math.atan2(I.x-T.x,T.y-I.y)*180/Math.PI,size:(A.size??wh)*i.height*Math.sqrt(i.stretch),skin:A.skin??(v==="none"?void 0:v),ink:o,lineWidth:i.lineWidth*.45,fingers:A.fingers,plump:A.plump,look:n.sketch?"pencil":"clean",seed:n.sketch?.seed},s)}const M=E=>{h(()=>{g(),m(i.arms[E],Lm),S(E)});const A=r.sleeve;A&&a&&h(()=>A(t,a,E,s,c))},$=He(e.turn)>Km;d(r.behind),h(()=>{u(),m(i.legs.left,yh),b("left"),m(i.legs.right,yh),b("right")}),$&&M("left"),h(()=>{f(),p(i.spine,i.spine.length>2,Rm)}),h(()=>{g();const{left:E,right:A}={left:i.arms.left.root,right:i.arms.right.root};if(E.x!==A.x)if(i.classic)p([E,A],!1,[1,1]);else{const T={x:(E.x+A.x)/2,y:E.y-.3*Math.abs(A.x-E.x)};p(Ce(E,T,A,1,8),!0,[1.1,1.1])}}),d(r.body),$||M("left"),M("right"),d(r.behindHead),h(()=>{g(),t.translate(0,i.neckY),t.rotate(Kt(e.headTilt));const E=-i.headRy;t.beginPath(),t.ellipse(0,E,i.headRx,i.headRy,0,0,Math.PI*2);const A=n.headFill??"#ffffff";if(A!=="none"&&(t.fillStyle=A,t.fill()),l){l.ellipse(0,E,i.headRx,i.headRy);const T=l.nudge();t.translate(T.x,T.y)}else t.stroke();t.translate(0,E),t.scale(i.headRx/i.r,i.headRy/i.r),Gm(t,e,i.r,0,o,i.lineWidth)}),d(r.overHead),d(r.front),t.restore(),n.label&&(t.save(),t.fillStyle=o,t.font=n.labelFont??`700 ${Math.round(i.height*.11)}px sans-serif`,t.textAlign="center",t.textBaseline="bottom",t.fillText(n.label,0,-i.height*i.stretch-.04*i.height+i.drop),t.restore())}function Jo(t,e,n,s){const i={...t},o=t.gait&&s?.[t.gait]||t.gait;let r=t.walking>0?cn(i,sh(o,t.walk,i),t.walking):i,a=t1(t);const l=t.dancing??0;if(n&&l>0){const c=n(t.beat??0);if(r=cn(r,c.pose,l),c.hands){const h=(d,u)=>u?ln(d??vt,u,l):d;a={left:h(a?.left,c.hands.left),right:h(a?.right,c.hands.right)}}}return t.talk>0&&(r={...r,mouth:Math.max(r.mouth,t.talk*hh(e))}),{pose:r,hands:a}}function Oh(t,e,n,s){return Jo(t,e,n,s).pose}const _h=(t,e)=>(t.facing??e.facing??1)<0?-1:1,Un=(t,e)=>`hand.${t}.${e}`;function t1(t){const e=i=>{if(typeof t[Un(i,"spread")]=="number")return Object.fromEntries(Object.keys(vt).map(o=>[o,t[Un(i,o)]]))},n=e("left"),s=e("right");return n||s?{left:n,right:s}:void 0}function e1(t,e){return!e||!t.hands?t:{...t,hands:{...t.hands,left:e.left??t.hands.left,right:e.right??t.hands.right}}}function Zo(t){const e=t.style??{},n=e.height??300,s=n*.8,i={...Et(t.pose??{}),walk:0,walking:0,gait:"walk",facing:(e.facing??1)<0?-1:1,talk:0,rubber:e.rubber??0,beat:0,dancing:0},o={};if(e.hands)for(const r of["left","right"]){const a=e.hands[r]??vt;for(const l of Object.keys(vt))o[Un(r,l)]=a[l]??vt[l]}return{type:"custom",x:t.x-s/2,y:t.y-n,width:s,height:n,props:{...i,...o},about:n1(Object.keys(o),t.cast),figureStyle:e,figureDance:t.dance,figureGaits:t.cast?.gaits,draw(r,a,l){const c=a.props,h=Jo(c,l,t.dance,t.cast?.gaits);r.translate(s/2,n),Ih(r,h.pose,e1({...e,rubber:c.rubber,facing:_h(c,e)},h.hands),l)}}}function n1(t,e){const n={...zc,...Xc};for(const s of t){const[,i,...o]=s.split("."),r=Uc[o.join(".")];r&&(n[s]={...r,description:`${i==="left"?"Left":"Right"} hand: ${r.description.toLowerCase()}`})}return{kind:"stick figure",summary:"A poseable stick figure: pose it with joint tracks, or give it beats (`scriptTracks`) that compile into acted tracks.",props:n,get actions(){return nm(e)}}}function Qo(t,e,n){const s=t.figureStyle;if(!s)throw new Error("stickFigureAt: the target was not made by stickFigureTarget");const i={...t.props};let o=0,r=0;for(const[c,h]of e.state?.values.get(n)??[])c==="gait"&&typeof h=="string"&&(i.gait=h),typeof h=="number"&&(c==="x"||c==="motionPathX"?o=h:c==="y"||c==="motionPathY"?r=h:c in i&&(i[c]=h));const a=Oh(i,e.time,t.figureDance,t.figureGaits),l=me(a,{...s,rubber:i.rubber,facing:_h(i,s)});return{pose:a,joints:xh(l,t.x+o+t.width/2,t.y+r+t.height)}}function tr(t){const e=[];return t.forEach((n,s)=>{const i=s===0?et:e[s-1],o=typeof n.pose=="string"?Dt[n.pose]:{...i,...n.pose};e.push(n.expression?ge(o,n.expression):o)}),e}function s1(t,e){const n=tr(e);return oh.filter(s=>n.some(i=>i[s]!==et[s])).map(s=>({id:`${t}-${s}`,target:t,property:s,keyframes:e.map((i,o)=>({time:i.time,value:n[o][s],...i.easing?{easing:i.easing}:{}}))}))}const er=.5,Us={pataka:Mt({"thumb.curl":.3,"thumb.across":.6,"index.curl":0,"middle.curl":0,"ring.curl":0,"pinky.curl":0,spread:0,turn:2}),tripataka:Mt({"thumb.curl":.3,"thumb.across":.6,"index.curl":0,"middle.curl":0,"ring.curl":1,"pinky.curl":0,spread:0,turn:2}),alapadma:Mt({"thumb.curl":.1,"thumb.across":0,"index.curl":.05,"middle.curl":.15,"ring.curl":.25,"pinky.curl":.35,spread:1,turn:2}),mushti:Tt.fist,shikhara:Tt.thumbsUp,hamsasya:Mt({"thumb.curl":.15,"thumb.across":.6,"index.curl":.6,"middle.curl":0,"ring.curl":0,"pinky.curl":0,spread:.7,turn:2}),katakamukha:Mt({"thumb.curl":.2,"thumb.across":.6,"index.curl":.65,"middle.curl":.7,"ring.curl":0,"pinky.curl":0,spread:.4,turn:2})};function Gs(t){return typeof t!="string"?t:t in Us?Us[t]:Tt[t]}function Ch(t,e,n){const s=[];for(const i of t.keys){const o=s[s.length-1],r=!o||i.reset?{pose:e,...n}:o;s.push({beat:i.beat,pose:{...r.pose,...i.pose},left:i.hands?.left?Gs(i.hands.left):r.left,right:i.hands?.right?Gs(i.hands.right):r.right,easing:i.easing??t.easing})}return s}const nr=(t,e)=>(t%e+e)%e;function i1(t,e,n,s){const i=Ch(t,n,s);if(i.length===0)return{pose:n,hands:s};const o=nr(e,t.beats);let r=i.length-1;for(let f=0;f<i.length;f++)i[f].beat<=o&&(r=f);const a=i[r],l=i[(r+1)%i.length],c=a.beat<=o?a.beat:a.beat-t.beats,h=l.beat>c?l.beat:l.beat+t.beats,d=h>c?(o-c)/(h-c):0,u=xt(l.easing??"ease-in-out")(Math.min(1,Math.max(0,d)));return{pose:cn(a.pose,l.pose,u),hands:{left:ln(a.left,l.left,u),right:ln(a.right,l.right,u)}}}const o1=[["leftShoulder","rightShoulder"],["leftElbow","rightElbow"],["leftWrist","rightWrist"],["leftHip","rightHip"],["leftKnee","rightKnee"],["leftAnkle","rightAnkle"],["leftFootOut","rightFootOut"],["leftEye","rightEye"],["leftBrow","rightBrow"]],r1=["lean","headTilt","lookX","spin"],a1=new Set(["leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee"]);function Hh(t){const e={...t},n=(t.turn??0)>=.5;for(const[s,i]of o1){const o=n&&a1.has(s)?-1:1;e[s]=o*t[i],e[i]=o*t[s]}if(!n)for(const s of r1)e[s]=-t[s];return e}const l1=t=>Math.min(1,Math.max(-1,(.5-t)*4));function Rh(t,e,n){const s=nr(n,1),i=(1+Math.cos(2*Math.PI*s))/2,o=e.bounce*(e.accent==="up"?1-i:i),r=Math.min(1,Math.max(0,t.turn??0)),a=l1(r);return{...t,leftHip:t.leftHip+a*o/2,rightHip:t.rightHip+o/2,leftKnee:t.leftKnee+a*o,rightKnee:t.rightKnee+o,lean:t.lean+(e.sway??0)*(1-r)*Math.sin(Math.PI*n)}}function Vs(t){const e={...et,...t.stance};return t.expression?ge(e,t.expression):e}function Lh(t){return{left:t.hands?.left?Gs(t.hands.left):vt,right:t.hands?.right?Gs(t.hands.right):vt}}function sr(t,e,n){const s=t.moves[e.move];if(!s)throw new Error(`dance: "${t.label}" has no move "${e.move}"`);const i=i1(s,n,Vs(t),Lh(t));return e.mirror?{pose:Hh(i.pose),hands:{left:i.hands?.right,right:i.hands?.left}}:i}function Js(t,e,n={}){const s=typeof t=="string"?ye[t]:t;let i;if(n.move)i=sr(s,{move:n.move,mirror:n.mirror},e);else{const o=s.routine,r=o.reduce((d,u)=>d+u.beats,0),a=nr(e,r);let l=0,c=0;for(;c<o.length-1&&a>=l+o[c].beats;)l+=o[c++].beats;const h=a-l;if(i=sr(s,o[c],h),h<er&&o.length>1&&e>=er){const d=o[(c-1+o.length)%o.length],u=sr(s,d,d.beats+h),f=xt("ease-in-out")(h/er);i={pose:cn(u.pose,i.pose,f),hands:{left:ln(u.hands.left,i.hands.left,f),right:ln(u.hands.right,i.hands.right,f)}}}}return{...i,pose:Rh(i.pose,s.groove,e)}}function c1(t,e,n={}){return Js(t,e,n).pose}function Zs(t){return(typeof t=="string"?ye[t]:t).routine.reduce((n,s)=>n+s.beats,0)}const h1={leftToe:"rightToe",rightToe:"leftToe",leftHeel:"rightHeel",rightHeel:"leftHeel"};function Nh(t,e,n,s,i,o,r){for(let a=0;a*t.beats<n;a++)for(const l of t.keys){const c=a*t.beats+l.beat,h=e+c;if(!(c>=n||h<o||h>=r))for(const d of l.taps??[])i.push({beat:h,tap:s?h1[d]:d})}}function d1(t,e,n,s={}){const i=typeof t=="string"?ye[t]:t,o=[];if(n<=e)return o;if(s.move){const r=i.moves[s.move],a=Math.floor(e/r.beats)*r.beats;Nh(r,a,Math.ceil((n-a)/r.beats)*r.beats,s.mirror,o,e,n)}else{const r=Zs(i);for(let a=Math.floor(e/r)*r;a<n;a+=r){let l=a;for(const c of i.routine)Nh(i.moves[c.move],l,c.beats,c.mirror,o,e,n),l+=c.beats}}return o.sort((r,a)=>r.beat-a.beat)}function Dh(t,e){const n=t.moves[e.move];if(!n?.travel)return 0;const s=n.travel/n.beats;return e.mirror?(Ch(n,Vs(t),Lh(t))[0]?.pose.turn??Vs(t).turn??0)>=.5?s:-s:s}function Fh(t,e){return e.move?[{move:e.move,beats:t.moves[e.move].beats,mirror:e.mirror}]:t.routine}function Qs(t,e,n={}){const s=typeof t=="string"?ye[t]:t,i=Fh(s,n),o=i.reduce((h,d)=>h+d.beats,0),r=i.reduce((h,d)=>h+Dh(s,d)*d.beats,0),a=Math.floor(e/o);let l=a*r,c=e-a*o;for(const h of i){const d=Math.min(h.beats,c);if(l+=Dh(s,h)*d,c-=d,c<=0)break}return l}function u1(t,e,n){const s=Fh(t,n),i=[0];let o=0;for(let r=0;o<e;r=(r+1)%s.length)o+=s[r].beats,i.push(Math.min(o,e));return i}const f1=8;function jh(t,e,n){const s=typeof e=="string"?ye[e]:e,i=n.bpm??s.bpm,o=n.beats??(n.move?s.moves[n.move].beats:Zs(s)),r=u1(s,o,n);if(r.every(b=>Qs(s,b,n)===0))return;const a=Math.min(n.fade??1,o/2),l=xt("ease-in-out"),c=b=>a<=0?1:Math.min(l(Math.min(1,b/a)),l(Math.min(1,(o-b)/a))),h=Math.ceil(a*f1),d=a<=0?[]:Array.from({length:h+1},(b,S)=>[S/h*a,o-S/h*a]).flat(),u=[...new Set([...r,...d])].sort((b,S)=>b-S);let f=0;const g=u.map((b,S)=>{if(S>0){const k=u[S-1],y=Math.max(1,Math.ceil((b-k)*16));for(let M=0;M<y;M++){const $=k+(b-k)*M/y,E=k+(b-k)*(M+1)/y;f+=(Qs(s,E,n)-Qs(s,$,n))*c(($+E)/2)}}return{beat:b,travel:f}}),p=n.start??0,m=n.x??0;return{id:`${t}-x`,target:t,property:"x",keyframes:g.map(b=>({time:p+b.beat*6e4/i,value:m+n.height*b.travel,easing:"linear"}))}}function p1(t,e,n=0){return(t-n)*e/6e4}function g1(t,e={}){return n=>Js(t,n,e)}function m1(t,e){const n=e.start??0,s=6e4/e.bpm,i=n+e.beats*s,o=Math.min((e.fade??1)*s,(i-n)/2);return[{id:`${t}-beat`,target:t,property:"beat",keyframes:[{time:n,value:0},{time:i,value:e.beats,easing:"linear"}]},{id:`${t}-dancing`,target:t,property:"dancing",keyframes:[{time:n,value:0},{time:n+o,value:1,easing:"ease-in-out"},{time:i-o,value:1},{time:i,value:0,easing:"ease-in-out"}]}]}function y1(t,e,n={}){const s=typeof e=="string"?ye[e]:e,i=n.bpm??s.bpm,o=n.beats??(n.move?s.moves[n.move].beats:Zs(s)),r=n.samplesPerBeat??4,a=n.start??0,l=Math.round(o*r),c=Array.from({length:l+1},(p,m)=>{const b=m/r;return{time:a+b*6e4/i,frame:Js(s,b,n)}}),h=(p,m)=>({id:`${t}-${p}`,target:t,property:p,keyframes:c.map(b=>({time:b.time,value:m(b.frame)}))}),u=Object.keys(et).filter(p=>c.some(m=>m.frame.pose[p]!==c[0].frame.pose[p])||c[0].frame.pose[p]!==et[p]).map(p=>h(p,m=>m.pose[p])),f=n.height===void 0?void 0:jh(t,s,{...n,bpm:i,beats:o,start:a,height:n.height,fade:0});if(f&&u.push(f),n.hands===!1)return u;const g=[];for(const p of["left","right"])for(const m of Object.keys(vt)){const b=S=>S.hands?.[p]?.[m]??vt[m];c.some(S=>b(S.frame)!==vt[m])&&g.push(h(Un(p,m),b))}return[...u,...g]}const Gn={type:"back",mode:"out",overshoot:1.1},_t="ease-out-cubic",b1={label:"Disco",bpm:120,stance:{leftHip:10,rightHip:10,leftKnee:6,rightKnee:6},expression:{smile:.9,mouth:.15,leftBrow:.3,rightBrow:.3},groove:{bounce:10,accent:"down",sway:2},moves:{point:{label:"The point",beats:2,easing:_t,keys:[{beat:0,pose:{rightShoulder:150,rightElbow:0,rightWrist:0,leftShoulder:40,leftElbow:-105,leftWrist:-20,lean:-5,headTilt:8,rightHip:18,leftHip:6,lookX:.6,lookY:-.7},hands:{right:"point",left:"fist"}},{beat:1,pose:{rightShoulder:-30,rightWrist:10,lean:5,headTilt:-6,rightHip:6,leftHip:18,lookX:-.4,lookY:.6}}]},roll:{label:"Roll the arms",beats:2,easing:"linear",keys:[{beat:0,pose:{leftShoulder:42,leftElbow:-128,rightShoulder:26,rightElbow:-100,rightHip:18,leftHip:6,lean:-3},hands:{left:"fist",right:"fist"}},{beat:.5,pose:{leftShoulder:26,leftElbow:-100,rightShoulder:42,rightElbow:-128}},{beat:1,pose:{leftShoulder:42,leftElbow:-128,rightShoulder:26,rightElbow:-100,rightHip:6,leftHip:18,lean:3}},{beat:1.5,pose:{leftShoulder:26,leftElbow:-100,rightShoulder:42,rightElbow:-128}}]},bump:{label:"Bump and clap",beats:4,keys:[{beat:0,pose:{lean:-10,rightHip:22,leftHip:4,leftShoulder:140,rightShoulder:140,leftElbow:0,rightElbow:0,leftWrist:20,rightWrist:20},hands:{left:"spread",right:"spread"},easing:_t},{beat:1,pose:{lean:0,rightHip:10,leftHip:10,leftShoulder:168,rightShoulder:168,leftElbow:22,rightElbow:22,leftWrist:0,rightWrist:0},hands:{left:"flat",right:"flat"}},{beat:2,pose:{lean:10,rightHip:4,leftHip:22,leftShoulder:140,rightShoulder:140,leftElbow:0,rightElbow:0,leftWrist:20,rightWrist:20},hands:{left:"spread",right:"spread"},easing:_t},{beat:3,pose:{lean:0,rightHip:10,leftHip:10,leftShoulder:168,rightShoulder:168,leftElbow:22,rightElbow:22,leftWrist:0,rightWrist:0},hands:{left:"flat",right:"flat"}}]}},routine:[{move:"point",beats:8},{move:"roll",beats:4},{move:"point",beats:8,mirror:!0},{move:"bump",beats:8}]},w1={label:"Hip hop",bpm:95,stance:{leftHip:14,rightHip:14,leftKnee:20,rightKnee:20,leftShoulder:22,rightShoulder:22,leftElbow:-30,rightElbow:-30,leftFootOut:.15,rightFootOut:.15},expression:"smug",hands:{left:"relaxed",right:"relaxed"},groove:{bounce:18,accent:"down"},moves:{bounce:{label:"Bounce",beats:2,keys:[{beat:0,pose:{leftShoulder:30,rightShoulder:30,leftElbow:-50,rightElbow:-50,lean:-3,headTilt:-5,leftWrist:-20,rightWrist:-20}},{beat:1,pose:{leftShoulder:14,rightShoulder:14,leftElbow:-18,rightElbow:-18,lean:3,headTilt:5,leftWrist:0,rightWrist:0}}]},runningMan:{label:"Running man",beats:2,keys:[{beat:0,reset:!0,pose:{turn:.85,leftHip:-84,leftKnee:-112,leftAnkle:25,rightHip:-26,rightKnee:8,leftShoulder:35,leftElbow:-50,rightShoulder:45,rightElbow:75,lean:6},hands:{left:"fist",right:"fist"}},{beat:.5,pose:{leftHip:-4,leftKnee:-18,leftAnkle:0,rightHip:4,rightKnee:18,leftShoulder:5,leftElbow:-40,rightShoulder:5,rightElbow:40}},{beat:1,pose:{rightHip:84,rightKnee:112,rightAnkle:25,leftHip:26,leftKnee:-8,rightShoulder:-35,rightElbow:50,leftShoulder:-45,leftElbow:-75}},{beat:1.5,pose:{rightHip:4,rightKnee:18,rightAnkle:0,leftHip:-4,leftKnee:-18,rightShoulder:-5,rightElbow:40,leftShoulder:-5,leftElbow:-40}}]},armWave:{label:"Arm wave",beats:4,keys:[{beat:0,reset:!0,pose:{leftShoulder:90,rightShoulder:90,leftElbow:0,rightElbow:0},hands:{left:"flat",right:"flat"}},{beat:.5,pose:{leftWrist:45,leftElbow:-15}},{beat:1,pose:{leftWrist:-35,leftElbow:40,leftShoulder:84}},{beat:1.5,pose:{leftWrist:0,leftElbow:-10,leftShoulder:102,headTilt:-8}},{beat:2,pose:{leftElbow:0,leftShoulder:90,rightShoulder:102,headTilt:8}},{beat:2.5,pose:{rightShoulder:84,rightElbow:40,headTilt:0}},{beat:3,pose:{rightElbow:-15,rightWrist:45}},{beat:3.5,pose:{rightElbow:0,rightWrist:-35}}]}},routine:[{move:"bounce",beats:8},{move:"runningMan",beats:8},{move:"armWave",beats:8},{move:"bounce",beats:4}]},k1={label:"Breaking (toprock)",bpm:110,stance:{leftHip:14,rightHip:14,leftKnee:14,rightKnee:14,leftShoulder:35,rightShoulder:35,leftElbow:-90,rightElbow:-90},expression:{smile:.3,leftBrow:-.3,rightBrow:-.3,browTilt:-.3},hands:{left:"fist",right:"fist"},groove:{bounce:8,accent:"down"},moves:{toprock:{label:"Toprock (Indian step)",beats:4,keys:[{beat:0,pose:{rightHip:-24,rightKnee:10,leftHip:10,leftShoulder:80,leftElbow:40,rightShoulder:55,rightElbow:-50,lean:6,headTilt:-6},easing:_t},{beat:1,reset:!0,pose:{leftHip:18,rightHip:18}},{beat:2,pose:{leftHip:-24,leftKnee:10,rightHip:10,rightShoulder:80,rightElbow:40,leftShoulder:55,leftElbow:-50,lean:-6,headTilt:6},easing:_t},{beat:3,reset:!0,pose:{leftHip:18,rightHip:18}}]},kick:{label:"Kick out",beats:2,keys:[{beat:0,pose:{rightHip:72,rightKnee:4,rightAnkle:-20,leftHip:4,lean:-12,leftShoulder:100,leftElbow:20},easing:_t},{beat:1,reset:!0}]},freeze:{label:"B-boy stance",beats:4,keys:[{beat:0,reset:!0,pose:{leftShoulder:26,leftElbow:-122,rightShoulder:22,rightElbow:-118,leftHip:18,rightHip:18,leftKnee:6,rightKnee:6,lean:-4,headTilt:10,smile:.6,leftEye:.6,rightEye:.6},easing:Gn},{beat:2,pose:{headTilt:14,lean:-6}}]}},routine:[{move:"toprock",beats:8},{move:"kick",beats:4},{move:"toprock",beats:8},{move:"kick",beats:4,mirror:!0},{move:"freeze",beats:4}]},v1={label:"Jazz",bpm:130,stance:{leftHip:10,rightHip:10},expression:{mouth:.55,smile:1,mouthWidth:1.2,leftBrow:.6,rightBrow:.6},hands:{left:"spread",right:"spread"},groove:{bounce:6,accent:"up"},moves:{jazzHands:{label:"Jazz hands",beats:2,easing:"linear",keys:[0,.25,.5,.75,1,1.25,1.5,1.75].map((t,e)=>({beat:t,pose:{leftShoulder:128,rightShoulder:128,leftElbow:8,rightElbow:8,leftWrist:e%2?4:26,rightWrist:e%2?26:4,leftHip:16,rightHip:16,leftKnee:t<1?26:8,rightKnee:t<1?26:8},hands:e===0?{left:{...Tt.spread,turn:2},right:{...Tt.spread,turn:2}}:void 0}))},kickBallChange:{label:"Kick ball change",beats:2,keys:[{beat:0,reset:!0,pose:{rightHip:88,rightKnee:0,rightAnkle:55,leftHip:4,lean:-12,leftShoulder:112,rightShoulder:112,leftWrist:15,rightWrist:15},hands:{left:"flat",right:"flat"},easing:_t},{beat:1,reset:!0,pose:{rightHip:10,rightKnee:24,rightAnkle:45,leftShoulder:60,rightShoulder:60,leftElbow:-20,rightElbow:-20}},{beat:1.5,pose:{rightAnkle:0,rightKnee:6,leftAnkle:45,leftKnee:20}}]},splitDrop:{label:"Drop into the splits",beats:8,keys:[{beat:0,reset:!0},{beat:2,reset:!0,pose:{leftHip:90,rightHip:90,leftKnee:0,rightKnee:0,leftAnkle:-45,rightAnkle:-45,leftShoulder:125,rightShoulder:125,leftElbow:10,rightElbow:10},easing:"ease-in-out-cubic"},{beat:4,pose:{leftShoulder:95,rightShoulder:95,leftElbow:0,rightElbow:0,leftWrist:50,rightWrist:50,headTilt:8}},{beat:6,reset:!0,pose:{leftHip:30,rightHip:30,leftKnee:60,rightKnee:60,leftShoulder:40,rightShoulder:40},easing:"ease-in-out-cubic"},{beat:7.5,reset:!0}]},jazzSquare:{label:"Jazz square",beats:4,keys:[{beat:0,reset:!0,pose:{rightHip:-18,leftHip:8,leftShoulder:38,rightShoulder:46,leftElbow:100,rightElbow:96,lean:4},hands:{left:"pinch",right:"pinch"}},{beat:1,pose:{leftHip:18,rightHip:6,leftShoulder:46,rightShoulder:38,lean:-4}},{beat:2,pose:{rightHip:22,leftHip:6,leftShoulder:38,rightShoulder:46,lean:4}},{beat:3,pose:{leftHip:10,rightHip:10,leftShoulder:46,rightShoulder:38,lean:0}}]}},routine:[{move:"jazzHands",beats:4},{move:"kickBallChange",beats:4},{move:"kickBallChange",beats:4,mirror:!0},{move:"jazzSquare",beats:8},{move:"jazzHands",beats:4},{move:"splitDrop",beats:8}]},M1={label:"K-pop",bpm:125,stance:{leftHip:9,rightHip:9,leftKnee:4,rightKnee:4},expression:"happy",groove:{bounce:5,accent:"down"},moves:{pointCombo:{label:"Point combo",beats:4,easing:Gn,keys:[{beat:0,reset:!0,pose:{rightShoulder:142,rightElbow:0,leftShoulder:25,leftElbow:-125,headTilt:6,lean:-3,lookX:.6,lookY:-.6},hands:{right:"point",left:"flat"}},{beat:1,pose:{rightShoulder:-38,headTilt:-6,lean:3,lookX:-.3,lookY:.5,rightHip:18}},{beat:2,reset:!0,pose:{leftShoulder:36,leftElbow:-96,rightShoulder:36,rightElbow:-96,leftWrist:20,rightWrist:20},hands:{left:"fist",right:"fist"}},{beat:3,reset:!0,pose:{leftShoulder:96,rightShoulder:96,leftElbow:0,rightElbow:0,leftWrist:50,rightWrist:50,headTilt:8,leftHip:18,rightHip:18},hands:{left:"flat",right:"flat"}}]},heart:{label:"Big heart, finger heart",beats:4,keys:[{beat:0,reset:!0,pose:{leftShoulder:165,rightShoulder:165,leftElbow:46,rightElbow:46,headTilt:-8,lean:-4},hands:{left:"cupped",right:"cupped"},easing:Gn},{beat:1,pose:{headTilt:8,lean:4}},{beat:2,reset:!0,pose:{rightShoulder:32,rightElbow:112,rightWrist:10,leftShoulder:20,leftElbow:-30,headTilt:10,leftEye:0,smile:1},hands:{right:"pinch",left:"relaxed"},easing:Gn},{beat:3,pose:{headTilt:4}}]},isolations:{label:"Isolations",beats:2,easing:_t,keys:[{beat:0,reset:!0,pose:{lean:-9,headTilt:11,leftShoulder:55,leftElbow:-112,rightShoulder:55,rightElbow:-112,rightHip:18},hands:{left:"fist",right:"fist"}},{beat:.5,pose:{lean:0,headTilt:0,rightHip:9}},{beat:1,pose:{lean:9,headTilt:-11,leftHip:18}},{beat:1.5,pose:{lean:0,headTilt:0,leftHip:9}}]}},routine:[{move:"pointCombo",beats:8},{move:"isolations",beats:4},{move:"heart",beats:8},{move:"pointCombo",beats:8,mirror:!0},{move:"isolations",beats:4}]},S1={label:"Bollywood",bpm:120,stance:{leftHip:10,rightHip:10},expression:{smile:1,mouth:.3,leftBrow:.4,rightBrow:.4},groove:{bounce:8,accent:"down",sway:3},moves:{lightBulb:{label:"Screw the bulb, pat the dog",beats:2,keys:[{beat:0,reset:!0,pose:{rightShoulder:160,rightElbow:12,rightWrist:-15,leftShoulder:40,leftElbow:-12,leftWrist:-45,lean:-4,rightHip:16,lookX:.5,lookY:-.6},hands:{right:{...Tt.cupped,roll:-30},left:{...Tt.flat,turn:0}}},{beat:.5,pose:{rightWrist:25,rightElbow:22,leftWrist:10,lean:4,rightHip:6,leftHip:16},hands:{right:{...Tt.cupped,roll:30}}},{beat:1,pose:{rightWrist:-15,rightElbow:12,leftWrist:-45,lean:-4,rightHip:16,leftHip:6},hands:{right:{...Tt.cupped,roll:-30}}},{beat:1.5,pose:{rightWrist:25,rightElbow:22,leftWrist:10,lean:4,rightHip:6,leftHip:16},hands:{right:{...Tt.cupped,roll:30}}}]},thumka:{label:"Thumka",beats:2,keys:[{beat:0,reset:!0,pose:{lean:-11,rightHip:22,leftHip:2,leftKnee:14,rightShoulder:45,rightElbow:-105,leftShoulder:128,leftElbow:18,leftWrist:35,headTilt:10,lookX:-.5},hands:{right:"fist",left:{...Tt.open,turn:2}},easing:_t},{beat:.5,pose:{lean:-4,rightHip:12,headTilt:6}},{beat:1,pose:{lean:-11,rightHip:22,headTilt:10},easing:_t},{beat:1.5,pose:{lean:-4,rightHip:12,headTilt:6}}]},flick:{label:"Cross and flick",beats:4,keys:[{beat:0,reset:!0,pose:{leftShoulder:22,rightShoulder:22,leftElbow:-62,rightElbow:-62,leftHip:16,rightHip:16,leftKnee:26,rightKnee:26},hands:{left:"fist",right:"fist"}},{beat:1,pose:{leftShoulder:132,rightShoulder:132,leftElbow:0,rightElbow:0,leftWrist:30,rightWrist:30,leftKnee:0,rightKnee:0,leftHip:10,rightHip:10,stretch:1.03},hands:{left:"spread",right:"spread"},easing:_t},{beat:2,pose:{leftShoulder:22,rightShoulder:22,leftElbow:-62,rightElbow:-62,leftWrist:0,rightWrist:0,leftHip:16,rightHip:16,leftKnee:26,rightKnee:26,stretch:1},hands:{left:"fist",right:"fist"}},{beat:3,pose:{leftShoulder:62,rightShoulder:62,leftElbow:0,rightElbow:0,leftWrist:35,rightWrist:35,leftKnee:0,rightKnee:0,leftHip:10,rightHip:10},hands:{left:"spread",right:"spread"},easing:_t}]}},routine:[{move:"thumka",beats:4},{move:"lightBulb",beats:8},{move:"flick",beats:8},{move:"thumka",beats:4,mirror:!0},{move:"lightBulb",beats:8,mirror:!0}]},T1={label:"Bhangra",bpm:100,stance:{leftShoulder:150,rightShoulder:150,leftElbow:18,rightElbow:18,leftHip:10,rightHip:10},expression:{mouth:.6,smile:1,mouthWidth:1.2,leftBrow:.5,rightBrow:.5},hands:{left:"open",right:"open"},groove:{bounce:12,accent:"down"},moves:{basic:{label:"Bhangra step",beats:2,keys:[{beat:0,reset:!0,pose:{rightHip:58,rightKnee:104,rightAnkle:30,leftShoulder:162,rightShoulder:140,headTilt:7}},{beat:.5,reset:!0,pose:{stretch:.98}},{beat:1,reset:!0,pose:{leftHip:58,leftKnee:104,leftAnkle:30,rightShoulder:162,leftShoulder:140,headTilt:-7}},{beat:1.5,reset:!0,pose:{stretch:.98}}]},dhamaal:{label:"Dhamaal (jump, arms up)",beats:2,keys:[{beat:0,reset:!0,pose:{leftHip:20,rightHip:20,leftKnee:40,rightKnee:40,stretch:.94}},{beat:.5,reset:!0,pose:{rise:.07,stretch:1.06,leftHip:6,rightHip:6,leftAnkle:45,rightAnkle:45,leftShoulder:172,rightShoulder:172,leftElbow:0,rightElbow:0},hands:{left:"point",right:"point"},easing:"ease-out-quad"},{beat:1,reset:!0,pose:{leftHip:20,rightHip:20,leftKnee:40,rightKnee:40,stretch:.94},hands:{left:"open",right:"open"},easing:"ease-in-quad"},{beat:1.5,reset:!0,pose:{rise:.07,stretch:1.06,leftHip:6,rightHip:6,leftAnkle:45,rightAnkle:45,leftShoulder:172,rightShoulder:172,leftElbow:0,rightElbow:0},hands:{left:"point",right:"point"},easing:"ease-out-quad"}]}},routine:[{move:"basic",beats:8},{move:"dhamaal",beats:4},{move:"basic",beats:8},{move:"dhamaal",beats:4}]},E1={label:"Bharatanatyam",bpm:80,stance:{...{leftHip:42,rightHip:42,leftKnee:82,rightKnee:82,leftFootOut:.3,rightFootOut:.3},leftShoulder:90,rightShoulder:90,leftElbow:0,rightElbow:0,leftWrist:75,rightWrist:75},expression:{smile:.5,leftEye:1.2,rightEye:1.2,leftBrow:.3,rightBrow:.3},hands:{left:"pataka",right:"pataka"},groove:{bounce:0},moves:{tatta:{label:"Tatta adavu (stamps)",beats:2,keys:[{beat:0,reset:!0,pose:{rightHip:48,rightKnee:104,rightAnkle:-18}},{beat:.3,reset:!0,easing:"ease-in-quad",taps:["rightToe","rightHeel"]},{beat:1,reset:!0,pose:{leftHip:48,leftKnee:104,leftAnkle:-18}},{beat:1.3,reset:!0,easing:"ease-in-quad",taps:["leftToe","leftHeel"]}]},natta:{label:"Natta adavu (stretch and look)",beats:4,keys:[{beat:0,reset:!0,pose:{rightHip:52,rightKnee:0,rightAnkle:-40,rightShoulder:125,rightWrist:60,leftShoulder:25,leftElbow:-125,leftWrist:0,headTilt:8,lookX:.9,lookY:-.4,lean:-6}},{beat:1,reset:!0},{beat:2,reset:!0,pose:{leftHip:52,leftKnee:0,leftAnkle:-40,leftShoulder:125,leftWrist:60,rightShoulder:25,rightElbow:-125,rightWrist:0,headTilt:-8,lookX:-.9,lookY:-.4,lean:6}},{beat:3,reset:!0}]},alapadma:{label:"Alapadma (lotus) to the sky",beats:4,keys:[{beat:0,reset:!0,pose:{rightShoulder:145,rightElbow:20,rightWrist:30,leftShoulder:28,leftElbow:-125,leftWrist:0,lookX:.7,lookY:-.9,headTilt:6},hands:{right:"alapadma",left:"pataka"}},{beat:1,pose:{rightWrist:55,headTilt:9}},{beat:2,reset:!0,pose:{leftShoulder:145,leftElbow:20,leftWrist:30,rightShoulder:28,rightElbow:-125,rightWrist:0,lookX:-.7,lookY:-.9,headTilt:-6},hands:{left:"alapadma",right:"pataka"}},{beat:3,pose:{leftWrist:55,headTilt:-9}}]}},routine:[{move:"tatta",beats:8},{move:"natta",beats:8},{move:"alapadma",beats:8},{move:"tatta",beats:4}]},A1={label:"Charleston",bpm:150,stance:{leftHip:10,rightHip:10,leftKnee:10,rightKnee:10,leftShoulder:30,rightShoulder:30,leftElbow:20,rightElbow:20},expression:{mouth:.4,smile:1,leftBrow:.5,rightBrow:.5},hands:{left:{...Tt.spread,turn:2},right:{...Tt.spread,turn:2}},groove:{bounce:8,accent:"down"},moves:{basic:{label:"Kick forward, kick back",beats:4,keys:[{beat:0,reset:!0,pose:{rightHip:48,rightKnee:8,rightAnkle:45,leftShoulder:75,rightShoulder:15,leftElbow:30,rightElbow:-10,lean:-7,headTilt:-5},easing:_t},{beat:1,reset:!0},{beat:2,reset:!0,pose:{leftHip:18,leftKnee:85,leftAnkle:35,rightShoulder:75,leftShoulder:15,rightElbow:30,leftElbow:-10,lean:7,headTilt:5},easing:_t},{beat:3,reset:!0}]},twist:{label:"Swivel (heels in, heels out)",beats:2,keys:[{beat:0,reset:!0,pose:{leftFootOut:-.9,rightFootOut:-.9,leftHip:4,rightHip:4,leftKnee:4,rightKnee:4,leftAnkle:-10,rightAnkle:-10,leftShoulder:18,rightShoulder:48,leftElbow:-10,rightElbow:50}},{beat:.5,pose:{leftFootOut:.6,rightFootOut:.6,leftHip:16,rightHip:16,leftKnee:22,rightKnee:22,leftAnkle:10,rightAnkle:10,leftShoulder:48,rightShoulder:18,leftElbow:50,rightElbow:-10}},{beat:1,pose:{leftFootOut:-.9,rightFootOut:-.9,leftHip:4,rightHip:4,leftKnee:4,rightKnee:4,leftAnkle:-10,rightAnkle:-10,leftShoulder:18,rightShoulder:48,leftElbow:-10,rightElbow:50}},{beat:1.5,pose:{leftFootOut:.6,rightFootOut:.6,leftHip:16,rightHip:16,leftKnee:22,rightKnee:22,leftAnkle:10,rightAnkle:10,leftShoulder:48,rightShoulder:18,leftElbow:50,rightElbow:-10}}]},kneeCross:{label:"Crossing knees",beats:2,keys:[{beat:0,reset:!0,pose:{leftHip:-6,rightHip:-6,leftKnee:-16,rightKnee:-16,leftFootOut:-.4,rightFootOut:-.4,leftShoulder:-12,rightShoulder:-12,leftElbow:0,rightElbow:0,lean:0,lookY:.6}},{beat:.5,pose:{leftHip:18,rightHip:18,leftKnee:28,rightKnee:28,leftFootOut:.3,rightFootOut:.3,leftShoulder:16,rightShoulder:16,lookY:0}},{beat:1,pose:{leftHip:-6,rightHip:-6,leftKnee:-16,rightKnee:-16,leftFootOut:-.4,rightFootOut:-.4,leftShoulder:-12,rightShoulder:-12,lookY:.6}},{beat:1.5,pose:{leftHip:18,rightHip:18,leftKnee:28,rightKnee:28,leftFootOut:.3,rightFootOut:.3,leftShoulder:16,rightShoulder:16,lookY:0}}]}},routine:[{move:"basic",beats:8},{move:"twist",beats:8},{move:"kneeCross",beats:8},{move:"basic",beats:8,mirror:!0},{move:"twist",beats:4}]},$1={label:"Tap",bpm:120,stance:{turn:.8,leftHip:-3,rightHip:3,leftKnee:-10,rightKnee:10,leftShoulder:12,rightShoulder:12,leftElbow:-40,rightElbow:40,leftWrist:-15,rightWrist:15,lean:4},expression:{smile:.9,mouth:.2,leftBrow:.3,rightBrow:.3,lookY:.3},hands:{left:"relaxed",right:"relaxed"},groove:{bounce:6,accent:"down"},moves:{shuffleBallChange:{label:"Shuffle ball change",beats:2,easing:"ease-out-quad",keys:[{beat:0,reset:!0,pose:{rightHip:34,rightKnee:8,rightAnkle:30,leftShoulder:30,rightShoulder:-10},taps:["rightToe"]},{beat:.25,pose:{rightHip:24,rightKnee:62,rightAnkle:40},taps:["rightToe"]},{beat:.5,pose:{rightHip:-8,rightKnee:14,rightAnkle:50,leftAnkle:15,leftShoulder:12,rightShoulder:12},taps:["rightToe"]},{beat:.75,pose:{rightHip:3,rightKnee:10,rightAnkle:0,leftAnkle:0},taps:["leftHeel"]},{beat:1,reset:!0,pose:{leftHip:-34,leftKnee:-8,leftAnkle:30,rightShoulder:-30,leftShoulder:10},taps:["leftToe"]},{beat:1.25,pose:{leftHip:-24,leftKnee:-62,leftAnkle:40},taps:["leftToe"]},{beat:1.5,pose:{leftHip:8,leftKnee:-14,leftAnkle:50,rightAnkle:15,leftShoulder:12,rightShoulder:12},taps:["leftToe"]},{beat:1.75,pose:{leftHip:-3,leftKnee:-10,leftAnkle:0,rightAnkle:0},taps:["rightHeel"]}]},timeStep:{label:"Single time step",beats:4,easing:"ease-out-quad",keys:[{beat:0,reset:!0,pose:{rightHip:8,rightKnee:4,rightAnkle:0,leftShoulder:25,rightShoulder:-20},taps:["rightToe","rightHeel"]},{beat:.5,pose:{rightHip:34,rightKnee:8,rightAnkle:30},taps:["rightToe"]},{beat:.75,pose:{rightHip:22,rightKnee:62,rightAnkle:40},taps:["rightToe"]},{beat:1,pose:{rise:.05,leftAnkle:45,leftKnee:-4,leftHip:-2,rightHip:26,rightKnee:70,stretch:1.03}},{beat:1.25,pose:{rise:0,leftAnkle:0,leftKnee:-14,stretch:1},taps:["leftToe"]},{beat:1.5,pose:{rightHip:4,rightKnee:12,rightAnkle:0,rightShoulder:25,leftShoulder:-20},taps:["rightToe"]},{beat:2,pose:{leftHip:-30,leftKnee:-6,leftAnkle:35},taps:["leftToe"]},{beat:2.25,pose:{leftHip:-4,leftKnee:-12,leftAnkle:0},taps:["leftToe"]},{beat:3,pose:{rightHip:10,rightAnkle:35,rightKnee:18,leftShoulder:12,rightShoulder:12},taps:["rightToe"]},{beat:3.5,pose:{rightHip:3,rightKnee:10,rightAnkle:0}}]},heelToe:{label:"Heel toe",beats:2,easing:"ease-out-quad",keys:[{beat:0,reset:!0,pose:{rightHip:26,rightKnee:0,rightAnkle:-35,leftShoulder:30,rightShoulder:-20},taps:["rightHeel"]},{beat:.5,pose:{rightHip:-16,rightKnee:24,rightAnkle:55,leftShoulder:-15,rightShoulder:25},taps:["rightToe"]},{beat:1,reset:!0,pose:{leftHip:-26,leftKnee:0,leftAnkle:-35,rightShoulder:-30,leftShoulder:20},taps:["leftHeel"]},{beat:1.5,pose:{leftHip:16,leftKnee:-24,leftAnkle:55,rightShoulder:15,leftShoulder:-25},taps:["leftToe"]}]},crampRoll:{label:"Cramp roll",beats:2,easing:"ease-out-quad",keys:[{beat:0,reset:!0,pose:{rightHip:12,rightKnee:26,leftHip:-12,leftKnee:-26}},{beat:.5,pose:{rightAnkle:40,rise:.02},taps:["rightToe"]},{beat:.625,pose:{leftAnkle:40},taps:["leftToe"]},{beat:.75,pose:{rightAnkle:0,rise:0},taps:["rightHeel"]},{beat:.875,pose:{leftAnkle:0},taps:["leftHeel"]},{beat:1,pose:{rightShoulder:135,leftShoulder:125,leftElbow:0,rightElbow:0,leftWrist:0,rightWrist:30,rightKnee:8,leftKnee:-8,rightHip:4,leftHip:-4},hands:{left:{...Tt.spread,turn:2},right:{...Tt.spread,turn:2}}},{beat:1.75,reset:!0}]}},routine:[{move:"shuffleBallChange",beats:8},{move:"timeStep",beats:4},{move:"timeStep",beats:4,mirror:!0},{move:"heelToe",beats:8},{move:"crampRoll",beats:4}]},ye={disco:b1,hipHop:w1,breaking:k1,jazz:v1,kpop:M1,bollywood:S1,bhangra:T1,bharatanatyam:E1,charleston:A1,tap:$1,popping:{label:"Popping (glides, moonwalk)",bpm:100,stance:{leftHip:9,rightHip:9,leftShoulder:16,rightShoulder:16,leftElbow:-24,rightElbow:-24},expression:{smile:.35,leftEye:.85,rightEye:.85,leftBrow:-.2,rightBrow:-.2},hands:{left:"relaxed",right:"relaxed"},groove:{bounce:0},moves:{sideGlide:{label:"Side glide",beats:2,easing:"linear",travel:.2,keys:[{beat:0,reset:!0,pose:{leftHip:11,leftKnee:0,leftAnkle:0,rightHip:36,rightKnee:45,rightAnkle:45,rightShoulder:80,rightElbow:-10,rightWrist:10,leftShoulder:28,leftElbow:18,lean:-2,headTilt:4,lookX:.7},hands:{right:"flat",left:"relaxed"}},{beat:1,pose:{leftHip:27,leftKnee:54,leftAnkle:45,rightHip:-1,rightKnee:0,rightAnkle:0,rightShoulder:74,rightWrist:-10,lean:2}}]},moonwalk:{label:"Moonwalk",beats:2,easing:"linear",travel:-.29,keys:[{beat:0,reset:!0,pose:{turn:.9,lean:4,headTilt:-4,leftHip:-12,leftKnee:0,leftAnkle:0,rightHip:23,rightKnee:57,rightAnkle:45,leftShoulder:-10,leftElbow:-45,rightShoulder:14,rightElbow:50}},{beat:1,pose:{leftHip:-23,leftKnee:-57,leftAnkle:45,rightHip:12,rightKnee:0,rightAnkle:0,leftShoulder:-14,leftElbow:-50,rightShoulder:10,rightElbow:45}}]},forwardGlide:{label:"Forward glide",beats:2,easing:"linear",travel:.29,keys:[{beat:0,reset:!0,pose:{turn:.9,lean:2,leftHip:16,leftKnee:0,leftAnkle:0,rightHip:33,rightKnee:59,rightAnkle:45,leftShoulder:12,leftElbow:-40,rightShoulder:-12,rightElbow:40}},{beat:1,pose:{leftHip:-33,leftKnee:-59,leftAnkle:45,rightHip:-16,rightKnee:0,rightAnkle:0,leftShoulder:-12,leftElbow:-40,rightShoulder:12,rightElbow:40}}]},toeStand:{label:"Toe stand",beats:4,keys:[{beat:0,reset:!0,pose:{leftHip:6,rightHip:6,leftKnee:0,rightKnee:0,leftAnkle:65,rightAnkle:65,rightShoulder:150,rightElbow:75,leftShoulder:30,leftElbow:20,headTilt:-10,lookY:.4},hands:{right:"fist",left:"fist"},easing:Gn},{beat:2,pose:{headTilt:-14,lean:-2}}]}},routine:[{move:"sideGlide",beats:4},{move:"sideGlide",beats:4,mirror:!0},{move:"moonwalk",beats:8},{move:"forwardGlide",beats:8},{move:"toeStand",beats:4}]}},ti=t=>Math.min(1,Math.max(0,t));function P1(t){const e={...et,turn:t.view},n=[];for(const s of t.keys){const i=n[n.length-1],o=!i||s.reset?e:i.pose;n.push({at:s.at,pose:{...o,...s.pose},easing:s.easing})}return n}function x1(t){return t-I1*Math.sin(2*Math.PI*t)/(2*Math.PI)}const I1=.5;function O1(t,e){if(!(e<=t.takeoff||e>=t.landing))return(e-t.takeoff)/(t.landing-t.takeoff)}function Bh(t,e){const n=typeof t=="string"?Vn[t]:t,s=P1(n),i=ti(e);let o=0;for(let d=0;d<s.length;d++)s[d].at<=i&&(o=d);const r=s[o],a=s[Math.min(o+1,s.length-1)],l=a.at>r.at?(i-r.at)/(a.at-r.at):0,c=cn(r.pose,a.pose,xt(a.easing??"ease-in-out")(ti(l))),h=O1(n,i);return h===void 0?{...c,spin:0,rise:0}:{...c,spin:n.spin*x1(h),rise:4*n.height*h*(1-h)}}function Wh(t,e,n){const s=typeof t=="string"?Vn[t]:t,i=ti(e),o=ti((i-s.takeoff)/(s.landing-s.takeoff));return s.travel*n*o}function _1(t,e,n={}){const s=typeof e=="string"?Vn[e]:e,i=n.start??0,o=n.duration??s.duration,r=n.samples??48,a=Array.from({length:r+1},(h,d)=>{const u=d/r;return{time:i+u*o,progress:u,pose:Bh(s,u)}}),c=Object.keys(et).filter(h=>a.some(d=>d.pose[h]!==et[h])).map(h=>({id:`${t}-${h}`,target:t,property:h,keyframes:a.map(d=>({time:d.time,value:d.pose[h]}))}));if(n.height!==void 0&&s.travel!==0){const h=(n.facing??1)<0?-1:1;c.push({id:`${t}-x`,target:t,property:"x",keyframes:a.map(d=>({time:d.time,value:(n.x??0)+h*Wh(s,d.progress,n.height)}))})}return c}const C1={leftHip:-55,leftKnee:-95,rightHip:55,rightKnee:95,leftShoulder:45,rightShoulder:-45,leftElbow:10,rightElbow:-10,lean:22,stretch:.94,headTilt:6},H1={leftHip:0,leftKnee:0,rightHip:0,rightKnee:0,leftAnkle:55,rightAnkle:55,leftShoulder:-172,rightShoulder:172,leftElbow:0,rightElbow:0,lean:0,stretch:1.08,headTilt:0},ei={leftHip:-128,leftKnee:-152,rightHip:128,rightKnee:152,leftAnkle:30,rightAnkle:30,leftShoulder:-78,rightShoulder:78,leftElbow:-48,rightElbow:48,lean:26,stretch:1,headTilt:14},R1={leftHip:-22,leftKnee:-30,rightHip:22,rightKnee:30,leftAnkle:10,rightAnkle:10,leftShoulder:-125,rightShoulder:125,leftElbow:0,rightElbow:0,lean:8,headTilt:0},L1={leftHip:-58,leftKnee:-100,rightHip:58,rightKnee:100,leftAnkle:0,rightAnkle:0,leftShoulder:-80,rightShoulder:80,leftElbow:-10,rightElbow:10,lean:20,stretch:.93};function hn(t,e,n,s,i,o=1300){return{label:t,view:1,spin:e,height:n,travel:s,takeoff:.27,landing:.8,duration:o,keys:[{at:0,reset:!0},{at:.16,pose:C1},{at:.27,pose:H1,easing:"ease-out-quad"},...i,{at:.76,pose:R1},{at:.86,pose:L1,easing:"ease-out-quad"},{at:1,reset:!0}]}}const Vn={frontFlip:hn("Front flip (tuck)",360,.56,.35,[{at:.38,pose:ei,easing:"ease-out-cubic"},{at:.64,pose:ei}]),backFlip:hn("Back flip (tuck)",-360,.58,-.15,[{at:.36,pose:{...ei,lean:18},easing:"ease-out-cubic"},{at:.64,pose:{...ei,lean:18}}]),layout:hn("Back layout (straight body)",-360,.66,-.2,[{at:.4,pose:{leftHip:8,rightHip:-8,leftKnee:0,rightKnee:0,leftAnkle:60,rightAnkle:60,leftShoulder:-178,rightShoulder:178,lean:-18,headTilt:-14}},{at:.64,pose:{leftHip:-4,rightHip:4,lean:-6,headTilt:-4,leftShoulder:-150,rightShoulder:150}}],1400),scissorFlip:hn("Scissor flip",360,.6,.45,[{at:.36,pose:{leftHip:-105,leftKnee:0,rightHip:-40,rightKnee:-20,leftAnkle:50,rightAnkle:50,leftShoulder:-150,rightShoulder:150,leftElbow:0,rightElbow:0,lean:12},easing:"ease-out-cubic"},{at:.52,pose:{leftHip:40,leftKnee:20,rightHip:105,rightKnee:0,leftShoulder:-140,rightShoulder:140}},{at:.66,pose:{leftHip:-30,leftKnee:-20,rightHip:30,rightKnee:20,leftShoulder:-110,rightShoulder:110,lean:6}}]),sideFlip:{label:"Side flip (tuck)",view:0,spin:360,height:.55,travel:.4,takeoff:.27,landing:.8,duration:1300,keys:[{at:0,reset:!0},{at:.16,pose:{leftHip:22,rightHip:22,leftKnee:44,rightKnee:44,leftShoulder:20,rightShoulder:20,lean:-10,stretch:.94}},{at:.27,pose:{leftHip:4,rightHip:4,leftKnee:0,rightKnee:0,leftAnkle:55,rightAnkle:55,leftShoulder:165,rightShoulder:165,lean:6,stretch:1.08},easing:"ease-out-quad"},{at:.38,pose:{leftHip:105,rightHip:105,leftKnee:135,rightKnee:135,leftShoulder:40,rightShoulder:40,leftElbow:-95,rightElbow:-95,lean:0,stretch:1,headTilt:10},easing:"ease-out-cubic"},{at:.64,pose:{}},{at:.76,pose:{leftHip:20,rightHip:20,leftKnee:20,rightKnee:20,leftAnkle:10,rightAnkle:10,leftShoulder:100,rightShoulder:100,leftElbow:0,rightElbow:0,headTilt:0}},{at:.86,pose:{leftHip:24,rightHip:24,leftKnee:48,rightKnee:48,leftAnkle:0,rightAnkle:0,leftShoulder:70,rightShoulder:70,stretch:.93},easing:"ease-out-quad"},{at:1,reset:!0}]},cartwheel:{label:"Cartwheel",view:0,spin:360,height:.155,travel:.9,takeoff:.2,landing:.86,duration:1600,keys:[{at:0,reset:!0},{at:.12,pose:{leftShoulder:165,rightShoulder:165,rightHip:30,rightKnee:0,lean:-6}},{at:.24,pose:{leftShoulder:172,rightShoulder:172,leftHip:55,rightHip:55,leftKnee:0,rightKnee:0,leftAnkle:40,rightAnkle:40,lean:0}},{at:.75,pose:{}},{at:.9,pose:{leftHip:30,rightHip:12,leftAnkle:0,rightAnkle:0,leftShoulder:150,rightShoulder:150}},{at:1,reset:!0}]},splitLeap:hn("Split leap (grand jeté)",0,.36,.9,[{at:.4,pose:{leftHip:-96,rightHip:-84,leftKnee:0,rightKnee:0,leftAnkle:55,rightAnkle:55,leftShoulder:-130,rightShoulder:-105,leftElbow:0,rightElbow:0,lean:4,headTilt:-6},easing:"ease-out-cubic"},{at:.64,pose:{lean:2}}]),toeTouch:{label:"Toe touch (straddle jump)",view:0,spin:0,height:.36,travel:0,takeoff:.27,landing:.8,duration:1200,keys:[{at:0,reset:!0},{at:.16,pose:{leftHip:22,rightHip:22,leftKnee:44,rightKnee:44,leftShoulder:-20,rightShoulder:-20,stretch:.94}},{at:.27,pose:{leftHip:4,rightHip:4,leftKnee:0,rightKnee:0,leftAnkle:55,rightAnkle:55,leftShoulder:170,rightShoulder:170,stretch:1.06},easing:"ease-out-quad"},{at:.42,pose:{leftHip:104,rightHip:104,leftShoulder:96,rightShoulder:96,leftElbow:0,rightElbow:0,stretch:1,headTilt:0},easing:"ease-out-cubic"},{at:.62,pose:{}},{at:.76,pose:{leftHip:12,rightHip:12,leftAnkle:10,rightAnkle:10,leftShoulder:120,rightShoulder:120}},{at:.86,pose:{leftHip:22,rightHip:22,leftKnee:44,rightKnee:44,leftAnkle:0,rightAnkle:0,leftShoulder:60,rightShoulder:60,stretch:.94},easing:"ease-out-quad"},{at:1,reset:!0}]},backHandspring:hn("Back handspring",-360,.16,-.7,[{at:.38,pose:{leftHip:10,rightHip:-10,leftKnee:0,rightKnee:0,leftShoulder:-178,rightShoulder:178,lean:-26,headTilt:-20}},{at:.6,pose:{leftHip:-40,rightHip:40,leftKnee:-20,rightKnee:20,lean:6,headTilt:0}}],1200)},ir=.215,or=.205,N1=.065,qh=.035,D1=.165,F1=.155,j1=12,B1=.3,W1=.7,q1=.35,K1=t=>t*Math.PI/180,ut={turn:0,lean:0,bend:0,side:0,"head.turn":0,"head.nod":0,"head.tilt":0,"arm.left.swing":0,"arm.left.spread":12,"arm.left.elbow":8,"arm.left.bend":0,"arm.right.swing":0,"arm.right.spread":12,"arm.right.elbow":8,"arm.right.bend":0,"leg.left.swing":0,"leg.left.spread":3,"leg.left.knee":0,"leg.left.ankle":0,"leg.left.toeOut":0,"leg.left.rotate":0,"leg.right.swing":0,"leg.right.spread":3,"leg.right.knee":0,"leg.right.ankle":0,"leg.right.toeOut":0,"leg.right.rotate":0,stretch:1,lift:0,roll:0,mouth:0,smile:.5,mouthWidth:1,blink:0,"eye.left":1,"eye.right":1,"brow.left":0,"brow.right":0,browTilt:0,lookX:0,lookY:0};function Ft(t={}){return{...ut,...t}}const Y1=new Set(["turn","side","head.turn","head.tilt","roll","lookX"]);function z1(t){const e={};for(const[n,s]of Object.entries(t)){const i=n.replace(/(^|\.)(left|right)(\.|$)/,(o,r,a,l)=>`${r}${a==="left"?"right":"left"}${l}`);e[i]=Y1.has(n)?-s:s}return e}function Yt(t,e){const n={};for(const s of["left","right"])for(const[i,o]of Object.entries(e))n[`${t}.${s}.${i}`]=o;return n}const Re={rest:ut,wave:Ft({"arm.right.spread":115,"arm.right.bend":55,"arm.right.elbow":0,"head.tilt":-6,smile:.9}),cheer:Ft({...Yt("arm",{spread:140,bend:20,elbow:0}),mouth:.6,smile:1,"eye.left":0,"eye.right":0}),point:Ft({"arm.right.spread":88,"arm.right.elbow":0,"arm.right.bend":0,"head.turn":-20,smile:.4}),handsOnHips:Ft({...Yt("arm",{spread:50,bend:-105,elbow:0}),...Yt("leg",{spread:9}),smile:.8}),think:Ft({"arm.right.spread":22,"arm.right.bend":-150,"arm.right.elbow":0,"head.tilt":10,lookX:-.5,lookY:-.8,smile:0}),shrug:Ft({...Yt("arm",{spread:35,bend:75,elbow:0}),"head.tilt":-10,smile:-.2}),sit:Ft({...Yt("leg",{swing:90,knee:90,spread:4}),...Yt("arm",{swing:25,elbow:45,spread:8})}),kneel:Ft({"leg.left.swing":90,"leg.left.knee":90,"leg.right.swing":-18,"leg.right.knee":108,"leg.right.ankle":16,...Yt("arm",{swing:20,elbow:30})}),crouch:Ft({...Yt("leg",{swing:75,knee:140,spread:6}),lean:25,...Yt("arm",{swing:50,elbow:40}),"head.nod":-15}),crawl:Ft({lean:82,"head.nod":-35,...Yt("arm",{swing:80,elbow:0,spread:4}),...Yt("leg",{knee:92,ankle:-88})}),lieDown:Ft({roll:90,...Yt("arm",{spread:8}),"head.nod":0})};function Kh(t={}){const e=t.headSize??.3,n=t.shoulderWidth??.06,s=t.hipWidth??.022,i=Math.max(.12,1-e-qh-(ir+or)),o=l=>({id:`arm.${l}`,parent:"spine",offset:[(l==="left"?1:-1)*n,-.035,0],rest:[0,-1,0],side:l==="left"?1:-1,bones:[{length:D1,width:[1.25,.9]},{length:F1,width:[.9,.75]}]}),r=l=>({id:`leg.${l}`,parent:null,offset:[(l==="left"?1:-1)*s,0,0],rest:[0,-1,0],side:l==="left"?1:-1,bones:[{length:ir,width:[1.45,1.05]},{length:or,width:[1.05,.85]},{length:N1,width:[.95,.7]}]}),a=(l,c)=>l[c]??ut[c]??0;return{id:"human",hipHeight:ir+or,chains:[r("left"),r("right"),{id:"spine",parent:null,rest:[0,1,0],bones:[{length:i/2,width:[1.7,1.4]},{length:i/2,width:[1.4,1.1]}]},{id:"neck",parent:"spine",rest:[0,1,0],bones:[{length:qh,width:[1,.9]}]},o("left"),o("right")],head:{on:"neck",size:e},contacts:[...["left","right"].flatMap(l=>[{chain:`leg.${l}`,joint:1},{chain:`leg.${l}`,joint:2},{chain:`leg.${l}`,joint:3},{chain:`arm.${l}`,joint:1},{chain:`arm.${l}`,joint:2}]),{chain:"spine",joint:0},{chain:"spine",joint:1},{chain:"spine",joint:2},{head:"top"}],angles(l,c){if(c.id==="spine"){const p=-a(l,"lean")/2,m=a(l,"side")/2,b=-a(l,"bend");return[{swing:p+b*B1,spread:m},{swing:p+b*W1,spread:m}]}if(c.id==="neck")return[{swing:-a(l,"bend")*q1,spread:0}];const[h,d]=c.id.split("."),u=p=>a(l,`${h}.${d}.${p}`);if(h==="arm")return[{swing:u("swing"),spread:u("spread")},{swing:u("elbow"),spread:u("bend")}];const f=(c.side??1)*u("rotate"),g=1-Math.cos(K1(u("rotate")));return[{swing:u("swing"),spread:u("spread"),yaw:f},{swing:-u("knee"),spread:0,yaw:f},{swing:90+u("ankle")-g*(u("swing")-u("knee")),spread:0,yaw:(j1+u("toeOut"))*(c.side??1)}]},withAngles(l,c,h){const[d,u]=c.id.split("."),f=g=>`${d}.${u}.${g}`;return d==="arm"?{...l,[f("swing")]:h[0].swing,[f("spread")]:h[0].spread,[f("elbow")]:h[1].swing,[f("bend")]:h[1].spread}:d==="leg"?{...l,[f("swing")]:h[0].swing,[f("spread")]:h[0].spread,[f("knee")]:-h[1].swing}:l},boneScale(l,c){const h=Math.min(3,Math.max(.3,a(l,"stretch")));return c?.id.startsWith("arm.")?Math.sqrt(h):h},headPose(l){const c=Math.min(3,Math.max(.3,a(l,"stretch")));return{yaw:a(l,"head.turn"),nod:a(l,"head.nod"),tilt:a(l,"head.tilt"),sx:1/Math.sqrt(c),sy:Math.sqrt(c)}},landmarks:{neck:["neck",0],"shoulder.left":["arm.left",0],"elbow.left":["arm.left",1],"hand.left":["arm.left",2],"shoulder.right":["arm.right",0],"elbow.right":["arm.right",1],"hand.right":["arm.right",2],"hip.left":["leg.left",0],"knee.left":["leg.left",1],"ankle.left":["leg.left",2],"toe.left":["leg.left",3],"hip.right":["leg.right",0],"knee.right":["leg.right",1],"ankle.right":["leg.right",2],"toe.right":["leg.right",3]}}}function X1(t){const e=t.split(".");if(e[0]==="hand"&&e.length>=3){const s=`${e[1]==="left"?"Left":"Right"} hand`,i={spread:"finger spread",turn:"wrist turn",bend:"wrist bend",tilt:"wrist tilt",roll:"roll"},o=e.slice(2).join(".");return`${s} · ${i[o]??o.replace(".curl"," curl").replace(".across"," across")}`}if(e.length===3){const[s,i,o]=e;return`${`${i==="left"?"Left":"Right"} ${s}`} · ${{swing:"forward / back",spread:"out / in",elbow:"elbow bend",bend:"forearm out / in",knee:"knee bend",ankle:"foot tilt",toeOut:"toes out / in",rotate:"turn out at the hip"}[o]??o}`}return{turn:"View (front → side → back)",lean:"Lean forward / back",bend:"Back curve (line of action)",side:"Lean sideways","head.turn":"Head · turn","head.nod":"Head · nod","head.tilt":"Head · tilt",stretch:"Squash / stretch",lift:"Lift off the ground",roll:"Roll (whole figure)",mouth:"Mouth open",smile:"Smile",mouthWidth:"Mouth width",blink:"Blink","eye.left":"Left eye open","eye.right":"Right eye open","brow.left":"Left brow","brow.right":"Right brow",browTilt:"Brow slant",lookX:"Look left / right",lookY:"Look up / down"}[t]??t}const U1={leftEye:"eye.left",rightEye:"eye.right",leftBrow:"brow.left",rightBrow:"brow.right"},rr=Object.fromEntries(Object.entries(ct).map(([t,e])=>[t,Object.fromEntries(Object.entries(e).map(([n,s])=>[U1[n]??n,s]))]));function G1(t,e){const n=Math.min(1,Math.max(0,t.turn??0)),s=1-n,i={...ut,turn:n},o=[{stick:"right",human:"left",s:1},{stick:"left",human:"right",s:-1}];for(const{stick:a,human:l,s:c}of o){const h=t[`${a}Shoulder`],d=t[`${a}Elbow`];i[`arm.${l}.spread`]=h*s,i[`arm.${l}.swing`]=c*h*n,i[`arm.${l}.bend`]=d*s,i[`arm.${l}.elbow`]=c*d*n;const u=t[`${a}Hip`],f=t[`${a}Knee`],g=s+c*n;i[`leg.${l}.rotate`]=90*s,i[`leg.${l}.spread`]=0,i[`leg.${l}.swing`]=u*g,i[`leg.${l}.knee`]=f*g,i[`leg.${l}.ankle`]=-(t[`${a}Ankle`]??0),i[`leg.${l}.toeOut`]=(t[`${a}FootOut`]??0)*V1,i[`eye.${l}`]=t[`${a}Eye`],i[`brow.${l}`]=t[`${a}Brow`],e&&Object.assign(i,J1(l,e[a]??vt,t[`${a}Wrist`]??0,n))}const r=t.bend??0;i.lean=t.lean*n,i.bend=r*n,i.side=(t.lean+r*.5)*s,i["head.tilt"]=(t.headTilt+r*.5)*s,i["head.nod"]=t.headTilt*n;for(const a of["mouth","smile","mouthWidth","blink","browTilt","lookX","lookY","stretch"])i[a]=t[a];return i.lift=t.rise??0,i.roll=t.spin??0,i}const V1=70;function J1(t,e,n,s){const i=t==="right"?1-s:1+s,o={};for(const r of Object.keys(vt))o[`hand.${t}.${r}`]=e[r]??vt[r];return o[`hand.${t}.turn`]=(e.turn??0)-i,o[`hand.${t}.roll`]=(e.roll??0)+n,o}const Xt=t=>t*Math.PI/180;function ar([t,e,n],s){const i=Math.cos(s),o=Math.sin(s);return[t,e*i+n*o,-e*o+n*i]}function lr([t,e,n],s){const i=Math.cos(s),o=Math.sin(s);return[t*i-e*o,t*o+e*i,n]}function be([t,e,n],s){const i=Math.cos(s),o=Math.sin(s);return[t*i+n*o,e,-t*o+n*i]}const we=(t,e)=>[t[0]+e[0],t[1]+e[1],t[2]+e[2]],ni=(t,e)=>[t[0]*e,t[1]*e,t[2]*e],si=(t,e)=>lr(ar(t,e.swing),e.spread);function cr(t,e){const n=be(t,e);return{point:{x:n[0],y:-n[1]},depth:n[2]}}function ii(t,e,n){const s=n,o=[0,t.hipHeight*s*(t.boneScale?.(e,null)??1),0],r={};for(const p of t.chains){const m=p.parent?r[p.parent]:void 0;if(p.parent&&!m)throw new Error(`body plan ${t.id}: chain ${p.id} comes before its parent ${p.parent}`);const b=p.at??(m?m.joints3.length-1:0),S=m?m.joints3[b]:o,k=m?m.frames[Math.max(0,b-1)]:{swing:0,spread:0},y=p.offset?we(S,si(ni(p.offset,s),k)):S,M=p.side??1,$=t.boneScale?.(e,p)??1,E=t.angles(e,p),A=[y],T=[];let I=k.swing,v=k.spread;p.bones.forEach((P,H)=>{const O=E[H]??{swing:0,spread:0};I+=Xt(O.swing),v+=Xt(O.spread)*M,T.push({swing:I,spread:v});const C=be(si(p.rest,{swing:I,spread:v}),Xt(O.yaw??0));A.push(we(A[H],ni(C,P.length*s*$)))}),r[p.id]={joints3:A,frames:T}}const a=r[t.head.on],l=t.headPose?.(e)??{yaw:0,nod:0,tilt:0,sx:1,sy:1},c=a.frames[a.frames.length-1],h=t.head.size/2*s,d=h*l.sx,u=h*l.sy,f=p=>si(be(ar(lr(p,-Xt(l.tilt)),-Xt(l.nod)),Xt(l.yaw)),c),g=we(a.joints3[a.joints3.length-1],f([0,u,0]));return{height:s,root:o,chains:r,head:{center:g,rx:d,ry:u,toBody:f}}}function hr(t,e,n){const s=n.height,i=Xt(90*(e.turn??0)),o=ii(t,e,s),{root:r}=o,a=o.chains,{rx:l,ry:c}=o.head,h=o.head.toBody,d=o.head.center,u={};for(const T of t.chains){const{joints3:I,frames:v}=a[T.id],P=I.map(H=>cr(H,i));u[T.id]={id:T.id,joints3:I,frames:v,points:P.map(H=>H.point),depths:P.map(H=>H.depth)}}const f=cr(d,i),g=[[1,0,0],[0,1,0],[0,0,1]].map(T=>be(h(T),i)),p=cr(r,i).point,m=Xt(e.roll??0),b=T=>{const I=T.x-p.x,v=T.y-p.y;return{x:p.x+I*Math.cos(m)-v*Math.sin(m),y:p.y+I*Math.sin(m)+v*Math.cos(m)}},S=([T,I,v])=>[T*Math.cos(m)+I*Math.sin(m),-T*Math.sin(m)+I*Math.cos(m),v];for(const T of Object.values(u))T.points=T.points.map(b);const k={center:b(f.point),depth:f.depth,rx:l,ry:c,angle:0,axes:g.map(S)},y=k.axes[1];k.angle=Math.atan2(y[0],y[1]);const M=T=>{if("head"in T)return{x:k.center.x+y[0]*c,y:k.center.y-y[1]*c};const I=u[T.chain];return I.points[Math.min(T.joint,I.points.length-1)]};let $=0;(n.contact??"ground")==="ground"&&($=-Math.max(...t.contacts.map(T=>M(T).y))),$-=(e.lift??0)*s;const E=T=>({x:T.x,y:T.y+$});for(const T of Object.values(u))T.points=T.points.map(E);k.center=E(k.center);const A=t.contacts.map(T=>({spec:T,point:M(T)}));return{height:s,view:i,chains:u,head:k,hip:E(b(p)),contacts:A,groundY:Math.max(...A.map(T=>T.point.y))}}const dr=(t,e)=>[t[0]-e[0],t[1]-e[1],t[2]-e[2]],Yh=t=>{const e=Math.hypot(t[0],t[1],t[2])||1;return[t[0]/e,t[1]/e,t[2]/e]};function oi(t,e,n){const s=n.height,i=Xt(90*(e.turn??0)),o=Xt(e.roll??0),r=ii(t,e,s),a=be(r.root,i),l=m=>we(lr(dr(be(m,i),a),-o),a),c={};for(const m of t.chains)c[m.id]=r.chains[m.id].joints3.map(l);const h=l(r.head.center),d=m=>Yh(dr(l(we(r.head.center,r.head.toBody(m))),h)),u=[d([1,0,0]),d([0,1,0]),d([0,0,1])],f=m=>{if("head"in m)return we(h,ni(u[1],r.head.ry));const b=c[m.chain];return b[Math.min(m.joint,b.length-1)]};let g=0;(n.contact??"ground")==="ground"&&(g=-Math.min(...t.contacts.map(m=>f(m)[1]))),g+=(e.lift??0)*s;const p=m=>[m[0],m[1]+g,m[2]];return{height:s,hip:p(a),chains:Object.fromEntries(Object.entries(c).map(([m,b])=>[m,b.map(p)])),head:{center:p(h),rx:r.head.rx,ry:r.head.ry,axes:u}}}function ri(t,e,n,s){const i=n.height,o=Xt(90*(e.turn??0)),r=ii(t,e,i),a=oi(t,e,n),l=a.hip,c=a.chains,h=a.head.center,d=T=>{if("head"in T)return we(h,ni(a.head.axes[1],a.head.ry));const I=c[T.chain];return I[Math.min(T.joint,I.length-1)]},u=s.toView(l),f=s.toScreen(u),g=s.toScreen([u[0]+1,u[1],u[2]]),p=Math.hypot(g.x-f.x,g.y-f.y),m=T=>{const I=s.toView(T);return{point:s.toScreen(I),depth:I[2]*p}},b={};for(const T of t.chains){const I=c[T.id].map(m);b[T.id]={id:T.id,joints3:r.chains[T.id].joints3,frames:r.chains[T.id].frames,points:I.map(v=>v.point),depths:I.map(v=>v.depth)}}const S=s.toView(h),k=s.toScreen(S),y=s.toScreen([S[0]+1,S[1],S[2]]),M=Math.hypot(y.x-k.x,y.y-k.y),$=a.head.axes.map(T=>Yh(dr(s.toView(we(h,T)),S))),E={center:k,depth:S[2]*p,rx:r.head.rx*M,ry:r.head.ry*M,angle:Math.atan2($[1][0],$[1][1]),axes:$},A=t.contacts.map(T=>({spec:T,point:m(d(T)).point}));return{height:i*p,view:o,chains:b,head:E,hip:f,contacts:A,groundY:Math.max(...A.map(T=>T.point.y))}}function zh(t,[e,n,s]){const[i,o,r]=t.axes,a=[i[0]*e*t.rx+o[0]*n*t.ry+r[0]*s*t.rx,i[1]*e*t.rx+o[1]*n*t.ry+r[1]*s*t.rx,i[2]*e*t.rx+o[2]*n*t.ry+r[2]*s*t.rx],l=Math.hypot(e,n,s)||1,c=(i[2]*e+o[2]*n+r[2]*s)/l;return{point:{x:t.center.x+a[0],y:t.center.y-a[1]},depth:t.depth+a[2],facing:c}}class Xh{positions=[];normals=[];indices=[];vertex(e,n,s,i,o,r){const a=Math.hypot(i,o,r)||1;return this.positions.push(e,n,s),this.normals.push(i/a,o/a,r/a),this.positions.length/3-1}triangle(e,n,s){this.indices.push(e,n,s)}quad(e,n,s,i){this.indices.push(e,n,s,e,s,i)}build(){return{positions:this.positions,normals:this.normals,indices:this.indices}}}function Z1(t){const e=new Map,n=[];for(let i=0;i<t.positions.length/3;i++){const o=[0,1,2].map(r=>Math.round(t.positions[i*3+r]*1e6)).join(",");e.has(o)||e.set(o,i),n.push(e.get(o))}const s=new Map;for(let i=0;i<t.indices.length/3;i++)for(let o=0;o<3;o++){const r=n[t.indices[i*3+o]],a=n[t.indices[i*3+(o+1)%3]];if(r===a)continue;const l=r<a?`${r}-${a}`:`${a}-${r}`,c=s.get(l);c?c.faces.push(i):s.set(l,{a:Math.min(r,a),b:Math.max(r,a),faces:[i]})}return[...s.values()]}const ur=Math.PI*2;function Q1(t,e=16){const n=new Xh,s=Math.max(6,Math.round(e)),i=Math.max(3,Math.round(s/2)),o=[];for(let r=0;r<=i;r++){const a=r/i*Math.PI,l=[];for(let c=0;c<=s;c++){const h=c/s*ur,d=Math.sin(a)*Math.sin(h),u=Math.cos(a),f=Math.sin(a)*Math.cos(h);l.push(n.vertex(d*t,u*t,f*t,d,u,f))}o.push(l)}for(let r=0;r<i;r++)for(let a=0;a<s;a++){const l=o[r][a],c=o[r+1][a],h=o[r+1][a+1],d=o[r][a+1];r>0&&n.triangle(l,c,d),r<i-1&&n.triangle(c,h,d)}return n.build()}function Uh(t,e,n,s,i){const o=t.vertex(0,n,0,0,s,0),r=Array.from({length:i},(a,l)=>{const c=l/i*ur;return t.vertex(Math.sin(c)*e,n,Math.cos(c)*e,0,s,0)});for(let a=0;a<i;a++){const l=r[a],c=r[(a+1)%i];s===1?t.triangle(o,l,c):t.triangle(o,c,l)}}function Gh(t,e,n=24){const s=new Xh,i=Math.max(6,Math.round(n)),o=e/2,r=-e/2,a=h=>Array.from({length:i+1},(d,u)=>{const f=u/i*ur;return s.vertex(Math.sin(f)*t,h,Math.cos(f)*t,Math.sin(f),0,Math.cos(f))}),l=a(r),c=a(o);for(let h=0;h<i;h++)s.quad(l[h],l[h+1],c[h+1],c[h]);return Uh(s,t,o,1,i),Uh(s,t,r,-1,i),s.build()}function ai(t){const e=Array.from({length:t.indices.length/3},()=>[]);for(const n of Z1(t))for(const s of n.faces){const i=n.faces.find(o=>o!==s)??-1;e[s].push({a:n.a,b:n.b,across:i})}return{...t,faceEdges:e}}const li=t=>t*180/Math.PI,dn=(t,e)=>[t[0]-e[0],t[1]-e[1],t[2]-e[2]],fr=(t,e)=>t[0]*e[0]+t[1]*e[1]+t[2]*e[2],Jn=t=>Math.hypot(t[0],t[1],t[2]),pr=t=>{const e=Jn(t)||1;return[t[0]/e,t[1]/e,t[2]/e]},ci=t=>Math.atan2(Math.sin(t),Math.cos(t));function Vh(t){const[e,n,s]=pr(t);return{swing:Math.asin(Math.max(-1,Math.min(1,s))),spread:Math.atan2(e,-n)}}function ty(t,e,n,s,i){const o=t.chains.find(I=>I.id===n);if(!o)throw new Error(`reach: no chain ${n} in ${t.id}`);if(o.bones.length<2||o.rest[1]>-.99)throw new Error(`reach: ${n} is not a hanging limb of two bones or more`);if(!t.withAngles)throw new Error(`reach: the ${t.id} plan cannot set angles`);const r=hr(t,{...e,turn:0,roll:0,lift:0},{height:i.height,contact:"none"}),a=r.chains[n],l=a.joints3[0],c=Jn(dn(a.joints3[1],a.joints3[0])),h=Jn(dn(a.joints3[2],a.joints3[1])),d=o.parent?r.chains[o.parent].frames[Math.max(0,(o.at??r.chains[o.parent].joints3.length-1)-1)]:{swing:0,spread:0},u=dn(s,l),f=Math.min(c+h-1e-6,Math.max(Math.abs(c-h)+1e-6,Jn(u))),g=pr(u),p=o.parent!==null,m=si(o.pole??(p?[0,-.35,-1]:[0,0,1]),d);let b=dn(m,[g[0]*fr(m,g),g[1]*fr(m,g),g[2]*fr(m,g)]);Jn(b)<1e-6&&(b=be([1,0,0],0)),b=pr(b);const S=(c*c+f*f-h*h)/(2*c*f),k=Math.sqrt(Math.max(0,1-S*S)),y=[l[0]+c*(S*g[0]+k*b[0]),l[1]+c*(S*g[1]+k*b[1]),l[2]+c*(S*g[2]+k*b[2])],M=[l[0]+g[0]*f,l[1]+g[1]*f,l[2]+g[2]*f],$=o.side??1,E=Vh(dn(y,l)),A=Vh(dn(M,y)),T=[{swing:li(ci(E.swing-d.swing)),spread:li(ci(E.spread-d.spread))*$},{swing:li(ci(A.swing-E.swing)),spread:li(ci(A.spread-E.spread))*$}];return t.withAngles(e,o,T)}const ey=.34,ke=.12,Qt=-.4,ee=(t,e,n)=>t[e]??n,ny=(t,e)=>Math.max(0,t)*(1-Math.min(1,Math.max(0,e))),sy=.45,iy=.35,oy=.7;function hi(t,e,n){const s=f=>Math.sqrt(Math.max(0,1-f.x*f.x-f.y*f.y)),i=zh(t,[n.x,n.y,s(n)]).facing,o=t.axes[2],r=Math.atan2(o[0],o[2]),a=Math.cos(r),l=a>=0?1:-1,c=l*Math.max(iy,Math.abs(a)),h=l*Math.max(oy,Math.abs(a)),d=Math.cos(t.angle),u=Math.sin(t.angle);return{facing:i,points:e.map(f=>{const g=sy*Math.sin(r)+n.x*c+(f.x-n.x)*h,p=f.y+o[1]*s(f),m=g*t.rx,b=p*t.ry;return{x:t.center.x+m*d+b*u,y:t.center.y+m*u-b*d}})}}const di=(t,e,n,s=12)=>Array.from({length:s+1},(i,o)=>{const r=o/s,a=1-r;return{x:a*a*t.x+2*a*r*e.x+r*r*n.x,y:a*a*t.y+2*a*r*e.y+r*r*n.y}}),gr=(t,e,n,s,i=16)=>Array.from({length:i},(o,r)=>{const a=Math.PI*2*r/i;return{x:t+Math.cos(a)*n,y:e+Math.sin(a)*s}}),Jh=.05;function ry(t,e,n,s){const i=Math.max(1,Math.min(s*.6,.14*e.rx)),o=(b,S)=>hi(e,b,S).points,r=(b,S)=>hi(e,[],{x:b,y:S}).facing,a=ee(n,"smile",0),l=ee(n,"blink",0),c=ee(n,"lookX",0),h=ee(n,"lookY",0),d=ee(n,"browTilt",0);for(const b of[1,-1]){const S=b===1?"left":"right",k=ey*b;if(r(k,ke)<Jh)continue;const y={x:k,y:ke},M=ny(ee(n,`eye.${S}`,1),l);if(M<.2){const T=a>.5?.12:-.06;t.line(o(di({x:k-.12,y:ke},{x:k,y:ke+T},{x:k+.12,y:ke}),y),i)}else{if(M>1.2){const P=.13*M;t.shape(o(gr(k,ke,P*.85,P),y),"#ffffff",i)}const T=M>1.2?.075:.1,I=k+c*.08,v=ke-h*.07;t.shape(o(gr(I,v,T,T*1.1*Math.min(M,1)),y),t.ink,0)}const $=ke+.3+ee(n,`brow.${S}`,0)*.14+Math.max(0,M-1)*.12,E={x:k+b*.13,y:$},A={x:k-b*.13,y:$+d*.1};t.line(o([E,{x:(E.x+A.x)/2,y:(E.y+A.y)/2},A],{x:k,y:$}),i)}const u={x:0,y:Qt};if(r(0,Qt)<-Jh)return;const f=.25*Math.max(.3,ee(n,"mouthWidth",1)),g=Math.min(1,Math.max(0,ee(n,"mouth",0)));if(g<=.05){t.line(o(di({x:-f,y:Qt},{x:0,y:Qt-a*.25},{x:f,y:Qt}),u),i);return}const p=.3*g;let m;if(a>.3){const b=Qt+.05;m=[...di({x:f,y:b},{x:0,y:Qt-p*2},{x:-f,y:b})]}else if(a<-.3){const b=Qt-p*.6;m=[...di({x:f,y:b},{x:0,y:Qt+p*1.4},{x:-f,y:b})]}else m=gr(0,Qt,f*.8,p);t.shape(o(m,u),t.ink,0)}function mr(t={}){const e=(t.proportions??"bold")==="bold",n=t.figure??"fluid",s=t.look??"clean",i=t.height??300,o=n==="stick";return{plan:t.plan??Kh({headSize:t.headSize??(e?.3:.24),shoulderWidth:o?0:t.shoulderWidth??.06,hipWidth:o?0:t.hipWidth??.022}),figure:n,look:s,height:i,lineWidth:t.lineWidth??i*(e?.045:.022),ink:t.ink??(s==="pencil"?"#2f2f33":"#1e293b"),skin:t.skin??(s==="pencil"?"none":"#ffffff"),seed:t.seed??1,pencil:t.pencil??{},layers:t.layers??{},contact:t.contact??"ground",hands:t.hands??"dot",handStyle:t.handStyle??"glove",handSize:t.handSize??(t.handStyle==="natural"?.14:.17)}}function ay(t,e,n,s){const{point:i,facing:o}=zh(t,[e,n,s]);return{point:i,facing:o}}const yr=t=>t.rest[1]<-.5,ly=.3;function cy(t,e,n){return t.figure==="stick"?yr(e)?n.slice(0,3):n:yr(e)&&n.length>=3?Ce(n[0],n[1],n[2],ly):n.length===3?Ce(n[0],n[1],n[2],1):n}function br(t,e){const n=t.plan.id==="human"?{...ut,...e}:e;return ui(t,n,hr(t.plan,n,{height:t.height,contact:t.contact}))}function ui(t,e,n){const s={},i={},o={},r=.01*t.height;t.plan.chains.forEach(u=>{const f=n.chains[u.id];s[u.id]=f.points;const g=f.depths.reduce((S,k)=>S+k,0)/f.depths.length,p=u.parent?n.chains[u.parent]:void 0,m=p?p.depths[u.at??p.depths.length-1]:0,b=g-m;o[u.id]=Math.abs(b)<r?0:b,i[u.id]={points:cy(t,u,f.points),depth:g}}),i.head={points:[n.head.center],depth:n.head.depth},o.head=0;const a=[...t.plan.chains.map(u=>u.id),"head"],l=[...a].sort((u,f)=>o[u]-o[f]||a.indexOf(u)-a.indexOf(f)),c={hip:n.hip};for(const[u,[f,g]]of Object.entries(t.plan.landmarks??{})){const p=n.chains[f]?.points;p&&(c[u]=p[Math.min(g,p.length-1)])}const h={};for(const[u,f]of Object.entries(c))h[u]=f.y>=n.groundY-.01*t.height;const d={height:t.height,lineWidth:t.lineWidth,turn:e.turn??0,points:c,chains:s,parts:i,head:n.head,groundY:n.groundY,grounded:h};return{skeleton:n,joints:d,order:l}}function Zh(t,e){return br(t,e).joints}function Qh(t,e,n){const{head:s}=n;t.guideEllipse(s.center.x,s.center.y,s.rx*1.03,s.ry*1.03,s.angle);const i=Array.from({length:13},(l,c)=>({x:0,y:-.95+1.9*c/12})),o=Array.from({length:13},(l,c)=>({x:-.95+1.9*c/12,y:.12})),r=hi(s,i,{x:0,y:0});r.facing>0&&t.guide(r.points),t.guide(hi(s,o,{x:0,y:.12}).points),t.guide(n.chains.spine??[]);const a=e.lineWidth*.9;for(const l of["shoulder.left","shoulder.right","elbow.left","elbow.right","hip.left","hip.right","knee.left","knee.right"]){const c=n.points[l];c&&t.guideEllipse(c.x,c.y,a,a,0)}}function td(t,e,n,s,i,o){const r=n.lineWidth;if(i==="head"){const{head:f}=s,g=n.skin==="none"?null:n.skin;e.ellipse(f.center.x,f.center.y,f.rx,f.ry,f.angle,g,r),e.look!=="silhouette"&&ry(e,f,o,r);return}const a=n.plan.chains.find(f=>f.id===i),l=s.chains[i],c=s.parts[i].points;if(n.figure==="stick"){if(i==="neck")return;const f=i==="spine"?[...l,...s.chains.neck?.slice(1)??[]]:c;e.line(f,r);return}const h=(f,g)=>[a.bones[f].width[0]*r,a.bones[g].width[1]*r];if(yr(a)){const[f,g]=h(0,1);if(e.limb(c,f,g),a.bones.length>=3)e.limb([l[2],l[3]],a.bones[2].width[0]*r,a.bones[2].width[1]*r);else if(n.hands==="cartoon"&&i.startsWith("arm."))hy(t,e,n,l,i.endsWith(".left")?"left":"right",o);else{const p=l[l.length-1];e.dot(p.x,p.y,r*.62)}return}if(i==="spine"){const f=s.points["hip.left"],g=s.points["hip.right"];f&&g&&Math.hypot(f.x-g.x,f.y-g.y)>.5&&e.limb([f,g],r*1.3,r*1.3);const[p,m]=h(0,a.bones.length-1);e.limb(c,p,m);const b=s.points["shoulder.left"],S=s.points["shoulder.right"];b&&S&&Math.hypot(b.x-S.x,b.y-S.y)>.5&&e.limb(Ce(b,l[l.length-1],S,1,10),r*1.15,r*1.15);return}const[d,u]=h(0,a.bones.length-1);e.limb(c,d,u)}function ed(t,e){const n=`hand.${e}.`,s={};for(const[r,a]of Object.entries(t))r.startsWith(n)&&(s[r.slice(n.length)]=a);const i=t.turn??0,o=e==="right"?1-i:1+i;return{...vt,...s,turn:o+(s.turn??0)}}function hy(t,e,n,s,i,o){const r=s[s.length-1],a=s[s.length-2],l=Math.atan2(r.x-a.x,-(r.y-a.y))*180/Math.PI;Ys(t,r,ed(o,i),{size:n.handSize*n.height,side:i,angle:l,pen:e,skin:n.skin==="none"?"#ffffff":n.skin,fingers:n.handStyle==="natural"?5:4,plump:n.handStyle==="natural"?1.15:1.6,lineWidth:n.lineWidth*.3})}function nd(t,e,n,s=0){const i=e.plan.id==="human"?{...ut,...n}:n;id(t,e,i,br(e,i),s)}function wr(t,e){const n=e/t.height;return{...t,height:e,lineWidth:t.lineWidth*n}}function dy(t,e,n,s){const i=t.plan.id==="human"?{...ut,...e}:e,o=ri(t.plan,i,{height:s.height,contact:t.contact},n);return ui(wr(t,o.height),i,o).joints}function uy(t,e,n,s,i){const o=e.plan.id==="human"?{...ut,...n}:n,r=ri(e.plan,o,{height:i.height,contact:e.contact},s),a=wr(e,r.height);id(t,a,o,ui(a,o,r),i.time??0)}function sd(t,e,n,s){const i=t.plan.id==="human"?{...ut,...e}:e,o=ri(t.plan,i,{height:s.height,contact:t.contact},n),r=wr(t,o.height),{joints:a,order:l}=ui(r,i,o),c=o.height/s.height;return l.map((h,d)=>({part:h,depth:(a.parts[h]?.depth??0)/c,draw(u,f=0){const g=Wn(u,{look:r.look,ink:r.ink,lineWidth:r.lineWidth,seed:qt(`${r.seed}:${h}`),time:f,pencil:r.pencil}),p=b=>{b&&(u.save(),b(u,a,g,f),u.restore())};u.save(),u.lineCap="round",u.lineJoin="round",d===0&&(r.look==="pencil"&&r.pencil.construction!==!1&&Qh(g,r,a),p(r.layers.behind));const m=r.layers.parts?.[h];p(m?.under),td(u,g,r,a,h,i),p(m?.over),d===l.length-1&&p(r.layers.front),u.restore()}}))}function id(t,e,n,s,i){const{joints:o,order:r}=s,a=Wn(t,{look:e.look,ink:e.ink,lineWidth:e.lineWidth,seed:e.seed,time:i,pencil:e.pencil}),l=c=>{c&&(t.save(),c(t,o,a,i),t.restore())};t.save(),t.lineCap="round",t.lineJoin="round",e.look==="pencil"&&e.pencil.construction!==!1&&Qh(a,e,o),l(e.layers.behind);for(const c of r){const h=e.layers.parts?.[c];l(h?.under),td(t,a,e,o,c,n),l(h?.over)}l(e.layers.front),t.restore()}function fy(t,e,n){const s={...t};for(const[i,o]of Object.entries(e)){const r=t[i]??o;s[i]=r+(o-r)*n}return s}function py(t,e,n,s){const i=t.plan.id==="human"?{...ut,...e}:e;let o;if(Array.isArray(s))o=s;else{const{skeleton:r}=br(t,i),a=hr(t.plan,{...i,roll:0},{height:t.height,contact:"none"}),l=(i.roll??0)*Math.PI/180,c=s.x-r.hip.x,h=s.y-r.hip.y,d=a.hip.x+c*Math.cos(-l)-h*Math.sin(-l),u=a.hip.y+c*Math.sin(-l)+h*Math.cos(-l),f=Math.PI/2*(i.turn??0),g=s.depth??r.chains[n].depths[r.chains[n].depths.length-1],p=Math.cos(f),m=Math.sin(f);o=[d*p-g*m,-u,d*m+g*p]}return ty(t.plan,i,n,o,{height:t.height})}function gy(t){const{character:e}=t,n=e.height*.8,s=e.height,i=e.plan.id==="human"?ut:{};return{type:"custom",x:t.x-n/2,y:t.y-s,width:n,height:s,props:{...i,...t.pose},character:e,draw(o,r,a){o.translate(n/2,s),nd(o,e,r.props,a)}}}function od(t,e,n){const s=o=>({x:o.x+e,y:o.y+n}),i=o=>Object.fromEntries(Object.entries(o).map(([r,a])=>[r,a.map(s)]));return{...t,points:Object.fromEntries(Object.entries(t.points).map(([o,r])=>[o,s(r)])),chains:i(t.chains),parts:Object.fromEntries(Object.entries(t.parts).map(([o,r])=>[o,{...r,points:r.points.map(s)}])),head:{...t.head,center:s(t.head.center)},groundY:t.groundY+n}}function my(t,e,n){const s=t.character;if(!s)throw new Error("characterAt: the target was not made by characterTarget");const i={...t.props};let o=0,r=0;for(const[l,c]of e.state?.values.get(n)??[])typeof c=="number"&&(l==="x"||l==="motionPathX"?o=c:l==="y"||l==="motionPathY"?r=c:l in i&&(i[l]=c));const a=Zh(s,i);return{pose:i,joints:od(a,t.x+o+t.width/2,t.y+r+t.height)}}function kr(t,e=ut){const n=[];return t.forEach((s,i)=>{const o=i===0?e:n[i-1],r=typeof s.pose=="string"?Re[s.pose]:void 0;n.push(r?{...r,turn:o.turn??0}:{...o,...s.pose})}),n}function yy(t,e,n=ut){const s=kr(e,n);return Object.keys(n).filter(o=>s.some(r=>(r[o]??n[o])!==n[o])).map(o=>({id:`${t}-${o}`,target:t,property:o,keyframes:e.map((r,a)=>({time:r.time,value:s[a][o]??n[o],...r.easing?{easing:r.easing}:{}}))}))}const vr=new Map;function by(t){const e=vr.get(t);if(e)return e;let n=[1,1,1];const s=t.trim().replace("#","");if(t.trim().startsWith("#")&&(s.length===3||s.length===6)){const i=s.length===3?s.split("").map(o=>o+o).join(""):s;n=[0,2,4].map(o=>Number.parseInt(i.slice(o,o+2),16)/255)}else{const i=t.match(/rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)/);i&&(n=[Number(i[1])/255,Number(i[2])/255,Number(i[3])/255])}return vr.size<512&&vr.set(t,n),n}Pe([-3,-5,-4]);const wy=(t,e,n)=>{const s=Math.min(1,Math.max(0,(n-t)/(e-t)));return s*s*(3-2*s)};function rd(t,e,n){const s=[0,0,0];for(const i of n){const o=by(i.color);let r;if(i.light==="ambient")r=i.intensity;else if(i.light==="directional")r=i.intensity*Math.max(0,-ue(e,i.direction));else{const a=tn(i.position,t),l=Is(a),c=l>0?en(a,1/l):e,h=i.range?Math.max(0,1-l/i.range)**2:1;if(r=i.intensity*Math.max(0,ue(e,c))*h,i.light==="spot"){const d=Math.cos(i.angle*Math.PI/180),u=Math.cos(i.angle*.8*Math.PI/180);r*=wy(d,u,-ue(c,i.direction))}}s[0]+=o[0]*r,s[1]+=o[1]*r,s[2]+=o[2]*r}return s}function ad(t,e){return t?Math.min(1,Math.max(0,(e-t.near)/(t.far-t.near))):0}function Mr(t,e,n={}){t.save(),ky(t,e,n),t.restore()}function ky(t,e,n){const s=Sr(e,n);n.shadow!==!1&&Tr(t,e,n);for(const i of e.under)$r(t,i,s,n);if(n.rider){if(t.save(),e.openings.length>0){t.beginPath();for(const i of e.openings){t.moveTo(i[0].x,i[0].y);for(const o of i.slice(1))t.lineTo(o.x,o.y);t.closePath()}t.clip("nonzero")}n.rider(t),t.restore()}for(const i of e.over)$r(t,i,s,n)}function Sr(t,e={}){return e.lineWidth??Math.max(1.3,t.sizePx*.022)}function Tr(t,e,n={}){e.shadow.opacity<=0||e.shadow.points.length<3||(t.save(),t.globalAlpha=e.shadow.opacity,fi(t,e.shadow.points,n.ink??"#26262b",!1),t.restore())}function vy(t,e,n,s={}){t.save(),$r(t,e,n,s),t.restore()}function ld(t,e,n,s={}){const i=s.style==="stick",o=e.flatMap(h=>{if(i&&h.part.solidOnly)return[];const d=h.part.layer??0;return i&&h.spine?[{depth:h.depth,layer:d,part:h}]:h.faces.map(u=>({depth:u.depth,layer:d,part:h,face:u}))}),r=new Map;for(const h of o){const d=h.face?.normal;if(!h.face?.center||!d)continue;const u=Math.abs(d[0])>=Math.abs(d[1])&&Math.abs(d[0])>=Math.abs(d[2])?0:Math.abs(d[1])>=Math.abs(d[2])?1:2,f=u*2+(d[u]<0?1:0);r.set(f,[...r.get(f)??[],h])}for(const h of r.values())for(const d of h){const{center:u,normal:f}=d.face;for(const g of h){if(g.part.part.id===d.part.part.id)continue;const p=g.face;if(p.normal[0]*f[0]+p.normal[1]*f[1]+p.normal[2]*f[2]<=.8)continue;const b=p.normal[0]*(u[0]-p.center[0])+p.normal[1]*(u[1]-p.center[1])+p.normal[2]*(u[2]-p.center[2]);b>-cd/5&&b<cd&&(d.layer=Math.max(d.layer,g.layer),d.depth=Math.max(d.depth,g.depth+1e-6))}}o.sort((h,d)=>h.layer-d.layer||h.depth-d.depth);const a=new Map,l=h=>{let d=a.get(h.part.id);return d||a.set(h.part.id,d=Er(t,h,n,s)),d};t.save();const c=t.globalAlpha;for(const{part:h,face:d}of o){t.globalAlpha=c*h.opacity;const u=l(h);if(!d)u.line(h.spine,n*1.15);else{const f=i?hd(h,s):d.light?My(h,d,s):Ar(h);f&&(!i&&s.look==="silhouette"?u.shape(d.points,f,0):fi(t,d.points,i||d.light?f:pi(f,d.tone),!0,h.cut?1.6:.8));const g=(h.part.outline??1)*n;if(g>0)for(const p of d.edges??[])p.length>1&&u.line(p,g);for(const p of d.marks??[])u.line(p,n*.7)}}t.restore()}const cd=.05;function Er(t,e,n,s){return Wn(t,{look:s.look??"clean",ink:e.part.ink??s.ink??"#26262b",lineWidth:n,seed:qt(`${s.seed??0}:${e.part.id}`),time:s.time??0,pencil:{construction:!1,rubbedOut:0,...s.pencil}})}function Ar(t){const{part:e}=t;return e.glow&&t.glow>0&&e.fill?Ir(e.fill,e.glow.color,t.glow):e.fill}function My(t,e,n){const{part:s}=t;if(!s.fill)return;const i=xr(s.fill,e.light,e.fog??0,n.fog);return s.glow&&t.glow>0?Ir(i,s.glow.color,t.glow):i}function hd(t,e){const n=Ar(t);return n&&(Ty(n)||t.glow>0)?n:e.paper??"#fbf8ef"}function $r(t,e,n,s){e.opacity<1?(t.save(),t.globalAlpha*=e.opacity,dd(t,e,n,s),t.restore()):dd(t,e,n,s)}function dd(t,e,n,s){if(s.style==="stick")return Sy(t,e,n,s);const{part:i}=e,o=Er(t,e,n,s),r=Ar(e),a=s.look==="silhouette";for(const c of e.faces)r&&(a?o.shape(c.points,r,0):fi(t,c.points,pi(r,c.tone)));const l=(i.outline??1)*n;if(l>0)for(const c of e.edges)c.length>1&&o.line(c,l);for(const c of e.marks)o.line(c,n*.7)}function Sy(t,e,n,s){const{part:i}=e;if(i.solidOnly)return;const o=Er(t,e,n,s);if(e.spine){o.line(e.spine,n*1.15);return}const r=hd(e,s);for(const l of e.faces)fi(t,l.points,r);const a=(i.outline??1)*n;if(a>0)for(const l of e.edges)l.length>1&&o.line(l,a);for(const l of e.marks)o.line(l,n*.7)}function Ty(t){const e=un(t);return e?(.299*e[0]+.587*e[1]+.114*e[2])/255<.3:!1}function fi(t,e,n,s=!0,i=.8){t.fillStyle=n,t.beginPath(),t.moveTo(e[0].x,e[0].y);for(let o=1;o<e.length;o++)t.lineTo(e[o].x,e[o].y);t.closePath(),t.fill(),s&&(t.strokeStyle=n,t.lineWidth=i,t.lineJoin="round",t.stroke())}function un(t){const e=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t.trim());if(!e)return;const n=e[1].length===3?e[1].replace(/./g,s=>s+s):e[1];return[0,2,4].map(s=>parseInt(n.slice(s,s+2),16))}const Pr=t=>`#${t.map(e=>Math.round(Math.max(0,Math.min(255,e))).toString(16).padStart(2,"0")).join("")}`;function pi(t,e){const n=un(t);return n?Pr(e>=1?n.map(s=>s+(255-s)*(e-1)*2):n.map(s=>s*e)):t}function xr(t,e,n,s){const i=un(t);if(!i)return t;let o=i.map((a,l)=>a*e[l]);const r=s?un(s):void 0;return r&&n>0&&(o=o.map((a,l)=>a+(r[l]-a)*n)),Pr(o)}function Ir(t,e,n){const s=un(t),i=un(e);return!s||!i?n<.5?t:e:Pr(s.map((o,r)=>o+(i[r]-o)*n))}const ud=40,Ey=.215+.205,jt=(t,e)=>{const n={};for(const s of["left","right"])for(const[i,o]of Object.entries(e))n[`${t}.${s}.${i}`]=o;return n},it=(t,e)=>t[e]??ut[e]??0;function fd(t,e,n=ut,s=1){const i=Yn(t),o=e*Math.PI*2,r=Math.sin(o)*s,a=Math.cos(o)*s,l=(1+Math.cos(o*2*(i.bounces??1)))/2,c=i.crouch??0,h=i.shoulder??0,d=i.forearm??0,u={...ut,...n};u["leg.left.swing"]=i.swing*r+c*.6,u["leg.right.swing"]=-i.swing*r+c*.6,u["leg.left.knee"]=i.knee*Math.max(0,a)+c*1.2,u["leg.right.knee"]=i.knee*Math.max(0,-a)+c*1.2,u["leg.left.ankle"]=it(n,"leg.left.ankle")-(i.tiptoe??0),u["leg.right.ankle"]=it(n,"leg.right.ankle")-(i.tiptoe??0);for(const[f,g]of[["left",-1],["right",1]])it(n,`arm.${f}.spread`)>ud||it(n,`arm.${f}.swing`)>ud||(u[`arm.${f}.swing`]=h+g*i.arm*r,u[`arm.${f}.elbow`]=it(n,`arm.${f}.elbow`)+d+i.elbow*Math.max(0,g*r));return u.lean=it(n,"lean")+i.lean*s,u.bend=it(n,"bend")+(i.bend??0),u["head.nod"]=it(n,"head.nod")-i.lean*.5*s+(i.headTilt??0),u.side=it(n,"side")+(i.sway??0)*Math.sin(o),u.lift=it(n,"lift")+(i.bounce??0)*s*l,u.stretch=it(n,"stretch")*(1+(i.squash??0)*(l-.5)),u}function pd(t,e,n=1){const s=Yn(t);return 4*Ey*e*Math.sin(s.swing*n*Math.PI/180)}const fn=t=>rr[t],gi={take:t=>[{after:140,pose:{stretch:.8,bend:10,lean:it(t,"lean")-4,...jt("arm",{spread:6,swing:0,elbow:10}),"eye.left":.35,"eye.right":.35,"brow.left":-.6,"brow.right":-.6,mouth:0},easing:"ease-in-out"},{after:260,pose:{stretch:.78}},{after:360,pose:{lift:.22,stretch:1.35,bend:-14,...jt("arm",{spread:150,bend:35,swing:0,elbow:0}),...jt("leg",{swing:25,knee:60}),...fn("shocked")},easing:"ease-out-cubic"},{after:720,pose:{lift:.25,stretch:1.25,bend:-10,...jt("arm",{spread:140})},easing:"ease-in-out"},{after:900,pose:{lift:0,stretch:.74,bend:12,...jt("arm",{spread:70,bend:0}),...jt("leg",{swing:30,knee:60})},easing:"ease-in-quad"},{after:1060,pose:{stretch:1.06,bend:-3,...jt("arm",{spread:60}),"leg.left.swing":it(t,"leg.left.swing"),"leg.right.swing":it(t,"leg.right.swing"),"leg.left.knee":it(t,"leg.left.knee"),"leg.right.knee":it(t,"leg.right.knee")},easing:"ease-out"},{after:1260,pose:{stretch:it(t,"stretch"),bend:it(t,"bend"),...fn("surprised"),...jt("arm",{spread:55,bend:60})},easing:"ease-in-out"}],doubleTake:t=>[{after:160,pose:{lookX:1,lookY:0,"head.turn":0},easing:"ease-out"},{after:520,pose:{lookX:-.6,"head.turn":30,"head.nod":it(t,"head.nod")-4,smile:.6,mouth:0},easing:"ease-in-out"},{after:1100,pose:{lookX:-.6}},{after:1180,pose:{"head.turn":0,"head.nod":it(t,"head.nod")-10,bend:it(t,"bend")-10,lift:.05,stretch:1.18,...fn("shocked"),lookX:1,lookY:0},easing:"ease-out-cubic"},{after:1360,pose:{lift:0,stretch:.88,"head.nod":it(t,"head.nod")-4,bend:it(t,"bend")+4},easing:"ease-in-quad"},{after:1560,pose:{stretch:it(t,"stretch"),"head.nod":it(t,"head.nod"),bend:it(t,"bend")},easing:{type:"elastic",mode:"out",amplitude:1,period:.35}}],windUp:()=>[{after:220,pose:{lean:-18,bend:-16,"head.nod":-6,"arm.left.swing":60,"arm.left.elbow":100,"arm.right.swing":-40,"arm.right.elbow":90,"leg.left.swing":55,"leg.left.knee":95,stretch:.92,...fn("angry"),lookX:1},easing:"ease-out"},{after:620,pose:{lean:-20,bend:-18,stretch:.9}},{after:700,pose:{lean:28,bend:14,"head.nod":6,"arm.left.swing":-30,"arm.right.swing":60,"leg.left.swing":-20,"leg.left.knee":30,"leg.right.swing":20,stretch:1.12},easing:"ease-out-cubic"}],land:t=>[{after:120,pose:{lift:0,stretch:.7,bend:14,...jt("arm",{spread:75}),...jt("leg",{swing:25,knee:50})},easing:"ease-in-quad"},{after:300,pose:{stretch:1.05,bend:-4,"arm.left.spread":it(t,"arm.left.spread"),"arm.right.spread":it(t,"arm.right.spread")},easing:"ease-out"},{after:460,pose:{lift:0,stretch:it(t,"stretch"),bend:it(t,"bend"),...jt("leg",{swing:0,knee:0})},easing:"ease-in-out"}],tremble:t=>{const e=[{after:80,pose:{...fn("scared"),...jt("arm",{swing:40,elbow:110,spread:14}),stretch:.94,bend:it(t,"bend")+8},easing:"ease-out"}];for(let n=1;n<=14;n++){const s=n%2===0?1:-1;e.push({after:80+n*45,pose:{side:it(t,"side")+2.5*s,"head.tilt":it(t,"head.tilt")-2*s}})}return e.push({after:755,pose:{side:it(t,"side"),"head.tilt":it(t,"head.tilt"),bend:it(t,"bend")}}),e},deflate:t=>[{after:260,pose:{stretch:1.04,"head.nod":it(t,"head.nod")-4,"brow.left":.3,"brow.right":.3},easing:"ease-in-out"},{after:900,pose:{...fn("sad"),bend:18,stretch:.92,lean:it(t,"lean")+5,"head.nod":14,...jt("arm",{spread:6,swing:0,elbow:4,bend:0})},easing:"ease-in-out"}]};function gd(t,e){const n=Ft(e.from??{}),s=e.speed??1;let i=n;return[{time:e.at,pose:n},...gi[t](n).map(o=>(i={...i,...o.pose},{time:e.at+o.after*s,pose:i,act:!1,...o.easing?{easing:o.easing}:{}}))]}const Ay=new Set(["x","y","z","position","rotateX","rotateY","rotateZ","quaternion","scale","scaleX","scaleY","scaleZ","visible","opacity","color"]),$y=new Set(["walk","walking","gait"]),md=t=>typeof t=="number"?t:void 0,Py=1.7;function xy(t,e,n){const s=Array.from({length:24},(i,o)=>{const r=o/24*Math.PI*2,a=e.toView([Math.cos(r)*n,0,Math.sin(r)*n*.8]);return a[2]<-.001?e.toScreen(a):null});s.some(i=>i===null)||(t.beginPath(),s.forEach((i,o)=>o===0?t.moveTo(i.x,i.y):t.lineTo(i.x,i.y)),t.closePath(),t.fillStyle="rgba(0, 0, 0, 0.22)",t.fill())}function Iy(t){const e=ue([0,1,0],t);if(e>.999999)return Os();if(e<-.999999)return zt(Wt([1,0,0],180));const n=xs([0,1,0],t);return zt(Wt(n,Math.acos(e)*180/Math.PI))}function Oy(t,e,n,s,i){const o=t.solid??{},r=o.outline===!1?void 0:o.outline??{width:2,color:"#0f172a"},a={color:o.color??"#475569",shading:o.shading??"toon",outline:r},l={color:o.skin??"#f2c49b",shading:o.shading??"toon",outline:r},c={color:"#0f172a",shading:"unlit"},h=s.height*.034,d=[],u=(k,y,M)=>d.push({mesh:k,world:mt(i,y),material:M}),f=(k,y,M)=>u(e.sphere,bo(k,[0,0,0,1],[y,y,y]),M);for(const k of n.chains){const y=s.chains[k.id],M=k.id==="spine"?1.9:1;k.bones.forEach(($,E)=>{const A=y[E],T=y[E+1],I=yo(A,T),[v,P]=$.width??[1,1],H=h*M*(v+P)/2;if(I>1e-6){const O=jl(A,T,.5),C=Iy(Pe(tn(T,A)));u(e.cylinder,mt(xe(O),mt(C,Ie([H,I,H]))),a)}f(A,h*M*v,a),f(T,h*M*P,a)}),k.id.startsWith("arm.")&&f(y[y.length-1],h*1.5,l)}const{center:g,rx:p,ry:m,axes:b}=s.head,S=[...b[0],0,...b[1],0,...b[2],0,...g,1];u(e.sphere,mt(S,Ie([p,m,p])),l);for(const k of[-1,1]){const y=Pe([k*.36,.15,.92]),M=Ps(g,Ps(Ps(en(b[0],y[0]*p*1.04),en(b[1],y[1]*m*1.04)),en(b[2],y[2]*p*1.04))),$=[...b[0],0,...b[1],0,...b[2],0,...M,1];u(e.sphere,mt($,Ie([p*.11,m*.14,p*.03])),c)}return d}const _y={kind:"character",validate(t){const e=t;return e.height!==void 0&&!(e.height>0)?["a character's height must be positive"]:[]},prepare(t){return{who:mr({...t.character,height:1}),cylinder:ai(Gh(1,1,16)),sphere:ai(Q1(1,20))}},resolve({object:t,prepared:e,values:n,world:s,camera:i,lights:o=[],fog:r,toScreen:a}){const l=t,c=e,h=c.who;let d={...ut,...l.pose};for(const[A,T]of n)typeof T=="number"&&!Ay.has(A)&&!$y.has(A)&&(d[A]=T);const u=Math.max(0,Math.min(1,md(n.get("walking"))??l.walking??0));if(u>0){const A=typeof n.get("gait")=="string"?n.get("gait"):l.gait,T=fd(A,md(n.get("walk"))??0,d);d=Object.fromEntries(Object.keys({...d,...T}).map(I=>[I,(d[I]??0)+((T[I]??0)-(d[I]??0))*u]))}const f=l.height??Py,g=mt(i.view,s),p={toView:A=>Rt(g,A),toScreen:A=>a(A)},b=-p.toView([0,f/2,0])[2];if(b<=i.near)return null;const S=l.shadow===!1?[]:[{depth:b+f,draw:A=>xy(A,p,f*.18)}];if(l.look==="solid"){const A=oi(h.plan,d,{height:f,contact:h.contact});return{meshes:Oy(l,c,h.plan,A,s),drawables:S}}const k=Rt(s,[0,f*.6,0]),y=Pe(tn(i.position,k)),M=rd(k,y,o).map(A=>Math.min(1,A)),$=o.length>0&&h.skin!=="none"?{...h,skin:xr(h.skin,M,ad(r,yo(k,i.position)),r?.color)}:h,E=sd($,d,p,{height:f});return{drawables:[...S,...E.map((A,T)=>({depth:-A.depth-T*1e-6,draw:(I,v)=>A.draw(I,v.time)}))]}}},Zn=([t,e,n])=>{const s=Math.hypot(t,e,n)||1;return[t/s,e/s,n/s]};function yd([t,e,n]){const[s,i,o]=[t/2,e/2,n/2];return{vertices:[[-s,-i,-o],[s,-i,-o],[s,i,-o],[-s,i,-o],[-s,-i,o],[s,-i,o],[s,i,o],[-s,i,o]],faces:[{corners:[4,5,6,7],normal:[0,0,1]},{corners:[1,0,3,2],normal:[0,0,-1]},{corners:[5,1,2,6],normal:[1,0,0]},{corners:[0,4,7,3],normal:[-1,0,0]},{corners:[7,6,2,3],normal:[0,1,0]},{corners:[0,1,5,4],normal:[0,-1,0]}]}}const pn=(t,[e,n,s])=>t==="z"?[e,n,s]:t==="x"?[s,n,e]:[e,s,n];function bd(t,e,n="x",s=20,i=0){const o=[],r=e/2;for(const c of[-r,r])for(let h=0;h<s;h++){const d=Math.PI*2*h/s;o.push(pn(n,[Math.cos(d)*t,Math.sin(d)*t,c]))}const a=[{corners:Array.from({length:s},(c,h)=>s-1-h),normal:pn(n,[0,0,-1])},{corners:Array.from({length:s},(c,h)=>s+h),normal:pn(n,[0,0,1])}];for(let c=0;c<s;c++){const h=(c+1)%s,d=Math.PI*2*(c+.5)/s;a.push({corners:[c,h,s+h,s+c],normal:pn(n,[Math.cos(d),Math.sin(d),0])})}const l=[];if(i>0)for(const c of[-r,r]){const h=o.push(pn(n,[0,0,c*1.01]))-1;for(let d=0;d<i;d++){const u=Math.PI*2*d/i,f=o.push(pn(n,[Math.cos(u)*t*.82,Math.sin(u)*t*.82,c*1.01]))-1;l.push([h,f])}}return{vertices:o,faces:a,marks:l,creases:!0}}function wd([t,e,n],s=16){const i=Math.max(4,Math.round(s/2)),o=[[0,e,0]];for(let h=1;h<i;h++){const d=Math.PI*h/i;for(let u=0;u<s;u++){const f=Math.PI*2*u/s;o.push([Math.sin(d)*Math.cos(f)*t,Math.cos(d)*e,Math.sin(d)*Math.sin(f)*n])}}const r=o.push([0,-e,0])-1,a=(h,d)=>1+(h-1)*s+d%s,l=h=>{const d=h.reduce((u,f)=>[u[0]+o[f][0],u[1]+o[f][1],u[2]+o[f][2]],[0,0,0]);return Zn([d[0]/(t*t),d[1]/(e*e),d[2]/(n*n)])},c=[];for(let h=0;h<s;h++){const d=[0,a(1,h+1),a(1,h)];c.push({corners:d,normal:l(d)});for(let f=1;f<i-1;f++){const g=[a(f,h),a(f,h+1),a(f+1,h+1),a(f+1,h)];c.push({corners:g,normal:l(g)})}const u=[a(i-1,h),a(i-1,h+1),r];c.push({corners:u,normal:l(u)})}return{vertices:o,faces:c,creases:!1}}const Cy=t=>t.reduce((e,[n,s],i)=>{const[o,r]=t[(i+1)%t.length];return e+n*r-o*s},0)/2;function kd(t,e){const n=Cy(t)<0?[...t].reverse():t,s=n.length,i=e/2,o=[...n.map(([a,l])=>[i,l,a]),...n.map(([a,l])=>[-i,l,a])],r=[{corners:Array.from({length:s},(a,l)=>s-1-l),normal:[1,0,0]},{corners:Array.from({length:s},(a,l)=>s+l),normal:[-1,0,0]}];for(let a=0;a<s;a++){const l=(a+1)%s,[c,h]=[n[l][0]-n[a][0],n[l][1]-n[a][1]];r.push({corners:[a,l,s+l,s+a],normal:Zn([0,-c,h])})}return{vertices:o,faces:r,creases:!0}}function vd(t,e){const n={left:([i,o])=>[0,o,i],right:([i,o])=>[0,o,i],front:([i,o])=>[i,o,0],back:([i,o])=>[i,o,0],up:([i,o])=>[i,0,o]},s={left:[1,0,0],right:[-1,0,0],front:[0,0,1],back:[0,0,-1],up:[0,1,0]};return{vertices:t.map(n[e]),faces:[{corners:t.map((i,o)=>o),normal:s[e]}]}}function Md(t,e,n=8){const s=r=>Array.isArray(e)?e[Math.min(r,e.length-1)]:e,i=[],o=[];t.forEach((r,a)=>{const l=t[Math.min(a+1,t.length-1)],c=t[Math.max(a-1,0)],h=Zn([l[0]-c[0],l[1]-c[1],l[2]-c[2]]),d=Math.abs(h[1])<.9?[0,1,0]:[1,0,0],u=Zn(Sd(h,d)),f=Sd(u,h);for(let g=0;g<n;g++){const p=Math.PI*2*g/n,m=Math.cos(p)*s(a),b=Math.sin(p)*s(a);i.push([r[0]+u[0]*m+f[0]*b,r[1]+u[1]*m+f[1]*b,r[2]+u[2]*m+f[2]*b])}});for(let r=0;r<t.length-1;r++)for(let a=0;a<n;a++){const l=(a+1)%n,c=[r*n+a,r*n+l,(r+1)*n+l,(r+1)*n+a],h=c.reduce((u,f)=>[u[0]+i[f][0]/4,u[1]+i[f][1]/4,u[2]+i[f][2]/4],[0,0,0]),d=[(t[r][0]+t[r+1][0])/2,(t[r][1]+t[r+1][1])/2,(t[r][2]+t[r+1][2])/2];o.push({corners:c,normal:Zn([h[0]-d[0],h[1]-d[1],h[2]-d[2]])})}return{vertices:i,faces:o,creases:!1}}function Sd(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function Td(t){switch(t.type){case"box":return yd(t.size);case"cylinder":return bd(t.radius,t.length,t.axis,t.segments,t.spokes);case"ellipsoid":return wd(t.radii,t.segments);case"extrude":return kd(t.profile,t.width);case"panel":return vd(t.points,t.facing);case"tube":return{...Md(t.points,t.radius,t.segments),joined:t.joined}}}function Or(t,e){if(t.length<2)return t;const n=i=>t[Math.max(0,Math.min(t.length-1,i))],s=i=>{const o=i*(t.length-1),r=Math.min(t.length-2,Math.floor(o)),a=o-r,[l,c,h,d]=[n(r-1),n(r),n(r+1),n(r+2)];return[0,1,2].map(u=>{const f=l[u],g=c[u],p=h[u],m=d[u];return .5*(2*g+(-f+p)*a+(2*f-5*g+4*p-m)*a*a+(-f+3*g-3*p+m)*a*a*a)})};return Array.from({length:e},(i,o)=>s(o/(e-1)))}const Le=t=>Array.isArray(t)&&t.length===2&&t.every(e=>typeof e=="number"&&Number.isFinite(e));function mi(t,e){return((e-t)%360+540)%360-180}function Ed(t){const e=t.map((n,s)=>({frame:n,i:s})).sort((n,s)=>n.frame.time-s.frame.time||n.i-s.i).map(({frame:n})=>n);return e.filter((n,s)=>s+1>=e.length||e[s+1].time!==n.time)}function gn(t,e){return Math.atan2(e[0]-t[0],e[1]-t[1])*180/Math.PI}function Ad(t){const e=t.filter((i,o)=>o===0||Math.hypot(i[0]-t[o-1][0],i[1]-t[o-1][1])>1e-6);if(e.length<2)return[];const n=e.length===2?e:Or(e.map(([i,o])=>[i,0,o]),(e.length-1)*12).map(([i,,o])=>[i,o]);let s=0;return n.map((i,o)=>(o>0&&(s+=Math.hypot(i[0]-n[o-1][0],i[1]-n[o-1][1])),{point:i,at:s}))}function $d(t,e){let n=1;for(;n<t.length-1&&t[n].at<e;)n++;const s=t[n-1],i=t[n],o=i.at>s.at?Math.max(0,Math.min(1,(e-s.at)/(i.at-s.at))):0;return{point:[s.point[0]+(i.point[0]-s.point[0])*o,s.point[1]+(i.point[1]-s.point[1])*o],direction:[i.point[0]-s.point[0],i.point[1]-s.point[1]]}}function Pd(t,e){if(e<=0)return 0;if(e>=1)return 1;let n=0,s=1;for(let i=0;i<40;i++){const o=(n+s)/2;t(o)<e?n=o:s=o}return(n+s)/2}const _r=["do","at","for","to","through","toward","speed","pose","gag"],xd={walk:1.3,bouncy:1.4,doubleBounce:1.2,sneak:.6,strut:1.2,tired:.8,run:3.6,shove:.7},Cr=Object.keys(Ot),Hr=Object.keys(Re),Rr=Object.keys(gi),Hy=.25,Ry=700/180,Ly=200,Ny=300;function Id(t){if(!Array.isArray(t))return[{beat:-1,message:`Beats must be an array of { do: … } objects (got ${typeof t}).`}];const e=[...Cr,"face","hold","pose","gag","place"],n=[];return t.forEach((s,i)=>{const o=c=>n.push({beat:i,message:c});if(!s||typeof s!="object"||Array.isArray(s))return o("Each beat must be an object like { do: 'walk', to: [x, z] }.");const r=s,a={duration:"for",path:"through",position:"to",heading:"toward",direction:"toward"};for(const c of Object.keys(r))_r.includes(c)||o(ot("beat field",c,_r,a[c]));const l=typeof r.do=="string"?Hr.includes(r.do)?"pose":Rr.includes(r.do)?"gag":r.do==="turn"?"face":void 0:void 0;if(typeof r.do!="string"||!e.includes(r.do))return o(ot("character 3D beat",r.do,e,l));Cr.includes(r.do)&&(r.to===void 0&&r.through===void 0&&o(`\`${r.do}\` needs \`to\` ([x, z] metres) or \`through\` (a list of them).`),r.to!==void 0&&!Le(r.to)&&o(`\`to\` is a point on the ground, [x, z] metres (got ${JSON.stringify(r.to)}).`),r.through!==void 0&&!(Array.isArray(r.through)&&r.through.length>0&&r.through.every(Le))&&o("`through` is a list of points on the ground, each [x, z] metres.")),r.do==="place"&&!Le(r.to)&&o("`place` needs `to`: a point on the ground, [x, z] metres."),r.do==="face"&&!(Le(r.toward)||typeof r.toward=="number")&&o("`face` needs `toward`: a point [x, z] or a heading in degrees."),r.do==="pose"&&!(typeof r.pose=="object"&&r.pose!==null)&&!Hr.includes(r.pose)&&o(ot("pose",r.pose,Hr)),r.do==="gag"&&!Rr.includes(r.gag)&&o(ot("gag",r.gag,Rr))}),n}function Dy(t,e,n){const s=Id(e);if(s.length>0)throw new Error(`characterScript3D: ${s.length} problem(s) in the beats:
|
|
54
|
-
${s.map(
|
|
55
|
-
`)}`);const i=n.height??1.7,o={...ut,...n.pose};let[r,a]=n.position??[0,0],l=n.heading??0,c=0;const h=new Map,d=[],u=(y,M,$,E="linear")=>{const A=h.get(y)??[];A.push({time:M,value:$,easing:E}),h.set(y,A)};u("x",0,r),u("z",0,a),u("rotateY",0,l);const f=(y,M)=>{const $=mi(l,M);if(Math.abs($)<1)return y;const E=Math.max(Ly,Math.abs($)*Ry);return u("rotateY",y,l),l+=$,u("rotateY",y+E,l,"ease-in-out"),y+E},g=(y,M,$,E="ease-in-out")=>{for(const[A,T]of Object.entries($))o[A]!==T&&(u(A,y,o[A]??0),u(A,M,T,E),o[A]=T)},p=(y,M,$)=>{const E=Ad([[r,a],...M.through??[M.to]]);if(E.length<2)return $;const A=f($,gn(E[0].point,E[1].point)),T=E[E.length-1].at,I=M.speed??xd[y]*Math.sqrt(i/1.7),v=M.for??T/I*1e3,P=pd(y,i),H=xt("ease-in-out"),O=Math.min(Ny,v/4);d.push({time:A,value:y}),u("walking",A,0),u("walking",A+O,1,"ease-out"),u("walking",A+v-O,1),u("walking",A+v,0,"ease-in");const C=c;let j=l;for(let D=0;;D=Math.min(T,D+Hy)){const W=A+Pd(H,D/T)*v,{point:B,direction:_}=$d(E,D);if(j+=mi(j,gn([0,0],_)),u("x",W,B[0]),u("z",W,B[1]),u("rotateY",W,j),u("walk",W,C+D/P),D>=T)break}return c=C+T/P,[r,a]=E[E.length-1].point,l=j,A+v},m=[];let b=0;for(const y of e){const M=y.at??b;let $=M;if(Cr.includes(y.do))$=p(y.do,y,M);else if(y.do==="face")$=f(M,typeof y.toward=="number"?y.toward:gn([r,a],y.toward));else if(y.do==="hold")$=M+(y.for??1e3);else if(y.do==="place")u("x",M,r),u("z",M,a),[r,a]=y.to,u("x",M+1,r),u("z",M+1,a),typeof y.toward=="number"&&(u("rotateY",M,l),l=y.toward,u("rotateY",M+1,l)),$=M+1;else if(y.do==="pose"){$=M+(y.for??500);const E=typeof y.pose=="string"?Re[y.pose]:y.pose;g(M,$,E)}else if(y.do==="gag"){const E=gd(y.gag,{at:M,from:{...o}});let A=E[0];for(const T of E.slice(1))g(A.time,T.time,Object.fromEntries(Object.entries(T.pose).filter(([I,v])=>o[I]!==v)),T.easing??"ease-in-out"),A=T;$=A.time}m.push({do:y.do,start:M,end:$}),b=$}const S=`${n.scene}/${t}`,k=[...h].map(([y,M])=>({id:`${t}-${y}`,target:S,property:y,keyframes:Ed(M)}));return d.length>0&&k.push({id:`${t}-gait`,target:S,property:"gait",keyframes:d}),{tracks:k,duration:b,beats:m,end:{position:[r,a],heading:l,pose:{...o}}}}const Od={x:0,y:0,scale:1,rotate:0,shakeX:0,shakeY:0,shakeRotate:0};function Fy(t){const e=n=>{const s=t?.get(n);return typeof s=="number"?s:Od[n]};return{x:e("x"),y:e("y"),scale:e("scale"),rotate:e("rotate"),shakeX:e("shakeX"),shakeY:e("shakeY"),shakeRotate:e("shakeRotate")}}function jy(t,e,n){const s=n.width/2,i=n.height/2,r=1+2*Math.max(Math.abs(e.shakeX),Math.abs(e.shakeY))/Math.max(1,Math.min(n.width,n.height));t.translate(s+e.x+e.shakeX,i+e.y+e.shakeY),t.rotate((e.rotate+e.shakeRotate)*Math.PI/180),t.scale(e.scale*r,e.scale*r),t.translate(-s,-i)}function By(t,e,n){const s=e.width/2,i=e.height/2,o=(t.rotate+t.shakeRotate)*Math.PI/180,r=(n.x-s)*t.scale,a=(n.y-i)*t.scale;return{x:s+t.x+t.shakeX+r*Math.cos(o)-a*Math.sin(o),y:i+t.y+t.shakeY+r*Math.sin(o)+a*Math.cos(o)}}function _d(t,e,n={},s){const i=n.length??240,o=9,r=28,a=i-22;t.save(),t.translate(e.x,e.y),t.rotate((n.angle??-30)*Math.PI/180),t.fillStyle=n.color??"#f4c542",t.fillRect(r,-o,a-r,2*o),t.fillStyle="#e8b4a0",t.fillRect(a,-o,i-a,2*o),t.fillStyle="#f1dcbf",t.beginPath(),t.moveTo(0,0),t.lineTo(r,-o),t.lineTo(r,o),t.closePath(),t.fill(),t.fillStyle=n.outline??"#2f2f33",t.beginPath(),t.moveTo(0,0),t.lineTo(r*.35,-o*.35),t.lineTo(r*.35,o*.35),t.closePath(),t.fill(),t.strokeStyle=n.outline??"#2f2f33",t.lineWidth=3,t.lineJoin="round",t.lineCap="round";const l=[[{x:0,y:0},{x:r,y:-o},{x:i,y:-o},{x:i,y:o},{x:r,y:o},{x:0,y:0}],[{x:r,y:-o},{x:r,y:o}],[{x:a,y:-o},{x:a,y:o}]];for(const c of l)Rd(t,c,s);t.restore()}function Lr(t,e,n={},s){const i=n.length??90,o=n.thickness??34;t.save(),t.translate(e.x,e.y),t.rotate((n.angle??-35)*Math.PI/180);const r=-o/2;t.fillStyle=n.color??"#f4a7b9",t.fillRect(0,r,i,o),t.fillStyle="#e9edf2",t.fillRect(i*.45,r,i*.55,o),t.strokeStyle=n.outline??"#2f2f33",t.lineWidth=3,t.lineJoin="round";const a=[{x:0,y:r},{x:i,y:r},{x:i,y:-r},{x:0,y:-r},{x:0,y:r}],l=[{x:i*.45,y:r},{x:i*.45,y:-r}];if(s)s.line(a),s.line(l);else for(const c of[a,l]){t.beginPath(),t.moveTo(c[0].x,c[0].y);for(const h of c.slice(1))t.lineTo(h.x,h.y);t.stroke()}t.restore()}const Cd=150,Wy={pencil:44,eraser:30};function Nr(t,e,n={},s){const i=n.tool??"pencil",o=n.skin??"#f1c9a5",r=n.outline??"#2f2f33",a=n.scale??1,l=Math.min(1,Math.max(0,n.lift??0)),c=(n.angle??-30)*Math.PI/180,h=s?s.nudge(.6):{x:0,y:0},d=Cd*a*(1+.05*l);l>0&&(t.save(),t.fillStyle=r,t.globalAlpha=.15*l,t.beginPath(),t.ellipse(e.x,e.y,9*a,4*a,0,0,Math.PI*2),t.fill(),t.restore());const u={x:e.x+h.x+6*l*a,y:e.y+h.y-18*l*a},f=Tt.pencilGrip,g=E=>{const A=E.fingers.thumb,T=E.fingers.index,I=E.fingers.middle,v=Hd([A.points[3],T.points[3],I.points[3]]),P=Hd([A.points[1],T.points[0]]),H=(A.depths[3]+T.depths[3]+I.depths[3])/3;return{pinch:v,direction:Math.atan2(P.y-v.y,P.x-v.x),depth:H}},p=Ks(f,{size:d}),m=c-g(p).direction,b=Ks(f,{size:d,angle:m*180/Math.PI}),S=g(b),k=Wy[i]*a,y={x:S.pinch.x-Math.cos(c)*k,y:S.pinch.y-Math.sin(c)*k},M={x:u.x-y.x,y:u.y-y.y},$=b.axes.up;qy(t,M,{x:-$.x,y:-$.y},d,n.arm??300*a,o,n.sleeve??"#5b7db1",r),Ys(t,M,f,{size:d,angle:m*180/Math.PI,skin:o,ink:r,lineWidth:3*a,prop:{depth:S.depth,draw:()=>{t.save(),t.translate(u.x,u.y),t.scale(a,a),i==="eraser"?Lr(t,{x:0,y:0},{angle:c*180/Math.PI,outline:r},s):_d(t,{x:0,y:0},{angle:c*180/Math.PI,length:190,outline:r},s),t.restore()}}})}const Hd=t=>({x:t.reduce((e,n)=>e+n.x,0)/t.length,y:t.reduce((e,n)=>e+n.y,0)/t.length});function qy(t,e,n,s,i,o,r,a){const l={x:-n.y,y:n.x},c=s*.15,h=(p,m,b)=>({x:e.x+n.x*p+l.x*m*b,y:e.y+n.y*p+l.y*m*b}),d=h(i,0,0),u=p=>{const m=t.createLinearGradient(e.x,e.y,d.x,d.y);return m.addColorStop(0,p),m.addColorStop(.6,p),m.addColorStop(1,Xy(p)),m},f=Math.min(s*.55,i*.35);t.save(),t.lineJoin="round",t.lineCap="round",t.lineWidth=3*(s/Cd),t.beginPath(),t.moveTo(h(-s*.1,-1,c).x,h(-s*.1,-1,c).y),t.lineTo(h(f+4,-1,c*1.1).x,h(f+4,-1,c*1.1).y),t.lineTo(h(f+4,1,c*1.1).x,h(f+4,1,c*1.1).y),t.lineTo(h(-s*.1,1,c).x,h(-s*.1,1,c).y),t.closePath(),t.fillStyle=o,t.fill(),t.strokeStyle=a,t.beginPath(),t.moveTo(h(0,-1,c).x,h(0,-1,c).y),t.lineTo(h(f,-1,c*1.1).x,h(f,-1,c*1.1).y),t.moveTo(h(0,1,c).x,h(0,1,c).y),t.lineTo(h(f,1,c*1.1).x,h(f,1,c*1.1).y),t.stroke();const g=[h(f,-1,c*1.3),h(i,-1,c*1.5),h(i,1,c*1.5),h(f,1,c*1.3)];t.beginPath(),g.forEach((p,m)=>m?t.lineTo(p.x,p.y):t.moveTo(p.x,p.y)),t.closePath(),t.fillStyle=u(r),t.fill(),t.strokeStyle=u(a),t.beginPath(),t.moveTo(g[1].x,g[1].y),t.lineTo(g[0].x,g[0].y),t.lineTo(g[3].x,g[3].y),t.lineTo(g[2].x,g[2].y),t.stroke(),t.restore()}function Ky(t,e,n={}){const s=n.offstage??{x:2e3,y:1400},i=n.enter??450,o=n.exit??450,r=n.linger??1500,a=[...t].filter(p=>p.path.length>0).sort((p,m)=>p.start-m.start),l=p=>p.tool??"pencil",c=p=>{const m=Math.min(1,Math.max(0,p));return m*m*(3-2*m)},h=(p,m,b)=>({x:p.x+(m.x-p.x)*b,y:p.y+(m.y-p.y)*b}),d=a.find(p=>e>=p.start&&e<=p.end);if(d){const p=d.end-d.start,m=p>0?(e-d.start)/p:1;return{at:Fs(d.path,m),tool:l(d),lift:0,drawing:!0}}const u=[...a].reverse().find(p=>p.end<e),f=a.find(p=>p.start>e),g=p=>p.path[p.path.length-1];if(u&&f&&f.start-u.end<=r){const p=(e-u.end)/(f.start-u.end),m=p<.5?l(u):l(f);return{at:h(g(u),f.path[0],c(p)),tool:m,lift:Math.sin(Math.PI*p),drawing:!1}}if(f&&f.start-e<=i){const p=1-(f.start-e)/i;return{at:h(s,f.path[0],c(p)),tool:l(f),lift:1-c(p),drawing:!1}}if(u&&e-u.end<=o){const p=(e-u.end)/o;return{at:h(g(u),s,c(p)),tool:l(u),lift:c(p),drawing:!1}}return null}function Yy(t,e,n,s=.08,i=32){const o=Math.PI*2*(1+s),r=[];for(let a=0;a<=i;a++){const l=-Math.PI/2+o*a/i;r.push({x:t+Math.cos(l)*n,y:e+Math.sin(l)*n})}return r}function zy(t){const{path:e}=t,n=e.map(a=>a.x),s=e.map(a=>a.y),i=Math.min(...n),o=Math.min(...s),r=t.hand===!1?void 0:t.hand===!0||t.hand===void 0?{}:t.hand;return{type:"custom",x:i,y:o,width:Math.max(1,Math.max(...n)-i),height:Math.max(1,Math.max(...s)-o),props:{draw:0},draw(a,l,c){const h=Math.min(1,Math.max(0,Number(l.props?.draw??0)));a.translate(-i,-o),a.strokeStyle=t.color??"#2f2f33",a.lineWidth=t.lineWidth??5,a.lineCap="round",a.lineJoin="round";const d=t.sketch?js(a,t.sketch,c):void 0;h>0&&(d?t.smooth?d.curve(e,h):d.line(e,h):Rd(a,an(e,h))),r&&h>0&&h<1&&Nr(a,Fs(e,h),r,d)}}}function Xy(t){const e=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t.trim());if(!e)return"rgba(0, 0, 0, 0)";const n=e[1].length===3?[...e[1]].map(r=>r+r).join(""):e[1],[s,i,o]=[0,2,4].map(r=>parseInt(n.slice(r,r+2),16));return`rgba(${s}, ${i}, ${o}, 0)`}function Rd(t,e,n){if(!(e.length<2)){if(n)return n.line(e);t.beginPath(),t.moveTo(e[0].x,e[0].y);for(const s of e.slice(1))t.lineTo(s.x,s.y);t.stroke()}}const yi=1e5;function Uy(t,e,n,s,i=6){const o=[],r=Math.max(1,Math.round(i));for(let a=0;a<=r;a++)o.push({x:a%2===0?t:t+n,y:e+s*a/r});return o}function Dr(t,e,n,s){if(s<=0||e.length===0)return;const i=an(e,s),o=n/2,r=a=>{t.beginPath(),t.rect(-yi,-yi,2*yi,2*yi),a(),t.clip("evenodd")};for(const a of i)r(()=>{t.moveTo(a.x+o,a.y),t.arc(a.x,a.y,o,0,Math.PI*2)});for(let a=1;a<i.length;a++){const l=i[a-1],c=i[a],h=Math.hypot(c.x-l.x,c.y-l.y);if(h===0)continue;const d=-(c.y-l.y)/h*o,u=(c.x-l.x)/h*o;r(()=>{t.moveTo(l.x+d,l.y+u),t.lineTo(c.x+d,c.y+u),t.lineTo(c.x-d,c.y-u),t.lineTo(l.x-d,l.y-u),t.closePath()})}}function Gy(t,e,n,s,i){t.save(),Dr(t,e,n,s),i(),t.restore()}function Vy(t,e){const n=e.width??40,s=e.hand===!0?{}:e.hand||void 0,i=e.eraser===!1?void 0:e.eraser===!0||e.eraser===void 0?{}:e.eraser;return{...t,props:{...t.props,erase:0},draw(o,r,a){const l=Number(r.props?.erase??0);if(o.save(),Dr(o,e.path,n,l),t.draw(o,r,a),o.restore(),!i||l<=0||l>=1)return;const c=Fs(e.path,l);s?Nr(o,c,{...s,tool:"eraser"}):Lr(o,c,i)}}}function Qn(){const t=new Map,e=(n,...s)=>t.set(n,[...t.get(n)??[],...s]);return{keys:n=>t.get(n),push:e,tween(n,s,i,o,r=300){e(n,{time:o.at,value:s},{time:o.at+(o.duration??r),value:i,...o.easing?{easing:o.easing}:{}})},last(n,s){const i=t.get(n);return i?[...i].sort((o,r)=>o.time-r.time)[i.length-1].value:s},valueAt:(n,s)=>bi(t.get(n),s),cutAfter(n,s){for(const i of n)t.set(i,(t.get(i)??[]).filter(o=>o.time<=s))},tracks(n){return[...t].filter(([,s])=>s.length>0).map(([s,i])=>({id:`${n}-${s}`,target:n,property:s,keyframes:Jy(i)}))}}}function bi(t,e){if(!t||t.length===0)return 0;const n=[...t].sort((s,i)=>s.time-i.time);if(e<=n[0].time)return n[0].value;for(let s=1;s<n.length;s++)if(e<=n[s].time){const i=n[s-1],o=n[s];return o.time===i.time?o.value:i.value+(o.value-i.value)*(e-i.time)/(o.time-i.time)}return n[n.length-1].value}function wi(t){const e=[...t??[]].sort((n,s)=>n.time-s.time);return e.slice(1).flatMap((n,s)=>n.value!==e[s].value?[{start:e[s].time,end:n.time}]:[])}function Jy(t){return[...t].sort((n,s)=>n.time-s.time).map(n=>({time:n.time,value:n.value,...n.easing?{easing:n.easing}:{}}))}const Zy=.0016,Qy=.6,Ne=33;function ts(t){const e=(o,r)=>`piece.${o.id}.${r}`,n=(o,r)=>({x:o.home.x+t.valueAt(e(o,"x"),r),y:o.home.y+t.valueAt(e(o,"y"),r)}),s=(o,r)=>{const a=t.keys(e(o,"x"));if(!a||a.length<2)return;const l=n(o,r-Ne),c=n(o,r);return{x:(c.x-l.x)/Ne,y:(c.y-l.y)/Ne}},i=(o,r)=>t.cutAfter(["x","y","rotate"].map(a=>e(o,a)),r);return{at:n,cutAfter:i,follow(o,r){for(const a of r)t.push(e(o,"x"),{time:a.time,value:a.x-o.home.x}),t.push(e(o,"y"),{time:a.time,value:a.y-o.home.y})},fling(o,r){const a=n(o,r.at),l=r.velocity??s(o,r.at)??{x:.5,y:-.6},c=r.gravity??Zy,h=r.duration??900,d=(r.spin??Qy)*(l.x<0?-1:1),u=t.valueAt(e(o,"rotate"),r.at);i(o,r.at);for(let f=0;f<=h;f+=Ne){const g=a.x+l.x*f,p=a.y+l.y*f+.5*c*f*f;t.push(e(o,"x"),{time:r.at+f,value:g-o.home.x}),t.push(e(o,"y"),{time:r.at+f,value:p-o.home.y}),t.push(e(o,"rotate"),{time:r.at+f,value:u+d*f})}t.tween(e(o,"opacity"),1,0,{at:r.at+h*.6,duration:h*.4})},move(o,r){const a=n(o,r.at);t.tween(e(o,"x"),a.x-o.home.x,r.to.x-o.home.x,r,400),t.tween(e(o,"y"),a.y-o.home.y,r.to.y-o.home.y,r,400)}}}function Fr(t,e,{ground:n,every:s,floors:i}){if(i.every(k=>k.windows.length===0))return t;const o=t.find(k=>k.target===e&&k.property==="y"),r=new Ht({id:`${e}-ride`,tracks:o?[o]:[]}),a=k=>o?Number(r.getStateAtTime(k).values.get(e)?.get("y")??0):0,l=k=>{const y=n+a(k);return i.findIndex(M=>Math.abs(M.top-y)<.5)},c=(o?.keyframes??[]).map(k=>k.time),h=k=>{const y=T=>T<0?0:i[T].offset(k),M=l(k);if(M>=0)return y(M);if(Math.abs(a(k))<.5)return 0;const $=T=>l(T)>=0||Math.abs(a(T))<.5,E=[...c].reverse().find(T=>T<=k&&$(T)),A=c.find(T=>T>=k&&$(T));return E===void 0&&A===void 0?0:E===void 0?y(l(A)):A===void 0||A===E?y(l(E)):y(l(E))+(y(l(A))-y(l(E)))*(k-E)/(A-E)},d=i.flatMap(k=>k.windows),u=(k,y)=>d.some(M=>M.start<y&&M.end>k)||h(k)!==h(y),f=o?[...o.keyframes]:[{time:0,value:0}],g=[{...f[0],value:f[0].value+h(f[0].time)}],p=(k,y)=>{const M=new Set([y]);for(let $=k+s;$<y;$+=s)M.add($);for(const $ of d)for(const E of[$.start,$.end])E>k&&E<y&&M.add(E);for(const $ of[...M].sort((E,A)=>E-A))g.push({time:$,value:a($)+h($)})};for(let k=1;k<f.length;k++){const y=f[k-1].time,M=f[k].time;u(y,M)?p(y,M):g.push({...f[k],value:f[k].value+h(M)})}const m=f[f.length-1].time,b=Math.max(m,...d.map(k=>k.end));b>m&&p(m,b);const S={id:o?.id??`${e}-y`,target:e,property:"y",keyframes:g};return o?t.map(k=>k===o?S:k):[...t,S]}function De(t){const e=t.indexOf(":");return e<0?{kind:t,rest:""}:{kind:t.slice(0,e),rest:t.slice(e+1)}}function ve(t,e,n,s){const i=Object.keys(n.anchors).map(r=>De(r).kind),{kind:o}=De(e);return i.includes(o)?new Error(`${t}: no anchor "${e}"${s?`: ${s}`:""} (anchors: ${Object.keys(n.anchors).join(", ")})`):new Error(`${t}: ${ot("anchor",o,i)} (anchors: ${Object.keys(n.anchors).join(", ")})`)}function es(t,e,n){return new Error(`${t}.edit: ${ot("edit",e,Object.keys(n.edits))}`)}function bt(t,e,n,s){return{x:t+n/2,y:e+s/2,left:t,right:t+n,top:e,bottom:e+s,width:n,height:s}}const Ld={background:"#1e1e2e",gutter:"#6c7086",text:"#cdd6f4",keyword:"#cba6f7",string:"#a6e3a1",number:"#fab387",comment:"#7f849c",highlight:"rgba(249, 226, 175, 0.22)",strike:"#f38ba8",font:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace"},ki=["wipe","fly","blur"],ns={kind:"code",create:"codePanel({ code, language?, x, y, fontSize?, lineHeight?, width?, hidden? })",anchors:{box:"the whole panel","line:N":"line N’s text (lines count from 1): stand on top, point at x, y, swipe left to right","token:N:TEXT":"the first TEXT on line N (token:N#K:TEXT for the Kth): a word, which can come loose as a piece","spot:N:C":"a place in line N before column C (0 is before its first character); spot:N:C:W is W characters wide. Aim a put or a write here"},edits:{highlight:"line anchors; { at, duration?, on? }: tint lines (on: false clears)",strike:"line anchors; { at, duration? }: strike lines through, left to right",remove:"line anchors; { at, duration?, style?: wipe | fly | blur, from?: left | right, close? }: take lines away; the lines below close the gap",type:"line anchors given in `hidden`; { at, duration? }: type them in",insert:"a spot; { at, text, duration? }: type new text into the line there; the line makes room",write:"a token; { at, text, duration? }: write new text into the word’s place",drop:"a token; { at, into: a spot, duration? }: put the word into a line there",move:"a token; { at, to: an anchor name or { x, y }, duration? }: move the word there",fling:"a token; { at, velocity?, spin?, gravity?, duration? }: throw or kick the word away on a spinning arc"}},tb=.9,eb=8;function nb(t){const e={...Ld,...t.theme},n=t.code.replace(/\t/g," ").replace(/\n$/,"").split(`
|
|
56
|
-
`),s=t.fontSize??16,i=(t.lineHeight??1.6)*s,o=(t.charWidth??.6)*s,r=t.padding??12,a=t.lineNumbers===!1?0:(String(n.length).length+2)*o,l=Math.max(1,...n.map(_=>_.length)),c=t.width??r*2+a+l*o,h=r*2+n.length*i,d=t.x+r+a,u=new Set(t.hidden??[]),f=t.language??"plain";if(!Mi.includes(f))throw new Error(`codePanel: ${ot("language",f,Mi)}`);const g=n.map(_=>Dd(_,f).flatMap(L=>Array.from(L.text,()=>e[L.kind]))),p=Qn(),m=ts(p),b=[],S=new Map,k=[],y=[],M=_=>{if(!Number.isInteger(_)||_<1||_>n.length)throw new Error(`codePanel: no line ${_} (it has ${n.length})`)},$=p.tween,E=p.last,A=(_,L,N,x,R,q=300)=>{M(_),$(`line.${_}.${L}`,N,x,R,q)},T=(_,L)=>b.filter(N=>N.line<_&&N.closed<=L).length,I=bt,v=_=>t.y+r+(_-1)*i,P=_=>Array.isArray(_)?_:[_],H=(_,L,N)=>{let x=-1;for(let R=0;R<N;R++)if(x=n[_-1].indexOf(L,x+1),x<0)throw new Error(`codePanel: line ${_} has no ${N>1?`${N}th `:""}"${L}"`);return x},O={};n.forEach((_,L)=>{const N=L+1;O[`line.${N}.highlight`]=0,O[`line.${N}.strike`]=0,O[`line.${N}.wipe`]=0,O[`line.${N}.reveal`]=u.has(N)?0:1,O[`line.${N}.shift`]=0});const C={type:"custom",x:t.x,y:t.y,width:c,height:h,props:O,about:{kind:"code panel",summary:`${n.length} lines of ${f} code. Its lines and words are places in the scene (line(), token(), spot()); its edits are methods that record tracks (tracks()).`,get props(){return ib(Object.keys(O))},actions:jr},draw(_,L){const N=L.props??{},x=Y=>Number(N[Y]??O[Y]),R=r+a,q=Y=>r+(Y-1)*i-x(`line.${Y}.shift`)*i;_.fillStyle=e.background,Nd(_,0,0,c,h,8),_.fill(),_.font=`${s}px ${e.font}`,_.textBaseline="middle",_.textAlign="left";const U=(Y,Z,nt,F,z)=>{const K=n[Y-1];for(let V=Z;V<nt;V++)K[V]!==" "&&(_.fillStyle=g[Y-1][V],_.fillText(K[V],F+(V-Z)*o,z))};_.save(),Nd(_,0,0,c,h,8),_.clip(),n.forEach((Y,Z)=>{const nt=Z+1,F=x(`line.${nt}.wipe`);if(F>=1)return;const z=q(nt),K=z+i/2,V=Math.max(1,Y.length)*o,Q=Math.round(x(`line.${nt}.reveal`)*Y.length),tt=S.get(nt)??{style:"wipe",from:"left"};_.save(),F>0&&sb(_,tt,F,{left:R-a,top:z,width:a+V+o,height:i},c);const st=x(`line.${nt}.highlight`);st>0&&(_.globalAlpha*=Math.min(1,st),_.fillStyle=e.highlight,_.fillRect(R-o/2,z,V+o,i),_.globalAlpha/=Math.min(1,st)),a>0&&Q>0&&(_.fillStyle=e.gutter,_.textAlign="right",_.fillText(String(nt),R-o,K),_.textAlign="left");const pt=[...k.filter(J=>J.line===nt).map(J=>({column:J.column,length:J.text.length,piece:J,insert:void 0})),...y.filter(J=>J.line===nt).map(J=>({column:J.column,length:0,piece:void 0,insert:J}))].sort((J,kt)=>J.column-kt.column||J.length-kt.length);let ht=0,rt=R;for(const J of pt){U(nt,ht,Math.min(J.column,Q),rt,K),rt+=(J.column-ht)*o;let kt=J.length,gt="";if(J.piece){const X=J.piece.written??"",G=x(`piece.${J.piece.id}.write`);X&&G>0?(gt=X.slice(0,Math.round(G*X.length)),kt=J.length+(X.length-J.length)*Math.min(1,G*2)):kt=J.length*(1-x(`piece.${J.piece.id}.away`))}else J.insert&&(kt=J.insert.chars*x(`insert.${J.insert.id}.open`),J.insert.text&&(gt=J.insert.text.slice(0,Math.round(x(`insert.${J.insert.id}.type`)*J.insert.text.length))));_.fillStyle=e.text;for(let X=0;X<gt.length;X++)gt[X]!==" "&&_.fillText(gt[X],rt+X*o,K);rt+=kt*o,ht=J.column+J.length}U(nt,ht,Math.max(ht,Q),rt,K);const wt=x(`line.${nt}.strike`);wt>0&&(_.strokeStyle=e.strike,_.lineWidth=Math.max(1.5,s/10),_.beginPath(),_.moveTo(R,K),_.lineTo(R+V*Math.min(1,wt),K),_.stroke()),_.restore()});for(const Y of k){const Z=x(`piece.${Y.id}.opacity`);if(Z<=0||x(`line.${Y.line}.wipe`)>=1)continue;const nt=R+(Y.column+Y.text.length/2)*o+x(`piece.${Y.id}.x`),F=q(Y.line)+i/2+x(`piece.${Y.id}.y`);_.save(),_.globalAlpha=Math.min(1,Z),_.translate(nt,F),_.rotate(x(`piece.${Y.id}.rotate`)*Math.PI/180),U(Y.line,Y.column,Y.column+Y.text.length,-Y.text.length*o/2,0),_.restore()}_.restore()}},j=_=>{const{kind:L,rest:N}=De(_),x=R=>ve("codePanel",_,ns,R);if(L==="box"){if(N)throw x("box takes no arguments");return{kind:L}}if(L==="line"){if(!/^\d+$/.test(N))throw x("write it line:N");return{kind:L,n:Number(N)}}if(L==="token"){const R=/^(\d+)(?:#(\d+))?:(.+)$/.exec(N);if(!R)throw x("write it token:N:TEXT, or token:N#K:TEXT for the Kth");return{kind:L,n:Number(R[1]),occurrence:R[2]?Number(R[2]):1,text:R[3]}}if(L==="spot"){const R=/^(\d+):(\d+)(?::(\d+))?$/.exec(N);if(!R)throw x("write it spot:N:C, or spot:N:C:W for W characters");return{kind:L,n:Number(R[1]),column:Number(R[2]),width:R[3]?Number(R[3]):1}}throw x()},D=(_,L,N,x=!1)=>{const R=Array.isArray(L)?L:[L];if(R.length===0||x&&R.length>1)throw new Error(`codePanel.edit: ${_} takes ${x?"one":"at least one"} ${N} anchor`);return R.map(q=>{const U=j(q);if(U.kind!==N)throw new Error(`codePanel.edit: ${_} takes ${N} anchors (${N}:…), not "${q}"`);return U})},W=(_,L)=>{if(typeof L.text!="string")throw new Error(`codePanel.edit: ${_} needs \`text\` (the text to write)`);return L.text},B={kind:"code",about:ns,target:C,lines:n,box:I(t.x,t.y,c,h),line(_,L=1/0){return M(_),I(d,v(_)-T(_,L)*i,Math.max(1,n[_-1].length)*o,i)},token(_,L,N=1,x=1/0){M(_);const R=H(_,L,N);return I(d+R*o,v(_)-T(_,x)*i,L.length*o,i)},highlight(_,L){for(const N of P(_)){const x=E(`line.${N}.highlight`,0);A(N,"highlight",x,L.on===!1?0:1,L,200)}return B},strike(_,L){for(const N of P(_))A(N,"strike",E(`line.${N}.strike`,0),1,L);return B},remove(_,L){const N=P(_),x=L.style??"wipe";if(!ki.includes(x))throw new Error(`codePanel.remove: ${ot("style",x,ki)}`);const R=x==="wipe"?300:450,q=L.at+(L.duration??R),U=L.close??250;for(const Y of N)A(Y,"wipe",0,1,{...L,easing:L.easing??(x==="fly"?"ease-in":void 0)},R),S.set(Y,{style:x,from:L.from??"left"}),b.push({line:Y,closed:q+U});for(let Y=1;Y<=n.length;Y++){if(N.includes(Y))continue;const Z=N.filter(F=>F<Y).length;if(Z===0)continue;const nt=E(`line.${Y}.shift`,0);A(Y,"shift",nt,nt+Z,{at:q,duration:U,easing:"ease-in-out"})}return B},type(_,L){return A(_,"reveal",0,1,{duration:n[_-1].length*45,...L}),B},piece(_,L,N=1){if(typeof _=="string"){const Y=j(_);if(Y.kind!=="token")throw new Error(`codePanel.piece: a piece is a word, token:N:TEXT, not "${_}"`);return B.piece(Y.n,Y.text,Y.occurrence)}const x=_;if(L===void 0)throw new Error('codePanel.piece: which word? piece(n, text) or piece("token:N:TEXT")');M(x);const R=H(x,L,N),q=k.find(Y=>Y.line===x&&Y.column===R&&Y.text===L);if(q)return q;if(k.some(Y=>Y.line===x&&R<Y.column+Y.text.length&&Y.column<R+L.length))throw new Error(`codePanel: "${L}" on line ${x} overlaps another piece`);const U={id:k.length+1,line:x,column:R,text:L,home:B.token(x,L,N,0)};k.push(U);for(const Y of["x","y","rotate","write","away"])O[`piece.${U.id}.${Y}`]=0;return O[`piece.${U.id}.opacity`]=1,U},follow(_,L){return m.follow(_,L),B},fling(_,L){return m.fling(_,L),B},move(_,L){return m.move(_,L),B},write(_,L,N){return _.written=L,$(`piece.${_.id}.write`,0,1,{duration:Math.max(1,L.length)*70,...N}),B},spot(_,L,N=1,x=1/0){M(_);const R=y.filter(q=>q.line===_&&q.column<=L&&q.at<=x).reduce((q,U)=>q+U.chars,0);return I(d+(L+R)*o,v(_)-T(_,x)*i,N*o,i)},insert(_,L,N,x){M(_);const R={id:y.length+1,line:_,column:L,chars:N.length,text:N,at:x.at};y.push(R),O[`insert.${R.id}.open`]=0,O[`insert.${R.id}.type`]=0;const q=x.duration??N.length*70;return $(`insert.${R.id}.open`,0,1,{at:x.at,duration:q*.6,easing:"ease-out"}),$(`insert.${R.id}.type`,0,1,{at:x.at,duration:q}),B},drop(_,L,N,x){M(L);const R=x.duration??250,q=L===_.line,U=x.easing??(q?"linear":"ease-out"),Y=B.landing(_,L,N,x.at),Z={id:y.length+1,line:L,column:N,chars:_.text.length,at:x.at};return y.push(Z),O[`insert.${Z.id}.open`]=0,$(`insert.${Z.id}.open`,0,1,{at:x.at,duration:R,easing:q?U:"ease-out"}),$(`piece.${_.id}.away`,E(`piece.${_.id}.away`,0),1,{at:x.at,duration:R,easing:q?U:"ease-in-out"}),m.cutAfter(_,x.at),B.move(_,{at:x.at,duration:R,easing:U,to:{x:Y.x,y:Y.y}}),$(`piece.${_.id}.rotate`,p.valueAt(`piece.${_.id}.rotate`,x.at),0,{at:x.at,duration:R}),B},landing(_,L,N,x=1/0){const R=B.spot(L,N,_.text.length,x),q=L===_.line&&N>_.column?_.text.length*o:0;return I(R.left-q,R.top,R.width,R.height)},ride(_,L,N){const x=n.map((R,q)=>{const U=p.keys(`line.${q+1}.shift`)??[];return{top:v(q+1),offset:Y=>-bi(U,Y)*i,windows:wi(U)}});return Fr(_,L,{ground:N.ground,every:N.every??Ne,floors:x})},tracks:p.tracks,anchor(_,L=1/0){const N=j(_);return N.kind==="box"?B.box:N.kind==="line"?B.line(N.n,L):N.kind==="token"?B.token(N.n,N.text,N.occurrence,L):B.spot(N.n,N.column,N.width,L)},edit(_,L,N){const x=()=>D(_,L,"line").map(R=>R.n);if(_==="highlight")return B.highlight(x(),N);if(_==="strike")return B.strike(x(),N);if(_==="remove")return B.remove(x(),N);if(_==="type"){for(const R of x())B.type(R,N);return B}if(_==="insert"){const[R]=D(_,L,"spot",!0);return B.insert(R.n,R.column,W(_,N),N)}if(_==="write"||_==="drop"||_==="move"||_==="fling"){const[R]=D(_,L,"token",!0),q=B.piece(R.n,R.text,R.occurrence);if(_==="write")return B.write(q,W(_,N),N);if(_==="fling")return B.fling(q,N);if(_==="drop"){const Y=typeof N.into=="string"?j(N.into):void 0;if(Y?.kind!=="spot")throw new Error("codePanel.edit: drop needs `into`, a spot anchor (spot:N:C)");return B.drop(q,Y.n,Y.column,N)}const U=typeof N.to=="string"?B.anchor(N.to,N.at):N.to;if(!U||typeof U.x!="number"||typeof U.y!="number")throw new Error("codePanel.edit: move needs `to`, an anchor name or { x, y }");return B.move(q,{...N,to:U})}throw es("codePanel",_,ns)}};return B}function sb(t,e,n,s,i){if(e.style==="wipe"){t.beginPath(),e.from==="right"?t.rect(s.left,s.top,s.width*(1-n),s.height):t.rect(s.left+n*s.width,s.top,s.width*(1-n),s.height),t.clip();return}const o=eb*n;if(o>.2&&"filter"in t&&(t.filter=`blur(${o.toFixed(1)}px)`),t.globalAlpha*=1-n,e.style==="fly"){const r=e.from==="right"?-1:1;t.translate(r*n*tb*i,0),t.rotate(r*n*.08)}else{const r=1+.08*n,a=s.left+s.width/2,l=s.top+s.height/2;t.translate(a,l),t.scale(r,r),t.translate(-a,-l)}}const jr={highlight:"highlight(n | n[], { at, duration?, on? }): tint lines (on: false clears)",strike:"strike(n | n[], { at, duration? }): strike lines through, left to right",remove:"remove(n | n[], { at, duration?, style?: wipe | fly | blur, from?: left | right, close? }): take lines away; the lines below close the gap",type:"type(n, { at, duration? }): type in a line given in `hidden`",piece:"piece(n, text, occurrence?): make a word a piece that can come loose (returns it, with its home box)",follow:"follow(piece, path): carry a piece along timed points (handPath() gives a hand’s)",fling:"fling(piece, { at, velocity?, spin?, gravity?, duration? }): throw or kick a piece away on a spinning arc",move:"move(piece, { at, to: { x, y }, duration?, easing? }): move a piece’s centre to a point",write:"write(piece, text, { at, duration? }): type new text into a piece’s place",insert:"insert(n, column, text, { at, duration? }): type new text into a line; the line makes room",drop:"drop(piece, n, column, { at, duration? }): put a piece into a line (into its own line it slides, the text closing behind it)",ride:"ride(tracks, figureId, { ground }): a figure’s tracks with it carried by the line it stands on"};function ib(t){const e=[[/^line\.\d+\.highlight$/,{description:"How much the line is tinted",unit:"0..1",min:0,max:1}],[/^line\.\d+\.strike$/,{description:"How far the strike-through has drawn",unit:"0..1",min:0,max:1}],[/^line\.\d+\.wipe$/,{description:"How far the line has gone (wiped, flown off or blurred)",unit:"0..1",min:0,max:1}],[/^line\.\d+\.reveal$/,{description:"How much of the line is typed in",unit:"0..1",min:0,max:1}],[/^line\.\d+\.shift$/,{description:"How many rows the line has moved up",unit:"rows"}],[/^piece\.\d+\.(x|y)$/,{description:"The piece moved from its home",unit:"px"}],[/^piece\.\d+\.rotate$/,{description:"The piece turned",unit:"degrees"}],[/^piece\.\d+\.opacity$/,{description:"How opaque the piece is",unit:"0..1",min:0,max:1}],[/^piece\.\d+\.write$/,{description:"How much of the text written into its place is typed",unit:"0..1",min:0,max:1}],[/^piece\.\d+\.away$/,{description:"How far its old place has closed",unit:"0..1",min:0,max:1}],[/^insert\.\d+\.open$/,{description:"How much room the insert has opened",unit:"0..1",min:0,max:1}],[/^insert\.\d+\.type$/,{description:"How much of the inserted text is typed",unit:"0..1",min:0,max:1}]],n={};for(const s of t){const i=e.find(([o])=>o.test(s));i&&(n[s]=i[1])}return n}function Nd(t,e,n,s,i,o){t.beginPath(),t.moveTo(e+o,n),t.arcTo(e+s,n,e+s,n+i,o),t.arcTo(e+s,n+i,e,n+i,o),t.arcTo(e,n+i,e,n,o),t.arcTo(e,n,e+s,n,o),t.closePath()}const vi={go:["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","nil","true","false"],rust:["as","async","await","break","const","continue","crate","else","enum","extern","false","fn","for","if","impl","in","let","loop","match","mod","move","mut","pub","ref","return","self","Self","static","struct","super","trait","true","type","unsafe","use","where","while","Some","None","Ok","Err"],csharp:["abstract","async","await","base","bool","break","case","catch","class","const","continue","default","do","else","enum","false","finally","for","foreach","if","in","int","interface","internal","is","namespace","new","null","object","out","override","private","protected","public","readonly","ref","return","sealed","static","string","struct","switch","this","throw","true","try","using","var","virtual","void","while"],javascript:["async","await","break","case","catch","class","const","continue","default","delete","do","else","export","extends","false","finally","for","function","if","import","in","instanceof","let","new","null","of","return","static","super","switch","this","throw","true","try","typeof","undefined","var","void","while","yield"],typescript:[],python:["and","as","assert","async","await","break","class","continue","def","del","elif","else","except","False","finally","for","from","global","if","import","in","is","lambda","None","nonlocal","not","or","pass","raise","return","True","try","while","with","yield"],plain:[]};vi.typescript=[...vi.javascript,"enum","interface","type","implements","private","public","readonly","keyof","as","declare","namespace"];const Mi=Object.keys(vi),ob={go:"//",rust:"//",csharp:"//",javascript:"//",typescript:"//",python:"#",plain:null};function Dd(t,e){const n=new Set(vi[e]),s=ob[e],i=[],o=(a,l)=>{const c=i[i.length-1];c&&c.kind===l?c.text+=a:i.push({text:a,kind:l})};let r=0;for(;r<t.length;){const a=t[r];if(e!=="plain"&&s&&t.startsWith(s,r)){o(t.slice(r),"comment");break}if(e!=="plain"&&(a==='"'||a==="'"||a==="`")){let h=r+1;for(;h<t.length&&t[h]!==a;)h+=t[h]==="\\"?2:1;o(t.slice(r,h+1),"string"),r=h+1;continue}const l=/^[A-Za-z_][A-Za-z0-9_]*/.exec(t.slice(r));if(l){o(l[0],n.has(l[0])?"keyword":"text"),r+=l[0].length;continue}const c=/^\d[\d_.]*/.exec(t.slice(r));if(c&&e!=="plain"){o(c[0],"number"),r+=c[0].length;continue}o(a,"text"),r++}return i}const Fd='"Segoe Print", "Bradley Hand", "Comic Sans MS", "Chalkboard SE", cursive',ss={whiteboard:{background:"#f7f7f2",frame:"#b8bcc4",ink:"#1f2a44",colors:{ink:"#1f2a44",red:"#d03b3b",blue:"#2f6fd0",green:"#2e9a52",orange:"#e07b1a"},font:Fd,stroke:.09,opacity:1},chalkboard:{background:"#2f4a3a",frame:"#7a5a3a",ink:"#f1f1e8",colors:{ink:"#f1f1e8",red:"#f2a3a3",blue:"#a8c8f0",green:"#b7e4a8",orange:"#f5c98a",yellow:"#f6ef9a"},font:Fd,stroke:.1,opacity:.9}},Br=["circle","box","underline","arrow"],ne={kind:"board",create:"whiteboard({ x, y, width, height, theme?: whiteboard | chalkboard, fontSize?, items: [{ id, text, at: [x, y], size?, color?, hidden? } | { id, mark: circle | box | underline | arrow, around? | from?, to?, color?, hidden? }] })",anchors:{box:"the whole board","text:ID":"a text item: write along it from left to right, point at it","term:ID:TEXT":"the first TEXT in text ID (term:ID#K:TEXT for the Kth): a term, which can come loose as a piece","mark:ID":"a mark (circle, box, underline or arrow)"},edits:{write:"text anchors given `hidden`; { at, duration? }: write them in by hand. Or a term; { at, text, duration? }: write new text in its place (move or erase the term first)",draw:"mark anchors given `hidden`; { at, duration? }: draw them in",erase:"text, term or mark anchors; { at, duration? }: wipe them off",strike:"text or term anchors; { at, duration? }: cross them out",move:"a term; { at, to: an anchor name or { x, y }, duration? }: move the term there",fling:"a term; { at, velocity?, spin?, gravity?, duration? }: throw or knock the term off on a spinning arc"}},jd=90,Bd=300,rb=.3;function ab(t){const e=typeof t.theme=="string"?t.theme:"whiteboard";if(!(e in ss))throw new Error(`whiteboard: ${ot("theme",e,Object.keys(ss))}`);const n=typeof t.theme=="object"?{...ss.whiteboard,...t.theme}:ss[e],s=t.fontSize??28,i=t.charWidth??.55,o=y=>y===void 0?n.ink:n.colors[y]??y,r=y=>bt(t.x+y.left,t.y+y.top,y.width,y.height),a=Qn(),l=ts(a),c={},h=new Map,d=[],u=[],f=(y,M,$,E)=>{const A=h.get(y);if(!A||A.kind!=="text")throw ve("whiteboard",E,ne,`there is no text "${y}" (texts: ${g().join(", ")||"none"})`);let T=-1;for(let v=0;v<$;v++)if(T=A.item.text.indexOf(M,T+1),T<0)throw ve("whiteboard",E,ne,`text "${y}" has no ${$>1?`${$}th `:""}"${M}"`);const I=A.size*i;return{column:T,box:bt(A.box.left+T*I,A.box.top,M.length*I,A.box.height)}},g=()=>[...h.values()].filter(y=>y.kind==="text").map(y=>y.item.id),p=y=>{const{kind:M,rest:$}=De(y),E=A=>ve("whiteboard",y,ne,A);if(M==="box"){if($)throw E("box takes no arguments");return{kind:M}}if(M==="text"||M==="mark"){if(!$)throw E(`write it ${M}:ID`);return{kind:M,id:$}}if(M==="term"){const A=/^([^:#]+)(?:#(\d+))?:(.+)$/.exec($);if(!A)throw E("write it term:ID:TEXT, or term:ID#K:TEXT for the Kth");return{kind:M,id:A[1],occurrence:A[2]?Number(A[2]):1,text:A[3]}}throw E()},m=y=>{const M=p(y);if(M.kind==="box")return bt(0,0,t.width,t.height);if(M.kind==="term")return f(M.id,M.text,M.occurrence,y).box;const $=h.get(M.id);if(!$||$.kind!==M.kind){const E=[...h.values()].filter(A=>A.kind===M.kind).map(A=>A.item.id);throw ve("whiteboard",y,ne,`there is no ${M.kind} "${M.id}" (${M.kind}s: ${E.join(", ")||"none"})`)}return $.box};for(const y of t.items??[]){if(!y||typeof y.id!="string"||!y.id||/[:#]/.test(y.id))throw new Error(`whiteboard: every item needs an \`id\` without ":" or "#" (got ${JSON.stringify(y?.id)})`);if(h.has(y.id))throw new Error(`whiteboard: two items are called "${y.id}"`);if("text"in y){if(!Array.isArray(y.at)||y.at.length!==2||!y.at.every(T=>typeof T=="number"))throw new Error(`whiteboard: text "${y.id}" needs \`at\`, [x, y] from the board's top-left`);const E=y.size??s,A=bt(y.at[0],y.at[1],Math.max(1,y.text.length)*E*i,E*1.3);h.set(y.id,{kind:"text",item:y,size:E,color:o(y.color),box:A}),c[`text.${y.id}.write`]=y.hidden?0:1,c[`text.${y.id}.erase`]=0;continue}if(!Br.includes(y.mark))throw new Error(`whiteboard: mark "${y.id}": ${ot("mark",y.mark,Br)}`);const M=y.mark==="arrow"?["from","to"]:["around"];for(const E of M)if(typeof y[E]!="string")throw new Error(`whiteboard: ${y.mark} "${y.id}" needs \`${E}\`, a place on the board (an item before it)`);const $=lb(y,m,s);h.set(y.id,{kind:"mark",item:y,color:o(y.color),points:$,box:hb($)}),c[`mark.${y.id}.draw`]=y.hidden?0:1,c[`mark.${y.id}.erase`]=0}const b=y=>d.filter(M=>M.item===y),S={type:"custom",x:t.x,y:t.y,width:t.width,height:t.height,props:c,about:{kind:"whiteboard",summary:`A board with ${h.size} items. Its texts, terms and marks are places in the scene (anchor()); its edits record tracks (edit(), tracks()).`,get props(){return ub(Object.keys(c))},actions:ne.edits},draw(y,M){const $=M.props??{},E=A=>Number($[A]??c[A]??0);y.save(),y.fillStyle=n.background,db(y,0,0,t.width,t.height,10),y.fill(),y.lineWidth=Math.max(4,t.width*.012),y.strokeStyle=n.frame,y.stroke(),y.textAlign="center",y.textBaseline="middle",y.lineCap="round",y.lineJoin="round",y.globalAlpha=n.opacity;for(const A of h.values()){if(y.save(),Wr(y,A.box,E(`${A.kind}.${A.item.id}.erase`)),A.kind==="text"){const T=b(A.item.id),I=E(`text.${A.item.id}.write`)*A.item.text.length;y.font=`${A.size}px ${n.font}`,y.fillStyle=A.color;for(let v=0;v<Math.ceil(I);v++)A.item.text[v]===" "||T.some(P=>v>=P.column&&v<P.column+P.text.length)||(y.globalAlpha=n.opacity*Math.min(1,I-v),y.fillText(A.item.text[v],A.box.left+(v+.5)*A.size*i,A.box.y))}else qd(y,A.points,E(`mark.${A.item.id}.draw`),A.color,s*n.stroke,A.item.mark==="arrow");y.restore()}for(const A of u){const T=E(`strike.${A.id}.draw`);if(T<=0)continue;const{box:I}=A,v=I.height*.15;qd(y,[{x:I.left-3,y:I.y+v},{x:I.right+3,y:I.y-v}],T,n.colors.red??n.ink,s*n.stroke*.8,!1)}for(const A of d){const T=h.get(A.item),I=T.size*i;y.font=`${T.size}px ${n.font}`,y.fillStyle=T.color;const v=A.written;if(v){const C=E(`piece.${A.id}.write`)*v.length,j=A.home.x-t.x-v.length*I/2;for(let D=0;D<Math.ceil(C);D++)v[D]!==" "&&(y.globalAlpha=n.opacity*Math.min(1,C-D),y.fillText(v[D],j+(D+.5)*I,A.home.y-t.y))}const P=E(`piece.${A.id}.opacity`)*Math.min(1,E(`text.${A.item}.write`)*T.item.text.length-A.column);if(P<=0)continue;y.save();const H={x:A.home.x-t.x,y:A.home.y-t.y},O={x:E(`piece.${A.id}.x`),y:E(`piece.${A.id}.y`)};Wr(y,bt(H.x+O.x-A.home.width/2,H.y+O.y-A.home.height/2,A.home.width,A.home.height),E(`piece.${A.id}.erase`)),Math.hypot(O.x,O.y)<1&&Wr(y,T.box,E(`text.${A.item}.erase`)),y.globalAlpha=n.opacity*Math.min(1,P),y.translate(H.x+O.x,H.y+O.y),y.rotate(E(`piece.${A.id}.rotate`)*Math.PI/180);for(let C=0;C<A.text.length;C++)A.text[C]!==" "&&y.fillText(A.text[C],(C+.5-A.text.length/2)*I,0);y.restore()}y.restore()}},k={kind:"board",about:ne,target:S,box:bt(t.x,t.y,t.width,t.height),anchor(y){return r(m(y))},piece(y){const M=p(y);if(M.kind!=="term")throw new Error(`whiteboard.piece: a piece is a term, term:ID:TEXT, not "${y}"`);const{column:$,box:E}=f(M.id,M.text,M.occurrence,y),A=d.find(I=>I.item===M.id&&I.column===$&&I.text===M.text);if(A)return A;if(d.some(I=>I.item===M.id&&$<I.column+I.text.length&&I.column<$+M.text.length))throw new Error(`whiteboard: "${M.text}" in "${M.id}" overlaps another piece`);const T={id:d.length+1,item:M.id,column:$,text:M.text,home:r(E)};d.push(T);for(const I of["x","y","rotate","erase","write"])c[`piece.${T.id}.${I}`]=0;return c[`piece.${T.id}.opacity`]=1,T},edit(y,M,$){const E=Array.isArray(M)?M:[M];if(E.length===0)throw new Error(`whiteboard.edit: ${y} takes at least one anchor`);const A=E.map(v=>({name:v,anchor:p(v)}));for(const{name:v}of A)m(v);const T=(v,P=!1)=>{const H=A.find(O=>!v.includes(O.anchor.kind));if(H)throw new Error(`whiteboard.edit: ${y} takes ${v.join(" or ")} anchors, not "${H.name}"`);if(P&&A.length>1)throw new Error(`whiteboard.edit: ${y} takes one ${v.join(" or ")} anchor`)},I=()=>k.piece(A[0].name);if(y==="write"){if(A.some(v=>v.anchor.kind==="term")){if(T(["term"],!0),typeof $.text!="string")throw new Error("whiteboard.edit: write into a term needs `text` (the new text)");const v=I();return v.written=$.text,a.tween(`piece.${v.id}.write`,0,1,{duration:Math.max(Bd,$.text.length*jd),...$}),k}T(["text"]);for(const{anchor:v}of A){const P=v.id,H=h.get(P).item.text;a.tween(`text.${P}.write`,0,1,{duration:Math.max(Bd,H.length*jd),...$})}return k}if(y==="draw"){T(["mark"]);for(const{anchor:v}of A)a.tween(`mark.${v.id}.draw`,0,1,{duration:500,...$});return k}if(y==="erase"){T(["text","term","mark"]);for(const v of A){const P=v.anchor.kind==="term"?`piece.${k.piece(v.name).id}.erase`:`${v.anchor.kind}.${v.anchor.id}.erase`;a.tween(P,0,1,{duration:400,...$})}return k}if(y==="strike"){T(["text","term"]);for(const v of A){const P={id:u.length+1,box:m(v.name)};u.push(P),c[`strike.${P.id}.draw`]=0,a.tween(`strike.${P.id}.draw`,0,1,{duration:250,...$})}return k}if(y==="move"){T(["term"],!0);const v=typeof $.to=="string"?k.anchor($.to):$.to;if(!v||typeof v.x!="number"||typeof v.y!="number")throw new Error("whiteboard.edit: move needs `to`, an anchor name or { x, y }");return k.move(I(),{...$,to:v})}if(y==="fling")return T(["term"],!0),k.fling(I(),$);throw es("whiteboard",y,ne)},follow(y,M){return l.follow(y,M),k},fling(y,M){return l.fling(y,M),k},move(y,M){return l.move(y,M),k},ride(y){return y},tracks:a.tracks};return k}function lb(t,e,n){const s=$e(qt(t.id)),i=g=>(s.next()*2-1)*g,o=n*rb;if(t.mark==="arrow"){const g=e(t.from),p=e(t.to),m=Wd(g,p,o*.6),b=Wd(p,g,o*.6),S=Math.hypot(b.x-m.x,b.y-m.y)*(.06+i(.04)),k=cb(m,b),y={x:(m.x+b.x)/2+k.x*S,y:(m.y+b.y)/2+k.y*S},M=[];for(let $=0;$<=24;$++){const E=$/24;M.push({x:(1-E)**2*m.x+2*(1-E)*E*y.x+E*E*b.x,y:(1-E)**2*m.y+2*(1-E)*E*y.y+E*E*b.y})}return M}const r=e(t.around);if(t.mark==="underline"){const g=r.bottom+o*.4;return[{x:r.left-o*.3,y:g+i(2)},{x:r.x,y:g+2+i(2)},{x:r.right+o*.5,y:g-1+i(3)}]}if(t.mark==="box"){const g=r.left-o,p=r.right+o,m=r.top-o*.6,b=r.bottom+o*.6,S=(y,M)=>({x:y+i(o*.2),y:M+i(o*.2)}),k=S(g,m);return[k,S(p,m),S(p,b),S(g,b),k,{x:k.x+o*.8,y:k.y+i(2)}]}const a=r.width/2+o,l=r.height/2+o*.6,c=-2.2+i(.3),h=s.next()*Math.PI*2,d=1.12,u=64,f=[];for(let g=0;g<=u*d;g++){const p=g/u,m=c+p*Math.PI*2,b=1+.035*Math.sin(p*Math.PI*4+h)+.06*p;f.push({x:r.x+Math.cos(m)*a*b,y:r.y+Math.sin(m)*l*b})}return f}function Wd(t,e,n){const s=e.x-t.x,i=e.y-t.y;if(s===0&&i===0)return{x:t.x,y:t.y};const o=Math.min(s===0?1/0:(t.width/2+n)/Math.abs(s),i===0?1/0:(t.height/2+n)/Math.abs(i));return{x:t.x+s*o,y:t.y+i*o}}function cb(t,e){const n=Math.hypot(e.x-t.x,e.y-t.y)||1;return{x:-(e.y-t.y)/n,y:(e.x-t.x)/n}}function hb(t){const e=t.map(o=>o.x),n=t.map(o=>o.y),s=Math.min(...e),i=Math.min(...n);return bt(s,i,Math.max(...e)-s,Math.max(...n)-i)}function qd(t,e,n,s,i,o){if(n<=0||e.length<2)return;const r=[0];for(let g=1;g<e.length;g++)r.push(r[g-1]+Math.hypot(e[g].x-e[g-1].x,e[g].y-e[g-1].y));const l=r[r.length-1]*Math.min(1,n/(o?.85:1));t.strokeStyle=s,t.lineWidth=i,t.beginPath(),t.moveTo(e[0].x,e[0].y);for(let g=1;g<e.length;g++){if(r[g]<=l){t.lineTo(e[g].x,e[g].y);continue}const p=(l-r[g-1])/(r[g]-r[g-1]||1);t.lineTo(e[g-1].x+(e[g].x-e[g-1].x)*p,e[g-1].y+(e[g].y-e[g-1].y)*p);break}if(t.stroke(),!o||n<=.85)return;const c=(n-.85)/.15,h=e[e.length-1],d=e[e.length-3]??e[0],u=Math.atan2(h.y-d.y,h.x-d.x),f=i*4.5*c;t.beginPath();for(const g of[-1,1])t.moveTo(h.x,h.y),t.lineTo(h.x-Math.cos(u+g*.45)*f,h.y-Math.sin(u+g*.45)*f);t.stroke()}function Wr(t,e,n){if(n<=0)return;const s=8;t.beginPath(),t.rect(e.left-s+n*(e.width+s*2),e.top-s*4,(1-n)*(e.width+s*2),e.height+s*8),t.clip()}function db(t,e,n,s,i,o){t.beginPath(),t.moveTo(e+o,n),t.arcTo(e+s,n,e+s,n+i,o),t.arcTo(e+s,n+i,e,n+i,o),t.arcTo(e,n+i,e,n,o),t.arcTo(e,n,e+s,n,o),t.closePath()}function ub(t){const e=[[/^text\..+\.write$/,{description:"How much of the text is written",unit:"0..1",min:0,max:1}],[/^(text|mark)\..+\.erase$/,{description:"How far it has been wiped off, left to right",unit:"0..1",min:0,max:1}],[/^mark\..+\.draw$/,{description:"How much of the mark is drawn",unit:"0..1",min:0,max:1}],[/^strike\.\d+\.draw$/,{description:"How far the strike-through has drawn",unit:"0..1",min:0,max:1}],[/^piece\.\d+\.(x|y)$/,{description:"The term moved from its home",unit:"px"}],[/^piece\.\d+\.rotate$/,{description:"The term turned",unit:"degrees"}],[/^piece\.\d+\.opacity$/,{description:"How opaque the term is",unit:"0..1",min:0,max:1}],[/^piece\.\d+\.erase$/,{description:"How far the term has been wiped off",unit:"0..1",min:0,max:1}],[/^piece\.\d+\.write$/,{description:"How much of the text written into its place is written",unit:"0..1",min:0,max:1}]],n={};for(const s of t){const i=e.find(([o])=>o.test(s));i&&(n[s]=i[1])}return n}const qr=["bar","line"],is={light:{background:"#ffffff",text:"#3b4252",grid:"#d8dee9",color:"#4c7bd9",highlight:"#e8833a",font:'system-ui, -apple-system, "Segoe UI", sans-serif'},dark:{background:"#1e2230",text:"#cdd6f4",grid:"#3a4055",color:"#89b4fa",highlight:"#fab387",font:'system-ui, -apple-system, "Segoe UI", sans-serif'}},Fe={kind:"chart",create:"chart({ x, y, width, height, kind: bar | line, data: [{ id, label?, value, hidden? }], max?, title?, theme?: light | dark, decimals?, prefix?, suffix?, values? })",anchors:{box:"the whole chart","bar:ID":"a bar (bar charts), as it stands at the time: stand on its top (it carries a figure as it grows), point at it","point:ID":"a point on the line (line charts), as it stands at the time","label:ID":"its label under the axis","value:ID":"its value label, above it"},edits:{set:"bar or point anchors; { at, value, duration? }: animate to a new value; its value label counts along",show:"bar or point anchors given `hidden`; { at, duration?, on? }: grow a bar in from the axis, or draw the line out to a point (on: false takes it back)",highlight:"bar or point anchors; { at, duration?, on? }: colour it out (on: false clears)"}},fb=600,pb=500,gb=200;function mb(t){if(!qr.includes(t.kind))throw new Error(`chart: ${ot("kind",t.kind,qr)}`);const e=typeof t.theme=="string"?t.theme:"light";if(!(e in is))throw new Error(`chart: ${ot("theme",e,Object.keys(is))}`);const n=typeof t.theme=="object"?{...is.light,...t.theme}:is[e];if(!Array.isArray(t.data)||t.data.length===0)throw new Error("chart: `data` needs at least one { id, value }");const s=new Set;for(const v of t.data){if(typeof v?.id!="string"||!v.id||v.id.includes(":"))throw new Error(`chart: every datum needs an \`id\` without ":" (got ${JSON.stringify(v?.id)})`);if(s.has(v.id))throw new Error(`chart: two data are called "${v.id}"`);if(typeof v.value!="number"||!Number.isFinite(v.value))throw new Error(`chart: "${v.id}" needs a \`value\`, a number`);s.add(v.id)}const i=t.kind,o=i==="bar"?"bar":"point",r=t.max??Kd(Math.max(...t.data.map(v=>v.value))*1.1);if(!(r>0))throw new Error(`chart: \`max\` must be above 0 (got ${r})`);const a=Math.max(10,Math.min(16,t.height/20)),l={left:a*3.6,right:t.width-a,top:t.title?a*3:a*1.6,bottom:t.height-a*2.4},c=l.bottom-l.top,h=(l.right-l.left)/t.data.length,d=h*.6,u=Math.max(4,a*.35),f=c/r,g=new Map(t.data.map((v,P)=>[v.id,P])),p=v=>l.left+h*(g.get(v)+.5),m=Qn(),b=ts(m),S={};for(const v of t.data)S[`${o}.${v.id}.value`]=v.value,S[`${o}.${v.id}.show`]=v.hidden?0:1,S[`${o}.${v.id}.highlight`]=0;const k=(v,P)=>m.keys(v)?.length?bi(m.keys(v),P):S[v],y=(v,P)=>k(`${o}.${v}.value`,P)*(i==="bar"?k(`${o}.${v}.show`,P):1)*f,M=v=>{const{kind:P,rest:H}=De(v),O=C=>ve("chart",v,Fe,C);if(P==="box"){if(H)throw O("box takes no arguments");return{kind:"box"}}if(P==="bar"||P==="point"||P==="label"||P==="value"){if(!H)throw O(`write it ${P}:ID`);if(!g.has(H))throw O(`there is no "${H}" (data: ${[...g.keys()].join(", ")})`);if((P==="bar"||P==="point")&&P!==o)throw O(`a ${i} chart has ${o}s, not ${P}s: ${o}:${H}`);return{kind:P,id:H}}throw O()},$=(v,P)=>{if(v.kind==="box")return bt(0,0,t.width,t.height);const H=p(v.id),O=l.bottom-y(v.id,P);if(v.kind==="bar")return bt(H-d/2,O,d,l.bottom-O);if(v.kind==="point")return bt(H-u,O-u,u*2,u*2);if(v.kind==="label")return bt(H-h/2,l.bottom+a*.4,h,a*1.4);const C=O-(i==="line"?u:0)-a*.3;return bt(H-h/2,C-a*1.3,h,a*1.3)},E=v=>bt(t.x+v.left,t.y+v.top,v.width,v.height),A=v=>`${t.prefix??""}${v.toFixed(t.decimals??0)}${t.suffix??""}`,T={type:"custom",x:t.x,y:t.y,width:t.width,height:t.height,props:S,about:{kind:`${i} chart`,summary:`A ${i} chart of ${t.data.length} values (${t.data.map(v=>v.id).join(", ")}), scaled to ${r}. Its ${o}s and labels are places in the scene (anchor()); its edits record tracks (edit(), tracks()).`,props:Object.fromEntries(Object.keys(S).map(v=>[v,kb(v)])),actions:Fe.edits},draw(v,P){const H=P.props??{},O=D=>Number(H[D]??S[D]??0);v.save(),v.fillStyle=n.background,bb(v,0,0,t.width,t.height,8),v.fill(),v.font=`${a}px ${n.font}`,v.textBaseline="middle",t.title&&(v.fillStyle=n.text,v.textAlign="left",v.font=`600 ${a*1.2}px ${n.font}`,v.fillText(t.title,l.left,a*1.5),v.font=`${a}px ${n.font}`),v.lineWidth=1,v.textAlign="right";for(let D=0;D<=4;D++){const W=l.bottom-c*D/4;v.strokeStyle=n.grid,v.beginPath(),v.moveTo(l.left,W),v.lineTo(l.right,W),v.stroke(),v.fillStyle=n.text,v.globalAlpha=.7,v.fillText(yb(r*D/4),l.left-a*.5,W),v.globalAlpha=1}const C=D=>O(`${o}.${D}.value`)*(i==="bar"?O(`${o}.${D}.show`):1)*f,j=D=>Yd(n.color,n.highlight,O(`${o}.${D}.highlight`));i==="line"&&(v.lineWidth=Math.max(2,a*.2),v.lineJoin="round",v.lineCap="round",v.strokeStyle=n.color,v.beginPath(),t.data.forEach((D,W)=>{const B={x:p(D.id),y:l.bottom-C(D.id)},_=O(`point.${D.id}.show`);if(W===0){_>0&&v.moveTo(B.x,B.y);return}const L=t.data[W-1];if(O(`point.${L.id}.show`)<1||_<=0)return;const N={x:p(L.id),y:l.bottom-C(L.id)};v.lineTo(N.x+(B.x-N.x)*_,N.y+(B.y-N.y)*_)}),v.stroke()),v.textAlign="center";for(const D of t.data){const W=p(D.id),B=C(D.id),_=O(`${o}.${D.id}.show`);if(v.fillStyle=j(D.id),i==="bar"?B>.5&&(wb(v,W-d/2,l.bottom-B,d,B,Math.min(6,d/4)),v.fill()):_>0&&(v.beginPath(),v.arc(W,l.bottom-B,u*Math.min(1,_*1.5)*(1+.3*O(`point.${D.id}.highlight`)),0,Math.PI*2),v.fill()),v.fillStyle=n.text,v.fillText(D.label??D.id,W,l.bottom+a*1.1),t.values!==!1&&_>0){v.globalAlpha=Math.min(1,_*2),v.font=`600 ${a}px ${n.font}`,v.fillStyle=Yd(n.text,n.highlight,O(`${o}.${D.id}.highlight`));const L=l.bottom-B-(i==="line"?u:0)-a*.95;v.fillText(A(O(`${o}.${D.id}.value`)),W,L),v.font=`${a}px ${n.font}`,v.globalAlpha=1}}v.strokeStyle=n.text,v.lineWidth=1.5,v.beginPath(),v.moveTo(l.left,l.bottom),v.lineTo(l.right,l.bottom),v.stroke(),v.restore()}},I={kind:"chart",chartKind:i,about:Fe,target:T,max:r,box:bt(t.x,t.y,t.width,t.height),anchor(v,P=1/0){return E($(M(v),P))},piece(v){throw new Error(`chart: a chart has no pieces to come loose ("${v}"); change it with edit('set' | 'show' | 'highlight', …)`)},edit(v,P,H){const O=Array.isArray(P)?P:[P];if(O.length===0)throw new Error(`chart.edit: ${v} takes at least one anchor`);if(!(v in Fe.edits))throw es("chart",v,Fe);const C=O.map(j=>{const D=M(j);if(D.kind!==o)throw new Error(`chart.edit: ${v} takes ${o} anchors (${o}:ID), not "${j}"`);return D.id});for(const j of C){const D=W=>`${o}.${j}.${W}`;if(v==="set"){if(typeof H.value!="number"||!Number.isFinite(H.value))throw new Error("chart.edit: set needs `value`, a number");m.tween(D("value"),k(D("value"),H.at),H.value,H,fb)}else v==="show"?m.tween(D("show"),k(D("show"),H.at),H.on===!1?0:1,H,pb):m.tween(D("highlight"),k(D("highlight"),H.at),H.on===!1?0:1,H,gb)}return I},follow(v,P){return b.follow(v,P),I},fling(v,P){return b.fling(v,P),I},move(v,P){return b.move(v,P),I},ride(v,P,H){if(i!=="bar")return v;const O=t.data.map(C=>{const j=y(C.id,0),D=[...wi(m.keys(`bar.${C.id}.value`)),...wi(m.keys(`bar.${C.id}.show`))];return{top:t.y+l.bottom-j,offset:W=>j-y(C.id,W),windows:D}});return Fr(v,P,{ground:H.ground,every:H.every??Ne,floors:O})},tracks:m.tracks};return I}function Kd(t){if(!(t>0))return 1;const e=10**Math.floor(Math.log10(t));for(const n of[1,2,2.5,5,10])if(n*e>=t-1e-9)return n*e;return 10*e}function yb(t){return Number.isInteger(t)?String(t):String(Number(t.toFixed(2)))}function Yd(t,e,n){if(n<=0)return t;if(n>=1)return e;const s=r=>[1,3,5].map(a=>parseInt(r.slice(a,a+2),16));if(!/^#[0-9a-f]{6}$/i.test(t)||!/^#[0-9a-f]{6}$/i.test(e))return n<.5?t:e;const[i,o]=[s(t),s(e)];return`#${i.map((r,a)=>Math.round(r+(o[a]-r)*n).toString(16).padStart(2,"0")).join("")}`}function bb(t,e,n,s,i,o){t.beginPath(),t.moveTo(e+o,n),t.arcTo(e+s,n,e+s,n+i,o),t.arcTo(e+s,n+i,e,n+i,o),t.arcTo(e,n+i,e,n,o),t.arcTo(e,n,e+s,n,o),t.closePath()}function wb(t,e,n,s,i,o){const r=Math.min(o,i);t.beginPath(),t.moveTo(e,n+i),t.lineTo(e,n+r),t.arcTo(e,n,e+r,n,r),t.lineTo(e+s-r,n),t.arcTo(e+s,n,e+s,n+r,r),t.lineTo(e+s,n+i),t.closePath()}function kb(t){return t.endsWith(".value")?{description:"Its value (the bar’s height or the point’s, and its value label)",unit:"value"}:t.endsWith(".show")?{description:"How much of it is shown: a bar grown in from the axis, the line drawn out to the point",unit:"0..1",min:0,max:1}:{description:"How much it is coloured out",unit:"0..1",min:0,max:1}}const vb=(t,e,n)=>t.slice(Math.floor((t.length-1)*e),Math.ceil((t.length-1)*n)+1);function Mb(t={}){const e=t.shirt??"#e2493b",n=t.trousers??"#24476b",s=a=>a.lineWidth*.45,i=(a,l,c)=>{const h=a.parts[`leg.${c}`].points;l.shape(Bn(h,a.height*.08,a.height*.05),n,s(a))},o=(a,l)=>{const c=a.chains.spine,h=c[0],d=c[c.length-1],u={x:h.x-(d.x-h.x)*.25,y:h.y-(d.y-h.y)*.25};l.shape(Bn([u,...a.parts.spine.points],a.height*.15,a.height*.14),e,s(a))},r=(a,l,c)=>{const h=a.parts[`arm.${c}`].points,d=h[0],u=a.chains.spine[a.chains.spine.length-1],g=[{x:d.x+(u.x-d.x)*.45,y:d.y+(u.y-d.y)*.45},...vb(h,0,.45)],p=Bn(g,a.height*.085,a.height*.06),m=g.length,b=p.slice(0,m),S=p.slice(m).reverse();l.shape(p,e,0);const k=$=>Math.hypot($[1].x-u.x,$[1].y-u.y),[y,M]=k(b)>k(S)?[b,S]:[S,b];l.line(y.slice(1),s(a)),l.line(M.slice(Math.ceil(m*.45)),s(a)),l.line([b[m-1],S[m-1]],s(a))};return{parts:{"leg.left":{over:(a,l,c)=>i(l,c,"left")},"leg.right":{over:(a,l,c)=>i(l,c,"right")},spine:{over:(a,l,c)=>o(l,c)},"arm.left":{over:(a,l,c)=>r(l,c,"left")},"arm.right":{over:(a,l,c)=>r(l,c,"right")}}}}const je={full:{anticipation:.12,anticipationTime:.3,hold:0,overshoot:.08,settle:220,settleEase:"ease-in-out",actionEase:"ease-in-out-cubic",overlap:45,eyeLead:120,eyeDart:160,drift:.12,blinks:!0,jumpSquash:1},snappy:{anticipation:.2,anticipationTime:.35,hold:.12,overshoot:.12,settle:320,settleEase:{type:"elastic",mode:"out",amplitude:1,period:.35},actionEase:"ease-out-cubic",overlap:35,eyeLead:100,eyeDart:100,drift:.1,blinks:!0,jumpSquash:1.3},limited:{anticipation:.06,anticipationTime:.25,hold:0,overshoot:0,settle:0,settleEase:"ease-out",actionEase:"ease-in-out",overlap:30,eyeLead:80,eyeDart:120,drift:0,blinks:!0,jumpSquash:.6},none:{anticipation:0,anticipationTime:0,hold:0,overshoot:0,settle:0,settleEase:"linear",actionEase:"linear",overlap:0,eyeLead:0,eyeDart:0,drift:0,blinks:!1,jumpSquash:0}};function Kr(t){if(t===void 0)return je.full;if(typeof t=="string")return je[t];const{base:e,...n}=t;return{...je[e??"full"],...n}}const Yr=160,Sb=120,Tb=700,zr=60,Eb=90,Si=3200,mn=1,Be=1e-6;function Ti(t,e,n={}){const s=Kr(n.style),i=n.seed??1,o={};if(t.length===0)return o;const r=Object.keys(t[0].pose).filter(d=>t.some(u=>Math.abs(u.pose[d]-t[0].pose[d])>Be));for(const d of r)o[d]=Ab(d,t,e,s,i);const a=e.blink,l=a!==void 0&&r.includes(a);if(s.blinks&&a!==void 0&&!l&&a in t[0].pose){const d=$b(t,e,s,i,t[0].pose[a]);d.length>0&&(o[a]=d)}const{lift:c,stretch:h}=e;if(s.jumpSquash>0&&c&&h&&r.includes(c)&&!r.includes(h)&&h in t[0].pose){const d=Pb(t,c,t[0].pose[h],s.jumpSquash);d.length>0&&(o[h]=d)}return o}function Ab(t,e,n,s,i){const o=n.eyes.includes(t),r=n.limits[t],a=r!==void 0,l=o?-s.eyeLead:(n.depth[t]??1)*s.overlap,c=f=>{const g=(e[f].time-e[f-1].time)/2;return Math.max(-g,Math.min(g,l))},h=[{time:e[0].time,value:e[0].pose[t]}],d=(f,g,p)=>{const m=h[h.length-1];if(f<=m.time+mn){h[h.length-1]={...m,value:g,...p?{easing:p}:{}};return}h.push({time:f,value:g,...p?{easing:p}:{}})};let u=e[0].pose[t];for(let f=1;f<e.length;f++){const g=e[f],p=e[f-1].pose[t],m=g.pose[t],b=m-p,S=h[h.length-1].time,k=g.act!==!1;if(Math.abs(b)<=Be){const v=g.time+(k?c(f):0);if(f===e.length-1)Math.abs(u-m)>Be&&d(Math.max(v,S+Yr),m,"ease-in-out"),u=m;else if(k&&a&&s.drift>0&&n.drift.includes(t)&&v-S>=Tb){const P=qt(`${i}:${t}:${f}`)%2===0?1:-1;u=m+P*s.drift*r,d(v,u,"ease-in-out")}continue}if(!k){d(e[f-1].time,u),d(g.time,m,g.easing),u=m;continue}const y=c(f),M=Math.max(e[f-1].time+y,S);let $=g.time+y;o&&s.eyeDart>0&&($=Math.min($,M+s.eyeDart));const E=$-M;if(E<=mn){d(g.time,m,g.easing),u=m;continue}d(M,u);const A=Math.sign(b);if(a&&s.anticipation>0&&r>0&&E>=Yr){const v=u-A*Math.min(Math.abs(b)*s.anticipation,r),P=M+E*s.anticipationTime;d(P,v,"ease-in-out"),s.hold>0&&d(P+E*s.hold,v)}const T=f+1<e.length?e[f+1].time-g.time:1/0,I=Math.min(s.settle,T/2);if(a&&s.overshoot>0&&r>0&&E>=Sb&&I>mn){const v=Math.min(Math.abs(b)*s.overshoot,r);d($,m+A*v,g.easing??s.actionEase),d($+I,m,s.settleEase)}else d($,m,g.easing??s.actionEase);u=m}return h}function $b(t,e,n,s,i){const o=[],r=zr+Eb;for(let f=1;f<t.length;f++){const g=t[f-1].pose,p=t[f].pose;Object.entries(e.headTurns).some(([b,S])=>Math.abs((p[b]??0)-(g[b]??0))>S)&&t[f].act!==!1&&o.push(Math.max(t[0].time,t[f-1].time-n.eyeLead))}const a=t[0].time,l=t[t.length-1].time,c=[...o];let h=a+Si*.6,d=0;for(;h<l;){c.some(p=>Math.abs(p-h)<Si/2)||o.push(h);const g=(qt(`${s}:blink:${d++}`)%1e3/1e3-.5)*(Si*.66);h+=Si+g}o.sort((f,g)=>f-g);const u=[{time:a,value:i}];for(const f of o){const g=u[u.length-1].time;f+zr<=g+mn||(f>g+mn&&u.push({time:f,value:i}),u.push({time:f+zr,value:1,easing:"ease-in"}),u.push({time:f+r,value:i,easing:"ease-out"}))}return u.length>1?u:[]}function Pb(t,e,n,s){const i=n*(1-.18*s),o=n*(1+.14*s),r=[{time:t[0].time,value:n}],a=(l,c,h)=>{const d=r[r.length-1];l<=d.time+mn||r.push({time:l,value:c,...h?{easing:h}:{}})};for(let l=1;l<t.length;l++){const c=t[l-1].pose[e],h=t[l].pose[e],d=t[l-1].time,u=t[l].time,f=u-d;if(!(f<Yr||t[l].act===!1)){if(c<=Be&&h>Be)a(d,n),a(d+f*.2,i,"ease-out"),a(d+f*.45,o,"ease-out"),a(u,n,"ease-in-out");else if(c>Be&&h<=Be){const g=l+1<t.length?t[l+1].time-u:400;a(d+f*.5,n),a(u-Math.min(60,f*.15),o,"ease-in"),a(u,i,"ease-out"),a(u+Math.min(260,g/2),n,{type:"back",mode:"out",overshoot:1.4})}}}return r.length>1?r:[]}const zd={depth:{lean:0,bend:0,rise:0,sit:0,spin:0,stretch:0,turn:0,leftHip:0,rightHip:0,headTilt:1,leftShoulder:1,rightShoulder:1,leftKnee:1,rightKnee:1,leftBrow:1,rightBrow:1,browTilt:1,leftEye:1,rightEye:1,leftElbow:2,rightElbow:2,leftAnkle:2,rightAnkle:2,leftFootOut:2,rightFootOut:2,mouth:2,smile:2,mouthWidth:2,leftWrist:3,rightWrist:3},limits:{lean:10,bend:10,headTilt:12,spin:25,turn:.06,sit:.06,stretch:.08,rise:0,leftShoulder:20,rightShoulder:20,leftElbow:18,rightElbow:18,leftWrist:15,rightWrist:15,leftHip:12,rightHip:12,leftKnee:15,rightKnee:15,leftAnkle:10,rightAnkle:10,leftBrow:.25,rightBrow:.25,leftEye:.15,rightEye:.15},eyes:["lookX","lookY"],blink:"blink",headTurns:{turn:.15,headTilt:8,lookX:.5,spin:45},drift:["lean","bend","headTilt","leftShoulder","rightShoulder","leftElbow","rightElbow"],lift:"rise",stretch:"stretch"};function xb(t){return/^(turn|lean|bend|side|lift|roll|stretch)$/.test(t)?{depth:0,limit:{turn:.06,lean:10,bend:10,side:8,lift:0,roll:25,stretch:.08}[t]}:/^leg\.\w+\.(swing|spread|rotate)$/.test(t)?{depth:0,limit:12}:/^head\./.test(t)?{depth:1,limit:12}:/^arm\.\w+\.(swing|spread)$/.test(t)?{depth:1,limit:20}:/^leg\.\w+\.knee$/.test(t)?{depth:1,limit:15}:/^(brow\.|browTilt$)/.test(t)?{depth:1,limit:t==="browTilt"?void 0:.25}:/^eye\./.test(t)?{depth:1,limit:.15}:/^arm\.\w+\.(elbow|bend)$/.test(t)?{depth:2,limit:18}:/^leg\.\w+\.(ankle|toeOut)$/.test(t)?{depth:2,limit:10}:/^(mouth|smile|mouthWidth)$/.test(t)?{depth:2}:/^hand\./.test(t)?{depth:3}:{depth:1}}function Ib(){const t={},e={};for(const n of Object.keys(ut)){const s=xb(n);t[n]=s.depth,s.limit!==void 0&&(e[n]=s.limit)}return{depth:t,limits:e,eyes:["lookX","lookY"],blink:"blink",headTurns:{turn:.15,"head.turn":15,"head.nod":12,lookX:.5,roll:45},drift:["lean","bend","head.tilt","head.nod","arm.left.spread","arm.right.spread","arm.left.elbow","arm.right.elbow"],lift:"lift",stretch:"stretch"}}const Xd=Ib();function Ud(t,e){return Object.entries(e).map(([n,s])=>({id:`${t}-${n}`,target:t,property:n,keyframes:s}))}function Gd(t,e,n={}){const s=tr(e),i=e.map((o,r)=>({time:o.time,pose:{...s[r]},easing:o.easing,act:o.act}));return Ud(t,Ti(i,n.rig??zd,n))}function Ob(t,e,n={}){const s=n.rest??ut,i=kr(e,s),o=e.map((r,a)=>({time:r.time,pose:{...s,...i[a]},easing:r.easing,act:r.act}));return Ud(t,Ti(o,n.rig??Xd,n))}const Vd=ct.shocked,_b=ct.scared,Me={take:t=>[{after:140,pose:{stretch:.8,bend:10,lean:t.lean-4,leftShoulder:8,rightShoulder:8,leftEye:.35,rightEye:.35,leftBrow:-.6,rightBrow:-.6,mouth:0},easing:"ease-in-out"},{after:260,pose:{stretch:.78}},{after:360,pose:{rise:.22,stretch:1.35,bend:-14,leftShoulder:150,rightShoulder:150,leftElbow:35,rightElbow:35,leftHip:22,rightHip:22,leftKnee:45,rightKnee:45,...Vd,headTilt:0},easing:"ease-out-cubic"},{after:720,pose:{rise:.25,stretch:1.25,bend:-10,leftShoulder:140,rightShoulder:140},easing:"ease-in-out"},{after:900,pose:{rise:0,stretch:.74,bend:12,leftShoulder:70,rightShoulder:70,leftHip:18,rightHip:18,leftKnee:30,rightKnee:30},easing:"ease-in-quad"},{after:1060,pose:{stretch:1.06,bend:-3,leftShoulder:60,rightShoulder:60,leftHip:t.leftHip,rightHip:t.rightHip,leftKnee:t.leftKnee,rightKnee:t.rightKnee},easing:"ease-out"},{after:1260,pose:{stretch:t.stretch,bend:t.bend,...ct.surprised,leftShoulder:70,rightShoulder:70,leftElbow:60,rightElbow:60},easing:"ease-in-out"}],doubleTake:t=>[{after:160,pose:{lookX:1,lookY:0},easing:"ease-out"},{after:520,pose:{lookX:-.6,headTilt:t.headTilt-4,smile:.6,mouth:0},easing:"ease-in-out"},{after:1100,pose:{lookX:-.6}},{after:1180,pose:{bend:t.bend-10,headTilt:t.headTilt+10,rise:.05,stretch:1.18,...Vd,lookX:1,lookY:0},easing:"ease-out-cubic"},{after:1360,pose:{rise:0,stretch:.88,bend:t.bend+4,headTilt:t.headTilt+4},easing:"ease-in-quad"},{after:1560,pose:{stretch:t.stretch,bend:t.bend,headTilt:t.headTilt},easing:{type:"elastic",mode:"out",amplitude:1,period:.35}}],windUp:()=>[{after:220,pose:{lean:-18,bend:-16,headTilt:-6,leftShoulder:70,leftElbow:-100,rightShoulder:40,rightElbow:100,leftHip:-45,leftKnee:-80,stretch:.92,...ct.angry,lookX:1},easing:"ease-out"},{after:620,pose:{lean:-20,bend:-18,stretch:.9}},{after:700,pose:{lean:28,bend:14,headTilt:6,leftShoulder:30,rightShoulder:60,leftHip:30,leftKnee:-30,rightHip:-20,stretch:1.12},easing:"ease-out-cubic"}],land:t=>[{after:120,pose:{rise:0,stretch:.7,bend:14,leftShoulder:75,rightShoulder:75,leftHip:20,rightHip:20,leftKnee:35,rightKnee:35},easing:"ease-in-quad"},{after:300,pose:{stretch:1.05,bend:-4,leftShoulder:t.leftShoulder,rightShoulder:t.rightShoulder},easing:"ease-out"},{after:460,pose:{rise:0,stretch:t.stretch,bend:t.bend,leftHip:et.leftHip,rightHip:et.rightHip,leftKnee:0,rightKnee:0},easing:"ease-in-out"}],tremble:t=>{const e=[{after:80,pose:{..._b,bend:t.bend+8,leftShoulder:40,rightShoulder:40,leftElbow:110,rightElbow:110,stretch:.94},easing:"ease-out"}];for(let n=1;n<=14;n++)e.push({after:80+n*45,pose:{lean:t.lean+(n%2===0?2.5:-2.5),headTilt:t.headTilt+(n%2===0?-2:2)}});return e.push({after:755,pose:{lean:t.lean,headTilt:t.headTilt,bend:t.bend}}),e},deflate:t=>[{after:260,pose:{stretch:1.04,headTilt:t.headTilt+4,leftBrow:.3,rightBrow:.3},easing:"ease-in-out"},{after:900,pose:{...Dt.sad,bend:18,stretch:.92,lean:t.lean+5,turn:t.turn,sit:t.sit},easing:"ease-in-out"}]};function Xr(t,e){const n=typeof e.from=="string"?Dt[e.from]:e.from??et;return Ur(Me[t](n),{...e,from:n})}function Ur(t,e){const n=e.speed??1;let s=e.from;return[{time:e.at,pose:e.from},...t.map(i=>(s={...s,...i.pose},{time:e.at+i.after*n,pose:s,act:!1,...i.easing?{easing:i.easing}:{}}))]}function os(t,e=1){const n=Me[t](et);return n[n.length-1].after*e}function Jd(t,e,n={}){if(e.length<2)return;const s=Math.max(1,Math.round(n.lines??3)),i=n.spacing??5,o=n.lineWidth??2,r=n.opacity??.7;t.save(),t.strokeStyle=n.color??"#222",t.lineCap="round";for(let a=0;a<s;a++){const l=(a-(s-1)/2)*i,c=Math.floor(Math.abs(l)/Math.max(i,1)*(e.length/6));for(let h=c+1;h<e.length;h++){const d=e[h-1],u=e[h],f=u.x-d.x,g=u.y-d.y,p=Math.hypot(f,g)||1,m=-g/p,b=f/p,S=1-h/(e.length-1);t.globalAlpha=r*(1-S),t.lineWidth=o*(1-S*.7),t.beginPath(),t.moveTo(d.x+m*l,d.y+b*l),t.lineTo(u.x+m*l,u.y+b*l),t.stroke()}}t.restore()}const Cb={hands:[{name:"left hand",at:t=>t.hands.left},{name:"right hand",at:t=>t.hands.right}],toes:[{name:"left toe",at:t=>t.toes.left},{name:"right toe",at:t=>t.toes.right}],head:[{name:"head",at:t=>t.head.center}],body:[{name:"hip",at:t=>t.hip},{name:"neck",at:t=>t.neck}]};function Hb(t,e,n,s,i={}){const o=n.stateAt;if(!o)return;const r=i.length??120,a=Math.max(2,Math.round(i.samples??8)),l=Math.max(0,n.time-r);if(n.time-l<1)return;const c=[];for(let f=0;f<a;f++){const g=l+(n.time-l)*f/(a-1);c.push(Qo(e,{time:g,state:o(g)},s).joints)}const h=c[c.length-1].height,d=(i.threshold??1.2)*h,u=(i.parts??["hands","toes","head"]).flatMap(f=>Cb[f]);for(const f of u){const g=c.map(f.at);let p=0;for(let S=1;S<g.length;S++)p+=Math.hypot(g[S].x-g[S-1].x,g[S].y-g[S-1].y);const m=p/((n.time-l)/1e3);if(m<=d)continue;const b=Math.min(1,(m-d)/(d*.5));Jd(t,g,{...i,opacity:(i.opacity??.7)*b,spacing:i.spacing??h*.02})}}function Zd(t,e,n,s={}){if(n<=0||n>=1)return;const i=s.size??40,o=s.seed??1,r=.45+.55*(1-(1-n)**3);t.save(),t.strokeStyle=s.color??"#555",t.lineWidth=Math.max(1,i*.03),t.globalAlpha=Math.min(1,n/.08)*(1-n);for(let a=0;a<5;a++){const l=qt(`${o}:puff:${a}`)%1e3/1e3,c=a-2,h=e.x+c*i*.3*r,d=e.y-i*(.06+.12*l)*r+Math.abs(c)*i*.03,u=i*(.11+.07*l)*r;t.beginPath(),t.arc(h,d,u,Math.PI*.95,Math.PI*2.05),t.stroke()}t.restore()}function Rb(t,e,n,s={}){if(n<=0||n>=1)return;const i=s.size??40,o=5,r=1-(1-n)**2;t.save(),t.strokeStyle=s.color??"#222",t.lineWidth=Math.max(1,i*.035),t.lineJoin="round",t.globalAlpha=n<.7?1:(1-n)/.3;for(let a=0;a<o;a++){const l=-Math.PI/2+(a-(o-1)/2)*Math.PI/(o+1),c=i*(.3+.7*r),h=e.x+Math.cos(l)*c,d=e.y+Math.sin(l)*c;Lb(t,h,d,i*.14,n*Math.PI+a),t.stroke()}t.restore()}function Lb(t,e,n,s,i){t.beginPath();for(let o=0;o<10;o++){const r=o%2===0?s:s*.45,a=i+o*Math.PI/5-Math.PI/2,l=e+Math.cos(a)*r,c=n+Math.sin(a)*r;o===0?t.moveTo(l,c):t.lineTo(l,c)}t.closePath()}const Se={rest:{mouth:0,mouthWidth:1},a:{mouth:.75,mouthWidth:1.1},e:{mouth:.45,mouthWidth:1.3},i:{mouth:.28,mouthWidth:1.45},o:{mouth:.6,mouthWidth:.7},u:{mouth:.32,mouthWidth:.55},m:{mouth:0,mouthWidth:.9},f:{mouth:.1,mouthWidth:1.05},l:{mouth:.3,mouthWidth:1},c:{mouth:.2,mouthWidth:1}},rs=1,Ei=.55,Qd=.35,Nb=1.6,tu={a:"a",e:"e",i:"i",y:"i",o:"o",u:"u"},eu={m:"m",b:"m",p:"m",f:"f",v:"f",w:"u",q:"u",l:"l",n:"l",d:"l",t:"l"},nu={अ:"a",आ:"a",इ:"i",ई:"i",उ:"u",ऊ:"u",ऋ:"i",ए:"e",ऐ:"e",ओ:"o",औ:"o",ऍ:"e",ऑ:"o"},su={"ा":"a","ि":"i","ी":"i","ु":"u","ू":"u","ृ":"i","े":"e","ै":"e","ो":"o","ौ":"o","ॅ":"e","ॉ":"o"},Db={प:"m",फ:"m",ब:"m",भ:"m",म:"m",व:"u"},Fb="्",iu="़",jb=t=>t>="क"&&t<="ह",ou=new Set([".",",","!","?",";",":","…","।","॥","—","-"]);function ru(t){const e=[],n=Array.from(t.toLowerCase()),s=(i,o)=>{const r=e[e.length-1];r&&r.viseme===i?r.weight+=o*.5:e.push({viseme:i,weight:o})};for(let i=0;i<n.length;i++){const o=n[i],r=n[i+1];if(ou.has(o))s("rest",Nb);else if(/\s/.test(o)){const a=e[e.length-1];a&&a.viseme!=="rest"&&e.push({viseme:"c",weight:Qd})}else if((o==="o"||o==="e")&&r===o)s(o==="o"?"u":"i",rs),i++;else if(o in tu)s(tu[o],rs);else if(o in eu)s(eu[o],Ei);else{if(o==="h")continue;if(/[a-z]/.test(o))s("c",Ei);else if(o in nu)s(nu[o],rs);else if(jb(o)){const a=r===iu?o==="फ"?"f":void 0:Db[o];s(a??"c",Ei);let l=i+1;n[l]===iu&&l++;const c=n[l];c===Fb?i=l:c&&c in su?(s(su[c],rs),i=l):(!c||/\s/.test(c)||ou.has(c)||s("a",rs*.6),i=l-1)}else(o==="ं"||o==="ँ")&&s("l",Ei*.6)}}for(;e.length>0&&(e[e.length-1].viseme==="rest"||e[e.length-1].weight===Qd);)e.pop();return e}function Gr(t,e={}){const n=e.fields?.mouth??"mouth",s=e.fields?.mouthWidth??"mouthWidth",i=e.energy??1,o=ru(t.text),r=[{time:t.start,value:Se.rest.mouth}],a=[{time:t.start,value:Se.rest.mouthWidth}],l=o.reduce((h,d)=>h+d.weight,0),c=t.end-t.start;if(l>0&&c>0){let h=t.start;for(const d of o){const u=c*d.weight/l,f=h+Math.min(u*.4,60);if(f>r[r.length-1].time){const g=Se[d.viseme];r.push({time:f,value:g.mouth*i,easing:"ease-out"}),a.push({time:f,value:1+(g.mouthWidth-1)*Math.min(1.3,i),easing:"ease-out"})}h+=u}}return t.end>r[r.length-1].time&&(r.push({time:t.end,value:Se.rest.mouth,easing:"ease-in-out"}),a.push({time:t.end,value:Se.rest.mouthWidth,easing:"ease-in-out"})),{[n]:r,[s]:a}}function Bb(t,e,n={}){const s={};for(const i of[...e].sort((o,r)=>o.start-r.start))for(const[o,r]of Object.entries(Gr(i,n))){const a=s[o]??=[],l=a.length>0?a[a.length-1].time:-1/0;a.push(...r.filter(c=>c.time>l))}return Object.entries(s).map(([i,o])=>({id:`${t}-${i}`,target:t,property:i,keyframes:o}))}function au(t,e,n,s={}){if(n.length===0)return e;const i=s.fields?.mouth??"mouth",o=s.fields?.mouthWidth??"mouthWidth",r={[i]:Se.rest.mouth,[o]:Se.rest.mouthWidth,...s.rest},a=new Ht({id:"before-speech",tracks:e}),l=(d,u)=>a.getStateAtTime(u).values.get(t)?.get(d)??r[d],c=[i,o],h=e.filter(d=>d.target!==t||!c.includes(d.property));for(const d of c){const u=e.find(g=>g.target===t&&g.property===d);let f=u?[...u.keyframes]:[{time:0,value:l(d,0)}];for(const g of n){const p=Gr(g,s)[d];p[0]={...p[0],value:l(d,g.start)},p[p.length-1]={...p[p.length-1],value:l(d,g.end)},f=[...f.filter(m=>m.time<g.start||m.time>g.end),...p],f.sort((m,b)=>m.time-b.time)}h.push({id:u?.id??`${t}-${d}`,target:t,property:d,keyframes:f})}return h}const as={look:{summary:"Turns the head and eyes toward a scene x, `viewer`, `ahead` or `back`.",uses:["toward"]},face:{summary:"Turns the whole figure toward a scene x (turning round if needed), `viewer`, `ahead` or `back`.",uses:["toward"]},say:{summary:"Lip-syncs the `say` line with small nods; the beat lasts as long as the line.",needs:["say"]},hold:{summary:"Holds the pose (the acting pass drifts long holds)."},stand:{summary:"Back to its resting stance (a character’s own, else the rest pose), keeping the way it is turned."},go:{summary:"Walks to `to` in its own gait (a character’s, else walk).",needs:["to"]},zip:{summary:"The cartoon exit: winds up, wheels its legs in place, then shoots off to `to`, leaving dust.",needs:["to"]},leap:{summary:"Crouches, springs, arcs and lands squashed at `to`, on the floor `onto` (a scene y).",uses:["to","onto"]},swipe:{summary:"Winds an arm up, then slides along the target with the arm out so the hand crosses it edge to edge.",uses:["target"]},grab:{summary:"Steps to where its arm reaches the target (crouching for low things), takes it and lifts it overhead.",needs:["target"]},throw:{summary:"Winds the arm back and throws forward and up toward `to` (or the target); `release` is when it lets go.",uses:["to","target"]},kick:{summary:"Steps to a leg’s length from the target, draws the leg back and kicks through it.",needs:["target"]},put:{summary:"Steps to where its arm reaches the spot and sets the thing down there.",needs:["target"]},write:{summary:"Reaches a pen to the spot and writes along it left to right (moving along when it is wide).",needs:["target"]},push:{summary:"Sets both hands on the target’s near side and walks it along until its centre is at `to`.",needs:["target","to"]}};function Vr(t={}){return[...Object.keys(Ot),...Object.keys(Dt),...Object.keys(Me),...Object.keys(as),...Object.keys(t.gaits??{}),...Object.keys(t.actions??{})]}function Jr(t={}){const e=new Set(Vr()),n=[];for(const s of[...Object.keys(t.actions??{}),...Object.keys(t.gaits??{})])e.has(s)&&n.push(`Custom action or gait "${s}" has the name of a built-in one; give it its own name.`);for(const s of Object.keys(t.actions??{}))t.gaits&&s in t.gaits&&n.push(`"${s}" is both a custom action and a custom gait.`);return n}function Zr(t={}){const e={};for(const n of Object.keys(Ot))e[n]=`Walks to \`to\` in the ${n} gait, feet planted, turning round first if needed.`;for(const n of Object.keys(Dt))e[n]=`Moves into the ${n} pose and holds it.`;for(const n of Object.keys(Me))e[n]=`The ${n} gag, built on the current pose.`;for(const[n,s]of Object.entries(as))e[n]=s.summary;for(const[n,s]of Object.entries(t.gaits??{}))e[n]=s.summary??`Walks to \`to\` in the ${n} gait (custom).`;for(const[n,s]of Object.entries(t.actions??{}))e[n]=s.summary;return e}const Ai=["do","at","for","to","toward","mood","say","pose","target","onto"],Wb={action:"do",type:"do",verb:"do",time:"at",start:"at",delay:"at",duration:"for",length:"for",ms:"for",x:"to",position:"to",destination:"to",expression:"mood",emotion:"mood",face:"mood",feeling:"mood",text:"say",line:"say",speech:"say",dialogue:"say",joints:"pose",y:"onto",floor:"onto",ground:"onto",object:"target",at_target:"target"},$i=["viewer","ahead","back"],We=t=>typeof t=="number"&&Number.isFinite(t);function ls(t,e={}){const n=Jr(e).map(l=>({level:"error",beat:-1,message:l}));if(!Array.isArray(t))return[...n,{level:"error",beat:-1,message:`Beats must be an array of { do: … } objects (got ${typeof t}).`}];const s=Vr(e),i=l=>l in Ot||l in(e.gaits??{}),o=Object.keys(ct),r=Object.keys(et);let a=-1/0;return t.forEach((l,c)=>{const h=p=>n.push({level:"error",beat:c,message:p}),d=p=>n.push({level:"warning",beat:c,message:p});if(!l||typeof l!="object"||Array.isArray(l)){h(`Each beat must be an object like { do: 'walk', to: 400 } (got ${JSON.stringify(l)}).`);return}const u=l;for(const p of Object.keys(u))Ai.includes(p)||h(ot("beat field",p,Ai,Wb[p.toLowerCase()]));const f=u.do;if(f===void 0){h(`A beat needs \`do\` (what happens). Actions: ${s.join(", ")}`);return}if(typeof f!="string"||!s.includes(f)){h(ot("action",f,s));return}const g=as[f]??e.actions?.[f];for(const p of g?.needs??[])u[p]===void 0&&h(`\`${f}\` needs \`${p}\`.`);if(i(f)&&u.to===void 0&&d(`\`${f}\` without \`to\` walks nowhere.`),f==="leap"&&u.to===void 0&&u.onto===void 0&&d("`leap` without `to` or `onto` jumps on the spot."),u.mood!==void 0&&(typeof u.mood!="string"||!o.includes(u.mood))&&h(ot("mood",u.mood,o)),u.pose!==void 0)if(!u.pose||typeof u.pose!="object"||Array.isArray(u.pose))h("`pose` is joints to change, an object like { rightShoulder: 90 } (for a named pose, use it as the action).");else for(const[p,m]of Object.entries(u.pose))r.includes(p)?We(m)||h(`Pose joint \`${p}\` must be a number (got ${JSON.stringify(m)}).`):h(ot("pose joint",p,r));for(const p of["at","for"]){const m=u[p];m!==void 0&&!(We(m)&&m>=0)&&h(`\`${p}\` is milliseconds, a number ≥ 0 (got ${JSON.stringify(m)}).`)}We(u.at)&&(u.at<a&&d(`\`at\` ${u.at} is before an earlier beat's \`at\` (${a}); beats run in order, so it starts when the one before ends.`),a=u.at);for(const p of["to","onto"]){const m=u[p];m!==void 0&&!We(m)&&h(`\`${p}\` is a scene ${p==="to"?"x":"y"} in px, a number (got ${JSON.stringify(m)}).`)}if(u.toward!==void 0&&!We(u.toward)&&!$i.includes(u.toward)&&h(`\`toward\` is a scene x or one of ${$i.join(", ")}${typeof u.toward=="string"&&Hn(u.toward,$i)?` (did you mean "${Hn(u.toward,$i)}"?)`:""} (got ${JSON.stringify(u.toward)}).`),u.say!==void 0&&typeof u.say!="string"&&h(`\`say\` is the line spoken, a string (got ${JSON.stringify(u.say)}).`),u.target!==void 0){const p=u.target;(!p||typeof p!="object"||!We(p.x)||!We(p.y))&&h("`target` is a point or box in scene px: { x, y } (a code panel’s line(), token() or spot() fits).")}}),n}function Qr(t,e={},n="scriptTracks"){const s=ls(t,e).filter(i=>i.level==="error");if(s.length!==0)throw new Error(`${n}: ${s.length} problem(s) in the beats:
|
|
53
|
+
`;function y1(t){if(t.getElementById(xh))return;const e=t.createElement("style");e.id=xh,e.textContent=m1,t.head.appendChild(e)}function $h(t,e){const n=Array.from(e.querySelectorAll("[data-tinyfly-choose]"));if(n.length===0)return()=>{};y1(e.ownerDocument);const s=[],i=[];for(const a of n){const l=a.getAttribute("data-tinyfly-choose")??"",c=[],h=(p,g)=>{a.hasAttribute(p)||(a.setAttribute(p,g),c.push(p))};h("role","button"),h("tabindex","0");const u=t.scenarios.find(p=>p.id===l)?.label;u!==void 0&&h("aria-label",u),a.setAttribute("aria-pressed","false"),c.push("aria-pressed"),s.push({element:a,attributes:c});const d=()=>t.setScenario(l),f=p=>{const g=p.key;g!=="Enter"&&g!==" "||(p.preventDefault(),d())};a.addEventListener("click",d),a.addEventListener("keydown",f),i.push(()=>{a.removeEventListener("click",d),a.removeEventListener("keydown",f)})}const o=()=>{for(const{element:a}of s)a.setAttribute("aria-pressed",String(a.getAttribute("data-tinyfly-choose")===t.scenario))},r=t.subscribe(o);return o(),()=>{r();for(const a of i)a();for(const{element:a,attributes:l}of s)for(const c of l)a.removeAttribute(c)}}const ei=new WeakMap,fr=new WeakMap;let b1=0;function Jn(t,e,n){if(t)try{return JSON.parse(t)}catch(s){console.warn(`tinyfly: invalid ${e} JSON on`,n,s);return}}async function Ph(t,e={}){const n=ei.get(t);if(n)return n;const s=Array.from(t.querySelectorAll("script[data-tinyfly-timeline]")),i=s[0],o=t.getAttribute("data-src"),r=k1(t.getAttribute("data-markers")),a=s.length>1||i?.hasAttribute("data-scenario")?w1(s,r,t):void 0;if(a&&a.length===0)return;let l=i&&!a?Jn(i.textContent,"timeline",t):void 0;if(!l&&o&&r){const f=await fetch(o);f.ok&&(l=await f.json())}if(l&&r&&(l=Ih(l,r)),!l&&!o&&!a){console.warn('tinyfly: embed has no timeline (a <script type="application/json" data-tinyfly-timeline> or data-src)',t);return}const c=Jn(t.querySelector("script[data-tinyfly-captions]")?.textContent,"captions",t),h={playWhenVisible:!0,...e.player,...c&&{captions:c},...Jn(t.getAttribute("data-options"),"data-options",t)};M1(t);const u=new ti(t,h),d={element:t,player:u};if(ei.set(t,d),t.setAttribute("data-tinyfly-mounted",""),a){const f=t.getAttribute("data-scenario")??void 0;await u.loadScenarios(a,{initial:a.some(p=>p.id===f)?f:void 0}),fr.set(t,$h(u,t))}else await u.load(l??o);if(t.getAttribute("data-controls")!=="false"){const f=Jn(t.getAttribute("data-labels"),"data-labels",t),p=t.querySelector("figcaption"),g=t.getAttribute("data-scenario-legend"),m=t.getAttribute("data-scenario-control");d.controls=Ah(u,t,{...e.controls,...t.getAttribute("data-fullscreen")==="true"?{fullscreen:!0}:{},...m==="slider"||m==="buttons"?{scenarioControl:m}:{},labels:{...e.controls?.labels,...f,...g?{scenario:g}:{}},mount:void 0}),p?t.insertBefore(d.controls.element,p):t.appendChild(d.controls.element)}return d}function w1(t,e,n){const s=[];return t.forEach((i,o)=>{const r=Jn(i.textContent,"timeline",n);if(!r)return;const a=i.getAttribute("data-scenario")||`scenario-${o+1}`;if(s.some(c=>c.id===a)){console.warn(`tinyfly: scenario id "${a}" is used more than once; the later one is skipped`,n);return}const l=i.getAttribute("data-scenario-label")??void 0;s.push({id:a,label:l,timeline:e?Ih(r,e):r})}),s}function Ih(t,e){return t.config.markers?.length?t:{...t,config:{...t.config,markers:e.map((n,s)=>({id:`step-${s+1}`,time:n}))}}}function k1(t){if(!t)return;const e=t.split(/[\s,]+/).filter(Boolean).map(Number).filter(n=>Number.isFinite(n)&&n>=0).sort((n,s)=>n-s);return e.length>0?e:void 0}async function Oh(t=document,e={}){const n=Array.from(t.querySelectorAll("[data-tinyfly-embed]"));return(await Promise.all(n.map(i=>Ph(i,e)))).filter(i=>i!==void 0)}function v1(t){const e=ei.get(t);e&&(fr.get(t)?.(),fr.delete(t),e.controls?.destroy(),e.player.destroy(),ei.delete(t),t.removeAttribute("data-tinyfly-mounted"))}function M1(t){const e=t.querySelector("svg");if(!e||e.hasAttribute("role")||e.hasAttribute("aria-hidden"))return;const n=t.getAttribute("data-alt"),s=t.querySelector("figcaption");e.setAttribute("role","img"),n?e.setAttribute("aria-label",n):s&&(s.id||=`tinyfly-caption-${++b1}`,e.setAttribute("aria-labelledby",s.id))}function S1(){if(!(typeof document<"u"?document.currentScript:null)?.hasAttribute("data-tinyfly-auto"))return;const e=()=>{Oh()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e,{once:!0}):e()}class _h{container;containerA;containerB;adapterA;adapterB;timelineA=null;timelineB=null;symbolDefs=new Map;nestedByAdapter=new Map;sequence=null;options;_currentSceneIndex=0;_state="idle";_isPlaying=!1;_isDestroyed=!1;loopIteration=0;animationFrameId;lastTime;transitionTimer;constructor(e,n={}){if(typeof e=="string"){const s=document.querySelector(e);if(!s)throw new Error(`Container not found: ${e}`);this.container=s}else this.container=e;this.options=n,this.container.style.position="relative",this.container.style.overflow="hidden",this.containerA=this.createSceneContainer(),this.containerB=this.createSceneContainer(),this.container.appendChild(this.containerA),this.container.appendChild(this.containerB),this.containerB.style.visibility="hidden",this.adapterA=new qe,this.adapterB=new qe}async load(e){let n;if(typeof e=="string"){const s=await fetch(e);if(!s.ok)throw new Error(`Failed to load sequence: ${s.statusText}`);n=await s.json()}else n=e;this.sequence=n,this.symbolDefs.clear();for(const s of n.symbols??[])s.timeline?.tracks?.length&&this.symbolDefs.set(s.id,s.timeline);this.container.style.width=`${n.canvas.width}px`,this.container.style.height=`${n.canvas.height}px`,n.scenes.length>0&&(this.renderScene(n.scenes[0],this.containerA,this.adapterA),this.timelineA=this.createTimeline(n.scenes[0])),this.options.autoplay&&this.play()}play(){if(!(!this.sequence||this._isDestroyed)&&this.sequence.scenes.length!==0){if(this._isPlaying=!0,this._state==="idle"){if(this._state="playing-scene",this._currentSceneIndex=0,this.timelineA)this.timelineA.onComplete=()=>this.onSceneComplete(),this.timelineA.play();else{this.onSceneComplete();return}this.options.onSceneChange?.(0)}else this._state==="playing-scene"&&this.timelineA&&this.timelineA.play();this.startAnimationLoop()}}pause(){this._isPlaying&&(this._isPlaying=!1,this.timelineA&&this.timelineA.pause(),this.timelineB&&this.timelineB.pause(),this.stopAnimationLoop())}stop(){if(this._isPlaying=!1,this._state="idle",this._currentSceneIndex=0,this.loopIteration=0,this.transitionTimer!==void 0&&(clearTimeout(this.transitionTimer),this.transitionTimer=void 0),this.timelineA&&this.timelineA.stop(),this.timelineB&&this.timelineB.stop(),this.stopAnimationLoop(),this.sequence&&this.sequence.scenes.length>0&&(this.clearContainer(this.containerA),this.clearContainer(this.containerB),this.adapterA.clearTargets(),this.adapterB.clearTargets(),this.containerB.style.visibility="hidden",this.resetTransitionStyles(this.containerA),this.resetTransitionStyles(this.containerB),this.renderScene(this.sequence.scenes[0],this.containerA,this.adapterA),this.timelineA=this.createTimeline(this.sequence.scenes[0]),this.timelineA)){const e=this.timelineA.getStateAtTime(0);this.adapterA.applyState(e),this.applyNested(this.adapterA,0)}}goToScene(e){if(!this.sequence||e<0||e>=this.sequence.scenes.length)return;const n=this._isPlaying;this.transitionTimer!==void 0&&(clearTimeout(this.transitionTimer),this.transitionTimer=void 0),this.stopAnimationLoop(),this.timelineA&&this.timelineA.stop(),this.timelineB&&this.timelineB.stop(),this._currentSceneIndex=e,this._state=n?"playing-scene":"idle",this.clearContainer(this.containerA),this.clearContainer(this.containerB),this.adapterA.clearTargets(),this.adapterB.clearTargets(),this.containerB.style.visibility="hidden",this.resetTransitionStyles(this.containerA),this.resetTransitionStyles(this.containerB);const s=this.sequence.scenes[e];if(this.renderScene(s,this.containerA,this.adapterA),this.timelineA=this.createTimeline(s),this.options.onSceneChange?.(e),n)this.timelineA?(this.timelineA.onComplete=()=>this.onSceneComplete(),this.timelineA.play(),this.startAnimationLoop()):this.onSceneComplete();else if(this.timelineA){const i=this.timelineA.getStateAtTime(0);this.adapterA.applyState(i),this.applyNested(this.adapterA,0)}}destroy(){this._isDestroyed=!0,this._isPlaying=!1,this.transitionTimer!==void 0&&(clearTimeout(this.transitionTimer),this.transitionTimer=void 0),this.stopAnimationLoop(),this.adapterA.clearTargets(),this.adapterB.clearTargets();for(const e of this.nestedByAdapter.values())for(const n of e)n.adapter.clearTargets();this.nestedByAdapter.clear(),this.timelineA&&this.timelineA.stop(),this.timelineB&&this.timelineB.stop(),this.timelineA=null,this.timelineB=null,this.containerA.parentNode&&this.containerA.remove(),this.containerB.parentNode&&this.containerB.remove(),this.sequence=null}get currentSceneIndex(){return this._currentSceneIndex}get sceneCount(){return this.sequence?.scenes.length??0}get isPlaying(){return this._isPlaying}get state(){return this._state}createSceneContainer(){const e=document.createElement("div");return e.style.position="absolute",e.style.top="0",e.style.left="0",e.style.width="100%",e.style.height="100%",e}renderScene(e,n,s){n.innerHTML="",s.clearTargets();const i=document.createElement("div");i.style.cssText="position:absolute;inset:0;transform-origin:center center",i.setAttribute("data-tinyfly","Camera"),n.appendChild(i),s.registerTarget("Camera",i);for(const o of e.elements){if(!o.html)continue;const r=document.createElement("div");r.innerHTML=o.html.trim();const a=r.firstElementChild;if(a){i.appendChild(a);const l=a.getAttribute("data-tinyfly");l&&s.registerTarget(l,a)}}this.setupNested(i,s)}setupNested(e,n){const s=[];e.querySelectorAll("[data-tinyfly-symbol]").forEach(i=>{const o=i.getAttribute("data-tinyfly-symbol");if(!o)return;const r=this.symbolDefs.get(o);if(!r)return;const a=new qe;i.querySelectorAll("[data-tinyfly]").forEach(l=>{const c=l.getAttribute("data-tinyfly");c&&a.registerTarget(c,l)}),s.push({adapter:a,timeline:hn(r)})}),s.length?this.nestedByAdapter.set(n,s):this.nestedByAdapter.delete(n)}applyNested(e,n){const s=this.nestedByAdapter.get(e);if(s)for(const i of s){const o=i.timeline.duration;i.adapter.applyState(i.timeline.getStateAtTime(o>0?n%o:n))}}clearContainer(e){e.innerHTML=""}createTimeline(e){return e.timeline?hn(e.timeline):null}onSceneComplete(){if(this._isDestroyed||!this.sequence)return;const e=this._currentSceneIndex+1;if(e>=this.sequence.scenes.length){const n=this.options.loop??this.sequence.loop??0;n===-1||n>0&&this.loopIteration<n-1?(this.loopIteration++,this.beginTransitionTo(0)):(this._isPlaying=!1,this._state="idle",this.stopAnimationLoop(),this.options.onComplete?.())}else this.beginTransitionTo(e)}beginTransitionTo(e){if(!this.sequence||this._isDestroyed)return;const n=this.sequence.scenes[e],s=n.transition;if(s.type==="none"||s.duration<=0){this.switchToScene(e);return}this._state="transitioning",this.containerB.style.visibility="visible",this.renderScene(n,this.containerB,this.adapterB),this.timelineB=this.createTimeline(n),this.timelineB&&this.timelineB.play(),this.applyTransition(s.type,s.duration),this.transitionTimer=window.setTimeout(()=>{this.finishTransition(e)},s.duration)}applyTransition(e,n){const s=`${n}ms`,i="ease-in-out";switch(this.resetTransitionStyles(this.containerA),this.resetTransitionStyles(this.containerB),e){case"fade":this.containerB.style.opacity="0";break;case"slide-left":this.containerB.style.transform="translateX(100%)";break;case"slide-right":this.containerB.style.transform="translateX(-100%)";break;case"slide-up":this.containerB.style.transform="translateY(100%)";break;case"slide-down":this.containerB.style.transform="translateY(-100%)";break}switch(this.containerB.offsetHeight,this.containerA.style.transition=`opacity ${s} ${i}, transform ${s} ${i}`,this.containerB.style.transition=`opacity ${s} ${i}, transform ${s} ${i}`,e){case"fade":this.containerA.style.opacity="0",this.containerB.style.opacity="1";break;case"slide-left":this.containerA.style.transform="translateX(-100%)",this.containerB.style.transform="translateX(0)";break;case"slide-right":this.containerA.style.transform="translateX(100%)",this.containerB.style.transform="translateX(0)";break;case"slide-up":this.containerA.style.transform="translateY(-100%)",this.containerB.style.transform="translateY(0)";break;case"slide-down":this.containerA.style.transform="translateY(100%)",this.containerB.style.transform="translateY(0)";break}}resetTransitionStyles(e){e.style.transition="",e.style.opacity="1",e.style.transform=""}finishTransition(e){this.transitionTimer=void 0,this.timelineA&&(this.timelineA.stop(),this.timelineA=null),this.adapterA.clearTargets(),this.clearContainer(this.containerA);const n=this.containerA;this.containerA=this.containerB,this.containerB=n;const s=this.adapterA;this.adapterA=this.adapterB,this.adapterB=s,this.timelineA=this.timelineB,this.timelineB=null,this.containerB.style.visibility="hidden",this.resetTransitionStyles(this.containerA),this.resetTransitionStyles(this.containerB),this._currentSceneIndex=e,this._state="playing-scene",this.options.onSceneChange?.(e),this.timelineA?(this.timelineA.onComplete=()=>this.onSceneComplete(),this.timelineA.playbackState!=="playing"&&this.timelineA.play()):this.onSceneComplete()}switchToScene(e){if(!this.sequence||this._isDestroyed)return;this.timelineA&&this.timelineA.stop(),this.adapterA.clearTargets(),this.clearContainer(this.containerA);const n=this.sequence.scenes[e];this.renderScene(n,this.containerA,this.adapterA),this.timelineA=this.createTimeline(n),this._currentSceneIndex=e,this._state="playing-scene",this.options.onSceneChange?.(e),this.timelineA?(this.timelineA.onComplete=()=>this.onSceneComplete(),this.timelineA.play()):this.onSceneComplete()}startAnimationLoop(){if(this.animationFrameId!==void 0)return;this.lastTime=performance.now();const e=n=>{if(this._isDestroyed||!this._isPlaying)return;const s=n-(this.lastTime??n);if(this.lastTime=n,this.timelineA&&this.timelineA.playbackState==="playing"){this.timelineA.tick(s);const i=this.timelineA.getStateAtTime(this.timelineA.currentTime);this.adapterA.applyState(i),this.applyNested(this.adapterA,this.timelineA.currentTime)}if(this._state==="transitioning"&&this.timelineB&&this.timelineB.playbackState==="playing"){this.timelineB.tick(s);const i=this.timelineB.getStateAtTime(this.timelineB.currentTime);this.adapterB.applyState(i),this.applyNested(this.adapterB,this.timelineB.currentTime)}this._isPlaying?this.animationFrameId=requestAnimationFrame(e):this.animationFrameId=void 0};this.animationFrameId=requestAnimationFrame(e)}stopAnimationLoop(){this.animationFrameId!==void 0&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0)}}async function T1(t,e,n={}){const s=new _h(t,{...n,autoplay:!0});return await s.load(e),s}const E1={type:"none",duration:0},kt=t=>({description:t,unit:"degrees"}),dt=(t,e=0,n=1)=>({description:t,unit:`${e}..${n}`,min:e,max:n}),Ch={lean:kt("Upper body tipped about the hips (+ toward the way it faces)"),bend:kt("Line of action: the spine curved (+ curls forward, − arches back)"),headTilt:kt("Head tilt"),leftShoulder:kt("Left upper arm: 0 hangs down, 90 straight out to its side, 180 straight up; in profile, forward is negative for the left arm"),rightShoulder:kt("Right upper arm: 0 hangs down, 90 straight out (forward, in profile), 180 straight up"),leftElbow:kt("Left elbow bend, added to the upper arm"),rightElbow:kt("Right elbow bend, added to the upper arm"),leftHip:kt("Left thigh: 0 straight down; in profile negative is forward"),rightHip:kt("Right thigh: 0 straight down; in profile positive is forward"),leftKnee:kt("Left knee bend (negative folds the shin back)"),rightKnee:kt("Right knee bend (positive folds the shin back)"),leftWrist:kt("Left wrist bend, added to the forearm"),rightWrist:kt("Right wrist bend, added to the forearm"),leftAnkle:kt("Left ankle: + points the toe down (tiptoe), − onto the heel"),rightAnkle:kt("Right ankle: + points the toe down (tiptoe), − onto the heel"),leftFootOut:dt("Left foot turned out (seen from the front): 0 natural, 1 sideways, negative turned in",-1,1),rightFootOut:dt("Right foot turned out (seen from the front): 0 natural, 1 sideways, negative turned in",-1,1),mouth:dt("Mouth open: 0 closed, 1 wide open"),smile:dt("−1 frown, 0 flat, 1 smile",-1,1),mouthWidth:{description:"Mouth width: 1 normal, 0.5 pursed, 1.5 wide",unit:"factor",min:.3,max:2},blink:dt("Eyes closed by a blink: 0 open, 1 shut"),leftEye:{description:"Left eye openness: 0 shut, 1 normal, 1.6 wide",unit:"factor",min:0,max:2},rightEye:{description:"Right eye openness: 0 shut, 1 normal, 1.6 wide",unit:"factor",min:0,max:2},leftBrow:dt("Left eyebrow: −1 lowered, 0 rest, 1 raised",-1,1),rightBrow:dt("Right eyebrow: −1 lowered, 0 rest, 1 raised",-1,1),browTilt:dt("Eyebrow slant: −1 angry, 1 worried",-1,1),lookX:dt("Eyes look across: + the way it faces",-1,1),lookY:dt("Eyes look down (+) or up (−)",-1,1),stretch:{description:"Squash and stretch: 1 normal, above taller (a jump), below squashed (a landing)",unit:"factor",min:.3,max:3},turn:dt("0 front-on, 1 in profile, turned the way it faces"),sit:dt("0 standing, 1 seated"),spin:kt("Whole body turned about the hips: + rolls forward (a front flip), 360 a full turn"),rise:{description:"Lift off the ground, as a fraction of its height (the arc of a jump)",unit:"× height"}},Hh={walk:{description:"Walk-cycle phase, in strides: animate 0 → n for n strides",unit:"strides"},walking:dt("How much of the walk cycle is applied (0 standing)"),gait:{description:"How it walks: a gait name (walk, bouncy, doubleBounce, sneak, strut, tired, run, shove); a string track switches it",kind:"string"},talk:dt("How much the mouth chatters"),rubber:dt("Limbs from jointed (0) to rubber hose (1)"),facing:{description:"Which way it faces: 1 right, −1 left (key the flip while turn is near 0)",unit:"±1",min:-1,max:1},beat:{description:"Beats into its dance (with a dance)",unit:"beats"},dancing:dt("How much of the dance is applied")},Rh={"thumb.curl":dt("Thumb curled in"),"thumb.across":dt("Thumb across the palm"),"index.curl":dt("Index finger curled"),"middle.curl":dt("Middle finger curled"),"ring.curl":dt("Ring finger curled"),"pinky.curl":dt("Little finger curled"),spread:dt("Fingers spread apart"),turn:kt("Hand turned about the forearm"),bend:kt("Hand bent at the wrist, palm-ward"),tilt:kt("Hand tilted sideways"),roll:kt("Hand rolled to show the back or the palm")};let Lh;function A1(t){Lh=t}function x1(t){return Lh?.(t)??{}}function Fh(t){let e=0;for(let n=1;n<t.length;n++)e+=Math.hypot(t[n].x-t[n-1].x,t[n].y-t[n-1].y);return e}function bn(t,e){const n=Math.min(1,Math.max(0,e));if(t.length<2||n===1)return t.slice();if(n===0)return t.slice(0,1);let s=Fh(t)*n;const i=[t[0]];for(let o=1;o<t.length;o++){const r=t[o-1],a=t[o],l=Math.hypot(a.x-r.x,a.y-r.y);if(l>=s){const c=l===0?0:s/l;return i.push({x:r.x+(a.x-r.x)*c,y:r.y+(a.y-r.y)*c}),i}i.push(a),s-=l}return i}function ni(t,e){const n=bn(t,e);return n[n.length-1]}function gr(t,e){return e>0?Math.floor(Math.max(0,t)*e/1e3):0}function si(t,e,n){const s=e.roughness??2,i=Math.max(1,Math.round(e.passes??2)),o=gr(n,e.boil??8);let r=0;const a=()=>{const d=r++;return f=>Ne(zt(`${e.seed??1}:${o}:${d}:${f}`))},l=(d,f)=>(d.next()*2-1)*f,c=d=>{const f=a(),p=t.lineWidth,g=t.globalAlpha;for(let m=0;m<i;m++)t.lineWidth=m===0?p:p*.55,t.globalAlpha=m===0?g:g*.6,d(f(m));t.lineWidth=p,t.globalAlpha=g},h=(d,f=1)=>{if(d.length<2)return;const p=d.slice(1).map((m,y)=>Math.hypot(m.x-d[y].x,m.y-d[y].y)),g=p.reduce((m,y)=>m+y,0)*Math.min(1,Math.max(0,f));c(m=>{const y=[],T=[];if(d.forEach((b,A)=>{y.push({x:b.x+l(m,s*.5),y:b.y+l(m,s*.5)}),A>0&&T.push([m.next()*2-1,m.next()*2-1])}),g<=0)return;t.beginPath(),t.moveTo(y[0].x,y[0].y);let k=0;for(let b=1;b<y.length;b++){const A=$1(y[b-1],y[b],s,T[b-1]),M=p[b-1];if(k+M<=g){t.bezierCurveTo(A[1].x,A[1].y,A[2].x,A[2].y,A[3].x,A[3].y),k+=M;continue}const E=P1(A,M===0?1:(g-k)/M);t.bezierCurveTo(E[1].x,E[1].y,E[2].x,E[2].y,E[3].x,E[3].y);break}t.stroke()})},u=(d,f,p,g,m=1)=>{c(y=>{const k=y.next()*Math.PI*2,b=Math.PI*2+.15+y.next()*.3,A=[];for(let E=0;E<=14;E++){const x=k+b*E/14,S=l(y,s*.6);A.push({x:d+Math.cos(x)*(p+S),y:f+Math.sin(x)*(g+S)})}const M=bn(A,m);M.length<2||(Nh(t,M),t.stroke())})};return{line:h,curve(d,f=1){if(d.length<2)return;const p=d[0],g=d[d.length-1],m=Math.hypot(g.x-p.x,g.y-p.y)||1,y=-(g.y-p.y)/m,T=(g.x-p.x)/m;c(k=>{const b={x:l(k,s*.5),y:l(k,s*.5)},A={x:l(k,s*.5),y:l(k,s*.5)},M=l(k,s*Math.min(1.5,Math.max(.3,m/80))),E=d.map((S,I)=>{const v=I/(d.length-1),$=Math.sin(Math.PI*v)*M;return{x:S.x+b.x+(A.x-b.x)*v+y*$,y:S.y+b.y+(A.y-b.y)*v+T*$}}),x=bn(E,f);x.length<2||(Nh(t,x),t.stroke())})},circle(d,f,p,g=1){u(d,f,p,p,g)},ellipse:u,nudge(d=.5){const f=a()(0);return{x:l(f,s*d),y:l(f,s*d)}}}}function $1(t,e,n,s){const i=e.x-t.x,o=e.y-t.y,r=Math.hypot(i,o)||1,a=n*Math.min(1.5,Math.max(.3,r/80)),l=-o/r,c=i/r;return[t,{x:t.x+i/3+l*s[0]*a,y:t.y+o/3+c*s[0]*a},{x:t.x+2*i/3+l*s[1]*a,y:t.y+2*o/3+c*s[1]*a},e]}function P1([t,e,n,s],i){const o=(u,d)=>({x:u.x+(d.x-u.x)*i,y:u.y+(d.y-u.y)*i}),r=o(t,e),a=o(e,n),l=o(n,s),c=o(r,a),h=o(a,l);return[t,r,c,o(c,h)]}function Nh(t,e){t.beginPath(),t.moveTo(e[0].x,e[0].y);for(let s=1;s<e.length-1;s++){const i={x:(e[s].x+e[s+1].x)/2,y:(e[s].y+e[s+1].y)/2};t.quadraticCurveTo(e[s].x,e[s].y,i.x,i.y)}const n=e[e.length-1];t.lineTo(n.x,n.y)}function oe(t,e,n){const s=t.length;if(s<2)return[];const i=[],o=[],r=a=>e+(n-e)*a/(s-1);return t.forEach((a,l)=>{const c=t[Math.max(0,l-1)],h=t[Math.min(s-1,l+1)],u=Math.hypot(h.x-c.x,h.y-c.y)||1,d=r(l)/2,f=-(h.y-c.y)/u*d,p=(h.x-c.x)/u*d;i.push({x:a.x+f,y:a.y+p}),o.push({x:a.x-f,y:a.y-p})}),[...i,...o.reverse()]}function ii(t,e,n,s){const i=e.length;if(i<2)return;const o=oe(e,n,s),r=a=>n+(s-n)*a/(i-1);t.beginPath(),t.moveTo(o[0].x,o[0].y);for(const a of o.slice(1))t.lineTo(a.x,a.y);t.closePath(),t.fill(),e.forEach((a,l)=>{l!==0&&l!==i-1&&i>3||(t.beginPath(),t.arc(a.x,a.y,r(l)/2,0,Math.PI*2),t.fill())})}function Ye(t,e,n,s,i=16){const o={x:2*e.x-(t.x+n.x)/2,y:2*e.y-(t.y+n.y)/2},r=[];for(let a=0;a<=i;a++){const l=a/i,c=l<.5?{x:t.x+(e.x-t.x)*2*l,y:t.y+(e.y-t.y)*2*l}:{x:e.x+(n.x-e.x)*(2*l-1),y:e.y+(n.y-e.y)*(2*l-1)},h=1-l,u={x:h*h*t.x+2*h*l*o.x+l*l*n.x,y:h*h*t.y+2*h*l*o.y+l*l*n.y};r.push({x:c.x+(u.x-c.x)*s,y:c.y+(u.y-c.y)*s})}return r}function pr(t,e,n,s,i,o=0,r=1,a=40){const l=Math.cos(i),c=Math.sin(i);return Array.from({length:a+1},(h,u)=>{const d=o+Math.PI*2*r*u/a,f=Math.cos(d)*n,p=Math.sin(d)*s;return{x:t+f*l-p*c,y:e+f*c+p*l}})}function Zn(t,e){return e.look==="pencil"?C1(t,e):I1(t,e.ink,e.look)}function oi(t,e,n=!1){t.beginPath(),t.moveTo(e[0].x,e[0].y);for(const s of e.slice(1))t.lineTo(s.x,s.y);n&&t.closePath()}function I1(t,e,n){const s=n==="silhouette",i=s?1.25:1;return{look:n,ink:e,limb(o,r,a){t.fillStyle=e,ii(t,o,r*i,a*i)},line(o,r){o.length<2||(t.strokeStyle=e,t.lineWidth=r*i,t.lineCap="round",t.lineJoin="round",oi(t,o),t.stroke())},shape(o,r,a){oi(t,o,!0),(r!==null||s)&&(t.fillStyle=s?e:r,t.fill()),!(a<=0)&&(t.strokeStyle=e,t.lineWidth=a*i,t.lineJoin="round",t.stroke())},ellipse(o,r,a,l,c,h,u){t.beginPath(),t.ellipse(o,r,a,l,c,0,Math.PI*2),(h!==null||s)&&(t.fillStyle=s?e:h,t.fill()),!(u<=0)&&(t.strokeStyle=e,t.lineWidth=u*i,t.stroke())},dot(o,r,a){t.fillStyle=e,t.beginPath(),t.arc(o,r,a*i,0,Math.PI*2),t.fill()},guide(){},guideEllipse(){}}}function O1(t,e){const n=[t[0]];let s=0;for(let r=1;r<t.length;r++){const a=t[r-1],l=t[r],c=Math.hypot(l.x-a.x,l.y-a.y);let h=e-s;for(;h<c;){const u=h/c;n.push({x:a.x+(l.x-a.x)*u,y:a.y+(l.y-a.y)*u}),h+=e}s=c-(h-e)}const i=t[t.length-1],o=n[n.length-1];return Math.hypot(i.x-o.x,i.y-o.y)>e*.25?n.push(i):n[n.length-1]=i,n}function _1(t,e){const n=t.length;return t.map((s,i)=>{const o=t[Math.max(0,i-1)],r=t[Math.min(n-1,i+1)],a=Math.hypot(r.x-o.x,r.y-o.y)||1,l=e(n===1?0:i/(n-1));return{x:s.x-(r.y-o.y)/a*l,y:s.y+(r.x-o.x)/a*l}})}function Dh(t){const e=[.6,1.4,2.9].map(s=>({frequency:s*(.8+t.next()*.4),phase:t.next()*Math.PI*2,amount:.5+t.next()*.5})),n=e.reduce((s,i)=>s+i.amount,0);return s=>e.reduce((i,o)=>i+o.amount*Math.sin(Math.PI*2*o.frequency*s+o.phase),0)/n}function C1(t,e){const n=e.pencil??{},s=e.ink,i=n.roughness??Math.max(1,e.lineWidth*.12),o=Math.max(1,Math.round(n.passes??2)),r=Math.min(1,Math.max(0,n.pressure??.25)),a=Math.min(1,Math.max(0,n.rubbedOut??.15)),l=gr(e.time,n.boil??8);let c=0;const h=(p,g,m=!1)=>Ne(zt(`${e.seed}:${m?"paper":l}:${p}:${g}`)),u=(p,g,m,y,T,k=0)=>{if(p.length<2)return;const b=p.slice(1).reduce((v,$,_)=>v+Math.hypot($.x-p[_].x,$.y-p[_].y),0);let A=O1(p,Math.max(1.5,Math.min(e.lineWidth*.8,b/24)));if(k>0&&A.length>=2){const[v,$]=[A[A.length-2],A[A.length-1]],_=Math.hypot($.x-v.x,$.y-v.y)||1;A=[...A,{x:$.x+($.x-v.x)/_*k,y:$.y+($.y-v.y)/_*k}]}const M=Dh(m),E=Dh(m),x=A.length,S=[],I=[];A.forEach((v,$)=>{const _=x===1?0:$/(x-1),P=A[Math.max(0,$-1)],C=A[Math.min(x-1,$+1)],F=Math.hypot(C.x-P.x,C.y-P.y)||1,R=-(C.y-P.y)/F,B=(C.x-P.x)/F,j=M(_)*T,H=Math.min(1,_/.08,(1-_)/.08),N=(.55+.45*Math.sqrt(Math.max(0,H)))*(1+r*E(_)),D=Math.max(.3,g(_)*N/2),O=v.x+R*j,L=v.y+B*j;S.push({x:O+R*D,y:L+B*D}),I.push({x:O-R*D,y:L-B*D})}),t.save(),t.globalAlpha*=y,t.fillStyle=s,oi(t,[...S,...I.reverse()],!0),t.fill(),t.restore()},d=(p,g)=>{const m=c++,y=h(m,99,!0);if(y.next()<a){const A=(y.next()*2-1)*e.lineWidth*1.4,M=(y.next()*2-1)*e.lineWidth*1.4,E=p.map(x=>({x:x.x+A,y:x.y+M}));u(E,x=>g(x)*1.8,h(m,98,!0),.035,i),u(E,x=>g(x)*.45,h(m,97,!0),.12,i*1.5)}const T=p.slice(1).reduce((A,M,E)=>A+Math.hypot(M.x-p[E].x,M.y-p[E].y),0),k=g(.5)>4&&T>g(.5)*6,b=k?[-.3,.3,0]:[0];for(let A=0;A<o;A++){const M=A===0;b.forEach((E,x)=>{const S=h(m,A*10+x),I=E===0?p:_1(p,$=>g($)*E*Math.sqrt(Math.sin(Math.PI*$))),v=!M&&E===0?e.lineWidth*(.3+S.next()*.8):0;u(I,$=>g($)*(k?.5:1)*(M?1:.6),S,M?.85:.45,i*(M?.6:1),v)})}},f=(p,g,m,y,T,k)=>{const A=h(c,50).next()*Math.PI*2;d(pr(p,g,m,y,T,A,1.08,48),()=>k)};return{look:"pencil",ink:s,limb(p,g,m){d(p,y=>g+(m-g)*y)},line(p,g){d(p,()=>g)},shape(p,g,m){g!==null&&(t.save(),t.globalAlpha*=.88,t.fillStyle=g,oi(t,p,!0),t.fill(),t.restore()),m>0&&d([...p,p[0]],()=>m)},ellipse(p,g,m,y,T,k,b){k!==null&&(t.save(),t.globalAlpha*=.9,t.fillStyle=k,t.beginPath(),t.ellipse(p,g,m,y,T,0,Math.PI*2),t.fill(),t.restore()),f(p,g,m,y,T,b)},dot(p,g,m){t.save(),t.globalAlpha*=.9,t.fillStyle=s,t.beginPath(),t.arc(p,g,m,0,Math.PI*2),t.fill(),t.restore()},guide(p){if(n.construction===!1||p.length<2)return;const g=c++;u(p,()=>Math.max(.6,e.lineWidth*.18),h(g,0),.28,i*1.2,e.lineWidth)},guideEllipse(p,g,m,y,T){if(n.construction===!1)return;const k=c++,b=h(k,0),A=pr(p,g,m,y,T,b.next()*Math.PI*2,1.12,48);u(A,()=>Math.max(.6,e.lineWidth*.18),b,.28,i*1.5)}}}const Wh=["thumb","index","middle","ring","pinky"],Et={"thumb.curl":.15,"thumb.across":.15,"index.curl":.12,"middle.curl":.16,"ring.curl":.2,"pinky.curl":.25,spread:.25,turn:0,bend:0,tilt:0,roll:0};function At(t={}){return{...Et,...t}}const Bt=(t,e,n,s,i)=>({"thumb.curl":t,"index.curl":e,"middle.curl":n,"ring.curl":s,"pinky.curl":i}),$t={relaxed:Et,open:At({...Bt(0,0,0,0,0),"thumb.across":0,spread:.55}),spread:At({...Bt(0,0,0,0,0),"thumb.across":0,spread:1}),flat:At({...Bt(0,0,0,0,0),"thumb.across":.35,spread:0}),fist:At({...Bt(.7,1,1,1,1),"thumb.across":.9,spread:0}),point:At({...Bt(.75,0,1,1,1),"thumb.across":.9,spread:0}),thumbsUp:At({...Bt(0,1,1,1,1),"thumb.across":0,spread:0,roll:70}),peace:At({...Bt(.75,0,0,1,1),"thumb.across":.9,spread:1}),ok:At({...Bt(.12,.6,.1,.15,.2),"thumb.across":.55,spread:.6}),pinch:At({...Bt(.1,.65,.75,.85,.9),"thumb.across":.55,spread:0}),cupped:At({...Bt(.25,.4,.4,.4,.4),"thumb.across":.4,spread:.05,turn:2}),wave:At({...Bt(0,.05,.05,.1,.12),"thumb.across":0,spread:.7,turn:2}),pencilGrip:At({...Bt(.1,.6,.72,.88,.95),"thumb.across":.5,spread:0,turn:.8,bend:10}),hold:At({...Bt(.5,.7,.72,.74,.76),"thumb.across":.75,spread:0,turn:1})};function wn(t,e,n){const s={...t};for(const[i,o]of Object.entries(e)){const r=t[i]??o;s[i]=r+(o-r)*n}return s}const H1={index:{knuckle:[-.16,.47,-.02],bones:[.2,.125,.1],width:.125,fan:-1},middle:{knuckle:[-.055,.49,-.02],bones:[.22,.135,.1],width:.13,fan:-.2},ring:{knuckle:[.05,.475,-.02],bones:[.2,.125,.1],width:.122,fan:.55},pinky:{knuckle:[.15,.43,-.02],bones:[.16,.1,.085],width:.108,fan:1.25}},R1={index:{knuckle:[-.14,.47,-.02],bones:[.2,.125,.1],width:.15,fan:-1},middle:{knuckle:[0,.49,-.02],bones:[.22,.135,.1],width:.155,fan:0},pinky:{knuckle:[.14,.45,-.02],bones:[.19,.115,.095],width:.145,fan:1}},ce={base:[-.11,.1,-.05],bones:[.2,.15,.12],widths:[.2,.145,.135],out:[-.7,.68,-.22],across:[.35,.5,-.8]},L1=[82,100,62],F1=[48,72],N1=3,D1=13,W1=.035,B1=-.075,j1=[[-.17,0],[-.215,.12],[-.235,.26],[-.225,.4],[-.185,.49],[-.075,.525],[.05,.51],[.16,.465],[.215,.4],[.225,.26],[.2,.1],[.16,0]],Se=t=>t*Math.PI/180,mr=(t,e)=>[t[0]+e[0],t[1]+e[1],t[2]+e[2]],ri=(t,e)=>[t[0]*e,t[1]*e,t[2]*e],yr=(t,e)=>[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]],Qn=t=>{const e=Math.hypot(t[0],t[1],t[2])||1;return[t[0]/e,t[1]/e,t[2]/e]};function Te(t,e,n){const s=Math.cos(n),i=Math.sin(n),o=yr(e,t),r=e[0]*t[0]+e[1]*t[1]+e[2]*t[2];return[t[0]*s+o[0]*i+e[0]*r*(1-s),t[1]*s+o[1]*i+e[1]*r*(1-s),t[2]*s+o[2]*i+e[2]*r*(1-s)]}const Bh=[1,0,0],jh=[0,1,0],ts=[0,0,1];function q1(t,e,n){const s=Se(t.fan*(N1+D1*n)),i=[Math.sin(s),Math.cos(s),0],o=[Math.cos(s),-Math.sin(s),0],r=[t.knuckle];let a=0;t.bones.forEach((h,u)=>{a+=Se(L1[u]*e),r.push(mr(r[u],ri(Te(i,o,-a),h)))});const l=Te(ts,o,-a),c=r.map((h,u)=>t.width*(1-.14*(u/(r.length-1))));return{joints:r,back:l,widths:c}}function Y1(t,e,n=1,s=1){const i=Math.min(1,Math.max(0,e)),o=Qn(mr(ri(Qn(ce.out),1-i),ri(Qn(ce.across),i))),r=Qn(yr(ts,o)),a=Qn(yr(o,r)),l=[[ce.base[0]*s,ce.base[1],ce.base[2]]];let c=0;ce.bones.forEach((d,f)=>{f>0&&(c+=Se(F1[f-1]*t)),l.push(mr(l[f],ri(Te(o,r,c),d)))});const h=Te(a,r,c),u=[...ce.widths,ce.widths[ce.widths.length-1]*.92].map(d=>d*n);return{joints:l,back:h,widths:u}}function ai(t,e={}){const n={...Et,...t},s=e.size??100,i=e.side??"right",o=i==="left"?-1:1,r=Se(e.angle??0),a=e.fingers===4,l=Math.max(.5,e.plump??1),c=1+(l-1)*.7,h=$=>({...$,knuckle:[$.knuckle[0]*c,$.knuckle[1],$.knuckle[2]],width:$.width*l}),u=Se(n.bend??0),d=Se(n.tilt??0),f=Se(90*(n.turn??0)),p=$=>Te(Te(Te($,Bh,-u),ts,-d),jh,f),g=Math.cos(r),m=Math.sin(r),y=Se(n.roll??0),T=Math.cos(y),k=Math.sin(y),b=$=>{const _=$[0]*s,P=-$[1]*s,C=(_*T-P*k)*o,F=_*k+P*T;return{x:C*g-F*m,y:C*m+F*g}},A=$=>{const _=b($),P=Math.hypot(_.x,_.y);return P>1e-6*s?{x:_.x/P,y:_.y/P}:{x:0,y:0}},M={thumb:Y1(n["thumb.curl"]??0,n["thumb.across"]??0,l,c)},E=a?R1:H1;for(const $ of Wh){const _=E[$];_&&(M[$]=q1(h(_),n[`${$}.curl`]??0,n.spread??0))}const x={};for(const[$,_]of Object.entries(M)){const P=_.joints.map(p),C=p(_.back);x[$]={points:P.map(b),depths:P.map(F=>F[2]*s),widths:_.widths.map(F=>F*s),nail:C[2],back:A(C)}}const S=j1.flatMap(([$,_])=>[p([$*c,_,W1]),p([$*c,_,B1])]),I=K1(S.map(b)),v=S.reduce(($,_)=>$+_[2],0)/S.length*s;return{size:s,side:i,wrist:{x:0,y:0},palm:I,palmDepth:v,palmFacing:-p(ts)[2],fingers:x,axes:{up:A(p(jh)),across:A(p(Bh)),out:A(p(ts))},curls:Object.fromEntries(Object.keys(x).map($=>[$,n[`${$}.curl`]??0]))}}function qh(t,e){const n=i=>({x:i.x+e.x-t.wrist.x,y:i.y+e.y-t.wrist.y}),s={};for(const[i,o]of Object.entries(t.fingers))s[i]={...o,points:o.points.map(n)};return{...t,wrist:n(t.wrist),palm:t.palm.map(n),fingers:s}}function K1(t){const e=[...t].sort((o,r)=>o.x-r.x||o.y-r.y);if(e.length<3)return e;const n=(o,r,a)=>(r.x-o.x)*(a.y-o.y)-(r.y-o.y)*(a.x-o.x),s=[];for(const o of e){for(;s.length>=2&&n(s[s.length-2],s[s.length-1],o)<=0;)s.pop();s.push(o)}const i=[];for(const o of[...e].reverse()){for(;i.length>=2&&n(i[i.length-2],i[i.length-1],o)<=0;)i.pop();i.push(o)}return[...s.slice(0,-1),...i.slice(0,-1)]}const z1="#f1c9a5",X1="#2f2f33";function li(t,e,n,s={},i=0){const o=qh(ai(n,s),e),r=s.ink??X1,a=s.lineWidth??o.size*.035,l=s.pen??Zn(t,{look:s.look??"clean",ink:r,lineWidth:a,seed:s.seed??1,time:i,pencil:{construction:!1,...s.pencil}}),c=s.skin??z1,h=s.nails??!0,u=[{depth:o.palmDepth,draw:()=>G1(l,o,c,a)}];for(const d of Object.values(o.fingers)){const f=d.depths.reduce((p,g)=>p+g,0)/d.depths.length;u.push({depth:f,draw:()=>U1(t,l,d,c,a,h)})}if(s.prop){const d=s.prop;u.push({depth:d.depth,draw:()=>d.draw(l)})}t.save(),t.lineCap="round",t.lineJoin="round";for(const d of[...u].sort((f,p)=>f.depth-p.depth))d.draw();return t.restore(),o}function G1(t,e,n,s){if(t.shape(e.palm,n,s),e.palmFacing<-.3&&t.look!=="silhouette"){const{up:i}=e.axes;for(const[o,r]of Object.entries(e.fingers)){const a=e.curls[o]??0;if(o==="thumb"||a<.5)continue;const l=r.points[0],c=r.widths[0]*.42,h={x:l.x-i.x*c*.2,y:l.y-i.y*c*.2},u=Math.atan2(i.y,i.x),d=Array.from({length:7},(f,p)=>{const g=u-Math.PI/2+Math.PI*p/6;return{x:h.x+Math.cos(g)*c,y:h.y+Math.sin(g)*c}});t.line(d,s*.6)}}if(e.palmFacing>.45&&t.look!=="silhouette"){const{up:i,across:o}=e.axes,r=e.size,a=e.wrist,l=(h,u)=>({x:a.x+(o.x*h+i.x*u)*r,y:a.y+(o.y*h+i.y*u)*r}),c=e.side==="left"?-1:1;t.line([l(-.15*c,.36),l(-.04*c,.3),l(.1*c,.33)],s*.5)}}function U1(t,e,n,s,i,o){const{widths:r}=n,a=V1(n.points,2),l=n.points[0],c=a[a.length-1],h=r[0],u=r[r.length-1];if(t.save(),e.look!=="silhouette"){t.beginPath(),t.rect(l.x-1e5,l.y-1e5,2e5,2e5);const g=h/2+i*1.6;t.moveTo(l.x+g,l.y),t.arc(l.x,l.y,g,0,Math.PI*2),t.clip("evenodd")}if(e.limb(a,h+2*i,u+2*i),t.restore(),e.look!=="silhouette"&&(t.fillStyle=s,ii(t,a,h,u)),e.look==="silhouette"||!o||n.nail<.25)return;const d=a[a.length-2],f=J1({x:c.x-d.x,y:c.y-d.y})??{x:0,y:-1},p={x:c.x-f.x*u*.22+n.back.x*u*.1,y:c.y-f.y*u*.22+n.back.y*u*.1};e.ellipse(p.x,p.y,u*.24*Math.max(.35,n.nail),u*.19,Math.atan2(f.y,f.x),"#f8e3d3",i*.45)}function V1(t,e){let n=t;for(let s=0;s<e;s++){if(n.length<3)return n;const i=[n[0]];for(let o=0;o<n.length-1;o++){const r=n[o],a=n[o+1];o>0&&i.push({x:r.x*.75+a.x*.25,y:r.y*.75+a.y*.25}),o<n.length-2&&i.push({x:r.x*.25+a.x*.75,y:r.y*.25+a.y*.75})}i.push(n[n.length-1]),n=i}return n}const J1=t=>{const e=Math.hypot(t.x,t.y);return e>1e-6?{x:t.x/e,y:t.y/e}:null},Ht={walk:{swing:24,knee:30,arm:22,elbow:28,lean:4},bouncy:{swing:26,knee:45,arm:34,elbow:30,lean:2,bend:-4,bounce:.035,squash:.06},doubleBounce:{swing:22,knee:40,arm:26,elbow:24,lean:3,bounce:.02,bounces:2,squash:.04},sneak:{swing:28,knee:70,arm:6,elbow:0,forearm:110,shoulder:55,lean:16,bend:14,headTilt:-8,crouch:50,tiptoe:25},strut:{swing:26,knee:30,arm:30,elbow:20,lean:-4,bend:-10,headTilt:-6,sway:4,bounce:.01},tired:{swing:14,knee:14,arm:6,elbow:6,lean:10,bend:16,headTilt:12},run:{swing:40,knee:95,arm:45,elbow:0,forearm:90,lean:16,bend:6,bounce:.05,squash:.06},shove:{swing:18,knee:28,arm:0,elbow:0,lean:0}},Z1=40;function es(t){return t===void 0?Ht.walk:typeof t=="string"?Ht[t]??Ht.walk:t}function Yh(t,e,n=et,s=1){const i=es(t);if(i===Ht.walk)return Uh(e,n,s);const o=e*Math.PI*2,r=Math.sin(o)*s,a=Math.cos(o)*s,l=y=>Math.abs(y)<=Z1,c=i.shoulder??0,h=(y,T)=>l(y)?T*c+i.arm*r:y,u=i.forearm??0,d=l(n.leftShoulder)?n.leftElbow-u-i.elbow*Math.max(0,-r):n.leftElbow,f=l(n.rightShoulder)?n.rightElbow+u+i.elbow*Math.max(0,r):n.rightElbow,p=i.bounces??1,g=(1+Math.cos(o*2*p))/2,m=i.crouch??0;return{...n,lean:n.lean+i.lean*s+(i.sway??0)*Math.sin(o)*(1-(n.turn??0)),bend:(n.bend??0)+(i.bend??0),headTilt:n.headTilt-i.lean*.5*s+(i.headTilt??0),leftElbow:d,rightElbow:f,leftHip:-i.swing*r-m*.5,rightHip:-i.swing*r+m*.5,leftKnee:-i.knee*Math.max(0,a)-m,rightKnee:i.knee*Math.max(0,-a)+m,leftAnkle:(n.leftAnkle??0)+(i.tiptoe??0),rightAnkle:(n.rightAnkle??0)+(i.tiptoe??0),leftShoulder:h(n.leftShoulder,-1),rightShoulder:h(n.rightShoulder,1),rise:(n.rise??0)+(i.bounce??0)*s*g,stretch:n.stretch*(1+(i.squash??0)*(g-.5))}}function br(t,e,n=1){const s=es(t),i=Ht.walk.swing,o=r=>Math.sin(r*Math.PI/180);return Vh(e,n)*o(s.swing*n)/o(i*n)}const et={lean:0,bend:0,headTilt:0,leftShoulder:18,rightShoulder:18,leftElbow:-6,rightElbow:-6,leftHip:8,rightHip:8,leftKnee:0,rightKnee:0,leftWrist:0,rightWrist:0,leftAnkle:0,rightAnkle:0,leftFootOut:0,rightFootOut:0,mouth:0,smile:.6,mouthWidth:1,blink:0,leftEye:1,rightEye:1,leftBrow:0,rightBrow:0,browTilt:0,lookX:0,lookY:0,stretch:1,turn:0,sit:0,spin:0,rise:0};function Pt(t){return{...et,...t}}const Kh={mouth:0,smile:0,mouthWidth:1,leftEye:1,rightEye:1,leftBrow:0,rightBrow:0,browTilt:0,lookX:0,lookY:0},_t=t=>({...Kh,...t}),ct={neutral:Kh,happy:_t({smile:.9,leftBrow:.2,rightBrow:.2}),joyful:_t({mouth:.6,smile:1,mouthWidth:1.2,leftEye:0,rightEye:0,leftBrow:.4,rightBrow:.4}),sad:_t({smile:-.8,leftEye:.8,rightEye:.8,browTilt:.9,leftBrow:-.1,rightBrow:-.1,lookY:.6}),crying:_t({mouth:.45,smile:-1,leftEye:0,rightEye:0,browTilt:1,lookY:.4}),surprised:_t({mouth:.7,mouthWidth:.7,leftEye:1.5,rightEye:1.5,leftBrow:1,rightBrow:1}),shocked:_t({mouth:1,mouthWidth:.8,leftEye:1.6,rightEye:1.6,leftBrow:1,rightBrow:1,browTilt:.4}),angry:_t({smile:-.6,mouthWidth:.9,leftEye:.8,rightEye:.8,leftBrow:-.6,rightBrow:-.6,browTilt:-1}),furious:_t({mouth:.5,smile:-1,mouthWidth:1.3,leftEye:.9,rightEye:.9,leftBrow:-.9,rightBrow:-.9,browTilt:-1}),worried:_t({smile:-.3,mouthWidth:.8,leftEye:1.1,rightEye:1.1,leftBrow:.3,rightBrow:.3,browTilt:.8,lookX:-.5}),scared:_t({mouth:.35,smile:-.5,mouthWidth:.8,leftEye:1.45,rightEye:1.45,leftBrow:.8,rightBrow:.8,browTilt:.9}),confused:_t({smile:-.2,mouthWidth:.8,leftEye:.9,rightEye:1.15,leftBrow:-.3,rightBrow:.8,lookX:.5,lookY:-.4}),skeptical:_t({smile:-.1,leftEye:.6,rightEye:1,leftBrow:-.4,rightBrow:.7,lookX:.4}),thinking:_t({smile:0,mouthWidth:.7,leftBrow:.3,rightBrow:.5,lookX:.6,lookY:-.8}),sleepy:_t({smile:.1,leftEye:.25,rightEye:.25,leftBrow:-.3,rightBrow:-.3,lookY:.5}),disgusted:_t({smile:-.7,mouthWidth:.9,leftEye:.6,rightEye:.75,leftBrow:-.5,rightBrow:-.2,browTilt:-.4,lookX:-.6}),smug:_t({smile:.6,mouthWidth:.9,leftEye:.6,rightEye:.6,leftBrow:.1,rightBrow:.5,lookX:.5}),wink:_t({smile:.9,leftEye:0,rightEye:1,leftBrow:-.2,rightBrow:.3})};function Ee(t,e){return{...t,...typeof e=="string"?ct[e]:e}}const jt={rest:et,wave:Pt({rightShoulder:135,rightElbow:30,headTilt:6,...ct.happy}),cheer:Pt({leftShoulder:125,leftElbow:20,rightShoulder:125,rightElbow:20,...ct.joyful}),shrug:Pt({leftShoulder:30,leftElbow:85,rightShoulder:30,rightElbow:85,headTilt:-10,...ct.confused,lookX:0,lookY:0}),point:Pt({rightShoulder:90,rightElbow:0,lean:4,smile:.4}),think:Pt({rightShoulder:60,rightElbow:150,headTilt:10,...ct.thinking}),handsOnHips:Pt({leftShoulder:45,leftElbow:-100,rightShoulder:45,rightElbow:-100,leftHip:14,rightHip:14,smile:.8}),sad:Pt({leftShoulder:14,rightShoulder:14,leftElbow:-4,rightElbow:-4,headTilt:-14,lean:-3,...ct.sad}),surprised:Pt({leftShoulder:70,leftElbow:60,rightShoulder:70,rightElbow:60,...ct.surprised}),crouch:Pt({stretch:.72,leftShoulder:35,rightShoulder:35,leftElbow:-50,rightElbow:-50,leftHip:22,rightHip:22,headTilt:-4}),sit:Pt({sit:1,turn:.5,leftShoulder:-25,rightShoulder:25,leftElbow:-55,rightElbow:55}),jump:Pt({stretch:1.22,leftShoulder:140,rightShoulder:140,leftElbow:20,rightElbow:20,leftHip:4,rightHip:4,...ct.joyful}),duck:Pt({stretch:.62,bend:28,headTilt:-8,leftShoulder:150,rightShoulder:150,leftElbow:130,rightElbow:130,leftHip:25,rightHip:25,...ct.scared}),lie:Pt({spin:-90,rise:-.42,leftShoulder:165,rightShoulder:165,leftElbow:150,rightElbow:150,...ct.sleepy}),sideSplit:Pt({leftHip:90,rightHip:90,leftAnkle:-45,rightAnkle:-45,leftShoulder:120,rightShoulder:120,leftElbow:10,rightElbow:10,...ct.happy}),frontSplit:Pt({turn:1,leftHip:-90,rightHip:-90,leftAnkle:-45,rightAnkle:-45,leftShoulder:-150,rightShoulder:150,leftElbow:10,rightElbow:-10,...ct.happy})},zh=Object.keys(et);function kn(t,e,n){const s={...t};for(const i of zh)s[i]=t[i]+(e[i]-t[i])*n;return s}const wr=24,Xh=4,Gh=28,Q1=40;function Uh(t,e=et,n=1){const s=Math.sin(t*Math.PI*2)*n,i=Math.cos(t*Math.PI*2)*n,o=c=>Math.abs(c)<=Q1,r=c=>o(c)?22*s:c,a=o(e.leftShoulder)?e.leftElbow-Gh*Math.max(0,-s):e.leftElbow,l=o(e.rightShoulder)?e.rightElbow+Gh*Math.max(0,s):e.rightElbow;return{...e,lean:e.lean+Xh*n,headTilt:e.headTilt-Xh*.5*n,leftElbow:a,rightElbow:l,leftHip:-wr*s,rightHip:-wr*s,leftKnee:-30*Math.max(0,i),rightKnee:30*Math.max(0,-i),leftShoulder:r(e.leftShoulder),rightShoulder:r(e.rightShoulder)}}function Vh(t,e=1){return 4*((kr+ci)*t)*Math.sin(wr*e*Math.PI/180)}function Jh(t){const e=Math.abs(Math.sin(t/65)),n=.55+.45*Math.sin(t/310);return e*n}const Zh=.12,Qh=.46,ty=1-2*Zh,ey=.1,ny=.21,sy=.19,kr=.24,ci=.22,tu=.12,iy=.14,eu=.33,nu=.7,su=.3,oy=.35,ry=[1.7,1.05],ay=[1.3,.75],iu=[1.45,.85],ly=[1.15,.75],ou=.06,cy=.7,hy=.65,ru=.075,uy=.3,dy=.02,fy=.012,gy=12,py=.25,hi=90,my=.25,yy=.04,au=.01,Ke=t=>Math.min(1,Math.max(0,t??0));function by(t,e=1){return ci*t*e}const vr=-.12,lu=.4,Xt=t=>t*Math.PI/180,wy=(t,e)=>({x:e*Math.sin(Xt(t)),y:Math.cos(Xt(t))}),cu=(t,e)=>Math.max(0,t)*(1-Math.min(1,Math.max(0,e))),hu=(t,e,n,s)=>t-.3*e-n*.14*e-Math.max(0,s-1)*.12*e;function ky(t,e,n,s,i,o){const r=Math.max(1,Math.min(o*.6,iy*n)),a=Ke(e.turn),l=(tu+eu*a)*n,c=s+vr*n,h=l+e.lookX*.08*n,u=e.lookY*.07*n,d=[{x:-.34*n*(1-nu*a),squeeze:1-nu*a,open:e.leftEye,brow:e.leftBrow,side:-1},{x:.34*n*(1-su*a),squeeze:1-su*a,open:e.rightEye,brow:e.rightBrow,side:1}];t.fillStyle=i,t.strokeStyle=i,t.lineWidth=r;for(const y of d){const T=cu(y.open,e.blink);if(T<.2){const M=e.smile>.5?-.12*n:.06*n;t.beginPath(),t.moveTo(y.x+l-.12*n,c),t.quadraticCurveTo(y.x+l,c+M,y.x+l+.12*n,c),t.stroke()}else{if(T>1.2){const E=.13*n*T;t.beginPath(),t.ellipse(y.x+l,c,E*.85,E,0,0,Math.PI*2),t.fillStyle="#ffffff",t.fill(),t.stroke(),t.fillStyle=i}const M=T>1.2?.075*n:.1*n;t.beginPath(),t.ellipse(y.x+h,c+u,M,M*1.1*Math.min(T,1),0,0,Math.PI*2),t.fill()}const k=hu(c,n,y.brow,T),b=y.x+l-y.side*.13*n*y.squeeze,A=y.x+l+y.side*.13*n*y.squeeze;t.beginPath(),t.moveTo(A,k),t.lineTo(b,k-e.browTilt*.1*n),t.stroke()}const f=s+lu*n,p=.25*n*Math.max(.3,e.mouthWidth)*(1-oy*a),g=Math.min(1,Math.max(0,e.mouth));if(t.beginPath(),g<=.05){t.moveTo(l-p,f),t.quadraticCurveTo(l,f+e.smile*.25*n,l+p,f),t.stroke();return}const m=.3*n*g;e.smile>.3?(t.moveTo(l-p,f-.05*n),t.lineTo(l+p,f-.05*n),t.quadraticCurveTo(l,f+m*2,l-p,f-.05*n)):e.smile<-.3?(t.moveTo(l-p,f+m*.6),t.lineTo(l+p,f+m*.6),t.quadraticCurveTo(l,f-m*1.4,l-p,f+m*.6)):t.ellipse(l,f,p*.8,m,0,0,Math.PI*2),t.fill()}function uu(t,e){const n=e.height??300,s=Math.min(3,Math.max(.3,t.stretch??1)),i=Math.sqrt(s),o=(e.headSize??2*Zh)/2,r=e.headSize===void 0?ty:1-2*o,a=o*n,l=Ke(t.sit),c=t.leftHip+(-hi-t.leftHip)*l,h=t.leftKnee+(-hi-t.leftKnee)*l,u=t.rightHip+(hi-t.rightHip)*l,d=t.rightKnee+(hi-t.rightKnee)*l,f=e.classic===!0,p=Ke(t.turn),g=(B,j,H,N,D)=>{const O=Math.max(-Math.PI/2,Math.min(Math.PI/2,Math.abs(Xt(j-H)/2)+Xt(N))),L=Math.max(-1,Math.min(1,cy+D)),q=p+(1-p)*B*L;return f?{x:0,y:0}:{x:Math.cos(O)*ou*q,y:Math.sin(O)*ou}},m={left:t.leftAnkle??0,right:t.rightAnkle??0},y={left:t.leftFootOut??0,right:t.rightFootOut??0};let T=0;if(l>0||!f){const B=(D,O,L,q,G)=>kr*Math.cos(Xt(O))+ci*Math.cos(Xt(O-L))+Math.max(0,g(D,O,L,q,G).y),j=Math.max(B(-1,c,h,m.left,y.left),B(1,u,d,m.right,y.right)),H=1-Ke((t.rise??0)/yy),N=(f?Math.min(1,l/my):1)*H;T=(Qh-j)*N*n*s}const k=-Qh*n*s+T,b=-r*n*s+T,A=f?0:(dy*Ke(t.turn)+fy*l)*n*s,M=Xt(t.bend??0),E={end:fu(k,b,M,1),bend:M};let x;if(M!==0){x=[];for(let B=0;B<=du;B++){const j=B/du,H=fu(k,b,M,j);x.push({x:H.x-A*Math.sin(Math.PI*j),y:H.y})}}else x=A===0?[{x:0,y:k},{x:0,y:b}]:Ye({x:0,y:k},{x:-A,y:(k+b)/2},{x:0,y:b},1,8);const S=b+ey*n*s,I=(e.shoulderWidth??0)*n*Math.cos(p*Math.PI/2),v=(B,j,H,N,D)=>{const O=wy(H,N);return{x:B+O.x*D*n,y:j+O.y*D*n}},$=(B,j,H)=>{const N=v(0,k,j,B,kr*s);return{root:{x:0,y:k},joint:N,end:v(N.x,N.y,j-H,B,ci*s)}},_=(B,j,H)=>{const N={x:B*I,y:S},D=v(N.x,N.y,j,B,ny*i);return{root:N,joint:D,end:v(D.x,D.y,j+H,B,sy*i)}},P={left:$(-1,c,h),right:$(1,u,d)},C=(B,j,H,N,D,O)=>{const L=g(B,H,N,D,O);return{x:j.end.x+L.x*n*s,y:j.end.y+L.y*n*s}},F=(B,j,H,N,D)=>v(j.end.x,j.end.y,H+N+D,B,ru*i),R={left:_(-1,t.leftShoulder,t.leftElbow),right:_(1,t.rightShoulder,t.rightElbow)};return{height:n,facing:(e.facing??1)<0?-1:1,stretch:s,lineWidth:e.lineWidth??n*.025,rubber:Math.min(1,Math.max(f?0:uy,e.rubber??0)),r:a,headRx:a/Math.sqrt(s),headRy:a*Math.sqrt(s),hipY:k,neckY:b,drop:T,lean:f?t.lean:t.lean+gy*Math.sin(Math.PI*l),classic:f,legs:P,toes:{left:C(-1,P.left,c,h,m.left,y.left),right:C(1,P.right,u,d,m.right,y.right)},spine:x,chest:E,arms:R,handTips:{left:F(-1,R.left,t.leftShoulder,t.leftElbow,t.leftWrist??0),right:F(1,R.right,t.rightShoulder,t.rightElbow,t.rightWrist??0)}}}const du=10;function fu(t,e,n,s){const i=t-e,o=n*s;if(Math.abs(n)<1e-9)return{x:0,y:t-i*s};const r=i/n;return{x:r*(1-Math.cos(o)),y:t-r*Math.sin(o)}}function vy(t,e){if(t.chest.bend===0)return e;const n=ss(e,{x:0,y:t.neckY},t.chest.bend);return{x:n.x+t.chest.end.x,y:n.y+t.chest.end.y-t.neckY}}const ns=(t,e)=>e===0?[t.root,t.joint,t.end]:Ye(t.root,t.joint,t.end,e);function ss(t,e,n){const s=Math.cos(n),i=Math.sin(n),o=t.x-e.x,r=t.y-e.y;return{x:e.x+o*s-r*i,y:e.y+o*i+r*s}}function gu(t,e,n=!0){const s=Sy(t,e),i=e.spin??0,o=e.rise??0;return n&&(i!==0||o!==0)?My(s,t,i,o):s}function pu(t,e,n){return{pivot:{x:0,y:t.hipY},angle:t.facing*Xt(e),lift:n*t.height}}function My(t,e,n,s){const{pivot:i,angle:o,lift:r}=pu(e,n,s),a=d=>{const f=ss(d,i,o);return{x:f.x,y:f.y-r}},l=d=>({left:a(d.left),right:a(d.right)}),c={left:Math.max(a(t.feet.left).y,a(t.toes.left).y),right:Math.max(a(t.feet.right).y,a(t.toes.right).y)},h=Math.max(c.left,c.right),u=au*e.height;return{...t,hip:a(t.hip),neck:a(t.neck),shoulders:l(t.shoulders),elbows:l(t.elbows),hands:l(t.hands),fingertips:l(t.fingertips),knees:l(t.knees),feet:l(t.feet),toes:l(t.toes),feetY:h,grounded:{left:c.left>=h-u,right:c.right>=h-u},handAngle:{left:t.handAngle.left+o,right:t.handAngle.right+o},limbs:{leftArm:t.limbs.leftArm.map(a),rightArm:t.limbs.rightArm.map(a),leftLeg:t.limbs.leftLeg.map(a),rightLeg:t.limbs.rightLeg.map(a),spine:t.limbs.spine.map(a)},head:{...t.head,center:a(t.head.center),angle:t.head.angle+o}}}function Sy(t,e){const n=Xt(t.lean),s=Xt(e.headTilt),i={x:0,y:t.hipY},o=b=>({x:t.facing*b.x,y:b.y}),r=b=>o(ss(b,i,n)),a=b=>r(vy(t,b)),l=b=>a(ss({x:b.x,y:b.y+t.neckY},{x:0,y:t.neckY},s)),c=ns(t.arms.left,t.rubber).map(a),h=ns(t.arms.right,t.rubber).map(a),u=(b,A)=>Math.atan2(A.y-b.y,A.x-b.x),d={left:a(t.handTips.left),right:a(t.handTips.right)},f=(b,A)=>{const[M,E]=b.slice(-2),x=t.arms[A],S=u(a(x.end),d[A])-u(a(x.joint),a(x.end));return u(M,E)+S};let p=1/0;for(const[b,A]of[[e.leftBrow,e.leftEye],[e.rightBrow,e.rightEye]]){const M=hu(vr,1,b,cu(A,e.blink));p=Math.min(p,M,M-e.browTilt*.1)}const g={left:o(t.legs.left.end),right:o(t.legs.right.end)},m={left:o(t.toes.left),right:o(t.toes.right)},y={left:Math.max(g.left.y,m.left.y),right:Math.max(g.right.y,m.right.y)},T=Math.max(y.left,y.right),k=au*t.height;return{facing:t.facing,height:t.height,stretch:t.stretch,lineWidth:t.lineWidth,hip:i,neck:a({x:0,y:t.neckY}),shoulders:{left:a(t.arms.left.root),right:a(t.arms.right.root)},elbows:{left:a(t.arms.left.joint),right:a(t.arms.right.joint)},hands:{left:a(t.arms.left.end),right:a(t.arms.right.end)},knees:{left:o(t.legs.left.joint),right:o(t.legs.right.joint)},feet:g,toes:m,feetY:T,grounded:{left:y.left>=T-k,right:y.right>=T-k},fingertips:d,handAngle:{left:f(c,"left"),right:f(h,"right")},limbs:{leftArm:c,rightArm:h,leftLeg:ns(t.legs.left,t.rubber).map(o),rightLeg:ns(t.legs.right,t.rubber).map(o),spine:t.spine.map(r)},head:{center:l({x:0,y:-t.headRy}),rx:t.headRx,ry:t.headRy,angle:t.facing*(n+t.chest.bend+s),eyeY:vr,browTopY:p,mouthY:lu,faceX:t.facing*(tu+eu*Ke(e.turn))}}}function Ae(t,e={}){return gu(uu(t,e),t)}function Ty(t,e,n){return ss({x:t.center.x+e*t.rx,y:t.center.y+n*t.ry},t.center,t.angle)}function mu(t,e,n){const s=o=>({x:o.x+e,y:o.y+n}),i=o=>({left:s(o.left),right:s(o.right)});return{...t,hip:s(t.hip),neck:s(t.neck),shoulders:i(t.shoulders),elbows:i(t.elbows),hands:i(t.hands),fingertips:i(t.fingertips),knees:i(t.knees),feet:i(t.feet),toes:i(t.toes),feetY:t.feetY+n,grounded:{...t.grounded},handAngle:{...t.handAngle},limbs:{leftArm:t.limbs.leftArm.map(s),rightArm:t.limbs.rightArm.map(s),leftLeg:t.limbs.leftLeg.map(s),rightLeg:t.limbs.rightLeg.map(s),spine:t.limbs.spine.map(s)},head:{...t.head,center:s(t.head.center)}}}function yu(t,e,n={},s=0){const i=uu(e,n),o=n.color??"#1e293b",r=n.layers??{},a=n.layers?gu(i,e,!1):void 0,l=n.sketch?si(t,n.sketch,s):void 0,c=n.sketch&&n.layers?si(t,n.sketch,s):void 0,h=E=>{t.save(),E(),t.restore()},u=E=>{E&&a&&h(()=>E(t,a,s,c))},d=()=>t.scale(i.facing,1),f=()=>{d(),t.translate(0,i.hipY),t.rotate(Xt(i.lean)),t.translate(0,-i.hipY)},p=()=>{f(),i.chest.bend!==0&&(t.translate(i.chest.end.x,i.chest.end.y),t.rotate(i.chest.bend),t.translate(0,-i.neckY))},g=(E,x,S)=>{if(l)return x?l.curve(E):l.line(E);if(i.classic){t.beginPath(),t.moveTo(E[0].x,E[0].y);for(const I of E.slice(1))t.lineTo(I.x,I.y);t.stroke();return}ii(t,E,S[0]*i.lineWidth,S[1]*i.lineWidth)},m=(E,x)=>g(ns(E,i.rubber),i.rubber>0,x),y=E=>{i.classic||g([i.legs[E].end,i.toes[E]],!1,ly)},T=E=>{if(n.hands&&!i.classic)return b(E);if(i.classic||l)return;const x=i.arms[E].end;t.beginPath(),t.arc(x.x,x.y,hy*i.lineWidth,0,Math.PI*2),t.fill()};t.save(),t.strokeStyle=o,t.fillStyle=o,t.lineWidth=i.lineWidth,t.lineCap="round",t.lineJoin="round";const k=pu(i,e.spin??0,e.rise??0);(k.angle!==0||k.lift!==0)&&(t.translate(0,-k.lift),t.translate(k.pivot.x,k.pivot.y),t.rotate(k.angle),t.translate(-k.pivot.x,-k.pivot.y));function b(E){const x=n.hands??{},S=i.arms[E].end,I=i.handTips[E],v=n.headFill??"#ffffff";li(t,S,x[E]??Et,{side:E,angle:Math.atan2(I.x-S.x,S.y-I.y)*180/Math.PI,size:(x.size??ru)*i.height*Math.sqrt(i.stretch),skin:x.skin??(v==="none"?void 0:v),ink:o,lineWidth:i.lineWidth*.45,fingers:x.fingers,plump:x.plump,look:n.sketch?"pencil":"clean",seed:n.sketch?.seed},s)}const A=E=>{h(()=>{p(),m(i.arms[E],ay),T(E)});const x=r.sleeve;x&&a&&h(()=>x(t,a,E,s,c))},M=Ke(e.turn)>py;u(r.behind),h(()=>{d(),m(i.legs.left,iu),y("left"),m(i.legs.right,iu),y("right")}),M&&A("left"),h(()=>{f(),g(i.spine,i.spine.length>2,ry)}),h(()=>{p();const{left:E,right:x}={left:i.arms.left.root,right:i.arms.right.root};if(E.x!==x.x)if(i.classic)g([E,x],!1,[1,1]);else{const S={x:(E.x+x.x)/2,y:E.y-.3*Math.abs(x.x-E.x)};g(Ye(E,S,x,1,8),!0,[1.1,1.1])}}),u(r.body),M||A("left"),A("right"),u(r.behindHead),h(()=>{p(),t.translate(0,i.neckY),t.rotate(Xt(e.headTilt));const E=-i.headRy;t.beginPath(),t.ellipse(0,E,i.headRx,i.headRy,0,0,Math.PI*2);const x=n.headFill??"#ffffff";if(x!=="none"&&(t.fillStyle=x,t.fill()),l){l.ellipse(0,E,i.headRx,i.headRy);const S=l.nudge();t.translate(S.x,S.y)}else t.stroke();t.translate(0,E),t.scale(i.headRx/i.r,i.headRy/i.r),ky(t,e,i.r,0,o,i.lineWidth)}),u(r.overHead),u(r.front),t.restore(),n.label&&(t.save(),t.fillStyle=o,t.font=n.labelFont??`700 ${Math.round(i.height*.11)}px sans-serif`,t.textAlign="center",t.textBaseline="bottom",t.fillText(n.label,0,-i.height*i.stretch-.04*i.height+i.drop),t.restore())}function Mr(t,e,n,s){const i={...t},o=t.gait&&s?.[t.gait]||t.gait;let r=t.walking>0?kn(i,Yh(o,t.walk,i),t.walking):i,a=Ey(t);const l=t.dancing??0;if(n&&l>0){const c=n(t.beat??0);if(r=kn(r,c.pose,l),c.hands){const h=(u,d)=>d?wn(u??Et,d,l):u;a={left:h(a?.left,c.hands.left),right:h(a?.right,c.hands.right)}}}return t.talk>0&&(r={...r,mouth:Math.max(r.mouth,t.talk*Jh(e))}),{pose:r,hands:a}}function bu(t,e,n,s){return Mr(t,e,n,s).pose}const wu=(t,e)=>(t.facing??e.facing??1)<0?-1:1,is=(t,e)=>`hand.${t}.${e}`;function Ey(t){const e=i=>{if(typeof t[is(i,"spread")]=="number")return Object.fromEntries(Object.keys(Et).map(o=>[o,t[is(i,o)]]))},n=e("left"),s=e("right");return n||s?{left:n,right:s}:void 0}function Ay(t,e){return!e||!t.hands?t:{...t,hands:{...t.hands,left:e.left??t.hands.left,right:e.right??t.hands.right}}}function Sr(t){const e=t.style??{},n=e.height??300,s=n*.8,i={...Pt(t.pose??{}),walk:0,walking:0,gait:"walk",facing:(e.facing??1)<0?-1:1,talk:0,rubber:e.rubber??0,beat:0,dancing:0},o={};if(e.hands)for(const r of["left","right"]){const a=e.hands[r]??Et;for(const l of Object.keys(Et))o[is(r,l)]=a[l]??Et[l]}return{type:"custom",x:t.x-s/2,y:t.y-n,width:s,height:n,props:{...i,...o},about:xy(Object.keys(o),t.cast),figureStyle:e,figureDance:t.dance,figureGaits:t.cast?.gaits,draw(r,a,l){const c=a.props,h=Mr(c,l,t.dance,t.cast?.gaits);r.translate(s/2,n),yu(r,h.pose,Ay({...e,rubber:c.rubber,facing:wu(c,e)},h.hands),l)}}}function xy(t,e){const n={...Ch,...Hh};for(const s of t){const[,i,...o]=s.split("."),r=Rh[o.join(".")];r&&(n[s]={...r,description:`${i==="left"?"Left":"Right"} hand: ${r.description.toLowerCase()}`})}return{kind:"stick figure",summary:"A poseable stick figure: pose it with joint tracks, or give it beats (`scriptTracks`) that compile into acted tracks.",props:n,get actions(){return x1(e)}}}function Tr(t,e,n){const s=t.figureStyle;if(!s)throw new Error("stickFigureAt: the target was not made by stickFigureTarget");const i={...t.props};let o=0,r=0;for(const[c,h]of e.state?.values.get(n)??[])c==="gait"&&typeof h=="string"&&(i.gait=h),typeof h=="number"&&(c==="x"||c==="motionPathX"?o=h:c==="y"||c==="motionPathY"?r=h:c in i&&(i[c]=h));const a=bu(i,e.time,t.figureDance,t.figureGaits),l=Ae(a,{...s,rubber:i.rubber,facing:wu(i,s)});return{pose:a,joints:mu(l,t.x+o+t.width/2,t.y+r+t.height)}}function Er(t){const e=[];return t.forEach((n,s)=>{const i=s===0?et:e[s-1],o=typeof n.pose=="string"?jt[n.pose]:{...i,...n.pose};e.push(n.expression?Ee(o,n.expression):o)}),e}function $y(t,e){const n=Er(e);return zh.filter(s=>n.some(i=>i[s]!==et[s])).map(s=>({id:`${t}-${s}`,target:t,property:s,keyframes:e.map((i,o)=>({time:i.time,value:n[o][s],...i.easing?{easing:i.easing}:{}}))}))}const Ar=.5,ui={pataka:At({"thumb.curl":.3,"thumb.across":.6,"index.curl":0,"middle.curl":0,"ring.curl":0,"pinky.curl":0,spread:0,turn:2}),tripataka:At({"thumb.curl":.3,"thumb.across":.6,"index.curl":0,"middle.curl":0,"ring.curl":1,"pinky.curl":0,spread:0,turn:2}),alapadma:At({"thumb.curl":.1,"thumb.across":0,"index.curl":.05,"middle.curl":.15,"ring.curl":.25,"pinky.curl":.35,spread:1,turn:2}),mushti:$t.fist,shikhara:$t.thumbsUp,hamsasya:At({"thumb.curl":.15,"thumb.across":.6,"index.curl":.6,"middle.curl":0,"ring.curl":0,"pinky.curl":0,spread:.7,turn:2}),katakamukha:At({"thumb.curl":.2,"thumb.across":.6,"index.curl":.65,"middle.curl":.7,"ring.curl":0,"pinky.curl":0,spread:.4,turn:2})};function di(t){return typeof t!="string"?t:t in ui?ui[t]:$t[t]}function ku(t,e,n){const s=[];for(const i of t.keys){const o=s[s.length-1],r=!o||i.reset?{pose:e,...n}:o;s.push({beat:i.beat,pose:{...r.pose,...i.pose},left:i.hands?.left?di(i.hands.left):r.left,right:i.hands?.right?di(i.hands.right):r.right,easing:i.easing??t.easing})}return s}const xr=(t,e)=>(t%e+e)%e;function Py(t,e,n,s){const i=ku(t,n,s);if(i.length===0)return{pose:n,hands:s};const o=xr(e,t.beats);let r=i.length-1;for(let f=0;f<i.length;f++)i[f].beat<=o&&(r=f);const a=i[r],l=i[(r+1)%i.length],c=a.beat<=o?a.beat:a.beat-t.beats,h=l.beat>c?l.beat:l.beat+t.beats,u=h>c?(o-c)/(h-c):0,d=Ct(l.easing??"ease-in-out")(Math.min(1,Math.max(0,u)));return{pose:kn(a.pose,l.pose,d),hands:{left:wn(a.left,l.left,d),right:wn(a.right,l.right,d)}}}const Iy=[["leftShoulder","rightShoulder"],["leftElbow","rightElbow"],["leftWrist","rightWrist"],["leftHip","rightHip"],["leftKnee","rightKnee"],["leftAnkle","rightAnkle"],["leftFootOut","rightFootOut"],["leftEye","rightEye"],["leftBrow","rightBrow"]],Oy=["lean","headTilt","lookX","spin"],_y=new Set(["leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee"]);function vu(t){const e={...t},n=(t.turn??0)>=.5;for(const[s,i]of Iy){const o=n&&_y.has(s)?-1:1;e[s]=o*t[i],e[i]=o*t[s]}if(!n)for(const s of Oy)e[s]=-t[s];return e}const Cy=t=>Math.min(1,Math.max(-1,(.5-t)*4));function Mu(t,e,n){const s=xr(n,1),i=(1+Math.cos(2*Math.PI*s))/2,o=e.bounce*(e.accent==="up"?1-i:i),r=Math.min(1,Math.max(0,t.turn??0)),a=Cy(r);return{...t,leftHip:t.leftHip+a*o/2,rightHip:t.rightHip+o/2,leftKnee:t.leftKnee+a*o,rightKnee:t.rightKnee+o,lean:t.lean+(e.sway??0)*(1-r)*Math.sin(Math.PI*n)}}function fi(t){const e={...et,...t.stance};return t.expression?Ee(e,t.expression):e}function Su(t){return{left:t.hands?.left?di(t.hands.left):Et,right:t.hands?.right?di(t.hands.right):Et}}function $r(t,e,n){const s=t.moves[e.move];if(!s)throw new Error(`dance: "${t.label}" has no move "${e.move}"`);const i=Py(s,n,fi(t),Su(t));return e.mirror?{pose:vu(i.pose),hands:{left:i.hands?.right,right:i.hands?.left}}:i}function gi(t,e,n={}){const s=typeof t=="string"?xe[t]:t;let i;if(n.move)i=$r(s,{move:n.move,mirror:n.mirror},e);else{const o=s.routine,r=o.reduce((u,d)=>u+d.beats,0),a=xr(e,r);let l=0,c=0;for(;c<o.length-1&&a>=l+o[c].beats;)l+=o[c++].beats;const h=a-l;if(i=$r(s,o[c],h),h<Ar&&o.length>1&&e>=Ar){const u=o[(c-1+o.length)%o.length],d=$r(s,u,u.beats+h),f=Ct("ease-in-out")(h/Ar);i={pose:kn(d.pose,i.pose,f),hands:{left:wn(d.hands.left,i.hands.left,f),right:wn(d.hands.right,i.hands.right,f)}}}}return{...i,pose:Mu(i.pose,s.groove,e)}}function Hy(t,e,n={}){return gi(t,e,n).pose}function pi(t){return(typeof t=="string"?xe[t]:t).routine.reduce((n,s)=>n+s.beats,0)}const Ry={leftToe:"rightToe",rightToe:"leftToe",leftHeel:"rightHeel",rightHeel:"leftHeel"};function Tu(t,e,n,s,i,o,r){for(let a=0;a*t.beats<n;a++)for(const l of t.keys){const c=a*t.beats+l.beat,h=e+c;if(!(c>=n||h<o||h>=r))for(const u of l.taps??[])i.push({beat:h,tap:s?Ry[u]:u})}}function Ly(t,e,n,s={}){const i=typeof t=="string"?xe[t]:t,o=[];if(n<=e)return o;if(s.move){const r=i.moves[s.move],a=Math.floor(e/r.beats)*r.beats;Tu(r,a,Math.ceil((n-a)/r.beats)*r.beats,s.mirror,o,e,n)}else{const r=pi(i);for(let a=Math.floor(e/r)*r;a<n;a+=r){let l=a;for(const c of i.routine)Tu(i.moves[c.move],l,c.beats,c.mirror,o,e,n),l+=c.beats}}return o.sort((r,a)=>r.beat-a.beat)}function Eu(t,e){const n=t.moves[e.move];if(!n?.travel)return 0;const s=n.travel/n.beats;return e.mirror?(ku(n,fi(t),Su(t))[0]?.pose.turn??fi(t).turn??0)>=.5?s:-s:s}function Au(t,e){return e.move?[{move:e.move,beats:t.moves[e.move].beats,mirror:e.mirror}]:t.routine}function mi(t,e,n={}){const s=typeof t=="string"?xe[t]:t,i=Au(s,n),o=i.reduce((h,u)=>h+u.beats,0),r=i.reduce((h,u)=>h+Eu(s,u)*u.beats,0),a=Math.floor(e/o);let l=a*r,c=e-a*o;for(const h of i){const u=Math.min(h.beats,c);if(l+=Eu(s,h)*u,c-=u,c<=0)break}return l}function Fy(t,e,n){const s=Au(t,n),i=[0];let o=0;for(let r=0;o<e;r=(r+1)%s.length)o+=s[r].beats,i.push(Math.min(o,e));return i}const Ny=8;function xu(t,e,n){const s=typeof e=="string"?xe[e]:e,i=n.bpm??s.bpm,o=n.beats??(n.move?s.moves[n.move].beats:pi(s)),r=Fy(s,o,n);if(r.every(y=>mi(s,y,n)===0))return;const a=Math.min(n.fade??1,o/2),l=Ct("ease-in-out"),c=y=>a<=0?1:Math.min(l(Math.min(1,y/a)),l(Math.min(1,(o-y)/a))),h=Math.ceil(a*Ny),u=a<=0?[]:Array.from({length:h+1},(y,T)=>[T/h*a,o-T/h*a]).flat(),d=[...new Set([...r,...u])].sort((y,T)=>y-T);let f=0;const p=d.map((y,T)=>{if(T>0){const k=d[T-1],b=Math.max(1,Math.ceil((y-k)*16));for(let A=0;A<b;A++){const M=k+(y-k)*A/b,E=k+(y-k)*(A+1)/b;f+=(mi(s,E,n)-mi(s,M,n))*c((M+E)/2)}}return{beat:y,travel:f}}),g=n.start??0,m=n.x??0;return{id:`${t}-x`,target:t,property:"x",keyframes:p.map(y=>({time:g+y.beat*6e4/i,value:m+n.height*y.travel,easing:"linear"}))}}function Dy(t,e,n=0){return(t-n)*e/6e4}function Wy(t,e={}){return n=>gi(t,n,e)}function By(t,e){const n=e.start??0,s=6e4/e.bpm,i=n+e.beats*s,o=Math.min((e.fade??1)*s,(i-n)/2);return[{id:`${t}-beat`,target:t,property:"beat",keyframes:[{time:n,value:0},{time:i,value:e.beats,easing:"linear"}]},{id:`${t}-dancing`,target:t,property:"dancing",keyframes:[{time:n,value:0},{time:n+o,value:1,easing:"ease-in-out"},{time:i-o,value:1},{time:i,value:0,easing:"ease-in-out"}]}]}function jy(t,e,n={}){const s=typeof e=="string"?xe[e]:e,i=n.bpm??s.bpm,o=n.beats??(n.move?s.moves[n.move].beats:pi(s)),r=n.samplesPerBeat??4,a=n.start??0,l=Math.round(o*r),c=Array.from({length:l+1},(g,m)=>{const y=m/r;return{time:a+y*6e4/i,frame:gi(s,y,n)}}),h=(g,m)=>({id:`${t}-${g}`,target:t,property:g,keyframes:c.map(y=>({time:y.time,value:m(y.frame)}))}),d=Object.keys(et).filter(g=>c.some(m=>m.frame.pose[g]!==c[0].frame.pose[g])||c[0].frame.pose[g]!==et[g]).map(g=>h(g,m=>m.pose[g])),f=n.height===void 0?void 0:xu(t,s,{...n,bpm:i,beats:o,start:a,height:n.height,fade:0});if(f&&d.push(f),n.hands===!1)return d;const p=[];for(const g of["left","right"])for(const m of Object.keys(Et)){const y=T=>T.hands?.[g]?.[m]??Et[m];c.some(T=>y(T.frame)!==Et[m])&&p.push(h(is(g,m),y))}return[...d,...p]}const os={type:"back",mode:"out",overshoot:1.1},Rt="ease-out-cubic",qy={label:"Disco",bpm:120,stance:{leftHip:10,rightHip:10,leftKnee:6,rightKnee:6},expression:{smile:.9,mouth:.15,leftBrow:.3,rightBrow:.3},groove:{bounce:10,accent:"down",sway:2},moves:{point:{label:"The point",beats:2,easing:Rt,keys:[{beat:0,pose:{rightShoulder:150,rightElbow:0,rightWrist:0,leftShoulder:40,leftElbow:-105,leftWrist:-20,lean:-5,headTilt:8,rightHip:18,leftHip:6,lookX:.6,lookY:-.7},hands:{right:"point",left:"fist"}},{beat:1,pose:{rightShoulder:-30,rightWrist:10,lean:5,headTilt:-6,rightHip:6,leftHip:18,lookX:-.4,lookY:.6}}]},roll:{label:"Roll the arms",beats:2,easing:"linear",keys:[{beat:0,pose:{leftShoulder:42,leftElbow:-128,rightShoulder:26,rightElbow:-100,rightHip:18,leftHip:6,lean:-3},hands:{left:"fist",right:"fist"}},{beat:.5,pose:{leftShoulder:26,leftElbow:-100,rightShoulder:42,rightElbow:-128}},{beat:1,pose:{leftShoulder:42,leftElbow:-128,rightShoulder:26,rightElbow:-100,rightHip:6,leftHip:18,lean:3}},{beat:1.5,pose:{leftShoulder:26,leftElbow:-100,rightShoulder:42,rightElbow:-128}}]},bump:{label:"Bump and clap",beats:4,keys:[{beat:0,pose:{lean:-10,rightHip:22,leftHip:4,leftShoulder:140,rightShoulder:140,leftElbow:0,rightElbow:0,leftWrist:20,rightWrist:20},hands:{left:"spread",right:"spread"},easing:Rt},{beat:1,pose:{lean:0,rightHip:10,leftHip:10,leftShoulder:168,rightShoulder:168,leftElbow:22,rightElbow:22,leftWrist:0,rightWrist:0},hands:{left:"flat",right:"flat"}},{beat:2,pose:{lean:10,rightHip:4,leftHip:22,leftShoulder:140,rightShoulder:140,leftElbow:0,rightElbow:0,leftWrist:20,rightWrist:20},hands:{left:"spread",right:"spread"},easing:Rt},{beat:3,pose:{lean:0,rightHip:10,leftHip:10,leftShoulder:168,rightShoulder:168,leftElbow:22,rightElbow:22,leftWrist:0,rightWrist:0},hands:{left:"flat",right:"flat"}}]}},routine:[{move:"point",beats:8},{move:"roll",beats:4},{move:"point",beats:8,mirror:!0},{move:"bump",beats:8}]},Yy={label:"Hip hop",bpm:95,stance:{leftHip:14,rightHip:14,leftKnee:20,rightKnee:20,leftShoulder:22,rightShoulder:22,leftElbow:-30,rightElbow:-30,leftFootOut:.15,rightFootOut:.15},expression:"smug",hands:{left:"relaxed",right:"relaxed"},groove:{bounce:18,accent:"down"},moves:{bounce:{label:"Bounce",beats:2,keys:[{beat:0,pose:{leftShoulder:30,rightShoulder:30,leftElbow:-50,rightElbow:-50,lean:-3,headTilt:-5,leftWrist:-20,rightWrist:-20}},{beat:1,pose:{leftShoulder:14,rightShoulder:14,leftElbow:-18,rightElbow:-18,lean:3,headTilt:5,leftWrist:0,rightWrist:0}}]},runningMan:{label:"Running man",beats:2,keys:[{beat:0,reset:!0,pose:{turn:.85,leftHip:-84,leftKnee:-112,leftAnkle:25,rightHip:-26,rightKnee:8,leftShoulder:35,leftElbow:-50,rightShoulder:45,rightElbow:75,lean:6},hands:{left:"fist",right:"fist"}},{beat:.5,pose:{leftHip:-4,leftKnee:-18,leftAnkle:0,rightHip:4,rightKnee:18,leftShoulder:5,leftElbow:-40,rightShoulder:5,rightElbow:40}},{beat:1,pose:{rightHip:84,rightKnee:112,rightAnkle:25,leftHip:26,leftKnee:-8,rightShoulder:-35,rightElbow:50,leftShoulder:-45,leftElbow:-75}},{beat:1.5,pose:{rightHip:4,rightKnee:18,rightAnkle:0,leftHip:-4,leftKnee:-18,rightShoulder:-5,rightElbow:40,leftShoulder:-5,leftElbow:-40}}]},armWave:{label:"Arm wave",beats:4,keys:[{beat:0,reset:!0,pose:{leftShoulder:90,rightShoulder:90,leftElbow:0,rightElbow:0},hands:{left:"flat",right:"flat"}},{beat:.5,pose:{leftWrist:45,leftElbow:-15}},{beat:1,pose:{leftWrist:-35,leftElbow:40,leftShoulder:84}},{beat:1.5,pose:{leftWrist:0,leftElbow:-10,leftShoulder:102,headTilt:-8}},{beat:2,pose:{leftElbow:0,leftShoulder:90,rightShoulder:102,headTilt:8}},{beat:2.5,pose:{rightShoulder:84,rightElbow:40,headTilt:0}},{beat:3,pose:{rightElbow:-15,rightWrist:45}},{beat:3.5,pose:{rightElbow:0,rightWrist:-35}}]}},routine:[{move:"bounce",beats:8},{move:"runningMan",beats:8},{move:"armWave",beats:8},{move:"bounce",beats:4}]},Ky={label:"Breaking (toprock)",bpm:110,stance:{leftHip:14,rightHip:14,leftKnee:14,rightKnee:14,leftShoulder:35,rightShoulder:35,leftElbow:-90,rightElbow:-90},expression:{smile:.3,leftBrow:-.3,rightBrow:-.3,browTilt:-.3},hands:{left:"fist",right:"fist"},groove:{bounce:8,accent:"down"},moves:{toprock:{label:"Toprock (Indian step)",beats:4,keys:[{beat:0,pose:{rightHip:-24,rightKnee:10,leftHip:10,leftShoulder:80,leftElbow:40,rightShoulder:55,rightElbow:-50,lean:6,headTilt:-6},easing:Rt},{beat:1,reset:!0,pose:{leftHip:18,rightHip:18}},{beat:2,pose:{leftHip:-24,leftKnee:10,rightHip:10,rightShoulder:80,rightElbow:40,leftShoulder:55,leftElbow:-50,lean:-6,headTilt:6},easing:Rt},{beat:3,reset:!0,pose:{leftHip:18,rightHip:18}}]},kick:{label:"Kick out",beats:2,keys:[{beat:0,pose:{rightHip:72,rightKnee:4,rightAnkle:-20,leftHip:4,lean:-12,leftShoulder:100,leftElbow:20},easing:Rt},{beat:1,reset:!0}]},freeze:{label:"B-boy stance",beats:4,keys:[{beat:0,reset:!0,pose:{leftShoulder:26,leftElbow:-122,rightShoulder:22,rightElbow:-118,leftHip:18,rightHip:18,leftKnee:6,rightKnee:6,lean:-4,headTilt:10,smile:.6,leftEye:.6,rightEye:.6},easing:os},{beat:2,pose:{headTilt:14,lean:-6}}]}},routine:[{move:"toprock",beats:8},{move:"kick",beats:4},{move:"toprock",beats:8},{move:"kick",beats:4,mirror:!0},{move:"freeze",beats:4}]},zy={label:"Jazz",bpm:130,stance:{leftHip:10,rightHip:10},expression:{mouth:.55,smile:1,mouthWidth:1.2,leftBrow:.6,rightBrow:.6},hands:{left:"spread",right:"spread"},groove:{bounce:6,accent:"up"},moves:{jazzHands:{label:"Jazz hands",beats:2,easing:"linear",keys:[0,.25,.5,.75,1,1.25,1.5,1.75].map((t,e)=>({beat:t,pose:{leftShoulder:128,rightShoulder:128,leftElbow:8,rightElbow:8,leftWrist:e%2?4:26,rightWrist:e%2?26:4,leftHip:16,rightHip:16,leftKnee:t<1?26:8,rightKnee:t<1?26:8},hands:e===0?{left:{...$t.spread,turn:2},right:{...$t.spread,turn:2}}:void 0}))},kickBallChange:{label:"Kick ball change",beats:2,keys:[{beat:0,reset:!0,pose:{rightHip:88,rightKnee:0,rightAnkle:55,leftHip:4,lean:-12,leftShoulder:112,rightShoulder:112,leftWrist:15,rightWrist:15},hands:{left:"flat",right:"flat"},easing:Rt},{beat:1,reset:!0,pose:{rightHip:10,rightKnee:24,rightAnkle:45,leftShoulder:60,rightShoulder:60,leftElbow:-20,rightElbow:-20}},{beat:1.5,pose:{rightAnkle:0,rightKnee:6,leftAnkle:45,leftKnee:20}}]},splitDrop:{label:"Drop into the splits",beats:8,keys:[{beat:0,reset:!0},{beat:2,reset:!0,pose:{leftHip:90,rightHip:90,leftKnee:0,rightKnee:0,leftAnkle:-45,rightAnkle:-45,leftShoulder:125,rightShoulder:125,leftElbow:10,rightElbow:10},easing:"ease-in-out-cubic"},{beat:4,pose:{leftShoulder:95,rightShoulder:95,leftElbow:0,rightElbow:0,leftWrist:50,rightWrist:50,headTilt:8}},{beat:6,reset:!0,pose:{leftHip:30,rightHip:30,leftKnee:60,rightKnee:60,leftShoulder:40,rightShoulder:40},easing:"ease-in-out-cubic"},{beat:7.5,reset:!0}]},jazzSquare:{label:"Jazz square",beats:4,keys:[{beat:0,reset:!0,pose:{rightHip:-18,leftHip:8,leftShoulder:38,rightShoulder:46,leftElbow:100,rightElbow:96,lean:4},hands:{left:"pinch",right:"pinch"}},{beat:1,pose:{leftHip:18,rightHip:6,leftShoulder:46,rightShoulder:38,lean:-4}},{beat:2,pose:{rightHip:22,leftHip:6,leftShoulder:38,rightShoulder:46,lean:4}},{beat:3,pose:{leftHip:10,rightHip:10,leftShoulder:46,rightShoulder:38,lean:0}}]}},routine:[{move:"jazzHands",beats:4},{move:"kickBallChange",beats:4},{move:"kickBallChange",beats:4,mirror:!0},{move:"jazzSquare",beats:8},{move:"jazzHands",beats:4},{move:"splitDrop",beats:8}]},Xy={label:"K-pop",bpm:125,stance:{leftHip:9,rightHip:9,leftKnee:4,rightKnee:4},expression:"happy",groove:{bounce:5,accent:"down"},moves:{pointCombo:{label:"Point combo",beats:4,easing:os,keys:[{beat:0,reset:!0,pose:{rightShoulder:142,rightElbow:0,leftShoulder:25,leftElbow:-125,headTilt:6,lean:-3,lookX:.6,lookY:-.6},hands:{right:"point",left:"flat"}},{beat:1,pose:{rightShoulder:-38,headTilt:-6,lean:3,lookX:-.3,lookY:.5,rightHip:18}},{beat:2,reset:!0,pose:{leftShoulder:36,leftElbow:-96,rightShoulder:36,rightElbow:-96,leftWrist:20,rightWrist:20},hands:{left:"fist",right:"fist"}},{beat:3,reset:!0,pose:{leftShoulder:96,rightShoulder:96,leftElbow:0,rightElbow:0,leftWrist:50,rightWrist:50,headTilt:8,leftHip:18,rightHip:18},hands:{left:"flat",right:"flat"}}]},heart:{label:"Big heart, finger heart",beats:4,keys:[{beat:0,reset:!0,pose:{leftShoulder:165,rightShoulder:165,leftElbow:46,rightElbow:46,headTilt:-8,lean:-4},hands:{left:"cupped",right:"cupped"},easing:os},{beat:1,pose:{headTilt:8,lean:4}},{beat:2,reset:!0,pose:{rightShoulder:32,rightElbow:112,rightWrist:10,leftShoulder:20,leftElbow:-30,headTilt:10,leftEye:0,smile:1},hands:{right:"pinch",left:"relaxed"},easing:os},{beat:3,pose:{headTilt:4}}]},isolations:{label:"Isolations",beats:2,easing:Rt,keys:[{beat:0,reset:!0,pose:{lean:-9,headTilt:11,leftShoulder:55,leftElbow:-112,rightShoulder:55,rightElbow:-112,rightHip:18},hands:{left:"fist",right:"fist"}},{beat:.5,pose:{lean:0,headTilt:0,rightHip:9}},{beat:1,pose:{lean:9,headTilt:-11,leftHip:18}},{beat:1.5,pose:{lean:0,headTilt:0,leftHip:9}}]}},routine:[{move:"pointCombo",beats:8},{move:"isolations",beats:4},{move:"heart",beats:8},{move:"pointCombo",beats:8,mirror:!0},{move:"isolations",beats:4}]},Gy={label:"Bollywood",bpm:120,stance:{leftHip:10,rightHip:10},expression:{smile:1,mouth:.3,leftBrow:.4,rightBrow:.4},groove:{bounce:8,accent:"down",sway:3},moves:{lightBulb:{label:"Screw the bulb, pat the dog",beats:2,keys:[{beat:0,reset:!0,pose:{rightShoulder:160,rightElbow:12,rightWrist:-15,leftShoulder:40,leftElbow:-12,leftWrist:-45,lean:-4,rightHip:16,lookX:.5,lookY:-.6},hands:{right:{...$t.cupped,roll:-30},left:{...$t.flat,turn:0}}},{beat:.5,pose:{rightWrist:25,rightElbow:22,leftWrist:10,lean:4,rightHip:6,leftHip:16},hands:{right:{...$t.cupped,roll:30}}},{beat:1,pose:{rightWrist:-15,rightElbow:12,leftWrist:-45,lean:-4,rightHip:16,leftHip:6},hands:{right:{...$t.cupped,roll:-30}}},{beat:1.5,pose:{rightWrist:25,rightElbow:22,leftWrist:10,lean:4,rightHip:6,leftHip:16},hands:{right:{...$t.cupped,roll:30}}}]},thumka:{label:"Thumka",beats:2,keys:[{beat:0,reset:!0,pose:{lean:-11,rightHip:22,leftHip:2,leftKnee:14,rightShoulder:45,rightElbow:-105,leftShoulder:128,leftElbow:18,leftWrist:35,headTilt:10,lookX:-.5},hands:{right:"fist",left:{...$t.open,turn:2}},easing:Rt},{beat:.5,pose:{lean:-4,rightHip:12,headTilt:6}},{beat:1,pose:{lean:-11,rightHip:22,headTilt:10},easing:Rt},{beat:1.5,pose:{lean:-4,rightHip:12,headTilt:6}}]},flick:{label:"Cross and flick",beats:4,keys:[{beat:0,reset:!0,pose:{leftShoulder:22,rightShoulder:22,leftElbow:-62,rightElbow:-62,leftHip:16,rightHip:16,leftKnee:26,rightKnee:26},hands:{left:"fist",right:"fist"}},{beat:1,pose:{leftShoulder:132,rightShoulder:132,leftElbow:0,rightElbow:0,leftWrist:30,rightWrist:30,leftKnee:0,rightKnee:0,leftHip:10,rightHip:10,stretch:1.03},hands:{left:"spread",right:"spread"},easing:Rt},{beat:2,pose:{leftShoulder:22,rightShoulder:22,leftElbow:-62,rightElbow:-62,leftWrist:0,rightWrist:0,leftHip:16,rightHip:16,leftKnee:26,rightKnee:26,stretch:1},hands:{left:"fist",right:"fist"}},{beat:3,pose:{leftShoulder:62,rightShoulder:62,leftElbow:0,rightElbow:0,leftWrist:35,rightWrist:35,leftKnee:0,rightKnee:0,leftHip:10,rightHip:10},hands:{left:"spread",right:"spread"},easing:Rt}]}},routine:[{move:"thumka",beats:4},{move:"lightBulb",beats:8},{move:"flick",beats:8},{move:"thumka",beats:4,mirror:!0},{move:"lightBulb",beats:8,mirror:!0}]},Uy={label:"Bhangra",bpm:100,stance:{leftShoulder:150,rightShoulder:150,leftElbow:18,rightElbow:18,leftHip:10,rightHip:10},expression:{mouth:.6,smile:1,mouthWidth:1.2,leftBrow:.5,rightBrow:.5},hands:{left:"open",right:"open"},groove:{bounce:12,accent:"down"},moves:{basic:{label:"Bhangra step",beats:2,keys:[{beat:0,reset:!0,pose:{rightHip:58,rightKnee:104,rightAnkle:30,leftShoulder:162,rightShoulder:140,headTilt:7}},{beat:.5,reset:!0,pose:{stretch:.98}},{beat:1,reset:!0,pose:{leftHip:58,leftKnee:104,leftAnkle:30,rightShoulder:162,leftShoulder:140,headTilt:-7}},{beat:1.5,reset:!0,pose:{stretch:.98}}]},dhamaal:{label:"Dhamaal (jump, arms up)",beats:2,keys:[{beat:0,reset:!0,pose:{leftHip:20,rightHip:20,leftKnee:40,rightKnee:40,stretch:.94}},{beat:.5,reset:!0,pose:{rise:.07,stretch:1.06,leftHip:6,rightHip:6,leftAnkle:45,rightAnkle:45,leftShoulder:172,rightShoulder:172,leftElbow:0,rightElbow:0},hands:{left:"point",right:"point"},easing:"ease-out-quad"},{beat:1,reset:!0,pose:{leftHip:20,rightHip:20,leftKnee:40,rightKnee:40,stretch:.94},hands:{left:"open",right:"open"},easing:"ease-in-quad"},{beat:1.5,reset:!0,pose:{rise:.07,stretch:1.06,leftHip:6,rightHip:6,leftAnkle:45,rightAnkle:45,leftShoulder:172,rightShoulder:172,leftElbow:0,rightElbow:0},hands:{left:"point",right:"point"},easing:"ease-out-quad"}]}},routine:[{move:"basic",beats:8},{move:"dhamaal",beats:4},{move:"basic",beats:8},{move:"dhamaal",beats:4}]},Vy={label:"Bharatanatyam",bpm:80,stance:{...{leftHip:42,rightHip:42,leftKnee:82,rightKnee:82,leftFootOut:.3,rightFootOut:.3},leftShoulder:90,rightShoulder:90,leftElbow:0,rightElbow:0,leftWrist:75,rightWrist:75},expression:{smile:.5,leftEye:1.2,rightEye:1.2,leftBrow:.3,rightBrow:.3},hands:{left:"pataka",right:"pataka"},groove:{bounce:0},moves:{tatta:{label:"Tatta adavu (stamps)",beats:2,keys:[{beat:0,reset:!0,pose:{rightHip:48,rightKnee:104,rightAnkle:-18}},{beat:.3,reset:!0,easing:"ease-in-quad",taps:["rightToe","rightHeel"]},{beat:1,reset:!0,pose:{leftHip:48,leftKnee:104,leftAnkle:-18}},{beat:1.3,reset:!0,easing:"ease-in-quad",taps:["leftToe","leftHeel"]}]},natta:{label:"Natta adavu (stretch and look)",beats:4,keys:[{beat:0,reset:!0,pose:{rightHip:52,rightKnee:0,rightAnkle:-40,rightShoulder:125,rightWrist:60,leftShoulder:25,leftElbow:-125,leftWrist:0,headTilt:8,lookX:.9,lookY:-.4,lean:-6}},{beat:1,reset:!0},{beat:2,reset:!0,pose:{leftHip:52,leftKnee:0,leftAnkle:-40,leftShoulder:125,leftWrist:60,rightShoulder:25,rightElbow:-125,rightWrist:0,headTilt:-8,lookX:-.9,lookY:-.4,lean:6}},{beat:3,reset:!0}]},alapadma:{label:"Alapadma (lotus) to the sky",beats:4,keys:[{beat:0,reset:!0,pose:{rightShoulder:145,rightElbow:20,rightWrist:30,leftShoulder:28,leftElbow:-125,leftWrist:0,lookX:.7,lookY:-.9,headTilt:6},hands:{right:"alapadma",left:"pataka"}},{beat:1,pose:{rightWrist:55,headTilt:9}},{beat:2,reset:!0,pose:{leftShoulder:145,leftElbow:20,leftWrist:30,rightShoulder:28,rightElbow:-125,rightWrist:0,lookX:-.7,lookY:-.9,headTilt:-6},hands:{left:"alapadma",right:"pataka"}},{beat:3,pose:{leftWrist:55,headTilt:-9}}]}},routine:[{move:"tatta",beats:8},{move:"natta",beats:8},{move:"alapadma",beats:8},{move:"tatta",beats:4}]},Jy={label:"Charleston",bpm:150,stance:{leftHip:10,rightHip:10,leftKnee:10,rightKnee:10,leftShoulder:30,rightShoulder:30,leftElbow:20,rightElbow:20},expression:{mouth:.4,smile:1,leftBrow:.5,rightBrow:.5},hands:{left:{...$t.spread,turn:2},right:{...$t.spread,turn:2}},groove:{bounce:8,accent:"down"},moves:{basic:{label:"Kick forward, kick back",beats:4,keys:[{beat:0,reset:!0,pose:{rightHip:48,rightKnee:8,rightAnkle:45,leftShoulder:75,rightShoulder:15,leftElbow:30,rightElbow:-10,lean:-7,headTilt:-5},easing:Rt},{beat:1,reset:!0},{beat:2,reset:!0,pose:{leftHip:18,leftKnee:85,leftAnkle:35,rightShoulder:75,leftShoulder:15,rightElbow:30,leftElbow:-10,lean:7,headTilt:5},easing:Rt},{beat:3,reset:!0}]},twist:{label:"Swivel (heels in, heels out)",beats:2,keys:[{beat:0,reset:!0,pose:{leftFootOut:-.9,rightFootOut:-.9,leftHip:4,rightHip:4,leftKnee:4,rightKnee:4,leftAnkle:-10,rightAnkle:-10,leftShoulder:18,rightShoulder:48,leftElbow:-10,rightElbow:50}},{beat:.5,pose:{leftFootOut:.6,rightFootOut:.6,leftHip:16,rightHip:16,leftKnee:22,rightKnee:22,leftAnkle:10,rightAnkle:10,leftShoulder:48,rightShoulder:18,leftElbow:50,rightElbow:-10}},{beat:1,pose:{leftFootOut:-.9,rightFootOut:-.9,leftHip:4,rightHip:4,leftKnee:4,rightKnee:4,leftAnkle:-10,rightAnkle:-10,leftShoulder:18,rightShoulder:48,leftElbow:-10,rightElbow:50}},{beat:1.5,pose:{leftFootOut:.6,rightFootOut:.6,leftHip:16,rightHip:16,leftKnee:22,rightKnee:22,leftAnkle:10,rightAnkle:10,leftShoulder:48,rightShoulder:18,leftElbow:50,rightElbow:-10}}]},kneeCross:{label:"Crossing knees",beats:2,keys:[{beat:0,reset:!0,pose:{leftHip:-6,rightHip:-6,leftKnee:-16,rightKnee:-16,leftFootOut:-.4,rightFootOut:-.4,leftShoulder:-12,rightShoulder:-12,leftElbow:0,rightElbow:0,lean:0,lookY:.6}},{beat:.5,pose:{leftHip:18,rightHip:18,leftKnee:28,rightKnee:28,leftFootOut:.3,rightFootOut:.3,leftShoulder:16,rightShoulder:16,lookY:0}},{beat:1,pose:{leftHip:-6,rightHip:-6,leftKnee:-16,rightKnee:-16,leftFootOut:-.4,rightFootOut:-.4,leftShoulder:-12,rightShoulder:-12,lookY:.6}},{beat:1.5,pose:{leftHip:18,rightHip:18,leftKnee:28,rightKnee:28,leftFootOut:.3,rightFootOut:.3,leftShoulder:16,rightShoulder:16,lookY:0}}]}},routine:[{move:"basic",beats:8},{move:"twist",beats:8},{move:"kneeCross",beats:8},{move:"basic",beats:8,mirror:!0},{move:"twist",beats:4}]},Zy={label:"Tap",bpm:120,stance:{turn:.8,leftHip:-3,rightHip:3,leftKnee:-10,rightKnee:10,leftShoulder:12,rightShoulder:12,leftElbow:-40,rightElbow:40,leftWrist:-15,rightWrist:15,lean:4},expression:{smile:.9,mouth:.2,leftBrow:.3,rightBrow:.3,lookY:.3},hands:{left:"relaxed",right:"relaxed"},groove:{bounce:6,accent:"down"},moves:{shuffleBallChange:{label:"Shuffle ball change",beats:2,easing:"ease-out-quad",keys:[{beat:0,reset:!0,pose:{rightHip:34,rightKnee:8,rightAnkle:30,leftShoulder:30,rightShoulder:-10},taps:["rightToe"]},{beat:.25,pose:{rightHip:24,rightKnee:62,rightAnkle:40},taps:["rightToe"]},{beat:.5,pose:{rightHip:-8,rightKnee:14,rightAnkle:50,leftAnkle:15,leftShoulder:12,rightShoulder:12},taps:["rightToe"]},{beat:.75,pose:{rightHip:3,rightKnee:10,rightAnkle:0,leftAnkle:0},taps:["leftHeel"]},{beat:1,reset:!0,pose:{leftHip:-34,leftKnee:-8,leftAnkle:30,rightShoulder:-30,leftShoulder:10},taps:["leftToe"]},{beat:1.25,pose:{leftHip:-24,leftKnee:-62,leftAnkle:40},taps:["leftToe"]},{beat:1.5,pose:{leftHip:8,leftKnee:-14,leftAnkle:50,rightAnkle:15,leftShoulder:12,rightShoulder:12},taps:["leftToe"]},{beat:1.75,pose:{leftHip:-3,leftKnee:-10,leftAnkle:0,rightAnkle:0},taps:["rightHeel"]}]},timeStep:{label:"Single time step",beats:4,easing:"ease-out-quad",keys:[{beat:0,reset:!0,pose:{rightHip:8,rightKnee:4,rightAnkle:0,leftShoulder:25,rightShoulder:-20},taps:["rightToe","rightHeel"]},{beat:.5,pose:{rightHip:34,rightKnee:8,rightAnkle:30},taps:["rightToe"]},{beat:.75,pose:{rightHip:22,rightKnee:62,rightAnkle:40},taps:["rightToe"]},{beat:1,pose:{rise:.05,leftAnkle:45,leftKnee:-4,leftHip:-2,rightHip:26,rightKnee:70,stretch:1.03}},{beat:1.25,pose:{rise:0,leftAnkle:0,leftKnee:-14,stretch:1},taps:["leftToe"]},{beat:1.5,pose:{rightHip:4,rightKnee:12,rightAnkle:0,rightShoulder:25,leftShoulder:-20},taps:["rightToe"]},{beat:2,pose:{leftHip:-30,leftKnee:-6,leftAnkle:35},taps:["leftToe"]},{beat:2.25,pose:{leftHip:-4,leftKnee:-12,leftAnkle:0},taps:["leftToe"]},{beat:3,pose:{rightHip:10,rightAnkle:35,rightKnee:18,leftShoulder:12,rightShoulder:12},taps:["rightToe"]},{beat:3.5,pose:{rightHip:3,rightKnee:10,rightAnkle:0}}]},heelToe:{label:"Heel toe",beats:2,easing:"ease-out-quad",keys:[{beat:0,reset:!0,pose:{rightHip:26,rightKnee:0,rightAnkle:-35,leftShoulder:30,rightShoulder:-20},taps:["rightHeel"]},{beat:.5,pose:{rightHip:-16,rightKnee:24,rightAnkle:55,leftShoulder:-15,rightShoulder:25},taps:["rightToe"]},{beat:1,reset:!0,pose:{leftHip:-26,leftKnee:0,leftAnkle:-35,rightShoulder:-30,leftShoulder:20},taps:["leftHeel"]},{beat:1.5,pose:{leftHip:16,leftKnee:-24,leftAnkle:55,rightShoulder:15,leftShoulder:-25},taps:["leftToe"]}]},crampRoll:{label:"Cramp roll",beats:2,easing:"ease-out-quad",keys:[{beat:0,reset:!0,pose:{rightHip:12,rightKnee:26,leftHip:-12,leftKnee:-26}},{beat:.5,pose:{rightAnkle:40,rise:.02},taps:["rightToe"]},{beat:.625,pose:{leftAnkle:40},taps:["leftToe"]},{beat:.75,pose:{rightAnkle:0,rise:0},taps:["rightHeel"]},{beat:.875,pose:{leftAnkle:0},taps:["leftHeel"]},{beat:1,pose:{rightShoulder:135,leftShoulder:125,leftElbow:0,rightElbow:0,leftWrist:0,rightWrist:30,rightKnee:8,leftKnee:-8,rightHip:4,leftHip:-4},hands:{left:{...$t.spread,turn:2},right:{...$t.spread,turn:2}}},{beat:1.75,reset:!0}]}},routine:[{move:"shuffleBallChange",beats:8},{move:"timeStep",beats:4},{move:"timeStep",beats:4,mirror:!0},{move:"heelToe",beats:8},{move:"crampRoll",beats:4}]},xe={disco:qy,hipHop:Yy,breaking:Ky,jazz:zy,kpop:Xy,bollywood:Gy,bhangra:Uy,bharatanatyam:Vy,charleston:Jy,tap:Zy,popping:{label:"Popping (glides, moonwalk)",bpm:100,stance:{leftHip:9,rightHip:9,leftShoulder:16,rightShoulder:16,leftElbow:-24,rightElbow:-24},expression:{smile:.35,leftEye:.85,rightEye:.85,leftBrow:-.2,rightBrow:-.2},hands:{left:"relaxed",right:"relaxed"},groove:{bounce:0},moves:{sideGlide:{label:"Side glide",beats:2,easing:"linear",travel:.2,keys:[{beat:0,reset:!0,pose:{leftHip:11,leftKnee:0,leftAnkle:0,rightHip:36,rightKnee:45,rightAnkle:45,rightShoulder:80,rightElbow:-10,rightWrist:10,leftShoulder:28,leftElbow:18,lean:-2,headTilt:4,lookX:.7},hands:{right:"flat",left:"relaxed"}},{beat:1,pose:{leftHip:27,leftKnee:54,leftAnkle:45,rightHip:-1,rightKnee:0,rightAnkle:0,rightShoulder:74,rightWrist:-10,lean:2}}]},moonwalk:{label:"Moonwalk",beats:2,easing:"linear",travel:-.29,keys:[{beat:0,reset:!0,pose:{turn:.9,lean:4,headTilt:-4,leftHip:-12,leftKnee:0,leftAnkle:0,rightHip:23,rightKnee:57,rightAnkle:45,leftShoulder:-10,leftElbow:-45,rightShoulder:14,rightElbow:50}},{beat:1,pose:{leftHip:-23,leftKnee:-57,leftAnkle:45,rightHip:12,rightKnee:0,rightAnkle:0,leftShoulder:-14,leftElbow:-50,rightShoulder:10,rightElbow:45}}]},forwardGlide:{label:"Forward glide",beats:2,easing:"linear",travel:.29,keys:[{beat:0,reset:!0,pose:{turn:.9,lean:2,leftHip:16,leftKnee:0,leftAnkle:0,rightHip:33,rightKnee:59,rightAnkle:45,leftShoulder:12,leftElbow:-40,rightShoulder:-12,rightElbow:40}},{beat:1,pose:{leftHip:-33,leftKnee:-59,leftAnkle:45,rightHip:-16,rightKnee:0,rightAnkle:0,leftShoulder:-12,leftElbow:-40,rightShoulder:12,rightElbow:40}}]},toeStand:{label:"Toe stand",beats:4,keys:[{beat:0,reset:!0,pose:{leftHip:6,rightHip:6,leftKnee:0,rightKnee:0,leftAnkle:65,rightAnkle:65,rightShoulder:150,rightElbow:75,leftShoulder:30,leftElbow:20,headTilt:-10,lookY:.4},hands:{right:"fist",left:"fist"},easing:os},{beat:2,pose:{headTilt:-14,lean:-2}}]}},routine:[{move:"sideGlide",beats:4},{move:"sideGlide",beats:4,mirror:!0},{move:"moonwalk",beats:8},{move:"forwardGlide",beats:8},{move:"toeStand",beats:4}]}},yi=t=>Math.min(1,Math.max(0,t));function Qy(t){const e={...et,turn:t.view},n=[];for(const s of t.keys){const i=n[n.length-1],o=!i||s.reset?e:i.pose;n.push({at:s.at,pose:{...o,...s.pose},easing:s.easing})}return n}function tb(t){return t-eb*Math.sin(2*Math.PI*t)/(2*Math.PI)}const eb=.5;function nb(t,e){if(!(e<=t.takeoff||e>=t.landing))return(e-t.takeoff)/(t.landing-t.takeoff)}function $u(t,e){const n=typeof t=="string"?rs[t]:t,s=Qy(n),i=yi(e);let o=0;for(let u=0;u<s.length;u++)s[u].at<=i&&(o=u);const r=s[o],a=s[Math.min(o+1,s.length-1)],l=a.at>r.at?(i-r.at)/(a.at-r.at):0,c=kn(r.pose,a.pose,Ct(a.easing??"ease-in-out")(yi(l))),h=nb(n,i);return h===void 0?{...c,spin:0,rise:0}:{...c,spin:n.spin*tb(h),rise:4*n.height*h*(1-h)}}function Pu(t,e,n){const s=typeof t=="string"?rs[t]:t,i=yi(e),o=yi((i-s.takeoff)/(s.landing-s.takeoff));return s.travel*n*o}function sb(t,e,n={}){const s=typeof e=="string"?rs[e]:e,i=n.start??0,o=n.duration??s.duration,r=n.samples??48,a=Array.from({length:r+1},(h,u)=>{const d=u/r;return{time:i+d*o,progress:d,pose:$u(s,d)}}),c=Object.keys(et).filter(h=>a.some(u=>u.pose[h]!==et[h])).map(h=>({id:`${t}-${h}`,target:t,property:h,keyframes:a.map(u=>({time:u.time,value:u.pose[h]}))}));if(n.height!==void 0&&s.travel!==0){const h=(n.facing??1)<0?-1:1;c.push({id:`${t}-x`,target:t,property:"x",keyframes:a.map(u=>({time:u.time,value:(n.x??0)+h*Pu(s,u.progress,n.height)}))})}return c}const ib={leftHip:-55,leftKnee:-95,rightHip:55,rightKnee:95,leftShoulder:45,rightShoulder:-45,leftElbow:10,rightElbow:-10,lean:22,stretch:.94,headTilt:6},ob={leftHip:0,leftKnee:0,rightHip:0,rightKnee:0,leftAnkle:55,rightAnkle:55,leftShoulder:-172,rightShoulder:172,leftElbow:0,rightElbow:0,lean:0,stretch:1.08,headTilt:0},bi={leftHip:-128,leftKnee:-152,rightHip:128,rightKnee:152,leftAnkle:30,rightAnkle:30,leftShoulder:-78,rightShoulder:78,leftElbow:-48,rightElbow:48,lean:26,stretch:1,headTilt:14},rb={leftHip:-22,leftKnee:-30,rightHip:22,rightKnee:30,leftAnkle:10,rightAnkle:10,leftShoulder:-125,rightShoulder:125,leftElbow:0,rightElbow:0,lean:8,headTilt:0},ab={leftHip:-58,leftKnee:-100,rightHip:58,rightKnee:100,leftAnkle:0,rightAnkle:0,leftShoulder:-80,rightShoulder:80,leftElbow:-10,rightElbow:10,lean:20,stretch:.93};function vn(t,e,n,s,i,o=1300){return{label:t,view:1,spin:e,height:n,travel:s,takeoff:.27,landing:.8,duration:o,keys:[{at:0,reset:!0},{at:.16,pose:ib},{at:.27,pose:ob,easing:"ease-out-quad"},...i,{at:.76,pose:rb},{at:.86,pose:ab,easing:"ease-out-quad"},{at:1,reset:!0}]}}const rs={frontFlip:vn("Front flip (tuck)",360,.56,.35,[{at:.38,pose:bi,easing:"ease-out-cubic"},{at:.64,pose:bi}]),backFlip:vn("Back flip (tuck)",-360,.58,-.15,[{at:.36,pose:{...bi,lean:18},easing:"ease-out-cubic"},{at:.64,pose:{...bi,lean:18}}]),layout:vn("Back layout (straight body)",-360,.66,-.2,[{at:.4,pose:{leftHip:8,rightHip:-8,leftKnee:0,rightKnee:0,leftAnkle:60,rightAnkle:60,leftShoulder:-178,rightShoulder:178,lean:-18,headTilt:-14}},{at:.64,pose:{leftHip:-4,rightHip:4,lean:-6,headTilt:-4,leftShoulder:-150,rightShoulder:150}}],1400),scissorFlip:vn("Scissor flip",360,.6,.45,[{at:.36,pose:{leftHip:-105,leftKnee:0,rightHip:-40,rightKnee:-20,leftAnkle:50,rightAnkle:50,leftShoulder:-150,rightShoulder:150,leftElbow:0,rightElbow:0,lean:12},easing:"ease-out-cubic"},{at:.52,pose:{leftHip:40,leftKnee:20,rightHip:105,rightKnee:0,leftShoulder:-140,rightShoulder:140}},{at:.66,pose:{leftHip:-30,leftKnee:-20,rightHip:30,rightKnee:20,leftShoulder:-110,rightShoulder:110,lean:6}}]),sideFlip:{label:"Side flip (tuck)",view:0,spin:360,height:.55,travel:.4,takeoff:.27,landing:.8,duration:1300,keys:[{at:0,reset:!0},{at:.16,pose:{leftHip:22,rightHip:22,leftKnee:44,rightKnee:44,leftShoulder:20,rightShoulder:20,lean:-10,stretch:.94}},{at:.27,pose:{leftHip:4,rightHip:4,leftKnee:0,rightKnee:0,leftAnkle:55,rightAnkle:55,leftShoulder:165,rightShoulder:165,lean:6,stretch:1.08},easing:"ease-out-quad"},{at:.38,pose:{leftHip:105,rightHip:105,leftKnee:135,rightKnee:135,leftShoulder:40,rightShoulder:40,leftElbow:-95,rightElbow:-95,lean:0,stretch:1,headTilt:10},easing:"ease-out-cubic"},{at:.64,pose:{}},{at:.76,pose:{leftHip:20,rightHip:20,leftKnee:20,rightKnee:20,leftAnkle:10,rightAnkle:10,leftShoulder:100,rightShoulder:100,leftElbow:0,rightElbow:0,headTilt:0}},{at:.86,pose:{leftHip:24,rightHip:24,leftKnee:48,rightKnee:48,leftAnkle:0,rightAnkle:0,leftShoulder:70,rightShoulder:70,stretch:.93},easing:"ease-out-quad"},{at:1,reset:!0}]},cartwheel:{label:"Cartwheel",view:0,spin:360,height:.155,travel:.9,takeoff:.2,landing:.86,duration:1600,keys:[{at:0,reset:!0},{at:.12,pose:{leftShoulder:165,rightShoulder:165,rightHip:30,rightKnee:0,lean:-6}},{at:.24,pose:{leftShoulder:172,rightShoulder:172,leftHip:55,rightHip:55,leftKnee:0,rightKnee:0,leftAnkle:40,rightAnkle:40,lean:0}},{at:.75,pose:{}},{at:.9,pose:{leftHip:30,rightHip:12,leftAnkle:0,rightAnkle:0,leftShoulder:150,rightShoulder:150}},{at:1,reset:!0}]},splitLeap:vn("Split leap (grand jeté)",0,.36,.9,[{at:.4,pose:{leftHip:-96,rightHip:-84,leftKnee:0,rightKnee:0,leftAnkle:55,rightAnkle:55,leftShoulder:-130,rightShoulder:-105,leftElbow:0,rightElbow:0,lean:4,headTilt:-6},easing:"ease-out-cubic"},{at:.64,pose:{lean:2}}]),toeTouch:{label:"Toe touch (straddle jump)",view:0,spin:0,height:.36,travel:0,takeoff:.27,landing:.8,duration:1200,keys:[{at:0,reset:!0},{at:.16,pose:{leftHip:22,rightHip:22,leftKnee:44,rightKnee:44,leftShoulder:-20,rightShoulder:-20,stretch:.94}},{at:.27,pose:{leftHip:4,rightHip:4,leftKnee:0,rightKnee:0,leftAnkle:55,rightAnkle:55,leftShoulder:170,rightShoulder:170,stretch:1.06},easing:"ease-out-quad"},{at:.42,pose:{leftHip:104,rightHip:104,leftShoulder:96,rightShoulder:96,leftElbow:0,rightElbow:0,stretch:1,headTilt:0},easing:"ease-out-cubic"},{at:.62,pose:{}},{at:.76,pose:{leftHip:12,rightHip:12,leftAnkle:10,rightAnkle:10,leftShoulder:120,rightShoulder:120}},{at:.86,pose:{leftHip:22,rightHip:22,leftKnee:44,rightKnee:44,leftAnkle:0,rightAnkle:0,leftShoulder:60,rightShoulder:60,stretch:.94},easing:"ease-out-quad"},{at:1,reset:!0}]},backHandspring:vn("Back handspring",-360,.16,-.7,[{at:.38,pose:{leftHip:10,rightHip:-10,leftKnee:0,rightKnee:0,leftShoulder:-178,rightShoulder:178,lean:-26,headTilt:-20}},{at:.6,pose:{leftHip:-40,rightHip:40,leftKnee:-20,rightKnee:20,lean:6,headTilt:0}}],1200)},wi={standard:{},slim:{headSize:.24,shoulderWidth:.05,hipWidth:.02},tall:{headSize:.25,legLength:1.1,armLength:1.05},short:{headSize:.33,legLength:.92,shoulderWidth:.065,hipWidth:.03},broad:{shoulderWidth:.11,hipWidth:.04},curvy:{shoulderWidth:.055,hipWidth:.065},stocky:{headSize:.34,shoulderWidth:.1,hipWidth:.06},kid:{headSize:.42},child:{headSize:.4,legLength:.88,armLength:.9,shoulderWidth:.05,hipWidth:.02},toddler:{headSize:.46,legLength:.78,armLength:.82,shoulderWidth:.05,hipWidth:.025}},Pr=.215,Ir=.205,lb=.065,Iu=.035,cb=.165,hb=.155,ub=12,db=.3,fb=.7,gb=.35,pb=t=>t*Math.PI/180,ft={turn:0,lean:0,bend:0,side:0,"head.turn":0,"head.nod":0,"head.tilt":0,"arm.left.swing":0,"arm.left.spread":12,"arm.left.elbow":8,"arm.left.bend":0,"arm.right.swing":0,"arm.right.spread":12,"arm.right.elbow":8,"arm.right.bend":0,"leg.left.swing":0,"leg.left.spread":3,"leg.left.knee":0,"leg.left.ankle":0,"leg.left.toeOut":0,"leg.left.rotate":0,"leg.right.swing":0,"leg.right.spread":3,"leg.right.knee":0,"leg.right.ankle":0,"leg.right.toeOut":0,"leg.right.rotate":0,stretch:1,lift:0,roll:0,mouth:0,smile:.5,mouthWidth:1,blink:0,"eye.left":1,"eye.right":1,"brow.left":0,"brow.right":0,browTilt:0,lookX:0,lookY:0,blush:0,tears:0,sweat:0,"held.left":1,"held.right":1,"held.both":1};function ht(t={}){return{...ft,...t}}const mb=new Set(["turn","side","head.turn","head.tilt","roll","lookX"]);function yb(t){const e={};for(const[n,s]of Object.entries(t)){const i=n.replace(/(^|\.)(left|right)(\.|$)/,(o,r,a,l)=>`${r}${a==="left"?"right":"left"}${l}`);e[i]=mb.has(n)?-s:s}return e}function gt(t,e){const n={};for(const s of["left","right"])for(const[i,o]of Object.entries(e))n[`${t}.${s}.${i}`]=o;return n}const ze={rest:ft,wave:ht({"arm.right.spread":115,"arm.right.bend":55,"arm.right.elbow":0,"head.tilt":-6,smile:.9}),cheer:ht({...gt("arm",{spread:140,bend:20,elbow:0}),mouth:.6,smile:1,"eye.left":0,"eye.right":0}),point:ht({"arm.right.spread":88,"arm.right.elbow":0,"arm.right.bend":0,"head.turn":-20,smile:.4}),handsOnHips:ht({...gt("arm",{spread:50,bend:-105,elbow:0}),...gt("leg",{spread:9}),smile:.8}),think:ht({"arm.right.spread":22,"arm.right.bend":-150,"arm.right.elbow":0,"head.tilt":10,lookX:-.5,lookY:-.8,smile:0}),shrug:ht({...gt("arm",{spread:35,bend:75,elbow:0}),"head.tilt":-10,smile:-.2}),sit:ht({...gt("leg",{swing:90,knee:90,spread:4}),...gt("arm",{swing:25,elbow:45,spread:8})}),kneel:ht({"leg.left.swing":90,"leg.left.knee":90,"leg.right.swing":-18,"leg.right.knee":108,"leg.right.ankle":16,...gt("arm",{swing:20,elbow:30})}),crouch:ht({...gt("leg",{swing:75,knee:140,spread:6}),lean:25,...gt("arm",{swing:50,elbow:40}),"head.nod":-15}),crawl:ht({lean:82,"head.nod":-35,...gt("arm",{swing:80,elbow:0,spread:4}),...gt("leg",{knee:92,ankle:-88})}),lieDown:ht({roll:90,...gt("arm",{spread:8}),"head.nod":0}),sleep:ht({roll:90,...gt("arm",{spread:8,swing:20,elbow:40}),"leg.left.knee":20,"leg.left.swing":15,blink:1,smile:.2}),stretch:ht({side:-16,"arm.left.spread":165,"arm.left.bend":35,"arm.left.elbow":0,"arm.right.spread":40,"arm.right.bend":-110,"arm.right.elbow":0,"head.tilt":-10,"eye.left":0,"eye.right":0,smile:.4}),sitFloor:ht({...gt("leg",{swing:80,spread:22,rotate:75,knee:145}),...gt("arm",{swing:25,spread:18,elbow:30}),lean:5,smile:.5}),carry:ht({...gt("arm",{spread:16,elbow:4}),lean:-3,smile:.4}),lift:ht({...gt("arm",{swing:28,spread:24,elbow:85,bend:-45}),...gt("leg",{swing:12,knee:22,spread:6}),lean:-4,smile:.2}),push:ht({lean:28,...gt("arm",{swing:82,spread:12,elbow:18}),"leg.left.swing":28,"leg.left.knee":30,"leg.right.swing":-28,"leg.right.knee":6,"head.nod":-20,browTilt:-.6,smile:-.2}),pull:ht({lean:-22,...gt("arm",{swing:70,spread:6,elbow:0}),"leg.left.swing":32,"leg.left.knee":8,"leg.right.swing":-8,"leg.right.knee":34,"head.nod":12,browTilt:-.6,smile:-.2}),drink:ht({"arm.right.swing":85,"arm.right.spread":8,"arm.right.elbow":120,"arm.right.bend":0,"head.nod":-14,"eye.left":.5,"eye.right":.5,smile:0}),phone:ht({"arm.right.swing":80,"arm.right.spread":8,"arm.right.elbow":80,"arm.right.bend":-10,"head.nod":18,lookY:.7,lookX:-.3,smile:.4}),read:ht({...gt("arm",{swing:32,spread:10,elbow:82,bend:-28}),"head.nod":22,lookY:.8,smile:.2}),type:ht({...gt("leg",{swing:90,knee:90,spread:4}),...gt("arm",{swing:40,spread:10,elbow:55,bend:-20}),lean:8,"head.nod":10,lookY:.5,smile:0})};function Ou(t={}){const e=t.headSize??.3,n=t.shoulderWidth??.06,s=t.hipWidth??.022,i=t.legLength??1,o=t.armLength??1,r=Math.max(.12,1-e-Iu-(Pr+Ir)*i),a=h=>({id:`arm.${h}`,parent:"spine",offset:[(h==="left"?1:-1)*n,-.035,0],rest:[0,-1,0],side:h==="left"?1:-1,bones:[{length:cb*o,width:[1.25,.9]},{length:hb*o,width:[.9,.75]}]}),l=h=>({id:`leg.${h}`,parent:null,offset:[(h==="left"?1:-1)*s,0,0],rest:[0,-1,0],side:h==="left"?1:-1,bones:[{length:Pr*i,width:[1.45,1.05]},{length:Ir*i,width:[1.05,.85]},{length:lb*Math.sqrt(i),width:[.95,.7]}]}),c=(h,u)=>h[u]??ft[u]??0;return{id:"human",hipHeight:(Pr+Ir)*i,chains:[l("left"),l("right"),{id:"spine",parent:null,rest:[0,1,0],bones:[{length:r/2,width:[1.7,1.4]},{length:r/2,width:[1.4,1.1]}]},{id:"neck",parent:"spine",rest:[0,1,0],bones:[{length:Iu,width:[1,.9]}]},a("left"),a("right")],head:{on:"neck",size:e},contacts:[...["left","right"].flatMap(h=>[{chain:`leg.${h}`,joint:1},{chain:`leg.${h}`,joint:2},{chain:`leg.${h}`,joint:3},{chain:`arm.${h}`,joint:1},{chain:`arm.${h}`,joint:2}]),{chain:"spine",joint:0},{chain:"spine",joint:1},{chain:"spine",joint:2},{head:"top"}],angles(h,u){if(u.id==="spine"){const y=-c(h,"lean")/2,T=c(h,"side")/2,k=-c(h,"bend");return[{swing:y+k*db,spread:T},{swing:y+k*fb,spread:T}]}if(u.id==="neck")return[{swing:-c(h,"bend")*gb,spread:0}];const[d,f]=u.id.split("."),p=y=>c(h,`${d}.${f}.${y}`);if(d==="arm")return[{swing:p("swing"),spread:p("spread")},{swing:p("elbow"),spread:p("bend")}];const g=(u.side??1)*p("rotate"),m=1-Math.cos(pb(p("rotate")));return[{swing:p("swing"),spread:p("spread"),yaw:g},{swing:-p("knee"),spread:0,yaw:g},{swing:90+p("ankle")-m*(p("swing")-p("knee")),spread:0,yaw:(ub+p("toeOut"))*(u.side??1)}]},withAngles(h,u,d){const[f,p]=u.id.split("."),g=m=>`${f}.${p}.${m}`;return f==="arm"?{...h,[g("swing")]:d[0].swing,[g("spread")]:d[0].spread,[g("elbow")]:d[1].swing,[g("bend")]:d[1].spread}:f==="leg"?{...h,[g("swing")]:d[0].swing,[g("spread")]:d[0].spread,[g("knee")]:-d[1].swing}:h},boneScale(h,u){const d=Math.min(3,Math.max(.3,c(h,"stretch")));return u?.id.startsWith("arm.")?Math.sqrt(d):d},headPose(h){const u=Math.min(3,Math.max(.3,c(h,"stretch")));return{yaw:c(h,"head.turn"),nod:c(h,"head.nod"),tilt:c(h,"head.tilt"),sx:1/Math.sqrt(u),sy:Math.sqrt(u)}},landmarks:{neck:["neck",0],"shoulder.left":["arm.left",0],"elbow.left":["arm.left",1],"hand.left":["arm.left",2],"shoulder.right":["arm.right",0],"elbow.right":["arm.right",1],"hand.right":["arm.right",2],"hip.left":["leg.left",0],"knee.left":["leg.left",1],"ankle.left":["leg.left",2],"toe.left":["leg.left",3],"hip.right":["leg.right",0],"knee.right":["leg.right",1],"ankle.right":["leg.right",2],"toe.right":["leg.right",3]}}}function bb(t){const e=t.split(".");if(e[0]==="hand"&&e.length>=3){const s=`${e[1]==="left"?"Left":"Right"} hand`,i={spread:"finger spread",turn:"wrist turn",bend:"wrist bend",tilt:"wrist tilt",roll:"roll"},o=e.slice(2).join(".");return`${s} · ${i[o]??o.replace(".curl"," curl").replace(".across"," across")}`}if(e.length===3){const[s,i,o]=e;return`${`${i==="left"?"Left":"Right"} ${s}`} · ${{swing:"forward / back",spread:"out / in",elbow:"elbow bend",bend:"forearm out / in",knee:"knee bend",ankle:"foot tilt",toeOut:"toes out / in",rotate:"turn out at the hip"}[o]??o}`}return{turn:"View (front → side → back)",lean:"Lean forward / back",bend:"Back curve (line of action)",side:"Lean sideways","head.turn":"Head · turn","head.nod":"Head · nod","head.tilt":"Head · tilt",stretch:"Squash / stretch",lift:"Lift off the ground",roll:"Roll (whole figure)",mouth:"Mouth open",smile:"Smile",mouthWidth:"Mouth width",blink:"Blink","eye.left":"Left eye open","eye.right":"Right eye open","brow.left":"Left brow","brow.right":"Right brow",browTilt:"Brow slant",lookX:"Look left / right",lookY:"Look up / down",blush:"Blush",tears:"Tears",sweat:"Sweat","held.left":"Left hand · holding","held.right":"Right hand · holding","held.both":"Both hands · holding"}[t]??t}const wb={leftEye:"eye.left",rightEye:"eye.right",leftBrow:"brow.left",rightBrow:"brow.right"},kb={blush:0,tears:0,sweat:0},as=Object.fromEntries(Object.entries(ct).map(([t,e])=>[t,{...Object.fromEntries(Object.entries(e).map(([n,s])=>[wb[n]??n,s])),...kb}]));as.crying.tears=1,as.scared.sweat=.8,as.worried.sweat=.6;const Gt=t=>({...as.neutral,...t}),Or={...as,laughing:Gt({mouth:.75,smile:1,mouthWidth:1.25,"eye.left":0,"eye.right":0,"brow.left":.5,"brow.right":.5}),afraid:Gt({mouth:.4,smile:-.6,mouthWidth:.9,"eye.left":1.3,"eye.right":1.3,"brow.left":.6,"brow.right":.6,browTilt:1,sweat:1}),bored:Gt({smile:-.05,mouthWidth:.6,"eye.left":.45,"eye.right":.45,"brow.left":-.4,"brow.right":-.4,lookX:.5}),tired:Gt({mouth:.2,smile:-.3,mouthWidth:.7,"eye.left":.3,"eye.right":.3,"brow.left":-.1,"brow.right":-.1,browTilt:.6,lookY:.6}),embarrassed:Gt({smile:.4,mouthWidth:.7,"eye.left":.9,"eye.right":.9,browTilt:.7,"brow.left":.2,"brow.right":.2,lookX:-.6,lookY:.5,blush:1}),proud:Gt({smile:.75,mouthWidth:1,"eye.left":.75,"eye.right":.75,"brow.left":.5,"brow.right":.5,lookY:-.2}),determined:Gt({smile:.35,mouthWidth:.8,"eye.left":.85,"eye.right":.85,"brow.left":-.5,"brow.right":-.5,browTilt:-.9}),affectionate:Gt({smile:.85,"eye.left":0,"eye.right":0,"brow.left":.3,"brow.right":.3,blush:.8}),hurt:Gt({smile:-.7,mouthWidth:.8,"eye.left":1.1,"eye.right":1.1,"brow.left":.2,"brow.right":.2,browTilt:1,lookY:.3,tears:.35}),suspicious:Gt({smile:-.25,mouthWidth:.7,"eye.left":.5,"eye.right":.85,"brow.left":-.6,"brow.right":.4,browTilt:-.3,lookX:.8}),relieved:Gt({smile:.7,"eye.left":0,"eye.right":0,"brow.left":.4,"brow.right":.4,browTilt:.4}),excited:Gt({mouth:.6,smile:1,mouthWidth:1.1,"eye.left":1.4,"eye.right":1.4,"brow.left":.9,"brow.right":.9,blush:.4})};function vb(t,e){const n=Math.min(1,Math.max(0,t.turn??0)),s=1-n,i={...ft,turn:n},o=[{stick:"right",human:"left",s:1},{stick:"left",human:"right",s:-1}];for(const{stick:a,human:l,s:c}of o){const h=t[`${a}Shoulder`],u=t[`${a}Elbow`];i[`arm.${l}.spread`]=h*s,i[`arm.${l}.swing`]=c*h*n,i[`arm.${l}.bend`]=u*s,i[`arm.${l}.elbow`]=c*u*n;const d=t[`${a}Hip`],f=t[`${a}Knee`],p=s+c*n;i[`leg.${l}.rotate`]=90*s,i[`leg.${l}.spread`]=0,i[`leg.${l}.swing`]=d*p,i[`leg.${l}.knee`]=f*p,i[`leg.${l}.ankle`]=-(t[`${a}Ankle`]??0),i[`leg.${l}.toeOut`]=(t[`${a}FootOut`]??0)*Mb,i[`eye.${l}`]=t[`${a}Eye`],i[`brow.${l}`]=t[`${a}Brow`],e&&Object.assign(i,Sb(l,e[a]??Et,t[`${a}Wrist`]??0,n))}const r=t.bend??0;i.lean=t.lean*n,i.bend=r*n,i.side=(t.lean+r*.5)*s,i["head.tilt"]=(t.headTilt+r*.5)*s,i["head.nod"]=t.headTilt*n;for(const a of["mouth","smile","mouthWidth","blink","browTilt","lookX","lookY","stretch"])i[a]=t[a];return i.lift=t.rise??0,i.roll=t.spin??0,i}const Mb=70;function Sb(t,e,n,s){const i=t==="right"?1-s:1+s,o={};for(const r of Object.keys(Et))o[`hand.${t}.${r}`]=e[r]??Et[r];return o[`hand.${t}.turn`]=(e.turn??0)-i,o[`hand.${t}.roll`]=(e.roll??0)+n,o}const Zt=t=>t*Math.PI/180;function _r([t,e,n],s){const i=Math.cos(s),o=Math.sin(s);return[t,e*i+n*o,-e*o+n*i]}function Cr([t,e,n],s){const i=Math.cos(s),o=Math.sin(s);return[t*i-e*o,t*o+e*i,n]}function $e([t,e,n],s){const i=Math.cos(s),o=Math.sin(s);return[t*i+n*o,e,-t*o+n*i]}const Pe=(t,e)=>[t[0]+e[0],t[1]+e[1],t[2]+e[2]],ki=(t,e)=>[t[0]*e,t[1]*e,t[2]*e],vi=(t,e)=>Cr(_r(t,e.swing),e.spread);function Hr(t,e){const n=$e(t,e);return{point:{x:n[0],y:-n[1]},depth:n[2]}}function Mi(t,e,n){const s=n,o=[0,t.hipHeight*s*(t.boneScale?.(e,null)??1),0],r={};for(const g of t.chains){const m=g.parent?r[g.parent]:void 0;if(g.parent&&!m)throw new Error(`body plan ${t.id}: chain ${g.id} comes before its parent ${g.parent}`);const y=g.at??(m?m.joints3.length-1:0),T=m?m.joints3[y]:o,k=m?m.frames[Math.max(0,y-1)]:{swing:0,spread:0},b=g.offset?Pe(T,vi(ki(g.offset,s),k)):T,A=g.side??1,M=t.boneScale?.(e,g)??1,E=t.angles(e,g),x=[b],S=[];let I=k.swing,v=k.spread;g.bones.forEach(($,_)=>{const P=E[_]??{swing:0,spread:0};I+=Zt(P.swing),v+=Zt(P.spread)*A,S.push({swing:I,spread:v});const C=$e(vi(g.rest,{swing:I,spread:v}),Zt(P.yaw??0));x.push(Pe(x[_],ki(C,$.length*s*M)))}),r[g.id]={joints3:x,frames:S}}const a=r[t.head.on],l=t.headPose?.(e)??{yaw:0,nod:0,tilt:0,sx:1,sy:1},c=a.frames[a.frames.length-1],h=t.head.size/2*s,u=h*l.sx,d=h*l.sy,f=g=>vi($e(_r(Cr(g,-Zt(l.tilt)),-Zt(l.nod)),Zt(l.yaw)),c),p=Pe(a.joints3[a.joints3.length-1],f([0,d,0]));return{height:s,root:o,chains:r,head:{center:p,rx:u,ry:d,toBody:f}}}function Rr(t,e,n){const s=n.height,i=Zt(90*(e.turn??0)),o=Mi(t,e,s),{root:r}=o,a=o.chains,{rx:l,ry:c}=o.head,h=o.head.toBody,u=o.head.center,d={};for(const S of t.chains){const{joints3:I,frames:v}=a[S.id],$=I.map(_=>Hr(_,i));d[S.id]={id:S.id,joints3:I,frames:v,points:$.map(_=>_.point),depths:$.map(_=>_.depth)}}const f=Hr(u,i),p=[[1,0,0],[0,1,0],[0,0,1]].map(S=>$e(h(S),i)),g=Hr(r,i).point,m=Zt(e.roll??0),y=S=>{const I=S.x-g.x,v=S.y-g.y;return{x:g.x+I*Math.cos(m)-v*Math.sin(m),y:g.y+I*Math.sin(m)+v*Math.cos(m)}},T=([S,I,v])=>[S*Math.cos(m)+I*Math.sin(m),-S*Math.sin(m)+I*Math.cos(m),v];for(const S of Object.values(d))S.points=S.points.map(y);const k={center:y(f.point),depth:f.depth,rx:l,ry:c,angle:0,axes:p.map(T)},b=k.axes[1];k.angle=Math.atan2(b[0],b[1]);const A=S=>{if("head"in S)return{x:k.center.x+b[0]*c,y:k.center.y-b[1]*c};const I=d[S.chain];return I.points[Math.min(S.joint,I.points.length-1)]};let M=0;(n.contact??"ground")==="ground"&&(M=-Math.max(...t.contacts.map(S=>A(S).y))),M-=(e.lift??0)*s;const E=S=>({x:S.x,y:S.y+M});for(const S of Object.values(d))S.points=S.points.map(E);k.center=E(k.center);const x=t.contacts.map(S=>({spec:S,point:A(S)}));return{height:s,view:i,chains:d,head:k,hip:E(y(g)),contacts:x,groundY:Math.max(...x.map(S=>S.point.y))}}const Lr=(t,e)=>[t[0]-e[0],t[1]-e[1],t[2]-e[2]],_u=t=>{const e=Math.hypot(t[0],t[1],t[2])||1;return[t[0]/e,t[1]/e,t[2]/e]};function Si(t,e,n){const s=n.height,i=Zt(90*(e.turn??0)),o=Zt(e.roll??0),r=Mi(t,e,s),a=$e(r.root,i),l=m=>Pe(Cr(Lr($e(m,i),a),-o),a),c={};for(const m of t.chains)c[m.id]=r.chains[m.id].joints3.map(l);const h=l(r.head.center),u=m=>_u(Lr(l(Pe(r.head.center,r.head.toBody(m))),h)),d=[u([1,0,0]),u([0,1,0]),u([0,0,1])],f=m=>{if("head"in m)return Pe(h,ki(d[1],r.head.ry));const y=c[m.chain];return y[Math.min(m.joint,y.length-1)]};let p=0;(n.contact??"ground")==="ground"&&(p=-Math.min(...t.contacts.map(m=>f(m)[1]))),p+=(e.lift??0)*s;const g=m=>[m[0],m[1]+p,m[2]];return{height:s,hip:g(a),chains:Object.fromEntries(Object.entries(c).map(([m,y])=>[m,y.map(g)])),head:{center:g(h),rx:r.head.rx,ry:r.head.ry,axes:d}}}function Ti(t,e,n,s){const i=n.height,o=Zt(90*(e.turn??0)),r=Mi(t,e,i),a=Si(t,e,n),l=a.hip,c=a.chains,h=a.head.center,u=S=>{if("head"in S)return Pe(h,ki(a.head.axes[1],a.head.ry));const I=c[S.chain];return I[Math.min(S.joint,I.length-1)]},d=s.toView(l),f=s.toScreen(d),p=s.toScreen([d[0]+1,d[1],d[2]]),g=Math.hypot(p.x-f.x,p.y-f.y),m=S=>{const I=s.toView(S);return{point:s.toScreen(I),depth:I[2]*g}},y={};for(const S of t.chains){const I=c[S.id].map(m);y[S.id]={id:S.id,joints3:r.chains[S.id].joints3,frames:r.chains[S.id].frames,points:I.map(v=>v.point),depths:I.map(v=>v.depth)}}const T=s.toView(h),k=s.toScreen(T),b=s.toScreen([T[0]+1,T[1],T[2]]),A=Math.hypot(b.x-k.x,b.y-k.y),M=a.head.axes.map(S=>_u(Lr(s.toView(Pe(h,S)),T))),E={center:k,depth:T[2]*g,rx:r.head.rx*A,ry:r.head.ry*A,angle:Math.atan2(M[1][0],M[1][1]),axes:M},x=t.contacts.map(S=>({spec:S,point:m(u(S)).point}));return{height:i*g,view:o,chains:y,head:E,hip:f,contacts:x,groundY:Math.max(...x.map(S=>S.point.y))}}function Fr(t,[e,n,s]){const[i,o,r]=t.axes,a=[i[0]*e*t.rx+o[0]*n*t.ry+r[0]*s*t.rx,i[1]*e*t.rx+o[1]*n*t.ry+r[1]*s*t.rx,i[2]*e*t.rx+o[2]*n*t.ry+r[2]*s*t.rx],l=Math.hypot(e,n,s)||1,c=(i[2]*e+o[2]*n+r[2]*s)/l;return{point:{x:t.center.x+a[0],y:t.center.y-a[1]},depth:t.depth+a[2],facing:c}}class Cu{positions=[];normals=[];indices=[];vertex(e,n,s,i,o,r){const a=Math.hypot(i,o,r)||1;return this.positions.push(e,n,s),this.normals.push(i/a,o/a,r/a),this.positions.length/3-1}triangle(e,n,s){this.indices.push(e,n,s)}quad(e,n,s,i){this.indices.push(e,n,s,e,s,i)}build(){return{positions:this.positions,normals:this.normals,indices:this.indices}}}function Tb(t){const e=new Map,n=[];for(let i=0;i<t.positions.length/3;i++){const o=[0,1,2].map(r=>Math.round(t.positions[i*3+r]*1e6)).join(",");e.has(o)||e.set(o,i),n.push(e.get(o))}const s=new Map;for(let i=0;i<t.indices.length/3;i++)for(let o=0;o<3;o++){const r=n[t.indices[i*3+o]],a=n[t.indices[i*3+(o+1)%3]];if(r===a)continue;const l=r<a?`${r}-${a}`:`${a}-${r}`,c=s.get(l);c?c.faces.push(i):s.set(l,{a:Math.min(r,a),b:Math.max(r,a),faces:[i]})}return[...s.values()]}const Nr=Math.PI*2;function Eb(t,e=16){const n=new Cu,s=Math.max(6,Math.round(e)),i=Math.max(3,Math.round(s/2)),o=[];for(let r=0;r<=i;r++){const a=r/i*Math.PI,l=[];for(let c=0;c<=s;c++){const h=c/s*Nr,u=Math.sin(a)*Math.sin(h),d=Math.cos(a),f=Math.sin(a)*Math.cos(h);l.push(n.vertex(u*t,d*t,f*t,u,d,f))}o.push(l)}for(let r=0;r<i;r++)for(let a=0;a<s;a++){const l=o[r][a],c=o[r+1][a],h=o[r+1][a+1],u=o[r][a+1];r>0&&n.triangle(l,c,u),r<i-1&&n.triangle(c,h,u)}return n.build()}function Hu(t,e,n,s,i){const o=t.vertex(0,n,0,0,s,0),r=Array.from({length:i},(a,l)=>{const c=l/i*Nr;return t.vertex(Math.sin(c)*e,n,Math.cos(c)*e,0,s,0)});for(let a=0;a<i;a++){const l=r[a],c=r[(a+1)%i];s===1?t.triangle(o,l,c):t.triangle(o,c,l)}}function Ru(t,e,n=24){const s=new Cu,i=Math.max(6,Math.round(n)),o=e/2,r=-e/2,a=h=>Array.from({length:i+1},(u,d)=>{const f=d/i*Nr;return s.vertex(Math.sin(f)*t,h,Math.cos(f)*t,Math.sin(f),0,Math.cos(f))}),l=a(r),c=a(o);for(let h=0;h<i;h++)s.quad(l[h],l[h+1],c[h+1],c[h]);return Hu(s,t,o,1,i),Hu(s,t,r,-1,i),s.build()}function Ei(t){const e=Array.from({length:t.indices.length/3},()=>[]);for(const n of Tb(t))for(const s of n.faces){const i=n.faces.find(o=>o!==s)??-1;e[s].push({a:n.a,b:n.b,across:i})}return{...t,faceEdges:e}}const Ai=t=>t*180/Math.PI,Mn=(t,e)=>[t[0]-e[0],t[1]-e[1],t[2]-e[2]],Dr=(t,e)=>t[0]*e[0]+t[1]*e[1]+t[2]*e[2],ls=t=>Math.hypot(t[0],t[1],t[2]),Wr=t=>{const e=ls(t)||1;return[t[0]/e,t[1]/e,t[2]/e]},xi=t=>Math.atan2(Math.sin(t),Math.cos(t));function Lu(t){const[e,n,s]=Wr(t);return{swing:Math.asin(Math.max(-1,Math.min(1,s))),spread:Math.atan2(e,-n)}}function Ab(t,e,n,s,i){const o=t.chains.find(I=>I.id===n);if(!o)throw new Error(`reach: no chain ${n} in ${t.id}`);if(o.bones.length<2||o.rest[1]>-.99)throw new Error(`reach: ${n} is not a hanging limb of two bones or more`);if(!t.withAngles)throw new Error(`reach: the ${t.id} plan cannot set angles`);const r=Rr(t,{...e,turn:0,roll:0,lift:0},{height:i.height,contact:"none"}),a=r.chains[n],l=a.joints3[0],c=ls(Mn(a.joints3[1],a.joints3[0])),h=ls(Mn(a.joints3[2],a.joints3[1])),u=o.parent?r.chains[o.parent].frames[Math.max(0,(o.at??r.chains[o.parent].joints3.length-1)-1)]:{swing:0,spread:0},d=Mn(s,l),f=Math.min(c+h-1e-6,Math.max(Math.abs(c-h)+1e-6,ls(d))),p=Wr(d),g=o.parent!==null,m=vi(o.pole??(g?[0,-.35,-1]:[0,0,1]),u);let y=Mn(m,[p[0]*Dr(m,p),p[1]*Dr(m,p),p[2]*Dr(m,p)]);ls(y)<1e-6&&(y=$e([1,0,0],0)),y=Wr(y);const T=(c*c+f*f-h*h)/(2*c*f),k=Math.sqrt(Math.max(0,1-T*T)),b=[l[0]+c*(T*p[0]+k*y[0]),l[1]+c*(T*p[1]+k*y[1]),l[2]+c*(T*p[2]+k*y[2])],A=[l[0]+p[0]*f,l[1]+p[1]*f,l[2]+p[2]*f],M=o.side??1,E=Lu(Mn(b,l)),x=Lu(Mn(A,b)),S=[{swing:Ai(xi(E.swing-u.swing)),spread:Ai(xi(E.spread-u.spread))*M},{swing:Ai(xi(x.swing-E.swing)),spread:Ai(xi(x.spread-E.spread))*M}];return t.withAngles(e,o,S)}const Fu=.34,Qt=.12,re=-.4,Ut=(t,e,n)=>t[e]??n,xb=(t,e)=>Math.max(0,t)*(1-Math.min(1,Math.max(0,e))),$b=.45,Pb=.35,Ib=.7;function vt(t,e,n){const s=f=>Math.sqrt(Math.max(0,1-f.x*f.x-f.y*f.y)),i=Fr(t,[n.x,n.y,s(n)]).facing,o=t.axes[2],r=Math.atan2(o[0],o[2]),a=Math.cos(r),l=a>=0?1:-1,c=l*Math.max(Pb,Math.abs(a)),h=l*Math.max(Ib,Math.abs(a)),u=Math.cos(t.angle),d=Math.sin(t.angle);return{facing:i,points:e.map(f=>{const p=$b*Math.sin(r)+n.x*c+(f.x-n.x)*h,g=f.y+o[1]*s(f),m=p*t.rx,y=g*t.ry;return{x:t.center.x+m*u+y*d,y:t.center.y+m*d-y*u}})}}const $i=(t,e,n,s=12)=>Array.from({length:s+1},(i,o)=>{const r=o/s,a=1-r;return{x:a*a*t.x+2*a*r*e.x+r*r*n.x,y:a*a*t.y+2*a*r*e.y+r*r*n.y}}),Pi=(t,e,n,s,i=16)=>Array.from({length:i},(o,r)=>{const a=Math.PI*2*r/i;return{x:t+Math.cos(a)*n,y:e+Math.sin(a)*s}}),cs=.05;function Ob(t,e,n,s){const i=Math.max(1,Math.min(s*.6,.14*e.rx)),o=(y,T)=>vt(e,y,T).points,r=(y,T)=>vt(e,[],{x:y,y:T}).facing,a=Ut(n,"smile",0),l=Ut(n,"blink",0),c=Ut(n,"lookX",0),h=Ut(n,"lookY",0),u=Ut(n,"browTilt",0);for(const y of[1,-1]){const T=y===1?"left":"right",k=Fu*y;if(r(k,Qt)<cs)continue;const b={x:k,y:Qt},A=xb(Ut(n,`eye.${T}`,1),l);if(A<.2){const S=a>.5?.12:-.06;t.line(o($i({x:k-.12,y:Qt},{x:k,y:Qt+S},{x:k+.12,y:Qt}),b),i)}else{if(A>1.2){const $=.13*A;t.shape(o(Pi(k,Qt,$*.85,$),b),"#ffffff",i)}const S=A>1.2?.075:.1,I=k+c*.08,v=Qt-h*.07;t.shape(o(Pi(I,v,S,S*1.1*Math.min(A,1)),b),t.ink,0)}const M=Qt+.3+Ut(n,`brow.${T}`,0)*.14+Math.max(0,A-1)*.12,E={x:k+y*.13,y:M},x={x:k-y*.13,y:M+u*.1};t.line(o([E,{x:(E.x+x.x)/2,y:(E.y+x.y)/2},x],{x:k,y:M}),i)}_b(t,e,n,i);const d={x:0,y:re};if(r(0,re)<-cs)return;const f=.25*Math.max(.3,Ut(n,"mouthWidth",1)),p=Math.min(1,Math.max(0,Ut(n,"mouth",0)));if(p<=.05){t.line(o($i({x:-f,y:re},{x:0,y:re-a*.25},{x:f,y:re}),d),i);return}const g=.3*p;let m;if(a>.3){const y=re+.05;m=[...$i({x:f,y},{x:0,y:re-g*2},{x:-f,y})]}else if(a<-.3){const y=re-g*.6;m=[...$i({x:f,y},{x:0,y:re+g*1.4},{x:-f,y})]}else m=Pi(0,re,f*.8,g);t.shape(o(m,d),t.ink,0)}const Nu="#8fd0f5",Du=(t,e,n)=>Array.from({length:18},(s,i)=>{const o=Math.PI*2*i/18,r=Math.sin(o/2);return{x:t+Math.sin(o)*n*r,y:e-n*.9+Math.cos(o)*n*1.6*(.55+.45*r)-n*.4}});function _b(t,e,n,s){const i=Math.min(1,Math.max(0,Ut(n,"blush",0))),o=Math.min(1,Math.max(0,Ut(n,"tears",0))),r=Math.min(1,Math.max(0,Ut(n,"sweat",0)));if(!(i+o+r<=.01)){for(const a of[1,-1]){const l={x:.5*a,y:-.16},c=vt(e,[],l).facing>=cs;if(i>.01&&c){const{points:u}=vt(e,Pi(l.x,l.y,.17,.1),l);if(t.shape(u,`rgba(240, 120, 140, ${(.75*i).toFixed(3)})`,0),i>.5)for(const d of[-.07,0,.07]){const f=[{x:l.x+d-.018,y:l.y-.03},{x:l.x+d+.018,y:l.y+.03}];t.line(vt(e,f,l).points,s*.3)}}const h={x:Fu*a,y:Qt};if(o>.01&&vt(e,[],h).facing>=cs){const u=.05+.04*o,d={x:h.x+.06*a,y:Qt-.2-.12*o};if(t.shape(vt(e,Du(d.x,d.y,u),d).points,Nu,s*.35),o>.6){const f=[{x:h.x+.05*a,y:Qt-.1},{x:d.x,y:d.y+u*.8}];t.line(vt(e,f,d).points,s*.3)}}}if(r>.01){const a={x:.64,y:.42};vt(e,[],a).facing>=cs&&t.shape(vt(e,Du(a.x,a.y,.05+.05*r),a).points,Nu,s*.35)}}}const Cb=15;function he(t,e){const n=Math.sqrt(Math.max(0,1-e*e));return[n*Math.sin(t),e,n*Math.cos(t)]}const Hb=([t,e,n])=>{const s=Math.hypot(t,e,n)||1;return[t/s,e/s,n/s]};function ue(t,[e,n,s]){const[i,o,r]=t.axes;return i[2]*e+o[2]*n+r[2]*s}function Lt(t,e){return Fr(t,e).point}function Ii(t,e){const n=Math.abs(t-e)%(Math.PI*2);return n>Math.PI?Math.PI*2-n:n}function Oi(t,e,n=64){const s=e.top??1,i=e.bottom??-1,o=Math.max(8,Math.ceil((s-i)*Cb)),r=p=>Math.min(s,Math.max(i,s-(s-i)*(p-1)/o)),a=p=>-Math.PI+Math.PI*2*p/n,l=(p,g)=>e.normal?e.normal(p,g):Hb(e.position(p,g)),c=o+3,h=new Float64Array(n*c),u=new Float64Array(n*c);for(let p=0;p<c;p++){const g=p===0||p===c-1,m=r(p);for(let y=0;y<n;y++){const T=p*n+y;if(g){h[T]=-1;continue}const k=a(y);h[T]=e.inside(k,m),u[T]=h[T]>-.35?ue(t,l(k,m)):0}}const d=p=>(p%n+n)%n,f=p=>{const g=n+1,m=new Float64Array(g*c);for(let $=0;$<c;$++)for(let _=0;_<=n;_++){const P=$*n+(_===n?0:_);m[$*g+_]=Math.min(h[P],p*u[P])}const y=($,_)=>m[_*g+$],T=($,_,P,C)=>{const F=y($,_),R=y(P,C),B=F===R?.5:Math.min(1,Math.max(0,F/(F-R)));return Lt(t,e.position(a($+(P-$)*B),r(_+(C-_)*B)))},k=n*c*2,b=new Int32Array(k).fill(-1),A=new Int32Array(k).fill(-1),M=new Map,E=($,_,P)=>{const C=(P*n+d(_))*2+($?1:0);return M.has(C)||M.set(C,$?T(d(_),P,d(_),P+1):T(_,P,_+1,P)),C},x=($,_)=>{b[$]===-1?b[$]=_:A[$]=_},S=($,_)=>{x($,_),x(_,$)};for(let $=0;$<c-1;$++)for(let _=0;_<n;_++){const P=$*g+_,C=(m[P]>0?8:0)|(m[P+1]>0?4:0)|(m[P+g+1]>0?2:0)|(m[P+g]>0?1:0);if(C===0||C===15)continue;const F=()=>E(!1,_,$),R=()=>E(!1,_,$+1),B=()=>E(!0,_,$),j=()=>E(!0,_+1,$);switch(C){case 1:case 14:S(B(),R());break;case 2:case 13:S(R(),j());break;case 3:case 12:S(B(),j());break;case 4:case 11:S(F(),j());break;case 6:case 9:S(F(),R());break;case 7:case 8:S(B(),F());break;case 5:case 10:{const H=(y(_,$)+y(_+1,$)+y(_+1,$+1)+y(_,$+1))/4>0;C===5===H?(S(B(),F()),S(R(),j())):(S(B(),R()),S(F(),j()));break}}}const I=[],v=new Uint8Array(k);for(const $ of M.keys()){if(v[$])continue;const _=[];let P=-1,C=$;for(;C!==-1&&!v[C];){v[C]=1,_.push(M.get(C));const F=b[C],R=A[C],B=F!==-1&&F!==P&&!v[F]?F:R!==-1&&R!==P&&!v[R]?R:-1;P=C,C=B}_.length>=3&&I.push(_)}return I};return{near:f(1),far:f(-1)}}const Wu=new WeakMap;function Br(t,e,n){let s=Wu.get(t);s||Wu.set(t,s=new Map);let i=s.get(e);return i||s.set(e,i=n()),i}function jr(t,e,n){t.save(),t.beginPath(),t.rect(-1e5,-1e5,2e5,2e5),t.ellipse(e.center.x,e.center.y,e.rx,e.ry,e.angle,0,Math.PI*2),t.clip("evenodd"),n(),t.restore()}function Bu(t,e,n,s=.04){const i=[];let o=[];return e.forEach((r,a)=>{ue(t,n[a])>s?o.push(Lt(t,r)):(o.length>=2&&i.push(o),o=[])}),o.length>=2&&i.push(o),i}const ju={color:"#6b4630",volume:.1,hairline:{front:.5,side:.12,back:-.82},sweep:0,recede:0,length:0,opening:84,texture:"smooth",textureAmount:0,quiff:0,flat:0,part:null,strands:"none",fill:"solid",ties:[],coversEars:!1},qu=1.75,qr={bald:{volume:0,hairline:{front:2,side:2,back:2}},buzzCut:{volume:0,fill:"stipple",hairline:{front:.52,side:.1,back:-.8}},crewCut:{volume:.1,texture:"spiky",textureAmount:.07,hairline:{front:.55,side:.1,back:-.8}},short:{volume:.12,texture:"spiky",textureAmount:.1,hairline:{front:.42,side:.1,back:-.82},sweep:.12},sidePart:{volume:.14,part:35,strands:"sweep",sweep:-.22,hairline:{front:.5,side:.08,back:-.82}},sideSwept:{volume:.15,part:45,strands:"sweep",sweep:-.38,hairline:{front:.42,side:.05,back:-.82}},slickBack:{volume:.12,strands:"combed",hairline:{front:.62,side:.15,back:-.8}},quiff:{volume:.12,quiff:.42,strands:"combed",hairline:{front:.6,side:.15,back:-.8}},spiky:{volume:.12,texture:"spiky",textureAmount:.34,hairline:{front:.5,side:.12,back:-.8}},undercut:{volume:.16,quiff:.18,part:40,strands:"sweep",sweep:-.15,hairline:{front:.55,side:.42,back:-.3}},curlyCrop:{volume:.14,texture:"curly",textureAmount:.12,hairline:{front:.5,side:.1,back:-.8}},afro:{volume:.5,texture:"curly",textureAmount:.12,hairline:{front:.5,side:-.1,back:-.85},coversEars:!0},wavyCrop:{volume:.16,texture:"wavy",textureAmount:.08,part:30,hairline:{front:.45,side:.05,back:-.82}},shortLocs:{volume:.16,texture:"locs",textureAmount:.1,hairline:{front:.38,side:-.25,back:-.85},strands:"hanging",coversEars:!0},flatTop:{volume:.1,flat:.42,hairline:{front:.5,side:.15,back:-.78}},receding:{volume:.14,recede:.28,strands:"thin",hairline:{front:.74,side:.1,back:-.8}},thinning:{volume:.05,strands:"thin",hairline:{front:.72,side:.05,back:-.78}},pixie:{volume:.16,texture:"spiky",textureAmount:.07,sweep:.3,hairline:{front:.32,side:-.1,back:-.82}},bob:{volume:.2,length:1.05,opening:84,sweep:.2,part:-25,hairline:{front:.34,side:.05,back:-.85},coversEars:!0},longBob:{volume:.18,length:1.35,opening:84,part:0,strands:"part",hairline:{front:.5,side:.05,back:-.85},coversEars:!0},wavyBob:{volume:.22,length:1.2,opening:84,part:18,texture:"wavy",textureAmount:.1,hairline:{front:.45,side:.05,back:-.85},coversEars:!0},shoulderStraight:{volume:.16,length:qu,opening:84,part:0,strands:"part",hairline:{front:.5,side:.05,back:-.85},coversEars:!0},shoulderWaves:{volume:.22,length:qu,opening:84,part:22,texture:"wavy",textureAmount:.12,hairline:{front:.45,side:.05,back:-.85},coversEars:!0},longStraight:{volume:.14,length:2.6,opening:84,part:0,strands:"hanging",hairline:{front:.5,side:.05,back:-.85},coversEars:!0},longWaves:{volume:.2,length:2.5,opening:84,part:20,texture:"wavy",textureAmount:.14,hairline:{front:.45,side:.05,back:-.85},coversEars:!0},longCurls:{volume:.26,length:2.5,opening:84,texture:"curly",textureAmount:.13,hairline:{front:.45,side:.05,back:-.85},coversEars:!0},longLocs:{volume:.2,length:2.6,opening:84,texture:"locs",textureAmount:.12,strands:"hanging",part:0,hairline:{front:.45,side:.05,back:-.85},coversEars:!0},lowPonytail:{volume:.12,part:0,strands:"combed",hairline:{front:.5,side:.1,back:-.82},ties:[{kind:"ponytail",at:"low",length:1.5}]},highPonytail:{volume:.12,part:18,strands:"combed",hairline:{front:.45,side:.1,back:-.78},ties:[{kind:"ponytail",at:"high",length:2}]},ponytail:{volume:.12,sweep:.2,hairline:{front:.42,side:.1,back:-.78},ties:[{kind:"ponytail",at:"high",length:1.8}]},sidePonytail:{volume:.12,part:-20,strands:"combed",hairline:{front:.45,side:.1,back:-.82},ties:[{kind:"ponytail",at:"left",length:1.5}]},topBun:{volume:.12,part:0,strands:"combed",hairline:{front:.5,side:.1,back:-.8},ties:[{kind:"bun",at:"top",size:.32}]},lowBun:{volume:.12,part:0,strands:"combed",hairline:{front:.5,side:.1,back:-.8},ties:[{kind:"bun",at:"low",size:.34}]},singleBraid:{volume:.12,part:0,strands:"combed",hairline:{front:.5,side:.1,back:-.82},ties:[{kind:"braid",at:"low",length:2.2}]},twinBraids:{volume:.12,part:0,strands:"part",hairline:{front:.5,side:.05,back:-.82},ties:[{kind:"braid",at:"left",length:1.9},{kind:"braid",at:"right",length:1.9}],coversEars:!0},braids:{volume:.12,part:0,strands:"part",hairline:{front:.5,side:.05,back:-.82},ties:[{kind:"braid",at:"left",length:1.6},{kind:"braid",at:"right",length:1.6}],coversEars:!0}},ae={black:"#22201f",brown:"#6b4630",chestnut:"#7b4a2b",auburn:"#9a4426",blond:"#d9b55a",ginger:"#c8662f",gray:"#a7a29c",white:"#ecebe7"};function Yu(t){const e=typeof t=="string"?{style:t}:t,n=e.style?qr[e.style]:{};if(e.style&&!n)throw new Error(`hair: unknown style '${e.style}'`);const{style:s,hairline:i,...o}=e;return{...ju,...n,...o,hairline:{...ju.hairline,...n.hairline,...i},ties:(o.ties??n.ties??[]).map(r=>({...r}))}}const Ku=t=>t*Math.PI/180,_i=(t,e,n)=>{const s=Math.min(1,Math.max(0,(n-t)/(e-t)));return s*s*(3-2*s)},Yr=t=>1-Math.abs(2*(t-Math.floor(t))-1);function hs(t,e){const{front:n,side:s,back:i}=t.hairline,o=(n-i)/2,r=(n+i)/2,a=(r+s)/2,l=(r-s)/2,c=Math.max(0,Math.cos(e));let h=a+o*Math.cos(e)+l*Math.cos(2*e);return h-=t.sweep*Math.sin(e)*c,h+=t.recede*Math.exp(-(((Math.abs(e)-.75)/.32)**2)),(t.texture==="spiky"||t.texture==="curly")&&(h-=t.textureAmount*.6*Yr(e*11/(Math.PI*2))*c),h}function zu(t,e,n){const s=t.textureAmount;switch(t.texture){case"spiky":return s*(Yr(e*11/(Math.PI*2))*Yr(n*2.6+.5))**1.2*_i(-.3,.4,n);case"curly":return s*Math.sqrt(Math.abs(Math.sin(e*7))*Math.abs(Math.sin(n*Math.PI*2.6)));case"wavy":return s*(.5+.5*Math.sin(e*6+n*6));case"locs":return s*Math.abs(Math.sin(e*10))**.6;default:return 0}}function Xu(t,e){const n=t.length>0,s=new Map,i=l=>{let c=s.get(l);return c===void 0&&s.set(l,c=hs(t,l)),c},o=Ku(t.opening),r=l=>t.length+(t.texture==="wavy"||t.texture==="curly"||t.texture==="locs"?.12*Math.sin(l*9):0),a=(l,c,h)=>{if(t.flat<=0||c<.45)return null;const u=(c-.45)/.55,d=Math.sqrt(1-.45*.45)*h*(1-u**5),f=.45+(1+t.flat-.45)*Math.min(1,u*1.8);return[d*Math.sin(l),f*(1+e),d*Math.cos(l)]};return{top:1,bottom:n?-(t.length+.25):-1,inside(l,c){const h=c-i(l);if(!n)return h;const u=Math.min(c+r(l),Ii(l,0)-o);return Math.max(h,u)},position(l,c){if(n&&c<0){const y=t.length<1.5?.14*_i(-t.length+.45,-t.length-.1,c):0,T=1+e+t.volume*(1-y*2.5)+zu(t,l,c)-y;return[T*Math.sin(l),c,T*Math.cos(l)]}const h=.4+.6*_i(0,.3,c-hs(t,l)),u=1+e+(t.volume+zu(t,l,c))*h,d=a(l,c,u);if(d)return d;const[f,p,g]=he(l,c),m=[f*u,p*u,g*u];if(t.quiff>0){const y=t.quiff*Math.exp(-((l/.7)**2))*_i(.15,.85,c);m[1]+=y*.7,m[2]+=y*.45}return m},normal(l,c){return n&&c<0?[Math.sin(l),0,Math.cos(l)]:he(l,c)}}}const Rb=t=>t.texture==="spiky"||t.texture==="curly"||t.texture==="locs"?104:t.texture==="wavy"?80:64;function Gu(t,e,n){return Br(t,e,()=>Oi(t,n,Rb(e)))}function Uu(t){switch(t){case"top":return{point:[0,1.02,-.12],out:[0,1,-.15]};case"high":return{point:[0,.72,-.78],out:[0,.55,-.85]};case"low":return{point:[0,-.2,-1.02],out:[0,-.1,-1]};case"left":return{point:[.82,-.32,-.45],out:[.8,-.2,-.5]};case"right":return{point:[-.82,-.32,-.45],out:[-.8,-.2,-.5]}}}function Vu(t,[e,n,s]){const i=Lt(t,[e,n,s]);return{x:i.x-t.center.x,y:i.y-t.center.y}}function Lb(t,e,n,s=16){return Array.from({length:s+1},(i,o)=>{const r=o/s,a=1-r;return{x:a*a*t.x+2*a*r*e.x+r*r*n.x,y:a*a*t.y+2*a*r*e.y+r*r*n.y}})}function Fb(t,e,n,s){const i=t.ry,o=(e.length??1.8)*i,r=Vu(t,s),a=Math.hypot(r.x,r.y)||1,l=e.at==="high"||e.at==="low"||e.at==="top"?Vu(t,[.95,0,0]):{x:0},c=e.kind==="braid"?.15:.5,h={x:n.x+r.x/a*i*c+l.x*.9,y:n.y+r.y/a*i*c*.6},u={x:n.x+r.x/a*i*c*.6+l.x*1.3,y:n.y+o};return Lb(n,h,u)}const Kr=t=>Math.max(1,t*.5),Ju=(t,e)=>Math.max(.8,Math.min(t*.4,.1*e.rx));function Zu(t,e,n,s,i){const{point:o,out:r}=Uu(s.at),a=1+n.volume,l=Lt(e,[o[0]*a,o[1]*a,o[2]*a]),c=Kr(i),h=Ju(i,e);if(s.kind==="bun"){const p=s.size??.32,g=Lt(e,[o[0]*a+r[0]*p,o[1]*a+r[1]*p,o[2]*a+r[2]*p]);t.ellipse(g.x,g.y,p*e.rx,p*e.ry,e.angle,n.color,c);const m=p*e.rx*.55;t.line(Array.from({length:9},(y,T)=>{const k=-.4+T/8*Math.PI*1.3;return{x:g.x+Math.cos(k)*m,y:g.y+Math.sin(k)*m*.8}}),h);return}const u=Fb(e,s,l,r),d=(s.size??(s.kind==="braid"?.2:.34))*e.rx*2;if(s.kind==="ponytail")t.shape(oe(u,d,d*.15),n.color,c),t.line(u.slice(3,u.length-3),h);else{const g=u.slice(0,u.length-3);for(let T=0;T<7;T++){const k=g[Math.floor(T/7*(g.length-1))],b=g[Math.floor((T+1)/7*(g.length-1))],A=Math.atan2(b.y-k.y,b.x-k.x),M=Math.hypot(b.x-k.x,b.y-k.y),E=d*(1-T/(7*2.2)),x=(T%2===0?1:-1)*.35,S={x:(k.x+b.x)/2,y:(k.y+b.y)/2};t.ellipse(S.x,S.y,M*.62,E*.5,A+x,n.color,c*.8)}const m=g[g.length-1],y=u[u.length-1];t.shape(oe([m,y],d*.7,d*.2),n.color,c*.8)}const f=u[s.kind==="braid"?u.length-4:2];t.ellipse(f.x,f.y,d*.32,d*.22,e.angle,n.color,c)}function Qu(t,e){return ue(t,Uu(e.at).out)<-.2}function Nb(t){const e=(i,o,r=0,a=14)=>Array.from({length:a+1},(l,c)=>{const h=c/a;return[i[0]+(o[0]-i[0])*h+r*Math.sin(Math.PI*h),i[1]+(o[1]-i[1])*h]}),n=Ku(t.part??0),s=i=>hs(t,i)+.04;switch(t.strands){case"part":return[e([n,s(n)],[n,.97])];case"sweep":{const i=Math.sign(t.sweep||-1),o=[.9,.72,.55].map((r,a)=>{const l=n+i*(.6+a*.35);return e([n,r],[l,Math.max(s(l)+.05,r-.35)],.05*i)});return[e([n,s(n)],[n,.97]),...o]}case"combed":return[-.75,-.35,.35,.75].map(i=>e([i,s(i)+.02],[i*.3,.86]));case"thin":return[-.5,.05,.6].map(i=>e([i,s(i)+.02],[i*.5,.95],.12));case"hanging":{const i=t.length>0?-t.length+.25:-.4,o=[-2.6,-2,-1.4,1.4,2,2.6,3.05].map(r=>e([r,hs(t,r)<.9?.6:.9],[r,i],0));return t.part!==null&&o.push(e([n,s(n)],[n,.97])),o}default:return[]}}function Db(t,e,n,s,i){if(s.fill==="stipple"||s.hairline.front>1.5)return;const o=i.lineWidth*.45/n.rx,{far:r}=Gu(n,s,Xu(s,o));jr(e,n,()=>{for(const a of s.ties)Qu(n,a)&&Zu(t,n,s,a,i.lineWidth);for(const a of r)t.shape(a,s.color,Kr(i.lineWidth))})}function t0(t,e,n,s){if(n.hairline.front>1.5)return;const i=s.lineWidth*.45/e.rx,o=Xu(n,i),r=Ju(s.lineWidth,e);if(n.fill==="stipple"){for(let c=.97;c>-1;c-=.17)for(let h=-Math.PI;h<Math.PI;h+=.27){const u=Math.round(c*100)%2*.13;if(o.inside(h+u,c)<.02)continue;const d=he(h+u,c);if(ue(e,d)<.12)continue;const f=Lt(e,d);t.dot(f.x,f.y,r*.4)}return}const{near:a}=Gu(e,n,o),l=Kr(s.lineWidth);for(const c of a)t.shape(c,n.color,l);for(const c of Nb(n)){const h=c.map(([d,f])=>{const[p,g,m]=o.position(d,f);return[p*.985,g*.985,m*.985]}),u=c.map(([d,f])=>o.normal(d,f));for(const d of Bu(e,h,u,.12))t.line(d,r)}for(const c of n.ties)Qu(e,c)||Zu(t,e,n,c,s.lineWidth)}const e0=.35,zr=t=>({centre:[t*.98,-.02,-.08],out:[t,0,-.12]});function n0(t,e,n,s,i){const{centre:o,out:r}=zr(n),a=ue(e,r),l=Math.max(1,s.lineWidth*.55),c=s.skin==="none"?null:s.skin,h=e.ry*.27;if(!i){const m=Lt(e,[o[0]*1.06,o[1],o[2]]);t.ellipse(m.x,m.y,e.rx*.17,h,e.angle,c,l);return}const u=Lt(e,o),d=e.rx*(.12+.08*a);t.ellipse(u.x,u.y,d,h,e.angle,c,l);const f=Math.cos(e.angle),p=Math.sin(e.angle),g=Array.from({length:9},(m,y)=>{const T=-Math.PI*.55+y/8*Math.PI*1.1,k=Math.cos(T)*d*.45*-n,b=Math.sin(T)*h*.55;return{x:u.x+k*f-b*p,y:u.y+k*p+b*f}});t.line(g,Math.max(.8,l*.7))}function Wb(t,e,n,s){jr(e,n,()=>{for(const i of[1,-1])ue(n,zr(i).out)<e0&&n0(t,n,i,s,!1)})}function Bb(t,e,n){for(const s of[1,-1])ue(e,zr(s).out)>=e0&&n0(t,e,s,n,!0)}const Xr={cleanShaven:{moustache:"none",beard:"none"},stubble:{moustache:"none",beard:"stubble"},pencilMoustache:{moustache:"pencil",beard:"none"},shortMoustache:{moustache:"short",beard:"none"},chevron:{moustache:"chevron",beard:"none"},handlebar:{moustache:"handlebar",beard:"none"},walrus:{moustache:"walrus",beard:"none"},goatee:{moustache:"none",beard:"goatee"},vanDyke:{moustache:"chevron",beard:"goatee"},circleBeard:{moustache:"short",beard:"circle"},shortBoxed:{moustache:"short",beard:"boxed"},fullBeard:{moustache:"chevron",beard:"full"},longBeard:{moustache:"walrus",beard:"long"},roundedBeard:{moustache:"chevron",beard:"rounded"},pointedBeard:{moustache:"chevron",beard:"pointed"},chinStrap:{moustache:"none",beard:"chinStrap"},soulPatch:{moustache:"none",beard:"soulPatch"},sideburns:{moustache:"none",beard:"sideburns"},muttonChops:{moustache:"none",beard:"muttonChops"},moustacheStubble:{moustache:"short",beard:"stubble"}};function s0(t,e){const n=typeof t=="string"?{style:t}:t,s=n.style?Xr[n.style]:void 0;if(n.style&&!s)throw new Error(`facialHair: unknown style '${n.style}'`);return{color:n.color??e??"#6b4630",moustache:n.moustache??s?.moustache??"none",beard:n.beard??s?.beard??"none"}}const Ie=t=>t*Math.PI/180,Ci=(t,e,n)=>{const s=Math.min(1,Math.max(0,(n-t)/(e-t)));return s*s*(3-2*s)},i0={goatee:{top:[-.55,-.55],reach:22,band:0,length:.22,shape:"point",volume:.06,aroundMouth:!1},circle:{top:[-.24,-.3],reach:42,band:0,length:.08,shape:"round",volume:.06,aroundMouth:!0},boxed:{top:[-.38,.02],reach:100,band:0,length:.18,shape:"square",volume:.08,aroundMouth:!0},full:{top:[-.36,.05],reach:100,band:0,length:.32,shape:"round",volume:.12,aroundMouth:!0},rounded:{top:[-.36,.05],reach:100,band:0,length:.55,shape:"round",volume:.14,aroundMouth:!0},pointed:{top:[-.36,.05],reach:100,band:0,length:.8,shape:"point",volume:.12,aroundMouth:!0},long:{top:[-.36,.05],reach:100,band:0,length:1.4,shape:"round",volume:.14,aroundMouth:!0},chinStrap:{top:[-.68,.05],reach:100,band:.18,length:0,shape:"round",volume:.04,aroundMouth:!1},sideburns:{top:[.08,.08],reach:100,band:.42,length:0,shape:"round",volume:.05,aroundMouth:!1},muttonChops:{top:[.08,.08],reach:100,band:.75,length:0,shape:"round",volume:.08,aroundMouth:!1}},jb=(t,e)=>{const n=Ci(Ie(48),Ie(100),Ii(e,0));return t.top[0]+(t.top[1]-t.top[0])*n},qb=t=>t==="sideburns"||t==="muttonChops";function Gr(t,e){const n=i0[t];if(!n)return null;const s=Ie(n.reach),i=o=>{const r=Ii(o,0);return n.shape==="point"?Math.exp(-((r/.42)**2)):n.shape==="square"?1-Ci(Ie(45),Ie(85),r):Math.cos(Math.min(r,Math.PI/2))**.7};return{top:Math.max(n.top[0],n.top[1])+.05,bottom:-1,inside(o,r){const a=Ii(o,0),l=jb(n,o);let c=Math.min(l-r,s-a);if(n.band>0&&(c=Math.min(c,r-(l-n.band))),qb(t)){const h=t==="muttonChops"?Ie(70)-Ie(22)*Ci(.08,-.6,r):Ie(72);c=Math.min(c,a-h)}return c},position(o,r){const[a,l,c]=he(o,r),h=1+e+n.volume,u=n.length*i(o)*Ci(-.45,-1,r);return[a*h,l*h-u,c*h+u*.25]},normal:(o,r)=>he(o,r)}}function Yb(t){const n=s=>s.map(([i,o])=>({x:i,y:-.24+o}));switch(t){case"short":return n([[-.17,-.02],[-.1,.04],[0,.03],[.1,.04],[.17,-.02],[.08,-.05],[0,-.03],[-.08,-.05]]);case"chevron":return n([[-.28,-.1],[-.16,.05],[0,.07],[.16,.05],[.28,-.1],[.12,-.08],[0,-.06],[-.12,-.08]]);case"walrus":return n([[-.38,-.2],[-.3,.02],[-.12,.09],[0,.07],[.12,.09],[.3,.02],[.38,-.2],[.2,-.13],[0,-.11],[-.2,-.13]]);case"handlebar":return n([[-.24,-.03],[-.12,.04],[0,.03],[.12,.04],[.24,-.03],[.1,-.05],[0,-.03],[-.1,-.05]]);default:return null}}const us=t=>Math.max(1,t*.45);function Kb(t,e,n,s){for(let i=.1;i>-1;i-=.13)for(let o=-Math.PI/1.7;o<Math.PI/1.7;o+=.2){const r=Math.round(i*100)%2*.1;if(n.inside(o+r,i)<.02)continue;const a=he(o+r,i);if(ue(e,a)<.15)continue;const l=Lt(e,a);t.dot(l.x,l.y,s)}}function zb(t,e,n,s,i){const o=s.beard==="stubble"?null:Gr(s.beard,i.lineWidth*.45/n.rx);if(!o)return;const{far:r}=Br(n,s,()=>Oi(n,o));jr(e,n,()=>{for(const a of r)t.shape(a,s.color,us(i.lineWidth))})}function Xb(t,e,n,s,i){if(n.beard==="none")return;const o=s.lineWidth*.45/e.rx;if(n.beard==="stubble"){Kb(t,e,Gr("full",o),Math.max(.5,s.lineWidth*.09));return}if(n.beard==="soulPatch"){const l=[{x:-.05,y:-.55},{x:.05,y:-.55},{x:0,y:-.68}],{points:c,facing:h}=vt(e,l,{x:0,y:-.6});h>-.05&&t.shape(c,n.color,us(s.lineWidth)*.7);return}const r=Gr(n.beard,o);if(!r)return;const{near:a}=Br(e,n,()=>Oi(e,r));for(const l of a)t.shape(l,n.color,us(s.lineWidth));if(i0[n.beard]?.aroundMouth){const l=.27*Math.max(.3,i),c=Array.from({length:20},(d,f)=>{const p=Math.PI*2*f/20;return{x:Math.cos(p)*l,y:-.42+Math.sin(p)*.13}}),{points:h,facing:u}=vt(e,c,{x:0,y:-.42});u>-.05&&t.shape(h,s.skin==="none"?"#ffffff":s.skin,0)}}function Gb(t,e,n,s){if(n.moustache==="none")return;const i={x:0,y:-.24};if(n.moustache==="pencil"){const l=[-.2,-.1,0,.1,.2].map(u=>({x:u,y:-.25+.03*Math.cos(u/.2*Math.PI)})),{points:c,facing:h}=vt(e,l,i);h>-.05&&t.line(c,Math.max(1,s.lineWidth*.32));return}const o=Yb(n.moustache);if(!o)return;const{points:r,facing:a}=vt(e,o,i);if(!(a<=-.05)&&(t.shape(r,n.color,us(s.lineWidth)*.8),n.moustache==="handlebar"))for(const l of[1,-1]){const c=Array.from({length:10},(h,u)=>{const d=-Math.PI/2+u/9*Math.PI*1.4;return{x:l*(.27+.05*Math.cos(d)),y:-.21+.05*(1+Math.sin(d))}});c.unshift({x:l*.22,y:-.27}),t.line(vt(e,c,i).points,us(s.lineWidth)*.8)}}const Ur={round:!0,square:!0,sunglasses:!0};function o0(t){const n=(typeof t=="string"?{style:t}:t).style??"round";if(!(n in Ur))throw new Error(`glasses: unknown style '${n}'`);return{style:n}}const r0=.34,le=.12,Ub=.05;function Vb(t,e){return Array.from({length:28},(s,i)=>{const o=Math.PI*2*i/28;if(t==="round")return{x:e+Math.cos(o)*.2,y:le+Math.sin(o)*.19};const r=Math.cos(o),a=Math.sin(o),l=t==="sunglasses"?.22:.21,c=t==="sunglasses"?.17:.16;return{x:e+Math.sign(r)*Math.abs(r)**.45*l,y:le-.01+Math.sign(a)*Math.abs(a)**.45*c}})}function Jb(t,e,n,s){const i=Math.max(1,Math.min(s.lineWidth*.5,.11*e.rx)),o=[];for(const r of[1,-1]){const a=r0*r,{points:l,facing:c}=vt(e,Vb(n.style,a),{x:a,y:le});if(c<Ub)continue;o.push(r),t.shape(l,n.style==="sunglasses"?"#1f2328":null,i);const h=[r*.97,le+.02,-.1];if(ue(e,[r,0,0])>.15){const u=vt(e,[{x:a+r*.21,y:le+.02}],{x:a,y:le}).points[0];t.line([u,Lt(e,h)],i*.9)}}if(o.length===2){const r=[{x:r0-.2,y:le+.02},{x:0,y:le+.07},{x:-.14,y:le+.02}];t.line(vt(e,r,{x:0,y:le}).points,i)}}const Hi={cap:{color:"#d64535",brim:[.36,.16],height:1,peak:.7,detail:"seams"},beanie:{color:"#3a6ea5",brim:[.3,.12],height:1.08,detail:"fold"},hardHat:{color:"#f2c230",brim:[.34,.22],height:1.12,ring:.16,detail:"ridge"},sunHat:{color:"#e3c98f",brim:[.36,.3],height:1.02,ring:.62,detail:"band"},bowler:{color:"#2f2b2a",brim:[.36,.28],height:1.15,ring:.2,detail:"band"}};function a0(t){const e=typeof t=="string"?{style:t}:t,n=e.style??"cap",s=Hi[n];if(!s)throw new Error(`hat: unknown style '${n}'`);return{style:n,color:e.color??s.color}}const Xe=(t,e)=>t.brim[1]+(t.brim[0]-t.brim[1])*(1+Math.cos(e))/2;function Zb(t,e){return{top:1,bottom:Math.min(...t.brim)-.05,inside:(n,s)=>s-Xe(t,n),position(n,s){const[i,o,r]=he(n,s),a=Xe(t,n),l=s>a?(o-a)*(t.height-1):0;return[i*e,o*e+l,r*e]},normal:(n,s)=>he(n,s)}}function Qb(t,e,n){const i=(o,r,a)=>{const l=Xe(e,o)*n-a;return[Math.sin(o)*r,l,Math.cos(o)*r]};if(e.peak){const o=[],r=[];for(let a=0;a<=24;a++){const l=(-80+160*a/24)*(Math.PI/180),c=e.peak*Math.cos(l)**.6;o.push(Lt(t,[Math.sin(l)*(n+c*.25),Xe(e,l)*n-.07*Math.cos(l),Math.cos(l)*(n+c)])),r.push(Lt(t,i(l,n,0)))}return[...o,...r.reverse()]}return e.ring?Array.from({length:48},(o,r)=>Lt(t,i(Math.PI*2*r/48,n+e.ring,.07))):null}function tw(t){const e=s=>Array.from({length:13},(i,o)=>[s,Xe(t,s)+(.97-Xe(t,s))*o/12]),n=s=>Array.from({length:49},(i,o)=>{const r=-Math.PI+Math.PI*2*o/48;return[r,Xe(t,r)+s]});switch(t.detail){case"seams":return[e(.55),e(-.55)];case"fold":return[n(.2)];case"ridge":return[e(0),e(Math.PI)];case"band":return[n(.12)]}}function l0(t,e,n,s){const i=Hi[n.style],r=1+s.lineWidth*.45/e.rx+Math.max(.05,Math.min(.3,s.hairVolume)+.04),a=Math.max(1,s.lineWidth*.5),l=Qb(e,i,r);l&&t.shape(l,n.color,a);const c=Zb(i,r),{near:h,far:u}=Oi(e,c);for(const f of[...u,...h])t.shape(f,n.color,a);const d=Math.max(.8,a*.7);for(const f of tw(i)){const p=f.map(([m,y])=>{const[T,k,b]=c.position(m,y);return[T*.99,k*.99,b*.99]}),g=f.map(([m,y])=>he(m,y));for(const m of Bu(e,p,g,.1))t.line(m,d)}if(i.detail==="seams"){const f=Lt(e,[0,r*1.01,0]);t.dot(f.x,f.y,a*.9)}}function c0(t){const e=t.hair?Yu(t.hair):null;return{hair:e,facialHair:t.facialHair?s0(t.facialHair,e?.color):null,glasses:t.glasses?o0(t.glasses):null,hat:t.hat?a0(t.hat):null,ears:t.ears??!1}}const h0=t=>!t.hair&&!t.facialHair&&!t.glasses&&!t.hat&&!t.ears,u0=t=>t.axes[2][2]<-.3,d0=t=>t.ears&&!t.hair?.coversEars;function f0(t,e,n,s,i,o){h0(n)||(n.hair&&Db(e,t,s,n.hair,o),n.facialHair&&zb(e,t,s,n.facialHair,o),d0(n)&&Wb(e,t,s,o))}function ew(t,e,n,s,i,o,r){if(h0(n)){r();return}const a=u0(s);d0(n)&&Bb(e,s,o),n.hair&&!a&&t0(e,s,n.hair,o),n.facialHair&&Xb(e,s,n.facialHair,o,i.mouthWidth??1),r(),n.facialHair&&Gb(e,s,n.facialHair,o),n.glasses&&Jb(e,s,n.glasses,o),n.hat&&!a&&l0(e,s,n.hat,{lineWidth:o.lineWidth,hairVolume:n.hair?.volume??0})}function g0(t,e,n,s,i,o){u0(s)&&(n.hair&&t0(e,s,n.hair,o),n.hat&&l0(e,s,n.hat,{lineWidth:o.lineWidth,hairVolume:n.hair?.volume??0}))}const p0=(t,e,n)=>t.slice(Math.floor((t.length-1)*e),Math.ceil((t.length-1)*n)+1),Vt=(t,e,n)=>({x:t.x+(e.x-t.x)*n,y:t.y+(e.y-t.y)*n});function nw(t){return Vr(t,t.parts["leg.left"].depth)>Vr(t,t.parts["leg.right"].depth)?"left":"right"}const Vr=(t,e)=>Math.abs(e)<.01*t.height?0:e,m0=t=>Vr(t,Math.max(t.parts["leg.left"].depth,t.parts["leg.right"].depth))>0,Ri=t=>Math.cos(t.turn*Math.PI/2);function y0(t={}){const e=t.shirt??"#e2493b",n=t.trousers??"#24476b",s=t.sleeves??"short",i=t.bottom??"trousers",o=t.over==="labCoat",r=t.overColor??(o?"#f4f6f8":"#d8b48a"),a=M=>M.lineWidth*.45,l=(M,E,x)=>{const S=M.parts[`leg.${x}`].points;if(i!=="skirt"){if(i==="shorts"){const I=p0(S,0,.5);E.shape(oe(I,M.height*.085,M.height*.07),n,a(M));return}E.shape(oe(S,M.height*.08,M.height*.05),n,a(M))}},c=M=>{const E=M.chains.spine,x=E[0],S=E[E.length-1],I={x:x.x-(S.x-x.x)*.25,y:x.y-(S.y-x.y)*.25};return{hip:x,top:S,below:I,line:[I,...M.parts.spine.points]}},h=(M,E)=>{E.shape(oe(c(M).line,M.height*.15,M.height*.14),e,a(M))},u=(M,E)=>{const{hip:x,top:S}=c(M),I=Vt(x,S,.18),v=[M.points["knee.left"],M.points["knee.right"]],$=Vt(x,{x:(v[0].x+v[1].x)/2,y:(v[0].y+v[1].y)/2},1.05),_=M.height*.075,P=Math.max(M.height*.13,Math.abs(v[0].x-v[1].x)/2+M.height*.08),C=$.x-I.x,F=$.y-I.y,R=Math.hypot(C,F)||1,B={x:-F/R,y:C/R};E.shape([{x:I.x+B.x*_,y:I.y+B.y*_},{x:$.x+B.x*P,y:$.y+B.y*P},{x:$.x-B.x*P,y:$.y-B.y*P},{x:I.x-B.x*_,y:I.y-B.y*_}],n,a(M))},d=(M,E)=>{const x=Ri(M);if(x<.2)return;const{top:S,hip:I}=c(M),v={x:(I.x-S.x)*.12,y:(I.y-S.y)*.12},$=M.height*.045*x;for(const _ of[-1,1])E.shape([{x:S.x+_*$*.2,y:S.y+v.y*.1},{x:S.x+_*$*1.3,y:S.y-v.y*.1},{x:S.x+_*$*.6+v.x,y:S.y+v.y}],e,a(M)*.8)},f=(M,E,x)=>{const S=Ri(M);if(S<.25)return;const{top:I,hip:v}=c(M),$=Math.sin(M.turn*Math.PI/2)*M.height*.03,_=R=>({x:Vt(I,v,R).x+$,y:Vt(I,v,R).y}),P=M.height*.022*S,C=_(.08),F=_(.62);E.shape([{x:C.x-P,y:C.y-P},{x:C.x+P,y:C.y-P},{x:C.x+P*.6,y:C.y+P},{x:C.x-P*.6,y:C.y+P}],x,a(M)*.7),E.shape([{x:C.x-P*.6,y:C.y+P},{x:C.x+P*.6,y:C.y+P},{x:F.x+P*1.4,y:F.y-P*2},F,{x:F.x-P*1.4,y:F.y-P*2}],x,a(M)*.7)},p=(M,E)=>{const x=Ri(M),{top:S,hip:I}=c(M),v=Vt(I,S,.72),$=[M.points["knee.left"],M.points["knee.right"]],_=Vt(I,{x:($[0].x+$[1].x)/2,y:($[0].y+$[1].y)/2},.9),P=Math.sin(M.turn*Math.PI/2)*M.height*.04;if(x<.15){const R=Vt(I,S,.2);x<-.3&&E.line([{x:R.x-M.height*.05,y:R.y},{x:R.x+M.height*.05,y:R.y}],a(M));return}const C=M.height*.075*x,F=Vt(I,S,.2);E.shape([{x:v.x+P-C*.7,y:v.y},{x:v.x+P+C*.7,y:v.y},{x:F.x+P+C,y:F.y},{x:_.x+P+C*1.15,y:_.y},{x:_.x+P-C*1.15,y:_.y},{x:F.x+P-C,y:F.y}],r,a(M)),E.line([{x:v.x+P-C*.6,y:v.y},{x:S.x-C*.2,y:S.y},{x:v.x+P+C*.6,y:v.y}],a(M)*.8)},g=(M,E,x)=>{const{top:S,hip:I}=c(M),v=[M.points["knee.left"],M.points["knee.right"]],$=Vt(I,{x:(v[0].x+v[1].x)/2,y:(v[0].y+v[1].y)/2},.95);x?E.shape(oe([Vt(S,I,.8),I,$],M.height*.145,M.height*.17),r,a(M)):E.shape(oe([S,Vt(S,I,.5),I],M.height*.14,M.height*.15),r,a(M));const _=Ri(M);if(_>.2){const P=Math.sin(M.turn*Math.PI/2)*M.height*.03,[C,F]=x?[I,$]:[S,I];if(E.line([{x:C.x+P,y:C.y},{x:F.x+P,y:F.y}],a(M)*.8),!x){const R=Vt(S,I,.35),B=M.height*.025*_;E.shape([{x:R.x+P-B*2.4,y:R.y},{x:R.x+P-B*.6,y:R.y},{x:R.x+P-B*.6,y:R.y+B*1.6},{x:R.x+P-B*2.4,y:R.y+B*1.6}],r,a(M)*.6)}}},m=(M,E,x,S,I)=>{const v=M.parts[`arm.${x}`].points,$=v[0],_=M.chains.spine[M.chains.spine.length-1],C=[{x:$.x+(_.x-$.x)*.45,y:$.y+(_.y-$.y)*.45},...p0(v,0,I)],F=oe(C,M.height*.085,M.height*(I>.6?.045:.06)),R=C.length,B=F.slice(0,R),j=F.slice(R).reverse();E.shape(F,S,0);const H=O=>Math.hypot(O[1].x-_.x,O[1].y-_.y),[N,D]=H(B)>H(j)?[B,j]:[j,B];E.line(N.slice(1),a(M)),E.line(D.slice(Math.ceil(R*.45)),a(M)),E.line([B[R-1],j[R-1]],a(M))},y=o?r:e,T=o||s==="long"?.95:.45,k=o||s!=="none",b=(M,E)=>{i==="skirt"&&u(M,E),o&&g(M,E,!0),t.over==="apron"&&p(M,E)},A=M=>(E,x,S)=>{l(x,S,M),nw(x)===M&&m0(x)&&b(x,S)};return{parts:{"leg.left":{over:A("left")},"leg.right":{over:A("right")},spine:{over:(M,E,x)=>{h(E,x),t.collar&&d(E,x),t.tie&&f(E,x,t.tie),o&&g(E,x,!1),m0(E)||b(E,x)}},"arm.left":{over:k?(M,E,x)=>m(E,x,"left",y,T):void 0},"arm.right":{over:k?(M,E,x)=>m(E,x,"right",y,T):void 0}}}}const Jr={mug:{color:"#e2493b",hands:"one"},phone:{color:"#2b2f36",hands:"one"},book:{color:"#3a6ea5",hands:"either"},bag:{color:"#e9d8b4",hands:"one"},briefcase:{color:"#6b4630",hands:"one"},umbrella:{color:"#3c9a6e",hands:"one"},broom:{color:"#c8963e",hands:"one"},parcel:{color:"#c9a06a",hands:"both"}};function b0(t){const e={};for(const n of["left","right","both"]){const s=t[n];if(!s)continue;const i=typeof s=="string"?s:s.item,o=Jr[i];if(!o)throw new Error(`holding: unknown item '${i}'`);if(n==="both"&&o.hands==="one")throw new Error(`holding: a ${i} is held in one hand ('left' or 'right'), not 'both'`);if(n!=="both"&&o.hands==="both")throw new Error(`holding: a ${i} is held in both hands ('both')`);e[n]={item:i,color:(typeof s=="object"?s.color:void 0)??o.color}}return e}function Li(t,e){const n=t.chains[`arm.${e}`],s=n[n.length-1],i=n[n.length-2],o=Math.hypot(s.x-i.x,s.y-i.y)||1,r={x:(s.x-i.x)/o,y:(s.y-i.y)/o},a=t.lineWidth*.5;return{point:{x:s.x+r.x*a,y:s.y+r.y*a},along:r,depth:t.parts[`arm.${e}`]?.depth??0}}function ds(t,e,n,s=0){const i=Math.cos(s),o=Math.sin(s);return[[-e/2,-n/2],[e/2,-n/2],[e/2,n/2],[-e/2,n/2]].map(([r,a])=>({x:t.x+r*i-a*o,y:t.y+r*o+a*i}))}const fs=(t,e,n,s,i=12)=>Array.from({length:i+1},(o,r)=>{const a=n+(s-n)*r/i;return{x:t.x+Math.cos(a)*e,y:t.y+Math.sin(a)*e}});function Zr(t,e,n,s,i,o=1,r){const{point:a,along:l}=n,c=s/300;switch(e.item){case"mug":{const h=ds({x:a.x,y:a.y-4*c},20*c,24*c);t.line(fs({x:a.x+10*c*Math.sign(o||1),y:a.y-4*c},7*c,-Math.PI/2,Math.PI/2).map(u=>({x:a.x+(u.x-a.x)*Math.sign(o||1),y:u.y})),i),t.shape(h,e.color,i);return}case"phone":{const h=Math.atan2(l.y,l.x)-Math.PI/2;t.shape(ds(a,13*c,24*c,h),e.color,i),t.shape(ds(a,9*c,17*c,h),"#8fd0f5",0);return}case"book":{const h=26*c,u=34*c;t.shape([{x:a.x,y:a.y-u/2},{x:a.x-h,y:a.y-u/2-3*c},{x:a.x-h,y:a.y+u/2-3*c},{x:a.x,y:a.y+u/2}],e.color,i),t.shape([{x:a.x,y:a.y-u/2},{x:a.x+h,y:a.y-u/2-3*c},{x:a.x+h,y:a.y+u/2-3*c},{x:a.x,y:a.y+u/2}],e.color,i);for(const d of[-1,1])for(const f of[.3,.5,.7]){const p=a.y-u/2+u*f;t.line([{x:a.x+d*5*c,y:p},{x:a.x+d*(h-5*c),y:p-2*c}],Math.max(.8,i*.5))}return}case"bag":{const h=a.y+10*c;t.line([{x:a.x-9*c,y:h},{x:a.x-5*c,y:a.y-2*c},{x:a.x+5*c,y:a.y-2*c},{x:a.x+9*c,y:h}],i),t.shape([{x:a.x-17*c,y:h},{x:a.x+17*c,y:h},{x:a.x+20*c,y:h+40*c},{x:a.x-20*c,y:h+40*c}],e.color,i);return}case"briefcase":{t.line(fs({x:a.x,y:a.y+6*c},7*c,Math.PI,Math.PI*2),i),t.shape(ds({x:a.x,y:a.y+22*c},46*c,32*c),e.color,i),t.line([{x:a.x-23*c,y:a.y+14*c},{x:a.x+23*c,y:a.y+14*c}],Math.max(.8,i*.6));return}case"umbrella":{const h=78*c,u=(r??a.y-120*c)-14*c,d={x:a.x,y:Math.min(a.y-60*c,u-h*.55)};t.line([{x:a.x,y:a.y+10*c},d],i),t.line(fs({x:a.x+5*c,y:a.y+10*c},5*c,Math.PI,0,8),i);const f=[...fs({x:d.x,y:d.y+h*.55},h,Math.PI,Math.PI*2,24)],p=[];for(let g=4;g>=0;g--){const m=d.x-h+2*h*g/5;p.push(...fs({x:m+h/5,y:d.y+h*.55},h/5,0,-Math.PI,6).reverse())}t.shape([...f,...p],e.color,i);return}case"broom":{const h={x:l.x*.4+.25*Math.sign(o||1),y:Math.max(.6,l.y)},u=Math.hypot(h.x,h.y),d={x:h.x/u,y:h.y/u},f={x:a.x-d.x*40*c,y:a.y-d.y*40*c},p={x:a.x+d.x*120*c,y:a.y+d.y*120*c};t.line([f,p],i*1.1);const g={x:-d.y,y:d.x},m=[{x:p.x+g.x*6*c,y:p.y+g.y*6*c},{x:p.x-g.x*6*c,y:p.y-g.y*6*c},{x:p.x-g.x*16*c+d.x*34*c,y:p.y-g.y*16*c+d.y*34*c},{x:p.x+g.x*16*c+d.x*34*c,y:p.y+g.y*16*c+d.y*34*c}];t.shape(m,e.color,i);return}case"parcel":{const h={x:a.x,y:a.y-6*c};t.shape(ds(h,50*c,40*c),e.color,i),t.line([{x:h.x-25*c,y:h.y-6*c},{x:h.x+25*c,y:h.y-6*c}],Math.max(.8,i*.7)),t.line([{x:h.x,y:h.y-20*c},{x:h.x,y:h.y+20*c}],Math.max(.8,i*.7));return}}}const Qr=(t,e)=>(t[`held.${e}`]??1)>=.5,w0=t=>Math.sin(t*Math.PI/2);function k0(t){const e=o=>Math.max(1,o.lineWidth*.45),n=o=>(r,a,l,c,h)=>{const u=t[o];u&&Qr(h??{},o)&&Zr(l,u,Li(a,o),a.height,e(a),w0(a.turn),a.head.center.y-a.head.ry)},s=(o,r,a,l,c)=>{const h=t.both;if(!h||!Qr(c??{},"both"))return;const u=Li(r,"left"),d=Li(r,"right"),f={point:{x:(u.point.x+d.point.x)/2,y:(u.point.y+d.point.y)/2},along:{x:(u.along.x+d.along.x)/2,y:(u.along.y+d.along.y)/2},depth:(u.depth+d.depth)/2};Zr(a,h,f,r.height,e(r),w0(r.turn),r.head.center.y-r.head.ry)},i={parts:{}};if(t.left&&(i.parts["arm.left"]={over:n("left")}),t.right&&(i.parts["arm.right"]={over:n("right")}),t.both){const o=r=>(a,l,c,h,u)=>{const d=r==="left"?"right":"left";(r==="left"?l.parts["arm.left"].depth>=l.parts["arm.right"].depth:l.parts["arm.right"].depth>l.parts[`arm.${d}`].depth)&&s(a,l,c,h,u)};for(const r of["left","right"])i.parts[`arm.${r}`]={...i.parts[`arm.${r}`],over:sw(i.parts[`arm.${r}`]?.over,o(r))}}return i}function sw(t,e){return t?(n,s,i,o,r)=>{t(n,s,i,o,r),e(n,s,i,o,r)}:e}function v0(t,e){const n=(i,o)=>i&&o?(r,a,l,c,h)=>{i(r,a,l,c,h),o(r,a,l,c,h)}:i??o,s={};for(const i of new Set([...Object.keys(t.parts??{}),...Object.keys(e.parts??{})])){const o=t.parts?.[i],r=e.parts?.[i];s[i]={under:n(o?.under,r?.under),over:n(o?.over,r?.over)}}return{behind:n(t.behind,e.behind),parts:s,front:n(t.front,e.front)}}function ta(t={}){if(t.build&&!(t.build in wi))throw new Error(`character: unknown build '${t.build}'`);const e=t.build?wi[t.build]:{},n=(t.proportions??"bold")==="bold",s=t.figure??"fluid",i=t.look??"clean",o=t.height??300,r=s==="stick",a=t.outfit?y0(t.outfit):null,l=t.holding?b0(t.holding):{};let c=a?v0(a,t.layers??{}):t.layers??{};return Object.keys(l).length>0&&(c=v0(c,k0(l))),{plan:t.plan??Ou({headSize:t.headSize??e.headSize??(n?.3:.24),shoulderWidth:r?0:t.shoulderWidth??e.shoulderWidth??.06,hipWidth:r?0:t.hipWidth??e.hipWidth??.022,legLength:t.legLength??e.legLength??1,armLength:t.armLength??e.armLength??1}),figure:s,look:i,height:o,lineWidth:t.lineWidth??o*(n?.045:.022),ink:t.ink??(i==="pencil"?"#2f2f33":"#1e293b"),skin:t.skin??(i==="pencil"?"none":"#ffffff"),seed:t.seed??1,pencil:t.pencil??{},layers:c,holding:l,contact:t.contact??"ground",hands:t.hands??"dot",handStyle:t.handStyle??"glove",handSize:t.handSize??(t.handStyle==="natural"?.14:.17),head:c0(t)}}function iw(t,e,n,s){const{point:i,facing:o}=Fr(t,[e,n,s]);return{point:i,facing:o}}const ea=t=>t.rest[1]<-.5,ow=.3;function rw(t,e,n){return t.figure==="stick"?ea(e)?n.slice(0,3):n:ea(e)&&n.length>=3?Ye(n[0],n[1],n[2],ow):n.length===3?Ye(n[0],n[1],n[2],1):n}function na(t,e){const n=t.plan.id==="human"?{...ft,...e}:e;return Fi(t,n,Rr(t.plan,n,{height:t.height,contact:t.contact}))}function Fi(t,e,n){const s={},i={},o={},r=.01*t.height;t.plan.chains.forEach(d=>{const f=n.chains[d.id];s[d.id]=f.points;const p=f.depths.reduce((T,k)=>T+k,0)/f.depths.length,g=d.parent?n.chains[d.parent]:void 0,m=g?g.depths[d.at??g.depths.length-1]:0,y=p-m;o[d.id]=Math.abs(y)<r?0:y,i[d.id]={points:rw(t,d,f.points),depth:p}}),i.head={points:[n.head.center],depth:n.head.depth},o.head=0;const a=[...t.plan.chains.map(d=>d.id),"head"],l=[...a].sort((d,f)=>o[d]-o[f]||a.indexOf(d)-a.indexOf(f)),c={hip:n.hip};for(const[d,[f,p]]of Object.entries(t.plan.landmarks??{})){const g=n.chains[f]?.points;g&&(c[d]=g[Math.min(p,g.length-1)])}const h={};for(const[d,f]of Object.entries(c))h[d]=f.y>=n.groundY-.01*t.height;const u={height:t.height,lineWidth:t.lineWidth,turn:e.turn??0,points:c,chains:s,parts:i,head:n.head,groundY:n.groundY,grounded:h};return{skeleton:n,joints:u,order:l}}function sa(t,e){return na(t,e).joints}function M0(t,e,n){const{head:s}=n;t.guideEllipse(s.center.x,s.center.y,s.rx*1.03,s.ry*1.03,s.angle);const i=Array.from({length:13},(l,c)=>({x:0,y:-.95+1.9*c/12})),o=Array.from({length:13},(l,c)=>({x:-.95+1.9*c/12,y:.12})),r=vt(s,i,{x:0,y:0});r.facing>0&&t.guide(r.points),t.guide(vt(s,o,{x:0,y:.12}).points),t.guide(n.chains.spine??[]);const a=e.lineWidth*.9;for(const l of["shoulder.left","shoulder.right","elbow.left","elbow.right","hip.left","hip.right","knee.left","knee.right"]){const c=n.points[l];c&&t.guideEllipse(c.x,c.y,a,a,0)}}function S0(t,e,n,s,i,o){const r=n.lineWidth;if(i==="head"){const{head:f}=s,p=n.skin==="none"?null:n.skin;e.ellipse(f.center.x,f.center.y,f.rx,f.ry,f.angle,p,r),ew(t,e,n.head,f,o,{lineWidth:r,skin:n.skin},()=>{e.look!=="silhouette"&&Ob(e,f,o,r)});return}const a=n.plan.chains.find(f=>f.id===i),l=s.chains[i],c=s.parts[i].points;if(n.figure==="stick"){if(i==="neck")return;const f=i==="spine"?[...l,...s.chains.neck?.slice(1)??[]]:c;e.line(f,r);return}const h=(f,p)=>[a.bones[f].width[0]*r,a.bones[p].width[1]*r];if(ea(a)){const[f,p]=h(0,1);if(e.limb(c,f,p),a.bones.length>=3)e.limb([l[2],l[3]],a.bones[2].width[0]*r,a.bones[2].width[1]*r);else if(n.hands==="cartoon"&&i.startsWith("arm."))aw(t,e,n,l,i.endsWith(".left")?"left":"right",o);else{const g=l[l.length-1];e.dot(g.x,g.y,r*.62)}return}if(i==="spine"){const f=s.points["hip.left"],p=s.points["hip.right"];f&&p&&Math.hypot(f.x-p.x,f.y-p.y)>.5&&e.limb([f,p],r*1.3,r*1.3);const[g,m]=h(0,a.bones.length-1);e.limb(c,g,m);const y=s.points["shoulder.left"],T=s.points["shoulder.right"];y&&T&&Math.hypot(y.x-T.x,y.y-T.y)>.5&&e.limb(Ye(y,l[l.length-1],T,1,10),r*1.15,r*1.15);return}const[u,d]=h(0,a.bones.length-1);e.limb(c,u,d)}function T0(t,e){const n=`hand.${e}.`,s={};for(const[r,a]of Object.entries(t))r.startsWith(n)&&(s[r.slice(n.length)]=a);const i=t.turn??0,o=e==="right"?1-i:1+i;return{...Et,...s,turn:o+(s.turn??0)}}function aw(t,e,n,s,i,o){const r=s[s.length-1],a=s[s.length-2],l=Math.atan2(r.x-a.x,-(r.y-a.y))*180/Math.PI;li(t,r,T0(o,i),{size:n.handSize*n.height,side:i,angle:l,pen:e,skin:n.skin==="none"?"#ffffff":n.skin,fingers:n.handStyle==="natural"?5:4,plump:n.handStyle==="natural"?1.15:1.6,lineWidth:n.lineWidth*.3})}function E0(t,e,n,s=0){const i=e.plan.id==="human"?{...ft,...n}:n;x0(t,e,i,na(e,i),s)}function ia(t,e){const n=e/t.height;return{...t,height:e,lineWidth:t.lineWidth*n}}function lw(t,e,n,s){const i=t.plan.id==="human"?{...ft,...e}:e,o=Ti(t.plan,i,{height:s.height,contact:t.contact},n);return Fi(ia(t,o.height),i,o).joints}function cw(t,e,n,s,i){const o=e.plan.id==="human"?{...ft,...n}:n,r=Ti(e.plan,o,{height:i.height,contact:e.contact},s),a=ia(e,r.height);x0(t,a,o,Fi(a,o,r),i.time??0)}function A0(t,e,n,s){const i=t.plan.id==="human"?{...ft,...e}:e,o=Ti(t.plan,i,{height:s.height,contact:t.contact},n),r=ia(t,o.height),{joints:a,order:l}=Fi(r,i,o),c=o.height/s.height;return l.map((h,u)=>({part:h,depth:(a.parts[h]?.depth??0)/c,draw(d,f=0){const p=Zn(d,{look:r.look,ink:r.ink,lineWidth:r.lineWidth,seed:zt(`${r.seed}:${h}`),time:f,pencil:r.pencil}),g=y=>{y&&(d.save(),y(d,a,p,f,i),d.restore())};d.save(),d.lineCap="round",d.lineJoin="round",u===0&&(r.look==="pencil"&&r.pencil.construction!==!1&&M0(p,r,a),g(r.layers.behind),f0(d,p,r.head,a.head,i,{lineWidth:r.lineWidth,skin:r.skin}));const m=r.layers.parts?.[h];g(m?.under),S0(d,p,r,a,h,i),g(m?.over),u===l.length-1&&(g0(d,p,r.head,a.head,i,{lineWidth:r.lineWidth,skin:r.skin}),g(r.layers.front)),d.restore()}}))}function x0(t,e,n,s,i){const{joints:o,order:r}=s,a=Zn(t,{look:e.look,ink:e.ink,lineWidth:e.lineWidth,seed:e.seed,time:i,pencil:e.pencil}),l=c=>{c&&(t.save(),c(t,o,a,i,n),t.restore())};t.save(),t.lineCap="round",t.lineJoin="round",e.look==="pencil"&&e.pencil.construction!==!1&&M0(a,e,o),l(e.layers.behind),f0(t,a,e.head,o.head,n,{lineWidth:e.lineWidth,skin:e.skin});for(const c of r){const h=e.layers.parts?.[c];l(h?.under),S0(t,a,e,o,c,n),l(h?.over)}g0(t,a,e.head,o.head,n,{lineWidth:e.lineWidth,skin:e.skin}),l(e.layers.front),t.restore()}function hw(t,e,n){const s={...t};for(const[i,o]of Object.entries(e)){const r=t[i]??o;s[i]=r+(o-r)*n}return s}function $0(t,e,n,s){const i=t.plan.id==="human"?{...ft,...e}:e;let o;if(Array.isArray(s))o=s;else{const{skeleton:r}=na(t,i),a=Rr(t.plan,{...i,roll:0},{height:t.height,contact:"none"}),l=(i.roll??0)*Math.PI/180,c=s.x-r.hip.x,h=s.y-r.hip.y,u=a.hip.x+c*Math.cos(-l)-h*Math.sin(-l),d=a.hip.y+c*Math.sin(-l)+h*Math.cos(-l),f=Math.PI/2*(i.turn??0),p=s.depth??r.chains[n].depths[r.chains[n].depths.length-1],g=Math.cos(f),m=Math.sin(f);o=[u*g-p*m,-d,u*m+p*g]}return Ab(t.plan,i,n,o,{height:t.height})}function uw(t){const{character:e}=t,n=e.height*.8,s=e.height,i=e.plan.id==="human"?ft:{};return{type:"custom",x:t.x-n/2,y:t.y-s,width:n,height:s,props:{...i,...t.pose},character:e,draw(o,r,a){o.translate(n/2,s),E0(o,e,r.props,a)}}}function P0(t,e,n){const s=o=>({x:o.x+e,y:o.y+n}),i=o=>Object.fromEntries(Object.entries(o).map(([r,a])=>[r,a.map(s)]));return{...t,points:Object.fromEntries(Object.entries(t.points).map(([o,r])=>[o,s(r)])),chains:i(t.chains),parts:Object.fromEntries(Object.entries(t.parts).map(([o,r])=>[o,{...r,points:r.points.map(s)}])),head:{...t.head,center:s(t.head.center)},groundY:t.groundY+n}}function dw(t,e,n){const s=t.character;if(!s)throw new Error("characterAt: the target was not made by characterTarget");const i={...t.props};let o=0,r=0;for(const[l,c]of e.state?.values.get(n)??[])typeof c=="number"&&(l==="x"||l==="motionPathX"?o=c:l==="y"||l==="motionPathY"?r=c:l in i&&(i[l]=c));const a=sa(s,i);return{pose:i,joints:P0(a,t.x+o+t.width/2,t.y+r+t.height)}}function oa(t,e=ft){const n=[];return t.forEach((s,i)=>{const o=i===0?e:n[i-1],r=typeof s.pose=="string"?ze[s.pose]:void 0;n.push(r?{...r,turn:o.turn??0}:{...o,...s.pose})}),n}function fw(t,e,n=ft){const s=oa(e,n);return Object.keys(n).filter(o=>s.some(r=>(r[o]??n[o])!==n[o])).map(o=>({id:`${t}-${o}`,target:t,property:o,keyframes:e.map((r,a)=>({time:r.time,value:s[a][o]??n[o],...r.easing?{easing:r.easing}:{}}))}))}const ra=new Map;function gw(t){const e=ra.get(t);if(e)return e;let n=[1,1,1];const s=t.trim().replace("#","");if(t.trim().startsWith("#")&&(s.length===3||s.length===6)){const i=s.length===3?s.split("").map(o=>o+o).join(""):s;n=[0,2,4].map(o=>Number.parseInt(i.slice(o,o+2),16)/255)}else{const i=t.match(/rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)/);i&&(n=[Number(i[1])/255,Number(i[2])/255,Number(i[3])/255])}return ra.size<512&&ra.set(t,n),n}De([-3,-5,-4]);const pw=(t,e,n)=>{const s=Math.min(1,Math.max(0,(n-t)/(e-t)));return s*s*(3-2*s)};function I0(t,e,n){const s=[0,0,0];for(const i of n){const o=gw(i.color);let r;if(i.light==="ambient")r=i.intensity;else if(i.light==="directional")r=i.intensity*Math.max(0,-Me(e,i.direction));else{const a=dn(i.position,t),l=Xs(a),c=l>0?fn(a,1/l):e,h=i.range?Math.max(0,1-l/i.range)**2:1;if(r=i.intensity*Math.max(0,Me(e,c))*h,i.light==="spot"){const u=Math.cos(i.angle*Math.PI/180),d=Math.cos(i.angle*.8*Math.PI/180);r*=pw(u,d,-Me(c,i.direction))}}s[0]+=o[0]*r,s[1]+=o[1]*r,s[2]+=o[2]*r}return s}function O0(t,e){return t?Math.min(1,Math.max(0,(e-t.near)/(t.far-t.near))):0}function aa(t,e,n={}){t.save(),mw(t,e,n),t.restore()}function mw(t,e,n){const s=la(e,n);n.shadow!==!1&&ca(t,e,n);for(const i of e.under)da(t,i,s,n);if(n.rider){if(t.save(),e.openings.length>0){t.beginPath();for(const i of e.openings){t.moveTo(i[0].x,i[0].y);for(const o of i.slice(1))t.lineTo(o.x,o.y);t.closePath()}t.clip("nonzero")}n.rider(t),t.restore()}for(const i of e.over)da(t,i,s,n)}function la(t,e={}){return e.lineWidth??Math.max(1.3,t.sizePx*.022)}function ca(t,e,n={}){e.shadow.opacity<=0||e.shadow.points.length<3||(t.save(),t.globalAlpha=e.shadow.opacity,Ni(t,e.shadow.points,n.ink??"#26262b",!1),t.restore())}function yw(t,e,n,s={}){t.save(),da(t,e,n,s),t.restore()}function _0(t,e,n,s={}){const i=s.style==="stick",o=e.flatMap(h=>{if(i&&h.part.solidOnly)return[];const u=h.part.layer??0;return i&&h.spine?[{depth:h.depth,layer:u,part:h}]:h.faces.map(d=>({depth:d.depth,layer:u,part:h,face:d}))}),r=new Map;for(const h of o){const u=h.face?.normal;if(!h.face?.center||!u)continue;const d=Math.abs(u[0])>=Math.abs(u[1])&&Math.abs(u[0])>=Math.abs(u[2])?0:Math.abs(u[1])>=Math.abs(u[2])?1:2,f=d*2+(u[d]<0?1:0);r.set(f,[...r.get(f)??[],h])}for(const h of r.values())for(const u of h){const{center:d,normal:f}=u.face;for(const p of h){if(p.part.part.id===u.part.part.id)continue;const g=p.face;if(g.normal[0]*f[0]+g.normal[1]*f[1]+g.normal[2]*f[2]<=.8)continue;const y=g.normal[0]*(d[0]-g.center[0])+g.normal[1]*(d[1]-g.center[1])+g.normal[2]*(d[2]-g.center[2]);y>-C0/5&&y<C0&&(u.layer=Math.max(u.layer,p.layer),u.depth=Math.max(u.depth,p.depth+1e-6))}}o.sort((h,u)=>h.layer-u.layer||h.depth-u.depth);const a=new Map,l=h=>{let u=a.get(h.part.id);return u||a.set(h.part.id,u=ha(t,h,n,s)),u};t.save();const c=t.globalAlpha;for(const{part:h,face:u}of o){t.globalAlpha=c*h.opacity;const d=l(h);if(!u)d.line(h.spine,n*1.15);else{const f=i?H0(h,s):u.light?bw(h,u,s):ua(h);f&&(!i&&s.look==="silhouette"?d.shape(u.points,f,0):Ni(t,u.points,i||u.light?f:Di(f,u.tone),!0,h.cut?1.6:.8));const p=(h.part.outline??1)*n;if(p>0)for(const g of u.edges??[])g.length>1&&d.line(g,p);for(const g of u.marks??[])d.line(g,n*.7)}}t.restore()}const C0=.05;function ha(t,e,n,s){return Zn(t,{look:s.look??"clean",ink:e.part.ink??s.ink??"#26262b",lineWidth:n,seed:zt(`${s.seed??0}:${e.part.id}`),time:s.time??0,pencil:{construction:!1,rubbedOut:0,...s.pencil}})}function ua(t){const{part:e}=t;return e.glow&&t.glow>0&&e.fill?pa(e.fill,e.glow.color,t.glow):e.fill}function bw(t,e,n){const{part:s}=t;if(!s.fill)return;const i=ga(s.fill,e.light,e.fog??0,n.fog);return s.glow&&t.glow>0?pa(i,s.glow.color,t.glow):i}function H0(t,e){const n=ua(t);return n&&(kw(n)||t.glow>0)?n:e.paper??"#fbf8ef"}function da(t,e,n,s){e.opacity<1?(t.save(),t.globalAlpha*=e.opacity,R0(t,e,n,s),t.restore()):R0(t,e,n,s)}function R0(t,e,n,s){if(s.style==="stick")return ww(t,e,n,s);const{part:i}=e,o=ha(t,e,n,s),r=ua(e),a=s.look==="silhouette";for(const c of e.faces)r&&(a?o.shape(c.points,r,0):Ni(t,c.points,Di(r,c.tone)));const l=(i.outline??1)*n;if(l>0)for(const c of e.edges)c.length>1&&o.line(c,l);for(const c of e.marks)o.line(c,n*.7)}function ww(t,e,n,s){const{part:i}=e;if(i.solidOnly)return;const o=ha(t,e,n,s);if(e.spine){o.line(e.spine,n*1.15);return}const r=H0(e,s);for(const l of e.faces)Ni(t,l.points,r);const a=(i.outline??1)*n;if(a>0)for(const l of e.edges)l.length>1&&o.line(l,a);for(const l of e.marks)o.line(l,n*.7)}function kw(t){const e=Sn(t);return e?(.299*e[0]+.587*e[1]+.114*e[2])/255<.3:!1}function Ni(t,e,n,s=!0,i=.8){t.fillStyle=n,t.beginPath(),t.moveTo(e[0].x,e[0].y);for(let o=1;o<e.length;o++)t.lineTo(e[o].x,e[o].y);t.closePath(),t.fill(),s&&(t.strokeStyle=n,t.lineWidth=i,t.lineJoin="round",t.stroke())}function Sn(t){const e=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t.trim());if(!e)return;const n=e[1].length===3?e[1].replace(/./g,s=>s+s):e[1];return[0,2,4].map(s=>parseInt(n.slice(s,s+2),16))}const fa=t=>`#${t.map(e=>Math.round(Math.max(0,Math.min(255,e))).toString(16).padStart(2,"0")).join("")}`;function Di(t,e){const n=Sn(t);return n?fa(e>=1?n.map(s=>s+(255-s)*(e-1)*2):n.map(s=>s*e)):t}function ga(t,e,n,s){const i=Sn(t);if(!i)return t;let o=i.map((a,l)=>a*e[l]);const r=s?Sn(s):void 0;return r&&n>0&&(o=o.map((a,l)=>a+(r[l]-a)*n)),fa(o)}function pa(t,e,n){const s=Sn(t),i=Sn(e);return!s||!i?n<.5?t:e:fa(s.map((o,r)=>o+(i[r]-o)*n))}const L0=40,vw=.215+.205,qt=(t,e)=>{const n={};for(const s of["left","right"])for(const[i,o]of Object.entries(e))n[`${t}.${s}.${i}`]=o;return n},it=(t,e)=>t[e]??ft[e]??0;function F0(t,e,n=ft,s=1){const i=es(t),o=e*Math.PI*2,r=Math.sin(o)*s,a=Math.cos(o)*s,l=(1+Math.cos(o*2*(i.bounces??1)))/2,c=i.crouch??0,h=i.shoulder??0,u=i.forearm??0,d={...ft,...n};d["leg.left.swing"]=i.swing*r+c*.6,d["leg.right.swing"]=-i.swing*r+c*.6,d["leg.left.knee"]=i.knee*Math.max(0,a)+c*1.2,d["leg.right.knee"]=i.knee*Math.max(0,-a)+c*1.2,d["leg.left.ankle"]=it(n,"leg.left.ankle")-(i.tiptoe??0),d["leg.right.ankle"]=it(n,"leg.right.ankle")-(i.tiptoe??0);for(const[f,p]of[["left",-1],["right",1]])it(n,`arm.${f}.spread`)>L0||it(n,`arm.${f}.swing`)>L0||(d[`arm.${f}.swing`]=h+p*i.arm*r,d[`arm.${f}.elbow`]=it(n,`arm.${f}.elbow`)+u+i.elbow*Math.max(0,p*r));return d.lean=it(n,"lean")+i.lean*s,d.bend=it(n,"bend")+(i.bend??0),d["head.nod"]=it(n,"head.nod")-i.lean*.5*s+(i.headTilt??0),d.side=it(n,"side")+(i.sway??0)*Math.sin(o),d.lift=it(n,"lift")+(i.bounce??0)*s*l,d.stretch=it(n,"stretch")*(1+(i.squash??0)*(l-.5)),d}function N0(t,e,n=1,s=1){const i=es(t);return 4*vw*s*e*Math.sin(i.swing*n*Math.PI/180)}const Tn=t=>Or[t],Wi={take:t=>[{after:140,pose:{stretch:.8,bend:10,lean:it(t,"lean")-4,...qt("arm",{spread:6,swing:0,elbow:10}),"eye.left":.35,"eye.right":.35,"brow.left":-.6,"brow.right":-.6,mouth:0},easing:"ease-in-out"},{after:260,pose:{stretch:.78}},{after:360,pose:{lift:.22,stretch:1.35,bend:-14,...qt("arm",{spread:150,bend:35,swing:0,elbow:0}),...qt("leg",{swing:25,knee:60}),...Tn("shocked")},easing:"ease-out-cubic"},{after:720,pose:{lift:.25,stretch:1.25,bend:-10,...qt("arm",{spread:140})},easing:"ease-in-out"},{after:900,pose:{lift:0,stretch:.74,bend:12,...qt("arm",{spread:70,bend:0}),...qt("leg",{swing:30,knee:60})},easing:"ease-in-quad"},{after:1060,pose:{stretch:1.06,bend:-3,...qt("arm",{spread:60}),"leg.left.swing":it(t,"leg.left.swing"),"leg.right.swing":it(t,"leg.right.swing"),"leg.left.knee":it(t,"leg.left.knee"),"leg.right.knee":it(t,"leg.right.knee")},easing:"ease-out"},{after:1260,pose:{stretch:it(t,"stretch"),bend:it(t,"bend"),...Tn("surprised"),...qt("arm",{spread:55,bend:60})},easing:"ease-in-out"}],doubleTake:t=>[{after:160,pose:{lookX:1,lookY:0,"head.turn":0},easing:"ease-out"},{after:520,pose:{lookX:-.6,"head.turn":30,"head.nod":it(t,"head.nod")-4,smile:.6,mouth:0},easing:"ease-in-out"},{after:1100,pose:{lookX:-.6}},{after:1180,pose:{"head.turn":0,"head.nod":it(t,"head.nod")-10,bend:it(t,"bend")-10,lift:.05,stretch:1.18,...Tn("shocked"),lookX:1,lookY:0},easing:"ease-out-cubic"},{after:1360,pose:{lift:0,stretch:.88,"head.nod":it(t,"head.nod")-4,bend:it(t,"bend")+4},easing:"ease-in-quad"},{after:1560,pose:{stretch:it(t,"stretch"),"head.nod":it(t,"head.nod"),bend:it(t,"bend")},easing:{type:"elastic",mode:"out",amplitude:1,period:.35}}],windUp:()=>[{after:220,pose:{lean:-18,bend:-16,"head.nod":-6,"arm.left.swing":60,"arm.left.elbow":100,"arm.right.swing":-40,"arm.right.elbow":90,"leg.left.swing":55,"leg.left.knee":95,stretch:.92,...Tn("angry"),lookX:1},easing:"ease-out"},{after:620,pose:{lean:-20,bend:-18,stretch:.9}},{after:700,pose:{lean:28,bend:14,"head.nod":6,"arm.left.swing":-30,"arm.right.swing":60,"leg.left.swing":-20,"leg.left.knee":30,"leg.right.swing":20,stretch:1.12},easing:"ease-out-cubic"}],land:t=>[{after:120,pose:{lift:0,stretch:.7,bend:14,...qt("arm",{spread:75}),...qt("leg",{swing:25,knee:50})},easing:"ease-in-quad"},{after:300,pose:{stretch:1.05,bend:-4,"arm.left.spread":it(t,"arm.left.spread"),"arm.right.spread":it(t,"arm.right.spread")},easing:"ease-out"},{after:460,pose:{lift:0,stretch:it(t,"stretch"),bend:it(t,"bend"),...qt("leg",{swing:0,knee:0})},easing:"ease-in-out"}],tremble:t=>{const e=[{after:80,pose:{...Tn("scared"),...qt("arm",{swing:40,elbow:110,spread:14}),stretch:.94,bend:it(t,"bend")+8},easing:"ease-out"}];for(let n=1;n<=14;n++){const s=n%2===0?1:-1;e.push({after:80+n*45,pose:{side:it(t,"side")+2.5*s,"head.tilt":it(t,"head.tilt")-2*s}})}return e.push({after:755,pose:{side:it(t,"side"),"head.tilt":it(t,"head.tilt"),bend:it(t,"bend")}}),e},deflate:t=>[{after:260,pose:{stretch:1.04,"head.nod":it(t,"head.nod")-4,"brow.left":.3,"brow.right":.3},easing:"ease-in-out"},{after:900,pose:{...Tn("sad"),bend:18,stretch:.92,lean:it(t,"lean")+5,"head.nod":14,...qt("arm",{spread:6,swing:0,elbow:4,bend:0})},easing:"ease-in-out"}]};function D0(t,e){const n=ht(e.from??{}),s=e.speed??1;let i=n;return[{time:e.at,pose:n},...Wi[t](n).map(o=>(i={...i,...o.pose},{time:e.at+o.after*s,pose:i,act:!1,...o.easing?{easing:o.easing}:{}}))]}const Mw=new Set(["x","y","z","position","rotateX","rotateY","rotateZ","quaternion","scale","scaleX","scaleY","scaleZ","visible","opacity","color"]),Sw=new Set(["walk","walking","gait"]),W0=t=>typeof t=="number"?t:void 0,Tw=1.7;function Ew(t,e,n){const s=Array.from({length:24},(i,o)=>{const r=o/24*Math.PI*2,a=e.toView([Math.cos(r)*n,0,Math.sin(r)*n*.8]);return a[2]<-.001?e.toScreen(a):null});s.some(i=>i===null)||(t.beginPath(),s.forEach((i,o)=>o===0?t.moveTo(i.x,i.y):t.lineTo(i.x,i.y)),t.closePath(),t.fillStyle="rgba(0, 0, 0, 0.22)",t.fill())}function Aw(t){const e=Me([0,1,0],t);if(e>.999999)return Gs();if(e<-.999999)return Jt(Kt([1,0,0],180));const n=zs([0,1,0],t);return Jt(Kt(n,Math.acos(e)*180/Math.PI))}function xw(t,e,n,s,i){const o=t.solid??{},r=o.outline===!1?void 0:o.outline??{width:2,color:"#0f172a"},a={color:o.color??"#475569",shading:o.shading??"toon",outline:r},l={color:o.skin??"#f2c49b",shading:o.shading??"toon",outline:r},c={color:"#0f172a",shading:"unlit"},h=s.height*.034,u=[],d=(k,b,A)=>u.push({mesh:k,world:wt(i,b),material:A}),f=(k,b,A)=>d(e.sphere,qo(k,[0,0,0,1],[b,b,b]),A);for(const k of n.chains){const b=s.chains[k.id],A=k.id==="spine"?1.9:1;k.bones.forEach((M,E)=>{const x=b[E],S=b[E+1],I=jo(x,S),[v,$]=M.width??[1,1],_=h*A*(v+$)/2;if(I>1e-6){const P=xc(x,S,.5),C=Aw(De(dn(S,x)));d(e.cylinder,wt(We(P),wt(C,Be([_,I,_]))),a)}f(x,h*A*v,a),f(S,h*A*$,a)}),k.id.startsWith("arm.")&&f(b[b.length-1],h*1.5,l)}const{center:p,rx:g,ry:m,axes:y}=s.head,T=[...y[0],0,...y[1],0,...y[2],0,...p,1];d(e.sphere,wt(T,Be([g,m,g])),l);for(const k of[-1,1]){const b=De([k*.36,.15,.92]),A=Ks(p,Ks(Ks(fn(y[0],b[0]*g*1.04),fn(y[1],b[1]*m*1.04)),fn(y[2],b[2]*g*1.04))),M=[...y[0],0,...y[1],0,...y[2],0,...A,1];d(e.sphere,wt(M,Be([g*.11,m*.14,g*.03])),c)}return u}const $w={kind:"character",validate(t){const e=t;return e.height!==void 0&&!(e.height>0)?["a character's height must be positive"]:[]},prepare(t){return{who:ta({...t.character,height:1}),cylinder:Ei(Ru(1,1,16)),sphere:Ei(Eb(1,20))}},resolve({object:t,prepared:e,values:n,world:s,camera:i,lights:o=[],fog:r,toScreen:a}){const l=t,c=e,h=c.who;let u={...ft,...l.pose};for(const[x,S]of n)typeof S=="number"&&!Mw.has(x)&&!Sw.has(x)&&(u[x]=S);const d=Math.max(0,Math.min(1,W0(n.get("walking"))??l.walking??0));if(d>0){const x=typeof n.get("gait")=="string"?n.get("gait"):l.gait,S=F0(x,W0(n.get("walk"))??0,u);u=Object.fromEntries(Object.keys({...u,...S}).map(I=>[I,(u[I]??0)+((S[I]??0)-(u[I]??0))*d]))}const f=l.height??Tw,p=wt(i.view,s),g={toView:x=>Dt(p,x),toScreen:x=>a(x)},y=-g.toView([0,f/2,0])[2];if(y<=i.near)return null;const T=l.shadow===!1?[]:[{depth:y+f,draw:x=>Ew(x,g,f*.18)}];if(l.look==="solid"){const x=Si(h.plan,u,{height:f,contact:h.contact});return{meshes:xw(l,c,h.plan,x,s),drawables:T}}const k=Dt(s,[0,f*.6,0]),b=De(dn(i.position,k)),A=I0(k,b,o).map(x=>Math.min(1,x)),M=o.length>0&&h.skin!=="none"?{...h,skin:ga(h.skin,A,O0(r,jo(k,i.position)),r?.color)}:h,E=A0(M,u,g,{height:f});return{drawables:[...T,...E.map((x,S)=>({depth:-x.depth-S*1e-6,draw:(I,v)=>x.draw(I,v.time)}))]}}},gs=([t,e,n])=>{const s=Math.hypot(t,e,n)||1;return[t/s,e/s,n/s]};function B0([t,e,n]){const[s,i,o]=[t/2,e/2,n/2];return{vertices:[[-s,-i,-o],[s,-i,-o],[s,i,-o],[-s,i,-o],[-s,-i,o],[s,-i,o],[s,i,o],[-s,i,o]],faces:[{corners:[4,5,6,7],normal:[0,0,1]},{corners:[1,0,3,2],normal:[0,0,-1]},{corners:[5,1,2,6],normal:[1,0,0]},{corners:[0,4,7,3],normal:[-1,0,0]},{corners:[7,6,2,3],normal:[0,1,0]},{corners:[0,1,5,4],normal:[0,-1,0]}]}}const En=(t,[e,n,s])=>t==="z"?[e,n,s]:t==="x"?[s,n,e]:[e,s,n];function j0(t,e,n="x",s=20,i=0){const o=[],r=e/2;for(const c of[-r,r])for(let h=0;h<s;h++){const u=Math.PI*2*h/s;o.push(En(n,[Math.cos(u)*t,Math.sin(u)*t,c]))}const a=[{corners:Array.from({length:s},(c,h)=>s-1-h),normal:En(n,[0,0,-1])},{corners:Array.from({length:s},(c,h)=>s+h),normal:En(n,[0,0,1])}];for(let c=0;c<s;c++){const h=(c+1)%s,u=Math.PI*2*(c+.5)/s;a.push({corners:[c,h,s+h,s+c],normal:En(n,[Math.cos(u),Math.sin(u),0])})}const l=[];if(i>0)for(const c of[-r,r]){const h=o.push(En(n,[0,0,c*1.01]))-1;for(let u=0;u<i;u++){const d=Math.PI*2*u/i,f=o.push(En(n,[Math.cos(d)*t*.82,Math.sin(d)*t*.82,c*1.01]))-1;l.push([h,f])}}return{vertices:o,faces:a,marks:l,creases:!0}}function q0([t,e,n],s=16){const i=Math.max(4,Math.round(s/2)),o=[[0,e,0]];for(let h=1;h<i;h++){const u=Math.PI*h/i;for(let d=0;d<s;d++){const f=Math.PI*2*d/s;o.push([Math.sin(u)*Math.cos(f)*t,Math.cos(u)*e,Math.sin(u)*Math.sin(f)*n])}}const r=o.push([0,-e,0])-1,a=(h,u)=>1+(h-1)*s+u%s,l=h=>{const u=h.reduce((d,f)=>[d[0]+o[f][0],d[1]+o[f][1],d[2]+o[f][2]],[0,0,0]);return gs([u[0]/(t*t),u[1]/(e*e),u[2]/(n*n)])},c=[];for(let h=0;h<s;h++){const u=[0,a(1,h+1),a(1,h)];c.push({corners:u,normal:l(u)});for(let f=1;f<i-1;f++){const p=[a(f,h),a(f,h+1),a(f+1,h+1),a(f+1,h)];c.push({corners:p,normal:l(p)})}const d=[a(i-1,h),a(i-1,h+1),r];c.push({corners:d,normal:l(d)})}return{vertices:o,faces:c,creases:!1}}const Pw=t=>t.reduce((e,[n,s],i)=>{const[o,r]=t[(i+1)%t.length];return e+n*r-o*s},0)/2;function Y0(t,e){const n=Pw(t)<0?[...t].reverse():t,s=n.length,i=e/2,o=[...n.map(([a,l])=>[i,l,a]),...n.map(([a,l])=>[-i,l,a])],r=[{corners:Array.from({length:s},(a,l)=>s-1-l),normal:[1,0,0]},{corners:Array.from({length:s},(a,l)=>s+l),normal:[-1,0,0]}];for(let a=0;a<s;a++){const l=(a+1)%s,[c,h]=[n[l][0]-n[a][0],n[l][1]-n[a][1]];r.push({corners:[a,l,s+l,s+a],normal:gs([0,-c,h])})}return{vertices:o,faces:r,creases:!0}}function K0(t,e){const n={left:([i,o])=>[0,o,i],right:([i,o])=>[0,o,i],front:([i,o])=>[i,o,0],back:([i,o])=>[i,o,0],up:([i,o])=>[i,0,o]},s={left:[1,0,0],right:[-1,0,0],front:[0,0,1],back:[0,0,-1],up:[0,1,0]};return{vertices:t.map(n[e]),faces:[{corners:t.map((i,o)=>o),normal:s[e]}]}}function z0(t,e,n=8){const s=r=>Array.isArray(e)?e[Math.min(r,e.length-1)]:e,i=[],o=[];t.forEach((r,a)=>{const l=t[Math.min(a+1,t.length-1)],c=t[Math.max(a-1,0)],h=gs([l[0]-c[0],l[1]-c[1],l[2]-c[2]]),u=Math.abs(h[1])<.9?[0,1,0]:[1,0,0],d=gs(X0(h,u)),f=X0(d,h);for(let p=0;p<n;p++){const g=Math.PI*2*p/n,m=Math.cos(g)*s(a),y=Math.sin(g)*s(a);i.push([r[0]+d[0]*m+f[0]*y,r[1]+d[1]*m+f[1]*y,r[2]+d[2]*m+f[2]*y])}});for(let r=0;r<t.length-1;r++)for(let a=0;a<n;a++){const l=(a+1)%n,c=[r*n+a,r*n+l,(r+1)*n+l,(r+1)*n+a],h=c.reduce((d,f)=>[d[0]+i[f][0]/4,d[1]+i[f][1]/4,d[2]+i[f][2]/4],[0,0,0]),u=[(t[r][0]+t[r+1][0])/2,(t[r][1]+t[r+1][1])/2,(t[r][2]+t[r+1][2])/2];o.push({corners:c,normal:gs([h[0]-u[0],h[1]-u[1],h[2]-u[2]])})}return{vertices:i,faces:o,creases:!1}}function X0(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function G0(t){switch(t.type){case"box":return B0(t.size);case"cylinder":return j0(t.radius,t.length,t.axis,t.segments,t.spokes);case"ellipsoid":return q0(t.radii,t.segments);case"extrude":return Y0(t.profile,t.width);case"panel":return K0(t.points,t.facing);case"tube":return{...z0(t.points,t.radius,t.segments),joined:t.joined}}}function ma(t,e){if(t.length<2)return t;const n=i=>t[Math.max(0,Math.min(t.length-1,i))],s=i=>{const o=i*(t.length-1),r=Math.min(t.length-2,Math.floor(o)),a=o-r,[l,c,h,u]=[n(r-1),n(r),n(r+1),n(r+2)];return[0,1,2].map(d=>{const f=l[d],p=c[d],g=h[d],m=u[d];return .5*(2*p+(-f+g)*a+(2*f-5*p+4*g-m)*a*a+(-f+3*p-3*g+m)*a*a*a)})};return Array.from({length:e},(i,o)=>s(o/(e-1)))}const Ge=t=>Array.isArray(t)&&t.length===2&&t.every(e=>typeof e=="number"&&Number.isFinite(e));function Bi(t,e){return((e-t)%360+540)%360-180}function U0(t){const e=t.map((n,s)=>({frame:n,i:s})).sort((n,s)=>n.frame.time-s.frame.time||n.i-s.i).map(({frame:n})=>n);return e.filter((n,s)=>s+1>=e.length||e[s+1].time!==n.time)}function An(t,e){return Math.atan2(e[0]-t[0],e[1]-t[1])*180/Math.PI}function V0(t){const e=t.filter((i,o)=>o===0||Math.hypot(i[0]-t[o-1][0],i[1]-t[o-1][1])>1e-6);if(e.length<2)return[];const n=e.length===2?e:ma(e.map(([i,o])=>[i,0,o]),(e.length-1)*12).map(([i,,o])=>[i,o]);let s=0;return n.map((i,o)=>(o>0&&(s+=Math.hypot(i[0]-n[o-1][0],i[1]-n[o-1][1])),{point:i,at:s}))}function J0(t,e){let n=1;for(;n<t.length-1&&t[n].at<e;)n++;const s=t[n-1],i=t[n],o=i.at>s.at?Math.max(0,Math.min(1,(e-s.at)/(i.at-s.at))):0;return{point:[s.point[0]+(i.point[0]-s.point[0])*o,s.point[1]+(i.point[1]-s.point[1])*o],direction:[i.point[0]-s.point[0],i.point[1]-s.point[1]]}}function Z0(t,e){if(e<=0)return 0;if(e>=1)return 1;let n=0,s=1;for(let i=0;i<40;i++){const o=(n+s)/2;t(o)<e?n=o:s=o}return(n+s)/2}const ya=["do","at","for","to","through","toward","speed","pose","gag"],Q0={walk:1.3,bouncy:1.4,doubleBounce:1.2,sneak:.6,strut:1.2,tired:.8,run:3.6,shove:.7},ba=Object.keys(Ht),wa=Object.keys(ze),ka=Object.keys(Wi),Iw=.25,Ow=700/180,_w=200,Cw=300;function td(t){if(!Array.isArray(t))return[{beat:-1,message:`Beats must be an array of { do: … } objects (got ${typeof t}).`}];const e=[...ba,"face","hold","pose","gag","place"],n=[];return t.forEach((s,i)=>{const o=c=>n.push({beat:i,message:c});if(!s||typeof s!="object"||Array.isArray(s))return o("Each beat must be an object like { do: 'walk', to: [x, z] }.");const r=s,a={duration:"for",path:"through",position:"to",heading:"toward",direction:"toward"};for(const c of Object.keys(r))ya.includes(c)||o(ot("beat field",c,ya,a[c]));const l=typeof r.do=="string"?wa.includes(r.do)?"pose":ka.includes(r.do)?"gag":r.do==="turn"?"face":void 0:void 0;if(typeof r.do!="string"||!e.includes(r.do))return o(ot("character 3D beat",r.do,e,l));ba.includes(r.do)&&(r.to===void 0&&r.through===void 0&&o(`\`${r.do}\` needs \`to\` ([x, z] metres) or \`through\` (a list of them).`),r.to!==void 0&&!Ge(r.to)&&o(`\`to\` is a point on the ground, [x, z] metres (got ${JSON.stringify(r.to)}).`),r.through!==void 0&&!(Array.isArray(r.through)&&r.through.length>0&&r.through.every(Ge))&&o("`through` is a list of points on the ground, each [x, z] metres.")),r.do==="place"&&!Ge(r.to)&&o("`place` needs `to`: a point on the ground, [x, z] metres."),r.do==="face"&&!(Ge(r.toward)||typeof r.toward=="number")&&o("`face` needs `toward`: a point [x, z] or a heading in degrees."),r.do==="pose"&&!(typeof r.pose=="object"&&r.pose!==null)&&!wa.includes(r.pose)&&o(ot("pose",r.pose,wa)),r.do==="gag"&&!ka.includes(r.gag)&&o(ot("gag",r.gag,ka))}),n}function Hw(t,e,n){const s=td(e);if(s.length>0)throw new Error(`characterScript3D: ${s.length} problem(s) in the beats:
|
|
54
|
+
${s.map(b=>` beat ${b.beat}: ${b.message}`).join(`
|
|
55
|
+
`)}`);const i=n.height??1.7,o={...ft,...n.pose};let[r,a]=n.position??[0,0],l=n.heading??0,c=0;const h=new Map,u=[],d=(b,A,M,E="linear")=>{const x=h.get(b)??[];x.push({time:A,value:M,easing:E}),h.set(b,x)};d("x",0,r),d("z",0,a),d("rotateY",0,l);const f=(b,A)=>{const M=Bi(l,A);if(Math.abs(M)<1)return b;const E=Math.max(_w,Math.abs(M)*Ow);return d("rotateY",b,l),l+=M,d("rotateY",b+E,l,"ease-in-out"),b+E},p=(b,A,M,E="ease-in-out")=>{for(const[x,S]of Object.entries(M))o[x]!==S&&(d(x,b,o[x]??0),d(x,A,S,E),o[x]=S)},g=(b,A,M)=>{const E=V0([[r,a],...A.through??[A.to]]);if(E.length<2)return M;const x=f(M,An(E[0].point,E[1].point)),S=E[E.length-1].at,I=A.speed??Q0[b]*Math.sqrt(i/1.7),v=A.for??S/I*1e3,$=N0(b,i),_=Ct("ease-in-out"),P=Math.min(Cw,v/4);u.push({time:x,value:b}),d("walking",x,0),d("walking",x+P,1,"ease-out"),d("walking",x+v-P,1),d("walking",x+v,0,"ease-in");const C=c;let F=l;for(let R=0;;R=Math.min(S,R+Iw)){const B=x+Z0(_,R/S)*v,{point:j,direction:H}=J0(E,R);if(F+=Bi(F,An([0,0],H)),d("x",B,j[0]),d("z",B,j[1]),d("rotateY",B,F),d("walk",B,C+R/$),R>=S)break}return c=C+S/$,[r,a]=E[E.length-1].point,l=F,x+v},m=[];let y=0;for(const b of e){const A=b.at??y;let M=A;if(ba.includes(b.do))M=g(b.do,b,A);else if(b.do==="face")M=f(A,typeof b.toward=="number"?b.toward:An([r,a],b.toward));else if(b.do==="hold")M=A+(b.for??1e3);else if(b.do==="place")d("x",A,r),d("z",A,a),[r,a]=b.to,d("x",A+1,r),d("z",A+1,a),typeof b.toward=="number"&&(d("rotateY",A,l),l=b.toward,d("rotateY",A+1,l)),M=A+1;else if(b.do==="pose"){M=A+(b.for??500);const E=typeof b.pose=="string"?ze[b.pose]:b.pose;p(A,M,E)}else if(b.do==="gag"){const E=D0(b.gag,{at:A,from:{...o}});let x=E[0];for(const S of E.slice(1))p(x.time,S.time,Object.fromEntries(Object.entries(S.pose).filter(([I,v])=>o[I]!==v)),S.easing??"ease-in-out"),x=S;M=x.time}m.push({do:b.do,start:A,end:M}),y=M}const T=`${n.scene}/${t}`,k=[...h].map(([b,A])=>({id:`${t}-${b}`,target:T,property:b,keyframes:U0(A)}));return u.length>0&&k.push({id:`${t}-gait`,target:T,property:"gait",keyframes:u}),{tracks:k,duration:y,beats:m,end:{position:[r,a],heading:l,pose:{...o}}}}const ed={x:0,y:0,scale:1,rotate:0,shakeX:0,shakeY:0,shakeRotate:0};function Rw(t){const e=n=>{const s=t?.get(n);return typeof s=="number"?s:ed[n]};return{x:e("x"),y:e("y"),scale:e("scale"),rotate:e("rotate"),shakeX:e("shakeX"),shakeY:e("shakeY"),shakeRotate:e("shakeRotate")}}function Lw(t,e,n){const s=n.width/2,i=n.height/2,r=1+2*Math.max(Math.abs(e.shakeX),Math.abs(e.shakeY))/Math.max(1,Math.min(n.width,n.height));t.translate(s+e.x+e.shakeX,i+e.y+e.shakeY),t.rotate((e.rotate+e.shakeRotate)*Math.PI/180),t.scale(e.scale*r,e.scale*r),t.translate(-s,-i)}function Fw(t,e,n){const s=e.width/2,i=e.height/2,o=(t.rotate+t.shakeRotate)*Math.PI/180,r=(n.x-s)*t.scale,a=(n.y-i)*t.scale;return{x:s+t.x+t.shakeX+r*Math.cos(o)-a*Math.sin(o),y:i+t.y+t.shakeY+r*Math.sin(o)+a*Math.cos(o)}}function nd(t,e,n={},s){const i=n.length??240,o=9,r=28,a=i-22;t.save(),t.translate(e.x,e.y),t.rotate((n.angle??-30)*Math.PI/180),t.fillStyle=n.color??"#f4c542",t.fillRect(r,-o,a-r,2*o),t.fillStyle="#e8b4a0",t.fillRect(a,-o,i-a,2*o),t.fillStyle="#f1dcbf",t.beginPath(),t.moveTo(0,0),t.lineTo(r,-o),t.lineTo(r,o),t.closePath(),t.fill(),t.fillStyle=n.outline??"#2f2f33",t.beginPath(),t.moveTo(0,0),t.lineTo(r*.35,-o*.35),t.lineTo(r*.35,o*.35),t.closePath(),t.fill(),t.strokeStyle=n.outline??"#2f2f33",t.lineWidth=3,t.lineJoin="round",t.lineCap="round";const l=[[{x:0,y:0},{x:r,y:-o},{x:i,y:-o},{x:i,y:o},{x:r,y:o},{x:0,y:0}],[{x:r,y:-o},{x:r,y:o}],[{x:a,y:-o},{x:a,y:o}]];for(const c of l)od(t,c,s);t.restore()}function va(t,e,n={},s){const i=n.length??90,o=n.thickness??34;t.save(),t.translate(e.x,e.y),t.rotate((n.angle??-35)*Math.PI/180);const r=-o/2;t.fillStyle=n.color??"#f4a7b9",t.fillRect(0,r,i,o),t.fillStyle="#e9edf2",t.fillRect(i*.45,r,i*.55,o),t.strokeStyle=n.outline??"#2f2f33",t.lineWidth=3,t.lineJoin="round";const a=[{x:0,y:r},{x:i,y:r},{x:i,y:-r},{x:0,y:-r},{x:0,y:r}],l=[{x:i*.45,y:r},{x:i*.45,y:-r}];if(s)s.line(a),s.line(l);else for(const c of[a,l]){t.beginPath(),t.moveTo(c[0].x,c[0].y);for(const h of c.slice(1))t.lineTo(h.x,h.y);t.stroke()}t.restore()}const sd=150,Nw={pencil:44,eraser:30};function Ma(t,e,n={},s){const i=n.tool??"pencil",o=n.skin??"#f1c9a5",r=n.outline??"#2f2f33",a=n.scale??1,l=Math.min(1,Math.max(0,n.lift??0)),c=(n.angle??-30)*Math.PI/180,h=s?s.nudge(.6):{x:0,y:0},u=sd*a*(1+.05*l);l>0&&(t.save(),t.fillStyle=r,t.globalAlpha=.15*l,t.beginPath(),t.ellipse(e.x,e.y,9*a,4*a,0,0,Math.PI*2),t.fill(),t.restore());const d={x:e.x+h.x+6*l*a,y:e.y+h.y-18*l*a},f=$t.pencilGrip,p=E=>{const x=E.fingers.thumb,S=E.fingers.index,I=E.fingers.middle,v=id([x.points[3],S.points[3],I.points[3]]),$=id([x.points[1],S.points[0]]),_=(x.depths[3]+S.depths[3]+I.depths[3])/3;return{pinch:v,direction:Math.atan2($.y-v.y,$.x-v.x),depth:_}},g=ai(f,{size:u}),m=c-p(g).direction,y=ai(f,{size:u,angle:m*180/Math.PI}),T=p(y),k=Nw[i]*a,b={x:T.pinch.x-Math.cos(c)*k,y:T.pinch.y-Math.sin(c)*k},A={x:d.x-b.x,y:d.y-b.y},M=y.axes.up;Dw(t,A,{x:-M.x,y:-M.y},u,n.arm??300*a,o,n.sleeve??"#5b7db1",r),li(t,A,f,{size:u,angle:m*180/Math.PI,skin:o,ink:r,lineWidth:3*a,prop:{depth:T.depth,draw:()=>{t.save(),t.translate(d.x,d.y),t.scale(a,a),i==="eraser"?va(t,{x:0,y:0},{angle:c*180/Math.PI,outline:r},s):nd(t,{x:0,y:0},{angle:c*180/Math.PI,length:190,outline:r},s),t.restore()}}})}const id=t=>({x:t.reduce((e,n)=>e+n.x,0)/t.length,y:t.reduce((e,n)=>e+n.y,0)/t.length});function Dw(t,e,n,s,i,o,r,a){const l={x:-n.y,y:n.x},c=s*.15,h=(g,m,y)=>({x:e.x+n.x*g+l.x*m*y,y:e.y+n.y*g+l.y*m*y}),u=h(i,0,0),d=g=>{const m=t.createLinearGradient(e.x,e.y,u.x,u.y);return m.addColorStop(0,g),m.addColorStop(.6,g),m.addColorStop(1,qw(g)),m},f=Math.min(s*.55,i*.35);t.save(),t.lineJoin="round",t.lineCap="round",t.lineWidth=3*(s/sd),t.beginPath(),t.moveTo(h(-s*.1,-1,c).x,h(-s*.1,-1,c).y),t.lineTo(h(f+4,-1,c*1.1).x,h(f+4,-1,c*1.1).y),t.lineTo(h(f+4,1,c*1.1).x,h(f+4,1,c*1.1).y),t.lineTo(h(-s*.1,1,c).x,h(-s*.1,1,c).y),t.closePath(),t.fillStyle=o,t.fill(),t.strokeStyle=a,t.beginPath(),t.moveTo(h(0,-1,c).x,h(0,-1,c).y),t.lineTo(h(f,-1,c*1.1).x,h(f,-1,c*1.1).y),t.moveTo(h(0,1,c).x,h(0,1,c).y),t.lineTo(h(f,1,c*1.1).x,h(f,1,c*1.1).y),t.stroke();const p=[h(f,-1,c*1.3),h(i,-1,c*1.5),h(i,1,c*1.5),h(f,1,c*1.3)];t.beginPath(),p.forEach((g,m)=>m?t.lineTo(g.x,g.y):t.moveTo(g.x,g.y)),t.closePath(),t.fillStyle=d(r),t.fill(),t.strokeStyle=d(a),t.beginPath(),t.moveTo(p[1].x,p[1].y),t.lineTo(p[0].x,p[0].y),t.lineTo(p[3].x,p[3].y),t.lineTo(p[2].x,p[2].y),t.stroke(),t.restore()}function Ww(t,e,n={}){const s=n.offstage??{x:2e3,y:1400},i=n.enter??450,o=n.exit??450,r=n.linger??1500,a=[...t].filter(g=>g.path.length>0).sort((g,m)=>g.start-m.start),l=g=>g.tool??"pencil",c=g=>{const m=Math.min(1,Math.max(0,g));return m*m*(3-2*m)},h=(g,m,y)=>({x:g.x+(m.x-g.x)*y,y:g.y+(m.y-g.y)*y}),u=a.find(g=>e>=g.start&&e<=g.end);if(u){const g=u.end-u.start,m=g>0?(e-u.start)/g:1;return{at:ni(u.path,m),tool:l(u),lift:0,drawing:!0}}const d=[...a].reverse().find(g=>g.end<e),f=a.find(g=>g.start>e),p=g=>g.path[g.path.length-1];if(d&&f&&f.start-d.end<=r){const g=(e-d.end)/(f.start-d.end),m=g<.5?l(d):l(f);return{at:h(p(d),f.path[0],c(g)),tool:m,lift:Math.sin(Math.PI*g),drawing:!1}}if(f&&f.start-e<=i){const g=1-(f.start-e)/i;return{at:h(s,f.path[0],c(g)),tool:l(f),lift:1-c(g),drawing:!1}}if(d&&e-d.end<=o){const g=(e-d.end)/o;return{at:h(p(d),s,c(g)),tool:l(d),lift:c(g),drawing:!1}}return null}function Bw(t,e,n,s=.08,i=32){const o=Math.PI*2*(1+s),r=[];for(let a=0;a<=i;a++){const l=-Math.PI/2+o*a/i;r.push({x:t+Math.cos(l)*n,y:e+Math.sin(l)*n})}return r}function jw(t){const{path:e}=t,n=e.map(a=>a.x),s=e.map(a=>a.y),i=Math.min(...n),o=Math.min(...s),r=t.hand===!1?void 0:t.hand===!0||t.hand===void 0?{}:t.hand;return{type:"custom",x:i,y:o,width:Math.max(1,Math.max(...n)-i),height:Math.max(1,Math.max(...s)-o),props:{draw:0},draw(a,l,c){const h=Math.min(1,Math.max(0,Number(l.props?.draw??0)));a.translate(-i,-o),a.strokeStyle=t.color??"#2f2f33",a.lineWidth=t.lineWidth??5,a.lineCap="round",a.lineJoin="round";const u=t.sketch?si(a,t.sketch,c):void 0;h>0&&(u?t.smooth?u.curve(e,h):u.line(e,h):od(a,bn(e,h))),r&&h>0&&h<1&&Ma(a,ni(e,h),r,u)}}}function qw(t){const e=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t.trim());if(!e)return"rgba(0, 0, 0, 0)";const n=e[1].length===3?[...e[1]].map(r=>r+r).join(""):e[1],[s,i,o]=[0,2,4].map(r=>parseInt(n.slice(r,r+2),16));return`rgba(${s}, ${i}, ${o}, 0)`}function od(t,e,n){if(!(e.length<2)){if(n)return n.line(e);t.beginPath(),t.moveTo(e[0].x,e[0].y);for(const s of e.slice(1))t.lineTo(s.x,s.y);t.stroke()}}const ji=1e5;function Yw(t,e,n,s,i=6){const o=[],r=Math.max(1,Math.round(i));for(let a=0;a<=r;a++)o.push({x:a%2===0?t:t+n,y:e+s*a/r});return o}function Sa(t,e,n,s){if(s<=0||e.length===0)return;const i=bn(e,s),o=n/2,r=a=>{t.beginPath(),t.rect(-ji,-ji,2*ji,2*ji),a(),t.clip("evenodd")};for(const a of i)r(()=>{t.moveTo(a.x+o,a.y),t.arc(a.x,a.y,o,0,Math.PI*2)});for(let a=1;a<i.length;a++){const l=i[a-1],c=i[a],h=Math.hypot(c.x-l.x,c.y-l.y);if(h===0)continue;const u=-(c.y-l.y)/h*o,d=(c.x-l.x)/h*o;r(()=>{t.moveTo(l.x+u,l.y+d),t.lineTo(c.x+u,c.y+d),t.lineTo(c.x-u,c.y-d),t.lineTo(l.x-u,l.y-d),t.closePath()})}}function Kw(t,e,n,s,i){t.save(),Sa(t,e,n,s),i(),t.restore()}function zw(t,e){const n=e.width??40,s=e.hand===!0?{}:e.hand||void 0,i=e.eraser===!1?void 0:e.eraser===!0||e.eraser===void 0?{}:e.eraser;return{...t,props:{...t.props,erase:0},draw(o,r,a){const l=Number(r.props?.erase??0);if(o.save(),Sa(o,e.path,n,l),t.draw(o,r,a),o.restore(),!i||l<=0||l>=1)return;const c=ni(e.path,l);s?Ma(o,c,{...s,tool:"eraser"}):va(o,c,i)}}}function ps(){const t=new Map,e=(n,...s)=>t.set(n,[...t.get(n)??[],...s]);return{keys:n=>t.get(n),push:e,tween(n,s,i,o,r=300){e(n,{time:o.at,value:s},{time:o.at+(o.duration??r),value:i,...o.easing?{easing:o.easing}:{}})},last(n,s){const i=t.get(n);return i?[...i].sort((o,r)=>o.time-r.time)[i.length-1].value:s},valueAt:(n,s)=>qi(t.get(n),s),cutAfter(n,s){for(const i of n)t.set(i,(t.get(i)??[]).filter(o=>o.time<=s))},tracks(n){return[...t].filter(([,s])=>s.length>0).map(([s,i])=>({id:`${n}-${s}`,target:n,property:s,keyframes:Xw(i)}))}}}function qi(t,e){if(!t||t.length===0)return 0;const n=[...t].sort((s,i)=>s.time-i.time);if(e<=n[0].time)return n[0].value;for(let s=1;s<n.length;s++)if(e<=n[s].time){const i=n[s-1],o=n[s];return o.time===i.time?o.value:i.value+(o.value-i.value)*(e-i.time)/(o.time-i.time)}return n[n.length-1].value}function Yi(t){const e=[...t??[]].sort((n,s)=>n.time-s.time);return e.slice(1).flatMap((n,s)=>n.value!==e[s].value?[{start:e[s].time,end:n.time}]:[])}function Xw(t){return[...t].sort((n,s)=>n.time-s.time).map(n=>({time:n.time,value:n.value,...n.easing?{easing:n.easing}:{}}))}const Gw=.0016,Uw=.6,Ue=33;function ms(t){const e=(o,r)=>`piece.${o.id}.${r}`,n=(o,r)=>({x:o.home.x+t.valueAt(e(o,"x"),r),y:o.home.y+t.valueAt(e(o,"y"),r)}),s=(o,r)=>{const a=t.keys(e(o,"x"));if(!a||a.length<2)return;const l=n(o,r-Ue),c=n(o,r);return{x:(c.x-l.x)/Ue,y:(c.y-l.y)/Ue}},i=(o,r)=>t.cutAfter(["x","y","rotate"].map(a=>e(o,a)),r);return{at:n,cutAfter:i,follow(o,r){for(const a of r)t.push(e(o,"x"),{time:a.time,value:a.x-o.home.x}),t.push(e(o,"y"),{time:a.time,value:a.y-o.home.y})},fling(o,r){const a=n(o,r.at),l=r.velocity??s(o,r.at)??{x:.5,y:-.6},c=r.gravity??Gw,h=r.duration??900,u=(r.spin??Uw)*(l.x<0?-1:1),d=t.valueAt(e(o,"rotate"),r.at);i(o,r.at);for(let f=0;f<=h;f+=Ue){const p=a.x+l.x*f,g=a.y+l.y*f+.5*c*f*f;t.push(e(o,"x"),{time:r.at+f,value:p-o.home.x}),t.push(e(o,"y"),{time:r.at+f,value:g-o.home.y}),t.push(e(o,"rotate"),{time:r.at+f,value:d+u*f})}t.tween(e(o,"opacity"),1,0,{at:r.at+h*.6,duration:h*.4})},move(o,r){const a=n(o,r.at);t.tween(e(o,"x"),a.x-o.home.x,r.to.x-o.home.x,r,400),t.tween(e(o,"y"),a.y-o.home.y,r.to.y-o.home.y,r,400)}}}function Ta(t,e,{ground:n,every:s,floors:i}){if(i.every(k=>k.windows.length===0))return t;const o=t.find(k=>k.target===e&&k.property==="y"),r=new Nt({id:`${e}-ride`,tracks:o?[o]:[]}),a=k=>o?Number(r.getStateAtTime(k).values.get(e)?.get("y")??0):0,l=k=>{const b=n+a(k);return i.findIndex(A=>Math.abs(A.top-b)<.5)},c=(o?.keyframes??[]).map(k=>k.time),h=k=>{const b=S=>S<0?0:i[S].offset(k),A=l(k);if(A>=0)return b(A);if(Math.abs(a(k))<.5)return 0;const M=S=>l(S)>=0||Math.abs(a(S))<.5,E=[...c].reverse().find(S=>S<=k&&M(S)),x=c.find(S=>S>=k&&M(S));return E===void 0&&x===void 0?0:E===void 0?b(l(x)):x===void 0||x===E?b(l(E)):b(l(E))+(b(l(x))-b(l(E)))*(k-E)/(x-E)},u=i.flatMap(k=>k.windows),d=(k,b)=>u.some(A=>A.start<b&&A.end>k)||h(k)!==h(b),f=o?[...o.keyframes]:[{time:0,value:0}],p=[{...f[0],value:f[0].value+h(f[0].time)}],g=(k,b)=>{const A=new Set([b]);for(let M=k+s;M<b;M+=s)A.add(M);for(const M of u)for(const E of[M.start,M.end])E>k&&E<b&&A.add(E);for(const M of[...A].sort((E,x)=>E-x))p.push({time:M,value:a(M)+h(M)})};for(let k=1;k<f.length;k++){const b=f[k-1].time,A=f[k].time;d(b,A)?g(b,A):p.push({...f[k],value:f[k].value+h(A)})}const m=f[f.length-1].time,y=Math.max(m,...u.map(k=>k.end));y>m&&g(m,y);const T={id:o?.id??`${e}-y`,target:e,property:"y",keyframes:p};return o?t.map(k=>k===o?T:k):[...t,T]}function Ve(t){const e=t.indexOf(":");return e<0?{kind:t,rest:""}:{kind:t.slice(0,e),rest:t.slice(e+1)}}function Oe(t,e,n,s){const i=Object.keys(n.anchors).map(r=>Ve(r).kind),{kind:o}=Ve(e);return i.includes(o)?new Error(`${t}: no anchor "${e}"${s?`: ${s}`:""} (anchors: ${Object.keys(n.anchors).join(", ")})`):new Error(`${t}: ${ot("anchor",o,i)} (anchors: ${Object.keys(n.anchors).join(", ")})`)}function ys(t,e,n){return new Error(`${t}.edit: ${ot("edit",e,Object.keys(n.edits))}`)}function Mt(t,e,n,s){return{x:t+n/2,y:e+s/2,left:t,right:t+n,top:e,bottom:e+s,width:n,height:s}}const rd={background:"#1e1e2e",gutter:"#6c7086",text:"#cdd6f4",keyword:"#cba6f7",string:"#a6e3a1",number:"#fab387",comment:"#7f849c",highlight:"rgba(249, 226, 175, 0.22)",strike:"#f38ba8",font:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace"},Ki=["wipe","fly","blur"],bs={kind:"code",create:"codePanel({ code, language?, x, y, fontSize?, lineHeight?, width?, hidden? })",anchors:{box:"the whole panel","line:N":"line N’s text (lines count from 1): stand on top, point at x, y, swipe left to right","token:N:TEXT":"the first TEXT on line N (token:N#K:TEXT for the Kth): a word, which can come loose as a piece","spot:N:C":"a place in line N before column C (0 is before its first character); spot:N:C:W is W characters wide. Aim a put or a write here"},edits:{highlight:"line anchors; { at, duration?, on? }: tint lines (on: false clears)",strike:"line anchors; { at, duration? }: strike lines through, left to right",remove:"line anchors; { at, duration?, style?: wipe | fly | blur, from?: left | right, close? }: take lines away; the lines below close the gap",type:"line anchors given in `hidden`; { at, duration? }: type them in",insert:"a spot; { at, text, duration? }: type new text into the line there; the line makes room",write:"a token; { at, text, duration? }: write new text into the word’s place",drop:"a token; { at, into: a spot, duration? }: put the word into a line there",move:"a token; { at, to: an anchor name or { x, y }, duration? }: move the word there",fling:"a token; { at, velocity?, spin?, gravity?, duration? }: throw or kick the word away on a spinning arc"}},Vw=.9,Jw=8;function Zw(t){const e={...rd,...t.theme},n=t.code.replace(/\t/g," ").replace(/\n$/,"").split(`
|
|
56
|
+
`),s=t.fontSize??16,i=(t.lineHeight??1.6)*s,o=(t.charWidth??.6)*s,r=t.padding??12,a=t.lineNumbers===!1?0:(String(n.length).length+2)*o,l=Math.max(1,...n.map(H=>H.length)),c=t.width??r*2+a+l*o,h=r*2+n.length*i,u=t.x+r+a,d=new Set(t.hidden??[]),f=t.language??"plain";if(!Xi.includes(f))throw new Error(`codePanel: ${ot("language",f,Xi)}`);const p=n.map(H=>ld(H,f).flatMap(N=>Array.from(N.text,()=>e[N.kind]))),g=ps(),m=ms(g),y=[],T=new Map,k=[],b=[],A=H=>{if(!Number.isInteger(H)||H<1||H>n.length)throw new Error(`codePanel: no line ${H} (it has ${n.length})`)},M=g.tween,E=g.last,x=(H,N,D,O,L,q=300)=>{A(H),M(`line.${H}.${N}`,D,O,L,q)},S=(H,N)=>y.filter(D=>D.line<H&&D.closed<=N).length,I=Mt,v=H=>t.y+r+(H-1)*i,$=H=>Array.isArray(H)?H:[H],_=(H,N,D)=>{let O=-1;for(let L=0;L<D;L++)if(O=n[H-1].indexOf(N,O+1),O<0)throw new Error(`codePanel: line ${H} has no ${D>1?`${D}th `:""}"${N}"`);return O},P={};n.forEach((H,N)=>{const D=N+1;P[`line.${D}.highlight`]=0,P[`line.${D}.strike`]=0,P[`line.${D}.wipe`]=0,P[`line.${D}.reveal`]=d.has(D)?0:1,P[`line.${D}.shift`]=0});const C={type:"custom",x:t.x,y:t.y,width:c,height:h,props:P,about:{kind:"code panel",summary:`${n.length} lines of ${f} code. Its lines and words are places in the scene (line(), token(), spot()); its edits are methods that record tracks (tracks()).`,get props(){return tk(Object.keys(P))},actions:Ea},draw(H,N){const D=N.props??{},O=K=>Number(D[K]??P[K]),L=r+a,q=K=>r+(K-1)*i-O(`line.${K}.shift`)*i;H.fillStyle=e.background,ad(H,0,0,c,h,8),H.fill(),H.font=`${s}px ${e.font}`,H.textBaseline="middle",H.textAlign="left";const G=(K,Z,nt,W,z)=>{const Y=n[K-1];for(let V=Z;V<nt;V++)Y[V]!==" "&&(H.fillStyle=p[K-1][V],H.fillText(Y[V],W+(V-Z)*o,z))};H.save(),ad(H,0,0,c,h,8),H.clip(),n.forEach((K,Z)=>{const nt=Z+1,W=O(`line.${nt}.wipe`);if(W>=1)return;const z=q(nt),Y=z+i/2,V=Math.max(1,K.length)*o,Q=Math.round(O(`line.${nt}.reveal`)*K.length),tt=T.get(nt)??{style:"wipe",from:"left"};H.save(),W>0&&Qw(H,tt,W,{left:L-a,top:z,width:a+V+o,height:i},c);const st=O(`line.${nt}.highlight`);st>0&&(H.globalAlpha*=Math.min(1,st),H.fillStyle=e.highlight,H.fillRect(L-o/2,z,V+o,i),H.globalAlpha/=Math.min(1,st)),a>0&&Q>0&&(H.fillStyle=e.gutter,H.textAlign="right",H.fillText(String(nt),L-o,Y),H.textAlign="left");const yt=[...k.filter(J=>J.line===nt).map(J=>({column:J.column,length:J.text.length,piece:J,insert:void 0})),...b.filter(J=>J.line===nt).map(J=>({column:J.column,length:0,piece:void 0,insert:J}))].sort((J,Tt)=>J.column-Tt.column||J.length-Tt.length);let ut=0,rt=L;for(const J of yt){G(nt,ut,Math.min(J.column,Q),rt,Y),rt+=(J.column-ut)*o;let Tt=J.length,bt="";if(J.piece){const X=J.piece.written??"",U=O(`piece.${J.piece.id}.write`);X&&U>0?(bt=X.slice(0,Math.round(U*X.length)),Tt=J.length+(X.length-J.length)*Math.min(1,U*2)):Tt=J.length*(1-O(`piece.${J.piece.id}.away`))}else J.insert&&(Tt=J.insert.chars*O(`insert.${J.insert.id}.open`),J.insert.text&&(bt=J.insert.text.slice(0,Math.round(O(`insert.${J.insert.id}.type`)*J.insert.text.length))));H.fillStyle=e.text;for(let X=0;X<bt.length;X++)bt[X]!==" "&&H.fillText(bt[X],rt+X*o,Y);rt+=Tt*o,ut=J.column+J.length}G(nt,ut,Math.max(ut,Q),rt,Y);const St=O(`line.${nt}.strike`);St>0&&(H.strokeStyle=e.strike,H.lineWidth=Math.max(1.5,s/10),H.beginPath(),H.moveTo(L,Y),H.lineTo(L+V*Math.min(1,St),Y),H.stroke()),H.restore()});for(const K of k){const Z=O(`piece.${K.id}.opacity`);if(Z<=0||O(`line.${K.line}.wipe`)>=1)continue;const nt=L+(K.column+K.text.length/2)*o+O(`piece.${K.id}.x`),W=q(K.line)+i/2+O(`piece.${K.id}.y`);H.save(),H.globalAlpha=Math.min(1,Z),H.translate(nt,W),H.rotate(O(`piece.${K.id}.rotate`)*Math.PI/180),G(K.line,K.column,K.column+K.text.length,-K.text.length*o/2,0),H.restore()}H.restore()}},F=H=>{const{kind:N,rest:D}=Ve(H),O=L=>Oe("codePanel",H,bs,L);if(N==="box"){if(D)throw O("box takes no arguments");return{kind:N}}if(N==="line"){if(!/^\d+$/.test(D))throw O("write it line:N");return{kind:N,n:Number(D)}}if(N==="token"){const L=/^(\d+)(?:#(\d+))?:(.+)$/.exec(D);if(!L)throw O("write it token:N:TEXT, or token:N#K:TEXT for the Kth");return{kind:N,n:Number(L[1]),occurrence:L[2]?Number(L[2]):1,text:L[3]}}if(N==="spot"){const L=/^(\d+):(\d+)(?::(\d+))?$/.exec(D);if(!L)throw O("write it spot:N:C, or spot:N:C:W for W characters");return{kind:N,n:Number(L[1]),column:Number(L[2]),width:L[3]?Number(L[3]):1}}throw O()},R=(H,N,D,O=!1)=>{const L=Array.isArray(N)?N:[N];if(L.length===0||O&&L.length>1)throw new Error(`codePanel.edit: ${H} takes ${O?"one":"at least one"} ${D} anchor`);return L.map(q=>{const G=F(q);if(G.kind!==D)throw new Error(`codePanel.edit: ${H} takes ${D} anchors (${D}:…), not "${q}"`);return G})},B=(H,N)=>{if(typeof N.text!="string")throw new Error(`codePanel.edit: ${H} needs \`text\` (the text to write)`);return N.text},j={kind:"code",about:bs,target:C,lines:n,box:I(t.x,t.y,c,h),line(H,N=1/0){return A(H),I(u,v(H)-S(H,N)*i,Math.max(1,n[H-1].length)*o,i)},token(H,N,D=1,O=1/0){A(H);const L=_(H,N,D);return I(u+L*o,v(H)-S(H,O)*i,N.length*o,i)},highlight(H,N){for(const D of $(H)){const O=E(`line.${D}.highlight`,0);x(D,"highlight",O,N.on===!1?0:1,N,200)}return j},strike(H,N){for(const D of $(H))x(D,"strike",E(`line.${D}.strike`,0),1,N);return j},remove(H,N){const D=$(H),O=N.style??"wipe";if(!Ki.includes(O))throw new Error(`codePanel.remove: ${ot("style",O,Ki)}`);const L=O==="wipe"?300:450,q=N.at+(N.duration??L),G=N.close??250;for(const K of D)x(K,"wipe",0,1,{...N,easing:N.easing??(O==="fly"?"ease-in":void 0)},L),T.set(K,{style:O,from:N.from??"left"}),y.push({line:K,closed:q+G});for(let K=1;K<=n.length;K++){if(D.includes(K))continue;const Z=D.filter(W=>W<K).length;if(Z===0)continue;const nt=E(`line.${K}.shift`,0);x(K,"shift",nt,nt+Z,{at:q,duration:G,easing:"ease-in-out"})}return j},type(H,N){return x(H,"reveal",0,1,{duration:n[H-1].length*45,...N}),j},piece(H,N,D=1){if(typeof H=="string"){const K=F(H);if(K.kind!=="token")throw new Error(`codePanel.piece: a piece is a word, token:N:TEXT, not "${H}"`);return j.piece(K.n,K.text,K.occurrence)}const O=H;if(N===void 0)throw new Error('codePanel.piece: which word? piece(n, text) or piece("token:N:TEXT")');A(O);const L=_(O,N,D),q=k.find(K=>K.line===O&&K.column===L&&K.text===N);if(q)return q;if(k.some(K=>K.line===O&&L<K.column+K.text.length&&K.column<L+N.length))throw new Error(`codePanel: "${N}" on line ${O} overlaps another piece`);const G={id:k.length+1,line:O,column:L,text:N,home:j.token(O,N,D,0)};k.push(G);for(const K of["x","y","rotate","write","away"])P[`piece.${G.id}.${K}`]=0;return P[`piece.${G.id}.opacity`]=1,G},follow(H,N){return m.follow(H,N),j},fling(H,N){return m.fling(H,N),j},move(H,N){return m.move(H,N),j},write(H,N,D){return H.written=N,M(`piece.${H.id}.write`,0,1,{duration:Math.max(1,N.length)*70,...D}),j},spot(H,N,D=1,O=1/0){A(H);const L=b.filter(q=>q.line===H&&q.column<=N&&q.at<=O).reduce((q,G)=>q+G.chars,0);return I(u+(N+L)*o,v(H)-S(H,O)*i,D*o,i)},insert(H,N,D,O){A(H);const L={id:b.length+1,line:H,column:N,chars:D.length,text:D,at:O.at};b.push(L),P[`insert.${L.id}.open`]=0,P[`insert.${L.id}.type`]=0;const q=O.duration??D.length*70;return M(`insert.${L.id}.open`,0,1,{at:O.at,duration:q*.6,easing:"ease-out"}),M(`insert.${L.id}.type`,0,1,{at:O.at,duration:q}),j},drop(H,N,D,O){A(N);const L=O.duration??250,q=N===H.line,G=O.easing??(q?"linear":"ease-out"),K=j.landing(H,N,D,O.at),Z={id:b.length+1,line:N,column:D,chars:H.text.length,at:O.at};return b.push(Z),P[`insert.${Z.id}.open`]=0,M(`insert.${Z.id}.open`,0,1,{at:O.at,duration:L,easing:q?G:"ease-out"}),M(`piece.${H.id}.away`,E(`piece.${H.id}.away`,0),1,{at:O.at,duration:L,easing:q?G:"ease-in-out"}),m.cutAfter(H,O.at),j.move(H,{at:O.at,duration:L,easing:G,to:{x:K.x,y:K.y}}),M(`piece.${H.id}.rotate`,g.valueAt(`piece.${H.id}.rotate`,O.at),0,{at:O.at,duration:L}),j},landing(H,N,D,O=1/0){const L=j.spot(N,D,H.text.length,O),q=N===H.line&&D>H.column?H.text.length*o:0;return I(L.left-q,L.top,L.width,L.height)},ride(H,N,D){const O=n.map((L,q)=>{const G=g.keys(`line.${q+1}.shift`)??[];return{top:v(q+1),offset:K=>-qi(G,K)*i,windows:Yi(G)}});return Ta(H,N,{ground:D.ground,every:D.every??Ue,floors:O})},tracks:g.tracks,anchor(H,N=1/0){const D=F(H);return D.kind==="box"?j.box:D.kind==="line"?j.line(D.n,N):D.kind==="token"?j.token(D.n,D.text,D.occurrence,N):j.spot(D.n,D.column,D.width,N)},edit(H,N,D){const O=()=>R(H,N,"line").map(L=>L.n);if(H==="highlight")return j.highlight(O(),D);if(H==="strike")return j.strike(O(),D);if(H==="remove")return j.remove(O(),D);if(H==="type"){for(const L of O())j.type(L,D);return j}if(H==="insert"){const[L]=R(H,N,"spot",!0);return j.insert(L.n,L.column,B(H,D),D)}if(H==="write"||H==="drop"||H==="move"||H==="fling"){const[L]=R(H,N,"token",!0),q=j.piece(L.n,L.text,L.occurrence);if(H==="write")return j.write(q,B(H,D),D);if(H==="fling")return j.fling(q,D);if(H==="drop"){const K=typeof D.into=="string"?F(D.into):void 0;if(K?.kind!=="spot")throw new Error("codePanel.edit: drop needs `into`, a spot anchor (spot:N:C)");return j.drop(q,K.n,K.column,D)}const G=typeof D.to=="string"?j.anchor(D.to,D.at):D.to;if(!G||typeof G.x!="number"||typeof G.y!="number")throw new Error("codePanel.edit: move needs `to`, an anchor name or { x, y }");return j.move(q,{...D,to:G})}throw ys("codePanel",H,bs)}};return j}function Qw(t,e,n,s,i){if(e.style==="wipe"){t.beginPath(),e.from==="right"?t.rect(s.left,s.top,s.width*(1-n),s.height):t.rect(s.left+n*s.width,s.top,s.width*(1-n),s.height),t.clip();return}const o=Jw*n;if(o>.2&&"filter"in t&&(t.filter=`blur(${o.toFixed(1)}px)`),t.globalAlpha*=1-n,e.style==="fly"){const r=e.from==="right"?-1:1;t.translate(r*n*Vw*i,0),t.rotate(r*n*.08)}else{const r=1+.08*n,a=s.left+s.width/2,l=s.top+s.height/2;t.translate(a,l),t.scale(r,r),t.translate(-a,-l)}}const Ea={highlight:"highlight(n | n[], { at, duration?, on? }): tint lines (on: false clears)",strike:"strike(n | n[], { at, duration? }): strike lines through, left to right",remove:"remove(n | n[], { at, duration?, style?: wipe | fly | blur, from?: left | right, close? }): take lines away; the lines below close the gap",type:"type(n, { at, duration? }): type in a line given in `hidden`",piece:"piece(n, text, occurrence?): make a word a piece that can come loose (returns it, with its home box)",follow:"follow(piece, path): carry a piece along timed points (handPath() gives a hand’s)",fling:"fling(piece, { at, velocity?, spin?, gravity?, duration? }): throw or kick a piece away on a spinning arc",move:"move(piece, { at, to: { x, y }, duration?, easing? }): move a piece’s centre to a point",write:"write(piece, text, { at, duration? }): type new text into a piece’s place",insert:"insert(n, column, text, { at, duration? }): type new text into a line; the line makes room",drop:"drop(piece, n, column, { at, duration? }): put a piece into a line (into its own line it slides, the text closing behind it)",ride:"ride(tracks, figureId, { ground }): a figure’s tracks with it carried by the line it stands on"};function tk(t){const e=[[/^line\.\d+\.highlight$/,{description:"How much the line is tinted",unit:"0..1",min:0,max:1}],[/^line\.\d+\.strike$/,{description:"How far the strike-through has drawn",unit:"0..1",min:0,max:1}],[/^line\.\d+\.wipe$/,{description:"How far the line has gone (wiped, flown off or blurred)",unit:"0..1",min:0,max:1}],[/^line\.\d+\.reveal$/,{description:"How much of the line is typed in",unit:"0..1",min:0,max:1}],[/^line\.\d+\.shift$/,{description:"How many rows the line has moved up",unit:"rows"}],[/^piece\.\d+\.(x|y)$/,{description:"The piece moved from its home",unit:"px"}],[/^piece\.\d+\.rotate$/,{description:"The piece turned",unit:"degrees"}],[/^piece\.\d+\.opacity$/,{description:"How opaque the piece is",unit:"0..1",min:0,max:1}],[/^piece\.\d+\.write$/,{description:"How much of the text written into its place is typed",unit:"0..1",min:0,max:1}],[/^piece\.\d+\.away$/,{description:"How far its old place has closed",unit:"0..1",min:0,max:1}],[/^insert\.\d+\.open$/,{description:"How much room the insert has opened",unit:"0..1",min:0,max:1}],[/^insert\.\d+\.type$/,{description:"How much of the inserted text is typed",unit:"0..1",min:0,max:1}]],n={};for(const s of t){const i=e.find(([o])=>o.test(s));i&&(n[s]=i[1])}return n}function ad(t,e,n,s,i,o){t.beginPath(),t.moveTo(e+o,n),t.arcTo(e+s,n,e+s,n+i,o),t.arcTo(e+s,n+i,e,n+i,o),t.arcTo(e,n+i,e,n,o),t.arcTo(e,n,e+s,n,o),t.closePath()}const zi={go:["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","nil","true","false"],rust:["as","async","await","break","const","continue","crate","else","enum","extern","false","fn","for","if","impl","in","let","loop","match","mod","move","mut","pub","ref","return","self","Self","static","struct","super","trait","true","type","unsafe","use","where","while","Some","None","Ok","Err"],csharp:["abstract","async","await","base","bool","break","case","catch","class","const","continue","default","do","else","enum","false","finally","for","foreach","if","in","int","interface","internal","is","namespace","new","null","object","out","override","private","protected","public","readonly","ref","return","sealed","static","string","struct","switch","this","throw","true","try","using","var","virtual","void","while"],javascript:["async","await","break","case","catch","class","const","continue","default","delete","do","else","export","extends","false","finally","for","function","if","import","in","instanceof","let","new","null","of","return","static","super","switch","this","throw","true","try","typeof","undefined","var","void","while","yield"],typescript:[],python:["and","as","assert","async","await","break","class","continue","def","del","elif","else","except","False","finally","for","from","global","if","import","in","is","lambda","None","nonlocal","not","or","pass","raise","return","True","try","while","with","yield"],plain:[]};zi.typescript=[...zi.javascript,"enum","interface","type","implements","private","public","readonly","keyof","as","declare","namespace"];const Xi=Object.keys(zi),ek={go:"//",rust:"//",csharp:"//",javascript:"//",typescript:"//",python:"#",plain:null};function ld(t,e){const n=new Set(zi[e]),s=ek[e],i=[],o=(a,l)=>{const c=i[i.length-1];c&&c.kind===l?c.text+=a:i.push({text:a,kind:l})};let r=0;for(;r<t.length;){const a=t[r];if(e!=="plain"&&s&&t.startsWith(s,r)){o(t.slice(r),"comment");break}if(e!=="plain"&&(a==='"'||a==="'"||a==="`")){let h=r+1;for(;h<t.length&&t[h]!==a;)h+=t[h]==="\\"?2:1;o(t.slice(r,h+1),"string"),r=h+1;continue}const l=/^[A-Za-z_][A-Za-z0-9_]*/.exec(t.slice(r));if(l){o(l[0],n.has(l[0])?"keyword":"text"),r+=l[0].length;continue}const c=/^\d[\d_.]*/.exec(t.slice(r));if(c&&e!=="plain"){o(c[0],"number"),r+=c[0].length;continue}o(a,"text"),r++}return i}const cd='"Segoe Print", "Bradley Hand", "Comic Sans MS", "Chalkboard SE", cursive',ws={whiteboard:{background:"#f7f7f2",frame:"#b8bcc4",ink:"#1f2a44",colors:{ink:"#1f2a44",red:"#d03b3b",blue:"#2f6fd0",green:"#2e9a52",orange:"#e07b1a"},font:cd,stroke:.09,opacity:1},chalkboard:{background:"#2f4a3a",frame:"#7a5a3a",ink:"#f1f1e8",colors:{ink:"#f1f1e8",red:"#f2a3a3",blue:"#a8c8f0",green:"#b7e4a8",orange:"#f5c98a",yellow:"#f6ef9a"},font:cd,stroke:.1,opacity:.9}},Aa=["circle","box","underline","arrow"],de={kind:"board",create:"whiteboard({ x, y, width, height, theme?: whiteboard | chalkboard, fontSize?, items: [{ id, text, at: [x, y], size?, color?, hidden? } | { id, mark: circle | box | underline | arrow, around? | from?, to?, color?, hidden? }] })",anchors:{box:"the whole board","text:ID":"a text item: write along it from left to right, point at it","term:ID:TEXT":"the first TEXT in text ID (term:ID#K:TEXT for the Kth): a term, which can come loose as a piece","mark:ID":"a mark (circle, box, underline or arrow)"},edits:{write:"text anchors given `hidden`; { at, duration? }: write them in by hand. Or a term; { at, text, duration? }: write new text in its place (move or erase the term first)",draw:"mark anchors given `hidden`; { at, duration? }: draw them in",erase:"text, term or mark anchors; { at, duration? }: wipe them off",strike:"text or term anchors; { at, duration? }: cross them out",move:"a term; { at, to: an anchor name or { x, y }, duration? }: move the term there",fling:"a term; { at, velocity?, spin?, gravity?, duration? }: throw or knock the term off on a spinning arc"}},hd=90,ud=300,nk=.3;function sk(t){const e=typeof t.theme=="string"?t.theme:"whiteboard";if(!(e in ws))throw new Error(`whiteboard: ${ot("theme",e,Object.keys(ws))}`);const n=typeof t.theme=="object"?{...ws.whiteboard,...t.theme}:ws[e],s=t.fontSize??28,i=t.charWidth??.55,o=b=>b===void 0?n.ink:n.colors[b]??b,r=b=>Mt(t.x+b.left,t.y+b.top,b.width,b.height),a=ps(),l=ms(a),c={},h=new Map,u=[],d=[],f=(b,A,M,E)=>{const x=h.get(b);if(!x||x.kind!=="text")throw Oe("whiteboard",E,de,`there is no text "${b}" (texts: ${p().join(", ")||"none"})`);let S=-1;for(let v=0;v<M;v++)if(S=x.item.text.indexOf(A,S+1),S<0)throw Oe("whiteboard",E,de,`text "${b}" has no ${M>1?`${M}th `:""}"${A}"`);const I=x.size*i;return{column:S,box:Mt(x.box.left+S*I,x.box.top,A.length*I,x.box.height)}},p=()=>[...h.values()].filter(b=>b.kind==="text").map(b=>b.item.id),g=b=>{const{kind:A,rest:M}=Ve(b),E=x=>Oe("whiteboard",b,de,x);if(A==="box"){if(M)throw E("box takes no arguments");return{kind:A}}if(A==="text"||A==="mark"){if(!M)throw E(`write it ${A}:ID`);return{kind:A,id:M}}if(A==="term"){const x=/^([^:#]+)(?:#(\d+))?:(.+)$/.exec(M);if(!x)throw E("write it term:ID:TEXT, or term:ID#K:TEXT for the Kth");return{kind:A,id:x[1],occurrence:x[2]?Number(x[2]):1,text:x[3]}}throw E()},m=b=>{const A=g(b);if(A.kind==="box")return Mt(0,0,t.width,t.height);if(A.kind==="term")return f(A.id,A.text,A.occurrence,b).box;const M=h.get(A.id);if(!M||M.kind!==A.kind){const E=[...h.values()].filter(x=>x.kind===A.kind).map(x=>x.item.id);throw Oe("whiteboard",b,de,`there is no ${A.kind} "${A.id}" (${A.kind}s: ${E.join(", ")||"none"})`)}return M.box};for(const b of t.items??[]){if(!b||typeof b.id!="string"||!b.id||/[:#]/.test(b.id))throw new Error(`whiteboard: every item needs an \`id\` without ":" or "#" (got ${JSON.stringify(b?.id)})`);if(h.has(b.id))throw new Error(`whiteboard: two items are called "${b.id}"`);if("text"in b){if(!Array.isArray(b.at)||b.at.length!==2||!b.at.every(S=>typeof S=="number"))throw new Error(`whiteboard: text "${b.id}" needs \`at\`, [x, y] from the board's top-left`);const E=b.size??s,x=Mt(b.at[0],b.at[1],Math.max(1,b.text.length)*E*i,E*1.3);h.set(b.id,{kind:"text",item:b,size:E,color:o(b.color),box:x}),c[`text.${b.id}.write`]=b.hidden?0:1,c[`text.${b.id}.erase`]=0;continue}if(!Aa.includes(b.mark))throw new Error(`whiteboard: mark "${b.id}": ${ot("mark",b.mark,Aa)}`);const A=b.mark==="arrow"?["from","to"]:["around"];for(const E of A)if(typeof b[E]!="string")throw new Error(`whiteboard: ${b.mark} "${b.id}" needs \`${E}\`, a place on the board (an item before it)`);const M=ik(b,m,s);h.set(b.id,{kind:"mark",item:b,color:o(b.color),points:M,box:rk(M)}),c[`mark.${b.id}.draw`]=b.hidden?0:1,c[`mark.${b.id}.erase`]=0}const y=b=>u.filter(A=>A.item===b),T={type:"custom",x:t.x,y:t.y,width:t.width,height:t.height,props:c,about:{kind:"whiteboard",summary:`A board with ${h.size} items. Its texts, terms and marks are places in the scene (anchor()); its edits record tracks (edit(), tracks()).`,get props(){return lk(Object.keys(c))},actions:de.edits},draw(b,A){const M=A.props??{},E=x=>Number(M[x]??c[x]??0);b.save(),b.fillStyle=n.background,ak(b,0,0,t.width,t.height,10),b.fill(),b.lineWidth=Math.max(4,t.width*.012),b.strokeStyle=n.frame,b.stroke(),b.textAlign="center",b.textBaseline="middle",b.lineCap="round",b.lineJoin="round",b.globalAlpha=n.opacity;for(const x of h.values()){if(b.save(),xa(b,x.box,E(`${x.kind}.${x.item.id}.erase`)),x.kind==="text"){const S=y(x.item.id),I=E(`text.${x.item.id}.write`)*x.item.text.length;b.font=`${x.size}px ${n.font}`,b.fillStyle=x.color;for(let v=0;v<Math.ceil(I);v++)x.item.text[v]===" "||S.some($=>v>=$.column&&v<$.column+$.text.length)||(b.globalAlpha=n.opacity*Math.min(1,I-v),b.fillText(x.item.text[v],x.box.left+(v+.5)*x.size*i,x.box.y))}else fd(b,x.points,E(`mark.${x.item.id}.draw`),x.color,s*n.stroke,x.item.mark==="arrow");b.restore()}for(const x of d){const S=E(`strike.${x.id}.draw`);if(S<=0)continue;const{box:I}=x,v=I.height*.15;fd(b,[{x:I.left-3,y:I.y+v},{x:I.right+3,y:I.y-v}],S,n.colors.red??n.ink,s*n.stroke*.8,!1)}for(const x of u){const S=h.get(x.item),I=S.size*i;b.font=`${S.size}px ${n.font}`,b.fillStyle=S.color;const v=x.written;if(v){const C=E(`piece.${x.id}.write`)*v.length,F=x.home.x-t.x-v.length*I/2;for(let R=0;R<Math.ceil(C);R++)v[R]!==" "&&(b.globalAlpha=n.opacity*Math.min(1,C-R),b.fillText(v[R],F+(R+.5)*I,x.home.y-t.y))}const $=E(`piece.${x.id}.opacity`)*Math.min(1,E(`text.${x.item}.write`)*S.item.text.length-x.column);if($<=0)continue;b.save();const _={x:x.home.x-t.x,y:x.home.y-t.y},P={x:E(`piece.${x.id}.x`),y:E(`piece.${x.id}.y`)};xa(b,Mt(_.x+P.x-x.home.width/2,_.y+P.y-x.home.height/2,x.home.width,x.home.height),E(`piece.${x.id}.erase`)),Math.hypot(P.x,P.y)<1&&xa(b,S.box,E(`text.${x.item}.erase`)),b.globalAlpha=n.opacity*Math.min(1,$),b.translate(_.x+P.x,_.y+P.y),b.rotate(E(`piece.${x.id}.rotate`)*Math.PI/180);for(let C=0;C<x.text.length;C++)x.text[C]!==" "&&b.fillText(x.text[C],(C+.5-x.text.length/2)*I,0);b.restore()}b.restore()}},k={kind:"board",about:de,target:T,box:Mt(t.x,t.y,t.width,t.height),anchor(b){return r(m(b))},piece(b){const A=g(b);if(A.kind!=="term")throw new Error(`whiteboard.piece: a piece is a term, term:ID:TEXT, not "${b}"`);const{column:M,box:E}=f(A.id,A.text,A.occurrence,b),x=u.find(I=>I.item===A.id&&I.column===M&&I.text===A.text);if(x)return x;if(u.some(I=>I.item===A.id&&M<I.column+I.text.length&&I.column<M+A.text.length))throw new Error(`whiteboard: "${A.text}" in "${A.id}" overlaps another piece`);const S={id:u.length+1,item:A.id,column:M,text:A.text,home:r(E)};u.push(S);for(const I of["x","y","rotate","erase","write"])c[`piece.${S.id}.${I}`]=0;return c[`piece.${S.id}.opacity`]=1,S},edit(b,A,M){const E=Array.isArray(A)?A:[A];if(E.length===0)throw new Error(`whiteboard.edit: ${b} takes at least one anchor`);const x=E.map(v=>({name:v,anchor:g(v)}));for(const{name:v}of x)m(v);const S=(v,$=!1)=>{const _=x.find(P=>!v.includes(P.anchor.kind));if(_)throw new Error(`whiteboard.edit: ${b} takes ${v.join(" or ")} anchors, not "${_.name}"`);if($&&x.length>1)throw new Error(`whiteboard.edit: ${b} takes one ${v.join(" or ")} anchor`)},I=()=>k.piece(x[0].name);if(b==="write"){if(x.some(v=>v.anchor.kind==="term")){if(S(["term"],!0),typeof M.text!="string")throw new Error("whiteboard.edit: write into a term needs `text` (the new text)");const v=I();return v.written=M.text,a.tween(`piece.${v.id}.write`,0,1,{duration:Math.max(ud,M.text.length*hd),...M}),k}S(["text"]);for(const{anchor:v}of x){const $=v.id,_=h.get($).item.text;a.tween(`text.${$}.write`,0,1,{duration:Math.max(ud,_.length*hd),...M})}return k}if(b==="draw"){S(["mark"]);for(const{anchor:v}of x)a.tween(`mark.${v.id}.draw`,0,1,{duration:500,...M});return k}if(b==="erase"){S(["text","term","mark"]);for(const v of x){const $=v.anchor.kind==="term"?`piece.${k.piece(v.name).id}.erase`:`${v.anchor.kind}.${v.anchor.id}.erase`;a.tween($,0,1,{duration:400,...M})}return k}if(b==="strike"){S(["text","term"]);for(const v of x){const $={id:d.length+1,box:m(v.name)};d.push($),c[`strike.${$.id}.draw`]=0,a.tween(`strike.${$.id}.draw`,0,1,{duration:250,...M})}return k}if(b==="move"){S(["term"],!0);const v=typeof M.to=="string"?k.anchor(M.to):M.to;if(!v||typeof v.x!="number"||typeof v.y!="number")throw new Error("whiteboard.edit: move needs `to`, an anchor name or { x, y }");return k.move(I(),{...M,to:v})}if(b==="fling")return S(["term"],!0),k.fling(I(),M);throw ys("whiteboard",b,de)},follow(b,A){return l.follow(b,A),k},fling(b,A){return l.fling(b,A),k},move(b,A){return l.move(b,A),k},ride(b){return b},tracks:a.tracks};return k}function ik(t,e,n){const s=Ne(zt(t.id)),i=p=>(s.next()*2-1)*p,o=n*nk;if(t.mark==="arrow"){const p=e(t.from),g=e(t.to),m=dd(p,g,o*.6),y=dd(g,p,o*.6),T=Math.hypot(y.x-m.x,y.y-m.y)*(.06+i(.04)),k=ok(m,y),b={x:(m.x+y.x)/2+k.x*T,y:(m.y+y.y)/2+k.y*T},A=[];for(let M=0;M<=24;M++){const E=M/24;A.push({x:(1-E)**2*m.x+2*(1-E)*E*b.x+E*E*y.x,y:(1-E)**2*m.y+2*(1-E)*E*b.y+E*E*y.y})}return A}const r=e(t.around);if(t.mark==="underline"){const p=r.bottom+o*.4;return[{x:r.left-o*.3,y:p+i(2)},{x:r.x,y:p+2+i(2)},{x:r.right+o*.5,y:p-1+i(3)}]}if(t.mark==="box"){const p=r.left-o,g=r.right+o,m=r.top-o*.6,y=r.bottom+o*.6,T=(b,A)=>({x:b+i(o*.2),y:A+i(o*.2)}),k=T(p,m);return[k,T(g,m),T(g,y),T(p,y),k,{x:k.x+o*.8,y:k.y+i(2)}]}const a=r.width/2+o,l=r.height/2+o*.6,c=-2.2+i(.3),h=s.next()*Math.PI*2,u=1.12,d=64,f=[];for(let p=0;p<=d*u;p++){const g=p/d,m=c+g*Math.PI*2,y=1+.035*Math.sin(g*Math.PI*4+h)+.06*g;f.push({x:r.x+Math.cos(m)*a*y,y:r.y+Math.sin(m)*l*y})}return f}function dd(t,e,n){const s=e.x-t.x,i=e.y-t.y;if(s===0&&i===0)return{x:t.x,y:t.y};const o=Math.min(s===0?1/0:(t.width/2+n)/Math.abs(s),i===0?1/0:(t.height/2+n)/Math.abs(i));return{x:t.x+s*o,y:t.y+i*o}}function ok(t,e){const n=Math.hypot(e.x-t.x,e.y-t.y)||1;return{x:-(e.y-t.y)/n,y:(e.x-t.x)/n}}function rk(t){const e=t.map(o=>o.x),n=t.map(o=>o.y),s=Math.min(...e),i=Math.min(...n);return Mt(s,i,Math.max(...e)-s,Math.max(...n)-i)}function fd(t,e,n,s,i,o){if(n<=0||e.length<2)return;const r=[0];for(let p=1;p<e.length;p++)r.push(r[p-1]+Math.hypot(e[p].x-e[p-1].x,e[p].y-e[p-1].y));const l=r[r.length-1]*Math.min(1,n/(o?.85:1));t.strokeStyle=s,t.lineWidth=i,t.beginPath(),t.moveTo(e[0].x,e[0].y);for(let p=1;p<e.length;p++){if(r[p]<=l){t.lineTo(e[p].x,e[p].y);continue}const g=(l-r[p-1])/(r[p]-r[p-1]||1);t.lineTo(e[p-1].x+(e[p].x-e[p-1].x)*g,e[p-1].y+(e[p].y-e[p-1].y)*g);break}if(t.stroke(),!o||n<=.85)return;const c=(n-.85)/.15,h=e[e.length-1],u=e[e.length-3]??e[0],d=Math.atan2(h.y-u.y,h.x-u.x),f=i*4.5*c;t.beginPath();for(const p of[-1,1])t.moveTo(h.x,h.y),t.lineTo(h.x-Math.cos(d+p*.45)*f,h.y-Math.sin(d+p*.45)*f);t.stroke()}function xa(t,e,n){if(n<=0)return;const s=8;t.beginPath(),t.rect(e.left-s+n*(e.width+s*2),e.top-s*4,(1-n)*(e.width+s*2),e.height+s*8),t.clip()}function ak(t,e,n,s,i,o){t.beginPath(),t.moveTo(e+o,n),t.arcTo(e+s,n,e+s,n+i,o),t.arcTo(e+s,n+i,e,n+i,o),t.arcTo(e,n+i,e,n,o),t.arcTo(e,n,e+s,n,o),t.closePath()}function lk(t){const e=[[/^text\..+\.write$/,{description:"How much of the text is written",unit:"0..1",min:0,max:1}],[/^(text|mark)\..+\.erase$/,{description:"How far it has been wiped off, left to right",unit:"0..1",min:0,max:1}],[/^mark\..+\.draw$/,{description:"How much of the mark is drawn",unit:"0..1",min:0,max:1}],[/^strike\.\d+\.draw$/,{description:"How far the strike-through has drawn",unit:"0..1",min:0,max:1}],[/^piece\.\d+\.(x|y)$/,{description:"The term moved from its home",unit:"px"}],[/^piece\.\d+\.rotate$/,{description:"The term turned",unit:"degrees"}],[/^piece\.\d+\.opacity$/,{description:"How opaque the term is",unit:"0..1",min:0,max:1}],[/^piece\.\d+\.erase$/,{description:"How far the term has been wiped off",unit:"0..1",min:0,max:1}],[/^piece\.\d+\.write$/,{description:"How much of the text written into its place is written",unit:"0..1",min:0,max:1}]],n={};for(const s of t){const i=e.find(([o])=>o.test(s));i&&(n[s]=i[1])}return n}const $a=["bar","line"],ks={light:{background:"#ffffff",text:"#3b4252",grid:"#d8dee9",color:"#4c7bd9",highlight:"#e8833a",font:'system-ui, -apple-system, "Segoe UI", sans-serif'},dark:{background:"#1e2230",text:"#cdd6f4",grid:"#3a4055",color:"#89b4fa",highlight:"#fab387",font:'system-ui, -apple-system, "Segoe UI", sans-serif'}},Je={kind:"chart",create:"chart({ x, y, width, height, kind: bar | line, data: [{ id, label?, value, hidden? }], max?, title?, theme?: light | dark, decimals?, prefix?, suffix?, values? })",anchors:{box:"the whole chart","bar:ID":"a bar (bar charts), as it stands at the time: stand on its top (it carries a figure as it grows), point at it","point:ID":"a point on the line (line charts), as it stands at the time","label:ID":"its label under the axis","value:ID":"its value label, above it"},edits:{set:"bar or point anchors; { at, value, duration? }: animate to a new value; its value label counts along",show:"bar or point anchors given `hidden`; { at, duration?, on? }: grow a bar in from the axis, or draw the line out to a point (on: false takes it back)",highlight:"bar or point anchors; { at, duration?, on? }: colour it out (on: false clears)"}},ck=600,hk=500,uk=200;function dk(t){if(!$a.includes(t.kind))throw new Error(`chart: ${ot("kind",t.kind,$a)}`);const e=typeof t.theme=="string"?t.theme:"light";if(!(e in ks))throw new Error(`chart: ${ot("theme",e,Object.keys(ks))}`);const n=typeof t.theme=="object"?{...ks.light,...t.theme}:ks[e];if(!Array.isArray(t.data)||t.data.length===0)throw new Error("chart: `data` needs at least one { id, value }");const s=new Set;for(const v of t.data){if(typeof v?.id!="string"||!v.id||v.id.includes(":"))throw new Error(`chart: every datum needs an \`id\` without ":" (got ${JSON.stringify(v?.id)})`);if(s.has(v.id))throw new Error(`chart: two data are called "${v.id}"`);if(typeof v.value!="number"||!Number.isFinite(v.value))throw new Error(`chart: "${v.id}" needs a \`value\`, a number`);s.add(v.id)}const i=t.kind,o=i==="bar"?"bar":"point",r=t.max??gd(Math.max(...t.data.map(v=>v.value))*1.1);if(!(r>0))throw new Error(`chart: \`max\` must be above 0 (got ${r})`);const a=Math.max(10,Math.min(16,t.height/20)),l={left:a*3.6,right:t.width-a,top:t.title?a*3:a*1.6,bottom:t.height-a*2.4},c=l.bottom-l.top,h=(l.right-l.left)/t.data.length,u=h*.6,d=Math.max(4,a*.35),f=c/r,p=new Map(t.data.map((v,$)=>[v.id,$])),g=v=>l.left+h*(p.get(v)+.5),m=ps(),y=ms(m),T={};for(const v of t.data)T[`${o}.${v.id}.value`]=v.value,T[`${o}.${v.id}.show`]=v.hidden?0:1,T[`${o}.${v.id}.highlight`]=0;const k=(v,$)=>m.keys(v)?.length?qi(m.keys(v),$):T[v],b=(v,$)=>k(`${o}.${v}.value`,$)*(i==="bar"?k(`${o}.${v}.show`,$):1)*f,A=v=>{const{kind:$,rest:_}=Ve(v),P=C=>Oe("chart",v,Je,C);if($==="box"){if(_)throw P("box takes no arguments");return{kind:"box"}}if($==="bar"||$==="point"||$==="label"||$==="value"){if(!_)throw P(`write it ${$}:ID`);if(!p.has(_))throw P(`there is no "${_}" (data: ${[...p.keys()].join(", ")})`);if(($==="bar"||$==="point")&&$!==o)throw P(`a ${i} chart has ${o}s, not ${$}s: ${o}:${_}`);return{kind:$,id:_}}throw P()},M=(v,$)=>{if(v.kind==="box")return Mt(0,0,t.width,t.height);const _=g(v.id),P=l.bottom-b(v.id,$);if(v.kind==="bar")return Mt(_-u/2,P,u,l.bottom-P);if(v.kind==="point")return Mt(_-d,P-d,d*2,d*2);if(v.kind==="label")return Mt(_-h/2,l.bottom+a*.4,h,a*1.4);const C=P-(i==="line"?d:0)-a*.3;return Mt(_-h/2,C-a*1.3,h,a*1.3)},E=v=>Mt(t.x+v.left,t.y+v.top,v.width,v.height),x=v=>`${t.prefix??""}${v.toFixed(t.decimals??0)}${t.suffix??""}`,S={type:"custom",x:t.x,y:t.y,width:t.width,height:t.height,props:T,about:{kind:`${i} chart`,summary:`A ${i} chart of ${t.data.length} values (${t.data.map(v=>v.id).join(", ")}), scaled to ${r}. Its ${o}s and labels are places in the scene (anchor()); its edits record tracks (edit(), tracks()).`,props:Object.fromEntries(Object.keys(T).map(v=>[v,mk(v)])),actions:Je.edits},draw(v,$){const _=$.props??{},P=R=>Number(_[R]??T[R]??0);v.save(),v.fillStyle=n.background,gk(v,0,0,t.width,t.height,8),v.fill(),v.font=`${a}px ${n.font}`,v.textBaseline="middle",t.title&&(v.fillStyle=n.text,v.textAlign="left",v.font=`600 ${a*1.2}px ${n.font}`,v.fillText(t.title,l.left,a*1.5),v.font=`${a}px ${n.font}`),v.lineWidth=1,v.textAlign="right";for(let R=0;R<=4;R++){const B=l.bottom-c*R/4;v.strokeStyle=n.grid,v.beginPath(),v.moveTo(l.left,B),v.lineTo(l.right,B),v.stroke(),v.fillStyle=n.text,v.globalAlpha=.7,v.fillText(fk(r*R/4),l.left-a*.5,B),v.globalAlpha=1}const C=R=>P(`${o}.${R}.value`)*(i==="bar"?P(`${o}.${R}.show`):1)*f,F=R=>pd(n.color,n.highlight,P(`${o}.${R}.highlight`));i==="line"&&(v.lineWidth=Math.max(2,a*.2),v.lineJoin="round",v.lineCap="round",v.strokeStyle=n.color,v.beginPath(),t.data.forEach((R,B)=>{const j={x:g(R.id),y:l.bottom-C(R.id)},H=P(`point.${R.id}.show`);if(B===0){H>0&&v.moveTo(j.x,j.y);return}const N=t.data[B-1];if(P(`point.${N.id}.show`)<1||H<=0)return;const D={x:g(N.id),y:l.bottom-C(N.id)};v.lineTo(D.x+(j.x-D.x)*H,D.y+(j.y-D.y)*H)}),v.stroke()),v.textAlign="center";for(const R of t.data){const B=g(R.id),j=C(R.id),H=P(`${o}.${R.id}.show`);if(v.fillStyle=F(R.id),i==="bar"?j>.5&&(pk(v,B-u/2,l.bottom-j,u,j,Math.min(6,u/4)),v.fill()):H>0&&(v.beginPath(),v.arc(B,l.bottom-j,d*Math.min(1,H*1.5)*(1+.3*P(`point.${R.id}.highlight`)),0,Math.PI*2),v.fill()),v.fillStyle=n.text,v.fillText(R.label??R.id,B,l.bottom+a*1.1),t.values!==!1&&H>0){v.globalAlpha=Math.min(1,H*2),v.font=`600 ${a}px ${n.font}`,v.fillStyle=pd(n.text,n.highlight,P(`${o}.${R.id}.highlight`));const N=l.bottom-j-(i==="line"?d:0)-a*.95;v.fillText(x(P(`${o}.${R.id}.value`)),B,N),v.font=`${a}px ${n.font}`,v.globalAlpha=1}}v.strokeStyle=n.text,v.lineWidth=1.5,v.beginPath(),v.moveTo(l.left,l.bottom),v.lineTo(l.right,l.bottom),v.stroke(),v.restore()}},I={kind:"chart",chartKind:i,about:Je,target:S,max:r,box:Mt(t.x,t.y,t.width,t.height),anchor(v,$=1/0){return E(M(A(v),$))},piece(v){throw new Error(`chart: a chart has no pieces to come loose ("${v}"); change it with edit('set' | 'show' | 'highlight', …)`)},edit(v,$,_){const P=Array.isArray($)?$:[$];if(P.length===0)throw new Error(`chart.edit: ${v} takes at least one anchor`);if(!(v in Je.edits))throw ys("chart",v,Je);const C=P.map(F=>{const R=A(F);if(R.kind!==o)throw new Error(`chart.edit: ${v} takes ${o} anchors (${o}:ID), not "${F}"`);return R.id});for(const F of C){const R=B=>`${o}.${F}.${B}`;if(v==="set"){if(typeof _.value!="number"||!Number.isFinite(_.value))throw new Error("chart.edit: set needs `value`, a number");m.tween(R("value"),k(R("value"),_.at),_.value,_,ck)}else v==="show"?m.tween(R("show"),k(R("show"),_.at),_.on===!1?0:1,_,hk):m.tween(R("highlight"),k(R("highlight"),_.at),_.on===!1?0:1,_,uk)}return I},follow(v,$){return y.follow(v,$),I},fling(v,$){return y.fling(v,$),I},move(v,$){return y.move(v,$),I},ride(v,$,_){if(i!=="bar")return v;const P=t.data.map(C=>{const F=b(C.id,0),R=[...Yi(m.keys(`bar.${C.id}.value`)),...Yi(m.keys(`bar.${C.id}.show`))];return{top:t.y+l.bottom-F,offset:B=>F-b(C.id,B),windows:R}});return Ta(v,$,{ground:_.ground,every:_.every??Ue,floors:P})},tracks:m.tracks};return I}function gd(t){if(!(t>0))return 1;const e=10**Math.floor(Math.log10(t));for(const n of[1,2,2.5,5,10])if(n*e>=t-1e-9)return n*e;return 10*e}function fk(t){return Number.isInteger(t)?String(t):String(Number(t.toFixed(2)))}function pd(t,e,n){if(n<=0)return t;if(n>=1)return e;const s=r=>[1,3,5].map(a=>parseInt(r.slice(a,a+2),16));if(!/^#[0-9a-f]{6}$/i.test(t)||!/^#[0-9a-f]{6}$/i.test(e))return n<.5?t:e;const[i,o]=[s(t),s(e)];return`#${i.map((r,a)=>Math.round(r+(o[a]-r)*n).toString(16).padStart(2,"0")).join("")}`}function gk(t,e,n,s,i,o){t.beginPath(),t.moveTo(e+o,n),t.arcTo(e+s,n,e+s,n+i,o),t.arcTo(e+s,n+i,e,n+i,o),t.arcTo(e,n+i,e,n,o),t.arcTo(e,n,e+s,n,o),t.closePath()}function pk(t,e,n,s,i,o){const r=Math.min(o,i);t.beginPath(),t.moveTo(e,n+i),t.lineTo(e,n+r),t.arcTo(e,n,e+r,n,r),t.lineTo(e+s-r,n),t.arcTo(e+s,n,e+s,n+r,r),t.lineTo(e+s,n+i),t.closePath()}function mk(t){return t.endsWith(".value")?{description:"Its value (the bar’s height or the point’s, and its value label)",unit:"value"}:t.endsWith(".show")?{description:"How much of it is shown: a bar grown in from the axis, the line drawn out to the point",unit:"0..1",min:0,max:1}:{description:"How much it is coloured out",unit:"0..1",min:0,max:1}}const Pa={boy:{label:"Boy",group:"family",scale:.66,options:{build:"child",hair:"short",ears:!0,outfit:{shirt:"#4f8fd6",trousers:"#2f4d6b",bottom:"shorts"}}},girl:{label:"Girl",group:"family",scale:.66,options:{build:"child",hair:{style:"bob",color:ae.chestnut},ears:!0,outfit:{shirt:"#e86a92",trousers:"#4a5b8c",bottom:"skirt"}}},youngMan:{label:"Young man",group:"family",scale:1,options:{build:"tall",hair:"spiky",ears:!0,outfit:{shirt:"#3c9a6e",trousers:"#2d3a4f"}}},youngWoman:{label:"Young woman",group:"family",scale:.96,options:{build:"slim",hair:{style:"highPonytail",color:ae.auburn},ears:!0,outfit:{shirt:"#f0b43c",trousers:"#36507a"}}},man:{label:"Man",group:"family",scale:1,options:{build:"broad",hair:"sidePart",facialHair:"chevron",ears:!0,outfit:{shirt:"#7a8fa6",trousers:"#3b3f46",sleeves:"long",collar:!0,tie:"#2b4f8c"}}},woman:{label:"Woman",group:"family",scale:.95,options:{build:"curvy",hair:{style:"shoulderWaves",color:ae.black},ears:!0,outfit:{shirt:"#9b5fc0",trousers:"#2f2f3a",sleeves:"long"}}},grandpa:{label:"Grandpa",group:"family",scale:.96,options:{build:"stocky",hair:{style:"receding",color:ae.gray},facialHair:{style:"shortBoxed",color:ae.white},glasses:"square",ears:!0,outfit:{shirt:"#b98a5a",trousers:"#4b4440",sleeves:"long",collar:!0}}},grandma:{label:"Grandma",group:"family",scale:.9,options:{build:"short",hair:{style:"topBun",color:ae.white},glasses:"round",ears:!0,outfit:{shirt:"#5d9fa8",trousers:"#5a4a5e",sleeves:"long",bottom:"skirt"}}},doctor:{label:"Doctor",group:"work",scale:.97,options:{build:"slim",hair:{style:"lowPonytail",color:ae.black},ears:!0,outfit:{shirt:"#8fb8d8",trousers:"#36507a",over:"labCoat",collar:!0}}},cook:{label:"Cook",group:"work",scale:1,options:{build:"stocky",hair:"crewCut",facialHair:"shortMoustache",ears:!0,outfit:{shirt:"#f4f6f8",trousers:"#3b3f46",sleeves:"long",over:"apron",overColor:"#e2493b"}}},builder:{label:"Builder",group:"work",scale:1,options:{build:"broad",hair:"short",facialHair:"stubble",hat:"hardHat",ears:!0,outfit:{shirt:"#f08a3c",trousers:"#4a5b8c"}}},courier:{label:"Courier",group:"work",scale:.98,options:{build:"standard",hair:"short",hat:{style:"cap",color:"#d64535"},ears:!0,outfit:{shirt:"#c94a3b",trousers:"#2f2f3a",bottom:"shorts"}}},teacher:{label:"Teacher",group:"work",scale:1,options:{build:"tall",hair:"slickBack",glasses:"square",ears:!0,outfit:{shirt:"#f4f6f8",trousers:"#3b3f46",sleeves:"long",collar:!0,tie:"#9a4426"}}},farmer:{label:"Farmer",group:"work",scale:.97,options:{build:"stocky",hair:{style:"shoulderStraight",color:ae.blond},hat:"sunHat",ears:!0,outfit:{shirt:"#d64535",trousers:"#4f6b3a",sleeves:"long"}}}};function yk(t,e=300,n={}){const s=Pa[t];if(!s)throw new Error(`castMember: unknown cast member '${t}'`);return{...s.options,height:Math.round(e*s.scale),...n}}const vs={handshake:{height:.47,spacing:.42,lean:6},highFive:{height:.9,spacing:.4,lean:4},fistBump:{height:.55,spacing:.44,lean:6},handOver:{height:.52,spacing:.46,lean:8}};function bk(t,e,n){return vs[t].spacing*Math.min(e.height,n.height)}const md=.075;function wk(t,e,n,s={}){const i=vs[t];if(!i)throw new Error(`meetHands: unknown meeting '${t}' (one of ${Object.keys(vs).join(", ")})`);const[o,r]=e.x<=n.x?[e,n]:[n,e],a=s.view==="side",l=Math.min(o.character.height,r.character.height),c={x:(o.x+r.x)/2,y:-(s.height??i.height)*l},h=(m,y)=>{const T=y?a?1:.62:a?3:3.38;let k={...ft,...m.pose,turn:T,lean:(m.pose?.lean??0)+i.lean};const b=y?1:-1,A=(M,E,x)=>{k=$0(m.character,k,M,{x:c.x+E-m.x,y:c.y,depth:x})};if(t==="handOver"){const M=md*l;A("arm.left",-b*M*.9,M),A("arm.right",-b*M*.9,-M)}else A("arm.right",0,0);return t==="fistBump"&&(k={...k,"hand.right.index.curl":1,"hand.right.middle.curl":1,"hand.right.ring.curl":1,"hand.right.pinky.curl":1}),k},u=h(o,!0),d=h(r,!1),f=.03*l,p=(m,y)=>{const T=sa(m.character,y),k=t==="handOver"?["hand.left","hand.right"]:["hand.right"],b=t==="handOver"?md*l+f:f;return k.every(A=>Math.abs(T.points[A].y-c.y)<f&&Math.abs(T.points[A].x+m.x-c.x)<b)},g=p(o,u)&&p(r,d);return e.x<=n.x?{a:u,b:d,point:c,reached:g}:{a:d,b:u,point:c,reached:g}}const Ze={full:{anticipation:.12,anticipationTime:.3,hold:0,overshoot:.08,settle:220,settleEase:"ease-in-out",actionEase:"ease-in-out-cubic",overlap:45,eyeLead:120,eyeDart:160,drift:.12,blinks:!0,jumpSquash:1},snappy:{anticipation:.2,anticipationTime:.35,hold:.12,overshoot:.12,settle:320,settleEase:{type:"elastic",mode:"out",amplitude:1,period:.35},actionEase:"ease-out-cubic",overlap:35,eyeLead:100,eyeDart:100,drift:.1,blinks:!0,jumpSquash:1.3},limited:{anticipation:.06,anticipationTime:.25,hold:0,overshoot:0,settle:0,settleEase:"ease-out",actionEase:"ease-in-out",overlap:30,eyeLead:80,eyeDart:120,drift:0,blinks:!0,jumpSquash:.6},none:{anticipation:0,anticipationTime:0,hold:0,overshoot:0,settle:0,settleEase:"linear",actionEase:"linear",overlap:0,eyeLead:0,eyeDart:0,drift:0,blinks:!1,jumpSquash:0}};function Ia(t){if(t===void 0)return Ze.full;if(typeof t=="string")return Ze[t];const{base:e,...n}=t;return{...Ze[e??"full"],...n}}const Oa=160,kk=120,vk=700,_a=60,Mk=90,Gi=3200,xn=1,Qe=1e-6;function Ui(t,e,n={}){const s=Ia(n.style),i=n.seed??1,o={};if(t.length===0)return o;const r=Object.keys(t[0].pose).filter(u=>t.some(d=>Math.abs(d.pose[u]-t[0].pose[u])>Qe));for(const u of r)o[u]=Sk(u,t,e,s,i);const a=e.blink,l=a!==void 0&&r.includes(a);if(s.blinks&&a!==void 0&&!l&&a in t[0].pose){const u=Tk(t,e,s,i,t[0].pose[a]);u.length>0&&(o[a]=u)}const{lift:c,stretch:h}=e;if(s.jumpSquash>0&&c&&h&&r.includes(c)&&!r.includes(h)&&h in t[0].pose){const u=Ek(t,c,t[0].pose[h],s.jumpSquash);u.length>0&&(o[h]=u)}return o}function Sk(t,e,n,s,i){const o=n.eyes.includes(t),r=n.limits[t],a=r!==void 0,l=o?-s.eyeLead:(n.depth[t]??1)*s.overlap,c=f=>{const p=(e[f].time-e[f-1].time)/2;return Math.max(-p,Math.min(p,l))},h=[{time:e[0].time,value:e[0].pose[t]}],u=(f,p,g)=>{const m=h[h.length-1];if(f<=m.time+xn){h[h.length-1]={...m,value:p,...g?{easing:g}:{}};return}h.push({time:f,value:p,...g?{easing:g}:{}})};let d=e[0].pose[t];for(let f=1;f<e.length;f++){const p=e[f],g=e[f-1].pose[t],m=p.pose[t],y=m-g,T=h[h.length-1].time,k=p.act!==!1;if(Math.abs(y)<=Qe){const v=p.time+(k?c(f):0);if(f===e.length-1)Math.abs(d-m)>Qe&&u(Math.max(v,T+Oa),m,"ease-in-out"),d=m;else if(k&&a&&s.drift>0&&n.drift.includes(t)&&v-T>=vk){const $=zt(`${i}:${t}:${f}`)%2===0?1:-1;d=m+$*s.drift*r,u(v,d,"ease-in-out")}continue}if(!k){u(e[f-1].time,d),u(p.time,m,p.easing),d=m;continue}const b=c(f),A=Math.max(e[f-1].time+b,T);let M=p.time+b;o&&s.eyeDart>0&&(M=Math.min(M,A+s.eyeDart));const E=M-A;if(E<=xn){u(p.time,m,p.easing),d=m;continue}u(A,d);const x=Math.sign(y);if(a&&s.anticipation>0&&r>0&&E>=Oa){const v=d-x*Math.min(Math.abs(y)*s.anticipation,r),$=A+E*s.anticipationTime;u($,v,"ease-in-out"),s.hold>0&&u($+E*s.hold,v)}const S=f+1<e.length?e[f+1].time-p.time:1/0,I=Math.min(s.settle,S/2);if(a&&s.overshoot>0&&r>0&&E>=kk&&I>xn){const v=Math.min(Math.abs(y)*s.overshoot,r);u(M,m+x*v,p.easing??s.actionEase),u(M+I,m,s.settleEase)}else u(M,m,p.easing??s.actionEase);d=m}return h}function Tk(t,e,n,s,i){const o=[],r=_a+Mk;for(let f=1;f<t.length;f++){const p=t[f-1].pose,g=t[f].pose;Object.entries(e.headTurns).some(([y,T])=>Math.abs((g[y]??0)-(p[y]??0))>T)&&t[f].act!==!1&&o.push(Math.max(t[0].time,t[f-1].time-n.eyeLead))}const a=t[0].time,l=t[t.length-1].time,c=[...o];let h=a+Gi*.6,u=0;for(;h<l;){c.some(g=>Math.abs(g-h)<Gi/2)||o.push(h);const p=(zt(`${s}:blink:${u++}`)%1e3/1e3-.5)*(Gi*.66);h+=Gi+p}o.sort((f,p)=>f-p);const d=[{time:a,value:i}];for(const f of o){const p=d[d.length-1].time;f+_a<=p+xn||(f>p+xn&&d.push({time:f,value:i}),d.push({time:f+_a,value:1,easing:"ease-in"}),d.push({time:f+r,value:i,easing:"ease-out"}))}return d.length>1?d:[]}function Ek(t,e,n,s){const i=n*(1-.18*s),o=n*(1+.14*s),r=[{time:t[0].time,value:n}],a=(l,c,h)=>{const u=r[r.length-1];l<=u.time+xn||r.push({time:l,value:c,...h?{easing:h}:{}})};for(let l=1;l<t.length;l++){const c=t[l-1].pose[e],h=t[l].pose[e],u=t[l-1].time,d=t[l].time,f=d-u;if(!(f<Oa||t[l].act===!1)){if(c<=Qe&&h>Qe)a(u,n),a(u+f*.2,i,"ease-out"),a(u+f*.45,o,"ease-out"),a(d,n,"ease-in-out");else if(c>Qe&&h<=Qe){const p=l+1<t.length?t[l+1].time-d:400;a(u+f*.5,n),a(d-Math.min(60,f*.15),o,"ease-in"),a(d,i,"ease-out"),a(d+Math.min(260,p/2),n,{type:"back",mode:"out",overshoot:1.4})}}}return r.length>1?r:[]}const yd={depth:{lean:0,bend:0,rise:0,sit:0,spin:0,stretch:0,turn:0,leftHip:0,rightHip:0,headTilt:1,leftShoulder:1,rightShoulder:1,leftKnee:1,rightKnee:1,leftBrow:1,rightBrow:1,browTilt:1,leftEye:1,rightEye:1,leftElbow:2,rightElbow:2,leftAnkle:2,rightAnkle:2,leftFootOut:2,rightFootOut:2,mouth:2,smile:2,mouthWidth:2,leftWrist:3,rightWrist:3},limits:{lean:10,bend:10,headTilt:12,spin:25,turn:.06,sit:.06,stretch:.08,rise:0,leftShoulder:20,rightShoulder:20,leftElbow:18,rightElbow:18,leftWrist:15,rightWrist:15,leftHip:12,rightHip:12,leftKnee:15,rightKnee:15,leftAnkle:10,rightAnkle:10,leftBrow:.25,rightBrow:.25,leftEye:.15,rightEye:.15},eyes:["lookX","lookY"],blink:"blink",headTurns:{turn:.15,headTilt:8,lookX:.5,spin:45},drift:["lean","bend","headTilt","leftShoulder","rightShoulder","leftElbow","rightElbow"],lift:"rise",stretch:"stretch"};function Ak(t){return/^(turn|lean|bend|side|lift|roll|stretch)$/.test(t)?{depth:0,limit:{turn:.06,lean:10,bend:10,side:8,lift:0,roll:25,stretch:.08}[t]}:/^leg\.\w+\.(swing|spread|rotate)$/.test(t)?{depth:0,limit:12}:/^head\./.test(t)?{depth:1,limit:12}:/^arm\.\w+\.(swing|spread)$/.test(t)?{depth:1,limit:20}:/^leg\.\w+\.knee$/.test(t)?{depth:1,limit:15}:/^(brow\.|browTilt$)/.test(t)?{depth:1,limit:t==="browTilt"?void 0:.25}:/^eye\./.test(t)?{depth:1,limit:.15}:/^arm\.\w+\.(elbow|bend)$/.test(t)?{depth:2,limit:18}:/^leg\.\w+\.(ankle|toeOut)$/.test(t)?{depth:2,limit:10}:/^(mouth|smile|mouthWidth)$/.test(t)?{depth:2}:/^hand\./.test(t)?{depth:3}:{depth:1}}function xk(){const t={},e={};for(const n of Object.keys(ft)){const s=Ak(n);t[n]=s.depth,s.limit!==void 0&&(e[n]=s.limit)}return{depth:t,limits:e,eyes:["lookX","lookY"],blink:"blink",headTurns:{turn:.15,"head.turn":15,"head.nod":12,lookX:.5,roll:45},drift:["lean","bend","head.tilt","head.nod","arm.left.spread","arm.right.spread","arm.left.elbow","arm.right.elbow"],lift:"lift",stretch:"stretch"}}const bd=xk();function wd(t,e){return Object.entries(e).map(([n,s])=>({id:`${t}-${n}`,target:t,property:n,keyframes:s}))}function kd(t,e,n={}){const s=Er(e),i=e.map((o,r)=>({time:o.time,pose:{...s[r]},easing:o.easing,act:o.act}));return wd(t,Ui(i,n.rig??yd,n))}function $k(t,e,n={}){const s=n.rest??ft,i=oa(e,s),o=e.map((r,a)=>({time:r.time,pose:{...s,...i[a]},easing:r.easing,act:r.act}));return wd(t,Ui(o,n.rig??bd,n))}const vd=ct.shocked,Pk=ct.scared,_e={take:t=>[{after:140,pose:{stretch:.8,bend:10,lean:t.lean-4,leftShoulder:8,rightShoulder:8,leftEye:.35,rightEye:.35,leftBrow:-.6,rightBrow:-.6,mouth:0},easing:"ease-in-out"},{after:260,pose:{stretch:.78}},{after:360,pose:{rise:.22,stretch:1.35,bend:-14,leftShoulder:150,rightShoulder:150,leftElbow:35,rightElbow:35,leftHip:22,rightHip:22,leftKnee:45,rightKnee:45,...vd,headTilt:0},easing:"ease-out-cubic"},{after:720,pose:{rise:.25,stretch:1.25,bend:-10,leftShoulder:140,rightShoulder:140},easing:"ease-in-out"},{after:900,pose:{rise:0,stretch:.74,bend:12,leftShoulder:70,rightShoulder:70,leftHip:18,rightHip:18,leftKnee:30,rightKnee:30},easing:"ease-in-quad"},{after:1060,pose:{stretch:1.06,bend:-3,leftShoulder:60,rightShoulder:60,leftHip:t.leftHip,rightHip:t.rightHip,leftKnee:t.leftKnee,rightKnee:t.rightKnee},easing:"ease-out"},{after:1260,pose:{stretch:t.stretch,bend:t.bend,...ct.surprised,leftShoulder:70,rightShoulder:70,leftElbow:60,rightElbow:60},easing:"ease-in-out"}],doubleTake:t=>[{after:160,pose:{lookX:1,lookY:0},easing:"ease-out"},{after:520,pose:{lookX:-.6,headTilt:t.headTilt-4,smile:.6,mouth:0},easing:"ease-in-out"},{after:1100,pose:{lookX:-.6}},{after:1180,pose:{bend:t.bend-10,headTilt:t.headTilt+10,rise:.05,stretch:1.18,...vd,lookX:1,lookY:0},easing:"ease-out-cubic"},{after:1360,pose:{rise:0,stretch:.88,bend:t.bend+4,headTilt:t.headTilt+4},easing:"ease-in-quad"},{after:1560,pose:{stretch:t.stretch,bend:t.bend,headTilt:t.headTilt},easing:{type:"elastic",mode:"out",amplitude:1,period:.35}}],windUp:()=>[{after:220,pose:{lean:-18,bend:-16,headTilt:-6,leftShoulder:70,leftElbow:-100,rightShoulder:40,rightElbow:100,leftHip:-45,leftKnee:-80,stretch:.92,...ct.angry,lookX:1},easing:"ease-out"},{after:620,pose:{lean:-20,bend:-18,stretch:.9}},{after:700,pose:{lean:28,bend:14,headTilt:6,leftShoulder:30,rightShoulder:60,leftHip:30,leftKnee:-30,rightHip:-20,stretch:1.12},easing:"ease-out-cubic"}],land:t=>[{after:120,pose:{rise:0,stretch:.7,bend:14,leftShoulder:75,rightShoulder:75,leftHip:20,rightHip:20,leftKnee:35,rightKnee:35},easing:"ease-in-quad"},{after:300,pose:{stretch:1.05,bend:-4,leftShoulder:t.leftShoulder,rightShoulder:t.rightShoulder},easing:"ease-out"},{after:460,pose:{rise:0,stretch:t.stretch,bend:t.bend,leftHip:et.leftHip,rightHip:et.rightHip,leftKnee:0,rightKnee:0},easing:"ease-in-out"}],tremble:t=>{const e=[{after:80,pose:{...Pk,bend:t.bend+8,leftShoulder:40,rightShoulder:40,leftElbow:110,rightElbow:110,stretch:.94},easing:"ease-out"}];for(let n=1;n<=14;n++)e.push({after:80+n*45,pose:{lean:t.lean+(n%2===0?2.5:-2.5),headTilt:t.headTilt+(n%2===0?-2:2)}});return e.push({after:755,pose:{lean:t.lean,headTilt:t.headTilt,bend:t.bend}}),e},deflate:t=>[{after:260,pose:{stretch:1.04,headTilt:t.headTilt+4,leftBrow:.3,rightBrow:.3},easing:"ease-in-out"},{after:900,pose:{...jt.sad,bend:18,stretch:.92,lean:t.lean+5,turn:t.turn,sit:t.sit},easing:"ease-in-out"}]};function Ca(t,e){const n=typeof e.from=="string"?jt[e.from]:e.from??et;return Ha(_e[t](n),{...e,from:n})}function Ha(t,e){const n=e.speed??1;let s=e.from;return[{time:e.at,pose:e.from},...t.map(i=>(s={...s,...i.pose},{time:e.at+i.after*n,pose:s,act:!1,...i.easing?{easing:i.easing}:{}}))]}function Ms(t,e=1){const n=_e[t](et);return n[n.length-1].after*e}function Md(t,e,n={}){if(e.length<2)return;const s=Math.max(1,Math.round(n.lines??3)),i=n.spacing??5,o=n.lineWidth??2,r=n.opacity??.7;t.save(),t.strokeStyle=n.color??"#222",t.lineCap="round";for(let a=0;a<s;a++){const l=(a-(s-1)/2)*i,c=Math.floor(Math.abs(l)/Math.max(i,1)*(e.length/6));for(let h=c+1;h<e.length;h++){const u=e[h-1],d=e[h],f=d.x-u.x,p=d.y-u.y,g=Math.hypot(f,p)||1,m=-p/g,y=f/g,T=1-h/(e.length-1);t.globalAlpha=r*(1-T),t.lineWidth=o*(1-T*.7),t.beginPath(),t.moveTo(u.x+m*l,u.y+y*l),t.lineTo(d.x+m*l,d.y+y*l),t.stroke()}}t.restore()}const Ik={hands:[{name:"left hand",at:t=>t.hands.left},{name:"right hand",at:t=>t.hands.right}],toes:[{name:"left toe",at:t=>t.toes.left},{name:"right toe",at:t=>t.toes.right}],head:[{name:"head",at:t=>t.head.center}],body:[{name:"hip",at:t=>t.hip},{name:"neck",at:t=>t.neck}]};function Ok(t,e,n,s,i={}){const o=n.stateAt;if(!o)return;const r=i.length??120,a=Math.max(2,Math.round(i.samples??8)),l=Math.max(0,n.time-r);if(n.time-l<1)return;const c=[];for(let f=0;f<a;f++){const p=l+(n.time-l)*f/(a-1);c.push(Tr(e,{time:p,state:o(p)},s).joints)}const h=c[c.length-1].height,u=(i.threshold??1.2)*h,d=(i.parts??["hands","toes","head"]).flatMap(f=>Ik[f]);for(const f of d){const p=c.map(f.at);let g=0;for(let T=1;T<p.length;T++)g+=Math.hypot(p[T].x-p[T-1].x,p[T].y-p[T-1].y);const m=g/((n.time-l)/1e3);if(m<=u)continue;const y=Math.min(1,(m-u)/(u*.5));Md(t,p,{...i,opacity:(i.opacity??.7)*y,spacing:i.spacing??h*.02})}}function Sd(t,e,n,s={}){if(n<=0||n>=1)return;const i=s.size??40,o=s.seed??1,r=.45+.55*(1-(1-n)**3);t.save(),t.strokeStyle=s.color??"#555",t.lineWidth=Math.max(1,i*.03),t.globalAlpha=Math.min(1,n/.08)*(1-n);for(let a=0;a<5;a++){const l=zt(`${o}:puff:${a}`)%1e3/1e3,c=a-2,h=e.x+c*i*.3*r,u=e.y-i*(.06+.12*l)*r+Math.abs(c)*i*.03,d=i*(.11+.07*l)*r;t.beginPath(),t.arc(h,u,d,Math.PI*.95,Math.PI*2.05),t.stroke()}t.restore()}function _k(t,e,n,s={}){if(n<=0||n>=1)return;const i=s.size??40,o=5,r=1-(1-n)**2;t.save(),t.strokeStyle=s.color??"#222",t.lineWidth=Math.max(1,i*.035),t.lineJoin="round",t.globalAlpha=n<.7?1:(1-n)/.3;for(let a=0;a<o;a++){const l=-Math.PI/2+(a-(o-1)/2)*Math.PI/(o+1),c=i*(.3+.7*r),h=e.x+Math.cos(l)*c,u=e.y+Math.sin(l)*c;Ck(t,h,u,i*.14,n*Math.PI+a),t.stroke()}t.restore()}function Ck(t,e,n,s,i){t.beginPath();for(let o=0;o<10;o++){const r=o%2===0?s:s*.45,a=i+o*Math.PI/5-Math.PI/2,l=e+Math.cos(a)*r,c=n+Math.sin(a)*r;o===0?t.moveTo(l,c):t.lineTo(l,c)}t.closePath()}const Ce={rest:{mouth:0,mouthWidth:1},a:{mouth:.75,mouthWidth:1.1},e:{mouth:.45,mouthWidth:1.3},i:{mouth:.28,mouthWidth:1.45},o:{mouth:.6,mouthWidth:.7},u:{mouth:.32,mouthWidth:.55},m:{mouth:0,mouthWidth:.9},f:{mouth:.1,mouthWidth:1.05},l:{mouth:.3,mouthWidth:1},c:{mouth:.2,mouthWidth:1}},Ss=1,Vi=.55,Td=.35,Hk=1.6,Ed={a:"a",e:"e",i:"i",y:"i",o:"o",u:"u"},Ad={m:"m",b:"m",p:"m",f:"f",v:"f",w:"u",q:"u",l:"l",n:"l",d:"l",t:"l"},xd={अ:"a",आ:"a",इ:"i",ई:"i",उ:"u",ऊ:"u",ऋ:"i",ए:"e",ऐ:"e",ओ:"o",औ:"o",ऍ:"e",ऑ:"o"},$d={"ा":"a","ि":"i","ी":"i","ु":"u","ू":"u","ृ":"i","े":"e","ै":"e","ो":"o","ौ":"o","ॅ":"e","ॉ":"o"},Rk={प:"m",फ:"m",ब:"m",भ:"m",म:"m",व:"u"},Lk="्",Pd="़",Fk=t=>t>="क"&&t<="ह",Id=new Set([".",",","!","?",";",":","…","।","॥","—","-"]);function Od(t){const e=[],n=Array.from(t.toLowerCase()),s=(i,o)=>{const r=e[e.length-1];r&&r.viseme===i?r.weight+=o*.5:e.push({viseme:i,weight:o})};for(let i=0;i<n.length;i++){const o=n[i],r=n[i+1];if(Id.has(o))s("rest",Hk);else if(/\s/.test(o)){const a=e[e.length-1];a&&a.viseme!=="rest"&&e.push({viseme:"c",weight:Td})}else if((o==="o"||o==="e")&&r===o)s(o==="o"?"u":"i",Ss),i++;else if(o in Ed)s(Ed[o],Ss);else if(o in Ad)s(Ad[o],Vi);else{if(o==="h")continue;if(/[a-z]/.test(o))s("c",Vi);else if(o in xd)s(xd[o],Ss);else if(Fk(o)){const a=r===Pd?o==="फ"?"f":void 0:Rk[o];s(a??"c",Vi);let l=i+1;n[l]===Pd&&l++;const c=n[l];c===Lk?i=l:c&&c in $d?(s($d[c],Ss),i=l):(!c||/\s/.test(c)||Id.has(c)||s("a",Ss*.6),i=l-1)}else(o==="ं"||o==="ँ")&&s("l",Vi*.6)}}for(;e.length>0&&(e[e.length-1].viseme==="rest"||e[e.length-1].weight===Td);)e.pop();return e}function Ra(t,e={}){const n=e.fields?.mouth??"mouth",s=e.fields?.mouthWidth??"mouthWidth",i=e.energy??1,o=Od(t.text),r=[{time:t.start,value:Ce.rest.mouth}],a=[{time:t.start,value:Ce.rest.mouthWidth}],l=o.reduce((h,u)=>h+u.weight,0),c=t.end-t.start;if(l>0&&c>0){let h=t.start;for(const u of o){const d=c*u.weight/l,f=h+Math.min(d*.4,60);if(f>r[r.length-1].time){const p=Ce[u.viseme];r.push({time:f,value:p.mouth*i,easing:"ease-out"}),a.push({time:f,value:1+(p.mouthWidth-1)*Math.min(1.3,i),easing:"ease-out"})}h+=d}}return t.end>r[r.length-1].time&&(r.push({time:t.end,value:Ce.rest.mouth,easing:"ease-in-out"}),a.push({time:t.end,value:Ce.rest.mouthWidth,easing:"ease-in-out"})),{[n]:r,[s]:a}}function Nk(t,e,n={}){const s={};for(const i of[...e].sort((o,r)=>o.start-r.start))for(const[o,r]of Object.entries(Ra(i,n))){const a=s[o]??=[],l=a.length>0?a[a.length-1].time:-1/0;a.push(...r.filter(c=>c.time>l))}return Object.entries(s).map(([i,o])=>({id:`${t}-${i}`,target:t,property:i,keyframes:o}))}function _d(t,e,n,s={}){if(n.length===0)return e;const i=s.fields?.mouth??"mouth",o=s.fields?.mouthWidth??"mouthWidth",r={[i]:Ce.rest.mouth,[o]:Ce.rest.mouthWidth,...s.rest},a=new Nt({id:"before-speech",tracks:e}),l=(u,d)=>a.getStateAtTime(d).values.get(t)?.get(u)??r[u],c=[i,o],h=e.filter(u=>u.target!==t||!c.includes(u.property));for(const u of c){const d=e.find(p=>p.target===t&&p.property===u);let f=d?[...d.keyframes]:[{time:0,value:l(u,0)}];for(const p of n){const g=Ra(p,s)[u];g[0]={...g[0],value:l(u,p.start)},g[g.length-1]={...g[g.length-1],value:l(u,p.end)},f=[...f.filter(m=>m.time<p.start||m.time>p.end),...g],f.sort((m,y)=>m.time-y.time)}h.push({id:d?.id??`${t}-${u}`,target:t,property:u,keyframes:f})}return h}const Ts={look:{summary:"Turns the head and eyes toward a scene x, `viewer`, `ahead` or `back`.",uses:["toward"]},face:{summary:"Turns the whole figure toward a scene x (turning round if needed), `viewer`, `ahead` or `back`.",uses:["toward"]},say:{summary:"Lip-syncs the `say` line with small nods; the beat lasts as long as the line.",needs:["say"]},hold:{summary:"Holds the pose (the acting pass drifts long holds)."},stand:{summary:"Back to its resting stance (a character’s own, else the rest pose), keeping the way it is turned."},go:{summary:"Walks to `to` in its own gait (a character’s, else walk).",needs:["to"]},zip:{summary:"The cartoon exit: winds up, wheels its legs in place, then shoots off to `to`, leaving dust.",needs:["to"]},leap:{summary:"Crouches, springs, arcs and lands squashed at `to`, on the floor `onto` (a scene y).",uses:["to","onto"]},swipe:{summary:"Winds an arm up, then slides along the target with the arm out so the hand crosses it edge to edge.",uses:["target"]},grab:{summary:"Steps to where its arm reaches the target (crouching for low things), takes it and lifts it overhead.",needs:["target"]},throw:{summary:"Winds the arm back and throws forward and up toward `to` (or the target); `release` is when it lets go.",uses:["to","target"]},kick:{summary:"Steps to a leg’s length from the target, draws the leg back and kicks through it.",needs:["target"]},put:{summary:"Steps to where its arm reaches the spot and sets the thing down there.",needs:["target"]},write:{summary:"Reaches a pen to the spot and writes along it left to right (moving along when it is wide).",needs:["target"]},push:{summary:"Sets both hands on the target’s near side and walks it along until its centre is at `to`.",needs:["target","to"]}};function La(t={}){return[...Object.keys(Ht),...Object.keys(jt),...Object.keys(_e),...Object.keys(Ts),...Object.keys(t.gaits??{}),...Object.keys(t.actions??{})]}function Fa(t={}){const e=new Set(La()),n=[];for(const s of[...Object.keys(t.actions??{}),...Object.keys(t.gaits??{})])e.has(s)&&n.push(`Custom action or gait "${s}" has the name of a built-in one; give it its own name.`);for(const s of Object.keys(t.actions??{}))t.gaits&&s in t.gaits&&n.push(`"${s}" is both a custom action and a custom gait.`);return n}function Na(t={}){const e={};for(const n of Object.keys(Ht))e[n]=`Walks to \`to\` in the ${n} gait, feet planted, turning round first if needed.`;for(const n of Object.keys(jt))e[n]=`Moves into the ${n} pose and holds it.`;for(const n of Object.keys(_e))e[n]=`The ${n} gag, built on the current pose.`;for(const[n,s]of Object.entries(Ts))e[n]=s.summary;for(const[n,s]of Object.entries(t.gaits??{}))e[n]=s.summary??`Walks to \`to\` in the ${n} gait (custom).`;for(const[n,s]of Object.entries(t.actions??{}))e[n]=s.summary;return e}const Ji=["do","at","for","to","toward","mood","say","pose","target","onto"],Dk={action:"do",type:"do",verb:"do",time:"at",start:"at",delay:"at",duration:"for",length:"for",ms:"for",x:"to",position:"to",destination:"to",expression:"mood",emotion:"mood",face:"mood",feeling:"mood",text:"say",line:"say",speech:"say",dialogue:"say",joints:"pose",y:"onto",floor:"onto",ground:"onto",object:"target",at_target:"target"},Zi=["viewer","ahead","back"],tn=t=>typeof t=="number"&&Number.isFinite(t);function Es(t,e={}){const n=Fa(e).map(l=>({level:"error",beat:-1,message:l}));if(!Array.isArray(t))return[...n,{level:"error",beat:-1,message:`Beats must be an array of { do: … } objects (got ${typeof t}).`}];const s=La(e),i=l=>l in Ht||l in(e.gaits??{}),o=Object.keys(ct),r=Object.keys(et);let a=-1/0;return t.forEach((l,c)=>{const h=g=>n.push({level:"error",beat:c,message:g}),u=g=>n.push({level:"warning",beat:c,message:g});if(!l||typeof l!="object"||Array.isArray(l)){h(`Each beat must be an object like { do: 'walk', to: 400 } (got ${JSON.stringify(l)}).`);return}const d=l;for(const g of Object.keys(d))Ji.includes(g)||h(ot("beat field",g,Ji,Dk[g.toLowerCase()]));const f=d.do;if(f===void 0){h(`A beat needs \`do\` (what happens). Actions: ${s.join(", ")}`);return}if(typeof f!="string"||!s.includes(f)){h(ot("action",f,s));return}const p=Ts[f]??e.actions?.[f];for(const g of p?.needs??[])d[g]===void 0&&h(`\`${f}\` needs \`${g}\`.`);if(i(f)&&d.to===void 0&&u(`\`${f}\` without \`to\` walks nowhere.`),f==="leap"&&d.to===void 0&&d.onto===void 0&&u("`leap` without `to` or `onto` jumps on the spot."),d.mood!==void 0&&(typeof d.mood!="string"||!o.includes(d.mood))&&h(ot("mood",d.mood,o)),d.pose!==void 0)if(!d.pose||typeof d.pose!="object"||Array.isArray(d.pose))h("`pose` is joints to change, an object like { rightShoulder: 90 } (for a named pose, use it as the action).");else for(const[g,m]of Object.entries(d.pose))r.includes(g)?tn(m)||h(`Pose joint \`${g}\` must be a number (got ${JSON.stringify(m)}).`):h(ot("pose joint",g,r));for(const g of["at","for"]){const m=d[g];m!==void 0&&!(tn(m)&&m>=0)&&h(`\`${g}\` is milliseconds, a number ≥ 0 (got ${JSON.stringify(m)}).`)}tn(d.at)&&(d.at<a&&u(`\`at\` ${d.at} is before an earlier beat's \`at\` (${a}); beats run in order, so it starts when the one before ends.`),a=d.at);for(const g of["to","onto"]){const m=d[g];m!==void 0&&!tn(m)&&h(`\`${g}\` is a scene ${g==="to"?"x":"y"} in px, a number (got ${JSON.stringify(m)}).`)}if(d.toward!==void 0&&!tn(d.toward)&&!Zi.includes(d.toward)&&h(`\`toward\` is a scene x or one of ${Zi.join(", ")}${typeof d.toward=="string"&&Kn(d.toward,Zi)?` (did you mean "${Kn(d.toward,Zi)}"?)`:""} (got ${JSON.stringify(d.toward)}).`),d.say!==void 0&&typeof d.say!="string"&&h(`\`say\` is the line spoken, a string (got ${JSON.stringify(d.say)}).`),d.target!==void 0){const g=d.target;(!g||typeof g!="object"||!tn(g.x)||!tn(g.y))&&h("`target` is a point or box in scene px: { x, y } (a code panel’s line(), token() or spot() fits).")}}),n}function Da(t,e={},n="scriptTracks"){const s=Es(t,e).filter(i=>i.level==="error");if(s.length!==0)throw new Error(`${n}: ${s.length} problem(s) in the beats:
|
|
57
57
|
${s.map(i=>` ${i.beat>=0?`beat ${i.beat}: `:""}${i.message}`).join(`
|
|
58
|
-
`)}`)}em(Zr);function qb(t){const e="steps"in t&&typeof t.steps=="function",n="beats"in t&&typeof t.beats=="function";if(e===n)throw new Error("defineAction: give either `steps: (from, beat) => [...]` or `beats: (beat) => [...]`");if(!t.summary)throw new Error("defineAction: give a `summary`: one line on what the figure does");return t}function Kb(t){for(const e of["swing","knee","arm","elbow","lean"])if(typeof t[e]!="number")throw new Error(`defineGait: \`${e}\` must be a number (degrees)`);if(t.cycle!==void 0&&!(t.cycle>0))throw new Error("defineGait: `cycle` is ms per two steps, above 0");return t}const lu=8;function Pi(t,e={},n=0){if(n>lu)throw new Error(`scriptTracks: custom actions nest more than ${lu} deep (does one build itself?)`);return t.flatMap(s=>{const i=e[s.do];if(!i||!("beats"in i))return[s];const o=i.beats(s).map((r,a)=>a===0?{...r,...s.at!==void 0&&r.at===void 0?{at:s.at}:{},...s.mood&&!r.mood?{mood:s.mood}:{},...s.say&&!r.say?{say:s.say}:{}}:r);return Pi(o,e,n+1)})}function cu(t){return t.length===0?0:Math.max(...t.map(e=>e.after))}const ta={walk:1e3,bouncy:900,doubleBounce:1100,sneak:1600,strut:1100,tired:1500,shove:1300,run:560},Yb=450,zb=2.4,Xb=160,hu=2.5,Ub=200,Gb=340,Vb=1.1,du=[380,900],Jb=.35,xi=300,ea=150,Zb=260,Qb=1.2,na=160,uu=400,cs=300,tw=450,fu=500,sa=350,pu=150,ew=120,ia=180,gu=420,nw=300,mu=300,sw=140,oa=150,yu=450,iw=450,ra=150,bu=350,wu=400,ow=12,rw=600,ku=90,vu=400,aw=200,lw=.09,Mu=350,se=450,aa=1200,cw=700,yn=320,ie=220,hw=65,dw=700,Su=t=>t in Me,uw=t=>t in Dt;function Tu(t){return Math.max(dw,Array.from(t).length*hw)}function la(t,e,n={}){const s={actions:n.actions,gaits:n.gaits};Qr(e,s);const i=n.gait??"walk",o=Pi(e,n.actions).map(x=>x.do==="go"?{...x,do:i}:x);Qr(o,s,"scriptTracks (after expanding custom actions)");const r=x=>Ot[x]??n.gaits?.[x],a=x=>ta[x]??n.gaits?.[x]?.cycle??1e3,l=x=>{const R=n.actions?.[x];return R&&"steps"in R?R:void 0},c=n.from??0,h=n.ground??0,d=n.height??300;let u=c,f=h,g=n.facing??1,p=n.start??et,m=0,b=0;const S=[{time:0,pose:p}],k=[{time:0,value:0}],y=[{time:0,value:0}],M=[{time:0,value:0}],$=[{time:0,value:0}],E=[{time:0,value:"walk"}],A=[{time:0,value:g}],T=[],I=[],v=[],P=(x,R,q,U)=>{p={...p,...R},q&&(p=ge(p,q)),S.push({time:x,pose:p,...U===!1?{act:U}:{}})},H=(x,R,q)=>(P(x+yn/2,{turn:0},q),A.push({time:x+yn/2,value:g},{time:x+yn/2+1,value:R}),g=R,P(x+yn,{turn:1}),x+yn),O=x=>x<u?-1:1,C=(x,R,q)=>O(R)!==g?H(x,O(R),q):x,j=(x,R,q,U="arm")=>{const Y=U==="arm",Z=me({...x,...Y?{rightShoulder:0,rightElbow:0}:{rightHip:0,rightKnee:0}},{height:d,facing:g}),nt=Y?Z.shoulders.right:Z.hip,F=Y?Z.elbows.right:Z.knees.right,z=(Q,tt)=>Math.atan2(g*Q,tt)*180/Math.PI,V=((z(R-(u+nt.x),q-(f+nt.y))-z(F.x-nt.x,F.y-nt.y))%360+360)%360;return V>270?V-360:V},D=(x,R,q,U)=>{const Y=U==="arm",Z=me({...x,...Y?{rightShoulder:90,rightElbow:0,rightWrist:0}:{rightHip:90,rightKnee:0}},{height:d,facing:g}),nt=Y?Z.shoulders.right:Z.hip,F=Y?{x:(Z.hands.right.x+Z.fingertips.right.x)/2,y:(Z.hands.right.y+Z.fingertips.right.y)/2}:Z.feet.right,z=Math.hypot(F.x-nt.x,F.y-nt.y),K=q-(f+nt.y),V=Math.abs(K)<z?Math.sqrt(z*z-K*K):z*.1;return R-nt.x-g*V},W=x=>{const R=me(x,{height:d,facing:g});return{x:u+(R.hands.right.x+R.fingertips.right.x)/2,y:f+(R.hands.right.y+R.fingertips.right.y)/2}},B=(x,R,q)=>{const U={...x,rightWrist:0,rightElbow:0,rightShoulder:j(x,R,q)},Y=me(U,{height:d,facing:g}),Z={x:u+Y.shoulders.right.x,y:f+Y.shoulders.right.y},nt={x:u+Y.elbows.right.x,y:f+Y.elbows.right.y},F=W(U),z=Math.hypot(nt.x-Z.x,nt.y-Z.y),K=Math.hypot(F.x-nt.x,F.y-nt.y),V=Math.min(z+K-.01,Math.max(Math.abs(z-K)+.01,Math.hypot(R-Z.x,q-Z.y))),Q=rt=>rt*180/Math.PI,tt=Q(Math.acos((z*z+V*V-K*K)/(2*z*V))),st=180-Q(Math.acos((z*z+K*K-V*V)/(2*z*K)));let pt={rightShoulder:U.rightShoulder,rightElbow:0},ht=1/0;for(const rt of[1,-1])for(const wt of[1,-1]){const J={rightShoulder:U.rightShoulder+rt*tt,rightElbow:wt*st},kt={...x,rightWrist:0,...J},gt=W(kt),G=Math.hypot(gt.x-R,gt.y-q)-me(kt,{height:d,facing:g}).elbows.right.y*.001;G<ht&&(ht=G,pt=J)}return pt},_=(x,R,q)=>Math.abs(R-u)<2?x:(k.push({time:x,value:u-c},{time:x+q,value:R-c,easing:"ease-in-out"}),u=R,x+q);for(const x of o){const R=Math.max(x.at??b,b===0?0:S[S.length-1].time);let q=R,U,Y;const Z=x.pose??{},nt=l(x.do);if(r(x.do)){const F=x.to??u,z=F===u?g:O(F);let K=R;z!==g?K=H(R,z,x.mood):p.turn<1?(K=R+ie,P(K,{turn:1,...Z},x.mood)):(x.mood||x.pose)&&P(R+ie,Z,x.mood);const Q=Math.abs(F-u)/Xo(r(x.do),d),tt=x.for??Math.max(ie*2,Q*a(x.do)),st=K+tt;E.push({time:K,value:x.do}),$.push({time:K,value:0},{time:K+ie,value:1,easing:"ease-out"}),$.push({time:st-ie,value:1},{time:st,value:0,easing:"ease-in"}),M.push({time:K,value:m},{time:st,value:m+Q}),k.push({time:K,value:u-c},{time:st,value:F-c}),m+=Q,u=F,P(st,{}),q=st}else if(x.do==="zip"){const F=x.to??u,z=F===u?g:O(F);let K=R;z!==g?K=H(R,z,x.mood):p.turn<1&&(K=R+ie,P(K,{turn:1},x.mood));const V=Xr("windUp",{at:K,from:x.mood?ge(p,x.mood):p});S.push(...V),p=V[V.length-1].pose;const Q=K+os("windUp"),tt=Q+Yb,st=tt+Math.max(Xb,Math.abs(F-u)/zb);E.push({time:Q,value:"run"}),$.push({time:Q,value:0},{time:Q+80,value:1,easing:"ease-out"},{time:st,value:1},{time:st+120,value:0}),M.push({time:Q,value:m},{time:tt,value:m+hu,easing:"ease-in"}),m+=hu+(st-tt)/ta.run*1.5,M.push({time:st,value:m}),k.push({time:tt,value:u-c},{time:st,value:F-c,easing:"ease-in"}),v.push({kind:"dust",time:tt,x:u,y:f,length:900}),u=F,P(st,{}),q=st}else if(x.do==="leap"){const F=x.to??u,z=x.onto??f;let K=F===u?R:C(R,F,x.mood);p.turn<1&&(K+=ie,P(K,{turn:1},x.mood));const V={leftShoulder:35,rightShoulder:35,leftElbow:-50,rightElbow:-50};P(K+Ub,{stretch:.75,bend:12,leftHip:22,rightHip:22,...V},x.mood,!1);const Q=K+Gb;P(Q-40,{stretch:.72},void 0,!1),P(Q,{stretch:1.2,bend:-6,leftShoulder:140,rightShoulder:140,leftElbow:20,rightElbow:20,leftHip:4,rightHip:4},void 0,!1);const tt=Math.hypot(F-u,z-f),st=x.for??Math.min(du[1],Math.max(du[0],300+tt*Vb)),pt=Math.min(f,z)-Jb*d,ht=Math.sqrt(f-pt),rt=Math.sqrt(z-pt),wt=Q+st*ht/(ht+rt),J=Q+st;P(wt,{stretch:1,bend:4,leftHip:-55,leftKnee:-80,rightHip:55,rightKnee:80,leftShoulder:110,rightShoulder:110},void 0,!1),P(J,{stretch:.72,bend:12,leftShoulder:75,rightShoulder:75,leftElbow:0,rightElbow:0,leftHip:18,rightHip:18,leftKnee:0,rightKnee:0},void 0,!1),P(J+180,{stretch:1.05,bend:-3},void 0,!1),P(J+340,{stretch:1,bend:0,leftHip:et.leftHip,rightHip:et.rightHip,leftShoulder:et.leftShoulder,rightShoulder:et.rightShoulder,leftElbow:et.leftElbow,rightElbow:et.rightElbow},void 0,!1),k.push({time:Q,value:u-c},{time:J,value:F-c}),y.push({time:Q,value:f-h},{time:wt,value:pt-h,easing:"ease-out-quad"},{time:J,value:z-h,easing:"ease-in-quad"}),u=F,f=z,v.push({kind:"dust",time:J,x:u,y:f,length:500}),q=J+340,U=J}else if(x.do==="point"&&x.target){const F=x.target,z=C(R,F.x,x.mood),K={...p,...x.mood?ct[x.mood]:{},turn:Math.max(p.turn,.6),rightElbow:0,rightWrist:0,...Z},V=me(K,{height:d,facing:g}).head.center,Q=Math.abs(F.x-(u+V.x)),tt=F.y-(f+V.y),st=z+se;P(st,{...K,rightShoulder:j(K,F.x,F.y),lookX:1,lookY:fw(tt/Math.max(1,Math.hypot(Q,tt)))*.8}),q=st+(x.for??aa),U=st,Y=q}else if(x.do==="swipe"){const F=x.target??{x:u+g*d*.5,y:f-d*.6},z=O(F.x),K=C(R,F.x,x.mood),V=z===1?F.left??F.x:F.right??F.x,Q=z===1?F.right??F.x:F.left??F.x,tt={...p,turn:1,lean:-10,bend:-8,rightElbow:40,lookX:1,...Z};P(K+xi,{...tt,rightShoulder:j(tt,u-g*d*.3,f-d*1.1)},x.mood,!1);const st={...p,lean:6,bend:4,rightElbow:0,rightWrist:0},pt={...p,lean:14,bend:12,rightElbow:0,rightWrist:0};_(K,D(st,V,F.y,"arm"),xi+ea),P(K+xi+ea,{lean:-12},void 0,!1);const ht=K+xi+ea+80;P(ht,{...st,rightShoulder:j(st,V,F.y)},void 0,!1);const rt=ht+(x.for??Math.max(Zb,Math.abs(Q-V)/Qb));k.push({time:ht,value:u-c}),u=D(pt,Q,F.y,"arm"),k.push({time:rt,value:u-c}),P(rt,{...pt,rightShoulder:j(pt,Q,F.y)},void 0,!1),P(rt+na,{lean:16,bend:14,rightShoulder:j(p,Q+z*d*.4,F.y+d*.25)},void 0,!1),P(rt+na+uu,{lean:0,bend:0,rightShoulder:et.rightShoulder,rightElbow:et.rightElbow}),q=rt+na+uu,U=ht,Y=rt}else if(x.do==="grab"&&x.target){const F=x.target,z=C(R,F.x,x.mood),K=F.y>f-d*.5,V={...p,turn:1,rightElbow:0,bend:K?35:0,lean:K?12:0,stretch:K?.75:1,lookX:1,lookY:K?.8:0,...Z},tt=_(z,D(V,F.x,F.y,"arm"),cs)+tw;P(tt,{...V,rightShoulder:j(V,F.x,F.y)},x.mood,!1),P(tt+120,{},void 0,!1),P(tt+fu,{bend:0,lean:-3,stretch:1,rightShoulder:165,rightElbow:20,lookY:-.6}),q=tt+fu+150,U=tt}else if(x.do==="throw"){const F=x.target?.x??x.to??u+g*d,z=C(R,F,x.mood),K={...p,turn:1,lean:-12,bend:-10,rightElbow:60,stretch:.95,lookX:1,lookY:-.3,...Z};P(z+sa,{...K,rightShoulder:j(K,u-g*d*.4,f-d*1.05)},x.mood,!1),P(z+sa+pu,{lean:-14},void 0,!1);const V=z+sa+pu+ew,Q={...p,lean:14,bend:12,rightElbow:0,stretch:1.04};S.push({time:V,pose:p={...Q,rightShoulder:j(Q,u+g*d,f-d*1.1)},easing:"ease-in",act:!1}),P(V+ia,{lean:18,bend:14,rightShoulder:55,stretch:1},void 0,!1),P(V+ia+gu,{lean:0,bend:0,rightShoulder:et.rightShoulder,rightElbow:et.rightElbow,lookY:0}),q=V+ia+gu,U=V,Y=V}else if(x.do==="kick"&&x.target){const F=x.target,z=C(R,F.x,x.mood),K={...p,turn:1,lean:-12,bend:-6,rightKnee:0,leftShoulder:100,rightShoulder:70},V=_(z,D(K,F.x,F.y,"leg"),nw),Q={leftShoulder:70,rightShoulder:50,leftElbow:-20,rightElbow:20};P(V+mu,{turn:1,lean:8,bend:6,rightHip:-40,rightKnee:80,lookX:1,lookY:.7,...Q,...Z},x.mood,!1);const tt=V+mu+sw,st=j(K,F.x,F.y,"leg");S.push({time:tt,pose:p={...p,...K,rightHip:st},easing:"ease-in",act:!1}),P(tt+oa,{lean:-15,rightHip:st+20},void 0,!1),P(tt+oa+yu,{lean:0,bend:0,rightHip:et.rightHip,rightKnee:0,leftShoulder:et.leftShoulder,rightShoulder:et.rightShoulder,leftElbow:et.leftElbow,rightElbow:et.rightElbow,lookY:0}),q=tt+oa+yu,U=tt}else if(x.do==="put"&&x.target){const F=x.target,z=C(R,F.x,x.mood),K=F.y>f-d*.5,V={...p,turn:1,rightElbow:0,rightWrist:0,bend:K?35:0,lean:K?12:0,stretch:K?.75:1,lookX:1,lookY:K?.8:0,...Z},tt=_(z,D(V,F.x,F.y,"arm"),cs)+iw;P(tt,{...V,rightShoulder:j(V,F.x,F.y)},x.mood,!1),P(tt+ra,{},void 0,!1),P(tt+ra+bu,{bend:0,lean:0,stretch:1,rightShoulder:et.rightShoulder,rightElbow:et.rightElbow,lookY:0}),q=tt+ra+bu,U=tt}else if(x.do==="write"&&x.target){const F=x.target,z=F.left??F.x,K=F.right??F.x,V=C(R,(z+K)/2,x.mood),Q={...p,turn:1,rightElbow:0,rightWrist:0,...ct.thinking,lookX:1,lookY:0,...Z},tt=gt=>D(Q,gt,F.y,"arm")+g*d*.08,st=gt=>{const X=W({...Q,...B(Q,gt,F.y),rightWrist:0});return Math.hypot(X.x-gt,X.y-F.y)<2},pt=g===1?z:K,ht=_(V,tt((z+K)/2),cs),rt=!st(z)||!st(K),wt=rt?_(ht,tt(z),cs)+wu:ht+wu;P(wt,{...Q,...B(Q,rt?z:pt,F.y)},x.mood,!1);const J=x.for??Math.max(rw,Math.abs(K-z)*ow);rt&&k.push({time:wt,value:u-c});for(let gt=ku,X=0;gt<=J;gt+=ku,X++){const G=z+(K-z)*Math.min(gt,J)/J;rt&&(u=tt(G),k.push({time:wt+gt,value:u-c}));const lt=(X%2===0?-1:1)*d*.02;P(wt+gt,B(Q,G,F.y+lt),void 0,!1)}const kt=wt+J;P(kt,B(Q,K,F.y),void 0,!1),P(kt+vu,{rightShoulder:et.rightShoulder,rightElbow:et.rightElbow,...ct.happy}),q=kt+vu,U=wt,Y=kt}else if(x.do==="push"&&x.target){const F=x.target,z=x.to??F.x,K=C(R,u+(z>=F.x?1:-1),x.mood),V=g===1?F.left??F.x:F.right??F.x,Q={...p,turn:1,lean:16,bend:8,rightWrist:0,leftWrist:0,lookX:1,...Z},tt=D(Q,V,F.y,"arm"),st=_(K,tt+g*d*.06,cs),pt=B(Q,V,F.y),ht={...Q,...pt,leftShoulder:-pt.rightShoulder,leftElbow:-pt.rightElbow},rt=st+aw;P(rt,ht,x.mood,!1);const wt=Math.abs(z-F.x),J=rt+(x.for??Math.max(600,wt/lw)),kt=wt/Xo("shove",d);E.push({time:rt,value:"shove"}),$.push({time:rt,value:0},{time:rt+ie,value:1,easing:"ease-out"},{time:J-ie,value:1},{time:J,value:0,easing:"ease-in"}),M.push({time:rt,value:m},{time:J,value:m+kt}),m+=kt,k.push({time:rt,value:u-c},{time:J,value:u+(z-F.x)-c}),u+=z-F.x,P(J,{},void 0,!1),P(J+Mu,{lean:0,bend:0,rightShoulder:et.rightShoulder,leftShoulder:et.leftShoulder,rightElbow:et.rightElbow,leftElbow:et.leftElbow}),q=J+Mu,U=rt,Y=J}else if(nt){const F=x.mood?ge(p,x.mood):p,z=nt.steps(F,x),K=Ur(z,{at:R,from:F});S.push(...K),p=K[K.length-1].pose,q=R+Math.max(cu(z),x.for??0)}else if(Su(x.do)){const F=Xr(x.do,{at:R,from:x.mood?ge(p,x.mood):p});S.push(...F),p=F[F.length-1].pose,q=R+os(x.do),x.do==="take"&&v.push({kind:"dust",time:R+900,x:u,y:f,length:500}),x.do==="land"&&v.push({kind:"dust",time:R+120,x:u,y:f,length:500})}else if(x.do==="look"||x.do==="face"){const F=x.toward??"viewer",z=x.for??cw;if(F==="viewer")P(R+se,{turn:0,lookX:0,lookY:0,...Z},x.mood);else if(F==="ahead")P(R+se,{turn:x.do==="face"?1:.6,lookX:1,...Z},x.mood);else if(F==="back")P(R+se,{turn:.2,lookX:-1,...Z},x.mood);else{const K=O(F);K!==g&&x.do==="face"?(H(R,K,x.mood),P(R+yn+1,{lookX:1,...Z})):K!==g?P(R+se,{turn:.25,lookX:-1,...Z},x.mood):P(R+se,{turn:x.do==="face"?1:.6,lookX:1,...Z},x.mood)}q=R+Math.max(z,se)}else if(uw(x.do)||x.do==="stand"){const F=x.do==="stand"?n.rest??et:Dt[x.do],z=F.turn!==et.turn?F.turn:p.turn,K=x.mood?ct[x.mood]:{lookX:p.lookX,lookY:p.lookY};P(R+se,{...F,turn:z,...K,...Z}),q=R+(x.for??aa)}else{const F=x.for??(x.say?Tu(x.say):aa);(x.mood||x.pose)&&P(R+Math.min(se,F/2),Z,x.mood),q=R+F}if(x.say){const F=r(x.do)||Su(x.do)||nt?R:R+Math.min(150,(q-R)/4),z=r(x.do)?q:Math.max(F+200,q-100);T.push({text:x.say,start:F,end:z}),x.do==="say"&&mw(S,p,F,z)}x.onto!==void 0&&x.do!=="leap"&&x.onto!==f&&(y.push({time:R,value:f-h},{time:q,value:x.onto-h,easing:"ease-in-out"}),f=x.onto),q>S[S.length-1].time&&S.push({time:q,pose:p}),I.push({start:R,end:q,...U!==void 0?{contact:U}:{},...Y!==void 0?{release:Y}:{}}),b=q}const L=Gd(t,gw(S),n),N=[{id:`${t}-x`,target:t,property:"x",keyframes:k},{id:`${t}-y`,target:t,property:"y",keyframes:y},{id:`${t}-walk`,target:t,property:"walk",keyframes:M},{id:`${t}-walking`,target:t,property:"walking",keyframes:$},{id:`${t}-gait`,target:t,property:"gait",keyframes:E},{id:`${t}-facing`,target:t,property:"facing",keyframes:A}].filter(x=>x.keyframes.length>1||x.property==="x"||x.property==="facing"&&x.keyframes[0].value===-1);return{tracks:[...au(t,L,T,{energy:n.energy}),...N],duration:b,lines:T,keys:S,beats:I,effects:v}}const fw=t=>Math.max(-1,Math.min(1,t)),pw=30;function gw(t){const e=[];for(const n of t){const s=e[e.length-1];s&&n.time-s.time<pw?e[e.length-1]={...n,time:s.time}:e.push(n)}return e}function mw(t,e,n,s){const o=t.filter(l=>l.time>n),r=t.filter(l=>l.time<=n),a=[];for(let l=n+520,c=0;l<s-520/2;l+=520,c++){const h=c%2===0?3:-2;a.push({time:l,pose:{...e,headTilt:e.headTilt+h,leftBrow:e.leftBrow+(c%2===0?.25:0),rightBrow:e.rightBrow+(c%2===0?.25:0)}})}a.length>0&&a.push({time:s,pose:e}),t.length=0,t.push(...r,...a.filter(l=>!o.some(c=>Math.abs(c.time-l.time)<60)),...o),t.sort((l,c)=>l.time-c.time)}function ca(t,e,n){const s=new Ht({id:`${t}-hand`,tracks:e.filter(l=>l.target===t)}),i=Zo({x:n.x,y:n.y,style:n.style,cast:n.cast}),o=n.side??"right",r=n.every??33,a=[];for(let l=n.start;;l=Math.min(n.end,l+r)){const{joints:c}=Qo(i,{time:l,state:s.getStateAtTime(l)},t),h=c.hands[o],d=c.fingertips[o];if(a.push({time:l,x:(h.x+d.x)/2,y:(h.y+d.y)/2}),l>=n.end)break}return a}const bn=["start","contact","release","end"],yw=["surface","edit","anchor","at","until"],bw=["carry"],Ii=t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&"surface"in t&&"anchor"in t,ww=t=>t.then===void 0?[]:Array.isArray(t.then)?t.then:[t.then];function kw(t,e,n,s={}){const i=Eu(n,e,s).filter(u=>u.level==="error");if(i.length>0)throw new Error(`surfaceScript: ${i.length} problem(s) in the beats:
|
|
59
|
-
${i.map(
|
|
60
|
-
`)}`);const o=n.map(u=>Au(u,e)),r=la(t,o,s),a=vw(o,r.beats,s),l=s.ground??0,c=u=>s.ride===!1?u:Object.values(e).reduce((f,g)=>g.ride(f,t,{ground:l}),u);n.forEach((u,f)=>{for(const g of ww(u)){const p=y=>new Error(`surfaceScript: beat ${f} (${u.do}), ${g.edit} on ${g.surface}: ${y}`),m=(y,M)=>{const $=typeof y=="object"?y.beat:f,E=(typeof y=="object"?y.at:y)??M??"start",A=a[$][E];if(A===void 0){const T=bn.filter(I=>a[$][I]!==void 0).join(", ");throw p(`beat ${$} (${n[$].do}) has no ${E} (it has ${T})`)}return A},b=e[g.surface],S=m(g.at??(a[f].contact!==void 0?"contact":"start")),k=g.until===void 0?void 0:m(g.until,"end");if(k!==void 0&&k<S)throw p(`it ends (${k} ms) before it starts (${S} ms)`);try{if(g.edit==="carry"){const M=b.piece(g.anchor),$=ca(t,c(r.tracks),{x:s.from??0,y:l,style:s.figureStyle??(s.height?{height:s.height}:void 0),cast:s,start:S,end:k});b.follow(M,$);continue}const y=Object.fromEntries(Object.entries(g).filter(([M])=>!yw.includes(M)));b.edit(g.edit,g.anchor,{...y,at:S,...k!==void 0?{duration:k-S}:{}})}catch(y){throw p(y.message)}}});const h=c(r.tracks),d=Object.entries(e).flatMap(([u,f])=>f.tracks(u));return{...r,tracks:[...h,...d],figureTracks:h}}function Eu(t,e,n={}){if(!Array.isArray(t))return ls(t,n);const s=[],i=Object.keys(e),o=(c,h,d)=>{const u=typeof h=="string"?e[h]:void 0;return u||s.push({level:"error",beat:c,message:`${d}: ${ot("surface",h,i)}`}),u},r=(c,h,d,u)=>{if(typeof d!="string"){s.push({level:"error",beat:c,message:`${u}: \`anchor\` is a place name such as ${Object.keys(h.about.anchors).join(", ")} (got ${JSON.stringify(d)}).`});return}try{h.anchor(d,0)}catch(f){s.push({level:"error",beat:c,message:`${u}: ${f.message}`})}},a=(c,h,d)=>{const u=typeof h=="object"&&h!==null?h.at:h;if(typeof h=="object"&&h!==null){const f=h.beat;if((typeof f!="number"||!Number.isInteger(f)||f<c||f>=t.length)&&s.push({level:"error",beat:c,message:`${d}: \`beat\` is the index of this beat or a later one, ${c} to ${t.length-1} (got ${JSON.stringify(f)}).`}),u===void 0)return}typeof u=="number"?s.push({level:"error",beat:c,message:`${d}: a cue starts at a moment of its beat (${bn.join(", ")}), not at ms; set the beat's own \`at\` to move it.`}):(typeof u!="string"||!bn.includes(u))&&s.push({level:"error",beat:c,message:`${d}: ${ot("moment",u,bn)}`})};t.forEach((c,h)=>{if(!c||typeof c!="object"||Array.isArray(c))return;const d=c;for(const f of["target","to","onto"]){if(!Ii(d[f]))continue;const g=d[f],p=o(h,g.surface,`\`${f}\``);p&&r(h,p,g.anchor,`\`${f}\``)}if(d.then===void 0)return;(Array.isArray(d.then)?d.then:[d.then]).forEach(f=>{if(!f||typeof f!="object"||Array.isArray(f)){s.push({level:"error",beat:h,message:"`then` is a cue, { surface, edit, anchor, at?, until? }, or a list of them."});return}const g=f,p=o(h,g.surface,"`then`");if(!p)return;const m=`\`then\` (${String(g.edit)} on ${String(g.surface)})`,b=[...Object.keys(p.about.edits),...bw];if(typeof g.edit!="string"||!b.includes(g.edit)){s.push({level:"error",beat:h,message:`\`then\`: ${ot("edit",g.edit,b)}`});return}for(const S of Array.isArray(g.anchor)?g.anchor:[g.anchor])r(h,p,S,m);g.edit==="carry"&&typeof g.anchor!="string"&&s.push({level:"error",beat:h,message:`${m}: \`carry\` takes one anchor, the piece it carries.`}),g.edit==="carry"&&g.until===void 0&&s.push({level:"error",beat:h,message:`${m}: \`carry\` needs \`until\` (when it lets go, such as { beat: ${h+1}, at: 'release' }).`}),g.at!==void 0&&a(h,g.at,`${m} \`at\``),g.until!==void 0&&a(h,g.until,`${m} \`until\``),g.until!==void 0&&g.duration!==void 0&&s.push({level:"error",beat:h,message:`${m}: give \`until\` or \`duration\`, not both.`})})});const l=t.map(c=>c&&typeof c=="object"&&!Array.isArray(c)?Au(c,e,!0):c);return[...ls(l,n),...s]}function Au(t,e,n=!1){const{then:s,...i}=t,o=a=>{try{return e[a.surface].anchor(a.anchor,0)}catch(l){if(n)return{x:0,y:0,left:0,right:0,top:0,bottom:0,width:0,height:0};throw l}},r={...i};return Ii(t.target)&&(r.target=o(t.target)),Ii(t.to)&&(r.to=o(t.to).x),Ii(t.onto)&&(r.onto=o(t.onto).top),r}function vw(t,e,n){let s=0;return t.map(i=>{const o=Pi([i],n.actions).length,r=e.slice(s,s+o);s+=o;const a=r.find(c=>c.contact!==void 0)?.contact,l=[...r].reverse().find(c=>c.release!==void 0)?.release;return{start:r[0]?.start,end:r[r.length-1]?.end,...a!==void 0?{contact:a}:{},...l!==void 0?{release:l}:{}}})}function Mw(t){const e={actions:t.actions,gaits:t.gaits},n=Jr(e);if(n.length>0)throw new Error(`persona "${t.name}": ${n.join(" ")}`);const s=[...Object.keys(Ot),...Object.keys(t.gaits??{})],i=t.gait??"walk";if(!s.includes(i))throw new Error(`persona "${t.name}": ${ot("gait",i,s)}`);if(t.mood&&!(t.mood in ct))throw new Error(`persona "${t.name}": ${ot("mood",t.mood,Object.keys(ct))}`);const o=t.acting??"snappy";if(typeof o=="string"&&!(o in je))throw new Error(`persona "${t.name}": ${ot("acting style",o,Object.keys(je))}`);if(typeof t.stance=="string"&&!(t.stance in Dt))throw new Error(`persona "${t.name}": ${ot("stance",t.stance,Object.keys(Dt))}`);const r=t.height??120,a=typeof t.stance=="string"?Dt[t.stance]:Et(t.stance??{}),l=t.mood?ge(a,t.mood):a,c={...t.look,height:r},h=t.summary??`${t.name}, a stick figure`;return{name:t.name,summary:h,cast:e,rest:l,height:r,figure:d=>Zo({x:d.x,y:d.y,pose:l,style:{...c,...d.facing?{facing:d.facing}:{}},cast:e}),script:(d,u,f={})=>la(d,u,{...e,from:f.from,ground:f.ground,facing:f.facing,height:r,style:o,gait:i,start:l,rest:l,energy:t.energy}),check:d=>ls(d,e),handPath:(d,u,f)=>ca(d,u,{...f,style:c,cast:e}),describe:()=>({name:t.name,summary:h,habits:{height:r,acting:typeof o=="string"?o:"custom",gait:i,...t.mood?{mood:t.mood}:{},stance:typeof t.stance=="string"?t.stance:t.stance?"custom":"rest"},actions:Zr(e),own:{actions:Object.keys(t.actions??{}),gaits:Object.keys(t.gaits??{})}})}}const at=["rect","circle","text","line","path","image","custom"],Oi={x:{description:"Moves it right by this much from where it was placed (an offset; the target’s own x is its place)",unit:"px",types:at},y:{description:"Moves it down by this much from where it was placed (an offset)",unit:"px",types:at},opacity:{description:"How opaque it is",unit:"0..1",min:0,max:1,types:at},rotate:{description:"Turns it clockwise about its origin",unit:"degrees",types:at},rotateX:{description:"Tips it about the horizontal axis (3D; shows with perspective)",unit:"degrees",types:at},rotateY:{description:"Turns it about the vertical axis (3D; shows with perspective)",unit:"degrees",types:at},z:{description:"Depth toward the viewer (shows with perspective)",unit:"px",types:at},perspective:{description:"Distance from the viewer: nearer parts grow, further ones shrink",unit:"px",min:1,types:at},scale:{description:"Size, both ways",unit:"factor",types:at},scaleX:{description:"Width factor",unit:"factor",types:at},scaleY:{description:"Height factor",unit:"factor",types:at},skewX:{description:"Slants it sideways",unit:"degrees",types:at},skewY:{description:"Slants it up and down",unit:"degrees",types:at},originX:{description:"Transform pivot across its box",unit:"% (0 left, 50 centre, 100 right)",min:0,max:100,types:at},originY:{description:"Transform pivot down its box",unit:"% (0 top, 50 centre, 100 bottom)",min:0,max:100,types:at},fill:{description:"Fill colour (also written fillStyle)",kind:"color",types:at},stroke:{description:"Outline colour (also written strokeStyle)",kind:"color",types:at},strokeWidth:{description:"Outline width (also written lineWidth)",unit:"px",min:0,types:at},clipTop:{description:"Hides this much from the top edge, for reveals",unit:"% of its height",min:0,max:100,types:at},clipRight:{description:"Hides this much from the right edge",unit:"% of its width",min:0,max:100,types:at},clipBottom:{description:"Hides this much from the bottom edge",unit:"% of its height",min:0,max:100,types:at},clipLeft:{description:"Hides this much from the left edge",unit:"% of its width",min:0,max:100,types:at},blur:{description:"Gaussian blur",unit:"px",min:0,types:at},brightness:{description:"Brightness factor (1 unchanged)",unit:"factor",min:0,types:at},glow:{description:"Soft glow around it, in glowColor",unit:"px",min:0,types:at},glowColor:{description:"Colour of the glow",kind:"color",types:at},shadowX:{description:"Drop shadow offset right",unit:"px",types:at},shadowY:{description:"Drop shadow offset down",unit:"px",types:at},shadowBlur:{description:"Drop shadow softness",unit:"px",min:0,types:at},shadowColor:{description:"Drop shadow colour",kind:"color",types:at},shine:{description:"A highlight sweeping across the fill",unit:"0..1 (progress)",min:0,max:1,types:at},drawOn:{description:"How much of the outline is drawn, for drawing a shape on; the fill appears when it is complete",unit:"0..1",min:0,max:1,types:["rect","circle","line","path"]},width:{description:"Box width",unit:"px",min:0,types:["rect","image"]},height:{description:"Box height",unit:"px",min:0,types:["rect","image"]},borderRadius:{description:"Rounded corners",unit:"px",min:0,types:["rect","image"]},radius:{description:"Circle radius",unit:"px",min:0,types:["circle"]},x2:{description:"Line end, x",unit:"px",types:["line"]},y2:{description:"Line end, y",unit:"px",types:["line"]},d:{description:"SVG path data; tween between paths to morph",kind:"string",types:["path"]},text:{description:"The text shown (a text track types or scrambles it)",kind:"string",types:["text"]},fontSize:{description:"Font size",unit:"px",min:0,types:["text"]},fontWeight:{description:"Font weight",unit:"100..900",min:100,max:900,types:["text"]},motionPath:{description:"Moves it along an SVG path (a motion-path track writes motionPathX/Y and, aligned, rotate)",kind:"string",types:at},quaternion:{description:'A rotation as [x, y, z, w] (a track with interpolation: "slerp")',kind:"list",types:at}},ha={fillStyle:"fill",strokeStyle:"stroke",lineWidth:"strokeWidth",rotateZ:"rotate",motionPathX:"x",motionPathY:"y",motionPathRotate:"rotate"},Sw={rotation:"rotate",angle:"rotate",alpha:"opacity",fade:"opacity",color:"fill",colour:"fill",background:"fill",size:"scale",left:"x",top:"y",translateX:"x",translateY:"y",r:"radius",path:"d",content:"text"};function $u(t){const e=t,n=Object.entries(Oi).filter(([,i])=>i.types.includes(t.type)).map(([i,{types:o,...r}])=>({name:i,...r,...e[i]!==void 0&&typeof e[i]!="object"?{value:e[i]}:{}}));if(t.type!=="custom")return{type:t.type,properties:n};const s=t.about;for(const[i,o]of Object.entries(t.props??{}))n.push({name:i,description:s?.props?.[i]?.description??"",...s?.props?.[i],value:o});return{type:"custom",...s?{kind:s.kind,summary:s.summary}:{},properties:n,...s?.actions?{actions:s.actions}:{}}}function Pu(t){const e=$u(t).properties.map(n=>n.name);return[...e,...Object.keys(ha).filter(n=>e.includes(ha[n]))]}function Tw(t,e){const n=[],s=Object.keys(e);for(const i of t){const o=u=>n.push({level:"error",track:i.id,message:u}),r=e[i.target];if(!r){o(ot("target",i.target,s));continue}const a=Pu(r),l=r.type==="custom"&&r.acceptsProp?.(i.property);if(!a.includes(i.property)&&!l){o(`${i.target}: ${ot("property",i.property,a,Sw[i.property])}`);continue}const c=i.keyframes??[];for(let u=1;u<c.length;u++)c[u].time<c[u-1].time&&o(`${i.target}.${i.property}: keyframes out of time order (${c[u-1].time} ms, then ${c[u].time} ms).`);const h=Oi[ha[i.property]??i.property]??r.about?.props?.[i.property],d=h&&(h.kind??"number")==="number";for(const u of c){if(d&&typeof u.value!="number"){o(`${i.target}.${i.property}: values are numbers${h.unit?` (${h.unit})`:""} (got ${JSON.stringify(u.value)} at ${u.time} ms).`);break}if(d&&typeof u.value=="number"&&(h.min!==void 0&&u.value<h.min||h.max!==void 0&&u.value>h.max)){n.push({level:"warning",track:i.id,message:`${i.target}.${i.property}: ${u.value} at ${u.time} ms is outside ${h.min??"−∞"}..${h.max??"∞"}${h.unit?` (${h.unit})`:""}.`});break}}}return n}const wn=(t,e)=>t[2]<=-e;function da(t,e,n){const s=(-n-t[2])/(e[2]-t[2]);return[t[0]+(e[0]-t[0])*s,t[1]+(e[1]-t[1])*s,-n]}function xu(t,e){if(t.every(s=>wn(s,e)))return t;const n=[];return t.forEach((s,i)=>{const o=t[(i+t.length-1)%t.length],r=wn(s,e),a=wn(o,e);r!==a&&n.push(da(o,s,e)),r&&n.push(s)}),n.length>=3?n:[]}function Ew(t,e){if(t.every(i=>wn(i,e)))return[t];const n=[];let s=[];return t.forEach((i,o)=>{const r=wn(i,e);if(o>0){const a=t[o-1],l=wn(a,e);l&&!r?(s.push(da(a,i,e)),n.push(s),s=[]):!l&&r&&s.push(da(a,i,e))}r&&s.push(i)}),s.length>0&&n.push(s),n.filter(i=>i.length>=2)}function Iu(t,e,n){const s=e-t;if(!(s>=n*1.5))return[t,e];const i=Math.round(s/n);return Array.from({length:i+1},(o,r)=>t+s*r/i)}function Aw(t,e,n){const s=(i,o)=>Math.max(0,Math.min(i.length-2,i.findIndex((r,a)=>a>0&&o<=r)-1));return[s(t,n[0]),s(e,n[2])]}function $w(t,e){const n=s=>{const i=[e[0]*s[0]+e[4]*s[1]+e[8]*s[2],e[1]*s[0]+e[5]*s[1]+e[9]*s[2],e[2]*s[0]+e[6]*s[1]+e[10]*s[2]],o=Math.hypot(...i)||1;return[i[0]/o,i[1]/o,i[2]/o]};return{...t,vertices:t.vertices.map(s=>Rt(e,s)),faces:t.faces.map(s=>({corners:s.corners,normal:n(s.normal)}))}}function _i(t,e,n,s){const i=r=>(r[e]-n)*s>=0;if(t.every(i))return t;const o=[];return t.forEach((r,a)=>{const l=t[(a+t.length-1)%t.length];if(i(r)!==i(l)){const c=(n-l[e])/(r[e]-l[e]);o.push([0,1,2].map(h=>h===e?n:l[h]+(r[h]-l[h])*c))}i(r)&&o.push(r)}),o.length>=3?o:[]}function Pw(t,e,n){const s=t.faces.map(r=>({points:r.corners.map(a=>t.vertices[a]),normal:r.normal})),i=[],o={x:e.slice(1,-1),z:n.slice(1,-1)};for(let r=0;r+1<e.length;r++)for(let a=0;a+1<n.length;a++){const l=[],c=new Map,h=g=>{const p=g.map(b=>Math.round(b*1e6)).join(",");let m=c.get(p);return m===void 0&&(m=l.length,l.push(g),c.set(p,m)),m},d=[],u=g=>g===0,f=(g,p)=>g+2===p.length;for(const g of s){let p=g.points;u(r)||(p=_i(p,0,e[r],1)),p.length&&!f(r,e)&&(p=_i(p,0,e[r+1],-1)),p.length&&!u(a)&&(p=_i(p,2,n[a],1)),p.length&&!f(a,n)&&(p=_i(p,2,n[a+1],-1)),p.length>=3&&d.push({corners:p.map(h),normal:g.normal})}d.length>0&&i.push({cell:[r,a],mesh:{vertices:l,faces:d,creases:t.creases,joined:t.joined,walls:o}})}return i}const xw=new WeakMap,Iw=new WeakMap,Ow=48,Ou=t=>t.map(e=>Math.round(e*1e5)).join(",");function _u(t,e,n,s){let i=t.get(e);i||t.set(e,i=new Map);let o=i.get(n);return o===void 0&&(i.size>=Ow&&i.clear(),i.set(n,o=s())),o}function ua(t,e){const n=Ou(e);return _u(xw,t,n,()=>{const s=$w(t,e),i=[1/0,1/0,1/0],o=[-1/0,-1/0,-1/0];for(const r of s.vertices)for(const a of[0,1,2])i[a]=Math.min(i[a],r[a]),o[a]=Math.max(o[a],r[a]);return{key:n,inSpace:s,low:i,high:o}})}function _w(t,e){const n=t.map(h=>({...h,...ua(h.mesh,h.local)})),s=[1/0,1/0,1/0],i=[-1/0,-1/0,-1/0];for(const h of n)for(const d of[0,1,2])s[d]=Math.min(s[d],h.low[d]),i[d]=Math.max(i[d],h.high[d]);const o=Iu(s[0],i[0],e),r=Iu(s[2],i[2],e),a=`${o.join(",")}|${r.join(",")}`,l=n.flatMap(h=>{if(h.high[0]-h.low[0]<=e*2.5&&h.high[2]-h.low[2]<=e*2.5||h.whole||h.mesh.joined||(h.mesh.marks?.length??0)>0){const u=[(h.low[0]+h.high[0])/2,(h.low[1]+h.high[1])/2,(h.low[2]+h.high[2])/2];return[{part:h.part,mesh:h.mesh,cut:!1,cell:Aw(o,r,u)}]}return _u(Iw,h.inSpace,a,()=>Pw(h.inSpace,o,r)).map(u=>({part:h.part,mesh:u.mesh,cut:!0,cell:u.cell}))}),c=(s[1]+i[1])/2;return{pieces:l,middle:([h,d])=>[(o[h]+o[h+1])/2,c,(r[d]+r[d+1])/2]}}const Cu=.004,fa=.05,Hu=new WeakMap;function Cw(t){let e=Hu.get(t);return e===void 0&&(e=!t.joined&&!t.walls&&t.faces.length>=4&&t.faces.every(n=>{const s=t.vertices[n.corners[0]];return t.vertices.every(i=>n.normal[0]*(i[0]-s[0])+n.normal[1]*(i[1]-s[1])+n.normal[2]*(i[2]-s[2])<=1e-6)}),Hu.set(t,e)),e}const Ru=new WeakMap;function Lu(t){return t.filter(({mesh:e})=>Cw(e)).map(({part:e,key:n,inSpace:s,low:i,high:o})=>{let r=Ru.get(s);return r||(r=s.faces.map(a=>{const l=s.vertices[a.corners[0]];return{normal:a.normal,offset:a.normal[0]*l[0]+a.normal[1]*l[1]+a.normal[2]*l[2]}}),Ru.set(s,r)),{part:e,key:n,planes:r,low:i,high:o}})}function Hw(t,e,n,s){const i=e.reduce((o,r)=>[o[0]+r[0]/e.length,o[1]+r[1]/e.length,o[2]+r[2]/e.length],[0,0,0]);for(const o of s){if(o.part===t||[0,1,2].some(a=>i[a]<o.low[a]-fa||i[a]>o.high[a]+fa))continue;if(o.planes.every(a=>{const l=a.normal[0]*n[0]+a.normal[1]*n[1]+a.normal[2]*n[2],c=e.map(d=>a.normal[0]*d[0]+a.normal[1]*d[1]+a.normal[2]*d[2]-a.offset);if(c.every(d=>Math.abs(d)<=Cu))return l<-.9;const h=Math.abs(l)<.5?fa:Cu;return c.every(d=>d<=h)}))return!0}return!1}const Nu=new WeakMap;function Du(t,e,n,s,i){const o=`${s}|${i.map(l=>l.key).join(";")}`;let r=Nu.get(e);r||Nu.set(e,r=new Map);let a=r.get(o);if(!a){r.size>=48&&r.clear();const l=h=>{const d=[n[0]*h[0]+n[4]*h[1]+n[8]*h[2],n[1]*h[0]+n[5]*h[1]+n[9]*h[2],n[2]*h[0]+n[6]*h[1]+n[10]*h[2]],u=Math.hypot(...d)||1;return[d[0]/u,d[1]/u,d[2]/u]},c=e.vertices.map(h=>Rt(n,h));a=e.faces.map(h=>Hw(t,h.corners.map(d=>c[d]),l(h.normal),i)),r.set(o,a)}return a}const kn={turn:{description:"Which way it faces: 0 toward the viewer, 1 screen-right, 2 away, 3 (or −1) screen-left; in between turns it in 3D",unit:"quarter turns"},tilt:{description:"How far the camera looks down on it: 0 level, 12 the ¾ look, 90 straight down",unit:"degrees",default:12,min:-90,max:90},pitch:{description:"Nose up (+) or down (−), about its middle on the ground",unit:"degrees"},roll:{description:"Tipped onto its right (+) or left (−) side",unit:"degrees"},squash:{description:"Squash and stretch about the ground, keeping its volume: 1 normal, below squashed, above stretched",unit:"factor",default:1,min:.3,max:3},lift:{description:"Off the ground",unit:"metres"},lean:{description:"The top sheared forward (+) or back (−): speed and drag",unit:"shear"},size:{description:"Its size, about the ground: 1 as built, 0 gone (pop it in or out)",unit:"factor",default:1,min:0}},pa=Math.PI/180;function Fu(t,e,n){return{toView:s=>ar(be(s,t*90*pa),-e*pa),toScreen:s=>({x:s[0]*n,y:-s[1]*n})}}const ju=new WeakMap,hs=t=>Ci(t),Ci=t=>{let e=ju.get(t);return e||ju.set(t,e=Td(t)),e};function ft(t,e,n){return e[n]??t.controls[n]?.default??kn[n]?.default??0}function ds(t,e){const n=Math.max(.05,ft(t,e,"squash")),s=1/Math.sqrt(n),o=[1,0,0,0,0,1,ft(t,e,"lean"),0,0,0,1,0,0,0,0,1];return[xe([0,ft(t,e,"lift"),0]),zt(Wt([1,0,0],-ft(t,e,"pitch"))),zt(Wt([0,0,1],ft(t,e,"roll"))),o,Ie([s,n,s]),Ie(Array(3).fill(Math.max(0,ft(t,e,"size"))))].reduce((r,a)=>mt(r,a))}function ga(t,e){const n=ds(t,e),s=new Map,i=Object.entries(t.controls).flatMap(([r,a])=>(a.bind??[]).map(l=>({value:ft(t,e,r),bind:l}))),o=r=>{const a=s.get(r.id);if(a)return a;const l=r.parent?t.parts.find(h=>h.id===r.parent):void 0;if(r.parent&&!l)throw new Error(`prop rig: part "${r.id}" hangs from "${r.parent}", which is not a part`);let c=mt(l?o(l):n,xe(r.at??[0,0,0]));if(r.rotate){const[h,d,u]=r.rotate;h&&(c=mt(c,zt(Wt([1,0,0],h)))),d&&(c=mt(c,zt(Wt([0,1,0],d)))),u&&(c=mt(c,zt(Wt([0,0,1],u))))}for(const{value:h,bind:d}of i)if(!(!d.parts.includes(r.id)||h===0)){if(d.translate&&(c=mt(c,xe([d.translate[0]*h,d.translate[1]*h,d.translate[2]*h]))),d.rotate){const u=d.rotate.pivot??[0,0,0],f=d.rotate.axis==="x"?[1,0,0]:d.rotate.axis==="y"?[0,1,0]:[0,0,1];c=[c,xe(u),zt(Wt(f,d.rotate.degrees*h)),xe([-u[0],-u[1],-u[2]])].reduce((g,p)=>mt(g,p))}d.scale&&(c=mt(c,Ie([1+(d.scale[0]-1)*h,1+(d.scale[1]-1)*h,1+(d.scale[2]-1)*h])))}return s.set(r.id,c),c};for(const r of t.parts)o(r);return s}const ma=(()=>{const t=[-.45,.75,.5],e=Math.hypot(...t);return[t[0]/e,t[1]/e,t[2]/e]})(),Rw=Math.cos(35*pa);function ya(t,e,n,s,i={}){const o=t.derive?{...e,...t.derive(e)}:e,r=ga(t,o),a=n.toView([0,0,0]),l=O=>C=>[O[0]*C[0]+O[4]*C[1]+O[8]*C[2],O[1]*C[0]+O[5]*C[1]+O[9]*C[2],O[2]*C[0]+O[6]*C[1]+O[10]*C[2]],c=ds(t,o),h=i.slice===void 0?null:wo(c),d=h?t.parts.map(O=>({part:O,mesh:Ci(O.shape),local:mt(h,r.get(O.id)),whole:O.shape.type==="tube"})):void 0,u=d?_w(d,i.slice):void 0,f=d?Lu(d.map(O=>({part:O.part.id,mesh:O.mesh,...ua(O.mesh,O.local)}))):void 0,g=(O,C,j,D)=>{const W=X=>n.toView(Rt(j,X)),B=C.vertices.map(W),_=B.map(X=>n.toScreen(X)),L=i.perspective?i.near:void 0,N=X=>X.map(G=>n.toScreen(G)),x=X=>L===void 0?X:xu(X,L),R=X=>L===void 0?[X]:Ew(X,L),q=l(j),U=C.faces.map(X=>{const G=n.toView(q(X.normal)),lt=[G[0]-a[0],G[1]-a[1],G[2]-a[2]],St=Math.hypot(...lt)||1;return[lt[0]/St,lt[1]/St,lt[2]/St]}),Y=f&&D?Du(O.id,C,D,Ou(D),f):void 0,Z=X=>Y?.[X]??!1,nt=U.map((X,G)=>{if(Z(G))return!1;if(!i.perspective)return X[2]>1e-6;const St=C.faces[G].corners.reduce((Ct,At)=>[Ct[0]+B[At][0],Ct[1]+B[At][1],Ct[2]+B[At][2]],[0,0,0]);return-(X[0]*St[0]+X[1]*St[1]+X[2]*St[2])>1e-9}),F=X=>C.faces[X].corners.reduce((G,lt)=>G+B[lt][2],0)/C.faces[X].corners.length,z=C.faces.map((X,G)=>({face:X,i:G})).filter(({i:X})=>nt[X]).map(({face:X,i:G})=>({i:G,solved:{points:L===void 0?X.corners.map(lt=>_[lt]):N(x(X.corners.map(lt=>B[lt]))),depth:F(G),tone:.72+.33*Math.max(0,U[G][0]*ma[0]+U[G][1]*ma[1]+U[G][2]*ma[2])}})).filter(X=>X.solved.points.length>=3).sort((X,G)=>X.solved.depth-G.solved.depth);if(i.light){const X=l(j);for(const{i:G,solved:lt}of z){const St=C.faces[G].corners,Ct=St.reduce(($a,c2)=>{const Pa=Rt(j,C.vertices[c2]);return[$a[0]+Pa[0]/St.length,$a[1]+Pa[1]/St.length,$a[2]+Pa[2]/St.length]},[0,0,0]),At=X(C.faces[G].normal),Ke=Math.hypot(...At)||1,_f=i.light(Ct,[At[0]/Ke,At[1]/Ke,At[2]/Ke]);lt.light=_f.light,lt.fog=_f.fog}}const K=z.map(X=>X.solved),V=Lw(C),Q=[],tt=[];for(const[X,G]of V){const lt=G.filter(Ct=>nt[Ct]).length;if(lt===0)continue;const St=G.length===2&<===2&&C.creases!==!1&&U[G[0]][0]*U[G[1]][0]+U[G[0]][1]*U[G[1]][1]+U[G[0]][2]*U[G[1]][2]<Rw;G.length===1&&(C.joined||Nw(C,X))||(G.length===1||lt===1||St)&&(Q.push(X.split("-").map(Number)),tt.push(G.filter(Ct=>nt[Ct]).reduce((Ct,At)=>F(At)>F(Ct)?At:Ct)))}const st=X=>C.faces.findIndex(G=>G.corners.length>4&&Math.sign(Fw(C.vertices[X],G.normal))>0),pt=(C.marks??[]).filter(([X])=>st(X)<0||nt[st(X)]),ht=([X,G])=>L===void 0?[[_[X],_[G]]]:R([B[X],B[G]]).map(N),rt=pt.flatMap(ht),wt=X=>L===void 0?[X.map(G=>_[G])]:R(X.map(G=>B[G])).map(N);if(i.slice!==void 0){const X=new Map;Q.forEach((G,lt)=>X.set(tt[lt],[...X.get(tt[lt])??[],G]));for(const{i:G,solved:lt}of z){lt.edges=Ku(X.get(G)??[]).flatMap(wt);const St=C.faces[G].corners;lt.center=St.reduce((At,Ke)=>[At[0]+B[Ke][0]/St.length,At[1]+B[Ke][1]/St.length,At[2]+B[Ke][2]/St.length],[0,0,0]),lt.normal=U[G];const Ct=z[z.length-1].i;lt.marks=pt.filter(([At])=>(st(At)>=0?st(At):Ct)===G).flatMap(ht)}}const J=O.glow?Math.max(0,Math.min(1,ft(t,o,O.glow.control))):0,kt=O.fade?Math.max(0,Math.min(1,ft(t,o,O.fade.control))):0,gt=O.fade?Math.max(0,Math.min(1,O.fade.from+(O.fade.to-O.fade.from)*kt)):1;return{part:O,depth:B.reduce((X,G)=>X+G[2],0)/Math.max(1,B.length),faces:K,edges:Ku(Q).flatMap(wt),marks:rt,glow:J,opacity:gt,...O.shape.type==="tube"?{spine:Dw(R(O.shape.points.map(W)).map(N))}:{},...C.walls?{cut:!0}:{}}},p=new Map(d?.map(O=>[O.part.id,O.local])),b=(u?u.pieces.map(O=>({part:O.part,mesh:O.mesh,m:O.cut?c:r.get(O.part.id),local:O.cut?Os():p.get(O.part.id),cell:O.cell})):t.parts.map(O=>({part:O,mesh:Ci(O.shape),m:r.get(O.id),local:void 0,cell:void 0}))).map(O=>({cell:O.cell,solved:g(O.part,O.mesh,O.m,O.local)})),S=b.map(O=>O.solved),k=O=>O.filter(C=>C.faces.length>0&&C.opacity>.01).sort((C,j)=>C.depth-j.depth);let y;if(u){const O=new Map(t.parts.map(j=>{const D=r.get(j.id),W=Ci(j.shape).vertices;return[j.id,W.reduce((B,_)=>B+n.toView(Rt(D,_))[2],0)/Math.max(1,W.length)]})),C=new Map;for(const j of b){const D=j.cell.join(",");C.has(D)||C.set(D,{cell:j.cell,parts:[]}),C.get(D).parts.push(j.solved),j.solved.depth=O.get(j.solved.part.id)}y=[...C.values()].map(({cell:j,parts:D})=>({depth:n.toView(Rt(c,u.middle(j)))[2],parts:k(D)})).filter(j=>j.parts.length>0)}const M={};for(const[O,C]of Object.entries(t.anchors??{})){const j=C.part?r.get(C.part):ds(t,o);if(!j)throw new Error(`prop rig: anchor "${O}" is on "${C.part}", which is not a part`);const D=n.toView(Rt(j,C.at));M[O]={point:n.toScreen(D),depth:D[2]}}const[$,E]=t.footprint??[t.length*.45,t.length],A=Math.max(0,ft(t,o,"lift")),T=Math.max(0,ft(t,o,"size"))/(1+A*.8),I=Array.from({length:24},(O,C)=>{const j=Math.PI*2*C/24;return n.toView([Math.cos(j)*$*.55*T,0,Math.sin(j)*E*.55*T])}),v=i.perspective?i.near:void 0,P={points:(v===void 0?I:xu(I,v)).map(O=>n.toScreen(O)),opacity:.16*T},H=S.filter(O=>O.part.seeThrough&&O.opacity>.01).flatMap(O=>O.faces.map(C=>C.points));return{under:k(S.filter(O=>!O.part.overRider)),over:k(S.filter(O=>O.part.overRider)),...y?{cells:y}:{},anchors:M,openings:H,shadow:P,pxPerUnit:s,sizePx:t.height*s}}const Bu=new WeakMap;function Lw(t){let e=Bu.get(t);if(!e){e=new Map;for(let n=0;n<t.faces.length;n++){const s=t.faces[n].corners;for(let i=0;i<s.length;i++){const o=s[i],r=s[(i+1)%s.length],a=o<r?`${o}-${r}`:`${r}-${o}`,l=e.get(a);l?l.push(n):e.set(a,[n])}}Bu.set(t,e)}return e}function Wu(t,e){const n=t.derive?{...e,...t.derive(e)}:e,s=ga(t,n),i=wo(ds(t,n))??Os(),o=r=>Math.max(0,Math.min(1,r));return t.parts.map(r=>{const a=r.fade?o(ft(t,n,r.fade.control)):0;return{part:r,matrix:s.get(r.id),local:mt(i,s.get(r.id)),glow:r.glow?o(ft(t,n,r.glow.control)):0,opacity:r.fade?o(r.fade.from+(r.fade.to-r.fade.from)*a):1}})}function qu(t,e){const n=t.derive?{...e,...t.derive(e)}:e,s=ga(t,n),i=ds(t,n),o={};for(const[r,a]of Object.entries(t.anchors??{})){const l=a.part?s.get(a.part):i;if(!l)throw new Error(`prop rig: anchor "${r}" is on "${a.part}", which is not a part`);o[r]=Rt(l,a.at)}return o}function Nw(t,e){if(!t.walls)return!1;const[n,s]=e.split("-").map(o=>t.vertices[Number(o)]),i=(o,r)=>r.some(a=>Math.abs(n[o]-a)<1e-6&&Math.abs(s[o]-a)<1e-6);return i(0,t.walls.x)||i(2,t.walls.z)}function Dw(t){return t.reduce((e,n)=>!e||n.length>e.length?n:e,void 0)}const Fw=(t,e)=>t[0]*e[0]+t[1]*e[1]+t[2]*e[2];function Ku(t){const e=t.map(s=>[...s]),n=[];for(;e.length>0;){const s=[...e.shift()];let i=!0;for(;i;){i=!1;for(let o=0;o<e.length;o++){const[r,a]=e[o],l=s[s.length-1],c=s[0];if(r===l)s.push(a);else if(a===l)s.push(r);else if(a===c)s.unshift(r);else if(r===c)s.unshift(a);else continue;e.splice(o,1),i=!0;break}}n.push(s)}return n}function ba(t){const e={};for(const[n,s]of Object.entries({...kn,...t.rig.controls})){const{bind:i,...o}=s;e[n]=o}return e}function jw(t){const{prop:e}=t,n=t.scale??60,s=e.rig.length*n*1.4,i=e.rig.height*n*1.6,o=ba(e),r={};for(const[l,c]of Object.entries(o))r[l]=t.values?.[l]??c.default??0;const a={look:t.look,ink:t.ink,lineWidth:t.lineWidth,pencil:t.pencil,seed:t.seed,style:t.style,paper:t.paper};return{type:"custom",x:t.x-s/2,y:t.y-i,width:s,height:i,props:r,prop:e,propScale:n,propDraw:a,about:{kind:e.kind,summary:e.summary,props:o,actions:Object.fromEntries(Object.entries(e.actions).map(([l,c])=>[l,c.summary]))},draw(l,c,h){const d=c.props??{};l.translate(s/2,i),Mr(l,vn(e,d,n),{...a,time:h})}}}function vn(t,e,n){const s=Fu(ft(t.rig,e,"turn"),ft(t.rig,e,"tilt"),n);return ya(t.rig,e,s,n)}function Hi(t,e,n){const s={...t.props};let i=0,o=0;for(const[l,c]of e.state?.values.get(n)??[])typeof c=="number"&&(l==="x"?i=c:l==="y"?o=c:l in s&&(s[l]=c));const r={x:t.x+t.width/2+i,y:t.y+t.height+o},a=vn(t.prop,s,t.propScale);return{values:s,origin:r,solved:a,anchor(l){const c=a.anchors[l];if(!c)throw new Error(`${t.prop.kind}: no anchor "${l}" (it has ${Object.keys(a.anchors).join(", ")||"none"})`);return{x:r.x+c.point.x,y:r.y+c.point.y,depth:c.depth}}}}function Bw(t,e,n,s,i={}){const o=Hi(e,n,s);return t.save(),t.translate(o.origin.x,o.origin.y),Mr(t,o.solved,{...e.propDraw,time:n.time,rider:i.rider?r=>{r.save(),r.translate(-o.origin.x,-o.origin.y),i.rider(r),r.restore()}:void 0}),t.restore(),o}const Mn={kind:"prop",create:"propSurface(propTarget({ x, y, prop }), { tracks? }): its controls and anchors are those the catalog lists for its preset",anchors:{box:"the prop’s whole box","anchor:NAME":"one of its rig’s anchors (door, seat, branch, ridge…), as posed at the time","part:ID":"one of its parts as seen at the time (window-1, door-left, wheel-0-left…)","control:NAME":"where the parts a control moves or lights are (control:door is the doors, control:lights the lamps)"},edits:{set:"control anchors; { at, value, duration? }: move a control to a value",switch:"control anchors; { at, on?, duration? }: a control to its full value (open, on), or back to its rest value with on: false"}},Ww=400,qw=.2;function Kw(t,e={}){const{prop:n}=t,s=ba(n),i=Object.keys(s),o=Object.keys(n.rig.anchors??{}),r=n.rig.parts.map(m=>m.id),a=Qn(),l=ts(a),c=e.tracks?.length?new Ht({id:`${n.kind}-surface`,tracks:e.tracks}):void 0,h=Math.max(0,...(e.tracks??[]).flatMap(m=>m.keyframes.map(b=>b.time))),d=m=>{const b={...t.props};let S=0,k=0;if(c){const y=c.getStateAtTime(Math.min(m,h));for(const M of y.values.values())for(const[$,E]of M)typeof E=="number"&&($==="x"?S=E:$==="y"?k=E:$ in b&&(b[$]=E))}for(const y of i)a.keys(y)?.length&&(b[y]=a.valueAt(y,m));return{values:b,origin:{x:t.x+t.width/2+S,y:t.y+t.height+k}}},u=m=>{const{kind:b,rest:S}=De(m),k=y=>ve(n.kind,m,Mn,y);if(b==="box"){if(S)throw k("box takes no arguments");return{kind:b}}if(b==="anchor"){if(!o.includes(S))throw k(ot(`${n.kind} anchor`,S,o));return{kind:b,name:S}}if(b==="part"){if(!r.includes(S))throw k(ot(`${n.kind} part`,S,r));return{kind:b,name:S}}if(b==="control"){if(!i.includes(S))throw k(ot(`${n.kind} control`,S,i));return{kind:b,name:S}}throw k()},f=m=>{const b=(n.rig.controls[m]?.bind??[]).flatMap(k=>k.parts),S=n.rig.parts.filter(k=>k.glow?.control===m).map(k=>k.id);return new Set([...b,...S])},g=(m,b)=>{const S=u(m),{values:k,origin:y}=d(b);if(S.kind==="box")return bt(y.x-t.width/2,y.y-t.height,t.width,t.height);const M=vn(n,k,t.propScale);if(S.kind==="anchor"){const A=M.anchors[S.name].point,T=qw*t.propScale;return bt(y.x+A.x-T/2,y.y+A.y-T/2,T,T)}if(S.kind==="part")return E(new Set([S.name]),`part "${S.name}" is`);const $=f(S.name);if($.size===0)throw new Error(`${n.kind}: control "${S.name}" moves no parts of its own (it moves the whole ${n.kind}): aim at box`);return E($,`the parts control "${S.name}" moves are`);function E(A,T){const I=[...M.under,...M.over].filter(C=>A.has(C.part.id)).flatMap(C=>C.faces.flatMap(j=>j.points));if(I.length===0){const C=Number.isFinite(b)?`at ${b} ms`:"after its edits";throw new Error(`${n.kind}: ${T} turned away from the viewer ${C}; aim at an anchor (${o.map(j=>`anchor:${j}`).join(", ")||"none"}) or box`)}const v=I.map(C=>C.x),P=I.map(C=>C.y),H=Math.min(...v),O=Math.min(...P);return bt(y.x+H,y.y+O,Math.max(...v)-H,Math.max(...P)-O)}},p={kind:"prop",prop:t,about:Mn,target:t,box:bt(t.x,t.y,t.width,t.height),anchor(m,b=1/0){return g(m,b)},piece(m){throw new Error(`${n.kind}: a prop has no pieces to come loose ("${m}"); change it with edit('set' | 'switch', 'control:NAME', …)`)},edit(m,b,S){if(!(m in Mn.edits))throw es(n.kind,m,Mn);const k=Array.isArray(b)?b:[b];if(k.length===0)throw new Error(`${n.kind}.edit: ${m} takes at least one control anchor`);for(const y of k){const M=u(y);if(M.kind!=="control")throw new Error(`${n.kind}.edit: ${m} takes control anchors (control:${i.join(", control:")}), not "${y}"`);const $=s[M.name];let E;if(m==="set"){if(typeof S.value!="number"||!Number.isFinite(S.value))throw new Error(`${n.kind}.edit: set needs \`value\`, a number (${M.name}: ${$.description})`);E=S.value}else E=S.on===!1?$.default??$.min??0:$.max??1;a.tween(M.name,d(S.at).values[M.name],E,S,Ww)}return p},follow(m,b){return l.follow(m,b),p},fling(m,b){return l.fling(m,b),p},move(m,b){return l.move(m,b),p},ride(m){return m},tracks:a.tracks};return p}const Yw={body:"#e8574a",trim:"#3b3b44",glass:"#bfe3f2",tyre:"#2c2c33",hub:"#c9ccd3",light:"#fff4b8",tail:"#ff5a4f",inside:"#3b3640",seat:"#6d5d55"};function oe(t){const e={...Yw,...t.colors},n=[],{forwardMost:s,backMost:i,top:o}=Yu(t);t.body&&n.push({id:"body",shape:{type:"extrude",profile:t.body,width:t.width},fill:e.body});for(const[h,d]of(t.frame??[]).entries())n.push({id:`frame-${h}`,shape:{type:"tube",points:d.points,radius:d.radius??.035,segments:6},fill:d.color??e.body,outline:.7});for(const[h,d]of(t.windows??[]).entries())for(const u of[1,-1])n.push({id:`window-${h}-${u>0?"left":"right"}`,shape:{type:"panel",points:[[d.from,d.low],[d.to,d.low],[d.to,d.high],[d.from,d.high]],facing:u>0?"left":"right"},at:[u*(t.width/2+.01),0,0],fill:e.glass,outline:.7,seeThrough:!0,glow:t.lights?{control:"lights",color:"#ffe9a3"}:void 0});for(const h of t.extras??[])n.push(h);if(t.cabin){const h=t.cabin.width??t.width*.85;n.push({id:"cabin",shape:{type:"extrude",profile:t.cabin.profile,width:h},fill:e.glass,outline:.9,seeThrough:!0,layer:1});const d=Math.min(...t.cabin.profile.map(([,f])=>f)),u=Math.max(...t.cabin.profile.map(([,f])=>f));for(const[f,g]of(t.cabin.pillars??[]).entries())n.push({id:`pillar-${f}`,shape:{type:"box",size:[h+.02,u-d,.1]},at:[0,(d+u)/2,g],fill:e.body,outline:.8,layer:1})}const r=t.wheels[0]?.radius??.4,a=[];t.wheels.forEach((h,d)=>{const u=h.side===0?[0]:[1,-1],f=h.thickness??(h.style==="spoked"?.05:.26);for(const g of u){const p=`wheel-${d}-${g>0?"left":g<0?"right":"middle"}`;if(a.push({parts:[p],rotate:{axis:"x",degrees:r/h.radius}}),n.push({id:p,shape:{type:"cylinder",radius:h.radius,length:f,axis:"x",segments:20,spokes:h.style==="spoked"?8:0},at:[g*h.side,h.radius,h.forward],fill:h.style==="spoked"?void 0:e.tyre,ink:h.style==="spoked"?e.tyre:void 0,outline:h.style==="spoked"?1.3:1}),h.style!=="spoked")for(const m of g===0?[1,-1]:[g])n.push({id:`${p}-hub${g===0?m>0?"-left":"-right":""}`,parent:p,shape:{type:"cylinder",radius:h.radius*.55,length:.02,axis:"x",segments:14,spokes:5},at:[m*(f/2+.012),0,0],fill:e.hub,outline:.6})}});const l={wheelSpin:{description:"How far the wheels have turned (keyed exactly with the distance driven, so they never skate)",unit:"degrees",bind:a}};if(t.door){const{from:h,to:d,low:u,high:f}=t.door,g=[[h,u],[d,u],[d,f],[h,f]];for(const p of[1,-1]){const m=p>0?"left":"right";n.push({id:`doorway-${m}`,shape:{type:"panel",points:g,facing:p>0?"left":"right"},at:[p*(t.width/2+.004),0,0],fill:e.inside,outline:.5,seeThrough:!0});const b=h+(d-h)*.15,S=h+(d-h)*.55;n.push({id:`seat-back-${m}`,shape:{type:"panel",points:[[b,u+.05],[S,u+.05],[S-.08,f-.06],[b+.06,f-.04]],facing:p>0?"left":"right"},at:[p*(t.width/2+.006),0,0],fill:e.seat,outline:.4}),n.push({id:`door-${m}`,shape:{type:"panel",points:g.map(([k,y])=>[k-d,y]),facing:p>0?"left":"right"},at:[p*(t.width/2+.01),0,d],fill:e.body,outline:.7,overRider:!0})}l.door={description:"Doors open: 0 shut, 1 open (hinged at the front)",unit:"0..1",min:0,max:1,bind:[{parts:["door-left"],rotate:{axis:"y",degrees:-70}},{parts:["door-right"],rotate:{axis:"y",degrees:70}}]}}if(t.lights){const{across:h,low:d,high:u,front:f,back:g}=t.lights,p=(t.lights.size??.32)/2,m=[[-p,d],[p,d],[p,u],[-p,u]];for(const b of[1,-1])n.push({id:`headlight-${b}`,shape:{type:"panel",points:m,facing:"front"},at:[b*h,0,f],fill:e.light,outline:.6,glow:{control:"lights",color:"#ffffff"}}),n.push({id:`taillight-${b}`,shape:{type:"panel",points:m,facing:"back"},at:[b*h,0,g],fill:pi(e.tail,.62),outline:.6,glow:{control:"lights",color:e.tail}});l.lights={description:"Lights on: 0 off, 1 on",unit:"0..1",min:0,max:1}}t.antenna&&(n.push({id:"antenna",shape:{type:"tube",points:[[0,0,0],[0,.75,0]],radius:.018,segments:5},at:t.antenna,fill:e.trim,outline:.6}),n.push({id:"antenna-tip",parent:"antenna",shape:{type:"ellipsoid",radii:[.05,.05,.05],segments:8},at:[0,.77,0],fill:e.tail,outline:.6}),l.antenna={description:"Antenna bend (follow-through: it trails the motion on a spring)",unit:"degrees",bind:[{parts:["antenna"],rotate:{axis:"x",degrees:1}}]});const c={parts:n,controls:l,length:s-i,height:o,footprint:[t.width,s-i],anchors:{...t.seat?{seat:{at:t.seat}}:{},front:{at:[0,o*.45,s]},back:{at:[0,o*.45,i]},roof:{at:[0,o,0]},...t.door?{door:{at:[-t.width/2,(t.door.low+t.door.high)/2,(t.door.from+t.door.to)/2]}}:{},...t.anchors}};return{kind:t.kind??"vehicle",family:"vehicle",summary:t.summary??"A wheeled vehicle",rig:c,actions:zw(t),acting:zu,colors:{body:e.body,ink:"#26262b"},follow:t.antenna?[{control:"antenna",of:"x",per:.9,stiffness:140,damping:7,limit:35}]:void 0,wheelRadius:r,...t.wheels.length>0?{moves:{drive:{speed:t.speed??6,perMetre:{wheelSpin:180/(Math.PI*r)}}}}:{}}}function Yu(t){const e=[...(t.body??[]).map(([s])=>s),...(t.frame??[]).flatMap(s=>s.points.map(i=>i[2])),...t.wheels.flatMap(s=>[s.forward+s.radius,s.forward-s.radius])],n=[...(t.body??[]).map(([,s])=>s),...(t.cabin?.profile??[]).map(([,s])=>s),...(t.frame??[]).flatMap(s=>s.points.map(i=>i[1])),...t.wheels.map(s=>s.radius*2)];return{forwardMost:Math.max(...e),backMost:Math.min(...e),top:Math.max(...n)}}const zu={depth:{turn:0,lift:0,lights:0,pitch:1,roll:1,squash:1,lean:1,door:2},limits:{turn:.08,pitch:5,roll:4,lean:.1,squash:.06,door:.12,lift:0},eyes:[],headTurns:{},drift:[]};function Ri(t,e,n,s,i,o,r=!1){const a=t.facing()||Math.sign(s-t.x)||1,l=t.values.wheelSpin??0,c=(s-t.x)*a/t.scale;t.set("wheelSpin",e,l),t.move(e,n,s,{easing:i}),t.set("wheelSpin",n,r?l:l+c/o*(180/Math.PI),i)}const Xu=.4;function zw(t){const e=t.wheels[0]?.radius??.4,{forwardMost:n,backMost:s}=Yu(t),i=(n-s)/2,o=(a,l,c)=>{const h=a.exaggeration;let d=l;return a.facing()!==c&&(d=a.turnTo(d,c>0?"right":"left")),a.key(d+200,{pitch:4*h,squash:1-.07*h,lean:-.1*h},{act:!1,easing:"ease-out"}),Ri(a,d,d+200,a.x-c*.15*h*a.scale,"ease-out",e),a.effect({kind:"exhaust",time:d+150,x:a.x-c*i*a.scale,y:a.floor-.3*a.scale,length:900,direction:-c}),d+260},r=(a,l,c)=>{const h=a.exaggeration*(c?1.8:1);a.key(l,{pitch:-5*h,lean:-.08*h,squash:.95},{act:!1,easing:"ease-out"}),a.key(l+380,{pitch:0,lean:0,squash:1})};return{drive:{summary:"Drives to `to`: rocks back and squats, lunges forward stretched, and stops with a nose-dive that settles; wheels roll exactly the distance.",needs:["to"],uses:["speed","for"],run(a,l,c){const h=Math.sign(l.to-a.x);if(h===0)return{end:c};const d=o(a,c,h),u=a.exaggeration,f=Math.abs(l.to-a.x),g=l.for??Math.max(500,f/(l.speed??Xu));return a.effect({kind:"dust",time:d,x:a.x-h*i*a.scale,y:a.floor,length:600,direction:-h}),a.key(d+140,{pitch:-1.5*u,squash:1+.05*u,lean:.12*u},{act:!1,easing:"ease-out"}),a.key(d+Math.max(160,g-160),{pitch:0,lean:.08*u,squash:1.02},{act:!1}),Ri(a,d,d+g,l.to,"ease-in-out",e),r(a,d+g,!1),{end:d+g+380,contact:d,release:d+g}}},brake:{summary:"Drives toward `to` and slams on the brakes: the wheels lock and it skids the last stretch, nose diving, leaving skid marks.",needs:["to"],uses:["speed","for"],run(a,l,c){const h=Math.sign(l.to-a.x);if(h===0)return{end:c};const d=o(a,c,h),u=a.exaggeration,f=a.x,g=Math.abs(l.to-f),p=l.for??Math.max(600,g/(l.speed??Xu*1.2)),m=d+p*.55,b=f+(l.to-f)*.65;return a.key(d+140,{pitch:-1.5*u,squash:1+.06*u,lean:.14*u},{act:!1,easing:"ease-out"}),Ri(a,d,m,b,"ease-in",e),a.key(m+80,{pitch:-7*u,lean:-.12*u,squash:.94},{act:!1,easing:"ease-out"}),Ri(a,m,d+p,l.to,"ease-out",e,!0),a.effect({kind:"skid",time:m,x:b,toX:l.to,y:a.floor,length:p*.45+1500}),a.effect({kind:"dust",time:d+p,x:l.to+h*i*a.scale,y:a.floor,length:600,direction:h}),r(a,d+p,!0),{end:d+p+380,contact:m,release:d+p}}},bump:{summary:"Hits a bump: squashes, hops up stretched, lands squashed with dust, and springs back.",uses:["for"],run(a,l,c){const h=a.exaggeration;return a.key(c+90,{squash:1-.16*h,pitch:3*h},{act:!1,easing:"ease-out"}),a.key(c+300,{lift:.35*h,squash:1+.12*h,pitch:-3*h},{act:!1,easing:"ease-out"}),a.key(c+540,{lift:0,squash:1-.2*h,pitch:0},{act:!1,easing:"ease-in"}),a.key(c+820,{squash:1}),a.effect({kind:"dust",time:c+540,x:a.x,y:a.floor,length:500}),{end:c+820,contact:c+540}}},honk:{summary:"Honks: a stretch and squash pulse, with honk lines from the front.",run(a,l,c){const h=a.exaggeration;a.key(c+110,{squash:1+.12*h,lean:.04*h},{act:!1,easing:"ease-out"}),a.key(c+240,{squash:1-.06*h,lean:0},{act:!1}),a.key(c+520,{squash:1});const d=a.facing();return a.effect({kind:"honk",time:c+60,x:a.x+(d||1)*i*a.scale,y:a.floor-.7*a.scale,length:700,direction:d||1}),{end:c+520,contact:c+60}}},...t.door?{door:{summary:"Opens the doors (`open: true`) or shuts them (`open: false`).",needs:["open"],run(a,l,c){return a.key(c+450,{door:l.open?1:0}),{end:c+600,contact:c+450}}}}:{},...t.lights?{lights:{summary:"Switches the lights on (`on: true`) or off.",needs:["on"],run(a,l,c){return a.key(c+120,{lights:l.on?1:0},{act:!1}),{end:c+300,contact:c+120}}}}:{}}}function Uu(t={}){return oe({kind:"car",summary:"A cartoon car: drives, brakes, bumps, honks, opens its doors, lights up, and turns toward the camera.",body:[[-2,.32],[2,.32],[2.08,.52],[1.98,.82],[1.05,.95],[-1.72,.98],[-2.02,.86],[-2.08,.5]],width:1.8,cabin:{profile:[[-1.5,.94],[.92,.94],[.3,1.52],[-1.22,1.54]],width:1.56,pillars:[-.42]},wheels:[{forward:1.28,side:.8,radius:.4},{forward:-1.28,side:.8,radius:.4}],door:{from:-.4,to:.88,low:.36,high:.92},lights:{across:.58,low:.55,high:.72,front:2.05,back:-2.06},antenna:t.antenna===!1?void 0:[.5,1.5,-1.05],seat:[0,.3,-.15],colors:t.colors})}function Gu(t={}){return oe({kind:"truck",summary:"A box truck: drives, brakes, bumps, honks, opens its cab doors, lights up, turns toward the camera.",body:[[-3.2,.5],[3.1,.5],[3.15,.95],[3,1.85],[2.3,2.25],[1.2,2.25],[1.2,1],[-3.2,1]],width:2,cabin:{profile:[[1.6,1.35],[2.95,1.35],[2.85,1.85],[2.3,2.15],[1.6,2.15]],width:2.04},extras:[{id:"cargo",shape:{type:"box",size:[2.1,1.75,4.2]},at:[0,1.9,-1.05],fill:t.cargo??"#f1f1ee"}],wheels:[{forward:2.2,side:.85,radius:.48,thickness:.32},{forward:-1.4,side:.85,radius:.48,thickness:.32},{forward:-2.45,side:.85,radius:.48,thickness:.32}],door:{from:1.4,to:2.25,low:.6,high:1.9},lights:{across:.7,low:.62,high:.82,front:3.13,back:-3.22,size:.28},seat:[0,1.15,1.9],colors:{body:"#2f6fb7",...t.colors}})}function Vu(t={}){return oe({kind:"bus",summary:"A bus: drives, brakes, bumps, honks, opens its front doors, lights its windows, turns toward the camera.",body:[[-4.5,.45],[4.5,.45],[4.6,.9],[4.55,2.9],[4.3,3],[-4.4,3],[-4.55,2.75],[-4.55,.6]],width:2.4,windows:Array.from({length:6},(e,n)=>({from:-4+n*1.18,to:-4+n*1.18+1,low:1.55,high:2.6})),extras:[{id:"windscreen",shape:{type:"panel",points:[[-1.05,1.35],[1.05,1.35],[1.05,2.75],[-1.05,2.75]],facing:"front"},at:[0,0,4.58],fill:"#bfe3f2",outline:.8,seeThrough:!0}],wheels:[{forward:3,side:1,radius:.5,thickness:.34},{forward:-2.8,side:1,radius:.5,thickness:.34}],door:{from:3.2,to:4.2,low:.5,high:2.6},lights:{across:.85,low:.65,high:.85,front:4.6,back:-4.56,size:.3},seat:[0,1.2,3.6],colors:{body:"#f2c230",...t.colors}})}function Ju(t={}){return oe({kind:"tractor",summary:"A tractor: big rear wheels and small front ones turning at their own rates; drives, brakes, bumps, honks.",body:[[-.5,.75],[2,.75],[2.12,1.25],[1.9,1.52],[-.5,1.52]],width:1,cabin:{profile:[[-1.35,1],[-.25,1],[-.25,2.55],[-1.35,2.55]],width:1.35},extras:[{id:"roof",shape:{type:"box",size:[1.55,.1,1.35]},at:[0,2.62,-.8],fill:"#3f9b47"},{id:"exhaust",shape:{type:"tube",points:[[.28,1.5,1.25],[.28,2.35,1.25]],radius:.06,segments:6},fill:"#3b3b44",outline:.7}],wheels:[{forward:-.85,side:.85,radius:.78,thickness:.45},{forward:1.55,side:.7,radius:.42,thickness:.26}],lights:{across:.3,low:1,high:1.18,front:2.1,back:-.52,size:.2},seat:[0,1.25,-.8],colors:{body:"#3f9b47",hub:"#e9c64a",...t.colors}})}function Zu(t={}){const e=t.colors?.body??"#a8743f";return oe({kind:"cart",summary:"A wooden cart on spoked wheels with shafts: rolls when pulled (drive), bumps, tips.",body:[[-1.25,.78],[1.25,.78],[1.35,1.18],[-1.35,1.18]],width:1.4,frame:[{points:[[.5,.9,1],[.5,.95,2.7]],radius:.05,color:e},{points:[[-.5,.9,1],[-.5,.95,2.7]],radius:.05,color:e}],wheels:[{forward:0,side:.82,radius:.66,style:"spoked"}],seat:[0,1.2,0],anchors:{shafts:{at:[0,.95,2.7]}},colors:{body:e,tyre:"#5a3a1f",...t.colors}})}function Qu(t={}){return oe({kind:"train carriage",summary:"A railway carriage: rolls along (drive), brakes, lights its windows, turns toward the camera.",body:[[-4,.72],[4,.72],[4,2.8],[3.6,3.12],[-3.6,3.12],[-4,2.8]],width:2.6,windows:Array.from({length:5},(e,n)=>({from:-3.3+n*1.4,to:-3.3+n*1.4+1,low:1.7,high:2.5})),wheels:[{forward:3,side:1,radius:.36,thickness:.16},{forward:2.2,side:1,radius:.36,thickness:.16},{forward:-2.2,side:1,radius:.36,thickness:.16},{forward:-3,side:1,radius:.36,thickness:.16}],lights:{across:.9,low:1,high:1.2,front:4.01,back:-4.01,size:.22},seat:[0,1,1.5],colors:{body:"#2f7d6d",...t.colors}})}function tf(t={}){const e=t.colors?.body??"#e0473b",n=[0,.32,-.05],s=[0,.86,-.22],i=[0,.9,.42],o=[0,.34,.56],r=[0,.34,-.56];return oe({kind:"bike",summary:"A bicycle: rides (drive) with its wire wheels turning, brakes, bumps, rings its bell (honk).",width:.5,frame:[{points:[r,n]},{points:[n,s]},{points:[s,r]},{points:[s,i]},{points:[n,i]},{points:[i,o]},{points:[[.24,.98,.44],[-.24,.98,.44]],radius:.025,color:"#3b3b44"},{points:[i,[0,.98,.44]],radius:.025,color:"#3b3b44"}],extras:[{id:"saddle",shape:{type:"ellipsoid",radii:[.08,.035,.15],segments:10},at:[0,.89,-.22],fill:"#3b3b44",outline:.7}],wheels:[{forward:.56,side:0,radius:.34,style:"spoked"},{forward:-.56,side:0,radius:.34,style:"spoked"}],seat:[0,.9,-.22],colors:{body:e,tyre:"#2c2c33",...t.colors}})}function ef(t={}){return oe({kind:"motorbike",summary:"A motorbike: rides (drive) with a lunge, brakes into a skid, bumps, honks, lights up.",body:[[-.62,.62],[.42,.62],[.55,.95],[.3,1.02],[-.1,.92],[-.8,.88],[-.86,.72]],width:.4,frame:[{points:[[0,.33,.78],[0,1.05,.5]],radius:.04,color:"#8c8f98"},{points:[[.3,1.08,.48],[-.3,1.08,.48]],radius:.025,color:"#3b3b44"},{points:[[.12,.42,-.2],[.12,.5,-.95]],radius:.04,color:"#8c8f98"}],extras:[{id:"engine",shape:{type:"box",size:[.38,.34,.5]},at:[0,.45,.05],fill:"#5b5f6a",outline:.8}],wheels:[{forward:.78,side:0,radius:.33,thickness:.14},{forward:-.72,side:0,radius:.33,thickness:.14}],lights:{across:0,low:.9,high:1.04,front:.62,back:-.87,size:.14},seat:[0,.92,-.3],colors:{body:"#1f1f26",hub:"#c9ccd3",...t.colors}})}function nf(t={}){const e=t.height??2.4,n=t.trunkRadius??.16,s=t.canopy?.radius??1.1,i=t.canopy?.shape==="tall",o={trunk:"#8a5a3b",leaves:"#5cae5a",...t.colors},r=$e(t.canopy?.seed??7),a=[{id:"trunk",shape:{type:"tube",points:[[0,0,0],[.06,e*.5,0],[-.02,e,0]],radius:n,segments:8},fill:o.trunk},{id:"branch",parent:"trunk",shape:{type:"tube",points:[[0,0,0],[.45,.4,.1]],radius:n*.45,segments:6},at:[.04,e*.62,0],fill:o.trunk},{id:"canopy",parent:"trunk",shape:{type:"ellipsoid",radii:[s,s*(i?1.35:.88),s],segments:14},at:[-.02,e+s*.55,0],fill:o.leaves}],l=t.canopy?.lobes??7;for(let h=0;h<l;h++){const d=Math.PI*2*h/l+r.next()*.6,u=(r.next()-.25)*s*(i?1.1:.7),f=s*(.48+r.next()*.22),g=[Math.cos(d)*s*.78,u,Math.sin(d)*s*.6];a.push({id:`lobe-${h}`,parent:"canopy",shape:{type:"ellipsoid",radii:[f,f*.86,f],segments:12},at:g,fill:o.leaves})}const c={parts:a,controls:{sway:{description:"The whole tree bending in the wind, about its base",unit:"degrees",bind:[{parts:["trunk"],rotate:{axis:"z",degrees:1}}]},canopySway:{description:"The canopy bending further than the trunk (it trails the sway)",unit:"degrees",bind:[{parts:["canopy"],rotate:{axis:"z",degrees:1,pivot:[0,-s*.8,0]}}]}},length:s*2.2,height:e+s*2,footprint:[s*1.6,s*1.6],anchors:{canopy:{part:"canopy",at:[0,0,0]},top:{part:"canopy",at:[0,s*.9,0]},base:{at:[0,0,0]},branch:{part:"branch",at:[.45,.4,.1]}}};return{kind:t.kind??"tree",family:"plant",summary:t.summary??"A tree: sways in the wind with its canopy trailing, shakes, sheds leaves, pops up.",rig:c,actions:Xw(),acting:sf,colors:{body:o.leaves}}}const sf={depth:{sway:1,canopySway:2,size:0,squash:1},limits:{sway:2,canopySway:3,squash:.08},eyes:[],headTurns:{},drift:[]};function Xw(){const t=(e,n,s,i)=>{const o=e.anchor("canopy");e.effect({kind:"leaves",time:n,x:o.x,y:o.y,length:s,direction:i,toY:e.floor})};return{sway:{summary:"Sways in gusts of `wind` (0..1, default 0.5) for `for` ms (default 3000); the canopy trails the trunk, and a strong wind sheds leaves.",uses:["wind","for"],run(e,n,s){const i=n.wind??.5,o=n.for??3e3,r=e.exaggeration,a=260;let l=0;for(let c=a;c<o;c+=a){const h=.55+.45*Math.sin(c/o*Math.PI*2.3),d=Math.sin(c/170)*.35,u=-i*9*r*(h+d*i);e.key(s+c,{sway:u,canopySway:l*1.3},{act:!1,easing:"ease-in-out"}),l=u}if(e.key(s+o,{sway:0,canopySway:0}),i>.45)for(let c=0;c<o;c+=700)t(e,s+c,2200,1);return{end:s+o}}},shake:{summary:"Shakes (something hit it): a quick wobble that dies away, shedding leaves.",uses:["for"],run(e,n,s){const i=n.for??900,o=e.exaggeration,r=6;for(let a=1;a<=r;a++){const l=1-a/(r+1),c=a%2===0?1:-1;e.key(s+i*a/(r+1),{sway:c*5*o*l,canopySway:-c*6*o*l},{act:!1,easing:"ease-in-out"})}return e.key(s+i,{sway:0,canopySway:0}),t(e,s+60,1800,1),t(e,s+260,1800,-1),{end:s+i,contact:s}}},shedLeaves:{summary:"Leaves fall from the canopy for `for` ms (default 2000).",uses:["for"],run(e,n,s){const i=n.for??2e3;for(let o=0;o<i;o+=500)t(e,s+o,2e3,o%1e3===0?1:-1);return{end:s+i}}}}}function of(t={}){const e=t.width??4,n=t.depth??3.2,s=t.wallHeight??2.5,i=t.roofHeight??1.5,o=t.overhang??.25,r={walls:"#f1d9a8",roof:"#b8433a",door:"#7a4b2a",doorway:"#3a2a22",glass:"#bfe3f2",lit:"#ffd66b",chimney:"#9b5a45",...t.colors},a=n/2+.01,l=t.door?.width??.9,c=t.door?.height??1.9,h=t.door?.at??0,d=t.windows??[{at:-1.25,low:1,width:.8,height:.8},{at:1.25,low:1,width:.8,height:.8}],u=[{id:"walls",shape:{type:"box",size:[e,s,n]},at:[0,s/2,0],fill:r.walls},{id:"roof",shape:{type:"extrude",profile:[[-n/2-o,s],[n/2+o,s],[0,s+i]],width:e+o*2},fill:r.roof,layer:1},{id:"doorway",shape:{type:"panel",points:[[0,0],[l,0],[l,c],[0,c]],facing:"front"},at:[h-l/2,0,a-.005],fill:r.doorway,outline:.6,seeThrough:!0},{id:"door",shape:{type:"panel",points:[[0,0],[l,0],[l,c],[0,c]],facing:"front"},at:[h-l/2,0,a+.005],fill:r.door,outline:.8,overRider:!0}];d.forEach((p,m)=>{u.push({id:`window-${m}`,shape:{type:"panel",points:[[-p.width/2,p.low],[p.width/2,p.low],[p.width/2,p.low+p.height],[-p.width/2,p.low+p.height]],facing:"front"},at:[p.at,0,a+.01],fill:r.glass,outline:.8,glow:{control:"lights",color:r.lit}})});for(const p of[1,-1])u.push({id:`side-window-${p>0?"left":"right"}`,shape:{type:"panel",points:[[-.4,1],[.4,1],[.4,1.8],[-.4,1.8]],facing:p>0?"left":"right"},at:[p*(e/2+.01),0,0],fill:r.glass,outline:.8,glow:{control:"lights",color:r.lit}});const f=t.chimney===!1?void 0:{at:t.chimney?.at??e*.28,back:t.chimney?.back??-n*.18};if(f){const p=s+i*(1-Math.abs(f.back)/(n/2+o)),m=s+i+.45;u.push({id:"chimney",shape:{type:"box",size:[.42,m-p+.3,.42]},at:[f.at,(m+p-.3)/2,f.back],fill:r.chimney,layer:1})}const g={parts:u,controls:{door:{description:"The front door open: 0 shut, 1 open",unit:"0..1",min:0,max:1,bind:[{parts:["door"],rotate:{axis:"y",degrees:-80}}]},lights:{description:"The windows lit: 0 dark, 1 lit",unit:"0..1",min:0,max:1}},length:n+o*2,height:s+i+.6,footprint:[e+.6,n+.6],anchors:{door:{at:[h,c/2,a]},doorstep:{at:[h,0,a+.4]},ridge:{at:[0,s+i,0]},...f?{chimney:{at:[f.at,s+i+.5,f.back]}}:{}}};return{kind:t.kind??"house",family:"building",summary:t.summary??"A house: opens its door, lights its windows, puffs chimney smoke, shakes, pops up.",rig:g,actions:Uw(!!f),acting:rf,colors:{body:r.walls}}}const rf={depth:{door:1,lights:0,roll:1,squash:1,size:0},limits:{door:.1,roll:1.5,squash:.05},eyes:[],headTurns:{},drift:[]};function Uw(t){return{door:{summary:"Opens the front door (`open: true`) or shuts it (`open: false`).",needs:["open"],run(e,n,s){return e.key(s+500,{door:n.open?1:0}),{end:s+650,contact:s+500}}},lights:{summary:"Lights the windows (`on: true`) or puts them out.",needs:["on"],run(e,n,s){return e.key(s+150,{lights:n.on?1:0},{act:!1}),{end:s+300,contact:s+150}}},shake:{summary:"Shakes, as when a door slams or something lands on it: a squash and a wobble that dies away, with dust.",uses:["for"],run(e,n,s){const i=n.for??700,o=e.exaggeration;e.key(s+80,{squash:1-.06*o},{act:!1,easing:"ease-out"});for(let r=1;r<=5;r++){const a=1-r/6;e.key(s+80+i*r/6,{roll:(r%2===0?1:-1)*2.2*o*a,squash:1+.02*a},{act:!1,easing:"ease-in-out"})}return e.key(s+i+80,{roll:0,squash:1}),e.effect({kind:"dust",time:s+80,x:e.x,y:e.floor,length:600}),{end:s+i+80,contact:s+80}}},...t?{smoke:{summary:"Starts smoke puffing from the chimney for `for` ms (default 3000), drifting with the wind; the next beat starts at once (the smoke carries on).",uses:["for","wind"],run(e,n,s){const i=n.for??3e3,o=e.anchor("chimney");return e.effect({kind:"smoke",time:s,x:o.x,y:o.y,length:i+1500,direction:(n.wind??.4)>=0?1:-1}),{end:s+50,release:s+i}}}}:{}}}function af(t={}){const e={body:"#3f86c8",glass:"#cfeaf5",trim:"#2c2c33",rotor:"#3b3b44",...t.colors},n=2.15,i={parts:[{id:"cabin",shape:{type:"extrude",profile:[[-1.2,.6],[.9,.55],[1.6,.85],[1.65,1.25],[1.2,1.75],[-.6,1.85],[-1.3,1.45]],width:1.5},fill:e.body},{id:"window",shape:{type:"extrude",profile:[[.75,1],[1.6,.95],[1.6,1.3],[1.15,1.72],[.6,1.72]],width:1.54},fill:e.glass,outline:.8},{id:"boom",shape:{type:"tube",points:[[0,1.4,-1.2],[0,1.55,-3.4]],radius:.16,segments:8},fill:e.body},{id:"fin",shape:{type:"extrude",profile:[[-3.55,1.45],[-3.2,1.5],[-3.35,2.25],[-3.6,2.25]],width:.12},fill:e.body},{id:"mast",shape:{type:"tube",points:[[0,1.82,.1],[0,n,.1]],radius:.07,segments:6},fill:e.trim},{id:"rotor-disc",shape:{type:"cylinder",radius:2.4,length:.01,axis:"y",segments:28},at:[0,n+.02,.1],fill:"#c9d4dd",outline:.4,fade:{control:"blur",from:0,to:.45}},{id:"blades",shape:{type:"box",size:[.16,.03,4.8]},at:[0,n+.05,.1],fill:e.rotor,outline:.7,fade:{control:"blur",from:1,to:.3}},{id:"tail-rotor",shape:{type:"box",size:[.04,.9,.12]},at:[.12,1.85,-3.45],fill:e.rotor,outline:.6},{id:"skid-left",shape:{type:"tube",points:[[0,.08,-1.1],[0,.08,1.2],[0,.22,1.45]],radius:.05,segments:6},at:[.7,0,0],fill:e.trim},{id:"skid-right",shape:{type:"tube",points:[[0,.08,-1.1],[0,.08,1.2],[0,.22,1.45]],radius:.05,segments:6},at:[-.7,0,0],fill:e.trim},{id:"strut-left",shape:{type:"tube",points:[[.7,.08,.6],[.55,.62,.5]],radius:.04,segments:5},fill:e.trim},{id:"strut-right",shape:{type:"tube",points:[[-.7,.08,.6],[-.55,.62,.5]],radius:.04,segments:5},fill:e.trim}],controls:{rotor:{description:"How far the rotors have turned (keyed exactly, not acted; the blades blur into a disc when they spin fast)",unit:"degrees",bind:[{parts:["blades"],rotate:{axis:"y",degrees:1}},{parts:["tail-rotor"],rotate:{axis:"x",degrees:3,pivot:[0,0,0]}}]},blur:{description:"How blurred the main rotor is: 0 still blades, 1 a spinning disc",unit:"0..1",min:0,max:1}},length:5.2,height:2.4,footprint:[1.8,3.4],anchors:{seat:{at:[0,.75,.7]},door:{at:[-.76,1,.2]},rotor:{at:[0,n,.1]},skids:{at:[0,0,.2]},hook:{at:[0,.4,0]}}};return{kind:t.kind??"helicopter",family:"aircraft",summary:t.summary??"A cartoon helicopter: spools up and takes off, flies nose-down banking into its moves, hovers with a bob, and lands with a squash.",rig:i,actions:Gw(),acting:wa,colors:{body:e.body,ink:"#26262b"},moves:{fly:{speed:15,flies:!0,hold:{blur:1},perSecond:{rotor:Te*1e3}}}}}const wa={depth:{turn:0,lift:0,blur:0,pitch:1,roll:1,squash:1,lean:1,size:0},limits:{turn:.08,pitch:6,roll:6,squash:.06,lift:.15},eyes:[],headTurns:{},drift:[]},Te=2.6;function Gw(){const t=(n,s,i,o,r)=>{const a=n.values.rotor??0;n.set("rotor",s,a);const l=r?o*(i-s)*.5:o*(i-s);n.set("rotor",i,a+l,r)},e=n=>n.values.lift>.05;return{takeOff:{summary:"Spools the rotor up (the skids squash as it bites), then lifts off nose-down to `height` metres (default 3).",uses:["height"],run(n,s,i){const o=n.exaggeration,r=s.height??3;t(n,i,i+900,Te,"ease-in"),n.key(i+900,{blur:1},{act:!1,easing:"ease-in"}),n.key(i+700,{squash:1-.08*o},{act:!1,easing:"ease-in"});const a=i+1e3;return n.key(a+150,{squash:1+.06*o,lift:.3},{act:!1,easing:"ease-out"}),n.key(a+1300,{squash:1,lift:r,pitch:-4*o},{act:!1,easing:"ease-in-out"}),n.key(a+1700,{pitch:0}),t(n,i+900,a+1700,Te),n.effect({kind:"dust",time:a,x:n.x,y:n.floor,length:900}),{end:a+1700,contact:a}}},fly:{summary:"Flies to `to` (and to `height`, if given): nose down and banked into the move, nose up and leveling as it stops.",needs:["to"],uses:["height","speed","for"],run(n,s,i){const o=n.exaggeration,r=Math.sign(s.to-n.x);let a=i;r!==0&&n.facing()!==r&&(a=n.turnTo(a,r>0?"right":"left"));const l=Math.abs(s.to-n.x),c=s.for??Math.max(700,l/(s.speed??.3)),h=s.height??n.values.lift;return n.key(a+300,{pitch:-9*o,roll:6*o},{act:!1,easing:"ease-out"}),n.key(a+c-250,{pitch:-4*o,roll:3*o,lift:h},{act:!1}),n.key(a+c,{pitch:7*o,roll:0},{act:!1,easing:"ease-out"}),n.key(a+c+450,{pitch:0}),n.move(a,a+c,s.to,{easing:"ease-in-out"}),t(n,i,a+c+450,Te),{end:a+c+450,contact:a,release:a+c}}},hover:{summary:"Hovers in place for `for` ms (default 2000), bobbing gently.",uses:["for"],run(n,s,i){const o=s.for??2e3,r=n.values.lift,a=n.exaggeration;for(let l=350,c=0;l<o;l+=350,c++)n.key(i+l,{lift:r+(c%2===0?.12:-.06)*a,roll:(c%2===0?1.5:-1.5)*a},{act:!1,easing:"ease-in-out"});return n.key(i+o,{lift:r,roll:0},{act:!1,easing:"ease-in-out"}),(e(n)||r>0)&&t(n,i,i+o,Te),{end:i+o}}},land:{summary:"Settles down onto its skids: a flare, a squash on touchdown with dust, and the rotor spools down.",run(n,s,i){const o=n.exaggeration,r=i+Math.max(900,n.values.lift*450);return n.key(i+400,{pitch:3*o},{act:!1,easing:"ease-out"}),n.key(r,{lift:0,pitch:0,squash:1-.14*o},{act:!1,easing:"ease-in"}),n.key(r+280,{squash:1}),t(n,i,r,Te),t(n,r,r+1600,Te,"ease-out"),n.key(r+1600,{blur:0},{act:!1,easing:"ease-out"}),n.effect({kind:"dust",time:r,x:n.x,y:n.floor,length:800}),{end:r+1600,contact:r}}}}}function lf(t={}){const e={body:"#e9e4d8",wings:"#d9483b",glass:"#cfeaf5",trim:"#2c2c33",...t.colors},n=3.15,i={parts:[{id:"fuselage",shape:{type:"extrude",profile:[[-3.7,1.55],[-2.6,1.05],[2.4,.85],[3,1],[3.1,1.4],[2.7,1.75],[1.4,1.9],[-2.9,1.85]],width:1},fill:e.body},{id:"canopy",shape:{type:"extrude",profile:[[.4,1.85],[1.6,1.85],[1.1,2.3],[.5,2.3]],width:.7},fill:e.glass,outline:.8},{id:"wing-left",shape:{type:"box",size:[3.6,.1,1.35]},at:[2.05,1.15,.55],fill:e.wings},{id:"wing-right",shape:{type:"box",size:[3.6,.1,1.35]},at:[-2.05,1.15,.55],fill:e.wings},{id:"tailplane-left",shape:{type:"box",size:[1.1,.07,.65]},at:[.6,1.7,-3.35],fill:e.wings},{id:"tailplane-right",shape:{type:"box",size:[1.1,.07,.65]},at:[-.6,1.7,-3.35],fill:e.wings},{id:"fin",shape:{type:"extrude",profile:[[-3.75,1.75],[-3,1.82],[-3.45,2.75],[-3.8,2.75]],width:.1},fill:e.wings},{id:"gear-left",shape:{type:"tube",points:[[.55,.95,1.2],[.75,.28,1.3]],radius:.04,segments:5},fill:e.trim},{id:"gear-right",shape:{type:"tube",points:[[-.55,.95,1.2],[-.75,.28,1.3]],radius:.04,segments:5},fill:e.trim},{id:"wheel-left",shape:{type:"cylinder",radius:.26,length:.14,axis:"x",segments:14},at:[.78,.26,1.3],fill:e.trim},{id:"wheel-right",shape:{type:"cylinder",radius:.26,length:.14,axis:"x",segments:14},at:[-.78,.26,1.3],fill:e.trim},{id:"tail-wheel",shape:{type:"cylinder",radius:.12,length:.08,axis:"x",segments:10},at:[0,.12,-3],fill:e.trim},{id:"tail-strut",shape:{type:"tube",points:[[0,.12,-3],[0,1.2,-2.9]],radius:.03,segments:5},fill:e.trim},{id:"spinner",shape:{type:"ellipsoid",radii:[.18,.18,.22],segments:10},at:[0,1.22,n],fill:e.wings,outline:.7},{id:"prop-disc",shape:{type:"cylinder",radius:.95,length:.01,axis:"z",segments:24},at:[0,1.22,n+.08],fill:"#c9d4dd",outline:.4,fade:{control:"blur",from:0,to:.45}},{id:"propeller",shape:{type:"box",size:[.12,1.85,.04]},at:[0,1.22,n+.1],fill:e.trim,outline:.6,fade:{control:"blur",from:1,to:.3}}],controls:{rotor:{description:"How far the propeller has turned (keyed exactly; it blurs into a disc at speed)",unit:"degrees",bind:[{parts:["propeller"],rotate:{axis:"z",degrees:1}}]},blur:{description:"How blurred the propeller is: 0 still, 1 a spinning disc",unit:"0..1",min:0,max:1}},length:7,height:2.8,footprint:[7.2,6.5],anchors:{seat:{at:[0,1.55,1]},nose:{at:[0,1.22,n+.2]},tail:{at:[0,1.6,-3.7]},wingtip:{at:[3.6,1.15,.55]}}};return{kind:t.kind??"airplane",family:"aircraft",summary:t.summary??"A propeller plane: takes off from a run, flies banked, loops the loop, and lands with a flare and a squash.",rig:i,actions:Jw(),acting:wa,colors:{body:e.body,ink:"#26262b"},moves:{fly:{speed:30,flies:!0,hold:{blur:1},perSecond:{rotor:Te*1e3}}}}}const Vw=3.2;function Jw(){const t=(n,s,i,o)=>{const r=n.values.rotor??0;n.set("rotor",s,r),n.set("rotor",i,r+Vw*(i-s)*(o?.5:1),o)},e=(n,s,i)=>{const o=Math.sign(i-n.x);return o!==0&&n.facing()!==o?n.turnTo(s,o>0?"right":"left"):s};return{takeOff:{summary:"Spins the propeller up, runs along the ground toward `to`, lifts its nose and climbs to `height` metres (default 4).",needs:["to"],uses:["height","for"],run(n,s,i){const o=n.exaggeration,r=e(n,i,s.to);t(n,r,r+700,"ease-in"),n.key(r+700,{blur:1},{act:!1,easing:"ease-in"});const a=s.for??2600,l=n.x,c=r+700+a*.55,h=l+(s.to-l)*.45;return n.move(r+700,c,h,{easing:"ease-in"}),n.key(c,{pitch:8*o,squash:1+.04*o},{act:!1,easing:"ease-out"}),n.key(r+700+a,{lift:s.height??4,pitch:10*o,squash:1},{act:!1,easing:"ease-in-out"}),n.move(c,r+700+a,s.to),n.key(r+700+a+500,{pitch:0}),t(n,r+700,r+700+a+500),n.effect({kind:"dust",time:c,x:h,y:n.floor,length:700}),{end:r+700+a+500,contact:c}}},fly:{summary:"Flies to `to` (and `height`), banking into the move and leveling out.",needs:["to"],uses:["height","speed","for"],run(n,s,i){const o=n.exaggeration,r=e(n,i,s.to),a=s.for??Math.max(800,Math.abs(s.to-n.x)/(s.speed??.45)),l=s.height??n.values.lift;return n.key(r+350,{roll:10*o,pitch:l>n.values.lift?6*o:-3*o},{act:!1,easing:"ease-out"}),n.key(r+a-300,{roll:4*o,lift:l},{act:!1}),n.key(r+a,{roll:0,pitch:0}),n.move(r,r+a,s.to,{easing:"ease-in-out"}),t(n,i,r+a),{end:r+a,contact:r,release:r+a}}},loop:{summary:"Loops the loop: pulls up and over in a full circle (`for` ms, default 2400), carrying on the way it was going.",uses:["for"],run(n,s,i){const o=s.for??2400,r=2.2*n.exaggeration,a=n.facing()||1,l=16,c=n.x,h=n.values.lift,d=n.values.pitch;for(let u=1;u<=l;u++){const f=Math.PI*2*u/l,g=i+o*u/l;n.key(g,{lift:h+r*(1-Math.cos(f)),pitch:d+360*u/l},{act:!1}),n.move(i+o*(u-1)/l,g,c+a*(r*Math.sin(f)+u/l*r*1.2)*n.scale)}return n.key(i+o+1,{pitch:d},{act:!1}),t(n,i,i+o),{end:i+o+1}}},land:{summary:"Comes down toward `to`: descends, flares nose-up, touches down with a squash and dust, rolls to a stop and the propeller spools down.",needs:["to"],uses:["for"],run(n,s,i){const o=n.exaggeration,r=e(n,i,s.to),a=n.x,l=s.for??2200,c=r+l,h=a+(s.to-a)*.7;return n.key(r+l*.4,{pitch:-4*o},{act:!1,easing:"ease-out"}),n.key(c-250,{pitch:6*o,lift:.15},{act:!1,easing:"ease-in-out"}),n.key(c,{lift:0,pitch:0,squash:1-.12*o},{act:!1,easing:"ease-in"}),n.key(c+260,{squash:1}),n.move(r,c,h),n.move(c,c+1200,s.to,{easing:"ease-out"}),t(n,i,c),t(n,c,c+1600,"ease-out"),n.key(c+1600,{blur:0},{act:!1,easing:"ease-out"}),n.effect({kind:"dust",time:c,x:h,y:n.floor,length:700}),{end:c+1600,contact:c}}}}}const Sn=["walk","trot","canter","gallop"],Zw=Sn,cf=["fl","fr","hl","hr"],Li={walk:{offsets:{hl:0,fl:.25,hr:.5,fr:.75},swing:16,lift:45,bob:.02,rock:0,cycle:1100},trot:{offsets:{fl:0,hr:0,fr:.5,hl:.5},swing:22,lift:75,bob:.05,rock:0,cycle:640},canter:{offsets:{hr:0,hl:.33,fr:.33,fl:.66},swing:30,lift:70,bob:.08,rock:5,cycle:560},gallop:{offsets:{hr:0,hl:.1,fr:.5,fl:.6},swing:40,lift:80,bob:.1,rock:7,cycle:460}},qe=Math.PI/180;function Ni(t,e){return 4*t*Math.sin(Li[e].swing*qe)}function us(t){const{legs:e,colors:n}=t,s=e.upper+e.lower+e.foot,i=s+t.body.rise,o=(d,u)=>[u*d[0],d[1],d[2]],r=[{id:"body",shape:{type:"ellipsoid",radii:t.body.radii,segments:18},at:[0,i,0],fill:n.coat},{id:"neck",shape:{type:"tube",points:t.neck.points,radius:t.neck.points.map((d,u,f)=>t.neck.radius*(1.25-.4*u/Math.max(1,f.length-1))),segments:12},at:t.neck.at,fill:n.coat},{id:"head",parent:"neck",shape:{type:"ellipsoid",radii:t.head.radii,segments:14},at:t.head.at,rotate:t.head.rotate,fill:n.coat},...tk(t,n,i)];t.mane&&r.push({id:"mane",parent:"neck",shape:{type:"tube",points:t.mane.points,radius:t.mane.radius,segments:6},fill:n.dark,outline:.7}),t.muzzle&&r.push({id:"muzzle",parent:"head",shape:{type:"ellipsoid",radii:t.muzzle.radii,segments:10},at:t.muzzle.at,fill:n.muzzle,outline:.8});for(const d of[1,-1]){const u=d>0?"left":"right",f=t.ears.rotate?o(t.ears.rotate,1).map((g,p)=>p===2?d*g:g):void 0;r.push({id:`ear-${u}`,parent:"head",shape:{type:"ellipsoid",radii:t.ears.radii,segments:8},at:o(t.ears.at,d),rotate:f,fill:n.coat,outline:.7},{id:`eye-${u}`,parent:"head",shape:{type:"ellipsoid",radii:[t.eyes.size*.8,t.eyes.size,t.eyes.size*.9],segments:8},at:o(t.eyes.at,d),fill:"#1d1d22",outline:.4})}r.push(...t.extras?.(n)??[]);const a={walk:{description:"Phase of the stride, in full cycles (keyed in step with the distance covered)",unit:"cycles"},walking:{description:"How much of the gait is applied: 0 standing, 1 moving",unit:"0..1",min:0,max:1},gait:{description:`Which gait: ${t.gaits.map(d=>`${Sn.indexOf(d)} ${d}`).join(", ")}`,unit:"index",min:0,max:3},neck:{description:"Neck bent down (+, eating, sniffing) or up (−, alert)",unit:"degrees",bind:[{parts:["neck"],rotate:{axis:"x",degrees:1}}]},tail:{description:"Tail flicked up and back (+), curling along its length, on a spring behind the motion",unit:"degrees",bind:[{parts:Ut,rotate:{axis:"x",degrees:1/Ut.length}}]},wag:{description:"Tail swung side to side, curling",unit:"degrees",bind:[{parts:Ut,rotate:{axis:"y",degrees:1/Ut.length}}]}};for(const d of cf){const u=d[0]==="f",f=d[1]==="l"?1:-1,g=u?e.thickness[0]:e.thickness[1];r.push({id:`${d}-upper`,shape:{type:"tube",points:[[0,e.upper*.2,0],[0,-e.upper*.5,0],[0,-e.upper,0]],radius:[g,g*.85,e.lowerThickness*1.15],segments:10},at:[f*e.across,s,u?e.front:e.hind],fill:n.coat},{id:`${d}-knee`,parent:`${d}-upper`,shape:{type:"ellipsoid",radii:Array(3).fill(e.lowerThickness*1.08),segments:10},at:[0,-e.upper,0],fill:n.coat,solidOnly:!0},{id:`${d}-lower`,parent:`${d}-upper`,shape:{type:"tube",points:[[0,0,0],[0,-e.lower,0]],radius:[e.lowerThickness*1.1,e.lowerThickness*.85],segments:10},at:[0,-e.upper,0],fill:n.coat},{id:`${d}-foot`,parent:`${d}-lower`,shape:{type:"ellipsoid",radii:[e.footSize[0]/2,e.foot/2+.004,e.footSize[1]/2],segments:12},at:[0,-e.lower-e.foot/2,e.footSize[1]*.12],fill:n.foot,outline:.8});const p=`${u?"Front":"Hind"} ${f>0?"left":"right"} leg`;a[`${d}.swing`]={description:`${p}: forward (+) or back (−) from the hip`,unit:"degrees",bind:[{parts:[`${d}-upper`],rotate:{axis:"x",degrees:-1}}]},a[`${d}.knee`]={description:`${p}: knee (hock) folded`,unit:"degrees",bind:[{parts:[`${d}-lower`],rotate:{axis:"x",degrees:u?1:-1}}]},a[`${d}.ankle`]={description:`${p}: foot turned at the ankle (+ toe forward)`,unit:"degrees",bind:[{parts:[`${d}-foot`],rotate:{axis:"x",degrees:-1,pivot:[0,e.foot/2,-e.footSize[1]*.12]}}]}}const l=t.neck.points[t.neck.points.length-1],c={parts:r,controls:a,length:t.body.radii[2]*2+Math.max(0,t.neck.at[2]+l[2]+t.head.radii[2]-t.body.radii[2])+.3,height:t.neck.at[1]+l[1]+t.head.radii[1]*2,footprint:[e.across*2+t.body.radii[0],(e.front-e.hind)*1.4],anchors:{back:{at:[0,i+t.body.radii[1],-t.body.radii[2]*.05]},head:{part:"head",at:[0,0,0]},mouth:{part:t.muzzle?"muzzle":"head",at:t.muzzle?[0,0,t.muzzle.radii[2]]:[0,0,t.head.radii[2]]},front:{at:[0,i,t.body.radii[2]]},...t.anchors},derive:d=>ek(d,t,s)},h={legLength:s,upper:e.upper,lower:e.lower,foot:e.foot,tailHangs:t.tail.points[t.tail.points.length-1][1]<0,front:e.front,hind:e.hind,call(d,u){const f=d.anchor("mouth");d.effect({kind:"honk",time:u,x:f.x,y:f.y,length:800,direction:d.facing()||1})}};return{kind:t.kind,family:"animal",summary:t.summary,rig:c,actions:{...sk(t,h),...t.actions?.(h)},acting:ka,colors:{body:n.coat,ink:"#26262b"},follow:[{control:"tail",of:"x",per:.6,stiffness:90,damping:6,limit:40}],moves:Qw(t,s)}}function Qw(t,e){const n=i=>{const o=Ni(e,i);return{speed:o/(Li[i].cycle*(t.cycleScale??1)/1e3),set:{gait:Sn.indexOf(i)},hold:{walking:1},perMetre:{walk:1/o}}},s=Object.fromEntries(t.gaits.map(i=>[i==="gallop"&&!t.gaits.includes("canter")?"run":i,n(i)]));return t.gaits.includes("gallop")&&!s.gallop&&(s.gallop=n("gallop")),s}const Ut=Array.from({length:7},(t,e)=>e===0?"tail":`tail-${e}`);function tk(t,e,n){const s=Or(t.tail.points,Ut.length+1),[,i,o]=t.body.radii,r=(t.tail.at[1]-n)/i,a=Math.abs(r)<1?-o*Math.sqrt(1-r*r):t.tail.at[2],l=[t.tail.at[0],t.tail.at[1],a+Math.min(.04,o*.08)],c=f=>t.tail.radius*(1-.5*f/Ut.length),h=Ut.map((f,g)=>{const p=s[g],m=s[g+1],b=[m[0]-p[0],m[1]-p[1],m[2]-p[2]],S=g===0?void 0:s[g-1];return{id:f,...g>0?{parent:Ut[g-1]}:{},shape:{type:"tube",points:[[0,0,0],b],radius:[c(g),c(g+1)],segments:8,joined:!0},at:g===0?l:[p[0]-S[0],p[1]-S[1],p[2]-S[2]],fill:e.dark,outline:.8}}),d=s[s.length-1],u=s[s.length-2];return h.push({id:"tail-tip",parent:Ut[Ut.length-1],shape:{type:"ellipsoid",radii:Array(3).fill(c(Ut.length)*1.05),segments:8},at:[d[0]-u[0],d[1]-u[1],d[2]-u[2]],fill:e.dark,outline:.8,solidOnly:!0}),h}function ek(t,e,n){const s=Math.max(0,Math.min(1,t.walking??0));if(s===0)return{};const i=Sn[Math.max(0,Math.min(3,Math.round(t.gait??0)))],o=Li[e.gaits.includes(i)?i:e.gaits[0]],r=t.walk??0,a={};for(const c of cf){const h=Math.PI*2*(r+o.offsets[c]);a[`${c}.swing`]=(t[`${c}.swing`]??0)+s*o.swing*Math.sin(h),a[`${c}.knee`]=(t[`${c}.knee`]??0)+s*o.lift*Math.max(0,Math.cos(h))}const l=Math.PI*2*r;return a.lift=(t.lift??0)+s*o.bob*n*Math.abs(Math.sin(l*2)),a.pitch=(t.pitch??0)+s*o.rock*Math.sin(l),a.neck=(t.neck??0)+s*(o.rock>0?-o.rock*1.4:5)*Math.sin(l*2),a}function hf(t){const n=Math.sin(32*qe),s=t.legLength-(t.front-t.hind)*n,i=72,r=(s-t.upper*Math.cos(i*qe)-t.foot)/t.lower,a=r>=1?0:r<=-1?180:Math.acos(r)/qe,l={pitch:32,lift:t.legLength*(1-Math.cos(32*qe))-t.front*n,neck:-10,tail:t.tailHangs?35:-40,"fl.swing":-32,"fr.swing":-32};for(const c of["hl","hr"])l[`${c}.swing`]=i-32,l[`${c}.knee`]=-(i+a),l[`${c}.ankle`]=a;return l}const ka={depth:{turn:0,lift:0,pitch:1,roll:1,squash:1,neck:2,tail:3,wag:3,"fl.swing":2,"fr.swing":2,"hl.swing":2,"hr.swing":2,"fl.knee":3,"fr.knee":3,"hl.knee":3,"hr.knee":3},limits:{pitch:6,neck:8,tail:10,wag:8,"fl.swing":8,"fr.swing":8,"hl.swing":8,"hr.swing":8,lift:0},eyes:[],headTurns:{},drift:[]},nk=ka;function sk(t,e){const n=t.cycleScale??1,s=r=>({summary:{walk:"Walks to `to` (four beats), its head bobbing.",trot:"Trots to `to`: legs in diagonal pairs, the body bouncing.",canter:"Canters to `to`: three beats, the body rocking.",gallop:"Gallops (runs) to `to`: legs reaching, the body rocking hard, kicking up dust."}[r],needs:["to"],uses:["for"],run(a,l,c){const h=Math.sign(l.to-a.x);if(h===0)return{end:c};let d=c;a.facing()!==h&&(d=a.turnTo(d,h>0?"right":"left"));const u=a.exaggeration;a.key(d+180,{neck:-12*u},{act:!1,easing:"ease-out"});const g=Math.abs(l.to-a.x)/a.scale/Ni(e.legLength,r),p=l.for??Math.max(500,g*Li[r].cycle*n),m=a.values.walk??0;return a.set("gait",d,a.values.gait??0),a.set("gait",d+1,Sn.indexOf(r)),a.set("walking",d,0),a.set("walking",d+240,1,"ease-out"),a.set("walking",d+p-240,1),a.set("walking",d+p,0,"ease-in"),a.set("walk",d,m),a.move(d,d+p,l.to,{easing:"ease-in-out"}),a.set("walk",d+p,m+g,"ease-in-out"),a.key(d+p+300,{neck:0}),(r==="gallop"||r==="canter")&&(a.effect({kind:"dust",time:d+200,x:a.x-h*e.legLength*a.scale,y:a.floor,length:700,direction:-h}),a.effect({kind:"dust",time:d+p,x:l.to+h*e.legLength*.6*a.scale,y:a.floor,length:600,direction:h})),{end:d+p+300,contact:d,release:d+p}}}),i=Object.fromEntries(t.gaits.map(r=>[r==="gallop"&&!t.gaits.includes("canter")?"run":r,s(r)]));t.gaits.includes("gallop")&&!i.gallop&&(i.gallop=s("gallop"));const o={...i,[t.call]:{summary:`Throws its head up and ${t.call}s.`,run(r,a,l){const c=r.exaggeration;return r.key(l+150,{neck:10*c},{act:!1,easing:"ease-out"}),r.key(l+380,{neck:-28*c,squash:1.05},{act:!1,easing:"ease-out"}),r.key(l+680,{neck:-20*c},{act:!1}),r.key(l+980,{neck:0,squash:1}),e.call(r,l+380),{end:l+980,contact:l+380}}},sit:{summary:"Sits on its haunches for `for` ms (default 1500): the rump goes down onto folded hind legs, paws flat on the ground, the front legs stay planted; then it gets up.",uses:["for"],run(r,a,l){const c=hf(e),h=l+450;r.key(h,c,{act:!1,easing:"ease-in-out"}),r.key(h+(a.for??1500),c,{act:!1});const d=h+(a.for??1500)+450,u={};for(const f of Object.keys(c))u[f]=0;return r.key(d,u),{end:d,contact:h,release:d-450}}},jump:{summary:"Crouches and jumps (forward to `to`, or up on the spot), legs tucked in the air, landing with a squash and dust.",uses:["to"],run(r,a,l){const c=r.exaggeration,h=e.legLength*.8*c,d=l+260,u=d+90,f=u+520;if(r.key(d,{squash:.86,"hl.knee":40,"hr.knee":40,"fl.knee":25,"fr.knee":25,neck:8},{act:!1,easing:"ease-out"}),r.key(u,{squash:1.12,"hl.knee":0,"hr.knee":0,"fl.knee":0,"fr.knee":0,pitch:8,"fl.swing":35,"fr.swing":35,"hl.swing":-35,"hr.swing":-35},{act:!1,easing:"ease-out"}),r.key((u+f)/2,{lift:h,squash:1,pitch:0,"fl.knee":60,"fr.knee":60,"hl.knee":60,"hr.knee":60,"fl.swing":25,"fr.swing":25,"hl.swing":-20,"hr.swing":-20},{act:!1,easing:"ease-out"}),r.key(f,{lift:0,squash:.85,pitch:-4,"fl.knee":0,"fr.knee":0,"hl.knee":0,"hr.knee":0,"fl.swing":0,"fr.swing":0,"hl.swing":0,"hr.swing":0},{act:!1,easing:"ease-in"}),r.key(f+280,{squash:1,pitch:0,neck:0}),a.to!==void 0){const g=Math.sign(a.to-r.x);g!==0&&r.facing()!==g&&r.turnTo(l,g>0?"right":"left"),r.move(u,f,a.to)}return r.effect({kind:"dust",time:f,x:r.x,y:r.floor,length:550}),{end:f+280,contact:f}}},nod:{summary:"Nods its head twice.",run(r,a,l){return r.key(l+200,{neck:20},{act:!1,easing:"ease-out"}),r.key(l+400,{neck:-5},{act:!1,easing:"ease-in-out"}),r.key(l+600,{neck:18},{act:!1,easing:"ease-in-out"}),r.key(l+900,{neck:0}),{end:l+900}}},swish:{summary:"Swishes its tail a few times.",uses:["for"],run(r,a,l){const c=a.for??900;for(let h=1;h<=4;h++)r.key(l+c*h/5,{tail:h%2===0?10:35},{act:!1,easing:"ease-in-out"});return r.key(l+c,{tail:0}),{end:l+c}}}};return t.grazes&&(o.graze={summary:"Lowers its head to graze for `for` ms (default 1800), nibbling, then looks up.",uses:["for"],run(r,a,l){const c=a.for??1800;r.key(l+600,{neck:75},{act:!1,easing:"ease-in-out"});for(let h=900;h<600+c;h+=400)r.key(l+h,{neck:h%800===100?70:78},{act:!1,easing:"ease-in-out"});return r.key(l+600+c+500,{neck:0}),{end:l+600+c+500}}}),o}function df(t={}){return us({kind:t.kind??"horse",summary:t.summary??"A cartoon horse: walks, trots, canters and gallops with its hooves in step with the ground, rears, bucks, neighs, grazes and swishes its tail.",legs:{upper:.5,lower:.42,foot:.08,footSize:[.12,.16],front:.62,hind:-.62,across:.2,thickness:[.075,.09],lowerThickness:.05},body:{radii:[.32,.36,.95],rise:.25},neck:{at:[0,1.42,.7],points:[[0,0,0],[0,.5,.3]],radius:.15},head:{at:[0,.48,.5],radii:[.13,.14,.3],rotate:[38,0,0]},muzzle:{at:[0,-.02,.24],radii:[.11,.1,.1]},ears:{at:[.07,.16,-.17],radii:[.035,.1,.05]},eyes:{at:[.115,.05,-.04],size:.04},tail:{at:[0,1.4,-.9],points:[[0,0,0],[0,-.22,-.2],[0,-.62,-.24]],radius:.08},mane:{points:[[0,.1,-.12],[0,.55,.17]],radius:.07},colors:{coat:"#b5763a",dark:"#4a2e1a",foot:"#3a2a22",muzzle:"#8d5a2c",accent:"#e8c9a0",...t.colors},gaits:["walk","trot","canter","gallop"],call:"neigh",grazes:!0,anchors:{hitch:{at:[0,.95,-.15]},saddle:{at:[0,1.6,-.05]}},actions:e=>({rear:{summary:"Rears up on its hind legs, front legs tucked and pawing, neighs, and drops back down with dust.",uses:["for"],run(n,s,i){const o=n.exaggeration,r=Math.min(55,32*o),a=-e.hind*Math.sin(r*qe),l=s.for??700;n.key(i+200,{pitch:-4,neck:6,"hl.knee":12,"hr.knee":12},{act:!1,easing:"ease-out"}),n.key(i+520,{pitch:r,lift:a,neck:-25,"fl.swing":55,"fl.knee":95,"fr.swing":40,"fr.knee":80,"hl.knee":0,"hr.knee":0},{act:!1,easing:"ease-out"}),n.key(i+520+l*.5,{"fl.swing":35,"fl.knee":70,"fr.swing":58,"fr.knee":100},{act:!1,easing:"ease-in-out"}),n.key(i+520+l,{"fl.swing":55,"fl.knee":95,"fr.swing":40,"fr.knee":80},{act:!1,easing:"ease-in-out"});const c=i+520+l+380;return n.key(c,{pitch:0,lift:0,neck:8,squash:.94,"fl.swing":0,"fl.knee":0,"fr.swing":0,"fr.knee":0},{act:!1,easing:"ease-in"}),n.key(c+320,{neck:0,squash:1}),e.call(n,i+520),n.effect({kind:"dust",time:c,x:n.x+(n.facing()||1)*e.front*n.scale,y:n.floor,length:600}),{end:c+320,contact:c}}},buck:{summary:"Bucks: drops its head and kicks both hind legs up and back.",run(n,s,i){const o=n.exaggeration,r=Math.min(35,18*o),a=e.front*Math.sin(r*qe);return n.key(i+220,{pitch:3,squash:.95},{act:!1,easing:"ease-out"}),n.key(i+480,{pitch:-r,lift:a,neck:30,"hl.swing":-65,"hr.swing":-60,"hl.knee":10,"hr.knee":10},{act:!1,easing:"ease-out"}),n.key(i+900,{pitch:0,lift:0,neck:0,squash:.95,"hl.swing":0,"hr.swing":0,"hl.knee":0,"hr.knee":0},{act:!1,easing:"ease-in"}),n.key(i+1150,{squash:1}),n.effect({kind:"dust",time:i+900,x:n.x-(n.facing()||1)*.6*n.scale,y:n.floor,length:600}),{end:i+1150,contact:i+480}}}})})}function uf(t={}){return us({kind:t.kind??"dog",summary:t.summary??"A cartoon dog: walks, trots and runs, barks, wags its tail, sits, jumps, sniffs the ground.",legs:{upper:.19,lower:.16,foot:.05,footSize:[.07,.1],front:.24,hind:-.24,across:.09,thickness:[.04,.05],lowerThickness:.032},body:{radii:[.14,.15,.36],rise:.1},neck:{at:[0,.56,.27],points:[[0,0,0],[0,.14,.06]],radius:.075},head:{at:[0,.15,.08],radii:[.12,.11,.13]},muzzle:{at:[0,-.03,.13],radii:[.065,.055,.08]},ears:{at:[.11,0,-.02],radii:[.025,.09,.05],rotate:[0,0,18]},eyes:{at:[.08,.04,.08],size:.025},tail:{at:[0,.58,-.34],points:[[0,0,0],[0,.1,-.08],[0,.2,-.1]],radius:.03},extras:e=>[{id:"nose",parent:"muzzle",shape:{type:"ellipsoid",radii:[.025,.02,.02],segments:8},at:[0,.03,.08],fill:"#1d1d22",outline:.4},{id:"patch",parent:"body",shape:{type:"ellipsoid",radii:[.012,.09,.11],segments:10},at:[.135,.04,-.06],fill:e.accent,outline:.5}],colors:{coat:"#d9a066",dark:"#a8703a",foot:"#a8703a",muzzle:"#f0d2a8",accent:"#f6ead8",...t.colors},gaits:["walk","trot","gallop"],cycleScale:.55,call:"bark",anchors:{leash:{part:"neck",at:[0,.06,0]}},actions:()=>({wag:{summary:"Wags its tail fast for `for` ms (default 1200).",uses:["for"],run(e,n,s){const i=n.for??1200;for(let o=80,r=0;o<i;o+=80,r++)e.key(s+o,{wag:r%2===0?35:-35,tail:25},{act:!1,easing:"ease-in-out"});return e.key(s+i,{wag:0,tail:0}),{end:s+i}}},sniff:{summary:"Puts its nose to the ground and sniffs (`for` ms, default 1400).",uses:["for"],run(e,n,s){const i=n.for??1400;e.key(s+350,{neck:70,pitch:-6},{act:!1,easing:"ease-in-out"});for(let o=500,r=0;o<i;o+=140,r++)e.key(s+o,{neck:r%2===0?74:66},{act:!1});return e.key(s+i+300,{neck:0,pitch:0}),{end:s+i+300}}}})})}function ff(t={}){return us({kind:t.kind??"cat",summary:t.summary??"A cartoon cat: walks, trots and runs, meows, arches its back, pounces, sits and swishes its tail.",legs:{upper:.13,lower:.11,foot:.035,footSize:[.05,.07],front:.17,hind:-.18,across:.06,thickness:[.028,.035],lowerThickness:.022},body:{radii:[.1,.105,.27],rise:.07},neck:{at:[0,.39,.2],points:[[0,0,0],[0,.08,.04]],radius:.05},head:{at:[0,.1,.05],radii:[.095,.085,.085]},muzzle:{at:[0,-.03,.07],radii:[.04,.03,.03]},ears:{at:[.055,.085,-.01],radii:[.03,.055,.02],rotate:[0,0,-12]},eyes:{at:[.045,.02,.07],size:.022},tail:{at:[0,.42,-.26],points:[[0,0,0],[0,.08,-.12],[0,.24,-.16],[0,.34,-.1]],radius:.022},extras:()=>[{id:"nose",parent:"muzzle",shape:{type:"ellipsoid",radii:[.014,.01,.01],segments:8},at:[0,.015,.03],fill:"#e48a9a",outline:.4}],colors:{coat:"#8f8a86",dark:"#5f5a57",foot:"#f2efe9",muzzle:"#f2efe9",accent:"#f2efe9",...t.colors},gaits:["walk","trot","gallop"],cycleScale:.5,call:"meow",actions:e=>({arch:{summary:"Arches its back, fur up and tail high, for `for` ms (default 1200): a startled cat.",uses:["for"],run(n,s,i){const o=n.exaggeration,r=s.for??1200,a={squash:1+.25*o,neck:25,tail:-45,"fl.swing":-8,"fr.swing":-8,"hl.swing":8,"hr.swing":8};return n.key(i+180,a,{act:!1,easing:"ease-out"}),n.key(i+180+r,a,{act:!1}),n.key(i+r+520,{squash:1,neck:0,tail:0,"fl.swing":0,"fr.swing":0,"hl.swing":0,"hr.swing":0}),{end:i+r+520,contact:i+180}}},pounce:{summary:"Crouches low, wiggles, and pounces to `to`, landing with a squash.",needs:["to"],run(n,s,i){const o=n.exaggeration,r=Math.sign(s.to-n.x);let a=i;r!==0&&n.facing()!==r&&(a=n.turnTo(a,r>0?"right":"left"));const l={squash:.75,"hl.knee":60,"hr.knee":60,"fl.knee":45,"fr.knee":45,neck:10,tail:-15};n.key(a+300,l,{act:!1,easing:"ease-out"});for(let d=1;d<=4;d++)n.key(a+300+d*110,{roll:d%2===0?3:-3},{act:!1});const c=a+300+550,h=c+480;return n.key(c,{roll:0,squash:1.2,"hl.knee":0,"hr.knee":0,"fl.knee":0,"fr.knee":0,"fl.swing":45,"fr.swing":45,"hl.swing":-45,"hr.swing":-45,tail:20},{act:!1,easing:"ease-out"}),n.key((c+h)/2,{lift:e.legLength*.9*o,squash:1.1,pitch:-6},{act:!1,easing:"ease-out"}),n.key(h,{lift:0,squash:.8,pitch:0,"fl.swing":0,"fr.swing":0,"hl.swing":0,"hr.swing":0,neck:0,tail:0},{act:!1,easing:"ease-in"}),n.key(h+260,{squash:1}),n.move(c,h,s.to),n.effect({kind:"dust",time:h,x:s.to,y:n.floor,length:450}),{end:h+260,contact:h}}}})})}function pf(t={}){return us({kind:t.kind??"cow",summary:t.summary??"A cartoon cow: walks and trots, moos, grazes, sits and swishes its tail.",legs:{upper:.42,lower:.36,foot:.08,footSize:[.13,.15],front:.68,hind:-.66,across:.24,thickness:[.085,.1],lowerThickness:.06},body:{radii:[.4,.42,1],rise:.32},neck:{at:[0,1.3,.85],points:[[0,0,0],[0,.22,.25]],radius:.19},head:{at:[0,.18,.4],radii:[.17,.19,.27],rotate:[30,0,0]},muzzle:{at:[0,-.06,.22],radii:[.15,.11,.1]},ears:{at:[.17,.06,-.12],radii:[.11,.035,.05],rotate:[0,0,-15]},eyes:{at:[.13,.06,.02],size:.04},tail:{at:[0,1.48,-1],points:[[0,0,0],[0,-.25,-.12],[0,-.7,-.14]],radius:.035},extras:e=>[{id:"horn-left",parent:"head",shape:{type:"tube",points:[[0,0,0],[.08,.12,.02]],radius:.025,segments:6},at:[.1,.16,-.14],fill:"#efe6d2",outline:.6},{id:"horn-right",parent:"head",shape:{type:"tube",points:[[0,0,0],[-.08,.12,.02]],radius:.025,segments:6},at:[-.1,.16,-.14],fill:"#efe6d2",outline:.6},{id:"udder",shape:{type:"ellipsoid",radii:[.16,.12,.18],segments:10},at:[0,.98,-.45],fill:"#f0a6b6",outline:.6},{id:"spot-1",parent:"body",shape:{type:"ellipsoid",radii:[.02,.2,.26],segments:10},at:[.39,.06,.2],fill:e.accent,outline:.4},{id:"spot-2",parent:"body",shape:{type:"ellipsoid",radii:[.02,.16,.22],segments:10},at:[-.39,.1,-.35],fill:e.accent,outline:.4},{id:"spot-3",parent:"body",shape:{type:"ellipsoid",radii:[.2,.02,.24],segments:10},at:[0,.41,-.2],fill:e.accent,outline:.4}],colors:{coat:"#f4f1ea",dark:"#2e2b2a",foot:"#3a3330",muzzle:"#f0b8c4",accent:"#2e2b2a",...t.colors},gaits:["walk","trot"],cycleScale:1.15,call:"moo",grazes:!0})}function ik(t){return Ni(1,t)}const Ee=.6,gf=75,va=80;function Di(t){const{colors:e}=t,[n,s,i]=t.body.radii,o=(t.tail.raised??15)*Math.PI/180,r=t.tail.length*.4,a=[{id:"body",shape:{type:"ellipsoid",radii:t.body.radii,segments:16},at:[0,t.body.height,0],fill:e.body},{id:"neck",shape:{type:"ellipsoid",radii:[n*.55,s*.55,i*.3],segments:10},at:[0,t.body.height+s*.45,i*.65],fill:e.body,outline:.5,solidOnly:!0},{id:"head",parent:"neck",shape:{type:"ellipsoid",radii:[t.head.radius,t.head.radius*1.02,t.head.radius*1.05],segments:14},at:[t.head.at[0],t.head.at[1]-(t.body.height+s*.45),t.head.at[2]-i*.65],fill:e.body},{id:"beak",parent:"head",shape:{type:"tube",points:[[0,0,0],[0,-t.beak.thickness*.4,t.beak.length]],radius:[t.beak.thickness,t.beak.thickness*.08],segments:8},at:[0,-t.head.radius*.1,t.head.radius*.8],fill:e.beak,outline:.8},{id:"tail",shape:{type:"ellipsoid",radii:[t.tail.width/2,.012*(i/.08),t.tail.length/2],segments:10},at:[t.tail.at[0],t.tail.at[1]+r*Math.sin(o),t.tail.at[2]-r*Math.cos(o)],rotate:[t.tail.raised??15,0,0],fill:e.wing,outline:.8}];if(e.belly&&a.push({id:"belly",parent:"body",shape:{type:"ellipsoid",radii:[n*.82,s*.7,i*.75],segments:12},at:[0,-s*.25,i*.12],fill:e.belly,outline:.4}),t.comb){const h=t.head.radius;a.push({id:"comb",parent:"head",shape:{type:"extrude",profile:[[-h*.5,h*.6],[h*.6,h*.6],[h*.5,h*1.3],[h*.15,h*1.05],[-h*.05,h*1.4],[-h*.3,h*1.05],[-h*.6,h*1.25]],width:h*.25},fill:e.comb??"#d9372e",outline:.7},{id:"wattle",parent:"head",shape:{type:"ellipsoid",radii:[h*.15,h*.35,h*.2],segments:8},at:[0,-h*.7,h*.6],fill:e.comb??"#d9372e",outline:.6})}for(const h of[1,-1]){const d=h>0?"left":"right",u=t.head.radius;a.push({id:`eye-${d}`,parent:"head",shape:{type:"ellipsoid",radii:[u*.16,u*.2,u*.18],segments:8},at:[h*u*.72,u*.18,u*.42],fill:"#1d1d22",outline:.3}),a.push({id:`wing-${d}`,shape:{type:"ellipsoid",radii:[.004,.004,.004],segments:4},at:[h*t.wing.shoulder[0],t.wing.shoulder[1],t.wing.shoulder[2]],rotate:[-8,h*90,0],outline:0}),a.push({id:`wing-${d}-blade`,parent:`wing-${d}`,shape:{type:"ellipsoid",radii:[t.wing.span*Ee/2,t.wing.chord*.1,t.wing.chord/2],segments:12},at:[h*t.wing.span*Ee/2,0,-t.wing.chord*.1],rotate:[-va,0,0],fill:e.wing,outline:.8}),a.push({id:`wing-${d}-tip`,parent:`wing-${d}-blade`,shape:{type:"ellipsoid",radii:[t.wing.span*Ee/2.4,t.wing.chord*.06,t.wing.chord*.3],segments:10},at:[h*t.wing.span*Ee/4,0,-t.wing.chord*.3],rotate:[0,h*14,0],fill:e.wing,outline:.8}),a.push({id:`leg-${d}`,shape:{type:"tube",points:[[0,0,0],[0,-t.legs.length,0]],radius:Math.max(.004,t.legs.length*.05),segments:5},at:[h*t.legs.across,t.legs.length,0],fill:e.legs,outline:.6}),a.push({id:`toes-${d}`,parent:`leg-${d}`,shape:{type:"tube",points:[[0,0,-t.legs.length*.15],[0,0,t.legs.length*.35]],radius:Math.max(.003,t.legs.length*.04),segments:5},at:[0,-t.legs.length,0],fill:e.legs,outline:.6})}const l={spread:{description:"Wings: 0 folded back along the body, 1 spread out",unit:"0..1",min:0,max:1,bind:[{parts:["wing-left"],rotate:{axis:"y",degrees:-90}},{parts:["wing-right"],rotate:{axis:"y",degrees:90}},{parts:["wing-left-blade"],translate:[t.wing.span*(1-Ee)/2,0,0],rotate:{axis:"x",degrees:va},scale:[1/Ee,1,1]},{parts:["wing-right-blade"],translate:[-t.wing.span*(1-Ee)/2,0,0],rotate:{axis:"x",degrees:va},scale:[1/Ee,1,1]}]},flap:{description:"Wings raised (+) or lowered (−) at the shoulders",unit:"degrees",bind:[{parts:["wing-left"],rotate:{axis:"z",degrees:1}},{parts:["wing-right"],rotate:{axis:"z",degrees:-1}}]},wingbeat:{description:"Phase of the wingbeat, in beats (keyed steadily while flapping)",unit:"beats"},flapping:{description:"How hard the wings beat: 0 still, 1 full beats",unit:"0..1",min:0,max:1},peck:{description:"Head bobbed down and forward (+, pecking) or up (−)",unit:"degrees",bind:[{parts:["neck"],rotate:{axis:"x",degrees:1},translate:[0,-(t.neckReach??0)/gf,0]}]},step:{description:"Phase of a walk, in steps (a chicken’s legs)",unit:"steps"},stepping:{description:"How much of the walk is applied",unit:"0..1",min:0,max:1},"leg.left":{description:"Left leg swung forward (+)",unit:"degrees",bind:[{parts:["leg-left"],rotate:{axis:"x",degrees:-1}}]},"leg.right":{description:"Right leg swung forward (+)",unit:"degrees",bind:[{parts:["leg-right"],rotate:{axis:"x",degrees:-1}}]}},c={parts:a,controls:l,length:i*2+t.tail.length+t.beak.length,height:t.head.at[1]+t.head.radius,footprint:[n*2.2,i*2.4],anchors:{beak:{part:"beak",at:[0,0,t.beak.length]},head:{part:"head",at:[0,0,0]},back:{at:[0,t.body.height+s,0]},feet:{at:[0,0,0]}},derive:h=>{const d={},u=Math.max(0,Math.min(1,h.flapping??0));u>0&&(d.flap=(h.flap??0)+u*48*Math.sin(Math.PI*2*(h.wingbeat??0)));const f=Math.max(0,Math.min(1,h.stepping??0));if(f>0){const g=Math.sin(Math.PI*2*(h.step??0));d["leg.left"]=(h["leg.left"]??0)+f*28*g,d["leg.right"]=(h["leg.right"]??0)-f*28*g,d.peck=(h.peck??0)+f*12*Math.sin(Math.PI*4*(h.step??0))}return d}};return{kind:t.kind,family:"bird",summary:t.summary,rig:c,actions:rk(t),acting:mf,colors:{body:e.body,ink:"#26262b"},moves:ok(t)}}function ok(t){const e=t.legs.length*1.2,n={walk:{speed:e/.42,hold:{stepping:1},perMetre:{step:.5/e}}};return t.flies!==!1&&(n.fly={speed:4+t.wing.span*12,flies:!0,hold:{flapping:1,spread:1},perSecond:{wingbeat:t.beatsPerSecond??4}}),n}const mf={depth:{turn:0,lift:0,pitch:1,roll:1,squash:1,spread:1,flap:2,peck:2},limits:{pitch:6,roll:6,squash:.06,peck:8,flap:10,lift:0},eyes:[],headTurns:{},drift:[]};function rk(t){const e=(t.beatsPerSecond??4)/1e3,n=(r,a,l)=>{const c=r.values.wingbeat??0;r.set("wingbeat",a,c),r.set("wingbeat",l,c+(l-a)*e)},s=(r,a,l)=>{const c=Math.sign(l-r.x);return c!==0&&r.facing()!==c?r.turnTo(a,c>0?"right":"left"):a},i=(r,a)=>{const l=r.anchor("beak");r.effect({kind:"honk",time:a,x:l.x,y:l.y,length:600,direction:r.facing()||1})},o={hop:{summary:"Hops to `to` in little bounces, wings twitching.",needs:["to"],run(r,a,l){const c=s(r,l,a.to),h=r.x,d=Math.abs(a.to-h),u=Math.max(1,Math.round(d/(t.body.radii[2]*3*r.scale))),f=260;for(let g=0;g<u;g++){const p=c+g*f;r.key(p+60,{squash:.85},{act:!1,easing:"ease-out"}),r.key(p+150,{squash:1.1,lift:t.legs.length*1.4,spread:.15},{act:!1,easing:"ease-out"}),r.key(p+f,{squash:.9,lift:0,spread:0},{act:!1,easing:"ease-in"}),r.move(p+60,p+f,h+(a.to-h)*(g+1)/u,{easing:"ease-in-out"})}return r.key(c+u*f+120,{squash:1}),{end:c+u*f+120}}},walk:{summary:"Walks to `to` on its two legs, its head bobbing with each step.",needs:["to"],uses:["for"],run(r,a,l){const c=s(r,l,a.to),h=Math.abs(a.to-r.x)/r.scale,d=t.legs.length*1.2,u=h/d,f=a.for??Math.max(400,u*420),g=r.values.step??0;return r.set("stepping",c,0),r.set("stepping",c+150,1,"ease-out"),r.set("stepping",c+f-150,1),r.set("stepping",c+f,0,"ease-in"),r.set("step",c,g),r.move(c,c+f,a.to,{easing:"ease-in-out"}),r.set("step",c+f,g+u/2,"ease-in-out"),{end:c+f,contact:c,release:c+f}}},peck:{summary:"Pecks at the ground (`for` ms, default 900): quick jabs of the head.",uses:["for"],run(r,a,l){const c=a.for??900,h=Math.max(1,Math.round(c/300));r.key(l+120,{pitch:-(t.stoop??12)},{act:!1,easing:"ease-out"});for(let d=0;d<h;d++)r.key(l+120+d*300+90,{peck:gf},{act:!1,easing:"ease-in"}),r.key(l+120+d*300+260,{peck:20},{act:!1,easing:"ease-out"});return r.key(l+120+h*300+200,{peck:0,pitch:0}),{end:l+120+h*300+200,contact:l+210}}},flap:{summary:"Flaps its wings on the spot (`for` ms, default 900), lifting a little.",uses:["for"],run(r,a,l){const c=a.for??900;return r.key(l+120,{spread:1},{act:!1,easing:"ease-out"}),r.set("flapping",l,0),r.set("flapping",l+150,1,"ease-out"),r.set("flapping",l+c-150,1),r.set("flapping",l+c,0,"ease-in"),n(r,l,l+c),r.key(l+c*.5,{lift:t.legs.length*.6},{act:!1,easing:"ease-out"}),r.key(l+c,{lift:0,spread:0},{act:!1,easing:"ease-in"}),{end:l+c+80}}},[t.call]:{summary:`${t.call[0].toUpperCase()}${t.call.slice(1)}s: its head comes up and its beak opens to call.`,run(r,a,l){return r.key(l+120,{peck:-25,squash:1.06},{act:!1,easing:"ease-out"}),r.key(l+500,{peck:-20},{act:!1}),r.key(l+760,{peck:0,squash:1}),i(r,l+150),{end:l+760,contact:l+150}}}};return t.flies!==!1?(o.fly={summary:"Takes off (a crouch and a leap, wings beating) and flies to `to` at `height` metres (default 2); `land` brings it down.",needs:["to"],uses:["height","for"],run(r,a,l){const c=r.exaggeration,h=s(r,l,a.to),d=a.height??2,u=a.for??Math.max(700,Math.abs(a.to-r.x)/.35),f=r.values.lift>t.legs.length,g=f?h:h+200;return f||(r.key(h+160,{squash:1-.18*c,spread:.6},{act:!1,easing:"ease-out"}),r.effect({kind:"dust",time:g,x:r.x,y:r.floor,length:400})),r.key(g+100,{spread:1,squash:1.08,pitch:10},{act:!1,easing:"ease-out"}),r.set("flapping",g,r.values.flapping??0),r.set("flapping",g+100,1,"ease-out"),r.set("flapping",g+u,.6),n(r,g,g+u),r.key(g+u*.4,{lift:d,pitch:-5,squash:1},{act:!1,easing:"ease-out"}),r.key(g+u,{lift:d,pitch:0},{act:!1,easing:"ease-in-out"}),r.move(g,g+u,a.to,{easing:"ease-in-out"}),{end:g+u,contact:g,release:g+u}}},o.land={summary:"Comes down to the floor it is over (or to `height` metres above it, a branch or a roof): wings braking, a squash on touchdown.",uses:["height","to"],run(r,a,l){const h=a.height??0;return r.set("flapping",l,r.values.flapping??1),r.set("flapping",l+700-120,1),r.set("flapping",l+700,0,"ease-in"),n(r,l,l+700),r.key(l+700*.6,{pitch:14},{act:!1,easing:"ease-out"}),r.key(l+700,{lift:h,pitch:0,squash:.85},{act:!1,easing:"ease-in"}),a.to!==void 0&&r.move(l,l+700,a.to,{easing:"ease-out"}),r.key(l+700+160,{squash:1,spread:0}),{end:l+700+200,contact:l+700}}}):o.flutter={summary:"Flutters up a little way and back down, wings beating hard (a chicken’s flight).",run(r,a,l){return r.key(l+100,{spread:1,squash:.9},{act:!1,easing:"ease-out"}),r.set("flapping",l+80,0),r.set("flapping",l+160,1,"ease-out"),r.set("flapping",l+900-100,1),r.set("flapping",l+900,0,"ease-in"),n(r,l+80,l+900),r.key(l+900*.5,{lift:t.legs.length*2.5,squash:1.08},{act:!1,easing:"ease-out"}),r.key(l+900,{lift:0,squash:.85,spread:0},{act:!1,easing:"ease-in"}),r.key(l+900+160,{squash:1}),{end:l+900+160,contact:l+900}}},o}function yf(t={}){return Di({kind:"songbird",summary:"A small songbird: hops, pecks, tweets, flaps, flies and lands (on the ground, a branch or a roof).",body:{radii:[.05,.05,.075],height:.085},head:{at:[0,.145,.065],radius:.036},beak:{length:.03,thickness:.01},wing:{shoulder:[.04,.1,.03],span:.11,chord:.06},tail:{at:[0,.095,-.07],length:.07,width:.045},legs:{length:.04,across:.018},colors:{body:"#7b6a58",wing:"#5c4c3d",beak:"#e7a43a",legs:"#c47a35",belly:"#e9c8a3",...t.colors},call:"tweet",beatsPerSecond:9})}function bf(t={}){return Di({kind:"crow",summary:"A crow: walks and hops, pecks, caws, flaps, flies and lands (on the ground, a branch or a roof).",body:{radii:[.09,.09,.17],height:.2},head:{at:[0,.32,.15],radius:.065},beak:{length:.08,thickness:.022},wing:{shoulder:[.07,.24,.06],span:.32,chord:.14},tail:{at:[0,.2,-.15],length:.16,width:.09},legs:{length:.1,across:.035},colors:{body:"#2b2b33",wing:"#1e1e25",beak:"#3b3b44",legs:"#3b3b44",...t.colors},call:"caw",beatsPerSecond:4})}function wf(t={}){return Di({kind:"chicken",summary:"A chicken: walks with a bobbing head, pecks, clucks, and flutters up and down (it cannot really fly).",body:{radii:[.13,.14,.19],height:.3},head:{at:[0,.5,.16],radius:.07},beak:{length:.05,thickness:.02},wing:{shoulder:[.11,.34,.04],span:.24,chord:.15},tail:{at:[0,.38,-.15],length:.16,width:.13,raised:50},legs:{length:.17,across:.05},comb:!0,stoop:20,neckReach:.12,colors:{body:"#f4ede0",wing:"#e6dccb",beak:"#e7a43a",legs:"#e7a43a",comb:"#d9372e",...t.colors},call:"cluck",flies:!1})}const Tn={car:Uu,truck:Gu,bus:Vu,tractor:Ju,cart:Zu,trainCar:Qu,bike:tf,motorbike:ef,tree:nf,house:of,helicopter:af,airplane:lf,horse:df,dog:uf,cat:ff,cow:pf,songbird:yf,crow:bf,chicken:wf};function kf(t,e={}){const n=Tn[t];if(!n)throw new Error(ot("prop preset",t,Object.keys(Tn)));return n(e)}const Fi=["do","at","for","to","toward","speed","open","on","height","wind"],Ma={viewer:0,right:1,away:2,left:3},ak=420,Sa={hold:{summary:"Holds still (`for` ms, default 1000).",run:(t,e,n)=>({end:n+(e.for??1e3)})},turn:{summary:"Turns to face `toward`: viewer, right, away, left, or a quarter-turn value (it turns in 3D, through the nearer way).",needs:["toward"],run:(t,e,n)=>({end:t.turnTo(n,e.toward)})},pop:{summary:"Pops into being: grows from nothing, stretched, overshoots and settles (`for` ms, default 500).",uses:["for"],run(t,e,n){const s=e.for??500,i=t.exaggeration;return t.key(n,{size:0,squash:1},{act:!1}),t.key(n+s*.6,{size:1+.15*i,squash:1+.15*i},{act:!1,easing:"ease-out"}),t.key(n+s,{size:1,squash:1}),{end:n+s,contact:n}}},vanish:{summary:"Shrinks away to nothing, with a little stretch first (`for` ms, default 400).",uses:["for"],run(t,e,n){const s=e.for??400,i=t.exaggeration;return t.key(n+s*.3,{size:1+.08*i,squash:1+.12*i},{act:!1,easing:"ease-out"}),t.key(n+s,{size:0,squash:1},{act:!1,easing:"ease-in"}),{end:n+s,release:n+s}}}};function ji(t){return{...Sa,...t.actions}}const Ta=t=>typeof t=="number"&&Number.isFinite(t);function vf(t,e){if(!Array.isArray(t))return[{level:"error",beat:-1,message:`Beats must be an array of { do: … } objects (got ${typeof t}).`}];const n=ji(e),s=Object.keys(n),i=[];return t.forEach((o,r)=>{const a=c=>i.push({level:"error",beat:r,message:c});if(!o||typeof o!="object"||Array.isArray(o))return a(`Each beat must be an object like { do: '${s[s.length-1]}' }.`);const l=o;for(const c of Object.keys(l))Fi.includes(c)||a(ot("beat field",c,Fi,c==="duration"?"for":c==="direction"?"toward":void 0));if(typeof l.do!="string"||!s.includes(l.do))return a(ot(`${e.kind} action`,l.do,s));for(const c of n[l.do].needs??[])l[c]===void 0&&a(`\`${l.do}\` needs \`${c}\`.`);for(const c of["at","for","speed","height","wind"])l[c]!==void 0&&!(Ta(l[c])&&l[c]>=0)&&a(`\`${c}\` must be a number ≥ 0 (got ${JSON.stringify(l[c])}).`);if(l.to!==void 0&&!Ta(l.to)&&a(`\`to\` is a scene x in px (got ${JSON.stringify(l.to)}).`),l.toward!==void 0&&!Ta(l.toward)&&!(typeof l.toward=="string"&&l.toward in Ma)){const c=typeof l.toward=="string"?Hn(l.toward,Object.keys(Ma)):void 0;a(`\`toward\` is viewer, right, away, left or a quarter-turn number${c?` (did you mean "${c}"?)`:""} (got ${JSON.stringify(l.toward)}).`)}for(const c of["open","on"])l[c]!==void 0&&typeof l[c]!="boolean"&&a(`\`${c}\` is true or false (got ${JSON.stringify(l[c])}).`)}),i}function Mf(t,e,n,s={}){const i=vf(n,e).filter(T=>T.level==="error");if(i.length>0)throw new Error(`propScript (${e.kind}): ${i.length} problem(s) in the beats:
|
|
61
|
-
${i.map(
|
|
62
|
-
`)}`);const o=s.from??0,r=s.ground??0,a=s.scale??60,l=s.exaggeration??1,c=ji(e),h={};for(const T of[...Object.keys(kn),...Object.keys(e.rig.controls)])h[T]=s.start?.[T]??ft(e.rig,{},T);const d=[{time:0,pose:{...h}}],u=new Map,f=[];let g=o,p=r;const m=(T,I,v,P)=>{const H=u.get(T)??[{time:0,value:T==="x"||T==="y"?0:h[T]}];H.push({time:I,value:v,...P?{easing:P}:{}}),u.set(T,H),T!=="x"&&T!=="y"&&(h[T]=v)},b=(T,I)=>{const v=T==="x"?g-o:T==="y"?p-r:h[T],P=u.get(T);(!P||P[P.length-1].time<I)&&m(T,I,v)},S={prop:e,scale:a,exaggeration:l,get x(){return g},get floor(){return p},values:h,facing(){const T=Math.sin(h.turn*Math.PI/2);return Math.abs(T)<.5?0:T>0?1:-1},key(T,I,v={}){Object.assign(h,I),d.push({time:T,pose:{...h},...v.act===!1?{act:!1}:{},...v.easing?{easing:v.easing}:{}})},move(T,I,v,P={}){b("x",T),m("x",I,v-o,P.easing),g=v,P.floor!==void 0&&(b("y",T),m("y",I,P.floor-r,P.easing),p=P.floor)},set(T,I,v,P){m(T,I,v,P)},turnTo(T,I){const v=typeof I=="number"?I:Ma[I],P=h.turn,O=[v-4,v,v+4].map(j=>({t:j,d:Math.abs(j-P)})).sort((j,D)=>j.d-D.d||Math.abs(j.t)-Math.abs(D.t))[0];if(O.d<.001)return T;const C=T+ak*Math.max(1,O.d);return S.key(C,{turn:O.t}),C},effect(T){f.push(T)},anchor(T){const v=vn(e,h,a).anchors[T];if(!v)throw new Error(`${e.kind}: no anchor "${T}"`);return{x:g+v.point.x,y:p+v.point.y}}},k=[];let y=0;for(const T of n){const I=Math.max(T.at??y,d[d.length-1].time),v=c[T.do].run(S,T,I);v.end>d[d.length-1].time&&d.push({time:v.end,pose:{...h}}),k.push({start:I,end:v.end,...v.contact!==void 0?{contact:v.contact}:{},...v.release!==void 0?{release:v.release}:{}}),y=v.end}const M=Kr(s.style??"snappy"),$={...M,anticipation:M.anticipation*l,overshoot:M.overshoot*l},E=Ti(dk(d),e.acting,{style:$}),A=[...Object.entries(E).filter(([T])=>!u.has(T)).map(([T,I])=>({id:`${t}-${T}`,target:t,property:T,keyframes:I})),...[...u].map(([T,I])=>({id:`${t}-${T}`,target:t,property:T,keyframes:uk(I)}))];for(const T of ck(t,e,A,y,d[0].pose)){const I=A.findIndex(H=>H.property===T.property);if(I<0){A.push(T);continue}const v=new Ht({id:`${t}-own`,tracks:[A[I]]}),P=H=>Number(v.getStateAtTime(H).values.get(t)?.get(T.property)??0);A[I]={...T,keyframes:T.keyframes.map(H=>({time:H.time,value:Number(H.value)+P(H.time)}))}}return{tracks:A,duration:y,beats:k,effects:f}}const lk=1500;function ck(t,e,n,s,i){if(!e.follow?.length)return[];const o=new Ht({id:`${t}-follow`,tracks:n.filter(a=>a.property==="turn"||e.follow.some(l=>l.of===a.property))}),r=(a,l)=>{const c=o.getStateAtTime(a).values.get(t)?.get(l);return typeof c=="number"?c:i[l]??0};return e.follow.map(a=>{const l=s+lk,c=Ll(u=>r(u,a.of),{start:0,end:l,stiffness:a.stiffness,damping:a.damping}),h=a.limit??1/0,d=c.map(({time:u,value:f})=>{const g=Math.sin(r(u,"turn")*Math.PI/2),p=(f-r(u,a.of))*g;return{time:u,value:Math.max(-h,Math.min(h,p*a.per))}});return{id:`${t}-${a.control}`,target:t,property:a.control,keyframes:d}})}const hk=20;function dk(t){const e=[...t].sort((s,i)=>s.time-i.time),n=[];for(const s of e){const i=n[n.length-1];i&&s.time-i.time<hk?n[n.length-1]={...s,time:i.time}:n.push(s)}return n}function uk(t){const e=t.map((s,i)=>({k:s,i})).sort((s,i)=>s.k.time-i.k.time||s.i-i.i),n=[];for(const{k:s}of e)n.length>0&&n[n.length-1].time===s.time?n[n.length-1]=s:n.push(s);return n}const fk={linear:!0,"ease-in":!0,"ease-out":!0,"ease-in-out":!0,"ease-in-quad":!0,"ease-out-quad":!0,"ease-in-out-quad":!0,"ease-in-cubic":!0,"ease-out-cubic":!0,"ease-in-out-cubic":!0};function Sf(t,e={}){const n={};for(const s of Object.keys(Ot))n[s]={summary:`Walks to \`to\` in the ${s} gait.`,needs:["to"]};for(const s of Object.keys(Dt))n[s]={summary:`Moves into the ${s} pose and holds it (\`for\` ms).`};for(const s of Object.keys(Me))n[s]={summary:`The ${s} gag (${os(s)} ms).`};for(const[s,i]of Object.entries(as))n[s]={...i};return{...t?{version:t}:{},timing:"JSON timelines and tracks are in milliseconds; the GSAP-style API (live.to, tf.timeline) takes seconds. Scene x grows right, y grows down, in px.",easings:{named:Object.keys(fk),parametric:{"cubic-bezier":'{ type: "cubic-bezier", points: [x1, y1, x2, y2] }',steps:'{ type: "steps", count, position?: start | end | none | both }',elastic:'{ type: "elastic", mode?: in | out | in-out, amplitude?, period? }',bounce:'{ type: "bounce", mode?: in | out | in-out }',back:'{ type: "back", mode?: in | out | in-out, overshoot? }'}},trackKinds:{keyframe:"{ id, target, property, keyframes: [{ time, value, easing? }] }: values between keys are interpolated (numbers, colours, paths)",spring:'{ id, target, property, kind: "spring", spring: { from, to, stiffness?, damping?, mass?, velocity? }, delay? }: physics settle',inertia:'{ id, target, property, kind: "inertia", inertia: { from, velocity, friction?, min?, max?, end? }, delay? }: a flick that slows (end snaps to a value or the nearest of a list)',motionPath:'{ property: "motionPath", path, align? }: moves along an SVG path',text:'{ property: "text", … }: types or scrambles text'},canvasProperties:Oi,stickFigure:{poseFields:zc,props:Xc,handFields:Uc,poses:Object.keys(Dt),expressions:Object.keys(ct),gags:Object.fromEntries(Object.keys(Me).map(s=>[s,os(s)])),gaits:Object.keys(Ot),actingStyles:Object.keys(je),beatFields:Ai,actions:n,dances:Object.fromEntries(Object.entries(ye).map(([s,i])=>[s,Object.keys(i.moves)])),flips:Object.fromEntries(Object.entries(Vn).map(([s,i])=>[s,i.label])),handShapes:Object.keys(Tt),mudras:Object.keys(Us)},props:{api:{"car() · truck() · bus() · tractor() · cart() · trainCar() · bike() · motorbike()":"wheeled vehicles (vehicle(spec) makes your own)","tree() · house()":"environment (tree(spec), house(spec))","helicopter() · airplane()":"aircraft","horse() · dog() · cat() · cow()":"animals (quadruped(spec) makes your own): gaits with footfall patterns keyed in step with the distance, sit, jump, their calls, species actions","songbird() · crow() · chicken()":"birds (bird(spec) makes your own): hop, walk, peck, flap, fly and land (a chicken flutters), their calls; wings fold and beat in rhythm","{ kind: 'prop', prop: 'car', position, rotation, values } with loadScene3D(scene, { kinds: [characterObjects, propObjects] })":"props in 3D scenes, by preset name, seen in perspective by the scene camera; controls are tracks on the object","characterScript3D(id, beats, { scene, position?, heading?, height?, pose? })":"a v2 character in a 3D scene in world metres: gaits to [x, z] or through points (its walk phase keyed with the distance), face, hold, pose, gag; checkCharacterBeats3D checks the beats","propRide3D({ prop, propId, propTracks, scene, placement, anchor, riderId, pose, start, end, mount?, dismount? })":"a character riding a prop in a 3D scene: hips on a seat anchor (saddle, seat) as it moves, hopping on and off; RIDING_POSES.astride / .seated","propScript3D(id, prop, beats, { scene, position?, heading?, values? })":"props scripted in world metres for 3D scenes: moves to [x, z] or through points (wheels and strides keyed with the distance), face, hold, and their actions; checkPropBeats3D checks the beats","propPreset(name, options?)":"a prop preset by name (did-you-mean on a wrong one)","propTarget({ …, style: 'stick' })":"line art to go with stick figures: tubes as single strokes, shapes outlined over paper","propTow({ leader, leaderId, leaderTracks, hitch, towed, towedId, anchor, start, end })":"a prop towed by another (a cart behind a horse): turns with it, its wheels roll exactly","propTarget({ x, y, prop, scale?, values?, look?, ink? })":"a canvas target that draws a prop (x, y: its middle on the ground; scale px per metre, default 60)","propScript(id, prop, beats, { from, ground, scale, style?, exaggeration?, start? })":"beats → acted tracks, with contact times and effect cues; checkPropBeats(beats, prop) checks them","drawProp(ctx, target, frame, id, { rider? })":"draw it as it is in a frame (a rider is drawn between its far and near parts)","propAt(target, frame, id).anchor(name)":"where an anchor (seat, door, chimney…) is, in scene px","propRide({ prop, propId, propTracks, anchor, figure, figureId, start, end, offset? })":"a figure carried at an anchor, turning with the prop; spliceTracks() puts it into the figure’s tracks","drawPropEffects(ctx, effects, time)":"dust, exhaust, skid marks, honk lines, leaves, smoke"},beatFields:Fi,commonControls:Object.fromEntries(Object.entries(kn).map(([s,i])=>[s,`${i.description}${i.unit?` (${i.unit})`:""}`])),commonActions:Object.fromEntries(Object.entries(Sa).map(([s,i])=>[s,i.summary])),presets:Object.fromEntries(Object.entries(Tn).map(([s,i])=>{const o=i();return[s,{family:o.family,summary:o.summary,actions:Object.fromEntries(Object.entries(o.actions).map(([r,a])=>[r,{summary:a.summary,...a.needs?{needs:a.needs}:{}}])),controls:Object.keys(o.rig.controls),anchors:Object.keys(o.rig.anchors??{})}]}))},custom:{api:{"defineAction({ summary, needs?, steps: (from, beat) => [{ after, pose, easing? }] })":"a new action written as timed pose steps from the current pose, like a gag","defineAction({ summary, needs?, beats: (beat) => [beats] })":"a new action built from other beats (which may be custom too)","defineGait({ swing, knee, arm, elbow, lean, cycle?, … })":"a new gait (the Gait fields in degrees; cycle is ms per two steps)","scriptTracks(id, beats, { actions, gaits })":"beats may then use those names; checkBeats(beats, { actions, gaits }) knows them","stickFigureTarget({ …, cast: { actions, gaits } })":"a figure that draws the gaits and lists the actions in describeTarget","persona({ name, summary?, height?, look?, acting?, gait?, mood?, stance?, energy?, actions?, gaits? })":"a character’s look, acting style and habits: .figure({ x, y }), .script(id, beats, { from, ground }), .check(beats), .handPath(…), .describe(); `go` walks in its gait, `stand` returns to its stance and face"},actions:Object.fromEntries(Object.entries(e.actions??{}).map(([s,i])=>[s,{summary:i.summary,...i.needs?{needs:i.needs}:{}}])),gaits:Object.fromEntries(Object.entries(e.gaits??{}).map(([s,i])=>[s,i.summary??"custom gait"]))},character:{poses:Object.keys(Re),expressions:Object.keys(rr),gags:Object.keys(gi)},codePanel:{languages:Mi,removeStyles:ki,anchors:{"line(n, time?)":"line n’s text box { x, y, left, right, top, bottom, width, height }: stand on top, point at x, y","token(n, text, occurrence?, time?)":"a word on a line","spot(n, column, width?, time?)":"a place in a line, for put and write","landing(piece, n, column)":"where a dropped piece will land",box:"the whole panel"},edits:jr},surfaces:{code:ns,board:ne,chart:Fe,prop:Mn},surfaceScript:{"surfaceScript(figureId, { name: surface }, beats, options)":"compiles beats that act on surfaces: returns the script result with `tracks` (the figure’s, ridden, then every surface’s, keyed by its name) and `figureTracks`; options are scriptTracks’ plus `figureStyle` (for carry) and `ride` (default true)","checkSurfaceBeats(beats, surfaces, cast?)":"every problem checkBeats finds, plus unknown surfaces, places, edits and moments, with suggestions","{ surface, anchor }":"a named place, where a beat takes `target` (its box), `to` (its centre x) or `onto` (its top); as laid out, before any edit moves it","then: { surface, edit, anchor, at?, until?, …options }":"what the surface does in answer to the beat (or a list of them): one of its edits, or `carry` (the piece follows the hand until `until`); the other fields are the edit’s options",at:`a moment of the beat: ${bn.join(", ")} (default contact, or start when the beat has none); not ms`,until:"a moment of this beat, or { beat: index, at? } of a later one; sets the edit’s duration (carry needs it)"},cameraShots:{frame:"{ at, duration?, easing?, frame: { focus?: { x, y }, scale?, rotate? } }: push in, pull out, or cut (duration 0)",shake:"{ at, duration, shake: { strength?, frequency?, roll?, seed? } }",follow:"{ at, until, follow: { x: <the subject’s x keyframes>, lead?, y?, lag?, scale? } }: keeps a subject centred"},teach:{"lesson({ id })":"steps as timeline JSON: to, set, together, wait, marker (with pause, question, captions)","cells, pointer, stack, queue, table, pipeline":"diagram primitives (SVG markup + step helpers)","figure({ width, height, children })":"the SVG holding the pieces"},cli:{"tinyfly capabilities [--json]":"this catalog","tinyfly check <beats.json>":"check a beat script (names, fields) with suggestions","tinyfly validate <timeline.json> [--markup file]":"check a timeline against its markup","tinyfly render <timeline.json> <markup> [--at …]":"a frame as static markup","tinyfly video <scene.mjs> [--stills dir --times …]":"MP4, or PNG stills to look at"}}}const It=t=>t.map(e=>`\`${e}\``).join(", "),Tf=t=>Object.entries(t).map(([e,n])=>`| \`${e}\` | ${n.unit??n.kind??""} | ${n.description} |`).join(`
|
|
63
|
-
`);function
|
|
64
|
-
`)}function gk(t,e,n,s={}){const i=s.color??"#555",o=s.size??60;for(const r of e){const a=(n-r.time)/r.length;if(a<=0||a>=1)continue;const l=qt(`${r.kind}:${r.time}:${r.x}`);r.kind==="dust"?Zd(t,{x:r.x,y:r.y},a,{size:o,color:i,seed:l}):r.kind==="exhaust"?bk(t,r,a,o,i,l):r.kind==="skid"?wk(t,r,a,n,i):r.kind==="honk"?kk(t,r,a,o,i):r.kind==="smoke"?mk(t,r,n,o,i):r.kind==="leaves"&&yk(t,r,a,o,s.leafColor??"#5cae5a",i,l)}}function mk(t,e,n,s,i,o){const r=e.direction??1,a=380,l=1500;t.save(),t.strokeStyle=i,t.lineWidth=Math.max(1,s*.025);for(let c=e.time;c<=e.time+e.length-l;c+=a){const h=(n-c)/l;if(h<=0||h>=1)continue;const d=Math.sin(c/97+h*4)*s*.06,u=e.x+r*h*s*.7+d,f=e.y-h*s*1.6;t.globalAlpha=Math.min(1,h*6)*(1-h)*.85,t.beginPath(),t.arc(u,f,s*(.07+h*.2),0,Math.PI*2),t.stroke()}t.restore()}function yk(t,e,n,s,i,o,r){const a=e.direction??1,l=e.toY??e.y+s*3;t.save(),t.lineWidth=Math.max(1,s*.02),t.strokeStyle=o,t.fillStyle=i;for(let c=0;c<4;c++){const h=qt(`${r}:${c}`)%1e3/1e3,d=Math.min(1,n*(1.1+h*.4)),u=e.x+(h-.5)*s*1.2,f=e.y+(h-.3)*s*.4,g=d*d*.4+d*.6,p=u+a*d*s*(.6+h)+Math.sin(d*9+h*6)*s*.18,m=Math.min(l-2,f+(l-f)*g);t.globalAlpha=n>.85?(1-n)/.15:1,t.save(),t.translate(p,m),t.rotate(Math.sin(d*7+h*5)*1.2),t.beginPath(),t.ellipse(0,0,s*.07,s*.035,0,0,Math.PI*2),t.fill(),t.stroke(),t.restore()}t.restore()}function bk(t,e,n,s,i,o){const r=e.direction??-1;t.save(),t.strokeStyle=i,t.lineWidth=Math.max(1,s*.025);for(let a=0;a<3;a++){const l=n*1.6-a*.25;if(l<=0||l>=1)continue;const c=(qt(`${o}:${a}`)%100/100-.5)*s*.1,h=e.x+r*l*s*.9,d=e.y-l*s*.45+c;t.globalAlpha=(1-l)*.9,t.beginPath(),t.arc(h,d,s*(.06+l*.14),0,Math.PI*2),t.stroke()}t.restore()}function wk(t,e,n,s,i){const o=e.toX??e.x,r=Math.min(1,(s-e.time)/e.length*3),a=e.x+(o-e.x)*r;t.save(),t.strokeStyle=i,t.lineCap="round",t.globalAlpha=n<.6?.8:.8*(1-(n-.6)/.4),t.lineWidth=3;for(const l of[-2,4])t.beginPath(),t.moveTo(e.x,e.y+l),t.lineTo(a,e.y+l),t.stroke();t.restore()}function kk(t,e,n,s,i){const o=e.direction??1;t.save(),t.strokeStyle=i,t.lineWidth=Math.max(1.5,s*.04),t.lineCap="round",t.globalAlpha=n<.7?1:(1-n)/.3;const r=s*(.15+.5*(1-(1-n)**2));for(let a=-1;a<=1;a++){const l=a*Math.PI/7,c=e.x+o*Math.cos(l)*r,h=e.y+Math.sin(l)*r;t.beginPath(),t.arc(c,h,s*.12,o>0?-Math.PI/3:Math.PI*2/3,o>0?Math.PI/3:Math.PI*4/3),t.stroke()}t.restore()}function vk(t){const e=new Ht({id:`${t.propId}-ride`,tracks:t.propTracks.filter(h=>h.target===t.propId)}),n=t.every??33,s=[],i=[],o=[],r=[];let a=1;for(let h=t.start;;h=Math.min(t.end,h+n)){const d=Hi(t.prop,{state:e.getStateAtTime(h)},t.propId),u=d.anchor(t.anchor);s.push({time:h,value:u.x+(t.offset?.x??0)-t.figure.x}),i.push({time:h,value:u.y+(t.offset?.y??0)-t.figure.y});const f=Math.sin(d.values.turn*Math.PI/2);if(Math.abs(f)>.15&&(a=f>0?1:-1),o.push({time:h,value:Math.abs(f)}),r.push({time:h,value:a}),h>=t.end)break}const l=t.figureId,c=[{id:`${l}-x`,target:l,property:"x",keyframes:s},{id:`${l}-y`,target:l,property:"y",keyframes:i}];return t.turn!==!1&&c.push({id:`${l}-turn`,target:l,property:"turn",keyframes:o},{id:`${l}-facing`,target:l,property:"facing",keyframes:Mk(r)}),c}function Mk(t){const e=[];for(const n of t){const s=e[e.length-1];s&&s.value!==n.value&&e.push({time:n.time-1,value:s.value}),(!s||s.value!==n.value||n===t[t.length-1])&&e.push(n)}return e}function Sk(t,e,n){const s=r=>`${r.target}\0${r.property}`,i=new Map(e.map(r=>[s(r),r]));return[...t.map(r=>{const a=i.get(s(r));if(!a)return r;i.delete(s(r));const c=[...(r.keyframes??[]).filter(h=>h.time<n.from||h.time>n.to),...a.keyframes??[]].sort((h,d)=>h.time-d.time);return{...r,keyframes:c}}),...i.values()]}function Tk(t){const e=new Ht({id:`${t.leaderId}-tow`,tracks:t.leaderTracks.filter(f=>f.target===t.leaderId)}),n=t.every??33,s=t.towed,i=s.x+s.width/2,o=s.props,r=s.prop.wheelRadius,a=[],l=[],c=[];let h=o.wheelSpin??0,d;for(let f=t.start;;f=Math.min(t.end,f+n)){const g=Hi(t.leader,{state:e.getStateAtTime(f)},t.leaderId),p=g.anchor(t.hitch),m=g.values.turn,b=vn(s.prop,{...o,turn:m},s.propScale).anchors[t.anchor];if(!b)throw new Error(`propTow: ${s.prop.kind} has no anchor "${t.anchor}"`);const S=p.x-b.point.x;if(d!==void 0&&r){const k=Math.sin(m*Math.PI/2);h+=(S-d)*(k||1)/s.propScale/r*(180/Math.PI)}if(d=S,a.push({time:f,value:S-i}),l.push({time:f,value:m}),c.push({time:f,value:h}),f>=t.end)break}const u=t.towedId;return[{id:`${u}-x`,target:u,property:"x",keyframes:a},{id:`${u}-turn`,target:u,property:"turn",keyframes:l},...r?[{id:`${u}-wheelSpin`,target:u,property:"wheelSpin",keyframes:c}]:[]]}const Ef=new WeakMap;function Ek(t,e){const n=e?.some(Boolean)?e.map(u=>u?1:0).join(""):"";let s=Ef.get(t);s||Ef.set(t,s=new Map);const i=s.get(n);if(i)return i;const o=hs(t),r={vertices:o.vertices,faces:o.faces.filter((u,f)=>!e?.[f])},a=r.vertices.flatMap(u=>[u[0],u[1],u[2]]),l=r.vertices.map(()=>[0,0,0]),c=[];r.faces.forEach(u=>{for(const p of u.corners)for(const m of[0,1,2])l[p][m]+=u.normal[m];const[f,...g]=u.corners;for(let p=0;p+1<g.length;p++){const[m,b,S]=[f,g[p],g[p+1]],[k,y,M]=[r.vertices[m],r.vertices[b],r.vertices[S]],$=[y[0]-k[0],y[1]-k[1],y[2]-k[2]],E=[M[0]-k[0],M[1]-k[1],M[2]-k[2]],A=[$[1]*E[2]-$[2]*E[1],$[2]*E[0]-$[0]*E[2],$[0]*E[1]-$[1]*E[0]],T=A[0]*u.normal[0]+A[1]*u.normal[1]+A[2]*u.normal[2];c.push(...T>=0?[m,b,S]:[m,S,b])}});const h=l.flatMap(u=>{const f=Math.hypot(...u)||1;return[u[0]/f,u[1]/f,u[2]/f]}),d=ai({positions:a,normals:h,indices:c});return s.size>=16&&s.clear(),s.set(n,d),d}function Ak(t,e,n={}){const s=t.ink??n.ink??"#26262b",i=(n.outline??2)*(t.outline??1),o=t.glow&&e.glow>0?$k(t.glow.color,e.glow):void 0;return{color:t.fill??s,creases:hs(t.shape).creases!==!1,shading:n.shading??"toon",...i>0?{outline:{width:i,color:s}}:{},...o?{emissive:o}:{},...t.seeThrough?{opacity:.45*e.opacity}:e.opacity<1?{opacity:e.opacity}:{}}}function $k(t,e){const n=/^#([0-9a-f]{6})$/i.exec(t.trim());return n?`#${[0,2,4].map(i=>Math.round(parseInt(n[1].slice(i,i+2),16)*Math.max(0,Math.min(1,e)))).map(i=>i.toString(16).padStart(2,"0")).join("")}`:t}const Pk=ai(Gh(1,.002,28));function xk(t,e,n){const s=t.rig,[i,o]=s.footprint??[s.length*.45,s.length],r=Math.max(0,ft(s,e,"lift")),a=Math.max(0,ft(s,e,"size"))/(1+r*.8);return{mesh:Pk,world:mt(n,bo([0,.004,0],[0,0,0,1],[i*.55*a||1e-4,1,o*.55*a||1e-4])),material:{color:"#000000",shading:"unlit",opacity:.16*a}}}const Ik=new Set(["x","y","z","position","rotateX","rotateY","rotateZ","quaternion","scale","scaleX","scaleY","scaleZ","visible","opacity","color"]),Ok=1,_k={kind:"prop",validate(t){const e=t,n=typeof e.prop=="string"&&e.prop in Tn?[]:[ot("prop preset",e.prop,Object.keys(Tn))];for(const[s,i]of[[0,"rotateX"],[1,"rotateY"],[2,"rotateZ"]])i in e&&n.push(`${i} is a track, not a field: place it turned with rotation: [${[0,1,2].map(o=>o===s?e[i]:0).join(", ")}]`);return n},prepare(t){const e=t;return kf(e.prop,e.options)},resolve({object:t,prepared:e,values:n,world:s,camera:i,lights:o=[],fog:r,toScreen:a}){const l=t,c=e,h={...l.values};for(const[E,A]of n)typeof A=="number"&&!Ik.has(E)&&(h[E]=A);h.turn=0,h.tilt=0;const d=mt(i.view,s),u={toView:E=>Rt(d,E),toScreen:E=>a(E)},f=u.toView([0,c.rig.height/2,0]);if(-f[2]<=i.near)return null;if(l.look==="mesh"){const E=Wu(c.rig,h),A=E.map(({part:v,local:P})=>({part:v.id,mesh:hs(v.shape),...ua(hs(v.shape),P)})),T=Lu(A),I=E.map((v,P)=>({...v,hidden:Du(v.part.id,A[P].mesh,v.local,A[P].key,T)})).filter(({opacity:v})=>v>.01).map(({part:v,matrix:P,glow:H,opacity:O,hidden:C})=>({mesh:Ek(v.shape,C),world:mt(s,P),material:Ak(v,{glow:H,opacity:O},{shading:l.shading,ink:l.ink,outline:l.outline})}));return{meshes:l.shadow===!1?I:[xk(c,h,s),...I]}}const g=a(f),p=a(u.toView([0,c.rig.height/2+1,0])),m=Math.hypot(p.x-g.x,p.y-g.y),b=o.length===0?void 0:(E,A)=>{const T=Rt(s,E),I=[s[0]*A[0]+s[4]*A[1]+s[8]*A[2],s[1]*A[0]+s[5]*A[1]+s[9]*A[2],s[2]*A[0]+s[6]*A[1]+s[10]*A[2]],v=Math.hypot(...I)||1;return{light:rd(T,[I[0]/v,I[1]/v,I[2]/v],o),fog:ad(r,Math.hypot(T[0]-i.position[0],T[1]-i.position[1],T[2]-i.position[2]))}},S=ya(c.rig,h,u,m,{perspective:!0,near:i.near,slice:Ok,light:b}),k={look:l.look,style:l.style,ink:l.ink,paper:l.paper,fog:r?.color},y=Sr(S),M=S.cells??[],$=Math.max(...M.map(E=>-E.depth),-f[2]);return{drawables:[...l.shadow===!1?[]:[{depth:$+c.rig.length,draw:E=>Tr(E,S,k)}],...M.map(E=>({depth:-E.depth,draw(A,T){A.lineCap="round",A.lineJoin="round",ld(A,E.parts,y,{...k,time:T.time})}}))]}}},Ea=["do","at","for","to","through","toward","speed","height","open","on","wind"],Ck=.25,Hk=800/180,Rk=220,Lk=300,Nk=["turn"];function Dk(t){const e=ji(t),n=Object.keys(t.moves??{});return Object.keys(e).filter(s=>!n.includes(s)&&!Nk.includes(s)&&!(e[s].needs??[]).includes("to"))}function Af(t,e){if(!Array.isArray(t))return[{beat:-1,message:`Beats must be an array of { do: … } objects (got ${typeof t}).`}];const n=Object.keys(e.moves??{}),s=Dk(e),i=[...n,"face","hold",...s.filter(r=>r!=="hold")],o=[];return t.forEach((r,a)=>{const l=d=>o.push({beat:a,message:d});if(!r||typeof r!="object"||Array.isArray(r))return l(`Each beat must be an object like { do: '${i[0]??"hold"}' }.`);const c=r,h={duration:"for",path:"through",points:"through",position:"to",heading:"toward",direction:"toward"};for(const d of Object.keys(c))Ea.includes(d)||l(ot("beat field",d,Ea,h[d]));if(typeof c.do!="string"||!i.includes(c.do)){const d=c.do==="turn"?"face":void 0;return l(ot(`${e.kind} 3D beat`,c.do,i,d))}n.includes(c.do)&&(c.to===void 0&&c.through===void 0&&l(`\`${c.do}\` needs \`to\` ([x, z] metres) or \`through\` (a list of them).`),c.to!==void 0&&!Le(c.to)&&l(`\`to\` is a point on the ground, [x, z] metres (got ${JSON.stringify(c.to)}).`),c.through!==void 0&&!(Array.isArray(c.through)&&c.through.length>0&&c.through.every(Le))&&l("`through` is a list of points on the ground, each [x, z] metres.")),c.do==="face"&&!(Le(c.toward)||typeof c.toward=="number")&&l("`face` needs `toward`: a point [x, z] or a heading in degrees.")}),o}function Fk(t,e,n,s){const i=Af(n,e);if(i.length>0)throw new Error(`propScript3D (${e.kind}): ${i.length} problem(s) in the beats:
|
|
58
|
+
`)}`)}A1(Na);function Wk(t){const e="steps"in t&&typeof t.steps=="function",n="beats"in t&&typeof t.beats=="function";if(e===n)throw new Error("defineAction: give either `steps: (from, beat) => [...]` or `beats: (beat) => [...]`");if(!t.summary)throw new Error("defineAction: give a `summary`: one line on what the figure does");return t}function Bk(t){for(const e of["swing","knee","arm","elbow","lean"])if(typeof t[e]!="number")throw new Error(`defineGait: \`${e}\` must be a number (degrees)`);if(t.cycle!==void 0&&!(t.cycle>0))throw new Error("defineGait: `cycle` is ms per two steps, above 0");return t}const Cd=8;function Qi(t,e={},n=0){if(n>Cd)throw new Error(`scriptTracks: custom actions nest more than ${Cd} deep (does one build itself?)`);return t.flatMap(s=>{const i=e[s.do];if(!i||!("beats"in i))return[s];const o=i.beats(s).map((r,a)=>a===0?{...r,...s.at!==void 0&&r.at===void 0?{at:s.at}:{},...s.mood&&!r.mood?{mood:s.mood}:{},...s.say&&!r.say?{say:s.say}:{}}:r);return Qi(o,e,n+1)})}function Hd(t){return t.length===0?0:Math.max(...t.map(e=>e.after))}const Wa={walk:1e3,bouncy:900,doubleBounce:1100,sneak:1600,strut:1100,tired:1500,shove:1300,run:560},jk=450,qk=2.4,Yk=160,Rd=2.5,Kk=200,zk=340,Xk=1.1,Ld=[380,900],Gk=.35,to=300,Ba=150,Uk=260,Vk=1.2,ja=160,Fd=400,As=300,Jk=450,Nd=500,qa=350,Dd=150,Zk=120,Ya=180,Wd=420,Qk=300,Bd=300,t2=140,Ka=150,jd=450,e2=450,za=150,qd=350,Yd=400,n2=12,s2=600,Kd=90,zd=400,i2=200,o2=.09,Xd=350,fe=450,Xa=1200,r2=700,$n=320,ge=220,a2=65,l2=700,Gd=t=>t in _e,c2=t=>t in jt;function Ud(t){return Math.max(l2,Array.from(t).length*a2)}function Ga(t,e,n={}){const s={actions:n.actions,gaits:n.gaits};Da(e,s);const i=n.gait??"walk",o=Qi(e,n.actions).map(O=>O.do==="go"?{...O,do:i}:O);Da(o,s,"scriptTracks (after expanding custom actions)");const r=O=>Ht[O]??n.gaits?.[O],a=O=>Wa[O]??n.gaits?.[O]?.cycle??1e3,l=O=>{const L=n.actions?.[O];return L&&"steps"in L?L:void 0},c=n.from??0,h=n.ground??0,u=n.height??300;let d=c,f=h,p=n.facing??1,g=n.start??et,m=0,y=0;const T=[{time:0,pose:g}],k=[{time:0,value:0}],b=[{time:0,value:0}],A=[{time:0,value:0}],M=[{time:0,value:0}],E=[{time:0,value:"walk"}],x=[{time:0,value:p}],S=[],I=[],v=[],$=(O,L,q,G)=>{g={...g,...L},q&&(g=Ee(g,q)),T.push({time:O,pose:g,...G===!1?{act:G}:{}})},_=(O,L,q)=>($(O+$n/2,{turn:0},q),x.push({time:O+$n/2,value:p},{time:O+$n/2+1,value:L}),p=L,$(O+$n,{turn:1}),O+$n),P=O=>O<d?-1:1,C=(O,L,q)=>P(L)!==p?_(O,P(L),q):O,F=(O,L,q,G="arm")=>{const K=G==="arm",Z=Ae({...O,...K?{rightShoulder:0,rightElbow:0}:{rightHip:0,rightKnee:0}},{height:u,facing:p}),nt=K?Z.shoulders.right:Z.hip,W=K?Z.elbows.right:Z.knees.right,z=(Q,tt)=>Math.atan2(p*Q,tt)*180/Math.PI,V=((z(L-(d+nt.x),q-(f+nt.y))-z(W.x-nt.x,W.y-nt.y))%360+360)%360;return V>270?V-360:V},R=(O,L,q,G)=>{const K=G==="arm",Z=Ae({...O,...K?{rightShoulder:90,rightElbow:0,rightWrist:0}:{rightHip:90,rightKnee:0}},{height:u,facing:p}),nt=K?Z.shoulders.right:Z.hip,W=K?{x:(Z.hands.right.x+Z.fingertips.right.x)/2,y:(Z.hands.right.y+Z.fingertips.right.y)/2}:Z.feet.right,z=Math.hypot(W.x-nt.x,W.y-nt.y),Y=q-(f+nt.y),V=Math.abs(Y)<z?Math.sqrt(z*z-Y*Y):z*.1;return L-nt.x-p*V},B=O=>{const L=Ae(O,{height:u,facing:p});return{x:d+(L.hands.right.x+L.fingertips.right.x)/2,y:f+(L.hands.right.y+L.fingertips.right.y)/2}},j=(O,L,q)=>{const G={...O,rightWrist:0,rightElbow:0,rightShoulder:F(O,L,q)},K=Ae(G,{height:u,facing:p}),Z={x:d+K.shoulders.right.x,y:f+K.shoulders.right.y},nt={x:d+K.elbows.right.x,y:f+K.elbows.right.y},W=B(G),z=Math.hypot(nt.x-Z.x,nt.y-Z.y),Y=Math.hypot(W.x-nt.x,W.y-nt.y),V=Math.min(z+Y-.01,Math.max(Math.abs(z-Y)+.01,Math.hypot(L-Z.x,q-Z.y))),Q=rt=>rt*180/Math.PI,tt=Q(Math.acos((z*z+V*V-Y*Y)/(2*z*V))),st=180-Q(Math.acos((z*z+Y*Y-V*V)/(2*z*Y)));let yt={rightShoulder:G.rightShoulder,rightElbow:0},ut=1/0;for(const rt of[1,-1])for(const St of[1,-1]){const J={rightShoulder:G.rightShoulder+rt*tt,rightElbow:St*st},Tt={...O,rightWrist:0,...J},bt=B(Tt),U=Math.hypot(bt.x-L,bt.y-q)-Ae(Tt,{height:u,facing:p}).elbows.right.y*.001;U<ut&&(ut=U,yt=J)}return yt},H=(O,L,q)=>Math.abs(L-d)<2?O:(k.push({time:O,value:d-c},{time:O+q,value:L-c,easing:"ease-in-out"}),d=L,O+q);for(const O of o){const L=Math.max(O.at??y,y===0?0:T[T.length-1].time);let q=L,G,K;const Z=O.pose??{},nt=l(O.do);if(r(O.do)){const W=O.to??d,z=W===d?p:P(W);let Y=L;z!==p?Y=_(L,z,O.mood):g.turn<1?(Y=L+ge,$(Y,{turn:1,...Z},O.mood)):(O.mood||O.pose)&&$(L+ge,Z,O.mood);const Q=Math.abs(W-d)/br(r(O.do),u),tt=O.for??Math.max(ge*2,Q*a(O.do)),st=Y+tt;E.push({time:Y,value:O.do}),M.push({time:Y,value:0},{time:Y+ge,value:1,easing:"ease-out"}),M.push({time:st-ge,value:1},{time:st,value:0,easing:"ease-in"}),A.push({time:Y,value:m},{time:st,value:m+Q}),k.push({time:Y,value:d-c},{time:st,value:W-c}),m+=Q,d=W,$(st,{}),q=st}else if(O.do==="zip"){const W=O.to??d,z=W===d?p:P(W);let Y=L;z!==p?Y=_(L,z,O.mood):g.turn<1&&(Y=L+ge,$(Y,{turn:1},O.mood));const V=Ca("windUp",{at:Y,from:O.mood?Ee(g,O.mood):g});T.push(...V),g=V[V.length-1].pose;const Q=Y+Ms("windUp"),tt=Q+jk,st=tt+Math.max(Yk,Math.abs(W-d)/qk);E.push({time:Q,value:"run"}),M.push({time:Q,value:0},{time:Q+80,value:1,easing:"ease-out"},{time:st,value:1},{time:st+120,value:0}),A.push({time:Q,value:m},{time:tt,value:m+Rd,easing:"ease-in"}),m+=Rd+(st-tt)/Wa.run*1.5,A.push({time:st,value:m}),k.push({time:tt,value:d-c},{time:st,value:W-c,easing:"ease-in"}),v.push({kind:"dust",time:tt,x:d,y:f,length:900}),d=W,$(st,{}),q=st}else if(O.do==="leap"){const W=O.to??d,z=O.onto??f;let Y=W===d?L:C(L,W,O.mood);g.turn<1&&(Y+=ge,$(Y,{turn:1},O.mood));const V={leftShoulder:35,rightShoulder:35,leftElbow:-50,rightElbow:-50};$(Y+Kk,{stretch:.75,bend:12,leftHip:22,rightHip:22,...V},O.mood,!1);const Q=Y+zk;$(Q-40,{stretch:.72},void 0,!1),$(Q,{stretch:1.2,bend:-6,leftShoulder:140,rightShoulder:140,leftElbow:20,rightElbow:20,leftHip:4,rightHip:4},void 0,!1);const tt=Math.hypot(W-d,z-f),st=O.for??Math.min(Ld[1],Math.max(Ld[0],300+tt*Xk)),yt=Math.min(f,z)-Gk*u,ut=Math.sqrt(f-yt),rt=Math.sqrt(z-yt),St=Q+st*ut/(ut+rt),J=Q+st;$(St,{stretch:1,bend:4,leftHip:-55,leftKnee:-80,rightHip:55,rightKnee:80,leftShoulder:110,rightShoulder:110},void 0,!1),$(J,{stretch:.72,bend:12,leftShoulder:75,rightShoulder:75,leftElbow:0,rightElbow:0,leftHip:18,rightHip:18,leftKnee:0,rightKnee:0},void 0,!1),$(J+180,{stretch:1.05,bend:-3},void 0,!1),$(J+340,{stretch:1,bend:0,leftHip:et.leftHip,rightHip:et.rightHip,leftShoulder:et.leftShoulder,rightShoulder:et.rightShoulder,leftElbow:et.leftElbow,rightElbow:et.rightElbow},void 0,!1),k.push({time:Q,value:d-c},{time:J,value:W-c}),b.push({time:Q,value:f-h},{time:St,value:yt-h,easing:"ease-out-quad"},{time:J,value:z-h,easing:"ease-in-quad"}),d=W,f=z,v.push({kind:"dust",time:J,x:d,y:f,length:500}),q=J+340,G=J}else if(O.do==="point"&&O.target){const W=O.target,z=C(L,W.x,O.mood),Y={...g,...O.mood?ct[O.mood]:{},turn:Math.max(g.turn,.6),rightElbow:0,rightWrist:0,...Z},V=Ae(Y,{height:u,facing:p}).head.center,Q=Math.abs(W.x-(d+V.x)),tt=W.y-(f+V.y),st=z+fe;$(st,{...Y,rightShoulder:F(Y,W.x,W.y),lookX:1,lookY:h2(tt/Math.max(1,Math.hypot(Q,tt)))*.8}),q=st+(O.for??Xa),G=st,K=q}else if(O.do==="swipe"){const W=O.target??{x:d+p*u*.5,y:f-u*.6},z=P(W.x),Y=C(L,W.x,O.mood),V=z===1?W.left??W.x:W.right??W.x,Q=z===1?W.right??W.x:W.left??W.x,tt={...g,turn:1,lean:-10,bend:-8,rightElbow:40,lookX:1,...Z};$(Y+to,{...tt,rightShoulder:F(tt,d-p*u*.3,f-u*1.1)},O.mood,!1);const st={...g,lean:6,bend:4,rightElbow:0,rightWrist:0},yt={...g,lean:14,bend:12,rightElbow:0,rightWrist:0};H(Y,R(st,V,W.y,"arm"),to+Ba),$(Y+to+Ba,{lean:-12},void 0,!1);const ut=Y+to+Ba+80;$(ut,{...st,rightShoulder:F(st,V,W.y)},void 0,!1);const rt=ut+(O.for??Math.max(Uk,Math.abs(Q-V)/Vk));k.push({time:ut,value:d-c}),d=R(yt,Q,W.y,"arm"),k.push({time:rt,value:d-c}),$(rt,{...yt,rightShoulder:F(yt,Q,W.y)},void 0,!1),$(rt+ja,{lean:16,bend:14,rightShoulder:F(g,Q+z*u*.4,W.y+u*.25)},void 0,!1),$(rt+ja+Fd,{lean:0,bend:0,rightShoulder:et.rightShoulder,rightElbow:et.rightElbow}),q=rt+ja+Fd,G=ut,K=rt}else if(O.do==="grab"&&O.target){const W=O.target,z=C(L,W.x,O.mood),Y=W.y>f-u*.5,V={...g,turn:1,rightElbow:0,bend:Y?35:0,lean:Y?12:0,stretch:Y?.75:1,lookX:1,lookY:Y?.8:0,...Z},tt=H(z,R(V,W.x,W.y,"arm"),As)+Jk;$(tt,{...V,rightShoulder:F(V,W.x,W.y)},O.mood,!1),$(tt+120,{},void 0,!1),$(tt+Nd,{bend:0,lean:-3,stretch:1,rightShoulder:165,rightElbow:20,lookY:-.6}),q=tt+Nd+150,G=tt}else if(O.do==="throw"){const W=O.target?.x??O.to??d+p*u,z=C(L,W,O.mood),Y={...g,turn:1,lean:-12,bend:-10,rightElbow:60,stretch:.95,lookX:1,lookY:-.3,...Z};$(z+qa,{...Y,rightShoulder:F(Y,d-p*u*.4,f-u*1.05)},O.mood,!1),$(z+qa+Dd,{lean:-14},void 0,!1);const V=z+qa+Dd+Zk,Q={...g,lean:14,bend:12,rightElbow:0,stretch:1.04};T.push({time:V,pose:g={...Q,rightShoulder:F(Q,d+p*u,f-u*1.1)},easing:"ease-in",act:!1}),$(V+Ya,{lean:18,bend:14,rightShoulder:55,stretch:1},void 0,!1),$(V+Ya+Wd,{lean:0,bend:0,rightShoulder:et.rightShoulder,rightElbow:et.rightElbow,lookY:0}),q=V+Ya+Wd,G=V,K=V}else if(O.do==="kick"&&O.target){const W=O.target,z=C(L,W.x,O.mood),Y={...g,turn:1,lean:-12,bend:-6,rightKnee:0,leftShoulder:100,rightShoulder:70},V=H(z,R(Y,W.x,W.y,"leg"),Qk),Q={leftShoulder:70,rightShoulder:50,leftElbow:-20,rightElbow:20};$(V+Bd,{turn:1,lean:8,bend:6,rightHip:-40,rightKnee:80,lookX:1,lookY:.7,...Q,...Z},O.mood,!1);const tt=V+Bd+t2,st=F(Y,W.x,W.y,"leg");T.push({time:tt,pose:g={...g,...Y,rightHip:st},easing:"ease-in",act:!1}),$(tt+Ka,{lean:-15,rightHip:st+20},void 0,!1),$(tt+Ka+jd,{lean:0,bend:0,rightHip:et.rightHip,rightKnee:0,leftShoulder:et.leftShoulder,rightShoulder:et.rightShoulder,leftElbow:et.leftElbow,rightElbow:et.rightElbow,lookY:0}),q=tt+Ka+jd,G=tt}else if(O.do==="put"&&O.target){const W=O.target,z=C(L,W.x,O.mood),Y=W.y>f-u*.5,V={...g,turn:1,rightElbow:0,rightWrist:0,bend:Y?35:0,lean:Y?12:0,stretch:Y?.75:1,lookX:1,lookY:Y?.8:0,...Z},tt=H(z,R(V,W.x,W.y,"arm"),As)+e2;$(tt,{...V,rightShoulder:F(V,W.x,W.y)},O.mood,!1),$(tt+za,{},void 0,!1),$(tt+za+qd,{bend:0,lean:0,stretch:1,rightShoulder:et.rightShoulder,rightElbow:et.rightElbow,lookY:0}),q=tt+za+qd,G=tt}else if(O.do==="write"&&O.target){const W=O.target,z=W.left??W.x,Y=W.right??W.x,V=C(L,(z+Y)/2,O.mood),Q={...g,turn:1,rightElbow:0,rightWrist:0,...ct.thinking,lookX:1,lookY:0,...Z},tt=bt=>R(Q,bt,W.y,"arm")+p*u*.08,st=bt=>{const X=B({...Q,...j(Q,bt,W.y),rightWrist:0});return Math.hypot(X.x-bt,X.y-W.y)<2},yt=p===1?z:Y,ut=H(V,tt((z+Y)/2),As),rt=!st(z)||!st(Y),St=rt?H(ut,tt(z),As)+Yd:ut+Yd;$(St,{...Q,...j(Q,rt?z:yt,W.y)},O.mood,!1);const J=O.for??Math.max(s2,Math.abs(Y-z)*n2);rt&&k.push({time:St,value:d-c});for(let bt=Kd,X=0;bt<=J;bt+=Kd,X++){const U=z+(Y-z)*Math.min(bt,J)/J;rt&&(d=tt(U),k.push({time:St+bt,value:d-c}));const lt=(X%2===0?-1:1)*u*.02;$(St+bt,j(Q,U,W.y+lt),void 0,!1)}const Tt=St+J;$(Tt,j(Q,Y,W.y),void 0,!1),$(Tt+zd,{rightShoulder:et.rightShoulder,rightElbow:et.rightElbow,...ct.happy}),q=Tt+zd,G=St,K=Tt}else if(O.do==="push"&&O.target){const W=O.target,z=O.to??W.x,Y=C(L,d+(z>=W.x?1:-1),O.mood),V=p===1?W.left??W.x:W.right??W.x,Q={...g,turn:1,lean:16,bend:8,rightWrist:0,leftWrist:0,lookX:1,...Z},tt=R(Q,V,W.y,"arm"),st=H(Y,tt+p*u*.06,As),yt=j(Q,V,W.y),ut={...Q,...yt,leftShoulder:-yt.rightShoulder,leftElbow:-yt.rightElbow},rt=st+i2;$(rt,ut,O.mood,!1);const St=Math.abs(z-W.x),J=rt+(O.for??Math.max(600,St/o2)),Tt=St/br("shove",u);E.push({time:rt,value:"shove"}),M.push({time:rt,value:0},{time:rt+ge,value:1,easing:"ease-out"},{time:J-ge,value:1},{time:J,value:0,easing:"ease-in"}),A.push({time:rt,value:m},{time:J,value:m+Tt}),m+=Tt,k.push({time:rt,value:d-c},{time:J,value:d+(z-W.x)-c}),d+=z-W.x,$(J,{},void 0,!1),$(J+Xd,{lean:0,bend:0,rightShoulder:et.rightShoulder,leftShoulder:et.leftShoulder,rightElbow:et.rightElbow,leftElbow:et.leftElbow}),q=J+Xd,G=rt,K=J}else if(nt){const W=O.mood?Ee(g,O.mood):g,z=nt.steps(W,O),Y=Ha(z,{at:L,from:W});T.push(...Y),g=Y[Y.length-1].pose,q=L+Math.max(Hd(z),O.for??0)}else if(Gd(O.do)){const W=Ca(O.do,{at:L,from:O.mood?Ee(g,O.mood):g});T.push(...W),g=W[W.length-1].pose,q=L+Ms(O.do),O.do==="take"&&v.push({kind:"dust",time:L+900,x:d,y:f,length:500}),O.do==="land"&&v.push({kind:"dust",time:L+120,x:d,y:f,length:500})}else if(O.do==="look"||O.do==="face"){const W=O.toward??"viewer",z=O.for??r2;if(W==="viewer")$(L+fe,{turn:0,lookX:0,lookY:0,...Z},O.mood);else if(W==="ahead")$(L+fe,{turn:O.do==="face"?1:.6,lookX:1,...Z},O.mood);else if(W==="back")$(L+fe,{turn:.2,lookX:-1,...Z},O.mood);else{const Y=P(W);Y!==p&&O.do==="face"?(_(L,Y,O.mood),$(L+$n+1,{lookX:1,...Z})):Y!==p?$(L+fe,{turn:.25,lookX:-1,...Z},O.mood):$(L+fe,{turn:O.do==="face"?1:.6,lookX:1,...Z},O.mood)}q=L+Math.max(z,fe)}else if(c2(O.do)||O.do==="stand"){const W=O.do==="stand"?n.rest??et:jt[O.do],z=W.turn!==et.turn?W.turn:g.turn,Y=O.mood?ct[O.mood]:{lookX:g.lookX,lookY:g.lookY};$(L+fe,{...W,turn:z,...Y,...Z}),q=L+(O.for??Xa)}else{const W=O.for??(O.say?Ud(O.say):Xa);(O.mood||O.pose)&&$(L+Math.min(fe,W/2),Z,O.mood),q=L+W}if(O.say){const W=r(O.do)||Gd(O.do)||nt?L:L+Math.min(150,(q-L)/4),z=r(O.do)?q:Math.max(W+200,q-100);S.push({text:O.say,start:W,end:z}),O.do==="say"&&f2(T,g,W,z)}O.onto!==void 0&&O.do!=="leap"&&O.onto!==f&&(b.push({time:L,value:f-h},{time:q,value:O.onto-h,easing:"ease-in-out"}),f=O.onto),q>T[T.length-1].time&&T.push({time:q,pose:g}),I.push({start:L,end:q,...G!==void 0?{contact:G}:{},...K!==void 0?{release:K}:{}}),y=q}const N=kd(t,d2(T),n),D=[{id:`${t}-x`,target:t,property:"x",keyframes:k},{id:`${t}-y`,target:t,property:"y",keyframes:b},{id:`${t}-walk`,target:t,property:"walk",keyframes:A},{id:`${t}-walking`,target:t,property:"walking",keyframes:M},{id:`${t}-gait`,target:t,property:"gait",keyframes:E},{id:`${t}-facing`,target:t,property:"facing",keyframes:x}].filter(O=>O.keyframes.length>1||O.property==="x"||O.property==="facing"&&O.keyframes[0].value===-1);return{tracks:[..._d(t,N,S,{energy:n.energy}),...D],duration:y,lines:S,keys:T,beats:I,effects:v}}const h2=t=>Math.max(-1,Math.min(1,t)),u2=30;function d2(t){const e=[];for(const n of t){const s=e[e.length-1];s&&n.time-s.time<u2?e[e.length-1]={...n,time:s.time}:e.push(n)}return e}function f2(t,e,n,s){const o=t.filter(l=>l.time>n),r=t.filter(l=>l.time<=n),a=[];for(let l=n+520,c=0;l<s-520/2;l+=520,c++){const h=c%2===0?3:-2;a.push({time:l,pose:{...e,headTilt:e.headTilt+h,leftBrow:e.leftBrow+(c%2===0?.25:0),rightBrow:e.rightBrow+(c%2===0?.25:0)}})}a.length>0&&a.push({time:s,pose:e}),t.length=0,t.push(...r,...a.filter(l=>!o.some(c=>Math.abs(c.time-l.time)<60)),...o),t.sort((l,c)=>l.time-c.time)}function Ua(t,e,n){const s=new Nt({id:`${t}-hand`,tracks:e.filter(l=>l.target===t)}),i=Sr({x:n.x,y:n.y,style:n.style,cast:n.cast}),o=n.side??"right",r=n.every??33,a=[];for(let l=n.start;;l=Math.min(n.end,l+r)){const{joints:c}=Tr(i,{time:l,state:s.getStateAtTime(l)},t),h=c.hands[o],u=c.fingertips[o];if(a.push({time:l,x:(h.x+u.x)/2,y:(h.y+u.y)/2}),l>=n.end)break}return a}const Pn=["start","contact","release","end"],g2=["surface","edit","anchor","at","until"],p2=["carry"],eo=t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&"surface"in t&&"anchor"in t,m2=t=>t.then===void 0?[]:Array.isArray(t.then)?t.then:[t.then];function y2(t,e,n,s={}){const i=Vd(n,e,s).filter(d=>d.level==="error");if(i.length>0)throw new Error(`surfaceScript: ${i.length} problem(s) in the beats:
|
|
59
|
+
${i.map(d=>` ${d.beat>=0?`beat ${d.beat}: `:""}${d.message}`).join(`
|
|
60
|
+
`)}`);const o=n.map(d=>Jd(d,e)),r=Ga(t,o,s),a=b2(o,r.beats,s),l=s.ground??0,c=d=>s.ride===!1?d:Object.values(e).reduce((f,p)=>p.ride(f,t,{ground:l}),d);n.forEach((d,f)=>{for(const p of m2(d)){const g=b=>new Error(`surfaceScript: beat ${f} (${d.do}), ${p.edit} on ${p.surface}: ${b}`),m=(b,A)=>{const M=typeof b=="object"?b.beat:f,E=(typeof b=="object"?b.at:b)??A??"start",x=a[M][E];if(x===void 0){const S=Pn.filter(I=>a[M][I]!==void 0).join(", ");throw g(`beat ${M} (${n[M].do}) has no ${E} (it has ${S})`)}return x},y=e[p.surface],T=m(p.at??(a[f].contact!==void 0?"contact":"start")),k=p.until===void 0?void 0:m(p.until,"end");if(k!==void 0&&k<T)throw g(`it ends (${k} ms) before it starts (${T} ms)`);try{if(p.edit==="carry"){const A=y.piece(p.anchor),M=Ua(t,c(r.tracks),{x:s.from??0,y:l,style:s.figureStyle??(s.height?{height:s.height}:void 0),cast:s,start:T,end:k});y.follow(A,M);continue}const b=Object.fromEntries(Object.entries(p).filter(([A])=>!g2.includes(A)));y.edit(p.edit,p.anchor,{...b,at:T,...k!==void 0?{duration:k-T}:{}})}catch(b){throw g(b.message)}}});const h=c(r.tracks),u=Object.entries(e).flatMap(([d,f])=>f.tracks(d));return{...r,tracks:[...h,...u],figureTracks:h}}function Vd(t,e,n={}){if(!Array.isArray(t))return Es(t,n);const s=[],i=Object.keys(e),o=(c,h,u)=>{const d=typeof h=="string"?e[h]:void 0;return d||s.push({level:"error",beat:c,message:`${u}: ${ot("surface",h,i)}`}),d},r=(c,h,u,d)=>{if(typeof u!="string"){s.push({level:"error",beat:c,message:`${d}: \`anchor\` is a place name such as ${Object.keys(h.about.anchors).join(", ")} (got ${JSON.stringify(u)}).`});return}try{h.anchor(u,0)}catch(f){s.push({level:"error",beat:c,message:`${d}: ${f.message}`})}},a=(c,h,u)=>{const d=typeof h=="object"&&h!==null?h.at:h;if(typeof h=="object"&&h!==null){const f=h.beat;if((typeof f!="number"||!Number.isInteger(f)||f<c||f>=t.length)&&s.push({level:"error",beat:c,message:`${u}: \`beat\` is the index of this beat or a later one, ${c} to ${t.length-1} (got ${JSON.stringify(f)}).`}),d===void 0)return}typeof d=="number"?s.push({level:"error",beat:c,message:`${u}: a cue starts at a moment of its beat (${Pn.join(", ")}), not at ms; set the beat's own \`at\` to move it.`}):(typeof d!="string"||!Pn.includes(d))&&s.push({level:"error",beat:c,message:`${u}: ${ot("moment",d,Pn)}`})};t.forEach((c,h)=>{if(!c||typeof c!="object"||Array.isArray(c))return;const u=c;for(const f of["target","to","onto"]){if(!eo(u[f]))continue;const p=u[f],g=o(h,p.surface,`\`${f}\``);g&&r(h,g,p.anchor,`\`${f}\``)}if(u.then===void 0)return;(Array.isArray(u.then)?u.then:[u.then]).forEach(f=>{if(!f||typeof f!="object"||Array.isArray(f)){s.push({level:"error",beat:h,message:"`then` is a cue, { surface, edit, anchor, at?, until? }, or a list of them."});return}const p=f,g=o(h,p.surface,"`then`");if(!g)return;const m=`\`then\` (${String(p.edit)} on ${String(p.surface)})`,y=[...Object.keys(g.about.edits),...p2];if(typeof p.edit!="string"||!y.includes(p.edit)){s.push({level:"error",beat:h,message:`\`then\`: ${ot("edit",p.edit,y)}`});return}for(const T of Array.isArray(p.anchor)?p.anchor:[p.anchor])r(h,g,T,m);p.edit==="carry"&&typeof p.anchor!="string"&&s.push({level:"error",beat:h,message:`${m}: \`carry\` takes one anchor, the piece it carries.`}),p.edit==="carry"&&p.until===void 0&&s.push({level:"error",beat:h,message:`${m}: \`carry\` needs \`until\` (when it lets go, such as { beat: ${h+1}, at: 'release' }).`}),p.at!==void 0&&a(h,p.at,`${m} \`at\``),p.until!==void 0&&a(h,p.until,`${m} \`until\``),p.until!==void 0&&p.duration!==void 0&&s.push({level:"error",beat:h,message:`${m}: give \`until\` or \`duration\`, not both.`})})});const l=t.map(c=>c&&typeof c=="object"&&!Array.isArray(c)?Jd(c,e,!0):c);return[...Es(l,n),...s]}function Jd(t,e,n=!1){const{then:s,...i}=t,o=a=>{try{return e[a.surface].anchor(a.anchor,0)}catch(l){if(n)return{x:0,y:0,left:0,right:0,top:0,bottom:0,width:0,height:0};throw l}},r={...i};return eo(t.target)&&(r.target=o(t.target)),eo(t.to)&&(r.to=o(t.to).x),eo(t.onto)&&(r.onto=o(t.onto).top),r}function b2(t,e,n){let s=0;return t.map(i=>{const o=Qi([i],n.actions).length,r=e.slice(s,s+o);s+=o;const a=r.find(c=>c.contact!==void 0)?.contact,l=[...r].reverse().find(c=>c.release!==void 0)?.release;return{start:r[0]?.start,end:r[r.length-1]?.end,...a!==void 0?{contact:a}:{},...l!==void 0?{release:l}:{}}})}function w2(t){const e={actions:t.actions,gaits:t.gaits},n=Fa(e);if(n.length>0)throw new Error(`persona "${t.name}": ${n.join(" ")}`);const s=[...Object.keys(Ht),...Object.keys(t.gaits??{})],i=t.gait??"walk";if(!s.includes(i))throw new Error(`persona "${t.name}": ${ot("gait",i,s)}`);if(t.mood&&!(t.mood in ct))throw new Error(`persona "${t.name}": ${ot("mood",t.mood,Object.keys(ct))}`);const o=t.acting??"snappy";if(typeof o=="string"&&!(o in Ze))throw new Error(`persona "${t.name}": ${ot("acting style",o,Object.keys(Ze))}`);if(typeof t.stance=="string"&&!(t.stance in jt))throw new Error(`persona "${t.name}": ${ot("stance",t.stance,Object.keys(jt))}`);const r=t.height??120,a=typeof t.stance=="string"?jt[t.stance]:Pt(t.stance??{}),l=t.mood?Ee(a,t.mood):a,c={...t.look,height:r},h=t.summary??`${t.name}, a stick figure`;return{name:t.name,summary:h,cast:e,rest:l,height:r,figure:u=>Sr({x:u.x,y:u.y,pose:l,style:{...c,...u.facing?{facing:u.facing}:{}},cast:e}),script:(u,d,f={})=>Ga(u,d,{...e,from:f.from,ground:f.ground,facing:f.facing,height:r,style:o,gait:i,start:l,rest:l,energy:t.energy}),check:u=>Es(u,e),handPath:(u,d,f)=>Ua(u,d,{...f,style:c,cast:e}),describe:()=>({name:t.name,summary:h,habits:{height:r,acting:typeof o=="string"?o:"custom",gait:i,...t.mood?{mood:t.mood}:{},stance:typeof t.stance=="string"?t.stance:t.stance?"custom":"rest"},actions:Na(e),own:{actions:Object.keys(t.actions??{}),gaits:Object.keys(t.gaits??{})}})}}const at=["rect","circle","text","line","path","image","custom"],no={x:{description:"Moves it right by this much from where it was placed (an offset; the target’s own x is its place)",unit:"px",types:at},y:{description:"Moves it down by this much from where it was placed (an offset)",unit:"px",types:at},opacity:{description:"How opaque it is",unit:"0..1",min:0,max:1,types:at},rotate:{description:"Turns it clockwise about its origin",unit:"degrees",types:at},rotateX:{description:"Tips it about the horizontal axis (3D; shows with perspective)",unit:"degrees",types:at},rotateY:{description:"Turns it about the vertical axis (3D; shows with perspective)",unit:"degrees",types:at},z:{description:"Depth toward the viewer (shows with perspective)",unit:"px",types:at},perspective:{description:"Distance from the viewer: nearer parts grow, further ones shrink",unit:"px",min:1,types:at},scale:{description:"Size, both ways",unit:"factor",types:at},scaleX:{description:"Width factor",unit:"factor",types:at},scaleY:{description:"Height factor",unit:"factor",types:at},skewX:{description:"Slants it sideways",unit:"degrees",types:at},skewY:{description:"Slants it up and down",unit:"degrees",types:at},originX:{description:"Transform pivot across its box",unit:"% (0 left, 50 centre, 100 right)",min:0,max:100,types:at},originY:{description:"Transform pivot down its box",unit:"% (0 top, 50 centre, 100 bottom)",min:0,max:100,types:at},fill:{description:"Fill colour (also written fillStyle)",kind:"color",types:at},stroke:{description:"Outline colour (also written strokeStyle)",kind:"color",types:at},strokeWidth:{description:"Outline width (also written lineWidth)",unit:"px",min:0,types:at},clipTop:{description:"Hides this much from the top edge, for reveals",unit:"% of its height",min:0,max:100,types:at},clipRight:{description:"Hides this much from the right edge",unit:"% of its width",min:0,max:100,types:at},clipBottom:{description:"Hides this much from the bottom edge",unit:"% of its height",min:0,max:100,types:at},clipLeft:{description:"Hides this much from the left edge",unit:"% of its width",min:0,max:100,types:at},blur:{description:"Gaussian blur",unit:"px",min:0,types:at},brightness:{description:"Brightness factor (1 unchanged)",unit:"factor",min:0,types:at},glow:{description:"Soft glow around it, in glowColor",unit:"px",min:0,types:at},glowColor:{description:"Colour of the glow",kind:"color",types:at},shadowX:{description:"Drop shadow offset right",unit:"px",types:at},shadowY:{description:"Drop shadow offset down",unit:"px",types:at},shadowBlur:{description:"Drop shadow softness",unit:"px",min:0,types:at},shadowColor:{description:"Drop shadow colour",kind:"color",types:at},shine:{description:"A highlight sweeping across the fill",unit:"0..1 (progress)",min:0,max:1,types:at},drawOn:{description:"How much of the outline is drawn, for drawing a shape on; the fill appears when it is complete",unit:"0..1",min:0,max:1,types:["rect","circle","line","path"]},width:{description:"Box width",unit:"px",min:0,types:["rect","image"]},height:{description:"Box height",unit:"px",min:0,types:["rect","image"]},borderRadius:{description:"Rounded corners",unit:"px",min:0,types:["rect","image"]},radius:{description:"Circle radius",unit:"px",min:0,types:["circle"]},x2:{description:"Line end, x",unit:"px",types:["line"]},y2:{description:"Line end, y",unit:"px",types:["line"]},d:{description:"SVG path data; tween between paths to morph",kind:"string",types:["path"]},text:{description:"The text shown (a text track types or scrambles it)",kind:"string",types:["text"]},fontSize:{description:"Font size",unit:"px",min:0,types:["text"]},fontWeight:{description:"Font weight",unit:"100..900",min:100,max:900,types:["text"]},motionPath:{description:"Moves it along an SVG path (a motion-path track writes motionPathX/Y and, aligned, rotate)",kind:"string",types:at},quaternion:{description:'A rotation as [x, y, z, w] (a track with interpolation: "slerp")',kind:"list",types:at}},Va={fillStyle:"fill",strokeStyle:"stroke",lineWidth:"strokeWidth",rotateZ:"rotate",motionPathX:"x",motionPathY:"y",motionPathRotate:"rotate"},k2={rotation:"rotate",angle:"rotate",alpha:"opacity",fade:"opacity",color:"fill",colour:"fill",background:"fill",size:"scale",left:"x",top:"y",translateX:"x",translateY:"y",r:"radius",path:"d",content:"text"};function Zd(t){const e=t,n=Object.entries(no).filter(([,i])=>i.types.includes(t.type)).map(([i,{types:o,...r}])=>({name:i,...r,...e[i]!==void 0&&typeof e[i]!="object"?{value:e[i]}:{}}));if(t.type!=="custom")return{type:t.type,properties:n};const s=t.about;for(const[i,o]of Object.entries(t.props??{}))n.push({name:i,description:s?.props?.[i]?.description??"",...s?.props?.[i],value:o});return{type:"custom",...s?{kind:s.kind,summary:s.summary}:{},properties:n,...s?.actions?{actions:s.actions}:{}}}function Qd(t){const e=Zd(t).properties.map(n=>n.name);return[...e,...Object.keys(Va).filter(n=>e.includes(Va[n]))]}function v2(t,e){const n=[],s=Object.keys(e);for(const i of t){const o=d=>n.push({level:"error",track:i.id,message:d}),r=e[i.target];if(!r){o(ot("target",i.target,s));continue}const a=Qd(r),l=r.type==="custom"&&r.acceptsProp?.(i.property);if(!a.includes(i.property)&&!l){o(`${i.target}: ${ot("property",i.property,a,k2[i.property])}`);continue}const c=i.keyframes??[];for(let d=1;d<c.length;d++)c[d].time<c[d-1].time&&o(`${i.target}.${i.property}: keyframes out of time order (${c[d-1].time} ms, then ${c[d].time} ms).`);const h=no[Va[i.property]??i.property]??r.about?.props?.[i.property],u=h&&(h.kind??"number")==="number";for(const d of c){if(u&&typeof d.value!="number"){o(`${i.target}.${i.property}: values are numbers${h.unit?` (${h.unit})`:""} (got ${JSON.stringify(d.value)} at ${d.time} ms).`);break}if(u&&typeof d.value=="number"&&(h.min!==void 0&&d.value<h.min||h.max!==void 0&&d.value>h.max)){n.push({level:"warning",track:i.id,message:`${i.target}.${i.property}: ${d.value} at ${d.time} ms is outside ${h.min??"−∞"}..${h.max??"∞"}${h.unit?` (${h.unit})`:""}.`});break}}}return n}const In=(t,e)=>t[2]<=-e;function Ja(t,e,n){const s=(-n-t[2])/(e[2]-t[2]);return[t[0]+(e[0]-t[0])*s,t[1]+(e[1]-t[1])*s,-n]}function tf(t,e){if(t.every(s=>In(s,e)))return t;const n=[];return t.forEach((s,i)=>{const o=t[(i+t.length-1)%t.length],r=In(s,e),a=In(o,e);r!==a&&n.push(Ja(o,s,e)),r&&n.push(s)}),n.length>=3?n:[]}function M2(t,e){if(t.every(i=>In(i,e)))return[t];const n=[];let s=[];return t.forEach((i,o)=>{const r=In(i,e);if(o>0){const a=t[o-1],l=In(a,e);l&&!r?(s.push(Ja(a,i,e)),n.push(s),s=[]):!l&&r&&s.push(Ja(a,i,e))}r&&s.push(i)}),s.length>0&&n.push(s),n.filter(i=>i.length>=2)}function ef(t,e,n){const s=e-t;if(!(s>=n*1.5))return[t,e];const i=Math.round(s/n);return Array.from({length:i+1},(o,r)=>t+s*r/i)}function S2(t,e,n){const s=(i,o)=>Math.max(0,Math.min(i.length-2,i.findIndex((r,a)=>a>0&&o<=r)-1));return[s(t,n[0]),s(e,n[2])]}function T2(t,e){const n=s=>{const i=[e[0]*s[0]+e[4]*s[1]+e[8]*s[2],e[1]*s[0]+e[5]*s[1]+e[9]*s[2],e[2]*s[0]+e[6]*s[1]+e[10]*s[2]],o=Math.hypot(...i)||1;return[i[0]/o,i[1]/o,i[2]/o]};return{...t,vertices:t.vertices.map(s=>Dt(e,s)),faces:t.faces.map(s=>({corners:s.corners,normal:n(s.normal)}))}}function so(t,e,n,s){const i=r=>(r[e]-n)*s>=0;if(t.every(i))return t;const o=[];return t.forEach((r,a)=>{const l=t[(a+t.length-1)%t.length];if(i(r)!==i(l)){const c=(n-l[e])/(r[e]-l[e]);o.push([0,1,2].map(h=>h===e?n:l[h]+(r[h]-l[h])*c))}i(r)&&o.push(r)}),o.length>=3?o:[]}function E2(t,e,n){const s=t.faces.map(r=>({points:r.corners.map(a=>t.vertices[a]),normal:r.normal})),i=[],o={x:e.slice(1,-1),z:n.slice(1,-1)};for(let r=0;r+1<e.length;r++)for(let a=0;a+1<n.length;a++){const l=[],c=new Map,h=p=>{const g=p.map(y=>Math.round(y*1e6)).join(",");let m=c.get(g);return m===void 0&&(m=l.length,l.push(p),c.set(g,m)),m},u=[],d=p=>p===0,f=(p,g)=>p+2===g.length;for(const p of s){let g=p.points;d(r)||(g=so(g,0,e[r],1)),g.length&&!f(r,e)&&(g=so(g,0,e[r+1],-1)),g.length&&!d(a)&&(g=so(g,2,n[a],1)),g.length&&!f(a,n)&&(g=so(g,2,n[a+1],-1)),g.length>=3&&u.push({corners:g.map(h),normal:p.normal})}u.length>0&&i.push({cell:[r,a],mesh:{vertices:l,faces:u,creases:t.creases,joined:t.joined,walls:o}})}return i}const A2=new WeakMap,x2=new WeakMap,$2=48,nf=t=>t.map(e=>Math.round(e*1e5)).join(",");function sf(t,e,n,s){let i=t.get(e);i||t.set(e,i=new Map);let o=i.get(n);return o===void 0&&(i.size>=$2&&i.clear(),i.set(n,o=s())),o}function Za(t,e){const n=nf(e);return sf(A2,t,n,()=>{const s=T2(t,e),i=[1/0,1/0,1/0],o=[-1/0,-1/0,-1/0];for(const r of s.vertices)for(const a of[0,1,2])i[a]=Math.min(i[a],r[a]),o[a]=Math.max(o[a],r[a]);return{key:n,inSpace:s,low:i,high:o}})}function P2(t,e){const n=t.map(h=>({...h,...Za(h.mesh,h.local)})),s=[1/0,1/0,1/0],i=[-1/0,-1/0,-1/0];for(const h of n)for(const u of[0,1,2])s[u]=Math.min(s[u],h.low[u]),i[u]=Math.max(i[u],h.high[u]);const o=ef(s[0],i[0],e),r=ef(s[2],i[2],e),a=`${o.join(",")}|${r.join(",")}`,l=n.flatMap(h=>{if(h.high[0]-h.low[0]<=e*2.5&&h.high[2]-h.low[2]<=e*2.5||h.whole||h.mesh.joined||(h.mesh.marks?.length??0)>0){const d=[(h.low[0]+h.high[0])/2,(h.low[1]+h.high[1])/2,(h.low[2]+h.high[2])/2];return[{part:h.part,mesh:h.mesh,cut:!1,cell:S2(o,r,d)}]}return sf(x2,h.inSpace,a,()=>E2(h.inSpace,o,r)).map(d=>({part:h.part,mesh:d.mesh,cut:!0,cell:d.cell}))}),c=(s[1]+i[1])/2;return{pieces:l,middle:([h,u])=>[(o[h]+o[h+1])/2,c,(r[u]+r[u+1])/2]}}const of=.004,Qa=.05,rf=new WeakMap;function I2(t){let e=rf.get(t);return e===void 0&&(e=!t.joined&&!t.walls&&t.faces.length>=4&&t.faces.every(n=>{const s=t.vertices[n.corners[0]];return t.vertices.every(i=>n.normal[0]*(i[0]-s[0])+n.normal[1]*(i[1]-s[1])+n.normal[2]*(i[2]-s[2])<=1e-6)}),rf.set(t,e)),e}const af=new WeakMap;function lf(t){return t.filter(({mesh:e})=>I2(e)).map(({part:e,key:n,inSpace:s,low:i,high:o})=>{let r=af.get(s);return r||(r=s.faces.map(a=>{const l=s.vertices[a.corners[0]];return{normal:a.normal,offset:a.normal[0]*l[0]+a.normal[1]*l[1]+a.normal[2]*l[2]}}),af.set(s,r)),{part:e,key:n,planes:r,low:i,high:o}})}function O2(t,e,n,s){const i=e.reduce((o,r)=>[o[0]+r[0]/e.length,o[1]+r[1]/e.length,o[2]+r[2]/e.length],[0,0,0]);for(const o of s){if(o.part===t||[0,1,2].some(a=>i[a]<o.low[a]-Qa||i[a]>o.high[a]+Qa))continue;if(o.planes.every(a=>{const l=a.normal[0]*n[0]+a.normal[1]*n[1]+a.normal[2]*n[2],c=e.map(u=>a.normal[0]*u[0]+a.normal[1]*u[1]+a.normal[2]*u[2]-a.offset);if(c.every(u=>Math.abs(u)<=of))return l<-.9;const h=Math.abs(l)<.5?Qa:of;return c.every(u=>u<=h)}))return!0}return!1}const cf=new WeakMap;function hf(t,e,n,s,i){const o=`${s}|${i.map(l=>l.key).join(";")}`;let r=cf.get(e);r||cf.set(e,r=new Map);let a=r.get(o);if(!a){r.size>=48&&r.clear();const l=h=>{const u=[n[0]*h[0]+n[4]*h[1]+n[8]*h[2],n[1]*h[0]+n[5]*h[1]+n[9]*h[2],n[2]*h[0]+n[6]*h[1]+n[10]*h[2]],d=Math.hypot(...u)||1;return[u[0]/d,u[1]/d,u[2]/d]},c=e.vertices.map(h=>Dt(n,h));a=e.faces.map(h=>O2(t,h.corners.map(u=>c[u]),l(h.normal),i)),r.set(o,a)}return a}const On={turn:{description:"Which way it faces: 0 toward the viewer, 1 screen-right, 2 away, 3 (or −1) screen-left; in between turns it in 3D",unit:"quarter turns"},tilt:{description:"How far the camera looks down on it: 0 level, 12 the ¾ look, 90 straight down",unit:"degrees",default:12,min:-90,max:90},pitch:{description:"Nose up (+) or down (−), about its middle on the ground",unit:"degrees"},roll:{description:"Tipped onto its right (+) or left (−) side",unit:"degrees"},squash:{description:"Squash and stretch about the ground, keeping its volume: 1 normal, below squashed, above stretched",unit:"factor",default:1,min:.3,max:3},lift:{description:"Off the ground",unit:"metres"},lean:{description:"The top sheared forward (+) or back (−): speed and drag",unit:"shear"},size:{description:"Its size, about the ground: 1 as built, 0 gone (pop it in or out)",unit:"factor",default:1,min:0}},tl=Math.PI/180;function uf(t,e,n){return{toView:s=>_r($e(s,t*90*tl),-e*tl),toScreen:s=>({x:s[0]*n,y:-s[1]*n})}}const df=new WeakMap,xs=t=>io(t),io=t=>{let e=df.get(t);return e||df.set(t,e=G0(t)),e};function mt(t,e,n){return e[n]??t.controls[n]?.default??On[n]?.default??0}function $s(t,e){const n=Math.max(.05,mt(t,e,"squash")),s=1/Math.sqrt(n),o=[1,0,0,0,0,1,mt(t,e,"lean"),0,0,0,1,0,0,0,0,1];return[We([0,mt(t,e,"lift"),0]),Jt(Kt([1,0,0],-mt(t,e,"pitch"))),Jt(Kt([0,0,1],mt(t,e,"roll"))),o,Be([s,n,s]),Be(Array(3).fill(Math.max(0,mt(t,e,"size"))))].reduce((r,a)=>wt(r,a))}function el(t,e){const n=$s(t,e),s=new Map,i=Object.entries(t.controls).flatMap(([r,a])=>(a.bind??[]).map(l=>({value:mt(t,e,r),bind:l}))),o=r=>{const a=s.get(r.id);if(a)return a;const l=r.parent?t.parts.find(h=>h.id===r.parent):void 0;if(r.parent&&!l)throw new Error(`prop rig: part "${r.id}" hangs from "${r.parent}", which is not a part`);let c=wt(l?o(l):n,We(r.at??[0,0,0]));if(r.rotate){const[h,u,d]=r.rotate;h&&(c=wt(c,Jt(Kt([1,0,0],h)))),u&&(c=wt(c,Jt(Kt([0,1,0],u)))),d&&(c=wt(c,Jt(Kt([0,0,1],d))))}for(const{value:h,bind:u}of i)if(!(!u.parts.includes(r.id)||h===0)){if(u.translate&&(c=wt(c,We([u.translate[0]*h,u.translate[1]*h,u.translate[2]*h]))),u.rotate){const d=u.rotate.pivot??[0,0,0],f=u.rotate.axis==="x"?[1,0,0]:u.rotate.axis==="y"?[0,1,0]:[0,0,1];c=[c,We(d),Jt(Kt(f,u.rotate.degrees*h)),We([-d[0],-d[1],-d[2]])].reduce((p,g)=>wt(p,g))}u.scale&&(c=wt(c,Be([1+(u.scale[0]-1)*h,1+(u.scale[1]-1)*h,1+(u.scale[2]-1)*h])))}return s.set(r.id,c),c};for(const r of t.parts)o(r);return s}const nl=(()=>{const t=[-.45,.75,.5],e=Math.hypot(...t);return[t[0]/e,t[1]/e,t[2]/e]})(),_2=Math.cos(35*tl);function sl(t,e,n,s,i={}){const o=t.derive?{...e,...t.derive(e)}:e,r=el(t,o),a=n.toView([0,0,0]),l=P=>C=>[P[0]*C[0]+P[4]*C[1]+P[8]*C[2],P[1]*C[0]+P[5]*C[1]+P[9]*C[2],P[2]*C[0]+P[6]*C[1]+P[10]*C[2]],c=$s(t,o),h=i.slice===void 0?null:Yo(c),u=h?t.parts.map(P=>({part:P,mesh:io(P.shape),local:wt(h,r.get(P.id)),whole:P.shape.type==="tube"})):void 0,d=u?P2(u,i.slice):void 0,f=u?lf(u.map(P=>({part:P.part.id,mesh:P.mesh,...Za(P.mesh,P.local)}))):void 0,p=(P,C,F,R)=>{const B=X=>n.toView(Dt(F,X)),j=C.vertices.map(B),H=j.map(X=>n.toScreen(X)),N=i.perspective?i.near:void 0,D=X=>X.map(U=>n.toScreen(U)),O=X=>N===void 0?X:tf(X,N),L=X=>N===void 0?[X]:M2(X,N),q=l(F),G=C.faces.map(X=>{const U=n.toView(q(X.normal)),lt=[U[0]-a[0],U[1]-a[1],U[2]-a[2]],xt=Math.hypot(...lt)||1;return[lt[0]/xt,lt[1]/xt,lt[2]/xt]}),K=f&&R?hf(P.id,C,R,nf(R),f):void 0,Z=X=>K?.[X]??!1,nt=G.map((X,U)=>{if(Z(U))return!1;if(!i.perspective)return X[2]>1e-6;const xt=C.faces[U].corners.reduce((Ft,It)=>[Ft[0]+j[It][0],Ft[1]+j[It][1],Ft[2]+j[It][2]],[0,0,0]);return-(X[0]*xt[0]+X[1]*xt[1]+X[2]*xt[2])>1e-9}),W=X=>C.faces[X].corners.reduce((U,lt)=>U+j[lt][2],0)/C.faces[X].corners.length,z=C.faces.map((X,U)=>({face:X,i:U})).filter(({i:X})=>nt[X]).map(({face:X,i:U})=>({i:U,solved:{points:N===void 0?X.corners.map(lt=>H[lt]):D(O(X.corners.map(lt=>j[lt]))),depth:W(U),tone:.72+.33*Math.max(0,G[U][0]*nl[0]+G[U][1]*nl[1]+G[U][2]*nl[2])}})).filter(X=>X.solved.points.length>=3).sort((X,U)=>X.solved.depth-U.solved.depth);if(i.light){const X=l(F);for(const{i:U,solved:lt}of z){const xt=C.faces[U].corners,Ft=xt.reduce((gl,r5)=>{const pl=Dt(F,C.vertices[r5]);return[gl[0]+pl[0]/xt.length,gl[1]+pl[1]/xt.length,gl[2]+pl[2]/xt.length]},[0,0,0]),It=X(C.faces[U].normal),en=Math.hypot(...It)||1,sg=i.light(Ft,[It[0]/en,It[1]/en,It[2]/en]);lt.light=sg.light,lt.fog=sg.fog}}const Y=z.map(X=>X.solved),V=C2(C),Q=[],tt=[];for(const[X,U]of V){const lt=U.filter(Ft=>nt[Ft]).length;if(lt===0)continue;const xt=U.length===2&<===2&&C.creases!==!1&&G[U[0]][0]*G[U[1]][0]+G[U[0]][1]*G[U[1]][1]+G[U[0]][2]*G[U[1]][2]<_2;U.length===1&&(C.joined||H2(C,X))||(U.length===1||lt===1||xt)&&(Q.push(X.split("-").map(Number)),tt.push(U.filter(Ft=>nt[Ft]).reduce((Ft,It)=>W(It)>W(Ft)?It:Ft)))}const st=X=>C.faces.findIndex(U=>U.corners.length>4&&Math.sign(L2(C.vertices[X],U.normal))>0),yt=(C.marks??[]).filter(([X])=>st(X)<0||nt[st(X)]),ut=([X,U])=>N===void 0?[[H[X],H[U]]]:L([j[X],j[U]]).map(D),rt=yt.flatMap(ut),St=X=>N===void 0?[X.map(U=>H[U])]:L(X.map(U=>j[U])).map(D);if(i.slice!==void 0){const X=new Map;Q.forEach((U,lt)=>X.set(tt[lt],[...X.get(tt[lt])??[],U]));for(const{i:U,solved:lt}of z){lt.edges=mf(X.get(U)??[]).flatMap(St);const xt=C.faces[U].corners;lt.center=xt.reduce((It,en)=>[It[0]+j[en][0]/xt.length,It[1]+j[en][1]/xt.length,It[2]+j[en][2]/xt.length],[0,0,0]),lt.normal=G[U];const Ft=z[z.length-1].i;lt.marks=yt.filter(([It])=>(st(It)>=0?st(It):Ft)===U).flatMap(ut)}}const J=P.glow?Math.max(0,Math.min(1,mt(t,o,P.glow.control))):0,Tt=P.fade?Math.max(0,Math.min(1,mt(t,o,P.fade.control))):0,bt=P.fade?Math.max(0,Math.min(1,P.fade.from+(P.fade.to-P.fade.from)*Tt)):1;return{part:P,depth:j.reduce((X,U)=>X+U[2],0)/Math.max(1,j.length),faces:Y,edges:mf(Q).flatMap(St),marks:rt,glow:J,opacity:bt,...P.shape.type==="tube"?{spine:R2(L(P.shape.points.map(B)).map(D))}:{},...C.walls?{cut:!0}:{}}},g=new Map(u?.map(P=>[P.part.id,P.local])),y=(d?d.pieces.map(P=>({part:P.part,mesh:P.mesh,m:P.cut?c:r.get(P.part.id),local:P.cut?Gs():g.get(P.part.id),cell:P.cell})):t.parts.map(P=>({part:P,mesh:io(P.shape),m:r.get(P.id),local:void 0,cell:void 0}))).map(P=>({cell:P.cell,solved:p(P.part,P.mesh,P.m,P.local)})),T=y.map(P=>P.solved),k=P=>P.filter(C=>C.faces.length>0&&C.opacity>.01).sort((C,F)=>C.depth-F.depth);let b;if(d){const P=new Map(t.parts.map(F=>{const R=r.get(F.id),B=io(F.shape).vertices;return[F.id,B.reduce((j,H)=>j+n.toView(Dt(R,H))[2],0)/Math.max(1,B.length)]})),C=new Map;for(const F of y){const R=F.cell.join(",");C.has(R)||C.set(R,{cell:F.cell,parts:[]}),C.get(R).parts.push(F.solved),F.solved.depth=P.get(F.solved.part.id)}b=[...C.values()].map(({cell:F,parts:R})=>({depth:n.toView(Dt(c,d.middle(F)))[2],parts:k(R)})).filter(F=>F.parts.length>0)}const A={};for(const[P,C]of Object.entries(t.anchors??{})){const F=C.part?r.get(C.part):$s(t,o);if(!F)throw new Error(`prop rig: anchor "${P}" is on "${C.part}", which is not a part`);const R=n.toView(Dt(F,C.at));A[P]={point:n.toScreen(R),depth:R[2]}}const[M,E]=t.footprint??[t.length*.45,t.length],x=Math.max(0,mt(t,o,"lift")),S=Math.max(0,mt(t,o,"size"))/(1+x*.8),I=Array.from({length:24},(P,C)=>{const F=Math.PI*2*C/24;return n.toView([Math.cos(F)*M*.55*S,0,Math.sin(F)*E*.55*S])}),v=i.perspective?i.near:void 0,$={points:(v===void 0?I:tf(I,v)).map(P=>n.toScreen(P)),opacity:.16*S},_=T.filter(P=>P.part.seeThrough&&P.opacity>.01).flatMap(P=>P.faces.map(C=>C.points));return{under:k(T.filter(P=>!P.part.overRider)),over:k(T.filter(P=>P.part.overRider)),...b?{cells:b}:{},anchors:A,openings:_,shadow:$,pxPerUnit:s,sizePx:t.height*s}}const ff=new WeakMap;function C2(t){let e=ff.get(t);if(!e){e=new Map;for(let n=0;n<t.faces.length;n++){const s=t.faces[n].corners;for(let i=0;i<s.length;i++){const o=s[i],r=s[(i+1)%s.length],a=o<r?`${o}-${r}`:`${r}-${o}`,l=e.get(a);l?l.push(n):e.set(a,[n])}}ff.set(t,e)}return e}function gf(t,e){const n=t.derive?{...e,...t.derive(e)}:e,s=el(t,n),i=Yo($s(t,n))??Gs(),o=r=>Math.max(0,Math.min(1,r));return t.parts.map(r=>{const a=r.fade?o(mt(t,n,r.fade.control)):0;return{part:r,matrix:s.get(r.id),local:wt(i,s.get(r.id)),glow:r.glow?o(mt(t,n,r.glow.control)):0,opacity:r.fade?o(r.fade.from+(r.fade.to-r.fade.from)*a):1}})}function pf(t,e){const n=t.derive?{...e,...t.derive(e)}:e,s=el(t,n),i=$s(t,n),o={};for(const[r,a]of Object.entries(t.anchors??{})){const l=a.part?s.get(a.part):i;if(!l)throw new Error(`prop rig: anchor "${r}" is on "${a.part}", which is not a part`);o[r]=Dt(l,a.at)}return o}function H2(t,e){if(!t.walls)return!1;const[n,s]=e.split("-").map(o=>t.vertices[Number(o)]),i=(o,r)=>r.some(a=>Math.abs(n[o]-a)<1e-6&&Math.abs(s[o]-a)<1e-6);return i(0,t.walls.x)||i(2,t.walls.z)}function R2(t){return t.reduce((e,n)=>!e||n.length>e.length?n:e,void 0)}const L2=(t,e)=>t[0]*e[0]+t[1]*e[1]+t[2]*e[2];function mf(t){const e=t.map(s=>[...s]),n=[];for(;e.length>0;){const s=[...e.shift()];let i=!0;for(;i;){i=!1;for(let o=0;o<e.length;o++){const[r,a]=e[o],l=s[s.length-1],c=s[0];if(r===l)s.push(a);else if(a===l)s.push(r);else if(a===c)s.unshift(r);else if(r===c)s.unshift(a);else continue;e.splice(o,1),i=!0;break}}n.push(s)}return n}function il(t){const e={};for(const[n,s]of Object.entries({...On,...t.rig.controls})){const{bind:i,...o}=s;e[n]=o}return e}function F2(t){const{prop:e}=t,n=t.scale??60,s=e.rig.length*n*1.4,i=e.rig.height*n*1.6,o=il(e),r={};for(const[l,c]of Object.entries(o))r[l]=t.values?.[l]??c.default??0;const a={look:t.look,ink:t.ink,lineWidth:t.lineWidth,pencil:t.pencil,seed:t.seed,style:t.style,paper:t.paper};return{type:"custom",x:t.x-s/2,y:t.y-i,width:s,height:i,props:r,prop:e,propScale:n,propDraw:a,about:{kind:e.kind,summary:e.summary,props:o,actions:Object.fromEntries(Object.entries(e.actions).map(([l,c])=>[l,c.summary]))},draw(l,c,h){const u=c.props??{};l.translate(s/2,i),aa(l,_n(e,u,n),{...a,time:h})}}}function _n(t,e,n){const s=uf(mt(t.rig,e,"turn"),mt(t.rig,e,"tilt"),n);return sl(t.rig,e,s,n)}function oo(t,e,n){const s={...t.props};let i=0,o=0;for(const[l,c]of e.state?.values.get(n)??[])typeof c=="number"&&(l==="x"?i=c:l==="y"?o=c:l in s&&(s[l]=c));const r={x:t.x+t.width/2+i,y:t.y+t.height+o},a=_n(t.prop,s,t.propScale);return{values:s,origin:r,solved:a,anchor(l){const c=a.anchors[l];if(!c)throw new Error(`${t.prop.kind}: no anchor "${l}" (it has ${Object.keys(a.anchors).join(", ")||"none"})`);return{x:r.x+c.point.x,y:r.y+c.point.y,depth:c.depth}}}}function N2(t,e,n,s,i={}){const o=oo(e,n,s);return t.save(),t.translate(o.origin.x,o.origin.y),aa(t,o.solved,{...e.propDraw,time:n.time,rider:i.rider?r=>{r.save(),r.translate(-o.origin.x,-o.origin.y),i.rider(r),r.restore()}:void 0}),t.restore(),o}const Cn={kind:"prop",create:"propSurface(propTarget({ x, y, prop }), { tracks? }): its controls and anchors are those the catalog lists for its preset",anchors:{box:"the prop’s whole box","anchor:NAME":"one of its rig’s anchors (door, seat, branch, ridge…), as posed at the time","part:ID":"one of its parts as seen at the time (window-1, door-left, wheel-0-left…)","control:NAME":"where the parts a control moves or lights are (control:door is the doors, control:lights the lamps)"},edits:{set:"control anchors; { at, value, duration? }: move a control to a value",switch:"control anchors; { at, on?, duration? }: a control to its full value (open, on), or back to its rest value with on: false"}},D2=400,W2=.2;function B2(t,e={}){const{prop:n}=t,s=il(n),i=Object.keys(s),o=Object.keys(n.rig.anchors??{}),r=n.rig.parts.map(m=>m.id),a=ps(),l=ms(a),c=e.tracks?.length?new Nt({id:`${n.kind}-surface`,tracks:e.tracks}):void 0,h=Math.max(0,...(e.tracks??[]).flatMap(m=>m.keyframes.map(y=>y.time))),u=m=>{const y={...t.props};let T=0,k=0;if(c){const b=c.getStateAtTime(Math.min(m,h));for(const A of b.values.values())for(const[M,E]of A)typeof E=="number"&&(M==="x"?T=E:M==="y"?k=E:M in y&&(y[M]=E))}for(const b of i)a.keys(b)?.length&&(y[b]=a.valueAt(b,m));return{values:y,origin:{x:t.x+t.width/2+T,y:t.y+t.height+k}}},d=m=>{const{kind:y,rest:T}=Ve(m),k=b=>Oe(n.kind,m,Cn,b);if(y==="box"){if(T)throw k("box takes no arguments");return{kind:y}}if(y==="anchor"){if(!o.includes(T))throw k(ot(`${n.kind} anchor`,T,o));return{kind:y,name:T}}if(y==="part"){if(!r.includes(T))throw k(ot(`${n.kind} part`,T,r));return{kind:y,name:T}}if(y==="control"){if(!i.includes(T))throw k(ot(`${n.kind} control`,T,i));return{kind:y,name:T}}throw k()},f=m=>{const y=(n.rig.controls[m]?.bind??[]).flatMap(k=>k.parts),T=n.rig.parts.filter(k=>k.glow?.control===m).map(k=>k.id);return new Set([...y,...T])},p=(m,y)=>{const T=d(m),{values:k,origin:b}=u(y);if(T.kind==="box")return Mt(b.x-t.width/2,b.y-t.height,t.width,t.height);const A=_n(n,k,t.propScale);if(T.kind==="anchor"){const x=A.anchors[T.name].point,S=W2*t.propScale;return Mt(b.x+x.x-S/2,b.y+x.y-S/2,S,S)}if(T.kind==="part")return E(new Set([T.name]),`part "${T.name}" is`);const M=f(T.name);if(M.size===0)throw new Error(`${n.kind}: control "${T.name}" moves no parts of its own (it moves the whole ${n.kind}): aim at box`);return E(M,`the parts control "${T.name}" moves are`);function E(x,S){const I=[...A.under,...A.over].filter(C=>x.has(C.part.id)).flatMap(C=>C.faces.flatMap(F=>F.points));if(I.length===0){const C=Number.isFinite(y)?`at ${y} ms`:"after its edits";throw new Error(`${n.kind}: ${S} turned away from the viewer ${C}; aim at an anchor (${o.map(F=>`anchor:${F}`).join(", ")||"none"}) or box`)}const v=I.map(C=>C.x),$=I.map(C=>C.y),_=Math.min(...v),P=Math.min(...$);return Mt(b.x+_,b.y+P,Math.max(...v)-_,Math.max(...$)-P)}},g={kind:"prop",prop:t,about:Cn,target:t,box:Mt(t.x,t.y,t.width,t.height),anchor(m,y=1/0){return p(m,y)},piece(m){throw new Error(`${n.kind}: a prop has no pieces to come loose ("${m}"); change it with edit('set' | 'switch', 'control:NAME', …)`)},edit(m,y,T){if(!(m in Cn.edits))throw ys(n.kind,m,Cn);const k=Array.isArray(y)?y:[y];if(k.length===0)throw new Error(`${n.kind}.edit: ${m} takes at least one control anchor`);for(const b of k){const A=d(b);if(A.kind!=="control")throw new Error(`${n.kind}.edit: ${m} takes control anchors (control:${i.join(", control:")}), not "${b}"`);const M=s[A.name];let E;if(m==="set"){if(typeof T.value!="number"||!Number.isFinite(T.value))throw new Error(`${n.kind}.edit: set needs \`value\`, a number (${A.name}: ${M.description})`);E=T.value}else E=T.on===!1?M.default??M.min??0:M.max??1;a.tween(A.name,u(T.at).values[A.name],E,T,D2)}return g},follow(m,y){return l.follow(m,y),g},fling(m,y){return l.fling(m,y),g},move(m,y){return l.move(m,y),g},ride(m){return m},tracks:a.tracks};return g}const j2={body:"#e8574a",trim:"#3b3b44",glass:"#bfe3f2",tyre:"#2c2c33",hub:"#c9ccd3",light:"#fff4b8",tail:"#ff5a4f",inside:"#3b3640",seat:"#6d5d55"};function pe(t){const e={...j2,...t.colors},n=[],{forwardMost:s,backMost:i,top:o}=yf(t);t.body&&n.push({id:"body",shape:{type:"extrude",profile:t.body,width:t.width},fill:e.body});for(const[h,u]of(t.frame??[]).entries())n.push({id:`frame-${h}`,shape:{type:"tube",points:u.points,radius:u.radius??.035,segments:6},fill:u.color??e.body,outline:.7});for(const[h,u]of(t.windows??[]).entries())for(const d of[1,-1])n.push({id:`window-${h}-${d>0?"left":"right"}`,shape:{type:"panel",points:[[u.from,u.low],[u.to,u.low],[u.to,u.high],[u.from,u.high]],facing:d>0?"left":"right"},at:[d*(t.width/2+.01),0,0],fill:e.glass,outline:.7,seeThrough:!0,glow:t.lights?{control:"lights",color:"#ffe9a3"}:void 0});for(const h of t.extras??[])n.push(h);if(t.cabin){const h=t.cabin.width??t.width*.85;n.push({id:"cabin",shape:{type:"extrude",profile:t.cabin.profile,width:h},fill:e.glass,outline:.9,seeThrough:!0,layer:1});const u=Math.min(...t.cabin.profile.map(([,f])=>f)),d=Math.max(...t.cabin.profile.map(([,f])=>f));for(const[f,p]of(t.cabin.pillars??[]).entries())n.push({id:`pillar-${f}`,shape:{type:"box",size:[h+.02,d-u,.1]},at:[0,(u+d)/2,p],fill:e.body,outline:.8,layer:1})}const r=t.wheels[0]?.radius??.4,a=[];t.wheels.forEach((h,u)=>{const d=h.side===0?[0]:[1,-1],f=h.thickness??(h.style==="spoked"?.05:.26);for(const p of d){const g=`wheel-${u}-${p>0?"left":p<0?"right":"middle"}`;if(a.push({parts:[g],rotate:{axis:"x",degrees:r/h.radius}}),n.push({id:g,shape:{type:"cylinder",radius:h.radius,length:f,axis:"x",segments:20,spokes:h.style==="spoked"?8:0},at:[p*h.side,h.radius,h.forward],fill:h.style==="spoked"?void 0:e.tyre,ink:h.style==="spoked"?e.tyre:void 0,outline:h.style==="spoked"?1.3:1}),h.style!=="spoked")for(const m of p===0?[1,-1]:[p])n.push({id:`${g}-hub${p===0?m>0?"-left":"-right":""}`,parent:g,shape:{type:"cylinder",radius:h.radius*.55,length:.02,axis:"x",segments:14,spokes:5},at:[m*(f/2+.012),0,0],fill:e.hub,outline:.6})}});const l={wheelSpin:{description:"How far the wheels have turned (keyed exactly with the distance driven, so they never skate)",unit:"degrees",bind:a}};if(t.door){const{from:h,to:u,low:d,high:f}=t.door,p=[[h,d],[u,d],[u,f],[h,f]];for(const g of[1,-1]){const m=g>0?"left":"right";n.push({id:`doorway-${m}`,shape:{type:"panel",points:p,facing:g>0?"left":"right"},at:[g*(t.width/2+.004),0,0],fill:e.inside,outline:.5,seeThrough:!0});const y=h+(u-h)*.15,T=h+(u-h)*.55;n.push({id:`seat-back-${m}`,shape:{type:"panel",points:[[y,d+.05],[T,d+.05],[T-.08,f-.06],[y+.06,f-.04]],facing:g>0?"left":"right"},at:[g*(t.width/2+.006),0,0],fill:e.seat,outline:.4}),n.push({id:`door-${m}`,shape:{type:"panel",points:p.map(([k,b])=>[k-u,b]),facing:g>0?"left":"right"},at:[g*(t.width/2+.01),0,u],fill:e.body,outline:.7,overRider:!0})}l.door={description:"Doors open: 0 shut, 1 open (hinged at the front)",unit:"0..1",min:0,max:1,bind:[{parts:["door-left"],rotate:{axis:"y",degrees:-70}},{parts:["door-right"],rotate:{axis:"y",degrees:70}}]}}if(t.lights){const{across:h,low:u,high:d,front:f,back:p}=t.lights,g=(t.lights.size??.32)/2,m=[[-g,u],[g,u],[g,d],[-g,d]];for(const y of[1,-1])n.push({id:`headlight-${y}`,shape:{type:"panel",points:m,facing:"front"},at:[y*h,0,f],fill:e.light,outline:.6,glow:{control:"lights",color:"#ffffff"}}),n.push({id:`taillight-${y}`,shape:{type:"panel",points:m,facing:"back"},at:[y*h,0,p],fill:Di(e.tail,.62),outline:.6,glow:{control:"lights",color:e.tail}});l.lights={description:"Lights on: 0 off, 1 on",unit:"0..1",min:0,max:1}}t.antenna&&(n.push({id:"antenna",shape:{type:"tube",points:[[0,0,0],[0,.75,0]],radius:.018,segments:5},at:t.antenna,fill:e.trim,outline:.6}),n.push({id:"antenna-tip",parent:"antenna",shape:{type:"ellipsoid",radii:[.05,.05,.05],segments:8},at:[0,.77,0],fill:e.tail,outline:.6}),l.antenna={description:"Antenna bend (follow-through: it trails the motion on a spring)",unit:"degrees",bind:[{parts:["antenna"],rotate:{axis:"x",degrees:1}}]});const c={parts:n,controls:l,length:s-i,height:o,footprint:[t.width,s-i],anchors:{...t.seat?{seat:{at:t.seat}}:{},front:{at:[0,o*.45,s]},back:{at:[0,o*.45,i]},roof:{at:[0,o,0]},...t.door?{door:{at:[-t.width/2,(t.door.low+t.door.high)/2,(t.door.from+t.door.to)/2]}}:{},...t.anchors}};return{kind:t.kind??"vehicle",family:"vehicle",summary:t.summary??"A wheeled vehicle",rig:c,actions:q2(t),acting:bf,colors:{body:e.body,ink:"#26262b"},follow:t.antenna?[{control:"antenna",of:"x",per:.9,stiffness:140,damping:7,limit:35}]:void 0,wheelRadius:r,...t.wheels.length>0?{moves:{drive:{speed:t.speed??6,perMetre:{wheelSpin:180/(Math.PI*r)}}}}:{}}}function yf(t){const e=[...(t.body??[]).map(([s])=>s),...(t.frame??[]).flatMap(s=>s.points.map(i=>i[2])),...t.wheels.flatMap(s=>[s.forward+s.radius,s.forward-s.radius])],n=[...(t.body??[]).map(([,s])=>s),...(t.cabin?.profile??[]).map(([,s])=>s),...(t.frame??[]).flatMap(s=>s.points.map(i=>i[1])),...t.wheels.map(s=>s.radius*2)];return{forwardMost:Math.max(...e),backMost:Math.min(...e),top:Math.max(...n)}}const bf={depth:{turn:0,lift:0,lights:0,pitch:1,roll:1,squash:1,lean:1,door:2},limits:{turn:.08,pitch:5,roll:4,lean:.1,squash:.06,door:.12,lift:0},eyes:[],headTurns:{},drift:[]};function ro(t,e,n,s,i,o,r=!1){const a=t.facing()||Math.sign(s-t.x)||1,l=t.values.wheelSpin??0,c=(s-t.x)*a/t.scale;t.set("wheelSpin",e,l),t.move(e,n,s,{easing:i}),t.set("wheelSpin",n,r?l:l+c/o*(180/Math.PI),i)}const wf=.4;function q2(t){const e=t.wheels[0]?.radius??.4,{forwardMost:n,backMost:s}=yf(t),i=(n-s)/2,o=(a,l,c)=>{const h=a.exaggeration;let u=l;return a.facing()!==c&&(u=a.turnTo(u,c>0?"right":"left")),a.key(u+200,{pitch:4*h,squash:1-.07*h,lean:-.1*h},{act:!1,easing:"ease-out"}),ro(a,u,u+200,a.x-c*.15*h*a.scale,"ease-out",e),a.effect({kind:"exhaust",time:u+150,x:a.x-c*i*a.scale,y:a.floor-.3*a.scale,length:900,direction:-c}),u+260},r=(a,l,c)=>{const h=a.exaggeration*(c?1.8:1);a.key(l,{pitch:-5*h,lean:-.08*h,squash:.95},{act:!1,easing:"ease-out"}),a.key(l+380,{pitch:0,lean:0,squash:1})};return{drive:{summary:"Drives to `to`: rocks back and squats, lunges forward stretched, and stops with a nose-dive that settles; wheels roll exactly the distance.",needs:["to"],uses:["speed","for"],run(a,l,c){const h=Math.sign(l.to-a.x);if(h===0)return{end:c};const u=o(a,c,h),d=a.exaggeration,f=Math.abs(l.to-a.x),p=l.for??Math.max(500,f/(l.speed??wf));return a.effect({kind:"dust",time:u,x:a.x-h*i*a.scale,y:a.floor,length:600,direction:-h}),a.key(u+140,{pitch:-1.5*d,squash:1+.05*d,lean:.12*d},{act:!1,easing:"ease-out"}),a.key(u+Math.max(160,p-160),{pitch:0,lean:.08*d,squash:1.02},{act:!1}),ro(a,u,u+p,l.to,"ease-in-out",e),r(a,u+p,!1),{end:u+p+380,contact:u,release:u+p}}},brake:{summary:"Drives toward `to` and slams on the brakes: the wheels lock and it skids the last stretch, nose diving, leaving skid marks.",needs:["to"],uses:["speed","for"],run(a,l,c){const h=Math.sign(l.to-a.x);if(h===0)return{end:c};const u=o(a,c,h),d=a.exaggeration,f=a.x,p=Math.abs(l.to-f),g=l.for??Math.max(600,p/(l.speed??wf*1.2)),m=u+g*.55,y=f+(l.to-f)*.65;return a.key(u+140,{pitch:-1.5*d,squash:1+.06*d,lean:.14*d},{act:!1,easing:"ease-out"}),ro(a,u,m,y,"ease-in",e),a.key(m+80,{pitch:-7*d,lean:-.12*d,squash:.94},{act:!1,easing:"ease-out"}),ro(a,m,u+g,l.to,"ease-out",e,!0),a.effect({kind:"skid",time:m,x:y,toX:l.to,y:a.floor,length:g*.45+1500}),a.effect({kind:"dust",time:u+g,x:l.to+h*i*a.scale,y:a.floor,length:600,direction:h}),r(a,u+g,!0),{end:u+g+380,contact:m,release:u+g}}},bump:{summary:"Hits a bump: squashes, hops up stretched, lands squashed with dust, and springs back.",uses:["for"],run(a,l,c){const h=a.exaggeration;return a.key(c+90,{squash:1-.16*h,pitch:3*h},{act:!1,easing:"ease-out"}),a.key(c+300,{lift:.35*h,squash:1+.12*h,pitch:-3*h},{act:!1,easing:"ease-out"}),a.key(c+540,{lift:0,squash:1-.2*h,pitch:0},{act:!1,easing:"ease-in"}),a.key(c+820,{squash:1}),a.effect({kind:"dust",time:c+540,x:a.x,y:a.floor,length:500}),{end:c+820,contact:c+540}}},honk:{summary:"Honks: a stretch and squash pulse, with honk lines from the front.",run(a,l,c){const h=a.exaggeration;a.key(c+110,{squash:1+.12*h,lean:.04*h},{act:!1,easing:"ease-out"}),a.key(c+240,{squash:1-.06*h,lean:0},{act:!1}),a.key(c+520,{squash:1});const u=a.facing();return a.effect({kind:"honk",time:c+60,x:a.x+(u||1)*i*a.scale,y:a.floor-.7*a.scale,length:700,direction:u||1}),{end:c+520,contact:c+60}}},...t.door?{door:{summary:"Opens the doors (`open: true`) or shuts them (`open: false`).",needs:["open"],run(a,l,c){return a.key(c+450,{door:l.open?1:0}),{end:c+600,contact:c+450}}}}:{},...t.lights?{lights:{summary:"Switches the lights on (`on: true`) or off.",needs:["on"],run(a,l,c){return a.key(c+120,{lights:l.on?1:0},{act:!1}),{end:c+300,contact:c+120}}}}:{}}}function kf(t={}){return pe({kind:"car",summary:"A cartoon car: drives, brakes, bumps, honks, opens its doors, lights up, and turns toward the camera.",body:[[-2,.32],[2,.32],[2.08,.52],[1.98,.82],[1.05,.95],[-1.72,.98],[-2.02,.86],[-2.08,.5]],width:1.8,cabin:{profile:[[-1.5,.94],[.92,.94],[.3,1.52],[-1.22,1.54]],width:1.56,pillars:[-.42]},wheels:[{forward:1.28,side:.8,radius:.4},{forward:-1.28,side:.8,radius:.4}],door:{from:-.4,to:.88,low:.36,high:.92},lights:{across:.58,low:.55,high:.72,front:2.05,back:-2.06},antenna:t.antenna===!1?void 0:[.5,1.5,-1.05],seat:[0,.3,-.15],colors:t.colors})}function vf(t={}){return pe({kind:"truck",summary:"A box truck: drives, brakes, bumps, honks, opens its cab doors, lights up, turns toward the camera.",body:[[-3.2,.5],[3.1,.5],[3.15,.95],[3,1.85],[2.3,2.25],[1.2,2.25],[1.2,1],[-3.2,1]],width:2,cabin:{profile:[[1.6,1.35],[2.95,1.35],[2.85,1.85],[2.3,2.15],[1.6,2.15]],width:2.04},extras:[{id:"cargo",shape:{type:"box",size:[2.1,1.75,4.2]},at:[0,1.9,-1.05],fill:t.cargo??"#f1f1ee"}],wheels:[{forward:2.2,side:.85,radius:.48,thickness:.32},{forward:-1.4,side:.85,radius:.48,thickness:.32},{forward:-2.45,side:.85,radius:.48,thickness:.32}],door:{from:1.4,to:2.25,low:.6,high:1.9},lights:{across:.7,low:.62,high:.82,front:3.13,back:-3.22,size:.28},seat:[0,1.15,1.9],colors:{body:"#2f6fb7",...t.colors}})}function Mf(t={}){return pe({kind:"bus",summary:"A bus: drives, brakes, bumps, honks, opens its front doors, lights its windows, turns toward the camera.",body:[[-4.5,.45],[4.5,.45],[4.6,.9],[4.55,2.9],[4.3,3],[-4.4,3],[-4.55,2.75],[-4.55,.6]],width:2.4,windows:Array.from({length:6},(e,n)=>({from:-4+n*1.18,to:-4+n*1.18+1,low:1.55,high:2.6})),extras:[{id:"windscreen",shape:{type:"panel",points:[[-1.05,1.35],[1.05,1.35],[1.05,2.75],[-1.05,2.75]],facing:"front"},at:[0,0,4.58],fill:"#bfe3f2",outline:.8,seeThrough:!0}],wheels:[{forward:3,side:1,radius:.5,thickness:.34},{forward:-2.8,side:1,radius:.5,thickness:.34}],door:{from:3.2,to:4.2,low:.5,high:2.6},lights:{across:.85,low:.65,high:.85,front:4.6,back:-4.56,size:.3},seat:[0,1.2,3.6],colors:{body:"#f2c230",...t.colors}})}function Sf(t={}){return pe({kind:"tractor",summary:"A tractor: big rear wheels and small front ones turning at their own rates; drives, brakes, bumps, honks.",body:[[-.5,.75],[2,.75],[2.12,1.25],[1.9,1.52],[-.5,1.52]],width:1,cabin:{profile:[[-1.35,1],[-.25,1],[-.25,2.55],[-1.35,2.55]],width:1.35},extras:[{id:"roof",shape:{type:"box",size:[1.55,.1,1.35]},at:[0,2.62,-.8],fill:"#3f9b47"},{id:"exhaust",shape:{type:"tube",points:[[.28,1.5,1.25],[.28,2.35,1.25]],radius:.06,segments:6},fill:"#3b3b44",outline:.7}],wheels:[{forward:-.85,side:.85,radius:.78,thickness:.45},{forward:1.55,side:.7,radius:.42,thickness:.26}],lights:{across:.3,low:1,high:1.18,front:2.1,back:-.52,size:.2},seat:[0,1.25,-.8],colors:{body:"#3f9b47",hub:"#e9c64a",...t.colors}})}function Tf(t={}){const e=t.colors?.body??"#a8743f";return pe({kind:"cart",summary:"A wooden cart on spoked wheels with shafts: rolls when pulled (drive), bumps, tips.",body:[[-1.25,.78],[1.25,.78],[1.35,1.18],[-1.35,1.18]],width:1.4,frame:[{points:[[.5,.9,1],[.5,.95,2.7]],radius:.05,color:e},{points:[[-.5,.9,1],[-.5,.95,2.7]],radius:.05,color:e}],wheels:[{forward:0,side:.82,radius:.66,style:"spoked"}],seat:[0,1.2,0],anchors:{shafts:{at:[0,.95,2.7]}},colors:{body:e,tyre:"#5a3a1f",...t.colors}})}function Ef(t={}){return pe({kind:"train carriage",summary:"A railway carriage: rolls along (drive), brakes, lights its windows, turns toward the camera.",body:[[-4,.72],[4,.72],[4,2.8],[3.6,3.12],[-3.6,3.12],[-4,2.8]],width:2.6,windows:Array.from({length:5},(e,n)=>({from:-3.3+n*1.4,to:-3.3+n*1.4+1,low:1.7,high:2.5})),wheels:[{forward:3,side:1,radius:.36,thickness:.16},{forward:2.2,side:1,radius:.36,thickness:.16},{forward:-2.2,side:1,radius:.36,thickness:.16},{forward:-3,side:1,radius:.36,thickness:.16}],lights:{across:.9,low:1,high:1.2,front:4.01,back:-4.01,size:.22},seat:[0,1,1.5],colors:{body:"#2f7d6d",...t.colors}})}function Af(t={}){const e=t.colors?.body??"#e0473b",n=[0,.32,-.05],s=[0,.86,-.22],i=[0,.9,.42],o=[0,.34,.56],r=[0,.34,-.56];return pe({kind:"bike",summary:"A bicycle: rides (drive) with its wire wheels turning, brakes, bumps, rings its bell (honk).",width:.5,frame:[{points:[r,n]},{points:[n,s]},{points:[s,r]},{points:[s,i]},{points:[n,i]},{points:[i,o]},{points:[[.24,.98,.44],[-.24,.98,.44]],radius:.025,color:"#3b3b44"},{points:[i,[0,.98,.44]],radius:.025,color:"#3b3b44"}],extras:[{id:"saddle",shape:{type:"ellipsoid",radii:[.08,.035,.15],segments:10},at:[0,.89,-.22],fill:"#3b3b44",outline:.7}],wheels:[{forward:.56,side:0,radius:.34,style:"spoked"},{forward:-.56,side:0,radius:.34,style:"spoked"}],seat:[0,.9,-.22],colors:{body:e,tyre:"#2c2c33",...t.colors}})}function xf(t={}){return pe({kind:"motorbike",summary:"A motorbike: rides (drive) with a lunge, brakes into a skid, bumps, honks, lights up.",body:[[-.62,.62],[.42,.62],[.55,.95],[.3,1.02],[-.1,.92],[-.8,.88],[-.86,.72]],width:.4,frame:[{points:[[0,.33,.78],[0,1.05,.5]],radius:.04,color:"#8c8f98"},{points:[[.3,1.08,.48],[-.3,1.08,.48]],radius:.025,color:"#3b3b44"},{points:[[.12,.42,-.2],[.12,.5,-.95]],radius:.04,color:"#8c8f98"}],extras:[{id:"engine",shape:{type:"box",size:[.38,.34,.5]},at:[0,.45,.05],fill:"#5b5f6a",outline:.8}],wheels:[{forward:.78,side:0,radius:.33,thickness:.14},{forward:-.72,side:0,radius:.33,thickness:.14}],lights:{across:0,low:.9,high:1.04,front:.62,back:-.87,size:.14},seat:[0,.92,-.3],colors:{body:"#1f1f26",hub:"#c9ccd3",...t.colors}})}function $f(t={}){const e=t.height??2.4,n=t.trunkRadius??.16,s=t.canopy?.radius??1.1,i=t.canopy?.shape==="tall",o={trunk:"#8a5a3b",leaves:"#5cae5a",...t.colors},r=Ne(t.canopy?.seed??7),a=[{id:"trunk",shape:{type:"tube",points:[[0,0,0],[.06,e*.5,0],[-.02,e,0]],radius:n,segments:8},fill:o.trunk},{id:"branch",parent:"trunk",shape:{type:"tube",points:[[0,0,0],[.45,.4,.1]],radius:n*.45,segments:6},at:[.04,e*.62,0],fill:o.trunk},{id:"canopy",parent:"trunk",shape:{type:"ellipsoid",radii:[s,s*(i?1.35:.88),s],segments:14},at:[-.02,e+s*.55,0],fill:o.leaves}],l=t.canopy?.lobes??7;for(let h=0;h<l;h++){const u=Math.PI*2*h/l+r.next()*.6,d=(r.next()-.25)*s*(i?1.1:.7),f=s*(.48+r.next()*.22),p=[Math.cos(u)*s*.78,d,Math.sin(u)*s*.6];a.push({id:`lobe-${h}`,parent:"canopy",shape:{type:"ellipsoid",radii:[f,f*.86,f],segments:12},at:p,fill:o.leaves})}const c={parts:a,controls:{sway:{description:"The whole tree bending in the wind, about its base",unit:"degrees",bind:[{parts:["trunk"],rotate:{axis:"z",degrees:1}}]},canopySway:{description:"The canopy bending further than the trunk (it trails the sway)",unit:"degrees",bind:[{parts:["canopy"],rotate:{axis:"z",degrees:1,pivot:[0,-s*.8,0]}}]}},length:s*2.2,height:e+s*2,footprint:[s*1.6,s*1.6],anchors:{canopy:{part:"canopy",at:[0,0,0]},top:{part:"canopy",at:[0,s*.9,0]},base:{at:[0,0,0]},branch:{part:"branch",at:[.45,.4,.1]}}};return{kind:t.kind??"tree",family:"plant",summary:t.summary??"A tree: sways in the wind with its canopy trailing, shakes, sheds leaves, pops up.",rig:c,actions:Y2(),acting:Pf,colors:{body:o.leaves}}}const Pf={depth:{sway:1,canopySway:2,size:0,squash:1},limits:{sway:2,canopySway:3,squash:.08},eyes:[],headTurns:{},drift:[]};function Y2(){const t=(e,n,s,i)=>{const o=e.anchor("canopy");e.effect({kind:"leaves",time:n,x:o.x,y:o.y,length:s,direction:i,toY:e.floor})};return{sway:{summary:"Sways in gusts of `wind` (0..1, default 0.5) for `for` ms (default 3000); the canopy trails the trunk, and a strong wind sheds leaves.",uses:["wind","for"],run(e,n,s){const i=n.wind??.5,o=n.for??3e3,r=e.exaggeration,a=260;let l=0;for(let c=a;c<o;c+=a){const h=.55+.45*Math.sin(c/o*Math.PI*2.3),u=Math.sin(c/170)*.35,d=-i*9*r*(h+u*i);e.key(s+c,{sway:d,canopySway:l*1.3},{act:!1,easing:"ease-in-out"}),l=d}if(e.key(s+o,{sway:0,canopySway:0}),i>.45)for(let c=0;c<o;c+=700)t(e,s+c,2200,1);return{end:s+o}}},shake:{summary:"Shakes (something hit it): a quick wobble that dies away, shedding leaves.",uses:["for"],run(e,n,s){const i=n.for??900,o=e.exaggeration,r=6;for(let a=1;a<=r;a++){const l=1-a/(r+1),c=a%2===0?1:-1;e.key(s+i*a/(r+1),{sway:c*5*o*l,canopySway:-c*6*o*l},{act:!1,easing:"ease-in-out"})}return e.key(s+i,{sway:0,canopySway:0}),t(e,s+60,1800,1),t(e,s+260,1800,-1),{end:s+i,contact:s}}},shedLeaves:{summary:"Leaves fall from the canopy for `for` ms (default 2000).",uses:["for"],run(e,n,s){const i=n.for??2e3;for(let o=0;o<i;o+=500)t(e,s+o,2e3,o%1e3===0?1:-1);return{end:s+i}}}}}function If(t={}){const e=t.width??4,n=t.depth??3.2,s=t.wallHeight??2.5,i=t.roofHeight??1.5,o=t.overhang??.25,r={walls:"#f1d9a8",roof:"#b8433a",door:"#7a4b2a",doorway:"#3a2a22",glass:"#bfe3f2",lit:"#ffd66b",chimney:"#9b5a45",...t.colors},a=n/2+.01,l=t.door?.width??.9,c=t.door?.height??1.9,h=t.door?.at??0,u=t.windows??[{at:-1.25,low:1,width:.8,height:.8},{at:1.25,low:1,width:.8,height:.8}],d=[{id:"walls",shape:{type:"box",size:[e,s,n]},at:[0,s/2,0],fill:r.walls},{id:"roof",shape:{type:"extrude",profile:[[-n/2-o,s],[n/2+o,s],[0,s+i]],width:e+o*2},fill:r.roof,layer:1},{id:"doorway",shape:{type:"panel",points:[[0,0],[l,0],[l,c],[0,c]],facing:"front"},at:[h-l/2,0,a-.005],fill:r.doorway,outline:.6,seeThrough:!0},{id:"door",shape:{type:"panel",points:[[0,0],[l,0],[l,c],[0,c]],facing:"front"},at:[h-l/2,0,a+.005],fill:r.door,outline:.8,overRider:!0}];u.forEach((g,m)=>{d.push({id:`window-${m}`,shape:{type:"panel",points:[[-g.width/2,g.low],[g.width/2,g.low],[g.width/2,g.low+g.height],[-g.width/2,g.low+g.height]],facing:"front"},at:[g.at,0,a+.01],fill:r.glass,outline:.8,glow:{control:"lights",color:r.lit}})});for(const g of[1,-1])d.push({id:`side-window-${g>0?"left":"right"}`,shape:{type:"panel",points:[[-.4,1],[.4,1],[.4,1.8],[-.4,1.8]],facing:g>0?"left":"right"},at:[g*(e/2+.01),0,0],fill:r.glass,outline:.8,glow:{control:"lights",color:r.lit}});const f=t.chimney===!1?void 0:{at:t.chimney?.at??e*.28,back:t.chimney?.back??-n*.18};if(f){const g=s+i*(1-Math.abs(f.back)/(n/2+o)),m=s+i+.45;d.push({id:"chimney",shape:{type:"box",size:[.42,m-g+.3,.42]},at:[f.at,(m+g-.3)/2,f.back],fill:r.chimney,layer:1})}const p={parts:d,controls:{door:{description:"The front door open: 0 shut, 1 open",unit:"0..1",min:0,max:1,bind:[{parts:["door"],rotate:{axis:"y",degrees:-80}}]},lights:{description:"The windows lit: 0 dark, 1 lit",unit:"0..1",min:0,max:1}},length:n+o*2,height:s+i+.6,footprint:[e+.6,n+.6],anchors:{door:{at:[h,c/2,a]},doorstep:{at:[h,0,a+.4]},ridge:{at:[0,s+i,0]},...f?{chimney:{at:[f.at,s+i+.5,f.back]}}:{}}};return{kind:t.kind??"house",family:"building",summary:t.summary??"A house: opens its door, lights its windows, puffs chimney smoke, shakes, pops up.",rig:p,actions:K2(!!f),acting:Of,colors:{body:r.walls}}}const Of={depth:{door:1,lights:0,roll:1,squash:1,size:0},limits:{door:.1,roll:1.5,squash:.05},eyes:[],headTurns:{},drift:[]};function K2(t){return{door:{summary:"Opens the front door (`open: true`) or shuts it (`open: false`).",needs:["open"],run(e,n,s){return e.key(s+500,{door:n.open?1:0}),{end:s+650,contact:s+500}}},lights:{summary:"Lights the windows (`on: true`) or puts them out.",needs:["on"],run(e,n,s){return e.key(s+150,{lights:n.on?1:0},{act:!1}),{end:s+300,contact:s+150}}},shake:{summary:"Shakes, as when a door slams or something lands on it: a squash and a wobble that dies away, with dust.",uses:["for"],run(e,n,s){const i=n.for??700,o=e.exaggeration;e.key(s+80,{squash:1-.06*o},{act:!1,easing:"ease-out"});for(let r=1;r<=5;r++){const a=1-r/6;e.key(s+80+i*r/6,{roll:(r%2===0?1:-1)*2.2*o*a,squash:1+.02*a},{act:!1,easing:"ease-in-out"})}return e.key(s+i+80,{roll:0,squash:1}),e.effect({kind:"dust",time:s+80,x:e.x,y:e.floor,length:600}),{end:s+i+80,contact:s+80}}},...t?{smoke:{summary:"Starts smoke puffing from the chimney for `for` ms (default 3000), drifting with the wind; the next beat starts at once (the smoke carries on).",uses:["for","wind"],run(e,n,s){const i=n.for??3e3,o=e.anchor("chimney");return e.effect({kind:"smoke",time:s,x:o.x,y:o.y,length:i+1500,direction:(n.wind??.4)>=0?1:-1}),{end:s+50,release:s+i}}}}:{}}}function _f(t={}){const e={body:"#3f86c8",glass:"#cfeaf5",trim:"#2c2c33",rotor:"#3b3b44",...t.colors},n=2.15,i={parts:[{id:"cabin",shape:{type:"extrude",profile:[[-1.2,.6],[.9,.55],[1.6,.85],[1.65,1.25],[1.2,1.75],[-.6,1.85],[-1.3,1.45]],width:1.5},fill:e.body},{id:"window",shape:{type:"extrude",profile:[[.75,1],[1.6,.95],[1.6,1.3],[1.15,1.72],[.6,1.72]],width:1.54},fill:e.glass,outline:.8},{id:"boom",shape:{type:"tube",points:[[0,1.4,-1.2],[0,1.55,-3.4]],radius:.16,segments:8},fill:e.body},{id:"fin",shape:{type:"extrude",profile:[[-3.55,1.45],[-3.2,1.5],[-3.35,2.25],[-3.6,2.25]],width:.12},fill:e.body},{id:"mast",shape:{type:"tube",points:[[0,1.82,.1],[0,n,.1]],radius:.07,segments:6},fill:e.trim},{id:"rotor-disc",shape:{type:"cylinder",radius:2.4,length:.01,axis:"y",segments:28},at:[0,n+.02,.1],fill:"#c9d4dd",outline:.4,fade:{control:"blur",from:0,to:.45}},{id:"blades",shape:{type:"box",size:[.16,.03,4.8]},at:[0,n+.05,.1],fill:e.rotor,outline:.7,fade:{control:"blur",from:1,to:.3}},{id:"tail-rotor",shape:{type:"box",size:[.04,.9,.12]},at:[.12,1.85,-3.45],fill:e.rotor,outline:.6},{id:"skid-left",shape:{type:"tube",points:[[0,.08,-1.1],[0,.08,1.2],[0,.22,1.45]],radius:.05,segments:6},at:[.7,0,0],fill:e.trim},{id:"skid-right",shape:{type:"tube",points:[[0,.08,-1.1],[0,.08,1.2],[0,.22,1.45]],radius:.05,segments:6},at:[-.7,0,0],fill:e.trim},{id:"strut-left",shape:{type:"tube",points:[[.7,.08,.6],[.55,.62,.5]],radius:.04,segments:5},fill:e.trim},{id:"strut-right",shape:{type:"tube",points:[[-.7,.08,.6],[-.55,.62,.5]],radius:.04,segments:5},fill:e.trim}],controls:{rotor:{description:"How far the rotors have turned (keyed exactly, not acted; the blades blur into a disc when they spin fast)",unit:"degrees",bind:[{parts:["blades"],rotate:{axis:"y",degrees:1}},{parts:["tail-rotor"],rotate:{axis:"x",degrees:3,pivot:[0,0,0]}}]},blur:{description:"How blurred the main rotor is: 0 still blades, 1 a spinning disc",unit:"0..1",min:0,max:1}},length:5.2,height:2.4,footprint:[1.8,3.4],anchors:{seat:{at:[0,.75,.7]},door:{at:[-.76,1,.2]},rotor:{at:[0,n,.1]},skids:{at:[0,0,.2]},hook:{at:[0,.4,0]}}};return{kind:t.kind??"helicopter",family:"aircraft",summary:t.summary??"A cartoon helicopter: spools up and takes off, flies nose-down banking into its moves, hovers with a bob, and lands with a squash.",rig:i,actions:z2(),acting:ol,colors:{body:e.body,ink:"#26262b"},moves:{fly:{speed:15,flies:!0,hold:{blur:1},perSecond:{rotor:He*1e3}}}}}const ol={depth:{turn:0,lift:0,blur:0,pitch:1,roll:1,squash:1,lean:1,size:0},limits:{turn:.08,pitch:6,roll:6,squash:.06,lift:.15},eyes:[],headTurns:{},drift:[]},He=2.6;function z2(){const t=(n,s,i,o,r)=>{const a=n.values.rotor??0;n.set("rotor",s,a);const l=r?o*(i-s)*.5:o*(i-s);n.set("rotor",i,a+l,r)},e=n=>n.values.lift>.05;return{takeOff:{summary:"Spools the rotor up (the skids squash as it bites), then lifts off nose-down to `height` metres (default 3).",uses:["height"],run(n,s,i){const o=n.exaggeration,r=s.height??3;t(n,i,i+900,He,"ease-in"),n.key(i+900,{blur:1},{act:!1,easing:"ease-in"}),n.key(i+700,{squash:1-.08*o},{act:!1,easing:"ease-in"});const a=i+1e3;return n.key(a+150,{squash:1+.06*o,lift:.3},{act:!1,easing:"ease-out"}),n.key(a+1300,{squash:1,lift:r,pitch:-4*o},{act:!1,easing:"ease-in-out"}),n.key(a+1700,{pitch:0}),t(n,i+900,a+1700,He),n.effect({kind:"dust",time:a,x:n.x,y:n.floor,length:900}),{end:a+1700,contact:a}}},fly:{summary:"Flies to `to` (and to `height`, if given): nose down and banked into the move, nose up and leveling as it stops.",needs:["to"],uses:["height","speed","for"],run(n,s,i){const o=n.exaggeration,r=Math.sign(s.to-n.x);let a=i;r!==0&&n.facing()!==r&&(a=n.turnTo(a,r>0?"right":"left"));const l=Math.abs(s.to-n.x),c=s.for??Math.max(700,l/(s.speed??.3)),h=s.height??n.values.lift;return n.key(a+300,{pitch:-9*o,roll:6*o},{act:!1,easing:"ease-out"}),n.key(a+c-250,{pitch:-4*o,roll:3*o,lift:h},{act:!1}),n.key(a+c,{pitch:7*o,roll:0},{act:!1,easing:"ease-out"}),n.key(a+c+450,{pitch:0}),n.move(a,a+c,s.to,{easing:"ease-in-out"}),t(n,i,a+c+450,He),{end:a+c+450,contact:a,release:a+c}}},hover:{summary:"Hovers in place for `for` ms (default 2000), bobbing gently.",uses:["for"],run(n,s,i){const o=s.for??2e3,r=n.values.lift,a=n.exaggeration;for(let l=350,c=0;l<o;l+=350,c++)n.key(i+l,{lift:r+(c%2===0?.12:-.06)*a,roll:(c%2===0?1.5:-1.5)*a},{act:!1,easing:"ease-in-out"});return n.key(i+o,{lift:r,roll:0},{act:!1,easing:"ease-in-out"}),(e(n)||r>0)&&t(n,i,i+o,He),{end:i+o}}},land:{summary:"Settles down onto its skids: a flare, a squash on touchdown with dust, and the rotor spools down.",run(n,s,i){const o=n.exaggeration,r=i+Math.max(900,n.values.lift*450);return n.key(i+400,{pitch:3*o},{act:!1,easing:"ease-out"}),n.key(r,{lift:0,pitch:0,squash:1-.14*o},{act:!1,easing:"ease-in"}),n.key(r+280,{squash:1}),t(n,i,r,He),t(n,r,r+1600,He,"ease-out"),n.key(r+1600,{blur:0},{act:!1,easing:"ease-out"}),n.effect({kind:"dust",time:r,x:n.x,y:n.floor,length:800}),{end:r+1600,contact:r}}}}}function Cf(t={}){const e={body:"#e9e4d8",wings:"#d9483b",glass:"#cfeaf5",trim:"#2c2c33",...t.colors},n=3.15,i={parts:[{id:"fuselage",shape:{type:"extrude",profile:[[-3.7,1.55],[-2.6,1.05],[2.4,.85],[3,1],[3.1,1.4],[2.7,1.75],[1.4,1.9],[-2.9,1.85]],width:1},fill:e.body},{id:"canopy",shape:{type:"extrude",profile:[[.4,1.85],[1.6,1.85],[1.1,2.3],[.5,2.3]],width:.7},fill:e.glass,outline:.8},{id:"wing-left",shape:{type:"box",size:[3.6,.1,1.35]},at:[2.05,1.15,.55],fill:e.wings},{id:"wing-right",shape:{type:"box",size:[3.6,.1,1.35]},at:[-2.05,1.15,.55],fill:e.wings},{id:"tailplane-left",shape:{type:"box",size:[1.1,.07,.65]},at:[.6,1.7,-3.35],fill:e.wings},{id:"tailplane-right",shape:{type:"box",size:[1.1,.07,.65]},at:[-.6,1.7,-3.35],fill:e.wings},{id:"fin",shape:{type:"extrude",profile:[[-3.75,1.75],[-3,1.82],[-3.45,2.75],[-3.8,2.75]],width:.1},fill:e.wings},{id:"gear-left",shape:{type:"tube",points:[[.55,.95,1.2],[.75,.28,1.3]],radius:.04,segments:5},fill:e.trim},{id:"gear-right",shape:{type:"tube",points:[[-.55,.95,1.2],[-.75,.28,1.3]],radius:.04,segments:5},fill:e.trim},{id:"wheel-left",shape:{type:"cylinder",radius:.26,length:.14,axis:"x",segments:14},at:[.78,.26,1.3],fill:e.trim},{id:"wheel-right",shape:{type:"cylinder",radius:.26,length:.14,axis:"x",segments:14},at:[-.78,.26,1.3],fill:e.trim},{id:"tail-wheel",shape:{type:"cylinder",radius:.12,length:.08,axis:"x",segments:10},at:[0,.12,-3],fill:e.trim},{id:"tail-strut",shape:{type:"tube",points:[[0,.12,-3],[0,1.2,-2.9]],radius:.03,segments:5},fill:e.trim},{id:"spinner",shape:{type:"ellipsoid",radii:[.18,.18,.22],segments:10},at:[0,1.22,n],fill:e.wings,outline:.7},{id:"prop-disc",shape:{type:"cylinder",radius:.95,length:.01,axis:"z",segments:24},at:[0,1.22,n+.08],fill:"#c9d4dd",outline:.4,fade:{control:"blur",from:0,to:.45}},{id:"propeller",shape:{type:"box",size:[.12,1.85,.04]},at:[0,1.22,n+.1],fill:e.trim,outline:.6,fade:{control:"blur",from:1,to:.3}}],controls:{rotor:{description:"How far the propeller has turned (keyed exactly; it blurs into a disc at speed)",unit:"degrees",bind:[{parts:["propeller"],rotate:{axis:"z",degrees:1}}]},blur:{description:"How blurred the propeller is: 0 still, 1 a spinning disc",unit:"0..1",min:0,max:1}},length:7,height:2.8,footprint:[7.2,6.5],anchors:{seat:{at:[0,1.55,1]},nose:{at:[0,1.22,n+.2]},tail:{at:[0,1.6,-3.7]},wingtip:{at:[3.6,1.15,.55]}}};return{kind:t.kind??"airplane",family:"aircraft",summary:t.summary??"A propeller plane: takes off from a run, flies banked, loops the loop, and lands with a flare and a squash.",rig:i,actions:G2(),acting:ol,colors:{body:e.body,ink:"#26262b"},moves:{fly:{speed:30,flies:!0,hold:{blur:1},perSecond:{rotor:He*1e3}}}}}const X2=3.2;function G2(){const t=(n,s,i,o)=>{const r=n.values.rotor??0;n.set("rotor",s,r),n.set("rotor",i,r+X2*(i-s)*(o?.5:1),o)},e=(n,s,i)=>{const o=Math.sign(i-n.x);return o!==0&&n.facing()!==o?n.turnTo(s,o>0?"right":"left"):s};return{takeOff:{summary:"Spins the propeller up, runs along the ground toward `to`, lifts its nose and climbs to `height` metres (default 4).",needs:["to"],uses:["height","for"],run(n,s,i){const o=n.exaggeration,r=e(n,i,s.to);t(n,r,r+700,"ease-in"),n.key(r+700,{blur:1},{act:!1,easing:"ease-in"});const a=s.for??2600,l=n.x,c=r+700+a*.55,h=l+(s.to-l)*.45;return n.move(r+700,c,h,{easing:"ease-in"}),n.key(c,{pitch:8*o,squash:1+.04*o},{act:!1,easing:"ease-out"}),n.key(r+700+a,{lift:s.height??4,pitch:10*o,squash:1},{act:!1,easing:"ease-in-out"}),n.move(c,r+700+a,s.to),n.key(r+700+a+500,{pitch:0}),t(n,r+700,r+700+a+500),n.effect({kind:"dust",time:c,x:h,y:n.floor,length:700}),{end:r+700+a+500,contact:c}}},fly:{summary:"Flies to `to` (and `height`), banking into the move and leveling out.",needs:["to"],uses:["height","speed","for"],run(n,s,i){const o=n.exaggeration,r=e(n,i,s.to),a=s.for??Math.max(800,Math.abs(s.to-n.x)/(s.speed??.45)),l=s.height??n.values.lift;return n.key(r+350,{roll:10*o,pitch:l>n.values.lift?6*o:-3*o},{act:!1,easing:"ease-out"}),n.key(r+a-300,{roll:4*o,lift:l},{act:!1}),n.key(r+a,{roll:0,pitch:0}),n.move(r,r+a,s.to,{easing:"ease-in-out"}),t(n,i,r+a),{end:r+a,contact:r,release:r+a}}},loop:{summary:"Loops the loop: pulls up and over in a full circle (`for` ms, default 2400), carrying on the way it was going.",uses:["for"],run(n,s,i){const o=s.for??2400,r=2.2*n.exaggeration,a=n.facing()||1,l=16,c=n.x,h=n.values.lift,u=n.values.pitch;for(let d=1;d<=l;d++){const f=Math.PI*2*d/l,p=i+o*d/l;n.key(p,{lift:h+r*(1-Math.cos(f)),pitch:u+360*d/l},{act:!1}),n.move(i+o*(d-1)/l,p,c+a*(r*Math.sin(f)+d/l*r*1.2)*n.scale)}return n.key(i+o+1,{pitch:u},{act:!1}),t(n,i,i+o),{end:i+o+1}}},land:{summary:"Comes down toward `to`: descends, flares nose-up, touches down with a squash and dust, rolls to a stop and the propeller spools down.",needs:["to"],uses:["for"],run(n,s,i){const o=n.exaggeration,r=e(n,i,s.to),a=n.x,l=s.for??2200,c=r+l,h=a+(s.to-a)*.7;return n.key(r+l*.4,{pitch:-4*o},{act:!1,easing:"ease-out"}),n.key(c-250,{pitch:6*o,lift:.15},{act:!1,easing:"ease-in-out"}),n.key(c,{lift:0,pitch:0,squash:1-.12*o},{act:!1,easing:"ease-in"}),n.key(c+260,{squash:1}),n.move(r,c,h),n.move(c,c+1200,s.to,{easing:"ease-out"}),t(n,i,c),t(n,c,c+1600,"ease-out"),n.key(c+1600,{blur:0},{act:!1,easing:"ease-out"}),n.effect({kind:"dust",time:c,x:h,y:n.floor,length:700}),{end:c+1600,contact:c}}}}}const Hn=["walk","trot","canter","gallop"],U2=Hn,Hf=["fl","fr","hl","hr"],ao={walk:{offsets:{hl:0,fl:.25,hr:.5,fr:.75},swing:16,lift:45,bob:.02,rock:0,cycle:1100},trot:{offsets:{fl:0,hr:0,fr:.5,hl:.5},swing:22,lift:75,bob:.05,rock:0,cycle:640},canter:{offsets:{hr:0,hl:.33,fr:.33,fl:.66},swing:30,lift:70,bob:.08,rock:5,cycle:560},gallop:{offsets:{hr:0,hl:.1,fr:.5,fl:.6},swing:40,lift:80,bob:.1,rock:7,cycle:460}},Re=Math.PI/180;function lo(t,e){return 4*t*Math.sin(ao[e].swing*Re)}function Ps(t){const{legs:e,colors:n}=t,s=e.upper+e.lower+e.foot,i=s+t.body.rise,o=(u,d)=>[d*u[0],u[1],u[2]],r=[{id:"body",shape:{type:"ellipsoid",radii:t.body.radii,segments:18},at:[0,i,0],fill:n.coat},{id:"neck",shape:{type:"tube",points:t.neck.points,radius:t.neck.points.map((u,d,f)=>t.neck.radius*(1.25-.4*d/Math.max(1,f.length-1))),segments:12},at:t.neck.at,fill:n.coat},{id:"head",parent:"neck",shape:{type:"ellipsoid",radii:t.head.radii,segments:14},at:t.head.at,rotate:t.head.rotate,fill:n.coat},...J2(t,n,i)];t.mane&&r.push({id:"mane",parent:"neck",shape:{type:"tube",points:t.mane.points,radius:t.mane.radius,segments:6},fill:n.dark,outline:.7}),t.muzzle&&r.push({id:"muzzle",parent:"head",shape:{type:"ellipsoid",radii:t.muzzle.radii,segments:10},at:t.muzzle.at,fill:n.muzzle,outline:.8});for(const u of[1,-1]){const d=u>0?"left":"right",f=t.ears.rotate?o(t.ears.rotate,1).map((p,g)=>g===2?u*p:p):void 0;r.push({id:`ear-${d}`,parent:"head",shape:{type:"ellipsoid",radii:t.ears.radii,segments:8},at:o(t.ears.at,u),rotate:f,fill:n.coat,outline:.7},{id:`eye-${d}`,parent:"head",shape:{type:"ellipsoid",radii:[t.eyes.size*.8,t.eyes.size,t.eyes.size*.9],segments:8},at:o(t.eyes.at,u),fill:"#1d1d22",outline:.4})}r.push(...t.extras?.(n)??[]);const a={walk:{description:"Phase of the stride, in full cycles (keyed in step with the distance covered)",unit:"cycles"},walking:{description:"How much of the gait is applied: 0 standing, 1 moving",unit:"0..1",min:0,max:1},gait:{description:`Which gait: ${t.gaits.map(u=>`${Hn.indexOf(u)} ${u}`).join(", ")}`,unit:"index",min:0,max:3},neck:{description:"Neck bent down (+, eating, sniffing) or up (−, alert)",unit:"degrees",bind:[{parts:["neck"],rotate:{axis:"x",degrees:1}}]},tail:{description:"Tail flicked up and back (+), curling along its length, on a spring behind the motion",unit:"degrees",bind:[{parts:te,rotate:{axis:"x",degrees:1/te.length}}]},wag:{description:"Tail swung side to side, curling",unit:"degrees",bind:[{parts:te,rotate:{axis:"y",degrees:1/te.length}}]}};for(const u of Hf){const d=u[0]==="f",f=u[1]==="l"?1:-1,p=d?e.thickness[0]:e.thickness[1];r.push({id:`${u}-upper`,shape:{type:"tube",points:[[0,e.upper*.2,0],[0,-e.upper*.5,0],[0,-e.upper,0]],radius:[p,p*.85,e.lowerThickness*1.15],segments:10},at:[f*e.across,s,d?e.front:e.hind],fill:n.coat},{id:`${u}-knee`,parent:`${u}-upper`,shape:{type:"ellipsoid",radii:Array(3).fill(e.lowerThickness*1.08),segments:10},at:[0,-e.upper,0],fill:n.coat,solidOnly:!0},{id:`${u}-lower`,parent:`${u}-upper`,shape:{type:"tube",points:[[0,0,0],[0,-e.lower,0]],radius:[e.lowerThickness*1.1,e.lowerThickness*.85],segments:10},at:[0,-e.upper,0],fill:n.coat},{id:`${u}-foot`,parent:`${u}-lower`,shape:{type:"ellipsoid",radii:[e.footSize[0]/2,e.foot/2+.004,e.footSize[1]/2],segments:12},at:[0,-e.lower-e.foot/2,e.footSize[1]*.12],fill:n.foot,outline:.8});const g=`${d?"Front":"Hind"} ${f>0?"left":"right"} leg`;a[`${u}.swing`]={description:`${g}: forward (+) or back (−) from the hip`,unit:"degrees",bind:[{parts:[`${u}-upper`],rotate:{axis:"x",degrees:-1}}]},a[`${u}.knee`]={description:`${g}: knee (hock) folded`,unit:"degrees",bind:[{parts:[`${u}-lower`],rotate:{axis:"x",degrees:d?1:-1}}]},a[`${u}.ankle`]={description:`${g}: foot turned at the ankle (+ toe forward)`,unit:"degrees",bind:[{parts:[`${u}-foot`],rotate:{axis:"x",degrees:-1,pivot:[0,e.foot/2,-e.footSize[1]*.12]}}]}}const l=t.neck.points[t.neck.points.length-1],c={parts:r,controls:a,length:t.body.radii[2]*2+Math.max(0,t.neck.at[2]+l[2]+t.head.radii[2]-t.body.radii[2])+.3,height:t.neck.at[1]+l[1]+t.head.radii[1]*2,footprint:[e.across*2+t.body.radii[0],(e.front-e.hind)*1.4],anchors:{back:{at:[0,i+t.body.radii[1],-t.body.radii[2]*.05]},head:{part:"head",at:[0,0,0]},mouth:{part:t.muzzle?"muzzle":"head",at:t.muzzle?[0,0,t.muzzle.radii[2]]:[0,0,t.head.radii[2]]},front:{at:[0,i,t.body.radii[2]]},...t.anchors},derive:u=>Z2(u,t,s)},h={legLength:s,upper:e.upper,lower:e.lower,foot:e.foot,tailHangs:t.tail.points[t.tail.points.length-1][1]<0,front:e.front,hind:e.hind,call(u,d){const f=u.anchor("mouth");u.effect({kind:"honk",time:d,x:f.x,y:f.y,length:800,direction:u.facing()||1})}};return{kind:t.kind,family:"animal",summary:t.summary,rig:c,actions:{...tv(t,h),...t.actions?.(h)},acting:al,colors:{body:n.coat,ink:"#26262b"},follow:[{control:"tail",of:"x",per:.6,stiffness:90,damping:6,limit:40}],moves:V2(t,s)}}function V2(t,e){const n=i=>{const o=lo(e,i);return{speed:o/(ao[i].cycle*(t.cycleScale??1)/1e3),set:{gait:Hn.indexOf(i)},hold:{walking:1},perMetre:{walk:1/o}}},s=Object.fromEntries(t.gaits.map(i=>[i==="gallop"&&!t.gaits.includes("canter")?"run":i,n(i)]));return t.gaits.includes("gallop")&&!s.gallop&&(s.gallop=n("gallop")),s}const te=Array.from({length:7},(t,e)=>e===0?"tail":`tail-${e}`);function J2(t,e,n){const s=ma(t.tail.points,te.length+1),[,i,o]=t.body.radii,r=(t.tail.at[1]-n)/i,a=Math.abs(r)<1?-o*Math.sqrt(1-r*r):t.tail.at[2],l=[t.tail.at[0],t.tail.at[1],a+Math.min(.04,o*.08)],c=f=>t.tail.radius*(1-.5*f/te.length),h=te.map((f,p)=>{const g=s[p],m=s[p+1],y=[m[0]-g[0],m[1]-g[1],m[2]-g[2]],T=p===0?void 0:s[p-1];return{id:f,...p>0?{parent:te[p-1]}:{},shape:{type:"tube",points:[[0,0,0],y],radius:[c(p),c(p+1)],segments:8,joined:!0},at:p===0?l:[g[0]-T[0],g[1]-T[1],g[2]-T[2]],fill:e.dark,outline:.8}}),u=s[s.length-1],d=s[s.length-2];return h.push({id:"tail-tip",parent:te[te.length-1],shape:{type:"ellipsoid",radii:Array(3).fill(c(te.length)*1.05),segments:8},at:[u[0]-d[0],u[1]-d[1],u[2]-d[2]],fill:e.dark,outline:.8,solidOnly:!0}),h}function Z2(t,e,n){const s=Math.max(0,Math.min(1,t.walking??0));if(s===0)return{};const i=Hn[Math.max(0,Math.min(3,Math.round(t.gait??0)))],o=ao[e.gaits.includes(i)?i:e.gaits[0]],r=t.walk??0,a={};for(const c of Hf){const h=Math.PI*2*(r+o.offsets[c]);a[`${c}.swing`]=(t[`${c}.swing`]??0)+s*o.swing*Math.sin(h),a[`${c}.knee`]=(t[`${c}.knee`]??0)+s*o.lift*Math.max(0,Math.cos(h))}const l=Math.PI*2*r;return a.lift=(t.lift??0)+s*o.bob*n*Math.abs(Math.sin(l*2)),a.pitch=(t.pitch??0)+s*o.rock*Math.sin(l),a.neck=(t.neck??0)+s*(o.rock>0?-o.rock*1.4:5)*Math.sin(l*2),a}function rl(t){const n=Math.sin(32*Re),s=t.legLength-(t.front-t.hind)*n,i=72,r=(s-t.upper*Math.cos(i*Re)-t.foot)/t.lower,a=r>=1?0:r<=-1?180:Math.acos(r)/Re,l={pitch:32,lift:t.legLength*(1-Math.cos(32*Re))-t.front*n,neck:-10,tail:t.tailHangs?35:-40,"fl.swing":-32,"fr.swing":-32};for(const c of["hl","hr"])l[`${c}.swing`]=i-32,l[`${c}.knee`]=-(i+a),l[`${c}.ankle`]=a;return l}const al={depth:{turn:0,lift:0,pitch:1,roll:1,squash:1,neck:2,tail:3,wag:3,"fl.swing":2,"fr.swing":2,"hl.swing":2,"hr.swing":2,"fl.knee":3,"fr.knee":3,"hl.knee":3,"hr.knee":3},limits:{pitch:6,neck:8,tail:10,wag:8,"fl.swing":8,"fr.swing":8,"hl.swing":8,"hr.swing":8,lift:0},eyes:[],headTurns:{},drift:[]},Q2=al;function Rf(t){const e=(t.upper+t.lower)*.32,n=Math.asin(Math.min(1,e/(t.upper+t.lower+t.foot)))/Re,s={pitch:0,lift:e-t.legLength,neck:-14,tail:t.tailHangs?60:-60,"fl.swing":90-n,"fr.swing":90-n,"fl.knee":0,"fr.knee":0,"fl.ankle":n,"fr.ankle":n};for(const i of["hl","hr"])s[`${i}.swing`]=70,s[`${i}.knee`]=-155,s[`${i}.ankle`]=85;return s}function tv(t,e){const n=t.cycleScale??1,s=r=>({summary:{walk:"Walks to `to` (four beats), its head bobbing.",trot:"Trots to `to`: legs in diagonal pairs, the body bouncing.",canter:"Canters to `to`: three beats, the body rocking.",gallop:"Gallops (runs) to `to`: legs reaching, the body rocking hard, kicking up dust."}[r],needs:["to"],uses:["for"],run(a,l,c){const h=Math.sign(l.to-a.x);if(h===0)return{end:c};let u=c;a.facing()!==h&&(u=a.turnTo(u,h>0?"right":"left"));const d=a.exaggeration;a.key(u+180,{neck:-12*d},{act:!1,easing:"ease-out"});const p=Math.abs(l.to-a.x)/a.scale/lo(e.legLength,r),g=l.for??Math.max(500,p*ao[r].cycle*n),m=a.values.walk??0;return a.set("gait",u,a.values.gait??0),a.set("gait",u+1,Hn.indexOf(r)),a.set("walking",u,0),a.set("walking",u+240,1,"ease-out"),a.set("walking",u+g-240,1),a.set("walking",u+g,0,"ease-in"),a.set("walk",u,m),a.move(u,u+g,l.to,{easing:"ease-in-out"}),a.set("walk",u+g,m+p,"ease-in-out"),a.key(u+g+300,{neck:0}),(r==="gallop"||r==="canter")&&(a.effect({kind:"dust",time:u+200,x:a.x-h*e.legLength*a.scale,y:a.floor,length:700,direction:-h}),a.effect({kind:"dust",time:u+g,x:l.to+h*e.legLength*.6*a.scale,y:a.floor,length:600,direction:h})),{end:u+g+300,contact:u,release:u+g}}}),i=Object.fromEntries(t.gaits.map(r=>[r==="gallop"&&!t.gaits.includes("canter")?"run":r,s(r)]));t.gaits.includes("gallop")&&!i.gallop&&(i.gallop=s("gallop"));const o={...i,[t.call]:{summary:`Throws its head up and ${t.call}s.`,run(r,a,l){const c=r.exaggeration;return r.key(l+150,{neck:10*c},{act:!1,easing:"ease-out"}),r.key(l+380,{neck:-28*c,squash:1.05},{act:!1,easing:"ease-out"}),r.key(l+680,{neck:-20*c},{act:!1}),r.key(l+980,{neck:0,squash:1}),e.call(r,l+380),{end:l+980,contact:l+380}}},sit:{summary:"Sits on its haunches for `for` ms (default 1500): the rump goes down onto folded hind legs, paws flat on the ground, the front legs stay planted; then it gets up.",uses:["for"],run(r,a,l){const c=rl(e),h=l+450;r.key(h,c,{act:!1,easing:"ease-in-out"}),r.key(h+(a.for??1500),c,{act:!1});const u=h+(a.for??1500)+450,d={};for(const f of Object.keys(c))d[f]=0;return r.key(u,d),{end:u,contact:h,release:u-450}}},lie:{summary:"Lies down for `for` ms (default 2000), head up and front paws forward (sinking back onto its haunches first), then gets up.",uses:["for"],run(r,a,l){const c=Rf(e),h={...rl(e)},u=l+400,d=u+450;r.key(u,h,{act:!1,easing:"ease-in-out"}),r.key(d,c,{act:!1,easing:"ease-in-out"}),r.key(d+(a.for??2e3),c,{act:!1});const f=d+(a.for??2e3)+600,p={};for(const g of new Set([...Object.keys(c),...Object.keys(h)]))p[g]=0;return r.key(f,p),{end:f,contact:d,release:f-600}}},jump:{summary:"Crouches and jumps (forward to `to`, or up on the spot), legs tucked in the air, landing with a squash and dust.",uses:["to"],run(r,a,l){const c=r.exaggeration,h=e.legLength*.8*c,u=l+260,d=u+90,f=d+520;if(r.key(u,{squash:.86,"hl.knee":40,"hr.knee":40,"fl.knee":25,"fr.knee":25,neck:8},{act:!1,easing:"ease-out"}),r.key(d,{squash:1.12,"hl.knee":0,"hr.knee":0,"fl.knee":0,"fr.knee":0,pitch:8,"fl.swing":35,"fr.swing":35,"hl.swing":-35,"hr.swing":-35},{act:!1,easing:"ease-out"}),r.key((d+f)/2,{lift:h,squash:1,pitch:0,"fl.knee":60,"fr.knee":60,"hl.knee":60,"hr.knee":60,"fl.swing":25,"fr.swing":25,"hl.swing":-20,"hr.swing":-20},{act:!1,easing:"ease-out"}),r.key(f,{lift:0,squash:.85,pitch:-4,"fl.knee":0,"fr.knee":0,"hl.knee":0,"hr.knee":0,"fl.swing":0,"fr.swing":0,"hl.swing":0,"hr.swing":0},{act:!1,easing:"ease-in"}),r.key(f+280,{squash:1,pitch:0,neck:0}),a.to!==void 0){const p=Math.sign(a.to-r.x);p!==0&&r.facing()!==p&&r.turnTo(l,p>0?"right":"left"),r.move(d,f,a.to)}return r.effect({kind:"dust",time:f,x:r.x,y:r.floor,length:550}),{end:f+280,contact:f}}},nod:{summary:"Nods its head twice.",run(r,a,l){return r.key(l+200,{neck:20},{act:!1,easing:"ease-out"}),r.key(l+400,{neck:-5},{act:!1,easing:"ease-in-out"}),r.key(l+600,{neck:18},{act:!1,easing:"ease-in-out"}),r.key(l+900,{neck:0}),{end:l+900}}},swish:{summary:"Swishes its tail a few times.",uses:["for"],run(r,a,l){const c=a.for??900;for(let h=1;h<=4;h++)r.key(l+c*h/5,{tail:h%2===0?10:35},{act:!1,easing:"ease-in-out"});return r.key(l+c,{tail:0}),{end:l+c}}}};return t.grazes&&(o.graze={summary:"Lowers its head to graze for `for` ms (default 1800), nibbling, then looks up.",uses:["for"],run(r,a,l){const c=a.for??1800;r.key(l+600,{neck:75},{act:!1,easing:"ease-in-out"});for(let h=900;h<600+c;h+=400)r.key(l+h,{neck:h%800===100?70:78},{act:!1,easing:"ease-in-out"});return r.key(l+600+c+500,{neck:0}),{end:l+600+c+500}}}),o}function Lf(t={}){return Ps({kind:t.kind??"horse",summary:t.summary??"A cartoon horse: walks, trots, canters and gallops with its hooves in step with the ground, rears, bucks, neighs, grazes and swishes its tail.",legs:{upper:.5,lower:.42,foot:.08,footSize:[.12,.16],front:.62,hind:-.62,across:.2,thickness:[.075,.09],lowerThickness:.05},body:{radii:[.32,.36,.95],rise:.25},neck:{at:[0,1.42,.7],points:[[0,0,0],[0,.5,.3]],radius:.15},head:{at:[0,.48,.5],radii:[.13,.14,.3],rotate:[38,0,0]},muzzle:{at:[0,-.02,.24],radii:[.11,.1,.1]},ears:{at:[.07,.16,-.17],radii:[.035,.1,.05]},eyes:{at:[.115,.05,-.04],size:.04},tail:{at:[0,1.4,-.9],points:[[0,0,0],[0,-.22,-.2],[0,-.62,-.24]],radius:.08},mane:{points:[[0,.1,-.12],[0,.55,.17]],radius:.07},colors:{coat:"#b5763a",dark:"#4a2e1a",foot:"#3a2a22",muzzle:"#8d5a2c",accent:"#e8c9a0",...t.colors},gaits:["walk","trot","canter","gallop"],call:"neigh",grazes:!0,anchors:{hitch:{at:[0,.95,-.15]},saddle:{at:[0,1.6,-.05]}},actions:e=>({rear:{summary:"Rears up on its hind legs, front legs tucked and pawing, neighs, and drops back down with dust.",uses:["for"],run(n,s,i){const o=n.exaggeration,r=Math.min(55,32*o),a=-e.hind*Math.sin(r*Re),l=s.for??700;n.key(i+200,{pitch:-4,neck:6,"hl.knee":12,"hr.knee":12},{act:!1,easing:"ease-out"}),n.key(i+520,{pitch:r,lift:a,neck:-25,"fl.swing":55,"fl.knee":95,"fr.swing":40,"fr.knee":80,"hl.knee":0,"hr.knee":0},{act:!1,easing:"ease-out"}),n.key(i+520+l*.5,{"fl.swing":35,"fl.knee":70,"fr.swing":58,"fr.knee":100},{act:!1,easing:"ease-in-out"}),n.key(i+520+l,{"fl.swing":55,"fl.knee":95,"fr.swing":40,"fr.knee":80},{act:!1,easing:"ease-in-out"});const c=i+520+l+380;return n.key(c,{pitch:0,lift:0,neck:8,squash:.94,"fl.swing":0,"fl.knee":0,"fr.swing":0,"fr.knee":0},{act:!1,easing:"ease-in"}),n.key(c+320,{neck:0,squash:1}),e.call(n,i+520),n.effect({kind:"dust",time:c,x:n.x+(n.facing()||1)*e.front*n.scale,y:n.floor,length:600}),{end:c+320,contact:c}}},buck:{summary:"Bucks: drops its head and kicks both hind legs up and back.",run(n,s,i){const o=n.exaggeration,r=Math.min(35,18*o),a=e.front*Math.sin(r*Re);return n.key(i+220,{pitch:3,squash:.95},{act:!1,easing:"ease-out"}),n.key(i+480,{pitch:-r,lift:a,neck:30,"hl.swing":-65,"hr.swing":-60,"hl.knee":10,"hr.knee":10},{act:!1,easing:"ease-out"}),n.key(i+900,{pitch:0,lift:0,neck:0,squash:.95,"hl.swing":0,"hr.swing":0,"hl.knee":0,"hr.knee":0},{act:!1,easing:"ease-in"}),n.key(i+1150,{squash:1}),n.effect({kind:"dust",time:i+900,x:n.x-(n.facing()||1)*.6*n.scale,y:n.floor,length:600}),{end:i+1150,contact:i+480}}}})})}function Ff(t={}){return Ps({kind:t.kind??"dog",summary:t.summary??"A cartoon dog: walks, trots and runs, barks, wags its tail, sits, jumps, sniffs the ground.",legs:{upper:.19,lower:.16,foot:.05,footSize:[.07,.1],front:.24,hind:-.24,across:.09,thickness:[.04,.05],lowerThickness:.032},body:{radii:[.14,.15,.36],rise:.1},neck:{at:[0,.56,.27],points:[[0,0,0],[0,.14,.06]],radius:.075},head:{at:[0,.15,.08],radii:[.12,.11,.13]},muzzle:{at:[0,-.03,.13],radii:[.065,.055,.08]},ears:{at:[.11,0,-.02],radii:[.025,.09,.05],rotate:[0,0,18]},eyes:{at:[.08,.04,.08],size:.025},tail:{at:[0,.58,-.34],points:[[0,0,0],[0,.1,-.08],[0,.2,-.1]],radius:.03},extras:e=>[{id:"nose",parent:"muzzle",shape:{type:"ellipsoid",radii:[.025,.02,.02],segments:8},at:[0,.03,.08],fill:"#1d1d22",outline:.4},{id:"patch",parent:"body",shape:{type:"ellipsoid",radii:[.012,.09,.11],segments:10},at:[.135,.04,-.06],fill:e.accent,outline:.5}],colors:{coat:"#d9a066",dark:"#a8703a",foot:"#a8703a",muzzle:"#f0d2a8",accent:"#f6ead8",...t.colors},gaits:["walk","trot","gallop"],cycleScale:.55,call:"bark",anchors:{leash:{part:"neck",at:[0,.06,0]}},actions:()=>({wag:{summary:"Wags its tail fast for `for` ms (default 1200).",uses:["for"],run(e,n,s){const i=n.for??1200;for(let o=80,r=0;o<i;o+=80,r++)e.key(s+o,{wag:r%2===0?35:-35,tail:25},{act:!1,easing:"ease-in-out"});return e.key(s+i,{wag:0,tail:0}),{end:s+i}}},sniff:{summary:"Puts its nose to the ground and sniffs (`for` ms, default 1400).",uses:["for"],run(e,n,s){const i=n.for??1400;e.key(s+350,{neck:70,pitch:-6},{act:!1,easing:"ease-in-out"});for(let o=500,r=0;o<i;o+=140,r++)e.key(s+o,{neck:r%2===0?74:66},{act:!1});return e.key(s+i+300,{neck:0,pitch:0}),{end:s+i+300}}}})})}function Nf(t={}){return Ps({kind:t.kind??"cat",summary:t.summary??"A cartoon cat: walks, trots and runs, meows, arches its back, pounces, sits and swishes its tail.",legs:{upper:.13,lower:.11,foot:.035,footSize:[.05,.07],front:.17,hind:-.18,across:.06,thickness:[.028,.035],lowerThickness:.022},body:{radii:[.1,.105,.27],rise:.07},neck:{at:[0,.39,.2],points:[[0,0,0],[0,.08,.04]],radius:.05},head:{at:[0,.1,.05],radii:[.095,.085,.085]},muzzle:{at:[0,-.03,.07],radii:[.04,.03,.03]},ears:{at:[.055,.085,-.01],radii:[.03,.055,.02],rotate:[0,0,-12]},eyes:{at:[.045,.02,.07],size:.022},tail:{at:[0,.42,-.26],points:[[0,0,0],[0,.08,-.12],[0,.24,-.16],[0,.34,-.1]],radius:.022},extras:()=>[{id:"nose",parent:"muzzle",shape:{type:"ellipsoid",radii:[.014,.01,.01],segments:8},at:[0,.015,.03],fill:"#e48a9a",outline:.4}],colors:{coat:"#8f8a86",dark:"#5f5a57",foot:"#f2efe9",muzzle:"#f2efe9",accent:"#f2efe9",...t.colors},gaits:["walk","trot","gallop"],cycleScale:.5,call:"meow",actions:e=>({arch:{summary:"Arches its back, fur up and tail high, for `for` ms (default 1200): a startled cat.",uses:["for"],run(n,s,i){const o=n.exaggeration,r=s.for??1200,a={squash:1+.25*o,neck:25,tail:-45,"fl.swing":-8,"fr.swing":-8,"hl.swing":8,"hr.swing":8};return n.key(i+180,a,{act:!1,easing:"ease-out"}),n.key(i+180+r,a,{act:!1}),n.key(i+r+520,{squash:1,neck:0,tail:0,"fl.swing":0,"fr.swing":0,"hl.swing":0,"hr.swing":0}),{end:i+r+520,contact:i+180}}},pounce:{summary:"Crouches low, wiggles, and pounces to `to`, landing with a squash.",needs:["to"],run(n,s,i){const o=n.exaggeration,r=Math.sign(s.to-n.x);let a=i;r!==0&&n.facing()!==r&&(a=n.turnTo(a,r>0?"right":"left"));const l={squash:.75,"hl.knee":60,"hr.knee":60,"fl.knee":45,"fr.knee":45,neck:10,tail:-15};n.key(a+300,l,{act:!1,easing:"ease-out"});for(let u=1;u<=4;u++)n.key(a+300+u*110,{roll:u%2===0?3:-3},{act:!1});const c=a+300+550,h=c+480;return n.key(c,{roll:0,squash:1.2,"hl.knee":0,"hr.knee":0,"fl.knee":0,"fr.knee":0,"fl.swing":45,"fr.swing":45,"hl.swing":-45,"hr.swing":-45,tail:20},{act:!1,easing:"ease-out"}),n.key((c+h)/2,{lift:e.legLength*.9*o,squash:1.1,pitch:-6},{act:!1,easing:"ease-out"}),n.key(h,{lift:0,squash:.8,pitch:0,"fl.swing":0,"fr.swing":0,"hl.swing":0,"hr.swing":0,neck:0,tail:0},{act:!1,easing:"ease-in"}),n.key(h+260,{squash:1}),n.move(c,h,s.to),n.effect({kind:"dust",time:h,x:s.to,y:n.floor,length:450}),{end:h+260,contact:h}}}})})}function Df(t={}){return Ps({kind:t.kind??"cow",summary:t.summary??"A cartoon cow: walks and trots, moos, grazes, sits and swishes its tail.",legs:{upper:.42,lower:.36,foot:.08,footSize:[.13,.15],front:.68,hind:-.66,across:.24,thickness:[.085,.1],lowerThickness:.06},body:{radii:[.4,.42,1],rise:.32},neck:{at:[0,1.3,.85],points:[[0,0,0],[0,.22,.25]],radius:.19},head:{at:[0,.18,.4],radii:[.17,.19,.27],rotate:[30,0,0]},muzzle:{at:[0,-.06,.22],radii:[.15,.11,.1]},ears:{at:[.17,.06,-.12],radii:[.11,.035,.05],rotate:[0,0,-15]},eyes:{at:[.13,.06,.02],size:.04},tail:{at:[0,1.48,-1],points:[[0,0,0],[0,-.25,-.12],[0,-.7,-.14]],radius:.035},extras:e=>[{id:"horn-left",parent:"head",shape:{type:"tube",points:[[0,0,0],[.08,.12,.02]],radius:.025,segments:6},at:[.1,.16,-.14],fill:"#efe6d2",outline:.6},{id:"horn-right",parent:"head",shape:{type:"tube",points:[[0,0,0],[-.08,.12,.02]],radius:.025,segments:6},at:[-.1,.16,-.14],fill:"#efe6d2",outline:.6},{id:"udder",shape:{type:"ellipsoid",radii:[.16,.12,.18],segments:10},at:[0,.98,-.45],fill:"#f0a6b6",outline:.6},{id:"spot-1",parent:"body",shape:{type:"ellipsoid",radii:[.02,.2,.26],segments:10},at:[.39,.06,.2],fill:e.accent,outline:.4},{id:"spot-2",parent:"body",shape:{type:"ellipsoid",radii:[.02,.16,.22],segments:10},at:[-.39,.1,-.35],fill:e.accent,outline:.4},{id:"spot-3",parent:"body",shape:{type:"ellipsoid",radii:[.2,.02,.24],segments:10},at:[0,.41,-.2],fill:e.accent,outline:.4}],colors:{coat:"#f4f1ea",dark:"#2e2b2a",foot:"#3a3330",muzzle:"#f0b8c4",accent:"#2e2b2a",...t.colors},gaits:["walk","trot"],cycleScale:1.15,call:"moo",grazes:!0})}function ev(t){return lo(1,t)}const Le=.6,Wf=75,ll=80;function co(t){const{colors:e}=t,[n,s,i]=t.body.radii,o=(t.tail.raised??15)*Math.PI/180,r=t.tail.length*.4,a=[{id:"body",shape:{type:"ellipsoid",radii:t.body.radii,segments:16},at:[0,t.body.height,0],fill:e.body},{id:"neck",shape:{type:"ellipsoid",radii:[n*.55,s*.55,i*.3],segments:10},at:[0,t.body.height+s*.45,i*.65],fill:e.body,outline:.5,solidOnly:!0},{id:"head",parent:"neck",shape:{type:"ellipsoid",radii:[t.head.radius,t.head.radius*1.02,t.head.radius*1.05],segments:14},at:[t.head.at[0],t.head.at[1]-(t.body.height+s*.45),t.head.at[2]-i*.65],fill:e.body},{id:"beak",parent:"head",shape:{type:"tube",points:[[0,0,0],[0,-t.beak.thickness*.4,t.beak.length]],radius:[t.beak.thickness,t.beak.thickness*.08],segments:8},at:[0,-t.head.radius*.1,t.head.radius*.8],fill:e.beak,outline:.8},{id:"tail",shape:{type:"ellipsoid",radii:[t.tail.width/2,.012*(i/.08),t.tail.length/2],segments:10},at:[t.tail.at[0],t.tail.at[1]+r*Math.sin(o),t.tail.at[2]-r*Math.cos(o)],rotate:[t.tail.raised??15,0,0],fill:e.wing,outline:.8}];if(e.belly&&a.push({id:"belly",parent:"body",shape:{type:"ellipsoid",radii:[n*.82,s*.7,i*.75],segments:12},at:[0,-s*.25,i*.12],fill:e.belly,outline:.4}),t.comb){const h=t.head.radius;a.push({id:"comb",parent:"head",shape:{type:"extrude",profile:[[-h*.5,h*.6],[h*.6,h*.6],[h*.5,h*1.3],[h*.15,h*1.05],[-h*.05,h*1.4],[-h*.3,h*1.05],[-h*.6,h*1.25]],width:h*.25},fill:e.comb??"#d9372e",outline:.7},{id:"wattle",parent:"head",shape:{type:"ellipsoid",radii:[h*.15,h*.35,h*.2],segments:8},at:[0,-h*.7,h*.6],fill:e.comb??"#d9372e",outline:.6})}for(const h of[1,-1]){const u=h>0?"left":"right",d=t.head.radius;a.push({id:`eye-${u}`,parent:"head",shape:{type:"ellipsoid",radii:[d*.16,d*.2,d*.18],segments:8},at:[h*d*.72,d*.18,d*.42],fill:"#1d1d22",outline:.3}),a.push({id:`wing-${u}`,shape:{type:"ellipsoid",radii:[.004,.004,.004],segments:4},at:[h*t.wing.shoulder[0],t.wing.shoulder[1],t.wing.shoulder[2]],rotate:[-8,h*90,0],outline:0}),a.push({id:`wing-${u}-blade`,parent:`wing-${u}`,shape:{type:"ellipsoid",radii:[t.wing.span*Le/2,t.wing.chord*.1,t.wing.chord/2],segments:12},at:[h*t.wing.span*Le/2,0,-t.wing.chord*.1],rotate:[-ll,0,0],fill:e.wing,outline:.8}),a.push({id:`wing-${u}-tip`,parent:`wing-${u}-blade`,shape:{type:"ellipsoid",radii:[t.wing.span*Le/2.4,t.wing.chord*.06,t.wing.chord*.3],segments:10},at:[h*t.wing.span*Le/4,0,-t.wing.chord*.3],rotate:[0,h*14,0],fill:e.wing,outline:.8}),a.push({id:`leg-${u}`,shape:{type:"tube",points:[[0,0,0],[0,-t.legs.length,0]],radius:Math.max(.004,t.legs.length*.05),segments:5},at:[h*t.legs.across,t.legs.length,0],fill:e.legs,outline:.6}),a.push({id:`toes-${u}`,parent:`leg-${u}`,shape:{type:"tube",points:[[0,0,-t.legs.length*.15],[0,0,t.legs.length*.35]],radius:Math.max(.003,t.legs.length*.04),segments:5},at:[0,-t.legs.length,0],fill:e.legs,outline:.6})}const l={spread:{description:"Wings: 0 folded back along the body, 1 spread out",unit:"0..1",min:0,max:1,bind:[{parts:["wing-left"],rotate:{axis:"y",degrees:-90}},{parts:["wing-right"],rotate:{axis:"y",degrees:90}},{parts:["wing-left-blade"],translate:[t.wing.span*(1-Le)/2,0,0],rotate:{axis:"x",degrees:ll},scale:[1/Le,1,1]},{parts:["wing-right-blade"],translate:[-t.wing.span*(1-Le)/2,0,0],rotate:{axis:"x",degrees:ll},scale:[1/Le,1,1]}]},flap:{description:"Wings raised (+) or lowered (−) at the shoulders",unit:"degrees",bind:[{parts:["wing-left"],rotate:{axis:"z",degrees:1}},{parts:["wing-right"],rotate:{axis:"z",degrees:-1}}]},wingbeat:{description:"Phase of the wingbeat, in beats (keyed steadily while flapping)",unit:"beats"},flapping:{description:"How hard the wings beat: 0 still, 1 full beats",unit:"0..1",min:0,max:1},peck:{description:"Head bobbed down and forward (+, pecking) or up (−)",unit:"degrees",bind:[{parts:["neck"],rotate:{axis:"x",degrees:1},translate:[0,-(t.neckReach??0)/Wf,0]}]},step:{description:"Phase of a walk, in steps (a chicken’s legs)",unit:"steps"},stepping:{description:"How much of the walk is applied",unit:"0..1",min:0,max:1},"leg.left":{description:"Left leg swung forward (+)",unit:"degrees",bind:[{parts:["leg-left"],rotate:{axis:"x",degrees:-1}}]},"leg.right":{description:"Right leg swung forward (+)",unit:"degrees",bind:[{parts:["leg-right"],rotate:{axis:"x",degrees:-1}}]}},c={parts:a,controls:l,length:i*2+t.tail.length+t.beak.length,height:t.head.at[1]+t.head.radius,footprint:[n*2.2,i*2.4],anchors:{beak:{part:"beak",at:[0,0,t.beak.length]},head:{part:"head",at:[0,0,0]},back:{at:[0,t.body.height+s,0]},feet:{at:[0,0,0]}},derive:h=>{const u={},d=Math.max(0,Math.min(1,h.flapping??0));d>0&&(u.flap=(h.flap??0)+d*48*Math.sin(Math.PI*2*(h.wingbeat??0)));const f=Math.max(0,Math.min(1,h.stepping??0));if(f>0){const p=Math.sin(Math.PI*2*(h.step??0));u["leg.left"]=(h["leg.left"]??0)+f*28*p,u["leg.right"]=(h["leg.right"]??0)-f*28*p,u.peck=(h.peck??0)+f*12*Math.sin(Math.PI*4*(h.step??0))}return u}};return{kind:t.kind,family:"bird",summary:t.summary,rig:c,actions:sv(t),acting:Bf,colors:{body:e.body,ink:"#26262b"},moves:nv(t)}}function nv(t){const e=t.legs.length*1.2,n={walk:{speed:e/.42,hold:{stepping:1},perMetre:{step:.5/e}}};return t.flies!==!1&&(n.fly={speed:4+t.wing.span*12,flies:!0,hold:{flapping:1,spread:1},perSecond:{wingbeat:t.beatsPerSecond??4}}),n}const Bf={depth:{turn:0,lift:0,pitch:1,roll:1,squash:1,spread:1,flap:2,peck:2},limits:{pitch:6,roll:6,squash:.06,peck:8,flap:10,lift:0},eyes:[],headTurns:{},drift:[]};function sv(t){const e=(t.beatsPerSecond??4)/1e3,n=(r,a,l)=>{const c=r.values.wingbeat??0;r.set("wingbeat",a,c),r.set("wingbeat",l,c+(l-a)*e)},s=(r,a,l)=>{const c=Math.sign(l-r.x);return c!==0&&r.facing()!==c?r.turnTo(a,c>0?"right":"left"):a},i=(r,a)=>{const l=r.anchor("beak");r.effect({kind:"honk",time:a,x:l.x,y:l.y,length:600,direction:r.facing()||1})},o={hop:{summary:"Hops to `to` in little bounces, wings twitching.",needs:["to"],run(r,a,l){const c=s(r,l,a.to),h=r.x,u=Math.abs(a.to-h),d=Math.max(1,Math.round(u/(t.body.radii[2]*3*r.scale))),f=260;for(let p=0;p<d;p++){const g=c+p*f;r.key(g+60,{squash:.85},{act:!1,easing:"ease-out"}),r.key(g+150,{squash:1.1,lift:t.legs.length*1.4,spread:.15},{act:!1,easing:"ease-out"}),r.key(g+f,{squash:.9,lift:0,spread:0},{act:!1,easing:"ease-in"}),r.move(g+60,g+f,h+(a.to-h)*(p+1)/d,{easing:"ease-in-out"})}return r.key(c+d*f+120,{squash:1}),{end:c+d*f+120}}},walk:{summary:"Walks to `to` on its two legs, its head bobbing with each step.",needs:["to"],uses:["for"],run(r,a,l){const c=s(r,l,a.to),h=Math.abs(a.to-r.x)/r.scale,u=t.legs.length*1.2,d=h/u,f=a.for??Math.max(400,d*420),p=r.values.step??0;return r.set("stepping",c,0),r.set("stepping",c+150,1,"ease-out"),r.set("stepping",c+f-150,1),r.set("stepping",c+f,0,"ease-in"),r.set("step",c,p),r.move(c,c+f,a.to,{easing:"ease-in-out"}),r.set("step",c+f,p+d/2,"ease-in-out"),{end:c+f,contact:c,release:c+f}}},peck:{summary:"Pecks at the ground (`for` ms, default 900): quick jabs of the head.",uses:["for"],run(r,a,l){const c=a.for??900,h=Math.max(1,Math.round(c/300));r.key(l+120,{pitch:-(t.stoop??12)},{act:!1,easing:"ease-out"});for(let u=0;u<h;u++)r.key(l+120+u*300+90,{peck:Wf},{act:!1,easing:"ease-in"}),r.key(l+120+u*300+260,{peck:20},{act:!1,easing:"ease-out"});return r.key(l+120+h*300+200,{peck:0,pitch:0}),{end:l+120+h*300+200,contact:l+210}}},flap:{summary:"Flaps its wings on the spot (`for` ms, default 900), lifting a little.",uses:["for"],run(r,a,l){const c=a.for??900;return r.key(l+120,{spread:1},{act:!1,easing:"ease-out"}),r.set("flapping",l,0),r.set("flapping",l+150,1,"ease-out"),r.set("flapping",l+c-150,1),r.set("flapping",l+c,0,"ease-in"),n(r,l,l+c),r.key(l+c*.5,{lift:t.legs.length*.6},{act:!1,easing:"ease-out"}),r.key(l+c,{lift:0,spread:0},{act:!1,easing:"ease-in"}),{end:l+c+80}}},[t.call]:{summary:`${t.call[0].toUpperCase()}${t.call.slice(1)}s: its head comes up and its beak opens to call.`,run(r,a,l){return r.key(l+120,{peck:-25,squash:1.06},{act:!1,easing:"ease-out"}),r.key(l+500,{peck:-20},{act:!1}),r.key(l+760,{peck:0,squash:1}),i(r,l+150),{end:l+760,contact:l+150}}}};return t.flies!==!1?(o.fly={summary:"Takes off (a crouch and a leap, wings beating) and flies to `to` at `height` metres (default 2); `land` brings it down.",needs:["to"],uses:["height","for"],run(r,a,l){const c=r.exaggeration,h=s(r,l,a.to),u=a.height??2,d=a.for??Math.max(700,Math.abs(a.to-r.x)/.35),f=r.values.lift>t.legs.length,p=f?h:h+200;return f||(r.key(h+160,{squash:1-.18*c,spread:.6},{act:!1,easing:"ease-out"}),r.effect({kind:"dust",time:p,x:r.x,y:r.floor,length:400})),r.key(p+100,{spread:1,squash:1.08,pitch:10},{act:!1,easing:"ease-out"}),r.set("flapping",p,r.values.flapping??0),r.set("flapping",p+100,1,"ease-out"),r.set("flapping",p+d,.6),n(r,p,p+d),r.key(p+d*.4,{lift:u,pitch:-5,squash:1},{act:!1,easing:"ease-out"}),r.key(p+d,{lift:u,pitch:0},{act:!1,easing:"ease-in-out"}),r.move(p,p+d,a.to,{easing:"ease-in-out"}),{end:p+d,contact:p,release:p+d}}},o.glide={summary:"Glides to `to` on still, spread wings, sinking gently to `height` metres (default: a third lower than it is); from the ground it takes off first, flying the first stretch.",needs:["to"],uses:["height","for"],run(r,a,l){let c=l;if(r.values.lift<=t.legs.length){const f=r.x+(a.to-r.x)/3;c=o.fly.run(r,{do:"fly",to:f,height:(a.height??1.5)*1.3},l).end}c=s(r,c,a.to);const h=r.values.lift,u=a.height??h*.67,d=a.for??Math.max(900,Math.abs(a.to-r.x)/.3);return r.set("flapping",c,r.values.flapping??1),r.set("flapping",c+250,0,"ease-out"),n(r,c,c+250),r.key(c+300,{spread:1,flap:10,pitch:-6},{act:!1,easing:"ease-out"}),r.key(c+d,{lift:u,pitch:-3,flap:10},{act:!1,easing:"ease-in-out"}),r.move(c,c+d,a.to,{easing:"ease-in-out"}),{end:c+d,contact:c,release:c+d}}},o.land={summary:"Comes down to the floor it is over (or to `height` metres above it, a branch or a roof): wings braking, a squash on touchdown.",uses:["height","to"],run(r,a,l){const h=a.height??0;return r.set("flapping",l,r.values.flapping??1),r.set("flapping",l+700-120,1),r.set("flapping",l+700,0,"ease-in"),n(r,l,l+700),r.key(l+700*.6,{pitch:14},{act:!1,easing:"ease-out"}),r.key(l+700,{lift:h,pitch:0,squash:.85},{act:!1,easing:"ease-in"}),a.to!==void 0&&r.move(l,l+700,a.to,{easing:"ease-out"}),r.key(l+700+160,{squash:1,spread:0,flap:0}),{end:l+700+200,contact:l+700}}}):o.flutter={summary:"Flutters up a little way and back down, wings beating hard (a chicken’s flight).",run(r,a,l){return r.key(l+100,{spread:1,squash:.9},{act:!1,easing:"ease-out"}),r.set("flapping",l+80,0),r.set("flapping",l+160,1,"ease-out"),r.set("flapping",l+900-100,1),r.set("flapping",l+900,0,"ease-in"),n(r,l+80,l+900),r.key(l+900*.5,{lift:t.legs.length*2.5,squash:1.08},{act:!1,easing:"ease-out"}),r.key(l+900,{lift:0,squash:.85,spread:0},{act:!1,easing:"ease-in"}),r.key(l+900+160,{squash:1}),{end:l+900+160,contact:l+900}}},o}function jf(t={}){return co({kind:"songbird",summary:"A small songbird: hops, pecks, tweets, flaps, flies and lands (on the ground, a branch or a roof).",body:{radii:[.05,.05,.075],height:.085},head:{at:[0,.145,.065],radius:.036},beak:{length:.03,thickness:.01},wing:{shoulder:[.04,.1,.03],span:.11,chord:.06},tail:{at:[0,.095,-.07],length:.07,width:.045},legs:{length:.04,across:.018},colors:{body:"#7b6a58",wing:"#5c4c3d",beak:"#e7a43a",legs:"#c47a35",belly:"#e9c8a3",...t.colors},call:"tweet",beatsPerSecond:9})}function qf(t={}){return co({kind:"crow",summary:"A crow: walks and hops, pecks, caws, flaps, flies and lands (on the ground, a branch or a roof).",body:{radii:[.09,.09,.17],height:.2},head:{at:[0,.32,.15],radius:.065},beak:{length:.08,thickness:.022},wing:{shoulder:[.07,.24,.06],span:.32,chord:.14},tail:{at:[0,.2,-.15],length:.16,width:.09},legs:{length:.1,across:.035},colors:{body:"#2b2b33",wing:"#1e1e25",beak:"#3b3b44",legs:"#3b3b44",...t.colors},call:"caw",beatsPerSecond:4})}function Yf(t={}){return co({kind:"chicken",summary:"A chicken: walks with a bobbing head, pecks, clucks, and flutters up and down (it cannot really fly).",body:{radii:[.13,.14,.19],height:.3},head:{at:[0,.5,.16],radius:.07},beak:{length:.05,thickness:.02},wing:{shoulder:[.11,.34,.04],span:.24,chord:.15},tail:{at:[0,.38,-.15],length:.16,width:.13,raised:50},legs:{length:.17,across:.05},comb:!0,stoop:20,neckReach:.12,colors:{body:"#f4ede0",wing:"#e6dccb",beak:"#e7a43a",legs:"#e7a43a",comb:"#d9372e",...t.colors},call:"cluck",flies:!1})}const Rn={car:kf,truck:vf,bus:Mf,tractor:Sf,cart:Tf,trainCar:Ef,bike:Af,motorbike:xf,tree:$f,house:If,helicopter:_f,airplane:Cf,horse:Lf,dog:Ff,cat:Nf,cow:Df,songbird:jf,crow:qf,chicken:Yf};function Kf(t,e={}){const n=Rn[t];if(!n)throw new Error(ot("prop preset",t,Object.keys(Rn)));return n(e)}const ho=["do","at","for","to","toward","speed","open","on","height","wind"],cl={viewer:0,right:1,away:2,left:3},iv=420,hl={hold:{summary:"Holds still (`for` ms, default 1000).",run:(t,e,n)=>({end:n+(e.for??1e3)})},turn:{summary:"Turns to face `toward`: viewer, right, away, left, or a quarter-turn value (it turns in 3D, through the nearer way).",needs:["toward"],run:(t,e,n)=>({end:t.turnTo(n,e.toward)})},pop:{summary:"Pops into being: grows from nothing, stretched, overshoots and settles (`for` ms, default 500).",uses:["for"],run(t,e,n){const s=e.for??500,i=t.exaggeration;return t.key(n,{size:0,squash:1},{act:!1}),t.key(n+s*.6,{size:1+.15*i,squash:1+.15*i},{act:!1,easing:"ease-out"}),t.key(n+s,{size:1,squash:1}),{end:n+s,contact:n}}},vanish:{summary:"Shrinks away to nothing, with a little stretch first (`for` ms, default 400).",uses:["for"],run(t,e,n){const s=e.for??400,i=t.exaggeration;return t.key(n+s*.3,{size:1+.08*i,squash:1+.12*i},{act:!1,easing:"ease-out"}),t.key(n+s,{size:0,squash:1},{act:!1,easing:"ease-in"}),{end:n+s,release:n+s}}}};function uo(t){return{...hl,...t.actions}}const ul=t=>typeof t=="number"&&Number.isFinite(t);function zf(t,e){if(!Array.isArray(t))return[{level:"error",beat:-1,message:`Beats must be an array of { do: … } objects (got ${typeof t}).`}];const n=uo(e),s=Object.keys(n),i=[];return t.forEach((o,r)=>{const a=c=>i.push({level:"error",beat:r,message:c});if(!o||typeof o!="object"||Array.isArray(o))return a(`Each beat must be an object like { do: '${s[s.length-1]}' }.`);const l=o;for(const c of Object.keys(l))ho.includes(c)||a(ot("beat field",c,ho,c==="duration"?"for":c==="direction"?"toward":void 0));if(typeof l.do!="string"||!s.includes(l.do))return a(ot(`${e.kind} action`,l.do,s));for(const c of n[l.do].needs??[])l[c]===void 0&&a(`\`${l.do}\` needs \`${c}\`.`);for(const c of["at","for","speed","height","wind"])l[c]!==void 0&&!(ul(l[c])&&l[c]>=0)&&a(`\`${c}\` must be a number ≥ 0 (got ${JSON.stringify(l[c])}).`);if(l.to!==void 0&&!ul(l.to)&&a(`\`to\` is a scene x in px (got ${JSON.stringify(l.to)}).`),l.toward!==void 0&&!ul(l.toward)&&!(typeof l.toward=="string"&&l.toward in cl)){const c=typeof l.toward=="string"?Kn(l.toward,Object.keys(cl)):void 0;a(`\`toward\` is viewer, right, away, left or a quarter-turn number${c?` (did you mean "${c}"?)`:""} (got ${JSON.stringify(l.toward)}).`)}for(const c of["open","on"])l[c]!==void 0&&typeof l[c]!="boolean"&&a(`\`${c}\` is true or false (got ${JSON.stringify(l[c])}).`)}),i}function Xf(t,e,n,s={}){const i=zf(n,e).filter(S=>S.level==="error");if(i.length>0)throw new Error(`propScript (${e.kind}): ${i.length} problem(s) in the beats:
|
|
61
|
+
${i.map(S=>` beat ${S.beat}: ${S.message}`).join(`
|
|
62
|
+
`)}`);const o=s.from??0,r=s.ground??0,a=s.scale??60,l=s.exaggeration??1,c=uo(e),h={};for(const S of[...Object.keys(On),...Object.keys(e.rig.controls)])h[S]=s.start?.[S]??mt(e.rig,{},S);const u=[{time:0,pose:{...h}}],d=new Map,f=[];let p=o,g=r;const m=(S,I,v,$)=>{const _=d.get(S)??[{time:0,value:S==="x"||S==="y"?0:h[S]}];_.push({time:I,value:v,...$?{easing:$}:{}}),d.set(S,_),S!=="x"&&S!=="y"&&(h[S]=v)},y=(S,I)=>{const v=S==="x"?p-o:S==="y"?g-r:h[S],$=d.get(S);(!$||$[$.length-1].time<I)&&m(S,I,v)},T={prop:e,scale:a,exaggeration:l,get x(){return p},get floor(){return g},values:h,facing(){const S=Math.sin(h.turn*Math.PI/2);return Math.abs(S)<.5?0:S>0?1:-1},key(S,I,v={}){Object.assign(h,I),u.push({time:S,pose:{...h},...v.act===!1?{act:!1}:{},...v.easing?{easing:v.easing}:{}})},move(S,I,v,$={}){y("x",S),m("x",I,v-o,$.easing),p=v,$.floor!==void 0&&(y("y",S),m("y",I,$.floor-r,$.easing),g=$.floor)},set(S,I,v,$){m(S,I,v,$)},turnTo(S,I){const v=typeof I=="number"?I:cl[I],$=h.turn,P=[v-4,v,v+4].map(F=>({t:F,d:Math.abs(F-$)})).sort((F,R)=>F.d-R.d||Math.abs(F.t)-Math.abs(R.t))[0];if(P.d<.001)return S;const C=S+iv*Math.max(1,P.d);return T.key(C,{turn:P.t}),C},effect(S){f.push(S)},anchor(S){const v=_n(e,h,a).anchors[S];if(!v)throw new Error(`${e.kind}: no anchor "${S}"`);return{x:p+v.point.x,y:g+v.point.y}}},k=[];let b=0;for(const S of n){const I=Math.max(S.at??b,u[u.length-1].time),v=c[S.do].run(T,S,I);v.end>u[u.length-1].time&&u.push({time:v.end,pose:{...h}}),k.push({start:I,end:v.end,...v.contact!==void 0?{contact:v.contact}:{},...v.release!==void 0?{release:v.release}:{}}),b=v.end}const A=Ia(s.style??"snappy"),M={...A,anticipation:A.anticipation*l,overshoot:A.overshoot*l},E=Ui(lv(u),e.acting,{style:M}),x=[...Object.entries(E).filter(([S])=>!d.has(S)).map(([S,I])=>({id:`${t}-${S}`,target:t,property:S,keyframes:I})),...[...d].map(([S,I])=>({id:`${t}-${S}`,target:t,property:S,keyframes:cv(I)}))];for(const S of rv(t,e,x,b,u[0].pose)){const I=x.findIndex(_=>_.property===S.property);if(I<0){x.push(S);continue}const v=new Nt({id:`${t}-own`,tracks:[x[I]]}),$=_=>Number(v.getStateAtTime(_).values.get(t)?.get(S.property)??0);x[I]={...S,keyframes:S.keyframes.map(_=>({time:_.time,value:Number(_.value)+$(_.time)}))}}return{tracks:x,duration:b,beats:k,effects:f}}const ov=1500;function rv(t,e,n,s,i){if(!e.follow?.length)return[];const o=new Nt({id:`${t}-follow`,tracks:n.filter(a=>a.property==="turn"||e.follow.some(l=>l.of===a.property))}),r=(a,l)=>{const c=o.getStateAtTime(a).values.get(t)?.get(l);return typeof c=="number"?c:i[l]??0};return e.follow.map(a=>{const l=s+ov,c=Sc(d=>r(d,a.of),{start:0,end:l,stiffness:a.stiffness,damping:a.damping}),h=a.limit??1/0,u=c.map(({time:d,value:f})=>{const p=Math.sin(r(d,"turn")*Math.PI/2),g=(f-r(d,a.of))*p;return{time:d,value:Math.max(-h,Math.min(h,g*a.per))}});return{id:`${t}-${a.control}`,target:t,property:a.control,keyframes:u}})}const av=20;function lv(t){const e=[...t].sort((s,i)=>s.time-i.time),n=[];for(const s of e){const i=n[n.length-1];i&&s.time-i.time<av?n[n.length-1]={...s,time:i.time}:n.push(s)}return n}function cv(t){const e=t.map((s,i)=>({k:s,i})).sort((s,i)=>s.k.time-i.k.time||s.i-i.i),n=[];for(const{k:s}of e)n.length>0&&n[n.length-1].time===s.time?n[n.length-1]=s:n.push(s);return n}const hv={linear:!0,"ease-in":!0,"ease-out":!0,"ease-in-out":!0,"ease-in-quad":!0,"ease-out-quad":!0,"ease-in-out-quad":!0,"ease-in-cubic":!0,"ease-out-cubic":!0,"ease-in-out-cubic":!0};function Gf(t,e={}){const n={};for(const s of Object.keys(Ht))n[s]={summary:`Walks to \`to\` in the ${s} gait.`,needs:["to"]};for(const s of Object.keys(jt))n[s]={summary:`Moves into the ${s} pose and holds it (\`for\` ms).`};for(const s of Object.keys(_e))n[s]={summary:`The ${s} gag (${Ms(s)} ms).`};for(const[s,i]of Object.entries(Ts))n[s]={...i};return{...t?{version:t}:{},timing:"JSON timelines and tracks are in milliseconds; the GSAP-style API (live.to, tf.timeline) takes seconds. Scene x grows right, y grows down, in px.",easings:{named:Object.keys(hv),parametric:{"cubic-bezier":'{ type: "cubic-bezier", points: [x1, y1, x2, y2] }',steps:'{ type: "steps", count, position?: start | end | none | both }',elastic:'{ type: "elastic", mode?: in | out | in-out, amplitude?, period? }',bounce:'{ type: "bounce", mode?: in | out | in-out }',back:'{ type: "back", mode?: in | out | in-out, overshoot? }'}},trackKinds:{keyframe:"{ id, target, property, keyframes: [{ time, value, easing? }] }: values between keys are interpolated (numbers, colours, paths)",spring:'{ id, target, property, kind: "spring", spring: { from, to, stiffness?, damping?, mass?, velocity? }, delay? }: physics settle',inertia:'{ id, target, property, kind: "inertia", inertia: { from, velocity, friction?, min?, max?, end? }, delay? }: a flick that slows (end snaps to a value or the nearest of a list)',motionPath:'{ property: "motionPath", path, align? }: moves along an SVG path',text:'{ property: "text", … }: types or scrambles text'},canvasProperties:no,stickFigure:{poseFields:Ch,props:Hh,handFields:Rh,poses:Object.keys(jt),expressions:Object.keys(ct),gags:Object.fromEntries(Object.keys(_e).map(s=>[s,Ms(s)])),gaits:Object.keys(Ht),actingStyles:Object.keys(Ze),beatFields:Ji,actions:n,dances:Object.fromEntries(Object.entries(xe).map(([s,i])=>[s,Object.keys(i.moves)])),flips:Object.fromEntries(Object.entries(rs).map(([s,i])=>[s,i.label])),handShapes:Object.keys($t),mudras:Object.keys(ui)},props:{api:{"car() · truck() · bus() · tractor() · cart() · trainCar() · bike() · motorbike()":"wheeled vehicles (vehicle(spec) makes your own)","tree() · house()":"environment (tree(spec), house(spec))","helicopter() · airplane()":"aircraft","horse() · dog() · cat() · cow()":"animals (quadruped(spec) makes your own): gaits with footfall patterns keyed in step with the distance, sit, jump, their calls, species actions","songbird() · crow() · chicken()":"birds (bird(spec) makes your own): hop, walk, peck, flap, fly and land (a chicken flutters), their calls; wings fold and beat in rhythm","{ kind: 'prop', prop: 'car', position, rotation, values } with loadScene3D(scene, { kinds: [characterObjects, propObjects] })":"props in 3D scenes, by preset name, seen in perspective by the scene camera; controls are tracks on the object","characterScript3D(id, beats, { scene, position?, heading?, height?, pose? })":"a v2 character in a 3D scene in world metres: gaits to [x, z] or through points (its walk phase keyed with the distance), face, hold, pose, gag; checkCharacterBeats3D checks the beats","propRide3D({ prop, propId, propTracks, scene, placement, anchor, riderId, pose, start, end, mount?, dismount? })":"a character riding a prop in a 3D scene: hips on a seat anchor (saddle, seat) as it moves, hopping on and off; RIDING_POSES.astride / .seated","propScript3D(id, prop, beats, { scene, position?, heading?, values? })":"props scripted in world metres for 3D scenes: moves to [x, z] or through points (wheels and strides keyed with the distance), face, hold, and their actions; checkPropBeats3D checks the beats","propPreset(name, options?)":"a prop preset by name (did-you-mean on a wrong one)","propTarget({ …, style: 'stick' })":"line art to go with stick figures: tubes as single strokes, shapes outlined over paper","propTow({ leader, leaderId, leaderTracks, hitch, towed, towedId, anchor, start, end })":"a prop towed by another (a cart behind a horse): turns with it, its wheels roll exactly","propTarget({ x, y, prop, scale?, values?, look?, ink? })":"a canvas target that draws a prop (x, y: its middle on the ground; scale px per metre, default 60)","propScript(id, prop, beats, { from, ground, scale, style?, exaggeration?, start? })":"beats → acted tracks, with contact times and effect cues; checkPropBeats(beats, prop) checks them","drawProp(ctx, target, frame, id, { rider? })":"draw it as it is in a frame (a rider is drawn between its far and near parts)","propAt(target, frame, id).anchor(name)":"where an anchor (seat, door, chimney…) is, in scene px","propRide({ prop, propId, propTracks, anchor, figure, figureId, start, end, offset? })":"a figure carried at an anchor, turning with the prop; spliceTracks() puts it into the figure’s tracks","drawPropEffects(ctx, effects, time)":"dust, exhaust, skid marks, honk lines, leaves, smoke"},beatFields:ho,commonControls:Object.fromEntries(Object.entries(On).map(([s,i])=>[s,`${i.description}${i.unit?` (${i.unit})`:""}`])),commonActions:Object.fromEntries(Object.entries(hl).map(([s,i])=>[s,i.summary])),presets:Object.fromEntries(Object.entries(Rn).map(([s,i])=>{const o=i();return[s,{family:o.family,summary:o.summary,actions:Object.fromEntries(Object.entries(o.actions).map(([r,a])=>[r,{summary:a.summary,...a.needs?{needs:a.needs}:{}}])),controls:Object.keys(o.rig.controls),anchors:Object.keys(o.rig.anchors??{})}]}))},custom:{api:{"defineAction({ summary, needs?, steps: (from, beat) => [{ after, pose, easing? }] })":"a new action written as timed pose steps from the current pose, like a gag","defineAction({ summary, needs?, beats: (beat) => [beats] })":"a new action built from other beats (which may be custom too)","defineGait({ swing, knee, arm, elbow, lean, cycle?, … })":"a new gait (the Gait fields in degrees; cycle is ms per two steps)","scriptTracks(id, beats, { actions, gaits })":"beats may then use those names; checkBeats(beats, { actions, gaits }) knows them","stickFigureTarget({ …, cast: { actions, gaits } })":"a figure that draws the gaits and lists the actions in describeTarget","persona({ name, summary?, height?, look?, acting?, gait?, mood?, stance?, energy?, actions?, gaits? })":"a character’s look, acting style and habits: .figure({ x, y }), .script(id, beats, { from, ground }), .check(beats), .handPath(…), .describe(); `go` walks in its gait, `stand` returns to its stance and face"},actions:Object.fromEntries(Object.entries(e.actions??{}).map(([s,i])=>[s,{summary:i.summary,...i.needs?{needs:i.needs}:{}}])),gaits:Object.fromEntries(Object.entries(e.gaits??{}).map(([s,i])=>[s,i.summary??"custom gait"]))},character:{poses:Object.keys(ze),expressions:Object.keys(Or),gags:Object.keys(Wi),builds:Object.keys(wi),hair:Object.keys(qr),hairColors:{...ae},facialHair:Object.keys(Xr),glasses:Object.keys(Ur),hats:Object.keys(Hi),cast:Object.keys(Pa),heldItems:Object.fromEntries(Object.entries(Jr).map(([s,i])=>[s,i.hands])),handMeetings:Object.keys(vs)},codePanel:{languages:Xi,removeStyles:Ki,anchors:{"line(n, time?)":"line n’s text box { x, y, left, right, top, bottom, width, height }: stand on top, point at x, y","token(n, text, occurrence?, time?)":"a word on a line","spot(n, column, width?, time?)":"a place in a line, for put and write","landing(piece, n, column)":"where a dropped piece will land",box:"the whole panel"},edits:Ea},surfaces:{code:bs,board:de,chart:Je,prop:Cn},surfaceScript:{"surfaceScript(figureId, { name: surface }, beats, options)":"compiles beats that act on surfaces: returns the script result with `tracks` (the figure’s, ridden, then every surface’s, keyed by its name) and `figureTracks`; options are scriptTracks’ plus `figureStyle` (for carry) and `ride` (default true)","checkSurfaceBeats(beats, surfaces, cast?)":"every problem checkBeats finds, plus unknown surfaces, places, edits and moments, with suggestions","{ surface, anchor }":"a named place, where a beat takes `target` (its box), `to` (its centre x) or `onto` (its top); as laid out, before any edit moves it","then: { surface, edit, anchor, at?, until?, …options }":"what the surface does in answer to the beat (or a list of them): one of its edits, or `carry` (the piece follows the hand until `until`); the other fields are the edit’s options",at:`a moment of the beat: ${Pn.join(", ")} (default contact, or start when the beat has none); not ms`,until:"a moment of this beat, or { beat: index, at? } of a later one; sets the edit’s duration (carry needs it)"},cameraShots:{frame:"{ at, duration?, easing?, frame: { focus?: { x, y }, scale?, rotate? } }: push in, pull out, or cut (duration 0)",shake:"{ at, duration, shake: { strength?, frequency?, roll?, seed? } }",follow:"{ at, until, follow: { x: <the subject’s x keyframes>, lead?, y?, lag?, scale? } }: keeps a subject centred"},teach:{"lesson({ id })":"steps as timeline JSON: to, set, together, wait, marker (with pause, question, captions)","cells, pointer, stack, queue, table, pipeline":"diagram primitives (SVG markup + step helpers)","figure({ width, height, children })":"the SVG holding the pieces"},cli:{"tinyfly capabilities [--json]":"this catalog","tinyfly check <beats.json>":"check a beat script (names, fields) with suggestions","tinyfly validate <timeline.json> [--markup file]":"check a timeline against its markup","tinyfly render <timeline.json> <markup> [--at …]":"a frame as static markup","tinyfly video <scene.mjs> [--stills dir --times …]":"MP4, or PNG stills to look at"}}}const pt=t=>t.map(e=>`\`${e}\``).join(", "),Uf=t=>Object.entries(t).map(([e,n])=>`| \`${e}\` | ${n.unit??n.kind??""} | ${n.description} |`).join(`
|
|
63
|
+
`);function uv(t,e={}){const n=Gf(t,e),s=n.stickFigure;return[`# tinyfly capabilities${n.version?` (v${n.version})`:""}`,"","Generated from the library itself: every name below is accepted, and names not listed are rejected (beat scripts, code panels and `checkTracks` say which name was probably meant).","",`**Timing.** ${n.timing}`,"","## Easings","",`Named: ${pt(n.easings.named)}.`,"",...Object.entries(n.easings.parametric).map(([o,r])=>`- ${o}: \`${r}\``),"","## Track kinds","",...Object.entries(n.trackKinds).map(([o,r])=>`- **${o}**: ${r}`),"","## Canvas targets","","Types: `rect`, `circle`, `text`, `line`, `path`, `image`, `custom`. `describeTarget(target)` lists what one can animate with its values; `checkTracks(tracks, targets)` checks tracks before playing them.","","| Property | Unit | What it does | Types |","|---|---|---|---|",...Object.entries(n.canvasProperties).map(([o,r])=>`| \`${o}\` | ${r.unit??r.kind??""} | ${r.description} | ${r.types.length===7?"all":r.types.join(", ")} |`),"","## Stick figure (`@algorisys/tinyfly/characters`)","","`stickFigureTarget({ x, y, style })` is a custom canvas target; its props are the pose fields and the props below. Pose it with tracks (`poseTracks`), or write beats (`scriptTracks`).","","### Pose fields","","| Field | Unit | What it does |","|---|---|---|",Uf(s.poseFields),"","### Other props","","| Prop | Unit | What it does |","|---|---|---|",Uf(s.props),"",`With \`style.hands\`, each hand has \`hand.left.<field>\` / \`hand.right.<field>\` props: ${pt(Object.keys(s.handFields))}.`,"",`**Poses** (a beat's \`do\`, or a pose key): ${pt(s.poses)}.`,"",`**Expressions** (a beat's \`mood\`): ${pt(s.expressions)}.`,"",`**Gags** (ms): ${Object.entries(s.gags).map(([o,r])=>`\`${o}\` (${r})`).join(", ")}.`,"",`**Gaits**: ${pt(s.gaits)}. **Acting styles** (\`style\`): ${pt(s.actingStyles)}.`,"","### Beat scripts","",`\`scriptTracks(target, beats, { from, ground, height, facing, style })\`. A beat has these fields only: ${pt(s.beatFields)}. Times are ms; \`to\` and \`target\` are scene px; \`onto\` is a floor's scene y.`,"","| `do` | Needs | What happens |","|---|---|---|",...Object.entries(s.actions).map(([o,r])=>`| \`${o}\` | ${(r.needs??[]).map(a=>`\`${a}\``).join(", ")} | ${r.summary} |`),"","Beats that touch something report `contact` (and `release`) times in `result.beats[i]`; key the thing they touch to those.","",`**Dances** (\`dancer(style, { move })\`): ${Object.entries(s.dances).map(([o,r])=>`\`${o}\` (${r.join(", ")})`).join("; ")}.`,"",`**Flips**: ${Object.entries(s.flips).map(([o,r])=>`\`${o}\` (${r})`).join(", ")}.`,"",`**Hand shapes**: ${pt(s.handShapes)}. **Mudras**: ${pt(s.mudras)}.`,"","### Your own actions, gaits and personas","","Nothing is registered globally: pass your definitions where they are used.","",...Object.entries(n.custom.api).map(([o,r])=>`- \`${o}\`: ${r}`),"",...Object.keys(n.custom.actions).length||Object.keys(n.custom.gaits).length?["**This cast’s own:**","",...Object.entries(n.custom.actions).map(([o,r])=>`- \`${o}\`${r.needs?.length?` (needs ${r.needs.map(a=>`\`${a}\``).join(", ")})`:""}: ${r.summary}`),...Object.entries(n.custom.gaits).map(([o,r])=>`- \`${o}\` (gait): ${r}`),""]:[],"## Props (everyday objects with behaviours)","","A prop is a 3D rig of simple parts drawn with the characters’ pens (clean, pencil, silhouette), so it turns toward the camera (`turn`), and its beats go through the same acting pass (anticipation, overshoot, overlap; `exaggeration` scales them).","",...Object.entries(n.props.api).map(([o,r])=>`- \`${o}\`: ${r}`),"",`Prop beat fields: ${pt(n.props.beatFields)}. Every prop has the controls ${Object.keys(n.props.commonControls).map(o=>`\`${o}\``).join(", ")} and the actions ${Object.keys(n.props.commonActions).map(o=>`\`${o}\``).join(", ")}.`,"","| Preset | Family | Actions (needs) | Controls | Anchors |","|---|---|---|---|---|",...Object.entries(n.props.presets).map(([o,r])=>`| \`${o}()\` | ${r.family} | ${Object.entries(r.actions).map(([a,l])=>`\`${a}\`${l.needs?.length?` (${l.needs.join(", ")})`:""}`).join(", ")} | ${r.controls.map(a=>`\`${a}\``).join(", ")} | ${r.anchors.join(", ")} |`),"","## Character (v2 human)","",`Poses: ${pt(n.character.poses)}. Expressions: ${pt(n.character.expressions)}. Gags: ${pt(n.character.gags)}.`,"","Appearance options of `character({ … })`, all plain data that turns with the head (see docs/character-appearance.md):","",`- \`build\`: ${pt(n.character.builds)}`,`- \`hair\`: ${pt(n.character.hair)} (colours: ${pt(Object.keys(n.character.hairColors))} in \`HAIR_COLORS\`)`,`- \`facialHair\`: ${pt(n.character.facialHair)}`,`- \`glasses\`: ${pt(n.character.glasses)}; \`hat\`: ${pt(n.character.hats)}; \`ears: true\``,"- `outfit`: `{ shirt, trousers, sleeves: short | long | none, bottom: trousers | shorts | skirt, collar, tie: colour, over: apron | labCoat, overColor }`",`- \`castMember(name, height)\`: ${pt(n.character.cast)}`,"- Face marks (pose fields, 0–1): `blush`, `tears`, `sweat`",`- \`holding\`: ${Object.entries(n.character.heldItems).map(([o,r])=>`\`${o}\` (${r==="both"?"both":r==="either"?"one hand or both":"left or right"})`).join(", ")}; pose fields \`held.left\`, \`held.right\`, \`held.both\` (below 0.5 lets go); \`handGrip(joints, side)\``,`- \`meetHands(kind, a, b)\` (stand them \`meetingSpacing(kind, a, b)\` apart): ${pt(n.character.handMeetings)}`,"","## Code panel","",`\`codePanel({ code, language, x, y, fontSize?, lineHeight?, width? })\`: a code listing as a scene object. Languages: ${pt(n.codePanel.languages)}. Remove styles: ${pt(n.codePanel.removeStyles)}.`,"",...Object.entries(n.codePanel.anchors).map(([o,r])=>`- \`${o}\`: ${r}`),"",...Object.values(n.codePanel.edits).map(o=>`- \`${o.split(":")[0]}\`:${o.split(":").slice(1).join(":")}`),"","## Surfaces","","Scene objects figures act on. Places are named `kind:args`: `surface.anchor(name)` gives the box there (stand on `top`, point at `x`, `y`; pass it as a beat `target`), `surface.piece(name)` makes the part there come loose, and `surface.edit(name, anchor, options)` changes the surface at a time (`at`, ms).","","Beats name places and say what surfaces do in answer (`surfaceScript`):","",...Object.entries(n.surfaceScript).map(([o,r])=>`- \`${o}\`: ${r}`),"",...Object.entries(n.surfaces).flatMap(([o,r])=>[`### ${o}`,"",...r.create?[`\`${r.create}\``,""]:[],"Anchors:",...Object.entries(r.anchors).map(([a,l])=>`- \`${a}\`: ${l}`),"","Edits:",...Object.entries(r.edits).map(([a,l])=>`- \`${a}\`: ${l}`),""]),"## Camera shots (`cameraTracks(shots, { stage })`)","",...Object.entries(n.cameraShots).map(([o,r])=>`- **${o}**: \`${r}\``),"","## Teaching (`@algorisys/tinyfly/teach`)","",...Object.entries(n.teach).map(([o,r])=>`- \`${o}\`: ${r}`),"","## Command line","",...Object.entries(n.cli).map(([o,r])=>`- \`${o}\`: ${r}`),""].join(`
|
|
64
|
+
`)}function dv(t,e,n,s={}){const i=s.color??"#555",o=s.size??60;for(const r of e){const a=(n-r.time)/r.length;if(a<=0||a>=1)continue;const l=zt(`${r.kind}:${r.time}:${r.x}`);r.kind==="dust"?Sd(t,{x:r.x,y:r.y},a,{size:o,color:i,seed:l}):r.kind==="exhaust"?pv(t,r,a,o,i,l):r.kind==="skid"?mv(t,r,a,n,i):r.kind==="honk"?yv(t,r,a,o,i):r.kind==="smoke"?fv(t,r,n,o,i):r.kind==="leaves"&&gv(t,r,a,o,s.leafColor??"#5cae5a",i,l)}}function fv(t,e,n,s,i,o){const r=e.direction??1,a=380,l=1500;t.save(),t.strokeStyle=i,t.lineWidth=Math.max(1,s*.025);for(let c=e.time;c<=e.time+e.length-l;c+=a){const h=(n-c)/l;if(h<=0||h>=1)continue;const u=Math.sin(c/97+h*4)*s*.06,d=e.x+r*h*s*.7+u,f=e.y-h*s*1.6;t.globalAlpha=Math.min(1,h*6)*(1-h)*.85,t.beginPath(),t.arc(d,f,s*(.07+h*.2),0,Math.PI*2),t.stroke()}t.restore()}function gv(t,e,n,s,i,o,r){const a=e.direction??1,l=e.toY??e.y+s*3;t.save(),t.lineWidth=Math.max(1,s*.02),t.strokeStyle=o,t.fillStyle=i;for(let c=0;c<4;c++){const h=zt(`${r}:${c}`)%1e3/1e3,u=Math.min(1,n*(1.1+h*.4)),d=e.x+(h-.5)*s*1.2,f=e.y+(h-.3)*s*.4,p=u*u*.4+u*.6,g=d+a*u*s*(.6+h)+Math.sin(u*9+h*6)*s*.18,m=Math.min(l-2,f+(l-f)*p);t.globalAlpha=n>.85?(1-n)/.15:1,t.save(),t.translate(g,m),t.rotate(Math.sin(u*7+h*5)*1.2),t.beginPath(),t.ellipse(0,0,s*.07,s*.035,0,0,Math.PI*2),t.fill(),t.stroke(),t.restore()}t.restore()}function pv(t,e,n,s,i,o){const r=e.direction??-1;t.save(),t.strokeStyle=i,t.lineWidth=Math.max(1,s*.025);for(let a=0;a<3;a++){const l=n*1.6-a*.25;if(l<=0||l>=1)continue;const c=(zt(`${o}:${a}`)%100/100-.5)*s*.1,h=e.x+r*l*s*.9,u=e.y-l*s*.45+c;t.globalAlpha=(1-l)*.9,t.beginPath(),t.arc(h,u,s*(.06+l*.14),0,Math.PI*2),t.stroke()}t.restore()}function mv(t,e,n,s,i){const o=e.toX??e.x,r=Math.min(1,(s-e.time)/e.length*3),a=e.x+(o-e.x)*r;t.save(),t.strokeStyle=i,t.lineCap="round",t.globalAlpha=n<.6?.8:.8*(1-(n-.6)/.4),t.lineWidth=3;for(const l of[-2,4])t.beginPath(),t.moveTo(e.x,e.y+l),t.lineTo(a,e.y+l),t.stroke();t.restore()}function yv(t,e,n,s,i){const o=e.direction??1;t.save(),t.strokeStyle=i,t.lineWidth=Math.max(1.5,s*.04),t.lineCap="round",t.globalAlpha=n<.7?1:(1-n)/.3;const r=s*(.15+.5*(1-(1-n)**2));for(let a=-1;a<=1;a++){const l=a*Math.PI/7,c=e.x+o*Math.cos(l)*r,h=e.y+Math.sin(l)*r;t.beginPath(),t.arc(c,h,s*.12,o>0?-Math.PI/3:Math.PI*2/3,o>0?Math.PI/3:Math.PI*4/3),t.stroke()}t.restore()}function bv(t){const e=new Nt({id:`${t.propId}-ride`,tracks:t.propTracks.filter(h=>h.target===t.propId)}),n=t.every??33,s=[],i=[],o=[],r=[];let a=1;for(let h=t.start;;h=Math.min(t.end,h+n)){const u=oo(t.prop,{state:e.getStateAtTime(h)},t.propId),d=u.anchor(t.anchor);s.push({time:h,value:d.x+(t.offset?.x??0)-t.figure.x}),i.push({time:h,value:d.y+(t.offset?.y??0)-t.figure.y});const f=Math.sin(u.values.turn*Math.PI/2);if(Math.abs(f)>.15&&(a=f>0?1:-1),o.push({time:h,value:Math.abs(f)}),r.push({time:h,value:a}),h>=t.end)break}const l=t.figureId,c=[{id:`${l}-x`,target:l,property:"x",keyframes:s},{id:`${l}-y`,target:l,property:"y",keyframes:i}];return t.turn!==!1&&c.push({id:`${l}-turn`,target:l,property:"turn",keyframes:o},{id:`${l}-facing`,target:l,property:"facing",keyframes:wv(r)}),c}function wv(t){const e=[];for(const n of t){const s=e[e.length-1];s&&s.value!==n.value&&e.push({time:n.time-1,value:s.value}),(!s||s.value!==n.value||n===t[t.length-1])&&e.push(n)}return e}function kv(t,e,n){const s=r=>`${r.target}\0${r.property}`,i=new Map(e.map(r=>[s(r),r]));return[...t.map(r=>{const a=i.get(s(r));if(!a)return r;i.delete(s(r));const c=[...(r.keyframes??[]).filter(h=>h.time<n.from||h.time>n.to),...a.keyframes??[]].sort((h,u)=>h.time-u.time);return{...r,keyframes:c}}),...i.values()]}function vv(t){const e=new Nt({id:`${t.leaderId}-tow`,tracks:t.leaderTracks.filter(f=>f.target===t.leaderId)}),n=t.every??33,s=t.towed,i=s.x+s.width/2,o=s.props,r=s.prop.wheelRadius,a=[],l=[],c=[];let h=o.wheelSpin??0,u;for(let f=t.start;;f=Math.min(t.end,f+n)){const p=oo(t.leader,{state:e.getStateAtTime(f)},t.leaderId),g=p.anchor(t.hitch),m=p.values.turn,y=_n(s.prop,{...o,turn:m},s.propScale).anchors[t.anchor];if(!y)throw new Error(`propTow: ${s.prop.kind} has no anchor "${t.anchor}"`);const T=g.x-y.point.x;if(u!==void 0&&r){const k=Math.sin(m*Math.PI/2);h+=(T-u)*(k||1)/s.propScale/r*(180/Math.PI)}if(u=T,a.push({time:f,value:T-i}),l.push({time:f,value:m}),c.push({time:f,value:h}),f>=t.end)break}const d=t.towedId;return[{id:`${d}-x`,target:d,property:"x",keyframes:a},{id:`${d}-turn`,target:d,property:"turn",keyframes:l},...r?[{id:`${d}-wheelSpin`,target:d,property:"wheelSpin",keyframes:c}]:[]]}const Vf=new WeakMap;function Mv(t,e){const n=e?.some(Boolean)?e.map(d=>d?1:0).join(""):"";let s=Vf.get(t);s||Vf.set(t,s=new Map);const i=s.get(n);if(i)return i;const o=xs(t),r={vertices:o.vertices,faces:o.faces.filter((d,f)=>!e?.[f])},a=r.vertices.flatMap(d=>[d[0],d[1],d[2]]),l=r.vertices.map(()=>[0,0,0]),c=[];r.faces.forEach(d=>{for(const g of d.corners)for(const m of[0,1,2])l[g][m]+=d.normal[m];const[f,...p]=d.corners;for(let g=0;g+1<p.length;g++){const[m,y,T]=[f,p[g],p[g+1]],[k,b,A]=[r.vertices[m],r.vertices[y],r.vertices[T]],M=[b[0]-k[0],b[1]-k[1],b[2]-k[2]],E=[A[0]-k[0],A[1]-k[1],A[2]-k[2]],x=[M[1]*E[2]-M[2]*E[1],M[2]*E[0]-M[0]*E[2],M[0]*E[1]-M[1]*E[0]],S=x[0]*d.normal[0]+x[1]*d.normal[1]+x[2]*d.normal[2];c.push(...S>=0?[m,y,T]:[m,T,y])}});const h=l.flatMap(d=>{const f=Math.hypot(...d)||1;return[d[0]/f,d[1]/f,d[2]/f]}),u=Ei({positions:a,normals:h,indices:c});return s.size>=16&&s.clear(),s.set(n,u),u}function Sv(t,e,n={}){const s=t.ink??n.ink??"#26262b",i=(n.outline??2)*(t.outline??1),o=t.glow&&e.glow>0?Tv(t.glow.color,e.glow):void 0;return{color:t.fill??s,creases:xs(t.shape).creases!==!1,shading:n.shading??"toon",...i>0?{outline:{width:i,color:s}}:{},...o?{emissive:o}:{},...t.seeThrough?{opacity:.45*e.opacity}:e.opacity<1?{opacity:e.opacity}:{}}}function Tv(t,e){const n=/^#([0-9a-f]{6})$/i.exec(t.trim());return n?`#${[0,2,4].map(i=>Math.round(parseInt(n[1].slice(i,i+2),16)*Math.max(0,Math.min(1,e)))).map(i=>i.toString(16).padStart(2,"0")).join("")}`:t}const Ev=Ei(Ru(1,.002,28));function Av(t,e,n){const s=t.rig,[i,o]=s.footprint??[s.length*.45,s.length],r=Math.max(0,mt(s,e,"lift")),a=Math.max(0,mt(s,e,"size"))/(1+r*.8);return{mesh:Ev,world:wt(n,qo([0,.004,0],[0,0,0,1],[i*.55*a||1e-4,1,o*.55*a||1e-4])),material:{color:"#000000",shading:"unlit",opacity:.16*a}}}const xv=new Set(["x","y","z","position","rotateX","rotateY","rotateZ","quaternion","scale","scaleX","scaleY","scaleZ","visible","opacity","color"]),$v=1,Pv={kind:"prop",validate(t){const e=t,n=typeof e.prop=="string"&&e.prop in Rn?[]:[ot("prop preset",e.prop,Object.keys(Rn))];for(const[s,i]of[[0,"rotateX"],[1,"rotateY"],[2,"rotateZ"]])i in e&&n.push(`${i} is a track, not a field: place it turned with rotation: [${[0,1,2].map(o=>o===s?e[i]:0).join(", ")}]`);return n},prepare(t){const e=t;return Kf(e.prop,e.options)},resolve({object:t,prepared:e,values:n,world:s,camera:i,lights:o=[],fog:r,toScreen:a}){const l=t,c=e,h={...l.values};for(const[E,x]of n)typeof x=="number"&&!xv.has(E)&&(h[E]=x);h.turn=0,h.tilt=0;const u=wt(i.view,s),d={toView:E=>Dt(u,E),toScreen:E=>a(E)},f=d.toView([0,c.rig.height/2,0]);if(-f[2]<=i.near)return null;if(l.look==="mesh"){const E=gf(c.rig,h),x=E.map(({part:v,local:$})=>({part:v.id,mesh:xs(v.shape),...Za(xs(v.shape),$)})),S=lf(x),I=E.map((v,$)=>({...v,hidden:hf(v.part.id,x[$].mesh,v.local,x[$].key,S)})).filter(({opacity:v})=>v>.01).map(({part:v,matrix:$,glow:_,opacity:P,hidden:C})=>({mesh:Mv(v.shape,C),world:wt(s,$),material:Sv(v,{glow:_,opacity:P},{shading:l.shading,ink:l.ink,outline:l.outline})}));return{meshes:l.shadow===!1?I:[Av(c,h,s),...I]}}const p=a(f),g=a(d.toView([0,c.rig.height/2+1,0])),m=Math.hypot(g.x-p.x,g.y-p.y),y=o.length===0?void 0:(E,x)=>{const S=Dt(s,E),I=[s[0]*x[0]+s[4]*x[1]+s[8]*x[2],s[1]*x[0]+s[5]*x[1]+s[9]*x[2],s[2]*x[0]+s[6]*x[1]+s[10]*x[2]],v=Math.hypot(...I)||1;return{light:I0(S,[I[0]/v,I[1]/v,I[2]/v],o),fog:O0(r,Math.hypot(S[0]-i.position[0],S[1]-i.position[1],S[2]-i.position[2]))}},T=sl(c.rig,h,d,m,{perspective:!0,near:i.near,slice:$v,light:y}),k={look:l.look,style:l.style,ink:l.ink,paper:l.paper,fog:r?.color},b=la(T),A=T.cells??[],M=Math.max(...A.map(E=>-E.depth),-f[2]);return{drawables:[...l.shadow===!1?[]:[{depth:M+c.rig.length,draw:E=>ca(E,T,k)}],...A.map(E=>({depth:-E.depth,draw(x,S){x.lineCap="round",x.lineJoin="round",_0(x,E.parts,b,{...k,time:S.time})}}))]}}},dl=["do","at","for","to","through","toward","speed","height","open","on","wind"],Iv=.25,Ov=800/180,_v=220,Cv=300,Hv=["turn"];function Rv(t){const e=uo(t),n=Object.keys(t.moves??{});return Object.keys(e).filter(s=>!n.includes(s)&&!Hv.includes(s)&&!(e[s].needs??[]).includes("to"))}function Jf(t,e){if(!Array.isArray(t))return[{beat:-1,message:`Beats must be an array of { do: … } objects (got ${typeof t}).`}];const n=Object.keys(e.moves??{}),s=Rv(e),i=[...n,"face","hold",...s.filter(r=>r!=="hold")],o=[];return t.forEach((r,a)=>{const l=u=>o.push({beat:a,message:u});if(!r||typeof r!="object"||Array.isArray(r))return l(`Each beat must be an object like { do: '${i[0]??"hold"}' }.`);const c=r,h={duration:"for",path:"through",points:"through",position:"to",heading:"toward",direction:"toward"};for(const u of Object.keys(c))dl.includes(u)||l(ot("beat field",u,dl,h[u]));if(typeof c.do!="string"||!i.includes(c.do)){const u=c.do==="turn"?"face":void 0;return l(ot(`${e.kind} 3D beat`,c.do,i,u))}n.includes(c.do)&&(c.to===void 0&&c.through===void 0&&l(`\`${c.do}\` needs \`to\` ([x, z] metres) or \`through\` (a list of them).`),c.to!==void 0&&!Ge(c.to)&&l(`\`to\` is a point on the ground, [x, z] metres (got ${JSON.stringify(c.to)}).`),c.through!==void 0&&!(Array.isArray(c.through)&&c.through.length>0&&c.through.every(Ge))&&l("`through` is a list of points on the ground, each [x, z] metres.")),c.do==="face"&&!(Ge(c.toward)||typeof c.toward=="number")&&l("`face` needs `toward`: a point [x, z] or a heading in degrees.")}),o}function Lv(t,e,n,s){const i=Jf(n,e);if(i.length>0)throw new Error(`propScript3D (${e.kind}): ${i.length} problem(s) in the beats:
|
|
65
65
|
${i.map(k=>` beat ${k.beat}: ${k.message}`).join(`
|
|
66
|
-
`)}`);const o={};for(const k of[...Object.keys(kn),...Object.keys(e.rig.controls)])o[k]=s.values?.[k]??ft(e.rig,{},k);let[r,a]=s.position??[0,0],l=s.heading??0;const c=new Map,h=(k,y,M,$="linear")=>{const E=c.get(k)??[];E.push({time:y,value:M,easing:$}),c.set(k,E)},d=(k,y,M)=>h(k,y,M);h("x",0,r),h("z",0,a),h("rotateY",0,l);const u=(k,y)=>{const M=mi(l,y);if(Math.abs(M)<1)return k;const $=Math.max(Rk,Math.abs(M)*Hk);return d("rotateY",k,l),l+=M,h("rotateY",k+$,l,"ease-in-out"),k+$},f=(k,y,M)=>{const $=Ad([[r,a],...y.through??[y.to]]);if($.length<2)return M;const E=u(M,gn($[0].point,$[1].point)),A=$[$.length-1].at,T=y.for??A/(y.speed??k.speed)*1e3,I=xt("ease-in-out"),v=Math.min(Lk,T/4);for(const[D,W]of Object.entries(k.set??{}))d(D,E,o[D]),h(D,E+1,W),o[D]=W;const P=k.flies?y.height??(o.lift>.05?o.lift:2):void 0,H=P!==void 0&&P>.05;for(const[D,W]of Object.entries(k.hold??{}))d(D,E,o[D]),h(D,E+v,W,"ease-out"),H||(h(D,E+T-v,W),h(D,E+T,0,"ease-in")),o[D]=H?W:0;P!==void 0&&(d("lift",E,o.lift),h("lift",E+Math.min(T*.35,1400),P,"ease-out"),h("lift",E+T,P),o.lift=P);const O={...o};let C=l;for(let D=0;;D=Math.min(A,D+Ck)){const W=E+Pd(I,D/A)*T,{point:B,direction:_}=$d($,D);C+=mi(C,gn([0,0],_)),h("x",W,B[0]),h("z",W,B[1]),h("rotateY",W,C);for(const[L,N]of Object.entries(k.perMetre??{}))h(L,W,O[L]+D*N);for(const[L,N]of Object.entries(k.perSecond??{}))h(L,W,O[L]+(W-E)/1e3*N);if(D>=A)break}for(const[D,W]of Object.entries(k.perMetre??{}))o[D]=O[D]+A*W;for(const[D,W]of Object.entries(k.perSecond??{}))o[D]=O[D]+T/1e3*W;return[r,a]=$[$.length-1].point,l=C,E+T},g=(k,y)=>{const M=Object.fromEntries(Object.entries(k).filter(([E])=>!["at","to","through","toward"].includes(E))),$=Mf(t,e,[M],{start:{...o,turn:1},scale:100,style:s.style,exaggeration:s.exaggeration});for(const E of $.tracks){if(jk.includes(E.property))continue;const A=E.keyframes??[],T=o[E.property];if(!A.every(I=>I.value===T)){d(E.property,y,T);for(const I of A)I.time>0&&c.get(E.property).push({...I,time:y+I.time});o[E.property]=A[A.length-1].value}}return y+$.duration},p=[];let m=0;for(const k of n){const y=k.at??m;let M=y;const $=e.moves?.[k.do];$?M=f($,k,y):k.do==="face"?M=u(y,typeof k.toward=="number"?k.toward:gn([r,a],k.toward)):k.do==="hold"?M=y+(k.for??1e3):M=g(k,y),p.push({do:k.do,start:y,end:M}),m=M}const b=`${s.scene}/${t}`;return{tracks:[...c].map(([k,y])=>({id:`${t}-${k}`,target:b,property:k,keyframes:Ed(y)})),duration:m,beats:p,end:{position:[r,a],heading:l,values:{...o}}}}const jk=["x","y","turn","facing","tilt"],Bk=.35,$f={seated:Re.sit,astride:{...Re.sit,"leg.left.spread":26,"leg.right.spread":26,"leg.left.swing":40,"leg.right.swing":40,"leg.left.knee":70,"leg.right.knee":70}},Pf=(t,e)=>{const n=e*Math.PI/180;return[t[0]*Math.cos(n)+t[2]*Math.sin(n),t[1],-t[0]*Math.sin(n)+t[2]*Math.cos(n)]};function Wk(t){const e=`${t.scene}/${t.propId}`,n=new Ht({id:`${t.propId}-ride-3d`,tracks:t.propTracks.filter(m=>m.target===e)}),s=t.placement??{},[i,o,r]=s.position??[0,0,0],a=t.prop.rig,l=mr({...t.character,height:1}),c={...ut,...t.pose??$f.seated},h=oi(l.plan,c,{height:t.height??1.7,contact:l.contact}).hip,d=t.facing??0,u=t.every??33,f={x:[],y:[],z:[],rotateY:[]};for(let m=t.start;;m=Math.min(t.end,m+u)){const b=n.getStateAtTime(m).values.get(e)??new Map,S=(O,C)=>{const j=b.get(O);return typeof j=="number"?j:C},k={...s.values};for(const O of Object.keys(a.controls))k[O]=S(O,s.values?.[O]??ft(a,{},O));for(const O of["pitch","roll","squash","lift","lean","size"])k[O]=S(O,s.values?.[O]??ft(a,{},O));const y=qu(a,k)[t.anchor];if(!y)throw new Error(`propRide3D: ${t.prop.kind} has no anchor "${t.anchor}" (it has ${Object.keys(a.anchors??{}).join(", ")||"none"})`);const M=S("rotateY",s.heading??0),$=Pf(y,M),E=[S("x",i)+$[0],S("y",o)+$[1],S("z",r)+$[2]],A=M+d,T=Pf(h,A);let I=[E[0]-T[0],E[1]-T[1],E[2]-T[2]];const v=(O,C)=>{const j=C*C*(3-2*C);return[O[0]+(I[0]-O[0])*j,I[1]*j+Bk*Math.sin(Math.PI*C),O[1]+(I[2]-O[1])*j]},P=t.mount?Math.max(1,t.mount.for??450):0,H=t.dismount?Math.max(1,t.dismount.for??450):0;if(t.mount&&m<t.start+P?I=v(t.mount.from,(m-t.start)/P):t.dismount&&m>t.end-H&&(I=v(t.dismount.to,(t.end-m)/H)),f.x.push({time:m,value:I[0]}),f.y.push({time:m,value:I[1]}),f.z.push({time:m,value:I[2]}),f.rotateY.push({time:m,value:A}),m>=t.end)break}const g=t.riderId,p=`${t.scene}/${g}`;return Object.keys(f).map(m=>({id:`${g}-${m}`,target:p,property:m,keyframes:f[m]}))}function qk(t){const{timeline:e}=t,n=new _e;for(const[c,h]of Object.entries(t.targets)){const d=typeof h=="string"?document.querySelector(h):h;if(!d)throw new Error(`quickPlay: no element found for target "${c}" (${String(h)})`);n.registerTarget(c,d)}e.onUpdate=c=>{n.applyState(c),t.onUpdate?.(c)},t.onComplete&&(e.onComplete=t.onComplete);let s=null,i=null,o=!1;const r=c=>{if(o)return;const h=i===null?0:c-i;i=c,h>0&&e.tick(h),s=requestAnimationFrame(r)},a=()=>{s!==null||o||(i=null,s=requestAnimationFrame(r))},l=()=>{s!==null&&cancelAnimationFrame(s),s=null,i=null};return n.applyState(e.getStateAtTime(e.currentTime)),t.autoplay!==!1&&(e.play(),a()),{timeline:e,adapter:n,play(){e.play(),a()},pause(){e.pause(),l()},restart(){e.stop(),e.play(),a()},seek(c){e.seek(c*1e3),n.applyState(e.getStateAtTime(e.currentTime))},destroy(){o=!0,l(),e.stop(),n.clearTargets()}}}const Kk={timeline:Ep,to(t,e,n){const s=new Oe(n);return s.to(t,e),s},from(t,e,n){const s=new Oe(n);return s.from(t,e),s},fromTo(t,e,n,s){const i=new Oe(s);return i.fromTo(t,e,n),i},set(t,e,n){const s=new Oe(n);return s.set(t,e),s}};function xf(t,e,n){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(e,n);const s=t.canvas;if(s?.ownerDocument){const i=s.ownerDocument.createElement("canvas");return i.width=e,i.height=n,i}try{return s?.constructor?new s.constructor(e,n):null}catch{return null}}function Yk(t,e){const n=t.length/4,s=new Float32Array(n*3),i=Math.min(.999,Math.max(0,e));for(let o=0;o<n;o++){const r=t[o*4]/255,a=t[o*4+1]/255,l=t[o*4+2]/255,c=t[o*4+3]/255,h=Math.max(r,a,l);if(h<=i)continue;const d=(h-i)/(1-i)*c/h;s[o*3]=r*d,s[o*3+1]=a*d,s[o*3+2]=l*d}return s}function If(t,e,n,s,i){const o=new Float32Array(t.length),r=i?n:e,a=i?e:n,l=(h,d)=>(i?h*e+d:d*e+h)*3,c=s*2+1;for(let h=0;h<r;h++)for(let d=0;d<3;d++){let u=0;for(let f=-s;f<=s;f++)u+=t[l(h,Math.min(a-1,Math.max(0,f)))+d];for(let f=0;f<a;f++){o[l(h,f)+d]=u/c;const g=t[l(h,Math.max(0,f-s))+d],p=t[l(h,Math.min(a-1,f+s+1))+d];u+=p-g}}return o}function Of(t,e,n,s){const i=Math.max(1,Math.round(s/Math.sqrt(3)));let o=t;for(let r=0;r<3;r++)o=If(o,e,n,i,!0),o=If(o,e,n,i,!1);return o}function zk(t,e={}){const n=t.canvas,s=n.width,i=n.height;if(!(s>0&&i>0))return;const o=Math.max(1,Math.round(e.downsample??4)),r=Math.max(1,Math.ceil(s/o)),a=Math.max(1,Math.ceil(i/o)),l=xf(t,r,a),c=l?.getContext("2d");if(!l||!c)return;c.imageSmoothingEnabled=!0,c.drawImage(t.canvas,0,0,r,a);const h=Yk(c.getImageData(0,0,r,a).data,e.threshold??.55),d=(e.radius??Math.max(s,i)*.02)/o,u=Of(h,r,a,d),f=Of(h,r,a,d*3),g=e.halo??.6,p=c.createImageData(r,a);for(let m=0;m<r*a;m++){for(let b=0;b<3;b++)p.data[m*4+b]=Math.round(Math.min(1,u[m*3+b]+f[m*3+b]*g)*255);p.data[m*4+3]=255}c.putImageData(p,0,0),t.save(),t.setTransform(1,0,0,1,0,0),t.globalCompositeOperation="lighter",t.globalAlpha=Math.max(0,e.strength??.9),t.imageSmoothingEnabled=!0,t.drawImage(l,0,0,s,i),t.restore()}function Xk(t,e,n){const s=n.width??6,i=n.taper??1,o=n.fade??1,r=n.opacity??1,a=n.blend==="add";if(t.save(),e.length>=2){const c=Gk(e,s,i,o,r);a?(t.globalCompositeOperation="lighter",Aa(t,c,n.color)):Vk(t,c,n.color)}const l=e[e.length-1];if(n.head&&l&&n.head.radius>0){a&&(t.globalCompositeOperation="lighter");const c=n.head.color??n.color,h=t.createRadialGradient(l.at.x,l.at.y,0,l.at.x,l.at.y,n.head.radius);h.addColorStop(0,c),h.addColorStop(.35,c),h.addColorStop(1,Uk(t,c)),t.globalAlpha=r,t.fillStyle=h,t.beginPath(),t.arc(l.at.x,l.at.y,n.head.radius,0,Math.PI*2),t.fill()}t.restore()}function Uk(t,e){t.fillStyle=e;const n=String(t.fillStyle),s=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/i.exec(n);if(s)return`rgba(${parseInt(s[1],16)}, ${parseInt(s[2],16)}, ${parseInt(s[3],16)}, 0)`;const i=/^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(n);return i?`rgba(${i[1]}, ${i[2]}, ${i[3]}, 0)`:"rgba(0, 0, 0, 0)"}function Gk(t,e,n,s,i){const o=t.map(c=>({x:c.at.x,y:c.at.y,width:e*(1-n*c.age)})),r=Dl(o),a=Fl(o)??void 0,l=[];for(let c=0;c+1<t.length;c++){const h=(t[c].age+t[c+1].age)/2,d=i*(1-s*h);if(d<=0)continue;const u=c+2===t.length;l.push({corners:[r.left[c],r.left[c+1],r.right[c+1],r.right[c]],alpha:d,...u&&a&&{cap:a}})}return l}function Aa(t,e,n){t.fillStyle=n;for(const s of e){const[i,o,r,a]=s.corners;t.globalAlpha=Math.min(1,s.alpha),t.beginPath(),t.moveTo(i.x,i.y),t.lineTo(o.x,o.y),s.cap&&t.arc(s.cap.x,s.cap.y,s.cap.radius,s.cap.start,s.cap.start-Math.PI,!0),t.lineTo(r.x,r.y),t.lineTo(a.x,a.y),t.closePath(),t.fill()}}function Vk(t,e,n){const s=typeof t.getTransform=="function"?t.getTransform():null,i=p=>s?{x:s.a*p.x+s.c*p.y+s.e,y:s.b*p.x+s.d*p.y+s.f}:p,o=s?Math.sqrt(Math.abs(s.a*s.d-s.b*s.c)):1,r=e.map(p=>({...p,corners:p.corners.map(i),...p.cap&&{cap:{...p.cap,...i(p.cap),radius:p.cap.radius*o,start:p.cap.start+(s?Math.atan2(s.b,s.a):0)}}}));let a=1/0,l=1/0,c=-1/0,h=-1/0;for(const p of r){const m=p.cap?[{x:p.cap.x-p.cap.radius,y:p.cap.y-p.cap.radius},{x:p.cap.x+p.cap.radius,y:p.cap.y+p.cap.radius}]:[];for(const b of[...p.corners,...m])a=Math.min(a,b.x),l=Math.min(l,b.y),c=Math.max(c,b.x),h=Math.max(h,b.y)}if(!(c>a&&h>l))return;const d=Math.floor(a)-1,u=Math.floor(l)-1,f=s?xf(t,Math.ceil(c)+1-d,Math.ceil(h)+1-u):null,g=f?.getContext("2d");if(!f||!g){Aa(t,e,n);return}g.translate(-d,-u),g.globalCompositeOperation="lighter",Aa(g,r,n),t.save(),t.setTransform(1,0,0,1,0,0),t.globalAlpha=1,t.drawImage(f,d,u),t.restore()}const Jk=Lt.to,Zk=Lt.from,Qk=Lt.fromTo,t2=Lt.set,e2=Lt.timeline,n2=Lt.ticker,s2=Lt.splitText,i2=Lt.context,o2=Lt.matchMedia,r2=Lt.quickTo,a2=Lt.imageSequence,l2=Lt.pageTransition;Zg(),w.ACTING_STYLES=je,w.AIRCRAFT_ACTING=wa,w.ANIMAL_GAITS=Sn,w.BEAT_FIELDS=Ai,w.BEAT_MOMENTS=bn,w.BIRD_ACTING=mf,w.BOARD_MARKS=Br,w.BOARD_THEMES=ss,w.CANVAS_PROPERTIES=Oi,w.CHARACTER_BEAT_3D_FIELDS=_r,w.CHARACTER_GAIT_SPEEDS=xd,w.CHART_KINDS=qr,w.CHART_SURFACE=Fe,w.CHART_THEMES=is,w.CODE_LANGUAGES=Mi,w.CODE_PANEL_EDITS=jr,w.CODE_SURFACE=ns,w.CODE_THEME=Ld,w.Clock=Rf,w.CompatTimeline=Oe,w.CustomBounce=$c,w.CustomEase=Ac,w.CustomWiggle=Pc,w.DANCE_STYLES=ye,w.DEFAULT_BAKE_INTERVAL_MS=oo,w.DEFAULT_INERTIA_FRICTION=Xi,w.DEFAULT_LABELS=Nc,w.DEFAULT_SPRING=Bt,w.DEFAULT_TRANSITION=tm,w.Draggable=$o,w.EXPRESSIONS=ct,w.FINGERS=Qc,w.FLIPS=Vn,w.FORMAT_VERSION=Bi,w.GAGS=Me,w.GAITS=Ot,w.GAIT_CYCLE_MS=ta,w.HAND_REST=vt,w.HAND_SHAPES=Tt,w.HORSE_ACTING=nk,w.HORSE_GAITS=Zw,w.HOUSE_ACTING=rf,w.HUMAN_ACTING_RIG=Xd,w.HUMAN_EXPRESSIONS=rr,w.HUMAN_GAGS=gi,w.HUMAN_POSES=Re,w.HUMAN_REST=ut,w.IDENTITY_CAMERA=Od,w.INERTIA_MAX_DURATION_MS=Ca,w.InertiaTrackPlayer=wl,w.LiveTimeline=Zt,w.MORPH_SAMPLES=s0,w.MUDRAS=Us,w.ManualClock=Hf,w.MediaSync=Bo,w.Observer=sc,w.POSES=Dt,w.PROP_BEAT_3D_FIELDS=Ea,w.PROP_BEAT_FIELDS=Fi,w.PROP_COMMON_ACTIONS=Sa,w.PROP_COMMON_CONTROLS=kn,w.PROP_PRESETS=Tn,w.PROP_SURFACE=Mn,w.QUADRUPED_ACTING=ka,w.REMOVE_STYLES=ki,w.REST_POSE=et,w.RIDING_POSES=$f,w.SAMPLE_STEP=Ne,w.SCRIPT_ACTIONS=as,w.SPRING_MAX_DURATION_MS=zi,w.SPRING_PRESETS=ys,w.SPRING_STEP_MS=Ye,w.STICK_ACTING_RIG=zd,w.ScrollAnimator=wc,w.ScrollDriver=Dn,w.ScrollMarkers=kc,w.ScrollPin=gc,w.SmoothScroll=Do,w.SpringSampler=$n,w.SpringTrackPlayer=bl,w.Stage=Jl,w.TREE_ACTING=sf,w.Timeline=Ht,w.TinyflyPlayer=Ns,w.TinyflySequencer=Yc,w.TrackPlayer=Ts,w.VEHICLE_ACTING=zu,w.VISEMES=Se,w.ValueResolver=O0,w.VisibilityDriver=pc,w.WHITEBOARD_SURFACE=ne,w.actCharacterTracks=Ob,w.actKeyframes=Ti,w.actTracks=Gd,w.actionNames=Vr,w.airplane=lf,w.anchorError=ve,w.animalStrideLength=Ni,w.animatableProperties=Pu,w.applyBloom=zk,w.applyCamera=jy,w.applyGroove=Rh,w.assertBeats=Qr,w.backOut=qa,w.bakeDanceTracks=y1,w.bakeEasing=lo,w.bakeInertiaTrack=ao,w.bakeSpringTrack=ro,w.basicOutfit=Mb,w.beatAt=p1,w.beatAtTime=As,w.beatLength=mo,w.beatTime=Es,w.beatsBetween=q0,w.bike=tf,w.bindChoiceHotspots=Bc,w.bird=Di,w.blendPose=cn,w.boilFrame=qo,w.bounceOut=Wa,w.boxMesh=yd,w.bus=Vu,w.cameraFromValues=Fy,w.cameraPoint=By,w.cameraTracks=X0,w.capabilities=Sf,w.capabilitiesMarkdown=pk,w.car=Uu,w.cart=Zu,w.cat=ff,w.changingWindows=wi,w.character=mr,w.characterAt=my,w.characterHandPose=ed,w.characterJoints=Zh,w.characterJointsInView=dy,w.characterObjects=_y,w.characterPartsInView=sd,w.characterPoseTracks=yy,w.characterScript3D=Dy,w.characterTarget=gy,w.charactersFor=kl,w.chart=mb,w.checkBeats=ls,w.checkCast=Jr,w.checkCharacterBeats3D=Id,w.checkPropBeats=vf,w.checkPropBeats3D=Af,w.checkSurfaceBeats=Eu,w.checkTracks=Tw,w.chicken=wf,w.circlePath=Yy,w.clamp01=Ho,w.clearMorphCache=u0,w.clearPathCache=Zf,w.clipErased=Dr,w.closestName=Hn,w.codePanel=nb,w.codeTokens=Dd,w.containerProgressAt=Ro,w.context=i2,w.controlValue=ft,w.cow=pf,w.create=Ng,w.createControls=Fc,w.createCubicBezier=ja,w.createLive=Oc,w.createPen=Wn,w.createRandom=$e,w.createTrack=Ss,w.criticalDamping=Df,w.crow=bf,w.customBounce=Ol,w.customEase=Il,w.customWiggle=_l,w.cylinderMesh=bd,w.danceFrame=Js,w.dancePose=c1,w.danceStance=Vs,w.danceTaps=d1,w.danceTracks=m1,w.danceTravel=Qs,w.danceTravelTrack=jh,w.dancer=g1,w.defineAction=qb,w.defineGait=Kb,w.describeTarget=$u,w.deserializeTimeline=Ze,w.deserializeTrack=Tl,w.detectTempo=K0,w.dog=uf,w.draggable=Vp,w.drawCartoonHand=Ys,w.drawCharacter=nd,w.drawCharacterInView=uy,w.drawDustPuff=Zd,w.drawEraser=Lr,w.drawHand=Nr,w.drawImpactStars=Rb,w.drawPencil=_d,w.drawProp=Bw,w.drawPropEffects=gk,w.drawPropShadow=Tr,w.drawSolvedFaces=ld,w.drawSolvedPart=vy,w.drawSolvedProp=Mr,w.drawSpeedLines=Jd,w.drawStickFigure=Ih,w.drawStickSmear=Hb,w.drawTrail=Xk,w.drawnPathTarget=zy,w.easeIn=Na,w.easeInCubic=Ui,w.easeInOut=Fa,w.easeInOutCubic=xn,w.easeInOutQuad=La,w.easeInQuad=Ha,w.easeOut=Da,w.easeOutCubic=Gi,w.easeOutQuad=Ra,w.editDistance=Rl,w.editError=es,w.editLog=Qn,w.elasticOut=Ba,w.ellipsePoints=Ko,w.ellipsoidMesh=wd,w.erasable=Vy,w.expandBeats=Pi,w.expandParametricEasings=ml,w.extrudeMesh=kd,w.flipPose=Bh,w.flipTracks=_1,w.flipTravel=Wh,w.formatVersionFor=Wi,w.from=Zk,w.fromJSON=P0,w.fromTo=Qk,w.gag=Xr,w.gagDuration=os,w.gaitPose=sh,w.gaitStrideLength=Xo,w.getEasingFunction=xt,w.getInterpolator=Cn,w.getMotionPathPoint=co,w.getPathLength=Qf,w.getPointAtProgress=Ua,w.gridLinesFor=rc,w.handAt=Ky,w.handJoints=Ks,w.handJointsAt=nh,w.handPath=ca,w.handPose=Mt,w.handProp=Un,w.hasKeyframes=Ia,w.hashSeed=qt,w.headPoint=Qm,w.heldTime=Oa,w.helicopter=af,w.horse=df,w.horseStrideLength=ik,w.house=of,w.humanFieldLabel=X1,w.humanGag=gd,w.humanGaitPose=fd,w.humanGaitStrideLength=pd,w.humanPlan=Kh,w.humanPose=Ft,w.imageSequence=a2,w.inertiaDuration=Xe,w.inertiaRest=ze,w.inertiaValueAt=ws,w.inertiaVelocityAt=Wf,w.interpolateArray=ul,w.interpolateColor=dl,w.interpolateMotionPath=S0,w.interpolateNumber=Gt,w.interpolatePathString=pl,w.interpolateQuaternion=fl,w.interpolateString=io,w.isCubicBezierEasing=xa,w.isInertiaTrack=re,w.isMotionPathPoint=Cf,w.isMotionPathTrack=qi,w.isParametricEasing=En,w.isPathData=Ge,w.isSpringTrack=ae,w.isTextTrack=fs,w.isUnderdamped=Nf,w.isUnresolved=I0,w.jointsInScene=od,w.jointsToScene=xh,w.linear=ks,w.lipSyncKeyframes=Gr,w.lipSyncOver=au,w.lipSyncTracks=Bb,w.lit=xr,w.live=Lt,w.mapEase=Rn,w.mat4=sp,w.matchMedia=o2,w.maxStaggerDistance=Yi,w.mirrorHumanPose=z1,w.mirrorPose=Hh,w.mixColors=Ir,w.mixHandPoses=ln,w.mixPoses=fy,w.morphPath=el,w.motorbike=ef,w.mount=Wc,w.mountAll=Kc,w.narrationMarkers=F0,w.narrationSceneAt=j0,w.naturalRest=Pn,w.nearestBeat=B0,w.nextBeat=W0,w.niceCeiling=Kd,w.pageTransition=l2,w.panelMesh=vd,w.parametricEasing=Ya,w.parseAnchor=De,w.parseEdge=_o,w.parsePath=Ae,w.parseTrigger=Co,w.partialPath=an,w.pathLength=Vc,w.persona=Mw,w.pieceMotion=ts,w.planNarration=D0,w.play=Lg,w.playSequence=Qg,w.playWhenVisible=cg,w.playheadCrossings=uo,w.pointAlong=Fs,w.pointAtDistance=Ji,w.pointOnHead=ay,w.pointsToPath=Nl,w.pose=Et,w.poseTracks=s1,w.propActions=ji,w.propAnchors3D=qu,w.propAt=Hi,w.propControls=ba,w.propLineWidth=Sr,w.propObjects=_k,w.propPartsInSpace=Wu,w.propPreset=kf,w.propRide=vk,w.propRide3D=Wk,w.propScript=Mf,w.propScript3D=Fk,w.propShapeMesh=hs,w.propSurface=Kw,w.propTarget=jw,w.propTow=Tk,w.propView=Fu,w.quadruped=us,w.quat=b0,w.quickPlay=qk,w.quickTo=r2,w.randomBetween=po,w.randomChoice=x0,w.randomSnapped=Al,w.reachCharacter=py,w.resolveActingStyle=Kr,w.resolveCharacterPoseKeys=kr,w.resolveGait=Yn,w.resolvePoseKeys=tr,w.resolveSequence=xl,w.resolveStickFrame=Jo,w.resolveStickPose=Oh,w.resolveValue=go,w.ribbon=Dl,w.ribbonHeadCap=Fl,w.rideFloors=Fr,w.rotateAbout=pe,w.routineBeats=Zs,w.rubberLimb=Ce,w.scriptActionSummaries=Zr,w.scriptTracks=la,w.scrollProgress=lg,w.scrubOnScroll=fg,w.scrubPath=Uy,w.seatHeight=Xm,w.serializeTimeline=El,w.serializeTrack=Ml,w.set=t2,w.shade=pi,w.shapeMesh=Td,w.shapeToPathData=$s,w.simplifyKeyframes=yl,w.sittingPose=hf,w.skeletonInView=ri,w.sketchPen=js,w.smoothPath=Or,w.smoothToward=fc,w.snapAxis=oc,w.snapConfig=mc,w.snapDuration=bc,w.snapProgress=yc,w.solveAt=vn,w.solvePlanSpace=ii,w.solveProp=ya,w.songbird=yf,w.soundsOf=ru,w.speechDuration=Tu,w.spliceTracks=Sk,w.splitText=s2,w.springDuration=_a,w.springFollow=Ll,w.springValueAt=Lf,w.stagePlanSpace=oi,w.staggerDistance=Ki,w.staggerOffset=ps,w.staggerOffsets=gs,w.staggerSpan=An,w.stepsDuration=cu,w.stepsEasing=Ka,w.stepsToKeys=Ur,w.stickFigureAt=Qo,w.stickFigureJoints=me,w.stickFigureTarget=Zo,w.stickToHuman=G1,w.strideLength=ch,w.surfaceBox=bt,w.surfaceScript=kw,w.syncMediaElement=Lc,w.talkingMouth=hh,w.taperedLine=Bs,w.taperedOutline=Bn,w.textAt=vl,w.tf=Kk,w.ticker=n2,w.timeline=e2,w.to=Jk,w.toJSON=$0,w.toKeyframedTrack=v0,w.toKeyframedTracks=M0,w.trackTargets=de,w.tractor=Ju,w.trailSamples=G0,w.trainCar=Qu,w.tree=nf,w.triggerDistance=nn,w.truck=Gu,w.tubeMesh=Md,w.unknownName=ot,w.unmount=Vg,w.valueAt=bi,w.vec3=J0,w.vehicle=oe,w.walkPose=lh,w.whiteboard=ab,w.withErased=Gy,w.withExpression=ge,Object.defineProperty(w,Symbol.toStringTag,{value:"Module"})})(this.tinyfly=this.tinyfly||{});
|
|
66
|
+
`)}`);const o={};for(const k of[...Object.keys(On),...Object.keys(e.rig.controls)])o[k]=s.values?.[k]??mt(e.rig,{},k);let[r,a]=s.position??[0,0],l=s.heading??0;const c=new Map,h=(k,b,A,M="linear")=>{const E=c.get(k)??[];E.push({time:b,value:A,easing:M}),c.set(k,E)},u=(k,b,A)=>h(k,b,A);h("x",0,r),h("z",0,a),h("rotateY",0,l);const d=(k,b)=>{const A=Bi(l,b);if(Math.abs(A)<1)return k;const M=Math.max(_v,Math.abs(A)*Ov);return u("rotateY",k,l),l+=A,h("rotateY",k+M,l,"ease-in-out"),k+M},f=(k,b,A)=>{const M=V0([[r,a],...b.through??[b.to]]);if(M.length<2)return A;const E=d(A,An(M[0].point,M[1].point)),x=M[M.length-1].at,S=b.for??x/(b.speed??k.speed)*1e3,I=Ct("ease-in-out"),v=Math.min(Cv,S/4);for(const[R,B]of Object.entries(k.set??{}))u(R,E,o[R]),h(R,E+1,B),o[R]=B;const $=k.flies?b.height??(o.lift>.05?o.lift:2):void 0,_=$!==void 0&&$>.05;for(const[R,B]of Object.entries(k.hold??{}))u(R,E,o[R]),h(R,E+v,B,"ease-out"),_||(h(R,E+S-v,B),h(R,E+S,0,"ease-in")),o[R]=_?B:0;$!==void 0&&(u("lift",E,o.lift),h("lift",E+Math.min(S*.35,1400),$,"ease-out"),h("lift",E+S,$),o.lift=$);const P={...o};let C=l;for(let R=0;;R=Math.min(x,R+Iv)){const B=E+Z0(I,R/x)*S,{point:j,direction:H}=J0(M,R);C+=Bi(C,An([0,0],H)),h("x",B,j[0]),h("z",B,j[1]),h("rotateY",B,C);for(const[N,D]of Object.entries(k.perMetre??{}))h(N,B,P[N]+R*D);for(const[N,D]of Object.entries(k.perSecond??{}))h(N,B,P[N]+(B-E)/1e3*D);if(R>=x)break}for(const[R,B]of Object.entries(k.perMetre??{}))o[R]=P[R]+x*B;for(const[R,B]of Object.entries(k.perSecond??{}))o[R]=P[R]+S/1e3*B;return[r,a]=M[M.length-1].point,l=C,E+S},p=(k,b)=>{const A=Object.fromEntries(Object.entries(k).filter(([E])=>!["at","to","through","toward"].includes(E))),M=Xf(t,e,[A],{start:{...o,turn:1},scale:100,style:s.style,exaggeration:s.exaggeration});for(const E of M.tracks){if(Fv.includes(E.property))continue;const x=E.keyframes??[],S=o[E.property];if(!x.every(I=>I.value===S)){u(E.property,b,S);for(const I of x)I.time>0&&c.get(E.property).push({...I,time:b+I.time});o[E.property]=x[x.length-1].value}}return b+M.duration},g=[];let m=0;for(const k of n){const b=k.at??m;let A=b;const M=e.moves?.[k.do];M?A=f(M,k,b):k.do==="face"?A=d(b,typeof k.toward=="number"?k.toward:An([r,a],k.toward)):k.do==="hold"?A=b+(k.for??1e3):A=p(k,b),g.push({do:k.do,start:b,end:A}),m=A}const y=`${s.scene}/${t}`;return{tracks:[...c].map(([k,b])=>({id:`${t}-${k}`,target:y,property:k,keyframes:U0(b)})),duration:m,beats:g,end:{position:[r,a],heading:l,values:{...o}}}}const Fv=["x","y","turn","facing","tilt"],Nv=.35,Zf={seated:ze.sit,astride:{...ze.sit,"leg.left.spread":26,"leg.right.spread":26,"leg.left.swing":40,"leg.right.swing":40,"leg.left.knee":70,"leg.right.knee":70}},Qf=(t,e)=>{const n=e*Math.PI/180;return[t[0]*Math.cos(n)+t[2]*Math.sin(n),t[1],-t[0]*Math.sin(n)+t[2]*Math.cos(n)]};function Dv(t){const e=`${t.scene}/${t.propId}`,n=new Nt({id:`${t.propId}-ride-3d`,tracks:t.propTracks.filter(m=>m.target===e)}),s=t.placement??{},[i,o,r]=s.position??[0,0,0],a=t.prop.rig,l=ta({...t.character,height:1}),c={...ft,...t.pose??Zf.seated},h=Si(l.plan,c,{height:t.height??1.7,contact:l.contact}).hip,u=t.facing??0,d=t.every??33,f={x:[],y:[],z:[],rotateY:[]};for(let m=t.start;;m=Math.min(t.end,m+d)){const y=n.getStateAtTime(m).values.get(e)??new Map,T=(P,C)=>{const F=y.get(P);return typeof F=="number"?F:C},k={...s.values};for(const P of Object.keys(a.controls))k[P]=T(P,s.values?.[P]??mt(a,{},P));for(const P of["pitch","roll","squash","lift","lean","size"])k[P]=T(P,s.values?.[P]??mt(a,{},P));const b=pf(a,k)[t.anchor];if(!b)throw new Error(`propRide3D: ${t.prop.kind} has no anchor "${t.anchor}" (it has ${Object.keys(a.anchors??{}).join(", ")||"none"})`);const A=T("rotateY",s.heading??0),M=Qf(b,A),E=[T("x",i)+M[0],T("y",o)+M[1],T("z",r)+M[2]],x=A+u,S=Qf(h,x);let I=[E[0]-S[0],E[1]-S[1],E[2]-S[2]];const v=(P,C)=>{const F=C*C*(3-2*C);return[P[0]+(I[0]-P[0])*F,I[1]*F+Nv*Math.sin(Math.PI*C),P[1]+(I[2]-P[1])*F]},$=t.mount?Math.max(1,t.mount.for??450):0,_=t.dismount?Math.max(1,t.dismount.for??450):0;if(t.mount&&m<t.start+$?I=v(t.mount.from,(m-t.start)/$):t.dismount&&m>t.end-_&&(I=v(t.dismount.to,(t.end-m)/_)),f.x.push({time:m,value:I[0]}),f.y.push({time:m,value:I[1]}),f.z.push({time:m,value:I[2]}),f.rotateY.push({time:m,value:x}),m>=t.end)break}const p=t.riderId,g=`${t.scene}/${p}`;return Object.keys(f).map(m=>({id:`${p}-${m}`,target:g,property:m,keyframes:f[m]}))}function Wv(t){const{timeline:e}=t,n=new qe;for(const[c,h]of Object.entries(t.targets)){const u=typeof h=="string"?document.querySelector(h):h;if(!u)throw new Error(`quickPlay: no element found for target "${c}" (${String(h)})`);n.registerTarget(c,u)}e.onUpdate=c=>{n.applyState(c),t.onUpdate?.(c)},t.onComplete&&(e.onComplete=t.onComplete);let s=null,i=null,o=!1;const r=c=>{if(o)return;const h=i===null?0:c-i;i=c,h>0&&e.tick(h),s=requestAnimationFrame(r)},a=()=>{s!==null||o||(i=null,s=requestAnimationFrame(r))},l=()=>{s!==null&&cancelAnimationFrame(s),s=null,i=null};return n.applyState(e.getStateAtTime(e.currentTime)),t.autoplay!==!1&&(e.play(),a()),{timeline:e,adapter:n,play(){e.play(),a()},pause(){e.pause(),l()},restart(){e.stop(),e.play(),a()},seek(c){e.seek(c*1e3),n.applyState(e.getStateAtTime(e.currentTime))},destroy(){o=!0,l(),e.stop(),n.clearTargets()}}}const Bv={timeline:Vp,to(t,e,n){const s=new je(n);return s.to(t,e),s},from(t,e,n){const s=new je(n);return s.from(t,e),s},fromTo(t,e,n,s){const i=new je(s);return i.fromTo(t,e,n),i},set(t,e,n){const s=new je(n);return s.set(t,e),s}};function tg(t,e,n){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(e,n);const s=t.canvas;if(s?.ownerDocument){const i=s.ownerDocument.createElement("canvas");return i.width=e,i.height=n,i}try{return s?.constructor?new s.constructor(e,n):null}catch{return null}}function jv(t,e){const n=t.length/4,s=new Float32Array(n*3),i=Math.min(.999,Math.max(0,e));for(let o=0;o<n;o++){const r=t[o*4]/255,a=t[o*4+1]/255,l=t[o*4+2]/255,c=t[o*4+3]/255,h=Math.max(r,a,l);if(h<=i)continue;const u=(h-i)/(1-i)*c/h;s[o*3]=r*u,s[o*3+1]=a*u,s[o*3+2]=l*u}return s}function eg(t,e,n,s,i){const o=new Float32Array(t.length),r=i?n:e,a=i?e:n,l=(h,u)=>(i?h*e+u:u*e+h)*3,c=s*2+1;for(let h=0;h<r;h++)for(let u=0;u<3;u++){let d=0;for(let f=-s;f<=s;f++)d+=t[l(h,Math.min(a-1,Math.max(0,f)))+u];for(let f=0;f<a;f++){o[l(h,f)+u]=d/c;const p=t[l(h,Math.max(0,f-s))+u],g=t[l(h,Math.min(a-1,f+s+1))+u];d+=g-p}}return o}function ng(t,e,n,s){const i=Math.max(1,Math.round(s/Math.sqrt(3)));let o=t;for(let r=0;r<3;r++)o=eg(o,e,n,i,!0),o=eg(o,e,n,i,!1);return o}function qv(t,e={}){const n=t.canvas,s=n.width,i=n.height;if(!(s>0&&i>0))return;const o=Math.max(1,Math.round(e.downsample??4)),r=Math.max(1,Math.ceil(s/o)),a=Math.max(1,Math.ceil(i/o)),l=tg(t,r,a),c=l?.getContext("2d");if(!l||!c)return;c.imageSmoothingEnabled=!0,c.drawImage(t.canvas,0,0,r,a);const h=jv(c.getImageData(0,0,r,a).data,e.threshold??.55),u=(e.radius??Math.max(s,i)*.02)/o,d=ng(h,r,a,u),f=ng(h,r,a,u*3),p=e.halo??.6,g=c.createImageData(r,a);for(let m=0;m<r*a;m++){for(let y=0;y<3;y++)g.data[m*4+y]=Math.round(Math.min(1,d[m*3+y]+f[m*3+y]*p)*255);g.data[m*4+3]=255}c.putImageData(g,0,0),t.save(),t.setTransform(1,0,0,1,0,0),t.globalCompositeOperation="lighter",t.globalAlpha=Math.max(0,e.strength??.9),t.imageSmoothingEnabled=!0,t.drawImage(l,0,0,s,i),t.restore()}function Yv(t,e,n){const s=n.width??6,i=n.taper??1,o=n.fade??1,r=n.opacity??1,a=n.blend==="add";if(t.save(),e.length>=2){const c=zv(e,s,i,o,r);a?(t.globalCompositeOperation="lighter",fl(t,c,n.color)):Xv(t,c,n.color)}const l=e[e.length-1];if(n.head&&l&&n.head.radius>0){a&&(t.globalCompositeOperation="lighter");const c=n.head.color??n.color,h=t.createRadialGradient(l.at.x,l.at.y,0,l.at.x,l.at.y,n.head.radius);h.addColorStop(0,c),h.addColorStop(.35,c),h.addColorStop(1,Kv(t,c)),t.globalAlpha=r,t.fillStyle=h,t.beginPath(),t.arc(l.at.x,l.at.y,n.head.radius,0,Math.PI*2),t.fill()}t.restore()}function Kv(t,e){t.fillStyle=e;const n=String(t.fillStyle),s=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/i.exec(n);if(s)return`rgba(${parseInt(s[1],16)}, ${parseInt(s[2],16)}, ${parseInt(s[3],16)}, 0)`;const i=/^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(n);return i?`rgba(${i[1]}, ${i[2]}, ${i[3]}, 0)`:"rgba(0, 0, 0, 0)"}function zv(t,e,n,s,i){const o=t.map(c=>({x:c.at.x,y:c.at.y,width:e*(1-n*c.age)})),r=Ec(o),a=Ac(o)??void 0,l=[];for(let c=0;c+1<t.length;c++){const h=(t[c].age+t[c+1].age)/2,u=i*(1-s*h);if(u<=0)continue;const d=c+2===t.length;l.push({corners:[r.left[c],r.left[c+1],r.right[c+1],r.right[c]],alpha:u,...d&&a&&{cap:a}})}return l}function fl(t,e,n){t.fillStyle=n;for(const s of e){const[i,o,r,a]=s.corners;t.globalAlpha=Math.min(1,s.alpha),t.beginPath(),t.moveTo(i.x,i.y),t.lineTo(o.x,o.y),s.cap&&t.arc(s.cap.x,s.cap.y,s.cap.radius,s.cap.start,s.cap.start-Math.PI,!0),t.lineTo(r.x,r.y),t.lineTo(a.x,a.y),t.closePath(),t.fill()}}function Xv(t,e,n){const s=typeof t.getTransform=="function"?t.getTransform():null,i=g=>s?{x:s.a*g.x+s.c*g.y+s.e,y:s.b*g.x+s.d*g.y+s.f}:g,o=s?Math.sqrt(Math.abs(s.a*s.d-s.b*s.c)):1,r=e.map(g=>({...g,corners:g.corners.map(i),...g.cap&&{cap:{...g.cap,...i(g.cap),radius:g.cap.radius*o,start:g.cap.start+(s?Math.atan2(s.b,s.a):0)}}}));let a=1/0,l=1/0,c=-1/0,h=-1/0;for(const g of r){const m=g.cap?[{x:g.cap.x-g.cap.radius,y:g.cap.y-g.cap.radius},{x:g.cap.x+g.cap.radius,y:g.cap.y+g.cap.radius}]:[];for(const y of[...g.corners,...m])a=Math.min(a,y.x),l=Math.min(l,y.y),c=Math.max(c,y.x),h=Math.max(h,y.y)}if(!(c>a&&h>l))return;const u=Math.floor(a)-1,d=Math.floor(l)-1,f=s?tg(t,Math.ceil(c)+1-u,Math.ceil(h)+1-d):null,p=f?.getContext("2d");if(!f||!p){fl(t,e,n);return}p.translate(-u,-d),p.globalCompositeOperation="lighter",fl(p,r,n),t.save(),t.setTransform(1,0,0,1,0,0),t.globalAlpha=1,t.drawImage(f,u,d),t.restore()}const Gv=Wt.to,Uv=Wt.from,Vv=Wt.fromTo,Jv=Wt.set,Zv=Wt.timeline,Qv=Wt.ticker,t5=Wt.splitText,e5=Wt.context,n5=Wt.matchMedia,s5=Wt.quickTo,i5=Wt.imageSequence,o5=Wt.pageTransition;S1(),w.ACTING_STYLES=Ze,w.AIRCRAFT_ACTING=ol,w.ANIMAL_GAITS=Hn,w.BEAT_FIELDS=Ji,w.BEAT_MOMENTS=Pn,w.BIRD_ACTING=Bf,w.BOARD_MARKS=Aa,w.BOARD_THEMES=ws,w.CANVAS_PROPERTIES=no,w.CHARACTER_BEAT_3D_FIELDS=ya,w.CHARACTER_CAST=Pa,w.CHARACTER_GAIT_SPEEDS=Q0,w.CHART_KINDS=$a,w.CHART_SURFACE=Je,w.CHART_THEMES=ks,w.CODE_LANGUAGES=Xi,w.CODE_PANEL_EDITS=Ea,w.CODE_SURFACE=bs,w.CODE_THEME=rd,w.Clock=rg,w.CompatTimeline=je,w.CustomBounce=gh,w.CustomEase=fh,w.CustomWiggle=ph,w.DANCE_STYLES=xe,w.DEFAULT_BAKE_INTERVAL_MS=Oo,w.DEFAULT_INERTIA_FRICTION=wo,w.DEFAULT_LABELS=Th,w.DEFAULT_SPRING=Yt,w.DEFAULT_TRANSITION=E1,w.Draggable=Zo,w.EXPRESSIONS=ct,w.FACIAL_HAIR_STYLES=Xr,w.FINGERS=Wh,w.FLIPS=rs,w.FORMAT_VERSION=fo,w.GAGS=_e,w.GAITS=Ht,w.GAIT_CYCLE_MS=Wa,w.GLASSES_STYLES=Ur,w.HAIR_COLORS=ae,w.HAIR_STYLES=qr,w.HAND_MEETINGS=vs,w.HAND_REST=Et,w.HAND_SHAPES=$t,w.HAT_STYLES=Hi,w.HELD_ITEMS=Jr,w.HORSE_ACTING=Q2,w.HORSE_GAITS=U2,w.HOUSE_ACTING=Of,w.HUMAN_ACTING_RIG=bd,w.HUMAN_BUILDS=wi,w.HUMAN_EXPRESSIONS=Or,w.HUMAN_GAGS=Wi,w.HUMAN_POSES=ze,w.HUMAN_REST=ft,w.IDENTITY_CAMERA=ed,w.INERTIA_MAX_DURATION_MS=kl,w.InertiaTrackPlayer=rc,w.LiveTimeline=ie,w.MORPH_SAMPLES=$g,w.MUDRAS=ui,w.ManualClock=og,w.MediaSync=dr,w.Observer=Yc,w.POSES=jt,w.PROP_BEAT_3D_FIELDS=dl,w.PROP_BEAT_FIELDS=ho,w.PROP_COMMON_ACTIONS=hl,w.PROP_COMMON_CONTROLS=On,w.PROP_PRESETS=Rn,w.PROP_SURFACE=Cn,w.QUADRUPED_ACTING=al,w.REMOVE_STYLES=Ki,w.REST_POSE=et,w.RIDING_POSES=Zf,w.SAMPLE_STEP=Ue,w.SCRIPT_ACTIONS=Ts,w.SPRING_MAX_DURATION_MS=bo,w.SPRING_PRESETS=Hs,w.SPRING_STEP_MS=nn,w.STICK_ACTING_RIG=yd,w.ScrollAnimator=rh,w.ScrollDriver=Un,w.ScrollMarkers=ah,w.ScrollPin=nh,w.SmoothScroll=cr,w.SpringSampler=Nn,w.SpringTrackPlayer=oc,w.Stage=Nc,w.TREE_ACTING=Pf,w.Timeline=Nt,w.TinyflyPlayer=ti,w.TinyflySequencer=_h,w.TrackPlayer=Bs,w.VEHICLE_ACTING=bf,w.VISEMES=Ce,w.ValueResolver=np,w.VisibilityDriver=eh,w.WHITEBOARD_SURFACE=de,w.actCharacterTracks=$k,w.actKeyframes=Ui,w.actTracks=kd,w.actionNames=La,w.airplane=Cf,w.anchorError=Oe,w.animalStrideLength=lo,w.animatableProperties=Qd,w.applyBloom=qv,w.applyCamera=Lw,w.applyGroove=Mu,w.assertBeats=Da,w.backOut=Il,w.bakeDanceTracks=jy,w.bakeEasing=Ho,w.bakeInertiaTrack=Co,w.bakeSpringTrack=_o,w.basicOutfit=y0,w.beatAt=Dy,w.beatAtTime=qs,w.beatLength=Bo,w.beatTime=js,w.beatsBetween=gp,w.bike=Af,w.bindChoiceHotspots=$h,w.bird=co,w.blendPose=kn,w.boilFrame=gr,w.bounceOut=Pl,w.boxMesh=B0,w.bus=Mf,w.cameraFromValues=Rw,w.cameraPoint=Fw,w.cameraTracks=bp,w.capabilities=Gf,w.capabilitiesMarkdown=uv,w.car=kf,w.cart=Tf,w.castMember=yk,w.cat=Nf,w.changingWindows=Yi,w.character=ta,w.characterAt=dw,w.characterHandPose=T0,w.characterJoints=sa,w.characterJointsInView=lw,w.characterObjects=$w,w.characterPartsInView=A0,w.characterPoseTracks=fw,w.characterScript3D=Hw,w.characterTarget=uw,w.charactersFor=ac,w.chart=dk,w.checkBeats=Es,w.checkCast=Fa,w.checkCharacterBeats3D=td,w.checkPropBeats=zf,w.checkPropBeats3D=Jf,w.checkSurfaceBeats=Vd,w.checkTracks=v2,w.chicken=Yf,w.circlePath=Bw,w.clamp01=or,w.clearMorphCache=Fg,w.clearPathCache=Sg,w.clipErased=Sa,w.closestName=Kn,w.codePanel=Zw,w.codeTokens=ld,w.containerProgressAt=rr,w.context=e5,w.controlValue=mt,w.cow=Df,w.create=l1,w.createControls=Ah,w.createCubicBezier=xl,w.createLive=bh,w.createPen=Zn,w.createRandom=Ne,w.createTrack=Ws,w.criticalDamping=cg,w.crow=qf,w.customBounce=bc,w.customEase=yc,w.customWiggle=wc,w.cylinderMesh=j0,w.danceFrame=gi,w.dancePose=Hy,w.danceStance=fi,w.danceTaps=Ly,w.danceTracks=By,w.danceTravel=mi,w.danceTravelTrack=xu,w.dancer=Wy,w.defineAction=Wk,w.defineGait=Bk,w.describeTarget=Zd,w.deserializeTimeline=hn,w.deserializeTrack=uc,w.detectTempo=pp,w.dog=Ff,w.draggable=vm,w.drawCartoonHand=li,w.drawCharacter=E0,w.drawCharacterInView=cw,w.drawDustPuff=Sd,w.drawEraser=va,w.drawHand=Ma,w.drawHeldItem=Zr,w.drawImpactStars=_k,w.drawPencil=nd,w.drawProp=N2,w.drawPropEffects=dv,w.drawPropShadow=ca,w.drawSolvedFaces=_0,w.drawSolvedPart=yw,w.drawSolvedProp=aa,w.drawSpeedLines=Md,w.drawStickFigure=yu,w.drawStickSmear=Ok,w.drawTrail=Yv,w.drawnPathTarget=jw,w.easeIn=Tl,w.easeInCubic=ko,w.easeInOut=Al,w.easeInOutCubic=Wn,w.easeInOutQuad=Sl,w.easeInQuad=vl,w.easeOut=El,w.easeOutCubic=vo,w.easeOutQuad=Ml,w.editDistance=Mc,w.editError=ys,w.editLog=ps,w.elasticOut=$l,w.ellipsePoints=pr,w.ellipsoidMesh=q0,w.erasable=zw,w.expandBeats=Qi,w.expandParametricEasings=sc,w.extrudeMesh=Y0,w.flipPose=$u,w.flipTracks=sb,w.flipTravel=Pu,w.formatVersionFor=go,w.from=Uv,w.fromJSON=Qg,w.fromTo=Vv,w.gag=Ca,w.gagDuration=Ms,w.gaitPose=Yh,w.gaitStrideLength=br,w.getEasingFunction=Ct,w.getInterpolator=Yn,w.getMotionPathPoint=Ro,w.getPathLength=Tg,w.getPointAtProgress=Rl,w.gridLinesFor=Xc,w.hairlineAt=hs,w.handAt=Ww,w.handGrip=Li,w.handJoints=ai,w.handJointsAt=qh,w.handPath=Ua,w.handPose=At,w.handProp=is,w.hasKeyframes=yl,w.hashSeed=zt,w.headPoint=Ty,w.heldTime=bl,w.helicopter=_f,w.holdingLayers=k0,w.horse=Lf,w.horseStrideLength=ev,w.house=If,w.humanFieldLabel=bb,w.humanGag=D0,w.humanGaitPose=F0,w.humanGaitStrideLength=N0,w.humanPlan=Ou,w.humanPose=ht,w.imageSequence=i5,w.inertiaDuration=on,w.inertiaRest=sn,w.inertiaValueAt=Ls,w.inertiaVelocityAt=fg,w.interpolateArray=Ql,w.interpolateColor=Zl,w.interpolateMotionPath=Gg,w.interpolateNumber=ee,w.interpolatePathString=ec,w.interpolateQuaternion=tc,w.interpolateString=Io,w.isCubicBezierEasing=ml,w.isHeld=Qr,w.isInertiaTrack=me,w.isMotionPathPoint=ig,w.isMotionPathTrack=po,w.isParametricEasing=Ln,w.isPathData=an,w.isSpringTrack=ye,w.isTextTrack=Is,w.isUnderdamped=lg,w.isUnresolved=ep,w.jointsInScene=P0,w.jointsToScene=mu,w.linear=Fs,w.lipSyncKeyframes=Ra,w.lipSyncOver=_d,w.lipSyncTracks=Nk,w.lit=ga,w.live=Wt,w.lyingPose=Rf,w.mapEase=zn,w.mat4=$p,w.matchMedia=n5,w.maxStaggerDistance=yo,w.meetHands=wk,w.meetingSpacing=bk,w.mirrorHumanPose=yb,w.mirrorPose=vu,w.mixColors=pa,w.mixHandPoses=wn,w.mixPoses=hw,w.morphPath=jl,w.motorbike=xf,w.mount=Ph,w.mountAll=Oh,w.narrationMarkers=hp,w.narrationSceneAt=up,w.naturalRest=Dn,w.nearestBeat=dp,w.nextBeat=fp,w.niceCeiling=gd,w.pageTransition=o5,w.panelMesh=K0,w.parametricEasing=_l,w.parseAnchor=Ve,w.parseEdge=sr,w.parsePath=Fe,w.parseTrigger=ir,w.partialPath=bn,w.pathLength=Fh,w.persona=w2,w.pieceMotion=ms,w.planNarration=cp,w.play=a1,w.playSequence=T1,w.playWhenVisible=Hm,w.playheadCrossings=Fo,w.pointAlong=ni,w.pointAtDistance=So,w.pointOnHead=iw,w.pointsToPath=Tc,w.pose=Pt,w.poseTracks=$y,w.propActions=uo,w.propAnchors3D=pf,w.propAt=oo,w.propControls=il,w.propLineWidth=la,w.propObjects=Pv,w.propPartsInSpace=gf,w.propPreset=Kf,w.propRide=bv,w.propRide3D=Dv,w.propScript=Xf,w.propScript3D=Lv,w.propShapeMesh=xs,w.propSurface=B2,w.propTarget=F2,w.propTow=vv,w.propView=uf,w.quadruped=Ps,w.quat=qg,w.quickPlay=Wv,w.quickTo=s5,w.randomBetween=Do,w.randomChoice=tp,w.randomSnapped=fc,w.reachCharacter=$0,w.resolveActingStyle=Ia,w.resolveCharacterPoseKeys=oa,w.resolveFacialHair=s0,w.resolveGait=es,w.resolveGlasses=o0,w.resolveHair=Yu,w.resolveHat=a0,w.resolveHeadLook=c0,w.resolveHolding=b0,w.resolvePoseKeys=Er,w.resolveSequence=mc,w.resolveStickFrame=Mr,w.resolveStickPose=bu,w.resolveValue=Wo,w.ribbon=Ec,w.ribbonHeadCap=Ac,w.rideFloors=Ta,w.rotateAbout=Te,w.routineBeats=pi,w.rubberLimb=Ye,w.scriptActionSummaries=Na,w.scriptTracks=Ga,w.scrollProgress=Cm,w.scrubOnScroll=Nm,w.scrubPath=Yw,w.seatHeight=by,w.serializeTimeline=dc,w.serializeTrack=cc,w.set=Jv,w.shade=Di,w.shapeMesh=G0,w.shapeToPathData=Ys,w.simplifyKeyframes=ic,w.sittingPose=rl,w.skeletonInView=Ti,w.sketchPen=si,w.smoothPath=ma,w.smoothToward=th,w.snapAxis=zc,w.snapConfig=sh,w.snapDuration=oh,w.snapProgress=ih,w.solveAt=_n,w.solvePlanSpace=Mi,w.solveProp=sl,w.songbird=jf,w.soundsOf=Od,w.speechDuration=Ud,w.spliceTracks=kv,w.splitText=t5,w.springDuration=wl,w.springFollow=Sc,w.springValueAt=ag,w.stagePlanSpace=Si,w.staggerDistance=mo,w.staggerOffset=Os,w.staggerOffsets=_s,w.staggerSpan=Fn,w.stepsDuration=Hd,w.stepsEasing=Ol,w.stepsToKeys=Ha,w.stickFigureAt=Tr,w.stickFigureJoints=Ae,w.stickFigureTarget=Sr,w.stickToHuman=vb,w.strideLength=Vh,w.surfaceBox=Mt,w.surfaceScript=y2,w.syncMediaElement=Sh,w.talkingMouth=Jh,w.taperedLine=ii,w.taperedOutline=oe,w.textAt=lc,w.tf=Bv,w.ticker=Qv,w.timeline=Zv,w.to=Gv,w.toJSON=Zg,w.toKeyframedTrack=zg,w.toKeyframedTracks=Xg,w.trackTargets=ve,w.tractor=Sf,w.trailSamples=kp,w.trainCar=Ef,w.tree=$f,w.triggerDistance=gn,w.truck=vf,w.tubeMesh=z0,w.unknownName=ot,w.unmount=v1,w.valueAt=qi,w.vec3=Mp,w.vehicle=pe,w.walkPose=Uh,w.whiteboard=sk,w.withErased=Kw,w.withExpression=Ee,Object.defineProperty(w,Symbol.toStringTag,{value:"Module"})})(this.tinyfly=this.tinyfly||{});
|