vizmatic 0.5.0 → 0.6.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/PROMPT.md +1 -1
- package/README.md +1 -1
- package/assets/THIRD_PARTY_LICENSES.md +4 -0
- package/assets/fonts/SourceSerif4-24pt-Italic.ttf +0 -0
- package/assets/fonts/SourceSerif4-24pt-Regular.ttf +0 -0
- package/dist/{chunk-WHT6HRMX.js → chunk-5ZAFH2JC.js} +40 -10
- package/dist/cli.js +2 -2
- package/dist/stage-browser/browser.d.ts +6 -5
- package/dist/stage-browser/stage.js +5 -5
- package/dist/stage-export.cjs +38 -8
- package/dist/stage-export.js +1 -1
- package/dist/stage.cjs +54 -10
- package/dist/stage.d.cts +6 -5
- package/dist/stage.d.ts +6 -5
- package/dist/stage.js +15 -1
- package/examples/videos/README.md +1 -1
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -126,11 +126,11 @@ parentPort.on('message', (job) => {
|
|
|
126
126
|
parentPort.postMessage({ id: job.id, error: String(error && error.message || error) })
|
|
127
127
|
}
|
|
128
128
|
})
|
|
129
|
-
`;function resolveResvg(){const here=typeof __filename!=="undefined"?__filename:fileURLToPath(import.meta.url);return createRequire(here).resolve("@resvg/resvg-js")}var RasterPool=class{workers=[];idle=[];queue=[];pending=new Map;nextId=1;failure=null;constructor(size=defaultPoolSize()){const resvgPath=resolveResvg();for(let i=0;i<size;i++){const worker=new Worker(RASTER_WORKER_SOURCE,{eval:true,workerData:{resvgPath}});worker.on("message",message=>{const entry=this.pending.get(message.id);this.pending.delete(message.id);this.idle.push(worker);this.pump();if(!entry)return;if(message.error||!message.pixels)entry.reject(new Error(`Frame rasterization failed: ${message.error}`));else entry.resolve(message.pixels)});worker.on("error",error=>this.fail(error instanceof Error?error:new Error(String(error))));this.workers.push(worker);this.idle.push(worker)}}get size(){return this.workers.length}fail(error){this.failure=error;for(const entry of this.pending.values())entry.reject(error);this.pending.clear()}pump(){while(this.idle.length>0&&this.queue.length>0){const worker=this.idle.pop();const{job,id}=this.queue.shift();worker.postMessage({id,...job})}}run(job){if(this.failure)return Promise.reject(this.failure);const id=this.nextId++;return new Promise((resolve4,reject)=>{this.pending.set(id,{resolve:resolve4,reject});this.queue.push({job,id});this.pump()})}async close(){this.failure??=new Error("The raster pool was closed.");for(const entry of this.pending.values())entry.reject(this.failure);this.pending.clear();this.queue.length=0;await Promise.all(this.workers.map(worker=>worker.terminate()))}};function defaultPoolSize(){return Math.max(1,Math.min(12,cpus().length-2))}function framesToJob(frames,width,parseBackground,height){const first=frames[0];const scale=width/first.width;return{svgs:frames.map(frame=>frameToSvg(frame)),width,height:height??Math.round(first.height*scale),bloom:first.dark?first.bloom:0,background:parseBackground(first.background)}}var clamp01=t=>t<=0?0:t>=1?1:t;var linear=t=>t;function sigmoid(x){return 1/(1+Math.exp(-x))}function smoothBy(inflection){const low=sigmoid(-inflection/2);const high=sigmoid(inflection/2);return t=>{if(t<=0)return 0;if(t>=1)return 1;return(sigmoid(inflection*(t-.5))-low)/(high-low)}}var smooth2=smoothBy(10);var smoother=t=>{const x=clamp01(t);return x*x*x*(x*(x*6-15)+10)};var easeInQuad=t=>t*t;var easeOutQuad=t=>1-(1-t)*(1-t);var easeInCubic=t=>t*t*t;var easeOutCubic=t=>1-Math.pow(1-t,3);var easeInOutCubic=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;var easeOutQuint=t=>1-Math.pow(1-t,5);var easeInOutQuint=t=>t<.5?16*t*t*t*t*t:1-Math.pow(-2*t+2,5)/2;var easeOutExpo=t=>t>=1?1:1-Math.pow(2,-10*t);var easeInExpo=t=>t<=0?0:Math.pow(2,10*t-10);var rushInto=t=>2*smooth2(t/2);var rushFrom=t=>2*smooth2(t/2+.5)-1;var slowInto=t=>Math.sqrt(Math.max(0,1-(1-t)*(1-t)));function overshoot(amount2=1.70158){return t=>{const x=t-1;return x*x*((amount2+1)*x+amount2)+1}}function spring(options={}){const bounce2=options.bounce??.28;const frequency=options.frequency??2.2;const decay=-Math.log(Math.max(1e-4,bounce2))*2.4;return t=>{if(t<=0)return 0;if(t>=1)return 1;return 1-Math.exp(-decay*t)*Math.cos(frequency*Math.PI*2*t)*(1-t)}}var bounce=t=>{const n=7.5625,d=2.75;if(t<1/d)return n*t*t;if(t<2/d)return n*(t-=1.5/d)*t+.75;if(t<2.5/d)return n*(t-=2.25/d)*t+.9375;return n*(t-=2.625/d)*t+.984375};var thereAndBack=t=>smooth2(t<.5?2*t:2*(1-t));function thereAndBackWithPause(pause=1/3){const a=(1-pause)/2;return t=>{if(t<a)return smooth2(t/a);if(t<1-a)return 1;return smooth2((1-t)/a)}}function wiggle(cycles=2){return t=>thereAndBack(t)*Math.sin(cycles*Math.PI*2*t)}function notQuiteThere(amount2=.7,inner=smooth2){return t=>amount2*inner(t)}function lingering(hold2=.25,inner=smooth2){return t=>inner(clamp01(t/(1-hold2)))}function runningStart(pull=-.5){return t=>{const u=1-t;return 15*u**4*t**2*pull+20*u**3*t**3*pull+15*u**2*t**4+6*u*t**5+t**6}}function during(from,to2,inner=smooth2){return t=>inner(clamp01((t-from)/(to2-from)))}function cubicBezier(x1,y1,x2,y2){const cx=3*x1,bx=3*(x2-x1)-cx,ax=1-cx-bx;const cy=3*y1,by=3*(y2-y1)-cy,ay=1-cy-by;const sampleX=t=>((ax*t+bx)*t+cx)*t;const sampleY=t=>((ay*t+by)*t+cy)*t;const slope=t=>(3*ax*t+2*bx)*t+cx;return x=>{if(x<=0)return 0;if(x>=1)return 1;let t=x;for(let i=0;i<8;i++){const dx=sampleX(t)-x;const d=slope(t);if(Math.abs(dx)<1e-5||Math.abs(d)<1e-6)break;t-=dx/d}return sampleY(t)}}function growTo(r,target){const count=segmentCount(r);if(count>=target||count===0)return r;const segments=[];for(let i=0;i<count;i++){const o=i*6;const pts=Array.from(r.p.subarray(o,o+8));segments.push({pts,length:chord(pts)})}while(segments.length<target){let longest=0;for(let i=1;i<segments.length;i++)if(segments[i].length>segments[longest].length)longest=i;const[a,b]=bisect(segments[longest].pts);segments.splice(longest,1,{pts:a,length:chord(a)},{pts:b,length:chord(b)})}const out=new Float64Array(2+target*6);out[0]=r.p[0];out[1]=r.p[1];for(let i=0;i<target;i++){const pts=segments[i].pts;for(let k=0;k<6;k++)out[2+i*6+k]=pts[2+k]}return{p:out,closed:r.closed}}function chord(pts){return Math.hypot(pts[2]-pts[0],pts[3]-pts[1])+Math.hypot(pts[4]-pts[2],pts[5]-pts[3])+Math.hypot(pts[6]-pts[4],pts[7]-pts[5])}function bisect(p){const ax=(p[0]+p[2])/2,ay=(p[1]+p[3])/2;const bx=(p[2]+p[4])/2,by=(p[3]+p[5])/2;const cx=(p[4]+p[6])/2,cy=(p[5]+p[7])/2;const dx=(ax+bx)/2,dy=(ay+by)/2;const ex=(bx+cx)/2,ey=(by+cy)/2;const fx=(dx+ex)/2,fy=(dy+ey)/2;return[[p[0],p[1],ax,ay,dx,dy,fx,fy],[fx,fy,ex,ey,cx,cy,p[6],p[7]]]}function bestRotation(a,b){const count=segmentCount(b);if(!a.closed||!b.closed||count<2)return b;const[ax,ay]=ringCenter(a),[bx,by]=ringCenter(b);const stride=Math.max(1,Math.floor(count/48));let best=0,bestCost=Infinity;for(let shift2=0;shift2<count;shift2+=stride){let cost=0;for(let i=0;i<count;i+=stride){const j=(i+shift2)%count;const dx=a.p[i*6]-ax-(b.p[j*6]-bx);const dy=a.p[i*6+1]-ay-(b.p[j*6+1]-by);cost+=dx*dx+dy*dy}if(cost<bestCost){bestCost=cost;best=shift2}}if(best===0)return b;const out=new Float64Array(b.p.length);out[0]=b.p[best*6];out[1]=b.p[best*6+1];for(let i=0;i<count;i++){const j=(i+best)%count;for(let k=0;k<6;k++)out[2+i*6+k]=b.p[2+j*6+k]}return{p:out,closed:b.closed}}function pointRing(x,y,count,closed){const out=new Float64Array(2+count*6);for(let i=0;i<out.length;i+=2){out[i]=x;out[i+1]=y}return{p:out,closed}}function pairRings(from,to2){const rank=path=>[...path].sort((a2,b2)=>Math.abs(signedArea(b2))+ringLength(b2)*.01-(Math.abs(signedArea(a2))+ringLength(a2)*.01));const a=rank(from),b=rank(to2);const pairs=[];const free=b.slice();for(const ringA of a){if(free.length===0){const[x,y]=ringCenter(ringA);pairs.push([ringA,pointRing(x,y,segmentCount(ringA),ringA.closed)]);continue}const[ax,ay]=ringCenter(ringA);let bestIndex=0,bestCost=Infinity;for(let i=0;i<Math.min(free.length,3);i++){const[bx,by]=ringCenter(free[i]);const cost=Math.hypot(ax-bx,ay-by)+i*40;if(cost<bestCost){bestCost=cost;bestIndex=i}}pairs.push([ringA,free[bestIndex]]);free.splice(bestIndex,1)}for(const ringB of free){const[x,y]=ringCenter(ringB);pairs.push([pointRing(x,y,segmentCount(ringB),ringB.closed),ringB])}return pairs}function alignPaths(from,to2,minSegments=12){const pairs=pairRings(from,to2);const a=[],b=[],closed=[];for(const[ra,rb]of pairs){const target=Math.max(segmentCount(ra),segmentCount(rb),ra.closed&&rb.closed?minSegments:1);let x=growTo(ra,target);let y=growTo(rb,target);if(x.closed&&y.closed){if(Math.sign(signedArea(x))!==Math.sign(signedArea(y))&&signedArea(x)!==0&&signedArea(y)!==0)y=reverseRing(y);y=bestRotation(x,y)}else if(!x.closed&&!y.closed){const n=x.p.length;const straight=Math.hypot(x.p[0]-y.p[0],x.p[1]-y.p[1])+Math.hypot(x.p[n-2]-y.p[n-2],x.p[n-1]-y.p[n-1]);const flipped=Math.hypot(x.p[0]-y.p[n-2],x.p[1]-y.p[n-1])+Math.hypot(x.p[n-2]-y.p[0],x.p[n-1]-y.p[1]);if(flipped<straight)y=reverseRing(y)}a.push(x.p);b.push(y.p);closed.push(x.closed&&y.closed)}return{from:a,to:b,closed}}function pathMixer(from,to2){if(from===to2)return()=>to2;if(pathLength(from)===0&&from.length===0)return alpha2=>alpha2>=1?to2:from;const aligned=alignPaths(from,to2);return alpha2=>{if(alpha2<=0)return from;if(alpha2>=1)return to2;const rings=new Array(aligned.from.length);for(let r=0;r<rings.length;r++){const a=aligned.from[r],b=aligned.to[r];const out=new Float64Array(a.length);for(let i=0;i<a.length;i++)out[i]=a[i]+(b[i]-a[i])*alpha2;rings[r]={p:out,closed:aligned.closed[r]}}return rings}}function matchSequence(a,b){const n=a.length,m=b.length;const table=Array.from({length:n+1},()=>new Uint16Array(m+1));for(let i2=n-1;i2>=0;i2--){for(let j2=m-1;j2>=0;j2--){table[i2][j2]=a[i2]===b[j2]?table[i2+1][j2+1]+1:Math.max(table[i2+1][j2],table[i2][j2+1])}}const pairs=[];let i=0,j=0;while(i<n&&j<m){if(a[i]===b[j]){pairs.push([i++,j++])}else if(table[i+1][j]>=table[i][j+1]){i++}else{j++}}return pairs}var DEFAULT_PROPS={x:0,y:0,rotation:0,sx:1,sy:1,px:0,py:0,opacity:1,visible:true,z:0,path:null,fill:null,fillOpacity:1,stroke:null,strokeOpacity:1,strokeWidth:3,cap:"round",join:"round",dash:null,dashOffset:0,trimFrom:0,trimTo:1,trimEach:false,glow:0,glowColor:null,blend:"normal",fixed:false,image:null};var NUMERIC=new Set(["x","y","rotation","sx","sy","px","py","opacity","z","fillOpacity","strokeOpacity","strokeWidth","dashOffset","trimFrom","trimTo","glow"]);function mixer(prop,from,to2){if(NUMERIC.has(prop)){const a=from,b=to2;return(alpha2=>a+(b-a)*alpha2)}if(prop==="fill"||prop==="stroke"){const a=from,b=to2;if(a&&b)return(alpha2=>mixPaint(a,b,alpha2));return null}if(prop==="glowColor"){const a=from,b=to2;if(a&&b)return(alpha2=>mixColor(a,b,alpha2));return null}if(prop==="path"){const a=from,b=to2;if(a&&b)return pathMixer(a,b);return null}return null}var nextId=1;var Node=class _Node{id=nextId++;parent=null;children=[];data={};label="";base=Object.create(DEFAULT_PROPS);tracks=null;overlay=null;overlayFrame=-1;mounted=false;draw=null;rawOps=null;constructor(path){if(path)this.base.path=path}get(prop){const overlay=this.overlay;if(overlay!==null&&overlay.has(prop)&&(this.overlayFrame===clock.frame||clock.capture!==null)){return overlay.get(prop)}const track=this.tracks?.get(prop);if(track)return track.sample(clock.now);return this.base[prop]}set(prop,value){if(clock.capture){this.overlay??=new Map;this.overlay.set(prop,value);clock.capture.add(this);return this}if(!this.mounted){this.base[prop]=value;return this}if(clock.mode==="render"){this.overlay??=new Map;if(this.overlayFrame!==clock.frame){this.overlay.clear();this.overlayFrame=clock.frame}this.overlay.set(prop,value);return this}this.track(prop).step(clock.now,value);return this}track(prop){this.tracks??=new Map;let track=this.tracks.get(prop);if(!track){track=new Track(this.base[prop]);this.tracks.set(prop,track)}return track}tween(prop,to2,t0,t1,ease){const previous=clock.now;clock.now=t0;const from=this.get(prop);clock.now=previous;const at=t1>t0?mixer(prop,from,to2):null;const key={t0,t1,ease,to:to2,at};this.track(prop).add(key)}add(...nodes){for(const child of nodes){if(child.parent===this)continue;child.parent?.drop(child);child.parent=this;this.children.push(child);if(this.mounted)mountTree(child,clock.now)}return this}drop(child){const index=this.children.indexOf(child);if(index>=0)this.children.splice(index,1);child.parent=null;return this}all(){const out=[];const visit=node=>{out.push(node);for(const child of node.children)visit(child)};visit(this);return out}leaves(){return this.all().filter(node=>node.get("path")!==null||node.draw!==null||node.get("image")!==null)}clone(){const copy=Object.create(Object.getPrototypeOf(this));Object.assign(copy,this);copy.id=nextId++;copy.parent=null;copy.mounted=false;copy.tracks=null;copy.overlay=null;copy.overlayFrame=-1;copy.data={...this.data};copy.base=Object.create(DEFAULT_PROPS);for(const key of Object.keys(DEFAULT_PROPS)){;copy.base[key]=this.get(key)}copy.children=this.children.map(child=>{const next=child.clone();next.parent=copy;return next});return copy}localMatrix(){return compose(this.get("x"),this.get("y"),this.get("rotation"),this.get("sx"),this.get("sy"),this.get("px"),this.get("py"))}worldMatrix(){let m=this.localMatrix();for(let node=this.parent;node;node=node.parent)m=mul(node.localMatrix(),m);return m}toWorld(x,y){return apply(this.worldMatrix(),x,y)}bounds(){return this.boundsFrom(this.parent?this.parent.worldMatrix():IDENTITY)??{x:0,y:0,width:0,height:0}}boundsFrom(parent){const m=mul(parent,this.localMatrix());let result=null;const path=this.get("path");if(path)result=pathBounds(transformPath(path,m));const image=this.get("image");if(image)result=unionBounds(result,boundsOfRect(m,image.width,image.height));if(this.draw){const built=this.draw(clock.now);const list3=built===null?[]:Array.isArray(built)?built:[built];for(const child of list3)result=unionBounds(result,child.boundsFrom(m))}for(const child of this.children){if(child.get("visible"))result=unionBounds(result,child.boundsFrom(m))}return result}get center(){const b=this.bounds();return[b.x+b.width/2,b.y+b.height/2]}get top(){const b=this.bounds();return[b.x+b.width/2,b.y]}get bottom(){const b=this.bounds();return[b.x+b.width/2,b.y+b.height]}get left(){const b=this.bounds();return[b.x,b.y+b.height/2]}get right(){const b=this.bounds();return[b.x+b.width,b.y+b.height/2]}get width(){return this.bounds().width}get height(){return this.bounds().height}at(x,y){const[px,py]=typeof x==="number"?[x,y??0]:x;this.set("x",px);this.set("y",py);return this}shift(dx,dy){const[ox,oy]=typeof dx==="number"?[dx,dy??0]:dx;this.set("x",this.get("x")+ox);this.set("y",this.get("y")+oy);return this}moveTo(target){const destination=target instanceof _Node?target.center:target;const[cx,cy]=this.center;const inverse=this.parent?invert(this.parent.worldMatrix()):IDENTITY;const[lx0,ly0]=apply(inverse,cx,cy);const[lx1,ly1]=apply(inverse,destination[0],destination[1]);return this.shift(lx1-lx0,ly1-ly0)}pivotAt(point){const parent=this.parent?this.parent.worldMatrix():IDENTITY;const before=mul(parent,this.localMatrix());const[lx,ly]=apply(invert(before),point[0],point[1]);const[nx,ny]=apply(invert(parent),point[0],point[1]);this.set("px",lx);this.set("py",ly);this.set("x",nx);this.set("y",ny);return this}scale(factor,about){const[fx,fy]=typeof factor==="number"?[factor,factor]:factor;this.pivotAt(about??this.center);this.set("sx",this.get("sx")*fx);this.set("sy",this.get("sy")*fy);return this}rotate(radians,about){this.pivotAt(about??this.center);this.set("rotation",this.get("rotation")+radians);return this}fitTo(size){const b=this.bounds();const scales=[];if(size.width!==void 0&&b.width>0)scales.push(size.width/b.width);if(size.height!==void 0&&b.height>0)scales.push(size.height/b.height);return scales.length?this.scale(Math.min(...scales)):this}nextTo(target,side="right",gap=28){const[dx,dy]=direction(side);const b=target instanceof _Node?target.bounds():{x:target[0],y:target[1],width:0,height:0};const own=this.bounds();const cx=b.x+b.width/2,cy=b.y+b.height/2;const anchorX=cx+dx*(b.width/2+gap+own.width/2);const anchorY=cy+dy*(b.height/2+gap+own.height/2);return this.moveTo([anchorX,anchorY])}alignTo(target,edge){const own=this.bounds();const b=target instanceof _Node?target.bounds():{x:target[0],y:target[1],width:0,height:0};if(edge==="left")return this.shift(b.x-own.x,0);if(edge==="right")return this.shift(b.x+b.width-own.x-own.width,0);if(edge==="top")return this.shift(0,b.y-own.y);return this.shift(0,b.y+b.height-own.y-own.height)}arrange(side="right",gap=24){const[dx,dy]=direction(side);const center2=this.center;let previous=null;for(const child of this.children){if(previous){const b=previous.bounds(),own=child.bounds();const px=b.x+b.width/2+dx*(b.width/2+gap+own.width/2);const py=b.y+b.height/2+dy*(b.height/2+gap+own.height/2);child.moveTo([dx===0?b.x+b.width/2:px,dy===0?b.y+b.height/2:py])}previous=child}return this.moveTo(center2)}fill(color,opacity){this.set("fill",color===null?null:toPaint(color));if(opacity!==void 0)this.set("fillOpacity",opacity);return this}stroke(color,width,opacity){this.set("stroke",color===null?null:toPaint(color));if(width!==void 0)this.set("strokeWidth",width);if(opacity!==void 0)this.set("strokeOpacity",opacity);return this}color(color){const paint=toPaint(color);for(const node of this.all()){if(node.get("stroke"))node.set("stroke",paint);if(node.get("fill"))node.set("fill",paint);if(node.get("glowColor")&&!isGradient(paint))node.set("glowColor",paint)}return this}opacity(value){return this.set("opacity",value)}glow(radius,color){this.set("glow",radius);if(color!==void 0){const paint=toPaint(color);this.set("glowColor",isGradient(paint)?null:paint)}return this}dash(pattern,offset=0){this.set("dash",pattern);return this.set("dashOffset",offset)}zIndex(value){return this.set("z",value)}pin(){return this.set("fixed",true)}hide(){return this.set("visible",false)}show(){return this.set("visible",true)}named(label){this.label=label;return this}};function boundsOfRect(m,width,height){const corners=[apply(m,0,0),apply(m,width,0),apply(m,width,height),apply(m,0,height)];const xs=corners.map(c=>c[0]),ys=corners.map(c=>c[1]);const x=Math.min(...xs),y=Math.min(...ys);return{x,y,width:Math.max(...xs)-x,height:Math.max(...ys)-y}}function direction(side){if(typeof side!=="string")return side;if(side==="left")return[-1,0];if(side==="right")return[1,0];if(side==="top"||side==="up")return[0,-1];return[0,1]}function mountTree(node,time){const wasVisible=node.base.visible;for(const entry of node.all())entry.mounted=true;if(time>0||!wasVisible){const track=node.track("visible");track.initial=false;if(wasVisible)track.step(time,true)}}function group(...children){return new Node().add(...children)}function dynamic(build){const node=new Node;node.draw=build;return node}function list(target){return Array.isArray(target)?[...target]:[target]}function run(anim,t0,t1,parent){clock.now=t0;anim.schedule({t0,t1,ease:anim.ease??parent.ease,stage:parent.stage})}function par(...anims){const duration=Math.max(0,...anims.map(a=>a.duration));return{label:"par",duration,schedule(ctx){const k=duration>0?(ctx.t1-ctx.t0)/duration:1;for(const anim of anims)run(anim,ctx.t0,ctx.t0+anim.duration*k,ctx)}}}function seq(...anims){const duration=anims.reduce((sum,a)=>sum+a.duration,0);return{label:"seq",duration,schedule(ctx){const k=duration>0?(ctx.t1-ctx.t0)/duration:1;let t=ctx.t0;for(const anim of anims){const next=t+anim.duration*k;run(anim,t,next,ctx);t=next}}}}function lagged(anims,options={}){const lag=options.lag??.15;const longest=Math.max(0,...anims.map(a=>a.duration));const natural=anims.length===0?0:longest*(1+(anims.length-1)*lag);return{label:"lagged",duration:options.duration??natural,schedule(ctx){const total=ctx.t1-ctx.t0;const each=anims.length===0?0:total/(1+(anims.length-1)*lag);anims.forEach((anim,i)=>{const start=ctx.t0+i*lag*each;run(anim,start,start+each,ctx)})}}}function delay(anim,seconds){return{label:anim.label,duration:anim.duration+seconds,ease:anim.ease,schedule(ctx){const k=anim.duration+seconds>0?(ctx.t1-ctx.t0)/(anim.duration+seconds):1;run(anim,ctx.t0+seconds*k,ctx.t1,ctx)}}}function retime(anim,options){return{...anim,duration:options.duration??anim.duration,ease:options.ease??anim.ease}}function call(fn){return{label:"call",duration:0,schedule:()=>fn()}}function ensureVisible(node,t,stage){if(!node.mounted){let top=node;while(top.parent&&top.parent!==stage.root)top=top.parent;stage.mountAt(top,t)}for(let n=node;n&&n!==stage.root;n=n.parent){const previous=clock.now;clock.now=t;const visible=n.get("visible");clock.now=previous;if(!visible)n.track("visible").step(t,true)}}function hideAt(node,t){node.track("visible").step(t,false)}function holdUntil(node,t0,start){if(start<=t0)return;node.track("visible").step(t0,false);node.track("visible").step(start,true)}var stepAt=(node,prop,value,t)=>{node.track(prop).step(t,value)};function valueAt(node,prop,t){const previous=clock.now;clock.now=t;const value=node.get(prop);clock.now=previous;return value}function solid2(paint){return isGradient(paint)?sampleStops(paint.stops,.5):paint}function drawable(target){return list(target).flatMap(node=>node.leaves().filter(leaf=>leaf.get("path")))}function drawLeaf(leaf,t0,t1,ease,outline){const d=t1-t0;const fill=leaf.get("fill"),stroke=leaf.get("stroke");const fillTarget=leaf.get("fillOpacity");const strokeTarget=leaf.get("strokeOpacity");if(fill&&!stroke){const width=valueAt(leaf,"strokeWidth",t0);stepAt(leaf,"stroke",solid2(fill),t0);stepAt(leaf,"strokeWidth",outline,t0);stepAt(leaf,"strokeOpacity",1,t0);stepAt(leaf,"trimTo",0,t0);stepAt(leaf,"fillOpacity",0,t0);leaf.tween("trimTo",1,t0,t0+d*.72,ease);leaf.tween("fillOpacity",fillTarget,t0+d*.42,t1,ease);leaf.tween("strokeOpacity",0,t0+d*.62,t1,ease);stepAt(leaf,"stroke",null,t1);stepAt(leaf,"strokeWidth",width,t1);stepAt(leaf,"strokeOpacity",strokeTarget,t1);return}stepAt(leaf,"trimTo",0,t0);leaf.tween("trimTo",1,t0,fill?t0+d*.8:t1,ease);if(fill){stepAt(leaf,"fillOpacity",0,t0);leaf.tween("fillOpacity",fillTarget,t0+d*.5,t1,ease)}}function drawAnim(label,target,options,defaults){const nodes=list(target);const count=drawable(nodes).length;const lag=options.lag??defaults.lag;const natural=options.duration??(count<=1?defaults.duration:Math.min(defaults.duration*2.4,defaults.duration+count*.035));return{label,duration:natural,ease:options.ease,schedule(ctx){for(const node of nodes)ensureVisible(node,ctx.t0,ctx.stage);const leaves=drawable(nodes);if(leaves.length===0)return;const total=ctx.t1-ctx.t0;const each=total/(1+(leaves.length-1)*lag);leaves.forEach((leaf,i)=>{const start=ctx.t0+i*lag*each;clock.now=start;holdUntil(leaf,ctx.t0,start);drawLeaf(leaf,start,start+each,ctx.ease,defaults.outline)});clock.now=ctx.t0}}}function draw(target,options={}){return drawAnim("draw",target,options,{lag:.04,duration:1.3,outline:2})}function write(target,options={}){return drawAnim("write",target,options,{lag:.22,duration:1.1,outline:1.3})}function erase(target,options={}){const nodes=list(target);return{label:"erase",duration:options.duration??.8,ease:options.ease,schedule(ctx){const leaves=drawable(nodes);const lag=options.lag??.02;const each=(ctx.t1-ctx.t0)/(1+Math.max(0,leaves.length-1)*lag);leaves.forEach((leaf,i)=>{const start=ctx.t0+i*lag*each;clock.now=start;const fill=leaf.get("fill");if(leaf.get("stroke"))leaf.tween("trimFrom",1,start,start+each,ctx.ease);if(fill)leaf.tween("fillOpacity",0,start,start+each*.7,ctx.ease)});for(const node of nodes)hideAt(node,ctx.t1)}}}function fadeIn(target,options={}){const nodes=list(target);return{label:"fadeIn",duration:options.duration??.8,ease:options.ease,schedule(ctx){const items=options.lag!==void 0&&nodes.length===1&&nodes[0].children.length>0?nodes[0].children:nodes;for(const node of nodes)ensureVisible(node,ctx.t0,ctx.stage);const lag=options.lag??0;const each=(ctx.t1-ctx.t0)/(1+Math.max(0,items.length-1)*lag);items.forEach((node,i)=>{const start=ctx.t0+i*lag*each,end=start+each;clock.now=start;holdUntil(node,ctx.t0,start);const opacity=node.get("opacity");stepAt(node,"opacity",0,start);node.tween("opacity",opacity,start,end,ctx.ease);if(options.shift){const x=node.get("x"),y=node.get("y");stepAt(node,"x",x+options.shift[0],start);stepAt(node,"y",y+options.shift[1],start);node.tween("x",x,start,end,ctx.ease);node.tween("y",y,start,end,ctx.ease)}if(options.scale!==void 0)scaleFrom(node,options.scale,start,end,ctx.ease)});clock.now=ctx.t0}}}function scaleFrom(node,factor,t0,t1,ease,about){const previous=clock.now;clock.now=t0;node.pivotAt(about??node.center);const sx=node.get("sx"),sy=node.get("sy");stepAt(node,"sx",sx*factor,t0);stepAt(node,"sy",sy*factor,t0);node.tween("sx",sx,t0,t1,ease);node.tween("sy",sy,t0,t1,ease);clock.now=previous}function fadeOut(target,options={}){const nodes=list(target);return{label:"fadeOut",duration:options.duration??.6,ease:options.ease,schedule(ctx){for(const node of nodes){const opacity=node.get("opacity");node.tween("opacity",0,ctx.t0,ctx.t1,ctx.ease);if(options.shift){node.tween("x",node.get("x")+options.shift[0],ctx.t0,ctx.t1,ctx.ease);node.tween("y",node.get("y")+options.shift[1],ctx.t0,ctx.t1,ctx.ease)}if(options.scale!==void 0){node.pivotAt(node.center);node.tween("sx",node.get("sx")*options.scale,ctx.t0,ctx.t1,ctx.ease);node.tween("sy",node.get("sy")*options.scale,ctx.t0,ctx.t1,ctx.ease)}hideAt(node,ctx.t1);stepAt(node,"opacity",opacity,ctx.t1)}}}}function grow(target,options={}){const nodes=list(target);return{label:"grow",duration:options.duration??.9,ease:options.ease,schedule(ctx){for(const node of nodes){ensureVisible(node,ctx.t0,ctx.stage);scaleFrom(node,.001,ctx.t0,ctx.t1,ctx.ease,options.from)}}}}function appear(target){const nodes=list(target);return{label:"appear",duration:0,schedule:ctx=>{for(const node of nodes)ensureVisible(node,ctx.t0,ctx.stage)}}}function vanish(target){const nodes=list(target);return{label:"vanish",duration:0,schedule:ctx=>{for(const node of nodes)hideAt(node,ctx.t0)}}}function to(node,change,options={}){return{label:"to",duration:options.duration??1,ease:options.ease,schedule(ctx){ensureVisible(node,ctx.t0,ctx.stage);const touched=new Set;clock.capture=touched;try{change(node)}finally{clock.capture=null}for(const entry of touched){const target=entry;const values=new Map(target.overlay);target.overlay.clear();applyChanges(target,values,ctx,options.restore===true)}}}}function applyChanges(node,values,ctx,restore){const{t0,t1,ease}=ctx;const props=values;const restoreValues=new Map;const px=props.get("px"),py=props.get("py");if(px!==void 0||py!==void 0){const nextPx=px??node.get("px"),nextPy=py??node.get("py");const m=compose(node.get("x"),node.get("y"),node.get("rotation"),node.get("sx"),node.get("sy"),node.get("px"),node.get("py"));const[startX,startY]=apply(m,nextPx,nextPy);stepAt(node,"px",nextPx,t0);stepAt(node,"py",nextPy,t0);stepAt(node,"x",startX,t0);stepAt(node,"y",startY,t0);props.delete("px");props.delete("py")}clock.now=t0;for(const[prop,value]of props){const from=node.get(prop);if(from===value)continue;if(restore)restoreValues.set(prop,from);node.tween(prop,value,t0,t1,ease)}for(const[prop,value]of restoreValues)stepAt(node,prop,value,t1)}function moveTo(node,target,options={}){return{...to(node,n=>n.moveTo(target),options),label:"moveTo"}}function shift(node,dx,dy,options={}){return{...to(node,n=>n.shift(dx,dy),options),label:"shift"}}function scaleBy(node,factor,options={}){return{...to(node,n=>n.scale(factor,options.about),options),label:"scale"}}function rotate(node,radians,options={}){return{...to(node,n=>n.rotate(radians,options.about),options),label:"rotate"}}function recolor(node,color,options={}){return{...to(node,n=>n.color(color),options),label:"recolor"}}function fade(node,opacity,options={}){return{...to(node,n=>n.opacity(opacity),{duration:.6,...options}),label:"fade"}}function along2(node,track,options={}){return{label:"along",duration:options.duration??2,ease:options.ease,schedule(ctx){ensureVisible(node,ctx.t0,ctx.stage);const path=track instanceof Node?transformPath(track.get("path")??[],track.worldMatrix()):track;const inverse=node.parent?invertSafe(node.parent.worldMatrix()):null;const position2=alpha2=>{const[x,y]=pointAt(path,alpha2);return inverse?apply(inverse,x,y):[x,y]};const[endX,endY]=position2(1);node.track("x").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:endX,at:a=>position2(a)[0]});node.track("y").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:endY,at:a=>position2(a)[1]});if(options.orient){const angle=alpha2=>{const[dx,dy]=tangentAt(path,alpha2);return Math.atan2(dy,dx)};node.track("rotation").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:angle(1),at:angle})}}}}function invertSafe(m){const det=m[0]*m[3]-m[1]*m[2];if(Math.abs(det)<1e-12)return[1,0,0,1,0,0];const i=1/det;return[m[3]*i,-m[1]*i,-m[2]*i,m[0]*i,(m[2]*m[5]-m[3]*m[4])*i,(m[1]*m[4]-m[0]*m[5])*i]}function warp(target,f,options={}){const nodes=list(target);return{label:"warp",duration:options.duration??2,ease:options.ease,schedule(ctx){for(const leaf of drawable(nodes)){ensureVisible(leaf,ctx.t0,ctx.stage);const path=leaf.get("path");const world=leaf.worldMatrix();const inverse=invertSafe(world);const start=path.map(r=>subdivideEach(r,options.subdivisions??6));const end=warpPath(start,(x,y)=>{const[wx,wy]=apply(world,x,y);const[mx,my]=f(wx,wy);return apply(inverse,mx,my)},1);leaf.track("path").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:end,at:alpha2=>start.map((r,i)=>{const a=r.p,b=end[i].p;const out=new Float64Array(a.length);for(let k=0;k<a.length;k++)out[k]=a[k]+(b[k]-a[k])*alpha2;return{p:out,closed:r.closed}})})}}}}function applyMatrix(target,matrix2,options={}){const[ox,oy]=options.origin??[0,0];const flip=options.yUp===false?1:-1;const[[a,b],[c,d]]=matrix2;return{...warp(target,(x,y)=>{const ux=x-ox,uy=(y-oy)*flip;const vx=a*ux+b*uy,vy=c*ux+d*uy;return[ox+vx,oy+vy*flip]},{subdivisions:1,...options}),label:"applyMatrix"}}function chainOpacity(node){let value=1;for(let n=node;n;n=n.parent)value*=n.get("opacity");return value}function bake(leaf){const m=leaf.worldMatrix();const opacity=chainOpacity(leaf);let z=0;let fixed=false;for(let n=leaf;n;n=n.parent){z+=n.get("z");fixed||=n.get("fixed")}return{path:transformPath(leaf.get("path")??[],m),fill:leaf.get("fill"),fillOpacity:leaf.get("fill")?leaf.get("fillOpacity")*opacity:0,stroke:leaf.get("stroke"),strokeOpacity:leaf.get("stroke")?leaf.get("strokeOpacity")*opacity:0,strokeWidth:leaf.get("strokeWidth")*matScale(m),glow:leaf.get("glow"),glowColor:leaf.get("glowColor"),cap:leaf.get("cap"),dash:leaf.get("dash"),z,fixed,key:leaf.data["key"]}}function ghost(stage,from,to2,ctx){const node=new Node;node.base.visible=false;node.base.path=from.path;node.base.cap=from.cap;node.base.z=from.z;node.base.fixed=from.fixed;node.base.fill=from.fill??to2.fill;node.base.stroke=from.stroke??to2.stroke;node.base.fillOpacity=from.fillOpacity;node.base.strokeOpacity=from.strokeOpacity;node.base.strokeWidth=from.strokeWidth||to2.strokeWidth;node.base.glow=from.glow;node.base.glowColor=from.glowColor??to2.glowColor;stage.root.add(node);node.track("visible").initial=false;node.track("visible").keys.length=0;stepAt(node,"visible",true,ctx.appear??ctx.t0);node.track("path").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:to2.path,at:pathMixer(from.path,to2.path)});if(from.fill&&to2.fill)node.tween("fill",to2.fill,ctx.t0,ctx.t1,ctx.ease);if(from.stroke&&to2.stroke)node.tween("stroke",to2.stroke,ctx.t0,ctx.t1,ctx.ease);node.tween("fillOpacity",to2.fillOpacity,ctx.t0,ctx.t1,ctx.ease);node.tween("strokeOpacity",to2.strokeOpacity,ctx.t0,ctx.t1,ctx.ease);node.tween("strokeWidth",to2.strokeWidth||from.strokeWidth,ctx.t0,ctx.t1,ctx.ease);if(from.glow!==to2.glow)node.tween("glow",to2.glow,ctx.t0,ctx.t1,ctx.ease);stepAt(node,"visible",false,ctx.t1);return node}function pairCounts(from,to2){const count=Math.max(from.length,to2.length);const pairs=[];for(let i=0;i<count;i++){pairs.push([from[Math.min(from.length-1,Math.floor(i*from.length/count))],to2[Math.min(to2.length-1,Math.floor(i*to2.length/count))]])}return pairs}function morph(from,to2,options={}){const a=list(from),b=list(to2);return{label:"morph",duration:options.duration??1.2,ease:options.ease,schedule(ctx){prepareTargets(b,ctx);const fromLeaves=drawable(a).map(bake);const toLeaves=drawable(b).map(bake);if(fromLeaves.length===0||toLeaves.length===0){for(const node of a)hideAt(node,ctx.t0);for(const node of b)ensureVisible(node,ctx.t0,ctx.stage);return}const pairs=pairCounts(fromLeaves,toLeaves);const lag=options.lag??0;const each=(ctx.t1-ctx.t0)/(1+Math.max(0,pairs.length-1)*lag);pairs.forEach(([x,y],i)=>{const start=ctx.t0+i*lag*each;ghost(ctx.stage,x,y,{t0:start,t1:start+each,ease:ctx.ease,appear:ctx.t0})});finishMorph(a,b,ctx)}}}function prepareTargets(targets,ctx){clock.now=ctx.t0;for(const node of targets){ctx.stage.mountAt(node,ctx.t0);hideAt(node,ctx.t0)}}function finishMorph(a,b,ctx){for(const node of a)hideAt(node,ctx.t0);for(const node of b)node.track("visible").step(ctx.t1,true);clock.now=ctx.t0}function morphMatching(from,to2,options={}){return{label:"morphMatching",duration:options.duration??1.4,ease:options.ease,schedule(ctx){prepareTargets([to2],ctx);const keyOf=options.key??(leaf=>leaf.data["key"]);const fromLeaves=drawable(from),toLeaves=drawable(to2);const fromBaked=fromLeaves.map(bake),toBaked=toLeaves.map(bake);const pairs=matchSequence(fromLeaves.map(keyOf),toLeaves.map(keyOf));const usedFrom=new Set(pairs.map(([i])=>i)),usedTo=new Set(pairs.map(([,j])=>j));for(const[i,j]of pairs)ghost(ctx.stage,fromBaked[i],toBaked[j],ctx);const span=ctx.t1-ctx.t0;const offset=options.fadeShift??[0,0];const shifted=(bakedPath,dx,dy)=>transformPath(bakedPath,[1,0,0,1,dx,dy]);fromBaked.forEach((baked,i)=>{if(usedFrom.has(i))return;ghost(ctx.stage,baked,{...baked,path:shifted(baked.path,offset[0],offset[1]),fillOpacity:0,strokeOpacity:0},{t0:ctx.t0,t1:ctx.t0+span*.55,ease:ctx.ease})});toBaked.forEach((baked,j)=>{if(usedTo.has(j))return;ghost(ctx.stage,{...baked,path:shifted(baked.path,-offset[0],-offset[1]),fillOpacity:0,strokeOpacity:0},baked,{t0:ctx.t0+span*.35,t1:ctx.t1,ease:ctx.ease})});finishMorph([from],[to2],ctx)}}}function indicate(target,options={}){const nodes=list(target);const anims=nodes.map(node=>retime(to(node,n=>{n.scale(options.scale??1.14);n.color(options.color??"yellow")},{restore:true}),{ease:options.ease??thereAndBack}));return{...par(...anims),label:"indicate",duration:options.duration??.9}}function shake(node,options={}){return{label:"shake",duration:options.duration??.8,ease:wiggle(options.cycles??3),schedule(ctx){clock.now=ctx.t0;const[cx,cy]=node.center;node.pivotAt([cx,cy]);const rotation=node.get("rotation");const angle=options.angle??.08;const track=node.track("rotation");track.add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:rotation,at:alpha2=>rotation+angle*alpha2})}}}function circumscribe(target,options={}){return{label:"circumscribe",duration:options.duration??1.3,ease:options.ease??linear,schedule(ctx){const b=target.bounds();const pad2=options.pad??14;const outline=new Node(rectPath(b.x-pad2,b.y-pad2,b.width+pad2*2,b.height+pad2*2,options.radius??12)).stroke(options.color??"yellow",options.width??3).glow(8);ctx.stage.add(outline);const t0=ctx.t0,t1=ctx.t1,mid=t0+(t1-t0)*.55;stepAt(outline,"trimTo",0,t0);outline.tween("trimTo",1,t0,mid,smooth2);outline.tween("trimFrom",1,mid-(t1-t0)*.08,t1,smooth2);hideAt(outline,t1)}}}function flash(point,options={}){return{label:"flash",duration:options.duration??.7,ease:options.ease??smooth2,schedule(ctx){const center2=point instanceof Node?point.center:point;const radius=options.radius??54;const rays=options.rays??12;for(let i=0;i<rays;i++){const angle=i/rays*Math.PI*2;const cos=Math.cos(angle),sin=Math.sin(angle);const ray=new Node(linePath([center2[0]+cos*radius*.35,center2[1]+sin*radius*.35],[center2[0]+cos*radius,center2[1]+sin*radius])).stroke(options.color??"yellow",2.5).glow(5);ctx.stage.add(ray);stepAt(ray,"trimTo",0,ctx.t0);ray.tween("trimTo",1,ctx.t0,ctx.t0+(ctx.t1-ctx.t0)*.6,ctx.ease);ray.tween("trimFrom",1,ctx.t0+(ctx.t1-ctx.t0)*.25,ctx.t1,ctx.ease);hideAt(ray,ctx.t1)}}}}function ripple(point,options={}){return{label:"ripple",duration:options.duration??1,ease:options.ease??smooth2,schedule(ctx){const center2=point instanceof Node?point.center:point;const ring2=new Node(circlePath(0,0,options.radius??90)).stroke(options.color??"blue",options.width??3).at(center2);ctx.stage.add(ring2);stepAt(ring2,"sx",.05,ctx.t0);stepAt(ring2,"sy",.05,ctx.t0);ring2.tween("sx",1,ctx.t0,ctx.t1,ctx.ease);ring2.tween("sy",1,ctx.t0,ctx.t1,ctx.ease);ring2.tween("strokeOpacity",0,ctx.t0+(ctx.t1-ctx.t0)*.2,ctx.t1,ctx.ease);hideAt(ring2,ctx.t1)}}}function pulse(line2,options={}){return{label:"pulse",duration:options.duration??1.1,ease:options.ease??smooth2,schedule(ctx){const path=line2.get("path");if(!path)return;const lit=new Node(transformPath(path,line2.worldMatrix())).stroke(options.color??"yellow",options.width??line2.get("strokeWidth")+1.5).glow(options.glow??10);ctx.stage.add(lit);const length=options.length??.18;stepAt(lit,"trimFrom",0,ctx.t0);stepAt(lit,"trimTo",0,ctx.t0);lit.track("trimTo").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:1,at:a=>Math.min(1,a*(1+length))});lit.track("trimFrom").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:1,at:a=>Math.max(0,a*(1+length)-length)});hideAt(lit,ctx.t1)}}}var Value=class{track;constructor(initial){this.track=new Track(initial)}get value(){return this.track.sample(clock.now)}set(value){this.track.step(clock.now,value);return this}to(value,options={}){const track=this.track;return{label:"value",duration:options.duration??1,ease:options.ease,schedule(ctx){const from=track.sample(ctx.t0);track.add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:value,at:a=>from+(value-from)*a})}}}};var ASPECTS={"16:9":[1920,1080],"9:16":[1080,1920],"1:1":[1080,1080],"4:3":[1440,1080],"21:9":[2520,1080]};var Stage=class{root=new Node;camera=new Node;width;height;fps;look;chapters=[];clips=[];captions=[];updaters=[];time=0;ending=0;constructor(options){const[w,h]=ASPECTS[options.aspect??"16:9"];this.width=options.width??w;this.height=options.height??h;this.fps=options.fps??60;this.look=resolveLook(options.look);this.root.mounted=true;this.camera.mounted=true}get right(){return this.width/2}get left(){return-this.width/2}get top(){return-this.height/2}get bottom(){return this.height/2}add(first,...rest){clock.now=this.time;for(const node of[first,...rest]){if(!node.mounted){node.parent?.drop(node);node.parent=this.root;this.root.children.push(node);mountTree(node,this.time)}else if(!node.get("visible")){node.track("visible").step(this.time,true)}}return first}mountAt(node,time){if(node.mounted)return;node.parent?.drop(node);node.parent=this.root;this.root.children.push(node);mountTree(node,time)}remove(...nodes){for(const node of nodes)node.track("visible").step(this.time,false)}play(...items){const anims=items.filter(item=>"schedule"in item);const options=items.find(item=>!("schedule"in item))??{};if(anims.length===0)return this;const natural=Math.max(...anims.map(anim=>anim.duration));const duration=options.duration??natural;const t0=this.time;const t1=t0+duration;for(const anim of anims){clock.now=t0;const end=options.duration!==void 0?t1:t0+anim.duration;anim.schedule({t0,t1:end,ease:options.ease??anim.ease??smooth2,stage:this})}this.clips.push({t0,t1,labels:options.label?[options.label]:anims.map(anim=>anim.label)});this.time=t1;this.ending=Math.max(this.ending,t1);clock.now=t1;return this}wait(seconds=1){this.time+=seconds;this.ending=Math.max(this.ending,this.time);clock.now=this.time;return this}at(time,build){const saved=this.time;this.time=time;clock.now=time;build();this.ending=Math.max(this.ending,this.time);this.time=saved;clock.now=saved;return this}chapter(title){this.chapters.push({title,time:this.time});return this}caption(text2,duration=3){this.captions.push({t0:this.time,t1:this.time+duration,text:text2});this.ending=Math.max(this.ending,this.time+duration);return this}value(initial=0){return new Value(initial)}update(node,fn,window={}){this.updaters.push({node,fn,from:window.from??this.time,to:window.to??Infinity});return node}get duration(){return Math.max(this.ending,this.time)}};function film(a,b){const options=typeof a==="function"?{}:a;const build=typeof a==="function"?a:b;if(!build)throw new Error("film(options, build) needs a build function.");const definition={kind:"vizmatic.film",options,build,compile:overrides=>compileFilm(definition,overrides)};return definition}function isFilm(value){return!!value&&typeof value==="object"&&value.kind==="vizmatic.film"}var Suspend=class{constructor(promise){this.promise=promise}promise;isVizmaticSuspend=true};function isSuspend(error){return typeof error==="object"&&error!==null&&error.isVizmaticSuspend===true}var CompiledFilm=class{width;height;fps;duration;title;description;look;bloom;background;posterTime;bleed;chapters;clips;captions;stage;constructor(stage,options,overrides){this.stage=stage;this.width=stage.width;this.height=stage.height;this.fps=overrides.fps??stage.fps;this.duration=Math.max(stage.duration,1/this.fps);this.title=options.title??"";this.description=options.description??"";this.look=stage.look;this.bloom=overrides.bloom??options.bloom??stage.look.bloom;const background=overrides.background!==void 0?overrides.background:options.background!==void 0?options.background:stage.look.background;this.background=background===null?null:stage.look.colors[background]??background;this.posterTime=options.poster;this.bleed=options.bleed===true;this.chapters=stage.chapters;this.clips=stage.clips;this.captions=stage.captions}get frameCount(){return Math.max(1,Math.round(this.duration*this.fps))}frame(time){const t=Math.max(0,Math.min(this.duration,time));const stage=this.stage;const previous={mode:clock.mode,now:clock.now};setColorTokens(stage.look.colors);clock.mode="render";clock.now=t;clock.frame++;try{for(const updater of stage.updaters){if(t>=updater.from&&t<=updater.to)updater.fn(updater.node,t)}const camera=stage.camera;const ops=buildOps(stage.root,{x:camera.get("x"),y:camera.get("y"),zoom:camera.get("sx"),rotation:camera.get("rotation")},stage.width,stage.height);return{width:stage.width,height:stage.height,background:this.background,bloom:this.bloom,dark:stage.look.dark,ops}}finally{clock.mode=previous.mode;clock.now=previous.now}}svg(time,options={}){return frameToSvg(this.frame(time),options)}};async function compileFilm(definition,overrides={}){const options={...definition.options,...overrides.look?{look:overrides.look}:{},...overrides.fps?{fps:overrides.fps}:{}};for(let attempt=0;attempt<64;attempt++){const stage=new Stage(options);setColorTokens(stage.look.colors);const saved={mode:clock.mode,now:clock.now};clock.mode="compile";clock.now=0;try{await definition.build(stage);clock.mode=saved.mode;clock.now=saved.now;const compiled=new CompiledFilm(stage,options,overrides);await probe(compiled);return compiled}catch(error){clock.mode=saved.mode;clock.now=saved.now;clock.capture=null;if(error instanceof Suspend){await error.promise;continue}throw error}}throw new Error("The film kept requesting new assets while compiling.")}async function probe(film2){const samples=[0,.25,.5,.75,1];for(const fraction of samples){for(let attempt=0;attempt<16;attempt++){try{film2.frame(film2.duration*fraction);break}catch(error){if(!(error instanceof Suspend))throw error;await error.promise}}}}function curveFree(contours){return{contours:contours.filter(contour=>contour.length>=8)}}var assetBase=null;function setAssetBase(url){assetBase=url}var isNode=typeof process!=="undefined"&&!!process.versions?.node&&typeof globalThis.document==="undefined";function moduleUrl(){const url=import.meta.url;if(url)return url;return`file://${typeof __filename!=="undefined"?__filename:""}`}async function nodeRead(relative3){const fsName="node:fs/promises",pathName="node:path",urlName="node:url";const[fs,path,url]=await Promise.all([import(fsName),import(pathName),import(urlName)]);let directory=path.dirname(url.fileURLToPath(moduleUrl()));for(let depth=0;depth<6;depth++){const candidate=path.join(directory,"assets",relative3);try{const bytes=await fs.readFile(candidate);return bytes.buffer.slice(bytes.byteOffset,bytes.byteOffset+bytes.byteLength)}catch(error){if(error.code!=="ENOENT")throw error}directory=path.dirname(directory)}throw new Error(`Bundled asset not found: assets/${relative3}`)}async function loadBinaryAsset(relative3){if(isNode)return nodeRead(relative3);const base=assetBase??new URL("./assets/",moduleUrl()).href;const response=await fetch(new URL(relative3,base));const type=response.headers.get("content-type")??"";if(!response.ok||type.includes("text/html")){throw new Error(`Could not load ${relative3} from ${response.url} (HTTP ${response.status}, ${type||"no content type"}). Call setAssetBase() with the folder that holds fonts/.`)}return response.arrayBuffer()}var Reader=class{constructor(bytes,offset=0){this.bytes=bytes;this.offset=offset;this.view=new DataView(bytes)}bytes;offset;view;seek(offset){this.offset=offset;return this}get position(){return this.offset}u8(){return this.view.getUint8(this.offset++)}i8(){return this.view.getInt8(this.offset++)}u16(){const v=this.view.getUint16(this.offset);this.offset+=2;return v}i16(){const v=this.view.getInt16(this.offset);this.offset+=2;return v}u32(){const v=this.view.getUint32(this.offset);this.offset+=4;return v}tag(){let out="";for(let i=0;i<4;i++)out+=String.fromCharCode(this.u8());return out}};function parseFont(bytes){const r=new Reader(bytes);const version=r.u32();if(version!==65536&&version!==1953658213){throw new Error("Stage text needs a TrueType (.ttf) font with glyf outlines.")}const tableCount=r.u16();r.seek(12);const tables=new Map;for(let i=0;i<tableCount;i++){const tag=r.tag();r.u32();tables.set(tag,{offset:r.u32(),length:r.u32()})}const need=tag=>{const table=tables.get(tag);if(!table)throw new Error(`Font is missing its ${tag} table.`);return table};const head=need("head");r.seek(head.offset+18);const unitsPerEm=r.u16();r.seek(head.offset+50);const longLoca=r.i16()===1;const hhea=need("hhea");r.seek(hhea.offset+4);const ascent=r.i16();const descent=r.i16();const lineGap=r.i16();r.seek(hhea.offset+34);const hMetrics=r.u16();r.seek(need("maxp").offset+4);const glyphCount=r.u16();const hmtx=need("hmtx");const loca=need("loca");const glyf=need("glyf");const cmap=parseCmap(r,need("cmap").offset);const kerning=tables.has("GPOS")?parseKerning(r,tables.get("GPOS").offset):()=>0;const advance=glyph=>{const index=Math.min(glyph,hMetrics-1);r.seek(hmtx.offset+index*4);return r.u16()};const outlines=new Map;const contours=(glyph,depth)=>{if(glyph>=glyphCount||depth>6)return[];r.seek(loca.offset+(longLoca?glyph*4:glyph*2));const start=longLoca?r.u32():r.u16()*2;const end=longLoca?r.u32():r.u16()*2;if(start===end)return[];r.seek(glyf.offset+start);const count=r.i16();r.seek(r.position+8);if(count<0)return composite(glyph,depth);const ends=[];for(let i=0;i<count;i++)ends.push(r.u16());const instructionLength=r.u16();r.seek(r.position+instructionLength);const total=(ends[ends.length-1]??-1)+1;const flags=[];while(flags.length<total){const flag=r.u8();flags.push(flag);if(flag&8){let repeat=r.u8();while(repeat-- >0)flags.push(flag)}}const xs=new Array(total);let x=0;for(let i=0;i<total;i++){const flag=flags[i];if(flag&2){const dx=r.u8();x+=flag&16?dx:-dx}else if(!(flag&16)){x+=r.i16()}xs[i]=x}const ys=new Array(total);let y=0;for(let i=0;i<total;i++){const flag=flags[i];if(flag&4){const dy=r.u8();y+=flag&32?dy:-dy}else if(!(flag&32)){y+=r.i16()}ys[i]=y}const out=[];let first=0;for(const last of ends){out.push(contourToCubics(xs,ys,flags,first,last));first=last+1}return out};function composite(_glyph,depth){const parts=[];let more=true;while(more){const flags=r.u16();const glyph=r.u16();const words=(flags&1)!==0;const xy=(flags&2)!==0;let dx=0,dy=0;if(words){dx=r.i16();dy=r.i16()}else{dx=r.i8();dy=r.i8()}if(!xy){dx=0;dy=0}let a=1,b=0,c=0,d=1;const f2=()=>r.i16()/16384;if(flags&8){a=d=f2()}else if(flags&64){a=f2();d=f2()}else if(flags&128){a=f2();b=f2();c=f2();d=f2()}parts.push({glyph,m:[a,b,c,d,dx,dy]});more=(flags&32)!==0}const out=[];for(const part of parts){for(const contour of contours(part.glyph,depth+1)){const moved=new Array(contour.length);const[a,b,c,d,e,f]=part.m;for(let i=0;i<contour.length;i+=2){moved[i]=a*contour[i]+c*contour[i+1]+e;moved[i+1]=b*contour[i]+d*contour[i+1]+f}out.push(moved)}}return out}return{unitsPerEm,ascent,descent,lineGap,glyphFor(code){return cmap(code)},advance,kern(left,right){return kerning(left,right)},outline(glyph){if(outlines.has(glyph))return outlines.get(glyph);const raw=contours(glyph,0);const result=raw.length?curveFree(raw):null;outlines.set(glyph,result);return result}}}function contourToCubics(xs,ys,flags,first,last){const count=last-first+1;if(count<2)return[];const at=i=>first+(i%count+count)%count;const on=i=>(flags[at(i)]&1)!==0;let startIndex=0;while(startIndex<count&&!on(startIndex))startIndex++;let sx,sy;if(startIndex===count){sx=(xs[at(0)]+xs[at(count-1)])/2;sy=(ys[at(0)]+ys[at(count-1)])/2;startIndex=0}else{sx=xs[at(startIndex)];sy=ys[at(startIndex)];startIndex+=1}const out=[sx,sy];let cx=sx,cy=sy;let controlX=0,controlY=0,hasControl=false;const quad=(qx,qy,ex,ey)=>{out.push(cx+(qx-cx)*2/3,cy+(qy-cy)*2/3,ex+(qx-ex)*2/3,ey+(qy-ey)*2/3,ex,ey);cx=ex;cy=ey};const line2=(ex,ey)=>{out.push(cx+(ex-cx)/3,cy+(ey-cy)/3,cx+(ex-cx)*2/3,cy+(ey-cy)*2/3,ex,ey);cx=ex;cy=ey};for(let k=0;k<count;k++){const i=startIndex+k;const x=xs[at(i)],y=ys[at(i)];if(on(i)){if(hasControl){quad(controlX,controlY,x,y);hasControl=false}else if(x!==cx||y!==cy){line2(x,y)}}else{if(hasControl)quad(controlX,controlY,(controlX+x)/2,(controlY+y)/2);controlX=x;controlY=y;hasControl=true}}if(hasControl)quad(controlX,controlY,sx,sy);else if(cx!==sx||cy!==sy)line2(sx,sy);return out}function parseCmap(r,offset){r.seek(offset+2);const count=r.u16();let best=-1,bestScore=-1;for(let i=0;i<count;i++){const platform=r.u16();const encoding=r.u16();const sub=r.u32();const score=platform===3&&encoding===10?4:platform===0&&encoding>=4?3:platform===3&&encoding===1?2:platform===0?1:0;if(score>bestScore){bestScore=score;best=offset+sub}}if(best<0)return()=>0;r.seek(best);const format=r.u16();if(format===12){r.seek(best+12);const groups=r.u32();const table=[];for(let i=0;i<groups;i++)table.push([r.u32(),r.u32(),r.u32()]);return code=>{let lo=0,hi=table.length-1;while(lo<=hi){const mid=lo+hi>>1;const[start,end,glyph]=table[mid];if(code<start)hi=mid-1;else if(code>end)lo=mid+1;else return glyph+code-start}return 0}}if(format===4){r.seek(best+6);const segX2=r.u16();const segs=segX2/2;const endsAt=best+14;const startsAt=endsAt+segX2+2;const deltasAt=startsAt+segX2;const rangesAt=deltasAt+segX2;const map=new Map;for(let i=0;i<segs;i++){const end=r.seek(endsAt+i*2).u16();const start=r.seek(startsAt+i*2).u16();const delta=r.seek(deltasAt+i*2).i16();const range=r.seek(rangesAt+i*2).u16();for(let c=start;c<=end&&c!==65535;c++){let glyph;if(range===0)glyph=c+delta&65535;else{const raw=r.seek(rangesAt+i*2+range+(c-start)*2).u16();glyph=raw===0?0:raw+delta&65535}if(glyph)map.set(c,glyph)}}return code=>map.get(code)??0}return()=>0}function parseKerning(r,gpos){const lookups=[];try{r.seek(gpos+6);const featureList=gpos+r.u16();const lookupList=gpos+r.u16();r.seek(featureList);const featureCount=r.u16();const indices=new Set;for(let i=0;i<featureCount;i++){r.seek(featureList+2+i*6);const tag=r.tag();const offset=r.u16();if(tag!=="kern")continue;r.seek(featureList+offset+2);const count=r.u16();for(let k=0;k<count;k++)indices.add(r.u16())}for(const index of[...indices].sort((a,b)=>a-b)){r.seek(lookupList+2+index*2);const lookup=lookupList+r.u16();r.seek(lookup);const lookupType=r.u16();r.u16();const subCount=r.u16();const subs=[];for(let i=0;i<subCount;i++)subs.push(lookup+r.u16());const tables=[];for(const first of subs){let sub=first;let type=lookupType;if(type===9){r.seek(sub+2);type=r.u16();sub+=r.u32()}if(type===2)tables.push(readPairs(r,sub))}lookups.push(tables)}}catch{}const cache2=new Map;return(left,right)=>{const key=left*65536+right;const cached=cache2.get(key);if(cached!==void 0)return cached;let total=0;for(const tables of lookups){for(const table of tables){const value=table(left,right);if(value!==void 0){total+=value;break}}}cache2.set(key,total);return total}}function readCoverage(r,offset){r.seek(offset);const format=r.u16();const out=new Set;if(format===1){const count=r.u16();for(let i=0;i<count;i++)out.add(r.u16())}else if(format===2){const count=r.u16();for(let i=0;i<count;i++){const start=r.u16(),end=r.u16();r.u16();for(let glyph=start;glyph<=end;glyph++)out.add(glyph)}}return out}function readClasses(r,offset){r.seek(offset);const format=r.u16();const classes=new Map;if(format===1){const start=r.u16();const count=r.u16();for(let i=0;i<count;i++)classes.set(start+i,r.u16())}else if(format===2){const count=r.u16();for(let i=0;i<count;i++){const start=r.u16(),end=r.u16(),value=r.u16();for(let glyph=start;glyph<=end;glyph++)classes.set(glyph,value)}}return glyph=>classes.get(glyph)??0}function valueSize(format){let count=0;for(let bit=0;bit<8;bit++)if(format&1<<bit)count++;return count*2}function readAdvance(r,format){let advance=0;if(format&1)r.i16();if(format&2)r.i16();if(format&4)advance=r.i16();if(format&8)r.i16();for(let bit=4;bit<8;bit++)if(format&1<<bit)r.u16();return advance}function readPairs(r,sub){r.seek(sub);const format=r.u16();const coverageOffset=r.u16();const value1=r.u16();const value2=r.u16();const size1=valueSize(value1);const size2=valueSize(value2);if(format===1){const setCount=r.u16();const offsets=[];for(let i=0;i<setCount;i++)offsets.push(r.u16());r.seek(sub+coverageOffset);const coverageFormat=r.u16();const glyphs=[];if(coverageFormat===1){const count=r.u16();for(let i=0;i<count;i++)glyphs.push(r.u16())}else if(coverageFormat===2){const count=r.u16();for(let i=0;i<count;i++){const start=r.u16(),end=r.u16();r.u16();for(let glyph=start;glyph<=end;glyph++)glyphs.push(glyph)}}const sets=new Map;for(let i=0;i<setCount;i++){r.seek(sub+offsets[i]);const count=r.u16();const pairs=new Map;for(let k=0;k<count;k++){const second=r.u16();const advance=readAdvance(r,value1);r.seek(r.position+size2);pairs.set(second,advance)}if(glyphs[i]!==void 0)sets.set(glyphs[i],pairs)}return(left,right)=>sets.get(left)?.get(right)}if(format===2){const class1Offset=r.u16();const class2Offset=r.u16();const class1Count=r.u16();const class2Count=r.u16();const matrix2=r.position;const coverage=readCoverage(r,sub+coverageOffset);const class1=readClasses(r,sub+class1Offset);const class2=readClasses(r,sub+class2Offset);return(left,right)=>{if(!coverage.has(left))return void 0;const c1=class1(left),c2=class2(right);if(c1>=class1Count||c2>=class2Count)return void 0;r.seek(matrix2+c1*class2Count*(size1+size2)+c2*(size1+size2));return readAdvance(r,value1)}}return()=>void 0}var FILES={sans:{"400":"Inter-Regular.ttf","600":"Inter-SemiBold.ttf","700":"Inter-Bold.ttf"},serif:{"400":"InstrumentSerif-Regular.ttf","italic":"InstrumentSerif-Italic.ttf"},mono:{"400":"JetBrainsMono-Regular.ttf"},noto:{"400":"NotoSans-Regular.ttf"}};var fonts=new Map;var pending=new Map;function fontFor(family,weight=400,italic=false){const files=FILES[family];const file=(italic?files["italic"]:void 0)??files[String(weight)]??files["400"];const loaded=fonts.get(file);if(loaded)return loaded;let waiting=pending.get(file);if(!waiting){waiting=loadBinaryAsset(`fonts/${file}`).then(bytes=>{fonts.set(file,parseFont(bytes));pending.delete(file)});pending.set(file,waiting)}throw new Suspend(waiting)}var glyphPaths=new WeakMap;function glyphPath(font,glyph,size){let bySize=glyphPaths.get(font);if(!bySize)glyphPaths.set(font,bySize=new Map);let byGlyph=bySize.get(size);if(!byGlyph)bySize.set(size,byGlyph=new Map);const cached=byGlyph.get(glyph);if(cached)return cached;const outline=font.outline(glyph);const scale=size/font.unitsPerEm;const path=outline?outline.contours.map(contour=>{const out=new Float64Array(contour.length);for(let i=0;i<contour.length;i+=2){out[i]=contour[i]*scale;out[i+1]=-contour[i+1]*scale}return ring(out,true)}):[];byGlyph.set(glyph,path);return path}var TextNode=class extends Node{chars=[];source="";find(fragment){const out=[];const keys=this.chars.map(glyph=>glyph.data["key"]).join("");const needle=fragment.replace(/\s/g,"");for(let at=keys.indexOf(needle);at>=0;at=keys.indexOf(needle,at+1)){out.push(...this.chars.slice(at,at+needle.length))}return out}};function centered(path){const b=pathBounds(path);if(!b)return{path,x:0,y:0};const x=b.x+b.width/2,y=b.y+b.height/2;return{path:transformPath(path,[1,0,0,1,-x,-y]),x,y}}function text(content,options={}){const size=options.size??40;const font=fontFor(options.font??"sans",options.weight??400,options.italic??false);const scale=size/font.unitsPerEm;const tracking=(options.tracking??0)*size;const leading=(options.leading??1.3)*size;const paint=toPaint(options.color??"ink");const source=options.uppercase?content.toUpperCase():content;const measureWord=word=>{const glyphs=[];let x=0,previous=0;for(const char of word){const code=char.codePointAt(0);const glyph=font.glyphFor(code);if(previous)x+=font.kern(previous,glyph)*scale;glyphs.push({code,glyph,x,char});x+=font.advance(glyph)*scale+tracking;previous=glyph}return{glyphs,width:x}};const lines=[];const space=font.advance(font.glyphFor(32))*scale+tracking;for(const paragraph of source.split("\n")){let line2=[];let width=0;for(const word of paragraph.split(" ")){const measured=measureWord(word);const gap=line2.length>0?space:0;if(options.maxWidth!==void 0&&line2.length>0&&width+gap+measured.width>options.maxWidth){lines.push({glyphs:line2,width});line2=[];width=0}const offset=width+(line2.length>0?space:0);for(const glyph of measured.glyphs)line2.push({...glyph,x:glyph.x+offset});width=offset+measured.width}lines.push({glyphs:line2,width})}const blockWidth=Math.max(0,...lines.map(line2=>line2.width));const align=options.align??"left";const node=new TextNode;node.source=content;lines.forEach((line2,row)=>{const start=align==="left"?0:align==="center"?(blockWidth-line2.width)/2:blockWidth-line2.width;for(const placed of line2.glyphs){const path=glyphPath(font,placed.glyph,size);if(path.length===0)continue;const shape2=centered(path);const leaf=new Node(shape2.path).at(start+placed.x+shape2.x,row*leading+shape2.y);leaf.base.fill=paint;leaf.base.trimEach=true;leaf.data["key"]=placed.char;node.chars.push(leaf);node.children.push(leaf);leaf.parent=node}});const ascent=font.ascent*scale;const height=(lines.length-1)*leading;node.base.px=blockWidth/2;node.base.py=height/2-ascent*.36;node.data["size"]=size;return node}function decode(value){return value.replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&#(\d+);/g,(_,code)=>String.fromCodePoint(Number(code))).replace(/&#x([\da-fA-F]+);/g,(_,code)=>String.fromCodePoint(parseInt(code,16))).replace(/&/g,"&")}function parseXml(source){const root={name:"#root",attrs:{},children:[],text:""};const stack=[root];const token=/<!--[\s\S]*?-->|<!\[CDATA\[([\s\S]*?)\]\]>|<\?[\s\S]*?\?>|<!DOCTYPE[^>]*>|<\/([\w:.-]+)\s*>|<([\w:.-]+)((?:\s+[\w:.-]+\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*(\/?)>|([^<]+)/g;for(let match=token.exec(source);match;match=token.exec(source)){const top=stack[stack.length-1];const[,cdata,closing,opening,attributes,selfClosing,content]=match;if(cdata!==void 0){top.text+=cdata}else if(closing){if(stack.length>1)stack.pop()}else if(opening){const element={name:opening.replace(/^.*:/,""),attrs:{},children:[],text:""};for(const attr of(attributes??"").matchAll(/([\w:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)){element.attrs[attr[1]]=decode(attr[2]??attr[3]??"")}top.children.push(element);if(!selfClosing)stack.push(element)}else if(content){top.text+=decode(content)}}return root}function parseTransform(value){if(!value)return IDENTITY;let m=IDENTITY;for(const match of value.matchAll(/(matrix|translate|scale|rotate|skewX|skewY)\s*\(([^)]*)\)/g)){const a=match[2].trim().split(/[\s,]+/).filter(Boolean).map(Number);const name=match[1];if(name==="matrix"&&a.length===6)m=mul(m,a);else if(name==="translate")m=mul(m,[1,0,0,1,a[0]??0,a[1]??0]);else if(name==="scale")m=mul(m,[a[0]??1,0,0,a[1]??a[0]??1,0,0]);else if(name==="rotate"){const r=(a[0]??0)*Math.PI/180;const c=Math.cos(r),s=Math.sin(r);const cx=a[1]??0,cy=a[2]??0;m=mul(m,[1,0,0,1,cx,cy]);m=mul(m,[c,s,-s,c,0,0]);m=mul(m,[1,0,0,1,-cx,-cy])}else if(name==="skewX")m=mul(m,[1,0,Math.tan((a[0]??0)*Math.PI/180),1,0,0]);else if(name==="skewY")m=mul(m,[1,Math.tan((a[0]??0)*Math.PI/180),0,1,0,0])}return m}var NOT_DRAWN=new Set(["defs","clipPath","mask","pattern","filter","symbol","marker","linearGradient","radialGradient","title","desc","metadata","style","script"]);var SvgNode=class extends Node{byId=new Map;pictureWidth=0;pictureHeight=0;find(id){const found=this.byId.get(id);if(!found)throw new Error(`The SVG has no element with id ${JSON.stringify(id)}.`);return found}};function parseCssRules(root){const rules=new Map;const visit=element=>{if(element.name==="style"){for(const rule of element.text.matchAll(/([^{}]+)\{([^{}]*)\}/g)){const body=parseStyle(rule[2]);for(const selector of rule[1].split(",")){const key=selector.trim();rules.set(key,{...rules.get(key),...body})}}}element.children.forEach(visit)};visit(root);return rules}function parseStyle(value){const out={};if(!value)return out;for(const part of value.split(";")){const index=part.indexOf(":");if(index>0)out[part.slice(0,index).trim()]=part.slice(index+1).trim()}return out}function safeColor(value){if(!value||value==="none"||value==="transparent")return null;try{return parseColor(value)}catch{return null}}function splitIntoGlyphs(path){const items=path.map(r=>{const b=pathBounds([r]);return{ring:r,b,area:b.width*b.height,owner:-1}});const order=items.map((_,i)=>i).sort((a,b)=>items[b].area-items[a].area);for(let k=0;k<order.length;k++){const inner=items[order[k]];for(let j=k-1;j>=0;j--){const outer=items[order[j]];if(outer.owner!==-1)continue;const inside=inner.b.x>=outer.b.x-.01&&inner.b.y>=outer.b.y-.01&&inner.b.x+inner.b.width<=outer.b.x+outer.b.width+.01&&inner.b.y+inner.b.height<=outer.b.y+outer.b.height+.01;if(inside){inner.owner=order[j];break}}}const glyphs=[];const ownerToGlyph=new Map;items.forEach((item,i)=>{if(item.owner!==-1)return;const glyph={x:item.b.x,rings:[item.ring]};ownerToGlyph.set(i,glyph);glyphs.push(glyph)});items.forEach(item=>{if(item.owner!==-1)ownerToGlyph.get(item.owner)?.rings.push(item.ring)});return glyphs.sort((a,b)=>a.x-b.x).map(glyph=>glyph.rings)}function fromSvg(source,options={}){const root=parseXml(source);const svg=root.children.find(child=>child.name==="svg");if(!svg)throw new Error("fromSvg needs markup with an <svg> element.");const rules=parseCssRules(svg);const defs=new Map;const index=element=>{if(element.attrs["id"])defs.set(element.attrs["id"],element);element.children.forEach(index)};index(svg);const box=(svg.attrs["viewBox"]??"").trim().split(/[\s,]+/).map(Number);const declaredW=parseFloat(svg.attrs["width"]??""),declaredH=parseFloat(svg.attrs["height"]??"");const viewW=box.length===4&&box[2]?box[2]:declaredW||300;const viewH=box.length===4&&box[3]?box[3]:declaredH||150;const viewX=box.length===4?box[0]:0,viewY=box.length===4?box[1]:0;const naturalW=Number.isFinite(declaredW)&&declaredW>0?declaredW:viewW;const naturalH=Number.isFinite(declaredH)&&declaredH>0?declaredH:viewH;let scale=1;if(options.width!==void 0||options.height!==void 0){const sx=options.width!==void 0?options.width/viewW:Infinity;const sy=options.height!==void 0?options.height/viewH:Infinity;scale=Math.min(sx,sy)}else{scale=Math.min(naturalW/viewW,naturalH/viewH)}const center2=options.center??true;const offsetX=center2?-(viewX+viewW/2)*scale:-viewX*scale;const offsetY=center2?-(viewY+viewH/2)*scale:-viewY*scale;const base=[scale,0,0,scale,offsetX,offsetY];const out=new SvgNode;out.pictureWidth=viewW*scale;out.pictureHeight=viewH*scale;const splitting=options.splitGlyphs??true;const keepBackground=options.background??false;let firstShape=true;const gradientOf=(id,m,path)=>{const element=defs.get(id);if(!element)return null;if(element.name==="pattern"){const inner=element.children.find(child=>child.name==="linearGradient");if(inner)return linear2(inner,m,path,true);const fill=element.children.find(child=>child.attrs["fill"]?.startsWith("url(#"));const nested=fill?.attrs["fill"]?.match(/url\(#([^)]+)\)/)?.[1];return nested?gradientOf(nested,m,path):null}if(element.name==="linearGradient")return linear2(element,m,path,element.attrs["gradientUnits"]!=="userSpaceOnUse");if(element.name==="radialGradient"){const stops=stopsOf(element);return stops.length?stops[stops.length-1][1]:null}return null};const stopsOf=element=>{const inherited=element.attrs["href"]??element.attrs["xlink:href"];const source2=element.children.some(child=>child.name==="stop")||!inherited?element:defs.get(inherited.replace(/^#/,""))??element;return source2.children.filter(child=>child.name==="stop").map(stop=>{const style2=parseStyle(stop.attrs["style"]);const offsetRaw=stop.attrs["offset"]??"0";const offset=offsetRaw.endsWith("%")?parseFloat(offsetRaw)/100:parseFloat(offsetRaw);const color=safeColor(style2["stop-color"]??stop.attrs["stop-color"]??"#000000")??[0,0,0,1];const alpha2=parseFloat(style2["stop-opacity"]??stop.attrs["stop-opacity"]??"1");return[offset,[color[0],color[1],color[2],color[3]*alpha2]]})};const linear2=(element,m,path,objectBox)=>{const stops=stopsOf(element);if(stops.length===0)return null;const coordinate=(value,fallback)=>{if(value===void 0)return fallback;return value.endsWith("%")?parseFloat(value)/100:parseFloat(value)};const x1=coordinate(element.attrs["x1"],0),y1=coordinate(element.attrs["y1"],0);const x2=coordinate(element.attrs["x2"],1),y2=coordinate(element.attrs["y2"],0);let from,to2;if(objectBox){const b=pathBounds(path)??{x:0,y:0,width:1,height:1};from=[b.x+x1*b.width,b.y+y1*b.height];to2=[b.x+x2*b.width,b.y+y2*b.height]}else{from=apply(m,x1,y1);to2=apply(m,x2,y2)}return{type:"linear",from,to:to2,stops}};const shapePath=element=>{const a=element.attrs;const num=(key,fallback=0)=>{const value=parseFloat(a[key]??"");return Number.isFinite(value)?value:fallback};switch(element.name){case"path":return a["d"]?parseSvgPath(a["d"]):null;case"rect":{const w=num("width"),h=num("height");if(w<=0||h<=0)return null;return rectPath(num("x"),num("y"),w,h,num("rx",num("ry")))}case"circle":return num("r")>0?arcPath(num("cx"),num("cy"),num("r"),num("r"),0,Math.PI*2):null;case"ellipse":return num("rx")>0&&num("ry")>0?arcPath(num("cx"),num("cy"),num("rx"),num("ry"),0,Math.PI*2):null;case"line":return polyPath([[num("x1"),num("y1")],[num("x2"),num("y2")]]);case"polyline":case"polygon":{const values=(a["points"]??"").trim().split(/[\s,]+/).filter(Boolean).map(Number);const points=[];for(let i=0;i+1<values.length;i+=2)points.push([values[i],values[i+1]]);return points.length>=2?polyPath(points,element.name==="polygon"):null}default:return null}};const styleOf=(element,inherited)=>{const a=element.attrs;const cls=(a["class"]??"").split(/\s+/).filter(Boolean);const merged={...rules.get(element.name)};for(const name of cls)Object.assign(merged,rules.get(`.${name}`));if(a["id"])Object.assign(merged,rules.get(`#${a["id"]}`));const pick=key=>parseStyle(a["style"])[key]??a[key]??merged[key];const style2={...inherited};const color=pick("color");if(color)style2.color=color;const fill=pick("fill");if(fill)style2.fill=fill==="currentColor"?style2.color:fill;const stroke=pick("stroke");if(stroke)style2.stroke=stroke==="currentColor"?style2.color:stroke;const width=pick("stroke-width");if(width!==void 0)style2.strokeWidth=parseFloat(width)||0;const fo=pick("fill-opacity");if(fo!==void 0)style2.fillOpacity=parseFloat(fo);const so=pick("stroke-opacity");if(so!==void 0)style2.strokeOpacity=parseFloat(so);const cap=pick("stroke-linecap");if(cap==="round"||cap==="butt"||cap==="square")style2.cap=cap;const join4=pick("stroke-linejoin");if(join4==="round"||join4==="miter"||join4==="bevel")style2.join=join4;const dash=pick("stroke-dasharray");if(dash!==void 0)style2.dash=dash==="none"?null:dash.trim().split(/[\s,]+/).map(Number);const dashOffset=pick("stroke-dashoffset");if(dashOffset!==void 0)style2.dashOffset=parseFloat(dashOffset)||0;const size=pick("font-size");if(size!==void 0)style2.fontSize=parseFloat(size)||style2.fontSize;const anchor=pick("text-anchor");if(anchor)style2.anchor=anchor;return{style:style2,opacity:parseFloat(pick("opacity")??"1")}};const leafFrom=(path,m,element,style2)=>{const world=transformPath(path,m);const scaleOf=matScale(m);const url=value=>value?.match(/^url\(#([^)]+)\)/)?.[1];const fillId=url(style2.fill),strokeId=url(style2.stroke);const fill=fillId?gradientOf(fillId,m,world):safeColor(style2.fill);const stroke=strokeId?gradientOf(strokeId,m,world):safeColor(style2.stroke);const visibleFill=fill&&style2.fillOpacity>0&&!(Array.isArray(fill)&&fill[3]===0);const visibleStroke=stroke&&style2.strokeOpacity>0&&style2.strokeWidth>0&&!(Array.isArray(stroke)&&stroke[3]===0);if(!visibleFill&&!visibleStroke)return[];const clippedStroke=element.attrs["clip-path"]?.5:1;const pieces=splitting&&visibleFill&&!visibleStroke&&world.length>1?splitIntoGlyphs(world):[world];return pieces.map(piece=>{const b=pathBounds(piece)??{x:0,y:0,width:0,height:0};const cx=b.x+b.width/2,cy=b.y+b.height/2;const leaf=new Node(transformPath(piece,[1,0,0,1,-cx,-cy])).at(cx,cy);if(visibleFill){leaf.base.fill=shiftPaint(fill,-cx,-cy);leaf.base.fillOpacity=style2.fillOpacity}if(visibleStroke){leaf.base.stroke=shiftPaint(stroke,-cx,-cy);leaf.base.strokeWidth=style2.strokeWidth*scaleOf*clippedStroke;leaf.base.strokeOpacity=style2.strokeOpacity;leaf.base.cap=style2.cap;leaf.base.join=style2.join;if(style2.dash)leaf.base.dash=style2.dash.map(value=>value*scaleOf);leaf.base.dashOffset=style2.dashOffset*scaleOf}leaf.base.trimEach=true;return leaf})};const walk2=(element,parent,inherited,parentMatrix)=>{if(NOT_DRAWN.has(element.name))return;if(element.attrs["filter"])return;const{style:style2,opacity}=styleOf(element,inherited);const m=mul(parentMatrix,parseTransform(element.attrs["transform"]));const register=node=>{if(element.attrs["id"])out.byId.set(element.attrs["id"],node)};if(element.name==="g"||element.name==="svg"||element.name==="a"){const group3=new Node;if(opacity<1)group3.base.opacity=opacity;register(group3);parent.add(group3);for(const child of element.children)walk2(child,group3,style2,m);return}if(element.name==="use"){const href=(element.attrs["href"]??element.attrs["xlink:href"]??"").replace(/^#/,"");const referenced=defs.get(href);if(!referenced)return;const placed=mul(m,[1,0,0,1,parseFloat(element.attrs["x"]??"0")||0,parseFloat(element.attrs["y"]??"0")||0]);const group3=new Node;if(opacity<1)group3.base.opacity=opacity;parent.add(group3);if(referenced.name==="symbol")for(const child of referenced.children)walk2(child,group3,style2,placed);else walk2(referenced,group3,style2,placed);return}if(element.name==="image"){const href=element.attrs["href"]??element.attrs["xlink:href"];if(!href)return;const width=parseFloat(element.attrs["width"]??"0"),height=parseFloat(element.attrs["height"]??"0");const[x,y]=apply(m,parseFloat(element.attrs["x"]??"0")||0,parseFloat(element.attrs["y"]??"0")||0);const unit=matScale(m);const image={src:href,width,height};const node=new Node().at(x,y);node.base.image=image;node.base.sx=unit;node.base.sy=unit;if(opacity<1)node.base.opacity=opacity;register(node);parent.add(node);return}if(element.name==="text"){const body=(element.text+element.children.map(child=>child.text).join("")).trim();if(!body)return;const color=safeColor(style2.fill)??[0,0,0,1];const size=style2.fontSize*matScale(m);const label=text(body,{size,color});const[x,y]=apply(m,parseFloat(element.attrs["x"]??"0")||0,parseFloat(element.attrs["y"]??"0")||0);const half=label.get("px");label.at(style2.anchor==="middle"?x:style2.anchor==="end"?x-half:x+half,y-size*.34);if(opacity<1)label.base.opacity=opacity;register(label);parent.add(label);return}const path=shapePath(element);if(!path||path.length===0)return;const isBackground=firstShape&&element.name==="rect"&&!keepBackground&&parseFloat(element.attrs["width"]??"0")>=viewW-.5&&parseFloat(element.attrs["height"]??"0")>=viewH-.5;firstShape=false;if(isBackground)return;const leaves=leafFrom(path,m,element,style2);if(leaves.length===0)return;if(leaves.length===1){if(opacity<1)leaves[0].base.opacity=opacity;register(leaves[0]);parent.add(leaves[0]);return}const group2=new Node;if(opacity<1)group2.base.opacity=opacity;group2.add(...leaves);register(group2);parent.add(group2)};const initial={fill:"#000000",stroke:null,strokeWidth:1,fillOpacity:1,strokeOpacity:1,cap:"butt",join:"miter",dash:null,dashOffset:0,color:"#000000",fontSize:16,anchor:"start"};const{style}=styleOf(svg,initial);for(const child of svg.children)walk2(child,out,style,base);return out}function shiftPaint(paint,dx,dy){if(Array.isArray(paint))return paint;const gradient=paint;if(gradient.type==="linear"){return{...gradient,from:[gradient.from[0]+dx,gradient.from[1]+dy],to:[gradient.to[0]+dx,gradient.to[1]+dy]}}if(gradient.type==="radial")return{...gradient,center:[gradient.center[0]+dx,gradient.center[1]+dy]};return gradient}var QUALITY={draft:{crf:26,vp9Crf:40,preset:"veryfast",motionBlur:1},standard:{crf:18,vp9Crf:31,preset:"medium",motionBlur:1},high:{crf:15,vp9Crf:24,preset:"slow",motionBlur:4},master:{crf:11,vp9Crf:15,preset:"slow",motionBlur:8}};var DEFAULT_GIF_WIDTH=960;var DEFAULT_GIF_FPS=25;var GIF_PALETTE_FRAMES=12;var GIF_PALETTE_PIXELS=1<<19;var MAX_GIF_DELAY=655350;async function resolveFilm(film2,overrides){return isFilm(film2)?film2.compile(overrides):film2}function frameAt(film2,time){try{return film2.frame(time)}catch(error){if(!isSuspend(error))throw error;return error.promise.then(()=>frameAt(film2,time))}}function backgroundBytes(color){if(!color)return[0,0,0];const rgba=parseColor(color);return[rgba[0],rgba[1],rgba[2]]}function outputSize(film2,requested){const width=requested??film2.width;if(!Number.isInteger(width)||width<2)throw new Error(`Output width must be an integer of at least 2, but received ${width}.`);return{width,height:Math.max(1,Math.round(width*film2.height/film2.width))}}function evenSize(film2,requested){const{width,height}=outputSize(film2,requested);return{width:width+width%2,height:Math.max(2,height+height%2)}}function timeRange(film2,options){const from=Math.max(0,options.from??0);const to2=Math.min(film2.duration,options.to??film2.duration);if(!Number.isFinite(from)||!Number.isFinite(to2)||to2<=from){throw new Error(`The render range ${from}:${to2} is empty. The film is ${film2.duration.toFixed(2)} seconds long.`)}return{from,to:to2}}function planRender(width,height,motionBlur,options={}){const frameBytes=width*height*4;const budget=options.memoryBudget??Math.min(2*1024**3,totalmem()*.25);const requested=Math.max(1,Math.floor(options.workers??defaultPoolSize()));const perWorker=frameBytes*(motionBlur>1?motionBlur+4:3);const workers=Math.max(1,Math.min(requested,Math.floor(budget*.75/perWorker)));const extra=Math.floor(budget*.25/frameBytes);return{workers,readAhead:Math.max(workers+1,Math.min(workers*2,workers+extra))}}function frameStream(film2,pool,timeOf,size,count,readAhead,subframes=1,shutterSpan=0){const inFlight=new Map;const submit=async index=>{const base=timeOf(index);const frames=[];for(let sub=0;sub<subframes;sub++){frames.push(await frameAt(film2,base+sub/subframes*shutterSpan))}return pool.run(framesToJob(frames,size.width,backgroundBytes,size.height))};return async index=>{for(let ahead=index;ahead<Math.min(count,index+readAhead);ahead++){if(inFlight.has(ahead))continue;const job=submit(ahead);job.catch(()=>{});inFlight.set(ahead,job)}const pixels=await inFlight.get(index);inFlight.delete(index);return pixels}}async function renderFilmVideo(film2,outputPath,options={}){const compiled=await resolveFilm(film2,options);const quality=QUALITY[options.quality??"standard"];if(!quality)throw new Error(`Unknown quality: ${options.quality}. Use draft, standard, high, or master.`);const size=evenSize(compiled,options.width);const motionBlur=Math.max(1,Math.floor(options.motionBlur??quality.motionBlur));const shutter=options.shutter??.5;const fps=compiled.fps;const codec=options.codec??"h264";const{from,to:to2}=timeRange(compiled,options);const plan=planRender(size.width,size.height,motionBlur,options);const pool=new RasterPool(plan.workers);try{const count=Math.max(1,Math.round((to2-from)*fps));const next=frameStream(compiled,pool,index=>from+index/fps,size,count,plan.readAhead,motionBlur,shutter/fps);const output=await renderRgbaVideo(info=>next(info.index),{width:size.width,height:size.height,fps,duration:(to2-from)*1e3,outputPath,codec,crf:codec==="vp9"?quality.vp9Crf:quality.crf,preset:quality.preset,tune:codec==="h264"?"animation":void 0,threads:options.threads??6,audioPath:options.audioPath,audioOffset:from>0?from:void 0,ffmpegPath:options.ffmpegPath,signal:options.signal,onProgress:options.onProgress});return{...output,title:compiled.title,workers:pool.size,motionBlur,codec}}finally{await pool.close()}}var gifApi=typeof gifenc2.GIFEncoder==="function"?gifenc2:gifenc2.default;function changedRegion(previous,current,width,height){let minX=width,minY=height,maxX=-1,maxY=-1;for(let y=0;y<height;y++){const row=y*width*4;for(let x=0;x<width;x++){const o=row+x*4;if(previous[o]!==current[o]||previous[o+1]!==current[o+1]||previous[o+2]!==current[o+2]){if(x<minX)minX=x;if(x>maxX)maxX=x;if(y<minY)minY=y;maxY=y}}}return maxX<0?null:{x:minX,y:minY,width:maxX-minX+1,height:maxY-minY+1}}function cropRegion(pixels,canvasWidth,region){const out=new Uint8Array(region.width*region.height*4);for(let y=0;y<region.height;y++){const start=((region.y+y)*canvasWidth+region.x)*4;out.set(pixels.subarray(start,start+region.width*4),y*region.width*4)}return out}async function renderFilmGif(film2,outputPath,options={}){const compiled=await resolveFilm(film2,{...options,fps:void 0});const size=outputSize(compiled,options.width??Math.min(DEFAULT_GIF_WIDTH,compiled.width));const fps=Math.min(options.fps??DEFAULT_GIF_FPS,50);const{from,to:to2}=timeRange(compiled,options);const count=Math.max(1,Math.round((to2-from)*fps));const delay2=1e3/fps;const plan=planRender(size.width,size.height,1,options);const pool=new RasterPool(plan.workers);try{const sampleCount=Math.min(count,GIF_PALETTE_FRAMES);const samples=await Promise.all(Array.from({length:sampleCount},async(_,i)=>{const index=Math.floor((i+.5)*count/sampleCount);return pool.run(framesToJob([await frameAt(compiled,from+index/fps)],size.width,backgroundBytes,size.height))}));const perFrame=Math.max(1,Math.floor(GIF_PALETTE_PIXELS/sampleCount));const combined=new Uint8Array(perFrame*sampleCount*4);samples.forEach((pixels,i)=>{const total=pixels.length/4;for(let k=0;k<perFrame;k++){const at=Math.floor((k+.5)*total/perFrame)*4;combined.set(pixels.subarray(at,at+4),(i*perFrame+k)*4)}});const palette=gifApi.quantize(combined,256,{format:"rgb565"});const gif=gifApi.GIFEncoder();const next=frameStream(compiled,pool,index=>from+index/fps,size,count,plan.readAhead);const repeat=options.loop===false?-1:0;let previous=null;let pending2=null;const flush=first=>{if(!pending2)return;let remaining=pending2.delay;let includePalette=first;do{const span=Math.min(MAX_GIF_DELAY,remaining);const start=gif.bytesView().length;gif.writeFrame(pending2.index,pending2.region.width,pending2.region.height,{...includePalette?{palette}:{},delay:Math.max(20,span),repeat,dispose:1});if(pending2.region.x!==0||pending2.region.y!==0){const bytes=gif.bytesView();const descriptor=start+8;if(bytes[descriptor]!==44)throw new Error("The GIF encoder wrote an unexpected frame layout.");bytes[descriptor+1]=pending2.region.x&255;bytes[descriptor+2]=pending2.region.x>>8&255;bytes[descriptor+3]=pending2.region.y&255;bytes[descriptor+4]=pending2.region.y>>8&255}includePalette=false;remaining-=span}while(remaining>0)};let wroteAny=false;for(let i=0;i<count;i++){options.signal?.throwIfAborted();const pixels=await next(i);const region=previous?changedRegion(previous,pixels,size.width,size.height):{x:0,y:0,width:size.width,height:size.height};if(!region){if(pending2)pending2.delay+=delay2}else{flush(!wroteAny);if(pending2)wroteAny=true;const cropped=region.width===size.width&®ion.height===size.height?pixels:cropRegion(pixels,size.width,region);pending2={index:gifApi.applyPalette(cropped,palette,"rgb565"),region,delay:delay2};previous=pixels}await options.onProgress?.({index:i,count,time:i*delay2,duration:count*delay2,progress:i/count,fps})}flush(!wroteAny);gif.finish();const path=resolve(outputPath);await mkdir2(dirname2(path),{recursive:true});await writeFile2(path,gif.bytesView());return{width:size.width,height:size.height,frameCount:count,duration:count*delay2,fps,bytes:(await stat(path)).size,outputPath:path,title:compiled.title}}finally{await pool.close()}}async function renderFilmFrame(film2,time,outputPath,options={}){const compiled=await resolveFilm(film2,options);const{width,height}=outputSize(compiled,options.width);const pool=new RasterPool(1);try{const frame=await frameAt(compiled,time);const pixels=await pool.run(framesToJob([frame],width,backgroundBytes,height));const path=resolve(outputPath);await mkdir2(dirname2(path),{recursive:true});await writeFile2(path,encodePng({width,height,data:pixels,depth:8,channels:4}));return{width,height,outputPath:path}}finally{await pool.close()}}async function renderFilmSvg(film2,time,outputPath,options={}){const compiled=await resolveFilm(film2,options);const path=resolve(outputPath);await mkdir2(dirname2(path),{recursive:true});const frame=await frameAt(compiled,time);const scale=(options.width??compiled.width)/compiled.width;await writeFile2(path,frameToSvg(frame,{scale}));return{width:Math.round(compiled.width*scale),height:Math.round(compiled.height*scale),outputPath:path}}async function posterTime(film2){if(film2.posterTime!==void 0)return Math.max(0,Math.min(film2.duration,film2.posterTime));const active=t=>film2.clips.some(clip=>clip.t0<t&&t<clip.t1);const nudge=.001;const candidates=new Set;for(const clip of film2.clips){const t=clip.t1+nudge;if(t<film2.duration&&!active(t))candidates.add(t)}if(candidates.size===0)for(let i=1;i<=10;i++)candidates.add(film2.duration*i/10-nudge);const scored=[];for(const time of[...candidates].sort((a,b)=>a-b)){const frame=await frameAt(film2,time);scored.push({time,ink:frame.ops.length})}const fullest=Math.max(...scored.map(entry=>entry.ink));const rich=scored.filter(entry=>entry.ink>=fullest*.75);return rich[rich.length-1]?.time??film2.duration}function captionsToVtt(film2){const stamp=seconds=>{const m=Math.floor(seconds/60),s=seconds-m*60;return`${String(m).padStart(2,"0")}:${s.toFixed(3).padStart(6,"0")}`};const cues=film2.captions.map(cue=>`${stamp(cue.t0)} --> ${stamp(cue.t1)}
|
|
129
|
+
`;function resolveResvg(){const here=typeof __filename!=="undefined"?__filename:fileURLToPath(import.meta.url);return createRequire(here).resolve("@resvg/resvg-js")}var RasterPool=class{workers=[];idle=[];queue=[];pending=new Map;nextId=1;failure=null;constructor(size=defaultPoolSize()){const resvgPath=resolveResvg();for(let i=0;i<size;i++){const worker=new Worker(RASTER_WORKER_SOURCE,{eval:true,workerData:{resvgPath}});worker.on("message",message=>{const entry=this.pending.get(message.id);this.pending.delete(message.id);this.idle.push(worker);this.pump();if(!entry)return;if(message.error||!message.pixels)entry.reject(new Error(`Frame rasterization failed: ${message.error}`));else entry.resolve(message.pixels)});worker.on("error",error=>this.fail(error instanceof Error?error:new Error(String(error))));this.workers.push(worker);this.idle.push(worker)}}get size(){return this.workers.length}fail(error){this.failure=error;for(const entry of this.pending.values())entry.reject(error);this.pending.clear()}pump(){while(this.idle.length>0&&this.queue.length>0){const worker=this.idle.pop();const{job,id}=this.queue.shift();worker.postMessage({id,...job})}}run(job){if(this.failure)return Promise.reject(this.failure);const id=this.nextId++;return new Promise((resolve4,reject)=>{this.pending.set(id,{resolve:resolve4,reject});this.queue.push({job,id});this.pump()})}async close(){this.failure??=new Error("The raster pool was closed.");for(const entry of this.pending.values())entry.reject(this.failure);this.pending.clear();this.queue.length=0;await Promise.all(this.workers.map(worker=>worker.terminate()))}};function defaultPoolSize(){return Math.max(1,Math.min(12,cpus().length-2))}function framesToJob(frames,width,parseBackground,height){const first=frames[0];const scale=width/first.width;return{svgs:frames.map(frame=>frameToSvg(frame)),width,height:height??Math.round(first.height*scale),bloom:first.dark?first.bloom:0,background:parseBackground(first.background)}}var clamp01=t=>t<=0?0:t>=1?1:t;var linear=t=>t;function sigmoid(x){return 1/(1+Math.exp(-x))}function smoothBy(inflection){const low=sigmoid(-inflection/2);const high=sigmoid(inflection/2);return t=>{if(t<=0)return 0;if(t>=1)return 1;return(sigmoid(inflection*(t-.5))-low)/(high-low)}}var smooth2=smoothBy(10);var smoother=t=>{const x=clamp01(t);return x*x*x*(x*(x*6-15)+10)};var easeInQuad=t=>t*t;var easeOutQuad=t=>1-(1-t)*(1-t);var easeInCubic=t=>t*t*t;var easeOutCubic=t=>1-Math.pow(1-t,3);var easeInOutCubic=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;var easeOutQuint=t=>1-Math.pow(1-t,5);var easeInOutQuint=t=>t<.5?16*t*t*t*t*t:1-Math.pow(-2*t+2,5)/2;var easeOutExpo=t=>t>=1?1:1-Math.pow(2,-10*t);var easeInExpo=t=>t<=0?0:Math.pow(2,10*t-10);var rushInto=t=>2*smooth2(t/2);var rushFrom=t=>2*smooth2(t/2+.5)-1;var slowInto=t=>Math.sqrt(Math.max(0,1-(1-t)*(1-t)));function overshoot(amount2=1.70158){return t=>{const x=t-1;return x*x*((amount2+1)*x+amount2)+1}}function spring(options={}){const bounce2=options.bounce??.28;const frequency=options.frequency??2.2;const decay=-Math.log(Math.max(1e-4,bounce2))*2.4;return t=>{if(t<=0)return 0;if(t>=1)return 1;return 1-Math.exp(-decay*t)*Math.cos(frequency*Math.PI*2*t)*(1-t)}}var bounce=t=>{const n=7.5625,d=2.75;if(t<1/d)return n*t*t;if(t<2/d)return n*(t-=1.5/d)*t+.75;if(t<2.5/d)return n*(t-=2.25/d)*t+.9375;return n*(t-=2.625/d)*t+.984375};var thereAndBack=t=>smooth2(t<.5?2*t:2*(1-t));function thereAndBackWithPause(pause=1/3){const a=(1-pause)/2;return t=>{if(t<a)return smooth2(t/a);if(t<1-a)return 1;return smooth2((1-t)/a)}}function wiggle(cycles=2){return t=>thereAndBack(t)*Math.sin(cycles*Math.PI*2*t)}function notQuiteThere(amount2=.7,inner=smooth2){return t=>amount2*inner(t)}function lingering(hold2=.25,inner=smooth2){return t=>inner(clamp01(t/(1-hold2)))}function runningStart(pull=-.5){return t=>{const u=1-t;return 15*u**4*t**2*pull+20*u**3*t**3*pull+15*u**2*t**4+6*u*t**5+t**6}}function during(from,to2,inner=smooth2){return t=>inner(clamp01((t-from)/(to2-from)))}function cubicBezier(x1,y1,x2,y2){const cx=3*x1,bx=3*(x2-x1)-cx,ax=1-cx-bx;const cy=3*y1,by=3*(y2-y1)-cy,ay=1-cy-by;const sampleX=t=>((ax*t+bx)*t+cx)*t;const sampleY=t=>((ay*t+by)*t+cy)*t;const slope=t=>(3*ax*t+2*bx)*t+cx;return x=>{if(x<=0)return 0;if(x>=1)return 1;let t=x;for(let i=0;i<8;i++){const dx=sampleX(t)-x;const d=slope(t);if(Math.abs(dx)<1e-5||Math.abs(d)<1e-6)break;t-=dx/d}return sampleY(t)}}function growTo(r,target){const count=segmentCount(r);if(count>=target||count===0)return r;const segments=[];for(let i=0;i<count;i++){const o=i*6;const pts=Array.from(r.p.subarray(o,o+8));segments.push({pts,length:chord(pts)})}while(segments.length<target){let longest=0;for(let i=1;i<segments.length;i++)if(segments[i].length>segments[longest].length)longest=i;const[a,b]=bisect(segments[longest].pts);segments.splice(longest,1,{pts:a,length:chord(a)},{pts:b,length:chord(b)})}const out=new Float64Array(2+target*6);out[0]=r.p[0];out[1]=r.p[1];for(let i=0;i<target;i++){const pts=segments[i].pts;for(let k=0;k<6;k++)out[2+i*6+k]=pts[2+k]}return{p:out,closed:r.closed}}function chord(pts){return Math.hypot(pts[2]-pts[0],pts[3]-pts[1])+Math.hypot(pts[4]-pts[2],pts[5]-pts[3])+Math.hypot(pts[6]-pts[4],pts[7]-pts[5])}function bisect(p){const ax=(p[0]+p[2])/2,ay=(p[1]+p[3])/2;const bx=(p[2]+p[4])/2,by=(p[3]+p[5])/2;const cx=(p[4]+p[6])/2,cy=(p[5]+p[7])/2;const dx=(ax+bx)/2,dy=(ay+by)/2;const ex=(bx+cx)/2,ey=(by+cy)/2;const fx=(dx+ex)/2,fy=(dy+ey)/2;return[[p[0],p[1],ax,ay,dx,dy,fx,fy],[fx,fy,ex,ey,cx,cy,p[6],p[7]]]}function bestRotation(a,b){const count=segmentCount(b);if(!a.closed||!b.closed||count<2)return b;const[ax,ay]=ringCenter(a),[bx,by]=ringCenter(b);const stride=Math.max(1,Math.floor(count/48));let best=0,bestCost=Infinity;for(let shift2=0;shift2<count;shift2+=stride){let cost=0;for(let i=0;i<count;i+=stride){const j=(i+shift2)%count;const dx=a.p[i*6]-ax-(b.p[j*6]-bx);const dy=a.p[i*6+1]-ay-(b.p[j*6+1]-by);cost+=dx*dx+dy*dy}if(cost<bestCost){bestCost=cost;best=shift2}}if(best===0)return b;const out=new Float64Array(b.p.length);out[0]=b.p[best*6];out[1]=b.p[best*6+1];for(let i=0;i<count;i++){const j=(i+best)%count;for(let k=0;k<6;k++)out[2+i*6+k]=b.p[2+j*6+k]}return{p:out,closed:b.closed}}function pointRing(x,y,count,closed){const out=new Float64Array(2+count*6);for(let i=0;i<out.length;i+=2){out[i]=x;out[i+1]=y}return{p:out,closed}}function pairRings(from,to2){const rank=path=>[...path].sort((a2,b2)=>Math.abs(signedArea(b2))+ringLength(b2)*.01-(Math.abs(signedArea(a2))+ringLength(a2)*.01));const a=rank(from),b=rank(to2);const pairs=[];const free=b.slice();for(const ringA of a){if(free.length===0){const[x,y]=ringCenter(ringA);pairs.push([ringA,pointRing(x,y,segmentCount(ringA),ringA.closed)]);continue}const[ax,ay]=ringCenter(ringA);let bestIndex=0,bestCost=Infinity;for(let i=0;i<Math.min(free.length,3);i++){const[bx,by]=ringCenter(free[i]);const cost=Math.hypot(ax-bx,ay-by)+i*40;if(cost<bestCost){bestCost=cost;bestIndex=i}}pairs.push([ringA,free[bestIndex]]);free.splice(bestIndex,1)}for(const ringB of free){const[x,y]=ringCenter(ringB);pairs.push([pointRing(x,y,segmentCount(ringB),ringB.closed),ringB])}return pairs}function alignPaths(from,to2,minSegments=12){const pairs=pairRings(from,to2);const a=[],b=[],closed=[];for(const[ra,rb]of pairs){const target=Math.max(segmentCount(ra),segmentCount(rb),ra.closed&&rb.closed?minSegments:1);let x=growTo(ra,target);let y=growTo(rb,target);if(x.closed&&y.closed){if(Math.sign(signedArea(x))!==Math.sign(signedArea(y))&&signedArea(x)!==0&&signedArea(y)!==0)y=reverseRing(y);y=bestRotation(x,y)}else if(!x.closed&&!y.closed){const n=x.p.length;const straight=Math.hypot(x.p[0]-y.p[0],x.p[1]-y.p[1])+Math.hypot(x.p[n-2]-y.p[n-2],x.p[n-1]-y.p[n-1]);const flipped=Math.hypot(x.p[0]-y.p[n-2],x.p[1]-y.p[n-1])+Math.hypot(x.p[n-2]-y.p[0],x.p[n-1]-y.p[1]);if(flipped<straight)y=reverseRing(y)}a.push(x.p);b.push(y.p);closed.push(x.closed&&y.closed)}return{from:a,to:b,closed}}function pathMixer(from,to2){if(from===to2)return()=>to2;if(pathLength(from)===0&&from.length===0)return alpha2=>alpha2>=1?to2:from;const aligned=alignPaths(from,to2);return alpha2=>{if(alpha2<=0)return from;if(alpha2>=1)return to2;const rings=new Array(aligned.from.length);for(let r=0;r<rings.length;r++){const a=aligned.from[r],b=aligned.to[r];const out=new Float64Array(a.length);for(let i=0;i<a.length;i++)out[i]=a[i]+(b[i]-a[i])*alpha2;rings[r]={p:out,closed:aligned.closed[r]}}return rings}}function matchSequence(a,b){const n=a.length,m=b.length;const table=Array.from({length:n+1},()=>new Uint16Array(m+1));for(let i2=n-1;i2>=0;i2--){for(let j2=m-1;j2>=0;j2--){table[i2][j2]=a[i2]===b[j2]?table[i2+1][j2+1]+1:Math.max(table[i2+1][j2],table[i2][j2+1])}}const pairs=[];let i=0,j=0;while(i<n&&j<m){if(a[i]===b[j]){pairs.push([i++,j++])}else if(table[i+1][j]>=table[i][j+1]){i++}else{j++}}return pairs}var DEFAULT_PROPS={x:0,y:0,rotation:0,sx:1,sy:1,px:0,py:0,opacity:1,visible:true,z:0,path:null,fill:null,fillOpacity:1,stroke:null,strokeOpacity:1,strokeWidth:3,cap:"round",join:"round",dash:null,dashOffset:0,trimFrom:0,trimTo:1,trimEach:false,glow:0,glowColor:null,blend:"normal",fixed:false,image:null};var NUMERIC=new Set(["x","y","rotation","sx","sy","px","py","opacity","z","fillOpacity","strokeOpacity","strokeWidth","dashOffset","trimFrom","trimTo","glow"]);function mixer(prop,from,to2){if(NUMERIC.has(prop)){const a=from,b=to2;return(alpha2=>a+(b-a)*alpha2)}if(prop==="fill"||prop==="stroke"){const a=from,b=to2;if(a&&b)return(alpha2=>mixPaint(a,b,alpha2));return null}if(prop==="glowColor"){const a=from,b=to2;if(a&&b)return(alpha2=>mixColor(a,b,alpha2));return null}if(prop==="path"){const a=from,b=to2;if(a&&b)return pathMixer(a,b);return null}return null}var nextId=1;var Node=class _Node{id=nextId++;parent=null;children=[];data={};label="";base=Object.create(DEFAULT_PROPS);tracks=null;overlay=null;overlayFrame=-1;mounted=false;draw=null;rawOps=null;constructor(path){if(path)this.base.path=path}get(prop){const overlay=this.overlay;if(overlay!==null&&overlay.has(prop)&&(this.overlayFrame===clock.frame||clock.capture!==null)){return overlay.get(prop)}const track=this.tracks?.get(prop);if(track)return track.sample(clock.now);return this.base[prop]}set(prop,value){if(clock.capture){this.overlay??=new Map;this.overlay.set(prop,value);clock.capture.add(this);return this}if(!this.mounted){this.base[prop]=value;return this}if(clock.mode==="render"){this.overlay??=new Map;if(this.overlayFrame!==clock.frame){this.overlay.clear();this.overlayFrame=clock.frame}this.overlay.set(prop,value);return this}this.track(prop).step(clock.now,value);return this}track(prop){this.tracks??=new Map;let track=this.tracks.get(prop);if(!track){track=new Track(this.base[prop]);this.tracks.set(prop,track)}return track}tween(prop,to2,t0,t1,ease){const previous=clock.now;clock.now=t0;const from=this.get(prop);clock.now=previous;const at=t1>t0?mixer(prop,from,to2):null;const key={t0,t1,ease,to:to2,at};this.track(prop).add(key)}add(...nodes){for(const child of nodes){if(child.parent===this)continue;child.parent?.drop(child);child.parent=this;this.children.push(child);if(this.mounted)mountTree(child,clock.now)}return this}drop(child){const index=this.children.indexOf(child);if(index>=0)this.children.splice(index,1);child.parent=null;return this}all(){const out=[];const visit=node=>{out.push(node);for(const child of node.children)visit(child)};visit(this);return out}leaves(){return this.all().filter(node=>node.get("path")!==null||node.draw!==null||node.get("image")!==null)}clone(){const copy=Object.create(Object.getPrototypeOf(this));Object.assign(copy,this);copy.id=nextId++;copy.parent=null;copy.mounted=false;copy.tracks=null;copy.overlay=null;copy.overlayFrame=-1;copy.data={...this.data};copy.base=Object.create(DEFAULT_PROPS);for(const key of Object.keys(DEFAULT_PROPS)){;copy.base[key]=this.get(key)}copy.children=this.children.map(child=>{const next=child.clone();next.parent=copy;return next});return copy}localMatrix(){return compose(this.get("x"),this.get("y"),this.get("rotation"),this.get("sx"),this.get("sy"),this.get("px"),this.get("py"))}worldMatrix(){let m=this.localMatrix();for(let node=this.parent;node;node=node.parent)m=mul(node.localMatrix(),m);return m}toWorld(x,y){return apply(this.worldMatrix(),x,y)}bounds(){return this.boundsFrom(this.parent?this.parent.worldMatrix():IDENTITY)??{x:0,y:0,width:0,height:0}}boundsFrom(parent){const m=mul(parent,this.localMatrix());let result=null;const path=this.get("path");if(path)result=pathBounds(transformPath(path,m));const image=this.get("image");if(image)result=unionBounds(result,boundsOfRect(m,image.width,image.height));if(this.draw){const built=this.draw(clock.now);const list3=built===null?[]:Array.isArray(built)?built:[built];for(const child of list3)result=unionBounds(result,child.boundsFrom(m))}for(const child of this.children){if(child.get("visible"))result=unionBounds(result,child.boundsFrom(m))}return result}get center(){const b=this.bounds();return[b.x+b.width/2,b.y+b.height/2]}get top(){const b=this.bounds();return[b.x+b.width/2,b.y]}get bottom(){const b=this.bounds();return[b.x+b.width/2,b.y+b.height]}get left(){const b=this.bounds();return[b.x,b.y+b.height/2]}get right(){const b=this.bounds();return[b.x+b.width,b.y+b.height/2]}get width(){return this.bounds().width}get height(){return this.bounds().height}at(x,y){const[px,py]=typeof x==="number"?[x,y??0]:x;this.set("x",px);this.set("y",py);return this}shift(dx,dy){const[ox,oy]=typeof dx==="number"?[dx,dy??0]:dx;this.set("x",this.get("x")+ox);this.set("y",this.get("y")+oy);return this}moveTo(target){const destination=target instanceof _Node?target.center:target;const[cx,cy]=this.center;const inverse=this.parent?invert(this.parent.worldMatrix()):IDENTITY;const[lx0,ly0]=apply(inverse,cx,cy);const[lx1,ly1]=apply(inverse,destination[0],destination[1]);return this.shift(lx1-lx0,ly1-ly0)}pivotAt(point){const parent=this.parent?this.parent.worldMatrix():IDENTITY;const before=mul(parent,this.localMatrix());const[lx,ly]=apply(invert(before),point[0],point[1]);const[nx,ny]=apply(invert(parent),point[0],point[1]);this.set("px",lx);this.set("py",ly);this.set("x",nx);this.set("y",ny);return this}scale(factor,about){const[fx,fy]=typeof factor==="number"?[factor,factor]:factor;this.pivotAt(about??this.center);this.set("sx",this.get("sx")*fx);this.set("sy",this.get("sy")*fy);return this}rotate(radians,about){this.pivotAt(about??this.center);this.set("rotation",this.get("rotation")+radians);return this}fitTo(size){const b=this.bounds();const scales=[];if(size.width!==void 0&&b.width>0)scales.push(size.width/b.width);if(size.height!==void 0&&b.height>0)scales.push(size.height/b.height);return scales.length?this.scale(Math.min(...scales)):this}nextTo(target,side="right",gap=28){const[dx,dy]=direction(side);const b=target instanceof _Node?target.bounds():{x:target[0],y:target[1],width:0,height:0};const own=this.bounds();const cx=b.x+b.width/2,cy=b.y+b.height/2;const anchorX=cx+dx*(b.width/2+gap+own.width/2);const anchorY=cy+dy*(b.height/2+gap+own.height/2);return this.moveTo([anchorX,anchorY])}alignTo(target,edge){const own=this.bounds();const b=target instanceof _Node?target.bounds():{x:target[0],y:target[1],width:0,height:0};if(edge==="left")return this.shift(b.x-own.x,0);if(edge==="right")return this.shift(b.x+b.width-own.x-own.width,0);if(edge==="top")return this.shift(0,b.y-own.y);return this.shift(0,b.y+b.height-own.y-own.height)}arrange(side="right",gap=24){const[dx,dy]=direction(side);const center2=this.center;let previous=null;for(const child of this.children){if(previous){const b=previous.bounds(),own=child.bounds();const px=b.x+b.width/2+dx*(b.width/2+gap+own.width/2);const py=b.y+b.height/2+dy*(b.height/2+gap+own.height/2);child.moveTo([dx===0?b.x+b.width/2:px,dy===0?b.y+b.height/2:py])}previous=child}return this.moveTo(center2)}fill(color,opacity){this.set("fill",color===null?null:toPaint(color));if(opacity!==void 0)this.set("fillOpacity",opacity);return this}stroke(color,width,opacity){this.set("stroke",color===null?null:toPaint(color));if(width!==void 0)this.set("strokeWidth",width);if(opacity!==void 0)this.set("strokeOpacity",opacity);return this}color(color){const paint=toPaint(color);for(const node of this.all()){if(node.get("stroke"))node.set("stroke",paint);if(node.get("fill"))node.set("fill",paint);if(node.get("glowColor")&&!isGradient(paint))node.set("glowColor",paint)}return this}opacity(value){return this.set("opacity",value)}glow(radius,color){this.set("glow",radius);if(color!==void 0){const paint=toPaint(color);this.set("glowColor",isGradient(paint)?null:paint)}return this}dash(pattern,offset=0){this.set("dash",pattern);return this.set("dashOffset",offset)}zIndex(value){return this.set("z",value)}pin(){return this.set("fixed",true)}hide(){return this.set("visible",false)}show(){return this.set("visible",true)}named(label){this.label=label;return this}};function boundsOfRect(m,width,height){const corners=[apply(m,0,0),apply(m,width,0),apply(m,width,height),apply(m,0,height)];const xs=corners.map(c=>c[0]),ys=corners.map(c=>c[1]);const x=Math.min(...xs),y=Math.min(...ys);return{x,y,width:Math.max(...xs)-x,height:Math.max(...ys)-y}}function direction(side){if(typeof side!=="string")return side;if(side==="left")return[-1,0];if(side==="right")return[1,0];if(side==="top"||side==="up")return[0,-1];return[0,1]}function mountTree(node,time){const wasVisible=node.base.visible;for(const entry of node.all())entry.mounted=true;if(time>0||!wasVisible){const track=node.track("visible");track.initial=false;if(wasVisible)track.step(time,true)}}function group(...children){return new Node().add(...children)}function dynamic(build){const node=new Node;node.draw=build;return node}function list(target){return Array.isArray(target)?[...target]:[target]}function run(anim,t0,t1,parent){clock.now=t0;anim.schedule({t0,t1,ease:anim.ease??parent.ease,stage:parent.stage})}function par(...anims){const duration=Math.max(0,...anims.map(a=>a.duration));return{label:"par",duration,schedule(ctx){const k=duration>0?(ctx.t1-ctx.t0)/duration:1;for(const anim of anims)run(anim,ctx.t0,ctx.t0+anim.duration*k,ctx)}}}function seq(...anims){const duration=anims.reduce((sum,a)=>sum+a.duration,0);return{label:"seq",duration,schedule(ctx){const k=duration>0?(ctx.t1-ctx.t0)/duration:1;let t=ctx.t0;for(const anim of anims){const next=t+anim.duration*k;run(anim,t,next,ctx);t=next}}}}function lagged(anims,options={}){const lag=options.lag??.15;const longest=Math.max(0,...anims.map(a=>a.duration));const natural=anims.length===0?0:longest*(1+(anims.length-1)*lag);return{label:"lagged",duration:options.duration??natural,schedule(ctx){const total=ctx.t1-ctx.t0;const each=anims.length===0?0:total/(1+(anims.length-1)*lag);anims.forEach((anim,i)=>{const start=ctx.t0+i*lag*each;run(anim,start,start+each,ctx)})}}}function delay(anim,seconds){return{label:anim.label,duration:anim.duration+seconds,ease:anim.ease,schedule(ctx){const k=anim.duration+seconds>0?(ctx.t1-ctx.t0)/(anim.duration+seconds):1;run(anim,ctx.t0+seconds*k,ctx.t1,ctx)}}}function retime(anim,options){return{...anim,duration:options.duration??anim.duration,ease:options.ease??anim.ease}}function call(fn){return{label:"call",duration:0,schedule:()=>fn()}}function ensureVisible(node,t,stage){if(!node.mounted){let top=node;while(top.parent&&top.parent!==stage.root)top=top.parent;stage.mountAt(top,t)}for(let n=node;n&&n!==stage.root;n=n.parent){const previous=clock.now;clock.now=t;const visible=n.get("visible");clock.now=previous;if(!visible)n.track("visible").step(t,true)}}function hideAt(node,t){node.track("visible").step(t,false)}function holdUntil(node,t0,start){if(start<=t0)return;node.track("visible").step(t0,false);node.track("visible").step(start,true)}var stepAt=(node,prop,value,t)=>{node.track(prop).step(t,value)};function valueAt(node,prop,t){const previous=clock.now;clock.now=t;const value=node.get(prop);clock.now=previous;return value}function solid2(paint){return isGradient(paint)?sampleStops(paint.stops,.5):paint}function drawable(target){return list(target).flatMap(node=>node.leaves().filter(leaf=>leaf.get("path")))}function drawLeaf(leaf,t0,t1,ease,outline){const d=t1-t0;const fill=leaf.get("fill"),stroke=leaf.get("stroke");const fillTarget=leaf.get("fillOpacity");const strokeTarget=leaf.get("strokeOpacity");if(fill&&!stroke){const width=valueAt(leaf,"strokeWidth",t0);stepAt(leaf,"stroke",solid2(fill),t0);stepAt(leaf,"strokeWidth",outline,t0);stepAt(leaf,"strokeOpacity",1,t0);stepAt(leaf,"trimTo",0,t0);stepAt(leaf,"fillOpacity",0,t0);leaf.tween("trimTo",1,t0,t0+d*.72,ease);leaf.tween("fillOpacity",fillTarget,t0+d*.42,t1,ease);leaf.tween("strokeOpacity",0,t0+d*.62,t1,ease);stepAt(leaf,"stroke",null,t1);stepAt(leaf,"strokeWidth",width,t1);stepAt(leaf,"strokeOpacity",strokeTarget,t1);return}stepAt(leaf,"trimTo",0,t0);leaf.tween("trimTo",1,t0,fill?t0+d*.8:t1,ease);if(fill){stepAt(leaf,"fillOpacity",0,t0);leaf.tween("fillOpacity",fillTarget,t0+d*.5,t1,ease)}}function drawAnim(label,target,options,defaults){const nodes=list(target);const count=drawable(nodes).length;const lag=options.lag??defaults.lag;const natural=options.duration??(count<=1?defaults.duration:Math.min(defaults.duration*2.4,defaults.duration+count*.035));return{label,duration:natural,ease:options.ease,schedule(ctx){for(const node of nodes)ensureVisible(node,ctx.t0,ctx.stage);const leaves=drawable(nodes);if(leaves.length===0)return;const total=ctx.t1-ctx.t0;const each=total/(1+(leaves.length-1)*lag);leaves.forEach((leaf,i)=>{const start=ctx.t0+i*lag*each;clock.now=start;holdUntil(leaf,ctx.t0,start);drawLeaf(leaf,start,start+each,ctx.ease,defaults.outline)});clock.now=ctx.t0}}}function draw(target,options={}){return drawAnim("draw",target,options,{lag:.04,duration:1.3,outline:2})}function write(target,options={}){return drawAnim("write",target,options,{lag:.22,duration:1.1,outline:1.3})}function erase(target,options={}){const nodes=list(target);return{label:"erase",duration:options.duration??.8,ease:options.ease,schedule(ctx){const leaves=drawable(nodes);const lag=options.lag??.02;const each=(ctx.t1-ctx.t0)/(1+Math.max(0,leaves.length-1)*lag);leaves.forEach((leaf,i)=>{const start=ctx.t0+i*lag*each;clock.now=start;const fill=leaf.get("fill");if(leaf.get("stroke"))leaf.tween("trimFrom",1,start,start+each,ctx.ease);if(fill)leaf.tween("fillOpacity",0,start,start+each*.7,ctx.ease)});for(const node of nodes)hideAt(node,ctx.t1)}}}function fadeIn(target,options={}){const nodes=list(target);return{label:"fadeIn",duration:options.duration??.8,ease:options.ease,schedule(ctx){const items=options.lag!==void 0&&nodes.length===1&&nodes[0].children.length>0?nodes[0].children:nodes;for(const node of nodes)ensureVisible(node,ctx.t0,ctx.stage);const lag=options.lag??0;const each=(ctx.t1-ctx.t0)/(1+Math.max(0,items.length-1)*lag);items.forEach((node,i)=>{const start=ctx.t0+i*lag*each,end=start+each;clock.now=start;holdUntil(node,ctx.t0,start);const opacity=node.get("opacity");stepAt(node,"opacity",0,start);node.tween("opacity",opacity,start,end,ctx.ease);if(options.shift){const x=node.get("x"),y=node.get("y");stepAt(node,"x",x+options.shift[0],start);stepAt(node,"y",y+options.shift[1],start);node.tween("x",x,start,end,ctx.ease);node.tween("y",y,start,end,ctx.ease)}if(options.scale!==void 0)scaleFrom(node,options.scale,start,end,ctx.ease)});clock.now=ctx.t0}}}function scaleFrom(node,factor,t0,t1,ease,about){const previous=clock.now;clock.now=t0;node.pivotAt(about??node.center);const sx=node.get("sx"),sy=node.get("sy");stepAt(node,"sx",sx*factor,t0);stepAt(node,"sy",sy*factor,t0);node.tween("sx",sx,t0,t1,ease);node.tween("sy",sy,t0,t1,ease);clock.now=previous}function fadeOut(target,options={}){const nodes=list(target);return{label:"fadeOut",duration:options.duration??.6,ease:options.ease,schedule(ctx){for(const node of nodes){const opacity=node.get("opacity");node.tween("opacity",0,ctx.t0,ctx.t1,ctx.ease);if(options.shift){node.tween("x",node.get("x")+options.shift[0],ctx.t0,ctx.t1,ctx.ease);node.tween("y",node.get("y")+options.shift[1],ctx.t0,ctx.t1,ctx.ease)}if(options.scale!==void 0){node.pivotAt(node.center);node.tween("sx",node.get("sx")*options.scale,ctx.t0,ctx.t1,ctx.ease);node.tween("sy",node.get("sy")*options.scale,ctx.t0,ctx.t1,ctx.ease)}hideAt(node,ctx.t1);stepAt(node,"opacity",opacity,ctx.t1)}}}}function grow(target,options={}){const nodes=list(target);return{label:"grow",duration:options.duration??.9,ease:options.ease,schedule(ctx){for(const node of nodes){ensureVisible(node,ctx.t0,ctx.stage);scaleFrom(node,.001,ctx.t0,ctx.t1,ctx.ease,options.from)}}}}function appear(target){const nodes=list(target);return{label:"appear",duration:0,schedule:ctx=>{for(const node of nodes)ensureVisible(node,ctx.t0,ctx.stage)}}}function vanish(target){const nodes=list(target);return{label:"vanish",duration:0,schedule:ctx=>{for(const node of nodes)hideAt(node,ctx.t0)}}}function to(node,change,options={}){return{label:"to",duration:options.duration??1,ease:options.ease,schedule(ctx){ensureVisible(node,ctx.t0,ctx.stage);const touched=new Set;clock.capture=touched;try{change(node)}finally{clock.capture=null}for(const entry of touched){const target=entry;const values=new Map(target.overlay);target.overlay.clear();applyChanges(target,values,ctx,options.restore===true)}}}}function applyChanges(node,values,ctx,restore){const{t0,t1,ease}=ctx;const props=values;const restoreValues=new Map;const px=props.get("px"),py=props.get("py");if(px!==void 0||py!==void 0){const nextPx=px??node.get("px"),nextPy=py??node.get("py");const m=compose(node.get("x"),node.get("y"),node.get("rotation"),node.get("sx"),node.get("sy"),node.get("px"),node.get("py"));const[startX,startY]=apply(m,nextPx,nextPy);stepAt(node,"px",nextPx,t0);stepAt(node,"py",nextPy,t0);stepAt(node,"x",startX,t0);stepAt(node,"y",startY,t0);props.delete("px");props.delete("py")}clock.now=t0;for(const[prop,value]of props){const from=node.get(prop);if(from===value)continue;if(restore)restoreValues.set(prop,from);node.tween(prop,value,t0,t1,ease)}for(const[prop,value]of restoreValues)stepAt(node,prop,value,t1)}function moveTo(node,target,options={}){return{...to(node,n=>n.moveTo(target),options),label:"moveTo"}}function shift(node,dx,dy,options={}){return{...to(node,n=>n.shift(dx,dy),options),label:"shift"}}function scaleBy(node,factor,options={}){return{...to(node,n=>n.scale(factor,options.about),options),label:"scale"}}function rotate(node,radians,options={}){return{...to(node,n=>n.rotate(radians,options.about),options),label:"rotate"}}function recolor(node,color,options={}){return{...to(node,n=>n.color(color),options),label:"recolor"}}function fade(node,opacity,options={}){return{...to(node,n=>n.opacity(opacity),{duration:.6,...options}),label:"fade"}}function along2(node,track,options={}){return{label:"along",duration:options.duration??2,ease:options.ease,schedule(ctx){ensureVisible(node,ctx.t0,ctx.stage);const path=track instanceof Node?transformPath(track.get("path")??[],track.worldMatrix()):track;const inverse=node.parent?invertSafe(node.parent.worldMatrix()):null;const position2=alpha2=>{const[x,y]=pointAt(path,alpha2);return inverse?apply(inverse,x,y):[x,y]};const[endX,endY]=position2(1);node.track("x").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:endX,at:a=>position2(a)[0]});node.track("y").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:endY,at:a=>position2(a)[1]});if(options.orient){const angle=alpha2=>{const[dx,dy]=tangentAt(path,alpha2);return Math.atan2(dy,dx)};node.track("rotation").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:angle(1),at:angle})}}}}function invertSafe(m){const det=m[0]*m[3]-m[1]*m[2];if(Math.abs(det)<1e-12)return[1,0,0,1,0,0];const i=1/det;return[m[3]*i,-m[1]*i,-m[2]*i,m[0]*i,(m[2]*m[5]-m[3]*m[4])*i,(m[1]*m[4]-m[0]*m[5])*i]}function warp(target,f,options={}){const nodes=list(target);return{label:"warp",duration:options.duration??2,ease:options.ease,schedule(ctx){for(const leaf of drawable(nodes)){ensureVisible(leaf,ctx.t0,ctx.stage);const path=leaf.get("path");const world=leaf.worldMatrix();const inverse=invertSafe(world);const start=path.map(r=>subdivideEach(r,options.subdivisions??6));const end=warpPath(start,(x,y)=>{const[wx,wy]=apply(world,x,y);const[mx,my]=f(wx,wy);return apply(inverse,mx,my)},1);leaf.track("path").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:end,at:alpha2=>start.map((r,i)=>{const a=r.p,b=end[i].p;const out=new Float64Array(a.length);for(let k=0;k<a.length;k++)out[k]=a[k]+(b[k]-a[k])*alpha2;return{p:out,closed:r.closed}})})}}}}function applyMatrix(target,matrix2,options={}){const[ox,oy]=options.origin??[0,0];const flip=options.yUp===false?1:-1;const[[a,b],[c,d]]=matrix2;return{...warp(target,(x,y)=>{const ux=x-ox,uy=(y-oy)*flip;const vx=a*ux+b*uy,vy=c*ux+d*uy;return[ox+vx,oy+vy*flip]},{subdivisions:1,...options}),label:"applyMatrix"}}function chainOpacity(node){let value=1;for(let n=node;n;n=n.parent)value*=n.get("opacity");return value}function bake(leaf){const m=leaf.worldMatrix();const opacity=chainOpacity(leaf);let z=0;let fixed=false;for(let n=leaf;n;n=n.parent){z+=n.get("z");fixed||=n.get("fixed")}return{path:transformPath(leaf.get("path")??[],m),fill:leaf.get("fill"),fillOpacity:leaf.get("fill")?leaf.get("fillOpacity")*opacity:0,stroke:leaf.get("stroke"),strokeOpacity:leaf.get("stroke")?leaf.get("strokeOpacity")*opacity:0,strokeWidth:leaf.get("strokeWidth")*matScale(m),glow:leaf.get("glow"),glowColor:leaf.get("glowColor"),cap:leaf.get("cap"),dash:leaf.get("dash"),z,fixed,key:leaf.data["key"]}}function ghost(stage,from,to2,ctx){const node=new Node;node.base.visible=false;node.base.path=from.path;node.base.cap=from.cap;node.base.z=from.z;node.base.fixed=from.fixed;node.base.fill=from.fill??to2.fill;node.base.stroke=from.stroke??to2.stroke;node.base.fillOpacity=from.fillOpacity;node.base.strokeOpacity=from.strokeOpacity;node.base.strokeWidth=from.strokeWidth||to2.strokeWidth;node.base.glow=from.glow;node.base.glowColor=from.glowColor??to2.glowColor;stage.root.add(node);node.track("visible").initial=false;node.track("visible").keys.length=0;stepAt(node,"visible",true,ctx.appear??ctx.t0);node.track("path").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:to2.path,at:pathMixer(from.path,to2.path)});if(from.fill&&to2.fill)node.tween("fill",to2.fill,ctx.t0,ctx.t1,ctx.ease);if(from.stroke&&to2.stroke)node.tween("stroke",to2.stroke,ctx.t0,ctx.t1,ctx.ease);node.tween("fillOpacity",to2.fillOpacity,ctx.t0,ctx.t1,ctx.ease);node.tween("strokeOpacity",to2.strokeOpacity,ctx.t0,ctx.t1,ctx.ease);node.tween("strokeWidth",to2.strokeWidth||from.strokeWidth,ctx.t0,ctx.t1,ctx.ease);if(from.glow!==to2.glow)node.tween("glow",to2.glow,ctx.t0,ctx.t1,ctx.ease);stepAt(node,"visible",false,ctx.hide??ctx.t1);return node}function pairCounts(from,to2){const count=Math.max(from.length,to2.length);const pairs=[];for(let i=0;i<count;i++){pairs.push([from[Math.min(from.length-1,Math.floor(i*from.length/count))],to2[Math.min(to2.length-1,Math.floor(i*to2.length/count))]])}return pairs}function morph(from,to2,options={}){const a=list(from),b=list(to2);return{label:"morph",duration:options.duration??1.2,ease:options.ease,schedule(ctx){prepareTargets(b,ctx);const fromLeaves=drawable(a).map(bake);const toLeaves=drawable(b).map(bake);if(fromLeaves.length===0||toLeaves.length===0){for(const node of a)hideAt(node,ctx.t0);for(const node of b)ensureVisible(node,ctx.t0,ctx.stage);return}const pairs=pairCounts(fromLeaves,toLeaves);const lag=options.lag??0;const each=(ctx.t1-ctx.t0)/(1+Math.max(0,pairs.length-1)*lag);pairs.forEach(([x,y],i)=>{const start=ctx.t0+i*lag*each;ghost(ctx.stage,x,y,{t0:start,t1:start+each,ease:ctx.ease,appear:ctx.t0,hide:ctx.t1})});finishMorph(a,b,ctx)}}}function prepareTargets(targets,ctx){clock.now=ctx.t0;for(const node of targets){ctx.stage.mountAt(node,ctx.t0);hideAt(node,ctx.t0)}}function finishMorph(a,b,ctx){for(const node of a)hideAt(node,ctx.t0);for(const node of b)node.track("visible").step(ctx.t1,true);clock.now=ctx.t0}function morphMatching(from,to2,options={}){return{label:"morphMatching",duration:options.duration??1.4,ease:options.ease,schedule(ctx){prepareTargets([to2],ctx);const keyOf=options.key??(leaf=>leaf.data["key"]);const fromLeaves=drawable(from),toLeaves=drawable(to2);const fromBaked=fromLeaves.map(bake),toBaked=toLeaves.map(bake);const pairs=matchSequence(fromLeaves.map(keyOf),toLeaves.map(keyOf));const usedFrom=new Set(pairs.map(([i])=>i)),usedTo=new Set(pairs.map(([,j])=>j));for(const[i,j]of pairs)ghost(ctx.stage,fromBaked[i],toBaked[j],ctx);const span=ctx.t1-ctx.t0;const offset=options.fadeShift??[0,0];const shifted=(bakedPath,dx,dy)=>transformPath(bakedPath,[1,0,0,1,dx,dy]);fromBaked.forEach((baked,i)=>{if(usedFrom.has(i))return;ghost(ctx.stage,baked,{...baked,path:shifted(baked.path,offset[0],offset[1]),fillOpacity:0,strokeOpacity:0},{t0:ctx.t0,t1:ctx.t0+span*.55,ease:ctx.ease})});toBaked.forEach((baked,j)=>{if(usedTo.has(j))return;ghost(ctx.stage,{...baked,path:shifted(baked.path,-offset[0],-offset[1]),fillOpacity:0,strokeOpacity:0},baked,{t0:ctx.t0+span*.35,t1:ctx.t1,ease:ctx.ease})});finishMorph([from],[to2],ctx)}}}function indicate(target,options={}){const nodes=list(target);const anims=nodes.map(node=>retime(to(node,n=>{n.scale(options.scale??1.14);n.color(options.color??"yellow")},{restore:true}),{ease:options.ease??thereAndBack}));return{...par(...anims),label:"indicate",duration:options.duration??.9}}function shake(node,options={}){return{label:"shake",duration:options.duration??.8,ease:wiggle(options.cycles??3),schedule(ctx){clock.now=ctx.t0;const[cx,cy]=node.center;node.pivotAt([cx,cy]);const rotation=node.get("rotation");const angle=options.angle??.08;const track=node.track("rotation");track.add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:rotation,at:alpha2=>rotation+angle*alpha2})}}}function circumscribe(target,options={}){return{label:"circumscribe",duration:options.duration??1.3,ease:options.ease??linear,schedule(ctx){const b=target.bounds();const pad2=options.pad??14;const outline=new Node(rectPath(b.x-pad2,b.y-pad2,b.width+pad2*2,b.height+pad2*2,options.radius??12)).stroke(options.color??"yellow",options.width??3).glow(8);ctx.stage.add(outline);const t0=ctx.t0,t1=ctx.t1,mid=t0+(t1-t0)*.55;stepAt(outline,"trimTo",0,t0);outline.tween("trimTo",1,t0,mid,smooth2);outline.tween("trimFrom",1,mid-(t1-t0)*.08,t1,smooth2);hideAt(outline,t1)}}}function flash(point,options={}){return{label:"flash",duration:options.duration??.7,ease:options.ease??smooth2,schedule(ctx){const center2=point instanceof Node?point.center:point;const radius=options.radius??54;const rays=options.rays??12;for(let i=0;i<rays;i++){const angle=i/rays*Math.PI*2;const cos=Math.cos(angle),sin=Math.sin(angle);const ray=new Node(linePath([center2[0]+cos*radius*.35,center2[1]+sin*radius*.35],[center2[0]+cos*radius,center2[1]+sin*radius])).stroke(options.color??"yellow",2.5).glow(5);ctx.stage.add(ray);stepAt(ray,"trimTo",0,ctx.t0);ray.tween("trimTo",1,ctx.t0,ctx.t0+(ctx.t1-ctx.t0)*.6,ctx.ease);ray.tween("trimFrom",1,ctx.t0+(ctx.t1-ctx.t0)*.25,ctx.t1,ctx.ease);hideAt(ray,ctx.t1)}}}}function ripple(point,options={}){return{label:"ripple",duration:options.duration??1,ease:options.ease??smooth2,schedule(ctx){const center2=point instanceof Node?point.center:point;const ring2=new Node(circlePath(0,0,options.radius??90)).stroke(options.color??"blue",options.width??3).at(center2);ctx.stage.add(ring2);stepAt(ring2,"sx",.05,ctx.t0);stepAt(ring2,"sy",.05,ctx.t0);ring2.tween("sx",1,ctx.t0,ctx.t1,ctx.ease);ring2.tween("sy",1,ctx.t0,ctx.t1,ctx.ease);ring2.tween("strokeOpacity",0,ctx.t0+(ctx.t1-ctx.t0)*.2,ctx.t1,ctx.ease);hideAt(ring2,ctx.t1)}}}function pulse(line2,options={}){return{label:"pulse",duration:options.duration??1.1,ease:options.ease??smooth2,schedule(ctx){const path=line2.get("path");if(!path)return;const lit=new Node(transformPath(path,line2.worldMatrix())).stroke(options.color??"yellow",options.width??line2.get("strokeWidth")+1.5).glow(options.glow??10);ctx.stage.add(lit);const length=options.length??.18;stepAt(lit,"trimFrom",0,ctx.t0);stepAt(lit,"trimTo",0,ctx.t0);lit.track("trimTo").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:1,at:a=>Math.min(1,a*(1+length))});lit.track("trimFrom").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:1,at:a=>Math.max(0,a*(1+length)-length)});hideAt(lit,ctx.t1)}}}var Value=class{track;constructor(initial){this.track=new Track(initial)}get value(){return this.track.sample(clock.now)}set(value){this.track.step(clock.now,value);return this}to(value,options={}){const track=this.track;return{label:"value",duration:options.duration??1,ease:options.ease,schedule(ctx){const from=track.sample(ctx.t0);track.add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:value,at:a=>from+(value-from)*a})}}}};var ASPECTS={"16:9":[1920,1080],"9:16":[1080,1920],"1:1":[1080,1080],"4:3":[1440,1080],"21:9":[2520,1080]};var Stage=class{root=new Node;camera=new Node;width;height;fps;look;chapters=[];clips=[];captions=[];updaters=[];time=0;ending=0;constructor(options){const[w,h]=ASPECTS[options.aspect??"16:9"];this.width=options.width??w;this.height=options.height??h;this.fps=options.fps??60;this.look=resolveLook(options.look);this.root.mounted=true;this.camera.mounted=true}get right(){return this.width/2}get left(){return-this.width/2}get top(){return-this.height/2}get bottom(){return this.height/2}add(first,...rest){clock.now=this.time;for(const node of[first,...rest]){if(!node.mounted){node.parent?.drop(node);node.parent=this.root;this.root.children.push(node);mountTree(node,this.time)}else if(!node.get("visible")){node.track("visible").step(this.time,true)}}return first}mountAt(node,time){if(node.mounted)return;node.parent?.drop(node);node.parent=this.root;this.root.children.push(node);mountTree(node,time)}remove(...nodes){for(const node of nodes)node.track("visible").step(this.time,false)}play(...items){const anims=items.filter(item=>"schedule"in item);const options=items.find(item=>!("schedule"in item))??{};if(anims.length===0)return this;const natural=Math.max(...anims.map(anim=>anim.duration));const duration=options.duration??natural;const t0=this.time;const t1=t0+duration;for(const anim of anims){clock.now=t0;const end=options.duration!==void 0?t1:t0+anim.duration;anim.schedule({t0,t1:end,ease:options.ease??anim.ease??smooth2,stage:this})}this.clips.push({t0,t1,labels:options.label?[options.label]:anims.map(anim=>anim.label)});this.time=t1;this.ending=Math.max(this.ending,t1);clock.now=t1;return this}wait(seconds=1){this.time+=seconds;this.ending=Math.max(this.ending,this.time);clock.now=this.time;return this}at(time,build){const saved=this.time;this.time=time;clock.now=time;build();this.ending=Math.max(this.ending,this.time);this.time=saved;clock.now=saved;return this}chapter(title){this.chapters.push({title,time:this.time});return this}caption(text2,duration=3){this.captions.push({t0:this.time,t1:this.time+duration,text:text2});this.ending=Math.max(this.ending,this.time+duration);return this}value(initial=0){return new Value(initial)}update(node,fn,window={}){this.updaters.push({node,fn,from:window.from??this.time,to:window.to??Infinity});return node}get duration(){return Math.max(this.ending,this.time)}};function film(a,b){const options=typeof a==="function"?{}:a;const build=typeof a==="function"?a:b;if(!build)throw new Error("film(options, build) needs a build function.");const definition={kind:"vizmatic.film",options,build,compile:overrides=>compileFilm(definition,overrides)};return definition}function isFilm(value){return!!value&&typeof value==="object"&&value.kind==="vizmatic.film"}var Suspend=class{constructor(promise){this.promise=promise}promise;isVizmaticSuspend=true};function isSuspend(error){return typeof error==="object"&&error!==null&&error.isVizmaticSuspend===true}var CompiledFilm=class{width;height;fps;duration;title;description;look;bloom;background;posterTime;bleed;chapters;clips;captions;stage;constructor(stage,options,overrides){this.stage=stage;this.width=stage.width;this.height=stage.height;this.fps=overrides.fps??stage.fps;this.duration=Math.max(stage.duration,1/this.fps);this.title=options.title??"";this.description=options.description??"";this.look=stage.look;this.bloom=overrides.bloom??options.bloom??stage.look.bloom;const background=overrides.background!==void 0?overrides.background:options.background!==void 0?options.background:stage.look.background;this.background=background===null?null:stage.look.colors[background]??background;this.posterTime=options.poster;this.bleed=options.bleed===true;this.chapters=stage.chapters;this.clips=stage.clips;this.captions=stage.captions}get frameCount(){return Math.max(1,Math.round(this.duration*this.fps))}frame(time){const t=Math.max(0,Math.min(this.duration,time));const stage=this.stage;const previous={mode:clock.mode,now:clock.now};setColorTokens(stage.look.colors);clock.mode="render";clock.now=t;clock.frame++;try{for(const updater of stage.updaters){if(t>=updater.from&&t<=updater.to)updater.fn(updater.node,t)}const camera=stage.camera;const ops=buildOps(stage.root,{x:camera.get("x"),y:camera.get("y"),zoom:camera.get("sx"),rotation:camera.get("rotation")},stage.width,stage.height);return{width:stage.width,height:stage.height,background:this.background,bloom:this.bloom,dark:stage.look.dark,ops}}finally{clock.mode=previous.mode;clock.now=previous.now}}svg(time,options={}){return frameToSvg(this.frame(time),options)}};async function compileFilm(definition,overrides={}){const options={...definition.options,...overrides.look?{look:overrides.look}:{},...overrides.fps?{fps:overrides.fps}:{}};for(let attempt=0;attempt<64;attempt++){const stage=new Stage(options);setColorTokens(stage.look.colors);const saved={mode:clock.mode,now:clock.now};clock.mode="compile";clock.now=0;try{await definition.build(stage);clock.mode=saved.mode;clock.now=saved.now;const compiled=new CompiledFilm(stage,options,overrides);await probe(compiled);return compiled}catch(error){clock.mode=saved.mode;clock.now=saved.now;clock.capture=null;if(error instanceof Suspend){await error.promise;continue}throw error}}throw new Error("The film kept requesting new assets while compiling.")}async function probe(film2){const samples=[0,.25,.5,.75,1];for(const fraction of samples){for(let attempt=0;attempt<16;attempt++){try{film2.frame(film2.duration*fraction);break}catch(error){if(!(error instanceof Suspend))throw error;await error.promise}}}}function curveFree(contours){return{contours:contours.filter(contour=>contour.length>=8)}}var assetBase=null;function setAssetBase(url){assetBase=url}var isNode=typeof process!=="undefined"&&!!process.versions?.node&&typeof globalThis.document==="undefined";function moduleUrl(){const url=import.meta.url;if(url)return url;return`file://${typeof __filename!=="undefined"?__filename:""}`}async function nodeRead(relative3){const fsName="node:fs/promises",pathName="node:path",urlName="node:url";const[fs,path,url]=await Promise.all([import(fsName),import(pathName),import(urlName)]);let directory=path.dirname(url.fileURLToPath(moduleUrl()));for(let depth=0;depth<6;depth++){const candidate=path.join(directory,"assets",relative3);try{const bytes=await fs.readFile(candidate);return bytes.buffer.slice(bytes.byteOffset,bytes.byteOffset+bytes.byteLength)}catch(error){if(error.code!=="ENOENT")throw error}directory=path.dirname(directory)}throw new Error(`Bundled asset not found: assets/${relative3}`)}async function loadBinaryAsset(relative3){if(isNode)return nodeRead(relative3);const base=assetBase??new URL("./assets/",moduleUrl()).href;const response=await fetch(new URL(relative3,base));const type=response.headers.get("content-type")??"";if(!response.ok||type.includes("text/html")){throw new Error(`Could not load ${relative3} from ${response.url} (HTTP ${response.status}, ${type||"no content type"}). Call setAssetBase() with the folder that holds fonts/.`)}return response.arrayBuffer()}var Reader=class{constructor(bytes,offset=0){this.bytes=bytes;this.offset=offset;this.view=new DataView(bytes)}bytes;offset;view;seek(offset){this.offset=offset;return this}get position(){return this.offset}u8(){return this.view.getUint8(this.offset++)}i8(){return this.view.getInt8(this.offset++)}u16(){const v=this.view.getUint16(this.offset);this.offset+=2;return v}i16(){const v=this.view.getInt16(this.offset);this.offset+=2;return v}u32(){const v=this.view.getUint32(this.offset);this.offset+=4;return v}tag(){let out="";for(let i=0;i<4;i++)out+=String.fromCharCode(this.u8());return out}};function parseFont(bytes){const r=new Reader(bytes);const version=r.u32();if(version!==65536&&version!==1953658213){throw new Error("Stage text needs a TrueType (.ttf) font with glyf outlines.")}const tableCount=r.u16();r.seek(12);const tables=new Map;for(let i=0;i<tableCount;i++){const tag=r.tag();r.u32();tables.set(tag,{offset:r.u32(),length:r.u32()})}const need=tag=>{const table=tables.get(tag);if(!table)throw new Error(`Font is missing its ${tag} table.`);return table};const head=need("head");r.seek(head.offset+18);const unitsPerEm=r.u16();r.seek(head.offset+50);const longLoca=r.i16()===1;const hhea=need("hhea");r.seek(hhea.offset+4);const ascent=r.i16();const descent=r.i16();const lineGap=r.i16();r.seek(hhea.offset+34);const hMetrics=r.u16();r.seek(need("maxp").offset+4);const glyphCount=r.u16();const hmtx=need("hmtx");const loca=need("loca");const glyf=need("glyf");const cmap=parseCmap(r,need("cmap").offset);const kerning=tables.has("GPOS")?parseKerning(r,tables.get("GPOS").offset):()=>0;const advance=glyph=>{const index=Math.min(glyph,hMetrics-1);r.seek(hmtx.offset+index*4);return r.u16()};const outlines=new Map;const contours=(glyph,depth)=>{if(glyph>=glyphCount||depth>6)return[];r.seek(loca.offset+(longLoca?glyph*4:glyph*2));const start=longLoca?r.u32():r.u16()*2;const end=longLoca?r.u32():r.u16()*2;if(start===end)return[];r.seek(glyf.offset+start);const count=r.i16();r.seek(r.position+8);if(count<0)return composite(glyph,depth);const ends=[];for(let i=0;i<count;i++)ends.push(r.u16());const instructionLength=r.u16();r.seek(r.position+instructionLength);const total=(ends[ends.length-1]??-1)+1;const flags=[];while(flags.length<total){const flag=r.u8();flags.push(flag);if(flag&8){let repeat=r.u8();while(repeat-- >0)flags.push(flag)}}const xs=new Array(total);let x=0;for(let i=0;i<total;i++){const flag=flags[i];if(flag&2){const dx=r.u8();x+=flag&16?dx:-dx}else if(!(flag&16)){x+=r.i16()}xs[i]=x}const ys=new Array(total);let y=0;for(let i=0;i<total;i++){const flag=flags[i];if(flag&4){const dy=r.u8();y+=flag&32?dy:-dy}else if(!(flag&32)){y+=r.i16()}ys[i]=y}const out=[];let first=0;for(const last of ends){out.push(contourToCubics(xs,ys,flags,first,last));first=last+1}return out};function composite(_glyph,depth){const parts=[];let more=true;while(more){const flags=r.u16();const glyph=r.u16();const words=(flags&1)!==0;const xy=(flags&2)!==0;let dx=0,dy=0;if(words){dx=r.i16();dy=r.i16()}else{dx=r.i8();dy=r.i8()}if(!xy){dx=0;dy=0}let a=1,b=0,c=0,d=1;const f2=()=>r.i16()/16384;if(flags&8){a=d=f2()}else if(flags&64){a=f2();d=f2()}else if(flags&128){a=f2();b=f2();c=f2();d=f2()}parts.push({glyph,m:[a,b,c,d,dx,dy]});more=(flags&32)!==0}const out=[];for(const part of parts){for(const contour of contours(part.glyph,depth+1)){const moved=new Array(contour.length);const[a,b,c,d,e,f]=part.m;for(let i=0;i<contour.length;i+=2){moved[i]=a*contour[i]+c*contour[i+1]+e;moved[i+1]=b*contour[i]+d*contour[i+1]+f}out.push(moved)}}return out}return{unitsPerEm,ascent,descent,lineGap,glyphFor(code){return cmap(code)},advance,kern(left,right){return kerning(left,right)},outline(glyph){if(outlines.has(glyph))return outlines.get(glyph);const raw=contours(glyph,0);const result=raw.length?curveFree(raw):null;outlines.set(glyph,result);return result}}}function contourToCubics(xs,ys,flags,first,last){const count=last-first+1;if(count<2)return[];const at=i=>first+(i%count+count)%count;const on=i=>(flags[at(i)]&1)!==0;let startIndex=0;while(startIndex<count&&!on(startIndex))startIndex++;let sx,sy;if(startIndex===count){sx=(xs[at(0)]+xs[at(count-1)])/2;sy=(ys[at(0)]+ys[at(count-1)])/2;startIndex=0}else{sx=xs[at(startIndex)];sy=ys[at(startIndex)];startIndex+=1}const out=[sx,sy];let cx=sx,cy=sy;let controlX=0,controlY=0,hasControl=false;const quad=(qx,qy,ex,ey)=>{out.push(cx+(qx-cx)*2/3,cy+(qy-cy)*2/3,ex+(qx-ex)*2/3,ey+(qy-ey)*2/3,ex,ey);cx=ex;cy=ey};const line2=(ex,ey)=>{out.push(cx+(ex-cx)/3,cy+(ey-cy)/3,cx+(ex-cx)*2/3,cy+(ey-cy)*2/3,ex,ey);cx=ex;cy=ey};for(let k=0;k<count;k++){const i=startIndex+k;const x=xs[at(i)],y=ys[at(i)];if(on(i)){if(hasControl){quad(controlX,controlY,x,y);hasControl=false}else if(x!==cx||y!==cy){line2(x,y)}}else{if(hasControl)quad(controlX,controlY,(controlX+x)/2,(controlY+y)/2);controlX=x;controlY=y;hasControl=true}}if(hasControl)quad(controlX,controlY,sx,sy);else if(cx!==sx||cy!==sy)line2(sx,sy);return out}function parseCmap(r,offset){r.seek(offset+2);const count=r.u16();let best=-1,bestScore=-1;for(let i=0;i<count;i++){const platform=r.u16();const encoding=r.u16();const sub=r.u32();const score=platform===3&&encoding===10?4:platform===0&&encoding>=4?3:platform===3&&encoding===1?2:platform===0?1:0;if(score>bestScore){bestScore=score;best=offset+sub}}if(best<0)return()=>0;r.seek(best);const format=r.u16();if(format===12){r.seek(best+12);const groups=r.u32();const table=[];for(let i=0;i<groups;i++)table.push([r.u32(),r.u32(),r.u32()]);return code=>{let lo=0,hi=table.length-1;while(lo<=hi){const mid=lo+hi>>1;const[start,end,glyph]=table[mid];if(code<start)hi=mid-1;else if(code>end)lo=mid+1;else return glyph+code-start}return 0}}if(format===4){r.seek(best+6);const segX2=r.u16();const segs=segX2/2;const endsAt=best+14;const startsAt=endsAt+segX2+2;const deltasAt=startsAt+segX2;const rangesAt=deltasAt+segX2;const map=new Map;for(let i=0;i<segs;i++){const end=r.seek(endsAt+i*2).u16();const start=r.seek(startsAt+i*2).u16();const delta=r.seek(deltasAt+i*2).i16();const range=r.seek(rangesAt+i*2).u16();for(let c=start;c<=end&&c!==65535;c++){let glyph;if(range===0)glyph=c+delta&65535;else{const raw=r.seek(rangesAt+i*2+range+(c-start)*2).u16();glyph=raw===0?0:raw+delta&65535}if(glyph)map.set(c,glyph)}}return code=>map.get(code)??0}return()=>0}function parseKerning(r,gpos){const lookups=[];try{r.seek(gpos+6);const featureList=gpos+r.u16();const lookupList=gpos+r.u16();r.seek(featureList);const featureCount=r.u16();const indices=new Set;for(let i=0;i<featureCount;i++){r.seek(featureList+2+i*6);const tag=r.tag();const offset=r.u16();if(tag!=="kern")continue;r.seek(featureList+offset+2);const count=r.u16();for(let k=0;k<count;k++)indices.add(r.u16())}for(const index of[...indices].sort((a,b)=>a-b)){r.seek(lookupList+2+index*2);const lookup=lookupList+r.u16();r.seek(lookup);const lookupType=r.u16();r.u16();const subCount=r.u16();const subs=[];for(let i=0;i<subCount;i++)subs.push(lookup+r.u16());const tables=[];for(const first of subs){let sub=first;let type=lookupType;if(type===9){r.seek(sub+2);type=r.u16();sub+=r.u32()}if(type===2)tables.push(readPairs(r,sub))}lookups.push(tables)}}catch{}const cache2=new Map;return(left,right)=>{const key=left*65536+right;const cached=cache2.get(key);if(cached!==void 0)return cached;let total=0;for(const tables of lookups){for(const table of tables){const value=table(left,right);if(value!==void 0){total+=value;break}}}cache2.set(key,total);return total}}function readCoverage(r,offset){r.seek(offset);const format=r.u16();const out=new Set;if(format===1){const count=r.u16();for(let i=0;i<count;i++)out.add(r.u16())}else if(format===2){const count=r.u16();for(let i=0;i<count;i++){const start=r.u16(),end=r.u16();r.u16();for(let glyph=start;glyph<=end;glyph++)out.add(glyph)}}return out}function readClasses(r,offset){r.seek(offset);const format=r.u16();const classes=new Map;if(format===1){const start=r.u16();const count=r.u16();for(let i=0;i<count;i++)classes.set(start+i,r.u16())}else if(format===2){const count=r.u16();for(let i=0;i<count;i++){const start=r.u16(),end=r.u16(),value=r.u16();for(let glyph=start;glyph<=end;glyph++)classes.set(glyph,value)}}return glyph=>classes.get(glyph)??0}function valueSize(format){let count=0;for(let bit=0;bit<8;bit++)if(format&1<<bit)count++;return count*2}function readAdvance(r,format){let advance=0;if(format&1)r.i16();if(format&2)r.i16();if(format&4)advance=r.i16();if(format&8)r.i16();for(let bit=4;bit<8;bit++)if(format&1<<bit)r.u16();return advance}function readPairs(r,sub){r.seek(sub);const format=r.u16();const coverageOffset=r.u16();const value1=r.u16();const value2=r.u16();const size1=valueSize(value1);const size2=valueSize(value2);if(format===1){const setCount=r.u16();const offsets=[];for(let i=0;i<setCount;i++)offsets.push(r.u16());r.seek(sub+coverageOffset);const coverageFormat=r.u16();const glyphs=[];if(coverageFormat===1){const count=r.u16();for(let i=0;i<count;i++)glyphs.push(r.u16())}else if(coverageFormat===2){const count=r.u16();for(let i=0;i<count;i++){const start=r.u16(),end=r.u16();r.u16();for(let glyph=start;glyph<=end;glyph++)glyphs.push(glyph)}}const sets=new Map;for(let i=0;i<setCount;i++){r.seek(sub+offsets[i]);const count=r.u16();const pairs=new Map;for(let k=0;k<count;k++){const second=r.u16();const advance=readAdvance(r,value1);r.seek(r.position+size2);pairs.set(second,advance)}if(glyphs[i]!==void 0)sets.set(glyphs[i],pairs)}return(left,right)=>sets.get(left)?.get(right)}if(format===2){const class1Offset=r.u16();const class2Offset=r.u16();const class1Count=r.u16();const class2Count=r.u16();const matrix2=r.position;const coverage=readCoverage(r,sub+coverageOffset);const class1=readClasses(r,sub+class1Offset);const class2=readClasses(r,sub+class2Offset);return(left,right)=>{if(!coverage.has(left))return void 0;const c1=class1(left),c2=class2(right);if(c1>=class1Count||c2>=class2Count)return void 0;r.seek(matrix2+c1*class2Count*(size1+size2)+c2*(size1+size2));return readAdvance(r,value1)}}return()=>void 0}var FILES={sans:{"400":"Inter-Regular.ttf","600":"Inter-SemiBold.ttf","700":"Inter-Bold.ttf"},serif:{"400":"InstrumentSerif-Regular.ttf","italic":"InstrumentSerif-Italic.ttf"},"text-serif":{"400":"SourceSerif4-24pt-Regular.ttf","italic":"SourceSerif4-24pt-Italic.ttf"},mono:{"400":"JetBrainsMono-Regular.ttf"},noto:{"400":"NotoSans-Regular.ttf"},math:{"400":"NotoSansMath-Regular.ttf"}};var FALLBACKS={sans:["noto","math"],serif:["text-serif","noto","math"],"text-serif":["noto","math"],mono:["noto","math"],noto:["math"]};var fonts=new Map;var pending=new Map;function fontFor(family,weight=400,italic=false){const files=FILES[family];const file=(italic?files["italic"]:void 0)??files[String(weight)]??files["400"];const loaded=fonts.get(file);if(loaded)return loaded;let waiting=pending.get(file);if(!waiting){waiting=loadBinaryAsset(`fonts/${file}`).then(bytes=>{fonts.set(file,parseFont(bytes));pending.delete(file)});pending.set(file,waiting)}throw new Suspend(waiting)}function fallbackGlyph(family,code,weight=400,italic=false){for(const next of FALLBACKS[family]){const font=fontFor(next,weight,italic);const glyph=font.glyphFor(code);if(glyph!==0)return{font,glyph}}return null}var glyphPaths=new WeakMap;function glyphPath(font,glyph,size){let bySize=glyphPaths.get(font);if(!bySize)glyphPaths.set(font,bySize=new Map);let byGlyph=bySize.get(size);if(!byGlyph)bySize.set(size,byGlyph=new Map);const cached=byGlyph.get(glyph);if(cached)return cached;const outline=font.outline(glyph);const scale=size/font.unitsPerEm;const path=outline?outline.contours.map(contour=>{const out=new Float64Array(contour.length);for(let i=0;i<contour.length;i+=2){out[i]=contour[i]*scale;out[i+1]=-contour[i+1]*scale}return ring(out,true)}):[];byGlyph.set(glyph,path);return path}var TextNode=class extends Node{chars=[];source="";find(fragment){const out=[];const keys=this.chars.map(glyph=>glyph.data["key"]).join("");const needle=fragment.replace(/\s/g,"");for(let at=keys.indexOf(needle);at>=0;at=keys.indexOf(needle,at+1)){out.push(...this.chars.slice(at,at+needle.length))}return out}};function centered(path){const b=pathBounds(path);if(!b)return{path,x:0,y:0};const x=b.x+b.width/2,y=b.y+b.height/2;return{path:transformPath(path,[1,0,0,1,-x,-y]),x,y}}function text(content,options={}){const size=options.size??40;const family=options.font??"sans";const weight=options.weight??400;const italic=options.italic??false;const font=fontFor(family,weight,italic);const scale=size/font.unitsPerEm;const tracking=(options.tracking??0)*size;const leading=(options.leading??1.3)*size;const paint=toPaint(options.color??"ink");const source=options.uppercase?content.toUpperCase():content;const measureWord=word=>{const glyphs=[];let x=0,previous=0,previousFont=null;for(const char of word){const code=char.codePointAt(0);let owner=font,glyph=font.glyphFor(code);if(glyph===0){const found=fallbackGlyph(family,code,weight,italic);if(found){owner=found.font;glyph=found.glyph}}const ownerScale=size/owner.unitsPerEm;if(previous&&previousFont===owner)x+=owner.kern(previous,glyph)*ownerScale;glyphs.push({font:owner,glyph,x,char});x+=owner.advance(glyph)*ownerScale+tracking;previous=glyph;previousFont=owner}return{glyphs,width:x}};const lines=[];const space=font.advance(font.glyphFor(32))*scale+tracking;for(const paragraph of source.split("\n")){let line2=[];let width=0;for(const word of paragraph.split(" ")){const measured=measureWord(word);const gap=line2.length>0?space:0;if(options.maxWidth!==void 0&&line2.length>0&&width+gap+measured.width>options.maxWidth){lines.push({glyphs:line2,width});line2=[];width=0}const offset=width+(line2.length>0?space:0);for(const glyph of measured.glyphs)line2.push({...glyph,x:glyph.x+offset});width=offset+measured.width}lines.push({glyphs:line2,width})}const blockWidth=Math.max(0,...lines.map(line2=>line2.width));const align=options.align??"left";const node=new TextNode;node.source=content;lines.forEach((line2,row)=>{const start=align==="left"?0:align==="center"?(blockWidth-line2.width)/2:blockWidth-line2.width;for(const placed of line2.glyphs){const path=glyphPath(placed.font,placed.glyph,size);if(path.length===0)continue;const shape2=centered(path);const leaf=new Node(shape2.path).at(start+placed.x+shape2.x,row*leading+shape2.y);leaf.base.fill=paint;leaf.base.trimEach=true;leaf.data["key"]=placed.char;if(placed.glyph===0)leaf.data["missingGlyph"]=true;node.chars.push(leaf);node.children.push(leaf);leaf.parent=node}});const ascent=font.ascent*scale;const height=(lines.length-1)*leading;node.base.px=blockWidth/2;node.base.py=height/2-ascent*.36;node.data["size"]=size;return node}function decode(value){return value.replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&#(\d+);/g,(_,code)=>String.fromCodePoint(Number(code))).replace(/&#x([\da-fA-F]+);/g,(_,code)=>String.fromCodePoint(parseInt(code,16))).replace(/&/g,"&")}function parseXml(source){const root={name:"#root",attrs:{},children:[],text:""};const stack=[root];const token=/<!--[\s\S]*?-->|<!\[CDATA\[([\s\S]*?)\]\]>|<\?[\s\S]*?\?>|<!DOCTYPE[^>]*>|<\/([\w:.-]+)\s*>|<([\w:.-]+)((?:\s+[\w:.-]+\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*(\/?)>|([^<]+)/g;for(let match=token.exec(source);match;match=token.exec(source)){const top=stack[stack.length-1];const[,cdata,closing,opening,attributes,selfClosing,content]=match;if(cdata!==void 0){top.text+=cdata}else if(closing){if(stack.length>1)stack.pop()}else if(opening){const element={name:opening.replace(/^.*:/,""),attrs:{},children:[],text:""};for(const attr of(attributes??"").matchAll(/([\w:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)){element.attrs[attr[1]]=decode(attr[2]??attr[3]??"")}top.children.push(element);if(!selfClosing)stack.push(element)}else if(content){top.text+=decode(content)}}return root}function parseTransform(value){if(!value)return IDENTITY;let m=IDENTITY;for(const match of value.matchAll(/(matrix|translate|scale|rotate|skewX|skewY)\s*\(([^)]*)\)/g)){const a=match[2].trim().split(/[\s,]+/).filter(Boolean).map(Number);const name=match[1];if(name==="matrix"&&a.length===6)m=mul(m,a);else if(name==="translate")m=mul(m,[1,0,0,1,a[0]??0,a[1]??0]);else if(name==="scale")m=mul(m,[a[0]??1,0,0,a[1]??a[0]??1,0,0]);else if(name==="rotate"){const r=(a[0]??0)*Math.PI/180;const c=Math.cos(r),s=Math.sin(r);const cx=a[1]??0,cy=a[2]??0;m=mul(m,[1,0,0,1,cx,cy]);m=mul(m,[c,s,-s,c,0,0]);m=mul(m,[1,0,0,1,-cx,-cy])}else if(name==="skewX")m=mul(m,[1,0,Math.tan((a[0]??0)*Math.PI/180),1,0,0]);else if(name==="skewY")m=mul(m,[1,Math.tan((a[0]??0)*Math.PI/180),0,1,0,0])}return m}var NOT_DRAWN=new Set(["defs","clipPath","mask","pattern","filter","symbol","marker","linearGradient","radialGradient","title","desc","metadata","style","script"]);var SvgNode=class extends Node{byId=new Map;pictureWidth=0;pictureHeight=0;find(id){const found=this.byId.get(id);if(!found)throw new Error(`The SVG has no element with id ${JSON.stringify(id)}.`);return found}};function parseCssRules(root){const rules=new Map;const visit=element=>{if(element.name==="style"){for(const rule of element.text.matchAll(/([^{}]+)\{([^{}]*)\}/g)){const body=parseStyle(rule[2]);for(const selector of rule[1].split(",")){const key=selector.trim();rules.set(key,{...rules.get(key),...body})}}}element.children.forEach(visit)};visit(root);return rules}function parseStyle(value){const out={};if(!value)return out;for(const part of value.split(";")){const index=part.indexOf(":");if(index>0)out[part.slice(0,index).trim()]=part.slice(index+1).trim()}return out}function safeColor(value){if(!value||value==="none"||value==="transparent")return null;try{return parseColor(value)}catch{return null}}function splitIntoGlyphs(path){const items=path.map(r=>{const b=pathBounds([r]);return{ring:r,b,area:b.width*b.height,owner:-1}});const order=items.map((_,i)=>i).sort((a,b)=>items[b].area-items[a].area);for(let k=0;k<order.length;k++){const inner=items[order[k]];for(let j=k-1;j>=0;j--){const outer=items[order[j]];if(outer.owner!==-1)continue;const inside=inner.b.x>=outer.b.x-.01&&inner.b.y>=outer.b.y-.01&&inner.b.x+inner.b.width<=outer.b.x+outer.b.width+.01&&inner.b.y+inner.b.height<=outer.b.y+outer.b.height+.01;if(inside){inner.owner=order[j];break}}}const glyphs=[];const ownerToGlyph=new Map;items.forEach((item,i)=>{if(item.owner!==-1)return;const glyph={x:item.b.x,rings:[item.ring]};ownerToGlyph.set(i,glyph);glyphs.push(glyph)});items.forEach(item=>{if(item.owner!==-1)ownerToGlyph.get(item.owner)?.rings.push(item.ring)});return glyphs.sort((a,b)=>a.x-b.x).map(glyph=>glyph.rings)}function fromSvg(source,options={}){const root=parseXml(source);const svg=root.children.find(child=>child.name==="svg");if(!svg)throw new Error("fromSvg needs markup with an <svg> element.");const rules=parseCssRules(svg);const defs=new Map;const index=element=>{if(element.attrs["id"])defs.set(element.attrs["id"],element);element.children.forEach(index)};index(svg);const box=(svg.attrs["viewBox"]??"").trim().split(/[\s,]+/).map(Number);const declaredW=parseFloat(svg.attrs["width"]??""),declaredH=parseFloat(svg.attrs["height"]??"");const viewW=box.length===4&&box[2]?box[2]:declaredW||300;const viewH=box.length===4&&box[3]?box[3]:declaredH||150;const viewX=box.length===4?box[0]:0,viewY=box.length===4?box[1]:0;const naturalW=Number.isFinite(declaredW)&&declaredW>0?declaredW:viewW;const naturalH=Number.isFinite(declaredH)&&declaredH>0?declaredH:viewH;let scale=1;if(options.width!==void 0||options.height!==void 0){const sx=options.width!==void 0?options.width/viewW:Infinity;const sy=options.height!==void 0?options.height/viewH:Infinity;scale=Math.min(sx,sy)}else{scale=Math.min(naturalW/viewW,naturalH/viewH)}const center2=options.center??true;const offsetX=center2?-(viewX+viewW/2)*scale:-viewX*scale;const offsetY=center2?-(viewY+viewH/2)*scale:-viewY*scale;const base=[scale,0,0,scale,offsetX,offsetY];const out=new SvgNode;out.pictureWidth=viewW*scale;out.pictureHeight=viewH*scale;const splitting=options.splitGlyphs??true;const keepBackground=options.background??false;let firstShape=true;const gradientOf=(id,m,path)=>{const element=defs.get(id);if(!element)return null;if(element.name==="pattern"){const inner=element.children.find(child=>child.name==="linearGradient");if(inner)return linear2(inner,m,path,true);const fill=element.children.find(child=>child.attrs["fill"]?.startsWith("url(#"));const nested=fill?.attrs["fill"]?.match(/url\(#([^)]+)\)/)?.[1];return nested?gradientOf(nested,m,path):null}if(element.name==="linearGradient")return linear2(element,m,path,element.attrs["gradientUnits"]!=="userSpaceOnUse");if(element.name==="radialGradient"){const stops=stopsOf(element);return stops.length?stops[stops.length-1][1]:null}return null};const stopsOf=element=>{const inherited=element.attrs["href"]??element.attrs["xlink:href"];const source2=element.children.some(child=>child.name==="stop")||!inherited?element:defs.get(inherited.replace(/^#/,""))??element;return source2.children.filter(child=>child.name==="stop").map(stop=>{const style2=parseStyle(stop.attrs["style"]);const offsetRaw=stop.attrs["offset"]??"0";const offset=offsetRaw.endsWith("%")?parseFloat(offsetRaw)/100:parseFloat(offsetRaw);const color=safeColor(style2["stop-color"]??stop.attrs["stop-color"]??"#000000")??[0,0,0,1];const alpha2=parseFloat(style2["stop-opacity"]??stop.attrs["stop-opacity"]??"1");return[offset,[color[0],color[1],color[2],color[3]*alpha2]]})};const linear2=(element,m,path,objectBox)=>{const stops=stopsOf(element);if(stops.length===0)return null;const coordinate=(value,fallback)=>{if(value===void 0)return fallback;return value.endsWith("%")?parseFloat(value)/100:parseFloat(value)};const x1=coordinate(element.attrs["x1"],0),y1=coordinate(element.attrs["y1"],0);const x2=coordinate(element.attrs["x2"],1),y2=coordinate(element.attrs["y2"],0);let from,to2;if(objectBox){const b=pathBounds(path)??{x:0,y:0,width:1,height:1};from=[b.x+x1*b.width,b.y+y1*b.height];to2=[b.x+x2*b.width,b.y+y2*b.height]}else{from=apply(m,x1,y1);to2=apply(m,x2,y2)}return{type:"linear",from,to:to2,stops}};const shapePath=element=>{const a=element.attrs;const num=(key,fallback=0)=>{const value=parseFloat(a[key]??"");return Number.isFinite(value)?value:fallback};switch(element.name){case"path":return a["d"]?parseSvgPath(a["d"]):null;case"rect":{const w=num("width"),h=num("height");if(w<=0||h<=0)return null;return rectPath(num("x"),num("y"),w,h,num("rx",num("ry")))}case"circle":return num("r")>0?arcPath(num("cx"),num("cy"),num("r"),num("r"),0,Math.PI*2):null;case"ellipse":return num("rx")>0&&num("ry")>0?arcPath(num("cx"),num("cy"),num("rx"),num("ry"),0,Math.PI*2):null;case"line":return polyPath([[num("x1"),num("y1")],[num("x2"),num("y2")]]);case"polyline":case"polygon":{const values=(a["points"]??"").trim().split(/[\s,]+/).filter(Boolean).map(Number);const points=[];for(let i=0;i+1<values.length;i+=2)points.push([values[i],values[i+1]]);return points.length>=2?polyPath(points,element.name==="polygon"):null}default:return null}};const styleOf=(element,inherited)=>{const a=element.attrs;const cls=(a["class"]??"").split(/\s+/).filter(Boolean);const merged={...rules.get(element.name)};for(const name of cls)Object.assign(merged,rules.get(`.${name}`));if(a["id"])Object.assign(merged,rules.get(`#${a["id"]}`));const pick=key=>parseStyle(a["style"])[key]??a[key]??merged[key];const style2={...inherited};const color=pick("color");if(color)style2.color=color;const fill=pick("fill");if(fill)style2.fill=fill==="currentColor"?style2.color:fill;const stroke=pick("stroke");if(stroke)style2.stroke=stroke==="currentColor"?style2.color:stroke;const width=pick("stroke-width");if(width!==void 0)style2.strokeWidth=parseFloat(width)||0;const fo=pick("fill-opacity");if(fo!==void 0)style2.fillOpacity=parseFloat(fo);const so=pick("stroke-opacity");if(so!==void 0)style2.strokeOpacity=parseFloat(so);const cap=pick("stroke-linecap");if(cap==="round"||cap==="butt"||cap==="square")style2.cap=cap;const join4=pick("stroke-linejoin");if(join4==="round"||join4==="miter"||join4==="bevel")style2.join=join4;const dash=pick("stroke-dasharray");if(dash!==void 0)style2.dash=dash==="none"?null:dash.trim().split(/[\s,]+/).map(Number);const dashOffset=pick("stroke-dashoffset");if(dashOffset!==void 0)style2.dashOffset=parseFloat(dashOffset)||0;const size=pick("font-size");if(size!==void 0)style2.fontSize=parseFloat(size)||style2.fontSize;const anchor=pick("text-anchor");if(anchor)style2.anchor=anchor;return{style:style2,opacity:parseFloat(pick("opacity")??"1")}};const leafFrom=(path,m,element,style2)=>{const world=transformPath(path,m);const scaleOf=matScale(m);const url=value=>value?.match(/^url\(#([^)]+)\)/)?.[1];const fillId=url(style2.fill),strokeId=url(style2.stroke);const fill=fillId?gradientOf(fillId,m,world):safeColor(style2.fill);const stroke=strokeId?gradientOf(strokeId,m,world):safeColor(style2.stroke);const visibleFill=fill&&style2.fillOpacity>0&&!(Array.isArray(fill)&&fill[3]===0);const visibleStroke=stroke&&style2.strokeOpacity>0&&style2.strokeWidth>0&&!(Array.isArray(stroke)&&stroke[3]===0);if(!visibleFill&&!visibleStroke)return[];const clippedStroke=element.attrs["clip-path"]?.5:1;const pieces=splitting&&visibleFill&&!visibleStroke&&world.length>1?splitIntoGlyphs(world):[world];return pieces.map(piece=>{const b=pathBounds(piece)??{x:0,y:0,width:0,height:0};const cx=b.x+b.width/2,cy=b.y+b.height/2;const leaf=new Node(transformPath(piece,[1,0,0,1,-cx,-cy])).at(cx,cy);if(visibleFill){leaf.base.fill=shiftPaint(fill,-cx,-cy);leaf.base.fillOpacity=style2.fillOpacity}if(visibleStroke){leaf.base.stroke=shiftPaint(stroke,-cx,-cy);leaf.base.strokeWidth=style2.strokeWidth*scaleOf*clippedStroke;leaf.base.strokeOpacity=style2.strokeOpacity;leaf.base.cap=style2.cap;leaf.base.join=style2.join;if(style2.dash)leaf.base.dash=style2.dash.map(value=>value*scaleOf);leaf.base.dashOffset=style2.dashOffset*scaleOf}leaf.base.trimEach=true;return leaf})};const walk2=(element,parent,inherited,parentMatrix)=>{if(NOT_DRAWN.has(element.name))return;if(element.attrs["filter"])return;const{style:style2,opacity}=styleOf(element,inherited);const m=mul(parentMatrix,parseTransform(element.attrs["transform"]));const register=node=>{if(element.attrs["id"])out.byId.set(element.attrs["id"],node)};if(element.name==="g"||element.name==="svg"||element.name==="a"){const group3=new Node;if(opacity<1)group3.base.opacity=opacity;register(group3);parent.add(group3);for(const child of element.children)walk2(child,group3,style2,m);return}if(element.name==="use"){const href=(element.attrs["href"]??element.attrs["xlink:href"]??"").replace(/^#/,"");const referenced=defs.get(href);if(!referenced)return;const placed=mul(m,[1,0,0,1,parseFloat(element.attrs["x"]??"0")||0,parseFloat(element.attrs["y"]??"0")||0]);const group3=new Node;if(opacity<1)group3.base.opacity=opacity;parent.add(group3);if(referenced.name==="symbol")for(const child of referenced.children)walk2(child,group3,style2,placed);else walk2(referenced,group3,style2,placed);return}if(element.name==="image"){const href=element.attrs["href"]??element.attrs["xlink:href"];if(!href)return;const width=parseFloat(element.attrs["width"]??"0"),height=parseFloat(element.attrs["height"]??"0");const[x,y]=apply(m,parseFloat(element.attrs["x"]??"0")||0,parseFloat(element.attrs["y"]??"0")||0);const unit=matScale(m);const image={src:href,width,height};const node=new Node().at(x,y);node.base.image=image;node.base.sx=unit;node.base.sy=unit;if(opacity<1)node.base.opacity=opacity;register(node);parent.add(node);return}if(element.name==="text"){const body=(element.text+element.children.map(child=>child.text).join("")).trim();if(!body)return;const color=safeColor(style2.fill)??[0,0,0,1];const size=style2.fontSize*matScale(m);const label=text(body,{size,color});const[x,y]=apply(m,parseFloat(element.attrs["x"]??"0")||0,parseFloat(element.attrs["y"]??"0")||0);const half=label.get("px");label.at(style2.anchor==="middle"?x:style2.anchor==="end"?x-half:x+half,y-size*.34);if(opacity<1)label.base.opacity=opacity;register(label);parent.add(label);return}const path=shapePath(element);if(!path||path.length===0)return;const isBackground=firstShape&&element.name==="rect"&&!keepBackground&&parseFloat(element.attrs["width"]??"0")>=viewW-.5&&parseFloat(element.attrs["height"]??"0")>=viewH-.5;firstShape=false;if(isBackground)return;const leaves=leafFrom(path,m,element,style2);if(leaves.length===0)return;if(leaves.length===1){if(opacity<1)leaves[0].base.opacity=opacity;register(leaves[0]);parent.add(leaves[0]);return}const group2=new Node;if(opacity<1)group2.base.opacity=opacity;group2.add(...leaves);register(group2);parent.add(group2)};const initial={fill:"#000000",stroke:null,strokeWidth:1,fillOpacity:1,strokeOpacity:1,cap:"butt",join:"miter",dash:null,dashOffset:0,color:"#000000",fontSize:16,anchor:"start"};const{style}=styleOf(svg,initial);for(const child of svg.children)walk2(child,out,style,base);return out}function shiftPaint(paint,dx,dy){if(Array.isArray(paint))return paint;const gradient=paint;if(gradient.type==="linear"){return{...gradient,from:[gradient.from[0]+dx,gradient.from[1]+dy],to:[gradient.to[0]+dx,gradient.to[1]+dy]}}if(gradient.type==="radial")return{...gradient,center:[gradient.center[0]+dx,gradient.center[1]+dy]};return gradient}var QUALITY={draft:{crf:26,vp9Crf:40,preset:"veryfast",motionBlur:1},standard:{crf:18,vp9Crf:31,preset:"medium",motionBlur:1},high:{crf:15,vp9Crf:24,preset:"slow",motionBlur:4},master:{crf:11,vp9Crf:15,preset:"slow",motionBlur:8}};var DEFAULT_GIF_WIDTH=960;var DEFAULT_GIF_FPS=25;var GIF_PALETTE_FRAMES=12;var GIF_PALETTE_PIXELS=1<<19;var MAX_GIF_DELAY=655350;async function resolveFilm(film2,overrides){return isFilm(film2)?film2.compile(overrides):film2}function frameAt(film2,time){try{return film2.frame(time)}catch(error){if(!isSuspend(error))throw error;return error.promise.then(()=>frameAt(film2,time))}}function backgroundBytes(color){if(!color)return[0,0,0];const rgba=parseColor(color);return[rgba[0],rgba[1],rgba[2]]}function outputSize(film2,requested){const width=requested??film2.width;if(!Number.isInteger(width)||width<2)throw new Error(`Output width must be an integer of at least 2, but received ${width}.`);return{width,height:Math.max(1,Math.round(width*film2.height/film2.width))}}function evenSize(film2,requested){const{width,height}=outputSize(film2,requested);return{width:width+width%2,height:Math.max(2,height+height%2)}}function timeRange(film2,options){const from=Math.max(0,options.from??0);const to2=Math.min(film2.duration,options.to??film2.duration);if(!Number.isFinite(from)||!Number.isFinite(to2)||to2<=from){throw new Error(`The render range ${from}:${to2} is empty. The film is ${film2.duration.toFixed(2)} seconds long.`)}return{from,to:to2}}function planRender(width,height,motionBlur,options={}){const frameBytes=width*height*4;const budget=options.memoryBudget??Math.min(2*1024**3,totalmem()*.25);const requested=Math.max(1,Math.floor(options.workers??defaultPoolSize()));const perWorker=frameBytes*(motionBlur>1?motionBlur+4:3);const workers=Math.max(1,Math.min(requested,Math.floor(budget*.75/perWorker)));const extra=Math.floor(budget*.25/frameBytes);return{workers,readAhead:Math.max(workers+1,Math.min(workers*2,workers+extra))}}function frameStream(film2,pool,timeOf,size,count,readAhead,subframes=1,shutterSpan=0){const inFlight=new Map;const submit=async index=>{const base=timeOf(index);const frames=[];for(let sub=0;sub<subframes;sub++){frames.push(await frameAt(film2,base+sub/subframes*shutterSpan))}return pool.run(framesToJob(frames,size.width,backgroundBytes,size.height))};return async index=>{for(let ahead=index;ahead<Math.min(count,index+readAhead);ahead++){if(inFlight.has(ahead))continue;const job=submit(ahead);job.catch(()=>{});inFlight.set(ahead,job)}const pixels=await inFlight.get(index);inFlight.delete(index);return pixels}}async function renderFilmVideo(film2,outputPath,options={}){const compiled=await resolveFilm(film2,options);const quality=QUALITY[options.quality??"standard"];if(!quality)throw new Error(`Unknown quality: ${options.quality}. Use draft, standard, high, or master.`);const size=evenSize(compiled,options.width);const motionBlur=Math.max(1,Math.floor(options.motionBlur??quality.motionBlur));const shutter=options.shutter??.5;const fps=compiled.fps;const codec=options.codec??"h264";const{from,to:to2}=timeRange(compiled,options);const plan=planRender(size.width,size.height,motionBlur,options);const pool=new RasterPool(plan.workers);try{const count=Math.max(1,Math.round((to2-from)*fps));const next=frameStream(compiled,pool,index=>from+index/fps,size,count,plan.readAhead,motionBlur,shutter/fps);const output=await renderRgbaVideo(info=>next(info.index),{width:size.width,height:size.height,fps,duration:(to2-from)*1e3,outputPath,codec,crf:codec==="vp9"?quality.vp9Crf:quality.crf,preset:quality.preset,tune:codec==="h264"?"animation":void 0,threads:options.threads??6,audioPath:options.audioPath,audioOffset:from>0?from:void 0,ffmpegPath:options.ffmpegPath,signal:options.signal,onProgress:options.onProgress});return{...output,title:compiled.title,workers:pool.size,motionBlur,codec}}finally{await pool.close()}}var gifApi=typeof gifenc2.GIFEncoder==="function"?gifenc2:gifenc2.default;function changedRegion(previous,current,width,height){let minX=width,minY=height,maxX=-1,maxY=-1;for(let y=0;y<height;y++){const row=y*width*4;for(let x=0;x<width;x++){const o=row+x*4;if(previous[o]!==current[o]||previous[o+1]!==current[o+1]||previous[o+2]!==current[o+2]){if(x<minX)minX=x;if(x>maxX)maxX=x;if(y<minY)minY=y;maxY=y}}}return maxX<0?null:{x:minX,y:minY,width:maxX-minX+1,height:maxY-minY+1}}function cropRegion(pixels,canvasWidth,region){const out=new Uint8Array(region.width*region.height*4);for(let y=0;y<region.height;y++){const start=((region.y+y)*canvasWidth+region.x)*4;out.set(pixels.subarray(start,start+region.width*4),y*region.width*4)}return out}async function renderFilmGif(film2,outputPath,options={}){const compiled=await resolveFilm(film2,{...options,fps:void 0});const size=outputSize(compiled,options.width??Math.min(DEFAULT_GIF_WIDTH,compiled.width));const fps=Math.min(options.fps??DEFAULT_GIF_FPS,50);const{from,to:to2}=timeRange(compiled,options);const count=Math.max(1,Math.round((to2-from)*fps));const delay2=1e3/fps;const plan=planRender(size.width,size.height,1,options);const pool=new RasterPool(plan.workers);try{const sampleCount=Math.min(count,GIF_PALETTE_FRAMES);const samples=await Promise.all(Array.from({length:sampleCount},async(_,i)=>{const index=Math.floor((i+.5)*count/sampleCount);return pool.run(framesToJob([await frameAt(compiled,from+index/fps)],size.width,backgroundBytes,size.height))}));const perFrame=Math.max(1,Math.floor(GIF_PALETTE_PIXELS/sampleCount));const combined=new Uint8Array(perFrame*sampleCount*4);samples.forEach((pixels,i)=>{const total=pixels.length/4;for(let k=0;k<perFrame;k++){const at=Math.floor((k+.5)*total/perFrame)*4;combined.set(pixels.subarray(at,at+4),(i*perFrame+k)*4)}});const palette=gifApi.quantize(combined,256,{format:"rgb565"});const gif=gifApi.GIFEncoder();const next=frameStream(compiled,pool,index=>from+index/fps,size,count,plan.readAhead);const repeat=options.loop===false?-1:0;let previous=null;let pending2=null;const flush=first=>{if(!pending2)return;let remaining=pending2.delay;let includePalette=first;do{const span=Math.min(MAX_GIF_DELAY,remaining);const start=gif.bytesView().length;gif.writeFrame(pending2.index,pending2.region.width,pending2.region.height,{...includePalette?{palette}:{},delay:Math.max(20,span),repeat,dispose:1});if(pending2.region.x!==0||pending2.region.y!==0){const bytes=gif.bytesView();const descriptor=start+8;if(bytes[descriptor]!==44)throw new Error("The GIF encoder wrote an unexpected frame layout.");bytes[descriptor+1]=pending2.region.x&255;bytes[descriptor+2]=pending2.region.x>>8&255;bytes[descriptor+3]=pending2.region.y&255;bytes[descriptor+4]=pending2.region.y>>8&255}includePalette=false;remaining-=span}while(remaining>0)};let wroteAny=false;for(let i=0;i<count;i++){options.signal?.throwIfAborted();const pixels=await next(i);const region=previous?changedRegion(previous,pixels,size.width,size.height):{x:0,y:0,width:size.width,height:size.height};if(!region){if(pending2)pending2.delay+=delay2}else{flush(!wroteAny);if(pending2)wroteAny=true;const cropped=region.width===size.width&®ion.height===size.height?pixels:cropRegion(pixels,size.width,region);pending2={index:gifApi.applyPalette(cropped,palette,"rgb565"),region,delay:delay2};previous=pixels}await options.onProgress?.({index:i,count,time:i*delay2,duration:count*delay2,progress:i/count,fps})}flush(!wroteAny);gif.finish();const path=resolve(outputPath);await mkdir2(dirname2(path),{recursive:true});await writeFile2(path,gif.bytesView());return{width:size.width,height:size.height,frameCount:count,duration:count*delay2,fps,bytes:(await stat(path)).size,outputPath:path,title:compiled.title}}finally{await pool.close()}}async function renderFilmFrame(film2,time,outputPath,options={}){const compiled=await resolveFilm(film2,options);const{width,height}=outputSize(compiled,options.width);const pool=new RasterPool(1);try{const frame=await frameAt(compiled,time);const pixels=await pool.run(framesToJob([frame],width,backgroundBytes,height));const path=resolve(outputPath);await mkdir2(dirname2(path),{recursive:true});await writeFile2(path,encodePng({width,height,data:pixels,depth:8,channels:4}));return{width,height,outputPath:path}}finally{await pool.close()}}async function renderFilmSvg(film2,time,outputPath,options={}){const compiled=await resolveFilm(film2,options);const path=resolve(outputPath);await mkdir2(dirname2(path),{recursive:true});const frame=await frameAt(compiled,time);const scale=(options.width??compiled.width)/compiled.width;await writeFile2(path,frameToSvg(frame,{scale}));return{width:Math.round(compiled.width*scale),height:Math.round(compiled.height*scale),outputPath:path}}async function posterTime(film2){if(film2.posterTime!==void 0)return Math.max(0,Math.min(film2.duration,film2.posterTime));const active=t=>film2.clips.some(clip=>clip.t0<t&&t<clip.t1);const nudge=.001;const candidates=new Set;for(const clip of film2.clips){const t=clip.t1+nudge;if(t<film2.duration&&!active(t))candidates.add(t)}if(candidates.size===0)for(let i=1;i<=10;i++)candidates.add(film2.duration*i/10-nudge);const scored=[];for(const time of[...candidates].sort((a,b)=>a-b)){const frame=await frameAt(film2,time);scored.push({time,ink:frame.ops.length})}const fullest=Math.max(...scored.map(entry=>entry.ink));const rich=scored.filter(entry=>entry.ink>=fullest*.75);return rich[rich.length-1]?.time??film2.duration}function captionsToVtt(film2){const stamp=seconds=>{const m=Math.floor(seconds/60),s=seconds-m*60;return`${String(m).padStart(2,"0")}:${s.toFixed(3).padStart(6,"0")}`};const cues=film2.captions.map(cue=>`${stamp(cue.t0)} --> ${stamp(cue.t1)}
|
|
130
130
|
${cue.text}`);return`WEBVTT
|
|
131
131
|
|
|
132
132
|
${cues.join("\n\n")}
|
|
133
|
-
`}var EDGE_TOLERANCE=1;var MIN_ALPHA=.08;var MIN_TEXT_ALPHA=.15;var MIN_OVERLAP=.12;var GLYPH_INSET=.12;var MIN_RESTING_MOMENTS=5;var AUTO_SAMPLES=12;var CUBIC_STEPS=6;var CROSSING_ERROR_WIDTH=2;var CROSSING_ERROR_CONTRAST=2;var MIN_STROKE_CONTRAST=1.6;var OPAQUE=.9;function solid3(paint){return isGradient(paint)?sampleStops(paint.stops,.5):paint}function luminance(color){const channel=value=>{const x=value/255;return x<=.03928?x/12.92:Math.pow((x+.055)/1.055,2.4)};return .2126*channel(color[0])+.7152*channel(color[1])+.0722*channel(color[2])}function contrastOver(color,alpha2,background){const a=color[3]*alpha2;const mixed=[color[0]*a+background[0]*(1-a),color[1]*a+background[1]*(1-a),color[2]*a+background[2]*(1-a),1];const x=luminance(mixed),y=luminance(background);return(Math.max(x,y)+.05)/(Math.min(x,y)+.05)}function pad(bounds2,amount2){return{x:bounds2.x-amount2,y:bounds2.y-amount2,width:bounds2.width+amount2*2,height:bounds2.height+amount2*2}}function inset(bounds2,fraction){const dx=bounds2.width*fraction,dy=bounds2.height*fraction;return{x:bounds2.x+dx,y:bounds2.y+dy,width:bounds2.width-dx*2,height:bounds2.height-dy*2}}function intersects(a,b){return a.x<b.x+b.width&&b.x<a.x+a.width&&a.y<b.y+b.height&&b.y<a.y+a.height}function intersection(a,b){const x=Math.max(a.x,b.x),y=Math.max(a.y,b.y);const right=Math.min(a.x+a.width,b.x+b.width),bottom=Math.min(a.y+a.height,b.y+b.height);return right>x&&bottom>y?{x,y,width:right-x,height:bottom-y}:null}function contains(outer,inner){return outer.x<=inner.x&&outer.y<=inner.y&&outer.x+outer.width>=inner.x+inner.width&&outer.y+outer.height>=inner.y+inner.height}function union(a,b){const x=Math.min(a.x,b.x),y=Math.min(a.y,b.y);return{x,y,width:Math.max(a.x+a.width,b.x+b.width)-x,height:Math.max(a.y+a.height,b.y+b.height)-y}}function segmentHitsBox(x0,y0,x1,y1,box){let t0=0,t1=1;const dx=x1-x0,dy=y1-y0;const edges=[[-dx,x0-box.x],[dx,box.x+box.width-x0],[-dy,y0-box.y],[dy,box.y+box.height-y0]];for(const[p,q]of edges){if(p===0){if(q<0)return false}else{const r=q/p;if(p<0){if(r>t1)return false;if(r>t0)t0=r}else{if(r<t0)return false;if(r<t1)t1=r}}}return t0<=t1}function strokeHitsBox(path,box){for(const r of path){const p=r.p;for(let o=0;o+7<p.length;o+=6){const x0=p[o],y0=p[o+1],x1=p[o+2],y1=p[o+3];const x2=p[o+4],y2=p[o+5],x3=p[o+6],y3=p[o+7];const left=Math.min(x0,x1,x2,x3),right=Math.max(x0,x1,x2,x3);const top=Math.min(y0,y1,y2,y3),bottom=Math.max(y0,y1,y2,y3);if(right<box.x||left>box.x+box.width||bottom<box.y||top>box.y+box.height)continue;let lastX=x0,lastY=y0;for(let k=1;k<=CUBIC_STEPS;k++){const t=k/CUBIC_STEPS,u=1-t;const a=u*u*u,b=3*u*u*t,c=3*u*t*t,d=t*t*t;const x=a*x0+b*x1+c*x2+d*x3;const y=a*y0+b*y1+c*y2+d*y3;if(segmentHitsBox(lastX,lastY,x,y,box))return true;lastX=x;lastY=y}}}return false}function textBlockOf(node){return node.data["key"]!==void 0?node.parent:null}function isGlyph(op){return!!op.node&&op.node.data["key"]!==void 0}function sourceOf(node){const source=node.source;return typeof source==="string"?source:""}function ownerKey(node){if(!node)return"unknown";let current=node;while(current.parent&¤t.parent.parent)current=current.parent;return current.mounted?String(current.id):"dynamic"}function restingMoments(film2,samples){const times=new Set;const clips=film2.clips;const active=t=>clips.some(clip=>clip.t0<t&&t<clip.t1);const nudge=.001;for(const clip of clips){const t=clip.t1+nudge;if(t<film2.duration&&!active(t))times.add(t)}times.add(Math.max(0,film2.duration-nudge));for(let i=0;i<samples;i++)times.add((i+.5)/samples*film2.duration);if(times.size<MIN_RESTING_MOMENTS){for(let i=0;i<AUTO_SAMPLES;i++){const t=(i+.5)/AUTO_SAMPLES*film2.duration;if(!active(t))times.add(t)}}return[...times].sort((a,b)=>a-b)}function frameAt2(film2,time){try{return film2.frame(time)}catch(error){if(!isSuspend(error))throw error;return error.promise.then(()=>frameAt2(film2,time))}}function zoomAt(film2,time){const camera=film2.stage.camera;const track=camera.tracks?.get("sx");return track?track.sample(time):camera.base.sx}function inspect(frame,time,zoomed,bleed){const findings=[];const{width,height,ops}=frame;const background=frame.background?parseColor(frame.background):frame.dark?[0,0,0,1]:[255,255,255,1];const canvas2={x:0,y:0,width,height};const blocks=new Map;const fills=[];const strokes=[];const off=new Map;let outsideMarks=0;ops.forEach((op,order)=>{if(op.kind!=="path"||op.path.length===0)return;const glyph=isGlyph(op);const alpha2=Math.max(op.fillAlpha,op.strokeAlpha);if(alpha2<MIN_ALPHA)return;const shape2=pathBounds(op.path);if(!shape2)return;const box=op.stroke?pad(shape2,op.strokeWidth/2):shape2;const block=glyph?textBlockOf(op.node):null;const outside=box.x<-EDGE_TOLERANCE||box.y<-EDGE_TOLERANCE||box.x+box.width>width+EDGE_TOLERANCE||box.y+box.height>height+EDGE_TOLERANCE;const spansFrame=box.x<=0&&box.x+box.width>=width||box.y<=0&&box.y+box.height>=height;if(outside&&(glyph||!spansFrame&&!zoomed&&!bleed)){const visible=intersects(box,canvas2);const text2=block?sourceOf(block):void 0;const key=glyph?`text:${text2}`:"marks";const existing=off.get(key);const severity=glyph&&visible&&!zoomed?"error":"warning";if(existing){existing.box=union(existing.box,box);if(!glyph)outsideMarks+=1}else{if(!glyph)outsideMarks=1;off.set(key,{key:`film.off_canvas:${key}`,code:"film.off_canvas",severity,time,box,message:glyph?`Text ${JSON.stringify(text2??"")} runs off the canvas${visible?" and is clipped":""}.`:"",...text2?{text:text2}:{}})}}if(glyph&&block&&op.fillAlpha>=MIN_TEXT_ALPHA){let entry=blocks.get(block);if(!entry)blocks.set(block,entry={id:block,source:sourceOf(block),bounds:shape2,glyphs:[]});entry.bounds=union(entry.bounds,shape2);entry.glyphs.push({box:shape2,order})}else if(!glyph){if(op.fill&&op.fillAlpha>=OPAQUE&&solid3(op.fill)[3]>=OPAQUE&&op.path.some(r=>r.closed))fills.push({order,bounds:shape2});if(op.stroke&&op.strokeAlpha>=MIN_ALPHA&&op.strokePath.length>0){const contrast=contrastOver(solid3(op.stroke),op.strokeAlpha,background);if(contrast>=MIN_STROKE_CONTRAST)strokes.push({op,order,contrast})}}});const marks=off.get("marks");if(marks)marks.message=`${outsideMarks===1?"A mark extends":`${outsideMarks} marks extend`} past the ${width}x${height} canvas.`;findings.push(...off.values());const occluded=(lower,upper,box)=>fills.some(fill=>fill.order>lower&&fill.order<upper&&contains(fill.bounds,box));const list3=[...blocks.values()];for(let i=0;i<list3.length;i++){const a=list3[i];for(let j=i+1;j<list3.length;j++){const b=list3[j];if(!intersects(a.bounds,b.bounds))continue;let hit=null;for(const ga of a.glyphs){if(!intersects(ga.box,b.bounds))continue;for(const gb of b.glyphs){const shared=intersection(ga.box,gb.box);if(!shared)continue;const smaller=Math.min(ga.box.width*ga.box.height,gb.box.width*gb.box.height);if(smaller<=0||shared.width*shared.height/smaller<MIN_OVERLAP)continue;if(occluded(Math.min(ga.order,gb.order),Math.max(ga.order,gb.order),ga.order<gb.order?ga.box:gb.box))continue;hit=hit?union(hit,shared):shared}}if(hit){findings.push({key:`film.text_overlap:${a.source}|${b.source}`,code:"film.text_overlap",severity:"error",time,box:hit,message:`Text ${JSON.stringify(a.source)} overlaps text ${JSON.stringify(b.source)}.`,text:a.source,other:b.source})}}}for(const block of list3){for(const{op,order,contrast}of strokes){const strokeBox=pathBounds(op.strokePath);if(!strokeBox||!intersects(pad(strokeBox,op.strokeWidth),block.bounds))continue;let hit=null;for(const glyph of block.glyphs){const target=inset(glyph.box,GLYPH_INSET);if(!intersects(strokeBox,target))continue;if(!strokeHitsBox(op.strokePath,target))continue;if(order<glyph.order&&occluded(order,glyph.order,glyph.box))continue;hit=hit?union(hit,glyph.box):glyph.box}if(hit){const strong=op.strokeWidth>=CROSSING_ERROR_WIDTH&&contrast>=CROSSING_ERROR_CONTRAST;findings.push({key:`film.text_crossed:${block.source}:${ownerKey(op.node)}`,code:"film.text_crossed",severity:strong?"error":"warning",time,box:hit,message:`A stroke crosses text ${JSON.stringify(block.source)}.`,text:block.source})}}}return findings}async function checkFilm(film2,options={}){const compiled=isFilm(film2)?await film2.compile(options):film2;const times=options.times?[...options.times]:restingMoments(compiled,options.samples??0);const merged=new Map;for(const time of times){const frame=await frameAt2(compiled,time);for(const{key,...finding}of inspect(frame,time,zoomAt(compiled,time)!==1,compiled.bleed)){const seen=merged.get(key);if(seen){seen.until=time;if(finding.severity==="error")seen.severity="error"}else{merged.set(key,{...finding,until:time,stage:{x:0,y:0}})}}}const round=value=>Math.round(value*100)/100;const diagnostics=[...merged.values()].map(entry=>({...entry,time:Math.round(entry.time*1e3)/1e3,until:Math.round(entry.until*1e3)/1e3,box:{x:round(entry.box.x),y:round(entry.box.y),width:round(entry.box.width),height:round(entry.box.height)},stage:{x:round(entry.box.x+entry.box.width/2-compiled.width/2),y:round(entry.box.y+entry.box.height/2-compiled.height/2)}})).sort((a,b)=>a.severity===b.severity?a.time-b.time:a.severity==="error"?-1:1);const errors=diagnostics.filter(entry=>entry.severity==="error").length;return{ok:errors===0,width:compiled.width,height:compiled.height,duration:compiled.duration,sampled:times.map(time=>Math.round(time*1e3)/1e3),diagnostics,summary:{errors,warnings:diagnostics.length-errors}}}var explainer=`import { axes, colorAlong, dot, draw, dynamic, fadeIn, film, line, tex, text, to, write } from 'vizmatic/stage'
|
|
133
|
+
`}var EDGE_TOLERANCE=1;var MIN_ALPHA=.08;var MIN_TEXT_ALPHA=.15;var MIN_OVERLAP=.12;var GLYPH_INSET=.12;var MIN_RESTING_MOMENTS=5;var AUTO_SAMPLES=12;var CUBIC_STEPS=6;var CROSSING_ERROR_WIDTH=2;var CROSSING_ERROR_CONTRAST=2;var MIN_STROKE_CONTRAST=1.6;var OPAQUE=.9;function solid3(paint){return isGradient(paint)?sampleStops(paint.stops,.5):paint}function luminance(color){const channel=value=>{const x=value/255;return x<=.03928?x/12.92:Math.pow((x+.055)/1.055,2.4)};return .2126*channel(color[0])+.7152*channel(color[1])+.0722*channel(color[2])}function contrastOver(color,alpha2,background){const a=color[3]*alpha2;const mixed=[color[0]*a+background[0]*(1-a),color[1]*a+background[1]*(1-a),color[2]*a+background[2]*(1-a),1];const x=luminance(mixed),y=luminance(background);return(Math.max(x,y)+.05)/(Math.min(x,y)+.05)}function pad(bounds2,amount2){return{x:bounds2.x-amount2,y:bounds2.y-amount2,width:bounds2.width+amount2*2,height:bounds2.height+amount2*2}}function inset(bounds2,fraction){const dx=bounds2.width*fraction,dy=bounds2.height*fraction;return{x:bounds2.x+dx,y:bounds2.y+dy,width:bounds2.width-dx*2,height:bounds2.height-dy*2}}function intersects(a,b){return a.x<b.x+b.width&&b.x<a.x+a.width&&a.y<b.y+b.height&&b.y<a.y+a.height}function intersection(a,b){const x=Math.max(a.x,b.x),y=Math.max(a.y,b.y);const right=Math.min(a.x+a.width,b.x+b.width),bottom=Math.min(a.y+a.height,b.y+b.height);return right>x&&bottom>y?{x,y,width:right-x,height:bottom-y}:null}function contains(outer,inner){return outer.x<=inner.x&&outer.y<=inner.y&&outer.x+outer.width>=inner.x+inner.width&&outer.y+outer.height>=inner.y+inner.height}function union(a,b){const x=Math.min(a.x,b.x),y=Math.min(a.y,b.y);return{x,y,width:Math.max(a.x+a.width,b.x+b.width)-x,height:Math.max(a.y+a.height,b.y+b.height)-y}}function segmentHitsBox(x0,y0,x1,y1,box){let t0=0,t1=1;const dx=x1-x0,dy=y1-y0;const edges=[[-dx,x0-box.x],[dx,box.x+box.width-x0],[-dy,y0-box.y],[dy,box.y+box.height-y0]];for(const[p,q]of edges){if(p===0){if(q<0)return false}else{const r=q/p;if(p<0){if(r>t1)return false;if(r>t0)t0=r}else{if(r<t0)return false;if(r<t1)t1=r}}}return t0<=t1}function strokeHitsBox(path,box){for(const r of path){const p=r.p;for(let o=0;o+7<p.length;o+=6){const x0=p[o],y0=p[o+1],x1=p[o+2],y1=p[o+3];const x2=p[o+4],y2=p[o+5],x3=p[o+6],y3=p[o+7];const left=Math.min(x0,x1,x2,x3),right=Math.max(x0,x1,x2,x3);const top=Math.min(y0,y1,y2,y3),bottom=Math.max(y0,y1,y2,y3);if(right<box.x||left>box.x+box.width||bottom<box.y||top>box.y+box.height)continue;let lastX=x0,lastY=y0;for(let k=1;k<=CUBIC_STEPS;k++){const t=k/CUBIC_STEPS,u=1-t;const a=u*u*u,b=3*u*u*t,c=3*u*t*t,d=t*t*t;const x=a*x0+b*x1+c*x2+d*x3;const y=a*y0+b*y1+c*y2+d*y3;if(segmentHitsBox(lastX,lastY,x,y,box))return true;lastX=x;lastY=y}}}return false}function textBlockOf(node){return node.data["key"]!==void 0?node.parent:null}function isGlyph(op){return!!op.node&&op.node.data["key"]!==void 0}function sourceOf(node){const source=node.source;return typeof source==="string"?source:""}function ownerKey(node){if(!node)return"unknown";let current=node;while(current.parent&¤t.parent.parent)current=current.parent;return current.mounted?String(current.id):"dynamic"}function restingMoments(film2,samples){const times=new Set;const clips=film2.clips;const active=t=>clips.some(clip=>clip.t0<t&&t<clip.t1);const nudge=.001;for(const clip of clips){const t=clip.t1+nudge;if(t<film2.duration&&!active(t))times.add(t)}times.add(Math.max(0,film2.duration-nudge));for(let i=0;i<samples;i++)times.add((i+.5)/samples*film2.duration);if(times.size<MIN_RESTING_MOMENTS){for(let i=0;i<AUTO_SAMPLES;i++){const t=(i+.5)/AUTO_SAMPLES*film2.duration;if(!active(t))times.add(t)}}return[...times].sort((a,b)=>a-b)}function frameAt2(film2,time){try{return film2.frame(time)}catch(error){if(!isSuspend(error))throw error;return error.promise.then(()=>frameAt2(film2,time))}}function zoomAt(film2,time){const camera=film2.stage.camera;const track=camera.tracks?.get("sx");return track?track.sample(time):camera.base.sx}function inspect(frame,time,zoomed,bleed){const findings=[];const{width,height,ops}=frame;const background=frame.background?parseColor(frame.background):frame.dark?[0,0,0,1]:[255,255,255,1];const canvas2={x:0,y:0,width,height};const blocks=new Map;const fills=[];const strokes=[];const off=new Map;let outsideMarks=0;ops.forEach((op,order)=>{if(op.kind!=="path"||op.path.length===0)return;const glyph=isGlyph(op);const alpha2=Math.max(op.fillAlpha,op.strokeAlpha);if(alpha2<MIN_ALPHA)return;const shape2=pathBounds(op.path);if(!shape2)return;const box=op.stroke?pad(shape2,op.strokeWidth/2):shape2;const block=glyph?textBlockOf(op.node):null;const outside=box.x<-EDGE_TOLERANCE||box.y<-EDGE_TOLERANCE||box.x+box.width>width+EDGE_TOLERANCE||box.y+box.height>height+EDGE_TOLERANCE;const spansFrame=box.x<=0&&box.x+box.width>=width||box.y<=0&&box.y+box.height>=height;if(outside&&(glyph||!spansFrame&&!zoomed&&!bleed)){const visible=intersects(box,canvas2);const text2=block?sourceOf(block):void 0;const key=glyph?`text:${text2}`:"marks";const existing=off.get(key);const severity=glyph&&visible&&!zoomed?"error":"warning";if(existing){existing.box=union(existing.box,box);if(!glyph)outsideMarks+=1}else{if(!glyph)outsideMarks=1;off.set(key,{key:`film.off_canvas:${key}`,code:"film.off_canvas",severity,time,box,message:glyph?`Text ${JSON.stringify(text2??"")} runs off the canvas${visible?" and is clipped":""}.`:"",...text2?{text:text2}:{}})}}if(glyph&&op.node.data["missingGlyph"]&&op.fillAlpha>=MIN_TEXT_ALPHA){const char=String(op.node.data["key"]);const code=`U+${char.codePointAt(0).toString(16).toUpperCase().padStart(4,"0")}`;const text2=block?sourceOf(block):"";findings.push({key:`film.missing_glyph:${text2}:${code}`,code:"film.missing_glyph",severity:"error",time,box:shape2,message:`Text ${JSON.stringify(text2)} has a character that no bundled font can draw (${code}). It renders as an empty box.`,text:text2})}if(glyph&&block&&op.fillAlpha>=MIN_TEXT_ALPHA){let entry=blocks.get(block);if(!entry)blocks.set(block,entry={id:block,source:sourceOf(block),bounds:shape2,glyphs:[]});entry.bounds=union(entry.bounds,shape2);entry.glyphs.push({box:shape2,order})}else if(!glyph){if(op.fill&&op.fillAlpha>=OPAQUE&&solid3(op.fill)[3]>=OPAQUE&&op.path.some(r=>r.closed))fills.push({order,bounds:shape2});if(op.stroke&&op.strokeAlpha>=MIN_ALPHA&&op.strokePath.length>0){const contrast=contrastOver(solid3(op.stroke),op.strokeAlpha,background);if(contrast>=MIN_STROKE_CONTRAST)strokes.push({op,order,contrast})}}});const marks=off.get("marks");if(marks)marks.message=`${outsideMarks===1?"A mark extends":`${outsideMarks} marks extend`} past the ${width}x${height} canvas.`;findings.push(...off.values());const occluded=(lower,upper,box)=>fills.some(fill=>fill.order>lower&&fill.order<upper&&contains(fill.bounds,box));const list3=[...blocks.values()];for(let i=0;i<list3.length;i++){const a=list3[i];for(let j=i+1;j<list3.length;j++){const b=list3[j];if(!intersects(a.bounds,b.bounds))continue;let hit=null;for(const ga of a.glyphs){if(!intersects(ga.box,b.bounds))continue;for(const gb of b.glyphs){const shared=intersection(ga.box,gb.box);if(!shared)continue;const smaller=Math.min(ga.box.width*ga.box.height,gb.box.width*gb.box.height);if(smaller<=0||shared.width*shared.height/smaller<MIN_OVERLAP)continue;if(occluded(Math.min(ga.order,gb.order),Math.max(ga.order,gb.order),ga.order<gb.order?ga.box:gb.box))continue;hit=hit?union(hit,shared):shared}}if(hit){findings.push({key:`film.text_overlap:${a.source}|${b.source}`,code:"film.text_overlap",severity:"error",time,box:hit,message:`Text ${JSON.stringify(a.source)} overlaps text ${JSON.stringify(b.source)}.`,text:a.source,other:b.source})}}}for(const block of list3){for(const{op,order,contrast}of strokes){const strokeBox=pathBounds(op.strokePath);if(!strokeBox||!intersects(pad(strokeBox,op.strokeWidth),block.bounds))continue;let hit=null;for(const glyph of block.glyphs){const target=inset(glyph.box,GLYPH_INSET);if(!intersects(strokeBox,target))continue;if(!strokeHitsBox(op.strokePath,target))continue;if(order<glyph.order&&occluded(order,glyph.order,glyph.box))continue;hit=hit?union(hit,glyph.box):glyph.box}if(hit){const strong=op.strokeWidth>=CROSSING_ERROR_WIDTH&&contrast>=CROSSING_ERROR_CONTRAST;findings.push({key:`film.text_crossed:${block.source}:${ownerKey(op.node)}`,code:"film.text_crossed",severity:strong?"error":"warning",time,box:hit,message:`A stroke crosses text ${JSON.stringify(block.source)}.`,text:block.source})}}}return findings}async function checkFilm(film2,options={}){const compiled=isFilm(film2)?await film2.compile(options):film2;const times=options.times?[...options.times]:restingMoments(compiled,options.samples??0);const merged=new Map;for(const time of times){const frame=await frameAt2(compiled,time);for(const{key,...finding}of inspect(frame,time,zoomAt(compiled,time)!==1,compiled.bleed)){const seen=merged.get(key);if(seen){seen.until=time;if(finding.severity==="error")seen.severity="error"}else{merged.set(key,{...finding,until:time,stage:{x:0,y:0}})}}}const round=value=>Math.round(value*100)/100;const diagnostics=[...merged.values()].map(entry=>({...entry,time:Math.round(entry.time*1e3)/1e3,until:Math.round(entry.until*1e3)/1e3,box:{x:round(entry.box.x),y:round(entry.box.y),width:round(entry.box.width),height:round(entry.box.height)},stage:{x:round(entry.box.x+entry.box.width/2-compiled.width/2),y:round(entry.box.y+entry.box.height/2-compiled.height/2)}})).sort((a,b)=>a.severity===b.severity?a.time-b.time:a.severity==="error"?-1:1);const errors=diagnostics.filter(entry=>entry.severity==="error").length;return{ok:errors===0,width:compiled.width,height:compiled.height,duration:compiled.duration,sampled:times.map(time=>Math.round(time*1e3)/1e3),diagnostics,summary:{errors,warnings:diagnostics.length-errors}}}var explainer=`import { axes, colorAlong, dot, draw, dynamic, fadeIn, film, line, tex, text, to, write } from 'vizmatic/stage'
|
|
134
134
|
|
|
135
135
|
// One idea, shown as it changes: a secant line becomes a tangent.
|
|
136
136
|
export default film({ title: 'A limit you can see' }, (s) => {
|
|
@@ -728,10 +728,11 @@ interface LoadedFont {
|
|
|
728
728
|
}
|
|
729
729
|
|
|
730
730
|
declare function parseFont(bytes: ArrayBuffer): LoadedFont;
|
|
731
|
-
type FontFamily = 'sans' | 'serif' | 'mono' | 'noto';
|
|
731
|
+
type FontFamily = 'sans' | 'serif' | 'text-serif' | 'mono' | 'noto';
|
|
732
732
|
type FontWeight = 400 | 600 | 700;
|
|
733
|
+
type BundledFamily = FontFamily | 'math';
|
|
733
734
|
/** Get a font now, or suspend the current compile until it arrives. */
|
|
734
|
-
declare function fontFor(family:
|
|
735
|
+
declare function fontFor(family: BundledFamily, weight?: FontWeight, italic?: boolean): LoadedFont;
|
|
735
736
|
/** Glyph outline scaled to a pixel size, with y pointing down and the origin on the baseline. */
|
|
736
737
|
declare function glyphPath(font: LoadedFont, glyph: number, size: number): Path;
|
|
737
738
|
|
|
@@ -931,7 +932,7 @@ interface DecimalOptions {
|
|
|
931
932
|
/** A number readout that follows a function of the timeline, drawn fresh each frame. */
|
|
932
933
|
declare function decimal(read: () => number, options?: DecimalOptions): Node;
|
|
933
934
|
|
|
934
|
-
type FilmDiagnosticCode = 'film.off_canvas' | 'film.text_overlap' | 'film.text_crossed';
|
|
935
|
+
type FilmDiagnosticCode = 'film.off_canvas' | 'film.text_overlap' | 'film.text_crossed' | 'film.missing_glyph';
|
|
935
936
|
interface FilmDiagnostic {
|
|
936
937
|
code: FilmDiagnosticCode;
|
|
937
938
|
severity: 'error' | 'warning';
|
|
@@ -972,8 +973,8 @@ interface FilmCheckOptions extends CompileOverrides {
|
|
|
972
973
|
samples?: number;
|
|
973
974
|
}
|
|
974
975
|
/**
|
|
975
|
-
* Inspect a film for layout defects: marks off the canvas, text on text,
|
|
976
|
-
*
|
|
976
|
+
* Inspect a film for layout defects: marks off the canvas, text on text, strokes
|
|
977
|
+
* through text, and characters that no font can draw. It looks where the film comes to rest, because objects may
|
|
977
978
|
* cross each other while moving. Runs anywhere, with no rendering.
|
|
978
979
|
*/
|
|
979
980
|
declare function checkFilm(film: FilmDefinition | CompiledFilm, options?: FilmCheckOptions): Promise<FilmCheckReport>;
|