@algorisys/tinyfly 0.112.0 → 0.113.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 +5 -5
- package/docs/cricket.md +59 -1
- package/docs/editor-guide.md +1 -1
- 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 +9 -0
- package/docs/maps.md +2 -2
- package/docs/teaching.md +1 -1
- package/lib/addons/characters.js +1043 -1041
- package/lib/addons/cricket-play-DQqoiwTG.js +4936 -0
- package/lib/addons/scene-3d.js +114 -112
- package/lib/addons/sports.js +23 -19
- package/lib/browser/tinyfly-scene-3d.iife.js +2 -2
- package/lib/browser/tinyfly.iife.js +14 -14
- package/lib/browser/tinyfly.js +5863 -5753
- package/lib/browser/tinyfly.umd.js +14 -14
- package/lib/types/characters/capabilities.d.ts +2 -0
- package/lib/types/scene-3d/resolve-scene.d.ts +1 -1
- package/lib/types/sports/cricket/cricket-camera-review.d.ts +34 -0
- package/lib/types/sports/cricket/cricket-camera.d.ts +22 -4
- package/lib/types/sports/cricket/index.d.ts +2 -1
- package/llms-full.txt +79 -10
- package/llms.txt +30 -30
- package/package.json +1 -1
- package/skills/tinyfly/SKILL.md +9 -0
- package/lib/addons/cricket-play-Zm5cghdV.js +0 -4828
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
(function(y,Wn){typeof exports=="object"&&typeof module<"u"?Wn(exports):typeof define=="function"&&define.amd?define(["exports"],Wn):(y=typeof globalThis<"u"?globalThis:y||self,Wn(y.tinyfly=y.tinyfly||{}))})(this,(function(y){"use strict";function Wn(t){return typeof t=="object"&&t!==null&&t.type==="cubic-bezier"}function Ls(t){return typeof t=="object"&&t!==null&&t.type!=="cubic-bezier"}const qr=2;function jr(t){return t.some(e=>e.interpolation!==void 0)?2:1}function Yi(t){return t.property==="text"&&"textConfig"in t}function We(t){return t.kind==="inertia"&&"inertia"in t}function De(t){return t.kind==="spring"&&"spring"in t}function Yr(t){return t.property==="motionPath"&&"motionPathConfig"in t}function Dy(t){return typeof t=="object"&&t!==null&&"x"in t&&"y"in t&&"angle"in t}function vh(t){return"keyframes"in t}class By{_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 zy{_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 Mh(t,e){if(!(e>0))return t;const n=1e3/e;return Math.floor(t/n+1e-9)*n}function Kr(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 Xr(t,e="start"){if(t<=1)return 0;let n=0;for(let s=0;s<t;s++)n=Math.max(n,Kr(s,t,e));return n}function Ki(t,e,n){if(n.offsets)return n.offsets[t]??0;const s=n.from??"start",i=Kr(t,e,s);if(n.amount!==void 0){const o=Xr(e,s);return o===0?0:n.amount*i/o}return n.each!==void 0?n.each*i:0}function Xi(t,e){return Array.from({length:t},(n,s)=>Ki(s,t,e))}function Fs(t,e){return t<=1?0:Math.max(...Xi(t,e))}const Dn=1,Gr=6e4,Gi=Gr/Dn,ce={stiffness:180,damping:12,mass:1,velocity:0,restDelta:.01,restSpeed:.1},Ui={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 Ns{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??ce.stiffness,this.damping=e.damping??ce.damping,this.mass=e.mass??ce.mass,this.restDelta=e.restDelta??ce.restDelta,this.restSpeed=e.restSpeed??ce.restSpeed,this.distance=Math.abs(this.to-this.from)||1,this.samples=[this.from],this.velocity=e.velocity??ce.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/Dn);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/Dn-n;return s+(i-s)*o}settleTime(){return this.simulateTo(Gi+1),this.settledStep!==null?this.settledStep*Dn:Gr}simulateTo(e){if(this.settledStep!==null)return;const n=Math.min(e,Gi+1),s=Dn/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>Gi&&(this.settledStep=Gi)}}function qy(t,e){return new Ns(t).valueAt(e)}function Sh(t){return new Ns(t).settleTime()}function jy(t){const e=t.stiffness??ce.stiffness,n=t.damping??ce.damping,s=t.mass??ce.mass;return n<2*Math.sqrt(e*s)}function Yy(t){const e=t.stiffness??ce.stiffness,n=t.mass??ce.mass;return 2*Math.sqrt(e*n)}const Ur=4,Ky=.002,Xy=1e-4,xh=6e4;function Vi(t){const e=t.friction??Ur;return e>0?e:Ur}function Ws(t){return t.from+t.velocity/Vi(t)}function Gy(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 Bn(t){let e=Gy(Ws(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 zn(t){const e=Math.abs(Bn(t)-t.from);if(e===0)return 0;const n=t.restDelta??Math.max(Xy,e*Ky);if(n>=e)return 0;const s=Math.log(e/n)/Vi(t);return Math.min(xh,s*1e3)}function Ji(t,e){if(e<=0)return t.from;const n=Bn(t);if(e>=zn(t))return n;const s=Vi(t);return t.from+(n-t.from)*(1-Math.exp(-s*e/1e3))}function Uy(t,e){const n=Vi(t),s=Bn(t);return e>=zn(t)?0:(s-t.from)*n*Math.exp(-n*Math.max(0,e)/1e3)}const Zi=t=>t,Th=t=>t*t,Eh=t=>1-(1-t)*(1-t),Ah=t=>t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2,Vr=t=>t*t*t,Jr=t=>1-Math.pow(1-t,3),Ds=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,$h=Vr,Ph=Jr,Ih=Ds,Vy={linear:Zi,"ease-in":$h,"ease-out":Ph,"ease-in-out":Ih,"ease-in-quad":Th,"ease-out-quad":Eh,"ease-in-out-quad":Ah,"ease-in-cubic":Vr,"ease-out-cubic":Jr,"ease-in-out-cubic":Ds};function Oh(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 w=u(m)-g;if(Math.abs(w)<1e-7)return m;const T=f(m);if(Math.abs(T)<1e-7)break;m-=w/T}let b=0,v=1;for(m=g;b<v;){const k=u(m);if(Math.abs(k-g)<1e-7)return m;g>k?b=m:v=m,m=(b+v)/2}return m};return g=>{if(g<=0)return 0;if(g>=1)return 1;const m=p(g);return d(m)}}function Zr(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 _h(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 Ch=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 Hh(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 Rh(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 Lh(t){switch(t.type){case"steps":return Rh(t.count,t.position);case"elastic":return Zr(_h(t.amplitude,t.period),t.mode);case"bounce":return Zr(Ch,t.mode);case"back":return Zr(Hh(t.overshoot),t.mode)}}function Wt(t){return t===void 0?Zi:Wn(t)?Oh(t.points):Ls(t)?Lh(t):Vy[t]??Zi}const Fh=32,Jy=256,qn=new Map,Zy=/[MmLlHhVvCcSsQqTtAaZz]/,Qy=/^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/,t1={M:2,L:2,H:1,V:1,C:6,S:4,Q:4,T:2,A:7,Z:0};function e1(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(Zy.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=Qy.exec(t.slice(n));if(!l)break;s.args.push(parseFloat(l[0])),n+=l[0].length}return e}function n1(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,b=-f*p+d*g,v=m*m/(c*c)+b*b/(h*h);if(v>1){const L=Math.sqrt(v);c*=L,h*=L}const k=o===r?-1:1,w=c*c*h*h-c*c*b*b-h*h*m*m,T=c*c*b*b+h*h*m*m,P=k*Math.sqrt(Math.max(0,w/T)),S=P*c*b/h,x=-P*h*m/c,M=d*S-f*x+(t+a)/2,E=f*S+d*x+(e+l)/2,I=(L,q,G,C)=>{const Y=L*G+q*C,st=Math.sqrt((L*L+q*q)*(G*G+C*C)),$=Math.acos(Math.max(-1,Math.min(1,Y/st)));return L*C-q*G<0?-$:$},A=I(1,0,(m-S)/c,(b-x)/h);let O=I((m-S)/c,(b-x)/h,(-m-S)/c,(-b-x)/h);!r&&O>0&&(O-=2*Math.PI),r&&O<0&&(O+=2*Math.PI);const H=Math.max(1,Math.ceil(Math.abs(O)/(Math.PI/2))),W=O/H,j=4/3*Math.tan(W/4),J=L=>{const q=c*Math.cos(L),G=h*Math.sin(L);return[d*q-f*G+M,f*q+d*G+E]},tt=L=>{const q=-c*Math.sin(L),G=h*Math.cos(L);return[d*q-f*G,f*q+d*G]},V=[];for(let L=0;L<H;L++){const q=A+L*W,G=q+W,[C,Y]=J(q),[st,$]=L===H-1?[a,l]:J(G),[_,z]=tt(q),[K,N]=tt(G);V.push([C+j*_,Y+j*z,st-j*K,$-j*N,st,$])}return V}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 Nh(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 Bs(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 Qi(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<=Fh;f++){const p=f/Fh,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 dn(t){const e=qn.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 e1(t)){const b=g.toUpperCase(),v=g!==b,k=t1[b];if(b==="Z"){(s!==o||i!==r)&&u(Bs(s,i,o,r)),c>=0&&h.add(c),s=o,i=r,a=l=null;continue}for(let w=0;w+k<=m.length;w+=k){const T=m.slice(w,w+k),P=v?s:0,S=v?i:0;let x=null,M=null;switch(b){case"M":w===0?(s=T[0]+P,i=T[1]+S,o=s,r=i,(c<0||n[n.length-1]?.subpath===c)&&c++):(u(Bs(s,i,T[0]+P,T[1]+S)),s=T[0]+P,i=T[1]+S);break;case"L":u(Bs(s,i,T[0]+P,T[1]+S)),s=T[0]+P,i=T[1]+S;break;case"H":u(Bs(s,i,T[0]+P,i)),s=T[0]+P;break;case"V":u(Bs(s,i,s,T[0]+S)),i=T[0]+S;break;case"C":{const E=[T[0]+P,T[1]+S,T[2]+P,T[3]+S,T[4]+P,T[5]+S];u(Qi(s,i,E)),x=[E[2],E[3]],s=E[4],i=E[5];break}case"S":{const[E,I]=a?[2*s-a[0],2*i-a[1]]:[s,i],A=[E,I,T[0]+P,T[1]+S,T[2]+P,T[3]+S];u(Qi(s,i,A)),x=[A[2],A[3]],s=A[4],i=A[5];break}case"Q":case"T":{let E=s,I=i;b==="Q"?(E=T[0]+P,I=T[1]+S):l&&(E=2*s-l[0],I=2*i-l[1]);const A=b==="Q"?T[2]+P:T[0]+P,O=b==="Q"?T[3]+S:T[1]+S;u(Qi(s,i,[s+2/3*(E-s),i+2/3*(I-i),A+2/3*(E-A),O+2/3*(I-O),A,O])),M=[E,I],s=A,i=O;break}case"A":{const E=T[5]+P,I=T[6]+S;let A=s,O=i;for(const H of n1(s,i,T[0],T[1],T[2],T[3],T[4],E,I))u(Qi(A,O,H)),A=H[4],O=H[5];s=E,i=I;break}}a=x,l=M}}const d=n.reduce((g,m)=>g+m.length,0),f=[];for(let g=0;g<n.length;){const m=n[g].subpath;let b=g,v=0;for(;b<n.length&&n[b].subpath===m;)v+=n[b++].length;const k=n[g],w=n[b-1],T=h.has(m)||Math.abs(w.endX-k.startX)<1e-9&&Math.abs(w.endY-k.startY)<1e-9;f.push({start:g,end:b,length:v,closed:T}),g=b}const p={segments:n,totalLength:d,subpaths:f};return qn.size>=Jy&&qn.delete(qn.keys().next().value),qn.set(t,p),p}function s1(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 i1(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=s1(t,e);let c=Nh(t.startX,n,i,r,l),h=Nh(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 Qr(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 i1(r,e-i);i+=r.length}return{x:0,y:0,angle:0}}function Wh(t,e){const{segments:n,totalLength:s}=dn(t);return Qr(n,Math.max(0,Math.min(1,e))*s)}function o1(){qn.clear()}function r1(t){return dn(t).totalLength}const a1=24,l1=320,c1=2.5,zs=72,h1=64,u1=.2,d1=128,qs=new Map;let to=0,ze;const Dh=t=>Math.round(t*100)/100;function Bh(t,e){const{segments:n,subpaths:s,totalLength:i}=dn(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 ta(t,e){const n=t.closed?(e%1+1)%1:Math.max(0,Math.min(1,e)),s=Qr(t.segments,n*t.length,t.start,t.end);return[s.x,s.y]}function zh(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 qh(t,e){const n=[];for(let s=0;s<e;s++)n.push(ta(t,t.closed?s/e:s/(e-1)));return n}function jh(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 f1(t,e,n){const s=t.closed&&e.closed;if(n!==void 0)return{offset:s?Math.abs(n)%zs/zs:0,reversed:n<0};const i=jh(qh(t,zs)),o=jh(qh(e,zs)),r=zs;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 g1(t,e,n){return n?((e.reversed?e.offset-t:t+e.offset)%1+1)%1:e.reversed?1-t:t}function p1(t,e,n){return n?((e.reversed?e.offset-t:t-e.offset)%1+1)%1:e.reversed?1-t:t}function m1(t,e,n){const s=t.closed&&e.closed,i=f1(t,e,n.shapeIndex),o=Math.max(a1,Math.min(l1,Math.ceil(Math.max(t.length,e.length)/c1))),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 zh(t))a(u);for(const u of zh(e))a(p1(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(...ta(t,u)),h.push(...ta(e,g1(u,i,s)));return y1({from:c,to:h,closed:s})}function y1(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=u1;for(let h=r+1;h<a;h++){const u=Math.max(Yh(t.from,r,a,h),Yh(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 Yh(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 b1(t,e,n){const s=n.shapeIndex;if(ze&&ze.from===t&&ze.to===e&&ze.shapeIndex===s)return ze.plan;const o=qs.get(String(s??"auto"))?.get(t)?.get(e);if(o)return ze={from:t,to:e,shapeIndex:s,plan:o},o;const r=dn(t).subpaths.filter(f=>f.length>0).length===dn(e).subpaths.filter(f=>f.length>0).length,a=Bh(t,!r),l=Bh(e,!r),c={pairs:a.map((f,p)=>m1(f,l[p],n))};to>=d1&&(qs.clear(),to=0);const h=String(s??"auto"),u=qs.get(h)??new Map;qs.set(h,u);const d=u.get(t)??new Map;return u.set(t,d),d.set(e,c),to++,ze={from:t,to:e,shapeIndex:s,plan:c},c}function Kh(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=b1(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=Dh(a.from[l]+(a.to[l]-a.from[l])*i),h=Dh(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 w1(){qs.clear(),to=0,ze=void 0}function jn(t){return/^\s*[Mm]\s*[-+]?(?:\d|\.\d)/.test(t)}const Yn=Math.PI/180,k1=.9995;function ea(){return[0,0,0,1]}function Vt(t,e){const n=Math.hypot(t[0],t[1],t[2]);if(n===0)return ea();const s=e*Yn/2,i=Math.sin(s)/n;return[t[0]*i,t[1]*i,t[2]*i,Math.cos(s)]}function v1(t,e,n){return na(na(Vt([0,1,0],e),Vt([1,0,0],t)),Vt([0,0,1],n))}function M1(t){const[e,n,s,i]=qe(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/Yn,Math.atan2(o,u)/Yn,Math.atan2(r,a)/Yn]:[d/Yn,Math.atan2(-h,c)/Yn,0]}function na(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 Xh(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]}function Gh(t){return Math.hypot(t[0],t[1],t[2],t[3])}function qe(t){const e=Gh(t);return e===0?ea():[t[0]/e,t[1]/e,t[2]/e,t[3]/e]}function S1(t){return[-t[0],-t[1],-t[2],t[3]]}function Uh(t,e,n){const s=qe(t);let i=qe(e),o=Xh(s,i);if(o<0&&(i=[-i[0],-i[1],-i[2],-i[3]],o=-o),o>k1)return qe([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 qe([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 x1(t,e){const[n,s,i,o]=qe(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 T1=Object.freeze(Object.defineProperty({__proto__:null,conjugate:S1,dot:Xh,fromAxisAngle:Vt,fromEuler:v1,identity:ea,length:Gh,multiply:na,normalize:qe,rotateVec3:x1,slerp:Uh,toEuler:M1},Symbol.toStringTag,{value:"Module"})),ke=(t,e,n)=>t+(e-t)*n,Vh=512,sa=new Map,ia=new Map;function Jh(t){const e=sa.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 sa.size<Vh&&sa.set(t,s),s}const Zh=t=>t.charCodeAt(0)===35,Qh=t=>t.startsWith("rgb"),t0=t=>t.startsWith("rgba"),E1=/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/,oa=t=>Math.round(t).toString(16).padStart(2,"0");function A1(t,e,n){return`#${oa(t)}${oa(e)}${oa(n)}`}function e0(t){const e=ia.get(t);if(e)return e;const n=t.match(E1);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 ia.size<Vh&&ia.set(t,r),r}const n0=(t,e,n)=>{if(Zh(t)&&Zh(e)){const[s,i,o]=Jh(t),[r,a,l]=Jh(e),c=ke(s,r,n),h=ke(i,a,n),u=ke(o,l,n);return A1(c,h,u)}if((Qh(t)||t0(t))&&(Qh(e)||t0(e))){const s=e0(t),i=e0(e),o=Math.round(ke(s[0],i[0],n)),r=Math.round(ke(s[1],i[1],n)),a=Math.round(ke(s[2],i[2],n));if(s.length===4||i.length===4){const l=s[3]??1,c=i[3]??1,h=ke(l,c,n);return`rgba(${o}, ${r}, ${a}, ${h})`}return`rgb(${o}, ${r}, ${a})`}return n<1?t:e},s0=(t,e,n)=>{const s=Math.min(t.length,e.length),i=[];for(let o=0;o<s;o++)i.push(ke(t[o],e[o],n));return i},i0=(t,e,n)=>Uh(t,e,n),ra=(t,e,n)=>n<1?t:e,o0=(t,e,n)=>Kh(t,e,n);function js(t,e){return e==="slerp"?i0:typeof t=="number"?ke:Array.isArray(t)?s0:typeof t=="string"?t.startsWith("#")||t.startsWith("rgb")?n0:jn(t)?o0:ra:ra}const aa=1e3/60;function la(t,e={}){if(!De(t))throw new Error(`bakeSpringTrack: track "${t.id}" is not a spring track`);const n=new Ns(t.spring);return r0(t,s=>n.valueAt(s),n.settleTime(),t.spring.from,t.spring.to,e)}function ca(t,e={}){if(!We(t))throw new Error(`bakeInertiaTrack: track "${t.id}" is not an inertia track`);const n=t.inertia;return r0(t,s=>Ji(n,s),zn(n),n.from,Bn(n),e)}function r0(t,e,n,s,i,o){const r=o.intervalMs??aa,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?l0(c,a):c,...t.targets&&{targets:[...t.targets]},...t.stagger&&{stagger:{...t.stagger}}}}function ha(t,e,n,s={}){const i=s.intervalMs??aa,o=typeof n=="function"?n:Wt(n),r=js(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 $1(t,e){return De(t)?la(t,e):We(t)?ca(t,e):t}function a0(t,e={}){const n=t.keyframes;if(!n.some(o=>Ls(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];Ls(r.easing)?s.push(...ha(n[o-1],r,r.easing,i)):s.push(r)}return{...t,keyframes:s}}function P1(t,e){return t.filter(vh).map(n=>a0(n,e)).concat(t.filter(De).map(n=>la(n,e)),t.filter(We).map(n=>ca(n,e)))}function l0(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 eo(t){const e=[...t.keyframes].sort((n,s)=>n.time-s.time);return{...t,keyframes:e}}function je(t){return t.targets&&t.targets.length>0?t.targets:[t.target]}function Kn(t,e,n,s){const i=n??0;return!s||e<=1?i:i+Ki(t,e,s)}class fn{track;targets;constructor(e){this.track=e,this.targets=je(e)}getValueAtTime(e){return this.valueForOffset(e-Kn(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=Kn(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?Fs(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=Wt(i.easing)(r);return js(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 c0{track;targets;sampler;constructor(e){this.track=e,this.targets=je(e),this.sampler=new Ns(e.spring)}getValueAtTime(e){return this.sampler.valueAt(e-Kn(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=Kn(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?Fs(this.targets.length,this.track.stagger):0;return this.sampler.settleTime()+(this.track.delay??0)+e}getTrack(){return this.track}}class h0{track;targets;duration;constructor(e){this.track=e,this.targets=je(e),this.duration=zn(e.inertia)}getValueAtTime(e){return Ji(this.track.inertia,e-Kn(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=Kn(i,n,this.track.delay,this.track.stagger);s.push({target:this.targets[i],value:Ji(this.track.inertia,e-o),start:o})}return s}getDuration(){const e=this.track.stagger?Fs(this.targets.length,this.track.stagger):0;return this.duration+(this.track.delay??0)+e}getTrack(){return this.track}}function ua(t,e){const n={...Wh(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 I1(t,e,n,s){const i=e+(n-e)*s;return ua(t,i)}const da={upperCase:"ABCDEFGHIJKLMNOPQRSTUVWXYZ",lowerCase:"abcdefghijklmnopqrstuvwxyz",upperAndLowerCase:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",numbers:"0123456789"},O1=20;function u0(t){const e=da[t??"upperCase"]??t??da.upperCase,n=Array.from(e);return n.length>0?n:Array.from(da.upperCase)}function _1(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 d0(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 v=Math.round(o*Math.max(r.length,a.length));return l?r.slice(0,Math.max(0,r.length-v)).join("")+a.slice(Math.max(0,a.length-v)).join(""):a.slice(0,v).join("")+r.slice(v).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=u0(t.chars),p=t.refreshRate??O1,g=p>0?Math.floor(n*p/1e3):0,m=t.seed??1;let b="";for(let v=0;v<d;v++){const k=l?v>=d-u:v<u,w=l?a[a.length-(d-v)]:a[v];k&&w!==void 0||w===" "||w===`
|
|
2
|
-
`?b+=w:b+=f[_1(m,v,g)%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=Mh(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",d0(l.textConfig,o,Math.max(0,r)));return}const c=this._motionPathTracks.get(n);if(c&&typeof o=="number"){const h=ua(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 je(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,We(e)){this._trackPlayers.set(e.id,new h0(e));return}if(De(e)){this._trackPlayers.set(e.id,new c0(e)),this._springTracks.set(e.id,e);return}if(Yi(e))this._trackPlayers.set(e.id,new fn(e)),this._textTracks.set(e.id,e);else if(Yr(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 fn(n)),this._motionPathTracks.set(e.id,e)}else this._trackPlayers.set(e.id,new fn(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(De(s)||We(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=je(r).filter(u=>je(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&&!je(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:jr(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 C1=100;function fa(t,e,n,s){const i=[],o=[],{duration:r,alternate:a}=s,l=(f,p,g,m)=>{o.push([f,p]);const b=[];t.forEach((v,k)=>{(g==="forward"?(m?v>=f:v>f)&&v<=p:(m?v<=f:v<f)&&v>=p)&&b.push(k)}),b.sort((v,k)=>(g==="forward"?t[v]-t[k]:t[k]-t[v])||v-k);for(const v of b)i.push({kind:"event",index:v,direction:g})};let c=e.time,h=e.direction,u=e.fresh===!0;const d=Math.min(C1,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 f0(t){return We(t)?{id:t.id,target:t.target,property:t.property,kind:"inertia",inertia:g0(t.inertia),...ve(t)}:De(t)?{id:t.id,target:t.target,property:t.property,kind:"spring",spring:{...t.spring},...ve(t)}:Yi(t)?{id:t.id,target:t.target,property:"text",textConfig:{...t.textConfig},keyframes:t.keyframes.map(ga),...ve(t)}:Yr(t)?{id:t.id,target:t.target,property:"motionPath",motionPathConfig:{...t.motionPathConfig},keyframes:t.keyframes.map(ga),...ve(t)}:{id:t.id,target:t.target,property:t.property,keyframes:t.keyframes.map(ga),...t.interpolation!==void 0&&{interpolation:t.interpolation},...ve(t)}}function g0(t){return{...t,...Array.isArray(t.end)&&{end:[...t.end]}}}function ga(t){return{time:t.time,value:t.value,...t.easing&&{easing:t.easing}}}function ve(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 p0(t){if(We(t)){const e=t;return{id:e.id,target:e.target,property:e.property,kind:"inertia",inertia:g0(e.inertia),...ve(e)}}if(De(t)){const e=t;return{id:e.id,target:e.target,property:e.property,kind:"spring",spring:{...e.spring},...ve(e)}}if(Yi(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),...ve(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,...ve(e)}}return eo({id:t.id,target:t.target,property:t.property,keyframes:t.keyframes,...t.interpolation!==void 0&&{interpolation:t.interpolation},...ve(t)})}function m0(t){const e=t._config.markers;return{formatVersion:jr(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(f0),...t.captions&&{captions:JSON.parse(JSON.stringify(t.captions))}}}function Xn(t){const e=t.formatVersion??1;if(e>qr)throw new Error(`tinyfly: this animation uses format version ${e}, but this tinyfly reads up to version ${qr}. Update tinyfly to play it.`);return new Ht({id:t.id,name:t.name,config:t.config,tracks:t.tracks.map(p0),captions:t.captions})}function H1(t){return JSON.stringify(m0(t))}function R1(t){const e=JSON.parse(t);return Xn(e)}function ne(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 Ye(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 pa(t,e,n){return e+t.next()*(n-e)}function y0(t,e,n,s){if(s<=0)return pa(t,e,n);const i=Math.floor((n-e)/s),o=Math.round(t.next()*i);return e+o*s}function L1(t,e){if(e.length!==0)return e[Math.floor(t.next()*e.length)]}const b0=/^([+\-*/])=\s*(-?[\d.]+)$/,w0=/^random\(\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*(?:,\s*(-?[\d.]+)\s*)?\)$/i;function F1(t){return typeof t!="string"?!1:b0.test(t.trim())||w0.test(t.trim())}function ma(t,e={}){if(typeof t!="string")return t;const n=t.trim(),s=b0.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=w0.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?y0(e.random,o,r,a):pa(e.random,o,r)}return t}function k0(t,e=0,n){const s=[];let i=e;for(const o of t){const r=ma(o,{base:i,random:n});s.push(r),typeof r=="number"&&(i=r)}return s}class N1{random;constructor(e){this.random=Ye(e)}get seed(){return this.random.seed}resolve(e,n=0){return ma(e,{base:n,random:this.random})}resolveSequence(e,n=0){return k0(e,n,this.random)}}const W1=600;function v0(t){if(Array.isArray(t)){const[d,f,p,g]=t;return{fn:x0(d,f,p,g),bezier:[d,f,p,g]}}const{segments:e}=dn(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:x0(...m),bezier:m}}const c=[],h=[],u=Math.max(8,Math.ceil(W1/e.length));for(const d of e)for(let f=c.length===0?0:1;f<=u;f++){const[p,g]=D1(d,f/u);c.push(a(p)),h.push(l(g))}return{fn:B1(c,h)}}function M0(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 S0(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 D1(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 B1(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 x0(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 z1=350,q1=300,j1=550;function Y1(t,e={}){const n=e.lead??z1,s=e.gap??q1,i=e.tail??j1,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 K1(t){return t.cues.map(e=>({id:e.id,time:e.start,label:e.text}))}function X1(t,e){let n=t.scenes[0];for(const s of t.scenes)if(e>=s.start)n=s;else break;return n}const Ys=t=>6e4/t.bpm;function no(t,e){return t.offset+e*Ys(t)}function Ks(t,e){return(e-t.offset)/Ys(t)}function G1(t,e){return no(t,Math.round(Ks(t,e)))}function U1(t,e){return no(t,Math.ceil(Ks(t,e)-1e-9))}function V1(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(Ks(t,e)-1e-9);;o++){const r=no(t,o);if(r>n+1e-9)break;i.push({time:r,bar:(o%s+s)%s===0,n:o})}return i}const Gn=100;function J1(t,e,n={}){const s=n.minBpm??70,i=n.maxBpm??180,o=Math.max(1,Math.round(e/Gn)),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 M=0;M<a;M++){let E=0;for(let I=M*o;I<(M+1)*o;I++)E+=t[I]*t[I];l[M]=Math.log(1e-6+E/o)}const c=new Float64Array(a);for(let M=1;M<a;M++)c[M]=Math.max(0,l[M]-l[M-1]);const h=c.reduce((M,E)=>M+E,0)/a;for(let M=0;M<a;M++)c[M]=Math.max(0,c[M]-h);const u=Math.max(1,Math.floor(60*Gn/i)),d=Math.min(a-1,Math.ceil(60*Gn/s)),f=M=>{let E=0;for(let I=M;I<a;I++)E+=c[I]*c[I-M];return E/(a-M)};let p=0;for(let M=0;M<a;M++)p+=c[M]*c[M];p/=a;let g=u,m=-1/0;for(let M=u;M<=d;M++){const E=60*Gn/M,I=Math.exp(-.5*(Math.log2(E/120)/.9)**2),A=f(M)*I;A>m&&(m=A,g=M)}const b=M=>{const E=Math.floor(M);return E<0||E+1>=a?0:c[E]+(c[E+1]-c[E])*(M-E)},v=(M,E)=>{let I=0;for(let A=E;A<a;A+=M)I+=b(A);return I};let k=g,w=0,T=-1/0;for(let M=g-.6;M<=g+.6+1e-9;M+=.02){if(M<1)continue;const E=Math.max(1,Math.round(M*4));for(let I=0;I<E;I++){const A=I/E*M,O=v(M,A);O>T&&(T=O,w=A,k=M)}}const P=60*Gn/k,S=p>0?Math.max(0,Math.min(1,f(g)/p)):0,x=(w+.5)*1e3/Gn;return{bpm:Math.round(P*100)/100,offset:Math.round(x%(6e4/P)),confidence:S}}const Z1=600,Q1=250,T0=1;function tb(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(T0,u.duration??Z1);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>T0?"ease-in-out":void 0))}else{const{follow:d}=u,f=d.lag??Q1,p=new Ht({id:"follow",tracks:[{id:"x",target:"s",property:"x",keyframes:d.x}]}),g=v=>p.getStateAtTime(v).values.get("s")?.get("x")??l.focusX,m=[u.at,...d.x.map(v=>v.time).filter(v=>v>u.at&&v<u.until),u.until];a(u.at,l);const b=v=>({focusX:g(v)+(d.lead??0),focusY:d.y??l.focusY,scale:d.scale??l.scale,rotate:l.rotate});for(const v of m){const k=d.x.find(w=>w.time===v)?.easing;a(v+f,b(v),v===u.at?"ease-in-out":k)}l=b(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=Ye(u.shake.seed??Math.round(u.at)+1),m=()=>g.next()*2-1;for(const b of["shakeX","shakeY","shakeRotate"])o(b,u.at,0);for(let b=u.at+p;b<u.at+u.duration;b+=p){const v=1-(b-u.at)/u.duration;o("shakeX",b,m()*d*v),o("shakeY",b,m()*d*v),o("shakeRotate",b,m()*f*v)}for(const b of["shakeX","shakeY","shakeRotate"])o(b,u.at+u.duration,0,"ease-out")}return Object.entries(i).map(([u,d])=>({id:`${n}-${u}`,target:n,property:u,keyframes:d}))}function E0(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 Xs(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=E0(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 ft(t,e,n,s){const i=typeof e=="string"?s??Xs(e,n):void 0;return`Unknown ${t} ${JSON.stringify(e)}${i?`: did you mean "${i}"?`:"."} Known: ${n.join(", ")}`}function Gs(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}function gn(t,e,n=1){if(!(e>0))return 0;const s=t*n/e;return s-Math.floor(s)}function ya(t){const e=t-Math.floor(t);return 1-Math.abs(e*2-1)}function eb(t,e){const n=Math.max(1,Math.round(e.cycles??1)),s=e.amplitude??1,i=gn(t,e.period,n)+(e.phase??0),o=i-Math.floor(i);switch(e.shape??"sine"){case"triangle":return s*(ya(o+.25)*2-1);case"square":return o<.5?s:-s;default:return s*Math.sin(o*Math.PI*2)}}function nb(t,e){const n=Math.max(1,Math.round(e.cycles??1)),s=typeof e.easing=="function"?e.easing:Wt(e.easing??"ease-in-out"),i=gn(t,e.period,n)+(e.phase??0);return s(ya(i))}function sb(t,e){const n=A0(e.seed),s=Math.max(1,Math.round(e.cycles??1)),i=(gn(t,e.period,1)+(e.phase??0))*Math.PI*2,o=s/Math.PI;return $0([Math.cos(i)*o+7.31,Math.sin(i)*o+3.17],n,e.octaves??1)}function ib(t,e,n){const s=A0(n.seed),i=Math.max(1,Math.round(n.cycles??1)),o=Math.max(1,Math.round(n.cyclesAlong??1)),r=gn(t,n.period,1)*Math.PI*2,a=gn(e,n.periodAlong,1)*Math.PI*2,l=i/Math.PI,c=o/Math.PI;return $0([Math.cos(r)*l+5.13,Math.sin(r)*l+9.47,Math.cos(a)*c+2.71,Math.sin(a)*c+6.29],s,n.octaves??1)}const A0=t=>typeof t=="string"?ne(t):(t??0)>>>0;function $0(t,e,n){const s=Math.max(1,Math.min(6,Math.round(n)));let i=0,o=1,r=0;for(let a=0;a<s;a++){const l=2**a;i+=o*ob(t.map(c=>c*l),e+a*1013),r+=o,o*=.5}return i/r}function ob(t,e){const n=t.length,s=t.map(Math.floor),o=t.map((a,l)=>a-s[l]).map(a=>a*a*(3-2*a));let r=0;for(let a=0;a<1<<n;a++){let l=1;const c=[];for(let h=0;h<n;h++){const u=a>>h&1;l*=u?o[h]:1-o[h],c.push(s[h]+u)}l!==0&&(r+=l*rb(c,e))}return r}function rb(t,e){let n=(e^2654435769)>>>0;for(const s of t)n=Math.imul(n^(s|0),2246822507)>>>0,n=(n^n>>>13)>>>0,n=Math.imul(n,3266489909)>>>0,n=(n^n>>>16)>>>0;return n/4294967296*2-1}function ab(t,e={}){if(t.length===0)throw new Error("curve: needs at least one key");const s={id:"curve",target:"curve",property:"value",keyframes:t.map(o=>({time:o.at,value:o.value,easing:o.easing})).sort((o,r)=>o.time-r.time),interpolation:e.interpolation},i=new fn(s);return o=>i.getValueAtTime(o)}function lb(t,e){return e*Ys({bpm:t.bpm})}function cb(t,e){const n=Math.max(1,Math.round(t/Ys(e)));return{beats:n,grid:{...e,bpm:n*6e4/t}}}function hb(t,e,n={}){const s=Math.max(1e-6,n.attack??.05),i=Math.max(1e-6,n.decay??.4),o=Ks(e,t),r=o-Math.floor(o),a=r<s?r/s:Math.max(0,1-(r-s)/i),l=n.barAccent??0;if(l<=0)return a;const c=Math.max(1,Math.round(e.beatsPerBar??4)),u=(Math.floor(o)%c+c)%c===0;return a*(u?1+l:1)/(1+l)}function ub(t,e,n={}){const s=n.fps??30,i=Math.max(1,Math.round(e/s)),o=Math.max(1,Math.ceil(t.length/i)),r=new Float32Array(o),a=Math.min(.99,Math.max(0,n.smoothing??.5));let l=0,c=0;for(let h=0;h<o;h++){let u=0;const d=h*i,f=Math.min(t.length,d+i);for(let g=d;g<f;g++)u+=t[g]*t[g];const p=f>d?Math.sqrt(u/(f-d)):0;l=p>l?p:l*a+p*(1-a),r[h]=l,c=Math.max(c,l)}if(n.normalize!==!1&&c>0)for(let h=0;h<o;h++)r[h]/=c;return r}function db(t,e,n=30,s){if(t.length===0)return 0;const o=(s?gn(e,s)*s:e)*n/1e3,r=Math.floor(o),a=t[Math.min(t.length-1,Math.max(0,r))],l=t[Math.min(t.length-1,Math.max(0,r+1))];return a+(l-a)*(o-r)}const P0={"16:9":16/9,"2.39:1":2.39,"4:3":4/3,"1:1":1,"9:16":9/16,"4:5":4/5},ba=t=>typeof t=="number"?t:P0[t];function fb(t,e){const n=ba(e),s=t.width/t.height;if(n>=s){const o=t.width/n;return{x:0,y:(t.height-o)/2,width:t.width,height:o}}const i=t.height*n;return{x:(t.width-i)/2,y:0,width:i,height:t.height}}function gb(t,e){const n=ba(t),s=i=>Math.max(2,Math.round(i/2)*2);return"width"in e?{width:s(e.width),height:s(e.width/n)}:{width:s(e.height*n),height:s(e.height)}}function pb(t,e={}){const n=s=>({x:t.x+t.width*(1-s)/2,y:t.y+t.height*(1-s)/2,width:t.width*s,height:t.height*s});return{action:n(e.action??.9),title:n(e.title??.8)}}const Me=t=>Math.round(t*1e3)/1e3;function I0(t,e={}){if(t.length===0)return"";const n=e.curviness??1,s=e.closed??!1,i=t.length;let o=`M${Me(t[0].x)} ${Me(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${Me(u.x)} ${Me(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,b=u.y-(d.y-h.y)*f;o+=` C${Me(p)} ${Me(g)} ${Me(m)} ${Me(b)} ${Me(u.x)} ${Me(u.y)}`}return s?`${o} Z`:o}const Bt=(t,e=0)=>{const n=parseFloat(t??"");return Number.isFinite(n)?n:e};function mb(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 so(t){const e=t.attributes;switch(t.tag.toLowerCase()){case"path":return e.d??null;case"circle":case"ellipse":{const n=Bt(e.cx),s=Bt(e.cy),i=t.tag.toLowerCase()==="circle"?Bt(e.r):Bt(e.rx),o=t.tag.toLowerCase()==="circle"?Bt(e.r):Bt(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=Bt(e.x),s=Bt(e.y),i=Bt(e.width),o=Bt(e.height);let r=e.rx!=null?Bt(e.rx):e.ry!=null?Bt(e.ry):0,a=e.ry!=null?Bt(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${Bt(e.x1)} ${Bt(e.y1)} L${Bt(e.x2)} ${Bt(e.y2)}`;case"polyline":case"polygon":{const n=mb(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 yb(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 bb=2.5;function O0(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(bb,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 _0(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}const wb={scale:1,turn:0,x:0,y:0};function kb(t={}){return{scale:t.scale??1,turn:t.turn??0,x:t.x??0,y:t.y??0}}function C0(t,e,n){const{ax:s,ay:i}=io(t,e);return{scale:t,turn:e,x:n.x-(s*n.x-i*n.y),y:n.y-(i*n.x+s*n.y)}}function wa(t,e){const{ax:n,ay:s}=io(t.scale,t.turn);return{x:n*e.x-s*e.y+t.x,y:s*e.x+n*e.y+t.y}}function vb(t,e){const n=wa(e,{x:t.x,y:t.y});return{scale:t.scale*e.scale,turn:t.turn+e.turn,x:n.x,y:n.y}}function Mb(t){if(t.scale===0)throw new Error("invertSimilarity: a scale of 0 cannot be undone");const e={scale:1/t.scale,turn:-t.turn,x:0,y:0},n=wa(e,{x:t.x,y:t.y});return{...e,x:-n.x,y:-n.y}}function H0(t){const{ax:e,ay:n}=io(t.scale,t.turn),s=1-e,i=-n,o=s*s+i*i;return o<1e-18?null:{x:(t.x*s+t.y*i)/o,y:(t.y*s-t.x*i)/o}}function Sb(t,e){if(t.scale<=0)throw new Error("powSimilarity: the scale must be positive");const n=Math.pow(t.scale,e),s=t.turn*e,i=H0(t);return i?C0(n,s,i):{scale:n,turn:s,x:t.x*e,y:t.y*e}}function xb(t){const{ax:e,ay:n}=io(t.scale,t.turn);return[e,n,-n,e,t.x,t.y]}const io=(t,e)=>{const n=e*Math.PI/180;return{ax:t*Math.cos(n),ay:t*Math.sin(n)}};function oo([t,e,n],s={}){const i=s.scale??1,o=s.centre??{x:0,y:0},r=Math.sqrt(3)/2;return{x:o.x+(t-e)*r*i,y:o.y+((t+e)*.5-n)*i}}const ka=([t,e,n])=>t+e+n;function va(t,e={}){const[n,s,i]=t.min,[o,r,a]=t.max,l=d=>oo(d,e),c=[(n+o)/2,(s+r)/2,(i+a)/2],h=ka(c),u=[{side:"top",depth:h,tag:t.tag,points:[l([n,s,a]),l([o,s,a]),l([o,r,a]),l([n,r,a])]},{side:"left",depth:h,tag:t.tag,points:[l([n,r,i]),l([o,r,i]),l([o,r,a]),l([n,r,a])]},{side:"right",depth:h,tag:t.tag,points:[l([o,s,i]),l([o,r,i]),l([o,r,a]),l([o,s,a])]}];return t.hide?u.filter(d=>!t.hide.includes(d.side)):u}function Ma(t,e={}){return t.map(n=>({box:n,depth:ka([(n.min[0]+n.max[0])/2,(n.min[1]+n.max[1])/2,(n.min[2]+n.max[2])/2])})).sort((n,s)=>n.depth-s.depth).flatMap(({box:n})=>va(n,e))}function Tb(t={}){const e=t.size??10,s=(t.thickness??2)/2,i=[{tag:0,min:[-s,-s,-s],max:[e-s,s,s]},{tag:1,min:[e-s,-s,-s],max:[e+s,e-s,s]},{tag:2,min:[e-s,e-s,-s],max:[e+s,e+s,e]}],o=t.centre??{x:0,y:0},r=oo([2*e/3,e/3,e/3],{scale:t.scale}),a={centre:{x:o.x-r.x,y:o.y-r.y},scale:t.scale};return{boxes:i,faces:[...Ma(i,a),...va({...i[0],hide:["right"]},a)]}}function Eb(t={}){const e=Math.max(2,Math.round(t.steps??8)),n=t.tread??1.5,s=t.rise??.25,i=t.width??3,o=t.base??1.5,r=Math.max(1,Math.round(e*(n-2*s)/(n+2*s))),a=2*(e+r),l=n*(e-r)/a,c=[{dir:[1,0,0],across:[0,1,0],count:e},{dir:[0,1,0],across:[-1,0,0],count:e},{dir:[-1,0,0],across:[0,-1,0],count:r},{dir:[0,-1,0],across:[1,0,0],count:r}],h=[];let u=[0,0,0],d=0;for(const b of c){for(let v=0;v<b.count;v++){const k=d*l,w=[u[0]+b.dir[0]*v*n,u[1]+b.dir[1]*v*n,0],T=[w[0]+b.dir[0]*n+b.across[0]*i,w[1]+b.dir[1]*n+b.across[1]*i,0];h.push({tag:d,min:[Math.min(w[0],T[0]),Math.min(w[1],T[1]),0],max:[Math.max(w[0],T[0]),Math.max(w[1],T[1]),k+o]}),d++}u=[u[0]+b.dir[0]*b.count*n,u[1]+b.dir[1]*b.count*n,0]}const f=a*l,p=t.centre??{x:0,y:0},g=oo([e*n/2,e*n/2,f/2+o],{scale:t.scale}),m={centre:{x:p.x-g.x,y:p.y-g.y},scale:t.scale};return{boxes:h,faces:Ma(h,m),rise:l}}function R0(t,e,n){let s=0;for(const i of t){const o=(e-i.x)**2+(n-i.y)**2;s+=o>1e-9?i.r*i.r/o:1e9}return s}function Ab(t,e={}){if(t.length===0)return[];const n=e.threshold??1,s=Math.max(.5,e.cell??4),i=Math.sqrt(1/n)*1.6,o=e.bounds??{x:Math.min(...t.map(f=>f.x-f.r*i)),y:Math.min(...t.map(f=>f.y-f.r*i)),width:Math.max(...t.map(f=>f.x+f.r*i))-Math.min(...t.map(f=>f.x-f.r*i)),height:Math.max(...t.map(f=>f.y+f.r*i))-Math.min(...t.map(f=>f.y-f.r*i))},r=Math.max(2,Math.ceil(o.width/s)+1),a=Math.max(2,Math.ceil(o.height/s)+1),l=new Float64Array(r*a);for(let f=0;f<a;f++)for(let p=0;p<r;p++)l[f*r+p]=R0(t,o.x+p*s,o.y+f*s)-n;const c=(f,p)=>l[p*r+f],h=(f,p,g,m,b,v)=>{const k=g===v?.5:g/(g-v);return{x:f+(m-f)*k,y:p+(b-p)*k}},u=[];for(let f=0;f+1<a;f++)for(let p=0;p+1<r;p++){const g=o.x+p*s,m=o.y+f*s,b=g+s,v=m+s,k=[c(p,f),c(p+1,f),c(p+1,f+1),c(p,f+1)],w=(k[0]>0?1:0)|(k[1]>0?2:0)|(k[2]>0?4:0)|(k[3]>0?8:0);if(w===0||w===15)continue;const T=()=>h(g,m,k[0],b,m,k[1]),P=()=>h(b,m,k[1],b,v,k[2]),S=()=>h(g,v,k[3],b,v,k[2]),x=()=>h(g,m,k[0],g,v,k[3]),M=(k[0]+k[1]+k[2]+k[3])/4>0;switch(w){case 1:case 14:u.push([x(),T()]);break;case 2:case 13:u.push([T(),P()]);break;case 3:case 12:u.push([x(),P()]);break;case 4:case 11:u.push([P(),S()]);break;case 6:case 9:u.push([T(),S()]);break;case 7:case 8:u.push([x(),S()]);break;case 5:M?u.push([x(),S()],[T(),P()]):u.push([x(),T()],[P(),S()]);break;case 10:M?u.push([x(),T()],[P(),S()]):u.push([x(),S()],[T(),P()]);break}}const d=$b(u);return e.smooth===!1?d:d.map(f=>L0(L0(f)))}function $b(t){const e=o=>`${Math.round(o.x*1e3)},${Math.round(o.y*1e3)}`,n=new Map;t.forEach(([o,r],a)=>{for(const l of[o,r]){const c=e(l);n.has(c)||n.set(c,[]),n.get(c).push(a)}});const s=new Array(t.length).fill(!1),i=[];for(let o=0;o<t.length;o++){if(s[o])continue;s[o]=!0;const r=[t[o][0],t[o][1]];let a=t[o][1];for(;;){const l=(n.get(e(a))??[]).find(u=>!s[u]);if(l===void 0)break;s[l]=!0;const[c,h]=t[l];if(a=e(c)===e(a)?h:c,e(a)===e(r[0]))break;r.push(a)}r.length>=3&&i.push(r)}return i}function L0(t){const e=[];for(let n=0;n<t.length;n++){const s=t[n],i=t[(n+1)%t.length];e.push({x:s.x*.75+i.x*.25,y:s.y*.75+i.y*.25},{x:s.x*.25+i.x*.75,y:s.y*.25+i.y*.75})}return e}function Pb(t){const e=Math.min(1,Math.max(0,t.progress));if(e<=0)return[];const n=t.width/2,s=n*(.55+.75*e),i=Math.max(t.length*e,s*1.2),o=t.x,r=t.y+i-s,a=Math.max(.1,n*(.35-.3*e)),l=r-Math.sqrt(Math.max(0,s*s-a*a)),c=Math.max(0,l-t.y),h=8,u=[],d=[];for(let v=0;v<=h;v++){const k=v/h,w=a+(n-a)*Math.pow(1-k,1.6+1.4*e);u.push({x:o-w,y:t.y+c*k}),d.push({x:o+w,y:t.y+c*k})}const f=Math.max(8,Math.round(t.segments??12)),p=Math.acos(Math.min(1,a/s)),g=-p,m=Math.PI+p,b=[];for(let v=1;v<f;v++){const k=g+(m-g)*v/f;b.push({x:o+Math.cos(k)*s,y:r+Math.sin(k)*s})}return[...d,...b,...u.reverse()]}function Ib(t){const e=Math.min(1,Math.max(0,t.grow??1)),n=e>=1?1:1-Math.pow(1-e,3)+.08*Math.sin(e*Math.PI)*e,s=t.r*Math.max(0,n);if(s<=0)return[];const i=Math.max(12,Math.round(t.segments??48)),o=t.wobble??.05,r=t.time??0,a=t.period?r/t.period:r/2500,l=(a-Math.floor(a))*Math.PI*2,c=t.seed??0,h=[];for(let u=0;u<i;u++){const d=u/i*Math.PI*2,f=1+o*(Math.sin(2*d+l+c)*.6+Math.sin(3*d-2*l+c*1.7)*.4);h.push({x:t.x+Math.cos(d)*s*f,y:t.y+Math.sin(d)*s*f})}return h}function Ob(t){const e=t.progress;if(e<=0||e>=1)return[];const n=Math.max(3,Math.round(t.pieces??8)),s=[],i=t.r*(1+1.2*e),o=Math.PI*2/n*.6*(1-e);for(let r=0;r<n;r++){const a=r/n*Math.PI*2+.3,l=[];for(let c=0;c<=4;c++){const h=a-o/2+o*c/4;l.push({x:t.x+Math.cos(h)*i,y:t.y+Math.sin(h)*i})}s.push(l)}return s}function _b(t,e={}){const n=Math.max(.05,1+t);return{sx:e.keep==="volume"?1/Math.sqrt(n):1/n,sy:n}}function Cb(t,e,n={x:0,y:0}){return t.map(s=>({x:n.x+(s.x-n.x)*e.sx,y:n.y+(s.y-n.y)*e.sy}))}function Us(t,e){return[t[0]+e[0],t[1]+e[1],t[2]+e[2]]}function se(t,e){return[t[0]-e[0],t[1]-e[1],t[2]-e[2]]}function pn(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function $e(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function Vs(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 ro(t){return Math.hypot(t[0],t[1],t[2])}function Js(t,e){return ro(se(t,e))}function Jt(t){const e=ro(t);return e===0?[0,0,0]:pn(t,1/e)}function mn(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 Hb=Object.freeze(Object.defineProperty({__proto__:null,add:Us,cross:Vs,distance:Js,dot:$e,length:ro,lerp:mn,normalize:Jt,scale:pn,subtract:se},Symbol.toStringTag,{value:"Module"})),Rb=Math.PI/180;function ao(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function Rt(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 yn(t){return[1,0,0,0,0,1,0,0,0,0,1,0,t[0],t[1],t[2],1]}function bn(t){return[t[0],0,0,0,0,t[1],0,0,0,0,t[2],0,0,0,0,1]}function pe(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 Sa(t,e,n){const s=pe(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 Lb(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 xa(t){const[e,n,s,i,o,r,a,l,c,h,u,d,f,p,g,m]=t,b=e*r-n*o,v=e*a-s*o,k=e*l-i*o,w=n*a-s*r,T=n*l-i*r,P=s*l-i*a,S=c*p-h*f,x=c*g-u*f,M=c*m-d*f,E=h*g-u*p,I=h*m-d*p,A=u*m-d*g,O=b*A-v*I+k*E+w*M-T*x+P*S;if(Math.abs(O)<1e-12)return null;const H=1/O;return[(r*A-a*I+l*E)*H,(s*I-n*A-i*E)*H,(p*P-g*T+m*w)*H,(u*T-h*P-d*w)*H,(a*M-o*A-l*x)*H,(e*A-s*M+i*x)*H,(g*k-f*P-m*v)*H,(c*P-u*k+d*v)*H,(o*I-r*M+l*S)*H,(n*M-e*I-i*S)*H,(f*T-p*k+m*b)*H,(h*k-c*T-d*b)*H,(r*x-o*E-a*S)*H,(e*E-n*x+s*S)*H,(p*v-f*w-g*b)*H,(c*w-h*v+u*b)*H]}function Fb(t,e,n,s){const i=1/Math.tan(t*Rb/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 Nb(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 Wb(t,e,n=[0,1,0]){const s=Jt(se(t,e)),i=Jt(Vs(n,s)),o=Vs(s,i);return[i[0],o[0],s[0],0,i[1],o[1],s[1],0,i[2],o[2],s[2],0,-$e(i,t),-$e(o,t),-$e(s,t),1]}function ie(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 Db=Object.freeze(Object.defineProperty({__proto__:null,compose:Sa,fromQuat:pe,identity:ao,invert:xa,lookAt:Wb,multiply:Rt,orthographic:Nb,perspective:Fb,scaling:bn,transformPoint:ie,translation:yn,transpose:Lb},Symbol.toStringTag,{value:"Module"})),lo={"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]},F0={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 Bb(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}Wt({type:"bounce",mode:"in"}),Wt({type:"bounce",mode:"in-out"});function Zs(t){const e=N0.get(t.trim().toLowerCase());if(e)return e;const n=Bb(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:Wt(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 lo)return{easing:{type:"cubic-bezier",points:lo[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:Wt(h)}}return n in F0?{easing:F0[n]}:n in lo?{easing:{type:"cubic-bezier",points:lo[n]}}:{easing:"ease-out"}}const N0=new Map;function Ta(t,e){return N0.set(t.trim().toLowerCase(),e.bezier?{easing:{type:"cubic-bezier",points:e.bezier},fn:e.fn}:{fn:e.fn,requiresBaking:"custom"}),t}function Ea(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 W0=/^\s*random\(\s*(\[.*\]|[^)]*)\s*\)\s*$/;function D0(t){return typeof t=="string"&&W0.test(t)}function zb(t=1){let e=Ea(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 B0(l,c,1/0);if("values"in l)return B0(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]=js(l[d])(l[d],c[d],h);return u}return js(l)(l,c,h)}),wrap:((l,c,h)=>{if(Array.isArray(l)){const g=l,m=b=>g[(Math.round(b)%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,v=Ki(f,m,{...c!==void 0?{amount:c}:{each:h??1},from:u}),k=c!==void 0?c:(h??1)*Xr(m,u),w=d&&k>0?d(v/k)*k:v;return l+w},pipe:(...l)=>c=>l.reduce((h,u)=>u(h),c),splitColor:l=>qb(l),getUnit:l=>typeof l=="number"?"":/^-?[\d.]+(?:e[-+]?\d+)?([a-z%]*)$/i.exec(l.trim())?.[1]??"",seed:l=>{e=Ea(l)},resolveRandomString:l=>{const c=W0.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 B0(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 qb(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 jb=/^([+-])=\s*(-?[\d.]+)$/,Yb=/^([<>])\s*(?:([+-])?=?\s*(-?[\d.]+))?$/;function Qs(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=jb.exec(i);if(o){const c=s(o[2]);return e.cursor+(o[1]==="-"?-c:c)}const r=Yb.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 Kb(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 Xb(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),b=Math.abs(g-a.x),v=Math.abs(m-a.y);return e.axis==="x"?b:e.axis==="y"?v:Math.hypot(b,v)};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?Zs(e.ease):void 0,f=d?d.fn??Wt(d.easing):void 0;return c.map(p=>{const g=h===0?0:p/h;return(f?f(g):g)*u})}const Aa=new Set(["duration","delay","ease","repeat","repeatDelay","yoyo","stagger","onComplete","onUpdate","onStart","onRepeat","onReverseComplete","repeatRefresh","keyframes","easeEach","scrollTo","id","immediateRender","overwrite","paused","scrollTrigger","spring"]),Gb={rotation:"rotate",rotationZ:"rotate",rotationX:"rotateX",rotationY:"rotateY",transformPerspective:"perspective",perspective:"childPerspective"};function co(t){const e={},n={};for(const[s,i]of Object.entries(t))Aa.has(s)?e[s]=i:n[Gb[s]??s]=i;return{config:e,properties:n}}function ho(t,e){return t===void 0?e:t*1e3}function $a(t,e){if(t!==void 0)return typeof t=="number"?{each:t*1e3}:Kb(t)?{offsets:Xb(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 Ub={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 z0(t){return Ub[t]}function Vb(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=I0(e.path,{curviness:e.curviness});else if(jn(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 Jb(t){const e=typeof t=="string"||Array.isArray(t)?{path:t}:{...t};return{...e,start:e.end??1,end:e.start??0}}function q0(t){return typeof t=="object"&&t!==null&&"shape"in t?t.shape:t}function Zb(t){if(t.morphSVG===void 0)return t;const{morphSVG:e,...n}=t,s=q0(e);if(typeof s!="string"||!jn(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 Qb(t,e){if(t===!0)return[0,e];if(t===!1)return[0,0];if(typeof t=="number")return[0,j0(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 j0(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 tw(t,e){const[n,s]=Qb(t,e);return{strokeDasharray:[s-n,e],strokeDashoffset:-n}}function ew(t,e){if(t.drawSVG===void 0)return t;const{drawSVG:n,...s}=t;return{...s,...tw(n,e)}}function nw(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 j0(t,e){return Math.max(0,Math.min(e,t))}function sw(t){let e=2166136261;for(let n=0;n<t.length;n++)e=Math.imul(e^t.charCodeAt(n),16777619);return e>>>0}function iw(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??sw(`${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 Pa(t){return Math.max(.1,t/25)}function ow(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?Pa(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(Ws(i))]:n.end!==void 0&&(i.end=Array.isArray(n.end)?[...n.end]:n.end),i}function rw(t){const e=t===!0?{}:typeof t=="string"?{preset:t}:t;if(e.preset!==void 0&&!(e.preset in Ui))throw new Error(`gsap-compat: unknown spring preset "${e.preset}" — use one of ${Object.keys(Ui).join(", ")}`);return{...e.preset?Ui[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 aw(t,e){if(t===!0||typeof t=="string")return;const n=t.velocity;return typeof n=="number"?n:n?.[e]}class wn{timeline;options;cursor=0;fallbackRandom=Ea(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,ti(n),s)}from(e,n,s){const{config:i,properties:o}=co(ti(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=Jb(r));const d={},f=String(this.resolveStart(h,"text"));return a!==void 0&&(d.text=Ia(a),u.text=typeof a=="object"?{...a,value:f}:f),l!==void 0&&(d.text=Ia(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}=co(ti(n));return this.build(e,o,ti(s),i)}set(e,n,s){return this.build(e,void 0,{...ti(n),duration:0},s)}get lastStart(){return this.previousStart}get lastEnd(){return this.previousEnd}addEvent(e){const n=Math.max(0,Qs(e,this.context()));return this.previousStart=n,this.previousEnd=n,this.cursor=Math.max(this.cursor,n),n}timeOf(e){return Qs(e,this.context())}addLabel(e,n){return this.labels.set(e,Qs(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=Qs(n,this.context());for(const o of e.timeline.tracks){if(!("keyframes"in o))continue;const r=eo({...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}=co(s),{motionPath:a,text:l,scrambleText:c,inertia:h,...u}=r,d=this.targetsOf(e),f=Qs(i,this.context()),p=ho(o.delay,0),g=ho(o.duration,500),m=$a(o.stagger,{count:d.length,columnsFromLayout:this.options.layoutColumns?()=>this.options.layoutColumns(d):void 0,random:this.options.random??this.fallbackRandom}),b=this.easingFor(o.ease),v=[],k=o.spring;let w=0,T=!1;for(const[I,A]of Object.entries(u)){const O=A;let H=n?.[I]!==void 0?n[I]:this.resolveStart(d[0],I);if(typeof H!=typeof O&&(this.warn(`no usable start value for "${I}" on "${d[0]}" — it will snap to ${String(O)}. Use fromTo() to animate it.`),H=O),k!==void 0&&(typeof H!="number"||typeof O!="number")&&this.warn(`spring works on numbers, so "${I}" on "${d[0]}" eases instead`),k!==void 0&&typeof H=="number"&&typeof O=="number"){const J={...rw(k),from:H,to:O,velocity:aw(k,I)??this.options.startVelocity?.(d[0],I)??0},tt=this.nextTrackId(`${d[0]}-${I}-spring`),V={id:tt,target:d[0],...d.length>1&&{targets:d},...m&&d.length>1&&{stagger:m},property:I,kind:"spring",spring:J,delay:f+p};this.timeline.addTrack(V),v.push(tt),w=Math.max(w,Sh(J));for(const L of d)this.lastValues.set(`${L}|${I}`,O);continue}T=!0;const W=this.keyframesFor(H,O,g,b,o.ease),j=this.nextTrackId(`${d[0]}-${I}`);this.timeline.addTrack(eo({id:j,target:d[0],...d.length>1&&{targets:d},...m&&d.length>1&&{stagger:m},property:I,delay:f+p,keyframes:W,...I==="quaternion"&&{interpolation:"slerp"}})),v.push(j);for(const J of d)this.lastValues.set(`${J}|${I}`,O)}const P=iw({text:l,scrambleText:c},d[0],g);if(P){const I=n?.text??n?.scrambleText,A=I!==void 0?Ia(I):this.resolveStart(d[0],"text"),O=this.nextTrackId(`${d[0]}-text`),H={id:O,target:d[0],...d.length>1&&{targets:d},...m&&d.length>1&&{stagger:m},property:"text",textConfig:{from:typeof A=="string"?A:String(A??""),...P},delay:f+p,keyframes:this.keyframesFor(0,1,g,b,o.ease)};this.timeline.addTrack(H),v.push(O);for(const W of d)this.lastValues.set(`${W}|text`,P.to)}if(a!==void 0){const{config:I,start:A,end:O}=Vb(a),H=this.nextTrackId(`${d[0]}-motionPath`),W={id:H,target:d[0],...d.length>1&&{targets:d},...m&&d.length>1&&{stagger:m},property:"motionPath",motionPathConfig:I,delay:f+p,keyframes:this.keyframesFor(A,O,g,b,o.ease)};this.timeline.addTrack(W),v.push(H)}if(h!==void 0)for(const[I,A]of Object.entries(h)){const O=this.resolveStart(d[0],I);if(typeof O!="number"){this.warn(`inertia on "${I}" needs a numeric start value; skipped`);continue}const H=ow(O,A),W=this.nextTrackId(`${d[0]}-${I}-inertia`),j={id:W,target:d[0],...d.length>1&&{targets:d},...m&&d.length>1&&{stagger:m},property:I,kind:"inertia",inertia:H,delay:f+p};this.timeline.addTrack(j),v.push(W),w=Math.max(w,zn(H));for(const J of d)this.lastValues.set(`${J}|${I}`,Bn(H))}const M=((h!==void 0||k!==void 0)&&!T&&!P&&a===void 0?w:Math.max(g,w))+(m&&d.length>1?Fs(d.length,m):0),E=f+p+M;return this.previousStart=f+p,this.previousEnd=E,this.cursor=Math.max(this.cursor,E),{trackIds:v,start:f+p,end:E,kill:()=>{for(const I of v)this.timeline.removeTrack(I)}}}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"?Zs(o):void 0;if(a?.requiresBaking==="custom"||this.options.bakeEases&&Ls(i)){const c=a?.fn??Wt(i);return[r,...ha(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=z0(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 Zs(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 Ia(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 lw(t){return new wn(t)}function ti(t){return nw(Zb(t))}function cw(t){return!Array.isArray(t)||t.length!==4?null:`matrix3d(${pe(qe(t)).map(n=>Math.round(n*1e6)/1e6+0).join(", ")})`}const hw=new Set(["blur","brightness","glow","glowColor","shadowX","shadowY","shadowBlur","shadowColor"]),uw="#ffffff",dw="rgba(0, 0, 0, 0.5)";function fw(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??uw})`),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??dw})`)}return e.length>0?e.join(" "):null}function gw(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 pw(t){if(!("ownerSVGElement"in t))return;const e=t.style;!e||e.transformBox||(e.transformBox="fill-box",e.transformOrigin||(e.transformOrigin="50% 50%"))}const Y0=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"]),mw=new Set(["x","y","z","rotate","rotateX","rotateY","rotateZ","scale","scaleX","scaleY","scaleZ","skewX","skewY","quaternion","motionPathX","motionPathY","motionPathRotate"]),yw=["x","motionPathX","y","motionPathY","z","rotate","rotateZ","motionPathRotate","rotateX","rotateY","quaternion","scale","scaleX","scaleY","scaleZ","skewX","skewY"],bw=new Set(["childPerspective","perspectiveOriginX","perspectiveOriginY"]),ww=new Set(["originX","originY"]),kw=new Set(["clipTop","clipRight","clipBottom","clipLeft"]),vw=new Set(["drawOn"]),Mw={fill:"backgroundColor",stroke:"borderColor",strokeWidth:"borderWidth",color:"color",backgroundColor:"backgroundColor",borderColor:"borderColor"},K0={fill:"fill",stroke:"stroke",strokeWidth:"strokeWidth",strokeDasharray:"strokeDasharray",strokeDashoffset:"strokeDashoffset",fillOpacity:"fillOpacity",strokeOpacity:"strokeOpacity"},Sw="http://www.w3.org/2000/svg";class kn{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)&&!vw.has(p)){if(mw.has(p))(s??={})[p]=g;else if(bw.has(p))typeof g=="number"&&((i??={})[p]=g);else if(ww.has(p))typeof g=="number"&&((o??={})[p]=g);else if(kw.has(p))typeof g=="number"&&((r??={})[p]=g);else if(hw.has(p))(a??={})[p]=g;else if(p!=="perspective"){if(p!=="shine")if(p==="text"&&typeof g=="string")gw(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 yw){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(" "),pw(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,b=r.clipLeft??0;e.style.clipPath=`inset(${p}% ${g}% ${m}% ${b}%)`}if(a){const p=fw(a);p&&(e.style.filter=p)}}buildTransformPart(e,n){if(e==="quaternion")return cw(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===Sw&&n in K0){const a=Array.isArray(s)?s.join(", "):String(s);e.style[K0[n]]=a;return}else n==="fill"&&e.dataset?.elementType==="text"?i="color":i=Mw[n]??n;let r;typeof s=="number"?Y0.has(n)||Y0.has(i)?r=`${s}px`:r=String(s):Array.isArray(s)?r=s.join(", "):r=s,e.style[i]=r}}const xw={request:t=>requestAnimationFrame(t),cancel:t=>cancelAnimationFrame(t)};class X0{adapter=new kn;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=zb();active=new Map;applied=new Map;dirty=new Set;frameId=null;lastTimestamp=null;destroyed=!1;constructor(e={}){this.scheduler=e.scheduler??xw,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);Oa(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(Oa(e))return[e];if(!Tw(e))return[e];const n=[];for(const s of Array.from(e))n.push(...this.targetsOf(s));return n}nameFor(e){return Oa(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 Oa(t){return typeof t=="object"&&t!==null&&t.nodeType===1}function Tw(t){if(Array.isArray(t))return!0;const e=t;return typeof e.length=="number"&&typeof e.item=="function"}function uo(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 G0=t=>typeof t=="object"&&t!==null&&t.nodeType===1;function Ew(t){const e={};for(const n of Array.from(t.attributes))e[n.name]=n.value;return e}function Aw(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 $w(t,e){const n=typeof t=="string"||Array.isArray(t)||G0(t)?{path:t}:t,{align:s,alignOrigin:i,path:o,...r}=n,a=P=>{const S=G0(P)?P:e.query(P);return S||e.warn(`gsap-compat: motionPath could not find "${String(P)}"`),S};let l=null,c="";if(Array.isArray(o)||typeof o=="string"&&jn(o))c=o;else{l=a(o);const P=l&&so({tag:l.localName,attributes:Ew(l)});l&&!P&&e.warn(`gsap-compat: motionPath element <${l.localName}> has no path geometry`),c=P??""}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,b,v]=Aw(u),k=uo(d),[w,T]=i??[.5,.5];for(const P of e.targets.slice(1)){const S=uo(P);if(Math.abs(S.left-k.left)>.5||Math.abs(S.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,b-k.left-w*k.width,v-k.top-T*k.height],h}const U0=t=>typeof t=="object"&&t!==null&&t.nodeType===1;function V0(t){const e={};for(const n of Array.from(t.attributes))e[n.name]=n.value;return e}function J0(t){if(!t)return null;const e=so({tag:t.localName,attributes:V0(t)});return e||(t.querySelector("path")?.getAttribute("d")??null)}function Pw(t,e,n){const s=q0(t);if(typeof s=="string"&&jn(s))return s;const i=U0(s)?s:typeof s=="string"?e(s):null,o=J0(i);return o||(n(`gsap-compat: morphSVG could not find a shape for "${String(s)}"`),"")}const Iw=new Set(["cx","cy","r","rx","ry","x","y","width","height","x1","y1","x2","y2","points"]);function Ow(t,e=document){return(typeof t=="string"?Array.from(e.querySelectorAll(t)):U0(t)?[t]:Array.from(t)).map(s=>{if(s.localName==="path")return s;const i=so({tag:s.localName,attributes:V0(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))Iw.has(r.name)||o.setAttribute(r.name,r.value);return o.setAttribute("d",i),s.parentNode.replaceChild(o,s),o})}const Z0=.3;class Q0{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=tu(),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=tu(),i=Math.max(1,s-this.lastTime);this.lastTime=s;const o=e/i*1e3,r=n/i*1e3;this.velocityX+=(o-this.velocityX)*Z0,this.velocityY+=(r-this.velocityY)*Z0}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 tu(){return typeof performance<"u"?performance.now():Date.now()}function eu(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 nu(t,e){return e<=0?[]:t.map(n=>Math.round(n/e)*e)}class _a{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 Q0({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=_w(i/s);e.pause(),e.seek(o*n)}applyConstraints(e,n){let s=e;const i=[...nu([s],this.options.snap??0),...(n==="x"?this.options.snapLinesX:this.options.snapLinesY)??[]],o=eu([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 _w(t){return t<0?0:t>1?1:t}function Cw(t){const e=new _a(t);return e.start(),e}const Hw={x:"x",y:"y","x,y":"both"},Ca=t=>typeof t=="object"&&t!==null&&t.nodeType===1;function su(t,e){const n=uo(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 iu(t){return Array.isArray(t)?[...t]:t}function Rw(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 Lw(t,e,i,o,s);const r=Hw[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):Ca(s.bounds)?s.bounds:null,h={bounds:(!l&&s.bounds&&!Ca(s.bounds)?s.bounds:void 0)??(l?su(o,l):void 0)};let u=null;const d=()=>{u?.kill(),u=null},f=g=>{const m=s.inertia===!0?{}:s.inertia,b=m.friction??(m.resistance!==void 0?Pa(m.resistance):4),v=a(),k=h.bounds??{};let w,T;const P=m.end;if(Array.isArray(P)){const x=Ws({from:v.x,velocity:r==="y"?0:g.x,friction:b}),M=Ws({from:v.y,velocity:r==="x"?0:g.y,friction:b});let E=P[0];for(const I of P)Math.hypot(I.x-x,I.y-M)<Math.hypot(E.x-x,E.y-M)&&(E=I);E&&(w=[E.x],T=[E.y])}else typeof P=="number"?(w=P,T=P):P&&(w=iu(P.x),T=iu(P.y));const S={};r!=="y"&&(S.x={velocity:g.x,friction:b,min:k.minX,max:k.maxX,end:w}),r!=="x"&&(S.y={velocity:g.y,friction:b,min:k.minY,max:k.maxY,end:T}),u=t.to(o,{inertia:S,onComplete:()=>s.onThrowComplete?.()})},p=new _a({target:o,axis:r,snap:s.snap,get bounds(){return h.bounds},getPosition:a,onPress:()=>{d(),l&&(h.bounds=su(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 Lw(t,e,n,s,i){const o=typeof i.bounds=="object"&&i.bounds!==null&&!Ca(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 w=s.getBoundingClientRect();u={x:w.left+w.width/2,y:w.top+w.height/2},d=g(k),f=r(),p=[{time:performance.now(),rotation:f}],i.onPress?.()},b=k=>{if(!c||k.pointerId!==h)return;const w=g(k);let T=w-d;T>180&&(T-=360),T<-180&&(T+=360),d=w,f+=T;let P=a(f);i.snap&&(P=a(Math.round(P/i.snap)*i.snap)),e.apply(n,{rotate:P});const S=performance.now();for(p.push({time:S,rotation:P});p.length>2&&S-p[0].time>100;)p.shift();const x={x:0,y:0};i.onDrag?.(x)},v=k=>{if(!c||k.pointerId!==h)return;c=!1;const w=p[0],T=p[p.length-1],P=w&&T?(T.time-w.time)/1e3:0,S=P>0?(T.rotation-w.rotation)/P:0;if(i.onRelease?.({x:S,y:0}),!i.inertia)return;const x=i.inertia===!0?{}:i.inertia,M=x.friction??(x.resistance!==void 0?Pa(x.resistance):4),E=typeof x.end=="number"||Array.isArray(x.end)?x.end:void 0;l=t.to(s,{inertia:{rotate:{velocity:S,friction:M,min:o.minRotation,max:o.maxRotation,end:Array.isArray(E)?E.filter(I=>typeof I=="number"):E}},onComplete:()=>i.onThrowComplete?.()})};return s.addEventListener("pointerdown",m),s.addEventListener("pointermove",b),s.addEventListener("pointerup",v),s.addEventListener("pointercancel",v),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",v),s.removeEventListener("pointercancel",v)}}}const Fw={opacity:0,scale:.6};function Nw(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 ou(t){const e=uo(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 Ha(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=Nw(r);i.set(r,a);const l=ru(r);a&&l!==void 0&&!o.has(l)&&o.set(l,{element:r,box:a})}return{elements:s,boxes:i,ids:o}}const Ra=new WeakMap;function La(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?Fw: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=ou(f);if(!p)continue;let g=n.boxes.get(f)??null,m;const b=ru(f),v=!g&&b!==void 0?n.ids.get(b):void 0;v&&v.element!==f&&(g=v.box,m=v.element);const[k]=t.resolveTargets(f);Ra.get(f)?.timeline.removeTracks({target:k});const w=d*r;if(!g){if(l===!1)continue;u.fromTo(f,{x:0,y:0,scaleX:1,scaleY:1,...l},{...au(l),x:0,y:0,scaleX:1,scaleY:1,duration:i,ease:o,delay:w},0),Ra.set(f,u),d++;continue}const T=g.cx-p.cx,P=g.cy-p.cy,S=a?g.width/p.width:1,x=a?g.height/p.height:1;if(!(Math.abs(T)>.5||Math.abs(P)>.5||Math.abs(S-1)>.001||Math.abs(x-1)>.001)){const I=(A,O)=>{const H=t.appliedValue(k,A);return typeof H=="number"&&Math.abs(H-O)>1e-6};(I("x",0)||I("y",0)||I("scaleX",1)||I("scaleY",1))&&u.set(f,{x:0,y:0,scaleX:1,scaleY:1},0);continue}const E=s.fade===!0&&m!==void 0;u.fromTo(f,{x:T,y:P,scaleX:S,scaleY:x,...E&&{opacity:0}},{x:0,y:0,scaleX:1,scaleY:1,...E&&{opacity:1},duration:i,ease:o,delay:w},0),E&&m&&ou(m)&&u.fromTo(m,{opacity:1},{opacity:0,duration:i,ease:o,delay:w},0),Ra.set(f,u),d++}return u}function ru(t){return t.dataset?.flipId}function au(t){const e={};for(const n of Object.keys(t))e[n]=n==="opacity"||n.startsWith("scale")?1:0;return e}function Ww(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:b}of o)g.innerHTML=m,b===null?g.removeAttribute("aria-label"):g.setAttribute("aria-label",b)},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 b=(m.textContent??"").replace(/\s+/g," ").trim(),v=Dw(m,s.words),k=n.has("chars")?v.flatMap(P=>Bw(P,s.chars)):[],w=n.has("lines")?qw(m,v,s.lines):[];if(i){!m.hasAttribute("aria-label")&&b&&m.setAttribute("aria-label",b);for(const P of v)P.setAttribute("aria-hidden","true")}if(n.has("words"))g.words.push(...v);else for(const P of v)P.removeAttribute("class");g.chars.push(...k),g.lines.push(...w);const T=e.mask==="lines"?w:e.mask==="words"?v:e.mask==="chars"?k:[];for(const P of T)g.masks.push(jw(P,`${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 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 w=!1;for(const T of k){const P=Math.round(T.contentRect.width),S=g.get(T.target);g.set(T.target,P),S!==void 0&&S!==P&&(w=!0)}w&&b()});for(const k of t)l.observe(k)}const v=t[0]?.ownerDocument?.fonts;v&&v.status!=="loaded"&&v.ready.then(()=>b())}return f}function Dw(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 Bw(t,e){const n=t.ownerDocument,s=zw(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 zw(t){const e=Intl.Segmenter;return e?Array.from(new e(void 0,{granularity:"grapheme"}).segment(t),n=>n.segment):Array.from(t)}function qw(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 b=0;for(;b<d.length&&b<m.length&&d[b].original===m[b];)b++;d.length=b;let v=b===0?l:d[b-1].clone;for(const k of m.slice(b)){const w=k.cloneNode(!1);v.appendChild(w),d.push({original:k,clone:w}),v=w}v.appendChild(p)}return t.replaceChildren(...a),a}function jw(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 lu={top:0,left:0,start:0,center:.5,centre:.5,middle:.5,bottom:1,right:1,end:1};function Fa(t){const e=t.trim().toLowerCase();if(e in lu)return lu[e];if(e.endsWith("%")){const n=Number.parseFloat(e.slice(0,-1));return Number.isNaN(n)?void 0:n/100}}function Na(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?Fa(s[0]):void 0,o=s[1]!==void 0?Fa(s[1]):void 0;return{elementFraction:i??0,viewportFraction:o??0,offsetPx:e}}function Un(t,e,n){const s=Na(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 Yw(t,e,n,s){const i=Un(t,e,n),r=Un(t,e,s)-i;return r<=0?i<=0?1:0:Wa(-i/r)}function Wa(t){return t<0?0:t>1?1:t===0?0:t}function cu(t,e,n,s){if(n<=0)return e;const i=1-Math.exp(-(s/1e3)/n);return t+(e-t)*i}function Da(t,e,n,s,i){const o=h=>Un({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 hu{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 Kw(t){const e=new hu(t);return e.start(),e}class uu{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 Xw=.15;function du(t){return typeof t=="object"&&!Array.isArray(t)?t:{snapTo:t}}function fu(t,e,n){const s=fo(t+e*Xw);if(typeof n=="function")return fo(n(s));if(typeof n=="number")return n<=0?t:fo(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 fo(i)}function gu(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 pu{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=Ds,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 fo(t){return Math.max(0,Math.min(1,t))}class mu{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 Gw=120,Vn=[],Jn=new Set;let Ba=!1;const Uw=()=>{Ba||Jn.size===0||(Ba=!0,queueMicrotask(()=>{Ba=!1;for(const t of Jn)t.afterRefresh()}))},yu=()=>{for(const t of Jn)t.beforeRefresh();for(const t of Vn)t.refresh();for(const t of Jn)t.afterRefresh()};let Zn={width:0,height:0};const bu=()=>{const t=window.innerWidth,e=window.innerHeight,n=t===Zn.width&&e!==Zn.height,s=Math.abs(e-Zn.height)<Zn.height*.25,i=typeof navigator<"u"&&(navigator.maxTouchPoints??0)>0;n&&s&&i||(Zn={width:t,height:e},yu())};class ei{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 pu(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 uu(e,{axis:this.options.horizontal?"x":"y",spacing:this.options.pinSpacing!==!1})),this.options.markers&&!this.options.horizontal&&typeof document<"u"&&(this.markers=new mu(document,this.options.scroller??null,this.options.markers)),this.scrollTarget()?.addEventListener("scroll",this.onScroll,{passive:!0}),Vn.length===0&&typeof window<"u"&&(Zn={width:window.innerWidth,height:window.innerHeight},window.addEventListener("resize",bu,{passive:!0})),Vn.push(this),this.refresh()}stop(){this.running&&(this.running=!1,this.scrollTarget()?.removeEventListener("scroll",this.onScroll),Vn.splice(Vn.indexOf(this),1),Vn.length===0&&typeof window<"u"&&window.removeEventListener("resize",bu),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(){yu()}static onRefresh(e){return Jn.add(e),()=>Jn.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+Un(n,s,ni(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,Uw()}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?Wa((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=ni(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+Un(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()},Gw))}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=du(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+fu(r,this.releaseVelocity/i,n.snapTo)*i;Math.abs(a-o)<1||this.snapper.animate(o,a,gu(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=Da(r,s.width,o,ni(this.options.start)??"left right",e.shiftAt);this.startPx=c(h);const u=ni(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(Da(r,s.width,o,u,e.shiftAt)),this.markerGeometry=null}markersFor(e){const n=(o,r)=>{const a=ni(o)??r;if(typeof a=="number")return 0;if(/^\s*\+=/.test(a))return;const l=Na(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=cu(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 ni(t){return typeof t=="function"?t():t}function Vw(t){const e=new ei(t);return e.start(),e}const za=new Set,Jw=16,wu=.5,Zw=2;class qa{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),za.add(this),this.stopListening=ei.onRefresh({beforeRefresh:()=>this.rest(),afterRefresh:()=>this.refresh()}),this.refresh(),this}static refreshAll(){for(const e of za)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),za.delete(this),this.stopListening?.(),this.stopListening=null,this.cancelFrame(),this.journey=null,this}destroy(){this.stop();for(const e of this.effects)ja(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??Ds,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)ja(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?Jw: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)<=Zw||(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)<wu&&(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)<wu?i.lagged=s:n=!0,o+=s-i.lagged}ja(i.element,o===0?i.saved:`0 ${Qw(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 ja(t,e){e?t.style.setProperty("translate",e):t.style.removeProperty("translate")}function Qw(t){return Math.round(t*100)/100}function t2(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 Ya(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&&t2(n,l[f]??"none"),e.once&&f===0&&queueMicrotask(()=>h.destroy())},d=e.containerAnimation?s2(t,e.containerAnimation,r,i):void 0;return h=new ei({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:e2(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 e2(t,e){const n=i=>i==="labels"?o=>n2(o,e?.labelProgresses?.()??[]):i;if(typeof t!="object"||Array.isArray(t))return n(t);const s=t.ease?Zs(t.ease):void 0;return{snapTo:n(t.snapTo),duration:t.duration,delay:t.delay,ease:s?s.fn??Wt(s.easing):void 0}}function n2(t,e){return e.reduce((n,s)=>Math.abs(s-t)<Math.abs(n-t)?s:n,e[0]??t)}function s2(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 ku{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 i2{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 ku(this.host,this.scope);o.conditions=n,o.add(()=>e.setup(o)),e.context=o}}class o2{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 r2={opacity:0,y:-16},a2={opacity:0,y:16};async function l2(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 c2(o,s,r);const a=s.duration??.35,l=s.ease??"power2.inOut",c=m=>new Promise(b=>{m(b)||b()}),h=r(),u=h.length?Ha(e,h):void 0,d=s.from!==void 0?vu(e,s.from,s.shared):[];if(d.length&&s.leave!==!1){const m=s.leave??r2;await c(b=>t.to(d,{...m,duration:a,ease:l,onComplete:b}))}await s.update();const f=[],p=typeof s.to=="function"?s.to():s.to,g=p!==void 0?vu(e,p,s.shared):[];if(g.length&&s.enter!==!1){const m=s.enter??a2;f.push(c(b=>t.fromTo(g,m,{...au(m),duration:a,ease:l,onComplete:b})))}if(u){const m=r().filter(b=>!h.includes(b));m.length&&f.push(c(b=>La(e,n,u,{targets:m,duration:a*1.4,ease:l,enter:!1,onComplete:b})))}await Promise.all(f)}function vu(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 c2(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 Mu={create:(t,e)=>Ta(t,v0(e))},Su={create:(t,e)=>Ta(t,{fn:M0(e)})},xu={create:(t,e)=>Ta(t,{fn:S0(e)})},h2=new Set(["keyframes","duration","delay","ease","easeEach","stagger","repeat","repeatDelay","yoyo","repeatRefresh","paused","id","onStart","onUpdate","onComplete","onRepeat","onReverseComplete","scrollTrigger"]),Tu=.5,u2="power1.inOut";function d2(t){return t.keyframes!==void 0&&t.keyframes!==null}function f2(t){const e=t.keyframes,n={};for(const[c,h]of Object.entries(t))h2.has(c)||(n[c]=h);if(Array.isArray(e))return e.map(c=>({...n,...c,duration:c.duration??t.duration??Tu}));const s=Object.entries(e),i=t.duration??Tu,o=e.easeEach??t.easeEach??u2;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 Eu(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=(v,k)=>{if(k===void 0)return r[v];if(typeof k=="number")return k;if(k==="max")return a[v];const w=typeof k=="string"?i.querySelector(k):k;if(!w)return r[v];const T=w.getBoundingClientRect(),P=o?.getBoundingClientRect(),S=(v==="x"?s.offsetX:s.offsetY)??s.offset??0;return v==="x"?T.left-(P?.left??0)+r.x-S:T.top-(P?.top??0)+r.y-S},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=()=>{b.kill(),m()},m=()=>{for(const v of f)p.removeEventListener(v,g)},b=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 v of f)p.addEventListener(v,g,{passive:!0});return b}function g2(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=b=>{p[b]!==void 0&&clearTimeout(p[b]),p[b]=void 0;const v=f[b].splice(0);v.length>0&&d[b]?.(v)},m=(b,v)=>{if(d[b]){if(f[b].push(v),r!==void 0&&f[b].length>=r)return g(b);p[b]===void 0&&(p[b]=setTimeout(()=>g(b),o*1e3))}};return i.map(b=>Ya(t,{...u,trigger:b,onEnter:()=>m("onEnter",b),onLeave:()=>m("onLeave",b),onEnterBack:()=>m("onEnterBack",b),onLeaveBack:()=>m("onLeaveBack",b)})).filter(b=>b!==void 0)}class Se{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 wn({...s,startValue:(i,o)=>{const r=e.objectFor(i);if(r)return y2(r[o]);const a=e.appliedValue(i,o);if(a!==void 0)return a;if(o==="d")return J0(e.elementFor(i))??void 0;if(o==="text")return e.elementFor(i)?.textContent??void 0;if(o==="strokeDasharray"||o==="strokeDashoffset"){const l=Ou(e.elementFor(i));if(l!==void 0)return o==="strokeDasharray"?[l,l]:0}},startVelocity:(i,o)=>e.velocityOf(i,o),layoutColumns:i=>Iu(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=Ya(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 d2(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 Se(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}=fa(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=f2(n);if(o.length===0)return;const r=i.length>1?$a(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?Xi(i.length,r).map(m=>m/1e3):[0],h=this.compat.timeOf(s)/1e3+ho(n.delay,0)/1e3;let u=1/0,d=-1/0;if(l.forEach((m,b)=>{o.forEach((v,k)=>{const w=k===0?h+c[b]:">";this.tween(m,[v],w,([T],P,S)=>this.compat.to(P,T,S)),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:()=>Iu(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(m2)||e.some(d=>this.stage.objectFor(d)!==void 0)))){const d=this.targetFor(e[0]);i(n.map(f=>this.prepare(Pu(f,0,d,this.stage.utils,o),e)),e,s);return}const a=n.length-1,{stagger:l,...c}=n[a],h=$a(l,this.staggerContext(e)),u=h?Xi(e.length,h).map(d=>d/1e3):e.map(()=>0);e.forEach((d,f)=>{const p=f===0?ho(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)}`,v=n.map((k,w)=>w===a?{...c,delay:p}:k).map(k=>this.prepare(Pu(k,f,this.targetFor(d),this.stage.utils,o),[d]));i(v,[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=$w(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=Pw(e.morphSVG,i,s),{morphSVG:a,...l}=o;o=r?{...o,morphSVG:r}:l}if(e.drawSVG!==void 0){const r=Ou(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=ew(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 ${b2(e)}`);return}return this.firstElement??=n.map(s=>this.stage.elementFor(s)).find(s=>s!==void 0),n}}function Au(t=new X0){const e=o=>{const{config:r}=co(o);return new Se(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)??z0(r)},scrollTrigger:o=>s(Ya(t,o)),scrollBatch:(o,r)=>g2(t,o,r).map(a=>s(a)),scrollTo:(o,r)=>Eu(i,t,o,r),refreshScroll:()=>{ei.refreshAll(),qa.refreshAll()},smoothScroll:(o={})=>{const r=typeof o.scroller=="string"?(t.collector?.scope??t.root).querySelector(o.scroller):o.scroller;return s(new qa({...o,scroller:r}).start())},context:(o,r)=>{const a=new ku(t,r);return o&&a.add(()=>o(a)),a},matchMedia:o=>new i2(t,o),customEase:Mu.create,customBounce:Su.create,customWiggle:xu.create,pageTransition:o=>l2(i,t,r=>new Se(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 o2(a,r))},quickTo:(o,r,a={})=>{const l=new Se(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:p2(a.spring,r,d)}}),l.timeline.stop(),l.timeline.play(),t.activate(l.timeline)},{tween:l,kill:()=>l.kill()})},timeline:o=>new Se(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 Eu(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 Se(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=>Ow(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(Ww(l,r))},draggable:(o,r)=>s(Rw(i,t,o,r)),getFlipState:o=>Ha(t,o),flipFrom:(o,r)=>La(t,a=>new Se(t,a),o,r),flip:(o,r,a)=>{const l=Ha(t,o);return r(),La(t,c=>new Se(t,c),l,{targets:o,...a})}};return i}const oe=Au();function p2(t,e,n){return t===!0?{velocity:{[e]:n}}:typeof t=="string"?{preset:t,velocity:{[e]:n}}:{...t,velocity:{[e]:n}}}function m2(t){return t.morphSVG!==void 0||t.drawSVG!==void 0||t.text!==void 0||t.scrambleText!==void 0||$u(t)}function $u(t){return Object.entries(t).some(([e,n])=>(typeof n=="function"||D0(n))&&!Aa.has(e))}function Pu(t,e,n,s,i){if(!$u(t))return t;const o={};for(const[r,a]of Object.entries(t))Aa.has(r)?o[r]=a:typeof a=="function"?o[r]=a(e,n,i):D0(a)?o[r]=s.resolveRandomString(a):o[r]=a;return o}function Iu(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 Ou(t){const e=t;if(typeof e?.getTotalLength=="function")return e.getTotalLength()}function y2(t){if(typeof t=="number"||typeof t=="string"||Array.isArray(t)&&t.every(e=>typeof e=="number"))return t}function b2(t){return typeof t=="string"?`"${t}"`:String(t)}class Ka{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 _u(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 go{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 kn}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=Xn({...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 Ka(s)})})}syncAllMedia(e,n){for(const s of this.mediaTargets)_u(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 kn;s.querySelectorAll("[data-tinyfly]").forEach(a=>{const l=a.getAttribute("data-tinyfly");l&&r.registerTarget(l,a)}),this.symbolInstances.push({adapter:r,timeline:Xn(o.timeline)})})}attachMedia(e,n){this.mediaSync=new Ka(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}=fa(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 w2(t,e,n={}){const s=new go(t,{...n,autoplay:!0});return await s.load(e),s}function k2(t,e={}){return new go(t,e)}const Cu={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"},Hu="tinyfly-controls-style",v2=`
|
|
1
|
+
(function(y,Dn){typeof exports=="object"&&typeof module<"u"?Dn(exports):typeof define=="function"&&define.amd?define(["exports"],Dn):(y=typeof globalThis<"u"?globalThis:y||self,Dn(y.tinyfly=y.tinyfly||{}))})(this,(function(y){"use strict";function Dn(t){return typeof t=="object"&&t!==null&&t.type==="cubic-bezier"}function Fs(t){return typeof t=="object"&&t!==null&&t.type!=="cubic-bezier"}const Go=2;function Uo(t){return t.some(e=>e.interpolation!==void 0)?2:1}function Ki(t){return t.property==="text"&&"textConfig"in t}function De(t){return t.kind==="inertia"&&"inertia"in t}function Be(t){return t.kind==="spring"&&"spring"in t}function Vo(t){return t.property==="motionPath"&&"motionPathConfig"in t}function Uy(t){return typeof t=="object"&&t!==null&&"x"in t&&"y"in t&&"angle"in t}function $h(t){return"keyframes"in t}class Vy{_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 Jy{_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 Ph(t,e){if(!(e>0))return t;const n=1e3/e;return Math.floor(t/n+1e-9)*n}function Jo(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 Zo(t,e="start"){if(t<=1)return 0;let n=0;for(let s=0;s<t;s++)n=Math.max(n,Jo(s,t,e));return n}function Xi(t,e,n){if(n.offsets)return n.offsets[t]??0;const s=n.from??"start",i=Jo(t,e,s);if(n.amount!==void 0){const r=Zo(e,s);return r===0?0:n.amount*i/r}return n.each!==void 0?n.each*i:0}function Gi(t,e){return Array.from({length:t},(n,s)=>Xi(s,t,e))}function Ns(t,e){return t<=1?0:Math.max(...Gi(t,e))}const Bn=1,Qo=6e4,Ui=Qo/Bn,ce={stiffness:180,damping:12,mass:1,velocity:0,restDelta:.01,restSpeed:.1},Vi={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 Ws{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??ce.stiffness,this.damping=e.damping??ce.damping,this.mass=e.mass??ce.mass,this.restDelta=e.restDelta??ce.restDelta,this.restSpeed=e.restSpeed??ce.restSpeed,this.distance=Math.abs(this.to-this.from)||1,this.samples=[this.from],this.velocity=e.velocity??ce.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/Bn);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)],r=e/Bn-n;return s+(i-s)*r}settleTime(){return this.simulateTo(Ui+1),this.settledStep!==null?this.settledStep*Bn:Qo}simulateTo(e){if(this.settledStep!==null)return;const n=Math.min(e,Ui+1),s=Bn/1e3;for(;this.samples.length<n;){const i=this.samples[this.samples.length-1],r=i-this.to,o=-this.stiffness*r,a=-this.damping*this.velocity,l=(o+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>Ui&&(this.settledStep=Ui)}}function Zy(t,e){return new Ws(t).valueAt(e)}function Ih(t){return new Ws(t).settleTime()}function Qy(t){const e=t.stiffness??ce.stiffness,n=t.damping??ce.damping,s=t.mass??ce.mass;return n<2*Math.sqrt(e*s)}function t1(t){const e=t.stiffness??ce.stiffness,n=t.mass??ce.mass;return 2*Math.sqrt(e*n)}const ta=4,e1=.002,n1=1e-4,Oh=6e4;function Ji(t){const e=t.friction??ta;return e>0?e:ta}function Ds(t){return t.from+t.velocity/Ji(t)}function s1(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 zn(t){let e=s1(Ds(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 qn(t){const e=Math.abs(zn(t)-t.from);if(e===0)return 0;const n=t.restDelta??Math.max(n1,e*e1);if(n>=e)return 0;const s=Math.log(e/n)/Ji(t);return Math.min(Oh,s*1e3)}function Zi(t,e){if(e<=0)return t.from;const n=zn(t);if(e>=qn(t))return n;const s=Ji(t);return t.from+(n-t.from)*(1-Math.exp(-s*e/1e3))}function i1(t,e){const n=Ji(t),s=zn(t);return e>=qn(t)?0:(s-t.from)*n*Math.exp(-n*Math.max(0,e)/1e3)}const Qi=t=>t,Ch=t=>t*t,_h=t=>1-(1-t)*(1-t),Hh=t=>t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2,ea=t=>t*t*t,na=t=>1-Math.pow(1-t,3),Bs=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,Rh=ea,Lh=na,Fh=Bs,r1={linear:Qi,"ease-in":Rh,"ease-out":Lh,"ease-in-out":Fh,"ease-in-quad":Ch,"ease-out-quad":_h,"ease-in-out-quad":Hh,"ease-in-cubic":ea,"ease-out-cubic":na,"ease-in-out-cubic":Bs};function Nh(t){const[e,n,s,i]=t,r=3*e,o=3*(s-e)-r,a=1-r-o,l=3*n,c=3*(i-n)-l,h=1-l-c,u=g=>((a*g+o)*g+r)*g,d=g=>((h*g+c)*g+l)*g,f=g=>(3*a*g+2*o)*g+r,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 T=f(m);if(Math.abs(T)<1e-7)break;m-=b/T}let w=0,v=1;for(m=g;w<v;){const k=u(m);if(Math.abs(k-g)<1e-7)return m;g>k?w=m:v=m,m=(w+v)/2}return m};return g=>{if(g<=0)return 0;if(g>=1)return 1;const m=p(g);return d(m)}}function sa(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 Wh(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 Dh=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 Bh(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 zh(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 qh(t){switch(t.type){case"steps":return zh(t.count,t.position);case"elastic":return sa(Wh(t.amplitude,t.period),t.mode);case"bounce":return sa(Dh,t.mode);case"back":return sa(Bh(t.overshoot),t.mode)}}function Wt(t){return t===void 0?Qi:Dn(t)?Nh(t.points):Fs(t)?qh(t):r1[t]??Qi}const jh=32,o1=256,jn=new Map,a1=/[MmLlHhVvCcSsQqTtAaZz]/,l1=/^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/,c1={M:2,L:2,H:1,V:1,C:6,S:4,Q:4,T:2,A:7,Z:0};function h1(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 r=t[n];if(a1.test(r)){s={type:r,args:[]},e.push(s),n++;continue}if(!s)break;const o=s.type==="A"||s.type==="a",a=s.args.length%7;if(o&&(a===3||a===4)){if(r!=="0"&&r!=="1")break;s.args.push(r==="1"?1:0),n++;continue}const l=l1.exec(t.slice(n));if(!l)break;s.args.push(parseFloat(l[0])),n+=l[0].length}return e}function u1(t,e,n,s,i,r,o,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,w=-f*p+d*g,v=m*m/(c*c)+w*w/(h*h);if(v>1){const L=Math.sqrt(v);c*=L,h*=L}const k=r===o?-1:1,b=c*c*h*h-c*c*w*w-h*h*m*m,T=c*c*w*w+h*h*m*m,$=k*Math.sqrt(Math.max(0,b/T)),M=$*c*w/h,x=-$*h*m/c,S=d*M-f*x+(t+a)/2,E=f*M+d*x+(e+l)/2,I=(L,q,G,_)=>{const Y=L*G+q*_,st=Math.sqrt((L*L+q*q)*(G*G+_*_)),P=Math.acos(Math.max(-1,Math.min(1,Y/st)));return L*_-q*G<0?-P:P},A=I(1,0,(m-M)/c,(w-x)/h);let O=I((m-M)/c,(w-x)/h,(-m-M)/c,(-w-x)/h);!o&&O>0&&(O-=2*Math.PI),o&&O<0&&(O+=2*Math.PI);const H=Math.max(1,Math.ceil(Math.abs(O)/(Math.PI/2))),W=O/H,j=4/3*Math.tan(W/4),J=L=>{const q=c*Math.cos(L),G=h*Math.sin(L);return[d*q-f*G+S,f*q+d*G+E]},tt=L=>{const q=-c*Math.sin(L),G=h*Math.cos(L);return[d*q-f*G,f*q+d*G]},V=[];for(let L=0;L<H;L++){const q=A+L*W,G=q+W,[_,Y]=J(q),[st,P]=L===H-1?[a,l]:J(G),[C,z]=tt(q),[K,N]=tt(G);V.push([_+j*C,Y+j*z,st-j*K,P-j*N,st,P])}return V}function ze(t,e,n,s,i){const r=1-i;return r*r*r*t+3*r*r*i*e+3*r*i*i*n+i*i*i*s}function Yh(t,e,n,s,i){const r=1-i;return 3*r*r*(e-t)+6*r*i*(n-e)+3*i*i*(s-n)}function zs(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 tr(t,e,n){const[s,i,r,o,a,l]=n,c=[0];let h=t,u=e,d=0;for(let f=1;f<=jh;f++){const p=f/jh,g=ze(t,s,r,a,p),m=ze(e,i,o,l,p);d+=Math.hypot(g-h,m-u),c.push(d),h=g,u=m}return{subpath:0,type:"C",points:[s,i,r,o,a,l],startX:t,startY:e,endX:a,endY:l,length:d,lengths:c}}function gn(t){const e=jn.get(t);if(e)return e;const n=[];let s=0,i=0,r=0,o=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 h1(t)){const w=g.toUpperCase(),v=g!==w,k=c1[w];if(w==="Z"){(s!==r||i!==o)&&u(zs(s,i,r,o)),c>=0&&h.add(c),s=r,i=o,a=l=null;continue}for(let b=0;b+k<=m.length;b+=k){const T=m.slice(b,b+k),$=v?s:0,M=v?i:0;let x=null,S=null;switch(w){case"M":b===0?(s=T[0]+$,i=T[1]+M,r=s,o=i,(c<0||n[n.length-1]?.subpath===c)&&c++):(u(zs(s,i,T[0]+$,T[1]+M)),s=T[0]+$,i=T[1]+M);break;case"L":u(zs(s,i,T[0]+$,T[1]+M)),s=T[0]+$,i=T[1]+M;break;case"H":u(zs(s,i,T[0]+$,i)),s=T[0]+$;break;case"V":u(zs(s,i,s,T[0]+M)),i=T[0]+M;break;case"C":{const E=[T[0]+$,T[1]+M,T[2]+$,T[3]+M,T[4]+$,T[5]+M];u(tr(s,i,E)),x=[E[2],E[3]],s=E[4],i=E[5];break}case"S":{const[E,I]=a?[2*s-a[0],2*i-a[1]]:[s,i],A=[E,I,T[0]+$,T[1]+M,T[2]+$,T[3]+M];u(tr(s,i,A)),x=[A[2],A[3]],s=A[4],i=A[5];break}case"Q":case"T":{let E=s,I=i;w==="Q"?(E=T[0]+$,I=T[1]+M):l&&(E=2*s-l[0],I=2*i-l[1]);const A=w==="Q"?T[2]+$:T[0]+$,O=w==="Q"?T[3]+M:T[1]+M;u(tr(s,i,[s+2/3*(E-s),i+2/3*(I-i),A+2/3*(E-A),O+2/3*(I-O),A,O])),S=[E,I],s=A,i=O;break}case"A":{const E=T[5]+$,I=T[6]+M;let A=s,O=i;for(const H of u1(s,i,T[0],T[1],T[2],T[3],T[4],E,I))u(tr(A,O,H)),A=H[4],O=H[5];s=E,i=I;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 w=g,v=0;for(;w<n.length&&n[w].subpath===m;)v+=n[w++].length;const k=n[g],b=n[w-1],T=h.has(m)||Math.abs(b.endX-k.startX)<1e-9&&Math.abs(b.endY-k.startY)<1e-9;f.push({start:g,end:w,length:v,closed:T}),g=w}const p={segments:n,totalLength:d,subpaths:f};return jn.size>=o1&&jn.delete(jn.keys().next().value),jn.set(t,p),p}function d1(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 r=n[i]-n[s],o=r>0?(e-n[s])/r:0;return(s+o)/(n.length-1)}function f1(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,r,o,a]=t.points,l=d1(t,e);let c=Yh(t.startX,n,i,o,l),h=Yh(t.startY,s,r,a,l);if(Math.hypot(c,h)<1e-9){const u=l<.5?Math.min(1,l+.001):Math.max(0,l-.001),d=ze(t.startX,n,i,o,u),f=ze(t.startY,s,r,a,u),p=ze(t.startX,n,i,o,l),g=ze(t.startY,s,r,a,l);c=l<.5?d-p:p-d,h=l<.5?f-g:g-f}return{x:ze(t.startX,n,i,o,l),y:ze(t.startY,s,r,a,l),angle:Math.atan2(h,c)*180/Math.PI}}function ia(t,e,n=0,s=t.length){if(s<=n)return{x:0,y:0,angle:0};let i=0;for(let r=n;r<s;r++){const o=t[r];if(i+o.length>=e||r===s-1)return f1(o,e-i);i+=o.length}return{x:0,y:0,angle:0}}function Kh(t,e){const{segments:n,totalLength:s}=gn(t);return ia(n,Math.max(0,Math.min(1,e))*s)}function g1(){jn.clear()}function p1(t){return gn(t).totalLength}const m1=24,y1=320,b1=2.5,qs=72,w1=64,k1=.2,v1=128,js=new Map;let er=0,qe;const Xh=t=>Math.round(t*100)/100;function Gh(t,e){const{segments:n,subpaths:s,totalLength:i}=gn(t);if(n.length===0)return[];if(e){const r=s.every(o=>o.closed);return[{segments:n,start:0,end:n.length,length:i,closed:r}]}return s.filter(r=>r.length>0).map(r=>({segments:n,start:r.start,end:r.end,length:r.length,closed:r.closed}))}function ra(t,e){const n=t.closed?(e%1+1)%1:Math.max(0,Math.min(1,e)),s=ia(t.segments,n*t.length,t.start,t.end);return[s.x,s.y]}function Uh(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 Vh(t,e){const n=[];for(let s=0;s<e;s++)n.push(ra(t,t.closed?s/e:s/(e-1)));return n}function Jh(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 M1(t,e,n){const s=t.closed&&e.closed;if(n!==void 0)return{offset:s?Math.abs(n)%qs/qs:0,reversed:n<0};const i=Jh(Vh(t,qs)),r=Jh(Vh(e,qs)),o=qs;let a={offset:0,reversed:!1},l=1/0;for(const c of[!1,!0]){const h=s?o:1;for(let u=0;u<h;u++){let d=0;for(let f=0;f<o&&d<l;f++){const p=s?c?(u-f+o)%o:(f+u)%o:c?o-1-f:f,g=i[f][0]-r[p][0],m=i[f][1]-r[p][1];d+=g*g+m*m}d<l&&(l=d,a={offset:s?u/o:0,reversed:c})}}return a}function S1(t,e,n){return n?((e.reversed?e.offset-t:t+e.offset)%1+1)%1:e.reversed?1-t:t}function x1(t,e,n){return n?((e.reversed?e.offset-t:t-e.offset)%1+1)%1:e.reversed?1-t:t}function T1(t,e,n){const s=t.closed&&e.closed,i=M1(t,e,n.shapeIndex),r=Math.max(m1,Math.min(y1,Math.ceil(Math.max(t.length,e.length)/b1))),o=new Set,a=u=>o.add(Math.round(u*1e7)/1e7);for(let u=0;u<=r;u++)a(u/r);for(const u of Uh(t))a(u);for(const u of Uh(e))a(x1(u,i,s));let l=[...o].sort((u,d)=>u-d);s&&(l=l.filter(u=>u<1));const c=[],h=[];for(const u of l)c.push(...ra(t,u)),h.push(...ra(e,S1(u,i,s)));return E1({from:c,to:h,closed:s})}function E1(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[o,a]=s.pop();let l=-1,c=k1;for(let h=o+1;h<a;h++){const u=Math.max(Zh(t.from,o,a,h),Zh(t.to,o,a,h));u>c&&(c=u,l=h)}l!==-1&&(n[l]=1,s.push([o,l],[l,a]))}const i=[],r=[];for(let o=0;o<e;o++)n[o]&&(i.push(t.from[o*2],t.from[o*2+1]),r.push(t.to[o*2],t.to[o*2+1]));return{from:i,to:r,closed:t.closed}}function Zh(t,e,n,s){const i=t[e*2],r=t[e*2+1],o=t[n*2]-i,a=t[n*2+1]-r,l=t[s*2]-i,c=t[s*2+1]-r,h=o*o+a*a,u=h===0?0:Math.max(0,Math.min(1,(l*o+c*a)/h));return Math.hypot(l-u*o,c-u*a)}function A1(t,e,n){const s=n.shapeIndex;if(qe&&qe.from===t&&qe.to===e&&qe.shapeIndex===s)return qe.plan;const r=js.get(String(s??"auto"))?.get(t)?.get(e);if(r)return qe={from:t,to:e,shapeIndex:s,plan:r},r;const o=gn(t).subpaths.filter(f=>f.length>0).length===gn(e).subpaths.filter(f=>f.length>0).length,a=Gh(t,!o),l=Gh(e,!o),c={pairs:a.map((f,p)=>T1(f,l[p],n))};er>=v1&&(js.clear(),er=0);const h=String(s??"auto"),u=js.get(h)??new Map;js.set(h,u);const d=u.get(t)??new Map;return u.set(t,d),d.set(e,c),er++,qe={from:t,to:e,shapeIndex:s,plan:c},c}function Qh(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 r=A1(t,e,s);if(r.pairs.length===0)return i<.5?t:e;let o="";for(const a of r.pairs){for(let l=0;l<a.from.length;l+=2){const c=Xh(a.from[l]+(a.to[l]-a.from[l])*i),h=Xh(a.from[l+1]+(a.to[l+1]-a.from[l+1])*i);o+=`${l===0?o?" M":"M":" L"}${c} ${h}`}a.closed&&(o+=" Z")}return o}function $1(){js.clear(),er=0,qe=void 0}function Yn(t){return/^\s*[Mm]\s*[-+]?(?:\d|\.\d)/.test(t)}const Kn=Math.PI/180,P1=.9995;function oa(){return[0,0,0,1]}function Vt(t,e){const n=Math.hypot(t[0],t[1],t[2]);if(n===0)return oa();const s=e*Kn/2,i=Math.sin(s)/n;return[t[0]*i,t[1]*i,t[2]*i,Math.cos(s)]}function I1(t,e,n){return aa(aa(Vt([0,1,0],e),Vt([1,0,0],t)),Vt([0,0,1],n))}function O1(t){const[e,n,s,i]=je(t),r=2*(e*s+n*i),o=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/Kn,Math.atan2(r,u)/Kn,Math.atan2(o,a)/Kn]:[d/Kn,Math.atan2(-h,c)/Kn,0]}function aa(t,e){const[n,s,i,r]=t,[o,a,l,c]=e;return[r*o+n*c+s*l-i*a,r*a-n*l+s*c+i*o,r*l+n*a-s*o+i*c,r*c-n*o-s*a-i*l]}function t0(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]}function e0(t){return Math.hypot(t[0],t[1],t[2],t[3])}function je(t){const e=e0(t);return e===0?oa():[t[0]/e,t[1]/e,t[2]/e,t[3]/e]}function C1(t){return[-t[0],-t[1],-t[2],t[3]]}function n0(t,e,n){const s=je(t);let i=je(e),r=t0(s,i);if(r<0&&(i=[-i[0],-i[1],-i[2],-i[3]],r=-r),r>P1)return je([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 o=Math.acos(r),a=Math.sin(o),l=Math.sin((1-n)*o)/a,c=Math.sin(n*o)/a;return je([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 _1(t,e){const[n,s,i,r]=je(t),o=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]+r*o+(s*l-i*a),e[1]+r*a+(i*o-n*l),e[2]+r*l+(n*a-s*o)]}const H1=Object.freeze(Object.defineProperty({__proto__:null,conjugate:C1,dot:t0,fromAxisAngle:Vt,fromEuler:I1,identity:oa,length:e0,multiply:aa,normalize:je,rotateVec3:_1,slerp:n0,toEuler:O1},Symbol.toStringTag,{value:"Module"})),ke=(t,e,n)=>t+(e-t)*n,s0=512,la=new Map,ca=new Map;function i0(t){const e=la.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 la.size<s0&&la.set(t,s),s}const r0=t=>t.charCodeAt(0)===35,o0=t=>t.startsWith("rgb"),a0=t=>t.startsWith("rgba"),R1=/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/,ha=t=>Math.round(t).toString(16).padStart(2,"0");function L1(t,e,n){return`#${ha(t)}${ha(e)}${ha(n)}`}function l0(t){const e=ca.get(t);if(e)return e;const n=t.match(R1);if(!n)throw new Error(`Invalid rgb color: ${t}`);const s=parseInt(n[1],10),i=parseInt(n[2],10),r=parseInt(n[3],10),o=n[4]!==void 0?[s,i,r,parseFloat(n[4])]:[s,i,r];return ca.size<s0&&ca.set(t,o),o}const c0=(t,e,n)=>{if(r0(t)&&r0(e)){const[s,i,r]=i0(t),[o,a,l]=i0(e),c=ke(s,o,n),h=ke(i,a,n),u=ke(r,l,n);return L1(c,h,u)}if((o0(t)||a0(t))&&(o0(e)||a0(e))){const s=l0(t),i=l0(e),r=Math.round(ke(s[0],i[0],n)),o=Math.round(ke(s[1],i[1],n)),a=Math.round(ke(s[2],i[2],n));if(s.length===4||i.length===4){const l=s[3]??1,c=i[3]??1,h=ke(l,c,n);return`rgba(${r}, ${o}, ${a}, ${h})`}return`rgb(${r}, ${o}, ${a})`}return n<1?t:e},h0=(t,e,n)=>{const s=Math.min(t.length,e.length),i=[];for(let r=0;r<s;r++)i.push(ke(t[r],e[r],n));return i},u0=(t,e,n)=>n0(t,e,n),ua=(t,e,n)=>n<1?t:e,d0=(t,e,n)=>Qh(t,e,n);function Ys(t,e){return e==="slerp"?u0:typeof t=="number"?ke:Array.isArray(t)?h0:typeof t=="string"?t.startsWith("#")||t.startsWith("rgb")?c0:Yn(t)?d0:ua:ua}const da=1e3/60;function fa(t,e={}){if(!Be(t))throw new Error(`bakeSpringTrack: track "${t.id}" is not a spring track`);const n=new Ws(t.spring);return f0(t,s=>n.valueAt(s),n.settleTime(),t.spring.from,t.spring.to,e)}function ga(t,e={}){if(!De(t))throw new Error(`bakeInertiaTrack: track "${t.id}" is not an inertia track`);const n=t.inertia;return f0(t,s=>Zi(n,s),qn(n),n.from,zn(n),e)}function f0(t,e,n,s,i,r){const o=r.intervalMs??da,a=r.tolerance??.01,l=t.delay??0,c=[];for(let u=0;u<=n;u+=o)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?p0(c,a):c,...t.targets&&{targets:[...t.targets]},...t.stagger&&{stagger:{...t.stagger}}}}function pa(t,e,n,s={}){const i=s.intervalMs??da,r=typeof n=="function"?n:Wt(n),o=Ys(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:o(t.value,e.value,r(u)),easing:"linear"})}const c=r(1);return l.push({...e,...c!==1&&{value:o(t.value,e.value,c)},easing:"linear"}),l}function F1(t,e){return Be(t)?fa(t,e):De(t)?ga(t,e):t}function g0(t,e={}){const n=t.keyframes;if(!n.some(r=>Fs(r.easing)))return t;const s=n.length>0?[n[0]]:[],i={...e,interpolation:t.interpolation??e.interpolation};for(let r=1;r<n.length;r++){const o=n[r];Fs(o.easing)?s.push(...pa(n[r-1],o,o.easing,i)):s.push(o)}return{...t,keyframes:s}}function N1(t,e){return t.filter($h).map(n=>g0(n,e)).concat(t.filter(Be).map(n=>fa(n,e)),t.filter(De).map(n=>ga(n,e)))}function p0(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],r=t[s],o=t[s+1],a=o.time-i.time;if(a<=0)continue;const l=(r.time-i.time)/a,c=i.value+(o.value-i.value)*l;Math.abs(r.value-c)>e&&n.push(r)}return n.push(t[t.length-1]),n}function nr(t){const e=[...t.keyframes].sort((n,s)=>n.time-s.time);return{...t,keyframes:e}}function Ye(t){return t.targets&&t.targets.length>0?t.targets:[t.target]}function Xn(t,e,n,s){const i=n??0;return!s||e<=1?i:i+Xi(t,e,s)}class Ke{track;targets;constructor(e){this.track=e,this.targets=Ye(e)}getValueAtTime(e){return this.valueForOffset(e-Xn(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 r=Xn(i,n,this.track.delay,this.track.stagger),o=this.valueForOffset(e-r);o!==void 0&&s.push({target:this.targets[i],value:o,start:r+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?Ns(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 r=i.time-s.time,o=(e-s.time)/r,l=Wt(i.easing)(o);return Ys(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 m0{track;targets;sampler;constructor(e){this.track=e,this.targets=Ye(e),this.sampler=new Ws(e.spring)}getValueAtTime(e){return this.sampler.valueAt(e-Xn(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 r=Xn(i,n,this.track.delay,this.track.stagger);s.push({target:this.targets[i],value:this.sampler.valueAt(e-r),start:r})}return s}getDuration(){const e=this.track.stagger?Ns(this.targets.length,this.track.stagger):0;return this.sampler.settleTime()+(this.track.delay??0)+e}getTrack(){return this.track}}class y0{track;targets;duration;constructor(e){this.track=e,this.targets=Ye(e),this.duration=qn(e.inertia)}getValueAtTime(e){return Zi(this.track.inertia,e-Xn(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 r=Xn(i,n,this.track.delay,this.track.stagger);s.push({target:this.targets[i],value:Zi(this.track.inertia,e-r),start:r})}return s}getDuration(){const e=this.track.stagger?Ns(this.targets.length,this.track.stagger):0;return this.duration+(this.track.delay??0)+e}getTrack(){return this.track}}function ma(t,e){const n={...Kh(t.pathData,e)};if(t.matrix){const[s,i,r,o,a,l]=t.matrix,{x:c,y:h}=n;n.x=s*c+r*h+a,n.y=i*c+o*h+l;const u=n.angle*Math.PI/180,d=Math.cos(u),f=Math.sin(u);n.angle=Math.atan2(i*d+o*f,s*d+r*f)*180/Math.PI}return t.autoRotate&&t.rotateOffset&&(n.angle+=t.rotateOffset),n}function W1(t,e,n,s){const i=e+(n-e)*s;return ma(t,i)}const ya={upperCase:"ABCDEFGHIJKLMNOPQRSTUVWXYZ",lowerCase:"abcdefghijklmnopqrstuvwxyz",upperAndLowerCase:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",numbers:"0123456789"},D1=20;function b0(t){const e=ya[t??"upperCase"]??t??ya.upperCase,n=Array.from(e);return n.length>0?n:Array.from(ya.upperCase)}function B1(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 w0(t,e,n=0){const s=t.from??"",i=t.to,r=Math.max(0,Math.min(1,e));if(r<=0)return s;if(r>=1)return i;const o=Array.from(s),a=Array.from(i),l=t.rightToLeft??!1;if(t.mode==="type"){const v=Math.round(r*Math.max(o.length,a.length));return l?o.slice(0,Math.max(0,o.length-v)).join("")+a.slice(Math.max(0,a.length-v)).join(""):a.slice(0,v).join("")+o.slice(v).join("")}const c=Math.max(0,Math.min(.999,t.revealDelay??0)),h=Math.max(0,(r-c)/(1-c)),u=Math.floor(h*a.length),d=t.tweenLength===!1?a.length:Math.round(o.length+(a.length-o.length)*r),f=b0(t.chars),p=t.refreshRate??D1,g=p>0?Math.floor(n*p/1e3):0,m=t.seed??1;let w="";for(let v=0;v<d;v++){const k=l?v>=d-u:v<u,b=l?a[a.length-(d-v)]:a[v];k&&b!==void 0||b===" "||b===`
|
|
2
|
+
`?w+=b:w+=f[B1(m,v,g)%f.length]}return w}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 r=1e3;for(let a=0;a<r&&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 o=this.getStateAtTime(this._currentTime);this.onUpdate?.(o)}getStateAtTime(e){const n=new Map;if(e=Ph(e,this._config.drawingRate??0),this._hasSharedWrites())this._resolveShared(e,n);else for(const[s,i]of this._trackPlayers){const r=i.getTrack().property;for(const{target:o,value:a,start:l}of i.getTargetValues(e))this._write(n,s,o,r,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,r]of this._trackPlayers){const o=r.getTrack().property;for(const{target:a,value:l,start:c}of r.getTargetValues(e)){const h=`${a}\0${o}`,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:o,value:l,start:c,started:u})}}for(const{trackId:i,target:r,property:o,value:a,start:l}of s.values())this._write(n,i,r,o,a,e-l)}_write(e,n,s,i,r,o){if(r===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 r=="number"){a.set("text",w0(l.textConfig,r,Math.max(0,o)));return}const c=this._motionPathTracks.get(n);if(c&&typeof r=="number"){const h=ma(c.motionPathConfig,r);a.set("motionPathX",h.x),a.set("motionPathY",h.y),c.motionPathConfig.autoRotate&&a.set("motionPathRotate",h.angle)}else a.set(i,r)}_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 Ye(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,De(e)){this._trackPlayers.set(e.id,new y0(e));return}if(Be(e)){this._trackPlayers.set(e.id,new m0(e)),this._springTracks.set(e.id,e);return}if(Ki(e))this._trackPlayers.set(e.id,new Ke(e)),this._textTracks.set(e.id,e);else if(Vo(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 Ke(n)),this._motionPathTracks.set(e.id,e)}else this._trackPlayers.set(e.id,new Ke(e))}replaceTrack(e,n){const s=this._tracks.findIndex(r=>r.id===e);if(s<0)return;const i=this._tracks.slice(s+1);this.removeTrack(e);for(const r of i)this.removeTrack(r.id);this.addTrack(n);for(const r of i)this.addTrack(r)}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(Be(s)||De(s))return{from:i,to:n.getDuration()};const r=s.keyframes;if(!(!r||r.length===0))return{from:r[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 r=0;r<n;r++){const o=this._tracks[r];if(o.property!==s.property)continue;const a=Ye(o).filter(u=>Ye(s).includes(u));if(a.length===0)continue;const l=this.getTrackSpan(o.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?o.id:s.id,winningTrackId:h?s.id:o.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&&!Ye(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:Uo(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,r)=>i.time-r.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 z1=100;function ba(t,e,n,s){const i=[],r=[],{duration:o,alternate:a}=s,l=(f,p,g,m)=>{r.push([f,p]);const w=[];t.forEach((v,k)=>{(g==="forward"?(m?v>=f:v>f)&&v<=p:(m?v<=f:v<f)&&v>=p)&&w.push(k)}),w.sort((v,k)=>(g==="forward"?t[v]-t[k]:t[k]-t[v])||v-k);for(const v of w)i.push({kind:"event",index:v,direction:g})};let c=e.time,h=e.direction,u=e.fresh===!0;const d=Math.min(z1,Math.max(0,n.iteration-e.iteration));for(let f=0;f<d;f++){const p=h==="forward"?o:0;l(c,p,h,u),i.push({kind:"repeat"}),a?(h=h==="forward"?"reverse":"forward",c=p,u=!1):(c=h==="forward"?0:o,u=!0)}return d>0&&s.holding&&!a?{crossings:i,passes:r}:(l(c,n.time,h,u),{crossings:i,passes:r})}function k0(t){return De(t)?{id:t.id,target:t.target,property:t.property,kind:"inertia",inertia:v0(t.inertia),...ve(t)}:Be(t)?{id:t.id,target:t.target,property:t.property,kind:"spring",spring:{...t.spring},...ve(t)}:Ki(t)?{id:t.id,target:t.target,property:"text",textConfig:{...t.textConfig},keyframes:t.keyframes.map(wa),...ve(t)}:Vo(t)?{id:t.id,target:t.target,property:"motionPath",motionPathConfig:{...t.motionPathConfig},keyframes:t.keyframes.map(wa),...ve(t)}:{id:t.id,target:t.target,property:t.property,keyframes:t.keyframes.map(wa),...t.interpolation!==void 0&&{interpolation:t.interpolation},...ve(t)}}function v0(t){return{...t,...Array.isArray(t.end)&&{end:[...t.end]}}}function wa(t){return{time:t.time,value:t.value,...t.easing&&{easing:t.easing}}}function ve(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 M0(t){if(De(t)){const e=t;return{id:e.id,target:e.target,property:e.property,kind:"inertia",inertia:v0(e.inertia),...ve(e)}}if(Be(t)){const e=t;return{id:e.id,target:e.target,property:e.property,kind:"spring",spring:{...e.spring},...ve(e)}}if(Ki(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),...ve(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,...ve(e)}}return nr({id:t.id,target:t.target,property:t.property,keyframes:t.keyframes,...t.interpolation!==void 0&&{interpolation:t.interpolation},...ve(t)})}function S0(t){const e=t._config.markers;return{formatVersion:Uo(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(k0),...t.captions&&{captions:JSON.parse(JSON.stringify(t.captions))}}}function Gn(t){const e=t.formatVersion??1;if(e>Go)throw new Error(`tinyfly: this animation uses format version ${e}, but this tinyfly reads up to version ${Go}. Update tinyfly to play it.`);return new Ht({id:t.id,name:t.name,config:t.config,tracks:t.tracks.map(M0),captions:t.captions})}function q1(t){return JSON.stringify(S0(t))}function j1(t){const e=JSON.parse(t);return Gn(e)}function ne(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 Xe(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 ka(t,e,n){return e+t.next()*(n-e)}function x0(t,e,n,s){if(s<=0)return ka(t,e,n);const i=Math.floor((n-e)/s),r=Math.round(t.next()*i);return e+r*s}function Y1(t,e){if(e.length!==0)return e[Math.floor(t.next()*e.length)]}const T0=/^([+\-*/])=\s*(-?[\d.]+)$/,E0=/^random\(\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*(?:,\s*(-?[\d.]+)\s*)?\)$/i;function K1(t){return typeof t!="string"?!1:T0.test(t.trim())||E0.test(t.trim())}function va(t,e={}){if(typeof t!="string")return t;const n=t.trim(),s=T0.exec(n);if(s){const[,r,o]=s,a=e.base??0,l=Number.parseFloat(o);switch(r){case"+":return a+l;case"-":return a-l;case"*":return a*l;case"/":return l===0?a:a/l}}const i=E0.exec(n);if(i){if(!e.random)throw new Error(`resolveValue: "${n}" needs a random source — pass one via context.random`);const r=Number.parseFloat(i[1]),o=Number.parseFloat(i[2]),a=i[3]!==void 0?Number.parseFloat(i[3]):void 0;return a!==void 0?x0(e.random,r,o,a):ka(e.random,r,o)}return t}function A0(t,e=0,n){const s=[];let i=e;for(const r of t){const o=va(r,{base:i,random:n});s.push(o),typeof o=="number"&&(i=o)}return s}class X1{random;constructor(e){this.random=Xe(e)}get seed(){return this.random.seed}resolve(e,n=0){return va(e,{base:n,random:this.random})}resolveSequence(e,n=0){return A0(e,n,this.random)}}const G1=600;function $0(t){if(Array.isArray(t)){const[d,f,p,g]=t;return{fn:O0(d,f,p,g),bezier:[d,f,p,g]}}const{segments:e}=gn(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],r=i.endX-n,o=i.endY-s;if(r===0||o===0)throw new Error(`customEase: "${t}" must move along both axes`);const a=d=>(d-n)/r,l=d=>(d-s)/o;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:O0(...m),bezier:m}}const c=[],h=[],u=Math.max(8,Math.ceil(G1/e.length));for(const d of e)for(let f=c.length===0?0:1;f<=u;f++){const[p,g]=U1(d,f/u);c.push(a(p)),h.push(l(g))}return{fn:V1(c,h)}}function P0(t={}){const n=.1+Math.max(0,Math.min(1,t.strength??.7))*.7,s=[1];for(let r=n;r>.002;r*=n)s.push(2*Math.sqrt(r));const i=s.reduce((r,o)=>r+o,0);return r=>{if(r<=0)return 0;if(r>=1)return 1;let o=r*i;for(let a=0;a<s.length;a++){if(o<=s[a]){if(a===0)return(o/s[0])**2;const l=s[a]/2,c=l*l,h=o-l;return 1-(c-h*h)}o-=s[a]}return 1}}function I0(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 U1(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,r,o,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*o,l*l*l*t.startY+3*l*l*e*s+3*l*e*e*r+e*e*e*a]}function V1(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 o=s+i>>1;t[o]<=n?s=o:i=o}const r=t[i]-t[s];return r===0?e[i]:e[s]+(n-t[s])/r*(e[i]-e[s])}}function O0(t,e,n,s){const i=(o,a,l)=>3*(1-o)*(1-o)*o*a+3*(1-o)*o*o*l+o*o*o,r=(o,a,l)=>3*(1-o)*(1-o)*a+6*(1-o)*o*(l-a)+3*o*o*(1-l);return o=>{if(o<=0)return 0;if(o>=1)return 1;let a=o;for(let h=0;h<8;h++){const u=i(a,t,n)-o,d=r(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=o;for(let h=0;h<40;h++)i(a,t,n)<o?l=a:c=a,a=(l+c)/2;return i(a,e,s)}}const J1=350,Z1=300,Q1=550;function tb(t,e={}){const n=e.lead??J1,s=e.gap??Z1,i=e.tail??Q1,r=[];let o=0;return t.forEach((a,l)=>{const c=[];let h=o+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);r.push({id:a.id??`s${l}`,start:o,duration:u-o,cues:c}),o=u}),{duration:o,scenes:r,cues:r.flatMap(a=>a.cues)}}function eb(t){return t.cues.map(e=>({id:e.id,time:e.start,label:e.text}))}function nb(t,e){let n=t.scenes[0];for(const s of t.scenes)if(e>=s.start)n=s;else break;return n}const Ks=t=>6e4/t.bpm;function sr(t,e){return t.offset+e*Ks(t)}function Xs(t,e){return(e-t.offset)/Ks(t)}function sb(t,e){return sr(t,Math.round(Xs(t,e)))}function ib(t,e){return sr(t,Math.ceil(Xs(t,e)-1e-9))}function rb(t,e,n){const s=Math.max(1,Math.round(t.beatsPerBar??4)),i=[];if(!(t.bpm>0)||n<e)return i;for(let r=Math.ceil(Xs(t,e)-1e-9);;r++){const o=sr(t,r);if(o>n+1e-9)break;i.push({time:o,bar:(r%s+s)%s===0,n:r})}return i}const Un=100;function ob(t,e,n={}){const s=n.minBpm??70,i=n.maxBpm??180,r=Math.max(1,Math.round(e/Un)),o=Math.min(t.length,Math.round((n.maxSeconds??60)*e)),a=Math.floor(o/r);if(a<4)return{bpm:120,offset:0,confidence:0};const l=new Float64Array(a);for(let S=0;S<a;S++){let E=0;for(let I=S*r;I<(S+1)*r;I++)E+=t[I]*t[I];l[S]=Math.log(1e-6+E/r)}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,E)=>S+E,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 E=0;for(let I=S;I<a;I++)E+=c[I]*c[I-S];return E/(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 E=60*Un/S,I=Math.exp(-.5*(Math.log2(E/120)/.9)**2),A=f(S)*I;A>m&&(m=A,g=S)}const w=S=>{const E=Math.floor(S);return E<0||E+1>=a?0:c[E]+(c[E+1]-c[E])*(S-E)},v=(S,E)=>{let I=0;for(let A=E;A<a;A+=S)I+=w(A);return I};let k=g,b=0,T=-1/0;for(let S=g-.6;S<=g+.6+1e-9;S+=.02){if(S<1)continue;const E=Math.max(1,Math.round(S*4));for(let I=0;I<E;I++){const A=I/E*S,O=v(S,A);O>T&&(T=O,b=A,k=S)}}const $=60*Un/k,M=p>0?Math.max(0,Math.min(1,f(g)/p)):0,x=(b+.5)*1e3/Un;return{bpm:Math.round($*100)/100,offset:Math.round(x%(6e4/$)),confidence:M}}const ab=600,lb=250,C0=1;function cb(t,e){const n=e.target??"Camera",s={x:e.stage.width/2,y:e.stage.height/2},i={},r=(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}:{}})},o=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=o(d);for(const g of["x","y","scale","rotate"])r(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(C0,u.duration??ab);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>C0?"ease-in-out":void 0))}else{const{follow:d}=u,f=d.lag??lb,p=new Ht({id:"follow",tracks:[{id:"x",target:"s",property:"x",keyframes:d.x}]}),g=v=>p.getStateAtTime(v).values.get("s")?.get("x")??l.focusX,m=[u.at,...d.x.map(v=>v.time).filter(v=>v>u.at&&v<u.until),u.until];a(u.at,l);const w=v=>({focusX:g(v)+(d.lead??0),focusY:d.y??l.focusY,scale:d.scale??l.scale,rotate:l.rotate});for(const v of m){const k=d.x.find(b=>b.time===v)?.easing;a(v+f,w(v),v===u.at?"ease-in-out":k)}l=w(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=Xe(u.shake.seed??Math.round(u.at)+1),m=()=>g.next()*2-1;for(const w of["shakeX","shakeY","shakeRotate"])r(w,u.at,0);for(let w=u.at+p;w<u.at+u.duration;w+=p){const v=1-(w-u.at)/u.duration;r("shakeX",w,m()*d*v),r("shakeY",w,m()*d*v),r("shakeRotate",w,m()*f*v)}for(const w of["shakeX","shakeY","shakeRotate"])r(w,u.at+u.duration,0,"ease-out")}return Object.entries(i).map(([u,d])=>({id:`${n}-${u}`,target:n,property:u,keyframes:d}))}function _0(t,e){const n=t.toLowerCase(),s=e.toLowerCase();let i=Array.from({length:s.length+1},(r,o)=>o);for(let r=1;r<=n.length;r++){const o=[r];for(let a=1;a<=s.length;a++)o[a]=Math.min(i[a]+1,o[a-1]+1,i[a-1]+(n[r-1]===s[a-1]?0:1));i=o}return i[s.length]}function Gs(t,e){const n=t.toLowerCase(),s=e.find(o=>o.toLowerCase().includes(n)||n.includes(o.toLowerCase()));if(s&&Math.min(t.length,s.length)>=3)return s;let i,r=1/0;for(const o of e){const a=_0(t,o);a<r&&(r=a,i=o)}return i!==void 0&&r<=Math.max(2,Math.floor(t.length/3))?i:void 0}function ft(t,e,n,s){const i=typeof e=="string"?s??Gs(e,n):void 0;return`Unknown ${t} ${JSON.stringify(e)}${i?`: did you mean "${i}"?`:"."} Known: ${n.join(", ")}`}function Us(t,e){const n=e.step??33,s=e.stiffness??120,i=e.damping??9,r=e.mass??1;let o=t(e.start),a=0;const l=[{time:e.start,value:o}];let c=e.start+n;for(let h=e.start+1;h<=e.end;h++){const d=s*(t(h)-o)-i*a;a+=d/r*.001,o+=a*.001,(h>=c||h===e.end)&&(l.push({time:h,value:o}),c+=n)}return l}function pn(t,e,n=1){if(!(e>0))return 0;const s=t*n/e;return s-Math.floor(s)}function Ma(t){const e=t-Math.floor(t);return 1-Math.abs(e*2-1)}function hb(t,e){const n=Math.max(1,Math.round(e.cycles??1)),s=e.amplitude??1,i=pn(t,e.period,n)+(e.phase??0),r=i-Math.floor(i);switch(e.shape??"sine"){case"triangle":return s*(Ma(r+.25)*2-1);case"square":return r<.5?s:-s;default:return s*Math.sin(r*Math.PI*2)}}function ub(t,e){const n=Math.max(1,Math.round(e.cycles??1)),s=typeof e.easing=="function"?e.easing:Wt(e.easing??"ease-in-out"),i=pn(t,e.period,n)+(e.phase??0);return s(Ma(i))}function db(t,e){const n=H0(e.seed),s=Math.max(1,Math.round(e.cycles??1)),i=(pn(t,e.period,1)+(e.phase??0))*Math.PI*2,r=s/Math.PI;return R0([Math.cos(i)*r+7.31,Math.sin(i)*r+3.17],n,e.octaves??1)}function fb(t,e,n){const s=H0(n.seed),i=Math.max(1,Math.round(n.cycles??1)),r=Math.max(1,Math.round(n.cyclesAlong??1)),o=pn(t,n.period,1)*Math.PI*2,a=pn(e,n.periodAlong,1)*Math.PI*2,l=i/Math.PI,c=r/Math.PI;return R0([Math.cos(o)*l+5.13,Math.sin(o)*l+9.47,Math.cos(a)*c+2.71,Math.sin(a)*c+6.29],s,n.octaves??1)}const H0=t=>typeof t=="string"?ne(t):(t??0)>>>0;function R0(t,e,n){const s=Math.max(1,Math.min(6,Math.round(n)));let i=0,r=1,o=0;for(let a=0;a<s;a++){const l=2**a;i+=r*gb(t.map(c=>c*l),e+a*1013),o+=r,r*=.5}return i/o}function gb(t,e){const n=t.length,s=t.map(Math.floor),r=t.map((a,l)=>a-s[l]).map(a=>a*a*(3-2*a));let o=0;for(let a=0;a<1<<n;a++){let l=1;const c=[];for(let h=0;h<n;h++){const u=a>>h&1;l*=u?r[h]:1-r[h],c.push(s[h]+u)}l!==0&&(o+=l*pb(c,e))}return o}function pb(t,e){let n=(e^2654435769)>>>0;for(const s of t)n=Math.imul(n^(s|0),2246822507)>>>0,n=(n^n>>>13)>>>0,n=Math.imul(n,3266489909)>>>0,n=(n^n>>>16)>>>0;return n/4294967296*2-1}function mb(t,e={}){if(t.length===0)throw new Error("curve: needs at least one key");const s={id:"curve",target:"curve",property:"value",keyframes:t.map(r=>({time:r.at,value:r.value,easing:r.easing})).sort((r,o)=>r.time-o.time),interpolation:e.interpolation},i=new Ke(s);return r=>i.getValueAtTime(r)}function yb(t,e){return e*Ks({bpm:t.bpm})}function bb(t,e){const n=Math.max(1,Math.round(t/Ks(e)));return{beats:n,grid:{...e,bpm:n*6e4/t}}}function wb(t,e,n={}){const s=Math.max(1e-6,n.attack??.05),i=Math.max(1e-6,n.decay??.4),r=Xs(e,t),o=r-Math.floor(r),a=o<s?o/s:Math.max(0,1-(o-s)/i),l=n.barAccent??0;if(l<=0)return a;const c=Math.max(1,Math.round(e.beatsPerBar??4)),u=(Math.floor(r)%c+c)%c===0;return a*(u?1+l:1)/(1+l)}function kb(t,e,n={}){const s=n.fps??30,i=Math.max(1,Math.round(e/s)),r=Math.max(1,Math.ceil(t.length/i)),o=new Float32Array(r),a=Math.min(.99,Math.max(0,n.smoothing??.5));let l=0,c=0;for(let h=0;h<r;h++){let u=0;const d=h*i,f=Math.min(t.length,d+i);for(let g=d;g<f;g++)u+=t[g]*t[g];const p=f>d?Math.sqrt(u/(f-d)):0;l=p>l?p:l*a+p*(1-a),o[h]=l,c=Math.max(c,l)}if(n.normalize!==!1&&c>0)for(let h=0;h<r;h++)o[h]/=c;return o}function vb(t,e,n=30,s){if(t.length===0)return 0;const r=(s?pn(e,s)*s:e)*n/1e3,o=Math.floor(r),a=t[Math.min(t.length-1,Math.max(0,o))],l=t[Math.min(t.length-1,Math.max(0,o+1))];return a+(l-a)*(r-o)}const L0={"16:9":16/9,"2.39:1":2.39,"4:3":4/3,"1:1":1,"9:16":9/16,"4:5":4/5},Sa=t=>typeof t=="number"?t:L0[t];function Mb(t,e){const n=Sa(e),s=t.width/t.height;if(n>=s){const r=t.width/n;return{x:0,y:(t.height-r)/2,width:t.width,height:r}}const i=t.height*n;return{x:(t.width-i)/2,y:0,width:i,height:t.height}}function Sb(t,e){const n=Sa(t),s=i=>Math.max(2,Math.round(i/2)*2);return"width"in e?{width:s(e.width),height:s(e.width/n)}:{width:s(e.height*n),height:s(e.height)}}function xb(t,e={}){const n=s=>({x:t.x+t.width*(1-s)/2,y:t.y+t.height*(1-s)/2,width:t.width*s,height:t.height*s});return{action:n(e.action??.9),title:n(e.title??.8)}}const Me=t=>Math.round(t*1e3)/1e3;function F0(t,e={}){if(t.length===0)return"";const n=e.curviness??1,s=e.closed??!1,i=t.length;let r=`M${Me(t[0].x)} ${Me(t[0].y)}`;if(i===1)return r;const o=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=o(l-1),h=o(l),u=o(l+1),d=o(l+2);if(n===0){r+=` L${Me(u.x)} ${Me(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,w=u.y-(d.y-h.y)*f;r+=` C${Me(p)} ${Me(g)} ${Me(m)} ${Me(w)} ${Me(u.x)} ${Me(u.y)}`}return s?`${r} Z`:r}const Bt=(t,e=0)=>{const n=parseFloat(t??"");return Number.isFinite(n)?n:e};function Tb(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 ir(t){const e=t.attributes;switch(t.tag.toLowerCase()){case"path":return e.d??null;case"circle":case"ellipse":{const n=Bt(e.cx),s=Bt(e.cy),i=t.tag.toLowerCase()==="circle"?Bt(e.r):Bt(e.rx),r=t.tag.toLowerCase()==="circle"?Bt(e.r):Bt(e.ry);return`M${n+i} ${s} A${i} ${r} 0 1 1 ${n-i} ${s} A${i} ${r} 0 1 1 ${n+i} ${s} Z`}case"rect":{const n=Bt(e.x),s=Bt(e.y),i=Bt(e.width),r=Bt(e.height);let o=e.rx!=null?Bt(e.rx):e.ry!=null?Bt(e.ry):0,a=e.ry!=null?Bt(e.ry):o;return o=Math.min(o,i/2),a=Math.min(a,r/2),o===0||a===0?`M${n} ${s} H${n+i} V${s+r} H${n} Z`:`M${n+o} ${s} H${n+i-o} A${o} ${a} 0 0 1 ${n+i} ${s+a} V${s+r-a} A${o} ${a} 0 0 1 ${n+i-o} ${s+r} H${n+o} A${o} ${a} 0 0 1 ${n} ${s+r-a} V${s+a} A${o} ${a} 0 0 1 ${n+o} ${s} Z`}case"line":return`M${Bt(e.x1)} ${Bt(e.y1)} L${Bt(e.x2)} ${Bt(e.y2)}`;case"polyline":case"polygon":{const n=Tb(e.points);if(n.length===0)return null;const s=n.map((i,r)=>`${r===0?"M":"L"}${i.x} ${i.y}`).join(" ");return t.tag.toLowerCase()==="polygon"?`${s} Z`:s}default:return null}}function Eb(t,e,n){const s=Math.max(2,Math.round(n.samples??32)),i=Math.max(0,n.length),r=n.since!==void 0?Math.max(e-i,n.since):e-i;if(r>=e)return[];const o=n.period,a=[];for(let l=0;l<s;l++){const c=r+(e-r)*l/(s-1),h=o&&o>0&&l<s-1?(c%o+o)%o:c;a.push({at:t(h),time:c,age:i>0?(e-c)/i:0})}return a}const Ab=2.5;function N0(t){const e=[],n=[],s=t.length,i=(r,o)=>{for(let a=r+o;a>=0&&a<s;a+=o){const l=(t[a].x-t[r].x)*o,c=(t[a].y-t[r].y)*o,h=Math.hypot(l,c);if(h>1e-9)return[l/h,c/h]}return null};for(let r=0;r<s;r++){const o=t[r],a=i(r,-1),l=i(r,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(Ab,1/Math.max(p,1e-6)),m=o.width/2*g;e.push({x:o.x-d*m,y:o.y+u*m}),n.push({x:o.x+d*m,y:o.y-u*m})}return{left:e,right:n}}function W0(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,r=n.y-t[s].y,o=Math.hypot(i,r);if(o>1e-9)return{x:n.x,y:n.y,radius:n.width/2,start:Math.atan2(i/o,-r/o)}}return null}const $b={scale:1,turn:0,x:0,y:0};function Pb(t={}){return{scale:t.scale??1,turn:t.turn??0,x:t.x??0,y:t.y??0}}function D0(t,e,n){const{ax:s,ay:i}=rr(t,e);return{scale:t,turn:e,x:n.x-(s*n.x-i*n.y),y:n.y-(i*n.x+s*n.y)}}function xa(t,e){const{ax:n,ay:s}=rr(t.scale,t.turn);return{x:n*e.x-s*e.y+t.x,y:s*e.x+n*e.y+t.y}}function Ib(t,e){const n=xa(e,{x:t.x,y:t.y});return{scale:t.scale*e.scale,turn:t.turn+e.turn,x:n.x,y:n.y}}function Ob(t){if(t.scale===0)throw new Error("invertSimilarity: a scale of 0 cannot be undone");const e={scale:1/t.scale,turn:-t.turn,x:0,y:0},n=xa(e,{x:t.x,y:t.y});return{...e,x:-n.x,y:-n.y}}function B0(t){const{ax:e,ay:n}=rr(t.scale,t.turn),s=1-e,i=-n,r=s*s+i*i;return r<1e-18?null:{x:(t.x*s+t.y*i)/r,y:(t.y*s-t.x*i)/r}}function Cb(t,e){if(t.scale<=0)throw new Error("powSimilarity: the scale must be positive");const n=Math.pow(t.scale,e),s=t.turn*e,i=B0(t);return i?D0(n,s,i):{scale:n,turn:s,x:t.x*e,y:t.y*e}}function _b(t){const{ax:e,ay:n}=rr(t.scale,t.turn);return[e,n,-n,e,t.x,t.y]}const rr=(t,e)=>{const n=e*Math.PI/180;return{ax:t*Math.cos(n),ay:t*Math.sin(n)}};function or([t,e,n],s={}){const i=s.scale??1,r=s.centre??{x:0,y:0},o=Math.sqrt(3)/2;return{x:r.x+(t-e)*o*i,y:r.y+((t+e)*.5-n)*i}}const Ta=([t,e,n])=>t+e+n;function Ea(t,e={}){const[n,s,i]=t.min,[r,o,a]=t.max,l=d=>or(d,e),c=[(n+r)/2,(s+o)/2,(i+a)/2],h=Ta(c),u=[{side:"top",depth:h,tag:t.tag,points:[l([n,s,a]),l([r,s,a]),l([r,o,a]),l([n,o,a])]},{side:"left",depth:h,tag:t.tag,points:[l([n,o,i]),l([r,o,i]),l([r,o,a]),l([n,o,a])]},{side:"right",depth:h,tag:t.tag,points:[l([r,s,i]),l([r,o,i]),l([r,o,a]),l([r,s,a])]}];return t.hide?u.filter(d=>!t.hide.includes(d.side)):u}function Aa(t,e={}){return t.map(n=>({box:n,depth:Ta([(n.min[0]+n.max[0])/2,(n.min[1]+n.max[1])/2,(n.min[2]+n.max[2])/2])})).sort((n,s)=>n.depth-s.depth).flatMap(({box:n})=>Ea(n,e))}function Hb(t={}){const e=t.size??10,s=(t.thickness??2)/2,i=[{tag:0,min:[-s,-s,-s],max:[e-s,s,s]},{tag:1,min:[e-s,-s,-s],max:[e+s,e-s,s]},{tag:2,min:[e-s,e-s,-s],max:[e+s,e+s,e]}],r=t.centre??{x:0,y:0},o=or([2*e/3,e/3,e/3],{scale:t.scale}),a={centre:{x:r.x-o.x,y:r.y-o.y},scale:t.scale};return{boxes:i,faces:[...Aa(i,a),...Ea({...i[0],hide:["right"]},a)]}}function Rb(t={}){const e=Math.max(2,Math.round(t.steps??8)),n=t.tread??1.5,s=t.rise??.25,i=t.width??3,r=t.base??1.5,o=Math.max(1,Math.round(e*(n-2*s)/(n+2*s))),a=2*(e+o),l=n*(e-o)/a,c=[{dir:[1,0,0],across:[0,1,0],count:e},{dir:[0,1,0],across:[-1,0,0],count:e},{dir:[-1,0,0],across:[0,-1,0],count:o},{dir:[0,-1,0],across:[1,0,0],count:o}],h=[];let u=[0,0,0],d=0;for(const w of c){for(let v=0;v<w.count;v++){const k=d*l,b=[u[0]+w.dir[0]*v*n,u[1]+w.dir[1]*v*n,0],T=[b[0]+w.dir[0]*n+w.across[0]*i,b[1]+w.dir[1]*n+w.across[1]*i,0];h.push({tag:d,min:[Math.min(b[0],T[0]),Math.min(b[1],T[1]),0],max:[Math.max(b[0],T[0]),Math.max(b[1],T[1]),k+r]}),d++}u=[u[0]+w.dir[0]*w.count*n,u[1]+w.dir[1]*w.count*n,0]}const f=a*l,p=t.centre??{x:0,y:0},g=or([e*n/2,e*n/2,f/2+r],{scale:t.scale}),m={centre:{x:p.x-g.x,y:p.y-g.y},scale:t.scale};return{boxes:h,faces:Aa(h,m),rise:l}}function z0(t,e,n){let s=0;for(const i of t){const r=(e-i.x)**2+(n-i.y)**2;s+=r>1e-9?i.r*i.r/r:1e9}return s}function Lb(t,e={}){if(t.length===0)return[];const n=e.threshold??1,s=Math.max(.5,e.cell??4),i=Math.sqrt(1/n)*1.6,r=e.bounds??{x:Math.min(...t.map(f=>f.x-f.r*i)),y:Math.min(...t.map(f=>f.y-f.r*i)),width:Math.max(...t.map(f=>f.x+f.r*i))-Math.min(...t.map(f=>f.x-f.r*i)),height:Math.max(...t.map(f=>f.y+f.r*i))-Math.min(...t.map(f=>f.y-f.r*i))},o=Math.max(2,Math.ceil(r.width/s)+1),a=Math.max(2,Math.ceil(r.height/s)+1),l=new Float64Array(o*a);for(let f=0;f<a;f++)for(let p=0;p<o;p++)l[f*o+p]=z0(t,r.x+p*s,r.y+f*s)-n;const c=(f,p)=>l[p*o+f],h=(f,p,g,m,w,v)=>{const k=g===v?.5:g/(g-v);return{x:f+(m-f)*k,y:p+(w-p)*k}},u=[];for(let f=0;f+1<a;f++)for(let p=0;p+1<o;p++){const g=r.x+p*s,m=r.y+f*s,w=g+s,v=m+s,k=[c(p,f),c(p+1,f),c(p+1,f+1),c(p,f+1)],b=(k[0]>0?1:0)|(k[1]>0?2:0)|(k[2]>0?4:0)|(k[3]>0?8:0);if(b===0||b===15)continue;const T=()=>h(g,m,k[0],w,m,k[1]),$=()=>h(w,m,k[1],w,v,k[2]),M=()=>h(g,v,k[3],w,v,k[2]),x=()=>h(g,m,k[0],g,v,k[3]),S=(k[0]+k[1]+k[2]+k[3])/4>0;switch(b){case 1:case 14:u.push([x(),T()]);break;case 2:case 13:u.push([T(),$()]);break;case 3:case 12:u.push([x(),$()]);break;case 4:case 11:u.push([$(),M()]);break;case 6:case 9:u.push([T(),M()]);break;case 7:case 8:u.push([x(),M()]);break;case 5:S?u.push([x(),M()],[T(),$()]):u.push([x(),T()],[$(),M()]);break;case 10:S?u.push([x(),T()],[$(),M()]):u.push([x(),M()],[T(),$()]);break}}const d=Fb(u);return e.smooth===!1?d:d.map(f=>q0(q0(f)))}function Fb(t){const e=r=>`${Math.round(r.x*1e3)},${Math.round(r.y*1e3)}`,n=new Map;t.forEach(([r,o],a)=>{for(const l of[r,o]){const c=e(l);n.has(c)||n.set(c,[]),n.get(c).push(a)}});const s=new Array(t.length).fill(!1),i=[];for(let r=0;r<t.length;r++){if(s[r])continue;s[r]=!0;const o=[t[r][0],t[r][1]];let a=t[r][1];for(;;){const l=(n.get(e(a))??[]).find(u=>!s[u]);if(l===void 0)break;s[l]=!0;const[c,h]=t[l];if(a=e(c)===e(a)?h:c,e(a)===e(o[0]))break;o.push(a)}o.length>=3&&i.push(o)}return i}function q0(t){const e=[];for(let n=0;n<t.length;n++){const s=t[n],i=t[(n+1)%t.length];e.push({x:s.x*.75+i.x*.25,y:s.y*.75+i.y*.25},{x:s.x*.25+i.x*.75,y:s.y*.25+i.y*.75})}return e}function Nb(t){const e=Math.min(1,Math.max(0,t.progress));if(e<=0)return[];const n=t.width/2,s=n*(.55+.75*e),i=Math.max(t.length*e,s*1.2),r=t.x,o=t.y+i-s,a=Math.max(.1,n*(.35-.3*e)),l=o-Math.sqrt(Math.max(0,s*s-a*a)),c=Math.max(0,l-t.y),h=8,u=[],d=[];for(let v=0;v<=h;v++){const k=v/h,b=a+(n-a)*Math.pow(1-k,1.6+1.4*e);u.push({x:r-b,y:t.y+c*k}),d.push({x:r+b,y:t.y+c*k})}const f=Math.max(8,Math.round(t.segments??12)),p=Math.acos(Math.min(1,a/s)),g=-p,m=Math.PI+p,w=[];for(let v=1;v<f;v++){const k=g+(m-g)*v/f;w.push({x:r+Math.cos(k)*s,y:o+Math.sin(k)*s})}return[...d,...w,...u.reverse()]}function Wb(t){const e=Math.min(1,Math.max(0,t.grow??1)),n=e>=1?1:1-Math.pow(1-e,3)+.08*Math.sin(e*Math.PI)*e,s=t.r*Math.max(0,n);if(s<=0)return[];const i=Math.max(12,Math.round(t.segments??48)),r=t.wobble??.05,o=t.time??0,a=t.period?o/t.period:o/2500,l=(a-Math.floor(a))*Math.PI*2,c=t.seed??0,h=[];for(let u=0;u<i;u++){const d=u/i*Math.PI*2,f=1+r*(Math.sin(2*d+l+c)*.6+Math.sin(3*d-2*l+c*1.7)*.4);h.push({x:t.x+Math.cos(d)*s*f,y:t.y+Math.sin(d)*s*f})}return h}function Db(t){const e=t.progress;if(e<=0||e>=1)return[];const n=Math.max(3,Math.round(t.pieces??8)),s=[],i=t.r*(1+1.2*e),r=Math.PI*2/n*.6*(1-e);for(let o=0;o<n;o++){const a=o/n*Math.PI*2+.3,l=[];for(let c=0;c<=4;c++){const h=a-r/2+r*c/4;l.push({x:t.x+Math.cos(h)*i,y:t.y+Math.sin(h)*i})}s.push(l)}return s}function Bb(t,e={}){const n=Math.max(.05,1+t);return{sx:e.keep==="volume"?1/Math.sqrt(n):1/n,sy:n}}function zb(t,e,n={x:0,y:0}){return t.map(s=>({x:n.x+(s.x-n.x)*e.sx,y:n.y+(s.y-n.y)*e.sy}))}function Vs(t,e){return[t[0]+e[0],t[1]+e[1],t[2]+e[2]]}function se(t,e){return[t[0]-e[0],t[1]-e[1],t[2]-e[2]]}function mn(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function $e(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function Js(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 ar(t){return Math.hypot(t[0],t[1],t[2])}function Zs(t,e){return ar(se(t,e))}function Jt(t){const e=ar(t);return e===0?[0,0,0]:mn(t,1/e)}function yn(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 qb=Object.freeze(Object.defineProperty({__proto__:null,add:Vs,cross:Js,distance:Zs,dot:$e,length:ar,lerp:yn,normalize:Jt,scale:mn,subtract:se},Symbol.toStringTag,{value:"Module"})),jb=Math.PI/180;function lr(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function Rt(t,e){const n=new Array(16);for(let s=0;s<4;s++)for(let i=0;i<4;i++){let r=0;for(let o=0;o<4;o++)r+=t[o*4+i]*e[s*4+o];n[s*4+i]=r}return n}function bn(t){return[1,0,0,0,0,1,0,0,0,0,1,0,t[0],t[1],t[2],1]}function wn(t){return[t[0],0,0,0,0,t[1],0,0,0,0,t[2],0,0,0,0,1]}function me(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 $a(t,e,n){const s=me(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 Yb(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 Pa(t){const[e,n,s,i,r,o,a,l,c,h,u,d,f,p,g,m]=t,w=e*o-n*r,v=e*a-s*r,k=e*l-i*r,b=n*a-s*o,T=n*l-i*o,$=s*l-i*a,M=c*p-h*f,x=c*g-u*f,S=c*m-d*f,E=h*g-u*p,I=h*m-d*p,A=u*m-d*g,O=w*A-v*I+k*E+b*S-T*x+$*M;if(Math.abs(O)<1e-12)return null;const H=1/O;return[(o*A-a*I+l*E)*H,(s*I-n*A-i*E)*H,(p*$-g*T+m*b)*H,(u*T-h*$-d*b)*H,(a*S-r*A-l*x)*H,(e*A-s*S+i*x)*H,(g*k-f*$-m*v)*H,(c*$-u*k+d*v)*H,(r*I-o*S+l*M)*H,(n*S-e*I-i*M)*H,(f*T-p*k+m*w)*H,(h*k-c*T-d*w)*H,(o*x-r*E-a*M)*H,(e*E-n*x+s*M)*H,(p*v-f*b-g*w)*H,(c*b-h*v+u*w)*H]}function Kb(t,e,n,s){const i=1/Math.tan(t*jb/2),r=1/(n-s);return[i/e,0,0,0,0,i,0,0,0,0,(s+n)*r,-1,0,0,2*s*n*r,0]}function Xb(t,e,n,s,i,r){const o=1/(e-t),a=1/(s-n),l=1/(r-i);return[2*o,0,0,0,0,2*a,0,0,0,0,-2*l,0,-(e+t)*o,-(s+n)*a,-(r+i)*l,1]}function Gb(t,e,n=[0,1,0]){const s=Jt(se(t,e)),i=Jt(Js(n,s)),r=Js(s,i);return[i[0],r[0],s[0],0,i[1],r[1],s[1],0,i[2],r[2],s[2],0,-$e(i,t),-$e(r,t),-$e(s,t),1]}function ie(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],r=t[3]*e[0]+t[7]*e[1]+t[11]*e[2]+t[15];return r===1||r===0?[n,s,i]:[n/r,s/r,i/r]}const Ub=Object.freeze(Object.defineProperty({__proto__:null,compose:$a,fromQuat:me,identity:lr,invert:Pa,lookAt:Gb,multiply:Rt,orthographic:Xb,perspective:Kb,scaling:wn,transformPoint:ie,translation:bn,transpose:Yb},Symbol.toStringTag,{value:"Module"})),cr={"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]},j0={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 Vb(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}Wt({type:"bounce",mode:"in"}),Wt({type:"bounce",mode:"in-out"});function Qs(t){const e=Y0.get(t.trim().toLowerCase());if(e)return e;const n=Vb(t),s=/^steps\(\s*(\d+)\s*\)$/.exec(n);if(s){const o={type:"steps",count:Math.max(1,Number.parseInt(s[1],10))+1,position:"none"};return{easing:o,fn:Wt(o)}}const i=/^(elastic|bounce|back)\.(in|out|inout)(?:\(([^)]*)\))?$/.exec(n);if(i){const[,r,o,a]=i,l=(a??"").split(",").map(u=>Number.parseFloat(u)).filter(u=>Number.isFinite(u)),c=o==="inout"?"in-out":o;if(r==="back"&&l.length===0&&n in cr)return{easing:{type:"cubic-bezier",points:cr[n]}};const h=r==="elastic"?{type:"elastic",mode:c,...l[0]!==void 0&&{amplitude:l[0]},...l[1]!==void 0&&{period:l[1]}}:r==="bounce"?{type:"bounce",mode:c}:{type:"back",mode:c,...l[0]!==void 0&&{overshoot:l[0]}};return{easing:h,fn:Wt(h)}}return n in j0?{easing:j0[n]}:n in cr?{easing:{type:"cubic-bezier",points:cr[n]}}:{easing:"ease-out"}}const Y0=new Map;function Ia(t,e){return Y0.set(t.trim().toLowerCase(),e.bezier?{easing:{type:"cubic-bezier",points:e.bezier},fn:e.fn}:{fn:e.fn,requiresBaking:"custom"}),t}function Oa(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 K0=/^\s*random\(\s*(\[.*\]|[^)]*)\s*\)\s*$/;function X0(t){return typeof t=="string"&&K0.test(t)}function Jb(t=1){let e=Oa(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),r=(l,c)=>{if(typeof l=="number")return l===0?c:Math.round(c/l)*l;if(Array.isArray(l))return G0(l,c,1/0);if("values"in l)return G0(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},o=(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]=Ys(l[d])(l[d],c[d],h);return u}return Ys(l)(l,c,h)}),wrap:((l,c,h)=>{if(Array.isArray(l)){const g=l,m=w=>g[(Math.round(w)%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,r),random:((l,c,h,u)=>{if(Array.isArray(l)){const f=()=>l[Math.floor(e()*l.length)];return c===!0?f:f()}const d=()=>o(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,v=Xi(f,m,{...c!==void 0?{amount:c}:{each:h??1},from:u}),k=c!==void 0?c:(h??1)*Zo(m,u),b=d&&k>0?d(v/k)*k:v;return l+b},pipe:(...l)=>c=>l.reduce((h,u)=>u(h),c),splitColor:l=>Zb(l),getUnit:l=>typeof l=="number"?"":/^-?[\d.]+(?:e[-+]?\d+)?([a-z%]*)$/i.exec(l.trim())?.[1]??"",seed:l=>{e=Oa(l)},resolveRandomString:l=>{const c=K0.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 o(h,u,Number.isFinite(d)?d:void 0)}}}function G0(t,e,n){let s=e,i=1/0;for(const r of t){const o=Math.abs(r-e);o<i&&(i=o,s=r)}return i<=n?s:e}function Zb(t){const e=t.trim(),n=/^#([0-9a-f]{3,8})$/i.exec(e)?.[1];if(n){const r=(n.length<=4?[...n].map(o=>o+o).join(""):n).match(/../g).map(o=>Number.parseInt(o,16));return r.length>=4?[r[0],r[1],r[2],Math.round(r[3]/255*1e3)/1e3]:[r[0],r[1],r[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 Qb=/^([+-])=\s*(-?[\d.]+)$/,tw=/^([<>])\s*(?:([+-])?=?\s*(-?[\d.]+))?$/;function ti(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 r=Qb.exec(i);if(r){const c=s(r[2]);return e.cursor+(r[1]==="-"?-c:c)}const o=tw.exec(i);if(o){const c=o[1]==="<"?e.previousStart:e.previousEnd;if(o[3]===void 0)return c;const h=s(o[3]);return c+(o[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 ew(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 nw(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),r=p=>({x:p%s,y:Math.floor(p/s)}),o=e.from??"start",a=Array.isArray(o)?{x:o[0]*(s-1),y:o[1]*(i-1)}:typeof o=="number"?r(Math.max(0,Math.min(t-1,o))):o==="end"?r(t-1):o==="center"||o==="edges"?{x:(s-1)/2,y:(i-1)/2}:{x:0,y:0},l=p=>{const{x:g,y:m}=r(p),w=Math.abs(g-a.x),v=Math.abs(m-a.y);return e.axis==="x"?w:e.axis==="y"?v:Math.hypot(w,v)};let c=Array.from({length:t},(p,g)=>l(g));const h=Math.max(...c);if(o==="edges"&&(c=c.map(p=>h-p)),o==="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?Qs(e.ease):void 0,f=d?d.fn??Wt(d.easing):void 0;return c.map(p=>{const g=h===0?0:p/h;return(f?f(g):g)*u})}const Ca=new Set(["duration","delay","ease","repeat","repeatDelay","yoyo","stagger","onComplete","onUpdate","onStart","onRepeat","onReverseComplete","repeatRefresh","keyframes","easeEach","scrollTo","id","immediateRender","overwrite","paused","scrollTrigger","spring"]),sw={rotation:"rotate",rotationZ:"rotate",rotationX:"rotateX",rotationY:"rotateY",transformPerspective:"perspective",perspective:"childPerspective"};function hr(t){const e={},n={};for(const[s,i]of Object.entries(t))Ca.has(s)?e[s]=i:n[sw[s]??s]=i;return{config:e,properties:n}}function ur(t,e){return t===void 0?e:t*1e3}function _a(t,e){if(t!==void 0)return typeof t=="number"?{each:t*1e3}:ew(t)?{offsets:nw(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 iw={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 U0(t){return iw[t]}function rw(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=F0(e.path,{curviness:e.curviness});else if(Yn(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 ow(t){const e=typeof t=="string"||Array.isArray(t)?{path:t}:{...t};return{...e,start:e.end??1,end:e.start??0}}function V0(t){return typeof t=="object"&&t!==null&&"shape"in t?t.shape:t}function aw(t){if(t.morphSVG===void 0)return t;const{morphSVG:e,...n}=t,s=V0(e);if(typeof s!="string"||!Yn(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 lw(t,e){if(t===!0)return[0,e];if(t===!1)return[0,0];if(typeof t=="number")return[0,J0(t,e)];const n=t.trim().split(/[\s,]+/).filter(Boolean),s=o=>{const a=Number.parseFloat(o);if(Number.isNaN(a))throw new Error(`gsap-compat: drawSVG "${t}" is not a length or percentage`);return J0(o.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]),r=s(n[1]);return i<=r?[i,r]:[r,i]}function cw(t,e){const[n,s]=lw(t,e);return{strokeDasharray:[s-n,e],strokeDashoffset:-n}}function hw(t,e){if(t.drawSVG===void 0)return t;const{drawSVG:n,...s}=t;return{...s,...cw(n,e)}}function uw(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 J0(t,e){return Math.max(0,Math.min(e,t))}function dw(t){let e=2166136261;for(let n=0;n<t.length;n++)e=Math.imul(e^t.charCodeAt(n),16777619);return e>>>0}function fw(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 r=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},...r!==void 0&&{revealDelay:Math.min(r,.999)},...i.tweenLength!==void 0&&{tweenLength:i.tweenLength},...i.rightToLeft!==void 0&&{rightToLeft:i.rightToLeft},seed:i.seed??dw(`${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 Ha(t){return Math.max(.1,t/25)}function gw(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?Ha(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(Ds(i))]:n.end!==void 0&&(i.end=Array.isArray(n.end)?[...n.end]:n.end),i}function pw(t){const e=t===!0?{}:typeof t=="string"?{preset:t}:t;if(e.preset!==void 0&&!(e.preset in Vi))throw new Error(`gsap-compat: unknown spring preset "${e.preset}" — use one of ${Object.keys(Vi).join(", ")}`);return{...e.preset?Vi[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 mw(t,e){if(t===!0||typeof t=="string")return;const n=t.velocity;return typeof n=="number"?n:n?.[e]}class kn{timeline;options;cursor=0;fallbackRandom=Oa(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,ei(n),s)}from(e,n,s){const{config:i,properties:r}=hr(ei(n)),{motionPath:o,text:a,scrambleText:l,...c}=r,h=this.targetsOf(e)[0],u={...i};for(const p of Object.keys(c))u[p]=this.resolveStart(h,p);o!==void 0&&(u.motionPath=ow(o));const d={},f=String(this.resolveStart(h,"text"));return a!==void 0&&(d.text=Ra(a),u.text=typeof a=="object"?{...a,value:f}:f),l!==void 0&&(d.text=Ra(l),u.scrambleText=typeof l=="object"?{...l,text:f}:f),this.build(e,{...c,...d},u,s)}fromTo(e,n,s,i){const{properties:r}=hr(ei(n));return this.build(e,r,ei(s),i)}set(e,n,s){return this.build(e,void 0,{...ei(n),duration:0},s)}get lastStart(){return this.previousStart}get lastEnd(){return this.previousEnd}addEvent(e){const n=Math.max(0,ti(e,this.context()));return this.previousStart=n,this.previousEnd=n,this.cursor=Math.max(this.cursor,n),n}timeOf(e){return ti(e,this.context())}addLabel(e,n){return this.labels.set(e,ti(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=ti(n,this.context());for(const r of e.timeline.tracks){if(!("keyframes"in r))continue;const o=nr({...r,id:this.nextTrackId(`nested-${r.id}`),keyframes:r.keyframes.map(a=>({...a,time:a.time+s}))});this.timeline.addTrack(o)}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:r,properties:o}=hr(s),{motionPath:a,text:l,scrambleText:c,inertia:h,...u}=o,d=this.targetsOf(e),f=ti(i,this.context()),p=ur(r.delay,0),g=ur(r.duration,500),m=_a(r.stagger,{count:d.length,columnsFromLayout:this.options.layoutColumns?()=>this.options.layoutColumns(d):void 0,random:this.options.random??this.fallbackRandom}),w=this.easingFor(r.ease),v=[],k=r.spring;let b=0,T=!1;for(const[I,A]of Object.entries(u)){const O=A;let H=n?.[I]!==void 0?n[I]:this.resolveStart(d[0],I);if(typeof H!=typeof O&&(this.warn(`no usable start value for "${I}" on "${d[0]}" — it will snap to ${String(O)}. Use fromTo() to animate it.`),H=O),k!==void 0&&(typeof H!="number"||typeof O!="number")&&this.warn(`spring works on numbers, so "${I}" on "${d[0]}" eases instead`),k!==void 0&&typeof H=="number"&&typeof O=="number"){const J={...pw(k),from:H,to:O,velocity:mw(k,I)??this.options.startVelocity?.(d[0],I)??0},tt=this.nextTrackId(`${d[0]}-${I}-spring`),V={id:tt,target:d[0],...d.length>1&&{targets:d},...m&&d.length>1&&{stagger:m},property:I,kind:"spring",spring:J,delay:f+p};this.timeline.addTrack(V),v.push(tt),b=Math.max(b,Ih(J));for(const L of d)this.lastValues.set(`${L}|${I}`,O);continue}T=!0;const W=this.keyframesFor(H,O,g,w,r.ease),j=this.nextTrackId(`${d[0]}-${I}`);this.timeline.addTrack(nr({id:j,target:d[0],...d.length>1&&{targets:d},...m&&d.length>1&&{stagger:m},property:I,delay:f+p,keyframes:W,...I==="quaternion"&&{interpolation:"slerp"}})),v.push(j);for(const J of d)this.lastValues.set(`${J}|${I}`,O)}const $=fw({text:l,scrambleText:c},d[0],g);if($){const I=n?.text??n?.scrambleText,A=I!==void 0?Ra(I):this.resolveStart(d[0],"text"),O=this.nextTrackId(`${d[0]}-text`),H={id:O,target:d[0],...d.length>1&&{targets:d},...m&&d.length>1&&{stagger:m},property:"text",textConfig:{from:typeof A=="string"?A:String(A??""),...$},delay:f+p,keyframes:this.keyframesFor(0,1,g,w,r.ease)};this.timeline.addTrack(H),v.push(O);for(const W of d)this.lastValues.set(`${W}|text`,$.to)}if(a!==void 0){const{config:I,start:A,end:O}=rw(a),H=this.nextTrackId(`${d[0]}-motionPath`),W={id:H,target:d[0],...d.length>1&&{targets:d},...m&&d.length>1&&{stagger:m},property:"motionPath",motionPathConfig:I,delay:f+p,keyframes:this.keyframesFor(A,O,g,w,r.ease)};this.timeline.addTrack(W),v.push(H)}if(h!==void 0)for(const[I,A]of Object.entries(h)){const O=this.resolveStart(d[0],I);if(typeof O!="number"){this.warn(`inertia on "${I}" needs a numeric start value; skipped`);continue}const H=gw(O,A),W=this.nextTrackId(`${d[0]}-${I}-inertia`),j={id:W,target:d[0],...d.length>1&&{targets:d},...m&&d.length>1&&{stagger:m},property:I,kind:"inertia",inertia:H,delay:f+p};this.timeline.addTrack(j),v.push(W),b=Math.max(b,qn(H));for(const J of d)this.lastValues.set(`${J}|${I}`,zn(H))}const S=((h!==void 0||k!==void 0)&&!T&&!$&&a===void 0?b:Math.max(g,b))+(m&&d.length>1?Ns(d.length,m):0),E=f+p+S;return this.previousStart=f+p,this.previousEnd=E,this.cursor=Math.max(this.cursor,E),{trackIds:v,start:f+p,end:E,kill:()=>{for(const I of v)this.timeline.removeTrack(I)}}}keyframesFor(e,n,s,i,r){const o={time:0,value:e};if(s<=0)return[{time:0,value:n}];const a=typeof r=="string"?Qs(r):void 0;if(a?.requiresBaking==="custom"||this.options.bakeEases&&Fs(i)){const c=a?.fn??Wt(i);return[o,...pa(o,{time:s,value:n},c,{intervalMs:this.options.bakeIntervalMs})]}return[o,{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 r=this.options.defaults?.[n];if(r!==void 0)return r;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 o=U0(n);return o!==void 0?(this.warn(`no start value for "${n}" on "${e}" — using the static default ${o}. GSAP would read the live DOM here; tinyfly cannot, so pass an explicit fromTo() or a defaults map.`),o):(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 Qs(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 Ra(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 yw(t){return new kn(t)}function ei(t){return uw(aw(t))}function bw(t){return!Array.isArray(t)||t.length!==4?null:`matrix3d(${me(je(t)).map(n=>Math.round(n*1e6)/1e6+0).join(", ")})`}const ww=new Set(["blur","brightness","glow","glowColor","shadowX","shadowY","shadowBlur","shadowColor"]),kw="#ffffff",vw="rgba(0, 0, 0, 0.5)";function Mw(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??kw})`),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??vw})`)}return e.length>0?e.join(" "):null}function Sw(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 xw(t){if(!("ownerSVGElement"in t))return;const e=t.style;!e||e.transformBox||(e.transformBox="fill-box",e.transformOrigin||(e.transformOrigin="50% 50%"))}const Z0=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"]),Tw=new Set(["x","y","z","rotate","rotateX","rotateY","rotateZ","scale","scaleX","scaleY","scaleZ","skewX","skewY","quaternion","motionPathX","motionPathY","motionPathRotate"]),Ew=["x","motionPathX","y","motionPathY","z","rotate","rotateZ","motionPathRotate","rotateX","rotateY","quaternion","scale","scaleX","scaleY","scaleZ","skewX","skewY"],Aw=new Set(["childPerspective","perspectiveOriginX","perspectiveOriginY"]),$w=new Set(["originX","originY"]),Pw=new Set(["clipTop","clipRight","clipBottom","clipLeft"]),Iw=new Set(["drawOn"]),Ow={fill:"backgroundColor",stroke:"borderColor",strokeWidth:"borderWidth",color:"color",backgroundColor:"backgroundColor",borderColor:"borderColor"},Q0={fill:"fill",stroke:"stroke",strokeWidth:"strokeWidth",strokeDasharray:"strokeDasharray",strokeDashoffset:"strokeDashoffset",fillOpacity:"fillOpacity",strokeOpacity:"strokeOpacity"},Cw="http://www.w3.org/2000/svg";class vn{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,r=null,o=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)&&!Iw.has(p)){if(Tw.has(p))(s??={})[p]=g;else if(Aw.has(p))typeof g=="number"&&((i??={})[p]=g);else if($w.has(p))typeof g=="number"&&((r??={})[p]=g);else if(Pw.has(p))typeof g=="number"&&((o??={})[p]=g);else if(ww.has(p))(a??={})[p]=g;else if(p!=="perspective"){if(p!=="shine")if(p==="text"&&typeof g=="string")Sw(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 Ew){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(" "),xw(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}%`)),r){const p=r.originX??50,g=r.originY??50;e.style.transformOrigin=`${p}% ${g}%`}if(o){const p=o.clipTop??0,g=o.clipRight??0,m=o.clipBottom??0,w=o.clipLeft??0;e.style.clipPath=`inset(${p}% ${g}% ${m}% ${w}%)`}if(a){const p=Mw(a);p&&(e.style.filter=p)}}buildTransformPart(e,n){if(e==="quaternion")return bw(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,r=e.style;r.color="transparent",r.backgroundImage=`linear-gradient(105deg, transparent 40%, rgba(255, 255, 255, 0.9) 50%, transparent 60%), linear-gradient(${s}, ${s})`,r.backgroundSize="250% 100%, 100% 100%",r.backgroundPosition=`${i}% 0, 0 0`,r.backgroundRepeat="no-repeat",r.webkitBackgroundClip="text",r.backgroundClip="text"}applyStyleProperty(e,n,s){let i;if(e.namespaceURI===Cw&&n in Q0){const a=Array.isArray(s)?s.join(", "):String(s);e.style[Q0[n]]=a;return}else n==="fill"&&e.dataset?.elementType==="text"?i="color":i=Ow[n]??n;let o;typeof s=="number"?Z0.has(n)||Z0.has(i)?o=`${s}px`:o=String(s):Array.isArray(s)?o=s.join(", "):o=s,e.style[i]=o}}const _w={request:t=>requestAnimationFrame(t),cancel:t=>cancelAnimationFrame(t)};class tu{adapter=new vn;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=Jb();active=new Map;applied=new Map;dirty=new Set;frameId=null;lastTimestamp=null;destroyed=!1;constructor(e={}){this.scheduler=e.scheduler??_w,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);La(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 r=i.currentTime;if(r<4)return 0;const o=i.getStateAtTime(r).values.get(e)?.get(n),a=i.getStateAtTime(r-4).values.get(e)?.get(n);if(typeof o!="number"||typeof a!="number")return;const l=(o-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[r,o]of s)i.set(r,o);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[r,o]of s)i[r]=o;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(La(e))return[e];if(!Hw(e))return[e];const n=[];for(const s of Array.from(e))n.push(...this.targetsOf(s));return n}nameFor(e){return La(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 La(t){return typeof t=="object"&&t!==null&&t.nodeType===1}function Hw(t){if(Array.isArray(t))return!0;const e=t;return typeof e.length=="number"&&typeof e.item=="function"}function dr(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 eu=t=>typeof t=="object"&&t!==null&&t.nodeType===1;function Rw(t){const e={};for(const n of Array.from(t.attributes))e[n.name]=n.value;return e}function Lw(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 Fw(t,e){const n=typeof t=="string"||Array.isArray(t)||eu(t)?{path:t}:t,{align:s,alignOrigin:i,path:r,...o}=n,a=$=>{const M=eu($)?$:e.query($);return M||e.warn(`gsap-compat: motionPath could not find "${String($)}"`),M};let l=null,c="";if(Array.isArray(r)||typeof r=="string"&&Yn(r))c=r;else{l=a(r);const $=l&&ir({tag:l.localName,attributes:Rw(l)});l&&!$&&e.warn(`gsap-compat: motionPath element <${l.localName}> has no path geometry`),c=$??""}const h={...o,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,w,v]=Lw(u),k=dr(d),[b,T]=i??[.5,.5];for(const $ of e.targets.slice(1)){const M=dr($);if(Math.abs(M.left-k.left)>.5||Math.abs(M.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,w-k.left-b*k.width,v-k.top-T*k.height],h}const nu=t=>typeof t=="object"&&t!==null&&t.nodeType===1;function su(t){const e={};for(const n of Array.from(t.attributes))e[n.name]=n.value;return e}function iu(t){if(!t)return null;const e=ir({tag:t.localName,attributes:su(t)});return e||(t.querySelector("path")?.getAttribute("d")??null)}function Nw(t,e,n){const s=V0(t);if(typeof s=="string"&&Yn(s))return s;const i=nu(s)?s:typeof s=="string"?e(s):null,r=iu(i);return r||(n(`gsap-compat: morphSVG could not find a shape for "${String(s)}"`),"")}const Ww=new Set(["cx","cy","r","rx","ry","x","y","width","height","x1","y1","x2","y2","points"]);function Dw(t,e=document){return(typeof t=="string"?Array.from(e.querySelectorAll(t)):nu(t)?[t]:Array.from(t)).map(s=>{if(s.localName==="path")return s;const i=ir({tag:s.localName,attributes:su(s)});if(!i||!s.parentNode)return s;const r=s.ownerDocument.createElementNS("http://www.w3.org/2000/svg","path");for(const o of Array.from(s.attributes))Ww.has(o.name)||r.setAttribute(o.name,o.value);return r.setAttribute("d",i),s.parentNode.replaceChild(r,s),r})}const ru=.3;class ou{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=au(),this.options.onPress?.(this.stateFrom(0,0,s))}move(e,n,s){if(!this.dragging)return;const i=e-this.lastX,r=n-this.lastY;this.lastX=e,this.lastY=n;const o=e-this.startX,a=n-this.startY,l=this.options.tolerance??3;if(!this.passedTolerance){if(Math.hypot(o,a)<l)return;this.passedTolerance=!0}this.updateVelocity(i,r),this.options.preventDefault!==!1&&s.cancelable&&s.preventDefault(),this.options.onMove?.(this.stateFrom(i,r,s))}end(e){this.dragging&&(this.dragging=!1,this.options.onRelease?.(this.stateFrom(0,0,e)))}updateVelocity(e,n){const s=au(),i=Math.max(1,s-this.lastTime);this.lastTime=s;const r=e/i*1e3,o=n/i*1e3;this.velocityX+=(r-this.velocityX)*ru,this.velocityY+=(o-this.velocityY)*ru}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 au(){return typeof performance<"u"?performance.now():Date.now()}function lu(t,e,n){let s={delta:0,line:null},i=n;for(const r of t)for(const o of e){const a=Math.abs(o-r);a<=i&&(i=a,s={delta:o-r,line:o})}return s}function cu(t,e){return e<=0?[]:t.map(n=>Math.round(n/e)*e)}class Fa{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 ou({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,r=Bw(i/s);e.pause(),e.seek(r*n)}applyConstraints(e,n){let s=e;const i=[...cu([s],this.options.snap??0),...(n==="x"?this.options.snapLinesX:this.options.snapLinesY)??[]],r=lu([s],i,this.snapThreshold());s+=r.delta,n==="x"?this.snappedX=r.line:this.snappedY=r.line;const o=this.options.bounds;if(o){const a=n==="x"?o.minX:o.minY,l=n==="x"?o.maxX:o.maxY;a!==void 0&&(s=Math.max(a,s)),l!==void 0&&(s=Math.min(l,s))}return s}}function Bw(t){return t<0?0:t>1?1:t}function zw(t){const e=new Fa(t);return e.start(),e}const qw={x:"x",y:"y","x,y":"both"},Na=t=>typeof t=="object"&&t!==null&&t.nodeType===1;function hu(t,e){const n=dr(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 uu(t){return Array.isArray(t)?[...t]:t}function jw(t,e,n,s={}){const[i]=e.resolveTargets(n),r=i?e.elementFor(i):void 0;if(!i||!r)throw new Error(`gsap-compat: live.draggable could not find ${String(n)}`);if(s.type==="rotation")return Yw(t,e,i,r,s);const o=qw[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):Na(s.bounds)?s.bounds:null,h={bounds:(!l&&s.bounds&&!Na(s.bounds)?s.bounds:void 0)??(l?hu(r,l):void 0)};let u=null;const d=()=>{u?.kill(),u=null},f=g=>{const m=s.inertia===!0?{}:s.inertia,w=m.friction??(m.resistance!==void 0?Ha(m.resistance):4),v=a(),k=h.bounds??{};let b,T;const $=m.end;if(Array.isArray($)){const x=Ds({from:v.x,velocity:o==="y"?0:g.x,friction:w}),S=Ds({from:v.y,velocity:o==="x"?0:g.y,friction:w});let E=$[0];for(const I of $)Math.hypot(I.x-x,I.y-S)<Math.hypot(E.x-x,E.y-S)&&(E=I);E&&(b=[E.x],T=[E.y])}else typeof $=="number"?(b=$,T=$):$&&(b=uu($.x),T=uu($.y));const M={};o!=="y"&&(M.x={velocity:g.x,friction:w,min:k.minX,max:k.maxX,end:b}),o!=="x"&&(M.y={velocity:g.y,friction:w,min:k.minY,max:k.maxY,end:T}),u=t.to(r,{inertia:M,onComplete:()=>s.onThrowComplete?.()})},p=new Fa({target:r,axis:o,snap:s.snap,get bounds(){return h.bounds},getPosition:a,onPress:()=>{d(),l&&(h.bounds=hu(r,l)),s.onPress?.()},onDrag:g=>{e.apply(i,o==="x"?{x:g.x}:o==="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 Yw(t,e,n,s,i){const r=typeof i.bounds=="object"&&i.bounds!==null&&!Na(i.bounds)?i.bounds:{},o=()=>{const k=e.appliedValue(n,"rotate");return typeof k=="number"?k:0},a=k=>Math.min(r.maxRotation??1/0,Math.max(r.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=o(),p=[{time:performance.now(),rotation:f}],i.onPress?.()},w=k=>{if(!c||k.pointerId!==h)return;const b=g(k);let T=b-d;T>180&&(T-=360),T<-180&&(T+=360),d=b,f+=T;let $=a(f);i.snap&&($=a(Math.round($/i.snap)*i.snap)),e.apply(n,{rotate:$});const M=performance.now();for(p.push({time:M,rotation:$});p.length>2&&M-p[0].time>100;)p.shift();const x={x:0,y:0};i.onDrag?.(x)},v=k=>{if(!c||k.pointerId!==h)return;c=!1;const b=p[0],T=p[p.length-1],$=b&&T?(T.time-b.time)/1e3:0,M=$>0?(T.rotation-b.rotation)/$:0;if(i.onRelease?.({x:M,y:0}),!i.inertia)return;const x=i.inertia===!0?{}:i.inertia,S=x.friction??(x.resistance!==void 0?Ha(x.resistance):4),E=typeof x.end=="number"||Array.isArray(x.end)?x.end:void 0;l=t.to(s,{inertia:{rotate:{velocity:M,friction:S,min:r.minRotation,max:r.maxRotation,end:Array.isArray(E)?E.filter(I=>typeof I=="number"):E}},onComplete:()=>i.onThrowComplete?.()})};return s.addEventListener("pointerdown",m),s.addEventListener("pointermove",w),s.addEventListener("pointerup",v),s.addEventListener("pointercancel",v),s.style.touchAction="none",{draggable:void 0,position:{x:0,y:0},get rotation(){return o()},destroy(){l?.kill(),s.removeEventListener("pointerdown",m),s.removeEventListener("pointermove",w),s.removeEventListener("pointerup",v),s.removeEventListener("pointercancel",v)}}}const Kw={opacity:0,scale:.6};function Xw(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 du(t){const e=dr(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 Wa(t,e){const s=t.resolveTargets(e).map(o=>t.elementFor(o)).filter(o=>!!o),i=new Map,r=new Map;for(const o of s){const a=Xw(o);i.set(o,a);const l=fu(o);a&&l!==void 0&&!r.has(l)&&r.set(l,{element:o,box:a})}return{elements:s,boxes:i,ids:r}}const Da=new WeakMap;function Ba(t,e,n,s={}){const i=s.duration??.6,r=s.ease??"power2.inOut",o=s.stagger??0,a=s.scale!==!1,l=s.enter===void 0?Kw: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=du(f);if(!p)continue;let g=n.boxes.get(f)??null,m;const w=fu(f),v=!g&&w!==void 0?n.ids.get(w):void 0;v&&v.element!==f&&(g=v.box,m=v.element);const[k]=t.resolveTargets(f);Da.get(f)?.timeline.removeTracks({target:k});const b=d*o;if(!g){if(l===!1)continue;u.fromTo(f,{x:0,y:0,scaleX:1,scaleY:1,...l},{...gu(l),x:0,y:0,scaleX:1,scaleY:1,duration:i,ease:r,delay:b},0),Da.set(f,u),d++;continue}const T=g.cx-p.cx,$=g.cy-p.cy,M=a?g.width/p.width:1,x=a?g.height/p.height:1;if(!(Math.abs(T)>.5||Math.abs($)>.5||Math.abs(M-1)>.001||Math.abs(x-1)>.001)){const I=(A,O)=>{const H=t.appliedValue(k,A);return typeof H=="number"&&Math.abs(H-O)>1e-6};(I("x",0)||I("y",0)||I("scaleX",1)||I("scaleY",1))&&u.set(f,{x:0,y:0,scaleX:1,scaleY:1},0);continue}const E=s.fade===!0&&m!==void 0;u.fromTo(f,{x:T,y:$,scaleX:M,scaleY:x,...E&&{opacity:0}},{x:0,y:0,scaleX:1,scaleY:1,...E&&{opacity:1},duration:i,ease:r,delay:b},0),E&&m&&du(m)&&u.fromTo(m,{opacity:1},{opacity:0,duration:i,ease:r,delay:b},0),Da.set(f,u),d++}return u}function fu(t){return t.dataset?.flipId}function gu(t){const e={};for(const n of Object.keys(t))e[n]=n==="opacity"||n.startsWith("scale")?1:0;return e}function Gw(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,r=t.map(g=>({element:g,html:g.innerHTML,ariaLabel:g.getAttribute("aria-label")}));let o={chars:[],words:[],lines:[],masks:[]},a,l,c=!1;const h=()=>{for(const{element:g,html:m,ariaLabel:w}of r)g.innerHTML=m,w===null?g.removeAttribute("aria-label"):g.setAttribute("aria-label",w)},u=()=>{a&&(a.revert?a.revert():a.kill?.(),a=void 0)},d=()=>{const g={chars:[],words:[],lines:[],masks:[]};for(const{element:m}of r){const w=(m.textContent??"").replace(/\s+/g," ").trim(),v=Uw(m,s.words),k=n.has("chars")?v.flatMap($=>Vw($,s.chars)):[],b=n.has("lines")?Zw(m,v,s.lines):[];if(i){!m.hasAttribute("aria-label")&&w&&m.setAttribute("aria-label",w);for(const $ of v)$.setAttribute("aria-hidden","true")}if(n.has("words"))g.words.push(...v);else for(const $ of v)$.removeAttribute("class");g.chars.push(...k),g.lines.push(...b);const T=e.mask==="lines"?b:e.mask==="words"?v:e.mask==="chars"?k:[];for(const $ of T)g.masks.push(Qw($,`${s[e.mask]}-mask`))}o=g},f={elements:t,get chars(){return o.chars},get words(){return o.words},get lines(){return o.lines},get masks(){return o.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 w=()=>{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 T of k){const $=Math.round(T.contentRect.width),M=g.get(T.target);g.set(T.target,$),M!==void 0&&M!==$&&(b=!0)}b&&w()});for(const k of t)l.observe(k)}const v=t[0]?.ownerDocument?.fonts;v&&v.status!=="loaded"&&v.ready.then(()=>w())}return f}function Uw(t,e){const n=t.ownerDocument,s=[],i=n.createTreeWalker(t,4),r=[];for(let o=i.nextNode();o;o=i.nextNode())r.push(o);for(const o of r){const a=o.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)}o.replaceWith(l)}return s}function Vw(t,e){const n=t.ownerDocument,s=Jw(t.textContent??"").map(i=>{const r=n.createElement("span");return r.className=e,r.style.display="inline-block",r.textContent=i,r});return t.replaceChildren(...s),s}function Jw(t){const e=Intl.Segmenter;return e?Array.from(new e(void 0,{granularity:"grapheme"}).segment(t),n=>n.segment):Array.from(t)}function Zw(t,e,n){const s=t.ownerDocument,i=new Map(e.map(p=>[p,p.getBoundingClientRect()])),r=[],o=p=>{for(const g of Array.from(p.childNodes))g.nodeType===3||i.has(g)||g.tagName==="BR"?r.push(g):o(g)};o(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 r){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 w=0;for(;w<d.length&&w<m.length&&d[w].original===m[w];)w++;d.length=w;let v=w===0?l:d[w-1].clone;for(const k of m.slice(w)){const b=k.cloneNode(!1);v.appendChild(b),d.push({original:k,clone:b}),v=b}v.appendChild(p)}return t.replaceChildren(...a),a}function Qw(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 pu={top:0,left:0,start:0,center:.5,centre:.5,middle:.5,bottom:1,right:1,end:1};function za(t){const e=t.trim().toLowerCase();if(e in pu)return pu[e];if(e.endsWith("%")){const n=Number.parseFloat(e.slice(0,-1));return Number.isNaN(n)?void 0:n/100}}function qa(t){if(typeof t=="number")return{elementFraction:0,viewportFraction:0,offsetPx:0,absolutePx:t};let e=0;const s=t.replace(/([+-])=\s*(-?[\d.]+)/g,(o,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?za(s[0]):void 0,r=s[1]!==void 0?za(s[1]):void 0;return{elementFraction:i??0,viewportFraction:r??0,offsetPx:e}}function Vn(t,e,n){const s=qa(n),i=s.absolutePx!==void 0?t.top+s.absolutePx:t.top+t.height*s.elementFraction,r=e*s.viewportFraction;return i-r+s.offsetPx}function t2(t,e,n,s){const i=Vn(t,e,n),o=Vn(t,e,s)-i;return o<=0?i<=0?1:0:ja(-i/o)}function ja(t){return t<0?0:t>1?1:t===0?0:t}function mu(t,e,n,s){if(n<=0)return e;const i=1-Math.exp(-(s/1e3)/n);return t+(e-t)*i}function Ya(t,e,n,s,i){const r=h=>Vn({top:t+i(h),bottom:t+i(h)+e,height:e},n,s),o=r(0),a=r(1);if(Math.sign(o)===Math.sign(a)||o===0||a===0)return o===0?0:a===0?1:Math.abs(o)<Math.abs(a)?0:1;let l=0,c=1;for(let h=0;h<40;h++){const u=(l+c)/2;Math.sign(r(u))===Math.sign(o)?l=u:c=u}return(l+c)/2}class yu{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 e2(t){const e=new yu(t);return e.start(),e}class bu{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 n2=.15;function wu(t){return typeof t=="object"&&!Array.isArray(t)?t:{snapTo:t}}function ku(t,e,n){const s=fr(t+e*n2);if(typeof n=="function")return fr(n(s));if(typeof n=="number")return n<=0?t:fr(Math.round(s/n)*n);if(n.length===0)return t;let i=n[0];for(const r of n)Math.abs(r-s)<Math.abs(i-s)&&(i=r);return fr(i)}function vu(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 Mu{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=Bs,r){if(this.cancel(),typeof requestAnimationFrame>"u"||s<=0){this.write(n),r?.();return}for(const l of this.cancelEvents)this.eventTarget?.addEventListener(l,this.onInterrupt,{passive:!0});let o=null;const a=l=>{o??=l;const c=Math.min(1,(l-o)/(s*1e3));this.write(e+(n-e)*i(c)),c<1?this.rafId=requestAnimationFrame(a):(this.rafId=null,this.detach(),r?.())};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 fr(t){return Math.max(0,Math.min(1,t))}class Su{options;scroller;nodes=[];scrollerStart;scrollerEnd;start;end;constructor(e,n,s){this.options=s===!0?{}:s,this.scroller=n;const{startColor:i="#3ecf7a",endColor:r="#ff5a5a",id:o}=this.options,a=o?`${o} `:"",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",r,!n),this.start=l("start",i,!1),this.end=l("end",r,!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 s2=120,Jn=[],Zn=new Set;let Ka=!1;const i2=()=>{Ka||Zn.size===0||(Ka=!0,queueMicrotask(()=>{Ka=!1;for(const t of Zn)t.afterRefresh()}))},xu=()=>{for(const t of Zn)t.beforeRefresh();for(const t of Jn)t.refresh();for(const t of Zn)t.afterRefresh()};let Qn={width:0,height:0};const Tu=()=>{const t=window.innerWidth,e=window.innerHeight,n=t===Qn.width&&e!==Qn.height,s=Math.abs(e-Qn.height)<Qn.height*.25,i=typeof navigator<"u"&&(navigator.maxTouchPoints??0)>0;n&&s&&i||(Qn={width:t,height:e},xu())};class ni{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 Mu(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 bu(e,{axis:this.options.horizontal?"x":"y",spacing:this.options.pinSpacing!==!1})),this.options.markers&&!this.options.horizontal&&typeof document<"u"&&(this.markers=new Su(document,this.options.scroller??null,this.options.markers)),this.scrollTarget()?.addEventListener("scroll",this.onScroll,{passive:!0}),Jn.length===0&&typeof window<"u"&&(Qn={width:window.innerWidth,height:window.innerHeight},window.addEventListener("resize",Tu,{passive:!0})),Jn.push(this),this.refresh()}stop(){this.running&&(this.running=!1,this.scrollTarget()?.removeEventListener("scroll",this.onScroll),Jn.splice(Jn.indexOf(this),1),Jn.length===0&&typeof window<"u"&&window.removeEventListener("resize",Tu),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(){xu()}static onRefresh(e){return Zn.add(e),()=>Zn.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+Vn(n,s,si(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,i2()}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?ja((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=si(this.options.end)??"bottom top",r=typeof i=="string"?i.trim().match(/^\+=\s*(-?[\d.]+)\s*(%|px)?$/):null;if(r){const o=Number.parseFloat(r[1]);return this.startPx+(r[2]==="%"?n*o/100:o)}return s+Vn(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()},s2))}fireBoundaryCallbacks(e,n){if(e===n)return;const{onEnter:s,onLeave:i,onEnterBack:r,onLeaveBack:o}=this.options;e==="before"?(s?.(),n==="after"&&i?.()):e==="after"?(r?.(),n==="before"&&o?.()):n==="after"?i?.():o?.()}scheduleSnap(){const e=this.options.snap;if(e===void 0||this.snapper.active)return;const n=wu(e),s=()=>{this.snapTimer=null;const i=this.endPx-this.startPx,r=this.scrollPosition();if(!this.running||i<=0||r<=this.startPx||r>=this.endPx)return;const o=(r-this.startPx)/i,a=this.startPx+ku(o,this.releaseVelocity/i,n.snapTo)*i;Math.abs(a-r)<1||this.snapper.animate(r,a,vu(n,a-r,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,r=this.options.scroller?this.options.scroller.clientWidth:typeof window<"u"?window.innerWidth:0,o=s.left-i-e.shiftAt(e.progress()),{start:a,end:l}=e.range(),c=f=>a+f*(l-a),h=Ya(o,s.width,r,si(this.options.start)??"left right",e.shiftAt);this.startPx=c(h);const u=si(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(Ya(o,s.width,r,u,e.shiftAt)),this.markerGeometry=null}markersFor(e){const n=(r,o)=>{const a=si(r)??o;if(typeof a=="number")return 0;if(/^\s*\+=/.test(a))return;const l=qa(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=mu(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,r=n?e.width??0:e.height,o=this.options.scroller;if(o&&typeof o.getBoundingClientRect=="function"){const a=o.getBoundingClientRect(),l=n?a.left:a.top;return{top:s-l,bottom:i-l,height:r}}return{top:s,bottom:i,height:r}}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 si(t){return typeof t=="function"?t():t}function r2(t){const e=new ni(t);return e.start(),e}const Xa=new Set,o2=16,Eu=.5,a2=2;class Ga{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),Xa.add(this),this.stopListening=ni.onRefresh({beforeRefresh:()=>this.rest(),afterRefresh:()=>this.refresh()}),this.refresh(),this}static refreshAll(){for(const e of Xa)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),Xa.delete(this),this.stopListening?.(),this.stopListening=null,this.cancelFrame(),this.journey=null,this}destroy(){this.stop();for(const e of this.effects)Ua(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),r=this.reduced?0:n.duration??Math.min(1.2,Math.max(.4,i/2500));if(r<=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:r*1e3,ease:n.ease??Bs,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(),r=this.options.scroller?.getBoundingClientRect().top??0;for(const o of n.querySelectorAll(e)){const a=Number.parseFloat(o.dataset.speed??""),l=Number.parseFloat(o.dataset.lag??""),c=o.getBoundingClientRect(),h=c.top-r+s;this.effects.push({element:o,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:o.style.getPropertyValue("translate")})}}this.current=this.target=this.clamp(this.position()),this.applyEffects(0)}rest(){for(const e of this.effects)Ua(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?o2: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)<=a2||(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 r=this.journey;r.elapsed+=n;const o=Math.min(1,r.elapsed/r.ms);this.current=r.from+(r.to-r.from)*r.ease(o),o>=1&&(this.journey=null)}else if(this.current!==this.target){const r=(this.options.smooth??.8)*1e3/3;this.current+=(this.target-this.current)*(1-Math.exp(-n/r)),Math.abs(this.target-this.current)<Eu&&(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 r=0;if(i.speed!==void 0&&(r+=(s-i.centre)*(1-i.speed)),i.lag!==void 0){const o=i.lag*1e3/3;i.lagged=e===0?s:i.lagged+(s-i.lagged)*(1-Math.exp(-e/o)),Math.abs(s-i.lagged)<Eu?i.lagged=s:n=!0,r+=s-i.lagged}Ua(i.element,r===0?i.saved:`0 ${l2(r)}px`),i.shift=r}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,r=this.effects.find(o=>o.element===s)?.shift??0;return s.getBoundingClientRect().top-i+this.position()-r}}function Ua(t,e){e?t.style.setProperty("translate",e):t.style.removeProperty("translate")}function l2(t){return Math.round(t*100)/100}function c2(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 Va(t,e,n,s,i=()=>{}){const r=f=>typeof f=="string"?t.query(f)??void 0:f,o=r(e.trigger)??s;if(!o){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&&c2(n,l[f]??"none"),e.once&&f===0&&queueMicrotask(()=>h.destroy())},d=e.containerAnimation?d2(t,e.containerAnimation,o,i):void 0;return h=new ni({trigger:o,start:e.start,end:e.end,scrub:a===!1?void 0:a,pin:e.pin===!0?!0:r(e.pin),scroller:r(e.scroller),horizontal:e.horizontal,pinSpacing:e.pinSpacing,onRefresh:e.invalidateOnRefresh&&n?.invalidate?()=>n.invalidate():void 0,snap:e.snap===void 0?void 0:h2(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 h2(t,e){const n=i=>i==="labels"?r=>u2(r,e?.labelProgresses?.()??[]):i;if(typeof t!="object"||Array.isArray(t))return n(t);const s=t.ease?Qs(t.ease):void 0;return{snapTo:n(t.snapTo),duration:t.duration,delay:t.delay,ease:s?s.fn??Wt(s.easing):void 0}}function u2(t,e){return e.reduce((n,s)=>Math.abs(s-t)<Math.abs(n-t)?s:n,e[0]??t)}function d2(t,e,n,s){const i=()=>e.timeline.getTracks({property:"x"}).map(r=>r.target).filter(r=>{const o=t.elementFor(r);return!!o&&o!==n&&o.contains(n)});return i().length===0&&s("gsap-compat: containerAnimation does not move an ancestor of the trigger along x"),{range:()=>{const r=e.scrollTrigger;return r||s("gsap-compat: containerAnimation needs its own scrollTrigger (created before this one)"),{start:r?.startOffset??0,end:r?.endOffset??0}},progress:()=>e.progress(),shiftAt:r=>{const o=e.timeline.getStateAtTime(r*e.timeline.duration);let a=0;for(const l of i()){const c=o.values.get(l)?.get("x");typeof c=="number"&&(a+=c)}return a}}}class Au{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 f2{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[r,o]of Object.entries(i)){const a=window.matchMedia(o);s.queries.set(r,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[o,a]of e.queries)n[o]=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 r=new Au(this.host,this.scope);r.conditions=n,r.add(()=>e.setup(r)),e.context=r}}class g2{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:r}=this.canvas,o=(this.options.fit??"cover")==="cover"?Math.max(i/s.naturalWidth,r/s.naturalHeight):Math.min(i/s.naturalWidth,r/s.naturalHeight),a=s.naturalWidth*o,l=s.naturalHeight*o;this.context.clearRect(0,0,i,r),this.context.drawImage(s,(i-a)/2,(r-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 r=Math.round(this.current);(Math.abs(e-r)<Math.abs(this.drawn-r)||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 p2={opacity:0,y:-16},m2={opacity:0,y:16};async function y2(t,e,n,s){const i=e.collector?.scope??e.root,r=i.ownerDocument??i,o=()=>s.shared?[...i.querySelectorAll(s.shared)]:[];if(s.native&&typeof r.startViewTransition=="function")return b2(r,s,o);const a=s.duration??.35,l=s.ease??"power2.inOut",c=m=>new Promise(w=>{m(w)||w()}),h=o(),u=h.length?Wa(e,h):void 0,d=s.from!==void 0?$u(e,s.from,s.shared):[];if(d.length&&s.leave!==!1){const m=s.leave??p2;await c(w=>t.to(d,{...m,duration:a,ease:l,onComplete:w}))}await s.update();const f=[],p=typeof s.to=="function"?s.to():s.to,g=p!==void 0?$u(e,p,s.shared):[];if(g.length&&s.enter!==!1){const m=s.enter??m2;f.push(c(w=>t.fromTo(g,m,{...gu(m),duration:a,ease:l,onComplete:w})))}if(u){const m=o().filter(w=>!h.includes(w));m.length&&f.push(c(w=>Ba(e,n,u,{targets:m,duration:a*1.4,ease:l,enter:!1,onComplete:w})))}await Promise.all(f)}function $u(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(r=>!r.matches(n)&&!r.querySelector(n))):s}async function b2(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 r=[];await t.startViewTransition(async()=>{i.forEach(a=>s(a,!1)),await e.update(),r=n(),r.forEach(a=>s(a,!0))}).finished,r.forEach(a=>s(a,!1))}const Pu={create:(t,e)=>Ia(t,$0(e))},Iu={create:(t,e)=>Ia(t,{fn:P0(e)})},Ou={create:(t,e)=>Ia(t,{fn:I0(e)})},w2=new Set(["keyframes","duration","delay","ease","easeEach","stagger","repeat","repeatDelay","yoyo","repeatRefresh","paused","id","onStart","onUpdate","onComplete","onRepeat","onReverseComplete","scrollTrigger"]),Cu=.5,k2="power1.inOut";function v2(t){return t.keyframes!==void 0&&t.keyframes!==null}function M2(t){const e=t.keyframes,n={};for(const[c,h]of Object.entries(t))w2.has(c)||(n[c]=h);if(Array.isArray(e))return e.map(c=>({...n,...c,duration:c.duration??t.duration??Cu}));const s=Object.entries(e),i=t.duration??Cu,r=e.easeEach??t.easeEach??k2;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:r,...f,duration:p*i}),u=d}return h}const o=s.filter(([c,h])=>c!=="easeEach"&&Array.isArray(h)),a=Math.max(0,...o.map(([,c])=>c.length)),l=[];for(let c=0;c<a;c++){const h={...n,ease:r,duration:i/a};for(const[u,d]of o)c<d.length&&(h[u]=d[c]);l.push(h)}return l}function _u(t,e,n,s={}){const i=e.collector?.scope??e.root,r=typeof s.scroller=="string"?i.querySelector(s.scroller):s.scroller??null,o={x:r?r.scrollLeft:window.scrollX,y:r?r.scrollTop:window.scrollY},a={x:r?r.scrollWidth-r.clientWidth:document.documentElement.scrollWidth-window.innerWidth,y:r?r.scrollHeight-r.clientHeight:document.documentElement.scrollHeight-window.innerHeight},l=(v,k)=>{if(k===void 0)return o[v];if(typeof k=="number")return k;if(k==="max")return a[v];const b=typeof k=="string"?i.querySelector(k):k;if(!b)return o[v];const T=b.getBoundingClientRect(),$=r?.getBoundingClientRect(),M=(v==="x"?s.offsetX:s.offsetY)??s.offset??0;return v==="x"?T.left-($?.left??0)+o.x-M:T.top-($?.top??0)+o.y-M},c=typeof n=="object"&&n!==null&&!("nodeType"in n)?{x:l("x",n.x),y:l("y",n.y)}:{x:o.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={...o},d=()=>{r?(r.scrollLeft=u.x,r.scrollTop=u.y):window.scrollTo({left:u.x,top:u.y,behavior:"instant"})},f=["wheel","touchstart","keydown"],p=r??window,g=()=>{w.kill(),m()},m=()=>{for(const v of f)p.removeEventListener(v,g)},w=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 v of f)p.addEventListener(v,g,{passive:!0});return w}function S2(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:r=.1,batchMax:o,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=w=>{p[w]!==void 0&&clearTimeout(p[w]),p[w]=void 0;const v=f[w].splice(0);v.length>0&&d[w]?.(v)},m=(w,v)=>{if(d[w]){if(f[w].push(v),o!==void 0&&f[w].length>=o)return g(w);p[w]===void 0&&(p[w]=setTimeout(()=>g(w),r*1e3))}};return i.map(w=>Va(t,{...u,trigger:w,onEnter:()=>m("onEnter",w),onLeave:()=>m("onLeave",w),onEnterBack:()=>m("onEnterBack",w),onLeaveBack:()=>m("onLeaveBack",w)})).filter(w=>w!==void 0)}class Se{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 kn({...s,startValue:(i,r)=>{const o=e.objectFor(i);if(o)return E2(o[r]);const a=e.appliedValue(i,r);if(a!==void 0)return a;if(r==="d")return iu(e.elementFor(i))??void 0;if(r==="text")return e.elementFor(i)?.textContent??void 0;if(r==="strokeDasharray"||r==="strokeDashoffset"){const l=Nu(e.elementFor(i));if(l!==void 0)return r==="strokeDasharray"?[l,l]:0}},startVelocity:(i,r)=>e.velocityOf(i,r),layoutColumns:i=>Fu(i.map(r=>e.elementFor(r))),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=Va(e,i,this,this.firstElement,r=>s.onWarning?.(r)))})}this.autoplayPending&&queueMicrotask(()=>{this.autoplayPending&&this.play()})}get timeline(){return this.compat.timeline}get scrollTrigger(){return this.scrollDriver}to(e,n,s){return v2(n)?this.record(()=>this.keyframed(e,n,s)):this.record(()=>this.tween(e,[n],s,([i],r,o)=>this.compat.to(r,i,o)))}from(e,n,s){return this.record(()=>this.tween(e,[n],s,([i],r,o)=>this.compat.from(r,i,o)))}fromTo(e,n,s,i){return this.record(()=>this.tween(e,[n,s],i,([r,o],a,l)=>this.compat.fromTo(a,r,o,l)))}set(e,n,s){return this.record(()=>this.tween(e,[n],s,([i],r,o)=>this.compat.set(r,i,o)))}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,r=Math.max(0,Math.min(this.timeline.duration,this.compat.timeOf(n))),o={time:i},a=s.duration??Math.abs(r-i)/1e3/(this.timeScale()||1),l=new Se(this.stage,{onStart:s.onStart,onComplete:s.onComplete});return l.to(o,{time:r,duration:a,ease:s.ease??"none",onUpdate:()=>{this.moveTo(o.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 r=this.options.yoyo===!0;n&&!r&&i.iteration>s.iteration&&(this.playhead={time:0,iteration:i.iteration,direction:"forward",fresh:!0},this.waitingToWrap=!0);const o=this.runCrossings(s,i,n);if(this.options.onUpdate?.(),this.finishedThisFrame&&!o){this.finishedThisFrame=!1;const a=e.currentTime===0&&e.direction==="reverse";!this.scrollDriver&&!r&&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:r,passes:o}=ba(i.map(a=>a.time),e,n,{duration:this.timeline.duration,alternate:this.options.yoyo===!0,holding:s});for(const a of r){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)o.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 r=this.resolve(e);if(!r)return;const{onStart:o,onUpdate:a,onComplete:l}=n[n.length-1];if(o||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(r,n,s,u),c===1/0)return;o&&this.events.push({time:c,direction:"forward",run:o}),a&&this.ranges.push({start:c,end:h,run:a}),l&&this.events.push({time:h,direction:"forward",run:l});return}this.buildTween(r,n,s,i)}keyframed(e,n,s){const i=this.resolve(e);if(!i)return;const r=M2(n);if(r.length===0)return;const o=i.length>1?_a(n.stagger,this.staggerContext(i)):void 0,a=i.map(m=>this.targetFor(m)).filter(m=>m!==void 0),l=o?a.map(m=>[m]):[a],c=o?Gi(i.length,o).map(m=>m/1e3):[0],h=this.compat.timeOf(s)/1e3+ur(n.delay,0)/1e3;let u=1/0,d=-1/0;if(l.forEach((m,w)=>{r.forEach((v,k)=>{const b=k===0?h+c[w]:">";this.tween(m,[v],b,([T],$,M)=>this.compat.to($,T,M)),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:()=>Fu(e.map(n=>this.stage.elementFor(n))),random:()=>this.stage.utils.random(0,1)}}buildTween(e,n,s,i){const r=e.map(d=>this.targetFor(d));if(!(e.length>1&&(n.some(T2)||e.some(d=>this.stage.objectFor(d)!==void 0)))){const d=this.targetFor(e[0]);i(n.map(f=>this.prepare(Lu(f,0,d,this.stage.utils,r),e)),e,s);return}const a=n.length-1,{stagger:l,...c}=n[a],h=_a(l,this.staggerContext(e)),u=h?Gi(e.length,h).map(d=>d/1e3):e.map(()=>0);e.forEach((d,f)=>{const p=f===0?ur(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)}`,v=n.map((k,b)=>b===a?{...c,delay:p}:k).map(k=>this.prepare(Lu(k,f,this.targetFor(d),this.stage.utils,r),[d]));i(v,[d],m)})}targetFor(e){return this.stage.elementFor(e)??this.stage.objectFor(e)}prepare(e,n){const s=o=>this.options.onWarning?.(o),i=o=>this.stage.query(o);let r=e;if(e.motionPath!==void 0){const o=Fw(e.motionPath,{query:i,targets:n.map(a=>this.stage.elementFor(a)).filter(a=>!!a),warn:s});r={...r,motionPath:o}}if(e.morphSVG!==void 0){const o=Nw(e.morphSVG,i,s),{morphSVG:a,...l}=r;r=o?{...r,morphSVG:o}:l}if(e.drawSVG!==void 0){const o=Nu(this.stage.elementFor(n[0]));if(o===void 0){s("gsap-compat: drawSVG needs an SVG shape with a stroke (path, line, circle…)");const{drawSVG:a,...l}=r;r=l}else r=hw(r,o)}return r}resolve(e){const n=this.stage.resolveTargets(e);if(n.length===0){this.options.onWarning?.(`gsap-compat: no elements found for target ${A2(e)}`);return}return this.firstElement??=n.map(s=>this.stage.elementFor(s)).find(s=>s!==void 0),n}}function Hu(t=new tu){const e=r=>{const{config:o}=hr(r);return new Se(t,{repeat:o.repeat,yoyo:o.yoyo,repeatDelay:o.repeatDelay,paused:o.paused,onStart:o.onStart,onUpdate:o.onUpdate,onComplete:o.onComplete,onRepeat:o.onRepeat,onReverseComplete:o.onReverseComplete,repeatRefresh:o.repeatRefresh,scrollTrigger:o.scrollTrigger})},n=r=>{const{onStart:o,onUpdate:a,onComplete:l,onRepeat:c,onReverseComplete:h,repeatRefresh:u,...d}=r;return d},s=r=>(r&&t.collector?.track(r),r),i={stage:t,ticker:t.ticker,utils:t.utils,getProperty:(r,o)=>{const[a]=t.resolveTargets(r);if(a===void 0)return;const l=t.objectFor(a);return l?l[o]:t.appliedValue(a,o)??U0(o)},scrollTrigger:r=>s(Va(t,r)),scrollBatch:(r,o)=>S2(t,r,o).map(a=>s(a)),scrollTo:(r,o)=>_u(i,t,r,o),refreshScroll:()=>{ni.refreshAll(),Ga.refreshAll()},smoothScroll:(r={})=>{const o=typeof r.scroller=="string"?(t.collector?.scope??t.root).querySelector(r.scroller):r.scroller;return s(new Ga({...r,scroller:o}).start())},context:(r,o)=>{const a=new Au(t,o);return r&&a.add(()=>r(a)),a},matchMedia:r=>new f2(t,r),customEase:Pu.create,customBounce:Iu.create,customWiggle:Ou.create,pageTransition:r=>y2(i,t,o=>new Se(t,o),r),imageSequence:(r,o)=>{const a=typeof r=="string"?(t.collector?.scope??t.root).querySelector(r):r;if(!(a instanceof HTMLCanvasElement))throw new Error(`gsap-compat: imageSequence needs a <canvas>, got ${String(r)}`);return s(new g2(a,o))},quickTo:(r,o,a={})=>{const l=new Se(t,{paused:!0}),[c]=t.resolveTargets(r);return Object.assign(u=>{if(!c)return;const d=a.spring!==void 0?t.velocityOf(c,o)??0:0;l.compat.reset(),l.compat.to(c,{[o]:u,duration:a.duration??.4,ease:a.ease??"power3.out",...a.spring!==void 0&&{spring:x2(a.spring,o,d)}}),l.timeline.stop(),l.timeline.play(),t.activate(l.timeline)},{tween:l,kill:()=>l.kill()})},timeline:r=>new Se(t,r),to:(r,o)=>{if(o.scrollTo!==void 0){const{scrollTo:a,...l}=o,c=typeof a=="object"&&a!==null&&!("nodeType"in a)?a:{},h=typeof r!="string"&&r!==window&&r.nodeType===1;return _u(i,t,a,{...l,offsetX:c.offsetX,offsetY:c.offsetY,scroller:h?r:void 0})}return e(o).to(r,n(o))},from:(r,o)=>e(o).from(r,n(o)),fromTo:(r,o,a)=>e(a).fromTo(r,o,n(a)),set:(r,o)=>e(o).set(r,n(o)),delayedCall:(r,o,a)=>new Se(t).call(o,a,r),killTweensOf:(r,o)=>{const a=t.resolveTargets(r),l=typeof o=="string"?o.split(",").map(c=>c.trim()).filter(Boolean):o;for(const c of[...t.liveTimelines])c.killTweensOf(a,l)},convertToPath:r=>Dw(r,t.root),splitText:(r,o)=>{const a=t.collector?.scope??t.root,l=typeof r=="string"?Array.from(a.querySelectorAll(r)):"nodeType"in r?[r]:Array.from(r);return s(Gw(l,o))},draggable:(r,o)=>s(jw(i,t,r,o)),getFlipState:r=>Wa(t,r),flipFrom:(r,o)=>Ba(t,a=>new Se(t,a),r,o),flip:(r,o,a)=>{const l=Wa(t,r);return o(),Ba(t,c=>new Se(t,c),l,{targets:r,...a})}};return i}const re=Hu();function x2(t,e,n){return t===!0?{velocity:{[e]:n}}:typeof t=="string"?{preset:t,velocity:{[e]:n}}:{...t,velocity:{[e]:n}}}function T2(t){return t.morphSVG!==void 0||t.drawSVG!==void 0||t.text!==void 0||t.scrambleText!==void 0||Ru(t)}function Ru(t){return Object.entries(t).some(([e,n])=>(typeof n=="function"||X0(n))&&!Ca.has(e))}function Lu(t,e,n,s,i){if(!Ru(t))return t;const r={};for(const[o,a]of Object.entries(t))Ca.has(o)?r[o]=a:typeof a=="function"?r[o]=a(e,n,i):X0(a)?r[o]=s.resolveRandomString(a):r[o]=a;return r}function Fu(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 Nu(t){const e=t;if(typeof e?.getTotalLength=="function")return e.getTotalLength()}function E2(t){if(typeof t=="number"||typeof t=="string"||Array.isArray(t)&&t.every(e=>typeof e=="number"))return t}function A2(t){return typeof t=="string"?`"${t}"`:String(t)}class Ja{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 Wu(t,e,n,s,i){const r=n-i;if(r<0){e.paused||e.pause(),e.currentTime=0;return}t.update(r,s)}class gr{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 vn}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=Gn({...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 r of e){if(s.has(r.id))throw new Error(`tinyfly: scenario id "${r.id}" is used more than once`);s.add(r.id)}const i=n.initial===void 0?e[0]:e.find(r=>r.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,r=this.currentMarker?.id;this.stopAnimationLoop(),this.stepping=!1,this.pausedByVisibility=!1,this.restoreAuthored(),this.scenarioId=e,this.useDefinition(n.timeline),this.lastMarkerId=null;let o=0;return this.reducedMotion||i?o=this.duration:r!==void 0&&(o=this.markers.find(a=>a.id===r)?.time??0),this.seek(o),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(o=>o.id===e):this.currentMarker;if(!s)return;const i=n??this.language(),r=o=>o?.[i]?.[s.id]??o?.[i.split("-")[0]]?.[s.id];return r(this.options.captions)??r(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,r=s.getAttribute("data-volume");r!==null&&(s.volume=Math.max(0,Math.min(1,Number(r)||0))),this.mediaTargets.push({el:s,startTime:i,sync:new Ja(s)})})}syncAllMedia(e,n){for(const s of this.mediaTargets)Wu(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 r=n.get(i);if(!r||!r.timeline.tracks?.length)return;const o=new vn;s.querySelectorAll("[data-tinyfly]").forEach(a=>{const l=a.getAttribute("data-tinyfly");l&&o.registerTarget(l,a)}),this.symbolInstances.push({adapter:o,timeline:Gn(r.timeline)})})}attachMedia(e,n){this.mediaSync=new Ja(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 r=this.timeline.playbackState==="playing";this.mediaSync?.update(this.timeline.currentTime,r),this.syncAllMedia(this.timeline.currentTime,r),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:r}=ba(i.map(o=>o.time),e,s,{duration:n.duration,alternate:n.config.alternate===!0,holding:n.repeatDelayRemaining>0});for(const o of r){if(o.kind!=="event")continue;const a=i[o.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 $2(t,e,n={}){const s=new gr(t,{...n,autoplay:!0});return await s.load(e),s}function P2(t,e={}){return new gr(t,e)}const Du={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"},Bu="tinyfly-controls-style",I2=`
|
|
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 O2=0;function C2(t){if(t.getElementById(Bu))return;const e=t.createElement("style");e.id=Bu,e.textContent=I2,t.head.appendChild(e)}function zu(t,e,n={}){const s=e.ownerDocument;C2(s);const i={...Du,...n.labels},r=n.speeds??[.5,1,2],o=()=>t.markers.length>0,a=()=>t.markers.some(W=>W.label!==void 0||t.caption(W.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=(W,j,J,tt="")=>{const V=s.createElement("button");return V.type="button",V.className=`tf-ctl-btn ${tt}`.trim(),V.setAttribute("aria-label",W),V.title=W,V.textContent=j,V.addEventListener("click",J),V},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 w=s.createElement("span");w.className="tf-ctl-step";const v=s.createElement("select");v.className="tf-ctl-speed",v.setAttribute("aria-label",i.speed);for(const W of r){const j=s.createElement("option");j.value=String(W),j.textContent=`${W}×`,W===1&&(j.selected=!0),v.appendChild(j)}v.addEventListener("change",()=>t.setSpeed(Number(v.value))),c.append(u,d,f,p,m,w),r.length>0&&c.append(v),l.append(c);const k=n.fullscreen?L2(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 T=s.createElement("div");T.className="tf-ctl-question",T.hidden=!0;const $=s.createElement("span"),M=h(i.reveal,i.reveal,()=>t.play(),"tf-ctl-primary");T.append($,M),l.append(T);const x=_2(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 E=()=>{const W=t.isPlaying;f.textContent=W?"❚❚":"▶",f.setAttribute("aria-label",W?i.pause:i.play),f.title=W?i.pause:i.play;const j=t.duration;s.activeElement!==m&&(m.value=String(j>0?Math.round(t.currentTime/j*1e3):0));const J=t.markers;if(d.hidden=p.hidden=w.hidden=J.length===0,J.length>0){const tt=t.currentMarker,V=tt?J.indexOf(tt)+1:0;w.textContent=i.stepFormat.replace("{index}",String(V)).replace("{total}",String(J.length)),w.setAttribute("aria-label",`${i.step} ${V} ${i.of} ${J.length}`),d.disabled=t.currentTime<=.5,p.disabled=t.currentTime>=j-.5;const L=t.caption()??"";b.textContent!==L&&(b.textContent=L),b.hidden=!a();const q=!W&&tt?.question!==void 0&&Math.abs(t.currentTime-tt.time)<1;T.hidden=!q,q&&$.textContent!==tt.question&&($.textContent=tt.question)}else T.hidden=!0,b.hidden=!0;x?.update()},I=t.subscribe(E);E();const A=n.keyboardScope??e;!A.hasAttribute("tabindex")&&A.tabIndex<0&&(A.tabIndex=0);const O=new WeakSet,H=W=>{if(O.has(W)||(O.add(W),W.defaultPrevented||W.altKey||W.ctrlKey||W.metaKey))return;const j=W.target;if(!(j.tagName==="INPUT"||j.tagName==="SELECT")&&!(W.key===" "&&j.tagName==="BUTTON"))switch(W.key){case" ":W.preventDefault(),t.isPlaying?t.pause():g();break;case"ArrowRight":if(!o())return;W.preventDefault(),t.next();break;case"ArrowLeft":if(!o())return;W.preventDefault(),t.prev();break;case"Home":W.preventDefault(),t.pause(),t.seek(0);break;case"f":case"F":if(!k)return;W.preventDefault(),k.active?k.exit():k.enter();break}};return A.addEventListener("keydown",H),l.addEventListener("keydown",H),{element:l,fullscreen:k&&{get active(){return k.active},enter:k.enter,exit:k.exit},destroy(){k?.destroy(),I(),A.removeEventListener("keydown",H),l.removeEventListener("keydown",H),l.remove()}}}function _2(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(w=>w.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 r=e.createElement("fieldset");r.className="tf-ctl-choices";const o=e.createElement("legend");o.textContent=n,r.append(o);const a=`tf-ctl-scenario-${++O2}`,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),r.append(u),d});return{element:r,update:()=>{for(const h of l){const u=h.value===t.scenario;h.checked!==u&&(h.checked=u)}}}}const H2='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/></svg>',R2='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5"/></svg>';function L2(t,e,n){const s=e,i=t,r=e.createElement("button");r.type="button",r.className="tf-ctl-btn tf-ctl-fullscreen";let o,a="";const l=()=>{const g=o!==void 0;r.innerHTML=g?R2:H2;const m=g?n.exitFullscreen:n.fullscreen;r.setAttribute("aria-label",m),r.title=m,r.setAttribute("aria-pressed",String(g)),t.classList.toggle("tf-fullscreen",g),t.classList.toggle("tf-fullscreen-overlay",o==="overlay")},c=()=>s.fullscreenElement??s.webkitFullscreenElement??null,h=()=>{c()===t?o="native":o==="native"&&(o=void 0),l()},u=g=>{g.key==="Escape"&&p()},d=()=>{o="overlay",a=e.documentElement.style.overflow,e.documentElement.style.overflow="hidden",e.addEventListener("keydown",u),l()};async function f(){if(o)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){o="native",l();return}}catch{}d()}async function p(){if(o==="overlay")e.removeEventListener("keydown",u),e.documentElement.style.overflow=a,o=void 0,l();else if(o==="native"){o=void 0,l();const g=s.exitFullscreen?.bind(s)??s.webkitExitFullscreen?.bind(s);c()===t&&g&&await g()}}return r.addEventListener("click",()=>{o?p():f()}),e.addEventListener("fullscreenchange",h),e.addEventListener("webkitfullscreenchange",h),l(),{button:r,get active(){return o!==void 0},enter:f,exit:p,destroy(){p(),e.removeEventListener("fullscreenchange",h),e.removeEventListener("webkitfullscreenchange",h),r.remove()}}}const qu="tinyfly-choices-style",F2=`
|
|
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 P2(t){if(t.getElementById(Lu))return;const e=t.createElement("style");e.id=Lu,e.textContent=$2,t.head.appendChild(e)}function Fu(t,e){const n=Array.from(e.querySelectorAll("[data-tinyfly-choose]"));if(n.length===0)return()=>{};P2(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 po=new WeakMap,Xa=new WeakMap;let I2=0;function si(t,e,n){if(t)try{return JSON.parse(t)}catch(s){console.warn(`tinyfly: invalid ${e} JSON on`,n,s);return}}async function Nu(t,e={}){const n=po.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=_2(t.getAttribute("data-markers")),a=s.length>1||i?.hasAttribute("data-scenario")?O2(s,r,t):void 0;if(a&&a.length===0)return;let l=i&&!a?si(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=Wu(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=si(t.querySelector("script[data-tinyfly-captions]")?.textContent,"captions",t),h={playWhenVisible:!0,...e.player,...c&&{captions:c},...si(t.getAttribute("data-options"),"data-options",t)};H2(t);const u=new go(t,h),d={element:t,player:u};if(po.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}),Xa.set(t,Fu(u,t))}else await u.load(l??o);if(t.getAttribute("data-controls")!=="false"){const f=si(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=Ru(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 O2(t,e,n){const s=[];return t.forEach((i,o)=>{const r=si(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?Wu(r,e):r})}),s}function Wu(t,e){return t.config.markers?.length?t:{...t,config:{...t.config,markers:e.map((n,s)=>({id:`step-${s+1}`,time:n}))}}}function _2(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 Du(t=document,e={}){const n=Array.from(t.querySelectorAll("[data-tinyfly-embed]"));return(await Promise.all(n.map(i=>Nu(i,e)))).filter(i=>i!==void 0)}function C2(t){const e=po.get(t);e&&(Xa.get(t)?.(),Xa.delete(t),e.controls?.destroy(),e.player.destroy(),po.delete(t),t.removeAttribute("data-tinyfly-mounted"))}function H2(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-${++I2}`,e.setAttribute("aria-labelledby",s.id))}function R2(){if(!(typeof document<"u"?document.currentScript:null)?.hasAttribute("data-tinyfly-auto"))return;const e=()=>{Du()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e,{once:!0}):e()}class Bu{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 kn,this.adapterB=new kn}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 kn;i.querySelectorAll("[data-tinyfly]").forEach(l=>{const c=l.getAttribute("data-tinyfly");c&&a.registerTarget(c,l)}),s.push({adapter:a,timeline:Xn(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?Xn(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 L2(t,e,n={}){const s=new Bu(t,{...n,autoplay:!0});return await s.load(e),s}const F2={type:"none",duration:0},Lt=t=>({description:t,unit:"degrees"}),At=(t,e=0,n=1)=>({description:t,unit:`${e}..${n}`,min:e,max:n}),zu={lean:Lt("Upper body tipped about the hips (+ toward the way it faces)"),bend:Lt("Line of action: the spine curved (+ curls forward, − arches back)"),headTilt:Lt("Head tilt"),leftShoulder:Lt("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:Lt("Right upper arm: 0 hangs down, 90 straight out (forward, in profile), 180 straight up"),leftElbow:Lt("Left elbow bend, added to the upper arm"),rightElbow:Lt("Right elbow bend, added to the upper arm"),leftHip:Lt("Left thigh: 0 straight down; in profile negative is forward"),rightHip:Lt("Right thigh: 0 straight down; in profile positive is forward"),leftKnee:Lt("Left knee bend (negative folds the shin back)"),rightKnee:Lt("Right knee bend (positive folds the shin back)"),leftWrist:Lt("Left wrist bend, added to the forearm"),rightWrist:Lt("Right wrist bend, added to the forearm"),leftAnkle:Lt("Left ankle: + points the toe down (tiptoe), − onto the heel"),rightAnkle:Lt("Right ankle: + points the toe down (tiptoe), − onto the heel"),leftFootOut:At("Left foot turned out (seen from the front): 0 natural, 1 sideways, negative turned in",-1,1),rightFootOut:At("Right foot turned out (seen from the front): 0 natural, 1 sideways, negative turned in",-1,1),mouth:At("Mouth open: 0 closed, 1 wide open"),smile:At("−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:At("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:At("Left eyebrow: −1 lowered, 0 rest, 1 raised",-1,1),rightBrow:At("Right eyebrow: −1 lowered, 0 rest, 1 raised",-1,1),browTilt:At("Eyebrow slant: −1 angry, 1 worried",-1,1),lookX:At("Eyes look across: + the way it faces",-1,1),lookY:At("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:At("0 front-on, 1 in profile, turned the way it faces"),sit:At("0 standing, 1 seated"),spin:Lt("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"}},qu={walk:{description:"Walk-cycle phase, in strides: animate 0 → n for n strides",unit:"strides"},walking:At("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:At("How much the mouth chatters"),rubber:At("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:At("How much of the dance is applied")},ju={"thumb.curl":At("Thumb curled in"),"thumb.across":At("Thumb across the palm"),"index.curl":At("Index finger curled"),"middle.curl":At("Middle finger curled"),"ring.curl":At("Ring finger curled"),"pinky.curl":At("Little finger curled"),spread:At("Fingers spread apart"),turn:Lt("Hand turned about the forearm"),bend:Lt("Hand bent at the wrist, palm-ward"),tilt:Lt("Hand tilted sideways"),roll:Lt("Hand rolled to show the back or the palm")};let Yu;function N2(t){Yu=t}function W2(t){return Yu?.(t)??{}}function Ku(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 Qn(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=Ku(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 mo(t,e){const n=Qn(t,e);return n[n.length-1]}function Ga(t,e){return e>0?Math.floor(Math.max(0,t)*e/1e3):0}function yo(t,e,n){const s=e.roughness??2,i=Math.max(1,Math.round(e.passes??2)),o=Ga(n,e.boil??8);let r=0;const a=()=>{const d=r++;return f=>Ye(ne(`${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,b)=>Math.hypot(m.x-d[b].x,m.y-d[b].y)),g=p.reduce((m,b)=>m+b,0)*Math.min(1,Math.max(0,f));c(m=>{const b=[],v=[];if(d.forEach((w,T)=>{b.push({x:w.x+l(m,s*.5),y:w.y+l(m,s*.5)}),T>0&&v.push([m.next()*2-1,m.next()*2-1])}),g<=0)return;t.beginPath(),t.moveTo(b[0].x,b[0].y);let k=0;for(let w=1;w<b.length;w++){const T=D2(b[w-1],b[w],s,v[w-1]),P=p[w-1];if(k+P<=g){t.bezierCurveTo(T[1].x,T[1].y,T[2].x,T[2].y,T[3].x,T[3].y),k+=P;continue}const S=B2(T,P===0?1:(g-k)/P);t.bezierCurveTo(S[1].x,S[1].y,S[2].x,S[2].y,S[3].x,S[3].y);break}t.stroke()})},u=(d,f,p,g,m=1)=>{c(b=>{const k=b.next()*Math.PI*2,w=Math.PI*2+.15+b.next()*.3,T=[];for(let S=0;S<=14;S++){const x=k+w*S/14,M=l(b,s*.6);T.push({x:d+Math.cos(x)*(p+M),y:f+Math.sin(x)*(g+M)})}const P=Qn(T,m);P.length<2||(Xu(t,P),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,b=-(g.y-p.y)/m,v=(g.x-p.x)/m;c(k=>{const w={x:l(k,s*.5),y:l(k,s*.5)},T={x:l(k,s*.5),y:l(k,s*.5)},P=l(k,s*Math.min(1.5,Math.max(.3,m/80))),S=d.map((M,E)=>{const I=E/(d.length-1),A=Math.sin(Math.PI*I)*P;return{x:M.x+w.x+(T.x-w.x)*I+b*A,y:M.y+w.y+(T.y-w.y)*I+v*A}}),x=Qn(S,f);x.length<2||(Xu(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 D2(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 B2([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 Xu(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 zt(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 bo(t,e,n,s){const i=e.length;if(i<2)return;const o=zt(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 vn(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 wo(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 ii(t,e){return e.look==="pencil"?j2(t,e):Gu(t,e.ink,e.look)}function ko(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 oi(t,e){return e.look==="silhouette"?Gu(t,e.ink,"silhouette",!1):e}function Gu(t,e,n,s=!0){const i=n==="silhouette",o=i?1.25:1;return{look:n,ink:e,limb(r,a,l){t.fillStyle=e,bo(t,r,a*o,l*o)},line(r,a){r.length<2||(t.strokeStyle=e,t.lineWidth=a*o,t.lineCap="round",t.lineJoin="round",ko(t,r),t.stroke())},shape(r,a,l){ko(t,r,!0),(a!==null||i&&s)&&(t.fillStyle=i?e:a,t.fill()),!(l<=0)&&(t.strokeStyle=e,t.lineWidth=l*o,t.lineJoin="round",t.stroke())},ellipse(r,a,l,c,h,u,d){t.beginPath(),t.ellipse(r,a,l,c,h,0,Math.PI*2),(u!==null||i&&s)&&(t.fillStyle=i?e:u,t.fill()),!(d<=0)&&(t.strokeStyle=e,t.lineWidth=d*o,t.stroke())},dot(r,a,l){t.fillStyle=e,t.beginPath(),t.arc(r,a,l*o,0,Math.PI*2),t.fill()},guide(){},guideEllipse(){}}}function z2(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 q2(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 Uu(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 j2(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=Ga(e.time,n.boil??8);let c=0;const h=(p,g,m=!1)=>Ye(ne(`${e.seed}:${m?"paper":l}:${p}:${g}`)),u=(p,g,m,b,v,k=0)=>{if(p.length<2)return;const w=p.slice(1).reduce((I,A,O)=>I+Math.hypot(A.x-p[O].x,A.y-p[O].y),0);let T=z2(p,Math.max(1.5,Math.min(e.lineWidth*.8,w/24)));if(k>0&&T.length>=2){const[I,A]=[T[T.length-2],T[T.length-1]],O=Math.hypot(A.x-I.x,A.y-I.y)||1;T=[...T,{x:A.x+(A.x-I.x)/O*k,y:A.y+(A.y-I.y)/O*k}]}const P=Uu(m),S=Uu(m),x=T.length,M=[],E=[];T.forEach((I,A)=>{const O=x===1?0:A/(x-1),H=T[Math.max(0,A-1)],W=T[Math.min(x-1,A+1)],j=Math.hypot(W.x-H.x,W.y-H.y)||1,J=-(W.y-H.y)/j,tt=(W.x-H.x)/j,V=P(O)*v,L=Math.min(1,O/.08,(1-O)/.08),q=(.55+.45*Math.sqrt(Math.max(0,L)))*(1+r*S(O)),G=Math.max(.3,g(O)*q/2),C=I.x+J*V,Y=I.y+tt*V;M.push({x:C+J*G,y:Y+tt*G}),E.push({x:C-J*G,y:Y-tt*G})}),t.save(),t.globalAlpha*=b,t.fillStyle=s,ko(t,[...M,...E.reverse()],!0),t.fill(),t.restore()},d=(p,g)=>{const m=c++,b=h(m,99,!0);if(b.next()<a){const T=(b.next()*2-1)*e.lineWidth*1.4,P=(b.next()*2-1)*e.lineWidth*1.4,S=p.map(x=>({x:x.x+T,y:x.y+P}));u(S,x=>g(x)*1.8,h(m,98,!0),.035,i),u(S,x=>g(x)*.45,h(m,97,!0),.12,i*1.5)}const v=p.slice(1).reduce((T,P,S)=>T+Math.hypot(P.x-p[S].x,P.y-p[S].y),0),k=g(.5)>4&&v>g(.5)*6,w=k?[-.3,.3,0]:[0];for(let T=0;T<o;T++){const P=T===0;w.forEach((S,x)=>{const M=h(m,T*10+x),E=S===0?p:q2(p,A=>g(A)*S*Math.sqrt(Math.sin(Math.PI*A))),I=!P&&S===0?e.lineWidth*(.3+M.next()*.8):0;u(E,A=>g(A)*(k?.5:1)*(P?1:.6),M,P?.85:.45,i*(P?.6:1),I)})}},f=(p,g,m,b,v,k)=>{const T=h(c,50).next()*Math.PI*2;d(wo(p,g,m,b,v,T,1.08,48),()=>k)};return{look:"pencil",ink:s,limb(p,g,m){d(p,b=>g+(m-g)*b)},line(p,g){d(p,()=>g)},shape(p,g,m){g!==null&&(t.save(),t.globalAlpha*=.88,t.fillStyle=g,ko(t,p,!0),t.fill(),t.restore()),m>0&&d([...p,p[0]],()=>m)},ellipse(p,g,m,b,v,k,w){k!==null&&(t.save(),t.globalAlpha*=.9,t.fillStyle=k,t.beginPath(),t.ellipse(p,g,m,b,v,0,Math.PI*2),t.fill(),t.restore()),f(p,g,m,b,v,w)},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,b,v){if(n.construction===!1)return;const k=c++,w=h(k,0),T=wo(p,g,m,b,v,w.next()*Math.PI*2,1.12,48);u(T,()=>Math.max(.6,e.lineWidth*.18),w,.28,i*1.5)}}}const Vu=["thumb","index","middle","ring","pinky"],Ot={"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 Nt(t={}){return{...Ot,...t}}const re=(t,e,n,s,i)=>({"thumb.curl":t,"index.curl":e,"middle.curl":n,"ring.curl":s,"pinky.curl":i}),St={relaxed:Ot,open:Nt({...re(0,0,0,0,0),"thumb.across":0,spread:.55}),spread:Nt({...re(0,0,0,0,0),"thumb.across":0,spread:1}),flat:Nt({...re(0,0,0,0,0),"thumb.across":.35,spread:0}),fist:Nt({...re(.7,1,1,1,1),"thumb.across":.9,spread:0}),point:Nt({...re(.75,0,1,1,1),"thumb.across":.9,spread:0}),thumbsUp:Nt({...re(0,1,1,1,1),"thumb.across":0,spread:0,roll:70}),peace:Nt({...re(.75,0,0,1,1),"thumb.across":.9,spread:1}),ok:Nt({...re(.12,.6,.1,.15,.2),"thumb.across":.55,spread:.6}),pinch:Nt({...re(.1,.65,.75,.85,.9),"thumb.across":.55,spread:0}),cupped:Nt({...re(.25,.4,.4,.4,.4),"thumb.across":.4,spread:.05,turn:2}),wave:Nt({...re(0,.05,.05,.1,.12),"thumb.across":0,spread:.7,turn:2}),pencilGrip:Nt({...re(.1,.6,.72,.88,.95),"thumb.across":.5,spread:0,turn:.8,bend:10}),hold:Nt({...re(.5,.7,.72,.74,.76),"thumb.across":.75,spread:0,turn:1})};function ts(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 Y2={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}},K2={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}},Pe={base:[-.11,.1,-.05],bones:[.2,.15,.12],widths:[.2,.145,.135],out:[-.7,.68,-.22],across:[.35,.5,-.8]},X2=[82,100,62],G2=[48,72],U2=3,V2=13,J2=.035,Z2=-.075,Q2=[[-.17,0],[-.215,.12],[-.235,.26],[-.225,.4],[-.185,.49],[-.075,.525],[.05,.51],[.16,.465],[.215,.4],[.225,.26],[.2,.1],[.16,0]],Ke=t=>t*Math.PI/180,Ua=(t,e)=>[t[0]+e[0],t[1]+e[1],t[2]+e[2]],vo=(t,e)=>[t[0]*e,t[1]*e,t[2]*e],Va=(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]],ri=t=>{const e=Math.hypot(t[0],t[1],t[2])||1;return[t[0]/e,t[1]/e,t[2]/e]};function Xe(t,e,n){const s=Math.cos(n),i=Math.sin(n),o=Va(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 Ju=[1,0,0],Zu=[0,1,0],ai=[0,0,1];function tk(t,e,n){const s=Ke(t.fan*(U2+V2*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+=Ke(X2[u]*e),r.push(Ua(r[u],vo(Xe(i,o,-a),h)))});const l=Xe(ai,o,-a),c=r.map((h,u)=>t.width*(1-.14*(u/(r.length-1))));return{joints:r,back:l,widths:c}}function ek(t,e,n=1,s=1){const i=Math.min(1,Math.max(0,e)),o=ri(Ua(vo(ri(Pe.out),1-i),vo(ri(Pe.across),i))),r=ri(Va(ai,o)),a=ri(Va(o,r)),l=[[Pe.base[0]*s,Pe.base[1],Pe.base[2]]];let c=0;Pe.bones.forEach((d,f)=>{f>0&&(c+=Ke(G2[f-1]*t)),l.push(Ua(l[f],vo(Xe(o,r,c),d)))});const h=Xe(a,r,c),u=[...Pe.widths,Pe.widths[Pe.widths.length-1]*.92].map(d=>d*n);return{joints:l,back:h,widths:u}}function Mo(t,e={}){const n={...Ot,...t},s=e.size??100,i=e.side??"right",o=i==="left"?-1:1,r=Ke(e.angle??0),a=e.fingers===4,l=Math.max(.5,e.plump??1),c=1+(l-1)*.7,h=A=>({...A,knuckle:[A.knuckle[0]*c,A.knuckle[1],A.knuckle[2]],width:A.width*l}),u=Ke(n.bend??0),d=Ke(n.tilt??0),f=Ke(90*(n.turn??0)),p=A=>Xe(Xe(Xe(A,Ju,-u),ai,-d),Zu,f),g=Math.cos(r),m=Math.sin(r),b=Ke(n.roll??0),v=Math.cos(b),k=Math.sin(b),w=A=>{const O=A[0]*s,H=-A[1]*s,W=(O*v-H*k)*o,j=O*k+H*v;return{x:W*g-j*m,y:W*m+j*g}},T=A=>{const O=w(A),H=Math.hypot(O.x,O.y);return H>1e-6*s?{x:O.x/H,y:O.y/H}:{x:0,y:0}},P={thumb:ek(n["thumb.curl"]??0,n["thumb.across"]??0,l,c)},S=a?K2:Y2;for(const A of Vu){const O=S[A];O&&(P[A]=tk(h(O),n[`${A}.curl`]??0,n.spread??0))}const x={};for(const[A,O]of Object.entries(P)){const H=O.joints.map(p),W=p(O.back);x[A]={points:H.map(w),depths:H.map(j=>j[2]*s),widths:O.widths.map(j=>j*s),nail:W[2],back:T(W)}}const M=Q2.flatMap(([A,O])=>[p([A*c,O,J2]),p([A*c,O,Z2])]),E=nk(M.map(w)),I=M.reduce((A,O)=>A+O[2],0)/M.length*s;return{size:s,side:i,wrist:{x:0,y:0},palm:E,palmDepth:I,palmFacing:-p(ai)[2],fingers:x,axes:{up:T(p(Zu)),across:T(p(Ju)),out:T(p(ai))},curls:Object.fromEntries(Object.keys(x).map(A=>[A,n[`${A}.curl`]??0]))}}function Qu(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 nk(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)]}function td(t,e,n,s){if(s.mode!=="cel"||e.length<3)return;const i=Math.hypot(...s.light),o=e.map(a=>{const l=a.x-n.x,c=a.y-n.y,h=(l*s.light[0]+c*s.light[1])/((Math.hypot(l,c)||1)*i),u=Math.max(0,-h)*.24;return{x:a.x-l*u,y:a.y-c*u}}),r=a=>{t.beginPath(),t.moveTo(a[0].x,a[0].y);for(const l of a.slice(1))t.lineTo(l.x,l.y);t.closePath()};t.save(),r(e),t.clip(),r([...e,...o.reverse()]),t.globalAlpha*=s.opacity,t.fillStyle=s.shadow,t.fill(),t.restore()}const sk="#f1c9a5",ik="#2f2f33";function So(t,e,n,s={},i=0){const o=Qu(Mo(n,s),e),r=s.ink??ik,a=s.lineWidth??o.size*.035;let l=s.pen??ii(t,{look:s.look??"clean",ink:r,lineWidth:a,seed:s.seed??1,time:i,pencil:{construction:!1,...s.pencil}});const c=s.skin??sk;c==="none"&&(l=oi(t,l));const h=s.nails??!0,u=[{depth:o.palmDepth,draw:()=>ok(t,l,o,c,a,s)}];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:()=>rk(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 ok(t,e,n,s,i,o){if(e.shape(n.palm,s==="none"?null:s,o.connected?0:i),s!=="none"&&o.shading&&e.look==="clean"){const r=n.palm.reduce((a,l)=>({x:a.x+l.x/n.palm.length,y:a.y+l.y/n.palm.length}),{x:0,y:0});td(t,n.palm,r,o.shading)}if(o.connected&&i>0&&(e.look!=="silhouette"||s==="none")){const{up:r}=n.axes;let a=[];for(let l=0;l<=n.palm.length;l++){const c=n.palm[l%n.palm.length],h=n.palm[(l+1)%n.palm.length];((c.x+h.x)/2-n.wrist.x)*r.x+((c.y+h.y)/2-n.wrist.y)*r.y<n.size*.08?(a.length>1&&e.line(a,i),a=[]):(a.length===0&&a.push(c),a.push(h))}a.length>1&&e.line(a,i)}if(n.palmFacing<-.3&&e.look!=="silhouette"){const{up:r}=n.axes;for(const[a,l]of Object.entries(n.fingers)){const c=n.curls[a]??0;if(a==="thumb"||c<.5)continue;const h=l.points[0],u=l.widths[0]*.42,d={x:h.x-r.x*u*.2,y:h.y-r.y*u*.2},f=Math.atan2(r.y,r.x),p=Array.from({length:7},(g,m)=>{const b=f-Math.PI/2+Math.PI*m/6;return{x:d.x+Math.cos(b)*u,y:d.y+Math.sin(b)*u}});e.line(p,i*.6)}}if(n.palmFacing>.45&&e.look!=="silhouette"){const{up:r,across:a}=n.axes,l=n.size,c=n.wrist,h=(d,f)=>({x:c.x+(a.x*d+r.x*f)*l,y:c.y+(a.y*d+r.y*f)*l}),u=n.side==="left"?-1:1;e.line([h(-.15*u,.36),h(-.04*u,.3),h(.1*u,.33)],i*.5)}}function rk(t,e,n,s,i,o){const{widths:r}=n,a=ak(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"||s==="none"){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(s==="none"){const g=zt(a,h,u),m=a[a.length-2],b=Math.atan2(c.y-m.y,c.x-m.x),v=Array.from({length:13},(k,w)=>{const T=b+Math.PI/2-w*Math.PI/12;return{x:c.x+Math.cos(T)*u/2,y:c.y+Math.sin(T)*u/2}});e.shape([...g.slice(0,a.length),...v.slice(1),...g.slice(a.length)],null,i)}else e.limb(a,h+2*i,u+2*i);if(t.restore(),s!=="none"&&e.look!=="silhouette"&&(t.fillStyle=s,bo(t,a,h,u)),s==="none"||e.look==="silhouette"||!o||n.nail<.25)return;const d=a[a.length-2],f=lk({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 ak(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 lk=t=>{const e=Math.hypot(t.x,t.y);return e>1e-6?{x:t.x/e,y:t.y/e}:null},Kt={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}},ck=40;function li(t){return t===void 0?Kt.walk:typeof t=="string"?Kt[t]??Kt.walk:t}function ed(t,e,n=ut,s=1){const i=li(t);if(i===Kt.walk)return rd(e,n,s);const o=e*Math.PI*2,r=Math.sin(o)*s,a=Math.cos(o)*s,l=b=>Math.abs(b)<=ck,c=i.shoulder??0,h=(b,v)=>l(b)?v*c+i.arm*r:b,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 xo(t,e,n=1){const s=li(t),i=Kt.walk.swing,o=r=>Math.sin(r*Math.PI/180);return ad(e,n)*o(s.swing*n)/o(i*n)}const ut={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 Dt(t){return{...ut,...t}}const nd={mouth:0,smile:0,mouthWidth:1,leftEye:1,rightEye:1,leftBrow:0,rightBrow:0,browTilt:0,lookX:0,lookY:0},qt=t=>({...nd,...t}),vt={neutral:nd,happy:qt({smile:.9,leftBrow:.2,rightBrow:.2}),joyful:qt({mouth:.6,smile:1,mouthWidth:1.2,leftEye:0,rightEye:0,leftBrow:.4,rightBrow:.4}),sad:qt({smile:-.8,leftEye:.8,rightEye:.8,browTilt:.9,leftBrow:-.1,rightBrow:-.1,lookY:.6}),crying:qt({mouth:.45,smile:-1,leftEye:0,rightEye:0,browTilt:1,lookY:.4}),surprised:qt({mouth:.7,mouthWidth:.7,leftEye:1.5,rightEye:1.5,leftBrow:1,rightBrow:1}),shocked:qt({mouth:1,mouthWidth:.8,leftEye:1.6,rightEye:1.6,leftBrow:1,rightBrow:1,browTilt:.4}),angry:qt({smile:-.6,mouthWidth:.9,leftEye:.8,rightEye:.8,leftBrow:-.6,rightBrow:-.6,browTilt:-1}),furious:qt({mouth:.5,smile:-1,mouthWidth:1.3,leftEye:.9,rightEye:.9,leftBrow:-.9,rightBrow:-.9,browTilt:-1}),worried:qt({smile:-.3,mouthWidth:.8,leftEye:1.1,rightEye:1.1,leftBrow:.3,rightBrow:.3,browTilt:.8,lookX:-.5}),scared:qt({mouth:.35,smile:-.5,mouthWidth:.8,leftEye:1.45,rightEye:1.45,leftBrow:.8,rightBrow:.8,browTilt:.9}),confused:qt({smile:-.2,mouthWidth:.8,leftEye:.9,rightEye:1.15,leftBrow:-.3,rightBrow:.8,lookX:.5,lookY:-.4}),skeptical:qt({smile:-.1,leftEye:.6,rightEye:1,leftBrow:-.4,rightBrow:.7,lookX:.4}),thinking:qt({smile:0,mouthWidth:.7,leftBrow:.3,rightBrow:.5,lookX:.6,lookY:-.8}),sleepy:qt({smile:.1,leftEye:.25,rightEye:.25,leftBrow:-.3,rightBrow:-.3,lookY:.5}),disgusted:qt({smile:-.7,mouthWidth:.9,leftEye:.6,rightEye:.75,leftBrow:-.5,rightBrow:-.2,browTilt:-.4,lookX:-.6}),smug:qt({smile:.6,mouthWidth:.9,leftEye:.6,rightEye:.6,leftBrow:.1,rightBrow:.5,lookX:.5}),wink:qt({smile:.9,leftEye:0,rightEye:1,leftBrow:-.2,rightBrow:.3})};function Ge(t,e){return{...t,...typeof e=="string"?vt[e]:e}}const ae={rest:ut,wave:Dt({rightShoulder:135,rightElbow:30,headTilt:6,...vt.happy}),cheer:Dt({leftShoulder:125,leftElbow:20,rightShoulder:125,rightElbow:20,...vt.joyful}),shrug:Dt({leftShoulder:30,leftElbow:85,rightShoulder:30,rightElbow:85,headTilt:-10,...vt.confused,lookX:0,lookY:0}),point:Dt({rightShoulder:90,rightElbow:0,lean:4,smile:.4}),think:Dt({rightShoulder:60,rightElbow:150,headTilt:10,...vt.thinking}),handsOnHips:Dt({leftShoulder:45,leftElbow:-100,rightShoulder:45,rightElbow:-100,leftHip:14,rightHip:14,smile:.8}),sad:Dt({leftShoulder:14,rightShoulder:14,leftElbow:-4,rightElbow:-4,headTilt:-14,lean:-3,...vt.sad}),surprised:Dt({leftShoulder:70,leftElbow:60,rightShoulder:70,rightElbow:60,...vt.surprised}),crouch:Dt({stretch:.72,leftShoulder:35,rightShoulder:35,leftElbow:-50,rightElbow:-50,leftHip:22,rightHip:22,headTilt:-4}),sit:Dt({sit:1,turn:.5,leftShoulder:-25,rightShoulder:25,leftElbow:-55,rightElbow:55}),jump:Dt({stretch:1.22,leftShoulder:140,rightShoulder:140,leftElbow:20,rightElbow:20,leftHip:4,rightHip:4,...vt.joyful}),duck:Dt({stretch:.62,bend:28,headTilt:-8,leftShoulder:150,rightShoulder:150,leftElbow:130,rightElbow:130,leftHip:25,rightHip:25,...vt.scared}),lie:Dt({spin:-90,rise:-.42,leftShoulder:165,rightShoulder:165,leftElbow:150,rightElbow:150,...vt.sleepy}),sideSplit:Dt({leftHip:90,rightHip:90,leftAnkle:-45,rightAnkle:-45,leftShoulder:120,rightShoulder:120,leftElbow:10,rightElbow:10,...vt.happy}),frontSplit:Dt({turn:1,leftHip:-90,rightHip:-90,leftAnkle:-45,rightAnkle:-45,leftShoulder:-150,rightShoulder:150,leftElbow:10,rightElbow:-10,...vt.happy})},sd=Object.keys(ut);function es(t,e,n){const s={...t};for(const i of sd)s[i]=t[i]+(e[i]-t[i])*n;return s}const Ja=24,id=4,od=28,hk=40;function rd(t,e=ut,n=1){const s=Math.sin(t*Math.PI*2)*n,i=Math.cos(t*Math.PI*2)*n,o=c=>Math.abs(c)<=hk,r=c=>o(c)?22*s:c,a=o(e.leftShoulder)?e.leftElbow-od*Math.max(0,-s):e.leftElbow,l=o(e.rightShoulder)?e.rightElbow+od*Math.max(0,s):e.rightElbow;return{...e,lean:e.lean+id*n,headTilt:e.headTilt-id*.5*n,leftElbow:a,rightElbow:l,leftHip:-Ja*s,rightHip:-Ja*s,leftKnee:-30*Math.max(0,i),rightKnee:30*Math.max(0,-i),leftShoulder:r(e.leftShoulder),rightShoulder:r(e.rightShoulder)}}function ad(t,e=1){return 4*((Za+To)*t)*Math.sin(Ja*e*Math.PI/180)}function ld(t){const e=Math.abs(Math.sin(t/65)),n=.55+.45*Math.sin(t/310);return e*n}const cd=.12,hd=.46,uk=1-2*cd,dk=.1,fk=.21,gk=.19,Za=.24,To=.22,ud=.12,pk=.14,dd=.33,fd=.7,gd=.3,mk=.35,yk=[1.7,1.05],bk=[1.3,.75],pd=[1.45,.85],wk=[1.15,.75],md=.06,kk=.7,vk=.65,yd=.075,Mk=.3,Sk=.02,xk=.012,Tk=12,Ek=.25,Eo=90,Ak=.25,$k=.04,bd=.01,Mn=t=>Math.min(1,Math.max(0,t??0));function Pk(t,e=1){return To*t*e}const Qa=-.12,wd=.4,he=t=>t*Math.PI/180,Ik=(t,e)=>({x:e*Math.sin(he(t)),y:Math.cos(he(t))}),kd=(t,e)=>Math.max(0,t)*(1-Math.min(1,Math.max(0,e))),vd=(t,e,n,s)=>t-.3*e-n*.14*e-Math.max(0,s-1)*.12*e;function Ok(t,e,n,s,i,o){const r=Math.max(1,Math.min(o*.6,pk*n)),a=Mn(e.turn),l=(ud+dd*a)*n,c=s+Qa*n,h=l+e.lookX*.08*n,u=e.lookY*.07*n,d=[{x:-.34*n*(1-fd*a),squeeze:1-fd*a,open:e.leftEye,brow:e.leftBrow,side:-1},{x:.34*n*(1-gd*a),squeeze:1-gd*a,open:e.rightEye,brow:e.rightBrow,side:1}];t.fillStyle=i,t.strokeStyle=i,t.lineWidth=r;for(const b of d){const v=kd(b.open,e.blink);if(v<.2){const P=e.smile>.5?-.12*n:.06*n;t.beginPath(),t.moveTo(b.x+l-.12*n,c),t.quadraticCurveTo(b.x+l,c+P,b.x+l+.12*n,c),t.stroke()}else{if(v>1.2){const S=.13*n*v;t.beginPath(),t.ellipse(b.x+l,c,S*.85,S,0,0,Math.PI*2),t.fillStyle="#ffffff",t.fill(),t.stroke(),t.fillStyle=i}const P=v>1.2?.075*n:.1*n;t.beginPath(),t.ellipse(b.x+h,c+u,P,P*1.1*Math.min(v,1),0,0,Math.PI*2),t.fill()}const k=vd(c,n,b.brow,v),w=b.x+l-b.side*.13*n*b.squeeze,T=b.x+l+b.side*.13*n*b.squeeze;t.beginPath(),t.moveTo(T,k),t.lineTo(w,k-e.browTilt*.1*n),t.stroke()}const f=s+wd*n,p=.25*n*Math.max(.3,e.mouthWidth)*(1-mk*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 Md(t,e){const n=e.height??300,s=Math.min(3,Math.max(.3,t.stretch??1)),i=Math.sqrt(s),o=e.armLength??1;if(!Number.isFinite(o)||o<=0)throw new Error("stick figure: armLength must be a positive finite multiplier");const r=(e.headSize??2*cd)/2,a=e.headSize===void 0?uk:1-2*r,l=r*n,c=Mn(t.sit),h=t.leftHip+(-Eo-t.leftHip)*c,u=t.leftKnee+(-Eo-t.leftKnee)*c,d=t.rightHip+(Eo-t.rightHip)*c,f=t.rightKnee+(Eo-t.rightKnee)*c,p=e.classic===!0,g=Mn(t.turn),m=(V,L,q,G,C)=>{const Y=Math.max(-Math.PI/2,Math.min(Math.PI/2,Math.abs(he(L-q)/2)+he(G))),st=Math.max(-1,Math.min(1,kk+C)),$=g+(1-g)*V*st;return p?{x:0,y:0}:{x:Math.cos(Y)*md*$,y:Math.sin(Y)*md}},b={left:t.leftAnkle??0,right:t.rightAnkle??0},v={left:t.leftFootOut??0,right:t.rightFootOut??0};let k=0;if(c>0||!p){const V=(C,Y,st,$,_)=>Za*Math.cos(he(Y))+To*Math.cos(he(Y-st))+Math.max(0,m(C,Y,st,$,_).y),L=Math.max(V(-1,h,u,b.left,v.left),V(1,d,f,b.right,v.right)),q=1-Mn((t.rise??0)/$k),G=(p?Math.min(1,c/Ak):1)*q;k=(hd-L)*G*n*s}const w=-hd*n*s+k,T=-a*n*s+k,P=p?0:(Sk*Mn(t.turn)+xk*c)*n*s,S=he(t.bend??0),x={end:xd(w,T,S,1),bend:S};let M;if(S!==0){M=[];for(let V=0;V<=Sd;V++){const L=V/Sd,q=xd(w,T,S,L);M.push({x:q.x-P*Math.sin(Math.PI*L),y:q.y})}}else M=P===0?[{x:0,y:w},{x:0,y:T}]:vn({x:0,y:w},{x:-P,y:(w+T)/2},{x:0,y:T},1,8);const E=T+dk*n*s,I=(e.shoulderWidth??0)*n*Math.cos(g*Math.PI/2),A=(V,L,q,G,C)=>{const Y=Ik(q,G);return{x:V+Y.x*C*n,y:L+Y.y*C*n}},O=(V,L,q)=>{const G=A(0,w,L,V,Za*s);return{root:{x:0,y:w},joint:G,end:A(G.x,G.y,L-q,V,To*s)}},H=(V,L,q)=>{const G={x:V*I,y:E},C=A(G.x,G.y,L,V,fk*i*o);return{root:G,joint:C,end:A(C.x,C.y,L+q,V,gk*i*o)}},W={left:O(-1,h,u),right:O(1,d,f)},j=(V,L,q,G,C,Y)=>{const st=m(V,q,G,C,Y);return{x:L.end.x+st.x*n*s,y:L.end.y+st.y*n*s}},J=(V,L,q,G,C)=>A(L.end.x,L.end.y,q+G+C,V,yd*i),tt={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(p?0:Mk,e.rubber??0)),r:l,headRx:l/Math.sqrt(s),headRy:l*Math.sqrt(s),hipY:w,neckY:T,drop:k,lean:p?t.lean:t.lean+Tk*Math.sin(Math.PI*c),classic:p,legs:W,toes:{left:j(-1,W.left,h,u,b.left,v.left),right:j(1,W.right,d,f,b.right,v.right)},spine:M,chest:x,arms:tt,handTips:{left:J(-1,tt.left,t.leftShoulder,t.leftElbow,t.leftWrist??0),right:J(1,tt.right,t.rightShoulder,t.rightElbow,t.rightWrist??0)}}}const Sd=10;function xd(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 _k(t,e){if(t.chest.bend===0)return e;const n=hi(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 ci=(t,e)=>e===0?[t.root,t.joint,t.end]:vn(t.root,t.joint,t.end,e);function hi(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 Td(t,e,n=!0){const s=Hk(t,e),i=e.spin??0,o=e.rise??0;return n&&(i!==0||o!==0)?Ck(s,t,i,o):s}function Ed(t,e,n){return{pivot:{x:0,y:t.hipY},angle:t.facing*he(e),lift:n*t.height}}function Ck(t,e,n,s){const{pivot:i,angle:o,lift:r}=Ed(e,n,s),a=d=>{const f=hi(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=bd*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 Hk(t,e){const n=he(t.lean),s=he(e.headTilt),i={x:0,y:t.hipY},o=w=>({x:t.facing*w.x,y:w.y}),r=w=>o(hi(w,i,n)),a=w=>r(_k(t,w)),l=w=>a(hi({x:w.x,y:w.y+t.neckY},{x:0,y:t.neckY},s)),c=ci(t.arms.left,t.rubber).map(a),h=ci(t.arms.right,t.rubber).map(a),u=(w,T)=>Math.atan2(T.y-w.y,T.x-w.x),d={left:a(t.handTips.left),right:a(t.handTips.right)},f=(w,T)=>{const[P,S]=w.slice(-2),x=t.arms[T],M=u(a(x.end),d[T])-u(a(x.joint),a(x.end));return u(P,S)+M};let p=1/0;for(const[w,T]of[[e.leftBrow,e.leftEye],[e.rightBrow,e.rightEye]]){const P=vd(Qa,1,w,kd(T,e.blink));p=Math.min(p,P,P-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)},b={left:Math.max(g.left.y,m.left.y),right:Math.max(g.right.y,m.right.y)},v=Math.max(b.left,b.right),k=bd*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:v,grounded:{left:b.left>=v-k,right:b.right>=v-k},fingertips:d,handAngle:{left:f(c,"left"),right:f(h,"right")},limbs:{leftArm:c,rightArm:h,leftLeg:ci(t.legs.left,t.rubber).map(o),rightLeg:ci(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:Qa,browTopY:p,mouthY:wd,faceX:t.facing*(ud+dd*Mn(e.turn))}}}function me(t,e={}){return Td(Md(t,e),t)}function Rk(t,e,n){return hi({x:t.center.x+e*t.rx,y:t.center.y+n*t.ry},t.center,t.angle)}function Ad(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 $d(t,e,n={},s=0){const i=Md(e,n),o=n.color??"#1e293b",r=n.layers??{},a=n.layers?Td(i,e,!1):void 0,l=n.sketch?yo(t,n.sketch,s):void 0,c=n.sketch&&n.layers?yo(t,n.sketch,s):void 0,h=S=>{t.save(),S(),t.restore()},u=S=>{S&&a&&h(()=>S(t,a,s,c))},d=()=>t.scale(i.facing,1),f=()=>{d(),t.translate(0,i.hipY),t.rotate(he(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=(S,x,M)=>{if(l)return x?l.curve(S):l.line(S);if(i.classic){t.beginPath(),t.moveTo(S[0].x,S[0].y);for(const E of S.slice(1))t.lineTo(E.x,E.y);t.stroke();return}bo(t,S,M[0]*i.lineWidth,M[1]*i.lineWidth)},m=(S,x)=>g(ci(S,i.rubber),i.rubber>0,x),b=S=>{i.classic||g([i.legs[S].end,i.toes[S]],!1,wk)},v=S=>{if(n.hands&&!i.classic)return w(S);if(i.classic||l)return;const x=i.arms[S].end;t.beginPath(),t.arc(x.x,x.y,vk*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=Ed(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 w(S){const x=n.hands??{},M=i.arms[S].end,E=i.handTips[S],I=n.headFill??"#ffffff";So(t,M,x[S]??Ot,{side:S,angle:Math.atan2(E.x-M.x,M.y-E.y)*180/Math.PI,size:(x.size??yd)*i.height*Math.sqrt(i.stretch),skin:x.skin??(I==="none"?void 0:I),ink:o,lineWidth:i.lineWidth*.45,fingers:x.fingers,plump:x.plump,look:n.sketch?"pencil":"clean",seed:n.sketch?.seed},s)}const T=S=>{h(()=>{p(),m(i.arms[S],bk),v(S)});const x=r.sleeve;x&&a&&h(()=>x(t,a,S,s,c))},P=Mn(e.turn)>Ek;u(r.behind),h(()=>{d(),m(i.legs.left,pd),b("left"),m(i.legs.right,pd),b("right")}),P&&T("left"),h(()=>{f(),g(i.spine,i.spine.length>2,yk)}),h(()=>{p();const{left:S,right:x}={left:i.arms.left.root,right:i.arms.right.root};if(S.x!==x.x)if(i.classic)g([S,x],!1,[1,1]);else{const M={x:(S.x+x.x)/2,y:S.y-.3*Math.abs(x.x-S.x)};g(vn(S,M,x,1,8),!0,[1.1,1.1])}}),u(r.body),P||T("left"),T("right"),u(r.behindHead),h(()=>{p(),t.translate(0,i.neckY),t.rotate(he(e.headTilt));const S=-i.headRy;t.beginPath(),t.ellipse(0,S,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,S,i.headRx,i.headRy);const M=l.nudge();t.translate(M.x,M.y)}else t.stroke();t.translate(0,S),t.scale(i.headRx/i.r,i.headRy/i.r),Ok(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 tl(t,e,n,s){const i={...t},o=t.gait&&s?.[t.gait]||t.gait;let r=t.walking>0?es(i,ed(o,t.walk,i),t.walking):i,a=Lk(t);const l=t.dancing??0;if(n&&l>0){const c=n(t.beat??0);if(r=es(r,c.pose,l),c.hands){const h=(u,d)=>d?ts(u??Ot,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*ld(e))}),{pose:r,hands:a}}function Pd(t,e,n,s){return tl(t,e,n,s).pose}const Id=(t,e)=>(t.facing??e.facing??1)<0?-1:1,ui=(t,e)=>`hand.${t}.${e}`;function Lk(t){const e=i=>{if(typeof t[ui(i,"spread")]=="number")return Object.fromEntries(Object.keys(Ot).map(o=>[o,t[ui(i,o)]]))},n=e("left"),s=e("right");return n||s?{left:n,right:s}:void 0}function Fk(t,e){return!e||!t.hands?t:{...t,hands:{...t.hands,left:e.left??t.hands.left,right:e.right??t.hands.right}}}function el(t){const e=t.style??{},n=e.height??300,s=n*.8,i={...Dt(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]??Ot;for(const l of Object.keys(Ot))o[ui(r,l)]=a[l]??Ot[l]}return{type:"custom",x:t.x-s/2,y:t.y-n,width:s,height:n,props:{...i,...o},about:Nk(Object.keys(o),t.cast),figureStyle:e,figureDance:t.dance,figureGaits:t.cast?.gaits,draw(r,a,l){const c=a.props,h=tl(c,l,t.dance,t.cast?.gaits);r.translate(s/2,n),$d(r,h.pose,Fk({...e,rubber:c.rubber,facing:Id(c,e)},h.hands),l)}}}function Nk(t,e){const n={...zu,...qu};for(const s of t){const[,i,...o]=s.split("."),r=ju[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 W2(e)}}}function nl(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=Pd(i,e.time,t.figureDance,t.figureGaits),l=me(a,{...s,rubber:i.rubber,facing:Id(i,s)});return{pose:a,joints:Ad(l,t.x+o+t.width/2,t.y+r+t.height)}}function Ao(t){const e=[];return t.forEach((n,s)=>{const i=s===0?ut:e[s-1],o=typeof n.pose=="string"?ae[n.pose]:{...i,...n.pose};e.push(n.expression?Ge(o,n.expression):o)}),e}function Wk(t,e){const n=Ao(e);return sd.filter(s=>n.some(i=>i[s]!==ut[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 sl=.5,$o={pataka:Nt({"thumb.curl":.3,"thumb.across":.6,"index.curl":0,"middle.curl":0,"ring.curl":0,"pinky.curl":0,spread:0,turn:2}),tripataka:Nt({"thumb.curl":.3,"thumb.across":.6,"index.curl":0,"middle.curl":0,"ring.curl":1,"pinky.curl":0,spread:0,turn:2}),alapadma:Nt({"thumb.curl":.1,"thumb.across":0,"index.curl":.05,"middle.curl":.15,"ring.curl":.25,"pinky.curl":.35,spread:1,turn:2}),mushti:St.fist,shikhara:St.thumbsUp,hamsasya:Nt({"thumb.curl":.15,"thumb.across":.6,"index.curl":.6,"middle.curl":0,"ring.curl":0,"pinky.curl":0,spread:.7,turn:2}),katakamukha:Nt({"thumb.curl":.2,"thumb.across":.6,"index.curl":.65,"middle.curl":.7,"ring.curl":0,"pinky.curl":0,spread:.4,turn:2})};function Po(t){return typeof t!="string"?t:t in $o?$o[t]:St[t]}function Od(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?Po(i.hands.left):r.left,right:i.hands?.right?Po(i.hands.right):r.right,easing:i.easing??t.easing})}return s}const il=(t,e)=>(t%e+e)%e;function Dk(t,e,n,s){const i=Od(t,n,s);if(i.length===0)return{pose:n,hands:s};const o=il(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=Wt(l.easing??"ease-in-out")(Math.min(1,Math.max(0,u)));return{pose:es(a.pose,l.pose,d),hands:{left:ts(a.left,l.left,d),right:ts(a.right,l.right,d)}}}const Bk=[["leftShoulder","rightShoulder"],["leftElbow","rightElbow"],["leftWrist","rightWrist"],["leftHip","rightHip"],["leftKnee","rightKnee"],["leftAnkle","rightAnkle"],["leftFootOut","rightFootOut"],["leftEye","rightEye"],["leftBrow","rightBrow"]],zk=["lean","headTilt","lookX","spin"],qk=new Set(["leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee"]);function _d(t){const e={...t},n=(t.turn??0)>=.5;for(const[s,i]of Bk){const o=n&&qk.has(s)?-1:1;e[s]=o*t[i],e[i]=o*t[s]}if(!n)for(const s of zk)e[s]=-t[s];return e}const jk=t=>Math.min(1,Math.max(-1,(.5-t)*4));function Cd(t,e,n){const s=il(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=jk(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 Io(t){const e={...ut,...t.stance};return t.expression?Ge(e,t.expression):e}function Hd(t){return{left:t.hands?.left?Po(t.hands.left):Ot,right:t.hands?.right?Po(t.hands.right):Ot}}function ol(t,e,n){const s=t.moves[e.move];if(!s)throw new Error(`dance: "${t.label}" has no move "${e.move}"`);const i=Dk(s,n,Io(t),Hd(t));return e.mirror?{pose:_d(i.pose),hands:{left:i.hands?.right,right:i.hands?.left}}:i}function Oo(t,e,n={}){const s=typeof t=="string"?Ue[t]:t;let i;if(n.move)i=ol(s,{move:n.move,mirror:n.mirror},e);else{const o=s.routine,r=o.reduce((u,d)=>u+d.beats,0),a=il(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=ol(s,o[c],h),h<sl&&o.length>1&&e>=sl){const u=o[(c-1+o.length)%o.length],d=ol(s,u,u.beats+h),f=Wt("ease-in-out")(h/sl);i={pose:es(d.pose,i.pose,f),hands:{left:ts(d.hands.left,i.hands.left,f),right:ts(d.hands.right,i.hands.right,f)}}}}return{...i,pose:Cd(i.pose,s.groove,e)}}function Yk(t,e,n={}){return Oo(t,e,n).pose}function _o(t){return(typeof t=="string"?Ue[t]:t).routine.reduce((n,s)=>n+s.beats,0)}const Kk={leftToe:"rightToe",rightToe:"leftToe",leftHeel:"rightHeel",rightHeel:"leftHeel"};function Rd(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?Kk[u]:u})}}function Xk(t,e,n,s={}){const i=typeof t=="string"?Ue[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;Rd(r,a,Math.ceil((n-a)/r.beats)*r.beats,s.mirror,o,e,n)}else{const r=_o(i);for(let a=Math.floor(e/r)*r;a<n;a+=r){let l=a;for(const c of i.routine)Rd(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 Ld(t,e){const n=t.moves[e.move];if(!n?.travel)return 0;const s=n.travel/n.beats;return e.mirror?(Od(n,Io(t),Hd(t))[0]?.pose.turn??Io(t).turn??0)>=.5?s:-s:s}function Fd(t,e){return e.move?[{move:e.move,beats:t.moves[e.move].beats,mirror:e.mirror}]:t.routine}function Co(t,e,n={}){const s=typeof t=="string"?Ue[t]:t,i=Fd(s,n),o=i.reduce((h,u)=>h+u.beats,0),r=i.reduce((h,u)=>h+Ld(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+=Ld(s,h)*u,c-=u,c<=0)break}return l}function Gk(t,e,n){const s=Fd(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 Uk=8;function Nd(t,e,n){const s=typeof e=="string"?Ue[e]:e,i=n.bpm??s.bpm,o=n.beats??(n.move?s.moves[n.move].beats:_o(s)),r=Gk(s,o,n);if(r.every(b=>Co(s,b,n)===0))return;const a=Math.min(n.fade??1,o/2),l=Wt("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*Uk),u=a<=0?[]:Array.from({length:h+1},(b,v)=>[v/h*a,o-v/h*a]).flat(),d=[...new Set([...r,...u])].sort((b,v)=>b-v);let f=0;const p=d.map((b,v)=>{if(v>0){const k=d[v-1],w=Math.max(1,Math.ceil((b-k)*16));for(let T=0;T<w;T++){const P=k+(b-k)*T/w,S=k+(b-k)*(T+1)/w;f+=(Co(s,S,n)-Co(s,P,n))*c((P+S)/2)}}return{beat:b,travel:f}}),g=n.start??0,m=n.x??0;return{id:`${t}-x`,target:t,property:"x",keyframes:p.map(b=>({time:g+b.beat*6e4/i,value:m+n.height*b.travel,easing:"linear"}))}}function Vk(t,e,n=0){return(t-n)*e/6e4}function Jk(t,e={}){return n=>Oo(t,n,e)}function Zk(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 Qk(t,e,n={}){const s=typeof e=="string"?Ue[e]:e,i=n.bpm??s.bpm,o=n.beats??(n.move?s.moves[n.move].beats:_o(s)),r=n.samplesPerBeat??4,a=n.start??0,l=Math.round(o*r),c=Array.from({length:l+1},(g,m)=>{const b=m/r;return{time:a+b*6e4/i,frame:Oo(s,b,n)}}),h=(g,m)=>({id:`${t}-${g}`,target:t,property:g,keyframes:c.map(b=>({time:b.time,value:m(b.frame)}))}),d=Object.keys(ut).filter(g=>c.some(m=>m.frame.pose[g]!==c[0].frame.pose[g])||c[0].frame.pose[g]!==ut[g]).map(g=>h(g,m=>m.pose[g])),f=n.height===void 0?void 0:Nd(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(Ot)){const b=v=>v.hands?.[g]?.[m]??Ot[m];c.some(v=>b(v.frame)!==Ot[m])&&p.push(h(ui(g,m),b))}return[...d,...p]}const di={type:"back",mode:"out",overshoot:1.1},Zt="ease-out-cubic",t5={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:Zt,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:Zt},{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:Zt},{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}]},e5={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}]},n5={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:Zt},{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:Zt},{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:Zt},{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:di},{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}]},s5={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:{...St.spread,turn:2},right:{...St.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:Zt},{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}]},i5={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:di,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:di},{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:di},{beat:3,pose:{headTilt:4}}]},isolations:{label:"Isolations",beats:2,easing:Zt,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}]},o5={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:{...St.cupped,roll:-30},left:{...St.flat,turn:0}}},{beat:.5,pose:{rightWrist:25,rightElbow:22,leftWrist:10,lean:4,rightHip:6,leftHip:16},hands:{right:{...St.cupped,roll:30}}},{beat:1,pose:{rightWrist:-15,rightElbow:12,leftWrist:-45,lean:-4,rightHip:16,leftHip:6},hands:{right:{...St.cupped,roll:-30}}},{beat:1.5,pose:{rightWrist:25,rightElbow:22,leftWrist:10,lean:4,rightHip:6,leftHip:16},hands:{right:{...St.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:{...St.open,turn:2}},easing:Zt},{beat:.5,pose:{lean:-4,rightHip:12,headTilt:6}},{beat:1,pose:{lean:-11,rightHip:22,headTilt:10},easing:Zt},{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:Zt},{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:Zt}]}},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}]},r5={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}]},a5={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}]},l5={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:{...St.spread,turn:2},right:{...St.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:Zt},{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:Zt},{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}]},c5={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:{...St.spread,turn:2},right:{...St.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}]},Ue={disco:t5,hipHop:e5,breaking:n5,jazz:s5,kpop:i5,bollywood:o5,bhangra:r5,bharatanatyam:a5,charleston:l5,tap:c5,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:di},{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}]}},Ho={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}},rl=.215,al=.205,h5=.065,Wd=.035,u5=.165,d5=.155,f5=12,g5=.3,p5=.7,m5=.35,y5=t=>t*Math.PI/180,lt={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,pupil:1,lid:0,bulge:0,"brow.left":0,"brow.right":0,browTilt:0,lookX:0,lookY:0,blush:0,tears:0,sweat:0,"hair.swing":0,"hair.trail":0,"hair.lift":0,"held.left":1,"held.right":1,"held.both":1};function kt(t={}){return{...lt,...t}}const b5=new Set(["turn","side","head.turn","head.tilt","roll","lookX","hair.swing"]);function Dd(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]=b5.has(n)?-s:s}return e}function $t(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 ye={rest:lt,wave:kt({"arm.right.spread":115,"arm.right.bend":55,"arm.right.elbow":0,"head.tilt":-6,smile:.9}),cheer:kt({...$t("arm",{spread:140,bend:20,elbow:0}),mouth:.6,smile:1,"eye.left":0,"eye.right":0}),point:kt({"arm.right.spread":88,"arm.right.elbow":0,"arm.right.bend":0,"head.turn":-20,smile:.4}),handsOnHips:kt({...$t("arm",{spread:50,bend:-105,elbow:0}),...$t("leg",{spread:9}),smile:.8}),think:kt({"arm.right.spread":22,"arm.right.bend":-150,"arm.right.elbow":0,"head.tilt":10,lookX:-.5,lookY:-.8,smile:0}),shrug:kt({...$t("arm",{spread:35,bend:75,elbow:0}),"head.tilt":-10,smile:-.2}),sit:kt({...$t("leg",{swing:90,knee:90,spread:4}),...$t("arm",{swing:25,elbow:45,spread:8})}),kneel:kt({"leg.left.swing":90,"leg.left.knee":90,"leg.right.swing":-18,"leg.right.knee":108,"leg.right.ankle":16,...$t("arm",{swing:20,elbow:30})}),crouch:kt({...$t("leg",{swing:75,knee:140,spread:6}),lean:25,...$t("arm",{swing:50,elbow:40}),"head.nod":-15}),crawl:kt({lean:82,"head.nod":-35,...$t("arm",{swing:80,elbow:0,spread:4}),...$t("leg",{knee:92,ankle:-88})}),lieDown:kt({roll:90,...$t("arm",{spread:8}),"head.nod":0}),sleep:kt({roll:90,...$t("arm",{spread:8,swing:20,elbow:40}),"leg.left.knee":20,"leg.left.swing":15,blink:1,smile:.2}),stretch:kt({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:kt({...$t("leg",{swing:80,spread:22,rotate:75,knee:145}),...$t("arm",{swing:25,spread:18,elbow:30}),lean:5,smile:.5}),carry:kt({...$t("arm",{spread:16,elbow:4}),lean:-3,smile:.4}),cane:kt({"arm.right.swing":16,"arm.right.spread":10,"arm.right.elbow":0,"arm.right.bend":0,"arm.left.swing":2,side:-3,lean:4,"leg.right.swing":4,smile:.3}),lift:kt({...$t("arm",{swing:28,spread:24,elbow:85,bend:-45}),...$t("leg",{swing:12,knee:22,spread:6}),lean:-4,smile:.2}),push:kt({lean:28,...$t("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:kt({lean:-22,...$t("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:kt({"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:kt({"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:kt({...$t("arm",{swing:32,spread:10,elbow:82,bend:-28}),"head.nod":22,lookY:.8,smile:.2}),type:kt({...$t("leg",{swing:90,knee:90,spread:4}),...$t("arm",{swing:40,spread:10,elbow:55,bend:-20}),lean:8,"head.nod":10,lookY:.5,smile:0})},Bd=["round","flat","pointed","big"],w5={round:{length:1,width:[.95,.7]},flat:{length:1.12,width:[.85,.85]},pointed:{length:1.25,width:[1,.3]},big:{length:1.5,width:[1.25,1.1]}};function ll(t={}){const e=t.headSize??.3,n=t.shoulderWidth??.06,s=t.hipWidth??.022,i=t.legLength??1,o=t.armLength??1,r=w5[t.feet??"round"],a=Math.max(.12,1-e-Wd-(rl+al)*i),l=u=>({id:`arm.${u}`,parent:"spine",offset:[(u==="left"?1:-1)*n,-.035,0],rest:[0,-1,0],side:u==="left"?1:-1,bones:[{length:u5*o,width:[1.25,.9]},{length:d5*o,width:[.9,.75]}]}),c=u=>({id:`leg.${u}`,parent:null,offset:[(u==="left"?1:-1)*s,0,0],rest:[0,-1,0],side:u==="left"?1:-1,bones:[{length:rl*i,width:[1.45,1.05]},{length:al*i,width:[1.05,.85]},{length:h5*Math.sqrt(i)*r.length,width:r.width}]}),h=(u,d)=>u[d]??lt[d]??0;return{id:"human",hipHeight:(rl+al)*i,chains:[c("left"),c("right"),{id:"spine",parent:null,rest:[0,1,0],bones:[{length:a/2,width:[1.7,1.4]},{length:a/2,width:[1.4,1.1]}]},{id:"neck",parent:"spine",rest:[0,1,0],bones:[{length:Wd,width:[1,.9]}]},l("left"),l("right")],head:{on:"neck",size:e},contacts:[...["left","right"].flatMap(u=>[{chain:`leg.${u}`,joint:1},{chain:`leg.${u}`,joint:2},{chain:`leg.${u}`,joint:3},{chain:`arm.${u}`,joint:1},{chain:`arm.${u}`,joint:2}]),{chain:"spine",joint:0},{chain:"spine",joint:1},{chain:"spine",joint:2},{head:"top"}],angles(u,d){if(d.id==="spine"){const v=-h(u,"lean")/2,k=h(u,"side")/2,w=-h(u,"bend");return[{swing:v+w*g5,spread:k},{swing:v+w*p5,spread:k}]}if(d.id==="neck")return[{swing:-h(u,"bend")*m5,spread:0}];const[f,p]=d.id.split("."),g=v=>h(u,`${f}.${p}.${v}`);if(f==="arm")return[{swing:g("swing"),spread:g("spread")},{swing:g("elbow"),spread:g("bend")}];const m=(d.side??1)*g("rotate"),b=1-Math.cos(y5(g("rotate")));return[{swing:g("swing"),spread:g("spread"),yaw:m},{swing:-g("knee"),spread:0,yaw:m},{swing:90+g("ankle")-b*(g("swing")-g("knee")),spread:0,yaw:(f5+g("toeOut"))*(d.side??1)}]},withAngles(u,d,f){const[p,g]=d.id.split("."),m=b=>`${p}.${g}.${b}`;return p==="arm"?{...u,[m("swing")]:f[0].swing,[m("spread")]:f[0].spread,[m("elbow")]:f[1].swing,[m("bend")]:f[1].spread}:p==="leg"?{...u,[m("swing")]:f[0].swing,[m("spread")]:f[0].spread,[m("knee")]:-f[1].swing}:u},boneScale(u,d){const f=Math.min(3,Math.max(.3,h(u,"stretch")));return d?.id.startsWith("arm.")?Math.sqrt(f):f},headPose(u){const d=Math.min(3,Math.max(.3,h(u,"stretch")));return{yaw:h(u,"head.turn"),nod:h(u,"head.nod"),tilt:h(u,"head.tilt"),sx:1/Math.sqrt(d),sy:Math.sqrt(d)}},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 k5(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",pupil:"Pupil size",lid:"Eyelids lowered",bulge:"Eyes bulging","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","hair.swing":"Hair · swing","hair.trail":"Hair · trail","hair.lift":"Hair · lift","held.left":"Left hand · holding","held.right":"Right hand · holding","held.both":"Both hands · holding"}[t]??t}const v5={leftEye:"eye.left",rightEye:"eye.right",leftBrow:"brow.left",rightBrow:"brow.right"},M5={blush:0,tears:0,sweat:0,pupil:1,lid:0,bulge:0},Sn=Object.fromEntries(Object.entries(vt).map(([t,e])=>[t,{...Object.fromEntries(Object.entries(e).map(([n,s])=>[v5[n]??n,s])),...M5}]));Sn.crying.tears=1,Sn.scared.sweat=.8,Sn.scared.bulge=.4,Sn.sleepy.lid=.5,Sn.worried.sweat=.6;const ue=t=>({...Sn.neutral,...t}),cl={...Sn,laughing:ue({mouth:.75,smile:1,mouthWidth:1.25,"eye.left":0,"eye.right":0,"brow.left":.5,"brow.right":.5}),afraid:ue({mouth:.4,smile:-.6,mouthWidth:.9,"eye.left":1.3,"eye.right":1.3,"brow.left":.6,"brow.right":.6,browTilt:1,sweat:1,pupil:.8,bulge:.5}),bored:ue({smile:-.05,mouthWidth:.6,"eye.left":.45,"eye.right":.45,"brow.left":-.4,"brow.right":-.4,lookX:.5}),tired:ue({mouth:.2,smile:-.3,mouthWidth:.7,"eye.left":.3,"eye.right":.3,"brow.left":-.1,"brow.right":-.1,browTilt:.6,lookY:.6}),embarrassed:ue({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:ue({smile:.75,mouthWidth:1,"eye.left":.75,"eye.right":.75,"brow.left":.5,"brow.right":.5,lookY:-.2}),determined:ue({smile:.35,mouthWidth:.8,"eye.left":.85,"eye.right":.85,"brow.left":-.5,"brow.right":-.5,browTilt:-.9}),affectionate:ue({smile:.85,"eye.left":0,"eye.right":0,"brow.left":.3,"brow.right":.3,blush:.8}),hurt:ue({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:ue({smile:-.25,mouthWidth:.7,"eye.left":.5,"eye.right":.85,"brow.left":-.6,"brow.right":.4,browTilt:-.3,lookX:.8,lid:.3}),relieved:ue({smile:.7,"eye.left":0,"eye.right":0,"brow.left":.4,"brow.right":.4,browTilt:.4}),excited:ue({mouth:.6,smile:1,mouthWidth:1.1,"eye.left":1.4,"eye.right":1.4,"brow.left":.9,"brow.right":.9,blush:.4,pupil:1.3})},de=t=>t*Math.PI/180;function hl([t,e,n],s){const i=Math.cos(s),o=Math.sin(s);return[t,e*i+n*o,-e*o+n*i]}function ns([t,e,n],s){const i=Math.cos(s),o=Math.sin(s);return[t*i-e*o,t*o+e*i,n]}function Qt([t,e,n],s){const i=Math.cos(s),o=Math.sin(s);return[t*i+n*o,e,-t*o+n*i]}const Ie=(t,e)=>[t[0]+e[0],t[1]+e[1],t[2]+e[2]],Ro=(t,e)=>[t[0]*e,t[1]*e,t[2]*e],Lo=(t,e)=>ns(hl(t,e.swing),e.spread);function Fo(t,e){const n=Qt(t,e);return{point:{x:n[0],y:-n[1]},depth:n[2]}}function ss(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 b=g.at??(m?m.joints3.length-1:0),v=m?m.joints3[b]:o,k=m?m.frames[Math.max(0,b-1)]:{swing:0,spread:0},w=g.offset?Ie(v,Lo(Ro(g.offset,s),k)):v,T=g.side??1,P=t.boneScale?.(e,g)??1,S=t.angles(e,g),x=[w],M=[];let E=k.swing,I=k.spread;g.bones.forEach((A,O)=>{const H=S[O]??{swing:0,spread:0};E+=de(H.swing),I+=de(H.spread)*T,M.push({swing:E,spread:I});const W=Qt(Lo(g.rest,{swing:E,spread:I}),de(H.yaw??0));x.push(Ie(x[O],Ro(W,A.length*s*P)))}),r[g.id]={joints3:x,frames:M}}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=>Lo(Qt(hl(ns(g,-de(l.tilt)),-de(l.nod)),de(l.yaw)),c),p=Ie(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 ul(t,e,n){const s=n.height,i=de(90*(e.turn??0)),o=ss(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 M of t.chains){const{joints3:E,frames:I}=a[M.id],A=E.map(O=>Fo(O,i));d[M.id]={id:M.id,joints3:E,frames:I,points:A.map(O=>O.point),depths:A.map(O=>O.depth)}}const f=Fo(u,i),p=[[1,0,0],[0,1,0],[0,0,1]].map(M=>Qt(h(M),i)),g=Fo(r,i).point,m=de(e.roll??0),b=M=>{const E=M.x-g.x,I=M.y-g.y;return{x:g.x+E*Math.cos(m)-I*Math.sin(m),y:g.y+E*Math.sin(m)+I*Math.cos(m)}},v=([M,E,I])=>[M*Math.cos(m)+E*Math.sin(m),-M*Math.sin(m)+E*Math.cos(m),I];for(const M of Object.values(d))M.points=M.points.map(b);const k={center:b(f.point),depth:f.depth,rx:l,ry:c,angle:0,axes:p.map(v)},w=k.axes[1];k.angle=Math.atan2(w[0],w[1]);const T=M=>{if("head"in M)return{x:k.center.x+w[0]*c,y:k.center.y-w[1]*c};const E=d[M.chain];return E.points[Math.min(M.joint,E.points.length-1)]};let P=0;(n.contact??"ground")==="ground"&&(P=-Math.max(...t.contacts.map(M=>T(M).y))),P-=(e.lift??0)*s;const S=M=>({x:M.x,y:M.y+P});for(const M of Object.values(d))M.points=M.points.map(S);k.center=S(k.center);const x=t.contacts.map(M=>({spec:M,point:T(M)}));return{height:s,view:i,chains:d,head:k,hip:S(b(g)),hipDepth:Fo(r,i).depth,contacts:x,groundY:Math.max(...x.map(M=>M.point.y))}}const No=(t,e)=>[t[0]-e[0],t[1]-e[1],t[2]-e[2]],dl=t=>{const e=Math.hypot(t[0],t[1],t[2])||1;return[t[0]/e,t[1]/e,t[2]/e]};function Ve(t,e,n){const s=n.height,i=de(90*(e.turn??0)),o=de(e.roll??0),r=ss(t,e,s),a=Qt(r.root,i),l=m=>Ie(ns(No(Qt(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=>dl(No(l(Ie(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 Ie(h,Ro(d[1],r.head.ry));const b=c[m.chain];return b[Math.min(m.joint,b.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,b])=>[m,b.map(g)])),head:{center:g(h),rx:r.head.rx,ry:r.head.ry,axes:d}}}function Wo(t,e,n,s){const i=n.height,o=de(90*(e.turn??0)),r=ss(t,e,i),a=Ve(t,e,n),l=a.hip,c=a.chains,h=a.head.center,u=I=>{if("head"in I)return Ie(h,Ro(a.head.axes[1],a.head.ry));const A=c[I.chain];return A[Math.min(I.joint,A.length-1)]},d=s.toView(l),f=ns(Qt([0,0,1],o),-de(e.roll??0)),p=dl(No(s.toView(Ie(l,f)),d)),g=s.toScreen(d),m=s.toScreen([d[0]+1,d[1],d[2]]),b=Math.hypot(m.x-g.x,m.y-g.y),v=I=>{const A=s.toView(I);return{point:s.toScreen(A),depth:A[2]*b}},k={};for(const I of t.chains){const A=c[I.id].map(v);k[I.id]={id:I.id,joints3:r.chains[I.id].joints3,frames:r.chains[I.id].frames,points:A.map(O=>O.point),depths:A.map(O=>O.depth)}}const w=s.toView(h),T=s.toScreen(w),P=s.toScreen([w[0]+1,w[1],w[2]]),S=Math.hypot(P.x-T.x,P.y-T.y),x=a.head.axes.map(I=>dl(No(s.toView(Ie(h,I)),w))),M={center:T,depth:w[2]*b,rx:r.head.rx*S,ry:r.head.ry*S,angle:Math.atan2(x[1][0],x[1][1]),axes:x},E=t.contacts.map(I=>({spec:I,point:v(u(I)).point}));return{height:i*b,view:o,bodyForward:p,chains:k,head:M,hip:g,hipDepth:d[2]*b,contacts:E,groundY:Math.max(...E.map(I=>I.point.y))}}function is(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}}const Do=t=>t*180/Math.PI,xn=(t,e)=>[t[0]-e[0],t[1]-e[1],t[2]-e[2]],fl=(t,e)=>t[0]*e[0]+t[1]*e[1]+t[2]*e[2],os=t=>Math.hypot(t[0],t[1],t[2]),gl=t=>{const e=os(t)||1;return[t[0]/e,t[1]/e,t[2]/e]},Bo=t=>Math.atan2(Math.sin(t),Math.cos(t));function zd(t){const[e,n,s]=gl(t);return{swing:Math.asin(Math.max(-1,Math.min(1,s))),spread:Math.atan2(e,-n)}}function fi(t,e,n,s,i){const o=t.chains.find(A=>A.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=ul(t,{...e,turn:0,roll:0,lift:0},{height:i.height,contact:"none"}),a=r.chains[n];if(os(xn(s,a.joints3[2]))<i.height*1e-12)return e;const l=a.joints3[0],c=os(xn(a.joints3[1],a.joints3[0])),h=os(xn(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=xn(s,l),f=t.angles(e,o),p=A=>(f[A]?.yaw??0)*Math.PI/180,g=Math.min(c+h-1e-6,Math.max(Math.abs(c-h)+1e-6,os(d))),m=gl(d),b=o.parent!==null,v=Qt(Lo(o.pole??(b?[0,-.35,-1]:[0,0,1]),u),p(0));let k=xn(v,[m[0]*fl(v,m),m[1]*fl(v,m),m[2]*fl(v,m)]);os(k)<1e-6&&(k=Qt([1,0,0],p(0))),k=gl(k);const w=(c*c+g*g-h*h)/(2*c*g),T=Math.sqrt(Math.max(0,1-w*w)),P=[l[0]+c*(w*m[0]+T*k[0]),l[1]+c*(w*m[1]+T*k[1]),l[2]+c*(w*m[2]+T*k[2])],S=[l[0]+m[0]*g,l[1]+m[1]*g,l[2]+m[2]*g],x=o.side??1,M=zd(Qt(xn(P,l),-p(0))),E=zd(Qt(xn(S,P),-p(1))),I=[{swing:Do(Bo(M.swing-u.swing)),spread:Do(Bo(M.spread-u.spread))*x},{swing:Do(Bo(E.swing-M.swing)),spread:Do(Bo(E.spread-M.spread))*x}];return t.withAngles(e,o,I)}const rs=(t,e)=>(t%e+e)%e,qd=t=>t*t*(3-2*t),S5=t=>Object.fromEntries(["left","right"].flatMap(e=>Object.entries(St[t]).map(([n,s])=>[`hand.${e}.${n}`,s])));function pl(t,e=!1){const n=ll(),s=fi(n,lt,"arm.left",[.015,.68,.2],{height:1}),i=fi(n,s,"arm.right",[-.015,.68,.2],{height:1});return Array.from({length:32},(o,r)=>{const a=r/4,l=Math.floor(a),c=a-l,h=l%2===0,u=Math.sin(Math.PI*c),d=Math.max(0,...t.map(p=>1-Math.min(rs(a-p,8),rs(p-a,8))/.5)),f={side:(h?1:-1)*5*Math.sin(Math.PI*c),bend:2+3*u,"head.tilt":(h?-1:1)*3*u,"head.nod":-2*u,"leg.left.swing":h?-4*u:17*u,"leg.right.swing":h?17*u:-4*u,"leg.left.knee":h?5*u:36*u,"leg.right.knee":h?36*u:5*u,"leg.left.spread":4,"leg.right.spread":4,"arm.left.swing":22+d*(e?45:42),"arm.right.swing":22+d*(e?45:42),"arm.left.spread":28-22*d,"arm.right.spread":28-22*d,"arm.left.elbow":48+22*d,"arm.right.elbow":48+22*d,"arm.left.bend":-35*d,"arm.right.bend":-35*d,smile:.9,...S5(e?"hold":"spread")};if(!e)for(const p of Object.keys(i))p.startsWith("arm.")&&(f[p]+=(i[p]-f[p])*d);return{beat:a,pose:f}})}const Tn={garba:{label:"Garba · two clap",bpm:120,beats:8,strikes:[2,3,6,7],keys:pl([2,3,6,7])},garbaThreeClap:{label:"Garba · three clap",bpm:120,beats:8,strikes:[1,2,3,5,6,7],keys:pl([1,2,3,5,6,7])},dandiya:{label:"Dandiya · partner strikes",bpm:120,beats:8,strikes:[1,3,5,7],keys:pl([1,3,5,7],!0)}};function jd(t){const e=typeof t=="string"&&Object.hasOwn(Tn,t)?Tn[t]:typeof t=="string"?void 0:t;if(!e||!Number.isFinite(e.beats)||e.beats<=0||!Array.isArray(e.keys)||!e.keys.length||!Array.isArray(e.strikes)||!e.keys.every((n,s)=>Number.isFinite(n.beat)&&n.beat>=0&&n.beat<e.beats&&(s===0||n.beat>e.keys[s-1].beat)&&n.pose&&Object.values(n.pose).every(Number.isFinite))||!e.strikes.every(n=>Number.isFinite(n)&&n>=0&&n<e.beats))throw new Error("humanDanceFrame: a dance with positive finite beats, ordered pose keys and strike beats within its loop is required");return e}function gi(t,e,n=lt){const s=jd(t);if(!Number.isFinite(e))throw new Error("humanDanceFrame: beat must be finite");const i=rs(e,s.beats);let o=s.keys.length-1;for(let m=0;m<s.keys.length;m++)s.keys[m].beat<=i&&(o=m);const r=s.keys[o],a=s.keys[(o+1)%s.keys.length],l=r.beat>i?r.beat-s.beats:r.beat,c=a.beat<=r.beat?a.beat+s.beats:a.beat,h=qd((i-l)/(c-r.beat)),u={...lt,...n};for(const m of new Set(s.keys.flatMap(b=>Object.keys(b.pose)))){if(m==="turn"||m==="roll")continue;const b=m.match(/^hand\.(?:left|right)\.(.+)$/)?.[1],v=n[m]??lt[m]??(b?Ot[b]:void 0)??0,k=r.pose[m]??v;u[m]=k+((a.pose[m]??v)-k)*h}const d=Math.floor(e),f=e-d,p=f<=.6?1:1-qd((f-.6)/.4),g=Math.max(0,...s.strikes.map(m=>1-Math.min(rs(i-m,s.beats),rs(m-i,s.beats))/.25));return{pose:u,contact:{side:rs(d,2)===0?"left":"right",start:d,weight:p},strike:g}}function x5(t,e){const n=jd(e.style),s=e.bpm??n.bpm,i=e.beats??n.beats,o=e.samplesPerBeat??16;if(![s,i,o].every(l=>Number.isFinite(l)&&l>0))throw new Error("humanDanceTracks: bpm, beats and samplesPerBeat must be positive and finite");if(!Number.isFinite(e.start??0))throw new Error("humanDanceTracks: start must be finite");const r=Math.max(1,Math.ceil(i*o)),a=Array.from({length:r+1},(l,c)=>({time:(e.start??0)+i*c/r*6e4/s,pose:gi(n,i*c/r,e.pose).pose}));return Object.keys(a[0].pose).filter(l=>l!=="turn"&&l!=="roll"&&a.some(c=>c.pose[l]!==(e.pose?.[l]??lt[l]))).map(l=>({id:`${t}-dance-${l}`,target:t,property:l,keyframes:a.map(c=>({time:c.time,value:c.pose[l],easing:"linear"}))}))}function as(t,e,n,s){if(!Number.isFinite(t)||t<n||t>s)throw new Error(`organic body: ${e} must be ${n}..${s}`);return t}function zo(t,e){if(t.length<2||t[0].at!==0||t.at(-1).at!==1)throw new Error(`organic body: ${e} must run from 0 to 1`);return t.map((n,s)=>{if(as(n.at,`${e}.at`,0,1),as(n.width,`${e}.width`,.001,.3),s>0&&n.at<=t[s-1].at)throw new Error(`organic body: ${e} positions must increase`);return{at:n.at,width:n.width}})}function Yd(t,e){const n=Math.max(.095,e.shoulderWidth+.025),s=Math.max(.085,e.hipWidth+.032),i=t.shading??{},o=i.light??[-.8,-.6];if(o.length!==2||!o.every(Number.isFinite)||Math.hypot(...o)===0)throw new Error("organic body: light must be a finite nonzero 2D vector");if(i.mode!==void 0&&i.mode!=="none"&&i.mode!=="cel")throw new Error("organic body: unknown shading mode");return{torso:zo(t.torso??[{at:0,width:s},{at:.2,width:s},{at:.42,width:s*.72},{at:.68,width:n*.9},{at:.86,width:n},{at:1,width:.024}],"torso"),arm:zo(t.arm??[{at:0,width:.028},{at:.22,width:.027},{at:.5,width:.019},{at:.68,width:.023},{at:1,width:.012}],"arm"),leg:zo(t.leg??[{at:0,width:.04},{at:.24,width:.042},{at:.5,width:.027},{at:.68,width:.032},{at:1,width:.016}],"leg"),neck:zo(t.neck??[{at:0,width:.024},{at:1,width:.023}],"neck"),depth:as(t.depth??.55,"depth",.2,1),fill:t.fill??e.skin,outline:{color:t.outline?.color??e.ink,width:as(t.outline?.width??e.lineWidth,"outline.width",0,100)},shading:{mode:i.mode??"cel",light:[...o],shadow:i.shadow??"#633923",opacity:as(i.opacity??.17,"shading.opacity",0,1),highlight:as(i.highlight??.12,"shading.highlight",0,1)}}}function Kd(t,e){const n=Math.min(1,Math.max(0,e)),s=t.findIndex(a=>a.at>=n);if(s<=0)return t[0].width;const i=t[s-1],o=t[s],r=(n-i.at)/(o.at-i.at);return i.width+(o.width-i.width)*r*r*(3-2*r)}const Xd=8,T5=(t,e,n)=>({x:t.x+(e.x-t.x)*n,y:t.y+(e.y-t.y)*n}),En=(t,e)=>{const n=Math.hypot(e.x-t.x,e.y-t.y)||1;return{x:(e.x-t.x)/n,y:(e.y-t.y)/n}},qo=(t,e,n)=>({x:t.x+e.x*n,y:t.y+e.y*n});function pi(t,e=12){if(!Number.isInteger(e)||e<1||e>128)throw new Error("organicCenterLine: steps must be an integer from 1 to 128");if(t.length<2)return t.map(i=>({...i}));const n=t.map((i,o)=>{const r=En(t[Math.max(0,o-1)],i),a=En(i,t[Math.min(t.length-1,o+1)]),l=Math.hypot(r.x+a.x,r.y+a.y);return l>1e-6?{x:(r.x+a.x)/l,y:(r.y+a.y)/l}:a}),s=[];for(let i=0;i<t.length-1;i++){const o=t[i],r=t[i+1],a=Math.hypot(r.x-o.x,r.y-o.y)*.28,l=qo(o,n[i],a),c=qo(r,n[i+1],-a);for(let h=i===0?0:1;h<=e;h++){const u=h/e,d=1-u;s.push({x:d**3*o.x+3*d*d*u*l.x+3*d*u*u*c.x+u**3*r.x,y:d**3*o.y+3*d*d*u*l.y+3*d*u*u*c.y+u**3*r.y})}}return s}function jo(t,e,n,s=1,i=1){const o=t.map((h,u)=>{const d=t[Math.max(0,u-1)],f=t[Math.min(t.length-1,u+1)];let p=En(d,f);Math.hypot(p.x,p.y)<1e-6&&(p={x:0,y:1});const g={x:-p.y,y:p.x},m=u/Math.max(1,t.length-1),b=Kd(e,m)*n*s,v=En(d,h),k=En(h,f),w=v.x*k.y-v.y*k.x,T=Math.acos(Math.min(1,Math.max(-1,v.x*k.x+v.y*k.y))),P=(Math.hypot(h.x-d.x,h.y-d.y)+Math.hypot(f.x-h.x,f.y-h.y))/(2*Math.max(1e-6,T)),S=Math.min(b,Math.max(b*.2,P*.8));return{center:h,width:b,at:m,left:qo(h,g,w>0?S:b),right:qo(h,g,w<0?-S:-b)}}),r=[],a=[],l=(h,u)=>{r.push(h),a.push(u)};for(const h of o)l(h.left,h.at);const c=(h,u,d)=>{const f={x:-u.y,y:u.x};for(let p=1;p<Xd;p++){const g=p*Math.PI/Xd,m=(d?1:-1)*Math.cos(g),b=(d?1:-i)*Math.sin(g);l({x:h.center.x+h.width*(f.x*m+u.x*b),y:h.center.y+h.width*(f.y*m+u.y*b)},h.at)}};c(o.at(-1),En(t[Math.max(0,t.length-2)],t.at(-1)),!0);for(const h of[...o].reverse())l(h.right,h.at);return c(o[0],En(t[0],t[Math.min(1,t.length-1)]),!1),{outline:r,samples:o,positions:a}}function Gd(t,e,n){const s={},i=e.height,o=e.chains.spine;if(o?.length>=2){const r=e.points["shoulder.left"],a=e.points["shoulder.right"],l=n.chains.find(f=>f.id==="arm.left")?.offset?.[0]??.07,c=Math.max(1e-6,Math.abs(l)*i*2),h=r&&a?Math.min(1,Math.hypot(r.x-a.x,r.y-a.y)/c):Math.abs(Math.cos(e.turn*Math.PI/2)),u=Math.sqrt(h*h+t.depth*t.depth*(1-h*h)),d=[T5(o[0],o[1],-.16),...o.slice(1)];s.spine=jo(pi(d),t.torso,i,u,.25)}e.chains.neck?.length>=2&&(s.neck=jo(pi(e.chains.neck),t.neck,i));for(const r of["left","right"])for(const a of["arm","leg"]){const l=e.chains[`${a}.${r}`];!l||l.length<3||(s[`${a}.${r}`]=jo(pi(l.slice(0,3)),t[a],i),a==="leg"&&l.length>3&&(s[`foot.${r}`]=jo(pi(l.slice(2)),[{at:0,width:.019},{at:1,width:.014}],i)))}return s}function Ud(t,e){let n=!1;for(let s=0,i=e.length-1;s<e.length;i=s++){const o=e[s],r=e[i];o.y>t.y!=r.y>t.y&&t.x<(r.x-o.x)*(t.y-o.y)/(r.y-o.y)+o.x&&(n=!n)}return n}function ml(t,e,n,s=0){const i=t.samples.filter(a=>a.at>=e&&a.at<=n),o=(a,l)=>{const c=a[l],h=a.center,u=Math.hypot(c.x-h.x,c.y-h.y)||1;return{x:c.x+(c.x-h.x)*s/u,y:c.y+(c.y-h.y)*s/u}},r=[...i.map(a=>o(a,"left")),...[...i].reverse().map(a=>o(a,"right"))];{const a=t.samples[0].center;for(const l of t.outline.slice(-7)){const c=Math.hypot(l.x-a.x,l.y-a.y)||1;r.push({x:l.x+(l.x-a.x)*s/c,y:l.y+(l.y-a.y)*s/c})}}return r}function Vd(t,e){t.beginPath(),t.moveTo(e[0].x,e[0].y);for(const n of e.slice(1))t.lineTo(n.x,n.y);t.closePath()}function E5(t,e,n){const s=n.shading;if(s.mode==="none"||n.fill==="none")return;const i=Math.hypot(...s.light),o={x:s.light[0]/i,y:s.light[1]/i},r=t.globalAlpha;t.save(),Vd(t,e.outline),t.clip();for(const a of["left","right"]){const l=e.samples.map(h=>h[a]),c=e.samples.map(h=>{const u=h[a],d=h.center,f=u.x-d.x,p=u.y-d.y,g=(f*o.x+p*o.y)/(Math.hypot(f,p)||1),m=Math.max(0,-g)*.44;return{x:u.x+(d.x-u.x)*m,y:u.y+(d.y-u.y)*m}});if(Vd(t,[...l,...c.reverse()]),t.fillStyle=s.shadow,t.globalAlpha=r*s.opacity,t.fill(),s.highlight>0){const h=e.samples.map(f=>{const p=f[a],g=f.center;return{x:p.x+(g.x-p.x)*.2,y:p.y+(g.y-p.y)*.2}}),u=e.samples[Math.floor(e.samples.length/2)][a],d=e.samples[Math.floor(e.samples.length/2)].center;if((u.x-d.x)*o.x+(u.y-d.y)*o.y>0){t.globalAlpha=r*s.highlight,t.strokeStyle="#ffffff",t.lineWidth=Math.max(1,e.samples[0].width*.16),t.beginPath(),t.moveTo(h[0].x,h[0].y);for(const f of h.slice(1))t.lineTo(f.x,f.y);t.stroke()}}}t.restore()}function A5(t,e,n,s){const i=s.bodyContours,o=r=>i[r]&&Ud(t,i[r].outline);if(n.startsWith("arm."))return e<.2&&o("spine");if(n.startsWith("leg."))return e<.2&&o("spine")||e>.85&&o(n.replace("leg.","foot."));if(n.startsWith("foot."))return e<.25&&o(n.replace("foot.","leg."));if(n==="neck")return e<.6&&o("spine");if(n==="spine"){if(e>.85&&o("neck"))return!0;for(const r of["left","right"]){if(e>.6&&o(`arm.${r}`)){const a=s.chains[`arm.${r}`]?.[0];if(a&&Math.hypot(a.x-t.x,a.y-t.y)<s.height*.07)return!0}if(e<.25&&o(`leg.${r}`))return!0}}return!1}function Jd(t,e,n,s,i){const o=s.bodyContours?.[i];if(!o)return!1;if(n.fill==="none"&&(e=oi(t,e)),e.shape(o.outline,n.fill==="none"?null:n.fill,0),e.look==="clean"&&E5(t,o,n),(e.look!=="silhouette"||n.fill==="none")&&s.lineWidth>0){let r=[];for(let a=0;a<=o.outline.length;a++){const l=a%o.outline.length,c=o.outline[l],h=o.outline[(l+1)%o.outline.length],u={x:(c.x+h.x)/2,y:(c.y+h.y)/2};i.startsWith("arm.")&&o.positions[l]===1||A5(u,o.positions[l],i,s)?(r.length>=2&&e.line(r,s.lineWidth),r=[]):(r.length===0&&r.push(c),r.push(h))}r.length>=2&&e.line(r,s.lineWidth)}return!0}function Zd(t){return[[.01,-.12,.8],[0,-.25,.98],[-.04,-.31,.8]].map(e=>is(t,e).point)}function Qd(t,e){const n=e.shape==="angular"?$5(t,e):e.projection==="volume"?P5(t):wo(t.center.x,t.center.y,t.rx,t.ry,t.angle);if(e.projection!=="volume"||!e.nose)return n;const s=Math.cos(t.angle),i=Math.sin(t.angle),o=u=>({x:((u.x-t.center.x)*s+(u.y-t.center.y)*i)/t.rx,y:((u.x-t.center.x)*i-(u.y-t.center.y)*s)/t.ry}),r=o(Zd(t)[1]),a=Math.sign(r.x),l=r.y,c=n.flatMap((u,d)=>{const f=o(u),p=o(n[(d+1)%n.length]);if(f.y>l==p.y>l)return[];const g=(l-f.y)/(p.y-f.y);return[(f.x+(p.x-f.x)*g)*a]}),h=Math.max(0,r.x*a-Math.max(...c));return!Number.isFinite(h)||h===0?n:n.flatMap((u,d)=>{const f=n[(d+1)%n.length],p=o(u),g=o(f),m=Math.max(1,Math.ceil(Math.hypot(g.x-p.x,g.y-p.y)/.025));return Array.from({length:m},(b,v)=>{const k=v/m,w={x:u.x+(f.x-u.x)*k,y:u.y+(f.y-u.y)*k},T=o(w),P=(T.y-l+.115)/.23;if(T.x*a<.5||P<=0||P>=1)return w;const S=Math.sin(P*Math.PI)**2*h*t.rx*a;return{x:w.x+S*s,y:w.y+S*i}})})}function $5(t,e){const n=Math.min(.95,Math.max(.55,e.jawWidth??.74)),s=Math.min(.35,Math.max(.03,e.chinWidth??.14)),i=[[-1,0],[-.92,s],[-.5,n],[-.12,Math.sqrt(1-.12**2)]];for(let o=0;o<=12;o++){const r=o*Math.PI/24;i.push([Math.sin(r),Math.cos(r)])}return tf(t,i,e.jawRoundness??0,e.projection==="volume")}function P5(t){const e=Array.from({length:41},(n,s)=>{const i=-Math.PI/2+s*Math.PI/40;return[Math.sin(i),Math.cos(i)]});return tf(t,e,0,!0)}function tf(t,e,n,s){const i=[];for(const[a,l]of e)for(let c=0;c<40;c++){const h=c*Math.PI/20,u=l*Math.sin(h);i.push(is(t,[l*Math.cos(h),a,s?Math.min(u,.82):u]).point)}let o=yl(i);if(n=Math.min(1,Math.max(0,n)),n===0)return o;const r=n*.25;for(let a=0;a<3;a++)o=o.flatMap((l,c)=>{const h=o[(c+1)%o.length];return[{x:l.x+(h.x-l.x)*r,y:l.y+(h.y-l.y)*r},{x:h.x+(l.x-h.x)*r,y:h.y+(l.y-h.y)*r}]});return o}function yl(t){const e=t.sort((i,o)=>i.x-o.x||i.y-o.y),n=(i,o,r)=>(o.x-i.x)*(r.y-i.y)-(o.y-i.y)*(r.x-i.x),s=i=>{const o=[];for(const r of i){for(;o.length>=2&&n(o[o.length-2],o[o.length-1],r)<=0;)o.pop();o.push(r)}return o.slice(0,-1)};return[...s(e),...s([...e].reverse())]}const ef=.34,Xt=.12,Gt=-.4,Ut=(t,e,n)=>t[e]??n,I5=(t,e)=>Math.max(0,t)*(1-Math.min(1,Math.max(0,e))),O5=.45,_5=.35,C5=.7,nf=.78;function xt(t,e,n,s="cartoon"){const i=f=>Math.sqrt(Math.max(0,1-f.x*f.x-f.y*f.y));let o=is(t,[n.x,n.y,i(n)]).facing;const r=t.axes[2];s==="volume"&&n.x*r[0]>0&&(o=Math.max(o,r[2]));const a=Math.atan2(r[0],r[2]),l=Math.cos(a),c=Math.max(_5,l),h=Math.max(C5,l),u=Math.cos(t.angle),d=Math.sin(t.angle);if(s==="volume"){const f=is(t,[n.x,n.y,i(n)*nf]).point,p=Math.abs(n.x)>.1?Math.min(1,Math.max(0,o)/.25):1,g=Math.max(n.x*r[0]>0?.2:.5,l);return{facing:o,points:e.map(m=>{const b=(m.x-n.x)*g*t.rx*p,v=(m.y-n.y+r[1]*(i(m)-i(n))*nf)*t.ry*p;return{x:f.x+b*u+v*d,y:f.y+b*d-v*u}})}}return{facing:o,points:e.map(f=>{const p=O5*Math.sin(a)+n.x*c+(f.x-n.x)*h,g=f.y+r[1]*i(f),m=p*t.rx,b=g*t.ry;return{x:t.center.x+m*u+b*d,y:t.center.y+m*d-b*u}})}}const Je=(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}}),mi=(t,e,n,s)=>{const i=Math.min(1,Math.max(0,(s-t.x)/(n.x-t.x))),o=1-i;return o*o*t.y+2*o*i*e.y+i*i*n.y},Oe=(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}}),An=.05,H5=.3,R5="#e06b7d";function L5(t,e,n,s,i={},o){const r=Math.max(1,Math.min(s*.6,.14*e.rx)),a=(A,O)=>xt(e,A,O,i.projection).points,l=(A,O)=>xt(e,[],{x:A,y:O},i.projection).facing,c=Ut(n,"smile",0),h=Ut(n,"blink",0),u=Ut(n,"lookX",0),d=Ut(n,"lookY",0),f=Ut(n,"browTilt",0),p=Math.max(.2,Ut(n,"pupil",1)),g=Math.min(1,Math.max(0,Ut(n,"lid",0))),m=Math.min(1,Math.max(0,Ut(n,"bulge",0)));for(const A of[1,-1]){const O=A===1?"left":"right",H=ef*A;if(l(H,Xt)<An)continue;const W={x:H,y:Xt},j=I5(Ut(n,`eye.${O}`,1),h);if(j<.2||i.style==="anime"&&g>=.98){const L=c>.5?.12:-.06;t.line(a(Je({x:H-.12,y:Xt},{x:H,y:Xt+L},{x:H+.12,y:Xt}),W),r)}else if(i.style==="anime")F5(t,e,W,A,j,g,m,p,u,d,r,i,o);else{const L=j>1.2||m>.02,q=.13*Math.max(j,1)*(1+m*.7);L&&t.shape(a(Oe(H,Xt,q*.85,q),W),"#ffffff",r);const G=(j>1.2?.075:.1)*p*(1+m*.3),C=H+u*.08,Y=Xt-d*.07,st=Oe(C,Y,G,G*1.1*Math.min(j,1));if(t.shape(a(st,W),t.ink,0),i.inPupil&&o){const[$]=a([{x:C,y:Y}],W),_=a(st,W),z=Math.min(..._.map(K=>Math.hypot(K.x-$.x,K.y-$.y)));z>.5&&(o.save(),o.beginPath(),o.arc($.x,$.y,z,0,Math.PI*2),o.clip(),i.inPupil(o,{x:$.x,y:$.y,r:z,side:O}),o.restore())}if(g>.02){const $=L?q*1.15:G*1.4,_=Xt+$,z=_-$*2*g,K=$*1.1;t.shape(a([{x:H-K,y:_+.02},{x:H+K,y:_+.02},{x:H+K,y:z},{x:H-K,y:z}],W),i.skin??"#ffffff",0),t.line(a([{x:H-K,y:z},{x:H+K,y:z}],W),r)}}const J=Xt+(i.style==="anime"?.38:.3)+Ut(n,`brow.${O}`,0)*.14+Math.max(0,j-1)*.12,tt={x:H+A*.13,y:J},V={x:H-A*.13,y:J+f*.1};t.line(a([tt,{x:(tt.x+V.x)/2,y:(tt.y+V.y)/2},V],{x:H,y:J}),r)}W5(t,e,n,r,i.projection),N5(t,e,i.ageLines??0,r,i.projection);const b={x:0,y:Gt};if(l(0,Gt)<-An)return;i.nose&&l(0,Xt-.15)>=An&&(i.projection==="volume"?t.line(Zd(e),r):t.line(a([{x:.01,y:Xt-.1},{x:.03,y:Gt+.2},{x:-.05,y:Gt+.17}],{x:0,y:Gt+.22}),r));const v=.25*Math.max(.3,Ut(n,"mouthWidth",1)),k=Math.min(1,Math.max(0,Ut(n,"mouth",0)));if(k<=.05){t.line(a(Je({x:-v,y:Gt},{x:0,y:Gt-c*.25},{x:v,y:Gt}),b),r);return}const w=.3*k;let T,P,S,x;if(c>.3){const A=Gt+.05,O={x:0,y:Gt-w*2};T=[...Je({x:v,y:A},O,{x:-v,y:A})],P=()=>A,S=H=>mi({x:v,y:A},O,{x:-v,y:A},H),x=.85}else if(c<-.3){const A=Gt-w*.6,O={x:0,y:Gt+w*1.4};T=[...Je({x:v,y:A},O,{x:-v,y:A})],P=H=>mi({x:v,y:A},O,{x:-v,y:A},H),S=()=>A,x=.5}else{const A=v*.8;T=Oe(0,Gt,A,w);const O=H=>w*Math.sqrt(Math.max(0,1-(H/A)**2));P=H=>Gt+O(H),S=H=>Gt-O(H),x=.5}if(t.shape(a(T,b),t.ink,0),k<H5)return;const M=P(0)-S(0),E=v*x,I=(A,O,H=8)=>Array.from({length:H+1},(W,j)=>A+(O-A)*j/H);if(i.tongue){const A=E*.55,O=I(A,-A).map(W=>({x:W,y:S(W)})),H=Je({x:-A,y:S(-A)},{x:0,y:S(0)+M*.8},{x:A,y:S(A)},8);t.shape(a([...O,...H.slice(1,-1)],b),R5,0)}if(i.teeth){const A=Math.min(.06,M*.4),O=I(-E,E).map(W=>({x:W,y:P(W)})),H=O.map(({x:W,y:j})=>({x:W*.92,y:j-A})).reverse();t.shape(a([...O,...H],b),"#ffffff",0);for(const W of[-.5,0,.5]){const j=E*W;t.line(a([{x:j,y:P(j)},{x:j*.92,y:P(j)-A}],b),r*.6)}}}function F5(t,e,n,s,i,o,r,a,l,c,h,u,d){const{x:f,y:p}=n,g=Math.min(1.2,Math.max(.5,u.eyeScale??1)),m=Math.min(1.2,Math.max(.45,u.eyeAspect??1)),b=.21*g*(1+r*.15),v=.25*g*m*Math.min(i,1.6)*(1-o)*(1+r*.3),k={x:f-b,y:p},w={x:f+b,y:p},T={x:f,y:p+v*1.9},P={x:f,y:p-v*1.35},S=Je(k,T,w),x=Je(w,P,k),M=J=>xt(e,J,n,u.projection).points,E=J=>J.map(tt=>{const V=Math.min(w.x,Math.max(k.x,tt.x));return{x:V,y:Math.min(mi(k,T,w,V),Math.max(mi(w,P,k,V),tt.y))}});t.shape(M([...S,...x.slice(1,-1)]),"#ffffff",h*.5);const I=f+Math.max(-1,Math.min(1,l))*.07*g,A=p-Math.max(-1,Math.min(1,c))*.055*g,O=.115*g,H=.185*g;t.shape(M(E(Oe(I,A,O,H,24))),u.iris??"#4b7fce",h*.4),t.shape(M(E(Oe(I,A-.075*g,O*.7,H*.35))),"rgba(255,255,255,0.25)",0);const W=Math.min(.085,.042*a)*g,j=E(Oe(I,A,W,W*1.35));if(t.shape(M(j),t.ink,0),u.inPupil&&d){const[J]=M([{x:I,y:A}]),tt=Math.min(...M(j).map(V=>Math.hypot(V.x-J.x,V.y-J.y)));tt>.5&&(d.save(),d.beginPath(),d.arc(J.x,J.y,tt,0,Math.PI*2),d.clip(),u.inPupil(d,{...J,r:tt,side:s===1?"left":"right"}),d.restore())}if(t.shape(M(E(Oe(I-.038*g,A+.075*g,.035*g,.045*g))),"#ffffff",0),t.shape(M(E(Oe(I+.04*g,A-.04*g,.014*g,.02*g))),"#ffffff",0),t.line(M(S),h*1.1),u.lashes!==!1)for(const J of[0,.035]){const tt=f+s*(b-J),V=mi(k,T,w,tt);t.line(M([{x:tt,y:V},{x:tt+s*.055,y:V+.07}]),h*.75)}}function N5(t,e,n,s,i){const o=Math.min(1,Math.max(0,n));if(!(o<=0))for(const r of[-1,1]){const a={x:r*.59,y:Xt};if(xt(e,[],a,i).facing<An)continue;for(const h of[-.06,.035]){const u=[{x:a.x,y:a.y},{x:a.x+r*.1,y:a.y+h}];t.line(xt(e,u,a,i).points,s*.45*o)}const l={x:r*.3,y:-.38},c=Je({x:l.x,y:-.31},{x:l.x+r*.07,y:-.4},{x:l.x+r*.035,y:-.49});t.line(xt(e,c,l,i).points,s*.35*o)}}const sf="#8fd0f5",of=(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 W5(t,e,n,s,i){const o=Math.min(1,Math.max(0,Ut(n,"blush",0))),r=Math.min(1,Math.max(0,Ut(n,"tears",0))),a=Math.min(1,Math.max(0,Ut(n,"sweat",0)));if(!(o+r+a<=.01)){for(const l of[1,-1]){const c={x:.5*l,y:-.16},h=xt(e,[],c,i).facing>=An;if(o>.01&&h){const{points:d}=xt(e,Oe(c.x,c.y,.17,.1),c,i);if(t.shape(d,`rgba(240, 120, 140, ${(.75*o).toFixed(3)})`,0),o>.5)for(const f of[-.07,0,.07]){const p=[{x:c.x+f-.018,y:c.y-.03},{x:c.x+f+.018,y:c.y+.03}];t.line(xt(e,p,c,i).points,s*.3)}}const u={x:ef*l,y:Xt};if(r>.01&&xt(e,[],u,i).facing>=An){const d=.05+.04*r,f={x:u.x+.06*l,y:Xt-.2-.12*r};if(t.shape(xt(e,of(f.x,f.y,d),f,i).points,sf,s*.35),r>.6){const p=[{x:u.x+.05*l,y:Xt-.1},{x:f.x,y:f.y+d*.8}];t.line(xt(e,p,f,i).points,s*.3)}}}if(a>.01){const l={x:.64,y:.42};xt(e,[],l,i).facing>=An&&t.shape(xt(e,of(l.x,l.y,.05+.05*a),l,i).points,sf,s*.35)}}}const D5=15;function xe(t,e){const n=Math.sqrt(Math.max(0,1-e*e));return[n*Math.sin(t),e,n*Math.cos(t)]}const B5=([t,e,n])=>{const s=Math.hypot(t,e,n)||1;return[t/s,e/s,n/s]};function te(t,[e,n,s]){const[i,o,r]=t.axes;return i[2]*e+o[2]*n+r[2]*s}function _t(t,e){return is(t,e).point}function Yo(t,e){const n=Math.abs(t-e)%(Math.PI*2);return n>Math.PI?Math.PI*2-n:n}function Ko(t,e,n=64){const s=e.top??1,i=e.bottom??-1,o=Math.max(8,Math.ceil((s-i)*D5)),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):B5(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 b=0;b<n;b++){const v=p*n+b;if(g){h[v]=-1;continue}const k=a(b);h[v]=e.inside(k,m),u[v]=h[v]>-.35?te(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 A=0;A<c;A++)for(let O=0;O<=n;O++){const H=A*n+(O===n?0:O);m[A*g+O]=Math.min(h[H],p*u[H])}const b=(A,O)=>m[O*g+A],v=(A,O,H,W)=>{const j=b(A,O),J=b(H,W),tt=j===J?.5:Math.min(1,Math.max(0,j/(j-J)));return _t(t,e.position(a(A+(H-A)*tt),r(O+(W-O)*tt)))},k=n*c*2,w=new Int32Array(k).fill(-1),T=new Int32Array(k).fill(-1),P=new Map,S=(A,O,H)=>{const W=(H*n+d(O))*2+(A?1:0);return P.has(W)||P.set(W,A?v(d(O),H,d(O),H+1):v(O,H,O+1,H)),W},x=(A,O)=>{w[A]===-1?w[A]=O:T[A]=O},M=(A,O)=>{x(A,O),x(O,A)};for(let A=0;A<c-1;A++)for(let O=0;O<n;O++){const H=A*g+O,W=(m[H]>0?8:0)|(m[H+1]>0?4:0)|(m[H+g+1]>0?2:0)|(m[H+g]>0?1:0);if(W===0||W===15)continue;const j=()=>S(!1,O,A),J=()=>S(!1,O,A+1),tt=()=>S(!0,O,A),V=()=>S(!0,O+1,A);switch(W){case 1:case 14:M(tt(),J());break;case 2:case 13:M(J(),V());break;case 3:case 12:M(tt(),V());break;case 4:case 11:M(j(),V());break;case 6:case 9:M(j(),J());break;case 7:case 8:M(tt(),j());break;case 5:case 10:{const L=(b(O,A)+b(O+1,A)+b(O+1,A+1)+b(O,A+1))/4>0;W===5===L?(M(tt(),j()),M(J(),V())):(M(tt(),J()),M(j(),V()));break}}}const E=[],I=new Uint8Array(k);for(const A of P.keys()){if(I[A])continue;const O=[];let H=-1,W=A;for(;W!==-1&&!I[W];){I[W]=1,O.push(P.get(W));const j=w[W],J=T[W],tt=j!==-1&&j!==H&&!I[j]?j:J!==-1&&J!==H&&!I[J]?J:-1;H=W,W=tt}O.length>=3&&E.push(O)}return E};return{near:f(1),far:f(-1)}}const rf=new WeakMap;function bl(t,e,n){let s=rf.get(t);s||rf.set(t,s=new Map);let i=s.get(e);return i||s.set(e,i=n()),i}function wl(t,e,n,s){if(t.save(),t.beginPath(),t.rect(-1e5,-1e5,2e5,2e5),s?.length){t.moveTo(s[0].x,s[0].y);for(const i of s.slice(1))t.lineTo(i.x,i.y);t.closePath()}else 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 af(t,e,n,s=.04){const i=[];let o=[];return e.forEach((r,a)=>{te(t,n[a])>s?o.push(_t(t,r)):(o.length>=2&&i.push(o),o=[])}),o.length>=2&&i.push(o),i}const lf=t=>t*Math.PI/180,kl=t=>{const e=Math.hypot(...t)||1;return t.map(n=>n/e)},z5=(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]];function cf(t,e,n){return t>=e+n?t:t<=e-n?e:e+(t-e+n)**2/(4*n)}function vl(t,e,n){const s=kl(n),i=t.reduce((c,h,u)=>c+h*s[u],0),r=t.map((c,h)=>c-i*s[h]).reduce((c,h)=>c+h*h,0),a=Math.sqrt(cf(1-r,e*e,e*e)),l=cf(i,a,e)-i;return l===0?t:t.map((c,h)=>c+s[h]*l)}function q5(t){if(t.path.length<4||(t.path.length-1)%3!==0)throw new Error("hair: a lock path needs a root and groups of three cubic points");if(!Number.isFinite(t.width)||t.width<=0||t.follow!==void 0&&(!Number.isFinite(t.follow)||t.follow<0))throw new Error("hair: lock width must be positive and follow must be nonnegative");for(const n of t.path)if(!Number.isFinite(n.around)||!Number.isFinite(n.up)||n.up>1||n.lift!==void 0&&(!Number.isFinite(n.lift)||n.lift<0))throw new Error("hair: lock points need finite around/up values, up <= 1 and nonnegative lift");const e=t.path[0];if(e.up<0||(e.lift??0)!==0)throw new Error("hair: a lock root must lie on the scalp (up 0..1, lift 0)");return{...t,path:t.path.map(n=>({...n}))}}function j5(t,e,n,s){const i=(t.path.length-1)/3,o=i*20,r=[],a=[],l=s.trail!==0||s.lift!==0,c=Math.max(0,e+n);for(let h=0;h<=o;h++){const u=h/o,d=Math.min(i-1,Math.floor(u*i)),f=u*i-d,p=1-f,g=[p**3,3*p*p*f,3*p*f*f,f**3],m=t.path.slice(d*3,d*3+4),b=lf(m.reduce((H,W,j)=>H+W.around*g[j],0)),v=m.reduce((H,W,j)=>H+W.up*g[j],0),k=m.reduce((H,W,j)=>H+(W.lift??0)*g[j],0),w=1+e+n+k,T=v>=0?Math.sqrt(Math.max(0,1-v*v)):1,P=u*u*(t.follow??1),S=lf(s.swing)*P,x=b-S,M=[Math.sin(x)*T*w,v*(v>=0?w:1),Math.cos(x)*T*w],E=[M[0],M[1]+s.lift*P,M[2]-s.trail*P],I=[Math.sin(x)*T,Math.max(0,v),Math.cos(x)*T],A=kl(M),O=l&&P>0?vl(E,c,A):E;a.push(A),r.push({center:O,normal:I,left:O,right:O,t:u})}return r.forEach((h,u)=>{const d=r[Math.max(0,u-1)].center,p=r[Math.min(o,u+1)].center.map((b,v)=>b-d[v]),g=kl(z5(h.normal,p)),m=t.width*Math.sin(Math.PI*h.t)**.6*.5;h.left=h.center.map((b,v)=>b+g[v]*m),h.right=h.center.map((b,v)=>b-g[v]*m),l&&h.t>0&&(t.follow??1)>0&&(h.left=vl(h.left,c,a[u]),h.right=vl(h.right,c,a[u]))}),r}const ls=(t,e,n)=>t.map((s,i)=>s+(e[i]-s)*n);function Y5(t,e,n){const s=n?1:-1,i=[];let o=[];for(let r=0;r<e.length;r++){const a=e[r],l=s*te(t,a.normal)>=0;if(r>0){const c=e[r-1],h=s*te(t,c.normal),u=s*te(t,a.normal);if(h>=0!==l){const d=h/(h-u),f={center:ls(c.center,a.center,d),left:ls(c.left,a.left,d),right:ls(c.right,a.right,d),normal:ls(c.normal,a.normal,d),t:c.t+(a.t-c.t)*d};l?o=[f]:(o.push(f),o.length>=2&&i.push(o),o=[])}}l&&o.push(a)}return o.length>=2&&i.push(o),i}function hf(t,e,n,s,i,o,r){const a=(n.locks??[]).map(h=>j5(h,n.volume,s,i)),l=h=>h.reduce((u,d)=>u+te(e,d.center),0)/h.length;a.sort((h,u)=>l(h)-l(u));const c=Math.max(.7,o*.35);for(const h of a)for(const u of Y5(e,h,r)){const d=u.map(g=>_t(e,g.left)),f=u.map(g=>_t(e,g.right));if(t.shape([...d,...f.slice().reverse()],n.color,0),t.look==="clean"&&(n.shine??0)>0){const g=u.filter(m=>m.t>=.2&&m.t<=.75);if(g.length>=3){const m=g.map((v,k)=>{const w=.16*Math.sin(Math.PI*k/(g.length-1));return _t(e,ls(v.center,v.left,.16+w))}),b=g.map(v=>_t(e,ls(v.center,v.left,.16)));t.shape([...m,...b.reverse()],`rgba(255,255,255,${n.shine})`,0)}}const p=u.filter(g=>g.t>.3);p.length>=2&&t.line(p.map(g=>_t(e,g.left)),c)}}const Pt=(t,e,n=0)=>({around:t,up:e,lift:n}),Ml=()=>[{width:.66,follow:.22,path:[Pt(-38,.88),Pt(-12,.94,.08),Pt(58,.76,.09),Pt(94,.16,.03)]},{width:.58,follow:.3,path:[Pt(-42,.8),Pt(-24,.7,.12),Pt(18,.57,.09),Pt(64,.3)]},{width:.36,follow:.18,path:[Pt(-58,.76),Pt(-76,.56,.07),Pt(-90,.12,.06),Pt(-102,-.36)]}];function uf(t){return[-100,-130,-160,-190,-220,-250,-280].map((e,n)=>{const s=n%2===0?1:-1,i=t?-2.45-n%3*.12:-1.06-n%3*.09;return{width:t?.88:.92,follow:t?.8+n%3*.12:.38+n%3*.08,path:t?[Pt(e,.7),Pt(e+s*9,.2,.12),Pt(e-s*13,-.5,.2),Pt(e-s*8,-.95,.16),Pt(e-s*3,-1.4,.12),Pt(e+s*18,i+.35,.22),Pt(e+s*12,i,.03)]:[Pt(e,.7),Pt(e+s*7,.15,.2),Pt(e-s*8,-.75,.25),Pt(e+s*5,i)]}})}const K5={softSweep:{volume:.12,shine:.16,part:-38,strands:"part",sweep:-.08,hairline:{front:.64,side:.12,back:-.8},locks:Ml()},flowingBob:{volume:.15,shine:.16,length:.96,fall:{taper:.08,wave:.08},part:-38,strands:"part",sweep:-.08,hairline:{front:.64,side:.08,back:-.8},coversEars:!0,locks:[...uf(!1),...Ml()]},cascadingWaves:{volume:.16,shine:.16,length:2.38,fall:{taper:.18,wave:.12},part:-38,strands:"part",sweep:-.08,hairline:{front:.64,side:.08,back:-.8},coversEars:!0,locks:[...uf(!0),...Ml()]}},cs={swing:0,trail:0,lift:0};function yi(t){if(!t)return cs;const e=t["hair.swing"]??0,n=t["hair.trail"]??0,s=t["hair.lift"]??0;return e===0&&n===0&&s===0?cs:{swing:e,trail:n,lift:s}}const df=t=>t.swing===0&&t.trail===0&&t.lift===0;function ff(t){return t.length>0||t.ties.some(e=>e.kind!=="bun")||(t.locks??[]).some(e=>(e.follow??1)>0)}function Sl([t,e,n],s){if(s===0)return[t,e,n];const i=Math.cos(s),o=Math.sin(s);return[t*i-n*o,e,n*i+t*o]}const gf={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},pf=1.75,xl={...K5,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}},mangaSpikes:{volume:.12,texture:"spiky",textureAmount:.08,hairline:{front:.55,side:.12,back:-.7},spikes:[{around:-100,up:.4,length:.55,width:.24},{around:-65,up:.7,length:.6,width:.25},{around:-25,up:.93,length:.6,width:.24},{around:40,up:.87,length:.7,width:.25},{around:85,up:.55,length:.55,width:.24},{around:160,up:.8,length:.5,width:.24},{around:-160,up:.65,length:.55,width:.24}]},mangaSweep:{volume:.14,texture:"spiky",textureAmount:.1,sweep:-.35,hairline:{front:.5,side:.08,back:-.8},spikes:[{around:-95,up:.45,length:.35,width:.2},{around:-60,up:.8,length:.4,width:.24},{around:75,up:.55,length:.4,width:.23},{around:150,up:.75,length:.35,width:.2}]},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:pf,opening:84,part:0,strands:"part",hairline:{front:.5,side:.05,back:-.85},coversEars:!0},shoulderWaves:{volume:.22,length:pf,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}},Te={black:"#22201f",brown:"#6b4630",chestnut:"#7b4a2b",auburn:"#9a4426",blond:"#d9b55a",ginger:"#c8662f",gray:"#a7a29c",white:"#ecebe7"};function mf(t){const e=typeof t=="string"?{style:t}:t,n=e.style?xl[e.style]:{};if(e.style&&!n)throw new Error(`hair: unknown style '${e.style}'`);const{style:s,hairline:i,...o}=e,r={...gf,...n,...o,hairline:{...gf.hairline,...n.hairline,...i},ties:(o.ties??n.ties??[]).map(a=>({...a})),...o.spikes??n.spikes?{spikes:(o.spikes??n.spikes).map(a=>({...a}))}:{},...o.locks??n.locks?{locks:(o.locks??n.locks).map(q5)}:{},...o.fall??n.fall?{fall:{...o.fall??n.fall}}:{}};if(r.shine!==void 0&&(!Number.isFinite(r.shine)||r.shine<0||r.shine>1))throw new Error("hair: shine must be between 0 and 1");if(r.fall&&(!Number.isFinite(r.fall.taper)||r.fall.taper<0||r.fall.taper>1||!Number.isFinite(r.fall.wave)||r.fall.wave<0))throw new Error("hair: fall needs taper between 0 and 1 and nonnegative wave");return r}const $n=t=>t*Math.PI/180,hs=(t,e,n)=>{const s=Math.min(1,Math.max(0,(n-t)/(e-t)));return s*s*(3-2*s)},Tl=t=>1-Math.abs(2*(t-Math.floor(t))-1);function bi(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*Tl(e*11/(Math.PI*2))*c),h}function yf(t,e,n){const s=t.textureAmount;switch(t.texture){case"spiky":return s*(Tl(e*11/(Math.PI*2))*Tl(n*2.6+.5))**1.2*hs(-.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 bf(t,e,n=cs){const s=t.length>0,i=new Map,o=h=>{let u=i.get(h);return u===void 0&&i.set(h,u=bi(t,h)),u},r=$n(t.opening),a=h=>t.length+(t.texture==="wavy"||t.texture==="curly"||t.texture==="locs"?.12*Math.sin(h*9):0)+(t.fall?.wave??0)*Math.cos(h*3+.6),l=(h,u,d)=>{if(t.flat<=0||u<.45)return null;const f=(u-.45)/.55,p=Math.sqrt(1-.45*.45)*d*(1-f**5),g=.45+(1+t.flat-.45)*Math.min(1,f*1.8);return[p*Math.sin(h),g*(1+e),p*Math.cos(h)]},c={top:1,bottom:s?-(t.length+.25+Math.abs(t.fall?.wave??0)):-1,inside(h,u){const d=u-o(h);if(!s)return d;const f=Math.min(u+a(h),Yo(h,0)-r);return Math.max(d,f)},position(h,u){if(s&&u<0){const k=t.length<1.5?.14*hs(-t.length+.45,-t.length-.1,u):0,w=(t.fall?.taper??0)*hs(0,-Math.max(.1,a(h)),u),T=1+e+t.volume*(1-k*2.5)+yf(t,h,u)-k-w;return[T*Math.sin(h),u,T*Math.cos(h)]}const d=.4+.6*hs(0,.3,u-bi(t,h)),f=1+e+(t.volume+yf(t,h,u))*d,p=l(h,u,f);if(p)return p;const[g,m,b]=xe(h,u),v=[g*f,m*f,b*f];if(t.quiff>0){const k=t.quiff*Math.exp(-((h/.7)**2))*hs(.15,.85,u);v[1]+=k*.7,v[2]+=k*.45}return v},normal(h,u){return s&&u<0?[Math.sin(h),0,Math.cos(h)]:xe(h,u)}};return s&&!df(n)?X5(c,t,n):c}function X5(t,e,n){const s=o=>o<0?hs(-.15,-Math.max(.7,e.length),o):0,i=o=>$n(n.swing)*s(o);return{top:t.top,bottom:t.bottom,inside:(o,r)=>t.inside(o+i(r),r),position(o,r){const a=s(r);if(a===0)return t.position(o,r);const l=i(r),[c,h,u]=Sl(t.position(o+l,r),l);return[c,h+n.lift*a,u-n.trail*a]},normal:(o,r)=>Sl(t.normal(o+i(r),r),i(r))}}const G5=t=>t.texture==="spiky"||t.texture==="curly"||t.texture==="locs"?104:t.texture==="wavy"?80:64;function wf(t,e,n,s){return bl(t,V5(e,s),()=>Ko(t,n,G5(e)))}const kf=new WeakMap;let U5=1;function V5(t,e){if(df(e))return t;let n=kf.get(t);return n||kf.set(t,n=U5++),`${n}:${e.swing}:${e.trail}:${e.lift}`}function vf(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 El(t,[e,n,s]){const i=_t(t,[e,n,s]);return{x:i.x-t.center.x,y:i.y-t.center.y}}function J5(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 Z5(t,e,n,s,i){const o=t.ry,r=(e.length??1.8)*o,a=El(t,Sl(s,$n(i.swing))),l=El(t,[0,i.lift,-i.trail]),c=Math.hypot(a.x,a.y)||1,h=e.at==="high"||e.at==="low"||e.at==="top"?El(t,[.95,0,0]):{x:0},u=e.kind==="braid"?.15:.5,d={x:n.x+a.x/c*o*u+h.x*.9+l.x*.5,y:n.y+a.y/c*o*u*.6+l.y*.5},f={x:n.x+a.x/c*o*u*.6+h.x*1.3+l.x,y:n.y+r+l.y};return J5(n,d,f)}const Xo=t=>Math.max(1,t*.5),Mf=(t,e)=>Math.max(.8,Math.min(t*.4,.1*e.rx));function Sf(t,e,n,s,i,o){const{point:r,out:a}=vf(s.at),l=1+n.volume,c=_t(e,[r[0]*l,r[1]*l,r[2]*l]),h=Xo(i),u=Mf(i,e);if(s.kind==="bun"){const g=s.size??.32,m=_t(e,[r[0]*l+a[0]*g,r[1]*l+a[1]*g,r[2]*l+a[2]*g]);t.ellipse(m.x,m.y,g*e.rx,g*e.ry,e.angle,n.color,h);const b=g*e.rx*.55;t.line(Array.from({length:9},(v,k)=>{const w=-.4+k/8*Math.PI*1.3;return{x:m.x+Math.cos(w)*b,y:m.y+Math.sin(w)*b*.8}}),u);return}const d=Z5(e,s,c,a,o),f=(s.size??(s.kind==="braid"?.2:.34))*e.rx*2;if(s.kind==="ponytail")t.shape(zt(d,f,f*.15),n.color,h),t.line(d.slice(3,d.length-3),u);else{const m=d.slice(0,d.length-3);for(let k=0;k<7;k++){const w=m[Math.floor(k/7*(m.length-1))],T=m[Math.floor((k+1)/7*(m.length-1))],P=Math.atan2(T.y-w.y,T.x-w.x),S=Math.hypot(T.x-w.x,T.y-w.y),x=f*(1-k/(7*2.2)),M=(k%2===0?1:-1)*.35,E={x:(w.x+T.x)/2,y:(w.y+T.y)/2};t.ellipse(E.x,E.y,S*.62,x*.5,P+M,n.color,h*.8)}const b=m[m.length-1],v=d[d.length-1];t.shape(zt([b,v],f*.7,f*.2),n.color,h*.8)}const p=d[s.kind==="braid"?d.length-4:2];t.ellipse(p.x,p.y,f*.32,f*.22,e.angle,n.color,h)}function xf(t,e){return te(t,vf(e.at).out)<-.2}function Q5(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=$n(t.part??0),s=i=>bi(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,bi(t,r)<.9?.6:.9],[r,i],0));return t.part!==null&&o.push(e([n,s(n)],[n,.97])),o}default:return[]}}function tv(t,e,n,s,i){if(s.fill==="stipple"||s.hairline.front>1.5)return;const o=i.motion??cs,r=i.lineWidth*.45/n.rx,{far:a}=wf(n,s,bf(s,r,o),o);wl(e,n,()=>{for(const l of s.ties)xf(n,l)&&Sf(t,n,s,l,i.lineWidth,o);Tf(t,n,s,i.lineWidth,r,!1);for(const l of a)t.shape(l,s.color,Xo(i.lineWidth));hf(t,n,s,r,o,i.lineWidth,!1)},i.headOutline)}function Al(t,e,n,s){if(n.hairline.front>1.5)return;const i=s.motion??cs,o=s.lineWidth*.45/e.rx,r=bf(n,o,i),a=Mf(s.lineWidth,e);if(n.fill==="stipple"){for(let h=.97;h>-1;h-=.17)for(let u=-Math.PI;u<Math.PI;u+=.27){const d=Math.round(h*100)%2*.13;if(r.inside(u+d,h)<.02)continue;const f=xe(u+d,h);if(te(e,f)<.12)continue;const p=_t(e,f);t.dot(p.x,p.y,a*.4)}return}const{near:l}=wf(e,n,r,i),c=Xo(s.lineWidth);Tf(t,e,n,s.lineWidth,o,!0);for(const h of l)t.shape(h,n.color,c);hf(t,e,n,o,i,s.lineWidth,!0);for(const h of Q5(n)){const u=h.map(([f,p])=>{const[g,m,b]=r.position(f,p);return[g*.985,m*.985,b*.985]}),d=h.map(([f,p])=>r.normal(f,p));for(const f of af(e,u,d,.12))t.line(f,a)}for(const h of n.ties)xf(e,h)||Sf(t,e,n,h,s.lineWidth,i)}function Tf(t,e,n,s,i,o){for(const r of n.spikes??[]){const a=xe($n(r.around),Math.max(-1,Math.min(1,r.up)));if(te(e,a)>=0!==o)continue;const l=[Math.cos($n(r.around)),0,-Math.sin($n(r.around))],c=[a[1]*l[2],a[2]*l[0]-a[0]*l[2],-a[1]*l[0]],h=1+n.volume+i,u=Math.max(0,r.width),d=Math.max(0,r.length),f=[_t(e,a.map(p=>p*(h+d)))];for(let p=0;p<8;p++){const g=p*Math.PI/4,m=a.map((b,v)=>b*h+u*(l[v]*Math.cos(g)+c[v]*Math.sin(g)));f.push(_t(e,m))}t.shape(yl(f),n.color,Xo(s))}}const Ef=.35,$l=t=>({centre:[t*.98,-.02,-.08],out:[t,0,-.12]});function Af(t,e,n,s,i){const{centre:o,out:r}=$l(n),a=te(e,r),l=Math.max(1,s.lineWidth*.55),c=s.skin==="none"?null:s.skin,h=e.ry*.27;if(!i){const m=_t(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=_t(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,b)=>{const v=-Math.PI*.55+b/8*Math.PI*1.1,k=Math.cos(v)*d*.45*-n,w=Math.sin(v)*h*.55;return{x:u.x+k*f-w*p,y:u.y+k*p+w*f}});t.line(g,Math.max(.8,l*.7))}function ev(t,e,n,s){wl(e,n,()=>{for(const i of[1,-1])te(n,$l(i).out)<Ef&&Af(t,n,i,s,!1)},s.headOutline)}function nv(t,e,n){for(const s of[1,-1])te(e,$l(s).out)>=Ef&&Af(t,e,s,n,!0)}const Pl={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 $f(t,e){const n=typeof t=="string"?{style:t}:t,s=n.style?Pl[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 Ze=t=>t*Math.PI/180,Go=(t,e,n)=>{const s=Math.min(1,Math.max(0,(n-t)/(e-t)));return s*s*(3-2*s)},Pf={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}},sv=(t,e)=>{const n=Go(Ze(48),Ze(100),Yo(e,0));return t.top[0]+(t.top[1]-t.top[0])*n},iv=t=>t==="sideburns"||t==="muttonChops";function Il(t,e){const n=Pf[t];if(!n)return null;const s=Ze(n.reach),i=o=>{const r=Yo(o,0);return n.shape==="point"?Math.exp(-((r/.42)**2)):n.shape==="square"?1-Go(Ze(45),Ze(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=Yo(o,0),l=sv(n,o);let c=Math.min(l-r,s-a);if(n.band>0&&(c=Math.min(c,r-(l-n.band))),iv(t)){const h=t==="muttonChops"?Ze(70)-Ze(22)*Go(.08,-.6,r):Ze(72);c=Math.min(c,a-h)}return c},position(o,r){const[a,l,c]=xe(o,r),h=1+e+n.volume,u=n.length*i(o)*Go(-.45,-1,r);return[a*h,l*h-u,c*h+u*.25]},normal:(o,r)=>xe(o,r)}}function ov(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 wi=t=>Math.max(1,t*.45);function rv(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=xe(o+r,i);if(te(e,a)<.15)continue;const l=_t(e,a);t.dot(l.x,l.y,s)}}function av(t,e,n,s,i){const o=s.beard==="stubble"?null:Il(s.beard,i.lineWidth*.45/n.rx);if(!o)return;const{far:r}=bl(n,s,()=>Ko(n,o));wl(e,n,()=>{for(const a of r)t.shape(a,s.color,wi(i.lineWidth))},i.headOutline)}function lv(t,e,n,s,i){if(n.beard==="none")return;const o=s.lineWidth*.45/e.rx;if(n.beard==="stubble"){rv(t,e,Il("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}=xt(e,l,{x:0,y:-.6},s.face?.projection);h>-.05&&t.shape(c,n.color,wi(s.lineWidth)*.7);return}const r=Il(n.beard,o);if(!r)return;const{near:a}=bl(e,n,()=>Ko(e,r));for(const l of a)t.shape(l,n.color,wi(s.lineWidth));if(Pf[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}=xt(e,c,{x:0,y:-.42},s.face?.projection);u>-.05&&t.shape(h,s.skin==="none"?"#ffffff":s.skin,0)}}function cv(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}=xt(e,l,i,s.face?.projection);h>-.05&&t.line(c,Math.max(1,s.lineWidth*.32));return}const o=ov(n.moustache);if(!o)return;const{points:r,facing:a}=xt(e,o,i,s.face?.projection);if(!(a<=-.05)&&(t.shape(r,n.color,wi(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(xt(e,c,i,s.face?.projection).points,wi(s.lineWidth)*.8)}}const Ol={round:!0,square:!0,sunglasses:!0};function If(t){const n=(typeof t=="string"?{style:t}:t).style??"round";if(!(n in Ol))throw new Error(`glasses: unknown style '${n}'`);return{style:n}}const Of=.34,Ee=.12,hv=.05;function uv(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:Ee+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:Ee-.01+Math.sign(a)*Math.abs(a)**.45*c}})}function dv(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=Of*r,{points:l,facing:c}=xt(e,uv(n.style,a),{x:a,y:Ee},s.face?.projection);if(c<hv)continue;o.push(r),t.shape(l,n.style==="sunglasses"?"#1f2328":null,i);const h=[r*.97,Ee+.02,-.1];if(te(e,[r,0,0])>.15){const u=xt(e,[{x:a+r*.21,y:Ee+.02}],{x:a,y:Ee},s.face?.projection).points[0];t.line([u,_t(e,h)],i*.9)}}if(o.length===2){const r=[{x:Of-.2,y:Ee+.02},{x:0,y:Ee+.07},{x:-.14,y:Ee+.02}];t.line(xt(e,r,{x:0,y:Ee},s.face?.projection).points,i)}}const Uo={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 _f(t){const e=typeof t=="string"?{style:t}:t,n=e.style??"cap",s=Uo[n];if(!s)throw new Error(`hat: unknown style '${n}'`);return{style:n,color:e.color??s.color}}const Pn=(t,e)=>t.brim[1]+(t.brim[0]-t.brim[1])*(1+Math.cos(e))/2;function fv(t,e){return{top:1,bottom:Math.min(...t.brim)-.05,inside:(n,s)=>s-Pn(t,n),position(n,s){const[i,o,r]=xe(n,s),a=Pn(t,n),l=s>a?(o-a)*(t.height-1):0;return[i*e,o*e+l,r*e]},normal:(n,s)=>xe(n,s)}}function gv(t,e,n){const i=(o,r,a)=>{const l=Pn(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(_t(t,[Math.sin(l)*(n+c*.25),Pn(e,l)*n-.07*Math.cos(l),Math.cos(l)*(n+c)])),r.push(_t(t,i(l,n,0)))}return[...o,...r.reverse()]}return e.ring?Array.from({length:48},(o,r)=>_t(t,i(Math.PI*2*r/48,n+e.ring,.07))):null}function pv(t){const e=s=>Array.from({length:13},(i,o)=>[s,Pn(t,s)+(.97-Pn(t,s))*o/12]),n=s=>Array.from({length:49},(i,o)=>{const r=-Math.PI+Math.PI*2*o/48;return[r,Pn(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 Cf(t,e,n,s){const i=Uo[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=gv(e,i,r);l&&t.shape(l,n.color,a);const c=fv(i,r),{near:h,far:u}=Ko(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 pv(i)){const p=f.map(([m,b])=>{const[v,k,w]=c.position(m,b);return[v*.99,k*.99,w*.99]}),g=f.map(([m,b])=>xe(m,b));for(const m of af(e,p,g,.1))t.line(m,d)}if(i.detail==="seams"){const f=_t(e,[0,r*1.01,0]);t.dot(f.x,f.y,a*.9)}}function Hf(t){const e=t.hair?mf(t.hair):null;return{hair:e,facialHair:t.facialHair?$f(t.facialHair,e?.color):null,glasses:t.glasses?If(t.glasses):null,hat:t.hat?_f(t.hat):null,ears:t.ears??!1}}const Rf=t=>!t.hair&&!t.facialHair&&!t.glasses&&!t.hat&&!t.ears,Lf=t=>t.axes[2][2]<-.3,Ff=t=>t.ears&&!t.hair?.coversEars;function Nf(t,e,n,s,i,o){if(Rf(n))return;const r={...o,headOutline:o.face&&(o.face.shape==="angular"||o.face.projection==="volume")?Qd(s,o.face):void 0};n.hair&&tv(e,t,s,n.hair,{...r,motion:yi(i)}),n.facialHair&&av(e,t,s,n.facialHair,r),Ff(n)&&ev(e,t,s,r)}function mv(t,e,n,s,i,o,r){if(Rf(n)){r();return}const a=Lf(s);Ff(n)&&nv(e,s,o),n.hair&&!a&&!o.faceUnderHair&&Al(e,s,n.hair,{...o,motion:yi(i)}),n.facialHair&&lv(e,s,n.facialHair,o,i.mouthWidth??1),r(),n.hair&&!a&&o.faceUnderHair&&Al(e,s,n.hair,{...o,motion:yi(i)}),n.facialHair&&cv(e,s,n.facialHair,o),n.glasses&&dv(e,s,n.glasses,o),n.hat&&!a&&Cf(e,s,n.hat,{lineWidth:o.lineWidth,hairVolume:n.hair?.volume??0})}function Wf(t,e,n,s,i,o){Lf(s)&&(n.hair&&Al(e,s,n.hair,{...o,motion:yi(i)}),n.hat&&Cf(e,s,n.hat,{lineWidth:o.lineWidth,hairVolume:n.hair?.volume??0}))}const Df=40,yv=.215+.205,le=(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},gt=(t,e)=>t[e]??lt[e]??0;function Vo(t,e,n=lt,s=1){const i=li(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={...lt,...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"]=gt(n,"leg.left.ankle")-(i.tiptoe??0),d["leg.right.ankle"]=gt(n,"leg.right.ankle")-(i.tiptoe??0);for(const[f,p]of[["left",-1],["right",1]])gt(n,`arm.${f}.spread`)>Df||gt(n,`arm.${f}.swing`)>Df||(d[`arm.${f}.swing`]=h+p*i.arm*r,d[`arm.${f}.elbow`]=gt(n,`arm.${f}.elbow`)+u+i.elbow*Math.max(0,p*r));return d.lean=gt(n,"lean")+i.lean*s,d.bend=gt(n,"bend")+(i.bend??0),d["head.nod"]=gt(n,"head.nod")-i.lean*.5*s+(i.headTilt??0),d.side=gt(n,"side")+(i.sway??0)*Math.sin(o),d.lift=gt(n,"lift")+(i.bounce??0)*s*l,d.stretch=gt(n,"stretch")*(1+(i.squash??0)*(l-.5)),d}function Jo(t,e,n=1,s=1){const i=li(t);return 4*yv*s*e*Math.sin(i.swing*n*Math.PI/180)}const us=t=>cl[t],Zo={take:t=>[{after:140,pose:{stretch:.8,bend:10,lean:gt(t,"lean")-4,...le("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,...le("arm",{spread:150,bend:35,swing:0,elbow:0}),...le("leg",{swing:25,knee:60}),...us("shocked")},easing:"ease-out-cubic"},{after:720,pose:{lift:.25,stretch:1.25,bend:-10,...le("arm",{spread:140})},easing:"ease-in-out"},{after:900,pose:{lift:0,stretch:.74,bend:12,...le("arm",{spread:70,bend:0}),...le("leg",{swing:30,knee:60})},easing:"ease-in-quad"},{after:1060,pose:{stretch:1.06,bend:-3,...le("arm",{spread:60}),"leg.left.swing":gt(t,"leg.left.swing"),"leg.right.swing":gt(t,"leg.right.swing"),"leg.left.knee":gt(t,"leg.left.knee"),"leg.right.knee":gt(t,"leg.right.knee")},easing:"ease-out"},{after:1260,pose:{stretch:gt(t,"stretch"),bend:gt(t,"bend"),...us("surprised"),...le("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":gt(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":gt(t,"head.nod")-10,bend:gt(t,"bend")-10,lift:.05,stretch:1.18,...us("shocked"),lookX:1,lookY:0},easing:"ease-out-cubic"},{after:1360,pose:{lift:0,stretch:.88,"head.nod":gt(t,"head.nod")-4,bend:gt(t,"bend")+4},easing:"ease-in-quad"},{after:1560,pose:{stretch:gt(t,"stretch"),"head.nod":gt(t,"head.nod"),bend:gt(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,...us("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,...le("arm",{spread:75}),...le("leg",{swing:25,knee:50})},easing:"ease-in-quad"},{after:300,pose:{stretch:1.05,bend:-4,"arm.left.spread":gt(t,"arm.left.spread"),"arm.right.spread":gt(t,"arm.right.spread")},easing:"ease-out"},{after:460,pose:{lift:0,stretch:gt(t,"stretch"),bend:gt(t,"bend"),...le("leg",{swing:0,knee:0})},easing:"ease-in-out"}],tremble:t=>{const e=[{after:80,pose:{...us("scared"),...le("arm",{swing:40,elbow:110,spread:14}),stretch:.94,bend:gt(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:gt(t,"side")+2.5*s,"head.tilt":gt(t,"head.tilt")-2*s}})}return e.push({after:755,pose:{side:gt(t,"side"),"head.tilt":gt(t,"head.tilt"),bend:gt(t,"bend")}}),e},deflate:t=>[{after:260,pose:{stretch:1.04,"head.nod":gt(t,"head.nod")-4,"brow.left":.3,"brow.right":.3},easing:"ease-in-out"},{after:900,pose:{...us("sad"),bend:18,stretch:.92,lean:gt(t,"lean")+5,"head.nod":14,...le("arm",{spread:6,swing:0,elbow:4,bend:0})},easing:"ease-in-out"}]};function Bf(t,e){const n=kt(e.from??{}),s=e.speed??1;let i=n;return[{time:e.at,pose:n},...Zo[t](n).map(o=>(i={...i,...o.pose},{time:e.at+o.after*s,pose:i,act:!1,...o.easing?{easing:o.easing}:{}}))]}function zf(t,e=lt){const n=t*Math.PI*2,s=Math.sin(n);return{...e,lean:(e.lean??0)+14,bend:(e.bend??0)+8,side:5*s,"head.nod":22,"arm.right.swing":38+22*s,"arm.right.spread":6,"arm.right.elbow":20+10*Math.max(0,-s),"arm.right.bend":-10,"arm.left.swing":52+22*s,"arm.left.spread":14,"arm.left.elbow":35+10*Math.max(0,s),"arm.left.bend":-20,"leg.left.swing":10,"leg.right.swing":-10,"leg.left.knee":8,"leg.right.knee":4,"leg.left.spread":8,"leg.right.spread":8}}function qf(t,e=lt){const n=t*Math.PI*2,s=Math.sin(n),i=Math.cos(n);return{...e,lean:(e.lean??0)+4,side:2*s,"head.nod":6,"arm.right.swing":62,"arm.right.spread":18+16*s,"arm.right.elbow":48-18*Math.abs(s),"arm.right.bend":-30+8*i,"arm.left.swing":12,"arm.left.spread":14,"arm.left.elbow":12,"leg.left.spread":6,"leg.right.spread":6}}const _l={sweeping:zf,brushing:qf};function bv(t,e,n=lt){const s=_l[t];if(!s)throw new Error(`humanCyclePose: ${ft("cycle",t,Object.keys(_l))}`);return s(e,n)}function jf(t){const e=t.top??!0,n=t.length??.32,s=t.color??"#638c39",i=t.accent??"#87ae4e";if(typeof e!="boolean")throw new Error("leafOutfit: top must be a boolean");if(!Number.isFinite(n)||n<.2||n>.45)throw new Error("leafOutfit: length must be 0.2..0.45");if(typeof s!="string"||typeof i!="string")throw new Error("leafOutfit: color and accent must be strings");return{top:e,length:n,color:s,accent:i}}function Yf(t,e){const n=t.flatMap(i=>Array.from({length:8},(o,r)=>({x:i.x+Math.cos(r*Math.PI/4)*e,y:i.y+Math.sin(r*Math.PI/4)*e})));let s=yl(n);for(let i=0;i<2;i++)s=s.flatMap((o,r)=>{const a=s[(r+1)%s.length];return[{x:o.x*.75+a.x*.25,y:o.y*.75+a.y*.25},{x:o.x*.25+a.x*.75,y:o.y*.25+a.y*.75}]});return s}const Kf=t=>t.flatMap(e=>[e.left,e.right]);function Cl(t,e={}){const{top:n,length:s}=jf(e),i=t.bodyContours;if(!i?.spine)throw new Error("leafOutfit requires organic body contours");const o=i.spine.samples.filter(a=>a.at<=.3),r=["left","right"].flatMap(a=>i[`leg.${a}`]?.samples.filter(l=>l.at<=s)??[]);return{...n?{top:Yf(Kf(i.spine.samples.filter(a=>a.at>=.52&&a.at<=.91)),t.height*.01)}:{},skirt:Yf(Kf([...o,...r]),t.height*.012)}}function wv(t,e){t.beginPath(),t.moveTo(e[0].x,e[0].y);for(const n of e.slice(1))t.lineTo(n.x,n.y);t.closePath()}function kv(t,e,n){const s=e.x-t.x,i=e.y-t.y,o=Math.hypot(s,i)||1,r=-i/o,a=s/o,l=[];for(const c of[1,-1])for(let h=0;h<=16;h++){const u=c===1?h/16:1-h/16,f=3*(1-u)*u*n*c;l.push({x:t.x+s*u+r*f,y:t.y+i*u+a*f})}return l}function Xf(t,e,n,s,i,o){const r=e.lineWidth*.7;if(n.shape(s,i,r),n.look==="silhouette")return;t.save(),wv(t,s),t.clip();const a=Math.min(...s.map(f=>f.x)),l=Math.max(...s.map(f=>f.x)),c=Math.min(...s.map(f=>f.y)),h=Math.max(...s.map(f=>f.y)),u=l-a,d=h-c;for(let f=0;f<2;f++)for(let p=0;p<5;p++){const g={x:a+u*(p/4+(f?.07:-.04)),y:c+d*(f?.38:-.1)},m={x:g.x+u*.09,y:g.y+d*.78};n.shape(kv(g,m,u*.13),(p+f)%2?i:o,r*.6),n.line([g,{x:g.x*.45+m.x*.55,y:g.y*.45+m.y*.55},m],r*.45);for(const b of[.32,.52,.7]){const v={x:g.x+(m.x-g.x)*b,y:g.y+(m.y-g.y)*b};n.line([{x:v.x-u*.045,y:v.y-d*.065},v,{x:v.x+u*.045,y:v.y-d*.05}],r*.3)}}t.restore()}function Gf(t={}){const e=jf(t),{color:n,accent:s}=e,i=o=>(r,a,l)=>{const c=Cl(a,e);o==="spine"&&c.top&&Xf(r,a,l,c.top,n,s);const h=["spine","leg.left","leg.right"].reduce((u,d)=>a.parts[u].order>a.parts[d].order?u:d);o===h&&Xf(r,a,l,c.skirt,n,s)};return{parts:{spine:{over:i("spine")},"leg.left":{over:i("leg.left")},"leg.right":{over:i("leg.right")}}}}const vv={apron:"#d8b48a",labCoat:"#f4f6f8",hoodie:"#6b7280",cardigan:"#6b8e4e",overalls:"",sari:"#16a34a"},Hl=(t,e,n)=>t.slice(Math.floor((t.length-1)*e),Math.ceil((t.length-1)*n)+1),pt=(t,e,n)=>({x:t.x+(e.x-t.x)*n,y:t.y+(e.y-t.y)*n});function Mv(t){return t.parts["leg.left"].order>t.parts["leg.right"].order?"left":"right"}const Uf=t=>Math.max(t.parts["leg.left"].order,t.parts["leg.right"].order)>t.parts.spine.order,ee=t=>t.bodyForward?.[2]??Math.cos(t.turn*Math.PI/2),_e=t=>t.bodyForward?.[0]??Math.sin(t.turn*Math.PI/2);function Vf(t,e,n){t.save(),t.beginPath(),t.moveTo(e[0].x,e[0].y);for(const s of e.slice(1))t.lineTo(s.x,s.y);t.closePath(),t.clip(),n(),t.restore()}function Jf(t,e,n=0){const s=e*(t.length-1),i=Math.min(t.length-2,Math.floor(s)),o=t[i],r=t[i+1],a=pt(o,r,s-i),l=Math.hypot(r.x-o.x,r.y-o.y)||1;return{x:a.x+(r.y-o.y)/l*n,y:a.y-(r.x-o.x)/l*n}}function Zf(t={}){if(t={...t},t.top!==void 0&&!["tshirt","shirt","blouse","dress"].includes(t.top))throw new Error(`basicOutfit: unknown top '${t.top}'`);if(t.trouserStyle!==void 0&&!["plain","jeans","cargo"].includes(t.trouserStyle))throw new Error(`basicOutfit: unknown trouser style '${t.trouserStyle}'`);const e=t.top,n=t.trouserStyle??"plain",s=t.collar??e==="shirt",i=t.shirt??"#e2493b",o=e==="dress"?i:t.trousers??"#24476b",r=t.sleeves??"short",a=e==="dress"?"skirt":t.bottom??"trousers",l=t.over==="labCoat",c=t.over==="hoodie",h=t.over==="cardigan",u=t.over==="overalls",d=t.over==="sari",f=t.overColor??(t.over&&t.over!=="overalls"?vv[t.over]:o),p=t.shoes==="boots",g=t.shoeColor??"#3b2a1e",m=$=>$.lineWidth*.45,b=($,_,z,K)=>{const N=_.parts[`leg.${K}`].points;if(a==="skirt"&&!u)return;const F=a==="shorts"&&!u,D=_.bodyContours?.[`leg.${K}`],X=D?ml(D,0,F?.5:1,_.height*.006):zt(F?Hl(N,0,.5):N,_.height*(F?.085:.08),_.height*(F?.07:.05));z.shape(X,o,m(_)),!(n==="plain"||ee(_)<.15)&&Vf($,X,()=>{const B=(Z,et=0)=>Jf(N,Z,et*_.height);if(n==="jeans")z.line([B(.07,-.018),B(.17,-.02),B(.23,0),B(.17,.02),B(.07,.018)],m(_)*.65),z.line([B(.27,.013),...[.4,.55,.7,.85,.96].filter(Z=>!F||Z<.5).map(Z=>B(Z,.013))],m(_)*.5);else{const Z=[B(.25,-.024),B(.25,.024),B(.43,.024),B(.43,-.024)];z.shape(Z,o,m(_)*.65),z.line([B(.28,-.024),B(.32,0),B(.28,.024)],m(_)*.65);const et=B(.32);z.dot(et.x,et.y,m(_)*.8)}})},v=($,_,z)=>{const K=$.parts[`leg.${z}`].points,N=Hl(K,.7,1);if(N.length<2)return;_.shape(zt(N,$.height*.075,$.height*.07),g,m($));const F=N[0],D=N[1],X=D.x-F.x,B=D.y-F.y,Z=Math.hypot(X,B)||1,et=$.height*.04;_.line([{x:F.x-B/Z*et,y:F.y+X/Z*et},{x:F.x+B/Z*et,y:F.y-X/Z*et}],m($)*.9)},k=$=>{const _=$.chains.spine,z=_[0],K=_[_.length-1],N={x:z.x-(K.x-z.x)*.25,y:z.y-(K.y-z.y)*.25};return{hip:z,top:K,below:N,line:[N,...$.parts.spine.points]}},w=$=>{if($.bodyContours?.spine)return ml($.bodyContours.spine,0,.97,$.height*(c?.014:.006));const _=c?1.14:1,z=Math.hypot($.points["hip.left"].x-$.points["hip.right"].x,$.points["hip.left"].y-$.points["hip.right"].y),K=Math.max($.height*.15*_,z+Math.max($.height*.08,$.lineWidth*1.45)+m($));return zt(k($).line,K,$.height*.14*_)},T=($,_)=>{const z=[w(_)],{top:K,hip:N}=k(_);h&&z.push(zt([K,pt(K,N,.5),pt(K,N,1.08)],_.height*.155,_.height*.15)),l&&z.push(zt([K,pt(K,N,.5),N],_.height*.14,_.height*.15));const F=Object.values(_.points),D=Math.min(...F.map(et=>et.x))-_.height,X=Math.min(...F.map(et=>et.y))-_.height,B=Math.max(...F.map(et=>et.x))+_.height,Z=Math.max(...F.map(et=>et.y))+_.height;for(const et of z){$.beginPath(),$.rect(D,X,B-D,Z-X),$.moveTo(et[0].x,et[0].y);for(const R of et.slice(1))$.lineTo(R.x,R.y);$.closePath(),$.clip("evenodd")}},P=($,_)=>{const z=c?f:i;_.shape(w($),z,m($))},S=($,_,z)=>{const K=ee(_);if(!e||K<.2||c)return;const{top:N,hip:F}=k(_),D=_e(_)*_.height*.025,X=[N,F],B=(Z,et=0)=>Jf(X,Z,D+et*_.height*K);Vf($,w(_),()=>{if(e==="shirt"){z.line([B(.12),B(.92)],m(_)*.65);for(const Z of[.24,.4,.56,.72,.88]){const et=B(Z,.008);z.dot(et.x,et.y,m(_)*.9)}}else if(e==="blouse"){z.line([B(.025,-.04),B(.24),B(.025,.04)],m(_)*.75);const Z=B(.31);z.dot(Z.x,Z.y,m(_))}else e==="dress"?z.line([B(.04,-.035),B(.17,-.028),B(.17,.028),B(.04,.035)],m(_)*.75):z.line([B(.025,-.035),B(.1,-.02),B(.12),B(.1,.02),B(.025,.035)],m(_)*.65)})},x=($,_)=>{const z=ee($),{top:K,hip:N}=k($),F=$.height*.07,D={x:(K.x-N.x)*.16,y:(K.y-N.y)*.16};if(z>=0){_.shape([{x:K.x-F,y:K.y+D.y*.25},{x:K.x-F*.8+D.x,y:K.y+D.y},{x:K.x+D.x*1.2,y:K.y+D.y*1.35},{x:K.x+F*.8+D.x,y:K.y+D.y},{x:K.x+F,y:K.y+D.y*.25}],f,m($));return}const X=pt(K,N,.42);_.shape([{x:K.x-F*.9,y:K.y},{x:K.x+F*.9,y:K.y},{x:X.x+F*.7,y:X.y},{x:X.x,y:X.y+$.height*.02},{x:X.x-F*.7,y:X.y}],f,m($))},M=($,_)=>{const z=ee($);if(z<.2)return;const{top:K,hip:N}=k($),F=_e($)*$.height*.03,D=$.height*.06*z,X=pt(K,N,.62),B=pt(K,N,.9);_.line([{x:X.x+F-D,y:X.y},{x:B.x+F-D*1.1,y:B.y}],m($)*.7),_.line([{x:X.x+F+D,y:X.y},{x:B.x+F+D*1.1,y:B.y}],m($)*.7);const Z=pt(K,N,.1);for(const et of[-1,1])_.line([{x:Z.x+F+et*D*.2,y:Z.y},{x:Z.x+F+et*D*.35,y:Z.y+$.height*.07}],m($)*.6)},E=($,_)=>{const{top:z,hip:K}=k($),N=ee($);if(_.shape(zt([z,pt(z,K,.5),pt(z,K,1.08)],$.height*.155,$.height*.15),f,m($)),N<.2)return;const F=_e($)*$.height*.03,D=$.height*.02*N,X=pt(z,K,.12),B=pt(z,K,1.05);_.shape([{x:X.x+F-D,y:X.y},{x:X.x+F+D,y:X.y},{x:B.x+F+D*1.3,y:B.y},{x:B.x+F-D*1.3,y:B.y}],i,m($)*.7);for(const Z of[.35,.55,.75]){const et=pt(z,K,Z);_.dot(et.x+F+D*1.6,et.y,m($)*1.2)}},I=($,_)=>{const z=ee($),{top:K,hip:N}=k($),F=_e($)*$.height*.04,D=pt(N,K,.12),X=pt(N,K,.74);if(z<.15){if(z<-.3){const R=$.points["shoulder.left"],U=$.points["shoulder.right"];_.line([R,{x:D.x+$.height*.03,y:D.y}],m($)*.8),_.line([U,{x:D.x-$.height*.03,y:D.y}],m($)*.8)}return}const B=$.height*.07*z;_.shape([{x:X.x+F-B*.75,y:X.y},{x:X.x+F+B*.75,y:X.y},{x:D.x+F+B*1.1,y:D.y},{x:D.x+F-B*1.1,y:D.y}],o,m($));for(const R of["left","right"]){const U=$.points[`shoulder.${R}`],nt={x:X.x+F+(U.x>X.x+F?1:-1)*B*.55,y:X.y};_.line([nt,{x:U.x+(nt.x-U.x)*.15,y:U.y+(nt.y-U.y)*.15}],m($)*1.6)}const Z=pt(X,D,.3),et=B*.4;_.line([{x:Z.x+F-et,y:Z.y},{x:Z.x+F-et,y:Z.y+et*1.4},{x:Z.x+F+et,y:Z.y+et*1.4},{x:Z.x+F+et,y:Z.y}],m($)*.6)},A=($,_)=>{const{hip:z,top:K}=k($),N=pt(z,K,.2),F=[$.points["ankle.left"],$.points["ankle.right"]],D=pt(z,{x:(F[0].x+F[1].x)/2,y:(F[0].y+F[1].y)/2},.98),X=$.height*.075,B=Math.max($.height*.12,Math.abs(F[0].x-F[1].x)/2+$.height*.07),Z=D.x-N.x,et=D.y-N.y,R=Math.hypot(Z,et)||1,U={x:-et/R,y:Z/R};if(_.shape([{x:N.x+U.x*X,y:N.y+U.y*X},{x:D.x+U.x*B,y:D.y+U.y*B},{x:D.x-U.x*B,y:D.y-U.y*B},{x:N.x-U.x*X,y:N.y-U.y*X}],f,m($)),ee($)>.2){const at=_e($)*$.height*.03;for(const ot of[-.35,0,.35]){const ct=X*.5*ot,it=B*.45*ot;_.line([{x:N.x+at+U.x*ct,y:N.y+U.y*ct+$.height*.02},{x:D.x+at+U.x*it,y:D.y+U.y*it}],m($)*.5)}}},O=($,_)=>{const z=ee($),{top:K,hip:N}=k($),F=_e($),D=F>=0?"left":"right",X=D==="left"?"right":"left",B=$.points[`shoulder.${D}`],Z=$.height*.035;if(z<.15){const U=pt(K,N,.9);_.shape(zt([B,{x:U.x+(B.x-K.x)*.5,y:U.y}],Z*2.2,Z*2.6),f,m($));return}const et={x:N.x+($.points[`hip.${X}`].x-N.x)*1.2,y:pt(N,K,.08).y};_.shape(zt([et,pt(et,B,.5),B],Z*2.4,Z*2),f,m($));const R={x:B.x-(N.x-B.x)*.05-F*$.height*.03,y:B.y+$.height*.16};_.shape(zt([B,R],Z*2,Z*1.6),f,m($))},H=($,_)=>{if($.bodyContours){_.shape(Cl($,{top:!1,length:.45}).skirt,o,m($));return}const{hip:z,top:K}=k($),N=pt(z,K,.18),F=[$.points["knee.left"],$.points["knee.right"]],D=pt(z,{x:(F[0].x+F[1].x)/2,y:(F[0].y+F[1].y)/2},1.05),X=$.height*.075,B=Math.max($.height*.13,Math.abs(F[0].x-F[1].x)/2+$.height*.08),Z=D.x-N.x,et=D.y-N.y,R=Math.hypot(Z,et)||1,U={x:-et/R,y:Z/R};_.shape([{x:N.x+U.x*X,y:N.y+U.y*X},{x:D.x+U.x*B,y:D.y+U.y*B},{x:D.x-U.x*B,y:D.y-U.y*B},{x:N.x-U.x*X,y:N.y-U.y*X}],o,m($))},W=($,_)=>{const z=ee($);if(z<.2)return;const{top:K,hip:N}=k($),F={x:(N.x-K.x)*.12,y:(N.y-K.y)*.12},D=$.height*.045*z;for(const X of[-1,1])_.shape([{x:K.x+X*D*.2,y:K.y+F.y*.1},{x:K.x+X*D*1.3,y:K.y-F.y*.1},{x:K.x+X*D*.6+F.x,y:K.y+F.y}],i,m($)*.8)},j=($,_,z)=>{const K=ee($);if(K<.25)return;const{top:N,hip:F}=k($),D=_e($)*$.height*.03,X=R=>({x:pt(N,F,R).x+D,y:pt(N,F,R).y}),B=$.height*.022*K,Z=X(.08),et=X(.62);_.shape([{x:Z.x-B,y:Z.y-B},{x:Z.x+B,y:Z.y-B},{x:Z.x+B*.6,y:Z.y+B},{x:Z.x-B*.6,y:Z.y+B}],z,m($)*.7),_.shape([{x:Z.x-B*.6,y:Z.y+B},{x:Z.x+B*.6,y:Z.y+B},{x:et.x+B*1.4,y:et.y-B*2},et,{x:et.x-B*1.4,y:et.y-B*2}],z,m($)*.7)},J=($,_)=>{const z=ee($),{top:K,hip:N}=k($),F=pt(N,K,.72),D=[$.points["knee.left"],$.points["knee.right"]],X=pt(N,{x:(D[0].x+D[1].x)/2,y:(D[0].y+D[1].y)/2},.9),B=_e($)*$.height*.04;if(z<.15){const R=pt(N,K,.2);z<-.3&&_.line([{x:R.x-$.height*.05,y:R.y},{x:R.x+$.height*.05,y:R.y}],m($));return}const Z=$.height*.075*z,et=pt(N,K,.2);_.shape([{x:F.x+B-Z*.7,y:F.y},{x:F.x+B+Z*.7,y:F.y},{x:et.x+B+Z,y:et.y},{x:X.x+B+Z*1.15,y:X.y},{x:X.x+B-Z*1.15,y:X.y},{x:et.x+B-Z,y:et.y}],f,m($)),_.line([{x:F.x+B-Z*.6,y:F.y},{x:K.x-Z*.2,y:K.y},{x:F.x+B+Z*.6,y:F.y}],m($)*.8)},tt=($,_,z)=>{const{top:K,hip:N}=k($),F=[$.points["knee.left"],$.points["knee.right"]],D=pt(N,{x:(F[0].x+F[1].x)/2,y:(F[0].y+F[1].y)/2},.95);z?_.shape(zt([pt(K,N,.8),N,D],$.height*.145,$.height*.17),f,m($)):_.shape(zt([K,pt(K,N,.5),N],$.height*.14,$.height*.15),f,m($));const X=ee($);if(X>.2){const B=_e($)*$.height*.03,[Z,et]=z?[N,D]:[K,N];if(_.line([{x:Z.x+B,y:Z.y},{x:et.x+B,y:et.y}],m($)*.8),!z){const R=pt(K,N,.35),U=$.height*.025*X;_.shape([{x:R.x+B-U*2.4,y:R.y},{x:R.x+B-U*.6,y:R.y},{x:R.x+B-U*.6,y:R.y+U*1.6},{x:R.x+B-U*2.4,y:R.y+U*1.6}],f,m($)*.6)}}},V=($,_,z,K,N)=>{const F=$.bodyContours?.[`arm.${z}`];if(F){const Q=ml(F,0,N,$.height*.006);_.shape(Q,K,0);const rt=w($);for(let ht=0;ht<Q.length;ht++){const dt=Q[ht],bt=Q[(ht+1)%Q.length];Ud({x:(dt.x+bt.x)/2,y:(dt.y+bt.y)/2},rt)||_.line([dt,bt],m($))}return}const D=$.parts[`arm.${z}`].points,X=D[0],B=$.chains.spine[$.chains.spine.length-1],et=[{x:X.x+(B.x-X.x)*.45,y:X.y+(B.y-X.y)*.45},...Hl(D,0,N)],R=zt(et,$.height*.085,$.height*(N>.6?.045:.06)),U=et.length,nt=R.slice(0,U),at=R.slice(U).reverse();_.shape(R,K,0);const ot=Q=>Math.hypot(Q[1].x-B.x,Q[1].y-B.y),[ct,it]=ot(nt)>ot(at)?[nt,at]:[at,nt];_.line(ct.slice(1),m($)),_.line(it.slice(Math.ceil(U*.45)),m($)),_.line([nt[U-1],at[U-1]],m($))},L=l||c||h,q=L?f:i,G=L||r==="long"?.95:.45,C=L||r!=="none",Y=($,_)=>{a==="skirt"&&!u&&!d&&H($,_),d&&A($,_),l&&tt($,_,!0),t.over==="apron"&&J($,_)},st=$=>(_,z,K)=>{_.save(),T(_,z),b(_,z,K,$),p&&v(z,K,$),_.restore(),Mv(z)===$&&Uf(z)&&Y(z,K)};return{parts:{"leg.left":{clip:T,over:st("left")},"leg.right":{clip:T,over:st("right")},spine:{over:($,_,z)=>{c&&ee(_)>=0&&x(_,z),P(_,z),S($,_,z),s&&!c&&W(_,z),t.tie&&!c&&j(_,z,t.tie),l&&tt(_,z,!1),h&&E(_,z),c&&(ee(_)<0&&x(_,z),M(_,z)),u&&I(_,z),d&&O(_,z),Uf(_)||Y(_,z)}},"arm.left":{over:C?($,_,z)=>V(_,z,"left",q,G):void 0},"arm.right":{over:C?($,_,z)=>V(_,z,"right",q,G):void 0}}}}const Rl={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"},cane:{color:"#6b4630",hands:"one"},parcel:{color:"#c9a06a",hands:"both"}};function Qf(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=Rl[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 Qo(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 Ll(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"cane":{const h=Math.min(.56*s,Math.max(.3*s,-a.y)),u=.12*Math.sign(o||1),d={x:u/Math.hypot(u,1),y:1/Math.hypot(u,1)},f={x:a.x+d.x*h,y:a.y+d.y*h},p=fs({x:a.x+7*c*Math.sign(o||1),y:a.y-2*c},7*c,Math.PI,Math.PI*2,8).map(g=>({x:a.x+(g.x-a.x)*Math.sign(o||1),y:g.y}));t.line([...p,{x:a.x,y:a.y+2*c},f],i*1.2),t.shape(ds({x:f.x,y:f.y-3*c},9*c,7*c),e.color,0);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 Fl=(t,e)=>(t[`held.${e}`]??1)>=.5,tg=t=>Math.sin(t*Math.PI/2);function eg(t){const e=o=>Math.max(1,o.lineWidth*.45),n=o=>(r,a,l,c,h)=>{const u=t[o];u&&Fl(h??{},o)&&Ll(l,u,Qo(a,o),a.height,e(a),tg(a.turn),a.head.center.y-a.head.ry)},s=(o,r,a,l,c)=>{const h=t.both;if(!h||!Fl(c??{},"both"))return;const u=Qo(r,"left"),d=Qo(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};Ll(a,h,f,r.height,e(r),tg(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:Sv(i.parts[`arm.${r}`]?.over,o(r))}}return i}function Sv(t,e){return t?(n,s,i,o,r)=>{t(n,s,i,o,r),e(n,s,i,o,r)}:e}function Nl(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),clip:n(o?.clip,r?.clip),over:n(o?.over,r?.over)}}return{behind:n(t.behind,e.behind),parts:s,front:n(t.front,e.front)}}function gs(t={}){if(t.build&&!(t.build in Ho))throw new Error(`character: unknown build '${t.build}'`);const e=t.build?Ho[t.build]:{},n=(t.proportions??"bold")==="bold",s=t.figure??"fluid",i=t.look??"clean",o=t.height??300,r=s==="stick",a=s==="organic",l=t.shoulderWidth??e.shoulderWidth??(a?.07:.06),c=t.hipWidth??e.hipWidth??(a?.045:.022),h=t.lineWidth??o*(a?.005:n?.045:.022),u=t.ink??(a?"#53362d":i==="pencil"?"#2f2f33":"#1e293b"),d=t.skin??(a?"#f1bf98":i==="pencil"?"none":"#ffffff"),f=a?Yd(t.body??{},{skin:d,ink:u,lineWidth:h,shoulderWidth:l,hipWidth:c}):void 0;if(t.leafOutfit&&!a)throw new Error("character: leafOutfit requires figure: 'organic'");const p=t.outfit?Zf(t.outfit):null,g=t.holding?Qf(t.holding):{};let m=p?Nl(p,t.layers??{}):t.layers??{};return t.leafOutfit&&(m=Nl(Gf(t.leafOutfit),m)),Object.keys(g).length>0&&(m=Nl(m,eg(g))),{plan:t.plan??ll({headSize:t.headSize??e.headSize??(a?.27:n?.3:.24),shoulderWidth:r?0:l,hipWidth:r?0:c,legLength:t.legLength??e.legLength??1,armLength:t.armLength??e.armLength??1,feet:t.feet??e.feet}),figure:s,...f?{body:f}:{},look:i,height:o,lineWidth:f?.outline.width??h,ink:f?.outline.color??u,skin:f?.fill??d,seed:t.seed??1,pencil:a?{construction:!1,...t.pencil}:t.pencil??{},layers:m,holding:g,contact:t.contact??"ground",hands:t.hands??(a?"cartoon":"dot"),handStyle:t.handStyle??(a?"natural":"glove"),handSize:t.handSize??(a?.073:t.handStyle==="natural"?.14:.17),head:Hf(t),face:{...a?{style:"anime",projection:"volume",iris:"#66422e",nose:!0}:{},...t.face,teeth:t.face?.teeth??!1,tongue:t.face?.tongue??!1}}}function xv(t,e,n,s){const{point:i,facing:o}=is(t,[e,n,s]);return{point:i,facing:o}}const Wl=t=>t.rest[1]<-.5,Tv=.3;function Ev(t,e,n){return t.figure==="stick"?Wl(e)?n.slice(0,3):n:Wl(e)&&n.length>=3?vn(n[0],n[1],n[2],Tv):n.length===3?vn(n[0],n[1],n[2],1):n}function ki(t,e){const n=t.plan.id==="human"?{...lt,...e}:e;return tr(t,n,ul(t.plan,n,{height:t.height,contact:t.contact}))}function tr(t,e,n){const s={},i={},o={},r=.01*t.height;t.plan.chains.forEach(f=>{const p=n.chains[f.id];s[f.id]=p.points;const g=p.depths.reduce((k,w)=>k+w,0)/p.depths.length,m=f.parent?n.chains[f.parent]:void 0,b=m?m.depths[f.at??m.depths.length-1]:n.hipDepth,v=g-b;o[f.id]=Math.abs(v)<r?0:v,i[f.id]={points:Ev(t,f,p.points),depth:g,order:0}}),i.head={points:[n.head.center],depth:n.head.depth,order:0},o.head=0;const a=[...t.plan.chains.map(f=>f.id),"head"],l=f=>t.body&&f.startsWith("arm.")&&o[f]>=0?1:0,c=[...a].sort((f,p)=>l(f)-l(p)||o[f]-o[p]||a.indexOf(f)-a.indexOf(p));c.forEach((f,p)=>{i[f].order=p});const h={hip:n.hip};for(const[f,[p,g]]of Object.entries(t.plan.landmarks??{})){const m=n.chains[p]?.points;m&&(h[f]=m[Math.min(g,m.length-1)])}const u={};for(const[f,p]of Object.entries(h))u[f]=p.y>=n.groundY-.01*t.height;const d={height:t.height,lineWidth:t.lineWidth,turn:e.turn??0,...n.bodyForward?{bodyForward:n.bodyForward}:{},points:h,chains:s,parts:i,head:n.head,groundY:n.groundY,grounded:u};return t.body&&(d.bodyContours=Gd(t.body,d,t.plan)),{skeleton:n,joints:d,order:c}}function fe(t,e){return ki(t,e).joints}function ng(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=xt(s,i,{x:0,y:0});r.facing>0&&t.guide(r.points),t.guide(xt(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 sg(t,e,n,s,i,o){const r=n.lineWidth;if(n.body&&n.skin==="none"&&(e=oi(t,e)),i==="head"){const{head:f}=s;let p;const g=()=>p??=Qd(f,n.face),m=n.skin==="none"?null:n.skin;n.face.projection==="volume"||n.face.shape==="angular"?e.shape(g(),m,r):e.ellipse(f.center.x,f.center.y,f.rx,f.ry,f.angle,m,r),n.body&&n.skin!=="none"&&e.look==="clean"&&td(t,g(),f.center,n.body.shading),mv(t,e,n.head,f,o,{lineWidth:r,skin:n.skin,face:n.face,faceUnderHair:!!n.body},()=>{e.look!=="silhouette"&&(t.save(),n.body&&(t.beginPath(),g().forEach((b,v)=>v?t.lineTo(b.x,b.y):t.moveTo(b.x,b.y)),t.closePath(),t.clip()),L5(e,f,o,r,{...n.face,skin:n.skin==="none"?"#ffffff":n.skin},t),t.restore())});return}const a=n.plan.chains.find(f=>f.id===i),l=s.chains[i],c=s.parts[i].points;if(n.body&&Jd(t,e,n.body,s,i)){if(i.startsWith("leg.")&&Jd(t,e,n.body,s,i.replace("leg.","foot.")),i.startsWith("arm."))if(n.hands==="cartoon")og(t,e,n,l,i.endsWith(".left")?"left":"right",o);else{const f=l.at(-1);e.ellipse(f.x,f.y,n.height*.014,n.height*.014,0,n.skin==="none"?null:n.skin,r)}return}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(Wl(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."))og(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 b=s.points["shoulder.left"],v=s.points["shoulder.right"];b&&v&&Math.hypot(b.x-v.x,b.y-v.y)>.5&&e.limb(vn(b,l[l.length-1],v,1,10),r*1.15,r*1.15);return}const[u,d]=h(0,a.bones.length-1);e.limb(c,u,d)}function ig(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{...Ot,...s,turn:o+(s.turn??0)}}function og(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;So(t,r,ig(o,i),{size:n.handSize*n.height,side:i,angle:l,pen:e,skin:n.skin==="none"&&!n.body?"#ffffff":n.skin,fingers:n.handStyle==="natural"?5:4,plump:n.handStyle==="natural"?1.15:1.6,lineWidth:n.lineWidth*(n.body?.65:.3),connected:!!n.body,shading:n.body?.shading,nails:n.body?!1:void 0})}function rg(t,e,n,s=0){const i=e.plan.id==="human"?{...lt,...n}:n;Dl(t,e,i,ki(e,i),s)}function er(t,e){const n=e/t.height;return{...t,height:e,lineWidth:t.lineWidth*n}}function Av(t,e,n,s){const i=t.plan.id==="human"?{...lt,...e}:e,o=Wo(t.plan,i,{height:s.height,contact:t.contact},n);return tr(er(t,o.height),i,o).joints}function $v(t,e,n,s,i){const o=e.plan.id==="human"?{...lt,...n}:n,r=Wo(e.plan,o,{height:i.height,contact:e.contact},s),a=er(e,r.height);Dl(t,a,o,tr(a,o,r),i.time??0)}function ag(t,e,n,s){const i=t.plan.id==="human"?{...lt,...e}:e,o=Wo(t.plan,i,{height:s.height,contact:t.contact},n),r=er(t,o.height),{joints:a,order:l}=tr(r,i,o),c=o.height/s.height,h=l.map(p=>(a.parts[p]?.depth??0)/c),u=l.filter(p=>p==="spine"||p.startsWith("leg.")),d=Math.max(...u.map(p=>a.parts[p].depth/c)),f=Math.max(...u.map(p=>a.parts[p].order));return l.map((p,g)=>({part:p,depth:h[g],...r.body?{sortDepth:p.startsWith("arm.")&&g>f?Math.max(h[g],d):h[g]}:{},draw(m,b=0){const v=ii(m,{look:r.look,ink:r.ink,lineWidth:r.lineWidth,seed:ne(`${r.seed}:${p}`),time:b,pencil:r.pencil}),k=T=>{T&&(m.save(),T(m,a,v,b,i),m.restore())};m.save(),m.lineCap="round",m.lineJoin="round",g===0&&(r.look==="pencil"&&r.pencil.construction!==!1&&ng(v,r,a),k(r.layers.behind),Nf(m,r.body&&r.skin==="none"?oi(m,v):v,r.head,a.head,i,{lineWidth:r.lineWidth,skin:r.skin,face:r.face}));const w=r.layers.parts?.[p];k(w?.under),m.save(),w?.clip?.(m,a,v,b,i),sg(m,v,r,a,p,i),m.restore(),k(w?.over),p==="head"&&Wf(m,v,r.head,a.head,i,{lineWidth:r.lineWidth,skin:r.skin,face:r.face}),g===l.length-1&&k(r.layers.front),m.restore()}}))}function Dl(t,e,n,s,i,o){const{joints:r}=s,a=o?s.order.filter(h=>o.has(h)):s.order,l=ii(t,{look:e.look,ink:e.ink,lineWidth:e.lineWidth,seed:e.seed,time:i,pencil:e.pencil}),c=h=>{h&&(t.save(),h(t,r,l,i,n),t.restore())};t.save(),t.lineCap="round",t.lineJoin="round",!o&&e.look==="pencil"&&e.pencil.construction!==!1&&ng(l,e,r),o||c(e.layers.behind),Nf(t,e.body&&e.skin==="none"?oi(t,l):l,e.head,r.head,n,{lineWidth:e.lineWidth,skin:e.skin,face:e.face});for(const h of a){const u=e.layers.parts?.[h];c(u?.under),t.save(),u?.clip?.(t,r,l,i,n),sg(t,l,e,r,h,n),t.restore(),c(u?.over)}Wf(t,l,e.head,r.head,n,{lineWidth:e.lineWidth,skin:e.skin}),o||c(e.layers.front),t.restore()}function Pv(t,e,n,s){const i=e.plan.id==="human"?{...lt,...n}:n,o=ki(e,i).joints.head.rx,r=er(e,e.height*s.radius/Math.max(1e-6,o)),a=ki(r,i);t.save(),t.translate(s.x-a.joints.head.center.x,s.y-a.joints.head.center.y),Dl(t,r,i,a,s.time??0,new Set(["head"])),t.restore()}function Bl(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 Ce(t,e,n,s){const i=t.plan.id==="human"?{...lt,...e}:e;let o;if(Array.isArray(s))o=s;else{const{skeleton:r}=ki(t,i),a=ul(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 fi(t.plan,i,n,o,{height:t.height})}const lg=new Set(["walk","walking","gait"]);function nr(t,e=lt,n){let s={...e};for(const[o,r]of Object.entries(t))typeof r=="number"&&!lg.has(o)&&(s[o]=r);const i=Math.max(0,Math.min(1,typeof t.walking=="number"?t.walking:0));if(i>0){const o=typeof t.gait=="string"?t.gait:void 0,r=o?n?.[o]??o:void 0,a=Vo(r,typeof t.walk=="number"?t.walk:0,s);s=Object.fromEntries(Object.keys({...s,...a}).map(l=>[l,(s[l]??0)+((a[l]??0)-(s[l]??0))*i]))}return s}function Iv(t){const{character:e}=t,n=e.height*.8,s=e.height,i=e.plan.id==="human"?lt:{};return{type:"custom",x:t.x-n/2,y:t.y-s,width:n,height:s,props:{...i,...t.pose},character:e,...t.gaits?{gaits:t.gaits}:{},draw(o,r,a){o.translate(n/2,s),rg(o,e,nr(r.props??{},i,t.gaits),a)}}}function cg(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,...t.bodyContours?{bodyContours:Object.fromEntries(Object.entries(t.bodyContours).map(([o,r])=>[o,{...r,outline:r.outline.map(s),samples:r.samples.map(a=>({...a,center:s(a.center),left:s(a.left),right:s(a.right)}))}]))}:{},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 Ov(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[c,h]of e.state?.values.get(n)??[])c==="x"||c==="motionPathX"?o=typeof h=="number"?h:o:c==="y"||c==="motionPathY"?r=typeof h=="number"?h:r:(typeof h=="number"||lg.has(c))&&(i[c]=h);const a=nr(i,s.plan.id==="human"?lt:{},t.gaits),l=fe(s,a);return{pose:a,joints:cg(l,t.x+o+t.width/2,t.y+r+t.height)}}function zl(t,e=lt){const n=[];return t.forEach((s,i)=>{const o=i===0?e:n[i-1],r=typeof s.pose=="string"?ye[s.pose]:void 0;n.push(r?{...r,turn:o.turn??0}:{...o,...s.pose})}),n}function _v(t,e,n=lt){const s=zl(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 sr=(t,e)=>[t[0]+e[0],t[1]+e[1],t[2]+e[2]],Ae=(t,e)=>[t[0]-e[0],t[1]-e[1],t[2]-e[2]],ir=(t,e)=>[t[0]*e,t[1]*e,t[2]*e],ql=t=>Math.hypot(...t),hg=t=>ir(t,1/(ql(t)||1)),or=t=>({...lt,...t}),jl=t=>Ve(t.character.plan,or(t.pose),{height:t.character.height,contact:t.character.contact});function In(t,e,n){return sr(t.position,jl(t).chains[e][n])}function ug(t,e,n){const s=or(t.pose),i=jl(t).hip,o=ss(t.character.plan,s,t.character.height),r=Ae(Ae(n,t.position),i),a=ns(r,(s.roll??0)*Math.PI/180),l=sr(o.root,Qt(a,-(s.turn??0)*Math.PI/2));return fi(t.character.plan,s,e,l,{height:t.character.height})}function dg(t,e,n,s="toe"){const i=`leg.${e}`,o=s==="toe"?3:2;let r={...t,pose:or(t.pose),position:[...t.position]};for(let l=0;l<6;l++){const c=jl(r).chains[i],h=Ae(c[o],c[2]);r={...r,pose:ug(r,i,Ae(n,h))};const u=In(r,i,o);r.position[1]+=n[1]-u[1]}const a=ql(Ae(In(r,i,o),n));return{...r,reached:a<t.character.height*.002}}function fg(t,e){const n=In(t,`arm.${e}`,2),s=In(t,`arm.${e}`,1);return sr(n,ir(hg(Ae(n,s)),t.character.lineWidth*.5))}function Cv(t,e,n={}){const s=Math.min(t.character.height,e.character.height),i=n.length??s*.22;if(!(i>0)||!Number.isFinite(i))throw new Error("meetDandiya: stick length must be positive and finite");const o=n.point??[(t.position[0]+e.position[0])/2,Math.max(t.position[1],e.position[1])+s*.62,(t.position[2]+e.position[2])/2],r=(c,h)=>{const u=hg([o[0]-c.position[0],s*.2,o[2]-c.position[2]]),d=Ae(o,ir(u,i));let f=or(c.pose);for(let g=0;g<6;g++){const m={...c,pose:f},b=In(m,`arm.${h}`,2);f=ug(m,`arm.${h}`,Ae(d,Ae(fg(m,h),b)))}for(const[g,m]of Object.entries(St.hold))f[`hand.${h}.${g}`]=m;const p=fg({...c,pose:f},h);return{pose:f,stick:{grip:p,tip:sr(p,ir(u,i))}}},a=r(t,n.sideA??"right"),l=r(e,n.sideB??"right");return{a:a.pose,b:l.pose,sticks:[a.stick,l.stick],point:o,reached:[a.stick,l.stick].every(c=>ql(Ae(c.tip,o))<s*.002)}}function gg(t,e){const n=e.count??8,s=e.beatsPerTurn??32;if(!Number.isFinite(t)||!Number.isFinite(e.radius)||e.radius<=0||!Number.isInteger(n)||n<1||!Number.isFinite(s)||s<=0)throw new Error("danceCircleAt: finite beat, positive radius/beatsPerTurn and a positive integer count are required");const i=e.center??[0,0],o=e.direction??1;if(i.length!==2||!i.every(Number.isFinite)||!Number.isFinite(e.angle??0)||!Number.isFinite(e.spins??0)||![1,-1].includes(o)||e.facing!==void 0&&!(typeof e.facing=="number"?Number.isFinite(e.facing):["inward","outward","tangent"].includes(e.facing)))throw new Error("danceCircleAt: center, angle, spins and facing must be finite; direction is 1 or -1");const r=e.character??gs({height:1.7}),a=e.style??"garba",l=(h,u)=>{const d=(e.angle??0)+360*u/n+o*360*h/s,f=d*Math.PI/180,p=e.facing??"inward",g=(typeof p=="number"?p:d+(p==="inward"?180:p==="tangent"?o*90:0))+(e.spins??0)*360*h/s,m=gi(a,h,{...e.pose,turn:g/90});return{character:r,position:[i[0]+e.radius*Math.sin(f),0,i[1]+e.radius*Math.cos(f)],pose:m.pose,heading:g,strike:m.strike}},c=gi(a,t).contact;return Array.from({length:n},(h,u)=>{const d=l(t,u);if(e.plantFeet===!1)return{...d,planted:!1};const f=l(c.start,u),p=In(f,`leg.${c.side}`,3),g=dg(d,c.side,p);return{...d,pose:Bl(d.pose,g.pose,c.weight),position:[d.position[0],g.position[1]*c.weight,d.position[2]],planted:g.reached&&c.weight===1}})}function Hv(t,e){if(e.count!==void 0&&e.count!==t.length)throw new Error("danceCircleTracks: count must match targets.length");const n=e.bpm??120,s=e.samplesPerBeat??16;if(!t.length||![n,e.beats,s].every(l=>Number.isFinite(l)&&l>0))throw new Error("danceCircleTracks: targets and positive finite bpm, beats and samplesPerBeat are required");if(!Number.isFinite(e.start??0))throw new Error("danceCircleTracks: start must be finite");const i=Math.max(1,Math.ceil(e.beats*s)),o=Array.from({length:i+1},(l,c)=>({time:(e.start??0)+e.beats*c/i*6e4/n,members:gg(e.beats*c/i,{...e,count:t.length})})),r=o.some(l=>l.members.some(c=>c.pose.roll!==0)),a=new Set(["x","y","z","rotateY",...r?["turn","roll"]:[]]);return t.flatMap((l,c)=>{const h=o.map(u=>{const d=u.members[c],{turn:f,...p}=d.pose;return{time:u.time,pose:{...r?d.pose:p,x:d.position[0],y:d.position[1],z:d.position[2],rotateY:r?0:d.heading}}});return Object.keys(h[0].pose).filter(u=>a.has(u)||h.some(d=>d.pose[u]!==(e.pose?.[u]??lt[u]))).map(u=>({id:`${l}-circle-${u}`,target:l,property:u,keyframes:h.map(d=>({time:d.time,value:d.pose[u],easing:"linear"}))}))})}const rr=t=>Math.min(1,Math.max(0,t));function Rv(t){const e={...ut,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 Lv(t){return t-Fv*Math.sin(2*Math.PI*t)/(2*Math.PI)}const Fv=.5;function Nv(t,e){if(!(e<=t.takeoff||e>=t.landing))return(e-t.takeoff)/(t.landing-t.takeoff)}function pg(t,e){const n=typeof t=="string"?vi[t]:t,s=Rv(n),i=rr(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=es(r.pose,a.pose,Wt(a.easing??"ease-in-out")(rr(l))),h=Nv(n,i);return h===void 0?{...c,spin:0,rise:0}:{...c,spin:n.spin*Lv(h),rise:4*n.height*h*(1-h)}}function mg(t,e,n){const s=typeof t=="string"?vi[t]:t,i=rr(e),o=rr((i-s.takeoff)/(s.landing-s.takeoff));return s.travel*n*o}function Wv(t,e,n={}){const s=typeof e=="string"?vi[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:pg(s,d)}}),c=Object.keys(ut).filter(h=>a.some(u=>u.pose[h]!==ut[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*mg(s,u.progress,n.height)}))})}return c}const Dv={leftHip:-55,leftKnee:-95,rightHip:55,rightKnee:95,leftShoulder:45,rightShoulder:-45,leftElbow:10,rightElbow:-10,lean:22,stretch:.94,headTilt:6},Bv={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},ar={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},zv={leftHip:-22,leftKnee:-30,rightHip:22,rightKnee:30,leftAnkle:10,rightAnkle:10,leftShoulder:-125,rightShoulder:125,leftElbow:0,rightElbow:0,lean:8,headTilt:0},qv={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 ps(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:Dv},{at:.27,pose:Bv,easing:"ease-out-quad"},...i,{at:.76,pose:zv},{at:.86,pose:qv,easing:"ease-out-quad"},{at:1,reset:!0}]}}const vi={frontFlip:ps("Front flip (tuck)",360,.56,.35,[{at:.38,pose:ar,easing:"ease-out-cubic"},{at:.64,pose:ar}]),backFlip:ps("Back flip (tuck)",-360,.58,-.15,[{at:.36,pose:{...ar,lean:18},easing:"ease-out-cubic"},{at:.64,pose:{...ar,lean:18}}]),layout:ps("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:ps("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:ps("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:ps("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)};function yg(t,e){const n=Math.min(1,Math.max(0,t.turn??0)),s=1-n,i={...lt,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)*jv,i[`eye.${l}`]=t[`${a}Eye`],i[`brow.${l}`]=t[`${a}Brow`],e&&Object.assign(i,Yv(l,e[a]??Ot,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 jv=70;function Yv(t,e,n,s){const i=t==="right"?1-s:1+s,o={};for(const r of Object.keys(Ot))o[`hand.${t}.${r}`]=e[r]??Ot[r];return o[`hand.${t}.turn`]=(e.turn??0)-i,o[`hand.${t}.roll`]=(e.roll??0)+n,o}class bg{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 Kv(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 Yl=Math.PI*2;function Xv(t,e=16){const n=new bg,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*Yl,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 wg(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*Yl;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 kg(t,e,n=24){const s=new bg,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*Yl;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 wg(s,t,o,1,i),wg(s,t,r,-1,i),s.build()}function lr(t){const e=Array.from({length:t.indices.length/3},()=>[]);for(const n of Kv(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 Kl=new Map;function Gv(t){const e=Kl.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 Kl.size<512&&Kl.set(t,n),n}Jt([-3,-5,-4]);const Uv=(t,e,n)=>{const s=Math.min(1,Math.max(0,(n-t)/(e-t)));return s*s*(3-2*s)};function vg(t,e,n){const s=[0,0,0];for(const i of n){const o=Gv(i.color);let r;if(i.light==="ambient")r=i.intensity;else if(i.light==="directional")r=i.intensity*Math.max(0,-$e(e,i.direction));else{const a=se(i.position,t),l=ro(a),c=l>0?pn(a,1/l):e,h=i.range?Math.max(0,1-l/i.range)**2:1;if(r=i.intensity*Math.max(0,$e(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*=Uv(u,d,-$e(c,i.direction))}}s[0]+=o[0]*r,s[1]+=o[1]*r,s[2]+=o[2]*r}return s}function Mg(t,e){return t?Math.min(1,Math.max(0,(e-t.near)/(t.far-t.near))):0}function Xl(t,e,n={}){t.save(),Vv(t,e,n),t.restore()}function Vv(t,e,n){const s=Gl(e,n);n.shadow!==!1&&Ul(t,e,n);for(const i of e.under)Sg(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)Sg(t,i,s,n)}function Sg(t,e,n,s){const i=s.loose?.[e.part.id];if(!i){Zl(t,e,n,s);return}if(i.opacity<=0)return;const o=e.faces.flatMap(c=>c.points);if(o.length===0)return;const r=o.map(c=>c.x),a=o.map(c=>c.y),l={x:(Math.min(...r)+Math.max(...r))/2,y:(Math.min(...a)+Math.max(...a))/2};t.save(),t.globalAlpha*=Math.min(1,i.opacity),t.translate(l.x+i.x,l.y+i.y),t.rotate(i.rotate*Math.PI/180),t.translate(-l.x,-l.y),Zl(t,e,n,s),t.restore()}function Gl(t,e={}){return e.lineWidth??Math.max(1.3,t.sizePx*.022)}function Ul(t,e,n={}){e.shadow.opacity<=0||e.shadow.points.length<3||(t.save(),t.globalAlpha=e.shadow.opacity,cr(t,e.shadow.points,n.ink??"#26262b",!1),t.restore())}function Jv(t,e,n,s={}){t.save(),Zl(t,e,n,s),t.restore()}function xg(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 b=g.normal[0]*(d[0]-g.center[0])+g.normal[1]*(d[1]-g.center[1])+g.normal[2]*(d[2]-g.center[2]);b>-Tg/5&&b<Tg&&(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=Vl(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?Eg(h,s):u.light?Zv(h,u,s):Jl(h);f&&(!i&&s.look==="silhouette"?d.shape(u.points,f,0):cr(t,u.points,i||u.light?f:hr(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 Tg=.05;function Vl(t,e,n,s){return ii(t,{look:s.look??"clean",ink:e.part.ink??s.ink??"#26262b",lineWidth:n,seed:ne(`${s.seed??0}:${e.part.id}`),time:s.time??0,pencil:{construction:!1,rubbedOut:0,...s.pencil}})}function Jl(t){const{part:e}=t;return e.glow&&t.glow>0&&e.fill?ec(e.fill,e.glow.color,t.glow):e.fill}function Zv(t,e,n){const{part:s}=t;if(!s.fill)return;const i=tc(s.fill,e.light,e.fog??0,n.fog);return s.glow&&t.glow>0?ec(i,s.glow.color,t.glow):i}function Eg(t,e){const n=Jl(t);return n&&(tM(n)||t.glow>0)?n:e.paper??"#fbf8ef"}function Zl(t,e,n,s){e.opacity<1?(t.save(),t.globalAlpha*=e.opacity,Ag(t,e,n,s),t.restore()):Ag(t,e,n,s)}function Ag(t,e,n,s){if(s.style==="stick")return Qv(t,e,n,s);const{part:i}=e,o=Vl(t,e,n,s),r=Jl(e),a=s.look==="silhouette";for(const c of e.faces)r&&(a?o.shape(c.points,r,0):cr(t,c.points,hr(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 Qv(t,e,n,s){const{part:i}=e;if(i.solidOnly)return;const o=Vl(t,e,n,s);if(e.spine){o.line(e.spine,n*1.15);return}const r=Eg(e,s);for(const l of e.faces)cr(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 tM(t){const e=ms(t);return e?(.299*e[0]+.587*e[1]+.114*e[2])/255<.3:!1}function cr(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 ms(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 Ql=t=>`#${t.map(e=>Math.round(Math.max(0,Math.min(255,e))).toString(16).padStart(2,"0")).join("")}`;function hr(t,e){const n=ms(t);return n?Ql(e>=1?n.map(s=>s+(255-s)*(e-1)*2):n.map(s=>s*e)):t}function tc(t,e,n,s){const i=ms(t);if(!i)return t;let o=i.map((a,l)=>a*e[l]);const r=s?ms(s):void 0;return r&&n>0&&(o=o.map((a,l)=>a+(r[l]-a)*n)),Ql(o)}function ec(t,e,n){const s=ms(t),i=ms(e);return!s||!i?n<.5?t:e:Ql(s.map((o,r)=>o+(i[r]-o)*n))}const eM=new Set(["x","y","z","position","rotateX","rotateY","rotateZ","quaternion","scale","scaleX","scaleY","scaleZ","visible","opacity","color"]),nM=new Set(["walk","walking","gait"]),$g=t=>typeof t=="number"?t:void 0,sM=1.7;function iM(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 oM(t){const e=$e([0,1,0],t);if(e>.999999)return ao();if(e<-.999999)return pe(Vt([1,0,0],180));const n=Vs([0,1,0],t);return pe(Vt(n,Math.acos(e)*180/Math.PI))}function rM(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,w,T)=>u.push({mesh:k,world:Rt(i,w),material:T}),f=(k,w,T)=>d(e.sphere,Sa(k,[0,0,0,1],[w,w,w]),T);for(const k of n.chains){const w=s.chains[k.id],T=k.id==="spine"?1.9:1;k.bones.forEach((P,S)=>{const x=w[S],M=w[S+1],E=Js(x,M),[I,A]=P.width??[1,1],O=h*T*(I+A)/2;if(E>1e-6){const H=mn(x,M,.5),W=oM(Jt(se(M,x)));d(e.cylinder,Rt(yn(H),Rt(W,bn([O,E,O]))),a)}f(x,h*T*I,a),f(M,h*T*A,a)}),k.id.startsWith("arm.")&&f(w[w.length-1],h*1.5,l)}const{center:p,rx:g,ry:m,axes:b}=s.head,v=[...b[0],0,...b[1],0,...b[2],0,...p,1];d(e.sphere,Rt(v,bn([g,m,g])),l);for(const k of[-1,1]){const w=Jt([k*.36,.15,.92]),T=Us(p,Us(Us(pn(b[0],w[0]*g*1.04),pn(b[1],w[1]*m*1.04)),pn(b[2],w[2]*g*1.04))),P=[...b[0],0,...b[1],0,...b[2],0,...T,1];d(e.sphere,Rt(P,bn([g*.11,m*.14,g*.03])),c)}return u}const aM={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:gs({...t.character,height:1}),cylinder:lr(kg(1,1,16)),sphere:lr(Xv(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={...lt,...l.pose};for(const[x,M]of n)typeof M=="number"&&!eM.has(x)&&!nM.has(x)&&(u[x]=M);const d=Math.max(0,Math.min(1,$g(n.get("walking"))??l.walking??0));if(d>0){const x=typeof n.get("gait")=="string"?n.get("gait"):l.gait,M=Vo(x,$g(n.get("walk"))??0,u);u=Object.fromEntries(Object.keys({...u,...M}).map(E=>[E,(u[E]??0)+((M[E]??0)-(u[E]??0))*d]))}const f=l.height??sM,p=Rt(i.view,s),g={toView:x=>ie(p,x),toScreen:x=>a(x)},b=-g.toView([0,f/2,0])[2];if(b<=i.near)return null;const v=l.shadow===!1?[]:[{depth:b+f,draw:x=>iM(x,g,f*.18)}];if(l.look==="solid"){const x=Ve(h.plan,u,{height:f,contact:h.contact});return{meshes:rM(l,c,h.plan,x,s),drawables:v}}const k=ie(s,[0,f*.6,0]),w=Jt(se(i.position,k)),T=vg(k,w,o).map(x=>Math.min(1,x));let P=h;if(o.length>0&&h.skin!=="none"){const x=tc(h.skin,T,Mg(r,Js(k,i.position)),r?.color);P={...h,skin:x,...h.body?{body:{...h.body,fill:x}}:{}}}const S=ag(P,u,g,{height:f});return{drawables:[...v,...S.map((x,M)=>({depth:-(x.sortDepth??x.depth)-M*1e-6,draw:(E,I)=>x.draw(E,I.time)}))]}}},Qe={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}},Mi=1,ur=.55,Pg=.35,lM=1.6,Ig={a:"a",e:"e",i:"i",y:"i",o:"o",u:"u"},Og={m:"m",b:"m",p:"m",f:"f",v:"f",w:"u",q:"u",l:"l",n:"l",d:"l",t:"l"},_g={अ:"a",आ:"a",इ:"i",ई:"i",उ:"u",ऊ:"u",ऋ:"i",ए:"e",ऐ:"e",ओ:"o",औ:"o",ऍ:"e",ऑ:"o"},Cg={"ा":"a","ि":"i","ी":"i","ु":"u","ू":"u","ृ":"i","े":"e","ै":"e","ो":"o","ौ":"o","ॅ":"e","ॉ":"o"},cM={प:"m",फ:"m",ब:"m",भ:"m",म:"m",व:"u"},hM="्",Hg="़",uM=t=>t>="क"&&t<="ह",Rg=new Set([".",",","!","?",";",":","…","।","॥","—","-"]);function Lg(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(Rg.has(o))s("rest",lM);else if(/\s/.test(o)){const a=e[e.length-1];a&&a.viseme!=="rest"&&e.push({viseme:"c",weight:Pg})}else if((o==="o"||o==="e")&&r===o)s(o==="o"?"u":"i",Mi),i++;else if(o in Ig)s(Ig[o],Mi);else if(o in Og)s(Og[o],ur);else{if(o==="h")continue;if(/[a-z]/.test(o))s("c",ur);else if(o in _g)s(_g[o],Mi);else if(uM(o)){const a=r===Hg?o==="फ"?"f":void 0:cM[o];s(a??"c",ur);let l=i+1;n[l]===Hg&&l++;const c=n[l];c===hM?i=l:c&&c in Cg?(s(Cg[c],Mi),i=l):(!c||/\s/.test(c)||Rg.has(c)||s("a",Mi*.6),i=l-1)}else(o==="ं"||o==="ँ")&&s("l",ur*.6)}}for(;e.length>0&&(e[e.length-1].viseme==="rest"||e[e.length-1].weight===Pg);)e.pop();return e}function nc(t,e={}){const n=e.fields?.mouth??"mouth",s=e.fields?.mouthWidth??"mouthWidth",i=e.energy??1,o=Lg(t.text),r=[{time:t.start,value:Qe.rest.mouth}],a=[{time:t.start,value:Qe.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=Qe[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:Qe.rest.mouth,easing:"ease-in-out"}),a.push({time:t.end,value:Qe.rest.mouthWidth,easing:"ease-in-out"})),{[n]:r,[s]:a}}function dM(t,e,n={}){const s={};for(const i of[...e].sort((o,r)=>o.start-r.start))for(const[o,r]of Object.entries(nc(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 dr(t,e,n,s={}){if(n.length===0)return e;const i=s.fields?.mouth??"mouth",o=s.fields?.mouthWidth??"mouthWidth",r={[i]:Qe.rest.mouth,[o]:Qe.rest.mouthWidth,...s.rest},a=new Ht({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=nc(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,b)=>m.time-b.time)}h.push({id:d?.id??`${t}-${u}`,target:t,property:u,keyframes:f})}return h}const Si=([t,e,n])=>{const s=Math.hypot(t,e,n)||1;return[t/s,e/s,n/s]};function Fg([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 ys=(t,[e,n,s])=>t==="z"?[e,n,s]:t==="x"?[s,n,e]:[e,s,n];function Ng(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(ys(n,[Math.cos(u)*t,Math.sin(u)*t,c]))}const a=[{corners:Array.from({length:s},(c,h)=>s-1-h),normal:ys(n,[0,0,-1])},{corners:Array.from({length:s},(c,h)=>s+h),normal:ys(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:ys(n,[Math.cos(u),Math.sin(u),0])})}const l=[];if(i>0)for(const c of[-r,r]){const h=o.push(ys(n,[0,0,c*1.01]))-1;for(let u=0;u<i;u++){const d=Math.PI*2*u/i,f=o.push(ys(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 Wg([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 Si([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 fM=t=>t.reduce((e,[n,s],i)=>{const[o,r]=t[(i+1)%t.length];return e+n*r-o*s},0)/2;function Dg(t,e){const n=fM(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:Si([0,-c,h])})}return{vertices:o,faces:r,creases:!0}}function Bg(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 zg(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=Si([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=Si(qg(h,u)),f=qg(d,h);for(let p=0;p<n;p++){const g=Math.PI*2*p/n,m=Math.cos(g)*s(a),b=Math.sin(g)*s(a);i.push([r[0]+d[0]*m+f[0]*b,r[1]+d[1]*m+f[1]*b,r[2]+d[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((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:Si([h[0]-u[0],h[1]-u[1],h[2]-u[2]])})}return{vertices:i,faces:o,creases:!1}}function qg(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 jg(t){switch(t.type){case"box":return Fg(t.size);case"cylinder":return Ng(t.radius,t.length,t.axis,t.segments,t.spokes);case"ellipsoid":return Wg(t.radii,t.segments);case"extrude":return Dg(t.profile,t.width);case"panel":return Bg(t.points,t.facing);case"tube":return{...zg(t.points,t.radius,t.segments),joined:t.joined}}}function sc(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 On=t=>Array.isArray(t)&&t.length===2&&t.every(e=>typeof e=="number"&&Number.isFinite(e));function fr(t,e){return((e-t)%360+540)%360-180}function Yg(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 bs(t,e){return Math.atan2(e[0]-t[0],e[1]-t[1])*180/Math.PI}function Kg(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:sc(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 Xg(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 Gg(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 xi=520,ic=["do","at","for","to","through","toward","speed","pose","gag","say","look","turns","dance","bpm","beats"],Ug=t=>Math.max(700,Array.from(t).length*65),Vg=70,Jg=35;function oc(t,e){const n=e[0]-t.x,s=e[1]-t.eyeHeight,i=e[2]-t.z,o=t.heading*Math.PI/180,r=n*Math.cos(o)-i*Math.sin(o),a=n*Math.sin(o)+i*Math.cos(o),l=Math.atan2(r,a)*180/Math.PI,c=Math.hypot(r,a),h=-Math.atan2(s,c)*180/Math.PI,u=Math.max(-Vg,Math.min(Vg,l*.75)),d=Math.max(-Jg,Math.min(Jg,h*.7));return{"head.turn":u,"head.nod":d,lookX:Math.max(-1,Math.min(1,(l-u)/45)),lookY:Math.max(-1,Math.min(1,(h-d)/30))}}const Zg={walk:1.3,bouncy:1.4,doubleBounce:1.2,sneak:.6,strut:1.2,tired:.8,run:3.6,shove:.7},rc=Object.keys(Kt),ac=Object.keys(ye),lc=Object.keys(Zo),gM=.25,pM=700/180,mM=200,yM=300;function Qg(t){if(!Array.isArray(t))return[{beat:-1,message:`Beats must be an array of { do: … } objects (got ${typeof t}).`}];const e=[...rc,"face","spin","dance","hold","pose","gag","place","say","look"],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))ic.includes(c)||o(ft("beat field",c,ic,a[c]));const l=typeof r.do=="string"?ac.includes(r.do)?"pose":lc.includes(r.do)?"gag":r.do==="turn"?"face":void 0:void 0;if(typeof r.do!="string"||!e.includes(r.do))return o(ft("character 3D beat",r.do,e,l));for(const c of["at","for","turns","bpm","beats"]){const h=r[c];h!==void 0&&(typeof h!="number"||!Number.isFinite(h)||(c==="at"?h<0:c!=="turns"&&h<=0))&&o(`\`${c}\` must be finite${c==="turns"?"":c==="at"?" and non-negative":" and positive"}.`)}if(r.do==="dance"&&!(typeof r.dance=="string"&&Object.hasOwn(Tn,r.dance))&&o(ft("native dance",r.dance,Object.keys(Tn))),rc.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&&!On(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(On))&&o("`through` is a list of points on the ground, each [x, z] metres.")),r.do==="place"&&!On(r.to)&&o("`place` needs `to`: a point on the ground, [x, z] metres."),r.do==="face"&&!(On(r.toward)||typeof r.toward=="number"&&Number.isFinite(r.toward))&&o("`face` needs `toward`: a point [x, z] or a finite heading in degrees."),r.do==="say"&&!(typeof r.say=="string"&&r.say.trim().length>0)&&o("`say` needs `say`: the line spoken."),r.do==="look"){const c=r.look??r.toward;Array.isArray(c)&&(c.length===2||c.length===3)&&c.every(u=>typeof u=="number"&&Number.isFinite(u))||c==="camera"||o("`look` needs `look`: a point [x, z] or [x, y, z] to look at, or `camera`.")}r.do==="pose"&&!(typeof r.pose=="object"&&r.pose!==null)&&!ac.includes(r.pose)&&o(ft("pose",r.pose,ac)),r.do==="gag"&&!lc.includes(r.gag)&&o(ft("gag",r.gag,lc))}),n}function bM(t,e,n){const s=Qg(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={...lt,...n.pose},r=(S,x=o)=>{const M=S.match(/^hand\.(?:left|right)\.(.+)$/)?.[1];return x[S]??lt[S]??(M?Ot[M]:void 0)??0};let[a,l]=n.position??[0,0],c=n.heading??0,h=0;const u=new Map,d=[],f=(S,x,M,E="linear")=>{const I=u.get(S)??[];I.push({time:x,value:M,easing:E}),u.set(S,I)},p=(S,x,M)=>{const E=u.get(S)??[];for(let I=E.length-1;I>=0;I--)if(E[I].time===x){if(E[I].value===M)return;break}f(S,x,M)};f("x",0,a),f("z",0,l),f("rotateY",0,c);const g=(S,x,M)=>{const E=fr(c,x);if(Math.abs(E)<1)return M!==void 0&&(p("rotateY",S,c),f("rotateY",S+M,c)),S+(M??0);const I=M??Math.max(mM,Math.abs(E)*pM);return p("rotateY",S,c),c+=E,f("rotateY",S+I,c,"ease-in-out"),S+I},m=(S,x,M,E="ease-in-out")=>{for(const[I,A]of Object.entries(M))r(I)!==A&&(p(I,S,r(I)),f(I,x,A,E),o[I]=A)},b=(S,x,M)=>{const E=Kg([[a,l],...x.through??[x.to]]);if(E.length<2)return M;const I=g(M,bs(E[0].point,E[1].point)),A=E[E.length-1].at,O=x.speed??Zg[S]*Math.sqrt(i/1.7),H=x.for??A/O*1e3,W=Jo(S,i),j=Wt("ease-in-out"),J=Math.min(yM,H/4);d.push({time:I,value:S}),p("walking",I,0),f("walking",I+J,1,"ease-out"),f("walking",I+H-J,1),f("walking",I+H,0,"ease-in");const tt=h;let V=c;for(let L=0;;L=Math.min(A,L+gM)){const q=I+Gg(j,L/A)*H,{point:G,direction:C}=Xg(E,L);V+=fr(V,bs([0,0],C));const Y=L===0?p:f;if(Y("x",q,G[0]),Y("z",q,G[1]),Y("rotateY",q,V),Y("walk",q,tt+L/W),L>=A)break}return h=tt+A/W,[a,l]=E[E.length-1].point,c=V,I+H},v=[],k=[];let w=0;for(const S of e){const x=S.at??w;let M=x;if(rc.includes(S.do))M=b(S.do,S,x);else if(S.do==="face")M=g(x,typeof S.toward=="number"?S.toward:bs([a,l],S.toward),S.for);else if(S.do==="spin")M=x+(S.for??1e3),p("rotateY",x,c),c+=(S.turns??1)*360,f("rotateY",M,c,"linear");else if(S.do==="dance"){const E=Tn[S.dance],I=S.bpm??E.bpm,A=S.beats??(S.for!==void 0?S.for*I/6e4:E.beats);M=x+(S.for??A*6e4/I);const O={...o},H=Math.max(1,Math.ceil(A*16)),W=Array.from({length:H+1},(J,tt)=>gi(S.dance,A*tt/H,O).pose),j=Math.min(150,(M-x)/4);for(const J of Object.keys(W[0])){const tt=r(J,O);J==="turn"||J==="roll"||W.every(V=>V[J]===tt)||(p(J,x,tt),W.slice(1).forEach((V,L)=>{const q=x+(M-x)*(L+1)/H,G=Math.min(1,(q-x)/j),C=G*G*(3-2*G);f(J,q,tt+(V[J]-tt)*C)}),o[J]=W[H][J])}}else if(S.do==="hold")M=x+(S.for??1e3);else if(S.do==="place")p("x",x,a),p("z",x,l),[a,l]=S.to,f("x",x+1,a),f("z",x+1,l),typeof S.toward=="number"&&(p("rotateY",x,c),c=S.toward,f("rotateY",x+1,c)),M=x+1;else if(S.do==="pose"){M=x+(S.for??500);const E=typeof S.pose=="string"?ye[S.pose]:S.pose;m(x,M,E)}else if(S.do==="gag"){const E=Bf(S.gag,{at:x,from:{...o}});let I=E[0];for(const A of E.slice(1))m(I.time,A.time,Object.fromEntries(Object.entries(A.pose).filter(([O,H])=>o[O]!==H)),A.easing??"ease-in-out"),I=A;M=I.time}else if(S.do==="say"){M=x+(S.for??Ug(S.say)),k.push({text:S.say,start:x,end:M});const E={tilt:o["head.tilt"]??0,left:o["brow.left"]??0,right:o["brow.right"]??0};let I=0;for(let A=x+xi;A<M-xi/2;A+=xi,I++){const O=I%2===0;m(A-xi/2,A,{"head.tilt":E.tilt+(O?3:-2),"brow.left":E.left+(O?.25:0),"brow.right":E.right+(O?.25:0)})}I>0&&m(M-xi/2,M,{"head.tilt":E.tilt,"brow.left":E.left,"brow.right":E.right})}else if(S.do==="look"){const E=S.look??S.toward,I=i*.9,A=E==="camera"?n.camera??[0,1.6,8]:E.length===3?E:[E[0],I,E[1]];M=x+(S.for??500),m(x,M,oc({x:a,z:l,heading:c,eyeHeight:I},A),"ease-out")}v.push({do:S.do,start:x,end:M}),w=M}const T=`${n.scene}/${t}`;let P=[...u].map(([S,x])=>({id:`${t}-${S}`,target:T,property:S,keyframes:Yg(x)}));return d.length>0&&P.push({id:`${t}-gait`,target:T,property:"gait",keyframes:d}),k.length>0&&(P=dr(T,P,k,{rest:{mouth:n.pose?.mouth??lt.mouth??0,mouthWidth:n.pose?.mouthWidth??lt.mouthWidth??1}})),{tracks:P,duration:w,beats:v,end:{position:[a,l],heading:c,pose:{...o}}}}function cc(t,e,n=[0,0,0]){const s=t.filter(o=>o.target===e),i=new Ht({id:`${e}-position`,tracks:s});return o=>{const r=i.getStateAtTime(o).values.get(e),a=r?.get("position");if(Array.isArray(a)&&a.length===3)return[a[0],a[1],a[2]];const l=(c,h)=>{const u=r?.get(c);return typeof u=="number"?u:h};return[l("x",n[0]),l("y",n[1]),l("z",n[2])]}}function wM(t,e){const n=`${e.scene}/${e.character}`,s=e.height??1.7,i=Math.max(1,e.every??66),o=e.objects?.[e.character]??[0,0,0],r=new Ht({id:`${n}-own`,tracks:t.filter(u=>u.target===n)}),a=e.at,l=typeof a=="function"?a:Array.isArray(a)?()=>a:"camera"in a?cc(t,`${e.scene}/${a.camera}`,e.objects?.[a.camera]??[0,1.6,8]):(()=>{const u=cc(t,`${e.scene}/${a.object}`,e.objects?.[a.object]??[0,0,0]),d=a.eyeHeight??s*.9;return f=>{const p=u(f);return[p[0],p[1]+d,p[2]]}})(),c=["head.turn","head.nod","lookX","lookY"],h={"head.turn":[],"head.nod":[],lookX:[],lookY:[]};for(let u=e.start;;u=Math.min(e.end,u+i)){const d=r.getStateAtTime(u).values.get(n),f=(g,m)=>{const b=d?.get(g);return typeof b=="number"?b:m},p=oc({x:f("x",o[0]),z:f("z",o[2]),heading:f("rotateY",0),eyeHeight:f("y",o[1])+s*.9},l(u));for(const g of c)h[g].push({time:u,value:p[g]??0});if(u>=e.end)break}return c.map(u=>({id:`${n}-lookAt-${u}`,target:n,property:u,keyframes:h[u]}))}function kM(t){const e=Math.max(1,Math.round(t.count)),[n,s]=t.centre??[0,0],i=t.spacing??1.2,o=t.shape??"line",r=[];if(o==="circle"){const h=e<2?0:Math.max(i,i*e/(Math.PI*2));for(let u=0;u<e;u++){const d=u/e*Math.PI*2,f=n+Math.sin(d)*h,p=s+Math.cos(d)*h;r.push({position:[f,p],heading:(Math.atan2(n-f,s-p)*180/Math.PI+360)%360})}return r}if(o==="cluster"){let h=(t.seed??1)>>>0||7;const u=()=>(h^=h<<13,h>>>=0,h^=h>>17,h^=h<<5,h>>>=0,h/4294967296),d=[];for(let f=0;f<e;f++){let p=[n,s],g=-1/0;for(let m=0;m<24;m++){const b=Math.sqrt(u())*i*Math.max(1,Math.sqrt(e)*.9),v=u()*Math.PI*2,k=[n+Math.cos(v)*b,s+Math.sin(v)*b],w=d.length===0?1/0:Math.min(...d.map(T=>Math.hypot(T[0]-k[0],T[1]-k[1])));if(w>g&&(g=w,p=k),w>=i)break}d.push(p),r.push({position:p,heading:0})}return r}const a=(t.heading??90)*Math.PI/180,l=i*(e-1),c=(t.bend??60)*Math.PI/180;for(let h=0;h<e;h++){const u=e===1?0:h/(e-1)-.5,d=u*l;let f=n+Math.sin(a)*d,p=s+Math.cos(a)*d,g=((t.heading??90)-90+360)%360;if(o==="arc"){const m=(1-Math.cos(u*c))*l*.5;f-=Math.cos(a)*m,p+=Math.sin(a)*m,g=(g-u*(t.bend??60)+360)%360}r.push({position:[f,p],heading:g})}return r}const tp={x:0,y:0,scale:1,rotate:0,shakeX:0,shakeY:0,shakeRotate:0};function vM(t){const e=n=>{const s=t?.get(n);return typeof s=="number"?s:tp[n]};return{x:e("x"),y:e("y"),scale:e("scale"),rotate:e("rotate"),shakeX:e("shakeX"),shakeY:e("shakeY"),shakeRotate:e("shakeRotate")}}function MM(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 SM(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 ep(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)ip(t,c,s);t.restore()}function hc(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 np=150,xM={pencil:44,eraser:30};function uc(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=np*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=St.pencilGrip,p=S=>{const x=S.fingers.thumb,M=S.fingers.index,E=S.fingers.middle,I=sp([x.points[3],M.points[3],E.points[3]]),A=sp([x.points[1],M.points[0]]),O=(x.depths[3]+M.depths[3]+E.depths[3])/3;return{pinch:I,direction:Math.atan2(A.y-I.y,A.x-I.x),depth:O}},g=Mo(f,{size:u}),m=c-p(g).direction,b=Mo(f,{size:u,angle:m*180/Math.PI}),v=p(b),k=xM[i]*a,w={x:v.pinch.x-Math.cos(c)*k,y:v.pinch.y-Math.sin(c)*k},T={x:d.x-w.x,y:d.y-w.y},P=b.axes.up;TM(t,T,{x:-P.x,y:-P.y},u,n.arm??300*a,o,n.sleeve??"#5b7db1",r),So(t,T,f,{size:u,angle:m*180/Math.PI,skin:o,ink:r,lineWidth:3*a,prop:{depth:v.depth,draw:()=>{t.save(),t.translate(d.x,d.y),t.scale(a,a),i==="eraser"?hc(t,{x:0,y:0},{angle:c*180/Math.PI,outline:r},s):ep(t,{x:0,y:0},{angle:c*180/Math.PI,length:190,outline:r},s),t.restore()}}})}const sp=t=>({x:t.reduce((e,n)=>e+n.x,0)/t.length,y:t.reduce((e,n)=>e+n.y,0)/t.length});function TM(t,e,n,s,i,o,r,a){const l={x:-n.y,y:n.x},c=s*.15,h=(g,m,b)=>({x:e.x+n.x*g+l.x*m*b,y:e.y+n.y*g+l.y*m*b}),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,PM(g)),m},f=Math.min(s*.55,i*.35);t.save(),t.lineJoin="round",t.lineCap="round",t.lineWidth=3*(s/np),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 EM(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,b)=>({x:g.x+(m.x-g.x)*b,y:g.y+(m.y-g.y)*b}),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:mo(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 AM(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 $M(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?yo(a,t.sketch,c):void 0;h>0&&(u?t.smooth?u.curve(e,h):u.line(e,h):ip(a,Qn(e,h))),r&&h>0&&h<1&&uc(a,mo(e,h),r,u)}}}function PM(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 ip(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 gr=1e5;function IM(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 dc(t,e,n,s){if(s<=0||e.length===0)return;const i=Qn(e,s),o=n/2,r=a=>{t.beginPath(),t.rect(-gr,-gr,2*gr,2*gr),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 OM(t,e,n,s,i){t.save(),dc(t,e,n,s),i(),t.restore()}function _M(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(),dc(o,e.path,n,l),t.draw(o,r,a),o.restore(),!i||l<=0||l>=1)return;const c=mo(e.path,l);s?uc(o,c,{...s,tool:"eraser"}):hc(o,c,i)}}}function ws(){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)=>pr(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:CM(i)}))}}}function pr(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 ks(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 CM(t){return[...t].sort((n,s)=>n.time-s.time).map(n=>({time:n.time,value:n.value,...n.easing?{easing:n.easing}:{}}))}const HM=.0016,RM=.6,tn=33;function Ti(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-tn),c=n(o,r);return{x:(c.x-l.x)/tn,y:(c.y-l.y)/tn}},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??HM,h=r.duration??900,u=(r.spin??RM)*(l.x<0?-1:1),d=t.valueAt(e(o,"rotate"),r.at);i(o,r.at);for(let f=0;f<=h;f+=tn){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 mr(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 w=n+a(k);return i.findIndex(T=>Math.abs(T.top-w)<.5)},c=(o?.keyframes??[]).map(k=>k.time),h=k=>{const w=M=>M<0?0:i[M].offset(k),T=l(k);if(T>=0)return w(T);if(Math.abs(a(k))<.5)return 0;const P=M=>l(M)>=0||Math.abs(a(M))<.5,S=[...c].reverse().find(M=>M<=k&&P(M)),x=c.find(M=>M>=k&&P(M));return S===void 0&&x===void 0?0:S===void 0?w(l(x)):x===void 0||x===S?w(l(S)):w(l(S))+(w(l(x))-w(l(S)))*(k-S)/(x-S)},u=i.flatMap(k=>k.windows),d=(k,w)=>u.some(T=>T.start<w&&T.end>k)||h(k)!==h(w),f=o?[...o.keyframes]:[{time:0,value:0}],p=[{...f[0],value:f[0].value+h(f[0].time)}],g=(k,w)=>{const T=new Set([w]);for(let P=k+s;P<w;P+=s)T.add(P);for(const P of u)for(const S of[P.start,P.end])S>k&&S<w&&T.add(S);for(const P of[...T].sort((S,x)=>S-x))p.push({time:P,value:a(P)+h(P)})};for(let k=1;k<f.length;k++){const w=f[k-1].time,T=f[k].time;d(w,T)?g(w,T):p.push({...f[k],value:f[k].value+h(T)})}const m=f[f.length-1].time,b=Math.max(m,...u.map(k=>k.end));b>m&&g(m,b);const v={id:o?.id??`${e}-y`,target:e,property:"y",keyframes:p};return o?t.map(k=>k===o?v:k):[...t,v]}function _n(t){const e=t.indexOf(":");return e<0?{kind:t,rest:""}:{kind:t.slice(0,e),rest:t.slice(e+1)}}function en(t,e,n,s){const i=Object.keys(n.anchors).map(r=>_n(r).kind),{kind:o}=_n(e);return i.includes(o)?new Error(`${t}: no anchor "${e}"${s?`: ${s}`:""} (anchors: ${Object.keys(n.anchors).join(", ")})`):new Error(`${t}: ${ft("anchor",o,i)} (anchors: ${Object.keys(n.anchors).join(", ")})`)}function Ei(t,e,n){return new Error(`${t}.edit: ${ft("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 op={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"},yr=["wipe","fly","blur"],Ai={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"}},LM=.9,FM=8;function NM(t){const e={...op,...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(L=>L.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(!wr.includes(f))throw new Error(`codePanel: ${ft("language",f,wr)}`);const p=n.map(L=>ap(L,f).flatMap(q=>Array.from(q.text,()=>e[q.kind]))),g=ws(),m=Ti(g),b=[],v=new Map,k=[],w=[],T=L=>{if(!Number.isInteger(L)||L<1||L>n.length)throw new Error(`codePanel: no line ${L} (it has ${n.length})`)},P=g.tween,S=g.last,x=(L,q,G,C,Y,st=300)=>{T(L),P(`line.${L}.${q}`,G,C,Y,st)},M=(L,q)=>b.filter(G=>G.line<L&&G.closed<=q).length,E=Mt,I=L=>t.y+r+(L-1)*i,A=L=>Array.isArray(L)?L:[L],O=(L,q,G)=>{let C=-1;for(let Y=0;Y<G;Y++)if(C=n[L-1].indexOf(q,C+1),C<0)throw new Error(`codePanel: line ${L} has no ${G>1?`${G}th `:""}"${q}"`);return C},H={};n.forEach((L,q)=>{const G=q+1;H[`line.${G}.highlight`]=0,H[`line.${G}.strike`]=0,H[`line.${G}.wipe`]=0,H[`line.${G}.reveal`]=d.has(G)?0:1,H[`line.${G}.shift`]=0});const W={type:"custom",x:t.x,y:t.y,width:c,height:h,props:H,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 DM(Object.keys(H))},actions:fc},draw(L,q){const G=q.props??{},C=_=>Number(G[_]??H[_]),Y=r+a,st=_=>r+(_-1)*i-C(`line.${_}.shift`)*i;L.fillStyle=e.background,rp(L,0,0,c,h,8),L.fill(),L.font=`${s}px ${e.font}`,L.textBaseline="middle",L.textAlign="left";const $=(_,z,K,N,F)=>{const D=n[_-1];for(let X=z;X<K;X++)D[X]!==" "&&(L.fillStyle=p[_-1][X],L.fillText(D[X],N+(X-z)*o,F))};L.save(),rp(L,0,0,c,h,8),L.clip(),n.forEach((_,z)=>{const K=z+1,N=C(`line.${K}.wipe`);if(N>=1)return;const F=st(K),D=F+i/2,X=Math.max(1,_.length)*o,B=Math.round(C(`line.${K}.reveal`)*_.length),Z=v.get(K)??{style:"wipe",from:"left"};L.save(),N>0&&WM(L,Z,N,{left:Y-a,top:F,width:a+X+o,height:i},c);const et=C(`line.${K}.highlight`);et>0&&(L.globalAlpha*=Math.min(1,et),L.fillStyle=e.highlight,L.fillRect(Y-o/2,F,X+o,i),L.globalAlpha/=Math.min(1,et)),a>0&&B>0&&(L.fillStyle=e.gutter,L.textAlign="right",L.fillText(String(K),Y-o,D),L.textAlign="left");const R=[...k.filter(ot=>ot.line===K).map(ot=>({column:ot.column,length:ot.text.length,piece:ot,insert:void 0})),...w.filter(ot=>ot.line===K).map(ot=>({column:ot.column,length:0,piece:void 0,insert:ot}))].sort((ot,ct)=>ot.column-ct.column||ot.length-ct.length);let U=0,nt=Y;for(const ot of R){$(K,U,Math.min(ot.column,B),nt,D),nt+=(ot.column-U)*o;let ct=ot.length,it="";if(ot.piece){const Q=ot.piece.written??"",rt=C(`piece.${ot.piece.id}.write`);Q&&rt>0?(it=Q.slice(0,Math.round(rt*Q.length)),ct=ot.length+(Q.length-ot.length)*Math.min(1,rt*2)):ct=ot.length*(1-C(`piece.${ot.piece.id}.away`))}else ot.insert&&(ct=ot.insert.chars*C(`insert.${ot.insert.id}.open`),ot.insert.text&&(it=ot.insert.text.slice(0,Math.round(C(`insert.${ot.insert.id}.type`)*ot.insert.text.length))));L.fillStyle=e.text;for(let Q=0;Q<it.length;Q++)it[Q]!==" "&&L.fillText(it[Q],nt+Q*o,D);nt+=ct*o,U=ot.column+ot.length}$(K,U,Math.max(U,B),nt,D);const at=C(`line.${K}.strike`);at>0&&(L.strokeStyle=e.strike,L.lineWidth=Math.max(1.5,s/10),L.beginPath(),L.moveTo(Y,D),L.lineTo(Y+X*Math.min(1,at),D),L.stroke()),L.restore()});for(const _ of k){const z=C(`piece.${_.id}.opacity`);if(z<=0||C(`line.${_.line}.wipe`)>=1)continue;const K=Y+(_.column+_.text.length/2)*o+C(`piece.${_.id}.x`),N=st(_.line)+i/2+C(`piece.${_.id}.y`);L.save(),L.globalAlpha=Math.min(1,z),L.translate(K,N),L.rotate(C(`piece.${_.id}.rotate`)*Math.PI/180),$(_.line,_.column,_.column+_.text.length,-_.text.length*o/2,0),L.restore()}L.restore()}},j=L=>{const{kind:q,rest:G}=_n(L),C=Y=>en("codePanel",L,Ai,Y);if(q==="box"){if(G)throw C("box takes no arguments");return{kind:q}}if(q==="line"){if(!/^\d+$/.test(G))throw C("write it line:N");return{kind:q,n:Number(G)}}if(q==="token"){const Y=/^(\d+)(?:#(\d+))?:(.+)$/.exec(G);if(!Y)throw C("write it token:N:TEXT, or token:N#K:TEXT for the Kth");return{kind:q,n:Number(Y[1]),occurrence:Y[2]?Number(Y[2]):1,text:Y[3]}}if(q==="spot"){const Y=/^(\d+):(\d+)(?::(\d+))?$/.exec(G);if(!Y)throw C("write it spot:N:C, or spot:N:C:W for W characters");return{kind:q,n:Number(Y[1]),column:Number(Y[2]),width:Y[3]?Number(Y[3]):1}}throw C()},J=(L,q,G,C=!1)=>{const Y=Array.isArray(q)?q:[q];if(Y.length===0||C&&Y.length>1)throw new Error(`codePanel.edit: ${L} takes ${C?"one":"at least one"} ${G} anchor`);return Y.map(st=>{const $=j(st);if($.kind!==G)throw new Error(`codePanel.edit: ${L} takes ${G} anchors (${G}:…), not "${st}"`);return $})},tt=(L,q)=>{if(typeof q.text!="string")throw new Error(`codePanel.edit: ${L} needs \`text\` (the text to write)`);return q.text},V={kind:"code",about:Ai,target:W,lines:n,box:E(t.x,t.y,c,h),line(L,q=1/0){return T(L),E(u,I(L)-M(L,q)*i,Math.max(1,n[L-1].length)*o,i)},token(L,q,G=1,C=1/0){T(L);const Y=O(L,q,G);return E(u+Y*o,I(L)-M(L,C)*i,q.length*o,i)},highlight(L,q){for(const G of A(L)){const C=S(`line.${G}.highlight`,0);x(G,"highlight",C,q.on===!1?0:1,q,200)}return V},strike(L,q){for(const G of A(L))x(G,"strike",S(`line.${G}.strike`,0),1,q);return V},remove(L,q){const G=A(L),C=q.style??"wipe";if(!yr.includes(C))throw new Error(`codePanel.remove: ${ft("style",C,yr)}`);const Y=C==="wipe"?300:450,st=q.at+(q.duration??Y),$=q.close??250;for(const _ of G)x(_,"wipe",0,1,{...q,easing:q.easing??(C==="fly"?"ease-in":void 0)},Y),v.set(_,{style:C,from:q.from??"left"}),b.push({line:_,closed:st+$});for(let _=1;_<=n.length;_++){if(G.includes(_))continue;const z=G.filter(N=>N<_).length;if(z===0)continue;const K=S(`line.${_}.shift`,0);x(_,"shift",K,K+z,{at:st,duration:$,easing:"ease-in-out"})}return V},type(L,q){return x(L,"reveal",0,1,{duration:n[L-1].length*45,...q}),V},piece(L,q,G=1){if(typeof L=="string"){const _=j(L);if(_.kind!=="token")throw new Error(`codePanel.piece: a piece is a word, token:N:TEXT, not "${L}"`);return V.piece(_.n,_.text,_.occurrence)}const C=L;if(q===void 0)throw new Error('codePanel.piece: which word? piece(n, text) or piece("token:N:TEXT")');T(C);const Y=O(C,q,G),st=k.find(_=>_.line===C&&_.column===Y&&_.text===q);if(st)return st;if(k.some(_=>_.line===C&&Y<_.column+_.text.length&&_.column<Y+q.length))throw new Error(`codePanel: "${q}" on line ${C} overlaps another piece`);const $={id:k.length+1,line:C,column:Y,text:q,home:V.token(C,q,G,0)};k.push($);for(const _ of["x","y","rotate","write","away"])H[`piece.${$.id}.${_}`]=0;return H[`piece.${$.id}.opacity`]=1,$},follow(L,q){return m.follow(L,q),V},fling(L,q){return m.fling(L,q),V},move(L,q){return m.move(L,q),V},write(L,q,G){return L.written=q,P(`piece.${L.id}.write`,0,1,{duration:Math.max(1,q.length)*70,...G}),V},spot(L,q,G=1,C=1/0){T(L);const Y=w.filter(st=>st.line===L&&st.column<=q&&st.at<=C).reduce((st,$)=>st+$.chars,0);return E(u+(q+Y)*o,I(L)-M(L,C)*i,G*o,i)},insert(L,q,G,C){T(L);const Y={id:w.length+1,line:L,column:q,chars:G.length,text:G,at:C.at};w.push(Y),H[`insert.${Y.id}.open`]=0,H[`insert.${Y.id}.type`]=0;const st=C.duration??G.length*70;return P(`insert.${Y.id}.open`,0,1,{at:C.at,duration:st*.6,easing:"ease-out"}),P(`insert.${Y.id}.type`,0,1,{at:C.at,duration:st}),V},drop(L,q,G,C){T(q);const Y=C.duration??250,st=q===L.line,$=C.easing??(st?"linear":"ease-out"),_=V.landing(L,q,G,C.at),z={id:w.length+1,line:q,column:G,chars:L.text.length,at:C.at};return w.push(z),H[`insert.${z.id}.open`]=0,P(`insert.${z.id}.open`,0,1,{at:C.at,duration:Y,easing:st?$:"ease-out"}),P(`piece.${L.id}.away`,S(`piece.${L.id}.away`,0),1,{at:C.at,duration:Y,easing:st?$:"ease-in-out"}),m.cutAfter(L,C.at),V.move(L,{at:C.at,duration:Y,easing:$,to:{x:_.x,y:_.y}}),P(`piece.${L.id}.rotate`,g.valueAt(`piece.${L.id}.rotate`,C.at),0,{at:C.at,duration:Y}),V},landing(L,q,G,C=1/0){const Y=V.spot(q,G,L.text.length,C),st=q===L.line&&G>L.column?L.text.length*o:0;return E(Y.left-st,Y.top,Y.width,Y.height)},ride(L,q,G){const C=n.map((Y,st)=>{const $=g.keys(`line.${st+1}.shift`)??[];return{top:I(st+1),offset:_=>-pr($,_)*i,windows:ks($)}});return mr(L,q,{ground:G.ground,every:G.every??tn,floors:C})},tracks:g.tracks,anchor(L,q=1/0){const G=j(L);return G.kind==="box"?V.box:G.kind==="line"?V.line(G.n,q):G.kind==="token"?V.token(G.n,G.text,G.occurrence,q):V.spot(G.n,G.column,G.width,q)},edit(L,q,G){const C=()=>J(L,q,"line").map(Y=>Y.n);if(L==="highlight")return V.highlight(C(),G);if(L==="strike")return V.strike(C(),G);if(L==="remove")return V.remove(C(),G);if(L==="type"){for(const Y of C())V.type(Y,G);return V}if(L==="insert"){const[Y]=J(L,q,"spot",!0);return V.insert(Y.n,Y.column,tt(L,G),G)}if(L==="write"||L==="drop"||L==="move"||L==="fling"){const[Y]=J(L,q,"token",!0),st=V.piece(Y.n,Y.text,Y.occurrence);if(L==="write")return V.write(st,tt(L,G),G);if(L==="fling")return V.fling(st,G);if(L==="drop"){const _=typeof G.into=="string"?j(G.into):void 0;if(_?.kind!=="spot")throw new Error("codePanel.edit: drop needs `into`, a spot anchor (spot:N:C)");return V.drop(st,_.n,_.column,G)}const $=typeof G.to=="string"?V.anchor(G.to,G.at):G.to;if(!$||typeof $.x!="number"||typeof $.y!="number")throw new Error("codePanel.edit: move needs `to`, an anchor name or { x, y }");return V.move(st,{...G,to:$})}throw Ei("codePanel",L,Ai)}};return V}function WM(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=FM*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*LM*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 fc={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 DM(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 rp(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 br={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:[]};br.typescript=[...br.javascript,"enum","interface","type","implements","private","public","readonly","keyof","as","declare","namespace"];const wr=Object.keys(br),BM={go:"//",rust:"//",csharp:"//",javascript:"//",typescript:"//",python:"#",plain:null};function ap(t,e){const n=new Set(br[e]),s=BM[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 gc='"Patrick Hand", "Segoe Print", "Bradley Hand", "Comic Sans MS", "Chalkboard SE", cursive',$i={whiteboard:{background:"#f7f7f2",frame:"#b8bcc4",ink:"#1f2a44",colors:{ink:"#1f2a44",red:"#d03b3b",blue:"#2f6fd0",green:"#2e9a52",orange:"#e07b1a"},font:gc,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:gc,stroke:.1,opacity:.9},lines:{background:"#fffdf5",frame:"#d9d3c0",ink:"#24315c",colors:{ink:"#24315c",red:"#c73b3b",blue:"#2f6fd0",green:"#2e9a52",orange:"#e07b1a",pencil:"#6b6b6b"},font:gc,stroke:.08,opacity:1,rule:{color:"#c9d6ec",spacing:1.55,margin:"#f0a3a3"}}},pc=["circle","box","underline","arrow"],He={kind:"board",create:"whiteboard({ x, y, width, height, theme?: whiteboard | chalkboard | lines, fontSize?, items: [{ id, text, at: [x, y], size?, color?, hidden? } | { id, mark: circle | box | underline | arrow, around? | from?, to?, bend?, 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"}},lp=90,cp=300,zM=.3;function qM(t){const e=typeof t.theme=="string"?t.theme:"whiteboard";if(!(e in $i))throw new Error(`whiteboard: ${ft("theme",e,Object.keys($i))}`);const n=typeof t.theme=="object"?{...$i.whiteboard,...t.theme}:$i[e],s=t.fontSize??28,i=t.charWidth??.55,o=w=>w===void 0?n.ink:n.colors[w]??w,r=w=>Mt(t.x+w.left,t.y+w.top,w.width,w.height),a=ws(),l=Ti(a),c={},h=new Map,u=[],d=[],f=(w,T,P,S)=>{const x=h.get(w);if(!x||x.kind!=="text")throw en("whiteboard",S,He,`there is no text "${w}" (texts: ${p().join(", ")||"none"})`);let M=-1;for(let I=0;I<P;I++)if(M=x.item.text.indexOf(T,M+1),M<0)throw en("whiteboard",S,He,`text "${w}" has no ${P>1?`${P}th `:""}"${T}"`);const E=x.size*i;return{column:M,box:Mt(x.box.left+M*E,x.box.top,T.length*E,x.box.height)}},p=()=>[...h.values()].filter(w=>w.kind==="text").map(w=>w.item.id),g=w=>{const{kind:T,rest:P}=_n(w),S=x=>en("whiteboard",w,He,x);if(T==="box"){if(P)throw S("box takes no arguments");return{kind:T}}if(T==="text"||T==="mark"){if(!P)throw S(`write it ${T}:ID`);return{kind:T,id:P}}if(T==="term"){const x=/^([^:#]+)(?:#(\d+))?:(.+)$/.exec(P);if(!x)throw S("write it term:ID:TEXT, or term:ID#K:TEXT for the Kth");return{kind:T,id:x[1],occurrence:x[2]?Number(x[2]):1,text:x[3]}}throw S()},m=w=>{const T=g(w);if(T.kind==="box")return Mt(0,0,t.width,t.height);if(T.kind==="term")return f(T.id,T.text,T.occurrence,w).box;const P=h.get(T.id);if(!P||P.kind!==T.kind){const S=[...h.values()].filter(x=>x.kind===T.kind).map(x=>x.item.id);throw en("whiteboard",w,He,`there is no ${T.kind} "${T.id}" (${T.kind}s: ${S.join(", ")||"none"})`)}return P.box};for(const w of t.items??[]){if(!w||typeof w.id!="string"||!w.id||/[:#]/.test(w.id))throw new Error(`whiteboard: every item needs an \`id\` without ":" or "#" (got ${JSON.stringify(w?.id)})`);if(h.has(w.id))throw new Error(`whiteboard: two items are called "${w.id}"`);if("text"in w){if(!Array.isArray(w.at)||w.at.length!==2||!w.at.every(I=>typeof I=="number"))throw new Error(`whiteboard: text "${w.id}" needs \`at\`, [x, y] from the board's top-left`);const M=w.size??s,E=Mt(w.at[0],w.at[1],Math.max(1,w.text.length)*M*i,M*1.3);h.set(w.id,{kind:"text",item:w,size:M,color:o(w.color),box:E}),c[`text.${w.id}.write`]=w.hidden?0:1,c[`text.${w.id}.erase`]=0;continue}if(!pc.includes(w.mark))throw new Error(`whiteboard: mark "${w.id}": ${ft("mark",w.mark,pc)}`);const T=w.mark==="arrow"?["from","to"]:["around"];for(const M of T)if(typeof w[M]!="string")throw new Error(`whiteboard: ${w.mark} "${w.id}" needs \`${M}\`, a place on the board (an item before it)`);const P=new Set([w.from,w.to].filter(M=>typeof M=="string").map(M=>M.split(":")[1])),S=w.mark==="arrow"?[...h.values()].filter(M=>M.kind==="text"&&!P.has(M.item.id)).map(M=>M.box):[],x=jM(w,m,s,S);h.set(w.id,{kind:"mark",item:w,color:o(w.color),points:x,box:XM(x)}),c[`mark.${w.id}.draw`]=w.hidden?0:1,c[`mark.${w.id}.erase`]=0}const b=w=>u.filter(T=>T.item===w),v={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 GM(Object.keys(c))},actions:He.edits},draw(w,T){const P=T.props??{},S=x=>Number(P[x]??c[x]??0);if(w.save(),w.fillStyle=n.background,dp(w,0,0,t.width,t.height,10),w.fill(),w.lineWidth=Math.max(4,t.width*.012),w.strokeStyle=n.frame,w.stroke(),n.rule){w.save(),w.beginPath(),dp(w,0,0,t.width,t.height,10),w.clip(),w.lineWidth=1,w.strokeStyle=n.rule.color;const x=s*(n.rule.spacing??1.55);for(let M=x;M<t.height;M+=x)w.beginPath(),w.moveTo(0,M),w.lineTo(t.width,M),w.stroke();n.rule.margin&&(w.strokeStyle=n.rule.margin,w.beginPath(),w.moveTo(s*2.2,0),w.lineTo(s*2.2,t.height),w.stroke()),w.restore()}w.textAlign="center",w.textBaseline="middle",w.lineCap="round",w.lineJoin="round",w.globalAlpha=n.opacity;for(const x of h.values()){if(w.save(),mc(w,x.box,S(`${x.kind}.${x.item.id}.erase`)),x.kind==="text"){const M=b(x.item.id),E=S(`text.${x.item.id}.write`)*x.item.text.length;w.font=`${x.size}px ${n.font}`,w.fillStyle=x.color;for(let I=0;I<Math.ceil(E);I++)x.item.text[I]===" "||M.some(A=>I>=A.column&&I<A.column+A.text.length)||(w.globalAlpha=n.opacity*Math.min(1,E-I),w.fillText(x.item.text[I],x.box.left+(I+.5)*x.size*i,x.box.y))}else up(w,x.points,S(`mark.${x.item.id}.draw`),x.color,s*n.stroke,x.item.mark==="arrow");w.restore()}for(const x of d){const M=S(`strike.${x.id}.draw`);if(M<=0)continue;const{box:E}=x,I=E.height*.15;up(w,[{x:E.left-3,y:E.y+I},{x:E.right+3,y:E.y-I}],M,n.colors.red??n.ink,s*n.stroke*.8,!1)}for(const x of u){const M=h.get(x.item),E=M.size*i;w.font=`${M.size}px ${n.font}`,w.fillStyle=M.color;const I=x.written;if(I){const W=S(`piece.${x.id}.write`)*I.length,j=x.home.x-t.x-I.length*E/2;for(let J=0;J<Math.ceil(W);J++)I[J]!==" "&&(w.globalAlpha=n.opacity*Math.min(1,W-J),w.fillText(I[J],j+(J+.5)*E,x.home.y-t.y))}const A=S(`piece.${x.id}.opacity`)*Math.min(1,S(`text.${x.item}.write`)*M.item.text.length-x.column);if(A<=0)continue;w.save();const O={x:x.home.x-t.x,y:x.home.y-t.y},H={x:S(`piece.${x.id}.x`),y:S(`piece.${x.id}.y`)};mc(w,Mt(O.x+H.x-x.home.width/2,O.y+H.y-x.home.height/2,x.home.width,x.home.height),S(`piece.${x.id}.erase`)),Math.hypot(H.x,H.y)<1&&mc(w,M.box,S(`text.${x.item}.erase`)),w.globalAlpha=n.opacity*Math.min(1,A),w.translate(O.x+H.x,O.y+H.y),w.rotate(S(`piece.${x.id}.rotate`)*Math.PI/180);for(let W=0;W<x.text.length;W++)x.text[W]!==" "&&w.fillText(x.text[W],(W+.5-x.text.length/2)*E,0);w.restore()}w.restore()}},k={kind:"board",about:He,target:v,box:Mt(t.x,t.y,t.width,t.height),anchor(w){return r(m(w))},piece(w){const T=g(w);if(T.kind!=="term")throw new Error(`whiteboard.piece: a piece is a term, term:ID:TEXT, not "${w}"`);const{column:P,box:S}=f(T.id,T.text,T.occurrence,w),x=u.find(E=>E.item===T.id&&E.column===P&&E.text===T.text);if(x)return x;if(u.some(E=>E.item===T.id&&P<E.column+E.text.length&&E.column<P+T.text.length))throw new Error(`whiteboard: "${T.text}" in "${T.id}" overlaps another piece`);const M={id:u.length+1,item:T.id,column:P,text:T.text,home:r(S)};u.push(M);for(const E of["x","y","rotate","erase","write"])c[`piece.${M.id}.${E}`]=0;return c[`piece.${M.id}.opacity`]=1,M},edit(w,T,P){const S=Array.isArray(T)?T:[T];if(S.length===0)throw new Error(`whiteboard.edit: ${w} takes at least one anchor`);const x=S.map(I=>({name:I,anchor:g(I)}));for(const{name:I}of x)m(I);const M=(I,A=!1)=>{const O=x.find(H=>!I.includes(H.anchor.kind));if(O)throw new Error(`whiteboard.edit: ${w} takes ${I.join(" or ")} anchors, not "${O.name}"`);if(A&&x.length>1)throw new Error(`whiteboard.edit: ${w} takes one ${I.join(" or ")} anchor`)},E=()=>k.piece(x[0].name);if(w==="write"){if(x.some(I=>I.anchor.kind==="term")){if(M(["term"],!0),typeof P.text!="string")throw new Error("whiteboard.edit: write into a term needs `text` (the new text)");const I=E();return I.written=P.text,a.tween(`piece.${I.id}.write`,0,1,{duration:Math.max(cp,P.text.length*lp),...P}),k}M(["text"]);for(const{anchor:I}of x){const A=I.id,O=h.get(A).item.text;a.tween(`text.${A}.write`,0,1,{duration:Math.max(cp,O.length*lp),...P})}return k}if(w==="draw"){M(["mark"]);for(const{anchor:I}of x)a.tween(`mark.${I.id}.draw`,0,1,{duration:500,...P});return k}if(w==="erase"){M(["text","term","mark"]);for(const I of x){const A=I.anchor.kind==="term"?`piece.${k.piece(I.name).id}.erase`:`${I.anchor.kind}.${I.anchor.id}.erase`;a.tween(A,0,1,{duration:400,...P})}return k}if(w==="strike"){M(["text","term"]);for(const I of x){const A={id:d.length+1,box:m(I.name)};d.push(A),c[`strike.${A.id}.draw`]=0,a.tween(`strike.${A.id}.draw`,0,1,{duration:250,...P})}return k}if(w==="move"){M(["term"],!0);const I=typeof P.to=="string"?k.anchor(P.to):P.to;if(!I||typeof I.x!="number"||typeof I.y!="number")throw new Error("whiteboard.edit: move needs `to`, an anchor name or { x, y }");return k.move(E(),{...P,to:I})}if(w==="fling")return M(["term"],!0),k.fling(E(),P);throw Ei("whiteboard",w,He)},follow(w,T){return l.follow(w,T),k},fling(w,T){return l.fling(w,T),k},move(w,T){return l.move(w,T),k},ride(w){return w},tracks:a.tracks};return k}function jM(t,e,n,s=[]){const i=Ye(ne(t.id)),o=g=>(i.next()*2-1)*g,r=n*zM;if(t.mark==="arrow"){const g=e(t.from),m=e(t.to),b=hp(g,m,r*.6),v=hp(m,g,r*.6),k=Math.hypot(v.x-b.x,v.y-b.y),w=KM(b,v);let T=k*(.06+o(.04));if(t.bend!==void 0)T=k*t.bend;else{const x=YM(b,v,w,s,r);x!==0&&(T=x)}const P={x:(b.x+v.x)/2+w.x*T,y:(b.y+v.y)/2+w.y*T},S=[];for(let x=0;x<=24;x++){const M=x/24;S.push({x:(1-M)**2*b.x+2*(1-M)*M*P.x+M*M*v.x,y:(1-M)**2*b.y+2*(1-M)*M*P.y+M*M*v.y})}return S}const a=e(t.around);if(t.mark==="underline"){const g=a.bottom+r*.4;return[{x:a.left-r*.3,y:g+o(2)},{x:a.x,y:g+2+o(2)},{x:a.right+r*.5,y:g-1+o(3)}]}if(t.mark==="box"){const g=a.left-r,m=a.right+r,b=a.top-r*.6,v=a.bottom+r*.6,k=(T,P)=>({x:T+o(r*.2),y:P+o(r*.2)}),w=k(g,b);return[w,k(m,b),k(m,v),k(g,v),w,{x:w.x+r*.8,y:w.y+o(2)}]}const l=a.width/2+r,c=a.height/2+r*.6,h=-2.2+o(.3),u=i.next()*Math.PI*2,d=1.12,f=64,p=[];for(let g=0;g<=f*d;g++){const m=g/f,b=h+m*Math.PI*2,v=1+.035*Math.sin(m*Math.PI*4+u)+.06*m;p.push({x:a.x+Math.cos(b)*l*v,y:a.y+Math.sin(b)*c*v})}return p}function YM(t,e,n,s,i){const o=Math.hypot(e.x-t.x,e.y-t.y);if(o<1e-6)return 0;const r={x:(e.x-t.x)/o,y:(e.y-t.y)/o};let a=0,l=0;for(const c of s){const u=[{x:c.left,y:c.top},{x:c.right,y:c.top},{x:c.right,y:c.bottom},{x:c.left,y:c.bottom}].map(p=>({t:(p.x-t.x)*r.x+(p.y-t.y)*r.y,n:(p.x-t.x)*n.x+(p.y-t.y)*n.y})),d=u.some(p=>p.t>0&&p.t<o),f=u.some(p=>p.n>0)&&u.some(p=>p.n<0);!d||!f||(a=Math.max(a,...u.map(p=>p.n)),l=Math.min(l,...u.map(p=>p.n)))}return a===0&&l===0?0:a<=-l?2*(a+i):2*(l-i)}function hp(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 KM(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 XM(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 up(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 mc(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 dp(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 GM(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 yc=["bar","line","pie","donut"],fp='system-ui, -apple-system, "Segoe UI", sans-serif',Pi={light:{background:"#ffffff",text:"#3b4252",grid:"#d8dee9",color:"#4c7bd9",highlight:"#e8833a",palette:["#4c7bd9","#3fa66b","#b05cc9","#d9c04c","#4cb8c4","#d95c6f","#8a7a5a","#6b7a99"],font:fp},dark:{background:"#1e2230",text:"#cdd6f4",grid:"#3a4055",color:"#89b4fa",highlight:"#fab387",palette:["#89b4fa","#a6e3a1","#cba6f7","#f9e2af","#94e2d5","#f38ba8","#b4a58a","#9399b2"],font:fp}},Cn={kind:"chart",create:"chart({ x, y, width, height, kind: bar | line | pie | donut, data: [{ id, label?, value | values: { SERIES: value }, hidden? }], series?: [{ id, label?, color? }], max?, title?, axis?: { x?, y? }, legend?, theme?: light | dark, decimals?, prefix?, suffix?, values? })",anchors:{box:"the whole chart","bar:ID":"a bar (bar charts; bar:ID:SERIES with several series), 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; point:ID:SERIES with several series), as it stands at the time","slice:ID":"a slice of a pie or donut, as it stands at the time (its middle; pulled out, it moves): point at it, make it a piece","label:ID":"its label: under the axis, or beside the slice","value:ID":"its value label: above the bar or point (value:ID:SERIES), or on the slice","legend:SERIES":"a series in the legend (several series)"},edits:{set:"bar, point or slice anchors; { at, value, duration? }: animate to a new value; its value label counts along (a pie re-shares the circle)",show:"bar, point or slice anchors given `hidden`; { at, duration?, on? }: grow a bar in from the axis, draw the line out to a point, or open a slice (on: false takes it back)",highlight:"bar, point or slice anchors; { at, duration?, on? }: colour it out (on: false clears)",pull:"slice anchors; { at, duration?, on? }: pull the slice out from the centre (on: false puts it back)"}},UM=600,VM=500,JM=200,ZM=400,QM=.14,tS=Math.PI*2;function eS(t){if(!yc.includes(t.kind))throw new Error(`chart: ${ft("kind",t.kind,yc)}`);const e=typeof t.theme=="string"?t.theme:"light";if(!(e in Pi))throw new Error(`chart: ${ft("theme",e,Object.keys(Pi))}`);const n=typeof t.theme=="object"?{...Pi.light,...t.theme}:Pi[e];if(!Array.isArray(t.data)||t.data.length===0)throw new Error("chart: `data` needs at least one { id, value }");const s=t.kind,i=s==="pie"||s==="donut",o=Array.isArray(t.series)&&t.series.length>1,r=Array.isArray(t.series)&&t.series.length>0?t.series:[{id:"value"}];if(i&&o)throw new Error(`chart: a ${s} shows one series (got ${r.length}); make a chart per series`);const a=new Set;for(const R of r){if(typeof R?.id!="string"||!R.id||/[:.]/.test(R.id))throw new Error(`chart: every series needs an \`id\` without ":" or "." (got ${JSON.stringify(R?.id)})`);if(a.has(R.id))throw new Error(`chart: two series are called "${R.id}"`);a.add(R.id)}const l=new Map(r.map((R,U)=>[R.id,U])),c=R=>r[l.get(R)].color??(l.get(R)===0?n.color:n.palette[l.get(R)%n.palette.length]),h=new Set,u=(R,U)=>{const nt=R.values?.[U.id]??(t.series?void 0:R.value)??R.value;if(typeof nt!="number"||!Number.isFinite(nt))throw new Error(o?`chart: "${R.id}" needs a value for series "${U.id}" (\`values: { ${U.id}: … }\`)`:`chart: "${R.id}" needs a \`value\`, a number`);return nt};for(const R of t.data){if(typeof R?.id!="string"||!R.id||/[:.]/.test(R.id))throw new Error(`chart: every datum needs an \`id\` without ":" or "." (got ${JSON.stringify(R?.id)})`);if(h.has(R.id))throw new Error(`chart: two data are called "${R.id}"`);for(const U of r)u(R,U);h.add(R.id)}const d=s==="bar"?"bar":s==="line"?"point":"slice",f=Math.max(...t.data.flatMap(R=>r.map(U=>u(R,U)))),p=i?t.data.reduce((R,U)=>R+u(U,r[0]),0):t.max??gp(f*1.1);if(!i&&!(p>0))throw new Error(`chart: \`max\` must be above 0 (got ${p})`);const g=Math.max(10,Math.min(16,t.height/20)),m=o&&t.legend!==!1,b=i?void 0:t.axis?.x,v=i?void 0:t.axis?.y,k=t.title?g*2.3:g*.5,w={left:g*3.6+(v?g*1.5:0),right:t.width-g,top:(t.title?g*3:g*1.6)+(m?g*1.6:0),bottom:t.height-g*2.4-(b?g*1.4:0)},T=w.bottom-w.top,P=(w.right-w.left)/t.data.length,S=o?P*.72/r.length:P*.6,x=o?S*.86:S,M=Math.max(4,g*.35),E=T/p,I=new Map(t.data.map((R,U)=>[R.id,U])),A=R=>w.left+P*(I.get(R)+.5),O=(R,U)=>o?A(R)-P*.36+S*l.get(U)+(S-x)/2:A(R)-x/2,H=(R,U)=>O(R,U)+x/2,W=t.height-g*1.2,j={cx:t.width/2,cy:(w.top+W)/2,r:Math.max(10,Math.min(t.width/2,(W-w.top)/2)-g*2.6)},J=s==="donut"?j.r*.55:0,tt=s==="donut"?(J+j.r)/2:j.r*.62,V=new Map;if(m){let R=w.right;for(const U of[...r].reverse()){const nt=U.label??U.id,at=g*.62*nt.length+g*1.9;V.set(U.id,Mt(R-at,k,at,g*1.4)),R-=at+g*.6}}const L=ws(),q=Ti(L),G={},C=(R,U,nt)=>o?`${d}.${R}.${U}.${nt}`:`${d}.${R}.${nt}`;for(const R of t.data)for(const U of r)G[C(R.id,U.id,"value")]=u(R,U),G[C(R.id,U.id,"show")]=R.hidden?0:1,G[C(R.id,U.id,"highlight")]=0,i&&(G[C(R.id,U.id,"pull")]=0);const Y=(R,U)=>L.keys(R)?.length?pr(L.keys(R),U):G[R],st=(R,U,nt)=>Y(C(R,U,"value"),nt)*(s==="bar"?Y(C(R,U,"show"),nt):1)*E,$=R=>{const U=r[0].id,nt=t.data.map(it=>Math.max(0,R(C(it.id,U,"value")))*Math.max(0,Math.min(1,R(C(it.id,U,"show"))))),at=nt.reduce((it,Q)=>it+Q,0),ot=new Map;let ct=-Math.PI/2;return t.data.forEach((it,Q)=>{const rt=at>0?tS*nt[Q]/at:0,ht=ct+rt/2,dt=Math.max(0,Math.min(1,R(C(it.id,U,"pull"))))*j.r*QM;ot.set(it.id,{start:ct,sweep:rt,mid:ht,out:dt,centre:{x:j.cx+Math.cos(ht)*(tt+dt),y:j.cy+Math.sin(ht)*(tt+dt)}}),ct+=rt}),ot},_=R=>$(U=>Y(U,R)),z=R=>{const{kind:U,rest:nt}=_n(R),at=ot=>en("chart",R,Cn,ot);if(U==="box"){if(nt)throw at("box takes no arguments");return{kind:"box"}}if(U==="legend"){if(!V.has(nt))throw at(m?`there is no series "${nt}" (series: ${r.map(ot=>ot.id).join(", ")})`:"only a chart with several series has a legend");return{kind:"legend",series:nt}}if(U==="bar"||U==="point"||U==="slice"||U==="label"||U==="value"){if(!nt)throw at(`write it ${U}:ID`);const ot=nt.indexOf(":"),ct=ot<0?nt:nt.slice(0,ot),it=ot<0?r[0].id:nt.slice(ot+1);if(!I.has(ct))throw at(`there is no "${ct}" (data: ${[...I.keys()].join(", ")})`);if(!a.has(it))throw at(`there is no series "${it}" (series: ${r.map(Q=>Q.id).join(", ")})`);if(U==="label"&&ot>=0)throw at("a label is one per datum: label:ID");if((U==="bar"||U==="point"||U==="slice")&&U!==d)throw at(`a ${s} chart has ${d}s, not ${U}s: ${d}:${ct}`);return{kind:U,id:ct,series:it}}throw at()},K=(R,U)=>{if(R.kind==="box")return Mt(0,0,t.width,t.height);if(R.kind==="legend")return V.get(R.series);if(i){const it=_(U).get(R.id),Q=Math.max(g*1.5,j.r*.42);if(R.kind==="slice")return Mt(it.centre.x-Q/2,it.centre.y-Q/2,Q,Q);const rt=N(it);return R.kind==="label"?rt:it.sweep>=.3?Mt(it.centre.x-g*1.6,it.centre.y-g*.65,g*3.2,g*1.3):Mt(rt.left,rt.bottom,rt.width,g*1.3)}const nt=R.kind==="label"?A(R.id):H(R.id,R.series),at=w.bottom-st(R.id,R.series,U);if(R.kind==="bar")return Mt(nt-x/2,at,x,w.bottom-at);if(R.kind==="point")return Mt(A(R.id)-M,at-M,M*2,M*2);if(R.kind==="label")return Mt(nt-P/2,w.bottom+g*.4,P,g*1.4);const ot=at-(s==="line"?M:0)-g*.3,ct=o&&s==="bar"?S:P;return Mt((s==="line"?A(R.id):nt)-ct/2,ot-g*1.3,ct,g*1.3)},N=R=>{const U=j.r+R.out+g*.9,nt={x:j.cx+Math.cos(R.mid)*U,y:j.cy+Math.sin(R.mid)*U},at=g*4.2,ot=Math.cos(R.mid),ct=ot>.2?nt.x:ot<-.2?nt.x-at:nt.x-at/2;return Mt(ct,nt.y-g*.7,at,g*1.4)},F=R=>Mt(t.x+R.left,t.y+R.top,R.width,R.height),D=R=>`${t.prefix??""}${R.toFixed(t.decimals??0)}${t.suffix??""}`,X=new Map,B={type:"custom",x:t.x,y:t.y,width:t.width,height:t.height,props:G,about:{kind:`${s} chart`,summary:`A ${s} chart of ${t.data.length} values (${t.data.map(R=>R.id).join(", ")})${o?` in ${r.length} series (${r.map(R=>R.id).join(", ")})`:""}${i?"":`, scaled to ${p}`}. Its ${d}s and labels are places in the scene (anchor()); its edits record tracks (edit(), tracks()).`,props:Object.fromEntries(Object.keys(G).map(R=>[R,iS(R)])),actions:Cn.edits},draw(R,U){const nt=U.props??{},at=it=>Number(nt[it]??G[it]??0);if(R.save(),R.fillStyle=n.background,pp(R,0,0,t.width,t.height,8),R.fill(),R.font=`${g}px ${n.font}`,R.textBaseline="middle",t.title&&(R.fillStyle=n.text,R.textAlign="left",R.font=`600 ${g*1.2}px ${n.font}`,R.fillText(t.title,i?g:w.left,g*1.5),R.font=`${g}px ${n.font}`),m){R.textAlign="left";for(const it of r){const Q=V.get(it.id);R.fillStyle=c(it.id),pp(R,Q.left,Q.top+g*.25,g*.9,g*.9,2),R.fill(),R.fillStyle=n.text,R.fillText(it.label??it.id,Q.left+g*1.3,Q.top+Q.height/2)}}if(i){Z(R,at),R.restore();return}R.lineWidth=1,R.textAlign="right";for(let it=0;it<=4;it++){const Q=w.bottom-T*it/4;R.strokeStyle=n.grid,R.beginPath(),R.moveTo(w.left,Q),R.lineTo(w.right,Q),R.stroke(),R.fillStyle=n.text,R.globalAlpha=.7,R.fillText(nS(p*it/4),w.left-g*.5,Q),R.globalAlpha=1}(v||b)&&(R.fillStyle=n.text,R.textAlign="center",R.globalAlpha=.85,v&&(R.save(),R.translate(g*.9,(w.top+w.bottom)/2),R.rotate(-Math.PI/2),R.fillText(v,0,0),R.restore()),b&&R.fillText(b,(w.left+w.right)/2,w.bottom+g*2.3),R.globalAlpha=1);const ot=(it,Q)=>at(C(it,Q,"value"))*(s==="bar"?at(C(it,Q,"show")):1)*E,ct=(it,Q)=>bc(c(Q),n.highlight,at(C(it,Q,"highlight")));if(s==="line"){R.lineWidth=Math.max(2,g*.2),R.lineJoin="round",R.lineCap="round";for(const it of r)R.strokeStyle=c(it.id),R.beginPath(),t.data.forEach((Q,rt)=>{const ht={x:A(Q.id),y:w.bottom-ot(Q.id,it.id)},dt=at(C(Q.id,it.id,"show"));if(rt===0){dt>0&&R.moveTo(ht.x,ht.y);return}const bt=t.data[rt-1];if(at(C(bt.id,it.id,"show"))<1||dt<=0)return;const wt={x:A(bt.id),y:w.bottom-ot(bt.id,it.id)};R.lineTo(wt.x+(ht.x-wt.x)*dt,wt.y+(ht.y-wt.y)*dt)}),R.stroke()}R.textAlign="center";for(const it of t.data){for(const Q of r){const rt=s==="bar"?H(it.id,Q.id):A(it.id),ht=ot(it.id,Q.id),dt=at(C(it.id,Q.id,"show"));if(R.fillStyle=ct(it.id,Q.id),s==="bar"?ht>.5&&(sS(R,rt-x/2,w.bottom-ht,x,ht,Math.min(6,x/4)),R.fill()):dt>0&&(R.beginPath(),R.arc(rt,w.bottom-ht,M*Math.min(1,dt*1.5)*(1+.3*at(C(it.id,Q.id,"highlight"))),0,Math.PI*2),R.fill()),t.values!==!1&&dt>0){R.globalAlpha=Math.min(1,dt*2),R.font=`600 ${o?g*.85:g}px ${n.font}`,R.fillStyle=bc(n.text,n.highlight,at(C(it.id,Q.id,"highlight")));const bt=w.bottom-ht-(s==="line"?M:0)-g*.95;R.fillText(D(at(C(it.id,Q.id,"value"))),rt,bt),R.font=`${g}px ${n.font}`,R.globalAlpha=1}}R.fillStyle=n.text,R.fillText(it.label??it.id,A(it.id),w.bottom+g*1.1)}R.strokeStyle=n.text,R.lineWidth=1.5,R.beginPath(),R.moveTo(w.left,w.bottom),R.lineTo(w.right,w.bottom),R.stroke(),R.restore()}};function Z(R,U){const nt=r[0].id,at=$(U);t.data.forEach((ot,ct)=>{const it=at.get(ot.id);if(it.sweep<=1e-4)return;const Q=X.get(ot.id),rt=Q?{x:U(`piece.${Q.id}.x`),y:U(`piece.${Q.id}.y`)}:{x:0,y:0},ht=Q?U(`piece.${Q.id}.rotate`)*Math.PI/180:0,dt=Q?U(`piece.${Q.id}.opacity`):1;if(dt<=0)return;R.save(),R.globalAlpha=dt;const bt={x:j.cx+Math.cos(it.mid)*it.out,y:j.cy+Math.sin(it.mid)*it.out};R.translate(it.centre.x+rt.x,it.centre.y+rt.y),R.rotate(ht),R.translate(-it.centre.x,-it.centre.y),R.beginPath(),R.arc(bt.x,bt.y,j.r,it.start,it.start+it.sweep),J>0?R.arc(bt.x,bt.y,J,it.start+it.sweep,it.start,!0):R.lineTo(bt.x,bt.y),R.closePath(),R.fillStyle=bc(n.palette[ct%n.palette.length],n.highlight,U(C(ot.id,nt,"highlight"))),R.fill(),R.strokeStyle=n.background,R.lineWidth=Math.max(1.5,g*.15),R.stroke(),t.values!==!1&&it.sweep>=.3&&(R.fillStyle=n.background,R.font=`600 ${g}px ${n.font}`,R.textAlign="center",R.fillText(D(U(C(ot.id,nt,"value"))),it.centre.x,it.centre.y),R.font=`${g}px ${n.font}`),R.restore();const wt=N(it),ge=Math.cos(it.mid);R.globalAlpha=dt,R.fillStyle=n.text,R.textAlign=ge>.2?"left":ge<-.2?"right":"center";const ji=ge>.2?wt.left:ge<-.2?wt.right:wt.left+wt.width/2;R.fillText(ot.label??ot.id,ji,wt.top+wt.height/2),t.values!==!1&&it.sweep<.3&&(R.globalAlpha=dt*.8,R.fillText(D(U(C(ot.id,nt,"value"))),ji,wt.bottom+g*.65)),R.globalAlpha=1})}const et={kind:"chart",chartKind:s,about:Cn,target:B,max:p,box:Mt(t.x,t.y,t.width,t.height),anchor(R,U=1/0){return F(K(z(R),U))},piece(R){const U=z(R);if(U.kind!=="slice")throw new Error(i?`chart: a piece is a slice, slice:ID, not "${R}"`:`chart: a ${d} is not a piece; slices of a pie or donut are (slice:ID). Change a ${d} with edit('set' | 'show' | 'highlight', …)`);const nt=X.get(U.id);if(nt)return nt;const at={id:X.size+1,datum:U.id,home:F(K(U,0))};X.set(U.id,at);for(const ot of["x","y","rotate"])G[`piece.${at.id}.${ot}`]=0;return G[`piece.${at.id}.opacity`]=1,at},edit(R,U,nt){const at=Array.isArray(U)?U:[U];if(at.length===0)throw new Error(`chart.edit: ${R} takes at least one anchor`);if(!(R in Cn.edits))throw Ei("chart",R,Cn);if(R==="pull"&&!i)throw new Error(`chart.edit: pull takes slice anchors of a pie or donut; a ${s} chart has ${d}s`);const ot=at.map(ct=>{const it=z(ct);if(it.kind!==d)throw new Error(`chart.edit: ${R} takes ${d} anchors (${d}:ID), not "${ct}"`);return it});for(const{id:ct,series:it}of ot){const Q=rt=>C(ct,it,rt);if(R==="set"){if(typeof nt.value!="number"||!Number.isFinite(nt.value))throw new Error("chart.edit: set needs `value`, a number");L.tween(Q("value"),Y(Q("value"),nt.at),nt.value,nt,UM)}else R==="show"?L.tween(Q("show"),Y(Q("show"),nt.at),nt.on===!1?0:1,nt,VM):R==="pull"?L.tween(Q("pull"),Y(Q("pull"),nt.at),nt.on===!1?0:1,nt,ZM):L.tween(Q("highlight"),Y(Q("highlight"),nt.at),nt.on===!1?0:1,nt,JM)}return et},follow(R,U){return q.follow(R,U),et},fling(R,U){return q.fling(R,U),et},move(R,U){return q.move(R,U),et},ride(R,U,nt){if(s!=="bar")return R;const at=t.data.flatMap(ot=>r.map(ct=>{const it=st(ot.id,ct.id,0),Q=[...ks(L.keys(C(ot.id,ct.id,"value"))),...ks(L.keys(C(ot.id,ct.id,"show")))];return{top:t.y+w.bottom-it,offset:rt=>it-st(ot.id,ct.id,rt),windows:Q}}));return mr(R,U,{ground:nt.ground,every:nt.every??tn,floors:at})},tracks:L.tracks};return et}function gp(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 nS(t){return Number.isInteger(t)?String(t):String(Number(t.toFixed(2)))}function bc(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 pp(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 sS(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 iS(t){return t.endsWith(".value")?{description:"Its value (the bar’s height, the point’s, or the slice’s share, 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, a slice opened",unit:"0..1",min:0,max:1}:t.endsWith(".pull")?{description:"How far the slice is pulled out from the centre",unit:"0..1",min:0,max:1}:t.startsWith("piece.")?{description:t.endsWith(".opacity")?"The loose slice’s opacity":t.endsWith(".rotate")?"The loose slice’s turn, degrees":"The loose slice’s offset from home, px",unit:t.endsWith(".rotate")?"degrees":t.endsWith(".opacity")?"0..1":"px"}:{description:"How much it is coloured out",unit:"0..1",min:0,max:1}}function mp(){return{torso:[{at:0,width:.083},{at:.25,width:.08},{at:.5,width:.075},{at:.8,width:.085},{at:1,width:.023}],arm:[{at:0,width:.026},{at:.3,width:.024},{at:.5,width:.018},{at:.7,width:.021},{at:1,width:.012}],leg:[{at:0,width:.036},{at:.3,width:.037},{at:.5,width:.026},{at:.7,width:.029},{at:1,width:.015}]}}const Ii={youngMan:{figure:"organic",skin:"#edb98d",ink:"#53372d",headSize:.28,shoulderWidth:.074,hipWidth:.045,handSize:.078,hair:{style:"softSweep",color:"#38291f"},ears:!0,face:{style:"anime",shape:"angular",jawWidth:.83,chinWidth:.35,jawRoundness:1,eyeScale:.95,eyeAspect:1.1,nose:!0,iris:"#6a472d"},outfit:{shirt:"#bc7050",trousers:"#495a67",sleeves:"short"}},youngWoman:{figure:"organic",skin:"#f1c299",ink:"#53372d",headSize:.28,shoulderWidth:.065,hipWidth:.054,handSize:.075,body:{torso:[{at:0,width:.098},{at:.18,width:.097},{at:.44,width:.061},{at:.7,width:.087},{at:.85,width:.09},{at:1,width:.024}]},hair:{style:"flowingBob",color:"#38291f"},ears:!0,face:{style:"anime",shape:"angular",jawWidth:.78,chinWidth:.32,jawRoundness:1,eyeScale:.95,eyeAspect:1.1,nose:!0,iris:"#6a472d",lashes:!0},outfit:{shirt:"#72958b",trousers:"#6b6888",sleeves:"short",bottom:"skirt"}},childBoy:{figure:"organic",height:230,skin:"#edb98d",ink:"#53372d",headSize:.36,shoulderWidth:.052,hipWidth:.038,legLength:.82,armLength:.8,handSize:.074,body:mp(),hair:{style:"softSweep",color:"#38291f"},ears:!0,face:{style:"anime",shape:"round",eyeScale:1,eyeAspect:1.1,nose:!0,iris:"#6a472d"},outfit:{shirt:"#d99843",trousers:"#497b91",sleeves:"short",bottom:"shorts"}},childGirl:{figure:"organic",height:225,skin:"#f1c299",ink:"#53372d",headSize:.36,shoulderWidth:.052,hipWidth:.038,legLength:.82,armLength:.8,handSize:.074,body:mp(),hair:{style:"flowingBob",color:"#38291f"},ears:!0,face:{style:"anime",shape:"round",eyeScale:1,eyeAspect:1.1,nose:!0,iris:"#6a472d",lashes:!0},outfit:{shirt:"#ae7396",trousers:"#648769",sleeves:"short",bottom:"skirt"}}};function oS(t,e={}){if(!Object.prototype.hasOwnProperty.call(Ii,t))throw new Error(`softCartoonCharacter: unknown actor '${t}'`);const n=Ii[t];return gs({...n,...e,body:{...n.body,...e.body},face:{...n.face,...e.face}})}const yp={animeBoy:{label:"Anime boy",group:"anime",scale:.68,options:{figure:"fluid",look:"clean",proportions:"thin",build:"child",headSize:.34,skin:"#f2c7a5",ink:"#302c48",ears:!0,hands:"cartoon",handStyle:"natural",hair:{style:"spiky",color:"#263c68"},face:{style:"anime",iris:"#318fa5",lashes:!1},outfit:{shirt:"#efac45",trousers:"#375a91",bottom:"shorts",shoes:"boots"}}},animeGirl:{label:"Anime girl",group:"anime",scale:.68,options:{figure:"fluid",look:"clean",proportions:"thin",build:"child",headSize:.34,skin:"#e8ad8c",ink:"#302c48",ears:!0,hands:"cartoon",handStyle:"natural",hair:{style:"bob",color:"#4f304e"},face:{style:"anime",iris:"#9d5f32"},outfit:{shirt:"#e9779f",trousers:"#5c4c86",bottom:"shorts",shoes:"boots"}}},animeYoungMan:{label:"Anime young man",group:"anime",scale:1,options:{figure:"fluid",look:"clean",proportions:"thin",build:"tall",headSize:.23,skin:"#efbf9c",ink:"#302c48",ears:!0,hands:"cartoon",handStyle:"natural",hair:{style:"spiky",color:"#243552"},face:{style:"anime",iris:"#507bcc",lashes:!1},outfit:{shirt:"#57bbc0",trousers:"#334967",sleeves:"long",over:"hoodie",overColor:"#57bbc0",shoes:"boots"}}},animeYoungWoman:{label:"Anime young woman",group:"anime",scale:1,options:{figure:"fluid",look:"clean",proportions:"thin",build:"slim",headSize:.23,skin:"#f3cbb4",ink:"#302c48",ears:!0,hands:"cartoon",handStyle:"natural",hair:{style:"highPonytail",color:"#773853"},face:{style:"anime",iris:"#9163c4"},outfit:{shirt:"#ae7cda",trousers:"#35456c",sleeves:"long",shoes:"boots"}}},animeMan:{label:"Anime man",group:"anime",scale:1,options:{figure:"fluid",look:"clean",proportions:"thin",build:"broad",headSize:.23,skin:"#b67f62",ink:"#302c48",ears:!0,hands:"cartoon",handStyle:"natural",hair:{style:"sidePart",color:"#302839"},face:{style:"anime",iris:"#9b713b",lashes:!1},outfit:{shirt:"#677aab",trousers:"#343848",sleeves:"long",collar:!0,shoes:"boots"}}},animeWoman:{label:"Anime woman",group:"anime",scale:1,options:{figure:"fluid",look:"clean",proportions:"thin",build:"standard",headSize:.23,skin:"#d59a73",ink:"#302c48",ears:!0,hands:"cartoon",handStyle:"natural",hair:{style:"shoulderWaves",color:"#382c4c"},face:{style:"anime",iris:"#2b8f82"},outfit:{shirt:"#df6c79",trousers:"#46506c",sleeves:"long",bottom:"skirt",shoes:"boots"}}},animeOlderMan:{label:"Anime older man",group:"anime",scale:1,options:{figure:"fluid",look:"clean",proportions:"thin",build:"stocky",headSize:.25,skin:"#e0b291",ink:"#302c48",ears:!0,hands:"cartoon",handStyle:"natural",hair:{style:"receding",color:"#b8c4d1"},facialHair:{style:"shortBoxed",color:"#dae0e8"},face:{style:"anime",iris:"#557c8b",lashes:!1,ageLines:.8},outfit:{shirt:"#9c846c",trousers:"#46505c",sleeves:"long",collar:!0,shoes:"boots"}}},animeOlderWoman:{label:"Anime older woman",group:"anime",scale:1,options:{figure:"fluid",look:"clean",proportions:"thin",build:"standard",headSize:.25,skin:"#c4947b",ink:"#302c48",ears:!0,hands:"cartoon",handStyle:"natural",hair:{style:"topBun",color:"#d1d3df"},face:{style:"anime",iris:"#7a6998",ageLines:.8},outfit:{shirt:"#6d9b93",trousers:"#66597a",sleeves:"long",over:"cardigan",overColor:"#6d9b93",shoes:"boots"}}}},bp={mangaYoungMan:{label:"Manga young man",group:"manga",scale:1,options:{figure:"fluid",look:"clean",proportions:"thin",build:"tall",headSize:.21,lineWidth:2.8,skin:"#edbf9b",ink:"#252536",ears:!0,hands:"cartoon",handStyle:"natural",hair:{style:"mangaSpikes",color:"#27354c"},face:{style:"anime",shape:"angular",jawWidth:.78,chinWidth:.16,eyeScale:.8,eyeAspect:.63,iris:"#3a9baa",lashes:!1,nose:!0},outfit:{shirt:"#c65a49",trousers:"#293c56",sleeves:"long",collar:!0,shoes:"boots"}}},mangaYoungWoman:{label:"Manga young woman",group:"manga",scale:1,options:{figure:"fluid",look:"clean",proportions:"thin",build:"slim",headSize:.21,lineWidth:2.8,skin:"#e2a482",ink:"#252536",ears:!0,hands:"cartoon",handStyle:"natural",hair:{style:"mangaSweep",color:"#683e64"},face:{style:"anime",shape:"angular",jawWidth:.69,chinWidth:.1,eyeScale:.85,eyeAspect:.72,iris:"#8462b7",nose:!0},outfit:{shirt:"#518c96",trousers:"#364361",sleeves:"long",shoes:"boots"}}},mangaRival:{label:"Manga rival",group:"manga",scale:1,options:{figure:"fluid",look:"clean",proportions:"thin",build:"broad",headSize:.21,lineWidth:2.8,skin:"#b77e5f",ink:"#252536",ears:!0,hands:"cartoon",handStyle:"natural",hair:{style:"mangaSpikes",color:"#e6e0cc",volume:.16},face:{style:"anime",shape:"angular",jawWidth:.9,chinWidth:.25,eyeScale:.75,eyeAspect:.55,iris:"#ba8445",lashes:!1,nose:!0},outfit:{shirt:"#4c4b75",trousers:"#303348",sleeves:"long",over:"hoodie",shoes:"boots"}}},mangaHeroine:{label:"Manga heroine",group:"manga",scale:1,options:{figure:"fluid",look:"clean",proportions:"thin",build:"tall",headSize:.21,lineWidth:2.8,skin:"#f0c5aa",ink:"#252536",ears:!0,hands:"cartoon",handStyle:"natural",hair:{style:"highPonytail",color:"#263647",texture:"spiky",textureAmount:.35},face:{style:"anime",shape:"angular",jawWidth:.73,chinWidth:.12,eyeScale:.83,eyeAspect:.65,iris:"#427e9b",nose:!0},outfit:{shirt:"#b65e7c",trousers:"#31405b",sleeves:"long",collar:!0,shoes:"boots"}}}},wc={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:Te.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:Te.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:Te.black},ears:!0,outfit:{shirt:"#9b5fc0",trousers:"#2f2f3a",sleeves:"long"}}},grandpa:{label:"Grandpa",group:"family",scale:.96,options:{build:"stocky",hair:{style:"receding",color:Te.gray},facialHair:{style:"shortBoxed",color:Te.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:Te.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:Te.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:Te.blond},hat:"sunHat",ears:!0,outfit:{shirt:"#d64535",trousers:"#4f6b3a",sleeves:"long"}}},...yp,...bp};function rS(t,e=300,n={}){const s=wc[t];if(!s)throw new Error(`castMember: unknown cast member '${t}'`);return{...s.options,height:Math.round(e*s.scale),...n}}const Oi={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 aS(t,e,n){return Oi[t].spacing*Math.min(e.height,n.height)}const wp=.075;function lS(t,e,n,s={}){const i=Oi[t];if(!i)throw new Error(`meetHands: unknown meeting '${t}' (one of ${Object.keys(Oi).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,b)=>{const v=b?a?1:.62:a?3:3.38;let k={...lt,...m.pose,turn:v,lean:(m.pose?.lean??0)+i.lean};const w=b?1:-1,T=(P,S,x)=>{k=Ce(m.character,k,P,{x:c.x+S-m.x,y:c.y,depth:x})};if(t==="handOver"){const P=wp*l;T("arm.left",-w*P*.9,P),T("arm.right",-w*P*.9,-P)}else T("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,b)=>{const v=fe(m.character,b),k=t==="handOver"?["hand.left","hand.right"]:["hand.right"],w=t==="handOver"?wp*l+f:f;return k.every(T=>Math.abs(v.points[T].y-c.y)<f&&Math.abs(v.points[T].x+m.x-c.x)<w)},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 kr={spacing:.3,lean:10,tilt:8};function cS(t,e){return kr.spacing*Math.min(t.height,e.height)}function hS(t,e,n={}){const[s,i]=t.x<=e.x?[t,e]:[e,t],o=n.view==="side",r=Math.min(s.character.height,i.character.height),a=(p,g,m)=>({over:{x:g.x-m*.02*r-p.x,y:-.72*r,depth:-.08*r},round:{x:g.x-m*.04*r-p.x,y:-.5*r,depth:.06*r}}),l=(p,g,m)=>{const b=m?o?1:.62:o?3:3.38,v=m?1:-1;let k={...lt,...p.pose,turn:b,lean:(p.pose?.lean??0)+kr.lean,"head.tilt":(p.pose?.["head.tilt"]??0)+v*kr.tilt};const{over:w,round:T}=a(p,g,v);return k=Ce(p.character,k,"arm.right",w),k=Ce(p.character,k,"arm.left",T),k},c=l(s,i,!0),h=l(i,s,!1),u=.05*r,d=(p,g,m,b)=>{const v=fe(p.character,b).points,{over:k,round:w}=a(p,g,m);return Math.hypot(v["hand.right"].x-k.x,v["hand.right"].y-k.y)<u&&Math.hypot(v["hand.left"].x-w.x,v["hand.left"].y-w.y)<u},f=d(s,i,1,c)&&d(i,s,-1,h);return t.x<=e.x?{a:c,b:h,reached:f}:{a:h,b:c,reached:f}}const Hn={spacing:.32,low:.3,high:.5,helperLean:40,helperBend:16};function uS(t,e){return Hn.spacing*Math.min(t.height,e.height)}function dS(t,e,n,s={}){const i=Math.max(0,Math.min(1,n)),o=s.view==="side",r=t.x<=e.x,a=Math.min(t.character.height,e.character.height),l={x:(t.x+e.x)/2,y:-(Hn.low+(Hn.high-Hn.low)*i)*a},c=m=>m?o?1:.62:o?3:3.38;let h={...lt,...t.pose,turn:c(r),lean:(t.pose?.lean??0)+Hn.helperLean*(1-i)+4,bend:(t.pose?.bend??0)+Hn.helperBend*(1-i),"head.nod":18*(1-i)};h=Ce(t.character,h,"arm.right",{x:l.x-t.x,y:l.y});const u={...ye.sitFloor,...e.pose,turn:c(!r)},d={...lt,...e.pose,turn:c(!r)};let f=Bl(u,d,i);f=Ce(e.character,f,"arm.right",{x:l.x-e.x,y:l.y});const p=.04*a,g=(m,b)=>{const v=fe(m.character,b).points["hand.right"];return Math.hypot(v.x+m.x-l.x,v.y-l.y)<p};return{helper:h,sitter:f,point:l,reached:g(t,h)&&g(e,f)}}const kc=Object.freeze({everyday:Object.freeze({shirt:"#bc7050",trousers:"#495a67",sleeves:"short",bottom:"trousers",collar:!1,tie:null}),formal:Object.freeze({top:"shirt",shirt:"#f4ede2",trousers:"#394653",sleeves:"long",bottom:"trousers",trouserStyle:"plain",collar:!0,tie:"#804453"}),casual:Object.freeze({top:"tshirt",shirt:"#648a83",trousers:"#426683",sleeves:"short",bottom:"trousers",trouserStyle:"jeans",collar:!1,tie:null})});function kp(t,e={}){if(!Object.prototype.hasOwnProperty.call(kc,t))throw new Error(`outfitPreset: unknown category '${t}'`);const n={...kc[t],...e};return e.top&&e.top!=="shirt"&&(n.collar=e.collar??!1,n.tie=e.tie??null),n.top==="dress"&&(n.bottom="skirt"),n}const fS=.7,gS=50,pS=1.2,mS=.8,yS=3,bS=30,wS=.8,kS=.6,vc=(t,e)=>Math.max(-e,Math.min(e,t)),vS=["hair.swing","hair.trail","hair.lift"];function vp(t,e){const n=e.start??0,s=e.amount??1,i=Math.max(1e-6,e.headRadius);let o=NaN,r={x:0,y:0,turn:0};const a=f=>(f!==o&&(r=t(f),o=f),r),l=f=>{const p=a(f);return p.turn*90+(p.headTurn??0)},c={start:n,end:e.end,step:e.step,stiffness:e.stiffness??70,damping:e.damping??6},h=Gs(l,c),u=Gs(f=>a(f).x,c),d=Gs(f=>a(f).y,c);return h.map((f,p)=>{const g=a(f.time),m=f.value-l(f.time),b=u[p].value-g.x-(e.wind??0)*fS*i,v=d[p].value-g.y,k=Math.sin(g.turn*Math.PI/2),w=Math.cos(g.turn*Math.PI/2),T=m*yS+b*w/i*bS,P=-b*k/i*wS,S=-v/i*kS;return{time:f.time,swing:vc(T*s,gS),trail:vc(P*s,pS),lift:vc(S*s,mS)}})}function MS(t,e){if(t.length===0)return{"hair.swing":0,"hair.trail":0,"hair.lift":0};if(e<=t[0].time)return Mp(t[0]);if(e>=t[t.length-1].time)return Mp(t[t.length-1]);let n=0,s=t.length-1;for(;s-n>1;){const a=n+s>>1;t[a].time<=e?n=a:s=a}const i=t[n],o=t[s],r=o.time===i.time?0:(e-i.time)/(o.time-i.time);return{"hair.swing":i.swing+(o.swing-i.swing)*r,"hair.trail":i.trail+(o.trail-i.trail)*r,"hair.lift":i.lift+(o.lift-i.lift)*r}}const Mp=t=>({"hair.swing":t.swing,"hair.trail":t.trail,"hair.lift":t.lift}),vs=16,SS=1500;function xS(t,e,n,s={}){const i=n.head.hair;if(!i||!ff(i))return[];const o=e.filter(v=>v.target===t),r=o.reduce((v,k)=>k.keyframes.reduce((w,T)=>Math.max(w,T.time),v),0),a=lt,l=new Set(["x","y","turn","head.turn"]),c=new Ht({id:`${t}-hair-follow`,tracks:o.filter(v=>l.has(v.property))}),h=(v,k,w)=>{const T=c.getStateAtTime(v).values.get(t)?.get(k);return typeof T=="number"?T:w},u=new Ht({id:`${t}-hair-pose`,tracks:o}),d=v=>u.getStateAtTime(v).values.get(t),f=new Map,p=v=>{const k=Math.round(v/vs);let w=f.get(k);if(!w){const T={};for(const[S,x]of d(k*vs)??[])T[S]=x;const P=fe(n,nr(T,a,s.gaits)).head.center;f.set(k,w={x:P.x,y:P.y})}return w},g=v=>{const k=Math.floor(v/vs),w=v/vs-k,T=p(k*vs),P=p((k+1)*vs);return{x:T.x+(P.x-T.x)*w,y:T.y+(P.y-T.y)*w}},m=vp(v=>{const k=g(v);return{x:h(v,"x",0)+k.x,y:h(v,"y",0)+k.y,turn:h(v,"turn",a.turn??0),headTurn:h(v,"head.turn",a["head.turn"]??0)}},{start:0,end:r+(s.settle??SS),headRadius:fe(n,lt).head.rx,step:s.step,stiffness:s.stiffness,damping:s.damping,amount:s.amount,wind:s.wind}),b=[];for(const v of vS){const k=v.slice(5);let w=m.map(P=>({time:P.time,value:P[k]}));if(w.every(P=>Math.abs(P.value)<.001))continue;const T=o.find(P=>P.property===v);if(T){const P=new Ht({id:`${t}-${v}-own`,tracks:[T]}),S=x=>Number(P.getStateAtTime(x).values.get(t)?.get(v)??0);w=w.map(x=>({time:x.time,value:x.value+S(x.time)}))}b.push({id:`${t}-${v}`,target:t,property:v,keyframes:w})}return b}const Rn={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 Mc(t){if(t===void 0)return Rn.full;if(typeof t=="string")return Rn[t];const{base:e,...n}=t;return{...Rn[e??"full"],...n}}const Sc=160,TS=120,ES=700,xc=60,AS=90,vr=3200,Ms=1,Ln=1e-6;function Mr(t,e,n={}){const s=Mc(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])>Ln));for(const u of r)o[u]=$S(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=PS(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=IS(t,c,t[0].pose[h],s.jumpSquash);u.length>0&&(o[h]=u)}return o}function $S(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+Ms){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],b=m-g,v=h[h.length-1].time,k=p.act!==!1;if(Math.abs(b)<=Ln){const I=p.time+(k?c(f):0);if(f===e.length-1)Math.abs(d-m)>Ln&&u(Math.max(I,v+Sc),m,"ease-in-out"),d=m;else if(k&&a&&s.drift>0&&n.drift.includes(t)&&I-v>=ES){const A=ne(`${i}:${t}:${f}`)%2===0?1:-1;d=m+A*s.drift*r,u(I,d,"ease-in-out")}continue}if(!k){u(e[f-1].time,d),u(p.time,m,p.easing),d=m;continue}const w=c(f),T=Math.max(e[f-1].time+w,v);let P=p.time+w;o&&s.eyeDart>0&&(P=Math.min(P,T+s.eyeDart));const S=P-T;if(S<=Ms){u(p.time,m,p.easing),d=m;continue}u(T,d);const x=Math.sign(b);if(a&&s.anticipation>0&&r>0&&S>=Sc){const I=d-x*Math.min(Math.abs(b)*s.anticipation,r),A=T+S*s.anticipationTime;u(A,I,"ease-in-out"),s.hold>0&&u(A+S*s.hold,I)}const M=f+1<e.length?e[f+1].time-p.time:1/0,E=Math.min(s.settle,M/2);if(a&&s.overshoot>0&&r>0&&S>=TS&&E>Ms){const I=Math.min(Math.abs(b)*s.overshoot,r);u(P,m+x*I,p.easing??s.actionEase),u(P+E,m,s.settleEase)}else u(P,m,p.easing??s.actionEase);d=m}return h}function PS(t,e,n,s,i){const o=[],r=xc+AS;for(let f=1;f<t.length;f++){const p=t[f-1].pose,g=t[f].pose;Object.entries(e.headTurns).some(([b,v])=>Math.abs((g[b]??0)-(p[b]??0))>v)&&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+vr*.6,u=0;for(;h<l;){c.some(g=>Math.abs(g-h)<vr/2)||o.push(h);const p=(ne(`${s}:blink:${u++}`)%1e3/1e3-.5)*(vr*.66);h+=vr+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+xc<=p+Ms||(f>p+Ms&&d.push({time:f,value:i}),d.push({time:f+xc,value:1,easing:"ease-in"}),d.push({time:f+r,value:i,easing:"ease-out"}))}return d.length>1?d:[]}function IS(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+Ms||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<Sc||t[l].act===!1)){if(c<=Ln&&h>Ln)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>Ln&&h<=Ln){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 Sp={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 OS(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 _S(){const t={},e={};for(const n of Object.keys(lt)){const s=OS(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 xp=_S();function Tp(t,e){return Object.entries(e).map(([n,s])=>({id:`${t}-${n}`,target:t,property:n,keyframes:s}))}function Ep(t,e,n={}){const s=Ao(e),i=e.map((o,r)=>({time:o.time,pose:{...s[r]},easing:o.easing,act:o.act}));return Tp(t,Mr(i,n.rig??Sp,n))}function Ap(t,e,n={}){const s=n.rest??lt,i=zl(e,s),o=e.map((r,a)=>({time:r.time,pose:{...s,...i[a]},easing:r.easing,act:r.act}));return Tp(t,Mr(o,n.rig??xp,n))}const $p=vt.shocked,CS=vt.scared,nn={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,...$p,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,...vt.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,...$p,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,...vt.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:ut.leftHip,rightHip:ut.rightHip,leftKnee:0,rightKnee:0},easing:"ease-in-out"}],tremble:t=>{const e=[{after:80,pose:{...CS,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:{...ae.sad,bend:18,stretch:.92,lean:t.lean+5,turn:t.turn,sit:t.sit},easing:"ease-in-out"}]};function Tc(t,e){const n=typeof e.from=="string"?ae[e.from]:e.from??ut;return Ec(nn[t](n),{...e,from:n})}function Ec(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 _i(t,e=1){const n=nn[t](ut);return n[n.length-1].after*e}function Pp(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,b=f/g,v=1-h/(e.length-1);t.globalAlpha=r*(1-v),t.lineWidth=o*(1-v*.7),t.beginPath(),t.moveTo(u.x+m*l,u.y+b*l),t.lineTo(d.x+m*l,d.y+b*l),t.stroke()}}t.restore()}const HS={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 RS(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(nl(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=>HS[f]);for(const f of d){const p=c.map(f.at);let g=0;for(let v=1;v<p.length;v++)g+=Math.hypot(p[v].x-p[v-1].x,p[v].y-p[v-1].y);const m=g/((n.time-l)/1e3);if(m<=u)continue;const b=Math.min(1,(m-u)/(u*.5));Pp(t,p,{...i,opacity:(i.opacity??.7)*b,spacing:i.spacing??h*.02})}}function Ip(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=ne(`${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 LS(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;FS(t,h,u,i*.14,n*Math.PI+a),t.stroke()}t.restore()}function FS(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 Ci={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 Ac(t={}){return[...Object.keys(Kt),...Object.keys(ae),...Object.keys(nn),...Object.keys(Ci),...Object.keys(t.gaits??{}),...Object.keys(t.actions??{})]}function $c(t={}){const e=new Set(Ac()),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 Pc(t={}){const e={};for(const n of Object.keys(Kt))e[n]=`Walks to \`to\` in the ${n} gait, feet planted, turning round first if needed.`;for(const n of Object.keys(ae))e[n]=`Moves into the ${n} pose and holds it.`;for(const n of Object.keys(nn))e[n]=`The ${n} gag, built on the current pose.`;for(const[n,s]of Object.entries(Ci))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 Sr=["do","at","for","to","toward","mood","say","pose","target","onto"],NS={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"},xr=["viewer","ahead","back"],Fn=t=>typeof t=="number"&&Number.isFinite(t);function Hi(t,e={}){const n=$c(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=Ac(e),i=l=>l in Kt||l in(e.gaits??{}),o=Object.keys(vt),r=Object.keys(ut);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))Sr.includes(g)||h(ft("beat field",g,Sr,NS[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(ft("action",f,s));return}const p=Ci[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(ft("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)?Fn(m)||h(`Pose joint \`${g}\` must be a number (got ${JSON.stringify(m)}).`):h(ft("pose joint",g,r));for(const g of["at","for"]){const m=d[g];m!==void 0&&!(Fn(m)&&m>=0)&&h(`\`${g}\` is milliseconds, a number ≥ 0 (got ${JSON.stringify(m)}).`)}Fn(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&&!Fn(m)&&h(`\`${g}\` is a scene ${g==="to"?"x":"y"} in px, a number (got ${JSON.stringify(m)}).`)}if(d.toward!==void 0&&!Fn(d.toward)&&!xr.includes(d.toward)&&h(`\`toward\` is a scene x or one of ${xr.join(", ")}${typeof d.toward=="string"&&Xs(d.toward,xr)?` (did you mean "${Xs(d.toward,xr)}"?)`:""} (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"||!Fn(g.x)||!Fn(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 Ic(t,e={},n="scriptTracks"){const s=Hi(t,e).filter(i=>i.level==="error");if(s.length!==0)throw new Error(`${n}: ${s.length} problem(s) in the beats:
|
|
53
|
+
`;function N2(t){if(t.getElementById(qu))return;const e=t.createElement("style");e.id=qu,e.textContent=F2,t.head.appendChild(e)}function ju(t,e){const n=Array.from(e.querySelectorAll("[data-tinyfly-choose]"));if(n.length===0)return()=>{};N2(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 r=()=>{for(const{element:a}of s)a.setAttribute("aria-pressed",String(a.getAttribute("data-tinyfly-choose")===t.scenario))},o=t.subscribe(r);return r(),()=>{o();for(const a of i)a();for(const{element:a,attributes:l}of s)for(const c of l)a.removeAttribute(c)}}const pr=new WeakMap,Za=new WeakMap;let W2=0;function ii(t,e,n){if(t)try{return JSON.parse(t)}catch(s){console.warn(`tinyfly: invalid ${e} JSON on`,n,s);return}}async function Yu(t,e={}){const n=pr.get(t);if(n)return n;const s=Array.from(t.querySelectorAll("script[data-tinyfly-timeline]")),i=s[0],r=t.getAttribute("data-src"),o=B2(t.getAttribute("data-markers")),a=s.length>1||i?.hasAttribute("data-scenario")?D2(s,o,t):void 0;if(a&&a.length===0)return;let l=i&&!a?ii(i.textContent,"timeline",t):void 0;if(!l&&r&&o){const f=await fetch(r);f.ok&&(l=await f.json())}if(l&&o&&(l=Ku(l,o)),!l&&!r&&!a){console.warn('tinyfly: embed has no timeline (a <script type="application/json" data-tinyfly-timeline> or data-src)',t);return}const c=ii(t.querySelector("script[data-tinyfly-captions]")?.textContent,"captions",t),h={playWhenVisible:!0,...e.player,...c&&{captions:c},...ii(t.getAttribute("data-options"),"data-options",t)};q2(t);const u=new gr(t,h),d={element:t,player:u};if(pr.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}),Za.set(t,ju(u,t))}else await u.load(l??r);if(t.getAttribute("data-controls")!=="false"){const f=ii(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=zu(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 D2(t,e,n){const s=[];return t.forEach((i,r)=>{const o=ii(i.textContent,"timeline",n);if(!o)return;const a=i.getAttribute("data-scenario")||`scenario-${r+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?Ku(o,e):o})}),s}function Ku(t,e){return t.config.markers?.length?t:{...t,config:{...t.config,markers:e.map((n,s)=>({id:`step-${s+1}`,time:n}))}}}function B2(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 Xu(t=document,e={}){const n=Array.from(t.querySelectorAll("[data-tinyfly-embed]"));return(await Promise.all(n.map(i=>Yu(i,e)))).filter(i=>i!==void 0)}function z2(t){const e=pr.get(t);e&&(Za.get(t)?.(),Za.delete(t),e.controls?.destroy(),e.player.destroy(),pr.delete(t),t.removeAttribute("data-tinyfly-mounted"))}function q2(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-${++W2}`,e.setAttribute("aria-labelledby",s.id))}function j2(){if(!(typeof document<"u"?document.currentScript:null)?.hasAttribute("data-tinyfly-auto"))return;const e=()=>{Xu()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e,{once:!0}):e()}class Gu{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 vn,this.adapterB=new vn}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 r of e.elements){if(!r.html)continue;const o=document.createElement("div");o.innerHTML=r.html.trim();const a=o.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 r=i.getAttribute("data-tinyfly-symbol");if(!r)return;const o=this.symbolDefs.get(r);if(!o)return;const a=new vn;i.querySelectorAll("[data-tinyfly]").forEach(l=>{const c=l.getAttribute("data-tinyfly");c&&a.registerTarget(c,l)}),s.push({adapter:a,timeline:Gn(o)})}),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 r=i.timeline.duration;i.adapter.applyState(i.timeline.getStateAtTime(r>0?n%r:n))}}clearContainer(e){e.innerHTML=""}createTimeline(e){return e.timeline?Gn(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 Y2(t,e,n={}){const s=new Gu(t,{...n,autoplay:!0});return await s.load(e),s}const K2={type:"none",duration:0},Lt=t=>({description:t,unit:"degrees"}),At=(t,e=0,n=1)=>({description:t,unit:`${e}..${n}`,min:e,max:n}),Uu={lean:Lt("Upper body tipped about the hips (+ toward the way it faces)"),bend:Lt("Line of action: the spine curved (+ curls forward, − arches back)"),headTilt:Lt("Head tilt"),leftShoulder:Lt("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:Lt("Right upper arm: 0 hangs down, 90 straight out (forward, in profile), 180 straight up"),leftElbow:Lt("Left elbow bend, added to the upper arm"),rightElbow:Lt("Right elbow bend, added to the upper arm"),leftHip:Lt("Left thigh: 0 straight down; in profile negative is forward"),rightHip:Lt("Right thigh: 0 straight down; in profile positive is forward"),leftKnee:Lt("Left knee bend (negative folds the shin back)"),rightKnee:Lt("Right knee bend (positive folds the shin back)"),leftWrist:Lt("Left wrist bend, added to the forearm"),rightWrist:Lt("Right wrist bend, added to the forearm"),leftAnkle:Lt("Left ankle: + points the toe down (tiptoe), − onto the heel"),rightAnkle:Lt("Right ankle: + points the toe down (tiptoe), − onto the heel"),leftFootOut:At("Left foot turned out (seen from the front): 0 natural, 1 sideways, negative turned in",-1,1),rightFootOut:At("Right foot turned out (seen from the front): 0 natural, 1 sideways, negative turned in",-1,1),mouth:At("Mouth open: 0 closed, 1 wide open"),smile:At("−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:At("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:At("Left eyebrow: −1 lowered, 0 rest, 1 raised",-1,1),rightBrow:At("Right eyebrow: −1 lowered, 0 rest, 1 raised",-1,1),browTilt:At("Eyebrow slant: −1 angry, 1 worried",-1,1),lookX:At("Eyes look across: + the way it faces",-1,1),lookY:At("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:At("0 front-on, 1 in profile, turned the way it faces"),sit:At("0 standing, 1 seated"),spin:Lt("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"}},Vu={walk:{description:"Walk-cycle phase, in strides: animate 0 → n for n strides",unit:"strides"},walking:At("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:At("How much the mouth chatters"),rubber:At("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:At("How much of the dance is applied")},Ju={"thumb.curl":At("Thumb curled in"),"thumb.across":At("Thumb across the palm"),"index.curl":At("Index finger curled"),"middle.curl":At("Middle finger curled"),"ring.curl":At("Ring finger curled"),"pinky.curl":At("Little finger curled"),spread:At("Fingers spread apart"),turn:Lt("Hand turned about the forearm"),bend:Lt("Hand bent at the wrist, palm-ward"),tilt:Lt("Hand tilted sideways"),roll:Lt("Hand rolled to show the back or the palm")};let Zu;function X2(t){Zu=t}function G2(t){return Zu?.(t)??{}}function Qu(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 ts(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=Qu(t)*n;const i=[t[0]];for(let r=1;r<t.length;r++){const o=t[r-1],a=t[r],l=Math.hypot(a.x-o.x,a.y-o.y);if(l>=s){const c=l===0?0:s/l;return i.push({x:o.x+(a.x-o.x)*c,y:o.y+(a.y-o.y)*c}),i}i.push(a),s-=l}return i}function mr(t,e){const n=ts(t,e);return n[n.length-1]}function Qa(t,e){return e>0?Math.floor(Math.max(0,t)*e/1e3):0}function yr(t,e,n){const s=e.roughness??2,i=Math.max(1,Math.round(e.passes??2)),r=Qa(n,e.boil??8);let o=0;const a=()=>{const d=o++;return f=>Xe(ne(`${e.seed??1}:${r}:${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,w)=>Math.hypot(m.x-d[w].x,m.y-d[w].y)),g=p.reduce((m,w)=>m+w,0)*Math.min(1,Math.max(0,f));c(m=>{const w=[],v=[];if(d.forEach((b,T)=>{w.push({x:b.x+l(m,s*.5),y:b.y+l(m,s*.5)}),T>0&&v.push([m.next()*2-1,m.next()*2-1])}),g<=0)return;t.beginPath(),t.moveTo(w[0].x,w[0].y);let k=0;for(let b=1;b<w.length;b++){const T=U2(w[b-1],w[b],s,v[b-1]),$=p[b-1];if(k+$<=g){t.bezierCurveTo(T[1].x,T[1].y,T[2].x,T[2].y,T[3].x,T[3].y),k+=$;continue}const M=V2(T,$===0?1:(g-k)/$);t.bezierCurveTo(M[1].x,M[1].y,M[2].x,M[2].y,M[3].x,M[3].y);break}t.stroke()})},u=(d,f,p,g,m=1)=>{c(w=>{const k=w.next()*Math.PI*2,b=Math.PI*2+.15+w.next()*.3,T=[];for(let M=0;M<=14;M++){const x=k+b*M/14,S=l(w,s*.6);T.push({x:d+Math.cos(x)*(p+S),y:f+Math.sin(x)*(g+S)})}const $=ts(T,m);$.length<2||(td(t,$),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,w=-(g.y-p.y)/m,v=(g.x-p.x)/m;c(k=>{const b={x:l(k,s*.5),y:l(k,s*.5)},T={x:l(k,s*.5),y:l(k,s*.5)},$=l(k,s*Math.min(1.5,Math.max(.3,m/80))),M=d.map((S,E)=>{const I=E/(d.length-1),A=Math.sin(Math.PI*I)*$;return{x:S.x+b.x+(T.x-b.x)*I+w*A,y:S.y+b.y+(T.y-b.y)*I+v*A}}),x=ts(M,f);x.length<2||(td(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 U2(t,e,n,s){const i=e.x-t.x,r=e.y-t.y,o=Math.hypot(i,r)||1,a=n*Math.min(1.5,Math.max(.3,o/80)),l=-r/o,c=i/o;return[t,{x:t.x+i/3+l*s[0]*a,y:t.y+r/3+c*s[0]*a},{x:t.x+2*i/3+l*s[1]*a,y:t.y+2*r/3+c*s[1]*a},e]}function V2([t,e,n,s],i){const r=(u,d)=>({x:u.x+(d.x-u.x)*i,y:u.y+(d.y-u.y)*i}),o=r(t,e),a=r(e,n),l=r(n,s),c=r(o,a),h=r(a,l);return[t,o,c,r(c,h)]}function td(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 zt(t,e,n){const s=t.length;if(s<2)return[];const i=[],r=[],o=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=o(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}),r.push({x:a.x-f,y:a.y-p})}),[...i,...r.reverse()]}function br(t,e,n,s){const i=e.length;if(i<2)return;const r=zt(e,n,s),o=a=>n+(s-n)*a/(i-1);t.beginPath(),t.moveTo(r[0].x,r[0].y);for(const a of r.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,o(l)/2,0,Math.PI*2),t.fill())})}function Mn(t,e,n,s,i=16){const r={x:2*e.x-(t.x+n.x)/2,y:2*e.y-(t.y+n.y)/2},o=[];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*r.x+l*l*n.x,y:h*h*t.y+2*h*l*r.y+l*l*n.y};o.push({x:c.x+(u.x-c.x)*s,y:c.y+(u.y-c.y)*s})}return o}function wr(t,e,n,s,i,r=0,o=1,a=40){const l=Math.cos(i),c=Math.sin(i);return Array.from({length:a+1},(h,u)=>{const d=r+Math.PI*2*o*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 ri(t,e){return e.look==="pencil"?Q2(t,e):ed(t,e.ink,e.look)}function kr(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 oi(t,e){return e.look==="silhouette"?ed(t,e.ink,"silhouette",!1):e}function ed(t,e,n,s=!0){const i=n==="silhouette",r=i?1.25:1;return{look:n,ink:e,limb(o,a,l){t.fillStyle=e,br(t,o,a*r,l*r)},line(o,a){o.length<2||(t.strokeStyle=e,t.lineWidth=a*r,t.lineCap="round",t.lineJoin="round",kr(t,o),t.stroke())},shape(o,a,l){kr(t,o,!0),(a!==null||i&&s)&&(t.fillStyle=i?e:a,t.fill()),!(l<=0)&&(t.strokeStyle=e,t.lineWidth=l*r,t.lineJoin="round",t.stroke())},ellipse(o,a,l,c,h,u,d){t.beginPath(),t.ellipse(o,a,l,c,h,0,Math.PI*2),(u!==null||i&&s)&&(t.fillStyle=i?e:u,t.fill()),!(d<=0)&&(t.strokeStyle=e,t.lineWidth=d*r,t.stroke())},dot(o,a,l){t.fillStyle=e,t.beginPath(),t.arc(o,a,l*r,0,Math.PI*2),t.fill()},guide(){},guideEllipse(){}}}function J2(t,e){const n=[t[0]];let s=0;for(let o=1;o<t.length;o++){const a=t[o-1],l=t[o],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],r=n[n.length-1];return Math.hypot(i.x-r.x,i.y-r.y)>e*.25?n.push(i):n[n.length-1]=i,n}function Z2(t,e){const n=t.length;return t.map((s,i)=>{const r=t[Math.max(0,i-1)],o=t[Math.min(n-1,i+1)],a=Math.hypot(o.x-r.x,o.y-r.y)||1,l=e(n===1?0:i/(n-1));return{x:s.x-(o.y-r.y)/a*l,y:s.y+(o.x-r.x)/a*l}})}function nd(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,r)=>i+r.amount*Math.sin(Math.PI*2*r.frequency*s+r.phase),0)/n}function Q2(t,e){const n=e.pencil??{},s=e.ink,i=n.roughness??Math.max(1,e.lineWidth*.12),r=Math.max(1,Math.round(n.passes??2)),o=Math.min(1,Math.max(0,n.pressure??.25)),a=Math.min(1,Math.max(0,n.rubbedOut??.15)),l=Qa(e.time,n.boil??8);let c=0;const h=(p,g,m=!1)=>Xe(ne(`${e.seed}:${m?"paper":l}:${p}:${g}`)),u=(p,g,m,w,v,k=0)=>{if(p.length<2)return;const b=p.slice(1).reduce((I,A,O)=>I+Math.hypot(A.x-p[O].x,A.y-p[O].y),0);let T=J2(p,Math.max(1.5,Math.min(e.lineWidth*.8,b/24)));if(k>0&&T.length>=2){const[I,A]=[T[T.length-2],T[T.length-1]],O=Math.hypot(A.x-I.x,A.y-I.y)||1;T=[...T,{x:A.x+(A.x-I.x)/O*k,y:A.y+(A.y-I.y)/O*k}]}const $=nd(m),M=nd(m),x=T.length,S=[],E=[];T.forEach((I,A)=>{const O=x===1?0:A/(x-1),H=T[Math.max(0,A-1)],W=T[Math.min(x-1,A+1)],j=Math.hypot(W.x-H.x,W.y-H.y)||1,J=-(W.y-H.y)/j,tt=(W.x-H.x)/j,V=$(O)*v,L=Math.min(1,O/.08,(1-O)/.08),q=(.55+.45*Math.sqrt(Math.max(0,L)))*(1+o*M(O)),G=Math.max(.3,g(O)*q/2),_=I.x+J*V,Y=I.y+tt*V;S.push({x:_+J*G,y:Y+tt*G}),E.push({x:_-J*G,y:Y-tt*G})}),t.save(),t.globalAlpha*=w,t.fillStyle=s,kr(t,[...S,...E.reverse()],!0),t.fill(),t.restore()},d=(p,g)=>{const m=c++,w=h(m,99,!0);if(w.next()<a){const T=(w.next()*2-1)*e.lineWidth*1.4,$=(w.next()*2-1)*e.lineWidth*1.4,M=p.map(x=>({x:x.x+T,y:x.y+$}));u(M,x=>g(x)*1.8,h(m,98,!0),.035,i),u(M,x=>g(x)*.45,h(m,97,!0),.12,i*1.5)}const v=p.slice(1).reduce((T,$,M)=>T+Math.hypot($.x-p[M].x,$.y-p[M].y),0),k=g(.5)>4&&v>g(.5)*6,b=k?[-.3,.3,0]:[0];for(let T=0;T<r;T++){const $=T===0;b.forEach((M,x)=>{const S=h(m,T*10+x),E=M===0?p:Z2(p,A=>g(A)*M*Math.sqrt(Math.sin(Math.PI*A))),I=!$&&M===0?e.lineWidth*(.3+S.next()*.8):0;u(E,A=>g(A)*(k?.5:1)*($?1:.6),S,$?.85:.45,i*($?.6:1),I)})}},f=(p,g,m,w,v,k)=>{const T=h(c,50).next()*Math.PI*2;d(wr(p,g,m,w,v,T,1.08,48),()=>k)};return{look:"pencil",ink:s,limb(p,g,m){d(p,w=>g+(m-g)*w)},line(p,g){d(p,()=>g)},shape(p,g,m){g!==null&&(t.save(),t.globalAlpha*=.88,t.fillStyle=g,kr(t,p,!0),t.fill(),t.restore()),m>0&&d([...p,p[0]],()=>m)},ellipse(p,g,m,w,v,k,b){k!==null&&(t.save(),t.globalAlpha*=.9,t.fillStyle=k,t.beginPath(),t.ellipse(p,g,m,w,v,0,Math.PI*2),t.fill(),t.restore()),f(p,g,m,w,v,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,w,v){if(n.construction===!1)return;const k=c++,b=h(k,0),T=wr(p,g,m,w,v,b.next()*Math.PI*2,1.12,48);u(T,()=>Math.max(.6,e.lineWidth*.18),b,.28,i*1.5)}}}const sd=["thumb","index","middle","ring","pinky"],Ot={"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 Nt(t={}){return{...Ot,...t}}const oe=(t,e,n,s,i)=>({"thumb.curl":t,"index.curl":e,"middle.curl":n,"ring.curl":s,"pinky.curl":i}),St={relaxed:Ot,open:Nt({...oe(0,0,0,0,0),"thumb.across":0,spread:.55}),spread:Nt({...oe(0,0,0,0,0),"thumb.across":0,spread:1}),flat:Nt({...oe(0,0,0,0,0),"thumb.across":.35,spread:0}),fist:Nt({...oe(.7,1,1,1,1),"thumb.across":.9,spread:0}),point:Nt({...oe(.75,0,1,1,1),"thumb.across":.9,spread:0}),thumbsUp:Nt({...oe(0,1,1,1,1),"thumb.across":0,spread:0,roll:70}),peace:Nt({...oe(.75,0,0,1,1),"thumb.across":.9,spread:1}),ok:Nt({...oe(.12,.6,.1,.15,.2),"thumb.across":.55,spread:.6}),pinch:Nt({...oe(.1,.65,.75,.85,.9),"thumb.across":.55,spread:0}),cupped:Nt({...oe(.25,.4,.4,.4,.4),"thumb.across":.4,spread:.05,turn:2}),wave:Nt({...oe(0,.05,.05,.1,.12),"thumb.across":0,spread:.7,turn:2}),pencilGrip:Nt({...oe(.1,.6,.72,.88,.95),"thumb.across":.5,spread:0,turn:.8,bend:10}),hold:Nt({...oe(.5,.7,.72,.74,.76),"thumb.across":.75,spread:0,turn:1})};function es(t,e,n){const s={...t};for(const[i,r]of Object.entries(e)){const o=t[i]??r;s[i]=o+(r-o)*n}return s}const tk={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}},ek={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}},Pe={base:[-.11,.1,-.05],bones:[.2,.15,.12],widths:[.2,.145,.135],out:[-.7,.68,-.22],across:[.35,.5,-.8]},nk=[82,100,62],sk=[48,72],ik=3,rk=13,ok=.035,ak=-.075,lk=[[-.17,0],[-.215,.12],[-.235,.26],[-.225,.4],[-.185,.49],[-.075,.525],[.05,.51],[.16,.465],[.215,.4],[.225,.26],[.2,.1],[.16,0]],Ge=t=>t*Math.PI/180,tl=(t,e)=>[t[0]+e[0],t[1]+e[1],t[2]+e[2]],vr=(t,e)=>[t[0]*e,t[1]*e,t[2]*e],el=(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]],ai=t=>{const e=Math.hypot(t[0],t[1],t[2])||1;return[t[0]/e,t[1]/e,t[2]/e]};function Ue(t,e,n){const s=Math.cos(n),i=Math.sin(n),r=el(e,t),o=e[0]*t[0]+e[1]*t[1]+e[2]*t[2];return[t[0]*s+r[0]*i+e[0]*o*(1-s),t[1]*s+r[1]*i+e[1]*o*(1-s),t[2]*s+r[2]*i+e[2]*o*(1-s)]}const id=[1,0,0],rd=[0,1,0],li=[0,0,1];function ck(t,e,n){const s=Ge(t.fan*(ik+rk*n)),i=[Math.sin(s),Math.cos(s),0],r=[Math.cos(s),-Math.sin(s),0],o=[t.knuckle];let a=0;t.bones.forEach((h,u)=>{a+=Ge(nk[u]*e),o.push(tl(o[u],vr(Ue(i,r,-a),h)))});const l=Ue(li,r,-a),c=o.map((h,u)=>t.width*(1-.14*(u/(o.length-1))));return{joints:o,back:l,widths:c}}function hk(t,e,n=1,s=1){const i=Math.min(1,Math.max(0,e)),r=ai(tl(vr(ai(Pe.out),1-i),vr(ai(Pe.across),i))),o=ai(el(li,r)),a=ai(el(r,o)),l=[[Pe.base[0]*s,Pe.base[1],Pe.base[2]]];let c=0;Pe.bones.forEach((d,f)=>{f>0&&(c+=Ge(sk[f-1]*t)),l.push(tl(l[f],vr(Ue(r,o,c),d)))});const h=Ue(a,o,c),u=[...Pe.widths,Pe.widths[Pe.widths.length-1]*.92].map(d=>d*n);return{joints:l,back:h,widths:u}}function Mr(t,e={}){const n={...Ot,...t},s=e.size??100,i=e.side??"right",r=i==="left"?-1:1,o=Ge(e.angle??0),a=e.fingers===4,l=Math.max(.5,e.plump??1),c=1+(l-1)*.7,h=A=>({...A,knuckle:[A.knuckle[0]*c,A.knuckle[1],A.knuckle[2]],width:A.width*l}),u=Ge(n.bend??0),d=Ge(n.tilt??0),f=Ge(90*(n.turn??0)),p=A=>Ue(Ue(Ue(A,id,-u),li,-d),rd,f),g=Math.cos(o),m=Math.sin(o),w=Ge(n.roll??0),v=Math.cos(w),k=Math.sin(w),b=A=>{const O=A[0]*s,H=-A[1]*s,W=(O*v-H*k)*r,j=O*k+H*v;return{x:W*g-j*m,y:W*m+j*g}},T=A=>{const O=b(A),H=Math.hypot(O.x,O.y);return H>1e-6*s?{x:O.x/H,y:O.y/H}:{x:0,y:0}},$={thumb:hk(n["thumb.curl"]??0,n["thumb.across"]??0,l,c)},M=a?ek:tk;for(const A of sd){const O=M[A];O&&($[A]=ck(h(O),n[`${A}.curl`]??0,n.spread??0))}const x={};for(const[A,O]of Object.entries($)){const H=O.joints.map(p),W=p(O.back);x[A]={points:H.map(b),depths:H.map(j=>j[2]*s),widths:O.widths.map(j=>j*s),nail:W[2],back:T(W)}}const S=lk.flatMap(([A,O])=>[p([A*c,O,ok]),p([A*c,O,ak])]),E=uk(S.map(b)),I=S.reduce((A,O)=>A+O[2],0)/S.length*s;return{size:s,side:i,wrist:{x:0,y:0},palm:E,palmDepth:I,palmFacing:-p(li)[2],fingers:x,axes:{up:T(p(rd)),across:T(p(id)),out:T(p(li))},curls:Object.fromEntries(Object.keys(x).map(A=>[A,n[`${A}.curl`]??0]))}}function od(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,r]of Object.entries(t.fingers))s[i]={...r,points:r.points.map(n)};return{...t,wrist:n(t.wrist),palm:t.palm.map(n),fingers:s}}function uk(t){const e=[...t].sort((r,o)=>r.x-o.x||r.y-o.y);if(e.length<3)return e;const n=(r,o,a)=>(o.x-r.x)*(a.y-r.y)-(o.y-r.y)*(a.x-r.x),s=[];for(const r of e){for(;s.length>=2&&n(s[s.length-2],s[s.length-1],r)<=0;)s.pop();s.push(r)}const i=[];for(const r of[...e].reverse()){for(;i.length>=2&&n(i[i.length-2],i[i.length-1],r)<=0;)i.pop();i.push(r)}return[...s.slice(0,-1),...i.slice(0,-1)]}function ad(t,e,n,s){if(s.mode!=="cel"||e.length<3)return;const i=Math.hypot(...s.light),r=e.map(a=>{const l=a.x-n.x,c=a.y-n.y,h=(l*s.light[0]+c*s.light[1])/((Math.hypot(l,c)||1)*i),u=Math.max(0,-h)*.24;return{x:a.x-l*u,y:a.y-c*u}}),o=a=>{t.beginPath(),t.moveTo(a[0].x,a[0].y);for(const l of a.slice(1))t.lineTo(l.x,l.y);t.closePath()};t.save(),o(e),t.clip(),o([...e,...r.reverse()]),t.globalAlpha*=s.opacity,t.fillStyle=s.shadow,t.fill(),t.restore()}const dk="#f1c9a5",fk="#2f2f33";function Sr(t,e,n,s={},i=0){const r=od(Mr(n,s),e),o=s.ink??fk,a=s.lineWidth??r.size*.035;let l=s.pen??ri(t,{look:s.look??"clean",ink:o,lineWidth:a,seed:s.seed??1,time:i,pencil:{construction:!1,...s.pencil}});const c=s.skin??dk;c==="none"&&(l=oi(t,l));const h=s.nails??!0,u=[{depth:r.palmDepth,draw:()=>gk(t,l,r,c,a,s)}];for(const d of Object.values(r.fingers)){const f=d.depths.reduce((p,g)=>p+g,0)/d.depths.length;u.push({depth:f,draw:()=>pk(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(),r}function gk(t,e,n,s,i,r){if(e.shape(n.palm,s==="none"?null:s,r.connected?0:i),s!=="none"&&r.shading&&e.look==="clean"){const o=n.palm.reduce((a,l)=>({x:a.x+l.x/n.palm.length,y:a.y+l.y/n.palm.length}),{x:0,y:0});ad(t,n.palm,o,r.shading)}if(r.connected&&i>0&&(e.look!=="silhouette"||s==="none")){const{up:o}=n.axes;let a=[];for(let l=0;l<=n.palm.length;l++){const c=n.palm[l%n.palm.length],h=n.palm[(l+1)%n.palm.length];((c.x+h.x)/2-n.wrist.x)*o.x+((c.y+h.y)/2-n.wrist.y)*o.y<n.size*.08?(a.length>1&&e.line(a,i),a=[]):(a.length===0&&a.push(c),a.push(h))}a.length>1&&e.line(a,i)}if(n.palmFacing<-.3&&e.look!=="silhouette"){const{up:o}=n.axes;for(const[a,l]of Object.entries(n.fingers)){const c=n.curls[a]??0;if(a==="thumb"||c<.5)continue;const h=l.points[0],u=l.widths[0]*.42,d={x:h.x-o.x*u*.2,y:h.y-o.y*u*.2},f=Math.atan2(o.y,o.x),p=Array.from({length:7},(g,m)=>{const w=f-Math.PI/2+Math.PI*m/6;return{x:d.x+Math.cos(w)*u,y:d.y+Math.sin(w)*u}});e.line(p,i*.6)}}if(n.palmFacing>.45&&e.look!=="silhouette"){const{up:o,across:a}=n.axes,l=n.size,c=n.wrist,h=(d,f)=>({x:c.x+(a.x*d+o.x*f)*l,y:c.y+(a.y*d+o.y*f)*l}),u=n.side==="left"?-1:1;e.line([h(-.15*u,.36),h(-.04*u,.3),h(.1*u,.33)],i*.5)}}function pk(t,e,n,s,i,r){const{widths:o}=n,a=mk(n.points,2),l=n.points[0],c=a[a.length-1],h=o[0],u=o[o.length-1];if(t.save(),e.look!=="silhouette"||s==="none"){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(s==="none"){const g=zt(a,h,u),m=a[a.length-2],w=Math.atan2(c.y-m.y,c.x-m.x),v=Array.from({length:13},(k,b)=>{const T=w+Math.PI/2-b*Math.PI/12;return{x:c.x+Math.cos(T)*u/2,y:c.y+Math.sin(T)*u/2}});e.shape([...g.slice(0,a.length),...v.slice(1),...g.slice(a.length)],null,i)}else e.limb(a,h+2*i,u+2*i);if(t.restore(),s!=="none"&&e.look!=="silhouette"&&(t.fillStyle=s,br(t,a,h,u)),s==="none"||e.look==="silhouette"||!r||n.nail<.25)return;const d=a[a.length-2],f=yk({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 mk(t,e){let n=t;for(let s=0;s<e;s++){if(n.length<3)return n;const i=[n[0]];for(let r=0;r<n.length-1;r++){const o=n[r],a=n[r+1];r>0&&i.push({x:o.x*.75+a.x*.25,y:o.y*.75+a.y*.25}),r<n.length-2&&i.push({x:o.x*.25+a.x*.75,y:o.y*.25+a.y*.75})}i.push(n[n.length-1]),n=i}return n}const yk=t=>{const e=Math.hypot(t.x,t.y);return e>1e-6?{x:t.x/e,y:t.y/e}:null},Kt={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}},bk=40;function ci(t){return t===void 0?Kt.walk:typeof t=="string"?Kt[t]??Kt.walk:t}function ld(t,e,n=ut,s=1){const i=ci(t);if(i===Kt.walk)return fd(e,n,s);const r=e*Math.PI*2,o=Math.sin(r)*s,a=Math.cos(r)*s,l=w=>Math.abs(w)<=bk,c=i.shoulder??0,h=(w,v)=>l(w)?v*c+i.arm*o:w,u=i.forearm??0,d=l(n.leftShoulder)?n.leftElbow-u-i.elbow*Math.max(0,-o):n.leftElbow,f=l(n.rightShoulder)?n.rightElbow+u+i.elbow*Math.max(0,o):n.rightElbow,p=i.bounces??1,g=(1+Math.cos(r*2*p))/2,m=i.crouch??0;return{...n,lean:n.lean+i.lean*s+(i.sway??0)*Math.sin(r)*(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*o-m*.5,rightHip:-i.swing*o+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 xr(t,e,n=1){const s=ci(t),i=Kt.walk.swing,r=o=>Math.sin(o*Math.PI/180);return gd(e,n)*r(s.swing*n)/r(i*n)}const ut={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 Dt(t){return{...ut,...t}}const cd={mouth:0,smile:0,mouthWidth:1,leftEye:1,rightEye:1,leftBrow:0,rightBrow:0,browTilt:0,lookX:0,lookY:0},qt=t=>({...cd,...t}),vt={neutral:cd,happy:qt({smile:.9,leftBrow:.2,rightBrow:.2}),joyful:qt({mouth:.6,smile:1,mouthWidth:1.2,leftEye:0,rightEye:0,leftBrow:.4,rightBrow:.4}),sad:qt({smile:-.8,leftEye:.8,rightEye:.8,browTilt:.9,leftBrow:-.1,rightBrow:-.1,lookY:.6}),crying:qt({mouth:.45,smile:-1,leftEye:0,rightEye:0,browTilt:1,lookY:.4}),surprised:qt({mouth:.7,mouthWidth:.7,leftEye:1.5,rightEye:1.5,leftBrow:1,rightBrow:1}),shocked:qt({mouth:1,mouthWidth:.8,leftEye:1.6,rightEye:1.6,leftBrow:1,rightBrow:1,browTilt:.4}),angry:qt({smile:-.6,mouthWidth:.9,leftEye:.8,rightEye:.8,leftBrow:-.6,rightBrow:-.6,browTilt:-1}),furious:qt({mouth:.5,smile:-1,mouthWidth:1.3,leftEye:.9,rightEye:.9,leftBrow:-.9,rightBrow:-.9,browTilt:-1}),worried:qt({smile:-.3,mouthWidth:.8,leftEye:1.1,rightEye:1.1,leftBrow:.3,rightBrow:.3,browTilt:.8,lookX:-.5}),scared:qt({mouth:.35,smile:-.5,mouthWidth:.8,leftEye:1.45,rightEye:1.45,leftBrow:.8,rightBrow:.8,browTilt:.9}),confused:qt({smile:-.2,mouthWidth:.8,leftEye:.9,rightEye:1.15,leftBrow:-.3,rightBrow:.8,lookX:.5,lookY:-.4}),skeptical:qt({smile:-.1,leftEye:.6,rightEye:1,leftBrow:-.4,rightBrow:.7,lookX:.4}),thinking:qt({smile:0,mouthWidth:.7,leftBrow:.3,rightBrow:.5,lookX:.6,lookY:-.8}),sleepy:qt({smile:.1,leftEye:.25,rightEye:.25,leftBrow:-.3,rightBrow:-.3,lookY:.5}),disgusted:qt({smile:-.7,mouthWidth:.9,leftEye:.6,rightEye:.75,leftBrow:-.5,rightBrow:-.2,browTilt:-.4,lookX:-.6}),smug:qt({smile:.6,mouthWidth:.9,leftEye:.6,rightEye:.6,leftBrow:.1,rightBrow:.5,lookX:.5}),wink:qt({smile:.9,leftEye:0,rightEye:1,leftBrow:-.2,rightBrow:.3})};function Ve(t,e){return{...t,...typeof e=="string"?vt[e]:e}}const ae={rest:ut,wave:Dt({rightShoulder:135,rightElbow:30,headTilt:6,...vt.happy}),cheer:Dt({leftShoulder:125,leftElbow:20,rightShoulder:125,rightElbow:20,...vt.joyful}),shrug:Dt({leftShoulder:30,leftElbow:85,rightShoulder:30,rightElbow:85,headTilt:-10,...vt.confused,lookX:0,lookY:0}),point:Dt({rightShoulder:90,rightElbow:0,lean:4,smile:.4}),think:Dt({rightShoulder:60,rightElbow:150,headTilt:10,...vt.thinking}),handsOnHips:Dt({leftShoulder:45,leftElbow:-100,rightShoulder:45,rightElbow:-100,leftHip:14,rightHip:14,smile:.8}),sad:Dt({leftShoulder:14,rightShoulder:14,leftElbow:-4,rightElbow:-4,headTilt:-14,lean:-3,...vt.sad}),surprised:Dt({leftShoulder:70,leftElbow:60,rightShoulder:70,rightElbow:60,...vt.surprised}),crouch:Dt({stretch:.72,leftShoulder:35,rightShoulder:35,leftElbow:-50,rightElbow:-50,leftHip:22,rightHip:22,headTilt:-4}),sit:Dt({sit:1,turn:.5,leftShoulder:-25,rightShoulder:25,leftElbow:-55,rightElbow:55}),jump:Dt({stretch:1.22,leftShoulder:140,rightShoulder:140,leftElbow:20,rightElbow:20,leftHip:4,rightHip:4,...vt.joyful}),duck:Dt({stretch:.62,bend:28,headTilt:-8,leftShoulder:150,rightShoulder:150,leftElbow:130,rightElbow:130,leftHip:25,rightHip:25,...vt.scared}),lie:Dt({spin:-90,rise:-.42,leftShoulder:165,rightShoulder:165,leftElbow:150,rightElbow:150,...vt.sleepy}),sideSplit:Dt({leftHip:90,rightHip:90,leftAnkle:-45,rightAnkle:-45,leftShoulder:120,rightShoulder:120,leftElbow:10,rightElbow:10,...vt.happy}),frontSplit:Dt({turn:1,leftHip:-90,rightHip:-90,leftAnkle:-45,rightAnkle:-45,leftShoulder:-150,rightShoulder:150,leftElbow:10,rightElbow:-10,...vt.happy})},hd=Object.keys(ut);function ns(t,e,n){const s={...t};for(const i of hd)s[i]=t[i]+(e[i]-t[i])*n;return s}const nl=24,ud=4,dd=28,wk=40;function fd(t,e=ut,n=1){const s=Math.sin(t*Math.PI*2)*n,i=Math.cos(t*Math.PI*2)*n,r=c=>Math.abs(c)<=wk,o=c=>r(c)?22*s:c,a=r(e.leftShoulder)?e.leftElbow-dd*Math.max(0,-s):e.leftElbow,l=r(e.rightShoulder)?e.rightElbow+dd*Math.max(0,s):e.rightElbow;return{...e,lean:e.lean+ud*n,headTilt:e.headTilt-ud*.5*n,leftElbow:a,rightElbow:l,leftHip:-nl*s,rightHip:-nl*s,leftKnee:-30*Math.max(0,i),rightKnee:30*Math.max(0,-i),leftShoulder:o(e.leftShoulder),rightShoulder:o(e.rightShoulder)}}function gd(t,e=1){return 4*((sl+Tr)*t)*Math.sin(nl*e*Math.PI/180)}function pd(t){const e=Math.abs(Math.sin(t/65)),n=.55+.45*Math.sin(t/310);return e*n}const md=.12,yd=.46,kk=1-2*md,vk=.1,Mk=.21,Sk=.19,sl=.24,Tr=.22,bd=.12,xk=.14,wd=.33,kd=.7,vd=.3,Tk=.35,Ek=[1.7,1.05],Ak=[1.3,.75],Md=[1.45,.85],$k=[1.15,.75],Sd=.06,Pk=.7,Ik=.65,xd=.075,Ok=.3,Ck=.02,_k=.012,Hk=12,Rk=.25,Er=90,Lk=.25,Fk=.04,Td=.01,Sn=t=>Math.min(1,Math.max(0,t??0));function Nk(t,e=1){return Tr*t*e}const il=-.12,Ed=.4,he=t=>t*Math.PI/180,Wk=(t,e)=>({x:e*Math.sin(he(t)),y:Math.cos(he(t))}),Ad=(t,e)=>Math.max(0,t)*(1-Math.min(1,Math.max(0,e))),$d=(t,e,n,s)=>t-.3*e-n*.14*e-Math.max(0,s-1)*.12*e;function Dk(t,e,n,s,i,r){const o=Math.max(1,Math.min(r*.6,xk*n)),a=Sn(e.turn),l=(bd+wd*a)*n,c=s+il*n,h=l+e.lookX*.08*n,u=e.lookY*.07*n,d=[{x:-.34*n*(1-kd*a),squeeze:1-kd*a,open:e.leftEye,brow:e.leftBrow,side:-1},{x:.34*n*(1-vd*a),squeeze:1-vd*a,open:e.rightEye,brow:e.rightBrow,side:1}];t.fillStyle=i,t.strokeStyle=i,t.lineWidth=o;for(const w of d){const v=Ad(w.open,e.blink);if(v<.2){const $=e.smile>.5?-.12*n:.06*n;t.beginPath(),t.moveTo(w.x+l-.12*n,c),t.quadraticCurveTo(w.x+l,c+$,w.x+l+.12*n,c),t.stroke()}else{if(v>1.2){const M=.13*n*v;t.beginPath(),t.ellipse(w.x+l,c,M*.85,M,0,0,Math.PI*2),t.fillStyle="#ffffff",t.fill(),t.stroke(),t.fillStyle=i}const $=v>1.2?.075*n:.1*n;t.beginPath(),t.ellipse(w.x+h,c+u,$,$*1.1*Math.min(v,1),0,0,Math.PI*2),t.fill()}const k=$d(c,n,w.brow,v),b=w.x+l-w.side*.13*n*w.squeeze,T=w.x+l+w.side*.13*n*w.squeeze;t.beginPath(),t.moveTo(T,k),t.lineTo(b,k-e.browTilt*.1*n),t.stroke()}const f=s+Ed*n,p=.25*n*Math.max(.3,e.mouthWidth)*(1-Tk*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 Pd(t,e){const n=e.height??300,s=Math.min(3,Math.max(.3,t.stretch??1)),i=Math.sqrt(s),r=e.armLength??1;if(!Number.isFinite(r)||r<=0)throw new Error("stick figure: armLength must be a positive finite multiplier");const o=(e.headSize??2*md)/2,a=e.headSize===void 0?kk:1-2*o,l=o*n,c=Sn(t.sit),h=t.leftHip+(-Er-t.leftHip)*c,u=t.leftKnee+(-Er-t.leftKnee)*c,d=t.rightHip+(Er-t.rightHip)*c,f=t.rightKnee+(Er-t.rightKnee)*c,p=e.classic===!0,g=Sn(t.turn),m=(V,L,q,G,_)=>{const Y=Math.max(-Math.PI/2,Math.min(Math.PI/2,Math.abs(he(L-q)/2)+he(G))),st=Math.max(-1,Math.min(1,Pk+_)),P=g+(1-g)*V*st;return p?{x:0,y:0}:{x:Math.cos(Y)*Sd*P,y:Math.sin(Y)*Sd}},w={left:t.leftAnkle??0,right:t.rightAnkle??0},v={left:t.leftFootOut??0,right:t.rightFootOut??0};let k=0;if(c>0||!p){const V=(_,Y,st,P,C)=>sl*Math.cos(he(Y))+Tr*Math.cos(he(Y-st))+Math.max(0,m(_,Y,st,P,C).y),L=Math.max(V(-1,h,u,w.left,v.left),V(1,d,f,w.right,v.right)),q=1-Sn((t.rise??0)/Fk),G=(p?Math.min(1,c/Lk):1)*q;k=(yd-L)*G*n*s}const b=-yd*n*s+k,T=-a*n*s+k,$=p?0:(Ck*Sn(t.turn)+_k*c)*n*s,M=he(t.bend??0),x={end:Od(b,T,M,1),bend:M};let S;if(M!==0){S=[];for(let V=0;V<=Id;V++){const L=V/Id,q=Od(b,T,M,L);S.push({x:q.x-$*Math.sin(Math.PI*L),y:q.y})}}else S=$===0?[{x:0,y:b},{x:0,y:T}]:Mn({x:0,y:b},{x:-$,y:(b+T)/2},{x:0,y:T},1,8);const E=T+vk*n*s,I=(e.shoulderWidth??0)*n*Math.cos(g*Math.PI/2),A=(V,L,q,G,_)=>{const Y=Wk(q,G);return{x:V+Y.x*_*n,y:L+Y.y*_*n}},O=(V,L,q)=>{const G=A(0,b,L,V,sl*s);return{root:{x:0,y:b},joint:G,end:A(G.x,G.y,L-q,V,Tr*s)}},H=(V,L,q)=>{const G={x:V*I,y:E},_=A(G.x,G.y,L,V,Mk*i*r);return{root:G,joint:_,end:A(_.x,_.y,L+q,V,Sk*i*r)}},W={left:O(-1,h,u),right:O(1,d,f)},j=(V,L,q,G,_,Y)=>{const st=m(V,q,G,_,Y);return{x:L.end.x+st.x*n*s,y:L.end.y+st.y*n*s}},J=(V,L,q,G,_)=>A(L.end.x,L.end.y,q+G+_,V,xd*i),tt={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(p?0:Ok,e.rubber??0)),r:l,headRx:l/Math.sqrt(s),headRy:l*Math.sqrt(s),hipY:b,neckY:T,drop:k,lean:p?t.lean:t.lean+Hk*Math.sin(Math.PI*c),classic:p,legs:W,toes:{left:j(-1,W.left,h,u,w.left,v.left),right:j(1,W.right,d,f,w.right,v.right)},spine:S,chest:x,arms:tt,handTips:{left:J(-1,tt.left,t.leftShoulder,t.leftElbow,t.leftWrist??0),right:J(1,tt.right,t.rightShoulder,t.rightElbow,t.rightWrist??0)}}}const Id=10;function Od(t,e,n,s){const i=t-e,r=n*s;if(Math.abs(n)<1e-9)return{x:0,y:t-i*s};const o=i/n;return{x:o*(1-Math.cos(r)),y:t-o*Math.sin(r)}}function Bk(t,e){if(t.chest.bend===0)return e;const n=ui(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 hi=(t,e)=>e===0?[t.root,t.joint,t.end]:Mn(t.root,t.joint,t.end,e);function ui(t,e,n){const s=Math.cos(n),i=Math.sin(n),r=t.x-e.x,o=t.y-e.y;return{x:e.x+r*s-o*i,y:e.y+r*i+o*s}}function Cd(t,e,n=!0){const s=qk(t,e),i=e.spin??0,r=e.rise??0;return n&&(i!==0||r!==0)?zk(s,t,i,r):s}function _d(t,e,n){return{pivot:{x:0,y:t.hipY},angle:t.facing*he(e),lift:n*t.height}}function zk(t,e,n,s){const{pivot:i,angle:r,lift:o}=_d(e,n,s),a=d=>{const f=ui(d,i,r);return{x:f.x,y:f.y-o}},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=Td*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+r,right:t.handAngle.right+r},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+r}}}function qk(t,e){const n=he(t.lean),s=he(e.headTilt),i={x:0,y:t.hipY},r=b=>({x:t.facing*b.x,y:b.y}),o=b=>r(ui(b,i,n)),a=b=>o(Bk(t,b)),l=b=>a(ui({x:b.x,y:b.y+t.neckY},{x:0,y:t.neckY},s)),c=hi(t.arms.left,t.rubber).map(a),h=hi(t.arms.right,t.rubber).map(a),u=(b,T)=>Math.atan2(T.y-b.y,T.x-b.x),d={left:a(t.handTips.left),right:a(t.handTips.right)},f=(b,T)=>{const[$,M]=b.slice(-2),x=t.arms[T],S=u(a(x.end),d[T])-u(a(x.joint),a(x.end));return u($,M)+S};let p=1/0;for(const[b,T]of[[e.leftBrow,e.leftEye],[e.rightBrow,e.rightEye]]){const $=$d(il,1,b,Ad(T,e.blink));p=Math.min(p,$,$-e.browTilt*.1)}const g={left:r(t.legs.left.end),right:r(t.legs.right.end)},m={left:r(t.toes.left),right:r(t.toes.right)},w={left:Math.max(g.left.y,m.left.y),right:Math.max(g.right.y,m.right.y)},v=Math.max(w.left,w.right),k=Td*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:r(t.legs.left.joint),right:r(t.legs.right.joint)},feet:g,toes:m,feetY:v,grounded:{left:w.left>=v-k,right:w.right>=v-k},fingertips:d,handAngle:{left:f(c,"left"),right:f(h,"right")},limbs:{leftArm:c,rightArm:h,leftLeg:hi(t.legs.left,t.rubber).map(r),rightLeg:hi(t.legs.right,t.rubber).map(r),spine:t.spine.map(o)},head:{center:l({x:0,y:-t.headRy}),rx:t.headRx,ry:t.headRy,angle:t.facing*(n+t.chest.bend+s),eyeY:il,browTopY:p,mouthY:Ed,faceX:t.facing*(bd+wd*Sn(e.turn))}}}function ye(t,e={}){return Cd(Pd(t,e),t)}function jk(t,e,n){return ui({x:t.center.x+e*t.rx,y:t.center.y+n*t.ry},t.center,t.angle)}function Hd(t,e,n){const s=r=>({x:r.x+e,y:r.y+n}),i=r=>({left:s(r.left),right:s(r.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 Rd(t,e,n={},s=0){const i=Pd(e,n),r=n.color??"#1e293b",o=n.layers??{},a=n.layers?Cd(i,e,!1):void 0,l=n.sketch?yr(t,n.sketch,s):void 0,c=n.sketch&&n.layers?yr(t,n.sketch,s):void 0,h=M=>{t.save(),M(),t.restore()},u=M=>{M&&a&&h(()=>M(t,a,s,c))},d=()=>t.scale(i.facing,1),f=()=>{d(),t.translate(0,i.hipY),t.rotate(he(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=(M,x,S)=>{if(l)return x?l.curve(M):l.line(M);if(i.classic){t.beginPath(),t.moveTo(M[0].x,M[0].y);for(const E of M.slice(1))t.lineTo(E.x,E.y);t.stroke();return}br(t,M,S[0]*i.lineWidth,S[1]*i.lineWidth)},m=(M,x)=>g(hi(M,i.rubber),i.rubber>0,x),w=M=>{i.classic||g([i.legs[M].end,i.toes[M]],!1,$k)},v=M=>{if(n.hands&&!i.classic)return b(M);if(i.classic||l)return;const x=i.arms[M].end;t.beginPath(),t.arc(x.x,x.y,Ik*i.lineWidth,0,Math.PI*2),t.fill()};t.save(),t.strokeStyle=r,t.fillStyle=r,t.lineWidth=i.lineWidth,t.lineCap="round",t.lineJoin="round";const k=_d(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(M){const x=n.hands??{},S=i.arms[M].end,E=i.handTips[M],I=n.headFill??"#ffffff";Sr(t,S,x[M]??Ot,{side:M,angle:Math.atan2(E.x-S.x,S.y-E.y)*180/Math.PI,size:(x.size??xd)*i.height*Math.sqrt(i.stretch),skin:x.skin??(I==="none"?void 0:I),ink:r,lineWidth:i.lineWidth*.45,fingers:x.fingers,plump:x.plump,look:n.sketch?"pencil":"clean",seed:n.sketch?.seed},s)}const T=M=>{h(()=>{p(),m(i.arms[M],Ak),v(M)});const x=o.sleeve;x&&a&&h(()=>x(t,a,M,s,c))},$=Sn(e.turn)>Rk;u(o.behind),h(()=>{d(),m(i.legs.left,Md),w("left"),m(i.legs.right,Md),w("right")}),$&&T("left"),h(()=>{f(),g(i.spine,i.spine.length>2,Ek)}),h(()=>{p();const{left:M,right:x}={left:i.arms.left.root,right:i.arms.right.root};if(M.x!==x.x)if(i.classic)g([M,x],!1,[1,1]);else{const S={x:(M.x+x.x)/2,y:M.y-.3*Math.abs(x.x-M.x)};g(Mn(M,S,x,1,8),!0,[1.1,1.1])}}),u(o.body),$||T("left"),T("right"),u(o.behindHead),h(()=>{p(),t.translate(0,i.neckY),t.rotate(he(e.headTilt));const M=-i.headRy;t.beginPath(),t.ellipse(0,M,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,M,i.headRx,i.headRy);const S=l.nudge();t.translate(S.x,S.y)}else t.stroke();t.translate(0,M),t.scale(i.headRx/i.r,i.headRy/i.r),Dk(t,e,i.r,0,r,i.lineWidth)}),u(o.overHead),u(o.front),t.restore(),n.label&&(t.save(),t.fillStyle=r,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 rl(t,e,n,s){const i={...t},r=t.gait&&s?.[t.gait]||t.gait;let o=t.walking>0?ns(i,ld(r,t.walk,i),t.walking):i,a=Yk(t);const l=t.dancing??0;if(n&&l>0){const c=n(t.beat??0);if(o=ns(o,c.pose,l),c.hands){const h=(u,d)=>d?es(u??Ot,d,l):u;a={left:h(a?.left,c.hands.left),right:h(a?.right,c.hands.right)}}}return t.talk>0&&(o={...o,mouth:Math.max(o.mouth,t.talk*pd(e))}),{pose:o,hands:a}}function Ld(t,e,n,s){return rl(t,e,n,s).pose}const Fd=(t,e)=>(t.facing??e.facing??1)<0?-1:1,di=(t,e)=>`hand.${t}.${e}`;function Yk(t){const e=i=>{if(typeof t[di(i,"spread")]=="number")return Object.fromEntries(Object.keys(Ot).map(r=>[r,t[di(i,r)]]))},n=e("left"),s=e("right");return n||s?{left:n,right:s}:void 0}function Kk(t,e){return!e||!t.hands?t:{...t,hands:{...t.hands,left:e.left??t.hands.left,right:e.right??t.hands.right}}}function ol(t){const e=t.style??{},n=e.height??300,s=n*.8,i={...Dt(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},r={};if(e.hands)for(const o of["left","right"]){const a=e.hands[o]??Ot;for(const l of Object.keys(Ot))r[di(o,l)]=a[l]??Ot[l]}return{type:"custom",x:t.x-s/2,y:t.y-n,width:s,height:n,props:{...i,...r},about:Xk(Object.keys(r),t.cast),figureStyle:e,figureDance:t.dance,figureGaits:t.cast?.gaits,draw(o,a,l){const c=a.props,h=rl(c,l,t.dance,t.cast?.gaits);o.translate(s/2,n),Rd(o,h.pose,Kk({...e,rubber:c.rubber,facing:Fd(c,e)},h.hands),l)}}}function Xk(t,e){const n={...Uu,...Vu};for(const s of t){const[,i,...r]=s.split("."),o=Ju[r.join(".")];o&&(n[s]={...o,description:`${i==="left"?"Left":"Right"} hand: ${o.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 G2(e)}}}function al(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 r=0,o=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"?r=h:c==="y"||c==="motionPathY"?o=h:c in i&&(i[c]=h));const a=Ld(i,e.time,t.figureDance,t.figureGaits),l=ye(a,{...s,rubber:i.rubber,facing:Fd(i,s)});return{pose:a,joints:Hd(l,t.x+r+t.width/2,t.y+o+t.height)}}function Ar(t){const e=[];return t.forEach((n,s)=>{const i=s===0?ut:e[s-1],r=typeof n.pose=="string"?ae[n.pose]:{...i,...n.pose};e.push(n.expression?Ve(r,n.expression):r)}),e}function Gk(t,e){const n=Ar(e);return hd.filter(s=>n.some(i=>i[s]!==ut[s])).map(s=>({id:`${t}-${s}`,target:t,property:s,keyframes:e.map((i,r)=>({time:i.time,value:n[r][s],...i.easing?{easing:i.easing}:{}}))}))}const ll=.5,$r={pataka:Nt({"thumb.curl":.3,"thumb.across":.6,"index.curl":0,"middle.curl":0,"ring.curl":0,"pinky.curl":0,spread:0,turn:2}),tripataka:Nt({"thumb.curl":.3,"thumb.across":.6,"index.curl":0,"middle.curl":0,"ring.curl":1,"pinky.curl":0,spread:0,turn:2}),alapadma:Nt({"thumb.curl":.1,"thumb.across":0,"index.curl":.05,"middle.curl":.15,"ring.curl":.25,"pinky.curl":.35,spread:1,turn:2}),mushti:St.fist,shikhara:St.thumbsUp,hamsasya:Nt({"thumb.curl":.15,"thumb.across":.6,"index.curl":.6,"middle.curl":0,"ring.curl":0,"pinky.curl":0,spread:.7,turn:2}),katakamukha:Nt({"thumb.curl":.2,"thumb.across":.6,"index.curl":.65,"middle.curl":.7,"ring.curl":0,"pinky.curl":0,spread:.4,turn:2})};function Pr(t){return typeof t!="string"?t:t in $r?$r[t]:St[t]}function Nd(t,e,n){const s=[];for(const i of t.keys){const r=s[s.length-1],o=!r||i.reset?{pose:e,...n}:r;s.push({beat:i.beat,pose:{...o.pose,...i.pose},left:i.hands?.left?Pr(i.hands.left):o.left,right:i.hands?.right?Pr(i.hands.right):o.right,easing:i.easing??t.easing})}return s}const cl=(t,e)=>(t%e+e)%e;function Uk(t,e,n,s){const i=Nd(t,n,s);if(i.length===0)return{pose:n,hands:s};const r=cl(e,t.beats);let o=i.length-1;for(let f=0;f<i.length;f++)i[f].beat<=r&&(o=f);const a=i[o],l=i[(o+1)%i.length],c=a.beat<=r?a.beat:a.beat-t.beats,h=l.beat>c?l.beat:l.beat+t.beats,u=h>c?(r-c)/(h-c):0,d=Wt(l.easing??"ease-in-out")(Math.min(1,Math.max(0,u)));return{pose:ns(a.pose,l.pose,d),hands:{left:es(a.left,l.left,d),right:es(a.right,l.right,d)}}}const Vk=[["leftShoulder","rightShoulder"],["leftElbow","rightElbow"],["leftWrist","rightWrist"],["leftHip","rightHip"],["leftKnee","rightKnee"],["leftAnkle","rightAnkle"],["leftFootOut","rightFootOut"],["leftEye","rightEye"],["leftBrow","rightBrow"]],Jk=["lean","headTilt","lookX","spin"],Zk=new Set(["leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee"]);function Wd(t){const e={...t},n=(t.turn??0)>=.5;for(const[s,i]of Vk){const r=n&&Zk.has(s)?-1:1;e[s]=r*t[i],e[i]=r*t[s]}if(!n)for(const s of Jk)e[s]=-t[s];return e}const Qk=t=>Math.min(1,Math.max(-1,(.5-t)*4));function Dd(t,e,n){const s=cl(n,1),i=(1+Math.cos(2*Math.PI*s))/2,r=e.bounce*(e.accent==="up"?1-i:i),o=Math.min(1,Math.max(0,t.turn??0)),a=Qk(o);return{...t,leftHip:t.leftHip+a*r/2,rightHip:t.rightHip+r/2,leftKnee:t.leftKnee+a*r,rightKnee:t.rightKnee+r,lean:t.lean+(e.sway??0)*(1-o)*Math.sin(Math.PI*n)}}function Ir(t){const e={...ut,...t.stance};return t.expression?Ve(e,t.expression):e}function Bd(t){return{left:t.hands?.left?Pr(t.hands.left):Ot,right:t.hands?.right?Pr(t.hands.right):Ot}}function hl(t,e,n){const s=t.moves[e.move];if(!s)throw new Error(`dance: "${t.label}" has no move "${e.move}"`);const i=Uk(s,n,Ir(t),Bd(t));return e.mirror?{pose:Wd(i.pose),hands:{left:i.hands?.right,right:i.hands?.left}}:i}function Or(t,e,n={}){const s=typeof t=="string"?Je[t]:t;let i;if(n.move)i=hl(s,{move:n.move,mirror:n.mirror},e);else{const r=s.routine,o=r.reduce((u,d)=>u+d.beats,0),a=cl(e,o);let l=0,c=0;for(;c<r.length-1&&a>=l+r[c].beats;)l+=r[c++].beats;const h=a-l;if(i=hl(s,r[c],h),h<ll&&r.length>1&&e>=ll){const u=r[(c-1+r.length)%r.length],d=hl(s,u,u.beats+h),f=Wt("ease-in-out")(h/ll);i={pose:ns(d.pose,i.pose,f),hands:{left:es(d.hands.left,i.hands.left,f),right:es(d.hands.right,i.hands.right,f)}}}}return{...i,pose:Dd(i.pose,s.groove,e)}}function t5(t,e,n={}){return Or(t,e,n).pose}function Cr(t){return(typeof t=="string"?Je[t]:t).routine.reduce((n,s)=>n+s.beats,0)}const e5={leftToe:"rightToe",rightToe:"leftToe",leftHeel:"rightHeel",rightHeel:"leftHeel"};function zd(t,e,n,s,i,r,o){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<r||h>=o))for(const u of l.taps??[])i.push({beat:h,tap:s?e5[u]:u})}}function n5(t,e,n,s={}){const i=typeof t=="string"?Je[t]:t,r=[];if(n<=e)return r;if(s.move){const o=i.moves[s.move],a=Math.floor(e/o.beats)*o.beats;zd(o,a,Math.ceil((n-a)/o.beats)*o.beats,s.mirror,r,e,n)}else{const o=Cr(i);for(let a=Math.floor(e/o)*o;a<n;a+=o){let l=a;for(const c of i.routine)zd(i.moves[c.move],l,c.beats,c.mirror,r,e,n),l+=c.beats}}return r.sort((o,a)=>o.beat-a.beat)}function qd(t,e){const n=t.moves[e.move];if(!n?.travel)return 0;const s=n.travel/n.beats;return e.mirror?(Nd(n,Ir(t),Bd(t))[0]?.pose.turn??Ir(t).turn??0)>=.5?s:-s:s}function jd(t,e){return e.move?[{move:e.move,beats:t.moves[e.move].beats,mirror:e.mirror}]:t.routine}function _r(t,e,n={}){const s=typeof t=="string"?Je[t]:t,i=jd(s,n),r=i.reduce((h,u)=>h+u.beats,0),o=i.reduce((h,u)=>h+qd(s,u)*u.beats,0),a=Math.floor(e/r);let l=a*o,c=e-a*r;for(const h of i){const u=Math.min(h.beats,c);if(l+=qd(s,h)*u,c-=u,c<=0)break}return l}function s5(t,e,n){const s=jd(t,n),i=[0];let r=0;for(let o=0;r<e;o=(o+1)%s.length)r+=s[o].beats,i.push(Math.min(r,e));return i}const i5=8;function Yd(t,e,n){const s=typeof e=="string"?Je[e]:e,i=n.bpm??s.bpm,r=n.beats??(n.move?s.moves[n.move].beats:Cr(s)),o=s5(s,r,n);if(o.every(w=>_r(s,w,n)===0))return;const a=Math.min(n.fade??1,r/2),l=Wt("ease-in-out"),c=w=>a<=0?1:Math.min(l(Math.min(1,w/a)),l(Math.min(1,(r-w)/a))),h=Math.ceil(a*i5),u=a<=0?[]:Array.from({length:h+1},(w,v)=>[v/h*a,r-v/h*a]).flat(),d=[...new Set([...o,...u])].sort((w,v)=>w-v);let f=0;const p=d.map((w,v)=>{if(v>0){const k=d[v-1],b=Math.max(1,Math.ceil((w-k)*16));for(let T=0;T<b;T++){const $=k+(w-k)*T/b,M=k+(w-k)*(T+1)/b;f+=(_r(s,M,n)-_r(s,$,n))*c(($+M)/2)}}return{beat:w,travel:f}}),g=n.start??0,m=n.x??0;return{id:`${t}-x`,target:t,property:"x",keyframes:p.map(w=>({time:g+w.beat*6e4/i,value:m+n.height*w.travel,easing:"linear"}))}}function r5(t,e,n=0){return(t-n)*e/6e4}function o5(t,e={}){return n=>Or(t,n,e)}function a5(t,e){const n=e.start??0,s=6e4/e.bpm,i=n+e.beats*s,r=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+r,value:1,easing:"ease-in-out"},{time:i-r,value:1},{time:i,value:0,easing:"ease-in-out"}]}]}function l5(t,e,n={}){const s=typeof e=="string"?Je[e]:e,i=n.bpm??s.bpm,r=n.beats??(n.move?s.moves[n.move].beats:Cr(s)),o=n.samplesPerBeat??4,a=n.start??0,l=Math.round(r*o),c=Array.from({length:l+1},(g,m)=>{const w=m/o;return{time:a+w*6e4/i,frame:Or(s,w,n)}}),h=(g,m)=>({id:`${t}-${g}`,target:t,property:g,keyframes:c.map(w=>({time:w.time,value:m(w.frame)}))}),d=Object.keys(ut).filter(g=>c.some(m=>m.frame.pose[g]!==c[0].frame.pose[g])||c[0].frame.pose[g]!==ut[g]).map(g=>h(g,m=>m.pose[g])),f=n.height===void 0?void 0:Yd(t,s,{...n,bpm:i,beats:r,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(Ot)){const w=v=>v.hands?.[g]?.[m]??Ot[m];c.some(v=>w(v.frame)!==Ot[m])&&p.push(h(di(g,m),w))}return[...d,...p]}const fi={type:"back",mode:"out",overshoot:1.1},Zt="ease-out-cubic",c5={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:Zt,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:Zt},{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:Zt},{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}]},h5={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}]},u5={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:Zt},{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:Zt},{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:Zt},{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:fi},{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}]},d5={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:{...St.spread,turn:2},right:{...St.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:Zt},{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}]},f5={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:fi,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:fi},{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:fi},{beat:3,pose:{headTilt:4}}]},isolations:{label:"Isolations",beats:2,easing:Zt,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}]},g5={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:{...St.cupped,roll:-30},left:{...St.flat,turn:0}}},{beat:.5,pose:{rightWrist:25,rightElbow:22,leftWrist:10,lean:4,rightHip:6,leftHip:16},hands:{right:{...St.cupped,roll:30}}},{beat:1,pose:{rightWrist:-15,rightElbow:12,leftWrist:-45,lean:-4,rightHip:16,leftHip:6},hands:{right:{...St.cupped,roll:-30}}},{beat:1.5,pose:{rightWrist:25,rightElbow:22,leftWrist:10,lean:4,rightHip:6,leftHip:16},hands:{right:{...St.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:{...St.open,turn:2}},easing:Zt},{beat:.5,pose:{lean:-4,rightHip:12,headTilt:6}},{beat:1,pose:{lean:-11,rightHip:22,headTilt:10},easing:Zt},{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:Zt},{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:Zt}]}},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}]},p5={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}]},m5={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}]},y5={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:{...St.spread,turn:2},right:{...St.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:Zt},{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:Zt},{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}]},b5={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:{...St.spread,turn:2},right:{...St.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}]},Je={disco:c5,hipHop:h5,breaking:u5,jazz:d5,kpop:f5,bollywood:g5,bhangra:p5,bharatanatyam:m5,charleston:y5,tap:b5,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:fi},{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}]}},Hr={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}},ul=.215,dl=.205,w5=.065,Kd=.035,k5=.165,v5=.155,M5=12,S5=.3,x5=.7,T5=.35,E5=t=>t*Math.PI/180,lt={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,pupil:1,lid:0,bulge:0,"brow.left":0,"brow.right":0,browTilt:0,lookX:0,lookY:0,blush:0,tears:0,sweat:0,"hair.swing":0,"hair.trail":0,"hair.lift":0,"held.left":1,"held.right":1,"held.both":1};function kt(t={}){return{...lt,...t}}const A5=new Set(["turn","side","head.turn","head.tilt","roll","lookX","hair.swing"]);function Xd(t){const e={};for(const[n,s]of Object.entries(t)){const i=n.replace(/(^|\.)(left|right)(\.|$)/,(r,o,a,l)=>`${o}${a==="left"?"right":"left"}${l}`);e[i]=A5.has(n)?-s:s}return e}function $t(t,e){const n={};for(const s of["left","right"])for(const[i,r]of Object.entries(e))n[`${t}.${s}.${i}`]=r;return n}const be={rest:lt,wave:kt({"arm.right.spread":115,"arm.right.bend":55,"arm.right.elbow":0,"head.tilt":-6,smile:.9}),cheer:kt({...$t("arm",{spread:140,bend:20,elbow:0}),mouth:.6,smile:1,"eye.left":0,"eye.right":0}),point:kt({"arm.right.spread":88,"arm.right.elbow":0,"arm.right.bend":0,"head.turn":-20,smile:.4}),handsOnHips:kt({...$t("arm",{spread:50,bend:-105,elbow:0}),...$t("leg",{spread:9}),smile:.8}),think:kt({"arm.right.spread":22,"arm.right.bend":-150,"arm.right.elbow":0,"head.tilt":10,lookX:-.5,lookY:-.8,smile:0}),shrug:kt({...$t("arm",{spread:35,bend:75,elbow:0}),"head.tilt":-10,smile:-.2}),sit:kt({...$t("leg",{swing:90,knee:90,spread:4}),...$t("arm",{swing:25,elbow:45,spread:8})}),kneel:kt({"leg.left.swing":90,"leg.left.knee":90,"leg.right.swing":-18,"leg.right.knee":108,"leg.right.ankle":16,...$t("arm",{swing:20,elbow:30})}),crouch:kt({...$t("leg",{swing:75,knee:140,spread:6}),lean:25,...$t("arm",{swing:50,elbow:40}),"head.nod":-15}),crawl:kt({lean:82,"head.nod":-35,...$t("arm",{swing:80,elbow:0,spread:4}),...$t("leg",{knee:92,ankle:-88})}),lieDown:kt({roll:90,...$t("arm",{spread:8}),"head.nod":0}),sleep:kt({roll:90,...$t("arm",{spread:8,swing:20,elbow:40}),"leg.left.knee":20,"leg.left.swing":15,blink:1,smile:.2}),stretch:kt({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:kt({...$t("leg",{swing:80,spread:22,rotate:75,knee:145}),...$t("arm",{swing:25,spread:18,elbow:30}),lean:5,smile:.5}),carry:kt({...$t("arm",{spread:16,elbow:4}),lean:-3,smile:.4}),cane:kt({"arm.right.swing":16,"arm.right.spread":10,"arm.right.elbow":0,"arm.right.bend":0,"arm.left.swing":2,side:-3,lean:4,"leg.right.swing":4,smile:.3}),lift:kt({...$t("arm",{swing:28,spread:24,elbow:85,bend:-45}),...$t("leg",{swing:12,knee:22,spread:6}),lean:-4,smile:.2}),push:kt({lean:28,...$t("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:kt({lean:-22,...$t("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:kt({"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:kt({"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:kt({...$t("arm",{swing:32,spread:10,elbow:82,bend:-28}),"head.nod":22,lookY:.8,smile:.2}),type:kt({...$t("leg",{swing:90,knee:90,spread:4}),...$t("arm",{swing:40,spread:10,elbow:55,bend:-20}),lean:8,"head.nod":10,lookY:.5,smile:0})},Gd=["round","flat","pointed","big"],$5={round:{length:1,width:[.95,.7]},flat:{length:1.12,width:[.85,.85]},pointed:{length:1.25,width:[1,.3]},big:{length:1.5,width:[1.25,1.1]}};function fl(t={}){const e=t.headSize??.3,n=t.shoulderWidth??.06,s=t.hipWidth??.022,i=t.legLength??1,r=t.armLength??1,o=$5[t.feet??"round"],a=Math.max(.12,1-e-Kd-(ul+dl)*i),l=u=>({id:`arm.${u}`,parent:"spine",offset:[(u==="left"?1:-1)*n,-.035,0],rest:[0,-1,0],side:u==="left"?1:-1,bones:[{length:k5*r,width:[1.25,.9]},{length:v5*r,width:[.9,.75]}]}),c=u=>({id:`leg.${u}`,parent:null,offset:[(u==="left"?1:-1)*s,0,0],rest:[0,-1,0],side:u==="left"?1:-1,bones:[{length:ul*i,width:[1.45,1.05]},{length:dl*i,width:[1.05,.85]},{length:w5*Math.sqrt(i)*o.length,width:o.width}]}),h=(u,d)=>u[d]??lt[d]??0;return{id:"human",hipHeight:(ul+dl)*i,chains:[c("left"),c("right"),{id:"spine",parent:null,rest:[0,1,0],bones:[{length:a/2,width:[1.7,1.4]},{length:a/2,width:[1.4,1.1]}]},{id:"neck",parent:"spine",rest:[0,1,0],bones:[{length:Kd,width:[1,.9]}]},l("left"),l("right")],head:{on:"neck",size:e},contacts:[...["left","right"].flatMap(u=>[{chain:`leg.${u}`,joint:1},{chain:`leg.${u}`,joint:2},{chain:`leg.${u}`,joint:3},{chain:`arm.${u}`,joint:1},{chain:`arm.${u}`,joint:2}]),{chain:"spine",joint:0},{chain:"spine",joint:1},{chain:"spine",joint:2},{head:"top"}],angles(u,d){if(d.id==="spine"){const v=-h(u,"lean")/2,k=h(u,"side")/2,b=-h(u,"bend");return[{swing:v+b*S5,spread:k},{swing:v+b*x5,spread:k}]}if(d.id==="neck")return[{swing:-h(u,"bend")*T5,spread:0}];const[f,p]=d.id.split("."),g=v=>h(u,`${f}.${p}.${v}`);if(f==="arm")return[{swing:g("swing"),spread:g("spread")},{swing:g("elbow"),spread:g("bend")}];const m=(d.side??1)*g("rotate"),w=1-Math.cos(E5(g("rotate")));return[{swing:g("swing"),spread:g("spread"),yaw:m},{swing:-g("knee"),spread:0,yaw:m},{swing:90+g("ankle")-w*(g("swing")-g("knee")),spread:0,yaw:(M5+g("toeOut"))*(d.side??1)}]},withAngles(u,d,f){const[p,g]=d.id.split("."),m=w=>`${p}.${g}.${w}`;return p==="arm"?{...u,[m("swing")]:f[0].swing,[m("spread")]:f[0].spread,[m("elbow")]:f[1].swing,[m("bend")]:f[1].spread}:p==="leg"?{...u,[m("swing")]:f[0].swing,[m("spread")]:f[0].spread,[m("knee")]:-f[1].swing}:u},boneScale(u,d){const f=Math.min(3,Math.max(.3,h(u,"stretch")));return d?.id.startsWith("arm.")?Math.sqrt(f):f},headPose(u){const d=Math.min(3,Math.max(.3,h(u,"stretch")));return{yaw:h(u,"head.turn"),nod:h(u,"head.nod"),tilt:h(u,"head.tilt"),sx:1/Math.sqrt(d),sy:Math.sqrt(d)}},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 P5(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"},r=e.slice(2).join(".");return`${s} · ${i[r]??r.replace(".curl"," curl").replace(".across"," across")}`}if(e.length===3){const[s,i,r]=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"}[r]??r}`}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",pupil:"Pupil size",lid:"Eyelids lowered",bulge:"Eyes bulging","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","hair.swing":"Hair · swing","hair.trail":"Hair · trail","hair.lift":"Hair · lift","held.left":"Left hand · holding","held.right":"Right hand · holding","held.both":"Both hands · holding"}[t]??t}const I5={leftEye:"eye.left",rightEye:"eye.right",leftBrow:"brow.left",rightBrow:"brow.right"},O5={blush:0,tears:0,sweat:0,pupil:1,lid:0,bulge:0},xn=Object.fromEntries(Object.entries(vt).map(([t,e])=>[t,{...Object.fromEntries(Object.entries(e).map(([n,s])=>[I5[n]??n,s])),...O5}]));xn.crying.tears=1,xn.scared.sweat=.8,xn.scared.bulge=.4,xn.sleepy.lid=.5,xn.worried.sweat=.6;const ue=t=>({...xn.neutral,...t}),gl={...xn,laughing:ue({mouth:.75,smile:1,mouthWidth:1.25,"eye.left":0,"eye.right":0,"brow.left":.5,"brow.right":.5}),afraid:ue({mouth:.4,smile:-.6,mouthWidth:.9,"eye.left":1.3,"eye.right":1.3,"brow.left":.6,"brow.right":.6,browTilt:1,sweat:1,pupil:.8,bulge:.5}),bored:ue({smile:-.05,mouthWidth:.6,"eye.left":.45,"eye.right":.45,"brow.left":-.4,"brow.right":-.4,lookX:.5}),tired:ue({mouth:.2,smile:-.3,mouthWidth:.7,"eye.left":.3,"eye.right":.3,"brow.left":-.1,"brow.right":-.1,browTilt:.6,lookY:.6}),embarrassed:ue({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:ue({smile:.75,mouthWidth:1,"eye.left":.75,"eye.right":.75,"brow.left":.5,"brow.right":.5,lookY:-.2}),determined:ue({smile:.35,mouthWidth:.8,"eye.left":.85,"eye.right":.85,"brow.left":-.5,"brow.right":-.5,browTilt:-.9}),affectionate:ue({smile:.85,"eye.left":0,"eye.right":0,"brow.left":.3,"brow.right":.3,blush:.8}),hurt:ue({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:ue({smile:-.25,mouthWidth:.7,"eye.left":.5,"eye.right":.85,"brow.left":-.6,"brow.right":.4,browTilt:-.3,lookX:.8,lid:.3}),relieved:ue({smile:.7,"eye.left":0,"eye.right":0,"brow.left":.4,"brow.right":.4,browTilt:.4}),excited:ue({mouth:.6,smile:1,mouthWidth:1.1,"eye.left":1.4,"eye.right":1.4,"brow.left":.9,"brow.right":.9,blush:.4,pupil:1.3})},de=t=>t*Math.PI/180;function pl([t,e,n],s){const i=Math.cos(s),r=Math.sin(s);return[t,e*i+n*r,-e*r+n*i]}function ss([t,e,n],s){const i=Math.cos(s),r=Math.sin(s);return[t*i-e*r,t*r+e*i,n]}function Qt([t,e,n],s){const i=Math.cos(s),r=Math.sin(s);return[t*i+n*r,e,-t*r+n*i]}const Ie=(t,e)=>[t[0]+e[0],t[1]+e[1],t[2]+e[2]],Rr=(t,e)=>[t[0]*e,t[1]*e,t[2]*e],Lr=(t,e)=>ss(pl(t,e.swing),e.spread);function Fr(t,e){const n=Qt(t,e);return{point:{x:n[0],y:-n[1]},depth:n[2]}}function is(t,e,n){const s=n,r=[0,t.hipHeight*s*(t.boneScale?.(e,null)??1),0],o={};for(const g of t.chains){const m=g.parent?o[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 w=g.at??(m?m.joints3.length-1:0),v=m?m.joints3[w]:r,k=m?m.frames[Math.max(0,w-1)]:{swing:0,spread:0},b=g.offset?Ie(v,Lr(Rr(g.offset,s),k)):v,T=g.side??1,$=t.boneScale?.(e,g)??1,M=t.angles(e,g),x=[b],S=[];let E=k.swing,I=k.spread;g.bones.forEach((A,O)=>{const H=M[O]??{swing:0,spread:0};E+=de(H.swing),I+=de(H.spread)*T,S.push({swing:E,spread:I});const W=Qt(Lr(g.rest,{swing:E,spread:I}),de(H.yaw??0));x.push(Ie(x[O],Rr(W,A.length*s*$)))}),o[g.id]={joints3:x,frames:S}}const a=o[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=>Lr(Qt(pl(ss(g,-de(l.tilt)),-de(l.nod)),de(l.yaw)),c),p=Ie(a.joints3[a.joints3.length-1],f([0,d,0]));return{height:s,root:r,chains:o,head:{center:p,rx:u,ry:d,toBody:f}}}function ml(t,e,n){const s=n.height,i=de(90*(e.turn??0)),r=is(t,e,s),{root:o}=r,a=r.chains,{rx:l,ry:c}=r.head,h=r.head.toBody,u=r.head.center,d={};for(const S of t.chains){const{joints3:E,frames:I}=a[S.id],A=E.map(O=>Fr(O,i));d[S.id]={id:S.id,joints3:E,frames:I,points:A.map(O=>O.point),depths:A.map(O=>O.depth)}}const f=Fr(u,i),p=[[1,0,0],[0,1,0],[0,0,1]].map(S=>Qt(h(S),i)),g=Fr(o,i).point,m=de(e.roll??0),w=S=>{const E=S.x-g.x,I=S.y-g.y;return{x:g.x+E*Math.cos(m)-I*Math.sin(m),y:g.y+E*Math.sin(m)+I*Math.cos(m)}},v=([S,E,I])=>[S*Math.cos(m)+E*Math.sin(m),-S*Math.sin(m)+E*Math.cos(m),I];for(const S of Object.values(d))S.points=S.points.map(w);const k={center:w(f.point),depth:f.depth,rx:l,ry:c,angle:0,axes:p.map(v)},b=k.axes[1];k.angle=Math.atan2(b[0],b[1]);const T=S=>{if("head"in S)return{x:k.center.x+b[0]*c,y:k.center.y-b[1]*c};const E=d[S.chain];return E.points[Math.min(S.joint,E.points.length-1)]};let $=0;(n.contact??"ground")==="ground"&&($=-Math.max(...t.contacts.map(S=>T(S).y))),$-=(e.lift??0)*s;const M=S=>({x:S.x,y:S.y+$});for(const S of Object.values(d))S.points=S.points.map(M);k.center=M(k.center);const x=t.contacts.map(S=>({spec:S,point:T(S)}));return{height:s,view:i,chains:d,head:k,hip:M(w(g)),hipDepth:Fr(o,i).depth,contacts:x,groundY:Math.max(...x.map(S=>S.point.y))}}const Nr=(t,e)=>[t[0]-e[0],t[1]-e[1],t[2]-e[2]],yl=t=>{const e=Math.hypot(t[0],t[1],t[2])||1;return[t[0]/e,t[1]/e,t[2]/e]};function Ze(t,e,n){const s=n.height,i=de(90*(e.turn??0)),r=de(e.roll??0),o=is(t,e,s),a=Qt(o.root,i),l=m=>Ie(ss(Nr(Qt(m,i),a),-r),a),c={};for(const m of t.chains)c[m.id]=o.chains[m.id].joints3.map(l);const h=l(o.head.center),u=m=>yl(Nr(l(Ie(o.head.center,o.head.toBody(m))),h)),d=[u([1,0,0]),u([0,1,0]),u([0,0,1])],f=m=>{if("head"in m)return Ie(h,Rr(d[1],o.head.ry));const w=c[m.chain];return w[Math.min(m.joint,w.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,w])=>[m,w.map(g)])),head:{center:g(h),rx:o.head.rx,ry:o.head.ry,axes:d}}}function Wr(t,e,n,s){const i=n.height,r=de(90*(e.turn??0)),o=is(t,e,i),a=Ze(t,e,n),l=a.hip,c=a.chains,h=a.head.center,u=I=>{if("head"in I)return Ie(h,Rr(a.head.axes[1],a.head.ry));const A=c[I.chain];return A[Math.min(I.joint,A.length-1)]},d=s.toView(l),f=ss(Qt([0,0,1],r),-de(e.roll??0)),p=yl(Nr(s.toView(Ie(l,f)),d)),g=s.toScreen(d),m=s.toScreen([d[0]+1,d[1],d[2]]),w=Math.hypot(m.x-g.x,m.y-g.y),v=I=>{const A=s.toView(I);return{point:s.toScreen(A),depth:A[2]*w}},k={};for(const I of t.chains){const A=c[I.id].map(v);k[I.id]={id:I.id,joints3:o.chains[I.id].joints3,frames:o.chains[I.id].frames,points:A.map(O=>O.point),depths:A.map(O=>O.depth)}}const b=s.toView(h),T=s.toScreen(b),$=s.toScreen([b[0]+1,b[1],b[2]]),M=Math.hypot($.x-T.x,$.y-T.y),x=a.head.axes.map(I=>yl(Nr(s.toView(Ie(h,I)),b))),S={center:T,depth:b[2]*w,rx:o.head.rx*M,ry:o.head.ry*M,angle:Math.atan2(x[1][0],x[1][1]),axes:x},E=t.contacts.map(I=>({spec:I,point:v(u(I)).point}));return{height:i*w,view:r,bodyForward:p,chains:k,head:S,hip:g,hipDepth:d[2]*w,contacts:E,groundY:Math.max(...E.map(I=>I.point.y))}}function rs(t,[e,n,s]){const[i,r,o]=t.axes,a=[i[0]*e*t.rx+r[0]*n*t.ry+o[0]*s*t.rx,i[1]*e*t.rx+r[1]*n*t.ry+o[1]*s*t.rx,i[2]*e*t.rx+r[2]*n*t.ry+o[2]*s*t.rx],l=Math.hypot(e,n,s)||1,c=(i[2]*e+r[2]*n+o[2]*s)/l;return{point:{x:t.center.x+a[0],y:t.center.y-a[1]},depth:t.depth+a[2],facing:c}}const Dr=t=>t*180/Math.PI,Tn=(t,e)=>[t[0]-e[0],t[1]-e[1],t[2]-e[2]],bl=(t,e)=>t[0]*e[0]+t[1]*e[1]+t[2]*e[2],os=t=>Math.hypot(t[0],t[1],t[2]),wl=t=>{const e=os(t)||1;return[t[0]/e,t[1]/e,t[2]/e]},Br=t=>Math.atan2(Math.sin(t),Math.cos(t));function Ud(t){const[e,n,s]=wl(t);return{swing:Math.asin(Math.max(-1,Math.min(1,s))),spread:Math.atan2(e,-n)}}function gi(t,e,n,s,i){const r=t.chains.find(A=>A.id===n);if(!r)throw new Error(`reach: no chain ${n} in ${t.id}`);if(r.bones.length<2||r.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 o=ml(t,{...e,turn:0,roll:0,lift:0},{height:i.height,contact:"none"}),a=o.chains[n];if(os(Tn(s,a.joints3[2]))<i.height*1e-12)return e;const l=a.joints3[0],c=os(Tn(a.joints3[1],a.joints3[0])),h=os(Tn(a.joints3[2],a.joints3[1])),u=r.parent?o.chains[r.parent].frames[Math.max(0,(r.at??o.chains[r.parent].joints3.length-1)-1)]:{swing:0,spread:0},d=Tn(s,l),f=t.angles(e,r),p=A=>(f[A]?.yaw??0)*Math.PI/180,g=Math.min(c+h-1e-6,Math.max(Math.abs(c-h)+1e-6,os(d))),m=wl(d),w=r.parent!==null,v=Qt(Lr(r.pole??(w?[0,-.35,-1]:[0,0,1]),u),p(0));let k=Tn(v,[m[0]*bl(v,m),m[1]*bl(v,m),m[2]*bl(v,m)]);os(k)<1e-6&&(k=Qt([1,0,0],p(0))),k=wl(k);const b=(c*c+g*g-h*h)/(2*c*g),T=Math.sqrt(Math.max(0,1-b*b)),$=[l[0]+c*(b*m[0]+T*k[0]),l[1]+c*(b*m[1]+T*k[1]),l[2]+c*(b*m[2]+T*k[2])],M=[l[0]+m[0]*g,l[1]+m[1]*g,l[2]+m[2]*g],x=r.side??1,S=Ud(Qt(Tn($,l),-p(0))),E=Ud(Qt(Tn(M,$),-p(1))),I=[{swing:Dr(Br(S.swing-u.swing)),spread:Dr(Br(S.spread-u.spread))*x},{swing:Dr(Br(E.swing-S.swing)),spread:Dr(Br(E.spread-S.spread))*x}];return t.withAngles(e,r,I)}const as=(t,e)=>(t%e+e)%e,Vd=t=>t*t*(3-2*t),C5=t=>Object.fromEntries(["left","right"].flatMap(e=>Object.entries(St[t]).map(([n,s])=>[`hand.${e}.${n}`,s])));function kl(t,e=!1){const n=fl(),s=gi(n,lt,"arm.left",[.015,.68,.2],{height:1}),i=gi(n,s,"arm.right",[-.015,.68,.2],{height:1});return Array.from({length:32},(r,o)=>{const a=o/4,l=Math.floor(a),c=a-l,h=l%2===0,u=Math.sin(Math.PI*c),d=Math.max(0,...t.map(p=>1-Math.min(as(a-p,8),as(p-a,8))/.5)),f={side:(h?1:-1)*5*Math.sin(Math.PI*c),bend:2+3*u,"head.tilt":(h?-1:1)*3*u,"head.nod":-2*u,"leg.left.swing":h?-4*u:17*u,"leg.right.swing":h?17*u:-4*u,"leg.left.knee":h?5*u:36*u,"leg.right.knee":h?36*u:5*u,"leg.left.spread":4,"leg.right.spread":4,"arm.left.swing":22+d*(e?45:42),"arm.right.swing":22+d*(e?45:42),"arm.left.spread":28-22*d,"arm.right.spread":28-22*d,"arm.left.elbow":48+22*d,"arm.right.elbow":48+22*d,"arm.left.bend":-35*d,"arm.right.bend":-35*d,smile:.9,...C5(e?"hold":"spread")};if(!e)for(const p of Object.keys(i))p.startsWith("arm.")&&(f[p]+=(i[p]-f[p])*d);return{beat:a,pose:f}})}const En={garba:{label:"Garba · two clap",bpm:120,beats:8,strikes:[2,3,6,7],keys:kl([2,3,6,7])},garbaThreeClap:{label:"Garba · three clap",bpm:120,beats:8,strikes:[1,2,3,5,6,7],keys:kl([1,2,3,5,6,7])},dandiya:{label:"Dandiya · partner strikes",bpm:120,beats:8,strikes:[1,3,5,7],keys:kl([1,3,5,7],!0)}};function Jd(t){const e=typeof t=="string"&&Object.hasOwn(En,t)?En[t]:typeof t=="string"?void 0:t;if(!e||!Number.isFinite(e.beats)||e.beats<=0||!Array.isArray(e.keys)||!e.keys.length||!Array.isArray(e.strikes)||!e.keys.every((n,s)=>Number.isFinite(n.beat)&&n.beat>=0&&n.beat<e.beats&&(s===0||n.beat>e.keys[s-1].beat)&&n.pose&&Object.values(n.pose).every(Number.isFinite))||!e.strikes.every(n=>Number.isFinite(n)&&n>=0&&n<e.beats))throw new Error("humanDanceFrame: a dance with positive finite beats, ordered pose keys and strike beats within its loop is required");return e}function pi(t,e,n=lt){const s=Jd(t);if(!Number.isFinite(e))throw new Error("humanDanceFrame: beat must be finite");const i=as(e,s.beats);let r=s.keys.length-1;for(let m=0;m<s.keys.length;m++)s.keys[m].beat<=i&&(r=m);const o=s.keys[r],a=s.keys[(r+1)%s.keys.length],l=o.beat>i?o.beat-s.beats:o.beat,c=a.beat<=o.beat?a.beat+s.beats:a.beat,h=Vd((i-l)/(c-o.beat)),u={...lt,...n};for(const m of new Set(s.keys.flatMap(w=>Object.keys(w.pose)))){if(m==="turn"||m==="roll")continue;const w=m.match(/^hand\.(?:left|right)\.(.+)$/)?.[1],v=n[m]??lt[m]??(w?Ot[w]:void 0)??0,k=o.pose[m]??v;u[m]=k+((a.pose[m]??v)-k)*h}const d=Math.floor(e),f=e-d,p=f<=.6?1:1-Vd((f-.6)/.4),g=Math.max(0,...s.strikes.map(m=>1-Math.min(as(i-m,s.beats),as(m-i,s.beats))/.25));return{pose:u,contact:{side:as(d,2)===0?"left":"right",start:d,weight:p},strike:g}}function _5(t,e){const n=Jd(e.style),s=e.bpm??n.bpm,i=e.beats??n.beats,r=e.samplesPerBeat??16;if(![s,i,r].every(l=>Number.isFinite(l)&&l>0))throw new Error("humanDanceTracks: bpm, beats and samplesPerBeat must be positive and finite");if(!Number.isFinite(e.start??0))throw new Error("humanDanceTracks: start must be finite");const o=Math.max(1,Math.ceil(i*r)),a=Array.from({length:o+1},(l,c)=>({time:(e.start??0)+i*c/o*6e4/s,pose:pi(n,i*c/o,e.pose).pose}));return Object.keys(a[0].pose).filter(l=>l!=="turn"&&l!=="roll"&&a.some(c=>c.pose[l]!==(e.pose?.[l]??lt[l]))).map(l=>({id:`${t}-dance-${l}`,target:t,property:l,keyframes:a.map(c=>({time:c.time,value:c.pose[l],easing:"linear"}))}))}function ls(t,e,n,s){if(!Number.isFinite(t)||t<n||t>s)throw new Error(`organic body: ${e} must be ${n}..${s}`);return t}function zr(t,e){if(t.length<2||t[0].at!==0||t.at(-1).at!==1)throw new Error(`organic body: ${e} must run from 0 to 1`);return t.map((n,s)=>{if(ls(n.at,`${e}.at`,0,1),ls(n.width,`${e}.width`,.001,.3),s>0&&n.at<=t[s-1].at)throw new Error(`organic body: ${e} positions must increase`);return{at:n.at,width:n.width}})}function Zd(t,e){const n=Math.max(.095,e.shoulderWidth+.025),s=Math.max(.085,e.hipWidth+.032),i=t.shading??{},r=i.light??[-.8,-.6];if(r.length!==2||!r.every(Number.isFinite)||Math.hypot(...r)===0)throw new Error("organic body: light must be a finite nonzero 2D vector");if(i.mode!==void 0&&i.mode!=="none"&&i.mode!=="cel")throw new Error("organic body: unknown shading mode");return{torso:zr(t.torso??[{at:0,width:s},{at:.2,width:s},{at:.42,width:s*.72},{at:.68,width:n*.9},{at:.86,width:n},{at:1,width:.024}],"torso"),arm:zr(t.arm??[{at:0,width:.028},{at:.22,width:.027},{at:.5,width:.019},{at:.68,width:.023},{at:1,width:.012}],"arm"),leg:zr(t.leg??[{at:0,width:.04},{at:.24,width:.042},{at:.5,width:.027},{at:.68,width:.032},{at:1,width:.016}],"leg"),neck:zr(t.neck??[{at:0,width:.024},{at:1,width:.023}],"neck"),depth:ls(t.depth??.55,"depth",.2,1),fill:t.fill??e.skin,outline:{color:t.outline?.color??e.ink,width:ls(t.outline?.width??e.lineWidth,"outline.width",0,100)},shading:{mode:i.mode??"cel",light:[...r],shadow:i.shadow??"#633923",opacity:ls(i.opacity??.17,"shading.opacity",0,1),highlight:ls(i.highlight??.12,"shading.highlight",0,1)}}}function Qd(t,e){const n=Math.min(1,Math.max(0,e)),s=t.findIndex(a=>a.at>=n);if(s<=0)return t[0].width;const i=t[s-1],r=t[s],o=(n-i.at)/(r.at-i.at);return i.width+(r.width-i.width)*o*o*(3-2*o)}const tf=8,H5=(t,e,n)=>({x:t.x+(e.x-t.x)*n,y:t.y+(e.y-t.y)*n}),An=(t,e)=>{const n=Math.hypot(e.x-t.x,e.y-t.y)||1;return{x:(e.x-t.x)/n,y:(e.y-t.y)/n}},qr=(t,e,n)=>({x:t.x+e.x*n,y:t.y+e.y*n});function mi(t,e=12){if(!Number.isInteger(e)||e<1||e>128)throw new Error("organicCenterLine: steps must be an integer from 1 to 128");if(t.length<2)return t.map(i=>({...i}));const n=t.map((i,r)=>{const o=An(t[Math.max(0,r-1)],i),a=An(i,t[Math.min(t.length-1,r+1)]),l=Math.hypot(o.x+a.x,o.y+a.y);return l>1e-6?{x:(o.x+a.x)/l,y:(o.y+a.y)/l}:a}),s=[];for(let i=0;i<t.length-1;i++){const r=t[i],o=t[i+1],a=Math.hypot(o.x-r.x,o.y-r.y)*.28,l=qr(r,n[i],a),c=qr(o,n[i+1],-a);for(let h=i===0?0:1;h<=e;h++){const u=h/e,d=1-u;s.push({x:d**3*r.x+3*d*d*u*l.x+3*d*u*u*c.x+u**3*o.x,y:d**3*r.y+3*d*d*u*l.y+3*d*u*u*c.y+u**3*o.y})}}return s}function jr(t,e,n,s=1,i=1){const r=t.map((h,u)=>{const d=t[Math.max(0,u-1)],f=t[Math.min(t.length-1,u+1)];let p=An(d,f);Math.hypot(p.x,p.y)<1e-6&&(p={x:0,y:1});const g={x:-p.y,y:p.x},m=u/Math.max(1,t.length-1),w=Qd(e,m)*n*s,v=An(d,h),k=An(h,f),b=v.x*k.y-v.y*k.x,T=Math.acos(Math.min(1,Math.max(-1,v.x*k.x+v.y*k.y))),$=(Math.hypot(h.x-d.x,h.y-d.y)+Math.hypot(f.x-h.x,f.y-h.y))/(2*Math.max(1e-6,T)),M=Math.min(w,Math.max(w*.2,$*.8));return{center:h,width:w,at:m,left:qr(h,g,b>0?M:w),right:qr(h,g,b<0?-M:-w)}}),o=[],a=[],l=(h,u)=>{o.push(h),a.push(u)};for(const h of r)l(h.left,h.at);const c=(h,u,d)=>{const f={x:-u.y,y:u.x};for(let p=1;p<tf;p++){const g=p*Math.PI/tf,m=(d?1:-1)*Math.cos(g),w=(d?1:-i)*Math.sin(g);l({x:h.center.x+h.width*(f.x*m+u.x*w),y:h.center.y+h.width*(f.y*m+u.y*w)},h.at)}};c(r.at(-1),An(t[Math.max(0,t.length-2)],t.at(-1)),!0);for(const h of[...r].reverse())l(h.right,h.at);return c(r[0],An(t[0],t[Math.min(1,t.length-1)]),!1),{outline:o,samples:r,positions:a}}function ef(t,e,n){const s={},i=e.height,r=e.chains.spine;if(r?.length>=2){const o=e.points["shoulder.left"],a=e.points["shoulder.right"],l=n.chains.find(f=>f.id==="arm.left")?.offset?.[0]??.07,c=Math.max(1e-6,Math.abs(l)*i*2),h=o&&a?Math.min(1,Math.hypot(o.x-a.x,o.y-a.y)/c):Math.abs(Math.cos(e.turn*Math.PI/2)),u=Math.sqrt(h*h+t.depth*t.depth*(1-h*h)),d=[H5(r[0],r[1],-.16),...r.slice(1)];s.spine=jr(mi(d),t.torso,i,u,.25)}e.chains.neck?.length>=2&&(s.neck=jr(mi(e.chains.neck),t.neck,i));for(const o of["left","right"])for(const a of["arm","leg"]){const l=e.chains[`${a}.${o}`];!l||l.length<3||(s[`${a}.${o}`]=jr(mi(l.slice(0,3)),t[a],i),a==="leg"&&l.length>3&&(s[`foot.${o}`]=jr(mi(l.slice(2)),[{at:0,width:.019},{at:1,width:.014}],i)))}return s}function nf(t,e){let n=!1;for(let s=0,i=e.length-1;s<e.length;i=s++){const r=e[s],o=e[i];r.y>t.y!=o.y>t.y&&t.x<(o.x-r.x)*(t.y-r.y)/(o.y-r.y)+r.x&&(n=!n)}return n}function vl(t,e,n,s=0){const i=t.samples.filter(a=>a.at>=e&&a.at<=n),r=(a,l)=>{const c=a[l],h=a.center,u=Math.hypot(c.x-h.x,c.y-h.y)||1;return{x:c.x+(c.x-h.x)*s/u,y:c.y+(c.y-h.y)*s/u}},o=[...i.map(a=>r(a,"left")),...[...i].reverse().map(a=>r(a,"right"))];{const a=t.samples[0].center;for(const l of t.outline.slice(-7)){const c=Math.hypot(l.x-a.x,l.y-a.y)||1;o.push({x:l.x+(l.x-a.x)*s/c,y:l.y+(l.y-a.y)*s/c})}}return o}function sf(t,e){t.beginPath(),t.moveTo(e[0].x,e[0].y);for(const n of e.slice(1))t.lineTo(n.x,n.y);t.closePath()}function R5(t,e,n){const s=n.shading;if(s.mode==="none"||n.fill==="none")return;const i=Math.hypot(...s.light),r={x:s.light[0]/i,y:s.light[1]/i},o=t.globalAlpha;t.save(),sf(t,e.outline),t.clip();for(const a of["left","right"]){const l=e.samples.map(h=>h[a]),c=e.samples.map(h=>{const u=h[a],d=h.center,f=u.x-d.x,p=u.y-d.y,g=(f*r.x+p*r.y)/(Math.hypot(f,p)||1),m=Math.max(0,-g)*.44;return{x:u.x+(d.x-u.x)*m,y:u.y+(d.y-u.y)*m}});if(sf(t,[...l,...c.reverse()]),t.fillStyle=s.shadow,t.globalAlpha=o*s.opacity,t.fill(),s.highlight>0){const h=e.samples.map(f=>{const p=f[a],g=f.center;return{x:p.x+(g.x-p.x)*.2,y:p.y+(g.y-p.y)*.2}}),u=e.samples[Math.floor(e.samples.length/2)][a],d=e.samples[Math.floor(e.samples.length/2)].center;if((u.x-d.x)*r.x+(u.y-d.y)*r.y>0){t.globalAlpha=o*s.highlight,t.strokeStyle="#ffffff",t.lineWidth=Math.max(1,e.samples[0].width*.16),t.beginPath(),t.moveTo(h[0].x,h[0].y);for(const f of h.slice(1))t.lineTo(f.x,f.y);t.stroke()}}}t.restore()}function L5(t,e,n,s){const i=s.bodyContours,r=o=>i[o]&&nf(t,i[o].outline);if(n.startsWith("arm."))return e<.2&&r("spine");if(n.startsWith("leg."))return e<.2&&r("spine")||e>.85&&r(n.replace("leg.","foot."));if(n.startsWith("foot."))return e<.25&&r(n.replace("foot.","leg."));if(n==="neck")return e<.6&&r("spine");if(n==="spine"){if(e>.85&&r("neck"))return!0;for(const o of["left","right"]){if(e>.6&&r(`arm.${o}`)){const a=s.chains[`arm.${o}`]?.[0];if(a&&Math.hypot(a.x-t.x,a.y-t.y)<s.height*.07)return!0}if(e<.25&&r(`leg.${o}`))return!0}}return!1}function rf(t,e,n,s,i){const r=s.bodyContours?.[i];if(!r)return!1;if(n.fill==="none"&&(e=oi(t,e)),e.shape(r.outline,n.fill==="none"?null:n.fill,0),e.look==="clean"&&R5(t,r,n),(e.look!=="silhouette"||n.fill==="none")&&s.lineWidth>0){let o=[];for(let a=0;a<=r.outline.length;a++){const l=a%r.outline.length,c=r.outline[l],h=r.outline[(l+1)%r.outline.length],u={x:(c.x+h.x)/2,y:(c.y+h.y)/2};i.startsWith("arm.")&&r.positions[l]===1||L5(u,r.positions[l],i,s)?(o.length>=2&&e.line(o,s.lineWidth),o=[]):(o.length===0&&o.push(c),o.push(h))}o.length>=2&&e.line(o,s.lineWidth)}return!0}function of(t){return[[.01,-.12,.8],[0,-.25,.98],[-.04,-.31,.8]].map(e=>rs(t,e).point)}function af(t,e){const n=e.shape==="angular"?F5(t,e):e.projection==="volume"?N5(t):wr(t.center.x,t.center.y,t.rx,t.ry,t.angle);if(e.projection!=="volume"||!e.nose)return n;const s=Math.cos(t.angle),i=Math.sin(t.angle),r=u=>({x:((u.x-t.center.x)*s+(u.y-t.center.y)*i)/t.rx,y:((u.x-t.center.x)*i-(u.y-t.center.y)*s)/t.ry}),o=r(of(t)[1]),a=Math.sign(o.x),l=o.y,c=n.flatMap((u,d)=>{const f=r(u),p=r(n[(d+1)%n.length]);if(f.y>l==p.y>l)return[];const g=(l-f.y)/(p.y-f.y);return[(f.x+(p.x-f.x)*g)*a]}),h=Math.max(0,o.x*a-Math.max(...c));return!Number.isFinite(h)||h===0?n:n.flatMap((u,d)=>{const f=n[(d+1)%n.length],p=r(u),g=r(f),m=Math.max(1,Math.ceil(Math.hypot(g.x-p.x,g.y-p.y)/.025));return Array.from({length:m},(w,v)=>{const k=v/m,b={x:u.x+(f.x-u.x)*k,y:u.y+(f.y-u.y)*k},T=r(b),$=(T.y-l+.115)/.23;if(T.x*a<.5||$<=0||$>=1)return b;const M=Math.sin($*Math.PI)**2*h*t.rx*a;return{x:b.x+M*s,y:b.y+M*i}})})}function F5(t,e){const n=Math.min(.95,Math.max(.55,e.jawWidth??.74)),s=Math.min(.35,Math.max(.03,e.chinWidth??.14)),i=[[-1,0],[-.92,s],[-.5,n],[-.12,Math.sqrt(1-.12**2)]];for(let r=0;r<=12;r++){const o=r*Math.PI/24;i.push([Math.sin(o),Math.cos(o)])}return lf(t,i,e.jawRoundness??0,e.projection==="volume")}function N5(t){const e=Array.from({length:41},(n,s)=>{const i=-Math.PI/2+s*Math.PI/40;return[Math.sin(i),Math.cos(i)]});return lf(t,e,0,!0)}function lf(t,e,n,s){const i=[];for(const[a,l]of e)for(let c=0;c<40;c++){const h=c*Math.PI/20,u=l*Math.sin(h);i.push(rs(t,[l*Math.cos(h),a,s?Math.min(u,.82):u]).point)}let r=Ml(i);if(n=Math.min(1,Math.max(0,n)),n===0)return r;const o=n*.25;for(let a=0;a<3;a++)r=r.flatMap((l,c)=>{const h=r[(c+1)%r.length];return[{x:l.x+(h.x-l.x)*o,y:l.y+(h.y-l.y)*o},{x:h.x+(l.x-h.x)*o,y:h.y+(l.y-h.y)*o}]});return r}function Ml(t){const e=t.sort((i,r)=>i.x-r.x||i.y-r.y),n=(i,r,o)=>(r.x-i.x)*(o.y-i.y)-(r.y-i.y)*(o.x-i.x),s=i=>{const r=[];for(const o of i){for(;r.length>=2&&n(r[r.length-2],r[r.length-1],o)<=0;)r.pop();r.push(o)}return r.slice(0,-1)};return[...s(e),...s([...e].reverse())]}const cf=.34,Xt=.12,Gt=-.4,Ut=(t,e,n)=>t[e]??n,W5=(t,e)=>Math.max(0,t)*(1-Math.min(1,Math.max(0,e))),D5=.45,B5=.35,z5=.7,hf=.78;function xt(t,e,n,s="cartoon"){const i=f=>Math.sqrt(Math.max(0,1-f.x*f.x-f.y*f.y));let r=rs(t,[n.x,n.y,i(n)]).facing;const o=t.axes[2];s==="volume"&&n.x*o[0]>0&&(r=Math.max(r,o[2]));const a=Math.atan2(o[0],o[2]),l=Math.cos(a),c=Math.max(B5,l),h=Math.max(z5,l),u=Math.cos(t.angle),d=Math.sin(t.angle);if(s==="volume"){const f=rs(t,[n.x,n.y,i(n)*hf]).point,p=Math.abs(n.x)>.1?Math.min(1,Math.max(0,r)/.25):1,g=Math.max(n.x*o[0]>0?.2:.5,l);return{facing:r,points:e.map(m=>{const w=(m.x-n.x)*g*t.rx*p,v=(m.y-n.y+o[1]*(i(m)-i(n))*hf)*t.ry*p;return{x:f.x+w*u+v*d,y:f.y+w*d-v*u}})}}return{facing:r,points:e.map(f=>{const p=D5*Math.sin(a)+n.x*c+(f.x-n.x)*h,g=f.y+o[1]*i(f),m=p*t.rx,w=g*t.ry;return{x:t.center.x+m*u+w*d,y:t.center.y+m*d-w*u}})}}const Qe=(t,e,n,s=12)=>Array.from({length:s+1},(i,r)=>{const o=r/s,a=1-o;return{x:a*a*t.x+2*a*o*e.x+o*o*n.x,y:a*a*t.y+2*a*o*e.y+o*o*n.y}}),yi=(t,e,n,s)=>{const i=Math.min(1,Math.max(0,(s-t.x)/(n.x-t.x))),r=1-i;return r*r*t.y+2*r*i*e.y+i*i*n.y},Oe=(t,e,n,s,i=16)=>Array.from({length:i},(r,o)=>{const a=Math.PI*2*o/i;return{x:t+Math.cos(a)*n,y:e+Math.sin(a)*s}}),$n=.05,q5=.3,j5="#e06b7d";function Y5(t,e,n,s,i={},r){const o=Math.max(1,Math.min(s*.6,.14*e.rx)),a=(A,O)=>xt(e,A,O,i.projection).points,l=(A,O)=>xt(e,[],{x:A,y:O},i.projection).facing,c=Ut(n,"smile",0),h=Ut(n,"blink",0),u=Ut(n,"lookX",0),d=Ut(n,"lookY",0),f=Ut(n,"browTilt",0),p=Math.max(.2,Ut(n,"pupil",1)),g=Math.min(1,Math.max(0,Ut(n,"lid",0))),m=Math.min(1,Math.max(0,Ut(n,"bulge",0)));for(const A of[1,-1]){const O=A===1?"left":"right",H=cf*A;if(l(H,Xt)<$n)continue;const W={x:H,y:Xt},j=W5(Ut(n,`eye.${O}`,1),h);if(j<.2||i.style==="anime"&&g>=.98){const L=c>.5?.12:-.06;t.line(a(Qe({x:H-.12,y:Xt},{x:H,y:Xt+L},{x:H+.12,y:Xt}),W),o)}else if(i.style==="anime")K5(t,e,W,A,j,g,m,p,u,d,o,i,r);else{const L=j>1.2||m>.02,q=.13*Math.max(j,1)*(1+m*.7);L&&t.shape(a(Oe(H,Xt,q*.85,q),W),"#ffffff",o);const G=(j>1.2?.075:.1)*p*(1+m*.3),_=H+u*.08,Y=Xt-d*.07,st=Oe(_,Y,G,G*1.1*Math.min(j,1));if(t.shape(a(st,W),t.ink,0),i.inPupil&&r){const[P]=a([{x:_,y:Y}],W),C=a(st,W),z=Math.min(...C.map(K=>Math.hypot(K.x-P.x,K.y-P.y)));z>.5&&(r.save(),r.beginPath(),r.arc(P.x,P.y,z,0,Math.PI*2),r.clip(),i.inPupil(r,{x:P.x,y:P.y,r:z,side:O}),r.restore())}if(g>.02){const P=L?q*1.15:G*1.4,C=Xt+P,z=C-P*2*g,K=P*1.1;t.shape(a([{x:H-K,y:C+.02},{x:H+K,y:C+.02},{x:H+K,y:z},{x:H-K,y:z}],W),i.skin??"#ffffff",0),t.line(a([{x:H-K,y:z},{x:H+K,y:z}],W),o)}}const J=Xt+(i.style==="anime"?.38:.3)+Ut(n,`brow.${O}`,0)*.14+Math.max(0,j-1)*.12,tt={x:H+A*.13,y:J},V={x:H-A*.13,y:J+f*.1};t.line(a([tt,{x:(tt.x+V.x)/2,y:(tt.y+V.y)/2},V],{x:H,y:J}),o)}G5(t,e,n,o,i.projection),X5(t,e,i.ageLines??0,o,i.projection);const w={x:0,y:Gt};if(l(0,Gt)<-$n)return;i.nose&&l(0,Xt-.15)>=$n&&(i.projection==="volume"?t.line(of(e),o):t.line(a([{x:.01,y:Xt-.1},{x:.03,y:Gt+.2},{x:-.05,y:Gt+.17}],{x:0,y:Gt+.22}),o));const v=.25*Math.max(.3,Ut(n,"mouthWidth",1)),k=Math.min(1,Math.max(0,Ut(n,"mouth",0)));if(k<=.05){t.line(a(Qe({x:-v,y:Gt},{x:0,y:Gt-c*.25},{x:v,y:Gt}),w),o);return}const b=.3*k;let T,$,M,x;if(c>.3){const A=Gt+.05,O={x:0,y:Gt-b*2};T=[...Qe({x:v,y:A},O,{x:-v,y:A})],$=()=>A,M=H=>yi({x:v,y:A},O,{x:-v,y:A},H),x=.85}else if(c<-.3){const A=Gt-b*.6,O={x:0,y:Gt+b*1.4};T=[...Qe({x:v,y:A},O,{x:-v,y:A})],$=H=>yi({x:v,y:A},O,{x:-v,y:A},H),M=()=>A,x=.5}else{const A=v*.8;T=Oe(0,Gt,A,b);const O=H=>b*Math.sqrt(Math.max(0,1-(H/A)**2));$=H=>Gt+O(H),M=H=>Gt-O(H),x=.5}if(t.shape(a(T,w),t.ink,0),k<q5)return;const S=$(0)-M(0),E=v*x,I=(A,O,H=8)=>Array.from({length:H+1},(W,j)=>A+(O-A)*j/H);if(i.tongue){const A=E*.55,O=I(A,-A).map(W=>({x:W,y:M(W)})),H=Qe({x:-A,y:M(-A)},{x:0,y:M(0)+S*.8},{x:A,y:M(A)},8);t.shape(a([...O,...H.slice(1,-1)],w),j5,0)}if(i.teeth){const A=Math.min(.06,S*.4),O=I(-E,E).map(W=>({x:W,y:$(W)})),H=O.map(({x:W,y:j})=>({x:W*.92,y:j-A})).reverse();t.shape(a([...O,...H],w),"#ffffff",0);for(const W of[-.5,0,.5]){const j=E*W;t.line(a([{x:j,y:$(j)},{x:j*.92,y:$(j)-A}],w),o*.6)}}}function K5(t,e,n,s,i,r,o,a,l,c,h,u,d){const{x:f,y:p}=n,g=Math.min(1.2,Math.max(.5,u.eyeScale??1)),m=Math.min(1.2,Math.max(.45,u.eyeAspect??1)),w=.21*g*(1+o*.15),v=.25*g*m*Math.min(i,1.6)*(1-r)*(1+o*.3),k={x:f-w,y:p},b={x:f+w,y:p},T={x:f,y:p+v*1.9},$={x:f,y:p-v*1.35},M=Qe(k,T,b),x=Qe(b,$,k),S=J=>xt(e,J,n,u.projection).points,E=J=>J.map(tt=>{const V=Math.min(b.x,Math.max(k.x,tt.x));return{x:V,y:Math.min(yi(k,T,b,V),Math.max(yi(b,$,k,V),tt.y))}});t.shape(S([...M,...x.slice(1,-1)]),"#ffffff",h*.5);const I=f+Math.max(-1,Math.min(1,l))*.07*g,A=p-Math.max(-1,Math.min(1,c))*.055*g,O=.115*g,H=.185*g;t.shape(S(E(Oe(I,A,O,H,24))),u.iris??"#4b7fce",h*.4),t.shape(S(E(Oe(I,A-.075*g,O*.7,H*.35))),"rgba(255,255,255,0.25)",0);const W=Math.min(.085,.042*a)*g,j=E(Oe(I,A,W,W*1.35));if(t.shape(S(j),t.ink,0),u.inPupil&&d){const[J]=S([{x:I,y:A}]),tt=Math.min(...S(j).map(V=>Math.hypot(V.x-J.x,V.y-J.y)));tt>.5&&(d.save(),d.beginPath(),d.arc(J.x,J.y,tt,0,Math.PI*2),d.clip(),u.inPupil(d,{...J,r:tt,side:s===1?"left":"right"}),d.restore())}if(t.shape(S(E(Oe(I-.038*g,A+.075*g,.035*g,.045*g))),"#ffffff",0),t.shape(S(E(Oe(I+.04*g,A-.04*g,.014*g,.02*g))),"#ffffff",0),t.line(S(M),h*1.1),u.lashes!==!1)for(const J of[0,.035]){const tt=f+s*(w-J),V=yi(k,T,b,tt);t.line(S([{x:tt,y:V},{x:tt+s*.055,y:V+.07}]),h*.75)}}function X5(t,e,n,s,i){const r=Math.min(1,Math.max(0,n));if(!(r<=0))for(const o of[-1,1]){const a={x:o*.59,y:Xt};if(xt(e,[],a,i).facing<$n)continue;for(const h of[-.06,.035]){const u=[{x:a.x,y:a.y},{x:a.x+o*.1,y:a.y+h}];t.line(xt(e,u,a,i).points,s*.45*r)}const l={x:o*.3,y:-.38},c=Qe({x:l.x,y:-.31},{x:l.x+o*.07,y:-.4},{x:l.x+o*.035,y:-.49});t.line(xt(e,c,l,i).points,s*.35*r)}}const uf="#8fd0f5",df=(t,e,n)=>Array.from({length:18},(s,i)=>{const r=Math.PI*2*i/18,o=Math.sin(r/2);return{x:t+Math.sin(r)*n*o,y:e-n*.9+Math.cos(r)*n*1.6*(.55+.45*o)-n*.4}});function G5(t,e,n,s,i){const r=Math.min(1,Math.max(0,Ut(n,"blush",0))),o=Math.min(1,Math.max(0,Ut(n,"tears",0))),a=Math.min(1,Math.max(0,Ut(n,"sweat",0)));if(!(r+o+a<=.01)){for(const l of[1,-1]){const c={x:.5*l,y:-.16},h=xt(e,[],c,i).facing>=$n;if(r>.01&&h){const{points:d}=xt(e,Oe(c.x,c.y,.17,.1),c,i);if(t.shape(d,`rgba(240, 120, 140, ${(.75*r).toFixed(3)})`,0),r>.5)for(const f of[-.07,0,.07]){const p=[{x:c.x+f-.018,y:c.y-.03},{x:c.x+f+.018,y:c.y+.03}];t.line(xt(e,p,c,i).points,s*.3)}}const u={x:cf*l,y:Xt};if(o>.01&&xt(e,[],u,i).facing>=$n){const d=.05+.04*o,f={x:u.x+.06*l,y:Xt-.2-.12*o};if(t.shape(xt(e,df(f.x,f.y,d),f,i).points,uf,s*.35),o>.6){const p=[{x:u.x+.05*l,y:Xt-.1},{x:f.x,y:f.y+d*.8}];t.line(xt(e,p,f,i).points,s*.3)}}}if(a>.01){const l={x:.64,y:.42};xt(e,[],l,i).facing>=$n&&t.shape(xt(e,df(l.x,l.y,.05+.05*a),l,i).points,uf,s*.35)}}}const U5=15;function xe(t,e){const n=Math.sqrt(Math.max(0,1-e*e));return[n*Math.sin(t),e,n*Math.cos(t)]}const V5=([t,e,n])=>{const s=Math.hypot(t,e,n)||1;return[t/s,e/s,n/s]};function te(t,[e,n,s]){const[i,r,o]=t.axes;return i[2]*e+r[2]*n+o[2]*s}function Ct(t,e){return rs(t,e).point}function Yr(t,e){const n=Math.abs(t-e)%(Math.PI*2);return n>Math.PI?Math.PI*2-n:n}function Kr(t,e,n=64){const s=e.top??1,i=e.bottom??-1,r=Math.max(8,Math.ceil((s-i)*U5)),o=p=>Math.min(s,Math.max(i,s-(s-i)*(p-1)/r)),a=p=>-Math.PI+Math.PI*2*p/n,l=(p,g)=>e.normal?e.normal(p,g):V5(e.position(p,g)),c=r+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=o(p);for(let w=0;w<n;w++){const v=p*n+w;if(g){h[v]=-1;continue}const k=a(w);h[v]=e.inside(k,m),u[v]=h[v]>-.35?te(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 A=0;A<c;A++)for(let O=0;O<=n;O++){const H=A*n+(O===n?0:O);m[A*g+O]=Math.min(h[H],p*u[H])}const w=(A,O)=>m[O*g+A],v=(A,O,H,W)=>{const j=w(A,O),J=w(H,W),tt=j===J?.5:Math.min(1,Math.max(0,j/(j-J)));return Ct(t,e.position(a(A+(H-A)*tt),o(O+(W-O)*tt)))},k=n*c*2,b=new Int32Array(k).fill(-1),T=new Int32Array(k).fill(-1),$=new Map,M=(A,O,H)=>{const W=(H*n+d(O))*2+(A?1:0);return $.has(W)||$.set(W,A?v(d(O),H,d(O),H+1):v(O,H,O+1,H)),W},x=(A,O)=>{b[A]===-1?b[A]=O:T[A]=O},S=(A,O)=>{x(A,O),x(O,A)};for(let A=0;A<c-1;A++)for(let O=0;O<n;O++){const H=A*g+O,W=(m[H]>0?8:0)|(m[H+1]>0?4:0)|(m[H+g+1]>0?2:0)|(m[H+g]>0?1:0);if(W===0||W===15)continue;const j=()=>M(!1,O,A),J=()=>M(!1,O,A+1),tt=()=>M(!0,O,A),V=()=>M(!0,O+1,A);switch(W){case 1:case 14:S(tt(),J());break;case 2:case 13:S(J(),V());break;case 3:case 12:S(tt(),V());break;case 4:case 11:S(j(),V());break;case 6:case 9:S(j(),J());break;case 7:case 8:S(tt(),j());break;case 5:case 10:{const L=(w(O,A)+w(O+1,A)+w(O+1,A+1)+w(O,A+1))/4>0;W===5===L?(S(tt(),j()),S(J(),V())):(S(tt(),J()),S(j(),V()));break}}}const E=[],I=new Uint8Array(k);for(const A of $.keys()){if(I[A])continue;const O=[];let H=-1,W=A;for(;W!==-1&&!I[W];){I[W]=1,O.push($.get(W));const j=b[W],J=T[W],tt=j!==-1&&j!==H&&!I[j]?j:J!==-1&&J!==H&&!I[J]?J:-1;H=W,W=tt}O.length>=3&&E.push(O)}return E};return{near:f(1),far:f(-1)}}const ff=new WeakMap;function Sl(t,e,n){let s=ff.get(t);s||ff.set(t,s=new Map);let i=s.get(e);return i||s.set(e,i=n()),i}function xl(t,e,n,s){if(t.save(),t.beginPath(),t.rect(-1e5,-1e5,2e5,2e5),s?.length){t.moveTo(s[0].x,s[0].y);for(const i of s.slice(1))t.lineTo(i.x,i.y);t.closePath()}else 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 gf(t,e,n,s=.04){const i=[];let r=[];return e.forEach((o,a)=>{te(t,n[a])>s?r.push(Ct(t,o)):(r.length>=2&&i.push(r),r=[])}),r.length>=2&&i.push(r),i}const pf=t=>t*Math.PI/180,Tl=t=>{const e=Math.hypot(...t)||1;return t.map(n=>n/e)},J5=(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]];function mf(t,e,n){return t>=e+n?t:t<=e-n?e:e+(t-e+n)**2/(4*n)}function El(t,e,n){const s=Tl(n),i=t.reduce((c,h,u)=>c+h*s[u],0),o=t.map((c,h)=>c-i*s[h]).reduce((c,h)=>c+h*h,0),a=Math.sqrt(mf(1-o,e*e,e*e)),l=mf(i,a,e)-i;return l===0?t:t.map((c,h)=>c+s[h]*l)}function Z5(t){if(t.path.length<4||(t.path.length-1)%3!==0)throw new Error("hair: a lock path needs a root and groups of three cubic points");if(!Number.isFinite(t.width)||t.width<=0||t.follow!==void 0&&(!Number.isFinite(t.follow)||t.follow<0))throw new Error("hair: lock width must be positive and follow must be nonnegative");for(const n of t.path)if(!Number.isFinite(n.around)||!Number.isFinite(n.up)||n.up>1||n.lift!==void 0&&(!Number.isFinite(n.lift)||n.lift<0))throw new Error("hair: lock points need finite around/up values, up <= 1 and nonnegative lift");const e=t.path[0];if(e.up<0||(e.lift??0)!==0)throw new Error("hair: a lock root must lie on the scalp (up 0..1, lift 0)");return{...t,path:t.path.map(n=>({...n}))}}function Q5(t,e,n,s){const i=(t.path.length-1)/3,r=i*20,o=[],a=[],l=s.trail!==0||s.lift!==0,c=Math.max(0,e+n);for(let h=0;h<=r;h++){const u=h/r,d=Math.min(i-1,Math.floor(u*i)),f=u*i-d,p=1-f,g=[p**3,3*p*p*f,3*p*f*f,f**3],m=t.path.slice(d*3,d*3+4),w=pf(m.reduce((H,W,j)=>H+W.around*g[j],0)),v=m.reduce((H,W,j)=>H+W.up*g[j],0),k=m.reduce((H,W,j)=>H+(W.lift??0)*g[j],0),b=1+e+n+k,T=v>=0?Math.sqrt(Math.max(0,1-v*v)):1,$=u*u*(t.follow??1),M=pf(s.swing)*$,x=w-M,S=[Math.sin(x)*T*b,v*(v>=0?b:1),Math.cos(x)*T*b],E=[S[0],S[1]+s.lift*$,S[2]-s.trail*$],I=[Math.sin(x)*T,Math.max(0,v),Math.cos(x)*T],A=Tl(S),O=l&&$>0?El(E,c,A):E;a.push(A),o.push({center:O,normal:I,left:O,right:O,t:u})}return o.forEach((h,u)=>{const d=o[Math.max(0,u-1)].center,p=o[Math.min(r,u+1)].center.map((w,v)=>w-d[v]),g=Tl(J5(h.normal,p)),m=t.width*Math.sin(Math.PI*h.t)**.6*.5;h.left=h.center.map((w,v)=>w+g[v]*m),h.right=h.center.map((w,v)=>w-g[v]*m),l&&h.t>0&&(t.follow??1)>0&&(h.left=El(h.left,c,a[u]),h.right=El(h.right,c,a[u]))}),o}const cs=(t,e,n)=>t.map((s,i)=>s+(e[i]-s)*n);function tv(t,e,n){const s=n?1:-1,i=[];let r=[];for(let o=0;o<e.length;o++){const a=e[o],l=s*te(t,a.normal)>=0;if(o>0){const c=e[o-1],h=s*te(t,c.normal),u=s*te(t,a.normal);if(h>=0!==l){const d=h/(h-u),f={center:cs(c.center,a.center,d),left:cs(c.left,a.left,d),right:cs(c.right,a.right,d),normal:cs(c.normal,a.normal,d),t:c.t+(a.t-c.t)*d};l?r=[f]:(r.push(f),r.length>=2&&i.push(r),r=[])}}l&&r.push(a)}return r.length>=2&&i.push(r),i}function yf(t,e,n,s,i,r,o){const a=(n.locks??[]).map(h=>Q5(h,n.volume,s,i)),l=h=>h.reduce((u,d)=>u+te(e,d.center),0)/h.length;a.sort((h,u)=>l(h)-l(u));const c=Math.max(.7,r*.35);for(const h of a)for(const u of tv(e,h,o)){const d=u.map(g=>Ct(e,g.left)),f=u.map(g=>Ct(e,g.right));if(t.shape([...d,...f.slice().reverse()],n.color,0),t.look==="clean"&&(n.shine??0)>0){const g=u.filter(m=>m.t>=.2&&m.t<=.75);if(g.length>=3){const m=g.map((v,k)=>{const b=.16*Math.sin(Math.PI*k/(g.length-1));return Ct(e,cs(v.center,v.left,.16+b))}),w=g.map(v=>Ct(e,cs(v.center,v.left,.16)));t.shape([...m,...w.reverse()],`rgba(255,255,255,${n.shine})`,0)}}const p=u.filter(g=>g.t>.3);p.length>=2&&t.line(p.map(g=>Ct(e,g.left)),c)}}const Pt=(t,e,n=0)=>({around:t,up:e,lift:n}),Al=()=>[{width:.66,follow:.22,path:[Pt(-38,.88),Pt(-12,.94,.08),Pt(58,.76,.09),Pt(94,.16,.03)]},{width:.58,follow:.3,path:[Pt(-42,.8),Pt(-24,.7,.12),Pt(18,.57,.09),Pt(64,.3)]},{width:.36,follow:.18,path:[Pt(-58,.76),Pt(-76,.56,.07),Pt(-90,.12,.06),Pt(-102,-.36)]}];function bf(t){return[-100,-130,-160,-190,-220,-250,-280].map((e,n)=>{const s=n%2===0?1:-1,i=t?-2.45-n%3*.12:-1.06-n%3*.09;return{width:t?.88:.92,follow:t?.8+n%3*.12:.38+n%3*.08,path:t?[Pt(e,.7),Pt(e+s*9,.2,.12),Pt(e-s*13,-.5,.2),Pt(e-s*8,-.95,.16),Pt(e-s*3,-1.4,.12),Pt(e+s*18,i+.35,.22),Pt(e+s*12,i,.03)]:[Pt(e,.7),Pt(e+s*7,.15,.2),Pt(e-s*8,-.75,.25),Pt(e+s*5,i)]}})}const ev={softSweep:{volume:.12,shine:.16,part:-38,strands:"part",sweep:-.08,hairline:{front:.64,side:.12,back:-.8},locks:Al()},flowingBob:{volume:.15,shine:.16,length:.96,fall:{taper:.08,wave:.08},part:-38,strands:"part",sweep:-.08,hairline:{front:.64,side:.08,back:-.8},coversEars:!0,locks:[...bf(!1),...Al()]},cascadingWaves:{volume:.16,shine:.16,length:2.38,fall:{taper:.18,wave:.12},part:-38,strands:"part",sweep:-.08,hairline:{front:.64,side:.08,back:-.8},coversEars:!0,locks:[...bf(!0),...Al()]}},hs={swing:0,trail:0,lift:0};function bi(t){if(!t)return hs;const e=t["hair.swing"]??0,n=t["hair.trail"]??0,s=t["hair.lift"]??0;return e===0&&n===0&&s===0?hs:{swing:e,trail:n,lift:s}}const wf=t=>t.swing===0&&t.trail===0&&t.lift===0;function kf(t){return t.length>0||t.ties.some(e=>e.kind!=="bun")||(t.locks??[]).some(e=>(e.follow??1)>0)}function $l([t,e,n],s){if(s===0)return[t,e,n];const i=Math.cos(s),r=Math.sin(s);return[t*i-n*r,e,n*i+t*r]}const vf={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},Mf=1.75,Pl={...ev,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}},mangaSpikes:{volume:.12,texture:"spiky",textureAmount:.08,hairline:{front:.55,side:.12,back:-.7},spikes:[{around:-100,up:.4,length:.55,width:.24},{around:-65,up:.7,length:.6,width:.25},{around:-25,up:.93,length:.6,width:.24},{around:40,up:.87,length:.7,width:.25},{around:85,up:.55,length:.55,width:.24},{around:160,up:.8,length:.5,width:.24},{around:-160,up:.65,length:.55,width:.24}]},mangaSweep:{volume:.14,texture:"spiky",textureAmount:.1,sweep:-.35,hairline:{front:.5,side:.08,back:-.8},spikes:[{around:-95,up:.45,length:.35,width:.2},{around:-60,up:.8,length:.4,width:.24},{around:75,up:.55,length:.4,width:.23},{around:150,up:.75,length:.35,width:.2}]},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:Mf,opening:84,part:0,strands:"part",hairline:{front:.5,side:.05,back:-.85},coversEars:!0},shoulderWaves:{volume:.22,length:Mf,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}},Te={black:"#22201f",brown:"#6b4630",chestnut:"#7b4a2b",auburn:"#9a4426",blond:"#d9b55a",ginger:"#c8662f",gray:"#a7a29c",white:"#ecebe7"};function Sf(t){const e=typeof t=="string"?{style:t}:t,n=e.style?Pl[e.style]:{};if(e.style&&!n)throw new Error(`hair: unknown style '${e.style}'`);const{style:s,hairline:i,...r}=e,o={...vf,...n,...r,hairline:{...vf.hairline,...n.hairline,...i},ties:(r.ties??n.ties??[]).map(a=>({...a})),...r.spikes??n.spikes?{spikes:(r.spikes??n.spikes).map(a=>({...a}))}:{},...r.locks??n.locks?{locks:(r.locks??n.locks).map(Z5)}:{},...r.fall??n.fall?{fall:{...r.fall??n.fall}}:{}};if(o.shine!==void 0&&(!Number.isFinite(o.shine)||o.shine<0||o.shine>1))throw new Error("hair: shine must be between 0 and 1");if(o.fall&&(!Number.isFinite(o.fall.taper)||o.fall.taper<0||o.fall.taper>1||!Number.isFinite(o.fall.wave)||o.fall.wave<0))throw new Error("hair: fall needs taper between 0 and 1 and nonnegative wave");return o}const Pn=t=>t*Math.PI/180,us=(t,e,n)=>{const s=Math.min(1,Math.max(0,(n-t)/(e-t)));return s*s*(3-2*s)},Il=t=>1-Math.abs(2*(t-Math.floor(t))-1);function wi(t,e){const{front:n,side:s,back:i}=t.hairline,r=(n-i)/2,o=(n+i)/2,a=(o+s)/2,l=(o-s)/2,c=Math.max(0,Math.cos(e));let h=a+r*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*Il(e*11/(Math.PI*2))*c),h}function xf(t,e,n){const s=t.textureAmount;switch(t.texture){case"spiky":return s*(Il(e*11/(Math.PI*2))*Il(n*2.6+.5))**1.2*us(-.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 Tf(t,e,n=hs){const s=t.length>0,i=new Map,r=h=>{let u=i.get(h);return u===void 0&&i.set(h,u=wi(t,h)),u},o=Pn(t.opening),a=h=>t.length+(t.texture==="wavy"||t.texture==="curly"||t.texture==="locs"?.12*Math.sin(h*9):0)+(t.fall?.wave??0)*Math.cos(h*3+.6),l=(h,u,d)=>{if(t.flat<=0||u<.45)return null;const f=(u-.45)/.55,p=Math.sqrt(1-.45*.45)*d*(1-f**5),g=.45+(1+t.flat-.45)*Math.min(1,f*1.8);return[p*Math.sin(h),g*(1+e),p*Math.cos(h)]},c={top:1,bottom:s?-(t.length+.25+Math.abs(t.fall?.wave??0)):-1,inside(h,u){const d=u-r(h);if(!s)return d;const f=Math.min(u+a(h),Yr(h,0)-o);return Math.max(d,f)},position(h,u){if(s&&u<0){const k=t.length<1.5?.14*us(-t.length+.45,-t.length-.1,u):0,b=(t.fall?.taper??0)*us(0,-Math.max(.1,a(h)),u),T=1+e+t.volume*(1-k*2.5)+xf(t,h,u)-k-b;return[T*Math.sin(h),u,T*Math.cos(h)]}const d=.4+.6*us(0,.3,u-wi(t,h)),f=1+e+(t.volume+xf(t,h,u))*d,p=l(h,u,f);if(p)return p;const[g,m,w]=xe(h,u),v=[g*f,m*f,w*f];if(t.quiff>0){const k=t.quiff*Math.exp(-((h/.7)**2))*us(.15,.85,u);v[1]+=k*.7,v[2]+=k*.45}return v},normal(h,u){return s&&u<0?[Math.sin(h),0,Math.cos(h)]:xe(h,u)}};return s&&!wf(n)?nv(c,t,n):c}function nv(t,e,n){const s=r=>r<0?us(-.15,-Math.max(.7,e.length),r):0,i=r=>Pn(n.swing)*s(r);return{top:t.top,bottom:t.bottom,inside:(r,o)=>t.inside(r+i(o),o),position(r,o){const a=s(o);if(a===0)return t.position(r,o);const l=i(o),[c,h,u]=$l(t.position(r+l,o),l);return[c,h+n.lift*a,u-n.trail*a]},normal:(r,o)=>$l(t.normal(r+i(o),o),i(o))}}const sv=t=>t.texture==="spiky"||t.texture==="curly"||t.texture==="locs"?104:t.texture==="wavy"?80:64;function Ef(t,e,n,s){return Sl(t,rv(e,s),()=>Kr(t,n,sv(e)))}const Af=new WeakMap;let iv=1;function rv(t,e){if(wf(e))return t;let n=Af.get(t);return n||Af.set(t,n=iv++),`${n}:${e.swing}:${e.trail}:${e.lift}`}function $f(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 Ol(t,[e,n,s]){const i=Ct(t,[e,n,s]);return{x:i.x-t.center.x,y:i.y-t.center.y}}function ov(t,e,n,s=16){return Array.from({length:s+1},(i,r)=>{const o=r/s,a=1-o;return{x:a*a*t.x+2*a*o*e.x+o*o*n.x,y:a*a*t.y+2*a*o*e.y+o*o*n.y}})}function av(t,e,n,s,i){const r=t.ry,o=(e.length??1.8)*r,a=Ol(t,$l(s,Pn(i.swing))),l=Ol(t,[0,i.lift,-i.trail]),c=Math.hypot(a.x,a.y)||1,h=e.at==="high"||e.at==="low"||e.at==="top"?Ol(t,[.95,0,0]):{x:0},u=e.kind==="braid"?.15:.5,d={x:n.x+a.x/c*r*u+h.x*.9+l.x*.5,y:n.y+a.y/c*r*u*.6+l.y*.5},f={x:n.x+a.x/c*r*u*.6+h.x*1.3+l.x,y:n.y+o+l.y};return ov(n,d,f)}const Xr=t=>Math.max(1,t*.5),Pf=(t,e)=>Math.max(.8,Math.min(t*.4,.1*e.rx));function If(t,e,n,s,i,r){const{point:o,out:a}=$f(s.at),l=1+n.volume,c=Ct(e,[o[0]*l,o[1]*l,o[2]*l]),h=Xr(i),u=Pf(i,e);if(s.kind==="bun"){const g=s.size??.32,m=Ct(e,[o[0]*l+a[0]*g,o[1]*l+a[1]*g,o[2]*l+a[2]*g]);t.ellipse(m.x,m.y,g*e.rx,g*e.ry,e.angle,n.color,h);const w=g*e.rx*.55;t.line(Array.from({length:9},(v,k)=>{const b=-.4+k/8*Math.PI*1.3;return{x:m.x+Math.cos(b)*w,y:m.y+Math.sin(b)*w*.8}}),u);return}const d=av(e,s,c,a,r),f=(s.size??(s.kind==="braid"?.2:.34))*e.rx*2;if(s.kind==="ponytail")t.shape(zt(d,f,f*.15),n.color,h),t.line(d.slice(3,d.length-3),u);else{const m=d.slice(0,d.length-3);for(let k=0;k<7;k++){const b=m[Math.floor(k/7*(m.length-1))],T=m[Math.floor((k+1)/7*(m.length-1))],$=Math.atan2(T.y-b.y,T.x-b.x),M=Math.hypot(T.x-b.x,T.y-b.y),x=f*(1-k/(7*2.2)),S=(k%2===0?1:-1)*.35,E={x:(b.x+T.x)/2,y:(b.y+T.y)/2};t.ellipse(E.x,E.y,M*.62,x*.5,$+S,n.color,h*.8)}const w=m[m.length-1],v=d[d.length-1];t.shape(zt([w,v],f*.7,f*.2),n.color,h*.8)}const p=d[s.kind==="braid"?d.length-4:2];t.ellipse(p.x,p.y,f*.32,f*.22,e.angle,n.color,h)}function Of(t,e){return te(t,$f(e.at).out)<-.2}function lv(t){const e=(i,r,o=0,a=14)=>Array.from({length:a+1},(l,c)=>{const h=c/a;return[i[0]+(r[0]-i[0])*h+o*Math.sin(Math.PI*h),i[1]+(r[1]-i[1])*h]}),n=Pn(t.part??0),s=i=>wi(t,i)+.04;switch(t.strands){case"part":return[e([n,s(n)],[n,.97])];case"sweep":{const i=Math.sign(t.sweep||-1),r=[.9,.72,.55].map((o,a)=>{const l=n+i*(.6+a*.35);return e([n,o],[l,Math.max(s(l)+.05,o-.35)],.05*i)});return[e([n,s(n)],[n,.97]),...r]}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,r=[-2.6,-2,-1.4,1.4,2,2.6,3.05].map(o=>e([o,wi(t,o)<.9?.6:.9],[o,i],0));return t.part!==null&&r.push(e([n,s(n)],[n,.97])),r}default:return[]}}function cv(t,e,n,s,i){if(s.fill==="stipple"||s.hairline.front>1.5)return;const r=i.motion??hs,o=i.lineWidth*.45/n.rx,{far:a}=Ef(n,s,Tf(s,o,r),r);xl(e,n,()=>{for(const l of s.ties)Of(n,l)&&If(t,n,s,l,i.lineWidth,r);Cf(t,n,s,i.lineWidth,o,!1);for(const l of a)t.shape(l,s.color,Xr(i.lineWidth));yf(t,n,s,o,r,i.lineWidth,!1)},i.headOutline)}function Cl(t,e,n,s){if(n.hairline.front>1.5)return;const i=s.motion??hs,r=s.lineWidth*.45/e.rx,o=Tf(n,r,i),a=Pf(s.lineWidth,e);if(n.fill==="stipple"){for(let h=.97;h>-1;h-=.17)for(let u=-Math.PI;u<Math.PI;u+=.27){const d=Math.round(h*100)%2*.13;if(o.inside(u+d,h)<.02)continue;const f=xe(u+d,h);if(te(e,f)<.12)continue;const p=Ct(e,f);t.dot(p.x,p.y,a*.4)}return}const{near:l}=Ef(e,n,o,i),c=Xr(s.lineWidth);Cf(t,e,n,s.lineWidth,r,!0);for(const h of l)t.shape(h,n.color,c);yf(t,e,n,r,i,s.lineWidth,!0);for(const h of lv(n)){const u=h.map(([f,p])=>{const[g,m,w]=o.position(f,p);return[g*.985,m*.985,w*.985]}),d=h.map(([f,p])=>o.normal(f,p));for(const f of gf(e,u,d,.12))t.line(f,a)}for(const h of n.ties)Of(e,h)||If(t,e,n,h,s.lineWidth,i)}function Cf(t,e,n,s,i,r){for(const o of n.spikes??[]){const a=xe(Pn(o.around),Math.max(-1,Math.min(1,o.up)));if(te(e,a)>=0!==r)continue;const l=[Math.cos(Pn(o.around)),0,-Math.sin(Pn(o.around))],c=[a[1]*l[2],a[2]*l[0]-a[0]*l[2],-a[1]*l[0]],h=1+n.volume+i,u=Math.max(0,o.width),d=Math.max(0,o.length),f=[Ct(e,a.map(p=>p*(h+d)))];for(let p=0;p<8;p++){const g=p*Math.PI/4,m=a.map((w,v)=>w*h+u*(l[v]*Math.cos(g)+c[v]*Math.sin(g)));f.push(Ct(e,m))}t.shape(Ml(f),n.color,Xr(s))}}const _f=.35,_l=t=>({centre:[t*.98,-.02,-.08],out:[t,0,-.12]});function Hf(t,e,n,s,i){const{centre:r,out:o}=_l(n),a=te(e,o),l=Math.max(1,s.lineWidth*.55),c=s.skin==="none"?null:s.skin,h=e.ry*.27;if(!i){const m=Ct(e,[r[0]*1.06,r[1],r[2]]);t.ellipse(m.x,m.y,e.rx*.17,h,e.angle,c,l);return}const u=Ct(e,r),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,w)=>{const v=-Math.PI*.55+w/8*Math.PI*1.1,k=Math.cos(v)*d*.45*-n,b=Math.sin(v)*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 hv(t,e,n,s){xl(e,n,()=>{for(const i of[1,-1])te(n,_l(i).out)<_f&&Hf(t,n,i,s,!1)},s.headOutline)}function uv(t,e,n){for(const s of[1,-1])te(e,_l(s).out)>=_f&&Hf(t,e,s,n,!0)}const Hl={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 Rf(t,e){const n=typeof t=="string"?{style:t}:t,s=n.style?Hl[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 tn=t=>t*Math.PI/180,Gr=(t,e,n)=>{const s=Math.min(1,Math.max(0,(n-t)/(e-t)));return s*s*(3-2*s)},Lf={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}},dv=(t,e)=>{const n=Gr(tn(48),tn(100),Yr(e,0));return t.top[0]+(t.top[1]-t.top[0])*n},fv=t=>t==="sideburns"||t==="muttonChops";function Rl(t,e){const n=Lf[t];if(!n)return null;const s=tn(n.reach),i=r=>{const o=Yr(r,0);return n.shape==="point"?Math.exp(-((o/.42)**2)):n.shape==="square"?1-Gr(tn(45),tn(85),o):Math.cos(Math.min(o,Math.PI/2))**.7};return{top:Math.max(n.top[0],n.top[1])+.05,bottom:-1,inside(r,o){const a=Yr(r,0),l=dv(n,r);let c=Math.min(l-o,s-a);if(n.band>0&&(c=Math.min(c,o-(l-n.band))),fv(t)){const h=t==="muttonChops"?tn(70)-tn(22)*Gr(.08,-.6,o):tn(72);c=Math.min(c,a-h)}return c},position(r,o){const[a,l,c]=xe(r,o),h=1+e+n.volume,u=n.length*i(r)*Gr(-.45,-1,o);return[a*h,l*h-u,c*h+u*.25]},normal:(r,o)=>xe(r,o)}}function gv(t){const n=s=>s.map(([i,r])=>({x:i,y:-.24+r}));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 ki=t=>Math.max(1,t*.45);function pv(t,e,n,s){for(let i=.1;i>-1;i-=.13)for(let r=-Math.PI/1.7;r<Math.PI/1.7;r+=.2){const o=Math.round(i*100)%2*.1;if(n.inside(r+o,i)<.02)continue;const a=xe(r+o,i);if(te(e,a)<.15)continue;const l=Ct(e,a);t.dot(l.x,l.y,s)}}function mv(t,e,n,s,i){const r=s.beard==="stubble"?null:Rl(s.beard,i.lineWidth*.45/n.rx);if(!r)return;const{far:o}=Sl(n,s,()=>Kr(n,r));xl(e,n,()=>{for(const a of o)t.shape(a,s.color,ki(i.lineWidth))},i.headOutline)}function yv(t,e,n,s,i){if(n.beard==="none")return;const r=s.lineWidth*.45/e.rx;if(n.beard==="stubble"){pv(t,e,Rl("full",r),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}=xt(e,l,{x:0,y:-.6},s.face?.projection);h>-.05&&t.shape(c,n.color,ki(s.lineWidth)*.7);return}const o=Rl(n.beard,r);if(!o)return;const{near:a}=Sl(e,n,()=>Kr(e,o));for(const l of a)t.shape(l,n.color,ki(s.lineWidth));if(Lf[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}=xt(e,c,{x:0,y:-.42},s.face?.projection);u>-.05&&t.shape(h,s.skin==="none"?"#ffffff":s.skin,0)}}function bv(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}=xt(e,l,i,s.face?.projection);h>-.05&&t.line(c,Math.max(1,s.lineWidth*.32));return}const r=gv(n.moustache);if(!r)return;const{points:o,facing:a}=xt(e,r,i,s.face?.projection);if(!(a<=-.05)&&(t.shape(o,n.color,ki(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(xt(e,c,i,s.face?.projection).points,ki(s.lineWidth)*.8)}}const Ll={round:!0,square:!0,sunglasses:!0};function Ff(t){const n=(typeof t=="string"?{style:t}:t).style??"round";if(!(n in Ll))throw new Error(`glasses: unknown style '${n}'`);return{style:n}}const Nf=.34,Ee=.12,wv=.05;function kv(t,e){return Array.from({length:28},(s,i)=>{const r=Math.PI*2*i/28;if(t==="round")return{x:e+Math.cos(r)*.2,y:Ee+Math.sin(r)*.19};const o=Math.cos(r),a=Math.sin(r),l=t==="sunglasses"?.22:.21,c=t==="sunglasses"?.17:.16;return{x:e+Math.sign(o)*Math.abs(o)**.45*l,y:Ee-.01+Math.sign(a)*Math.abs(a)**.45*c}})}function vv(t,e,n,s){const i=Math.max(1,Math.min(s.lineWidth*.5,.11*e.rx)),r=[];for(const o of[1,-1]){const a=Nf*o,{points:l,facing:c}=xt(e,kv(n.style,a),{x:a,y:Ee},s.face?.projection);if(c<wv)continue;r.push(o),t.shape(l,n.style==="sunglasses"?"#1f2328":null,i);const h=[o*.97,Ee+.02,-.1];if(te(e,[o,0,0])>.15){const u=xt(e,[{x:a+o*.21,y:Ee+.02}],{x:a,y:Ee},s.face?.projection).points[0];t.line([u,Ct(e,h)],i*.9)}}if(r.length===2){const o=[{x:Nf-.2,y:Ee+.02},{x:0,y:Ee+.07},{x:-.14,y:Ee+.02}];t.line(xt(e,o,{x:0,y:Ee},s.face?.projection).points,i)}}const Ur={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 Wf(t){const e=typeof t=="string"?{style:t}:t,n=e.style??"cap",s=Ur[n];if(!s)throw new Error(`hat: unknown style '${n}'`);return{style:n,color:e.color??s.color}}const In=(t,e)=>t.brim[1]+(t.brim[0]-t.brim[1])*(1+Math.cos(e))/2;function Mv(t,e){return{top:1,bottom:Math.min(...t.brim)-.05,inside:(n,s)=>s-In(t,n),position(n,s){const[i,r,o]=xe(n,s),a=In(t,n),l=s>a?(r-a)*(t.height-1):0;return[i*e,r*e+l,o*e]},normal:(n,s)=>xe(n,s)}}function Sv(t,e,n){const i=(r,o,a)=>{const l=In(e,r)*n-a;return[Math.sin(r)*o,l,Math.cos(r)*o]};if(e.peak){const r=[],o=[];for(let a=0;a<=24;a++){const l=(-80+160*a/24)*(Math.PI/180),c=e.peak*Math.cos(l)**.6;r.push(Ct(t,[Math.sin(l)*(n+c*.25),In(e,l)*n-.07*Math.cos(l),Math.cos(l)*(n+c)])),o.push(Ct(t,i(l,n,0)))}return[...r,...o.reverse()]}return e.ring?Array.from({length:48},(r,o)=>Ct(t,i(Math.PI*2*o/48,n+e.ring,.07))):null}function xv(t){const e=s=>Array.from({length:13},(i,r)=>[s,In(t,s)+(.97-In(t,s))*r/12]),n=s=>Array.from({length:49},(i,r)=>{const o=-Math.PI+Math.PI*2*r/48;return[o,In(t,o)+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 Df(t,e,n,s){const i=Ur[n.style],o=1+s.lineWidth*.45/e.rx+Math.max(.05,Math.min(.3,s.hairVolume)+.04),a=Math.max(1,s.lineWidth*.5),l=Sv(e,i,o);l&&t.shape(l,n.color,a);const c=Mv(i,o),{near:h,far:u}=Kr(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 xv(i)){const p=f.map(([m,w])=>{const[v,k,b]=c.position(m,w);return[v*.99,k*.99,b*.99]}),g=f.map(([m,w])=>xe(m,w));for(const m of gf(e,p,g,.1))t.line(m,d)}if(i.detail==="seams"){const f=Ct(e,[0,o*1.01,0]);t.dot(f.x,f.y,a*.9)}}function Bf(t){const e=t.hair?Sf(t.hair):null;return{hair:e,facialHair:t.facialHair?Rf(t.facialHair,e?.color):null,glasses:t.glasses?Ff(t.glasses):null,hat:t.hat?Wf(t.hat):null,ears:t.ears??!1}}const zf=t=>!t.hair&&!t.facialHair&&!t.glasses&&!t.hat&&!t.ears,qf=t=>t.axes[2][2]<-.3,jf=t=>t.ears&&!t.hair?.coversEars;function Yf(t,e,n,s,i,r){if(zf(n))return;const o={...r,headOutline:r.face&&(r.face.shape==="angular"||r.face.projection==="volume")?af(s,r.face):void 0};n.hair&&cv(e,t,s,n.hair,{...o,motion:bi(i)}),n.facialHair&&mv(e,t,s,n.facialHair,o),jf(n)&&hv(e,t,s,o)}function Tv(t,e,n,s,i,r,o){if(zf(n)){o();return}const a=qf(s);jf(n)&&uv(e,s,r),n.hair&&!a&&!r.faceUnderHair&&Cl(e,s,n.hair,{...r,motion:bi(i)}),n.facialHair&&yv(e,s,n.facialHair,r,i.mouthWidth??1),o(),n.hair&&!a&&r.faceUnderHair&&Cl(e,s,n.hair,{...r,motion:bi(i)}),n.facialHair&&bv(e,s,n.facialHair,r),n.glasses&&vv(e,s,n.glasses,r),n.hat&&!a&&Df(e,s,n.hat,{lineWidth:r.lineWidth,hairVolume:n.hair?.volume??0})}function Kf(t,e,n,s,i,r){qf(s)&&(n.hair&&Cl(e,s,n.hair,{...r,motion:bi(i)}),n.hat&&Df(e,s,n.hat,{lineWidth:r.lineWidth,hairVolume:n.hair?.volume??0}))}const Xf=40,Ev=.215+.205,le=(t,e)=>{const n={};for(const s of["left","right"])for(const[i,r]of Object.entries(e))n[`${t}.${s}.${i}`]=r;return n},gt=(t,e)=>t[e]??lt[e]??0;function Vr(t,e,n=lt,s=1){const i=ci(t),r=e*Math.PI*2,o=Math.sin(r)*s,a=Math.cos(r)*s,l=(1+Math.cos(r*2*(i.bounces??1)))/2,c=i.crouch??0,h=i.shoulder??0,u=i.forearm??0,d={...lt,...n};d["leg.left.swing"]=i.swing*o+c*.6,d["leg.right.swing"]=-i.swing*o+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"]=gt(n,"leg.left.ankle")-(i.tiptoe??0),d["leg.right.ankle"]=gt(n,"leg.right.ankle")-(i.tiptoe??0);for(const[f,p]of[["left",-1],["right",1]])gt(n,`arm.${f}.spread`)>Xf||gt(n,`arm.${f}.swing`)>Xf||(d[`arm.${f}.swing`]=h+p*i.arm*o,d[`arm.${f}.elbow`]=gt(n,`arm.${f}.elbow`)+u+i.elbow*Math.max(0,p*o));return d.lean=gt(n,"lean")+i.lean*s,d.bend=gt(n,"bend")+(i.bend??0),d["head.nod"]=gt(n,"head.nod")-i.lean*.5*s+(i.headTilt??0),d.side=gt(n,"side")+(i.sway??0)*Math.sin(r),d.lift=gt(n,"lift")+(i.bounce??0)*s*l,d.stretch=gt(n,"stretch")*(1+(i.squash??0)*(l-.5)),d}function Jr(t,e,n=1,s=1){const i=ci(t);return 4*Ev*s*e*Math.sin(i.swing*n*Math.PI/180)}const ds=t=>gl[t],Zr={take:t=>[{after:140,pose:{stretch:.8,bend:10,lean:gt(t,"lean")-4,...le("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,...le("arm",{spread:150,bend:35,swing:0,elbow:0}),...le("leg",{swing:25,knee:60}),...ds("shocked")},easing:"ease-out-cubic"},{after:720,pose:{lift:.25,stretch:1.25,bend:-10,...le("arm",{spread:140})},easing:"ease-in-out"},{after:900,pose:{lift:0,stretch:.74,bend:12,...le("arm",{spread:70,bend:0}),...le("leg",{swing:30,knee:60})},easing:"ease-in-quad"},{after:1060,pose:{stretch:1.06,bend:-3,...le("arm",{spread:60}),"leg.left.swing":gt(t,"leg.left.swing"),"leg.right.swing":gt(t,"leg.right.swing"),"leg.left.knee":gt(t,"leg.left.knee"),"leg.right.knee":gt(t,"leg.right.knee")},easing:"ease-out"},{after:1260,pose:{stretch:gt(t,"stretch"),bend:gt(t,"bend"),...ds("surprised"),...le("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":gt(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":gt(t,"head.nod")-10,bend:gt(t,"bend")-10,lift:.05,stretch:1.18,...ds("shocked"),lookX:1,lookY:0},easing:"ease-out-cubic"},{after:1360,pose:{lift:0,stretch:.88,"head.nod":gt(t,"head.nod")-4,bend:gt(t,"bend")+4},easing:"ease-in-quad"},{after:1560,pose:{stretch:gt(t,"stretch"),"head.nod":gt(t,"head.nod"),bend:gt(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,...ds("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,...le("arm",{spread:75}),...le("leg",{swing:25,knee:50})},easing:"ease-in-quad"},{after:300,pose:{stretch:1.05,bend:-4,"arm.left.spread":gt(t,"arm.left.spread"),"arm.right.spread":gt(t,"arm.right.spread")},easing:"ease-out"},{after:460,pose:{lift:0,stretch:gt(t,"stretch"),bend:gt(t,"bend"),...le("leg",{swing:0,knee:0})},easing:"ease-in-out"}],tremble:t=>{const e=[{after:80,pose:{...ds("scared"),...le("arm",{swing:40,elbow:110,spread:14}),stretch:.94,bend:gt(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:gt(t,"side")+2.5*s,"head.tilt":gt(t,"head.tilt")-2*s}})}return e.push({after:755,pose:{side:gt(t,"side"),"head.tilt":gt(t,"head.tilt"),bend:gt(t,"bend")}}),e},deflate:t=>[{after:260,pose:{stretch:1.04,"head.nod":gt(t,"head.nod")-4,"brow.left":.3,"brow.right":.3},easing:"ease-in-out"},{after:900,pose:{...ds("sad"),bend:18,stretch:.92,lean:gt(t,"lean")+5,"head.nod":14,...le("arm",{spread:6,swing:0,elbow:4,bend:0})},easing:"ease-in-out"}]};function Gf(t,e){const n=kt(e.from??{}),s=e.speed??1;let i=n;return[{time:e.at,pose:n},...Zr[t](n).map(r=>(i={...i,...r.pose},{time:e.at+r.after*s,pose:i,act:!1,...r.easing?{easing:r.easing}:{}}))]}function Uf(t,e=lt){const n=t*Math.PI*2,s=Math.sin(n);return{...e,lean:(e.lean??0)+14,bend:(e.bend??0)+8,side:5*s,"head.nod":22,"arm.right.swing":38+22*s,"arm.right.spread":6,"arm.right.elbow":20+10*Math.max(0,-s),"arm.right.bend":-10,"arm.left.swing":52+22*s,"arm.left.spread":14,"arm.left.elbow":35+10*Math.max(0,s),"arm.left.bend":-20,"leg.left.swing":10,"leg.right.swing":-10,"leg.left.knee":8,"leg.right.knee":4,"leg.left.spread":8,"leg.right.spread":8}}function Vf(t,e=lt){const n=t*Math.PI*2,s=Math.sin(n),i=Math.cos(n);return{...e,lean:(e.lean??0)+4,side:2*s,"head.nod":6,"arm.right.swing":62,"arm.right.spread":18+16*s,"arm.right.elbow":48-18*Math.abs(s),"arm.right.bend":-30+8*i,"arm.left.swing":12,"arm.left.spread":14,"arm.left.elbow":12,"leg.left.spread":6,"leg.right.spread":6}}const Fl={sweeping:Uf,brushing:Vf};function Av(t,e,n=lt){const s=Fl[t];if(!s)throw new Error(`humanCyclePose: ${ft("cycle",t,Object.keys(Fl))}`);return s(e,n)}function Jf(t){const e=t.top??!0,n=t.length??.32,s=t.color??"#638c39",i=t.accent??"#87ae4e";if(typeof e!="boolean")throw new Error("leafOutfit: top must be a boolean");if(!Number.isFinite(n)||n<.2||n>.45)throw new Error("leafOutfit: length must be 0.2..0.45");if(typeof s!="string"||typeof i!="string")throw new Error("leafOutfit: color and accent must be strings");return{top:e,length:n,color:s,accent:i}}function Zf(t,e){const n=t.flatMap(i=>Array.from({length:8},(r,o)=>({x:i.x+Math.cos(o*Math.PI/4)*e,y:i.y+Math.sin(o*Math.PI/4)*e})));let s=Ml(n);for(let i=0;i<2;i++)s=s.flatMap((r,o)=>{const a=s[(o+1)%s.length];return[{x:r.x*.75+a.x*.25,y:r.y*.75+a.y*.25},{x:r.x*.25+a.x*.75,y:r.y*.25+a.y*.75}]});return s}const Qf=t=>t.flatMap(e=>[e.left,e.right]);function Nl(t,e={}){const{top:n,length:s}=Jf(e),i=t.bodyContours;if(!i?.spine)throw new Error("leafOutfit requires organic body contours");const r=i.spine.samples.filter(a=>a.at<=.3),o=["left","right"].flatMap(a=>i[`leg.${a}`]?.samples.filter(l=>l.at<=s)??[]);return{...n?{top:Zf(Qf(i.spine.samples.filter(a=>a.at>=.52&&a.at<=.91)),t.height*.01)}:{},skirt:Zf(Qf([...r,...o]),t.height*.012)}}function $v(t,e){t.beginPath(),t.moveTo(e[0].x,e[0].y);for(const n of e.slice(1))t.lineTo(n.x,n.y);t.closePath()}function Pv(t,e,n){const s=e.x-t.x,i=e.y-t.y,r=Math.hypot(s,i)||1,o=-i/r,a=s/r,l=[];for(const c of[1,-1])for(let h=0;h<=16;h++){const u=c===1?h/16:1-h/16,f=3*(1-u)*u*n*c;l.push({x:t.x+s*u+o*f,y:t.y+i*u+a*f})}return l}function tg(t,e,n,s,i,r){const o=e.lineWidth*.7;if(n.shape(s,i,o),n.look==="silhouette")return;t.save(),$v(t,s),t.clip();const a=Math.min(...s.map(f=>f.x)),l=Math.max(...s.map(f=>f.x)),c=Math.min(...s.map(f=>f.y)),h=Math.max(...s.map(f=>f.y)),u=l-a,d=h-c;for(let f=0;f<2;f++)for(let p=0;p<5;p++){const g={x:a+u*(p/4+(f?.07:-.04)),y:c+d*(f?.38:-.1)},m={x:g.x+u*.09,y:g.y+d*.78};n.shape(Pv(g,m,u*.13),(p+f)%2?i:r,o*.6),n.line([g,{x:g.x*.45+m.x*.55,y:g.y*.45+m.y*.55},m],o*.45);for(const w of[.32,.52,.7]){const v={x:g.x+(m.x-g.x)*w,y:g.y+(m.y-g.y)*w};n.line([{x:v.x-u*.045,y:v.y-d*.065},v,{x:v.x+u*.045,y:v.y-d*.05}],o*.3)}}t.restore()}function eg(t={}){const e=Jf(t),{color:n,accent:s}=e,i=r=>(o,a,l)=>{const c=Nl(a,e);r==="spine"&&c.top&&tg(o,a,l,c.top,n,s);const h=["spine","leg.left","leg.right"].reduce((u,d)=>a.parts[u].order>a.parts[d].order?u:d);r===h&&tg(o,a,l,c.skirt,n,s)};return{parts:{spine:{over:i("spine")},"leg.left":{over:i("leg.left")},"leg.right":{over:i("leg.right")}}}}const Iv={apron:"#d8b48a",labCoat:"#f4f6f8",hoodie:"#6b7280",cardigan:"#6b8e4e",overalls:"",sari:"#16a34a"},Wl=(t,e,n)=>t.slice(Math.floor((t.length-1)*e),Math.ceil((t.length-1)*n)+1),pt=(t,e,n)=>({x:t.x+(e.x-t.x)*n,y:t.y+(e.y-t.y)*n});function Ov(t){return t.parts["leg.left"].order>t.parts["leg.right"].order?"left":"right"}const ng=t=>Math.max(t.parts["leg.left"].order,t.parts["leg.right"].order)>t.parts.spine.order,ee=t=>t.bodyForward?.[2]??Math.cos(t.turn*Math.PI/2),Ce=t=>t.bodyForward?.[0]??Math.sin(t.turn*Math.PI/2);function sg(t,e,n){t.save(),t.beginPath(),t.moveTo(e[0].x,e[0].y);for(const s of e.slice(1))t.lineTo(s.x,s.y);t.closePath(),t.clip(),n(),t.restore()}function ig(t,e,n=0){const s=e*(t.length-1),i=Math.min(t.length-2,Math.floor(s)),r=t[i],o=t[i+1],a=pt(r,o,s-i),l=Math.hypot(o.x-r.x,o.y-r.y)||1;return{x:a.x+(o.y-r.y)/l*n,y:a.y-(o.x-r.x)/l*n}}function rg(t={}){if(t={...t},t.top!==void 0&&!["tshirt","shirt","blouse","dress"].includes(t.top))throw new Error(`basicOutfit: unknown top '${t.top}'`);if(t.trouserStyle!==void 0&&!["plain","jeans","cargo"].includes(t.trouserStyle))throw new Error(`basicOutfit: unknown trouser style '${t.trouserStyle}'`);const e=t.top,n=t.trouserStyle??"plain",s=t.collar??e==="shirt",i=t.shirt??"#e2493b",r=e==="dress"?i:t.trousers??"#24476b",o=t.sleeves??"short",a=e==="dress"?"skirt":t.bottom??"trousers",l=t.over==="labCoat",c=t.over==="hoodie",h=t.over==="cardigan",u=t.over==="overalls",d=t.over==="sari",f=t.overColor??(t.over&&t.over!=="overalls"?Iv[t.over]:r),p=t.shoes==="boots",g=t.shoeColor??"#3b2a1e",m=P=>P.lineWidth*.45,w=(P,C,z,K)=>{const N=C.parts[`leg.${K}`].points;if(a==="skirt"&&!u)return;const F=a==="shorts"&&!u,D=C.bodyContours?.[`leg.${K}`],X=D?vl(D,0,F?.5:1,C.height*.006):zt(F?Wl(N,0,.5):N,C.height*(F?.085:.08),C.height*(F?.07:.05));z.shape(X,r,m(C)),!(n==="plain"||ee(C)<.15)&&sg(P,X,()=>{const B=(Z,et=0)=>ig(N,Z,et*C.height);if(n==="jeans")z.line([B(.07,-.018),B(.17,-.02),B(.23,0),B(.17,.02),B(.07,.018)],m(C)*.65),z.line([B(.27,.013),...[.4,.55,.7,.85,.96].filter(Z=>!F||Z<.5).map(Z=>B(Z,.013))],m(C)*.5);else{const Z=[B(.25,-.024),B(.25,.024),B(.43,.024),B(.43,-.024)];z.shape(Z,r,m(C)*.65),z.line([B(.28,-.024),B(.32,0),B(.28,.024)],m(C)*.65);const et=B(.32);z.dot(et.x,et.y,m(C)*.8)}})},v=(P,C,z)=>{const K=P.parts[`leg.${z}`].points,N=Wl(K,.7,1);if(N.length<2)return;C.shape(zt(N,P.height*.075,P.height*.07),g,m(P));const F=N[0],D=N[1],X=D.x-F.x,B=D.y-F.y,Z=Math.hypot(X,B)||1,et=P.height*.04;C.line([{x:F.x-B/Z*et,y:F.y+X/Z*et},{x:F.x+B/Z*et,y:F.y-X/Z*et}],m(P)*.9)},k=P=>{const C=P.chains.spine,z=C[0],K=C[C.length-1],N={x:z.x-(K.x-z.x)*.25,y:z.y-(K.y-z.y)*.25};return{hip:z,top:K,below:N,line:[N,...P.parts.spine.points]}},b=P=>{if(P.bodyContours?.spine)return vl(P.bodyContours.spine,0,.97,P.height*(c?.014:.006));const C=c?1.14:1,z=Math.hypot(P.points["hip.left"].x-P.points["hip.right"].x,P.points["hip.left"].y-P.points["hip.right"].y),K=Math.max(P.height*.15*C,z+Math.max(P.height*.08,P.lineWidth*1.45)+m(P));return zt(k(P).line,K,P.height*.14*C)},T=(P,C)=>{const z=[b(C)],{top:K,hip:N}=k(C);h&&z.push(zt([K,pt(K,N,.5),pt(K,N,1.08)],C.height*.155,C.height*.15)),l&&z.push(zt([K,pt(K,N,.5),N],C.height*.14,C.height*.15));const F=Object.values(C.points),D=Math.min(...F.map(et=>et.x))-C.height,X=Math.min(...F.map(et=>et.y))-C.height,B=Math.max(...F.map(et=>et.x))+C.height,Z=Math.max(...F.map(et=>et.y))+C.height;for(const et of z){P.beginPath(),P.rect(D,X,B-D,Z-X),P.moveTo(et[0].x,et[0].y);for(const R of et.slice(1))P.lineTo(R.x,R.y);P.closePath(),P.clip("evenodd")}},$=(P,C)=>{const z=c?f:i;C.shape(b(P),z,m(P))},M=(P,C,z)=>{const K=ee(C);if(!e||K<.2||c)return;const{top:N,hip:F}=k(C),D=Ce(C)*C.height*.025,X=[N,F],B=(Z,et=0)=>ig(X,Z,D+et*C.height*K);sg(P,b(C),()=>{if(e==="shirt"){z.line([B(.12),B(.92)],m(C)*.65);for(const Z of[.24,.4,.56,.72,.88]){const et=B(Z,.008);z.dot(et.x,et.y,m(C)*.9)}}else if(e==="blouse"){z.line([B(.025,-.04),B(.24),B(.025,.04)],m(C)*.75);const Z=B(.31);z.dot(Z.x,Z.y,m(C))}else e==="dress"?z.line([B(.04,-.035),B(.17,-.028),B(.17,.028),B(.04,.035)],m(C)*.75):z.line([B(.025,-.035),B(.1,-.02),B(.12),B(.1,.02),B(.025,.035)],m(C)*.65)})},x=(P,C)=>{const z=ee(P),{top:K,hip:N}=k(P),F=P.height*.07,D={x:(K.x-N.x)*.16,y:(K.y-N.y)*.16};if(z>=0){C.shape([{x:K.x-F,y:K.y+D.y*.25},{x:K.x-F*.8+D.x,y:K.y+D.y},{x:K.x+D.x*1.2,y:K.y+D.y*1.35},{x:K.x+F*.8+D.x,y:K.y+D.y},{x:K.x+F,y:K.y+D.y*.25}],f,m(P));return}const X=pt(K,N,.42);C.shape([{x:K.x-F*.9,y:K.y},{x:K.x+F*.9,y:K.y},{x:X.x+F*.7,y:X.y},{x:X.x,y:X.y+P.height*.02},{x:X.x-F*.7,y:X.y}],f,m(P))},S=(P,C)=>{const z=ee(P);if(z<.2)return;const{top:K,hip:N}=k(P),F=Ce(P)*P.height*.03,D=P.height*.06*z,X=pt(K,N,.62),B=pt(K,N,.9);C.line([{x:X.x+F-D,y:X.y},{x:B.x+F-D*1.1,y:B.y}],m(P)*.7),C.line([{x:X.x+F+D,y:X.y},{x:B.x+F+D*1.1,y:B.y}],m(P)*.7);const Z=pt(K,N,.1);for(const et of[-1,1])C.line([{x:Z.x+F+et*D*.2,y:Z.y},{x:Z.x+F+et*D*.35,y:Z.y+P.height*.07}],m(P)*.6)},E=(P,C)=>{const{top:z,hip:K}=k(P),N=ee(P);if(C.shape(zt([z,pt(z,K,.5),pt(z,K,1.08)],P.height*.155,P.height*.15),f,m(P)),N<.2)return;const F=Ce(P)*P.height*.03,D=P.height*.02*N,X=pt(z,K,.12),B=pt(z,K,1.05);C.shape([{x:X.x+F-D,y:X.y},{x:X.x+F+D,y:X.y},{x:B.x+F+D*1.3,y:B.y},{x:B.x+F-D*1.3,y:B.y}],i,m(P)*.7);for(const Z of[.35,.55,.75]){const et=pt(z,K,Z);C.dot(et.x+F+D*1.6,et.y,m(P)*1.2)}},I=(P,C)=>{const z=ee(P),{top:K,hip:N}=k(P),F=Ce(P)*P.height*.04,D=pt(N,K,.12),X=pt(N,K,.74);if(z<.15){if(z<-.3){const R=P.points["shoulder.left"],U=P.points["shoulder.right"];C.line([R,{x:D.x+P.height*.03,y:D.y}],m(P)*.8),C.line([U,{x:D.x-P.height*.03,y:D.y}],m(P)*.8)}return}const B=P.height*.07*z;C.shape([{x:X.x+F-B*.75,y:X.y},{x:X.x+F+B*.75,y:X.y},{x:D.x+F+B*1.1,y:D.y},{x:D.x+F-B*1.1,y:D.y}],r,m(P));for(const R of["left","right"]){const U=P.points[`shoulder.${R}`],nt={x:X.x+F+(U.x>X.x+F?1:-1)*B*.55,y:X.y};C.line([nt,{x:U.x+(nt.x-U.x)*.15,y:U.y+(nt.y-U.y)*.15}],m(P)*1.6)}const Z=pt(X,D,.3),et=B*.4;C.line([{x:Z.x+F-et,y:Z.y},{x:Z.x+F-et,y:Z.y+et*1.4},{x:Z.x+F+et,y:Z.y+et*1.4},{x:Z.x+F+et,y:Z.y}],m(P)*.6)},A=(P,C)=>{const{hip:z,top:K}=k(P),N=pt(z,K,.2),F=[P.points["ankle.left"],P.points["ankle.right"]],D=pt(z,{x:(F[0].x+F[1].x)/2,y:(F[0].y+F[1].y)/2},.98),X=P.height*.075,B=Math.max(P.height*.12,Math.abs(F[0].x-F[1].x)/2+P.height*.07),Z=D.x-N.x,et=D.y-N.y,R=Math.hypot(Z,et)||1,U={x:-et/R,y:Z/R};if(C.shape([{x:N.x+U.x*X,y:N.y+U.y*X},{x:D.x+U.x*B,y:D.y+U.y*B},{x:D.x-U.x*B,y:D.y-U.y*B},{x:N.x-U.x*X,y:N.y-U.y*X}],f,m(P)),ee(P)>.2){const at=Ce(P)*P.height*.03;for(const rt of[-.35,0,.35]){const ct=X*.5*rt,it=B*.45*rt;C.line([{x:N.x+at+U.x*ct,y:N.y+U.y*ct+P.height*.02},{x:D.x+at+U.x*it,y:D.y+U.y*it}],m(P)*.5)}}},O=(P,C)=>{const z=ee(P),{top:K,hip:N}=k(P),F=Ce(P),D=F>=0?"left":"right",X=D==="left"?"right":"left",B=P.points[`shoulder.${D}`],Z=P.height*.035;if(z<.15){const U=pt(K,N,.9);C.shape(zt([B,{x:U.x+(B.x-K.x)*.5,y:U.y}],Z*2.2,Z*2.6),f,m(P));return}const et={x:N.x+(P.points[`hip.${X}`].x-N.x)*1.2,y:pt(N,K,.08).y};C.shape(zt([et,pt(et,B,.5),B],Z*2.4,Z*2),f,m(P));const R={x:B.x-(N.x-B.x)*.05-F*P.height*.03,y:B.y+P.height*.16};C.shape(zt([B,R],Z*2,Z*1.6),f,m(P))},H=(P,C)=>{if(P.bodyContours){C.shape(Nl(P,{top:!1,length:.45}).skirt,r,m(P));return}const{hip:z,top:K}=k(P),N=pt(z,K,.18),F=[P.points["knee.left"],P.points["knee.right"]],D=pt(z,{x:(F[0].x+F[1].x)/2,y:(F[0].y+F[1].y)/2},1.05),X=P.height*.075,B=Math.max(P.height*.13,Math.abs(F[0].x-F[1].x)/2+P.height*.08),Z=D.x-N.x,et=D.y-N.y,R=Math.hypot(Z,et)||1,U={x:-et/R,y:Z/R};C.shape([{x:N.x+U.x*X,y:N.y+U.y*X},{x:D.x+U.x*B,y:D.y+U.y*B},{x:D.x-U.x*B,y:D.y-U.y*B},{x:N.x-U.x*X,y:N.y-U.y*X}],r,m(P))},W=(P,C)=>{const z=ee(P);if(z<.2)return;const{top:K,hip:N}=k(P),F={x:(N.x-K.x)*.12,y:(N.y-K.y)*.12},D=P.height*.045*z;for(const X of[-1,1])C.shape([{x:K.x+X*D*.2,y:K.y+F.y*.1},{x:K.x+X*D*1.3,y:K.y-F.y*.1},{x:K.x+X*D*.6+F.x,y:K.y+F.y}],i,m(P)*.8)},j=(P,C,z)=>{const K=ee(P);if(K<.25)return;const{top:N,hip:F}=k(P),D=Ce(P)*P.height*.03,X=R=>({x:pt(N,F,R).x+D,y:pt(N,F,R).y}),B=P.height*.022*K,Z=X(.08),et=X(.62);C.shape([{x:Z.x-B,y:Z.y-B},{x:Z.x+B,y:Z.y-B},{x:Z.x+B*.6,y:Z.y+B},{x:Z.x-B*.6,y:Z.y+B}],z,m(P)*.7),C.shape([{x:Z.x-B*.6,y:Z.y+B},{x:Z.x+B*.6,y:Z.y+B},{x:et.x+B*1.4,y:et.y-B*2},et,{x:et.x-B*1.4,y:et.y-B*2}],z,m(P)*.7)},J=(P,C)=>{const z=ee(P),{top:K,hip:N}=k(P),F=pt(N,K,.72),D=[P.points["knee.left"],P.points["knee.right"]],X=pt(N,{x:(D[0].x+D[1].x)/2,y:(D[0].y+D[1].y)/2},.9),B=Ce(P)*P.height*.04;if(z<.15){const R=pt(N,K,.2);z<-.3&&C.line([{x:R.x-P.height*.05,y:R.y},{x:R.x+P.height*.05,y:R.y}],m(P));return}const Z=P.height*.075*z,et=pt(N,K,.2);C.shape([{x:F.x+B-Z*.7,y:F.y},{x:F.x+B+Z*.7,y:F.y},{x:et.x+B+Z,y:et.y},{x:X.x+B+Z*1.15,y:X.y},{x:X.x+B-Z*1.15,y:X.y},{x:et.x+B-Z,y:et.y}],f,m(P)),C.line([{x:F.x+B-Z*.6,y:F.y},{x:K.x-Z*.2,y:K.y},{x:F.x+B+Z*.6,y:F.y}],m(P)*.8)},tt=(P,C,z)=>{const{top:K,hip:N}=k(P),F=[P.points["knee.left"],P.points["knee.right"]],D=pt(N,{x:(F[0].x+F[1].x)/2,y:(F[0].y+F[1].y)/2},.95);z?C.shape(zt([pt(K,N,.8),N,D],P.height*.145,P.height*.17),f,m(P)):C.shape(zt([K,pt(K,N,.5),N],P.height*.14,P.height*.15),f,m(P));const X=ee(P);if(X>.2){const B=Ce(P)*P.height*.03,[Z,et]=z?[N,D]:[K,N];if(C.line([{x:Z.x+B,y:Z.y},{x:et.x+B,y:et.y}],m(P)*.8),!z){const R=pt(K,N,.35),U=P.height*.025*X;C.shape([{x:R.x+B-U*2.4,y:R.y},{x:R.x+B-U*.6,y:R.y},{x:R.x+B-U*.6,y:R.y+U*1.6},{x:R.x+B-U*2.4,y:R.y+U*1.6}],f,m(P)*.6)}}},V=(P,C,z,K,N)=>{const F=P.bodyContours?.[`arm.${z}`];if(F){const Q=vl(F,0,N,P.height*.006);C.shape(Q,K,0);const ot=b(P);for(let ht=0;ht<Q.length;ht++){const dt=Q[ht],bt=Q[(ht+1)%Q.length];nf({x:(dt.x+bt.x)/2,y:(dt.y+bt.y)/2},ot)||C.line([dt,bt],m(P))}return}const D=P.parts[`arm.${z}`].points,X=D[0],B=P.chains.spine[P.chains.spine.length-1],et=[{x:X.x+(B.x-X.x)*.45,y:X.y+(B.y-X.y)*.45},...Wl(D,0,N)],R=zt(et,P.height*.085,P.height*(N>.6?.045:.06)),U=et.length,nt=R.slice(0,U),at=R.slice(U).reverse();C.shape(R,K,0);const rt=Q=>Math.hypot(Q[1].x-B.x,Q[1].y-B.y),[ct,it]=rt(nt)>rt(at)?[nt,at]:[at,nt];C.line(ct.slice(1),m(P)),C.line(it.slice(Math.ceil(U*.45)),m(P)),C.line([nt[U-1],at[U-1]],m(P))},L=l||c||h,q=L?f:i,G=L||o==="long"?.95:.45,_=L||o!=="none",Y=(P,C)=>{a==="skirt"&&!u&&!d&&H(P,C),d&&A(P,C),l&&tt(P,C,!0),t.over==="apron"&&J(P,C)},st=P=>(C,z,K)=>{C.save(),T(C,z),w(C,z,K,P),p&&v(z,K,P),C.restore(),Ov(z)===P&&ng(z)&&Y(z,K)};return{parts:{"leg.left":{clip:T,over:st("left")},"leg.right":{clip:T,over:st("right")},spine:{over:(P,C,z)=>{c&&ee(C)>=0&&x(C,z),$(C,z),M(P,C,z),s&&!c&&W(C,z),t.tie&&!c&&j(C,z,t.tie),l&&tt(C,z,!1),h&&E(C,z),c&&(ee(C)<0&&x(C,z),S(C,z)),u&&I(C,z),d&&O(C,z),ng(C)||Y(C,z)}},"arm.left":{over:_?(P,C,z)=>V(C,z,"left",q,G):void 0},"arm.right":{over:_?(P,C,z)=>V(C,z,"right",q,G):void 0}}}}const Dl={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"},cane:{color:"#6b4630",hands:"one"},parcel:{color:"#c9a06a",hands:"both"}};function og(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,r=Dl[i];if(!r)throw new Error(`holding: unknown item '${i}'`);if(n==="both"&&r.hands==="one")throw new Error(`holding: a ${i} is held in one hand ('left' or 'right'), not 'both'`);if(n!=="both"&&r.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)??r.color}}return e}function Qr(t,e){const n=t.chains[`arm.${e}`],s=n[n.length-1],i=n[n.length-2],r=Math.hypot(s.x-i.x,s.y-i.y)||1,o={x:(s.x-i.x)/r,y:(s.y-i.y)/r},a=t.lineWidth*.5;return{point:{x:s.x+o.x*a,y:s.y+o.y*a},along:o,depth:t.parts[`arm.${e}`]?.depth??0}}function fs(t,e,n,s=0){const i=Math.cos(s),r=Math.sin(s);return[[-e/2,-n/2],[e/2,-n/2],[e/2,n/2],[-e/2,n/2]].map(([o,a])=>({x:t.x+o*i-a*r,y:t.y+o*r+a*i}))}const gs=(t,e,n,s,i=12)=>Array.from({length:i+1},(r,o)=>{const a=n+(s-n)*o/i;return{x:t.x+Math.cos(a)*e,y:t.y+Math.sin(a)*e}});function Bl(t,e,n,s,i,r=1,o){const{point:a,along:l}=n,c=s/300;switch(e.item){case"mug":{const h=fs({x:a.x,y:a.y-4*c},20*c,24*c);t.line(gs({x:a.x+10*c*Math.sign(r||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(r||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(fs(a,13*c,24*c,h),e.color,i),t.shape(fs(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(gs({x:a.x,y:a.y+6*c},7*c,Math.PI,Math.PI*2),i),t.shape(fs({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=(o??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(gs({x:a.x+5*c,y:a.y+10*c},5*c,Math.PI,0,8),i);const f=[...gs({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(...gs({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(r||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"cane":{const h=Math.min(.56*s,Math.max(.3*s,-a.y)),u=.12*Math.sign(r||1),d={x:u/Math.hypot(u,1),y:1/Math.hypot(u,1)},f={x:a.x+d.x*h,y:a.y+d.y*h},p=gs({x:a.x+7*c*Math.sign(r||1),y:a.y-2*c},7*c,Math.PI,Math.PI*2,8).map(g=>({x:a.x+(g.x-a.x)*Math.sign(r||1),y:g.y}));t.line([...p,{x:a.x,y:a.y+2*c},f],i*1.2),t.shape(fs({x:f.x,y:f.y-3*c},9*c,7*c),e.color,0);return}case"parcel":{const h={x:a.x,y:a.y-6*c};t.shape(fs(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 zl=(t,e)=>(t[`held.${e}`]??1)>=.5,ag=t=>Math.sin(t*Math.PI/2);function lg(t){const e=r=>Math.max(1,r.lineWidth*.45),n=r=>(o,a,l,c,h)=>{const u=t[r];u&&zl(h??{},r)&&Bl(l,u,Qr(a,r),a.height,e(a),ag(a.turn),a.head.center.y-a.head.ry)},s=(r,o,a,l,c)=>{const h=t.both;if(!h||!zl(c??{},"both"))return;const u=Qr(o,"left"),d=Qr(o,"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};Bl(a,h,f,o.height,e(o),ag(o.turn),o.head.center.y-o.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 r=o=>(a,l,c,h,u)=>{const d=o==="left"?"right":"left";(o==="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 o of["left","right"])i.parts[`arm.${o}`]={...i.parts[`arm.${o}`],over:Cv(i.parts[`arm.${o}`]?.over,r(o))}}return i}function Cv(t,e){return t?(n,s,i,r,o)=>{t(n,s,i,r,o),e(n,s,i,r,o)}:e}function ql(t,e){const n=(i,r)=>i&&r?(o,a,l,c,h)=>{i(o,a,l,c,h),r(o,a,l,c,h)}:i??r,s={};for(const i of new Set([...Object.keys(t.parts??{}),...Object.keys(e.parts??{})])){const r=t.parts?.[i],o=e.parts?.[i];s[i]={under:n(r?.under,o?.under),clip:n(r?.clip,o?.clip),over:n(r?.over,o?.over)}}return{behind:n(t.behind,e.behind),parts:s,front:n(t.front,e.front)}}function ps(t={}){if(t.build&&!(t.build in Hr))throw new Error(`character: unknown build '${t.build}'`);const e=t.build?Hr[t.build]:{},n=(t.proportions??"bold")==="bold",s=t.figure??"fluid",i=t.look??"clean",r=t.height??300,o=s==="stick",a=s==="organic",l=t.shoulderWidth??e.shoulderWidth??(a?.07:.06),c=t.hipWidth??e.hipWidth??(a?.045:.022),h=t.lineWidth??r*(a?.005:n?.045:.022),u=t.ink??(a?"#53362d":i==="pencil"?"#2f2f33":"#1e293b"),d=t.skin??(a?"#f1bf98":i==="pencil"?"none":"#ffffff"),f=a?Zd(t.body??{},{skin:d,ink:u,lineWidth:h,shoulderWidth:l,hipWidth:c}):void 0;if(t.leafOutfit&&!a)throw new Error("character: leafOutfit requires figure: 'organic'");const p=t.outfit?rg(t.outfit):null,g=t.holding?og(t.holding):{};let m=p?ql(p,t.layers??{}):t.layers??{};return t.leafOutfit&&(m=ql(eg(t.leafOutfit),m)),Object.keys(g).length>0&&(m=ql(m,lg(g))),{plan:t.plan??fl({headSize:t.headSize??e.headSize??(a?.27:n?.3:.24),shoulderWidth:o?0:l,hipWidth:o?0:c,legLength:t.legLength??e.legLength??1,armLength:t.armLength??e.armLength??1,feet:t.feet??e.feet}),figure:s,...f?{body:f}:{},look:i,height:r,lineWidth:f?.outline.width??h,ink:f?.outline.color??u,skin:f?.fill??d,seed:t.seed??1,pencil:a?{construction:!1,...t.pencil}:t.pencil??{},layers:m,holding:g,contact:t.contact??"ground",hands:t.hands??(a?"cartoon":"dot"),handStyle:t.handStyle??(a?"natural":"glove"),handSize:t.handSize??(a?.073:t.handStyle==="natural"?.14:.17),head:Bf(t),face:{...a?{style:"anime",projection:"volume",iris:"#66422e",nose:!0}:{},...t.face,teeth:t.face?.teeth??!1,tongue:t.face?.tongue??!1}}}function _v(t,e,n,s){const{point:i,facing:r}=rs(t,[e,n,s]);return{point:i,facing:r}}const jl=t=>t.rest[1]<-.5,Hv=.3;function Rv(t,e,n){return t.figure==="stick"?jl(e)?n.slice(0,3):n:jl(e)&&n.length>=3?Mn(n[0],n[1],n[2],Hv):n.length===3?Mn(n[0],n[1],n[2],1):n}function vi(t,e){const n=t.plan.id==="human"?{...lt,...e}:e;return to(t,n,ml(t.plan,n,{height:t.height,contact:t.contact}))}function to(t,e,n){const s={},i={},r={},o=.01*t.height;t.plan.chains.forEach(f=>{const p=n.chains[f.id];s[f.id]=p.points;const g=p.depths.reduce((k,b)=>k+b,0)/p.depths.length,m=f.parent?n.chains[f.parent]:void 0,w=m?m.depths[f.at??m.depths.length-1]:n.hipDepth,v=g-w;r[f.id]=Math.abs(v)<o?0:v,i[f.id]={points:Rv(t,f,p.points),depth:g,order:0}}),i.head={points:[n.head.center],depth:n.head.depth,order:0},r.head=0;const a=[...t.plan.chains.map(f=>f.id),"head"],l=f=>t.body&&f.startsWith("arm.")&&r[f]>=0?1:0,c=[...a].sort((f,p)=>l(f)-l(p)||r[f]-r[p]||a.indexOf(f)-a.indexOf(p));c.forEach((f,p)=>{i[f].order=p});const h={hip:n.hip};for(const[f,[p,g]]of Object.entries(t.plan.landmarks??{})){const m=n.chains[p]?.points;m&&(h[f]=m[Math.min(g,m.length-1)])}const u={};for(const[f,p]of Object.entries(h))u[f]=p.y>=n.groundY-.01*t.height;const d={height:t.height,lineWidth:t.lineWidth,turn:e.turn??0,...n.bodyForward?{bodyForward:n.bodyForward}:{},points:h,chains:s,parts:i,head:n.head,groundY:n.groundY,grounded:u};return t.body&&(d.bodyContours=ef(t.body,d,t.plan)),{skeleton:n,joints:d,order:c}}function fe(t,e){return vi(t,e).joints}function cg(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})),r=Array.from({length:13},(l,c)=>({x:-.95+1.9*c/12,y:.12})),o=xt(s,i,{x:0,y:0});o.facing>0&&t.guide(o.points),t.guide(xt(s,r,{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 hg(t,e,n,s,i,r){const o=n.lineWidth;if(n.body&&n.skin==="none"&&(e=oi(t,e)),i==="head"){const{head:f}=s;let p;const g=()=>p??=af(f,n.face),m=n.skin==="none"?null:n.skin;n.face.projection==="volume"||n.face.shape==="angular"?e.shape(g(),m,o):e.ellipse(f.center.x,f.center.y,f.rx,f.ry,f.angle,m,o),n.body&&n.skin!=="none"&&e.look==="clean"&&ad(t,g(),f.center,n.body.shading),Tv(t,e,n.head,f,r,{lineWidth:o,skin:n.skin,face:n.face,faceUnderHair:!!n.body},()=>{e.look!=="silhouette"&&(t.save(),n.body&&(t.beginPath(),g().forEach((w,v)=>v?t.lineTo(w.x,w.y):t.moveTo(w.x,w.y)),t.closePath(),t.clip()),Y5(e,f,r,o,{...n.face,skin:n.skin==="none"?"#ffffff":n.skin},t),t.restore())});return}const a=n.plan.chains.find(f=>f.id===i),l=s.chains[i],c=s.parts[i].points;if(n.body&&rf(t,e,n.body,s,i)){if(i.startsWith("leg.")&&rf(t,e,n.body,s,i.replace("leg.","foot.")),i.startsWith("arm."))if(n.hands==="cartoon")dg(t,e,n,l,i.endsWith(".left")?"left":"right",r);else{const f=l.at(-1);e.ellipse(f.x,f.y,n.height*.014,n.height*.014,0,n.skin==="none"?null:n.skin,o)}return}if(n.figure==="stick"){if(i==="neck")return;const f=i==="spine"?[...l,...s.chains.neck?.slice(1)??[]]:c;e.line(f,o);return}const h=(f,p)=>[a.bones[f].width[0]*o,a.bones[p].width[1]*o];if(jl(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]*o,a.bones[2].width[1]*o);else if(n.hands==="cartoon"&&i.startsWith("arm."))dg(t,e,n,l,i.endsWith(".left")?"left":"right",r);else{const g=l[l.length-1];e.dot(g.x,g.y,o*.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],o*1.3,o*1.3);const[g,m]=h(0,a.bones.length-1);e.limb(c,g,m);const w=s.points["shoulder.left"],v=s.points["shoulder.right"];w&&v&&Math.hypot(w.x-v.x,w.y-v.y)>.5&&e.limb(Mn(w,l[l.length-1],v,1,10),o*1.15,o*1.15);return}const[u,d]=h(0,a.bones.length-1);e.limb(c,u,d)}function ug(t,e){const n=`hand.${e}.`,s={};for(const[o,a]of Object.entries(t))o.startsWith(n)&&(s[o.slice(n.length)]=a);const i=t.turn??0,r=e==="right"?1-i:1+i;return{...Ot,...s,turn:r+(s.turn??0)}}function dg(t,e,n,s,i,r){const o=s[s.length-1],a=s[s.length-2],l=Math.atan2(o.x-a.x,-(o.y-a.y))*180/Math.PI;Sr(t,o,ug(r,i),{size:n.handSize*n.height,side:i,angle:l,pen:e,skin:n.skin==="none"&&!n.body?"#ffffff":n.skin,fingers:n.handStyle==="natural"?5:4,plump:n.handStyle==="natural"?1.15:1.6,lineWidth:n.lineWidth*(n.body?.65:.3),connected:!!n.body,shading:n.body?.shading,nails:n.body?!1:void 0})}function fg(t,e,n,s=0){const i=e.plan.id==="human"?{...lt,...n}:n;Yl(t,e,i,vi(e,i),s)}function eo(t,e){const n=e/t.height;return{...t,height:e,lineWidth:t.lineWidth*n}}function Lv(t,e,n,s){const i=t.plan.id==="human"?{...lt,...e}:e,r=Wr(t.plan,i,{height:s.height,contact:t.contact},n);return to(eo(t,r.height),i,r).joints}function Fv(t,e,n,s,i){const r=e.plan.id==="human"?{...lt,...n}:n,o=Wr(e.plan,r,{height:i.height,contact:e.contact},s),a=eo(e,o.height);Yl(t,a,r,to(a,r,o),i.time??0)}function gg(t,e,n,s){const i=t.plan.id==="human"?{...lt,...e}:e,r=Wr(t.plan,i,{height:s.height,contact:t.contact},n),o=eo(t,r.height),{joints:a,order:l}=to(o,i,r),c=r.height/s.height,h=l.map(p=>(a.parts[p]?.depth??0)/c),u=l.filter(p=>p==="spine"||p.startsWith("leg.")),d=Math.max(...u.map(p=>a.parts[p].depth/c)),f=Math.max(...u.map(p=>a.parts[p].order));return l.map((p,g)=>({part:p,depth:h[g],...o.body?{sortDepth:p.startsWith("arm.")&&g>f?Math.max(h[g],d):h[g]}:{},draw(m,w=0){const v=ri(m,{look:o.look,ink:o.ink,lineWidth:o.lineWidth,seed:ne(`${o.seed}:${p}`),time:w,pencil:o.pencil}),k=T=>{T&&(m.save(),T(m,a,v,w,i),m.restore())};m.save(),m.lineCap="round",m.lineJoin="round",g===0&&(o.look==="pencil"&&o.pencil.construction!==!1&&cg(v,o,a),k(o.layers.behind),Yf(m,o.body&&o.skin==="none"?oi(m,v):v,o.head,a.head,i,{lineWidth:o.lineWidth,skin:o.skin,face:o.face}));const b=o.layers.parts?.[p];k(b?.under),m.save(),b?.clip?.(m,a,v,w,i),hg(m,v,o,a,p,i),m.restore(),k(b?.over),p==="head"&&Kf(m,v,o.head,a.head,i,{lineWidth:o.lineWidth,skin:o.skin,face:o.face}),g===l.length-1&&k(o.layers.front),m.restore()}}))}function Yl(t,e,n,s,i,r){const{joints:o}=s,a=r?s.order.filter(h=>r.has(h)):s.order,l=ri(t,{look:e.look,ink:e.ink,lineWidth:e.lineWidth,seed:e.seed,time:i,pencil:e.pencil}),c=h=>{h&&(t.save(),h(t,o,l,i,n),t.restore())};t.save(),t.lineCap="round",t.lineJoin="round",!r&&e.look==="pencil"&&e.pencil.construction!==!1&&cg(l,e,o),r||c(e.layers.behind),Yf(t,e.body&&e.skin==="none"?oi(t,l):l,e.head,o.head,n,{lineWidth:e.lineWidth,skin:e.skin,face:e.face});for(const h of a){const u=e.layers.parts?.[h];c(u?.under),t.save(),u?.clip?.(t,o,l,i,n),hg(t,l,e,o,h,n),t.restore(),c(u?.over)}Kf(t,l,e.head,o.head,n,{lineWidth:e.lineWidth,skin:e.skin}),r||c(e.layers.front),t.restore()}function Nv(t,e,n,s){const i=e.plan.id==="human"?{...lt,...n}:n,r=vi(e,i).joints.head.rx,o=eo(e,e.height*s.radius/Math.max(1e-6,r)),a=vi(o,i);t.save(),t.translate(s.x-a.joints.head.center.x,s.y-a.joints.head.center.y),Yl(t,o,i,a,s.time??0,new Set(["head"])),t.restore()}function Kl(t,e,n){const s={...t};for(const[i,r]of Object.entries(e)){const o=t[i]??r;s[i]=o+(r-o)*n}return s}function _e(t,e,n,s){const i=t.plan.id==="human"?{...lt,...e}:e;let r;if(Array.isArray(s))r=s;else{const{skeleton:o}=vi(t,i),a=ml(t.plan,{...i,roll:0},{height:t.height,contact:"none"}),l=(i.roll??0)*Math.PI/180,c=s.x-o.hip.x,h=s.y-o.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??o.chains[n].depths[o.chains[n].depths.length-1],g=Math.cos(f),m=Math.sin(f);r=[u*g-p*m,-d,u*m+p*g]}return gi(t.plan,i,n,r,{height:t.height})}const pg=new Set(["walk","walking","gait"]);function no(t,e=lt,n){let s={...e};for(const[r,o]of Object.entries(t))typeof o=="number"&&!pg.has(r)&&(s[r]=o);const i=Math.max(0,Math.min(1,typeof t.walking=="number"?t.walking:0));if(i>0){const r=typeof t.gait=="string"?t.gait:void 0,o=r?n?.[r]??r:void 0,a=Vr(o,typeof t.walk=="number"?t.walk:0,s);s=Object.fromEntries(Object.keys({...s,...a}).map(l=>[l,(s[l]??0)+((a[l]??0)-(s[l]??0))*i]))}return s}function Wv(t){const{character:e}=t,n=e.height*.8,s=e.height,i=e.plan.id==="human"?lt:{};return{type:"custom",x:t.x-n/2,y:t.y-s,width:n,height:s,props:{...i,...t.pose},character:e,...t.gaits?{gaits:t.gaits}:{},draw(r,o,a){r.translate(n/2,s),fg(r,e,no(o.props??{},i,t.gaits),a)}}}function mg(t,e,n){const s=r=>({x:r.x+e,y:r.y+n}),i=r=>Object.fromEntries(Object.entries(r).map(([o,a])=>[o,a.map(s)]));return{...t,...t.bodyContours?{bodyContours:Object.fromEntries(Object.entries(t.bodyContours).map(([r,o])=>[r,{...o,outline:o.outline.map(s),samples:o.samples.map(a=>({...a,center:s(a.center),left:s(a.left),right:s(a.right)}))}]))}:{},points:Object.fromEntries(Object.entries(t.points).map(([r,o])=>[r,s(o)])),chains:i(t.chains),parts:Object.fromEntries(Object.entries(t.parts).map(([r,o])=>[r,{...o,points:o.points.map(s)}])),head:{...t.head,center:s(t.head.center)},groundY:t.groundY+n}}function Dv(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 r=0,o=0;for(const[c,h]of e.state?.values.get(n)??[])c==="x"||c==="motionPathX"?r=typeof h=="number"?h:r:c==="y"||c==="motionPathY"?o=typeof h=="number"?h:o:(typeof h=="number"||pg.has(c))&&(i[c]=h);const a=no(i,s.plan.id==="human"?lt:{},t.gaits),l=fe(s,a);return{pose:a,joints:mg(l,t.x+r+t.width/2,t.y+o+t.height)}}function Xl(t,e=lt){const n=[];return t.forEach((s,i)=>{const r=i===0?e:n[i-1],o=typeof s.pose=="string"?be[s.pose]:void 0;n.push(o?{...o,turn:r.turn??0}:{...r,...s.pose})}),n}function Bv(t,e,n=lt){const s=Xl(e,n);return Object.keys(n).filter(r=>s.some(o=>(o[r]??n[r])!==n[r])).map(r=>({id:`${t}-${r}`,target:t,property:r,keyframes:e.map((o,a)=>({time:o.time,value:s[a][r]??n[r],...o.easing?{easing:o.easing}:{}}))}))}const so=(t,e)=>[t[0]+e[0],t[1]+e[1],t[2]+e[2]],Ae=(t,e)=>[t[0]-e[0],t[1]-e[1],t[2]-e[2]],io=(t,e)=>[t[0]*e,t[1]*e,t[2]*e],Gl=t=>Math.hypot(...t),yg=t=>io(t,1/(Gl(t)||1)),ro=t=>({...lt,...t}),Ul=t=>Ze(t.character.plan,ro(t.pose),{height:t.character.height,contact:t.character.contact});function On(t,e,n){return so(t.position,Ul(t).chains[e][n])}function bg(t,e,n){const s=ro(t.pose),i=Ul(t).hip,r=is(t.character.plan,s,t.character.height),o=Ae(Ae(n,t.position),i),a=ss(o,(s.roll??0)*Math.PI/180),l=so(r.root,Qt(a,-(s.turn??0)*Math.PI/2));return gi(t.character.plan,s,e,l,{height:t.character.height})}function wg(t,e,n,s="toe"){const i=`leg.${e}`,r=s==="toe"?3:2;let o={...t,pose:ro(t.pose),position:[...t.position]};for(let l=0;l<6;l++){const c=Ul(o).chains[i],h=Ae(c[r],c[2]);o={...o,pose:bg(o,i,Ae(n,h))};const u=On(o,i,r);o.position[1]+=n[1]-u[1]}const a=Gl(Ae(On(o,i,r),n));return{...o,reached:a<t.character.height*.002}}function kg(t,e){const n=On(t,`arm.${e}`,2),s=On(t,`arm.${e}`,1);return so(n,io(yg(Ae(n,s)),t.character.lineWidth*.5))}function zv(t,e,n={}){const s=Math.min(t.character.height,e.character.height),i=n.length??s*.22;if(!(i>0)||!Number.isFinite(i))throw new Error("meetDandiya: stick length must be positive and finite");const r=n.point??[(t.position[0]+e.position[0])/2,Math.max(t.position[1],e.position[1])+s*.62,(t.position[2]+e.position[2])/2],o=(c,h)=>{const u=yg([r[0]-c.position[0],s*.2,r[2]-c.position[2]]),d=Ae(r,io(u,i));let f=ro(c.pose);for(let g=0;g<6;g++){const m={...c,pose:f},w=On(m,`arm.${h}`,2);f=bg(m,`arm.${h}`,Ae(d,Ae(kg(m,h),w)))}for(const[g,m]of Object.entries(St.hold))f[`hand.${h}.${g}`]=m;const p=kg({...c,pose:f},h);return{pose:f,stick:{grip:p,tip:so(p,io(u,i))}}},a=o(t,n.sideA??"right"),l=o(e,n.sideB??"right");return{a:a.pose,b:l.pose,sticks:[a.stick,l.stick],point:r,reached:[a.stick,l.stick].every(c=>Gl(Ae(c.tip,r))<s*.002)}}function vg(t,e){const n=e.count??8,s=e.beatsPerTurn??32;if(!Number.isFinite(t)||!Number.isFinite(e.radius)||e.radius<=0||!Number.isInteger(n)||n<1||!Number.isFinite(s)||s<=0)throw new Error("danceCircleAt: finite beat, positive radius/beatsPerTurn and a positive integer count are required");const i=e.center??[0,0],r=e.direction??1;if(i.length!==2||!i.every(Number.isFinite)||!Number.isFinite(e.angle??0)||!Number.isFinite(e.spins??0)||![1,-1].includes(r)||e.facing!==void 0&&!(typeof e.facing=="number"?Number.isFinite(e.facing):["inward","outward","tangent"].includes(e.facing)))throw new Error("danceCircleAt: center, angle, spins and facing must be finite; direction is 1 or -1");const o=e.character??ps({height:1.7}),a=e.style??"garba",l=(h,u)=>{const d=(e.angle??0)+360*u/n+r*360*h/s,f=d*Math.PI/180,p=e.facing??"inward",g=(typeof p=="number"?p:d+(p==="inward"?180:p==="tangent"?r*90:0))+(e.spins??0)*360*h/s,m=pi(a,h,{...e.pose,turn:g/90});return{character:o,position:[i[0]+e.radius*Math.sin(f),0,i[1]+e.radius*Math.cos(f)],pose:m.pose,heading:g,strike:m.strike}},c=pi(a,t).contact;return Array.from({length:n},(h,u)=>{const d=l(t,u);if(e.plantFeet===!1)return{...d,planted:!1};const f=l(c.start,u),p=On(f,`leg.${c.side}`,3),g=wg(d,c.side,p);return{...d,pose:Kl(d.pose,g.pose,c.weight),position:[d.position[0],g.position[1]*c.weight,d.position[2]],planted:g.reached&&c.weight===1}})}function qv(t,e){if(e.count!==void 0&&e.count!==t.length)throw new Error("danceCircleTracks: count must match targets.length");const n=e.bpm??120,s=e.samplesPerBeat??16;if(!t.length||![n,e.beats,s].every(l=>Number.isFinite(l)&&l>0))throw new Error("danceCircleTracks: targets and positive finite bpm, beats and samplesPerBeat are required");if(!Number.isFinite(e.start??0))throw new Error("danceCircleTracks: start must be finite");const i=Math.max(1,Math.ceil(e.beats*s)),r=Array.from({length:i+1},(l,c)=>({time:(e.start??0)+e.beats*c/i*6e4/n,members:vg(e.beats*c/i,{...e,count:t.length})})),o=r.some(l=>l.members.some(c=>c.pose.roll!==0)),a=new Set(["x","y","z","rotateY",...o?["turn","roll"]:[]]);return t.flatMap((l,c)=>{const h=r.map(u=>{const d=u.members[c],{turn:f,...p}=d.pose;return{time:u.time,pose:{...o?d.pose:p,x:d.position[0],y:d.position[1],z:d.position[2],rotateY:o?0:d.heading}}});return Object.keys(h[0].pose).filter(u=>a.has(u)||h.some(d=>d.pose[u]!==(e.pose?.[u]??lt[u]))).map(u=>({id:`${l}-circle-${u}`,target:l,property:u,keyframes:h.map(d=>({time:d.time,value:d.pose[u],easing:"linear"}))}))})}const oo=t=>Math.min(1,Math.max(0,t));function jv(t){const e={...ut,turn:t.view},n=[];for(const s of t.keys){const i=n[n.length-1],r=!i||s.reset?e:i.pose;n.push({at:s.at,pose:{...r,...s.pose},easing:s.easing})}return n}function Yv(t){return t-Kv*Math.sin(2*Math.PI*t)/(2*Math.PI)}const Kv=.5;function Xv(t,e){if(!(e<=t.takeoff||e>=t.landing))return(e-t.takeoff)/(t.landing-t.takeoff)}function Mg(t,e){const n=typeof t=="string"?Mi[t]:t,s=jv(n),i=oo(e);let r=0;for(let u=0;u<s.length;u++)s[u].at<=i&&(r=u);const o=s[r],a=s[Math.min(r+1,s.length-1)],l=a.at>o.at?(i-o.at)/(a.at-o.at):0,c=ns(o.pose,a.pose,Wt(a.easing??"ease-in-out")(oo(l))),h=Xv(n,i);return h===void 0?{...c,spin:0,rise:0}:{...c,spin:n.spin*Yv(h),rise:4*n.height*h*(1-h)}}function Sg(t,e,n){const s=typeof t=="string"?Mi[t]:t,i=oo(e),r=oo((i-s.takeoff)/(s.landing-s.takeoff));return s.travel*n*r}function Gv(t,e,n={}){const s=typeof e=="string"?Mi[e]:e,i=n.start??0,r=n.duration??s.duration,o=n.samples??48,a=Array.from({length:o+1},(h,u)=>{const d=u/o;return{time:i+d*r,progress:d,pose:Mg(s,d)}}),c=Object.keys(ut).filter(h=>a.some(u=>u.pose[h]!==ut[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*Sg(s,u.progress,n.height)}))})}return c}const Uv={leftHip:-55,leftKnee:-95,rightHip:55,rightKnee:95,leftShoulder:45,rightShoulder:-45,leftElbow:10,rightElbow:-10,lean:22,stretch:.94,headTilt:6},Vv={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},ao={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},Jv={leftHip:-22,leftKnee:-30,rightHip:22,rightKnee:30,leftAnkle:10,rightAnkle:10,leftShoulder:-125,rightShoulder:125,leftElbow:0,rightElbow:0,lean:8,headTilt:0},Zv={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 ms(t,e,n,s,i,r=1300){return{label:t,view:1,spin:e,height:n,travel:s,takeoff:.27,landing:.8,duration:r,keys:[{at:0,reset:!0},{at:.16,pose:Uv},{at:.27,pose:Vv,easing:"ease-out-quad"},...i,{at:.76,pose:Jv},{at:.86,pose:Zv,easing:"ease-out-quad"},{at:1,reset:!0}]}}const Mi={frontFlip:ms("Front flip (tuck)",360,.56,.35,[{at:.38,pose:ao,easing:"ease-out-cubic"},{at:.64,pose:ao}]),backFlip:ms("Back flip (tuck)",-360,.58,-.15,[{at:.36,pose:{...ao,lean:18},easing:"ease-out-cubic"},{at:.64,pose:{...ao,lean:18}}]),layout:ms("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:ms("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:ms("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:ms("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)};function xg(t,e){const n=Math.min(1,Math.max(0,t.turn??0)),s=1-n,i={...lt,turn:n},r=[{stick:"right",human:"left",s:1},{stick:"left",human:"right",s:-1}];for(const{stick:a,human:l,s:c}of r){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)*Qv,i[`eye.${l}`]=t[`${a}Eye`],i[`brow.${l}`]=t[`${a}Brow`],e&&Object.assign(i,tM(l,e[a]??Ot,t[`${a}Wrist`]??0,n))}const o=t.bend??0;i.lean=t.lean*n,i.bend=o*n,i.side=(t.lean+o*.5)*s,i["head.tilt"]=(t.headTilt+o*.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 Qv=70;function tM(t,e,n,s){const i=t==="right"?1-s:1+s,r={};for(const o of Object.keys(Ot))r[`hand.${t}.${o}`]=e[o]??Ot[o];return r[`hand.${t}.turn`]=(e.turn??0)-i,r[`hand.${t}.roll`]=(e.roll??0)+n,r}class Tg{positions=[];normals=[];indices=[];vertex(e,n,s,i,r,o){const a=Math.hypot(i,r,o)||1;return this.positions.push(e,n,s),this.normals.push(i/a,r/a,o/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 eM(t){const e=new Map,n=[];for(let i=0;i<t.positions.length/3;i++){const r=[0,1,2].map(o=>Math.round(t.positions[i*3+o]*1e6)).join(",");e.has(r)||e.set(r,i),n.push(e.get(r))}const s=new Map;for(let i=0;i<t.indices.length/3;i++)for(let r=0;r<3;r++){const o=n[t.indices[i*3+r]],a=n[t.indices[i*3+(r+1)%3]];if(o===a)continue;const l=o<a?`${o}-${a}`:`${a}-${o}`,c=s.get(l);c?c.faces.push(i):s.set(l,{a:Math.min(o,a),b:Math.max(o,a),faces:[i]})}return[...s.values()]}const Vl=Math.PI*2;function nM(t,e=16){const n=new Tg,s=Math.max(6,Math.round(e)),i=Math.max(3,Math.round(s/2)),r=[];for(let o=0;o<=i;o++){const a=o/i*Math.PI,l=[];for(let c=0;c<=s;c++){const h=c/s*Vl,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))}r.push(l)}for(let o=0;o<i;o++)for(let a=0;a<s;a++){const l=r[o][a],c=r[o+1][a],h=r[o+1][a+1],u=r[o][a+1];o>0&&n.triangle(l,c,u),o<i-1&&n.triangle(c,h,u)}return n.build()}function Eg(t,e,n,s,i){const r=t.vertex(0,n,0,0,s,0),o=Array.from({length:i},(a,l)=>{const c=l/i*Vl;return t.vertex(Math.sin(c)*e,n,Math.cos(c)*e,0,s,0)});for(let a=0;a<i;a++){const l=o[a],c=o[(a+1)%i];s===1?t.triangle(r,l,c):t.triangle(r,c,l)}}function Ag(t,e,n=24){const s=new Tg,i=Math.max(6,Math.round(n)),r=e/2,o=-e/2,a=h=>Array.from({length:i+1},(u,d)=>{const f=d/i*Vl;return s.vertex(Math.sin(f)*t,h,Math.cos(f)*t,Math.sin(f),0,Math.cos(f))}),l=a(o),c=a(r);for(let h=0;h<i;h++)s.quad(l[h],l[h+1],c[h+1],c[h]);return Eg(s,t,r,1,i),Eg(s,t,o,-1,i),s.build()}function lo(t){const e=Array.from({length:t.indices.length/3},()=>[]);for(const n of eM(t))for(const s of n.faces){const i=n.faces.find(r=>r!==s)??-1;e[s].push({a:n.a,b:n.b,across:i})}return{...t,faceEdges:e}}const Jl=new Map;function sM(t){const e=Jl.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(r=>r+r).join(""):s;n=[0,2,4].map(r=>Number.parseInt(i.slice(r,r+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 Jl.size<512&&Jl.set(t,n),n}Jt([-3,-5,-4]);const iM=(t,e,n)=>{const s=Math.min(1,Math.max(0,(n-t)/(e-t)));return s*s*(3-2*s)};function $g(t,e,n){const s=[0,0,0];for(const i of n){const r=sM(i.color);let o;if(i.light==="ambient")o=i.intensity;else if(i.light==="directional")o=i.intensity*Math.max(0,-$e(e,i.direction));else{const a=se(i.position,t),l=ar(a),c=l>0?mn(a,1/l):e,h=i.range?Math.max(0,1-l/i.range)**2:1;if(o=i.intensity*Math.max(0,$e(e,c))*h,i.light==="spot"){const u=Math.cos(i.angle*Math.PI/180),d=Math.cos(i.angle*.8*Math.PI/180);o*=iM(u,d,-$e(c,i.direction))}}s[0]+=r[0]*o,s[1]+=r[1]*o,s[2]+=r[2]*o}return s}function Pg(t,e){return t?Math.min(1,Math.max(0,(e-t.near)/(t.far-t.near))):0}function Zl(t,e,n={}){t.save(),rM(t,e,n),t.restore()}function rM(t,e,n){const s=Ql(e,n);n.shadow!==!1&&tc(t,e,n);for(const i of e.under)Ig(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 r of i.slice(1))t.lineTo(r.x,r.y);t.closePath()}t.clip("nonzero")}n.rider(t),t.restore()}for(const i of e.over)Ig(t,i,s,n)}function Ig(t,e,n,s){const i=s.loose?.[e.part.id];if(!i){sc(t,e,n,s);return}if(i.opacity<=0)return;const r=e.faces.flatMap(c=>c.points);if(r.length===0)return;const o=r.map(c=>c.x),a=r.map(c=>c.y),l={x:(Math.min(...o)+Math.max(...o))/2,y:(Math.min(...a)+Math.max(...a))/2};t.save(),t.globalAlpha*=Math.min(1,i.opacity),t.translate(l.x+i.x,l.y+i.y),t.rotate(i.rotate*Math.PI/180),t.translate(-l.x,-l.y),sc(t,e,n,s),t.restore()}function Ql(t,e={}){return e.lineWidth??Math.max(1.3,t.sizePx*.022)}function tc(t,e,n={}){e.shadow.opacity<=0||e.shadow.points.length<3||(t.save(),t.globalAlpha=e.shadow.opacity,co(t,e.shadow.points,n.ink??"#26262b",!1),t.restore())}function oM(t,e,n,s={}){t.save(),sc(t,e,n,s),t.restore()}function Og(t,e,n,s={}){const i=s.style==="stick",r=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}))}),o=new Map;for(const h of r){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);o.set(f,[...o.get(f)??[],h])}for(const h of o.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 w=g.normal[0]*(d[0]-g.center[0])+g.normal[1]*(d[1]-g.center[1])+g.normal[2]*(d[2]-g.center[2]);w>-Cg/5&&w<Cg&&(u.layer=Math.max(u.layer,p.layer),u.depth=Math.max(u.depth,p.depth+1e-6))}}r.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=ec(t,h,n,s)),u};t.save();const c=t.globalAlpha;for(const{part:h,face:u}of r){t.globalAlpha=c*h.opacity;const d=l(h);if(!u)d.line(h.spine,n*1.15);else{const f=i?_g(h,s):u.light?aM(h,u,s):nc(h);f&&(!i&&s.look==="silhouette"?d.shape(u.points,f,0):co(t,u.points,i||u.light?f:ho(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 Cg=.05;function ec(t,e,n,s){return ri(t,{look:s.look??"clean",ink:e.part.ink??s.ink??"#26262b",lineWidth:n,seed:ne(`${s.seed??0}:${e.part.id}`),time:s.time??0,pencil:{construction:!1,rubbedOut:0,...s.pencil}})}function nc(t){const{part:e}=t;return e.glow&&t.glow>0&&e.fill?oc(e.fill,e.glow.color,t.glow):e.fill}function aM(t,e,n){const{part:s}=t;if(!s.fill)return;const i=rc(s.fill,e.light,e.fog??0,n.fog);return s.glow&&t.glow>0?oc(i,s.glow.color,t.glow):i}function _g(t,e){const n=nc(t);return n&&(cM(n)||t.glow>0)?n:e.paper??"#fbf8ef"}function sc(t,e,n,s){e.opacity<1?(t.save(),t.globalAlpha*=e.opacity,Hg(t,e,n,s),t.restore()):Hg(t,e,n,s)}function Hg(t,e,n,s){if(s.style==="stick")return lM(t,e,n,s);const{part:i}=e,r=ec(t,e,n,s),o=nc(e),a=s.look==="silhouette";for(const c of e.faces)o&&(a?r.shape(c.points,o,0):co(t,c.points,ho(o,c.tone)));const l=(i.outline??1)*n;if(l>0)for(const c of e.edges)c.length>1&&r.line(c,l);for(const c of e.marks)r.line(c,n*.7)}function lM(t,e,n,s){const{part:i}=e;if(i.solidOnly)return;const r=ec(t,e,n,s);if(e.spine){r.line(e.spine,n*1.15);return}const o=_g(e,s);for(const l of e.faces)co(t,l.points,o);const a=(i.outline??1)*n;if(a>0)for(const l of e.edges)l.length>1&&r.line(l,a);for(const l of e.marks)r.line(l,n*.7)}function cM(t){const e=ys(t);return e?(.299*e[0]+.587*e[1]+.114*e[2])/255<.3:!1}function co(t,e,n,s=!0,i=.8){t.fillStyle=n,t.beginPath(),t.moveTo(e[0].x,e[0].y);for(let r=1;r<e.length;r++)t.lineTo(e[r].x,e[r].y);t.closePath(),t.fill(),s&&(t.strokeStyle=n,t.lineWidth=i,t.lineJoin="round",t.stroke())}function ys(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 ic=t=>`#${t.map(e=>Math.round(Math.max(0,Math.min(255,e))).toString(16).padStart(2,"0")).join("")}`;function ho(t,e){const n=ys(t);return n?ic(e>=1?n.map(s=>s+(255-s)*(e-1)*2):n.map(s=>s*e)):t}function rc(t,e,n,s){const i=ys(t);if(!i)return t;let r=i.map((a,l)=>a*e[l]);const o=s?ys(s):void 0;return o&&n>0&&(r=r.map((a,l)=>a+(o[l]-a)*n)),ic(r)}function oc(t,e,n){const s=ys(t),i=ys(e);return!s||!i?n<.5?t:e:ic(s.map((r,o)=>r+(i[o]-r)*n))}const hM=new Set(["x","y","z","position","rotateX","rotateY","rotateZ","quaternion","scale","scaleX","scaleY","scaleZ","visible","opacity","color"]),uM=new Set(["walk","walking","gait"]),Rg=t=>typeof t=="number"?t:void 0,dM=1.7;function fM(t,e,n){const s=Array.from({length:24},(i,r)=>{const o=r/24*Math.PI*2,a=e.toView([Math.cos(o)*n,0,Math.sin(o)*n*.8]);return a[2]<-.001?e.toScreen(a):null});s.some(i=>i===null)||(t.beginPath(),s.forEach((i,r)=>r===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 gM(t){const e=$e([0,1,0],t);if(e>.999999)return lr();if(e<-.999999)return me(Vt([1,0,0],180));const n=Js([0,1,0],t);return me(Vt(n,Math.acos(e)*180/Math.PI))}function pM(t,e,n,s,i){const r=t.solid??{},o=r.outline===!1?void 0:r.outline??{width:2,color:"#0f172a"},a={color:r.color??"#475569",shading:r.shading??"toon",outline:o},l={color:r.skin??"#f2c49b",shading:r.shading??"toon",outline:o},c={color:"#0f172a",shading:"unlit"},h=s.height*.034,u=[],d=(k,b,T)=>u.push({mesh:k,world:Rt(i,b),material:T}),f=(k,b,T)=>d(e.sphere,$a(k,[0,0,0,1],[b,b,b]),T);for(const k of n.chains){const b=s.chains[k.id],T=k.id==="spine"?1.9:1;k.bones.forEach(($,M)=>{const x=b[M],S=b[M+1],E=Zs(x,S),[I,A]=$.width??[1,1],O=h*T*(I+A)/2;if(E>1e-6){const H=yn(x,S,.5),W=gM(Jt(se(S,x)));d(e.cylinder,Rt(bn(H),Rt(W,wn([O,E,O]))),a)}f(x,h*T*I,a),f(S,h*T*A,a)}),k.id.startsWith("arm.")&&f(b[b.length-1],h*1.5,l)}const{center:p,rx:g,ry:m,axes:w}=s.head,v=[...w[0],0,...w[1],0,...w[2],0,...p,1];d(e.sphere,Rt(v,wn([g,m,g])),l);for(const k of[-1,1]){const b=Jt([k*.36,.15,.92]),T=Vs(p,Vs(Vs(mn(w[0],b[0]*g*1.04),mn(w[1],b[1]*m*1.04)),mn(w[2],b[2]*g*1.04))),$=[...w[0],0,...w[1],0,...w[2],0,...T,1];d(e.sphere,Rt($,wn([g*.11,m*.14,g*.03])),c)}return u}const mM={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:ps({...t.character,height:1}),cylinder:lo(Ag(1,1,16)),sphere:lo(nM(1,20))}},resolve({object:t,prepared:e,values:n,world:s,camera:i,lights:r=[],fog:o,toScreen:a}){const l=t,c=e,h=c.who;let u={...lt,...l.pose};for(const[x,S]of n)typeof S=="number"&&!hM.has(x)&&!uM.has(x)&&(u[x]=S);const d=Math.max(0,Math.min(1,Rg(n.get("walking"))??l.walking??0));if(d>0){const x=typeof n.get("gait")=="string"?n.get("gait"):l.gait,S=Vr(x,Rg(n.get("walk"))??0,u);u=Object.fromEntries(Object.keys({...u,...S}).map(E=>[E,(u[E]??0)+((S[E]??0)-(u[E]??0))*d]))}const f=l.height??dM,p=Rt(i.view,s),g={toView:x=>ie(p,x),toScreen:x=>a(x)},w=-g.toView([0,f/2,0])[2];if(w<=i.near)return null;const v=l.shadow===!1?[]:[{depth:w+f,draw:x=>fM(x,g,f*.18)}];if(l.look==="solid"){const x=Ze(h.plan,u,{height:f,contact:h.contact});return{meshes:pM(l,c,h.plan,x,s),drawables:v}}const k=ie(s,[0,f*.6,0]),b=Jt(se(i.position,k)),T=$g(k,b,r).map(x=>Math.min(1,x));let $=h;if(r.length>0&&h.skin!=="none"){const x=rc(h.skin,T,Pg(o,Zs(k,i.position)),o?.color);$={...h,skin:x,...h.body?{body:{...h.body,fill:x}}:{}}}const M=gg($,u,g,{height:f});return{drawables:[...v,...M.map((x,S)=>({depth:-(x.sortDepth??x.depth)-S*1e-6,draw:(E,I)=>x.draw(E,I.time)}))]}}},en={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}},Si=1,uo=.55,Lg=.35,yM=1.6,Fg={a:"a",e:"e",i:"i",y:"i",o:"o",u:"u"},Ng={m:"m",b:"m",p:"m",f:"f",v:"f",w:"u",q:"u",l:"l",n:"l",d:"l",t:"l"},Wg={अ:"a",आ:"a",इ:"i",ई:"i",उ:"u",ऊ:"u",ऋ:"i",ए:"e",ऐ:"e",ओ:"o",औ:"o",ऍ:"e",ऑ:"o"},Dg={"ा":"a","ि":"i","ी":"i","ु":"u","ू":"u","ृ":"i","े":"e","ै":"e","ो":"o","ौ":"o","ॅ":"e","ॉ":"o"},bM={प:"m",फ:"m",ब:"m",भ:"m",म:"m",व:"u"},wM="्",Bg="़",kM=t=>t>="क"&&t<="ह",zg=new Set([".",",","!","?",";",":","…","।","॥","—","-"]);function qg(t){const e=[],n=Array.from(t.toLowerCase()),s=(i,r)=>{const o=e[e.length-1];o&&o.viseme===i?o.weight+=r*.5:e.push({viseme:i,weight:r})};for(let i=0;i<n.length;i++){const r=n[i],o=n[i+1];if(zg.has(r))s("rest",yM);else if(/\s/.test(r)){const a=e[e.length-1];a&&a.viseme!=="rest"&&e.push({viseme:"c",weight:Lg})}else if((r==="o"||r==="e")&&o===r)s(r==="o"?"u":"i",Si),i++;else if(r in Fg)s(Fg[r],Si);else if(r in Ng)s(Ng[r],uo);else{if(r==="h")continue;if(/[a-z]/.test(r))s("c",uo);else if(r in Wg)s(Wg[r],Si);else if(kM(r)){const a=o===Bg?r==="फ"?"f":void 0:bM[r];s(a??"c",uo);let l=i+1;n[l]===Bg&&l++;const c=n[l];c===wM?i=l:c&&c in Dg?(s(Dg[c],Si),i=l):(!c||/\s/.test(c)||zg.has(c)||s("a",Si*.6),i=l-1)}else(r==="ं"||r==="ँ")&&s("l",uo*.6)}}for(;e.length>0&&(e[e.length-1].viseme==="rest"||e[e.length-1].weight===Lg);)e.pop();return e}function ac(t,e={}){const n=e.fields?.mouth??"mouth",s=e.fields?.mouthWidth??"mouthWidth",i=e.energy??1,r=qg(t.text),o=[{time:t.start,value:en.rest.mouth}],a=[{time:t.start,value:en.rest.mouthWidth}],l=r.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 r){const d=c*u.weight/l,f=h+Math.min(d*.4,60);if(f>o[o.length-1].time){const p=en[u.viseme];o.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>o[o.length-1].time&&(o.push({time:t.end,value:en.rest.mouth,easing:"ease-in-out"}),a.push({time:t.end,value:en.rest.mouthWidth,easing:"ease-in-out"})),{[n]:o,[s]:a}}function vM(t,e,n={}){const s={};for(const i of[...e].sort((r,o)=>r.start-o.start))for(const[r,o]of Object.entries(ac(i,n))){const a=s[r]??=[],l=a.length>0?a[a.length-1].time:-1/0;a.push(...o.filter(c=>c.time>l))}return Object.entries(s).map(([i,r])=>({id:`${t}-${i}`,target:t,property:i,keyframes:r}))}function fo(t,e,n,s={}){if(n.length===0)return e;const i=s.fields?.mouth??"mouth",r=s.fields?.mouthWidth??"mouthWidth",o={[i]:en.rest.mouth,[r]:en.rest.mouthWidth,...s.rest},a=new Ht({id:"before-speech",tracks:e}),l=(u,d)=>a.getStateAtTime(d).values.get(t)?.get(u)??o[u],c=[i,r],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=ac(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,w)=>m.time-w.time)}h.push({id:d?.id??`${t}-${u}`,target:t,property:u,keyframes:f})}return h}const xi=([t,e,n])=>{const s=Math.hypot(t,e,n)||1;return[t/s,e/s,n/s]};function jg([t,e,n]){const[s,i,r]=[t/2,e/2,n/2];return{vertices:[[-s,-i,-r],[s,-i,-r],[s,i,-r],[-s,i,-r],[-s,-i,r],[s,-i,r],[s,i,r],[-s,i,r]],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 bs=(t,[e,n,s])=>t==="z"?[e,n,s]:t==="x"?[s,n,e]:[e,s,n];function Yg(t,e,n="x",s=20,i=0){const r=[],o=e/2;for(const c of[-o,o])for(let h=0;h<s;h++){const u=Math.PI*2*h/s;r.push(bs(n,[Math.cos(u)*t,Math.sin(u)*t,c]))}const a=[{corners:Array.from({length:s},(c,h)=>s-1-h),normal:bs(n,[0,0,-1])},{corners:Array.from({length:s},(c,h)=>s+h),normal:bs(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:bs(n,[Math.cos(u),Math.sin(u),0])})}const l=[];if(i>0)for(const c of[-o,o]){const h=r.push(bs(n,[0,0,c*1.01]))-1;for(let u=0;u<i;u++){const d=Math.PI*2*u/i,f=r.push(bs(n,[Math.cos(d)*t*.82,Math.sin(d)*t*.82,c*1.01]))-1;l.push([h,f])}}return{vertices:r,faces:a,marks:l,creases:!0}}function Kg([t,e,n],s=16){const i=Math.max(4,Math.round(s/2)),r=[[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;r.push([Math.sin(u)*Math.cos(f)*t,Math.cos(u)*e,Math.sin(u)*Math.sin(f)*n])}}const o=r.push([0,-e,0])-1,a=(h,u)=>1+(h-1)*s+u%s,l=h=>{const u=h.reduce((d,f)=>[d[0]+r[f][0],d[1]+r[f][1],d[2]+r[f][2]],[0,0,0]);return xi([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),o];c.push({corners:d,normal:l(d)})}return{vertices:r,faces:c,creases:!1}}const MM=t=>t.reduce((e,[n,s],i)=>{const[r,o]=t[(i+1)%t.length];return e+n*o-r*s},0)/2;function Xg(t,e){const n=MM(t)<0?[...t].reverse():t,s=n.length,i=e/2,r=[...n.map(([a,l])=>[i,l,a]),...n.map(([a,l])=>[-i,l,a])],o=[{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]];o.push({corners:[a,l,s+l,s+a],normal:xi([0,-c,h])})}return{vertices:r,faces:o,creases:!0}}function Gg(t,e){const n={left:([i,r])=>[0,r,i],right:([i,r])=>[0,r,i],front:([i,r])=>[i,r,0],back:([i,r])=>[i,r,0],up:([i,r])=>[i,0,r]},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,r)=>r),normal:s[e]}]}}function Ug(t,e,n=8){const s=o=>Array.isArray(e)?e[Math.min(o,e.length-1)]:e,i=[],r=[];t.forEach((o,a)=>{const l=t[Math.min(a+1,t.length-1)],c=t[Math.max(a-1,0)],h=xi([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=xi(Vg(h,u)),f=Vg(d,h);for(let p=0;p<n;p++){const g=Math.PI*2*p/n,m=Math.cos(g)*s(a),w=Math.sin(g)*s(a);i.push([o[0]+d[0]*m+f[0]*w,o[1]+d[1]*m+f[1]*w,o[2]+d[2]*m+f[2]*w])}});for(let o=0;o<t.length-1;o++)for(let a=0;a<n;a++){const l=(a+1)%n,c=[o*n+a,o*n+l,(o+1)*n+l,(o+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[o][0]+t[o+1][0])/2,(t[o][1]+t[o+1][1])/2,(t[o][2]+t[o+1][2])/2];r.push({corners:c,normal:xi([h[0]-u[0],h[1]-u[1],h[2]-u[2]])})}return{vertices:i,faces:r,creases:!1}}function Vg(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 Jg(t){switch(t.type){case"box":return jg(t.size);case"cylinder":return Yg(t.radius,t.length,t.axis,t.segments,t.spokes);case"ellipsoid":return Kg(t.radii,t.segments);case"extrude":return Xg(t.profile,t.width);case"panel":return Gg(t.points,t.facing);case"tube":return{...Ug(t.points,t.radius,t.segments),joined:t.joined}}}function lc(t,e){if(t.length<2)return t;const n=i=>t[Math.max(0,Math.min(t.length-1,i))],s=i=>{const r=i*(t.length-1),o=Math.min(t.length-2,Math.floor(r)),a=r-o,[l,c,h,u]=[n(o-1),n(o),n(o+1),n(o+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,r)=>s(r/(e-1)))}const Cn=t=>Array.isArray(t)&&t.length===2&&t.every(e=>typeof e=="number"&&Number.isFinite(e));function go(t,e){return((e-t)%360+540)%360-180}function Zg(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 ws(t,e){return Math.atan2(e[0]-t[0],e[1]-t[1])*180/Math.PI}function Qg(t){const e=t.filter((i,r)=>r===0||Math.hypot(i[0]-t[r-1][0],i[1]-t[r-1][1])>1e-6);if(e.length<2)return[];const n=e.length===2?e:lc(e.map(([i,r])=>[i,0,r]),(e.length-1)*12).map(([i,,r])=>[i,r]);let s=0;return n.map((i,r)=>(r>0&&(s+=Math.hypot(i[0]-n[r-1][0],i[1]-n[r-1][1])),{point:i,at:s}))}function tp(t,e){let n=1;for(;n<t.length-1&&t[n].at<e;)n++;const s=t[n-1],i=t[n],r=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])*r,s.point[1]+(i.point[1]-s.point[1])*r],direction:[i.point[0]-s.point[0],i.point[1]-s.point[1]]}}function ep(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 r=(n+s)/2;t(r)<e?n=r:s=r}return(n+s)/2}const Ti=520,cc=["do","at","for","to","through","toward","speed","pose","gag","say","look","turns","dance","bpm","beats"],np=t=>Math.max(700,Array.from(t).length*65),sp=70,ip=35;function hc(t,e){const n=e[0]-t.x,s=e[1]-t.eyeHeight,i=e[2]-t.z,r=t.heading*Math.PI/180,o=n*Math.cos(r)-i*Math.sin(r),a=n*Math.sin(r)+i*Math.cos(r),l=Math.atan2(o,a)*180/Math.PI,c=Math.hypot(o,a),h=-Math.atan2(s,c)*180/Math.PI,u=Math.max(-sp,Math.min(sp,l*.75)),d=Math.max(-ip,Math.min(ip,h*.7));return{"head.turn":u,"head.nod":d,lookX:Math.max(-1,Math.min(1,(l-u)/45)),lookY:Math.max(-1,Math.min(1,(h-d)/30))}}const rp={walk:1.3,bouncy:1.4,doubleBounce:1.2,sneak:.6,strut:1.2,tired:.8,run:3.6,shove:.7},uc=Object.keys(Kt),dc=Object.keys(be),fc=Object.keys(Zr),SM=.25,xM=700/180,TM=200,EM=300;function op(t){if(!Array.isArray(t))return[{beat:-1,message:`Beats must be an array of { do: … } objects (got ${typeof t}).`}];const e=[...uc,"face","spin","dance","hold","pose","gag","place","say","look"],n=[];return t.forEach((s,i)=>{const r=c=>n.push({beat:i,message:c});if(!s||typeof s!="object"||Array.isArray(s))return r("Each beat must be an object like { do: 'walk', to: [x, z] }.");const o=s,a={duration:"for",path:"through",position:"to",heading:"toward",direction:"toward"};for(const c of Object.keys(o))cc.includes(c)||r(ft("beat field",c,cc,a[c]));const l=typeof o.do=="string"?dc.includes(o.do)?"pose":fc.includes(o.do)?"gag":o.do==="turn"?"face":void 0:void 0;if(typeof o.do!="string"||!e.includes(o.do))return r(ft("character 3D beat",o.do,e,l));for(const c of["at","for","turns","bpm","beats"]){const h=o[c];h!==void 0&&(typeof h!="number"||!Number.isFinite(h)||(c==="at"?h<0:c!=="turns"&&h<=0))&&r(`\`${c}\` must be finite${c==="turns"?"":c==="at"?" and non-negative":" and positive"}.`)}if(o.do==="dance"&&!(typeof o.dance=="string"&&Object.hasOwn(En,o.dance))&&r(ft("native dance",o.dance,Object.keys(En))),uc.includes(o.do)&&(o.to===void 0&&o.through===void 0&&r(`\`${o.do}\` needs \`to\` ([x, z] metres) or \`through\` (a list of them).`),o.to!==void 0&&!Cn(o.to)&&r(`\`to\` is a point on the ground, [x, z] metres (got ${JSON.stringify(o.to)}).`),o.through!==void 0&&!(Array.isArray(o.through)&&o.through.length>0&&o.through.every(Cn))&&r("`through` is a list of points on the ground, each [x, z] metres.")),o.do==="place"&&!Cn(o.to)&&r("`place` needs `to`: a point on the ground, [x, z] metres."),o.do==="face"&&!(Cn(o.toward)||typeof o.toward=="number"&&Number.isFinite(o.toward))&&r("`face` needs `toward`: a point [x, z] or a finite heading in degrees."),o.do==="say"&&!(typeof o.say=="string"&&o.say.trim().length>0)&&r("`say` needs `say`: the line spoken."),o.do==="look"){const c=o.look??o.toward;Array.isArray(c)&&(c.length===2||c.length===3)&&c.every(u=>typeof u=="number"&&Number.isFinite(u))||c==="camera"||r("`look` needs `look`: a point [x, z] or [x, y, z] to look at, or `camera`.")}o.do==="pose"&&!(typeof o.pose=="object"&&o.pose!==null)&&!dc.includes(o.pose)&&r(ft("pose",o.pose,dc)),o.do==="gag"&&!fc.includes(o.gag)&&r(ft("gag",o.gag,fc))}),n}function AM(t,e,n){const s=op(e);if(s.length>0)throw new Error(`characterScript3D: ${s.length} problem(s) in the beats:
|
|
54
|
+
${s.map(M=>` beat ${M.beat}: ${M.message}`).join(`
|
|
55
|
+
`)}`);const i=n.height??1.7,r={...lt,...n.pose},o=(M,x=r)=>{const S=M.match(/^hand\.(?:left|right)\.(.+)$/)?.[1];return x[M]??lt[M]??(S?Ot[S]:void 0)??0};let[a,l]=n.position??[0,0],c=n.heading??0,h=0;const u=new Map,d=[],f=(M,x,S,E="linear")=>{const I=u.get(M)??[];I.push({time:x,value:S,easing:E}),u.set(M,I)},p=(M,x,S)=>{const E=u.get(M)??[];for(let I=E.length-1;I>=0;I--)if(E[I].time===x){if(E[I].value===S)return;break}f(M,x,S)};f("x",0,a),f("z",0,l),f("rotateY",0,c);const g=(M,x,S)=>{const E=go(c,x);if(Math.abs(E)<1)return S!==void 0&&(p("rotateY",M,c),f("rotateY",M+S,c)),M+(S??0);const I=S??Math.max(TM,Math.abs(E)*xM);return p("rotateY",M,c),c+=E,f("rotateY",M+I,c,"ease-in-out"),M+I},m=(M,x,S,E="ease-in-out")=>{for(const[I,A]of Object.entries(S))o(I)!==A&&(p(I,M,o(I)),f(I,x,A,E),r[I]=A)},w=(M,x,S)=>{const E=Qg([[a,l],...x.through??[x.to]]);if(E.length<2)return S;const I=g(S,ws(E[0].point,E[1].point)),A=E[E.length-1].at,O=x.speed??rp[M]*Math.sqrt(i/1.7),H=x.for??A/O*1e3,W=Jr(M,i),j=Wt("ease-in-out"),J=Math.min(EM,H/4);d.push({time:I,value:M}),p("walking",I,0),f("walking",I+J,1,"ease-out"),f("walking",I+H-J,1),f("walking",I+H,0,"ease-in");const tt=h;let V=c;for(let L=0;;L=Math.min(A,L+SM)){const q=I+ep(j,L/A)*H,{point:G,direction:_}=tp(E,L);V+=go(V,ws([0,0],_));const Y=L===0?p:f;if(Y("x",q,G[0]),Y("z",q,G[1]),Y("rotateY",q,V),Y("walk",q,tt+L/W),L>=A)break}return h=tt+A/W,[a,l]=E[E.length-1].point,c=V,I+H},v=[],k=[];let b=0;for(const M of e){const x=M.at??b;let S=x;if(uc.includes(M.do))S=w(M.do,M,x);else if(M.do==="face")S=g(x,typeof M.toward=="number"?M.toward:ws([a,l],M.toward),M.for);else if(M.do==="spin")S=x+(M.for??1e3),p("rotateY",x,c),c+=(M.turns??1)*360,f("rotateY",S,c,"linear");else if(M.do==="dance"){const E=En[M.dance],I=M.bpm??E.bpm,A=M.beats??(M.for!==void 0?M.for*I/6e4:E.beats);S=x+(M.for??A*6e4/I);const O={...r},H=Math.max(1,Math.ceil(A*16)),W=Array.from({length:H+1},(J,tt)=>pi(M.dance,A*tt/H,O).pose),j=Math.min(150,(S-x)/4);for(const J of Object.keys(W[0])){const tt=o(J,O);J==="turn"||J==="roll"||W.every(V=>V[J]===tt)||(p(J,x,tt),W.slice(1).forEach((V,L)=>{const q=x+(S-x)*(L+1)/H,G=Math.min(1,(q-x)/j),_=G*G*(3-2*G);f(J,q,tt+(V[J]-tt)*_)}),r[J]=W[H][J])}}else if(M.do==="hold")S=x+(M.for??1e3);else if(M.do==="place")p("x",x,a),p("z",x,l),[a,l]=M.to,f("x",x+1,a),f("z",x+1,l),typeof M.toward=="number"&&(p("rotateY",x,c),c=M.toward,f("rotateY",x+1,c)),S=x+1;else if(M.do==="pose"){S=x+(M.for??500);const E=typeof M.pose=="string"?be[M.pose]:M.pose;m(x,S,E)}else if(M.do==="gag"){const E=Gf(M.gag,{at:x,from:{...r}});let I=E[0];for(const A of E.slice(1))m(I.time,A.time,Object.fromEntries(Object.entries(A.pose).filter(([O,H])=>r[O]!==H)),A.easing??"ease-in-out"),I=A;S=I.time}else if(M.do==="say"){S=x+(M.for??np(M.say)),k.push({text:M.say,start:x,end:S});const E={tilt:r["head.tilt"]??0,left:r["brow.left"]??0,right:r["brow.right"]??0};let I=0;for(let A=x+Ti;A<S-Ti/2;A+=Ti,I++){const O=I%2===0;m(A-Ti/2,A,{"head.tilt":E.tilt+(O?3:-2),"brow.left":E.left+(O?.25:0),"brow.right":E.right+(O?.25:0)})}I>0&&m(S-Ti/2,S,{"head.tilt":E.tilt,"brow.left":E.left,"brow.right":E.right})}else if(M.do==="look"){const E=M.look??M.toward,I=i*.9,A=E==="camera"?n.camera??[0,1.6,8]:E.length===3?E:[E[0],I,E[1]];S=x+(M.for??500),m(x,S,hc({x:a,z:l,heading:c,eyeHeight:I},A),"ease-out")}v.push({do:M.do,start:x,end:S}),b=S}const T=`${n.scene}/${t}`;let $=[...u].map(([M,x])=>({id:`${t}-${M}`,target:T,property:M,keyframes:Zg(x)}));return d.length>0&&$.push({id:`${t}-gait`,target:T,property:"gait",keyframes:d}),k.length>0&&($=fo(T,$,k,{rest:{mouth:n.pose?.mouth??lt.mouth??0,mouthWidth:n.pose?.mouthWidth??lt.mouthWidth??1}})),{tracks:$,duration:b,beats:v,end:{position:[a,l],heading:c,pose:{...r}}}}function gc(t,e,n=[0,0,0]){const s=t.filter(r=>r.target===e),i=new Ht({id:`${e}-position`,tracks:s});return r=>{const o=i.getStateAtTime(r).values.get(e),a=o?.get("position");if(Array.isArray(a)&&a.length===3)return[a[0],a[1],a[2]];const l=(c,h)=>{const u=o?.get(c);return typeof u=="number"?u:h};return[l("x",n[0]),l("y",n[1]),l("z",n[2])]}}function $M(t,e){const n=`${e.scene}/${e.character}`,s=e.height??1.7,i=Math.max(1,e.every??66),r=e.objects?.[e.character]??[0,0,0],o=new Ht({id:`${n}-own`,tracks:t.filter(u=>u.target===n)}),a=e.at,l=typeof a=="function"?a:Array.isArray(a)?()=>a:"camera"in a?gc(t,`${e.scene}/${a.camera}`,e.objects?.[a.camera]??[0,1.6,8]):(()=>{const u=gc(t,`${e.scene}/${a.object}`,e.objects?.[a.object]??[0,0,0]),d=a.eyeHeight??s*.9;return f=>{const p=u(f);return[p[0],p[1]+d,p[2]]}})(),c=["head.turn","head.nod","lookX","lookY"],h={"head.turn":[],"head.nod":[],lookX:[],lookY:[]};for(let u=e.start;;u=Math.min(e.end,u+i)){const d=o.getStateAtTime(u).values.get(n),f=(g,m)=>{const w=d?.get(g);return typeof w=="number"?w:m},p=hc({x:f("x",r[0]),z:f("z",r[2]),heading:f("rotateY",0),eyeHeight:f("y",r[1])+s*.9},l(u));for(const g of c)h[g].push({time:u,value:p[g]??0});if(u>=e.end)break}return c.map(u=>({id:`${n}-lookAt-${u}`,target:n,property:u,keyframes:h[u]}))}function PM(t){const e=Math.max(1,Math.round(t.count)),[n,s]=t.centre??[0,0],i=t.spacing??1.2,r=t.shape??"line",o=[];if(r==="circle"){const h=e<2?0:Math.max(i,i*e/(Math.PI*2));for(let u=0;u<e;u++){const d=u/e*Math.PI*2,f=n+Math.sin(d)*h,p=s+Math.cos(d)*h;o.push({position:[f,p],heading:(Math.atan2(n-f,s-p)*180/Math.PI+360)%360})}return o}if(r==="cluster"){let h=(t.seed??1)>>>0||7;const u=()=>(h^=h<<13,h>>>=0,h^=h>>17,h^=h<<5,h>>>=0,h/4294967296),d=[];for(let f=0;f<e;f++){let p=[n,s],g=-1/0;for(let m=0;m<24;m++){const w=Math.sqrt(u())*i*Math.max(1,Math.sqrt(e)*.9),v=u()*Math.PI*2,k=[n+Math.cos(v)*w,s+Math.sin(v)*w],b=d.length===0?1/0:Math.min(...d.map(T=>Math.hypot(T[0]-k[0],T[1]-k[1])));if(b>g&&(g=b,p=k),b>=i)break}d.push(p),o.push({position:p,heading:0})}return o}const a=(t.heading??90)*Math.PI/180,l=i*(e-1),c=(t.bend??60)*Math.PI/180;for(let h=0;h<e;h++){const u=e===1?0:h/(e-1)-.5,d=u*l;let f=n+Math.sin(a)*d,p=s+Math.cos(a)*d,g=((t.heading??90)-90+360)%360;if(r==="arc"){const m=(1-Math.cos(u*c))*l*.5;f-=Math.cos(a)*m,p+=Math.sin(a)*m,g=(g-u*(t.bend??60)+360)%360}o.push({position:[f,p],heading:g})}return o}const ap={x:0,y:0,scale:1,rotate:0,shakeX:0,shakeY:0,shakeRotate:0};function IM(t){const e=n=>{const s=t?.get(n);return typeof s=="number"?s:ap[n]};return{x:e("x"),y:e("y"),scale:e("scale"),rotate:e("rotate"),shakeX:e("shakeX"),shakeY:e("shakeY"),shakeRotate:e("shakeRotate")}}function OM(t,e,n){const s=n.width/2,i=n.height/2,o=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*o,e.scale*o),t.translate(-s,-i)}function CM(t,e,n){const s=e.width/2,i=e.height/2,r=(t.rotate+t.shakeRotate)*Math.PI/180,o=(n.x-s)*t.scale,a=(n.y-i)*t.scale;return{x:s+t.x+t.shakeX+o*Math.cos(r)-a*Math.sin(r),y:i+t.y+t.shakeY+o*Math.sin(r)+a*Math.cos(r)}}function lp(t,e,n={},s){const i=n.length??240,r=9,o=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(o,-r,a-o,2*r),t.fillStyle="#e8b4a0",t.fillRect(a,-r,i-a,2*r),t.fillStyle="#f1dcbf",t.beginPath(),t.moveTo(0,0),t.lineTo(o,-r),t.lineTo(o,r),t.closePath(),t.fill(),t.fillStyle=n.outline??"#2f2f33",t.beginPath(),t.moveTo(0,0),t.lineTo(o*.35,-r*.35),t.lineTo(o*.35,r*.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:o,y:-r},{x:i,y:-r},{x:i,y:r},{x:o,y:r},{x:0,y:0}],[{x:o,y:-r},{x:o,y:r}],[{x:a,y:-r},{x:a,y:r}]];for(const c of l)up(t,c,s);t.restore()}function pc(t,e,n={},s){const i=n.length??90,r=n.thickness??34;t.save(),t.translate(e.x,e.y),t.rotate((n.angle??-35)*Math.PI/180);const o=-r/2;t.fillStyle=n.color??"#f4a7b9",t.fillRect(0,o,i,r),t.fillStyle="#e9edf2",t.fillRect(i*.45,o,i*.55,r),t.strokeStyle=n.outline??"#2f2f33",t.lineWidth=3,t.lineJoin="round";const a=[{x:0,y:o},{x:i,y:o},{x:i,y:-o},{x:0,y:-o},{x:0,y:o}],l=[{x:i*.45,y:o},{x:i*.45,y:-o}];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 cp=150,_M={pencil:44,eraser:30};function mc(t,e,n={},s){const i=n.tool??"pencil",r=n.skin??"#f1c9a5",o=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=cp*a*(1+.05*l);l>0&&(t.save(),t.fillStyle=o,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=St.pencilGrip,p=M=>{const x=M.fingers.thumb,S=M.fingers.index,E=M.fingers.middle,I=hp([x.points[3],S.points[3],E.points[3]]),A=hp([x.points[1],S.points[0]]),O=(x.depths[3]+S.depths[3]+E.depths[3])/3;return{pinch:I,direction:Math.atan2(A.y-I.y,A.x-I.x),depth:O}},g=Mr(f,{size:u}),m=c-p(g).direction,w=Mr(f,{size:u,angle:m*180/Math.PI}),v=p(w),k=_M[i]*a,b={x:v.pinch.x-Math.cos(c)*k,y:v.pinch.y-Math.sin(c)*k},T={x:d.x-b.x,y:d.y-b.y},$=w.axes.up;HM(t,T,{x:-$.x,y:-$.y},u,n.arm??300*a,r,n.sleeve??"#5b7db1",o),Sr(t,T,f,{size:u,angle:m*180/Math.PI,skin:r,ink:o,lineWidth:3*a,prop:{depth:v.depth,draw:()=>{t.save(),t.translate(d.x,d.y),t.scale(a,a),i==="eraser"?pc(t,{x:0,y:0},{angle:c*180/Math.PI,outline:o},s):lp(t,{x:0,y:0},{angle:c*180/Math.PI,length:190,outline:o},s),t.restore()}}})}const hp=t=>({x:t.reduce((e,n)=>e+n.x,0)/t.length,y:t.reduce((e,n)=>e+n.y,0)/t.length});function HM(t,e,n,s,i,r,o,a){const l={x:-n.y,y:n.x},c=s*.15,h=(g,m,w)=>({x:e.x+n.x*g+l.x*m*w,y:e.y+n.y*g+l.y*m*w}),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,NM(g)),m},f=Math.min(s*.55,i*.35);t.save(),t.lineJoin="round",t.lineCap="round",t.lineWidth=3*(s/cp),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=r,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(o),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 RM(t,e,n={}){const s=n.offstage??{x:2e3,y:1400},i=n.enter??450,r=n.exit??450,o=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,w)=>({x:g.x+(m.x-g.x)*w,y:g.y+(m.y-g.y)*w}),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:mr(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<=o){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<=r){const g=(e-d.end)/r;return{at:h(p(d),s,c(g)),tool:l(d),lift:c(g),drawing:!1}}return null}function LM(t,e,n,s=.08,i=32){const r=Math.PI*2*(1+s),o=[];for(let a=0;a<=i;a++){const l=-Math.PI/2+r*a/i;o.push({x:t+Math.cos(l)*n,y:e+Math.sin(l)*n})}return o}function FM(t){const{path:e}=t,n=e.map(a=>a.x),s=e.map(a=>a.y),i=Math.min(...n),r=Math.min(...s),o=t.hand===!1?void 0:t.hand===!0||t.hand===void 0?{}:t.hand;return{type:"custom",x:i,y:r,width:Math.max(1,Math.max(...n)-i),height:Math.max(1,Math.max(...s)-r),props:{draw:0},draw(a,l,c){const h=Math.min(1,Math.max(0,Number(l.props?.draw??0)));a.translate(-i,-r),a.strokeStyle=t.color??"#2f2f33",a.lineWidth=t.lineWidth??5,a.lineCap="round",a.lineJoin="round";const u=t.sketch?yr(a,t.sketch,c):void 0;h>0&&(u?t.smooth?u.curve(e,h):u.line(e,h):up(a,ts(e,h))),o&&h>0&&h<1&&mc(a,mr(e,h),o,u)}}}function NM(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(o=>o+o).join(""):e[1],[s,i,r]=[0,2,4].map(o=>parseInt(n.slice(o,o+2),16));return`rgba(${s}, ${i}, ${r}, 0)`}function up(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 po=1e5;function WM(t,e,n,s,i=6){const r=[],o=Math.max(1,Math.round(i));for(let a=0;a<=o;a++)r.push({x:a%2===0?t:t+n,y:e+s*a/o});return r}function yc(t,e,n,s){if(s<=0||e.length===0)return;const i=ts(e,s),r=n/2,o=a=>{t.beginPath(),t.rect(-po,-po,2*po,2*po),a(),t.clip("evenodd")};for(const a of i)o(()=>{t.moveTo(a.x+r,a.y),t.arc(a.x,a.y,r,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*r,d=(c.x-l.x)/h*r;o(()=>{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 DM(t,e,n,s,i){t.save(),yc(t,e,n,s),i(),t.restore()}function BM(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(r,o,a){const l=Number(o.props?.erase??0);if(r.save(),yc(r,e.path,n,l),t.draw(r,o,a),r.restore(),!i||l<=0||l>=1)return;const c=mr(e.path,l);s?mc(r,c,{...s,tool:"eraser"}):pc(r,c,i)}}}function ks(){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,r,o=300){e(n,{time:r.at,value:s},{time:r.at+(r.duration??o),value:i,...r.easing?{easing:r.easing}:{}})},last(n,s){const i=t.get(n);return i?[...i].sort((r,o)=>r.time-o.time)[i.length-1].value:s},valueAt:(n,s)=>mo(t.get(n),s),cutAfter(n,s){for(const i of n)t.set(i,(t.get(i)??[]).filter(r=>r.time<=s))},tracks(n){return[...t].filter(([,s])=>s.length>0).map(([s,i])=>({id:`${n}-${s}`,target:n,property:s,keyframes:zM(i)}))}}}function mo(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],r=n[s];return r.time===i.time?r.value:i.value+(r.value-i.value)*(e-i.time)/(r.time-i.time)}return n[n.length-1].value}function vs(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 zM(t){return[...t].sort((n,s)=>n.time-s.time).map(n=>({time:n.time,value:n.value,...n.easing?{easing:n.easing}:{}}))}const qM=.0016,jM=.6,nn=33;function Ei(t){const e=(r,o)=>`piece.${r.id}.${o}`,n=(r,o)=>({x:r.home.x+t.valueAt(e(r,"x"),o),y:r.home.y+t.valueAt(e(r,"y"),o)}),s=(r,o)=>{const a=t.keys(e(r,"x"));if(!a||a.length<2)return;const l=n(r,o-nn),c=n(r,o);return{x:(c.x-l.x)/nn,y:(c.y-l.y)/nn}},i=(r,o)=>t.cutAfter(["x","y","rotate"].map(a=>e(r,a)),o);return{at:n,cutAfter:i,follow(r,o){for(const a of o)t.push(e(r,"x"),{time:a.time,value:a.x-r.home.x}),t.push(e(r,"y"),{time:a.time,value:a.y-r.home.y})},fling(r,o){const a=n(r,o.at),l=o.velocity??s(r,o.at)??{x:.5,y:-.6},c=o.gravity??qM,h=o.duration??900,u=(o.spin??jM)*(l.x<0?-1:1),d=t.valueAt(e(r,"rotate"),o.at);i(r,o.at);for(let f=0;f<=h;f+=nn){const p=a.x+l.x*f,g=a.y+l.y*f+.5*c*f*f;t.push(e(r,"x"),{time:o.at+f,value:p-r.home.x}),t.push(e(r,"y"),{time:o.at+f,value:g-r.home.y}),t.push(e(r,"rotate"),{time:o.at+f,value:d+u*f})}t.tween(e(r,"opacity"),1,0,{at:o.at+h*.6,duration:h*.4})},move(r,o){const a=n(r,o.at);t.tween(e(r,"x"),a.x-r.home.x,o.to.x-r.home.x,o,400),t.tween(e(r,"y"),a.y-r.home.y,o.to.y-r.home.y,o,400)}}}function yo(t,e,{ground:n,every:s,floors:i}){if(i.every(k=>k.windows.length===0))return t;const r=t.find(k=>k.target===e&&k.property==="y"),o=new Ht({id:`${e}-ride`,tracks:r?[r]:[]}),a=k=>r?Number(o.getStateAtTime(k).values.get(e)?.get("y")??0):0,l=k=>{const b=n+a(k);return i.findIndex(T=>Math.abs(T.top-b)<.5)},c=(r?.keyframes??[]).map(k=>k.time),h=k=>{const b=S=>S<0?0:i[S].offset(k),T=l(k);if(T>=0)return b(T);if(Math.abs(a(k))<.5)return 0;const $=S=>l(S)>=0||Math.abs(a(S))<.5,M=[...c].reverse().find(S=>S<=k&&$(S)),x=c.find(S=>S>=k&&$(S));return M===void 0&&x===void 0?0:M===void 0?b(l(x)):x===void 0||x===M?b(l(M)):b(l(M))+(b(l(x))-b(l(M)))*(k-M)/(x-M)},u=i.flatMap(k=>k.windows),d=(k,b)=>u.some(T=>T.start<b&&T.end>k)||h(k)!==h(b),f=r?[...r.keyframes]:[{time:0,value:0}],p=[{...f[0],value:f[0].value+h(f[0].time)}],g=(k,b)=>{const T=new Set([b]);for(let $=k+s;$<b;$+=s)T.add($);for(const $ of u)for(const M of[$.start,$.end])M>k&&M<b&&T.add(M);for(const $ of[...T].sort((M,x)=>M-x))p.push({time:$,value:a($)+h($)})};for(let k=1;k<f.length;k++){const b=f[k-1].time,T=f[k].time;d(b,T)?g(b,T):p.push({...f[k],value:f[k].value+h(T)})}const m=f[f.length-1].time,w=Math.max(m,...u.map(k=>k.end));w>m&&g(m,w);const v={id:r?.id??`${e}-y`,target:e,property:"y",keyframes:p};return r?t.map(k=>k===r?v:k):[...t,v]}function _n(t){const e=t.indexOf(":");return e<0?{kind:t,rest:""}:{kind:t.slice(0,e),rest:t.slice(e+1)}}function sn(t,e,n,s){const i=Object.keys(n.anchors).map(o=>_n(o).kind),{kind:r}=_n(e);return i.includes(r)?new Error(`${t}: no anchor "${e}"${s?`: ${s}`:""} (anchors: ${Object.keys(n.anchors).join(", ")})`):new Error(`${t}: ${ft("anchor",r,i)} (anchors: ${Object.keys(n.anchors).join(", ")})`)}function Ai(t,e,n){return new Error(`${t}.edit: ${ft("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 dp={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"},bo=["wipe","fly","blur"],$i={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"}},YM=.9,KM=8;function XM(t){const e={...dp,...t.theme},n=t.code.replace(/\t/g," ").replace(/\n$/,"").split(`
|
|
56
|
+
`),s=t.fontSize??16,i=(t.lineHeight??1.6)*s,r=(t.charWidth??.6)*s,o=t.padding??12,a=t.lineNumbers===!1?0:(String(n.length).length+2)*r,l=Math.max(1,...n.map(L=>L.length)),c=t.width??o*2+a+l*r,h=o*2+n.length*i,u=t.x+o+a,d=new Set(t.hidden??[]),f=t.language??"plain";if(!ko.includes(f))throw new Error(`codePanel: ${ft("language",f,ko)}`);const p=n.map(L=>gp(L,f).flatMap(q=>Array.from(q.text,()=>e[q.kind]))),g=ks(),m=Ei(g),w=[],v=new Map,k=[],b=[],T=L=>{if(!Number.isInteger(L)||L<1||L>n.length)throw new Error(`codePanel: no line ${L} (it has ${n.length})`)},$=g.tween,M=g.last,x=(L,q,G,_,Y,st=300)=>{T(L),$(`line.${L}.${q}`,G,_,Y,st)},S=(L,q)=>w.filter(G=>G.line<L&&G.closed<=q).length,E=Mt,I=L=>t.y+o+(L-1)*i,A=L=>Array.isArray(L)?L:[L],O=(L,q,G)=>{let _=-1;for(let Y=0;Y<G;Y++)if(_=n[L-1].indexOf(q,_+1),_<0)throw new Error(`codePanel: line ${L} has no ${G>1?`${G}th `:""}"${q}"`);return _},H={};n.forEach((L,q)=>{const G=q+1;H[`line.${G}.highlight`]=0,H[`line.${G}.strike`]=0,H[`line.${G}.wipe`]=0,H[`line.${G}.reveal`]=d.has(G)?0:1,H[`line.${G}.shift`]=0});const W={type:"custom",x:t.x,y:t.y,width:c,height:h,props:H,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 UM(Object.keys(H))},actions:bc},draw(L,q){const G=q.props??{},_=C=>Number(G[C]??H[C]),Y=o+a,st=C=>o+(C-1)*i-_(`line.${C}.shift`)*i;L.fillStyle=e.background,fp(L,0,0,c,h,8),L.fill(),L.font=`${s}px ${e.font}`,L.textBaseline="middle",L.textAlign="left";const P=(C,z,K,N,F)=>{const D=n[C-1];for(let X=z;X<K;X++)D[X]!==" "&&(L.fillStyle=p[C-1][X],L.fillText(D[X],N+(X-z)*r,F))};L.save(),fp(L,0,0,c,h,8),L.clip(),n.forEach((C,z)=>{const K=z+1,N=_(`line.${K}.wipe`);if(N>=1)return;const F=st(K),D=F+i/2,X=Math.max(1,C.length)*r,B=Math.round(_(`line.${K}.reveal`)*C.length),Z=v.get(K)??{style:"wipe",from:"left"};L.save(),N>0&&GM(L,Z,N,{left:Y-a,top:F,width:a+X+r,height:i},c);const et=_(`line.${K}.highlight`);et>0&&(L.globalAlpha*=Math.min(1,et),L.fillStyle=e.highlight,L.fillRect(Y-r/2,F,X+r,i),L.globalAlpha/=Math.min(1,et)),a>0&&B>0&&(L.fillStyle=e.gutter,L.textAlign="right",L.fillText(String(K),Y-r,D),L.textAlign="left");const R=[...k.filter(rt=>rt.line===K).map(rt=>({column:rt.column,length:rt.text.length,piece:rt,insert:void 0})),...b.filter(rt=>rt.line===K).map(rt=>({column:rt.column,length:0,piece:void 0,insert:rt}))].sort((rt,ct)=>rt.column-ct.column||rt.length-ct.length);let U=0,nt=Y;for(const rt of R){P(K,U,Math.min(rt.column,B),nt,D),nt+=(rt.column-U)*r;let ct=rt.length,it="";if(rt.piece){const Q=rt.piece.written??"",ot=_(`piece.${rt.piece.id}.write`);Q&&ot>0?(it=Q.slice(0,Math.round(ot*Q.length)),ct=rt.length+(Q.length-rt.length)*Math.min(1,ot*2)):ct=rt.length*(1-_(`piece.${rt.piece.id}.away`))}else rt.insert&&(ct=rt.insert.chars*_(`insert.${rt.insert.id}.open`),rt.insert.text&&(it=rt.insert.text.slice(0,Math.round(_(`insert.${rt.insert.id}.type`)*rt.insert.text.length))));L.fillStyle=e.text;for(let Q=0;Q<it.length;Q++)it[Q]!==" "&&L.fillText(it[Q],nt+Q*r,D);nt+=ct*r,U=rt.column+rt.length}P(K,U,Math.max(U,B),nt,D);const at=_(`line.${K}.strike`);at>0&&(L.strokeStyle=e.strike,L.lineWidth=Math.max(1.5,s/10),L.beginPath(),L.moveTo(Y,D),L.lineTo(Y+X*Math.min(1,at),D),L.stroke()),L.restore()});for(const C of k){const z=_(`piece.${C.id}.opacity`);if(z<=0||_(`line.${C.line}.wipe`)>=1)continue;const K=Y+(C.column+C.text.length/2)*r+_(`piece.${C.id}.x`),N=st(C.line)+i/2+_(`piece.${C.id}.y`);L.save(),L.globalAlpha=Math.min(1,z),L.translate(K,N),L.rotate(_(`piece.${C.id}.rotate`)*Math.PI/180),P(C.line,C.column,C.column+C.text.length,-C.text.length*r/2,0),L.restore()}L.restore()}},j=L=>{const{kind:q,rest:G}=_n(L),_=Y=>sn("codePanel",L,$i,Y);if(q==="box"){if(G)throw _("box takes no arguments");return{kind:q}}if(q==="line"){if(!/^\d+$/.test(G))throw _("write it line:N");return{kind:q,n:Number(G)}}if(q==="token"){const Y=/^(\d+)(?:#(\d+))?:(.+)$/.exec(G);if(!Y)throw _("write it token:N:TEXT, or token:N#K:TEXT for the Kth");return{kind:q,n:Number(Y[1]),occurrence:Y[2]?Number(Y[2]):1,text:Y[3]}}if(q==="spot"){const Y=/^(\d+):(\d+)(?::(\d+))?$/.exec(G);if(!Y)throw _("write it spot:N:C, or spot:N:C:W for W characters");return{kind:q,n:Number(Y[1]),column:Number(Y[2]),width:Y[3]?Number(Y[3]):1}}throw _()},J=(L,q,G,_=!1)=>{const Y=Array.isArray(q)?q:[q];if(Y.length===0||_&&Y.length>1)throw new Error(`codePanel.edit: ${L} takes ${_?"one":"at least one"} ${G} anchor`);return Y.map(st=>{const P=j(st);if(P.kind!==G)throw new Error(`codePanel.edit: ${L} takes ${G} anchors (${G}:…), not "${st}"`);return P})},tt=(L,q)=>{if(typeof q.text!="string")throw new Error(`codePanel.edit: ${L} needs \`text\` (the text to write)`);return q.text},V={kind:"code",about:$i,target:W,lines:n,box:E(t.x,t.y,c,h),line(L,q=1/0){return T(L),E(u,I(L)-S(L,q)*i,Math.max(1,n[L-1].length)*r,i)},token(L,q,G=1,_=1/0){T(L);const Y=O(L,q,G);return E(u+Y*r,I(L)-S(L,_)*i,q.length*r,i)},highlight(L,q){for(const G of A(L)){const _=M(`line.${G}.highlight`,0);x(G,"highlight",_,q.on===!1?0:1,q,200)}return V},strike(L,q){for(const G of A(L))x(G,"strike",M(`line.${G}.strike`,0),1,q);return V},remove(L,q){const G=A(L),_=q.style??"wipe";if(!bo.includes(_))throw new Error(`codePanel.remove: ${ft("style",_,bo)}`);const Y=_==="wipe"?300:450,st=q.at+(q.duration??Y),P=q.close??250;for(const C of G)x(C,"wipe",0,1,{...q,easing:q.easing??(_==="fly"?"ease-in":void 0)},Y),v.set(C,{style:_,from:q.from??"left"}),w.push({line:C,closed:st+P});for(let C=1;C<=n.length;C++){if(G.includes(C))continue;const z=G.filter(N=>N<C).length;if(z===0)continue;const K=M(`line.${C}.shift`,0);x(C,"shift",K,K+z,{at:st,duration:P,easing:"ease-in-out"})}return V},type(L,q){return x(L,"reveal",0,1,{duration:n[L-1].length*45,...q}),V},piece(L,q,G=1){if(typeof L=="string"){const C=j(L);if(C.kind!=="token")throw new Error(`codePanel.piece: a piece is a word, token:N:TEXT, not "${L}"`);return V.piece(C.n,C.text,C.occurrence)}const _=L;if(q===void 0)throw new Error('codePanel.piece: which word? piece(n, text) or piece("token:N:TEXT")');T(_);const Y=O(_,q,G),st=k.find(C=>C.line===_&&C.column===Y&&C.text===q);if(st)return st;if(k.some(C=>C.line===_&&Y<C.column+C.text.length&&C.column<Y+q.length))throw new Error(`codePanel: "${q}" on line ${_} overlaps another piece`);const P={id:k.length+1,line:_,column:Y,text:q,home:V.token(_,q,G,0)};k.push(P);for(const C of["x","y","rotate","write","away"])H[`piece.${P.id}.${C}`]=0;return H[`piece.${P.id}.opacity`]=1,P},follow(L,q){return m.follow(L,q),V},fling(L,q){return m.fling(L,q),V},move(L,q){return m.move(L,q),V},write(L,q,G){return L.written=q,$(`piece.${L.id}.write`,0,1,{duration:Math.max(1,q.length)*70,...G}),V},spot(L,q,G=1,_=1/0){T(L);const Y=b.filter(st=>st.line===L&&st.column<=q&&st.at<=_).reduce((st,P)=>st+P.chars,0);return E(u+(q+Y)*r,I(L)-S(L,_)*i,G*r,i)},insert(L,q,G,_){T(L);const Y={id:b.length+1,line:L,column:q,chars:G.length,text:G,at:_.at};b.push(Y),H[`insert.${Y.id}.open`]=0,H[`insert.${Y.id}.type`]=0;const st=_.duration??G.length*70;return $(`insert.${Y.id}.open`,0,1,{at:_.at,duration:st*.6,easing:"ease-out"}),$(`insert.${Y.id}.type`,0,1,{at:_.at,duration:st}),V},drop(L,q,G,_){T(q);const Y=_.duration??250,st=q===L.line,P=_.easing??(st?"linear":"ease-out"),C=V.landing(L,q,G,_.at),z={id:b.length+1,line:q,column:G,chars:L.text.length,at:_.at};return b.push(z),H[`insert.${z.id}.open`]=0,$(`insert.${z.id}.open`,0,1,{at:_.at,duration:Y,easing:st?P:"ease-out"}),$(`piece.${L.id}.away`,M(`piece.${L.id}.away`,0),1,{at:_.at,duration:Y,easing:st?P:"ease-in-out"}),m.cutAfter(L,_.at),V.move(L,{at:_.at,duration:Y,easing:P,to:{x:C.x,y:C.y}}),$(`piece.${L.id}.rotate`,g.valueAt(`piece.${L.id}.rotate`,_.at),0,{at:_.at,duration:Y}),V},landing(L,q,G,_=1/0){const Y=V.spot(q,G,L.text.length,_),st=q===L.line&&G>L.column?L.text.length*r:0;return E(Y.left-st,Y.top,Y.width,Y.height)},ride(L,q,G){const _=n.map((Y,st)=>{const P=g.keys(`line.${st+1}.shift`)??[];return{top:I(st+1),offset:C=>-mo(P,C)*i,windows:vs(P)}});return yo(L,q,{ground:G.ground,every:G.every??nn,floors:_})},tracks:g.tracks,anchor(L,q=1/0){const G=j(L);return G.kind==="box"?V.box:G.kind==="line"?V.line(G.n,q):G.kind==="token"?V.token(G.n,G.text,G.occurrence,q):V.spot(G.n,G.column,G.width,q)},edit(L,q,G){const _=()=>J(L,q,"line").map(Y=>Y.n);if(L==="highlight")return V.highlight(_(),G);if(L==="strike")return V.strike(_(),G);if(L==="remove")return V.remove(_(),G);if(L==="type"){for(const Y of _())V.type(Y,G);return V}if(L==="insert"){const[Y]=J(L,q,"spot",!0);return V.insert(Y.n,Y.column,tt(L,G),G)}if(L==="write"||L==="drop"||L==="move"||L==="fling"){const[Y]=J(L,q,"token",!0),st=V.piece(Y.n,Y.text,Y.occurrence);if(L==="write")return V.write(st,tt(L,G),G);if(L==="fling")return V.fling(st,G);if(L==="drop"){const C=typeof G.into=="string"?j(G.into):void 0;if(C?.kind!=="spot")throw new Error("codePanel.edit: drop needs `into`, a spot anchor (spot:N:C)");return V.drop(st,C.n,C.column,G)}const P=typeof G.to=="string"?V.anchor(G.to,G.at):G.to;if(!P||typeof P.x!="number"||typeof P.y!="number")throw new Error("codePanel.edit: move needs `to`, an anchor name or { x, y }");return V.move(st,{...G,to:P})}throw Ai("codePanel",L,$i)}};return V}function GM(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 r=KM*n;if(r>.2&&"filter"in t&&(t.filter=`blur(${r.toFixed(1)}px)`),t.globalAlpha*=1-n,e.style==="fly"){const o=e.from==="right"?-1:1;t.translate(o*n*YM*i,0),t.rotate(o*n*.08)}else{const o=1+.08*n,a=s.left+s.width/2,l=s.top+s.height/2;t.translate(a,l),t.scale(o,o),t.translate(-a,-l)}}const bc={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 UM(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(([r])=>r.test(s));i&&(n[s]=i[1])}return n}function fp(t,e,n,s,i,r){t.beginPath(),t.moveTo(e+r,n),t.arcTo(e+s,n,e+s,n+i,r),t.arcTo(e+s,n+i,e,n+i,r),t.arcTo(e,n+i,e,n,r),t.arcTo(e,n,e+s,n,r),t.closePath()}const wo={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:[]};wo.typescript=[...wo.javascript,"enum","interface","type","implements","private","public","readonly","keyof","as","declare","namespace"];const ko=Object.keys(wo),VM={go:"//",rust:"//",csharp:"//",javascript:"//",typescript:"//",python:"#",plain:null};function gp(t,e){const n=new Set(wo[e]),s=VM[e],i=[],r=(a,l)=>{const c=i[i.length-1];c&&c.kind===l?c.text+=a:i.push({text:a,kind:l})};let o=0;for(;o<t.length;){const a=t[o];if(e!=="plain"&&s&&t.startsWith(s,o)){r(t.slice(o),"comment");break}if(e!=="plain"&&(a==='"'||a==="'"||a==="`")){let h=o+1;for(;h<t.length&&t[h]!==a;)h+=t[h]==="\\"?2:1;r(t.slice(o,h+1),"string"),o=h+1;continue}const l=/^[A-Za-z_][A-Za-z0-9_]*/.exec(t.slice(o));if(l){r(l[0],n.has(l[0])?"keyword":"text"),o+=l[0].length;continue}const c=/^\d[\d_.]*/.exec(t.slice(o));if(c&&e!=="plain"){r(c[0],"number"),o+=c[0].length;continue}r(a,"text"),o++}return i}const wc='"Patrick Hand", "Segoe Print", "Bradley Hand", "Comic Sans MS", "Chalkboard SE", cursive',Pi={whiteboard:{background:"#f7f7f2",frame:"#b8bcc4",ink:"#1f2a44",colors:{ink:"#1f2a44",red:"#d03b3b",blue:"#2f6fd0",green:"#2e9a52",orange:"#e07b1a"},font:wc,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:wc,stroke:.1,opacity:.9},lines:{background:"#fffdf5",frame:"#d9d3c0",ink:"#24315c",colors:{ink:"#24315c",red:"#c73b3b",blue:"#2f6fd0",green:"#2e9a52",orange:"#e07b1a",pencil:"#6b6b6b"},font:wc,stroke:.08,opacity:1,rule:{color:"#c9d6ec",spacing:1.55,margin:"#f0a3a3"}}},kc=["circle","box","underline","arrow"],He={kind:"board",create:"whiteboard({ x, y, width, height, theme?: whiteboard | chalkboard | lines, fontSize?, items: [{ id, text, at: [x, y], size?, color?, hidden? } | { id, mark: circle | box | underline | arrow, around? | from?, to?, bend?, 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"}},pp=90,mp=300,JM=.3;function ZM(t){const e=typeof t.theme=="string"?t.theme:"whiteboard";if(!(e in Pi))throw new Error(`whiteboard: ${ft("theme",e,Object.keys(Pi))}`);const n=typeof t.theme=="object"?{...Pi.whiteboard,...t.theme}:Pi[e],s=t.fontSize??28,i=t.charWidth??.55,r=b=>b===void 0?n.ink:n.colors[b]??b,o=b=>Mt(t.x+b.left,t.y+b.top,b.width,b.height),a=ks(),l=Ei(a),c={},h=new Map,u=[],d=[],f=(b,T,$,M)=>{const x=h.get(b);if(!x||x.kind!=="text")throw sn("whiteboard",M,He,`there is no text "${b}" (texts: ${p().join(", ")||"none"})`);let S=-1;for(let I=0;I<$;I++)if(S=x.item.text.indexOf(T,S+1),S<0)throw sn("whiteboard",M,He,`text "${b}" has no ${$>1?`${$}th `:""}"${T}"`);const E=x.size*i;return{column:S,box:Mt(x.box.left+S*E,x.box.top,T.length*E,x.box.height)}},p=()=>[...h.values()].filter(b=>b.kind==="text").map(b=>b.item.id),g=b=>{const{kind:T,rest:$}=_n(b),M=x=>sn("whiteboard",b,He,x);if(T==="box"){if($)throw M("box takes no arguments");return{kind:T}}if(T==="text"||T==="mark"){if(!$)throw M(`write it ${T}:ID`);return{kind:T,id:$}}if(T==="term"){const x=/^([^:#]+)(?:#(\d+))?:(.+)$/.exec($);if(!x)throw M("write it term:ID:TEXT, or term:ID#K:TEXT for the Kth");return{kind:T,id:x[1],occurrence:x[2]?Number(x[2]):1,text:x[3]}}throw M()},m=b=>{const T=g(b);if(T.kind==="box")return Mt(0,0,t.width,t.height);if(T.kind==="term")return f(T.id,T.text,T.occurrence,b).box;const $=h.get(T.id);if(!$||$.kind!==T.kind){const M=[...h.values()].filter(x=>x.kind===T.kind).map(x=>x.item.id);throw sn("whiteboard",b,He,`there is no ${T.kind} "${T.id}" (${T.kind}s: ${M.join(", ")||"none"})`)}return $.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(I=>typeof I=="number"))throw new Error(`whiteboard: text "${b.id}" needs \`at\`, [x, y] from the board's top-left`);const S=b.size??s,E=Mt(b.at[0],b.at[1],Math.max(1,b.text.length)*S*i,S*1.3);h.set(b.id,{kind:"text",item:b,size:S,color:r(b.color),box:E}),c[`text.${b.id}.write`]=b.hidden?0:1,c[`text.${b.id}.erase`]=0;continue}if(!kc.includes(b.mark))throw new Error(`whiteboard: mark "${b.id}": ${ft("mark",b.mark,kc)}`);const T=b.mark==="arrow"?["from","to"]:["around"];for(const S of T)if(typeof b[S]!="string")throw new Error(`whiteboard: ${b.mark} "${b.id}" needs \`${S}\`, a place on the board (an item before it)`);const $=new Set([b.from,b.to].filter(S=>typeof S=="string").map(S=>S.split(":")[1])),M=b.mark==="arrow"?[...h.values()].filter(S=>S.kind==="text"&&!$.has(S.item.id)).map(S=>S.box):[],x=QM(b,m,s,M);h.set(b.id,{kind:"mark",item:b,color:r(b.color),points:x,box:nS(x)}),c[`mark.${b.id}.draw`]=b.hidden?0:1,c[`mark.${b.id}.erase`]=0}const w=b=>u.filter(T=>T.item===b),v={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 sS(Object.keys(c))},actions:He.edits},draw(b,T){const $=T.props??{},M=x=>Number($[x]??c[x]??0);if(b.save(),b.fillStyle=n.background,wp(b,0,0,t.width,t.height,10),b.fill(),b.lineWidth=Math.max(4,t.width*.012),b.strokeStyle=n.frame,b.stroke(),n.rule){b.save(),b.beginPath(),wp(b,0,0,t.width,t.height,10),b.clip(),b.lineWidth=1,b.strokeStyle=n.rule.color;const x=s*(n.rule.spacing??1.55);for(let S=x;S<t.height;S+=x)b.beginPath(),b.moveTo(0,S),b.lineTo(t.width,S),b.stroke();n.rule.margin&&(b.strokeStyle=n.rule.margin,b.beginPath(),b.moveTo(s*2.2,0),b.lineTo(s*2.2,t.height),b.stroke()),b.restore()}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(),vc(b,x.box,M(`${x.kind}.${x.item.id}.erase`)),x.kind==="text"){const S=w(x.item.id),E=M(`text.${x.item.id}.write`)*x.item.text.length;b.font=`${x.size}px ${n.font}`,b.fillStyle=x.color;for(let I=0;I<Math.ceil(E);I++)x.item.text[I]===" "||S.some(A=>I>=A.column&&I<A.column+A.text.length)||(b.globalAlpha=n.opacity*Math.min(1,E-I),b.fillText(x.item.text[I],x.box.left+(I+.5)*x.size*i,x.box.y))}else bp(b,x.points,M(`mark.${x.item.id}.draw`),x.color,s*n.stroke,x.item.mark==="arrow");b.restore()}for(const x of d){const S=M(`strike.${x.id}.draw`);if(S<=0)continue;const{box:E}=x,I=E.height*.15;bp(b,[{x:E.left-3,y:E.y+I},{x:E.right+3,y:E.y-I}],S,n.colors.red??n.ink,s*n.stroke*.8,!1)}for(const x of u){const S=h.get(x.item),E=S.size*i;b.font=`${S.size}px ${n.font}`,b.fillStyle=S.color;const I=x.written;if(I){const W=M(`piece.${x.id}.write`)*I.length,j=x.home.x-t.x-I.length*E/2;for(let J=0;J<Math.ceil(W);J++)I[J]!==" "&&(b.globalAlpha=n.opacity*Math.min(1,W-J),b.fillText(I[J],j+(J+.5)*E,x.home.y-t.y))}const A=M(`piece.${x.id}.opacity`)*Math.min(1,M(`text.${x.item}.write`)*S.item.text.length-x.column);if(A<=0)continue;b.save();const O={x:x.home.x-t.x,y:x.home.y-t.y},H={x:M(`piece.${x.id}.x`),y:M(`piece.${x.id}.y`)};vc(b,Mt(O.x+H.x-x.home.width/2,O.y+H.y-x.home.height/2,x.home.width,x.home.height),M(`piece.${x.id}.erase`)),Math.hypot(H.x,H.y)<1&&vc(b,S.box,M(`text.${x.item}.erase`)),b.globalAlpha=n.opacity*Math.min(1,A),b.translate(O.x+H.x,O.y+H.y),b.rotate(M(`piece.${x.id}.rotate`)*Math.PI/180);for(let W=0;W<x.text.length;W++)x.text[W]!==" "&&b.fillText(x.text[W],(W+.5-x.text.length/2)*E,0);b.restore()}b.restore()}},k={kind:"board",about:He,target:v,box:Mt(t.x,t.y,t.width,t.height),anchor(b){return o(m(b))},piece(b){const T=g(b);if(T.kind!=="term")throw new Error(`whiteboard.piece: a piece is a term, term:ID:TEXT, not "${b}"`);const{column:$,box:M}=f(T.id,T.text,T.occurrence,b),x=u.find(E=>E.item===T.id&&E.column===$&&E.text===T.text);if(x)return x;if(u.some(E=>E.item===T.id&&$<E.column+E.text.length&&E.column<$+T.text.length))throw new Error(`whiteboard: "${T.text}" in "${T.id}" overlaps another piece`);const S={id:u.length+1,item:T.id,column:$,text:T.text,home:o(M)};u.push(S);for(const E of["x","y","rotate","erase","write"])c[`piece.${S.id}.${E}`]=0;return c[`piece.${S.id}.opacity`]=1,S},edit(b,T,$){const M=Array.isArray(T)?T:[T];if(M.length===0)throw new Error(`whiteboard.edit: ${b} takes at least one anchor`);const x=M.map(I=>({name:I,anchor:g(I)}));for(const{name:I}of x)m(I);const S=(I,A=!1)=>{const O=x.find(H=>!I.includes(H.anchor.kind));if(O)throw new Error(`whiteboard.edit: ${b} takes ${I.join(" or ")} anchors, not "${O.name}"`);if(A&&x.length>1)throw new Error(`whiteboard.edit: ${b} takes one ${I.join(" or ")} anchor`)},E=()=>k.piece(x[0].name);if(b==="write"){if(x.some(I=>I.anchor.kind==="term")){if(S(["term"],!0),typeof $.text!="string")throw new Error("whiteboard.edit: write into a term needs `text` (the new text)");const I=E();return I.written=$.text,a.tween(`piece.${I.id}.write`,0,1,{duration:Math.max(mp,$.text.length*pp),...$}),k}S(["text"]);for(const{anchor:I}of x){const A=I.id,O=h.get(A).item.text;a.tween(`text.${A}.write`,0,1,{duration:Math.max(mp,O.length*pp),...$})}return k}if(b==="draw"){S(["mark"]);for(const{anchor:I}of x)a.tween(`mark.${I.id}.draw`,0,1,{duration:500,...$});return k}if(b==="erase"){S(["text","term","mark"]);for(const I of x){const A=I.anchor.kind==="term"?`piece.${k.piece(I.name).id}.erase`:`${I.anchor.kind}.${I.anchor.id}.erase`;a.tween(A,0,1,{duration:400,...$})}return k}if(b==="strike"){S(["text","term"]);for(const I of x){const A={id:d.length+1,box:m(I.name)};d.push(A),c[`strike.${A.id}.draw`]=0,a.tween(`strike.${A.id}.draw`,0,1,{duration:250,...$})}return k}if(b==="move"){S(["term"],!0);const I=typeof $.to=="string"?k.anchor($.to):$.to;if(!I||typeof I.x!="number"||typeof I.y!="number")throw new Error("whiteboard.edit: move needs `to`, an anchor name or { x, y }");return k.move(E(),{...$,to:I})}if(b==="fling")return S(["term"],!0),k.fling(E(),$);throw Ai("whiteboard",b,He)},follow(b,T){return l.follow(b,T),k},fling(b,T){return l.fling(b,T),k},move(b,T){return l.move(b,T),k},ride(b){return b},tracks:a.tracks};return k}function QM(t,e,n,s=[]){const i=Xe(ne(t.id)),r=g=>(i.next()*2-1)*g,o=n*JM;if(t.mark==="arrow"){const g=e(t.from),m=e(t.to),w=yp(g,m,o*.6),v=yp(m,g,o*.6),k=Math.hypot(v.x-w.x,v.y-w.y),b=eS(w,v);let T=k*(.06+r(.04));if(t.bend!==void 0)T=k*t.bend;else{const x=tS(w,v,b,s,o);x!==0&&(T=x)}const $={x:(w.x+v.x)/2+b.x*T,y:(w.y+v.y)/2+b.y*T},M=[];for(let x=0;x<=24;x++){const S=x/24;M.push({x:(1-S)**2*w.x+2*(1-S)*S*$.x+S*S*v.x,y:(1-S)**2*w.y+2*(1-S)*S*$.y+S*S*v.y})}return M}const a=e(t.around);if(t.mark==="underline"){const g=a.bottom+o*.4;return[{x:a.left-o*.3,y:g+r(2)},{x:a.x,y:g+2+r(2)},{x:a.right+o*.5,y:g-1+r(3)}]}if(t.mark==="box"){const g=a.left-o,m=a.right+o,w=a.top-o*.6,v=a.bottom+o*.6,k=(T,$)=>({x:T+r(o*.2),y:$+r(o*.2)}),b=k(g,w);return[b,k(m,w),k(m,v),k(g,v),b,{x:b.x+o*.8,y:b.y+r(2)}]}const l=a.width/2+o,c=a.height/2+o*.6,h=-2.2+r(.3),u=i.next()*Math.PI*2,d=1.12,f=64,p=[];for(let g=0;g<=f*d;g++){const m=g/f,w=h+m*Math.PI*2,v=1+.035*Math.sin(m*Math.PI*4+u)+.06*m;p.push({x:a.x+Math.cos(w)*l*v,y:a.y+Math.sin(w)*c*v})}return p}function tS(t,e,n,s,i){const r=Math.hypot(e.x-t.x,e.y-t.y);if(r<1e-6)return 0;const o={x:(e.x-t.x)/r,y:(e.y-t.y)/r};let a=0,l=0;for(const c of s){const u=[{x:c.left,y:c.top},{x:c.right,y:c.top},{x:c.right,y:c.bottom},{x:c.left,y:c.bottom}].map(p=>({t:(p.x-t.x)*o.x+(p.y-t.y)*o.y,n:(p.x-t.x)*n.x+(p.y-t.y)*n.y})),d=u.some(p=>p.t>0&&p.t<r),f=u.some(p=>p.n>0)&&u.some(p=>p.n<0);!d||!f||(a=Math.max(a,...u.map(p=>p.n)),l=Math.min(l,...u.map(p=>p.n)))}return a===0&&l===0?0:a<=-l?2*(a+i):2*(l-i)}function yp(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 r=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*r,y:t.y+i*r}}function eS(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 nS(t){const e=t.map(r=>r.x),n=t.map(r=>r.y),s=Math.min(...e),i=Math.min(...n);return Mt(s,i,Math.max(...e)-s,Math.max(...n)-i)}function bp(t,e,n,s,i,r){if(n<=0||e.length<2)return;const o=[0];for(let p=1;p<e.length;p++)o.push(o[p-1]+Math.hypot(e[p].x-e[p-1].x,e[p].y-e[p-1].y));const l=o[o.length-1]*Math.min(1,n/(r?.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(o[p]<=l){t.lineTo(e[p].x,e[p].y);continue}const g=(l-o[p-1])/(o[p]-o[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(),!r||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 vc(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 wp(t,e,n,s,i,r){t.beginPath(),t.moveTo(e+r,n),t.arcTo(e+s,n,e+s,n+i,r),t.arcTo(e+s,n+i,e,n+i,r),t.arcTo(e,n+i,e,n,r),t.arcTo(e,n,e+s,n,r),t.closePath()}function sS(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(([r])=>r.test(s));i&&(n[s]=i[1])}return n}const Mc=["bar","line","pie","donut"],kp='system-ui, -apple-system, "Segoe UI", sans-serif',Ii={light:{background:"#ffffff",text:"#3b4252",grid:"#d8dee9",color:"#4c7bd9",highlight:"#e8833a",palette:["#4c7bd9","#3fa66b","#b05cc9","#d9c04c","#4cb8c4","#d95c6f","#8a7a5a","#6b7a99"],font:kp},dark:{background:"#1e2230",text:"#cdd6f4",grid:"#3a4055",color:"#89b4fa",highlight:"#fab387",palette:["#89b4fa","#a6e3a1","#cba6f7","#f9e2af","#94e2d5","#f38ba8","#b4a58a","#9399b2"],font:kp}},Hn={kind:"chart",create:"chart({ x, y, width, height, kind: bar | line | pie | donut, data: [{ id, label?, value | values: { SERIES: value }, hidden? }], series?: [{ id, label?, color? }], max?, title?, axis?: { x?, y? }, legend?, theme?: light | dark, decimals?, prefix?, suffix?, values? })",anchors:{box:"the whole chart","bar:ID":"a bar (bar charts; bar:ID:SERIES with several series), 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; point:ID:SERIES with several series), as it stands at the time","slice:ID":"a slice of a pie or donut, as it stands at the time (its middle; pulled out, it moves): point at it, make it a piece","label:ID":"its label: under the axis, or beside the slice","value:ID":"its value label: above the bar or point (value:ID:SERIES), or on the slice","legend:SERIES":"a series in the legend (several series)"},edits:{set:"bar, point or slice anchors; { at, value, duration? }: animate to a new value; its value label counts along (a pie re-shares the circle)",show:"bar, point or slice anchors given `hidden`; { at, duration?, on? }: grow a bar in from the axis, draw the line out to a point, or open a slice (on: false takes it back)",highlight:"bar, point or slice anchors; { at, duration?, on? }: colour it out (on: false clears)",pull:"slice anchors; { at, duration?, on? }: pull the slice out from the centre (on: false puts it back)"}},iS=600,rS=500,oS=200,aS=400,lS=.14,cS=Math.PI*2;function hS(t){if(!Mc.includes(t.kind))throw new Error(`chart: ${ft("kind",t.kind,Mc)}`);const e=typeof t.theme=="string"?t.theme:"light";if(!(e in Ii))throw new Error(`chart: ${ft("theme",e,Object.keys(Ii))}`);const n=typeof t.theme=="object"?{...Ii.light,...t.theme}:Ii[e];if(!Array.isArray(t.data)||t.data.length===0)throw new Error("chart: `data` needs at least one { id, value }");const s=t.kind,i=s==="pie"||s==="donut",r=Array.isArray(t.series)&&t.series.length>1,o=Array.isArray(t.series)&&t.series.length>0?t.series:[{id:"value"}];if(i&&r)throw new Error(`chart: a ${s} shows one series (got ${o.length}); make a chart per series`);const a=new Set;for(const R of o){if(typeof R?.id!="string"||!R.id||/[:.]/.test(R.id))throw new Error(`chart: every series needs an \`id\` without ":" or "." (got ${JSON.stringify(R?.id)})`);if(a.has(R.id))throw new Error(`chart: two series are called "${R.id}"`);a.add(R.id)}const l=new Map(o.map((R,U)=>[R.id,U])),c=R=>o[l.get(R)].color??(l.get(R)===0?n.color:n.palette[l.get(R)%n.palette.length]),h=new Set,u=(R,U)=>{const nt=R.values?.[U.id]??(t.series?void 0:R.value)??R.value;if(typeof nt!="number"||!Number.isFinite(nt))throw new Error(r?`chart: "${R.id}" needs a value for series "${U.id}" (\`values: { ${U.id}: … }\`)`:`chart: "${R.id}" needs a \`value\`, a number`);return nt};for(const R of t.data){if(typeof R?.id!="string"||!R.id||/[:.]/.test(R.id))throw new Error(`chart: every datum needs an \`id\` without ":" or "." (got ${JSON.stringify(R?.id)})`);if(h.has(R.id))throw new Error(`chart: two data are called "${R.id}"`);for(const U of o)u(R,U);h.add(R.id)}const d=s==="bar"?"bar":s==="line"?"point":"slice",f=Math.max(...t.data.flatMap(R=>o.map(U=>u(R,U)))),p=i?t.data.reduce((R,U)=>R+u(U,o[0]),0):t.max??vp(f*1.1);if(!i&&!(p>0))throw new Error(`chart: \`max\` must be above 0 (got ${p})`);const g=Math.max(10,Math.min(16,t.height/20)),m=r&&t.legend!==!1,w=i?void 0:t.axis?.x,v=i?void 0:t.axis?.y,k=t.title?g*2.3:g*.5,b={left:g*3.6+(v?g*1.5:0),right:t.width-g,top:(t.title?g*3:g*1.6)+(m?g*1.6:0),bottom:t.height-g*2.4-(w?g*1.4:0)},T=b.bottom-b.top,$=(b.right-b.left)/t.data.length,M=r?$*.72/o.length:$*.6,x=r?M*.86:M,S=Math.max(4,g*.35),E=T/p,I=new Map(t.data.map((R,U)=>[R.id,U])),A=R=>b.left+$*(I.get(R)+.5),O=(R,U)=>r?A(R)-$*.36+M*l.get(U)+(M-x)/2:A(R)-x/2,H=(R,U)=>O(R,U)+x/2,W=t.height-g*1.2,j={cx:t.width/2,cy:(b.top+W)/2,r:Math.max(10,Math.min(t.width/2,(W-b.top)/2)-g*2.6)},J=s==="donut"?j.r*.55:0,tt=s==="donut"?(J+j.r)/2:j.r*.62,V=new Map;if(m){let R=b.right;for(const U of[...o].reverse()){const nt=U.label??U.id,at=g*.62*nt.length+g*1.9;V.set(U.id,Mt(R-at,k,at,g*1.4)),R-=at+g*.6}}const L=ks(),q=Ei(L),G={},_=(R,U,nt)=>r?`${d}.${R}.${U}.${nt}`:`${d}.${R}.${nt}`;for(const R of t.data)for(const U of o)G[_(R.id,U.id,"value")]=u(R,U),G[_(R.id,U.id,"show")]=R.hidden?0:1,G[_(R.id,U.id,"highlight")]=0,i&&(G[_(R.id,U.id,"pull")]=0);const Y=(R,U)=>L.keys(R)?.length?mo(L.keys(R),U):G[R],st=(R,U,nt)=>Y(_(R,U,"value"),nt)*(s==="bar"?Y(_(R,U,"show"),nt):1)*E,P=R=>{const U=o[0].id,nt=t.data.map(it=>Math.max(0,R(_(it.id,U,"value")))*Math.max(0,Math.min(1,R(_(it.id,U,"show"))))),at=nt.reduce((it,Q)=>it+Q,0),rt=new Map;let ct=-Math.PI/2;return t.data.forEach((it,Q)=>{const ot=at>0?cS*nt[Q]/at:0,ht=ct+ot/2,dt=Math.max(0,Math.min(1,R(_(it.id,U,"pull"))))*j.r*lS;rt.set(it.id,{start:ct,sweep:ot,mid:ht,out:dt,centre:{x:j.cx+Math.cos(ht)*(tt+dt),y:j.cy+Math.sin(ht)*(tt+dt)}}),ct+=ot}),rt},C=R=>P(U=>Y(U,R)),z=R=>{const{kind:U,rest:nt}=_n(R),at=rt=>sn("chart",R,Hn,rt);if(U==="box"){if(nt)throw at("box takes no arguments");return{kind:"box"}}if(U==="legend"){if(!V.has(nt))throw at(m?`there is no series "${nt}" (series: ${o.map(rt=>rt.id).join(", ")})`:"only a chart with several series has a legend");return{kind:"legend",series:nt}}if(U==="bar"||U==="point"||U==="slice"||U==="label"||U==="value"){if(!nt)throw at(`write it ${U}:ID`);const rt=nt.indexOf(":"),ct=rt<0?nt:nt.slice(0,rt),it=rt<0?o[0].id:nt.slice(rt+1);if(!I.has(ct))throw at(`there is no "${ct}" (data: ${[...I.keys()].join(", ")})`);if(!a.has(it))throw at(`there is no series "${it}" (series: ${o.map(Q=>Q.id).join(", ")})`);if(U==="label"&&rt>=0)throw at("a label is one per datum: label:ID");if((U==="bar"||U==="point"||U==="slice")&&U!==d)throw at(`a ${s} chart has ${d}s, not ${U}s: ${d}:${ct}`);return{kind:U,id:ct,series:it}}throw at()},K=(R,U)=>{if(R.kind==="box")return Mt(0,0,t.width,t.height);if(R.kind==="legend")return V.get(R.series);if(i){const it=C(U).get(R.id),Q=Math.max(g*1.5,j.r*.42);if(R.kind==="slice")return Mt(it.centre.x-Q/2,it.centre.y-Q/2,Q,Q);const ot=N(it);return R.kind==="label"?ot:it.sweep>=.3?Mt(it.centre.x-g*1.6,it.centre.y-g*.65,g*3.2,g*1.3):Mt(ot.left,ot.bottom,ot.width,g*1.3)}const nt=R.kind==="label"?A(R.id):H(R.id,R.series),at=b.bottom-st(R.id,R.series,U);if(R.kind==="bar")return Mt(nt-x/2,at,x,b.bottom-at);if(R.kind==="point")return Mt(A(R.id)-S,at-S,S*2,S*2);if(R.kind==="label")return Mt(nt-$/2,b.bottom+g*.4,$,g*1.4);const rt=at-(s==="line"?S:0)-g*.3,ct=r&&s==="bar"?M:$;return Mt((s==="line"?A(R.id):nt)-ct/2,rt-g*1.3,ct,g*1.3)},N=R=>{const U=j.r+R.out+g*.9,nt={x:j.cx+Math.cos(R.mid)*U,y:j.cy+Math.sin(R.mid)*U},at=g*4.2,rt=Math.cos(R.mid),ct=rt>.2?nt.x:rt<-.2?nt.x-at:nt.x-at/2;return Mt(ct,nt.y-g*.7,at,g*1.4)},F=R=>Mt(t.x+R.left,t.y+R.top,R.width,R.height),D=R=>`${t.prefix??""}${R.toFixed(t.decimals??0)}${t.suffix??""}`,X=new Map,B={type:"custom",x:t.x,y:t.y,width:t.width,height:t.height,props:G,about:{kind:`${s} chart`,summary:`A ${s} chart of ${t.data.length} values (${t.data.map(R=>R.id).join(", ")})${r?` in ${o.length} series (${o.map(R=>R.id).join(", ")})`:""}${i?"":`, scaled to ${p}`}. Its ${d}s and labels are places in the scene (anchor()); its edits record tracks (edit(), tracks()).`,props:Object.fromEntries(Object.keys(G).map(R=>[R,fS(R)])),actions:Hn.edits},draw(R,U){const nt=U.props??{},at=it=>Number(nt[it]??G[it]??0);if(R.save(),R.fillStyle=n.background,Mp(R,0,0,t.width,t.height,8),R.fill(),R.font=`${g}px ${n.font}`,R.textBaseline="middle",t.title&&(R.fillStyle=n.text,R.textAlign="left",R.font=`600 ${g*1.2}px ${n.font}`,R.fillText(t.title,i?g:b.left,g*1.5),R.font=`${g}px ${n.font}`),m){R.textAlign="left";for(const it of o){const Q=V.get(it.id);R.fillStyle=c(it.id),Mp(R,Q.left,Q.top+g*.25,g*.9,g*.9,2),R.fill(),R.fillStyle=n.text,R.fillText(it.label??it.id,Q.left+g*1.3,Q.top+Q.height/2)}}if(i){Z(R,at),R.restore();return}R.lineWidth=1,R.textAlign="right";for(let it=0;it<=4;it++){const Q=b.bottom-T*it/4;R.strokeStyle=n.grid,R.beginPath(),R.moveTo(b.left,Q),R.lineTo(b.right,Q),R.stroke(),R.fillStyle=n.text,R.globalAlpha=.7,R.fillText(uS(p*it/4),b.left-g*.5,Q),R.globalAlpha=1}(v||w)&&(R.fillStyle=n.text,R.textAlign="center",R.globalAlpha=.85,v&&(R.save(),R.translate(g*.9,(b.top+b.bottom)/2),R.rotate(-Math.PI/2),R.fillText(v,0,0),R.restore()),w&&R.fillText(w,(b.left+b.right)/2,b.bottom+g*2.3),R.globalAlpha=1);const rt=(it,Q)=>at(_(it,Q,"value"))*(s==="bar"?at(_(it,Q,"show")):1)*E,ct=(it,Q)=>Sc(c(Q),n.highlight,at(_(it,Q,"highlight")));if(s==="line"){R.lineWidth=Math.max(2,g*.2),R.lineJoin="round",R.lineCap="round";for(const it of o)R.strokeStyle=c(it.id),R.beginPath(),t.data.forEach((Q,ot)=>{const ht={x:A(Q.id),y:b.bottom-rt(Q.id,it.id)},dt=at(_(Q.id,it.id,"show"));if(ot===0){dt>0&&R.moveTo(ht.x,ht.y);return}const bt=t.data[ot-1];if(at(_(bt.id,it.id,"show"))<1||dt<=0)return;const wt={x:A(bt.id),y:b.bottom-rt(bt.id,it.id)};R.lineTo(wt.x+(ht.x-wt.x)*dt,wt.y+(ht.y-wt.y)*dt)}),R.stroke()}R.textAlign="center";for(const it of t.data){for(const Q of o){const ot=s==="bar"?H(it.id,Q.id):A(it.id),ht=rt(it.id,Q.id),dt=at(_(it.id,Q.id,"show"));if(R.fillStyle=ct(it.id,Q.id),s==="bar"?ht>.5&&(dS(R,ot-x/2,b.bottom-ht,x,ht,Math.min(6,x/4)),R.fill()):dt>0&&(R.beginPath(),R.arc(ot,b.bottom-ht,S*Math.min(1,dt*1.5)*(1+.3*at(_(it.id,Q.id,"highlight"))),0,Math.PI*2),R.fill()),t.values!==!1&&dt>0){R.globalAlpha=Math.min(1,dt*2),R.font=`600 ${r?g*.85:g}px ${n.font}`,R.fillStyle=Sc(n.text,n.highlight,at(_(it.id,Q.id,"highlight")));const bt=b.bottom-ht-(s==="line"?S:0)-g*.95;R.fillText(D(at(_(it.id,Q.id,"value"))),ot,bt),R.font=`${g}px ${n.font}`,R.globalAlpha=1}}R.fillStyle=n.text,R.fillText(it.label??it.id,A(it.id),b.bottom+g*1.1)}R.strokeStyle=n.text,R.lineWidth=1.5,R.beginPath(),R.moveTo(b.left,b.bottom),R.lineTo(b.right,b.bottom),R.stroke(),R.restore()}};function Z(R,U){const nt=o[0].id,at=P(U);t.data.forEach((rt,ct)=>{const it=at.get(rt.id);if(it.sweep<=1e-4)return;const Q=X.get(rt.id),ot=Q?{x:U(`piece.${Q.id}.x`),y:U(`piece.${Q.id}.y`)}:{x:0,y:0},ht=Q?U(`piece.${Q.id}.rotate`)*Math.PI/180:0,dt=Q?U(`piece.${Q.id}.opacity`):1;if(dt<=0)return;R.save(),R.globalAlpha=dt;const bt={x:j.cx+Math.cos(it.mid)*it.out,y:j.cy+Math.sin(it.mid)*it.out};R.translate(it.centre.x+ot.x,it.centre.y+ot.y),R.rotate(ht),R.translate(-it.centre.x,-it.centre.y),R.beginPath(),R.arc(bt.x,bt.y,j.r,it.start,it.start+it.sweep),J>0?R.arc(bt.x,bt.y,J,it.start+it.sweep,it.start,!0):R.lineTo(bt.x,bt.y),R.closePath(),R.fillStyle=Sc(n.palette[ct%n.palette.length],n.highlight,U(_(rt.id,nt,"highlight"))),R.fill(),R.strokeStyle=n.background,R.lineWidth=Math.max(1.5,g*.15),R.stroke(),t.values!==!1&&it.sweep>=.3&&(R.fillStyle=n.background,R.font=`600 ${g}px ${n.font}`,R.textAlign="center",R.fillText(D(U(_(rt.id,nt,"value"))),it.centre.x,it.centre.y),R.font=`${g}px ${n.font}`),R.restore();const wt=N(it),pe=Math.cos(it.mid);R.globalAlpha=dt,R.fillStyle=n.text,R.textAlign=pe>.2?"left":pe<-.2?"right":"center";const Yi=pe>.2?wt.left:pe<-.2?wt.right:wt.left+wt.width/2;R.fillText(rt.label??rt.id,Yi,wt.top+wt.height/2),t.values!==!1&&it.sweep<.3&&(R.globalAlpha=dt*.8,R.fillText(D(U(_(rt.id,nt,"value"))),Yi,wt.bottom+g*.65)),R.globalAlpha=1})}const et={kind:"chart",chartKind:s,about:Hn,target:B,max:p,box:Mt(t.x,t.y,t.width,t.height),anchor(R,U=1/0){return F(K(z(R),U))},piece(R){const U=z(R);if(U.kind!=="slice")throw new Error(i?`chart: a piece is a slice, slice:ID, not "${R}"`:`chart: a ${d} is not a piece; slices of a pie or donut are (slice:ID). Change a ${d} with edit('set' | 'show' | 'highlight', …)`);const nt=X.get(U.id);if(nt)return nt;const at={id:X.size+1,datum:U.id,home:F(K(U,0))};X.set(U.id,at);for(const rt of["x","y","rotate"])G[`piece.${at.id}.${rt}`]=0;return G[`piece.${at.id}.opacity`]=1,at},edit(R,U,nt){const at=Array.isArray(U)?U:[U];if(at.length===0)throw new Error(`chart.edit: ${R} takes at least one anchor`);if(!(R in Hn.edits))throw Ai("chart",R,Hn);if(R==="pull"&&!i)throw new Error(`chart.edit: pull takes slice anchors of a pie or donut; a ${s} chart has ${d}s`);const rt=at.map(ct=>{const it=z(ct);if(it.kind!==d)throw new Error(`chart.edit: ${R} takes ${d} anchors (${d}:ID), not "${ct}"`);return it});for(const{id:ct,series:it}of rt){const Q=ot=>_(ct,it,ot);if(R==="set"){if(typeof nt.value!="number"||!Number.isFinite(nt.value))throw new Error("chart.edit: set needs `value`, a number");L.tween(Q("value"),Y(Q("value"),nt.at),nt.value,nt,iS)}else R==="show"?L.tween(Q("show"),Y(Q("show"),nt.at),nt.on===!1?0:1,nt,rS):R==="pull"?L.tween(Q("pull"),Y(Q("pull"),nt.at),nt.on===!1?0:1,nt,aS):L.tween(Q("highlight"),Y(Q("highlight"),nt.at),nt.on===!1?0:1,nt,oS)}return et},follow(R,U){return q.follow(R,U),et},fling(R,U){return q.fling(R,U),et},move(R,U){return q.move(R,U),et},ride(R,U,nt){if(s!=="bar")return R;const at=t.data.flatMap(rt=>o.map(ct=>{const it=st(rt.id,ct.id,0),Q=[...vs(L.keys(_(rt.id,ct.id,"value"))),...vs(L.keys(_(rt.id,ct.id,"show")))];return{top:t.y+b.bottom-it,offset:ot=>it-st(rt.id,ct.id,ot),windows:Q}}));return yo(R,U,{ground:nt.ground,every:nt.every??nn,floors:at})},tracks:L.tracks};return et}function vp(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 uS(t){return Number.isInteger(t)?String(t):String(Number(t.toFixed(2)))}function Sc(t,e,n){if(n<=0)return t;if(n>=1)return e;const s=o=>[1,3,5].map(a=>parseInt(o.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,r]=[s(t),s(e)];return`#${i.map((o,a)=>Math.round(o+(r[a]-o)*n).toString(16).padStart(2,"0")).join("")}`}function Mp(t,e,n,s,i,r){t.beginPath(),t.moveTo(e+r,n),t.arcTo(e+s,n,e+s,n+i,r),t.arcTo(e+s,n+i,e,n+i,r),t.arcTo(e,n+i,e,n,r),t.arcTo(e,n,e+s,n,r),t.closePath()}function dS(t,e,n,s,i,r){const o=Math.min(r,i);t.beginPath(),t.moveTo(e,n+i),t.lineTo(e,n+o),t.arcTo(e,n,e+o,n,o),t.lineTo(e+s-o,n),t.arcTo(e+s,n,e+s,n+o,o),t.lineTo(e+s,n+i),t.closePath()}function fS(t){return t.endsWith(".value")?{description:"Its value (the bar’s height, the point’s, or the slice’s share, 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, a slice opened",unit:"0..1",min:0,max:1}:t.endsWith(".pull")?{description:"How far the slice is pulled out from the centre",unit:"0..1",min:0,max:1}:t.startsWith("piece.")?{description:t.endsWith(".opacity")?"The loose slice’s opacity":t.endsWith(".rotate")?"The loose slice’s turn, degrees":"The loose slice’s offset from home, px",unit:t.endsWith(".rotate")?"degrees":t.endsWith(".opacity")?"0..1":"px"}:{description:"How much it is coloured out",unit:"0..1",min:0,max:1}}function Sp(){return{torso:[{at:0,width:.083},{at:.25,width:.08},{at:.5,width:.075},{at:.8,width:.085},{at:1,width:.023}],arm:[{at:0,width:.026},{at:.3,width:.024},{at:.5,width:.018},{at:.7,width:.021},{at:1,width:.012}],leg:[{at:0,width:.036},{at:.3,width:.037},{at:.5,width:.026},{at:.7,width:.029},{at:1,width:.015}]}}const Oi={youngMan:{figure:"organic",skin:"#edb98d",ink:"#53372d",headSize:.28,shoulderWidth:.074,hipWidth:.045,handSize:.078,hair:{style:"softSweep",color:"#38291f"},ears:!0,face:{style:"anime",shape:"angular",jawWidth:.83,chinWidth:.35,jawRoundness:1,eyeScale:.95,eyeAspect:1.1,nose:!0,iris:"#6a472d"},outfit:{shirt:"#bc7050",trousers:"#495a67",sleeves:"short"}},youngWoman:{figure:"organic",skin:"#f1c299",ink:"#53372d",headSize:.28,shoulderWidth:.065,hipWidth:.054,handSize:.075,body:{torso:[{at:0,width:.098},{at:.18,width:.097},{at:.44,width:.061},{at:.7,width:.087},{at:.85,width:.09},{at:1,width:.024}]},hair:{style:"flowingBob",color:"#38291f"},ears:!0,face:{style:"anime",shape:"angular",jawWidth:.78,chinWidth:.32,jawRoundness:1,eyeScale:.95,eyeAspect:1.1,nose:!0,iris:"#6a472d",lashes:!0},outfit:{shirt:"#72958b",trousers:"#6b6888",sleeves:"short",bottom:"skirt"}},childBoy:{figure:"organic",height:230,skin:"#edb98d",ink:"#53372d",headSize:.36,shoulderWidth:.052,hipWidth:.038,legLength:.82,armLength:.8,handSize:.074,body:Sp(),hair:{style:"softSweep",color:"#38291f"},ears:!0,face:{style:"anime",shape:"round",eyeScale:1,eyeAspect:1.1,nose:!0,iris:"#6a472d"},outfit:{shirt:"#d99843",trousers:"#497b91",sleeves:"short",bottom:"shorts"}},childGirl:{figure:"organic",height:225,skin:"#f1c299",ink:"#53372d",headSize:.36,shoulderWidth:.052,hipWidth:.038,legLength:.82,armLength:.8,handSize:.074,body:Sp(),hair:{style:"flowingBob",color:"#38291f"},ears:!0,face:{style:"anime",shape:"round",eyeScale:1,eyeAspect:1.1,nose:!0,iris:"#6a472d",lashes:!0},outfit:{shirt:"#ae7396",trousers:"#648769",sleeves:"short",bottom:"skirt"}}};function gS(t,e={}){if(!Object.prototype.hasOwnProperty.call(Oi,t))throw new Error(`softCartoonCharacter: unknown actor '${t}'`);const n=Oi[t];return ps({...n,...e,body:{...n.body,...e.body},face:{...n.face,...e.face}})}const xp={animeBoy:{label:"Anime boy",group:"anime",scale:.68,options:{figure:"fluid",look:"clean",proportions:"thin",build:"child",headSize:.34,skin:"#f2c7a5",ink:"#302c48",ears:!0,hands:"cartoon",handStyle:"natural",hair:{style:"spiky",color:"#263c68"},face:{style:"anime",iris:"#318fa5",lashes:!1},outfit:{shirt:"#efac45",trousers:"#375a91",bottom:"shorts",shoes:"boots"}}},animeGirl:{label:"Anime girl",group:"anime",scale:.68,options:{figure:"fluid",look:"clean",proportions:"thin",build:"child",headSize:.34,skin:"#e8ad8c",ink:"#302c48",ears:!0,hands:"cartoon",handStyle:"natural",hair:{style:"bob",color:"#4f304e"},face:{style:"anime",iris:"#9d5f32"},outfit:{shirt:"#e9779f",trousers:"#5c4c86",bottom:"shorts",shoes:"boots"}}},animeYoungMan:{label:"Anime young man",group:"anime",scale:1,options:{figure:"fluid",look:"clean",proportions:"thin",build:"tall",headSize:.23,skin:"#efbf9c",ink:"#302c48",ears:!0,hands:"cartoon",handStyle:"natural",hair:{style:"spiky",color:"#243552"},face:{style:"anime",iris:"#507bcc",lashes:!1},outfit:{shirt:"#57bbc0",trousers:"#334967",sleeves:"long",over:"hoodie",overColor:"#57bbc0",shoes:"boots"}}},animeYoungWoman:{label:"Anime young woman",group:"anime",scale:1,options:{figure:"fluid",look:"clean",proportions:"thin",build:"slim",headSize:.23,skin:"#f3cbb4",ink:"#302c48",ears:!0,hands:"cartoon",handStyle:"natural",hair:{style:"highPonytail",color:"#773853"},face:{style:"anime",iris:"#9163c4"},outfit:{shirt:"#ae7cda",trousers:"#35456c",sleeves:"long",shoes:"boots"}}},animeMan:{label:"Anime man",group:"anime",scale:1,options:{figure:"fluid",look:"clean",proportions:"thin",build:"broad",headSize:.23,skin:"#b67f62",ink:"#302c48",ears:!0,hands:"cartoon",handStyle:"natural",hair:{style:"sidePart",color:"#302839"},face:{style:"anime",iris:"#9b713b",lashes:!1},outfit:{shirt:"#677aab",trousers:"#343848",sleeves:"long",collar:!0,shoes:"boots"}}},animeWoman:{label:"Anime woman",group:"anime",scale:1,options:{figure:"fluid",look:"clean",proportions:"thin",build:"standard",headSize:.23,skin:"#d59a73",ink:"#302c48",ears:!0,hands:"cartoon",handStyle:"natural",hair:{style:"shoulderWaves",color:"#382c4c"},face:{style:"anime",iris:"#2b8f82"},outfit:{shirt:"#df6c79",trousers:"#46506c",sleeves:"long",bottom:"skirt",shoes:"boots"}}},animeOlderMan:{label:"Anime older man",group:"anime",scale:1,options:{figure:"fluid",look:"clean",proportions:"thin",build:"stocky",headSize:.25,skin:"#e0b291",ink:"#302c48",ears:!0,hands:"cartoon",handStyle:"natural",hair:{style:"receding",color:"#b8c4d1"},facialHair:{style:"shortBoxed",color:"#dae0e8"},face:{style:"anime",iris:"#557c8b",lashes:!1,ageLines:.8},outfit:{shirt:"#9c846c",trousers:"#46505c",sleeves:"long",collar:!0,shoes:"boots"}}},animeOlderWoman:{label:"Anime older woman",group:"anime",scale:1,options:{figure:"fluid",look:"clean",proportions:"thin",build:"standard",headSize:.25,skin:"#c4947b",ink:"#302c48",ears:!0,hands:"cartoon",handStyle:"natural",hair:{style:"topBun",color:"#d1d3df"},face:{style:"anime",iris:"#7a6998",ageLines:.8},outfit:{shirt:"#6d9b93",trousers:"#66597a",sleeves:"long",over:"cardigan",overColor:"#6d9b93",shoes:"boots"}}}},Tp={mangaYoungMan:{label:"Manga young man",group:"manga",scale:1,options:{figure:"fluid",look:"clean",proportions:"thin",build:"tall",headSize:.21,lineWidth:2.8,skin:"#edbf9b",ink:"#252536",ears:!0,hands:"cartoon",handStyle:"natural",hair:{style:"mangaSpikes",color:"#27354c"},face:{style:"anime",shape:"angular",jawWidth:.78,chinWidth:.16,eyeScale:.8,eyeAspect:.63,iris:"#3a9baa",lashes:!1,nose:!0},outfit:{shirt:"#c65a49",trousers:"#293c56",sleeves:"long",collar:!0,shoes:"boots"}}},mangaYoungWoman:{label:"Manga young woman",group:"manga",scale:1,options:{figure:"fluid",look:"clean",proportions:"thin",build:"slim",headSize:.21,lineWidth:2.8,skin:"#e2a482",ink:"#252536",ears:!0,hands:"cartoon",handStyle:"natural",hair:{style:"mangaSweep",color:"#683e64"},face:{style:"anime",shape:"angular",jawWidth:.69,chinWidth:.1,eyeScale:.85,eyeAspect:.72,iris:"#8462b7",nose:!0},outfit:{shirt:"#518c96",trousers:"#364361",sleeves:"long",shoes:"boots"}}},mangaRival:{label:"Manga rival",group:"manga",scale:1,options:{figure:"fluid",look:"clean",proportions:"thin",build:"broad",headSize:.21,lineWidth:2.8,skin:"#b77e5f",ink:"#252536",ears:!0,hands:"cartoon",handStyle:"natural",hair:{style:"mangaSpikes",color:"#e6e0cc",volume:.16},face:{style:"anime",shape:"angular",jawWidth:.9,chinWidth:.25,eyeScale:.75,eyeAspect:.55,iris:"#ba8445",lashes:!1,nose:!0},outfit:{shirt:"#4c4b75",trousers:"#303348",sleeves:"long",over:"hoodie",shoes:"boots"}}},mangaHeroine:{label:"Manga heroine",group:"manga",scale:1,options:{figure:"fluid",look:"clean",proportions:"thin",build:"tall",headSize:.21,lineWidth:2.8,skin:"#f0c5aa",ink:"#252536",ears:!0,hands:"cartoon",handStyle:"natural",hair:{style:"highPonytail",color:"#263647",texture:"spiky",textureAmount:.35},face:{style:"anime",shape:"angular",jawWidth:.73,chinWidth:.12,eyeScale:.83,eyeAspect:.65,iris:"#427e9b",nose:!0},outfit:{shirt:"#b65e7c",trousers:"#31405b",sleeves:"long",collar:!0,shoes:"boots"}}}},xc={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:Te.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:Te.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:Te.black},ears:!0,outfit:{shirt:"#9b5fc0",trousers:"#2f2f3a",sleeves:"long"}}},grandpa:{label:"Grandpa",group:"family",scale:.96,options:{build:"stocky",hair:{style:"receding",color:Te.gray},facialHair:{style:"shortBoxed",color:Te.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:Te.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:Te.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:Te.blond},hat:"sunHat",ears:!0,outfit:{shirt:"#d64535",trousers:"#4f6b3a",sleeves:"long"}}},...xp,...Tp};function pS(t,e=300,n={}){const s=xc[t];if(!s)throw new Error(`castMember: unknown cast member '${t}'`);return{...s.options,height:Math.round(e*s.scale),...n}}const Ci={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 mS(t,e,n){return Ci[t].spacing*Math.min(e.height,n.height)}const Ep=.075;function yS(t,e,n,s={}){const i=Ci[t];if(!i)throw new Error(`meetHands: unknown meeting '${t}' (one of ${Object.keys(Ci).join(", ")})`);const[r,o]=e.x<=n.x?[e,n]:[n,e],a=s.view==="side",l=Math.min(r.character.height,o.character.height),c={x:(r.x+o.x)/2,y:-(s.height??i.height)*l},h=(m,w)=>{const v=w?a?1:.62:a?3:3.38;let k={...lt,...m.pose,turn:v,lean:(m.pose?.lean??0)+i.lean};const b=w?1:-1,T=($,M,x)=>{k=_e(m.character,k,$,{x:c.x+M-m.x,y:c.y,depth:x})};if(t==="handOver"){const $=Ep*l;T("arm.left",-b*$*.9,$),T("arm.right",-b*$*.9,-$)}else T("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(r,!0),d=h(o,!1),f=.03*l,p=(m,w)=>{const v=fe(m.character,w),k=t==="handOver"?["hand.left","hand.right"]:["hand.right"],b=t==="handOver"?Ep*l+f:f;return k.every(T=>Math.abs(v.points[T].y-c.y)<f&&Math.abs(v.points[T].x+m.x-c.x)<b)},g=p(r,u)&&p(o,d);return e.x<=n.x?{a:u,b:d,point:c,reached:g}:{a:d,b:u,point:c,reached:g}}const vo={spacing:.3,lean:10,tilt:8};function bS(t,e){return vo.spacing*Math.min(t.height,e.height)}function wS(t,e,n={}){const[s,i]=t.x<=e.x?[t,e]:[e,t],r=n.view==="side",o=Math.min(s.character.height,i.character.height),a=(p,g,m)=>({over:{x:g.x-m*.02*o-p.x,y:-.72*o,depth:-.08*o},round:{x:g.x-m*.04*o-p.x,y:-.5*o,depth:.06*o}}),l=(p,g,m)=>{const w=m?r?1:.62:r?3:3.38,v=m?1:-1;let k={...lt,...p.pose,turn:w,lean:(p.pose?.lean??0)+vo.lean,"head.tilt":(p.pose?.["head.tilt"]??0)+v*vo.tilt};const{over:b,round:T}=a(p,g,v);return k=_e(p.character,k,"arm.right",b),k=_e(p.character,k,"arm.left",T),k},c=l(s,i,!0),h=l(i,s,!1),u=.05*o,d=(p,g,m,w)=>{const v=fe(p.character,w).points,{over:k,round:b}=a(p,g,m);return Math.hypot(v["hand.right"].x-k.x,v["hand.right"].y-k.y)<u&&Math.hypot(v["hand.left"].x-b.x,v["hand.left"].y-b.y)<u},f=d(s,i,1,c)&&d(i,s,-1,h);return t.x<=e.x?{a:c,b:h,reached:f}:{a:h,b:c,reached:f}}const Rn={spacing:.32,low:.3,high:.5,helperLean:40,helperBend:16};function kS(t,e){return Rn.spacing*Math.min(t.height,e.height)}function vS(t,e,n,s={}){const i=Math.max(0,Math.min(1,n)),r=s.view==="side",o=t.x<=e.x,a=Math.min(t.character.height,e.character.height),l={x:(t.x+e.x)/2,y:-(Rn.low+(Rn.high-Rn.low)*i)*a},c=m=>m?r?1:.62:r?3:3.38;let h={...lt,...t.pose,turn:c(o),lean:(t.pose?.lean??0)+Rn.helperLean*(1-i)+4,bend:(t.pose?.bend??0)+Rn.helperBend*(1-i),"head.nod":18*(1-i)};h=_e(t.character,h,"arm.right",{x:l.x-t.x,y:l.y});const u={...be.sitFloor,...e.pose,turn:c(!o)},d={...lt,...e.pose,turn:c(!o)};let f=Kl(u,d,i);f=_e(e.character,f,"arm.right",{x:l.x-e.x,y:l.y});const p=.04*a,g=(m,w)=>{const v=fe(m.character,w).points["hand.right"];return Math.hypot(v.x+m.x-l.x,v.y-l.y)<p};return{helper:h,sitter:f,point:l,reached:g(t,h)&&g(e,f)}}const Tc=Object.freeze({everyday:Object.freeze({shirt:"#bc7050",trousers:"#495a67",sleeves:"short",bottom:"trousers",collar:!1,tie:null}),formal:Object.freeze({top:"shirt",shirt:"#f4ede2",trousers:"#394653",sleeves:"long",bottom:"trousers",trouserStyle:"plain",collar:!0,tie:"#804453"}),casual:Object.freeze({top:"tshirt",shirt:"#648a83",trousers:"#426683",sleeves:"short",bottom:"trousers",trouserStyle:"jeans",collar:!1,tie:null})});function Ap(t,e={}){if(!Object.prototype.hasOwnProperty.call(Tc,t))throw new Error(`outfitPreset: unknown category '${t}'`);const n={...Tc[t],...e};return e.top&&e.top!=="shirt"&&(n.collar=e.collar??!1,n.tie=e.tie??null),n.top==="dress"&&(n.bottom="skirt"),n}const MS=.7,SS=50,xS=1.2,TS=.8,ES=3,AS=30,$S=.8,PS=.6,Ec=(t,e)=>Math.max(-e,Math.min(e,t)),IS=["hair.swing","hair.trail","hair.lift"];function $p(t,e){const n=e.start??0,s=e.amount??1,i=Math.max(1e-6,e.headRadius);let r=NaN,o={x:0,y:0,turn:0};const a=f=>(f!==r&&(o=t(f),r=f),o),l=f=>{const p=a(f);return p.turn*90+(p.headTurn??0)},c={start:n,end:e.end,step:e.step,stiffness:e.stiffness??70,damping:e.damping??6},h=Us(l,c),u=Us(f=>a(f).x,c),d=Us(f=>a(f).y,c);return h.map((f,p)=>{const g=a(f.time),m=f.value-l(f.time),w=u[p].value-g.x-(e.wind??0)*MS*i,v=d[p].value-g.y,k=Math.sin(g.turn*Math.PI/2),b=Math.cos(g.turn*Math.PI/2),T=m*ES+w*b/i*AS,$=-w*k/i*$S,M=-v/i*PS;return{time:f.time,swing:Ec(T*s,SS),trail:Ec($*s,xS),lift:Ec(M*s,TS)}})}function OS(t,e){if(t.length===0)return{"hair.swing":0,"hair.trail":0,"hair.lift":0};if(e<=t[0].time)return Pp(t[0]);if(e>=t[t.length-1].time)return Pp(t[t.length-1]);let n=0,s=t.length-1;for(;s-n>1;){const a=n+s>>1;t[a].time<=e?n=a:s=a}const i=t[n],r=t[s],o=r.time===i.time?0:(e-i.time)/(r.time-i.time);return{"hair.swing":i.swing+(r.swing-i.swing)*o,"hair.trail":i.trail+(r.trail-i.trail)*o,"hair.lift":i.lift+(r.lift-i.lift)*o}}const Pp=t=>({"hair.swing":t.swing,"hair.trail":t.trail,"hair.lift":t.lift}),Ms=16,CS=1500;function _S(t,e,n,s={}){const i=n.head.hair;if(!i||!kf(i))return[];const r=e.filter(v=>v.target===t),o=r.reduce((v,k)=>k.keyframes.reduce((b,T)=>Math.max(b,T.time),v),0),a=lt,l=new Set(["x","y","turn","head.turn"]),c=new Ht({id:`${t}-hair-follow`,tracks:r.filter(v=>l.has(v.property))}),h=(v,k,b)=>{const T=c.getStateAtTime(v).values.get(t)?.get(k);return typeof T=="number"?T:b},u=new Ht({id:`${t}-hair-pose`,tracks:r}),d=v=>u.getStateAtTime(v).values.get(t),f=new Map,p=v=>{const k=Math.round(v/Ms);let b=f.get(k);if(!b){const T={};for(const[M,x]of d(k*Ms)??[])T[M]=x;const $=fe(n,no(T,a,s.gaits)).head.center;f.set(k,b={x:$.x,y:$.y})}return b},g=v=>{const k=Math.floor(v/Ms),b=v/Ms-k,T=p(k*Ms),$=p((k+1)*Ms);return{x:T.x+($.x-T.x)*b,y:T.y+($.y-T.y)*b}},m=$p(v=>{const k=g(v);return{x:h(v,"x",0)+k.x,y:h(v,"y",0)+k.y,turn:h(v,"turn",a.turn??0),headTurn:h(v,"head.turn",a["head.turn"]??0)}},{start:0,end:o+(s.settle??CS),headRadius:fe(n,lt).head.rx,step:s.step,stiffness:s.stiffness,damping:s.damping,amount:s.amount,wind:s.wind}),w=[];for(const v of IS){const k=v.slice(5);let b=m.map($=>({time:$.time,value:$[k]}));if(b.every($=>Math.abs($.value)<.001))continue;const T=r.find($=>$.property===v);if(T){const $=new Ht({id:`${t}-${v}-own`,tracks:[T]}),M=x=>Number($.getStateAtTime(x).values.get(t)?.get(v)??0);b=b.map(x=>({time:x.time,value:x.value+M(x.time)}))}w.push({id:`${t}-${v}`,target:t,property:v,keyframes:b})}return w}const Ln={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 Ac(t){if(t===void 0)return Ln.full;if(typeof t=="string")return Ln[t];const{base:e,...n}=t;return{...Ln[e??"full"],...n}}const $c=160,HS=120,RS=700,Pc=60,LS=90,Mo=3200,Ss=1,Fn=1e-6;function So(t,e,n={}){const s=Ac(n.style),i=n.seed??1,r={};if(t.length===0)return r;const o=Object.keys(t[0].pose).filter(u=>t.some(d=>Math.abs(d.pose[u]-t[0].pose[u])>Fn));for(const u of o)r[u]=FS(u,t,e,s,i);const a=e.blink,l=a!==void 0&&o.includes(a);if(s.blinks&&a!==void 0&&!l&&a in t[0].pose){const u=NS(t,e,s,i,t[0].pose[a]);u.length>0&&(r[a]=u)}const{lift:c,stretch:h}=e;if(s.jumpSquash>0&&c&&h&&o.includes(c)&&!o.includes(h)&&h in t[0].pose){const u=WS(t,c,t[0].pose[h],s.jumpSquash);u.length>0&&(r[h]=u)}return r}function FS(t,e,n,s,i){const r=n.eyes.includes(t),o=n.limits[t],a=o!==void 0,l=r?-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+Ss){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],w=m-g,v=h[h.length-1].time,k=p.act!==!1;if(Math.abs(w)<=Fn){const I=p.time+(k?c(f):0);if(f===e.length-1)Math.abs(d-m)>Fn&&u(Math.max(I,v+$c),m,"ease-in-out"),d=m;else if(k&&a&&s.drift>0&&n.drift.includes(t)&&I-v>=RS){const A=ne(`${i}:${t}:${f}`)%2===0?1:-1;d=m+A*s.drift*o,u(I,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),T=Math.max(e[f-1].time+b,v);let $=p.time+b;r&&s.eyeDart>0&&($=Math.min($,T+s.eyeDart));const M=$-T;if(M<=Ss){u(p.time,m,p.easing),d=m;continue}u(T,d);const x=Math.sign(w);if(a&&s.anticipation>0&&o>0&&M>=$c){const I=d-x*Math.min(Math.abs(w)*s.anticipation,o),A=T+M*s.anticipationTime;u(A,I,"ease-in-out"),s.hold>0&&u(A+M*s.hold,I)}const S=f+1<e.length?e[f+1].time-p.time:1/0,E=Math.min(s.settle,S/2);if(a&&s.overshoot>0&&o>0&&M>=HS&&E>Ss){const I=Math.min(Math.abs(w)*s.overshoot,o);u($,m+x*I,p.easing??s.actionEase),u($+E,m,s.settleEase)}else u($,m,p.easing??s.actionEase);d=m}return h}function NS(t,e,n,s,i){const r=[],o=Pc+LS;for(let f=1;f<t.length;f++){const p=t[f-1].pose,g=t[f].pose;Object.entries(e.headTurns).some(([w,v])=>Math.abs((g[w]??0)-(p[w]??0))>v)&&t[f].act!==!1&&r.push(Math.max(t[0].time,t[f-1].time-n.eyeLead))}const a=t[0].time,l=t[t.length-1].time,c=[...r];let h=a+Mo*.6,u=0;for(;h<l;){c.some(g=>Math.abs(g-h)<Mo/2)||r.push(h);const p=(ne(`${s}:blink:${u++}`)%1e3/1e3-.5)*(Mo*.66);h+=Mo+p}r.sort((f,p)=>f-p);const d=[{time:a,value:i}];for(const f of r){const p=d[d.length-1].time;f+Pc<=p+Ss||(f>p+Ss&&d.push({time:f,value:i}),d.push({time:f+Pc,value:1,easing:"ease-in"}),d.push({time:f+o,value:i,easing:"ease-out"}))}return d.length>1?d:[]}function WS(t,e,n,s){const i=n*(1-.18*s),r=n*(1+.14*s),o=[{time:t[0].time,value:n}],a=(l,c,h)=>{const u=o[o.length-1];l<=u.time+Ss||o.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<$c||t[l].act===!1)){if(c<=Fn&&h>Fn)a(u,n),a(u+f*.2,i,"ease-out"),a(u+f*.45,r,"ease-out"),a(d,n,"ease-in-out");else if(c>Fn&&h<=Fn){const p=l+1<t.length?t[l+1].time-d:400;a(u+f*.5,n),a(d-Math.min(60,f*.15),r,"ease-in"),a(d,i,"ease-out"),a(d+Math.min(260,p/2),n,{type:"back",mode:"out",overshoot:1.4})}}}return o.length>1?o:[]}const Ip={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 DS(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 BS(){const t={},e={};for(const n of Object.keys(lt)){const s=DS(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 Op=BS();function Cp(t,e){return Object.entries(e).map(([n,s])=>({id:`${t}-${n}`,target:t,property:n,keyframes:s}))}function _p(t,e,n={}){const s=Ar(e),i=e.map((r,o)=>({time:r.time,pose:{...s[o]},easing:r.easing,act:r.act}));return Cp(t,So(i,n.rig??Ip,n))}function Hp(t,e,n={}){const s=n.rest??lt,i=Xl(e,s),r=e.map((o,a)=>({time:o.time,pose:{...s,...i[a]},easing:o.easing,act:o.act}));return Cp(t,So(r,n.rig??Op,n))}const Rp=vt.shocked,zS=vt.scared,rn={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,...Rp,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,...vt.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,...Rp,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,...vt.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:ut.leftHip,rightHip:ut.rightHip,leftKnee:0,rightKnee:0},easing:"ease-in-out"}],tremble:t=>{const e=[{after:80,pose:{...zS,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:{...ae.sad,bend:18,stretch:.92,lean:t.lean+5,turn:t.turn,sit:t.sit},easing:"ease-in-out"}]};function Ic(t,e){const n=typeof e.from=="string"?ae[e.from]:e.from??ut;return Oc(rn[t](n),{...e,from:n})}function Oc(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 _i(t,e=1){const n=rn[t](ut);return n[n.length-1].after*e}function Lp(t,e,n={}){if(e.length<2)return;const s=Math.max(1,Math.round(n.lines??3)),i=n.spacing??5,r=n.lineWidth??2,o=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,w=f/g,v=1-h/(e.length-1);t.globalAlpha=o*(1-v),t.lineWidth=r*(1-v*.7),t.beginPath(),t.moveTo(u.x+m*l,u.y+w*l),t.lineTo(d.x+m*l,d.y+w*l),t.stroke()}}t.restore()}const qS={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 jS(t,e,n,s,i={}){const r=n.stateAt;if(!r)return;const o=i.length??120,a=Math.max(2,Math.round(i.samples??8)),l=Math.max(0,n.time-o);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(al(e,{time:p,state:r(p)},s).joints)}const h=c[c.length-1].height,u=(i.threshold??1.2)*h,d=(i.parts??["hands","toes","head"]).flatMap(f=>qS[f]);for(const f of d){const p=c.map(f.at);let g=0;for(let v=1;v<p.length;v++)g+=Math.hypot(p[v].x-p[v-1].x,p[v].y-p[v-1].y);const m=g/((n.time-l)/1e3);if(m<=u)continue;const w=Math.min(1,(m-u)/(u*.5));Lp(t,p,{...i,opacity:(i.opacity??.7)*w,spacing:i.spacing??h*.02})}}function Fp(t,e,n,s={}){if(n<=0||n>=1)return;const i=s.size??40,r=s.seed??1,o=.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=ne(`${r}:puff:${a}`)%1e3/1e3,c=a-2,h=e.x+c*i*.3*o,u=e.y-i*(.06+.12*l)*o+Math.abs(c)*i*.03,d=i*(.11+.07*l)*o;t.beginPath(),t.arc(h,u,d,Math.PI*.95,Math.PI*2.05),t.stroke()}t.restore()}function YS(t,e,n,s={}){if(n<=0||n>=1)return;const i=s.size??40,r=5,o=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<r;a++){const l=-Math.PI/2+(a-(r-1)/2)*Math.PI/(r+1),c=i*(.3+.7*o),h=e.x+Math.cos(l)*c,u=e.y+Math.sin(l)*c;KS(t,h,u,i*.14,n*Math.PI+a),t.stroke()}t.restore()}function KS(t,e,n,s,i){t.beginPath();for(let r=0;r<10;r++){const o=r%2===0?s:s*.45,a=i+r*Math.PI/5-Math.PI/2,l=e+Math.cos(a)*o,c=n+Math.sin(a)*o;r===0?t.moveTo(l,c):t.lineTo(l,c)}t.closePath()}const Hi={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 Cc(t={}){return[...Object.keys(Kt),...Object.keys(ae),...Object.keys(rn),...Object.keys(Hi),...Object.keys(t.gaits??{}),...Object.keys(t.actions??{})]}function _c(t={}){const e=new Set(Cc()),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 Hc(t={}){const e={};for(const n of Object.keys(Kt))e[n]=`Walks to \`to\` in the ${n} gait, feet planted, turning round first if needed.`;for(const n of Object.keys(ae))e[n]=`Moves into the ${n} pose and holds it.`;for(const n of Object.keys(rn))e[n]=`The ${n} gag, built on the current pose.`;for(const[n,s]of Object.entries(Hi))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 xo=["do","at","for","to","toward","mood","say","pose","target","onto"],XS={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"},To=["viewer","ahead","back"],Nn=t=>typeof t=="number"&&Number.isFinite(t);function Ri(t,e={}){const n=_c(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=Cc(e),i=l=>l in Kt||l in(e.gaits??{}),r=Object.keys(vt),o=Object.keys(ut);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))xo.includes(g)||h(ft("beat field",g,xo,XS[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(ft("action",f,s));return}const p=Hi[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"||!r.includes(d.mood))&&h(ft("mood",d.mood,r)),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))o.includes(g)?Nn(m)||h(`Pose joint \`${g}\` must be a number (got ${JSON.stringify(m)}).`):h(ft("pose joint",g,o));for(const g of["at","for"]){const m=d[g];m!==void 0&&!(Nn(m)&&m>=0)&&h(`\`${g}\` is milliseconds, a number ≥ 0 (got ${JSON.stringify(m)}).`)}Nn(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&&!Nn(m)&&h(`\`${g}\` is a scene ${g==="to"?"x":"y"} in px, a number (got ${JSON.stringify(m)}).`)}if(d.toward!==void 0&&!Nn(d.toward)&&!To.includes(d.toward)&&h(`\`toward\` is a scene x or one of ${To.join(", ")}${typeof d.toward=="string"&&Gs(d.toward,To)?` (did you mean "${Gs(d.toward,To)}"?)`:""} (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"||!Nn(g.x)||!Nn(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 Rc(t,e={},n="scriptTracks"){const s=Ri(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
|
-
`)}`)}N2(Pc);function WS(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 DS(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 Op=8;function Tr(t,e={},n=0){if(n>Op)throw new Error(`scriptTracks: custom actions nest more than ${Op} 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 Tr(o,e,n+1)})}function _p(t){return t.length===0?0:Math.max(...t.map(e=>e.after))}const Oc={walk:1e3,bouncy:900,doubleBounce:1100,sneak:1600,strut:1100,tired:1500,shove:1300,run:560},BS=450,zS=2.4,qS=160,Cp=2.5,jS=200,YS=340,KS=1.1,Hp=[380,900],XS=.35,Er=300,_c=150,GS=260,US=1.2,Cc=160,Rp=400,Ri=300,VS=450,Lp=500,Hc=350,Fp=150,JS=120,Rc=180,Np=420,ZS=300,Wp=300,QS=140,Lc=150,Dp=450,t3=450,Fc=150,Bp=350,zp=400,e3=12,n3=600,qp=90,jp=400,s3=200,i3=.09,Yp=350,Re=450,Nc=1200,o3=700,Ss=320,Le=220,r3=65,a3=700,Kp=t=>t in nn,l3=t=>t in ae;function Xp(t){return Math.max(a3,Array.from(t).length*r3)}function Ar(t,e,n={}){const s={actions:n.actions,gaits:n.gaits};Ic(e,s);const i=n.gait??"walk",o=Tr(e,n.actions).map(C=>C.do==="go"?{...C,do:i}:C);Ic(o,s,"scriptTracks (after expanding custom actions)");const r=C=>Kt[C]??n.gaits?.[C],a=C=>Oc[C]??n.gaits?.[C]?.cycle??1e3,l=C=>{const Y=n.actions?.[C];return Y&&"steps"in Y?Y: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??ut,m=0,b=0;const v=[{time:0,pose:g}],k=[{time:0,value:0}],w=[{time:0,value:0}],T=[{time:0,value:0}],P=[{time:0,value:0}],S=[{time:0,value:"walk"}],x=[{time:0,value:p}],M=[],E=[],I=[],A=(C,Y,st,$)=>{g={...g,...Y},st&&(g=Ge(g,st)),v.push({time:C,pose:g,...$===!1?{act:$}:{}})},O=(C,Y,st)=>(A(C+Ss/2,{turn:0},st),x.push({time:C+Ss/2,value:p},{time:C+Ss/2+1,value:Y}),p=Y,A(C+Ss,{turn:1}),C+Ss),H=C=>C<d?-1:1,W=(C,Y,st)=>H(Y)!==p?O(C,H(Y),st):C,j=(C,Y,st,$="arm")=>{const _=$==="arm",z=me({...C,..._?{rightShoulder:0,rightElbow:0}:{rightHip:0,rightKnee:0}},{height:u,facing:p}),K=_?z.shoulders.right:z.hip,N=_?z.elbows.right:z.knees.right,F=(B,Z)=>Math.atan2(p*B,Z)*180/Math.PI,X=((F(Y-(d+K.x),st-(f+K.y))-F(N.x-K.x,N.y-K.y))%360+360)%360;return X>270?X-360:X},J=(C,Y,st,$)=>{const _=$==="arm",z=me({...C,..._?{rightShoulder:90,rightElbow:0,rightWrist:0}:{rightHip:90,rightKnee:0}},{height:u,facing:p}),K=_?z.shoulders.right:z.hip,N=_?{x:(z.hands.right.x+z.fingertips.right.x)/2,y:(z.hands.right.y+z.fingertips.right.y)/2}:z.feet.right,F=Math.hypot(N.x-K.x,N.y-K.y)*((_?n.reach?.arm:n.reach?.leg)??1),D=st-(f+K.y),X=Math.abs(D)<F?Math.sqrt(F*F-D*D):F*.1;return Y-K.x-p*X},tt=C=>{const Y=me(C,{height:u,facing:p});return{x:d+(Y.hands.right.x+Y.fingertips.right.x)/2,y:f+(Y.hands.right.y+Y.fingertips.right.y)/2}},V=(C,Y,st)=>{const $={...C,rightWrist:0,rightElbow:0,rightShoulder:j(C,Y,st)},_=me($,{height:u,facing:p}),z={x:d+_.shoulders.right.x,y:f+_.shoulders.right.y},K={x:d+_.elbows.right.x,y:f+_.elbows.right.y},N=tt($),F=Math.hypot(K.x-z.x,K.y-z.y),D=Math.hypot(N.x-K.x,N.y-K.y),X=Math.min(F+D-.01,Math.max(Math.abs(F-D)+.01,Math.hypot(Y-z.x,st-z.y))),B=nt=>nt*180/Math.PI,Z=B(Math.acos((F*F+X*X-D*D)/(2*F*X))),et=180-B(Math.acos((F*F+D*D-X*X)/(2*F*D)));let R={rightShoulder:$.rightShoulder,rightElbow:0},U=1/0;for(const nt of[1,-1])for(const at of[1,-1]){const ot={rightShoulder:$.rightShoulder+nt*Z,rightElbow:at*et},ct={...C,rightWrist:0,...ot},it=tt(ct),rt=Math.hypot(it.x-Y,it.y-st)-me(ct,{height:u,facing:p}).elbows.right.y*.001;rt<U&&(U=rt,R=ot)}return R},L=(C,Y,st)=>Math.abs(Y-d)<2?C:(k.push({time:C,value:d-c},{time:C+st,value:Y-c,easing:"ease-in-out"}),d=Y,C+st);for(const C of o){const Y=Math.max(C.at??b,b===0?0:v[v.length-1].time);let st=Y,$,_;const z=C.pose??{},K=l(C.do);if(r(C.do)){const N=C.to??d,F=N===d?p:H(N);let D=Y;F!==p?D=O(Y,F,C.mood):g.turn<1?(D=Y+Le,A(D,{turn:1,...z},C.mood)):(C.mood||C.pose)&&A(Y+Le,z,C.mood);const B=Math.abs(N-d)/xo(r(C.do),u),Z=C.for??Math.max(Le*2,B*a(C.do)),et=D+Z;S.push({time:D,value:C.do}),P.push({time:D,value:0},{time:D+Le,value:1,easing:"ease-out"}),P.push({time:et-Le,value:1},{time:et,value:0,easing:"ease-in"}),T.push({time:D,value:m},{time:et,value:m+B}),k.push({time:D,value:d-c},{time:et,value:N-c}),m+=B,d=N,A(et,{}),st=et}else if(C.do==="zip"){const N=C.to??d,F=N===d?p:H(N);let D=Y;F!==p?D=O(Y,F,C.mood):g.turn<1&&(D=Y+Le,A(D,{turn:1},C.mood));const X=Tc("windUp",{at:D,from:C.mood?Ge(g,C.mood):g});v.push(...X),g=X[X.length-1].pose;const B=D+_i("windUp"),Z=B+BS,et=Z+Math.max(qS,Math.abs(N-d)/zS);S.push({time:B,value:"run"}),P.push({time:B,value:0},{time:B+80,value:1,easing:"ease-out"},{time:et,value:1},{time:et+120,value:0}),T.push({time:B,value:m},{time:Z,value:m+Cp,easing:"ease-in"}),m+=Cp+(et-Z)/Oc.run*1.5,T.push({time:et,value:m}),k.push({time:Z,value:d-c},{time:et,value:N-c,easing:"ease-in"}),I.push({kind:"dust",time:Z,x:d,y:f,length:900}),d=N,A(et,{}),st=et}else if(C.do==="leap"){const N=C.to??d,F=C.onto??f;let D=N===d?Y:W(Y,N,C.mood);g.turn<1&&(D+=Le,A(D,{turn:1},C.mood));const X={leftShoulder:35,rightShoulder:35,leftElbow:-50,rightElbow:-50};A(D+jS,{stretch:.75,bend:12,leftHip:22,rightHip:22,...X},C.mood,!1);const B=D+YS;A(B-40,{stretch:.72},void 0,!1),A(B,{stretch:1.2,bend:-6,leftShoulder:140,rightShoulder:140,leftElbow:20,rightElbow:20,leftHip:4,rightHip:4},void 0,!1);const Z=Math.hypot(N-d,F-f),et=C.for??Math.min(Hp[1],Math.max(Hp[0],300+Z*KS)),R=Math.min(f,F)-XS*u,U=Math.sqrt(f-R),nt=Math.sqrt(F-R),at=B+et*U/(U+nt),ot=B+et;A(at,{stretch:1,bend:4,leftHip:-55,leftKnee:-80,rightHip:55,rightKnee:80,leftShoulder:110,rightShoulder:110},void 0,!1),A(ot,{stretch:.72,bend:12,leftShoulder:75,rightShoulder:75,leftElbow:0,rightElbow:0,leftHip:18,rightHip:18,leftKnee:0,rightKnee:0},void 0,!1),A(ot+180,{stretch:1.05,bend:-3},void 0,!1),A(ot+340,{stretch:1,bend:0,leftHip:ut.leftHip,rightHip:ut.rightHip,leftShoulder:ut.leftShoulder,rightShoulder:ut.rightShoulder,leftElbow:ut.leftElbow,rightElbow:ut.rightElbow},void 0,!1),k.push({time:B,value:d-c},{time:ot,value:N-c}),w.push({time:B,value:f-h},{time:at,value:R-h,easing:"ease-out-quad"},{time:ot,value:F-h,easing:"ease-in-quad"}),d=N,f=F,I.push({kind:"dust",time:ot,x:d,y:f,length:500}),st=ot+340,$=ot}else if(C.do==="point"&&C.target){const N=C.target,F=W(Y,N.x,C.mood),D={...g,...C.mood?vt[C.mood]:{},turn:Math.max(g.turn,.6),rightElbow:0,rightWrist:0,...z},X=me(D,{height:u,facing:p}).head.center,B=Math.abs(N.x-(d+X.x)),Z=N.y-(f+X.y),et=F+Re;A(et,{...D,rightShoulder:j(D,N.x,N.y),lookX:1,lookY:c3(Z/Math.max(1,Math.hypot(B,Z)))*.8}),st=et+(C.for??Nc),$=et,_=st}else if(C.do==="swipe"){const N=C.target??{x:d+p*u*.5,y:f-u*.6},F=H(N.x),D=W(Y,N.x,C.mood),X=F===1?N.left??N.x:N.right??N.x,B=F===1?N.right??N.x:N.left??N.x,Z={...g,turn:1,lean:-10,bend:-8,rightElbow:40,lookX:1,...z};A(D+Er,{...Z,rightShoulder:j(Z,d-p*u*.3,f-u*1.1)},C.mood,!1);const et={...g,lean:6,bend:4,rightElbow:0,rightWrist:0},R={...g,lean:14,bend:12,rightElbow:0,rightWrist:0};L(D,J(et,X,N.y,"arm"),Er+_c),A(D+Er+_c,{lean:-12},void 0,!1);const U=D+Er+_c+80;A(U,{...et,rightShoulder:j(et,X,N.y)},void 0,!1);const nt=U+(C.for??Math.max(GS,Math.abs(B-X)/US));k.push({time:U,value:d-c}),d=J(R,B,N.y,"arm"),k.push({time:nt,value:d-c}),A(nt,{...R,rightShoulder:j(R,B,N.y)},void 0,!1),A(nt+Cc,{lean:16,bend:14,rightShoulder:j(g,B+F*u*.4,N.y+u*.25)},void 0,!1),A(nt+Cc+Rp,{lean:0,bend:0,rightShoulder:ut.rightShoulder,rightElbow:ut.rightElbow}),st=nt+Cc+Rp,$=U,_=nt}else if(C.do==="grab"&&C.target){const N=C.target,F=W(Y,N.x,C.mood),D=N.y>f-u*.5,X={...g,turn:1,rightElbow:0,bend:D?35:0,lean:D?12:0,stretch:D?.75:1,lookX:1,lookY:D?.8:0,...z},Z=L(F,J(X,N.x,N.y,"arm"),Ri)+VS;A(Z,{...X,rightShoulder:j(X,N.x,N.y)},C.mood,!1),A(Z+120,{},void 0,!1),A(Z+Lp,{bend:0,lean:-3,stretch:1,rightShoulder:165,rightElbow:20,lookY:-.6}),st=Z+Lp+150,$=Z}else if(C.do==="throw"){const N=C.target?.x??C.to??d+p*u,F=W(Y,N,C.mood),D={...g,turn:1,lean:-12,bend:-10,rightElbow:60,stretch:.95,lookX:1,lookY:-.3,...z};A(F+Hc,{...D,rightShoulder:j(D,d-p*u*.4,f-u*1.05)},C.mood,!1),A(F+Hc+Fp,{lean:-14},void 0,!1);const X=F+Hc+Fp+JS,B={...g,lean:14,bend:12,rightElbow:0,stretch:1.04};v.push({time:X,pose:g={...B,rightShoulder:j(B,d+p*u,f-u*1.1)},easing:"ease-in",act:!1}),A(X+Rc,{lean:18,bend:14,rightShoulder:55,stretch:1},void 0,!1),A(X+Rc+Np,{lean:0,bend:0,rightShoulder:ut.rightShoulder,rightElbow:ut.rightElbow,lookY:0}),st=X+Rc+Np,$=X,_=X}else if(C.do==="kick"&&C.target){const N=C.target,F=W(Y,N.x,C.mood),D={...g,turn:1,lean:-12,bend:-6,rightKnee:0,leftShoulder:100,rightShoulder:70},X=L(F,J(D,N.x,N.y,"leg"),ZS),B={leftShoulder:70,rightShoulder:50,leftElbow:-20,rightElbow:20};A(X+Wp,{turn:1,lean:8,bend:6,rightHip:-40,rightKnee:80,lookX:1,lookY:.7,...B,...z},C.mood,!1);const Z=X+Wp+QS,et=j(D,N.x,N.y,"leg");v.push({time:Z,pose:g={...g,...D,rightHip:et},easing:"ease-in",act:!1}),A(Z+Lc,{lean:-15,rightHip:et+20},void 0,!1),A(Z+Lc+Dp,{lean:0,bend:0,rightHip:ut.rightHip,rightKnee:0,leftShoulder:ut.leftShoulder,rightShoulder:ut.rightShoulder,leftElbow:ut.leftElbow,rightElbow:ut.rightElbow,lookY:0}),st=Z+Lc+Dp,$=Z}else if(C.do==="put"&&C.target){const N=C.target,F=W(Y,N.x,C.mood),D=N.y>f-u*.5,X={...g,turn:1,rightElbow:0,rightWrist:0,bend:D?35:0,lean:D?12:0,stretch:D?.75:1,lookX:1,lookY:D?.8:0,...z},Z=L(F,J(X,N.x,N.y,"arm"),Ri)+t3;A(Z,{...X,rightShoulder:j(X,N.x,N.y)},C.mood,!1),A(Z+Fc,{},void 0,!1),A(Z+Fc+Bp,{bend:0,lean:0,stretch:1,rightShoulder:ut.rightShoulder,rightElbow:ut.rightElbow,lookY:0}),st=Z+Fc+Bp,$=Z}else if(C.do==="write"&&C.target){const N=C.target,F=N.left??N.x,D=N.right??N.x,X=W(Y,(F+D)/2,C.mood),B={...g,turn:1,rightElbow:0,rightWrist:0,...vt.thinking,lookX:1,lookY:0,...z},Z=it=>J(B,it,N.y,"arm")+p*u*.08,et=it=>{const Q=tt({...B,...V(B,it,N.y),rightWrist:0});return Math.hypot(Q.x-it,Q.y-N.y)<2},R=p===1?F:D,U=L(X,Z((F+D)/2),Ri),nt=!et(F)||!et(D),at=nt?L(U,Z(F),Ri)+zp:U+zp;A(at,{...B,...V(B,nt?F:R,N.y)},C.mood,!1);const ot=C.for??Math.max(n3,Math.abs(D-F)*e3);nt&&k.push({time:at,value:d-c});for(let it=qp,Q=0;it<=ot;it+=qp,Q++){const rt=F+(D-F)*Math.min(it,ot)/ot;nt&&(d=Z(rt),k.push({time:at+it,value:d-c}));const ht=(Q%2===0?-1:1)*u*.02;A(at+it,V(B,rt,N.y+ht),void 0,!1)}const ct=at+ot;A(ct,V(B,D,N.y),void 0,!1),A(ct+jp,{rightShoulder:ut.rightShoulder,rightElbow:ut.rightElbow,...vt.happy}),st=ct+jp,$=at,_=ct}else if(C.do==="push"&&C.target){const N=C.target,F=C.to??N.x,D=W(Y,d+(F>=N.x?1:-1),C.mood),X=p===1?N.left??N.x:N.right??N.x,B={...g,turn:1,lean:16,bend:8,rightWrist:0,leftWrist:0,lookX:1,...z},Z=J(B,X,N.y,"arm"),et=L(D,Z+p*u*.06,Ri),R=V(B,X,N.y),U={...B,...R,leftShoulder:-R.rightShoulder,leftElbow:-R.rightElbow},nt=et+s3;A(nt,U,C.mood,!1);const at=Math.abs(F-N.x),ot=nt+(C.for??Math.max(600,at/i3)),ct=at/xo("shove",u);S.push({time:nt,value:"shove"}),P.push({time:nt,value:0},{time:nt+Le,value:1,easing:"ease-out"},{time:ot-Le,value:1},{time:ot,value:0,easing:"ease-in"}),T.push({time:nt,value:m},{time:ot,value:m+ct}),m+=ct,k.push({time:nt,value:d-c},{time:ot,value:d+(F-N.x)-c}),d+=F-N.x,A(ot,{},void 0,!1),A(ot+Yp,{lean:0,bend:0,rightShoulder:ut.rightShoulder,leftShoulder:ut.leftShoulder,rightElbow:ut.rightElbow,leftElbow:ut.leftElbow}),st=ot+Yp,$=nt,_=ot}else if(K){const N=C.mood?Ge(g,C.mood):g,F=K.steps(N,C),D=Ec(F,{at:Y,from:N});v.push(...D),g=D[D.length-1].pose,st=Y+Math.max(_p(F),C.for??0)}else if(Kp(C.do)){const N=Tc(C.do,{at:Y,from:C.mood?Ge(g,C.mood):g});v.push(...N),g=N[N.length-1].pose,st=Y+_i(C.do),C.do==="take"&&I.push({kind:"dust",time:Y+900,x:d,y:f,length:500}),C.do==="land"&&I.push({kind:"dust",time:Y+120,x:d,y:f,length:500})}else if(C.do==="look"||C.do==="face"){const N=C.toward??"viewer",F=C.for??o3;if(N==="viewer")A(Y+Re,{turn:0,lookX:0,lookY:0,...z},C.mood);else if(N==="ahead")A(Y+Re,{turn:C.do==="face"?1:.6,lookX:1,...z},C.mood);else if(N==="back")A(Y+Re,{turn:.2,lookX:-1,...z},C.mood);else{const D=H(N);D!==p&&C.do==="face"?(O(Y,D,C.mood),A(Y+Ss+1,{lookX:1,...z})):D!==p?A(Y+Re,{turn:.25,lookX:-1,...z},C.mood):A(Y+Re,{turn:C.do==="face"?1:.6,lookX:1,...z},C.mood)}st=Y+Math.max(F,Re)}else if(l3(C.do)||C.do==="stand"){const N=C.do==="stand"?n.rest??ut:ae[C.do],F=N.turn!==ut.turn?N.turn:g.turn,D=C.mood?vt[C.mood]:{lookX:g.lookX,lookY:g.lookY};A(Y+Re,{...N,turn:F,...D,...z}),st=Y+(C.for??Nc)}else{const N=C.for??(C.say?Xp(C.say):Nc);(C.mood||C.pose)&&A(Y+Math.min(Re,N/2),z,C.mood),st=Y+N}if(C.say){const N=r(C.do)||Kp(C.do)||K?Y:Y+Math.min(150,(st-Y)/4),F=r(C.do)?st:Math.max(N+200,st-100);M.push({text:C.say,start:N,end:F}),C.do==="say"&&d3(v,g,N,F)}C.onto!==void 0&&C.do!=="leap"&&C.onto!==f&&(w.push({time:Y,value:f-h},{time:st,value:C.onto-h,easing:"ease-in-out"}),f=C.onto),st>v[v.length-1].time&&v.push({time:st,pose:g}),E.push({start:Y,end:st,...$!==void 0?{contact:$}:{},..._!==void 0?{release:_}:{}}),b=st}const q=Ep(t,u3(v),n),G=[{id:`${t}-x`,target:t,property:"x",keyframes:k},{id:`${t}-y`,target:t,property:"y",keyframes:w},{id:`${t}-walk`,target:t,property:"walk",keyframes:T},{id:`${t}-walking`,target:t,property:"walking",keyframes:P},{id:`${t}-gait`,target:t,property:"gait",keyframes:S},{id:`${t}-facing`,target:t,property:"facing",keyframes:x}].filter(C=>C.keyframes.length>1||C.property==="x"||C.property==="facing"&&C.keyframes[0].value===-1);return{tracks:[...dr(t,q,M,{energy:n.energy}),...G],duration:b,lines:M,keys:v,beats:E,effects:I}}const c3=t=>Math.max(-1,Math.min(1,t)),h3=30;function u3(t){const e=[];for(const n of t){const s=e[e.length-1];s&&n.time-s.time<h3?e[e.length-1]={...n,time:s.time}:e.push(n)}return e}function d3(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 Wc(t,e,n){const s=new Ht({id:`${t}-hand`,tracks:e.filter(l=>l.target===t)}),i=el({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}=nl(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 xs=["start","contact","release","end"],f3=["surface","edit","anchor","at","until"],g3=["carry"],$r=t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&"surface"in t&&"anchor"in t,p3=t=>t.then===void 0?[]:Array.isArray(t.then)?t.then:[t.then];function m3(t,e,n,s={}){const i=Gp(n,e,s).filter(d=>d.level==="error");if(i.length>0)throw new Error(`surfaceScript: ${i.length} problem(s) in the beats:
|
|
58
|
+
`)}`)}X2(Hc);function GS(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 US(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 Np=8;function Eo(t,e={},n=0){if(n>Np)throw new Error(`scriptTracks: custom actions nest more than ${Np} deep (does one build itself?)`);return t.flatMap(s=>{const i=e[s.do];if(!i||!("beats"in i))return[s];const r=i.beats(s).map((o,a)=>a===0?{...o,...s.at!==void 0&&o.at===void 0?{at:s.at}:{},...s.mood&&!o.mood?{mood:s.mood}:{},...s.say&&!o.say?{say:s.say}:{}}:o);return Eo(r,e,n+1)})}function Wp(t){return t.length===0?0:Math.max(...t.map(e=>e.after))}const Lc={walk:1e3,bouncy:900,doubleBounce:1100,sneak:1600,strut:1100,tired:1500,shove:1300,run:560},VS=450,JS=2.4,ZS=160,Dp=2.5,QS=200,t3=340,e3=1.1,Bp=[380,900],n3=.35,Ao=300,Fc=150,s3=260,i3=1.2,Nc=160,zp=400,Li=300,r3=450,qp=500,Wc=350,jp=150,o3=120,Dc=180,Yp=420,a3=300,Kp=300,l3=140,Bc=150,Xp=450,c3=450,zc=150,Gp=350,Up=400,h3=12,u3=600,Vp=90,Jp=400,d3=200,f3=.09,Zp=350,Re=450,qc=1200,g3=700,xs=320,Le=220,p3=65,m3=700,Qp=t=>t in rn,y3=t=>t in ae;function tm(t){return Math.max(m3,Array.from(t).length*p3)}function $o(t,e,n={}){const s={actions:n.actions,gaits:n.gaits};Rc(e,s);const i=n.gait??"walk",r=Eo(e,n.actions).map(_=>_.do==="go"?{..._,do:i}:_);Rc(r,s,"scriptTracks (after expanding custom actions)");const o=_=>Kt[_]??n.gaits?.[_],a=_=>Lc[_]??n.gaits?.[_]?.cycle??1e3,l=_=>{const Y=n.actions?.[_];return Y&&"steps"in Y?Y: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??ut,m=0,w=0;const v=[{time:0,pose:g}],k=[{time:0,value:0}],b=[{time:0,value:0}],T=[{time:0,value:0}],$=[{time:0,value:0}],M=[{time:0,value:"walk"}],x=[{time:0,value:p}],S=[],E=[],I=[],A=(_,Y,st,P)=>{g={...g,...Y},st&&(g=Ve(g,st)),v.push({time:_,pose:g,...P===!1?{act:P}:{}})},O=(_,Y,st)=>(A(_+xs/2,{turn:0},st),x.push({time:_+xs/2,value:p},{time:_+xs/2+1,value:Y}),p=Y,A(_+xs,{turn:1}),_+xs),H=_=>_<d?-1:1,W=(_,Y,st)=>H(Y)!==p?O(_,H(Y),st):_,j=(_,Y,st,P="arm")=>{const C=P==="arm",z=ye({..._,...C?{rightShoulder:0,rightElbow:0}:{rightHip:0,rightKnee:0}},{height:u,facing:p}),K=C?z.shoulders.right:z.hip,N=C?z.elbows.right:z.knees.right,F=(B,Z)=>Math.atan2(p*B,Z)*180/Math.PI,X=((F(Y-(d+K.x),st-(f+K.y))-F(N.x-K.x,N.y-K.y))%360+360)%360;return X>270?X-360:X},J=(_,Y,st,P)=>{const C=P==="arm",z=ye({..._,...C?{rightShoulder:90,rightElbow:0,rightWrist:0}:{rightHip:90,rightKnee:0}},{height:u,facing:p}),K=C?z.shoulders.right:z.hip,N=C?{x:(z.hands.right.x+z.fingertips.right.x)/2,y:(z.hands.right.y+z.fingertips.right.y)/2}:z.feet.right,F=Math.hypot(N.x-K.x,N.y-K.y)*((C?n.reach?.arm:n.reach?.leg)??1),D=st-(f+K.y),X=Math.abs(D)<F?Math.sqrt(F*F-D*D):F*.1;return Y-K.x-p*X},tt=_=>{const Y=ye(_,{height:u,facing:p});return{x:d+(Y.hands.right.x+Y.fingertips.right.x)/2,y:f+(Y.hands.right.y+Y.fingertips.right.y)/2}},V=(_,Y,st)=>{const P={..._,rightWrist:0,rightElbow:0,rightShoulder:j(_,Y,st)},C=ye(P,{height:u,facing:p}),z={x:d+C.shoulders.right.x,y:f+C.shoulders.right.y},K={x:d+C.elbows.right.x,y:f+C.elbows.right.y},N=tt(P),F=Math.hypot(K.x-z.x,K.y-z.y),D=Math.hypot(N.x-K.x,N.y-K.y),X=Math.min(F+D-.01,Math.max(Math.abs(F-D)+.01,Math.hypot(Y-z.x,st-z.y))),B=nt=>nt*180/Math.PI,Z=B(Math.acos((F*F+X*X-D*D)/(2*F*X))),et=180-B(Math.acos((F*F+D*D-X*X)/(2*F*D)));let R={rightShoulder:P.rightShoulder,rightElbow:0},U=1/0;for(const nt of[1,-1])for(const at of[1,-1]){const rt={rightShoulder:P.rightShoulder+nt*Z,rightElbow:at*et},ct={..._,rightWrist:0,...rt},it=tt(ct),ot=Math.hypot(it.x-Y,it.y-st)-ye(ct,{height:u,facing:p}).elbows.right.y*.001;ot<U&&(U=ot,R=rt)}return R},L=(_,Y,st)=>Math.abs(Y-d)<2?_:(k.push({time:_,value:d-c},{time:_+st,value:Y-c,easing:"ease-in-out"}),d=Y,_+st);for(const _ of r){const Y=Math.max(_.at??w,w===0?0:v[v.length-1].time);let st=Y,P,C;const z=_.pose??{},K=l(_.do);if(o(_.do)){const N=_.to??d,F=N===d?p:H(N);let D=Y;F!==p?D=O(Y,F,_.mood):g.turn<1?(D=Y+Le,A(D,{turn:1,...z},_.mood)):(_.mood||_.pose)&&A(Y+Le,z,_.mood);const B=Math.abs(N-d)/xr(o(_.do),u),Z=_.for??Math.max(Le*2,B*a(_.do)),et=D+Z;M.push({time:D,value:_.do}),$.push({time:D,value:0},{time:D+Le,value:1,easing:"ease-out"}),$.push({time:et-Le,value:1},{time:et,value:0,easing:"ease-in"}),T.push({time:D,value:m},{time:et,value:m+B}),k.push({time:D,value:d-c},{time:et,value:N-c}),m+=B,d=N,A(et,{}),st=et}else if(_.do==="zip"){const N=_.to??d,F=N===d?p:H(N);let D=Y;F!==p?D=O(Y,F,_.mood):g.turn<1&&(D=Y+Le,A(D,{turn:1},_.mood));const X=Ic("windUp",{at:D,from:_.mood?Ve(g,_.mood):g});v.push(...X),g=X[X.length-1].pose;const B=D+_i("windUp"),Z=B+VS,et=Z+Math.max(ZS,Math.abs(N-d)/JS);M.push({time:B,value:"run"}),$.push({time:B,value:0},{time:B+80,value:1,easing:"ease-out"},{time:et,value:1},{time:et+120,value:0}),T.push({time:B,value:m},{time:Z,value:m+Dp,easing:"ease-in"}),m+=Dp+(et-Z)/Lc.run*1.5,T.push({time:et,value:m}),k.push({time:Z,value:d-c},{time:et,value:N-c,easing:"ease-in"}),I.push({kind:"dust",time:Z,x:d,y:f,length:900}),d=N,A(et,{}),st=et}else if(_.do==="leap"){const N=_.to??d,F=_.onto??f;let D=N===d?Y:W(Y,N,_.mood);g.turn<1&&(D+=Le,A(D,{turn:1},_.mood));const X={leftShoulder:35,rightShoulder:35,leftElbow:-50,rightElbow:-50};A(D+QS,{stretch:.75,bend:12,leftHip:22,rightHip:22,...X},_.mood,!1);const B=D+t3;A(B-40,{stretch:.72},void 0,!1),A(B,{stretch:1.2,bend:-6,leftShoulder:140,rightShoulder:140,leftElbow:20,rightElbow:20,leftHip:4,rightHip:4},void 0,!1);const Z=Math.hypot(N-d,F-f),et=_.for??Math.min(Bp[1],Math.max(Bp[0],300+Z*e3)),R=Math.min(f,F)-n3*u,U=Math.sqrt(f-R),nt=Math.sqrt(F-R),at=B+et*U/(U+nt),rt=B+et;A(at,{stretch:1,bend:4,leftHip:-55,leftKnee:-80,rightHip:55,rightKnee:80,leftShoulder:110,rightShoulder:110},void 0,!1),A(rt,{stretch:.72,bend:12,leftShoulder:75,rightShoulder:75,leftElbow:0,rightElbow:0,leftHip:18,rightHip:18,leftKnee:0,rightKnee:0},void 0,!1),A(rt+180,{stretch:1.05,bend:-3},void 0,!1),A(rt+340,{stretch:1,bend:0,leftHip:ut.leftHip,rightHip:ut.rightHip,leftShoulder:ut.leftShoulder,rightShoulder:ut.rightShoulder,leftElbow:ut.leftElbow,rightElbow:ut.rightElbow},void 0,!1),k.push({time:B,value:d-c},{time:rt,value:N-c}),b.push({time:B,value:f-h},{time:at,value:R-h,easing:"ease-out-quad"},{time:rt,value:F-h,easing:"ease-in-quad"}),d=N,f=F,I.push({kind:"dust",time:rt,x:d,y:f,length:500}),st=rt+340,P=rt}else if(_.do==="point"&&_.target){const N=_.target,F=W(Y,N.x,_.mood),D={...g,..._.mood?vt[_.mood]:{},turn:Math.max(g.turn,.6),rightElbow:0,rightWrist:0,...z},X=ye(D,{height:u,facing:p}).head.center,B=Math.abs(N.x-(d+X.x)),Z=N.y-(f+X.y),et=F+Re;A(et,{...D,rightShoulder:j(D,N.x,N.y),lookX:1,lookY:b3(Z/Math.max(1,Math.hypot(B,Z)))*.8}),st=et+(_.for??qc),P=et,C=st}else if(_.do==="swipe"){const N=_.target??{x:d+p*u*.5,y:f-u*.6},F=H(N.x),D=W(Y,N.x,_.mood),X=F===1?N.left??N.x:N.right??N.x,B=F===1?N.right??N.x:N.left??N.x,Z={...g,turn:1,lean:-10,bend:-8,rightElbow:40,lookX:1,...z};A(D+Ao,{...Z,rightShoulder:j(Z,d-p*u*.3,f-u*1.1)},_.mood,!1);const et={...g,lean:6,bend:4,rightElbow:0,rightWrist:0},R={...g,lean:14,bend:12,rightElbow:0,rightWrist:0};L(D,J(et,X,N.y,"arm"),Ao+Fc),A(D+Ao+Fc,{lean:-12},void 0,!1);const U=D+Ao+Fc+80;A(U,{...et,rightShoulder:j(et,X,N.y)},void 0,!1);const nt=U+(_.for??Math.max(s3,Math.abs(B-X)/i3));k.push({time:U,value:d-c}),d=J(R,B,N.y,"arm"),k.push({time:nt,value:d-c}),A(nt,{...R,rightShoulder:j(R,B,N.y)},void 0,!1),A(nt+Nc,{lean:16,bend:14,rightShoulder:j(g,B+F*u*.4,N.y+u*.25)},void 0,!1),A(nt+Nc+zp,{lean:0,bend:0,rightShoulder:ut.rightShoulder,rightElbow:ut.rightElbow}),st=nt+Nc+zp,P=U,C=nt}else if(_.do==="grab"&&_.target){const N=_.target,F=W(Y,N.x,_.mood),D=N.y>f-u*.5,X={...g,turn:1,rightElbow:0,bend:D?35:0,lean:D?12:0,stretch:D?.75:1,lookX:1,lookY:D?.8:0,...z},Z=L(F,J(X,N.x,N.y,"arm"),Li)+r3;A(Z,{...X,rightShoulder:j(X,N.x,N.y)},_.mood,!1),A(Z+120,{},void 0,!1),A(Z+qp,{bend:0,lean:-3,stretch:1,rightShoulder:165,rightElbow:20,lookY:-.6}),st=Z+qp+150,P=Z}else if(_.do==="throw"){const N=_.target?.x??_.to??d+p*u,F=W(Y,N,_.mood),D={...g,turn:1,lean:-12,bend:-10,rightElbow:60,stretch:.95,lookX:1,lookY:-.3,...z};A(F+Wc,{...D,rightShoulder:j(D,d-p*u*.4,f-u*1.05)},_.mood,!1),A(F+Wc+jp,{lean:-14},void 0,!1);const X=F+Wc+jp+o3,B={...g,lean:14,bend:12,rightElbow:0,stretch:1.04};v.push({time:X,pose:g={...B,rightShoulder:j(B,d+p*u,f-u*1.1)},easing:"ease-in",act:!1}),A(X+Dc,{lean:18,bend:14,rightShoulder:55,stretch:1},void 0,!1),A(X+Dc+Yp,{lean:0,bend:0,rightShoulder:ut.rightShoulder,rightElbow:ut.rightElbow,lookY:0}),st=X+Dc+Yp,P=X,C=X}else if(_.do==="kick"&&_.target){const N=_.target,F=W(Y,N.x,_.mood),D={...g,turn:1,lean:-12,bend:-6,rightKnee:0,leftShoulder:100,rightShoulder:70},X=L(F,J(D,N.x,N.y,"leg"),a3),B={leftShoulder:70,rightShoulder:50,leftElbow:-20,rightElbow:20};A(X+Kp,{turn:1,lean:8,bend:6,rightHip:-40,rightKnee:80,lookX:1,lookY:.7,...B,...z},_.mood,!1);const Z=X+Kp+l3,et=j(D,N.x,N.y,"leg");v.push({time:Z,pose:g={...g,...D,rightHip:et},easing:"ease-in",act:!1}),A(Z+Bc,{lean:-15,rightHip:et+20},void 0,!1),A(Z+Bc+Xp,{lean:0,bend:0,rightHip:ut.rightHip,rightKnee:0,leftShoulder:ut.leftShoulder,rightShoulder:ut.rightShoulder,leftElbow:ut.leftElbow,rightElbow:ut.rightElbow,lookY:0}),st=Z+Bc+Xp,P=Z}else if(_.do==="put"&&_.target){const N=_.target,F=W(Y,N.x,_.mood),D=N.y>f-u*.5,X={...g,turn:1,rightElbow:0,rightWrist:0,bend:D?35:0,lean:D?12:0,stretch:D?.75:1,lookX:1,lookY:D?.8:0,...z},Z=L(F,J(X,N.x,N.y,"arm"),Li)+c3;A(Z,{...X,rightShoulder:j(X,N.x,N.y)},_.mood,!1),A(Z+zc,{},void 0,!1),A(Z+zc+Gp,{bend:0,lean:0,stretch:1,rightShoulder:ut.rightShoulder,rightElbow:ut.rightElbow,lookY:0}),st=Z+zc+Gp,P=Z}else if(_.do==="write"&&_.target){const N=_.target,F=N.left??N.x,D=N.right??N.x,X=W(Y,(F+D)/2,_.mood),B={...g,turn:1,rightElbow:0,rightWrist:0,...vt.thinking,lookX:1,lookY:0,...z},Z=it=>J(B,it,N.y,"arm")+p*u*.08,et=it=>{const Q=tt({...B,...V(B,it,N.y),rightWrist:0});return Math.hypot(Q.x-it,Q.y-N.y)<2},R=p===1?F:D,U=L(X,Z((F+D)/2),Li),nt=!et(F)||!et(D),at=nt?L(U,Z(F),Li)+Up:U+Up;A(at,{...B,...V(B,nt?F:R,N.y)},_.mood,!1);const rt=_.for??Math.max(u3,Math.abs(D-F)*h3);nt&&k.push({time:at,value:d-c});for(let it=Vp,Q=0;it<=rt;it+=Vp,Q++){const ot=F+(D-F)*Math.min(it,rt)/rt;nt&&(d=Z(ot),k.push({time:at+it,value:d-c}));const ht=(Q%2===0?-1:1)*u*.02;A(at+it,V(B,ot,N.y+ht),void 0,!1)}const ct=at+rt;A(ct,V(B,D,N.y),void 0,!1),A(ct+Jp,{rightShoulder:ut.rightShoulder,rightElbow:ut.rightElbow,...vt.happy}),st=ct+Jp,P=at,C=ct}else if(_.do==="push"&&_.target){const N=_.target,F=_.to??N.x,D=W(Y,d+(F>=N.x?1:-1),_.mood),X=p===1?N.left??N.x:N.right??N.x,B={...g,turn:1,lean:16,bend:8,rightWrist:0,leftWrist:0,lookX:1,...z},Z=J(B,X,N.y,"arm"),et=L(D,Z+p*u*.06,Li),R=V(B,X,N.y),U={...B,...R,leftShoulder:-R.rightShoulder,leftElbow:-R.rightElbow},nt=et+d3;A(nt,U,_.mood,!1);const at=Math.abs(F-N.x),rt=nt+(_.for??Math.max(600,at/f3)),ct=at/xr("shove",u);M.push({time:nt,value:"shove"}),$.push({time:nt,value:0},{time:nt+Le,value:1,easing:"ease-out"},{time:rt-Le,value:1},{time:rt,value:0,easing:"ease-in"}),T.push({time:nt,value:m},{time:rt,value:m+ct}),m+=ct,k.push({time:nt,value:d-c},{time:rt,value:d+(F-N.x)-c}),d+=F-N.x,A(rt,{},void 0,!1),A(rt+Zp,{lean:0,bend:0,rightShoulder:ut.rightShoulder,leftShoulder:ut.leftShoulder,rightElbow:ut.rightElbow,leftElbow:ut.leftElbow}),st=rt+Zp,P=nt,C=rt}else if(K){const N=_.mood?Ve(g,_.mood):g,F=K.steps(N,_),D=Oc(F,{at:Y,from:N});v.push(...D),g=D[D.length-1].pose,st=Y+Math.max(Wp(F),_.for??0)}else if(Qp(_.do)){const N=Ic(_.do,{at:Y,from:_.mood?Ve(g,_.mood):g});v.push(...N),g=N[N.length-1].pose,st=Y+_i(_.do),_.do==="take"&&I.push({kind:"dust",time:Y+900,x:d,y:f,length:500}),_.do==="land"&&I.push({kind:"dust",time:Y+120,x:d,y:f,length:500})}else if(_.do==="look"||_.do==="face"){const N=_.toward??"viewer",F=_.for??g3;if(N==="viewer")A(Y+Re,{turn:0,lookX:0,lookY:0,...z},_.mood);else if(N==="ahead")A(Y+Re,{turn:_.do==="face"?1:.6,lookX:1,...z},_.mood);else if(N==="back")A(Y+Re,{turn:.2,lookX:-1,...z},_.mood);else{const D=H(N);D!==p&&_.do==="face"?(O(Y,D,_.mood),A(Y+xs+1,{lookX:1,...z})):D!==p?A(Y+Re,{turn:.25,lookX:-1,...z},_.mood):A(Y+Re,{turn:_.do==="face"?1:.6,lookX:1,...z},_.mood)}st=Y+Math.max(F,Re)}else if(y3(_.do)||_.do==="stand"){const N=_.do==="stand"?n.rest??ut:ae[_.do],F=N.turn!==ut.turn?N.turn:g.turn,D=_.mood?vt[_.mood]:{lookX:g.lookX,lookY:g.lookY};A(Y+Re,{...N,turn:F,...D,...z}),st=Y+(_.for??qc)}else{const N=_.for??(_.say?tm(_.say):qc);(_.mood||_.pose)&&A(Y+Math.min(Re,N/2),z,_.mood),st=Y+N}if(_.say){const N=o(_.do)||Qp(_.do)||K?Y:Y+Math.min(150,(st-Y)/4),F=o(_.do)?st:Math.max(N+200,st-100);S.push({text:_.say,start:N,end:F}),_.do==="say"&&v3(v,g,N,F)}_.onto!==void 0&&_.do!=="leap"&&_.onto!==f&&(b.push({time:Y,value:f-h},{time:st,value:_.onto-h,easing:"ease-in-out"}),f=_.onto),st>v[v.length-1].time&&v.push({time:st,pose:g}),E.push({start:Y,end:st,...P!==void 0?{contact:P}:{},...C!==void 0?{release:C}:{}}),w=st}const q=_p(t,k3(v),n),G=[{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:T},{id:`${t}-walking`,target:t,property:"walking",keyframes:$},{id:`${t}-gait`,target:t,property:"gait",keyframes:M},{id:`${t}-facing`,target:t,property:"facing",keyframes:x}].filter(_=>_.keyframes.length>1||_.property==="x"||_.property==="facing"&&_.keyframes[0].value===-1);return{tracks:[...fo(t,q,S,{energy:n.energy}),...G],duration:w,lines:S,keys:v,beats:E,effects:I}}const b3=t=>Math.max(-1,Math.min(1,t)),w3=30;function k3(t){const e=[];for(const n of t){const s=e[e.length-1];s&&n.time-s.time<w3?e[e.length-1]={...n,time:s.time}:e.push(n)}return e}function v3(t,e,n,s){const r=t.filter(l=>l.time>n),o=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(...o,...a.filter(l=>!r.some(c=>Math.abs(c.time-l.time)<60)),...r),t.sort((l,c)=>l.time-c.time)}function jc(t,e,n){const s=new Ht({id:`${t}-hand`,tracks:e.filter(l=>l.target===t)}),i=ol({x:n.x,y:n.y,style:n.style,cast:n.cast}),r=n.side??"right",o=n.every??33,a=[];for(let l=n.start;;l=Math.min(n.end,l+o)){const{joints:c}=al(i,{time:l,state:s.getStateAtTime(l)},t),h=c.hands[r],u=c.fingertips[r];if(a.push({time:l,x:(h.x+u.x)/2,y:(h.y+u.y)/2}),l>=n.end)break}return a}const Ts=["start","contact","release","end"],M3=["surface","edit","anchor","at","until"],S3=["carry"],Po=t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&"surface"in t&&"anchor"in t,x3=t=>t.then===void 0?[]:Array.isArray(t.then)?t.then:[t.then];function T3(t,e,n,s={}){const i=em(n,e,s).filter(d=>d.level==="error");if(i.length>0)throw new Error(`surfaceScript: ${i.length} problem(s) in the beats:
|
|
59
59
|
${i.map(d=>` ${d.beat>=0?`beat ${d.beat}: `:""}${d.message}`).join(`
|
|
60
|
-
`)}`);const o=n.map(d=>Up(d,e)),r=Ar(t,o,s),a=y3(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 p3(d)){const g=w=>new Error(`surfaceScript: beat ${f} (${d.do}), ${p.edit} on ${p.surface}: ${w}`),m=(w,T)=>{const P=typeof w=="object"?w.beat:f,S=(typeof w=="object"?w.at:w)??T??"start",x=a[P][S];if(x===void 0){const M=xs.filter(E=>a[P][E]!==void 0).join(", ");throw g(`beat ${P} (${n[P].do}) has no ${S} (it has ${M})`)}return x},b=e[p.surface],v=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<v)throw g(`it ends (${k} ms) before it starts (${v} ms)`);try{if(p.edit==="carry"){const T=b.piece(p.anchor),P=Wc(t,c(r.tracks),{x:s.from??0,y:l,style:s.figureStyle??(s.height?{height:s.height}:void 0),cast:s,start:v,end:k});b.follow(T,P);continue}const w=Object.fromEntries(Object.entries(p).filter(([T])=>!f3.includes(T)));b.edit(p.edit,p.anchor,{...w,at:v,...k!==void 0?{duration:k-v}:{}})}catch(w){throw g(w.message)}}});const h=c(r.tracks),u=Object.entries(e).flatMap(([d,f])=>f.tracks(d));return{...r,tracks:[...h,...u],figureTracks:h}}function Gp(t,e,n={}){if(!Array.isArray(t))return Hi(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}: ${ft("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 (${xs.join(", ")}), not at ms; set the beat's own \`at\` to move it.`}):(typeof d!="string"||!xs.includes(d))&&s.push({level:"error",beat:c,message:`${u}: ${ft("moment",d,xs)}`})};t.forEach((c,h)=>{if(!c||typeof c!="object"||Array.isArray(c))return;const u=c;for(const f of["target","to","onto"]){if(!$r(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)})`,b=[...Object.keys(g.about.edits),...g3];if(typeof p.edit!="string"||!b.includes(p.edit)){s.push({level:"error",beat:h,message:`\`then\`: ${ft("edit",p.edit,b)}`});return}for(const v of Array.isArray(p.anchor)?p.anchor:[p.anchor])r(h,g,v,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)?Up(c,e,!0):c);return[...Hi(l,n),...s]}function Up(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 $r(t.target)&&(r.target=o(t.target)),$r(t.to)&&(r.to=o(t.to).x),$r(t.onto)&&(r.onto=o(t.onto).top),r}function y3(t,e,n){let s=0;return t.map(i=>{const o=Tr([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 b3(t){const e={actions:t.actions,gaits:t.gaits},n=$c(e);if(n.length>0)throw new Error(`persona "${t.name}": ${n.join(" ")}`);const s=[...Object.keys(Kt),...Object.keys(t.gaits??{})],i=t.gait??"walk";if(!s.includes(i))throw new Error(`persona "${t.name}": ${ft("gait",i,s)}`);if(t.mood&&!(t.mood in vt))throw new Error(`persona "${t.name}": ${ft("mood",t.mood,Object.keys(vt))}`);const o=t.acting??"snappy";if(typeof o=="string"&&!(o in Rn))throw new Error(`persona "${t.name}": ${ft("acting style",o,Object.keys(Rn))}`);if(typeof t.stance=="string"&&!(t.stance in ae))throw new Error(`persona "${t.name}": ${ft("stance",t.stance,Object.keys(ae))}`);const r=t.height??120,a=typeof t.stance=="string"?ae[t.stance]:Dt(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:u=>el({x:u.x,y:u.y,pose:l,style:{...c,...u.facing?{facing:u.facing}:{}},cast:e}),script:(u,d,f={})=>Ar(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=>Hi(u,e),handPath:(u,d,f)=>Wc(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:Pc(e),own:{actions:Object.keys(t.actions??{}),gaits:Object.keys(t.gaits??{})}})}}const w3=new Set(["x","y","walking","gait"]),Vp=.215+.205;function Jp(t,e,n=1){const{points:s}=fe(t,lt),i=s["hip.left"],o=s["knee.left"],r=s["ankle.left"],a=i&&o&&r?Math.hypot(o.x-i.x,o.y-i.y)+Math.hypot(r.x-o.x,r.y-o.y):Vp*t.height;return Jo(e,a/Vp,n)}function k3(t,e,n,s={}){const i=Ar(t,n,{...s,height:e.height,reach:s.reach??Zp(e)}),o=i.tracks.find(b=>b.property==="facing")?.keyframes??[],r=b=>{let v=s.facing??1;for(const k of o)k.time<=b&&(v=k.value);return v},a=Ao(i.keys),l=i.keys.map((b,v)=>{const k=yg(a[v]);return{time:b.time,pose:r(b.time)<0?Dd(k):k,...b.easing?{easing:b.easing}:{},...b.act===!1?{act:!1}:{}}}),{rest:c,start:h,...u}=s;S3(l,a,n,i,e,r,s);const d=Ap(t,l,u),f=dr(t,d,i.lines,{energy:s.energy}),p=i.tracks.filter(b=>w3.has(b.property)),g=i.tracks.find(b=>b.property==="walk");return{tracks:g?[...f,...p,P3(t,g,i.tracks,e,s)]:[...f,...p],duration:i.duration,lines:i.lines,keys:l,beats:i.beats,effects:i.effects}}function Zp(t){const e=kt({"arm.left.spread":90,"arm.left.elbow":0,"arm.left.bend":0,"leg.left.knee":0}),n=fe(t,e).points,s=Math.hypot(n["hand.left"].x-n["shoulder.left"].x,n["hand.left"].y-n["shoulder.left"].y),i=Math.hypot(n["toe.left"].x-n["hip.left"].x,n["toe.left"].y-n["hip.left"].y),o=me({...ut,rightShoulder:90,rightElbow:0,rightWrist:0},{height:t.height,facing:1}),r=me({...ut,rightHip:90,rightKnee:0},{height:t.height,facing:1}),a={x:(o.hands.right.x+o.fingertips.right.x)/2,y:(o.hands.right.y+o.fingertips.right.y)/2},l=Math.hypot(a.x-o.shoulders.right.x,a.y-o.shoulders.right.y),c=Math.hypot(r.feet.right.x-r.hip.x,r.feet.right.y-r.hip.y);return{arm:l>0?s/l:1,leg:c>0?i/c:1}}const v3={point:"arm",grab:"arm",put:"arm",write:"arm",swipe:"arm",push:"arm",kick:"leg"},M3=new Set(["point","grab","put","kick"]);function S3(t,e,n,s,i,o,r){const a=s.beats;if(n.length!==a.length)return;const l=new Ht({id:"placed",tracks:s.tracks.filter(h=>h.property==="x"||h.property==="y")}),c=h=>{const u=l.getStateAtTime(h).values.get(s.tracks[0]?.target??"");return{x:(r.from??0)+Number(u?.get("x")??0),y:(r.ground??0)+Number(u?.get("y")??0)}};n.forEach((h,u)=>{const d=v3[h.do],f=a[u];if(!d||f.contact===void 0||h.do!=="swipe"&&!h.target)return;const p=f.contact,g=f.release??f.contact;t.forEach((m,b)=>{if(m.time<p-1||m.time>g+1)return;const v=o(m.time),k=me(e[b],{height:i.height,facing:v<0?-1:1}),w=c(m.time),T=M3.has(h.do)&&h.target?{x:h.target.x-w.x,y:h.target.y-w.y}:void 0,P={x:(k.hands.right.x+k.fingertips.right.x)/2,y:(k.hands.right.y+k.fingertips.right.y)/2},S=T??(d==="arm"?P:k.toes.right),x=v<0?"right":"left",M=`${d}.${x}`;let E=m.pose;if(h.do==="point")E=Ce(i,E,M,S);else if(d==="arm")E=Ce(i,$3(i,E,x,S),M,S);else for(let I=0;I<3;I++){const A=fe(i,E).points,O=A[`ankle.${x}`],H=A[`toe.${x}`];E=Ce(i,E,M,{x:S.x-(H.x-O.x),y:S.y-(H.y-O.y)})}t[b]={...m,pose:E}})})}function x3(t,e){const n=kt({[`arm.${e}.spread`]:90,[`arm.${e}.elbow`]:0,[`arm.${e}.bend`]:0}),s=fe(t,n).points;return Math.hypot(s[`hand.${e}`].x-s[`shoulder.${e}`].x,s[`hand.${e}`].y-s[`shoulder.${e}`].y)}const T3=5,E3=4,A3=8;function $3(t,e,n,s){const i=x3(t,n)*.9,o=a=>{const l=fe(t,a).points[`shoulder.${n}`];return Math.hypot(s.x-l.x,s.y-l.y)<=i};if(o(e))return e;let r=e;for(let a=1;a<=A3;a++)if(r={...e,lean:(e.lean??0)+T3*a,bend:(e.bend??0)+E3*a},o(r))return r;return r}function P3(t,e,n,s,i){const o=n.find(u=>u.property==="gait"),r=o?new Ht({id:`${t}-gait-of`,tracks:[o]}):void 0,a=u=>{const d=r?.getStateAtTime(u).values.get(t)?.get("gait");if(typeof d=="string")return Kt[d]??i.gaits?.[d]??d},l=e.keyframes,c=[];let h=l[0]?.value??0;return l.forEach((u,d)=>{if(d>0){const f=l[d-1],p=a((f.time+u.time)/2),g=xo(p,s.height),m=Jp(s,p);h+=(u.value-f.value)*(m>0?g/m:1)}else h=u.value;c.push({...u,value:h})}),{...e,keyframes:c}}const mt=["rect","circle","text","line","path","image","custom"],Pr={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:mt},y:{description:"Moves it down by this much from where it was placed (an offset)",unit:"px",types:mt},opacity:{description:"How opaque it is",unit:"0..1",min:0,max:1,types:mt},rotate:{description:"Turns it clockwise about its origin",unit:"degrees",types:mt},rotateX:{description:"Tips it about the horizontal axis (3D; shows with perspective)",unit:"degrees",types:mt},rotateY:{description:"Turns it about the vertical axis (3D; shows with perspective)",unit:"degrees",types:mt},z:{description:"Depth toward the viewer (shows with perspective)",unit:"px",types:mt},perspective:{description:"Distance from the viewer: nearer parts grow, further ones shrink",unit:"px",min:1,types:mt},scale:{description:"Size, both ways",unit:"factor",types:mt},scaleX:{description:"Width factor",unit:"factor",types:mt},scaleY:{description:"Height factor",unit:"factor",types:mt},skewX:{description:"Slants it sideways",unit:"degrees",types:mt},skewY:{description:"Slants it up and down",unit:"degrees",types:mt},originX:{description:"Transform pivot across its box",unit:"% (0 left, 50 centre, 100 right)",min:0,max:100,types:mt},originY:{description:"Transform pivot down its box",unit:"% (0 top, 50 centre, 100 bottom)",min:0,max:100,types:mt},fill:{description:"Fill colour (also written fillStyle)",kind:"color",types:mt},stroke:{description:"Outline colour (also written strokeStyle)",kind:"color",types:mt},strokeWidth:{description:"Outline width (also written lineWidth)",unit:"px",min:0,types:mt},clipTop:{description:"Hides this much from the top edge, for reveals",unit:"% of its height",min:0,max:100,types:mt},clipRight:{description:"Hides this much from the right edge",unit:"% of its width",min:0,max:100,types:mt},clipBottom:{description:"Hides this much from the bottom edge",unit:"% of its height",min:0,max:100,types:mt},clipLeft:{description:"Hides this much from the left edge",unit:"% of its width",min:0,max:100,types:mt},blur:{description:"Gaussian blur",unit:"px",min:0,types:mt},brightness:{description:"Brightness factor (1 unchanged)",unit:"factor",min:0,types:mt},glow:{description:"Soft glow around it, in glowColor",unit:"px",min:0,types:mt},glowColor:{description:"Colour of the glow",kind:"color",types:mt},shadowX:{description:"Drop shadow offset right",unit:"px",types:mt},shadowY:{description:"Drop shadow offset down",unit:"px",types:mt},shadowBlur:{description:"Drop shadow softness",unit:"px",min:0,types:mt},shadowColor:{description:"Drop shadow colour",kind:"color",types:mt},shine:{description:"A highlight sweeping across the fill",unit:"0..1 (progress)",min:0,max:1,types:mt},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:mt},quaternion:{description:'A rotation as [x, y, z, w] (a track with interpolation: "slerp")',kind:"list",types:mt}},Dc={fillStyle:"fill",strokeStyle:"stroke",lineWidth:"strokeWidth",rotateZ:"rotate",motionPathX:"x",motionPathY:"y",motionPathRotate:"rotate"},I3={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 Qp(t){const e=t,n=Object.entries(Pr).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 tm(t){const e=Qp(t).properties.map(n=>n.name);return[...e,...Object.keys(Dc).filter(n=>e.includes(Dc[n]))]}function O3(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(ft("target",i.target,s));continue}const a=tm(r),l=r.type==="custom"&&r.acceptsProp?.(i.property);if(!a.includes(i.property)&&!l){o(`${i.target}: ${ft("property",i.property,a,I3[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=Pr[Dc[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 Ts=(t,e)=>t[2]<=-e;function Bc(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 em(t,e){if(t.every(s=>Ts(s,e)))return t;const n=[];return t.forEach((s,i)=>{const o=t[(i+t.length-1)%t.length],r=Ts(s,e),a=Ts(o,e);r!==a&&n.push(Bc(o,s,e)),r&&n.push(s)}),n.length>=3?n:[]}function _3(t,e){if(t.every(i=>Ts(i,e)))return[t];const n=[];let s=[];return t.forEach((i,o)=>{const r=Ts(i,e);if(o>0){const a=t[o-1],l=Ts(a,e);l&&!r?(s.push(Bc(a,i,e)),n.push(s),s=[]):!l&&r&&s.push(Bc(a,i,e))}r&&s.push(i)}),s.length>0&&n.push(s),n.filter(i=>i.length>=2)}function nm(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 C3(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 H3(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=>ie(e,s)),faces:t.faces.map(s=>({corners:s.corners,normal:n(s.normal)}))}}function Ir(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 R3(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(b=>Math.round(b*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=Ir(g,0,e[r],1)),g.length&&!f(r,e)&&(g=Ir(g,0,e[r+1],-1)),g.length&&!d(a)&&(g=Ir(g,2,n[a],1)),g.length&&!f(a,n)&&(g=Ir(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 L3=new WeakMap,F3=new WeakMap,N3=48,sm=t=>t.map(e=>Math.round(e*1e5)).join(",");function im(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>=N3&&i.clear(),i.set(n,o=s())),o}function zc(t,e){const n=sm(e);return im(L3,t,n,()=>{const s=H3(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 W3(t,e){const n=t.map(h=>({...h,...zc(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=nm(s[0],i[0],e),r=nm(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:C3(o,r,d)}]}return im(F3,h.inSpace,a,()=>R3(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 om=.004,qc=.05,rm=new WeakMap;function D3(t){let e=rm.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)}),rm.set(t,e)),e}const am=new WeakMap;function lm(t){return t.filter(({mesh:e})=>D3(e)).map(({part:e,key:n,inSpace:s,low:i,high:o})=>{let r=am.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]}}),am.set(s,r)),{part:e,key:n,planes:r,low:i,high:o}})}function B3(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]-qc||i[a]>o.high[a]+qc))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)<=om))return l<-.9;const h=Math.abs(l)<.5?qc:om;return c.every(u=>u<=h)}))return!0}return!1}const cm=new WeakMap;function hm(t,e,n,s,i){const o=`${s}|${i.map(l=>l.key).join(";")}`;let r=cm.get(e);r||cm.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=>ie(n,h));a=e.faces.map(h=>B3(t,h.corners.map(u=>c[u]),l(h.normal),i)),r.set(o,a)}return a}const Es={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}},jc=Math.PI/180;function um(t,e,n){return{toView:s=>hl(Qt(s,t*90*jc),-e*jc),toScreen:s=>({x:s[0]*n,y:-s[1]*n})}}const dm=new WeakMap,Li=t=>Or(t),Or=t=>{let e=dm.get(t);return e||dm.set(t,e=jg(t)),e};function It(t,e,n){return e[n]??t.controls[n]?.default??Es[n]?.default??0}function Fi(t,e){const n=Math.max(.05,It(t,e,"squash")),s=1/Math.sqrt(n),o=[1,0,0,0,0,1,It(t,e,"lean"),0,0,0,1,0,0,0,0,1];return[yn([0,It(t,e,"lift"),0]),pe(Vt([1,0,0],-It(t,e,"pitch"))),pe(Vt([0,0,1],It(t,e,"roll"))),o,bn([s,n,s]),bn(Array(3).fill(Math.max(0,It(t,e,"size"))))].reduce((r,a)=>Rt(r,a))}function Yc(t,e){const n=Fi(t,e),s=new Map,i=Object.entries(t.controls).flatMap(([r,a])=>(a.bind??[]).map(l=>({value:It(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=Rt(l?o(l):n,yn(r.at??[0,0,0]));if(r.rotate){const[h,u,d]=r.rotate;h&&(c=Rt(c,pe(Vt([1,0,0],h)))),u&&(c=Rt(c,pe(Vt([0,1,0],u)))),d&&(c=Rt(c,pe(Vt([0,0,1],d))))}for(const{value:h,bind:u}of i)if(!(!u.parts.includes(r.id)||h===0)){if(u.translate&&(c=Rt(c,yn([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,yn(d),pe(Vt(f,u.rotate.degrees*h)),yn([-d[0],-d[1],-d[2]])].reduce((p,g)=>Rt(p,g))}u.scale&&(c=Rt(c,bn([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 Kc=(()=>{const t=[-.45,.75,.5],e=Math.hypot(...t);return[t[0]/e,t[1]/e,t[2]/e]})(),z3=Math.cos(35*jc);function Xc(t,e,n,s,i={}){const o=t.derive?{...e,...t.derive(e)}:e,r=Yc(t,o),a=n.toView([0,0,0]),l=H=>W=>[H[0]*W[0]+H[4]*W[1]+H[8]*W[2],H[1]*W[0]+H[5]*W[1]+H[9]*W[2],H[2]*W[0]+H[6]*W[1]+H[10]*W[2]],c=Fi(t,o),h=i.slice===void 0?null:xa(c),u=h?t.parts.map(H=>({part:H,mesh:Or(H.shape),local:Rt(h,r.get(H.id)),whole:H.shape.type==="tube"})):void 0,d=u?W3(u,i.slice):void 0,f=u?lm(u.map(H=>({part:H.part.id,mesh:H.mesh,...zc(H.mesh,H.local)}))):void 0,p=(H,W,j,J)=>{const tt=Q=>n.toView(ie(j,Q)),V=W.vertices.map(tt),L=V.map(Q=>n.toScreen(Q)),q=i.perspective?i.near:void 0,G=Q=>Q.map(rt=>n.toScreen(rt)),C=Q=>q===void 0?Q:em(Q,q),Y=Q=>q===void 0?[Q]:_3(Q,q),st=l(j),$=W.faces.map(Q=>{const rt=n.toView(st(Q.normal)),ht=[rt[0]-a[0],rt[1]-a[1],rt[2]-a[2]],dt=Math.hypot(...ht)||1;return[ht[0]/dt,ht[1]/dt,ht[2]/dt]}),_=f&&J?hm(H.id,W,J,sm(J),f):void 0,z=Q=>_?.[Q]??!1,K=$.map((Q,rt)=>{if(z(rt))return!1;if(!i.perspective)return Q[2]>1e-6;const dt=W.faces[rt].corners.reduce((bt,wt)=>[bt[0]+V[wt][0],bt[1]+V[wt][1],bt[2]+V[wt][2]],[0,0,0]);return-(Q[0]*dt[0]+Q[1]*dt[1]+Q[2]*dt[2])>1e-9}),N=Q=>W.faces[Q].corners.reduce((rt,ht)=>rt+V[ht][2],0)/W.faces[Q].corners.length,F=W.faces.map((Q,rt)=>({face:Q,i:rt})).filter(({i:Q})=>K[Q]).map(({face:Q,i:rt})=>({i:rt,solved:{points:q===void 0?Q.corners.map(ht=>L[ht]):G(C(Q.corners.map(ht=>V[ht]))),depth:N(rt),tone:.72+.33*Math.max(0,$[rt][0]*Kc[0]+$[rt][1]*Kc[1]+$[rt][2]*Kc[2])}})).filter(Q=>Q.solved.points.length>=3).sort((Q,rt)=>Q.solved.depth-rt.solved.depth);if(i.light){const Q=l(j);for(const{i:rt,solved:ht}of F){const dt=W.faces[rt].corners,bt=dt.reduce((wh,Xx)=>{const kh=ie(j,W.vertices[Xx]);return[wh[0]+kh[0]/dt.length,wh[1]+kh[1]/dt.length,wh[2]+kh[2]/dt.length]},[0,0,0]),wt=Q(W.faces[rt].normal),ge=Math.hypot(...wt)||1,ji=i.light(bt,[wt[0]/ge,wt[1]/ge,wt[2]/ge]);ht.light=ji.light,ht.fog=ji.fog}}const D=F.map(Q=>Q.solved),X=q3(W),B=[],Z=[];for(const[Q,rt]of X){const ht=rt.filter(bt=>K[bt]).length;if(ht===0)continue;const dt=rt.length===2&&ht===2&&W.creases!==!1&&$[rt[0]][0]*$[rt[1]][0]+$[rt[0]][1]*$[rt[1]][1]+$[rt[0]][2]*$[rt[1]][2]<z3;rt.length===1&&(W.joined||j3(W,Q))||(rt.length===1||ht===1||dt)&&(B.push(Q.split("-").map(Number)),Z.push(rt.filter(bt=>K[bt]).reduce((bt,wt)=>N(wt)>N(bt)?wt:bt)))}const et=Q=>W.faces.findIndex(rt=>rt.corners.length>4&&Math.sign(K3(W.vertices[Q],rt.normal))>0),R=(W.marks??[]).filter(([Q])=>et(Q)<0||K[et(Q)]),U=([Q,rt])=>q===void 0?[[L[Q],L[rt]]]:Y([V[Q],V[rt]]).map(G),nt=R.flatMap(U),at=Q=>q===void 0?[Q.map(rt=>L[rt])]:Y(Q.map(rt=>V[rt])).map(G);if(i.slice!==void 0){const Q=new Map;B.forEach((rt,ht)=>Q.set(Z[ht],[...Q.get(Z[ht])??[],rt]));for(const{i:rt,solved:ht}of F){ht.edges=mm(Q.get(rt)??[]).flatMap(at);const dt=W.faces[rt].corners;ht.center=dt.reduce((wt,ge)=>[wt[0]+V[ge][0]/dt.length,wt[1]+V[ge][1]/dt.length,wt[2]+V[ge][2]/dt.length],[0,0,0]),ht.normal=$[rt];const bt=F[F.length-1].i;ht.marks=R.filter(([wt])=>(et(wt)>=0?et(wt):bt)===rt).flatMap(U)}}const ot=H.glow?Math.max(0,Math.min(1,It(t,o,H.glow.control))):0,ct=H.fade?Math.max(0,Math.min(1,It(t,o,H.fade.control))):0,it=H.fade?Math.max(0,Math.min(1,H.fade.from+(H.fade.to-H.fade.from)*ct)):1;return{part:H,depth:V.reduce((Q,rt)=>Q+rt[2],0)/Math.max(1,V.length),faces:D,edges:mm(B).flatMap(at),marks:nt,glow:ot,opacity:it,...H.shape.type==="tube"?{spine:Y3(Y(H.shape.points.map(tt)).map(G))}:{},...W.walls?{cut:!0}:{}}},g=new Map(u?.map(H=>[H.part.id,H.local])),b=(d?d.pieces.map(H=>({part:H.part,mesh:H.mesh,m:H.cut?c:r.get(H.part.id),local:H.cut?ao():g.get(H.part.id),cell:H.cell})):t.parts.map(H=>({part:H,mesh:Or(H.shape),m:r.get(H.id),local:void 0,cell:void 0}))).map(H=>({cell:H.cell,solved:p(H.part,H.mesh,H.m,H.local)})),v=b.map(H=>H.solved),k=H=>H.filter(W=>W.faces.length>0&&W.opacity>.01).sort((W,j)=>W.depth-j.depth);let w;if(d){const H=new Map(t.parts.map(j=>{const J=r.get(j.id),tt=Or(j.shape).vertices;return[j.id,tt.reduce((V,L)=>V+n.toView(ie(J,L))[2],0)/Math.max(1,tt.length)]})),W=new Map;for(const j of b){const J=j.cell.join(",");W.has(J)||W.set(J,{cell:j.cell,parts:[]}),W.get(J).parts.push(j.solved),j.solved.depth=H.get(j.solved.part.id)}w=[...W.values()].map(({cell:j,parts:J})=>({depth:n.toView(ie(c,d.middle(j)))[2],parts:k(J)})).filter(j=>j.parts.length>0)}const T={};for(const[H,W]of Object.entries(t.anchors??{})){const j=W.part?r.get(W.part):Fi(t,o);if(!j)throw new Error(`prop rig: anchor "${H}" is on "${W.part}", which is not a part`);const J=n.toView(ie(j,W.at));T[H]={point:n.toScreen(J),depth:J[2]}}const[P,S]=t.footprint??[t.length*.45,t.length],x=Math.max(0,It(t,o,"lift")),M=Math.max(0,It(t,o,"size"))/(1+x*.8),E=Array.from({length:24},(H,W)=>{const j=Math.PI*2*W/24;return n.toView([Math.cos(j)*P*.55*M,0,Math.sin(j)*S*.55*M])}),I=i.perspective?i.near:void 0,A={points:(I===void 0?E:em(E,I)).map(H=>n.toScreen(H)),opacity:.16*M},O=v.filter(H=>H.part.seeThrough&&H.opacity>.01).flatMap(H=>H.faces.map(W=>W.points));return{under:k(v.filter(H=>!H.part.overRider)),over:k(v.filter(H=>H.part.overRider)),...w?{cells:w}:{},anchors:T,openings:O,shadow:A,pxPerUnit:s,sizePx:t.height*s}}const fm=new WeakMap;function q3(t){let e=fm.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])}}fm.set(t,e)}return e}function gm(t,e){const n=t.derive?{...e,...t.derive(e)}:e,s=Yc(t,n),i=xa(Fi(t,n))??ao(),o=r=>Math.max(0,Math.min(1,r));return t.parts.map(r=>{const a=r.fade?o(It(t,n,r.fade.control)):0;return{part:r,matrix:s.get(r.id),local:Rt(i,s.get(r.id)),glow:r.glow?o(It(t,n,r.glow.control)):0,opacity:r.fade?o(r.fade.from+(r.fade.to-r.fade.from)*a):1}})}function pm(t,e){const n=t.derive?{...e,...t.derive(e)}:e,s=Yc(t,n),i=Fi(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]=ie(l,a.at)}return o}function j3(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 Y3(t){return t.reduce((e,n)=>!e||n.length>e.length?n:e,void 0)}const K3=(t,e)=>t[0]*e[0]+t[1]*e[1]+t[2]*e[2];function mm(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 Gc(t,e){if(!t.loose?.size)return;const n={};for(const[s,i]of t.loose)n[s]={x:e[`piece.${i}.x`]??0,y:e[`piece.${i}.y`]??0,rotate:e[`piece.${i}.rotate`]??0,opacity:e[`piece.${i}.opacity`]??1};return n}function Uc(t){const e={};for(const[n,s]of Object.entries({...Es,...t.rig.controls})){const{bind:i,...o}=s;e[n]=o}return e}function ym(t){const{prop:e}=t,n=t.scale??60,s=e.rig.length*n*1.4,i=e.rig.height*n*1.6,o=Uc(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),Xl(l,As(e,u,n),{...a,time:h,loose:Gc(c,u)})}}}function As(t,e,n){const s=um(It(t.rig,e,"turn"),It(t.rig,e,"tilt"),n);return Xc(t.rig,e,s,n)}function _r(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=As(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 X3(t,e,n,s,i={}){const o=_r(e,n,s);return t.save(),t.translate(o.origin.x,o.origin.y),Xl(t,o.solved,{...e.propDraw,time:n.time,loose:Gc(e,o.values),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 $s={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…); it can come loose as a piece","control:NAME":"where the parts a control moves or lights are (control:door is the doors, control:lights the lamps; a control of the whole prop, like lift, is its box)"},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",move:"a part; { at, to: an anchor name or { x, y }, duration? }: carry the part there, loose",fling:"a part; { at, velocity?, spin?, gravity?, duration? }: knock the part off on a spinning arc"}},G3=400,U3=.2;function V3(t,e={}){const{prop:n}=t,s=Uc(n),i=Object.keys(s),o=Object.keys(n.rig.anchors??{}),r=n.rig.parts.map(P=>P.id),a=ws(),l=Ti(a),c=e.tracks?.length?new Ht({id:`${n.kind}-surface`,tracks:e.tracks}):void 0,h=Math.max(0,...(e.tracks??[]).flatMap(P=>P.keyframes.map(S=>S.time))),u=new Map,d=new Map;t.loose=d;const f=t.props,p=P=>{const S={...t.props};let x=0,M=0;if(c){const E=c.getStateAtTime(Math.min(P,h));for(const I of E.values.values())for(const[A,O]of I)typeof O=="number"&&(A==="x"?x=O:A==="y"?M=O:A in S&&(S[A]=O))}for(const E of i)a.keys(E)?.length&&(S[E]=a.valueAt(E,P));return{values:S,origin:{x:t.x+t.width/2+x,y:t.y+t.height+M}}},g=P=>{const{kind:S,rest:x}=_n(P),M=E=>en(n.kind,P,$s,E);if(S==="box"){if(x)throw M("box takes no arguments");return{kind:S}}if(S==="anchor"){if(!o.includes(x))throw M(ft(`${n.kind} anchor`,x,o));return{kind:S,name:x}}if(S==="part"){if(!r.includes(x))throw M(ft(`${n.kind} part`,x,r));return{kind:S,name:x}}if(S==="control"){if(!i.includes(x))throw M(ft(`${n.kind} control`,x,i));return{kind:S,name:x}}throw M()},m=P=>{const S=(n.rig.controls[P]?.bind??[]).flatMap(M=>M.parts),x=n.rig.parts.filter(M=>M.glow?.control===P).map(M=>M.id);return new Set([...S,...x])},b=new Map,v=P=>{let S=b.get(P);if(!S){const x=p(P);b.set(P,S={...x,solved:As(n,x.values,t.propScale)})}return S},k=(P,S)=>{const x=g(P),{values:M,origin:E,solved:I}=v(S);if(x.kind==="box")return Mt(E.x-t.width/2,E.y-t.height,t.width,t.height);if(x.kind==="anchor"){const H=I.anchors[x.name].point,W=U3*t.propScale;return Mt(E.x+H.x-W/2,E.y+H.y-W/2,W,W)}if(x.kind==="part")return O(new Set([x.name]),`part "${x.name}" is`);const A=m(x.name);if(A.size===0)return Mt(E.x-t.width/2,E.y-t.height,t.width,t.height);return O(A,`the parts control "${x.name}" moves are`);function O(H,W){const j=[...I.under,...I.over].filter(q=>H.has(q.part.id)).flatMap(q=>q.faces.flatMap(G=>G.points));if(j.length===0){const q=Number.isFinite(S)?`at ${S} ms`:"after its edits";throw new Error(`${n.kind}: ${W} turned away from the viewer ${q}; aim at an anchor (${o.map(G=>`anchor:${G}`).join(", ")||"none"}) or box`)}const J=j.map(q=>q.x),tt=j.map(q=>q.y),V=Math.min(...J),L=Math.min(...tt);return Mt(E.x+V,E.y+L,Math.max(...J)-V,Math.max(...tt)-L)}},w=(P,S)=>{try{return k(P,S)}catch{return}},T={kind:"prop",prop:t,about:$s,target:t,box:Mt(t.x,t.y,t.width,t.height),anchor(P,S=1/0){return k(P,S)},piece(P){const S=g(P);if(S.kind!=="part")throw new Error(`${n.kind}: a piece is a part, part:ID (${r.slice(0,6).map(I=>`part:${I}`).join(", ")}…), not "${P}"`);const x=u.get(S.name);if(x)return x;const M=[S.name];for(let I=0;I<M.length;I++)for(const A of n.rig.parts)A.parent===M[I]&&!M.includes(A.id)&&M.push(A.id);const E={id:u.size+1,part:S.name,home:k(P,0)};u.set(S.name,E);for(const I of M)d.set(I,E.id);for(const I of["x","y","rotate"])f[`piece.${E.id}.${I}`]=0;return f[`piece.${E.id}.opacity`]=1,E},edit(P,S,x){if(!(P in $s.edits))throw Ei(n.kind,P,$s);const M=Array.isArray(S)?S:[S];if(M.length===0)throw new Error(`${n.kind}.edit: ${P} takes at least one anchor`);if(b.clear(),P==="move"||P==="fling"){if(M.length>1)throw new Error(`${n.kind}.edit: ${P} takes one part anchor`);const E=T.piece(M[0]);if(P==="fling")return T.fling(E,x);const I=x.to;if(!I)throw new Error(`${n.kind}.edit: move needs \`to\`, an anchor name or { x, y }`);const A=typeof I=="string"?k(I,x.at):void 0;return T.move(E,{...x,to:A?{x:A.left+A.width/2,y:A.top+A.height/2}:I})}for(const E of M){const I=g(E);if(I.kind!=="control")throw new Error(`${n.kind}.edit: ${P} takes control anchors (control:${i.join(", control:")}), not "${E}"`);const A=s[I.name];let O;if(P==="set"){if(typeof x.value!="number"||!Number.isFinite(x.value))throw new Error(`${n.kind}.edit: set needs \`value\`, a number (${I.name}: ${A.description})`);O=x.value}else O=x.on===!1?A.default??A.min??0:A.max??1;a.tween(I.name,p(x.at).values[I.name],O,x,G3)}return T},follow(P,S){return b.clear(),l.follow(P,S),T},fling(P,S){return b.clear(),l.fling(P,S),T},move(P,S){return b.clear(),l.move(P,S),T},ride(P,S,x){const M=[...i.flatMap(I=>ks(a.keys(I))),...(e.tracks??[]).flatMap(I=>ks(I.keyframes.filter(A=>typeof A.value=="number")))];if(M.length===0)return P;const E=[...o.map(I=>`anchor:${I}`),...r.map(I=>`part:${I}`)].flatMap(I=>{const A=w(I,0);return A?[{top:A.top,offset:O=>(w(I,O)?.top??A.top)-A.top,windows:M}]:[]});return mr(P,S,{ground:x.ground,every:x.every??tn,floors:E})},tracks:a.tracks};return T}const J3={body:"#e8574a",trim:"#3b3b44",glass:"#bfe3f2",tyre:"#2c2c33",hub:"#c9ccd3",light:"#fff4b8",tail:"#ff5a4f",inside:"#3b3640",seat:"#6d5d55"};function Fe(t){const e={...J3,...t.colors},n=[],{forwardMost:s,backMost:i,top:o}=bm(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 b=h+(u-h)*.15,v=h+(u-h)*.55;n.push({id:`seat-back-${m}`,shape:{type:"panel",points:[[b,d+.05],[v,d+.05],[v-.08,f-.06],[b+.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,w])=>[k-u,w]),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 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,p],fill:hr(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:Z3(t),acting:wm,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 bm(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 wm={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 Cr(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 km=.4;function Z3(t){const e=t.wheels[0]?.radius??.4,{forwardMost:n,backMost:s}=bm(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"}),Cr(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??km));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}),Cr(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??km*1.2)),m=u+g*.55,b=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"}),Cr(a,u,m,b,"ease-in",e),a.key(m+80,{pitch:-7*d,lean:-.12*d,squash:.94},{act:!1,easing:"ease-out"}),Cr(a,m,u+g,l.to,"ease-out",e,!0),a.effect({kind:"skid",time:m,x:b,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 vm(t={}){return Fe({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 Mm(t={}){return Fe({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 Sm(t={}){return Fe({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 xm(t={}){return Fe({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 Tm(t={}){const e=t.colors?.body??"#a8743f";return Fe({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 Em(t={}){return Fe({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 Am(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 Fe({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 $m(t={}){return Fe({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 Pm(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=Ye(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:Q3(),acting:Im,colors:{body:o.leaves}}}const Im={depth:{sway:1,canopySway:2,size:0,squash:1},limits:{sway:2,canopySway:3,squash:.08},eyes:[],headTurns:{},drift:[]};function Q3(){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 Om(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:t4(!!f),acting:_m,colors:{body:r.walls}}}const _m={depth:{door:1,lights:0,roll:1,squash:1,size:0},limits:{door:.1,roll:1.5,squash:.05},eyes:[],headTurns:{},drift:[]};function t4(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 Cm(t={}){const e=t.width??.46,n=t.depth??.46,s=t.seatHeight??.46,i=t.backHeight??.95,o={wood:"#8a5a3b",seat:"#c48a4a",...t.colors},r=.05,a=.025,l=[{id:"seat",shape:{type:"box",size:[e,r,n]},at:[0,s-r/2,0],fill:o.seat},{id:"back",shape:{type:"box",size:[e,i-s,r]},at:[0,(i+s)/2,-n/2+r/2],fill:o.wood}];for(const[h,u,d]of[[-1,1,"front-left"],[1,1,"front-right"],[-1,-1,"back-left"],[1,-1,"back-right"]])l.push({id:`leg-${d}`,shape:{type:"tube",points:[[0,0,0],[0,s-r,0]],radius:a,segments:6},at:[h*(e/2-a*1.5),0,u*(n/2-a*1.5)],fill:o.wood});const c={parts:l,controls:{tip:{description:"Tipped back on its rear legs (+), degrees",unit:"degrees",min:0,max:60,bind:[{parts:l.map(h=>h.id),rotate:{axis:"x",degrees:1,pivot:[0,0,-n/2+a*1.5]}}]}},length:n,height:i,footprint:[e,n],anchors:{seat:{at:[0,s,0]},back:{at:[0,i,-n/2]},front:{at:[0,0,n/2+.3]}}};return{kind:t.kind??"chair",family:"furniture",summary:t.summary??"A chair: a seat to sit on (`seat`), tips back on its rear legs and settles, or falls over.",rig:c,actions:e4(),acting:Hm,colors:{body:o.seat}}}const Hm={depth:{tip:1,roll:1,squash:1,size:0},limits:{tip:2,roll:1,squash:.05},eyes:[],headTurns:{},drift:[]};function e4(){return{tip:{summary:"Tips back on its rear legs for `for` ms (default 1200), rocking a little, then settles down.",uses:["for"],run(t,e,n){const s=18*t.exaggeration,i=e.for??1200;return t.key(n+350,{tip:s},{easing:"ease-out"}),t.key(n+350+i*.4,{tip:s*.85},{act:!1,easing:"ease-in-out"}),t.key(n+350+i*.7,{tip:s},{act:!1,easing:"ease-in-out"}),t.key(n+350+i,{tip:0},{easing:"ease-in"}),{end:n+350+i,contact:n+350}}},fall:{summary:"Falls over backwards onto its back and bounces, with dust.",uses:["for"],run(t,e,n){const s=e.for??700;return t.key(n+s*.6,{tip:90},{act:!1,easing:"ease-in"}),t.key(n+s*.75,{tip:82},{act:!1,easing:"ease-out"}),t.key(n+s,{tip:90},{act:!1,easing:"ease-in"}),t.effect({kind:"dust",time:n+s*.6,x:t.x,y:t.floor,length:600}),{end:n+s,contact:n+s*.6}}}}}function Rm(t={}){const e=t.width??1.4,n=t.depth??.7,s=t.height??.75,i={wood:"#8a5a3b",top:"#a9754a",knob:"#2b2b2b",...t.colors},o=.04,r=.03,a=.14,l=e*.4,c=[{id:"top",shape:{type:"box",size:[e,o,n]},at:[0,s-o/2,0],fill:i.top},{id:"drawer",shape:{type:"box",size:[l,a,n*.8]},at:[-e/2+l/2+.05,s-o-a/2,0],fill:i.wood},{id:"knob",parent:"drawer",shape:{type:"ellipsoid",radii:[.02,.02,.015],segments:8},at:[0,0,n*.4+.012],fill:i.knob,outline:.6}];for(const[u,d,f]of[[-1,1,"front-left"],[1,1,"front-right"],[-1,-1,"back-left"],[1,-1,"back-right"]])c.push({id:`leg-${f}`,shape:{type:"tube",points:[[0,0,0],[0,s-o,0]],radius:r,segments:6},at:[u*(e/2-r*2),0,d*(n/2-r*2)],fill:i.wood});const h={parts:c,controls:{drawer:{description:"The drawer out: 0 shut, 1 open",unit:"0..1",min:0,max:1,bind:[{parts:["drawer"],translate:[0,0,n*.5]}]}},length:n,height:s,footprint:[e,n],anchors:{top:{at:[0,s,0]},edge:{at:[0,s,n/2]},drawer:{part:"drawer",at:[0,0,n*.4]},chair:{at:[0,0,n/2+.35]}}};return{kind:t.kind??"desk",family:"furniture",summary:t.summary??"A desk: a top to work at (`top`, `edge`), a drawer that opens (`drawer`), a place for a chair in front (`chair`).",rig:h,actions:{drawer:{summary:"Opens the drawer (`open: true`) or shuts it (`open: false`).",needs:["open"],run(u,d,f){return u.key(f+400,{drawer:d.open?1:0},{easing:d.open?"ease-out":"ease-in"}),{end:f+500,contact:f+400}}}},acting:Lm,colors:{body:i.top}}}const Lm={depth:{drawer:1,roll:1,squash:1,size:0},limits:{drawer:.08,roll:1,squash:.04},eyes:[],headTurns:{},drift:[]};function Fm(t={}){const e=t.length??2,n=t.width??1,s=t.height??.55,i=t.headboard??.95,o={wood:"#8a5a3b",mattress:"#f1ece2",blanket:"#5b7fb0",pillow:"#fbf8f2",...t.colors},r=.3,a=s-r,c={parts:[{id:"frame",shape:{type:"box",size:[n,r,e]},at:[0,r/2,0],fill:o.wood},{id:"headboard",shape:{type:"box",size:[n+.06,i-r,.06]},at:[0,(i+r)/2,-e/2-.03],fill:o.wood},{id:"mattress",shape:{type:"box",size:[n-.04,a,e-.04]},at:[0,r+a/2,0],fill:o.mattress},{id:"blanket",parent:"mattress",shape:{type:"box",size:[n-.02,.04,e*.62]},at:[0,a/2+.02,e*.19],fill:o.blanket,outline:.7},{id:"pillow",parent:"mattress",shape:{type:"ellipsoid",radii:[n*.32,.07,.22],segments:12},at:[0,a/2+.06,-e/2+.32],fill:o.pillow,outline:.7}],controls:{give:{description:"The mattress pressed down: 1 as made, below squashed (someone landed on it)",unit:"factor",default:1,min:.5,max:1.2,bind:[{parts:["mattress"],scale:[1,1,1]}]}},length:e,height:i,footprint:[n,e],anchors:{mattress:{part:"mattress",at:[0,a/2,0]},pillow:{part:"mattress",at:[0,a/2+.1,-e/2+.32]},foot:{at:[0,s,e/2]},side:{at:[n/2+.25,0,0]}}};return{kind:t.kind??"bed",family:"furniture",summary:t.summary??"A bed: a mattress to lie on (`mattress`, `pillow`) that gives and springs back when someone lands on it (`bounce`), a side to sit on (`side`).",rig:c,actions:{bounce:{summary:"The mattress gives (someone landed on it) and springs back over `for` ms (default 700).",uses:["for"],run(h,u,d){const f=u.for??700,p=h.exaggeration;return h.key(d+90,{give:1-.18*p},{act:!1,easing:"ease-out"}),h.key(d+f*.45,{give:1+.05*p},{act:!1,easing:"ease-in-out"}),h.key(d+f*.7,{give:1-.04*p},{act:!1,easing:"ease-in-out"}),h.key(d+f,{give:1}),{end:d+f,contact:d+90}}}},acting:Nm,colors:{body:o.blanket}}}const Nm={depth:{give:1,roll:1,squash:1,size:0},limits:{give:.03,roll:.5,squash:.03},eyes:[],headTurns:{},drift:[]};function Wm(t={}){const e=t.width??.9,n=t.height??2.05,s=t.hinge??"left",i={frame:"#d9d2c3",door:"#7a4b2a",handle:"#c9a227",beyond:"#2a2f3a",...t.colors},o=.1,r=s==="left"?1:-1,a=r>0?[[0,0],[-e,0],[-e,n],[0,n]]:[[0,0],[e,0],[e,n],[0,n]],c={parts:[{id:"post-left",shape:{type:"box",size:[o,n+o,o]},at:[e/2+o/2,(n+o)/2,0],fill:i.frame},{id:"post-right",shape:{type:"box",size:[o,n+o,o]},at:[-e/2-o/2,(n+o)/2,0],fill:i.frame},{id:"lintel",shape:{type:"box",size:[e+o*2,o,o]},at:[0,n+o/2,0],fill:i.frame},{id:"beyond",shape:{type:"panel",points:[[-e/2,0],[e/2,0],[e/2,n],[-e/2,n]],facing:"front"},at:[0,0,-.03],fill:i.beyond,outline:.4,seeThrough:!0},{id:"door",shape:{type:"panel",points:a,facing:"front"},at:[r*e/2,0,.005],fill:i.door,outline:.9,overRider:!0},{id:"handle",parent:"door",shape:{type:"ellipsoid",radii:[.03,.03,.03],segments:8},at:[-r*(e-.1),n*.47,.03],fill:i.handle,outline:.5}],controls:{open:{description:"How far the door is open: 0 shut, 1 open wide",unit:"0..1",min:0,max:1,bind:[{parts:["door"],rotate:{axis:"y",degrees:r*-95}}]}},length:.3,height:n+o,footprint:[e+o*2,.3],anchors:{handle:{part:"door",at:[-r*(e-.1),n*.47,.03]},doorway:{at:[0,0,0]},front:{at:[0,0,.5]},beyond:{at:[0,0,-.5]}}};return{kind:t.kind??"door",family:"furniture",summary:t.summary??"A door in its frame: opens and shuts on its hinge (`open`), slams, rattles when knocked; a figure goes through the `doorway` from `front` to `beyond`.",rig:c,actions:n4(),acting:Dm,colors:{body:i.door}}}const Dm={depth:{open:1,roll:1,squash:1,size:0},limits:{open:.08,roll:.6,squash:.03},eyes:[],headTurns:{},drift:[]};function n4(){return{open:{summary:"Opens the door (`open: true`, default) or shuts it (`open: false`), over `for` ms (default 600).",uses:["open","for"],run(t,e,n){const s=e.for??600;return t.key(n+s,{open:e.open===!1?0:1},{easing:"ease-in-out"}),{end:n+s+80,contact:n+s}}},slam:{summary:"Slams shut: a fast swing, a shudder in the frame, dust.",run(t,e,n){const s=t.exaggeration;t.key(n+180,{open:0},{act:!1,easing:"ease-in"});for(let i=1;i<=4;i++)t.key(n+180+i*70,{roll:(i%2===0?1:-1)*1.2*s*(1-i/5)},{act:!1});return t.key(n+180+350,{roll:0}),t.effect({kind:"dust",time:n+180,x:t.x,y:t.floor,length:500}),{end:n+180+350,contact:n+180}}},knock:{summary:"Someone knocks three times: the door rattles over `for` ms (default 700).",uses:["for"],run(t,e,n){const i=e.for??700,o=t.exaggeration;for(let r=0;r<3;r++){const a=n+i*(r+.5)/3;t.key(a,{open:.03*o},{act:!1,easing:"ease-out"}),t.key(a+60,{open:0},{act:!1,easing:"ease-in"})}return{end:n+i,contact:n+i/6}}}}}const Bm=1.4;function zm(t={}){const e=t.width??.5,n=t.seatHeight??.5,s=t.wheelRadius??.3,i=.08,o={frame:"#2b2f36",seat:"#3c6ea5",tyre:"#1f2328",...t.colors},r=.04,a=.018,l=.44,c=n+.5,h=-.08,u=e/2+.06,d=[{id:"seat",shape:{type:"box",size:[e,r,l]},at:[0,n-r/2,0],fill:o.seat},{id:"back",shape:{type:"box",size:[e,c-n-.02,r]},at:[0,(c+n)/2,-l/2+r/2],fill:o.seat},{id:"footrest",shape:{type:"box",size:[e*.8,.02,.14]},at:[0,.12,l/2+.22],fill:o.frame}];for(const[g,m]of[[-1,"left"],[1,"right"]]){const b=g*u,v=(k,w,T=a)=>{d.push({id:k,shape:{type:"tube",points:w,radius:T,segments:6},fill:o.frame,outline:.7})};v(`post-${m}`,[[b,n-.1,-l/2],[b,c+.04,-l/2],[b,c+.04,-l/2-.14]]),v(`rail-${m}`,[[b,n-.03,-l/2],[b,n-.03,l/2]]),v(`leg-${m}`,[[b,n-.03,l/2],[b*.85,i,l/2+.06]]),v(`strut-${m}`,[[b*.85,i+.08,l/2+.04],[b*.8,.13,l/2+.22]]),v(`armrest-${m}`,[[b,n+.22,-l/2+.02],[b,n+.22,l/2-.08]],a*1.3),d.push({id:`wheel-${m}`,shape:{type:"cylinder",radius:s,length:.04,axis:"x",segments:20,spokes:8},at:[b+g*.03,s,h],ink:o.tyre,outline:1.3}),d.push({id:`rim-${m}`,shape:{type:"cylinder",radius:s*.9,length:.012,axis:"x",segments:20},at:[g*.045,0,0],parent:`wheel-${m}`,ink:o.frame,outline:.8}),d.push({id:`castor-${m}`,shape:{type:"cylinder",radius:i,length:.03,axis:"x",segments:12,spokes:3},at:[b*.85,i,l/2+.06],fill:o.tyre})}const f=d.map(g=>g.id).filter(g=>!g.startsWith("rim-")),p={parts:d,controls:{wheelSpin:{description:"How far the big wheels have turned, degrees (keyed with the distance rolled, so they never skate); the castors turn faster",unit:"degrees",bind:[{parts:["wheel-left","wheel-right"],rotate:{axis:"x",degrees:1}},{parts:["castor-left","castor-right"],rotate:{axis:"x",degrees:s/i}}]},tip:{description:"Tipped back on its big wheels (+), degrees: a wheelie, or a helper tipping it up a kerb",unit:"degrees",min:0,max:45,bind:[{parts:f,rotate:{axis:"x",degrees:1,pivot:[0,s,h]}}]}},length:l+.4,height:c+.04,footprint:[u*2+.1,l+.4],anchors:{seat:{at:[0,n,.02]},handles:{at:[0,0,-l/2-.5]},front:{at:[0,0,l/2+.6]},footrest:{at:[0,.13,l/2+.22]}}};return{kind:t.kind??"wheelchair",family:"furniture",summary:t.summary??"A wheelchair: rolls to `to` with its wheels turning the distance (roll), brakes, tips back on its big wheels (wheelie); its `seat` is ridden in the `wheeling` pose and a pusher stands at `handles`.",rig:p,actions:s4(s),acting:qm,colors:{body:o.seat,ink:o.frame},wheelRadius:s,moves:{roll:{speed:Bm,perMetre:{wheelSpin:180/(Math.PI*s)}}}}}const qm={depth:{wheelSpin:0,tip:1,roll:1,squash:1,size:0},limits:{tip:2,roll:1,squash:.03},eyes:[],headTurns:{},drift:[]};function jm(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)}function s4(t){return{roll:{summary:"Rolls to `to` at `speed` px/ms (or over `for` ms): a small push-off, the wheels turning exactly the distance, and a gentle stop.",needs:["to"],uses:["speed","for"],run(e,n,s){const i=Math.sign(n.to-e.x);if(i===0)return{end:s};let o=s;e.facing()!==i&&(o=e.turnTo(o,i>0?"right":"left"));const r=Math.abs(n.to-e.x),a=n.for??Math.max(300,r/(n.speed??Bm*e.scale/1e3));return e.key(o+150,{tip:1.5*e.exaggeration},{act:!1,easing:"ease-out"}),jm(e,o,o+a,n.to,"ease-in-out",t),e.key(o+a,{tip:0},{easing:"ease-out"}),{end:o+a}}},brake:{summary:"Stops short at `to`: the wheels lock and it skids the last bit, tipping forward a touch.",needs:["to"],uses:["for"],run(e,n,s){if(Math.sign(n.to-e.x)===0)return{end:s};const o=n.for??500;return jm(e,s,s+o,n.to,"ease-out",t,!0),e.key(s+o,{tip:0},{easing:"ease-out"}),e.effect({kind:"dust",time:s+o*.5,x:n.to,y:e.floor,length:500}),{end:s+o,contact:s+o}}},wheelie:{summary:"Tips back onto its big wheels, balances there for `for` ms (default 1200), and drops down.",uses:["for"],run(e,n,s){const i=24*e.exaggeration,o=n.for??1200;return e.key(s+300,{tip:i},{easing:"ease-out"}),e.key(s+300+o*.5,{tip:i*.9},{act:!1,easing:"ease-in-out"}),e.key(s+300+o,{tip:i},{act:!1,easing:"ease-in-out"}),e.key(s+300+o+250,{tip:0},{easing:"ease-in"}),e.effect({kind:"dust",time:s+300+o+250,x:e.x,y:e.floor,length:400}),{end:s+300+o+250,contact:s+300+o+250}}}}}function Ym(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:i4(),acting:Vc,colors:{body:e.body,ink:"#26262b"},moves:{fly:{speed:15,flies:!0,hold:{blur:1},perSecond:{rotor:sn*1e3}}}}}const Vc={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:[]},sn=2.6;function i4(){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,sn,"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,sn),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,sn),{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,sn),{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,sn),t(n,r,r+1600,sn,"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 Km(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:r4(),acting:Vc,colors:{body:e.body,ink:"#26262b"},moves:{fly:{speed:30,flies:!0,hold:{blur:1},perSecond:{rotor:sn*1e3}}}}}const o4=3.2;function r4(){const t=(n,s,i,o)=>{const r=n.values.rotor??0;n.set("rotor",s,r),n.set("rotor",i,r+o4*(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 Ps=["walk","trot","canter","gallop"],a4=Ps,Xm=["fl","fr","hl","hr"],Hr={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}},on=Math.PI/180;function Rr(t,e){return 4*t*Math.sin(Hr[e].swing*on)}function rn(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},...c4(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=>`${Ps.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:be,rotate:{axis:"x",degrees:1/be.length}}]},wag:{description:"Tail swung side to side, curling",unit:"degrees",bind:[{parts:be,rotate:{axis:"y",degrees:1/be.length}}]},ears:{description:"Ears pricked forward (+) or laid back (−), on a spring behind the motion",unit:"degrees",bind:[{parts:["ear-left","ear-right"],rotate:{axis:"x",degrees:1,pivot:[0,-t.ears.radii[1],0]}}]}};for(const u of Xm){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=>h4(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:{...d4(t,h),...t.actions?.(h)},acting:Zc,colors:{body:n.coat,ink:"#26262b"},follow:[{control:"tail",of:"x",per:.6,stiffness:90,damping:6,limit:40},{control:"ears",of:"x",per:1.4,stiffness:150,damping:8,limit:45}],moves:l4(t,s)}}function l4(t,e){const n=i=>{const o=Rr(e,i);return{speed:o/(Hr[i].cycle*(t.cycleScale??1)/1e3),set:{gait:Ps.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 be=Array.from({length:7},(t,e)=>e===0?"tail":`tail-${e}`);function c4(t,e,n){const s=sc(t.tail.points,be.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/be.length),h=be.map((f,p)=>{const g=s[p],m=s[p+1],b=[m[0]-g[0],m[1]-g[1],m[2]-g[2]],v=p===0?void 0:s[p-1];return{id:f,...p>0?{parent:be[p-1]}:{},shape:{type:"tube",points:[[0,0,0],b],radius:[c(p),c(p+1)],segments:8,joined:!0},at:p===0?l:[g[0]-v[0],g[1]-v[1],g[2]-v[2]],fill:e.dark,outline:.8}}),u=s[s.length-1],d=s[s.length-2];return h.push({id:"tail-tip",parent:be[be.length-1],shape:{type:"ellipsoid",radii:Array(3).fill(c(be.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 h4(t,e,n){const s=Math.max(0,Math.min(1,t.walking??0));if(s===0)return{};const i=Ps[Math.max(0,Math.min(3,Math.round(t.gait??0)))],o=Hr[e.gaits.includes(i)?i:e.gaits[0]],r=t.walk??0,a={};for(const c of Xm){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 Jc(t){const n=Math.sin(32*on),s=t.legLength-(t.front-t.hind)*n,i=72,r=(s-t.upper*Math.cos(i*on)-t.foot)/t.lower,a=r>=1?0:r<=-1?180:Math.acos(r)/on,l={pitch:32,lift:t.legLength*(1-Math.cos(32*on))-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 Zc={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:[]},u4=Zc;function Gm(t){const e=(t.upper+t.lower)*.32,n=Math.asin(Math.min(1,e/(t.upper+t.lower+t.foot)))/on,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 d4(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/Rr(e.legLength,r),g=l.for??Math.max(500,p*Hr[r].cycle*n),m=a.values.walk??0;return a.set("gait",u,a.values.gait??0),a.set("gait",u+1,Ps.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=Jc(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=Gm(e),h={...Jc(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 Um(t={}){return rn({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*on),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*on);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 Vm(t={}){return rn({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 Jm(t={}){return rn({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 Zm(t={}){return rn({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 f4(t){return Rr(1,t)}function Qm(t={}){return rn({kind:t.kind??"goat",summary:t.summary??"A goat: walks, trots and gallops, bleats, grazes, sits, lies, jumps, and swishes its stubby tail.",legs:{upper:.22,lower:.2,foot:.05,footSize:[.07,.09],front:.26,hind:-.26,across:.1,thickness:[.045,.05],lowerThickness:.03},body:{radii:[.15,.17,.38],rise:.1},neck:{at:[0,.62,.3],points:[[0,0,0],[0,.16,.1]],radius:.07},head:{at:[0,.16,.1],radii:[.09,.1,.15],rotate:[-20,0,0]},muzzle:{at:[0,-.05,.13],radii:[.055,.05,.07]},ears:{at:[.1,.03,-.02],radii:[.06,.025,.03],rotate:[0,0,-20]},eyes:{at:[.065,.05,.09],size:.022},tail:{at:[0,.64,-.37],points:[[0,0,0],[0,.06,-.05]],radius:.025},extras:e=>[{id:"horn-left",parent:"head",shape:{type:"tube",points:[[0,0,0],[.01,.07,-.03],[.015,.12,-.08]],radius:.014,segments:6},at:[.045,.08,-.02],fill:e.dark},{id:"horn-right",parent:"head",shape:{type:"tube",points:[[0,0,0],[-.01,.07,-.03],[-.015,.12,-.08]],radius:.014,segments:6},at:[-.045,.08,-.02],fill:e.dark},{id:"beard",parent:"head",shape:{type:"ellipsoid",radii:[.025,.05,.02],segments:8},at:[0,-.12,.06],fill:e.accent,outline:.5}],colors:{coat:"#e9e2d3",dark:"#8c7b66",foot:"#4f4339",muzzle:"#d8cdb8",accent:"#cfc4b0",...t.colors},gaits:["walk","trot","gallop"],cycleScale:.8,call:"bleat",grazes:!0})}function ty(t={}){return rn({kind:t.kind??"rabbit",summary:t.summary??"A rabbit: walks and hops (gallop), squeaks, nibbles the ground (graze), sits, lies and jumps; long ears and a puff of a tail.",legs:{upper:.07,lower:.07,foot:.03,footSize:[.04,.07],front:.11,hind:-.12,across:.06,thickness:[.028,.04],lowerThickness:.02},body:{radii:[.1,.11,.19],rise:.05},neck:{at:[0,.22,.14],points:[[0,0,0],[0,.06,.04]],radius:.05},head:{at:[0,.07,.04],radii:[.08,.075,.09]},muzzle:{at:[0,-.02,.07],radii:[.035,.028,.03]},ears:{at:[.035,.08,-.02],radii:[.022,.1,.03],rotate:[-15,0,-8]},eyes:{at:[.045,.015,.06],size:.02},tail:{at:[0,.2,-.18],points:[[0,0,0],[0,.03,-.02]],radius:.03},extras:()=>[{id:"nose",parent:"muzzle",shape:{type:"ellipsoid",radii:[.012,.009,.009],segments:8},at:[0,.012,.03],fill:"#e48a9a",outline:.4}],colors:{coat:"#c9b8a6",dark:"#9a8574",foot:"#b5a493",muzzle:"#eadfd2",accent:"#f4ece2",...t.colors},gaits:["walk","gallop"],cycleScale:.4,call:"squeak",grazes:!0})}function ey(t={}){return rn({kind:t.kind??"squirrel",summary:t.summary??"A squirrel: scampers (gallop) and walks, chatters, sits up, nibbles (graze), with a bushy tail curled over its back.",legs:{upper:.05,lower:.05,foot:.02,footSize:[.025,.04],front:.08,hind:-.08,across:.04,thickness:[.02,.025],lowerThickness:.014},body:{radii:[.065,.07,.14],rise:.03},neck:{at:[0,.16,.1],points:[[0,0,0],[0,.04,.03]],radius:.035},head:{at:[0,.05,.03],radii:[.055,.05,.06]},muzzle:{at:[0,-.015,.05],radii:[.025,.02,.02]},ears:{at:[.03,.05,-.01],radii:[.015,.03,.012],rotate:[0,0,-5]},eyes:{at:[.035,.012,.04],size:.015},tail:{at:[0,.14,-.13],points:[[0,0,0],[0,.08,-.06],[0,.2,-.04],[0,.26,.04]],radius:.045},colors:{coat:"#a9663a",dark:"#7a4523",foot:"#7a4523",muzzle:"#e9c9a8",accent:"#f0dcc4",...t.colors},gaits:["walk","gallop"],cycleScale:.3,call:"chatter",grazes:!0})}const an=.6,ny=75,Qc=80;function ln(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*an/2,t.wing.chord*.1,t.wing.chord/2],segments:12},at:[h*t.wing.span*an/2,0,-t.wing.chord*.1],rotate:[-Qc,0,0],fill:e.wing,outline:.8}),a.push({id:`wing-${u}-tip`,parent:`wing-${u}-blade`,shape:{type:"ellipsoid",radii:[t.wing.span*an/2.4,t.wing.chord*.06,t.wing.chord*.3],segments:10},at:[h*t.wing.span*an/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-an)/2,0,0],rotate:{axis:"x",degrees:Qc},scale:[1/an,1,1]},{parts:["wing-right-blade"],translate:[-t.wing.span*(1-an)/2,0,0],rotate:{axis:"x",degrees:Qc},scale:[1/an,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)/ny,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}}]},grip:{description:"The toes curled down round a perch: 0 flat on the ground, 1 gripping",unit:"0..1",min:0,max:1,bind:[{parts:["toes-left","toes-right"],rotate:{axis:"x",degrees:55}}]}},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:p4(t),acting:sy,colors:{body:e.body,ink:"#26262b"},moves:g4(t)}}function g4(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 sy={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 p4(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:ny},{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;r.key(l+60,{grip:0},{act:!1});const 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,grip:h>0?1:0},{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 iy(t={}){return ln({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 oy(t={}){return ln({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 ry(t={}){return ln({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})}function ay(t={}){return ln({kind:"pigeon",summary:"A pigeon: walks with a bobbing head, pecks at crumbs, coos, flaps, flies and lands (on the ground, a ledge or a branch).",body:{radii:[.08,.075,.14],height:.14},head:{at:[0,.24,.12],radius:.045},beak:{length:.035,thickness:.014},wing:{shoulder:[.065,.17,.05],span:.24,chord:.11},tail:{at:[0,.13,-.13],length:.12,width:.08,raised:8},legs:{length:.06,across:.03},colors:{body:"#8d93a3",wing:"#6f7586",beak:"#5a5a66",legs:"#d9627a",belly:"#b9bdc8",...t.colors},call:"coo",beatsPerSecond:6,stoop:16})}function ly(t={}){return ln({kind:"duck",summary:"A duck: waddles, dabbles with its bill (peck), quacks, flaps, flies and lands (on the ground or the water’s edge).",body:{radii:[.11,.1,.2],height:.16},head:{at:[0,.33,.15],radius:.055},beak:{length:.075,thickness:.028},wing:{shoulder:[.09,.22,.06],span:.28,chord:.13},tail:{at:[0,.17,-.19],length:.1,width:.09,raised:30},legs:{length:.07,across:.045},colors:{body:"#c9b48b",wing:"#8f7a55",beak:"#f2a71b",legs:"#f2a71b",belly:"#e8dcc0",...t.colors},call:"quack",beatsPerSecond:7,stoop:22,neckReach:.04})}function cy(t={}){return ln({kind:"owl",summary:"An owl: a big round head, slow silent wingbeats; hoots, turns its head, flies and lands on a branch.",body:{radii:[.1,.12,.13],height:.19},head:{at:[0,.37,.07],radius:.085},beak:{length:.025,thickness:.02},wing:{shoulder:[.085,.27,.03],span:.34,chord:.18},tail:{at:[0,.14,-.12],length:.1,width:.1,raised:-10},legs:{length:.07,across:.04},colors:{body:"#9c7a55",wing:"#6e5538",beak:"#3d3028",legs:"#c9a76a",belly:"#e3cda8",...t.colors},call:"hoot",beatsPerSecond:3,stoop:6})}function hy(t={}){return ln({kind:"parrot",summary:"A parrot: bright, with a big hooked beak and a long tail; squawks, bobs, flies and lands on a perch, gripping it.",body:{radii:[.07,.08,.13],height:.15},head:{at:[0,.29,.1],radius:.055},beak:{length:.045,thickness:.03},wing:{shoulder:[.06,.2,.05],span:.26,chord:.11},tail:{at:[0,.12,-.12],length:.22,width:.06,raised:-20},legs:{length:.06,across:.03},colors:{body:"#4caf50",wing:"#2e7d32",beak:"#5a5a66",legs:"#8d8d8d",belly:"#a5d66f",comb:"#d9372e",...t.colors},call:"squawk",beatsPerSecond:6,stoop:10})}const Is={car:vm,truck:Mm,bus:Sm,tractor:xm,cart:Tm,trainCar:Em,bike:Am,motorbike:$m,tree:Pm,house:Om,chair:Cm,desk:Rm,bed:Fm,door:Wm,wheelchair:zm,helicopter:Ym,airplane:Km,horse:Um,dog:Vm,cat:Jm,cow:Zm,goat:Qm,rabbit:ty,squirrel:ey,songbird:iy,crow:oy,chicken:ry,pigeon:ay,duck:ly,owl:cy,parrot:hy};function th(t,e={}){const n=Is[t];if(!n)throw new Error(ft("prop preset",t,Object.keys(Is)));return n(e)}const Lr=["do","at","for","to","toward","speed","open","on","height","wind"],eh={viewer:0,right:1,away:2,left:3},m4=420,nh={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 Fr(t){return{...nh,...t.actions}}const sh=t=>typeof t=="number"&&Number.isFinite(t);function uy(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=Fr(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))Lr.includes(c)||a(ft("beat field",c,Lr,c==="duration"?"for":c==="direction"?"toward":void 0));if(typeof l.do!="string"||!s.includes(l.do))return a(ft(`${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&&!(sh(l[c])&&l[c]>=0)&&a(`\`${c}\` must be a number ≥ 0 (got ${JSON.stringify(l[c])}).`);if(l.to!==void 0&&!sh(l.to)&&a(`\`to\` is a scene x in px (got ${JSON.stringify(l.to)}).`),l.toward!==void 0&&!sh(l.toward)&&!(typeof l.toward=="string"&&l.toward in eh)){const c=typeof l.toward=="string"?Xs(l.toward,Object.keys(eh)):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 dy(t,e,n,s={}){const i=uy(n,e).filter(M=>M.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=Fr(e),h={};for(const M of[...Object.keys(Es),...Object.keys(e.rig.controls)])h[M]=s.start?.[M]??It(e.rig,{},M);const u=[{time:0,pose:{...h}}],d=new Map,f=[];let p=o,g=r;const m=(M,E,I,A)=>{const O=d.get(M)??[{time:0,value:M==="x"||M==="y"?0:h[M]}];O.push({time:E,value:I,...A?{easing:A}:{}}),d.set(M,O),M!=="x"&&M!=="y"&&(h[M]=I)},b=(M,E)=>{const I=M==="x"?p-o:M==="y"?g-r:h[M],A=d.get(M);(!A||A[A.length-1].time<E)&&m(M,E,I)},v={prop:e,scale:a,exaggeration:l,get x(){return p},get floor(){return g},values:h,facing(){const M=Math.sin(h.turn*Math.PI/2);return Math.abs(M)<.5?0:M>0?1:-1},key(M,E,I={}){Object.assign(h,E),u.push({time:M,pose:{...h},...I.act===!1?{act:!1}:{},...I.easing?{easing:I.easing}:{}})},move(M,E,I,A={}){b("x",M),m("x",E,I-o,A.easing),p=I,A.floor!==void 0&&(b("y",M),m("y",E,A.floor-r,A.easing),g=A.floor)},set(M,E,I,A){m(M,E,I,A)},turnTo(M,E){const I=typeof E=="number"?E:eh[E],A=h.turn,H=[I-4,I,I+4].map(j=>({t:j,d:Math.abs(j-A)})).sort((j,J)=>j.d-J.d||Math.abs(j.t)-Math.abs(J.t))[0];if(H.d<.001)return M;const W=M+m4*Math.max(1,H.d);return v.key(W,{turn:H.t}),W},effect(M){f.push(M)},anchor(M){const I=As(e,h,a).anchors[M];if(!I)throw new Error(`${e.kind}: no anchor "${M}"`);return{x:p+I.point.x,y:g+I.point.y}}},k=[];let w=0;for(const M of n){const E=Math.max(M.at??w,u[u.length-1].time),I=c[M.do].run(v,M,E);I.end>u[u.length-1].time&&u.push({time:I.end,pose:{...h}}),k.push({start:E,end:I.end,...I.contact!==void 0?{contact:I.contact}:{},...I.release!==void 0?{release:I.release}:{}}),w=I.end}const T=Mc(s.style??"snappy"),P={...T,anticipation:T.anticipation*l,overshoot:T.overshoot*l},S=Mr(k4(u),e.acting,{style:P}),x=[...Object.entries(S).filter(([M])=>!d.has(M)).map(([M,E])=>({id:`${t}-${M}`,target:t,property:M,keyframes:E})),...[...d].map(([M,E])=>({id:`${t}-${M}`,target:t,property:M,keyframes:v4(E)}))];for(const M of b4(t,e,x,w,u[0].pose)){const E=x.findIndex(O=>O.property===M.property);if(E<0){x.push(M);continue}const I=new Ht({id:`${t}-own`,tracks:[x[E]]}),A=O=>Number(I.getStateAtTime(O).values.get(t)?.get(M.property)??0);x[E]={...M,keyframes:M.keyframes.map(O=>({time:O.time,value:Number(O.value)+A(O.time)}))}}return{tracks:x,duration:w,beats:k,effects:f}}const y4=1500;function b4(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+y4,c=Gs(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 w4=20;function k4(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<w4?n[n.length-1]={...s,time:i.time}:n.push(s)}return n}function v4(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 Ne=Object.freeze({test:Object.freeze({name:"Test",inningsPerSide:2,oversPerInnings:null,ballsPerOver:6,freeHitAfterNoBall:!1,summary:"Multi-day cricket. Each side can have two innings; there is no innings over limit."}),odi:Object.freeze({name:"ODI",inningsPerSide:1,oversPerInnings:50,ballsPerOver:6,freeHitAfterNoBall:!0,summary:"One innings per side, up to 50 overs. A no-ball gives a free hit on the next legitimate delivery."}),t20:Object.freeze({name:"T20",inningsPerSide:1,oversPerInnings:20,ballsPerOver:6,freeHitAfterNoBall:!0,summary:"One innings per side, up to 20 overs. A no-ball gives a free hit on the next legitimate delivery."})}),ih=Object.freeze({adults:"Adults",men:"Men",children:"Children",mixed:"Mixed cast"}),Os=Object.freeze({bowler:"Bowler",keeper:"Wicketkeeper",fielder:"Extra cover",slip:"Slip",point:"Point",cover:"Cover","mid-off":"Mid-off","mid-on":"Mid-on","square-leg":"Square leg","fine-leg":"Fine leg","third-man":"Third man"}),Nn=Object.freeze(Object.fromEntries(Object.entries({bowling:{name:"Pace bowling",summary:"Run up, deliver with a straight arm, bounce and follow through."},spin:{name:"Spin bowling",summary:"A shorter approach and a curved illustrative flight before the bounce."},batting:{name:"Drive",summary:"Two hands on the bat, a backlift, contact and a follow-through."},defend:{name:"Defensive block",summary:"Meet the ball with a controlled bat and keep it close."},running:{name:"Running between wickets",summary:"Both batters make the opposite ground to complete one run."},four:{name:"Boundary four",summary:"A struck ball reaches the boundary after touching the ground."},six:{name:"Boundary six",summary:"A struck ball clears the boundary before touching the ground."},catch:{name:"Catch",summary:"A fielder controls the struck ball before it touches the ground."},fielding:{name:"Ground field",summary:"A fielder moves to the ball, bends and gathers it."},throw:{name:"Field and throw",summary:"Gather, wind up, release and return the ball to the keeper."},bowled:{name:"Bowled",summary:"A legal delivery hits the wicket and removes a bail."},lbw:{name:"LBW illustration",summary:"Pad contact and a projected path to the stumps illustrate an authored LBW decision."},stumping:{name:"Stumping",summary:"The keeper holds the ball and breaks the wicket while the striker is out of ground, not attempting a run."},"run-out":{name:"Run-out",summary:"A direct throw breaks the wicket before the running batter makes that ground."},"no-ball":{name:"Front-foot no-ball",summary:"The landing front foot oversteps the popping crease at release; one extra, no legal ball."},wide:{name:"Wide ball",summary:"An untouched delivery passes beyond reach for a normal stroke; one extra, no legal ball."}}).map(([t,e])=>[t,Object.freeze(e)])));function we(t,e,n){if(!Object.prototype.hasOwnProperty.call(t,e))throw new Error(`${n}: unknown choice '${e}'`);return e}function oh(t,e,n,s){const i=e*Math.PI/180,o=n*Math.PI/180;return[t[0]+s*Math.cos(o)*Math.sin(i),t[1]+s*Math.sin(o),t[2]+s*Math.cos(o)*Math.cos(i)]}const rh=(t,e,n)=>[t[0]+(e[0]-t[0])*n,t[1]+(e[1]-t[1])*n,t[2]+(e[2]-t[2])*n];function M4(t,e,n){const s={target:[0,0,0],yaw:0,pitch:15,distance:8,...t},i={...s,...e},o=rh(s.target,i.target,n),r=s.position||i.position?rh(s.position??oh(s.target,s.yaw,s.pitch,s.distance),i.position??oh(i.target,i.yaw,i.pitch,i.distance),n):oh(o,s.yaw+(i.yaw-s.yaw)*n,s.pitch+(i.pitch-s.pitch)*n,s.distance+(i.distance-s.distance)*n),a=rh(s.lookAt??s.target,i.lookAt??i.target,n),l=s.fov!==void 0||i.fov!==void 0?(s.fov??i.fov)+((i.fov??s.fov)-(s.fov??i.fov))*n:void 0;return{position:r,lookAt:a,fov:l}}function S4(t){const e=Math.max(1,t.every??33),n=Wt(t.easing??"ease-in-out"),s=`${t.scene}/${t.camera}`,i=[],o=[],r=[];for(let l=t.start;;l=Math.min(t.end,l+e)){const c=t.end>t.start?n((l-t.start)/(t.end-t.start)):1,h=M4(t.from,t.to,c);if(i.push({time:l,value:h.position}),o.push({time:l,value:h.lookAt}),h.fov!==void 0&&r.push({time:l,value:h.fov}),l>=t.end)break}const a=[{id:`${s}-move-position`,target:s,property:"position",keyframes:i},{id:`${s}-move-lookAt`,target:s,property:"lookAt",keyframes:o}];return r.length>0&&a.push({id:`${s}-move-fov`,target:s,property:"fov",keyframes:r}),a}function x4(t){const e=Math.max(1,t.every??33),n=t.offset??[0,2,6],s=t.lag??0,i=`${t.scene}/${t.camera}`,o=[],r=[];for(let a=t.start;;a=Math.min(t.end,a+e)){const l=t.subjectAt(a),c=t.subjectAt(Math.max(t.start,a-s));if(o.push({time:a,value:[c[0]+n[0],c[1]+n[1],c[2]+n[2]]}),r.push({time:a,value:l}),a>=t.end)break}return[{id:`${i}-follow-position`,target:i,property:"position",keyframes:o},{id:`${i}-follow-lookAt`,target:i,property:"lookAt",keyframes:r}]}const ah=Object.freeze({pitch:"Whole pitch",batter:"Batter close-up",bowler:"Bowler close-up",keeper:"Keeper close-up",field:"Whole ground",overhead:"Overhead ground",orbit:"360° ground orbit","follow-ball":"Follow the ball"}),fy=Object.freeze({pitch:75,batter:145,bowler:35,keeper:145,field:75,overhead:75,orbit:75,"follow-ball":75});function T4(t,e={}){const n=we(ah,e.view??"pitch","cricketCamera.view"),s=e.yaw??fy[n];if(!Number.isFinite(s))throw new Error("cricketCamera: yaw must be finite");const i=(s%360+360)%360,o=e.zoom??1;if(!Number.isFinite(o)||o<.25||o>4)throw new Error("cricketCamera: zoom must be between 0.25 and 4");const r=d=>o===1?d:Math.atan(Math.tan(d*Math.PI/360)/o)*360/Math.PI,a=e.every??40;if(!Number.isFinite(a)||a<16||a>1e3)throw new Error("cricketCamera: every must be between 16 and 1000 ms");if(n==="follow-ball"){const d=["x","y","z"].map(m=>{const b=t.timeline.tracks.find(T=>T.target===`${t.scene.id}/ball`&&T.property===m);if(!b||!("keyframes"in b)||!b.keyframes.length)throw new Error(`cricketCamera: missing ball ${m} keyframes`);const v=b.keyframes;let k=0,w=new fn({...b,keyframes:v.slice(0,2)});return T=>{const P=k;for(;k<v.length-2&&T-(b.delay??0)>v[k+1].time;)k++;return k!==P&&(w=new fn({...b,keyframes:v.slice(k,k+2)})),w.getValueAtTime(T)}}),f=x4({scene:t.scene.id,camera:"camera",start:0,end:t.duration,every:a,offset:[5,3,6],subjectAt:m=>d.map(b=>b(m))}),p=t.scene.objects.find(m=>m.id==="camera"&&m.kind==="camera"),g=r(p?.kind==="camera"&&p.projection==="perspective"?p.fov:48);return[...f,{id:`${t.scene.id}/camera-zoom-fov`,target:`${t.scene.id}/camera`,property:"fov",keyframes:[{time:0,value:g},{time:t.duration,value:g}]}]}const l=n==="field"||n==="overhead"||n==="orbit",c=n==="batter"?[.1,.85,9.3]:n==="bowler"?[.68,1,-9.55]:n==="keeper"?[0,.7,10.1]:[0,.65,0],h=l?t.boundaryRadius*2.8:n==="pitch"?29:4.3,u=n==="overhead"?89:l?52:n==="pitch"?16:12;return S4({scene:t.scene.id,camera:"camera",start:0,end:t.duration,every:a,easing:"linear",from:{target:c,yaw:i,pitch:u,distance:h,fov:r(l?48:n==="pitch"?50:46)},to:{yaw:n==="orbit"?i+360:i}})}function _s(t,e){if(!Array.isArray(t)||t.length!==3||!t.every(Number.isFinite))throw new Error(`${e}: expected three finite coordinates`)}function gy(t,e,n=40,s=[]){if(!Number.isFinite(t)||!Number.isFinite(e)||t<0||e<t)throw new Error("sampleTimes: expected finite ordered nonnegative times");if(!Number.isFinite(n)||n<16||n>1e3)throw new Error("sampleTimes: every must be between 16 and 1000 ms");if((e-t)/n>2e4)throw new Error("sampleTimes: too many samples");const i=new Set([t,e,...s.filter(o=>o>=t&&o<=e&&Number.isFinite(o))]);for(let o=t+n;o<e;o+=n)i.add(o);return[...i].sort((o,r)=>o-r)}function lh(t,e){if(py(t),!Number.isFinite(e))throw new Error("ballFlightPoint: time must be finite");const n=Math.max(0,Math.min(1,(e-t.start)/(t.end-t.start))),s=4*n*(1-n),i=t.to[0]-t.from[0],o=t.to[2]-t.from[2],r=Math.hypot(i,o)||1;return[t.from[0]+i*n-o/r*(t.curve??0)*s,t.from[1]+(t.to[1]-t.from[1])*n+(t.arc??0)*s,t.from[2]+o*n+i/r*(t.curve??0)*s]}function py(t){if(!t.target?.trim())throw new Error("ballFlight: target is required");if(_s(t.from,"ballFlight.from"),_s(t.to,"ballFlight.to"),!Number.isFinite(t.start)||!Number.isFinite(t.end)||t.start<0||t.end<=t.start)throw new Error("ballFlight: end must be greater than start, both finite and nonnegative");if(!Number.isFinite(t.arc??0)||(t.arc??0)<0||!Number.isFinite(t.curve??0))throw new Error("ballFlight: arc must be finite and nonnegative; curve must be finite")}function E4(t){py(t);const e=gy(t.start,t.end,t.every),n=e.map(s=>lh(t,s));return["x","y","z"].map((s,i)=>({id:`${t.id??"flight"}-${s}`,target:t.target,property:s,keyframes:e.map((o,r)=>({time:o,value:n[r][i]}))}))}const Ct=(t,e,n)=>Math.max(0,Math.min(1,(t-e)/(n-e))),Ft=t=>t*t*(3-2*t),Tt=(t,e)=>Us(t,e),ch=(t,e)=>pn(t,e);function hh(t,e){const n=e+((t-e+2)%4+4)%4-2;return n===0?0:n}function Cs(t,e,n=0){return Math.hypot(e[0]-t[0],e[2]-t[2])<.001?n:hh(Math.atan2(e[0]-t[0],e[2]-t[2])*2/Math.PI,n)}function my(){return{turn:1,"head.turn":90,"leg.left.spread":12,"leg.right.spread":12,"leg.left.swing":6,"leg.right.swing":6,"leg.left.knee":12,"leg.right.knee":12}}function yy(t,e){const n=t.objects.find(s=>s.id===e);if(!n||n.kind!=="character")throw new Error(`cricketAction: required character '${e}' is missing`);if(n.parent||n.rotation?.some(s=>s!==0)||n.quaternion||n.scale!==void 0)throw new Error(`cricketAction: '${e}' must use position and pose.turn, without a transformed parent, scale or object rotation`);return{object:n,who:gs({...n.character,height:n.height??1.78})}}function A4(t){return{position:[...t.object.position??[0,0,0]],pose:{...lt,...t.object.pose}}}function Ni(t,e,n,s){const i=Ve(t.who.plan,e.pose,{height:t.who.height,contact:t.who.contact});return Tt(e.position,i.chains[n][s])}function Wi(t,e,n){const s=Ni(t,e,`arm.${n}`,2),i=Ni(t,e,`arm.${n}`,1);return Tt(s,ch(Jt(se(s,i)),t.who.lineWidth*.5))}function $4(t,e,n){const s={...e.pose,"head.turn":0,"head.nod":0,"head.tilt":0},i=Ve(t.who.plan,s,{height:t.who.height,contact:t.who.contact}).head,o=se(n,Tt(e.position,i.center)),r=i.axes.map(c=>$e(o,c)),a=Math.atan2(r[0],r[2])*180/Math.PI,l=Math.atan2(-r[1],Math.hypot(r[0],r[2]))*180/Math.PI;return{...e,pose:{...e.pose,"head.turn":Math.max(-90,Math.min(90,a)),"head.nod":Math.max(-25,Math.min(30,l)),"head.tilt":0}}}function cn(t,e,n,s,i="hold"){let o={...e.pose};for(let r=0;r<10;r++){const a={...e,pose:o},l=Ve(t.who.plan,o,{height:t.who.height,contact:t.who.contact}),c=ss(t.who.plan,o,t.who.height),h=se(Wi(t,a,n),Ni(t,a,`arm.${n}`,2)),u=se(se(se(s,h),e.position),l.hip),d=ns(u,(o.roll??0)*Math.PI/180),f=Tt(c.root,Qt(d,-(o.turn??0)*Math.PI/2));o=fi(t.who.plan,o,`arm.${n}`,f,{height:t.who.height})}for(const[r,a]of Object.entries(St[i]))o[`hand.${n}.${r}`]=a;return{...e,pose:o}}function P4(t,e,n,s){const i=Jt(s),o=t.who.height/1.78;let r=cn(t,e,"left",n);return r=cn(t,r,"right",Tt(Wi(t,r,"left"),ch(i,.105*o))),{...r,bat:{grip:Wi(t,r,"left"),axis:i,scale:o}}}function I4(t){return Tt(t.grip,ch(t.axis,.51*t.scale))}function by(t){const e=Jt(t),n=Math.max(-1,Math.min(1,e[1]));return n>.999999?[0,0,0,1]:n<-.999999?Vt([1,0,0],180):Vt(Jt(Vs([0,1,0],e)),Math.acos(n)*180/Math.PI).map(s=>s===0?0:s)}function Nr(t,e,n){const s={};for(const i of Object.keys({...t,...e})){const o=t[i]??lt[i]??0;s[i]=o+((e[i]??lt[i]??0)-o)*n}return s}function uh(t,e){if(t<=e[0][0])return{...lt,...e[0][1]};for(let n=1;n<e.length;n++)if(t<=e[n][0])return Nr({...lt,...e[n-1][1]},{...lt,...e[n][1]},Ft(Ct(t,e[n-1][0],e[n][0])));return{...lt,...e.at(-1)[1]}}const Wr=Object.freeze({mcc:Object.freeze({name:"MCC",poppingCreaseHalfWidth:1.83,fieldingRadius:null,summary:"MCC minimum crease markings. The base Laws do not prescribe a limited-over restriction area."}),"icc-men":Object.freeze({name:"ICC men",poppingCreaseHalfWidth:7.5,fieldingRadius:27.43,summary:"ICC men: extended crease markings; ODI/T20 restriction-area arcs have a 27.43 m radius."}),"icc-women":Object.freeze({name:"ICC women",poppingCreaseHalfWidth:7.5,fieldingRadius:23,summary:"ICC women: extended crease markings; ODI/T20 restriction-area arcs have a 23 m radius."})});function O4(t){const[e,n]=t.centres,s=Math.hypot(n[0]-e[0],n[2]-e[2]),i=(n[0]-e[0])/s,o=(n[2]-e[2])/s,r=[];for(let a=0;a<2;a++){const l=a===0?n:e;for(let c=0;c<=64;c++){const h=(a+c/64)*Math.PI,u=Math.cos(h)*t.radius,d=Math.sin(h)*t.radius;r.push([l[0]+o*u+i*d,.018,l[2]-i*u+o*d])}}return r}function wy(t,e){_s(e,"cricketFieldingAreaContains.point");const n=t.fieldingArea;if(n==null)return null;if(!Number.isFinite(n.radius)||n.radius<=0)throw new Error("cricketFieldingAreaContains: radius must be positive and finite");if(!Array.isArray(n.centres)||n.centres.length!==2)throw new Error("cricketFieldingAreaContains: two centres are required");const[s,i]=n.centres;_s(s,"cricketFieldingAreaContains.centre"),_s(i,"cricketFieldingAreaContains.centre");const o=i[0]-s[0],r=i[2]-s[2],a=o*o+r*r,l=a?Math.max(0,Math.min(1,((e[0]-s[0])*o+(e[2]-s[2])*r)/a)):0;return Math.hypot(e[0]-s[0]-l*o,e[2]-s[2]-l*r)<=n.radius+1e-9}function ky(t){return Object.keys(Os).flatMap(e=>{const n=t.scene.objects.find(i=>i.id===e&&i.kind==="character");if(!n)return[];if(n.parent)throw new Error(`cricketFieldingPositions: '${e}' must be unparented for setup markers`);const s=[...n.position??[0,0,0]];return[{id:e,name:n.name??Os[e],position:s,inside:wy(t,s)}]})}function _4(t){return t.fieldingArea?ky(t).map(e=>({id:`fielding-review-${e.id}`,name:`${e.name}: ${e.inside?"inside":"outside"} restriction area`,kind:"line",closed:!0,width:.12,color:e.inside?"#d8eb8a":"#ee9670",points:Array.from({length:32},(n,s)=>[e.position[0]+Math.cos(s*Math.PI/16)*.7,.06,e.position[2]+Math.sin(s*Math.PI/16)*.7])})):[]}const jt=Object.freeze({length:20.12,width:3.05,poppingCrease:1.22,returnCrease:1.32,stumpHeight:.711,wicketWidth:.2286});function vy(t){if(!t.id?.trim())throw new Error("cricketPlayer: id is required");we({batter:1,bowler:1,keeper:1,fielder:1,umpire:1},t.role,"cricketPlayer.role");const e=we(Ii,t.preset??"youngMan","cricketPlayer.preset"),n=we(Ne,t.format??"t20","cricketPlayer.format"),s=we({none:1,cap:1,"sun-hat":1},t.headwear??"none","cricketPlayer.headwear"),i=e==="childBoy"||e==="childGirl",o=t.height??(i?1.24:1.78);if(!Number.isFinite(o)||o<.5||o>3)throw new Error("cricketPlayer: height must be between .5 and 3 metres");_s(t.position??[0,0,0],"cricketPlayer.position");const r=t.role==="umpire"?"#f5ebd5":n==="test"?"#f5f0df":t.color??"#3577b5",a=JSON.parse(JSON.stringify({...Ii[e],...t.appearance,outfit:kp("casual",{top:"shirt",shirt:r,trousers:t.role==="umpire"?"#405058":r,bottom:"trousers",trouserStyle:"plain",sleeves:"short",collar:!0,tie:null,shoes:"boots",shoeColor:"#f3ead7"}),hat:s==="none"?null:{style:s==="sun-hat"?"sunHat":"cap",color:r}}));return{id:t.id,name:t.role,kind:"character",look:"pen",height:o,position:[...t.position??[0,0,0]],character:a,pose:t.role==="batter"?my():{turn:t.role==="keeper"?2:0}}}function Dr(t,e,n,s,i=0){return{id:t,kind:"mesh",position:e,geometry:{type:"box",size:n},material:s,layer:i}}function C4(t,e){const n=jt.stumpHeight,s=(jt.wicketWidth-.036)/2;return[...[-1,0,1].map((i,o)=>({id:`${t}-stump-${o}`,kind:"mesh",position:[i*s,n/2,e],geometry:{type:"cylinder",radius:.018,height:n,segments:10},material:"wicket"})),...[-1,1].map((i,o)=>Dr(`${t}-bail-${o}`,[i*s/2,n+.015,e],[.105,.025,.035],"bail"))]}function My(t,e){return[{id:t,kind:"group",scale:e,visible:!1},Dr(`${t}-grip`,[0,.1,0],[.036,.28,.036],"bat-grip"),Dr(`${t}-blade`,[0,.51,0],[.108,.54,.055],"bat-blade"),Dr(`${t}-label`,[0,.41,.029],[.07,.16,.004],"bat-label")].map((s,i)=>i===0?s:{...s,parent:t})}function dh(t={}){const e=we(Ne,t.format??"t20","cricketField.format"),n=we(ih,t.cast??"adults","cricketField.cast"),s=we(Wr,t.markingProfile??"icc-men","cricketField.markingProfile"),i=Wr[s],o=t.boundaryRadius??64;if(!Number.isFinite(o)||o<24||o>250)throw new Error("cricketField: boundaryRadius must be between 24 and 250 metres");const r=t.id??"cricket";if(!r.trim())throw new Error("cricketField: id is required");const a=jt.length/2,l=e!=="test"&&i.fieldingRadius!==null?{radius:i.fieldingRadius,centres:[[0,0,-a],[0,0,a]]}:null,c={"striker-wicket":[0,0,a],"bowler-wicket":[0,0,-a],"striker-crease":[0,0,a-jt.poppingCrease],"bowler-crease":[0,0,-a+jt.poppingCrease]},h=[{id:"camera",kind:"camera",projection:"perspective",position:[25,9,6],lookAt:[0,.65,0],fov:48,near:.02,far:Math.max(600,o*4)},{id:"sun",kind:"light",light:"directional",position:[4,8,5],intensity:.8,color:"#fff2dd"},{id:"ambient",kind:"light",light:"ambient",intensity:.85,color:"#eaf6f4"},{id:"outfield",kind:"mesh",layer:-4,position:[0,-.04,0],geometry:{type:"cylinder",radius:o+1,height:.06,segments:80},material:"grass"},{id:"square",kind:"mesh",layer:-3,geometry:{type:"plane",size:[8,25]},position:[0,.003,0],material:"square"},{id:"pitch",kind:"mesh",layer:-2,geometry:{type:"plane",size:[jt.width,jt.length]},position:[0,.008,0],material:"pitch"},{id:"boundary",kind:"line",layer:-1,closed:!0,width:.15,color:"#f8f2db",points:Array.from({length:96},(p,g)=>[Math.cos(g*Math.PI/48)*o,.022,Math.sin(g*Math.PI/48)*o])}];l&&h.push({id:"fielding-circle",kind:"line",layer:-1,closed:!0,width:.06,color:"#d6e4c8",points:O4(l)});for(const p of[-1,1]){const g=p>0?"striker":"bowler",m=p*a,b=m-p*jt.poppingCrease;h.push(...C4(g,m));const v=(k,w)=>h.push({id:`${g}-${k}`,kind:"line",layer:-1,color:"#fffdf0",width:.045,points:w});v("popping-line",[[-i.poppingCreaseHalfWidth,.02,b],[i.poppingCreaseHalfWidth,.02,b]]),v("bowling-line",[[-1.32,.02,m],[1.32,.02,m]]);for(const k of[-1,1])v(`return-line-${k<0?"left":"right"}`,[[k*1.32,.02,b],[k*1.32,.02,m+p*2.5]])}const u=[["batter","batter",[-.38,0,9.3]],["non-striker","batter",[-.85,0,-9.3]],["bowler","bowler",[.68,0,-17]],["keeper","keeper",[0,0,11.25]],["fielder","fielder",[12,0,-3]],["slip","fielder",[3.5,0,12]],["point","fielder",[20,0,6]],["cover","fielder",[22,0,-16]],["mid-off","fielder",[9,0,-25]],["mid-on","fielder",[-9,0,-25]],["square-leg","fielder",[-20,0,7]],["fine-leg","fielder",[-20,0,35]],["third-man","fielder",[23,0,35]],["umpire","umpire",[0,0,-12.4]],["square-umpire","umpire",[-15,0,8.84]]];u.forEach(([p,g,m],b)=>{const v=n==="children"||n==="mixed"&&b%3===0,k=n==="men"?"youngMan":v?b%2?"childGirl":"childBoy":b%2?"youngWoman":"youngMan",w=Math.hypot(m[0],m[2]),T=w>o*.88?[m[0]*o*.88/w,0,m[2]*o*.88/w]:[...m];c[p]=[...T];const P=vy({id:p,role:g,preset:k,format:e,position:T,color:g==="batter"?t.battingColor??"#397cb9":t.fieldingColor??"#bf604e"});if(Object.hasOwn(Os,p)&&(P.name=Os[p]),p!=="batter"){const S=p==="non-striker"||p==="bowler"?u[0][2]:u.find(([x])=>x==="bowler")[2];P.pose={turn:Cs(T,S)}}h.push(P)});const d=p=>h.find(g=>g.id===p).height/1.78;h.push(...My("bat",d("batter")),...My("non-striker-bat",d("non-striker"))),h.push({id:"ball",kind:"mesh",position:[0,.075,0],geometry:{type:"sphere",radius:.075,segments:12},material:"ball"}),h.push({id:"lbw-guide",kind:"group",visible:!1},{id:"lbw-projection",kind:"line",parent:"lbw-guide",points:[[0,0,0],[0,1,0]],width:.04,color:"#e9ae38"});const f=p=>({color:p,shading:"toon",outline:{color:"#69513a",width:.8}});return{format:e,boundaryRadius:o,landmarks:c,markingProfile:s,fieldingArea:l,scene:{id:r,formatVersion:1,camera:"camera",background:{top:"#c8e5ef",bottom:"#e9efcc"},ground:0,objects:h,materials:{grass:{color:"#81a95c",shading:"unlit"},square:{color:"#a6b76a",shading:"unlit",doubleSided:!0},pitch:{color:"#ddbd85",shading:"unlit",doubleSided:!0},wicket:f("#edd99e"),bail:f("#bd8c4d"),"bat-grip":f("#385b5c"),"bat-blade":f("#e8c58d"),"bat-label":f("#c34d4c"),ball:{color:e==="test"?"#b32d36":"#fff9e7",shading:"toon",outline:{color:"#9b3840",width:1}}}}}}const Yt=1900,Di=2450,Et=2900,Bi=4100,hn=4200,Hs=4600,Br=5300,fh=5500;function zr(t,e,n,s,i,o,r=t.object.pose?.turn??0){const a=Ct(e,n,s),l=Js(i,o),c=Cs(i,o,r),h=r+(c-r)*Ft(Ct(e,n,n+200)),u={...lt,...t.object.pose,turn:h},d=Jo("run",t.who.height,1,t.object.character?.legLength??1),f=Vo("run",l*a/d,u),p=Math.min(a*12,(1-a)*12,1);return{position:mn(i,o,a),pose:Nr(u,f,Math.max(0,p))}}function gh(t,e,n){const s=(t.pose.turn??0)*Math.PI/2;return Tt(t.position,[Math.sin(s)*e,n,Math.cos(s)*e])}function H4(t,e,n,s,i){const o=`${e}/${n.object.id}`,r={...lt,...n.object.pose},a=new Set(i.flatMap(l=>Object.keys(l.pose)));for(const l of a){const c=r[l]??0;i.some(h=>h.pose[l]!==c)&&t.push({id:`${n.object.id}-${l}`,target:o,property:l,keyframes:s.map((h,u)=>({time:h,value:i[u].pose[l]??c}))})}for(const[l,c]of["x","y","z"].entries())i.some(h=>h.position[l]!==(n.object.position?.[l]??0))&&t.push({id:`${n.object.id}-${c}`,target:o,property:c,keyframes:s.map((h,u)=>({time:h,value:i[u].position[l]}))});if(i[0].bat){const l=n.object.id==="batter"?"bat":"non-striker-bat",c=`${e}/${l}`;t.push({id:`${l}-visible`,target:c,property:"visible",keyframes:[{time:0,value:1}]}),t.push({id:`${l}-position`,target:c,property:"position",keyframes:s.map((h,u)=>({time:h,value:[...i[u].bat.grip]}))}),t.push({id:`${l}-rotation`,target:c,property:"quaternion",interpolation:"slerp",keyframes:s.map((h,u)=>({time:h,value:by(i[u].bat.axis)}))})}}function R4(t,e){const n={runs:0,extras:0,wickets:0,legalBall:!0,freeHitNext:!1};t==="running"&&(n.runs=1),t==="four"&&(n.runs=4),t==="six"&&(n.runs=6),(t==="wide"||t==="no-ball")&&(n.extras=1,n.legalBall=!1),t==="no-ball"&&(n.freeHitNext=Ne[e].freeHitAfterNoBall);const i={catch:"caught",bowled:"bowled",lbw:"lbw",stumping:"stumped","run-out":"run-out"}[t];return i&&(n.wickets=1,n.dismissal=i),n}function Sy(t,e={}){return xy(t,e)}function xy(t,e,n){const s=we(Nn,e.action??"bowling","cricketAction.action"),i=n?n.delivery.legality==="no-ball":s==="no-ball",o=n?n.delivery.legality==="wide":s==="wide",r=n?n.delivery.style==="spin":s==="spin";we(Ne,t.format,"cricketAction.format");const a=n?.result??R4(s,t.format),l=e.duration??6e3;if(!Number.isFinite(l)||l<4e3||l>6e4)throw new Error("cricketAction: duration must be between 4000 and 60000 ms");const c=t.scene.id;for(const $ of["ball","bat","non-striker-bat","lbw-guide","striker-bail-0","striker-bail-1","bowler-bail-0","bowler-bail-1"])if(!t.scene.objects.some(_=>_.id===$))throw new Error(`cricketAction: required equipment '${$}' is missing`);const h=Object.fromEntries(["batter","non-striker","bowler","keeper","fielder","umpire"].map($=>[$,yy(t.scene,$)]));for(const $ of["slip","point","cover","mid-off","mid-on","square-leg","fine-leg","third-man","square-umpire"])t.scene.objects.some(_=>_.id===$&&_.kind==="character")&&(h[$]=yy(t.scene,$));const u=$=>h[$].who.height,d=$=>A4(h[$]),f=$=>Math.round($*6e3/l*1e9)/1e9,p=$=>$*l/6e3,g=["batting","defend","running","four","six","catch","fielding","throw","run-out"].includes(s),m=["bowling","spin","no-ball","stumping"].includes(s),b=["catch","fielding","throw","run-out","batting","running"].includes(s),v=s==="running"||s==="run-out",k=new Map,w=[d("bowler").position[0],0,i?-8.25:-9.55],T=s==="fielding"?[10.5,0,2]:[9,0,-1],P=d("fielder").position,S=($,_)=>{let z=k.get($);z||(z=new Map,k.set($,z));const K=z.get(_);if(K)return K;const N=h[$];let F=d($);if($==="bowler"){const D=F.position;if(_<1400){const X=Tt(w,[0,0,-.65]);F=zr(N,_,0,1400,D,X),F.pose["arm.right.swing"]=45,F.pose["arm.right.elbow"]=80}else F.position=_<=Yt?mn(Tt(w,[0,0,-.65]),w,Ft(Ct(_,1400,Yt))):Tt(w,[0,0,.8*Ft(Ct(_,Yt,2600))]),F.pose=uh(_,[[1400,{turn:0,"arm.right.swing":285,"arm.right.elbow":8,"arm.left.swing":115,"leg.right.swing":15,"leg.left.knee":45}],[1800,{turn:0,"arm.right.swing":180,"arm.right.elbow":0,"arm.left.swing":80,"leg.right.swing":25,"leg.right.knee":0,"leg.left.swing":-25,"leg.left.knee":60}],[Yt,{turn:0,lean:8,"arm.right.swing":155,"arm.right.elbow":0,"arm.left.swing":45,"leg.right.swing":25,"leg.right.knee":0,"leg.left.swing":-25,"leg.left.knee":60}],[2250,{turn:0,lean:26,bend:12,"arm.right.swing":40,"arm.right.elbow":0,"arm.left.swing":-35,"leg.left.swing":-35,"leg.left.knee":55}],[3e3,{turn:0,"head.turn":10}],[6e3,{turn:0,"head.turn":10}]]);r&&(F.pose={...F.pose,"arm.right.spread":18,"head.tilt":-5});for(const[X,B]of Object.entries(_<Yt?St.hold:St.open))F.pose[`hand.right.${X}`]=B}else if($==="batter"||$==="non-striker"){const D=u($);if(s==="lbw"&&$==="batter"&&(F.position[0]=0),s==="stumping"&&$==="batter"&&(F.position[2]-=1.1*Ft(Ct(_,2150,2800))),v&&_>3050){const X=S($,3050),B=$==="batter"?[1,0,-9.5]:[-1,0,9.5];F=zr(N,_,3050,s==="run-out"?6e3:fh,X.position,B,X.pose.turn);const et=Wi(N,F,"right");F.bat={grip:et,axis:Jt([.7,-.35,.5]),scale:D/1.78}}else{F.pose={...F.pose,...$==="batter"?my():{turn:.15,"leg.left.knee":8,"leg.right.knee":8}};let B=[0,-1,$==="batter"?.05:.12],Z=Tt(F.position,[D*.15,D*.44,D*.04]);if($==="non-striker"&&(Z=Tt(F.position,[D*.08,D*.44,D*.17])),$==="batter"){const et=Ft(Ct(_,2100,2600))*(1-Ft(Ct(_,2600,Et))),R=Ft(Ct(_,2600,Et))*(1-Ft(Ct(_,Et,3800))),U=Ft(Ct(_,Et,3250))*(1-Ft(Ct(_,3250,4e3)));if(g){Z=Tt(F.position,[D*(.15+.03*et-.02*R-.03*U),D*(.44+.14*et+.07*R+.23*U),D*(.04+.16*et-.12*R-.06*U)]),B=Jt([.15*et+.25*U,-1+1.85*et+1.6*U,.05+.55*et-.4*R-.8*U]),F.pose.turn=1+.12*R+.3*U,F.pose.lean=3+4*R;const nt=12+4*R;F.pose["leg.left.spread"]=nt,F.pose["leg.right.spread"]=nt,s==="defend"&&(B=[0,-1,-.08],Z=Tt(F.position,[D*.1,D*.5,-D*.12]))}else if(["stumping","bowled","lbw"].includes(s)){const nt=Ft(Ct(_,2100,2700))*(1-Ft(Ct(_,4e3,4500)));B=Jt([.15*nt,-1+1.85*nt,.05+.55*nt]),Z=Tt(F.position,[D*(.15+.03*nt),D*(.44+.14*nt),D*(.04+.16*nt)])}}F=P4(N,F,Z,B)}}else if($==="keeper"){F.pose={...F.pose,turn:Cs(F.position,d("bowler").position,2),lean:20,"leg.left.swing":22,"leg.right.swing":22,"leg.left.knee":50,"leg.right.knee":50},o&&(F.position[0]=2.15*Ft(Ct(_,2900,3500))),s==="stumping"&&(F.position[2]-=.85*Ft(Ct(_,3400,3900)));const D=gh(F,u($)*.27,u($)*.44);if(s==="stumping"&&_>=3500){const X=gh({...F,position:d($).position},u($)*.27,u($)*.44),B=[0,jt.stumpHeight,jt.length/2],Z=mn(X,B,Ft(Ct(_,3500,3900)));F=cn(N,F,"right",Z),F=cn(N,F,"left",Tt(Z,[.045,0,0]))}else F=cn(N,F,"right",D),F=cn(N,F,"left",Tt(D,[.045,0,0]))}else if($==="fielder"&&b){if(F=zr(N,_,3050,s==="catch"?3800:3950,P,T),_>=3800){const D={...lt,turn:Cs(T,d("batter").position,F.pose.turn),lean:s==="catch"?5:42,bend:s==="catch"?0:18,"leg.left.swing":s==="catch"?0:45,"leg.right.swing":s==="catch"?0:45,"leg.left.knee":s==="catch"?0:85,"leg.right.knee":s==="catch"?0:85,smile:.7};F.pose=Nr(F.pose,D,Ft(Ct(_,3800,hn)));const X=gh(F,u($)*.22,u($)*(s==="catch"?.73:.2));if(F=cn(N,F,"right",X),F=cn(N,F,"left",Tt(X,[.035,0,0])),(s==="throw"||s==="run-out")&&_>hn){const B={...lt,turn:Cs(T,s==="throw"?d("keeper").position:t.landmarks["bowler-wicket"],F.pose.turn),"arm.right.swing":225,"arm.right.elbow":60,"arm.left.spread":70,"leg.left.swing":15},Z={...B,"arm.right.swing":110,"arm.right.elbow":0,lean:15};F.pose=uh(_,[[hn,F.pose],[4450,B],[Hs,Z],[4900,{...lt,turn:B.turn,"arm.right.swing":25,lean:22}],[6e3,{...lt,turn:B.turn}]])}}}else if($==="umpire"){let D={...lt};const X=s==="stumping"?4150:s==="run-out"?5150:s==="bowled"||s==="lbw"?3500:s==="catch"?4350:5100;if(s==="no-ball")D={...D,"arm.right.spread":90,"arm.right.elbow":0};else if(s==="wide")D={...D,"arm.right.spread":90,"arm.left.spread":90,"arm.right.elbow":0,"arm.left.elbow":0};else if(s==="six")D={...D,"arm.right.spread":180,"arm.left.spread":180,"arm.right.elbow":0,"arm.left.elbow":0};else if(s==="four")D={...D,"arm.right.spread":90-70*(.5+Math.sin((_-5100)/180)*.5),"arm.right.elbow":12};else if(["catch","bowled","lbw","stumping","run-out"].includes(s)){D={...D,"arm.right.swing":165,"arm.right.elbow":0};for(const[B,Z]of Object.entries(St.point))D[`hand.right.${B}`]=Z}if(n){const B={...lt},Z=[[0,B]];let et=B;if(i||o){const R=i?Yt:3100;et=i?{...B,"arm.right.spread":90,"arm.right.elbow":0}:{...B,"arm.right.spread":90,"arm.left.spread":90,"arm.right.elbow":0,"arm.left.elbow":0},Z.push([R,B],[R+350,et])}if(a.wickets||s==="four"||s==="six"){const R=a.wickets?X:5100;let U=D;if(a.wickets){U={...B,"arm.right.swing":165,"arm.right.elbow":0};for(const[nt,at]of Object.entries(St.point))U[`hand.right.${nt}`]=at}Z.push([R,et],[R+350,U])}F.pose=uh(_,Z)}else F.pose=Nr(F.pose,D,Ft(Ct(_,s==="no-ball"?Yt:s==="wide"?3100:X,(s==="no-ball"?Yt:s==="wide"?3100:X)+350)))}return z.set(_,F),F},x=($,_)=>Wi(h[$],S($,_),"right"),M=g?I4(S("batter",Et).bat):s==="lbw"?mn(Ni(h.batter,S("batter",Et),"leg.right",1),Ni(h.batter,S("batter",Et),"leg.right",2),.6):[m?jt.wicketWidth/2+.075+.15:0,.45,9.25],E=x("bowler",Yt),I=[o?.85:r?-.35:s==="lbw"?M[0]*.6:0,.075,3.9],A=x("keeper",s==="stumping"?3400:3500),O=x("fielder",Bi),H=x("fielder",hn),W=s==="run-out"?"bowler":"striker",j=s==="run-out"?5e3:s==="stumping"?3900:3200,J=[t.boundaryRadius*.8,s==="six"?2.1:.075,-t.boundaryRadius*.6],tt=($,_,z,K,N,F=0,D=0)=>lh({target:`${c}/ball`,start:_,end:z,from:K,to:N,arc:F,curve:D},$),V=$=>{if($<=Yt)return x("bowler",$);if($<=Di)return tt($,Yt,Di,E,I,.15,r?.35:0);const _=o?Tt(A,[0,0,-.6]):M;if($<=Et)return tt($,Di,Et,I,_,.08);if(s==="bowled"){const K=[0,.36,jt.length/2];return $<=j?tt($,Et,j,M,K):tt($,j,4100,K,[0,.075,12.5],.2)}if(s==="lbw")return[...M];if(["bowling","spin","no-ball","wide","stumping"].includes(s)){const K=s==="stumping"?3400:3500;if(m&&$<=K){const N=[_[0],A[1],jt.length/2+.2];return $<=3200?tt($,Et,3200,_,N,.04):tt($,3200,K,N,A,.04)}return $<=K?tt($,Et,K,_,A,.04):x("keeper",$)}if(s==="defend")return tt($,Et,3400,M,Tt(M,[-.5,-M[1]+.075,-.7]),.12);if(s==="four"||s==="six"){if(s==="six")return $<=5e3?tt($,Et,5e3,M,J,12):tt($,5e3,5700,J,Tt(J,[2,-2.025,-1.5]));const K=[5,.075,5];return $<=3300?tt($,Et,3300,M,K,.5):tt($,3300,5e3,K,J)}if(s==="catch")return $<=Bi?tt($,Et,Bi,M,O,5):x("fielder",$);const z=[4,.075,5];if($<=3300)return tt($,Et,3300,M,z,.8);if($<=hn)return tt($,3300,hn,z,H);if(s==="throw"||s==="run-out"){if($<=Hs)return x("fielder",$);const K=x("fielder",Hs),N=s==="run-out"?[0,.42,-jt.length/2]:x("keeper",Br),F=s==="run-out"?j:Br;return $<=F?tt($,Hs,F,K,N,1.2):s==="run-out"?tt($,F,5700,N,[0,.075,-12],.18):x("keeper",$)}return[...H]},L=[],q=($,_,z,K,N)=>L.push({id:$,time:p(_),kind:z,label:K,caption:N}),G=n?{bowled:"Delivery hits stumps",lbw:"Pad contact",stumping:"Keeper breaks wicket","run-out":"Throw breaks wicket"}[s]??Nn[s].name:Nn[s].name;if(q("setup",0,"setup",G,n?`${n.delivery.style} delivery · ${n.delivery.legality}${n.freeHit?" · free hit":""}. ${Nn[s].summary.replace("A legal delivery","A delivery")}`:Nn[s].summary),q("release",Yt,"release","Ball released",i?"The front foot has landed beyond the popping crease. No-ball.":"The bowler releases the ball; the front foot is behind the popping crease."),q("bounce",Di,"bounce","Pitch bounce",r?"The curved flight is illustrative. Spin can change the ball’s path after it bounces.":"The delivery bounces on the pitch on its way to the striker."),g?q("contact",Et,"contact","Bat contact","The ball meets the blade. The bat is keyed from the same two hand grips."):s==="lbw"?q("pad-contact",Et,"contact","Pad contact",n?"The ball contacts the pad. The highlighted path is illustrative; the authored decision is resolved separately.":"The highlighted path illustrates a ball that would hit the stumps. This is an authored LBW example."):q("miss",Et,"contact",s==="wide"?"Beyond normal reach":"The batter misses",s==="wide"?"The untouched ball is too far away for a normal stroke. The umpire calls Wide.":"The untouched delivery passes the striker."),s==="catch"&&q("catch",Bi,"collect","Catch controlled",n?"The fielder controls the ball before it touches the ground. The authored decision is resolved separately.":"The fielder controls the ball before it touches the ground: caught."),["fielding","throw","run-out","batting","running"].includes(s)&&q("gather",hn,"collect","Ground ball gathered","The ball has touched the ground. Gathering it is fielding, not a catch dismissal."),["bowling","spin","wide","no-ball","stumping"].includes(s)&&q("keeper",s==="stumping"?3400:3500,"collect","Keeper gathers","The keeper controls the ball behind the striker’s wicket."),(s==="throw"||s==="run-out")&&q("throw",Hs,"throw","Throw released","The fielder releases the gathered ball toward the wicket."),s==="throw"&&q("return",Br,"collect","Return received","The keeper receives and controls the return throw."),s==="stumping"&&q("wicket",j,"wicket",n?"Wicket broken":"Stumped","Holding the ball, the keeper removes a bail. The striker is out of ground and is not attempting a run."),s==="run-out"&&q("wicket",j,"wicket",n?"Wicket broken":"Run out","The direct throw removes a bail before the running batter makes this ground."),s==="bowled"&&q("wicket",j,"wicket",n?"Stumps hit":"Bowled",n?"The delivery hits the wicket and removes a bail. A broken wicket does not by itself decide a dismissal.":"The legal delivery hits the wicket and removes a bail."),(s==="four"||s==="six")&&q("boundary",5e3,"boundary",s==="four"?"Four runs":"Six runs",s==="four"?"The struck ball reaches the boundary after touching the ground: four.":"The struck ball clears the boundary without touching the ground: six."),s==="running"&&q("run",fh,"result","One run completed","Both batters have reached the opposite ground. One run is completed."),q("result",5700,"result","Illustrated result",s==="no-ball"?`One no-ball extra; it does not count in the over.${a.freeHitNext?" The next legitimate delivery is a free hit.":" Test cricket has no automatic free hit."}`:s==="wide"?"One wide extra; the delivery does not count in the over.":s==="lbw"?"LBW is declared for this illustrated legal delivery. A full decision also checks pitching, impact and any bat contact.":`${a.runs} bat runs · ${a.extras} extras · ${a.wickets} wicket${a.wickets===1?"":"s"}.`),n){const $={"no-dismissal":"No dismissal was authored for this play.",dismissal:`The authored ${n.ruling.dismissal} decision is allowed in this delivery context.`,"no-ball":`Not out: ${s==="catch"?"a catch":"this dismissal"} cannot dismiss the striker on a no-ball.`,"free-hit":`Not out: ${s==="catch"?"a catch":"this dismissal"} cannot dismiss the striker on a free hit.`,wide:"Not out: this dismissal is not available from a Wide."},_=L.find(z=>z.id==="result");_.label=a.wickets?"Out":"Not out",_.caption=`${$[n.ruling.reason]} ${a.runs} bat runs · ${a.extras} extras · ${a.wickets} wickets. ${a.legalBall?"Counts as a legal ball.":"Does not count in the over."}${a.freeHitNext?" The next delivery is a free hit; an illegal delivery carries it forward.":n.freeHit?" This legal delivery consumes the free hit.":""}`}L.sort(($,_)=>$.time-_.time);const C=gy(0,l,e.every,[1400,1800,Yt,2100,2150,2250,Di,2600,2800,Et,3050,3100,3200,3250,3300,3400,3500,3800,3900,3950,4e3,Bi,hn,4350,4450,Hs,4900,5e3,5100,5150,Br,fh,5700].map(p)),Y=C.map($=>V(f($))),st=[];for(const[$,_]of Object.entries(h)){let z=_.object.pose?.turn??0,K=z;const N=C.map((F,D)=>{const X=f(F);let B=$==="fielder"&&b&&X>3050&&X<3250?zr(_,X,3050,s==="catch"?3800:3950,P,T,K):S($,X),Z=Y[D];const et=!["batter","non-striker","bowler","keeper"].includes($);if(et){const U=S("bowler",Math.min(X,Yt)),nt=Tt(U.position,[0,u("bowler")*.8,0]);Z=X<=Yt?nt:X<2100?mn(nt,Z,Ft(Ct(X,Yt,2100))):Z}if(v&&($==="batter"||$==="non-striker")&&X>3050&&(Z=$==="batter"?[1,u($)*.8,-10.5]:[-1,u($)*.8,10.5]),$==="bowler"&&X<=Et&&(Z=Tt(S("batter",X).position,[0,u("batter")*.65,0])),et&&($!=="fielder"||!b||X<=3050)||$==="bowler"&&X>=3e3){const U=Cs(B.position,Z,z);z=$==="bowler"&&X<3500?(B.pose.turn??0)+(hh(U,B.pose.turn??0)-(B.pose.turn??0))*Ft(Ct(X,3e3,3500)):U,B={...B,pose:{...B.pose,turn:z}}}return $==="fielder"&&b&&(X===3050?K=z:X>3050&&(z=hh(B.pose.turn??0,z),B={...B,pose:{...B.pose,turn:z}})),$4(_,B,Z)});H4(st,c,_,C,N)}for(const[$,_]of["x","y","z"].entries())st.push({id:`ball-${_}`,target:`${c}/ball`,property:_,keyframes:C.map((z,K)=>({time:z,value:Y[K][$]}))});if(["bowled","stumping","run-out"].includes(s))for(let $=0;$<2;$++){const _=`${W}-bail-${$}`,K=t.scene.objects.find(N=>N.id===_).position;st.push({id:`${_}-fall`,target:`${c}/${_}`,property:"position",keyframes:[{time:0,value:[...K]},{time:p(j),value:[...K]},{time:p(j+180),value:Tt(K,[$?.25:-.25,.22,W==="striker"?.22:-.22]),easing:"ease-out"},{time:p(j+650),value:[K[0]+($?.4:-.4),.035,K[2]+(W==="striker"?.45:-.45)],easing:"ease-in"}]}),st.push({id:`${_}-spin`,target:`${c}/${_}`,property:"rotateZ",keyframes:[{time:0,value:0},{time:p(j),value:0},{time:p(j+650),value:$?145:-145}]})}if(s==="lbw"){const $=[M[0]*.8,M[1],jt.length/2],_=se($,M);st.push({id:"lbw-position",target:`${c}/lbw-guide`,property:"position",keyframes:[{time:0,value:[...M]}]},{id:"lbw-rotation",target:`${c}/lbw-guide`,property:"quaternion",interpolation:"slerp",keyframes:[{time:0,value:by(_)}]},{id:"lbw-length",target:`${c}/lbw-guide`,property:"scaleY",keyframes:[{time:0,value:Js(M,$)}]},{id:"lbw-visible",target:`${c}/lbw-guide`,property:"visible",keyframes:[{time:0,value:0},{time:p(Et)-.001,value:0},{time:p(Et),value:1}]})}return{action:s,duration:l,events:L,result:a,timeline:{id:`${c}-${s}`,formatVersion:2,name:G,config:{duration:l,markers:L.map($=>({id:$.id,time:$.time,label:$.label}))},captions:{en:Object.fromEntries(L.map($=>[$.id,$.caption]))},tracks:st}}}function L4(t={}){const e=dh(t);return{...e,...Sy(e,t)}}function F4(t,e){if(!Number.isFinite(e))throw new Error("cricketEventAt: time must be finite");let n;for(const s of t){if(s.time>e)break;n=s}return n}const un=Object.freeze({deliveryStyles:Object.freeze(["pace","spin"]),deliveryLegalities:Object.freeze(["legal","no-ball","wide"]),shots:Object.freeze(["miss","drive","defend"]),finishes:Object.freeze(["none","single","four","six","stumps","pad"]),fielding:Object.freeze(["none","keeper","catch","gather","throw","stumping","run-out"]),dismissals:Object.freeze(["caught","bowled","lbw","stumped","run-out"])});function Rs(t,e,n){if(!t.includes(e))throw new Error(`cricketPlay.${n}: unknown choice '${e}'`);return e}function N4(t){const{shot:e,finish:n,fielding:s}=t;if(t.delivery.legality==="wide"){if(e!=="miss"||n!=="none"||s!=="keeper")throw new Error("cricketPlay: Wide currently supports only an untouched delivery gathered by the keeper");return"wide"}if(e==="miss"){if(s==="none"&&n==="stumps")return"bowled";if(s==="none"&&n==="pad")return"lbw";if(n==="none"&&s==="stumping")return"stumping";if(n==="none"&&s==="keeper")return t.delivery.style==="spin"?"spin":"bowling"}if(e==="defend"&&n==="none"&&s==="none")return"defend";if(e==="drive"){if(s==="none"&&(n==="four"||n==="six"))return n;if(s==="gather"&&n==="single")return"running";if(n==="none"){if(s==="catch")return"catch";if(s==="gather")return"fielding";if(s==="throw")return"throw";if(s==="run-out")return"run-out"}}throw new Error(`cricketPlay: unsupported motion combination (${e}, ${n}, ${s})`)}function W4(t){const e=Rs(un.shots,t.shot??"miss","shot"),n=Rs(un.finishes,t.finish??"none","finish");let s=e==="miss"?"keeper":"gather";(e==="defend"||n!=="none")&&(s=n==="single"?"gather":"none");const i=Rs(un.fielding,t.fielding??s,"fielding"),o=t.context?.freeHit??!1;if(typeof o!="boolean")throw new Error("cricketPlay.context.freeHit must be boolean");const r=t.decision?.dismissal??null;return r!==null&&Rs(un.dismissals,r,"decision.dismissal"),{delivery:{style:Rs(un.deliveryStyles,t.delivery?.style??"pace","delivery.style"),legality:Rs(un.deliveryLegalities,t.delivery?.legality??"legal","delivery.legality")},shot:e,finish:n,fielding:i,context:{freeHit:o},decision:{dismissal:r}}}function D4(t,e){const n=t.decision.dismissal;if(!n)return{dismissal:null,reason:"no-dismissal"};if({catch:"caught",bowled:"bowled",lbw:"lbw",stumping:"stumped","run-out":"run-out"}[e]!==n)throw new Error(`cricketPlay: '${n}' decision does not match '${e}' motion`);if(n!=="run-out"){if(t.context.freeHit)return{dismissal:null,reason:"free-hit"};if(t.delivery.legality==="no-ball")return{dismissal:null,reason:"no-ball"};if(t.delivery.legality==="wide"&&n!=="stumped")return{dismissal:null,reason:"wide"}}return{dismissal:n,reason:"dismissal"}}function Ty(t,e={}){const n=we(Ne,t.format,"cricketPlay.format"),s=W4(e);if(s.context.freeHit&&!Ne[n].freeHitAfterNoBall)throw new Error("cricketPlay: Test format does not support free-hit context");const i=N4(s),o=D4(s,i),r=s.delivery.legality==="legal",a={runs:s.finish==="single"?1:s.finish==="four"?4:s.finish==="six"?6:0,extras:r?0:1,wickets:o.dismissal?1:0,legalBall:r,freeHitNext:Ne[n].freeHitAfterNoBall&&(s.delivery.legality==="no-ball"||s.context.freeHit&&!r),...o.dismissal?{dismissal:o.dismissal}:{}};return{...xy(t,{action:i,duration:e.duration,every:e.every},{delivery:s.delivery,result:a,ruling:o,freeHit:s.context.freeHit}),play:s,ruling:o}}function B4(t={}){const e=dh(t);return{...e,...Ty(e,t)}}const Ey=Object.freeze({"no-ball-stumps":Object.freeze({name:"No-ball + stumps hit",options:Object.freeze({delivery:Object.freeze({legality:"no-ball"}),finish:"stumps",decision:Object.freeze({dismissal:"bowled"})})}),"free-hit-catch":Object.freeze({name:"Free hit + catch",options:Object.freeze({context:Object.freeze({freeHit:!0}),shot:"drive",fielding:"catch",decision:Object.freeze({dismissal:"caught"})})}),"no-ball-four":Object.freeze({name:"No-ball + four",options:Object.freeze({delivery:Object.freeze({legality:"no-ball"}),shot:"drive",finish:"four"})}),"free-hit-run-out":Object.freeze({name:"Free hit + run-out",options:Object.freeze({context:Object.freeze({freeHit:!0}),shot:"drive",fielding:"run-out",decision:Object.freeze({dismissal:"run-out"})})}),"free-hit-wide":Object.freeze({name:"Free hit + Wide",options:Object.freeze({context:Object.freeze({freeHit:!0}),delivery:Object.freeze({legality:"wide"})})})}),z4={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 Ay(t,e={}){const n={};for(const s of Object.keys(Kt))n[s]={summary:`Walks to \`to\` in the ${s} gait.`,needs:["to"]};for(const s of Object.keys(ae))n[s]={summary:`Moves into the ${s} pose and holds it (\`for\` ms).`};for(const s of Object.keys(nn))n[s]={summary:`The ${s} gag (${_i(s)} ms).`};for(const[s,i]of Object.entries(Ci))n[s]={...i};return{sports:{cricket:{actions:{...Nn},formats:{...Ne},casts:{...ih},fieldingPositions:{...Os},markingProfiles:{...Wr},cameras:{...ah},playComponents:un,playExamples:Ey}},...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(z4),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:Pr,stickFigure:{poseFields:zu,props:qu,handFields:ju,poses:Object.keys(ae),expressions:Object.keys(vt),gags:Object.fromEntries(Object.keys(nn).map(s=>[s,_i(s)])),gaits:Object.keys(Kt),actingStyles:Object.keys(Rn),beatFields:Sr,actions:n,dances:Object.fromEntries(Object.entries(Ue).map(([s,i])=>[s,Object.keys(i.moves)])),flips:Object.fromEntries(Object.entries(vi).map(([s,i])=>[s,i.label])),handShapes:Object.keys(St),mudras:Object.keys($o)},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 world metres: gaits, face (shortest turn), spin (signed turns and duration), dance (native style, bpm, beats), 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 / .driving / .cycling / .wheeling (a wheelchair)","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:Lr,commonControls:Object.fromEntries(Object.entries(Es).map(([s,i])=>[s,`${i.description}${i.unit?` (${i.unit})`:""}`])),commonActions:Object.fromEntries(Object.entries(nh).map(([s,i])=>[s,i.summary])),presets:Object.fromEntries(Object.entries(Is).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:{figureStyles:["fluid","stick","organic"],body:{"body.torso · body.arm · body.leg · body.neck":"Organic half-width profiles: [{ at: 0..1, width: fractionOfHeight }], increasing from 0 to 1; independent of ink width.","body.fill · body.outline · body.shading":"Shared skin fill, outline { color, width }, cel material { mode: cel | none, light: [x,y], shadow, opacity, highlight }.","softCartoonCharacter(name, options?)":"Original youngMan / youngWoman / childBoy / childGirl story presets. Children have larger head proportions, shorter limbs and rounded torsos; every face, hair, build, hand, clothing and material option can be overridden.","face.projection":"Organic default volume follows the head axes, keeps both eyes in three-quarter views and projects a small nose above the mouth; opaque hair covers features. cartoon keeps the classic face slide.","outfitPreset(category, overrides?)":"Fresh JSON Everyday / Formal / Casual wardrobe defaults for every actor; top: tshirt | shirt | blouse | dress, trouserStyle: plain | jeans | cargo, colours, sleeves, bottoms, collar and tie are editable.",leafOutfit:"Organic-only JSON garment { top?, color?, accent?, length? }; curved leaves follow torso/thighs at native part depths. Everyday basicOutfit also follows organic contours."},poses:Object.keys(ye),dances:Object.keys(Tn),expressions:Object.keys(cl),faceStyles:["simple","anime"],faceShapes:["round","angular"],gags:Object.keys(Zo),builds:Object.keys(Ho),hair:Object.keys(xl),hairColors:{...Te},facialHair:Object.keys(Pl),glasses:Object.keys(Ol),hats:Object.keys(Uo),feet:[...Bd],cast:Object.keys(wc),heldItems:Object.fromEntries(Object.entries(Rl).map(([s,i])=>[s,i.hands])),handMeetings:Object.keys(Oi)},codePanel:{languages:wr,removeStyles:yr,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:fc},surfaces:{code:Ai,board:He,chart:Cn,prop:$s},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: ${xs.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 yt=t=>t.map(e=>`\`${e}\``).join(", "),$y=t=>Object.entries(t).map(([e,n])=>`| \`${e}\` | ${n.unit??n.kind??""} | ${n.description} |`).join(`
|
|
63
|
-
`);function q4(t,e={}){const n=Ay(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: ${yt(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`).","","Style proportions: `headSize` is a fraction of height; `armLength` multiplies both upper arm and forearm lengths (default 1, positive finite). Hands, shoulders, torso and legs retain their sizes.","","### Pose fields","","| Field | Unit | What it does |","|---|---|---|",$y(s.poseFields),"","### Other props","","| Prop | Unit | What it does |","|---|---|---|",$y(s.props),"",`With \`style.hands\`, each hand has \`hand.left.<field>\` / \`hand.right.<field>\` props: ${yt(Object.keys(s.handFields))}.`,"",`**Poses** (a beat's \`do\`, or a pose key): ${yt(s.poses)}.`,"",`**Expressions** (a beat's \`mood\`): ${yt(s.expressions)}.`,"",`**Gags** (ms): ${Object.entries(s.gags).map(([o,r])=>`\`${o}\` (${r})`).join(", ")}.`,"",`**Gaits**: ${yt(s.gaits)}. **Acting styles** (\`style\`): ${yt(s.actingStyles)}.`,"","### Beat scripts","",`\`scriptTracks(target, beats, { from, ground, height, facing, style })\`. A beat has these fields only: ${yt(s.beatFields)}. Times are ms; \`to\` and \`target\` are scene px; \`onto\` is a floor's scene y.`,"","`characterScript(target, who, beats, options)` compiles the same beats for a v2 `character()` on a `characterTarget` (every option but `height`; the same result, its key poses on the human body; the walk phase keyed to that character's stride, and `walk` / `walking` / `gait` tracks that step the gait as the target draws). Add `hairFollowTracks(target, tracks, who)` after it so hanging hair swings.","","| `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**: ${yt(s.handShapes)}. **Mudras**: ${yt(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: ${yt(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(", ")}.`,"","Scenery: `scenery({ x, y, width, height, kind: sky | room, hour, clouds, wind, rain, snow, horizon: hills | city | flat })` is a canvas target whose values `hour` (0–24), `clouds`, `rain`, `snow` (0–1) and `wind` (−1..1) are tracks (`set(prop, { at, value, duration })`, `tracks(id)`; `anchor('sun' | 'moon' | 'horizon' | 'ground', time)`); the same `wind` streams hair (`hairFollowTracks(…, { wind })`). `scenePreset('park' | 'street' | 'office' | 'home', { width, height })` lays out scenery and props as data; `buildScene` builds them into targets.","","| 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: ${yt(n.character.poses)}. Expressions: ${yt(n.character.expressions)}. Gags: ${yt(n.character.gags)}.`,`Native dances: ${yt(n.character.dances)}; \`humanDanceFrame(style, beat, base)\` keeps body heading independent; \`humanDanceTracks(target, options)\` bakes JSON pose tracks. \`danceCircleAt(beat, { radius, count, beatsPerTurn, facing, spins })\` gives a formation with planted toes; \`danceCircleTracks(targets, options)\` bakes scene tracks. \`plantDanceFoot(partner, side, worldPoint)\` returns pose AND position; \`meetDandiya(a, b)\` solves both stick tips to one shared world point and reports unreachable contacts.`,"","Appearance options of `character({ … })`, all plain data that turns with the head (see docs/character-appearance.md):","",`- \`build\`: ${yt(n.character.builds)}`,`- \`figure\`: ${yt(n.character.figureStyles)}`,...Object.entries(n.character.body).map(([o,r])=>`- \`${o}\`: ${r}`),`- \`hair\`: ${yt(n.character.hair)} (colours: ${yt(Object.keys(n.character.hairColors))} in \`HAIR_COLORS\`)`,"- Flowing hair: `softSweep`, `flowingBob`, `cascadingWaves`; editable `locks: [{ path, width, follow? }]` with cubic `{ around, up, lift? }` points (around in degrees, dimensions in head radii), `fall: { taper, wave }` and `shine` (0–1). Roots stay attached; `hairFollowTracks` also drives flexible short locks.",`- \`facialHair\`: ${yt(n.character.facialHair)}`,`- \`glasses\`: ${yt(n.character.glasses)}; \`hat\`: ${yt(n.character.hats)}; \`ears: true\`; \`face: { teeth, tongue }\` (shown when the mouth opens); \`feet\`: ${yt(n.character.feet)}`,"- `outfit`: `{ top: tshirt | shirt | blouse | dress, trouserStyle: plain | jeans | cargo, shirt: top colour, trousers: bottom colour, sleeves: short | long | none, bottom: trousers | shorts | skirt, collar, tie: colour, over: apron | labCoat | hoodie | cardigan | overalls | sari, overColor, shoes: boots, shoeColor }`",`- \`castMember(name, height)\`: ${yt(n.character.cast)}`,"- Face marks (pose fields, 0–1): `blush`, `tears`, `sweat`; close-up fields `pupil` (size, 1 usual), `lid` (upper lids lowered, 0–1), `bulge` (eyes out of the head, 0–1); `face: { nose: true, inPupil(ctx, pupil) }`; `drawCharacterHead(ctx, who, pose, { x, y, radius })` draws just the head big",`- Face styles: ${yt(n.character.faceStyles)}; \`face: { style: 'anime', iris: '#4b7fce', lashes: true, ageLines: 0.8 }\` uses coloured eyes and the same expressions, blinks and gaze. \`ANIME_CAST\` contains eight age presets, also available through \`castMember\`.`,`- Face shapes: ${yt(n.character.faceShapes)}; \`face: { shape: 'angular', jawWidth: 0.74, chinWidth: 0.14, eyeScale: 0.8, eyeAspect: 0.65 }\` sets a tapered 3D jaw and narrower anime eyes; \`jawRoundness: 1\` softens the cheek/chin corners (default 0 keeps sharp jaws). \`MANGA_CAST\` contains four original young adult presets; hair styles \`mangaSpikes\` and \`mangaSweep\` remain editable.`,"- Hair in motion (pose fields): `hair.swing` (degrees round the head, + toward its left), `hair.trail` (head radii back), `hair.lift` (head radii up); key them with `hairFollowTracks(target, tracks, who)` after the character's tracks, or `hairFollow` + `hairMotionAt` when posing per frame",`- \`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): ${yt(n.character.handMeetings)}; \`embrace(a, b)\` (a hug, \`embraceSpacing\` apart); \`helpUp(helper, sitter, progress)\` (0 on the floor, hand taken; 1 standing; \`helpUpSpacing\` apart)`,"- Everyday cycles like a gait: `humanCyclePose('sweeping' | 'brushing', phase, base)` (0 → 1 is one stroke and back; sweeping with `holding: { right: 'broom' }`)","","## Code panel","",`\`codePanel({ code, language, x, y, fontSize?, lineHeight?, width? })\`: a code listing as a scene object. Languages: ${yt(n.codePanel.languages)}. Remove styles: ${yt(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}`),""]),"## Cricket stories (`@algorisys/tinyfly/sports`)","","`cricketClip({ format, action, cast })` returns an organic-player scene, JSON tracks, timed events/captions and a declared result. `cricketField`, `cricketPlayer` and `cricketAction` compose separately; `cricketCameraTracks` adds camera tracks. These are authored tutorial plays, not physics or automatic umpiring. See docs/cricket.md.","",`Marking profiles: ${yt(Object.keys(n.sports.cricket.markingProfiles))}; default ICC men, independently of cast. Limited-over ICC profiles draw a wicket-centred capsule; Test/MCC have no restriction-area line. \`cricketFieldingAreaContains(field, point)\` returns true/false/null; \`cricketFieldingPositions\` and \`cricketFieldingOverlay\` provide owned setup markers, not umpiring decisions.`,"","`cricketPlay(field, options)` / `cricketPlayClip(options)` independently author delivery style/legality, shot, finish, fielding, current free-hit context and candidate dismissal. Omitted dismissal means no dismissal. Unsupported motion combinations throw; no-ball/free-hit protection changes result/signals without removing physical catches or wicket breaks. Run-out remains available. Illegal free hits carry forward; legal ones consume context. Test rejects free-hit context. Keep innings/score/strike in the consuming app.","",...Object.entries(n.sports.cricket.playComponents).map(([o,r])=>`Play ${o}: ${yt(r)}`),...Object.entries(n.sports.cricket.playExamples).map(([o,r])=>`- Composed example \`${o}\`: ${r.name}`),"",...Object.entries(n.sports.cricket.actions).map(([o,r])=>`- \`${o}\`: ${r.summary}`),"",`Formats: ${yt(Object.keys(n.sports.cricket.formats))}. Casts: ${yt(Object.keys(n.sports.cricket.casts))}. Cameras: ${yt(Object.keys(n.sports.cricket.cameras))}. Orbit turns 360° around the whole ground. \`cricketCameraTracks(clip, { view, zoom })\` supports 0.25–4× optical magnification (default 1) in every view.`,"",`Stock fielding labels (\`CRICKET_FIELDING_POSITIONS\`): ${Object.entries(n.sports.cricket.fieldingPositions).map(([o,r])=>`\`${o}\`: ${r}`).join(", ")}. Eleven fielders, two on-field batters and two umpires; nine batting teammates wait off-field. Mid-on is closer to the pitch; long-on is its deeper boundary alternative, not an extra stock fielder. For the right-handed striker, +x is off side and -x is on/leg side.`,"","## 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 j4(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=ne(`${r.kind}:${r.time}:${r.x}`);r.kind==="dust"?Ip(t,{x:r.x,y:r.y},a,{size:o,color:i,seed:l}):r.kind==="exhaust"?X4(t,r,a,o,i,l):r.kind==="skid"?G4(t,r,a,n,i):r.kind==="honk"?U4(t,r,a,o,i):r.kind==="smoke"?Y4(t,r,n,o,i):r.kind==="leaves"&&K4(t,r,a,o,s.leafColor??"#5cae5a",i,l)}}function Y4(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 K4(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=ne(`${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 X4(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=(ne(`${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 G4(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 U4(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 V4(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 u=_r(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:J4(r)}),c}function J4(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 Z4(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 Q4(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,u;for(let f=t.start;;f=Math.min(t.end,f+n)){const p=_r(t.leader,{state:e.getStateAtTime(f)},t.leaderId),g=p.anchor(t.hitch),m=p.values.turn,b=As(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 v=g.x-b.point.x;if(u!==void 0&&r){const k=Math.sin(m*Math.PI/2);h+=(v-u)*(k||1)/s.propScale/r*(180/Math.PI)}if(u=v,a.push({time:f,value:v-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 Py=new WeakMap;function tx(t,e){const n=e?.some(Boolean)?e.map(d=>d?1:0).join(""):"";let s=Py.get(t);s||Py.set(t,s=new Map);const i=s.get(n);if(i)return i;const o=Li(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,b,v]=[f,p[g],p[g+1]],[k,w,T]=[r.vertices[m],r.vertices[b],r.vertices[v]],P=[w[0]-k[0],w[1]-k[1],w[2]-k[2]],S=[T[0]-k[0],T[1]-k[1],T[2]-k[2]],x=[P[1]*S[2]-P[2]*S[1],P[2]*S[0]-P[0]*S[2],P[0]*S[1]-P[1]*S[0]],M=x[0]*d.normal[0]+x[1]*d.normal[1]+x[2]*d.normal[2];c.push(...M>=0?[m,b,v]:[m,v,b])}});const h=l.flatMap(d=>{const f=Math.hypot(...d)||1;return[d[0]/f,d[1]/f,d[2]/f]}),u=lr({positions:a,normals:h,indices:c});return s.size>=16&&s.clear(),s.set(n,u),u}function ex(t,e,n={}){const s=t.ink??n.ink??"#26262b",i=(n.outline??2)*(t.outline??1),o=t.glow&&e.glow>0?nx(t.glow.color,e.glow):void 0;return{color:t.fill??s,creases:Li(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 nx(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 sx=lr(kg(1,.002,28));function ix(t,e,n){const s=t.rig,[i,o]=s.footprint??[s.length*.45,s.length],r=Math.max(0,It(s,e,"lift")),a=Math.max(0,It(s,e,"size"))/(1+r*.8);return{mesh:sx,world:Rt(n,Sa([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 ox=new Set(["x","y","z","position","rotateX","rotateY","rotateZ","quaternion","scale","scaleX","scaleY","scaleZ","visible","opacity","color"]),rx=1,ax={kind:"prop",validate(t){const e=t,n=typeof e.prop=="string"&&e.prop in Is?[]:[ft("prop preset",e.prop,Object.keys(Is))];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 th(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[S,x]of n)typeof x=="number"&&!ox.has(S)&&(h[S]=x);h.turn=0,h.tilt=0;const u=Rt(i.view,s),d={toView:S=>ie(u,S),toScreen:S=>a(S)},f=d.toView([0,c.rig.height/2,0]);if(-f[2]<=i.near)return null;if(l.look==="mesh"){const S=gm(c.rig,h),x=S.map(({part:I,local:A})=>({part:I.id,mesh:Li(I.shape),...zc(Li(I.shape),A)})),M=lm(x),E=S.map((I,A)=>({...I,hidden:hm(I.part.id,x[A].mesh,I.local,x[A].key,M)})).filter(({opacity:I})=>I>.01).map(({part:I,matrix:A,glow:O,opacity:H,hidden:W})=>({mesh:tx(I.shape,W),world:Rt(s,A),material:ex(I,{glow:O,opacity:H},{shading:l.shading,ink:l.ink,outline:l.outline})}));return{meshes:l.shadow===!1?E:[ix(c,h,s),...E]}}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),b=o.length===0?void 0:(S,x)=>{const M=ie(s,S),E=[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]],I=Math.hypot(...E)||1;return{light:vg(M,[E[0]/I,E[1]/I,E[2]/I],o),fog:Mg(r,Math.hypot(M[0]-i.position[0],M[1]-i.position[1],M[2]-i.position[2]))}},v=Xc(c.rig,h,d,m,{perspective:!0,near:i.near,slice:rx,light:b}),k={look:l.look,style:l.style,ink:l.ink,paper:l.paper,fog:r?.color},w=Gl(v),T=v.cells??[],P=Math.max(...T.map(S=>-S.depth),-f[2]);return{drawables:[...l.shadow===!1?[]:[{depth:P+c.rig.length,draw:S=>Ul(S,v,k)}],...T.map(S=>({depth:-S.depth,draw(x,M){x.lineCap="round",x.lineJoin="round",xg(x,S.parts,w,{...k,time:M.time})}}))]}}},ph=["do","at","for","to","through","toward","speed","height","open","on","wind"],lx=.25,cx=800/180,hx=220,ux=300,dx=["turn"];function fx(t){const e=Fr(t),n=Object.keys(t.moves??{});return Object.keys(e).filter(s=>!n.includes(s)&&!dx.includes(s)&&!(e[s].needs??[]).includes("to"))}function Iy(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=fx(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))ph.includes(u)||l(ft("beat field",u,ph,h[u]));if(typeof c.do!="string"||!i.includes(c.do)){const u=c.do==="turn"?"face":void 0;return l(ft(`${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&&!On(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(On))&&l("`through` is a list of points on the ground, each [x, z] metres.")),c.do==="face"&&!(On(c.toward)||typeof c.toward=="number")&&l("`face` needs `toward`: a point [x, z] or a heading in degrees.")}),o}function gx(t,e,n,s){const i=Iy(n,e);if(i.length>0)throw new Error(`propScript3D (${e.kind}): ${i.length} problem(s) in the beats:
|
|
60
|
+
`)}`);const r=n.map(d=>nm(d,e)),o=$o(t,r,s),a=E3(r,o.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 x3(d)){const g=b=>new Error(`surfaceScript: beat ${f} (${d.do}), ${p.edit} on ${p.surface}: ${b}`),m=(b,T)=>{const $=typeof b=="object"?b.beat:f,M=(typeof b=="object"?b.at:b)??T??"start",x=a[$][M];if(x===void 0){const S=Ts.filter(E=>a[$][E]!==void 0).join(", ");throw g(`beat ${$} (${n[$].do}) has no ${M} (it has ${S})`)}return x},w=e[p.surface],v=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<v)throw g(`it ends (${k} ms) before it starts (${v} ms)`);try{if(p.edit==="carry"){const T=w.piece(p.anchor),$=jc(t,c(o.tracks),{x:s.from??0,y:l,style:s.figureStyle??(s.height?{height:s.height}:void 0),cast:s,start:v,end:k});w.follow(T,$);continue}const b=Object.fromEntries(Object.entries(p).filter(([T])=>!M3.includes(T)));w.edit(p.edit,p.anchor,{...b,at:v,...k!==void 0?{duration:k-v}:{}})}catch(b){throw g(b.message)}}});const h=c(o.tracks),u=Object.entries(e).flatMap(([d,f])=>f.tracks(d));return{...o,tracks:[...h,...u],figureTracks:h}}function em(t,e,n={}){if(!Array.isArray(t))return Ri(t,n);const s=[],i=Object.keys(e),r=(c,h,u)=>{const d=typeof h=="string"?e[h]:void 0;return d||s.push({level:"error",beat:c,message:`${u}: ${ft("surface",h,i)}`}),d},o=(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 (${Ts.join(", ")}), not at ms; set the beat's own \`at\` to move it.`}):(typeof d!="string"||!Ts.includes(d))&&s.push({level:"error",beat:c,message:`${u}: ${ft("moment",d,Ts)}`})};t.forEach((c,h)=>{if(!c||typeof c!="object"||Array.isArray(c))return;const u=c;for(const f of["target","to","onto"]){if(!Po(u[f]))continue;const p=u[f],g=r(h,p.surface,`\`${f}\``);g&&o(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=r(h,p.surface,"`then`");if(!g)return;const m=`\`then\` (${String(p.edit)} on ${String(p.surface)})`,w=[...Object.keys(g.about.edits),...S3];if(typeof p.edit!="string"||!w.includes(p.edit)){s.push({level:"error",beat:h,message:`\`then\`: ${ft("edit",p.edit,w)}`});return}for(const v of Array.isArray(p.anchor)?p.anchor:[p.anchor])o(h,g,v,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)?nm(c,e,!0):c);return[...Ri(l,n),...s]}function nm(t,e,n=!1){const{then:s,...i}=t,r=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}},o={...i};return Po(t.target)&&(o.target=r(t.target)),Po(t.to)&&(o.to=r(t.to).x),Po(t.onto)&&(o.onto=r(t.onto).top),o}function E3(t,e,n){let s=0;return t.map(i=>{const r=Eo([i],n.actions).length,o=e.slice(s,s+r);s+=r;const a=o.find(c=>c.contact!==void 0)?.contact,l=[...o].reverse().find(c=>c.release!==void 0)?.release;return{start:o[0]?.start,end:o[o.length-1]?.end,...a!==void 0?{contact:a}:{},...l!==void 0?{release:l}:{}}})}function A3(t){const e={actions:t.actions,gaits:t.gaits},n=_c(e);if(n.length>0)throw new Error(`persona "${t.name}": ${n.join(" ")}`);const s=[...Object.keys(Kt),...Object.keys(t.gaits??{})],i=t.gait??"walk";if(!s.includes(i))throw new Error(`persona "${t.name}": ${ft("gait",i,s)}`);if(t.mood&&!(t.mood in vt))throw new Error(`persona "${t.name}": ${ft("mood",t.mood,Object.keys(vt))}`);const r=t.acting??"snappy";if(typeof r=="string"&&!(r in Ln))throw new Error(`persona "${t.name}": ${ft("acting style",r,Object.keys(Ln))}`);if(typeof t.stance=="string"&&!(t.stance in ae))throw new Error(`persona "${t.name}": ${ft("stance",t.stance,Object.keys(ae))}`);const o=t.height??120,a=typeof t.stance=="string"?ae[t.stance]:Dt(t.stance??{}),l=t.mood?Ve(a,t.mood):a,c={...t.look,height:o},h=t.summary??`${t.name}, a stick figure`;return{name:t.name,summary:h,cast:e,rest:l,height:o,figure:u=>ol({x:u.x,y:u.y,pose:l,style:{...c,...u.facing?{facing:u.facing}:{}},cast:e}),script:(u,d,f={})=>$o(u,d,{...e,from:f.from,ground:f.ground,facing:f.facing,height:o,style:r,gait:i,start:l,rest:l,energy:t.energy}),check:u=>Ri(u,e),handPath:(u,d,f)=>jc(u,d,{...f,style:c,cast:e}),describe:()=>({name:t.name,summary:h,habits:{height:o,acting:typeof r=="string"?r:"custom",gait:i,...t.mood?{mood:t.mood}:{},stance:typeof t.stance=="string"?t.stance:t.stance?"custom":"rest"},actions:Hc(e),own:{actions:Object.keys(t.actions??{}),gaits:Object.keys(t.gaits??{})}})}}const $3=new Set(["x","y","walking","gait"]),sm=.215+.205;function im(t,e,n=1){const{points:s}=fe(t,lt),i=s["hip.left"],r=s["knee.left"],o=s["ankle.left"],a=i&&r&&o?Math.hypot(r.x-i.x,r.y-i.y)+Math.hypot(o.x-r.x,o.y-r.y):sm*t.height;return Jr(e,a/sm,n)}function P3(t,e,n,s={}){const i=$o(t,n,{...s,height:e.height,reach:s.reach??rm(e)}),r=i.tracks.find(w=>w.property==="facing")?.keyframes??[],o=w=>{let v=s.facing??1;for(const k of r)k.time<=w&&(v=k.value);return v},a=Ar(i.keys),l=i.keys.map((w,v)=>{const k=xg(a[v]);return{time:w.time,pose:o(w.time)<0?Xd(k):k,...w.easing?{easing:w.easing}:{},...w.act===!1?{act:!1}:{}}}),{rest:c,start:h,...u}=s;C3(l,a,n,i,e,o,s);const d=Hp(t,l,u),f=fo(t,d,i.lines,{energy:s.energy}),p=i.tracks.filter(w=>$3.has(w.property)),g=i.tracks.find(w=>w.property==="walk");return{tracks:g?[...f,...p,N3(t,g,i.tracks,e,s)]:[...f,...p],duration:i.duration,lines:i.lines,keys:l,beats:i.beats,effects:i.effects}}function rm(t){const e=kt({"arm.left.spread":90,"arm.left.elbow":0,"arm.left.bend":0,"leg.left.knee":0}),n=fe(t,e).points,s=Math.hypot(n["hand.left"].x-n["shoulder.left"].x,n["hand.left"].y-n["shoulder.left"].y),i=Math.hypot(n["toe.left"].x-n["hip.left"].x,n["toe.left"].y-n["hip.left"].y),r=ye({...ut,rightShoulder:90,rightElbow:0,rightWrist:0},{height:t.height,facing:1}),o=ye({...ut,rightHip:90,rightKnee:0},{height:t.height,facing:1}),a={x:(r.hands.right.x+r.fingertips.right.x)/2,y:(r.hands.right.y+r.fingertips.right.y)/2},l=Math.hypot(a.x-r.shoulders.right.x,a.y-r.shoulders.right.y),c=Math.hypot(o.feet.right.x-o.hip.x,o.feet.right.y-o.hip.y);return{arm:l>0?s/l:1,leg:c>0?i/c:1}}const I3={point:"arm",grab:"arm",put:"arm",write:"arm",swipe:"arm",push:"arm",kick:"leg"},O3=new Set(["point","grab","put","kick"]);function C3(t,e,n,s,i,r,o){const a=s.beats;if(n.length!==a.length)return;const l=new Ht({id:"placed",tracks:s.tracks.filter(h=>h.property==="x"||h.property==="y")}),c=h=>{const u=l.getStateAtTime(h).values.get(s.tracks[0]?.target??"");return{x:(o.from??0)+Number(u?.get("x")??0),y:(o.ground??0)+Number(u?.get("y")??0)}};n.forEach((h,u)=>{const d=I3[h.do],f=a[u];if(!d||f.contact===void 0||h.do!=="swipe"&&!h.target)return;const p=f.contact,g=f.release??f.contact;t.forEach((m,w)=>{if(m.time<p-1||m.time>g+1)return;const v=r(m.time),k=ye(e[w],{height:i.height,facing:v<0?-1:1}),b=c(m.time),T=O3.has(h.do)&&h.target?{x:h.target.x-b.x,y:h.target.y-b.y}:void 0,$={x:(k.hands.right.x+k.fingertips.right.x)/2,y:(k.hands.right.y+k.fingertips.right.y)/2},M=T??(d==="arm"?$:k.toes.right),x=v<0?"right":"left",S=`${d}.${x}`;let E=m.pose;if(h.do==="point")E=_e(i,E,S,M);else if(d==="arm")E=_e(i,F3(i,E,x,M),S,M);else for(let I=0;I<3;I++){const A=fe(i,E).points,O=A[`ankle.${x}`],H=A[`toe.${x}`];E=_e(i,E,S,{x:M.x-(H.x-O.x),y:M.y-(H.y-O.y)})}t[w]={...m,pose:E}})})}function _3(t,e){const n=kt({[`arm.${e}.spread`]:90,[`arm.${e}.elbow`]:0,[`arm.${e}.bend`]:0}),s=fe(t,n).points;return Math.hypot(s[`hand.${e}`].x-s[`shoulder.${e}`].x,s[`hand.${e}`].y-s[`shoulder.${e}`].y)}const H3=5,R3=4,L3=8;function F3(t,e,n,s){const i=_3(t,n)*.9,r=a=>{const l=fe(t,a).points[`shoulder.${n}`];return Math.hypot(s.x-l.x,s.y-l.y)<=i};if(r(e))return e;let o=e;for(let a=1;a<=L3;a++)if(o={...e,lean:(e.lean??0)+H3*a,bend:(e.bend??0)+R3*a},r(o))return o;return o}function N3(t,e,n,s,i){const r=n.find(u=>u.property==="gait"),o=r?new Ht({id:`${t}-gait-of`,tracks:[r]}):void 0,a=u=>{const d=o?.getStateAtTime(u).values.get(t)?.get("gait");if(typeof d=="string")return Kt[d]??i.gaits?.[d]??d},l=e.keyframes,c=[];let h=l[0]?.value??0;return l.forEach((u,d)=>{if(d>0){const f=l[d-1],p=a((f.time+u.time)/2),g=xr(p,s.height),m=im(s,p);h+=(u.value-f.value)*(m>0?g/m:1)}else h=u.value;c.push({...u,value:h})}),{...e,keyframes:c}}const mt=["rect","circle","text","line","path","image","custom"],Io={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:mt},y:{description:"Moves it down by this much from where it was placed (an offset)",unit:"px",types:mt},opacity:{description:"How opaque it is",unit:"0..1",min:0,max:1,types:mt},rotate:{description:"Turns it clockwise about its origin",unit:"degrees",types:mt},rotateX:{description:"Tips it about the horizontal axis (3D; shows with perspective)",unit:"degrees",types:mt},rotateY:{description:"Turns it about the vertical axis (3D; shows with perspective)",unit:"degrees",types:mt},z:{description:"Depth toward the viewer (shows with perspective)",unit:"px",types:mt},perspective:{description:"Distance from the viewer: nearer parts grow, further ones shrink",unit:"px",min:1,types:mt},scale:{description:"Size, both ways",unit:"factor",types:mt},scaleX:{description:"Width factor",unit:"factor",types:mt},scaleY:{description:"Height factor",unit:"factor",types:mt},skewX:{description:"Slants it sideways",unit:"degrees",types:mt},skewY:{description:"Slants it up and down",unit:"degrees",types:mt},originX:{description:"Transform pivot across its box",unit:"% (0 left, 50 centre, 100 right)",min:0,max:100,types:mt},originY:{description:"Transform pivot down its box",unit:"% (0 top, 50 centre, 100 bottom)",min:0,max:100,types:mt},fill:{description:"Fill colour (also written fillStyle)",kind:"color",types:mt},stroke:{description:"Outline colour (also written strokeStyle)",kind:"color",types:mt},strokeWidth:{description:"Outline width (also written lineWidth)",unit:"px",min:0,types:mt},clipTop:{description:"Hides this much from the top edge, for reveals",unit:"% of its height",min:0,max:100,types:mt},clipRight:{description:"Hides this much from the right edge",unit:"% of its width",min:0,max:100,types:mt},clipBottom:{description:"Hides this much from the bottom edge",unit:"% of its height",min:0,max:100,types:mt},clipLeft:{description:"Hides this much from the left edge",unit:"% of its width",min:0,max:100,types:mt},blur:{description:"Gaussian blur",unit:"px",min:0,types:mt},brightness:{description:"Brightness factor (1 unchanged)",unit:"factor",min:0,types:mt},glow:{description:"Soft glow around it, in glowColor",unit:"px",min:0,types:mt},glowColor:{description:"Colour of the glow",kind:"color",types:mt},shadowX:{description:"Drop shadow offset right",unit:"px",types:mt},shadowY:{description:"Drop shadow offset down",unit:"px",types:mt},shadowBlur:{description:"Drop shadow softness",unit:"px",min:0,types:mt},shadowColor:{description:"Drop shadow colour",kind:"color",types:mt},shine:{description:"A highlight sweeping across the fill",unit:"0..1 (progress)",min:0,max:1,types:mt},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:mt},quaternion:{description:'A rotation as [x, y, z, w] (a track with interpolation: "slerp")',kind:"list",types:mt}},Yc={fillStyle:"fill",strokeStyle:"stroke",lineWidth:"strokeWidth",rotateZ:"rotate",motionPathX:"x",motionPathY:"y",motionPathRotate:"rotate"},W3={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 om(t){const e=t,n=Object.entries(Io).filter(([,i])=>i.types.includes(t.type)).map(([i,{types:r,...o}])=>({name:i,...o,...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,r]of Object.entries(t.props??{}))n.push({name:i,description:s?.props?.[i]?.description??"",...s?.props?.[i],value:r});return{type:"custom",...s?{kind:s.kind,summary:s.summary}:{},properties:n,...s?.actions?{actions:s.actions}:{}}}function am(t){const e=om(t).properties.map(n=>n.name);return[...e,...Object.keys(Yc).filter(n=>e.includes(Yc[n]))]}function D3(t,e){const n=[],s=Object.keys(e);for(const i of t){const r=d=>n.push({level:"error",track:i.id,message:d}),o=e[i.target];if(!o){r(ft("target",i.target,s));continue}const a=am(o),l=o.type==="custom"&&o.acceptsProp?.(i.property);if(!a.includes(i.property)&&!l){r(`${i.target}: ${ft("property",i.property,a,W3[i.property])}`);continue}const c=i.keyframes??[];for(let d=1;d<c.length;d++)c[d].time<c[d-1].time&&r(`${i.target}.${i.property}: keyframes out of time order (${c[d-1].time} ms, then ${c[d].time} ms).`);const h=Io[Yc[i.property]??i.property]??o.about?.props?.[i.property],u=h&&(h.kind??"number")==="number";for(const d of c){if(u&&typeof d.value!="number"){r(`${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 Es=(t,e)=>t[2]<=-e;function Kc(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 lm(t,e){if(t.every(s=>Es(s,e)))return t;const n=[];return t.forEach((s,i)=>{const r=t[(i+t.length-1)%t.length],o=Es(s,e),a=Es(r,e);o!==a&&n.push(Kc(r,s,e)),o&&n.push(s)}),n.length>=3?n:[]}function B3(t,e){if(t.every(i=>Es(i,e)))return[t];const n=[];let s=[];return t.forEach((i,r)=>{const o=Es(i,e);if(r>0){const a=t[r-1],l=Es(a,e);l&&!o?(s.push(Kc(a,i,e)),n.push(s),s=[]):!l&&o&&s.push(Kc(a,i,e))}o&&s.push(i)}),s.length>0&&n.push(s),n.filter(i=>i.length>=2)}function cm(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},(r,o)=>t+s*o/i)}function z3(t,e,n){const s=(i,r)=>Math.max(0,Math.min(i.length-2,i.findIndex((o,a)=>a>0&&r<=o)-1));return[s(t,n[0]),s(e,n[2])]}function q3(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]],r=Math.hypot(...i)||1;return[i[0]/r,i[1]/r,i[2]/r]};return{...t,vertices:t.vertices.map(s=>ie(e,s)),faces:t.faces.map(s=>({corners:s.corners,normal:n(s.normal)}))}}function Oo(t,e,n,s){const i=o=>(o[e]-n)*s>=0;if(t.every(i))return t;const r=[];return t.forEach((o,a)=>{const l=t[(a+t.length-1)%t.length];if(i(o)!==i(l)){const c=(n-l[e])/(o[e]-l[e]);r.push([0,1,2].map(h=>h===e?n:l[h]+(o[h]-l[h])*c))}i(o)&&r.push(o)}),r.length>=3?r:[]}function j3(t,e,n){const s=t.faces.map(o=>({points:o.corners.map(a=>t.vertices[a]),normal:o.normal})),i=[],r={x:e.slice(1,-1),z:n.slice(1,-1)};for(let o=0;o+1<e.length;o++)for(let a=0;a+1<n.length;a++){const l=[],c=new Map,h=p=>{const g=p.map(w=>Math.round(w*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(o)||(g=Oo(g,0,e[o],1)),g.length&&!f(o,e)&&(g=Oo(g,0,e[o+1],-1)),g.length&&!d(a)&&(g=Oo(g,2,n[a],1)),g.length&&!f(a,n)&&(g=Oo(g,2,n[a+1],-1)),g.length>=3&&u.push({corners:g.map(h),normal:p.normal})}u.length>0&&i.push({cell:[o,a],mesh:{vertices:l,faces:u,creases:t.creases,joined:t.joined,walls:r}})}return i}const Y3=new WeakMap,K3=new WeakMap,X3=48,hm=t=>t.map(e=>Math.round(e*1e5)).join(",");function um(t,e,n,s){let i=t.get(e);i||t.set(e,i=new Map);let r=i.get(n);return r===void 0&&(i.size>=X3&&i.clear(),i.set(n,r=s())),r}function Xc(t,e){const n=hm(e);return um(Y3,t,n,()=>{const s=q3(t,e),i=[1/0,1/0,1/0],r=[-1/0,-1/0,-1/0];for(const o of s.vertices)for(const a of[0,1,2])i[a]=Math.min(i[a],o[a]),r[a]=Math.max(r[a],o[a]);return{key:n,inSpace:s,low:i,high:r}})}function G3(t,e){const n=t.map(h=>({...h,...Xc(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 r=cm(s[0],i[0],e),o=cm(s[2],i[2],e),a=`${r.join(",")}|${o.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:z3(r,o,d)}]}return um(K3,h.inSpace,a,()=>j3(h.inSpace,r,o)).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])=>[(r[h]+r[h+1])/2,c,(o[u]+o[u+1])/2]}}const dm=.004,Gc=.05,fm=new WeakMap;function U3(t){let e=fm.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)}),fm.set(t,e)),e}const gm=new WeakMap;function pm(t){return t.filter(({mesh:e})=>U3(e)).map(({part:e,key:n,inSpace:s,low:i,high:r})=>{let o=gm.get(s);return o||(o=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]}}),gm.set(s,o)),{part:e,key:n,planes:o,low:i,high:r}})}function V3(t,e,n,s){const i=e.reduce((r,o)=>[r[0]+o[0]/e.length,r[1]+o[1]/e.length,r[2]+o[2]/e.length],[0,0,0]);for(const r of s){if(r.part===t||[0,1,2].some(a=>i[a]<r.low[a]-Gc||i[a]>r.high[a]+Gc))continue;if(r.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)<=dm))return l<-.9;const h=Math.abs(l)<.5?Gc:dm;return c.every(u=>u<=h)}))return!0}return!1}const mm=new WeakMap;function ym(t,e,n,s,i){const r=`${s}|${i.map(l=>l.key).join(";")}`;let o=mm.get(e);o||mm.set(e,o=new Map);let a=o.get(r);if(!a){o.size>=48&&o.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=>ie(n,h));a=e.faces.map(h=>V3(t,h.corners.map(u=>c[u]),l(h.normal),i)),o.set(r,a)}return a}const As={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}},Uc=Math.PI/180;function bm(t,e,n){return{toView:s=>pl(Qt(s,t*90*Uc),-e*Uc),toScreen:s=>({x:s[0]*n,y:-s[1]*n})}}const wm=new WeakMap,Fi=t=>Co(t),Co=t=>{let e=wm.get(t);return e||wm.set(t,e=Jg(t)),e};function It(t,e,n){return e[n]??t.controls[n]?.default??As[n]?.default??0}function Ni(t,e){const n=Math.max(.05,It(t,e,"squash")),s=1/Math.sqrt(n),r=[1,0,0,0,0,1,It(t,e,"lean"),0,0,0,1,0,0,0,0,1];return[bn([0,It(t,e,"lift"),0]),me(Vt([1,0,0],-It(t,e,"pitch"))),me(Vt([0,0,1],It(t,e,"roll"))),r,wn([s,n,s]),wn(Array(3).fill(Math.max(0,It(t,e,"size"))))].reduce((o,a)=>Rt(o,a))}function Vc(t,e){const n=Ni(t,e),s=new Map,i=Object.entries(t.controls).flatMap(([o,a])=>(a.bind??[]).map(l=>({value:It(t,e,o),bind:l}))),r=o=>{const a=s.get(o.id);if(a)return a;const l=o.parent?t.parts.find(h=>h.id===o.parent):void 0;if(o.parent&&!l)throw new Error(`prop rig: part "${o.id}" hangs from "${o.parent}", which is not a part`);let c=Rt(l?r(l):n,bn(o.at??[0,0,0]));if(o.rotate){const[h,u,d]=o.rotate;h&&(c=Rt(c,me(Vt([1,0,0],h)))),u&&(c=Rt(c,me(Vt([0,1,0],u)))),d&&(c=Rt(c,me(Vt([0,0,1],d))))}for(const{value:h,bind:u}of i)if(!(!u.parts.includes(o.id)||h===0)){if(u.translate&&(c=Rt(c,bn([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,bn(d),me(Vt(f,u.rotate.degrees*h)),bn([-d[0],-d[1],-d[2]])].reduce((p,g)=>Rt(p,g))}u.scale&&(c=Rt(c,wn([1+(u.scale[0]-1)*h,1+(u.scale[1]-1)*h,1+(u.scale[2]-1)*h])))}return s.set(o.id,c),c};for(const o of t.parts)r(o);return s}const Jc=(()=>{const t=[-.45,.75,.5],e=Math.hypot(...t);return[t[0]/e,t[1]/e,t[2]/e]})(),J3=Math.cos(35*Uc);function Zc(t,e,n,s,i={}){const r=t.derive?{...e,...t.derive(e)}:e,o=Vc(t,r),a=n.toView([0,0,0]),l=H=>W=>[H[0]*W[0]+H[4]*W[1]+H[8]*W[2],H[1]*W[0]+H[5]*W[1]+H[9]*W[2],H[2]*W[0]+H[6]*W[1]+H[10]*W[2]],c=Ni(t,r),h=i.slice===void 0?null:Pa(c),u=h?t.parts.map(H=>({part:H,mesh:Co(H.shape),local:Rt(h,o.get(H.id)),whole:H.shape.type==="tube"})):void 0,d=u?G3(u,i.slice):void 0,f=u?pm(u.map(H=>({part:H.part.id,mesh:H.mesh,...Xc(H.mesh,H.local)}))):void 0,p=(H,W,j,J)=>{const tt=Q=>n.toView(ie(j,Q)),V=W.vertices.map(tt),L=V.map(Q=>n.toScreen(Q)),q=i.perspective?i.near:void 0,G=Q=>Q.map(ot=>n.toScreen(ot)),_=Q=>q===void 0?Q:lm(Q,q),Y=Q=>q===void 0?[Q]:B3(Q,q),st=l(j),P=W.faces.map(Q=>{const ot=n.toView(st(Q.normal)),ht=[ot[0]-a[0],ot[1]-a[1],ot[2]-a[2]],dt=Math.hypot(...ht)||1;return[ht[0]/dt,ht[1]/dt,ht[2]/dt]}),C=f&&J?ym(H.id,W,J,hm(J),f):void 0,z=Q=>C?.[Q]??!1,K=P.map((Q,ot)=>{if(z(ot))return!1;if(!i.perspective)return Q[2]>1e-6;const dt=W.faces[ot].corners.reduce((bt,wt)=>[bt[0]+V[wt][0],bt[1]+V[wt][1],bt[2]+V[wt][2]],[0,0,0]);return-(Q[0]*dt[0]+Q[1]*dt[1]+Q[2]*dt[2])>1e-9}),N=Q=>W.faces[Q].corners.reduce((ot,ht)=>ot+V[ht][2],0)/W.faces[Q].corners.length,F=W.faces.map((Q,ot)=>({face:Q,i:ot})).filter(({i:Q})=>K[Q]).map(({face:Q,i:ot})=>({i:ot,solved:{points:q===void 0?Q.corners.map(ht=>L[ht]):G(_(Q.corners.map(ht=>V[ht]))),depth:N(ot),tone:.72+.33*Math.max(0,P[ot][0]*Jc[0]+P[ot][1]*Jc[1]+P[ot][2]*Jc[2])}})).filter(Q=>Q.solved.points.length>=3).sort((Q,ot)=>Q.solved.depth-ot.solved.depth);if(i.light){const Q=l(j);for(const{i:ot,solved:ht}of F){const dt=W.faces[ot].corners,bt=dt.reduce((Eh,nT)=>{const Ah=ie(j,W.vertices[nT]);return[Eh[0]+Ah[0]/dt.length,Eh[1]+Ah[1]/dt.length,Eh[2]+Ah[2]/dt.length]},[0,0,0]),wt=Q(W.faces[ot].normal),pe=Math.hypot(...wt)||1,Yi=i.light(bt,[wt[0]/pe,wt[1]/pe,wt[2]/pe]);ht.light=Yi.light,ht.fog=Yi.fog}}const D=F.map(Q=>Q.solved),X=Z3(W),B=[],Z=[];for(const[Q,ot]of X){const ht=ot.filter(bt=>K[bt]).length;if(ht===0)continue;const dt=ot.length===2&&ht===2&&W.creases!==!1&&P[ot[0]][0]*P[ot[1]][0]+P[ot[0]][1]*P[ot[1]][1]+P[ot[0]][2]*P[ot[1]][2]<J3;ot.length===1&&(W.joined||Q3(W,Q))||(ot.length===1||ht===1||dt)&&(B.push(Q.split("-").map(Number)),Z.push(ot.filter(bt=>K[bt]).reduce((bt,wt)=>N(wt)>N(bt)?wt:bt)))}const et=Q=>W.faces.findIndex(ot=>ot.corners.length>4&&Math.sign(ex(W.vertices[Q],ot.normal))>0),R=(W.marks??[]).filter(([Q])=>et(Q)<0||K[et(Q)]),U=([Q,ot])=>q===void 0?[[L[Q],L[ot]]]:Y([V[Q],V[ot]]).map(G),nt=R.flatMap(U),at=Q=>q===void 0?[Q.map(ot=>L[ot])]:Y(Q.map(ot=>V[ot])).map(G);if(i.slice!==void 0){const Q=new Map;B.forEach((ot,ht)=>Q.set(Z[ht],[...Q.get(Z[ht])??[],ot]));for(const{i:ot,solved:ht}of F){ht.edges=Sm(Q.get(ot)??[]).flatMap(at);const dt=W.faces[ot].corners;ht.center=dt.reduce((wt,pe)=>[wt[0]+V[pe][0]/dt.length,wt[1]+V[pe][1]/dt.length,wt[2]+V[pe][2]/dt.length],[0,0,0]),ht.normal=P[ot];const bt=F[F.length-1].i;ht.marks=R.filter(([wt])=>(et(wt)>=0?et(wt):bt)===ot).flatMap(U)}}const rt=H.glow?Math.max(0,Math.min(1,It(t,r,H.glow.control))):0,ct=H.fade?Math.max(0,Math.min(1,It(t,r,H.fade.control))):0,it=H.fade?Math.max(0,Math.min(1,H.fade.from+(H.fade.to-H.fade.from)*ct)):1;return{part:H,depth:V.reduce((Q,ot)=>Q+ot[2],0)/Math.max(1,V.length),faces:D,edges:Sm(B).flatMap(at),marks:nt,glow:rt,opacity:it,...H.shape.type==="tube"?{spine:tx(Y(H.shape.points.map(tt)).map(G))}:{},...W.walls?{cut:!0}:{}}},g=new Map(u?.map(H=>[H.part.id,H.local])),w=(d?d.pieces.map(H=>({part:H.part,mesh:H.mesh,m:H.cut?c:o.get(H.part.id),local:H.cut?lr():g.get(H.part.id),cell:H.cell})):t.parts.map(H=>({part:H,mesh:Co(H.shape),m:o.get(H.id),local:void 0,cell:void 0}))).map(H=>({cell:H.cell,solved:p(H.part,H.mesh,H.m,H.local)})),v=w.map(H=>H.solved),k=H=>H.filter(W=>W.faces.length>0&&W.opacity>.01).sort((W,j)=>W.depth-j.depth);let b;if(d){const H=new Map(t.parts.map(j=>{const J=o.get(j.id),tt=Co(j.shape).vertices;return[j.id,tt.reduce((V,L)=>V+n.toView(ie(J,L))[2],0)/Math.max(1,tt.length)]})),W=new Map;for(const j of w){const J=j.cell.join(",");W.has(J)||W.set(J,{cell:j.cell,parts:[]}),W.get(J).parts.push(j.solved),j.solved.depth=H.get(j.solved.part.id)}b=[...W.values()].map(({cell:j,parts:J})=>({depth:n.toView(ie(c,d.middle(j)))[2],parts:k(J)})).filter(j=>j.parts.length>0)}const T={};for(const[H,W]of Object.entries(t.anchors??{})){const j=W.part?o.get(W.part):Ni(t,r);if(!j)throw new Error(`prop rig: anchor "${H}" is on "${W.part}", which is not a part`);const J=n.toView(ie(j,W.at));T[H]={point:n.toScreen(J),depth:J[2]}}const[$,M]=t.footprint??[t.length*.45,t.length],x=Math.max(0,It(t,r,"lift")),S=Math.max(0,It(t,r,"size"))/(1+x*.8),E=Array.from({length:24},(H,W)=>{const j=Math.PI*2*W/24;return n.toView([Math.cos(j)*$*.55*S,0,Math.sin(j)*M*.55*S])}),I=i.perspective?i.near:void 0,A={points:(I===void 0?E:lm(E,I)).map(H=>n.toScreen(H)),opacity:.16*S},O=v.filter(H=>H.part.seeThrough&&H.opacity>.01).flatMap(H=>H.faces.map(W=>W.points));return{under:k(v.filter(H=>!H.part.overRider)),over:k(v.filter(H=>H.part.overRider)),...b?{cells:b}:{},anchors:T,openings:O,shadow:A,pxPerUnit:s,sizePx:t.height*s}}const km=new WeakMap;function Z3(t){let e=km.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 r=s[i],o=s[(i+1)%s.length],a=r<o?`${r}-${o}`:`${o}-${r}`,l=e.get(a);l?l.push(n):e.set(a,[n])}}km.set(t,e)}return e}function vm(t,e){const n=t.derive?{...e,...t.derive(e)}:e,s=Vc(t,n),i=Pa(Ni(t,n))??lr(),r=o=>Math.max(0,Math.min(1,o));return t.parts.map(o=>{const a=o.fade?r(It(t,n,o.fade.control)):0;return{part:o,matrix:s.get(o.id),local:Rt(i,s.get(o.id)),glow:o.glow?r(It(t,n,o.glow.control)):0,opacity:o.fade?r(o.fade.from+(o.fade.to-o.fade.from)*a):1}})}function Mm(t,e){const n=t.derive?{...e,...t.derive(e)}:e,s=Vc(t,n),i=Ni(t,n),r={};for(const[o,a]of Object.entries(t.anchors??{})){const l=a.part?s.get(a.part):i;if(!l)throw new Error(`prop rig: anchor "${o}" is on "${a.part}", which is not a part`);r[o]=ie(l,a.at)}return r}function Q3(t,e){if(!t.walls)return!1;const[n,s]=e.split("-").map(r=>t.vertices[Number(r)]),i=(r,o)=>o.some(a=>Math.abs(n[r]-a)<1e-6&&Math.abs(s[r]-a)<1e-6);return i(0,t.walls.x)||i(2,t.walls.z)}function tx(t){return t.reduce((e,n)=>!e||n.length>e.length?n:e,void 0)}const ex=(t,e)=>t[0]*e[0]+t[1]*e[1]+t[2]*e[2];function Sm(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 r=0;r<e.length;r++){const[o,a]=e[r],l=s[s.length-1],c=s[0];if(o===l)s.push(a);else if(a===l)s.push(o);else if(a===c)s.unshift(o);else if(o===c)s.unshift(a);else continue;e.splice(r,1),i=!0;break}}n.push(s)}return n}function Qc(t,e){if(!t.loose?.size)return;const n={};for(const[s,i]of t.loose)n[s]={x:e[`piece.${i}.x`]??0,y:e[`piece.${i}.y`]??0,rotate:e[`piece.${i}.rotate`]??0,opacity:e[`piece.${i}.opacity`]??1};return n}function th(t){const e={};for(const[n,s]of Object.entries({...As,...t.rig.controls})){const{bind:i,...r}=s;e[n]=r}return e}function xm(t){const{prop:e}=t,n=t.scale??60,s=e.rig.length*n*1.4,i=e.rig.height*n*1.6,r=th(e),o={};for(const[l,c]of Object.entries(r))o[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:o,prop:e,propScale:n,propDraw:a,about:{kind:e.kind,summary:e.summary,props:r,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),Zl(l,$s(e,u,n),{...a,time:h,loose:Qc(c,u)})}}}function $s(t,e,n){const s=bm(It(t.rig,e,"turn"),It(t.rig,e,"tilt"),n);return Zc(t.rig,e,s,n)}function _o(t,e,n){const s={...t.props};let i=0,r=0;for(const[l,c]of e.state?.values.get(n)??[])typeof c=="number"&&(l==="x"?i=c:l==="y"?r=c:l in s&&(s[l]=c));const o={x:t.x+t.width/2+i,y:t.y+t.height+r},a=$s(t.prop,s,t.propScale);return{values:s,origin:o,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:o.x+c.point.x,y:o.y+c.point.y,depth:c.depth}}}}function nx(t,e,n,s,i={}){const r=_o(e,n,s);return t.save(),t.translate(r.origin.x,r.origin.y),Zl(t,r.solved,{...e.propDraw,time:n.time,loose:Qc(e,r.values),rider:i.rider?o=>{o.save(),o.translate(-r.origin.x,-r.origin.y),i.rider(o),o.restore()}:void 0}),t.restore(),r}const Ps={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…); it can come loose as a piece","control:NAME":"where the parts a control moves or lights are (control:door is the doors, control:lights the lamps; a control of the whole prop, like lift, is its box)"},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",move:"a part; { at, to: an anchor name or { x, y }, duration? }: carry the part there, loose",fling:"a part; { at, velocity?, spin?, gravity?, duration? }: knock the part off on a spinning arc"}},sx=400,ix=.2;function rx(t,e={}){const{prop:n}=t,s=th(n),i=Object.keys(s),r=Object.keys(n.rig.anchors??{}),o=n.rig.parts.map($=>$.id),a=ks(),l=Ei(a),c=e.tracks?.length?new Ht({id:`${n.kind}-surface`,tracks:e.tracks}):void 0,h=Math.max(0,...(e.tracks??[]).flatMap($=>$.keyframes.map(M=>M.time))),u=new Map,d=new Map;t.loose=d;const f=t.props,p=$=>{const M={...t.props};let x=0,S=0;if(c){const E=c.getStateAtTime(Math.min($,h));for(const I of E.values.values())for(const[A,O]of I)typeof O=="number"&&(A==="x"?x=O:A==="y"?S=O:A in M&&(M[A]=O))}for(const E of i)a.keys(E)?.length&&(M[E]=a.valueAt(E,$));return{values:M,origin:{x:t.x+t.width/2+x,y:t.y+t.height+S}}},g=$=>{const{kind:M,rest:x}=_n($),S=E=>sn(n.kind,$,Ps,E);if(M==="box"){if(x)throw S("box takes no arguments");return{kind:M}}if(M==="anchor"){if(!r.includes(x))throw S(ft(`${n.kind} anchor`,x,r));return{kind:M,name:x}}if(M==="part"){if(!o.includes(x))throw S(ft(`${n.kind} part`,x,o));return{kind:M,name:x}}if(M==="control"){if(!i.includes(x))throw S(ft(`${n.kind} control`,x,i));return{kind:M,name:x}}throw S()},m=$=>{const M=(n.rig.controls[$]?.bind??[]).flatMap(S=>S.parts),x=n.rig.parts.filter(S=>S.glow?.control===$).map(S=>S.id);return new Set([...M,...x])},w=new Map,v=$=>{let M=w.get($);if(!M){const x=p($);w.set($,M={...x,solved:$s(n,x.values,t.propScale)})}return M},k=($,M)=>{const x=g($),{values:S,origin:E,solved:I}=v(M);if(x.kind==="box")return Mt(E.x-t.width/2,E.y-t.height,t.width,t.height);if(x.kind==="anchor"){const H=I.anchors[x.name].point,W=ix*t.propScale;return Mt(E.x+H.x-W/2,E.y+H.y-W/2,W,W)}if(x.kind==="part")return O(new Set([x.name]),`part "${x.name}" is`);const A=m(x.name);if(A.size===0)return Mt(E.x-t.width/2,E.y-t.height,t.width,t.height);return O(A,`the parts control "${x.name}" moves are`);function O(H,W){const j=[...I.under,...I.over].filter(q=>H.has(q.part.id)).flatMap(q=>q.faces.flatMap(G=>G.points));if(j.length===0){const q=Number.isFinite(M)?`at ${M} ms`:"after its edits";throw new Error(`${n.kind}: ${W} turned away from the viewer ${q}; aim at an anchor (${r.map(G=>`anchor:${G}`).join(", ")||"none"}) or box`)}const J=j.map(q=>q.x),tt=j.map(q=>q.y),V=Math.min(...J),L=Math.min(...tt);return Mt(E.x+V,E.y+L,Math.max(...J)-V,Math.max(...tt)-L)}},b=($,M)=>{try{return k($,M)}catch{return}},T={kind:"prop",prop:t,about:Ps,target:t,box:Mt(t.x,t.y,t.width,t.height),anchor($,M=1/0){return k($,M)},piece($){const M=g($);if(M.kind!=="part")throw new Error(`${n.kind}: a piece is a part, part:ID (${o.slice(0,6).map(I=>`part:${I}`).join(", ")}…), not "${$}"`);const x=u.get(M.name);if(x)return x;const S=[M.name];for(let I=0;I<S.length;I++)for(const A of n.rig.parts)A.parent===S[I]&&!S.includes(A.id)&&S.push(A.id);const E={id:u.size+1,part:M.name,home:k($,0)};u.set(M.name,E);for(const I of S)d.set(I,E.id);for(const I of["x","y","rotate"])f[`piece.${E.id}.${I}`]=0;return f[`piece.${E.id}.opacity`]=1,E},edit($,M,x){if(!($ in Ps.edits))throw Ai(n.kind,$,Ps);const S=Array.isArray(M)?M:[M];if(S.length===0)throw new Error(`${n.kind}.edit: ${$} takes at least one anchor`);if(w.clear(),$==="move"||$==="fling"){if(S.length>1)throw new Error(`${n.kind}.edit: ${$} takes one part anchor`);const E=T.piece(S[0]);if($==="fling")return T.fling(E,x);const I=x.to;if(!I)throw new Error(`${n.kind}.edit: move needs \`to\`, an anchor name or { x, y }`);const A=typeof I=="string"?k(I,x.at):void 0;return T.move(E,{...x,to:A?{x:A.left+A.width/2,y:A.top+A.height/2}:I})}for(const E of S){const I=g(E);if(I.kind!=="control")throw new Error(`${n.kind}.edit: ${$} takes control anchors (control:${i.join(", control:")}), not "${E}"`);const A=s[I.name];let O;if($==="set"){if(typeof x.value!="number"||!Number.isFinite(x.value))throw new Error(`${n.kind}.edit: set needs \`value\`, a number (${I.name}: ${A.description})`);O=x.value}else O=x.on===!1?A.default??A.min??0:A.max??1;a.tween(I.name,p(x.at).values[I.name],O,x,sx)}return T},follow($,M){return w.clear(),l.follow($,M),T},fling($,M){return w.clear(),l.fling($,M),T},move($,M){return w.clear(),l.move($,M),T},ride($,M,x){const S=[...i.flatMap(I=>vs(a.keys(I))),...(e.tracks??[]).flatMap(I=>vs(I.keyframes.filter(A=>typeof A.value=="number")))];if(S.length===0)return $;const E=[...r.map(I=>`anchor:${I}`),...o.map(I=>`part:${I}`)].flatMap(I=>{const A=b(I,0);return A?[{top:A.top,offset:O=>(b(I,O)?.top??A.top)-A.top,windows:S}]:[]});return yo($,M,{ground:x.ground,every:x.every??nn,floors:E})},tracks:a.tracks};return T}const ox={body:"#e8574a",trim:"#3b3b44",glass:"#bfe3f2",tyre:"#2c2c33",hub:"#c9ccd3",light:"#fff4b8",tail:"#ff5a4f",inside:"#3b3640",seat:"#6d5d55"};function Fe(t){const e={...ox,...t.colors},n=[],{forwardMost:s,backMost:i,top:r}=Tm(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 o=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:o/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 w=h+(u-h)*.15,v=h+(u-h)*.55;n.push({id:`seat-back-${m}`,shape:{type:"panel",points:[[w,d+.05],[v,d+.05],[v-.08,f-.06],[w+.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 w of[1,-1])n.push({id:`headlight-${w}`,shape:{type:"panel",points:m,facing:"front"},at:[w*h,0,f],fill:e.light,outline:.6,glow:{control:"lights",color:"#ffffff"}}),n.push({id:`taillight-${w}`,shape:{type:"panel",points:m,facing:"back"},at:[w*h,0,p],fill:ho(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:r,footprint:[t.width,s-i],anchors:{...t.seat?{seat:{at:t.seat}}:{},front:{at:[0,r*.45,s]},back:{at:[0,r*.45,i]},roof:{at:[0,r,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:ax(t),acting:Em,colors:{body:e.body,ink:"#26262b"},follow:t.antenna?[{control:"antenna",of:"x",per:.9,stiffness:140,damping:7,limit:35}]:void 0,wheelRadius:o,...t.wheels.length>0?{moves:{drive:{speed:t.speed??6,perMetre:{wheelSpin:180/(Math.PI*o)}}}}:{}}}function Tm(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 Em={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 Ho(t,e,n,s,i,r,o=!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,o?l:l+c/r*(180/Math.PI),i)}const Am=.4;function ax(t){const e=t.wheels[0]?.radius??.4,{forwardMost:n,backMost:s}=Tm(t),i=(n-s)/2,r=(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"}),Ho(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},o=(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=r(a,c,h),d=a.exaggeration,f=Math.abs(l.to-a.x),p=l.for??Math.max(500,f/(l.speed??Am));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}),Ho(a,u,u+p,l.to,"ease-in-out",e),o(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=r(a,c,h),d=a.exaggeration,f=a.x,p=Math.abs(l.to-f),g=l.for??Math.max(600,p/(l.speed??Am*1.2)),m=u+g*.55,w=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"}),Ho(a,u,m,w,"ease-in",e),a.key(m+80,{pitch:-7*d,lean:-.12*d,squash:.94},{act:!1,easing:"ease-out"}),Ho(a,m,u+g,l.to,"ease-out",e,!0),a.effect({kind:"skid",time:m,x:w,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}),o(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 $m(t={}){return Fe({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 Pm(t={}){return Fe({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 Im(t={}){return Fe({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 Om(t={}){return Fe({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 Cm(t={}){const e=t.colors?.body??"#a8743f";return Fe({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 _m(t={}){return Fe({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 Hm(t={}){const e=t.colors?.body??"#e0473b",n=[0,.32,-.05],s=[0,.86,-.22],i=[0,.9,.42],r=[0,.34,.56],o=[0,.34,-.56];return Fe({kind:"bike",summary:"A bicycle: rides (drive) with its wire wheels turning, brakes, bumps, rings its bell (honk).",width:.5,frame:[{points:[o,n]},{points:[n,s]},{points:[s,o]},{points:[s,i]},{points:[n,i]},{points:[i,r]},{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 Rm(t={}){return Fe({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 Lm(t={}){const e=t.height??2.4,n=t.trunkRadius??.16,s=t.canopy?.radius??1.1,i=t.canopy?.shape==="tall",r={trunk:"#8a5a3b",leaves:"#5cae5a",...t.colors},o=Xe(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:r.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:r.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:r.leaves}],l=t.canopy?.lobes??7;for(let h=0;h<l;h++){const u=Math.PI*2*h/l+o.next()*.6,d=(o.next()-.25)*s*(i?1.1:.7),f=s*(.48+o.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:r.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:lx(),acting:Fm,colors:{body:r.leaves}}}const Fm={depth:{sway:1,canopySway:2,size:0,squash:1},limits:{sway:2,canopySway:3,squash:.08},eyes:[],headTurns:{},drift:[]};function lx(){const t=(e,n,s,i)=>{const r=e.anchor("canopy");e.effect({kind:"leaves",time:n,x:r.x,y:r.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,r=n.for??3e3,o=e.exaggeration,a=260;let l=0;for(let c=a;c<r;c+=a){const h=.55+.45*Math.sin(c/r*Math.PI*2.3),u=Math.sin(c/170)*.35,d=-i*9*o*(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+r,{sway:0,canopySway:0}),i>.45)for(let c=0;c<r;c+=700)t(e,s+c,2200,1);return{end:s+r}}},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,r=e.exaggeration,o=6;for(let a=1;a<=o;a++){const l=1-a/(o+1),c=a%2===0?1:-1;e.key(s+i*a/(o+1),{sway:c*5*r*l,canopySway:-c*6*r*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 r=0;r<i;r+=500)t(e,s+r,2e3,r%1e3===0?1:-1);return{end:s+i}}}}}function Nm(t={}){const e=t.width??4,n=t.depth??3.2,s=t.wallHeight??2.5,i=t.roofHeight??1.5,r=t.overhang??.25,o={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:o.walls},{id:"roof",shape:{type:"extrude",profile:[[-n/2-r,s],[n/2+r,s],[0,s+i]],width:e+r*2},fill:o.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:o.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:o.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:o.glass,outline:.8,glow:{control:"lights",color:o.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:o.glass,outline:.8,glow:{control:"lights",color:o.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+r)),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:o.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+r*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:cx(!!f),acting:Wm,colors:{body:o.walls}}}const Wm={depth:{door:1,lights:0,roll:1,squash:1,size:0},limits:{door:.1,roll:1.5,squash:.05},eyes:[],headTurns:{},drift:[]};function cx(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,r=e.exaggeration;e.key(s+80,{squash:1-.06*r},{act:!1,easing:"ease-out"});for(let o=1;o<=5;o++){const a=1-o/6;e.key(s+80+i*o/6,{roll:(o%2===0?1:-1)*2.2*r*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,r=e.anchor("chimney");return e.effect({kind:"smoke",time:s,x:r.x,y:r.y,length:i+1500,direction:(n.wind??.4)>=0?1:-1}),{end:s+50,release:s+i}}}}:{}}}function Dm(t={}){const e=t.width??.46,n=t.depth??.46,s=t.seatHeight??.46,i=t.backHeight??.95,r={wood:"#8a5a3b",seat:"#c48a4a",...t.colors},o=.05,a=.025,l=[{id:"seat",shape:{type:"box",size:[e,o,n]},at:[0,s-o/2,0],fill:r.seat},{id:"back",shape:{type:"box",size:[e,i-s,o]},at:[0,(i+s)/2,-n/2+o/2],fill:r.wood}];for(const[h,u,d]of[[-1,1,"front-left"],[1,1,"front-right"],[-1,-1,"back-left"],[1,-1,"back-right"]])l.push({id:`leg-${d}`,shape:{type:"tube",points:[[0,0,0],[0,s-o,0]],radius:a,segments:6},at:[h*(e/2-a*1.5),0,u*(n/2-a*1.5)],fill:r.wood});const c={parts:l,controls:{tip:{description:"Tipped back on its rear legs (+), degrees",unit:"degrees",min:0,max:60,bind:[{parts:l.map(h=>h.id),rotate:{axis:"x",degrees:1,pivot:[0,0,-n/2+a*1.5]}}]}},length:n,height:i,footprint:[e,n],anchors:{seat:{at:[0,s,0]},back:{at:[0,i,-n/2]},front:{at:[0,0,n/2+.3]}}};return{kind:t.kind??"chair",family:"furniture",summary:t.summary??"A chair: a seat to sit on (`seat`), tips back on its rear legs and settles, or falls over.",rig:c,actions:hx(),acting:Bm,colors:{body:r.seat}}}const Bm={depth:{tip:1,roll:1,squash:1,size:0},limits:{tip:2,roll:1,squash:.05},eyes:[],headTurns:{},drift:[]};function hx(){return{tip:{summary:"Tips back on its rear legs for `for` ms (default 1200), rocking a little, then settles down.",uses:["for"],run(t,e,n){const s=18*t.exaggeration,i=e.for??1200;return t.key(n+350,{tip:s},{easing:"ease-out"}),t.key(n+350+i*.4,{tip:s*.85},{act:!1,easing:"ease-in-out"}),t.key(n+350+i*.7,{tip:s},{act:!1,easing:"ease-in-out"}),t.key(n+350+i,{tip:0},{easing:"ease-in"}),{end:n+350+i,contact:n+350}}},fall:{summary:"Falls over backwards onto its back and bounces, with dust.",uses:["for"],run(t,e,n){const s=e.for??700;return t.key(n+s*.6,{tip:90},{act:!1,easing:"ease-in"}),t.key(n+s*.75,{tip:82},{act:!1,easing:"ease-out"}),t.key(n+s,{tip:90},{act:!1,easing:"ease-in"}),t.effect({kind:"dust",time:n+s*.6,x:t.x,y:t.floor,length:600}),{end:n+s,contact:n+s*.6}}}}}function zm(t={}){const e=t.width??1.4,n=t.depth??.7,s=t.height??.75,i={wood:"#8a5a3b",top:"#a9754a",knob:"#2b2b2b",...t.colors},r=.04,o=.03,a=.14,l=e*.4,c=[{id:"top",shape:{type:"box",size:[e,r,n]},at:[0,s-r/2,0],fill:i.top},{id:"drawer",shape:{type:"box",size:[l,a,n*.8]},at:[-e/2+l/2+.05,s-r-a/2,0],fill:i.wood},{id:"knob",parent:"drawer",shape:{type:"ellipsoid",radii:[.02,.02,.015],segments:8},at:[0,0,n*.4+.012],fill:i.knob,outline:.6}];for(const[u,d,f]of[[-1,1,"front-left"],[1,1,"front-right"],[-1,-1,"back-left"],[1,-1,"back-right"]])c.push({id:`leg-${f}`,shape:{type:"tube",points:[[0,0,0],[0,s-r,0]],radius:o,segments:6},at:[u*(e/2-o*2),0,d*(n/2-o*2)],fill:i.wood});const h={parts:c,controls:{drawer:{description:"The drawer out: 0 shut, 1 open",unit:"0..1",min:0,max:1,bind:[{parts:["drawer"],translate:[0,0,n*.5]}]}},length:n,height:s,footprint:[e,n],anchors:{top:{at:[0,s,0]},edge:{at:[0,s,n/2]},drawer:{part:"drawer",at:[0,0,n*.4]},chair:{at:[0,0,n/2+.35]}}};return{kind:t.kind??"desk",family:"furniture",summary:t.summary??"A desk: a top to work at (`top`, `edge`), a drawer that opens (`drawer`), a place for a chair in front (`chair`).",rig:h,actions:{drawer:{summary:"Opens the drawer (`open: true`) or shuts it (`open: false`).",needs:["open"],run(u,d,f){return u.key(f+400,{drawer:d.open?1:0},{easing:d.open?"ease-out":"ease-in"}),{end:f+500,contact:f+400}}}},acting:qm,colors:{body:i.top}}}const qm={depth:{drawer:1,roll:1,squash:1,size:0},limits:{drawer:.08,roll:1,squash:.04},eyes:[],headTurns:{},drift:[]};function jm(t={}){const e=t.length??2,n=t.width??1,s=t.height??.55,i=t.headboard??.95,r={wood:"#8a5a3b",mattress:"#f1ece2",blanket:"#5b7fb0",pillow:"#fbf8f2",...t.colors},o=.3,a=s-o,c={parts:[{id:"frame",shape:{type:"box",size:[n,o,e]},at:[0,o/2,0],fill:r.wood},{id:"headboard",shape:{type:"box",size:[n+.06,i-o,.06]},at:[0,(i+o)/2,-e/2-.03],fill:r.wood},{id:"mattress",shape:{type:"box",size:[n-.04,a,e-.04]},at:[0,o+a/2,0],fill:r.mattress},{id:"blanket",parent:"mattress",shape:{type:"box",size:[n-.02,.04,e*.62]},at:[0,a/2+.02,e*.19],fill:r.blanket,outline:.7},{id:"pillow",parent:"mattress",shape:{type:"ellipsoid",radii:[n*.32,.07,.22],segments:12},at:[0,a/2+.06,-e/2+.32],fill:r.pillow,outline:.7}],controls:{give:{description:"The mattress pressed down: 1 as made, below squashed (someone landed on it)",unit:"factor",default:1,min:.5,max:1.2,bind:[{parts:["mattress"],scale:[1,1,1]}]}},length:e,height:i,footprint:[n,e],anchors:{mattress:{part:"mattress",at:[0,a/2,0]},pillow:{part:"mattress",at:[0,a/2+.1,-e/2+.32]},foot:{at:[0,s,e/2]},side:{at:[n/2+.25,0,0]}}};return{kind:t.kind??"bed",family:"furniture",summary:t.summary??"A bed: a mattress to lie on (`mattress`, `pillow`) that gives and springs back when someone lands on it (`bounce`), a side to sit on (`side`).",rig:c,actions:{bounce:{summary:"The mattress gives (someone landed on it) and springs back over `for` ms (default 700).",uses:["for"],run(h,u,d){const f=u.for??700,p=h.exaggeration;return h.key(d+90,{give:1-.18*p},{act:!1,easing:"ease-out"}),h.key(d+f*.45,{give:1+.05*p},{act:!1,easing:"ease-in-out"}),h.key(d+f*.7,{give:1-.04*p},{act:!1,easing:"ease-in-out"}),h.key(d+f,{give:1}),{end:d+f,contact:d+90}}}},acting:Ym,colors:{body:r.blanket}}}const Ym={depth:{give:1,roll:1,squash:1,size:0},limits:{give:.03,roll:.5,squash:.03},eyes:[],headTurns:{},drift:[]};function Km(t={}){const e=t.width??.9,n=t.height??2.05,s=t.hinge??"left",i={frame:"#d9d2c3",door:"#7a4b2a",handle:"#c9a227",beyond:"#2a2f3a",...t.colors},r=.1,o=s==="left"?1:-1,a=o>0?[[0,0],[-e,0],[-e,n],[0,n]]:[[0,0],[e,0],[e,n],[0,n]],c={parts:[{id:"post-left",shape:{type:"box",size:[r,n+r,r]},at:[e/2+r/2,(n+r)/2,0],fill:i.frame},{id:"post-right",shape:{type:"box",size:[r,n+r,r]},at:[-e/2-r/2,(n+r)/2,0],fill:i.frame},{id:"lintel",shape:{type:"box",size:[e+r*2,r,r]},at:[0,n+r/2,0],fill:i.frame},{id:"beyond",shape:{type:"panel",points:[[-e/2,0],[e/2,0],[e/2,n],[-e/2,n]],facing:"front"},at:[0,0,-.03],fill:i.beyond,outline:.4,seeThrough:!0},{id:"door",shape:{type:"panel",points:a,facing:"front"},at:[o*e/2,0,.005],fill:i.door,outline:.9,overRider:!0},{id:"handle",parent:"door",shape:{type:"ellipsoid",radii:[.03,.03,.03],segments:8},at:[-o*(e-.1),n*.47,.03],fill:i.handle,outline:.5}],controls:{open:{description:"How far the door is open: 0 shut, 1 open wide",unit:"0..1",min:0,max:1,bind:[{parts:["door"],rotate:{axis:"y",degrees:o*-95}}]}},length:.3,height:n+r,footprint:[e+r*2,.3],anchors:{handle:{part:"door",at:[-o*(e-.1),n*.47,.03]},doorway:{at:[0,0,0]},front:{at:[0,0,.5]},beyond:{at:[0,0,-.5]}}};return{kind:t.kind??"door",family:"furniture",summary:t.summary??"A door in its frame: opens and shuts on its hinge (`open`), slams, rattles when knocked; a figure goes through the `doorway` from `front` to `beyond`.",rig:c,actions:ux(),acting:Xm,colors:{body:i.door}}}const Xm={depth:{open:1,roll:1,squash:1,size:0},limits:{open:.08,roll:.6,squash:.03},eyes:[],headTurns:{},drift:[]};function ux(){return{open:{summary:"Opens the door (`open: true`, default) or shuts it (`open: false`), over `for` ms (default 600).",uses:["open","for"],run(t,e,n){const s=e.for??600;return t.key(n+s,{open:e.open===!1?0:1},{easing:"ease-in-out"}),{end:n+s+80,contact:n+s}}},slam:{summary:"Slams shut: a fast swing, a shudder in the frame, dust.",run(t,e,n){const s=t.exaggeration;t.key(n+180,{open:0},{act:!1,easing:"ease-in"});for(let i=1;i<=4;i++)t.key(n+180+i*70,{roll:(i%2===0?1:-1)*1.2*s*(1-i/5)},{act:!1});return t.key(n+180+350,{roll:0}),t.effect({kind:"dust",time:n+180,x:t.x,y:t.floor,length:500}),{end:n+180+350,contact:n+180}}},knock:{summary:"Someone knocks three times: the door rattles over `for` ms (default 700).",uses:["for"],run(t,e,n){const i=e.for??700,r=t.exaggeration;for(let o=0;o<3;o++){const a=n+i*(o+.5)/3;t.key(a,{open:.03*r},{act:!1,easing:"ease-out"}),t.key(a+60,{open:0},{act:!1,easing:"ease-in"})}return{end:n+i,contact:n+i/6}}}}}const Gm=1.4;function Um(t={}){const e=t.width??.5,n=t.seatHeight??.5,s=t.wheelRadius??.3,i=.08,r={frame:"#2b2f36",seat:"#3c6ea5",tyre:"#1f2328",...t.colors},o=.04,a=.018,l=.44,c=n+.5,h=-.08,u=e/2+.06,d=[{id:"seat",shape:{type:"box",size:[e,o,l]},at:[0,n-o/2,0],fill:r.seat},{id:"back",shape:{type:"box",size:[e,c-n-.02,o]},at:[0,(c+n)/2,-l/2+o/2],fill:r.seat},{id:"footrest",shape:{type:"box",size:[e*.8,.02,.14]},at:[0,.12,l/2+.22],fill:r.frame}];for(const[g,m]of[[-1,"left"],[1,"right"]]){const w=g*u,v=(k,b,T=a)=>{d.push({id:k,shape:{type:"tube",points:b,radius:T,segments:6},fill:r.frame,outline:.7})};v(`post-${m}`,[[w,n-.1,-l/2],[w,c+.04,-l/2],[w,c+.04,-l/2-.14]]),v(`rail-${m}`,[[w,n-.03,-l/2],[w,n-.03,l/2]]),v(`leg-${m}`,[[w,n-.03,l/2],[w*.85,i,l/2+.06]]),v(`strut-${m}`,[[w*.85,i+.08,l/2+.04],[w*.8,.13,l/2+.22]]),v(`armrest-${m}`,[[w,n+.22,-l/2+.02],[w,n+.22,l/2-.08]],a*1.3),d.push({id:`wheel-${m}`,shape:{type:"cylinder",radius:s,length:.04,axis:"x",segments:20,spokes:8},at:[w+g*.03,s,h],ink:r.tyre,outline:1.3}),d.push({id:`rim-${m}`,shape:{type:"cylinder",radius:s*.9,length:.012,axis:"x",segments:20},at:[g*.045,0,0],parent:`wheel-${m}`,ink:r.frame,outline:.8}),d.push({id:`castor-${m}`,shape:{type:"cylinder",radius:i,length:.03,axis:"x",segments:12,spokes:3},at:[w*.85,i,l/2+.06],fill:r.tyre})}const f=d.map(g=>g.id).filter(g=>!g.startsWith("rim-")),p={parts:d,controls:{wheelSpin:{description:"How far the big wheels have turned, degrees (keyed with the distance rolled, so they never skate); the castors turn faster",unit:"degrees",bind:[{parts:["wheel-left","wheel-right"],rotate:{axis:"x",degrees:1}},{parts:["castor-left","castor-right"],rotate:{axis:"x",degrees:s/i}}]},tip:{description:"Tipped back on its big wheels (+), degrees: a wheelie, or a helper tipping it up a kerb",unit:"degrees",min:0,max:45,bind:[{parts:f,rotate:{axis:"x",degrees:1,pivot:[0,s,h]}}]}},length:l+.4,height:c+.04,footprint:[u*2+.1,l+.4],anchors:{seat:{at:[0,n,.02]},handles:{at:[0,0,-l/2-.5]},front:{at:[0,0,l/2+.6]},footrest:{at:[0,.13,l/2+.22]}}};return{kind:t.kind??"wheelchair",family:"furniture",summary:t.summary??"A wheelchair: rolls to `to` with its wheels turning the distance (roll), brakes, tips back on its big wheels (wheelie); its `seat` is ridden in the `wheeling` pose and a pusher stands at `handles`.",rig:p,actions:dx(s),acting:Vm,colors:{body:r.seat,ink:r.frame},wheelRadius:s,moves:{roll:{speed:Gm,perMetre:{wheelSpin:180/(Math.PI*s)}}}}}const Vm={depth:{wheelSpin:0,tip:1,roll:1,squash:1,size:0},limits:{tip:2,roll:1,squash:.03},eyes:[],headTurns:{},drift:[]};function Jm(t,e,n,s,i,r,o=!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,o?l:l+c/r*(180/Math.PI),i)}function dx(t){return{roll:{summary:"Rolls to `to` at `speed` px/ms (or over `for` ms): a small push-off, the wheels turning exactly the distance, and a gentle stop.",needs:["to"],uses:["speed","for"],run(e,n,s){const i=Math.sign(n.to-e.x);if(i===0)return{end:s};let r=s;e.facing()!==i&&(r=e.turnTo(r,i>0?"right":"left"));const o=Math.abs(n.to-e.x),a=n.for??Math.max(300,o/(n.speed??Gm*e.scale/1e3));return e.key(r+150,{tip:1.5*e.exaggeration},{act:!1,easing:"ease-out"}),Jm(e,r,r+a,n.to,"ease-in-out",t),e.key(r+a,{tip:0},{easing:"ease-out"}),{end:r+a}}},brake:{summary:"Stops short at `to`: the wheels lock and it skids the last bit, tipping forward a touch.",needs:["to"],uses:["for"],run(e,n,s){if(Math.sign(n.to-e.x)===0)return{end:s};const r=n.for??500;return Jm(e,s,s+r,n.to,"ease-out",t,!0),e.key(s+r,{tip:0},{easing:"ease-out"}),e.effect({kind:"dust",time:s+r*.5,x:n.to,y:e.floor,length:500}),{end:s+r,contact:s+r}}},wheelie:{summary:"Tips back onto its big wheels, balances there for `for` ms (default 1200), and drops down.",uses:["for"],run(e,n,s){const i=24*e.exaggeration,r=n.for??1200;return e.key(s+300,{tip:i},{easing:"ease-out"}),e.key(s+300+r*.5,{tip:i*.9},{act:!1,easing:"ease-in-out"}),e.key(s+300+r,{tip:i},{act:!1,easing:"ease-in-out"}),e.key(s+300+r+250,{tip:0},{easing:"ease-in"}),e.effect({kind:"dust",time:s+300+r+250,x:e.x,y:e.floor,length:400}),{end:s+300+r+250,contact:s+300+r+250}}}}}function Zm(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:fx(),acting:eh,colors:{body:e.body,ink:"#26262b"},moves:{fly:{speed:15,flies:!0,hold:{blur:1},perSecond:{rotor:on*1e3}}}}}const eh={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:[]},on=2.6;function fx(){const t=(n,s,i,r,o)=>{const a=n.values.rotor??0;n.set("rotor",s,a);const l=o?r*(i-s)*.5:r*(i-s);n.set("rotor",i,a+l,o)},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 r=n.exaggeration,o=s.height??3;t(n,i,i+900,on,"ease-in"),n.key(i+900,{blur:1},{act:!1,easing:"ease-in"}),n.key(i+700,{squash:1-.08*r},{act:!1,easing:"ease-in"});const a=i+1e3;return n.key(a+150,{squash:1+.06*r,lift:.3},{act:!1,easing:"ease-out"}),n.key(a+1300,{squash:1,lift:o,pitch:-4*r},{act:!1,easing:"ease-in-out"}),n.key(a+1700,{pitch:0}),t(n,i+900,a+1700,on),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 r=n.exaggeration,o=Math.sign(s.to-n.x);let a=i;o!==0&&n.facing()!==o&&(a=n.turnTo(a,o>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*r,roll:6*r},{act:!1,easing:"ease-out"}),n.key(a+c-250,{pitch:-4*r,roll:3*r,lift:h},{act:!1}),n.key(a+c,{pitch:7*r,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,on),{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 r=s.for??2e3,o=n.values.lift,a=n.exaggeration;for(let l=350,c=0;l<r;l+=350,c++)n.key(i+l,{lift:o+(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+r,{lift:o,roll:0},{act:!1,easing:"ease-in-out"}),(e(n)||o>0)&&t(n,i,i+r,on),{end:i+r}}},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 r=n.exaggeration,o=i+Math.max(900,n.values.lift*450);return n.key(i+400,{pitch:3*r},{act:!1,easing:"ease-out"}),n.key(o,{lift:0,pitch:0,squash:1-.14*r},{act:!1,easing:"ease-in"}),n.key(o+280,{squash:1}),t(n,i,o,on),t(n,o,o+1600,on,"ease-out"),n.key(o+1600,{blur:0},{act:!1,easing:"ease-out"}),n.effect({kind:"dust",time:o,x:n.x,y:n.floor,length:800}),{end:o+1600,contact:o}}}}}function Qm(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:px(),acting:eh,colors:{body:e.body,ink:"#26262b"},moves:{fly:{speed:30,flies:!0,hold:{blur:1},perSecond:{rotor:on*1e3}}}}}const gx=3.2;function px(){const t=(n,s,i,r)=>{const o=n.values.rotor??0;n.set("rotor",s,o),n.set("rotor",i,o+gx*(i-s)*(r?.5:1),r)},e=(n,s,i)=>{const r=Math.sign(i-n.x);return r!==0&&n.facing()!==r?n.turnTo(s,r>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 r=n.exaggeration,o=e(n,i,s.to);t(n,o,o+700,"ease-in"),n.key(o+700,{blur:1},{act:!1,easing:"ease-in"});const a=s.for??2600,l=n.x,c=o+700+a*.55,h=l+(s.to-l)*.45;return n.move(o+700,c,h,{easing:"ease-in"}),n.key(c,{pitch:8*r,squash:1+.04*r},{act:!1,easing:"ease-out"}),n.key(o+700+a,{lift:s.height??4,pitch:10*r,squash:1},{act:!1,easing:"ease-in-out"}),n.move(c,o+700+a,s.to),n.key(o+700+a+500,{pitch:0}),t(n,o+700,o+700+a+500),n.effect({kind:"dust",time:c,x:h,y:n.floor,length:700}),{end:o+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 r=n.exaggeration,o=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(o+350,{roll:10*r,pitch:l>n.values.lift?6*r:-3*r},{act:!1,easing:"ease-out"}),n.key(o+a-300,{roll:4*r,lift:l},{act:!1}),n.key(o+a,{roll:0,pitch:0}),n.move(o,o+a,s.to,{easing:"ease-in-out"}),t(n,i,o+a),{end:o+a,contact:o,release:o+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 r=s.for??2400,o=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+r*d/l;n.key(p,{lift:h+o*(1-Math.cos(f)),pitch:u+360*d/l},{act:!1}),n.move(i+r*(d-1)/l,p,c+a*(o*Math.sin(f)+d/l*o*1.2)*n.scale)}return n.key(i+r+1,{pitch:u},{act:!1}),t(n,i,i+r),{end:i+r+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 r=n.exaggeration,o=e(n,i,s.to),a=n.x,l=s.for??2200,c=o+l,h=a+(s.to-a)*.7;return n.key(o+l*.4,{pitch:-4*r},{act:!1,easing:"ease-out"}),n.key(c-250,{pitch:6*r,lift:.15},{act:!1,easing:"ease-in-out"}),n.key(c,{lift:0,pitch:0,squash:1-.12*r},{act:!1,easing:"ease-in"}),n.key(c+260,{squash:1}),n.move(o,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 Is=["walk","trot","canter","gallop"],mx=Is,ty=["fl","fr","hl","hr"],Ro={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}},an=Math.PI/180;function Lo(t,e){return 4*t*Math.sin(Ro[e].swing*an)}function ln(t){const{legs:e,colors:n}=t,s=e.upper+e.lower+e.foot,i=s+t.body.rise,r=(u,d)=>[d*u[0],u[1],u[2]],o=[{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},...bx(t,n,i)];t.mane&&o.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&&o.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?r(t.ears.rotate,1).map((p,g)=>g===2?u*p:p):void 0;o.push({id:`ear-${d}`,parent:"head",shape:{type:"ellipsoid",radii:t.ears.radii,segments:8},at:r(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:r(t.eyes.at,u),fill:"#1d1d22",outline:.4})}o.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=>`${Is.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:we,rotate:{axis:"x",degrees:1/we.length}}]},wag:{description:"Tail swung side to side, curling",unit:"degrees",bind:[{parts:we,rotate:{axis:"y",degrees:1/we.length}}]},ears:{description:"Ears pricked forward (+) or laid back (−), on a spring behind the motion",unit:"degrees",bind:[{parts:["ear-left","ear-right"],rotate:{axis:"x",degrees:1,pivot:[0,-t.ears.radii[1],0]}}]}};for(const u of ty){const d=u[0]==="f",f=u[1]==="l"?1:-1,p=d?e.thickness[0]:e.thickness[1];o.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:o,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=>wx(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:{...vx(t,h),...t.actions?.(h)},acting:sh,colors:{body:n.coat,ink:"#26262b"},follow:[{control:"tail",of:"x",per:.6,stiffness:90,damping:6,limit:40},{control:"ears",of:"x",per:1.4,stiffness:150,damping:8,limit:45}],moves:yx(t,s)}}function yx(t,e){const n=i=>{const r=Lo(e,i);return{speed:r/(Ro[i].cycle*(t.cycleScale??1)/1e3),set:{gait:Is.indexOf(i)},hold:{walking:1},perMetre:{walk:1/r}}},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 we=Array.from({length:7},(t,e)=>e===0?"tail":`tail-${e}`);function bx(t,e,n){const s=lc(t.tail.points,we.length+1),[,i,r]=t.body.radii,o=(t.tail.at[1]-n)/i,a=Math.abs(o)<1?-r*Math.sqrt(1-o*o):t.tail.at[2],l=[t.tail.at[0],t.tail.at[1],a+Math.min(.04,r*.08)],c=f=>t.tail.radius*(1-.5*f/we.length),h=we.map((f,p)=>{const g=s[p],m=s[p+1],w=[m[0]-g[0],m[1]-g[1],m[2]-g[2]],v=p===0?void 0:s[p-1];return{id:f,...p>0?{parent:we[p-1]}:{},shape:{type:"tube",points:[[0,0,0],w],radius:[c(p),c(p+1)],segments:8,joined:!0},at:p===0?l:[g[0]-v[0],g[1]-v[1],g[2]-v[2]],fill:e.dark,outline:.8}}),u=s[s.length-1],d=s[s.length-2];return h.push({id:"tail-tip",parent:we[we.length-1],shape:{type:"ellipsoid",radii:Array(3).fill(c(we.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 wx(t,e,n){const s=Math.max(0,Math.min(1,t.walking??0));if(s===0)return{};const i=Is[Math.max(0,Math.min(3,Math.round(t.gait??0)))],r=Ro[e.gaits.includes(i)?i:e.gaits[0]],o=t.walk??0,a={};for(const c of ty){const h=Math.PI*2*(o+r.offsets[c]);a[`${c}.swing`]=(t[`${c}.swing`]??0)+s*r.swing*Math.sin(h),a[`${c}.knee`]=(t[`${c}.knee`]??0)+s*r.lift*Math.max(0,Math.cos(h))}const l=Math.PI*2*o;return a.lift=(t.lift??0)+s*r.bob*n*Math.abs(Math.sin(l*2)),a.pitch=(t.pitch??0)+s*r.rock*Math.sin(l),a.neck=(t.neck??0)+s*(r.rock>0?-r.rock*1.4:5)*Math.sin(l*2),a}function nh(t){const n=Math.sin(32*an),s=t.legLength-(t.front-t.hind)*n,i=72,o=(s-t.upper*Math.cos(i*an)-t.foot)/t.lower,a=o>=1?0:o<=-1?180:Math.acos(o)/an,l={pitch:32,lift:t.legLength*(1-Math.cos(32*an))-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 sh={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:[]},kx=sh;function ey(t){const e=(t.upper+t.lower)*.32,n=Math.asin(Math.min(1,e/(t.upper+t.lower+t.foot)))/an,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 vx(t,e){const n=t.cycleScale??1,s=o=>({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."}[o],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,o),g=l.for??Math.max(500,p*Ro[o].cycle*n),m=a.values.walk??0;return a.set("gait",u,a.values.gait??0),a.set("gait",u+1,Is.indexOf(o)),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}),(o==="gallop"||o==="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(o=>[o==="gallop"&&!t.gaits.includes("canter")?"run":o,s(o)]));t.gaits.includes("gallop")&&!i.gallop&&(i.gallop=s("gallop"));const r={...i,[t.call]:{summary:`Throws its head up and ${t.call}s.`,run(o,a,l){const c=o.exaggeration;return o.key(l+150,{neck:10*c},{act:!1,easing:"ease-out"}),o.key(l+380,{neck:-28*c,squash:1.05},{act:!1,easing:"ease-out"}),o.key(l+680,{neck:-20*c},{act:!1}),o.key(l+980,{neck:0,squash:1}),e.call(o,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(o,a,l){const c=nh(e),h=l+450;o.key(h,c,{act:!1,easing:"ease-in-out"}),o.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 o.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(o,a,l){const c=ey(e),h={...nh(e)},u=l+400,d=u+450;o.key(u,h,{act:!1,easing:"ease-in-out"}),o.key(d,c,{act:!1,easing:"ease-in-out"}),o.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 o.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(o,a,l){const c=o.exaggeration,h=e.legLength*.8*c,u=l+260,d=u+90,f=d+520;if(o.key(u,{squash:.86,"hl.knee":40,"hr.knee":40,"fl.knee":25,"fr.knee":25,neck:8},{act:!1,easing:"ease-out"}),o.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"}),o.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"}),o.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"}),o.key(f+280,{squash:1,pitch:0,neck:0}),a.to!==void 0){const p=Math.sign(a.to-o.x);p!==0&&o.facing()!==p&&o.turnTo(l,p>0?"right":"left"),o.move(d,f,a.to)}return o.effect({kind:"dust",time:f,x:o.x,y:o.floor,length:550}),{end:f+280,contact:f}}},nod:{summary:"Nods its head twice.",run(o,a,l){return o.key(l+200,{neck:20},{act:!1,easing:"ease-out"}),o.key(l+400,{neck:-5},{act:!1,easing:"ease-in-out"}),o.key(l+600,{neck:18},{act:!1,easing:"ease-in-out"}),o.key(l+900,{neck:0}),{end:l+900}}},swish:{summary:"Swishes its tail a few times.",uses:["for"],run(o,a,l){const c=a.for??900;for(let h=1;h<=4;h++)o.key(l+c*h/5,{tail:h%2===0?10:35},{act:!1,easing:"ease-in-out"});return o.key(l+c,{tail:0}),{end:l+c}}}};return t.grazes&&(r.graze={summary:"Lowers its head to graze for `for` ms (default 1800), nibbling, then looks up.",uses:["for"],run(o,a,l){const c=a.for??1800;o.key(l+600,{neck:75},{act:!1,easing:"ease-in-out"});for(let h=900;h<600+c;h+=400)o.key(l+h,{neck:h%800===100?70:78},{act:!1,easing:"ease-in-out"});return o.key(l+600+c+500,{neck:0}),{end:l+600+c+500}}}),r}function ny(t={}){return ln({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 r=n.exaggeration,o=Math.min(55,32*r),a=-e.hind*Math.sin(o*an),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:o,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 r=n.exaggeration,o=Math.min(35,18*r),a=e.front*Math.sin(o*an);return n.key(i+220,{pitch:3,squash:.95},{act:!1,easing:"ease-out"}),n.key(i+480,{pitch:-o,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 sy(t={}){return ln({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 r=80,o=0;r<i;r+=80,o++)e.key(s+r,{wag:o%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 r=500,o=0;r<i;r+=140,o++)e.key(s+r,{neck:o%2===0?74:66},{act:!1});return e.key(s+i+300,{neck:0,pitch:0}),{end:s+i+300}}}})})}function iy(t={}){return ln({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 r=n.exaggeration,o=s.for??1200,a={squash:1+.25*r,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+o,a,{act:!1}),n.key(i+o+520,{squash:1,neck:0,tail:0,"fl.swing":0,"fr.swing":0,"hl.swing":0,"hr.swing":0}),{end:i+o+520,contact:i+180}}},pounce:{summary:"Crouches low, wiggles, and pounces to `to`, landing with a squash.",needs:["to"],run(n,s,i){const r=n.exaggeration,o=Math.sign(s.to-n.x);let a=i;o!==0&&n.facing()!==o&&(a=n.turnTo(a,o>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*r,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 ry(t={}){return ln({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 Mx(t){return Lo(1,t)}function oy(t={}){return ln({kind:t.kind??"goat",summary:t.summary??"A goat: walks, trots and gallops, bleats, grazes, sits, lies, jumps, and swishes its stubby tail.",legs:{upper:.22,lower:.2,foot:.05,footSize:[.07,.09],front:.26,hind:-.26,across:.1,thickness:[.045,.05],lowerThickness:.03},body:{radii:[.15,.17,.38],rise:.1},neck:{at:[0,.62,.3],points:[[0,0,0],[0,.16,.1]],radius:.07},head:{at:[0,.16,.1],radii:[.09,.1,.15],rotate:[-20,0,0]},muzzle:{at:[0,-.05,.13],radii:[.055,.05,.07]},ears:{at:[.1,.03,-.02],radii:[.06,.025,.03],rotate:[0,0,-20]},eyes:{at:[.065,.05,.09],size:.022},tail:{at:[0,.64,-.37],points:[[0,0,0],[0,.06,-.05]],radius:.025},extras:e=>[{id:"horn-left",parent:"head",shape:{type:"tube",points:[[0,0,0],[.01,.07,-.03],[.015,.12,-.08]],radius:.014,segments:6},at:[.045,.08,-.02],fill:e.dark},{id:"horn-right",parent:"head",shape:{type:"tube",points:[[0,0,0],[-.01,.07,-.03],[-.015,.12,-.08]],radius:.014,segments:6},at:[-.045,.08,-.02],fill:e.dark},{id:"beard",parent:"head",shape:{type:"ellipsoid",radii:[.025,.05,.02],segments:8},at:[0,-.12,.06],fill:e.accent,outline:.5}],colors:{coat:"#e9e2d3",dark:"#8c7b66",foot:"#4f4339",muzzle:"#d8cdb8",accent:"#cfc4b0",...t.colors},gaits:["walk","trot","gallop"],cycleScale:.8,call:"bleat",grazes:!0})}function ay(t={}){return ln({kind:t.kind??"rabbit",summary:t.summary??"A rabbit: walks and hops (gallop), squeaks, nibbles the ground (graze), sits, lies and jumps; long ears and a puff of a tail.",legs:{upper:.07,lower:.07,foot:.03,footSize:[.04,.07],front:.11,hind:-.12,across:.06,thickness:[.028,.04],lowerThickness:.02},body:{radii:[.1,.11,.19],rise:.05},neck:{at:[0,.22,.14],points:[[0,0,0],[0,.06,.04]],radius:.05},head:{at:[0,.07,.04],radii:[.08,.075,.09]},muzzle:{at:[0,-.02,.07],radii:[.035,.028,.03]},ears:{at:[.035,.08,-.02],radii:[.022,.1,.03],rotate:[-15,0,-8]},eyes:{at:[.045,.015,.06],size:.02},tail:{at:[0,.2,-.18],points:[[0,0,0],[0,.03,-.02]],radius:.03},extras:()=>[{id:"nose",parent:"muzzle",shape:{type:"ellipsoid",radii:[.012,.009,.009],segments:8},at:[0,.012,.03],fill:"#e48a9a",outline:.4}],colors:{coat:"#c9b8a6",dark:"#9a8574",foot:"#b5a493",muzzle:"#eadfd2",accent:"#f4ece2",...t.colors},gaits:["walk","gallop"],cycleScale:.4,call:"squeak",grazes:!0})}function ly(t={}){return ln({kind:t.kind??"squirrel",summary:t.summary??"A squirrel: scampers (gallop) and walks, chatters, sits up, nibbles (graze), with a bushy tail curled over its back.",legs:{upper:.05,lower:.05,foot:.02,footSize:[.025,.04],front:.08,hind:-.08,across:.04,thickness:[.02,.025],lowerThickness:.014},body:{radii:[.065,.07,.14],rise:.03},neck:{at:[0,.16,.1],points:[[0,0,0],[0,.04,.03]],radius:.035},head:{at:[0,.05,.03],radii:[.055,.05,.06]},muzzle:{at:[0,-.015,.05],radii:[.025,.02,.02]},ears:{at:[.03,.05,-.01],radii:[.015,.03,.012],rotate:[0,0,-5]},eyes:{at:[.035,.012,.04],size:.015},tail:{at:[0,.14,-.13],points:[[0,0,0],[0,.08,-.06],[0,.2,-.04],[0,.26,.04]],radius:.045},colors:{coat:"#a9663a",dark:"#7a4523",foot:"#7a4523",muzzle:"#e9c9a8",accent:"#f0dcc4",...t.colors},gaits:["walk","gallop"],cycleScale:.3,call:"chatter",grazes:!0})}const cn=.6,cy=75,ih=80;function hn(t){const{colors:e}=t,[n,s,i]=t.body.radii,r=(t.tail.raised??15)*Math.PI/180,o=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]+o*Math.sin(r),t.tail.at[2]-o*Math.cos(r)],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*cn/2,t.wing.chord*.1,t.wing.chord/2],segments:12},at:[h*t.wing.span*cn/2,0,-t.wing.chord*.1],rotate:[-ih,0,0],fill:e.wing,outline:.8}),a.push({id:`wing-${u}-tip`,parent:`wing-${u}-blade`,shape:{type:"ellipsoid",radii:[t.wing.span*cn/2.4,t.wing.chord*.06,t.wing.chord*.3],segments:10},at:[h*t.wing.span*cn/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-cn)/2,0,0],rotate:{axis:"x",degrees:ih},scale:[1/cn,1,1]},{parts:["wing-right-blade"],translate:[-t.wing.span*(1-cn)/2,0,0],rotate:{axis:"x",degrees:ih},scale:[1/cn,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)/cy,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}}]},grip:{description:"The toes curled down round a perch: 0 flat on the ground, 1 gripping",unit:"0..1",min:0,max:1,bind:[{parts:["toes-left","toes-right"],rotate:{axis:"x",degrees:55}}]}},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:xx(t),acting:hy,colors:{body:e.body,ink:"#26262b"},moves:Sx(t)}}function Sx(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 hy={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 xx(t){const e=(t.beatsPerSecond??4)/1e3,n=(o,a,l)=>{const c=o.values.wingbeat??0;o.set("wingbeat",a,c),o.set("wingbeat",l,c+(l-a)*e)},s=(o,a,l)=>{const c=Math.sign(l-o.x);return c!==0&&o.facing()!==c?o.turnTo(a,c>0?"right":"left"):a},i=(o,a)=>{const l=o.anchor("beak");o.effect({kind:"honk",time:a,x:l.x,y:l.y,length:600,direction:o.facing()||1})},r={hop:{summary:"Hops to `to` in little bounces, wings twitching.",needs:["to"],run(o,a,l){const c=s(o,l,a.to),h=o.x,u=Math.abs(a.to-h),d=Math.max(1,Math.round(u/(t.body.radii[2]*3*o.scale))),f=260;for(let p=0;p<d;p++){const g=c+p*f;o.key(g+60,{squash:.85},{act:!1,easing:"ease-out"}),o.key(g+150,{squash:1.1,lift:t.legs.length*1.4,spread:.15},{act:!1,easing:"ease-out"}),o.key(g+f,{squash:.9,lift:0,spread:0},{act:!1,easing:"ease-in"}),o.move(g+60,g+f,h+(a.to-h)*(p+1)/d,{easing:"ease-in-out"})}return o.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(o,a,l){const c=s(o,l,a.to),h=Math.abs(a.to-o.x)/o.scale,u=t.legs.length*1.2,d=h/u,f=a.for??Math.max(400,d*420),p=o.values.step??0;return o.set("stepping",c,0),o.set("stepping",c+150,1,"ease-out"),o.set("stepping",c+f-150,1),o.set("stepping",c+f,0,"ease-in"),o.set("step",c,p),o.move(c,c+f,a.to,{easing:"ease-in-out"}),o.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(o,a,l){const c=a.for??900,h=Math.max(1,Math.round(c/300));o.key(l+120,{pitch:-(t.stoop??12)},{act:!1,easing:"ease-out"});for(let u=0;u<h;u++)o.key(l+120+u*300+90,{peck:cy},{act:!1,easing:"ease-in"}),o.key(l+120+u*300+260,{peck:20},{act:!1,easing:"ease-out"});return o.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(o,a,l){const c=a.for??900;return o.key(l+120,{spread:1},{act:!1,easing:"ease-out"}),o.set("flapping",l,0),o.set("flapping",l+150,1,"ease-out"),o.set("flapping",l+c-150,1),o.set("flapping",l+c,0,"ease-in"),n(o,l,l+c),o.key(l+c*.5,{lift:t.legs.length*.6},{act:!1,easing:"ease-out"}),o.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(o,a,l){return o.key(l+120,{peck:-25,squash:1.06},{act:!1,easing:"ease-out"}),o.key(l+500,{peck:-20},{act:!1}),o.key(l+760,{peck:0,squash:1}),i(o,l+150),{end:l+760,contact:l+150}}}};return t.flies!==!1?(r.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(o,a,l){const c=o.exaggeration;o.key(l+60,{grip:0},{act:!1});const h=s(o,l,a.to),u=a.height??2,d=a.for??Math.max(700,Math.abs(a.to-o.x)/.35),f=o.values.lift>t.legs.length,p=f?h:h+200;return f||(o.key(h+160,{squash:1-.18*c,spread:.6},{act:!1,easing:"ease-out"}),o.effect({kind:"dust",time:p,x:o.x,y:o.floor,length:400})),o.key(p+100,{spread:1,squash:1.08,pitch:10},{act:!1,easing:"ease-out"}),o.set("flapping",p,o.values.flapping??0),o.set("flapping",p+100,1,"ease-out"),o.set("flapping",p+d,.6),n(o,p,p+d),o.key(p+d*.4,{lift:u,pitch:-5,squash:1},{act:!1,easing:"ease-out"}),o.key(p+d,{lift:u,pitch:0},{act:!1,easing:"ease-in-out"}),o.move(p,p+d,a.to,{easing:"ease-in-out"}),{end:p+d,contact:p,release:p+d}}},r.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(o,a,l){let c=l;if(o.values.lift<=t.legs.length){const f=o.x+(a.to-o.x)/3;c=r.fly.run(o,{do:"fly",to:f,height:(a.height??1.5)*1.3},l).end}c=s(o,c,a.to);const h=o.values.lift,u=a.height??h*.67,d=a.for??Math.max(900,Math.abs(a.to-o.x)/.3);return o.set("flapping",c,o.values.flapping??1),o.set("flapping",c+250,0,"ease-out"),n(o,c,c+250),o.key(c+300,{spread:1,flap:10,pitch:-6},{act:!1,easing:"ease-out"}),o.key(c+d,{lift:u,pitch:-3,flap:10},{act:!1,easing:"ease-in-out"}),o.move(c,c+d,a.to,{easing:"ease-in-out"}),{end:c+d,contact:c,release:c+d}}},r.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(o,a,l){const h=a.height??0;return o.set("flapping",l,o.values.flapping??1),o.set("flapping",l+700-120,1),o.set("flapping",l+700,0,"ease-in"),n(o,l,l+700),o.key(l+700*.6,{pitch:14},{act:!1,easing:"ease-out"}),o.key(l+700,{lift:h,pitch:0,squash:.85,grip:h>0?1:0},{act:!1,easing:"ease-in"}),a.to!==void 0&&o.move(l,l+700,a.to,{easing:"ease-out"}),o.key(l+700+160,{squash:1,spread:0,flap:0}),{end:l+700+200,contact:l+700}}}):r.flutter={summary:"Flutters up a little way and back down, wings beating hard (a chicken’s flight).",run(o,a,l){return o.key(l+100,{spread:1,squash:.9},{act:!1,easing:"ease-out"}),o.set("flapping",l+80,0),o.set("flapping",l+160,1,"ease-out"),o.set("flapping",l+900-100,1),o.set("flapping",l+900,0,"ease-in"),n(o,l+80,l+900),o.key(l+900*.5,{lift:t.legs.length*2.5,squash:1.08},{act:!1,easing:"ease-out"}),o.key(l+900,{lift:0,squash:.85,spread:0},{act:!1,easing:"ease-in"}),o.key(l+900+160,{squash:1}),{end:l+900+160,contact:l+900}}},r}function uy(t={}){return hn({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 dy(t={}){return hn({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 fy(t={}){return hn({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})}function gy(t={}){return hn({kind:"pigeon",summary:"A pigeon: walks with a bobbing head, pecks at crumbs, coos, flaps, flies and lands (on the ground, a ledge or a branch).",body:{radii:[.08,.075,.14],height:.14},head:{at:[0,.24,.12],radius:.045},beak:{length:.035,thickness:.014},wing:{shoulder:[.065,.17,.05],span:.24,chord:.11},tail:{at:[0,.13,-.13],length:.12,width:.08,raised:8},legs:{length:.06,across:.03},colors:{body:"#8d93a3",wing:"#6f7586",beak:"#5a5a66",legs:"#d9627a",belly:"#b9bdc8",...t.colors},call:"coo",beatsPerSecond:6,stoop:16})}function py(t={}){return hn({kind:"duck",summary:"A duck: waddles, dabbles with its bill (peck), quacks, flaps, flies and lands (on the ground or the water’s edge).",body:{radii:[.11,.1,.2],height:.16},head:{at:[0,.33,.15],radius:.055},beak:{length:.075,thickness:.028},wing:{shoulder:[.09,.22,.06],span:.28,chord:.13},tail:{at:[0,.17,-.19],length:.1,width:.09,raised:30},legs:{length:.07,across:.045},colors:{body:"#c9b48b",wing:"#8f7a55",beak:"#f2a71b",legs:"#f2a71b",belly:"#e8dcc0",...t.colors},call:"quack",beatsPerSecond:7,stoop:22,neckReach:.04})}function my(t={}){return hn({kind:"owl",summary:"An owl: a big round head, slow silent wingbeats; hoots, turns its head, flies and lands on a branch.",body:{radii:[.1,.12,.13],height:.19},head:{at:[0,.37,.07],radius:.085},beak:{length:.025,thickness:.02},wing:{shoulder:[.085,.27,.03],span:.34,chord:.18},tail:{at:[0,.14,-.12],length:.1,width:.1,raised:-10},legs:{length:.07,across:.04},colors:{body:"#9c7a55",wing:"#6e5538",beak:"#3d3028",legs:"#c9a76a",belly:"#e3cda8",...t.colors},call:"hoot",beatsPerSecond:3,stoop:6})}function yy(t={}){return hn({kind:"parrot",summary:"A parrot: bright, with a big hooked beak and a long tail; squawks, bobs, flies and lands on a perch, gripping it.",body:{radii:[.07,.08,.13],height:.15},head:{at:[0,.29,.1],radius:.055},beak:{length:.045,thickness:.03},wing:{shoulder:[.06,.2,.05],span:.26,chord:.11},tail:{at:[0,.12,-.12],length:.22,width:.06,raised:-20},legs:{length:.06,across:.03},colors:{body:"#4caf50",wing:"#2e7d32",beak:"#5a5a66",legs:"#8d8d8d",belly:"#a5d66f",comb:"#d9372e",...t.colors},call:"squawk",beatsPerSecond:6,stoop:10})}const Os={car:$m,truck:Pm,bus:Im,tractor:Om,cart:Cm,trainCar:_m,bike:Hm,motorbike:Rm,tree:Lm,house:Nm,chair:Dm,desk:zm,bed:jm,door:Km,wheelchair:Um,helicopter:Zm,airplane:Qm,horse:ny,dog:sy,cat:iy,cow:ry,goat:oy,rabbit:ay,squirrel:ly,songbird:uy,crow:dy,chicken:fy,pigeon:gy,duck:py,owl:my,parrot:yy};function rh(t,e={}){const n=Os[t];if(!n)throw new Error(ft("prop preset",t,Object.keys(Os)));return n(e)}const Fo=["do","at","for","to","toward","speed","open","on","height","wind"],oh={viewer:0,right:1,away:2,left:3},Tx=420,ah={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 No(t){return{...ah,...t.actions}}const lh=t=>typeof t=="number"&&Number.isFinite(t);function by(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=No(e),s=Object.keys(n),i=[];return t.forEach((r,o)=>{const a=c=>i.push({level:"error",beat:o,message:c});if(!r||typeof r!="object"||Array.isArray(r))return a(`Each beat must be an object like { do: '${s[s.length-1]}' }.`);const l=r;for(const c of Object.keys(l))Fo.includes(c)||a(ft("beat field",c,Fo,c==="duration"?"for":c==="direction"?"toward":void 0));if(typeof l.do!="string"||!s.includes(l.do))return a(ft(`${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&&!(lh(l[c])&&l[c]>=0)&&a(`\`${c}\` must be a number ≥ 0 (got ${JSON.stringify(l[c])}).`);if(l.to!==void 0&&!lh(l.to)&&a(`\`to\` is a scene x in px (got ${JSON.stringify(l.to)}).`),l.toward!==void 0&&!lh(l.toward)&&!(typeof l.toward=="string"&&l.toward in oh)){const c=typeof l.toward=="string"?Gs(l.toward,Object.keys(oh)):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 wy(t,e,n,s={}){const i=by(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 r=s.from??0,o=s.ground??0,a=s.scale??60,l=s.exaggeration??1,c=No(e),h={};for(const S of[...Object.keys(As),...Object.keys(e.rig.controls)])h[S]=s.start?.[S]??It(e.rig,{},S);const u=[{time:0,pose:{...h}}],d=new Map,f=[];let p=r,g=o;const m=(S,E,I,A)=>{const O=d.get(S)??[{time:0,value:S==="x"||S==="y"?0:h[S]}];O.push({time:E,value:I,...A?{easing:A}:{}}),d.set(S,O),S!=="x"&&S!=="y"&&(h[S]=I)},w=(S,E)=>{const I=S==="x"?p-r:S==="y"?g-o:h[S],A=d.get(S);(!A||A[A.length-1].time<E)&&m(S,E,I)},v={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,E,I={}){Object.assign(h,E),u.push({time:S,pose:{...h},...I.act===!1?{act:!1}:{},...I.easing?{easing:I.easing}:{}})},move(S,E,I,A={}){w("x",S),m("x",E,I-r,A.easing),p=I,A.floor!==void 0&&(w("y",S),m("y",E,A.floor-o,A.easing),g=A.floor)},set(S,E,I,A){m(S,E,I,A)},turnTo(S,E){const I=typeof E=="number"?E:oh[E],A=h.turn,H=[I-4,I,I+4].map(j=>({t:j,d:Math.abs(j-A)})).sort((j,J)=>j.d-J.d||Math.abs(j.t)-Math.abs(J.t))[0];if(H.d<.001)return S;const W=S+Tx*Math.max(1,H.d);return v.key(W,{turn:H.t}),W},effect(S){f.push(S)},anchor(S){const I=$s(e,h,a).anchors[S];if(!I)throw new Error(`${e.kind}: no anchor "${S}"`);return{x:p+I.point.x,y:g+I.point.y}}},k=[];let b=0;for(const S of n){const E=Math.max(S.at??b,u[u.length-1].time),I=c[S.do].run(v,S,E);I.end>u[u.length-1].time&&u.push({time:I.end,pose:{...h}}),k.push({start:E,end:I.end,...I.contact!==void 0?{contact:I.contact}:{},...I.release!==void 0?{release:I.release}:{}}),b=I.end}const T=Ac(s.style??"snappy"),$={...T,anticipation:T.anticipation*l,overshoot:T.overshoot*l},M=So(Px(u),e.acting,{style:$}),x=[...Object.entries(M).filter(([S])=>!d.has(S)).map(([S,E])=>({id:`${t}-${S}`,target:t,property:S,keyframes:E})),...[...d].map(([S,E])=>({id:`${t}-${S}`,target:t,property:S,keyframes:Ix(E)}))];for(const S of Ax(t,e,x,b,u[0].pose)){const E=x.findIndex(O=>O.property===S.property);if(E<0){x.push(S);continue}const I=new Ht({id:`${t}-own`,tracks:[x[E]]}),A=O=>Number(I.getStateAtTime(O).values.get(t)?.get(S.property)??0);x[E]={...S,keyframes:S.keyframes.map(O=>({time:O.time,value:Number(O.value)+A(O.time)}))}}return{tracks:x,duration:b,beats:k,effects:f}}const Ex=1500;function Ax(t,e,n,s,i){if(!e.follow?.length)return[];const r=new Ht({id:`${t}-follow`,tracks:n.filter(a=>a.property==="turn"||e.follow.some(l=>l.of===a.property))}),o=(a,l)=>{const c=r.getStateAtTime(a).values.get(t)?.get(l);return typeof c=="number"?c:i[l]??0};return e.follow.map(a=>{const l=s+Ex,c=Us(d=>o(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(o(d,"turn")*Math.PI/2),g=(f-o(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 $x=20;function Px(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<$x?n[n.length-1]={...s,time:i.time}:n.push(s)}return n}function Ix(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 Ne=Object.freeze({test:Object.freeze({name:"Test",inningsPerSide:2,oversPerInnings:null,ballsPerOver:6,freeHitAfterNoBall:!1,summary:"Multi-day cricket. Each side can have two innings; there is no innings over limit."}),odi:Object.freeze({name:"ODI",inningsPerSide:1,oversPerInnings:50,ballsPerOver:6,freeHitAfterNoBall:!0,summary:"One innings per side, up to 50 overs. A no-ball gives a free hit on the next legitimate delivery."}),t20:Object.freeze({name:"T20",inningsPerSide:1,oversPerInnings:20,ballsPerOver:6,freeHitAfterNoBall:!0,summary:"One innings per side, up to 20 overs. A no-ball gives a free hit on the next legitimate delivery."})}),ch=Object.freeze({adults:"Adults",men:"Men",children:"Children",mixed:"Mixed cast"}),Cs=Object.freeze({bowler:"Bowler",keeper:"Wicketkeeper",fielder:"Extra cover",slip:"Slip",point:"Point",cover:"Cover","mid-off":"Mid-off","mid-on":"Mid-on","square-leg":"Square leg","fine-leg":"Fine leg","third-man":"Third man"}),Wn=Object.freeze(Object.fromEntries(Object.entries({bowling:{name:"Pace bowling",summary:"Run up, deliver with a straight arm, bounce and follow through."},spin:{name:"Spin bowling",summary:"A shorter approach and a curved illustrative flight before the bounce."},batting:{name:"Drive",summary:"Two hands on the bat, a backlift, contact and a follow-through."},defend:{name:"Defensive block",summary:"Meet the ball with a controlled bat and keep it close."},running:{name:"Running between wickets",summary:"Both batters make the opposite ground to complete one run."},four:{name:"Boundary four",summary:"A struck ball reaches the boundary after touching the ground."},six:{name:"Boundary six",summary:"A struck ball clears the boundary before touching the ground."},catch:{name:"Catch",summary:"A fielder controls the struck ball before it touches the ground."},fielding:{name:"Ground field",summary:"A fielder moves to the ball, bends and gathers it."},throw:{name:"Field and throw",summary:"Gather, wind up, release and return the ball to the keeper."},bowled:{name:"Bowled",summary:"A legal delivery hits the wicket and removes a bail."},lbw:{name:"LBW illustration",summary:"Pad contact and a projected path to the stumps illustrate an authored LBW decision."},stumping:{name:"Stumping",summary:"The keeper holds the ball and breaks the wicket while the striker is out of ground, not attempting a run."},"run-out":{name:"Run-out",summary:"A direct throw breaks the wicket before the running batter makes that ground."},"no-ball":{name:"Front-foot no-ball",summary:"The landing front foot oversteps the popping crease at release; one extra, no legal ball."},wide:{name:"Wide ball",summary:"An untouched delivery passes beyond reach for a normal stroke; one extra, no legal ball."}}).map(([t,e])=>[t,Object.freeze(e)])));function ge(t,e,n){if(!Object.prototype.hasOwnProperty.call(t,e))throw new Error(`${n}: unknown choice '${e}'`);return e}const _t=(t,e,n)=>Math.max(0,Math.min(1,(t-e)/(n-e))),Ft=t=>t*t*(3-2*t),Tt=(t,e)=>Vs(t,e),hh=(t,e)=>mn(t,e);function uh(t,e){const n=e+((t-e+2)%4+4)%4-2;return n===0?0:n}function _s(t,e,n=0){return Math.hypot(e[0]-t[0],e[2]-t[2])<.001?n:uh(Math.atan2(e[0]-t[0],e[2]-t[2])*2/Math.PI,n)}function ky(){return{turn:1,"head.turn":90,"leg.left.spread":12,"leg.right.spread":12,"leg.left.swing":6,"leg.right.swing":6,"leg.left.knee":12,"leg.right.knee":12}}function dh(t,e){const n=t.objects.find(s=>s.id===e);if(!n||n.kind!=="character")throw new Error(`cricketAction: required character '${e}' is missing`);if(n.parent||n.rotation?.some(s=>s!==0)||n.quaternion||n.scale!==void 0)throw new Error(`cricketAction: '${e}' must use position and pose.turn, without a transformed parent, scale or object rotation`);return{object:n,who:ps({...n.character,height:n.height??1.78})}}function vy(t){return{position:[...t.object.position??[0,0,0]],pose:{...lt,...t.object.pose}}}function Hs(t,e,n,s){const i=Ze(t.who.plan,e.pose,{height:t.who.height,contact:t.who.contact});return Tt(e.position,i.chains[n][s])}function Wi(t,e,n){const s=Hs(t,e,`arm.${n}`,2),i=Hs(t,e,`arm.${n}`,1);return Tt(s,hh(Jt(se(s,i)),t.who.lineWidth*.5))}function Ox(t,e,n){const s={...e.pose,"head.turn":0,"head.nod":0,"head.tilt":0},i=Ze(t.who.plan,s,{height:t.who.height,contact:t.who.contact}).head,r=se(n,Tt(e.position,i.center)),o=i.axes.map(c=>$e(r,c)),a=Math.atan2(o[0],o[2])*180/Math.PI,l=Math.atan2(-o[1],Math.hypot(o[0],o[2]))*180/Math.PI;return{...e,pose:{...e.pose,"head.turn":Math.max(-90,Math.min(90,a)),"head.nod":Math.max(-25,Math.min(30,l)),"head.tilt":0}}}function un(t,e,n,s,i="hold"){let r={...e.pose};for(let o=0;o<10;o++){const a={...e,pose:r},l=Ze(t.who.plan,r,{height:t.who.height,contact:t.who.contact}),c=is(t.who.plan,r,t.who.height),h=se(Wi(t,a,n),Hs(t,a,`arm.${n}`,2)),u=se(se(se(s,h),e.position),l.hip),d=ss(u,(r.roll??0)*Math.PI/180),f=Tt(c.root,Qt(d,-(r.turn??0)*Math.PI/2));r=gi(t.who.plan,r,`arm.${n}`,f,{height:t.who.height})}for(const[o,a]of Object.entries(St[i]))r[`hand.${n}.${o}`]=a;return{...e,pose:r}}function Cx(t,e,n,s){const i=Jt(s),r=t.who.height/1.78;let o=un(t,e,"left",n);return o=un(t,o,"right",Tt(Wi(t,o,"left"),hh(i,.105*r))),{...o,bat:{grip:Wi(t,o,"left"),axis:i,scale:r}}}function _x(t){return Tt(t.grip,hh(t.axis,.51*t.scale))}function My(t){const e=Jt(t),n=Math.max(-1,Math.min(1,e[1]));return n>.999999?[0,0,0,1]:n<-.999999?Vt([1,0,0],180):Vt(Jt(Js([0,1,0],e)),Math.acos(n)*180/Math.PI).map(s=>s===0?0:s)}function Wo(t,e,n){const s={};for(const i of Object.keys({...t,...e})){const r=t[i]??lt[i]??0;s[i]=r+((e[i]??lt[i]??0)-r)*n}return s}function fh(t,e){if(t<=e[0][0])return{...lt,...e[0][1]};for(let n=1;n<e.length;n++)if(t<=e[n][0])return Wo({...lt,...e[n-1][1]},{...lt,...e[n][1]},Ft(_t(t,e[n-1][0],e[n][0])));return{...lt,...e.at(-1)[1]}}function We(t,e){if(!Array.isArray(t)||t.length!==3||!t.every(Number.isFinite))throw new Error(`${e}: expected three finite coordinates`)}function Sy(t,e,n=40,s=[]){if(!Number.isFinite(t)||!Number.isFinite(e)||t<0||e<t)throw new Error("sampleTimes: expected finite ordered nonnegative times");if(!Number.isFinite(n)||n<16||n>1e3)throw new Error("sampleTimes: every must be between 16 and 1000 ms");if((e-t)/n>2e4)throw new Error("sampleTimes: too many samples");const i=new Set([t,e,...s.filter(r=>r>=t&&r<=e&&Number.isFinite(r))]);for(let r=t+n;r<e;r+=n)i.add(r);return[...i].sort((r,o)=>r-o)}function gh(t,e){if(xy(t),!Number.isFinite(e))throw new Error("ballFlightPoint: time must be finite");const n=Math.max(0,Math.min(1,(e-t.start)/(t.end-t.start))),s=4*n*(1-n),i=t.to[0]-t.from[0],r=t.to[2]-t.from[2],o=Math.hypot(i,r)||1;return[t.from[0]+i*n-r/o*(t.curve??0)*s,t.from[1]+(t.to[1]-t.from[1])*n+(t.arc??0)*s,t.from[2]+r*n+i/o*(t.curve??0)*s]}function xy(t){if(!t.target?.trim())throw new Error("ballFlight: target is required");if(We(t.from,"ballFlight.from"),We(t.to,"ballFlight.to"),!Number.isFinite(t.start)||!Number.isFinite(t.end)||t.start<0||t.end<=t.start)throw new Error("ballFlight: end must be greater than start, both finite and nonnegative");if(!Number.isFinite(t.arc??0)||(t.arc??0)<0||!Number.isFinite(t.curve??0))throw new Error("ballFlight: arc must be finite and nonnegative; curve must be finite")}function Hx(t){xy(t);const e=Sy(t.start,t.end,t.every),n=e.map(s=>gh(t,s));return["x","y","z"].map((s,i)=>({id:`${t.id??"flight"}-${s}`,target:t.target,property:s,keyframes:e.map((r,o)=>({time:r,value:n[o][i]}))}))}const Di=Object.freeze({"front-foot":Object.freeze({name:"Front-foot review",summary:"A fixed side view of the landing front foot and bowler’s popping crease at release."}),"striker-crease":Object.freeze({name:"Striker crease",summary:"A fixed side view of the striker’s popping crease, wicket and keeper arrival."}),"bowler-crease":Object.freeze({name:"Bowler crease",summary:"A fixed side view of the other crease and wicket for a running batter and return throw."})});function ph(t){return Object.prototype.hasOwnProperty.call(Di,t)}function Do(t,e){if(!ph(e))return;const n=i=>t.events.find(r=>r.id===i),s=e==="front-foot"?n("release"):e==="bowler-crease"?t.action==="run-out"?n("wicket"):n("run")??n("release"):(t.action!=="run-out"?n("wicket"):void 0)??n("run")??n("keeper")??n("return")??t.events.find(i=>i.kind==="contact");if(s){if(!Number.isFinite(s.time)||s.time<0||s.time>t.duration)throw new Error("cricketCameraReview: event time must be within the clip");return{...s}}}function Bo(t,e,n){const s=dh(t.scene,e),i=vy(s);for(const r of t.timeline.tracks){if(r.target!==t.scene.id+"/"+e)continue;if(!("keyframes"in r))throw new Error("cricketCamera: review requires baked actor tracks");const o=new Ke(r).getValueAtTime(n);if(typeof o!="number"||!Number.isFinite(o))continue;const a=["x","y","z"].indexOf(r.property);a>=0?i.position[a]=o:i.pose[r.property]=o}return{actor:s,sample:i}}function Ty(t){const e=Do(t,"front-foot");if(!e)throw new Error("cricketCamera: front-foot view requires a release event");const{actor:n,sample:s}=Bo(t,"bowler",e.time);return{point:Hs(n,s,"leg.right",2),height:n.who.height}}function Ey(t,e){const n=e==="striker-crease"?"striker":"bowler",s=t.landmarks[n+"-crease"];return We(s,"cricketCamera.crease"),[...s]}function Rx(t,e){if(!ph(e))return[];const n=Ey(t,e),s=e==="front-foot"?Ty(t).point[0]:0;return[{id:"decision-review-"+e,name:Di[e].name+": crease reference",kind:"line",color:"#f4b83f",width:.035,points:[[s-1.1,.045,n[2]],[s+1.1,.045,n[2]]]}]}function mh(t,e,n,s){const i=e*Math.PI/180,r=n*Math.PI/180;return[t[0]+s*Math.cos(r)*Math.sin(i),t[1]+s*Math.sin(r),t[2]+s*Math.cos(r)*Math.cos(i)]}const yh=(t,e,n)=>[t[0]+(e[0]-t[0])*n,t[1]+(e[1]-t[1])*n,t[2]+(e[2]-t[2])*n];function Lx(t,e,n){const s={target:[0,0,0],yaw:0,pitch:15,distance:8,...t},i={...s,...e},r=yh(s.target,i.target,n),o=s.position||i.position?yh(s.position??mh(s.target,s.yaw,s.pitch,s.distance),i.position??mh(i.target,i.yaw,i.pitch,i.distance),n):mh(r,s.yaw+(i.yaw-s.yaw)*n,s.pitch+(i.pitch-s.pitch)*n,s.distance+(i.distance-s.distance)*n),a=yh(s.lookAt??s.target,i.lookAt??i.target,n),l=s.fov!==void 0||i.fov!==void 0?(s.fov??i.fov)+((i.fov??s.fov)-(s.fov??i.fov))*n:void 0;return{position:o,lookAt:a,fov:l}}function Fx(t){const e=Math.max(1,t.every??33),n=Wt(t.easing??"ease-in-out"),s=`${t.scene}/${t.camera}`,i=[],r=[],o=[];for(let l=t.start;;l=Math.min(t.end,l+e)){const c=t.end>t.start?n((l-t.start)/(t.end-t.start)):1,h=Lx(t.from,t.to,c);if(i.push({time:l,value:h.position}),r.push({time:l,value:h.lookAt}),h.fov!==void 0&&o.push({time:l,value:h.fov}),l>=t.end)break}const a=[{id:`${s}-move-position`,target:s,property:"position",keyframes:i},{id:`${s}-move-lookAt`,target:s,property:"lookAt",keyframes:r}];return o.length>0&&a.push({id:`${s}-move-fov`,target:s,property:"fov",keyframes:o}),a}function Nx(t){const e=Math.max(1,t.every??33),n=t.offset??[0,2,6],s=t.lag??0,i=`${t.scene}/${t.camera}`,r=[],o=[];for(let a=t.start;;a=Math.min(t.end,a+e)){const l=t.subjectAt(a),c=t.subjectAt(Math.max(t.start,a-s));if(r.push({time:a,value:[c[0]+n[0],c[1]+n[1],c[2]+n[2]]}),o.push({time:a,value:l}),a>=t.end)break}return[{id:`${i}-follow-position`,target:i,property:"position",keyframes:r},{id:`${i}-follow-lookAt`,target:i,property:"lookAt",keyframes:o}]}const zo=Object.freeze({pitch:"Whole pitch",batter:"Batter close-up",bowler:"Bowler close-up",keeper:"Keeper close-up",field:"Whole ground",overhead:"Overhead ground",orbit:"360° ground orbit","follow-ball":"Follow the ball",...Object.fromEntries(Object.entries(Di).map(([t,e])=>[t,e.name]))}),qo=Object.freeze({pitch:75,batter:145,bowler:35,keeper:145,field:75,overhead:75,orbit:75,"follow-ball":75,"front-foot":90,"striker-crease":90,"bowler-crease":90});function Ay(t,e="pitch"){const n=ge(zo,e,"cricketCamera.view");if(ph(n)){const i=Ey(t,n);if(n==="front-foot"){const c=Ty(t);return{target:[c.point[0],.12,(c.point[2]+i[2])/2],pitch:25,distance:Math.max(2.2,2.6*c.height/1.78),fov:40}}const r=t.landmarks[n==="striker-crease"?"striker-wicket":"bowler-wicket"];We(r,"cricketCamera.wicket");let o=(i[2]+r[2])/2,a=4;if(t.action==="run-out"&&n==="bowler-crease"||t.action==="running"){const c=Do(t,n);if(c){const u=Bo(t,n==="bowler-crease"?"batter":"non-striker",c.time).sample.position;o=(Math.min(i[2],r[2],u[2])+Math.max(i[2],r[2],u[2]))/2,a=Math.max(4,Math.abs(r[2]-u[2])*1.8)}}let l=0;if(n==="striker-crease"&&t.action==="wide"){const c=Do(t,n);if(c){const h=Bo(t,"keeper",c.time).sample.position,u=Bo(t,"batter",c.time).sample.position,d=Math.min(i[0],r[0],h[0],u[0]),f=Math.max(i[0],r[0],h[0],u[0]),p=Math.min(i[2],r[2],h[2],u[2]),g=Math.max(i[2],r[2],h[2],u[2]);l=(d+f)/2,o=(p+g)/2,a=Math.max(4,Math.hypot(f-d,g-p)*1.8)}}return{target:[l,.42,o],pitch:12,distance:a,fov:44}}if(n==="follow-ball"){const i=t.scene.objects.find(r=>r.id==="camera"&&r.kind==="camera");return{pitch:Math.atan2(3,Math.hypot(5,6))*180/Math.PI,distance:Math.sqrt(70),fov:i?.kind==="camera"&&i.projection==="perspective"?i.fov:48}}const s=n==="field"||n==="overhead"||n==="orbit";return{target:n==="batter"?[.1,.85,9.3]:n==="bowler"?[.68,1,-9.55]:n==="keeper"?[0,.7,10.1]:[0,.65,0],distance:s?t.boundaryRadius*2.8:n==="pitch"?29:4.3,pitch:n==="overhead"?89:s?52:n==="pitch"?16:12,fov:s?48:n==="pitch"?50:46}}function bh(t,e,n,s){if(t!==void 0&&(!Number.isFinite(t)||t<e||t>n))throw new Error("cricketCamera: "+s+" must be between "+e+" and "+n)}function Wx(t,e={}){const n=ge(zo,e.view??"pitch","cricketCamera.view"),s=e.yaw??qo[n];if(!Number.isFinite(s))throw new Error("cricketCamera: yaw must be finite");const i=(s%360+360)%360,r=e.zoom??1;if(!Number.isFinite(r)||r<.25||r>4)throw new Error("cricketCamera: zoom must be between 0.25 and 4");const o=g=>r===1?g:Math.atan(Math.tan(g*Math.PI/360)/r)*360/Math.PI,a=e.every??40;if(!Number.isFinite(a)||a<16||a>1e3)throw new Error("cricketCamera: every must be between 16 and 1000 ms");if(bh(e.pitch,0,89,"pitch"),bh(e.distance,.5,2e3,"distance"),bh(e.fov,10,100,"fov"),e.target!==void 0&&(We(e.target,"cricketCamera.target"),n==="follow-ball"))throw new Error("cricketCamera: target override is not supported by follow-ball");const l=Ay(t,n),c=e.pitch??l.pitch,h=e.distance??l.distance,u=o(e.fov??l.fov),d=e.target?[...e.target]:l.target??[0,0,0],f=t.scene.id+"/camera",p=g=>{if(e.distance===void 0&&e.target===void 0)return g;const m=g.find(k=>k.property==="position");if(!m||!("keyframes"in m))return g;const w=t.scene.objects.find(k=>k.id==="camera"&&k.kind==="camera");let v=w?.kind==="camera"?Math.max(600,w.far):600;for(const k of m.keyframes)v=Math.max(v,Math.hypot(...k.value)+t.boundaryRadius+10);if(!Number.isFinite(v))throw new Error("cricketCamera: framing exceeds finite camera range");return[...g,{id:f+"-framing-far",target:f,property:"far",keyframes:[{time:0,value:v},{time:t.duration,value:v}]}]};if(n==="follow-ball"){const g=["x","y","z"].map(b=>{const T=t.timeline.tracks.find(S=>S.target===t.scene.id+"/ball"&&S.property===b);if(!T||!("keyframes"in T)||!T.keyframes.length)throw new Error("cricketCamera: missing ball "+b+" keyframes");const $=T.keyframes;let M=0,x=new Ke({...T,keyframes:$.slice(0,2)});return S=>{const E=M;for(;M<$.length-2&&S-(T.delay??0)>$[M+1].time;)M++;return M!==E&&(x=new Ke({...T,keyframes:$.slice(M,M+2)})),x.getValueAtTime(S)}}),m=(Math.atan2(5,6)*180/Math.PI+i-qo["follow-ball"])*Math.PI/180,w=c*Math.PI/180,v=i===qo["follow-ball"]&&(e.pitch===void 0||e.pitch===l.pitch)&&(e.distance===void 0||e.distance===l.distance)?[5,3,6]:[Math.sin(m)*Math.cos(w)*h,Math.sin(w)*h,Math.cos(m)*Math.cos(w)*h],k=Nx({scene:t.scene.id,camera:"camera",start:0,end:t.duration,every:a,offset:v,subjectAt:b=>g.map(T=>T(b))});return p([...k,{id:f+"-zoom-fov",target:f,property:"fov",keyframes:[{time:0,value:u},{time:t.duration,value:u}]}])}return p(Fx({scene:t.scene.id,camera:"camera",start:0,end:t.duration,every:a,easing:"linear",from:{target:d,yaw:i,pitch:c,distance:h,fov:u},to:{yaw:n==="orbit"?i+360:i}}))}const jo=Object.freeze({mcc:Object.freeze({name:"MCC",poppingCreaseHalfWidth:1.83,fieldingRadius:null,summary:"MCC minimum crease markings. The base Laws do not prescribe a limited-over restriction area."}),"icc-men":Object.freeze({name:"ICC men",poppingCreaseHalfWidth:7.5,fieldingRadius:27.43,summary:"ICC men: extended crease markings; ODI/T20 restriction-area arcs have a 27.43 m radius."}),"icc-women":Object.freeze({name:"ICC women",poppingCreaseHalfWidth:7.5,fieldingRadius:23,summary:"ICC women: extended crease markings; ODI/T20 restriction-area arcs have a 23 m radius."})});function Dx(t){const[e,n]=t.centres,s=Math.hypot(n[0]-e[0],n[2]-e[2]),i=(n[0]-e[0])/s,r=(n[2]-e[2])/s,o=[];for(let a=0;a<2;a++){const l=a===0?n:e;for(let c=0;c<=64;c++){const h=(a+c/64)*Math.PI,u=Math.cos(h)*t.radius,d=Math.sin(h)*t.radius;o.push([l[0]+r*u+i*d,.018,l[2]-i*u+r*d])}}return o}function $y(t,e){We(e,"cricketFieldingAreaContains.point");const n=t.fieldingArea;if(n==null)return null;if(!Number.isFinite(n.radius)||n.radius<=0)throw new Error("cricketFieldingAreaContains: radius must be positive and finite");if(!Array.isArray(n.centres)||n.centres.length!==2)throw new Error("cricketFieldingAreaContains: two centres are required");const[s,i]=n.centres;We(s,"cricketFieldingAreaContains.centre"),We(i,"cricketFieldingAreaContains.centre");const r=i[0]-s[0],o=i[2]-s[2],a=r*r+o*o,l=a?Math.max(0,Math.min(1,((e[0]-s[0])*r+(e[2]-s[2])*o)/a)):0;return Math.hypot(e[0]-s[0]-l*r,e[2]-s[2]-l*o)<=n.radius+1e-9}function Py(t){return Object.keys(Cs).flatMap(e=>{const n=t.scene.objects.find(i=>i.id===e&&i.kind==="character");if(!n)return[];if(n.parent)throw new Error(`cricketFieldingPositions: '${e}' must be unparented for setup markers`);const s=[...n.position??[0,0,0]];return[{id:e,name:n.name??Cs[e],position:s,inside:$y(t,s)}]})}function Bx(t){return t.fieldingArea?Py(t).map(e=>({id:`fielding-review-${e.id}`,name:`${e.name}: ${e.inside?"inside":"outside"} restriction area`,kind:"line",closed:!0,width:.12,color:e.inside?"#d8eb8a":"#ee9670",points:Array.from({length:32},(n,s)=>[e.position[0]+Math.cos(s*Math.PI/16)*.7,.06,e.position[2]+Math.sin(s*Math.PI/16)*.7])})):[]}const jt=Object.freeze({length:20.12,width:3.05,poppingCrease:1.22,returnCrease:1.32,stumpHeight:.711,wicketWidth:.2286});function Iy(t){if(!t.id?.trim())throw new Error("cricketPlayer: id is required");ge({batter:1,bowler:1,keeper:1,fielder:1,umpire:1},t.role,"cricketPlayer.role");const e=ge(Oi,t.preset??"youngMan","cricketPlayer.preset"),n=ge(Ne,t.format??"t20","cricketPlayer.format"),s=ge({none:1,cap:1,"sun-hat":1},t.headwear??"none","cricketPlayer.headwear"),i=e==="childBoy"||e==="childGirl",r=t.height??(i?1.24:1.78);if(!Number.isFinite(r)||r<.5||r>3)throw new Error("cricketPlayer: height must be between .5 and 3 metres");We(t.position??[0,0,0],"cricketPlayer.position");const o=t.role==="umpire"?"#f5ebd5":n==="test"?"#f5f0df":t.color??"#3577b5",a=JSON.parse(JSON.stringify({...Oi[e],...t.appearance,outfit:Ap("casual",{top:"shirt",shirt:o,trousers:t.role==="umpire"?"#405058":o,bottom:"trousers",trouserStyle:"plain",sleeves:"short",collar:!0,tie:null,shoes:"boots",shoeColor:"#f3ead7"}),hat:s==="none"?null:{style:s==="sun-hat"?"sunHat":"cap",color:o}}));return{id:t.id,name:t.role,kind:"character",look:"pen",height:r,position:[...t.position??[0,0,0]],character:a,pose:t.role==="batter"?ky():{turn:t.role==="keeper"?2:0}}}function Yo(t,e,n,s,i=0){return{id:t,kind:"mesh",position:e,geometry:{type:"box",size:n},material:s,layer:i}}function zx(t,e){const n=jt.stumpHeight,s=(jt.wicketWidth-.036)/2;return[...[-1,0,1].map((i,r)=>({id:`${t}-stump-${r}`,kind:"mesh",position:[i*s,n/2,e],geometry:{type:"cylinder",radius:.018,height:n,segments:10},material:"wicket"})),...[-1,1].map((i,r)=>Yo(`${t}-bail-${r}`,[i*s/2,n+.015,e],[.105,.025,.035],"bail"))]}function Oy(t,e){return[{id:t,kind:"group",scale:e,visible:!1},Yo(`${t}-grip`,[0,.1,0],[.036,.28,.036],"bat-grip"),Yo(`${t}-blade`,[0,.51,0],[.108,.54,.055],"bat-blade"),Yo(`${t}-label`,[0,.41,.029],[.07,.16,.004],"bat-label")].map((s,i)=>i===0?s:{...s,parent:t})}function wh(t={}){const e=ge(Ne,t.format??"t20","cricketField.format"),n=ge(ch,t.cast??"adults","cricketField.cast"),s=ge(jo,t.markingProfile??"icc-men","cricketField.markingProfile"),i=jo[s],r=t.boundaryRadius??64;if(!Number.isFinite(r)||r<24||r>250)throw new Error("cricketField: boundaryRadius must be between 24 and 250 metres");const o=t.id??"cricket";if(!o.trim())throw new Error("cricketField: id is required");const a=jt.length/2,l=e!=="test"&&i.fieldingRadius!==null?{radius:i.fieldingRadius,centres:[[0,0,-a],[0,0,a]]}:null,c={"striker-wicket":[0,0,a],"bowler-wicket":[0,0,-a],"striker-crease":[0,0,a-jt.poppingCrease],"bowler-crease":[0,0,-a+jt.poppingCrease]},h=[{id:"camera",kind:"camera",projection:"perspective",position:[25,9,6],lookAt:[0,.65,0],fov:48,near:.02,far:Math.max(600,r*4)},{id:"sun",kind:"light",light:"directional",position:[4,8,5],intensity:.8,color:"#fff2dd"},{id:"ambient",kind:"light",light:"ambient",intensity:.85,color:"#eaf6f4"},{id:"outfield",kind:"mesh",layer:-4,position:[0,-.04,0],geometry:{type:"cylinder",radius:r+1,height:.06,segments:80},material:"grass"},{id:"square",kind:"mesh",layer:-3,geometry:{type:"plane",size:[8,25]},position:[0,.003,0],material:"square"},{id:"pitch",kind:"mesh",layer:-2,geometry:{type:"plane",size:[jt.width,jt.length]},position:[0,.008,0],material:"pitch"},{id:"boundary",kind:"line",layer:-1,closed:!0,width:.15,color:"#f8f2db",points:Array.from({length:96},(p,g)=>[Math.cos(g*Math.PI/48)*r,.022,Math.sin(g*Math.PI/48)*r])}];l&&h.push({id:"fielding-circle",kind:"line",layer:-1,closed:!0,width:.06,color:"#d6e4c8",points:Dx(l)});for(const p of[-1,1]){const g=p>0?"striker":"bowler",m=p*a,w=m-p*jt.poppingCrease;h.push(...zx(g,m));const v=(k,b)=>h.push({id:`${g}-${k}`,kind:"line",layer:-1,color:"#fffdf0",width:.045,points:b});v("popping-line",[[-i.poppingCreaseHalfWidth,.02,w],[i.poppingCreaseHalfWidth,.02,w]]),v("bowling-line",[[-1.32,.02,m],[1.32,.02,m]]);for(const k of[-1,1])v(`return-line-${k<0?"left":"right"}`,[[k*1.32,.02,w],[k*1.32,.02,m+p*2.5]])}const u=[["batter","batter",[-.38,0,9.3]],["non-striker","batter",[-.85,0,-9.3]],["bowler","bowler",[.68,0,-17]],["keeper","keeper",[0,0,11.25]],["fielder","fielder",[12,0,-3]],["slip","fielder",[3.5,0,12]],["point","fielder",[20,0,6]],["cover","fielder",[22,0,-16]],["mid-off","fielder",[9,0,-25]],["mid-on","fielder",[-9,0,-25]],["square-leg","fielder",[-20,0,7]],["fine-leg","fielder",[-20,0,35]],["third-man","fielder",[23,0,35]],["umpire","umpire",[0,0,-12.4]],["square-umpire","umpire",[-15,0,8.84]]];u.forEach(([p,g,m],w)=>{const v=n==="children"||n==="mixed"&&w%3===0,k=n==="men"?"youngMan":v?w%2?"childGirl":"childBoy":w%2?"youngWoman":"youngMan",b=Math.hypot(m[0],m[2]),T=b>r*.88?[m[0]*r*.88/b,0,m[2]*r*.88/b]:[...m];c[p]=[...T];const $=Iy({id:p,role:g,preset:k,format:e,position:T,color:g==="batter"?t.battingColor??"#397cb9":t.fieldingColor??"#bf604e"});if(Object.hasOwn(Cs,p)&&($.name=Cs[p]),p!=="batter"){const M=p==="non-striker"||p==="bowler"?u[0][2]:u.find(([x])=>x==="bowler")[2];$.pose={turn:_s(T,M)}}h.push($)});const d=p=>h.find(g=>g.id===p).height/1.78;h.push(...Oy("bat",d("batter")),...Oy("non-striker-bat",d("non-striker"))),h.push({id:"ball",kind:"mesh",position:[0,.075,0],geometry:{type:"sphere",radius:.075,segments:12},material:"ball"}),h.push({id:"lbw-guide",kind:"group",visible:!1},{id:"lbw-projection",kind:"line",parent:"lbw-guide",points:[[0,0,0],[0,1,0]],width:.04,color:"#e9ae38"});const f=p=>({color:p,shading:"toon",outline:{color:"#69513a",width:.8}});return{format:e,boundaryRadius:r,landmarks:c,markingProfile:s,fieldingArea:l,scene:{id:o,formatVersion:1,camera:"camera",background:{top:"#c8e5ef",bottom:"#e9efcc"},ground:0,objects:h,materials:{grass:{color:"#81a95c",shading:"unlit"},square:{color:"#a6b76a",shading:"unlit",doubleSided:!0},pitch:{color:"#ddbd85",shading:"unlit",doubleSided:!0},wicket:f("#edd99e"),bail:f("#bd8c4d"),"bat-grip":f("#385b5c"),"bat-blade":f("#e8c58d"),"bat-label":f("#c34d4c"),ball:{color:e==="test"?"#b32d36":"#fff9e7",shading:"toon",outline:{color:"#9b3840",width:1}}}}}}const Yt=1900,Bi=2450,Et=2900,zi=4100,dn=4200,Rs=4600,Ko=5300,kh=5500;function Xo(t,e,n,s,i,r,o=t.object.pose?.turn??0){const a=_t(e,n,s),l=Zs(i,r),c=_s(i,r,o),h=o+(c-o)*Ft(_t(e,n,n+200)),u={...lt,...t.object.pose,turn:h},d=Jr("run",t.who.height,1,t.object.character?.legLength??1),f=Vr("run",l*a/d,u),p=Math.min(a*12,(1-a)*12,1);return{position:yn(i,r,a),pose:Wo(u,f,Math.max(0,p))}}function vh(t,e,n){const s=(t.pose.turn??0)*Math.PI/2;return Tt(t.position,[Math.sin(s)*e,n,Math.cos(s)*e])}function qx(t,e,n,s,i){const r=`${e}/${n.object.id}`,o={...lt,...n.object.pose},a=new Set(i.flatMap(l=>Object.keys(l.pose)));for(const l of a){const c=o[l]??0;i.some(h=>h.pose[l]!==c)&&t.push({id:`${n.object.id}-${l}`,target:r,property:l,keyframes:s.map((h,u)=>({time:h,value:i[u].pose[l]??c}))})}for(const[l,c]of["x","y","z"].entries())i.some(h=>h.position[l]!==(n.object.position?.[l]??0))&&t.push({id:`${n.object.id}-${c}`,target:r,property:c,keyframes:s.map((h,u)=>({time:h,value:i[u].position[l]}))});if(i[0].bat){const l=n.object.id==="batter"?"bat":"non-striker-bat",c=`${e}/${l}`;t.push({id:`${l}-visible`,target:c,property:"visible",keyframes:[{time:0,value:1}]}),t.push({id:`${l}-position`,target:c,property:"position",keyframes:s.map((h,u)=>({time:h,value:[...i[u].bat.grip]}))}),t.push({id:`${l}-rotation`,target:c,property:"quaternion",interpolation:"slerp",keyframes:s.map((h,u)=>({time:h,value:My(i[u].bat.axis)}))})}}function jx(t,e){const n={runs:0,extras:0,wickets:0,legalBall:!0,freeHitNext:!1};t==="running"&&(n.runs=1),t==="four"&&(n.runs=4),t==="six"&&(n.runs=6),(t==="wide"||t==="no-ball")&&(n.extras=1,n.legalBall=!1),t==="no-ball"&&(n.freeHitNext=Ne[e].freeHitAfterNoBall);const i={catch:"caught",bowled:"bowled",lbw:"lbw",stumping:"stumped","run-out":"run-out"}[t];return i&&(n.wickets=1,n.dismissal=i),n}function Cy(t,e={}){return _y(t,e)}function _y(t,e,n){const s=ge(Wn,e.action??"bowling","cricketAction.action"),i=n?n.delivery.legality==="no-ball":s==="no-ball",r=n?n.delivery.legality==="wide":s==="wide",o=n?n.delivery.style==="spin":s==="spin";ge(Ne,t.format,"cricketAction.format");const a=n?.result??jx(s,t.format),l=e.duration??6e3;if(!Number.isFinite(l)||l<4e3||l>6e4)throw new Error("cricketAction: duration must be between 4000 and 60000 ms");const c=t.scene.id;for(const P of["ball","bat","non-striker-bat","lbw-guide","striker-bail-0","striker-bail-1","bowler-bail-0","bowler-bail-1"])if(!t.scene.objects.some(C=>C.id===P))throw new Error(`cricketAction: required equipment '${P}' is missing`);const h=Object.fromEntries(["batter","non-striker","bowler","keeper","fielder","umpire"].map(P=>[P,dh(t.scene,P)]));for(const P of["slip","point","cover","mid-off","mid-on","square-leg","fine-leg","third-man","square-umpire"])t.scene.objects.some(C=>C.id===P&&C.kind==="character")&&(h[P]=dh(t.scene,P));const u=P=>h[P].who.height,d=P=>vy(h[P]),f=P=>Math.round(P*6e3/l*1e9)/1e9,p=P=>P*l/6e3,g=["batting","defend","running","four","six","catch","fielding","throw","run-out"].includes(s),m=["bowling","spin","no-ball","stumping"].includes(s),w=["catch","fielding","throw","run-out","batting","running"].includes(s),v=s==="running"||s==="run-out",k=new Map,b=[d("bowler").position[0],0,i?-8.25:-9.55],T=s==="fielding"?[10.5,0,2]:[9,0,-1],$=d("fielder").position,M=(P,C)=>{let z=k.get(P);z||(z=new Map,k.set(P,z));const K=z.get(C);if(K)return K;const N=h[P];let F=d(P);if(P==="bowler"){const D=F.position;if(C<1400){const X=Tt(b,[0,0,-.65]);F=Xo(N,C,0,1400,D,X),F.pose["arm.right.swing"]=45,F.pose["arm.right.elbow"]=80}else F.position=C<=Yt?yn(Tt(b,[0,0,-.65]),b,Ft(_t(C,1400,Yt))):Tt(b,[0,0,.8*Ft(_t(C,Yt,2600))]),F.pose=fh(C,[[1400,{turn:0,"arm.right.swing":285,"arm.right.elbow":8,"arm.left.swing":115,"leg.right.swing":15,"leg.left.knee":45}],[1800,{turn:0,"arm.right.swing":180,"arm.right.elbow":0,"arm.left.swing":80,"leg.right.swing":25,"leg.right.knee":0,"leg.left.swing":-25,"leg.left.knee":60}],[Yt,{turn:0,lean:8,"arm.right.swing":155,"arm.right.elbow":0,"arm.left.swing":45,"leg.right.swing":25,"leg.right.knee":0,"leg.left.swing":-25,"leg.left.knee":60}],[2250,{turn:0,lean:26,bend:12,"arm.right.swing":40,"arm.right.elbow":0,"arm.left.swing":-35,"leg.left.swing":-35,"leg.left.knee":55}],[3e3,{turn:0,"head.turn":10}],[6e3,{turn:0,"head.turn":10}]]);o&&(F.pose={...F.pose,"arm.right.spread":18,"head.tilt":-5});for(const[X,B]of Object.entries(C<Yt?St.hold:St.open))F.pose[`hand.right.${X}`]=B}else if(P==="batter"||P==="non-striker"){const D=u(P);if(s==="lbw"&&P==="batter"&&(F.position[0]=0),s==="stumping"&&P==="batter"&&(F.position[2]-=1.1*Ft(_t(C,2150,2800))),v&&C>3050){const X=M(P,3050),B=P==="batter"?[1,0,-9.5]:[-1,0,9.5];F=Xo(N,C,3050,s==="run-out"?6e3:kh,X.position,B,X.pose.turn);const et=Wi(N,F,"right");F.bat={grip:et,axis:Jt([.7,-.35,.5]),scale:D/1.78}}else{F.pose={...F.pose,...P==="batter"?ky():{turn:.15,"leg.left.knee":8,"leg.right.knee":8}};let B=[0,-1,P==="batter"?.05:.12],Z=Tt(F.position,[D*.15,D*.44,D*.04]);if(P==="non-striker"&&(Z=Tt(F.position,[D*.08,D*.44,D*.17])),P==="batter"){const et=Ft(_t(C,2100,2600))*(1-Ft(_t(C,2600,Et))),R=Ft(_t(C,2600,Et))*(1-Ft(_t(C,Et,3800))),U=Ft(_t(C,Et,3250))*(1-Ft(_t(C,3250,4e3)));if(g){Z=Tt(F.position,[D*(.15+.03*et-.02*R-.03*U),D*(.44+.14*et+.07*R+.23*U),D*(.04+.16*et-.12*R-.06*U)]),B=Jt([.15*et+.25*U,-1+1.85*et+1.6*U,.05+.55*et-.4*R-.8*U]),F.pose.turn=1+.12*R+.3*U,F.pose.lean=3+4*R;const nt=12+4*R;F.pose["leg.left.spread"]=nt,F.pose["leg.right.spread"]=nt,s==="defend"&&(B=[0,-1,-.08],Z=Tt(F.position,[D*.1,D*.5,-D*.12]))}else if(["stumping","bowled","lbw"].includes(s)){const nt=Ft(_t(C,2100,2700))*(1-Ft(_t(C,4e3,4500)));B=Jt([.15*nt,-1+1.85*nt,.05+.55*nt]),Z=Tt(F.position,[D*(.15+.03*nt),D*(.44+.14*nt),D*(.04+.16*nt)])}}F=Cx(N,F,Z,B)}}else if(P==="keeper"){F.pose={...F.pose,turn:_s(F.position,d("bowler").position,2),lean:20,"leg.left.swing":22,"leg.right.swing":22,"leg.left.knee":50,"leg.right.knee":50},r&&(F.position[0]=2.15*Ft(_t(C,2900,3500))),s==="stumping"&&(F.position[2]-=.85*Ft(_t(C,3400,3900)));const D=vh(F,u(P)*.27,u(P)*.44);if(s==="stumping"&&C>=3500){const X=vh({...F,position:d(P).position},u(P)*.27,u(P)*.44),B=[0,jt.stumpHeight,jt.length/2],Z=yn(X,B,Ft(_t(C,3500,3900)));F=un(N,F,"right",Z),F=un(N,F,"left",Tt(Z,[.045,0,0]))}else F=un(N,F,"right",D),F=un(N,F,"left",Tt(D,[.045,0,0]))}else if(P==="fielder"&&w){if(F=Xo(N,C,3050,s==="catch"?3800:3950,$,T),C>=3800){const D={...lt,turn:_s(T,d("batter").position,F.pose.turn),lean:s==="catch"?5:42,bend:s==="catch"?0:18,"leg.left.swing":s==="catch"?0:45,"leg.right.swing":s==="catch"?0:45,"leg.left.knee":s==="catch"?0:85,"leg.right.knee":s==="catch"?0:85,smile:.7};F.pose=Wo(F.pose,D,Ft(_t(C,3800,dn)));const X=vh(F,u(P)*.22,u(P)*(s==="catch"?.73:.2));if(F=un(N,F,"right",X),F=un(N,F,"left",Tt(X,[.035,0,0])),(s==="throw"||s==="run-out")&&C>dn){const B={...lt,turn:_s(T,s==="throw"?d("keeper").position:t.landmarks["bowler-wicket"],F.pose.turn),"arm.right.swing":225,"arm.right.elbow":60,"arm.left.spread":70,"leg.left.swing":15},Z={...B,"arm.right.swing":110,"arm.right.elbow":0,lean:15};F.pose=fh(C,[[dn,F.pose],[4450,B],[Rs,Z],[4900,{...lt,turn:B.turn,"arm.right.swing":25,lean:22}],[6e3,{...lt,turn:B.turn}]])}}}else if(P==="umpire"){let D={...lt};const X=s==="stumping"?4150:s==="run-out"?5150:s==="bowled"||s==="lbw"?3500:s==="catch"?4350:5100;if(s==="no-ball")D={...D,"arm.right.spread":90,"arm.right.elbow":0};else if(s==="wide")D={...D,"arm.right.spread":90,"arm.left.spread":90,"arm.right.elbow":0,"arm.left.elbow":0};else if(s==="six")D={...D,"arm.right.spread":180,"arm.left.spread":180,"arm.right.elbow":0,"arm.left.elbow":0};else if(s==="four")D={...D,"arm.right.spread":90-70*(.5+Math.sin((C-5100)/180)*.5),"arm.right.elbow":12};else if(["catch","bowled","lbw","stumping","run-out"].includes(s)){D={...D,"arm.right.swing":165,"arm.right.elbow":0};for(const[B,Z]of Object.entries(St.point))D[`hand.right.${B}`]=Z}if(n){const B={...lt},Z=[[0,B]];let et=B;if(i||r){const R=i?Yt:3100;et=i?{...B,"arm.right.spread":90,"arm.right.elbow":0}:{...B,"arm.right.spread":90,"arm.left.spread":90,"arm.right.elbow":0,"arm.left.elbow":0},Z.push([R,B],[R+350,et])}if(a.wickets||s==="four"||s==="six"){const R=a.wickets?X:5100;let U=D;if(a.wickets){U={...B,"arm.right.swing":165,"arm.right.elbow":0};for(const[nt,at]of Object.entries(St.point))U[`hand.right.${nt}`]=at}Z.push([R,et],[R+350,U])}F.pose=fh(C,Z)}else F.pose=Wo(F.pose,D,Ft(_t(C,s==="no-ball"?Yt:s==="wide"?3100:X,(s==="no-ball"?Yt:s==="wide"?3100:X)+350)))}return z.set(C,F),F},x=(P,C)=>Wi(h[P],M(P,C),"right"),S=g?_x(M("batter",Et).bat):s==="lbw"?yn(Hs(h.batter,M("batter",Et),"leg.right",1),Hs(h.batter,M("batter",Et),"leg.right",2),.6):[m?jt.wicketWidth/2+.075+.15:0,.45,9.25],E=x("bowler",Yt),I=[r?.85:o?-.35:s==="lbw"?S[0]*.6:0,.075,3.9],A=x("keeper",s==="stumping"?3400:3500),O=x("fielder",zi),H=x("fielder",dn),W=s==="run-out"?"bowler":"striker",j=s==="run-out"?5e3:s==="stumping"?3900:3200,J=[t.boundaryRadius*.8,s==="six"?2.1:.075,-t.boundaryRadius*.6],tt=(P,C,z,K,N,F=0,D=0)=>gh({target:`${c}/ball`,start:C,end:z,from:K,to:N,arc:F,curve:D},P),V=P=>{if(P<=Yt)return x("bowler",P);if(P<=Bi)return tt(P,Yt,Bi,E,I,.15,o?.35:0);const C=r?Tt(A,[0,0,-.6]):S;if(P<=Et)return tt(P,Bi,Et,I,C,.08);if(s==="bowled"){const K=[0,.36,jt.length/2];return P<=j?tt(P,Et,j,S,K):tt(P,j,4100,K,[0,.075,12.5],.2)}if(s==="lbw")return[...S];if(["bowling","spin","no-ball","wide","stumping"].includes(s)){const K=s==="stumping"?3400:3500;if(m&&P<=K){const N=[C[0],A[1],jt.length/2+.2];return P<=3200?tt(P,Et,3200,C,N,.04):tt(P,3200,K,N,A,.04)}return P<=K?tt(P,Et,K,C,A,.04):x("keeper",P)}if(s==="defend")return tt(P,Et,3400,S,Tt(S,[-.5,-S[1]+.075,-.7]),.12);if(s==="four"||s==="six"){if(s==="six")return P<=5e3?tt(P,Et,5e3,S,J,12):tt(P,5e3,5700,J,Tt(J,[2,-2.025,-1.5]));const K=[5,.075,5];return P<=3300?tt(P,Et,3300,S,K,.5):tt(P,3300,5e3,K,J)}if(s==="catch")return P<=zi?tt(P,Et,zi,S,O,5):x("fielder",P);const z=[4,.075,5];if(P<=3300)return tt(P,Et,3300,S,z,.8);if(P<=dn)return tt(P,3300,dn,z,H);if(s==="throw"||s==="run-out"){if(P<=Rs)return x("fielder",P);const K=x("fielder",Rs),N=s==="run-out"?[0,.42,-jt.length/2]:x("keeper",Ko),F=s==="run-out"?j:Ko;return P<=F?tt(P,Rs,F,K,N,1.2):s==="run-out"?tt(P,F,5700,N,[0,.075,-12],.18):x("keeper",P)}return[...H]},L=[],q=(P,C,z,K,N)=>L.push({id:P,time:p(C),kind:z,label:K,caption:N}),G=n?{bowled:"Delivery hits stumps",lbw:"Pad contact",stumping:"Keeper breaks wicket","run-out":"Throw breaks wicket"}[s]??Wn[s].name:Wn[s].name;if(q("setup",0,"setup",G,n?`${n.delivery.style} delivery · ${n.delivery.legality}${n.freeHit?" · free hit":""}. ${Wn[s].summary.replace("A legal delivery","A delivery")}`:Wn[s].summary),q("release",Yt,"release","Ball released",i?"The front foot has landed beyond the popping crease. No-ball.":"The bowler releases the ball; the front foot is behind the popping crease."),q("bounce",Bi,"bounce","Pitch bounce",o?"The curved flight is illustrative. Spin can change the ball’s path after it bounces.":"The delivery bounces on the pitch on its way to the striker."),g?q("contact",Et,"contact","Bat contact","The ball meets the blade. The bat is keyed from the same two hand grips."):s==="lbw"?q("pad-contact",Et,"contact","Pad contact",n?"The ball contacts the pad. The highlighted path is illustrative; the authored decision is resolved separately.":"The highlighted path illustrates a ball that would hit the stumps. This is an authored LBW example."):q("miss",Et,"contact",s==="wide"?"Beyond normal reach":"The batter misses",s==="wide"?"The untouched ball is too far away for a normal stroke. The umpire calls Wide.":"The untouched delivery passes the striker."),s==="catch"&&q("catch",zi,"collect","Catch controlled",n?"The fielder controls the ball before it touches the ground. The authored decision is resolved separately.":"The fielder controls the ball before it touches the ground: caught."),["fielding","throw","run-out","batting","running"].includes(s)&&q("gather",dn,"collect","Ground ball gathered","The ball has touched the ground. Gathering it is fielding, not a catch dismissal."),["bowling","spin","wide","no-ball","stumping"].includes(s)&&q("keeper",s==="stumping"?3400:3500,"collect","Keeper gathers","The keeper controls the ball behind the striker’s wicket."),(s==="throw"||s==="run-out")&&q("throw",Rs,"throw","Throw released","The fielder releases the gathered ball toward the wicket."),s==="throw"&&q("return",Ko,"collect","Return received","The keeper receives and controls the return throw."),s==="stumping"&&q("wicket",j,"wicket",n?"Wicket broken":"Stumped","Holding the ball, the keeper removes a bail. The striker is out of ground and is not attempting a run."),s==="run-out"&&q("wicket",j,"wicket",n?"Wicket broken":"Run out","The direct throw removes a bail before the running batter makes this ground."),s==="bowled"&&q("wicket",j,"wicket",n?"Stumps hit":"Bowled",n?"The delivery hits the wicket and removes a bail. A broken wicket does not by itself decide a dismissal.":"The legal delivery hits the wicket and removes a bail."),(s==="four"||s==="six")&&q("boundary",5e3,"boundary",s==="four"?"Four runs":"Six runs",s==="four"?"The struck ball reaches the boundary after touching the ground: four.":"The struck ball clears the boundary without touching the ground: six."),s==="running"&&q("run",kh,"result","One run completed","Both batters have reached the opposite ground. One run is completed."),q("result",5700,"result","Illustrated result",s==="no-ball"?`One no-ball extra; it does not count in the over.${a.freeHitNext?" The next legitimate delivery is a free hit.":" Test cricket has no automatic free hit."}`:s==="wide"?"One wide extra; the delivery does not count in the over.":s==="lbw"?"LBW is declared for this illustrated legal delivery. A full decision also checks pitching, impact and any bat contact.":`${a.runs} bat runs · ${a.extras} extras · ${a.wickets} wicket${a.wickets===1?"":"s"}.`),n){const P={"no-dismissal":"No dismissal was authored for this play.",dismissal:`The authored ${n.ruling.dismissal} decision is allowed in this delivery context.`,"no-ball":`Not out: ${s==="catch"?"a catch":"this dismissal"} cannot dismiss the striker on a no-ball.`,"free-hit":`Not out: ${s==="catch"?"a catch":"this dismissal"} cannot dismiss the striker on a free hit.`,wide:"Not out: this dismissal is not available from a Wide."},C=L.find(z=>z.id==="result");C.label=a.wickets?"Out":"Not out",C.caption=`${P[n.ruling.reason]} ${a.runs} bat runs · ${a.extras} extras · ${a.wickets} wickets. ${a.legalBall?"Counts as a legal ball.":"Does not count in the over."}${a.freeHitNext?" The next delivery is a free hit; an illegal delivery carries it forward.":n.freeHit?" This legal delivery consumes the free hit.":""}`}L.sort((P,C)=>P.time-C.time);const _=Sy(0,l,e.every,[1400,1800,Yt,2100,2150,2250,Bi,2600,2800,Et,3050,3100,3200,3250,3300,3400,3500,3800,3900,3950,4e3,zi,dn,4350,4450,Rs,4900,5e3,5100,5150,Ko,kh,5700].map(p)),Y=_.map(P=>V(f(P))),st=[];for(const[P,C]of Object.entries(h)){let z=C.object.pose?.turn??0,K=z;const N=_.map((F,D)=>{const X=f(F);let B=P==="fielder"&&w&&X>3050&&X<3250?Xo(C,X,3050,s==="catch"?3800:3950,$,T,K):M(P,X),Z=Y[D];const et=!["batter","non-striker","bowler","keeper"].includes(P);if(et){const U=M("bowler",Math.min(X,Yt)),nt=Tt(U.position,[0,u("bowler")*.8,0]);Z=X<=Yt?nt:X<2100?yn(nt,Z,Ft(_t(X,Yt,2100))):Z}if(v&&(P==="batter"||P==="non-striker")&&X>3050&&(Z=P==="batter"?[1,u(P)*.8,-10.5]:[-1,u(P)*.8,10.5]),P==="bowler"&&X<=Et&&(Z=Tt(M("batter",X).position,[0,u("batter")*.65,0])),et&&(P!=="fielder"||!w||X<=3050)||P==="bowler"&&X>=3e3){const U=_s(B.position,Z,z);z=P==="bowler"&&X<3500?(B.pose.turn??0)+(uh(U,B.pose.turn??0)-(B.pose.turn??0))*Ft(_t(X,3e3,3500)):U,B={...B,pose:{...B.pose,turn:z}}}return P==="fielder"&&w&&(X===3050?K=z:X>3050&&(z=uh(B.pose.turn??0,z),B={...B,pose:{...B.pose,turn:z}})),Ox(C,B,Z)});qx(st,c,C,_,N)}for(const[P,C]of["x","y","z"].entries())st.push({id:`ball-${C}`,target:`${c}/ball`,property:C,keyframes:_.map((z,K)=>({time:z,value:Y[K][P]}))});if(["bowled","stumping","run-out"].includes(s))for(let P=0;P<2;P++){const C=`${W}-bail-${P}`,K=t.scene.objects.find(N=>N.id===C).position;st.push({id:`${C}-fall`,target:`${c}/${C}`,property:"position",keyframes:[{time:0,value:[...K]},{time:p(j),value:[...K]},{time:p(j+180),value:Tt(K,[P?.25:-.25,.22,W==="striker"?.22:-.22]),easing:"ease-out"},{time:p(j+650),value:[K[0]+(P?.4:-.4),.035,K[2]+(W==="striker"?.45:-.45)],easing:"ease-in"}]}),st.push({id:`${C}-spin`,target:`${c}/${C}`,property:"rotateZ",keyframes:[{time:0,value:0},{time:p(j),value:0},{time:p(j+650),value:P?145:-145}]})}if(s==="lbw"){const P=[S[0]*.8,S[1],jt.length/2],C=se(P,S);st.push({id:"lbw-position",target:`${c}/lbw-guide`,property:"position",keyframes:[{time:0,value:[...S]}]},{id:"lbw-rotation",target:`${c}/lbw-guide`,property:"quaternion",interpolation:"slerp",keyframes:[{time:0,value:My(C)}]},{id:"lbw-length",target:`${c}/lbw-guide`,property:"scaleY",keyframes:[{time:0,value:Zs(S,P)}]},{id:"lbw-visible",target:`${c}/lbw-guide`,property:"visible",keyframes:[{time:0,value:0},{time:p(Et)-.001,value:0},{time:p(Et),value:1}]})}return{action:s,duration:l,events:L,result:a,timeline:{id:`${c}-${s}`,formatVersion:2,name:G,config:{duration:l,markers:L.map(P=>({id:P.id,time:P.time,label:P.label}))},captions:{en:Object.fromEntries(L.map(P=>[P.id,P.caption]))},tracks:st}}}function Yx(t={}){const e=wh(t);return{...e,...Cy(e,t)}}function Kx(t,e){if(!Number.isFinite(e))throw new Error("cricketEventAt: time must be finite");let n;for(const s of t){if(s.time>e)break;n=s}return n}const fn=Object.freeze({deliveryStyles:Object.freeze(["pace","spin"]),deliveryLegalities:Object.freeze(["legal","no-ball","wide"]),shots:Object.freeze(["miss","drive","defend"]),finishes:Object.freeze(["none","single","four","six","stumps","pad"]),fielding:Object.freeze(["none","keeper","catch","gather","throw","stumping","run-out"]),dismissals:Object.freeze(["caught","bowled","lbw","stumped","run-out"])});function Ls(t,e,n){if(!t.includes(e))throw new Error(`cricketPlay.${n}: unknown choice '${e}'`);return e}function Xx(t){const{shot:e,finish:n,fielding:s}=t;if(t.delivery.legality==="wide"){if(e!=="miss"||n!=="none"||s!=="keeper")throw new Error("cricketPlay: Wide currently supports only an untouched delivery gathered by the keeper");return"wide"}if(e==="miss"){if(s==="none"&&n==="stumps")return"bowled";if(s==="none"&&n==="pad")return"lbw";if(n==="none"&&s==="stumping")return"stumping";if(n==="none"&&s==="keeper")return t.delivery.style==="spin"?"spin":"bowling"}if(e==="defend"&&n==="none"&&s==="none")return"defend";if(e==="drive"){if(s==="none"&&(n==="four"||n==="six"))return n;if(s==="gather"&&n==="single")return"running";if(n==="none"){if(s==="catch")return"catch";if(s==="gather")return"fielding";if(s==="throw")return"throw";if(s==="run-out")return"run-out"}}throw new Error(`cricketPlay: unsupported motion combination (${e}, ${n}, ${s})`)}function Gx(t){const e=Ls(fn.shots,t.shot??"miss","shot"),n=Ls(fn.finishes,t.finish??"none","finish");let s=e==="miss"?"keeper":"gather";(e==="defend"||n!=="none")&&(s=n==="single"?"gather":"none");const i=Ls(fn.fielding,t.fielding??s,"fielding"),r=t.context?.freeHit??!1;if(typeof r!="boolean")throw new Error("cricketPlay.context.freeHit must be boolean");const o=t.decision?.dismissal??null;return o!==null&&Ls(fn.dismissals,o,"decision.dismissal"),{delivery:{style:Ls(fn.deliveryStyles,t.delivery?.style??"pace","delivery.style"),legality:Ls(fn.deliveryLegalities,t.delivery?.legality??"legal","delivery.legality")},shot:e,finish:n,fielding:i,context:{freeHit:r},decision:{dismissal:o}}}function Ux(t,e){const n=t.decision.dismissal;if(!n)return{dismissal:null,reason:"no-dismissal"};if({catch:"caught",bowled:"bowled",lbw:"lbw",stumping:"stumped","run-out":"run-out"}[e]!==n)throw new Error(`cricketPlay: '${n}' decision does not match '${e}' motion`);if(n!=="run-out"){if(t.context.freeHit)return{dismissal:null,reason:"free-hit"};if(t.delivery.legality==="no-ball")return{dismissal:null,reason:"no-ball"};if(t.delivery.legality==="wide"&&n!=="stumped")return{dismissal:null,reason:"wide"}}return{dismissal:n,reason:"dismissal"}}function Hy(t,e={}){const n=ge(Ne,t.format,"cricketPlay.format"),s=Gx(e);if(s.context.freeHit&&!Ne[n].freeHitAfterNoBall)throw new Error("cricketPlay: Test format does not support free-hit context");const i=Xx(s),r=Ux(s,i),o=s.delivery.legality==="legal",a={runs:s.finish==="single"?1:s.finish==="four"?4:s.finish==="six"?6:0,extras:o?0:1,wickets:r.dismissal?1:0,legalBall:o,freeHitNext:Ne[n].freeHitAfterNoBall&&(s.delivery.legality==="no-ball"||s.context.freeHit&&!o),...r.dismissal?{dismissal:r.dismissal}:{}};return{..._y(t,{action:i,duration:e.duration,every:e.every},{delivery:s.delivery,result:a,ruling:r,freeHit:s.context.freeHit}),play:s,ruling:r}}function Vx(t={}){const e=wh(t);return{...e,...Hy(e,t)}}const Ry=Object.freeze({"no-ball-stumps":Object.freeze({name:"No-ball + stumps hit",options:Object.freeze({delivery:Object.freeze({legality:"no-ball"}),finish:"stumps",decision:Object.freeze({dismissal:"bowled"})})}),"free-hit-catch":Object.freeze({name:"Free hit + catch",options:Object.freeze({context:Object.freeze({freeHit:!0}),shot:"drive",fielding:"catch",decision:Object.freeze({dismissal:"caught"})})}),"no-ball-four":Object.freeze({name:"No-ball + four",options:Object.freeze({delivery:Object.freeze({legality:"no-ball"}),shot:"drive",finish:"four"})}),"free-hit-run-out":Object.freeze({name:"Free hit + run-out",options:Object.freeze({context:Object.freeze({freeHit:!0}),shot:"drive",fielding:"run-out",decision:Object.freeze({dismissal:"run-out"})})}),"free-hit-wide":Object.freeze({name:"Free hit + Wide",options:Object.freeze({context:Object.freeze({freeHit:!0}),delivery:Object.freeze({legality:"wide"})})})}),Jx={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 Ly(t,e={}){const n={};for(const s of Object.keys(Kt))n[s]={summary:`Walks to \`to\` in the ${s} gait.`,needs:["to"]};for(const s of Object.keys(ae))n[s]={summary:`Moves into the ${s} pose and holds it (\`for\` ms).`};for(const s of Object.keys(rn))n[s]={summary:`The ${s} gag (${_i(s)} ms).`};for(const[s,i]of Object.entries(Hi))n[s]={...i};return{sports:{cricket:{actions:{...Wn},formats:{...Ne},casts:{...ch},fieldingPositions:{...Cs},markingProfiles:{...jo},cameras:{...zo},decisionCameras:Di,playComponents:fn,playExamples:Ry}},...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(Jx),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:Io,stickFigure:{poseFields:Uu,props:Vu,handFields:Ju,poses:Object.keys(ae),expressions:Object.keys(vt),gags:Object.fromEntries(Object.keys(rn).map(s=>[s,_i(s)])),gaits:Object.keys(Kt),actingStyles:Object.keys(Ln),beatFields:xo,actions:n,dances:Object.fromEntries(Object.entries(Je).map(([s,i])=>[s,Object.keys(i.moves)])),flips:Object.fromEntries(Object.entries(Mi).map(([s,i])=>[s,i.label])),handShapes:Object.keys(St),mudras:Object.keys($r)},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 world metres: gaits, face (shortest turn), spin (signed turns and duration), dance (native style, bpm, beats), 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 / .driving / .cycling / .wheeling (a wheelchair)","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:Fo,commonControls:Object.fromEntries(Object.entries(As).map(([s,i])=>[s,`${i.description}${i.unit?` (${i.unit})`:""}`])),commonActions:Object.fromEntries(Object.entries(ah).map(([s,i])=>[s,i.summary])),presets:Object.fromEntries(Object.entries(Os).map(([s,i])=>{const r=i();return[s,{family:r.family,summary:r.summary,actions:Object.fromEntries(Object.entries(r.actions).map(([o,a])=>[o,{summary:a.summary,...a.needs?{needs:a.needs}:{}}])),controls:Object.keys(r.rig.controls),anchors:Object.keys(r.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:{figureStyles:["fluid","stick","organic"],body:{"body.torso · body.arm · body.leg · body.neck":"Organic half-width profiles: [{ at: 0..1, width: fractionOfHeight }], increasing from 0 to 1; independent of ink width.","body.fill · body.outline · body.shading":"Shared skin fill, outline { color, width }, cel material { mode: cel | none, light: [x,y], shadow, opacity, highlight }.","softCartoonCharacter(name, options?)":"Original youngMan / youngWoman / childBoy / childGirl story presets. Children have larger head proportions, shorter limbs and rounded torsos; every face, hair, build, hand, clothing and material option can be overridden.","face.projection":"Organic default volume follows the head axes, keeps both eyes in three-quarter views and projects a small nose above the mouth; opaque hair covers features. cartoon keeps the classic face slide.","outfitPreset(category, overrides?)":"Fresh JSON Everyday / Formal / Casual wardrobe defaults for every actor; top: tshirt | shirt | blouse | dress, trouserStyle: plain | jeans | cargo, colours, sleeves, bottoms, collar and tie are editable.",leafOutfit:"Organic-only JSON garment { top?, color?, accent?, length? }; curved leaves follow torso/thighs at native part depths. Everyday basicOutfit also follows organic contours."},poses:Object.keys(be),dances:Object.keys(En),expressions:Object.keys(gl),faceStyles:["simple","anime"],faceShapes:["round","angular"],gags:Object.keys(Zr),builds:Object.keys(Hr),hair:Object.keys(Pl),hairColors:{...Te},facialHair:Object.keys(Hl),glasses:Object.keys(Ll),hats:Object.keys(Ur),feet:[...Gd],cast:Object.keys(xc),heldItems:Object.fromEntries(Object.entries(Dl).map(([s,i])=>[s,i.hands])),handMeetings:Object.keys(Ci)},codePanel:{languages:ko,removeStyles:bo,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:bc},surfaces:{code:$i,board:He,chart:Hn,prop:Ps},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: ${Ts.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 yt=t=>t.map(e=>`\`${e}\``).join(", "),Fy=t=>Object.entries(t).map(([e,n])=>`| \`${e}\` | ${n.unit??n.kind??""} | ${n.description} |`).join(`
|
|
63
|
+
`);function Zx(t,e={}){const n=Ly(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: ${yt(n.easings.named)}.`,"",...Object.entries(n.easings.parametric).map(([r,o])=>`- ${r}: \`${o}\``),"","## Track kinds","",...Object.entries(n.trackKinds).map(([r,o])=>`- **${r}**: ${o}`),"","## 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(([r,o])=>`| \`${r}\` | ${o.unit??o.kind??""} | ${o.description} | ${o.types.length===7?"all":o.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`).","","Style proportions: `headSize` is a fraction of height; `armLength` multiplies both upper arm and forearm lengths (default 1, positive finite). Hands, shoulders, torso and legs retain their sizes.","","### Pose fields","","| Field | Unit | What it does |","|---|---|---|",Fy(s.poseFields),"","### Other props","","| Prop | Unit | What it does |","|---|---|---|",Fy(s.props),"",`With \`style.hands\`, each hand has \`hand.left.<field>\` / \`hand.right.<field>\` props: ${yt(Object.keys(s.handFields))}.`,"",`**Poses** (a beat's \`do\`, or a pose key): ${yt(s.poses)}.`,"",`**Expressions** (a beat's \`mood\`): ${yt(s.expressions)}.`,"",`**Gags** (ms): ${Object.entries(s.gags).map(([r,o])=>`\`${r}\` (${o})`).join(", ")}.`,"",`**Gaits**: ${yt(s.gaits)}. **Acting styles** (\`style\`): ${yt(s.actingStyles)}.`,"","### Beat scripts","",`\`scriptTracks(target, beats, { from, ground, height, facing, style })\`. A beat has these fields only: ${yt(s.beatFields)}. Times are ms; \`to\` and \`target\` are scene px; \`onto\` is a floor's scene y.`,"","`characterScript(target, who, beats, options)` compiles the same beats for a v2 `character()` on a `characterTarget` (every option but `height`; the same result, its key poses on the human body; the walk phase keyed to that character's stride, and `walk` / `walking` / `gait` tracks that step the gait as the target draws). Add `hairFollowTracks(target, tracks, who)` after it so hanging hair swings.","","| `do` | Needs | What happens |","|---|---|---|",...Object.entries(s.actions).map(([r,o])=>`| \`${r}\` | ${(o.needs??[]).map(a=>`\`${a}\``).join(", ")} | ${o.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(([r,o])=>`\`${r}\` (${o.join(", ")})`).join("; ")}.`,"",`**Flips**: ${Object.entries(s.flips).map(([r,o])=>`\`${r}\` (${o})`).join(", ")}.`,"",`**Hand shapes**: ${yt(s.handShapes)}. **Mudras**: ${yt(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(([r,o])=>`- \`${r}\`: ${o}`),"",...Object.keys(n.custom.actions).length||Object.keys(n.custom.gaits).length?["**This cast’s own:**","",...Object.entries(n.custom.actions).map(([r,o])=>`- \`${r}\`${o.needs?.length?` (needs ${o.needs.map(a=>`\`${a}\``).join(", ")})`:""}: ${o.summary}`),...Object.entries(n.custom.gaits).map(([r,o])=>`- \`${r}\` (gait): ${o}`),""]:[],"## 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(([r,o])=>`- \`${r}\`: ${o}`),"",`Prop beat fields: ${yt(n.props.beatFields)}. Every prop has the controls ${Object.keys(n.props.commonControls).map(r=>`\`${r}\``).join(", ")} and the actions ${Object.keys(n.props.commonActions).map(r=>`\`${r}\``).join(", ")}.`,"","Scenery: `scenery({ x, y, width, height, kind: sky | room, hour, clouds, wind, rain, snow, horizon: hills | city | flat })` is a canvas target whose values `hour` (0–24), `clouds`, `rain`, `snow` (0–1) and `wind` (−1..1) are tracks (`set(prop, { at, value, duration })`, `tracks(id)`; `anchor('sun' | 'moon' | 'horizon' | 'ground', time)`); the same `wind` streams hair (`hairFollowTracks(…, { wind })`). `scenePreset('park' | 'street' | 'office' | 'home', { width, height })` lays out scenery and props as data; `buildScene` builds them into targets.","","| Preset | Family | Actions (needs) | Controls | Anchors |","|---|---|---|---|---|",...Object.entries(n.props.presets).map(([r,o])=>`| \`${r}()\` | ${o.family} | ${Object.entries(o.actions).map(([a,l])=>`\`${a}\`${l.needs?.length?` (${l.needs.join(", ")})`:""}`).join(", ")} | ${o.controls.map(a=>`\`${a}\``).join(", ")} | ${o.anchors.join(", ")} |`),"","## Character (v2 human)","",`Poses: ${yt(n.character.poses)}. Expressions: ${yt(n.character.expressions)}. Gags: ${yt(n.character.gags)}.`,`Native dances: ${yt(n.character.dances)}; \`humanDanceFrame(style, beat, base)\` keeps body heading independent; \`humanDanceTracks(target, options)\` bakes JSON pose tracks. \`danceCircleAt(beat, { radius, count, beatsPerTurn, facing, spins })\` gives a formation with planted toes; \`danceCircleTracks(targets, options)\` bakes scene tracks. \`plantDanceFoot(partner, side, worldPoint)\` returns pose AND position; \`meetDandiya(a, b)\` solves both stick tips to one shared world point and reports unreachable contacts.`,"","Appearance options of `character({ … })`, all plain data that turns with the head (see docs/character-appearance.md):","",`- \`build\`: ${yt(n.character.builds)}`,`- \`figure\`: ${yt(n.character.figureStyles)}`,...Object.entries(n.character.body).map(([r,o])=>`- \`${r}\`: ${o}`),`- \`hair\`: ${yt(n.character.hair)} (colours: ${yt(Object.keys(n.character.hairColors))} in \`HAIR_COLORS\`)`,"- Flowing hair: `softSweep`, `flowingBob`, `cascadingWaves`; editable `locks: [{ path, width, follow? }]` with cubic `{ around, up, lift? }` points (around in degrees, dimensions in head radii), `fall: { taper, wave }` and `shine` (0–1). Roots stay attached; `hairFollowTracks` also drives flexible short locks.",`- \`facialHair\`: ${yt(n.character.facialHair)}`,`- \`glasses\`: ${yt(n.character.glasses)}; \`hat\`: ${yt(n.character.hats)}; \`ears: true\`; \`face: { teeth, tongue }\` (shown when the mouth opens); \`feet\`: ${yt(n.character.feet)}`,"- `outfit`: `{ top: tshirt | shirt | blouse | dress, trouserStyle: plain | jeans | cargo, shirt: top colour, trousers: bottom colour, sleeves: short | long | none, bottom: trousers | shorts | skirt, collar, tie: colour, over: apron | labCoat | hoodie | cardigan | overalls | sari, overColor, shoes: boots, shoeColor }`",`- \`castMember(name, height)\`: ${yt(n.character.cast)}`,"- Face marks (pose fields, 0–1): `blush`, `tears`, `sweat`; close-up fields `pupil` (size, 1 usual), `lid` (upper lids lowered, 0–1), `bulge` (eyes out of the head, 0–1); `face: { nose: true, inPupil(ctx, pupil) }`; `drawCharacterHead(ctx, who, pose, { x, y, radius })` draws just the head big",`- Face styles: ${yt(n.character.faceStyles)}; \`face: { style: 'anime', iris: '#4b7fce', lashes: true, ageLines: 0.8 }\` uses coloured eyes and the same expressions, blinks and gaze. \`ANIME_CAST\` contains eight age presets, also available through \`castMember\`.`,`- Face shapes: ${yt(n.character.faceShapes)}; \`face: { shape: 'angular', jawWidth: 0.74, chinWidth: 0.14, eyeScale: 0.8, eyeAspect: 0.65 }\` sets a tapered 3D jaw and narrower anime eyes; \`jawRoundness: 1\` softens the cheek/chin corners (default 0 keeps sharp jaws). \`MANGA_CAST\` contains four original young adult presets; hair styles \`mangaSpikes\` and \`mangaSweep\` remain editable.`,"- Hair in motion (pose fields): `hair.swing` (degrees round the head, + toward its left), `hair.trail` (head radii back), `hair.lift` (head radii up); key them with `hairFollowTracks(target, tracks, who)` after the character's tracks, or `hairFollow` + `hairMotionAt` when posing per frame",`- \`holding\`: ${Object.entries(n.character.heldItems).map(([r,o])=>`\`${r}\` (${o==="both"?"both":o==="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): ${yt(n.character.handMeetings)}; \`embrace(a, b)\` (a hug, \`embraceSpacing\` apart); \`helpUp(helper, sitter, progress)\` (0 on the floor, hand taken; 1 standing; \`helpUpSpacing\` apart)`,"- Everyday cycles like a gait: `humanCyclePose('sweeping' | 'brushing', phase, base)` (0 → 1 is one stroke and back; sweeping with `holding: { right: 'broom' }`)","","## Code panel","",`\`codePanel({ code, language, x, y, fontSize?, lineHeight?, width? })\`: a code listing as a scene object. Languages: ${yt(n.codePanel.languages)}. Remove styles: ${yt(n.codePanel.removeStyles)}.`,"",...Object.entries(n.codePanel.anchors).map(([r,o])=>`- \`${r}\`: ${o}`),"",...Object.values(n.codePanel.edits).map(r=>`- \`${r.split(":")[0]}\`:${r.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(([r,o])=>`- \`${r}\`: ${o}`),"",...Object.entries(n.surfaces).flatMap(([r,o])=>[`### ${r}`,"",...o.create?[`\`${o.create}\``,""]:[],"Anchors:",...Object.entries(o.anchors).map(([a,l])=>`- \`${a}\`: ${l}`),"","Edits:",...Object.entries(o.edits).map(([a,l])=>`- \`${a}\`: ${l}`),""]),"## Cricket stories (`@algorisys/tinyfly/sports`)","","`cricketClip({ format, action, cast })` returns an organic-player scene, JSON tracks, timed events/captions and a declared result. `cricketField`, `cricketPlayer` and `cricketAction` compose separately; `cricketCameraTracks` adds camera tracks. These are authored tutorial plays, not physics or automatic umpiring. See docs/cricket.md.","",`Marking profiles: ${yt(Object.keys(n.sports.cricket.markingProfiles))}; default ICC men, independently of cast. Limited-over ICC profiles draw a wicket-centred capsule; Test/MCC have no restriction-area line. \`cricketFieldingAreaContains(field, point)\` returns true/false/null; \`cricketFieldingPositions\` and \`cricketFieldingOverlay\` provide owned setup markers, not umpiring decisions.`,"","`cricketPlay(field, options)` / `cricketPlayClip(options)` independently author delivery style/legality, shot, finish, fielding, current free-hit context and candidate dismissal. Omitted dismissal means no dismissal. Unsupported motion combinations throw; no-ball/free-hit protection changes result/signals without removing physical catches or wicket breaks. Run-out remains available. Illegal free hits carry forward; legal ones consume context. Test rejects free-hit context. Keep innings/score/strike in the consuming app.","",...Object.entries(n.sports.cricket.playComponents).map(([r,o])=>`Play ${r}: ${yt(o)}`),...Object.entries(n.sports.cricket.playExamples).map(([r,o])=>`- Composed example \`${r}\`: ${o.name}`),"",...Object.entries(n.sports.cricket.actions).map(([r,o])=>`- \`${r}\`: ${o.summary}`),"",`Formats: ${yt(Object.keys(n.sports.cricket.formats))}. Casts: ${yt(Object.keys(n.sports.cricket.casts))}. Cameras: ${yt(Object.keys(n.sports.cricket.cameras))}. Orbit turns 360° around the whole ground. \`cricketCameraTracks(clip, { view, zoom })\` supports 0.25–4× optical magnification (default 1) in every view.`,"",`Stock fielding labels (\`CRICKET_FIELDING_POSITIONS\`): ${Object.entries(n.sports.cricket.fieldingPositions).map(([r,o])=>`\`${r}\`: ${o}`).join(", ")}. Eleven fielders, two on-field batters and two umpires; nine batting teammates wait off-field. Mid-on is closer to the pitch; long-on is its deeper boundary alternative, not an extra stock fielder. For the right-handed striker, +x is off side and -x is on/leg side.`,"","Decision review cameras: front-foot, striker-crease, bowler-crease. cricketCameraFraming returns owned defaults; cricketCameraReview returns a physical event without seeking. Optional cricketDecisionOverlay marks the crease reference. pitch 0–89, distance 0.5–2000, fov 10–100 before zoom, and fixed-view target customize framing. Ball-follow yaw rotates its default offset relative to 75 degrees; pitch/distance apply too. Export all camera tracks, including far for distant framing. These APIs never alter motion or rulings.","","## Camera shots (`cameraTracks(shots, { stage })`)","",...Object.entries(n.cameraShots).map(([r,o])=>`- **${r}**: \`${o}\``),"","## Teaching (`@algorisys/tinyfly/teach`)","",...Object.entries(n.teach).map(([r,o])=>`- \`${r}\`: ${o}`),"","## Command line","",...Object.entries(n.cli).map(([r,o])=>`- \`${r}\`: ${o}`),""].join(`
|
|
64
|
+
`)}function Qx(t,e,n,s={}){const i=s.color??"#555",r=s.size??60;for(const o of e){const a=(n-o.time)/o.length;if(a<=0||a>=1)continue;const l=ne(`${o.kind}:${o.time}:${o.x}`);o.kind==="dust"?Fp(t,{x:o.x,y:o.y},a,{size:r,color:i,seed:l}):o.kind==="exhaust"?n4(t,o,a,r,i,l):o.kind==="skid"?s4(t,o,a,n,i):o.kind==="honk"?i4(t,o,a,r,i):o.kind==="smoke"?t4(t,o,n,r,i):o.kind==="leaves"&&e4(t,o,a,r,s.leafColor??"#5cae5a",i,l)}}function t4(t,e,n,s,i,r){const o=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+o*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 e4(t,e,n,s,i,r,o){const a=e.direction??1,l=e.toY??e.y+s*3;t.save(),t.lineWidth=Math.max(1,s*.02),t.strokeStyle=r,t.fillStyle=i;for(let c=0;c<4;c++){const h=ne(`${o}:${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 n4(t,e,n,s,i,r){const o=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=(ne(`${r}:${a}`)%100/100-.5)*s*.1,h=e.x+o*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 s4(t,e,n,s,i){const r=e.toX??e.x,o=Math.min(1,(s-e.time)/e.length*3),a=e.x+(r-e.x)*o;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 i4(t,e,n,s,i){const r=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 o=s*(.15+.5*(1-(1-n)**2));for(let a=-1;a<=1;a++){const l=a*Math.PI/7,c=e.x+r*Math.cos(l)*o,h=e.y+Math.sin(l)*o;t.beginPath(),t.arc(c,h,s*.12,r>0?-Math.PI/3:Math.PI*2/3,r>0?Math.PI/3:Math.PI*4/3),t.stroke()}t.restore()}function r4(t){const e=new Ht({id:`${t.propId}-ride`,tracks:t.propTracks.filter(h=>h.target===t.propId)}),n=t.every??33,s=[],i=[],r=[],o=[];let a=1;for(let h=t.start;;h=Math.min(t.end,h+n)){const u=_o(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),r.push({time:h,value:Math.abs(f)}),o.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:r},{id:`${l}-facing`,target:l,property:"facing",keyframes:o4(o)}),c}function o4(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 a4(t,e,n){const s=o=>`${o.target}\0${o.property}`,i=new Map(e.map(o=>[s(o),o]));return[...t.map(o=>{const a=i.get(s(o));if(!a)return o;i.delete(s(o));const c=[...(o.keyframes??[]).filter(h=>h.time<n.from||h.time>n.to),...a.keyframes??[]].sort((h,u)=>h.time-u.time);return{...o,keyframes:c}}),...i.values()]}function l4(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,r=s.props,o=s.prop.wheelRadius,a=[],l=[],c=[];let h=r.wheelSpin??0,u;for(let f=t.start;;f=Math.min(t.end,f+n)){const p=_o(t.leader,{state:e.getStateAtTime(f)},t.leaderId),g=p.anchor(t.hitch),m=p.values.turn,w=$s(s.prop,{...r,turn:m},s.propScale).anchors[t.anchor];if(!w)throw new Error(`propTow: ${s.prop.kind} has no anchor "${t.anchor}"`);const v=g.x-w.point.x;if(u!==void 0&&o){const k=Math.sin(m*Math.PI/2);h+=(v-u)*(k||1)/s.propScale/o*(180/Math.PI)}if(u=v,a.push({time:f,value:v-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},...o?[{id:`${d}-wheelSpin`,target:d,property:"wheelSpin",keyframes:c}]:[]]}const Ny=new WeakMap;function c4(t,e){const n=e?.some(Boolean)?e.map(d=>d?1:0).join(""):"";let s=Ny.get(t);s||Ny.set(t,s=new Map);const i=s.get(n);if(i)return i;const r=Fi(t),o={vertices:r.vertices,faces:r.faces.filter((d,f)=>!e?.[f])},a=o.vertices.flatMap(d=>[d[0],d[1],d[2]]),l=o.vertices.map(()=>[0,0,0]),c=[];o.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,w,v]=[f,p[g],p[g+1]],[k,b,T]=[o.vertices[m],o.vertices[w],o.vertices[v]],$=[b[0]-k[0],b[1]-k[1],b[2]-k[2]],M=[T[0]-k[0],T[1]-k[1],T[2]-k[2]],x=[$[1]*M[2]-$[2]*M[1],$[2]*M[0]-$[0]*M[2],$[0]*M[1]-$[1]*M[0]],S=x[0]*d.normal[0]+x[1]*d.normal[1]+x[2]*d.normal[2];c.push(...S>=0?[m,w,v]:[m,v,w])}});const h=l.flatMap(d=>{const f=Math.hypot(...d)||1;return[d[0]/f,d[1]/f,d[2]/f]}),u=lo({positions:a,normals:h,indices:c});return s.size>=16&&s.clear(),s.set(n,u),u}function h4(t,e,n={}){const s=t.ink??n.ink??"#26262b",i=(n.outline??2)*(t.outline??1),r=t.glow&&e.glow>0?u4(t.glow.color,e.glow):void 0;return{color:t.fill??s,creases:Fi(t.shape).creases!==!1,shading:n.shading??"toon",...i>0?{outline:{width:i,color:s}}:{},...r?{emissive:r}:{},...t.seeThrough?{opacity:.45*e.opacity}:e.opacity<1?{opacity:e.opacity}:{}}}function u4(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 d4=lo(Ag(1,.002,28));function f4(t,e,n){const s=t.rig,[i,r]=s.footprint??[s.length*.45,s.length],o=Math.max(0,It(s,e,"lift")),a=Math.max(0,It(s,e,"size"))/(1+o*.8);return{mesh:d4,world:Rt(n,$a([0,.004,0],[0,0,0,1],[i*.55*a||1e-4,1,r*.55*a||1e-4])),material:{color:"#000000",shading:"unlit",opacity:.16*a}}}const g4=new Set(["x","y","z","position","rotateX","rotateY","rotateZ","quaternion","scale","scaleX","scaleY","scaleZ","visible","opacity","color"]),p4=1,m4={kind:"prop",validate(t){const e=t,n=typeof e.prop=="string"&&e.prop in Os?[]:[ft("prop preset",e.prop,Object.keys(Os))];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(r=>r===s?e[i]:0).join(", ")}]`);return n},prepare(t){const e=t;return rh(e.prop,e.options)},resolve({object:t,prepared:e,values:n,world:s,camera:i,lights:r=[],fog:o,toScreen:a}){const l=t,c=e,h={...l.values};for(const[M,x]of n)typeof x=="number"&&!g4.has(M)&&(h[M]=x);h.turn=0,h.tilt=0;const u=Rt(i.view,s),d={toView:M=>ie(u,M),toScreen:M=>a(M)},f=d.toView([0,c.rig.height/2,0]);if(-f[2]<=i.near)return null;if(l.look==="mesh"){const M=vm(c.rig,h),x=M.map(({part:I,local:A})=>({part:I.id,mesh:Fi(I.shape),...Xc(Fi(I.shape),A)})),S=pm(x),E=M.map((I,A)=>({...I,hidden:ym(I.part.id,x[A].mesh,I.local,x[A].key,S)})).filter(({opacity:I})=>I>.01).map(({part:I,matrix:A,glow:O,opacity:H,hidden:W})=>({mesh:c4(I.shape,W),world:Rt(s,A),material:h4(I,{glow:O,opacity:H},{shading:l.shading,ink:l.ink,outline:l.outline})}));return{meshes:l.shadow===!1?E:[f4(c,h,s),...E]}}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),w=r.length===0?void 0:(M,x)=>{const S=ie(s,M),E=[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]],I=Math.hypot(...E)||1;return{light:$g(S,[E[0]/I,E[1]/I,E[2]/I],r),fog:Pg(o,Math.hypot(S[0]-i.position[0],S[1]-i.position[1],S[2]-i.position[2]))}},v=Zc(c.rig,h,d,m,{perspective:!0,near:i.near,slice:p4,light:w}),k={look:l.look,style:l.style,ink:l.ink,paper:l.paper,fog:o?.color},b=Ql(v),T=v.cells??[],$=Math.max(...T.map(M=>-M.depth),-f[2]);return{drawables:[...l.shadow===!1?[]:[{depth:$+c.rig.length,draw:M=>tc(M,v,k)}],...T.map(M=>({depth:-M.depth,draw(x,S){x.lineCap="round",x.lineJoin="round",Og(x,M.parts,b,{...k,time:S.time})}}))]}}},Mh=["do","at","for","to","through","toward","speed","height","open","on","wind"],y4=.25,b4=800/180,w4=220,k4=300,v4=["turn"];function M4(t){const e=No(t),n=Object.keys(t.moves??{});return Object.keys(e).filter(s=>!n.includes(s)&&!v4.includes(s)&&!(e[s].needs??[]).includes("to"))}function Wy(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=M4(e),i=[...n,"face","hold",...s.filter(o=>o!=="hold")],r=[];return t.forEach((o,a)=>{const l=u=>r.push({beat:a,message:u});if(!o||typeof o!="object"||Array.isArray(o))return l(`Each beat must be an object like { do: '${i[0]??"hold"}' }.`);const c=o,h={duration:"for",path:"through",points:"through",position:"to",heading:"toward",direction:"toward"};for(const u of Object.keys(c))Mh.includes(u)||l(ft("beat field",u,Mh,h[u]));if(typeof c.do!="string"||!i.includes(c.do)){const u=c.do==="turn"?"face":void 0;return l(ft(`${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&&!Cn(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(Cn))&&l("`through` is a list of points on the ground, each [x, z] metres.")),c.do==="face"&&!(Cn(c.toward)||typeof c.toward=="number")&&l("`face` needs `toward`: a point [x, z] or a heading in degrees.")}),r}function S4(t,e,n,s){const i=Wy(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(Es),...Object.keys(e.rig.controls)])o[k]=s.values?.[k]??It(e.rig,{},k);let[r,a]=s.position??[0,0],l=s.heading??0;const c=new Map,h=(k,w,T,P="linear")=>{const S=c.get(k)??[];S.push({time:w,value:T,easing:P}),c.set(k,S)},u=(k,w,T)=>h(k,w,T);h("x",0,r),h("z",0,a),h("rotateY",0,l);const d=(k,w)=>{const T=fr(l,w);if(Math.abs(T)<1)return k;const P=Math.max(hx,Math.abs(T)*cx);return u("rotateY",k,l),l+=T,h("rotateY",k+P,l,"ease-in-out"),k+P},f=(k,w,T)=>{const P=Kg([[r,a],...w.through??[w.to]]);if(P.length<2)return T;const S=d(T,bs(P[0].point,P[1].point)),x=P[P.length-1].at,M=w.for??x/(w.speed??k.speed)*1e3,E=Wt("ease-in-out"),I=Math.min(ux,M/4);for(const[J,tt]of Object.entries(k.set??{}))u(J,S,o[J]),h(J,S+1,tt),o[J]=tt;const A=k.flies?w.height??(o.lift>.05?o.lift:2):void 0,O=A!==void 0&&A>.05;for(const[J,tt]of Object.entries(k.hold??{}))u(J,S,o[J]),h(J,S+I,tt,"ease-out"),O||(h(J,S+M-I,tt),h(J,S+M,0,"ease-in")),o[J]=O?tt:0;A!==void 0&&(u("lift",S,o.lift),h("lift",S+Math.min(M*.35,1400),A,"ease-out"),h("lift",S+M,A),o.lift=A);const H={...o};let W=l;for(let J=0;;J=Math.min(x,J+lx)){const tt=S+Gg(E,J/x)*M,{point:V,direction:L}=Xg(P,J);W+=fr(W,bs([0,0],L)),h("x",tt,V[0]),h("z",tt,V[1]),h("rotateY",tt,W);for(const[q,G]of Object.entries(k.perMetre??{}))h(q,tt,H[q]+J*G);for(const[q,G]of Object.entries(k.perSecond??{}))h(q,tt,H[q]+(tt-S)/1e3*G);if(J>=x)break}for(const[J,tt]of Object.entries(k.perMetre??{}))o[J]=H[J]+x*tt;for(const[J,tt]of Object.entries(k.perSecond??{}))o[J]=H[J]+M/1e3*tt;return[r,a]=P[P.length-1].point,l=W,S+M},p=(k,w)=>{const T=Object.fromEntries(Object.entries(k).filter(([S])=>!["at","to","through","toward"].includes(S))),P=dy(t,e,[T],{start:{...o,turn:1},scale:100,style:s.style,exaggeration:s.exaggeration});for(const S of P.tracks){if(px.includes(S.property))continue;const x=S.keyframes??[],M=o[S.property];if(!x.every(E=>E.value===M)){u(S.property,w,M);for(const E of x)E.time>0&&c.get(S.property).push({...E,time:w+E.time});o[S.property]=x[x.length-1].value}}return w+P.duration},g=[];let m=0;for(const k of n){const w=k.at??m;let T=w;const P=e.moves?.[k.do];P?T=f(P,k,w):k.do==="face"?T=d(w,typeof k.toward=="number"?k.toward:bs([r,a],k.toward)):k.do==="hold"?T=w+(k.for??1e3):T=p(k,w),g.push({do:k.do,start:w,end:T}),m=T}const b=`${s.scene}/${t}`;return{tracks:[...c].map(([k,w])=>({id:`${t}-${k}`,target:b,property:k,keyframes:Yg(w)})),duration:m,beats:g,end:{position:[r,a],heading:l,values:{...o}}}}const px=["x","y","turn","facing","tilt"],mx=.35,mh={seated:ye.sit,astride:{...ye.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},driving:{...ye.sit,"arm.left.swing":52,"arm.right.swing":52,"arm.left.spread":8,"arm.right.spread":8,"arm.left.elbow":38,"arm.right.elbow":38,lean:4},wheeling:{...ye.sit,"arm.left.swing":-6,"arm.right.swing":-6,"arm.left.spread":16,"arm.right.spread":16,"arm.left.elbow":28,"arm.right.elbow":28,"leg.left.knee":80,"leg.right.knee":80},cycling:{...ye.sit,lean:22,bend:10,"head.nod":-14,"arm.left.swing":58,"arm.right.swing":58,"arm.left.spread":10,"arm.right.spread":10,"arm.left.elbow":22,"arm.right.elbow":22,"leg.left.spread":6,"leg.right.spread":6}},yx=22,Oy=38;function yh(t,e=mh.cycling){const n=t*Math.PI*2,s=r=>({swing:(e["leg.left.swing"]??40)+yx*Math.cos(n+r),knee:(e["leg.left.knee"]??70)+Oy*(.5+.5*Math.cos(n+r))-Oy*.5,ankle:12*Math.sin(n+r)}),i=s(0),o=s(Math.PI);return{...e,"leg.left.swing":i.swing,"leg.left.knee":i.knee,"leg.left.ankle":i.ankle,"leg.right.swing":o.swing,"leg.right.knee":o.knee,"leg.right.ankle":o.ankle}}function bx(t){const e=t.cadence??1.2,n=Math.max(2,t.samplesPerTurn??8),s=1e3/e/n,i=[];for(let o=t.start,r=0;o<t.end;o+=s,r++)i.push({time:Math.round(o),pose:yh((o-t.start)/1e3*e,t.base),...r>0?{act:!1}:{}});return i.push({time:t.end,pose:yh((t.end-t.start)/1e3*e,t.base),act:!1}),i}const _y=(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 wx(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=gs({...t.character,height:1}),c={...lt,...t.pose??mh.seated},h=Ve(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 b=n.getStateAtTime(m).values.get(e)??new Map,v=(H,W)=>{const j=b.get(H);return typeof j=="number"?j:W},k={...s.values};for(const H of Object.keys(a.controls))k[H]=v(H,s.values?.[H]??It(a,{},H));for(const H of["pitch","roll","squash","lift","lean","size"])k[H]=v(H,s.values?.[H]??It(a,{},H));const w=pm(a,k)[t.anchor];if(!w)throw new Error(`propRide3D: ${t.prop.kind} has no anchor "${t.anchor}" (it has ${Object.keys(a.anchors??{}).join(", ")||"none"})`);const T=v("rotateY",s.heading??0),P=_y(w,T),S=[v("x",i)+P[0],v("y",o)+P[1],v("z",r)+P[2]],x=T+u,M=_y(h,x);let E=[S[0]-M[0],S[1]-M[1],S[2]-M[2]];const I=(H,W)=>{const j=W*W*(3-2*W);return[H[0]+(E[0]-H[0])*j,E[1]*j+mx*Math.sin(Math.PI*W),H[1]+(E[2]-H[1])*j]},A=t.mount?Math.max(1,t.mount.for??450):0,O=t.dismount?Math.max(1,t.dismount.for??450):0;if(t.mount&&m<t.start+A?E=I(t.mount.from,(m-t.start)/A):t.dismount&&m>t.end-O&&(E=I(t.dismount.to,(t.end-m)/O)),f.x.push({time:m,value:E[0]}),f.y.push({time:m,value:E[1]}),f.z.push({time:m,value:E[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]}))}const Cy={ground:"#7fb56a",hills:"#5f9a58",city:"#4b5468",cloud:"#ffffff",sun:"#ffd45c",moon:"#f3f0e0",rain:"#9fc4e8",snow:"#ffffff",wall:"#e9e1cf",floor:"#b08a5e",skirting:"#8a6a44",frame:"#f7f3ea"},zi=[[0,"#0b1530","#1b2a4a"],[4.5,"#141a3e","#2a2f5a"],[6,"#4a3f7a","#f0a070"],[7.5,"#86c2ee","#d8ecf8"],[12,"#5aaef2","#c0e2f8"],[16.5,"#69b0e6","#f5d79a"],[18.5,"#4c3f78","#f08a5a"],[20.5,"#17203f","#2d3660"],[24,"#0b1530","#1b2a4a"]],qi=(t,e,n)=>{const s=r=>[1,3,5].map(a=>parseInt(r.slice(a,a+2),16)),[i,o]=[s(t),s(e)];return`#${i.map((r,a)=>Math.round(r+(o[a]-r)*n).toString(16).padStart(2,"0")).join("")}`},kx=t=>{const e=(t%24+24)%24;return e<5||e>20?0:e<7?(e-5)/2:e>18?(20-e)/2:1};function Hy(t){const e=(t%24+24)%24;for(let n=1;n<zi.length;n++){const[s,i,o]=zi[n-1],[r,a,l]=zi[n];if(e<=r){const c=(e-s)/(r-s);return{top:qi(i,a,c),bottom:qi(o,l,c)}}}return{top:zi[0][1],bottom:zi[0][2]}}const vx=(t,e)=>{const n=((t-e)%24+24)%24;return n<=12?n/12:-1},Mx=9,Sx=55,xx=28;function Ry(t){const{x:e,y:n,width:s,height:i}=t,o=t.kind??"sky",r=t.ground??n+i*.85,a={...Cy,...t.colors},l=t.horizon??"hills",c=t.window!==!1,h=Ye(t.seed??1),u=s*i/1e5,d=Array.from({length:Math.ceil(Mx*u)+2},()=>({u:h.next(),v:h.next(),size:.6+h.next()*.8,puffs:2+Math.floor(h.next()*3)})),f=Array.from({length:Math.ceil(Sx*u)+4},()=>({u:h.next(),v:h.next(),speed:.8+h.next()*.5})),p=Array.from({length:Math.ceil(xx*u)+4},()=>({u:h.next(),v:h.next(),speed:.7+h.next()*.6,sway:h.next()*Math.PI*2,size:1.5+h.next()*2})),g=Array.from({length:Math.ceil(30*u)+10},()=>({u:h.next(),v:h.next()*.6,size:.6+h.next()*1.2})),m=Array.from({length:6},()=>({phase:h.next()*Math.PI*2,amp:.5+h.next()})),b=Array.from({length:24},()=>({h:.35+h.next()*.65,w:.6+h.next()*.8,windows:h.next()>.3})),v={hour:t.hour??12,clouds:t.clouds??.3,wind:t.wind??0,rain:t.rain??0,snow:t.snow??0},k=ws(),w=(E,I)=>k.keys(E)?.length?k.valueAt(E,I):v[E],T=(E,I)=>{const A=vx(E,I),O=A<0?.5:A,H=r-n;return{x:.1*s+.8*s*O,y:A<0?H+i*.2:H-Math.sin(O*Math.PI)*H*.8,up:A>=0}},P=(E,I,A,O,H)=>{const W=I("hour"),{top:j,bottom:J}=Hy(W),tt=E.createLinearGradient(0,O.y,0,O.ground);tt.addColorStop(0,j),tt.addColorStop(1,J),E.fillStyle=tt,E.fillRect(O.x,O.y,O.w,O.ground-O.y);const V=kx(W);if(V<.6){E.fillStyle="#ffffff",E.globalAlpha=(.6-V)/.6*.9;for(const _ of g)E.beginPath(),E.arc(O.x+_.u*O.w,O.y+_.v*(O.ground-O.y),_.size,0,Math.PI*2),E.fill();E.globalAlpha=1}const L=T(W,6),q=T(W,18),G=Math.min(O.w,O.h)*.06;if(L.up&&(E.fillStyle=a.sun,E.beginPath(),E.arc(O.x+L.x/s*O.w,O.y+L.y/i*O.h,G,0,Math.PI*2),E.fill()),q.up){const _=O.x+q.x/s*O.w,z=O.y+q.y/i*O.h;E.fillStyle=a.moon,E.beginPath(),E.arc(_,z,G*.8,0,Math.PI*2),E.fill(),E.fillStyle=j,E.beginPath(),E.arc(_-G*.35,z-G*.15,G*.7,0,Math.PI*2),E.fill()}const C=Math.max(0,Math.min(1,I("clouds"))),Y=Math.max(-1,Math.min(1,I("wind"))),st=Math.round(C*d.length);E.fillStyle=qi("#ffffff",a.cloud==="#ffffff"?"#ffffff":a.cloud,1),E.globalAlpha=.55+.4*V;for(let _=0;_<st;_++){const z=d[_],K=((z.u*O.w+Y*A*.012*(.6+z.size*.5))%(O.w*1.4)+O.w*1.4)%(O.w*1.4)-O.w*.2,N=O.x+K,F=O.y+(.08+z.v*.42)*(O.ground-O.y),D=Math.min(O.w,O.h)*.07*z.size;for(let X=0;X<z.puffs;X++)E.beginPath(),E.ellipse(N+(X-(z.puffs-1)/2)*D*.9,F+X%2*D*.25,D*(X%2?.8:1),D*.62,0,0,Math.PI*2),E.fill()}E.globalAlpha=1;const $=_=>qi(qi(_,"#0b1530",.65),_,V);if(l==="hills"){E.fillStyle=$(a.hills),E.beginPath(),E.moveTo(O.x,O.ground);const _=40;for(let z=0;z<=_;z++){const K=z/_;let N=0;m.forEach((F,D)=>N+=Math.sin(K*Math.PI*(1.5+D*.7)+F.phase)*F.amp),E.lineTo(O.x+K*O.w,O.ground-Math.max(0,N)*O.h*.045-O.h*.03)}E.lineTo(O.x+O.w,O.ground),E.closePath(),E.fill()}else if(l==="city"){E.fillStyle=$(a.city);let _=O.x;const z=O.w/18;for(const K of b){if(_>O.x+O.w)break;const N=z*K.w,F=O.h*.22*K.h;if(E.fillRect(_,O.ground-F,N,F),K.windows&&V<.5){E.fillStyle="#ffd66b",E.globalAlpha=.5-V;for(let D=O.ground-F+6;D<O.ground-8;D+=9)for(let X=_+4;X<_+N-4;X+=8)E.fillRect(X,D,3,4);E.globalAlpha=1,E.fillStyle=$(a.city)}_+=N+z*.15}}E.fillStyle=$(a.ground),E.fillRect(O.x,O.ground,O.w,O.y+O.h-O.ground)},S=(E,I,A,O)=>{const H=Math.max(-1,Math.min(1,I("wind"))),W=Math.max(0,Math.min(1,I("rain"))),j=Math.max(0,Math.min(1,I("snow")));if(W>0){E.strokeStyle=a.rain,E.globalAlpha=.35+.45*W,E.lineWidth=1.2,E.lineCap="round";const J=O.h*.05,tt=H*.45,V=Math.round(W*f.length);E.beginPath();for(let L=0;L<V;L++){const q=f[L],G=((q.v*O.h+A*q.speed*.9)%O.h+O.h)%O.h,C=((q.u*O.w+G*tt)%O.w+O.w)%O.w;E.moveTo(O.x+C,O.y+G),E.lineTo(O.x+C+tt*J,O.y+G+J)}E.stroke(),E.globalAlpha=1}if(j>0){E.fillStyle=a.snow,E.globalAlpha=.85;const J=Math.round(j*p.length);for(let tt=0;tt<J;tt++){const V=p[tt],L=((V.v*O.h+A*V.speed*.08)%O.h+O.h)%O.h,q=Math.sin(A*.002+V.sway)*O.w*.02,G=((V.u*O.w+q+H*L*.3)%O.w+O.w)%O.w;E.beginPath(),E.arc(O.x+G,O.y+L,V.size,0,Math.PI*2),E.fill()}E.globalAlpha=1}},M={kind:"scenery",target:{type:"custom",x:e,y:n,width:s,height:i,props:v,about:{kind:o==="room"?"room":"sky",summary:o==="room"?"A room: a wall, a floor and a window on the sky. Its values are tracks: hour, clouds, wind, rain, snow (seen through the window).":`A sky over ${l==="flat"?"the ground":l}: the sun and moon on their arcs, stars, clouds on the wind, rain and snow. Its values are tracks: hour (0–24), clouds, wind (−1..1), rain, snow (0..1).`,props:Object.fromEntries(Object.keys(v).map(E=>[E,Tx(E)]))},draw(E,I,A){const O=I.props??{},H=j=>Number(O[j]??v[j]??0);E.save();const W={x:0,y:0,w:s,h:i,ground:r-n};if(o==="sky")P(E,H,A,W),S(E,H,A,W);else if(E.fillStyle=a.wall,E.fillRect(0,0,s,W.ground),E.fillStyle=a.floor,E.fillRect(0,W.ground,s,i-W.ground),E.fillStyle=a.skirting,E.fillRect(0,W.ground-i*.012,s,i*.012),c){const j=s*.26,J=W.ground*.5,tt=s*.62,V=W.ground*.14;E.fillStyle=a.frame,E.fillRect(tt-6,V-6,j+12,J+12),E.save(),E.beginPath(),E.rect(tt,V,j,J),E.clip(),P(E,H,A,{x:tt,y:V,w:j,h:J,ground:V+J*.8}),S(E,H,A,{x:tt,y:V,w:j,h:J}),E.restore(),E.strokeStyle=a.frame,E.lineWidth=4,E.beginPath(),E.moveTo(tt+j/2,V),E.lineTo(tt+j/2,V+J),E.moveTo(tt,V+J/2),E.lineTo(tt+j,V+J/2),E.stroke()}E.restore()}},ground:r,anchor(E,I=1/0){const A=w("hour",I);if(E==="sun"||E==="moon"){const O=T(A,E==="sun"?6:18);return{x:e+O.x,y:n+O.y}}if(E==="horizon")return{x:e+s/2,y:r-i*.03};if(E==="ground")return{x:e+s/2,y:r};throw new Error(`scenery: ${ft("place",E,["sun","moon","horizon","ground"])}`)},set(E,I){if(!(E in v))throw new Error(`scenery: ${ft("value",E,Object.keys(v))}`);if(typeof I.value!="number"||!Number.isFinite(I.value))throw new Error("scenery.set needs `value`, a number");return k.tween(E,w(E,I.at),I.value,I,1e3),M},tracks:k.tracks};return M}function Tx(t){switch(t){case"hour":return{description:"The time of day, 0–24: the sky’s colours, the sun and the moon on their arcs, stars at night",unit:"hours",min:0,max:24};case"clouds":return{description:"Cloud cover",unit:"0..1",min:0,max:1};case"wind":return{description:"The wind, blowing left (−) or right (+): clouds drift, rain slants, snow drifts",unit:"-1..1",min:-1,max:1};case"rain":return{description:"How hard it rains",unit:"0..1",min:0,max:1};default:return{description:"How hard it snows",unit:"0..1",min:0,max:1}}}function Ly(t,e){const{width:n,height:s}=e,i=e.ground??s*.85,o=e.scale??s/4.5,r={x:0,y:0,width:n,height:s,ground:i},a=(l,c,h={})=>({preset:l,x:n*c,scale:o,...h});switch(t){case"park":return{scenery:{...r,hour:10.5,clouds:.35,horizon:"hills",...e.scenery},props:[a("tree",.14,{scale:o*1.1}),a("chair",.5,{turn:0}),a("tree",.86,{scale:o*.9})]};case"street":return{scenery:{...r,hour:16,clouds:.25,horizon:"city",colors:{ground:"#8a8f99"},...e.scenery},props:[a("house",.2,{scale:o*.75,turn:.1}),a("car",.5,{turn:1,scale:o*.9}),a("house",.78,{scale:o*.7,turn:.1}),a("tree",.95,{scale:o*.8})]};case"office":return{scenery:{...r,kind:"room",hour:11,clouds:.3,colors:{wall:"#dfe5ec",floor:"#9aa3ad",skirting:"#6c757d"},...e.scenery},props:[a("door",.1,{turn:.15}),a("chair",.46,{turn:0}),a("desk",.58,{turn:0})]};case"home":return{scenery:{...r,kind:"room",hour:20,clouds:.2,...e.scenery},props:[a("door",.08,{turn:.15}),a("chair",.35,{turn:.3}),a("bed",.72,{turn:.25})]};default:throw new Error(ft("scene preset",t,["park","street","office","home"]))}}function Ex(t,e){const n=Ly(t,e),s=Ry(n.scenery),i=n.props.map(o=>ym({x:o.x,y:s.ground,prop:th(o.preset),scale:o.scale,values:{turn:o.turn??0,...o.values}}));return{scenery:s,props:i,ground:s.ground}}function Ax(t){const{timeline:e}=t,n=new kn;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 $x={timeline:lw,to(t,e,n){const s=new wn(n);return s.to(t,e),s},from(t,e,n){const s=new wn(n);return s.from(t,e),s},fromTo(t,e,n,s){const i=new wn(s);return i.fromTo(t,e,n),i},set(t,e,n){const s=new wn(n);return s.set(t,e),s}};function Fy(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 Px(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 Ny(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 Wy(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=Ny(o,e,n,i,!0),o=Ny(o,e,n,i,!1);return o}function Ix(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=Fy(t,r,a),c=l?.getContext("2d");if(!l||!c)return;c.imageSmoothingEnabled=!0,c.drawImage(t.canvas,0,0,r,a);const h=Px(c.getImageData(0,0,r,a).data,e.threshold??.55),u=(e.radius??Math.max(s,i)*.02)/o,d=Wy(h,r,a,u),f=Wy(h,r,a,u*3),p=e.halo??.6,g=c.createImageData(r,a);for(let m=0;m<r*a;m++){for(let b=0;b<3;b++)g.data[m*4+b]=Math.round(Math.min(1,d[m*3+b]+f[m*3+b]*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 Ox(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=Cx(e,s,i,o,r);a?(t.globalCompositeOperation="lighter",bh(t,c,n.color)):Hx(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,_x(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 _x(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 Cx(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=O0(o),a=_0(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 bh(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 Hx(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 b of[...g.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 u=Math.floor(a)-1,d=Math.floor(l)-1,f=s?Fy(t,Math.ceil(c)+1-u,Math.ceil(h)+1-d):null,p=f?.getContext("2d");if(!f||!p){bh(t,e,n);return}p.translate(-u,-d),p.globalCompositeOperation="lighter",bh(p,r,n),t.save(),t.setTransform(1,0,0,1,0,0),t.globalAlpha=1,t.drawImage(f,u,d),t.restore()}const Rx=oe.to,Lx=oe.from,Fx=oe.fromTo,Nx=oe.set,Wx=oe.timeline,Dx=oe.ticker,Bx=oe.splitText,zx=oe.context,qx=oe.matchMedia,jx=oe.quickTo,Yx=oe.imageSequence,Kx=oe.pageTransition;R2(),y.ACTING_STYLES=Rn,y.AIRCRAFT_ACTING=Vc,y.ANIMAL_GAITS=Ps,y.ANIME_CAST=yp,y.BEAT_FIELDS=Sr,y.BEAT_MOMENTS=xs,y.BED_ACTING=Nm,y.BIRD_ACTING=sy,y.BOARD_MARKS=pc,y.BOARD_THEMES=$i,y.CANVAS_PROPERTIES=Pr,y.CHAIR_ACTING=Hm,y.CHARACTER_BEAT_3D_FIELDS=ic,y.CHARACTER_CAST=wc,y.CHARACTER_GAIT_SPEEDS=Zg,y.CHART_KINDS=yc,y.CHART_SURFACE=Cn,y.CHART_THEMES=Pi,y.CODE_LANGUAGES=wr,y.CODE_PANEL_EDITS=fc,y.CODE_SURFACE=Ai,y.CODE_THEME=op,y.CRICKET_ACTIONS=Nn,y.CRICKET_CAMERA_ANGLES=fy,y.CRICKET_CASTS=ih,y.CRICKET_FIELDING_POSITIONS=Os,y.CRICKET_FORMATS=Ne,y.CRICKET_MARKING_PROFILES=Wr,y.CRICKET_PITCH=jt,y.CRICKET_PLAY_COMPONENTS=un,y.CRICKET_PLAY_EXAMPLES=Ey,y.CRICKET_VIEWS=ah,y.Clock=zy,y.CompatTimeline=wn,y.CustomBounce=Su,y.CustomEase=Mu,y.CustomWiggle=xu,y.DANCE_STYLES=Ue,y.DEFAULT_BAKE_INTERVAL_MS=aa,y.DEFAULT_INERTIA_FRICTION=Ur,y.DEFAULT_LABELS=Cu,y.DEFAULT_SPRING=ce,y.DEFAULT_TRANSITION=F2,y.DESK_ACTING=Lm,y.DOOR_ACTING=Dm,y.Draggable=_a,y.EMBRACE=kr,y.EXPRESSIONS=vt,y.FACIAL_HAIR_STYLES=Pl,y.FINGERS=Vu,y.FLIPS=vi,y.FOOT_SHAPES=Bd,y.FORMAT_VERSION=qr,y.FRAME_ASPECTS=P0,y.GAGS=nn,y.GAITS=Kt,y.GAIT_CYCLE_MS=Oc,y.GLASSES_STYLES=Ol,y.HAIR_COLORS=Te,y.HAIR_STILL=cs,y.HAIR_STYLES=xl,y.HAND_MEETINGS=Oi,y.HAND_REST=Ot,y.HAND_SHAPES=St,y.HAT_STYLES=Uo,y.HELD_ITEMS=Rl,y.HELP_UP=Hn,y.HORSE_ACTING=u4,y.HORSE_GAITS=a4,y.HOUSE_ACTING=_m,y.HUMAN_ACTING_RIG=xp,y.HUMAN_BUILDS=Ho,y.HUMAN_CYCLES=_l,y.HUMAN_DANCES=Tn,y.HUMAN_EXPRESSIONS=cl,y.HUMAN_GAGS=Zo,y.HUMAN_POSES=ye,y.HUMAN_REST=lt,y.IDENTITY_CAMERA=tp,y.IDENTITY_SIMILARITY=wb,y.INERTIA_MAX_DURATION_MS=xh,y.InertiaTrackPlayer=h0,y.LiveTimeline=Se,y.MANGA_CAST=bp,y.MORPH_SAMPLES=h1,y.MUDRAS=$o,y.ManualClock=By,y.MediaSync=Ka,y.OUTFIT_PRESETS=kc,y.Observer=Q0,y.POSES=ae,y.PROP_BEAT_3D_FIELDS=ph,y.PROP_BEAT_FIELDS=Lr,y.PROP_COMMON_ACTIONS=nh,y.PROP_COMMON_CONTROLS=Es,y.PROP_PRESETS=Is,y.PROP_SURFACE=$s,y.QUADRUPED_ACTING=Zc,y.REMOVE_STYLES=yr,y.REST_POSE=ut,y.RIDING_POSES=mh,y.SAMPLE_STEP=tn,y.SCENERY_COLORS=Cy,y.SCRIPT_ACTIONS=Ci,y.SOFT_CARTOON_CAST=Ii,y.SPRING_MAX_DURATION_MS=Gr,y.SPRING_PRESETS=Ui,y.SPRING_STEP_MS=Dn,y.STICK_ACTING_RIG=Sp,y.ScrollAnimator=pu,y.ScrollDriver=ei,y.ScrollMarkers=mu,y.ScrollPin=uu,y.SmoothScroll=qa,y.SpringSampler=Ns,y.SpringTrackPlayer=c0,y.Stage=X0,y.TREE_ACTING=Im,y.Timeline=Ht,y.TinyflyPlayer=go,y.TinyflySequencer=Bu,y.TrackPlayer=fn,y.VEHICLE_ACTING=wm,y.VISEMES=Qe,y.ValueResolver=N1,y.VisibilityDriver=hu,y.WHEELCHAIR_ACTING=qm,y.WHITEBOARD_SURFACE=He,y.actCharacterTracks=Ap,y.actKeyframes=Mr,y.actTracks=Ep,y.actionNames=Ac,y.airplane=Km,y.anchorError=en,y.animalStrideLength=Rr,y.animatableProperties=tm,y.applyBloom=Ix,y.applyCamera=MM,y.applyGroove=Cd,y.applySimilarity=wa,y.aspectOf=ba,y.assertBeats=Ic,y.audioEnvelope=ub,y.backOut=Hh,y.bakeDanceTracks=Qk,y.bakeEasing=ha,y.bakeInertiaTrack=ca,y.bakeSpringTrack=la,y.ballFlightPoint=lh,y.ballFlightTracks=E4,y.basicOutfit=Zf,y.beatAt=Vk,y.beatAtTime=Ks,y.beatLength=Ys,y.beatPeriod=lb,y.beatPulse=hb,y.beatTime=no,y.beatsBetween=V1,y.bed=Fm,y.bike=Am,y.bindChoiceHotspots=Fu,y.bird=ln,y.blendPose=es,y.bodyProfileWidth=Kd,y.boilFrame=Ga,y.bounceOut=Ch,y.boxMesh=Fg,y.brushingPose=qf,y.bubblePath=Ib,y.bubblePop=Ob,y.buildScene=Ex,y.bus=Sm,y.cameraFromValues=vM,y.cameraPoint=SM,y.cameraTracks=tb,y.capabilities=Ay,y.capabilitiesMarkdown=q4,y.car=vm,y.cart=Tm,y.castMember=rS,y.cat=Jm,y.chair=Cm,y.changingWindows=ks,y.character=gs,y.characterAt=Ov,y.characterHandPose=ig,y.characterJoints=fe,y.characterJointsInView=Av,y.characterLookAtTracks=wM,y.characterObjects=aM,y.characterPartsInView=ag,y.characterPoseOf=nr,y.characterPoseTracks=_v,y.characterScript=k3,y.characterScript3D=bM,y.characterStrideLength=Jp,y.characterTarget=Iv,y.charactersFor=u0,y.chart=eS,y.checkBeats=Hi,y.checkCast=$c,y.checkCharacterBeats3D=Qg,y.checkPropBeats=uy,y.checkPropBeats3D=Iy,y.checkSurfaceBeats=Gp,y.checkTracks=O3,y.chicken=ry,y.circlePath=AM,y.clamp01=Wa,y.clearMorphCache=w1,y.clearPathCache=o1,y.clipErased=dc,y.closestName=Xs,y.codePanel=NM,y.codeTokens=ap,y.composeSimilarity=vb,y.containerProgressAt=Da,y.context=zx,y.controlValue=It,y.cow=Zm,y.create=k2,y.createControls=Ru,y.createCubicBezier=Oh,y.createLive=Au,y.createPen=ii,y.createRandom=Ye,y.createTrack=eo,y.cricketAction=Sy,y.cricketCameraTracks=T4,y.cricketClip=L4,y.cricketEventAt=F4,y.cricketField=dh,y.cricketFieldingAreaContains=wy,y.cricketFieldingOverlay=_4,y.cricketFieldingPositions=ky,y.cricketPlay=Ty,y.cricketPlayClip=B4,y.cricketPlayer=vy,y.criticalDamping=Yy,y.crow=oy,y.curve=ab,y.customBounce=M0,y.customEase=v0,y.customWiggle=S0,y.cylinderMesh=Ng,y.danceCircleAt=gg,y.danceCircleTracks=Hv,y.danceFrame=Oo,y.danceJoint=In,y.dancePose=Yk,y.danceStance=Io,y.danceTaps=Xk,y.danceTracks=Zk,y.danceTravel=Co,y.danceTravelTrack=Nd,y.dancer=Jk,y.defineAction=WS,y.defineGait=DS,y.describeTarget=Qp,y.deserializeTimeline=Xn,y.deserializeTrack=p0,y.desk=Rm,y.detectTempo=J1,y.dog=Vm,y.door=Wm,y.draggable=Cw,y.drawCartoonHand=So,y.drawCharacter=rg,y.drawCharacterHead=Pv,y.drawCharacterInView=$v,y.drawDustPuff=Ip,y.drawEraser=hc,y.drawHand=uc,y.drawHeldItem=Ll,y.drawImpactStars=LS,y.drawPencil=ep,y.drawProp=X3,y.drawPropEffects=j4,y.drawPropShadow=Ul,y.drawSolvedFaces=xg,y.drawSolvedPart=Jv,y.drawSolvedProp=Xl,y.drawSpeedLines=Pp,y.drawStickFigure=$d,y.drawStickSmear=RS,y.drawTrail=Ox,y.drawnPathTarget=$M,y.dripPath=Pb,y.duck=ly,y.easeIn=$h,y.easeInCubic=Vr,y.easeInOut=Ih,y.easeInOutCubic=Ds,y.easeInOutQuad=Ah,y.easeInQuad=Th,y.easeOut=Ph,y.easeOutCubic=Jr,y.easeOutQuad=Eh,y.editDistance=E0,y.editError=Ei,y.editLog=ws,y.elasticOut=_h,y.ellipsePoints=wo,y.ellipsoidMesh=Wg,y.embrace=hS,y.embraceSpacing=cS,y.envelopeAt=db,y.erasable=_M,y.expandBeats=Tr,y.expandParametricEasings=a0,y.extrudeMesh=Dg,y.flipPose=pg,y.flipTracks=Wv,y.flipTravel=mg,y.formatVersionFor=jr,y.frameRect=fb,y.frameSize=gb,y.from=Lx,y.fromJSON=R1,y.fromTo=Fx,y.gag=Tc,y.gagDuration=_i,y.gaitPose=ed,y.gaitStrideLength=xo,y.getEasingFunction=Wt,y.getInterpolator=js,y.getMotionPathPoint=ua,y.getPathLength=r1,y.getPointAtProgress=Wh,y.goat=Qm,y.gridLinesFor=nu,y.hairFollow=vp,y.hairFollowTracks=xS,y.hairHangs=ff,y.hairMotionAt=MS,y.hairMotionOf=yi,y.hairlineAt=bi,y.handAt=EM,y.handGrip=Qo,y.handJoints=Mo,y.handJointsAt=Qu,y.handPath=Wc,y.handPose=Nt,y.handProp=ui,y.hasKeyframes=vh,y.hashSeed=ne,y.headPoint=Rk,y.heldTime=Mh,y.helicopter=Ym,y.helpUp=dS,y.helpUpSpacing=uS,y.holdingLayers=eg,y.horse=Um,y.horseStrideLength=f4,y.house=Om,y.humanCyclePose=bv,y.humanDanceFrame=gi,y.humanDanceTracks=x5,y.humanFieldLabel=k5,y.humanGag=Bf,y.humanGaitPose=Vo,y.humanGaitStrideLength=Jo,y.humanPlan=ll,y.humanPose=kt,y.imageSequence=Yx,y.inertiaDuration=zn,y.inertiaRest=Bn,y.inertiaValueAt=Ji,y.inertiaVelocityAt=Uy,y.interpolateArray=s0,y.interpolateColor=n0,y.interpolateMotionPath=I1,y.interpolateNumber=ke,y.interpolatePathString=o0,y.interpolateQuaternion=i0,y.interpolateString=ra,y.invertSimilarity=Mb,y.isCubicBezierEasing=Wn,y.isHeld=Fl,y.isInertiaTrack=We,y.isMotionPathPoint=Dy,y.isMotionPathTrack=Yr,y.isParametricEasing=Ls,y.isPathData=jn,y.isSpringTrack=De,y.isTextTrack=Yi,y.isUnderdamped=jy,y.isUnresolved=F1,y.isoDepth=ka,y.isometricBoxFaces=va,y.isometricFaces=Ma,y.jointsInScene=cg,y.jointsToScene=Ad,y.leafOutfit=Gf,y.leafOutfitContours=Cl,y.linear=Zi,y.lipSyncKeyframes=nc,y.lipSyncOver=dr,y.lipSyncTracks=dM,y.lit=tc,y.live=oe,y.lookFields=oc,y.loopBeats=cb,y.loopEase=nb,y.loopNoise=sb,y.loosePartsOf=Gc,y.lyingPose=Gm,y.mapEase=Zs,y.mat4=Db,y.matchMedia=qx,y.maxStaggerDistance=Xr,y.meetDandiya=Cv,y.meetHands=lS,y.meetingSpacing=aS,y.metaballContours=Ab,y.metaballField=R0,y.mirrorHumanPose=Dd,y.mirrorPose=_d,y.mixColors=ec,y.mixHandPoses=ts,y.mixPoses=Bl,y.morphPath=Kh,y.motorbike=$m,y.mount=Nu,y.mountAll=Du,y.narrationMarkers=K1,y.narrationSceneAt=X1,y.naturalRest=Ws,y.nearestBeat=G1,y.nextBeat=U1,y.niceCeiling=gp,y.objectPositionAt=cc,y.organicBodyContours=Gd,y.organicCenterLine=pi,y.outfitPreset=kp,y.owl=cy,y.pageTransition=Kx,y.panelMesh=Bg,y.parametricEasing=Lh,y.parrot=hy,y.parseAnchor=_n,y.parseEdge=Fa,y.parsePath=dn,y.parseTrigger=Na,y.partialPath=Qn,y.pathLength=Ku,y.pedallingKeys=bx,y.pedallingPose=yh,y.penroseStairs=Eb,y.penroseTriangle=Tb,y.persona=b3,y.phaseOf=gn,y.pieceMotion=Ti,y.pigeon=ay,y.pingPong=ya,y.planNarration=Y1,y.plantDanceFoot=dg,y.play=w2,y.playSequence=L2,y.playWhenVisible=Kw,y.playheadCrossings=fa,y.pointAlong=mo,y.pointAtDistance=Qr,y.pointOnHead=xv,y.pointsToPath=I0,y.pose=Dt,y.poseTracks=Wk,y.powSimilarity=Sb,y.projectIsometric=oo,y.propActions=Fr,y.propAnchors3D=pm,y.propAt=_r,y.propControls=Uc,y.propLineWidth=Gl,y.propObjects=ax,y.propPartsInSpace=gm,y.propPreset=th,y.propRide=V4,y.propRide3D=wx,y.propScript=dy,y.propScript3D=gx,y.propShapeMesh=Li,y.propSurface=V3,y.propTarget=ym,y.propTow=Q4,y.propView=um,y.quadruped=rn,y.quat=T1,y.quickPlay=Ax,y.quickTo=jx,y.rabbit=ty,y.randomBetween=pa,y.randomChoice=L1,y.randomSnapped=y0,y.reachCharacter=Ce,y.reachOf=Zp,y.resolveActingStyle=Mc,y.resolveCharacterPoseKeys=zl,y.resolveFacialHair=$f,y.resolveGait=li,y.resolveGlasses=If,y.resolveHair=mf,y.resolveHat=_f,y.resolveHeadLook=Hf,y.resolveHolding=Qf,y.resolveOrganicBody=Yd,y.resolvePoseKeys=Ao,y.resolveSequence=k0,y.resolveStickFrame=tl,y.resolveStickPose=Pd,y.resolveValue=ma,y.ribbon=O0,y.ribbonHeadCap=_0,y.rideFloors=mr,y.rotateAbout=Xe,y.routineBeats=_o,y.rubberLimb=vn,y.safeAreas=pb,y.scalePoints=Cb,y.scenePreset=Ly,y.scenery=Ry,y.scriptActionSummaries=Pc,y.scriptTracks=Ar,y.scrollProgress=Yw,y.scrubOnScroll=Vw,y.scrubPath=IM,y.seatHeight=Pk,y.serializeTimeline=m0,y.serializeTrack=f0,y.set=Nx,y.shade=hr,y.shapeMesh=jg,y.shapeToPathData=so,y.similarity=kb,y.similarityAbout=C0,y.similarityFixedPoint=H0,y.similarityMatrix=xb,y.simplifyKeyframes=l0,y.sittingPose=Jc,y.skeletonInView=Wo,y.sketchPen=yo,y.skyColors=Hy,y.smoothPath=sc,y.smoothToward=cu,y.snapAxis=eu,y.snapConfig=du,y.snapDuration=gu,y.snapProgress=fu,y.softCartoonCharacter=oS,y.solveAt=As,y.solvePlanSpace=ss,y.solveProp=Xc,y.songbird=iy,y.soundsOf=Lg,y.speechDuration=Xp,y.speechLength=Ug,y.spliceTracks=Z4,y.splitText=Bx,y.springDuration=Sh,y.springFollow=Gs,y.springValueAt=qy,y.squashStretch=_b,y.squirrel=ey,y.stagePlanSpace=Ve,y.stageSpots=kM,y.staggerDistance=Kr,y.staggerOffset=Ki,y.staggerOffsets=Xi,y.staggerSpan=Fs,y.stepsDuration=_p,y.stepsEasing=Rh,y.stepsToKeys=Ec,y.stickFigureAt=nl,y.stickFigureJoints=me,y.stickFigureTarget=el,y.stickToHuman=yg,y.strideLength=ad,y.surfaceBox=Mt,y.surfaceScript=m3,y.sweepingPose=zf,y.syncMediaElement=_u,y.talkingMouth=ld,y.taperedLine=bo,y.taperedOutline=zt,y.textAt=d0,y.tf=$x,y.ticker=Dx,y.timeline=Wx,y.to=Rx,y.toJSON=H1,y.toKeyframedTrack=$1,y.toKeyframedTracks=P1,y.torusNoise=ib,y.trackTargets=je,y.tractor=xm,y.trailSamples=yb,y.trainCar=Em,y.tree=Pm,y.triggerDistance=Un,y.truck=Mm,y.tubeMesh=zg,y.unknownName=ft,y.unmount=C2,y.valueAt=pr,y.vec3=Hb,y.vehicle=Fe,y.walkPose=rd,y.wheelchair=zm,y.whiteboard=qM,y.withErased=OM,y.withExpression=Ge,y.wobble=eb,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})}));
|
|
66
|
+
`)}`);const r={};for(const k of[...Object.keys(As),...Object.keys(e.rig.controls)])r[k]=s.values?.[k]??It(e.rig,{},k);let[o,a]=s.position??[0,0],l=s.heading??0;const c=new Map,h=(k,b,T,$="linear")=>{const M=c.get(k)??[];M.push({time:b,value:T,easing:$}),c.set(k,M)},u=(k,b,T)=>h(k,b,T);h("x",0,o),h("z",0,a),h("rotateY",0,l);const d=(k,b)=>{const T=go(l,b);if(Math.abs(T)<1)return k;const $=Math.max(w4,Math.abs(T)*b4);return u("rotateY",k,l),l+=T,h("rotateY",k+$,l,"ease-in-out"),k+$},f=(k,b,T)=>{const $=Qg([[o,a],...b.through??[b.to]]);if($.length<2)return T;const M=d(T,ws($[0].point,$[1].point)),x=$[$.length-1].at,S=b.for??x/(b.speed??k.speed)*1e3,E=Wt("ease-in-out"),I=Math.min(k4,S/4);for(const[J,tt]of Object.entries(k.set??{}))u(J,M,r[J]),h(J,M+1,tt),r[J]=tt;const A=k.flies?b.height??(r.lift>.05?r.lift:2):void 0,O=A!==void 0&&A>.05;for(const[J,tt]of Object.entries(k.hold??{}))u(J,M,r[J]),h(J,M+I,tt,"ease-out"),O||(h(J,M+S-I,tt),h(J,M+S,0,"ease-in")),r[J]=O?tt:0;A!==void 0&&(u("lift",M,r.lift),h("lift",M+Math.min(S*.35,1400),A,"ease-out"),h("lift",M+S,A),r.lift=A);const H={...r};let W=l;for(let J=0;;J=Math.min(x,J+y4)){const tt=M+ep(E,J/x)*S,{point:V,direction:L}=tp($,J);W+=go(W,ws([0,0],L)),h("x",tt,V[0]),h("z",tt,V[1]),h("rotateY",tt,W);for(const[q,G]of Object.entries(k.perMetre??{}))h(q,tt,H[q]+J*G);for(const[q,G]of Object.entries(k.perSecond??{}))h(q,tt,H[q]+(tt-M)/1e3*G);if(J>=x)break}for(const[J,tt]of Object.entries(k.perMetre??{}))r[J]=H[J]+x*tt;for(const[J,tt]of Object.entries(k.perSecond??{}))r[J]=H[J]+S/1e3*tt;return[o,a]=$[$.length-1].point,l=W,M+S},p=(k,b)=>{const T=Object.fromEntries(Object.entries(k).filter(([M])=>!["at","to","through","toward"].includes(M))),$=wy(t,e,[T],{start:{...r,turn:1},scale:100,style:s.style,exaggeration:s.exaggeration});for(const M of $.tracks){if(x4.includes(M.property))continue;const x=M.keyframes??[],S=r[M.property];if(!x.every(E=>E.value===S)){u(M.property,b,S);for(const E of x)E.time>0&&c.get(M.property).push({...E,time:b+E.time});r[M.property]=x[x.length-1].value}}return b+$.duration},g=[];let m=0;for(const k of n){const b=k.at??m;let T=b;const $=e.moves?.[k.do];$?T=f($,k,b):k.do==="face"?T=d(b,typeof k.toward=="number"?k.toward:ws([o,a],k.toward)):k.do==="hold"?T=b+(k.for??1e3):T=p(k,b),g.push({do:k.do,start:b,end:T}),m=T}const w=`${s.scene}/${t}`;return{tracks:[...c].map(([k,b])=>({id:`${t}-${k}`,target:w,property:k,keyframes:Zg(b)})),duration:m,beats:g,end:{position:[o,a],heading:l,values:{...r}}}}const x4=["x","y","turn","facing","tilt"],T4=.35,Sh={seated:be.sit,astride:{...be.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},driving:{...be.sit,"arm.left.swing":52,"arm.right.swing":52,"arm.left.spread":8,"arm.right.spread":8,"arm.left.elbow":38,"arm.right.elbow":38,lean:4},wheeling:{...be.sit,"arm.left.swing":-6,"arm.right.swing":-6,"arm.left.spread":16,"arm.right.spread":16,"arm.left.elbow":28,"arm.right.elbow":28,"leg.left.knee":80,"leg.right.knee":80},cycling:{...be.sit,lean:22,bend:10,"head.nod":-14,"arm.left.swing":58,"arm.right.swing":58,"arm.left.spread":10,"arm.right.spread":10,"arm.left.elbow":22,"arm.right.elbow":22,"leg.left.spread":6,"leg.right.spread":6}},E4=22,Dy=38;function xh(t,e=Sh.cycling){const n=t*Math.PI*2,s=o=>({swing:(e["leg.left.swing"]??40)+E4*Math.cos(n+o),knee:(e["leg.left.knee"]??70)+Dy*(.5+.5*Math.cos(n+o))-Dy*.5,ankle:12*Math.sin(n+o)}),i=s(0),r=s(Math.PI);return{...e,"leg.left.swing":i.swing,"leg.left.knee":i.knee,"leg.left.ankle":i.ankle,"leg.right.swing":r.swing,"leg.right.knee":r.knee,"leg.right.ankle":r.ankle}}function A4(t){const e=t.cadence??1.2,n=Math.max(2,t.samplesPerTurn??8),s=1e3/e/n,i=[];for(let r=t.start,o=0;r<t.end;r+=s,o++)i.push({time:Math.round(r),pose:xh((r-t.start)/1e3*e,t.base),...o>0?{act:!1}:{}});return i.push({time:t.end,pose:xh((t.end-t.start)/1e3*e,t.base),act:!1}),i}const By=(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 $4(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,r,o]=s.position??[0,0,0],a=t.prop.rig,l=ps({...t.character,height:1}),c={...lt,...t.pose??Sh.seated},h=Ze(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 w=n.getStateAtTime(m).values.get(e)??new Map,v=(H,W)=>{const j=w.get(H);return typeof j=="number"?j:W},k={...s.values};for(const H of Object.keys(a.controls))k[H]=v(H,s.values?.[H]??It(a,{},H));for(const H of["pitch","roll","squash","lift","lean","size"])k[H]=v(H,s.values?.[H]??It(a,{},H));const b=Mm(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 T=v("rotateY",s.heading??0),$=By(b,T),M=[v("x",i)+$[0],v("y",r)+$[1],v("z",o)+$[2]],x=T+u,S=By(h,x);let E=[M[0]-S[0],M[1]-S[1],M[2]-S[2]];const I=(H,W)=>{const j=W*W*(3-2*W);return[H[0]+(E[0]-H[0])*j,E[1]*j+T4*Math.sin(Math.PI*W),H[1]+(E[2]-H[1])*j]},A=t.mount?Math.max(1,t.mount.for??450):0,O=t.dismount?Math.max(1,t.dismount.for??450):0;if(t.mount&&m<t.start+A?E=I(t.mount.from,(m-t.start)/A):t.dismount&&m>t.end-O&&(E=I(t.dismount.to,(t.end-m)/O)),f.x.push({time:m,value:E[0]}),f.y.push({time:m,value:E[1]}),f.z.push({time:m,value:E[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]}))}const zy={ground:"#7fb56a",hills:"#5f9a58",city:"#4b5468",cloud:"#ffffff",sun:"#ffd45c",moon:"#f3f0e0",rain:"#9fc4e8",snow:"#ffffff",wall:"#e9e1cf",floor:"#b08a5e",skirting:"#8a6a44",frame:"#f7f3ea"},qi=[[0,"#0b1530","#1b2a4a"],[4.5,"#141a3e","#2a2f5a"],[6,"#4a3f7a","#f0a070"],[7.5,"#86c2ee","#d8ecf8"],[12,"#5aaef2","#c0e2f8"],[16.5,"#69b0e6","#f5d79a"],[18.5,"#4c3f78","#f08a5a"],[20.5,"#17203f","#2d3660"],[24,"#0b1530","#1b2a4a"]],ji=(t,e,n)=>{const s=o=>[1,3,5].map(a=>parseInt(o.slice(a,a+2),16)),[i,r]=[s(t),s(e)];return`#${i.map((o,a)=>Math.round(o+(r[a]-o)*n).toString(16).padStart(2,"0")).join("")}`},P4=t=>{const e=(t%24+24)%24;return e<5||e>20?0:e<7?(e-5)/2:e>18?(20-e)/2:1};function qy(t){const e=(t%24+24)%24;for(let n=1;n<qi.length;n++){const[s,i,r]=qi[n-1],[o,a,l]=qi[n];if(e<=o){const c=(e-s)/(o-s);return{top:ji(i,a,c),bottom:ji(r,l,c)}}}return{top:qi[0][1],bottom:qi[0][2]}}const I4=(t,e)=>{const n=((t-e)%24+24)%24;return n<=12?n/12:-1},O4=9,C4=55,_4=28;function jy(t){const{x:e,y:n,width:s,height:i}=t,r=t.kind??"sky",o=t.ground??n+i*.85,a={...zy,...t.colors},l=t.horizon??"hills",c=t.window!==!1,h=Xe(t.seed??1),u=s*i/1e5,d=Array.from({length:Math.ceil(O4*u)+2},()=>({u:h.next(),v:h.next(),size:.6+h.next()*.8,puffs:2+Math.floor(h.next()*3)})),f=Array.from({length:Math.ceil(C4*u)+4},()=>({u:h.next(),v:h.next(),speed:.8+h.next()*.5})),p=Array.from({length:Math.ceil(_4*u)+4},()=>({u:h.next(),v:h.next(),speed:.7+h.next()*.6,sway:h.next()*Math.PI*2,size:1.5+h.next()*2})),g=Array.from({length:Math.ceil(30*u)+10},()=>({u:h.next(),v:h.next()*.6,size:.6+h.next()*1.2})),m=Array.from({length:6},()=>({phase:h.next()*Math.PI*2,amp:.5+h.next()})),w=Array.from({length:24},()=>({h:.35+h.next()*.65,w:.6+h.next()*.8,windows:h.next()>.3})),v={hour:t.hour??12,clouds:t.clouds??.3,wind:t.wind??0,rain:t.rain??0,snow:t.snow??0},k=ks(),b=(E,I)=>k.keys(E)?.length?k.valueAt(E,I):v[E],T=(E,I)=>{const A=I4(E,I),O=A<0?.5:A,H=o-n;return{x:.1*s+.8*s*O,y:A<0?H+i*.2:H-Math.sin(O*Math.PI)*H*.8,up:A>=0}},$=(E,I,A,O,H)=>{const W=I("hour"),{top:j,bottom:J}=qy(W),tt=E.createLinearGradient(0,O.y,0,O.ground);tt.addColorStop(0,j),tt.addColorStop(1,J),E.fillStyle=tt,E.fillRect(O.x,O.y,O.w,O.ground-O.y);const V=P4(W);if(V<.6){E.fillStyle="#ffffff",E.globalAlpha=(.6-V)/.6*.9;for(const C of g)E.beginPath(),E.arc(O.x+C.u*O.w,O.y+C.v*(O.ground-O.y),C.size,0,Math.PI*2),E.fill();E.globalAlpha=1}const L=T(W,6),q=T(W,18),G=Math.min(O.w,O.h)*.06;if(L.up&&(E.fillStyle=a.sun,E.beginPath(),E.arc(O.x+L.x/s*O.w,O.y+L.y/i*O.h,G,0,Math.PI*2),E.fill()),q.up){const C=O.x+q.x/s*O.w,z=O.y+q.y/i*O.h;E.fillStyle=a.moon,E.beginPath(),E.arc(C,z,G*.8,0,Math.PI*2),E.fill(),E.fillStyle=j,E.beginPath(),E.arc(C-G*.35,z-G*.15,G*.7,0,Math.PI*2),E.fill()}const _=Math.max(0,Math.min(1,I("clouds"))),Y=Math.max(-1,Math.min(1,I("wind"))),st=Math.round(_*d.length);E.fillStyle=ji("#ffffff",a.cloud==="#ffffff"?"#ffffff":a.cloud,1),E.globalAlpha=.55+.4*V;for(let C=0;C<st;C++){const z=d[C],K=((z.u*O.w+Y*A*.012*(.6+z.size*.5))%(O.w*1.4)+O.w*1.4)%(O.w*1.4)-O.w*.2,N=O.x+K,F=O.y+(.08+z.v*.42)*(O.ground-O.y),D=Math.min(O.w,O.h)*.07*z.size;for(let X=0;X<z.puffs;X++)E.beginPath(),E.ellipse(N+(X-(z.puffs-1)/2)*D*.9,F+X%2*D*.25,D*(X%2?.8:1),D*.62,0,0,Math.PI*2),E.fill()}E.globalAlpha=1;const P=C=>ji(ji(C,"#0b1530",.65),C,V);if(l==="hills"){E.fillStyle=P(a.hills),E.beginPath(),E.moveTo(O.x,O.ground);const C=40;for(let z=0;z<=C;z++){const K=z/C;let N=0;m.forEach((F,D)=>N+=Math.sin(K*Math.PI*(1.5+D*.7)+F.phase)*F.amp),E.lineTo(O.x+K*O.w,O.ground-Math.max(0,N)*O.h*.045-O.h*.03)}E.lineTo(O.x+O.w,O.ground),E.closePath(),E.fill()}else if(l==="city"){E.fillStyle=P(a.city);let C=O.x;const z=O.w/18;for(const K of w){if(C>O.x+O.w)break;const N=z*K.w,F=O.h*.22*K.h;if(E.fillRect(C,O.ground-F,N,F),K.windows&&V<.5){E.fillStyle="#ffd66b",E.globalAlpha=.5-V;for(let D=O.ground-F+6;D<O.ground-8;D+=9)for(let X=C+4;X<C+N-4;X+=8)E.fillRect(X,D,3,4);E.globalAlpha=1,E.fillStyle=P(a.city)}C+=N+z*.15}}E.fillStyle=P(a.ground),E.fillRect(O.x,O.ground,O.w,O.y+O.h-O.ground)},M=(E,I,A,O)=>{const H=Math.max(-1,Math.min(1,I("wind"))),W=Math.max(0,Math.min(1,I("rain"))),j=Math.max(0,Math.min(1,I("snow")));if(W>0){E.strokeStyle=a.rain,E.globalAlpha=.35+.45*W,E.lineWidth=1.2,E.lineCap="round";const J=O.h*.05,tt=H*.45,V=Math.round(W*f.length);E.beginPath();for(let L=0;L<V;L++){const q=f[L],G=((q.v*O.h+A*q.speed*.9)%O.h+O.h)%O.h,_=((q.u*O.w+G*tt)%O.w+O.w)%O.w;E.moveTo(O.x+_,O.y+G),E.lineTo(O.x+_+tt*J,O.y+G+J)}E.stroke(),E.globalAlpha=1}if(j>0){E.fillStyle=a.snow,E.globalAlpha=.85;const J=Math.round(j*p.length);for(let tt=0;tt<J;tt++){const V=p[tt],L=((V.v*O.h+A*V.speed*.08)%O.h+O.h)%O.h,q=Math.sin(A*.002+V.sway)*O.w*.02,G=((V.u*O.w+q+H*L*.3)%O.w+O.w)%O.w;E.beginPath(),E.arc(O.x+G,O.y+L,V.size,0,Math.PI*2),E.fill()}E.globalAlpha=1}},S={kind:"scenery",target:{type:"custom",x:e,y:n,width:s,height:i,props:v,about:{kind:r==="room"?"room":"sky",summary:r==="room"?"A room: a wall, a floor and a window on the sky. Its values are tracks: hour, clouds, wind, rain, snow (seen through the window).":`A sky over ${l==="flat"?"the ground":l}: the sun and moon on their arcs, stars, clouds on the wind, rain and snow. Its values are tracks: hour (0–24), clouds, wind (−1..1), rain, snow (0..1).`,props:Object.fromEntries(Object.keys(v).map(E=>[E,H4(E)]))},draw(E,I,A){const O=I.props??{},H=j=>Number(O[j]??v[j]??0);E.save();const W={x:0,y:0,w:s,h:i,ground:o-n};if(r==="sky")$(E,H,A,W),M(E,H,A,W);else if(E.fillStyle=a.wall,E.fillRect(0,0,s,W.ground),E.fillStyle=a.floor,E.fillRect(0,W.ground,s,i-W.ground),E.fillStyle=a.skirting,E.fillRect(0,W.ground-i*.012,s,i*.012),c){const j=s*.26,J=W.ground*.5,tt=s*.62,V=W.ground*.14;E.fillStyle=a.frame,E.fillRect(tt-6,V-6,j+12,J+12),E.save(),E.beginPath(),E.rect(tt,V,j,J),E.clip(),$(E,H,A,{x:tt,y:V,w:j,h:J,ground:V+J*.8}),M(E,H,A,{x:tt,y:V,w:j,h:J}),E.restore(),E.strokeStyle=a.frame,E.lineWidth=4,E.beginPath(),E.moveTo(tt+j/2,V),E.lineTo(tt+j/2,V+J),E.moveTo(tt,V+J/2),E.lineTo(tt+j,V+J/2),E.stroke()}E.restore()}},ground:o,anchor(E,I=1/0){const A=b("hour",I);if(E==="sun"||E==="moon"){const O=T(A,E==="sun"?6:18);return{x:e+O.x,y:n+O.y}}if(E==="horizon")return{x:e+s/2,y:o-i*.03};if(E==="ground")return{x:e+s/2,y:o};throw new Error(`scenery: ${ft("place",E,["sun","moon","horizon","ground"])}`)},set(E,I){if(!(E in v))throw new Error(`scenery: ${ft("value",E,Object.keys(v))}`);if(typeof I.value!="number"||!Number.isFinite(I.value))throw new Error("scenery.set needs `value`, a number");return k.tween(E,b(E,I.at),I.value,I,1e3),S},tracks:k.tracks};return S}function H4(t){switch(t){case"hour":return{description:"The time of day, 0–24: the sky’s colours, the sun and the moon on their arcs, stars at night",unit:"hours",min:0,max:24};case"clouds":return{description:"Cloud cover",unit:"0..1",min:0,max:1};case"wind":return{description:"The wind, blowing left (−) or right (+): clouds drift, rain slants, snow drifts",unit:"-1..1",min:-1,max:1};case"rain":return{description:"How hard it rains",unit:"0..1",min:0,max:1};default:return{description:"How hard it snows",unit:"0..1",min:0,max:1}}}function Yy(t,e){const{width:n,height:s}=e,i=e.ground??s*.85,r=e.scale??s/4.5,o={x:0,y:0,width:n,height:s,ground:i},a=(l,c,h={})=>({preset:l,x:n*c,scale:r,...h});switch(t){case"park":return{scenery:{...o,hour:10.5,clouds:.35,horizon:"hills",...e.scenery},props:[a("tree",.14,{scale:r*1.1}),a("chair",.5,{turn:0}),a("tree",.86,{scale:r*.9})]};case"street":return{scenery:{...o,hour:16,clouds:.25,horizon:"city",colors:{ground:"#8a8f99"},...e.scenery},props:[a("house",.2,{scale:r*.75,turn:.1}),a("car",.5,{turn:1,scale:r*.9}),a("house",.78,{scale:r*.7,turn:.1}),a("tree",.95,{scale:r*.8})]};case"office":return{scenery:{...o,kind:"room",hour:11,clouds:.3,colors:{wall:"#dfe5ec",floor:"#9aa3ad",skirting:"#6c757d"},...e.scenery},props:[a("door",.1,{turn:.15}),a("chair",.46,{turn:0}),a("desk",.58,{turn:0})]};case"home":return{scenery:{...o,kind:"room",hour:20,clouds:.2,...e.scenery},props:[a("door",.08,{turn:.15}),a("chair",.35,{turn:.3}),a("bed",.72,{turn:.25})]};default:throw new Error(ft("scene preset",t,["park","street","office","home"]))}}function R4(t,e){const n=Yy(t,e),s=jy(n.scenery),i=n.props.map(r=>xm({x:r.x,y:s.ground,prop:rh(r.preset),scale:r.scale,values:{turn:r.turn??0,...r.values}}));return{scenery:s,props:i,ground:s.ground}}function L4(t){const{timeline:e}=t,n=new vn;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,r=!1;const o=c=>{if(r)return;const h=i===null?0:c-i;i=c,h>0&&e.tick(h),s=requestAnimationFrame(o)},a=()=>{s!==null||r||(i=null,s=requestAnimationFrame(o))},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(){r=!0,l(),e.stop(),n.clearTargets()}}}const F4={timeline:yw,to(t,e,n){const s=new kn(n);return s.to(t,e),s},from(t,e,n){const s=new kn(n);return s.from(t,e),s},fromTo(t,e,n,s){const i=new kn(s);return i.fromTo(t,e,n),i},set(t,e,n){const s=new kn(n);return s.set(t,e),s}};function Ky(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 N4(t,e){const n=t.length/4,s=new Float32Array(n*3),i=Math.min(.999,Math.max(0,e));for(let r=0;r<n;r++){const o=t[r*4]/255,a=t[r*4+1]/255,l=t[r*4+2]/255,c=t[r*4+3]/255,h=Math.max(o,a,l);if(h<=i)continue;const u=(h-i)/(1-i)*c/h;s[r*3]=o*u,s[r*3+1]=a*u,s[r*3+2]=l*u}return s}function Xy(t,e,n,s,i){const r=new Float32Array(t.length),o=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<o;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++){r[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 r}function Gy(t,e,n,s){const i=Math.max(1,Math.round(s/Math.sqrt(3)));let r=t;for(let o=0;o<3;o++)r=Xy(r,e,n,i,!0),r=Xy(r,e,n,i,!1);return r}function W4(t,e={}){const n=t.canvas,s=n.width,i=n.height;if(!(s>0&&i>0))return;const r=Math.max(1,Math.round(e.downsample??4)),o=Math.max(1,Math.ceil(s/r)),a=Math.max(1,Math.ceil(i/r)),l=Ky(t,o,a),c=l?.getContext("2d");if(!l||!c)return;c.imageSmoothingEnabled=!0,c.drawImage(t.canvas,0,0,o,a);const h=N4(c.getImageData(0,0,o,a).data,e.threshold??.55),u=(e.radius??Math.max(s,i)*.02)/r,d=Gy(h,o,a,u),f=Gy(h,o,a,u*3),p=e.halo??.6,g=c.createImageData(o,a);for(let m=0;m<o*a;m++){for(let w=0;w<3;w++)g.data[m*4+w]=Math.round(Math.min(1,d[m*3+w]+f[m*3+w]*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 D4(t,e,n){const s=n.width??6,i=n.taper??1,r=n.fade??1,o=n.opacity??1,a=n.blend==="add";if(t.save(),e.length>=2){const c=z4(e,s,i,r,o);a?(t.globalCompositeOperation="lighter",Th(t,c,n.color)):q4(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,B4(t,c)),t.globalAlpha=o,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 B4(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 z4(t,e,n,s,i){const r=t.map(c=>({x:c.at.x,y:c.at.y,width:e*(1-n*c.age)})),o=N0(r),a=W0(r)??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:[o.left[c],o.left[c+1],o.right[c+1],o.right[c]],alpha:u,...d&&a&&{cap:a}})}return l}function Th(t,e,n){t.fillStyle=n;for(const s of e){const[i,r,o,a]=s.corners;t.globalAlpha=Math.min(1,s.alpha),t.beginPath(),t.moveTo(i.x,i.y),t.lineTo(r.x,r.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(o.x,o.y),t.lineTo(a.x,a.y),t.closePath(),t.fill()}}function q4(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,r=s?Math.sqrt(Math.abs(s.a*s.d-s.b*s.c)):1,o=e.map(g=>({...g,corners:g.corners.map(i),...g.cap&&{cap:{...g.cap,...i(g.cap),radius:g.cap.radius*r,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 o){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 w of[...g.corners,...m])a=Math.min(a,w.x),l=Math.min(l,w.y),c=Math.max(c,w.x),h=Math.max(h,w.y)}if(!(c>a&&h>l))return;const u=Math.floor(a)-1,d=Math.floor(l)-1,f=s?Ky(t,Math.ceil(c)+1-u,Math.ceil(h)+1-d):null,p=f?.getContext("2d");if(!f||!p){Th(t,e,n);return}p.translate(-u,-d),p.globalCompositeOperation="lighter",Th(p,o,n),t.save(),t.setTransform(1,0,0,1,0,0),t.globalAlpha=1,t.drawImage(f,u,d),t.restore()}const j4=re.to,Y4=re.from,K4=re.fromTo,X4=re.set,G4=re.timeline,U4=re.ticker,V4=re.splitText,J4=re.context,Z4=re.matchMedia,Q4=re.quickTo,tT=re.imageSequence,eT=re.pageTransition;j2(),y.ACTING_STYLES=Ln,y.AIRCRAFT_ACTING=eh,y.ANIMAL_GAITS=Is,y.ANIME_CAST=xp,y.BEAT_FIELDS=xo,y.BEAT_MOMENTS=Ts,y.BED_ACTING=Ym,y.BIRD_ACTING=hy,y.BOARD_MARKS=kc,y.BOARD_THEMES=Pi,y.CANVAS_PROPERTIES=Io,y.CHAIR_ACTING=Bm,y.CHARACTER_BEAT_3D_FIELDS=cc,y.CHARACTER_CAST=xc,y.CHARACTER_GAIT_SPEEDS=rp,y.CHART_KINDS=Mc,y.CHART_SURFACE=Hn,y.CHART_THEMES=Ii,y.CODE_LANGUAGES=ko,y.CODE_PANEL_EDITS=bc,y.CODE_SURFACE=$i,y.CODE_THEME=dp,y.CRICKET_ACTIONS=Wn,y.CRICKET_CAMERA_ANGLES=qo,y.CRICKET_CASTS=ch,y.CRICKET_DECISION_VIEWS=Di,y.CRICKET_FIELDING_POSITIONS=Cs,y.CRICKET_FORMATS=Ne,y.CRICKET_MARKING_PROFILES=jo,y.CRICKET_PITCH=jt,y.CRICKET_PLAY_COMPONENTS=fn,y.CRICKET_PLAY_EXAMPLES=Ry,y.CRICKET_VIEWS=zo,y.Clock=Jy,y.CompatTimeline=kn,y.CustomBounce=Iu,y.CustomEase=Pu,y.CustomWiggle=Ou,y.DANCE_STYLES=Je,y.DEFAULT_BAKE_INTERVAL_MS=da,y.DEFAULT_INERTIA_FRICTION=ta,y.DEFAULT_LABELS=Du,y.DEFAULT_SPRING=ce,y.DEFAULT_TRANSITION=K2,y.DESK_ACTING=qm,y.DOOR_ACTING=Xm,y.Draggable=Fa,y.EMBRACE=vo,y.EXPRESSIONS=vt,y.FACIAL_HAIR_STYLES=Hl,y.FINGERS=sd,y.FLIPS=Mi,y.FOOT_SHAPES=Gd,y.FORMAT_VERSION=Go,y.FRAME_ASPECTS=L0,y.GAGS=rn,y.GAITS=Kt,y.GAIT_CYCLE_MS=Lc,y.GLASSES_STYLES=Ll,y.HAIR_COLORS=Te,y.HAIR_STILL=hs,y.HAIR_STYLES=Pl,y.HAND_MEETINGS=Ci,y.HAND_REST=Ot,y.HAND_SHAPES=St,y.HAT_STYLES=Ur,y.HELD_ITEMS=Dl,y.HELP_UP=Rn,y.HORSE_ACTING=kx,y.HORSE_GAITS=mx,y.HOUSE_ACTING=Wm,y.HUMAN_ACTING_RIG=Op,y.HUMAN_BUILDS=Hr,y.HUMAN_CYCLES=Fl,y.HUMAN_DANCES=En,y.HUMAN_EXPRESSIONS=gl,y.HUMAN_GAGS=Zr,y.HUMAN_POSES=be,y.HUMAN_REST=lt,y.IDENTITY_CAMERA=ap,y.IDENTITY_SIMILARITY=$b,y.INERTIA_MAX_DURATION_MS=Oh,y.InertiaTrackPlayer=y0,y.LiveTimeline=Se,y.MANGA_CAST=Tp,y.MORPH_SAMPLES=w1,y.MUDRAS=$r,y.ManualClock=Vy,y.MediaSync=Ja,y.OUTFIT_PRESETS=Tc,y.Observer=ou,y.POSES=ae,y.PROP_BEAT_3D_FIELDS=Mh,y.PROP_BEAT_FIELDS=Fo,y.PROP_COMMON_ACTIONS=ah,y.PROP_COMMON_CONTROLS=As,y.PROP_PRESETS=Os,y.PROP_SURFACE=Ps,y.QUADRUPED_ACTING=sh,y.REMOVE_STYLES=bo,y.REST_POSE=ut,y.RIDING_POSES=Sh,y.SAMPLE_STEP=nn,y.SCENERY_COLORS=zy,y.SCRIPT_ACTIONS=Hi,y.SOFT_CARTOON_CAST=Oi,y.SPRING_MAX_DURATION_MS=Qo,y.SPRING_PRESETS=Vi,y.SPRING_STEP_MS=Bn,y.STICK_ACTING_RIG=Ip,y.ScrollAnimator=Mu,y.ScrollDriver=ni,y.ScrollMarkers=Su,y.ScrollPin=bu,y.SmoothScroll=Ga,y.SpringSampler=Ws,y.SpringTrackPlayer=m0,y.Stage=tu,y.TREE_ACTING=Fm,y.Timeline=Ht,y.TinyflyPlayer=gr,y.TinyflySequencer=Gu,y.TrackPlayer=Ke,y.VEHICLE_ACTING=Em,y.VISEMES=en,y.ValueResolver=X1,y.VisibilityDriver=yu,y.WHEELCHAIR_ACTING=Vm,y.WHITEBOARD_SURFACE=He,y.actCharacterTracks=Hp,y.actKeyframes=So,y.actTracks=_p,y.actionNames=Cc,y.airplane=Qm,y.anchorError=sn,y.animalStrideLength=Lo,y.animatableProperties=am,y.applyBloom=W4,y.applyCamera=OM,y.applyGroove=Dd,y.applySimilarity=xa,y.aspectOf=Sa,y.assertBeats=Rc,y.audioEnvelope=kb,y.backOut=Bh,y.bakeDanceTracks=l5,y.bakeEasing=pa,y.bakeInertiaTrack=ga,y.bakeSpringTrack=fa,y.ballFlightPoint=gh,y.ballFlightTracks=Hx,y.basicOutfit=rg,y.beatAt=r5,y.beatAtTime=Xs,y.beatLength=Ks,y.beatPeriod=yb,y.beatPulse=wb,y.beatTime=sr,y.beatsBetween=rb,y.bed=jm,y.bike=Hm,y.bindChoiceHotspots=ju,y.bird=hn,y.blendPose=ns,y.bodyProfileWidth=Qd,y.boilFrame=Qa,y.bounceOut=Dh,y.boxMesh=jg,y.brushingPose=Vf,y.bubblePath=Wb,y.bubblePop=Db,y.buildScene=R4,y.bus=Im,y.cameraFromValues=IM,y.cameraPoint=CM,y.cameraTracks=cb,y.capabilities=Ly,y.capabilitiesMarkdown=Zx,y.car=$m,y.cart=Cm,y.castMember=pS,y.cat=iy,y.chair=Dm,y.changingWindows=vs,y.character=ps,y.characterAt=Dv,y.characterHandPose=ug,y.characterJoints=fe,y.characterJointsInView=Lv,y.characterLookAtTracks=$M,y.characterObjects=mM,y.characterPartsInView=gg,y.characterPoseOf=no,y.characterPoseTracks=Bv,y.characterScript=P3,y.characterScript3D=AM,y.characterStrideLength=im,y.characterTarget=Wv,y.charactersFor=b0,y.chart=hS,y.checkBeats=Ri,y.checkCast=_c,y.checkCharacterBeats3D=op,y.checkPropBeats=by,y.checkPropBeats3D=Wy,y.checkSurfaceBeats=em,y.checkTracks=D3,y.chicken=fy,y.circlePath=LM,y.clamp01=ja,y.clearMorphCache=$1,y.clearPathCache=g1,y.clipErased=yc,y.closestName=Gs,y.codePanel=XM,y.codeTokens=gp,y.composeSimilarity=Ib,y.containerProgressAt=Ya,y.context=J4,y.controlValue=It,y.cow=ry,y.create=P2,y.createControls=zu,y.createCubicBezier=Nh,y.createLive=Hu,y.createPen=ri,y.createRandom=Xe,y.createTrack=nr,y.cricketAction=Cy,y.cricketCameraFraming=Ay,y.cricketCameraReview=Do,y.cricketCameraTracks=Wx,y.cricketClip=Yx,y.cricketDecisionOverlay=Rx,y.cricketEventAt=Kx,y.cricketField=wh,y.cricketFieldingAreaContains=$y,y.cricketFieldingOverlay=Bx,y.cricketFieldingPositions=Py,y.cricketPlay=Hy,y.cricketPlayClip=Vx,y.cricketPlayer=Iy,y.criticalDamping=t1,y.crow=dy,y.curve=mb,y.customBounce=P0,y.customEase=$0,y.customWiggle=I0,y.cylinderMesh=Yg,y.danceCircleAt=vg,y.danceCircleTracks=qv,y.danceFrame=Or,y.danceJoint=On,y.dancePose=t5,y.danceStance=Ir,y.danceTaps=n5,y.danceTracks=a5,y.danceTravel=_r,y.danceTravelTrack=Yd,y.dancer=o5,y.defineAction=GS,y.defineGait=US,y.describeTarget=om,y.deserializeTimeline=Gn,y.deserializeTrack=M0,y.desk=zm,y.detectTempo=ob,y.dog=sy,y.door=Km,y.draggable=zw,y.drawCartoonHand=Sr,y.drawCharacter=fg,y.drawCharacterHead=Nv,y.drawCharacterInView=Fv,y.drawDustPuff=Fp,y.drawEraser=pc,y.drawHand=mc,y.drawHeldItem=Bl,y.drawImpactStars=YS,y.drawPencil=lp,y.drawProp=nx,y.drawPropEffects=Qx,y.drawPropShadow=tc,y.drawSolvedFaces=Og,y.drawSolvedPart=oM,y.drawSolvedProp=Zl,y.drawSpeedLines=Lp,y.drawStickFigure=Rd,y.drawStickSmear=jS,y.drawTrail=D4,y.drawnPathTarget=FM,y.dripPath=Nb,y.duck=py,y.easeIn=Rh,y.easeInCubic=ea,y.easeInOut=Fh,y.easeInOutCubic=Bs,y.easeInOutQuad=Hh,y.easeInQuad=Ch,y.easeOut=Lh,y.easeOutCubic=na,y.easeOutQuad=_h,y.editDistance=_0,y.editError=Ai,y.editLog=ks,y.elasticOut=Wh,y.ellipsePoints=wr,y.ellipsoidMesh=Kg,y.embrace=wS,y.embraceSpacing=bS,y.envelopeAt=vb,y.erasable=BM,y.expandBeats=Eo,y.expandParametricEasings=g0,y.extrudeMesh=Xg,y.flipPose=Mg,y.flipTracks=Gv,y.flipTravel=Sg,y.formatVersionFor=Uo,y.frameRect=Mb,y.frameSize=Sb,y.from=Y4,y.fromJSON=j1,y.fromTo=K4,y.gag=Ic,y.gagDuration=_i,y.gaitPose=ld,y.gaitStrideLength=xr,y.getEasingFunction=Wt,y.getInterpolator=Ys,y.getMotionPathPoint=ma,y.getPathLength=p1,y.getPointAtProgress=Kh,y.goat=oy,y.gridLinesFor=cu,y.hairFollow=$p,y.hairFollowTracks=_S,y.hairHangs=kf,y.hairMotionAt=OS,y.hairMotionOf=bi,y.hairlineAt=wi,y.handAt=RM,y.handGrip=Qr,y.handJoints=Mr,y.handJointsAt=od,y.handPath=jc,y.handPose=Nt,y.handProp=di,y.hasKeyframes=$h,y.hashSeed=ne,y.headPoint=jk,y.heldTime=Ph,y.helicopter=Zm,y.helpUp=vS,y.helpUpSpacing=kS,y.holdingLayers=lg,y.horse=ny,y.horseStrideLength=Mx,y.house=Nm,y.humanCyclePose=Av,y.humanDanceFrame=pi,y.humanDanceTracks=_5,y.humanFieldLabel=P5,y.humanGag=Gf,y.humanGaitPose=Vr,y.humanGaitStrideLength=Jr,y.humanPlan=fl,y.humanPose=kt,y.imageSequence=tT,y.inertiaDuration=qn,y.inertiaRest=zn,y.inertiaValueAt=Zi,y.inertiaVelocityAt=i1,y.interpolateArray=h0,y.interpolateColor=c0,y.interpolateMotionPath=W1,y.interpolateNumber=ke,y.interpolatePathString=d0,y.interpolateQuaternion=u0,y.interpolateString=ua,y.invertSimilarity=Ob,y.isCubicBezierEasing=Dn,y.isHeld=zl,y.isInertiaTrack=De,y.isMotionPathPoint=Uy,y.isMotionPathTrack=Vo,y.isParametricEasing=Fs,y.isPathData=Yn,y.isSpringTrack=Be,y.isTextTrack=Ki,y.isUnderdamped=Qy,y.isUnresolved=K1,y.isoDepth=Ta,y.isometricBoxFaces=Ea,y.isometricFaces=Aa,y.jointsInScene=mg,y.jointsToScene=Hd,y.leafOutfit=eg,y.leafOutfitContours=Nl,y.linear=Qi,y.lipSyncKeyframes=ac,y.lipSyncOver=fo,y.lipSyncTracks=vM,y.lit=rc,y.live=re,y.lookFields=hc,y.loopBeats=bb,y.loopEase=ub,y.loopNoise=db,y.loosePartsOf=Qc,y.lyingPose=ey,y.mapEase=Qs,y.mat4=Ub,y.matchMedia=Z4,y.maxStaggerDistance=Zo,y.meetDandiya=zv,y.meetHands=yS,y.meetingSpacing=mS,y.metaballContours=Lb,y.metaballField=z0,y.mirrorHumanPose=Xd,y.mirrorPose=Wd,y.mixColors=oc,y.mixHandPoses=es,y.mixPoses=Kl,y.morphPath=Qh,y.motorbike=Rm,y.mount=Yu,y.mountAll=Xu,y.narrationMarkers=eb,y.narrationSceneAt=nb,y.naturalRest=Ds,y.nearestBeat=sb,y.nextBeat=ib,y.niceCeiling=vp,y.objectPositionAt=gc,y.organicBodyContours=ef,y.organicCenterLine=mi,y.outfitPreset=Ap,y.owl=my,y.pageTransition=eT,y.panelMesh=Gg,y.parametricEasing=qh,y.parrot=yy,y.parseAnchor=_n,y.parseEdge=za,y.parsePath=gn,y.parseTrigger=qa,y.partialPath=ts,y.pathLength=Qu,y.pedallingKeys=A4,y.pedallingPose=xh,y.penroseStairs=Rb,y.penroseTriangle=Hb,y.persona=A3,y.phaseOf=pn,y.pieceMotion=Ei,y.pigeon=gy,y.pingPong=Ma,y.planNarration=tb,y.plantDanceFoot=wg,y.play=$2,y.playSequence=Y2,y.playWhenVisible=e2,y.playheadCrossings=ba,y.pointAlong=mr,y.pointAtDistance=ia,y.pointOnHead=_v,y.pointsToPath=F0,y.pose=Dt,y.poseTracks=Gk,y.powSimilarity=Cb,y.projectIsometric=or,y.propActions=No,y.propAnchors3D=Mm,y.propAt=_o,y.propControls=th,y.propLineWidth=Ql,y.propObjects=m4,y.propPartsInSpace=vm,y.propPreset=rh,y.propRide=r4,y.propRide3D=$4,y.propScript=wy,y.propScript3D=S4,y.propShapeMesh=Fi,y.propSurface=rx,y.propTarget=xm,y.propTow=l4,y.propView=bm,y.quadruped=ln,y.quat=H1,y.quickPlay=L4,y.quickTo=Q4,y.rabbit=ay,y.randomBetween=ka,y.randomChoice=Y1,y.randomSnapped=x0,y.reachCharacter=_e,y.reachOf=rm,y.resolveActingStyle=Ac,y.resolveCharacterPoseKeys=Xl,y.resolveFacialHair=Rf,y.resolveGait=ci,y.resolveGlasses=Ff,y.resolveHair=Sf,y.resolveHat=Wf,y.resolveHeadLook=Bf,y.resolveHolding=og,y.resolveOrganicBody=Zd,y.resolvePoseKeys=Ar,y.resolveSequence=A0,y.resolveStickFrame=rl,y.resolveStickPose=Ld,y.resolveValue=va,y.ribbon=N0,y.ribbonHeadCap=W0,y.rideFloors=yo,y.rotateAbout=Ue,y.routineBeats=Cr,y.rubberLimb=Mn,y.safeAreas=xb,y.scalePoints=zb,y.scenePreset=Yy,y.scenery=jy,y.scriptActionSummaries=Hc,y.scriptTracks=$o,y.scrollProgress=t2,y.scrubOnScroll=r2,y.scrubPath=WM,y.seatHeight=Nk,y.serializeTimeline=S0,y.serializeTrack=k0,y.set=X4,y.shade=ho,y.shapeMesh=Jg,y.shapeToPathData=ir,y.similarity=Pb,y.similarityAbout=D0,y.similarityFixedPoint=B0,y.similarityMatrix=_b,y.simplifyKeyframes=p0,y.sittingPose=nh,y.skeletonInView=Wr,y.sketchPen=yr,y.skyColors=qy,y.smoothPath=lc,y.smoothToward=mu,y.snapAxis=lu,y.snapConfig=wu,y.snapDuration=vu,y.snapProgress=ku,y.softCartoonCharacter=gS,y.solveAt=$s,y.solvePlanSpace=is,y.solveProp=Zc,y.songbird=uy,y.soundsOf=qg,y.speechDuration=tm,y.speechLength=np,y.spliceTracks=a4,y.splitText=V4,y.springDuration=Ih,y.springFollow=Us,y.springValueAt=Zy,y.squashStretch=Bb,y.squirrel=ly,y.stagePlanSpace=Ze,y.stageSpots=PM,y.staggerDistance=Jo,y.staggerOffset=Xi,y.staggerOffsets=Gi,y.staggerSpan=Ns,y.stepsDuration=Wp,y.stepsEasing=zh,y.stepsToKeys=Oc,y.stickFigureAt=al,y.stickFigureJoints=ye,y.stickFigureTarget=ol,y.stickToHuman=xg,y.strideLength=gd,y.surfaceBox=Mt,y.surfaceScript=T3,y.sweepingPose=Uf,y.syncMediaElement=Wu,y.talkingMouth=pd,y.taperedLine=br,y.taperedOutline=zt,y.textAt=w0,y.tf=F4,y.ticker=U4,y.timeline=G4,y.to=j4,y.toJSON=q1,y.toKeyframedTrack=F1,y.toKeyframedTracks=N1,y.torusNoise=fb,y.trackTargets=Ye,y.tractor=Om,y.trailSamples=Eb,y.trainCar=_m,y.tree=Lm,y.triggerDistance=Vn,y.truck=Pm,y.tubeMesh=Ug,y.unknownName=ft,y.unmount=z2,y.valueAt=mo,y.vec3=qb,y.vehicle=Fe,y.walkPose=fd,y.wheelchair=Um,y.whiteboard=ZM,y.withErased=DM,y.withExpression=Ve,y.wobble=hb,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})}));
|