image-to-pixel 3.0.1 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +69 -69
- package/dist/editor.css +1 -1
- package/dist/editor.css.map +2 -2
- package/dist/editor.esm.js +60 -60
- package/dist/editor.esm.js.map +4 -4
- package/dist/image-to-pixel.bundle.esm.js +10 -10
- package/dist/image-to-pixel.bundle.esm.js.map +3 -3
- package/dist/image-to-pixel.cjs +2 -2
- package/dist/image-to-pixel.cjs.map +2 -2
- package/dist/image-to-pixel.esm.js +2 -2
- package/dist/image-to-pixel.esm.js.map +2 -2
- package/dist/image-to-pixel.js +2 -2
- package/dist/image-to-pixel.js.map +2 -2
- package/dist/image-to-pixel.min.js +9 -9
- package/dist/image-to-pixel.min.js.map +3 -3
- package/dist/video.esm.js +2 -2
- package/dist/video.esm.js.map +4 -4
- package/lib/core/video/audio.js +159 -0
- package/lib/core/video/frames.js +182 -144
- package/lib/core/video/mux-mp4.js +320 -131
- package/lib/core/video/mux-webm.js +168 -127
- package/lib/editor/exporter.js +225 -185
- package/lib/editor/icons.js +65 -61
- package/lib/editor/index.js +1002 -793
- package/lib/editor/inspector.js +343 -328
- package/lib/editor/library.js +188 -182
- package/lib/editor/styles/editor.css +418 -385
- package/lib/editor/workspace.js +62 -0
- package/lib/index.js +31 -31
- package/lib/video.js +122 -92
- package/package.json +92 -92
- package/types/video.d.ts +99 -43
package/dist/editor.esm.js
CHANGED
|
@@ -1,82 +1,82 @@
|
|
|
1
|
-
/*! image-to-pixel v3.0
|
|
2
|
-
var
|
|
1
|
+
/*! image-to-pixel v3.1.0 | MIT | https://github.com/Tezumie/Image-to-Pixel */
|
|
2
|
+
var Gi=Object.defineProperty;var xt=(e,t)=>()=>(e&&(t=e(e=0)),t);var ji=(e,t)=>{for(var n in t)Gi(e,n,{get:t[n],enumerable:!0})};function wt(e){if(Array.isArray(e))return[e[0]|0,e[1]|0,e[2]|0];let t=String(e).trim().replace(/^#|^0x/i,"");if((t.length===3||t.length===4)&&(t=t.slice(0,3).split("").map(n=>n+n).join("")),!/^[0-9a-f]{6}([0-9a-f]{2})?$/i.test(t))throw new Error(`Invalid colour "${e}"`);return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]}function wn(e){try{return wt(e),!0}catch{return!1}}function Nt(e){return"#"+e.slice(0,3).map(t=>Math.max(0,Math.min(255,Math.round(t))).toString(16).padStart(2,"0")).join("")}function Zn(e,t,n){e=Kn(e),t=Kn(t),n=Kn(n);let o=Math.cbrt(.4122214708*e+.5363325363*t+.0514459929*n),i=Math.cbrt(.2119034982*e+.6806995451*t+.1073969566*n),r=Math.cbrt(.0883024619*e+.2817188376*t+.6299787005*n);return[.2104542553*o+.793617785*i-.0040720468*r,1.9779984951*o-2.428592205*i+.4505937099*r,.0259040371*o+.7827717662*i-.808675766*r]}function zo(e){if(e.length<2)return 1;let t=0;for(let n=0;n<e.length;n++){let o=1/0;for(let i=0;i<e.length;i++){if(n===i)continue;let r=e[n][0]-e[i][0],a=e[n][1]-e[i][1],c=e[n][2]-e[i][2],u=Math.sqrt(r*r+a*a+c*c);u<o&&(o=u)}t+=o}return Math.max(.04,Math.min(1,t/e.length/255))}var Xe,Kn,vn,vt=xt(()=>{Xe=e=>Nt(wt(e)),Kn=e=>e<=.04045?e/12.92:Math.pow((e+.055)/1.055,2.4);vn=[.2126,.7152,.0722]});function Rt(e,t=1,n={}){t=Math.max(1,Math.round(t));let o=e.width*t,i=e.height*t,r=new Uint8ClampedArray(o*i*4),a=e.data,c=e.width;for(let u=0;u<i;u++){let s=u/t|0;for(let l=0;l<o;l++){let p=(s*c+(l/t|0))*4,f=(u*o+l)*4;r[f]=a[p],r[f+1]=a[p+1],r[f+2]=a[p+2],r[f+3]=a[p+3]}}if(n.grid&&t>=3){let[u,s,l]=wt(n.gridColor||"#000000"),p=n.gridAlpha??.35;for(let f=0;f<i;f++)for(let h=0;h<o;h++){if(h%t&&f%t)continue;let y=(f*o+h)*4,E=r[y+3]/255,v=p+E*(1-p);r[y]=(u*p+r[y]*E*(1-p))/v,r[y+1]=(s*p+r[y+1]*E*(1-p))/v,r[y+2]=(l*p+r[y+2]*E*(1-p))/v,r[y+3]=v*255}}return{width:o,height:i,data:r}}function Vr(e,t,n){t=Math.max(1,Math.round(t)),n=Math.max(1,Math.round(n));let o=new Uint8ClampedArray(t*n*4),i=new Int32Array(t);for(let r=0;r<t;r++)i[r]=Math.min(e.width-1,Math.floor((r+.5)*e.width/t));for(let r=0;r<n;r++){let a=Math.min(e.height-1,Math.floor((r+.5)*e.height/n));for(let c=0;c<t;c++){let u=(a*e.width+i[c])*4,s=(r*t+c)*4;o[s]=e.data[u],o[s+1]=e.data[u+1],o[s+2]=e.data[u+2],o[s+3]=e.data[u+3]}}return{width:t,height:n,data:o}}function Xr(e,t=1/0){let n=new Set,o=e.data;for(let i=0;i<o.length&&!(o[i+3]!==0&&(n.add(o[i]<<16|o[i+1]<<8|o[i+2]),n.size>t));i+=4);return[...n].map(i=>Nt([i>>16,i>>8&255,i&255]))}function Wr(e,t=8){let{width:n,height:o,data:i}=e,r=(l,p)=>Math.abs(i[l]-i[p])<=t&&Math.abs(i[l+1]-i[p+1])<=t&&Math.abs(i[l+2]-i[p+2])<=t&&Math.abs(i[l+3]-i[p+3])<=t,a=(l,p)=>p?a(p,l%p):l,c=0,u=Math.max(1,Math.floor(o/64)),s=Math.max(1,Math.floor(n/64));for(let l=0;l<o;l+=u){let p=1;for(let f=1;f<n;f++)if(r((l*n+f)*4,(l*n+f-1)*4))p++;else if(c=a(c,p),p=1,c===1)return 1}for(let l=0;l<n;l+=s){let p=1;for(let f=1;f<o;f++)if(r((f*n+l)*4,((f-1)*n+l)*4))p++;else if(c=a(c,p),p=1,c===1)return 1}return c||1}var Vt=xt(()=>{vt()});function As(e){let t=e.split(/\r?\n/);if(!/^GIMP Palette/i.test(t[0]||""))throw new Error('Not a GIMP palette (missing "GIMP Palette" header)');let n="",o=[];for(let i of t.slice(1)){let r=i.trim();if(!r||r.startsWith("#"))continue;let a=/^Name:\s*(.*)$/i.exec(r);if(a){n=a[1].trim();continue}if(/^Columns:/i.test(r))continue;let c=/^(\d{1,3})\s+(\d{1,3})\s+(\d{1,3})/.exec(r);c&&o.push(Xe([+c[1],+c[2],+c[3]]))}return{name:n,colors:o}}function Kr(e){let t=[];for(let n of e.split(/\r?\n/)){let o=n.trim();if(!o||o.startsWith(";")||o.startsWith("//"))continue;let i=/^#?([0-9a-f]{6}|[0-9a-f]{8}|[0-9a-f]{3})\b/i.exec(o);if(!i)continue;let r=i[1].length===8?i[1].slice(2):i[1];t.push(Xe(r))}return{name:"",colors:t}}function _s(e){let t=e.split(/\r?\n/).map(i=>i.trim());if(t[0]!=="JASC-PAL")throw new Error("Not a JASC palette");let n=parseInt(t[2],10)||0,o=[];for(let i=3;i<3+n&&i<t.length;i++){let r=/^(\d+)\s+(\d+)\s+(\d+)/.exec(t[i]);r&&o.push(Xe([+r[1],+r[2],+r[3]]))}return{name:"",colors:o}}function mo(e){let t=typeof e=="string"?JSON.parse(e):e,o=(Array.isArray(t)?t:t.colors||t.palette||[]).map(i=>typeof i=="object"&&i?i.hex||i.color:i).filter(Boolean).map(Xe);return{name:!Array.isArray(t)&&t.name||"",colors:o}}function Ps(e){let t=[],n=/#?\b([0-9a-f]{6})\b/gi,o;for(;o=n.exec(e);)t.push(Xe(o[1]));return{name:"",colors:t}}function go(e,t=""){let n=(/\.([a-z0-9]+)$/i.exec(t)||[])[1]?.toLowerCase()||"",i=String(e).replace(/^/,"").trim(),r;if(n==="gpl"||/^GIMP Palette/i.test(i)?r=As(i):n==="pal"||i.startsWith("JASC-PAL")?r=_s(i):n==="json"||i.startsWith("{")||i.startsWith("[")?r=mo(i):n==="hex"||n==="txt"?r=Kr(i):(r=Kr(i),r.colors.length||(r=Ps(i))),r.colors=Ts(r.colors).slice(0,256),!r.name&&t&&(r.name=t.replace(/\.[^.]+$/,"").replace(/[-_]+/g," ")),!r.colors.length)throw new Error("No colours found in that palette");return r}function Zr(e,t){let n=t.map(o=>{let i=Xe(o),r=parseInt(i.slice(1,3),16),a=parseInt(i.slice(3,5),16),c=parseInt(i.slice(5,7),16);return`${String(r).padStart(3)} ${String(a).padStart(3)} ${String(c).padStart(3)} ${i.slice(1)}`});return`GIMP Palette
|
|
3
3
|
Name: ${e||"Palette"}
|
|
4
4
|
Columns: 8
|
|
5
5
|
#
|
|
6
6
|
${n.join(`
|
|
7
7
|
`)}
|
|
8
|
-
`}var
|
|
8
|
+
`}var Ts,Jr,Qr,bo=xt(()=>{vt();Ts=e=>[...new Set(e)];Jr=e=>e.map(t=>Xe(t).slice(1)).join(`
|
|
9
9
|
`)+`
|
|
10
|
-
`,Or=(e,t)=>JSON.stringify({name:e||"Palette",colors:t.map(n=>Ne(n).slice(1))},null,2)});function is(e){let t=String(e||"").trim(),n=/palette-list\/([a-z0-9-]+)/i.exec(t);return(n?n[1]:t).toLowerCase().replace(/\.(json|hex|gpl)$/,"")}async function $r(e,{fetch:t=globalThis.fetch}={}){let n=is(e);if(!/^[a-z0-9-]+$/.test(n))throw new Error("That does not look like a Lospec palette slug");let o=await t(`https://lospec.com/palette-list/${n}.json`);if(!o.ok)throw new Error(`Lospec returned ${o.status} for "${n}"`);let i=await o.json(),r=io(i);return{name:i.name||n,author:i.author||"",colors:r.colors,slug:n}}var zr=St(()=>{so()});function Br(e){let t=e.error?e.error.code:0,n=new Error(ss[t]||"the video could not be loaded");return n.code=t,e.error&&e.error.message&&(n.detail=e.error.message),n}async function en(e,{timeout:t=6e4}={}){if(e.error)throw Br(e);return e.readyState<1&&await Nr(e,"loadedmetadata",t),e.readyState<2&&await Nr(e,"loadeddata",t).catch(n=>{if(n.code)throw n}),e}async function Gr(e){let t=new Uint8Array(await e.arrayBuffer()),n={avc1:"H.264",avc3:"H.264",hvc1:"H.265 (HEVC)",hev1:"H.265 (HEVC)",av01:"AV1",vp09:"VP9",vp08:"VP8",mp4v:"MPEG-4 Part 2",apcn:"ProRes",apch:"ProRes",apcs:"ProRes",apco:"ProRes",ap4h:"ProRes 4444",dvh1:"Dolby Vision",dvhe:"Dolby Vision"};for(let r=0;r+24<t.length;r++)if(t[r]===115&&t[r+1]===116&&t[r+2]===115&&t[r+3]===100){let a=String.fromCharCode(t[r+16],t[r+17],t[r+18],t[r+19]);if(n[a])return n[a]}let o=new TextDecoder("latin1").decode(t.subarray(0,Math.min(t.length,1<<20))),i=/V_(VP8|VP9|AV1|MPEG4\/ISO\/AVC|MPEGH\/ISO\/HEVC)/.exec(o);return i?{VP8:"VP8",VP9:"VP9",AV1:"AV1","MPEG4/ISO/AVC":"H.264","MPEGH/ISO/HEVC":"H.265 (HEVC)"}[i[1]]:""}async function Gt(e,t){if(t=Math.max(0,Math.min(t,(e.duration||0)-1e-4)),Math.abs(e.currentTime-t)<1e-6&&e.readyState>=2)return;let n="requestVideoFrameCallback"in e?new Promise(i=>{e.requestVideoFrameCallback(()=>i()),setTimeout(i,500)}):null,o=as(e,"seeked");e.currentTime=t,await o,n&&await n}async function Pn(e,t=30){if(!("requestVideoFrameCallback"in e))return t;await en(e);let n={t:e.currentTime,muted:e.muted,paused:e.paused},o=[];try{e.muted=!0,await new Promise(a=>{let c=setTimeout(a,1200),l=(s,d)=>{o.push(d.mediaTime),o.length>=12?(clearTimeout(c),a()):e.requestVideoFrameCallback(l)};e.requestVideoFrameCallback(l),e.play().catch(()=>{clearTimeout(c),a()})})}finally{e.pause(),e.muted=n.muted,await Gt(e,n.t).catch(()=>{})}let i=[];for(let a=1;a<o.length;a++){let c=o[a]-o[a-1];c>.001&&i.push(c)}if(i.length<3)return t;i.sort((a,c)=>a-c);let r=1/i[Math.floor(i.length/2)];for(let a of[12,15,23.976,24,25,29.97,30,48,50,59.94,60])if(Math.abs(r-a)<.6)return a;return Math.round(r)}function co({duration:e,fps:t,start:n=0,end:o=e,maxFrames:i=1/0}){let r=[],a=Math.min(i,Math.max(1,Math.floor((o-n)*t+1e-6)));for(let c=0;c<a;c++)r.push(n+(c+.5)/t);return r}async function Ln(e,t){await en(e);let n=e.paused;e.pause();let o=co({duration:e.duration,...t});for(let i=0;i<o.length;i++){if(t.signal&&t.signal.aborted)throw new DOMException("Aborted","AbortError");await Gt(e,o[i]),await t.onFrame({index:i,time:o[i],total:o.length})}return n||e.play().catch(()=>{}),o.length}var as,ss,Nr,Rn=St(()=>{as=(e,t,n=4e3)=>new Promise((o,i)=>{let r=setTimeout(()=>{e.removeEventListener(t,a),i(new Error(`Timed out waiting for "${t}"`))},n),a=()=>{clearTimeout(r),o()};e.addEventListener(t,a,{once:!0})}),ss={1:"loading was aborted",2:"a network error stopped the download",3:"the browser could not decode it",4:"this browser can't play this video's format"};Nr=(e,t,n)=>new Promise((o,i)=>{let r=()=>{clearTimeout(l),e.removeEventListener(t,a),e.removeEventListener("error",c)},a=()=>{r(),o()},c=()=>{r(),i(Br(e))},l=setTimeout(()=>{r(),i(new Error(`no response from the video decoder after ${n/1e3} s`))},n);e.addEventListener(t,a,{once:!0}),e.addEventListener("error",c,{once:!0})})});function ut(e,t){let n=new In;t(n);let o=n.out(),i=new In().u32(o.length+8).str(e).out(),r=new Uint8Array(o.length+8);return r.set(i),r.set(o,8),r}function mo({width:e,height:t,timescale:n=9e4}){let o=[],i=null;return{addChunk(r,a){if(a&&a.decoderConfig&&a.decoderConfig.description&&!i){let l=a.decoderConfig.description;i=new Uint8Array(l instanceof ArrayBuffer?l:l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength))}let c=new Uint8Array(r.byteLength);r.copyTo(c),o.push({data:c,key:r.type==="key",ts:r.timestamp,dur:r.duration||0})},addSample(r,{key:a,timestamp:c,duration:l}){o.push({data:r,key:!!a,ts:c,dur:l||0})},setDescription(r){i=r},finish(){if(!o.length)throw new Error("No video frames were encoded");if(!i)throw new Error("The encoder gave no H.264 decoder configuration (avcC)");let r=v=>Math.round(v*n/1e6),a=o.map(v=>r(v.ts)),c=a.slice().sort((v,I)=>v-I),l=r(o[o.length-1].dur)||(c.length>1?c[c.length-1]-c[c.length-2]:r(33333)),s=c.map((v,I)=>I+1<c.length?c[I+1]-v:l),d=a.map((v,I)=>v-c[I]),f=d.some(v=>v!==0),u=s.reduce((v,I)=>v+I,0),h=Math.round(u*1e3/n),x=[];for(let v of s){let I=x[x.length-1];I&&I[1]===v?I[0]++:x.push([1,v])}let E=[];for(let v of d){let I=E[E.length-1];I&&I[1]===v?I[0]++:E.push([1,v])}let y=o.map((v,I)=>v.key?I+1:0).filter(Boolean),k=o.reduce((v,I)=>v+I.data.length,0),b=ut("ftyp",v=>v.str("isom").u32(512).str("isom").str("iso2").str("avc1").str("mp41")),S=v=>ut("moov",I=>{I.bytes(Ue("mvhd",0,0,D=>{D.u32(0).u32(0).u32(1e3).u32(h).u32(65536).u16(256).zeros(10),ei.forEach(U=>D.u32(U)),D.zeros(24).u32(2)})),I.bytes(ut("trak",D=>{D.bytes(Ue("tkhd",0,3,U=>{U.u32(0).u32(0).u32(1).u32(0).u32(h).zeros(8).u16(0).u16(0).u16(0).u16(0),ei.forEach(B=>U.u32(B)),U.u32(e<<16).u32(t<<16)})),D.bytes(ut("mdia",U=>{U.bytes(Ue("mdhd",0,0,B=>B.u32(0).u32(0).u32(n).u32(u).u16(21956).u16(0))),U.bytes(Ue("hdlr",0,0,B=>B.u32(0).str("vide").zeros(12).str("VideoHandler").u8(0))),U.bytes(ut("minf",B=>{B.bytes(Ue("vmhd",0,1,H=>H.u16(0).u16(0).u16(0).u16(0))),B.bytes(ut("dinf",H=>H.bytes(Ue("dref",0,0,V=>{V.u32(1),V.bytes(Ue("url ",0,1,()=>{}))})))),B.bytes(ut("stbl",H=>{H.bytes(Ue("stsd",0,0,V=>{V.u32(1),V.bytes(ut("avc1",G=>{G.zeros(6).u16(1).zeros(16).u16(e).u16(t).u32(4718592).u32(4718592).u32(0).u16(1);let ce=ho.encode("image-to-pixel").slice(0,31);G.u8(ce.length).bytes(ce).zeros(31-ce.length).u16(24).u16(65535),G.bytes(ut("avcC",be=>be.bytes(i)))}))})),H.bytes(Ue("stts",0,0,V=>{V.u32(x.length);for(let[G,ce]of x)V.u32(G).u32(ce)})),f&&H.bytes(Ue("ctts",1,0,V=>{V.u32(E.length);for(let[G,ce]of E)V.u32(G).u32(ce>>>0)})),y.length<o.length&&H.bytes(Ue("stss",0,0,V=>{V.u32(y.length);for(let G of y)V.u32(G)})),H.bytes(Ue("stsc",0,0,V=>V.u32(1).u32(1).u32(o.length).u32(1))),H.bytes(Ue("stsz",0,0,V=>{V.u32(0).u32(o.length);for(let G of o)V.u32(G.data.length)})),H.bytes(Ue("stco",0,0,V=>V.u32(1).u32(v)))}))}))}))}))}),w=S(0).length,A=b.length+w+8;if(A+k>4294967295)throw new Error("Video is larger than 4 GB");let L=S(A),T=new Uint8Array(A+k);T.set(b,0),T.set(L,b.length),new DataView(T.buffer).setUint32(b.length+L.length,k+8),T.set(ho.encode("mdat"),b.length+L.length+4);let z=A;for(let v of o)T.set(v.data,z),z+=v.data.length;return T}}}var ho,In,Ue,ei,ti=St(()=>{ho=new TextEncoder,In=class{constructor(){this.parts=[],this.size=0}u8(t){return this.bytes([t&255])}u16(t){return this.bytes([t>>>8&255,t&255])}u32(t){return this.bytes([t>>>24&255,t>>>16&255,t>>>8&255,t&255])}str(t){return this.bytes(ho.encode(t))}bytes(t){let n=t instanceof Uint8Array?t:Uint8Array.from(t);return this.parts.push(n),this.size+=n.length,this}zeros(t){return this.bytes(new Uint8Array(t))}out(){let t=new Uint8Array(this.size),n=0;for(let o of this.parts)t.set(o,n),n+=o.length;return t}};Ue=(e,t,n,o)=>ut(e,i=>{i.u8(t).u8(n>>16).u8(n>>8).u8(n),o(i)}),ei=[65536,0,0,0,65536,0,0,0,1073741824]});function gs(e){let t=new Uint8Array(8);t[0]=1;let n=e;for(let o=7;o>=1;o--)t[o]=n%256,n=Math.floor(n/256);return t}function ni(e){let t=[];for(let n=e;n>0;n=Math.floor(n/256))t.unshift(n%256);return t}function Dn(e){let t=0;for(let i of e)t+=i.length;let n=new Uint8Array(t),o=0;for(let i of e)n.set(i,o),o+=i.length;return n}function go({width:e,height:t,codec:n="vp9",fps:o=0}){let i=[],r=null;return{addChunk(a,c){if(c&&c.decoderConfig&&c.decoderConfig.description&&!r){let s=c.decoderConfig.description;r=new Uint8Array(s instanceof ArrayBuffer?s:s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength))}let l=new Uint8Array(a.byteLength);a.copyTo(l),i.push({data:l,key:a.type==="key",ms:a.timestamp/1e3})},addFrame(a,{key:c,timestamp:l}){i.push({data:a,key:!!c,ms:l/1e3})},finish(){if(!i.length)throw new Error("No video frames were encoded");let a=o?1e3/o:i.length>1?(i[i.length-1].ms-i[0].ms)/(i.length-1):33.333,c=i[i.length-1].ms+a,l=Ie(K.Info,[pe(K.TimestampScale,1e6),bs(K.Duration,c),Fn(K.MuxingApp,"image-to-pixel"),Fn(K.WritingApp,"image-to-pixel")]),s=Ie(K.Tracks,[Ie(K.TrackEntry,[pe(K.TrackNumber,1),pe(K.TrackUID,1),pe(K.TrackType,1),pe(K.FlagLacing,0),Fn(K.CodecID,xs[n]||n),...r?[qt(K.CodecPrivate,r)]:[],pe(K.DefaultDuration,Math.round(a*1e6)),Ie(K.Video,[pe(K.PixelWidth,e),pe(K.PixelHeight,t)])])]),d=[],f=null;for(let T of i){let P=Math.round(T.ms);(!f||T.key||P-f.start>3e4)&&(f={start:P,key:T.key,blocks:[]},d.push(f));let z=new Uint8Array(4);z[0]=129,new DataView(z.buffer).setInt16(1,P-f.start),z[3]=T.key?128:0,f.blocks.push(qt(K.SimpleBlock,Dn([z,T.data])))}let u=d.map(T=>Ie(K.Cluster,[pe(K.Timestamp,T.start),...T.blocks])),h=(T,P,z)=>Ie(K.SeekHead,[[K.Info,T],[K.Tracks,P],[K.Cues,z]].map(([v,I])=>Ie(K.Seek,[qt(K.SeekID,Uint8Array.from(ni(v))),pe(K.SeekPosition,I,8)]))),E=h(0,0,0).length,y=E+l.length,k=y+s.length,b=[];d.forEach((T,P)=>{T.key&&b.push(Ie(K.CuePoint,[pe(K.CueTime,T.start),Ie(K.CueTrackPositions,[pe(K.CueTrack,1),pe(K.CueClusterPosition,k)])])),k+=u[P].length});let S=Ie(K.Cues,b.length?b:[Ie(K.CuePoint,[pe(K.CueTime,0),Ie(K.CueTrackPositions,[pe(K.CueTrack,1),pe(K.CueClusterPosition,y+s.length)])])]),w=k,A=Ie(K.EBML,[pe(K.EBMLVersion,1),pe(K.EBMLReadVersion,1),pe(K.EBMLMaxIDLength,4),pe(K.EBMLMaxSizeLength,8),Fn(K.DocType,"webm"),pe(K.DocTypeVersion,4),pe(K.DocTypeReadVersion,2)]),L=Ie(K.Segment,[h(E,y,w),l,s,...u,S]);return Dn([A,L])}}}var ms,qt,pe,Fn,bs,Ie,K,xs,oi=St(()=>{ms=new TextEncoder;qt=(e,t)=>Dn([Uint8Array.from(ni(e)),gs(t.length),t]),pe=(e,t,n=0)=>{let o=[];for(let i=t;i>0||o.length===0;i=Math.floor(i/256))o.unshift(i%256);for(;o.length<n;)o.unshift(0);return qt(e,Uint8Array.from(o))},Fn=(e,t)=>qt(e,ms.encode(t)),bs=(e,t)=>{let n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,t),qt(e,n)},Ie=(e,t)=>qt(e,Dn(t)),K={EBML:440786851,EBMLVersion:17030,EBMLReadVersion:17143,EBMLMaxIDLength:17138,EBMLMaxSizeLength:17139,DocType:17026,DocTypeVersion:17031,DocTypeReadVersion:17029,Segment:408125543,SeekHead:290298740,Seek:19899,SeekID:21419,SeekPosition:21420,Info:357149030,TimestampScale:2807729,Duration:17545,MuxingApp:19840,WritingApp:22337,Tracks:374648427,TrackEntry:174,TrackNumber:215,TrackUID:29637,TrackType:131,FlagLacing:156,CodecID:134,CodecPrivate:25506,DefaultDuration:2352003,Video:224,PixelWidth:176,PixelHeight:186,Cluster:524531317,Timestamp:231,SimpleBlock:163,Cues:475249515,CuePoint:187,CueTime:179,CueTrackPositions:183,CueTrack:247,CueClusterPosition:241},xs={vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1"}});var bo={};bi(bo,{createMp4Muxer:()=>mo,createVideoEncoder:()=>si,createWebmMuxer:()=>go,encodeVideo:()=>ws,estimateFps:()=>Pn,forEachFrame:()=>Ln,frameTimes:()=>co,seekTo:()=>Gt,videoReady:()=>en,videoSupport:()=>ys});async function ys(e=640,t=480){let n={mp4:!1,webm:!1,webcodecs:typeof VideoEncoder<"u"};if(n.webcodecs){for(let o of ii)if((await VideoEncoder.isConfigSupported({codec:o,width:e,height:t}).catch(()=>({}))).supported){n.mp4=!0;break}for(let[o]of ai)if((await VideoEncoder.isConfigSupported({codec:o,width:e,height:t}).catch(()=>({}))).supported){n.webm=!0;break}}return n}async function si(e){let t=Math.max(1,Math.round(e.scale||1)),n=ri(e.width*t),o=ri(e.height*t),i=e.fps||30,r=e.bitrate||Math.min(2e7,Math.max(2e6,n*o*i*.15));if(typeof VideoEncoder>"u")throw new Error("This browser has no WebCodecs VideoEncoder. Export a GIF or PNG sequence instead.");let a=null,c=null,l=e.format==="mp4"?ii.map(y=>[y,"avc"]):ai;for(let[y,k]of l)if((await VideoEncoder.isConfigSupported({codec:y,width:n,height:o,bitrate:r,framerate:i}).catch(()=>({}))).supported){a=y,c=k;break}if(!a)throw new Error(`No ${e.format.toUpperCase()} encoder available in this browser at ${n}\xD7${o}.`);let s=e.format==="mp4"?mo({width:n,height:o}):go({width:n,height:o,codec:c,fps:i}),d=null,f=new VideoEncoder({output:(y,k)=>s.addChunk(y,k),error:y=>{d=y}});f.configure({codec:a,width:n,height:o,bitrate:r,framerate:i,latencyMode:"quality",...e.format==="mp4"?{avc:{format:"avc"}}:{}});let u=new OffscreenCanvas(n,o),h=u.getContext("2d"),x=0,E=1e6/i;return{width:n,height:o,codec:a,async add(y){if(d)throw d;let k=t>1?_t(y,t):y;h.fillStyle="#000",h.fillRect(0,0,n,o),h.putImageData(new ImageData(new Uint8ClampedArray(k.data),k.width,k.height),0,0);let b=new VideoFrame(u,{timestamp:Math.round(x*E),duration:Math.round(E)});f.encode(b,{keyFrame:x%Math.max(1,Math.round(i*2))===0}),b.close(),x++,f.encodeQueueSize>8&&await new Promise(S=>setTimeout(S,0))},async finish(){if(await f.flush(),d)throw d;return f.close(),new Blob([s.finish()],{type:e.format==="mp4"?"video/mp4":"video/webm"})}}}async function ws(e,t){let n=await si({...t,width:e[0].width,height:e[0].height});for(let o of e)await n.add(o);return n.finish()}var ii,ai,ri,xo=St(()=>{ti();oi();Bt();Rn();ii=["avc1.640033","avc1.4d0033","avc1.42003e","avc1.640028","avc1.42001f"],ai=[["vp09.00.10.08","vp9"],["vp8","vp8"]];ri=e=>e+(e&1)});var nn=[{id:"1-bit-monitor",name:"1-Bit Monitor",author:"",colors:["222323","f0f6f0"]},{id:"apollo",name:"Apollo",author:"AdamCYounis",colors:["172038","253a5e","3c5e8b","4f8fba","73bed3","a4dddb","19332d","25562e","468232","75a743","a8ca58","d0da91","4d2b32","7a4841","ad7757","c09473","d7b594","e7d5b3","341c27","602c2c","884b2b","be772b","de9e41","e8c170","241527","411d31","752438","a53030","cf573c","da863e","1e1d39","402751","7a367b","a23e8c","c65197","df84a5","090a14","10141f","151d28","202e37","394a50","577277","819796","a8b5b2","c7cfcc","ebede9"]},{id:"batpalette",name:"Batpalette",author:"el Rojaz",colors:["000000","7f7f7f","ffffff","681e99","3f48cc","88ff82","bfa621","cc3d18"]},{id:"beached-boogaloo",name:"Beached Boogaloo",author:".tomais",colors:["ff0b20","8f0434","500037","a0ff00","57e71e","0ea717","057833","2cdeef","2483e7","153ab7","0d0a87","ff0b88","a60fff","6409cf","eaef30","ff880b","b75308","802202","000000","231940","514378","ffffff","73a3a7","366770","f7b771","c77650","974c38","873939","601e2c","300c1f"]},{id:"cc-29",name:"CC-29",author:"Alpha6",colors:["f2f0e5","b8b5b9","868188","646365","45444f","3a3858","212123","352b42","43436a","4b80ca","68c2d3","a2dcc7","ede19e","d3a068","b45252","6a536e","4b4158","80493a","a77b5b","e5ceb4","c2d368","8ab060","567b79","4e584a","7b7243","b2b47e","edc8c4","cf8acb","5f556a"]},{id:"cga-16",name:"CGA 16",author:"",colors:["000000","0000aa","00aa00","00aaaa","aa0000","aa00aa","aa5500","aaaaaa","555555","5555ff","55ff55","55ffff","ff5555","ff55ff","ffff55","ffffff"]},{id:"chaotic-neutral",name:"Chaotic neutral",author:"Dodecahedron \u2DFD",colors:["e1d4cb","c19f90","a56457","6d504d","484044","392b29","31312f","d8eef0","97999f","81a4c0","6a7f92","415973","43425a","45334b","4b1f40","671087","955ab9"]},{id:"endesga-32",name:"Endesga 32",author:"ENDESGA",colors:["be4a2f","d77643","ead4aa","e4a672","b86f50","733e39","3e2731","a22633","e43b44","f77622","feae34","fee761","63c74d","3e8948","265c42","193c3e","124e89","0099db","2ce8f5","ffffff","c0cbdc","8b9bb4","5a6988","3a4466","262b44","181425","ff0044","68386c","b55088","f6757a","e8b796","c28569"]},{id:"fantasy-24",name:"Fantasy 24",author:"",colors:["1f240a","39571c","a58c27","efac28","efd8a1","ab5c1c","183f39","ef692f","efb775","a56243","773421","724113","2a1d0d","392a1c","684c3c","927e6a","276468","ef3a0c","45230d","3c9f9c","9b1a0a","36170c","550f0a","300f0a"]},{id:"game-boy-dmg",name:"Game Boy (DMG)",author:"",colors:["0f380f","306230","8bac0f","9bbc0f"]},{id:"grayscale-4",name:"Grayscale 4",author:"",colors:["000000","555555","aaaaaa","ffffff"]},{id:"hidden-library",name:"Hidden Library",author:"Pixel Hoo",colors:["100b2a","2a213a","314743","65856d","adca9a","ecfeca","582d27","974133","d67654","5d3441","a3685b","ffb379","ffe6a9","ffffff"]},{id:"intacto14",name:"Intacto14",author:"Anubi",colors:["221529","4b5561","879ba3","cbf5ef","62b4de","5660d6","5b29a6","d64562","f2735c","edbb8e","ab6375","522152","37ada2","8cde8c"]},{id:"journey",name:"Journey",author:"\u{1F34D}PineappleOnPizza\u{1F34D}",colors:["050914","110524","3b063a","691749","9c3247","d46453","f5a15d","ffcf8e","ff7a7d","ff417d","d61a88","94007a","42004e","220029","100726","25082c","3d1132","73263d","bd4035","ed7b39","ffb84a","fff540","c6d831","77b02a","429058","2c645e","153c4a","052137","0e0421","0c0b42","032769","144491","488bd4","78d7ff","b0fff1","faffff","c7d4e1","928fb8","5b537d","392946","24142c","0e0f2c","132243","1a466b","10908e","28c074","3dff6e","f8ffb8","f0c297","cf968c","8f5765","52294b","0f022e","35003b","64004c","9b0e3e","d41e3c","ed4c40","ff9757","d4662f","9c341a","691b22","450c28","2d002e"]},{id:"lospec500",name:"Lospec500",author:"",colors:["10121c","2c1e31","6b2643","ac2847","ec273f","94493a","de5d3a","e98537","f3a833","4d3533","6e4c30","a26d3f","ce9248","dab163","e8d282","f7f3b7","1e4044","006554","26854c","5ab552","9de64e","008b8b","62a477","a6cb96","d3eed3","3e3b65","3859b3","3388de","36c5f4","6dead6","5e5b8c","8c78a5","b0a7b8","deceed","9a4d76","c878af","cc99ff","fa6e79","ffa2ac","ffd1d5","f6e8e0","ffffff"]},{id:"nyx8",name:"Nyx8",author:"Javier Guerrero",colors:["08141e","0f2a3f","20394f","4e495f","816271","997577","c3a38a","f6d6bd"]},{id:"oil-6",name:"Oil 6",author:"",colors:["fbf5ef","f2d3ab","c69fa5","8b6d9c","494d7e","272744"]},{id:"pico-8",name:"PICO-8",author:"",colors:["000000","1d2b53","7e2553","008751","ab5236","5f574f","c2c3c7","fff1e8","ff004d","ffa300","ffec27","00e436","29adff","83769c","ff77a8","ffccaa"]},{id:"resurrect-64",name:"Resurrect 64",author:"Kerrie Lake",colors:["2e222f","3e3546","625565","966c6c","ab947a","694f62","7f708a","9babb2","c7dcd0","ffffff","6e2727","b33831","ea4f36","f57d4a","ae2334","e83b3b","fb6b1d","f79617","f9c22b","7a3045","9e4539","cd683d","e6904e","fbb954","4c3e24","676633","a2a947","d5e04b","fbff86","165a4c","239063","1ebc73","91db69","cddf6c","313638","374e4a","547e64","92a984","b2ba90","0b5e65","0b8a8f","0eaf9b","30e1b9","8ff8e2","323353","484a77","4d65b4","4d9be6","8fd3ff","45293f","6b3e75","905ea9","a884f3","eaaded","753c54","a24b6f","cf657f","ed8099","831c5d","c32454","f04f78","f68181","fca790","fdcbb0"]},{id:"slso8",name:"SLSO8",author:"Luis Miguel Maldonado",colors:["0d2b45","203c56","544e68","8d697a","d08159","ffaa5e","ffd4a3","ffecd6"]},{id:"sweet-canyon-extended-64",name:"Sweet Canyon Extended 64",author:"Mr Slime",colors:["0f0e11","2d2c33","40404a","51545c","6b7179","7c8389","a8b2b6","d5d5d5","eeebe0","f1dbb1","eec99f","e1a17e","cc9562","ab7b49","9a643a","86482f","783a29","6a3328","541d29","42192c","512240","782349","8b2e5d","a93e89","d062c8","ec94ea","f2bdfc","eaebff","a2fafa","64e7e7","54cfd8","2fb6c3","2c89af","25739d","2a5684","214574","1f2966","101445","3c0d3b","66164c","901f3d","bb3030","dc473c","ec6a45","fb9b41","f0c04c","f4d66e","fffb76","ccf17a","97d948","6fba3b","229443","1d7e45","116548","0c4f3f","0a3639","251746","48246d","69189c","9f20c0","e527d2","ff51cf","ff7ada","ff9edb"]},{id:"sweetie-16",name:"Sweetie 16",author:"",colors:["1a1c2c","5d275d","b13e53","ef7d57","ffcd75","a7f070","38b764","257179","29366f","3b5dc9","41a6f6","73eff7","f4f4f4","94b0c2","566c86","333c57"]},{id:"toxic-haze",name:"Toxic Haze",author:"sillyTheJester",colors:["e5ff00","b8d14a","9ab06e","708763","4c5c52","393e40","242424"]},{id:"vinik24",name:"Vinik24",author:"Vinik",colors:["000000","6f6776","9a9a97","c5ccb8","8b5580","c38890","a593a5","666092","9a4f50","c28d75","7ca1c0","416aa3","8d6268","be955c","68aca9","387080","6e6962","93a167","6eaa78","557064","9d9f7f","7e9e99","5d6872","433455"]}];function Nn(e){let t=String(e||"").toLowerCase();return nn.find(n=>n.id===t||n.name.toLowerCase()===t)||null}bt();var xn=1,bn=2048,rn=[{id:"none",label:"None",kind:"none"},{id:"bayer2",label:"Bayer 2\xD72",kind:"ordered"},{id:"bayer4",label:"Bayer 4\xD74",kind:"ordered"},{id:"bayer8",label:"Bayer 8\xD78",kind:"ordered"},{id:"bayer16",label:"Bayer 16\xD716",kind:"ordered"},{id:"cluster4",label:"Clustered dot 4\xD74",kind:"ordered"},{id:"cluster8",label:"Clustered dot 8\xD78",kind:"ordered"},{id:"lines",label:"Horizontal lines",kind:"ordered"},{id:"bluenoise",label:"Blue noise",kind:"ordered"},{id:"custom",label:"Custom matrix",kind:"ordered"},{id:"floyd-steinberg",label:"Floyd\u2013Steinberg",kind:"diffusion"},{id:"atkinson",label:"Atkinson",kind:"diffusion"},{id:"sierra-lite",label:"Sierra Lite",kind:"diffusion"},{id:"sierra",label:"Sierra",kind:"diffusion"},{id:"burkes",label:"Burkes",kind:"diffusion"},{id:"jarvis",label:"Jarvis\u2013Judice\u2013Ninke",kind:"diffusion"},{id:"stucki",label:"Stucki",kind:"diffusion"}],yn=e=>(rn.find(t=>t.id===e)||{kind:"none"}).kind;var xi=Object.freeze({version:xn,size:{mode:"width",width:96,height:0,block:8,resample:"box"},adjust:{brightness:0,contrast:0,saturation:0,hue:0,gamma:1},frame:{aspect:"original",zoom:1,x:.5,y:.5},palette:{source:"builtin",id:"endesga-32",name:"Endesga 32",colors:[],count:16,distance:"oklab"},dither:{method:"bayer4",strength:.6,matrix:null},alpha:{threshold:.5},cleanup:{orphans:!1,smooth:!1},outline:{mode:"none",color:"#000000",corners:!1},export:{size:"scale",scale:4,indexed:!0,grid:!1,gridColor:"#000000"}}),Me=(e,t,n,o)=>{let i=Number(e);return Number.isFinite(i)?Math.min(n,Math.max(t,i)):o},$t=(e,t,n)=>t.includes(e)?e:n,on=(e,t)=>typeof e=="boolean"?e:t;function xt(){return et({})}function et(e={}){let t=xi,n=e||{},o={},i=n.size||{},r=n.adjust||{},a=n.palette||{},c=n.dither||{},l=n.alpha||{},s=n.cleanup||{},d=n.outline||{},f=n.export||{};o.version=xn,o.size={mode:$t(i.mode,["width","block"],t.size.mode),width:Math.round(Me(i.width,1,bn,t.size.width)),height:Math.round(Me(i.height,0,bn,t.size.height)),block:Me(i.block,1,256,t.size.block),resample:$t(i.resample,["box","nearest"],t.size.resample)},o.adjust={brightness:Me(r.brightness,-1,1,0),contrast:Me(r.contrast,-1,1,0),saturation:Me(r.saturation,-1,1,0),hue:Me(r.hue,-180,180,0),gamma:Me(r.gamma,.2,5,1)};let u=n.frame||{};o.frame={aspect:$t(u.aspect,Kt.map(E=>E.id),"original"),zoom:Me(u.zoom,1,8,1),x:Me(u.x,0,1,.5),y:Me(u.y,0,1,.5)};let h=$t(a.source,["builtin","custom","extract","none"],t.palette.source);if(o.palette={source:h,id:typeof a.id=="string"?a.id:h==="builtin"?t.palette.id:"",name:typeof a.name=="string"?a.name:"",colors:[],count:Math.round(Me(a.count,2,256,t.palette.count)),distance:$t(a.distance,["oklab","rgb"],t.palette.distance)},h==="builtin"){let E=Nn(o.palette.id)||Nn(t.palette.id);o.palette.id=E.id,o.palette.name=E.name,o.palette.colors=E.colors.map(y=>"#"+y)}else h==="custom"?(o.palette.colors=(Array.isArray(a.colors)?a.colors:[]).filter(mn).map(Ne).slice(0,256),o.palette.colors.length||(o.palette.colors=["#000000","#ffffff"]),o.palette.name=o.palette.name||"Custom"):h==="extract"?o.palette.name=`Extracted (${o.palette.count})`:o.palette.name="None";let x=rn.some(E=>E.id===c.method)?c.method:t.dither.method;return o.dither={method:x,strength:Me(c.strength,0,1,t.dither.strength),matrix:yi(c.matrix)},o.alpha={threshold:Me(l.threshold,0,1,t.alpha.threshold)},o.cleanup={orphans:on(s.orphans,!1),smooth:on(s.smooth,!1)},o.outline={mode:$t(d.mode,["none","outer","inner"],"none"),color:mn(d.color)?Ne(d.color):t.outline.color,corners:on(d.corners,!1)},o.export={size:$t(f.size,["scale","source"],"scale"),scale:Math.round(Me(f.scale,1,64,t.export.scale)),indexed:on(f.indexed,t.export.indexed),grid:on(f.grid,!1),gridColor:mn(f.gridColor)?Ne(f.gridColor):t.export.gridColor},o}function yi(e){if(!Array.isArray(e)||!e.length||!Array.isArray(e[0]))return null;let t=Math.min(16,e.length),n=Math.min(16,e[0].length),o=[];for(let i=0;i<t;i++){let r=[];for(let a=0;a<n;a++){let c=Number((e[i]||[])[a]);r.push(Number.isFinite(c)?c:0)}o.push(r)}return o}var Kt=[{id:"original",label:"Original",ratio:null},{id:"1:1",label:"1:1",ratio:1},{id:"4:3",label:"4:3",ratio:4/3},{id:"3:4",label:"3:4",ratio:3/4},{id:"3:2",label:"3:2",ratio:3/2},{id:"2:3",label:"2:3",ratio:2/3},{id:"16:9",label:"16:9",ratio:16/9},{id:"9:16",label:"9:16",ratio:9/16}];function wn(e,t,n={}){let o=(Kt.find(s=>s.id===n.aspect)||Kt[0]).ratio||e/t,i=e,r=e/o;r>t&&(r=t,i=t*o);let a=Math.max(1,n.zoom||1);i=Math.max(1,Math.min(e,Math.round(i/a))),r=Math.max(1,Math.min(t,Math.round(r/a)));let c=n.x??.5,l=n.y??.5;return{x:Math.round((e-i)*c),y:Math.round((t-r)*l),w:i,h:r}}function Mo(e,t,n){let o,i;return n.mode==="block"?(o=Math.max(1,Math.round(e/n.block)),i=Math.max(1,Math.round(t/n.block))):(o=n.width,i=n.height||Math.max(1,Math.round(o*t/e))),{width:Math.min(bn,o),height:Math.min(bn,i)}}function wi(e,t){let n={};for(let o of Object.keys(e)){if(o==="version")continue;let i=e[o],r=t[o];if(i&&typeof i=="object"&&!Array.isArray(i)){let a={};for(let c of Object.keys(i))JSON.stringify(i[c])!==JSON.stringify(r&&r[c])&&(a[c]=i[c]);Object.keys(a).length&&(n[o]=a)}else JSON.stringify(i)!==JSON.stringify(r)&&(n[o]=i)}return n}var Co={enc(e){let t=new TextEncoder().encode(e),n="";for(let o of t)n+=String.fromCharCode(o);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")},dec(e){let t=atob(e.replace(/-/g,"+").replace(/_/g,"/"));return new TextDecoder().decode(Uint8Array.from(t,n=>n.charCodeAt(0)))}};function So(e){let t=et(e),n=wi(t,xt());return n.palette&&(t.palette.source!=="custom"&&(delete n.palette.colors,delete n.palette.name),t.palette.source!=="builtin"&&delete n.palette.id,t.palette.source!=="extract"&&delete n.palette.count),n.palette&&!Object.keys(n.palette).length&&delete n.palette,n}function jn(e){return Co.enc(JSON.stringify({v:xn,...So(e)}))}function Hn(e){let t=String(e),n=/[#&?]s=([A-Za-z0-9_-]+)/.exec(t);n&&(t=n[1]);let o=JSON.parse(Co.dec(t));return delete o.v,et(o)}function Zt(e){return JSON.stringify({$schema:"image-to-pixel/settings",version:xn,...So(e)},null,2)}function Xn(e){let t=typeof e=="string"?JSON.parse(e):e;return delete t.$schema,et(t)}function Tt(e,t){let n=JSON.parse(JSON.stringify(e));for(let o of Object.keys(t||{}))t[o]&&typeof t[o]=="object"&&!Array.isArray(t[o])&&n[o]&&typeof n[o]=="object"?Object.assign(n[o],t[o]):n[o]=t[o];return et(n)}bt();var To="DHos2hHvghjhcwXqwKFF/I5L2ny43U2CNthWL2uZuIRL+h7EVxA0YALtMcH8NbbVUPllGoW/JOwz00rvXqMkVz7EYJ7BTqNbvi6qPIwRXa4kwO9YHI8KwRmt7YvNQV/mNKB2OofloLpEyqZhCYxtF4KtQ8mZ4Ud9uQiHHTy+cdiT8wWJO2/UDP6DUtBm3jLocQ+aLq/9atWZRXgD4R/EEGjRAe6qJdB1khZ7SeCqRPAwzwl3Ll6tGP9rqt+W6hSza0+s3xryLJNAsxbxI7d9zEGHZ9NGeiRZ8WYnsVKkdvOyj1a5RmcKU+gq9ZjOIny/XY7nuPcM1p1VOs4rZkyKMhzoKHpfsMR4Ycudb5BLAZ8e96gF6pW0Ow2904T3NpJOHzLhFoH1ltc9tVoTOWXmAqIjO2ZOinMm3I8PfsMA/Muevj/SmkoB6SHcCzqv+8Vg3k29OGEXyeSHnUARacEG2ofHbZvON70gaYnbdsKujVL+c9qlHLLHRGrvtkLlpVt5CVKID/swjak9VIDoXRUzdJMmfdCKpUttLftb3Jko7mOuR/8rXg12qPwDoUbrDy7HQrYPk+Y09QisHFeZciQ93WT0r2rFVtls9pS7IMqGpu4S2FQO8yvXAK14H7R/T6M3GIAHpuuNQsxVMsghXpp73xqGW8xJfl+chMkv9hXQspEb1TYgoXsTKcEGZKFE31K/PrGabbtdgetUzjnoFcdv0Oq9adNOteITmXLwh7j5PWOg8S5xAbon1Uvha76JSukvwJl+7UPitYZK0Tb6cyoJa4P4Lt5BHZu/GouiYkT6C49XI4k4GmcqgdhBrgxQJtMIv0fXp/uP6RJ2OwOpWwx/a0ECUcsMYjSc63erFI3Mm+kiXwSMqf83cEj1B8KHny61QNig+MeX9KxeHeRqxH+pbpEjgRY6aVCftP2WKu3Iofqx422nkL31FV0f203uXLhD1KzFTnnMCtmzLNt0IOFge+0BcFEQdz0Ewn0unj7eG/RR47NX078uzR9HfthwOR5YLIUU/ylMcspAuIKeADN7D5N2NeEUZJVRfJxbO7RPyxmVwjKr3LpV6qBH/s0AkF0yxgVw8JQMc4nmZL8RT7aL3JzGPV7WiAOi6GcpyG6y2PtXGvCZKb3oIfEOyv2RBaT4R2XlhB6SLG3ZEYhUcum7n3w9oipIrvZWBa0w9J/SCGgY7Kt3G7PgM5EO/ULiUSSlOc9ptFWBOq1pQ4Ibbuc1ciKxDUph+8YZj123Hq0qShD6zWLhgCDWO5zbhV4ic/dJgDNRzvFEYHzDU62KF5h/Yb2LAkP6ywePxeCnvSpbx4PbkfG/oj56sDfJ4Tz2hNlsjSCvDsRSkLpxFkLKlT6nv9yYBYotmxD3Itx4Nbz1COch2nijG2ziXC4XVj3al7MKVDptK9UG50/1CXeiYhXBOORaQZT/agkt8ljmtADoK1tw+bdmxHKrvUZpBdVNa55BrE/pNLqHRaT5cZ3xfhRI75vPGH6WXSWoZpsoStGUVaQDt9F1M6rdyIqkIXtjiNUOJkoV5yHcUzCGpfKRH80uw3IPlF/wJ9YTu4sAzCRt4DBlt/1R4r2L2xeD7LwG8SVw+IAj5RVLe18RSdMx/ky4ocyuhlpAkgbqyxRXt37oWof+KbLQCpdUezncSmKmw4yrH4MCpzcScjLKValrOXqwyjVOnGKz7504+a9smMEVOntkNNSg/cd9YJk82yhFCqcXzFWBPHCryO5oIrD/NlII81rERXXL60yz+z8Q4I7WRw+L1wnChicCvIAe4QlX5ZL0A+MfdA43tiX3dqpn+pbWbkC55Rv0SC4HlsWAD5bedzzSl+cmjmOgBJF5wy1aHZvkW6rrOVPUauhUyj+Lq3AjUJx+wEewbOFNGL4CjMNPLvKOAaBckNuCtFnhMnDKHrWJKQ9erxf2LM9fIO6euP5pvyx5HW/2kkKmK5pn9S/E2bM88liP7xWXg9dZ7jgafKteI9J1K7wOZ/k+GqXuSWX3UKnuftpPunxE5K5OcgE8ghLvQ5q1C8YWdNcFuhd/Rg5ozycK1S1cyTqkKpV10OYKv+pQrvtA0SSdzI5UuymeAthvQ8A1bhLYlwuHNNSVx1KxjsXgTH81rvtLhexV25n6iLueabN6qOsHarjfSaFkP5iBOhaJbqhRdgPnfA7Ugze6HZ0KkPKmOGbF+hVg5yH0MF4EKGTR51iLHaw7b6gsWxtI4DX8RSBRf/ocYAwosv0bbN/HWeYS87cwZEP8rG7sjV3+ySlYgOkkUrR2pUaMbaXZdv2kGJUnwmXgJr4Jyul1AX2TEL+M3LFCyI3yzodP0jCeBrMnmDqD3sKWLFkYSsYuek3asAXNcps82Ci8B98ZP7SEO75xRe4Qlc+BTo81pfVTzmDmbg2cMHWoUzdzBLmM9mY92nHPWR6kEs3kkrEH3aQTa5dDtxvvC4j2VoDEmFLKElvxANOeeD9c/yDdYsUsshqkKT3PXOwB2R7BmuJgH0rAhaZOCI/0bk6CYzH3aIU/u+Qh+lZ/qErGbBzmM2b2JZveibBVL7njBZpysBKKceJBgvi4kyG1SYVm7BNArOp4DO4d48ItsDzfvwyfR88l81d9N47UK+FiMa+bQ7YLftFtNEsdfvlhI6lIyDjtTA6X02kUUHrfbP+jKrNaftY0n81eNXmeYdEAjSbwuHkTqZABza4SarwDk9AQ8nTUlEmqBsCj5cYPkNd28RZfob79XDK8jO0KOJgYPdCN+CWSaBlIspH2EkZ1/6ZXbzneUMIz62VL9JxGd/5TgilZFfAv4F38dStlrDpRvTCT5HsniLAF5UKhyF7Wu1V3EEjICLr8f9okVbvmhhlCy5geifxfdqEhgsYw6BqxNtzApYdoxSCNPxSYSczrCYdm0AJB2BpNzGMlca8qhQbmqdpwm1fdPqUDbNM5qSjAae0I2LIrC9NE4rEJW4jKZ58HSes4sU+feNK28oEcdKH5HqpUumvzpHeX+hbbS/dqkCE2ufQqeR1g8LSADWKY3zKqekhjooO5GI42cdelKE3wkHUf0AP4E+RYNQKn3lQqxUd+8JotP9cQN7ZZgJwZykfwYwJCrIvMlyxDlPrHTROLUyPJ8jvcT/dgw+1EEOWBFNW3YZmDbb0mlHDOXzi5jGHfNhTTi7xb7IfPAO09tS+hfc2U5GcO7FDC3R90NexvzPu1kgVtIZh1A6Milbhqwz5YLvNF3jSjS/C7IYj8F9UIkbNuVwl/JW5Koi3EdFzqDFW0GFHXtzpyCKdTugSvnTwNXjGC6bHKL+VQe/tULaD4iqQKwh5cyYQIQN+fTXOiP/YmxeSm/MevG9pglRXahqwm/HYwfx2i/odo6I7WXSCA2KPhwlUXRYvRqzYMjd0CbyDQaH6r/xbXYrB5DsQv5GSrT3scRjUFk+k2fP5NwDpn00Cd6MaQXivRFD4leEXzwExyGT+qff9hEmy61mLAPOa0R+ooTo9rNpn0KVzqgRHNhgPtmmaL0k1ougmrKJoE748Ru1wEReO8TK32yJzgC44r+ZVk7A2hwSrwlEUhfJtahA2UvtsA7bYcSM2okUa9JFrUMLreWKkVhe9C03HlV3nJTXAn+Kp0DJV7WBhqL7JlqQPRL8l1O95ZhBbjpvMSyC36XjpzpUR93YptAzLycJ7/j0pzEfh34CueXIwTti+nGPSvz4U00iLuMcGoitJU7n1GtIQcUZAAtDfHVm80Tdt0nrYZyyVgyA5W+bHVUxe1OQ3FnSc4yUe9Gss0+WXVRoMtkw1kn1C3YtYAROQRPcYX41naova/ZZz4egbUuoitHUDehfOR4zSevD0jfZfJZH/dXey1ZgSUbfR8qU6SB+vEWuM72RrpiDuSc/xagaMllXI2CGo/J+MZS6+WJf4LZO9WC2tMB655HemRZeYRQNYoqkMahk7psTNTCN0hvHWcHmymT4CycQr0pRu1LcvxYr39rYzrsobQdS/rZj99oji9kc2nNsFb/URvBsZMr++IAPltltOnfBbShr5qPu9WNrj/AsbxJkPNVyrZZpkHd0AQUCnSHk4OWpLGE9e1UM4g5Xgq+IHbJI7LrNwpn3QyX5u8NOMOMf5EmuocoovODd6JRXgZjV/kq3nASYfhUajniMmgYH7Dn/w8p1aKGuJvjEkRtlEXoGkOUzWFXfsKw9xKG4JXwXNdtidiS/sueaxmI5zaOL6gETORBuwWOMEc0TFyDPUz2XAl5AZ5+DKaAfWtZNh06UK38pfiErtGjyOneM/uoiCTyQLid8MHtU8X88xYrWr4SHPI/WSdt3b6aJRZst1DkANIuWXCQqxpv1ktyTycB4kw0ngmqGvQfOZU9jkGY0Db9EyDqTSQ12fjoEB/CessGYXfUyI91lsmoUQB8iKaY77rqIQclNQh6j/do4Ed/VjCo18DTu0/HTOzFGuSsciGDWU32RP3Rx+CM8WQKLlMj9WoAbmOr38N5YS81nc6yhZ4K1reN/VSgQ+TdBPuaLsr3hT5lMqDuJPcXJ3UJ/FSLK7CIp9YbK+X8FkA/GPccsRBYzHoaRnxUsc3E1Wr44lP/50Qy3UJpGHPsilU0kGVf0twPrIxYwz+cQLASYIPb+iWedOK58ErzhO0d0erG5oN9nzOm0S+M4ylZfOVJmcGtdJBhrNN5bwk/UXGia4G5xmozojjH9RTqkOK8zLfo74+FvhQBUAYe19C4p7RMO1aOasiVgv6eNcE4iJ6w0j3nzFfHe9oLYk+mHoLZ+oxdrhf8i0QaZ955SzHHKd4YSKI214yp3S59aLXiSNoEI16vtmK6sCGKFCdbEa1O90Vgs1z6JXCAKXSE+xW2qYbm0zZO47EVfdBuxWZatlUC839Swi2zhvfjVIzB/LAOPfJTARoF0huo+G3FcX+hAqZWbM+D6wpSn37WHHDL4E9813EIKIAd6/RB45P9TqD6rk4lqxsgJNGYSTHbrZJfZtYsCam/pov1xI+Yo4lWqjRb/Ak4FKAz2PbF7hEnQSwz4wIfP9s50UfgzXpYsMEoCVJehTHJ/EBrv+cFu2WYBnYCXPnPH/OuV31esvuOdkaTjCmjWm3+QujNpEohtb4YSNJ360xVbuY2WumzCh7sVfQkPJh5D9Z5nE31Hs+3Syp7UaL0GEeUAuPrikNqm2XffbBAdQYM5RF7HbI8VscO3fGnWcUjc8RLFr7SBSY4B78agquIoigwS2JuwxSrQKFw24xuQ+WsPB0QeVWhEfgBrJBZYRR68ZvH7xUBa1upOKTDfQ5ue9DfuywC4q6aEw5hLdB3VPVEWvLHFzpks5j90wbpPlN4DKF1h/Flvm+IFzLJOOhO3qnWOCKL+dCGb9LJ7FR1HUipGPFPHTRMfWqzBHnJ5d5NbRIl/epQnMmtjmW0lyAI27IBGSmNwdnMaDzcJIPvP0SKtUKsGeY1Xz+jNhshRiZVuIEkSOj5lMBcZJZoW/DBPuD4g==";function vi(e){return typeof atob=="function"?Uint8Array.from(atob(e),t=>t.charCodeAt(0)):new Uint8Array(Buffer.from(e,"base64"))}function Jt(e){let t=[[0]];for(let n=1;n<e;n*=2){let o=[];for(let i=0;i<n*2;i++)o.push(new Array(n*2));for(let i=0;i<n;i++)for(let r=0;r<n;r++){let a=4*t[i][r];o[i][r]=a,o[i][r+n]=a+2,o[i+n][r]=a+3,o[i+n][r+n]=a+1}t=o}return t}function Ao(e){let t=e.length,n=e[0].length,o=[];for(let r=0;r<t;r++)for(let a=0;a<n;a++)o.push({i:r*n+a,v:e[r][a]});o.sort((r,a)=>r.v-a.v||r.i-a.i);let i=new Uint8Array(n*t);return o.forEach((r,a)=>{i[r.i]=a}),i}function Ei(e){let t=[];for(let n=0;n<e;n++){let o=[];for(let i=0;i<e;i++){let r=(i+.5)/e*2*Math.PI,a=(n+.5)/e*2*Math.PI;o.push(-(Math.cos(r)+Math.cos(a))+(i*e+n)*1e-9)}t.push(o)}return t}var ki=[[7,13,11,4],[12,16,14,8],[10,15,6,2],[5,9,3,1]],Vn=new Map;function Po(e,t=null){if(e==="custom"){let i=t&&t.length?t:Jt(4);return{w:i[0].length,h:i.length,levels:i.length*i[0].length,values:Ao(i)}}if(Vn.has(e))return Vn.get(e);let n,o=i=>({w:i[0].length,h:i.length,levels:i.length*i[0].length,values:Ao(i)});switch(e){case"bayer2":n=o(Jt(2));break;case"bayer4":n=o(Jt(4));break;case"bayer8":n=o(Jt(8));break;case"bayer16":n=o(Jt(16));break;case"cluster4":n=o(ki);break;case"cluster8":n=o(Ei(8));break;case"lines":n=o([[0],[2],[1],[3]]);break;case"bluenoise":n={w:64,h:64,levels:256,values:vi(To)};break;default:n=o(Jt(4))}return Vn.set(e,n),n}function Lo(e){let t=String(e).split(/\r?\n|;/).map(o=>o.trim()).filter(o=>o&&!/^\//.test(o)).map(o=>o.replace(/[[\]]/g,"").split(/[\s,]+/).filter(Boolean).map(Number));if(!t.length)throw new Error("Matrix is empty");let n=t[0].length;if(t.some(o=>o.length!==n||o.some(i=>!Number.isFinite(i))))throw new Error("Every row needs the same number of values");if(n>16||t.length>16)throw new Error("Matrices are limited to 16\xD716");return t}var zt=(e,t)=>t.map(([n,o,i])=>[n,o,i/e]),Ro={"floyd-steinberg":zt(16,[[1,0,7],[-1,1,3],[0,1,5],[1,1,1]]),atkinson:zt(8,[[1,0,1],[2,0,1],[-1,1,1],[0,1,1],[1,1,1],[0,2,1]]),"sierra-lite":zt(4,[[1,0,2],[-1,1,1],[0,1,1]]),sierra:zt(32,[[1,0,5],[2,0,3],[-2,1,2],[-1,1,4],[0,1,5],[1,1,4],[2,1,2],[-1,2,2],[0,2,3],[1,2,2]]),burkes:zt(32,[[1,0,8],[2,0,4],[-2,1,2],[-1,1,4],[0,1,8],[1,1,4],[2,1,2]]),jarvis:zt(48,[[1,0,7],[2,0,5],[-2,1,3],[-1,1,5],[0,1,7],[1,1,5],[2,1,3],[-2,2,1],[-1,2,3],[0,2,5],[1,2,3],[2,2,1]]),stucki:zt(42,[[1,0,8],[2,0,4],[-2,1,2],[-1,1,4],[0,1,8],[1,1,4],[2,1,2],[-2,2,1],[-1,2,2],[0,2,4],[1,2,2],[2,2,1]])},Wn=12;function Uo(e){let t=1;for(let[n,o]of e)o>0&&(t=Math.max(t,Math.floor(-n/o)+1));return t}var Io=(e,t,n)=>e-1+n*(t-1)+1;bt();function vn(e,t=16,n={}){let{maxSamples:o=4e4,alphaThreshold:i=.5}=n,r=e.width*e.height,a=Math.max(1,Math.floor(r/o)),c=[];for(let u=0;u<r;u+=a){let h=u*4;e.data[h+3]<i*255||c.push([e.data[h],e.data[h+1],e.data[h+2]])}if(!c.length)return["#000000","#ffffff"].slice(0,Math.max(1,t));let l=[c];for(;l.length<t;){let u=-1,h=-1,x=0;if(l.forEach((k,b)=>{if(!(k.length<2))for(let S=0;S<3;S++){let w=255,A=0;for(let T of k)T[S]<w&&(w=T[S]),T[S]>A&&(A=T[S]);let L=(A-w)*Math.sqrt(k.length);L>h&&(h=L,u=b,x=S)}}),u<0||h<=0)break;let E=l[u].slice().sort((k,b)=>k[x]-b[x]),y=E.length>>1;l.splice(u,1,E.slice(0,y),E.slice(y))}let s=l.map(u=>Mi(u));for(let u=0;u<6;u++){let h=s.map(()=>[0,0,0,0]);for(let x of c){let E=0,y=1/0;for(let b=0;b<s.length;b++){let S=x[0]-s[b][0],w=x[1]-s[b][1],A=x[2]-s[b][2],L=S*S+w*w+A*A;L<y&&(y=L,E=b)}let k=h[E];k[0]+=x[0],k[1]+=x[1],k[2]+=x[2],k[3]++}s=s.map((x,E)=>h[E][3]?[h[E][0]/h[E][3],h[E][1]/h[E][3],h[E][2]/h[E][3]]:x)}let d=[...new Set(s.map(u=>Ot(u)))],f=u=>{let h=parseInt(u.slice(1),16);return .2126*(h>>16)+.7152*(h>>8&255)+.0722*(h&255)};return d.sort((u,h)=>f(u)-f(h))}function Mi(e){let t=0,n=0,o=0;for(let i of e)t+=i[0],n+=i[1],o+=i[2];return[t/e.length,n/e.length,o/e.length]}bt();function kn(e,t,n,o="box",i=null){let r=i?i.x:0,a=i?i.y:0,c=i?i.w:e.width,l=i?i.h:e.height,s=e.data,d=e.width,f=new Float32Array(t*n*4),u=o==="nearest"?1:Math.min(16,Math.max(1,Math.ceil(c/t))),h=o==="nearest"?1:Math.min(16,Math.max(1,Math.ceil(l/n))),x=new Int32Array(t*u),E=new Int32Array(n*h);for(let y=0;y<t;y++)for(let k=0;k<u;k++)x[y*u+k]=r+Math.min(c-1,Math.floor((2*(y*u+k)+1)*c/(2*t*u)));for(let y=0;y<n;y++)for(let k=0;k<h;k++)E[y*h+k]=a+Math.min(l-1,Math.floor((2*(y*h+k)+1)*l/(2*n*h)));for(let y=0;y<n;y++)for(let k=0;k<t;k++){let b=0,S=0,w=0,A=0;for(let T=0;T<h;T++){let P=E[y*h+T]*d;for(let z=0;z<u;z++){let v=(P+x[k*u+z])*4,I=s[v+3]/255;b+=s[v]/255*I,S+=s[v+1]/255*I,w+=s[v+2]/255*I,A+=I}}let L=(y*t+k)*4;A>0&&(f[L]=b/A,f[L+1]=S/A,f[L+2]=w/A),f[L+3]=A/(u*h)}return f}function Mn(e,{brightness:t=0,contrast:n=0,saturation:o=0,hue:i=0,gamma:r=1}){if(!t&&!n&&!o&&!i&&r===1)return e;let a=n>=0?1/(1-.99*n):1+n,c=1/r,l=Math.cos(i*Math.PI/180),s=Math.sin(i*Math.PI/180),d=[.213+.787*l-.213*s,.715-.715*l-.715*s,.072-.072*l+.928*s,.213-.213*l+.143*s,.715+.285*l+.14*s,.072-.072*l-.283*s,.213-.213*l-.787*s,.715-.715*l+.715*s,.072+.928*l+.072*s];for(let f=0;f<e.length;f+=4){let u=e[f]+t,h=e[f+1]+t,x=e[f+2]+t;u=(u-.5)*a+.5,h=(h-.5)*a+.5,x=(x-.5)*a+.5;let E=u*gn[0]+h*gn[1]+x*gn[2],y=1+o;if(u=E+(u-E)*y,h=E+(h-E)*y,x=E+(x-E)*y,i){let k=d[0]*u+d[1]*h+d[2]*x,b=d[3]*u+d[4]*h+d[5]*x,S=d[6]*u+d[7]*h+d[8]*x;u=k,h=b,x=S}e[f]=Math.pow(yt(u),c),e[f+1]=Math.pow(yt(h),c),e[f+2]=Math.pow(yt(x),c)}return e}function Fo(e,t){for(let n=3;n<e.length;n+=4)e[n]=e[n]>=t&&e[n]>0?1:0;return e}var yt=e=>e<0?0:e>1?1:e;function Do(e,t){let n=e.length,o=new Float64Array(n*3),i=new Float64Array(n*3);return e.forEach((r,a)=>{i.set([r[0]/255,r[1]/255,r[2]/255],a*3),o.set(t===1?[r[0]/255,r[1]/255,r[2]/255]:Gn(r[0]/255,r[1]/255,r[2]/255),a*3)}),{n,coords:o,rgb:i,distance:t}}var qn=[.299,.587,.114];function Oo(e,t,n,o){let i,r,a,c=1,l=1,s=1;e.distance===1?(i=t,r=n,a=o,c=qn[0],l=qn[1],s=qn[2]):[i,r,a]=Gn(t,n,o);let d=0,f=1/0,u=e.coords;for(let h=0;h<e.n;h++){let x=i-u[h*3],E=r-u[h*3+1],y=a-u[h*3+2],k=c*x*x+l*E*E+s*y*y;k<f&&(f=k,d=h)}return d}function $o(e,t,n,o){let i=new Uint8ClampedArray(t*n*4),r=o.quantize?Do(o.palette,o.distance):null,a=o.kind==="ordered"?o.map:null,c=a?o.spread*o.settings.dither.strength:0;for(let l=0;l<n;l++)for(let s=0;s<t;s++){let d=(l*t+s)*4;if(e[d+3]<.5)continue;let f=e[d],u=e[d+1],h=e[d+2];if(r){if(a){let E=(a.values[l%a.h*a.w+s%a.w]+.5)/a.levels-.5;f=yt(f+E*c),u=yt(u+E*c),h=yt(h+E*c)}let x=Oo(r,f,u,h);i[d]=o.palette[x][0],i[d+1]=o.palette[x][1],i[d+2]=o.palette[x][2]}else i[d]=Math.round(f*255),i[d+1]=Math.round(u*255),i[d+2]=Math.round(h*255);i[d+3]=255}return i}function zo(e,t,n,o){let i=new Uint8ClampedArray(t*n*4),r=Do(o.palette,o.distance),a=new Float32Array(t*n*3),c=o.settings.dither.strength,l=o.kernel;for(let s=0;s<n;s++)for(let d=0;d<t;d++){let f=s*t+d,u=f*4;if(e[u+3]<.5)continue;let h=yt(e[u]+a[f*3]*c),x=yt(e[u+1]+a[f*3+1]*c),E=yt(e[u+2]+a[f*3+2]*c),y=Oo(r,h,x,E),k=h-r.rgb[y*3],b=x-r.rgb[y*3+1],S=E-r.rgb[y*3+2];for(let[w,A,L]of l){let T=d+w,P=s+A;if(T<0||T>=t||P>=n)continue;let z=(P*t+T)*3;a[z]+=k*L,a[z+1]+=b*L,a[z+2]+=S*L}i[u]=o.palette[y][0],i[u+1]=o.palette[y][1],i[u+2]=o.palette[y][2],i[u+3]=255}return i}var En=(e,t)=>e[t+3]===0?-1:e[t]<<16|e[t+1]<<8|e[t+2],No=[[0,-1],[1,0],[0,1],[-1,0]];function Bo(e,t,n){let o=e.slice();for(let i=0;i<n;i++)for(let r=0;r<t;r++){let a=(i*t+r)*4,c=En(o,a),l=[],s=[];for(let[u,h]of No){let x=r+u,E=i+h;if(x<0||E<0||x>=t||E>=n)continue;let y=(E*t+x)*4;l.push(En(o,y)),s.push(y)}if(l.length<2||l.includes(c))continue;let d=0,f=0;for(let u=0;u<l.length;u++){let h=0;for(let x=0;x<l.length;x++)l[x]===l[u]&&h++;h>f&&(f=h,d=u)}e.set(o.subarray(s[d],s[d]+4),a)}return e}function Go(e,t,n){let o=e.slice();for(let i=0;i<n;i++)for(let r=0;r<t;r++){let a=(i*t+r)*4,c=En(o,a),l=[],s=[];for(let d=-1;d<=1;d++)for(let f=-1;f<=1;f++){let u=Math.min(t-1,Math.max(0,r+f)),x=(Math.min(n-1,Math.max(0,i+d))*t+u)*4;l.push(En(o,x)),s.push(x)}for(let d=0;d<9;d++){if(l[d]===c)continue;let f=0;for(let u=0;u<9;u++)l[u]===l[d]&&f++;if(f>=5){e.set(o.subarray(s[d],s[d]+4),a);break}}}return e}function jo(e,t,n,{mode:o,color:i,corners:r}){if(o==="none")return e;let a=e.slice(),c=(d,f)=>d>=0&&f>=0&&d<t&&f<n&&a[(f*t+d)*4+3]>0,l=(d,f)=>d>=0&&f>=0&&d<t&&f<n,s=r?[[0,-1],[1,0],[0,1],[-1,0],[-1,-1],[1,-1],[1,1],[-1,1]]:No;for(let d=0;d<n;d++)for(let f=0;f<t;f++){let u=c(f,d),h=!1;for(let[x,E]of s){let y=f+x,k=d+E;if(l(y,k)&&(o==="outer"?!u&&c(y,k):u&&!c(y,k))){h=!0;break}}if(h){let x=(d*t+f)*4;e[x]=i[0],e[x+1]=i[1],e[x+2]=i[2],e[x+3]=255}}return e}function Ho(e,t){let n=et(e),o=wn(t.width,t.height,n.frame),{width:i,height:r}=Mo(o.w,o.h,n.size),a=n.palette.colors;n.palette.source==="extract"&&(a=Ci(t,n,i,r,o));let c=n.palette.source!=="none"&&a.length>0,l=c?a.map(gt):[],s=c?yn(n.dither.method):"none";n.dither.strength<=0&&(s="none");let d=s==="ordered"?Po(n.dither.method,n.dither.matrix):null,f=s==="diffusion"?Ro[n.dither.method]:null,u=f?Uo(f):1;return{settings:n,srcWidth:t.width,srcHeight:t.height,crop:o,width:i,height:r,quantize:c,kind:s,palette:l,paletteHex:c?a.slice():null,distance:n.palette.distance==="rgb"?1:0,spread:c?ko(l):0,map:d,kernel:f,skew:u,waves:f?Io(i,r,u):0,outline:{mode:n.outline.mode,color:gt(n.outline.color),corners:n.outline.corners}}}function Ci(e,t,n,o,i){let r=Math.min(1,160/Math.max(n,o)),a=Math.max(1,Math.round(n*r)),c=Math.max(1,Math.round(o*r)),l=kn(e,a,c,"box",i);Mn(l,t.adjust);let s=new Uint8ClampedArray(l.length);for(let d=0;d<l.length;d++)s[d]=Math.round(l[d]*255);return vn({data:s,width:a,height:c},t.palette.count,{alphaThreshold:Math.max(.01,t.alpha.threshold)})}function Xo(e,t){let{width:n,height:o,settings:i}=e,r=kn(t,n,o,i.size.resample,e.crop);Mn(r,i.adjust),Fo(r,i.alpha.threshold);let a=e.kind==="diffusion"?zo(r,n,o,e):$o(r,n,o,e);return i.cleanup.orphans&&Bo(a,n,o),i.cleanup.smooth&&Go(a,n,o),jo(a,n,o,e.outline),a}var Si="2.0.0",an=4,Vo="glcanvas",ye=class extends Error{constructor(e,t){super(e),this.name="ShaderMateError",t&&Object.assign(this,t)}},Wo=new Set;function Nt(e,...t){Wo.has(e)||(Wo.add(e),console.warn("[ShaderMate]",...t))}var Qn=typeof window<"u"&&typeof document<"u",Ti=e=>Array.isArray(e)||ArrayBuffer.isView(e)&&!(e instanceof DataView),qo=e=>e==null?[]:Array.isArray(e)?e:[e],Yo=e=>e>0&&(e&e-1)===0;function _i(e){var t,n,o,i;if(e==null)return null;if(Array.isArray(e))return[(t=e[0])!=null?t:0,(n=e[1])!=null?n:0,(o=e[2])!=null?o:0,(i=e[3])!=null?i:1];if(typeof e=="string"&&Qn){let r=document.createElement("canvas");r.width=r.height=1;let a=r.getContext("2d");a.fillStyle=e,a.fillRect(0,0,1,1);let c=a.getImageData(0,0,1,1).data;return[c[0]/255,c[1]/255,c[2]/255,c[3]/255]}return null}function Ai(){if(!Qn)return!1;let e=location.hostname;return location.protocol==="file:"||e==="localhost"||e==="127.0.0.1"||e===""||e.endsWith(".local")}var Pi=class{constructor(e){this.gl=e,this._items=new Map,this._nextId=1}add(e,t){let n=this._nextId++;return this._items.set(n,{obj:e,count:1,type:t}),n}ref(e){let t=this._items.get(e);return t&&t.count++,e}get(e){let t=this._items.get(e);return t?t.obj:null}unref(e){let t=this._items.get(e);t&&(t.count--,t.count<=0&&this._destroy(e,t))}_destroy(e,t){let{obj:n,type:o}=t,i=this.gl;switch(o){case"texture2D":case"textureCube":i.deleteTexture(n);break;case"fbo":i.deleteFramebuffer(n);break;case"buffer":i.deleteBuffer(n);break;case"program":i.deleteProgram(n);break}this._items.delete(e)}dispose(){for(let[e,t]of[...this._items])this._destroy(e,t)}};function Li(e){let t=new Map;function n(c,l){return t.has(c)||t.set(c,new Set),t.get(c).add(l),()=>o(c,l)}function o(c,l){let s=t.get(c);s&&s.delete(l)}function i(c,l){let s=d=>{o(c,s),l(d)};return n(c,s)}function r(c,l){let s=t.get(c);if(s)for(let d of[...s])try{d(l)}catch(f){console.error(`[ShaderMate] error in "${c}" listener`,f)}e&&e(c,l)}function a(){t.clear()}return{on:n,off:o,once:i,emit:r,clear:a}}var Ko={linear:e=>e,inQuad:e=>e*e,outQuad:e=>e*(2-e),inOutQuad:e=>e<.5?2*e*e:-1+(4-2*e)*e,inCubic:e=>e*e*e,outCubic:e=>1-Math.pow(1-e,3),inOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,outExpo:e=>e===1?1:1-Math.pow(2,-10*e),outBack:e=>1+2.70158*Math.pow(e-1,3)+1.70158*Math.pow(e-1,2),outElastic:e=>e===0||e===1?e:Math.pow(2,-10*e)*Math.sin((e*10-.75)*(2*Math.PI)/3)+1};function Ri(){let e=new Map;function t(i,r,a,c,l={}){let{duration:s=500,delay:d=0}=l,f=typeof l.ease=="function"?l.ease:Ko[l.ease]||Ko.outCubic,u=e.get(i);u&&u.resolve(!1);let h=r(),x=Array.isArray(c)||ArrayBuffer.isView(c),E=x?Array.from(h??c):Number(h??0),y=x?Array.from(c):Number(c);return new Promise(k=>{let b={start:performance.now()+d,resolve:S=>{e.delete(i),k(S)},update(S){let w=s>0?Ui((S-this.start)/s):1;if(w<0)return;let A=f(w);a(x?E.map((L,T)=>L+(y[T]-L)*A):E+(y-E)*A),w>=1&&this.resolve(!0)}};e.set(i,b)})}function n(i){for(let r of[...e.values()])r.update(i)}function o(i){if(i===void 0){for(let a of[...e.values()])a.resolve(!1);return}let r=e.get(i);r&&r.resolve(!1)}return{tween:t,update:n,cancel:o,get size(){return e.size}}}var Ui=e=>e<0?e:e>1?1:e;function Ii(e){let t;if(typeof e=="string")t=[{src:e}];else if(Array.isArray(e))t=e.map(i=>typeof i=="string"?{src:i}:{...i});else if(e&&typeof e=="object")t=[{...e}];else throw new ye("ShaderMate: expected a shader (string), a pass object, or an array of passes");if(!t.length)throw new ye("ShaderMate: no passes given");t.forEach((i,r)=>{var a,c,l,s,d;if(i.src==null&&(i.src=(s=(l=(c=(a=i.shader)!=null?a:i.frag)!=null?c:i.fragment)!=null?l:i.glsl)!=null?s:i.url),i.src==null)throw new ye(`Pass ${(d=i.name)!=null?d:r} has no shader source (use "shader")`);i.name==null&&(i.name=t.length===1?"main":"pass"+r),i.uniforms==null&&(i.uniforms={})}),t.some(i=>i.screen)||(t[t.length-1].screen=!0),t.filter(i=>i.screen).length>1&&console.warn("[ShaderMate] Multiple screen:true passes; last drawn wins.");let n=t.map(i=>i.name),o=n.filter((i,r)=>n.indexOf(i)!==r);if(o.length)throw new ye("Duplicate pass names: "+[...new Set(o)].join(", "));for(let i of t){let r=Array.isArray(i.channels)?i.channels:i.channels?[i.channels]:[];for(i.channels=r.slice(0,an).map(a=>lr(a,n,i.name));i.channels.length<an;)i.channels.push(null)}return t}var Fi=e=>typeof HTMLElement<"u"&&e instanceof HTMLElement,Di=e=>typeof ImageBitmap<"u"&&e instanceof ImageBitmap,Oi=e=>typeof WebGLTexture<"u"&&e instanceof WebGLTexture;function lr(e,t=[],n=""){if(e==null||e===!1)return null;if(typeof e=="string")return t.includes(e)?{pass:e}:{url:e};if(Fi(e)||Di(e))return{element:e};if(Oi(e))return{texture:e};let o={...e};return o.pass==null&&o.id!=null&&(o.pass=o.id),o.url==null&&o.image!=null&&(o.url=o.image),o.element==null&&o.canvas!=null&&(o.element=o.canvas),o.pass==null&&o.src!=null&&o.url==null&&o.video==null&&(o.url=o.src),o.pass!=null&&!t.includes(o.pass)&&console.warn(`[ShaderMate] Pass "${n}": channel references unknown pass "${o.pass}"`),o}function Yn(e){return/[\r\n]/.test(e)||/^\s*(void|#|precision|uniform|in |out |\/\/|\/\*)/.test(e)||/[{};]/.test(e)}var $i=e=>typeof WebGL2RenderingContext<"u"&&e instanceof WebGL2RenderingContext;function zi(e,t={}){let n=Object.assign({alpha:t.alpha!==!1,premultipliedAlpha:t.premultipliedAlpha!==!1,preserveDrawingBuffer:!!t.preserveDrawingBuffer,antialias:!!t.antialias,powerPreference:t.powerPreference||"default"},t.contextAttributes),o=t.webgl===void 0?"auto":String(t.webgl),i=null;if((o==="auto"||o==="2")&&(i=e.getContext("webgl2",n)),!i&&(o==="auto"||o==="1")&&(i=e.getContext("webgl",n)||e.getContext("experimental-webgl",n)),!i)throw new ye("WebGL not supported");return i}function Ni(e,t){let n={};return t?(n.EXT_color_buffer_float=e.getExtension("EXT_color_buffer_float"),n.EXT_color_buffer_half_float=e.getExtension("EXT_color_buffer_half_float"),n.OES_texture_float_linear=e.getExtension("OES_texture_float_linear")):(n.OES_texture_float=e.getExtension("OES_texture_float"),n.OES_texture_half_float=e.getExtension("OES_texture_half_float"),n.OES_texture_float_linear=e.getExtension("OES_texture_float_linear"),n.OES_texture_half_float_linear=e.getExtension("OES_texture_half_float_linear"),n.OES_standard_derivatives=e.getExtension("OES_standard_derivatives"),n.WEBGL_color_buffer_float=e.getExtension("WEBGL_color_buffer_float"),n.EXT_color_buffer_half_float=e.getExtension("EXT_color_buffer_half_float"),n.WEBGL_depth_texture=e.getExtension("WEBGL_depth_texture"),n.EXT_shader_texture_lod=e.getExtension("EXT_shader_texture_lod")),n}function Bi(e){let t=e.createBuffer();return e.bindBuffer(e.ARRAY_BUFFER,t),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),e.STATIC_DRAW),{bind(n){e.bindBuffer(e.ARRAY_BUFFER,t);let o=e.getAttribLocation(n,"a_position");o!==-1&&(e.enableVertexAttribArray(o),e.vertexAttribPointer(o,2,e.FLOAT,!1,0,0))},draw(){e.drawArrays(e.TRIANGLES,0,6)},dispose(){e.deleteBuffer(t)}}}function Gi(e,t){var n;let o=t.split(`
|
|
10
|
+
`,Qr=(e,t)=>JSON.stringify({name:e||"Palette",colors:t.map(n=>Xe(n).slice(1))},null,2)});function Ls(e){let t=String(e||"").trim(),n=/palette-list\/([a-z0-9-]+)/i.exec(t);return(n?n[1]:t).toLowerCase().replace(/\.(json|hex|gpl)$/,"")}async function ei(e,{fetch:t=globalThis.fetch}={}){let n=Ls(e);if(!/^[a-z0-9-]+$/.test(n))throw new Error("That does not look like a Lospec palette slug");let o=await t(`https://lospec.com/palette-list/${n}.json`);if(!o.ok)throw new Error(`Lospec returned ${o.status} for "${n}"`);let i=await o.json(),r=mo(i);return{name:i.name||n,author:i.author||"",colors:r.colors,slug:n}}var ti=xt(()=>{bo()});function oi(e){let t=e.error?e.error.code:0,n=new Error(Us[t]||"the video could not be loaded");return n.code=t,e.error&&e.error.message&&(n.detail=e.error.message),n}async function nn(e,{timeout:t=6e4}={}){if(e.error)throw oi(e);return e.readyState<1&&await ni(e,"loadedmetadata",t),e.readyState<2&&await ni(e,"loadeddata",t).catch(n=>{if(n.code)throw n}),e}async function ri(e){let t=new Uint8Array(await e.arrayBuffer()),n={avc1:"H.264",avc3:"H.264",hvc1:"H.265 (HEVC)",hev1:"H.265 (HEVC)",av01:"AV1",vp09:"VP9",vp08:"VP8",mp4v:"MPEG-4 Part 2",apcn:"ProRes",apch:"ProRes",apcs:"ProRes",apco:"ProRes",ap4h:"ProRes 4444",dvh1:"Dolby Vision",dvhe:"Dolby Vision"};for(let r=0;r+24<t.length;r++)if(t[r]===115&&t[r+1]===116&&t[r+2]===115&&t[r+3]===100){let a=String.fromCharCode(t[r+16],t[r+17],t[r+18],t[r+19]);if(n[a])return n[a]}let o=new TextDecoder("latin1").decode(t.subarray(0,Math.min(t.length,1<<20))),i=/V_(VP8|VP9|AV1|MPEG4\/ISO\/AVC|MPEGH\/ISO\/HEVC)/.exec(o);return i?{VP8:"VP8",VP9:"VP9",AV1:"AV1","MPEG4/ISO/AVC":"H.264","MPEGH/ISO/HEVC":"H.265 (HEVC)"}[i[1]]:""}async function ii(e){try{let t=new Uint8Array(await e.slice(0,12).arrayBuffer());if(t[0]===26&&t[1]===69&&t[2]===223&&t[3]===163){let n=new TextDecoder("latin1").decode(await e.slice(0,4194304).arrayBuffer());return/A_(OPUS|VORBIS|AAC|MPEG|AC3|EAC3|FLAC|PCM|DTS|TRUEHD|ALAC)/.test(n)}for(let n=0;n+8<=e.size;){let o=new DataView(await e.slice(n,n+16).arrayBuffer()),i=o.getUint32(0),r=String.fromCharCode(o.getUint8(4),o.getUint8(5),o.getUint8(6),o.getUint8(7));if(i===1?i=Number(o.getBigUint64(8)):i===0&&(i=e.size-n),i<8)return null;if(r==="moov"){let a=new Uint8Array(await e.slice(n,n+i).arrayBuffer());for(let c=4;c+16<=a.length;c++)if(a[c]===104&&a[c+1]===100&&a[c+2]===108&&a[c+3]===114&&a[c+12]===115&&a[c+13]===111&&a[c+14]===117&&a[c+15]===110)return!0;return!1}n+=i}return null}catch{return null}}async function Xt(e,t){if(t=Math.max(0,Math.min(t,(e.duration||0)-1e-4)),Math.abs(e.currentTime-t)<1e-6&&e.readyState>=2)return;let n="requestVideoFrameCallback"in e?new Promise(i=>{e.requestVideoFrameCallback(()=>i()),setTimeout(i,500)}):null,o=Rs(e,"seeked");e.currentTime=t,await o,n&&await n}async function On(e,t=30){if(!("requestVideoFrameCallback"in e))return t;await nn(e);let n={t:e.currentTime,muted:e.muted,paused:e.paused},o=[];try{e.muted=!0,await new Promise(a=>{let c=setTimeout(a,1200),u=(s,l)=>{o.push(l.mediaTime),o.length>=12?(clearTimeout(c),a()):e.requestVideoFrameCallback(u)};e.requestVideoFrameCallback(u),e.play().catch(()=>{clearTimeout(c),a()})})}finally{e.pause(),e.muted=n.muted,await Xt(e,n.t).catch(()=>{})}let i=[];for(let a=1;a<o.length;a++){let c=o[a]-o[a-1];c>.001&&i.push(c)}if(i.length<3)return t;i.sort((a,c)=>a-c);let r=1/i[Math.floor(i.length/2)];for(let a of[12,15,23.976,24,25,29.97,30,48,50,59.94,60])if(Math.abs(r-a)<.6)return a;return Math.round(r)}function yo({duration:e,fps:t,start:n=0,end:o=e,maxFrames:i=1/0}){let r=[],a=Math.min(i,Math.max(1,Math.floor((o-n)*t+1e-6)));for(let c=0;c<a;c++)r.push(n+(c+.5)/t);return r}async function Dn(e,t){await nn(e);let n=e.paused;e.pause();let o=yo({duration:e.duration,...t});for(let i=0;i<o.length;i++){if(t.signal&&t.signal.aborted)throw new DOMException("Aborted","AbortError");await Xt(e,o[i]),await t.onFrame({index:i,time:o[i],total:o.length})}return n||e.play().catch(()=>{}),o.length}var Rs,Us,ni,Fn=xt(()=>{Rs=(e,t,n=4e3)=>new Promise((o,i)=>{let r=setTimeout(()=>{e.removeEventListener(t,a),i(new Error(`Timed out waiting for "${t}"`))},n),a=()=>{clearTimeout(r),o()};e.addEventListener(t,a,{once:!0})}),Us={1:"loading was aborted",2:"a network error stopped the download",3:"the browser could not decode it",4:"this browser can't play this video's format"};ni=(e,t,n)=>new Promise((o,i)=>{let r=()=>{clearTimeout(u),e.removeEventListener(t,a),e.removeEventListener("error",c)},a=()=>{r(),o()},c=()=>{r(),i(oi(e))},u=setTimeout(()=>{r(),i(new Error(`no response from the video decoder after ${n/1e3} s`))},n);e.addEventListener(t,a,{once:!0}),e.addEventListener("error",c,{once:!0})})});async function Ns(e){if(e instanceof ArrayBuffer)return e.slice(0);if(ArrayBuffer.isView(e))return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);if(typeof Blob<"u"&&e instanceof Blob)return e.arrayBuffer();let t=typeof e=="string"?e:e&&(e.currentSrc||e.src);if(!t)throw new TypeError("decodeAudio() takes a File, Blob, ArrayBuffer, URL or <video>/<audio> element");let n=await fetch(t);if(!n.ok)throw new Error(`Couldn't load the audio: ${n.status} ${n.statusText}`);return n.arrayBuffer()}async function bi(e,t={}){if(typeof OfflineAudioContext>"u")return null;let n=t.sampleRate||Mo,o=await Ns(e),i;try{i=await new OfflineAudioContext(1,1,n).decodeAudioData(o)}catch{return null}let r=Math.max(0,t.start||0),a=Math.min(i.duration,t.end>r?t.end:i.duration),c=Math.floor((a-r)*n);if(c<1)return null;let u=Math.min(t.channels||2,i.numberOfChannels),s=new OfflineAudioContext(u,c,n),l=s.createBufferSource();l.buffer=i,l.connect(s.destination),l.start(0,r,c/n);let p=await s.startRendering(),f=[];for(let h=0;h<u;h++)f.push(p.getChannelData(h));return{sampleRate:n,numberOfChannels:u,channels:f,duration:c/n}}async function zn(e,t=Mo,n=2,o=128e3){if(typeof AudioEncoder>"u"||!ko[e])return null;let i=e==="opus"?[48e3]:[...new Set([t,48e3,44100])],r=[...new Set([o,128e3,192e3,16e4,96e3,0])];for(let a of i)for(let c of r){let u={codec:ko[e],sampleRate:a,numberOfChannels:n,...c?{bitrate:c}:{},...e==="aac"?{aac:{format:"aac"}}:{}};if((await AudioEncoder.isConfigSupported(u).catch(()=>({}))).supported)return u}return null}async function Bn(e,t=Mo,n=2){return!!await zn(e,t,n)}async function Gs(e,t){if(e.sampleRate===t)return e;let{numberOfChannels:n,channels:o}=e,i=Math.max(1,Math.round(o[0].length*t/e.sampleRate)),r=new OfflineAudioContext(n,i,t),a=r.createBuffer(n,o[0].length,e.sampleRate);for(let l=0;l<n;l++)a.copyToChannel(o[l],l);let c=r.createBufferSource();c.buffer=a,c.connect(r.destination),c.start();let u=await r.startRendering(),s=[];for(let l=0;l<n;l++)s.push(u.getChannelData(l));return{sampleRate:t,numberOfChannels:n,channels:s,duration:i/t}}async function Co(e,t){if(typeof AudioEncoder>"u")throw new Error("This browser has no WebCodecs AudioEncoder");let n=t.config||{codec:ko[t.codec],sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,bitrate:t.bitrate||128e3,...t.codec==="aac"?{aac:{format:"aac"}}:{}};n.sampleRate!==e.sampleRate&&(e=await Gs(e,n.sampleRate));let{sampleRate:o,numberOfChannels:i,channels:r}=e,a=null,c=new AudioEncoder({output:(p,f)=>t.onChunk(p,f),error:p=>{a=p}});c.configure(n);let u=Number.isFinite(t.maxDuration)?Math.floor(t.maxDuration*o):1/0,s=Math.min(r[0].length,u),l=Math.round(o/10);for(let p=0;p<s&&!a;p+=l){let f=Math.min(l,s-p),h=new Float32Array(f*i);for(let E=0;E<i;E++)h.set(r[E].subarray(p,p+f),E*f);let y=new AudioData({format:"f32-planar",sampleRate:o,numberOfFrames:f,numberOfChannels:i,timestamp:Math.round(p*1e6/o),data:h});c.encode(y),y.close(),c.encodeQueueSize>16&&await new Promise(E=>setTimeout(E,0))}if(a||await c.flush().catch(p=>{a=p}),c.state!=="closed"&&c.close(),a)throw a}function yi(e,t,n=312){let o=new Uint8Array(19);o.set([79,112,117,115,72,101,97,100]);let i=new DataView(o.buffer);return i.setUint8(8,1),i.setUint8(9,e),i.setUint16(10,n,!0),i.setUint32(12,t,!0),i.setInt16(16,0,!0),i.setUint8(18,0),o}function gn(e){if(!e||e.length<19||String.fromCharCode(...e.subarray(0,8))!=="OpusHead")return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{channels:t.getUint8(9),preSkip:t.getUint16(10,!0),sampleRate:t.getUint32(12,!0)}}var ko,Mo,Nn=xt(()=>{ko={aac:"mp4a.40.2",opus:"opus"},Mo=48e3});function Te(e,t){let n=new jn;t(n);let o=n.out(),i=new jn().u32(o.length+8).str(e).out(),r=new Uint8Array(o.length+8);return r.set(i),r.set(o,8),r}function js(e,t){let n=Gn(5,[...e]),o=Gn(4,[64,21,0,0,0,...wi(t),...wi(t),...n]),i=Gn(6,[2]);return Ee("esds",0,0,r=>r.bytes(Gn(3,[0,2,0,...o,...i])))}function Vs(e){if(!e||e.length<7||e[0]!==1)return!1;let t=5,n=e[t++]&31;if(!n)return!1;for(let i=0;i<n;i++){if(t+2>e.length)return!1;let r=e[t]<<8|e[t+1];if(t+=2,r<4||t+r>e.length)return!1;let a=e.subarray(t,t+r);if((a[0]&31)!==7||i===0&&(a[1]!==e[1]||a[2]!==e[2]||a[3]!==e[3]))return!1;t+=r}if(t>=e.length)return!1;let o=e[t++];if(!o)return!1;for(let i=0;i<o;i++){if(t+2>e.length)return!1;let r=e[t]<<8|e[t+1];if(t+=2,r<1||t+r>e.length||(e[t]&31)!==8)return!1;t+=r}return!0}function Xs(e){let t=[],n=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let o=0;o+4<=e.length;){let i=n.getUint32(o);if(o+=4,!i||o+i>e.length)break;t.push(e.subarray(o,o+i)),o+=i}return t}function Ws(e){let t=[];for(let a=1;a<e.length;a++)a>=3&&e[a]===3&&e[a-1]===0&&e[a-2]===0||t.push(e[a]);let n=24,o=()=>{let a=t[n>>3]>>7-(n&7)&1;return n++,a},i=()=>{let a=0;for(;n<t.length*8&&!o();)a++;let c=0;for(let u=0;u<a;u++)c=c*2+o();return 2**a-1+c};i();let r=i();return r===3&&o(),{chroma:r,lumaBits:i(),chromaBits:i()}}function qs(e){let t=Xs(e),n=t.filter(r=>(r[0]&31)===7),o=t.filter(r=>(r[0]&31)===8);if(!n.length||!o.length||n[0].length<4)return null;let i=[1,n[0][1],n[0][2],n[0][3],255,224|n.length];for(let r of n)i.push(r.length>>8,r.length&255,...r);i.push(o.length);for(let r of o)i.push(r.length>>8,r.length&255,...r);if(Hs.has(n[0][1])){let r=Ws(n[0]);i.push(252|r.chroma&3,248|r.lumaBits&7,248|r.chromaBits&7,0)}return Uint8Array.from(i)}function To(e){let t=[];for(let n of e){let o=t[t.length-1];o&&o[1]===n?o[0]++:t.push([1,n])}return t}function _o({width:e,height:t,timescale:n=9e4,audio:o=null}){let i=[],r=[],a=null,c=null;function u(){if(!o||!r.length)return null;let s=o.sampleRate,l=o.numberOfChannels,p=r[0].ts,f=r.map(v=>Math.round((v.ts-p)*s/1e6)),h=Math.round(r[r.length-1].dur*s/1e6)||(o.codec==="aac"?1024:960),y=f.map((v,M)=>M+1<f.length?Math.max(1,f[M+1]-v):h),E;if(o.codec==="aac"){if(!c)throw new Error("The audio encoder gave no AAC decoder configuration (AudioSpecificConfig)");E=Te("mp4a",v=>{v.zeros(6).u16(1).zeros(8).u16(l).u16(16).u16(0).u16(0).u32(s<=65535?s*65536:0),v.bytes(js(c,o.bitrate||128e3))})}else{let v=gn(c),M=v?v.preSkip:312;E=Te("Opus",x=>{x.zeros(6).u16(1).zeros(8).u16(l).u16(16).u16(0).u16(0).u32(48e3*65536),x.bytes(Te("dOps",S=>S.u8(0).u8(l).u16(M).u32(s).u16(0).u8(0)))})}return{rate:s,durs:y,entry:E,mediaDur:y.reduce((v,M)=>v+M,0)}}return{addChunk(s,l){l&&l.decoderConfig&&l.decoderConfig.description&&!a&&(a=xi(l.decoderConfig.description));let p=new Uint8Array(s.byteLength);s.copyTo(p),i.push({data:p,key:s.type==="key",ts:s.timestamp,dur:s.duration||0})},addSample(s,{key:l,timestamp:p,duration:f}){i.push({data:s,key:!!l,ts:p,dur:f||0})},setDescription(s){a=s},addAudioChunk(s,l){l&&l.decoderConfig&&l.decoderConfig.description&&!c&&(c=xi(l.decoderConfig.description));let p=new Uint8Array(s.byteLength);s.copyTo(p),r.push({data:p,ts:s.timestamp,dur:s.duration||0})},addAudioSample(s,{timestamp:l,duration:p}){r.push({data:s,ts:l,dur:p||0})},setAudioDescription(s){c=s},finish(){if(!i.length)throw new Error("No video frames were encoded");if(!Vs(a)){let W=i.find(Y=>Y.key)||i[0];a=qs(W.data)||a}if(!a)throw new Error("The encoder gave no H.264 decoder configuration (avcC)");let s=W=>Math.round(W*n/1e6),l=i.map(W=>s(W.ts)),p=l.slice().sort((W,Y)=>W-Y),f=s(i[i.length-1].dur)||(p.length>1?p[p.length-1]-p[p.length-2]:s(33333)),h=p.map((W,Y)=>Y+1<p.length?p[Y+1]-W:f),y=l.map((W,Y)=>W-p[Y]),E=y.some(W=>W!==0),v=h.reduce((W,Y)=>W+Y,0),M=Math.round(v*1e3/n),x=To(h),S=To(y),b=i.map((W,Y)=>W.key?Y+1:0).filter(Boolean),_=i.reduce((W,Y)=>W+Y.data.length,0),L=u(),P=L?Math.round(L.mediaDur*1e3/L.rate):0,R=L?r.reduce((W,Y)=>W+Y.data.length,0):0,j=Math.max(M,P),C=_+R,D=Te("ftyp",W=>W.str("isom").u32(512).str("isom").str("iso2").str("avc1").str("mp41")),F=()=>Te("dinf",W=>W.bytes(Ee("dref",0,0,Y=>{Y.u32(1),Y.bytes(Ee("url ",0,1,()=>{}))}))),I=W=>Ee("stsc",0,0,Y=>Y.u32(1).u32(1).u32(W).u32(1)),N=W=>Ee("stsz",0,0,Y=>{Y.u32(0).u32(W.length);for(let be of W)Y.u32(be.data.length)}),z=W=>Ee("stco",0,0,Y=>Y.u32(1).u32(W)),se=W=>Te("moov",Y=>{Y.bytes(Ee("mvhd",0,0,be=>{be.u32(0).u32(0).u32(1e3).u32(j).u32(65536).u16(256).zeros(10),So.forEach(ce=>be.u32(ce)),be.zeros(24).u32(L?3:2)})),Y.bytes(Te("trak",be=>{be.bytes(Ee("tkhd",0,3,ce=>{ce.u32(0).u32(0).u32(1).u32(0).u32(M).zeros(8).u16(0).u16(0).u16(0).u16(0),So.forEach(le=>ce.u32(le)),ce.u32(e<<16).u32(t<<16)})),be.bytes(Te("mdia",ce=>{ce.bytes(Ee("mdhd",0,0,le=>le.u32(0).u32(0).u32(n).u32(v).u16(21956).u16(0))),ce.bytes(Ee("hdlr",0,0,le=>le.u32(0).str("vide").zeros(12).str("VideoHandler").u8(0))),ce.bytes(Te("minf",le=>{le.bytes(Ee("vmhd",0,1,me=>me.u16(0).u16(0).u16(0).u16(0))),le.bytes(F()),le.bytes(Te("stbl",me=>{me.bytes(Ee("stsd",0,0,pe=>{pe.u32(1),pe.bytes(Te("avc1",ge=>{ge.zeros(6).u16(1).zeros(16).u16(e).u16(t).u32(4718592).u32(4718592).u32(0).u16(1);let xe=Ao.encode("image-to-pixel").slice(0,31);ge.u8(xe.length).bytes(xe).zeros(31-xe.length).u16(24).u16(65535),ge.bytes(Te("avcC",ke=>ke.bytes(a)))}))})),me.bytes(Ee("stts",0,0,pe=>{pe.u32(x.length);for(let[ge,xe]of x)pe.u32(ge).u32(xe)})),E&&me.bytes(Ee("ctts",1,0,pe=>{pe.u32(S.length);for(let[ge,xe]of S)pe.u32(ge).u32(xe>>>0)})),b.length<i.length&&me.bytes(Ee("stss",0,0,pe=>{pe.u32(b.length);for(let ge of b)pe.u32(ge)})),me.bytes(I(i.length)),me.bytes(N(i)),me.bytes(z(W))}))}))}))})),L&&Y.bytes(Te("trak",be=>{be.bytes(Ee("tkhd",0,3,ce=>{ce.u32(0).u32(0).u32(2).u32(0).u32(P).zeros(8).u16(0).u16(1).u16(256).u16(0),So.forEach(le=>ce.u32(le)),ce.u32(0).u32(0)})),be.bytes(Te("mdia",ce=>{ce.bytes(Ee("mdhd",0,0,le=>le.u32(0).u32(0).u32(L.rate).u32(L.mediaDur).u16(21956).u16(0))),ce.bytes(Ee("hdlr",0,0,le=>le.u32(0).str("soun").zeros(12).str("SoundHandler").u8(0))),ce.bytes(Te("minf",le=>{le.bytes(Ee("smhd",0,0,me=>me.u16(0).u16(0))),le.bytes(F()),le.bytes(Te("stbl",me=>{me.bytes(Ee("stsd",0,0,ge=>{ge.u32(1),ge.bytes(L.entry)}));let pe=To(L.durs);me.bytes(Ee("stts",0,0,ge=>{ge.u32(pe.length);for(let[xe,ke]of pe)ge.u32(xe).u32(ke)})),me.bytes(I(r.length)),me.bytes(N(r)),me.bytes(z(W+_))}))}))}))}))}),de=se(0).length,oe=D.length+de+8;if(oe+C>4294967295)throw new Error("Video is larger than 4 GB");let ee=se(oe),te=new Uint8Array(oe+C);te.set(D,0),te.set(ee,D.length),new DataView(te.buffer).setUint32(D.length+ee.length,C+8),te.set(Ao.encode("mdat"),D.length+ee.length+4);let ue=oe;for(let W of i)te.set(W.data,ue),ue+=W.data.length;if(L)for(let W of r)te.set(W.data,ue),ue+=W.data.length;return te}}}var Ao,jn,Ee,So,xi,Gn,wi,Hs,vi=xt(()=>{Nn();Ao=new TextEncoder,jn=class{constructor(){this.parts=[],this.size=0}u8(t){return this.bytes([t&255])}u16(t){return this.bytes([t>>>8&255,t&255])}u32(t){return this.bytes([t>>>24&255,t>>>16&255,t>>>8&255,t&255])}str(t){return this.bytes(Ao.encode(t))}bytes(t){let n=t instanceof Uint8Array?t:Uint8Array.from(t);return this.parts.push(n),this.size+=n.length,this}zeros(t){return this.bytes(new Uint8Array(t))}out(){let t=new Uint8Array(this.size),n=0;for(let o of this.parts)t.set(o,n),n+=o.length;return t}};Ee=(e,t,n,o)=>Te(e,i=>{i.u8(t).u8(n>>16).u8(n>>8).u8(n),o(i)}),So=[65536,0,0,0,65536,0,0,0,1073741824],xi=e=>new Uint8Array(e instanceof ArrayBuffer?e:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)),Gn=(e,t)=>[e,t.length,...t],wi=e=>[e>>>24&255,e>>>16&255,e>>>8&255,e&255];Hs=new Set([100,110,122,244,44,83,86,118,128,138,139,134,135])});function Ks(e){let t=new Uint8Array(8);t[0]=1;let n=e;for(let o=7;o>=1;o--)t[o]=n%256,n=Math.floor(n/256);return t}function Mi(e){let t=[];for(let n=e;n>0;n=Math.floor(n/256))t.unshift(n%256);return t}function Hn(e){let t=0;for(let i of e)t+=i.length;let n=new Uint8Array(t),o=0;for(let i of e)n.set(i,o),o+=i.length;return n}function Lo({width:e,height:t,codec:n="vp9",fps:o=0,audio:i=null}){if(i&&i.codec&&i.codec!=="opus")throw new Error(`WebM audio must be Opus, not ${i.codec}`);let r=[],a=[],c=null,u=null;return{addChunk(s,l){l&&l.decoderConfig&&l.decoderConfig.description&&!c&&(c=ki(l.decoderConfig.description));let p=new Uint8Array(s.byteLength);s.copyTo(p),r.push({data:p,key:s.type==="key",ms:s.timestamp/1e3})},addFrame(s,{key:l,timestamp:p}){r.push({data:s,key:!!l,ms:p/1e3})},addAudioChunk(s,l){l&&l.decoderConfig&&l.decoderConfig.description&&!u&&(u=ki(l.decoderConfig.description));let p=new Uint8Array(s.byteLength);s.copyTo(p),a.push({data:p,ms:s.timestamp/1e3,dms:(s.duration||0)/1e3})},addAudioFrame(s,{timestamp:l,duration:p}){a.push({data:s,ms:l/1e3,dms:(p||0)/1e3})},finish(){if(!r.length)throw new Error("No video frames were encoded");let s=!!(i&&a.length),l=o?1e3/o:r.length>1?(r[r.length-1].ms-r[0].ms)/(r.length-1):33.333,p=r[r.length-1].ms+l;if(s){let I=a[a.length-1];p=Math.max(p,I.ms+(I.dms||20))}let f=Pe(q.Info,[he(q.TimestampScale,1e6),Ei(q.Duration,p),bn(q.MuxingApp,"image-to-pixel"),bn(q.WritingApp,"image-to-pixel")]),h=[Pe(q.TrackEntry,[he(q.TrackNumber,rn),he(q.TrackUID,rn),he(q.TrackType,1),he(q.FlagLacing,0),bn(q.CodecID,Zs[n]||n),...c?[Ot(q.CodecPrivate,c)]:[],he(q.DefaultDuration,Math.round(l*1e6)),Pe(q.Video,[he(q.PixelWidth,e),he(q.PixelHeight,t)])])];if(s){let I=gn(u)?u:yi(i.numberOfChannels,i.sampleRate),N=gn(I).preSkip;h.push(Pe(q.TrackEntry,[he(q.TrackNumber,Po),he(q.TrackUID,Po),he(q.TrackType,2),he(q.FlagLacing,0),bn(q.CodecID,"A_OPUS"),Ot(q.CodecPrivate,I),he(q.CodecDelay,Math.round(N*1e9/48e3)),he(q.SeekPreRoll,8e7),Pe(q.Audio,[Ei(q.SamplingFrequency,i.sampleRate),he(q.Channels,i.numberOfChannels)])]))}let y=Pe(q.Tracks,h),E=r.map((I,N)=>({track:rn,data:I.data,key:I.key,ms:I.ms,order:N}));s&&a.forEach((I,N)=>E.push({track:Po,data:I.data,key:!0,ms:I.ms,order:r.length+N})),s&&E.sort((I,N)=>I.ms-N.ms||I.track-N.track||I.order-N.order);let v=[],M=null;for(let I of E){let N=Math.round(I.ms),z=I.track===rn&&I.key;(!M||z||N-M.start>3e4)&&(M={start:N,key:z,blocks:[]},v.push(M));let se=new Uint8Array(4);se[0]=128|I.track,new DataView(se.buffer).setInt16(1,N-M.start),se[3]=I.key?128:0,M.blocks.push(Ot(q.SimpleBlock,Hn([se,I.data])))}let x=v.map(I=>Pe(q.Cluster,[he(q.Timestamp,I.start),...I.blocks])),S=(I,N,z)=>Pe(q.SeekHead,[[q.Info,I],[q.Tracks,N],[q.Cues,z]].map(([se,de])=>Pe(q.Seek,[Ot(q.SeekID,Uint8Array.from(Mi(se))),he(q.SeekPosition,de,8)]))),_=S(0,0,0).length,L=_+f.length,P=L+y.length,R=[];v.forEach((I,N)=>{I.key&&R.push(Pe(q.CuePoint,[he(q.CueTime,I.start),Pe(q.CueTrackPositions,[he(q.CueTrack,rn),he(q.CueClusterPosition,P)])])),P+=x[N].length});let j=Pe(q.Cues,R.length?R:[Pe(q.CuePoint,[he(q.CueTime,0),Pe(q.CueTrackPositions,[he(q.CueTrack,rn),he(q.CueClusterPosition,L+y.length)])])]),C=P,D=Pe(q.EBML,[he(q.EBMLVersion,1),he(q.EBMLReadVersion,1),he(q.EBMLMaxIDLength,4),he(q.EBMLMaxSizeLength,8),bn(q.DocType,"webm"),he(q.DocTypeVersion,4),he(q.DocTypeReadVersion,2)]),F=Pe(q.Segment,[S(_,L,C),f,y,...x,j]);return Hn([D,F])}}}var Ys,Ot,he,bn,Ei,Pe,q,Zs,rn,Po,ki,Ci=xt(()=>{Nn();Ys=new TextEncoder;Ot=(e,t)=>Hn([Uint8Array.from(Mi(e)),Ks(t.length),t]),he=(e,t,n=0)=>{let o=[];for(let i=t;i>0||o.length===0;i=Math.floor(i/256))o.unshift(i%256);for(;o.length<n;)o.unshift(0);return Ot(e,Uint8Array.from(o))},bn=(e,t)=>Ot(e,Ys.encode(t)),Ei=(e,t)=>{let n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,t),Ot(e,n)},Pe=(e,t)=>Ot(e,Hn(t)),q={EBML:440786851,EBMLVersion:17030,EBMLReadVersion:17143,EBMLMaxIDLength:17138,EBMLMaxSizeLength:17139,DocType:17026,DocTypeVersion:17031,DocTypeReadVersion:17029,Segment:408125543,SeekHead:290298740,Seek:19899,SeekID:21419,SeekPosition:21420,Info:357149030,TimestampScale:2807729,Duration:17545,MuxingApp:19840,WritingApp:22337,Tracks:374648427,TrackEntry:174,TrackNumber:215,TrackUID:29637,TrackType:131,FlagLacing:156,CodecID:134,CodecPrivate:25506,DefaultDuration:2352003,Video:224,PixelWidth:176,PixelHeight:186,CodecDelay:22186,SeekPreRoll:22203,Audio:225,SamplingFrequency:181,Channels:159,Cluster:524531317,Timestamp:231,SimpleBlock:163,Cues:475249515,CuePoint:187,CueTime:179,CueTrackPositions:183,CueTrack:247,CueClusterPosition:241},Zs={vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1"},rn=1,Po=2,ki=e=>new Uint8Array(e instanceof ArrayBuffer?e:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength))});var Ro={};ji(Ro,{audioCodecSupported:()=>Bn,createMp4Muxer:()=>_o,createVideoEncoder:()=>_i,createWebmMuxer:()=>Lo,decodeAudio:()=>bi,encodeAudio:()=>Co,encodeVideo:()=>ec,estimateFps:()=>On,findAudioConfig:()=>zn,forEachFrame:()=>Dn,frameTimes:()=>yo,seekTo:()=>Xt,videoReady:()=>nn,videoSupport:()=>Js});async function Js(e=640,t=480){let n={mp4:!1,webm:!1,webcodecs:typeof VideoEncoder<"u",aac:!1,opus:!1};if(n.webcodecs){for(let o of Ti)if((await VideoEncoder.isConfigSupported({codec:o,width:e,height:t}).catch(()=>({}))).supported){n.mp4=!0;break}for(let[o]of Ai)if((await VideoEncoder.isConfigSupported({codec:o,width:e,height:t}).catch(()=>({}))).supported){n.webm=!0;break}}return n.aac=await Bn("aac"),n.opus=await Bn("opus"),n}async function Qs(e,t,n){let o=e==="mp4"?["aac","opus"]:["opus"];for(let i of o){let r=await zn(i,t.sampleRate,t.numberOfChannels,n);if(r)return{codec:i,config:r}}return null}async function _i(e){let t=Math.max(1,Math.round(e.scale||1)),n=Si(e.width*t),o=Si(e.height*t),i=e.fps||30,r=e.bitrate||Math.min(2e7,Math.max(2e6,n*o*i*.15));if(typeof VideoEncoder>"u")throw new Error("This browser has no WebCodecs VideoEncoder. Export a GIF or PNG sequence instead.");let a=null,c=null,u=e.format==="mp4"?Ti.map(b=>[b,"avc"]):Ai;for(let[b,_]of u)if((await VideoEncoder.isConfigSupported({codec:b,width:n,height:o,bitrate:r,framerate:i}).catch(()=>({}))).supported){a=b,c=_;break}if(!a)throw new Error(`No ${e.format.toUpperCase()} encoder available in this browser at ${n}\xD7${o}.`);let s=e.audio&&e.audio.channels&&e.audio.channels.length?e.audio:null,l=s?await Qs(e.format,s,e.audioBitrate||128e3):null,p=l?l.codec:null,f=l?{codec:p,sampleRate:l.config.sampleRate,numberOfChannels:l.config.numberOfChannels,bitrate:l.config.bitrate||128e3}:null,h=e.format==="mp4"?_o({width:n,height:o,audio:f}):Lo({width:n,height:o,codec:c,fps:i,audio:f}),y=null,E=new VideoEncoder({output:(b,_)=>h.addChunk(b,_),error:b=>{y=b}});E.configure({codec:a,width:n,height:o,bitrate:r,framerate:i,latencyMode:"quality",...e.format==="mp4"?{avc:{format:"avc"}}:{}});let v=new OffscreenCanvas(n,o),M=v.getContext("2d"),x=0,S=1e6/i;return{width:n,height:o,codec:a,audioCodec:p,async add(b){if(y)throw y;let _=t>1?Rt(b,t):b;M.fillStyle="#000",M.fillRect(0,0,n,o),M.putImageData(new ImageData(new Uint8ClampedArray(_.data),_.width,_.height),0,0);let L=new VideoFrame(v,{timestamp:Math.round(x*S),duration:Math.round(S)});E.encode(L,{keyFrame:x%Math.max(1,Math.round(i*2))===0}),L.close(),x++,E.encodeQueueSize>8&&await new Promise(P=>setTimeout(P,0))},async finish(){if(await E.flush(),y)throw y;return E.close(),p&&x>0&&await Co(s,{config:l.config,maxDuration:x/i,onChunk:(b,_)=>h.addAudioChunk(b,_)}),new Blob([h.finish()],{type:e.format==="mp4"?"video/mp4":"video/webm"})}}}async function ec(e,t){let n=await _i({...t,width:e[0].width,height:e[0].height});for(let o of e)await n.add(o);return n.finish()}var Ti,Ai,Si,Uo=xt(()=>{vi();Ci();Nn();Vt();Fn();Ti=["avc1.640033","avc1.4d0033","avc1.42003e","avc1.640028","avc1.42001f"],Ai=[["vp09.00.10.08","vp9"],["vp8","vp8"]];Si=e=>e+(e&1)});var an=[{id:"1-bit-monitor",name:"1-Bit Monitor",author:"",colors:["222323","f0f6f0"]},{id:"apollo",name:"Apollo",author:"AdamCYounis",colors:["172038","253a5e","3c5e8b","4f8fba","73bed3","a4dddb","19332d","25562e","468232","75a743","a8ca58","d0da91","4d2b32","7a4841","ad7757","c09473","d7b594","e7d5b3","341c27","602c2c","884b2b","be772b","de9e41","e8c170","241527","411d31","752438","a53030","cf573c","da863e","1e1d39","402751","7a367b","a23e8c","c65197","df84a5","090a14","10141f","151d28","202e37","394a50","577277","819796","a8b5b2","c7cfcc","ebede9"]},{id:"batpalette",name:"Batpalette",author:"el Rojaz",colors:["000000","7f7f7f","ffffff","681e99","3f48cc","88ff82","bfa621","cc3d18"]},{id:"beached-boogaloo",name:"Beached Boogaloo",author:".tomais",colors:["ff0b20","8f0434","500037","a0ff00","57e71e","0ea717","057833","2cdeef","2483e7","153ab7","0d0a87","ff0b88","a60fff","6409cf","eaef30","ff880b","b75308","802202","000000","231940","514378","ffffff","73a3a7","366770","f7b771","c77650","974c38","873939","601e2c","300c1f"]},{id:"cc-29",name:"CC-29",author:"Alpha6",colors:["f2f0e5","b8b5b9","868188","646365","45444f","3a3858","212123","352b42","43436a","4b80ca","68c2d3","a2dcc7","ede19e","d3a068","b45252","6a536e","4b4158","80493a","a77b5b","e5ceb4","c2d368","8ab060","567b79","4e584a","7b7243","b2b47e","edc8c4","cf8acb","5f556a"]},{id:"cga-16",name:"CGA 16",author:"",colors:["000000","0000aa","00aa00","00aaaa","aa0000","aa00aa","aa5500","aaaaaa","555555","5555ff","55ff55","55ffff","ff5555","ff55ff","ffff55","ffffff"]},{id:"chaotic-neutral",name:"Chaotic neutral",author:"Dodecahedron \u2DFD",colors:["e1d4cb","c19f90","a56457","6d504d","484044","392b29","31312f","d8eef0","97999f","81a4c0","6a7f92","415973","43425a","45334b","4b1f40","671087","955ab9"]},{id:"endesga-32",name:"Endesga 32",author:"ENDESGA",colors:["be4a2f","d77643","ead4aa","e4a672","b86f50","733e39","3e2731","a22633","e43b44","f77622","feae34","fee761","63c74d","3e8948","265c42","193c3e","124e89","0099db","2ce8f5","ffffff","c0cbdc","8b9bb4","5a6988","3a4466","262b44","181425","ff0044","68386c","b55088","f6757a","e8b796","c28569"]},{id:"fantasy-24",name:"Fantasy 24",author:"",colors:["1f240a","39571c","a58c27","efac28","efd8a1","ab5c1c","183f39","ef692f","efb775","a56243","773421","724113","2a1d0d","392a1c","684c3c","927e6a","276468","ef3a0c","45230d","3c9f9c","9b1a0a","36170c","550f0a","300f0a"]},{id:"game-boy-dmg",name:"Game Boy (DMG)",author:"",colors:["0f380f","306230","8bac0f","9bbc0f"]},{id:"grayscale-4",name:"Grayscale 4",author:"",colors:["000000","555555","aaaaaa","ffffff"]},{id:"hidden-library",name:"Hidden Library",author:"Pixel Hoo",colors:["100b2a","2a213a","314743","65856d","adca9a","ecfeca","582d27","974133","d67654","5d3441","a3685b","ffb379","ffe6a9","ffffff"]},{id:"intacto14",name:"Intacto14",author:"Anubi",colors:["221529","4b5561","879ba3","cbf5ef","62b4de","5660d6","5b29a6","d64562","f2735c","edbb8e","ab6375","522152","37ada2","8cde8c"]},{id:"journey",name:"Journey",author:"\u{1F34D}PineappleOnPizza\u{1F34D}",colors:["050914","110524","3b063a","691749","9c3247","d46453","f5a15d","ffcf8e","ff7a7d","ff417d","d61a88","94007a","42004e","220029","100726","25082c","3d1132","73263d","bd4035","ed7b39","ffb84a","fff540","c6d831","77b02a","429058","2c645e","153c4a","052137","0e0421","0c0b42","032769","144491","488bd4","78d7ff","b0fff1","faffff","c7d4e1","928fb8","5b537d","392946","24142c","0e0f2c","132243","1a466b","10908e","28c074","3dff6e","f8ffb8","f0c297","cf968c","8f5765","52294b","0f022e","35003b","64004c","9b0e3e","d41e3c","ed4c40","ff9757","d4662f","9c341a","691b22","450c28","2d002e"]},{id:"lospec500",name:"Lospec500",author:"",colors:["10121c","2c1e31","6b2643","ac2847","ec273f","94493a","de5d3a","e98537","f3a833","4d3533","6e4c30","a26d3f","ce9248","dab163","e8d282","f7f3b7","1e4044","006554","26854c","5ab552","9de64e","008b8b","62a477","a6cb96","d3eed3","3e3b65","3859b3","3388de","36c5f4","6dead6","5e5b8c","8c78a5","b0a7b8","deceed","9a4d76","c878af","cc99ff","fa6e79","ffa2ac","ffd1d5","f6e8e0","ffffff"]},{id:"nyx8",name:"Nyx8",author:"Javier Guerrero",colors:["08141e","0f2a3f","20394f","4e495f","816271","997577","c3a38a","f6d6bd"]},{id:"oil-6",name:"Oil 6",author:"",colors:["fbf5ef","f2d3ab","c69fa5","8b6d9c","494d7e","272744"]},{id:"pico-8",name:"PICO-8",author:"",colors:["000000","1d2b53","7e2553","008751","ab5236","5f574f","c2c3c7","fff1e8","ff004d","ffa300","ffec27","00e436","29adff","83769c","ff77a8","ffccaa"]},{id:"resurrect-64",name:"Resurrect 64",author:"Kerrie Lake",colors:["2e222f","3e3546","625565","966c6c","ab947a","694f62","7f708a","9babb2","c7dcd0","ffffff","6e2727","b33831","ea4f36","f57d4a","ae2334","e83b3b","fb6b1d","f79617","f9c22b","7a3045","9e4539","cd683d","e6904e","fbb954","4c3e24","676633","a2a947","d5e04b","fbff86","165a4c","239063","1ebc73","91db69","cddf6c","313638","374e4a","547e64","92a984","b2ba90","0b5e65","0b8a8f","0eaf9b","30e1b9","8ff8e2","323353","484a77","4d65b4","4d9be6","8fd3ff","45293f","6b3e75","905ea9","a884f3","eaaded","753c54","a24b6f","cf657f","ed8099","831c5d","c32454","f04f78","f68181","fca790","fdcbb0"]},{id:"slso8",name:"SLSO8",author:"Luis Miguel Maldonado",colors:["0d2b45","203c56","544e68","8d697a","d08159","ffaa5e","ffd4a3","ffecd6"]},{id:"sweet-canyon-extended-64",name:"Sweet Canyon Extended 64",author:"Mr Slime",colors:["0f0e11","2d2c33","40404a","51545c","6b7179","7c8389","a8b2b6","d5d5d5","eeebe0","f1dbb1","eec99f","e1a17e","cc9562","ab7b49","9a643a","86482f","783a29","6a3328","541d29","42192c","512240","782349","8b2e5d","a93e89","d062c8","ec94ea","f2bdfc","eaebff","a2fafa","64e7e7","54cfd8","2fb6c3","2c89af","25739d","2a5684","214574","1f2966","101445","3c0d3b","66164c","901f3d","bb3030","dc473c","ec6a45","fb9b41","f0c04c","f4d66e","fffb76","ccf17a","97d948","6fba3b","229443","1d7e45","116548","0c4f3f","0a3639","251746","48246d","69189c","9f20c0","e527d2","ff51cf","ff7ada","ff9edb"]},{id:"sweetie-16",name:"Sweetie 16",author:"",colors:["1a1c2c","5d275d","b13e53","ef7d57","ffcd75","a7f070","38b764","257179","29366f","3b5dc9","41a6f6","73eff7","f4f4f4","94b0c2","566c86","333c57"]},{id:"toxic-haze",name:"Toxic Haze",author:"sillyTheJester",colors:["e5ff00","b8d14a","9ab06e","708763","4c5c52","393e40","242424"]},{id:"vinik24",name:"Vinik24",author:"Vinik",colors:["000000","6f6776","9a9a97","c5ccb8","8b5580","c38890","a593a5","666092","9a4f50","c28d75","7ca1c0","416aa3","8d6268","be955c","68aca9","387080","6e6962","93a167","6eaa78","557064","9d9f7f","7e9e99","5d6872","433455"]}];function Yn(e){let t=String(e||"").toLowerCase();return an.find(n=>n.id===t||n.name.toLowerCase()===t)||null}vt();var kn=1,En=2048,cn=[{id:"none",label:"None",kind:"none"},{id:"bayer2",label:"Bayer 2\xD72",kind:"ordered"},{id:"bayer4",label:"Bayer 4\xD74",kind:"ordered"},{id:"bayer8",label:"Bayer 8\xD78",kind:"ordered"},{id:"bayer16",label:"Bayer 16\xD716",kind:"ordered"},{id:"cluster4",label:"Clustered dot 4\xD74",kind:"ordered"},{id:"cluster8",label:"Clustered dot 8\xD78",kind:"ordered"},{id:"lines",label:"Horizontal lines",kind:"ordered"},{id:"bluenoise",label:"Blue noise",kind:"ordered"},{id:"custom",label:"Custom matrix",kind:"ordered"},{id:"floyd-steinberg",label:"Floyd\u2013Steinberg",kind:"diffusion"},{id:"atkinson",label:"Atkinson",kind:"diffusion"},{id:"sierra-lite",label:"Sierra Lite",kind:"diffusion"},{id:"sierra",label:"Sierra",kind:"diffusion"},{id:"burkes",label:"Burkes",kind:"diffusion"},{id:"jarvis",label:"Jarvis\u2013Judice\u2013Ninke",kind:"diffusion"},{id:"stucki",label:"Stucki",kind:"diffusion"}],Mn=e=>(cn.find(t=>t.id===e)||{kind:"none"}).kind;var Hi=Object.freeze({version:kn,size:{mode:"width",width:96,height:0,block:8,resample:"box"},adjust:{brightness:0,contrast:0,saturation:0,hue:0,gamma:1},frame:{aspect:"original",zoom:1,x:.5,y:.5},palette:{source:"builtin",id:"endesga-32",name:"Endesga 32",colors:[],count:16,distance:"oklab"},dither:{method:"bayer4",strength:.6,matrix:null},alpha:{threshold:.5},cleanup:{orphans:!1,smooth:!1},outline:{mode:"none",color:"#000000",corners:!1},export:{size:"scale",scale:4,indexed:!0,grid:!1,gridColor:"#000000"}}),Ue=(e,t,n,o)=>{let i=Number(e);return Number.isFinite(i)?Math.min(n,Math.max(t,i)):o},Gt=(e,t,n)=>t.includes(e)?e:n,sn=(e,t)=>typeof e=="boolean"?e:t;function Et(){return at({})}function at(e={}){let t=Hi,n=e||{},o={},i=n.size||{},r=n.adjust||{},a=n.palette||{},c=n.dither||{},u=n.alpha||{},s=n.cleanup||{},l=n.outline||{},p=n.export||{};o.version=kn,o.size={mode:Gt(i.mode,["width","block"],t.size.mode),width:Math.round(Ue(i.width,1,En,t.size.width)),height:Math.round(Ue(i.height,0,En,t.size.height)),block:Ue(i.block,1,256,t.size.block),resample:Gt(i.resample,["box","nearest"],t.size.resample)},o.adjust={brightness:Ue(r.brightness,-1,1,0),contrast:Ue(r.contrast,-1,1,0),saturation:Ue(r.saturation,-1,1,0),hue:Ue(r.hue,-180,180,0),gamma:Ue(r.gamma,.2,5,1)};let f=n.frame||{};o.frame={aspect:Gt(f.aspect,Jt.map(E=>E.id),"original"),zoom:Ue(f.zoom,1,8,1),x:Ue(f.x,0,1,.5),y:Ue(f.y,0,1,.5)};let h=Gt(a.source,["builtin","custom","extract","none"],t.palette.source);if(o.palette={source:h,id:typeof a.id=="string"?a.id:h==="builtin"?t.palette.id:"",name:typeof a.name=="string"?a.name:"",colors:[],count:Math.round(Ue(a.count,2,256,t.palette.count)),distance:Gt(a.distance,["oklab","rgb"],t.palette.distance)},h==="builtin"){let E=Yn(o.palette.id)||Yn(t.palette.id);o.palette.id=E.id,o.palette.name=E.name,o.palette.colors=E.colors.map(v=>"#"+v)}else h==="custom"?(o.palette.colors=(Array.isArray(a.colors)?a.colors:[]).filter(wn).map(Xe).slice(0,256),o.palette.colors.length||(o.palette.colors=["#000000","#ffffff"]),o.palette.name=o.palette.name||"Custom"):h==="extract"?o.palette.name=`Extracted (${o.palette.count})`:o.palette.name="None";let y=cn.some(E=>E.id===c.method)?c.method:t.dither.method;return o.dither={method:y,strength:Ue(c.strength,0,1,t.dither.strength),matrix:Vi(c.matrix)},o.alpha={threshold:Ue(u.threshold,0,1,t.alpha.threshold)},o.cleanup={orphans:sn(s.orphans,!1),smooth:sn(s.smooth,!1)},o.outline={mode:Gt(l.mode,["none","outer","inner"],"none"),color:wn(l.color)?Xe(l.color):t.outline.color,corners:sn(l.corners,!1)},o.export={size:Gt(p.size,["scale","source"],"scale"),scale:Math.round(Ue(p.scale,1,64,t.export.scale)),indexed:sn(p.indexed,t.export.indexed),grid:sn(p.grid,!1),gridColor:wn(p.gridColor)?Xe(p.gridColor):t.export.gridColor},o}function Vi(e){if(!Array.isArray(e)||!e.length||!Array.isArray(e[0]))return null;let t=Math.min(16,e.length),n=Math.min(16,e[0].length),o=[];for(let i=0;i<t;i++){let r=[];for(let a=0;a<n;a++){let c=Number((e[i]||[])[a]);r.push(Number.isFinite(c)?c:0)}o.push(r)}return o}var Jt=[{id:"original",label:"Original",ratio:null},{id:"1:1",label:"1:1",ratio:1},{id:"4:3",label:"4:3",ratio:4/3},{id:"3:4",label:"3:4",ratio:3/4},{id:"3:2",label:"3:2",ratio:3/2},{id:"2:3",label:"2:3",ratio:2/3},{id:"16:9",label:"16:9",ratio:16/9},{id:"9:16",label:"9:16",ratio:9/16}];function Cn(e,t,n={}){let o=(Jt.find(s=>s.id===n.aspect)||Jt[0]).ratio||e/t,i=e,r=e/o;r>t&&(r=t,i=t*o);let a=Math.max(1,n.zoom||1);i=Math.max(1,Math.min(e,Math.round(i/a))),r=Math.max(1,Math.min(t,Math.round(r/a)));let c=n.x??.5,u=n.y??.5;return{x:Math.round((e-i)*c),y:Math.round((t-r)*u),w:i,h:r}}function Bo(e,t,n){let o,i;return n.mode==="block"?(o=Math.max(1,Math.round(e/n.block)),i=Math.max(1,Math.round(t/n.block))):(o=n.width,i=n.height||Math.max(1,Math.round(o*t/e))),{width:Math.min(En,o),height:Math.min(En,i)}}function Xi(e,t){let n={};for(let o of Object.keys(e)){if(o==="version")continue;let i=e[o],r=t[o];if(i&&typeof i=="object"&&!Array.isArray(i)){let a={};for(let c of Object.keys(i))JSON.stringify(i[c])!==JSON.stringify(r&&r[c])&&(a[c]=i[c]);Object.keys(a).length&&(n[o]=a)}else JSON.stringify(i)!==JSON.stringify(r)&&(n[o]=i)}return n}var No={enc(e){let t=new TextEncoder().encode(e),n="";for(let o of t)n+=String.fromCharCode(o);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")},dec(e){let t=atob(e.replace(/-/g,"+").replace(/_/g,"/"));return new TextDecoder().decode(Uint8Array.from(t,n=>n.charCodeAt(0)))}};function Go(e){let t=at(e),n=Xi(t,Et());return n.palette&&(t.palette.source!=="custom"&&(delete n.palette.colors,delete n.palette.name),t.palette.source!=="builtin"&&delete n.palette.id,t.palette.source!=="extract"&&delete n.palette.count),n.palette&&!Object.keys(n.palette).length&&delete n.palette,n}function Jn(e){return No.enc(JSON.stringify({v:kn,...Go(e)}))}function Qn(e){let t=String(e),n=/[#&?]s=([A-Za-z0-9_-]+)/.exec(t);n&&(t=n[1]);let o=JSON.parse(No.dec(t));return delete o.v,at(o)}function Qt(e){return JSON.stringify({$schema:"image-to-pixel/settings",version:kn,...Go(e)},null,2)}function eo(e){let t=typeof e=="string"?JSON.parse(e):e;return delete t.$schema,at(t)}function Lt(e,t){let n=JSON.parse(JSON.stringify(e));for(let o of Object.keys(t||{}))t[o]&&typeof t[o]=="object"&&!Array.isArray(t[o])&&n[o]&&typeof n[o]=="object"?Object.assign(n[o],t[o]):n[o]=t[o];return at(n)}vt();var jo="DHos2hHvghjhcwXqwKFF/I5L2ny43U2CNthWL2uZuIRL+h7EVxA0YALtMcH8NbbVUPllGoW/JOwz00rvXqMkVz7EYJ7BTqNbvi6qPIwRXa4kwO9YHI8KwRmt7YvNQV/mNKB2OofloLpEyqZhCYxtF4KtQ8mZ4Ud9uQiHHTy+cdiT8wWJO2/UDP6DUtBm3jLocQ+aLq/9atWZRXgD4R/EEGjRAe6qJdB1khZ7SeCqRPAwzwl3Ll6tGP9rqt+W6hSza0+s3xryLJNAsxbxI7d9zEGHZ9NGeiRZ8WYnsVKkdvOyj1a5RmcKU+gq9ZjOIny/XY7nuPcM1p1VOs4rZkyKMhzoKHpfsMR4Ycudb5BLAZ8e96gF6pW0Ow2904T3NpJOHzLhFoH1ltc9tVoTOWXmAqIjO2ZOinMm3I8PfsMA/Muevj/SmkoB6SHcCzqv+8Vg3k29OGEXyeSHnUARacEG2ofHbZvON70gaYnbdsKujVL+c9qlHLLHRGrvtkLlpVt5CVKID/swjak9VIDoXRUzdJMmfdCKpUttLftb3Jko7mOuR/8rXg12qPwDoUbrDy7HQrYPk+Y09QisHFeZciQ93WT0r2rFVtls9pS7IMqGpu4S2FQO8yvXAK14H7R/T6M3GIAHpuuNQsxVMsghXpp73xqGW8xJfl+chMkv9hXQspEb1TYgoXsTKcEGZKFE31K/PrGabbtdgetUzjnoFcdv0Oq9adNOteITmXLwh7j5PWOg8S5xAbon1Uvha76JSukvwJl+7UPitYZK0Tb6cyoJa4P4Lt5BHZu/GouiYkT6C49XI4k4GmcqgdhBrgxQJtMIv0fXp/uP6RJ2OwOpWwx/a0ECUcsMYjSc63erFI3Mm+kiXwSMqf83cEj1B8KHny61QNig+MeX9KxeHeRqxH+pbpEjgRY6aVCftP2WKu3Iofqx422nkL31FV0f203uXLhD1KzFTnnMCtmzLNt0IOFge+0BcFEQdz0Ewn0unj7eG/RR47NX078uzR9HfthwOR5YLIUU/ylMcspAuIKeADN7D5N2NeEUZJVRfJxbO7RPyxmVwjKr3LpV6qBH/s0AkF0yxgVw8JQMc4nmZL8RT7aL3JzGPV7WiAOi6GcpyG6y2PtXGvCZKb3oIfEOyv2RBaT4R2XlhB6SLG3ZEYhUcum7n3w9oipIrvZWBa0w9J/SCGgY7Kt3G7PgM5EO/ULiUSSlOc9ptFWBOq1pQ4Ibbuc1ciKxDUph+8YZj123Hq0qShD6zWLhgCDWO5zbhV4ic/dJgDNRzvFEYHzDU62KF5h/Yb2LAkP6ywePxeCnvSpbx4PbkfG/oj56sDfJ4Tz2hNlsjSCvDsRSkLpxFkLKlT6nv9yYBYotmxD3Itx4Nbz1COch2nijG2ziXC4XVj3al7MKVDptK9UG50/1CXeiYhXBOORaQZT/agkt8ljmtADoK1tw+bdmxHKrvUZpBdVNa55BrE/pNLqHRaT5cZ3xfhRI75vPGH6WXSWoZpsoStGUVaQDt9F1M6rdyIqkIXtjiNUOJkoV5yHcUzCGpfKRH80uw3IPlF/wJ9YTu4sAzCRt4DBlt/1R4r2L2xeD7LwG8SVw+IAj5RVLe18RSdMx/ky4ocyuhlpAkgbqyxRXt37oWof+KbLQCpdUezncSmKmw4yrH4MCpzcScjLKValrOXqwyjVOnGKz7504+a9smMEVOntkNNSg/cd9YJk82yhFCqcXzFWBPHCryO5oIrD/NlII81rERXXL60yz+z8Q4I7WRw+L1wnChicCvIAe4QlX5ZL0A+MfdA43tiX3dqpn+pbWbkC55Rv0SC4HlsWAD5bedzzSl+cmjmOgBJF5wy1aHZvkW6rrOVPUauhUyj+Lq3AjUJx+wEewbOFNGL4CjMNPLvKOAaBckNuCtFnhMnDKHrWJKQ9erxf2LM9fIO6euP5pvyx5HW/2kkKmK5pn9S/E2bM88liP7xWXg9dZ7jgafKteI9J1K7wOZ/k+GqXuSWX3UKnuftpPunxE5K5OcgE8ghLvQ5q1C8YWdNcFuhd/Rg5ozycK1S1cyTqkKpV10OYKv+pQrvtA0SSdzI5UuymeAthvQ8A1bhLYlwuHNNSVx1KxjsXgTH81rvtLhexV25n6iLueabN6qOsHarjfSaFkP5iBOhaJbqhRdgPnfA7Ugze6HZ0KkPKmOGbF+hVg5yH0MF4EKGTR51iLHaw7b6gsWxtI4DX8RSBRf/ocYAwosv0bbN/HWeYS87cwZEP8rG7sjV3+ySlYgOkkUrR2pUaMbaXZdv2kGJUnwmXgJr4Jyul1AX2TEL+M3LFCyI3yzodP0jCeBrMnmDqD3sKWLFkYSsYuek3asAXNcps82Ci8B98ZP7SEO75xRe4Qlc+BTo81pfVTzmDmbg2cMHWoUzdzBLmM9mY92nHPWR6kEs3kkrEH3aQTa5dDtxvvC4j2VoDEmFLKElvxANOeeD9c/yDdYsUsshqkKT3PXOwB2R7BmuJgH0rAhaZOCI/0bk6CYzH3aIU/u+Qh+lZ/qErGbBzmM2b2JZveibBVL7njBZpysBKKceJBgvi4kyG1SYVm7BNArOp4DO4d48ItsDzfvwyfR88l81d9N47UK+FiMa+bQ7YLftFtNEsdfvlhI6lIyDjtTA6X02kUUHrfbP+jKrNaftY0n81eNXmeYdEAjSbwuHkTqZABza4SarwDk9AQ8nTUlEmqBsCj5cYPkNd28RZfob79XDK8jO0KOJgYPdCN+CWSaBlIspH2EkZ1/6ZXbzneUMIz62VL9JxGd/5TgilZFfAv4F38dStlrDpRvTCT5HsniLAF5UKhyF7Wu1V3EEjICLr8f9okVbvmhhlCy5geifxfdqEhgsYw6BqxNtzApYdoxSCNPxSYSczrCYdm0AJB2BpNzGMlca8qhQbmqdpwm1fdPqUDbNM5qSjAae0I2LIrC9NE4rEJW4jKZ58HSes4sU+feNK28oEcdKH5HqpUumvzpHeX+hbbS/dqkCE2ufQqeR1g8LSADWKY3zKqekhjooO5GI42cdelKE3wkHUf0AP4E+RYNQKn3lQqxUd+8JotP9cQN7ZZgJwZykfwYwJCrIvMlyxDlPrHTROLUyPJ8jvcT/dgw+1EEOWBFNW3YZmDbb0mlHDOXzi5jGHfNhTTi7xb7IfPAO09tS+hfc2U5GcO7FDC3R90NexvzPu1kgVtIZh1A6Milbhqwz5YLvNF3jSjS/C7IYj8F9UIkbNuVwl/JW5Koi3EdFzqDFW0GFHXtzpyCKdTugSvnTwNXjGC6bHKL+VQe/tULaD4iqQKwh5cyYQIQN+fTXOiP/YmxeSm/MevG9pglRXahqwm/HYwfx2i/odo6I7WXSCA2KPhwlUXRYvRqzYMjd0CbyDQaH6r/xbXYrB5DsQv5GSrT3scRjUFk+k2fP5NwDpn00Cd6MaQXivRFD4leEXzwExyGT+qff9hEmy61mLAPOa0R+ooTo9rNpn0KVzqgRHNhgPtmmaL0k1ougmrKJoE748Ru1wEReO8TK32yJzgC44r+ZVk7A2hwSrwlEUhfJtahA2UvtsA7bYcSM2okUa9JFrUMLreWKkVhe9C03HlV3nJTXAn+Kp0DJV7WBhqL7JlqQPRL8l1O95ZhBbjpvMSyC36XjpzpUR93YptAzLycJ7/j0pzEfh34CueXIwTti+nGPSvz4U00iLuMcGoitJU7n1GtIQcUZAAtDfHVm80Tdt0nrYZyyVgyA5W+bHVUxe1OQ3FnSc4yUe9Gss0+WXVRoMtkw1kn1C3YtYAROQRPcYX41naova/ZZz4egbUuoitHUDehfOR4zSevD0jfZfJZH/dXey1ZgSUbfR8qU6SB+vEWuM72RrpiDuSc/xagaMllXI2CGo/J+MZS6+WJf4LZO9WC2tMB655HemRZeYRQNYoqkMahk7psTNTCN0hvHWcHmymT4CycQr0pRu1LcvxYr39rYzrsobQdS/rZj99oji9kc2nNsFb/URvBsZMr++IAPltltOnfBbShr5qPu9WNrj/AsbxJkPNVyrZZpkHd0AQUCnSHk4OWpLGE9e1UM4g5Xgq+IHbJI7LrNwpn3QyX5u8NOMOMf5EmuocoovODd6JRXgZjV/kq3nASYfhUajniMmgYH7Dn/w8p1aKGuJvjEkRtlEXoGkOUzWFXfsKw9xKG4JXwXNdtidiS/sueaxmI5zaOL6gETORBuwWOMEc0TFyDPUz2XAl5AZ5+DKaAfWtZNh06UK38pfiErtGjyOneM/uoiCTyQLid8MHtU8X88xYrWr4SHPI/WSdt3b6aJRZst1DkANIuWXCQqxpv1ktyTycB4kw0ngmqGvQfOZU9jkGY0Db9EyDqTSQ12fjoEB/CessGYXfUyI91lsmoUQB8iKaY77rqIQclNQh6j/do4Ed/VjCo18DTu0/HTOzFGuSsciGDWU32RP3Rx+CM8WQKLlMj9WoAbmOr38N5YS81nc6yhZ4K1reN/VSgQ+TdBPuaLsr3hT5lMqDuJPcXJ3UJ/FSLK7CIp9YbK+X8FkA/GPccsRBYzHoaRnxUsc3E1Wr44lP/50Qy3UJpGHPsilU0kGVf0twPrIxYwz+cQLASYIPb+iWedOK58ErzhO0d0erG5oN9nzOm0S+M4ylZfOVJmcGtdJBhrNN5bwk/UXGia4G5xmozojjH9RTqkOK8zLfo74+FvhQBUAYe19C4p7RMO1aOasiVgv6eNcE4iJ6w0j3nzFfHe9oLYk+mHoLZ+oxdrhf8i0QaZ955SzHHKd4YSKI214yp3S59aLXiSNoEI16vtmK6sCGKFCdbEa1O90Vgs1z6JXCAKXSE+xW2qYbm0zZO47EVfdBuxWZatlUC839Swi2zhvfjVIzB/LAOPfJTARoF0huo+G3FcX+hAqZWbM+D6wpSn37WHHDL4E9813EIKIAd6/RB45P9TqD6rk4lqxsgJNGYSTHbrZJfZtYsCam/pov1xI+Yo4lWqjRb/Ak4FKAz2PbF7hEnQSwz4wIfP9s50UfgzXpYsMEoCVJehTHJ/EBrv+cFu2WYBnYCXPnPH/OuV31esvuOdkaTjCmjWm3+QujNpEohtb4YSNJ360xVbuY2WumzCh7sVfQkPJh5D9Z5nE31Hs+3Syp7UaL0GEeUAuPrikNqm2XffbBAdQYM5RF7HbI8VscO3fGnWcUjc8RLFr7SBSY4B78agquIoigwS2JuwxSrQKFw24xuQ+WsPB0QeVWhEfgBrJBZYRR68ZvH7xUBa1upOKTDfQ5ue9DfuywC4q6aEw5hLdB3VPVEWvLHFzpks5j90wbpPlN4DKF1h/Flvm+IFzLJOOhO3qnWOCKL+dCGb9LJ7FR1HUipGPFPHTRMfWqzBHnJ5d5NbRIl/epQnMmtjmW0lyAI27IBGSmNwdnMaDzcJIPvP0SKtUKsGeY1Xz+jNhshRiZVuIEkSOj5lMBcZJZoW/DBPuD4g==";function Wi(e){return typeof atob=="function"?Uint8Array.from(atob(e),t=>t.charCodeAt(0)):new Uint8Array(Buffer.from(e,"base64"))}function en(e){let t=[[0]];for(let n=1;n<e;n*=2){let o=[];for(let i=0;i<n*2;i++)o.push(new Array(n*2));for(let i=0;i<n;i++)for(let r=0;r<n;r++){let a=4*t[i][r];o[i][r]=a,o[i][r+n]=a+2,o[i+n][r]=a+3,o[i+n][r+n]=a+1}t=o}return t}function Vo(e){let t=e.length,n=e[0].length,o=[];for(let r=0;r<t;r++)for(let a=0;a<n;a++)o.push({i:r*n+a,v:e[r][a]});o.sort((r,a)=>r.v-a.v||r.i-a.i);let i=new Uint8Array(n*t);return o.forEach((r,a)=>{i[r.i]=a}),i}function qi(e){let t=[];for(let n=0;n<e;n++){let o=[];for(let i=0;i<e;i++){let r=(i+.5)/e*2*Math.PI,a=(n+.5)/e*2*Math.PI;o.push(-(Math.cos(r)+Math.cos(a))+(i*e+n)*1e-9)}t.push(o)}return t}var Yi=[[7,13,11,4],[12,16,14,8],[10,15,6,2],[5,9,3,1]],to=new Map;function Xo(e,t=null){if(e==="custom"){let i=t&&t.length?t:en(4);return{w:i[0].length,h:i.length,levels:i.length*i[0].length,values:Vo(i)}}if(to.has(e))return to.get(e);let n,o=i=>({w:i[0].length,h:i.length,levels:i.length*i[0].length,values:Vo(i)});switch(e){case"bayer2":n=o(en(2));break;case"bayer4":n=o(en(4));break;case"bayer8":n=o(en(8));break;case"bayer16":n=o(en(16));break;case"cluster4":n=o(Yi);break;case"cluster8":n=o(qi(8));break;case"lines":n=o([[0],[2],[1],[3]]);break;case"bluenoise":n={w:64,h:64,levels:256,values:Wi(jo)};break;default:n=o(en(4))}return to.set(e,n),n}function Wo(e){let t=String(e).split(/\r?\n|;/).map(o=>o.trim()).filter(o=>o&&!/^\//.test(o)).map(o=>o.replace(/[[\]]/g,"").split(/[\s,]+/).filter(Boolean).map(Number));if(!t.length)throw new Error("Matrix is empty");let n=t[0].length;if(t.some(o=>o.length!==n||o.some(i=>!Number.isFinite(i))))throw new Error("Every row needs the same number of values");if(n>16||t.length>16)throw new Error("Matrices are limited to 16\xD716");return t}var jt=(e,t)=>t.map(([n,o,i])=>[n,o,i/e]),qo={"floyd-steinberg":jt(16,[[1,0,7],[-1,1,3],[0,1,5],[1,1,1]]),atkinson:jt(8,[[1,0,1],[2,0,1],[-1,1,1],[0,1,1],[1,1,1],[0,2,1]]),"sierra-lite":jt(4,[[1,0,2],[-1,1,1],[0,1,1]]),sierra:jt(32,[[1,0,5],[2,0,3],[-2,1,2],[-1,1,4],[0,1,5],[1,1,4],[2,1,2],[-1,2,2],[0,2,3],[1,2,2]]),burkes:jt(32,[[1,0,8],[2,0,4],[-2,1,2],[-1,1,4],[0,1,8],[1,1,4],[2,1,2]]),jarvis:jt(48,[[1,0,7],[2,0,5],[-2,1,3],[-1,1,5],[0,1,7],[1,1,5],[2,1,3],[-2,2,1],[-1,2,3],[0,2,5],[1,2,3],[2,2,1]]),stucki:jt(42,[[1,0,8],[2,0,4],[-2,1,2],[-1,1,4],[0,1,8],[1,1,4],[2,1,2],[-2,2,1],[-1,2,2],[0,2,4],[1,2,2],[2,2,1]])},no=12;function Yo(e){let t=1;for(let[n,o]of e)o>0&&(t=Math.max(t,Math.floor(-n/o)+1));return t}var Ko=(e,t,n)=>e-1+n*(t-1)+1;vt();function Sn(e,t=16,n={}){let{maxSamples:o=4e4,alphaThreshold:i=.5}=n,r=e.width*e.height,a=Math.max(1,Math.floor(r/o)),c=[];for(let f=0;f<r;f+=a){let h=f*4;e.data[h+3]<i*255||c.push([e.data[h],e.data[h+1],e.data[h+2]])}if(!c.length)return["#000000","#ffffff"].slice(0,Math.max(1,t));let u=[c];for(;u.length<t;){let f=-1,h=-1,y=0;if(u.forEach((M,x)=>{if(!(M.length<2))for(let S=0;S<3;S++){let b=255,_=0;for(let P of M)P[S]<b&&(b=P[S]),P[S]>_&&(_=P[S]);let L=(_-b)*Math.sqrt(M.length);L>h&&(h=L,f=x,y=S)}}),f<0||h<=0)break;let E=u[f].slice().sort((M,x)=>M[y]-x[y]),v=E.length>>1;u.splice(f,1,E.slice(0,v),E.slice(v))}let s=u.map(f=>Ki(f));for(let f=0;f<6;f++){let h=s.map(()=>[0,0,0,0]);for(let y of c){let E=0,v=1/0;for(let x=0;x<s.length;x++){let S=y[0]-s[x][0],b=y[1]-s[x][1],_=y[2]-s[x][2],L=S*S+b*b+_*_;L<v&&(v=L,E=x)}let M=h[E];M[0]+=y[0],M[1]+=y[1],M[2]+=y[2],M[3]++}s=s.map((y,E)=>h[E][3]?[h[E][0]/h[E][3],h[E][1]/h[E][3],h[E][2]/h[E][3]]:y)}let l=[...new Set(s.map(f=>Nt(f)))],p=f=>{let h=parseInt(f.slice(1),16);return .2126*(h>>16)+.7152*(h>>8&255)+.0722*(h&255)};return l.sort((f,h)=>p(f)-p(h))}function Ki(e){let t=0,n=0,o=0;for(let i of e)t+=i[0],n+=i[1],o+=i[2];return[t/e.length,n/e.length,o/e.length]}vt();function An(e,t,n,o="box",i=null){let r=i?i.x:0,a=i?i.y:0,c=i?i.w:e.width,u=i?i.h:e.height,s=e.data,l=e.width,p=new Float32Array(t*n*4),f=o==="nearest"?1:Math.min(16,Math.max(1,Math.ceil(c/t))),h=o==="nearest"?1:Math.min(16,Math.max(1,Math.ceil(u/n))),y=new Int32Array(t*f),E=new Int32Array(n*h);for(let v=0;v<t;v++)for(let M=0;M<f;M++)y[v*f+M]=r+Math.min(c-1,Math.floor((2*(v*f+M)+1)*c/(2*t*f)));for(let v=0;v<n;v++)for(let M=0;M<h;M++)E[v*h+M]=a+Math.min(u-1,Math.floor((2*(v*h+M)+1)*u/(2*n*h)));for(let v=0;v<n;v++)for(let M=0;M<t;M++){let x=0,S=0,b=0,_=0;for(let P=0;P<h;P++){let R=E[v*h+P]*l;for(let j=0;j<f;j++){let C=(R+y[M*f+j])*4,D=s[C+3]/255;x+=s[C]/255*D,S+=s[C+1]/255*D,b+=s[C+2]/255*D,_+=D}}let L=(v*t+M)*4;_>0&&(p[L]=x/_,p[L+1]=S/_,p[L+2]=b/_),p[L+3]=_/(f*h)}return p}function _n(e,{brightness:t=0,contrast:n=0,saturation:o=0,hue:i=0,gamma:r=1}){if(!t&&!n&&!o&&!i&&r===1)return e;let a=n>=0?1/(1-.99*n):1+n,c=1/r,u=Math.cos(i*Math.PI/180),s=Math.sin(i*Math.PI/180),l=[.213+.787*u-.213*s,.715-.715*u-.715*s,.072-.072*u+.928*s,.213-.213*u+.143*s,.715+.285*u+.14*s,.072-.072*u-.283*s,.213-.213*u-.787*s,.715-.715*u+.715*s,.072+.928*u+.072*s];for(let p=0;p<e.length;p+=4){let f=e[p]+t,h=e[p+1]+t,y=e[p+2]+t;f=(f-.5)*a+.5,h=(h-.5)*a+.5,y=(y-.5)*a+.5;let E=f*vn[0]+h*vn[1]+y*vn[2],v=1+o;if(f=E+(f-E)*v,h=E+(h-E)*v,y=E+(y-E)*v,i){let M=l[0]*f+l[1]*h+l[2]*y,x=l[3]*f+l[4]*h+l[5]*y,S=l[6]*f+l[7]*h+l[8]*y;f=M,h=x,y=S}e[p]=Math.pow(kt(f),c),e[p+1]=Math.pow(kt(h),c),e[p+2]=Math.pow(kt(y),c)}return e}function Zo(e,t){for(let n=3;n<e.length;n+=4)e[n]=e[n]>=t&&e[n]>0?1:0;return e}var kt=e=>e<0?0:e>1?1:e;function Jo(e,t){let n=e.length,o=new Float64Array(n*3),i=new Float64Array(n*3);return e.forEach((r,a)=>{i.set([r[0]/255,r[1]/255,r[2]/255],a*3),o.set(t===1?[r[0]/255,r[1]/255,r[2]/255]:Zn(r[0]/255,r[1]/255,r[2]/255),a*3)}),{n,coords:o,rgb:i,distance:t}}var oo=[.299,.587,.114];function Qo(e,t,n,o){let i,r,a,c=1,u=1,s=1;e.distance===1?(i=t,r=n,a=o,c=oo[0],u=oo[1],s=oo[2]):[i,r,a]=Zn(t,n,o);let l=0,p=1/0,f=e.coords;for(let h=0;h<e.n;h++){let y=i-f[h*3],E=r-f[h*3+1],v=a-f[h*3+2],M=c*y*y+u*E*E+s*v*v;M<p&&(p=M,l=h)}return l}function er(e,t,n,o){let i=new Uint8ClampedArray(t*n*4),r=o.quantize?Jo(o.palette,o.distance):null,a=o.kind==="ordered"?o.map:null,c=a?o.spread*o.settings.dither.strength:0;for(let u=0;u<n;u++)for(let s=0;s<t;s++){let l=(u*t+s)*4;if(e[l+3]<.5)continue;let p=e[l],f=e[l+1],h=e[l+2];if(r){if(a){let E=(a.values[u%a.h*a.w+s%a.w]+.5)/a.levels-.5;p=kt(p+E*c),f=kt(f+E*c),h=kt(h+E*c)}let y=Qo(r,p,f,h);i[l]=o.palette[y][0],i[l+1]=o.palette[y][1],i[l+2]=o.palette[y][2]}else i[l]=Math.round(p*255),i[l+1]=Math.round(f*255),i[l+2]=Math.round(h*255);i[l+3]=255}return i}function tr(e,t,n,o){let i=new Uint8ClampedArray(t*n*4),r=Jo(o.palette,o.distance),a=new Float32Array(t*n*3),c=o.settings.dither.strength,u=o.kernel;for(let s=0;s<n;s++)for(let l=0;l<t;l++){let p=s*t+l,f=p*4;if(e[f+3]<.5)continue;let h=kt(e[f]+a[p*3]*c),y=kt(e[f+1]+a[p*3+1]*c),E=kt(e[f+2]+a[p*3+2]*c),v=Qo(r,h,y,E),M=h-r.rgb[v*3],x=y-r.rgb[v*3+1],S=E-r.rgb[v*3+2];for(let[b,_,L]of u){let P=l+b,R=s+_;if(P<0||P>=t||R>=n)continue;let j=(R*t+P)*3;a[j]+=M*L,a[j+1]+=x*L,a[j+2]+=S*L}i[f]=o.palette[v][0],i[f+1]=o.palette[v][1],i[f+2]=o.palette[v][2],i[f+3]=255}return i}var Tn=(e,t)=>e[t+3]===0?-1:e[t]<<16|e[t+1]<<8|e[t+2],nr=[[0,-1],[1,0],[0,1],[-1,0]];function or(e,t,n){let o=e.slice();for(let i=0;i<n;i++)for(let r=0;r<t;r++){let a=(i*t+r)*4,c=Tn(o,a),u=[],s=[];for(let[f,h]of nr){let y=r+f,E=i+h;if(y<0||E<0||y>=t||E>=n)continue;let v=(E*t+y)*4;u.push(Tn(o,v)),s.push(v)}if(u.length<2||u.includes(c))continue;let l=0,p=0;for(let f=0;f<u.length;f++){let h=0;for(let y=0;y<u.length;y++)u[y]===u[f]&&h++;h>p&&(p=h,l=f)}e.set(o.subarray(s[l],s[l]+4),a)}return e}function rr(e,t,n){let o=e.slice();for(let i=0;i<n;i++)for(let r=0;r<t;r++){let a=(i*t+r)*4,c=Tn(o,a),u=[],s=[];for(let l=-1;l<=1;l++)for(let p=-1;p<=1;p++){let f=Math.min(t-1,Math.max(0,r+p)),y=(Math.min(n-1,Math.max(0,i+l))*t+f)*4;u.push(Tn(o,y)),s.push(y)}for(let l=0;l<9;l++){if(u[l]===c)continue;let p=0;for(let f=0;f<9;f++)u[f]===u[l]&&p++;if(p>=5){e.set(o.subarray(s[l],s[l]+4),a);break}}}return e}function ir(e,t,n,{mode:o,color:i,corners:r}){if(o==="none")return e;let a=e.slice(),c=(l,p)=>l>=0&&p>=0&&l<t&&p<n&&a[(p*t+l)*4+3]>0,u=(l,p)=>l>=0&&p>=0&&l<t&&p<n,s=r?[[0,-1],[1,0],[0,1],[-1,0],[-1,-1],[1,-1],[1,1],[-1,1]]:nr;for(let l=0;l<n;l++)for(let p=0;p<t;p++){let f=c(p,l),h=!1;for(let[y,E]of s){let v=p+y,M=l+E;if(u(v,M)&&(o==="outer"?!f&&c(v,M):f&&!c(v,M))){h=!0;break}}if(h){let y=(l*t+p)*4;e[y]=i[0],e[y+1]=i[1],e[y+2]=i[2],e[y+3]=255}}return e}function ar(e,t){let n=at(e),o=Cn(t.width,t.height,n.frame),{width:i,height:r}=Bo(o.w,o.h,n.size),a=n.palette.colors;n.palette.source==="extract"&&(a=Zi(t,n,i,r,o));let c=n.palette.source!=="none"&&a.length>0,u=c?a.map(wt):[],s=c?Mn(n.dither.method):"none";n.dither.strength<=0&&(s="none");let l=s==="ordered"?Xo(n.dither.method,n.dither.matrix):null,p=s==="diffusion"?qo[n.dither.method]:null,f=p?Yo(p):1;return{settings:n,srcWidth:t.width,srcHeight:t.height,crop:o,width:i,height:r,quantize:c,kind:s,palette:u,paletteHex:c?a.slice():null,distance:n.palette.distance==="rgb"?1:0,spread:c?zo(u):0,map:l,kernel:p,skew:f,waves:p?Ko(i,r,f):0,outline:{mode:n.outline.mode,color:wt(n.outline.color),corners:n.outline.corners}}}function Zi(e,t,n,o,i){let r=Math.min(1,160/Math.max(n,o)),a=Math.max(1,Math.round(n*r)),c=Math.max(1,Math.round(o*r)),u=An(e,a,c,"box",i);_n(u,t.adjust);let s=new Uint8ClampedArray(u.length);for(let l=0;l<u.length;l++)s[l]=Math.round(u[l]*255);return Sn({data:s,width:a,height:c},t.palette.count,{alphaThreshold:Math.max(.01,t.alpha.threshold)})}function sr(e,t){let{width:n,height:o,settings:i}=e,r=An(t,n,o,i.size.resample,e.crop);_n(r,i.adjust),Zo(r,i.alpha.threshold);let a=e.kind==="diffusion"?tr(r,n,o,e):er(r,n,o,e);return i.cleanup.orphans&&or(a,n,o),i.cleanup.smooth&&rr(a,n,o),ir(a,n,o,e.outline),a}var Ji="2.0.0",ln=4,cr="glcanvas",Se=class extends Error{constructor(e,t){super(e),this.name="ShaderMateError",t&&Object.assign(this,t)}},lr=new Set;function Ht(e,...t){lr.has(e)||(lr.add(e),console.warn("[ShaderMate]",...t))}var co=typeof window<"u"&&typeof document<"u",Qi=e=>Array.isArray(e)||ArrayBuffer.isView(e)&&!(e instanceof DataView),ur=e=>e==null?[]:Array.isArray(e)?e:[e],dr=e=>e>0&&(e&e-1)===0;function ea(e){var t,n,o,i;if(e==null)return null;if(Array.isArray(e))return[(t=e[0])!=null?t:0,(n=e[1])!=null?n:0,(o=e[2])!=null?o:0,(i=e[3])!=null?i:1];if(typeof e=="string"&&co){let r=document.createElement("canvas");r.width=r.height=1;let a=r.getContext("2d");a.fillStyle=e,a.fillRect(0,0,1,1);let c=a.getImageData(0,0,1,1).data;return[c[0]/255,c[1]/255,c[2]/255,c[3]/255]}return null}function ta(){if(!co)return!1;let e=location.hostname;return location.protocol==="file:"||e==="localhost"||e==="127.0.0.1"||e===""||e.endsWith(".local")}var na=class{constructor(e){this.gl=e,this._items=new Map,this._nextId=1}add(e,t){let n=this._nextId++;return this._items.set(n,{obj:e,count:1,type:t}),n}ref(e){let t=this._items.get(e);return t&&t.count++,e}get(e){let t=this._items.get(e);return t?t.obj:null}unref(e){let t=this._items.get(e);t&&(t.count--,t.count<=0&&this._destroy(e,t))}_destroy(e,t){let{obj:n,type:o}=t,i=this.gl;switch(o){case"texture2D":case"textureCube":i.deleteTexture(n);break;case"fbo":i.deleteFramebuffer(n);break;case"buffer":i.deleteBuffer(n);break;case"program":i.deleteProgram(n);break}this._items.delete(e)}dispose(){for(let[e,t]of[...this._items])this._destroy(e,t)}};function oa(e){let t=new Map;function n(c,u){return t.has(c)||t.set(c,new Set),t.get(c).add(u),()=>o(c,u)}function o(c,u){let s=t.get(c);s&&s.delete(u)}function i(c,u){let s=l=>{o(c,s),u(l)};return n(c,s)}function r(c,u){let s=t.get(c);if(s)for(let l of[...s])try{l(u)}catch(p){console.error(`[ShaderMate] error in "${c}" listener`,p)}e&&e(c,u)}function a(){t.clear()}return{on:n,off:o,once:i,emit:r,clear:a}}var fr={linear:e=>e,inQuad:e=>e*e,outQuad:e=>e*(2-e),inOutQuad:e=>e<.5?2*e*e:-1+(4-2*e)*e,inCubic:e=>e*e*e,outCubic:e=>1-Math.pow(1-e,3),inOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,outExpo:e=>e===1?1:1-Math.pow(2,-10*e),outBack:e=>1+2.70158*Math.pow(e-1,3)+1.70158*Math.pow(e-1,2),outElastic:e=>e===0||e===1?e:Math.pow(2,-10*e)*Math.sin((e*10-.75)*(2*Math.PI)/3)+1};function ra(){let e=new Map;function t(i,r,a,c,u={}){let{duration:s=500,delay:l=0}=u,p=typeof u.ease=="function"?u.ease:fr[u.ease]||fr.outCubic,f=e.get(i);f&&f.resolve(!1);let h=r(),y=Array.isArray(c)||ArrayBuffer.isView(c),E=y?Array.from(h??c):Number(h??0),v=y?Array.from(c):Number(c);return new Promise(M=>{let x={start:performance.now()+l,resolve:S=>{e.delete(i),M(S)},update(S){let b=s>0?ia((S-this.start)/s):1;if(b<0)return;let _=p(b);a(y?E.map((L,P)=>L+(v[P]-L)*_):E+(v-E)*_),b>=1&&this.resolve(!0)}};e.set(i,x)})}function n(i){for(let r of[...e.values()])r.update(i)}function o(i){if(i===void 0){for(let a of[...e.values()])a.resolve(!1);return}let r=e.get(i);r&&r.resolve(!1)}return{tween:t,update:n,cancel:o,get size(){return e.size}}}var ia=e=>e<0?e:e>1?1:e;function aa(e){let t;if(typeof e=="string")t=[{src:e}];else if(Array.isArray(e))t=e.map(i=>typeof i=="string"?{src:i}:{...i});else if(e&&typeof e=="object")t=[{...e}];else throw new Se("ShaderMate: expected a shader (string), a pass object, or an array of passes");if(!t.length)throw new Se("ShaderMate: no passes given");t.forEach((i,r)=>{var a,c,u,s,l;if(i.src==null&&(i.src=(s=(u=(c=(a=i.shader)!=null?a:i.frag)!=null?c:i.fragment)!=null?u:i.glsl)!=null?s:i.url),i.src==null)throw new Se(`Pass ${(l=i.name)!=null?l:r} has no shader source (use "shader")`);i.name==null&&(i.name=t.length===1?"main":"pass"+r),i.uniforms==null&&(i.uniforms={})}),t.some(i=>i.screen)||(t[t.length-1].screen=!0),t.filter(i=>i.screen).length>1&&console.warn("[ShaderMate] Multiple screen:true passes; last drawn wins.");let n=t.map(i=>i.name),o=n.filter((i,r)=>n.indexOf(i)!==r);if(o.length)throw new Se("Duplicate pass names: "+[...new Set(o)].join(", "));for(let i of t){let r=Array.isArray(i.channels)?i.channels:i.channels?[i.channels]:[];for(i.channels=r.slice(0,ln).map(a=>Cr(a,n,i.name));i.channels.length<ln;)i.channels.push(null)}return t}var sa=e=>typeof HTMLElement<"u"&&e instanceof HTMLElement,ca=e=>typeof ImageBitmap<"u"&&e instanceof ImageBitmap,la=e=>typeof WebGLTexture<"u"&&e instanceof WebGLTexture;function Cr(e,t=[],n=""){if(e==null||e===!1)return null;if(typeof e=="string")return t.includes(e)?{pass:e}:{url:e};if(sa(e)||ca(e))return{element:e};if(la(e))return{texture:e};let o={...e};return o.pass==null&&o.id!=null&&(o.pass=o.id),o.url==null&&o.image!=null&&(o.url=o.image),o.element==null&&o.canvas!=null&&(o.element=o.canvas),o.pass==null&&o.src!=null&&o.url==null&&o.video==null&&(o.url=o.src),o.pass!=null&&!t.includes(o.pass)&&console.warn(`[ShaderMate] Pass "${n}": channel references unknown pass "${o.pass}"`),o}function ro(e){return/[\r\n]/.test(e)||/^\s*(void|#|precision|uniform|in |out |\/\/|\/\*)/.test(e)||/[{};]/.test(e)}var ua=e=>typeof WebGL2RenderingContext<"u"&&e instanceof WebGL2RenderingContext;function da(e,t={}){let n=Object.assign({alpha:t.alpha!==!1,premultipliedAlpha:t.premultipliedAlpha!==!1,preserveDrawingBuffer:!!t.preserveDrawingBuffer,antialias:!!t.antialias,powerPreference:t.powerPreference||"default"},t.contextAttributes),o=t.webgl===void 0?"auto":String(t.webgl),i=null;if((o==="auto"||o==="2")&&(i=e.getContext("webgl2",n)),!i&&(o==="auto"||o==="1")&&(i=e.getContext("webgl",n)||e.getContext("experimental-webgl",n)),!i)throw new Se("WebGL not supported");return i}function fa(e,t){let n={};return t?(n.EXT_color_buffer_float=e.getExtension("EXT_color_buffer_float"),n.EXT_color_buffer_half_float=e.getExtension("EXT_color_buffer_half_float"),n.OES_texture_float_linear=e.getExtension("OES_texture_float_linear")):(n.OES_texture_float=e.getExtension("OES_texture_float"),n.OES_texture_half_float=e.getExtension("OES_texture_half_float"),n.OES_texture_float_linear=e.getExtension("OES_texture_float_linear"),n.OES_texture_half_float_linear=e.getExtension("OES_texture_half_float_linear"),n.OES_standard_derivatives=e.getExtension("OES_standard_derivatives"),n.WEBGL_color_buffer_float=e.getExtension("WEBGL_color_buffer_float"),n.EXT_color_buffer_half_float=e.getExtension("EXT_color_buffer_half_float"),n.WEBGL_depth_texture=e.getExtension("WEBGL_depth_texture"),n.EXT_shader_texture_lod=e.getExtension("EXT_shader_texture_lod")),n}function pa(e){let t=e.createBuffer();return e.bindBuffer(e.ARRAY_BUFFER,t),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),e.STATIC_DRAW),{bind(n){e.bindBuffer(e.ARRAY_BUFFER,t);let o=e.getAttribLocation(n,"a_position");o!==-1&&(e.enableVertexAttribArray(o),e.vertexAttribPointer(o,2,e.FLOAT,!1,0,0))},draw(){e.drawArrays(e.TRIANGLES,0,6)},dispose(){e.deleteBuffer(t)}}}function ha(e,t){var n;let o=t.split(`
|
|
11
11
|
`),i=o.findIndex(a=>/^\s*#line\s+1\b/.test(a))+1,r=[];for(let a of e.split(`
|
|
12
|
-
`)){let c=/ERROR:\s*\d+:(\d+):\s*(.*)/.exec(a);if(!c)continue;let
|
|
13
|
-
`):a.trim(),
|
|
14
|
-
${s}`,{pass:o,stage:
|
|
15
|
-
`).map((h,
|
|
16
|
-
`);console.error("[ShaderMate] "+
|
|
17
|
-
`+
|
|
12
|
+
`)){let c=/ERROR:\s*\d+:(\d+):\s*(.*)/.exec(a);if(!c)continue;let u=parseInt(c[1],10),s=i>0?i+u-1:u-1;r.push({line:u,message:c[2].trim(),source:(n=o[s])!=null?n:"",physical:s})}return r}function pr(e,t,n,{label:o="",showExpandedOnError:i=!0}={}){let r=e.createShader(t);if(e.shaderSource(r,n),e.compileShader(r),e.getShaderParameter(r,e.COMPILE_STATUS))return{shader:r};let a=e.getShaderInfoLog(r)||"";e.deleteShader(r);let c=ha(a,n),u=t===e.VERTEX_SHADER?"Vertex":"Fragment",s=c.length?c.map(p=>`line ${p.line}: ${p.message}`).join(`
|
|
13
|
+
`):a.trim(),l=new Se(`${u} shader compile error${o?` in pass "${o}"`:""}:
|
|
14
|
+
${s}`,{pass:o,stage:u,log:a,errors:c,source:n});if(i){let p=new Set(c.map(h=>h.physical)),f=n.split(`
|
|
15
|
+
`).map((h,y)=>`${p.has(y)?">>>":" "} ${String(y+1).padStart(4," ")} | ${h}`).join(`
|
|
16
|
+
`);console.error("[ShaderMate] "+l.message,{COMPILED:`
|
|
17
|
+
`+f})}else console.error("[ShaderMate] "+l.message);return{error:l}}function Sr(e,t,n,o){let i=pr(e,e.VERTEX_SHADER,t,o);if(i.error)return i;let r=pr(e,e.FRAGMENT_SHADER,n,o);if(r.error)return e.deleteShader(i.shader),r;let a=e.createProgram();if(e.attachShader(a,i.shader),e.attachShader(a,r.shader),e.linkProgram(a),e.deleteShader(i.shader),e.deleteShader(r.shader),!e.getProgramParameter(a,e.LINK_STATUS)){let c=e.getProgramInfoLog(a)||"";e.deleteProgram(a);let u=new Se(`Program link error${o&&o.label?` in pass "${o.label}"`:""}: ${c}`,{pass:o&&o.label,log:c});return console.error("[ShaderMate] "+u.message),{error:u}}return{program:a}}function hr(e,t){let n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS),o={};for(let i=0;i<n;i++){let r=e.getActiveUniform(t,i);r&&(o[r.name.replace(/\[0\]$/,"")]={loc:e.getUniformLocation(t,r.name),type:r.type,size:r.size})}return o}var Tr=`#version 300 es
|
|
18
18
|
layout(location=0) in vec2 a_position;
|
|
19
|
-
void main(){ gl_Position = vec4(a_position,0.0,1.0); }`,
|
|
20
|
-
void main(){ gl_Position = vec4(a_position,0.0,1.0); }`,
|
|
19
|
+
void main(){ gl_Position = vec4(a_position,0.0,1.0); }`,Ar=`attribute vec2 a_position;
|
|
20
|
+
void main(){ gl_Position = vec4(a_position,0.0,1.0); }`,ma=`#define texture2D(s,u) texture(s,u)
|
|
21
21
|
#define textureCube(s,u) texture(s,u)
|
|
22
22
|
#define TEX(s,u) texture(s,u)
|
|
23
23
|
#define TEX_LOD(s,u,l) textureLod(s,u,l)
|
|
24
|
-
`,
|
|
24
|
+
`,ga=`#define texture(s,u) texture2D(s,u)
|
|
25
25
|
#define TEX(s,u) texture2D(s,u)
|
|
26
26
|
#define TEX_LOD(s,u,l) texture2D(s,u)
|
|
27
|
-
`,
|
|
27
|
+
`,ba=`
|
|
28
28
|
#line 100000
|
|
29
29
|
void main(){
|
|
30
30
|
vec4 c = vec4(0.0);
|
|
31
31
|
mainImage(c, gl_FragCoord.xy);
|
|
32
32
|
outColor = c;
|
|
33
|
-
}`,
|
|
33
|
+
}`,ya=`
|
|
34
34
|
#line 100000
|
|
35
35
|
void main(){
|
|
36
36
|
vec4 c = vec4(0.0);
|
|
37
37
|
mainImage(c, gl_FragCoord.xy);
|
|
38
38
|
gl_FragColor = c;
|
|
39
|
-
}`,
|
|
39
|
+
}`,xa=`#version 300 es
|
|
40
40
|
precision highp float;
|
|
41
41
|
uniform sampler2D u_tex; uniform vec2 u_size; out vec4 o;
|
|
42
|
-
void main(){ o = texture(u_tex, gl_FragCoord.xy / u_size); }`,
|
|
42
|
+
void main(){ o = texture(u_tex, gl_FragCoord.xy / u_size); }`,wa=`precision highp float;
|
|
43
43
|
uniform sampler2D u_tex; uniform vec2 u_size;
|
|
44
|
-
void main(){ gl_FragColor = texture2D(u_tex, gl_FragCoord.xy / u_size); }`;function
|
|
45
|
-
`;function
|
|
44
|
+
void main(){ gl_FragColor = texture2D(u_tex, gl_FragCoord.xy / u_size); }`;function va(e,t,n){let o=Sr(e,t?Tr:Ar,t?xa:wa,{label:"blit"});if(o.error)throw o.error;let i=o.program,r=e.getUniformLocation(i,"u_tex"),a=e.getUniformLocation(i,"u_size");return{draw(c,u,s){e.bindFramebuffer(e.FRAMEBUFFER,null),e.viewport(0,0,u,s),e.useProgram(i),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,c),e.uniform1i(r,0),e.uniform2f(a,u,s),n.bind(i),n.draw()},dispose(){e.deleteProgram(i)}}}function lo(e,t){return t==="repeat"?e.REPEAT:t==="mirror"||t==="mirrored"?e.MIRRORED_REPEAT:e.CLAMP_TO_EDGE}function uo(e,t){return t==="nearest"?e.NEAREST:e.LINEAR}function Ea(e,t,n,o){let i=t?e.RGBA8:e.RGBA,r=e.RGBA,a=e.UNSIGNED_BYTE;return o.float==="full"||o.float===32?t?(i=e.RGBA32F,a=e.FLOAT):n.OES_texture_float&&(a=e.FLOAT):o.float&&(t?(i=e.RGBA16F,a=e.HALF_FLOAT):n.OES_texture_half_float?a=n.OES_texture_half_float.HALF_FLOAT_OES:n.OES_texture_float&&(a=e.FLOAT)),{ifmt:i,fmt:r,type:a}}function ka(e,t,n,o){let i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texImage2D(e.TEXTURE_2D,0,t,4,4,0,n,o,null);let r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,i,0);let a=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteFramebuffer(r),e.deleteTexture(i),a}function mr(e,t,n,o,i,r,a){let c=Ea(e,r,a,i),u=c;ka(e,c.ifmt,c.fmt,c.type)||(Ht("fmt-fallback","Requested float format not renderable on this device; falling back to 8-bit."),u={ifmt:r?e.RGBA8:e.RGBA,fmt:e.RGBA,type:e.UNSIGNED_BYTE});let s=i.filter;u.type!==e.UNSIGNED_BYTE&&s!=="nearest"&&((r?u.type===e.HALF_FLOAT||a.OES_texture_float_linear:u.type===e.FLOAT?a.OES_texture_float_linear:a.OES_texture_half_float_linear)||(s="nearest"));let l=e.createTexture();e.bindTexture(e.TEXTURE_2D,l);let p=lo(e,i.wrap),f=uo(e,s);e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,f),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,f),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,p),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,p),e.texImage2D(e.TEXTURE_2D,0,u.ifmt,n,o,0,u.fmt,u.type,null);let h=null;i.depth&&(!r&&!a.WEBGL_depth_texture?Ht("depth-tex","depth: true needs WebGL2 or WEBGL_depth_texture; ignoring."):(h=e.createTexture(),e.bindTexture(e.TEXTURE_2D,h),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),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.texImage2D(e.TEXTURE_2D,0,r?e.DEPTH_COMPONENT16:e.DEPTH_COMPONENT,n,o,0,e.DEPTH_COMPONENT,e.UNSIGNED_SHORT,null)));let y=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,y),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,l,0),h&&e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,h,0);let E=e.checkFramebufferStatus(e.FRAMEBUFFER);return E!==e.FRAMEBUFFER_COMPLETE&&console.warn("[ShaderMate] Framebuffer incomplete:",E),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindTexture(e.TEXTURE_2D,null),{texId:t.add(l,"texture2D"),depthId:h?t.add(h,"texture2D"):null,fboId:t.add(y,"fbo"),width:n,height:o,fmt:u}}function Pn(e,t){t&&(e.unref(t.texId),t.depthId&&e.unref(t.depthId),e.unref(t.fboId))}function Ma(e,t,n){let o=i=>Math.max(1,Math.round(i));return e==null||e==="screen"||e==="canvas"?[t,n]:e==="half"?[o(t/2),o(n/2)]:e==="quarter"?[o(t/4),o(n/4)]:typeof e=="number"?[o(t*e),o(n*e)]:Array.isArray(e)?[o(e[0]),o(e[1])]:typeof e=="object"&&e.width&&e.height?[o(e.width),o(e.height)]:[t,n]}var Ca={iResolution:"vec3",iTime:"float",iTimeDelta:"float",iFrame:"int",iFrameRate:"float",iMouse:"vec4",iDate:"vec4",iScroll:"vec2",iSampleRate:"float",iChannelTime:"float[4]",iChannelResolution:"vec3[4]",u_resolution:"vec2",u_time:"float",u_delta:"float",u_frame:"int",u_fps:"float",u_mouse:"vec2",u_mouseUV:"vec2",u_mouseDown:"float",u_date:"vec4",u_scroll:"vec2",u_pixelRatio:"float",u_aspect:"float",u_time_delta:"float",u_refresh_rate:"float",u_drag:"vec2",u_wheel:"float"},fo=e=>e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,""),Sa=`#define iGlobalTime iTime
|
|
45
|
+
`;function Ta(e,t){let n=fo(e);return!/\bfragColor\b/.test(n)||!/\bvoid\s+main\s*\(/.test(n)||/\bout\s+vec4\s+fragColor\b/.test(n)||/#define\s+fragColor\b/.test(n)?"":t?`out vec4 fragColor;
|
|
46
46
|
`:`#define fragColor gl_FragColor
|
|
47
|
-
`}var
|
|
48
|
-
`:`uniform ${s} ${
|
|
49
|
-
`}for(let
|
|
50
|
-
`)}for(let
|
|
47
|
+
`}var Aa={u_camera_pos:"vec3",u_camera_dir:"vec3",u_camera_view:"mat4",u_recursion:"int",u_max_recursion:"int",u_color_gamut:"int"},_a=["u_audio","u_keyboard","u_webcam","u_main"];function Pa(e){let t=fo(e);return/\bfragColor\b/.test(t)&&/\bvoid\s+main\s*\(/.test(t)&&!/\bmainImage\s*\(/.test(t)}function La(e,t=[],n={}){let o=fo(e),i="",r=u=>new RegExp("uniform\\s+(?:\\w+\\s+)*"+u+"\\b").test(o),a=u=>new RegExp("\\b"+u+"\\b").test(o),c=Object.assign({},Ca,n.fragcoord?Aa:null);n.mouseVec4&&(c.u_mouse="vec4"),n.scrollFloat&&(c.u_scroll="float");for(let u in c){if(!a(u)||r(u))continue;let s=c[u],l=/^(\w+)\[(\d+)\]$/.exec(s);i+=l?`uniform ${l[1]} ${u}[${l[2]}];
|
|
48
|
+
`:`uniform ${s} ${u};
|
|
49
|
+
`}for(let u=0;u<4;u++){let s="iChannel"+u;!a(s)||r(s)||(i+=`uniform ${t[u]==="cube"?"samplerCube":"sampler2D"} ${s};
|
|
50
|
+
`)}for(let u of new Set([..._a,...n.samplerNames||[]]))a(u)&&!r(u)&&(i+=`uniform sampler2D ${u};
|
|
51
51
|
`);return n.passCount>0&&/\bu_passes\b/.test(o)&&!r("u_passes")&&(i+=`uniform sampler2D u_passes[${n.passCount}];
|
|
52
|
-
`),i}var
|
|
53
|
-
// skipped include "${
|
|
54
|
-
`;else if(i.has(
|
|
55
|
-
// skipped include "${
|
|
56
|
-
`;else{i.add(
|
|
57
|
-
// begin include "${
|
|
58
|
-
${
|
|
59
|
-
// end include "${
|
|
60
|
-
`}catch(h){if(o(`[ShaderMate] Failed to load include "${
|
|
61
|
-
// failed include "${
|
|
62
|
-
`}finally{r.pop()}}}return s+c.slice(
|
|
52
|
+
`),i}var gr=e=>e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"");async function Ra(e,{loader:t,throwOnError:n=!1,warn:o=console.warn}={}){let i=new Set,r=[];async function a(c){let u=/^[ \t]*#include\s+["<]([^">]+)[">]/gm,s="",l=0,p;for(;p=u.exec(c);){let f=p[1];if(s+=c.slice(l,p.index),l=u.lastIndex,r.includes(f))o("[ShaderMate] Circular include:",f),s+=`
|
|
53
|
+
// skipped include "${f}" (circular)
|
|
54
|
+
`;else if(i.has(f))s+=`
|
|
55
|
+
// skipped include "${f}" (already included)
|
|
56
|
+
`;else{i.add(f),r.push(f);try{let h=await t(f),y=await a(h);s+=`
|
|
57
|
+
// begin include "${f}"
|
|
58
|
+
${y}
|
|
59
|
+
// end include "${f}"
|
|
60
|
+
`}catch(h){if(o(`[ShaderMate] Failed to load include "${f}"`,h),n)throw h;s+=`
|
|
61
|
+
// failed include "${f}"
|
|
62
|
+
`}finally{r.pop()}}}return s+c.slice(l)}return a(e)}function Ua(e){let t="";for(let n of e)if(typeof n=="string")t+=`#define ${n}
|
|
63
63
|
`;else if(n&&typeof n=="object")for(let o in n){let i=n[o];t+=i===!0||i===void 0?`#define ${o}
|
|
64
64
|
`:`#define ${o} ${i}
|
|
65
|
-
`}return t}var
|
|
66
|
-
`,
|
|
67
|
-
`),i.builtins&&!t&&o&&(
|
|
68
|
-
`),i.header&&(
|
|
65
|
+
`}return t}var _r={header:!0,builtins:!0,uniforms:!0,defines:!0,mainWrap:!0},Ia={header:!1,builtins:!1,uniforms:!1,defines:!1,mainWrap:!1};function Oa(e,{isGL2:t,defines:n=[],enableDerivatives:o=!1,inject:i=_r,channelTypes:r=[],builtinOpts:a={}}={}){if(!i||!Object.values(i).some(Boolean))return e;let c="",u=e,s=/^[ \t]*#version[^\n]*/m.exec(u);s&&(c=s[0].trim()+`
|
|
66
|
+
`,u=u.slice(0,s.index)+u.slice(s.index+s[0].length));let l="";if(c?l+=c:i.header&&t&&(l+=`#version 300 es
|
|
67
|
+
`),i.builtins&&!t&&o&&(l+=`#extension GL_OES_standard_derivatives : enable
|
|
68
|
+
`),i.header&&(l+=`precision highp float;
|
|
69
69
|
precision highp int;
|
|
70
|
-
`),i.builtins){
|
|
71
|
-
`)}i.uniforms&&(
|
|
72
|
-
`+
|
|
73
|
-
`:"")+c;return}let
|
|
74
|
-
`),i=/^\s*uniform\s+(?:(?:lowp|mediump|highp)\s+)?(\w+)\s+(\w+)(?:\s*\[\s*\d+\s*\])?\s*(?:=\s*([^;]+))?;\s*(?:\/\/(.*))?$/;return{source:o.map(a=>{var c,
|
|
75
|
-
`),uniforms:t,samplers:n}}function ka(e,t,n){let o=Ea(t),i=t.replace(/\[[^\]]*\]/g,"").trim(),r=/^ref:\s*(.+)$/i.exec(i);if(r){let a=r[1].trim(),c;return(c=/^pass\s*(\d+)(?::out(\d+))?$/i.exec(a))?{pass:"pass"+c[1],...o}:(c=/^pass:\s*(\S+)/i.exec(a))?{pass:c[1],...o}:/^main$/i.test(a)?{pass:"main",...o}:(c=/^sampler\s+(\w+)/i.exec(a))?{sameAs:c[1],...o}:null}if(e==="u_audio"||/audio/i.test(e)&&/^(mic|\[CAM\]|\[VIDEO\])?$/i.test(i))return/^https?:|^data:/i.test(i)?{audio:i,layout:"spectrogram"}:{mic:!0,layout:"spectrogram"};if(e==="u_webcam")return{camera:!0,...o};if(e==="u_keyboard")return{keyboard:!0};if(/^(https?:|data:)/i.test(i)){let a=i.split(/\s+/)[0];return/\.(mp4|webm|mov|ogv|m4v)(\?|$)/i.test(a)?{video:a,...o}:/\.(mp3|wav|ogg|m4a|aac|flac)(\?|$)/i.test(a)?{audio:a,layout:"spectrogram"}:n==="samplerCube"?null:{url:a,...o}}return null}function Ma(e){return/\bu_mouse\s*\.\s*[xyzw]*[zw]/.test(hr(e))}var Ca=35678,Sa=35680,Ta=e=>e.filter(t=>!t.cfg.screen);function _a(e,t,n={}){let o=[],i=Ta(t),r=t.find(l=>l.cfg.screen),a=new Map(t.map(l=>[l.name,l])),c=Object.assign({},e.cfg.annotatedSamplers,e.cfg.samplers);for(let l in e.uniformInfo){let s=e.uniformInfo[l];if(s.type!==Ca&&s.type!==Sa||/^iChannel\d$/.test(l))continue;let d=n[l]||c[l]||null,f;if(d&&d.sameAs&&(d=c[d.sameAs]||n[d.sameAs]||null),d||(l==="u_passes"&&s.size>1?d={array:i.slice(0,s.size)}:l==="u_main"?d=r?{pass:r.name}:null:(f=/^u_pass(\d+)$/.exec(l))&&i[+f[1]-1]?d={pass:i[+f[1]-1].name}:l.startsWith("u_")&&a.has(l.slice(2))?d={pass:l.slice(2)}:l==="u_audio"?d={mic:!0,layout:"spectrogram"}:l==="u_keyboard"?d={keyboard:!0}:l==="u_webcam"&&(d={camera:!0})),d&&d.pass!=null&&!a.has(d.pass)){let u=/^pass(\d+)$/.exec(d.pass);u&&i[+u[1]-1]?d={...d,pass:i[+u[1]-1].name}:d.pass==="main"&&r&&(d={...d,pass:r.name})}d&&o.push({name:l,info:s,spec:d})}return o}function Aa(e){let t=e.find(n=>n.cfg.screen);return t?e.some(n=>(n.samplers||[]).some(o=>o.spec.pass===t.name)||n.cfg.channels.some(o=>o&&o.pass===t.name)):!1}function Pa(e,{target:t=window,speed:n=1.5,sensitivity:o=.004}={}){let i=[0,0,0],r=-Math.PI/2,a=0,c=new Set,l=!1,s=0,d=0,f=[0,0,-1],u=new Float32Array(16),h=(L,T)=>{let P=L.key.length===1?L.key.toLowerCase():L.key;T?c.add(P):c.delete(P)},x=L=>h(L,!0),E=L=>h(L,!1),y=L=>{L.button===0&&(l=!0,s=L.clientX,d=L.clientY)},k=L=>{l&&(r+=(L.clientX-s)*o,a-=(L.clientY-d)*o,a=Math.max(-1.55,Math.min(1.55,a)),s=L.clientX,d=L.clientY)},b=()=>{l=!1},S=L=>{let T=f,P=-L.deltaY*.002*n;i[0]+=T[0]*P,i[1]+=T[1]*P,i[2]+=T[2]*P},w=()=>c.clear();t.addEventListener("keydown",x),t.addEventListener("keyup",E),e.addEventListener("pointerdown",y),window.addEventListener("pointermove",k),window.addEventListener("pointerup",b),e.addEventListener("wheel",S,{passive:!0}),window.addEventListener("blur",w);function A(){let L=f,T=[0,1,0],P=[L[1]*T[2]-L[2]*T[1],L[2]*T[0]-L[0]*T[2],L[0]*T[1]-L[1]*T[0]],z=Math.hypot(P[0],P[1],P[2])||1;P=P.map(I=>I/z);let v=[P[1]*L[2]-P[2]*L[1],P[2]*L[0]-P[0]*L[2],P[0]*L[1]-P[1]*L[0]];return u.set([P[0],v[0],-L[0],0,P[1],v[1],-L[1],0,P[2],v[2],-L[2],0,-(P[0]*i[0]+P[1]*i[1]+P[2]*i[2]),-(v[0]*i[0]+v[1]*i[1]+v[2]*i[2]),L[0]*i[0]+L[1]*i[1]+L[2]*i[2],1]),{right:P,up:v}}return{pos:i,dir:f,view:u,update(L){f[0]=Math.cos(a)*Math.cos(r),f[1]=Math.sin(a),f[2]=Math.cos(a)*Math.sin(r);let{right:T}=A(),P=n*L*(c.has("Shift")?3:1),z=(v,I)=>{i[0]+=v[0]*I,i[1]+=v[1]*I,i[2]+=v[2]*I};(c.has("w")||c.has("ArrowUp"))&&z(f,P),(c.has("s")||c.has("ArrowDown"))&&z(f,-P),(c.has("d")||c.has("ArrowRight"))&&z(T,P),(c.has("a")||c.has("ArrowLeft"))&&z(T,-P),(c.has("e")||c.has(" "))&&(i[1]+=P),(c.has("q")||c.has("c"))&&(i[1]-=P),A()},dispose(){t.removeEventListener("keydown",x),t.removeEventListener("keyup",E),e.removeEventListener("pointerdown",y),window.removeEventListener("pointermove",k),window.removeEventListener("pointerup",b),e.removeEventListener("wheel",S),window.removeEventListener("blur",w)}}}var mr=Object.create(null),Ce=(e,...t)=>t.forEach(n=>{mr[n.toLowerCase()]=e});Ce({kind:"f",n:1},"float","number","f","1f","1fv","float[]","uniform1f","uniform1fv");Ce({kind:"f",n:2},"vec2","2f","2fv","vec2[]","uniform2f","uniform2fv");Ce({kind:"f",n:3},"vec3","3f","3fv","vec3[]","uniform3f","uniform3fv");Ce({kind:"f",n:4},"vec4","4f","4fv","vec4[]","uniform4f","uniform4fv");Ce({kind:"i",n:1},"int","bool","boolean","i","1i","1iv","int[]","bool[]","uniform1i","uniform1iv");Ce({kind:"i",n:2},"ivec2","bvec2","2i","2iv","ivec2[]","bvec2[]","uniform2i","uniform2iv");Ce({kind:"i",n:3},"ivec3","bvec3","3i","3iv","ivec3[]","bvec3[]","uniform3i","uniform3iv");Ce({kind:"i",n:4},"ivec4","bvec4","4i","4iv","ivec4[]","bvec4[]","uniform4i","uniform4iv");Ce({kind:"u",n:1},"uint","1ui","1uiv","uint[]");Ce({kind:"u",n:2},"uvec2","2ui","2uiv","uvec2[]");Ce({kind:"u",n:3},"uvec3","3ui","3uiv","uvec3[]");Ce({kind:"u",n:4},"uvec4","4ui","4uiv","uvec4[]");Ce({kind:"m",n:2},"mat2","matrix2fv","mat2fv","uniformmatrix2fv");Ce({kind:"m",n:3},"mat3","matrix3fv","mat3fv","uniformmatrix3fv");Ce({kind:"m",n:4},"mat4","matrix4fv","mat4fv","uniformmatrix4fv");function La(e){return typeof e!="string"?null:mr[e.trim().toLowerCase()]||null}var Ra={5126:{kind:"f",n:1},35664:{kind:"f",n:2},35665:{kind:"f",n:3},35666:{kind:"f",n:4},5124:{kind:"i",n:1},35667:{kind:"i",n:2},35668:{kind:"i",n:3},35669:{kind:"i",n:4},35670:{kind:"i",n:1},35671:{kind:"i",n:2},35672:{kind:"i",n:3},35673:{kind:"i",n:4},5125:{kind:"u",n:1},36294:{kind:"u",n:2},36295:{kind:"u",n:3},36296:{kind:"u",n:4},35674:{kind:"m",n:2},35675:{kind:"m",n:3},35676:{kind:"m",n:4}};function Ua(e){return Ra[e]}var Ia=5126,rr=35666;function oo(e){return e!=null&&typeof e=="object"&&!Ti(e)&&"value"in e}var ir=e=>typeof e=="boolean"?e?1:0:e;function Zn(e,t){return typeof e=="number"||typeof e=="boolean"?new Array(t).fill(ir(e)):ArrayBuffer.isView(e)?e:Array.isArray(e)&&e.some(n=>typeof n=="boolean")?e.map(ir):e}function Fa(e,t,n,o,i){let r=n.n;switch(n.kind){case"f":return r===1&&typeof o=="number"?e.uniform1f(t,o):e["uniform"+r+"fv"](t,Zn(o,r));case"i":return r===1&&(typeof o=="number"||typeof o=="boolean")?e.uniform1i(t,+o):e["uniform"+r+"iv"](t,Zn(o,r));case"u":return r===1&&typeof o=="number"?e.uniform1ui(t,o):e["uniform"+r+"uiv"](t,Zn(o,r));case"m":return e["uniformMatrix"+r+"fv"](t,!!i,o)}}function ar(e,t,n,{strict:o=!1,warnMissing:i=!1,label:r=""}={}){if(n)for(let a in n){let c=n[a],l=oo(c)?c:null,s=l?l.value:c;if(s==null)continue;let d=t[a];if(!d||!d.loc){if(o)throw new ye("Unknown uniform: "+a);i&&Nt("missing-uniform:"+r+":"+a,`Uniform "${a}" not found in ${r?`pass "${r}"`:"shader"} (misspelled, undeclared, or optimized out).`);continue}let f;if(l&&l.type!=null){if(f=La(l.type),!f){if(o)throw new ye("Unknown uniform type: "+l.type+" for "+a);Nt("bad-type:"+a,"Unknown uniform type",l.type,a);continue}}else if(f=Ua(d.type),!f)continue;Fa(e,d.loc,f,s,l&&l.transpose)}}function Da(e,t,n={}){let o=n.target==="canvas"?e:n.target&&typeof n.target=="object"?n.target:window,i=+n.smooth||0,r={x:0,y:0,down:!1,over:!1,dragX:0,dragY:0,wheel:0},a={x:0,y:0,clickX:0,clickY:0,down:!1,over:!1,uvX:0,uvY:0,dragX:0,dragY:0,wheel:0,clicked:!1},c=!1,l=0,s=0,d=!1;function f(){let S=e.getBoundingClientRect(),w=t?t():"fill";if(!S.width||!S.height||w!=="contain"&&w!=="cover")return S;let A=e.width/e.height,L=S.width/S.height,T,P;return L>A==(w==="contain")?(P=S.height,T=P*A):(T=S.width,P=T/A),{left:S.left+(S.width-T)/2,top:S.top+(S.height-P)/2,width:T,height:P,bottom:0,right:0}}function u(S,w){let A=f();return!A.width||!A.height?[0,0]:[(S-A.left)*(e.width/A.width),(A.top+A.height-w)*(e.height/A.height)]}let h=(S,w)=>{let[A,L]=u(S,w);return[A/e.width,L/e.height]},x=S=>{let[w,A]=u(S.clientX,S.clientY);r.down&&(r.dragX+=w-l,r.dragY+=A-s),l=w,s=A,r.x=w,r.y=A,r.over=w>=0&&A>=0&&w<=e.width&&A<=e.height,d||(d=!0,a.x=w,a.y=A)},E=S=>{S.button!==void 0&&S.button!==0||(x(S),!(o===window&&!r.over)&&(r.down=!0,a.down=!0,c=!0,l=r.x,s=r.y,a.clickX=r.x,a.clickY=r.y,i||(a.x=r.x,a.y=r.y)))},y=()=>{r.down=!1,a.down=!1},k=()=>{r.over=!1},b=S=>{r.wheel+=-S.deltaY*.002};return n.touch!==!1&&o===e&&(e.style.touchAction="none"),o.addEventListener("pointermove",x,{passive:!0}),o.addEventListener("pointerdown",E,{passive:!0}),window.addEventListener("pointerup",y,{passive:!0}),window.addEventListener("pointercancel",y,{passive:!0}),o.addEventListener("pointerleave",k,{passive:!0}),o.addEventListener("wheel",b,{passive:!0}),{state:a,toShader:u,toUV:h,update(){if(i>0&&i<1){let S=1-Math.pow(1-i,1);a.x+=(r.x-a.x)*S,a.y+=(r.y-a.y)*S}else a.x=r.x,a.y=r.y;a.over=r.over,a.clicked=c,c=!1,a.dragX=r.dragX,a.dragY=r.dragY,a.wheel=r.wheel,a.uvX=e.width?a.x/e.width:0,a.uvY=e.height?a.y/e.height:0},dispose(){o.removeEventListener("pointermove",x),o.removeEventListener("pointerdown",E),window.removeEventListener("pointerup",y),window.removeEventListener("pointercancel",y),o.removeEventListener("pointerleave",k),o.removeEventListener("wheel",b)}}}function Oa(e){if(!e)return 0;if(typeof e=="number")return e;if(Array.isArray(e))return e[0]/e[1];if(typeof e=="string"){let t=e.split(/[:/x]/).map(Number);return t.length===2&&t[1]?t[0]/t[1]:Number(e)||0}return 0}function $a(e={},t=!0){var n,o,i,r,a,c;let l=(n=e.size)!=null?n:e.sizing,s={mode:t?"canvas":"window",width:0,height:0,aspect:Oa(e.aspect),fit:e.fit||"contain",pixelRatio:(i=(o=e.pixelRatio)!=null?o:e.dpr)!=null?i:"auto",maxPixelRatio:(r=e.maxPixelRatio)!=null?r:2,scale:(c=(a=e.scale)!=null?a:e.renderScale)!=null?c:1};return Array.isArray(l)?(s.mode="fixed",s.width=l[0],s.height=l[1]):typeof l=="string"?s.mode=l==="screen"||l==="fullscreen"?"window":l==="element"?"canvas":l:l&&typeof l=="object"&&(s.mode="fixed",s.width=l.width,s.height=l.height,l.fit&&(s.fit=l.fit)),s.mode==="fixed"&&(s.aspect=s.width/s.height),s}function za(e,t={},n=!0){let o=$a(t,n),i=()=>o.pixelRatio==="auto"?Math.min(window.devicePixelRatio||1,o.maxPixelRatio):Number(o.pixelRatio)||1,r=!1;function a(){return o.mode==="window"?{w:window.innerWidth,h:window.innerHeight}:{w:e.clientWidth||window.innerWidth,h:e.clientHeight||window.innerHeight}}function c(){if(o.mode==="fixed")return{w:o.width,h:o.height};let s=a(),d=i()*o.scale,f=s.w,u=s.h;return o.aspect&&(f/u>o.aspect?f=u*o.aspect:u=f/o.aspect),{w:f*d,h:u*d}}function l(){r||(r=!0,o.mode==="window"&&(e.style.cssText+=";display:block;position:fixed;left:0;top:0;width:100%;height:100%;"),(o.mode==="fixed"||o.aspect)&&(e.style.objectFit=o.fit))}return{cfg:o,fit:()=>o.mode==="fixed"||o.aspect?o.fit:"fill",setFixed(s,d){o.mode="fixed",o.width=s,o.height=d,o.aspect=s/d,r=!1},update(){l();let s=c(),d=Math.max(1,Math.round(s.w)),f=Math.max(1,Math.round(s.h));return e.width===d&&e.height===f?!1:(e.width=d,e.height=f,!0)},observe(s){let d=!1,f=()=>{d||(d=!0,requestAnimationFrame(()=>{d=!1,s()}))};window.addEventListener("resize",f);let u=null;return o.mode==="canvas"&&typeof ResizeObserver<"u"&&(u=new ResizeObserver(f),u.observe(e)),()=>{window.removeEventListener("resize",f),u&&u.disconnect()}}}}function Na(e,{enabled:t=!0,margin:n="100px",onChange:o}={}){let i=typeof document>"u"?!0:!document.hidden,r=!0,a=()=>o&&o(i&&r),c=()=>{i=!document.hidden,a()},l=null;return t&&(document.addEventListener("visibilitychange",c),typeof IntersectionObserver<"u"&&(l=new IntersectionObserver(s=>{for(let d of s)r=d.isIntersecting;a()},{rootMargin:n}),l.observe(e))),{get visible(){return i&&r},dispose(){t&&document.removeEventListener("visibilitychange",c),l&&l.disconnect()}}}var Ba={font:'"Geist", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif',mono:'"Geist Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',bg:"#1f1f1f",bgAlt:"#181818",raised:"#2a2d2e",hover:"#37373d",border:"#3c3c3c",text:"#cccccc",textStrong:"#ececec",label:"#9d9d9d",accent:"#4daafc",number:"#4daafc",string:"#d1977f",red:"#e46962",redSoft:"#4e3534",redText:"#f9dedc",radius:"8px",shadow:"0 1px 0 rgba(255,255,255,.03) inset, 0 16px 40px -16px rgba(0,0,0,.7), 0 4px 14px rgba(0,0,0,.3)"};function gr(e){return Object.assign({},Ba,e&&typeof e=="object"?e:null)}function sr({visible:e=!1,key:t="F1",position:n="top-left",theme:o}={}){let i=gr(o),r=document.createElement("div"),[a,c]=n.split("-");r.style.cssText=`position:fixed;${a==="bottom"?"bottom":"top"}:12px;${c==="right"?"right":"left"}:12px;z-index:2147483647;min-width:168px;padding:8px 10px;border:1px solid ${i.border};border-radius:${i.radius};background:${i.bg}e6;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);box-shadow:${i.shadow};color:${i.text};font:12px/1.5 ${i.mono};pointer-events:none;display:none`,document.body.appendChild(r);let l=(k,b)=>`<div style="display:flex;justify-content:space-between;gap:14px"><span style="color:${i.label}">${k}</span><span style="color:${i.textStrong}">${b}</span></div>`,s=!1,d=0,f=0,u=0,h=0;function x(k=!0){s=!!k,r.style.display=s?"block":"none",d=f=u=0}let E=()=>x(!s),y=k=>{k.key===t&&(k.preventDefault(),E())};return t&&window.addEventListener("keydown",y),x(e),{show:x,toggle:E,isVisible:()=>s,update(k){if(!s)return;d+=k.rawDt,f+=k.cpuMs,u++;let b=performance.now();if(b-h<250)return;h=b;let S=d/u*1e3;r.innerHTML=`<div style="display:flex;justify-content:space-between;align-items:baseline;margin-bottom:4px"><b style="color:${i.accent};font-size:16px;font-weight:600">${(1e3/S).toFixed(0)}<span style="font-size:11px;color:${i.label};font-weight:400"> fps</span></b><span style="color:${i.label}">${S.toFixed(1)} ms</span></div>`+l("cpu",(f/u).toFixed(2)+" ms")+l("frame",k.frame)+l("time",k.time.toFixed(2)+" s")+l("size",`${k.width}\xD7${k.height}`)+l("passes",k.passes),d=f=u=0},dispose(){t&&window.removeEventListener("keydown",y),r.remove()}}}function Ga(e,t){let n=gr(t),o=null;function i(){if(!o)return;let a=e.getBoundingClientRect();Object.assign(o.style,{left:a.left+"px",top:a.top+"px",width:a.width+"px",height:a.height+"px"})}let r=a=>String(a).replace(/&/g,"&").replace(/</g,"<");return{show(a){o||(o=document.createElement("div"),o.style.cssText=`position:fixed;z-index:2147483646;box-sizing:border-box;overflow:auto;padding:16px;background:${n.bgAlt}f2;-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);color:${n.text};font:13px/1.55 ${n.font}`,document.body.appendChild(o),window.addEventListener("resize",i));let c=a.errors||[],l=r(a.message.split(`
|
|
76
|
-
`)[0]),s="";c.length?s=c.map(
|
|
70
|
+
`),i.builtins){l+=t?ma:ga,l+=Sa;let y=Ta(u,t),E=/\bout\s+(?:\w+\s+)*vec4\s+\w+\s*;/.test(gr(u));y?l+=y:t&&!E&&(l+=`out vec4 outColor;
|
|
71
|
+
`)}i.uniforms&&(l+=La(u,r,a)),i.defines&&(l+=Ua(n));let p=gr(u),f=i.mainWrap&&/\bmainImage\s*\(/.test(p)&&!/\bvoid\s+main\s*\(/.test(p),h=l+`#line 1
|
|
72
|
+
`+u;return f&&(h+=t?ba:ya),h}function Rn(e,t,n,o,i,r={},a={},{dynamic:c=!1,flipDefault:u=!1}={}){let s=e.createTexture();e.bindTexture(e.TEXTURE_2D,s);let l=r.flipY===void 0?u:!!r.flipY,p=!a.isGL2&&!(dr(o)&&dr(i));p&&r.wrap&&r.wrap!=="clamp"&&Ht("npot-wrap","Non-power-of-two texture in WebGL1: forcing wrap to clamp.");let f=p?e.CLAMP_TO_EDGE:lo(e,r.wrap),h=!!r.mipmap&&!c&&!p,y=uo(e,r.filter),E=h?r.filter==="nearest"?e.NEAREST_MIPMAP_NEAREST:e.LINEAR_MIPMAP_LINEAR:y;e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,E),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,y),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,f),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,f);let v=()=>{e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,l),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!!r.premultiplyAlpha),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1)};return v(),h&&e.generateMipmap(e.TEXTURE_2D),e.bindTexture(e.TEXTURE_2D,null),{texId:t.add(s,"texture2D"),width:o,height:i,source:n,update:c?()=>{n.readyState!==void 0&&n.readyState<2||(e.bindTexture(e.TEXTURE_2D,s),v(),e.bindTexture(e.TEXTURE_2D,null))}:()=>{}}}function Da(e,t,n,o={},i={}){return new Promise((r,a)=>{let c=new Image;c.crossOrigin=o.crossOrigin===void 0?"anonymous":o.crossOrigin,c.onload=()=>r(Rn(e,t,c,c.naturalWidth,c.naturalHeight,o,i)),c.onerror=()=>a(new Error(`Failed to load image "${n}"`)),c.src=n})}var Fa=["+X","-X","+Y","-Y","+Z","-Z"];function $a(e,t,n,o={}){return new Promise((i,r)=>{if(!Array.isArray(n)||n.length!==6)return r(new Error("cubemap needs an array of 6 URLs"));let a=e.createTexture();e.bindTexture(e.TEXTURE_CUBE_MAP,a);let c=lo(e,o.wrap),u=uo(e,o.filter);e.texParameteri(e.TEXTURE_CUBE_MAP,e.TEXTURE_MIN_FILTER,u),e.texParameteri(e.TEXTURE_CUBE_MAP,e.TEXTURE_MAG_FILTER,u),e.texParameteri(e.TEXTURE_CUBE_MAP,e.TEXTURE_WRAP_S,c),e.texParameteri(e.TEXTURE_CUBE_MAP,e.TEXTURE_WRAP_T,c);let s=[e.TEXTURE_CUBE_MAP_POSITIVE_X,e.TEXTURE_CUBE_MAP_NEGATIVE_X,e.TEXTURE_CUBE_MAP_POSITIVE_Y,e.TEXTURE_CUBE_MAP_NEGATIVE_Y,e.TEXTURE_CUBE_MAP_POSITIVE_Z,e.TEXTURE_CUBE_MAP_NEGATIVE_Z],l=0,p=0,f=0,h=!1;n.forEach((y,E)=>{let v=new Image;v.crossOrigin="anonymous",v.onload=()=>{h||(p||(p=v.width,f=v.height),e.bindTexture(e.TEXTURE_CUBE_MAP,a),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),e.texImage2D(s[E],0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,v),++l===6&&(o.mipmap&&e.generateMipmap(e.TEXTURE_CUBE_MAP),e.bindTexture(e.TEXTURE_CUBE_MAP,null),i({texId:t.add(a,"textureCube"),width:p,height:f,cubemap:!0,update(){}})))},v.onerror=()=>{h||(h=!0,e.deleteTexture(a),r(new Error(`Failed to load cubemap face ${Fa[E]}: "${y}"`)))},v.src=y})})}function za(e){let t=e.play&&e.play();t&&t.catch&&t.catch(()=>{let n=()=>{e.play().catch(()=>{})};window.addEventListener("pointerdown",n,{once:!0}),window.addEventListener("keydown",n,{once:!0})})}function Ba(e,t,n,o={},i={}){return new Promise((r,a)=>{let c=document.createElement("video");Object.assign(c,{src:n,crossOrigin:"anonymous",loop:o.loop!==!1,muted:o.muted!==!1,playsInline:!0,autoplay:!0}),c.addEventListener("error",()=>a(new Error(`Failed to load video "${n}"`)),{once:!0}),c.addEventListener("canplay",()=>{za(c);let u=Rn(e,t,c,c.videoWidth,c.videoHeight,{...o,flipY:o.flipY===void 0?!0:o.flipY},i,{dynamic:!0});u.getTime=()=>c.currentTime,u.media=c,u.dispose=()=>{c.pause(),c.removeAttribute("src"),c.load()},r(u)},{once:!0}),c.load()})}function Na(e,t,n={},o={}){let i=typeof n.camera=="object"?n.camera:{facingMode:"user"};return navigator.mediaDevices.getUserMedia({video:i,audio:!1}).then(r=>new Promise(a=>{let c=document.createElement("video");Object.assign(c,{srcObject:r,muted:!0,playsInline:!0,autoplay:!0}),c.addEventListener("loadedmetadata",()=>{c.play().catch(()=>{});let u=Rn(e,t,c,c.videoWidth,c.videoHeight,{...n,flipY:n.flipY===void 0?!0:n.flipY},o,{dynamic:!0});u.media=c,u.dispose=()=>{c.pause(),r.getTracks().forEach(s=>s.stop())},a(u)},{once:!0})}))}function br(e,t,n,{mic:o=!1}={}){let i=n.layout==="spectrogram",r=n.fftSize||(i?1024:512),a=window.AudioContext||window.webkitAudioContext;return new Promise((c,u)=>{var s;let l=new a,p=l.createAnalyser();p.fftSize=r,p.smoothingTimeConstant=(s=n.smoothing)!=null?s:.8;let f=p.frequencyBinCount,h=new Uint8Array(r),y=i?f:2,E=i?3:1,v=new Uint8Array(f*y*E),M=i?new Uint8Array(f):null,x=null;i&&(x=l.createAnalyser(),x.fftSize=r,x.smoothingTimeConstant=0);let S=e.createTexture(),b=i?e.RGB:e.LUMINANCE,_=()=>{e.bindTexture(e.TEXTURE_2D,S),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),e.pixelStorei(e.UNPACK_ALIGNMENT,1),e.texImage2D(e.TEXTURE_2D,0,b,f,y,0,b,e.UNSIGNED_BYTE,v),e.bindTexture(e.TEXTURE_2D,null)};e.bindTexture(e.TEXTURE_2D,S),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,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),_();let L=()=>l.currentTime,P=()=>{},R=()=>{let I=()=>{l.state==="suspended"&&l.resume()};I(),window.addEventListener("pointerdown",I,{once:!0}),window.addEventListener("keydown",I,{once:!0}),c({texId:t.add(S,"texture2D"),width:f,height:y,analyser:p,context:l,getTime:L,update(){if(i){let N=f*3;v.copyWithin(N,0,v.length-N),p.getByteFrequencyData(M),p.getByteTimeDomainData(h);for(let z=0;z<f;z++)v[z*3]=M[z],v[z*3+1]=h[z*2];x.getByteFrequencyData(M);for(let z=0;z<f;z++)v[z*3+2]=M[z]}else p.getByteFrequencyData(v.subarray(0,f)),p.getByteTimeDomainData(h),v.set(h.subarray(0,f),f);_()},dispose(){P(),l.close&&l.close()}})};if(o){navigator.mediaDevices.getUserMedia({audio:!0,video:!1}).then(I=>{let N=l.createMediaStreamSource(I);N.connect(p),x&&N.connect(x),P=()=>I.getTracks().forEach(z=>z.stop()),R()}).catch(u);return}let j=n.audio||n.audioFFT,C=j instanceof HTMLMediaElement?j:new Audio,D=C!==j;D&&Object.assign(C,{src:j,crossOrigin:"anonymous",loop:n.loop!==!1,autoplay:!0}),L=()=>C.currentTime;let F=()=>{let I=l.createMediaElementSource(C);if(I.connect(p),x&&I.connect(x),p.connect(l.destination),D){let N=()=>{l.state==="suspended"&&l.resume(),C.play().catch(()=>{})};N(),window.addEventListener("pointerdown",N,{once:!0}),window.addEventListener("keydown",N,{once:!0}),P=()=>{C.pause(),C.removeAttribute("src"),C.load()}}R()};C.readyState>=3?F():(C.addEventListener("canplay",F,{once:!0}),C.addEventListener("error",()=>u(new Error(`Failed to load audio "${j}"`)),{once:!0}),D&&C.load())})}var Ga=e=>typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement,yr=e=>typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement;function ja(e,t,n,o={},i={}){let r=n.videoWidth||n.naturalWidth||n.width||1,a=n.videoHeight||n.naturalHeight||n.height||1,c=Ga(n)||yr(n),u=o.dynamic===void 0?c:!!o.dynamic,s=Rn(e,t,n,r,a,o,i,{dynamic:u,flipDefault:c});if(yr(n)&&(s.getTime=()=>n.currentTime),u){let l=s.update;s.update=()=>{s.width=n.videoWidth||n.naturalWidth||n.width||1,s.height=n.videoHeight||n.naturalHeight||n.height||1,l()}}return Promise.resolve(s)}function Ha(e,t,n){let o=t.add(n.texture,n.cube?"textureCube":"texture2D");return t.ref(o),Promise.resolve({texId:o,width:n.width||1,height:n.height||1,cubemap:!!n.cube,update(){}})}function Va(e,t,n={}){let r=new Uint8Array(768),a=new Uint8Array(256),c=new Uint8Array(256),u=new Uint8Array(256),s=n.keyboard&&typeof n.keyboard=="object"&&n.keyboard.target||window,l=v=>{if(typeof v.keyCode=="number"&&v.keyCode)return v.keyCode&255;let M=v.key||"";return M.length===1?M.toUpperCase().charCodeAt(0)&255:0},p=v=>{let M=l(v);a[M]||(c[M]=255,u[M]=u[M]?0:255),a[M]=255},f=v=>{a[l(v)]=0},h=()=>a.fill(0);s.addEventListener("keydown",p),s.addEventListener("keyup",f),window.addEventListener("blur",h);let y=e.createTexture();e.bindTexture(e.TEXTURE_2D,y),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),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);let E=()=>{e.bindTexture(e.TEXTURE_2D,y),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),e.pixelStorei(e.UNPACK_ALIGNMENT,1),e.texImage2D(e.TEXTURE_2D,0,e.LUMINANCE,256,3,0,e.LUMINANCE,e.UNSIGNED_BYTE,r),e.bindTexture(e.TEXTURE_2D,null)};return E(),Promise.resolve({texId:t.add(y,"texture2D"),width:256,height:3,keyboard:!0,update(){r.set(a,0),r.set(c,256),r.set(u,256*2),E(),c.fill(0)},dispose(){s.removeEventListener("keydown",p),s.removeEventListener("keyup",f),window.removeEventListener("blur",h)}})}function io(e,t,n,o){return n.texture?Ha(e,t,n):n.element?ja(e,t,n.element,n,o):n.url?Da(e,t,n.url,n,o):n.video?Ba(e,t,n.video,n,o):n.camera?Na(e,t,n,o):n.mic?br(e,t,n,{mic:!0}):n.keyboard?Va(e,t,n):n.audio||n.audioFFT?br(e,t,n):n.cubemap?$a(e,t,n.cubemap,n):Promise.reject(new Error("Unrecognised channel: "+JSON.stringify(n)))}function Xa(e){return e?e.cubemap||e.texture&&e.cube?"cube":"2D":null}var Pr=e=>e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"");function Wa(e){let t=/^[ \t]*\/\/[ \t]*(?:=+[ \t]*)?(?:Pass[ \t]*:?[ \t]*([^\n=—–-]+?)|(Main)|(Common))[ \t]*(?:[—–-]+[^\n]*)?(?:=+)?[ \t]*$/gim,n=[],o;for(;o=t.exec(e);)n.push({index:o.index,end:o.index+o[0].length,raw:o[0],pass:o[1],main:!!o[2],common:!!o[3]});if(!n.length)return null;let i={common:e.slice(0,n[0].index).trim(),passes:[]};return n.forEach((r,a)=>{let c=e.slice(r.end,a+1<n.length?n[a+1].index:e.length).trim();if(r.common){i.common=(i.common?i.common+`
|
|
73
|
+
`:"")+c;return}let u=r.main?"main":String(r.pass).trim(),s=/buffer\s*type\s*:\s*(\w+)/i.exec(r.raw),l=/^(\d+)$/.exec(u);i.passes.push({name:r.main?"main":l?"pass"+l[1]:u.replace(/[^\w]+/g,"_").replace(/^_+|_+$/g,"").toLowerCase(),label:u,main:r.main,src:c,bufferType:s?s[1].toLowerCase():"2d"})}),i.common&&/[{};]/.test(Pr(i.common)),i}function qa(e){let t={},n=/\[([^\]]*)\]/.exec(e||"");if(!n)return t;for(let o of n[1].toLowerCase().split(/[\s,]+/))o==="nearest"||o==="linear"?t.filter=o:o==="clamp"||o==="repeat"||o==="mirror"?t.wrap=o:o==="mipmap"?t.mipmap=!0:(o==="flipy"||o==="flip")&&(t.flipY=!0);return t}function xr(e){let t={},n={},o=e.split(`
|
|
74
|
+
`),i=/^\s*uniform\s+(?:(?:lowp|mediump|highp)\s+)?(\w+)\s+(\w+)(?:\s*\[\s*\d+\s*\])?\s*(?:=\s*([^;]+))?;\s*(?:\/\/(.*))?$/;return{source:o.map(a=>{var c,u,s;let l=i.exec(a);if(!l)return a;let[,p,f,h,y=""]=l,E=y.trim();if(/^sampler/.test(p)){let M=Ya(f,E,p);M&&(n[f]=M)}else{let M={},x=R=>(R.match(/-?\d*\.?\d+(?:e-?\d+)?/g)||[]).map(Number),S=/\[([^\]]*)\]/.exec(E),b=x(E.replace(/\[[^\]]*\]/,"")),_=/vec(\d)/.test(p)?+p.match(/vec(\d)/)[1]:1,L=/^bool/.test(p),P;if(h){let R=x(h);P=_===1?L?/true/.test(h):(c=R[0])!=null?c:0:R.slice(0,_)}else b.length&&(P=_===1?b[0]:b.length>=_?b.slice(0,_):new Array(_).fill(b[0]));if(S){let R=x(S[1]);R.length>=2&&(M.min=R[0],M.max=R[1],R.length>=3&&(M.step=R[2]))}(P!==void 0||S)&&(M.value=P!==void 0?P:_===1?(u=M.min)!=null?u:0:new Array(_).fill((s=M.min)!=null?s:0),t[f]=M)}return h?a.replace(/\s*=\s*[^;]+;/,";"):a}).join(`
|
|
75
|
+
`),uniforms:t,samplers:n}}function Ya(e,t,n){let o=qa(t),i=t.replace(/\[[^\]]*\]/g,"").trim(),r=/^ref:\s*(.+)$/i.exec(i);if(r){let a=r[1].trim(),c;return(c=/^pass\s*(\d+)(?::out(\d+))?$/i.exec(a))?{pass:"pass"+c[1],...o}:(c=/^pass:\s*(\S+)/i.exec(a))?{pass:c[1],...o}:/^main$/i.test(a)?{pass:"main",...o}:(c=/^sampler\s+(\w+)/i.exec(a))?{sameAs:c[1],...o}:null}if(e==="u_audio"||/audio/i.test(e)&&/^(mic|\[CAM\]|\[VIDEO\])?$/i.test(i))return/^https?:|^data:/i.test(i)?{audio:i,layout:"spectrogram"}:{mic:!0,layout:"spectrogram"};if(e==="u_webcam")return{camera:!0,...o};if(e==="u_keyboard")return{keyboard:!0};if(/^(https?:|data:)/i.test(i)){let a=i.split(/\s+/)[0];return/\.(mp4|webm|mov|ogv|m4v)(\?|$)/i.test(a)?{video:a,...o}:/\.(mp3|wav|ogg|m4a|aac|flac)(\?|$)/i.test(a)?{audio:a,layout:"spectrogram"}:n==="samplerCube"?null:{url:a,...o}}return null}function Ka(e){return/\bu_mouse\s*\.\s*[xyzw]*[zw]/.test(Pr(e))}var Za=35678,Ja=35680,Qa=e=>e.filter(t=>!t.cfg.screen);function es(e,t,n={}){let o=[],i=Qa(t),r=t.find(u=>u.cfg.screen),a=new Map(t.map(u=>[u.name,u])),c=Object.assign({},e.cfg.annotatedSamplers,e.cfg.samplers);for(let u in e.uniformInfo){let s=e.uniformInfo[u];if(s.type!==Za&&s.type!==Ja||/^iChannel\d$/.test(u))continue;let l=n[u]||c[u]||null,p;if(l&&l.sameAs&&(l=c[l.sameAs]||n[l.sameAs]||null),l||(u==="u_passes"&&s.size>1?l={array:i.slice(0,s.size)}:u==="u_main"?l=r?{pass:r.name}:null:(p=/^u_pass(\d+)$/.exec(u))&&i[+p[1]-1]?l={pass:i[+p[1]-1].name}:u.startsWith("u_")&&a.has(u.slice(2))?l={pass:u.slice(2)}:u==="u_audio"?l={mic:!0,layout:"spectrogram"}:u==="u_keyboard"?l={keyboard:!0}:u==="u_webcam"&&(l={camera:!0})),l&&l.pass!=null&&!a.has(l.pass)){let f=/^pass(\d+)$/.exec(l.pass);f&&i[+f[1]-1]?l={...l,pass:i[+f[1]-1].name}:l.pass==="main"&&r&&(l={...l,pass:r.name})}l&&o.push({name:u,info:s,spec:l})}return o}function ts(e){let t=e.find(n=>n.cfg.screen);return t?e.some(n=>(n.samplers||[]).some(o=>o.spec.pass===t.name)||n.cfg.channels.some(o=>o&&o.pass===t.name)):!1}function ns(e,{target:t=window,speed:n=1.5,sensitivity:o=.004}={}){let i=[0,0,0],r=-Math.PI/2,a=0,c=new Set,u=!1,s=0,l=0,p=[0,0,-1],f=new Float32Array(16),h=(L,P)=>{let R=L.key.length===1?L.key.toLowerCase():L.key;P?c.add(R):c.delete(R)},y=L=>h(L,!0),E=L=>h(L,!1),v=L=>{L.button===0&&(u=!0,s=L.clientX,l=L.clientY)},M=L=>{u&&(r+=(L.clientX-s)*o,a-=(L.clientY-l)*o,a=Math.max(-1.55,Math.min(1.55,a)),s=L.clientX,l=L.clientY)},x=()=>{u=!1},S=L=>{let P=p,R=-L.deltaY*.002*n;i[0]+=P[0]*R,i[1]+=P[1]*R,i[2]+=P[2]*R},b=()=>c.clear();t.addEventListener("keydown",y),t.addEventListener("keyup",E),e.addEventListener("pointerdown",v),window.addEventListener("pointermove",M),window.addEventListener("pointerup",x),e.addEventListener("wheel",S,{passive:!0}),window.addEventListener("blur",b);function _(){let L=p,P=[0,1,0],R=[L[1]*P[2]-L[2]*P[1],L[2]*P[0]-L[0]*P[2],L[0]*P[1]-L[1]*P[0]],j=Math.hypot(R[0],R[1],R[2])||1;R=R.map(D=>D/j);let C=[R[1]*L[2]-R[2]*L[1],R[2]*L[0]-R[0]*L[2],R[0]*L[1]-R[1]*L[0]];return f.set([R[0],C[0],-L[0],0,R[1],C[1],-L[1],0,R[2],C[2],-L[2],0,-(R[0]*i[0]+R[1]*i[1]+R[2]*i[2]),-(C[0]*i[0]+C[1]*i[1]+C[2]*i[2]),L[0]*i[0]+L[1]*i[1]+L[2]*i[2],1]),{right:R,up:C}}return{pos:i,dir:p,view:f,update(L){p[0]=Math.cos(a)*Math.cos(r),p[1]=Math.sin(a),p[2]=Math.cos(a)*Math.sin(r);let{right:P}=_(),R=n*L*(c.has("Shift")?3:1),j=(C,D)=>{i[0]+=C[0]*D,i[1]+=C[1]*D,i[2]+=C[2]*D};(c.has("w")||c.has("ArrowUp"))&&j(p,R),(c.has("s")||c.has("ArrowDown"))&&j(p,-R),(c.has("d")||c.has("ArrowRight"))&&j(P,R),(c.has("a")||c.has("ArrowLeft"))&&j(P,-R),(c.has("e")||c.has(" "))&&(i[1]+=R),(c.has("q")||c.has("c"))&&(i[1]-=R),_()},dispose(){t.removeEventListener("keydown",y),t.removeEventListener("keyup",E),e.removeEventListener("pointerdown",v),window.removeEventListener("pointermove",M),window.removeEventListener("pointerup",x),e.removeEventListener("wheel",S),window.removeEventListener("blur",b)}}}var Lr=Object.create(null),Ie=(e,...t)=>t.forEach(n=>{Lr[n.toLowerCase()]=e});Ie({kind:"f",n:1},"float","number","f","1f","1fv","float[]","uniform1f","uniform1fv");Ie({kind:"f",n:2},"vec2","2f","2fv","vec2[]","uniform2f","uniform2fv");Ie({kind:"f",n:3},"vec3","3f","3fv","vec3[]","uniform3f","uniform3fv");Ie({kind:"f",n:4},"vec4","4f","4fv","vec4[]","uniform4f","uniform4fv");Ie({kind:"i",n:1},"int","bool","boolean","i","1i","1iv","int[]","bool[]","uniform1i","uniform1iv");Ie({kind:"i",n:2},"ivec2","bvec2","2i","2iv","ivec2[]","bvec2[]","uniform2i","uniform2iv");Ie({kind:"i",n:3},"ivec3","bvec3","3i","3iv","ivec3[]","bvec3[]","uniform3i","uniform3iv");Ie({kind:"i",n:4},"ivec4","bvec4","4i","4iv","ivec4[]","bvec4[]","uniform4i","uniform4iv");Ie({kind:"u",n:1},"uint","1ui","1uiv","uint[]");Ie({kind:"u",n:2},"uvec2","2ui","2uiv","uvec2[]");Ie({kind:"u",n:3},"uvec3","3ui","3uiv","uvec3[]");Ie({kind:"u",n:4},"uvec4","4ui","4uiv","uvec4[]");Ie({kind:"m",n:2},"mat2","matrix2fv","mat2fv","uniformmatrix2fv");Ie({kind:"m",n:3},"mat3","matrix3fv","mat3fv","uniformmatrix3fv");Ie({kind:"m",n:4},"mat4","matrix4fv","mat4fv","uniformmatrix4fv");function os(e){return typeof e!="string"?null:Lr[e.trim().toLowerCase()]||null}var rs={5126:{kind:"f",n:1},35664:{kind:"f",n:2},35665:{kind:"f",n:3},35666:{kind:"f",n:4},5124:{kind:"i",n:1},35667:{kind:"i",n:2},35668:{kind:"i",n:3},35669:{kind:"i",n:4},35670:{kind:"i",n:1},35671:{kind:"i",n:2},35672:{kind:"i",n:3},35673:{kind:"i",n:4},5125:{kind:"u",n:1},36294:{kind:"u",n:2},36295:{kind:"u",n:3},36296:{kind:"u",n:4},35674:{kind:"m",n:2},35675:{kind:"m",n:3},35676:{kind:"m",n:4}};function is(e){return rs[e]}var as=5126,wr=35666;function po(e){return e!=null&&typeof e=="object"&&!Qi(e)&&"value"in e}var vr=e=>typeof e=="boolean"?e?1:0:e;function ao(e,t){return typeof e=="number"||typeof e=="boolean"?new Array(t).fill(vr(e)):ArrayBuffer.isView(e)?e:Array.isArray(e)&&e.some(n=>typeof n=="boolean")?e.map(vr):e}function ss(e,t,n,o,i){let r=n.n;switch(n.kind){case"f":return r===1&&typeof o=="number"?e.uniform1f(t,o):e["uniform"+r+"fv"](t,ao(o,r));case"i":return r===1&&(typeof o=="number"||typeof o=="boolean")?e.uniform1i(t,+o):e["uniform"+r+"iv"](t,ao(o,r));case"u":return r===1&&typeof o=="number"?e.uniform1ui(t,o):e["uniform"+r+"uiv"](t,ao(o,r));case"m":return e["uniformMatrix"+r+"fv"](t,!!i,o)}}function Er(e,t,n,{strict:o=!1,warnMissing:i=!1,label:r=""}={}){if(n)for(let a in n){let c=n[a],u=po(c)?c:null,s=u?u.value:c;if(s==null)continue;let l=t[a];if(!l||!l.loc){if(o)throw new Se("Unknown uniform: "+a);i&&Ht("missing-uniform:"+r+":"+a,`Uniform "${a}" not found in ${r?`pass "${r}"`:"shader"} (misspelled, undeclared, or optimized out).`);continue}let p;if(u&&u.type!=null){if(p=os(u.type),!p){if(o)throw new Se("Unknown uniform type: "+u.type+" for "+a);Ht("bad-type:"+a,"Unknown uniform type",u.type,a);continue}}else if(p=is(l.type),!p)continue;ss(e,l.loc,p,s,u&&u.transpose)}}function cs(e,t,n={}){let o=n.target==="canvas"?e:n.target&&typeof n.target=="object"?n.target:window,i=+n.smooth||0,r={x:0,y:0,down:!1,over:!1,dragX:0,dragY:0,wheel:0},a={x:0,y:0,clickX:0,clickY:0,down:!1,over:!1,uvX:0,uvY:0,dragX:0,dragY:0,wheel:0,clicked:!1},c=!1,u=0,s=0,l=!1;function p(){let S=e.getBoundingClientRect(),b=t?t():"fill";if(!S.width||!S.height||b!=="contain"&&b!=="cover")return S;let _=e.width/e.height,L=S.width/S.height,P,R;return L>_==(b==="contain")?(R=S.height,P=R*_):(P=S.width,R=P/_),{left:S.left+(S.width-P)/2,top:S.top+(S.height-R)/2,width:P,height:R,bottom:0,right:0}}function f(S,b){let _=p();return!_.width||!_.height?[0,0]:[(S-_.left)*(e.width/_.width),(_.top+_.height-b)*(e.height/_.height)]}let h=(S,b)=>{let[_,L]=f(S,b);return[_/e.width,L/e.height]},y=S=>{let[b,_]=f(S.clientX,S.clientY);r.down&&(r.dragX+=b-u,r.dragY+=_-s),u=b,s=_,r.x=b,r.y=_,r.over=b>=0&&_>=0&&b<=e.width&&_<=e.height,l||(l=!0,a.x=b,a.y=_)},E=S=>{S.button!==void 0&&S.button!==0||(y(S),!(o===window&&!r.over)&&(r.down=!0,a.down=!0,c=!0,u=r.x,s=r.y,a.clickX=r.x,a.clickY=r.y,i||(a.x=r.x,a.y=r.y)))},v=()=>{r.down=!1,a.down=!1},M=()=>{r.over=!1},x=S=>{r.wheel+=-S.deltaY*.002};return n.touch!==!1&&o===e&&(e.style.touchAction="none"),o.addEventListener("pointermove",y,{passive:!0}),o.addEventListener("pointerdown",E,{passive:!0}),window.addEventListener("pointerup",v,{passive:!0}),window.addEventListener("pointercancel",v,{passive:!0}),o.addEventListener("pointerleave",M,{passive:!0}),o.addEventListener("wheel",x,{passive:!0}),{state:a,toShader:f,toUV:h,update(){if(i>0&&i<1){let S=1-Math.pow(1-i,1);a.x+=(r.x-a.x)*S,a.y+=(r.y-a.y)*S}else a.x=r.x,a.y=r.y;a.over=r.over,a.clicked=c,c=!1,a.dragX=r.dragX,a.dragY=r.dragY,a.wheel=r.wheel,a.uvX=e.width?a.x/e.width:0,a.uvY=e.height?a.y/e.height:0},dispose(){o.removeEventListener("pointermove",y),o.removeEventListener("pointerdown",E),window.removeEventListener("pointerup",v),window.removeEventListener("pointercancel",v),o.removeEventListener("pointerleave",M),o.removeEventListener("wheel",x)}}}function ls(e){if(!e)return 0;if(typeof e=="number")return e;if(Array.isArray(e))return e[0]/e[1];if(typeof e=="string"){let t=e.split(/[:/x]/).map(Number);return t.length===2&&t[1]?t[0]/t[1]:Number(e)||0}return 0}function us(e={},t=!0){var n,o,i,r,a,c;let u=(n=e.size)!=null?n:e.sizing,s={mode:t?"canvas":"window",width:0,height:0,aspect:ls(e.aspect),fit:e.fit||"contain",pixelRatio:(i=(o=e.pixelRatio)!=null?o:e.dpr)!=null?i:"auto",maxPixelRatio:(r=e.maxPixelRatio)!=null?r:2,scale:(c=(a=e.scale)!=null?a:e.renderScale)!=null?c:1};return Array.isArray(u)?(s.mode="fixed",s.width=u[0],s.height=u[1]):typeof u=="string"?s.mode=u==="screen"||u==="fullscreen"?"window":u==="element"?"canvas":u:u&&typeof u=="object"&&(s.mode="fixed",s.width=u.width,s.height=u.height,u.fit&&(s.fit=u.fit)),s.mode==="fixed"&&(s.aspect=s.width/s.height),s}function ds(e,t={},n=!0){let o=us(t,n),i=()=>o.pixelRatio==="auto"?Math.min(window.devicePixelRatio||1,o.maxPixelRatio):Number(o.pixelRatio)||1,r=!1;function a(){return o.mode==="window"?{w:window.innerWidth,h:window.innerHeight}:{w:e.clientWidth||window.innerWidth,h:e.clientHeight||window.innerHeight}}function c(){if(o.mode==="fixed")return{w:o.width,h:o.height};let s=a(),l=i()*o.scale,p=s.w,f=s.h;return o.aspect&&(p/f>o.aspect?p=f*o.aspect:f=p/o.aspect),{w:p*l,h:f*l}}function u(){r||(r=!0,o.mode==="window"&&(e.style.cssText+=";display:block;position:fixed;left:0;top:0;width:100%;height:100%;"),(o.mode==="fixed"||o.aspect)&&(e.style.objectFit=o.fit))}return{cfg:o,fit:()=>o.mode==="fixed"||o.aspect?o.fit:"fill",setFixed(s,l){o.mode="fixed",o.width=s,o.height=l,o.aspect=s/l,r=!1},update(){u();let s=c(),l=Math.max(1,Math.round(s.w)),p=Math.max(1,Math.round(s.h));return e.width===l&&e.height===p?!1:(e.width=l,e.height=p,!0)},observe(s){let l=!1,p=()=>{l||(l=!0,requestAnimationFrame(()=>{l=!1,s()}))};window.addEventListener("resize",p);let f=null;return o.mode==="canvas"&&typeof ResizeObserver<"u"&&(f=new ResizeObserver(p),f.observe(e)),()=>{window.removeEventListener("resize",p),f&&f.disconnect()}}}}function fs(e,{enabled:t=!0,margin:n="100px",onChange:o}={}){let i=typeof document>"u"?!0:!document.hidden,r=!0,a=()=>o&&o(i&&r),c=()=>{i=!document.hidden,a()},u=null;return t&&(document.addEventListener("visibilitychange",c),typeof IntersectionObserver<"u"&&(u=new IntersectionObserver(s=>{for(let l of s)r=l.isIntersecting;a()},{rootMargin:n}),u.observe(e))),{get visible(){return i&&r},dispose(){t&&document.removeEventListener("visibilitychange",c),u&&u.disconnect()}}}var ps={font:'"Geist", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif',mono:'"Geist Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',bg:"#1f1f1f",bgAlt:"#181818",raised:"#2a2d2e",hover:"#37373d",border:"#3c3c3c",text:"#cccccc",textStrong:"#ececec",label:"#9d9d9d",accent:"#4daafc",number:"#4daafc",string:"#d1977f",red:"#e46962",redSoft:"#4e3534",redText:"#f9dedc",radius:"8px",shadow:"0 1px 0 rgba(255,255,255,.03) inset, 0 16px 40px -16px rgba(0,0,0,.7), 0 4px 14px rgba(0,0,0,.3)"};function Rr(e){return Object.assign({},ps,e&&typeof e=="object"?e:null)}function kr({visible:e=!1,key:t="F1",position:n="top-left",theme:o}={}){let i=Rr(o),r=document.createElement("div"),[a,c]=n.split("-");r.style.cssText=`position:fixed;${a==="bottom"?"bottom":"top"}:12px;${c==="right"?"right":"left"}:12px;z-index:2147483647;min-width:168px;padding:8px 10px;border:1px solid ${i.border};border-radius:${i.radius};background:${i.bg}e6;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);box-shadow:${i.shadow};color:${i.text};font:12px/1.5 ${i.mono};pointer-events:none;display:none`,document.body.appendChild(r);let u=(M,x)=>`<div style="display:flex;justify-content:space-between;gap:14px"><span style="color:${i.label}">${M}</span><span style="color:${i.textStrong}">${x}</span></div>`,s=!1,l=0,p=0,f=0,h=0;function y(M=!0){s=!!M,r.style.display=s?"block":"none",l=p=f=0}let E=()=>y(!s),v=M=>{M.key===t&&(M.preventDefault(),E())};return t&&window.addEventListener("keydown",v),y(e),{show:y,toggle:E,isVisible:()=>s,update(M){if(!s)return;l+=M.rawDt,p+=M.cpuMs,f++;let x=performance.now();if(x-h<250)return;h=x;let S=l/f*1e3;r.innerHTML=`<div style="display:flex;justify-content:space-between;align-items:baseline;margin-bottom:4px"><b style="color:${i.accent};font-size:16px;font-weight:600">${(1e3/S).toFixed(0)}<span style="font-size:11px;color:${i.label};font-weight:400"> fps</span></b><span style="color:${i.label}">${S.toFixed(1)} ms</span></div>`+u("cpu",(p/f).toFixed(2)+" ms")+u("frame",M.frame)+u("time",M.time.toFixed(2)+" s")+u("size",`${M.width}\xD7${M.height}`)+u("passes",M.passes),l=p=f=0},dispose(){t&&window.removeEventListener("keydown",v),r.remove()}}}function hs(e,t){let n=Rr(t),o=null;function i(){if(!o)return;let a=e.getBoundingClientRect();Object.assign(o.style,{left:a.left+"px",top:a.top+"px",width:a.width+"px",height:a.height+"px"})}let r=a=>String(a).replace(/&/g,"&").replace(/</g,"<");return{show(a){o||(o=document.createElement("div"),o.style.cssText=`position:fixed;z-index:2147483646;box-sizing:border-box;overflow:auto;padding:16px;background:${n.bgAlt}f2;-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);color:${n.text};font:13px/1.55 ${n.font}`,document.body.appendChild(o),window.addEventListener("resize",i));let c=a.errors||[],u=r(a.message.split(`
|
|
76
|
+
`)[0]),s="";c.length?s=c.map(l=>`<div style="display:grid;grid-template-columns:auto 1fr;gap:4px 12px;padding:10px 12px;border:1px solid ${n.border};border-radius:${n.radius};background:${n.bg};margin-bottom:8px"><span style="color:${n.red};font-family:${n.mono};font-size:12px">line ${l.line}</span><span style="color:${n.textStrong}">${r(l.message)}</span><span></span><code style="color:${n.label};font-family:${n.mono};font-size:12px;white-space:pre-wrap">${r(l.source.trim())}</code></div>`).join(""):a.log&&(s=`<pre style="margin:0;padding:10px 12px;border:1px solid ${n.border};border-radius:${n.radius};background:${n.bg};color:${n.label};font:12px/1.5 ${n.mono};white-space:pre-wrap">${r(a.log)}</pre>`),o.innerHTML=`<div style="display:flex;align-items:center;gap:10px;margin-bottom:12px"><span style="display:inline-flex;align-items:center;height:22px;padding:0 9px;border-radius:11px;background:${n.redSoft};color:${n.redText};font-size:11.5px;font-weight:500">Shader error</span><b style="color:${n.textStrong};font-weight:600">${u}</b></div>`+s,o.style.display="block",i()},hide(){o&&(o.style.display="none")},dispose(){o&&(o.remove(),window.removeEventListener("resize",i),o=null)}}}function ms(e,t){function n(a="image/png",c){return t(),e.toDataURL(a,c)}function o(a="image/png",c){return t(),new Promise((u,s)=>e.toBlob(l=>l?u(l):s(new Error("toBlob failed")),a,c))}async function i(a="shadermate.png",c,u){c||(c=/\.jpe?g$/i.test(a)?"image/jpeg":/\.webp$/i.test(a)?"image/webp":"image/png");let s=await o(c,u);Mr(s,a)}function r({fps:a=60,mimeType:c,bitsPerSecond:u=8e6,duration:s=0,download:l}={}){if(typeof MediaRecorder>"u"||!e.captureStream)throw new Error("MediaRecorder not supported");let p=e.captureStream(a),f=c||["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"].find(M=>MediaRecorder.isTypeSupported(M))||"",h=new MediaRecorder(p,{mimeType:f||void 0,videoBitsPerSecond:u}),y=[];h.ondataavailable=M=>{M.data.size&&y.push(M.data)};let E=new Promise(M=>{h.onstop=()=>M(new Blob(y,{type:h.mimeType}))});h.start(100);let v={recorder:h,stop(){return h.state!=="inactive"&&h.stop(),p.getTracks().forEach(M=>M.stop()),E},done:E};if(s>0){let M=new Promise(x=>setTimeout(()=>x(v.stop()),s));return l?M.then(x=>(Mr(x,typeof l=="string"?l:"shadermate.webm"),x)):M}return v}return{screenshot:n,toBlob:o,download:i,record:r}}function Mr(e,t){let n=URL.createObjectURL(e),o=document.createElement("a");o.href=n,o.download=t,document.body.appendChild(o),o.click(),o.remove(),setTimeout(()=>URL.revokeObjectURL(n),1e3)}function gs(e,t){var n;if(typeof e=="string"||Array.isArray(e))return{...t||{},passes:e};if(e&&typeof e=="object"&&(e.shader!=null||e.passes!=null||e.src!=null)){let o={...e};return o.passes==null?o.passes={src:(n=o.shader)!=null?n:o.src,uniforms:o.passUniforms,channels:o.channels,pingpong:o.pingpong,float:o.float}:o.channels!=null&&console.warn("[ShaderMate] `channels` only applies to the single-shader form; put channels on each pass instead."),o}throw new Se("createShader: pass a shader string, an array of passes, or { shader | passes, ...options }")}function bs(e){if(e&&typeof e=="object"&&typeof e.getContext=="function")return{canvas:e,given:!0};if(typeof e=="string"){let n=document.getElementById(e);if(!n)try{n=document.querySelector(e)}catch{}if(!n)throw new Se(`Canvas not found: "${e}"`);return{canvas:n,given:!0}}let t=document.getElementById(cr);return t?{canvas:t,given:!0}:(t=document.createElement("canvas"),t.id=cr,(document.body||document.documentElement).appendChild(t),{canvas:t,given:!1})}function Ln(e,t,n){let o=e[t];po(o)?o.value=n:e[t]=n}var so=(e,t)=>po(e[t])?e[t].value:e[t];function Ur(e,t){var n,o,i;if(!co)throw new Se("ShaderMate needs a browser environment (window/document).");let r=gs(e,t),a=r.autoSetup!==!1,c=Object.assign({},a?_r:Ia,r.inject),u=ur(r.defines),s=typeof r.common=="string"?r.common:"",l=r.dialect||"auto",p=r.samplers||{},f=r.uniforms||{},h=r.includes||{},y=!!r.strictUniforms,E=r.warnMissingUniforms!==!1,v=r.showExpandedOnError!==!1,M=r.errorOverlay===void 0||r.errorOverlay==="auto"?ta():!!r.errorOverlay,x,S,b;r.gl?(b=r.gl,x=b.canvas,S=!0):({canvas:x,given:S}=bs(r.canvas),b=da(x,r));let _=ua(b),L=fa(b,_),P={isGL2:_,ext:L},R=new na(b),j=!!(_||L.OES_standard_derivatives),C=ea((n=r.background)!=null?n:r.clearColor)||[0,0,0,0];b.clearColor(C[0],C[1],C[2],C[3]);let D=oa(),{emit:F,on:I,off:N,once:z}=D,se=pa(b),de=ds(x,r,S),oe=cs(x,de.fit,r.pointer===!1?{target:"canvas",smooth:0}:typeof r.pointer=="object"?r.pointer:{}),ee=ra(),te=M?hs(x,r.theme):null,we=null;r.stats&&(we=kr({visible:r.stats===!0||r.stats==="visible",key:r.statsKey===void 0?"F1":r.statsKey,position:r.statsPosition,theme:r.theme}));let ue=[],W=new Map,Y=[],be=!1,ce=!1,le=null,me=()=>{},pe=performance.now(),ge=0,xe=0,ke=r.time||0,ie=r.autoplay!==!1&&!r.startPaused&&!r.paused,ze=(o=r.timeScale)!=null?o:1,Be=r.fixedDelta||0,lt=r.maxFps||r.fps||0,qe=r.loop||0,Ne=(i=r.maxDelta)!=null?i:.1,Ct=!0,De=null,Ft=60,et=[],Me=null,Ye=null,Ae=!1,ht=fs(x,{enabled:r.pauseWhenHidden!==!1,onChange:T=>{Ct=T,T&&(pe=performance.now()),F("visibility",T)}});function Fe(T){De=T,te&&te.show(T),F("error",T),r.onError&&r.onError(T)}function mt(){De=null,te&&te.hide()}let tt=async T=>{let O=await fetch(T);if(!O.ok)throw new Se(`Failed to fetch ${T}: ${O.status} ${O.statusText}`);return O.text()},St=async T=>h[T]!=null?h[T]:tt(T),Ce=null;async function Tt(){if(Ce!==null)return Ce;if(!s)return Ce="";let T=ro(s)?s:await tt(s),O=xr(T);for(let $ in O.uniforms)$ in f||(f[$]=O.uniforms[$]);return Object.assign(p,O.samplers,p),Ce=O.source}async function nt(T,O,$=Y){let V=ro(O)?O:await tt(O),K=await Tt(),H=xr(V);V=H.source;for(let g in H.uniforms)!(g in T.uniforms)&&!(g in f)&&(T.uniforms[g]=H.uniforms[g]);T.annotatedSamplers=H.samplers;let J=K?K+`
|
|
77
77
|
#line 1
|
|
78
|
-
`+
|
|
79
|
-
`+R.common:R.common);let O=R.passes.find(q=>q.bufferType!=="2d");if(O)throw new ye(`Pass "${O.label}" uses a ${O.bufferType} buffer; ShaderMate supports 2D buffers only.`);let j=R.passes.map(q=>q.main?{name:"main",shader:q.src,screen:!0}:{name:q.name,shader:q.src,pingpong:!0,float:!0});return j.some(q=>q.screen)||(j[j.length-1].screen=!0),j}async function He(){Fe=Ii(It(r.passes));for(let C of Fe)C.iterations>1&&!C.screen&&(C.pingpong=!0);for(let C=0;C<Fe.length;C++){let R=Fe[C],{program:O,source:j,compiled:q,fragcoord:N}=await Ut(R,R.src);if(Ee){w.deleteProgram(O);return}let g={cfg:R,name:R.name,index:C,programId:P.add(O,"program"),uniformInfo:Jo(w,O),source:j,compiled:q,fragcoord:N,target:null,targetPrev:null,texChannels:new Array(an).fill(null),samplers:[]};ae.push(g),he.set(g.name,g)}await Promise.all(ae.map(pt)),!Ee&&(we=Aa(ae),we&&!je&&(je=Yi(w,A,V)),!ge&&ae.some(C=>C.uniformInfo.u_camera_pos||C.uniformInfo.u_camera_dir||C.uniformInfo.u_camera_view)&&(ge=Pa(b,typeof r.camera=="object"?r.camera:{})),Je())}function it(C,R,O){let j=null;return R.targetPrev?j=O==="prev"||O!=="current"&&R.index>=C.index?R.targetPrev:R.target:R===C?Nt("self:"+C.name,`Pass "${C.name}" reads its own output; add pingpong: true.`):R.cfg.screen?Nt("screen:"+R.name,`Pass "${C.name}" can't read screen pass "${R.name}" (it has no texture).`):j=R.target,j}function $e(C,R,O=0){let j=C.cfg,q=P.get(C.programId),N=C.uniformInfo,g=ce.state,$=(Z,ve)=>{let ue=N[Z];ue&&w.uniform1f(ue.loc,ve)},ee=(Z,ve)=>{let ue=N[Z];ue&&w.uniform1i(ue.loc,ve)};if(C.targetPrev){let Z=C.targetPrev;C.targetPrev=C.target,C.target=Z}let J,oe;j.screen&&!we?(w.bindFramebuffer(w.FRAMEBUFFER,null),J=b.width,oe=b.height):(w.bindFramebuffer(w.FRAMEBUFFER,P.get(C.target.fboId)),J=C.target.width,oe=C.target.height);let re=j.screen?1:J/b.width,Q=j.screen?1:oe/b.height;if(w.viewport(0,0,J,oe),w.useProgram(q),w.clear(w.COLOR_BUFFER_BIT|(C.target&&C.target.depthId?w.DEPTH_BUFFER_BIT:0)),$("iTime",R.time),$("u_time",R.time),$("iTimeDelta",R.dt),$("u_delta",R.dt),$("u_time_delta",R.dt),ee("iFrame",R.frame),ee("u_frame",R.frame),$("iFrameRate",R.fps),$("u_fps",R.fps),$("u_refresh_rate",R.refreshRate),$("iSampleRate",44100),N.iResolution&&w.uniform3f(N.iResolution.loc,J,oe,1),N.u_resolution&&w.uniform2f(N.u_resolution.loc,J,oe),$("u_aspect",J/oe),$("u_pixelRatio",R.dpr),N.iDate&&w.uniform4fv(N.iDate.loc,R.date),N.u_date&&w.uniform4fv(N.u_date.loc,R.date),N.iScroll&&w.uniform2f(N.iScroll.loc,R.scrollX,R.scrollY),N.u_scroll&&(N.u_scroll.type===Ia?w.uniform1f(N.u_scroll.loc,g.wheel):w.uniform2f(N.u_scroll.loc,R.scrollX,R.scrollY)),$("u_wheel",g.wheel),N.u_drag&&w.uniform2f(N.u_drag.loc,g.dragX*re,g.dragY*Q),ee("u_recursion",O),ee("u_max_recursion",j.iterations||1),ee("u_color_gamut",0),ge&&(N.u_camera_pos&&w.uniform3fv(N.u_camera_pos.loc,ge.pos),N.u_camera_dir&&w.uniform3fv(N.u_camera_dir.loc,ge.dir),N.u_camera_view&&w.uniformMatrix4fv(N.u_camera_view.loc,!1,ge.view)),N.iMouse){let Z=g.down?1:-1,ve=g.clicked?1:-1;w.uniform4f(N.iMouse.loc,g.x*re,g.y*Q,g.clickX*re*Z,g.clickY*Q*ve)}if(N.u_mouse)if(N.u_mouse.type===rr){let Z=g.down?1:-1;w.uniform4f(N.u_mouse.loc,g.x*re,g.y*Q,g.clickX*re*Z,g.clickY*Q*Z)}else w.uniform2f(N.u_mouse.loc,g.x*re,g.y*Q);N.u_mouseUV&&w.uniform2f(N.u_mouseUV.loc,g.uvX,g.uvY),$("u_mouseDown",g.down?1:0);let de=[0,0,0,0],ht=new Float32Array(12);for(let Z=0;Z<an;Z++){let ve=j.channels[Z];if(!ve)continue;let ue=null,xe=0,Ct=0,vo=!1,Eo=R.time;if(ve.pass!=null){let lt=he.get(ve.pass),hn=lt?it(C,lt,ve.buffer):null;hn&&(ue=P.get(hn.texId),xe=hn.width,Ct=hn.height)}else{let lt=C.texChannels[Z];lt&&(ue=P.get(lt.texId),xe=lt.width,Ct=lt.height,vo=!!lt.cubemap,lt.getTime&&(Eo=lt.getTime()))}ue&&(w.activeTexture(w.TEXTURE0+Z),w.bindTexture(vo?w.TEXTURE_CUBE_MAP:w.TEXTURE_2D,ue),ee("iChannel"+Z,Z),de[Z]=Eo,ht[Z*3]=xe,ht[Z*3+1]=Ct,ht[Z*3+2]=1)}N.iChannelTime&&(N.iChannelTime.type===rr?w.uniform4fv:w.uniform1fv).call(w,N.iChannelTime.loc,de),N.iChannelResolution&&w.uniform3fv(N.iChannelResolution.loc,ht);let mt=an;for(let Z of C.samplers){let ve=(ue,xe)=>(w.activeTexture(w.TEXTURE0+mt),w.bindTexture(xe?w.TEXTURE_CUBE_MAP:w.TEXTURE_2D,ue),mt++);if(Z.spec.array){let ue=Z.spec.array.map(xe=>{let Ct=it(C,xe,Z.spec.buffer);return Ct?ve(P.get(Ct.texId),!1):0});w.uniform1iv(Z.info.loc,ue)}else if(Z.spec.pass!=null){let ue=he.get(Z.spec.pass),xe=ue?it(C,ue,Z.spec.buffer):null;xe&&w.uniform1i(Z.info.loc,ve(P.get(xe.texId),!1))}else if(Z.wrap){w.uniform1i(Z.info.loc,ve(P.get(Z.wrap.texId),!!Z.wrap.cubemap)),Z.wrap.getTime&&$(Z.name+"_time",Z.wrap.getTime());let ue=N[Z.name+"_resolution"];ue&&w.uniform2f(ue.loc,Z.wrap.width,Z.wrap.height)}}ar(w,N,u,{strict:!1}),ar(w,N,j.uniforms,{strict:x,warnMissing:E,label:C.name}),V.bind(q),V.draw()}function at(C,{advance:R=le,rawDt:O}={}){let j=performance.now();if(O===void 0&&(O=Math.max(0,(C-De)*.001)),De=C,O>.002&&O<.1&&(Pe.push(O),Pe.length>30&&Pe.shift(),Pe.length>=10)){let J=[...Pe].sort((oe,re)=>oe-re);Ye=Math.round(1/J[J.length>>1])}let q=Ae>0?Ae:Math.min(O,Lt);R?(ke+=q*nt,Ge>0&&(ke=(ke%Ge+Ge)%Ge)):q=0,_e++;let N=O>0?1/O:0;be.update(C),ce.update();let g={time:ke,frame:_e,dt:q,fps:N};D("beforeFrame",g),r.onFrame&&r.onFrame(g);let $=new Date,ee={time:ke,frame:_e,dt:q,fps:N,dpr:window.devicePixelRatio||1,date:[$.getFullYear(),$.getMonth()+1,$.getDate(),$.getHours()*3600+$.getMinutes()*60+$.getSeconds()+$.getMilliseconds()/1e3],scrollX:window.scrollX||0,scrollY:window.scrollY||0,refreshRate:Ye};ge&&ge.update(O);for(let J of ae){for(let oe of J.texChannels)oe&&oe.update&&oe.update();for(let oe of J.samplers)oe.wrap&&oe.wrap.update&&oe.wrap.update()}for(let J of ae){let oe=Math.max(1,J.cfg.iterations|0);for(let re=0;re<oe;re++)$e(J,ee,re);J.cfg.screen&&we&&je&&je.draw(P.get(J.target.texId),b.width,b.height)}w.bindFramebuffer(w.FRAMEBUFFER,null),D("afterFrame",g),se&&se.update({rawDt:O,cpuMs:performance.now()-j,frame:_e,time:ke,width:b.width,height:b.height,passes:ae.length})}function Re(C){if(Xe=requestAnimationFrame(Re),!me||!Oe){De=C;return}if(!le&&be.size===0&&r.renderWhilePaused!==!0){De=C;return}qe>0&&C-We<1e3/qe-.5||(We=C,at(C))}function ze(){!me||Ee||at(performance.now(),{advance:!1,rawDt:0})}function Ft(){Ee||Xe!=null||(De=performance.now(),Xe=requestAnimationFrame(Re))}function Yt(){Xe!=null&&cancelAnimationFrame(Xe),Xe=null}function Mt(){Ee||(Ee=!0,Yt(),Ve(),ce.dispose(),Et.dispose(),be.cancel(),se&&se.dispose(),Te&&Te.dispose(),ge&&ge.dispose(),je&&je.dispose(),b.removeEventListener("webglcontextlost",Qe),b.removeEventListener("webglcontextrestored",ct),st(),V.dispose(),D("destroy"),I.clear(),!S&&b.parentNode&&b.parentNode.removeChild(b))}function st(){for(let C of ae)P.unref(C.programId),Cn(P,C.target),Cn(P,C.targetPrev),C.texChannels.forEach(R=>{R&&(R.dispose&&R.dispose(),P.unref(R.texId))}),(C.samplers||[]).forEach(R=>{R.wrap&&(R.wrap.dispose&&R.wrap.dispose(),P.unref(R.wrap.texId))});ae.length=0,he.clear()}function Qe(C){C.preventDefault(),Yt(),me=!1,console.warn("[ShaderMate] WebGL context lost."),D("contextlost")}async function ct(){console.warn("[ShaderMate] WebGL context restored, rebuilding."),P._items.clear(),ae.length=0,he.clear();try{await He(),me=!0,Ft(),D("contextrestored")}catch(C){Le(C)}}b.addEventListener("webglcontextlost",Qe),b.addEventListener("webglcontextrestored",ct);let Dt=ja(b,ze);function p(C,R,O){if(C&&typeof C=="object"){for(let q in C)p(q,C[q],R);return te}be.cancel(C);let j=!1;for(let q of ae)O&&q.name!==O||C in q.cfg.uniforms&&(Sn(q.cfg.uniforms,C,R),j=!0);if(!j)if(O){let q=he.get(O);if(!q)throw new ye(`set: unknown pass "${O}"`);Sn(q.cfg.uniforms,C,R)}else Sn(u,C,R);return!le&&me&&X(),te}function M(C,R){for(let O of ae)if(!(R&&O.name!==R)&&C in O.cfg.uniforms)return Jn(O.cfg.uniforms,C);return Jn(u,C)}function _(C,R,O={}){let j=O.pass,q=()=>{for(let N of ae)if((!j||N.name===j)&&C in N.cfg.uniforms)return N.cfg.uniforms;return u};return be.tween(C,()=>Jn(q(),C),N=>Sn(q(),C,N),R,O)}let F=!1;function X(){F||(F=!0,requestAnimationFrame(()=>{F=!1,le||ze()}))}async function ne(C,R){let O=R?he.get(R):ae.find(j=>j.cfg.screen)||ae[0];if(!O)throw new ye(`setShader: unknown pass "${R}"`);try{let{program:j,source:q,compiled:N}=await Ut(O.cfg,C,Fe);if(Ee){w.deleteProgram(j);return}P.unref(O.programId),O.programId=P.add(j,"program"),O.uniformInfo=Jo(w,j),O.cfg.src=C,O.source=q,O.compiled=N,await pt(O),Rt(),D("shader",{pass:O.name}),le||X()}catch(j){throw Le(j),j}}async function ie(C,R,O){let j=O?he.get(O):ae.find(g=>g.cfg.screen)||ae[0];if(!j)throw new ye(`setChannel: unknown pass "${O}"`);let q=lr(R,[...he.keys()],j.name),N=j.texChannels[C];N&&(N.dispose&&N.dispose(),P.unref(N.texId),j.texChannels[C]=null),j.cfg.channels[C]=q,q&&q.pass==null&&(j.texChannels[C]=await Kn(w,P,q,T)),le||X()}let te={version:Si,canvas:b,gl:w,isWebGL2:A,theme:r.theme,get camera(){return ge},uniforms:u,get passes(){return ae},get ready(){return fe},get loaded(){return me},get error(){return ot},play(){return le||(le=!0,De=performance.now(),D("play")),te},pause(){return le&&(le=!1,D("pause")),te},toggle(){return le?te.pause():te.play()},get playing(){return le},step(C=1){for(let R=0;R<C;R++)at(performance.now(),{advance:!0,rawDt:Ae||1/60});return te},render:ze,destroy:Mt,dispose:Mt,get time(){return ke},set time(C){ke=C,le||X()},get frame(){return _e},get timeScale(){return nt},set timeScale(C){nt=C},get maxFps(){return qe},set maxFps(C){qe=C||0},get loop(){return Ge},set loop(C){Ge=C||0},seek(C){return ke=C,le||X(),te},setFixedDelta(C){return Ae=C||0,te},set:p,get:M,tween:_,setUniform:p,getUniform:M,setShader:ne,setChannel:ie,getPass:C=>he.get(C)||null,getTexture(C){let R=C?he.get(C):ae.find(O=>!O.cfg.screen)||ae[0];return R&&R.target?P.get(R.target.texId):null},readPixels({pass:C,x:R=0,y:O=0,width:j,height:q,float:N}={}){let g=C?he.get(C):null;ze(),g&&g.target?w.bindFramebuffer(w.FRAMEBUFFER,P.get(g.target.fboId)):w.bindFramebuffer(w.FRAMEBUFFER,null);let $=j??(g&&g.target?g.target.width:b.width),ee=q??(g&&g.target?g.target.height:b.height),J=new Uint8Array($*ee*4);if(g&&g.target&&g.target.fmt.type!==w.UNSIGNED_BYTE){let re=new Float32Array($*ee*4);if(w.readPixels(R,O,$,ee,w.RGBA,w.FLOAT,re),N!==!1)J=re;else for(let Q=0;Q<re.length;Q++)J[Q]=Math.max(0,Math.min(255,Math.round(re[Q]*255)))}else w.readPixels(R,O,$,ee,w.RGBA,w.UNSIGNED_BYTE,J);return w.bindFramebuffer(w.FRAMEBUFFER,null),{data:J,width:$,height:ee,float:J instanceof Float32Array}},resize:ft,setSize(C,R){return G.setFixed(C,R),ft(),te},get width(){return b.width},get height(){return b.height},pointer:ce.state,domToShader:ce.toShader,domToUV:ce.toUV,screenshot:Dt.screenshot,toBlob:Dt.toBlob,download:Dt.download,record:Dt.record,on:U,off:B,once:H,stats:{show:(C=!0)=>{se||(se=sr({visible:!1,key:r.statsKey===void 0?"F1":r.statsKey,theme:r.theme})),se.show(C)},toggle:()=>te.stats.show(!(se&&se.isVisible()))}};G.update(),w.viewport(0,0,b.width,b.height),Ve=G.observe(ft);let fe=(async()=>(await He(),Ee||(me=!0,Rt(),D("load",te),r.onReady&&r.onReady(te),Ft(),le||ze()),te))();return fe.catch(C=>{Ee||Le(C)}),te}var xr=`
|
|
78
|
+
`+V:V,ae=await Ra(J,{loader:St}),ye=l==="fragcoord"||l==="auto"&&Pa(ae),w=[],G=$.filter(g=>!g.screen);$.forEach(g=>w.push("u_"+g.name)),G.forEach((g,k)=>{let A="u_pass"+(k+1);w.includes(A)||w.push(A)});let ne=Oa(ae,{isGL2:_,defines:[...u,...ur(T.defines)],enableDerivatives:j,inject:c,channelTypes:T.channels.map(Xa),builtinOpts:{fragcoord:ye,mouseVec4:ye||l==="fragcoord"||Ka(ae),scrollFloat:ye||l==="fragcoord",samplerNames:w,passCount:G.length}}),d=Sr(b,_?Tr:Ar,ne,{label:T.name,showExpandedOnError:v});if(d.error)throw d.error;return{program:d.program,source:V,compiled:ne,fragcoord:ye}}function Ke(){for(let T of ue){let O=T.cfg;if(O.screen&&!Ae)continue;let[$,V]=O.screen?[x.width,x.height]:Ma(O.size,x.width,x.height);T.target&&T.target.width===$&&T.target.height===V||(Pn(R,T.target),Pn(R,T.targetPrev),T.target=mr(b,R,$,V,O,_,L),T.targetPrev=O.pingpong||O.screen&&Ae?mr(b,R,$,V,O,_,L):null)}}function ot(){be||de.update()&&(b.viewport(0,0,x.width,x.height),Ke(),F("resize",{width:x.width,height:x.height}),!ie&&ce&&$e())}async function gt(T){await Promise.all(T.cfg.channels.map(async(O,$)=>{if(!(!O||O.pass!=null))try{T.texChannels[$]=await io(b,R,O,P)}catch(V){console.warn(`[ShaderMate] Pass "${T.name}" channel ${$}: ${V.message}`),F("error",V)}})),T.samplers=es(T,ue,p),await Promise.all(T.samplers.map(async O=>{if(!(O.spec.pass!=null||O.spec.array))try{O.wrap=await io(b,R,O.spec,P)}catch($){console.warn(`[ShaderMate] Pass "${T.name}" sampler ${O.name}: ${$.message}`),F("error",$)}}))}function ut(T){if(typeof T!="string"||!ro(T))return T;let O=Wa(T);if(!O)return T;O.common&&(s=s?s+`
|
|
79
|
+
`+O.common:O.common);let $=O.passes.find(K=>K.bufferType!=="2d");if($)throw new Se(`Pass "${$.label}" uses a ${$.bufferType} buffer; ShaderMate supports 2D buffers only.`);let V=O.passes.map(K=>K.main?{name:"main",shader:K.src,screen:!0}:{name:K.name,shader:K.src,pingpong:!0,float:!0});return V.some(K=>K.screen)||(V[V.length-1].screen=!0),V}async function Ge(){Y=aa(ut(r.passes));for(let T of Y)T.iterations>1&&!T.screen&&(T.pingpong=!0);for(let T=0;T<Y.length;T++){let O=Y[T],{program:$,source:V,compiled:K,fragcoord:H}=await nt(O,O.src);if(be){b.deleteProgram($);return}let J={cfg:O,name:O.name,index:T,programId:R.add($,"program"),uniformInfo:hr(b,$),source:V,compiled:K,fragcoord:H,target:null,targetPrev:null,texChannels:new Array(ln).fill(null),samplers:[]};ue.push(J),W.set(J.name,J)}await Promise.all(ue.map(gt)),!be&&(Ae=ts(ue),Ae&&!Ye&&(Ye=va(b,_,se)),!Me&&ue.some(T=>T.uniformInfo.u_camera_pos||T.uniformInfo.u_camera_dir||T.uniformInfo.u_camera_view)&&(Me=ns(x,typeof r.camera=="object"?r.camera:{})),Ke())}function dt(T,O,$){let V=null;return O.targetPrev?V=$==="prev"||$!=="current"&&O.index>=T.index?O.targetPrev:O.target:O===T?Ht("self:"+T.name,`Pass "${T.name}" reads its own output; add pingpong: true.`):O.cfg.screen?Ht("screen:"+O.name,`Pass "${T.name}" can't read screen pass "${O.name}" (it has no texture).`):V=O.target,V}function je(T,O,$=0){let V=T.cfg,K=R.get(T.programId),H=T.uniformInfo,J=oe.state,ae=(U,B)=>{let X=H[U];X&&b.uniform1f(X.loc,B)},ye=(U,B)=>{let X=H[U];X&&b.uniform1i(X.loc,B)};if(T.targetPrev){let U=T.targetPrev;T.targetPrev=T.target,T.target=U}let w,G;V.screen&&!Ae?(b.bindFramebuffer(b.FRAMEBUFFER,null),w=x.width,G=x.height):(b.bindFramebuffer(b.FRAMEBUFFER,R.get(T.target.fboId)),w=T.target.width,G=T.target.height);let ne=V.screen?1:w/x.width,d=V.screen?1:G/x.height;if(b.viewport(0,0,w,G),b.useProgram(K),b.clear(b.COLOR_BUFFER_BIT|(T.target&&T.target.depthId?b.DEPTH_BUFFER_BIT:0)),ae("iTime",O.time),ae("u_time",O.time),ae("iTimeDelta",O.dt),ae("u_delta",O.dt),ae("u_time_delta",O.dt),ye("iFrame",O.frame),ye("u_frame",O.frame),ae("iFrameRate",O.fps),ae("u_fps",O.fps),ae("u_refresh_rate",O.refreshRate),ae("iSampleRate",44100),H.iResolution&&b.uniform3f(H.iResolution.loc,w,G,1),H.u_resolution&&b.uniform2f(H.u_resolution.loc,w,G),ae("u_aspect",w/G),ae("u_pixelRatio",O.dpr),H.iDate&&b.uniform4fv(H.iDate.loc,O.date),H.u_date&&b.uniform4fv(H.u_date.loc,O.date),H.iScroll&&b.uniform2f(H.iScroll.loc,O.scrollX,O.scrollY),H.u_scroll&&(H.u_scroll.type===as?b.uniform1f(H.u_scroll.loc,J.wheel):b.uniform2f(H.u_scroll.loc,O.scrollX,O.scrollY)),ae("u_wheel",J.wheel),H.u_drag&&b.uniform2f(H.u_drag.loc,J.dragX*ne,J.dragY*d),ye("u_recursion",$),ye("u_max_recursion",V.iterations||1),ye("u_color_gamut",0),Me&&(H.u_camera_pos&&b.uniform3fv(H.u_camera_pos.loc,Me.pos),H.u_camera_dir&&b.uniform3fv(H.u_camera_dir.loc,Me.dir),H.u_camera_view&&b.uniformMatrix4fv(H.u_camera_view.loc,!1,Me.view)),H.iMouse){let U=J.down?1:-1,B=J.clicked?1:-1;b.uniform4f(H.iMouse.loc,J.x*ne,J.y*d,J.clickX*ne*U,J.clickY*d*B)}if(H.u_mouse)if(H.u_mouse.type===wr){let U=J.down?1:-1;b.uniform4f(H.u_mouse.loc,J.x*ne,J.y*d,J.clickX*ne*U,J.clickY*d*U)}else b.uniform2f(H.u_mouse.loc,J.x*ne,J.y*d);H.u_mouseUV&&b.uniform2f(H.u_mouseUV.loc,J.uvX,J.uvY),ae("u_mouseDown",J.down?1:0);let g=[0,0,0,0],k=new Float32Array(12);for(let U=0;U<ln;U++){let B=V.channels[U];if(!B)continue;let X=null,re=0,fe=0,_e=!1,Ve=O.time;if(B.pass!=null){let Qe=W.get(B.pass),xn=Qe?dt(T,Qe,B.buffer):null;xn&&(X=R.get(xn.texId),re=xn.width,fe=xn.height)}else{let Qe=T.texChannels[U];Qe&&(X=R.get(Qe.texId),re=Qe.width,fe=Qe.height,_e=!!Qe.cubemap,Qe.getTime&&(Ve=Qe.getTime()))}X&&(b.activeTexture(b.TEXTURE0+U),b.bindTexture(_e?b.TEXTURE_CUBE_MAP:b.TEXTURE_2D,X),ye("iChannel"+U,U),g[U]=Ve,k[U*3]=re,k[U*3+1]=fe,k[U*3+2]=1)}H.iChannelTime&&(H.iChannelTime.type===wr?b.uniform4fv:b.uniform1fv).call(b,H.iChannelTime.loc,g),H.iChannelResolution&&b.uniform3fv(H.iChannelResolution.loc,k);let A=ln;for(let U of T.samplers){let B=(X,re)=>(b.activeTexture(b.TEXTURE0+A),b.bindTexture(re?b.TEXTURE_CUBE_MAP:b.TEXTURE_2D,X),A++);if(U.spec.array){let X=U.spec.array.map(re=>{let fe=dt(T,re,U.spec.buffer);return fe?B(R.get(fe.texId),!1):0});b.uniform1iv(U.info.loc,X)}else if(U.spec.pass!=null){let X=W.get(U.spec.pass),re=X?dt(T,X,U.spec.buffer):null;re&&b.uniform1i(U.info.loc,B(R.get(re.texId),!1))}else if(U.wrap){b.uniform1i(U.info.loc,B(R.get(U.wrap.texId),!!U.wrap.cubemap)),U.wrap.getTime&&ae(U.name+"_time",U.wrap.getTime());let X=H[U.name+"_resolution"];X&&b.uniform2f(X.loc,U.wrap.width,U.wrap.height)}}Er(b,H,f,{strict:!1}),Er(b,H,V.uniforms,{strict:y,warnMissing:E,label:T.name}),se.bind(K),se.draw()}function Le(T,{advance:O=ie,rawDt:$}={}){let V=performance.now();if($===void 0&&($=Math.max(0,(T-pe)*.001)),pe=T,$>.002&&$<.1&&(et.push($),et.length>30&&et.shift(),et.length>=10)){let w=[...et].sort((G,ne)=>G-ne);Ft=Math.round(1/w[w.length>>1])}let K=Be>0?Be:Math.min($,Ne);O?(ke+=K*ze,qe>0&&(ke=(ke%qe+qe)%qe)):K=0,xe++;let H=$>0?1/$:0;ee.update(T),oe.update();let J={time:ke,frame:xe,dt:K,fps:H};F("beforeFrame",J),r.onFrame&&r.onFrame(J);let ae=new Date,ye={time:ke,frame:xe,dt:K,fps:H,dpr:window.devicePixelRatio||1,date:[ae.getFullYear(),ae.getMonth()+1,ae.getDate(),ae.getHours()*3600+ae.getMinutes()*60+ae.getSeconds()+ae.getMilliseconds()/1e3],scrollX:window.scrollX||0,scrollY:window.scrollY||0,refreshRate:Ft};Me&&Me.update($);for(let w of ue){for(let G of w.texChannels)G&&G.update&&G.update();for(let G of w.samplers)G.wrap&&G.wrap.update&&G.wrap.update()}for(let w of ue){let G=Math.max(1,w.cfg.iterations|0);for(let ne=0;ne<G;ne++)je(w,ye,ne);w.cfg.screen&&Ae&&Ye&&Ye.draw(R.get(w.target.texId),x.width,x.height)}b.bindFramebuffer(b.FRAMEBUFFER,null),F("afterFrame",J),we&&we.update({rawDt:$,cpuMs:performance.now()-V,frame:xe,time:ke,width:x.width,height:x.height,passes:ue.length})}function rt(T){if(le=requestAnimationFrame(rt),!ce||!Ct){pe=T;return}if(!ie&&ee.size===0&&r.renderWhilePaused!==!0){pe=T;return}lt>0&&T-ge<1e3/lt-.5||(ge=T,Le(T))}function $e(){!ce||be||Le(performance.now(),{advance:!1,rawDt:0})}function Ze(){be||le!=null||(pe=performance.now(),le=requestAnimationFrame(rt))}function At(){le!=null&&cancelAnimationFrame(le),le=null}function He(){be||(be=!0,At(),me(),oe.dispose(),ht.dispose(),ee.cancel(),we&&we.dispose(),te&&te.dispose(),Me&&Me.dispose(),Ye&&Ye.dispose(),x.removeEventListener("webglcontextlost",Pt),x.removeEventListener("webglcontextrestored",$t),_t(),se.dispose(),F("destroy"),D.clear(),!S&&x.parentNode&&x.parentNode.removeChild(x))}function _t(){for(let T of ue)R.unref(T.programId),Pn(R,T.target),Pn(R,T.targetPrev),T.texChannels.forEach(O=>{O&&(O.dispose&&O.dispose(),R.unref(O.texId))}),(T.samplers||[]).forEach(O=>{O.wrap&&(O.wrap.dispose&&O.wrap.dispose(),R.unref(O.wrap.texId))});ue.length=0,W.clear()}function Pt(T){T.preventDefault(),At(),ce=!1,console.warn("[ShaderMate] WebGL context lost."),F("contextlost")}async function $t(){console.warn("[ShaderMate] WebGL context restored, rebuilding."),R._items.clear(),ue.length=0,W.clear();try{await Ge(),ce=!0,Ze(),F("contextrestored")}catch(T){Fe(T)}}x.addEventListener("webglcontextlost",Pt),x.addEventListener("webglcontextrestored",$t);let it=ms(x,$e);function Je(T,O,$){if(T&&typeof T=="object"){for(let K in T)Je(K,T[K],O);return ve}ee.cancel(T);let V=!1;for(let K of ue)$&&K.name!==$||T in K.cfg.uniforms&&(Ln(K.cfg.uniforms,T,O),V=!0);if(!V)if($){let K=W.get($);if(!K)throw new Se(`set: unknown pass "${$}"`);Ln(K.cfg.uniforms,T,O)}else Ln(f,T,O);return!ie&&ce&&Re(),ve}function bt(T,O){for(let $ of ue)if(!(O&&$.name!==O)&&T in $.cfg.uniforms)return so($.cfg.uniforms,T);return so(f,T)}function Kt(T,O,$={}){let V=$.pass,K=()=>{for(let H of ue)if((!V||H.name===V)&&T in H.cfg.uniforms)return H.cfg.uniforms;return f};return ee.tween(T,()=>so(K(),T),H=>Ln(K(),T,H),O,$)}let yt=!1;function Re(){yt||(yt=!0,requestAnimationFrame(()=>{yt=!1,ie||$e()}))}async function zt(T,O){let $=O?W.get(O):ue.find(V=>V.cfg.screen)||ue[0];if(!$)throw new Se(`setShader: unknown pass "${O}"`);try{let{program:V,source:K,compiled:H}=await nt($.cfg,T,Y);if(be){b.deleteProgram(V);return}R.unref($.programId),$.programId=R.add(V,"program"),$.uniformInfo=hr(b,V),$.cfg.src=T,$.source=K,$.compiled=H,await gt($),mt(),F("shader",{pass:$.name}),ie||Re()}catch(V){throw Fe(V),V}}async function Zt(T,O,$){let V=$?W.get($):ue.find(J=>J.cfg.screen)||ue[0];if(!V)throw new Se(`setChannel: unknown pass "${$}"`);let K=Cr(O,[...W.keys()],V.name),H=V.texChannels[T];H&&(H.dispose&&H.dispose(),R.unref(H.texId),V.texChannels[T]=null),V.cfg.channels[T]=K,K&&K.pass==null&&(V.texChannels[T]=await io(b,R,K,P)),ie||Re()}let ve={version:Ji,canvas:x,gl:b,isWebGL2:_,theme:r.theme,get camera(){return Me},uniforms:f,get passes(){return ue},get ready(){return Bt},get loaded(){return ce},get error(){return De},play(){return ie||(ie=!0,pe=performance.now(),F("play")),ve},pause(){return ie&&(ie=!1,F("pause")),ve},toggle(){return ie?ve.pause():ve.play()},get playing(){return ie},step(T=1){for(let O=0;O<T;O++)Le(performance.now(),{advance:!0,rawDt:Be||1/60});return ve},render:$e,destroy:He,dispose:He,get time(){return ke},set time(T){ke=T,ie||Re()},get frame(){return xe},get timeScale(){return ze},set timeScale(T){ze=T},get maxFps(){return lt},set maxFps(T){lt=T||0},get loop(){return qe},set loop(T){qe=T||0},seek(T){return ke=T,ie||Re(),ve},setFixedDelta(T){return Be=T||0,ve},set:Je,get:bt,tween:Kt,setUniform:Je,getUniform:bt,setShader:zt,setChannel:Zt,getPass:T=>W.get(T)||null,getTexture(T){let O=T?W.get(T):ue.find($=>!$.cfg.screen)||ue[0];return O&&O.target?R.get(O.target.texId):null},readPixels({pass:T,x:O=0,y:$=0,width:V,height:K,float:H}={}){let J=T?W.get(T):null;$e(),J&&J.target?b.bindFramebuffer(b.FRAMEBUFFER,R.get(J.target.fboId)):b.bindFramebuffer(b.FRAMEBUFFER,null);let ae=V??(J&&J.target?J.target.width:x.width),ye=K??(J&&J.target?J.target.height:x.height),w=new Uint8Array(ae*ye*4);if(J&&J.target&&J.target.fmt.type!==b.UNSIGNED_BYTE){let ne=new Float32Array(ae*ye*4);if(b.readPixels(O,$,ae,ye,b.RGBA,b.FLOAT,ne),H!==!1)w=ne;else for(let d=0;d<ne.length;d++)w[d]=Math.max(0,Math.min(255,Math.round(ne[d]*255)))}else b.readPixels(O,$,ae,ye,b.RGBA,b.UNSIGNED_BYTE,w);return b.bindFramebuffer(b.FRAMEBUFFER,null),{data:w,width:ae,height:ye,float:w instanceof Float32Array}},resize:ot,setSize(T,O){return de.setFixed(T,O),ot(),ve},get width(){return x.width},get height(){return x.height},pointer:oe.state,domToShader:oe.toShader,domToUV:oe.toUV,screenshot:it.screenshot,toBlob:it.toBlob,download:it.download,record:it.record,on:I,off:N,once:z,stats:{show:(T=!0)=>{we||(we=kr({visible:!1,key:r.statsKey===void 0?"F1":r.statsKey,theme:r.theme})),we.show(T)},toggle:()=>ve.stats.show(!(we&&we.isVisible()))}};de.update(),b.viewport(0,0,x.width,x.height),me=de.observe(ot);let Bt=(async()=>(await Ge(),be||(ce=!0,mt(),F("load",ve),r.onReady&&r.onReady(ve),Ze(),ie||$e()),ve))();return Bt.catch(T=>{be||Fe(T)}),ve}var Ir=`
|
|
80
80
|
// 256\xD71, palette colours in x = 0..count-1
|
|
81
81
|
uniform sampler2D u_palette;
|
|
82
82
|
uniform int u_count;
|
|
@@ -116,7 +116,7 @@ int colorKey(vec4 c) {
|
|
|
116
116
|
ivec3 b = ivec3(floor(c.rgb * 255.0 + 0.5));
|
|
117
117
|
return b.r * 65536 + b.g * 256 + b.b;
|
|
118
118
|
}
|
|
119
|
-
`,
|
|
119
|
+
`,Or=`
|
|
120
120
|
// 0 box, 1 nearest
|
|
121
121
|
uniform int u_resample;
|
|
122
122
|
// brightness, contrast, saturation, gamma
|
|
@@ -166,7 +166,7 @@ void main() {
|
|
|
166
166
|
a = (a >= u_alphaCut && a > 0.0) ? 1.0 : 0.0;
|
|
167
167
|
fragColor = vec4(c * a, a);
|
|
168
168
|
}
|
|
169
|
-
`,
|
|
169
|
+
`,Dr=`
|
|
170
170
|
// threshold bytes in .r
|
|
171
171
|
uniform sampler2D u_matrix;
|
|
172
172
|
// 0 pass-through, 1 nearest, 2 ordered
|
|
@@ -189,7 +189,7 @@ void main() {
|
|
|
189
189
|
}
|
|
190
190
|
fragColor = vec4(palColor(nearestIndex(c)), 1.0);
|
|
191
191
|
}
|
|
192
|
-
`,
|
|
192
|
+
`,Fr=`
|
|
193
193
|
// iteration index, set by ShaderMate for passes with iterations (declared here: a FragCoord.xyz built-in)
|
|
194
194
|
uniform int u_recursion;
|
|
195
195
|
uniform int u_on;
|
|
@@ -220,7 +220,7 @@ void main() {
|
|
|
220
220
|
int idx = nearestIndex(c);
|
|
221
221
|
fragColor = vec4(c - palColor(idx), float(idx));
|
|
222
222
|
}
|
|
223
|
-
|
|
223
|
+
`,$r=`
|
|
224
224
|
uniform int u_on;
|
|
225
225
|
void main() {
|
|
226
226
|
ivec2 P = topDown();
|
|
@@ -228,7 +228,7 @@ void main() {
|
|
|
228
228
|
vec4 d = at(iChannel1, P);
|
|
229
229
|
fragColor = d.a < 0.0 ? vec4(0.0) : vec4(palColor(int(d.a + 0.5)), 1.0);
|
|
230
230
|
}
|
|
231
|
-
`,
|
|
231
|
+
`,zr=`
|
|
232
232
|
uniform int u_on;
|
|
233
233
|
void main() {
|
|
234
234
|
ivec2 P = topDown();
|
|
@@ -255,7 +255,7 @@ void main() {
|
|
|
255
255
|
}
|
|
256
256
|
fragColor = cs[best];
|
|
257
257
|
}
|
|
258
|
-
`,
|
|
258
|
+
`,Br=`
|
|
259
259
|
uniform int u_on;
|
|
260
260
|
void main() {
|
|
261
261
|
ivec2 P = topDown();
|
|
@@ -276,7 +276,7 @@ void main() {
|
|
|
276
276
|
if (m >= 5) { fragColor = cs[i]; return; }
|
|
277
277
|
}
|
|
278
278
|
}
|
|
279
|
-
`,
|
|
279
|
+
`,Nr=`
|
|
280
280
|
// 0 none, 1 outer, 2 inner
|
|
281
281
|
uniform int u_outline;
|
|
282
282
|
uniform int u_corners;
|
|
@@ -298,11 +298,11 @@ void main() {
|
|
|
298
298
|
if (u_outline == 1 ? (!o && other) : (o && !other)) { fragColor = vec4(u_outlineColor, 1.0); return; }
|
|
299
299
|
}
|
|
300
300
|
}
|
|
301
|
-
`;var sn=(e,t)=>{let n=document.createElement("canvas");return n.width=e,n.height=t,n};async function Sr(){if(typeof document>"u")throw new Error("No DOM");let e=sn(1,1).getContext("webgl2");if(!e)throw new Error("WebGL 2 is not available");if(!e.getExtension("EXT_color_buffer_float"))throw new Error("Float render targets are not available");let t=e.getExtension("WEBGL_debug_renderer_info"),n=String(t?e.getParameter(t.UNMASKED_RENDERER_WEBGL):e.getParameter(e.RENDERER));e.getExtension("WEBGL_lose_context")?.loseContext();let o=sn(1,1),i=sn(1,1),r=sn(256,1),a=sn(1,1),c=b=>({element:b,filter:"nearest",wrap:"clamp"}),l=br({canvas:o,webgl:2,size:[1,1],pixelRatio:1,autoplay:!1,pauseWhenHidden:!1,pointer:!1,errorOverlay:!1,warnMissingUniforms:!1,preserveDrawingBuffer:!0,premultipliedAlpha:!1,antialias:!1,dialect:"shadermate",common:xr,samplers:{u_palette:c(r),u_matrix:c(a)},uniforms:{u_count:1,u_distance:0,u_resample:0,u_adjust:[0,0,0,1],u_hue:0,u_crop:[0,0,1,1],u_alphaCut:.5,u_mode:0,u_levels:1,u_amount:0,u_skew:1,u_strength:1,u_kn:0,u_kernel:new Float32Array(Wn*3),u_outline:0,u_corners:0,u_outlineColor:[0,0,0]},passes:[{name:"prep",shader:yr,float:"full",filter:"nearest",channels:[{...c(i),dynamic:!1}]},{name:"quant",shader:wr,filter:"nearest",channels:["prep"]},{name:"diffuse",shader:vr,float:"full",filter:"nearest",pingpong:!0,iterations:2,channels:["prep","diffuse"]},{name:"resolve",shader:Er,filter:"nearest",channels:["quant","diffuse"]},{name:"orphan",shader:kr,filter:"nearest",channels:["resolve"]},{name:"smooth",shader:Mr,filter:"nearest",channels:["orphan"]},{name:"out",shader:Cr,screen:!0,channels:["smooth"]}]}),s=null;if(l.on("error",b=>{s=b}),await l.ready,s||l.error)throw l.destroy(),s||l.error;let d=(b,S)=>{for(let w in S)l.set(w,S[w],b)},f=null,u="",h="";async function x(b){if(b.canvas===f&&!b.dirty)return;i.width=b.width,i.height=b.height;let S=i.getContext("2d");S.clearRect(0,0,i.width,i.height),S.drawImage(b.canvas,0,0),await l.setChannel(0,{...c(i),dynamic:!1},"prep"),f=b.canvas}function E(b){let S=b.palette.map(L=>L.join(",")).join(";");if(S===u)return;u=S;let w=r.getContext("2d"),A=w.createImageData(256,1);b.palette.forEach((L,T)=>A.data.set([L[0],L[1],L[2],255],T*4)),w.putImageData(A,0,0)}function y(b){let S=b?`${b.w}x${b.h}:${b.levels}:${b.values.join(",")}`:"none";if(S===h)return;h=S;let w=b||{w:1,h:1,values:[0]};a.width=w.w,a.height=w.h;let A=a.getContext("2d"),L=A.createImageData(w.w,w.h);for(let T=0;T<w.values.length;T++)L.data.set([w.values[T],0,0,255],T*4);A.putImageData(L,0,0)}async function k(b,S){let w=b.settings;await x(S),b.quantize&&E(b),y(b.map),(l.width!==b.width||l.height!==b.height)&&l.setSize(b.width,b.height);let A=b.kind==="diffusion",L=new Array(Wn).fill(null).map((D,U)=>b.kernel&&b.kernel[U]||[0,0,0]);l.set({u_count:b.palette.length||1,u_distance:b.distance,u_resample:w.size.resample==="nearest"?1:0,u_adjust:[w.adjust.brightness,w.adjust.contrast,w.adjust.saturation,w.adjust.gamma],u_hue:w.adjust.hue,u_crop:[b.crop.x,b.crop.y,b.crop.w,b.crop.h],u_alphaCut:w.alpha.threshold,u_mode:b.quantize?b.kind==="ordered"?2:1:0,u_levels:b.map?b.map.levels:1,u_amount:b.map?b.spread*w.dither.strength:0,u_skew:b.skew,u_strength:w.dither.strength,u_kn:b.kernel?b.kernel.length:0,u_kernel:new Float32Array(L.flat()),u_outline:{none:0,outer:1,inner:2}[b.outline.mode],u_corners:b.outline.corners?1:0,u_outlineColor:b.outline.color.map(D=>D/255)}),d("diffuse",{u_on:A?1:0}),d("resolve",{u_on:A?1:0}),d("orphan",{u_on:w.cleanup.orphans?1:0}),d("smooth",{u_on:w.cleanup.smooth?1:0}),l.getPass("diffuse").cfg.iterations=A?b.waves:1;let{data:T}=l.readPixels(),P=b.width,z=b.height,v=new Uint8ClampedArray(P*z*4),I=P*4;for(let D=0;D<z;D++)v.set(T.subarray((z-1-D)*I,(z-D)*I),D*I);return v}return{name:"webgl",renderer:n,software:/swiftshader|llvmpipe|softpipe|software|basic render/i.test(n),run:k,shader:l,destroy(){l.destroy()}}}var ro=typeof document<"u",Tr=e=>e&&typeof e=="object"&&"data"in e&&"width"in e&&"height"in e&&e.data&&e.data.length===e.width*e.height*4;async function Va(e){if(typeof Blob<"u"&&e instanceof Blob){if(typeof createImageBitmap=="function")try{return await createImageBitmap(e)}catch{}e=URL.createObjectURL(e)}if(!ro)throw new Error("Loading images by URL needs a browser; pass { width, height, data } in Node.");let t=new Image;return t.crossOrigin="anonymous",t.decoding="async",t.src=e,await t.decode(),t}function Wa(e){return{width:e.naturalWidth||e.videoWidth||e.displayWidth||e.codedWidth||e.width||0,height:e.naturalHeight||e.videoHeight||e.displayHeight||e.codedHeight||e.height||0}}function qa(e){if(e&&!Tr(e)&&typeof e=="object"){if(e.canvas&&typeof e.canvas=="object"&&"getContext"in e.canvas)return e.canvas;if(e.elt&&typeof e.elt=="object"&&"getContext"in e.elt)return e.elt}return e}async function _r(e,t={}){let n=t.maxSize||4096,o=qa(e);if((typeof o=="string"||typeof Blob<"u"&&o instanceof Blob)&&(o=await Va(o)),o&&typeof o.complete=="boolean"&&!o.complete&&o.decode&&await o.decode(),Tr(o)){let d={width:o.width,height:o.height,data:o.data,canvas:null};return ro&&Object.defineProperty(d,"canvas",{configurable:!0,get(){let f=document.createElement("canvas");f.width=o.width,f.height=o.height;let u=new ImageData(new Uint8ClampedArray(o.data),o.width,o.height);return f.getContext("2d").putImageData(u,0,0),Object.defineProperty(d,"canvas",{value:f}),f}}),d}if(!ro)throw new Error("Unsupported source in a non-browser environment. Pass { width, height, data }.");let{width:i,height:r}=Wa(o);if(!i||!r)throw new Error("Source has no size yet (is the image or video loaded?)");let a=Math.min(1,n/Math.max(i,r));i=Math.max(1,Math.round(i*a)),r=Math.max(1,Math.round(r*a));let c=t.canvas||document.createElement("canvas");c.width=i,c.height=r;let l=c.getContext("2d",{willReadFrequently:!0});l.clearRect(0,0,i,r),l.imageSmoothingEnabled=a<1,l.imageSmoothingQuality="high",l.drawImage(o,0,0,i,r);let s=null;return{width:i,height:r,canvas:c,dirty:!0,get data(){return s||(s=l.getImageData(0,0,i,r).data)}}}Bt();Bt();function Rr(e,t=1,n={}){let o=t>1||n.grid?_t(e,t,n):e,i=n.canvas||document.createElement("canvas");return i.width=o.width,i.height=o.height,i.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(o.data),o.width,o.height),0,0),i}function Be(e,t,n="application/octet-stream"){let o=e instanceof Blob?e:new Blob([e],{type:n}),i=URL.createObjectURL(o),r=document.createElement("a");r.href=i,r.download=t,r.rel="noopener",document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(i),1e4)}var _n=null;function An(e,t=0){if(!_n){_n=new Uint32Array(256);for(let n=0;n<256;n++){let o=n;for(let i=0;i<8;i++)o=o&1?3988292384^o>>>1:o>>>1;_n[n]=o>>>0}}t=~t>>>0;for(let n=0;n<e.length;n++)t=_n[(t^e[n])&255]^t>>>8;return~t>>>0}Bt();var Ya=[137,80,78,71,13,10,26,10];async function Ka(e){if(typeof CompressionStream=="function"){let n=new CompressionStream("deflate"),o=new Blob([e]).stream().pipeThrough(n);return new Uint8Array(await new Response(o).arrayBuffer())}let{deflateSync:t}=await import("node:zlib");return new Uint8Array(t(e))}function Qt(e,t){let n=new Uint8Array(12+t.length),o=new DataView(n.buffer);o.setUint32(0,t.length);for(let i=0;i<4;i++)n[4+i]=e.charCodeAt(i);return n.set(t,8),o.setUint32(8+t.length,An(n.subarray(4,8+t.length))),n}function Za(e){let t=e.data,n=e.width*e.height,o=new Map,i=[],r=new Uint8Array(n);for(let a=0;a<n;a++){let c=a*4,l=t[c+3]===0?-1:(t[c]<<24|t[c+1]<<16|t[c+2]<<8|t[c+3])>>>0,s=o.get(l);if(s===void 0){if(i.length===256)return null;s=i.length,o.set(l,s),i.push(l===-1?[0,0,0,0]:[t[c],t[c+1],t[c+2],t[c+3]])}r[a]=s}return{colors:i,indices:r}}async function dt(e,t={}){t.width&&t.height?e=Ar(e,t.width,t.height):(t.scale&&t.scale>1||t.grid)&&(e=_t(e,t.scale||1,t));let{width:n,height:o}=e,i=t.indexed===!1?null:Za(e),r=new Uint8Array(13),a=new DataView(r.buffer);a.setUint32(0,n),a.setUint32(4,o);let c=[new Uint8Array(Ya)],l;if(i){let u=i.colors.length<=2?1:i.colors.length<=4?2:i.colors.length<=16?4:8;r.set([u,3,0,0,0],8);let h=Math.ceil(n*u/8);l=new Uint8Array((h+1)*o);for(let x=0;x<o;x++){let E=x*(h+1)+1;for(let y=0;y<n;y++){let k=i.indices[x*n+y],b=y*u;l[E+(b>>3)]|=k<<8-u-(b&7)}}if(c.push(Qt("IHDR",r)),c.push(Qt("PLTE",Uint8Array.from(i.colors.flatMap(x=>x.slice(0,3))))),i.colors.some(x=>x[3]<255)){let x=i.colors.length;for(;x>0&&i.colors[x-1][3]===255;)x--;c.push(Qt("tRNS",Uint8Array.from(i.colors.slice(0,x).map(E=>E[3]))))}}else{r.set([8,6,0,0,0],8),l=new Uint8Array((n*4+1)*o);for(let u=0;u<o;u++)l.set(e.data.subarray?e.data.subarray(u*n*4,(u+1)*n*4):Array.prototype.slice.call(e.data,u*n*4,(u+1)*n*4),u*(n*4+1)+1);c.push(Qt("IHDR",r))}c.push(Qt("IDAT",await Ka(l))),c.push(Qt("IEND",new Uint8Array(0)));let s=c.reduce((u,h)=>u+h.length,0),d=new Uint8Array(s),f=0;for(let u of c)d.set(u,f),f+=u.length;return d}var Ja=e=>typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement,Qa=e=>typeof VideoFrame<"u"&&e instanceof VideoFrame;async function Ur(e={}){let t=e.backend||"auto",n=null,o=null;if(t!=="cpu"&&typeof document<"u")try{n=await Sr()}catch(s){if(o=s,t==="webgl")throw s}let i=typeof document<"u"?document.createElement("canvas"):null,r={source:null,frame:null},a=Promise.resolve();async function c(s){if(s===r.source&&r.frame&&!Ja(s)&&!Qa(s))return r.frame.dirty=!1,r.frame;let d=await _r(s,{maxSize:e.maxSourceSize,canvas:i});return r={source:s,frame:d},d}async function l(s,d){let f=typeof performance<"u"?performance.now():Date.now(),u=await c(s),h=Ho(d,u),x,E="cpu",y=h.kind==="diffusion"&&(e.diffusion==="cpu"||e.diffusion!=="gpu"&&n&&n.software);n&&u.canvas&&!y?(x=await n.run(h,u),E="webgl"):x=Xo(h,u);let k=(typeof performance<"u"?performance.now():Date.now())-f;return es(h,x,E,k)}return{get backend(){return n?"webgl":"cpu"},get renderer(){return n?n.renderer:""},get fallbackReason(){return o?String(o.message||o):""},process(s,d={}){let f=a.then(()=>l(s,d));return a=f.catch(()=>{}),f},invalidate(){r={source:null,frame:null}},destroy(){n&&n.destroy(),n=null},get shader(){return n?n.shader:null}}}function es(e,t,n="cpu",o=0){return{width:e.width,height:e.height,data:t,palette:e.paletteHex?e.paletteHex.slice():null,settings:e.settings,kind:e.kind,waves:e.waves,crop:{x:e.crop.x/e.srcWidth,y:e.crop.y/e.srcHeight,w:e.crop.w/e.srcWidth,h:e.crop.h/e.srcHeight},backend:n,ms:o,usedColors(){return Pr(this)},toImageData(){return new ImageData(new Uint8ClampedArray(this.data),this.width,this.height)},toCanvas(r=1,a={}){return Rr(this,r,a)},toPNG(r={}){return dt(this,r)},async toBlob(r={}){return new Blob([await dt(this,r)],{type:"image/png"})}}}so();zr();Bt();bt();Rn();var cn=[{id:"balanced",name:"Balanced",description:"Endesga 32, Bayer 4\xD74. A good first look at most photos.",settings:{size:{width:96},palette:{source:"builtin",id:"endesga-32"},dither:{method:"bayer4",strength:.6}}},{id:"game-boy",name:"Game Boy",description:"Four greens, 160 px wide, ordered dither.",settings:{size:{width:160},palette:{source:"builtin",id:"game-boy-dmg"},dither:{method:"bayer4",strength:1},adjust:{contrast:.15}}},{id:"pico-8",name:"PICO-8",description:"128 px, the PICO-8 palette, blue-noise dither.",settings:{size:{width:128},palette:{source:"builtin",id:"pico-8"},dither:{method:"bluenoise",strength:.7}}},{id:"one-bit",name:"1-bit Atkinson",description:"Classic Mac look: two colours, Atkinson diffusion.",settings:{size:{width:192},palette:{source:"builtin",id:"1-bit-monitor"},dither:{method:"atkinson",strength:1},adjust:{contrast:.2}}},{id:"faithful",name:"Faithful colour",description:"Palette extracted from the image, Floyd\u2013Steinberg.",settings:{size:{width:128},palette:{source:"extract",count:24},dither:{method:"floyd-steinberg",strength:.75}}},{id:"sprite",name:"Clean sprite",description:"No dither, nearest resample, orphan cleanup and a dark outline. For art with transparency.",settings:{size:{width:48,resample:"nearest"},palette:{source:"extract",count:12},dither:{method:"none"},cleanup:{orphans:!0},outline:{mode:"outer",color:"#1a1c2c"}}},{id:"cga",name:"CGA",description:"16 hard colours with an 8\xD78 Bayer pattern.",settings:{size:{width:160},palette:{source:"builtin",id:"cga-16"},dither:{method:"bayer8",strength:1}}},{id:"newsprint",name:"Newsprint",description:"Grey clustered-dot halftone.",settings:{size:{width:220},palette:{source:"builtin",id:"grayscale-4"},dither:{method:"cluster8",strength:1},adjust:{saturation:-1}}},{id:"soft",name:"Soft painterly",description:"Resurrect 64 with Sierra Lite and a light smooth.",settings:{size:{width:112},palette:{source:"builtin",id:"resurrect-64"},dither:{method:"sierra-lite",strength:.6},cleanup:{smooth:!0}}}];function m(e,t={},...n){let[o,...i]=e.split("."),r=document.createElement(o||"div");i.length&&(r.className=i.join(" "));for(let[a,c]of Object.entries(t||{}))c==null||c===!1||(a.startsWith("on")&&typeof c=="function"?r.addEventListener(a.slice(2),c):a==="html"?r.innerHTML=c:a==="text"?r.textContent=c:a==="style"&&typeof c=="object"?Object.assign(r.style,c):a==="dataset"?Object.assign(r.dataset,c):a in r&&typeof c!="string"&&a!=="list"?r[a]=c:r.setAttribute(a,c===!0?"":c));return jr(r,n),r}function jr(e,t){for(let n of t.flat(1/0))n==null||n===!1||e.append(n instanceof Node?n:document.createTextNode(String(n)));return e}function tt(e,...t){return e.replaceChildren(),jr(e,t)}var cs=0,ln=(e="itp")=>`${e}-${++cs}`;function Un({accept:e="",multiple:t=!1}={}){return new Promise(n=>{let o=m("input",{type:"file",accept:e,multiple:t,style:{display:"none"}});o.addEventListener("change",()=>{n([...o.files]),o.remove()}),o.addEventListener("cancel",()=>{n([]),o.remove()}),document.body.append(o),o.click()})}var Hr={upload:'<path d="M12 15V4m0 0-4 4m4-4 4 4"/><path d="M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"/>',download:'<path d="M12 4v11m0 0-4-4m4 4 4-4"/><path d="M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"/>',image:'<rect x="3.5" y="4.5" width="17" height="15" rx="2"/><circle cx="9" cy="10" r="1.6"/><path d="m4 17 5-4.5 4 3.5 3-2.5 4 3.5"/>',film:'<rect x="3.5" y="4.5" width="17" height="15" rx="2"/><path d="M7.5 4.5v15M16.5 4.5v15M3.5 9h4M3.5 15h4M16.5 9h4M16.5 15h4"/>',files:'<path d="M8 7V5.5A1.5 1.5 0 0 1 9.5 4H15l4 4v8.5a1.5 1.5 0 0 1-1.5 1.5H16"/><rect x="4.5" y="7" width="11.5" height="13" rx="1.5"/>',presets:'<rect x="4" y="4" width="7" height="7" rx="1.5"/><rect x="13" y="4" width="7" height="7" rx="1.5"/><rect x="4" y="13" width="7" height="7" rx="1.5"/><path d="M16.5 13.5v6M13.5 16.5h6"/>',palette:'<path d="M12 3.5a8.5 8.5 0 1 0 0 17c1.2 0 1.8-.9 1.4-2l-.3-.8c-.4-1.2.5-2.2 1.7-2.2h1.7a4 4 0 0 0 4-4c0-4.4-3.8-8-8.5-8Z"/><circle cx="8" cy="11" r="1"/><circle cx="11" cy="7.5" r="1"/><circle cx="15.5" cy="8.5" r="1"/>',search:'<circle cx="11" cy="11" r="6"/><path d="m20 20-4.5-4.5"/>',x:'<path d="M6 6l12 12M18 6 6 18"/>',plus:'<path d="M12 5v14M5 12h14"/>',minus:'<path d="M5 12h14"/>',chevron:'<path d="m9.5 6 6 6-6 6"/>',chevronDown:'<path d="m6 9.5 6 6 6-6"/>',undo:'<path d="M9 7 4.5 11.5 9 16"/><path d="M5 11.5h9.5a5 5 0 0 1 0 10H11"/>',redo:'<path d="m15 7 4.5 4.5L15 16"/><path d="M19 11.5H9.5a5 5 0 0 0 0 10H13"/>',compare:'<rect x="3.5" y="4.5" width="17" height="15" rx="2"/><path d="M12 2.5v19"/><path d="M15 9.5l2 2.5-2 2.5"/><path d="M9 9.5 7 12l2 2.5"/>',grid:'<rect x="3.5" y="3.5" width="17" height="17" rx="2"/><path d="M9.2 3.5v17M14.8 3.5v17M3.5 9.2h17M3.5 14.8h17"/>',fit:'<path d="M4 9V5.5A1.5 1.5 0 0 1 5.5 4H9M15 4h3.5A1.5 1.5 0 0 1 20 5.5V9M20 15v3.5a1.5 1.5 0 0 1-1.5 1.5H15M9 20H5.5A1.5 1.5 0 0 1 4 18.5V15"/>',zoomIn:'<circle cx="11" cy="11" r="6"/><path d="m20 20-4.5-4.5M11 8.5v5M8.5 11h5"/>',zoomOut:'<circle cx="11" cy="11" r="6"/><path d="m20 20-4.5-4.5M8.5 11h5"/>',sun:'<circle cx="12" cy="12" r="3.5"/><path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6 7 7M17 17l1.4 1.4M5.6 18.4 7 17M17 7l1.4-1.4"/>',moon:'<path d="M19.5 14.5A7.5 7.5 0 0 1 9.5 4.5a7.5 7.5 0 1 0 10 10Z"/>',sidebarLeft:'<rect x="3.5" y="4.5" width="17" height="15" rx="2"/><path d="M9.5 4.5v15"/>',sidebarRight:'<rect x="3.5" y="4.5" width="17" height="15" rx="2"/><path d="M14.5 4.5v15"/>',play:'<path d="M8 5.5v13l10.5-6.5L8 5.5Z"/>',pause:'<path d="M8.5 5.5v13M15.5 5.5v13"/>',stepBack:'<path d="M7 5.5v13M18 6l-8 6 8 6V6Z"/>',stepForward:'<path d="M17 5.5v13M6 6l8 6-8 6V6Z"/>',trash:'<path d="M4.5 7h15M9.5 7V5a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1v2M6.5 7l1 12a1.5 1.5 0 0 0 1.5 1.4h6a1.5 1.5 0 0 0 1.5-1.4l1-12"/>',link:'<path d="M10 14a4 4 0 0 0 5.7 0l2.8-2.8a4 4 0 0 0-5.7-5.7L11.5 6.8"/><path d="M14 10a4 4 0 0 0-5.7 0l-2.8 2.8a4 4 0 0 0 5.7 5.7l1.3-1.3"/>',braces:'<path d="M8.5 4.5H8A2 2 0 0 0 6 6.5v3A2.5 2.5 0 0 1 3.5 12 2.5 2.5 0 0 1 6 14.5v3a2 2 0 0 0 2 2h.5M15.5 4.5h.5a2 2 0 0 1 2 2v3a2.5 2.5 0 0 0 2.5 2.5 2.5 2.5 0 0 0-2.5 2.5v3a2 2 0 0 1-2 2h-.5"/>',pipette:'<path d="m14.5 6.5 3 3M12 9l-7.2 7.2a2 2 0 0 0-.5 1V20h2.8a2 2 0 0 0 1-.5L15.2 12"/><path d="M13 7.5 15.8 4.7a2.3 2.3 0 0 1 3.3 3.3L16.3 10.8 13 7.5Z"/>',check:'<path d="m5 12.5 4.5 4.5L19 7.5"/>',keyboard:'<rect x="2.5" y="6" width="19" height="12" rx="2"/><path d="M6 10h.01M9.5 10h.01M13 10h.01M16.5 10h.01M8 14h8"/>',reset:'<path d="M4.5 12a7.5 7.5 0 1 0 2.2-5.3L4.5 9"/><path d="M4.5 4.5V9H9"/>',sheet:'<rect x="3.5" y="3.5" width="17" height="17" rx="2"/><path d="M3.5 12h17M12 3.5v17"/>',tiles:'<rect x="3.5" y="3.5" width="7" height="7" rx="1"/><rect x="13.5" y="3.5" width="7" height="7" rx="1"/><rect x="3.5" y="13.5" width="7" height="7" rx="1"/><path d="M13.5 17h7M17 13.5v7"/>',zip:'<path d="M6 3.5h8l4.5 4.5v11a1.5 1.5 0 0 1-1.5 1.5H6A1.5 1.5 0 0 1 4.5 19V5A1.5 1.5 0 0 1 6 3.5Z"/><path d="M10 3.5v2h2v2h-2v2h2v2h-2v3"/>',gif:'<rect x="3.5" y="5.5" width="17" height="13" rx="2"/><path d="M10 10.5H8.5a1.5 1.5 0 0 0 0 3H10V12M13 10v4M16 14v-4h2M16 12h1.5"/>',more:'<circle cx="6" cy="12" r="1"/><circle cx="12" cy="12" r="1"/><circle cx="18" cy="12" r="1"/>',menu:'<path d="M4 7h16M4 12h16M4 17h16"/>',sliders:'<path d="M4 7h9M17 7h3M4 17h3M11 17h9"/><circle cx="15" cy="7" r="2"/><circle cx="9" cy="17" r="2"/>',info:'<circle cx="12" cy="12" r="8.5"/><path d="M12 11v5M12 8h.01"/>',unlink:'<path d="M10 14a4 4 0 0 0 5.7 0l2.8-2.8a4 4 0 0 0-5.7-5.7L11.5 6.8"/><path d="M14 10a4 4 0 0 0-5.7 0l-2.8 2.8a4 4 0 0 0 5.7 5.7l1.3-1.3"/><path d="M4 4l16 16"/>',arrowUp:'<path d="M12 19V5M6 11l6-6 6 6"/>',arrowDown:'<path d="M12 5v14M6 13l6 6 6-6"/>',layers:'<path d="m12 4 8.5 4.5L12 13 3.5 8.5 12 4Z"/><path d="m3.5 12.5 8.5 4.5 8.5-4.5"/><path d="m3.5 16.5 8.5 4.5 8.5-4.5"/>',frame:'<path d="M7 3v14a1 1 0 0 0 1 1h13"/><path d="M3 7h13a1 1 0 0 1 1 1v13"/>',copy:'<rect x="8.5" y="8.5" width="11" height="11" rx="1.5"/><path d="M15.5 8.5V6A1.5 1.5 0 0 0 14 4.5H6A1.5 1.5 0 0 0 4.5 6v8A1.5 1.5 0 0 0 6 15.5h2.5"/>',clipboard:'<rect x="5" y="4.5" width="14" height="16" rx="2"/><path d="M9 4.5V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v.5M9 10h6M9 14h4"/>',github:'<path d="M9 19c-4 1.3-4-2-5.5-2.5M14.5 21v-3.2c0-1 .1-1.4-.5-2 2.6-.3 5.5-1.3 5.5-5.8a4.5 4.5 0 0 0-1.2-3.1 4.2 4.2 0 0 0-.1-3.1s-1-.3-3.3 1.2a11.4 11.4 0 0 0-6 0C6.6 3.5 5.6 3.8 5.6 3.8a4.2 4.2 0 0 0-.1 3.1A4.5 4.5 0 0 0 4.3 10c0 4.5 2.9 5.5 5.5 5.8-.6.6-.6 1.2-.5 2V21"/>'};function Y(e,t=""){return`<svg class="i ${t}" viewBox="0 0 24 24" aria-hidden="true" focusable="false">${Hr[e]||""}</svg>`}var Sc=Object.keys(Hr);function Xr(e){let t=et(e),n="shared",o=[],i=[],r=new Map,a=new Set,c=null,l=0,s=200,d=u=>{for(let h of a)h(t,u)},f=(u,h)=>JSON.stringify(u)===JSON.stringify(h);return{get settings(){return t},get target(){return n},subscribe(u){return a.add(u),()=>a.delete(u)},update(u,h={}){let x=Tt(t,u);if(f(x,t))return;let E=Date.now(),y=h.key&&h.key===c&&E-l<1200;h.history!==!1&&!y&&(o.push(t),o.length>s&&o.shift(),i.length=0),c=h.key||null,l=E,t=x,d("update")},replace(u,h="replace"){u=et(u),!f(u,t)&&(o.push(t),i.length=0,c=null,t=u,d(h))},setTarget(u,h){r.set(n,{past:o,future:i}),n=u;let x=r.get(u)||{past:[],future:[]};o=x.past,i=x.future,c=null,t=et(h),d("target")},dropTarget(u){u!==n&&r.delete(u)},commit(){c=null},undo(){return o.length?(i.push(t),t=o.pop(),c=null,d("undo"),!0):!1},redo(){return i.length?(o.push(t),t=i.pop(),c=null,d("redo"),!0):!1},get canUndo(){return o.length>0},get canRedo(){return i.length>0}}}var Vr=[.25,.5,1,2,3,4,6,8,12,16,24,32,48,64];function Wr({onPick:e,onViewChange:t}={}){let n=m("canvas.screen",{role:"img","aria-label":"Preview"}),o=m("span.lbl.l",{text:"Original"}),i=m("span.lbl.r",{text:"Pixel"}),r=m("button",{type:"button","aria-label":"Drag to compare original and result",html:Y("compare")}),a=m("div.itp-split",{hidden:!0},o,i,r),c=m("div.itp-view",{tabindex:"0","aria-label":"Canvas. Scroll to zoom, drag to pan."},n,a),l=n.getContext("2d"),s={result:null,original:null,crop:null,w:0,h:0,x:0,y:0,z:1,fitted:!0,compare:!1,splitAt:.5,grid:!1,picking:!1},d=1,f=0,u=0,h=null,x="";function E(){let v=getComputedStyle(c),I=v.getPropertyValue("--checker-a").trim()||"#1a1b1f",D=v.getPropertyValue("--checker-b").trim()||"#222",U=I+D;if(U===x)return h;let B=document.createElement("canvas");B.width=B.height=16;let H=B.getContext("2d");return H.fillStyle=I,H.fillRect(0,0,16,16),H.fillStyle=D,H.fillRect(0,0,8,8),H.fillRect(8,8,8,8),x=U,h=l.createPattern(B,"repeat"),h}function y(){let v=c.getBoundingClientRect(),I=Math.min(3,window.devicePixelRatio||1);if(Math.abs(v.width-f)<.5&&Math.abs(v.height-u)<.5&&I===d&&n.width>1){A();return}d=I,f=v.width,u=v.height,n.width=Math.max(1,Math.round(f*d)),n.height=Math.max(1,Math.round(u*d)),s.fitted?b(!1):A()}function k(){if(!s.w)return 1;let v=f<600?16:48;return Math.max(.05,Math.min((f-v)/s.w,(u-v)/s.h))}function b(v=!0){s.z=k(),s.x=(f-s.w*s.z)/2,s.y=(u-s.h*s.z)/2,s.fitted=!0,A(),v&&t&&t(z())}function S(v,I=f/2,D=u/2){v=Math.max(.05,Math.min(128,v));let U=(I-s.x)/s.z,B=(D-s.y)/s.z;s.z=v,s.x=I-U*v,s.y=D-B*v,s.fitted=!1,A(),t&&t(z())}function w(v,I,D){let U=s.z,B;v>0?B=Vr.find(H=>H>U+1e-6)||U*1.5:B=[...Vr].reverse().find(H=>H<U-1e-6)||U/1.5,S(B,I,D)}function A(){if(l.setTransform(1,0,0,1,0,0),l.clearRect(0,0,n.width,n.height),!s.result){a.hidden=!0;return}l.setTransform(d,0,0,d,0,0);let v=Math.round(s.x*d)/d,I=Math.round(s.y*d)/d,D=Math.round(s.w*s.z*d)/d,U=Math.round(s.h*s.z*d)/d;if(l.fillStyle=E(),l.fillRect(v,I,D,U),l.imageSmoothingEnabled=!1,l.drawImage(s.result,v,I,D,U),s.compare&&s.original){let B=v+D*s.splitAt;l.save(),l.beginPath(),l.rect(v,I,Math.max(0,B-v),U),l.clip(),l.fillStyle=E(),l.fillRect(v,I,D,U),l.imageSmoothingEnabled=!0,l.imageSmoothingQuality="high";try{let H=s.original.naturalWidth||s.original.videoWidth||s.original.width,V=s.original.naturalHeight||s.original.videoHeight||s.original.height,G=s.crop||{x:0,y:0,w:1,h:1};l.drawImage(s.original,G.x*H,G.y*V,G.w*H,G.h*V,v,I,D,U)}catch{}l.restore(),a.hidden=!1,a.style.left=`${B}px`,a.style.top=`${Math.max(0,I)}px`,a.style.bottom=`${Math.max(0,u-(I+U))}px`}else a.hidden=!0;if(s.grid&&s.z>=6){l.save(),l.beginPath(),l.rect(v,I,D,U),l.clip(),l.strokeStyle="rgba(127,127,127,0.35)",l.lineWidth=1/d,l.beginPath();let B=Math.max(0,Math.floor(-s.x/s.z)),H=Math.min(s.w,Math.ceil((f-s.x)/s.z)),V=Math.max(0,Math.floor(-s.y/s.z)),G=Math.min(s.h,Math.ceil((u-s.y)/s.z));for(let ce=B;ce<=H;ce++){let be=Math.round((v+ce*s.z)*d)/d+.5/d;l.moveTo(be,Math.max(I,0)),l.lineTo(be,Math.min(I+U,u))}for(let ce=V;ce<=G;ce++){let be=Math.round((I+ce*s.z)*d)/d+.5/d;l.moveTo(Math.max(v,0),be),l.lineTo(Math.min(v+D,f),be)}l.stroke(),l.restore()}}let L=null,T=new Map;c.addEventListener("pointerdown",v=>{if(!(v.target===r||r.contains(v.target))&&!(v.target!==c&&v.target!==n)){if(c.focus({preventScroll:!0}),T.set(v.pointerId,{x:v.clientX,y:v.clientY}),c.setPointerCapture(v.pointerId),s.picking&&v.button===0&&T.size===1){let I=c.getBoundingClientRect(),D=(v.clientX-I.left-s.x)/(s.w*s.z),U=(v.clientY-I.top-s.y)/(s.h*s.z);D>=0&&U>=0&&D<1&&U<1&&e&&e(D,U);return}L={x:v.clientX,y:v.clientY,ox:s.x,oy:s.y},c.classList.add("panning")}}),c.addEventListener("pointermove",v=>{if(!T.has(v.pointerId))return;let I=T.get(v.pointerId);if(T.set(v.pointerId,{x:v.clientX,y:v.clientY}),T.size===2){let[D,U]=[...T.values()],B=[...T.entries()].find(([G])=>G!==v.pointerId)[1],H=Math.hypot(I.x-B.x,I.y-B.y),V=Math.hypot(D.x-U.x,D.y-U.y);if(H>0){let G=c.getBoundingClientRect();S(s.z*V/H,(D.x+U.x)/2-G.left,(D.y+U.y)/2-G.top)}L=null;return}L&&(s.x=L.ox+v.clientX-L.x,s.y=L.oy+v.clientY-L.y,s.fitted=!1,A())});let P=v=>{T.delete(v.pointerId),T.size||(L=null,c.classList.remove("panning"),t&&t(z()))};c.addEventListener("pointerup",P),c.addEventListener("pointercancel",P),c.addEventListener("wheel",v=>{v.preventDefault();let I=c.getBoundingClientRect(),D=v.clientX-I.left,U=v.clientY-I.top;if(!v.ctrlKey&&v.deltaMode===0&&Math.abs(v.deltaX)>0){s.x-=v.deltaX,s.y-=v.deltaY,s.fitted=!1,A();return}v.ctrlKey&&v.deltaMode===0?S(s.z*Math.exp(-v.deltaY*.01),D,U):w(v.deltaY<0?1:-1,D,U)},{passive:!1}),c.addEventListener("dblclick",()=>b()),r.addEventListener("pointerdown",v=>{v.preventDefault(),r.setPointerCapture(v.pointerId);let I=U=>{let B=c.getBoundingClientRect();s.splitAt=Math.min(1,Math.max(0,(U.clientX-B.left-s.x)/(s.w*s.z))),A()},D=()=>{r.removeEventListener("pointermove",I),r.removeEventListener("pointerup",D)};r.addEventListener("pointermove",I),r.addEventListener("pointerup",D)}),r.addEventListener("keydown",v=>{(v.key==="ArrowLeft"||v.key==="ArrowRight")&&(v.preventDefault(),v.stopPropagation(),s.splitAt=Math.min(1,Math.max(0,s.splitAt+(v.key==="ArrowLeft"?-.05:.05))),A())}),new ResizeObserver(y).observe(c);let z=()=>({zoom:s.z,fitted:s.fitted,x:s.x,y:s.y});return{el:c,show(v,I,D){let U=!s.result||v.width!==s.w||v.height!==s.h,B={w:s.w*s.z,cx:s.x+s.w*s.z/2,cy:s.y+s.h*s.z/2};if(s.result=v,s.original=I||s.original,s.crop=D||null,U)if(s.w=v.width,s.h=v.height,s.fitted||!B.w)b();else{let H=B.w/s.w;s.z=H,s.x=B.cx-s.w*H/2,s.y=B.cy-s.h*H/2,A(),t&&t(z())}else A()},clear(){s.result=null,s.original=null,s.w=s.h=0,s.fitted=!0,A()},fit:b,zoomTo:S,zoomStep:w,zoomIn(){w(1)},zoomOut(){w(-1)},get zoom(){return s.z},get fitted(){return s.fitted},get rect(){return{x:s.x,y:s.y,width:s.w*s.z,height:s.h*s.z,zoom:s.z}},setCompare(v){s.compare=v,A()},get compare(){return s.compare},setGrid(v){s.grid=v,A()},get grid(){return s.grid},setPicking(v){s.picking=v,c.classList.toggle("picking",v)},get picking(){return s.picking},redraw:A,resize:y}}function qr(e,t={},...n){let o=ln("sec"),i=m("span.hint",{}),r=m("button.itp-sec-toggle",{type:"button","aria-controls":o},m("span.title",{text:e}),i,m("span.chev",{html:Y("chevron")})),a=t.onReset?m("button.itp-btn.small.icon.itp-sec-reset",{type:"button",hidden:!0,title:t.resetLabel||`Reset ${e.toLowerCase()}`,"aria-label":t.resetLabel||`Reset ${e.toLowerCase()} to defaults`,html:Y("reset"),onclick:()=>t.onReset()}):null,c=m("div.body",{id:o},...n),l=m("section.itp-sec",{},m("div.itp-sec-head",{},r,a),c),s=d=>{l.dataset.open=String(d),r.setAttribute("aria-expanded",String(d)),c.hidden=!d};return r.addEventListener("click",()=>{let d=l.dataset.open!=="true";s(d),t.onToggle?.(d)}),s(t.open!==!1),{el:l,body:c,setHint(d){i.textContent=d},setChanged(d){a&&(a.hidden=!d)},setOpen:s,get open(){return l.dataset.open==="true"}}}function wt(e,t,{help:n="",value:o=null,id:i}={}){let r=m("div.lab",{},m("label",{for:i||t.id||null,text:e}),o);return m("div.itp-field",{},r,t,n?m("div.help",{text:n}):null)}function Se(e){let t=ln("sl"),n=e.scale||1,o=e.step||1,i=m("input",{type:"range",id:t,min:e.min*n,max:e.max*n,step:o*n,"aria-label":e.label}),r=m("input.itp-input",{type:"number",min:e.min*n,max:e.max*n,step:o*n,"aria-label":`${e.label} value`}),a=()=>{let s=(i.value-i.min)/(i.max-i.min)*100;i.style.setProperty("--p",`${s}%`)},c=s=>{let d=ls(s*n,o*n);i.value=d,r.value=d,a()};return i.addEventListener("input",()=>{r.value=i.value,a(),e.onInput(Number(i.value)/n)}),i.addEventListener("change",()=>e.onCommit&&e.onCommit()),r.addEventListener("change",()=>{let s=Math.min(e.max*n,Math.max(e.min*n,Number(r.value)||0));c(s/n),e.onInput(s/n),e.onCommit&&e.onCommit()}),i.addEventListener("dblclick",()=>{e.reset!=null&&(c(e.reset),e.onInput(e.reset),e.onCommit&&e.onCommit())}),c(e.value),{el:wt(e.label,m("div.itp-slider",{},i,r),{help:e.help,id:t}),set:c,input:i}}var ls=(e,t)=>{let n=Math.max(0,-Math.floor(Math.log10(t)+1e-9));return Number((Math.round(e/t)*t).toFixed(n))};function jt(e){let t=ln("se"),n=m("select.itp-select",{id:t,"aria-label":e.label}),o=new Map;for(let r of e.options){let a=m("option",{value:r.value,text:r.label});if(r.group){if(!o.has(r.group)){let c=m("optgroup",{label:r.group});o.set(r.group,c),n.append(c)}o.get(r.group).append(a)}else n.append(a)}return n.addEventListener("change",()=>e.onChange(n.value)),{el:e.bare?n:wt(e.label,n,{help:e.help,id:t}),select:n,set(r){n.value=r}}}function Ht(e){let t=e.options.map(r=>m("button",{type:"button","aria-pressed":"false",title:r.title||null,html:(r.icon?Y(r.icon):"")+(r.label?`<span>${r.label}</span>`:""),onclick:()=>e.onChange(r.value)})),n=m("div.itp-seg",{role:"group","aria-label":e.label},...t),o=r=>t.forEach((a,c)=>a.setAttribute("aria-pressed",String(e.options[c].value===r)));return o(e.value),{el:e.bare?n:wt(e.label,n,{help:e.help}),set:o}}function Xt(e){let t=m("input",{type:"checkbox",role:"switch"});t.addEventListener("change",()=>e.onChange(t.checked));let n=m("label.itp-switch",{},m("span",{text:e.label}),t);return{el:e.help?m("div.itp-field",{},n,m("div.help",{text:e.help})):n,set(i){t.checked=!!i}}}function Yr(e){let t=m("input",{type:"color","aria-label":e.label}),n=m("span.mono",{});t.addEventListener("input",()=>{n.textContent=t.value,e.onChange(t.value)});let o=m("label.itp-color",{},t,n),i=r=>{t.value=r,n.textContent=r};return i(e.value||"#000000"),{el:e.bare?o:wt(e.label,o),set:i}}function Vt(e){let t=ln("nu"),n=m("input.itp-input.num",{type:"number",id:t,min:e.min,max:e.max,step:e.step||1,"aria-label":e.label});return n.addEventListener("change",()=>{let o=Math.min(e.max,Math.max(e.min,Number(n.value)||e.min));(n.value!==""||!n.placeholder)&&(n.value=o),e.onChange(o)}),{el:e.bare?n:wt(e.label,n,{help:e.help,id:t}),input:n,set(o){n.value=o}}}Bt();bt();var uo=class{constructor(){this.buf=new Uint8Array(65536),this.n=0}byte(t){if(this.n===this.buf.length){let n=new Uint8Array(this.buf.length*2);n.set(this.buf),this.buf=n}this.buf[this.n++]=t}bytes(t){for(let n=0;n<t.length;n++)this.byte(t[n])}u16(t){this.byte(t&255),this.byte(t>>8&255)}str(t){for(let n=0;n<t.length;n++)this.byte(t.charCodeAt(n))}result(){return this.buf.slice(0,this.n)}};function ds(e,t,n){let o=1<<t,i=o+1,r=t+1,a=i+1,c=new Map,l=0,s=0,d=[],f=[],u=x=>{for(l|=x<<s,s+=r;s>=8;)f.push(l&255),l>>>=8,s-=8,f.length===255&&(d.push(f),f=[])};u(o);let h=e[0];for(let x=1;x<e.length;x++){let E=e[x],y=h*256+E,k=c.get(y);if(k!==void 0){h=k;continue}u(h),a<4096?(c.set(y,a++),a>1<<r&&r<12&&r++):(u(o),c=new Map,r=t+1,a=i+1),h=E}u(h),u(i),s>0&&f.push(l&255),f.length&&d.push(f),n.byte(t);for(let x of d)n.byte(x.length),n.bytes(x);n.byte(0)}var lo=(e,t)=>e[t+3]<128?-1:e[t]<<16|e[t+1]<<8|e[t+2];function Kr(e,t){let n=[...e].filter(c=>c!==-1),o=n.map(c=>[c>>16,c>>8&255,c&255]),i=t?o.length:-1;t&&o.push([0,0,0]);let r=1;for(;1<<r<o.length;)r++;for(;o.length<1<<r;)o.push([0,0,0]);let a=new Map(n.map((c,l)=>[c,l]));return{colors:o,bits:r,tIndex:i,index:a}}function us(e,t){let n=vn(e,t).map(gt),o=new Uint8ClampedArray(e.data),i=new Map;for(let r=0;r<o.length;r+=4){if(o[r+3]<128)continue;let a=o[r]<<16|o[r+1]<<8|o[r+2],c=i.get(a);if(c===void 0){let l=1/0;c=0;for(let s=0;s<n.length;s++){let d=o[r]-n[s][0],f=o[r+1]-n[s][1],u=o[r+2]-n[s][2],h=d*d*3+f*f*4+u*u*2;h<l&&(l=h,c=s)}i.set(a,c)}o.set(n[c],r)}return{...e,data:o}}function Zr(e,t={}){if(!e.length)throw new Error("No frames");let n=Math.max(1,Math.round(t.scale||1)),o=e.map(h=>({...n>1?_t(h,n):h,delay:h.delay??t.delay??100})),i=o[0].width,r=o[0].height,a=!1,c=new Set,l=o.map(h=>{let x=new Set;for(let E=0;E<h.data.length;E+=4){let y=lo(h.data,E);y===-1&&(a=!0),x.add(y),c.add(y)}return x}),s=h=>h.size-(h.has(-1)?1:0),f=s(c)+(a?1:0)<=256?Kr(c,a):null,u=new uo;if(u.str("GIF89a"),u.u16(i),u.u16(r),u.byte(f?240|f.bits-1:0),u.byte(0),u.byte(0),f)for(let h of f.colors)u.bytes(h);return o.length>1&&t.loop!==-1&&(u.byte(33),u.byte(255),u.byte(11),u.str("NETSCAPE2.0"),u.byte(3),u.byte(1),u.u16(t.loop||0),u.byte(0)),o.forEach((h,x)=>{let E=h,y=f,k=l[x];if(!y){let S=a?255:256;if(s(k)>S){E=us(h,S),k=new Set;for(let w=0;w<E.data.length;w+=4)k.add(lo(E.data,w))}y=Kr(k,k.has(-1))}if(u.byte(33),u.byte(249),u.byte(4),u.byte((a?2:1)<<2|(y.tIndex>=0?1:0)),u.u16(Math.max(2,Math.round(E.delay/10))),u.byte(y.tIndex>=0?y.tIndex:0),u.byte(0),u.byte(44),u.u16(0),u.u16(0),u.u16(i),u.u16(r),u.byte(y===f?0:128|y.bits-1),y!==f)for(let S of y.colors)u.bytes(S);let b=new Uint8Array(i*r);for(let S=0;S<b.length;S++){let w=lo(E.data,S*4);b[S]=w===-1?y.tIndex:y.index.get(w)}ds(b,Math.max(2,y.bits),u)}),u.byte(59),u.result()}var Jr=new TextEncoder;function dn(e){let t=[],n=[],o=0,i=new Set;for(let d of e){let f=d.name.replace(/\\/g,"/").replace(/^\/+/,"");if(i.has(f)){let L=/^(.*?)(\.[^.]*)?$/.exec(f),T=2;for(;i.has(`${L[1]}-${T}${L[2]||""}`);)T++;f=`${L[1]}-${T}${L[2]||""}`}i.add(f);let u=Jr.encode(f),h=typeof d.data=="string"?Jr.encode(d.data):d.data,x=An(h),E=d.date||new Date,y=E.getHours()<<11|E.getMinutes()<<5|E.getSeconds()>>1,k=E.getFullYear()-1980<<9|E.getMonth()+1<<5|E.getDate(),b=new Uint8Array(30+u.length),S=new DataView(b.buffer);S.setUint32(0,67324752,!0),S.setUint16(4,20,!0),S.setUint16(6,2048,!0),S.setUint16(8,0,!0),S.setUint16(10,y,!0),S.setUint16(12,k,!0),S.setUint32(14,x,!0),S.setUint32(18,h.length,!0),S.setUint32(22,h.length,!0),S.setUint16(26,u.length,!0),S.setUint16(28,0,!0),b.set(u,30);let w=new Uint8Array(46+u.length),A=new DataView(w.buffer);A.setUint32(0,33639248,!0),A.setUint16(4,20,!0),A.setUint16(6,20,!0),A.setUint16(8,2048,!0),A.setUint16(10,0,!0),A.setUint16(12,y,!0),A.setUint16(14,k,!0),A.setUint32(16,x,!0),A.setUint32(20,h.length,!0),A.setUint32(24,h.length,!0),A.setUint16(28,u.length,!0),A.setUint32(42,o,!0),w.set(u,46),t.push(b,h),n.push(w),o+=b.length+h.length}let r=n.reduce((d,f)=>d+f.length,0),a=new Uint8Array(22),c=new DataView(a.buffer);c.setUint32(0,101010256,!0),c.setUint16(8,e.length,!0),c.setUint16(10,e.length,!0),c.setUint32(12,r,!0),c.setUint32(16,o,!0);let l=new Uint8Array(o+r+22),s=0;for(let d of[...t,...n,a])l.set(d,s),s+=d.length;return l}var fo=(e,t)=>({width:e,height:t,data:new Uint8ClampedArray(e*t*4)});function fs(e,t,n,o,i=0,r=0,a=t.width,c=t.height){for(let l=0;l<c;l++){let s=((r+l)*t.width+i)*4,d=((o+l)*e.width+n)*4;e.data.set(t.data.subarray?t.data.subarray(s,s+a*4):Array.prototype.slice.call(t.data,s,s+a*4),d)}}function po(e,t={}){if(!e.length)throw new Error("No frames");let n=Math.max(0,t.padding|0),o=Math.max(...e.map(u=>u.width)),i=Math.max(...e.map(u=>u.height)),r=Math.max(1,Math.min(e.length,t.columns||Math.ceil(Math.sqrt(e.length)))),a=Math.ceil(e.length/r),c=r*o+(r-1)*n,l=a*i+(a-1)*n,s=fo(c,l),d={};e.forEach((u,h)=>{let x=h%r*(o+n),E=Math.floor(h/r)*(i+n);fs(s,u,x,E),d[u.name||`frame-${String(h).padStart(3,"0")}`]={frame:{x,y:E,w:u.width,h:u.height},sourceSize:{w:u.width,h:u.height},...u.delay!=null?{duration:Math.round(u.delay)}:{}}});let f={frames:d,meta:{app:"image-to-pixel",image:(t.name||"sheet")+".png",size:{w:c,h:l},scale:"1",columns:r,rows:a,padding:n}};return{image:s,atlas:f}}function Qr(e,t={}){let n=Math.max(1,t.tileWidth||8),o=Math.max(1,t.tileHeight||n),i=Math.ceil(e.width/n),r=Math.ceil(e.height/o),a=[],c=new Map,l=[],s=[],d=(x,E)=>{let y=fo(n,o);for(let k=0;k<o;k++)for(let b=0;b<n;b++){let S=x*n+b,w=E*o+k;if(S>=e.width||w>=e.height)continue;let A=(w*e.width+S)*4;y.data.set([e.data[A],e.data[A+1],e.data[A+2],e.data[A+3]],(k*n+b)*4)}return y},f=x=>{let E="";for(let y=0;y<x.data.length;y+=4)E+=x.data[y+3]===0?".":String.fromCharCode(x.data[y]+1,x.data[y+1]+1,x.data[y+2]+1);return E},u=(x,E,y)=>{let k=fo(n,o);for(let b=0;b<o;b++)for(let S=0;S<n;S++){let w=((y?o-1-b:b)*n+(E?n-1-S:S))*4;k.data.set(x.data.subarray(w,w+4),(b*n+S)*4)}return k};for(let x=0;x<r;x++)for(let E=0;E<i;E++){let y=d(E,x),k=c.get(f(y)),b=0;if(k===void 0&&t.flips)for(let[S,w,A]of[[1,0,1],[0,1,2],[1,1,3]]){let L=c.get(f(u(y,S,w)));if(L!==void 0){k=L,b=A;break}}k===void 0&&(k=a.length,a.push(y),c.set(f(y),k)),l.push(k),s.push(b)}return{image:po(a,{columns:t.columns||Math.min(16,a.length)}).image,map:{width:i,height:r,tileWidth:n,tileHeight:o,tiles:l,...t.flips?{flips:s}:{}},count:a.length}}Rn();var ps=null,hs=()=>ps||(ps=document.body.appendChild(m("div.itp-toasts.itp",{role:"status","aria-live":"polite"})));function W(e,t={}){let n=t.kind||"info",o=m("div.msg",{},m("div",{text:e})),i=t.progress?m("div.itp-progress",{},m("i")):null;i&&o.append(i);let r=m(`div.itp-toast.${n}`,{},t.progress?m("div.itp-spinner"):m("span.itp-dot"),o);t.action&&r.append(m("button.itp-btn.small.outline",{type:"button",text:t.action.label,onclick:()=>{t.action.onClick(),c()}})),t.onCancel?r.append(m("button.itp-btn.small",{type:"button",text:"Cancel",onclick:()=>{t.onCancel(),c()}})):r.append(m("button.itp-btn.small.icon",{type:"button","aria-label":"Dismiss",html:Y("x"),onclick:()=>c()})),hs().append(r);let a=null,c=()=>{clearTimeout(a),r.remove()};return(s=>{clearTimeout(a),s&&(a=setTimeout(c,s))})(t.timeout??(t.progress?0:n==="error"?7e3:3200)),{update(s){o.firstChild.textContent=s},progress(s){i&&(i.firstChild.style.width=`${Math.round(s*100)}%`)},close:c,done(s,d="ok"){c(),W(s,{kind:d})}}}var tn=null;function un(e,t,{align:n="end"}={}){Wt();let o=m("div.itp-menu.itp",{role:"menu"});for(let u of t){if(u==="sep"){o.append(m("hr"));continue}if(u.group){o.append(m("div.mlabel",{text:u.group}));continue}let h=m("button.mi",{type:"button",role:"menuitem",disabled:!!u.disabled},m("span",{html:u.icon?Y(u.icon):""}),m("span",{},u.label,u.sub?m("small",{text:u.sub}):null),u.kbd?m("kbd",{text:u.kbd}):m("span"));h.addEventListener("click",()=>{Wt(),u.onClick()}),o.append(h)}document.body.append(o);let i=e.getBoundingClientRect(),r=o.offsetWidth,a=o.offsetHeight,c=n==="end"?i.right-r:i.left;c=Math.max(8,Math.min(c,innerWidth-r-8));let l=i.bottom+6;l+a>innerHeight-8&&(l=Math.max(8,i.top-a-6)),Object.assign(o.style,{left:`${c}px`,top:`${l}px`}),e.setAttribute("aria-expanded","true");let s=[...o.querySelectorAll("button.mi:not(:disabled)")];s[0]?.focus();let d=u=>{let h=s.indexOf(document.activeElement);u.key==="Escape"?(u.preventDefault(),Wt(),e.focus()):u.key==="ArrowDown"?(u.preventDefault(),s[(h+1)%s.length]?.focus()):u.key==="ArrowUp"?(u.preventDefault(),s[(h-1+s.length)%s.length]?.focus()):u.key==="Tab"&&Wt()},f=u=>{!o.contains(u.target)&&u.target!==e&&!e.contains(u.target)&&Wt()};o.addEventListener("keydown",d),setTimeout(()=>document.addEventListener("pointerdown",f,!0)),tn={el:o,anchor:e,cleanup:()=>document.removeEventListener("pointerdown",f,!0)}}function Wt(){tn&&(tn.cleanup(),tn.el.remove(),tn.anchor.setAttribute("aria-expanded","false"),tn=null)}function fn(e,t,{actions:n=[],onClose:o}={}){let i=m("div.content",{},t),r=m("dialog.itp-dialog.itp",{"aria-label":e},m("header",{},m("h2",{text:e}),m("button.itp-btn.icon",{type:"button","aria-label":"Close",html:Y("x"),onclick:()=>r.close()})),i,n.length?m("footer",{},...n.map(a=>m(`button.itp-btn${a.primary?".primary":".outline"}`,{type:"button",text:a.label,onclick:async()=>{await a.onClick?.()!==!1&&r.close()}}))):null);return r.addEventListener("close",()=>{r.remove(),o?.()}),document.body.append(r),r.showModal(),r.body=i,r.setContent=(...a)=>tt(i,...a),r}var At=e=>(e||"image").replace(/\.[^.]+$/,"").replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"")||"image",On=e=>({scale:e.export.scale,grid:e.export.grid,gridColor:e.export.gridColor,indexed:e.export.indexed});function $n(e,t,n){return e.export.size==="source"&&t&&n&&t.crop?{width:Math.max(1,Math.round(t.crop.w*n.width)),height:Math.max(1,Math.round(t.crop.h*n.height))}:{width:t?t.width*e.export.scale:0,height:t?t.height*e.export.scale:0}}var yo=(e,t,n)=>e.export.size==="source"&&n?{...$n(e,t,n),indexed:e.export.indexed}:On(e);function ci(e){let t=()=>e.store.settings;async function n(){if(!e.result)return W("Open an image first",{kind:"error"});let d=t(),f=await dt(e.result,yo(d,e.result,e.current)),u=$n(d,e.result,e.current),h=d.export.size==="source"?`-${u.width}x${u.height}`:d.export.scale>1?`@${d.export.scale}x`:"";Be(f,`${At(e.current.name)}-${e.result.width}x${e.result.height}${h}.png`,"image/png"),W(`Saved ${u.width} \xD7 ${u.height} PNG`,{kind:"ok"})}async function o(){if(e.result)try{let d=await dt(e.result,{...yo(t(),e.result,e.current),indexed:!1});await navigator.clipboard.write([new ClipboardItem({"image/png":new Blob([d],{type:"image/png"})})]),W("Image copied",{kind:"ok"})}catch(d){W(`Couldn't copy: ${d.message}`,{kind:"error"})}}async function i(d,f){let u=new AbortController,h=W(d,{progress:!0,onCancel:()=>u.abort()});e.exporting=!0;try{let x=await f(u.signal,(E,y)=>{h.progress(E),y&&h.update(y)});h.done(x)}catch(x){h.close(),x.name!=="AbortError"?(W(`Export failed: ${x.message}`,{kind:"error"}),console.error(x)):W("Export cancelled")}finally{e.exporting=!1,e.schedule()}}async function r(){let d=e.items.slice();d.length&&await i(`Processing ${d.length} files`,async(f,u)=>{let h=[],x=[];for(let E=0;E<d.length;E++){if(f.aborted)throw new DOMException("Aborted","AbortError");let y=d[E],k=e.settingsFor(y);y.type==="video"&&e.engine.invalidate();let b=await e.engine.process(y.source,k);h.push({name:`${At(y.name)}.png`,data:await dt(b,yo(k,b,y))}),y.own&&x.push({name:`${At(y.name)}.settings.json`,data:Zt(k)}),u((E+1)/d.length,`Processed ${E+1} of ${d.length}`)}return h.push({name:"settings.json",data:Zt(e.shared)},...x),Be(dn(h),"pixel-art.zip","application/zip"),`Saved ${d.length} images as a ZIP`})}async function a(d,f,u,h){let x=t();if(d.source==="files"){let b=e.items.filter(w=>w.type==="image"),S=null;for(let w=0;w<b.length;w++){if(f.aborted)throw new DOMException("Aborted","AbortError");let A=e.settingsFor(b[w]),L=await e.engine.process(b[w].source,S?Tt(A,{size:S}):A);S||(S={mode:"width",width:L.width,height:L.height}),await h(L,w,b.length,b[w].name),u((w+1)/b.length,`Frame ${w+1} of ${b.length}`)}return b.length}let E=e.current;if(!E||E.type!=="video")throw new Error("Open a video first");let y=E.source,k=d.end>d.start?d.end:y.duration;return Ln(y,{fps:d.fps,start:d.start,end:k,signal:f,onFrame:async({index:b,total:S})=>{e.engine.invalidate();let w=await e.engine.process(y,x);await h(w,b,S,`${At(E.name)}-${String(b).padStart(4,"0")}`),u((b+1)/S,`Frame ${b+1} of ${S}`)}})}async function c(d){let f=d.source==="files"?"animation":At(e.current?.name),u=t(),h=1e3/d.fps;if(d.format==="gif"||d.format==="png-seq"){await i("Rendering frames",async(x,E)=>{let y=[];if(await a(d,x,E,async(k,b,S,w)=>{d.format==="gif"?y.push({width:k.width,height:k.height,data:k.data,delay:h}):y.push({name:`${w}.png`,data:await dt(k,On(u))})}),d.format==="gif"){E(1,"Encoding GIF"),await new Promise(b=>setTimeout(b,0));let k=Zr(y,{scale:u.export.scale,loop:0});return Be(k,`${f}.gif`,"image/gif"),`Saved GIF (${y.length} frames, ${(k.length/1024).toFixed(0)} KB)`}return Be(dn(y),`${f}-frames.zip`,"application/zip"),`Saved ${y.length} PNG frames`});return}await i(`Encoding ${d.format.toUpperCase()}`,async(x,E)=>{let{createVideoEncoder:y}=await Promise.resolve().then(()=>(xo(),bo)),k=null;await a(d,x,E,async S=>{k||(k=await y({format:d.format,fps:d.fps,width:S.width,height:S.height,scale:Math.max(u.export.scale,Math.ceil(240/S.height))})),await k.add(S)});let b=await k.finish();return Be(b,`${f}.${d.format}`),`Saved ${d.format.toUpperCase()} (${(b.size/1024/1024).toFixed(1)} MB)`})}async function l(d){let f=d.source==="files"?"sheet":`${At(e.current?.name)}-sheet`,u=t();await i("Building sprite sheet",async(h,x)=>{let E=[];await a(d,h,x,(S,w,A,L)=>{E.push({width:S.width,height:S.height,data:S.data,name:L?At(L):void 0,delay:1e3/d.fps})});let{image:y,atlas:k}=po(E,{columns:d.columns,padding:d.padding,name:f});if(u.export.scale>1){let S=u.export.scale;for(let w of Object.values(k.frames)){for(let A of["x","y","w","h"])w.frame[A]*=S;w.sourceSize.w*=S,w.sourceSize.h*=S}k.meta.size.w*=S,k.meta.size.h*=S,k.meta.scale=String(S)}let b=await dt(y,On(u));return Be(dn([{name:`${f}.png`,data:b},{name:`${f}.json`,data:JSON.stringify(k,null,2)}]),`${f}.zip`,"application/zip"),`Saved a ${E.length}-frame sprite sheet`})}async function s({tile:d,flips:f}){if(!e.result)return W("Open an image first",{kind:"error"});let u=t(),h=Qr(e.result,{tileWidth:d,tileHeight:d,flips:f}),x=`${At(e.current.name)}-tiles`,E=await dt(h.image,On(u)),y={...h.map,image:`${x}.png`,note:"tiles[] holds one tile index per cell, row by row"+(f?"; flips[] is 0 none, 1 horizontal, 2 vertical, 3 both":"")};Be(dn([{name:`${x}.png`,data:E},{name:`${x}.json`,data:JSON.stringify(y,null,2)}]),`${x}.zip`,"application/zip"),W(`Saved ${h.count} unique tiles (${h.map.width} \xD7 ${h.map.height} map)`,{kind:"ok"})}return{exportPNG:n,copyImage:o,exportZip:r,exportAnimation:c,exportSheet:l,exportTileset:s}}var li="itp:";function Pt(e,t){try{let n=localStorage.getItem(li+e);return n==null?t:JSON.parse(n)}catch{return t}}function vt(e,t){try{return localStorage.setItem(li+e,JSON.stringify(t)),!0}catch{return!1}}function ui(e){let{store:t}=e,n=(g,$)=>t.update(g,{key:$}),o=()=>t.commit(),i=()=>t.settings,r=xt(),a=(g,$)=>JSON.stringify(g)===JSON.stringify($),c=Pt("sections",{}),l=(g,$,ee,J,...oe)=>qr($,{open:c[g]??ee,onToggle:re=>{c[g]=re,vt("sections",c)},onReset:J?()=>{let re={};for(let Q of J)re[Q]=JSON.parse(JSON.stringify(r[Q]));t.update(re)}:null},...oe),s=m("div.v",{text:"\u2013"}),d=m("div.v",{text:"\u2013"}),f=m("div.v",{text:"\u2013"}),u=m("div.itp-stats",{"aria-live":"polite"},m("div.itp-stat",{},m("div.k",{text:"Output"}),s),m("div.itp-stat",{},m("div.k",{text:"Colours"}),d),m("div.itp-stat",{},m("div.k",{text:"Render"}),f)),h=m("button",{type:"button",role:"tab","aria-selected":"true",id:"itp-tab-setup","aria-controls":"itp-pane-setup",html:`${Y("sliders")}<span>Setup</span>`}),x=m("button",{type:"button",role:"tab","aria-selected":"false",id:"itp-tab-export","aria-controls":"itp-pane-export",html:`${Y("download")}<span>Export</span>`}),E=m("div.itp-seg",{role:"tablist","aria-label":"Inspector"},h,x),y=Ht({label:"Settings apply to",bare:!0,options:[{value:"shared",label:"All files",icon:"layers"},{value:"own",label:"This file",icon:"unlink"}],value:"shared",onChange:g=>e.current&&e.setOwn(e.current,g==="own")}),k=m("span.itp-scope-note",{}),b=m("div.itp-scope",{hidden:!0},m("div.lab",{},m("span",{text:"Settings apply to"}),k),y.el),S=Ht({label:"Size by",options:[{value:"width",label:"Width"},{value:"block",label:"Pixel size"}],value:"width",onChange:g=>n({size:{mode:g}})}),w=Se({label:"Pixel width",min:8,max:512,step:1,value:96,reset:96,onInput:g=>n({size:{width:g}},"width"),onCommit:o}),A=Vt({label:"Height",min:0,max:2048,help:"Leave empty to keep the aspect ratio.",onChange:g=>n({size:{height:g}})});A.input.placeholder="Auto";let L=Se({label:"Pixel size",min:1,max:64,step:1,value:8,reset:8,help:"How many source pixels become one output pixel.",onInput:g=>n({size:{block:g}},"block"),onCommit:o}),T=Ht({label:"Resample",options:[{value:"box",label:"Average"},{value:"nearest",label:"Nearest"}],value:"box",help:"Nearest keeps hard edges; use it for art that is already pixelated.",onChange:g=>n({size:{resample:g}})}),P=m("button.itp-btn.small.outline",{type:"button",html:`${Y("grid")}<span>Detect grid</span>`,title:"Find the pixel size of upscaled pixel art",onclick:()=>e.detectGrid()}),z=m("div",{style:{display:"contents"}},w.el,A.el),v=m("div",{style:{display:"contents"}},L.el),I=l("size","Size",!0,["size"],S.el,z,v,T.el,m("div.itp-row",{},P)),D=Kt.map(g=>{let $=g.ratio||1.3333333333333333,ee=m("i",{style:{width:`${Math.round($>=1?16:16*$)}px`,height:`${Math.round($>=1?16/$:16)}px`}});return g.ratio||ee.classList.add("orig"),m("button",{type:"button","aria-pressed":"false",title:g.id==="original"?"The source's own shape":`Crop to ${g.label}`,onclick:()=>n({frame:{aspect:g.id}})},ee,m("span",{text:g.label}))}),U=m("div.itp-aspects",{role:"group","aria-label":"Aspect ratio"},...D),B=Se({label:"Zoom",min:1,max:8,step:.05,value:1,reset:1,help:"Crop into the middle of the frame.",onInput:g=>n({frame:{zoom:g}},"fz"),onCommit:o}),H=Se({label:"Horizontal position",min:0,max:1,step:.01,scale:100,value:.5,reset:.5,onInput:g=>n({frame:{x:g}},"fx"),onCommit:o}),V=Se({label:"Vertical position",min:0,max:1,step:.01,scale:100,value:.5,reset:.5,onInput:g=>n({frame:{y:g}},"fy"),onCommit:o}),G=l("frame","Frame",!1,["frame"],wt("Aspect ratio",U),B.el,H.el,V.el),ce=jt({label:"Source",options:[{value:"builtin",label:"Built-in palette"},{value:"custom",label:"Custom colours"},{value:"extract",label:"From the image"},{value:"none",label:"None (keep colours)"}],onChange:g=>n({palette:{source:g}})}),be=jt({label:"Palette",options:nn.map(g=>({value:g.id,label:`${g.name} (${g.colors.length})`})),onChange:g=>n({palette:{source:"builtin",id:g}})}),Te=Se({label:"Number of colours",min:2,max:64,step:1,value:16,reset:16,onInput:g=>n({palette:{count:g}},"count"),onCommit:o}),se=m("div.itp-swatches",{role:"list","aria-label":"Palette colours"}),ae=m("span.val.num",{}),he=wt("Colours",se,{value:ae}),Fe=Ht({label:"Colour matching",options:[{value:"oklab",label:"Perceptual"},{value:"rgb",label:"RGB"}],value:"oklab",onChange:g=>n({palette:{distance:g}})}),Ee=m("div.itp-row",{style:{flexWrap:"wrap"}},m("button.itp-btn.small.outline",{type:"button",html:`${Y("upload")}<span>Import</span>`,title:".gpl, .hex, .pal, .txt or .json",onclick:()=>e.importPalette()}),m("button.itp-btn.small.outline",{type:"button",html:`${Y("palette")}<span>Lospec</span>`,onclick:()=>e.lospecDialog()}),m("button.itp-btn.small.outline",{type:"button",html:`${Y("pipette")}<span>Pick</span>`,title:"Add colours by clicking the image","aria-pressed":"false",onclick:g=>e.togglePicker(g.currentTarget)}),m("button.itp-btn.small",{type:"button",html:`${Y("download")}<span>Save</span>`,title:"Save to Your palettes",onclick:()=>e.savePalette()})),me=l("palette","Palette",!1,["palette"],ce.el,be.el,Te.el,he,Fe.el,Ee),Xe={none:"None",ordered:"Ordered",diffusion:"Error diffusion"},Ve=jt({label:"Method",options:rn.map(g=>({value:g.id,label:g.label,group:Xe[g.kind]})),onChange:g=>n({dither:{method:g}})}),De=Se({label:"Strength",min:0,max:1,step:.01,scale:100,value:.6,reset:.6,onInput:g=>n({dither:{strength:g}},"strength"),onCommit:o}),We=m("textarea.itp-input",{rows:4,spellcheck:!1,"aria-label":"Custom threshold matrix",placeholder:`0 8 2 10
|
|
301
|
+
`;var un=(e,t)=>{let n=document.createElement("canvas");return n.width=e,n.height=t,n};async function Gr(){if(typeof document>"u")throw new Error("No DOM");let e=un(1,1).getContext("webgl2");if(!e)throw new Error("WebGL 2 is not available");if(!e.getExtension("EXT_color_buffer_float"))throw new Error("Float render targets are not available");let t=e.getExtension("WEBGL_debug_renderer_info"),n=String(t?e.getParameter(t.UNMASKED_RENDERER_WEBGL):e.getParameter(e.RENDERER));e.getExtension("WEBGL_lose_context")?.loseContext();let o=un(1,1),i=un(1,1),r=un(256,1),a=un(1,1),c=x=>({element:x,filter:"nearest",wrap:"clamp"}),u=Ur({canvas:o,webgl:2,size:[1,1],pixelRatio:1,autoplay:!1,pauseWhenHidden:!1,pointer:!1,errorOverlay:!1,warnMissingUniforms:!1,preserveDrawingBuffer:!0,premultipliedAlpha:!1,antialias:!1,dialect:"shadermate",common:Ir,samplers:{u_palette:c(r),u_matrix:c(a)},uniforms:{u_count:1,u_distance:0,u_resample:0,u_adjust:[0,0,0,1],u_hue:0,u_crop:[0,0,1,1],u_alphaCut:.5,u_mode:0,u_levels:1,u_amount:0,u_skew:1,u_strength:1,u_kn:0,u_kernel:new Float32Array(no*3),u_outline:0,u_corners:0,u_outlineColor:[0,0,0]},passes:[{name:"prep",shader:Or,float:"full",filter:"nearest",channels:[{...c(i),dynamic:!1}]},{name:"quant",shader:Dr,filter:"nearest",channels:["prep"]},{name:"diffuse",shader:Fr,float:"full",filter:"nearest",pingpong:!0,iterations:2,channels:["prep","diffuse"]},{name:"resolve",shader:$r,filter:"nearest",channels:["quant","diffuse"]},{name:"orphan",shader:zr,filter:"nearest",channels:["resolve"]},{name:"smooth",shader:Br,filter:"nearest",channels:["orphan"]},{name:"out",shader:Nr,screen:!0,channels:["smooth"]}]}),s=null;if(u.on("error",x=>{s=x}),await u.ready,s||u.error)throw u.destroy(),s||u.error;let l=(x,S)=>{for(let b in S)u.set(b,S[b],x)},p=null,f="",h="";async function y(x){if(x.canvas===p&&!x.dirty)return;i.width=x.width,i.height=x.height;let S=i.getContext("2d");S.clearRect(0,0,i.width,i.height),S.drawImage(x.canvas,0,0),await u.setChannel(0,{...c(i),dynamic:!1},"prep"),p=x.canvas}function E(x){let S=x.palette.map(L=>L.join(",")).join(";");if(S===f)return;f=S;let b=r.getContext("2d"),_=b.createImageData(256,1);x.palette.forEach((L,P)=>_.data.set([L[0],L[1],L[2],255],P*4)),b.putImageData(_,0,0)}function v(x){let S=x?`${x.w}x${x.h}:${x.levels}:${x.values.join(",")}`:"none";if(S===h)return;h=S;let b=x||{w:1,h:1,values:[0]};a.width=b.w,a.height=b.h;let _=a.getContext("2d"),L=_.createImageData(b.w,b.h);for(let P=0;P<b.values.length;P++)L.data.set([b.values[P],0,0,255],P*4);_.putImageData(L,0,0)}async function M(x,S){let b=x.settings;await y(S),x.quantize&&E(x),v(x.map),(u.width!==x.width||u.height!==x.height)&&u.setSize(x.width,x.height);let _=x.kind==="diffusion",L=new Array(no).fill(null).map((F,I)=>x.kernel&&x.kernel[I]||[0,0,0]);u.set({u_count:x.palette.length||1,u_distance:x.distance,u_resample:b.size.resample==="nearest"?1:0,u_adjust:[b.adjust.brightness,b.adjust.contrast,b.adjust.saturation,b.adjust.gamma],u_hue:b.adjust.hue,u_crop:[x.crop.x,x.crop.y,x.crop.w,x.crop.h],u_alphaCut:b.alpha.threshold,u_mode:x.quantize?x.kind==="ordered"?2:1:0,u_levels:x.map?x.map.levels:1,u_amount:x.map?x.spread*b.dither.strength:0,u_skew:x.skew,u_strength:b.dither.strength,u_kn:x.kernel?x.kernel.length:0,u_kernel:new Float32Array(L.flat()),u_outline:{none:0,outer:1,inner:2}[x.outline.mode],u_corners:x.outline.corners?1:0,u_outlineColor:x.outline.color.map(F=>F/255)}),l("diffuse",{u_on:_?1:0}),l("resolve",{u_on:_?1:0}),l("orphan",{u_on:b.cleanup.orphans?1:0}),l("smooth",{u_on:b.cleanup.smooth?1:0}),u.getPass("diffuse").cfg.iterations=_?x.waves:1;let{data:P}=u.readPixels(),R=x.width,j=x.height,C=new Uint8ClampedArray(R*j*4),D=R*4;for(let F=0;F<j;F++)C.set(P.subarray((j-1-F)*D,(j-F)*D),F*D);return C}return{name:"webgl",renderer:n,software:/swiftshader|llvmpipe|softpipe|software|basic render/i.test(n),run:M,shader:u,destroy(){u.destroy()}}}var ho=typeof document<"u",jr=e=>e&&typeof e=="object"&&"data"in e&&"width"in e&&"height"in e&&e.data&&e.data.length===e.width*e.height*4;async function ys(e){if(typeof Blob<"u"&&e instanceof Blob){if(typeof createImageBitmap=="function")try{return await createImageBitmap(e)}catch{}e=URL.createObjectURL(e)}if(!ho)throw new Error("Loading images by URL needs a browser; pass { width, height, data } in Node.");let t=new Image;return t.crossOrigin="anonymous",t.decoding="async",t.src=e,await t.decode(),t}function xs(e){return{width:e.naturalWidth||e.videoWidth||e.displayWidth||e.codedWidth||e.width||0,height:e.naturalHeight||e.videoHeight||e.displayHeight||e.codedHeight||e.height||0}}function ws(e){if(e&&!jr(e)&&typeof e=="object"){if(e.canvas&&typeof e.canvas=="object"&&"getContext"in e.canvas)return e.canvas;if(e.elt&&typeof e.elt=="object"&&"getContext"in e.elt)return e.elt}return e}async function Hr(e,t={}){let n=t.maxSize||4096,o=ws(e);if((typeof o=="string"||typeof Blob<"u"&&o instanceof Blob)&&(o=await ys(o)),o&&typeof o.complete=="boolean"&&!o.complete&&o.decode&&await o.decode(),jr(o)){let l={width:o.width,height:o.height,data:o.data,canvas:null};return ho&&Object.defineProperty(l,"canvas",{configurable:!0,get(){let p=document.createElement("canvas");p.width=o.width,p.height=o.height;let f=new ImageData(new Uint8ClampedArray(o.data),o.width,o.height);return p.getContext("2d").putImageData(f,0,0),Object.defineProperty(l,"canvas",{value:p}),p}}),l}if(!ho)throw new Error("Unsupported source in a non-browser environment. Pass { width, height, data }.");let{width:i,height:r}=xs(o);if(!i||!r)throw new Error("Source has no size yet (is the image or video loaded?)");let a=Math.min(1,n/Math.max(i,r));i=Math.max(1,Math.round(i*a)),r=Math.max(1,Math.round(r*a));let c=t.canvas||document.createElement("canvas");c.width=i,c.height=r;let u=c.getContext("2d",{willReadFrequently:!0});u.clearRect(0,0,i,r),u.imageSmoothingEnabled=a<1,u.imageSmoothingQuality="high",u.drawImage(o,0,0,i,r);let s=null;return{width:i,height:r,canvas:c,dirty:!0,get data(){return s||(s=u.getImageData(0,0,i,r).data)}}}Vt();Vt();function qr(e,t=1,n={}){let o=t>1||n.grid?Rt(e,t,n):e,i=n.canvas||document.createElement("canvas");return i.width=o.width,i.height=o.height,i.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(o.data),o.width,o.height),0,0),i}function We(e,t,n="application/octet-stream"){let o=e instanceof Blob?e:new Blob([e],{type:n}),i=URL.createObjectURL(o),r=document.createElement("a");r.href=i,r.download=t,r.rel="noopener",document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(i),1e4)}var Un=null;function In(e,t=0){if(!Un){Un=new Uint32Array(256);for(let n=0;n<256;n++){let o=n;for(let i=0;i<8;i++)o=o&1?3988292384^o>>>1:o>>>1;Un[n]=o>>>0}}t=~t>>>0;for(let n=0;n<e.length;n++)t=Un[(t^e[n])&255]^t>>>8;return~t>>>0}Vt();var vs=[137,80,78,71,13,10,26,10];async function Es(e){if(typeof CompressionStream=="function"){let n=new CompressionStream("deflate"),o=new Blob([e]).stream().pipeThrough(n);return new Uint8Array(await new Response(o).arrayBuffer())}let{deflateSync:t}=await import("node:zlib");return new Uint8Array(t(e))}function tn(e,t){let n=new Uint8Array(12+t.length),o=new DataView(n.buffer);o.setUint32(0,t.length);for(let i=0;i<4;i++)n[4+i]=e.charCodeAt(i);return n.set(t,8),o.setUint32(8+t.length,In(n.subarray(4,8+t.length))),n}function ks(e){let t=e.data,n=e.width*e.height,o=new Map,i=[],r=new Uint8Array(n);for(let a=0;a<n;a++){let c=a*4,u=t[c+3]===0?-1:(t[c]<<24|t[c+1]<<16|t[c+2]<<8|t[c+3])>>>0,s=o.get(u);if(s===void 0){if(i.length===256)return null;s=i.length,o.set(u,s),i.push(u===-1?[0,0,0,0]:[t[c],t[c+1],t[c+2],t[c+3]])}r[a]=s}return{colors:i,indices:r}}async function ft(e,t={}){t.width&&t.height?e=Vr(e,t.width,t.height):(t.scale&&t.scale>1||t.grid)&&(e=Rt(e,t.scale||1,t));let{width:n,height:o}=e,i=t.indexed===!1?null:ks(e),r=new Uint8Array(13),a=new DataView(r.buffer);a.setUint32(0,n),a.setUint32(4,o);let c=[new Uint8Array(vs)],u;if(i){let f=i.colors.length<=2?1:i.colors.length<=4?2:i.colors.length<=16?4:8;r.set([f,3,0,0,0],8);let h=Math.ceil(n*f/8);u=new Uint8Array((h+1)*o);for(let y=0;y<o;y++){let E=y*(h+1)+1;for(let v=0;v<n;v++){let M=i.indices[y*n+v],x=v*f;u[E+(x>>3)]|=M<<8-f-(x&7)}}if(c.push(tn("IHDR",r)),c.push(tn("PLTE",Uint8Array.from(i.colors.flatMap(y=>y.slice(0,3))))),i.colors.some(y=>y[3]<255)){let y=i.colors.length;for(;y>0&&i.colors[y-1][3]===255;)y--;c.push(tn("tRNS",Uint8Array.from(i.colors.slice(0,y).map(E=>E[3]))))}}else{r.set([8,6,0,0,0],8),u=new Uint8Array((n*4+1)*o);for(let f=0;f<o;f++)u.set(e.data.subarray?e.data.subarray(f*n*4,(f+1)*n*4):Array.prototype.slice.call(e.data,f*n*4,(f+1)*n*4),f*(n*4+1)+1);c.push(tn("IHDR",r))}c.push(tn("IDAT",await Es(u))),c.push(tn("IEND",new Uint8Array(0)));let s=c.reduce((f,h)=>f+h.length,0),l=new Uint8Array(s),p=0;for(let f of c)l.set(f,p),p+=f.length;return l}var Ms=e=>typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement,Cs=e=>typeof VideoFrame<"u"&&e instanceof VideoFrame;async function Yr(e={}){let t=e.backend||"auto",n=null,o=null;if(t!=="cpu"&&typeof document<"u")try{n=await Gr()}catch(s){if(o=s,t==="webgl")throw s}let i=typeof document<"u"?document.createElement("canvas"):null,r={source:null,frame:null},a=Promise.resolve();async function c(s){if(s===r.source&&r.frame&&!Ms(s)&&!Cs(s))return r.frame.dirty=!1,r.frame;let l=await Hr(s,{maxSize:e.maxSourceSize,canvas:i});return r={source:s,frame:l},l}async function u(s,l){let p=typeof performance<"u"?performance.now():Date.now(),f=await c(s),h=ar(l,f),y,E="cpu",v=h.kind==="diffusion"&&(e.diffusion==="cpu"||e.diffusion!=="gpu"&&n&&n.software);n&&f.canvas&&!v?(y=await n.run(h,f),E="webgl"):y=sr(h,f);let M=(typeof performance<"u"?performance.now():Date.now())-p;return Ss(h,y,E,M)}return{get backend(){return n?"webgl":"cpu"},get renderer(){return n?n.renderer:""},get fallbackReason(){return o?String(o.message||o):""},process(s,l={}){let p=a.then(()=>u(s,l));return a=p.catch(()=>{}),p},invalidate(){r={source:null,frame:null}},destroy(){n&&n.destroy(),n=null},get shader(){return n?n.shader:null}}}function Ss(e,t,n="cpu",o=0){return{width:e.width,height:e.height,data:t,palette:e.paletteHex?e.paletteHex.slice():null,settings:e.settings,kind:e.kind,waves:e.waves,crop:{x:e.crop.x/e.srcWidth,y:e.crop.y/e.srcHeight,w:e.crop.w/e.srcWidth,h:e.crop.h/e.srcHeight},backend:n,ms:o,usedColors(){return Xr(this)},toImageData(){return new ImageData(new Uint8ClampedArray(this.data),this.width,this.height)},toCanvas(r=1,a={}){return qr(this,r,a)},toPNG(r={}){return ft(this,r)},async toBlob(r={}){return new Blob([await ft(this,r)],{type:"image/png"})}}}bo();ti();Vt();vt();Fn();var dn=[{id:"balanced",name:"Balanced",description:"Endesga 32, Bayer 4\xD74. A good first look at most photos.",settings:{size:{width:96},palette:{source:"builtin",id:"endesga-32"},dither:{method:"bayer4",strength:.6}}},{id:"game-boy",name:"Game Boy",description:"Four greens, 160 px wide, ordered dither.",settings:{size:{width:160},palette:{source:"builtin",id:"game-boy-dmg"},dither:{method:"bayer4",strength:1},adjust:{contrast:.15}}},{id:"pico-8",name:"PICO-8",description:"128 px, the PICO-8 palette, blue-noise dither.",settings:{size:{width:128},palette:{source:"builtin",id:"pico-8"},dither:{method:"bluenoise",strength:.7}}},{id:"one-bit",name:"1-bit Atkinson",description:"Classic Mac look: two colours, Atkinson diffusion.",settings:{size:{width:192},palette:{source:"builtin",id:"1-bit-monitor"},dither:{method:"atkinson",strength:1},adjust:{contrast:.2}}},{id:"faithful",name:"Faithful colour",description:"Palette extracted from the image, Floyd\u2013Steinberg.",settings:{size:{width:128},palette:{source:"extract",count:24},dither:{method:"floyd-steinberg",strength:.75}}},{id:"sprite",name:"Clean sprite",description:"No dither, nearest resample, orphan cleanup and a dark outline. For art with transparency.",settings:{size:{width:48,resample:"nearest"},palette:{source:"extract",count:12},dither:{method:"none"},cleanup:{orphans:!0},outline:{mode:"outer",color:"#1a1c2c"}}},{id:"cga",name:"CGA",description:"16 hard colours with an 8\xD78 Bayer pattern.",settings:{size:{width:160},palette:{source:"builtin",id:"cga-16"},dither:{method:"bayer8",strength:1}}},{id:"newsprint",name:"Newsprint",description:"Grey clustered-dot halftone.",settings:{size:{width:220},palette:{source:"builtin",id:"grayscale-4"},dither:{method:"cluster8",strength:1},adjust:{saturation:-1}}},{id:"soft",name:"Soft painterly",description:"Resurrect 64 with Sierra Lite and a light smooth.",settings:{size:{width:112},palette:{source:"builtin",id:"resurrect-64"},dither:{method:"sierra-lite",strength:.6},cleanup:{smooth:!0}}}];function m(e,t={},...n){let[o,...i]=e.split("."),r=document.createElement(o||"div");i.length&&(r.className=i.join(" "));for(let[a,c]of Object.entries(t||{}))c==null||c===!1||(a.startsWith("on")&&typeof c=="function"?r.addEventListener(a.slice(2),c):a==="html"?r.innerHTML=c:a==="text"?r.textContent=c:a==="style"&&typeof c=="object"?Object.assign(r.style,c):a==="dataset"?Object.assign(r.dataset,c):a in r&&typeof c!="string"&&a!=="list"?r[a]=c:r.setAttribute(a,c===!0?"":c));return ai(r,n),r}function ai(e,t){for(let n of t.flat(1/0))n==null||n===!1||e.append(n instanceof Node?n:document.createTextNode(String(n)));return e}function st(e,...t){return e.replaceChildren(),ai(e,t)}var Is=0,fn=(e="itp")=>`${e}-${++Is}`;function $n({accept:e="",multiple:t=!1}={}){return new Promise(n=>{let o=m("input",{type:"file",accept:e,multiple:t,style:{display:"none"}});o.addEventListener("change",()=>{n([...o.files]),o.remove()}),o.addEventListener("cancel",()=>{n([]),o.remove()}),document.body.append(o),o.click()})}var si={upload:'<path d="M12 15V4m0 0-4 4m4-4 4 4"/><path d="M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"/>',download:'<path d="M12 4v11m0 0-4-4m4 4 4-4"/><path d="M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"/>',image:'<rect x="3.5" y="4.5" width="17" height="15" rx="2"/><circle cx="9" cy="10" r="1.6"/><path d="m4 17 5-4.5 4 3.5 3-2.5 4 3.5"/>',film:'<rect x="3.5" y="4.5" width="17" height="15" rx="2"/><path d="M7.5 4.5v15M16.5 4.5v15M3.5 9h4M3.5 15h4M16.5 9h4M16.5 15h4"/>',files:'<path d="M8 7V5.5A1.5 1.5 0 0 1 9.5 4H15l4 4v8.5a1.5 1.5 0 0 1-1.5 1.5H16"/><rect x="4.5" y="7" width="11.5" height="13" rx="1.5"/>',presets:'<rect x="4" y="4" width="7" height="7" rx="1.5"/><rect x="13" y="4" width="7" height="7" rx="1.5"/><rect x="4" y="13" width="7" height="7" rx="1.5"/><path d="M16.5 13.5v6M13.5 16.5h6"/>',palette:'<path d="M12 3.5a8.5 8.5 0 1 0 0 17c1.2 0 1.8-.9 1.4-2l-.3-.8c-.4-1.2.5-2.2 1.7-2.2h1.7a4 4 0 0 0 4-4c0-4.4-3.8-8-8.5-8Z"/><circle cx="8" cy="11" r="1"/><circle cx="11" cy="7.5" r="1"/><circle cx="15.5" cy="8.5" r="1"/>',search:'<circle cx="11" cy="11" r="6"/><path d="m20 20-4.5-4.5"/>',x:'<path d="M6 6l12 12M18 6 6 18"/>',plus:'<path d="M12 5v14M5 12h14"/>',minus:'<path d="M5 12h14"/>',chevron:'<path d="m9.5 6 6 6-6 6"/>',chevronDown:'<path d="m6 9.5 6 6 6-6"/>',undo:'<path d="M9 7 4.5 11.5 9 16"/><path d="M5 11.5h9.5a5 5 0 0 1 0 10H11"/>',redo:'<path d="m15 7 4.5 4.5L15 16"/><path d="M19 11.5H9.5a5 5 0 0 0 0 10H13"/>',compare:'<rect x="3.5" y="4.5" width="17" height="15" rx="2"/><path d="M12 2.5v19"/><path d="M15 9.5l2 2.5-2 2.5"/><path d="M9 9.5 7 12l2 2.5"/>',grid:'<rect x="3.5" y="3.5" width="17" height="17" rx="2"/><path d="M9.2 3.5v17M14.8 3.5v17M3.5 9.2h17M3.5 14.8h17"/>',fit:'<path d="M4 9V5.5A1.5 1.5 0 0 1 5.5 4H9M15 4h3.5A1.5 1.5 0 0 1 20 5.5V9M20 15v3.5a1.5 1.5 0 0 1-1.5 1.5H15M9 20H5.5A1.5 1.5 0 0 1 4 18.5V15"/>',zoomIn:'<circle cx="11" cy="11" r="6"/><path d="m20 20-4.5-4.5M11 8.5v5M8.5 11h5"/>',zoomOut:'<circle cx="11" cy="11" r="6"/><path d="m20 20-4.5-4.5M8.5 11h5"/>',sun:'<circle cx="12" cy="12" r="3.5"/><path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6 7 7M17 17l1.4 1.4M5.6 18.4 7 17M17 7l1.4-1.4"/>',moon:'<path d="M19.5 14.5A7.5 7.5 0 0 1 9.5 4.5a7.5 7.5 0 1 0 10 10Z"/>',sidebarLeft:'<rect x="3.5" y="4.5" width="17" height="15" rx="2"/><path d="M9.5 4.5v15"/>',sidebarRight:'<rect x="3.5" y="4.5" width="17" height="15" rx="2"/><path d="M14.5 4.5v15"/>',play:'<path d="M8 5.5v13l10.5-6.5L8 5.5Z"/>',pause:'<path d="M8.5 5.5v13M15.5 5.5v13"/>',stepBack:'<path d="M7 5.5v13M18 6l-8 6 8 6V6Z"/>',stepForward:'<path d="M17 5.5v13M6 6l8 6-8 6V6Z"/>',save:'<path d="M5 4.5h11l3.5 3.5v10A1.5 1.5 0 0 1 18 19.5H6A1.5 1.5 0 0 1 4.5 18V6A1.5 1.5 0 0 1 6 4.5Z"/><path d="M8 4.5v4h7v-4M8 19.5v-6h8v6"/>',rename:'<path d="M4 20h4L19 9l-4-4L4 16v4Z"/><path d="m13.5 6.5 4 4"/>',volume:'<path d="M4 9.5h3.5L12 6v12l-4.5-3.5H4z"/><path d="M15.5 9.5a3.5 3.5 0 0 1 0 5M18 7a7 7 0 0 1 0 10"/>',volumeOff:'<path d="M4 9.5h3.5L12 6v12l-4.5-3.5H4z"/><path d="m16 9.5 5 5M21 9.5l-5 5"/>',trash:'<path d="M4.5 7h15M9.5 7V5a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1v2M6.5 7l1 12a1.5 1.5 0 0 0 1.5 1.4h6a1.5 1.5 0 0 0 1.5-1.4l1-12"/>',link:'<path d="M10 14a4 4 0 0 0 5.7 0l2.8-2.8a4 4 0 0 0-5.7-5.7L11.5 6.8"/><path d="M14 10a4 4 0 0 0-5.7 0l-2.8 2.8a4 4 0 0 0 5.7 5.7l1.3-1.3"/>',braces:'<path d="M8.5 4.5H8A2 2 0 0 0 6 6.5v3A2.5 2.5 0 0 1 3.5 12 2.5 2.5 0 0 1 6 14.5v3a2 2 0 0 0 2 2h.5M15.5 4.5h.5a2 2 0 0 1 2 2v3a2.5 2.5 0 0 0 2.5 2.5 2.5 2.5 0 0 0-2.5 2.5v3a2 2 0 0 1-2 2h-.5"/>',pipette:'<path d="m14.5 6.5 3 3M12 9l-7.2 7.2a2 2 0 0 0-.5 1V20h2.8a2 2 0 0 0 1-.5L15.2 12"/><path d="M13 7.5 15.8 4.7a2.3 2.3 0 0 1 3.3 3.3L16.3 10.8 13 7.5Z"/>',check:'<path d="m5 12.5 4.5 4.5L19 7.5"/>',keyboard:'<rect x="2.5" y="6" width="19" height="12" rx="2"/><path d="M6 10h.01M9.5 10h.01M13 10h.01M16.5 10h.01M8 14h8"/>',reset:'<path d="M4.5 12a7.5 7.5 0 1 0 2.2-5.3L4.5 9"/><path d="M4.5 4.5V9H9"/>',sheet:'<rect x="3.5" y="3.5" width="17" height="17" rx="2"/><path d="M3.5 12h17M12 3.5v17"/>',tiles:'<rect x="3.5" y="3.5" width="7" height="7" rx="1"/><rect x="13.5" y="3.5" width="7" height="7" rx="1"/><rect x="3.5" y="13.5" width="7" height="7" rx="1"/><path d="M13.5 17h7M17 13.5v7"/>',zip:'<path d="M6 3.5h8l4.5 4.5v11a1.5 1.5 0 0 1-1.5 1.5H6A1.5 1.5 0 0 1 4.5 19V5A1.5 1.5 0 0 1 6 3.5Z"/><path d="M10 3.5v2h2v2h-2v2h2v2h-2v3"/>',gif:'<rect x="3.5" y="5.5" width="17" height="13" rx="2"/><path d="M10 10.5H8.5a1.5 1.5 0 0 0 0 3H10V12M13 10v4M16 14v-4h2M16 12h1.5"/>',more:'<circle cx="6" cy="12" r="1"/><circle cx="12" cy="12" r="1"/><circle cx="18" cy="12" r="1"/>',menu:'<path d="M4 7h16M4 12h16M4 17h16"/>',sliders:'<path d="M4 7h9M17 7h3M4 17h3M11 17h9"/><circle cx="15" cy="7" r="2"/><circle cx="9" cy="17" r="2"/>',info:'<circle cx="12" cy="12" r="8.5"/><path d="M12 11v5M12 8h.01"/>',unlink:'<path d="M10 14a4 4 0 0 0 5.7 0l2.8-2.8a4 4 0 0 0-5.7-5.7L11.5 6.8"/><path d="M14 10a4 4 0 0 0-5.7 0l-2.8 2.8a4 4 0 0 0 5.7 5.7l1.3-1.3"/><path d="M4 4l16 16"/>',arrowUp:'<path d="M12 19V5M6 11l6-6 6 6"/>',arrowDown:'<path d="M12 5v14M6 13l6 6 6-6"/>',layers:'<path d="m12 4 8.5 4.5L12 13 3.5 8.5 12 4Z"/><path d="m3.5 12.5 8.5 4.5 8.5-4.5"/><path d="m3.5 16.5 8.5 4.5 8.5-4.5"/>',frame:'<path d="M7 3v14a1 1 0 0 0 1 1h13"/><path d="M3 7h13a1 1 0 0 1 1 1v13"/>',copy:'<rect x="8.5" y="8.5" width="11" height="11" rx="1.5"/><path d="M15.5 8.5V6A1.5 1.5 0 0 0 14 4.5H6A1.5 1.5 0 0 0 4.5 6v8A1.5 1.5 0 0 0 6 15.5h2.5"/>',clipboard:'<rect x="5" y="4.5" width="14" height="16" rx="2"/><path d="M9 4.5V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v.5M9 10h6M9 14h4"/>',github:'<path d="M9 19c-4 1.3-4-2-5.5-2.5M14.5 21v-3.2c0-1 .1-1.4-.5-2 2.6-.3 5.5-1.3 5.5-5.8a4.5 4.5 0 0 0-1.2-3.1 4.2 4.2 0 0 0-.1-3.1s-1-.3-3.3 1.2a11.4 11.4 0 0 0-6 0C6.6 3.5 5.6 3.8 5.6 3.8a4.2 4.2 0 0 0-.1 3.1A4.5 4.5 0 0 0 4.3 10c0 4.5 2.9 5.5 5.5 5.8-.6.6-.6 1.2-.5 2V21"/>'};function Q(e,t=""){return`<svg class="i ${t}" viewBox="0 0 24 24" aria-hidden="true" focusable="false">${si[e]||""}</svg>`}var ll=Object.keys(si);function ci(e){let t=at(e),n="shared",o=[],i=[],r=new Map,a=new Set,c=null,u=0,s=200,l=f=>{for(let h of a)h(t,f)},p=(f,h)=>JSON.stringify(f)===JSON.stringify(h);return{get settings(){return t},get target(){return n},subscribe(f){return a.add(f),()=>a.delete(f)},update(f,h={}){let y=Lt(t,f);if(p(y,t))return;let E=Date.now(),v=h.key&&h.key===c&&E-u<1200;h.history!==!1&&!v&&(o.push(t),o.length>s&&o.shift(),i.length=0),c=h.key||null,u=E,t=y,l("update")},replace(f,h="replace"){f=at(f),!p(f,t)&&(o.push(t),i.length=0,c=null,t=f,l(h))},setTarget(f,h){r.set(n,{past:o,future:i}),n=f;let y=r.get(f)||{past:[],future:[]};o=y.past,i=y.future,c=null,t=at(h),l("target")},dropTarget(f){f!==n&&r.delete(f)},commit(){c=null},undo(){return o.length?(i.push(t),t=o.pop(),c=null,l("undo"),!0):!1},redo(){return i.length?(o.push(t),t=i.pop(),c=null,l("redo"),!0):!1},get canUndo(){return o.length>0},get canRedo(){return i.length>0}}}var li=[.25,.5,1,2,3,4,6,8,12,16,24,32,48,64];function ui({onPick:e,onViewChange:t}={}){let n=m("canvas.screen",{role:"img","aria-label":"Preview"}),o=m("span.lbl.l",{text:"Original"}),i=m("span.lbl.r",{text:"Pixel"}),r=m("button",{type:"button","aria-label":"Drag to compare original and result",html:Q("compare")}),a=m("div.itp-split",{hidden:!0},o,i,r),c=m("div.itp-view",{tabindex:"0","aria-label":"Canvas. Scroll to zoom, drag to pan."},n,a),u=n.getContext("2d"),s={result:null,original:null,crop:null,w:0,h:0,x:0,y:0,z:1,fitted:!0,compare:!1,splitAt:.5,grid:!1,picking:!1},l=1,p=0,f=0,h=null,y="";function E(){let C=getComputedStyle(c),D=C.getPropertyValue("--checker-a").trim()||"#1a1b1f",F=C.getPropertyValue("--checker-b").trim()||"#222",I=D+F;if(I===y)return h;let N=document.createElement("canvas");N.width=N.height=16;let z=N.getContext("2d");return z.fillStyle=D,z.fillRect(0,0,16,16),z.fillStyle=F,z.fillRect(0,0,8,8),z.fillRect(8,8,8,8),y=I,h=u.createPattern(N,"repeat"),h}function v(){let C=c.getBoundingClientRect(),D=Math.min(3,window.devicePixelRatio||1);if(Math.abs(C.width-p)<.5&&Math.abs(C.height-f)<.5&&D===l&&n.width>1){_();return}l=D,p=C.width,f=C.height,n.width=Math.max(1,Math.round(p*l)),n.height=Math.max(1,Math.round(f*l)),s.fitted?x(!1):_()}function M(){if(!s.w)return 1;let C=p<600?16:48;return Math.max(.05,Math.min((p-C)/s.w,(f-C)/s.h))}function x(C=!0){s.z=M(),s.x=(p-s.w*s.z)/2,s.y=(f-s.h*s.z)/2,s.fitted=!0,_(),C&&t&&t(j())}function S(C,D=p/2,F=f/2){C=Math.max(.05,Math.min(128,C));let I=(D-s.x)/s.z,N=(F-s.y)/s.z;s.z=C,s.x=D-I*C,s.y=F-N*C,s.fitted=!1,_(),t&&t(j())}function b(C,D,F){let I=s.z,N;C>0?N=li.find(z=>z>I+1e-6)||I*1.5:N=[...li].reverse().find(z=>z<I-1e-6)||I/1.5,S(N,D,F)}function _(){if(u.setTransform(1,0,0,1,0,0),u.clearRect(0,0,n.width,n.height),!s.result){a.hidden=!0;return}u.setTransform(l,0,0,l,0,0);let C=Math.round(s.x*l)/l,D=Math.round(s.y*l)/l,F=Math.round(s.w*s.z*l)/l,I=Math.round(s.h*s.z*l)/l;if(u.fillStyle=E(),u.fillRect(C,D,F,I),u.imageSmoothingEnabled=!1,u.drawImage(s.result,C,D,F,I),s.compare&&s.original){let N=C+F*s.splitAt;u.save(),u.beginPath(),u.rect(C,D,Math.max(0,N-C),I),u.clip(),u.fillStyle=E(),u.fillRect(C,D,F,I),u.imageSmoothingEnabled=!0,u.imageSmoothingQuality="high";try{let z=s.original.naturalWidth||s.original.videoWidth||s.original.width,se=s.original.naturalHeight||s.original.videoHeight||s.original.height,de=s.crop||{x:0,y:0,w:1,h:1};u.drawImage(s.original,de.x*z,de.y*se,de.w*z,de.h*se,C,D,F,I)}catch{}u.restore(),a.hidden=!1,a.style.left=`${N}px`,a.style.top=`${Math.max(0,D)}px`,a.style.bottom=`${Math.max(0,f-(D+I))}px`}else a.hidden=!0;if(s.grid&&s.z>=6){u.save(),u.beginPath(),u.rect(C,D,F,I),u.clip(),u.strokeStyle="rgba(127,127,127,0.35)",u.lineWidth=1/l,u.beginPath();let N=Math.max(0,Math.floor(-s.x/s.z)),z=Math.min(s.w,Math.ceil((p-s.x)/s.z)),se=Math.max(0,Math.floor(-s.y/s.z)),de=Math.min(s.h,Math.ceil((f-s.y)/s.z));for(let oe=N;oe<=z;oe++){let ee=Math.round((C+oe*s.z)*l)/l+.5/l;u.moveTo(ee,Math.max(D,0)),u.lineTo(ee,Math.min(D+I,f))}for(let oe=se;oe<=de;oe++){let ee=Math.round((D+oe*s.z)*l)/l+.5/l;u.moveTo(Math.max(C,0),ee),u.lineTo(Math.min(C+F,p),ee)}u.stroke(),u.restore()}}let L=null,P=new Map;c.addEventListener("pointerdown",C=>{if(!(C.target===r||r.contains(C.target))&&!(C.target!==c&&C.target!==n)){if(c.focus({preventScroll:!0}),P.set(C.pointerId,{x:C.clientX,y:C.clientY}),c.setPointerCapture(C.pointerId),s.picking&&C.button===0&&P.size===1){let D=c.getBoundingClientRect(),F=(C.clientX-D.left-s.x)/(s.w*s.z),I=(C.clientY-D.top-s.y)/(s.h*s.z);F>=0&&I>=0&&F<1&&I<1&&e&&e(F,I);return}L={x:C.clientX,y:C.clientY,ox:s.x,oy:s.y},c.classList.add("panning")}}),c.addEventListener("pointermove",C=>{if(!P.has(C.pointerId))return;let D=P.get(C.pointerId);if(P.set(C.pointerId,{x:C.clientX,y:C.clientY}),P.size===2){let[F,I]=[...P.values()],N=[...P.entries()].find(([de])=>de!==C.pointerId)[1],z=Math.hypot(D.x-N.x,D.y-N.y),se=Math.hypot(F.x-I.x,F.y-I.y);if(z>0){let de=c.getBoundingClientRect();S(s.z*se/z,(F.x+I.x)/2-de.left,(F.y+I.y)/2-de.top)}L=null;return}L&&(s.x=L.ox+C.clientX-L.x,s.y=L.oy+C.clientY-L.y,s.fitted=!1,_())});let R=C=>{P.delete(C.pointerId),P.size||(L=null,c.classList.remove("panning"),t&&t(j()))};c.addEventListener("pointerup",R),c.addEventListener("pointercancel",R),c.addEventListener("wheel",C=>{C.preventDefault();let D=c.getBoundingClientRect(),F=C.clientX-D.left,I=C.clientY-D.top;if(!C.ctrlKey&&C.deltaMode===0&&Math.abs(C.deltaX)>0){s.x-=C.deltaX,s.y-=C.deltaY,s.fitted=!1,_();return}C.ctrlKey&&C.deltaMode===0?S(s.z*Math.exp(-C.deltaY*.01),F,I):b(C.deltaY<0?1:-1,F,I)},{passive:!1}),c.addEventListener("dblclick",()=>x()),r.addEventListener("pointerdown",C=>{C.preventDefault(),r.setPointerCapture(C.pointerId);let D=I=>{let N=c.getBoundingClientRect();s.splitAt=Math.min(1,Math.max(0,(I.clientX-N.left-s.x)/(s.w*s.z))),_()},F=()=>{r.removeEventListener("pointermove",D),r.removeEventListener("pointerup",F)};r.addEventListener("pointermove",D),r.addEventListener("pointerup",F)}),r.addEventListener("keydown",C=>{(C.key==="ArrowLeft"||C.key==="ArrowRight")&&(C.preventDefault(),C.stopPropagation(),s.splitAt=Math.min(1,Math.max(0,s.splitAt+(C.key==="ArrowLeft"?-.05:.05))),_())}),new ResizeObserver(v).observe(c);let j=()=>({zoom:s.z,fitted:s.fitted,x:s.x,y:s.y});return{el:c,show(C,D,F){let I=!s.result||C.width!==s.w||C.height!==s.h,N={w:s.w*s.z,cx:s.x+s.w*s.z/2,cy:s.y+s.h*s.z/2};if(s.result=C,s.original=D||s.original,s.crop=F||null,I)if(s.w=C.width,s.h=C.height,s.fitted||!N.w)x();else{let z=N.w/s.w;s.z=z,s.x=N.cx-s.w*z/2,s.y=N.cy-s.h*z/2,_(),t&&t(j())}else _()},clear(){s.result=null,s.original=null,s.w=s.h=0,s.fitted=!0,_()},fit:x,zoomTo:S,zoomStep:b,zoomIn(){b(1)},zoomOut(){b(-1)},get zoom(){return s.z},get fitted(){return s.fitted},get rect(){return{x:s.x,y:s.y,width:s.w*s.z,height:s.h*s.z,zoom:s.z}},setCompare(C){s.compare=C,_()},get compare(){return s.compare},setGrid(C){s.grid=C,_()},get grid(){return s.grid},setPicking(C){s.picking=C,c.classList.toggle("picking",C)},get picking(){return s.picking},redraw:_,resize:v}}function di(e,t={},...n){let o=fn("sec"),i=m("span.hint",{}),r=m("button.itp-sec-toggle",{type:"button","aria-controls":o},m("span.title",{text:e}),i,m("span.chev",{html:Q("chevron")})),a=t.onReset?m("button.itp-btn.small.icon.itp-sec-reset",{type:"button",hidden:!0,title:t.resetLabel||`Reset ${e.toLowerCase()}`,"aria-label":t.resetLabel||`Reset ${e.toLowerCase()} to defaults`,html:Q("reset"),onclick:()=>t.onReset()}):null,c=m("div.body",{id:o},...n),u=m("section.itp-sec",{},m("div.itp-sec-head",{},r,a),c),s=l=>{u.dataset.open=String(l),r.setAttribute("aria-expanded",String(l)),c.hidden=!l};return r.addEventListener("click",()=>{let l=u.dataset.open!=="true";s(l),t.onToggle?.(l)}),s(t.open!==!1),{el:u,body:c,setHint(l){i.textContent=l},setChanged(l){a&&(a.hidden=!l)},setOpen:s,get open(){return u.dataset.open==="true"}}}function Mt(e,t,{help:n="",value:o=null,id:i}={}){let r=m("div.lab",{},m("label",{for:i||t.id||null,text:e}),o);return m("div.itp-field",{},r,t,n?m("div.help",{text:n}):null)}function Oe(e){let t=fn("sl"),n=e.scale||1,o=e.step||1,i=m("input",{type:"range",id:t,min:e.min*n,max:e.max*n,step:o*n,"aria-label":e.label}),r=m("input.itp-input",{type:"number",min:e.min*n,max:e.max*n,step:o*n,"aria-label":`${e.label} value`}),a=()=>{let s=(i.value-i.min)/(i.max-i.min)*100;i.style.setProperty("--p",`${s}%`)},c=s=>{let l=Os(s*n,o*n);i.value=l,r.value=l,a()};return i.addEventListener("input",()=>{r.value=i.value,a(),e.onInput(Number(i.value)/n)}),i.addEventListener("change",()=>e.onCommit&&e.onCommit()),r.addEventListener("change",()=>{let s=Math.min(e.max*n,Math.max(e.min*n,Number(r.value)||0));c(s/n),e.onInput(s/n),e.onCommit&&e.onCommit()}),i.addEventListener("dblclick",()=>{e.reset!=null&&(c(e.reset),e.onInput(e.reset),e.onCommit&&e.onCommit())}),c(e.value),{el:Mt(e.label,m("div.itp-slider",{},i,r),{help:e.help,id:t}),set:c,input:i}}var Os=(e,t)=>{let n=Math.max(0,-Math.floor(Math.log10(t)+1e-9));return Number((Math.round(e/t)*t).toFixed(n))};function Ut(e){let t=fn("se"),n=m("select.itp-select",{id:t,"aria-label":e.label}),o=new Map;for(let r of e.options){let a=m("option",{value:r.value,text:r.label});if(r.group){if(!o.has(r.group)){let c=m("optgroup",{label:r.group});o.set(r.group,c),n.append(c)}o.get(r.group).append(a)}else n.append(a)}return n.addEventListener("change",()=>e.onChange(n.value)),{el:e.bare?n:Mt(e.label,n,{help:e.help,id:t}),select:n,set(r){n.value=r}}}function Wt(e){let t=e.options.map(r=>m("button",{type:"button","aria-pressed":"false",title:r.title||null,html:(r.icon?Q(r.icon):"")+(r.label?`<span>${r.label}</span>`:""),onclick:()=>e.onChange(r.value)})),n=m("div.itp-seg",{role:"group","aria-label":e.label},...t),o=r=>t.forEach((a,c)=>a.setAttribute("aria-pressed",String(e.options[c].value===r)));return o(e.value),{el:e.bare?n:Mt(e.label,n,{help:e.help}),set:o}}function It(e){let t=m("input",{type:"checkbox",role:"switch"});t.addEventListener("change",()=>e.onChange(t.checked));let n=m("label.itp-switch",{},m("span",{text:e.label}),t);return{el:e.help?m("div.itp-field",{},n,m("div.help",{text:e.help})):n,set(i){t.checked=!!i}}}function fi(e){let t=m("input",{type:"color","aria-label":e.label}),n=m("span.mono",{});t.addEventListener("input",()=>{n.textContent=t.value,e.onChange(t.value)});let o=m("label.itp-color",{},t,n),i=r=>{t.value=r,n.textContent=r};return i(e.value||"#000000"),{el:e.bare?o:Mt(e.label,o),set:i}}function qt(e){let t=fn("nu"),n=m("input.itp-input.num",{type:"number",id:t,min:e.min,max:e.max,step:e.step||1,"aria-label":e.label});return n.addEventListener("change",()=>{let o=Math.min(e.max,Math.max(e.min,Number(n.value)||e.min));(n.value!==""||!n.placeholder)&&(n.value=o),e.onChange(o)}),{el:e.bare?n:Mt(e.label,n,{help:e.help,id:t}),input:n,set(o){n.value=o}}}Vt();vt();var wo=class{constructor(){this.buf=new Uint8Array(65536),this.n=0}byte(t){if(this.n===this.buf.length){let n=new Uint8Array(this.buf.length*2);n.set(this.buf),this.buf=n}this.buf[this.n++]=t}bytes(t){for(let n=0;n<t.length;n++)this.byte(t[n])}u16(t){this.byte(t&255),this.byte(t>>8&255)}str(t){for(let n=0;n<t.length;n++)this.byte(t.charCodeAt(n))}result(){return this.buf.slice(0,this.n)}};function Ds(e,t,n){let o=1<<t,i=o+1,r=t+1,a=i+1,c=new Map,u=0,s=0,l=[],p=[],f=y=>{for(u|=y<<s,s+=r;s>=8;)p.push(u&255),u>>>=8,s-=8,p.length===255&&(l.push(p),p=[])};f(o);let h=e[0];for(let y=1;y<e.length;y++){let E=e[y],v=h*256+E,M=c.get(v);if(M!==void 0){h=M;continue}f(h),a<4096?(c.set(v,a++),a>1<<r&&r<12&&r++):(f(o),c=new Map,r=t+1,a=i+1),h=E}f(h),f(i),s>0&&p.push(u&255),p.length&&l.push(p),n.byte(t);for(let y of l)n.byte(y.length),n.bytes(y);n.byte(0)}var xo=(e,t)=>e[t+3]<128?-1:e[t]<<16|e[t+1]<<8|e[t+2];function pi(e,t){let n=[...e].filter(c=>c!==-1),o=n.map(c=>[c>>16,c>>8&255,c&255]),i=t?o.length:-1;t&&o.push([0,0,0]);let r=1;for(;1<<r<o.length;)r++;for(;o.length<1<<r;)o.push([0,0,0]);let a=new Map(n.map((c,u)=>[c,u]));return{colors:o,bits:r,tIndex:i,index:a}}function Fs(e,t){let n=Sn(e,t).map(wt),o=new Uint8ClampedArray(e.data),i=new Map;for(let r=0;r<o.length;r+=4){if(o[r+3]<128)continue;let a=o[r]<<16|o[r+1]<<8|o[r+2],c=i.get(a);if(c===void 0){let u=1/0;c=0;for(let s=0;s<n.length;s++){let l=o[r]-n[s][0],p=o[r+1]-n[s][1],f=o[r+2]-n[s][2],h=l*l*3+p*p*4+f*f*2;h<u&&(u=h,c=s)}i.set(a,c)}o.set(n[c],r)}return{...e,data:o}}function hi(e,t={}){if(!e.length)throw new Error("No frames");let n=Math.max(1,Math.round(t.scale||1)),o=e.map(h=>({...n>1?Rt(h,n):h,delay:h.delay??t.delay??100})),i=o[0].width,r=o[0].height,a=!1,c=new Set,u=o.map(h=>{let y=new Set;for(let E=0;E<h.data.length;E+=4){let v=xo(h.data,E);v===-1&&(a=!0),y.add(v),c.add(v)}return y}),s=h=>h.size-(h.has(-1)?1:0),p=s(c)+(a?1:0)<=256?pi(c,a):null,f=new wo;if(f.str("GIF89a"),f.u16(i),f.u16(r),f.byte(p?240|p.bits-1:0),f.byte(0),f.byte(0),p)for(let h of p.colors)f.bytes(h);return o.length>1&&t.loop!==-1&&(f.byte(33),f.byte(255),f.byte(11),f.str("NETSCAPE2.0"),f.byte(3),f.byte(1),f.u16(t.loop||0),f.byte(0)),o.forEach((h,y)=>{let E=h,v=p,M=u[y];if(!v){let S=a?255:256;if(s(M)>S){E=Fs(h,S),M=new Set;for(let b=0;b<E.data.length;b+=4)M.add(xo(E.data,b))}v=pi(M,M.has(-1))}if(f.byte(33),f.byte(249),f.byte(4),f.byte((a?2:1)<<2|(v.tIndex>=0?1:0)),f.u16(Math.max(2,Math.round(E.delay/10))),f.byte(v.tIndex>=0?v.tIndex:0),f.byte(0),f.byte(44),f.u16(0),f.u16(0),f.u16(i),f.u16(r),f.byte(v===p?0:128|v.bits-1),v!==p)for(let S of v.colors)f.bytes(S);let x=new Uint8Array(i*r);for(let S=0;S<x.length;S++){let b=xo(E.data,S*4);x[S]=b===-1?v.tIndex:v.index.get(b)}Ds(x,Math.max(2,v.bits),f)}),f.byte(59),f.result()}var mi=new TextEncoder;function pn(e){let t=[],n=[],o=0,i=new Set;for(let l of e){let p=l.name.replace(/\\/g,"/").replace(/^\/+/,"");if(i.has(p)){let L=/^(.*?)(\.[^.]*)?$/.exec(p),P=2;for(;i.has(`${L[1]}-${P}${L[2]||""}`);)P++;p=`${L[1]}-${P}${L[2]||""}`}i.add(p);let f=mi.encode(p),h=typeof l.data=="string"?mi.encode(l.data):l.data,y=In(h),E=l.date||new Date,v=E.getHours()<<11|E.getMinutes()<<5|E.getSeconds()>>1,M=E.getFullYear()-1980<<9|E.getMonth()+1<<5|E.getDate(),x=new Uint8Array(30+f.length),S=new DataView(x.buffer);S.setUint32(0,67324752,!0),S.setUint16(4,20,!0),S.setUint16(6,2048,!0),S.setUint16(8,0,!0),S.setUint16(10,v,!0),S.setUint16(12,M,!0),S.setUint32(14,y,!0),S.setUint32(18,h.length,!0),S.setUint32(22,h.length,!0),S.setUint16(26,f.length,!0),S.setUint16(28,0,!0),x.set(f,30);let b=new Uint8Array(46+f.length),_=new DataView(b.buffer);_.setUint32(0,33639248,!0),_.setUint16(4,20,!0),_.setUint16(6,20,!0),_.setUint16(8,2048,!0),_.setUint16(10,0,!0),_.setUint16(12,v,!0),_.setUint16(14,M,!0),_.setUint32(16,y,!0),_.setUint32(20,h.length,!0),_.setUint32(24,h.length,!0),_.setUint16(28,f.length,!0),_.setUint32(42,o,!0),b.set(f,46),t.push(x,h),n.push(b),o+=x.length+h.length}let r=n.reduce((l,p)=>l+p.length,0),a=new Uint8Array(22),c=new DataView(a.buffer);c.setUint32(0,101010256,!0),c.setUint16(8,e.length,!0),c.setUint16(10,e.length,!0),c.setUint32(12,r,!0),c.setUint32(16,o,!0);let u=new Uint8Array(o+r+22),s=0;for(let l of[...t,...n,a])u.set(l,s),s+=l.length;return u}var vo=(e,t)=>({width:e,height:t,data:new Uint8ClampedArray(e*t*4)});function $s(e,t,n,o,i=0,r=0,a=t.width,c=t.height){for(let u=0;u<c;u++){let s=((r+u)*t.width+i)*4,l=((o+u)*e.width+n)*4;e.data.set(t.data.subarray?t.data.subarray(s,s+a*4):Array.prototype.slice.call(t.data,s,s+a*4),l)}}function Eo(e,t={}){if(!e.length)throw new Error("No frames");let n=Math.max(0,t.padding|0),o=Math.max(...e.map(f=>f.width)),i=Math.max(...e.map(f=>f.height)),r=Math.max(1,Math.min(e.length,t.columns||Math.ceil(Math.sqrt(e.length)))),a=Math.ceil(e.length/r),c=r*o+(r-1)*n,u=a*i+(a-1)*n,s=vo(c,u),l={};e.forEach((f,h)=>{let y=h%r*(o+n),E=Math.floor(h/r)*(i+n);$s(s,f,y,E),l[f.name||`frame-${String(h).padStart(3,"0")}`]={frame:{x:y,y:E,w:f.width,h:f.height},sourceSize:{w:f.width,h:f.height},...f.delay!=null?{duration:Math.round(f.delay)}:{}}});let p={frames:l,meta:{app:"image-to-pixel",image:(t.name||"sheet")+".png",size:{w:c,h:u},scale:"1",columns:r,rows:a,padding:n}};return{image:s,atlas:p}}function gi(e,t={}){let n=Math.max(1,t.tileWidth||8),o=Math.max(1,t.tileHeight||n),i=Math.ceil(e.width/n),r=Math.ceil(e.height/o),a=[],c=new Map,u=[],s=[],l=(y,E)=>{let v=vo(n,o);for(let M=0;M<o;M++)for(let x=0;x<n;x++){let S=y*n+x,b=E*o+M;if(S>=e.width||b>=e.height)continue;let _=(b*e.width+S)*4;v.data.set([e.data[_],e.data[_+1],e.data[_+2],e.data[_+3]],(M*n+x)*4)}return v},p=y=>{let E="";for(let v=0;v<y.data.length;v+=4)E+=y.data[v+3]===0?".":String.fromCharCode(y.data[v]+1,y.data[v+1]+1,y.data[v+2]+1);return E},f=(y,E,v)=>{let M=vo(n,o);for(let x=0;x<o;x++)for(let S=0;S<n;S++){let b=((v?o-1-x:x)*n+(E?n-1-S:S))*4;M.data.set(y.data.subarray(b,b+4),(x*n+S)*4)}return M};for(let y=0;y<r;y++)for(let E=0;E<i;E++){let v=l(E,y),M=c.get(p(v)),x=0;if(M===void 0&&t.flips)for(let[S,b,_]of[[1,0,1],[0,1,2],[1,1,3]]){let L=c.get(p(f(v,S,b)));if(L!==void 0){M=L,x=_;break}}M===void 0&&(M=a.length,a.push(v),c.set(p(v),M)),u.push(M),s.push(x)}return{image:Eo(a,{columns:t.columns||Math.min(16,a.length)}).image,map:{width:i,height:r,tileWidth:n,tileHeight:o,tiles:u,...t.flips?{flips:s}:{}},count:a.length}}Fn();var zs=null,Bs=()=>zs||(zs=document.body.appendChild(m("div.itp-toasts.itp",{role:"status","aria-live":"polite"})));function Z(e,t={}){let n=t.kind||"info",o=m("div.msg",{},m("div",{text:e})),i=t.progress?m("div.itp-progress",{},m("i")):null;i&&o.append(i);let r=m(`div.itp-toast.${n}`,{},t.progress?m("div.itp-spinner"):m("span.itp-dot"),o);t.action&&r.append(m("button.itp-btn.small.outline",{type:"button",text:t.action.label,onclick:()=>{t.action.onClick(),c()}})),t.onCancel?r.append(m("button.itp-btn.small",{type:"button",text:"Cancel",onclick:()=>{t.onCancel(),c()}})):r.append(m("button.itp-btn.small.icon",{type:"button","aria-label":"Dismiss",html:Q("x"),onclick:()=>c()})),Bs().append(r);let a=null,c=()=>{clearTimeout(a),r.remove()};return(s=>{clearTimeout(a),s&&(a=setTimeout(c,s))})(t.timeout??(t.progress?0:n==="error"?7e3:3200)),{update(s){o.firstChild.textContent=s},progress(s){i&&(i.firstChild.style.width=`${Math.round(s*100)}%`)},close:c,done(s,l="ok"){c(),Z(s,{kind:l})}}}var on=null;function hn(e,t,{align:n="end"}={}){Yt();let o=m("div.itp-menu.itp",{role:"menu"});for(let f of t){if(f==="sep"){o.append(m("hr"));continue}if(f.group){o.append(m("div.mlabel",{text:f.group}));continue}let h=m("button.mi",{type:"button",role:"menuitem",disabled:!!f.disabled},m("span",{html:f.icon?Q(f.icon):""}),m("span",{},f.label,f.sub?m("small",{text:f.sub}):null),f.kbd?m("kbd",{text:f.kbd}):m("span"));h.addEventListener("click",()=>{Yt(),f.onClick()}),o.append(h)}document.body.append(o);let i=e.getBoundingClientRect(),r=o.offsetWidth,a=o.offsetHeight,c=n==="end"?i.right-r:i.left;c=Math.max(8,Math.min(c,innerWidth-r-8));let u=i.bottom+6;u+a>innerHeight-8&&(u=Math.max(8,i.top-a-6)),Object.assign(o.style,{left:`${c}px`,top:`${u}px`}),e.setAttribute("aria-expanded","true");let s=[...o.querySelectorAll("button.mi:not(:disabled)")];s[0]?.focus();let l=f=>{let h=s.indexOf(document.activeElement);f.key==="Escape"?(f.preventDefault(),Yt(),e.focus()):f.key==="ArrowDown"?(f.preventDefault(),s[(h+1)%s.length]?.focus()):f.key==="ArrowUp"?(f.preventDefault(),s[(h-1+s.length)%s.length]?.focus()):f.key==="Tab"&&Yt()},p=f=>{!o.contains(f.target)&&f.target!==e&&!e.contains(f.target)&&Yt()};o.addEventListener("keydown",l),setTimeout(()=>document.addEventListener("pointerdown",p,!0)),on={el:o,anchor:e,cleanup:()=>document.removeEventListener("pointerdown",p,!0)}}function Yt(){on&&(on.cleanup(),on.el.remove(),on.anchor.setAttribute("aria-expanded","false"),on=null)}function mn(e,t,{actions:n=[],onClose:o}={}){let i=m("div.content",{},t),r=m("dialog.itp-dialog.itp",{"aria-label":e},m("header",{},m("h2",{text:e}),m("button.itp-btn.icon",{type:"button","aria-label":"Close",html:Q("x"),onclick:()=>r.close()})),i,n.length?m("footer",{},...n.map(a=>m(`button.itp-btn${a.primary?".primary":".outline"}`,{type:"button",text:a.label,onclick:async()=>{await a.onClick?.()!==!1&&r.close()}}))):null);return r.addEventListener("close",()=>{r.remove(),o?.()}),document.body.append(r),r.showModal(),r.body=i,r.setContent=(...a)=>st(i,...a),r}var Dt=e=>(e||"image").replace(/\.[^.]+$/,"").replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"")||"image",Vn=e=>({scale:e.export.scale,grid:e.export.grid,gridColor:e.export.gridColor,indexed:e.export.indexed});function Xn(e,t,n){return e.export.size==="source"&&t&&n&&t.crop?{width:Math.max(1,Math.round(t.crop.w*n.width)),height:Math.max(1,Math.round(t.crop.h*n.height))}:{width:t?t.width*e.export.scale:0,height:t?t.height*e.export.scale:0}}var Io=(e,t,n)=>e.export.size==="source"&&n?{...Xn(e,t,n),indexed:e.export.indexed}:Vn(e);function tc(e,t,n=4){let o=Math.max(1,Math.ceil(240/Math.min(t.width,t.height))),i=c=>{let u=Math.round(c*16/9),s=t.height>t.width,l=s?c:u,p=s?u:c;return Math.max(o,Math.min(Math.floor(l/t.width),Math.floor(p/t.height)))},r=e==="scale"?Math.max(o,n):i(Number(e)||1080);return[r,i(1080),i(720),o].filter((c,u,s)=>c<=r&&s.indexOf(c)===u).sort((c,u)=>u-c)}function Pi(e){let t=()=>e.store.settings;async function n(){if(!e.result)return Z("Open an image first",{kind:"error"});let l=t(),p=await ft(e.result,Io(l,e.result,e.current)),f=Xn(l,e.result,e.current),h=l.export.size==="source"?`-${f.width}x${f.height}`:l.export.scale>1?`@${l.export.scale}x`:"";We(p,`${Dt(e.current.name)}-${e.result.width}x${e.result.height}${h}.png`,"image/png"),Z(`Saved ${f.width} \xD7 ${f.height} PNG`,{kind:"ok"})}async function o(){if(e.result)try{let l=await ft(e.result,{...Io(t(),e.result,e.current),indexed:!1});await navigator.clipboard.write([new ClipboardItem({"image/png":new Blob([l],{type:"image/png"})})]),Z("Image copied",{kind:"ok"})}catch(l){Z(`Couldn't copy: ${l.message}`,{kind:"error"})}}async function i(l,p){let f=new AbortController,h=Z(l,{progress:!0,onCancel:()=>f.abort()});e.exporting=!0;try{let y=await p(f.signal,(E,v)=>{h.progress(E),v&&h.update(v)});h.done(y)}catch(y){h.close(),y.name!=="AbortError"?(Z(`Export failed: ${y.message}`,{kind:"error"}),console.error(y)):Z("Export cancelled")}finally{e.exporting=!1,e.schedule()}}async function r(){let l=e.items.slice();l.length&&await i(`Processing ${l.length} files`,async(p,f)=>{let h=[],y=[];for(let E=0;E<l.length;E++){if(p.aborted)throw new DOMException("Aborted","AbortError");let v=l[E],M=e.settingsFor(v);v.type==="video"&&e.engine.invalidate();let x=await e.engine.process(v.source,M);h.push({name:`${Dt(v.name)}.png`,data:await ft(x,Io(M,x,v))}),v.own&&y.push({name:`${Dt(v.name)}.settings.json`,data:Qt(M)}),f((E+1)/l.length,`Processed ${E+1} of ${l.length}`)}return h.push({name:"settings.json",data:Qt(e.shared)},...y),We(pn(h),"pixel-art.zip","application/zip"),`Saved ${l.length} images as a ZIP`})}async function a(l,p,f,h){let y=t();if(l.source==="files"){let x=e.items.filter(b=>b.type==="image"),S=null;for(let b=0;b<x.length;b++){if(p.aborted)throw new DOMException("Aborted","AbortError");let _=e.settingsFor(x[b]),L=await e.engine.process(x[b].source,S?Lt(_,{size:S}):_);S||(S={mode:"width",width:L.width,height:L.height}),await h(L,b,x.length,x[b].name),f((b+1)/x.length,`Frame ${b+1} of ${x.length}`)}return x.length}let E=e.current;if(!E||E.type!=="video")throw new Error("Open a video first");let v=E.source,M=l.end>l.start?l.end:v.duration;return Dn(v,{fps:l.fps,start:l.start,end:M,signal:p,onFrame:async({index:x,total:S})=>{e.engine.invalidate();let b=await e.engine.process(v,y);await h(b,x,S,`${Dt(E.name)}-${String(x).padStart(4,"0")}`),f((x+1)/S,`Frame ${x+1} of ${S}`)}})}async function c(l){let p=l.source==="files"?"animation":Dt(e.current?.name),f=t(),h=1e3/l.fps;if(l.format==="gif"||l.format==="png-seq"){await i("Rendering frames",async(y,E)=>{let v=[];if(await a(l,y,E,async(M,x,S,b)=>{l.format==="gif"?v.push({width:M.width,height:M.height,data:M.data,delay:h}):v.push({name:`${b}.png`,data:await ft(M,Vn(f))})}),l.format==="gif"){E(1,"Encoding GIF"),await new Promise(x=>setTimeout(x,0));let M=hi(v,{scale:f.export.scale,loop:0});return We(M,`${p}.gif`,"image/gif"),`Saved GIF (${v.length} frames, ${(M.length/1024).toFixed(0)} KB)`}return We(pn(v),`${p}-frames.zip`,"application/zip"),`Saved ${v.length} PNG frames`});return}await i(`Encoding ${l.format.toUpperCase()}`,async(y,E)=>{let{createVideoEncoder:v,decodeAudio:M}=await Promise.resolve().then(()=>(Uo(),Ro)),x=e.current,S=null;if(l.audio&&l.source==="video"&&x&&x.type==="video"&&x.file){E(0,"Reading audio");let P=l.end>l.start?l.end:x.source.duration;S=await M(x.file,{start:l.start,end:P}).catch(R=>(console.warn("[export] audio",R),null))}let b=null;await a(l,y,E,async P=>{if(!b){let R=tc(l.videoSize,P,f.export.scale),j=null;for(let C of R)try{b=await v({format:l.format,fps:l.fps,width:P.width,height:P.height,scale:C,audio:S});break}catch(D){if(j=D,!/encoder available/.test(D.message))throw D}if(!b)throw j}await b.add(P)}),S&&b.audioCodec&&E(1,"Encoding audio");let _=await b.finish();We(_,`${p}.${l.format}`);let L=!l.audio||l.source!=="video"?"":b.audioCodec==="opus"&&l.format==="mp4"?", with Opus audio: VLC and browsers play it, Windows Media Player and QuickTime may not":b.audioCodec?", with audio":S?", without audio (this browser can't encode it)":", no audio track in the source";return`Saved ${l.format.toUpperCase()} (${(_.size/1024/1024).toFixed(1)} MB${L})`})}async function u(l){let p=l.source==="files"?"sheet":`${Dt(e.current?.name)}-sheet`,f=t();await i("Building sprite sheet",async(h,y)=>{let E=[];await a(l,h,y,(S,b,_,L)=>{E.push({width:S.width,height:S.height,data:S.data,name:L?Dt(L):void 0,delay:1e3/l.fps})});let{image:v,atlas:M}=Eo(E,{columns:l.columns,padding:l.padding,name:p});if(f.export.scale>1){let S=f.export.scale;for(let b of Object.values(M.frames)){for(let _ of["x","y","w","h"])b.frame[_]*=S;b.sourceSize.w*=S,b.sourceSize.h*=S}M.meta.size.w*=S,M.meta.size.h*=S,M.meta.scale=String(S)}let x=await ft(v,Vn(f));return We(pn([{name:`${p}.png`,data:x},{name:`${p}.json`,data:JSON.stringify(M,null,2)}]),`${p}.zip`,"application/zip"),`Saved a ${E.length}-frame sprite sheet`})}async function s({tile:l,flips:p}){if(!e.result)return Z("Open an image first",{kind:"error"});let f=t(),h=gi(e.result,{tileWidth:l,tileHeight:l,flips:p}),y=`${Dt(e.current.name)}-tiles`,E=await ft(h.image,Vn(f)),v={...h.map,image:`${y}.png`,note:"tiles[] holds one tile index per cell, row by row"+(p?"; flips[] is 0 none, 1 horizontal, 2 vertical, 3 both":"")};We(pn([{name:`${y}.png`,data:E},{name:`${y}.json`,data:JSON.stringify(v,null,2)}]),`${y}.zip`,"application/zip"),Z(`Saved ${h.count} unique tiles (${h.map.width} \xD7 ${h.map.height} map)`,{kind:"ok"})}return{exportPNG:n,copyImage:o,exportZip:r,exportAnimation:c,exportSheet:u,exportTileset:s}}var Li="itp:";function pt(e,t){try{let n=localStorage.getItem(Li+e);return n==null?t:JSON.parse(n)}catch{return t}}function ct(e,t){try{return localStorage.setItem(Li+e,JSON.stringify(t)),!0}catch{return!1}}function Ui(e){let{store:t}=e,n=(w,G)=>t.update(w,{key:G}),o=()=>t.commit(),i=()=>t.settings,r=Et(),a=(w,G)=>JSON.stringify(w)===JSON.stringify(G),c=pt("sections",{}),u=(w,G,ne,d,...g)=>di(G,{open:c[w]??ne,onToggle:k=>{c[w]=k,ct("sections",c)},onReset:d?()=>{let k={};for(let A of d)k[A]=JSON.parse(JSON.stringify(r[A]));t.update(k)}:null},...g),s=m("div.v",{text:"\u2013"}),l=m("div.v",{text:"\u2013"}),p=m("div.v",{text:"\u2013"}),f=m("div.itp-stats",{"aria-live":"polite"},m("div.itp-stat",{},m("div.k",{text:"Output"}),s),m("div.itp-stat",{},m("div.k",{text:"Colours"}),l),m("div.itp-stat",{},m("div.k",{text:"Render"}),p)),h=m("button",{type:"button",role:"tab","aria-selected":"true",id:"itp-tab-setup","aria-controls":"itp-pane-setup",html:`${Q("sliders")}<span>Setup</span>`}),y=m("button",{type:"button",role:"tab","aria-selected":"false",id:"itp-tab-export","aria-controls":"itp-pane-export",html:`${Q("download")}<span>Export</span>`}),E=m("div.itp-seg",{role:"tablist","aria-label":"Inspector"},h,y),v=Wt({label:"Settings apply to",bare:!0,options:[{value:"shared",label:"All files",icon:"layers"},{value:"own",label:"This file",icon:"unlink"}],value:"shared",onChange:w=>e.current&&e.setOwn(e.current,w==="own")}),M=m("span.itp-scope-note",{}),x=m("div.itp-scope",{hidden:!0},m("div.lab",{},m("span",{text:"Settings apply to"}),M),v.el),S=Wt({label:"Size by",options:[{value:"width",label:"Width"},{value:"block",label:"Pixel size"}],value:"width",onChange:w=>n({size:{mode:w}})}),b=Oe({label:"Pixel width",min:8,max:512,step:1,value:96,reset:96,onInput:w=>n({size:{width:w}},"width"),onCommit:o}),_=qt({label:"Height",min:0,max:2048,help:"Leave empty to keep the aspect ratio.",onChange:w=>n({size:{height:w}})});_.input.placeholder="Auto";let L=Oe({label:"Pixel size",min:1,max:64,step:1,value:8,reset:8,help:"How many source pixels become one output pixel.",onInput:w=>n({size:{block:w}},"block"),onCommit:o}),P=Wt({label:"Resample",options:[{value:"box",label:"Average"},{value:"nearest",label:"Nearest"}],value:"box",help:"Nearest keeps hard edges; use it for art that is already pixelated.",onChange:w=>n({size:{resample:w}})}),R=m("button.itp-btn.small.outline",{type:"button",html:`${Q("grid")}<span>Detect grid</span>`,title:"Find the pixel size of upscaled pixel art",onclick:()=>e.detectGrid()}),j=m("div",{style:{display:"contents"}},b.el,_.el),C=m("div",{style:{display:"contents"}},L.el),D=u("size","Size",!0,["size"],S.el,j,C,P.el,m("div.itp-row",{},R)),F=Jt.map(w=>{let G=w.ratio||1.3333333333333333,ne=m("i",{style:{width:`${Math.round(G>=1?16:16*G)}px`,height:`${Math.round(G>=1?16/G:16)}px`}});return w.ratio||ne.classList.add("orig"),m("button",{type:"button","aria-pressed":"false",title:w.id==="original"?"The source's own shape":`Crop to ${w.label}`,onclick:()=>n({frame:{aspect:w.id}})},ne,m("span",{text:w.label}))}),I=m("div.itp-aspects",{role:"group","aria-label":"Aspect ratio"},...F),N=Oe({label:"Zoom",min:1,max:8,step:.05,value:1,reset:1,help:"Crop into the middle of the frame.",onInput:w=>n({frame:{zoom:w}},"fz"),onCommit:o}),z=Oe({label:"Horizontal position",min:0,max:1,step:.01,scale:100,value:.5,reset:.5,onInput:w=>n({frame:{x:w}},"fx"),onCommit:o}),se=Oe({label:"Vertical position",min:0,max:1,step:.01,scale:100,value:.5,reset:.5,onInput:w=>n({frame:{y:w}},"fy"),onCommit:o}),de=u("frame","Frame",!1,["frame"],Mt("Aspect ratio",I),N.el,z.el,se.el),oe=Ut({label:"Source",options:[{value:"builtin",label:"Built-in palette"},{value:"custom",label:"Custom colours"},{value:"extract",label:"From the image"},{value:"none",label:"None (keep colours)"}],onChange:w=>n({palette:{source:w}})}),ee=Ut({label:"Palette",options:an.map(w=>({value:w.id,label:`${w.name} (${w.colors.length})`})),onChange:w=>n({palette:{source:"builtin",id:w}})}),te=Oe({label:"Number of colours",min:2,max:64,step:1,value:16,reset:16,onInput:w=>n({palette:{count:w}},"count"),onCommit:o}),we=m("div.itp-swatches",{role:"list","aria-label":"Palette colours"}),ue=m("span.val.num",{}),W=Mt("Colours",we,{value:ue}),Y=Wt({label:"Colour matching",options:[{value:"oklab",label:"Perceptual"},{value:"rgb",label:"RGB"}],value:"oklab",onChange:w=>n({palette:{distance:w}})}),be=m("div.itp-row",{style:{flexWrap:"wrap"}},m("button.itp-btn.small.outline",{type:"button",html:`${Q("upload")}<span>Import</span>`,title:".gpl, .hex, .pal, .txt or .json",onclick:()=>e.importPalette()}),m("button.itp-btn.small.outline",{type:"button",html:`${Q("palette")}<span>Lospec</span>`,onclick:()=>e.lospecDialog()}),m("button.itp-btn.small.outline",{type:"button",html:`${Q("pipette")}<span>Pick</span>`,title:"Add colours by clicking the image","aria-pressed":"false",onclick:w=>e.togglePicker(w.currentTarget)}),m("button.itp-btn.small",{type:"button",html:`${Q("download")}<span>Save</span>`,title:"Save to Your palettes",onclick:()=>e.savePalette()})),ce=u("palette","Palette",!1,["palette"],oe.el,ee.el,te.el,W,Y.el,be),le={none:"None",ordered:"Ordered",diffusion:"Error diffusion"},me=Ut({label:"Method",options:cn.map(w=>({value:w.id,label:w.label,group:le[w.kind]})),onChange:w=>n({dither:{method:w}})}),pe=Oe({label:"Strength",min:0,max:1,step:.01,scale:100,value:.6,reset:.6,onInput:w=>n({dither:{strength:w}},"strength"),onCommit:o}),ge=m("textarea.itp-input",{rows:4,spellcheck:!1,"aria-label":"Custom threshold matrix",placeholder:`0 8 2 10
|
|
302
302
|
12 4 14 6
|
|
303
303
|
3 11 1 9
|
|
304
|
-
15 7 13 5`}),_e=m("div.help",{text:"Rows of numbers, up to 16\xD716. Only their order matters."});We.addEventListener("change",()=>{try{n({dither:{method:"custom",matrix:Lo(We.value)}}),_e.textContent="Rows of numbers, up to 16\xD716. Only their order matters.",_e.style.color=""}catch(g){_e.textContent=g.message,_e.style.color="var(--danger)"}});let ke=m("div.itp-field",{},m("div.lab",{},m("span",{text:"Matrix"})),We,_e),le=l("dither","Dither",!1,["dither"],Ve.el,De.el,ke),nt={min:-1,max:1,step:.01,scale:100,value:0,reset:0},Ae=Se({label:"Brightness",...nt,onInput:g=>n({adjust:{brightness:g}},"br"),onCommit:o}),qe=Se({label:"Contrast",...nt,onInput:g=>n({adjust:{contrast:g}},"co"),onCommit:o}),Ge=Se({label:"Saturation",...nt,onInput:g=>n({adjust:{saturation:g}},"sa"),onCommit:o}),Lt=Se({label:"Hue",min:-180,max:180,step:1,value:0,reset:0,help:"Rotates every colour around the colour wheel; greys stay grey.",onInput:g=>n({adjust:{hue:g}},"hu"),onCommit:o}),Oe=Se({label:"Gamma",min:.2,max:3,step:.05,value:1,reset:1,onInput:g=>n({adjust:{gamma:g}},"ga"),onCommit:o}),ot=l("adjust","Adjust",!1,["adjust"],Ae.el,qe.el,Ge.el,Lt.el,Oe.el),Ye=Se({label:"Alpha cutoff",min:0,max:1,step:.01,scale:100,value:.5,reset:.5,help:"Pixels less opaque than this become transparent.",onInput:g=>n({alpha:{threshold:g}},"alpha"),onCommit:o}),Pe=Xt({label:"Remove stray pixels",onChange:g=>n({cleanup:{orphans:g}})}),ge=Xt({label:"Smooth small specks",onChange:g=>n({cleanup:{smooth:g}})}),je=Ht({label:"Outline",options:[{value:"none",label:"None"},{value:"outer",label:"Outside"},{value:"inner",label:"Inside"}],value:"none",help:"Follows transparent edges.",onChange:g=>n({outline:{mode:g}})}),we=Yr({label:"Outline colour",onChange:g=>n({outline:{color:g}},"olc")}),Et=Xt({label:"Include diagonals",onChange:g=>n({outline:{corners:g}})}),Le=l("cleanup","Cleanup & outline",!1,["cleanup","outline","alpha"],Pe.el,ge.el,Ye.el,je.el,we.el,Et.el),Rt=m("div",{id:"itp-pane-setup",role:"tabpanel","aria-labelledby":"itp-tab-setup"},I.el,G.el,me.el,le.el,ot.el,Le.el),Ke=Ht({label:"Size",options:[{value:"scale",label:"Scale"},{value:"source",label:"Source size"}],value:"scale",help:"",onChange:g=>n({export:{size:g}})}),rt=Se({label:"Scale",min:1,max:32,step:1,value:4,reset:4,help:"Whole-number upscale keeps every pixel square.",onInput:g=>n({export:{scale:g}},"scale"),onCommit:o}),Ze=m("span.val.num",{}),kt=Xt({label:"Grid lines",onChange:g=>n({export:{grid:g}})}),Ut=Xt({label:"Indexed PNG",help:"Smaller files; up to 256 colours.",onChange:g=>n({export:{indexed:g}})}),Je=m("button.itp-btn.primary.block",{type:"button",html:`${Y("download")}<span>Download PNG</span>`,onclick:()=>e.exportPNG()}),ft=m("button.itp-btn.outline.block",{type:"button",html:`${Y("copy")}<span>Copy image</span>`,onclick:()=>e.copyImage()}),pt=m("button.itp-btn.outline.block",{type:"button",html:`${Y("zip")}<span>Download all as ZIP</span>`,onclick:()=>e.exportZip()}),It=l("image","Image",!0,["export"],wt("Output size",m("div"),{value:Ze}),Ke.el,rt.el,kt.el,Ut.el,m("div.itp-grid2",{},Je,ft),pt),He=jt({label:"Frames from",options:[{value:"video",label:"Current video"},{value:"files",label:"All files, in order"}],onChange:()=>R()}),it=jt({label:"Format",options:[{value:"gif",label:"GIF"},{value:"webm",label:"WebM video"},{value:"mp4",label:"MP4 video"},{value:"png-seq",label:"PNG sequence (ZIP)"}],onChange:()=>R()}),$e=Vt({label:"Frames per second",min:1,max:60,onChange:()=>{}}),at=Vt({label:"Start (s)",min:0,max:36e3,step:.1,onChange:()=>{}}),Re=Vt({label:"End (s)",min:0,max:36e3,step:.1,onChange:()=>{}}),ze=m("div.help",{}),Ft=m("button.itp-btn.primary.block",{type:"button",html:`${Y("film")}<span>Export animation</span>`,onclick:()=>e.exportAnimation(Mt())}),Yt=l("animation","Animation",!1,null,He.el,it.el,$e.el,m("div.itp-grid2",{},at.el,Re.el),ze,Ft);$e.set(12),at.set(0),Re.set(0);let Mt=()=>({source:He.select.value,format:it.select.value,fps:Number($e.input.value)||12,start:Number(at.input.value)||0,end:Number(Re.input.value)||0}),st=Vt({label:"Columns",min:0,max:256,help:"0 = as square as possible.",onChange:()=>{}}),Qe=Vt({label:"Padding",min:0,max:64,onChange:()=>{}});st.set(0),Qe.set(0);let ct=m("button.itp-btn.outline.block",{type:"button",html:`${Y("sheet")}<span>Download sprite sheet</span>`,onclick:()=>e.exportSheet({...Mt(),columns:Number(st.input.value)||0,padding:Number(Qe.input.value)||0})}),Dt=l("sheet","Sprite sheet",!1,null,m("div.help",{text:"Packs the frames chosen under Animation into one PNG with a JSON atlas (TexturePacker hash format)."}),m("div.itp-grid2",{},st.el,Qe.el),ct),p=jt({label:"Tile size",options:[8,12,16,24,32,48,64].map(g=>({value:String(g),label:`${g} \xD7 ${g}`})),onChange:()=>{}});p.set("16");let M=Xt({label:"Count mirrored tiles as duplicates",onChange:()=>{}}),_=m("button.itp-btn.outline.block",{type:"button",html:`${Y("tiles")}<span>Download tileset</span>`,onclick:()=>e.exportTileset({tile:Number(p.select.value),flips:M.el.querySelector("input").checked})}),F=l("tileset","Tileset",!1,null,m("div.help",{text:"Cuts the current result into tiles, keeps one copy of each and writes a tile map."}),p.el,M.el,_),X=l("settings","Settings",!1,null,m("div.itp-grid2",{},m("button.itp-btn.outline",{type:"button",html:`${Y("link")}<span>Copy link</span>`,onclick:()=>e.copyLink()}),m("button.itp-btn.outline",{type:"button",html:`${Y("braces")}<span>Save JSON</span>`,onclick:()=>e.saveSettingsFile()})),m("button.itp-btn.outline.block",{type:"button",html:`${Y("upload")}<span>Load settings file</span>`,onclick:()=>e.loadSettingsFile()})),ne=m("div",{id:"itp-pane-export",role:"tabpanel","aria-labelledby":"itp-tab-export",hidden:!0},It.el,Yt.el,Dt.el,F.el,X.el),ie=m("div.itp-insp-foot",{},m("button.itp-link",{type:"button",text:"Reset to defaults",onclick:()=>e.resetSettings()}),m("span.muted",{style:{fontSize:"var(--fs-xs)"},id:"itp-backend"})),te=m("div.itp-panel-body",{},Rt,ne),fe=m("aside.itp-insp",{"aria-label":"Inspector"},m("div.itp-insp-head",{},u,b,E),m("div",{style:{height:"8px"}}),te,ie);function C(g){let $=g==="setup";h.setAttribute("aria-selected",String($)),x.setAttribute("aria-selected",String(!$)),Rt.hidden=!$,ne.hidden=$,$||R()}h.onclick=()=>C("setup"),x.onclick=()=>C("export"),E.addEventListener("keydown",g=>{if(g.key==="ArrowRight"||g.key==="ArrowLeft"){let $=h.getAttribute("aria-selected")==="true"?x:h;$.click(),$.focus()}});function R(){let g=e.current,$=g&&g.type==="video",ee=e.items.filter(Q=>Q.type==="image").length;!$&&He.select.value==="video"&&ee>1&&He.set("files"),$&&He.select.value==="files"&&ee<2&&He.set("video");let J=He.select.value,oe=J==="video"?$:ee>1;at.el.hidden=Re.el.hidden=J!=="video",Ft.disabled=!oe,ct.disabled=!oe,$&&!Number(Re.input.value)&&Re.set(Math.round((g.duration||0)*10)/10),$&&g.fps&&!$e.input.dataset.touched&&$e.set(Math.min(30,Math.round(g.fps)));let re=it.select.value;ze.textContent=oe?(re==="mp4"||re==="webm")&&!e.videoSupport?.[re]?`${re.toUpperCase()} encoding isn't available in this browser. GIF and PNG sequence always work.`:"":J==="video"?"Open a video to export an animation.":"Add two or more images to animate them."}$e.input.addEventListener("change",()=>{$e.input.dataset.touched="1"});function O(g,$){tt(se,...g.map((ee,J)=>{let oe=m("button.itp-swatch",{type:"button",role:"listitem",title:$?`${ee}. Click to change, Alt+click to remove`:ee,style:{background:ee}});return oe.setAttribute("aria-label",$?`${ee}, edit`:ee),$?oe.addEventListener("click",re=>{if(re.altKey){let de=i().palette.colors.filter((ht,mt)=>mt!==J);de.length&&n({palette:{colors:de}});return}let Q=m("input",{type:"color",value:ee,style:{position:"fixed",opacity:0,pointerEvents:"none"}});document.body.append(Q),Q.addEventListener("input",()=>{let de=i().palette.colors.slice();de[J]=Q.value,n({palette:{colors:de}},"sw"+J)}),Q.addEventListener("change",()=>Q.remove()),Q.click()}):oe.addEventListener("click",()=>{n({palette:{source:"custom",colors:i().palette.colors.slice(),name:`${i().palette.name} (edited)`}}),e.toast("Copied to a custom palette you can edit")}),oe}),$?m("button.itp-swatch.add",{type:"button","aria-label":"Add colour",title:"Add colour",html:Y("plus"),onclick:()=>n({palette:{colors:[...i().palette.colors,"#808080"]}})}):null)}let j="";function q(g,$){S.set(g.size.mode),z.hidden=g.size.mode!=="width",v.hidden=g.size.mode!=="block",w.set(g.size.width),A.set(g.size.height||""),L.set(g.size.block),T.set(g.size.resample),I.setHint($?`${$.width} \xD7 ${$.height}`:""),ce.set(g.palette.source),be.set(g.palette.id),be.el.hidden=g.palette.source!=="builtin",Te.el.hidden=g.palette.source!=="extract",Te.set(g.palette.count),Fe.set(g.palette.distance),Fe.el.hidden=g.palette.source==="none",he.hidden=g.palette.source==="none";let ee=g.palette.source==="extract"?$&&$.palette||[]:g.palette.colors,J=g.palette.source+ee.join();J!==j&&(j=J,O(ee,g.palette.source==="custom")),ae.textContent=String(ee.length),me.setHint(g.palette.source==="none"?"None":g.palette.name),Ve.set(g.dither.method),De.set(g.dither.strength);let oe=yn(g.dither.method);De.el.hidden=oe==="none",ke.hidden=g.dither.method!=="custom",g.dither.method==="custom"&&document.activeElement!==We&&(We.value=(g.dither.matrix||[]).map(xe=>xe.join(" ")).join(`
|
|
305
|
-
`)),le.setHint(g.palette.source==="none"?"Needs a palette":rn.find(xe=>xe.id===g.dither.method).label),le.el.querySelector("select").disabled=g.palette.source==="none",Ae.set(g.adjust.brightness),qe.set(g.adjust.contrast),Ge.set(g.adjust.saturation),Lt.set(g.adjust.hue),Oe.set(g.adjust.gamma);let re=g.adjust.brightness||g.adjust.contrast||g.adjust.saturation||g.adjust.hue||g.adjust.gamma!==1;D.forEach((xe,Ct)=>xe.setAttribute("aria-pressed",String(Kt[Ct].id===g.frame.aspect))),B.set(g.frame.zoom),H.set(g.frame.x),V.set(g.frame.y);let Q=e.current,de=Q?wn(Q.width,Q.height,g.frame):null;H.el.hidden=!de||de.w>=Q.width,V.el.hidden=!de||de.h>=Q.height;let ht=g.frame.aspect!=="original"||g.frame.zoom>1;G.setHint(ht?[g.frame.aspect!=="original"?g.frame.aspect:"",g.frame.zoom>1?`${Math.round(g.frame.zoom*100)/100}\xD7`:""].filter(Boolean).join(", "):""),G.setChanged(!a(g.frame,r.frame));let mt=e.items.length>1;b.hidden=!(Q&&(mt||Q.own)),y.set(Q&&Q.own?"own":"shared");let Z=e.items.filter(xe=>!xe.own).length;k.textContent=Q&&Q.own?"Only this file":`${Z} ${Z===1?"file":"files"}`,fe.dataset.scope=Q&&Q.own?"own":"shared",ot.setHint(re?"Changed":""),Ye.set(g.alpha.threshold),Pe.set(g.cleanup.orphans),ge.set(g.cleanup.smooth),je.set(g.outline.mode),we.set(g.outline.color),Et.set(g.outline.corners),we.el.hidden=Et.el.hidden=g.outline.mode==="none";let ve=[g.cleanup.orphans&&"strays",g.cleanup.smooth&&"smooth",g.outline.mode!=="none"&&"outline"].filter(Boolean);Le.setHint(ve.join(", ")),I.setChanged(!a(g.size,r.size)),me.setChanged(!a(g.palette,r.palette)),le.setChanged(!a(g.dither,r.dither)),ot.setChanged(!a(g.adjust,r.adjust)),Le.setChanged(!a([g.cleanup,g.outline,g.alpha],[r.cleanup,r.outline,r.alpha])),It.setChanged(!a(g.export,r.export)),rt.set(g.export.scale),kt.set(g.export.grid),Ut.set(g.export.indexed),Ke.set(g.export.size),rt.el.hidden=kt.el.hidden=g.export.size==="source";let ue=$n(g,$,e.current);Ze.textContent=$?`${ue.width} \xD7 ${ue.height} px`:"\u2013",Ke.el.querySelector(".help")?.remove(),g.export.size==="source"&&Ke.el.append(m("div.help",{text:"The size of the framed part of the source, like a full-resolution download. Pixels can differ by one in size when the ratio isn't a whole number."})),pt.hidden=e.items.length<2,pt.querySelector("span").textContent=`Download all ${e.items.length} as ZIP`,R()}function N(g){if(!g){s.textContent=d.textContent=f.textContent="\u2013";return}s.innerHTML=`${g.width}<small>\xD7 ${g.height}</small>`;let $=g.usedColors().length;d.innerHTML=g.palette?`${$}<small>/ ${g.palette.length}</small>`:`${$}`,f.innerHTML=`${g.ms<10?g.ms.toFixed(1):Math.round(g.ms)}<small>ms</small>`,f.parentElement.title=g.backend==="webgl"?"Rendered on the GPU (WebGL 2 via ShaderMate)":"Rendered on the CPU"}return{el:fe,sync:q,setStats:N,setTab:C,syncAnim:R}}function fi(e){let t="files",n=(T,P,z)=>m("button",{type:"button",role:"tab","aria-selected":String(T===t),html:`${Y(z)}<span>${P}</span>`,onclick:()=>u(T)}),o=n("files","Files","files"),i=n("presets","Presets","presets"),r=n("palettes","Palettes","palette"),a=m("span.count",{});o.append(a);let c=m("div.itp-seg",{role:"tablist","aria-label":"Library"},o,i,r),l=m("input",{type:"search",placeholder:"Search","aria-label":"Search the library"}),s=m("div.itp-search",{},m("span",{html:Y("search")}),l);l.addEventListener("input",()=>L());let d=m("div.itp-panel-body",{}),f=m("aside.itp-lib",{"aria-label":"Library"},m("div.itp-panel-head",{},c),s,d);function u(T){t=T;for(let[P,z]of[[o,"files"],[i,"presets"],[r,"palettes"]])P.setAttribute("aria-selected",String(z===T));l.value="",L(),T==="presets"&&!y.size&&S()}let h=()=>l.value.trim().toLowerCase();function x(T,P){let z=e.items.indexOf(T),v=e.items.length>1;un(P,[T.own?{label:"Use shared settings",sub:"Drop this file's own settings",icon:"link",onClick:()=>e.setOwn(T,!1)}:{label:"Give it its own settings",sub:"Edits stop affecting other files",icon:"unlink",disabled:!v,onClick:()=>e.setOwn(T,!0)},"sep",{label:"Copy settings",icon:"copy",onClick:()=>e.copySettings(T)},{label:"Paste settings",sub:e.clipboard?"Gives this file its own settings":"Copy settings from a file first",icon:"clipboard",disabled:!e.clipboard,onClick:()=>e.pasteSettings(T)},{label:"Apply these settings to all files",icon:"layers",disabled:!v,onClick:()=>e.applyToAll(T)},"sep",{label:"Duplicate",sub:"A copy with its own settings, to compare looks",icon:"copy",onClick:()=>e.duplicate(T)},{label:"Move up",icon:"arrowUp",kbd:"Alt Shift \u2191",disabled:z<=0,onClick:()=>e.move(T,-1)},{label:"Move down",icon:"arrowDown",kbd:"Alt Shift \u2193",disabled:z>=e.items.length-1,onClick:()=>e.move(T,1)},"sep",{label:"Remove",icon:"trash",kbd:"Del",onClick:()=>e.removeItem(T)}],{align:"start"})}function E(){let T=e.items.filter(U=>!h()||U.name.toLowerCase().includes(h())),P=m("ul.itp-files",{"aria-label":"Files"});for(let U of T){let B=m("button.itp-btn.small.icon",{type:"button","aria-label":`Options for ${U.name}`,"aria-haspopup":"menu",title:"Settings, duplicate, order",html:Y("more"),onclick:G=>{G.stopPropagation(),x(U,B)}}),H=U.type==="video"?`Video, ${pn(U.duration)}`:`${U.width} \xD7 ${U.height}`,V=m("li.itp-file-row",{tabindex:"0","aria-current":String(e.current===U),"data-own":U.own?"true":null},m("img.thumb",{src:U.thumb||"",alt:""}),m("div",{style:{minWidth:0}},m("div.title",{text:U.name}),m("div.sub",{},H,U.own?m("span.itp-own",{title:"This file has its own settings",html:`${Y("unlink")}<span>Own</span>`}):null)),m("div.actions",{},B,m("button.itp-btn.small.icon.danger",{type:"button","aria-label":`Remove ${U.name}`,title:"Remove",html:Y("x"),onclick:G=>{G.stopPropagation(),e.removeItem(U)}})));V.addEventListener("click",()=>e.select(U)),V.addEventListener("contextmenu",G=>{G.preventDefault(),e.select(U),x(U,B)}),V.addEventListener("keydown",G=>{G.target===V&&((G.key==="Enter"||G.key===" ")&&(G.preventDefault(),e.select(U)),(G.key==="Delete"||G.key==="Backspace")&&(G.preventDefault(),e.removeItem(U)),!G.altKey&&(G.key==="ArrowDown"&&(G.preventDefault(),V.nextElementSibling?.focus()),G.key==="ArrowUp"&&(G.preventDefault(),V.previousElementSibling?.focus()),(G.key==="ContextMenu"||G.key==="F10"&&G.shiftKey)&&(G.preventDefault(),x(U,B))))}),P.append(V)}let z=e.items.filter(U=>U.own).length,v=e.items.length?e.items.length===1?"1 file":z?`${e.items.length} files, ${z} with ${z===1?"its":"their"} own settings`:`${e.items.length} files, shared settings`:"No files yet",I=m("div.itp-group",{},m("span",{text:v}),e.items.length>1?m("button.itp-link",{type:"button",text:"Clear",onclick:()=>e.clearItems()}):null),D=m("div",{style:{padding:"4px 12px 12px",display:"flex",gap:"6px"}},m("button.itp-btn.outline.small",{type:"button",html:`${Y("plus")}<span>Add files</span>`,onclick:()=>e.openFiles()}),m("button.itp-btn.small",{type:"button",html:`${Y("clipboard")}<span>Paste</span>`,title:"Paste an image from the clipboard (Ctrl+V)",onclick:()=>e.pasteFromClipboard()}));tt(d,I,P,D,m("div.itp-group",{},m("span",{text:"Drop images or videos anywhere in the window. Files share one set of settings unless you give one its own (\u22EF menu or right-click)."})))}let y=new Map,k=0;function b(){let T=e.store.settings,P=cn.filter(v=>!h()||(v.name+v.description).toLowerCase().includes(h())),z=m("div.itp-presets",{});for(let v of P){let I=e.activePreset===v.id,D=y.get(v.id)||m("div.ph",{}),U=m("button.itp-preset",{type:"button","aria-pressed":String(I),title:v.description,onclick:()=>e.applyPreset(v)},D,m("span.t",{text:v.name}),m("span.d",{text:v.description}));z.append(U)}tt(d,m("div.itp-group",{},m("span",{text:"Presets replace the current settings. Undo with Ctrl+Z."})),z)}async function S(){let T=++k,P=e.current;if(!(!P||!e.engine))for(let z of cn){if(T!==k)return;let v=Tt(xt(),z.settings);v.size={...v.size,mode:"width",width:Math.min(v.size.width,72),height:0};try{let I=await e.engine.process(P.source,v);if(T!==k)return;let D=I.toCanvas(1);y.set(z.id,D),t==="presets"&&b()}catch{}}}function w(T,P,z){let v=m("div.itp-strip",{},...T.colors.slice(0,64).map(U=>m("i",{style:{background:U.startsWith("#")?U:"#"+U}}))),I=m("li.itp-pal",{tabindex:"0",role:"button","aria-pressed":String(P)},m("div.row",{},m("span",{text:T.name}),m("span.n",{text:String(T.colors.length),title:T.author?`by ${T.author}`:null})),v),D=()=>e.usePalette(T);if(I.addEventListener("click",D),I.addEventListener("keydown",U=>{(U.key==="Enter"||U.key===" ")&&(U.preventDefault(),D()),z&&U.key==="Delete"&&e.deletePalette(T)}),z){let U=m("button.itp-btn.small.icon.danger",{type:"button","aria-label":`Delete ${T.name}`,title:"Delete",html:Y("trash"),onclick:B=>{B.stopPropagation(),e.deletePalette(T)}});I.firstChild.append(U)}return I}function A(){let T=e.store.settings.palette,P=U=>!h()||(U.name+" "+(U.author||"")).toLowerCase().includes(h())||String(U.colors.length)===h(),z=e.userPalettes.filter(P),v=nn.filter(P),I=m("div",{style:{padding:"0 12px 4px",display:"flex",gap:"6px",flexWrap:"wrap"}},m("button.itp-btn.outline.small",{type:"button",html:`${Y("upload")}<span>Import file</span>`,onclick:()=>e.importPalette()}),m("button.itp-btn.small",{type:"button",html:`${Y("palette")}<span>From Lospec</span>`,onclick:()=>e.lospecDialog()})),D=z.length?[m("div.itp-group",{},m("span",{text:"Your palettes"}),m("span.itp-badge",{text:String(z.length)})),m("ul.itp-pal-list",{},...z.map(U=>w(U,T.source==="custom"&&T.name===U.name,!0)))]:[];tt(d,I,...D,m("div.itp-group",{},m("span",{text:"Built-in"}),m("span.itp-badge",{text:String(v.length)})),m("ul.itp-pal-list",{},...v.map(U=>w({...U,colors:U.colors.map(B=>"#"+B)},T.source==="builtin"&&T.id===U.id,!1))))}function L(){a.textContent=e.items.length?String(e.items.length):"",t==="files"?E():t==="presets"?b():A()}return{el:f,refresh:L,setTab:u,focusFile(T){t==="files"&&d.querySelectorAll(".itp-file-row")[e.items.indexOf(T)]?.focus()},sourceChanged(){y.clear(),k++,t==="presets"&&(L(),S())},get tab(){return t}}}function pn(e=0){let t=Math.floor(e/60),n=e-t*60;return`${t}:${n.toFixed(1).padStart(4,"0")}`}var vs=`<svg xmlns="http://www.w3.org/2000/svg" width="960" height="640" viewBox="0 0 960 640">
|
|
304
|
+
15 7 13 5`}),xe=m("div.help",{text:"Rows of numbers, up to 16\xD716. Only their order matters."});ge.addEventListener("change",()=>{try{n({dither:{method:"custom",matrix:Wo(ge.value)}}),xe.textContent="Rows of numbers, up to 16\xD716. Only their order matters.",xe.style.color=""}catch(w){xe.textContent=w.message,xe.style.color="var(--danger)"}});let ke=m("div.itp-field",{},m("div.lab",{},m("span",{text:"Matrix"})),ge,xe),ie=u("dither","Dither",!1,["dither"],me.el,pe.el,ke),ze={min:-1,max:1,step:.01,scale:100,value:0,reset:0},Be=Oe({label:"Brightness",...ze,onInput:w=>n({adjust:{brightness:w}},"br"),onCommit:o}),lt=Oe({label:"Contrast",...ze,onInput:w=>n({adjust:{contrast:w}},"co"),onCommit:o}),qe=Oe({label:"Saturation",...ze,onInput:w=>n({adjust:{saturation:w}},"sa"),onCommit:o}),Ne=Oe({label:"Hue",min:-180,max:180,step:1,value:0,reset:0,help:"Rotates every colour around the colour wheel; greys stay grey.",onInput:w=>n({adjust:{hue:w}},"hu"),onCommit:o}),Ct=Oe({label:"Gamma",min:.2,max:3,step:.05,value:1,reset:1,onInput:w=>n({adjust:{gamma:w}},"ga"),onCommit:o}),De=u("adjust","Adjust",!1,["adjust"],Be.el,lt.el,qe.el,Ne.el,Ct.el),Ft=Oe({label:"Alpha cutoff",min:0,max:1,step:.01,scale:100,value:.5,reset:.5,help:"Pixels less opaque than this become transparent.",onInput:w=>n({alpha:{threshold:w}},"alpha"),onCommit:o}),et=It({label:"Remove stray pixels",onChange:w=>n({cleanup:{orphans:w}})}),Me=It({label:"Smooth small specks",onChange:w=>n({cleanup:{smooth:w}})}),Ye=Wt({label:"Outline",options:[{value:"none",label:"None"},{value:"outer",label:"Outside"},{value:"inner",label:"Inside"}],value:"none",help:"Follows transparent edges.",onChange:w=>n({outline:{mode:w}})}),Ae=fi({label:"Outline colour",onChange:w=>n({outline:{color:w}},"olc")}),ht=It({label:"Include diagonals",onChange:w=>n({outline:{corners:w}})}),Fe=u("cleanup","Cleanup & outline",!1,["cleanup","outline","alpha"],et.el,Me.el,Ft.el,Ye.el,Ae.el,ht.el),mt=m("div",{id:"itp-pane-setup",role:"tabpanel","aria-labelledby":"itp-tab-setup"},D.el,de.el,ce.el,ie.el,De.el,Fe.el),tt=Wt({label:"Size",options:[{value:"scale",label:"Scale"},{value:"source",label:"Source size"}],value:"scale",help:"",onChange:w=>n({export:{size:w}})}),St=Oe({label:"Scale",min:1,max:32,step:1,value:4,reset:4,help:"Whole-number upscale keeps every pixel square.",onInput:w=>n({export:{scale:w}},"scale"),onCommit:o}),Ce=m("span.val.num",{}),Tt=It({label:"Grid lines",onChange:w=>n({export:{grid:w}})}),nt=It({label:"Indexed PNG",help:"Smaller files; up to 256 colours.",onChange:w=>n({export:{indexed:w}})}),Ke=m("button.itp-btn.primary.block",{type:"button",html:`${Q("download")}<span>Download PNG</span>`,onclick:()=>e.exportPNG()}),ot=m("button.itp-btn.outline.block",{type:"button",html:`${Q("copy")}<span>Copy image</span>`,onclick:()=>e.copyImage()}),gt=m("button.itp-btn.outline.block",{type:"button",html:`${Q("zip")}<span>Download all as ZIP</span>`,onclick:()=>e.exportZip()}),ut=u("image","Image",!0,["export"],Mt("Output size",m("div"),{value:Ce}),tt.el,St.el,Tt.el,nt.el,m("div.itp-grid2",{},Ke,ot),gt),Ge=Ut({label:"Frames from",options:[{value:"video",label:"Current video"},{value:"files",label:"All files, in order"}],onChange:()=>K()}),dt=Ut({label:"Format",options:[{value:"gif",label:"GIF"},{value:"webm",label:"WebM video"},{value:"mp4",label:"MP4 video"},{value:"png-seq",label:"PNG sequence (ZIP)"}],onChange:()=>K()}),je=qt({label:"Frames per second",min:1,max:60,onChange:()=>{}}),Le=qt({label:"Start (s)",min:0,max:36e3,step:.1,onChange:()=>{}}),rt=qt({label:"End (s)",min:0,max:36e3,step:.1,onChange:()=>{}}),$e=Ut({label:"Video size",options:[{value:"1080",label:"Full HD (sharp in any player)"},{value:"720",label:"720p"},{value:"2160",label:"4K"},{value:"scale",label:"Same scale as PNG"}],onChange:()=>{}});$e.set("1080");let Ze=It({label:"Keep audio",help:"The video's soundtrack, cut to the same start and end. MP4 and WebM only.",onChange:()=>K()}),At=Ze.el.querySelector("input"),He=m("div.help",{}),_t=m("button.itp-btn.primary.block",{type:"button",html:`${Q("film")}<span>Export animation</span>`,onclick:()=>e.exportAnimation($t())}),Pt=u("animation","Animation",!1,null,Ge.el,dt.el,je.el,m("div.itp-grid2",{},Le.el,rt.el),$e.el,Ze.el,He,_t);je.set(12),Le.set(0),rt.set(0),Ze.set(!0);let $t=()=>({source:Ge.select.value,format:dt.select.value,fps:Number(je.input.value)||12,start:Number(Le.input.value)||0,end:Number(rt.input.value)||0,audio:At.checked,videoSize:$e.select.value}),it=qt({label:"Columns",min:0,max:256,help:"0 = as square as possible.",onChange:()=>{}}),Je=qt({label:"Padding",min:0,max:64,onChange:()=>{}});it.set(0),Je.set(0);let bt=m("button.itp-btn.outline.block",{type:"button",html:`${Q("sheet")}<span>Download sprite sheet</span>`,onclick:()=>e.exportSheet({...$t(),columns:Number(it.input.value)||0,padding:Number(Je.input.value)||0})}),Kt=u("sheet","Sprite sheet",!1,null,m("div.help",{text:"Packs the frames chosen under Animation into one PNG with a JSON atlas (TexturePacker hash format)."}),m("div.itp-grid2",{},it.el,Je.el),bt),yt=Ut({label:"Tile size",options:[8,12,16,24,32,48,64].map(w=>({value:String(w),label:`${w} \xD7 ${w}`})),onChange:()=>{}});yt.set("16");let Re=It({label:"Count mirrored tiles as duplicates",onChange:()=>{}}),zt=m("button.itp-btn.outline.block",{type:"button",html:`${Q("tiles")}<span>Download tileset</span>`,onclick:()=>e.exportTileset({tile:Number(yt.select.value),flips:Re.el.querySelector("input").checked})}),Zt=u("tileset","Tileset",!1,null,m("div.help",{text:"Cuts the current result into tiles, keeps one copy of each and writes a tile map."}),yt.el,Re.el,zt),ve=u("settings","Settings",!1,null,m("div.itp-grid2",{},m("button.itp-btn.outline",{type:"button",html:`${Q("link")}<span>Copy link</span>`,onclick:()=>e.copyLink()}),m("button.itp-btn.outline",{type:"button",html:`${Q("braces")}<span>Save JSON</span>`,onclick:()=>e.saveSettingsFile()})),m("button.itp-btn.outline.block",{type:"button",html:`${Q("upload")}<span>Load settings file</span>`,onclick:()=>e.loadSettingsFile()})),Bt=m("div",{id:"itp-pane-export",role:"tabpanel","aria-labelledby":"itp-tab-export",hidden:!0},ut.el,Pt.el,Kt.el,Zt.el,ve.el),T=m("div.itp-insp-foot",{},m("button.itp-link",{type:"button",text:"Reset to defaults",onclick:()=>e.resetSettings()}),m("span.muted",{style:{fontSize:"var(--fs-xs)"},id:"itp-backend"})),O=m("div.itp-panel-body",{},mt,Bt),$=m("aside.itp-insp",{"aria-label":"Inspector"},m("div.itp-insp-head",{},f,x,E),m("div",{style:{height:"8px"}}),O,T);function V(w){let G=w==="setup";h.setAttribute("aria-selected",String(G)),y.setAttribute("aria-selected",String(!G)),mt.hidden=!G,Bt.hidden=G,G||K()}h.onclick=()=>V("setup"),y.onclick=()=>V("export"),E.addEventListener("keydown",w=>{if(w.key==="ArrowRight"||w.key==="ArrowLeft"){let G=h.getAttribute("aria-selected")==="true"?y:h;G.click(),G.focus()}});function K(){let w=e.current,G=w&&w.type==="video",ne=e.items.filter(X=>X.type==="image").length;!G&&Ge.select.value==="video"&&ne>1&&Ge.set("files"),G&&Ge.select.value==="files"&&ne<2&&Ge.set("video");let d=Ge.select.value,g=d==="video"?G:ne>1;Le.el.hidden=rt.el.hidden=d!=="video",_t.disabled=!g,bt.disabled=!g,G&&!Number(rt.input.value)&&rt.set(Math.round((w.duration||0)*10)/10),G&&w.fps&&!je.input.dataset.touched&&je.set(Math.min(30,Math.round(w.fps)));let k=dt.select.value,A=k==="mp4"||k==="webm";Ze.el.hidden=!(d==="video"&&A),$e.el.hidden=!A;let U=e.videoSupport,B=U&&"opus"in U&&At.checked&&!Ze.el.hidden&&!(k==="mp4"&&U.aac||U.opus);He.textContent=g?A&&!U?.[k]?`${k.toUpperCase()} encoding isn't available in this browser. GIF and PNG sequence always work.`:B?"This browser can't encode audio, so the video will be silent.":k==="mp4"&&U&&"aac"in U&&!U.aac&&U.opus&&At.checked&&!Ze.el.hidden?"This browser can't encode AAC, so the MP4's sound will be Opus, which Windows Media Player and QuickTime may not play. WebM, or Chrome/Edge on Windows or macOS, avoids that.":"":d==="video"?"Open a video to export an animation.":"Add two or more images to animate them."}je.input.addEventListener("change",()=>{je.input.dataset.touched="1"});function H(w,G){st(we,...w.map((ne,d)=>{let g=m("button.itp-swatch",{type:"button",role:"listitem",title:G?`${ne}. Click to change, Alt+click to remove`:ne,style:{background:ne}});return g.setAttribute("aria-label",G?`${ne}, edit`:ne),G?g.addEventListener("click",k=>{if(k.altKey){let U=i().palette.colors.filter((B,X)=>X!==d);U.length&&n({palette:{colors:U}});return}let A=m("input",{type:"color",value:ne,style:{position:"fixed",opacity:0,pointerEvents:"none"}});document.body.append(A),A.addEventListener("input",()=>{let U=i().palette.colors.slice();U[d]=A.value,n({palette:{colors:U}},"sw"+d)}),A.addEventListener("change",()=>A.remove()),A.click()}):g.addEventListener("click",()=>{n({palette:{source:"custom",colors:i().palette.colors.slice(),name:`${i().palette.name} (edited)`}}),e.toast("Copied to a custom palette you can edit")}),g}),G?m("button.itp-swatch.add",{type:"button","aria-label":"Add colour",title:"Add colour",html:Q("plus"),onclick:()=>n({palette:{colors:[...i().palette.colors,"#808080"]}})}):null)}let J="";function ae(w,G){S.set(w.size.mode),j.hidden=w.size.mode!=="width",C.hidden=w.size.mode!=="block",b.set(w.size.width),_.set(w.size.height||""),L.set(w.size.block),P.set(w.size.resample),D.setHint(G?`${G.width} \xD7 ${G.height}`:""),oe.set(w.palette.source),ee.set(w.palette.id),ee.el.hidden=w.palette.source!=="builtin",te.el.hidden=w.palette.source!=="extract",te.set(w.palette.count),Y.set(w.palette.distance),Y.el.hidden=w.palette.source==="none",W.hidden=w.palette.source==="none";let ne=w.palette.source==="extract"?G&&G.palette||[]:w.palette.colors,d=w.palette.source+ne.join();d!==J&&(J=d,H(ne,w.palette.source==="custom")),ue.textContent=String(ne.length),ce.setHint(w.palette.source==="none"?"None":w.palette.name),me.set(w.dither.method),pe.set(w.dither.strength);let g=Mn(w.dither.method);pe.el.hidden=g==="none",ke.hidden=w.dither.method!=="custom",w.dither.method==="custom"&&document.activeElement!==ge&&(ge.value=(w.dither.matrix||[]).map(Ve=>Ve.join(" ")).join(`
|
|
305
|
+
`)),ie.setHint(w.palette.source==="none"?"Needs a palette":cn.find(Ve=>Ve.id===w.dither.method).label),ie.el.querySelector("select").disabled=w.palette.source==="none",Be.set(w.adjust.brightness),lt.set(w.adjust.contrast),qe.set(w.adjust.saturation),Ne.set(w.adjust.hue),Ct.set(w.adjust.gamma);let k=w.adjust.brightness||w.adjust.contrast||w.adjust.saturation||w.adjust.hue||w.adjust.gamma!==1;F.forEach((Ve,Qe)=>Ve.setAttribute("aria-pressed",String(Jt[Qe].id===w.frame.aspect))),N.set(w.frame.zoom),z.set(w.frame.x),se.set(w.frame.y);let A=e.current,U=A?Cn(A.width,A.height,w.frame):null;z.el.hidden=!U||U.w>=A.width,se.el.hidden=!U||U.h>=A.height;let B=w.frame.aspect!=="original"||w.frame.zoom>1;de.setHint(B?[w.frame.aspect!=="original"?w.frame.aspect:"",w.frame.zoom>1?`${Math.round(w.frame.zoom*100)/100}\xD7`:""].filter(Boolean).join(", "):""),de.setChanged(!a(w.frame,r.frame));let X=e.items.length>1;x.hidden=!(A&&(X||A.own)),v.set(A&&A.own?"own":"shared");let re=e.items.filter(Ve=>!Ve.own).length;M.textContent=A&&A.own?"Only this file":`${re} ${re===1?"file":"files"}`,$.dataset.scope=A&&A.own?"own":"shared",De.setHint(k?"Changed":""),Ft.set(w.alpha.threshold),et.set(w.cleanup.orphans),Me.set(w.cleanup.smooth),Ye.set(w.outline.mode),Ae.set(w.outline.color),ht.set(w.outline.corners),Ae.el.hidden=ht.el.hidden=w.outline.mode==="none";let fe=[w.cleanup.orphans&&"strays",w.cleanup.smooth&&"smooth",w.outline.mode!=="none"&&"outline"].filter(Boolean);Fe.setHint(fe.join(", ")),D.setChanged(!a(w.size,r.size)),ce.setChanged(!a(w.palette,r.palette)),ie.setChanged(!a(w.dither,r.dither)),De.setChanged(!a(w.adjust,r.adjust)),Fe.setChanged(!a([w.cleanup,w.outline,w.alpha],[r.cleanup,r.outline,r.alpha])),ut.setChanged(!a(w.export,r.export)),St.set(w.export.scale),Tt.set(w.export.grid),nt.set(w.export.indexed),tt.set(w.export.size),St.el.hidden=Tt.el.hidden=w.export.size==="source";let _e=Xn(w,G,e.current);Ce.textContent=G?`${_e.width} \xD7 ${_e.height} px`:"\u2013",tt.el.querySelector(".help")?.remove(),w.export.size==="source"&&tt.el.append(m("div.help",{text:"The size of the framed part of the source, like a full-resolution download. Pixels can differ by one in size when the ratio isn't a whole number."})),gt.hidden=e.items.length<2,gt.querySelector("span").textContent=`Download all ${e.items.length} as ZIP`,K()}function ye(w){if(!w){s.textContent=l.textContent=p.textContent="\u2013";return}s.innerHTML=`${w.width}<small>\xD7 ${w.height}</small>`;let G=w.usedColors().length;l.innerHTML=w.palette?`${G}<small>/ ${w.palette.length}</small>`:`${G}`,p.innerHTML=`${w.ms<10?w.ms.toFixed(1):Math.round(w.ms)}<small>ms</small>`,p.parentElement.title=w.backend==="webgl"?"Rendered on the GPU (WebGL 2 via ShaderMate)":"Rendered on the CPU"}return{el:$,sync:ae,setStats:ye,setTab:V,syncAnim:K}}function Ii(e){let t="files",n=(P,R,j)=>m("button",{type:"button",role:"tab",title:R,"aria-selected":String(P===t),html:`${Q(j)}<span>${R}</span>`,onclick:()=>f(P)}),o=n("files","Files","files"),i=n("presets","Presets","presets"),r=n("palettes","Palettes","palette"),a=m("span.count",{});o.append(a);let c=m("div.itp-seg",{role:"tablist","aria-label":"Library"},o,i,r),u=m("input",{type:"search",placeholder:"Search","aria-label":"Search the library"}),s=m("div.itp-search",{},m("span",{html:Q("search")}),u);u.addEventListener("input",()=>L());let l=m("div.itp-panel-body",{}),p=m("aside.itp-lib",{"aria-label":"Library"},m("div.itp-panel-head",{},c),s,l);function f(P){t=P;for(let[R,j]of[[o,"files"],[i,"presets"],[r,"palettes"]])R.setAttribute("aria-selected",String(j===P));u.value="",L(),P==="presets"&&!v.size&&S()}let h=()=>u.value.trim().toLowerCase();function y(P,R){let j=e.items.indexOf(P),C=e.items.length>1;hn(R,[P.own?{label:"Use shared settings",sub:"Drop this file's own settings",icon:"link",onClick:()=>e.setOwn(P,!1)}:{label:"Give it its own settings",sub:"Edits stop affecting other files",icon:"unlink",disabled:!C,onClick:()=>e.setOwn(P,!0)},"sep",{label:"Copy settings",icon:"copy",onClick:()=>e.copySettings(P)},{label:"Paste settings",sub:e.clipboard?"Gives this file its own settings":"Copy settings from a file first",icon:"clipboard",disabled:!e.clipboard,onClick:()=>e.pasteSettings(P)},{label:"Apply these settings to all files",icon:"layers",disabled:!C,onClick:()=>e.applyToAll(P)},"sep",{label:"Rename",sub:"Exports are named after it",icon:"rename",kbd:"F2",onClick:()=>e.startRename(P)},{label:"Duplicate",sub:"A copy with its own settings, to compare looks",icon:"copy",onClick:()=>e.duplicate(P)},{label:"Move up",icon:"arrowUp",kbd:"Alt Shift \u2191",disabled:j<=0,onClick:()=>e.move(P,-1)},{label:"Move down",icon:"arrowDown",kbd:"Alt Shift \u2193",disabled:j>=e.items.length-1,onClick:()=>e.move(P,1)},"sep",{label:"Remove",icon:"trash",kbd:"Del",onClick:()=>e.removeItem(P)}],{align:"start"})}function E(){let P=e.items.filter(z=>!h()||z.name.toLowerCase().includes(h())),R=m("ul.itp-files",{"aria-label":"Files"});for(let z of P){let se=m("button.itp-btn.small.icon",{type:"button","aria-label":`Options for ${z.name}`,"aria-haspopup":"menu",title:"Settings, duplicate, order",html:Q("more"),onclick:ee=>{ee.stopPropagation(),y(z,se)}}),de=z.type==="video"?`Video, ${yn(z.duration)}`:`${z.width} \xD7 ${z.height}`,oe=m("li.itp-file-row",{tabindex:"0","aria-current":String(e.current===z),"data-own":z.own?"true":null},m("img.thumb",{src:z.thumb||"",alt:""}),m("div",{style:{minWidth:0}},m("div.title",{text:z.name}),m("div.sub",{},de,z.own?m("span.itp-own",{title:"This file has its own settings",html:`${Q("unlink")}<span>Own</span>`}):null)),m("div.actions",{},se,m("button.itp-btn.small.icon.danger",{type:"button","aria-label":`Remove ${z.name}`,title:"Remove",html:Q("x"),onclick:ee=>{ee.stopPropagation(),e.removeItem(z)}})));oe.addEventListener("click",()=>e.select(z)),oe.addEventListener("dblclick",ee=>{ee.target.closest(".title")&&e.startRename(z)}),oe.addEventListener("contextmenu",ee=>{ee.preventDefault(),e.select(z),y(z,se)}),oe.addEventListener("keydown",ee=>{ee.target===oe&&((ee.key==="Enter"||ee.key===" ")&&(ee.preventDefault(),e.select(z)),(ee.key==="Delete"||ee.key==="Backspace")&&(ee.preventDefault(),e.removeItem(z)),!ee.altKey&&(ee.key==="ArrowDown"&&(ee.preventDefault(),oe.nextElementSibling?.focus()),ee.key==="ArrowUp"&&(ee.preventDefault(),oe.previousElementSibling?.focus()),(ee.key==="ContextMenu"||ee.key==="F10"&&ee.shiftKey)&&(ee.preventDefault(),y(z,se))))}),R.append(oe)}let j=e.items.filter(z=>z.own).length,C=e.items.length?e.items.length===1?"1 file":j?`${e.items.length} files, ${j} with ${j===1?"its":"their"} own settings`:`${e.items.length} files, shared settings`:"No files yet",D=m("div.itp-group",{},m("span",{text:C}),e.items.length>1?m("button.itp-link",{type:"button",text:"Clear",onclick:()=>e.clearItems()}):null),F=m("div",{style:{padding:"4px 12px 12px",display:"flex",gap:"6px"}},m("button.itp-btn.outline.small",{type:"button",html:`${Q("plus")}<span>Add files</span>`,onclick:()=>e.openFiles()}),m("button.itp-btn.small",{type:"button",html:`${Q("clipboard")}<span>Paste</span>`,title:"Paste an image from the clipboard (Ctrl+V)",onclick:()=>e.pasteFromClipboard()})),I=e.savedWorkspace&&e.savedWorkspace(),N=I?m("div.itp-group.itp-saved",{},m("span",{text:`Saved in this browser: ${I.count} file${I.count===1?"":"s"}`,title:"Kept in this browser's storage, never uploaded. Clearing the site's data also removes it."}),m("button.itp-link",{type:"button",text:"Forget",title:"Remove the saved files from this browser",onclick:()=>e.forgetWorkspace()})):null;st(l,D,R,F,N,m("div.itp-group",{},m("span",{text:"Drop images or videos anywhere in the window. Files share one set of settings unless you give one its own (\u22EF menu or right-click). Save keeps them in this browser for next time."})))}let v=new Map,M=0;function x(){let P=e.store.settings,R=dn.filter(C=>!h()||(C.name+C.description).toLowerCase().includes(h())),j=m("div.itp-presets",{});for(let C of R){let D=e.activePreset===C.id,F=v.get(C.id)||m("div.ph",{}),I=m("button.itp-preset",{type:"button","aria-pressed":String(D),title:C.description,onclick:()=>e.applyPreset(C)},F,m("span.t",{text:C.name}),m("span.d",{text:C.description}));j.append(I)}st(l,m("div.itp-group",{},m("span",{text:"Presets replace the current settings. Undo with Ctrl+Z."})),j)}async function S(){let P=++M,R=e.current;if(!(!R||!e.engine))for(let j of dn){if(P!==M)return;let C=Lt(Et(),j.settings);C.size={...C.size,mode:"width",width:Math.min(C.size.width,72),height:0};try{let D=await e.engine.process(R.source,C);if(P!==M)return;let F=D.toCanvas(1);v.set(j.id,F),t==="presets"&&x()}catch{}}}function b(P,R,j){let C=m("div.itp-strip",{},...P.colors.slice(0,64).map(I=>m("i",{style:{background:I.startsWith("#")?I:"#"+I}}))),D=m("li.itp-pal",{tabindex:"0",role:"button","aria-pressed":String(R)},m("div.row",{},m("span",{text:P.name}),m("span.n",{text:String(P.colors.length),title:P.author?`by ${P.author}`:null})),C),F=()=>e.usePalette(P);if(D.addEventListener("click",F),D.addEventListener("keydown",I=>{(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),F()),j&&I.key==="Delete"&&e.deletePalette(P)}),j){let I=m("button.itp-btn.small.icon.danger",{type:"button","aria-label":`Delete ${P.name}`,title:"Delete",html:Q("trash"),onclick:N=>{N.stopPropagation(),e.deletePalette(P)}});D.firstChild.append(I)}return D}function _(){let P=e.store.settings.palette,R=I=>!h()||(I.name+" "+(I.author||"")).toLowerCase().includes(h())||String(I.colors.length)===h(),j=e.userPalettes.filter(R),C=an.filter(R),D=m("div",{style:{padding:"0 12px 4px",display:"flex",gap:"6px",flexWrap:"wrap"}},m("button.itp-btn.outline.small",{type:"button",html:`${Q("upload")}<span>Import file</span>`,onclick:()=>e.importPalette()}),m("button.itp-btn.small",{type:"button",html:`${Q("palette")}<span>From Lospec</span>`,onclick:()=>e.lospecDialog()})),F=j.length?[m("div.itp-group",{},m("span",{text:"Your palettes"}),m("span.itp-badge",{text:String(j.length)})),m("ul.itp-pal-list",{},...j.map(I=>b(I,P.source==="custom"&&P.name===I.name,!0)))]:[];st(l,D,...F,m("div.itp-group",{},m("span",{text:"Built-in"}),m("span.itp-badge",{text:String(C.length)})),m("ul.itp-pal-list",{},...C.map(I=>b({...I,colors:I.colors.map(N=>"#"+N)},P.source==="builtin"&&P.id===I.id,!1))))}function L(){a.textContent=e.items.length?String(e.items.length):"",t==="files"?E():t==="presets"?x():_()}return{el:p,refresh:L,setTab:f,focusFile(P){t==="files"&&l.querySelectorAll(".itp-file-row")[e.items.indexOf(P)]?.focus()},sourceChanged(){v.clear(),M++,t==="presets"&&(L(),S())},get tab(){return t}}}function yn(e=0){let t=Math.floor(e/60),n=e-t*60;return`${t}:${n.toFixed(1).padStart(4,"0")}`}var nc=`<svg xmlns="http://www.w3.org/2000/svg" width="960" height="640" viewBox="0 0 960 640">
|
|
306
306
|
<defs>
|
|
307
307
|
<linearGradient id="sky" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#1d1a3f"/><stop offset=".45" stop-color="#6b3f7c"/><stop offset=".72" stop-color="#e0766a"/><stop offset=".86" stop-color="#f6c27a"/></linearGradient>
|
|
308
308
|
<radialGradient id="sun" cx=".5" cy=".5" r=".5"><stop offset="0" stop-color="#fff4d6"/><stop offset=".35" stop-color="#ffd98a"/><stop offset=".6" stop-color="#ffb46a" stop-opacity=".55"/><stop offset="1" stop-color="#ff9a6a" stop-opacity="0"/></radialGradient>
|
|
@@ -324,7 +324,7 @@ void main() {
|
|
|
324
324
|
<path d="M0 470 L140 430 L260 455 L380 425 L520 462 L660 432 L800 458 L960 436 V480 H0Z" fill="#120d22" opacity=".9"/>
|
|
325
325
|
<path d="M60 640 C120 560 180 560 240 640Z" fill="#0d0a1a"/><path d="M780 640 C840 575 900 560 960 600 V640Z" fill="#0d0a1a"/>
|
|
326
326
|
<g fill="none" stroke="#2a1b38" stroke-width="3" stroke-linecap="round"><path d="M300 170 q10 -10 20 0 q10 -10 20 0"/><path d="M350 200 q7 -7 14 0 q7 -7 14 0"/><path d="M262 210 q6 -6 12 0 q6 -6 12 0"/></g>
|
|
327
|
-
</svg>`,
|
|
327
|
+
</svg>`,oc=`<svg xmlns="http://www.w3.org/2000/svg" width="900" height="680" viewBox="0 0 900 680">
|
|
328
328
|
<defs>
|
|
329
329
|
<linearGradient id="wall" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#2f3b45"/><stop offset="1" stop-color="#1a2129"/></linearGradient>
|
|
330
330
|
<linearGradient id="table" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#9a6a45"/><stop offset="1" stop-color="#4c2f1f"/></linearGradient>
|
|
@@ -354,7 +354,7 @@ void main() {
|
|
|
354
354
|
<ellipse cx="690" cy="530" rx="80" ry="56" fill="url(#lemon)"/>
|
|
355
355
|
<circle cx="370" cy="560" r="44" fill="url(#plum)"/>
|
|
356
356
|
<circle cx="780" cy="585" r="34" fill="url(#plum)"/>
|
|
357
|
-
</svg>`,
|
|
357
|
+
</svg>`,rc=`<svg xmlns="http://www.w3.org/2000/svg" width="560" height="560" viewBox="0 0 560 560">
|
|
358
358
|
<defs>
|
|
359
359
|
<radialGradient id="glass" cx=".38" cy=".35" r=".7"><stop offset="0" stop-color="#e8fbff" stop-opacity=".9"/><stop offset=".5" stop-color="#9fd8f0" stop-opacity=".55"/><stop offset="1" stop-color="#3a6f9e" stop-opacity=".85"/></radialGradient>
|
|
360
360
|
<linearGradient id="liquid" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#ff7ad1"/><stop offset=".6" stop-color="#b8248f"/><stop offset="1" stop-color="#5d0e4c"/></linearGradient>
|
|
@@ -368,7 +368,7 @@ void main() {
|
|
|
368
368
|
<path d="M160 300 C180 262 214 240 250 228" stroke="#ffffff" stroke-width="16" stroke-linecap="round" fill="none" opacity=".75"/>
|
|
369
369
|
<path d="M150 340 v12" stroke="#ffffff" stroke-width="16" stroke-linecap="round" opacity=".6"/>
|
|
370
370
|
<path d="M240 156 V210 C150 240 104 310 104 380 C104 470 182 520 280 520 C378 520 456 470 456 380 C456 310 410 240 320 210 V156Z" fill="none" stroke="#1d3150" stroke-width="10"/>
|
|
371
|
-
</svg>`,zn=[{id:"dusk",name:"Dusk",svg:vs},{id:"still-life",name:"Still life",svg:Es},{id:"potion",name:"Potion (transparent)",svg:ks}],wo=e=>"data:image/svg+xml;charset=utf-8,"+encodeURIComponent(e.svg);async function pi(e){let t=new Image;return t.src=wo(e),await t.decode(),t}var hi=/^image\//,mi=/^video\//,Ms=/\.(gpl|hex|pal|txt|json)$/i;async function Bl(e,t={}){let n=t.persist!==!1,o=()=>matchMedia("(max-width: 900px)").matches,i=t.settings||n&&Pt("settings",null)||xt();if(/[#&]s=/.test(location.hash))try{i=Hn(location.hash)}catch{W("That share link could not be read; using your last settings",{kind:"error"})}let r=Xr(i),a={store:r,engine:null,items:[],current:null,result:null,exporting:!1,activePreset:null,userPalettes:n?Pt("palettes",[]):[],shared:r.settings,clipboard:null,videoSupport:{mp4:!1,webm:!1},toast:(p,M)=>W(p,M)},c=Wr({onPick:He,onViewChange:()=>De()}),l=ui(a),s=fi(a),d=ci(a),f=(p,M,_,F={})=>m("button.itp-btn.icon",{type:"button","aria-label":M,title:M,html:Y(p),onclick:_,...F}),u=m("span.name",{text:"No image"}),h=m("span.meta.num",{}),x=f("undo","Undo (Ctrl+Z)",()=>r.undo()),E=f("redo","Redo (Ctrl+Shift+Z)",()=>r.redo()),y=f("compare","Compare with original (C)",()=>Ze(),{"aria-pressed":"false"}),k=f("grid","Pixel grid (G)",()=>kt(),{"aria-pressed":"false"}),b=m("button.itp-btn.itp-zoom.num",{type:"button","aria-label":"Zoom","aria-haspopup":"menu",html:`<span>Fit</span>${Y("chevronDown")}`,onclick:p=>Ut(p.currentTarget)}),S=f("moon","Toggle theme (T)",()=>pt()),w=f("sidebarLeft","Toggle library (\\)",()=>Je("lib")),A=f("sidebarRight","Toggle inspector (/)",()=>Je("insp")),L=f("keyboard","Keyboard shortcuts (?)",()=>Mt()),T=m("button.itp-btn.primary",{type:"button","aria-haspopup":"menu",html:`${Y("download")}<span>Export</span>`,onclick:p=>Ft(p.currentTarget)}),P=m("a.itp-brand",{href:t.homeHref||"#",title:"Image-to-Pixel"},m("span.itp-mark",{"aria-hidden":"true"},...Array.from({length:9},()=>m("i"))),m("span.hide-sm",{text:"Image-to-Pixel"}));t.homeHref||P.addEventListener("click",p=>p.preventDefault());let z=m("header.itp-top",{},w,P,m("span.sep.hide-sm"),m("div.itp-file",{},u,h),m("div.spacer"),m("span.hide-sm.contents",{},x,E,m("span.sep")),y,k,b,m("span.sep.hide-sm"),m("span.hide-sm.contents",{},S,L),A,m("span",{style:{width:"6px"}}),T),v=t.samples===!1?null:m("div.samples",{},...zn.map(p=>m("button",{type:"button",title:`Try "${p.name}"`,"aria-label":`Open sample: ${p.name}`,onclick:()=>Ge(p)},m("img",{src:wo(p),alt:""})))),I=m("div.itp-empty",{},m("div.itp-drop",{},m("h2",{text:"Drop an image or a video"}),m("p",{text:"PNG, JPG, WebP, GIF, SVG, MP4 or WebM. Add several files to process them as a batch. You can also paste with Ctrl+V."}),m("div.actions",{},m("button.itp-btn.primary",{type:"button",html:`${Y("upload")}<span>Choose files</span>`,onclick:()=>qe()}),m("button.itp-btn.outline",{type:"button",html:`${Y("clipboard")}<span>Paste</span>`,onclick:()=>Lt()})),v?m("p",{style:{fontSize:"var(--fs-xs)",color:"var(--faint)"},text:"Or start from a sample"}):null,v)),D=m("div.itp-float.bl",{"aria-live":"polite"}),U=m("div.itp-busy.itp-float",{hidden:!0,style:{padding:"6px 10px",alignItems:"center",gap:"8px",fontSize:"var(--fs-xs)",color:"var(--muted)",display:"flex"}},m("span.itp-spinner"),m("span",{text:"Rendering"})),B=m("div.itp-float.br",{},f("zoomOut","Zoom out (-)",()=>c.zoomOut()),f("fit","Fit to view (F)",()=>c.fit()),f("zoomIn","Zoom in (+)",()=>c.zoomIn()));c.el.append(I,D,U,B);let H=f("play","Play (Space)",()=>Ke()),V=m("span.itp-time",{}),G=m("input.itp-scrub",{type:"range",min:0,max:1e3,value:0,"aria-label":"Video position"}),ce=m("span.muted.num",{style:{fontSize:"var(--fs-xs)",whiteSpace:"nowrap"}}),be=m("div.itp-transport",{role:"group","aria-label":"Video"},f("stepBack","Previous frame (,)",()=>rt(-1)),H,f("stepForward","Next frame (.)",()=>rt(1)),V,G,ce),Te=m("main.itp-stage",{"data-video":"false"},c.el,be);Te.addEventListener("pointerdown",()=>{o()&&se.dataset.lib==="open"&&Je("lib")},!0);let se=m("div.itp.itp-app",{"data-lib":o()?"closed":Pt("lib","open"),"data-insp":Pt("insp","open")},z,s.el,Te,l.el);tt(e,se),ft(Pt("theme",null)),D.textContent="Starting\u2026";try{a.engine=await Ur()}catch(p){throw W(`Could not start: ${p.message}`,{kind:"error"}),p}l.el.querySelector("#itp-backend").textContent=a.engine.backend==="webgl"?"GPU \xB7 ShaderMate":"CPU",l.el.querySelector("#itp-backend").title=a.engine.backend==="webgl"?`WebGL 2: ${a.engine.renderer}`:a.engine.fallbackReason||"CPU renderer",Promise.resolve().then(()=>(xo(),bo)).then(p=>p.videoSupport()).then(p=>{a.videoSupport=p}).catch(()=>{});let ae=!1,he=!1,Fe=null,Ee=document.createElement("canvas");function me(){ae=!0,he||requestAnimationFrame(Xe)}a.schedule=me;async function Xe(){if(he||!ae||a.exporting)return;ae=!1;let p=a.current;if(!p){a.result=null,c.clear(),Ve();return}he=!0;let M=setTimeout(()=>{U.hidden=!1},250);try{p.type==="video"&&a.engine.invalidate();let _=await a.engine.process(p.source,r.settings);if(p!==a.current)return;a.result=_,_.toCanvas(1,{canvas:Ee}),c.show(Ee,p.source,_.crop),l.setStats(_),l.sync(r.settings,_),Fe!==p&&(Fe=p),Ve()}catch(_){console.error(_),W(`Rendering failed: ${_.message}`,{kind:"error"})}finally{clearTimeout(M),U.hidden=!0,he=!1,ae&&requestAnimationFrame(Xe)}}function Ve(){let p=a.result,M=a.current;if(u.textContent=M?M.name:"No image",h.textContent=M?M.type==="video"?`${M.width} \xD7 ${M.height}, ${pn(M.duration)}`:`${M.width} \xD7 ${M.height}`:"",I.hidden=!!M,B.hidden=!M,!M||!p){D.hidden=!0;return}D.hidden=!1,tt(D,m("span",{},m("b",{text:`${p.width} \xD7 ${p.height}`})," px"),m("span",{text:`${Math.round(c.zoom*100)/100}\xD7 zoom`})),x.disabled=!r.canUndo,E.disabled=!r.canRedo}function De(){b.querySelector("span").textContent=!a.current||c.fitted?"Fit":c.zoom>=1?`${Math.round(c.zoom*10)/10}\xD7`:`${Math.round(c.zoom*100)}%`,a.result&&Ve()}r.subscribe((p,M)=>{let _=a.current;_&&_.own&&r.target===_.id?_.own=p:r.target==="shared"&&(a.shared=p),l.sync(p,a.result),x.disabled=!r.canUndo,E.disabled=!r.canRedo,M!=="preset"&&(a.activePreset=null),n&&_e(),s.tab==="palettes"&&s.refresh(),me()});let We=null,_e=()=>{clearTimeout(We),We=setTimeout(()=>vt("settings",a.shared),300)};async function ke(p,M,_){let F=document.createElement("canvas"),X=72/Math.max(M,_);F.width=Math.max(1,Math.round(M*X)),F.height=Math.max(1,Math.round(_*X));try{F.getContext("2d").drawImage(p,0,0,F.width,F.height)}catch{}return F.toDataURL()}async function le(p,M,_=null){let F=M.naturalWidth||M.width,X=M.naturalHeight||M.height,ne={id:crypto.randomUUID?.()||String(Math.random()),name:p,type:"image",source:M,width:F,height:X,file:_};return ne.thumb=await ke(M,F,X),a.items.push(ne),ne}async function nt(p,M){let _=m("video",{muted:!0,playsInline:!0,loop:!0,preload:"auto",crossOrigin:"anonymous"});_.muted=!0,_.src=URL.createObjectURL(M);try{await en(_)}catch(X){if(URL.revokeObjectURL(_.src),X.code===3||X.code===4){let ne=await Gr(M).catch(()=>""),ie=ne==="H.264"?"WebM (VP9)":ne==="VP9"?"H.264 MP4":"H.264 MP4 or WebM (VP9)",te=new Error(ne?`it's ${ne}, which this browser can't play. Re-save it as ${ie}, or open the editor in a browser that plays ${ne}.`:`this browser can't play this video's format. Re-save it as ${ie}.`);throw te.code=X.code,te}throw X}let F={id:crypto.randomUUID?.()||String(Math.random()),name:p,type:"video",source:_,width:_.videoWidth,height:_.videoHeight,duration:_.duration,fps:30,file:M};return await Gt(_,Math.min(.05,_.duration/2)).catch(()=>{}),F.thumb=await ke(_,F.width,F.height),a.items.push(F),Pn(_,30).then(X=>{F.fps=X,a.current===F&&Le(),l.syncAnim()}),_.addEventListener("timeupdate",()=>{a.current===F&&Le()}),_.addEventListener("play",()=>{a.current===F&&(Le(),Rt(F))}),_.addEventListener("pause",()=>{a.current===F&&(Le(),me())}),_.addEventListener("seeked",()=>{a.current===F&&!a.exporting&&me()}),F}async function Ae(p){let M=[],_=[],F=[];for(let ie of p)Ms.test(ie.name)&&!/^image|^video/.test(ie.type)?/\.json$/i.test(ie.name)?F.push(ie):_.push(ie):(hi.test(ie.type)||mi.test(ie.type)||/\.(png|jpe?g|gif|webp|bmp|svg|avif|mp4|webm|mov)$/i.test(ie.name))&&M.push(ie);for(let ie of _)await ze(ie);for(let ie of F){let te=await ie.text();try{let fe=JSON.parse(te);fe.colors||Array.isArray(fe)?await ze(ie,te):(r.replace(Xn(fe)),W(`Loaded settings from ${ie.name}`,{kind:"ok"}))}catch(fe){W(`${ie.name}: ${fe.message}`,{kind:"error"})}}let X=null,ne=M.length>2?W(`Loading ${M.length} files`,{progress:!0}):null;for(let ie=0;ie<M.length;ie++){let te=M[ie];try{let fe;if(mi.test(te.type)||/\.(mp4|webm|mov)$/i.test(te.name))fe=await nt(te.name,te);else{let C;try{C=await createImageBitmap(te)}catch{C=new Image,C.src=URL.createObjectURL(te),await C.decode()}fe=await le(te.name,C,te)}X||(X=fe)}catch(fe){W(`${te.name} could not be opened: ${fe.message}`,{kind:"error"})}ne?.progress((ie+1)/M.length)}ne?.close(),X&&Oe(X),s.refresh(),M.length>1&&W(`Added ${M.length} files. They share one set of settings.`,{kind:"ok"})}a.addFiles=Ae;async function qe(){let p=await Un({accept:"image/*,video/*,.gpl,.hex,.pal,.txt,.json",multiple:!0});p.length&&Ae(p)}a.openFiles=qe;async function Ge(p){let M=await pi(p),_=await le(`${p.name}.svg`,M);Oe(_),s.refresh()}async function Lt(){try{let p=await navigator.clipboard.read(),M=[];for(let _ of p)for(let F of _.types)if(hi.test(F)){let X=await _.getType(F);M.push(new File([X],`pasted-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.${F.split("/")[1]}`,{type:F}))}M.length?Ae(M):W("The clipboard has no image",{kind:"error"})}catch{W("Press Ctrl+V (\u2318V) to paste. The browser blocked direct clipboard access.")}}a.pasteFromClipboard=Lt;function Oe(p){a.current&&a.current.type==="video"&&a.current!==p&&a.current.source.pause(),a.current=p,ge(p),Te.dataset.video=String(p&&p.type==="video"),p&&p.type==="video"&&Le(),c.clear(),a.result=null,c.picking&&$e(),s.refresh(),s.sourceChanged(),me(),Ve()}a.select=Oe;function ot(p){let M=a.items.indexOf(p);M<0||(a.items.splice(M,1),r.dropTarget(p.id),p.type==="video"&&(p.source.pause(),URL.revokeObjectURL(p.source.src)),p.source.close&&!a.items.some(_=>_.source===p.source)&&p.source.close(),a.current===p&&Oe(a.items[Math.min(M,a.items.length-1)]||null),s.refresh(),l.sync(r.settings,a.result))}a.removeItem=ot,a.clearItems=()=>{for(let p of a.items.slice())ot(p)};let Ye=p=>p===a.current?r.settings:p&&p.own||a.shared;a.settingsFor=Ye;let Pe=p=>JSON.parse(JSON.stringify(p));function ge(p,M=!1){let _=p&&p.own?p.id:"shared";r.target===_&&!M||r.setTarget(_,_==="shared"?a.shared:p.own)}function je(p,M,{quiet:_=!1}={}){if(!(!p||!!p.own===M)){if(M)p.own=Pe(Ye(p)),p===a.current&&ge(p),_||W(`${p.name} now has its own settings. Changes no longer affect other files.`);else{let F=p.own;p.own=null,r.dropTarget(p.id),p===a.current&&ge(p),_||W(`${p.name} uses the shared settings again`,{action:{label:"Undo",onClick:()=>{p.own=F,p===a.current&&ge(p),we()}}})}we()}}function we(){s.refresh(),l.sync(r.settings,a.result),a.result&&l.setStats(a.result),me()}a.setOwn=je,a.copySettings=p=>{a.clipboard=Pe(Ye(p)),W(`Copied the settings of ${p.name}`,{timeout:1800}),s.refresh()},a.pasteSettings=p=>{a.clipboard&&(p.own||je(p,!0,{quiet:!0}),p===a.current?r.replace(a.clipboard,"paste"):p.own=Pe(a.clipboard),W(`Pasted settings onto ${p.name}`,{kind:"ok",timeout:1800}),we())},a.applyToAll=p=>{let M={shared:a.shared,own:new Map(a.items.map(_=>[_,_.own]))};a.shared=Pe(Ye(p));for(let _ of a.items)_.own&&r.dropTarget(_.id),_.own=null;r.setTarget("shared",a.shared),n&&_e(),W(`Every file now uses the settings of ${p.name}`,{action:{label:"Undo",onClick:()=>{a.shared=M.shared;for(let[_,F]of M.own)_.own=F;ge(a.current,!0),we()}}}),we()},a.duplicate=async p=>{let M;p.type==="video"?M=await nt(Et(p.name),p.file):M=await le(Et(p.name),p.source,p.file),a.items.splice(a.items.indexOf(M),1),a.items.splice(a.items.indexOf(p)+1,0,M),M.own=Pe(Ye(p)),Oe(M),W(`Duplicated ${p.name}. The copy has its own settings.`,{timeout:2400})};let Et=p=>{let M=/^(.*?)(\.[^.]*)?$/.exec(p);return`${M[1]} copy${M[2]||""}`};a.move=(p,M)=>{let _=a.items.indexOf(p),F=_+M;_<0||F<0||F>=a.items.length||([a.items[_],a.items[F]]=[a.items[F],a.items[_]],s.refresh(),(document.activeElement===document.body||document.activeElement?.closest?.(".itp-files"))&&s.focusFile(p))};function Le(){let p=a.current;if(!p||p.type!=="video")return;let M=p.source;H.innerHTML=Y(M.paused?"play":"pause"),H.setAttribute("aria-label",M.paused?"Play (Space)":"Pause (Space)");let _=Math.floor(M.currentTime*p.fps+1e-6);V.innerHTML=`${pn(M.currentTime)} <span>/ ${pn(M.duration)}</span>`,V.title=`Frame ${_}`,G.value=String(Math.round(M.currentTime/(M.duration||1)*1e3)),G.style.setProperty("--p",`${G.value/10}%`),ce.textContent=`${p.fps} fps`}function Rt(p){let M=p.source,_=()=>{M.paused||a.current!==p||(me(),"requestVideoFrameCallback"in M?M.requestVideoFrameCallback(_):requestAnimationFrame(_))};_()}function Ke(){let p=a.current;!p||p.type!=="video"||(p.source.paused?p.source.play().catch(M=>W(M.message,{kind:"error"})):p.source.pause())}function rt(p){let M=a.current;if(!M||M.type!=="video")return;let _=M.source;_.pause();let F=Math.floor(_.currentTime*M.fps+1e-6)+p;Gt(_,(Math.max(0,F)+.5)/M.fps).then(()=>{Le(),me()})}G.addEventListener("input",()=>{let p=a.current;!p||p.type!=="video"||(p.source.currentTime=G.value/1e3*p.source.duration)});function Ze(p){let M=p??!c.compare;c.setCompare(M),y.setAttribute("aria-pressed",String(M))}function kt(p){let M=p??!c.grid;c.setGrid(M),k.setAttribute("aria-pressed",String(M)),M&&c.zoom<6&&a.result&&W("The grid shows from 6\xD7 zoom")}function Ut(p){un(p,[{label:"Fit to view",kbd:"F",icon:"fit",onClick:()=>c.fit()},"sep",...[1,2,4,8,16,32].map(M=>({label:`${M}\xD7`,sub:M===1?"One screen pixel per pixel":null,onClick:()=>c.zoomTo(M)})),"sep",{label:"Zoom in",kbd:"+",icon:"zoomIn",onClick:()=>c.zoomIn()},{label:"Zoom out",kbd:"-",icon:"zoomOut",onClick:()=>c.zoomOut()}])}function Je(p){let M=p==="lib"?"lib":"insp",_=se.dataset[M]!=="open";se.dataset[M]=_?"open":"closed",(!o()||p==="insp")&&vt(M,se.dataset[M]),requestAnimationFrame(()=>c.resize())}function ft(p){p?document.documentElement.dataset.theme=p:delete document.documentElement.dataset.theme;let M=p?p==="dark":!matchMedia("(prefers-color-scheme: light)").matches;S.innerHTML=Y(M?"sun":"moon"),S.setAttribute("aria-label",M?"Switch to light theme (T)":"Switch to dark theme (T)"),c.redraw()}function pt(){let M=(document.documentElement.dataset.theme||(matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"))==="dark"?"light":"dark";vt("theme",M),ft(M)}function It(p,M=4096){let _=p.width,F=p.height,X=Math.min(1,M/Math.max(_,F)),ne=document.createElement("canvas");ne.width=Math.round(_*X),ne.height=Math.round(F*X);let ie=ne.getContext("2d",{willReadFrequently:!0});return ie.drawImage(p.source,0,0,ne.width,ne.height),ie.getImageData(0,0,ne.width,ne.height)}function He(p,M){let _=a.current;if(!_)return;let F=It(_,1024),X=a.result?a.result.crop:{x:0,y:0,w:1,h:1},ne=Math.min(F.width-1,Math.floor((X.x+p*X.w)*F.width)),te=(Math.min(F.height-1,Math.floor((X.y+M*X.h)*F.height))*F.width+ne)*4,fe=Ot([F.data[te],F.data[te+1],F.data[te+2]]),C=r.settings,R=C.palette.source==="custom"?C.palette.colors:[];if(R.includes(fe))return W(`${fe} is already in the palette`);r.update({palette:{source:"custom",name:C.palette.source==="custom"?C.palette.name:"Picked",colors:[...R,fe]}}),W(`Added ${fe}`,{kind:"ok",timeout:1500})}let it=null;function $e(p){p&&(it=p);let M=!c.picking;c.setPicking(M),it?.setAttribute("aria-pressed",String(M)),M&&(Ze(!0),W("Click the image to add colours. Press Esc when done."))}a.togglePicker=$e;function at(p){p.id&&!p.custom?r.update({palette:{source:"builtin",id:p.id}}):r.update({palette:{source:"custom",name:p.name,colors:p.colors}})}a.usePalette=at;function Re(p,M){let _=a.userPalettes.filter(F=>F.name!==p);_.unshift({name:p,colors:M,custom:!0}),a.userPalettes=_.slice(0,100),n&&vt("palettes",a.userPalettes),s.tab==="palettes"&&s.refresh()}async function ze(p,M){try{let _=ao(M??await p.text(),p.name);Re(_.name||"Imported",_.colors),r.update({palette:{source:"custom",name:_.name||"Imported",colors:_.colors}}),W(`Imported "${_.name}" (${_.colors.length} colours)`,{kind:"ok"})}catch(_){W(`${p.name}: ${_.message}`,{kind:"error"})}}a.importPalette=async()=>{let[p]=await Un({accept:".gpl,.hex,.pal,.txt,.json"});p&&ze(p)},a.savePalette=()=>{let p=r.settings,M=p.palette.source==="extract"?a.result?.palette||[]:p.palette.colors;if(!M.length)return W("There is no palette to save",{kind:"error"});let _=m("input.itp-input",{value:p.palette.source==="custom"?p.palette.name:`${p.palette.name} copy`,"aria-label":"Palette name"}),F=m("select.itp-select",{"aria-label":"Also download as"},m("option",{value:"",text:"Don't download"}),m("option",{value:"gpl",text:".gpl (GIMP, Aseprite)"}),m("option",{value:"hex",text:".hex (Lospec)"}),m("option",{value:"json",text:".json"}));fn("Save palette",[m("div.itp-field",{},m("div.lab",{},m("span",{text:"Name"})),_),m("div.itp-field",{},m("div.lab",{},m("span",{text:"Also download as"})),F),m("div.itp-strip",{style:{height:"18px"}},...M.map(X=>m("i",{style:{background:X}})))],{actions:[{label:"Cancel"},{label:"Save",primary:!0,onClick:()=>{let X=_.value.trim()||"Palette";Re(X,M),r.update({palette:{source:"custom",name:X,colors:M}});let ne=X.replace(/[^\w-]+/g,"-").toLowerCase();F.value==="gpl"&&Be(Fr(X,M),`${ne}.gpl`,"text/plain"),F.value==="hex"&&Be(Dr(M),`${ne}.hex`,"text/plain"),F.value==="json"&&Be(Or(X,M),`${ne}.json`,"application/json"),W(`Saved "${X}" to Your palettes`,{kind:"ok"})}}]}),_.select()},a.deletePalette=p=>{a.userPalettes=a.userPalettes.filter(M=>M!==p),n&&vt("palettes",a.userPalettes),s.refresh(),W(`Deleted "${p.name}"`,{action:{label:"Undo",onClick:()=>Re(p.name,p.colors)}})},a.lospecDialog=()=>{let p=m("input.itp-input",{placeholder:"e.g. rgbg-36 or a lospec.com palette URL","aria-label":"Lospec slug or URL"}),M=m("div.help",{text:"Looks the palette up on lospec.com. Needs an internet connection."}),_=fn("Palette from Lospec",[m("div.itp-field",{},m("div.lab",{},m("span",{text:"Slug or URL"})),p,M)],{actions:[{label:"Cancel"},{label:"Fetch",primary:!0,onClick:async()=>{M.textContent="Fetching\u2026",M.style.color="";try{let F=await $r(p.value);return Re(F.name,F.colors),r.update({palette:{source:"custom",name:F.name,colors:F.colors}}),W(`Loaded "${F.name}" from Lospec`,{kind:"ok"}),!0}catch(F){return M.textContent=F.message,M.style.color="var(--danger)",!1}}}]});p.addEventListener("keydown",F=>{F.key==="Enter"&&_.querySelector("footer .primary").click()}),p.focus()},a.detectGrid=()=>{let p=a.current;if(!p||p.type!=="image")return W("Open an image first",{kind:"error"});let M=Lr(It(p));if(M<=1)return W("No pixel grid found. This image doesn't look upscaled.");r.update({size:{mode:"block",block:M,resample:"nearest"}}),W(`Found ${M} px blocks: switched to pixel size ${M} with nearest sampling`,{kind:"ok"})},a.settingsJSON=()=>Zt(r.settings),a.copyLink=async()=>{let p=`${location.origin}${location.pathname}#s=${jn(r.settings)}`;try{await navigator.clipboard.writeText(p),W("Link copied. It holds the settings, not the image.",{kind:"ok"})}catch{fn("Share link",[m("textarea.itp-input",{rows:3,readOnly:!0,value:p})])}history.replaceState(null,"",`#s=${jn(r.settings)}`)},a.saveSettingsFile=()=>Be(Zt(r.settings),"image-to-pixel-settings.json","application/json"),a.loadSettingsFile=async()=>{let[p]=await Un({accept:".json,application/json"});if(p)try{r.replace(Xn(await p.text())),W(`Loaded ${p.name}`,{kind:"ok"})}catch(M){W(`${p.name}: ${M.message}`,{kind:"error"})}},a.resetSettings=()=>{r.replace(xt()),W("Settings reset",{action:{label:"Undo",onClick:()=>r.undo()}})},a.applyPreset=p=>{r.replace(Tt(xt(),{...p.settings,export:r.settings.export}),"preset"),a.activePreset=p.id,s.refresh()},Object.assign(a,d);function Ft(p){let M=a.current,_=M&&M.type==="video",F=a.items.filter(ne=>ne.type==="image").length,X=r.settings;un(p,[{group:"Image"},{label:"PNG",sub:a.result?`${a.result.width*X.export.scale} \xD7 ${a.result.height*X.export.scale}, ${X.export.scale}\xD7 scale`:"Open an image first",icon:"image",kbd:"Ctrl S",disabled:!a.result,onClick:()=>a.exportPNG()},{label:"Copy to clipboard",icon:"copy",disabled:!a.result,onClick:()=>a.copyImage()},{label:a.items.length>1?`All ${a.items.length} files as ZIP`:"All files as ZIP",sub:a.items.length>1?null:"Add two or more files",icon:"zip",disabled:a.items.length<2,onClick:()=>a.exportZip()},{group:"Animation"},{label:_?"GIF from this video":"GIF from all images",icon:"gif",disabled:!_&&F<2,onClick:()=>a.exportAnimation({...Yt(),format:"gif"})},{label:"More formats\u2026",sub:"WebM, MP4, PNG sequence, sprite sheet",icon:"film",onClick:()=>{l.setTab("export"),se.dataset.insp!=="open"&&Je("insp")}},{group:"Other"},{label:"Tileset",sub:"16 \xD7 16 tiles, duplicates removed",icon:"tiles",disabled:!a.result,onClick:()=>a.exportTileset({tile:16,flips:!1})},{label:"Copy settings link",icon:"link",onClick:()=>a.copyLink()},{label:"Settings as JSON",icon:"braces",onClick:()=>a.saveSettingsFile()}])}let Yt=()=>{let p=a.current,M=p&&p.type==="video";return{source:M?"video":"files",fps:M?Math.min(30,Math.round(p.fps||12)):8,start:0,end:M?p.duration:0}};function Mt(){fn("Keyboard shortcuts",[m("div.itp-keys",{},...[["Open files","Ctrl O"],["Paste image","Ctrl V"],["Export PNG","Ctrl S"],["Undo","Ctrl Z"],["Redo","Ctrl Shift Z"],["Compare","C"],["Pixel grid","G"],["Fit","F"],["Zoom in / out","+ -"],["Pixel width \xB11","[ ]"],["Pixel width \xB18","Shift [ ]"],["Next / previous dither","D Shift D"],["Play / pause video","Space"],["Step one frame",", ."],["Library","\\"],["Inspector","/"],["Theme","T"],["Next / previous file","Alt \u2193 \u2191"],["Move file down / up","Alt Shift \u2193 \u2191"],["This list","?"]].map(([M,_])=>m("div",{},m("span",{text:M}),m("span",{},..._.split(" ").filter(Boolean).map(F=>m("kbd",{text:F}))))))])}let st=p=>p.target.closest('input, select, textarea, [contenteditable="true"]')&&!(p.target.type==="range"||p.target.type==="checkbox"),Qe=["none","bayer4","bayer8","bluenoise","cluster4","floyd-steinberg","atkinson","sierra-lite","jarvis"];window.addEventListener("keydown",p=>{if(!se.isConnected||document.querySelector("dialog[open]"))return;let M=p.ctrlKey||p.metaKey,_=p.key;if(M&&_.toLowerCase()==="z"){if(st(p))return;p.preventDefault(),p.shiftKey?r.redo():r.undo();return}if(M&&_.toLowerCase()==="y"){if(st(p))return;p.preventDefault(),r.redo();return}if(M&&_.toLowerCase()==="s"){p.preventDefault(),a.exportPNG();return}if(M&&_.toLowerCase()==="o"){p.preventDefault(),qe();return}if(M||p.altKey&&!["ArrowUp","ArrowDown"].includes(_))return;if(st(p)){_==="Escape"&&p.target.blur();return}let F=r.settings;switch(_){case"c":case"C":Ze();break;case"g":case"G":kt();break;case"f":case"F":c.fit();break;case"+":case"=":c.zoomIn();break;case"-":case"_":c.zoomOut();break;case"t":case"T":pt();break;case"\\":Je("lib");break;case"/":Je("insp");break;case"?":Mt();break;case"[":case"{":r.update({size:{mode:"width",width:Math.max(8,F.size.width-(p.shiftKey?8:1))}},{key:"kw"});break;case"]":case"}":r.update({size:{mode:"width",width:F.size.width+(p.shiftKey?8:1)}},{key:"kw"});break;case"d":case"D":{let X=Qe.indexOf(F.dither.method),ne=Qe[(X+(p.shiftKey?-1:1)+Qe.length)%Qe.length];r.update({dither:{method:ne}}),W(ne==="none"?"No dither":ne.replace(/-/g," "),{timeout:900});break}case" ":a.current?.type==="video"&&(p.preventDefault(),Ke());break;case",":rt(-1);break;case".":rt(1);break;case"Escape":c.picking?$e():Wt();break;case"ArrowDown":case"ArrowUp":if(p.altKey&&p.shiftKey&&a.current){p.preventDefault(),a.move(a.current,_==="ArrowDown"?1:-1);break}if(p.altKey&&a.items.length>1){p.preventDefault();let X=a.items.indexOf(a.current);Oe(a.items[(X+(_==="ArrowDown"?1:-1)+a.items.length)%a.items.length])}break;default:return}});let ct=0;return se.addEventListener("dragenter",p=>{[...p.dataTransfer.types].includes("Files")&&(ct++,se.classList.add("itp-dragging"))}),se.addEventListener("dragleave",()=>{--ct<=0&&(ct=0,se.classList.remove("itp-dragging"))}),se.addEventListener("dragover",p=>{[...p.dataTransfer.types].includes("Files")&&p.preventDefault()}),se.addEventListener("drop",p=>{p.preventDefault(),ct=0,se.classList.remove("itp-dragging"),p.dataTransfer.files.length&&Ae([...p.dataTransfer.files])}),window.addEventListener("paste",p=>{if(!se.isConnected||st(p))return;let M=[...p.clipboardData?.files||[]];if(M.length){p.preventDefault(),Ae(M);return}let _=p.clipboardData?.getData("text")||"";if(/#?[0-9a-f]{6}/i.test(_)&&/\n|,|\s/.test(_.trim()))try{let F=ao(_);r.update({palette:{source:"custom",name:"Pasted",colors:F.colors}}),W(`Pasted a ${F.colors.length}-colour palette`,{kind:"ok"})}catch{}}),window.addEventListener("hashchange",()=>{if(/[#&]s=/.test(location.hash))try{r.replace(Hn(location.hash))}catch{}}),l.sync(r.settings,null),s.refresh(),Ve(),x.disabled=E.disabled=!0,{app:a,store:r,addFiles:Ae,async addImage(p,M="image"){let _=await le(M,p);return Oe(_),s.refresh(),_},openSample:p=>Ge(zn.find(M=>M.id===p)||zn[0]),applyPreset:p=>{let M=cn.find(_=>_.id===p);M&&a.applyPreset(M)},setTheme:p=>{vt("theme",p),ft(p)},get result(){return a.result},get view(){return c.rect},async idle(){for(let p=0;p<200&&(ae||he);p++)await new Promise(M=>setTimeout(M,25))}}}export{zn as SAMPLES,Bl as mountEditor};
|
|
371
|
+
</svg>`,Wn=[{id:"dusk",name:"Dusk",svg:nc},{id:"still-life",name:"Still life",svg:oc},{id:"potion",name:"Potion (transparent)",svg:rc}],Oo=e=>"data:image/svg+xml;charset=utf-8,"+encodeURIComponent(e.svg);async function Oi(e){let t=new Image;return t.src=Oo(e),await t.decode(),t}var ic="image-to-pixel",qn="workspace",Do="current";function ac(){return new Promise((e,t)=>{if(typeof indexedDB>"u"){t(new Error("This browser has no IndexedDB"));return}let n=indexedDB.open(ic,1);n.onupgradeneeded=()=>{n.result.objectStoreNames.contains(qn)||n.result.createObjectStore(qn)},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}async function Fo(e,t){let n=await ac();try{return await new Promise((o,i)=>{let r=n.transaction(qn,e),a=t(r.objectStore(qn));r.oncomplete=()=>o(a&&a.result),r.onerror=()=>i(r.error||a&&a.error),r.onabort=()=>i(r.error||new Error("Saving was cancelled"))})}finally{n.close()}}async function Di(e){let t={version:1,savedAt:Date.now(),...e};return await Fo("readwrite",n=>n.put(t,Do)),e.items.reduce((n,o)=>n+(o.file?o.file.size:0),0)}async function Fi(){try{let e=await Fo("readonly",t=>t.get(Do));return e&&e.version===1&&Array.isArray(e.items)?e:null}catch{return null}}async function $i(){await Fo("readwrite",e=>e.delete(Do))}var zi=e=>!!e&&(e.name==="QuotaExceededError"||/quota|space/i.test(e.message||"")),$o=e=>e>=1e9?`${(e/1e9).toFixed(1)} GB`:e>=1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1e3))} KB`;var Bi=/^image\//,Ni=/^video\//,sc=/\.(gpl|hex|pal|txt|json)$/i;async function Pu(e,t={}){let n=t.persist!==!1,o=()=>matchMedia("(max-width: 900px)").matches,i=t.settings||n&&pt("settings",null)||Et();if(/[#&]s=/.test(location.hash))try{i=Qn(location.hash)}catch{Z("That share link could not be read; using your last settings",{kind:"error"})}let r=ci(i),a={store:r,engine:null,items:[],current:null,result:null,exporting:!1,activePreset:null,userPalettes:n?pt("palettes",[]):[],shared:r.settings,clipboard:null,videoSupport:{mp4:!1,webm:!1},toast:(d,g)=>Z(d,g)},c=ui({onPick:Bt,onViewChange:()=>Ft()}),u=Ui(a),s=Ii(a),l=Pi(a),p=(d,g,k,A={})=>m("button.itp-btn.icon",{type:"button","aria-label":g,title:g,html:Q(d),onclick:k,...A}),f=m("span.name",{text:"No image"});f.addEventListener("click",()=>{a.current&&je(a.current)});let h=m("span.meta.num",{}),y=p("undo","Undo (Ctrl+Z)",()=>r.undo()),E=p("redo","Redo (Ctrl+Shift+Z)",()=>r.redo()),v=p("compare","Compare with original (C)",()=>bt(),{"aria-pressed":"false"}),M=p("grid","Pixel grid (G)",()=>Kt(),{"aria-pressed":"false"}),x=m("button.itp-btn.itp-zoom.num",{type:"button","aria-label":"Zoom","aria-haspopup":"menu",html:`<span>Fit</span>${Q("chevronDown")}`,onclick:d=>yt(d.currentTarget)}),S=p("moon","Toggle theme (T)",()=>Zt()),b=p("sidebarLeft","Toggle library (\\)",()=>Re("lib")),_=p("sidebarRight","Toggle inspector (/)",()=>Re("insp")),L=p("keyboard","Keyboard shortcuts (?)",()=>ae()),P=m("button.itp-btn.primary",{type:"button","aria-haspopup":"menu",html:`${Q("download")}<span>Export</span>`,onclick:d=>H(d.currentTarget)}),R=m("button.itp-btn.outline",{type:"button",title:"Save these files and their settings in this browser",html:`${Q("save")}<span class="hide-sm">Save</span>`,onclick:()=>$e()});R.hidden=!n;let j=m("a.itp-brand",{href:t.homeHref||"#",title:"Image-to-Pixel"},m("span.itp-mark",{"aria-hidden":"true"},...Array.from({length:9},()=>m("i"))),m("span.hide-sm",{text:"Image-to-Pixel"}));t.homeHref||j.addEventListener("click",d=>d.preventDefault());let C=m("header.itp-top",{},b,j,m("span.sep.hide-sm"),m("div.itp-file",{},f,h),m("div.spacer"),m("span.hide-sm.contents",{},y,E,m("span.sep")),v,M,x,m("span.sep.hide-sm"),m("span.hide-sm.contents",{},S,L),_,m("span",{style:{width:"6px"}}),R,P),D=t.samples===!1?null:m("div.samples",{},...Wn.map(d=>m("button",{type:"button",title:`Try "${d.name}"`,"aria-label":`Open sample: ${d.name}`,onclick:()=>tt(d)},m("img",{src:Oo(d),alt:""})))),F=m("div.itp-empty",{},m("div.itp-drop",{},m("h2",{text:"Drop an image or a video"}),m("p",{text:"PNG, JPG, WebP, GIF, SVG, MP4 or WebM. Add several files to process them as a batch. You can also paste with Ctrl+V."}),m("div.actions",{},m("button.itp-btn.primary",{type:"button",html:`${Q("upload")}<span>Choose files</span>`,onclick:()=>mt()}),m("button.itp-btn.outline",{type:"button",html:`${Q("clipboard")}<span>Paste</span>`,onclick:()=>St()})),D?m("p",{style:{fontSize:"var(--fs-xs)",color:"var(--faint)"},text:"Or start from a sample"}):null,D)),I=m("div.itp-float.bl",{"aria-live":"polite"}),N=m("div.itp-busy.itp-float",{hidden:!0,style:{padding:"6px 10px",alignItems:"center",gap:"8px",fontSize:"var(--fs-xs)",color:"var(--muted)",display:"flex"}},m("span.itp-spinner"),m("span",{text:"Rendering"})),z=m("div.itp-float.br",{},p("zoomOut","Zoom out (-)",()=>c.zoomOut()),p("fit","Fit to view (F)",()=>c.fit()),p("zoomIn","Zoom in (+)",()=>c.zoomIn()));c.el.append(F,I,N,z);let se=p("play","Play (Space)",()=>it()),de=m("span.itp-time",{}),oe=m("input.itp-scrub",{type:"range",min:0,max:1e3,value:0,"aria-label":"Video position"}),ee=m("span.muted.num",{style:{fontSize:"var(--fs-xs)",whiteSpace:"nowrap"}}),te={muted:pt("muted",!0)!==!1,volume:Number(pt("volume",1))};te.volume>=0&&te.volume<=1||(te.volume=1);let we=p("volumeOff","Volume (M mutes)",()=>ge(),{"aria-haspopup":"true","aria-expanded":"false"}),ue=m("div.fill"),W=m("div.thumb"),Y=m("div.itp-vslider",{role:"slider",tabindex:"0","aria-label":"Volume","aria-orientation":"vertical","aria-valuemin":"0","aria-valuemax":"100"},m("div.track",{},ue,W)),be=m("span.num",{}),ce=m("div.itp-volpop",{hidden:!0},be,Y),le=m("div.itp-sound",{hidden:!0},ce,we),me=d=>Pt(d<=.005?{muted:!0}:{muted:!1,volume:Math.min(1,d)}),pe=d=>{let g=Y.querySelector(".track").getBoundingClientRect();return Math.max(0,Math.min(1,(g.bottom-d.clientY)/g.height))};Y.addEventListener("pointerdown",d=>{d.preventDefault(),Y.focus(),Y.setPointerCapture(d.pointerId);let g=te.muted?0:te.volume;me(pe(d));let k=U=>me(pe(U)),A=()=>{Y.removeEventListener("pointermove",k),Y.removeEventListener("pointerup",A),Y.removeEventListener("pointercancel",A),te.muted&&g>0&&Pt({muted:!0,volume:g})};Y.addEventListener("pointermove",k),Y.addEventListener("pointerup",A),Y.addEventListener("pointercancel",A)}),Y.addEventListener("keydown",d=>{let g=te.muted?0:te.volume,k={ArrowUp:g+.05,ArrowRight:g+.05,ArrowDown:g-.05,ArrowLeft:g-.05,PageUp:g+.2,PageDown:g-.2,Home:0,End:1}[d.key];if(k===void 0){d.key==="Escape"&&(d.preventDefault(),ge(!1),we.focus());return}d.preventDefault(),d.stopPropagation(),me(k)}),Y.addEventListener("wheel",d=>{d.preventDefault(),me((te.muted?0:te.volume)-Math.sign(d.deltaY)*.05)},{passive:!1});function ge(d=ce.hidden){if(ce.hidden=!d,we.setAttribute("aria-expanded",String(d)),d){let g=k=>{le.contains(k.target)||(ge(!1),document.removeEventListener("pointerdown",g,!0))};document.addEventListener("pointerdown",g,!0)}}let xe=m("div.itp-transport",{role:"group","aria-label":"Video"},p("stepBack","Previous frame (,)",()=>Je(-1)),se,p("stepForward","Next frame (.)",()=>Je(1)),de,oe,le,ee),ke=m("main.itp-stage",{"data-video":"false"},c.el,xe);ke.addEventListener("pointerdown",()=>{o()&&ie.dataset.lib==="open"&&Re("lib")},!0);let ie=m("div.itp.itp-app",{"data-lib":o()?"closed":pt("lib","open"),"data-insp":pt("insp","open")},C,s.el,ke,u.el);st(e,ie),zt(pt("theme",null)),I.textContent="Starting\u2026";try{a.engine=await Yr()}catch(d){throw Z(`Could not start: ${d.message}`,{kind:"error"}),d}u.el.querySelector("#itp-backend").textContent=a.engine.backend==="webgl"?"GPU \xB7 ShaderMate":"CPU",u.el.querySelector("#itp-backend").title=a.engine.backend==="webgl"?`WebGL 2: ${a.engine.renderer}`:a.engine.fallbackReason||"CPU renderer",Promise.resolve().then(()=>(Uo(),Ro)).then(d=>d.videoSupport()).then(d=>{a.videoSupport=d}).catch(()=>{});let ze=!1,Be=!1,lt=null,qe=document.createElement("canvas");function Ne(){ze=!0,Be||requestAnimationFrame(Ct)}a.schedule=Ne;async function Ct(){if(Be||!ze||a.exporting)return;ze=!1;let d=a.current;if(!d){a.result=null,c.clear(),De();return}Be=!0;let g=setTimeout(()=>{N.hidden=!1},250);try{d.type==="video"&&a.engine.invalidate();let k=await a.engine.process(d.source,r.settings);if(d!==a.current)return;a.result=k,k.toCanvas(1,{canvas:qe}),c.show(qe,d.source,k.crop),u.setStats(k),u.sync(r.settings,k),lt!==d&&(lt=d),De()}catch(k){console.error(k),Z(`Rendering failed: ${k.message}`,{kind:"error"})}finally{clearTimeout(g),N.hidden=!0,Be=!1,ze&&requestAnimationFrame(Ct)}}function De(){let d=a.result,g=a.current;if(f.textContent=g?g.name:"No image",h.textContent=g?g.type==="video"?`${g.width} \xD7 ${g.height}, ${yn(g.duration)}`:`${g.width} \xD7 ${g.height}`:"",F.hidden=!!g,z.hidden=!g,!g||!d){I.hidden=!0;return}I.hidden=!1,st(I,m("span",{},m("b",{text:`${d.width} \xD7 ${d.height}`})," px"),m("span",{text:`${Math.round(c.zoom*100)/100}\xD7 zoom`})),y.disabled=!r.canUndo,E.disabled=!r.canRedo}function Ft(){x.querySelector("span").textContent=!a.current||c.fitted?"Fit":c.zoom>=1?`${Math.round(c.zoom*10)/10}\xD7`:`${Math.round(c.zoom*100)}%`,a.result&&De()}r.subscribe((d,g)=>{let k=a.current;k&&k.own&&r.target===k.id?k.own=d:r.target==="shared"&&(a.shared=d),u.sync(d,a.result),y.disabled=!r.canUndo,E.disabled=!r.canRedo,g!=="preset"&&(a.activePreset=null),n&&Me(),s.tab==="palettes"&&s.refresh(),Ne()});let et=null,Me=()=>{clearTimeout(et),et=setTimeout(()=>ct("settings",a.shared),300)};async function Ye(d,g,k){let A=document.createElement("canvas"),U=72/Math.max(g,k);A.width=Math.max(1,Math.round(g*U)),A.height=Math.max(1,Math.round(k*U));try{A.getContext("2d").drawImage(d,0,0,A.width,A.height)}catch{}return A.toDataURL()}async function Ae(d,g,k=null){let A=g.naturalWidth||g.width,U=g.naturalHeight||g.height,B={id:crypto.randomUUID?.()||String(Math.random()),name:d,type:"image",source:g,width:A,height:U,file:k};return B.thumb=await Ye(g,A,U),a.items.push(B),B}async function ht(d,g){let k=m("video",{muted:!0,playsInline:!0,preload:"auto",crossOrigin:"anonymous"});k.muted=!0,k.src=URL.createObjectURL(g);try{await nn(k)}catch(U){if(URL.revokeObjectURL(k.src),U.code===3||U.code===4){let B=await ri(g).catch(()=>""),X=B==="H.264"?"WebM (VP9)":B==="VP9"?"H.264 MP4":"H.264 MP4 or WebM (VP9)",re=new Error(B?`it's ${B}, which this browser can't play. Re-save it as ${X}, or open the editor in a browser that plays ${B}.`:`this browser can't play this video's format. Re-save it as ${X}.`);throw re.code=U.code,re}throw U}let A={id:crypto.randomUUID?.()||String(Math.random()),name:d,type:"video",source:k,width:k.videoWidth,height:k.videoHeight,duration:k.duration,fps:30,file:g};return await Xt(k,Math.min(.05,k.duration/2)).catch(()=>{}),A.thumb=await Ye(k,A.width,A.height),a.items.push(A),A.fpsReady=On(k,30).catch(()=>30).then(U=>{A.fps=U,A.fpsReady=null,a.current===A&&He(),u.syncAnim()}),ii(g).then(U=>{A.hasAudio=U,a.current===A&&He()}),k.addEventListener("timeupdate",()=>{a.current===A&&He()}),k.addEventListener("play",()=>{a.current===A&&(He(),$t(A))}),k.addEventListener("pause",()=>{a.current===A&&(He(),Ne())}),k.addEventListener("seeked",()=>{a.current===A&&!a.exporting&&Ne()}),k.addEventListener("ended",()=>{a.current!==A||a.exporting||A.fpsReady||(k.currentTime=0,k.play().catch(()=>{}))}),A}async function Fe(d){let g=[],k=[],A=[];for(let X of d)sc.test(X.name)&&!/^image|^video/.test(X.type)?/\.json$/i.test(X.name)?A.push(X):k.push(X):(Bi.test(X.type)||Ni.test(X.type)||/\.(png|jpe?g|gif|webp|bmp|svg|avif|mp4|webm|mov)$/i.test(X.name))&&g.push(X);for(let X of k)await K(X);for(let X of A){let re=await X.text();try{let fe=JSON.parse(re);fe.colors||Array.isArray(fe)?await K(X,re):(r.replace(eo(fe)),Z(`Loaded settings from ${X.name}`,{kind:"ok"}))}catch(fe){Z(`${X.name}: ${fe.message}`,{kind:"error"})}}let U=null,B=g.length>2?Z(`Loading ${g.length} files`,{progress:!0}):null;for(let X=0;X<g.length;X++){let re=g[X];try{let fe;if(Ni.test(re.type)||/\.(mp4|webm|mov)$/i.test(re.name))fe=await ht(re.name,re);else{let _e;try{_e=await createImageBitmap(re)}catch{_e=new Image,_e.src=URL.createObjectURL(re),await _e.decode()}fe=await Ae(re.name,_e,re)}U||(U=fe)}catch(fe){Z(`${re.name} could not be opened: ${fe.message}`,{kind:"error"})}B?.progress((X+1)/g.length)}B?.close(),U&&Ce(U),s.refresh(),g.length>1&&Z(`Added ${g.length} files. They share one set of settings.`,{kind:"ok"})}a.addFiles=Fe;async function mt(){let d=await $n({accept:"image/*,video/*,.gpl,.hex,.pal,.txt,.json",multiple:!0});d.length&&Fe(d)}a.openFiles=mt;async function tt(d){let g=await Oi(d),k=await Ae(`${d.name}.svg`,g,new File([d.svg],`${d.name}.svg`,{type:"image/svg+xml"}));Ce(k),s.refresh()}async function St(){try{let d=await navigator.clipboard.read(),g=[];for(let k of d)for(let A of k.types)if(Bi.test(A)){let U=await k.getType(A);g.push(new File([U],`pasted-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.${A.split("/")[1]}`,{type:A}))}g.length?Fe(g):Z("The clipboard has no image",{kind:"error"})}catch{Z("Press Ctrl+V (\u2318V) to paste. The browser blocked direct clipboard access.")}}a.pasteFromClipboard=St;function Ce(d){a.current&&a.current.type==="video"&&a.current!==d&&a.current.source.pause(),a.current=d,ot(d),ke.dataset.video=String(d&&d.type==="video"),d&&d.type==="video"&&He(),c.clear(),a.result=null,c.picking&&O(),s.refresh(),s.sourceChanged(),Ne(),De()}a.select=Ce;function Tt(d){let g=a.items.indexOf(d);g<0||(a.items.splice(g,1),r.dropTarget(d.id),d.type==="video"&&(d.source.pause(),URL.revokeObjectURL(d.source.src)),d.source.close&&!a.items.some(k=>k.source===d.source)&&d.source.close(),a.current===d&&Ce(a.items[Math.min(g,a.items.length-1)]||null),s.refresh(),u.sync(r.settings,a.result))}a.removeItem=Tt,a.clearItems=()=>{for(let d of a.items.slice())Tt(d)};let nt=d=>d===a.current?r.settings:d&&d.own||a.shared;a.settingsFor=nt;let Ke=d=>JSON.parse(JSON.stringify(d));function ot(d,g=!1){let k=d&&d.own?d.id:"shared";r.target===k&&!g||r.setTarget(k,k==="shared"?a.shared:d.own)}function gt(d,g,{quiet:k=!1}={}){if(!(!d||!!d.own===g)){if(g)d.own=Ke(nt(d)),d===a.current&&ot(d),k||Z(`${d.name} now has its own settings. Changes no longer affect other files.`);else{let A=d.own;d.own=null,r.dropTarget(d.id),d===a.current&&ot(d),k||Z(`${d.name} uses the shared settings again`,{action:{label:"Undo",onClick:()=>{d.own=A,d===a.current&&ot(d),ut()}}})}ut()}}function ut(){s.refresh(),u.sync(r.settings,a.result),a.result&&u.setStats(a.result),Ne()}a.setOwn=gt,a.copySettings=d=>{a.clipboard=Ke(nt(d)),Z(`Copied the settings of ${d.name}`,{timeout:1800}),s.refresh()},a.pasteSettings=d=>{a.clipboard&&(d.own||gt(d,!0,{quiet:!0}),d===a.current?r.replace(a.clipboard,"paste"):d.own=Ke(a.clipboard),Z(`Pasted settings onto ${d.name}`,{kind:"ok",timeout:1800}),ut())},a.applyToAll=d=>{let g={shared:a.shared,own:new Map(a.items.map(k=>[k,k.own]))};a.shared=Ke(nt(d));for(let k of a.items)k.own&&r.dropTarget(k.id),k.own=null;r.setTarget("shared",a.shared),n&&Me(),Z(`Every file now uses the settings of ${d.name}`,{action:{label:"Undo",onClick:()=>{a.shared=g.shared;for(let[k,A]of g.own)k.own=A;ot(a.current,!0),ut()}}}),ut()},a.duplicate=async d=>{let g;d.type==="video"?g=await ht(Ge(d.name),d.file):g=await Ae(Ge(d.name),d.source,d.file),a.items.splice(a.items.indexOf(g),1),a.items.splice(a.items.indexOf(d)+1,0,g),g.own=Ke(nt(d)),Ce(g),Z(`Duplicated ${d.name}. The copy has its own settings.`,{timeout:2400})};let Ge=d=>{let g=/^(.*?)(\.[^.]*)?$/.exec(d);return`${g[1]} copy${g[2]||""}`};a.move=(d,g)=>{let k=a.items.indexOf(d),A=k+g;k<0||A<0||A>=a.items.length||([a.items[k],a.items[A]]=[a.items[A],a.items[k]],s.refresh(),(document.activeElement===document.body||document.activeElement?.closest?.(".itp-files"))&&s.focusFile(d))};let dt=d=>{let g=/^(.*?)(\.[^.\s]{1,5})?$/.exec(d);return[g[1],g[2]||""]};a.rename=(d,g)=>{let[,k]=dt(d.name),A=String(g||"").trim().replace(/[\\/:*?"<>|]+/g,"-");k&&A.toLowerCase().endsWith(k.toLowerCase())&&(A=A.slice(0,-k.length)),!(!A||A+k===d.name)&&(d.name=A+k,s.refresh(),De())};function je(d){if(!d||f.hidden)return;a.current!==d&&Ce(d);let[g]=dt(d.name),k=m("input.itp-name-input",{type:"text",value:d.name,"aria-label":"File name",spellcheck:!1});k.style.width=`${Math.min(40,Math.max(12,d.name.length+2))}ch`,f.hidden=!0,f.after(k),k.focus(),k.setSelectionRange(0,g.length);let A=!1,U=B=>{A||(A=!0,B&&a.rename(d,k.value),k.remove(),f.hidden=!1)};k.addEventListener("keydown",B=>{B.stopPropagation(),B.key==="Enter"&&(B.preventDefault(),U(!0)),B.key==="Escape"&&(B.preventDefault(),U(!1))}),k.addEventListener("blur",()=>U(!0))}a.startRename=je;let Le=null;a.savedWorkspace=()=>Le;async function rt(d){if(d.file)return d.file;let g=document.createElement("canvas");return g.width=d.width,g.height=d.height,g.getContext("2d").drawImage(d.source,0,0),new Promise(k=>g.toBlob(A=>k(A),"image/png"))}async function $e(){if(n){if(!a.items.length){if(Le){await Ze();return}Z("Add files first, then Save keeps them here for next time.");return}R.disabled=!0;try{let d=[];for(let A of a.items)d.push({name:A.name,type:A.type,file:await rt(A),own:A.own?Ke(A.own):null});let g=await Di({shared:Ke(a.shared),current:Math.max(0,a.items.indexOf(a.current)),items:d}),k=!Le;Le={count:d.length,bytes:g,savedAt:Date.now()},s.refresh(),Z(k?`Saved ${d.length} file${d.length===1?"":"s"} (${$o(g)}) in this browser only. They reopen next time; remove them with Forget in the Files list.`:`Saved ${d.length} file${d.length===1?"":"s"} (${$o(g)})`,{kind:"ok",timeout:k?7e3:2200})}catch(d){console.error(d),Z(zi(d)?"Not enough browser storage to save these files. Remove some (videos are large) and try again.":`Couldn't save: ${d.message}`,{kind:"error"})}finally{R.disabled=!1}}}a.saveWorkspace=$e;async function Ze(){try{await $i()}catch(d){Z(`Couldn't remove the saved files: ${d.message}`,{kind:"error"});return}Le=null,s.refresh(),Z("Removed the saved files from this browser. Files open now stay open.")}a.forgetWorkspace=Ze;async function At(){let d=await Fi();if(!d)return;if(Le={count:d.items.length,bytes:d.items.reduce((U,B)=>U+(B.file?B.file.size:0),0),savedAt:d.savedAt},a.items.length||!d.items.length){s.refresh();return}d.shared&&!/[#&]s=/.test(location.hash)&&r.setTarget("shared",d.shared);let g=d.items.length>2?Z(`Opening ${d.items.length} saved files`,{progress:!0}):null,k=[];for(let U=0;U<d.items.length;U++){let B=d.items[U];try{let X=B.file instanceof File?B.file:new File([B.file],B.name,{type:B.file.type}),re;if(B.type==="video")re=await ht(B.name,X);else{let fe;try{fe=await createImageBitmap(X)}catch{fe=new Image,fe.src=URL.createObjectURL(X),await fe.decode()}re=await Ae(B.name,fe,X)}re.own=B.own||null,k.push(re)}catch(X){console.warn("[workspace] skipped",B.name,X)}g?.progress((U+1)/d.items.length)}g?.close();let A=k[Math.min(d.current||0,k.length-1)];A&&Ce(A),s.refresh(),k.length&&Z(`Reopened your saved files (${k.length})`,{timeout:2200})}function He(){let d=a.current;if(!d||d.type!=="video")return;let g=d.source;se.innerHTML=Q(g.paused?"play":"pause"),se.setAttribute("aria-label",g.paused?"Play (Space)":"Pause (Space)");let k=Math.floor(g.currentTime*d.fps+1e-6);de.innerHTML=`${yn(g.currentTime)} <span>/ ${yn(g.duration)}</span>`,de.title=`Frame ${k}`,oe.value=String(Math.round(g.currentTime/(g.duration||1)*1e3)),oe.style.setProperty("--p",`${oe.value/10}%`),ee.textContent=`${d.fps} fps`,le.hidden=d.hasAudio===!1,_t(g)}function _t(d){d&&!a.exporting&&!a.current?.fpsReady&&(d.muted!==te.muted&&(d.muted=te.muted),d.volume!==te.volume&&(d.volume=te.volume));let g=te.muted?0:te.volume,k=Math.round(g*100);we.innerHTML=Q(g?"volume":"volumeOff");let A=g?`Volume ${k}% (M mutes)`:"Muted (M unmutes)";we.setAttribute("aria-label",A),we.title=A,Y.setAttribute("aria-valuenow",String(k)),Y.setAttribute("aria-valuetext",g?`${k}%`:"Muted"),Y.style.setProperty("--v",`${k}%`),be.textContent=g?String(k):"Off"}function Pt(d){Object.assign(te,d),d.muted===!1&&!te.volume&&(te.volume=1),ct("muted",te.muted),ct("volume",te.volume),_t(a.current&&a.current.type==="video"?a.current.source:null)}function $t(d){let g=d.source,k=()=>{g.paused||a.current!==d||(Ne(),"requestVideoFrameCallback"in g?g.requestVideoFrameCallback(k):requestAnimationFrame(k))};k()}async function it(){let d=a.current;if(!(!d||d.type!=="video")){if(!d.source.paused){d.source.pause();return}d.fpsReady&&await d.fpsReady,a.current===d&&(_t(d.source),d.source.ended&&(d.source.currentTime=0),d.source.play().catch(g=>Z(g.message,{kind:"error"})))}}function Je(d){let g=a.current;if(!g||g.type!=="video")return;let k=g.source;k.pause();let A=Math.floor(k.currentTime*g.fps+1e-6)+d;Xt(k,(Math.max(0,A)+.5)/g.fps).then(()=>{He(),Ne()})}oe.addEventListener("input",()=>{let d=a.current;!d||d.type!=="video"||(d.source.currentTime=oe.value/1e3*d.source.duration)});function bt(d){let g=d??!c.compare;c.setCompare(g),v.setAttribute("aria-pressed",String(g))}function Kt(d){let g=d??!c.grid;c.setGrid(g),M.setAttribute("aria-pressed",String(g)),g&&c.zoom<6&&a.result&&Z("The grid shows from 6\xD7 zoom")}function yt(d){hn(d,[{label:"Fit to view",kbd:"F",icon:"fit",onClick:()=>c.fit()},"sep",...[1,2,4,8,16,32].map(g=>({label:`${g}\xD7`,sub:g===1?"One screen pixel per pixel":null,onClick:()=>c.zoomTo(g)})),"sep",{label:"Zoom in",kbd:"+",icon:"zoomIn",onClick:()=>c.zoomIn()},{label:"Zoom out",kbd:"-",icon:"zoomOut",onClick:()=>c.zoomOut()}])}function Re(d){let g=d==="lib"?"lib":"insp",k=ie.dataset[g]!=="open";ie.dataset[g]=k?"open":"closed",(!o()||d==="insp")&&ct(g,ie.dataset[g]),requestAnimationFrame(()=>c.resize())}function zt(d){d?document.documentElement.dataset.theme=d:delete document.documentElement.dataset.theme;let g=d?d==="dark":!matchMedia("(prefers-color-scheme: light)").matches;S.innerHTML=Q(g?"sun":"moon"),S.setAttribute("aria-label",g?"Switch to light theme (T)":"Switch to dark theme (T)"),c.redraw()}function Zt(){let g=(document.documentElement.dataset.theme||(matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"))==="dark"?"light":"dark";ct("theme",g),zt(g)}function ve(d,g=4096){let k=d.width,A=d.height,U=Math.min(1,g/Math.max(k,A)),B=document.createElement("canvas");B.width=Math.round(k*U),B.height=Math.round(A*U);let X=B.getContext("2d",{willReadFrequently:!0});return X.drawImage(d.source,0,0,B.width,B.height),X.getImageData(0,0,B.width,B.height)}function Bt(d,g){let k=a.current;if(!k)return;let A=ve(k,1024),U=a.result?a.result.crop:{x:0,y:0,w:1,h:1},B=Math.min(A.width-1,Math.floor((U.x+d*U.w)*A.width)),re=(Math.min(A.height-1,Math.floor((U.y+g*U.h)*A.height))*A.width+B)*4,fe=Nt([A.data[re],A.data[re+1],A.data[re+2]]),_e=r.settings,Ve=_e.palette.source==="custom"?_e.palette.colors:[];if(Ve.includes(fe))return Z(`${fe} is already in the palette`);r.update({palette:{source:"custom",name:_e.palette.source==="custom"?_e.palette.name:"Picked",colors:[...Ve,fe]}}),Z(`Added ${fe}`,{kind:"ok",timeout:1500})}let T=null;function O(d){d&&(T=d);let g=!c.picking;c.setPicking(g),T?.setAttribute("aria-pressed",String(g)),g&&(bt(!0),Z("Click the image to add colours. Press Esc when done."))}a.togglePicker=O;function $(d){d.id&&!d.custom?r.update({palette:{source:"builtin",id:d.id}}):r.update({palette:{source:"custom",name:d.name,colors:d.colors}})}a.usePalette=$;function V(d,g){let k=a.userPalettes.filter(A=>A.name!==d);k.unshift({name:d,colors:g,custom:!0}),a.userPalettes=k.slice(0,100),n&&ct("palettes",a.userPalettes),s.tab==="palettes"&&s.refresh()}async function K(d,g){try{let k=go(g??await d.text(),d.name);V(k.name||"Imported",k.colors),r.update({palette:{source:"custom",name:k.name||"Imported",colors:k.colors}}),Z(`Imported "${k.name}" (${k.colors.length} colours)`,{kind:"ok"})}catch(k){Z(`${d.name}: ${k.message}`,{kind:"error"})}}a.importPalette=async()=>{let[d]=await $n({accept:".gpl,.hex,.pal,.txt,.json"});d&&K(d)},a.savePalette=()=>{let d=r.settings,g=d.palette.source==="extract"?a.result?.palette||[]:d.palette.colors;if(!g.length)return Z("There is no palette to save",{kind:"error"});let k=m("input.itp-input",{value:d.palette.source==="custom"?d.palette.name:`${d.palette.name} copy`,"aria-label":"Palette name"}),A=m("select.itp-select",{"aria-label":"Also download as"},m("option",{value:"",text:"Don't download"}),m("option",{value:"gpl",text:".gpl (GIMP, Aseprite)"}),m("option",{value:"hex",text:".hex (Lospec)"}),m("option",{value:"json",text:".json"}));mn("Save palette",[m("div.itp-field",{},m("div.lab",{},m("span",{text:"Name"})),k),m("div.itp-field",{},m("div.lab",{},m("span",{text:"Also download as"})),A),m("div.itp-strip",{style:{height:"18px"}},...g.map(U=>m("i",{style:{background:U}})))],{actions:[{label:"Cancel"},{label:"Save",primary:!0,onClick:()=>{let U=k.value.trim()||"Palette";V(U,g),r.update({palette:{source:"custom",name:U,colors:g}});let B=U.replace(/[^\w-]+/g,"-").toLowerCase();A.value==="gpl"&&We(Zr(U,g),`${B}.gpl`,"text/plain"),A.value==="hex"&&We(Jr(g),`${B}.hex`,"text/plain"),A.value==="json"&&We(Qr(U,g),`${B}.json`,"application/json"),Z(`Saved "${U}" to Your palettes`,{kind:"ok"})}}]}),k.select()},a.deletePalette=d=>{a.userPalettes=a.userPalettes.filter(g=>g!==d),n&&ct("palettes",a.userPalettes),s.refresh(),Z(`Deleted "${d.name}"`,{action:{label:"Undo",onClick:()=>V(d.name,d.colors)}})},a.lospecDialog=()=>{let d=m("input.itp-input",{placeholder:"e.g. rgbg-36 or a lospec.com palette URL","aria-label":"Lospec slug or URL"}),g=m("div.help",{text:"Looks the palette up on lospec.com. Needs an internet connection."}),k=mn("Palette from Lospec",[m("div.itp-field",{},m("div.lab",{},m("span",{text:"Slug or URL"})),d,g)],{actions:[{label:"Cancel"},{label:"Fetch",primary:!0,onClick:async()=>{g.textContent="Fetching\u2026",g.style.color="";try{let A=await ei(d.value);return V(A.name,A.colors),r.update({palette:{source:"custom",name:A.name,colors:A.colors}}),Z(`Loaded "${A.name}" from Lospec`,{kind:"ok"}),!0}catch(A){return g.textContent=A.message,g.style.color="var(--danger)",!1}}}]});d.addEventListener("keydown",A=>{A.key==="Enter"&&k.querySelector("footer .primary").click()}),d.focus()},a.detectGrid=()=>{let d=a.current;if(!d||d.type!=="image")return Z("Open an image first",{kind:"error"});let g=Wr(ve(d));if(g<=1)return Z("No pixel grid found. This image doesn't look upscaled.");r.update({size:{mode:"block",block:g,resample:"nearest"}}),Z(`Found ${g} px blocks: switched to pixel size ${g} with nearest sampling`,{kind:"ok"})},a.settingsJSON=()=>Qt(r.settings),a.copyLink=async()=>{let d=`${location.origin}${location.pathname}#s=${Jn(r.settings)}`;try{await navigator.clipboard.writeText(d),Z("Link copied. It holds the settings, not the image.",{kind:"ok"})}catch{mn("Share link",[m("textarea.itp-input",{rows:3,readOnly:!0,value:d})])}history.replaceState(null,"",`#s=${Jn(r.settings)}`)},a.saveSettingsFile=()=>We(Qt(r.settings),"image-to-pixel-settings.json","application/json"),a.loadSettingsFile=async()=>{let[d]=await $n({accept:".json,application/json"});if(d)try{r.replace(eo(await d.text())),Z(`Loaded ${d.name}`,{kind:"ok"})}catch(g){Z(`${d.name}: ${g.message}`,{kind:"error"})}},a.resetSettings=()=>{r.replace(Et()),Z("Settings reset",{action:{label:"Undo",onClick:()=>r.undo()}})},a.applyPreset=d=>{r.replace(Lt(Et(),{...d.settings,export:r.settings.export}),"preset"),a.activePreset=d.id,s.refresh()},Object.assign(a,l);function H(d){let g=a.current,k=g&&g.type==="video",A=a.items.filter(B=>B.type==="image").length,U=r.settings;hn(d,[{group:"Image"},{label:"PNG",sub:a.result?`${a.result.width*U.export.scale} \xD7 ${a.result.height*U.export.scale}, ${U.export.scale}\xD7 scale`:"Open an image first",icon:"image",kbd:"Ctrl S",disabled:!a.result,onClick:()=>a.exportPNG()},{label:"Copy to clipboard",icon:"copy",disabled:!a.result,onClick:()=>a.copyImage()},{label:a.items.length>1?`All ${a.items.length} files as ZIP`:"All files as ZIP",sub:a.items.length>1?null:"Add two or more files",icon:"zip",disabled:a.items.length<2,onClick:()=>a.exportZip()},{group:"Animation"},{label:k?"GIF from this video":"GIF from all images",icon:"gif",disabled:!k&&A<2,onClick:()=>a.exportAnimation({...J(),format:"gif"})},{label:"More formats\u2026",sub:"WebM, MP4, PNG sequence, sprite sheet",icon:"film",onClick:()=>{u.setTab("export"),ie.dataset.insp!=="open"&&Re("insp")}},{group:"Other"},{label:"Tileset",sub:"16 \xD7 16 tiles, duplicates removed",icon:"tiles",disabled:!a.result,onClick:()=>a.exportTileset({tile:16,flips:!1})},{label:"Copy settings link",icon:"link",onClick:()=>a.copyLink()},{label:"Settings as JSON",icon:"braces",onClick:()=>a.saveSettingsFile()}])}let J=()=>{let d=a.current,g=d&&d.type==="video";return{source:g?"video":"files",fps:g?Math.min(30,Math.round(d.fps||12)):8,start:0,end:g?d.duration:0}};function ae(){mn("Keyboard shortcuts",[m("div.itp-keys",{},...[["Open files","Ctrl O"],["Paste image","Ctrl V"],["Export PNG","Ctrl S"],["Undo","Ctrl Z"],["Redo","Ctrl Shift Z"],["Compare","C"],["Pixel grid","G"],["Fit","F"],["Zoom in / out","+ -"],["Pixel width \xB11","[ ]"],["Pixel width \xB18","Shift [ ]"],["Next / previous dither","D Shift D"],["Play / pause video","Space"],["Mute / unmute video","M"],["Rename file","F2"],["Step one frame",", ."],["Library","\\"],["Inspector","/"],["Theme","T"],["Next / previous file","Alt \u2193 \u2191"],["Move file down / up","Alt Shift \u2193 \u2191"],["This list","?"]].map(([g,k])=>m("div",{},m("span",{text:g}),m("span",{},...k.split(" ").filter(Boolean).map(A=>m("kbd",{text:A}))))))])}let ye=d=>d.target.closest('input, select, textarea, [contenteditable="true"]')&&!(d.target.type==="range"||d.target.type==="checkbox"),w=["none","bayer4","bayer8","bluenoise","cluster4","floyd-steinberg","atkinson","sierra-lite","jarvis"];window.addEventListener("keydown",d=>{if(!ie.isConnected||document.querySelector("dialog[open]"))return;let g=d.ctrlKey||d.metaKey,k=d.key;if(g&&k.toLowerCase()==="z"){if(ye(d))return;d.preventDefault(),d.shiftKey?r.redo():r.undo();return}if(g&&k.toLowerCase()==="y"){if(ye(d))return;d.preventDefault(),r.redo();return}if(g&&k.toLowerCase()==="s"){d.preventDefault(),a.exportPNG();return}if(g&&k.toLowerCase()==="o"){d.preventDefault(),mt();return}if(g||d.altKey&&!["ArrowUp","ArrowDown"].includes(k))return;if(ye(d)){k==="Escape"&&d.target.blur();return}let A=r.settings;switch(k){case"c":case"C":bt();break;case"g":case"G":Kt();break;case"f":case"F":c.fit();break;case"+":case"=":c.zoomIn();break;case"-":case"_":c.zoomOut();break;case"t":case"T":Zt();break;case"\\":Re("lib");break;case"/":Re("insp");break;case"?":ae();break;case"[":case"{":r.update({size:{mode:"width",width:Math.max(8,A.size.width-(d.shiftKey?8:1))}},{key:"kw"});break;case"]":case"}":r.update({size:{mode:"width",width:A.size.width+(d.shiftKey?8:1)}},{key:"kw"});break;case"d":case"D":{let U=w.indexOf(A.dither.method),B=w[(U+(d.shiftKey?-1:1)+w.length)%w.length];r.update({dither:{method:B}}),Z(B==="none"?"No dither":B.replace(/-/g," "),{timeout:900});break}case" ":a.current?.type==="video"&&(d.preventDefault(),it());break;case"F2":a.current&&(d.preventDefault(),je(a.current));break;case"m":case"M":a.current?.type==="video"&&!le.hidden&&(d.preventDefault(),Pt({muted:!te.muted}));break;case",":Je(-1);break;case".":Je(1);break;case"Escape":c.picking?O():Yt();break;case"ArrowDown":case"ArrowUp":if(d.altKey&&d.shiftKey&&a.current){d.preventDefault(),a.move(a.current,k==="ArrowDown"?1:-1);break}if(d.altKey&&a.items.length>1){d.preventDefault();let U=a.items.indexOf(a.current);Ce(a.items[(U+(k==="ArrowDown"?1:-1)+a.items.length)%a.items.length])}break;default:return}});let G=0;return ie.addEventListener("dragenter",d=>{[...d.dataTransfer.types].includes("Files")&&(G++,ie.classList.add("itp-dragging"))}),ie.addEventListener("dragleave",()=>{--G<=0&&(G=0,ie.classList.remove("itp-dragging"))}),ie.addEventListener("dragover",d=>{[...d.dataTransfer.types].includes("Files")&&d.preventDefault()}),ie.addEventListener("drop",d=>{d.preventDefault(),G=0,ie.classList.remove("itp-dragging"),d.dataTransfer.files.length&&Fe([...d.dataTransfer.files])}),window.addEventListener("paste",d=>{if(!ie.isConnected||ye(d))return;let g=[...d.clipboardData?.files||[]];if(g.length){d.preventDefault(),Fe(g);return}let k=d.clipboardData?.getData("text")||"";if(/#?[0-9a-f]{6}/i.test(k)&&/\n|,|\s/.test(k.trim()))try{let A=go(k);r.update({palette:{source:"custom",name:"Pasted",colors:A.colors}}),Z(`Pasted a ${A.colors.length}-colour palette`,{kind:"ok"})}catch{}}),window.addEventListener("hashchange",()=>{if(/[#&]s=/.test(location.hash))try{r.replace(Qn(location.hash))}catch{}}),u.sync(r.settings,null),s.refresh(),De(),y.disabled=E.disabled=!0,n&&t.restore!==!1&&At().catch(d=>console.warn("[workspace]",d)),{app:a,store:r,addFiles:Fe,async addImage(d,g="image"){let k=await Ae(g,d);return Ce(k),s.refresh(),k},openSample:d=>tt(Wn.find(g=>g.id===d)||Wn[0]),applyPreset:d=>{let g=dn.find(k=>k.id===d);g&&a.applyPreset(g)},setTheme:d=>{ct("theme",d),zt(d)},get result(){return a.result},get view(){return c.rect},async idle(){for(let d=0;d<200&&(ze||Be);d++)await new Promise(g=>setTimeout(g,25))}}}export{Wn as SAMPLES,Pu as mountEditor};
|
|
372
372
|
/*! Bundled license information:
|
|
373
373
|
|
|
374
374
|
shadermate/dist/shadermate.esm.js:
|