@mathzetta/qblur 0.1.0 → 0.1.2
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/CHANGELOG.md +29 -0
- package/LICENSE +1 -1
- package/README.md +13 -4
- package/dist/cpu-worker.js +2 -2
- package/dist/qblur-apply.js +2 -2
- package/dist/qblur-element.js +2 -2
- package/dist/qblur.core.js +2 -2
- package/dist/qblur.external.global.min.js +2 -2
- package/dist/qblur.external.js +2 -2
- package/dist/qblur.global.min.js +2 -2
- package/dist/qblur.js +2 -2
- package/docs/filters.md +1 -1
- package/docs/library.md +3 -6
- package/package.json +8 -2
- package/src/cpu-helpers.js +2 -0
- package/src/cpu-runner.js +26 -12
- package/src/cpu.js +15 -10
- package/src/format.js +22 -13
- package/src/graphics.js +1 -1
- package/src/png.js +3 -0
- package/src/runtime.js +25 -6
- package/src/strokes.js +11 -3
package/dist/qblur.external.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/* qblur 0.1.
|
|
2
|
-
import{FILTER_NAMES as e,COLOUR_SPACES as t,PLACES as r,filterShader as o,filterVertexShader as n,REACH as a,FILTER_FUNCTIONS as s,FILTER_VALUES as i,filterPictureCalls as c}from"mathzetta/glsl";import{parseTree as l}from"mathzetta";import{checkGeneratedJs as h}from"mathzetta/formulas";const u=["round","soft","marker","chalk","spray"],p=["recorded","even","per-stroke"],f=["pressure","speed","none"],m=["none","inside","outside"],d=30,g={type:"strokes",strokes:[],brush:"round",size:.03,flow:1,spacing:.2,taper:0,buildUp:!1,widthFrom:"pressure",timing:"recorded",speed:1,gap:6,start:0,fit:0,age:30,clip:"none",shadows:[]};function $(e,t){throw new Error(`Graphic "${e}": ${t}`)}function y(e,t,r,o,n){const a=Number(r);return(!Number.isFinite(a)||a<o||a>n)&&$(e,`"${t}" is a number from ${o} to ${n}`),a}function w(e,t){for(const r of Object.keys(t))r in g||$(e,`no such setting "${r}" for strokes`);const r={...g,...t},o=(t,o)=>(o.includes(r[t])||$(e,`"${t}" is ${o.join(", ")} — not "${r[t]}"`),r[t]),n={type:"strokes",brush:o("brush",u),widthFrom:o("widthFrom",f),timing:o("timing",p),clip:o("clip",m),size:y(e,"size",r.size,.001,.5),flow:y(e,"flow",r.flow,.01,1),spacing:y(e,"spacing",r.spacing,.02,2),taper:y(e,"taper",r.taper,0,.5),speed:y(e,"speed",r.speed,.05,20),gap:y(e,"gap",r.gap,0,600),start:y(e,"start",r.start,0,1e4),fit:y(e,"fit",r.fit,0,1e4),age:y(e,"age",r.age,1,1e4),buildUp:Boolean(r.buildUp),shadows:[]};Array.isArray(r.strokes)||$(e,'"strokes" is a list of { "points": [[x, y, ms, pressure], …] }');let a=0;return n.strokes=r.strokes.map((t,r)=>{const o=Array.isArray(t)?t:t?.points;return Array.isArray(o)||$(e,`stroke ${r+1} is { "points": [[x, y, ms, pressure], …] }`),a+=o.length,a>6e4&&$(e,"a drawing has at most 60000 points"),{points:o.map((t,o)=>((!Array.isArray(t)||t.length<2||!t.every(e=>Number.isFinite(Number(e))))&&$(e,`stroke ${r+1}, point ${o+1} is [x, y, ms, pressure]`),[+Number(t[0]).toFixed(4),+Number(t[1]).toFixed(4),Math.round(Number(t[2]??16*o)),+Math.min(1,Math.max(0,Number(t[3]??1))).toFixed(2)]))}}),n}function b(e,t=1){const r=[];let o=e.start;const n=30/e.speed,a=20/e.speed;for(const s of e.strokes){const i=s.points;if(!i.length)continue;const c=[0];for(let e=1;e<i.length;e++)c.push(c[e-1]+Math.hypot((i[e][0]-i[e-1][0])*t,i[e][1]-i[e-1][1]));const l=c[c.length-1]||1e-9,h=i[0][2],u=i.map((t,r)=>{let o;o="recorded"===e.timing?(t[2]-h)/1e3*30/e.speed:"even"===e.timing?c[r]*n:c[r]/l*a;let s=1;if("pressure"===e.widthFrom)s=.3+.7*t[3];else if("speed"===e.widthFrom&&r>0){const e=Math.max(1,t[2]-i[r-1][2]),o=(c[r]-c[r-1])/e*1e3;s=Math.min(1.3,Math.max(.35,1.3-.6*o))}return e.taper>0&&(s*=Math.max(.15,Math.min(1,c[r]/l/e.taper,(1-c[r]/l)/e.taper))),{x:t[0],y:t[1],f:o,wf:s}});"speed"===e.widthFrom&&u.length>1&&(u[0].wf=u[1].wf);const p=u[u.length-1].f;for(const e of u)e.f+=o;r.push({points:u,start:o,end:o+p}),o+=p+e.gap}let s=r.length?r[r.length-1].end:e.start;if(e.fit>0&&s>e.start){const t=e.fit/(s-e.start);for(const o of r){for(const r of o.points)r.f=e.start+(r.f-e.start)*t;o.start=e.start+(o.start-e.start)*t,o.end=e.start+(o.end-e.start)*t}s=e.start+e.fit}return{strokes:r,total:s}}function x(e,t){let r=Math.imul(0|e,374761393)+Math.imul(0|t,668265263)|0;return r=Math.imul(r^r>>>13,1274126177),((r^r>>>16)>>>0)/4294967296}const _=new Map;function k(e,t,r,o=1/0,{mask:n=null}={}){const a=t*r,{alpha:s,passes:i,latest:c,cov:l,when:h,touched:u}=function(e){let t=_.get(e);return t||(t={alpha:new Float32Array(e),passes:new Float32Array(e),latest:new Float32Array(e),cov:new Float32Array(e),when:new Float32Array(e),touched:new Int32Array(e)},_.clear(),_.set(e,t)),t.alpha.fill(0),t.passes.fill(0),t.latest.fill(-1),t}(a),{strokes:p,total:f}=b(e,t/r),m=Number.isFinite(o)?o:f,d=Math.max(.5,e.size*r/2);let g=0;p.forEach(o=>{if(o.start>m)return;let n=0;const a=(t,r,o,n)=>{const a=g++;if("spray"===e.brush){const e=Math.max(3,Math.round(.6*o)),s=Math.max(.6,.07*o);for(let i=0;i<e;i++){const e=x(a,2*i)*Math.PI*2,c=Math.sqrt(x(a,2*i+1))*o;p(t+Math.cos(e)*c,r+Math.sin(e)*c,s,n,"round")}}else p(t,r,o,n,e.brush)},p=(o,a,s,i,c)=>{const p="marker"===c?s:s+1,f=Math.max(0,Math.floor(o-p)),m=Math.min(t-1,Math.ceil(o+p)),d=Math.max(0,Math.floor(a-p)),g=Math.min(r-1,Math.ceil(a+p));for(let r=d;r<=g;r++)for(let p=f;p<=m;p++){const f=p+.5-o,m=r+.5-a;let d;if("soft"===c){const e=Math.hypot(f,m)/s;if(e>=1)continue;const t=1-e;d=t*t*(3-2*t)}else if("marker"===c){const e=(f+m)*Math.SQRT1_2,t=(m-f)*Math.SQRT1_2,r=Math.hypot(e/s,t/(.33*s));d=Math.min(1,Math.max(0,(1-r)*s*.33+.5))}else d=Math.min(1,Math.max(0,s-Math.hypot(f,m)+.5)),"chalk"===c&&(d*=x(p,7919*r)>.42?1:.12);if(d<=0)continue;d*=e.flow;const g=r*t+p;d>l[g]&&(0===l[g]&&(u[n++]=g),l[g]=d),d>.02&&(h[g]=i)}},f=o.points;let $=0;const y=e=>[e.x*t,e.y*r];if(1===f.length||f.every(e=>e.x===f[0].x&&e.y===f[0].y)){const[e,t]=y(f[0]);a(e,t,d*f[0].wf,f[0].f)}for(let t=1;t<f.length;t++){const r=f[t-1],o=f[t];if(r.f>m)break;const[n,s]=y(r),[i,c]=y(o);let l=1;o.f>m&&(l=(m-r.f)/Math.max(1e-9,o.f-r.f));const h=Math.hypot(i-n,c-s);let u=1===t?0:$;for(;u<=h*l;){const t=h?u/h:0,l=d*(r.wf+(o.wf-r.wf)*t);a(n+(i-n)*t,s+(c-s)*t,l,r.f+(o.f-r.f)*t),u+=Math.max(.5,2*e.spacing*l)}if($=u-h,l<1)break}for(let t=0;t<n;t++){const r=u[t],o=l[r];s[r]=e.buildUp?1-(1-s[r])*(1-o):Math.max(s[r],o),i[r]+=o,o>.02&&h[r]>c[r]&&(c[r]=h[r]),l[r]=0}});const $=new Uint8ClampedArray(4*a),y="inside"===e.clip,w="outside"===e.clip;for(let t=0;t<a;t++){let r=s[t];if(0===r)continue;let o=1;n&&(y||w)&&(o=y?n[t]:1-n[t]),r*=o;const a=4*t;$[a]=Math.round(255*Math.min(1,Math.max(0,(m-c[t])/e.age))),$[a+1]=Math.round(255*Math.min(1,i[t]*o/4)),$[a+2]=Math.round(255*Math.min(1,Math.max(0,c[t]/Math.max(1e-9,f)))),$[a+3]=Math.round(255*r)}return{data:$,width:t,height:r,total:f}}function v(e,t,r,{minArea:o=40,tolerance:n=.8}={}){const a=(o,n)=>o>=0&&n>=0&&o<t&&n<r&&e[n*t+o]>.5,s=new Int32Array(t*r).fill(-1),i=[],c=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]];let l=0;for(let e=0;e<r;e++)for(let r=0;r<t;r++){if(!a(r,e)||s[e*t+r]>=0)continue;const h=l++,u=[e*t+r];s[e*t+r]=h;let p=0;for(;u.length;){const e=u.pop();p++;const r=e%t,o=(e-r)/t;for(const[e,n]of[[1,0],[-1,0],[0,1],[0,-1]]){const i=r+e,c=o+n;a(i,c)&&s[c*t+i]<0&&(s[c*t+i]=h,u.push(c*t+i))}}if(p<o)continue;const f=[[r,e]];let m=r,d=e,g=4;for(let o=0;o<4*p+16;o++){let o=!1;for(let e=1;e<=8;e++){const r=(g+e)%8,n=m+c[r][0],i=d+c[r][1];if(a(n,i)&&s[i*t+n]===h){g=(r+4)%8,m=n,d=i,o=!0;break}}if(!o||m===r&&d===e)break;f.push([m,d])}i.push(E(f,n))}return i}function E(e,t){if(e.length<4)return[...e,e[0]];const[r,o]=e[0];let n=0;return e.forEach(([t,a],s)=>{Math.hypot(t-r,a-o)>Math.hypot(e[n][0]-r,e[n][1]-o)&&(n=s)}),[...M(e.slice(0,n+1),t),...M([...e.slice(n),e[0]],t).slice(1)]}function M(e,t){if(e.length<3)return e;const r=new Uint8Array(e.length);r[0]=r[e.length-1]=1;const o=[[0,e.length-1]];for(;o.length;){const[n,a]=o.pop(),[s,i]=e[n],[c,l]=e[a],h=Math.hypot(c-s,l-i)||1e-9;let u=-1,p=-1;for(let t=n+1;t<a;t++){const r=Math.abs((c-s)*(i-e[t][1])-(s-e[t][0])*(l-i))/h;r>u&&(u=r,p=t)}u>t&&(r[p]=1,o.push([n,p],[p,a]))}return e.filter((e,t)=>r[t])}const A=["text","rect","ellipse","strokes"],T={text:{type:"text",text:"Text",font:"sans-serif",weight:"bold",style:"normal",size:.08,x:.5,y:.85,align:"center",angle:0,lineHeight:1.2,color:"#ffffff",outline:null,shadow:{color:"rgba(0,0,0,0.6)",blur:.15,dx:.04,dy:.06},shadows:[]},rect:{type:"rect",x:.5,y:.85,w:.8,h:.18,radius:.15,angle:0,color:"#ffffff",outline:null,shadow:null,shadows:[]},ellipse:{type:"ellipse",x:.5,y:.5,w:.4,h:.4,angle:0,color:"#ffffff",outline:null,shadow:null,shadows:[]}},O=8,j=(e,t)=>(t.shadows??[]).map((t,r)=>`${e}_shadow${r+1}`);function S(e,t){let r="rgb";for(const o of j(e,t))r=`mix(${r}, ${o}, alpha(${o}))`;return`mix(${r}, ${e}, alpha(${e}))`}const F=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([\d.,\s%deg/]+\)|[a-z]{3,20}|transparent)$/i,R=/^[\w\s,'"-]{1,80}$/,z=["normal","bold","100","200","300","400","500","600","700","800","900"];function I(e,t,r){if("string"!=typeof r||!F.test(r.trim()))throw new Error(`Graphic "${e}": "${t}" is a colour like "#ffcc00", "rgba(0,0,0,0.5)" or "white"`);return r.trim()}function N(e,t,r,o=-1/0,n=1/0){const a=Number(r);if(!Number.isFinite(a)||a<o||a>n)throw new Error(`Graphic "${e}": "${t}" is a number${Number.isFinite(o)?` from ${o} to ${n}`:""}`);return a}function U(e,t){if(null===t||!1===t)return null;if("object"!=typeof t)throw new Error(`Graphic "${e}": "outline" is { "color", "width" } or null`);return{color:I(e,"outline.color",t.color??"#000000"),width:N(e,"outline.width",t.width??.06,0,1)}}function B(e,t){if(null===t||!1===t)return null;if("object"!=typeof t)throw new Error(`Graphic "${e}": "shadow" is { "color", "blur", "dx", "dy" } or null`);return{color:I(e,"shadow.color",t.color??"rgba(0,0,0,0.6)"),blur:N(e,"shadow.blur",t.blur??.15,0,2),dx:N(e,"shadow.dx",t.dx??0,-2,2),dy:N(e,"shadow.dy",t.dy??0,-2,2)}}function C(e,t){if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(`Graphic "${e}": give { "type": "text" | "rect" | "ellipse", … }`);const r=t.type??"text";if(!A.includes(r))throw new Error(`Graphic "${e}": "type" is text, rect, ellipse or strokes — not "${r}"`);if("strokes"===r)return w(e,t);const o=T[r];for(const n of Object.keys(t))if(!(n in o)&&"fontUrl"!==n&&"onlyShadow"!==n)throw new Error(`Graphic "${e}": no such setting "${n}" for ${r}`);const n={type:r};for(const[r,a]of Object.entries(o)){if("type"===r)continue;const o=r in t&&void 0!==t[r]?t[r]:a;if("color"===r)n.color=I(e,r,o);else if("outline"===r)n.outline=U(e,o);else if("shadow"===r)n.shadow=B(e,o);else if("shadows"===r){if(!Array.isArray(o)||o.length>8)throw new Error(`Graphic "${e}": "shadows" is a list of up to 8 { "color", "blur", "dx", "dy" }`);n.shadows=o.map((t,r)=>{if(!t||"object"!=typeof t)throw new Error(`Graphic "${e}": shadow layer ${r+1} is { "color", "blur", "dx", "dy" }`);return B(e,t)})}else if("text"===r){if("string"!=typeof o||o.length>500)throw new Error(`Graphic "${e}": "text" is up to 500 characters`);n.text=o}else if("font"===r){if("string"!=typeof o||!R.test(o))throw new Error(`Graphic "${e}": "font" is a font family, like "Georgia" or "sans-serif"`);n.font=o}else if("weight"===r){if(!z.includes(String(o)))throw new Error(`Graphic "${e}": "weight" is normal, bold or 100–900`);n.weight=String(o)}else if("style"===r){if(!["normal","italic"].includes(o))throw new Error(`Graphic "${e}": "style" is normal or italic`);n.style=o}else if("align"===r){if(!["left","center","right"].includes(o))throw new Error(`Graphic "${e}": "align" is left, center or right`);n.align=o}else"size"===r?n.size=N(e,r,o,.005,2):"w"===r||"h"===r?n[r]=N(e,r,o,0,4):"radius"===r?n.radius=N(e,r,o,0,.5):"lineHeight"===r?n.lineHeight=N(e,r,o,.5,4):n[r]=N(e,r,o)}if(void 0!==t.fontUrl&&null!==t.fontUrl&&""!==t.fontUrl){if("text"!==r)throw new Error(`Graphic "${e}": "fontUrl" is for text`);let o;try{o=new URL(t.fontUrl)}catch{o=null}if(!o||"https:"!==o.protocol)throw new Error(`Graphic "${e}": "fontUrl" is an https:// address of a font file (.woff2, .woff, .ttf, .otf) or of a Google Fonts stylesheet`);n.fontUrl=o.href}return void 0!==t.onlyShadow&&(n.onlyShadow=N(e,"onlyShadow",t.onlyShadow,0,7)),n}function P(e){const t=String(e).trim().replace(/\s+/g," ");if(!/^[A-Za-z0-9 ]{1,60}$/.test(t))throw new Error('A Google Fonts name is letters, digits and spaces, like "Lobster" or "Playfair Display"');return`https://fonts.googleapis.com/css2?family=${t.replace(/ /g,"+")}:ital,wght@0,400;0,700;1,400;1,700&display=swap`}function G(e){try{const t=new URL(e);return"fonts.googleapis.com"!==t.hostname?null:(t.searchParams.get("family")??"").split(":")[0].replace(/\+/g," ")||null}catch{return null}}function D(e,{weight:t="400",style:r="normal"}={}){const o=[...e.matchAll(/@font-face\s*{([^}]*)}/g)].map(e=>e[1]),n=(e,t)=>(new RegExp(`${t}\\s*:\\s*([^;]+);`).exec(e)?.[1]??"").trim(),a=String("bold"===t?700:"normal"===t?400:t),s=o.filter(e=>n(e,"font-weight")===a&&n(e,"font-style")===r),i=(s.length?s:o).at(-1);return i&&(/url\(([^)]+)\)/.exec(i)?.[1]??"").replace(/^['"]|['"]$/g,"")||null}function L(e,t){const r=e.fontUrl?`"${q(e.fontUrl)}", ${e.font}`:e.font;return`${e.style} ${e.weight} ${Math.max(1,e.size*t)}px ${r}`}function q(e){let t=0;for(const r of e)t=31*t+r.charCodeAt(0)>>>0;return`mz-font-${t.toString(36)}`}const W=new Map;async function X(e,t=100){if("undefined"==typeof document&&"undefined"==typeof self)return[];const r="undefined"!=typeof document?document.fonts:self.fonts;if(!r)return[];const o=[];for(const n of Object.values(e??{}))if("text"===n.type){if(n.fontUrl&&"undefined"!=typeof FontFace){const e=`${n.fontUrl} ${n.weight} ${n.style}`;W.has(e)||W.set(e,H(n,r)),await W.get(e)||o.push(n.fontUrl)}try{await r.load(L(n,t),n.text)}catch{}}return[...new Set(o)]}async function H(e,t){try{let r=e.fontUrl;if(!/\.(woff2?|ttf|otf)(\?|$)/i.test(new URL(r).pathname)||G(r)){if(r=D(await(await fetch(r)).text(),e),!r||!r.startsWith("https://"))return null}const o=new FontFace(q(e.fontUrl),`url(${JSON.stringify(r)})`,{weight:e.weight,style:e.style});return t.add(await o.load()),o}catch{return null}}function K(e,t,r,o){e.save();const n="text"===t.type?t.size*o:o,a=void 0!==t.onlyShadow?t.shadows[t.onlyShadow]:null,s=a?2*(r+o)+1e3:0,i=a??t.shadow;if(e.translate(t.x*r-s,t.y*o),t.angle&&e.rotate(t.angle),i&&(e.shadowColor=i.color,e.shadowBlur=i.blur*n,e.shadowOffsetX=i.dx*n+s,e.shadowOffsetY=i.dy*n),e.fillStyle=a?"#000000":t.color,t.outline&&(e.strokeStyle=t.outline.color,e.lineWidth=t.outline.width*n,e.lineJoin="round"),"text"===t.type){e.font=L(t,o),e.textAlign=t.align,e.textBaseline="middle";const r=t.text.split("\n"),n=t.size*o*t.lineHeight;r.forEach((o,s)=>{const c=(s-(r.length-1)/2)*n;t.outline&&e.strokeText(o,0,c),t.outline&&i&&!a&&(e.shadowColor="transparent"),e.fillText(o,0,c),t.outline&&i&&!a&&(e.shadowColor=i.color)})}else{const n=t.w*r,s=t.h*o;if(e.beginPath(),"ellipse"===t.type)e.ellipse(0,0,n/2,s/2,0,0,2*Math.PI);else{const r=Math.min(n,s)*t.radius;e.roundRect?e.roundRect(-n/2,-s/2,n,s,r):e.rect(-n/2,-s/2,n,s)}e.fill(),t.outline&&(a||(e.shadowColor="transparent"),e.stroke())}e.restore()}async function Y(e,t,r,{t:o=1/0,mask:n=null}={}){const a=e.graphics??{},s=await X(a,r),i={};for(const[e,s]of Object.entries(a)){if("strokes"===s.type){const a=k(s,t,r,o,{mask:n});i[e]="undefined"!=typeof ImageData?new ImageData(a.data,t,r):a;continue}const a="undefined"!=typeof OffscreenCanvas&&"undefined"==typeof document?new OffscreenCanvas(t,r):Object.assign(document.createElement("canvas"),{width:t,height:r});K(a.getContext("2d"),s,t,r),i[e]=a}return Object.defineProperty(i,"failedFonts",{value:s}),i}const J="mathzetta-filter/1",V=["r","g","b","a","rgb","rgba"],Z=/^[A-Za-z][A-Za-z0-9_]*$/,Q=new Set([...e,"r","g","b","a","x","y","w","h","t","c","e","pi","color","image","resolution","base","position","main","in","out","inout","const","uniform","varying","attribute","void","float","int","bool","vec2","vec3","vec4","mat2","mat3","mat4","sampler2D","struct","precision","highp","mediump","lowp","if","else","for","while","do","return","break","continue","discard","true","false","texture2D","texture","mix","clamp","step","smoothstep","abs","sign","floor","ceil","fract","mod","min","max","sin","cos","tan","asin","acos","atan","pow","exp","log","exp2","log2","sqrt","inversesqrt","length","distance","dot","cross","normalize","radians","degrees"]),ee=e=>Array.isArray(e)&&3===e.length&&e.every(e=>Number.isFinite(Number(e))),te=e=>e&&"object"==typeof e&&!Array.isArray(e),re={place:"cover",zoom:1,x:.5,y:.5,angle:0};function oe(e){if("string"==typeof e){if(!e.trim())throw new Error("The filter is empty");return{format:J,color:e.trim()}}if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('A filter is an expression, or an object with "color" or "steps"');if(void 0!==e.format&&e.format!==J)throw new Error(`Unknown filter format "${e.format}" (this is ${J})`);const r={format:J};for(const t of["name","author","description"])void 0!==e[t]&&""!==e[t]&&(r[t]=String(e[t]));if(void 0!==e.steps){if(void 0!==e.color)throw new Error('A filter has either "color" or "steps", not both');if(!Array.isArray(e.steps)||!e.steps.length)throw new Error('"steps" must be a list with at least one step');return r.steps=e.steps.map(ie),void 0!==e.notes&&(r.notes=ne(e.notes,he(r))),r}if(void 0===e.color)throw new Error('A filter needs "color" (an expression, or one per channel) or "steps"');const o=function(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('"params" is an object of name → { default, min, max }');const t={};for(const[r,o]of Object.entries(e)){if(!Z.test(r))throw new Error(`Parameter name "${r}" must be letters, digits and _, starting with a letter`);if(Q.has(r))throw new Error(`"${r}" is already defined in every filter; pick another parameter name`);t[r]=ce(r,o)}return t}(e.params??{});Object.keys(o).length&&(r.params=o),void 0!==e.notes&&(r.notes=ne(e.notes,o));const n=function(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,{}])):e;if(!r||"object"!=typeof r)throw new Error('"images" is a list of names, or an object of name → { description }');const o={};for(const[e,n]of Object.entries(r)){if(!Z.test(e)||e.startsWith("mz_"))throw new Error(`Image name "${e}" must be letters, digits and _, starting with a letter`);if("source"===e)throw new Error('"source" is always available: the picture the chain started from');if(Q.has(e))throw new Error(`"${e}" is already defined in every filter; pick another image name`);if(e in t)throw new Error(`"${e}" is both a parameter and an image`);o[e]=se(e,n)}return o}(e.images??{},o);Object.keys(n).length&&(r.images=n);const a=function(e,t,r){if(!te(e))throw new Error('"graphics" is an object of name → { "type": "text" | "rect" | "ellipse", … }');const o={};for(const[n,a]of Object.entries(e)){if(!Z.test(n)||n.startsWith("mz_"))throw new Error(`Graphic name "${n}" must be letters, digits and _, starting with a letter`);if(Q.has(n)||"source"===n||"selection"===n)throw new Error(`"${n}" is already defined in every filter; pick another graphic name`);if(n in t||n in r)throw new Error(`"${n}" is both a graphic and a parameter or picture`);o[n]=C(n,a)}const n=new Set(Object.keys(o).flatMap(e=>Array.from({length:8},(t,r)=>`${e}_shadow${r+1}`)));for(const e of[...Object.keys(o),...Object.keys(t),...Object.keys(r)])if(n.has(e))throw new Error(`"${e}" is the name of a shadow layer of another graphic; pick another name`);return o}(e.graphics??{},o,n);Object.keys(a).length&&(r.graphics=a);const s=function(e){if(null==e)return null;const r="string"==typeof e?{in:e,out:e}:e;if(!te(r))throw new Error(`"space" is a colour space (${t.join(", ")}) or { "in": …, "out": … }`);const o={in:r.in??"srgb",out:r.out??"srgb"};for(const e of["in","out"])if(!t.includes(o[e]))throw new Error(`"space": "${o[e]}" is not a colour space; they are ${t.join(", ")}`);return"srgb"===o.in&&"srgb"===o.out?null:o}(e.space);return s&&(r.space=s),r.color=function(e){if("string"==typeof e){if(!e.trim())throw new Error('"color" is empty');return e.trim()}if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('"color" is an expression, or an object with r, g, b, a, rgb or rgba expressions');const t={};for(const[r,o]of Object.entries(e)){if(!V.includes(r))throw new Error(`"color" can set r, g, b, a, rgb or rgba — not "${r}"`);if("string"!=typeof o||!o.trim())throw new Error(`"color.${r}" must be an expression`);t[r]=o.trim()}if(!Object.keys(t).length)throw new Error('"color" sets no channels');return t}(e.color),r}function ne(e,t){if(!Array.isArray(e))throw new Error('"notes" is a list of Markdown texts and { "param": name } entries');return e.map(e=>{if("string"==typeof e)return e;if(!te(e)||"string"!=typeof e.param||1!==Object.keys(e).length)throw new Error('"notes": each entry is a Markdown text or { "param": name }');if(!(e.param in t))throw new Error(`"notes" places "${e.param}", but there is no parameter called that`);return{param:e.param}})}function ae(e){if(e.color)return{...e.graphics??{}};const t={};for(const r of e.steps)for(const[e,o]of Object.entries(ae(r.filter)))e in t||(t[e]=o);return t}function se(e,t){if(!te(t))throw new Error(`Image "${e}": give { description, place, zoom, x, y, angle }`);const o={};if(t.description&&(o.description=String(t.description)),void 0!==t.place){if(!r.includes(t.place))throw new Error(`Image "${e}": "place" is ${r.join(", ")} — not "${t.place}"`);o.place=t.place}for(const r of["zoom","x","y","angle"]){if(void 0===t[r])continue;const n=Number(t[r]);if(!Number.isFinite(n))throw new Error(`Image "${e}": "${r}" is a number`);o[r]=n}for(const r of Object.keys(t))if(!["description","place","zoom","x","y","angle"].includes(r))throw new Error(`Image "${e}": no such setting "${r}"`);return o}function ie(e){if("string"==typeof e)return{filter:oe(e),with:{},opacity:1,skip:!1};if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('A step is an expression, a filter, or { "filter": …, "with": { … }, "opacity": … }');const{filter:t,with:r,opacity:o,skip:n,...a}=e,s={filter:oe(void 0!==t?t:a),with:{},opacity:1,skip:Boolean(n)};if(void 0!==r){if(!r||"object"!=typeof r||Array.isArray(r))throw new Error('"with" is an object of parameter name → value');s.with={...r}}if(void 0!==o){const e=Number(o);if(!(e>=0&&e<=1))throw new Error('"opacity" is a number from 0 to 1');s.opacity=e}return s}function ce(e,t){if("number"==typeof t)t={default:t};else if(Array.isArray(t))t={type:"color",default:t};else if(!t||"object"!=typeof t)throw new Error(`Parameter "${e}" needs a default value`);const r=t.type??(Array.isArray(t.default)?"color":"number"),o={type:r};if(void 0!==t.label&&(o.label=String(t.label)),"color"===r){const r=t.default??[1,1,1];if(!ee(r))throw new Error(`Colour parameter "${e}" needs a default of three numbers, 0–1`);return o.default=r.map(Number),o}if("number"!==r)throw new Error(`Parameter "${e}": the type is "number" or "color", not "${r}"`);let n=null;if(void 0!==t.options){if(!Array.isArray(t.options)||!t.options.length||!t.options.every(e=>""!==e&&Number.isFinite(Number(e))))throw new Error(`Parameter "${e}": "options" is a list of numbers`);n=t.options.map(Number)}if(void 0!==t.input&&"slider"!==t.input&&"box"!==t.input)throw new Error(`Parameter "${e}": "input" is "slider" or "box", not "${t.input}"`);const a=Number(t.default??(n?n[0]:0));if(!Number.isFinite(a))throw new Error(`Parameter "${e}" needs a numeric default`);if(o.default=a,o.min=void 0!==t.min?Number(t.min):n?Math.min(...n,a):Math.min(0,2*a),o.max=void 0!==t.max?Number(t.max):n?Math.max(...n,a):Math.max(1,2*a),void 0!==t.step&&(o.step=Number(t.step)),n&&(o.options=n),"box"!==t.input||n||(o.input="box"),!(o.min<=a&&a<=o.max))throw new Error(`Parameter "${e}": the default ${a} is outside ${o.min} to ${o.max}`);return o}function le(e){if(e.color)return{...e.images??{}};const t={};for(const r of e.steps)for(const[e,o]of Object.entries(le(r.filter)))e in t||(t[e]=o);return t}function he(e){if(e.color)return{...e.params??{}};const t={};for(const r of e.steps)for(const[e,o]of Object.entries(he(r.filter)))e in t||(t[e]=o);return t}function ue(e){let t;try{t=oe(e)}catch(e){return[e.message]}const r=[];return pe({filter:t,with:{},opacity:1},[],r,!0),r}function pe(e,t,r,o){const{filter:n}=e,a=fe(n,t),s=he(n),i=le(n),c=ae(n);for(const[t,o]of Object.entries(e.with)){if(t in c){if(te(o))try{C(t,{...c[t],...o})}catch(e){r.push(`${a}: ${e.message}`)}else r.push(`${a}: "with" for the graphic "${t}" is an object of its settings`);continue}if(t in i){try{se(t,o)}catch(e){r.push(`${a}: ${e.message}`)}continue}const e=s[t];e?("color"===e.type?ee(o):Number.isFinite(Number(o)))||r.push(`${a}: "${t}" should be a ${"color"===e.type?"colour: three numbers, 0–1":"number"}`):r.push(`${a}: "with" sets "${t}", but there is no parameter called that`)}if(n.steps)n.steps.forEach((e,n)=>pe(e,[...t,n],r,o));else if(o)try{ge(n,Object.fromEntries(Object.entries(e.with).filter(([e])=>e in(n.graphics??{}))),1,t,100)}catch(e){r.push(`${a}: ${e.message}`)}}function fe(e,t){return e.name?`"${e.name}"`:t.length?`step ${t.map(e=>e+1).join(".")}`:"the filter"}function me(e,t={}){const r=oe(e),o=[];if(pe({filter:r,with:{},opacity:1},[],o,!1),o.length)throw new Error(o.join("\n"));const n={passes:[],credits:[],problems:o,version:300===t.version?300:100,top:r,graphics:{}};if(de({filter:r,with:{},opacity:1,skip:!1},[],{},n),o.length)throw new Error(o.join("\n"));return n.passes.length||n.passes.push(ge(oe("pixel(px, py)"),{},1,[],n.version)),{name:r.name??"",author:r.author??"",description:r.description??"",version:n.version,passes:n.passes,credits:n.credits,images:le(r),graphics:n.graphics}}function de(e,t,r,o){if(e.skip)return;const n=function(e){if(!e.space||void 0===e.color)return null;const{space:t,name:r,author:o,description:n,...a}=e,s=e=>({filter:e,with:{},opacity:1,skip:!1}),i=[];"srgb"!==t.in&&i.push(s({format:J,color:{rgb:`to${t.in}(rgb)`}}));i.push(s({...a,_space:t.in})),"srgb"!==t.out&&i.push(s({format:J,color:{rgb:`from${t.out}(rgb)`}}));const c={format:J,steps:i};for(const[e,t]of Object.entries({name:r,author:o,description:n}))t&&(c[e]=t);return c}(e.filter)??function(e){if("string"!=typeof e.color)return null;const t=/^(gaussian|blur)\((.*)\)$/s.exec(e.color.trim());if(!t)return null;let r=0;for(const e of t[2])if("("===e)r++;else if(")"===e&&--r<0)return null;if(0!==r)return null;const{color:o,...n}=e,a=e=>{const r={format:J,color:`${t[1]}${e}(${t[2]})`};return n.params&&(r.params=n.params),n.images&&(r.images=n.images),n.graphics&&(r.graphics=n.graphics),{filter:r,with:{},opacity:1,skip:!1}};return{...n,steps:[a("x"),a("y")]}}(e.filter);if(n)return e.filter===o.top&&(o.top=n),void de({...e,filter:n},t,r,o);const{filter:a}=e,s={...e.with,...r};for(const t of Object.keys(r))te(r[t])&&te(e.with[t])&&(s[t]={...e.with[t],...r[t]});if(a.name&&a!==o.top&&!o.credits.some(e=>e.name===a.name&&e.author===(a.author??""))&&o.credits.push({name:a.name,author:a.author??""}),a.color){try{o.passes.push(function(e,t){e.bind={};for(const[r,o]of Object.entries(e.graphics??{})){let n=r;for(let e=2;n in t&&JSON.stringify(t[n])!==JSON.stringify(o);e++)n=`${r}~${e}`;t[n]=o,e.bind[r]=n}return e}(ge(a,s,e.opacity,t,o.version),o.graphics))}catch(e){o.problems.push(`${fe(a,t)}: ${e.message}`)}return}const i=o.passes.length;a.steps.forEach((e,r)=>de(e,[...t,r],s,o)),e.opacity<1&&(o.passes.length-i===1?o.passes[i].opacity*=e.opacity:(o.passes[i].keepInput+=1,o.passes.push(function(e,t,r){const o=300===r,n=o?"texture":"texture2D",a=[o?"#version 300 es":"","precision highp float;","uniform sampler2D image;","uniform sampler2D base;","uniform vec2 resolution;","uniform float mz_opacity;",o?"out vec4 fragColor;":"","void main() {"," vec2 uv = gl_FragCoord.xy / resolution;",` ${o?"fragColor":"gl_FragColor"} = mix(${n}(base, uv), ${n}(image, uv), mz_opacity);`,"}"].filter(Boolean).join("\n");return{name:"blend",author:"",path:t,fragment:a,params:{},values:{},opacity:e,images:[],placements:{},graphics:{},keepInput:0,blendKept:!0}}(e.opacity,t,o.version))))}function ge(e,t,r,n,a){const s=e.params??{},i={};for(const[e,r]of Object.entries(s))i[e]=e in t?"color"===r.type?t[e].map(Number):Number(t[e]):r.default;const c={};for(const[r,o]of Object.entries(e.images??{})){const{description:e,...n}=o;c[r]={...re,...n,...te(t[r])?t[r]:{}}}const l={};for(const[r,o]of Object.entries(e.graphics??{}))l[r]=te(t[r])?C(r,{...o,...t[r]}):o,c[r]={...re,place:"stretch"},j(r,l[r]).forEach((e,t)=>{l[e]={...l[r],onlyShadow:t},c[e]={...re,place:"stretch"}});const h=function(e,t,r=null){const n=e.params??{},a={};for(const[e,t]of Object.entries(n))a[e]="color"===t.type?"vec3":"float";const s={};for(const[t,o]of Object.entries(e.images??{}))s[t]={place:r?.[t]?.place??o.place??re.place};for(const[t,o]of Object.entries(e.graphics??{})){s[t]={place:"stretch"};const e=r?Object.keys(r).filter(e=>/_shadow\d+$/.test(e)&&e.startsWith(`${t}_shadow`)):j(t,o);for(const t of e)s[t]={place:"stretch"}}return o(e.color,{version:t,uniforms:a,values:Object.keys(n),images:s,blend:!0,space:e._space??e.space?.in??"srgb"})}(e,a,c),u=Object.keys(c);return h.includes("uniform sampler2D mz_img_source;")&&u.push("source"),h.includes("uniform sampler2D mz_img_selection;")&&u.push("selection"),{name:e.name??"",author:e.author??"",path:n,color:e.color,space:e._space??"srgb",fragment:h,params:s,values:i,opacity:r,images:u,placements:c,graphics:l,keepInput:0,blendKept:!1}}function $e(e){return JSON.stringify(_e(oe(e),!0),null,2)}function ye(e){let t;try{t=JSON.parse(e)}catch{throw new Error("Not valid JSON")}return oe(t)}function we(e,t=""){return`${t}#${function(e){let t="";for(const r of(new TextEncoder).encode(e))t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}(JSON.stringify(_e(oe(e),!0)))}`}function be(e){const t=e.includes("#")?e.slice(e.lastIndexOf("#")+1):e;let r;try{r=JSON.parse(function(e){const t=atob(e.replace(/-/g,"+").replace(/_/g,"/"));return(new TextDecoder).decode(Uint8Array.from(t,e=>e.charCodeAt(0)))}(t.trim()))}catch{throw new Error("Not a filter link")}return oe(r)}function xe(e){const t=String(e??"").trim();if(!t)throw new Error("Nothing to read");if(t.startsWith("{"))return ye(t);if(!/\s/.test(t)){const e=t.includes("#")?t.slice(t.lastIndexOf("#")+1):t;if(/^[A-Za-z0-9_-]{8,}$/.test(e))try{return be(e)}catch(e){if(t.includes("#"))throw e}}return oe(t)}function _e(e,t){const r={};t&&(r.format=J);for(const t of["name","author","description"])e[t]&&(r[t]=e[t]);return e.notes&&e.notes.length&&(r.notes=e.notes),e.steps?(r.steps=e.steps.map(e=>{const t=_e(e.filter,!1),r=1===Object.keys(t).length&&"string"==typeof t.color?t.color:t,o={};return Object.keys(e.with).length&&(o.with=e.with),1!==e.opacity&&(o.opacity=e.opacity),e.skip&&(o.skip=!0),Object.keys(o).length?{filter:r,...o}:r}),r):(e.params&&(r.params=e.params),e.images&&(r.images=e.images),e.graphics&&(r.graphics=e.graphics),e.space&&(r.space=e.space.in===e.space.out?e.space.in:e.space),r.color=e.color,r)}function ke(e,t,r={}){if(e.isContextLost())throw new Error("The WebGL context is lost");const o=Ee(e,r.precision),a=n({version:t.version}),s=t.passes.map(t=>function(e,t,r,o){const n=e.createProgram();for(const[a,s]of[[e.VERTEX_SHADER,t],[e.FRAGMENT_SHADER,r]]){const t=e.createShader(a);if(e.shaderSource(t,s),e.compileShader(t),!e.getShaderParameter(t,e.COMPILE_STATUS))throw new Error(`${o||"The filter"} does not compile: ${e.getShaderInfoLog(t).trim()}`);e.attachShader(n,t)}if(e.linkProgram(n),!e.getProgramParameter(n,e.LINK_STATUS))throw new Error(`${o||"The filter"} does not link: ${e.getProgramInfoLog(n).trim()}`);return n}(e,a,t.fragment,t.name)),i=s.map(()=>new Map),c=(t,r)=>(i[t].has(r)||i[t].set(r,e.getUniformLocation(s[t],r)),i[t].get(r)),l=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,l),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),e.STATIC_DRAW);const h={texture:e.createTexture(),framebuffer:null};e.bindTexture(e.TEXTURE_2D,h.texture),ve(e);const u=new Map,p=new Map,f=e.createTexture();e.bindTexture(e.TEXTURE_2D,f),ve(e),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([255,255,255,255]));const m=e.createTexture();e.bindTexture(e.TEXTURE_2D,m),ve(e),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([0,0,0,0]));const d=[];let g=0,$=0;const y={passes:t.passes,get precision(){return o.name},setImage(t,r){if("string"!=typeof t&&(r=t,t=null),t&&"source"!==t&&null==r)return u.has(t)&&e.deleteTexture(u.get(t)),u.delete(t),p.delete(t),y;let o=h.texture;if(t&&"source"!==t&&(u.has(t)||(u.set(t,e.createTexture()),e.bindTexture(e.TEXTURE_2D,u.get(t)),ve(e)),o=u.get(t)),r&&r.data&&r.width&&r.height&&"undefined"!=typeof ImageData&&!(r instanceof ImageData)){const e=r.data,t=e instanceof Float32Array||e instanceof Float64Array,o=e instanceof Uint8ClampedArray?e:Uint8ClampedArray.from(e,t?e=>255*e:void 0);r=new ImageData(o,r.width,r.height)}return e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,r),t&&p.set(t,[r.naturalWidth||r.videoWidth||r.width||1,r.naturalHeight||r.videoHeight||r.height||1]),y},draw({t:r=0}={}){if(e.drawingBufferWidth!==g||e.drawingBufferHeight!==$){g=e.drawingBufferWidth,$=e.drawingBufferHeight;for(const t of d)e.bindTexture(e.TEXTURE_2D,t.texture),e.texImage2D(e.TEXTURE_2D,0,o.internal,g,$,0,e.RGBA,o.type,null)}let n=h;const a=[];return t.passes.forEach((i,y)=>{for(let e=0;e<i.keepInput;e++)a.push(n);const w=y===t.passes.length-1?null:function(t){let r=d.find(e=>!t.includes(e));return r||(r={texture:e.createTexture(),framebuffer:e.createFramebuffer()},e.bindTexture(e.TEXTURE_2D,r.texture),ve(e,o.filter),e.texImage2D(e.TEXTURE_2D,0,o.internal,g,$,0,e.RGBA,o.type,null),e.bindFramebuffer(e.FRAMEBUFFER,r.framebuffer),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r.texture,0),e.checkFramebufferStatus(e.FRAMEBUFFER)!==e.FRAMEBUFFER_COMPLETE&&"byte"!==o.name&&(Object.assign(o,Ee(e,"byte")),e.bindTexture(e.TEXTURE_2D,r.texture),ve(e,o.filter),e.texImage2D(e.TEXTURE_2D,0,o.internal,g,$,0,e.RGBA,o.type,null)),d.push(r)),r}([n,...a]);e.bindFramebuffer(e.FRAMEBUFFER,w?w.framebuffer:null),e.viewport(0,0,g,$);const b=s[y];e.useProgram(b);const x=e.getAttribLocation(b,"position");e.bindBuffer(e.ARRAY_BUFFER,l),e.enableVertexAttribArray(x),e.vertexAttribPointer(x,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,n.texture),e.uniform1i(c(y,"image"),0),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,i.blendKept?a[a.length-1].texture:null),i.blendKept&&e.uniform1i(c(y,"base"),1),i.images.forEach((t,r)=>{if(e.activeTexture(e.TEXTURE2+r),e.bindTexture(e.TEXTURE_2D,"source"===t?h.texture:u.get(i.bind?.[t]??t)??(i.graphics?.[t]?m:f)),e.uniform1i(c(y,`mz_img_${t}`),2+r),!i.placements[t])return;const o=p.get(i.bind?.[t]??t)??[1,1],n=i.placements[t];e.uniform2f(c(y,`mz_size_${t}`),o[0],o[1]),e.uniform4f(c(y,`mz_place_${t}`),Number(n.zoom),Number(n.x),Number(n.y),Number(n.angle))}),e.uniform2f(c(y,"resolution"),g,$),e.uniform1f(c(y,"t"),r),e.uniform1f(c(y,"mz_opacity"),i.opacity);for(const[t,r]of Object.entries(i.params)){const o=i.values[t];"color"===r.type?e.uniform3fv(c(y,t),o.map(Number)):e.uniform1f(c(y,t),Number(o))}e.drawArrays(e.TRIANGLES,0,3),i.blendKept&&a.pop(),n=w}),y},dispose(){for(const t of s)e.deleteProgram(t);e.deleteTexture(h.texture),e.deleteTexture(f),e.deleteTexture(m);for(const t of u.values())e.deleteTexture(t);for(const t of d)e.deleteTexture(t.texture),e.deleteFramebuffer(t.framebuffer);e.deleteBuffer(l)}};return y}function ve(e,t=e.LINEAR){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t)}function Ee(e,t="byte"){const r={name:"byte",internal:e.RGBA,type:e.UNSIGNED_BYTE,filter:e.LINEAR};if("half"!==t&&"float"!==t)return r;if("undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext){if(!e.getExtension("EXT_color_buffer_float"))return r;const o=e.getExtension("OES_texture_float_linear")?e.LINEAR:e.NEAREST;return"float"===t?{name:"float",internal:e.RGBA32F,type:e.FLOAT,filter:o}:{name:"half",internal:e.RGBA16F,type:e.HALF_FLOAT,filter:e.LINEAR}}if("float"===t&&e.getExtension("OES_texture_float")&&e.getExtension("WEBGL_color_buffer_float"))return{name:"float",internal:e.RGBA,type:e.FLOAT,filter:e.getExtension("OES_texture_float_linear")?e.LINEAR:e.NEAREST};const o=e.getExtension("OES_texture_half_float");return o&&e.getExtension("EXT_color_buffer_half_float")?{name:"half",internal:e.RGBA,type:o.HALF_FLOAT_OES,filter:e.getExtension("OES_texture_half_float_linear")?e.LINEAR:e.NEAREST}:r}const Me={data:new Float32Array([1,1,1,1]),width:1,height:1},Ae={data:new Float32Array([0,0,0,0]),width:1,height:1},Te={cover:0,fit:1,stretch:2,tile:3};function Oe(e){return Te[e??"cover"]??0}function je(e,t){return e-t*Math.floor(e/t)}const Se=(e,t)=>e<0?0:e>t?t:e;function Fe(e,t,r,o,n,a){const s=Math.floor(o),i=Math.floor(n),c=o-s,l=n-i,h=Se(s,t-1),u=Se(s+1,t-1),p=Se(i,r-1),f=Se(i+1,r-1),m=4*(p*t+h),d=4*(p*t+u),g=4*(f*t+h),$=4*(f*t+u);for(let t=0;t<4;t++){const r=e[m+t]+(e[d+t]-e[m+t])*c,o=e[g+t]+(e[$+t]-e[g+t])*c;a[t]=r+(o-r)*l}return a}function Re(e,t,r){const o=Math.min(Math.max(Math.ceil(e),0),t),n=[];for(let e=-o;e<=o;e++)r(e)&&n.push(e);return n}function ze(e,t,r,o,n,a,s,i,c=0,l=o){const h=new Float32Array(r*o*3),u=a.length,p=Int32Array.from(a),f=Float64Array.from(s??a.map(()=>1)),m="x"===n?r:o,d=new Int32Array(u);for(let o=c;o<l;o++)for(let a=0;a<r;a++){const s="x"===n?a:o;for(let e=0;e<u;e++){let i=s+p[e];i=i<0?0:i>=m?m-1:i,d[e]=("x"===n?o*r+i:i*r+a)*t}let c=0,l=0,g=0;for(let t=0;t<u;t++){const r=d[t],o=f[t];c+=e[r]*o,l+=e[r+1]*o,g+=e[r+2]*o}const $=3*(o*r+a);h[$]=c/i,h[$+1]=l/i,h[$+2]=g/i}return h}function Ie(e,t,r,o,n,a,s,i=0,c=o){const l=new Float32Array(r*o*3),h="x"===n?r:o,u="x"===n?o:r,p=s-a+1,f=(e,t)=>"x"===n?e*r+t:t*r+e,m=e=>e<0?0:e>=h?h-1:e,[d,g]="x"===n?[i,c]:[0,u],[$,y]="x"===n?[0,h]:[i,c];for(let r=d;r<g;r++){let o=0,n=0,i=0;for(let c=$+a;c<=$+s;c++){const a=f(r,m(c))*t;o+=e[a],n+=e[a+1],i+=e[a+2]}for(let c=$;c<y;c++){const h=3*f(r,c);l[h]=o/p,l[h+1]=n/p,l[h+2]=i/p;const u=f(r,m(c+a))*t,d=f(r,m(c+s+1))*t;o+=e[d]-e[u],n+=e[d+1]-e[u+1],i+=e[d+2]-e[u+2]}}return l}function Ne(e,t,r,o,n,a,s,i,c=0,l=o){const h=new Float32Array(r*o*3),u="x"===n?r:o;for(let o=c;o<l;o++)for(let c=0;c<r;c++){const l="x"===n?c:o;let p=s,f=s,m=s;for(let s=0;s<a.length;s++){let h=l+a[s];h=h<0?0:h>=u?u-1:h;const d=("x"===n?o*r+h:h*r+c)*t;i?(e[d]>p&&(p=e[d]),e[d+1]>f&&(f=e[d+1]),e[d+2]>m&&(m=e[d+2])):(e[d]<p&&(p=e[d]),e[d+1]<f&&(f=e[d+1]),e[d+2]<m&&(m=e[d+2]))}const d=3*(o*r+c);h[d]=p,h[d+1]=f,h[d+2]=m}return h}const Ue=(e,t,r)=>e+t*r,Be=(e,t)=>t>e?t:e,Ce=(e,t)=>t<e?t:e;function Pe(e,t,r,o=0,n=r){const a=new Float32Array(t*r*3);for(let r=o*t;r<n*t;r++)a[3*r]=e[4*r],a[3*r+1]=e[4*r+1],a[3*r+2]=e[4*r+2];return a}const Ge=(e,t,r,o)=>[Math.max(0,e-r),Math.min(o,t+r)];function De(e,t,r,o,n,a,s,i){const c=Re(a,i,e=>Math.abs(e)<=a);if(!c.length)return Pe(e,t,r,o,n);const l=c[0],h=c[c.length-1];if(1===s.length)return Ie(e,4,t,r,s[0],l,h,o,n);const[u,p]=Ge(o,n,h,r);return Ie(Ie(e,4,t,r,"x",l,h,u,p),3,t,r,"y",l,h,o,n)}function Le(e,t,r,o,n,a,s,i){if(!(a>0))return Pe(e,t,r,o,n);const c=3*a,l=Re(c,i,e=>Math.abs(e)<=c),h=l.map(e=>Math.exp(-e*e/(2*a*a))),u=h.reduce((e,t)=>e+t,0);if(1===s.length)return ze(e,4,t,r,s[0],l,h,u,o,n);const[p,f]=Ge(o,n,l[l.length-1],r);return ze(ze(e,4,t,r,"x",l,h,u,p,f),3,t,r,"y",l,h,u,o,n)}function qe(e,t,r,o,n,s,i,c){const l=Re(s,a.square,e=>Math.abs(e)<=s);if(!l.length)return new Float32Array(t*r*3).fill(i);const[h,u]=Ge(o,n,l[l.length-1],r);return Ne(Ne(e,4,t,r,"x",l,i,c,h,u),3,t,r,"y",l,i,c,o,n)}function We(e,t,r,o,n,a){const s=function(e,t,r){const o=new Float32Array(t*r);for(let n=0;n<t*r;n++)o[n]=.299*e[4*n]+.587*e[4*n+1]+.114*e[4*n+2];return o}(e,t,r),i=new Float32Array(t*r);for(let e=o;e<n;e++)for(let o=0;o<t;o++){const n=(n,a)=>s[Se(e+a,r-1)*t+Se(o+n,t-1)];i[e*t+o]=a(n)}return i}const Xe=e=>e(1,-1)+2*e(1,0)+e(1,1)-(e(-1,-1)+2*e(-1,0)+e(-1,1)),He=e=>e(-1,1)+2*e(0,1)+e(1,1)-(e(-1,-1)+2*e(0,-1)+e(1,-1)),Ke=e=>4*e(0,0)-e(-1,0)-e(1,0)-e(0,-1)-e(0,1),Ye=e=>.5+e(-1,-1)-e(1,1),Je=e=>Math.hypot(Xe(e),He(e));function Ve(e,t,r,o,n,a,s,i,c,l,h){for(let u=0;u<3;u++){let p=i,f=0;for(const i of a)for(const l of a){const a=s?s(i,l):1;p=c(p,e[4*(Se(n+l,r-1)*t+Se(o+i,t-1))+u],a),f+=a}l[u]=h?h(p,f):p}return l}function Ze(e,t,r,o,n,a,s,i,c){for(let l=0;l<3;l++){let h=0,u=0;for(const c of s){const s=i?i(c):1,p="x"===a?Se(o+c,t-1):o;h+=e[4*(("y"===a?Se(n+c,r-1):n)*t+p)+l]*s,u+=s}c[l]=h/u}return c}const Qe=(e,t,r,o,n)=>{const a=4*(o*t+r);return n[0]=e[a],n[1]=e[a+1],n[2]=e[a+2],n};const et=e=>e<.04045?e/12.92:Math.pow((e+.055)/1.055,2.4),tt=e=>(e=Math.max(e,0))<.0031308?12.92*e:1.055*Math.pow(e,1/2.4)-.055,rt=(e,t,r,o,n)=>{const a=o===e?(t-r)/n:o===t?2+(r-e)/n:4+(e-t)/n;return a/6-Math.floor(a/6)},ot=(e,t)=>{const r=Math.abs(6*(e+t-Math.floor(e+t))-3);return Math.min(Math.max(r-1,0),1)};const nt=e=>e<.008856?7.787*e+16/116:Math.cbrt(e),at=e=>e<.206893?(e-16/116)/7.787:e*e*e;var st=Object.freeze({__proto__:null,BLANK:Me,CLEAR:Ae,at:function(e,t,r){return Number(e[t][r])},at_blur:function(e,t,r,o,n,s,i){return Ve(e,t,r,o,n,Re(s,a.square,e=>Math.abs(e)<=s),null,0,Ue,i,(e,t)=>e/t)},at_blurx:function(e,t,r,o,n,s,i){return Ze(e,t,r,o,n,"x",Re(s,a.line,e=>Math.abs(e)<=s),null,i)},at_blury:function(e,t,r,o,n,s,i){return Ze(e,t,r,o,n,"y",Re(s,a.line,e=>Math.abs(e)<=s),null,i)},at_dilate:function(e,t,r,o,n,s,i){return Ve(e,t,r,o,n,Re(s,a.square,e=>Math.abs(e)<=s),null,0,Be,i)},at_erode:function(e,t,r,o,n,s,i){return Ve(e,t,r,o,n,Re(s,a.square,e=>Math.abs(e)<=s),null,1,Ce,i)},at_gaussian:function(e,t,r,o,n,s,i){if(!(s>0))return Qe(e,t,o,n,i);const c=3*s;return Ve(e,t,r,o,n,Re(c,a.square,e=>Math.abs(e)<=c),(e,t)=>Math.exp(-(e*e+t*t)/(2*s*s)),0,Ue,i,(e,t)=>e/t)},at_gaussianx:function(e,t,r,o,n,s,i){if(!(s>0))return Qe(e,t,o,n,i);const c=3*s;return Ze(e,t,r,o,n,"x",Re(c,a.line,e=>Math.abs(e)<=c),e=>Math.exp(-e*e/(2*s*s)),i)},at_gaussiany:function(e,t,r,o,n,s,i){if(!(s>0))return Qe(e,t,o,n,i);const c=3*s;return Ze(e,t,r,o,n,"y",Re(c,a.line,e=>Math.abs(e)<=c),e=>Math.exp(-e*e/(2*s*s)),i)},at_sharpen:function(e,t,r,o,n,a,s){const i=(e,o)=>4*(Se(o,r-1)*t+Se(e,t-1)),c=i(o,n),l=i(o-1,n),h=i(o+1,n),u=i(o,n-1),p=i(o,n+1);for(let t=0;t<3;t++)s[t]=e[c+t]+a*(4*e[c+t]-e[l+t]-e[h+t]-e[u+t]-e[p+t]);return s},col_fromhsl:function(e,t,r,o){const n=(1-Math.abs(2*r-1))*t;return o[0]=r-.5*n+n*ot(e,0),o[1]=r-.5*n+n*ot(e,2/3),o[2]=r-.5*n+n*ot(e,1/3),o},col_fromhsv:function(e,t,r,o){return o[0]=r*(1+(ot(e,0)-1)*t),o[1]=r*(1+(ot(e,2/3)-1)*t),o[2]=r*(1+(ot(e,1/3)-1)*t),o},col_fromlab:function(e,t,r,o){const n=(100*e+16)/116,a=n-256*(r-.5)/200,s=.95047*at(n+256*(t-.5)/500),i=at(n),c=1.08883*at(a),l=Math.min(Math.max(3.2404542*s-1.5371385*i-.4985314*c,0),1),h=Math.min(Math.max(-.969266*s+1.8760108*i+.041556*c,0),1),u=Math.min(Math.max(.0556434*s-.2040259*i+1.0572252*c,0),1);return o[0]=tt(l),o[1]=tt(h),o[2]=tt(u),o},col_fromlinear:function(e,t,r,o){return o[0]=tt(e),o[1]=tt(t),o[2]=tt(r),o},col_fromoklab:function(e,t,r,o){let n=e+.3963377774*(t-=.5)+.2158037573*(r-=.5),a=e-.1055613458*t-.0638541728*r,s=e-.0894841775*t-1.291485548*r;n*=n*n,a*=a*a,s*=s*s;const i=Math.min(Math.max(4.0767416621*n-3.3077115913*a+.2309699292*s,0),1),c=Math.min(Math.max(-1.2684380046*n+2.6097574011*a-.3413193965*s,0),1),l=Math.min(Math.max(-.0041960863*n-.7034186147*a+1.707614701*s,0),1);return o[0]=tt(i),o[1]=tt(c),o[2]=tt(l),o},col_fromycbcr:function(e,t,r,o){return t-=.5,r-=.5,o[0]=e+1.402*r,o[1]=e-.344136*t-.714136*r,o[2]=e+1.772*t,o},col_tohsl:function(e,t,r,o){const n=Math.max(e,t,r),a=Math.min(e,t,r),s=n-a,i=.5*(n+a);return o[0]=s>0?rt(e,t,r,n,s):0,o[1]=s>0?s/(1-Math.abs(2*i-1)):0,o[2]=i,o},col_tohsv:function(e,t,r,o){const n=Math.max(e,t,r),a=n-Math.min(e,t,r);return o[0]=a>0?rt(e,t,r,n,a):0,o[1]=n>0?a/n:0,o[2]=n,o},col_tolab:function(e,t,r,o){const n=et(e),a=et(t),s=et(r),i=nt((.4124564*n+.3575761*a+.1804375*s)/.95047),c=nt(.2126729*n+.7151522*a+.072175*s),l=nt((.0193339*n+.119192*a+.9503041*s)/1.08883);return o[0]=(116*c-16)/100,o[1]=.5+500*(i-c)/256,o[2]=.5+200*(c-l)/256,o},col_tolinear:function(e,t,r,o){return o[0]=et(e),o[1]=et(t),o[2]=et(r),o},col_tooklab:function(e,t,r,o){const n=et(e),a=et(t),s=et(r),i=Math.cbrt(.4122214708*n+.5363325363*a+.0514459929*s),c=Math.cbrt(.2119034982*n+.6806995451*a+.1073969566*s),l=Math.cbrt(.0883024619*n+.2817188376*a+.6299787005*s);return o[0]=.2104542553*i+.793617785*c-.0040720468*l,o[1]=.5+1.9779984951*i-2.428592205*c+.4505937099*l,o[2]=.5+.0259040371*i+.7827717662*c-.808675766*l,o},col_toycbcr:function(e,t,r,o){const n=.299*e+.587*t+.114*r;return o[0]=n,o[1]=.5+.5643*(r-n),o[2]=.5+.7132*(e-n),o},convolve:function(e,t,r,o,n,a,s,i,c,l,h,u,p,f,m){const d=(e,a)=>4*(Se(n+a,r-1)*t+Se(o+e,t-1)),g=[[a,-1,-1],[s,0,-1],[i,1,-1],[c,-1,0],[l,0,0],[h,1,0],[u,-1,1],[p,0,1],[f,1,1]];for(let t=0;t<3;t++){let r=0;for(const[o,n,a]of g)r+=o*e[d(n,a)+t];m[t]=r}return m},factorial:function(e){let t=1;for(let r=2;r<=170&&!(r>e);r++)t*=r;return t},fmod:je,gcd:function(e,t){e=Math.abs(e),t=Math.abs(t);for(let r=0;r<64&&0!==t;r++){const r=je(e,t);e=t,t=r}return e},perm:function(e,t){let r=1;for(let o=0;o<170&&!(o>=t);o++)r*=e-o;return r},picture:function(e,t,r,o,n,a,s,i,c,l,h,u,p){let f,m;0===l?f=m=Math.max(o/t,n/r):1===l?f=m=Math.min(o/t,n/r):2===l?(f=o/t,m=n/r):f=m=1,f*=a,m*=a;const d=h+.5-s*o,g=u+.5-i*n,$=Math.cos(c),y=Math.sin(c);let w=($*d+y*g)/f+.5*t,b=($*g-y*d)/m+.5*r;if(3===l)w=je(w,t),b=je(b,r);else if(w<0||b<0||w>t||b>r)return p[0]=p[1]=p[2]=p[3]=0,p;return Fe(e,t,r,w-.5,b-.5,p)},placeCode:Oe,plane_blur:function(e,t,r,o,n,s){return De(e,t,r,o,n,s,["x","y"],a.square)},plane_blurx:function(e,t,r,o,n,s){return De(e,t,r,o,n,s,["x"],a.line)},plane_blury:function(e,t,r,o,n,s){return De(e,t,r,o,n,s,["y"],a.line)},plane_dilate:function(e,t,r,o,n,a){return qe(e,t,r,o,n,a,0,!0)},plane_emboss:function(e,t,r,o,n){return We(e,t,r,o,n,Ye)},plane_erode:function(e,t,r,o,n,a){return qe(e,t,r,o,n,a,1,!1)},plane_gaussian:function(e,t,r,o,n,s){return Le(e,t,r,o,n,s,["x","y"],a.square)},plane_gaussianx:function(e,t,r,o,n,s){return Le(e,t,r,o,n,s,["x"],a.line)},plane_gaussiany:function(e,t,r,o,n,s){return Le(e,t,r,o,n,s,["y"],a.line)},plane_laplacian:function(e,t,r,o,n){return We(e,t,r,o,n,Ke)},plane_sharpen:function(e,t,r,o,n,a){const s=new Float32Array(t*r*3);for(let i=o;i<n;i++)for(let o=0;o<t;o++){const n=(e,o)=>4*(Se(o,r-1)*t+Se(e,t-1)),c=n(o,i),l=n(o-1,i),h=n(o+1,i),u=n(o,i-1),p=n(o,i+1);for(let r=0;r<3;r++)s[3*(i*t+o)+r]=e[c+r]+a*(4*e[c+r]-e[l+r]-e[h+r]-e[u+r]-e[p+r])}return s},plane_sobel:function(e,t,r,o,n){return We(e,t,r,o,n,Je)},plane_sobelx:function(e,t,r,o,n){return We(e,t,r,o,n,Xe)},plane_sobely:function(e,t,r,o,n){return We(e,t,r,o,n,He)},random:function(e,t,r,o){const n=43758.5453*Math.sin(12.9898*(e+.5)+78.233*(r-t-.5)+37.719*o);return n-Math.floor(n)},root:function(e,t){return 2===e?Math.sqrt(t):3===e?Math.sign(t)*Math.pow(Math.abs(t),1/3):Math.pow(t,1/e)},sample:Fe,sampleOrZero:function(e,t,r,o,n,a){const s=o+.5,i=n+.5;return s<0||i<0||s>t||i>r?(a[0]=a[1]=a[2]=a[3]=0,a):Fe(e,t,r,o,n,a)},scratch:function(){return new Float64Array(4)},smoothstep:function(e,t,r){const o=Math.min(Math.max((r-e)/(t-e),0),1);return o*o*(3-2*o)}});const it="\\:",ct=Object.keys(st).filter(e=>"function"==typeof st[e]),lt={r:"$r",g:"$g",b:"$b",a:"$a",x:"$x",y:"$y",px:"$px",py:"$py",w:"$w",h:"$h",t:"$t",gray:"$gray"},ht={pi:"Math.PI","π":"Math.PI",e:"Math.E",tau:"(2 * Math.PI)","τ":"(2 * Math.PI)","∞":"Infinity","-∞":"(-Infinity)"},ut={sqrt:1,abs:1,floor:1,ceil:1,ln:"log",sin:1,cos:1,tan:1,arcsin:"asin",arccos:"acos",arctan:"atan",sinh:1,cosh:1,tanh:1,arcsinh:"asinh",arccosh:"acosh",arctanh:"atanh",sign:1,exp:1,exp2:e=>`Math.pow(2, ${e})`,log2:1,expm1:e=>`(Math.exp(${e}) - 1)`,loglog:e=>`Math.log(Math.log(${e}))`,logloglog:e=>`Math.log(Math.log(Math.log(${e})))`,csc:e=>`(1 / Math.sin(${e}))`,sec:e=>`(1 / Math.cos(${e}))`,cot:e=>`(1 / Math.tan(${e}))`,fract:e=>`(${e} - Math.floor(${e}))`,radians:e=>`(${e} * 0.017453292519943295)`,degrees:e=>`(${e} * 57.29577951308232)`,inversesqrt:e=>`(1 / Math.sqrt(${e}))`,atan2:(e,t)=>`Math.atan2(${e}, ${t})`,pow:(e,t)=>`Math.pow(${e}, ${t})`,mod:(e,t)=>`(${e} - ${t} * Math.floor(${e} / ${t}))`,step:(e,t)=>`(${t} < ${e} ? 0 : 1)`,clamp:(e,t,r)=>`Math.min(Math.max(${e}, ${t}), ${r})`,mix:(e,t,r)=>`(${e} + (${t} - ${e}) * ${r})`,smoothstep:(e,t,r)=>`$h_smoothstep(${e}, ${t}, ${r})`},pt={atan2:2,pow:2,mod:2,step:2,clamp:3,mix:3,smoothstep:3},ft={blur:3,blurx:3,blury:3,gaussian:3,gaussianx:3,gaussiany:3,dilate:3,erode:3,sharpen:3,sobel:1,sobelx:1,sobely:1,laplacian:1,emboss:1},mt=(e,t)=>({kind:e,c:t}),dt=e=>mt("f",[e]),gt=e=>mt("b",[e]),$t=e=>1===e.length?dt(e[0]):mt("v",e),yt=(e,t=0)=>"b"===e.kind?`(${e.c[0]} ? 1 : 0)`:"f"===e.kind?e.c[0]:e.c[t]??e.c[0],wt=e=>"v"===e.kind?e.c.length:1;class bt extends Error{}function xt(e){if(e.blendKept)return{blend:!0,source:""};const t=e.params??{},r=new Set([...Object.keys(e.placements??{}),"source","selection"]),o=new _t(t,r,e.space??"srgb");o.graphics=new Set(Object.keys(e.graphics??{})),o.bind=e.bind??{};const n="string"==typeof e.color?{rgba:e.color}:e.color,a=(o,n)=>{const a=[...s,...Object.keys(e.placements??{})],h=[...i,...Object.keys(t)];return c(l(o,{names:a,values:h,blocks:null}),r,{whole:n})};for(const e of["rgba","rgb","r","g","b","a"]){if(!n[e])continue;let t;try{t=a(n[e],"rgba"===e)}catch(e){throw new bt(e.message)}o.channel(e,t)}const u=o.source();h(u,{variables:/^\$\w+$/,indexable:/^\$[A-Z]\w*$/,strings:!1});const p=new Function(...o.parameters(),u);return{source:u,uses:o.uses,pictures:[...o.pictureNames],run(e){p(...o.arguments(e))}}}class _t{constructor(e,t,r="srgb"){this.params=e,this.pictures=t,this.space="srgb"===r?null:r,this.pre=[],this.body=[],this.n=0,this.uses=new Set,this.pictureNames=new Set,this.perPixel=new Map,this.planes=new Map,this.scratch=0}temp(e,t=this.body){const r="$v"+this.n++;return t.push(`let ${r} = ${e};`),r}keep(e,t=this.body){return mt(e.kind,e.c.map(e=>/^[\w$.]+$|^\(?-?[\d.e+]+\)?$/.test(e)?e:this.temp(e,t)))}fail(e){throw new bt(e)}leaf(e){if("number"===e.type)return dt(`(${e.value.replace(/\.+$/,"")})`);"string"===e.type&&this.fail("a filter has no text: numbers and colours only");const t=e.value;if("t"===t&&this.uses.add("t"),lt[t])return dt(lt[t]);if("rgb"===t)return $t(["$r","$g","$b"]);if("unchanged"===t)return dt("$u");if("selected"===t)return dt(this.pictureHere("selection").c[0]);if(ht[t])return dt(ht[t]);if("true"===t||"false"===t)return gt(t);if(Object.prototype.hasOwnProperty.call(this.params,t)){const e=`$p_${t}`;return"color"===this.params[t].type?$t([`${e}_0`,`${e}_1`,`${e}_2`]):dt(e)}if(this.pictures.has(t)){const e=this.pictureHere(t);return $t(e.c.slice(0,3))}if(t.startsWith("mz_px_")&&this.pictures.has(t.slice(6)))return this.pictureHere(t.slice(6));this.fail(`unknown name "${t}"`)}pictureHere(e){if(!this.perPixel.has(e)){const t=this.sampler(e,"$px","$py");this.perPixel.set(e,this.keep(t))}return this.perPixel.get(e)}sampler(e,t,r){const o=this.scratchArray();return"source"===e?(this.uses.add("source"),this.body.push(`$h_sample($S, $w, $h, ${t}, ${r}, ${o});`)):(this.pictureNames.add(e),this.body.push(`$h_picture($Q_${e}, $qw_${e}, $qh_${e}, $w, $h, $qz_${e}, $qx_${e}, $qy_${e}, $qa_${e}, $qm_${e}, ${t}, ${r}, ${o});`)),this.space&&"selection"!==e&&this.body.push(`$h_col_to${this.space}(${o}[0], ${o}[1], ${o}[2], ${o});`),$t([0,1,2,3].map(e=>`${o}[${e}]`))}scratchArray(){const e="$T"+this.scratch++;return this.pre.push(`let ${e} = $h_scratch();`),e}value(e){return"op"===e.type?this.op(e):this.leaf(e)}op(e){const{op:t,args:r}=e,o=t.startsWith(it)?t.slice(2):null;if(null!==o)return this.call(o,r,e);const n=()=>r.map(e=>this.value(e));switch(t){case"+":case"-":case"*":case"/":{const[e,r]=n();return this.componentwise([e,r],(e,r)=>`(${e} ${t} ${r})`)}case"neg":return this.componentwise(n(),e=>`(-${e})`);case"^":return this.power(r);case"mod":return this.componentwise(n(),ut.mod);case"<":case">":case"≤":case"≥":{const[e,r]=n(),o={"≤":"<=","≥":">="}[t]??t;return gt(`(${yt(e)} ${o} ${yt(r)})`)}case"=":case"===":case"≠":case"≠=":case"≡":{const[e,r]=n(),o=Math.max(wt(e),wt(r)),a=Array.from({length:o},(t,o)=>`${yt(e,o)} === ${yt(r,o)}`).join(" && ");return gt("≠"===t||"≠="===t?`!(${a})`:`(${a})`)}case"≈":{const[e,t]=n();return gt(`(Math.abs(${yt(e)} - ${yt(t)}) < 1e-5)`)}case"&":{const[e,t]=n();return gt(`(${this.truth(e)} && ${this.truth(t)})`)}case"|":{const[e,t]=n();return gt(`(${this.truth(e)} || ${this.truth(t)})`)}case"\\xor":{const[e,t]=n();return gt(`(${this.truth(e)} !== ${this.truth(t)})`)}case"\\nand":{const[e,t]=n();return gt(`!(${this.truth(e)} && ${this.truth(t)})`)}case"\\nor":{const[e,t]=n();return gt(`!(${this.truth(e)} || ${this.truth(t)})`)}case"\\not":{const[e]=n();return gt(`!${this.truth(e)}`)}case"?:":return this.ternary(r);case"max":case"min":return this.componentwise(n(),(...e)=>`Math.${t}(${e.join(", ")})`);case"sum":return this.componentwise(n(),(...e)=>`(${e.join(" + ")})`);case"prod":return this.componentwise(n(),(...e)=>`(${e.join(" * ")})`);case"mean":return this.componentwise(n(),(...e)=>`((${e.join(" + ")}) / ${e.length})`);case"()":case"[]":case"{}":case"(]":case"[)":{const e=n().flatMap(e=>"b"===e.kind?[yt(e)]:e.c.map((t,r)=>yt(e,r)));return e.length>4&&this.fail("a colour has at most 4 values (r, g, b, a)"),$t(e)}case"!":return this.componentwise(n(),e=>`$h_factorial(${e})`);case"perm":return this.componentwise(n(),(e,t)=>`$h_perm(${e}, ${t})`);case"comb":return this.componentwise(n(),(e,t)=>`($h_perm(${e}, ${t}) / $h_factorial(${t}))`);case"gcd":return this.componentwise(n(),(...e)=>e.reduce((e,t)=>`$h_gcd(${e}, ${t})`));case"round":{const[e,t]=n();return this.componentwise([e,t],(e,t)=>`(Math.floor(${e} * Math.pow(10, ${t}) + 0.5) / Math.pow(10, ${t}))`)}case"log":{const[e,t]=n();return this.componentwise([e,t],(e,t)=>`(Math.log(${t}) / Math.log(${e}))`)}case"root":{const[e,t]=n();return this.componentwise([e,t],(e,t)=>`$h_root(${e}, ${t})`)}case"∈":case"∉":return this.membership(e);case"random":return this.random();case"_":{const[e,t]=r;if("symbol"===e.type&&("number"===t.type||"symbol"===t.type))return this.leaf({type:"symbol",value:`${e.value}_${t.value}`});break}}if(ut[t])return this.builtin(t,n());this.fail(`"${t}" isn't available in a filter`)}truth(e){return"b"===e.kind?e.c[0]:`(${yt(e)} !== 0)`}componentwise(e,t){const r=e.map(wt),o=Math.max(...r),n=new Set(r.filter(e=>e>1));n.size>1&&this.fail(`can't combine vectors of ${[...n].join(" and ")} values`);const a=Array.from({length:o},(r,o)=>t(...e.map(e=>yt(e,o))));return this.keep($t(a))}builtin(e,t){const r=ut[e];if(pt[e]&&t.length!==pt[e]&&this.fail(`${e}() takes ${pt[e]} values`),"function"==typeof r)return this.componentwise(t,r);const o=1===r?e:r;return this.componentwise(t,(...e)=>`Math.${o}(${e.join(", ")})`)}power([e,t]){const r="number"===t.type&&/^-?\d+$/.test(t.value)?Number(t.value):null,o=this.keep(this.value(e)),n=e=>this.componentwise([o],t=>Array(e).fill(t).join(" * "));return 0===r?this.componentwise([o],()=>"1"):null!==r&&r>=1&&r<=4?n(r):null!==r&&r<=-1&&r>=-4?this.componentwise([n(-r)],e=>`(1 / ${e})`):"symbol"===e.type&&"e"===e.value?this.componentwise([this.value(t)],e=>`Math.exp(${e})`):"number"===e.type&&"2"===e.value?this.componentwise([this.value(t)],e=>`Math.pow(2, ${e})`):this.componentwise([o,this.value(t)],(e,t)=>`Math.pow(${e}, ${t})`)}ternary([e,t,r]){const o=this.truth(this.value(e)),n=e=>"symbol"===e.type&&"unchanged"===e.value;let a=n(t)?null:this.value(t),s=n(r)?null:this.value(r);const i=e=>"b"===e.kind?gt("($u > 0.5)"):"f"===e.kind?dt("$u"):$t(["$k0","$k1","$k2","$k3"].slice(0,4===e.c.length?4:3));if(!a&&!s)return dt("$u");if(a||(a=i(s)),s||(s=i(a)),"b"===a.kind&&"b"===s.kind)return gt(this.temp(`(${o} ? ${a.c[0]} : ${s.c[0]})`));const c=Math.max(wt(a),wt(s)),l=Array.from({length:c},(e,t)=>this.temp(`(${o} ? ${yt(a,t)} : ${yt(s,t)})`));return $t(l)}membership(e){const[t,r]=e.args,o=yt(this.value(t)),n="∉"===e.op;let a;if("op"===r.type&&["()","[]","(]","[)"].includes(r.op)&&2===r.args.length){const[e,t]=r.args.map(e=>yt(this.value(e)));a=`(${o} ${"["===r.op[0]?">=":">"} ${e} && ${o} ${"]"===r.op[1]?"<=":"<"} ${t})`}else"op"===r.type&&"{}"===r.op?a=`(${r.args.map(e=>`${o} === ${yt(this.value(e))}`).join(" || ")})`:"symbol"===r.type&&["ℝ","ℤ","ℕ"].includes(r.value)?a={"ℝ":`Number.isFinite(${o})`,"ℤ":`Number.isInteger(${o})`,"ℕ":`(Number.isInteger(${o}) && ${o} > 0)`}[r.value]:this.fail("∈ needs an interval [a, b], a set {…}, ℝ, ℤ or ℕ");return gt(n?`!${a}`:a)}random(){return this.uses.add("random"),dt(this.temp("$h_random($px, $py, $h, ++$seed)"))}call(e,t,r){const o=()=>t.map(e=>this.value(e));if(e.startsWith("mz_sample_")){const t=e.slice(10),[r,n]=o(),[a,s]=n?[yt(r),yt(n)]:[yt(r,0),yt(r,1)];if("image"===t){const e=this.scratchArray();return this.body.push(`$h_sampleOrZero($I, $w, $h, ${a}, ${s}, ${e});`),this.keep($t([0,1,2,3].map(t=>`${e}[${t}]`)))}return this.pictures.has(t)||this.fail(`unknown picture "${t}"`),this.keep(this.sampler(t,a,s))}if(e.startsWith("mz_at_")){const t=e.slice(6),[r,n]=o(),[a,s]=n?[yt(r),yt(n)]:[yt(r,0),yt(r,1)];if("image"===t){const e=this.scratchArray();return this.body.push(`$h_sampleOrZero($I, $w, $h, ${a}, ${s}, ${e});`),$t([0,1,2].map(t=>`${e}[${t}]`))}return this.pictures.has(t)||this.fail(`unknown picture "${t}"`),this.keep($t(this.sampler(t,a,s).c.slice(0,3)))}if(e.startsWith("mz_width_")||e.startsWith("mz_height_")){const t=e.replace(/^mz_(width|height)_/,"");return this.pictureNames.add(t),dt(e.startsWith("mz_width_")?`$qw_${t}`:`$qh_${t}`)}switch(e){case"pixel":{const[e,t]=o().map(e=>yt(e)),r=this.scratchArray();return this.body.push(`$h_sample($I, $w, $h, ${e}, ${t}, ${r});`),this.keep($t([0,1,2,3].map(e=>`${r}[${e}]`)))}case"red":case"green":case"blue":case"alpha":case"luma":{let r;2===t.length?r=this.call("pixel",t):1===t.length?r=this.value(t[0]):this.fail(`${e}() takes a colour, or a position px, py`);const o={red:0,green:1,blue:2,alpha:3}[e];return"luma"===e?dt(`(${yt(r,0)} * 0.299 + ${yt(r,1)} * 0.587 + ${yt(r,2)} * 0.114)`):"alpha"===e&&3===wt(r)?dt("1"):dt(yt(r,o))}case"length":{const[e]=o();return dt(`Math.sqrt(${e.c.map((t,r)=>`${yt(e,r)} * ${yt(e,r)}`).join(" + ")})`)}case"distance":{const[e,t]=o(),r=this.componentwise([e,t],(e,t)=>`(${e} - ${t})`);return dt(`Math.sqrt(${r.c.map(e=>`${e} * ${e}`).join(" + ")})`)}case"dot":{const[e,t]=o(),r=Math.max(wt(e),wt(t));return dt(`(${Array.from({length:r},(r,o)=>`${yt(e,o)} * ${yt(t,o)}`).join(" + ")})`)}case"normalize":{const[e]=o(),t=this.temp(`Math.sqrt(${e.c.map((t,r)=>`${yt(e,r)} * ${yt(e,r)}`).join(" + ")})`);return this.componentwise([e],e=>`(${e} / ${t})`)}case"cross":{const[e,t]=o();3===wt(e)&&3===wt(t)||this.fail("cross() takes two colours (3 values each)");const[r,n,a]=e.c,[s,i,c]=t.c;return this.keep($t([`(${n} * ${c} - ${a} * ${i})`,`(${a} * ${s} - ${r} * ${c})`,`(${r} * ${i} - ${n} * ${s})`]))}case"convolve":{const e=o().map(e=>yt(e));9!==e.length&&this.fail("convolve() takes 9 numbers: the 3×3 kernel, row by row");const t=this.scratchArray();return this.body.push(`$h_convolve($I, $w, $h, $px, $py, ${e.join(", ")}, ${t});`),$t([0,1,2].map(e=>`${t}[${e}]`))}case"mz_zoom":case"mz_shift":case"mz_rotate":case"mz_crop":case"mz_tile":case"mz_flipx":case"mz_flipy":return this.geometry(e.slice(3),o().map(e=>yt(e)));case"tolinear":case"fromlinear":case"tohsv":case"fromhsv":case"tohsl":case"fromhsl":case"tolab":case"fromlab":case"tooklab":case"fromoklab":case"toycbcr":case"fromycbcr":{const t=o(),r=3===t.length?t.map(e=>yt(e)):[0,1,2].map(e=>yt(t[0],e));1!==t.length&&3!==t.length&&this.fail(`${e}() takes a colour`);const n=this.scratchArray();return this.body.push(`$h_col_${e}(${r.join(", ")}, ${n});`),this.keep($t([0,1,2].map(e=>`${n}[${e}]`)))}case"random":return this.random();case"exp":case"exp2":case"log2":case"sign":case"fract":case"radians":case"degrees":case"inversesqrt":case"pow":case"mod":case"step":case"clamp":case"mix":case"smoothstep":case"abs":case"floor":case"ceil":case"sqrt":case"sin":case"cos":case"tan":return this.builtin(e,o());case"asin":return this.builtin("arcsin",o());case"acos":return this.builtin("arccos",o());case"atan":return 2===t.length?this.builtin("atan2",o()):this.builtin("arctan",o());case"log":return this.builtin("ln",o());case"max":case"min":return this.componentwise(o(),(...t)=>`Math.${e}(${t.join(", ")})`)}if(ft[e])return this.neighbourhood(e,t);this.fail(`unknown function "${e}"`)}geometry(e,t){const r=(e,t)=>this.keep($t([e,t]));switch(e){case"zoom":{const[e,o="0.5",n="0.5"]=t,a=r(`(${o} * $w - 0.5)`,`(${n} * $h - 0.5)`);return r(`(${a.c[0]} + ($px - ${a.c[0]}) / ${e})`,`(${a.c[1]} + ($py - ${a.c[1]}) / ${e})`)}case"shift":{const[e,o]=t;return r(`($h_fmod($px - ${e} + 0.5, $w) - 0.5)`,`($h_fmod($py - ${o} + 0.5, $h) - 0.5)`)}case"rotate":{const[e,o="0.5",n="0.5"]=t,a=r(`(${o} * $w - 0.5)`,`(${n} * $h - 0.5)`),s=r(`($px - ${a.c[0]})`,`($py - ${a.c[1]})`),i=this.keep($t([`Math.cos(${e})`,`Math.sin(${e})`]));return r(`(${a.c[0]} + ${i.c[0]} * ${s.c[0]} + ${i.c[1]} * ${s.c[1]})`,`(${a.c[1]} + ${i.c[0]} * ${s.c[1]} - ${i.c[1]} * ${s.c[0]})`)}case"crop":{const[e,o,n,a]=t;return r(`((${e} + (${n} - ${e}) * ($px + 0.5) / $w) * $w - 0.5)`,`((${o} + (${a} - ${o}) * ($py + 0.5) / $h) * $h - 0.5)`)}case"tile":{const[e,o=e]=t;return r(`($h_fmod(($px + 0.5) * ${e}, $w) - 0.5)`,`($h_fmod(($py + 0.5) * ${o}, $h) - 0.5)`)}case"flipx":return r("($w - 1 - $px)","$py");case"flipy":return r("$px","($h - 1 - $py)")}this.fail(`unknown geometry ${e}`)}neighbourhood(e,t){const r=ft[e];if(t.every(e=>this.isUniform(e))){const o=t.map(e=>yt(this.uniformValue(e))),n=`${e}(${o.join(",")})`;if(!this.planes.has(n)){const t=`$N${this.planes.size}`;this.pre.push(`let ${t} = $h_plane_${e}($I, $w, $h, $y0, $y1${o.map(e=>`, ${e}`).join("")});`),this.planes.set(n,t)}const a=this.planes.get(n);return 3===r?$t([0,1,2].map(e=>`${a}[$j3 + ${e}]`)):dt(`${a}[$j]`)}const o=t.map(e=>yt(this.value(e)));if(1===r)return dt(this.temp(`$h_at_${e}($I, $w, $h, $px, $py${o.map(e=>`, ${e}`).join("")})`));const n=this.scratchArray();return this.body.push(`$h_at_${e}($I, $w, $h, $px, $py${o.map(e=>`, ${e}`).join("")}, ${n});`),$t([0,1,2].map(e=>`${n}[${e}]`))}isUniform(e){return"number"===e.type||("symbol"===e.type?["w","h","t"].includes(e.value)||Boolean(ht[e.value])||Object.prototype.hasOwnProperty.call(this.params,e.value)&&"color"!==this.params[e.value].type:"op"===e.type&&!e.op.startsWith(it)&&"random"!==e.op&&e.args.every(e=>this.isUniform(e)))}uniformValue(e){const t=this.body;this.body=this.pre;try{return this.value(e)}finally{this.body=t}}channel(e,t){const r="rgba"===e||"rgb"===e?"$gray":`$c${"rgba".indexOf(e)}`;this.body.push(`$u = ${r}; $k0 = $c0; $k1 = $c1; $k2 = $c2; $k3 = $c3;`);const o=this.value(t),n=wt(o),a=e=>yt(o,e);if("rgba"===e){2===n&&this.fail("a colour is one number (grey), three (r, g, b) or four (r, g, b, a) — not two");const e=1===n?[a(0),a(0),a(0),"1"]:3===n?[a(0),a(1),a(2),"1"]:[0,1,2,3].map(a);this.body.push(`$c0 = ${e[0]}; $c1 = ${e[1]}; $c2 = ${e[2]}; $c3 = ${e[3]};`)}else if("rgb"===e){2===n&&this.fail("a colour is one number (grey), three (r, g, b) or four — not two");const e=1===n?[a(0),a(0),a(0)]:[a(0),a(1),a(2)];this.body.push(`$c0 = ${e[0]}; $c1 = ${e[1]}; $c2 = ${e[2]};`)}else{const t="rgba".indexOf(e),r=1===n?a(0):3===n&&"a"===e?"1":a(t);this.body.push(`$c${t} = ${r};`)}}parameters(){return["$I","$O","$S","$w","$h","$t","$P","$op","$y0","$y1",...[...this.pictureNames].flatMap(e=>[`$Q_${e}`,`$qw_${e}`,`$qh_${e}`,`$qz_${e}`,`$qx_${e}`,`$qy_${e}`,`$qa_${e}`,`$qm_${e}`]),...ct.map(e=>`$h_${e}`)]}arguments(e){const t=[...this.pictureNames];return[e.input,e.output,e.source,e.width,e.height,e.t,e.params,e.opacity,e.y0??0,e.y1??e.height,...t.flatMap(t=>{const r=e.pictures[this.bind?.[t]??t]??(this.graphics?.has(t)?Ae:Me),o=e.placements[t]??{};return[r.data,r.width,r.height,Number(o.zoom??1),Number(o.x??.5),Number(o.y??.5),Number(o.angle??0),Oe(o.place)]}),...ct.map(e=>st[e])]}source(){return[...Object.entries(this.params).map(([e,t],r)=>"color"===t.type?`let $p_${e}_0 = $P[${r}][0], $p_${e}_1 = $P[${r}][1], $p_${e}_2 = $P[${r}][2];`:`let $p_${e} = $P[${r}];`).map(e=>e.replace(/\$P\[(\d+)\]\[(\d)\]/g,"$h_at($P, $1, $2)")),"let $u = 0, $k0 = 0, $k1 = 0, $k2 = 0, $k3 = 0, $seed = 0, $CS = $h_scratch();",...this.pre,"for (let $py = $y0; $py < $y1; $py++) {"," for (let $px = 0; $px < $w; $px++) {"," let $j = $py * $w + $px, $j3 = $j * 3, $j4 = $j * 4;"," let $r = $I[$j4], $g = $I[$j4 + 1], $b = $I[$j4 + 2], $a = $I[$j4 + 3];"," let $c0 = $r, $c1 = $g, $c2 = $b, $c3 = $a;"," let $x = ($px + 0.5) / $w, $y = ($py + 0.5) / $h;",this.space?` $h_col_from${this.space}($r, $g, $b, $CS); let $gray = $CS[0] * 0.299 + $CS[1] * 0.587 + $CS[2] * 0.114;`:" let $gray = $r * 0.299 + $g * 0.587 + $b * 0.114;"," $seed = $t;",...this.body.map(e=>` ${e}`)," $O[$j4] = $r + ($c0 - $r) * $op;"," $O[$j4 + 1] = $g + ($c1 - $g) * $op;"," $O[$j4 + 2] = $b + ($c2 - $b) * $op;"," $O[$j4 + 3] = $a + ($c3 - $a) * $op;"," }","}"].join("\n")}}function kt(e,t={}){const r="float"===t.precision||"half"===t.precision?"float":"byte",o=e.passes.map(e=>xt(e)),n={};let a=null;const s=t.parallelFrom??25e4,i=void 0===t.workers||"auto"===t.workers?function(){const e="undefined"!=typeof navigator&&navigator.hardwareConcurrency?navigator.hardwareConcurrency:4;return Math.max(0,Math.min(8,e-1))}():Number(t.workers);let c=null,l=new Map;const h={passes:e.passes,get precision(){return r},sources:o.map(e=>e.source),setImage(e,t){"string"!=typeof e&&(t=e,e=null);const r=Et(t);return e&&"source"!==e?n[e]=r:a=r,h},draw({t:t=0,canvas:s=null}={}){if(!a)throw new Error("setImage() first");const{width:i,height:c}=a,l=i*c*4;let h=a.data;const u=[];e.passes.forEach((e,s)=>{for(let t=0;t<e.keepInput;t++)u.push(h);const p=new Float32Array(l);if(e.blendKept){const t=u.pop(),r=e.opacity;for(let e=0;e<l;e++)p[e]=t[e]+(h[e]-t[e])*r}else o[s].run({input:h,output:p,source:a.data,width:i,height:c,t:t,params:Object.keys(e.params??{}).map(t=>e.values[t]),opacity:e.opacity,pictures:n,placements:e.placements??{}});"byte"===r&&vt(p),h=p});const p=new Uint8ClampedArray(l);for(let e=0;e<l;e++){const t=h[e];p[e]=t>0?t<1?Math.round(255*t):255:0}const f={data:p,width:i,height:c};return s&&(s.width=i,s.height=c,s.getContext("2d").putImageData(new ImageData(p,i,c),0,0)),f},async drawAsync({t:o=0,canvas:u=null}={}){if(!a)throw new Error("setImage() first");const{width:p,height:f}=a;if(i<2||p*f<s)return h.draw({t:o,canvas:u});if(null===c&&(c=await async function(e,t,r){const o=new URL(r??"./cpu-worker.js",import.meta.url);let n,a=()=>{};if("undefined"!=typeof Worker&&"undefined"!=typeof window){const e=o.origin===location.origin?o:URL.createObjectURL(new Blob([`import ${JSON.stringify(o.href)};`],{type:"text/javascript"}));e!==o&&(a=()=>URL.revokeObjectURL(e)),n=()=>{const t=new Worker(e,{type:"module"});return{send:e=>t.postMessage(e),on:e=>{t.onmessage=t=>e(t.data),t.onerror=t=>e({id:-1,ok:!1,error:t.message})},close:()=>t.terminate()}}}else try{const{Worker:e}=await(import("node:worker_threads"));n=()=>{const t=new e(o);return{send:e=>t.postMessage(e),on:e=>{t.on("message",e),t.on("error",t=>e({id:-1,ok:!1,error:t.message}))},close:()=>t.terminate()}}}catch{return null}const s=Array.from({length:e},n);let i=1;const c=s.map(()=>new Map);s.forEach((e,t)=>e.on(e=>{if(-1===e.id){for(const[,r]of c[t])r.reject(new Error(e.error));return void c[t].clear()}const r=c[t].get(e.id);r&&(c[t].delete(e.id),e.ok?r.resolve(e):r.reject(new Error(e.error)))}));const l=(e,t)=>new Promise((r,o)=>{const n=i++;c[e].set(n,{resolve:r,reject:o}),s[e].send({...t,id:n})}),h={size:e,shared:At(),ask:l,broadcast:e=>Promise.all(s.map((t,r)=>l(r,e))),close:()=>s.forEach(e=>e.close())};try{await h.broadcast({type:"init",passes:t.map(({fragment:e,...t})=>t)})}catch(e){throw h.close(),e}finally{a()}return h}(i,e.passes,t.workerUrl).catch(()=>!1)),!c)return h.draw({t:o,canvas:u});const m=p*f*4,d=()=>c.shared?new Float32Array(new SharedArrayBuffer(4*m)):new Float32Array(m);for(const[e,t]of[["source",a],...Object.entries(n)])l.get(e)!==t&&(await c.broadcast({type:"picture",name:e,picture:c.shared?Tt(t):t}),l.set(e,t));let g=c.shared?Tt(a).data:a.data;const $=[];for(let t=0;t<e.passes.length;t++){const n=e.passes[t];for(let e=0;e<n.keepInput;e++)$.push(g);const a=d();if(n.blendKept){const e=$.pop();for(let t=0;t<m;t++)a[t]=e[t]+(g[t]-e[t])*n.opacity;"byte"===r&&vt(a)}else{const e=Object.keys(n.params??{}).map(e=>n.values[e]),s=Mt(f,c.size),i=await Promise.all(s.map(([s,i],l)=>c.ask(l,{type:"run",pass:t,input:g,output:c.shared?a:null,width:p,height:f,t:o,params:e,opacity:n.opacity,placements:n.placements??{},y0:s,y1:i,quantize:"byte"===r})));c.shared||i.forEach((e,t)=>a.set(e.band,s[t][0]*p*4))}g=a}const y=new Uint8ClampedArray(m);for(let e=0;e<m;e++){const t=g[e];y[e]=t>0?t<1?Math.round(255*t):255:0}const w={data:y,width:p,height:f};return u&&(u.width=p,u.height=f,u.getContext("2d").putImageData(new ImageData(y,p,f),0,0)),w},get workers(){return c?c.size:0},dispose(){a=null;for(const e of Object.keys(n))delete n[e];c&&c.close(),c=null,l=new Map}};return h}function vt(e){for(let t=0;t<e.length;t++){const r=e[t];e[t]=r>0?r<1?Math.round(255*r)/255:1:0}}function Et(e){if(e&&e.data&&e.width&&e.height){const t=e.data,r=t instanceof Float32Array||t instanceof Float64Array?1:1/255,o=new Float32Array(e.width*e.height*4);for(let e=0;e<o.length;e++)o[e]=t[e]*r;return{data:o,width:e.width,height:e.height}}if("undefined"!=typeof document||"undefined"!=typeof OffscreenCanvas){const t=e.naturalWidth||e.videoWidth||e.width,r=e.naturalHeight||e.videoHeight||e.height;if(!t||!r)throw new Error("setImage: the picture has no size yet (not loaded?)");const o=("undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(t,r):Object.assign(document.createElement("canvas"),{width:t,height:r})).getContext("2d",{willReadFrequently:!0});return o.drawImage(e,0,0,t,r),Et(o.getImageData(0,0,t,r))}throw new Error("setImage: give ImageData or { data, width, height }")}function Mt(e,t){const r=[];for(let o=0;o<t;o++){const n=Math.floor(e*o/t),a=Math.floor(e*(o+1)/t);a>n&&r.push([n,a])}return r}const At=()=>"undefined"!=typeof SharedArrayBuffer&&("undefined"==typeof crossOriginIsolated||!0===crossOriginIsolated);function Tt(e){if(e.data.buffer instanceof(globalThis.SharedArrayBuffer??Object))return e;const t=new Float32Array(new SharedArrayBuffer(e.data.byteLength));return t.set(e.data),e.shared??={data:t,width:e.width,height:e.height},e.shared}function Ot({webgl:e=!1,prefer:t="auto"}={}){return"cpu"===t?{engine:"cpu",reason:"asked for the CPU"}:e?{engine:"gpu",reason:"gpu"===t?"asked for the GPU":"WebGL is here"}:{engine:"cpu",reason:"no WebGL here"}}function jt(e,t={}){const r=Ot({webgl:Boolean(t.gl),prefer:t.prefer});if("gpu"===r.engine)try{return{runner:ke(t.gl,e,{precision:t.precision}),...r}}catch(r){if("gpu"===t.prefer)throw r;return{runner:kt(e,t),engine:"cpu",reason:`the GPU refused the shader (${r.message.split("\n")[0]})`}}return{runner:kt(e,t),...r}}const St=[{name:"Wave",group:"Shape & motion",description:"Rows slide back and forth as t advances",params:{amplitude:{default:8,min:0,max:40},wavelength:{default:10,min:1,max:60},speed:{default:5,min:1,max:30}},color:"pixel(px + amplitude sin(py / wavelength + t / speed), py)"},{name:"Invert",group:"Colour & tone",color:"(1 - r, 1 - g, 1 - b)"},{name:"Grayscale",group:"Colour & tone",color:"gray"},{name:"Threshold",group:"Colour & tone",params:{cutoff:.5},color:"if gray > cutoff then 1 else 0"},{name:"Posterize",group:"Colour & tone",params:{levels:{default:4,min:2,max:16,step:1}},color:"min(floor(rgb * levels) / (levels - 1), 1)"},{name:"Brightness & contrast",group:"Colour & tone",params:{brightness:{default:0,min:-.5,max:.5},contrast:{default:1,min:0,max:3}},color:"(rgb - 0.5) contrast + 0.5 + brightness"},{name:"Tint",group:"Colour & tone",params:{tint:[1,.85,.7]},color:"rgb * tint"},{name:"Sepia",group:"Colour & tone",color:"(0.393r + 0.769g + 0.189b, 0.349r + 0.686g + 0.168b, 0.272r + 0.534g + 0.131b)"},{name:"Colour circle",group:"Colour & tone",description:"Black and white, except a soft circle that keeps its colour",params:{across:{default:.5,min:0,max:1,label:"where, across"},down:{default:.5,min:0,max:1,label:"where, down"},radius:{default:.3,min:0,max:1},softness:{default:.08,min:0,max:.5}},notes:["The colour stays inside a circle and fades to grey over the softness. Sizes are parts of the picture's shorter side, so it stays round.",{param:"across"},{param:"down"},{param:"radius"},{param:"softness"}],color:"mix((gray, gray, gray), rgb, 1 - smoothstep(radius, radius + softness, distance((px, py), (across w, down h)) / min(w, h)))"},{name:"Vignette",group:"Colour & tone",params:{strength:{default:1.6,min:0,max:4}},color:"rgb * (1 - strength ((x - 0.5)^2 + (y - 0.5)^2))"},{name:"Sobel edges",group:"Blur & edges",description:"How fast the brightness changes",params:{gain:{default:2,min:.2,max:10}},color:"gain sobel()"},{name:"Edge map",group:"Blur & edges",description:"White where an edge is stronger than the cutoff",params:{cutoff:{default:.3,min:0,max:2}},color:"if sobel() > cutoff then 1 else 0"},{name:"Outline",group:"Blur & edges",description:"Ink lines over the colour",params:{gain:{default:3,min:0,max:10}},color:"rgb (1 - gain sobel())"},{name:"Box blur",group:"Blur & edges",params:{radius:{default:2,min:0,max:8,step:1}},color:"blur(radius)"},{name:"Gaussian blur",group:"Blur & edges",description:"Computed in two passes, across then down, so it can be wide",params:{sigma:{default:3,min:0,max:8}},color:"gaussian(sigma)"},{name:"Canny edges",group:"Blur & edges",description:"Thin, clean edge lines: smooth, gradient, thinning, two thresholds, hysteresis — a chain",steps:[{params:{sigma:{default:1.4,min:.5,max:4}},color:"gaussian(sigma)"},{color:"(min(sobel() / 4, 1), floor(fract((atan2(sobely(), sobelx()) + π/8) / π) 4) / 4, 0)"},{color:"if green(px, py) < 0.125 then (if r >= red(px - 1, py) & r >= red(px + 1, py) then r else 0) else if green(px, py) < 0.375 then (if r >= red(px + 1, py + 1) & r >= red(px - 1, py - 1) then r else 0) else if green(px, py) < 0.625 then (if r >= red(px, py - 1) & r >= red(px, py + 1) then r else 0) else (if r >= red(px - 1, py + 1) & r >= red(px + 1, py - 1) then r else 0)"},{params:{low:{default:.08,min:0,max:.5},high:{default:.2,min:0,max:1}},color:"if r > high then 1 else if r > low then 0.5 else 0"},"if r > 0.9 then 1 else if r > 0.4 then (if red(dilate(1)) > 0.9 then 1 else 0.5) else 0","if r > 0.9 then 1 else if r > 0.4 then (if red(dilate(1)) > 0.9 then 1 else 0.5) else 0","if r > 0.9 then 1 else if r > 0.4 then (if red(dilate(1)) > 0.9 then 1 else 0.5) else 0","if r > 0.9 then 1 else 0"]},{name:"Sharpen",group:"Blur & edges",params:{amount:{default:.6,min:0,max:3}},color:"sharpen(amount)"},{name:"Unsharp mask",group:"Blur & edges",description:"The picture plus what a blur removes",params:{amount:{default:1.5,min:0,max:5},sigma:{default:2,min:.5,max:4}},color:"rgb + amount (rgb - gaussian(sigma))"},{name:"Bloom",group:"Blur & edges",description:"Bright parts glow",params:{amount:{default:.8,min:0,max:3},sigma:{default:3,min:.5,max:4},cutoff:{default:.6,min:0,max:1}},color:"rgb + amount max(gaussian(sigma) - cutoff, 0)"},{name:"Emboss",group:"Blur & edges",color:"emboss()"},{name:"Dilate",group:"Blur & edges",description:"Light areas grow",params:{radius:{default:2,min:0,max:8,step:1}},color:"dilate(radius)"},{name:"Erode",group:"Blur & edges",description:"Dark areas grow",params:{radius:{default:2,min:0,max:8,step:1}},color:"erode(radius)"},{name:"3×3 kernel",group:"Blur & edges",description:"Your own convolution; the default is a sharpen",params:{k1:{default:0,min:-8,max:8},k2:{default:-1,min:-8,max:8},k3:{default:0,min:-8,max:8},k4:{default:-1,min:-8,max:8},k5:{default:5,min:-8,max:8},k6:{default:-1,min:-8,max:8},k7:{default:0,min:-8,max:8},k8:{default:-1,min:-8,max:8},k9:{default:0,min:-8,max:8}},color:"convolve(k1, k2, k3, k4, k5, k6, k7, k8, k9)"},{name:"Pixelate",group:"Shape & motion",params:{size:{default:8,min:1,max:32,step:1}},color:"pixel(floor(px / size) size, floor(py / size) size)"},{name:"Mirror",group:"Shape & motion",color:"pixel(w - px, py)"},{name:"Scanlines",group:"Shape & motion",params:{period:{default:4,min:2,max:16,step:1}},color:"if py mod period < period / 2 then rgb else rgb * 0.6"},{name:"Pulse",group:"Shape & motion",description:"Brightness breathes with t",params:{speed:{default:6,min:1,max:30},depth:{default:.25,min:0,max:1}},color:"rgb (1 - depth + depth sin(t / speed))"},{name:"Chroma key",group:"Colour & tone",description:"Replaces one colour with another",params:{key:[.22,.71,.29],tolerance:{default:.35,min:0,max:1},background:[.1,.1,.4]},color:"if distance(rgb, key) < tolerance then background else rgb"},{name:"Through a mask",group:"Other pictures",description:"Put this last: the steps above show only where the mask is light",images:{mask:{description:"light where the effect shows"}},color:"mix(source, rgb, luma(mask))"},{name:"Mix",group:"Other pictures",description:"Fade towards another picture",images:["overlay"],params:{amount:.5},color:"mix(rgb, overlay, amount)"},{name:"Masked mix",group:"Other pictures",images:{overlay:{},mask:{description:"light where the overlay shows"}},color:"mix(rgb, overlay, luma(mask))"},{name:"Multiply",group:"Other pictures",images:["overlay"],color:"rgb * overlay"},{name:"Screen",group:"Other pictures",images:["overlay"],color:"1 - (1 - rgb)(1 - overlay)"},{name:"Overlay blend",group:"Other pictures",images:["overlay"],color:"if gray < 0.5 then 2 rgb overlay else 1 - 2 (1 - rgb)(1 - overlay)"},{name:"Difference",group:"Other pictures",images:["overlay"],color:"abs(rgb - overlay)"},{name:"Alpha over",group:"Other pictures",description:"A picture with transparency laid on top",images:["overlay"],color:"mix(rgb, overlay, alpha(overlay))"},{name:"Chroma key onto a picture",group:"Other pictures",images:{background:{}},params:{key:[.22,.71,.29],tolerance:{default:.35,min:0,max:1}},color:"if distance(rgb, key) < tolerance then background else rgb"},{name:"Only inside the selection",group:"Other pictures",description:"Put this last: the steps above show only inside what you selected on the picture (everywhere, without a selection)",color:"mix(source, rgb, selected)"},{name:"Only outside the selection",group:"Other pictures",description:"Put this last: the steps above show only outside what you selected",color:"mix(rgb, source, selected)"},{name:"Caption",group:"Text & shapes",description:"Words along the bottom, with a soft shadow; change them under the step",graphics:{title:{text:"Your caption here",y:.88}},color:"mix(rgb, title, alpha(title))"},{name:"Poster title",group:"Text & shapes",description:"Big outlined letters across the top",graphics:{title:{text:"BIG TITLE",font:"Impact, Haettenschweiler, sans-serif",weight:"normal",size:.16,y:.14,outline:{color:"#000000",width:.08},shadow:null}},color:"mix(rgb, title, alpha(title))"},{name:"Gradient text",group:"Text & shapes",description:"The letters coloured by maths: a sunset from left to right",graphics:{title:{text:"Golden hour",font:"Georgia, serif",size:.13,y:.5,shadow:{color:"rgba(0,0,0,0.5)",blur:.2,dx:0,dy:.05}}},color:"mix(rgb, mix((1, 0.35, 0.3), (1, 0.85, 0.25), x), alpha(title))"},{name:"Neon sign",group:"Text & shapes",description:"White letters with a coloured glow",graphics:{title:{text:"OPEN",font:"Trebuchet MS, sans-serif",size:.18,y:.5,shadow:{color:"#00e5ff",blur:.45,dx:0,dy:0}}},color:"mix(rgb * 0.6, title, alpha(title))"},{name:"Layered shadow",group:"Text & shapes",description:"Two shadow layers, each with its own filter: a soft glow that darkens and breathes with t, and a hard offset coloured by a gradient",graphics:{title:{text:"LAYERS",font:"Impact, Haettenschweiler, sans-serif",weight:"normal",size:.17,y:.5,shadow:null,shadows:[{color:"#000000",blur:.7,dx:0,dy:.08},{color:"#000000",blur:0,dx:.07,dy:.07}]}},color:"mix(mix(mix(rgb, rgb * 0.25, alpha(title_shadow1) (0.7 + 0.3 sin(t / 10))), mix((1, 0.2, 0.6), (0.2, 0.6, 1), x), alpha(title_shadow2)), title, alpha(title))"},{name:"Ink brush",group:"Brushes",description:'Paint in a colour; draw on the picture with "draw" under the step',graphics:{brush:{type:"strokes",brush:"round",size:.025}},params:{ink:[.95,.2,.25]},color:"mix(rgb, ink, alpha(brush))"},{name:"Blur brush",group:"Brushes",description:"Paint a blur in — stronger every time a stroke goes over the same place",graphics:{brush:{type:"strokes",brush:"soft",size:.08}},color:"mix(rgb, gaussian(2 + 3 min(4 green(brush), 3)), alpha(brush))"},{name:"Darken brush",group:"Brushes",description:"Each pass darkens a little more, like layers of a wash",graphics:{brush:{type:"strokes",brush:"soft",size:.07,flow:.7}},color:"rgb (1 - 0.22 min(4 green(brush), 4))"},{name:"Colour reveal brush",group:"Brushes",description:"The picture starts grey; the brush paints its colour back",graphics:{brush:{type:"strokes",brush:"soft",size:.1}},color:"mix((gray, gray, gray), rgb, alpha(brush))"},{name:"Fuse brush",group:"Brushes",description:"Paint glows as it goes down, then cools to charcoal (red(brush) is its age)",graphics:{brush:{type:"strokes",brush:"round",size:.02,age:40}},color:"mix(rgb, mix((1, 0.9, 0.5), (0.1, 0.07, 0.06), red(brush)), alpha(brush)) + (1, 0.5, 0.1) alpha(brush) max(0, 1 - 3 red(brush)) 0.6"},{name:"Rainbow brush",group:"Brushes",description:"The colour runs round the wheel along the drawing (blue(brush) is how far through it)",graphics:{brush:{type:"strokes",brush:"marker",size:.035}},color:"mix(rgb, fromhsv(blue(brush), 0.85, 1), alpha(brush))"},{name:"Chalk outline",group:"Brushes",description:'Chalk round an object: select it, then "outline the selection" under the step',graphics:{brush:{type:"strokes",brush:"chalk",size:.018,timing:"even",speed:2}},color:"mix(rgb, (0.97, 0.97, 0.92), alpha(brush))"},{name:"Frosted panel",group:"Text & shapes",description:"A rounded panel that blurs and darkens what is behind it — a shape with its own filter",graphics:{panel:{type:"rect",y:.86,w:.9,h:.2,radius:.25}},color:"mix(rgb, gaussian(5) * 0.7, alpha(panel))"},{name:"Spotlight oval",group:"Text & shapes",description:"Darkens everything but a soft oval",graphics:{spot:{type:"ellipse",x:.5,y:.45,w:.45,h:.55,shadow:{color:"#ffffff",blur:.12,dx:0,dy:0}}},color:"mix(rgb * 0.3, rgb, alpha(spot))"},{name:"Scrolling banner",group:"Text & shapes",description:"Text that slides across and wraps round (animated with t)",graphics:{title:{text:"Breaking news · scrolling text · ",size:.07,y:.92}},params:{speed:{default:3,min:-10,max:10}},color:"mix(rgb, shift(title, -speed t, 0), alpha(shift(title, -speed t, 0)))"},{name:"Pulsing title",group:"Text & shapes",description:"Text that grows and shrinks a little (animated with t)",graphics:{title:{text:"Hello!",size:.14,y:.5}},params:{amount:{default:.06,min:0,max:.3}},color:"mix(rgb, zoom(title, 1 + amount sin(t / 8)), alpha(zoom(title, 1 + amount sin(t / 8))))"},{name:"Fade-in title",group:"Text & shapes",description:"Text that fades in over the first frames (animated with t)",graphics:{title:{text:"Once upon a time",font:"Georgia, serif",style:"italic",weight:"normal",size:.09,y:.5}},params:{frames:{default:40,min:1,max:200}},color:"mix(rgb, title, alpha(title) clamp(t / frames, 0, 1))"},{name:"Zoom",group:"Shape & motion",params:{scale:{default:1.5,min:.25,max:4},cx:.5,cy:.5},color:"zoom(scale, cx, cy)"},{name:"Ken Burns",group:"Shape & motion",description:"A slow zoom that drifts across — a still picture that moves",params:{speed:{default:.002,min:0,max:.01},drift:{default:3e-4,min:-.001,max:.001}},color:"zoom(1 + speed t, 0.5 + drift t, 0.45)"},{name:"Scroll",group:"Shape & motion",description:"Slides and wraps around",params:{dx:{default:1,min:-5,max:5},dy:{default:0,min:-5,max:5}},color:"shift(dx t, dy t)"},{name:"Spin",group:"Shape & motion",params:{speed:{default:.01,min:-.05,max:.05}},color:"rotate(speed t)"},{name:"Tile",group:"Shape & motion",params:{n:{default:2,min:1,max:8,step:1}},color:"tile(n)"},{name:"Crop",group:"Shape & motion",description:"A part of the picture, filling the frame",params:{left:.1,top:.1,right:.9,bottom:.9},color:"crop(left, top, right, bottom)"},{name:"Flip",group:"Shape & motion",color:"flipx()"},{name:"Picture in picture",group:"Other pictures",description:"Another picture, fitted small in a corner",images:{inset:{description:"any size: it is fitted whole",place:"fit",zoom:.35,x:.8,y:.78}},color:"mix(rgb, inset, alpha(inset))"},{name:"Moving overlay",group:"Other pictures",description:"Another picture scrolling across at half strength",images:["overlay"],params:{speed:{default:2,min:-10,max:10}},color:"mix(rgb, shift(overlay, speed t, 0), 0.5)"},{name:"Hue shift",group:"Colour & tone",description:"Turns every colour around the hue wheel (in HSV)",space:"hsv",params:{amount:{default:.1,min:-.5,max:.5}},color:"(fract(r + amount), g, b)"},{name:"Saturation",group:"Colour & tone",description:"More or less colour (in HSV)",space:"hsv",params:{amount:{default:1.5,min:0,max:3}},color:"(r, clamp(g amount, 0, 1), b)"},{name:"Lightness",group:"Colour & tone",description:"Lighter or darker without changing the colours (in Lab)",space:"lab",params:{amount:{default:1.15,min:.5,max:2}},color:"(clamp(r amount, 0, 1), g, b)"},{name:"Vivid",group:"Colour & tone",description:"Colourfulness, perceptually even (in OKLab)",space:"oklab",params:{amount:{default:1.6,min:0,max:3}},color:"(r, 0.5 + (g - 0.5) amount, 0.5 + (b - 0.5) amount)"},{name:"Linear-light blur",group:"Blur & edges",description:"A Gaussian in linear light: bright spots stay bright, as a lens does",space:"linear",params:{sigma:{default:3,min:0,max:8}},color:"gaussian(sigma)"},{name:"Film grain",group:"Colour & tone",description:"Noise that changes every frame",params:{amount:{default:.15,min:0,max:.6}},color:"rgb + amount (random() - 0.5)"},{name:"Swirl",group:"Shape & motion",params:{strength:{default:.02,min:0,max:.1}},color:"pixel(w/2 + (px - w/2) cos(strength t gray) - (py - h/2) sin(strength t gray), h/2 + (px - w/2) sin(strength t gray) + (py - h/2) cos(strength t gray))"}],Ft=e=>St.find(t=>t.name===e);St.push({name:"Old film",group:"Chains",description:"Sepia, a vignette and faint scanlines — a chain of three",steps:[Ft("Sepia"),{filter:Ft("Vignette"),with:{strength:1.2}},{filter:Ft("Scanlines"),opacity:.5}]},{name:"Comic",group:"Chains",description:"Bold flat colours with ink lines: a small blur first, so a photo's fine texture isn't inked — a chain of four",steps:[{filter:Ft("Gaussian blur"),with:{sigma:1.6}},{filter:Ft("Vivid"),with:{amount:1.5}},{filter:Ft("Posterize"),with:{levels:4}},{filter:Ft("Outline"),with:{gain:1.2}}]},{name:"Cartoon",group:"Chains",description:"Blur, then flatten the colours, then outline — a chain of three",steps:[{filter:Ft("Gaussian blur"),with:{sigma:1.5}},{filter:Ft("Posterize"),with:{levels:6}},{filter:Ft("Outline"),with:{gain:2}}]},{name:"Dreamy",group:"Chains",description:"A soft glow mixed over the picture",steps:[{filter:Ft("Bloom"),with:{amount:1.2}},{filter:Ft("Gaussian blur"),with:{sigma:2},opacity:.4}]},{name:"Tilt shift",group:"Chains",description:"Blurred where the mask is light — a chain",steps:[{filter:Ft("Gaussian blur"),with:{sigma:4}},Ft("Through a mask")]},{name:"Title card",group:"Chains",description:"A frosted panel with a caption on it — a chain of two",steps:[Ft("Frosted panel"),{filter:Ft("Caption"),with:{title:{text:"A title on a panel",y:.86}}}]},{name:"Colour spotlight",group:"Chains",description:"Grey except where the mask is dark — a chain",steps:[Ft("Grayscale"),Ft("Through a mask")]});const Rt=St,zt=["Colour & tone","Blur & edges","Shape & motion","Text & shapes","Brushes","Other pictures","Chains"];export{u as BRUSHES,m as CLIPS,J as FILTER_FORMAT,d as FPS,T as GRAPHIC_DEFAULTS,A as GRAPHIC_TYPES,zt as GROUPS,Rt as LIBRARY,O as MAX_SHADOW_LAYERS,re as PLACEMENT,g as STROKES_DEFAULTS,p as TIMINGS,f as WIDTH_FROM,Ot as chooseEngine,xt as compileCpuPass,me as compileFilter,kt as createCpuRunner,ke as createFilterRunner,jt as createRunner,L as cssFont,K as drawGraphic,q as familyFor,ye as filterFromJSON,be as filterFromLink,ae as filterGraphics,le as filterImages,he as filterParams,$e as filterToJSON,we as filterToLink,D as fontFileFromCss,G as googleFontFamily,P as googleFontUrl,S as layeredExpression,X as loadGraphicFonts,oe as normalizeFilter,C as normalizeGraphic,w as normalizeStrokes,k as rasterizeStrokes,xe as readFilter,Y as renderGraphics,j as shadowLayerNames,M as simplify,E as simplifyLoop,b as strokeTimeline,Et as toPicture,v as traceContours,ue as validateFilter};
|
|
1
|
+
/* qblur 0.1.2 (MathZetta not included: map mathzetta, mathzetta/glsl and mathzetta/formulas with an import map) — Copyright (c) 2025-2026 Robert Wilcox — MIT licence — https://qblur.com */
|
|
2
|
+
import{FILTER_NAMES as e,COLOUR_SPACES as t,PLACES as r,filterShader as o,filterVertexShader as n,REACH as a,FILTER_FUNCTIONS as s,FILTER_VALUES as i,filterPictureCalls as c}from"mathzetta/glsl";import{parseTree as l}from"mathzetta";import{checkGeneratedJs as h}from"mathzetta/formulas";const u=["round","soft","marker","chalk","spray"],p=["recorded","even","per-stroke"],f=["pressure","speed","none"],m=["none","inside","outside"],d=30,g={type:"strokes",strokes:[],brush:"round",size:.03,flow:1,spacing:.2,taper:0,buildUp:!1,widthFrom:"pressure",timing:"recorded",speed:1,gap:6,start:0,fit:0,age:30,clip:"none",shadows:[]};function $(e,t){throw new Error(`Graphic "${e}": ${t}`)}function w(e,t,r,o,n){const a=Number(r);return(!Number.isFinite(a)||a<o||a>n)&&$(e,`"${t}" is a number from ${o} to ${n}`),a}function y(e,t){for(const r of Object.keys(t))r in g||$(e,`no such setting "${r}" for strokes`);const r={...g,...t},o=(t,o)=>(o.includes(r[t])||$(e,`"${t}" is ${o.join(", ")} — not "${r[t]}"`),r[t]),n={type:"strokes",brush:o("brush",u),widthFrom:o("widthFrom",f),timing:o("timing",p),clip:o("clip",m),size:w(e,"size",r.size,.001,.5),flow:w(e,"flow",r.flow,.01,1),spacing:w(e,"spacing",r.spacing,.02,2),taper:w(e,"taper",r.taper,0,.5),speed:w(e,"speed",r.speed,.05,20),gap:w(e,"gap",r.gap,0,600),start:w(e,"start",r.start,0,1e4),fit:w(e,"fit",r.fit,0,1e4),age:w(e,"age",r.age,1,1e4),buildUp:Boolean(r.buildUp),shadows:[]};Array.isArray(r.strokes)||$(e,'"strokes" is a list of { "points": [[x, y, ms, pressure], …] }');let a=0;return n.strokes=r.strokes.map((t,r)=>{const o=Array.isArray(t)?t:t?.points;return Array.isArray(o)||$(e,`stroke ${r+1} is { "points": [[x, y, ms, pressure], …] }`),a+=o.length,a>6e4&&$(e,"a drawing has at most 60000 points"),{points:o.map((t,o)=>((!Array.isArray(t)||t.length<2||!t.every(e=>Number.isFinite(Number(e))))&&$(e,`stroke ${r+1}, point ${o+1} is [x, y, ms, pressure]`),[+Number(t[0]).toFixed(4),+Number(t[1]).toFixed(4),Math.round(Number(t[2]??16*o)),+Math.min(1,Math.max(0,Number(t[3]??1))).toFixed(2)]))}}),n}function b(e,t=1){const r=[];let o=e.start;const n=30/e.speed,a=20/e.speed;for(const s of e.strokes){const i=s.points;if(!i.length)continue;const c=[0];for(let e=1;e<i.length;e++)c.push(c[e-1]+Math.hypot((i[e][0]-i[e-1][0])*t,i[e][1]-i[e-1][1]));const l=c[c.length-1]||1e-9,h=i[0][2],u=i.map((t,r)=>{let o;o="recorded"===e.timing?(t[2]-h)/1e3*30/e.speed:"even"===e.timing?c[r]*n:c[r]/l*a;let s=1;if("pressure"===e.widthFrom)s=.3+.7*t[3];else if("speed"===e.widthFrom&&r>0){const e=Math.max(1,t[2]-i[r-1][2]),o=(c[r]-c[r-1])/e*1e3;s=Math.min(1.3,Math.max(.35,1.3-.6*o))}return e.taper>0&&(s*=Math.max(.15,Math.min(1,c[r]/l/e.taper,(1-c[r]/l)/e.taper))),{x:t[0],y:t[1],f:o,wf:s}});"speed"===e.widthFrom&&u.length>1&&(u[0].wf=u[1].wf);const p=u[u.length-1].f;for(const e of u)e.f+=o;r.push({points:u,start:o,end:o+p}),o+=p+e.gap}let s=r.length?r[r.length-1].end:e.start;if(e.fit>0&&s>e.start){const t=e.fit/(s-e.start);for(const o of r){for(const r of o.points)r.f=e.start+(r.f-e.start)*t;o.start=e.start+(o.start-e.start)*t,o.end=e.start+(o.end-e.start)*t}s=e.start+e.fit}return{strokes:r,total:s}}function x(e,t){let r=Math.imul(0|e,374761393)+Math.imul(0|t,668265263)|0;return r=Math.imul(r^r>>>13,1274126177),((r^r>>>16)>>>0)/4294967296}const _=new Map;function k(e,t,r,o=1/0,{mask:n=null}={}){const a=t*r,{alpha:s,passes:i,latest:c,cov:l,when:h,touched:u}=function(e){let t=_.get(e);return t||(t={alpha:new Float32Array(e),passes:new Float32Array(e),latest:new Float32Array(e),cov:new Float32Array(e),when:new Float32Array(e),touched:new Int32Array(e)},_.clear(),_.set(e,t)),t.alpha.fill(0),t.passes.fill(0),t.latest.fill(-1),t}(a),{strokes:p,total:f}=b(e,t/r),m=Number.isFinite(o)?o:f,d=Math.max(.5,e.size*r/2);let g=0,$=256*Math.max(a,65536);p.forEach(o=>{if(o.start>m||$<=0)return;let n=0;const a=(t,r,o,n)=>{const a=g++;if("spray"===e.brush){const e=Math.max(3,Math.round(.6*o)),s=Math.max(.6,.07*o);for(let i=0;i<e;i++){const e=x(a,2*i)*Math.PI*2,c=Math.sqrt(x(a,2*i+1))*o;p(t+Math.cos(e)*c,r+Math.sin(e)*c,s,n,"round")}}else p(t,r,o,n,e.brush)},p=(o,a,s,i,c)=>{const p="marker"===c?s:s+1,f=Math.max(0,Math.floor(o-p)),m=Math.min(t-1,Math.ceil(o+p)),d=Math.max(0,Math.floor(a-p)),g=Math.min(r-1,Math.ceil(a+p));$-=m>=f&&g>=d?(m-f+1)*(g-d+1):16;for(let r=d;r<=g;r++)for(let p=f;p<=m;p++){const f=p+.5-o,m=r+.5-a;let d;if("soft"===c){const e=Math.hypot(f,m)/s;if(e>=1)continue;const t=1-e;d=t*t*(3-2*t)}else if("marker"===c){const e=(f+m)*Math.SQRT1_2,t=(m-f)*Math.SQRT1_2,r=Math.hypot(e/s,t/(.33*s));d=Math.min(1,Math.max(0,(1-r)*s*.33+.5))}else d=Math.min(1,Math.max(0,s-Math.hypot(f,m)+.5)),"chalk"===c&&(d*=x(p,7919*r)>.42?1:.12);if(d<=0)continue;d*=e.flow;const g=r*t+p;d>l[g]&&(0===l[g]&&(u[n++]=g),l[g]=d),d>.02&&(h[g]=i)}},f=o.points;let w=0;const y=e=>[e.x*t,e.y*r];if(1===f.length||f.every(e=>e.x===f[0].x&&e.y===f[0].y)){const[e,t]=y(f[0]);a(e,t,d*f[0].wf,f[0].f)}for(let t=1;t<f.length;t++){const r=f[t-1],o=f[t];if(r.f>m)break;const[n,s]=y(r),[i,c]=y(o);let l=1;o.f>m&&(l=(m-r.f)/Math.max(1e-9,o.f-r.f));const h=Math.hypot(i-n,c-s);let u=1===t?0:w;for(;u<=h*l&&$>0;){const t=h?u/h:0,l=d*(r.wf+(o.wf-r.wf)*t);a(n+(i-n)*t,s+(c-s)*t,l,r.f+(o.f-r.f)*t),u+=Math.max(.5,2*e.spacing*l)}if(w=u-h,l<1||$<=0)break}for(let t=0;t<n;t++){const r=u[t],o=l[r];s[r]=e.buildUp?1-(1-s[r])*(1-o):Math.max(s[r],o),i[r]+=o,o>.02&&h[r]>c[r]&&(c[r]=h[r]),l[r]=0}});const w=new Uint8ClampedArray(4*a),y="inside"===e.clip,k="outside"===e.clip;for(let t=0;t<a;t++){let r=s[t];if(0===r)continue;let o=1;n&&(y||k)&&(o=y?n[t]:1-n[t]),r*=o;const a=4*t;w[a]=Math.round(255*Math.min(1,Math.max(0,(m-c[t])/e.age))),w[a+1]=Math.round(255*Math.min(1,i[t]*o/4)),w[a+2]=Math.round(255*Math.min(1,Math.max(0,c[t]/Math.max(1e-9,f)))),w[a+3]=Math.round(255*r)}return{data:w,width:t,height:r,total:f}}function v(e,t,r,{minArea:o=40,tolerance:n=.8}={}){const a=(o,n)=>o>=0&&n>=0&&o<t&&n<r&&e[n*t+o]>.5,s=new Int32Array(t*r).fill(-1),i=[],c=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]];let l=0;for(let e=0;e<r;e++)for(let r=0;r<t;r++){if(!a(r,e)||s[e*t+r]>=0)continue;const h=l++,u=[e*t+r];s[e*t+r]=h;let p=0;for(;u.length;){const e=u.pop();p++;const r=e%t,o=(e-r)/t;for(const[e,n]of[[1,0],[-1,0],[0,1],[0,-1]]){const i=r+e,c=o+n;a(i,c)&&s[c*t+i]<0&&(s[c*t+i]=h,u.push(c*t+i))}}if(p<o)continue;const f=[[r,e]];let m=r,d=e,g=4;for(let o=0;o<4*p+16;o++){let o=!1;for(let e=1;e<=8;e++){const r=(g+e)%8,n=m+c[r][0],i=d+c[r][1];if(a(n,i)&&s[i*t+n]===h){g=(r+4)%8,m=n,d=i,o=!0;break}}if(!o||m===r&&d===e)break;f.push([m,d])}i.push(E(f,n))}return i}function E(e,t){if(e.length<4)return[...e,e[0]];const[r,o]=e[0];let n=0;return e.forEach(([t,a],s)=>{Math.hypot(t-r,a-o)>Math.hypot(e[n][0]-r,e[n][1]-o)&&(n=s)}),[...M(e.slice(0,n+1),t),...M([...e.slice(n),e[0]],t).slice(1)]}function M(e,t){if(e.length<3)return e;const r=new Uint8Array(e.length);r[0]=r[e.length-1]=1;const o=[[0,e.length-1]];for(;o.length;){const[n,a]=o.pop(),[s,i]=e[n],[c,l]=e[a],h=Math.hypot(c-s,l-i)||1e-9;let u=-1,p=-1;for(let t=n+1;t<a;t++){const r=Math.abs((c-s)*(i-e[t][1])-(s-e[t][0])*(l-i))/h;r>u&&(u=r,p=t)}u>t&&(r[p]=1,o.push([n,p],[p,a]))}return e.filter((e,t)=>r[t])}const A=["text","rect","ellipse","strokes"],O={text:{type:"text",text:"Text",font:"sans-serif",weight:"bold",style:"normal",size:.08,x:.5,y:.85,align:"center",angle:0,lineHeight:1.2,color:"#ffffff",outline:null,shadow:{color:"rgba(0,0,0,0.6)",blur:.15,dx:.04,dy:.06},shadows:[]},rect:{type:"rect",x:.5,y:.85,w:.8,h:.18,radius:.15,angle:0,color:"#ffffff",outline:null,shadow:null,shadows:[]},ellipse:{type:"ellipse",x:.5,y:.5,w:.4,h:.4,angle:0,color:"#ffffff",outline:null,shadow:null,shadows:[]}},T=8,j=(e,t)=>(t.shadows??[]).map((t,r)=>`${e}_shadow${r+1}`);function S(e,t){let r="rgb";for(const o of j(e,t))r=`mix(${r}, ${o}, alpha(${o}))`;return`mix(${r}, ${e}, alpha(${e}))`}const F=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([\d.,\s%deg/]+\)|[a-z]{3,20}|transparent)$/i,R=/^[\w\s,'"-]{1,80}$/,z=["normal","bold","100","200","300","400","500","600","700","800","900"];function I(e,t,r){if("string"!=typeof r||!F.test(r.trim()))throw new Error(`Graphic "${e}": "${t}" is a colour like "#ffcc00", "rgba(0,0,0,0.5)" or "white"`);return r.trim()}function N(e,t,r,o=-1/0,n=1/0){const a=Number(r);if(!Number.isFinite(a)||a<o||a>n)throw new Error(`Graphic "${e}": "${t}" is a number${Number.isFinite(o)?` from ${o} to ${n}`:""}`);return a}function U(e,t){if(null===t||!1===t)return null;if("object"!=typeof t)throw new Error(`Graphic "${e}": "outline" is { "color", "width" } or null`);return{color:I(e,"outline.color",t.color??"#000000"),width:N(e,"outline.width",t.width??.06,0,1)}}function B(e,t){if(null===t||!1===t)return null;if("object"!=typeof t)throw new Error(`Graphic "${e}": "shadow" is { "color", "blur", "dx", "dy" } or null`);return{color:I(e,"shadow.color",t.color??"rgba(0,0,0,0.6)"),blur:N(e,"shadow.blur",t.blur??.15,0,2),dx:N(e,"shadow.dx",t.dx??0,-2,2),dy:N(e,"shadow.dy",t.dy??0,-2,2)}}function C(e,t){if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(`Graphic "${e}": give { "type": "text" | "rect" | "ellipse", … }`);const r=t.type??"text";if(!A.includes(r))throw new Error(`Graphic "${e}": "type" is text, rect, ellipse or strokes — not "${r}"`);if("strokes"===r)return y(e,t);const o=O[r];for(const n of Object.keys(t))if(!(n in o)&&"fontUrl"!==n&&"onlyShadow"!==n)throw new Error(`Graphic "${e}": no such setting "${n}" for ${r}`);const n={type:r};for(const[r,a]of Object.entries(o)){if("type"===r)continue;const o=r in t&&void 0!==t[r]?t[r]:a;if("color"===r)n.color=I(e,r,o);else if("outline"===r)n.outline=U(e,o);else if("shadow"===r)n.shadow=B(e,o);else if("shadows"===r){if(!Array.isArray(o)||o.length>8)throw new Error(`Graphic "${e}": "shadows" is a list of up to 8 { "color", "blur", "dx", "dy" }`);n.shadows=o.map((t,r)=>{if(!t||"object"!=typeof t)throw new Error(`Graphic "${e}": shadow layer ${r+1} is { "color", "blur", "dx", "dy" }`);return B(e,t)})}else if("text"===r){if("string"!=typeof o||o.length>500)throw new Error(`Graphic "${e}": "text" is up to 500 characters`);n.text=o}else if("font"===r){if("string"!=typeof o||!R.test(o))throw new Error(`Graphic "${e}": "font" is a font family, like "Georgia" or "sans-serif"`);n.font=o}else if("weight"===r){if(!z.includes(String(o)))throw new Error(`Graphic "${e}": "weight" is normal, bold or 100–900`);n.weight=String(o)}else if("style"===r){if(!["normal","italic"].includes(o))throw new Error(`Graphic "${e}": "style" is normal or italic`);n.style=o}else if("align"===r){if(!["left","center","right"].includes(o))throw new Error(`Graphic "${e}": "align" is left, center or right`);n.align=o}else"size"===r?n.size=N(e,r,o,.005,2):"w"===r||"h"===r?n[r]=N(e,r,o,0,4):"radius"===r?n.radius=N(e,r,o,0,.5):"lineHeight"===r?n.lineHeight=N(e,r,o,.5,4):n[r]=N(e,r,o)}if(void 0!==t.fontUrl&&null!==t.fontUrl&&""!==t.fontUrl){if("text"!==r)throw new Error(`Graphic "${e}": "fontUrl" is for text`);let o;try{o=new URL(t.fontUrl)}catch{o=null}if(!o||"https:"!==o.protocol)throw new Error(`Graphic "${e}": "fontUrl" is an https:// address of a font file (.woff2, .woff, .ttf, .otf) or of a Google Fonts stylesheet`);n.fontUrl=o.href}return void 0!==t.onlyShadow&&(n.onlyShadow=N(e,"onlyShadow",t.onlyShadow,0,7)),n}function P(e){const t=String(e).trim().replace(/\s+/g," ");if(!/^[A-Za-z0-9 ]{1,60}$/.test(t))throw new Error('A Google Fonts name is letters, digits and spaces, like "Lobster" or "Playfair Display"');return`https://fonts.googleapis.com/css2?family=${t.replace(/ /g,"+")}:ital,wght@0,400;0,700;1,400;1,700&display=swap`}function G(e){try{const t=new URL(e);return"fonts.googleapis.com"!==t.hostname?null:(t.searchParams.get("family")??"").split(":")[0].replace(/\+/g," ")||null}catch{return null}}function D(e,{weight:t="400",style:r="normal"}={}){const o=[...e.matchAll(/@font-face\s*{([^}]*)}/g)].map(e=>e[1]),n=(e,t)=>(new RegExp(`${t}\\s*:\\s*([^;]+);`).exec(e)?.[1]??"").trim(),a=String("bold"===t?700:"normal"===t?400:t),s=o.filter(e=>n(e,"font-weight")===a&&n(e,"font-style")===r),i=(s.length?s:o).at(-1);return i&&(/url\(([^)]+)\)/.exec(i)?.[1]??"").replace(/^['"]|['"]$/g,"")||null}function L(e,t){const r=e.fontUrl?`"${q(e.fontUrl)}", ${e.font}`:e.font;return`${e.style} ${e.weight} ${Math.max(1,e.size*t)}px ${r}`}function q(e){let t=0;for(const r of e)t=31*t+r.charCodeAt(0)>>>0;return`mz-font-${t.toString(36)}`}const W=new Map;async function X(e,t=100){if("undefined"==typeof document&&"undefined"==typeof self)return[];const r="undefined"!=typeof document?document.fonts:self.fonts;if(!r)return[];const o=[];for(const n of Object.values(e??{}))if("text"===n.type){if(n.fontUrl&&"undefined"!=typeof FontFace){const e=`${n.fontUrl} ${n.weight} ${n.style}`;W.has(e)||W.set(e,H(n,r)),await W.get(e)||o.push(n.fontUrl)}try{await r.load(L(n,t),n.text)}catch{}}return[...new Set(o)]}async function H(e,t){try{let r=e.fontUrl;if(!/\.(woff2?|ttf|otf)(\?|$)/i.test(new URL(r).pathname)||G(r)){if(r=D(await(await fetch(r,{credentials:"omit",referrerPolicy:"no-referrer"})).text(),e),!r||!r.startsWith("https://"))return null}const o=new FontFace(q(e.fontUrl),`url(${JSON.stringify(r)})`,{weight:e.weight,style:e.style});return t.add(await o.load()),o}catch{return null}}function K(e,t,r,o){e.save();const n="text"===t.type?t.size*o:o,a=void 0!==t.onlyShadow?t.shadows[t.onlyShadow]:null,s=a?2*(r+o)+1e3:0,i=a??t.shadow;if(e.translate(t.x*r-s,t.y*o),t.angle&&e.rotate(t.angle),i&&(e.shadowColor=i.color,e.shadowBlur=i.blur*n,e.shadowOffsetX=i.dx*n+s,e.shadowOffsetY=i.dy*n),e.fillStyle=a?"#000000":t.color,t.outline&&(e.strokeStyle=t.outline.color,e.lineWidth=t.outline.width*n,e.lineJoin="round"),"text"===t.type){e.font=L(t,o),e.textAlign=t.align,e.textBaseline="middle";const r=t.text.split("\n"),n=t.size*o*t.lineHeight;r.forEach((o,s)=>{const c=(s-(r.length-1)/2)*n;t.outline&&e.strokeText(o,0,c),t.outline&&i&&!a&&(e.shadowColor="transparent"),e.fillText(o,0,c),t.outline&&i&&!a&&(e.shadowColor=i.color)})}else{const n=t.w*r,s=t.h*o;if(e.beginPath(),"ellipse"===t.type)e.ellipse(0,0,n/2,s/2,0,0,2*Math.PI);else{const r=Math.min(n,s)*t.radius;e.roundRect?e.roundRect(-n/2,-s/2,n,s,r):e.rect(-n/2,-s/2,n,s)}e.fill(),t.outline&&(a||(e.shadowColor="transparent"),e.stroke())}e.restore()}async function Y(e,t,r,{t:o=1/0,mask:n=null}={}){const a=e.graphics??{},s=await X(a,r),i={};for(const[e,s]of Object.entries(a)){if("strokes"===s.type){const a=k(s,t,r,o,{mask:n});i[e]="undefined"!=typeof ImageData?new ImageData(a.data,t,r):a;continue}const a="undefined"!=typeof OffscreenCanvas&&"undefined"==typeof document?new OffscreenCanvas(t,r):Object.assign(document.createElement("canvas"),{width:t,height:r});K(a.getContext("2d"),s,t,r),i[e]=a}return Object.defineProperty(i,"failedFonts",{value:s}),i}const J="mathzetta-filter/1",V=["r","g","b","a","rgb","rgba"],Z=/^[A-Za-z][A-Za-z0-9_]*$/,Q=new Set([...e,"r","g","b","a","x","y","w","h","t","c","e","pi","color","image","resolution","base","position","main","in","out","inout","const","uniform","varying","attribute","void","float","int","bool","vec2","vec3","vec4","mat2","mat3","mat4","sampler2D","struct","precision","highp","mediump","lowp","if","else","for","while","do","return","break","continue","discard","true","false","texture2D","texture","mix","clamp","step","smoothstep","abs","sign","floor","ceil","fract","mod","min","max","sin","cos","tan","asin","acos","atan","pow","exp","log","exp2","log2","sqrt","inversesqrt","length","distance","dot","cross","normalize","radians","degrees"]),ee=e=>Array.isArray(e)&&3===e.length&&e.every(e=>Number.isFinite(Number(e))),te=e=>e&&"object"==typeof e&&!Array.isArray(e),re={place:"cover",zoom:1,x:.5,y:.5,angle:0};function oe(e){if("string"==typeof e){if(!e.trim())throw new Error("The filter is empty");return{format:J,color:e.trim()}}if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('A filter is an expression, or an object with "color" or "steps"');if(void 0!==e.format&&e.format!==J)throw new Error(`Unknown filter format "${e.format}" (this is ${J})`);const r={format:J};for(const t of["name","author","description"])void 0!==e[t]&&""!==e[t]&&(r[t]=String(e[t]));if(void 0!==e.steps){if(void 0!==e.color)throw new Error('A filter has either "color" or "steps", not both');if(!Array.isArray(e.steps)||!e.steps.length)throw new Error('"steps" must be a list with at least one step');return r.steps=e.steps.map(ie),void 0!==e.notes&&(r.notes=ne(e.notes,he(r))),r}if(void 0===e.color)throw new Error('A filter needs "color" (an expression, or one per channel) or "steps"');const o=function(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('"params" is an object of name → { default, min, max }');const t={};for(const[r,o]of Object.entries(e)){if(!Z.test(r))throw new Error(`Parameter name "${r}" must be letters, digits and _, starting with a letter`);if(Q.has(r))throw new Error(`"${r}" is already defined in every filter; pick another parameter name`);t[r]=ce(r,o)}return t}(e.params??{});Object.keys(o).length&&(r.params=o),void 0!==e.notes&&(r.notes=ne(e.notes,o));const n=function(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,{}])):e;if(!r||"object"!=typeof r)throw new Error('"images" is a list of names, or an object of name → { description }');const o={};for(const[e,n]of Object.entries(r)){if(!Z.test(e)||e.startsWith("mz_"))throw new Error(`Image name "${e}" must be letters, digits and _, starting with a letter`);if("source"===e)throw new Error('"source" is always available: the picture the chain started from');if(Q.has(e))throw new Error(`"${e}" is already defined in every filter; pick another image name`);if(Object.hasOwn(t,e))throw new Error(`"${e}" is both a parameter and an image`);o[e]=se(e,n)}return o}(e.images??{},o);Object.keys(n).length&&(r.images=n);const a=function(e,t,r){if(!te(e))throw new Error('"graphics" is an object of name → { "type": "text" | "rect" | "ellipse", … }');if(Object.keys(e).length>64)throw new Error("A filter has at most 64 graphics");const o={};for(const[n,a]of Object.entries(e)){if(!Z.test(n)||n.startsWith("mz_"))throw new Error(`Graphic name "${n}" must be letters, digits and _, starting with a letter`);if(Q.has(n)||"source"===n||"selection"===n)throw new Error(`"${n}" is already defined in every filter; pick another graphic name`);if(Object.hasOwn(t,n)||Object.hasOwn(r,n))throw new Error(`"${n}" is both a graphic and a parameter or picture`);o[n]=C(n,a)}const n=new Set(Object.keys(o).flatMap(e=>Array.from({length:8},(t,r)=>`${e}_shadow${r+1}`)));for(const e of[...Object.keys(o),...Object.keys(t),...Object.keys(r)])if(n.has(e))throw new Error(`"${e}" is the name of a shadow layer of another graphic; pick another name`);return o}(e.graphics??{},o,n);Object.keys(a).length&&(r.graphics=a);const s=function(e){if(null==e)return null;const r="string"==typeof e?{in:e,out:e}:e;if(!te(r))throw new Error(`"space" is a colour space (${t.join(", ")}) or { "in": …, "out": … }`);const o={in:r.in??"srgb",out:r.out??"srgb"};for(const e of["in","out"])if(!t.includes(o[e]))throw new Error(`"space": "${o[e]}" is not a colour space; they are ${t.join(", ")}`);return"srgb"===o.in&&"srgb"===o.out?null:o}(e.space);return s&&(r.space=s),r.color=function(e){if("string"==typeof e){if(!e.trim())throw new Error('"color" is empty');return e.trim()}if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('"color" is an expression, or an object with r, g, b, a, rgb or rgba expressions');const t={};for(const[r,o]of Object.entries(e)){if(!V.includes(r))throw new Error(`"color" can set r, g, b, a, rgb or rgba — not "${r}"`);if("string"!=typeof o||!o.trim())throw new Error(`"color.${r}" must be an expression`);t[r]=o.trim()}if(!Object.keys(t).length)throw new Error('"color" sets no channels');return t}(e.color),r}function ne(e,t){if(!Array.isArray(e))throw new Error('"notes" is a list of Markdown texts and { "param": name } entries');return e.map(e=>{if("string"==typeof e)return e;if(!te(e)||"string"!=typeof e.param||1!==Object.keys(e).length)throw new Error('"notes": each entry is a Markdown text or { "param": name }');if(!Object.hasOwn(t,e.param))throw new Error(`"notes" places "${e.param}", but there is no parameter called that`);return{param:e.param}})}function ae(e){if(e.color)return{...e.graphics??{}};const t={};for(const r of e.steps)for(const[e,o]of Object.entries(ae(r.filter)))Object.hasOwn(t,e)||(t[e]=o);return t}function se(e,t){if(!te(t))throw new Error(`Image "${e}": give { description, place, zoom, x, y, angle }`);const o={};if(t.description&&(o.description=String(t.description)),void 0!==t.place){if(!r.includes(t.place))throw new Error(`Image "${e}": "place" is ${r.join(", ")} — not "${t.place}"`);o.place=t.place}for(const r of["zoom","x","y","angle"]){if(void 0===t[r])continue;const n=Number(t[r]);if(!Number.isFinite(n))throw new Error(`Image "${e}": "${r}" is a number`);o[r]=n}for(const r of Object.keys(t))if(!["description","place","zoom","x","y","angle"].includes(r))throw new Error(`Image "${e}": no such setting "${r}"`);return o}function ie(e){if("string"==typeof e)return{filter:oe(e),with:{},opacity:1,skip:!1};if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('A step is an expression, a filter, or { "filter": …, "with": { … }, "opacity": … }');const{filter:t,with:r,opacity:o,skip:n,...a}=e,s={filter:oe(void 0!==t?t:a),with:{},opacity:1,skip:Boolean(n)};if(void 0!==r){if(!r||"object"!=typeof r||Array.isArray(r))throw new Error('"with" is an object of parameter name → value');s.with={...r}}if(void 0!==o){const e=Number(o);if(!(e>=0&&e<=1))throw new Error('"opacity" is a number from 0 to 1');s.opacity=e}return s}function ce(e,t){if("number"==typeof t)t={default:t};else if(Array.isArray(t))t={type:"color",default:t};else if(!t||"object"!=typeof t)throw new Error(`Parameter "${e}" needs a default value`);const r=t.type??(Array.isArray(t.default)?"color":"number"),o={type:r};if(void 0!==t.label&&(o.label=String(t.label)),"color"===r){const r=t.default??[1,1,1];if(!ee(r))throw new Error(`Colour parameter "${e}" needs a default of three numbers, 0–1`);return o.default=r.map(Number),o}if("number"!==r)throw new Error(`Parameter "${e}": the type is "number" or "color", not "${r}"`);let n=null;if(void 0!==t.options){if(!Array.isArray(t.options)||!t.options.length||!t.options.every(e=>""!==e&&Number.isFinite(Number(e))))throw new Error(`Parameter "${e}": "options" is a list of numbers`);n=t.options.map(Number)}if(void 0!==t.input&&"slider"!==t.input&&"box"!==t.input)throw new Error(`Parameter "${e}": "input" is "slider" or "box", not "${t.input}"`);const a=Number(t.default??(n?n[0]:0));if(!Number.isFinite(a))throw new Error(`Parameter "${e}" needs a numeric default`);if(o.default=a,o.min=void 0!==t.min?Number(t.min):n?n.reduce((e,t)=>Math.min(e,t),a):Math.min(0,2*a),o.max=void 0!==t.max?Number(t.max):n?n.reduce((e,t)=>Math.max(e,t),a):Math.max(1,2*a),void 0!==t.step&&(o.step=Number(t.step)),n&&(o.options=n),"box"!==t.input||n||(o.input="box"),!(o.min<=a&&a<=o.max))throw new Error(`Parameter "${e}": the default ${a} is outside ${o.min} to ${o.max}`);return o}function le(e){if(e.color)return{...e.images??{}};const t={};for(const r of e.steps)for(const[e,o]of Object.entries(le(r.filter)))Object.hasOwn(t,e)||(t[e]=o);return t}function he(e){if(e.color)return{...e.params??{}};const t={};for(const r of e.steps)for(const[e,o]of Object.entries(he(r.filter)))Object.hasOwn(t,e)||(t[e]=o);return t}function ue(e){let t;try{t=oe(e)}catch(e){return[e.message]}const r=[];return pe({filter:t,with:{},opacity:1},[],r,!0),r}function pe(e,t,r,o){const{filter:n}=e,a=fe(n,t),s=he(n),i=le(n),c=ae(n);for(const[t,o]of Object.entries(e.with)){if(Object.hasOwn(c,t)){if(te(o))try{C(t,{...c[t],...o})}catch(e){r.push(`${a}: ${e.message}`)}else r.push(`${a}: "with" for the graphic "${t}" is an object of its settings`);continue}if(Object.hasOwn(i,t)){try{se(t,o)}catch(e){r.push(`${a}: ${e.message}`)}continue}const e=Object.hasOwn(s,t)?s[t]:null;e?("color"===e.type?ee(o):Number.isFinite(Number(o)))||r.push(`${a}: "${t}" should be a ${"color"===e.type?"colour: three numbers, 0–1":"number"}`):r.push(`${a}: "with" sets "${t}", but there is no parameter called that`)}if(n.steps)n.steps.forEach((e,n)=>pe(e,[...t,n],r,o));else if(o)try{ge(n,Object.fromEntries(Object.entries(e.with).filter(([e])=>Object.hasOwn(n.graphics??{},e))),1,t,100)}catch(e){r.push(`${a}: ${e.message}`)}}function fe(e,t){return e.name?`"${e.name}"`:t.length?`step ${t.map(e=>e+1).join(".")}`:"the filter"}function me(e,t={}){const r=oe(e),o=[];if(pe({filter:r,with:{},opacity:1},[],o,!1),o.length)throw new Error(o.join("\n"));const n={passes:[],credits:[],problems:o,version:300===t.version?300:100,top:r,graphics:{}};if(de({filter:r,with:{},opacity:1,skip:!1},[],{},n),o.length)throw new Error(o.join("\n"));return n.passes.length||n.passes.push(ge(oe("pixel(px, py)"),{},1,[],n.version)),{name:r.name??"",author:r.author??"",description:r.description??"",version:n.version,passes:n.passes,credits:n.credits,images:le(r),graphics:n.graphics}}function de(e,t,r,o){if(e.skip)return;if(o.passes.length>256){const e="A filter has at most 256 passes";return void(o.problems.includes(e)||o.problems.push(e))}const n=function(e){if(!e.space||void 0===e.color)return null;const{space:t,name:r,author:o,description:n,...a}=e,s=e=>({filter:e,with:{},opacity:1,skip:!1}),i=[];"srgb"!==t.in&&i.push(s({format:J,color:{rgb:`to${t.in}(rgb)`}}));i.push(s({...a,_space:t.in})),"srgb"!==t.out&&i.push(s({format:J,color:{rgb:`from${t.out}(rgb)`}}));const c={format:J,steps:i};for(const[e,t]of Object.entries({name:r,author:o,description:n}))t&&(c[e]=t);return c}(e.filter)??function(e){if("string"!=typeof e.color)return null;const t=/^(gaussian|blur)\((.*)\)$/s.exec(e.color.trim());if(!t)return null;let r=0;for(const e of t[2])if("("===e)r++;else if(")"===e&&--r<0)return null;if(0!==r)return null;const{color:o,...n}=e,a=e=>{const r={format:J,color:`${t[1]}${e}(${t[2]})`};return n.params&&(r.params=n.params),n.images&&(r.images=n.images),n.graphics&&(r.graphics=n.graphics),{filter:r,with:{},opacity:1,skip:!1}};return{...n,steps:[a("x"),a("y")]}}(e.filter);if(n)return e.filter===o.top&&(o.top=n),void de({...e,filter:n},t,r,o);const{filter:a}=e,s={...e.with,...r};for(const t of Object.keys(r))te(r[t])&&te(e.with[t])&&(s[t]={...e.with[t],...r[t]});if(a.name&&a!==o.top&&!o.credits.some(e=>e.name===a.name&&e.author===(a.author??""))&&o.credits.push({name:a.name,author:a.author??""}),a.color){try{o.passes.push(function(e,t){e.bind={};for(const[r,o]of Object.entries(e.graphics??{})){let n=r;for(let e=2;n in t&&JSON.stringify(t[n])!==JSON.stringify(o);e++)n=`${r}~${e}`;t[n]=o,e.bind[r]=n}return e}(ge(a,s,e.opacity,t,o.version),o.graphics))}catch(e){o.problems.push(`${fe(a,t)}: ${e.message}`)}return}const i=o.passes.length;a.steps.forEach((e,r)=>de(e,[...t,r],s,o)),e.opacity<1&&(o.passes.length-i===1?o.passes[i].opacity*=e.opacity:(o.passes[i].keepInput+=1,o.passes.push(function(e,t,r){const o=300===r,n=o?"texture":"texture2D",a=[o?"#version 300 es":"","precision highp float;","uniform sampler2D image;","uniform sampler2D base;","uniform vec2 resolution;","uniform float mz_opacity;",o?"out vec4 fragColor;":"","void main() {"," vec2 uv = gl_FragCoord.xy / resolution;",` ${o?"fragColor":"gl_FragColor"} = mix(${n}(base, uv), ${n}(image, uv), mz_opacity);`,"}"].filter(Boolean).join("\n");return{name:"blend",author:"",path:t,fragment:a,params:{},values:{},opacity:e,images:[],placements:{},graphics:{},keepInput:0,blendKept:!0}}(e.opacity,t,o.version))))}function ge(e,t,r,n,a){const s=e.params??{},i={};for(const[e,r]of Object.entries(s))Object.hasOwn(t,e)?i[e]="color"===r.type?t[e].map(Number):Number(t[e]):i[e]=r.default;const c={};for(const[r,o]of Object.entries(e.images??{})){const{description:e,...n}=o;c[r]={...re,...n,...te(t[r])?t[r]:{}}}const l={};for(const[r,o]of Object.entries(e.graphics??{}))l[r]=te(t[r])?C(r,{...o,...t[r]}):o,c[r]={...re,place:"stretch"},j(r,l[r]).forEach((e,t)=>{l[e]={...l[r],onlyShadow:t},c[e]={...re,place:"stretch"}});const h=function(e,t,r=null){const n=e.params??{},a={};for(const[e,t]of Object.entries(n))a[e]="color"===t.type?"vec3":"float";const s={};for(const[t,o]of Object.entries(e.images??{}))s[t]={place:r?.[t]?.place??o.place??re.place};for(const[t,o]of Object.entries(e.graphics??{})){s[t]={place:"stretch"};const e=r?Object.keys(r).filter(e=>/_shadow\d+$/.test(e)&&e.startsWith(`${t}_shadow`)):j(t,o);for(const t of e)s[t]={place:"stretch"}}return o(e.color,{version:t,uniforms:a,values:Object.keys(n),images:s,blend:!0,space:e._space??e.space?.in??"srgb"})}(e,a,c),u=Object.keys(c);return h.includes("uniform sampler2D mz_img_source;")&&u.push("source"),h.includes("uniform sampler2D mz_img_selection;")&&u.push("selection"),{name:e.name??"",author:e.author??"",path:n,color:e.color,space:e._space??"srgb",fragment:h,params:s,values:i,opacity:r,images:u,placements:c,graphics:l,keepInput:0,blendKept:!1}}function $e(e){return JSON.stringify(_e(oe(e),!0),null,2)}function we(e){let t;try{t=JSON.parse(e)}catch{throw new Error("Not valid JSON")}return oe(t)}function ye(e,t=""){return`${t}#${function(e){let t="";for(const r of(new TextEncoder).encode(e))t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}(JSON.stringify(_e(oe(e),!0)))}`}function be(e){const t=e.includes("#")?e.slice(e.lastIndexOf("#")+1):e;let r;try{r=JSON.parse(function(e){const t=atob(e.replace(/-/g,"+").replace(/_/g,"/"));return(new TextDecoder).decode(Uint8Array.from(t,e=>e.charCodeAt(0)))}(t.trim()))}catch{throw new Error("Not a filter link")}return oe(r)}function xe(e){const t=String(e??"").trim();if(!t)throw new Error("Nothing to read");if(t.startsWith("{"))return we(t);if(!/\s/.test(t)){const e=t.includes("#")?t.slice(t.lastIndexOf("#")+1):t;if(/^[A-Za-z0-9_-]{8,}$/.test(e))try{return be(e)}catch(e){if(t.includes("#"))throw e}}return oe(t)}function _e(e,t){const r={};t&&(r.format=J);for(const t of["name","author","description"])e[t]&&(r[t]=e[t]);return e.notes&&e.notes.length&&(r.notes=e.notes),e.steps?(r.steps=e.steps.map(e=>{const t=_e(e.filter,!1),r=1===Object.keys(t).length&&"string"==typeof t.color?t.color:t,o={};return Object.keys(e.with).length&&(o.with=e.with),1!==e.opacity&&(o.opacity=e.opacity),e.skip&&(o.skip=!0),Object.keys(o).length?{filter:r,...o}:r}),r):(e.params&&(r.params=e.params),e.images&&(r.images=e.images),e.graphics&&(r.graphics=e.graphics),e.space&&(r.space=e.space.in===e.space.out?e.space.in:e.space),r.color=e.color,r)}function ke(e,t,r={}){if(e.isContextLost())throw new Error("The WebGL context is lost");const o=Ee(e,r.precision),a=n({version:t.version}),s=[];try{for(const r of t.passes)s.push(Me(e,a,r.fragment,r.name))}catch(t){for(const t of s)e.deleteProgram(t);throw t}const i=(e,t)=>e.bind&&Object.hasOwn(e.bind,t)?e.bind[t]:t,c=s.map(()=>new Map),l=(t,r)=>(c[t].has(r)||c[t].set(r,e.getUniformLocation(s[t],r)),c[t].get(r)),h=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,h),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),e.STATIC_DRAW);const u={texture:e.createTexture(),framebuffer:null};e.bindTexture(e.TEXTURE_2D,u.texture),ve(e);const p=new Map,f=new Map,m=e.createTexture();e.bindTexture(e.TEXTURE_2D,m),ve(e),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([255,255,255,255]));const d=e.createTexture();e.bindTexture(e.TEXTURE_2D,d),ve(e),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([0,0,0,0]));const g=[];let $=0,w=0;const y={passes:t.passes,get precision(){return o.name},setImage(t,r){if("string"!=typeof t&&(r=t,t=null),t&&"source"!==t&&null==r)return p.has(t)&&e.deleteTexture(p.get(t)),p.delete(t),f.delete(t),y;let o=u.texture;if(t&&"source"!==t&&(p.has(t)||(p.set(t,e.createTexture()),e.bindTexture(e.TEXTURE_2D,p.get(t)),ve(e)),o=p.get(t)),r&&r.data&&r.width&&r.height&&"undefined"!=typeof ImageData&&!(r instanceof ImageData)){const e=r.data,t=e instanceof Float32Array||e instanceof Float64Array,o=e instanceof Uint8ClampedArray?e:Uint8ClampedArray.from(e,t?e=>255*e:void 0);r=new ImageData(o,r.width,r.height)}return e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,r),t&&f.set(t,[r.naturalWidth||r.videoWidth||r.width||1,r.naturalHeight||r.videoHeight||r.height||1]),y},draw({t:r=0}={}){if(e.drawingBufferWidth!==$||e.drawingBufferHeight!==w){$=e.drawingBufferWidth,w=e.drawingBufferHeight;for(const t of g)e.bindTexture(e.TEXTURE_2D,t.texture),e.texImage2D(e.TEXTURE_2D,0,o.internal,$,w,0,e.RGBA,o.type,null)}let n=u;const a=[];return t.passes.forEach((c,y)=>{for(let e=0;e<c.keepInput;e++)a.push(n);const b=y===t.passes.length-1?null:function(t){let r=g.find(e=>!t.includes(e));return r||(r={texture:e.createTexture(),framebuffer:e.createFramebuffer()},e.bindTexture(e.TEXTURE_2D,r.texture),ve(e,o.filter),e.texImage2D(e.TEXTURE_2D,0,o.internal,$,w,0,e.RGBA,o.type,null),e.bindFramebuffer(e.FRAMEBUFFER,r.framebuffer),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r.texture,0),e.checkFramebufferStatus(e.FRAMEBUFFER)!==e.FRAMEBUFFER_COMPLETE&&"byte"!==o.name&&(Object.assign(o,Ee(e,"byte")),e.bindTexture(e.TEXTURE_2D,r.texture),ve(e,o.filter),e.texImage2D(e.TEXTURE_2D,0,o.internal,$,w,0,e.RGBA,o.type,null)),g.push(r)),r}([n,...a]);e.bindFramebuffer(e.FRAMEBUFFER,b?b.framebuffer:null),e.viewport(0,0,$,w);const x=s[y];e.useProgram(x);const _=e.getAttribLocation(x,"position");e.bindBuffer(e.ARRAY_BUFFER,h),e.enableVertexAttribArray(_),e.vertexAttribPointer(_,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,n.texture),e.uniform1i(l(y,"image"),0),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,c.blendKept?a[a.length-1].texture:null),c.blendKept&&e.uniform1i(l(y,"base"),1),c.images.forEach((t,r)=>{if(e.activeTexture(e.TEXTURE2+r),e.bindTexture(e.TEXTURE_2D,"source"===t?u.texture:p.get(i(c,t))??(c.graphics?.[t]?d:m)),e.uniform1i(l(y,`mz_img_${t}`),2+r),!c.placements[t])return;const o=f.get(i(c,t))??[1,1],n=c.placements[t];e.uniform2f(l(y,`mz_size_${t}`),o[0],o[1]),e.uniform4f(l(y,`mz_place_${t}`),Number(n.zoom),Number(n.x),Number(n.y),Number(n.angle))}),e.uniform2f(l(y,"resolution"),$,w),e.uniform1f(l(y,"t"),r),e.uniform1f(l(y,"mz_opacity"),c.opacity);for(const[t,r]of Object.entries(c.params)){const o=c.values[t];"color"===r.type?e.uniform3fv(l(y,t),o.map(Number)):e.uniform1f(l(y,t),Number(o))}e.drawArrays(e.TRIANGLES,0,3),c.blendKept&&a.pop(),n=b}),y},dispose(){for(const t of s)e.deleteProgram(t);e.deleteTexture(u.texture),e.deleteTexture(m),e.deleteTexture(d);for(const t of p.values())e.deleteTexture(t);for(const t of g)e.deleteTexture(t.texture),e.deleteFramebuffer(t.framebuffer);e.deleteBuffer(h)}};return y}function ve(e,t=e.LINEAR){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t)}function Ee(e,t="byte"){const r={name:"byte",internal:e.RGBA,type:e.UNSIGNED_BYTE,filter:e.LINEAR};if("half"!==t&&"float"!==t)return r;if("undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext){if(!e.getExtension("EXT_color_buffer_float"))return r;const o=e.getExtension("OES_texture_float_linear")?e.LINEAR:e.NEAREST;return"float"===t?{name:"float",internal:e.RGBA32F,type:e.FLOAT,filter:o}:{name:"half",internal:e.RGBA16F,type:e.HALF_FLOAT,filter:e.LINEAR}}if("float"===t&&e.getExtension("OES_texture_float")&&e.getExtension("WEBGL_color_buffer_float"))return{name:"float",internal:e.RGBA,type:e.FLOAT,filter:e.getExtension("OES_texture_float_linear")?e.LINEAR:e.NEAREST};const o=e.getExtension("OES_texture_half_float");return o&&e.getExtension("EXT_color_buffer_half_float")?{name:"half",internal:e.RGBA,type:o.HALF_FLOAT_OES,filter:e.getExtension("OES_texture_half_float_linear")?e.LINEAR:e.NEAREST}:r}function Me(e,t,r,o){const n=e.createProgram(),a=[];let s=null;for(const[i,c]of[[e.VERTEX_SHADER,t],[e.FRAGMENT_SHADER,r]]){const t=e.createShader(i);if(a.push(t),e.shaderSource(t,c),e.compileShader(t),!e.getShaderParameter(t,e.COMPILE_STATUS)){s=`${o||"The filter"} does not compile: ${(e.getShaderInfoLog(t)??"").trim()}`;break}e.attachShader(n,t)}s||(e.linkProgram(n),e.getProgramParameter(n,e.LINK_STATUS)||(s=`${o||"The filter"} does not link: ${(e.getProgramInfoLog(n)??"").trim()}`));for(const t of a)e.deleteShader(t);if(s)throw e.deleteProgram(n),new Error(s);return n}const Ae={data:new Float32Array([1,1,1,1]),width:1,height:1},Oe={data:new Float32Array([0,0,0,0]),width:1,height:1},Te={cover:0,fit:1,stretch:2,tile:3};function je(e){return Te[e??"cover"]??0}function Se(e,t){return e-t*Math.floor(e/t)}const Fe=(e,t)=>e<0?0:e>t?t:e;function Re(e,t,r,o,n,a){const s=Math.floor(o),i=Math.floor(n),c=o-s,l=n-i,h=Fe(s,t-1),u=Fe(s+1,t-1),p=Fe(i,r-1),f=Fe(i+1,r-1),m=4*(p*t+h),d=4*(p*t+u),g=4*(f*t+h),$=4*(f*t+u);for(let t=0;t<4;t++){const r=e[m+t]+(e[d+t]-e[m+t])*c,o=e[g+t]+(e[$+t]-e[g+t])*c;a[t]=r+(o-r)*l}return a}function ze(e,t,r){const o=Math.min(Math.max(Math.ceil(e),0),t),n=[];for(let e=-o;e<=o;e++)r(e)&&n.push(e);return n}function Ie(e,t,r,o,n,a,s,i,c=0,l=o){const h=new Float32Array(r*o*3),u=a.length,p=Int32Array.from(a),f=Float64Array.from(s??a.map(()=>1)),m="x"===n?r:o,d=new Int32Array(u);for(let o=c;o<l;o++)for(let a=0;a<r;a++){const s="x"===n?a:o;for(let e=0;e<u;e++){let i=s+p[e];i=i<0?0:i>=m?m-1:i,d[e]=("x"===n?o*r+i:i*r+a)*t}let c=0,l=0,g=0;for(let t=0;t<u;t++){const r=d[t],o=f[t];c+=e[r]*o,l+=e[r+1]*o,g+=e[r+2]*o}const $=3*(o*r+a);h[$]=c/i,h[$+1]=l/i,h[$+2]=g/i}return h}function Ne(e,t,r,o,n,a,s,i=0,c=o){const l=new Float32Array(r*o*3),h="x"===n?r:o,u="x"===n?o:r,p=s-a+1,f=(e,t)=>"x"===n?e*r+t:t*r+e,m=e=>e<0?0:e>=h?h-1:e,[d,g]="x"===n?[i,c]:[0,u],[$,w]="x"===n?[0,h]:[i,c];for(let r=d;r<g;r++){let o=0,n=0,i=0;for(let c=$+a;c<=$+s;c++){const a=f(r,m(c))*t;o+=e[a],n+=e[a+1],i+=e[a+2]}for(let c=$;c<w;c++){const h=3*f(r,c);l[h]=o/p,l[h+1]=n/p,l[h+2]=i/p;const u=f(r,m(c+a))*t,d=f(r,m(c+s+1))*t;o+=e[d]-e[u],n+=e[d+1]-e[u+1],i+=e[d+2]-e[u+2]}}return l}function Ue(e,t,r,o,n,a,s,i,c=0,l=o){const h=new Float32Array(r*o*3),u="x"===n?r:o;for(let o=c;o<l;o++)for(let c=0;c<r;c++){const l="x"===n?c:o;let p=s,f=s,m=s;for(let s=0;s<a.length;s++){let h=l+a[s];h=h<0?0:h>=u?u-1:h;const d=("x"===n?o*r+h:h*r+c)*t;i?(e[d]>p&&(p=e[d]),e[d+1]>f&&(f=e[d+1]),e[d+2]>m&&(m=e[d+2])):(e[d]<p&&(p=e[d]),e[d+1]<f&&(f=e[d+1]),e[d+2]<m&&(m=e[d+2]))}const d=3*(o*r+c);h[d]=p,h[d+1]=f,h[d+2]=m}return h}const Be=(e,t,r)=>e+t*r,Ce=(e,t)=>t>e?t:e,Pe=(e,t)=>t<e?t:e;function Ge(e,t,r,o=0,n=r){const a=new Float32Array(t*r*3);for(let r=o*t;r<n*t;r++)a[3*r]=e[4*r],a[3*r+1]=e[4*r+1],a[3*r+2]=e[4*r+2];return a}const De=(e,t,r,o)=>[Math.max(0,e-r),Math.min(o,t+r)];function Le(e,t,r,o,n,a,s,i){const c=ze(a,i,e=>Math.abs(e)<=a);if(!c.length)return Ge(e,t,r,o,n);const l=c[0],h=c[c.length-1];if(1===s.length)return Ne(e,4,t,r,s[0],l,h,o,n);const[u,p]=De(o,n,h,r);return Ne(Ne(e,4,t,r,"x",l,h,u,p),3,t,r,"y",l,h,o,n)}function qe(e,t,r,o,n,a,s,i){if(!(a>0))return Ge(e,t,r,o,n);const c=3*a,l=ze(c,i,e=>Math.abs(e)<=c),h=l.map(e=>Math.exp(-e*e/(2*a*a))),u=h.reduce((e,t)=>e+t,0);if(1===s.length)return Ie(e,4,t,r,s[0],l,h,u,o,n);const[p,f]=De(o,n,l[l.length-1],r);return Ie(Ie(e,4,t,r,"x",l,h,u,p,f),3,t,r,"y",l,h,u,o,n)}function We(e,t,r,o,n,s,i,c){const l=ze(s,a.square,e=>Math.abs(e)<=s);if(!l.length)return new Float32Array(t*r*3).fill(i);const[h,u]=De(o,n,l[l.length-1],r);return Ue(Ue(e,4,t,r,"x",l,i,c,h,u),3,t,r,"y",l,i,c,o,n)}function Xe(e,t,r,o,n,a){const s=function(e,t,r){const o=new Float32Array(t*r);for(let n=0;n<t*r;n++)o[n]=.299*e[4*n]+.587*e[4*n+1]+.114*e[4*n+2];return o}(e,t,r),i=new Float32Array(t*r);for(let e=o;e<n;e++)for(let o=0;o<t;o++){const n=(n,a)=>s[Fe(e+a,r-1)*t+Fe(o+n,t-1)];i[e*t+o]=a(n)}return i}const He=e=>e(1,-1)+2*e(1,0)+e(1,1)-(e(-1,-1)+2*e(-1,0)+e(-1,1)),Ke=e=>e(-1,1)+2*e(0,1)+e(1,1)-(e(-1,-1)+2*e(0,-1)+e(1,-1)),Ye=e=>4*e(0,0)-e(-1,0)-e(1,0)-e(0,-1)-e(0,1),Je=e=>.5+e(-1,-1)-e(1,1),Ve=e=>Math.hypot(He(e),Ke(e));function Ze(e,t,r,o,n,a,s,i,c,l,h){for(let u=0;u<3;u++){let p=i,f=0;for(const i of a)for(const l of a){const a=s?s(i,l):1;p=c(p,e[4*(Fe(n+l,r-1)*t+Fe(o+i,t-1))+u],a),f+=a}l[u]=h?h(p,f):p}return l}function Qe(e,t,r,o,n,a,s,i,c){for(let l=0;l<3;l++){let h=0,u=0;for(const c of s){const s=i?i(c):1,p="x"===a?Fe(o+c,t-1):o;h+=e[4*(("y"===a?Fe(n+c,r-1):n)*t+p)+l]*s,u+=s}c[l]=h/u}return c}const et=(e,t,r,o,n)=>{const a=4*(o*t+r);return n[0]=e[a],n[1]=e[a+1],n[2]=e[a+2],n};const tt=e=>e<.04045?e/12.92:Math.pow((e+.055)/1.055,2.4),rt=e=>(e=Math.max(e,0))<.0031308?12.92*e:1.055*Math.pow(e,1/2.4)-.055,ot=(e,t,r,o,n)=>{const a=o===e?(t-r)/n:o===t?2+(r-e)/n:4+(e-t)/n;return a/6-Math.floor(a/6)},nt=(e,t)=>{const r=Math.abs(6*(e+t-Math.floor(e+t))-3);return Math.min(Math.max(r-1,0),1)};const at=e=>e<.008856?7.787*e+16/116:Math.cbrt(e),st=e=>e<.206893?(e-16/116)/7.787:e*e*e;var it=Object.freeze({__proto__:null,BLANK:Ae,CLEAR:Oe,at:function(e,t,r){return Number(e[t][r])},at_blur:function(e,t,r,o,n,s,i){return Ze(e,t,r,o,n,ze(s,a.square,e=>Math.abs(e)<=s),null,0,Be,i,(e,t)=>e/t)},at_blurx:function(e,t,r,o,n,s,i){return Qe(e,t,r,o,n,"x",ze(s,a.line,e=>Math.abs(e)<=s),null,i)},at_blury:function(e,t,r,o,n,s,i){return Qe(e,t,r,o,n,"y",ze(s,a.line,e=>Math.abs(e)<=s),null,i)},at_dilate:function(e,t,r,o,n,s,i){return Ze(e,t,r,o,n,ze(s,a.square,e=>Math.abs(e)<=s),null,0,Ce,i)},at_erode:function(e,t,r,o,n,s,i){return Ze(e,t,r,o,n,ze(s,a.square,e=>Math.abs(e)<=s),null,1,Pe,i)},at_gaussian:function(e,t,r,o,n,s,i){if(!(s>0))return et(e,t,o,n,i);const c=3*s;return Ze(e,t,r,o,n,ze(c,a.square,e=>Math.abs(e)<=c),(e,t)=>Math.exp(-(e*e+t*t)/(2*s*s)),0,Be,i,(e,t)=>e/t)},at_gaussianx:function(e,t,r,o,n,s,i){if(!(s>0))return et(e,t,o,n,i);const c=3*s;return Qe(e,t,r,o,n,"x",ze(c,a.line,e=>Math.abs(e)<=c),e=>Math.exp(-e*e/(2*s*s)),i)},at_gaussiany:function(e,t,r,o,n,s,i){if(!(s>0))return et(e,t,o,n,i);const c=3*s;return Qe(e,t,r,o,n,"y",ze(c,a.line,e=>Math.abs(e)<=c),e=>Math.exp(-e*e/(2*s*s)),i)},at_sharpen:function(e,t,r,o,n,a,s){const i=(e,o)=>4*(Fe(o,r-1)*t+Fe(e,t-1)),c=i(o,n),l=i(o-1,n),h=i(o+1,n),u=i(o,n-1),p=i(o,n+1);for(let t=0;t<3;t++)s[t]=e[c+t]+a*(4*e[c+t]-e[l+t]-e[h+t]-e[u+t]-e[p+t]);return s},col_fromhsl:function(e,t,r,o){const n=(1-Math.abs(2*r-1))*t;return o[0]=r-.5*n+n*nt(e,0),o[1]=r-.5*n+n*nt(e,2/3),o[2]=r-.5*n+n*nt(e,1/3),o},col_fromhsv:function(e,t,r,o){return o[0]=r*(1+(nt(e,0)-1)*t),o[1]=r*(1+(nt(e,2/3)-1)*t),o[2]=r*(1+(nt(e,1/3)-1)*t),o},col_fromlab:function(e,t,r,o){const n=(100*e+16)/116,a=n-256*(r-.5)/200,s=.95047*st(n+256*(t-.5)/500),i=st(n),c=1.08883*st(a),l=Math.min(Math.max(3.2404542*s-1.5371385*i-.4985314*c,0),1),h=Math.min(Math.max(-.969266*s+1.8760108*i+.041556*c,0),1),u=Math.min(Math.max(.0556434*s-.2040259*i+1.0572252*c,0),1);return o[0]=rt(l),o[1]=rt(h),o[2]=rt(u),o},col_fromlinear:function(e,t,r,o){return o[0]=rt(e),o[1]=rt(t),o[2]=rt(r),o},col_fromoklab:function(e,t,r,o){let n=e+.3963377774*(t-=.5)+.2158037573*(r-=.5),a=e-.1055613458*t-.0638541728*r,s=e-.0894841775*t-1.291485548*r;n*=n*n,a*=a*a,s*=s*s;const i=Math.min(Math.max(4.0767416621*n-3.3077115913*a+.2309699292*s,0),1),c=Math.min(Math.max(-1.2684380046*n+2.6097574011*a-.3413193965*s,0),1),l=Math.min(Math.max(-.0041960863*n-.7034186147*a+1.707614701*s,0),1);return o[0]=rt(i),o[1]=rt(c),o[2]=rt(l),o},col_fromycbcr:function(e,t,r,o){return t-=.5,r-=.5,o[0]=e+1.402*r,o[1]=e-.344136*t-.714136*r,o[2]=e+1.772*t,o},col_tohsl:function(e,t,r,o){const n=Math.max(e,t,r),a=Math.min(e,t,r),s=n-a,i=.5*(n+a);return o[0]=s>0?ot(e,t,r,n,s):0,o[1]=s>0?s/(1-Math.abs(2*i-1)):0,o[2]=i,o},col_tohsv:function(e,t,r,o){const n=Math.max(e,t,r),a=n-Math.min(e,t,r);return o[0]=a>0?ot(e,t,r,n,a):0,o[1]=n>0?a/n:0,o[2]=n,o},col_tolab:function(e,t,r,o){const n=tt(e),a=tt(t),s=tt(r),i=at((.4124564*n+.3575761*a+.1804375*s)/.95047),c=at(.2126729*n+.7151522*a+.072175*s),l=at((.0193339*n+.119192*a+.9503041*s)/1.08883);return o[0]=(116*c-16)/100,o[1]=.5+500*(i-c)/256,o[2]=.5+200*(c-l)/256,o},col_tolinear:function(e,t,r,o){return o[0]=tt(e),o[1]=tt(t),o[2]=tt(r),o},col_tooklab:function(e,t,r,o){const n=tt(e),a=tt(t),s=tt(r),i=Math.cbrt(.4122214708*n+.5363325363*a+.0514459929*s),c=Math.cbrt(.2119034982*n+.6806995451*a+.1073969566*s),l=Math.cbrt(.0883024619*n+.2817188376*a+.6299787005*s);return o[0]=.2104542553*i+.793617785*c-.0040720468*l,o[1]=.5+1.9779984951*i-2.428592205*c+.4505937099*l,o[2]=.5+.0259040371*i+.7827717662*c-.808675766*l,o},col_toycbcr:function(e,t,r,o){const n=.299*e+.587*t+.114*r;return o[0]=n,o[1]=.5+.5643*(r-n),o[2]=.5+.7132*(e-n),o},convolve:function(e,t,r,o,n,a,s,i,c,l,h,u,p,f,m){const d=(e,a)=>4*(Fe(n+a,r-1)*t+Fe(o+e,t-1)),g=[[a,-1,-1],[s,0,-1],[i,1,-1],[c,-1,0],[l,0,0],[h,1,0],[u,-1,1],[p,0,1],[f,1,1]];for(let t=0;t<3;t++){let r=0;for(const[o,n,a]of g)r+=o*e[d(n,a)+t];m[t]=r}return m},factorial:function(e){let t=1;for(let r=2;r<=170&&!(r>e);r++)t*=r;return t},fmod:Se,gcd:function(e,t){e=Math.abs(e),t=Math.abs(t);for(let r=0;r<64&&0!==t;r++){const r=Se(e,t);e=t,t=r}return e},perm:function(e,t){let r=1;for(let o=0;o<170&&!(o>=t);o++)r*=e-o;return r},picture:function(e,t,r,o,n,a,s,i,c,l,h,u,p){let f,m;0===l?f=m=Math.max(o/t,n/r):1===l?f=m=Math.min(o/t,n/r):2===l?(f=o/t,m=n/r):f=m=1,f*=a,m*=a;const d=h+.5-s*o,g=u+.5-i*n,$=Math.cos(c),w=Math.sin(c);let y=($*d+w*g)/f+.5*t,b=($*g-w*d)/m+.5*r;if(3===l)y=Se(y,t),b=Se(b,r);else if(y<0||b<0||y>t||b>r)return p[0]=p[1]=p[2]=p[3]=0,p;return Re(e,t,r,y-.5,b-.5,p)},placeCode:je,plane_blur:function(e,t,r,o,n,s){return Le(e,t,r,o,n,s,["x","y"],a.square)},plane_blurx:function(e,t,r,o,n,s){return Le(e,t,r,o,n,s,["x"],a.line)},plane_blury:function(e,t,r,o,n,s){return Le(e,t,r,o,n,s,["y"],a.line)},plane_dilate:function(e,t,r,o,n,a){return We(e,t,r,o,n,a,0,!0)},plane_emboss:function(e,t,r,o,n){return Xe(e,t,r,o,n,Je)},plane_erode:function(e,t,r,o,n,a){return We(e,t,r,o,n,a,1,!1)},plane_gaussian:function(e,t,r,o,n,s){return qe(e,t,r,o,n,s,["x","y"],a.square)},plane_gaussianx:function(e,t,r,o,n,s){return qe(e,t,r,o,n,s,["x"],a.line)},plane_gaussiany:function(e,t,r,o,n,s){return qe(e,t,r,o,n,s,["y"],a.line)},plane_laplacian:function(e,t,r,o,n){return Xe(e,t,r,o,n,Ye)},plane_sharpen:function(e,t,r,o,n,a){const s=new Float32Array(t*r*3);for(let i=o;i<n;i++)for(let o=0;o<t;o++){const n=(e,o)=>4*(Fe(o,r-1)*t+Fe(e,t-1)),c=n(o,i),l=n(o-1,i),h=n(o+1,i),u=n(o,i-1),p=n(o,i+1);for(let r=0;r<3;r++)s[3*(i*t+o)+r]=e[c+r]+a*(4*e[c+r]-e[l+r]-e[h+r]-e[u+r]-e[p+r])}return s},plane_sobel:function(e,t,r,o,n){return Xe(e,t,r,o,n,Ve)},plane_sobelx:function(e,t,r,o,n){return Xe(e,t,r,o,n,He)},plane_sobely:function(e,t,r,o,n){return Xe(e,t,r,o,n,Ke)},random:function(e,t,r,o){const n=43758.5453*Math.sin(12.9898*(e+.5)+78.233*(r-t-.5)+37.719*o);return n-Math.floor(n)},root:function(e,t){return 2===e?Math.sqrt(t):3===e?Math.sign(t)*Math.pow(Math.abs(t),1/3):Math.pow(t,1/e)},round:function(e,t){const r=Math.pow(10,t);return Math.sign(e)*Math.floor(Math.abs(e)*r+.5)/r},sample:Re,sampleOrZero:function(e,t,r,o,n,a){const s=o+.5,i=n+.5;return s<0||i<0||s>t||i>r?(a[0]=a[1]=a[2]=a[3]=0,a):Re(e,t,r,o,n,a)},scratch:function(){return new Float64Array(4)},smoothstep:function(e,t,r){const o=Math.min(Math.max((r-e)/(t-e),0),1);return o*o*(3-2*o)}});const ct="\\:",lt=Object.keys(it).filter(e=>"function"==typeof it[e]),ht=e=>Object.assign(Object.create(null),e),ut=ht({r:"$r",g:"$g",b:"$b",a:"$a",x:"$x",y:"$y",px:"$px",py:"$py",w:"$w",h:"$h",t:"$t",gray:"$gray"}),pt=ht({pi:"Math.PI","π":"Math.PI",e:"Math.E",tau:"(2 * Math.PI)","τ":"(2 * Math.PI)","∞":"Infinity","-∞":"(-Infinity)"}),ft=ht({sqrt:1,abs:1,floor:1,ceil:1,ln:"log",sin:1,cos:1,tan:1,arcsin:"asin",arccos:"acos",arctan:"atan",sinh:1,cosh:1,tanh:1,arcsinh:"asinh",arccosh:"acosh",arctanh:"atanh",sign:1,exp:1,exp2:e=>`Math.pow(2, ${e})`,log2:1,expm1:e=>`(Math.exp(${e}) - 1)`,loglog:e=>`Math.log(Math.log(${e}))`,logloglog:e=>`Math.log(Math.log(Math.log(${e})))`,csc:e=>`(1 / Math.sin(${e}))`,sec:e=>`(1 / Math.cos(${e}))`,cot:e=>`(1 / Math.tan(${e}))`,fract:e=>`(${e} - Math.floor(${e}))`,radians:e=>`(${e} * 0.017453292519943295)`,degrees:e=>`(${e} * 57.29577951308232)`,inversesqrt:e=>`(1 / Math.sqrt(${e}))`,atan2:(e,t)=>`Math.atan2(${e}, ${t})`,pow:(e,t)=>`Math.pow(${e}, ${t})`,mod:(e,t)=>`(${e} - ${t} * Math.floor(${e} / ${t}))`,step:(e,t)=>`(${t} < ${e} ? 0 : 1)`,clamp:(e,t,r)=>`Math.min(Math.max(${e}, ${t}), ${r})`,mix:(e,t,r)=>`(${e} + (${t} - ${e}) * ${r})`,smoothstep:(e,t,r)=>`$h_smoothstep(${e}, ${t}, ${r})`}),mt=ht({atan2:2,pow:2,mod:2,step:2,clamp:3,mix:3,smoothstep:3}),dt=ht({blur:3,blurx:3,blury:3,gaussian:3,gaussianx:3,gaussiany:3,dilate:3,erode:3,sharpen:3,sobel:1,sobelx:1,sobely:1,laplacian:1,emboss:1}),gt=(e,t)=>({kind:e,c:t}),$t=e=>gt("f",[e]),wt=e=>gt("b",[e]),yt=e=>1===e.length?$t(e[0]):gt("v",e),bt=(e,t=0)=>"b"===e.kind?`(${e.c[0]} ? 1 : 0)`:"f"===e.kind?e.c[0]:e.c[t]??e.c[0],xt=e=>"v"===e.kind?e.c.length:1;class _t extends Error{}function kt(e){if(e.blendKept)return{blend:!0,source:""};const t=e.params??{},r=new Set([...Object.keys(e.placements??{}),"source","selection"]),o=new vt(t,r,e.space??"srgb");o.graphics=new Set(Object.keys(e.graphics??{})),o.bind=ht(e.bind??{});const n="string"==typeof e.color?{rgba:e.color}:e.color,a=(o,n)=>{const a=[...s,...Object.keys(e.placements??{})],h=[...i,...Object.keys(t)];return c(l(o,{names:a,values:h,blocks:null}),r,{whole:n})};for(const e of["rgba","rgb","r","g","b","a"]){if(!n[e])continue;let t;try{t=a(n[e],"rgba"===e)}catch(e){throw new _t(e.message)}o.channel(e,t)}const u=o.source();h(u,{variables:/^\$\w+$/,indexable:/^\$[A-Z]\w*$/,strings:!1});const p=new Function(...o.parameters(),u);return{source:u,uses:o.uses,pictures:[...o.pictureNames],run(e){p(...o.arguments(e))}}}class vt{constructor(e,t,r="srgb"){this.params=e,this.pictures=t,this.space="srgb"===r?null:r,this.pre=[],this.body=[],this.n=0,this.uses=new Set,this.pictureNames=new Set,this.perPixel=new Map,this.planes=new Map,this.scratch=0}temp(e,t=this.body){const r="$v"+this.n++;return t.push(`let ${r} = ${e};`),r}keep(e,t=this.body){return gt(e.kind,e.c.map(e=>/^[\w$.]+$|^\(?-?[\d.e+]+\)?$/.test(e)?e:this.temp(e,t)))}fail(e){throw new _t(e)}leaf(e){if("number"===e.type)return $t(`(${e.value.replace(/\.+$/,"")})`);"string"===e.type&&this.fail("a filter has no text: numbers and colours only");const t=e.value,r=/^(-?(?:\d+\.?\d*|\.\d+))%$/.exec(t);if(r)return $t(`(${r[1]} / 100)`);if("t"===t&&this.uses.add("t"),ut[t])return $t(ut[t]);if("rgb"===t)return yt(["$r","$g","$b"]);if("unchanged"===t)return $t("$u");if("selected"===t)return $t(this.pictureHere("selection").c[0]);if(pt[t])return $t(pt[t]);if("true"===t||"false"===t)return wt(t);if(Object.prototype.hasOwnProperty.call(this.params,t)){const e=`$p_${t}`;return"color"===this.params[t].type?yt([`${e}_0`,`${e}_1`,`${e}_2`]):$t(e)}if(this.pictures.has(t)){const e=this.pictureHere(t);return yt(e.c.slice(0,3))}if(t.startsWith("mz_px_")&&this.pictures.has(t.slice(6)))return this.pictureHere(t.slice(6));this.fail(`unknown name "${t}"`)}pictureHere(e){if(!this.perPixel.has(e)){const t=this.sampler(e,"$px","$py");this.perPixel.set(e,this.keep(t))}return this.perPixel.get(e)}sampler(e,t,r){const o=this.scratchArray();return"source"===e?(this.uses.add("source"),this.body.push(`$h_sample($S, $w, $h, ${t}, ${r}, ${o});`)):(this.pictureNames.add(e),this.body.push(`$h_picture($Q_${e}, $qw_${e}, $qh_${e}, $w, $h, $qz_${e}, $qx_${e}, $qy_${e}, $qa_${e}, $qm_${e}, ${t}, ${r}, ${o});`)),this.space&&"selection"!==e&&this.body.push(`$h_col_to${this.space}(${o}[0], ${o}[1], ${o}[2], ${o});`),yt([0,1,2,3].map(e=>`${o}[${e}]`))}scratchArray(){const e="$T"+this.scratch++;return this.pre.push(`let ${e} = $h_scratch();`),e}value(e){return"op"===e.type?this.op(e):this.leaf(e)}op(e){const{op:t,args:r}=e,o=t.startsWith(ct)?t.slice(2):null;if(null!==o)return this.call(o,r,e);const n=()=>r.map(e=>this.value(e));switch(t){case"+":case"-":case"*":case"/":{const[e,r]=n();return this.componentwise([e,r],(e,r)=>`(${e} ${t} ${r})`)}case"neg":return this.componentwise(n(),e=>`(-${e})`);case"^":return this.power(r);case"mod":return this.componentwise(n(),ft.mod);case"<":case">":case"≤":case"≥":{const[e,r]=n(),o={"≤":"<=","≥":">="}[t]??t;return wt(`(${bt(e)} ${o} ${bt(r)})`)}case"=":case"===":case"≠":case"≠=":case"≡":{const[e,r]=n(),o=Math.max(xt(e),xt(r)),a=Array.from({length:o},(t,o)=>`${bt(e,o)} === ${bt(r,o)}`).join(" && ");return wt("≠"===t||"≠="===t?`!(${a})`:`(${a})`)}case"≈":{const[e,t]=n();return wt(`(Math.abs(${bt(e)} - ${bt(t)}) < 1e-5)`)}case"&":{const[e,t]=n();return wt(`(${this.truth(e)} && ${this.truth(t)})`)}case"|":{const[e,t]=n();return wt(`(${this.truth(e)} || ${this.truth(t)})`)}case"\\xor":{const[e,t]=n();return wt(`(${this.truth(e)} !== ${this.truth(t)})`)}case"\\nand":{const[e,t]=n();return wt(`!(${this.truth(e)} && ${this.truth(t)})`)}case"\\nor":{const[e,t]=n();return wt(`!(${this.truth(e)} || ${this.truth(t)})`)}case"\\not":{const[e]=n();return wt(`!${this.truth(e)}`)}case"?:":return this.ternary(r);case"max":case"min":return this.componentwise(n(),(...e)=>`Math.${t}(${e.join(", ")})`);case"sum":return this.componentwise(n(),(...e)=>`(${e.join(" + ")})`);case"prod":return this.componentwise(n(),(...e)=>`(${e.join(" * ")})`);case"mean":return this.componentwise(n(),(...e)=>`((${e.join(" + ")}) / ${e.length})`);case"()":case"[]":case"{}":case"(]":case"[)":{const e=n().flatMap(e=>"b"===e.kind?[bt(e)]:e.c.map((t,r)=>bt(e,r)));return e.length>4&&this.fail("a colour has at most 4 values (r, g, b, a)"),yt(e)}case"!":return this.componentwise(n(),e=>`$h_factorial(${e})`);case"perm":return this.componentwise(n(),(e,t)=>`$h_perm(${e}, ${t})`);case"comb":return this.componentwise(n(),(e,t)=>`($h_perm(${e}, ${t}) / $h_factorial(${t}))`);case"gcd":return this.componentwise(n(),(...e)=>e.reduce((e,t)=>`$h_gcd(${e}, ${t})`));case"round":{const[e,t]=n();return this.componentwise([e,t],(e,t)=>`$h_round(${e}, ${t})`)}case"log":{const[e,t]=n();return this.componentwise([e,t],(e,t)=>`(Math.log(${t}) / Math.log(${e}))`)}case"root":{const[e,t]=n();return this.componentwise([e,t],(e,t)=>`$h_root(${e}, ${t})`)}case"∈":case"∉":return this.membership(e);case"random":return this.random();case"_":{const[e,t]=r;if("symbol"===e.type&&("number"===t.type||"symbol"===t.type))return this.leaf({type:"symbol",value:`${e.value}_${t.value}`});break}}if(ft[t])return this.builtin(t,n());this.fail(`"${t}" isn't available in a filter`)}truth(e){return"b"===e.kind?e.c[0]:`(${bt(e)} !== 0)`}componentwise(e,t){const r=e.map(xt),o=Math.max(...r),n=new Set(r.filter(e=>e>1));n.size>1&&this.fail(`can't combine vectors of ${[...n].join(" and ")} values`);const a=Array.from({length:o},(r,o)=>t(...e.map(e=>bt(e,o))));return this.keep(yt(a))}builtin(e,t){const r=ft[e];if(mt[e]&&t.length!==mt[e]&&this.fail(`${e}() takes ${mt[e]} values`),"function"==typeof r)return this.componentwise(t,r);const o=1===r?e:r;return this.componentwise(t,(...e)=>`Math.${o}(${e.join(", ")})`)}power([e,t]){const r="number"===t.type&&/^-?\d+$/.test(t.value)?Number(t.value):null,o=this.keep(this.value(e)),n=e=>this.componentwise([o],t=>Array(e).fill(t).join(" * "));return 0===r?this.componentwise([o],()=>"1"):null!==r&&r>=1&&r<=4?n(r):null!==r&&r<=-1&&r>=-4?this.componentwise([n(-r)],e=>`(1 / ${e})`):"symbol"===e.type&&"e"===e.value?this.componentwise([this.value(t)],e=>`Math.exp(${e})`):"number"===e.type&&"2"===e.value?this.componentwise([this.value(t)],e=>`Math.pow(2, ${e})`):this.componentwise([o,this.value(t)],(e,t)=>`Math.pow(${e}, ${t})`)}ternary([e,t,r]){const o=this.truth(this.value(e)),n=e=>"symbol"===e.type&&"unchanged"===e.value;let a=n(t)?null:this.value(t),s=n(r)?null:this.value(r);const i=e=>"b"===e.kind?wt("($u > 0.5)"):"f"===e.kind?$t("$u"):yt(["$k0","$k1","$k2","$k3"].slice(0,4===e.c.length?4:3));if(!a&&!s)return $t("$u");if(a||(a=i(s)),s||(s=i(a)),"b"===a.kind&&"b"===s.kind)return wt(this.temp(`(${o} ? ${a.c[0]} : ${s.c[0]})`));const c=Math.max(xt(a),xt(s)),l=Array.from({length:c},(e,t)=>this.temp(`(${o} ? ${bt(a,t)} : ${bt(s,t)})`));return yt(l)}membership(e){const[t,r]=e.args,o=bt(this.value(t)),n="∉"===e.op;let a;if("op"===r.type&&["()","[]","(]","[)"].includes(r.op)&&2===r.args.length){const[e,t]=r.args.map(e=>bt(this.value(e)));a=`(${o} ${"["===r.op[0]?">=":">"} ${e} && ${o} ${"]"===r.op[1]?"<=":"<"} ${t})`}else"op"===r.type&&"{}"===r.op?a=`(${r.args.map(e=>`${o} === ${bt(this.value(e))}`).join(" || ")})`:"symbol"===r.type&&["ℝ","ℤ","ℕ"].includes(r.value)?a={"ℝ":`Number.isFinite(${o})`,"ℤ":`Number.isInteger(${o})`,"ℕ":`(Number.isInteger(${o}) && ${o} > 0)`}[r.value]:this.fail("∈ needs an interval [a, b], a set {…}, ℝ, ℤ or ℕ");return wt(n?`!${a}`:a)}random(){return this.uses.add("random"),$t(this.temp("$h_random($px, $py, $h, ++$seed)"))}call(e,t,r){const o=()=>t.map(e=>this.value(e));if(e.startsWith("mz_sample_")){const t=e.slice(10),[r,n]=o(),[a,s]=n?[bt(r),bt(n)]:[bt(r,0),bt(r,1)];if("image"===t){const e=this.scratchArray();return this.body.push(`$h_sampleOrZero($I, $w, $h, ${a}, ${s}, ${e});`),this.keep(yt([0,1,2,3].map(t=>`${e}[${t}]`)))}return this.pictures.has(t)||this.fail(`unknown picture "${t}"`),this.keep(this.sampler(t,a,s))}if(e.startsWith("mz_at_")){const t=e.slice(6),[r,n]=o(),[a,s]=n?[bt(r),bt(n)]:[bt(r,0),bt(r,1)];if("image"===t){const e=this.scratchArray();return this.body.push(`$h_sampleOrZero($I, $w, $h, ${a}, ${s}, ${e});`),yt([0,1,2].map(t=>`${e}[${t}]`))}return this.pictures.has(t)||this.fail(`unknown picture "${t}"`),this.keep(yt(this.sampler(t,a,s).c.slice(0,3)))}if(e.startsWith("mz_width_")||e.startsWith("mz_height_")){const t=e.replace(/^mz_(width|height)_/,"");return this.pictureNames.add(t),$t(e.startsWith("mz_width_")?`$qw_${t}`:`$qh_${t}`)}switch(e){case"pixel":{const[e,t]=o().map(e=>bt(e)),r=this.scratchArray();return this.body.push(`$h_sample($I, $w, $h, ${e}, ${t}, ${r});`),this.keep(yt([0,1,2,3].map(e=>`${r}[${e}]`)))}case"red":case"green":case"blue":case"alpha":case"luma":{let r;2===t.length?r=this.call("pixel",t):1===t.length?r=this.value(t[0]):this.fail(`${e}() takes a colour, or a position px, py`);const o={red:0,green:1,blue:2,alpha:3}[e];return"luma"===e?$t(`(${bt(r,0)} * 0.299 + ${bt(r,1)} * 0.587 + ${bt(r,2)} * 0.114)`):"alpha"===e&&3===xt(r)?$t("1"):$t(bt(r,o))}case"length":{const[e]=o();return $t(`Math.sqrt(${e.c.map((t,r)=>`${bt(e,r)} * ${bt(e,r)}`).join(" + ")})`)}case"distance":{const[e,t]=o(),r=this.componentwise([e,t],(e,t)=>`(${e} - ${t})`);return $t(`Math.sqrt(${r.c.map(e=>`${e} * ${e}`).join(" + ")})`)}case"dot":{const[e,t]=o(),r=Math.max(xt(e),xt(t));return $t(`(${Array.from({length:r},(r,o)=>`${bt(e,o)} * ${bt(t,o)}`).join(" + ")})`)}case"normalize":{const[e]=o(),t=this.temp(`Math.sqrt(${e.c.map((t,r)=>`${bt(e,r)} * ${bt(e,r)}`).join(" + ")})`);return this.componentwise([e],e=>`(${e} / ${t})`)}case"cross":{const[e,t]=o();3===xt(e)&&3===xt(t)||this.fail("cross() takes two colours (3 values each)");const[r,n,a]=e.c,[s,i,c]=t.c;return this.keep(yt([`(${n} * ${c} - ${a} * ${i})`,`(${a} * ${s} - ${r} * ${c})`,`(${r} * ${i} - ${n} * ${s})`]))}case"convolve":{const e=o().map(e=>bt(e));9!==e.length&&this.fail("convolve() takes 9 numbers: the 3×3 kernel, row by row");const t=this.scratchArray();return this.body.push(`$h_convolve($I, $w, $h, $px, $py, ${e.join(", ")}, ${t});`),yt([0,1,2].map(e=>`${t}[${e}]`))}case"mz_zoom":case"mz_shift":case"mz_rotate":case"mz_crop":case"mz_tile":case"mz_flipx":case"mz_flipy":return this.geometry(e.slice(3),o().map(e=>bt(e)));case"tolinear":case"fromlinear":case"tohsv":case"fromhsv":case"tohsl":case"fromhsl":case"tolab":case"fromlab":case"tooklab":case"fromoklab":case"toycbcr":case"fromycbcr":{const t=o(),r=3===t.length?t.map(e=>bt(e)):[0,1,2].map(e=>bt(t[0],e));1!==t.length&&3!==t.length&&this.fail(`${e}() takes a colour`);const n=this.scratchArray();return this.body.push(`$h_col_${e}(${r.join(", ")}, ${n});`),this.keep(yt([0,1,2].map(e=>`${n}[${e}]`)))}case"random":return this.random();case"exp":case"exp2":case"log2":case"sign":case"fract":case"radians":case"degrees":case"inversesqrt":case"pow":case"mod":case"step":case"clamp":case"mix":case"smoothstep":case"abs":case"floor":case"ceil":case"sqrt":case"sin":case"cos":case"tan":return this.builtin(e,o());case"asin":return this.builtin("arcsin",o());case"acos":return this.builtin("arccos",o());case"atan":return 2===t.length?this.builtin("atan2",o()):this.builtin("arctan",o());case"log":return this.builtin("ln",o());case"max":case"min":return this.componentwise(o(),(...t)=>`Math.${e}(${t.join(", ")})`)}if(dt[e])return this.neighbourhood(e,t);this.fail(`unknown function "${e}"`)}geometry(e,t){const r=(e,t)=>this.keep(yt([e,t]));switch(e){case"zoom":{const[e,o="0.5",n="0.5"]=t,a=r(`(${o} * $w - 0.5)`,`(${n} * $h - 0.5)`);return r(`(${a.c[0]} + ($px - ${a.c[0]}) / ${e})`,`(${a.c[1]} + ($py - ${a.c[1]}) / ${e})`)}case"shift":{const[e,o]=t;return r(`($h_fmod($px - ${e} + 0.5, $w) - 0.5)`,`($h_fmod($py - ${o} + 0.5, $h) - 0.5)`)}case"rotate":{const[e,o="0.5",n="0.5"]=t,a=r(`(${o} * $w - 0.5)`,`(${n} * $h - 0.5)`),s=r(`($px - ${a.c[0]})`,`($py - ${a.c[1]})`),i=this.keep(yt([`Math.cos(${e})`,`Math.sin(${e})`]));return r(`(${a.c[0]} + ${i.c[0]} * ${s.c[0]} + ${i.c[1]} * ${s.c[1]})`,`(${a.c[1]} + ${i.c[0]} * ${s.c[1]} - ${i.c[1]} * ${s.c[0]})`)}case"crop":{const[e,o,n,a]=t;return r(`((${e} + (${n} - ${e}) * ($px + 0.5) / $w) * $w - 0.5)`,`((${o} + (${a} - ${o}) * ($py + 0.5) / $h) * $h - 0.5)`)}case"tile":{const[e,o=e]=t;return r(`($h_fmod(($px + 0.5) * ${e}, $w) - 0.5)`,`($h_fmod(($py + 0.5) * ${o}, $h) - 0.5)`)}case"flipx":return r("($w - 1 - $px)","$py");case"flipy":return r("$px","($h - 1 - $py)")}this.fail(`unknown geometry ${e}`)}neighbourhood(e,t){const r=dt[e];if(t.every(e=>this.isUniform(e))){const o=t.map(e=>bt(this.uniformValue(e))),n=`${e}(${o.join(",")})`;if(!this.planes.has(n)){const t=`$N${this.planes.size}`;this.pre.push(`let ${t} = $h_plane_${e}($I, $w, $h, $y0, $y1${o.map(e=>`, ${e}`).join("")});`),this.planes.set(n,t)}const a=this.planes.get(n);return 3===r?yt([0,1,2].map(e=>`${a}[$j3 + ${e}]`)):$t(`${a}[$j]`)}const o=t.map(e=>bt(this.value(e)));if(1===r)return $t(this.temp(`$h_at_${e}($I, $w, $h, $px, $py${o.map(e=>`, ${e}`).join("")})`));const n=this.scratchArray();return this.body.push(`$h_at_${e}($I, $w, $h, $px, $py${o.map(e=>`, ${e}`).join("")}, ${n});`),yt([0,1,2].map(e=>`${n}[${e}]`))}isUniform(e){return"number"===e.type||("symbol"===e.type?["w","h","t"].includes(e.value)||Boolean(pt[e.value])||Object.prototype.hasOwnProperty.call(this.params,e.value)&&"color"!==this.params[e.value].type:"op"===e.type&&!e.op.startsWith(ct)&&"random"!==e.op&&e.args.every(e=>this.isUniform(e)))}uniformValue(e){const t=this.body;this.body=this.pre;try{return this.value(e)}finally{this.body=t}}channel(e,t){const r="rgba"===e||"rgb"===e?"$gray":`$c${"rgba".indexOf(e)}`;this.body.push(`$u = ${r}; $k0 = $c0; $k1 = $c1; $k2 = $c2; $k3 = $c3;`);const o=this.value(t),n=xt(o),a=e=>bt(o,e);if("rgba"===e){2===n&&this.fail("a colour is one number (grey), three (r, g, b) or four (r, g, b, a) — not two");const e=1===n?[a(0),a(0),a(0),"1"]:3===n?[a(0),a(1),a(2),"1"]:[0,1,2,3].map(a);this.body.push(`$c0 = ${e[0]}; $c1 = ${e[1]}; $c2 = ${e[2]}; $c3 = ${e[3]};`)}else if("rgb"===e){2===n&&this.fail("a colour is one number (grey), three (r, g, b) or four — not two");const e=1===n?[a(0),a(0),a(0)]:[a(0),a(1),a(2)];this.body.push(`$c0 = ${e[0]}; $c1 = ${e[1]}; $c2 = ${e[2]};`)}else{const t="rgba".indexOf(e),r=1===n?a(0):3===n&&"a"===e?"1":a(t);this.body.push(`$c${t} = ${r};`)}}parameters(){return["$I","$O","$S","$w","$h","$t","$P","$op","$y0","$y1",...[...this.pictureNames].flatMap(e=>[`$Q_${e}`,`$qw_${e}`,`$qh_${e}`,`$qz_${e}`,`$qx_${e}`,`$qy_${e}`,`$qa_${e}`,`$qm_${e}`]),...lt.map(e=>`$h_${e}`)]}arguments(e){const t=[...this.pictureNames];return[e.input,e.output,e.source,e.width,e.height,e.t,e.params,e.opacity,e.y0??0,e.y1??e.height,...t.flatMap(t=>{const r=e.pictures[this.bind?.[t]??t]??(this.graphics?.has(t)?Oe:Ae),o=e.placements[t]??{};return[r.data,r.width,r.height,Number(o.zoom??1),Number(o.x??.5),Number(o.y??.5),Number(o.angle??0),je(o.place)]}),...lt.map(e=>it[e])]}source(){return[...Object.entries(this.params).map(([e,t],r)=>"color"===t.type?`let $p_${e}_0 = $P[${r}][0], $p_${e}_1 = $P[${r}][1], $p_${e}_2 = $P[${r}][2];`:`let $p_${e} = $P[${r}];`).map(e=>e.replace(/\$P\[(\d+)\]\[(\d)\]/g,"$h_at($P, $1, $2)")),"let $u = 0, $k0 = 0, $k1 = 0, $k2 = 0, $k3 = 0, $seed = 0, $CS = $h_scratch();",...this.pre,"for (let $py = $y0; $py < $y1; $py++) {"," for (let $px = 0; $px < $w; $px++) {"," let $j = $py * $w + $px, $j3 = $j * 3, $j4 = $j * 4;"," let $r = $I[$j4], $g = $I[$j4 + 1], $b = $I[$j4 + 2], $a = $I[$j4 + 3];"," let $c0 = $r, $c1 = $g, $c2 = $b, $c3 = $a;"," let $x = ($px + 0.5) / $w, $y = ($py + 0.5) / $h;",this.space?` $h_col_from${this.space}($r, $g, $b, $CS); let $gray = $CS[0] * 0.299 + $CS[1] * 0.587 + $CS[2] * 0.114;`:" let $gray = $r * 0.299 + $g * 0.587 + $b * 0.114;"," $seed = $t;",...this.body.map(e=>` ${e}`)," $O[$j4] = $r + ($c0 - $r) * $op;"," $O[$j4 + 1] = $g + ($c1 - $g) * $op;"," $O[$j4 + 2] = $b + ($c2 - $b) * $op;"," $O[$j4 + 3] = $a + ($c3 - $a) * $op;"," }","}"].join("\n")}}function Et(e,t={}){const r="float"===t.precision||"half"===t.precision?"float":"byte",o=e.passes.map(e=>kt(e)),n={};let a=null;const s=t.parallelFrom??25e4,i=void 0===t.workers||"auto"===t.workers?function(){const e="undefined"!=typeof navigator&&navigator.hardwareConcurrency?navigator.hardwareConcurrency:4;return Math.max(0,Math.min(8,e-1))}():Number(t.workers);let c=null,l=null,h=new Map;const u={passes:e.passes,get precision(){return r},sources:o.map(e=>e.source),setImage(e,t){"string"!=typeof e&&(t=e,e=null);const r=At(t);return e&&"source"!==e?n[e]=r:a=r,u},draw({t:t=0,canvas:s=null}={}){if(!a)throw new Error("setImage() first");const{width:i,height:c}=a,l=i*c*4;let h=a.data;const u=[];e.passes.forEach((e,s)=>{for(let t=0;t<e.keepInput;t++)u.push(h);const p=new Float32Array(l);if(e.blendKept){const t=u.pop(),r=e.opacity;for(let e=0;e<l;e++)p[e]=t[e]+(h[e]-t[e])*r}else o[s].run({input:h,output:p,source:a.data,width:i,height:c,t:t,params:Object.keys(e.params??{}).map(t=>e.values[t]),opacity:e.opacity,pictures:n,placements:e.placements??{}});"byte"===r&&Mt(p),h=p});const p=new Uint8ClampedArray(l);for(let e=0;e<l;e++){const t=h[e];p[e]=t>0?t<1?Math.round(255*t):255:0}const f={data:p,width:i,height:c};return s&&(s.width=i,s.height=c,s.getContext("2d").putImageData(new ImageData(p,i,c),0,0)),f},async drawAsync({t:o=0,canvas:p=null}={}){if(!a)throw new Error("setImage() first");const{width:f,height:m}=a;if(i<2||f*m<s)return u.draw({t:o,canvas:p});l??=async function(e,t,r){const o=new URL(r??"./cpu-worker.js",import.meta.url);let n,a=()=>{};if("undefined"!=typeof Worker&&"undefined"!=typeof window){const e=o.origin===location.origin?o:URL.createObjectURL(new Blob([`import ${JSON.stringify(o.href)};`],{type:"text/javascript"}));e!==o&&(a=()=>URL.revokeObjectURL(e)),n=()=>{const t=new Worker(e,{type:"module"});return{send:e=>t.postMessage(e),on:e=>{t.onmessage=t=>e(t.data),t.onerror=t=>e({id:-1,ok:!1,error:t.message})},close:()=>t.terminate()}}}else try{const{Worker:e}=await(import("node:worker_threads"));n=()=>{const t=new e(o);return{send:e=>t.postMessage(e),on:e=>{t.on("message",e),t.on("error",t=>e({id:-1,ok:!1,error:t.message}))},close:()=>t.terminate()}}}catch{return null}const s=Array.from({length:e},n);let i=1;const c=s.map(()=>new Map);s.forEach((e,t)=>e.on(e=>{if(-1===e.id){for(const[,r]of c[t])r.reject(new Error(e.error));return void c[t].clear()}const r=c[t].get(e.id);r&&(c[t].delete(e.id),e.ok?r.resolve(e):r.reject(new Error(e.error)))}));const l=(e,t)=>new Promise((r,o)=>{const n=i++;c[e].set(n,{resolve:r,reject:o}),s[e].send({...t,id:n})}),h={size:e,shared:Tt(),ask:l,broadcast:e=>Promise.all(s.map((t,r)=>l(r,e))),close:()=>{s.forEach(e=>e.close());for(const e of c){for(const[,t]of e)t.reject(new Error("The runner was disposed of while drawing"));e.clear()}}};try{await h.broadcast({type:"init",passes:t.map(({fragment:e,...t})=>t)})}catch(e){throw h.close(),e}finally{a()}return h}(i,e.passes,t.workerUrl).catch(()=>!1);const d=l,g=await d;if(d!==l)throw new Error("The runner was disposed of while drawing");if(c=g,!g)return u.draw({t:o,canvas:p});const $=f*m*4,w=()=>g.shared?new Float32Array(new SharedArrayBuffer(4*$)):new Float32Array($);for(const[e,t]of[["source",a],...Object.entries(n)])h.get(e)!==t&&(await g.broadcast({type:"picture",name:e,picture:g.shared?jt(t):t}),h.set(e,t));let y=g.shared?jt(a).data:a.data;const b=[];for(let t=0;t<e.passes.length;t++){const n=e.passes[t];for(let e=0;e<n.keepInput;e++)b.push(y);const a=w();if(n.blendKept){const e=b.pop();for(let t=0;t<$;t++)a[t]=e[t]+(y[t]-e[t])*n.opacity;"byte"===r&&Mt(a)}else{const e=Object.keys(n.params??{}).map(e=>n.values[e]),s=Ot(m,g.size),i=await Promise.all(s.map(([s,i],c)=>g.ask(c,{type:"run",pass:t,input:y,output:g.shared?a:null,width:f,height:m,t:o,params:e,opacity:n.opacity,placements:n.placements??{},y0:s,y1:i,quantize:"byte"===r})));g.shared||i.forEach((e,t)=>a.set(e.band,s[t][0]*f*4))}y=a}const x=new Uint8ClampedArray($);for(let e=0;e<$;e++){const t=y[e];x[e]=t>0?t<1?Math.round(255*t):255:0}const _={data:x,width:f,height:m};return p&&(p.width=f,p.height=m,p.getContext("2d").putImageData(new ImageData(x,f,m),0,0)),_},get workers(){return c?c.size:0},dispose(){a=null;for(const e of Object.keys(n))delete n[e];l&&l.then(e=>e&&e.close()),l=null,c=null,h=new Map}};return u}function Mt(e){for(let t=0;t<e.length;t++){const r=e[t];e[t]=r>0?r<1?Math.round(255*r)/255:1:0}}function At(e){if(e&&e.data&&e.width&&e.height){const t=e.data,r=t instanceof Float32Array||t instanceof Float64Array?1:1/255,o=new Float32Array(e.width*e.height*4);for(let e=0;e<o.length;e++)o[e]=t[e]*r;return{data:o,width:e.width,height:e.height}}if("undefined"!=typeof document||"undefined"!=typeof OffscreenCanvas){const t=e.naturalWidth||e.videoWidth||e.width,r=e.naturalHeight||e.videoHeight||e.height;if(!t||!r)throw new Error("setImage: the picture has no size yet (not loaded?)");const o=("undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(t,r):Object.assign(document.createElement("canvas"),{width:t,height:r})).getContext("2d",{willReadFrequently:!0});return o.drawImage(e,0,0,t,r),At(o.getImageData(0,0,t,r))}throw new Error("setImage: give ImageData or { data, width, height }")}function Ot(e,t){const r=[];for(let o=0;o<t;o++){const n=Math.floor(e*o/t),a=Math.floor(e*(o+1)/t);a>n&&r.push([n,a])}return r}const Tt=()=>"undefined"!=typeof SharedArrayBuffer&&("undefined"==typeof crossOriginIsolated||!0===crossOriginIsolated);function jt(e){if(e.data.buffer instanceof(globalThis.SharedArrayBuffer??Object))return e;if(e.shared)return e.shared;const t=new Float32Array(new SharedArrayBuffer(e.data.byteLength));return t.set(e.data),e.shared={data:t,width:e.width,height:e.height},e.shared}function St({webgl:e=!1,prefer:t="auto"}={}){return"cpu"===t?{engine:"cpu",reason:"asked for the CPU"}:e?{engine:"gpu",reason:"gpu"===t?"asked for the GPU":"WebGL is here"}:{engine:"cpu",reason:"no WebGL here"}}function Ft(e,t={}){const r=St({webgl:Boolean(t.gl),prefer:t.prefer});if("gpu"===r.engine)try{return{runner:ke(t.gl,e,{precision:t.precision}),...r}}catch(r){if("gpu"===t.prefer)throw r;return{runner:Et(e,t),engine:"cpu",reason:`the GPU refused the shader (${r.message.split("\n")[0]})`}}return{runner:Et(e,t),...r}}const Rt=[{name:"Wave",group:"Shape & motion",description:"Rows slide back and forth as t advances",params:{amplitude:{default:8,min:0,max:40},wavelength:{default:10,min:1,max:60},speed:{default:5,min:1,max:30}},color:"pixel(px + amplitude sin(py / wavelength + t / speed), py)"},{name:"Invert",group:"Colour & tone",color:"(1 - r, 1 - g, 1 - b)"},{name:"Grayscale",group:"Colour & tone",color:"gray"},{name:"Threshold",group:"Colour & tone",params:{cutoff:.5},color:"if gray > cutoff then 1 else 0"},{name:"Posterize",group:"Colour & tone",params:{levels:{default:4,min:2,max:16,step:1}},color:"min(floor(rgb * levels) / (levels - 1), 1)"},{name:"Brightness & contrast",group:"Colour & tone",params:{brightness:{default:0,min:-.5,max:.5},contrast:{default:1,min:0,max:3}},color:"(rgb - 0.5) contrast + 0.5 + brightness"},{name:"Tint",group:"Colour & tone",params:{tint:[1,.85,.7]},color:"rgb * tint"},{name:"Sepia",group:"Colour & tone",color:"(0.393r + 0.769g + 0.189b, 0.349r + 0.686g + 0.168b, 0.272r + 0.534g + 0.131b)"},{name:"Colour circle",group:"Colour & tone",description:"Black and white, except a soft circle that keeps its colour",params:{across:{default:.5,min:0,max:1,label:"where, across"},down:{default:.5,min:0,max:1,label:"where, down"},radius:{default:.3,min:0,max:1},softness:{default:.08,min:0,max:.5}},notes:["The colour stays inside a circle and fades to grey over the softness. Sizes are parts of the picture's shorter side, so it stays round.",{param:"across"},{param:"down"},{param:"radius"},{param:"softness"}],color:"mix((gray, gray, gray), rgb, 1 - smoothstep(radius, radius + softness, distance((px, py), (across w, down h)) / min(w, h)))"},{name:"Vignette",group:"Colour & tone",params:{strength:{default:1.6,min:0,max:4}},color:"rgb * (1 - strength ((x - 0.5)^2 + (y - 0.5)^2))"},{name:"Sobel edges",group:"Blur & edges",description:"How fast the brightness changes",params:{gain:{default:2,min:.2,max:10}},color:"gain sobel()"},{name:"Edge map",group:"Blur & edges",description:"White where an edge is stronger than the cutoff",params:{cutoff:{default:.3,min:0,max:2}},color:"if sobel() > cutoff then 1 else 0"},{name:"Outline",group:"Blur & edges",description:"Ink lines over the colour",params:{gain:{default:3,min:0,max:10}},color:"rgb (1 - gain sobel())"},{name:"Box blur",group:"Blur & edges",params:{radius:{default:2,min:0,max:8,step:1}},color:"blur(radius)"},{name:"Gaussian blur",group:"Blur & edges",description:"Computed in two passes, across then down, so it can be wide",params:{sigma:{default:3,min:0,max:8}},color:"gaussian(sigma)"},{name:"Canny edges",group:"Blur & edges",description:"Thin, clean edge lines: smooth, gradient, thinning, two thresholds, hysteresis — a chain",steps:[{params:{sigma:{default:1.4,min:.5,max:4}},color:"gaussian(sigma)"},{color:"(min(sobel() / 4, 1), floor(fract((atan2(sobely(), sobelx()) + π/8) / π) 4) / 4, 0)"},{color:"if green(px, py) < 0.125 then (if r >= red(px - 1, py) & r >= red(px + 1, py) then r else 0) else if green(px, py) < 0.375 then (if r >= red(px + 1, py + 1) & r >= red(px - 1, py - 1) then r else 0) else if green(px, py) < 0.625 then (if r >= red(px, py - 1) & r >= red(px, py + 1) then r else 0) else (if r >= red(px - 1, py + 1) & r >= red(px + 1, py - 1) then r else 0)"},{params:{low:{default:.08,min:0,max:.5},high:{default:.2,min:0,max:1}},color:"if r > high then 1 else if r > low then 0.5 else 0"},"if r > 0.9 then 1 else if r > 0.4 then (if red(dilate(1)) > 0.9 then 1 else 0.5) else 0","if r > 0.9 then 1 else if r > 0.4 then (if red(dilate(1)) > 0.9 then 1 else 0.5) else 0","if r > 0.9 then 1 else if r > 0.4 then (if red(dilate(1)) > 0.9 then 1 else 0.5) else 0","if r > 0.9 then 1 else 0"]},{name:"Sharpen",group:"Blur & edges",params:{amount:{default:.6,min:0,max:3}},color:"sharpen(amount)"},{name:"Unsharp mask",group:"Blur & edges",description:"The picture plus what a blur removes",params:{amount:{default:1.5,min:0,max:5},sigma:{default:2,min:.5,max:4}},color:"rgb + amount (rgb - gaussian(sigma))"},{name:"Bloom",group:"Blur & edges",description:"Bright parts glow",params:{amount:{default:.8,min:0,max:3},sigma:{default:3,min:.5,max:4},cutoff:{default:.6,min:0,max:1}},color:"rgb + amount max(gaussian(sigma) - cutoff, 0)"},{name:"Emboss",group:"Blur & edges",color:"emboss()"},{name:"Dilate",group:"Blur & edges",description:"Light areas grow",params:{radius:{default:2,min:0,max:8,step:1}},color:"dilate(radius)"},{name:"Erode",group:"Blur & edges",description:"Dark areas grow",params:{radius:{default:2,min:0,max:8,step:1}},color:"erode(radius)"},{name:"3×3 kernel",group:"Blur & edges",description:"Your own convolution; the default is a sharpen",params:{k1:{default:0,min:-8,max:8},k2:{default:-1,min:-8,max:8},k3:{default:0,min:-8,max:8},k4:{default:-1,min:-8,max:8},k5:{default:5,min:-8,max:8},k6:{default:-1,min:-8,max:8},k7:{default:0,min:-8,max:8},k8:{default:-1,min:-8,max:8},k9:{default:0,min:-8,max:8}},color:"convolve(k1, k2, k3, k4, k5, k6, k7, k8, k9)"},{name:"Pixelate",group:"Shape & motion",params:{size:{default:8,min:1,max:32,step:1}},color:"pixel(floor(px / size) size, floor(py / size) size)"},{name:"Mirror",group:"Shape & motion",color:"pixel(w - px, py)"},{name:"Scanlines",group:"Shape & motion",params:{period:{default:4,min:2,max:16,step:1}},color:"if py mod period < period / 2 then rgb else rgb * 0.6"},{name:"Pulse",group:"Shape & motion",description:"Brightness breathes with t",params:{speed:{default:6,min:1,max:30},depth:{default:.25,min:0,max:1}},color:"rgb (1 - depth + depth sin(t / speed))"},{name:"Chroma key",group:"Colour & tone",description:"Replaces one colour with another",params:{key:[.22,.71,.29],tolerance:{default:.35,min:0,max:1},background:[.1,.1,.4]},color:"if distance(rgb, key) < tolerance then background else rgb"},{name:"Through a mask",group:"Other pictures",description:"Put this last: the steps above show only where the mask is light",images:{mask:{description:"light where the effect shows"}},color:"mix(source, rgb, luma(mask))"},{name:"Mix",group:"Other pictures",description:"Fade towards another picture",images:["overlay"],params:{amount:.5},color:"mix(rgb, overlay, amount)"},{name:"Masked mix",group:"Other pictures",images:{overlay:{},mask:{description:"light where the overlay shows"}},color:"mix(rgb, overlay, luma(mask))"},{name:"Multiply",group:"Other pictures",images:["overlay"],color:"rgb * overlay"},{name:"Screen",group:"Other pictures",images:["overlay"],color:"1 - (1 - rgb)(1 - overlay)"},{name:"Overlay blend",group:"Other pictures",images:["overlay"],color:"if gray < 0.5 then 2 rgb overlay else 1 - 2 (1 - rgb)(1 - overlay)"},{name:"Difference",group:"Other pictures",images:["overlay"],color:"abs(rgb - overlay)"},{name:"Alpha over",group:"Other pictures",description:"A picture with transparency laid on top",images:["overlay"],color:"mix(rgb, overlay, alpha(overlay))"},{name:"Chroma key onto a picture",group:"Other pictures",images:{background:{}},params:{key:[.22,.71,.29],tolerance:{default:.35,min:0,max:1}},color:"if distance(rgb, key) < tolerance then background else rgb"},{name:"Only inside the selection",group:"Other pictures",description:"Put this last: the steps above show only inside what you selected on the picture (everywhere, without a selection)",color:"mix(source, rgb, selected)"},{name:"Only outside the selection",group:"Other pictures",description:"Put this last: the steps above show only outside what you selected",color:"mix(rgb, source, selected)"},{name:"Caption",group:"Text & shapes",description:"Words along the bottom, with a soft shadow; change them under the step",graphics:{title:{text:"Your caption here",y:.88}},color:"mix(rgb, title, alpha(title))"},{name:"Poster title",group:"Text & shapes",description:"Big outlined letters across the top",graphics:{title:{text:"BIG TITLE",font:"Impact, Haettenschweiler, sans-serif",weight:"normal",size:.16,y:.14,outline:{color:"#000000",width:.08},shadow:null}},color:"mix(rgb, title, alpha(title))"},{name:"Gradient text",group:"Text & shapes",description:"The letters coloured by maths: a sunset from left to right",graphics:{title:{text:"Golden hour",font:"Georgia, serif",size:.13,y:.5,shadow:{color:"rgba(0,0,0,0.5)",blur:.2,dx:0,dy:.05}}},color:"mix(rgb, mix((1, 0.35, 0.3), (1, 0.85, 0.25), x), alpha(title))"},{name:"Neon sign",group:"Text & shapes",description:"White letters with a coloured glow",graphics:{title:{text:"OPEN",font:"Trebuchet MS, sans-serif",size:.18,y:.5,shadow:{color:"#00e5ff",blur:.45,dx:0,dy:0}}},color:"mix(rgb * 0.6, title, alpha(title))"},{name:"Layered shadow",group:"Text & shapes",description:"Two shadow layers, each with its own filter: a soft glow that darkens and breathes with t, and a hard offset coloured by a gradient",graphics:{title:{text:"LAYERS",font:"Impact, Haettenschweiler, sans-serif",weight:"normal",size:.17,y:.5,shadow:null,shadows:[{color:"#000000",blur:.7,dx:0,dy:.08},{color:"#000000",blur:0,dx:.07,dy:.07}]}},color:"mix(mix(mix(rgb, rgb * 0.25, alpha(title_shadow1) (0.7 + 0.3 sin(t / 10))), mix((1, 0.2, 0.6), (0.2, 0.6, 1), x), alpha(title_shadow2)), title, alpha(title))"},{name:"Ink brush",group:"Brushes",description:'Paint in a colour; draw on the picture with "draw" under the step',graphics:{brush:{type:"strokes",brush:"round",size:.025}},params:{ink:[.95,.2,.25]},color:"mix(rgb, ink, alpha(brush))"},{name:"Blur brush",group:"Brushes",description:"Paint a blur in — stronger every time a stroke goes over the same place",graphics:{brush:{type:"strokes",brush:"soft",size:.08}},color:"mix(rgb, gaussian(2 + 3 min(4 green(brush), 3)), alpha(brush))"},{name:"Darken brush",group:"Brushes",description:"Each pass darkens a little more, like layers of a wash",graphics:{brush:{type:"strokes",brush:"soft",size:.07,flow:.7}},color:"rgb (1 - 0.22 min(4 green(brush), 4))"},{name:"Colour reveal brush",group:"Brushes",description:"The picture starts grey; the brush paints its colour back",graphics:{brush:{type:"strokes",brush:"soft",size:.1}},color:"mix((gray, gray, gray), rgb, alpha(brush))"},{name:"Fuse brush",group:"Brushes",description:"Paint glows as it goes down, then cools to charcoal (red(brush) is its age)",graphics:{brush:{type:"strokes",brush:"round",size:.02,age:40}},color:"mix(rgb, mix((1, 0.9, 0.5), (0.1, 0.07, 0.06), red(brush)), alpha(brush)) + (1, 0.5, 0.1) alpha(brush) max(0, 1 - 3 red(brush)) 0.6"},{name:"Rainbow brush",group:"Brushes",description:"The colour runs round the wheel along the drawing (blue(brush) is how far through it)",graphics:{brush:{type:"strokes",brush:"marker",size:.035}},color:"mix(rgb, fromhsv(blue(brush), 0.85, 1), alpha(brush))"},{name:"Chalk outline",group:"Brushes",description:'Chalk round an object: select it, then "outline the selection" under the step',graphics:{brush:{type:"strokes",brush:"chalk",size:.018,timing:"even",speed:2}},color:"mix(rgb, (0.97, 0.97, 0.92), alpha(brush))"},{name:"Frosted panel",group:"Text & shapes",description:"A rounded panel that blurs and darkens what is behind it — a shape with its own filter",graphics:{panel:{type:"rect",y:.86,w:.9,h:.2,radius:.25}},color:"mix(rgb, gaussian(5) * 0.7, alpha(panel))"},{name:"Spotlight oval",group:"Text & shapes",description:"Darkens everything but a soft oval",graphics:{spot:{type:"ellipse",x:.5,y:.45,w:.45,h:.55,shadow:{color:"#ffffff",blur:.12,dx:0,dy:0}}},color:"mix(rgb * 0.3, rgb, alpha(spot))"},{name:"Scrolling banner",group:"Text & shapes",description:"Text that slides across and wraps round (animated with t)",graphics:{title:{text:"Breaking news · scrolling text · ",size:.07,y:.92}},params:{speed:{default:3,min:-10,max:10}},color:"mix(rgb, shift(title, -speed t, 0), alpha(shift(title, -speed t, 0)))"},{name:"Pulsing title",group:"Text & shapes",description:"Text that grows and shrinks a little (animated with t)",graphics:{title:{text:"Hello!",size:.14,y:.5}},params:{amount:{default:.06,min:0,max:.3}},color:"mix(rgb, zoom(title, 1 + amount sin(t / 8)), alpha(zoom(title, 1 + amount sin(t / 8))))"},{name:"Fade-in title",group:"Text & shapes",description:"Text that fades in over the first frames (animated with t)",graphics:{title:{text:"Once upon a time",font:"Georgia, serif",style:"italic",weight:"normal",size:.09,y:.5}},params:{frames:{default:40,min:1,max:200}},color:"mix(rgb, title, alpha(title) clamp(t / frames, 0, 1))"},{name:"Zoom",group:"Shape & motion",params:{scale:{default:1.5,min:.25,max:4},cx:.5,cy:.5},color:"zoom(scale, cx, cy)"},{name:"Ken Burns",group:"Shape & motion",description:"A slow zoom that drifts across — a still picture that moves",params:{speed:{default:.002,min:0,max:.01},drift:{default:3e-4,min:-.001,max:.001}},color:"zoom(1 + speed t, 0.5 + drift t, 0.45)"},{name:"Scroll",group:"Shape & motion",description:"Slides and wraps around",params:{dx:{default:1,min:-5,max:5},dy:{default:0,min:-5,max:5}},color:"shift(dx t, dy t)"},{name:"Spin",group:"Shape & motion",params:{speed:{default:.01,min:-.05,max:.05}},color:"rotate(speed t)"},{name:"Tile",group:"Shape & motion",params:{n:{default:2,min:1,max:8,step:1}},color:"tile(n)"},{name:"Crop",group:"Shape & motion",description:"A part of the picture, filling the frame",params:{left:.1,top:.1,right:.9,bottom:.9},color:"crop(left, top, right, bottom)"},{name:"Flip",group:"Shape & motion",color:"flipx()"},{name:"Picture in picture",group:"Other pictures",description:"Another picture, fitted small in a corner",images:{inset:{description:"any size: it is fitted whole",place:"fit",zoom:.35,x:.8,y:.78}},color:"mix(rgb, inset, alpha(inset))"},{name:"Moving overlay",group:"Other pictures",description:"Another picture scrolling across at half strength",images:["overlay"],params:{speed:{default:2,min:-10,max:10}},color:"mix(rgb, shift(overlay, speed t, 0), 0.5)"},{name:"Hue shift",group:"Colour & tone",description:"Turns every colour around the hue wheel (in HSV)",space:"hsv",params:{amount:{default:.1,min:-.5,max:.5}},color:"(fract(r + amount), g, b)"},{name:"Saturation",group:"Colour & tone",description:"More or less colour (in HSV)",space:"hsv",params:{amount:{default:1.5,min:0,max:3}},color:"(r, clamp(g amount, 0, 1), b)"},{name:"Lightness",group:"Colour & tone",description:"Lighter or darker without changing the colours (in Lab)",space:"lab",params:{amount:{default:1.15,min:.5,max:2}},color:"(clamp(r amount, 0, 1), g, b)"},{name:"Vivid",group:"Colour & tone",description:"Colourfulness, perceptually even (in OKLab)",space:"oklab",params:{amount:{default:1.6,min:0,max:3}},color:"(r, 0.5 + (g - 0.5) amount, 0.5 + (b - 0.5) amount)"},{name:"Linear-light blur",group:"Blur & edges",description:"A Gaussian in linear light: bright spots stay bright, as a lens does",space:"linear",params:{sigma:{default:3,min:0,max:8}},color:"gaussian(sigma)"},{name:"Film grain",group:"Colour & tone",description:"Noise that changes every frame",params:{amount:{default:.15,min:0,max:.6}},color:"rgb + amount (random() - 0.5)"},{name:"Swirl",group:"Shape & motion",params:{strength:{default:.02,min:0,max:.1}},color:"pixel(w/2 + (px - w/2) cos(strength t gray) - (py - h/2) sin(strength t gray), h/2 + (px - w/2) sin(strength t gray) + (py - h/2) cos(strength t gray))"}],zt=e=>Rt.find(t=>t.name===e);Rt.push({name:"Old film",group:"Chains",description:"Sepia, a vignette and faint scanlines — a chain of three",steps:[zt("Sepia"),{filter:zt("Vignette"),with:{strength:1.2}},{filter:zt("Scanlines"),opacity:.5}]},{name:"Comic",group:"Chains",description:"Bold flat colours with ink lines: a small blur first, so a photo's fine texture isn't inked — a chain of four",steps:[{filter:zt("Gaussian blur"),with:{sigma:1.6}},{filter:zt("Vivid"),with:{amount:1.5}},{filter:zt("Posterize"),with:{levels:4}},{filter:zt("Outline"),with:{gain:1.2}}]},{name:"Cartoon",group:"Chains",description:"Blur, then flatten the colours, then outline — a chain of three",steps:[{filter:zt("Gaussian blur"),with:{sigma:1.5}},{filter:zt("Posterize"),with:{levels:6}},{filter:zt("Outline"),with:{gain:2}}]},{name:"Dreamy",group:"Chains",description:"A soft glow mixed over the picture",steps:[{filter:zt("Bloom"),with:{amount:1.2}},{filter:zt("Gaussian blur"),with:{sigma:2},opacity:.4}]},{name:"Tilt shift",group:"Chains",description:"Blurred where the mask is light — a chain",steps:[{filter:zt("Gaussian blur"),with:{sigma:4}},zt("Through a mask")]},{name:"Title card",group:"Chains",description:"A frosted panel with a caption on it — a chain of two",steps:[zt("Frosted panel"),{filter:zt("Caption"),with:{title:{text:"A title on a panel",y:.86}}}]},{name:"Colour spotlight",group:"Chains",description:"Grey except where the mask is dark — a chain",steps:[zt("Grayscale"),zt("Through a mask")]});const It=Rt,Nt=["Colour & tone","Blur & edges","Shape & motion","Text & shapes","Brushes","Other pictures","Chains"];export{u as BRUSHES,m as CLIPS,J as FILTER_FORMAT,d as FPS,O as GRAPHIC_DEFAULTS,A as GRAPHIC_TYPES,Nt as GROUPS,It as LIBRARY,T as MAX_SHADOW_LAYERS,re as PLACEMENT,g as STROKES_DEFAULTS,p as TIMINGS,f as WIDTH_FROM,St as chooseEngine,kt as compileCpuPass,me as compileFilter,Et as createCpuRunner,ke as createFilterRunner,Ft as createRunner,L as cssFont,K as drawGraphic,q as familyFor,we as filterFromJSON,be as filterFromLink,ae as filterGraphics,le as filterImages,he as filterParams,$e as filterToJSON,ye as filterToLink,D as fontFileFromCss,G as googleFontFamily,P as googleFontUrl,S as layeredExpression,X as loadGraphicFonts,oe as normalizeFilter,C as normalizeGraphic,y as normalizeStrokes,k as rasterizeStrokes,xe as readFilter,Y as renderGraphics,j as shadowLayerNames,M as simplify,E as simplifyLoop,b as strokeTimeline,At as toPicture,v as traceContours,ue as validateFilter};
|