Skip to content

Unlock custom brushes, natural fill effects and intuitive hatching in p5.js

Working libr

acamposuribe9f48f319bbf2
diff --git a/dist/brush.esm.js b/dist/brush.esm.js
index 60b9843..732991d 100644
--- a/dist/brush.esm.js
+++ b/dist/brush.esm.js
@@ -1,2 +1,2 @@
-const t={a:1,b:0,c:0,d:1,x:0,y:0};let e,r,n,i,a=()=>!1,o=t=>t,s=()=>{throw new Error("No runtime color adapter registered.")},c=()=>t,l={load:()=>{throw new Error("No target runtime adapter registered.")},syncDensity:()=>i,isCanvasReady:()=>{throw new Error("No target runtime adapter registered.")},instance:t=>{},activateInstance:t=>{},deactivateInstance:()=>{},getActiveFramebuffer:()=>null,isFramebufferTarget:()=>!1};function u(t){"Cwidth"in t&&(e=t.Cwidth),"Cheight"in t&&(r=t.Cheight),"Instance"in t&&t.Instance,"Renderer"in t&&(n=t.Renderer),"Density"in t&&(i=t.Density)}const h=()=>l.isCanvasReady(),f=t=>l.instance(t),m=()=>l.getActiveFramebuffer(),d=t=>l.isFramebufferTarget(t),x=(t,e=0)=>t?{minX:t.minX-e,minY:t.minY-e,maxX:t.maxX+e,maxY:t.maxY+e}:null,g=(t,e,r=!1)=>{const n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(t,e):(()=>{const r=document.createElement("canvas");return r.width=t,r.height=e,r})();return n.drawingContext=n.getContext("2d",r?{willReadFrequently:!0}:void 0),n};let p={clearTarget:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendShaderProgram:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendSourceFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},createFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},runBlendShaderPass:()=>{throw new Error("No compositor runtime adapter registered.")},blitSourceToFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")}};const y=(...t)=>p.createFramebuffer(...t);let _=null,b=null;const v=t=>{((...t)=>{p.clearTarget(...t)})(n,t,d)},R=()=>({width:Math.max(1,Math.round(e*i)),height:Math.max(1,Math.round(r*i))}),w=t=>{if(!t)return null;const{width:e,height:r}=R();return((t,e,r)=>{if(!t)return null;const n=Math.max(0,Math.floor(Math.min(t.minX,t.maxX))),i=Math.max(0,Math.floor(Math.min(t.minY,t.maxY))),a=Math.min(e,Math.ceil(Math.max(t.minX,t.maxX))),o=Math.min(r,Math.ceil(Math.max(t.minY,t.maxY)));return a<=n||o<=i?null:{minX:n,minY:i,maxX:a,maxY:o}})(t,e,r)},E=()=>{const{width:t,height:e}=R();return((t,e)=>({minX:0,minY:0,maxX:t,maxY:e}))(t,e)},A=(t,e=!0)=>{const r=w(t);if(!r)return null;const{height:n}=R();return{x:r.minX,y:e?n-r.maxY:r.minY,width:r.maxX-r.minX,height:r.maxY-r.minY}},M=(t,e,r,n=!0)=>{const i=A(e,n);if(i){t.enable(t.SCISSOR_TEST),t.scissor(i.x,i.y,i.width,i.height);try{r()}finally{t.disable(t.SCISSOR_TEST)}}else r()},T={},S=()=>{n?.loaded||(h(),P.load())},P={isBlending:!1,cachedColor:null,markDirtyRect(t,e){const r=w(e);var n,i;t&&r&&(t.dirtyRect=(i=r,(n=t.dirtyRect)?i?{minX:Math.min(n.minX,i.minX),minY:Math.min(n.minY,i.minY),maxX:Math.max(n.maxX,i.maxX),maxY:Math.max(n.maxY,i.maxY)}:n:i),t.isDrawn=!0)},clearMask(t){if(!t)return;const e=t===this.glMask?_:b;e?.clearMask?.(t,v)},getCompositeRect(t,e){const r=e?_:b;return r?.getCompositeRect?.(t,m,E,x,w)},load(){l.syncDensity();const t=!n.blendSourceFramebuffer||n.blendSourceFramebuffer.width!==e||n.blendSourceFramebuffer.height!==r||"function"==typeof n.blendSourceFramebuffer.pixelDensity&&n.blendSourceFramebuffer.pixelDensity()!==i;((...t)=>{p.ensureBlendShaderProgram(...t)})(n,"#version 300 es\n#define GLSLIFY 1\nout vec2 p;void main(){vec3 v=vec3(-1);v[gl_VertexID]=3.;p=v.xy;gl_Position=vec4(v.x,-v.y,0,1);}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nuniform bool u_isBrush;uniform bool u_targetIsFramebuffer;uniform sampler2D u_source;uniform sampler2D u_mask;uniform vec3 u_color;in vec2 p;out vec4 outColor;const int SPECTRAL_SIZE=38;const float SPECTRAL_GAMMA=2.4;const float SPECTRAL_EPSILON=0.0000000000000001;float spectral_uncompand(float x){return(x<0.04045)? x/12.92 : pow((x+0.055)/1.055,SPECTRAL_GAMMA);}float spectral_compand(float x){return(x<0.0031308)? x*12.92 : 1.055*pow(x,1.0/SPECTRAL_GAMMA)-0.055;}vec3 spectral_srgb_to_linear(vec3 srgb){return vec3(spectral_uncompand(srgb[0]),spectral_uncompand(srgb[1]),spectral_uncompand(srgb[2]));}vec3 spectral_linear_to_srgb(vec3 lrgb){return clamp(vec3(spectral_compand(lrgb[0]),spectral_compand(lrgb[1]),spectral_compand(lrgb[2])),0.,1.);}void spectral_linear_to_reflectance(vec3 lrgb,inout float R[SPECTRAL_SIZE]){float w=min(lrgb.r,min(lrgb.g,lrgb.b));lrgb-=w;float c=min(lrgb.g,lrgb.b);float m=min(lrgb.r,lrgb.b);float y=min(lrgb.r,lrgb.g);float r=min(max(0.0,lrgb.r-lrgb.b),max(0.0,lrgb.r-lrgb.g));float g=min(max(0.0,lrgb.g-lrgb.b),max(0.0,lrgb.g-lrgb.r));float b=min(max(0.0,lrgb.b-lrgb.g),max(0.0,lrgb.b-lrgb.r));R[0]=max(SPECTRAL_EPSILON,w*1.0011607271876400+c*0.9705850013229620+m*0.9906735573199880+y*0.0210523371789306+r*0.0315605737777207+g*0.0095560747554212+b*0.9794047525020140);R[1]=max(SPECTRAL_EPSILON,w*1.0011606515972800+c*0.9705924981434250+m*0.9906715249619790+y*0.0210564627517414+r*0.0315520718330149+g*0.0095581580120851+b*0.9794007068431300);R[2]=max(SPECTRAL_EPSILON,w*1.0011603192274700+c*0.9706253487298910+m*0.9906625823534210+y*0.0210746178695038+r*0.0315148215513658+g*0.0095673245444588+b*0.9793829034702610);R[3]=max(SPECTRAL_EPSILON,w*1.0011586727078900+c*0.9707868061190170+m*0.9906181076447950+y*0.0211649058448753+r*0.0313318044982702+g*0.0096129126297349+b*0.9792943649455940);R[4]=max(SPECTRAL_EPSILON,w*1.0011525984455200+c*0.9713686732282480+m*0.9904514808787100+y*0.0215027957272504+r*0.0306729857725527+g*0.0097837090401843+b*0.9789630146085700);R[5]=max(SPECTRAL_EPSILON,w*1.0011325252899800+c*0.9731632306212520+m*0.9898710814002040+y*0.0226738799041561+r*0.0286480476989607+g*0.0103786227058710+b*0.9778144666940430);R[6]=max(SPECTRAL_EPSILON,w*1.0010850066332700+c*0.9767402231587650+m*0.9882866087596400+y*0.0258235649693629+r*0.0246450407045709+g*0.0120026452378567+b*0.9747243211338360);R[7]=max(SPECTRAL_EPSILON,w*1.0009968788945300+c*0.9815876054913770+m*0.9842906927975040+y*0.0334879385639851+r*0.0192960753663651+g*0.0160977721473922+b*0.9671984823439730);R[8]=max(SPECTRAL_EPSILON,w*1.0008652515227400+c*0.9862802656529490+m*0.9739349056253060+y*0.0519069663740307+r*0.0142066612220556+g*0.0267061902231680+b*0.9490796575305750);R[9]=max(SPECTRAL_EPSILON,w*1.0006962900094000+c*0.9899491476891340+m*0.9418178384601450+y*0.1007490148334730+r*0.0102942608878609+g*0.0595555440185881+b*0.9008501289409770);R[10]=max(SPECTRAL_EPSILON,w*1.0005049611488800+c*0.9924927015384200+m*0.8173903261951560+y*0.2391298997068470+r*0.0076191460521811+g*0.1860398265328260+b*0.7631504454622400);R[11]=max(SPECTRAL_EPSILON,w*1.0003080818799200+c*0.9941456804052560+m*0.4324728050657290+y*0.5348043122727480+r*0.0058980410835420+g*0.5705798201161590+b*0.4659221716493190);R[12]=max(SPECTRAL_EPSILON,w*1.0001196660201300+c*0.9951839750332120+m*0.1384539782588700+y*0.7978075786430300+r*0.0048233247781713+g*0.8614677684002920+b*0.2012632804510050);R[13]=max(SPECTRAL_EPSILON,w*0.9999527659684070+c*0.9957567501108180+m*0.0537347216940033+y*0.9114498940673840+r*0.0042298748350633+g*0.9458790897676580+b*0.0877524413419623);R[14]=max(SPECTRAL_EPSILON,w*0.9998218368992970+c*0.9959128182867100+m*0.0292174996673231+y*0.9537979630045070+r*0.0040599171299341+g*0.9704654864743050+b*0.0457176793291679);R[15]=max(SPECTRAL_EPSILON,w*0.9997386095575930+c*0.9956061578345280+m*0.0213136517508590+y*0.9712416154654290+r*0.0043533695594676+g*0.9784136302844500+b*0.0284706050521843);R[16]=max(SPECTRAL_EPSILON,w*0.9997095516396120+c*0.9945976009618540+m*0.0201349530181136+y*0.9793031238075880+r*0.0053434425970201+g*0.9795890314112240+b*0.0205271767569850);R[17]=max(SPECTRAL_EPSILON,w*0.9997319302106270+c*0.9922157154923700+m*0.0241323096280662+y*0.9833801195075750+r*0.0076917201010463+g*0.9755335369086320+b*0.0165302792310211);R[18]=max(SPECTRAL_EPSILON,w*0.9997994363461950+c*0.9862364527832490+m*0.0372236145223627+y*0.9854612465677550+r*0.0135969795736536+g*0.9622887553978130+b*0.0145135107212858);R[19]=max(SPECTRAL_EPSILON,w*0.9999003303166710+c*0.9679433372645410+m*0.0760506552706601+y*0.9864350469766050+r*0.0316975442661115+g*0.9231215745131200+b*0.0136003508637687);R[20]=max(SPECTRAL_EPSILON,w*1.0000204065261100+c*0.8912850042449430+m*0.2053754719423990+y*0.9867382506701410+r*0.1078611963552490+g*0.7934340189431110+b*0.0133604258769571);R[21]=max(SPECTRAL_EPSILON,w*1.0001447879365800+c*0.5362024778620530+m*0.5412689034604390+y*0.9866178824450320+r*0.4638126031687040+g*0.4592701359024290+b*0.0135488943145680);R[22]=max(SPECTRAL_EPSILON,w*1.0002599790341200+c*0.1541081190018780+m*0.8158416850864860+y*0.9862777767586430+r*0.8470554052720110+g*0.1855741036663030+b*0.0139594356366992);R[23]=max(SPECTRAL_EPSILON,w*1.0003557969708900+c*0.0574575093228929+m*0.9128177041239760+y*0.9858605924440560+r*0.9431854093939180+g*0.0881774959955372+b*0.0144434255753570);R[24]=max(SPECTRAL_EPSILON,w*1.0004275378026900+c*0.0315349873107007+m*0.9463398301669620+y*0.9854749276762100+r*0.9688621506965580+g*0.0543630228766700+b*0.0148854440621406);R[25]=max(SPECTRAL_EPSILON,w*1.0004762334488800+c*0.0222633920086335+m*0.9599276963319910+y*0.9851769347655580+r*0.9780306674736030+g*0.0406288447060719+b*0.0152254296999746);R[26]=max(SPECTRAL_EPSILON,w*1.0005072096750800+c*0.0182022841492439+m*0.9662605952303120+y*0.9849715740141810+r*0.9820436438543060+g*0.0342215204316970+b*0.0154592848180209);R[27]=max(SPECTRAL_EPSILON,w*1.0005251915637300+c*0.0162990559732640+m*0.9693259700584240+y*0.9848463034157120+r*0.9839236237187070+g*0.0311185790956966+b*0.0156018026485961);R[28]=max(SPECTRAL_EPSILON,w*1.0005350960689600+c*0.0153656239334613+m*0.9708545367213990+y*0.9847753518111990+r*0.9848454841543820+g*0.0295708898336134+b*0.0156824871281936);R[29]=max(SPECTRAL_EPSILON,w*1.0005402209748200+c*0.0149111568733976+m*0.9716050665281280+y*0.9847380666252650+r*0.9852942758145960+g*0.0288108739348928+b*0.0157248764360615);R[30]=max(SPECTRAL_EPSILON,w*1.0005427281678400+c*0.0146954339898235+m*0.9719627697573920+y*0.9847196483117650+r*0.9855072952198250+g*0.0284486271324597+b*0.0157458108784121);R[31]=max(SPECTRAL_EPSILON,w*1.0005438956908700+c*0.0145964146717719+m*0.9721272722745090+y*0.9847110233919390+r*0.9856050715398370+g*0.0282820301724731+b*0.0157556123350225);R[32]=max(SPECTRAL_EPSILON,w*1.0005444821215100+c*0.0145470156699655+m*0.9722094177458120+y*0.9847066833006760+r*0.9856538499335780+g*0.0281988376490237+b*0.0157605443964911);R[33]=max(SPECTRAL_EPSILON,w*1.0005447695999200+c*0.0145228771899495+m*0.9722495776784240+y*0.9847045543930910+r*0.9856776850338830+g*0.0281581655342037+b*0.0157629637515278);R[34]=max(SPECTRAL_EPSILON,w*1.0005448988776200+c*0.0145120341118965+m*0.9722676219987420+y*0.9847035963093700+r*0.9856883918061220+g*0.0281398910216386+b*0.0157640525629106);R[35]=max(SPECTRAL_EPSILON,w*1.0005449625468900+c*0.0145066940939832+m*0.9722765094621500+y*0.9847031240775520+r*0.9856936646900310+g*0.0281308901665811+b*0.0157645892329510);R[36]=max(SPECTRAL_EPSILON,w*1.0005449892705800+c*0.0145044507314479+m*0.9722802433068740+y*0.9847029256150900+r*0.9856958798482050+g*0.0281271086805816+b*0.0157648147772649);R[37]=max(SPECTRAL_EPSILON,w*1.0005449969930000+c*0.0145038009464639+m*0.9722813248265600+y*0.9847028681227950+r*0.9856965214637620+g*0.0281260133612096+b*0.0157648801149616);}vec3 spectral_xyz_to_srgb(vec3 xyz){mat3 XYZ_RGB;XYZ_RGB[0]=vec3(3.2409699419045200,-1.537383177570090,-0.4986107602930030);XYZ_RGB[1]=vec3(-0.9692436362808790,1.875967501507720,0.0415550574071756);XYZ_RGB[2]=vec3(0.0556300796969936,-0.203976958888976,1.0569715142428700);float r=dot(XYZ_RGB[0],xyz);float g=dot(XYZ_RGB[1],xyz);float b=dot(XYZ_RGB[2],xyz);return spectral_linear_to_srgb(vec3(r,g,b));}vec3 spectral_reflectance_to_xyz(float R[SPECTRAL_SIZE]){vec3 xyz=vec3(0.);xyz+=R[0]*vec3(0.0000646919989576,0.0000018442894440,0.0003050171476380);xyz+=R[1]*vec3(0.0002194098998132,0.0000062053235865,0.0010368066663574);xyz+=R[2]*vec3(0.0011205743509343,0.0000310096046799,0.0053131363323992);xyz+=R[3]*vec3(0.0037666134117111,0.0001047483849269,0.0179543925899536);xyz+=R[4]*vec3(0.0118805536037990,0.0003536405299538,0.0570775815345485);xyz+=R[5]*vec3(0.0232864424191771,0.0009514714056444,0.1136516189362870);xyz+=R[6]*vec3(0.0345594181969747,0.0022822631748318,0.1733587261835500);xyz+=R[7]*vec3(0.0372237901162006,0.0042073290434730,0.1962065755586570);xyz+=R[8]*vec3(0.0324183761091486,0.0066887983719014,0.1860823707062960);xyz+=R[9]*vec3(0.0212332056093810,0.0098883960193565,0.1399504753832070);xyz+=R[10]*vec3(0.0104909907685421,0.0152494514496311,0.0891745294268649);xyz+=R[11]*vec3(0.0032958375797931,0.0214183109449723,0.0478962113517075);xyz+=R[12]*vec3(0.0005070351633801,0.0334229301575068,0.0281456253957952);xyz+=R[13]*vec3(0.0009486742057141,0.0513100134918512,0.0161376622950514);xyz+=R[14]*vec3(0.0062737180998318,0.0704020839399490,0.0077591019215214);xyz+=R[15]*vec3(0.0168646241897775,0.0878387072603517,0.0042961483736618);xyz+=R[16]*vec3(0.0286896490259810,0.0942490536184085,0.0020055092122156);xyz+=R[17]*vec3(0.0426748124691731,0.0979566702718931,0.0008614711098802);xyz+=R[18]*vec3(0.0562547481311377,0.0941521856862608,0.0003690387177652);xyz+=R[19]*vec3(0.0694703972677158,0.0867810237486753,0.0001914287288574);xyz+=R[20]*vec3(0.0830531516998291,0.0788565338632013,0.0001495555858975);xyz+=R[21]*vec3(0.0861260963002257,0.0635267026203555,0.0000923109285104);xyz+=R[22]*vec3(0.0904661376847769,0.0537414167568200,0.0000681349182337);xyz+=R[23]*vec3(0.0850038650591277,0.0426460643574120,0.0000288263655696);xyz+=R[24]*vec3(0.0709066691074488,0.0316173492792708,0.0000157671820553);xyz+=R[25]*vec3(0.0506288916373645,0.0208852059213910,0.0000039406041027);xyz+=R[26]*vec3(0.0354739618852640,0.0138601101360152,0.0000015840125870);xyz+=R[27]*vec3(0.0214682102597065,0.0081026402038399,0.0000000000000000);xyz+=R[28]*vec3(0.0125164567619117,0.0046301022588030,0.0000000000000000);xyz+=R[29]*vec3(0.0068045816390165,0.0024913800051319,0.0000000000000000);xyz+=R[30]*vec3(0.0034645657946526,0.0012593033677378,0.0000000000000000);xyz+=R[31]*vec3(0.0014976097506959,0.0005416465221680,0.0000000000000000);xyz+=R[32]*vec3(0.0007697004809280,0.0002779528920067,0.0000000000000000);xyz+=R[33]*vec3(0.0004073680581315,0.0001471080673854,0.0000000000000000);xyz+=R[34]*vec3(0.0001690104031614,0.0000610327472927,0.0000000000000000);xyz+=R[35]*vec3(0.0000952245150365,0.0000343873229523,0.0000000000000000);xyz+=R[36]*vec3(0.0000490309872958,0.0000177059860053,0.0000000000000000);xyz+=R[37]*vec3(0.0000199961492222,0.0000072209749130,0.0000000000000000);return xyz;}float KS(float R){return pow(1.0-R,2.0)/(2.0*R);}float KM(float KS){return 1.0+KS-sqrt(pow(KS,2.0)+2.0*KS);}vec3 spectral_mix(vec3 color1,float tintingStrength1,float factor1,vec3 color2,float tintingStrength2,float factor2){vec3 lrgb1=spectral_srgb_to_linear(color1);vec3 lrgb2=spectral_srgb_to_linear(color2);float R1[SPECTRAL_SIZE];float R2[SPECTRAL_SIZE];spectral_linear_to_reflectance(lrgb1,R1);spectral_linear_to_reflectance(lrgb2,R2);float luminance1=spectral_reflectance_to_xyz(R1)[1];float luminance2=spectral_reflectance_to_xyz(R2)[1];float R[SPECTRAL_SIZE];for(int i=0;i<SPECTRAL_SIZE;i++){float concentration1=pow(factor1,2.)*pow(tintingStrength1,2.)*luminance1;float concentration2=pow(factor2,2.)*pow(tintingStrength2,2.)*luminance2;float totalConcentration=concentration1+concentration2;float ksMix=0.;ksMix+=KS(R1[i])*concentration1;ksMix+=KS(R2[i])*concentration2;R[i]=KM(ksMix/totalConcentration);}return spectral_xyz_to_srgb(spectral_reflectance_to_xyz(R));}vec3 spectral_mix(vec3 color1,vec3 color2,float factor){return spectral_mix(color1,1.,1.-factor,color2,1.,factor);}vec3 spectral_mix(vec3 color1,float factor1,vec3 color2,float factor2){return spectral_mix(color1,1.,factor1,color2,1.,factor2);}const float GAMMA=2.4,EPSILON=0.0001;const float DARKEN_THRESHOLD=0.7;const float EDGE_MIN=0.05,EDGE_MAX=0.35;void main(void){vec2 uv=0.5*p+0.5;vec2 sourceUV=vec2(uv.x,1.0-uv.y);vec2 maskUV=u_targetIsFramebuffer ? vec2(uv.x,1.0-uv.y): uv;vec4 source=texture(u_source,sourceUV);vec4 maskColor=texture(u_mask,maskUV);if(maskColor.a==0.0){outColor=source;return;}vec4 pigment=vec4(u_color.xyz,1.0);if(maskColor.a>DARKEN_THRESHOLD){float blacken=0.5*(min(maskColor.a,1.0)-DARKEN_THRESHOLD);pigment=pigment*(1.0-blacken)-vec4(0.5)*blacken;pigment.rgb=max(pigment.rgb,vec3(0.0));}float mixIntensity=min(maskColor.a,1.0);if(!u_isBrush){vec2 texelSize=1.0/vec2(textureSize(u_mask,0));float scaledAlpha=maskColor.a*15.0;float blurEdge=0.0;for(int i=-2;i<=2;i+=2){for(int j=-2;j<=2;j+=2){vec2 neighborUV=maskUV+vec2(float(i),float(j))*texelSize;float neighborAlpha=texture(u_mask,neighborUV).a*15.0;blurEdge+=smoothstep(EDGE_MIN,EDGE_MAX,length(vec2(dFdx(neighborAlpha),dFdy(neighborAlpha))));}}blurEdge/=9.0;mixIntensity=clamp(maskColor.a+blurEdge*0.1,0.0,1.0);}vec3 bgColor=mix(vec3(1.0),source.rgb,source.a);outColor=vec4(spectral_mix(bgColor,pigment.rgb,mixIntensity),1.);}"),this.glMask=_?.ensureResources?.(n,e,r,i);const a=b?.ensureResources?.(n,e,r,i,v)??{mask:null,ctx:null};t&&(n.blendSourceFramebuffer=((...t)=>p.ensureBlendSourceFramebuffer(...t))(n,n.blendSourceFramebuffer,e,r,i)),this.mask=a.mask,this.ctx=a.ctx},blend(t=!1,e=!1){S();const r=!0===this.isBrush,n=r?this.glMask:this.mask,i=r?this.mask:this.glMask,a=t?._array,o=!!a&&(this.cachedColor?.[0]!==a[0]||this.cachedColor?.[1]!==a[1]||this.cachedColor?.[2]!==a[2]||this.cachedColor?.[3]!==a[3]);!this.isBlending&&a&&(this.isBlending=!0,this.cachedColor=a,this.clearMask(this.glMask)),(e||o)&&(this.justChanged&&(this.applyShader(i,!r),this.justChanged=!1),this.isBlending&&this.applyShader(n,r),a&&(this.cachedColor=a),e&&(this.isBlending=!1,this.cachedColor=null))},applyShader(t,i){if(!t?.isDrawn)return;const a=this.getCompositeRect(t,i);if(!a)return void this.clearMask(t);n.drawingContext;const o=n.shaderProgram,s=m(),c=((...t)=>p.blitSourceToFramebuffer(...t))({renderer:n,sourceTarget:s??n,sourceFramebuffer:n.blendSourceFramebuffer,dirtyRect:a,isFramebufferTarget:d,Cwidth:e,Cheight:r,getTargetPixelSize:R,toScissorBox:A,withScissor:M}),l=!!s,u=(i?_:b).getShaderMask(n,t,a,w,E,v);((...t)=>{p.runBlendShaderPass(...t)})({renderer:n,shader:o,source:c,mask:u,color:this.cachedColor,isBrushMask:i,Cwidth:e,Cheight:r,dirtyRect:a,targetIsFramebuffer:l,withScissor:M}),this.clearMask(t)}},C=()=>{S(),P.blend(!1,!0),P.clearMask(P.glMask),P.clearMask(P.mask),P.justChanged=!1,P.isBlending=!1,P.isBrush=null,P.cachedColor=null},F=(t=!1)=>{((t=!1)=>{l.load(t)})(t),n.loaded&&P.load()},k=Math.sqrt(3),I=.5*(k-1),L=(3-k)/6,D=t=>0|Math.floor(t),N=new Float64Array([1,1,-1,1,1,-1,-1,-1,1,0,-1,0,1,0,-1,0,0,1,0,-1,0,1,0,-1]);function B(t=Math.random){const e=function(t){const e=new Uint8Array(512);for(let t=0;t<256;t++)e[t]=t;for(let r=0;r<255;r++){const n=r+~~(t()*(256-r)),i=e[r];e[r]=e[n],e[n]=i}for(let t=256;t<512;t++)e[t]=e[t-256];return e}(t),r=new Float64Array(e).map(t=>N[t%12*2]),n=new Float64Array(e).map(t=>N[t%12*2+1]);return function(t,i){let a=0,o=0,s=0;const c=(t+i)*I,l=D(t+c),u=D(i+c),h=(l+u)*L,f=t-(l-h),m=i-(u-h);let d,x;f>m?(d=1,x=0):(d=0,x=1);const g=f-d+L,p=m-x+L,y=f-1+2*L,_=m-1+2*L,b=255&l,v=255&u;let R=.5-f*f-m*m;if(R>=0){const t=b+e[v];R*=R,a=R*R*(r[t]*f+n[t]*m)}let w=.5-g*g-p*p;if(w>=0){const t=b+d+e[v+x];w*=w,o=w*w*(r[t]*g+n[t]*p)}let E=.5-y*y-_*_;if(E>=0){const t=b+1+e[v+1];E*=E,s=E*E*(r[t]*y+n[t]*_)}return 70*(a+o+s)}}function U(t,e){let r=new O(t),n=()=>r.next();return n.double=()=>n()+11102230246251565e-32*(2097152*n()|0),n.int32=()=>4294967296*r.next()|0,n.quick=n,n}class O{constructor(t){null==t&&(t=+new Date);let e=4022871197;function r(t){t=String(t);for(let r=0;r<t.length;r++){e+=t.charCodeAt(r);let n=.02519603282416938*e;e=n>>>0,n-=e,n*=e,e=n>>>0,n-=e,e+=4294967296*n}return 2.3283064365386963e-10*(e>>>0)}this.c=1,this.s0=r(" "),this.s1=r(" "),this.s2=r(" "),this.s0-=r(t),this.s0<0&&(this.s0+=1),this.s1-=r(t),this.s1<0&&(this.s1+=1),this.s2-=r(t),this.s2<0&&(this.s2+=1)}next(){let{c:t,s0:e,s1:r,s2:n}=this,i=2091639*e+2.3283064365386963e-10*t;return this.s0=r,this.s1=n,this.s2=i-(this.c=0|i)}copy(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}}let Y=U(Math.random()),z=U(Math.random());const X=[],G=t=>X.push(t),Z=t=>{Y=U(t),z=U(`${t}:2`);for(const t of X)t()};let V=B(U(Math.random())),$=B(U(Math.random()));const H=t=>{V=B(U(t)),$=B(U(`${t}:2`))},W=(t=0,e=1)=>t+Y()*(e-t),q=(t=0,e=1)=>t+z()*(e-t),j=t=>t[~~(Y()*t.length)],K=(t,e)=>~~W(t,e),J=(t,e)=>~~q(t,e),Q=(t=0,e=1)=>{const r=1-Y(),n=Y();return Math.sqrt(-2*Math.log(r))*ct(360*n)*e+t},tt=t=>{let e=0;const r=[];for(const n in t)e+=t[n],r.push({key:n,cumulative:e});const n=Y()*e;for(const{key:t,cumulative:e}of r)if(n<e)return isNaN(t)?t:parseInt(t)},et=(t,e,r,n,i,a=!1)=>{let o=n+(t-e)/(r-e)*(i-n);return a?n<i?rt(o,n,i):rt(o,i,n):o},rt=(t,e,r)=>Math.max(Math.min(t,r),e),nt=t=>(t%=360)<0?t+360:t,it=1440,at=2*Math.PI/it,ot=new Float32Array(it).fill(NaN),st=new Float32Array(it).fill(NaN),ct=t=>{const e=~~(4*nt(t));let r=ot[e];return isNaN(r)&&(r=Math.cos(e*at),ot[e]=r),r},lt=t=>{const e=~~(4*nt(t));let r=st[e];return isNaN(r)&&(r=Math.sin(e*at),st[e]=r),r},ut=(t,e=!1)=>{if(e||a()){let e=180*t/Math.PI%360;return e<0?e+360:e}return t},ht=(t,e=!1)=>e||a()?180*t/Math.PI:t,ft=(t,e,r,n,i)=>{let a=ct(i),o=lt(i);return{x:a*(r-t)+o*(n-e)+t,y:a*(n-e)-o*(r-t)+e}},mt=(t,e,r,n)=>Math.hypot(r-t,n-e),dt=(t,e,r,n)=>ut(Math.atan2(-(n-e),r-t),!0),xt=(t,e,r,n,i=!1)=>{let a=t.x,o=t.y,s=e.x,c=e.y,l=r.x,u=r.y,h=n.x,f=n.y;if(a===s&&o===c||l===h&&u===f)return!1;let m=s-a,d=c-o,x=h-l,g=f-u,p=g*m-x*d;if(0===p)return!1;let y=(x*(o-u)-g*(a-l))/p,_=(m*(o-u)-d*(a-l))/p;return!(!i&&(_<0||_>1))&&{x:a+y*m,y:o+y*d}};let gt=!1;function pt(){gt||(S(),_t=.01*e,bt=-.5*e,vt=-.5*r,Rt=Math.round(2*e/_t),wt=Math.round(2*r/_t),Ft("hand",(t,e)=>{const r=q(.2,.8),n=J(5,10);return Lt(e,(e,i)=>.5*n*lt(r*i*e+J(15,25))*.2*ct(t)+$(e,i)*n*.7)}),Ft("curved",(t,e)=>{let r=J(-10,10);return J(0,100)%2==0&&(r*=-1),Lt(e,(e,n)=>3*et($(.02*e+.03*t,.02*n+.03*t),0,1,-r,r))}),Ft("zigzag",(t,e)=>{let r=J(-30,-15)+Math.abs(44*lt(t));J(0,100)%2==0&&(r*=-1);let n=r,i=0;for(let t=0;t<Rt;t++){for(let r=0;r<wt;r++)e[t][r]=i,i+=n,n*=-1;i+=n,n*=-1}return e}),Ft("waves",(t,e)=>{const r=J(10,15)+5*lt(t),n=J(3,6)+3*ct(t),i=J(20,35);return Lt(e,(t,e)=>lt(r*t)*i*ct(e*n)+J(-3,3))}),Ft("seabed",(t,e)=>{const r=q(.4,.8),n=J(18,26);return Lt(e,(e,i)=>1.1*n*lt(r*i*e+J(15,20))*ct(t))}),Ft("spiral",(t,e)=>{const r=J(5,10),n=2*J(0,2)-1,i=J(65,80),a=Array.from({length:r},()=>({x:q(.1,.9)*Rt,y:q(.1,.9)*wt}));return Lt(e,(t,e)=>{let r=0,o=0;for(const s of a){const a=t-s.x,c=e-s.y,l=1/(a*a+c*c+1),u=Math.atan2(c,a)*(180/Math.PI),h=n*(u+i)*Math.PI/180;r+=l*Math.cos(h),o+=l*Math.sin(h)}return Math.atan2(o,r)*(180/Math.PI)})}),Ft("columns",(t,e)=>{const r=J(3,8),n=J(25,45);return Lt(e,(t,e)=>lt(t*r)*n)}),gt=!0)}class yt{constructor(t,e){pt();const r=c();this.mx=r.x,this.my=r.y,this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=Math.round((t+this.mx-bt)/_t),this.rowIdx=Math.round((e+this.my-vt)/_t)}reset(){this.plotted=0}isIn(){return T.field.isActive?yt.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const t=e,n=r,i=this.x+this.mx,a=this.y+this.my;return i>=-.3*t&&i<=1.3*t&&a>=-.3*n&&a<=1.3*n}angle(t=!1){return T.field.isActive&&(t||this.isIn())?Et.get(T.field.current).field[this.colIdx][this.rowIdx]*T.field.wiggle:0}moveTo(t,e,r=1){this.movePos(ht(t),e,r)}_moveToDegrees(t,e,r=1){this.movePos(t,e,r)}plotTo(t,e,r,n=1){this.movePos(t,e,r,n)}movePos(t,e,r,n=!1){const i=n||1;if(!this.isIn())return void(this.plotted+=r/i);const a=e/r,o=T.field.isActive,s=!!n;for(let e=0;e<a;e++){const e=(o?this.angle(!0):0)-(s?t.angle(this.plotted):t);this.update(this.x+r*ct(e),this.y+r*lt(e)),this.plotted+=r/i}}static getRowIndex(t,e=1){const r=t+c().y-vt;return Math.round(r/_t/e)}static getColIndex(t,e=1){const r=t+c().x-bt;return Math.round(r/_t/e)}static isIn(t,e){return t>=0&&e>=0&&t<Rt&&e<wt}}T.field={isActive:!1,current:null,wiggle:1};let _t,bt,vt,Rt,wt,Et=new Map;const At=new Set(["degrees","radians"]);function Mt(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!At.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function Tt(t,e){return function(t,e){if("radians"!==e)return t;for(let e=0;e<t.length;e++)for(let r=0;r<t[e].length;r++)t[e][r]=ht(t[e][r],!0);return t}(t.gen(e,new Array(Rt).fill(null).map(()=>new Float32Array(wt))),t.angleMode)}function St(t=0){if(!T.field.isActive||!T.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=Et.get(T.field.current);e.field=Tt(e,t)}function Pt(t){if(T.field.wiggle||(T.field.wiggle=1),pt(),!Et.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(Et.keys()).join(", ")}.`);T.field.isActive=!0,T.field.current=t;const e=Et.get(t);e.field||(e.field=Tt(e,0))}function Ct(){pt(),T.field.isActive=!1}function Ft(t,e,r={}){Et.set(t,{gen:e,field:null,angleMode:Mt(r)})}function kt(){return pt(),Array.from(Et.keys())}function It(t=1){Pt("hand"),T.field.wiggle=t}function Lt(t,e){for(let r=0;r<Rt;r++)for(let n=0;n<wt;n++)t[r][n]=e(r,n);return t}const Dt=[],Nt=(t,e,r)=>Math.max(e,Math.min(t,r)),Bt="degrees",Ut="radians";let Ot=null,Yt=Bt;const zt=[];let Xt={a:1,b:0,c:0,d:1,x:0,y:0};function Gt(t,e){return{a:t.a*e.a+t.c*e.b,b:t.b*e.a+t.d*e.b,c:t.a*e.c+t.c*e.d,d:t.b*e.c+t.d*e.d,x:t.a*e.x+t.c*e.y+t.x,y:t.b*e.x+t.d*e.y+t.y}}class Zt{constructor(t,e,r){if(t?._array)return this.r=Math.round(255*t._array[0]),this.g=Math.round(255*t._array[1]),this.b=Math.round(255*t._array[2]),this.hex=this.rgbToHex(this.r,this.g,this.b),this._array=[...t._array],void(this.gl=this._array);if("string"==typeof t){const e=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)$/i.exec(t);if(e){this.r=Nt(parseInt(e[1]),0,255),this.g=Nt(parseInt(e[2]),0,255),this.b=Nt(parseInt(e[3]),0,255),this.hex=this.rgbToHex(this.r,this.g,this.b);const t=void 0!==e[4]?Nt(parseFloat(e[4]),0,1):1;return this._array=[this.r/255,this.g/255,this.b/255,t],void(this.gl=this._array)}this.hex=this.standardize(t);const r=this.hexToRgb(this.hex);this.r=r.r,this.g=r.g,this.b=r.b}else this.r=Nt(t??0,0,255),this.g=Nt(e??t??0,0,255),this.b=Nt(r??t??0,0,255),this.hex=this.rgbToHex(this.r,this.g,this.b);this._array=[this.r/255,this.g/255,this.b/255,1],this.gl=this._array}rgbToHex(t,e,r){return`#${(1<<24|t<<16|e<<8|r).toString(16).slice(1)}`}hexToRgb(t){t=t.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,(t,e,r,n)=>e+e+r+r+n+n);const e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(!e)throw new Error(`Invalid color value "${t}".`);return{r:parseInt(e[1],16),g:parseInt(e[2],16),b:parseInt(e[3],16)}}standardize(t){const e=function(){if(Ot)return Ot;if("undefined"!=typeof document)return Ot=document.createElement("canvas").getContext("2d"),Ot;if("undefined"!=typeof OffscreenCanvas)return Ot=new OffscreenCanvas(1,1).getContext("2d"),Ot;throw new Error("Standalone color parsing requires CanvasRenderingContext2D support.")}();return e.fillStyle=t,e.fillStyle}_getRed(){return this.r}_getGreen(){return this.g}_getBlue(){return this.b}}function Vt(t){if(t!==Bt&&t!==Ut)throw new Error(`Invalid angle mode "${t}". Use "degrees" or "radians".`);Yt=t}function $t(){return Yt}function Ht(){pt(),Dt.push({fill:{...T.fill},wash:T.wash?{...T.wash}:null,stroke:{...T.stroke},hatch:{...T.hatch},mass:T.mass?{...T.mass}:null,field:{...T.field}}),zt.push({...Xt})}function Wt(){0!==zt.length&&(Xt=zt.pop(),function(){const t=Dt.pop();t&&(T.stroke={...t.stroke},T.field={...t.field},T.hatch={...t.hatch},T.fill={...t.fill},t.wash&&(T.wash={...t.wash}),t.mass?T.mass={...t.mass}:T.mass&&(T.mass={...T.mass,isActive:!1,brush:null,color:null,options:{}}))}())}function qt(t,e){Xt=Gt(Xt,{a:1,b:0,c:0,d:1,x:t,y:e})}function jt(t){const e=Yt===Ut?t:t*Math.PI/180,r=Math.cos(e),n=Math.sin(e);Xt=Gt(Xt,{a:r,b:n,c:-n,d:r,x:0,y:0})}function Kt(t,e=t){Xt=Gt(Xt,{a:t,b:0,c:0,d:e,x:0,y:0})}function Jt(){var t;(t={usesRadians:()=>"radians"===Yt,fromDegrees:t=>"radians"===Yt?t*Math.PI/180:t,createColor:(...t)=>1===t.length&&t[0]?._array?t[0]:new Zt(...t),getAffineMatrix:()=>Xt}).usesRadians&&(a=t.usesRadians),t.fromDegrees&&(o=t.fromDegrees),t.createColor&&(s=t.createColor),t.getAffineMatrix&&(c=t.getAffineMatrix)}function Qt(){C()}function te(...t){h(),P.glMask&&P.clearMask(P.glMask),P.mask&&P.clearMask(P.mask),P.justChanged=!1,P.isBlending=!1,P.isBrush=null,P.cachedColor=null;const e=n.drawingContext,r=0===t.length?[1,1,1,0]:[...s(...t)._array.slice(0,3),1];e.bindFramebuffer(e.FRAMEBUFFER,null),e.disable(e.SCISSOR_TEST),e.clearColor(r[0],r[1],r[2],r[3]),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}let ee,re,ne,ie,ae=null,oe=!1,se=1,ce=0,le=0;function ue(t,e,r,n){ae=t,ce=e,le=r,se=n;const i=function(t,e,r,n){const i=function(t){return t.getContext("webgl2",{premultipliedAlpha:!0})??t.getContext("webgl2")}(t);if(!i)throw new Error("brush.load(target) requires a canvas with a WebGL2 context.");return{canvas:t,drawingContext:i,width:e,height:r,pixelDensity:()=>n}}(t,e,r,n);u({Renderer:i,Cwidth:e,Cheight:r,Density:n}),oe=!0}function he(t,e,r={}){if("undefined"==typeof document)throw new Error("brush.createCanvas() requires a browser document.");const n=Math.max(1,Math.round(t)),i=Math.max(1,Math.round(e)),a=Math.max(1,Number(r.pixelDensity)||1),o=document.createElement("canvas");if(o.width=Math.max(1,Math.round(n*a)),o.height=Math.max(1,Math.round(i*a)),o.style.width=`${n}px`,o.style.height=`${i}px`,r.id&&(o.id=r.id),r.parent){const t="string"==typeof r.parent?document.querySelector(r.parent):r.parent;if(!t)throw new Error(`Could not find parent "${r.parent}" for brush.createCanvas().`);t.appendChild(o)}return ue(o,n,i,a),o}class fe{constructor(t,e=!1){this.a=t,this.vertices=e?t:t.map(([t,e])=>({x:t,y:e})),this.sides=this.vertices.map((t,e,r)=>[t,r[(e+1)%r.length]]),this._intersectionCache={}}intersect(t){const e=`${t.point1.x},${t.point1.y}-${t.point2.x},${t.point2.y}`;if(this._intersectionCache[e])return this._intersectionCache[e];const r=[];for(const[e,n]of this.sides){const i=xt(t.point1,t.point2,e,n);i&&r.push(i)}return this._intersectionCache[e]=r,r}show(){T.wash&&this.wash(),T.fill&&this.fill(),T.mass&&this.mass(),T.hatch&&this.hatch(),T.stroke&&this.draw()}}class me{constructor(t){this.segments=[],this.angles=[],this.pres=[],this.type=t,this.dir=0,this.calcIndex(0),this.pol=!1}addSegment(t=0,e=0,r=1,n=!1){this.angles.length>0&&this.angles.pop(),t=n?(t%360+360)%360:ut(t),this.angles.push(t,t),this.pres.push(r),this.segments.push(e),this.length=this.segments.reduce((t,e)=>t+e,0)}endPlot(t=0,e=1,r=!1){t=r?(t%360+360)%360:ut(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=ut(t)}pressure(t){return t>this.length?this.pres[this.pres.length-1]:this.curving(this.pres,t)}angle(t){return t>this.length?this.angles[this.angles.length-1]:(this.calcIndex(t),"curve"===this.type?this.curving(this.angles,t)+this.dir:this.angles[this.index]+this.dir)}curving(t,e){let r=t[this.index],n=t[this.index+1]??r;return Math.abs(n-r)>180&&(n>r?n=-(360-n):r=-(360-r)),et(e-this.suma,0,this.segments[this.index],r,n,!0)}calcIndex(t){this.index=-1,this.suma=0;let e=0;for(;e<=t;)this.suma=e,e+=this.segments[this.index+1],this.index++;return this.index}genPol(t,n,i=1,a){pt();const o=a<0?4:1,s=[],c=Math.round(this.length/o),l=new yt(t+e/2,n+r/2);let u=0,h=0;for(let t=0;t<c;t++){l.plotTo(this,o,o);const t=this.calcIndex(l.plotted);u+=o,(u>=(a<=0?8:Math.max(this.segments[t]*a*q(.7,1.3),20))||t>=h)&&l.x&&(s.push([l.x-e/2,l.y-r/2]),u=0,t>=h&&h++)}return new fe(s)}show(t,e,r=1){T.wash&&this.wash(t,e,r),T.fill&&this.fill(t,e,r),T.mass&&this.mass(t,e,r),T.hatch&&this.hatch(t,e,r),T.stroke&&this.draw(t,e,r)}}function de(t){new fe(t).show()}function xe(t,e,r,n,i="corner"){"center"===i&&(t-=r/2,e-=n/2),_e(0),be(t,e),be(t+r,e),be(t+r,e+n),be(t,e+n),ve(!0)}function ge(t,e,r,n=!1){const i=new me("curve"),a=Math.PI*r,o=q(0,360),s=n?()=>1+.2*n*q():()=>1;for(let t=0;t<4;t++){const e=-90*t+o;i.addSegment(e*s(),a/2*s(),1,!0)}if(n){const t=n*J(-5,5);i.addSegment(o,Math.abs(t)*(Math.PI/180)*r,1,!0),i.endPlot(t+o,1,!0)}else i.endPlot(o,1,!0);const c=t-r*lt(o),l=e-r*ct(-o);i.show(c,l,1)}function pe(t,e,r,n,i){const a=ht(n),o=((ht(i)-a)%360+360)%360;if(0===o)return;const s=new me("curve"),c=Math.max(1,Math.ceil(o/90)),l=o/c,u=Math.PI*r*l/180;for(let t=0;t<c;t++)s.addSegment(a+t*l+90,u,1,!0);s.endPlot(a+o+90,1,!0);const h=t+r*ct(a),f=e-r*lt(a);s.draw(h,f,1)}class ye{constructor(){this.isClosed=!1,this.curvature=re,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){Me(this.vert,this.curvature,this.isClosed).show()}}function _e(t=0){re=rt(t,0,1),ee=new ye}function be(t,e,r=1){if(!ee)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");ee.vertex(t,e,r)}function ve(t=!1){if(!ee)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(ee.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(ee.vertex(...ee.vert[0]),ee.isClosed=!0),ee.show(),ee=!1}function Re(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);ie=[e,r],ne=new me(t)}function we(t,e,r){if(!ne)throw new Error("move() called without beginStroke(). Call beginStroke() first.");ne.addSegment(t,e,r)}function Ee(t,e){if(!ne)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");ne.endPlot(t,e),ne.draw(ie[0],ie[1],1),ne=!1}function Ae(t,e=.5){if(!t||t.length<2)throw new Error("spline() requires at least 2 points. Each point should be [x, y, pressure].");Me(t,e).draw()}function Me(t,e=.5,r=!1){const n=new me(0===e?"segments":"curve"),i=2*Math.PI;if(r&&0!==e&&t.push(t[1]),t&&t.length>0){let a,o,s,c=0;for(let l=0;l<t.length-1;l++)if(e>0&&l<t.length-2){const u=t[l],h=t[l+1],f=t[l+2],m=mt(u[0],u[1],h[0],h[1]),d=mt(h[0],h[1],f[0],f[1]),x=dt(u[0],u[1],h[0],h[1]),g=dt(h[0],h[1],f[0],f[1]),p=e*Math.min(m,d,.5*Math.min(m,d)),y=Math.max(m,d),_=m-p,b=d-p;if(Math.floor(x)===Math.floor(g)){const e=r&&0===l?0:m-c,i=r?0===l?0:d-s:d;n.addSegment(x,e,u[2],!0),l===t.length-3&&n.addSegment(g,i,h[2],!0),c=0,0===l&&(a=m,s=p,o=t[1],c=0)}else{const e={x:h[0]-p*ct(-x),y:h[1]-p*lt(-x)},f={x:e.x+y*ct(90-x),y:e.y+y*lt(90-x)},m={x:h[0]+p*ct(-g),y:h[1]+p*lt(-g)},d={x:m.x+y*ct(90-g),y:m.y+y*lt(90-g)},v=xt(e,f,m,d,!0),R=mt(e.x,e.y,v.x,v.y),w=mt(e.x,e.y,m.x,m.y)/2,E=i*R*(2*Math.asin(w/R)*(180/Math.PI))/360,A=r&&0===l?0:_-c,M=l===t.length-3?r?a-p:b:0;n.addSegment(x,A,u[2],!0),n.addSegment(x,isNaN(E)?0:E,u[2],!0),n.addSegment(g,M,h[2],!0),c=p,0===l&&(a=_,s=p,o=[e.x,e.y])}l===t.length-3&&n.endPlot(g,h[2],!0)}else if(0===e){const e=t[l],r=t[l+1],i=mt(e[0],e[1],r[0],r[1]),a=dt(e[0],e[1],r[0],r[1]);n.addSegment(a,i,r[2],!0),l===t.length-2&&n.endPlot(a,1,!0)}n.origin=r&&0!==e?o:t[0]}return n}let Te={createTipSurface:()=>{throw new Error("No stroke runtime adapter registered.")},loadImageTip:()=>{throw new Error("No stroke runtime adapter registered.")}},Se=!1;const Pe=(t,e,r)=>{const n=t.createProgram();for(let[i,a]of[[t.VERTEX_SHADER,e],[t.FRAGMENT_SHADER,r]]){const e=t.createShader(i);t.shaderSource(e,a),t.compileShader(e),t.attachShader(n,e)}return t.linkProgram(n),n};let Ce={beginDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},endDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},resetDirectShaderTracking:()=>{}};const Fe=(t,e)=>Ce.resetDirectShaderTracking(t,e);let ke,Ie,Le,De,Ne,Be=!1,Ue=0,Oe=0,Ye=null;const ze={},Xe={};let Ge=1,Ze=0,Ve=0,$e=1,He=0,We=0,qe=0,je=0,Ke=1,Je=1,Qe=new Float32Array(8192),tr=0,er=2048,rr=32768,nr=null,ir=null,ar=null,or=null,sr=null;const cr={},lr={};let ur=0,hr=new Float32Array(1280),fr=0,mr=256,dr=null;const xr=new Map,gr=new Float32Array([-1,-1,1,-1,-1,1,1,1]);function pr(){return Ie}function yr(){return((t,e,r)=>Ce.beginDirectMaskDraw(t,e,r))(n,ke,P.glMask)}function _r(t){((t,e,r)=>{Ce.endDirectMaskDraw(t,e,r)})(n,ke,t)}function br(t,e,r,n,i){return t?(e<t.minX&&(t.minX=e),r<t.minY&&(t.minY=r),n>t.maxX&&(t.maxX=n),i>t.maxY&&(t.maxY=i),t):{minX:e,minY:r,maxX:n,maxY:i}}function vr(t,e,r,n){if(tr>=er){er*=2;const t=new Float32Array(4*er);t.set(Qe),Qe=t}const i=t-qe,a=e-je,o=4*tr,s=Ge*i+Ve*a+He+qe,c=Ze*i+$e*a+We+je,l=Je*r*Ke/2;Qe[o]=s,Qe[o+1]=c,Qe[o+2]=l,Qe[o+3]=n/255;const u=s*Je,h=c*Je;nr=br(nr,u-l-1,h-l-1,u+l+1,h+l+1),tr++}function Rr(t,e){if(0===fr)return;P.glMask.isDrawn=!0;const r=yr();let i=xr.get(e);i||(i=ke.createTexture(),ke.bindTexture(ke.TEXTURE_2D,i),ke.texImage2D(ke.TEXTURE_2D,0,ke.RGBA,ke.RGBA,ke.UNSIGNED_BYTE,t.canvas),ke.texParameteri(ke.TEXTURE_2D,ke.TEXTURE_MIN_FILTER,ke.LINEAR),ke.texParameteri(ke.TEXTURE_2D,ke.TEXTURE_MAG_FILTER,ke.LINEAR),ke.texParameteri(ke.TEXTURE_2D,ke.TEXTURE_WRAP_S,ke.CLAMP_TO_EDGE),ke.texParameteri(ke.TEXTURE_2D,ke.TEXTURE_WRAP_T,ke.CLAMP_TO_EDGE),xr.set(e,i)),ke.useProgram(ir),ke.enable(ke.BLEND),ke.blendFunc(ke.ONE_MINUS_DST_ALPHA,ke.ONE),ke.activeTexture(ke.TEXTURE0),ke.bindTexture(ke.TEXTURE_2D,i),ke.uniform1i(lr.u_tex,0);const a=T.stroke.color._array;ke.uniform4f(lr.u_color,...a),ke.uniformMatrix4fv(lr.u_proj,!1,pr()),ke.bindVertexArray(ar),ke.bindBuffer(ke.ARRAY_BUFFER,sr);const o=5*fr*4,s=hr.subarray(0,5*fr);o>ur?(ke.bufferData(ke.ARRAY_BUFFER,hr,ke.DYNAMIC_DRAW),ur=hr.byteLength):ke.bufferSubData(ke.ARRAY_BUFFER,0,s),ke.drawArraysInstanced(ke.TRIANGLE_STRIP,0,4,fr),ke.flush(),ke.bindVertexArray(null),ke.bindTexture(ke.TEXTURE_2D,null),_r(r),dr&&(P.markDirtyRect(P.glMask,dr),dr=null),fr=0,Fe(n,ke)}Se||(_={ensureResources:function(t,e,r,n){return function(t,e,r,n){return!t.glMask||t.glMask.width!==e||t.glMask.height!==r||"function"==typeof t.glMask.pixelDensity&&t.glMask.pixelDensity()!==n}(t,e,r,n)&&(t.glMask?.remove&&t.glMask.remove(),t.glMask=y(t,{width:e,height:r,density:n,antialias:!1,depth:!1,stencil:!1})),t.glMask.dirtyRect??=null,t.glMask.isDrawn??=!1,t.glMask},clearMask:function(t,e){t&&(e(t),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:function(t,e,r,n,i){return t?t.dirtyRect?e()?r():i(n(t.dirtyRect,2)):r():null},getShaderMask:function(t,e){return e}},Se=!0),T.stroke={color:null,weight:1,type:"HB",isActive:!1,opacity:1};let wr=new Map;const Er={offset:.08,scale:.08,warp:.06,tilt:.06};function Ar(){return{...T.stroke}}function Mr(t){T.stroke={...t}}function Tr(t,e){if(e.type=["marker","custom","image","spray"].includes(e.type)?e.type:"default",void 0===e.markerTip&&(e.markerTip=!0),void 0===e.noise&&(e.noise=.3),e.noise=Math.max(0,Math.min(1,e.noise)),void 0!==e.vibration&&void 0===e.scatter&&(e.scatter=e.vibration),void 0!==e.definition&&void 0===e.sharpness&&(e.sharpness=e.definition),void 0!==e.quality&&void 0===e.grain&&(e.grain=e.quality),e.pressure=function(t){if(!t)return t;if("function"==typeof t)return{type:"custom",min_max:[0,1],curve:t,variation:{...Er}};if("object"==typeof t&&!Array.isArray(t)){if("custom"===t.type||"custom"===t.mode){const{mode:e,...r}=t;return{...r,type:"custom",variation:{...Er,...r.variation??{}}}}return"gaussian"===t.type||"gaussian"===t.mode||Array.isArray(t.curve)&&Array.isArray(t.min_max)?{...t,type:"gaussian",curve:t.curve,min_max:t.min_max}:t}if(Array.isArray(t)){const[e,r,n]=2===t.length?[t[0],(t[0]+t[1])/2,t[1]]:t,i=Math.min(e,r,n),a=Math.max(e,r,n),o=a-i||1,[s,c,l]=[(e-i)/o,(r-i)/o,(n-i)/o];return{type:"custom",min_max:[i,a],variation:{...Er},curve:t=>t<.5?s+(c-s)*t*2:c+(l-c)*(t-.5)*2}}}(e.pressure),"custom"===e.type){if("function"!=typeof e.tip)throw new Error(`Brush "${t}" is type "custom" but is missing a tip function.`);const r=`custom::${t}`;!function(t){const e=xr.get(t);e&&ke&&ke.deleteTexture(e),xr.delete(t)}(r);const n=Te.createTipSurface(500,500);return n.pixelDensity(1),n.background(255),n.noSmooth(),n.push(),n.translate(250,250),n.scale(5),n.noStroke(),e.tip(n),n.pop(),rn.imageToWhite(n),rn.tips.set(r,n),e.tipKey=r,void wr.set(t,{param:e,colors:[],buffers:[]})}if("image"===e.type){if(!e.image||!e.image.src)throw new Error(`Brush "${t}" is type "image" but is missing params.image.src. Example: image: { src: "./tip.jpg" }`);return rn.add(e.image.src),wr.set(t,{param:e,colors:[],buffers:[]}),rn.load()}wr.set(t,{param:e,colors:[],buffers:[]})}function Sr(){return[...wr.keys()]}function Pr(t){return wr.get(t)?.param??null}function Cr(t){for(const{param:e}of wr.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)}function Fr(t){if(!wr.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...wr.keys()].join(", ")}.`);T.stroke.type=t}function kr(t,e,r){h(),T.stroke.color=s(...arguments),T.stroke.isActive=!0}function Ir(t){T.stroke.weight=t}function Lr(t,e,r=1){Fr(t),kr(e),Ir(r)}function Dr(){T.stroke.isActive=!1}function Nr(t){return h(),t}function Br(){}let Ur,Or,Yr,zr;const Xr={};function Gr(t,n,a,o=!1){!function(){const t=c();Ge=t.a,Ze=t.b,Ve=t.c,$e=t.d,He=t.x,We=t.y,qe=e/2,je=r/2,Ke=Math.sqrt(Ge*Ge+Ze*Ze),Je=i}(),Ur=new yt(t+e/2,n+r/2),Or=a,Yr=o,Yr&&Yr.calcIndex(0)}const Zr=[];function Vr(t,i){i||(zr=t),function(){Xr.seed=999999*W();const{param:t}=wr.get(T.stroke.type)??{};if(!t)return;Xr.p=t;const{pressure:i}=t;if(Xr.a="custom"!==i.type?W(-1,1):0,Xr.b="custom"!==i.type?W(1,1.5):0,"custom"!==i.type)Xr.cp=W(3,3.5),Xr.ct=0,Xr.cs=1,Xr.ck=0;else{const t=i.variation??Er;Xr.cp=W(-t.offset,t.offset),Xr.ct=W(-t.warp,t.warp),Xr.cs=W(1-t.scale,1+t.scale),Xr.ck=W(-t.tilt,t.tilt)}[Xr.min,Xr.max]=i.min_max,Xr.noiseoffset=.05*Xr.p.noise,Yr||(Xr.cos=ct(zr),Xr.sin=lt(zr)),function(){S(),function(){const t=n?.glMask;t&&(Ye=t,Ye.dirtyRect??=null,Ye.isDrawn??=!1,P.glMask=Ye)}();const t=n.drawingContext,i=!Be||ke!==t;(i||Ue!==e||Oe!==r)&&(Ie=new Float32Array([2/e,0,0,0,0,2/r,0,0,0,0,1,0,-1,-1,0,1]),Ue=e,Oe=r),i&&(ke=t,Ne=Pe(ke,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_position;in float a_radius;in float a_alpha;uniform mat4 u_matrix;out float v_alpha;void main(){gl_Position=u_matrix*vec4(a_position,0.0,1.0);v_alpha=a_alpha;gl_PointSize=a_radius*2.0;}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin float v_alpha;out vec4 outColor;uniform vec4 u_color;void main(){vec2 v=gl_PointCoord-vec2(0.5);float f=length(v);float a=fwidth(f);f=1.0-smoothstep(0.5-a,0.5+a,f);if(f<0.01){discard;}outColor=vec4(u_color.xyz,v_alpha*f);}"),ke.useProgram(Ne),ke.enable(ke.BLEND),ke.blendFunc(ke.ONE_MINUS_DST_ALPHA,ke.ONE),["a_position","a_radius","a_alpha"].forEach(t=>ze[t]=ke.getAttribLocation(Ne,t)),["u_matrix","u_color"].forEach(t=>Xe[t]=ke.getUniformLocation(Ne,t)),Le=ke.createVertexArray(),ke.bindVertexArray(Le),De=ke.createBuffer(),ke.bindBuffer(ke.ARRAY_BUFFER,De),ke.bufferData(ke.ARRAY_BUFFER,Qe.byteLength,ke.DYNAMIC_DRAW),rr=Qe.byteLength,ke.enableVertexAttribArray(ze.a_position),ke.vertexAttribPointer(ze.a_position,2,ke.FLOAT,!1,16,0),ke.enableVertexAttribArray(ze.a_radius),ke.vertexAttribPointer(ze.a_radius,1,ke.FLOAT,!1,16,8),ke.enableVertexAttribArray(ze.a_alpha),ke.vertexAttribPointer(ze.a_alpha,1,ke.FLOAT,!1,16,12),ke.bindVertexArray(null),xr.clear(),ir=Pe(ke,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_corner;in vec2 a_pos;in float a_size;in float a_angle;in float a_alpha;uniform mat4 u_proj;out vec2 v_uv;out float v_alpha;void main(){float c=cos(a_angle);float s=sin(a_angle);vec2 rotated=vec2(c*a_corner.x-s*a_corner.y,s*a_corner.x+c*a_corner.y);gl_Position=u_proj*vec4(a_pos+rotated*a_size,0.0,1.0);v_uv=a_corner*0.5+0.5;v_alpha=a_alpha;}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin vec2 v_uv;in float v_alpha;uniform sampler2D u_tex;uniform vec4 u_color;out vec4 outColor;void main(){float inkAlpha=texture(u_tex,v_uv).a;if(inkAlpha<0.01)discard;outColor=vec4(u_color.rgb,inkAlpha*v_alpha);}"),["a_corner","a_pos","a_size","a_angle","a_alpha"].forEach(t=>cr[t]=ke.getAttribLocation(ir,t)),["u_proj","u_color","u_tex"].forEach(t=>lr[t]=ke.getUniformLocation(ir,t)),ar=ke.createVertexArray(),ke.bindVertexArray(ar),or=ke.createBuffer(),ke.bindBuffer(ke.ARRAY_BUFFER,or),ke.bufferData(ke.ARRAY_BUFFER,gr,ke.STATIC_DRAW),ke.enableVertexAttribArray(cr.a_corner),ke.vertexAttribPointer(cr.a_corner,2,ke.FLOAT,!1,0,0),sr=ke.createBuffer(),ke.bindBuffer(ke.ARRAY_BUFFER,sr),ke.bufferData(ke.ARRAY_BUFFER,hr.byteLength,ke.DYNAMIC_DRAW),ur=hr.byteLength,ke.enableVertexAttribArray(cr.a_pos),ke.vertexAttribPointer(cr.a_pos,2,ke.FLOAT,!1,20,0),ke.vertexAttribDivisor(cr.a_pos,1),ke.enableVertexAttribArray(cr.a_size),ke.vertexAttribPointer(cr.a_size,1,ke.FLOAT,!1,20,8),ke.vertexAttribDivisor(cr.a_size,1),ke.enableVertexAttribArray(cr.a_angle),ke.vertexAttribPointer(cr.a_angle,1,ke.FLOAT,!1,20,12),ke.vertexAttribDivisor(cr.a_angle,1),ke.enableVertexAttribArray(cr.a_alpha),ke.vertexAttribPointer(cr.a_alpha,1,ke.FLOAT,!1,20,16),ke.vertexAttribDivisor(cr.a_alpha,1),ke.bindVertexArray(null),Be=!0)}();const a=!0!==P.isBrush;P.isBrush=!0,a&&(P.justChanged=!0),P.blend(T.stroke.color),Xr.alpha=["default","spray"].includes(Xr.p.type)?Xr.p.opacity:Xr.p.opacity/Math.min(T.stroke.weight,1.3),Kr()}();const a=function(){const{param:t}=wr.get(T.stroke.type)??{};return t?t.spacing:1}(),o=Math.round(Or*(i?t:1)/a);Xr.pressureCount=10,Xr.cachedPressure=void 0,Xr.lineNoiseCount=5,Xr.cachedLineNoise=void 0;for(let e=0;e<o;e++)Zr.length<2*o&&Zr.push(Q()),$r(),i?Ur.plotTo(Yr,a,a,t,e<10):Ur._moveToDegrees(t,a,a);!function(){Kr(),function(){if(0===tr)return;P.glMask.isDrawn=!0;const t=yr(),e=T.stroke.color._array;ke.useProgram(Ne),ke.enable(ke.BLEND),ke.blendFunc(ke.ONE_MINUS_DST_ALPHA,ke.ONE),ke.bindVertexArray(Le),ke.bindBuffer(ke.ARRAY_BUFFER,De);const r=16*tr,i=Qe.subarray(0,4*tr);r>rr?(ke.bufferData(ke.ARRAY_BUFFER,Qe,ke.DYNAMIC_DRAW),rr=Qe.byteLength):ke.bufferSubData(ke.ARRAY_BUFFER,0,i),ke.uniform4f(Xe.u_color,...e),ke.uniformMatrix4fv(Xe.u_matrix,!1,pr()),ke.drawArrays(ke.POINTS,0,tr),ke.flush(),ke.bindVertexArray(null),_r(t),nr&&(P.markDirtyRect(P.glMask,nr),nr=null),tr=0,Fe(n,ke)}();const t=Xr.p?.type;"image"===t?Rr(rn.tips.get(Xr.p.image.src),Xr.p.image.src):"custom"===t&&Rr(rn.tips.get(Xr.p.tipKey),Xr.p.tipKey)}()}function $r(){const t=Hr(),e=((Xr.lineNoiseCount>=10||void 0===Xr.cachedLineNoise)&&(Xr.cachedLineNoise=et(V(Xr.seed+.01*Ur.plotted,0),-1,1,1-Xr.noiseoffset,1+Xr.noiseoffset),Xr.lineNoiseCount=0),Xr.lineNoiseCount++,Xr.cachedLineNoise);if(!(e>W(1,1.02)&&W(0,1)<.7))switch(Xr.p.type){case"spray":!function(t){const e=T.stroke.weight*Xr.p.scatter*t+T.stroke.weight*j(Zr)*Xr.p.scatter/3,r=Xr.p.weight*W(.9,1.1),n=Math.ceil(Xr.p.grain/t);for(let t=0;t<n;t++){const t=W(.9,1.1),n=t*e*W(-1,1),i=W(-1,1),a=Math.sqrt((t*e)**2-n**2);vr(Ur.x+n,Ur.y+i*a,r,Xr.alpha)}}(t*e);break;case"marker":qr(t*e);break;case"custom":case"image":jr(t*e);break;default:!function(t,e=1){const r=(e=et(e,0,1,.9,1.05))*T.stroke.weight*Xr.p.scatter*(Xr.p.sharpness+(1-Xr.p.sharpness)*j(Zr)/t);if(W(0,Xr.p.grain*t)>.4){let e,n;if(Yr){const t=Yr.angle(Ur.plotted),i=ct(t),a=lt(t),o=r*W(-1,1),s=.3*r*W(-1,1);e=o*a+s*i,n=o*i-s*a}else{const t=r*W(-1,1),i=.3*r*W(-1,1);e=t*Xr.sin+i*Xr.cos,n=t*Xr.cos-i*Xr.sin}const i=t*t*Xr.p.weight*W(.85,1.15)*T.stroke.weight,a=Math.max(.9,t)*Xr.alpha*W(.75,1.1);vr(Ur.x+e,Ur.y+n,i,a)}}(t*e)}}function Hr(){return(Xr.pressureCount>=10||void 0===Xr.cachedPressure)&&(Xr.cachedPressure=Yr?Wr()*Yr.pressure(Ur.plotted):Wr(),Xr.pressureCount=0),Xr.pressureCount++,Xr.cachedPressure}function Wr(){return"custom"===Xr.p.pressure.type?et(Xr.p.pressure.curve(Math.max(0,Math.min(1,.5+(Ur.plotted/Or-.5+Xr.ct)*Xr.cs)))+Xr.cp+Xr.ck*(Ur.plotted/Or-.5),0,1,Xr.min,Xr.max,!0):function(t=.5+Xr.p.pressure.curve[0]*Xr.a,e=1-Xr.p.pressure.curve[1]*Xr.b,r=Xr.cp,n=Xr.min,i=Xr.max){const a=t*Or,o=(Ur.plotted<a?1.2*e:.8*e)*(Or/2);return et(1/(1+Math.pow(Math.abs((Ur.plotted-a)/o),2*r)),0,1,n,i)}()}function qr(t,e=!0,r=Xr.alpha){const n=e?T.stroke.weight*Xr.p.scatter:0,i=e?n*W(-1,1):0,a=e?n*W(-1,1):0;vr(Ur.x+i,Ur.y+a,T.stroke.weight*Xr.p.weight*t,r*Math.max(.8,t)*W(.9,1.1))}function jr(t,e=Xr.alpha){const r=T.stroke.weight*Xr.p.scatter,n=r*W(-1,1),i=r*W(-1,1),a=Xr.p.weight*T.stroke.weight*t,o=function(){const t=Math.max(1,Xr.max??1),e=T.stroke.weight*Xr.p.scatter,r=T.stroke.weight*Xr.p.weight*t;return Math.max(8,1.5*e+.75*r)}();let s=0;"random"===Xr.p.rotate?s=K(0,360)*(Math.PI/180):"natural"===Xr.p.rotate&&(s=((Yr?-Yr.angle(Ur.plotted):-zr)+Ur.angle())*(Math.PI/180)),function(t,e,r,n,i,a=0){if(fr>=mr){mr*=2;const t=new Float32Array(5*mr);t.set(hr),hr=t}const o=t-qe,s=e-je,c=Ge*o+Ve*s+He+qe,l=Ze*o+$e*s+We+je,u=Je*r*Ke/2,h=Je*a*Ke,f=5*fr;hr[f]=c,hr[f+1]=l,hr[f+2]=u,hr[f+3]=n,hr[f+4]=i/255;const m=c*Je,d=l*Je,x=1.42*u+h;dr=br(dr,m-x-1,d-x-1,m+x+1,d+x+1),fr++}(Ur.x+n,Ur.y+i,a,s,e*Math.max(.8,t)*W(.9,1.1),o)}function Kr(){if(!1===Xr.p.markerTip)return;let t=Hr(),e=Xr.alpha;if("marker"===Xr.p.type)for(let r=1;r<10;r++)qr(t*r/10,!0,8*e);else if("custom"===Xr.p.type||"image"===Xr.p.type)for(let r=1;r<5;r++)jr(t*r/10,2*e)}function Jr(t,e,r,n){if(!T.stroke.isActive||!T.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");pt();let i=mt(t,e,r,n);0!=i&&(Gr(t,e,i),Vr(dt(t,e,r,n),!1))}function Qr(t,e,r,n){if(!T.stroke.isActive||!T.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");pt(),Gr(t,e,r),Vr(ut(n),!1)}G(()=>{Zr.length=0});const tn=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate","markerTip","noise"],en=[["pen",[.3,.15,.9,2,150,.1,{curve:[.15,.2],min_max:[1.2,1]}]],["rotring",[.15,.05,.7,15,210,.1,{curve:[.35,.2],min_max:[1.3,1]}]],["2B",[.3,.75,.45,15,180,.1,{curve:[.1,.3],min_max:[1.1,.9]}]],["HB",[.3,.6,.3,10,170,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["2H",[.2,.6,.3,4,120,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["cpencil",[.3,.55,.8,7,75,.1,{curve:[.15,.2],min_max:[.95,1.2]}]],["pastel",[2.05/3,13.4/3,.91,28,35,.085/3,{mode:"gaussian",curve:[.4,.05],min_max:[1.09,.93]},"default",void 0,"natural",!0,1]],["crayon",[.3,5.45/3,.75,250,159,.23/3,[1.1,.9],"default",void 0,"natural",!0,1]],["charcoal",[.35,1.5,.68,500,120,.03,{curve:[.15,.4],min_max:[1.1,.95]}]],["spray",[.2,6,15,40,90,.5,{curve:[.2,.35],min_max:[.7,1]},"spray"]],["marker",[2,.2,null,null,1,.03,{curve:[.35,.25],min_max:[1.2,.85]},"marker"]]];for(let t of en){let e={};for(let r=0;r<t[1].length;r++)e[tn[r]]=t[1][r];Tr(t[0],e)}fe.prototype.draw=function(t=!1,e,r){let n=Ar();if(t&&Lr(t,e,r),n.isActive)for(let t of this.sides)Jr(t[0].x,t[0].y,t[1].x,t[1].y);Mr(n)},me.prototype.draw=function(t,e,r){Ar().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,n){pt(),Gr(e,r,t.length,t),Vr(n,!0)}(this,t,e,r))};const rn={tips:new Map,add(t){this.tips.has(t)||this.tips.set(t,!1)},imageToWhite(t){t.loadPixels();for(let e=0;e<4*t.width*t.height;e+=4){let r=(t.pixels[e]+t.pixels[e+1]+t.pixels[e+2])/3;t.pixels[e]=t.pixels[e+1]=t.pixels[e+2]=255,t.pixels[e+3]=255-r}t.updatePixels()},async load(){const t=[...this.tips.keys()].filter(t=>!this.tips.get(t));await Promise.all(t.map(t=>((t,e)=>Te.loadImageTip(t,e))(t,rn.imageToWhite).then(e=>{this.tips.set(t,e)})))}};function nn(){return{...T.hatch}}function an(t){T.hatch={...t}}function on(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let n=T.hatch;n.isActive=!0,n.dist=t,n.angle=ht(e),n.options=r}function sn(t,e="black",r=1){T.hatch.hBrush={brush:t,color:e,weight:r}}function cn(){T.hatch.isActive=!1,T.hatch.hBrush=!1}function ln(t,e,r,n){const i=e*Math.PI/180,a=Math.cos(i),o=Math.sin(i),s=Math.cos(-i),c=Math.sin(-i),l=t.a,u=l.length,h=new Array(u);let f=Infinity,m=-Infinity;for(let t=0;t<u;t++){const e=l[t][0],r=l[t][1],n=[e*a-r*o,e*o+r*a];h[t]=n,n[1]<f&&(f=n[1]),n[1]>m&&(m=n[1])}const d=[];for(let t=0;t<u;t++){const e=h[t],r=h[(t+1)%u];e[1]!==r[1]&&d.push(e,r)}const x=d.length,g=[],p=[];let y=f+.5*r,_=r;for(;y<m;){p.length=0;for(let t=0;t<x;t+=2){const e=d[t][1],r=d[t+1][1];(e<=y&&y<r||r<=y&&y<e)&&p.push(d[t][0]+(y-e)/(r-e)*(d[t+1][0]-d[t][0]))}p.sort((t,e)=>t-e);for(let t=0;t<p.length-1;t+=2)g.push({scanY:y,x1:p[t]*s-y*c,y1:p[t]*c+y*s,x2:p[t+1]*s-y*c,y2:p[t+1]*c+y*s});y+=_,_*=n}return g}function un(t){const{dist:e,options:r,segs:n}=function(t){const e=T.hatch.dist,r=(T.hatch.angle%180+180)%180,n=T.hatch.options,i=function(t,e,r,n){Array.isArray(t)||(t=[t]);const i=[];for(const a of t)for(const t of ln(a,r,e,n))i.push(t);return i.sort((t,e)=>t.scanY===e.scanY?t.x1-e.x1:t.scanY-e.scanY),i}(t,e,r,n.gradient?et(n.gradient,0,1,1,1.1,!0):1);return{dist:e,options:n,segs:i}}(t),i=r.rand||0,a=[];for(let t=0;t<n.length;t++){const o=n[t];let s=o.x1,c=o.y1,l=o.x2,u=o.y2;i&&(s+=2*i*e*W(-1,1),c+=2*i*e*W(-1,1),l+=2*i*e*W(-1,1),u+=2*i*e*W(-1,1));const h=r.continuous&&t%2==1?{x1:l,y1:u,x2:s,y2:c,scanY:o.scanY,isConnector:!1}:{x1:s,y1:c,x2:l,y2:u,scanY:o.scanY,isConnector:!1};if(a.push(h),t>0&&r.continuous){const t=a[a.length-2];a.push({x1:t.x2,y1:t.y2,x2:h.x1,y2:h.y1,scanY:o.scanY,isConnector:!0})}}return a}function hn(t){!function(t,e){const r=un(t);!function(){const t=Ar();T.hatch.hBrush&&Lr(...Object.values(T.hatch.hBrush)),(()=>{for(let t=0;t<r.length;t++){const n=r[t];e(n.x1,n.y1,n.x2,n.y2,t,r)}})(),Mr(t)}()}(t,(t,e,r,n)=>{Jr(t,e,r,n)})}function fn(t,e,r={}){T.mass.brush=t,T.mass.color=e,T.mass.options=r,T.mass.isActive=!0}function mn(){T.mass.isActive=!1,T.mass.brush=null,T.mass.color=null,T.mass.options={}}function dn(t,e,r){return new fe(t.vertices.map(t=>[t.x+e,t.y+r]))}function xn(t,e,r,n,i){const a=(e+n)/2,o=(r+i)/2,s=n-e,c=i-r,l=Math.hypot(s,c);if(!l)return null;const u=-c/l,h=s/l,f=(t.x-a)*u+(t.y-o)*h;return{x:a+u*f,y:o+h*f}}function gn(t,e,r,n,i,a,o){let s=dt(t,e,r,n),c=dt(t,e,i,a);return((c-s)%360+360)%360>180&&([s,c]=[c,s]),[o(s),o(c)]}function pn(t){const e=q(.35,.65),r=t.x1+(t.x2-t.x1)*e,n=t.y1+(t.y2-t.y1)*e,i=t.x2-t.x1,a=t.y2-t.y1,o=Math.hypot(i,a)||1,s=q(.04,.1)*o,c=i/o*s*.5,l=a/o*s*.5;return[{x1:t.x1,y1:t.y1,x2:r-c,y2:n-l},{x1:r+c,y1:n+l,x2:t.x2,y2:t.y2}]}function yn(t,e,r){const n=function(t,e){const r=function(t){const e=t?.a??[];let r=Infinity,n=Infinity,i=-Infinity,a=-Infinity;for(const[t,o]of e)t<r&&(r=t),o<n&&(n=o),t>i&&(i=t),o>a&&(a=o);return{minX:r,minY:n,maxX:i,maxY:a,cx:(r+i)/2,cy:(n+a)/2,size:Math.hypot(i-r,a-n)}}(t),n=r.size*q(.6,1.4),[i,a]=e;return{x:r.cx+i*n,y:r.cy+a*n}}(t,e);for(const e of un(t)){const t=!e.isConnector&&q()<.35?pn(e):[e];for(const e of t){const t=xn(n,e.x1,e.y1,e.x2,e.y2);if(!t)continue;const i=mt(t.x,t.y,e.x1,e.y1);if(!i)continue;const[a,o]=gn(t.x,t.y,e.x1,e.y1,e.x2,e.y2,r);pe(t.x,t.y,i,a,o)}}}function _n(t,e,r,n,i,a){on(e,r,n),yn(t,i,a)}function bn(t,e,r,n){const i=function(t,e,r,n){const i=!1===e,a=Pr(T.mass.brush)?.scatter??0,o=i?t:t.genPol(e,r,n,.15),s=Math.min(2*a,5),c=[[q(-s,s),q(-s,s)],[q(-s,s),q(-s,s)]];return[o,dn(o,c[0][0],c[0][1]),dn(o,c[1][0],c[1][1])]}(t,e,r,n),s=nn(),c=Ar(),l={...T.field},u=T.mass.options?.precision??.5,h=T.mass.options?.strength??1,f=T.mass.options?.gradient??.1,m=T.mass.options?.outline??!1,d=Pr(T.mass.brush)?.scatter??0,x=1.6*q(.65*d,.85*d)-.4*f,g=q(-90,90),p=((g+90)%180+180)%180-90>=0?q()<.5?[1,1]:[-1,-1]:q()<.5?[-1,1]:[1,-1],y=a()?t=>t*Math.PI/180:t=>t;Lr(T.mass.brush,T.mass.color,1),It(2-u),m&&i[0].draw(),_n(i[0],.9*x,o(g),{gradient:f,rand:2-2*u,continuous:!0},p,y),h>.33&&_n(i[1],x,o(g+20*q(-1,1)),{gradient:f,rand:.6-.6*u,continuous:!0},p,y),h>.66&&_n(i[2],.8*x,o(g+15*q(-1,1)),{gradient:f,rand:.6-.6*u,continuous:!0},p,y),Mr(c),an(s),T.field={...l}}function vn(t,e,r){const n=2*Math.PI,i=P.ctx,a=r/2;i.moveTo(t+a,e),i.arc(t,e,a,0,n)}T.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},fe.prototype.hatch=function(t=!1,e,r){let n=nn();t&&on(t,e,r),T.hatch.isActive&&hn(this),an(n)},me.prototype.hatch=function(t,e,r){nn().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,.3),this.pol.hatch())},T.mass={isActive:!1,brush:null,color:null,options:{}},fe.prototype.mass=function(){T.mass?.isActive&&bn(this,!1)},me.prototype.mass=function(t,e,r){T.mass?.isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),bn(this,t,e,r))};let Rn=null,wn=!1;wn||(b={ensureResources:function(t,e,r,n,i){const a=Math.max(1,Math.round(e*n)),o=Math.max(1,Math.round(r*n));return function(t,e,r){return!t.mask||t.mask.width!==e||t.mask.height!==r}(t,a,o)&&(t.mask=g(a,o)),function(t,e,r,n){return!t.fillMaskFramebuffer||t.fillMaskFramebuffer.width!==e||t.fillMaskFramebuffer.height!==r||"function"==typeof t.fillMaskFramebuffer.pixelDensity&&t.fillMaskFramebuffer.pixelDensity()!==n}(t,e,r,n)&&(t.fillMaskFramebuffer?.remove&&t.fillMaskFramebuffer.remove(),t.fillMaskFramebuffer=y(t,{width:e,height:r,density:n,antialias:!1,depth:!1,stencil:!1}),i(t.fillMaskFramebuffer)),t.mask.dirtyRect??=null,t.mask.isDrawn??=!1,t.mask.drawingContext.imageSmoothingEnabled=!1,{mask:t.mask,ctx:t.mask.drawingContext}},clearMask:function(t,e){t&&(e(t),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:function(t,e,r,n,i){return t?t.dirtyRect?i(n(t.dirtyRect,4)):r():null},getShaderMask:function(t,e,r,n,i,a){const o=t.fillMaskFramebuffer,s=t.drawingContext,c=n(r)??i(),l=c.maxX-c.minX,u=c.maxY-c.minY;Rn&&Rn.width===l&&Rn.height===u||(Rn=g(l,u));const h=Rn.drawingContext;return h.clearRect(0,0,l,u),h.drawImage(e,c.minX,c.minY,l,u,0,0,l,u),a(o),s.bindTexture(s.TEXTURE_2D,o.colorTexture),s.texSubImage2D(s.TEXTURE_2D,0,c.minX,c.minY,s.RGBA,s.UNSIGNED_BYTE,Rn),o}},wn=!0);let En,An=[],Mn=[],Tn=[],Sn=[];T.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const Pn=()=>({...T.fill});function Cn(t,e,r,n){T.fill.opacity=(arguments.length<4?e:n)||150,T.fill.color=arguments.length<3?s(t):s(t,e,r),T.fill.isActive=!0}function Fn(t,e="out"){T.fill.bleed_strength=rt(t,0,1),T.fill.direction=e}function kn(t=.4,e=.4){T.fill.texture_strength=rt(t,0,1),T.fill.border_strength=rt(e,0,1)}function In(){T.fill.isActive=!1}let Ln;const Dn=[[],[]];function Nn(){for(let t=0;t<512;t++)Dn[0][t]=Q(.5,.2),Dn[1][t]=Q(0,.02)}function Bn(t,e,r){return(e.x-t.x)*(r.y-t.y)-(e.y-t.y)*(r.x-t.x)>.01}G(Nn);class Un{constructor(t,e,r,n=[],i=!1,a,o){if(this.v=t,this.m=e,this.dir=n,this.midP=r,i){let e=0,n=0;const i=[];for(let a=0;a<t.length;a++){const o=Math.abs(r.x-t[a].x),s=Math.abs(r.y-t[a].y);e=Math.max(e,o),n=Math.max(n,s);const c=t[a],l=t[(a+1)%t.length],u={x:l.x-c.x,y:l.y-c.y},h=ft(0,0,u.x,u.y,90),f={x:c.x+u.x/2,y:c.y+u.y/2};i.push({v1:c,v2:l,ray:{point1:f,point2:{x:f.x+h.x,y:f.y+h.y}}})}this.sizeX=e,this.sizeY=n,this.dir=Array(t.length),i.forEach((t,e)=>{let r=0;for(const e of Ln.intersect(t.ray))Bn(t.v1,t.v2,e)&&r++;this.dir[e]=r%2==0});const a=W(-.6,.6)*e,o=W(-.6,.6)*n;this.midP={x:r.x+a,y:r.y+o}}else this.sizeX=a,this.sizeY=o}trim(t=1){if(t>=1||t<0||this.v.length<=8)return{v:this.v,m:this.m,dir:this.dir};const e=~~((1-t)*this.v.length),r=~~(this.v.length/2-e/2),n=this.v.length-e,i=new Array(n),a=new Array(n),o=new Array(n);let s=0;for(let t=0;t<r;t++,s++)i[s]=this.v[t],a[s]=this.m[t],o[s]=this.dir[t];for(let t=r+e;t<this.v.length;t++,s++)i[s]=this.v[t],a[s]=this.m[t],o[s]=this.dir[t];const c=r,l=r+e,u=this.v[(c-1+this.v.length)%this.v.length],h=this.v[l%this.v.length],f=h.x-u.x,m=h.y-u.y;for(let t=0;t<2;t++){const e=W(.25,.75),n={x:u.x+f*e,y:u.y+m*e},s=r+t;i.splice(s,0,n),a.splice(s,0,W(.4,.7)),o.splice(s,0,this.dir[c%this.dir.length])}return{v:i,m:a,dir:o}}scatter(t=.3){const e=this.v.length,r=Math.max(3,~~(e*t)),n=[],i=e/r;for(let t=0;t<r;t++)n.push(~~(t*i+W(0,.8*i)));const a=[],o=[],s=[],c=this.midP,l=Ln.sides;for(const t of n){const r=t%e;let n=this.v[r],i=0;for(const[t,e]of l){const r=t.y,a=e.y;if(r>n.y==a>n.y)continue;const o=(n.y-r)/(a-r);n.x<t.x+o*(e.x-t.x)&&i++}i%2==0&&(n={x:c.x+(n.x-c.x)*W(.3,.6),y:c.y+(n.y-c.y)*W(.3,.6)}),a.push(n),o.push(this.m[r]),s.push(!this.dir[r])}return new Un(a,o,this.midP,s,!1,this.sizeX,this.sizeY)}flipDirs(){return new Un(this.v,this.m,this.midP,this.dir.map(t=>!t),!1,this.sizeX,this.sizeY)}grow(t=1){const{v:e,m:r,dir:n}=this.trim(t),i=e.length,a=2*i;An.length<i&&(An=new Array(i),Mn=new Array(i)),Tn.length<a&&(Tn=new Array(a),Sn=new Array(a));const o=An,s=Mn,c=Tn,l=Sn,u="out"===T.fill.direction?-90:90;0===Dn[0].length&&Nn();const h=Dn[0],f=h.length,m=Dn[1],d=m.length;let x,g,p,y=0,_=0,b=999===t?W(.6,.8):T.fill.bleed_strength;for(let a=0;a<i;a++){const x=e[a],g=e[a+1<i?a+1:0],p=r[a],v=n[a];if(t<997&&(b=p),b<.05){c[y]=p,l[y]=v,y++,o[_]=(x.x+g.x)/2,s[_]=(x.y+g.y)/2,c[y]=p,l[y]=v,y++,_++;continue}const R=(v?u:-u)+5*W(-1,1),w=ct(R),E=lt(R),A=g.x-x.x,M=g.y-x.y,T=w*A+E*M,S=w*M-E*A,P=h[~~(W(0,1)*f)]*W(.65,1.35)*b,C=p+m[~~(W(0,1)*d)];c[y]=p,l[y]=v,y++,o[_]=x.x+.5*A+T*P,s[_]=x.y+.5*M+S*P,c[y]=C,l[y]=v,y++,_++}if(En&&y>En){const t=Math.ceil(y/En),r=Math.ceil(y/t);x=new Array(r),g=new Array(r),p=new Array(r);let n=0;for(let r=0;r<y;r+=t,n++)x[n]=r%2==0?e[r>>1]:{x:o[r>>1],y:s[r>>1]},g[n]=c[r],p[n]=l[r]}else{x=new Array(y);for(let t=0;t<y;t++)x[t]=t%2==0?e[t>>1]:{x:o[t>>1],y:s[t>>1]};g=c.slice(0,y),p=l.slice(0,y)}return new Un(x,g,this.midP,p,!1,this.sizeX,this.sizeY)}fill(t,n,a){const o=3*a,s=2*n*(1+a/2),l=!1!==P.isBrush;P.isBrush=!1,l&&(P.justChanged=!0),P.blend(t);const u=c();P.ctx.save(),P.ctx.setTransform(i*u.a,i*u.b,i*u.c,i*u.d,i*(u.x+e/2),i*(u.y+r/2)),P.ctx.strokeStyle=`rgb(${t._getRed()} ${t._getGreen()} ${t._getBlue()} / ${.005*T.fill.border_strength})`,P.ctx.lineCap="round",En=2024*Math.max(.1,2*T.fill.bleed_strength);const h=Math.max(this.sizeX,this.sizeY),f=W(.15,.7);let m=this.grow();const d=this.scatter(.1).grow().scatter(.75).flipDirs();let x;for(let e=0;e<20;e++){e%4==0&&(m=m.grow()),e%2==0&&(x=[m.grow(1-.0125*e),m.grow(.7-.0125*e),m.grow(.4-.0125*e)]);for(const r of x)r.grow(999).grow(997).layer(e,h,s,t);d.grow(999).flipDirs().grow(997).layer(e,h,s*o,t),e%2==0&&m.grow(f).grow(999).layer(e,h,2*s,t),e%8!=0&&19!==e||(0!==o&&m.erase(3*o,n),P.blend(t,!0))}P.ctx.restore()}layer(t,e,r,n){P.ctx.lineWidth=et(t,0,24,e/25,e/30,!0),P.ctx.fillStyle=`rgb(${n._getRed()} ${n._getGreen()} ${n._getBlue()} / ${r}%)`,function(t){const e=P.ctx,r=e.getTransform(),n=r.a,i=r.b,a=r.c,o=r.d,s=r.e,c=r.f;let l=Infinity,u=Infinity,h=-Infinity,f=-Infinity;e.beginPath();const m=t[0];let d=n*m.x+a*m.y+s,x=i*m.x+o*m.y+c;l=h=d,u=f=x,e.moveTo(m.x,m.y);for(let r=1;r<t.length;r++){const m=t[r];d=n*m.x+a*m.y+s,x=i*m.x+o*m.y+c,l=Math.min(l,d),u=Math.min(u,x),h=Math.max(h,d),f=Math.max(f,x),e.lineTo(m.x,m.y)}e.closePath();const g=function(t,e){const r=t.lineWidth||0;return r<=0?1:1+r*Math.max(Math.hypot(e.a,e.c),Math.hypot(e.b,e.d))/2}(e,r);P.markDirtyRect(P.mask,{minX:l-g,minY:u-g,maxX:h+g,maxY:f+g})}(this.v),P.ctx.fill(),P.ctx.stroke()}erase(t,e){P.ctx.save();const r=~~(W(80,110)*et(t,0,1,2,3.5)),n=this.sizeX/1.3,i=this.sizeY/1.3,a=1.3*Math.min(this.sizeX,this.sizeY),o=.03*a,s=.45*a,{x:c,y:l}=this.midP;P.ctx.globalCompositeOperation="destination-out";const u=(5-et(e,80,100,.3,.7,!0))*t/255;P.ctx.fillStyle=`rgb(255 0 0 / ${u})`,P.ctx.lineWidth=0;for(let t=0;t<r;t++){const e=c+Q(0,n),r=l+Q(0,i),a=W(o,s);P.ctx.beginPath(),vn(e,r,a),t%5!=0&&P.ctx.fill()}P.ctx.globalCompositeOperation="source-over",P.ctx.restore()}}function On(t,e){if(!t)return t;e||(e=t);let r,n=t;do{if(r=!1,n.steiner||!qn(n,n.next)&&0!==Wn(n.prev,n,n.next))n=n.next;else{if(ri(n),n=e=n.prev,n===n.next)break;r=!0}}while(r||n!==e);return e}function Yn(t,e,r,n,i,a,o){if(!t)return;!o&&a&&function(t,e,r,n){let i=t;do{0===i.z&&(i.z=Vn(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){let e,r=1;do{let n,i=t;t=null;let a=null;for(e=0;i;){e++;let o=i,s=0;for(let t=0;t<r&&(s++,o=o.nextZ,o);t++);let c=r;for(;s>0||c>0&&o;)0!==s&&(0===c||!o||i.z<=o.z)?(n=i,i=i.nextZ,s--):(n=o,o=o.nextZ,c--),a?a.nextZ=n:t=n,n.prevZ=a,a=n;i=o}a.nextZ=null,r*=2}while(e>1)}(i)}(t,n,i,a);let s=t;for(;t.prev!==t.next;){const c=t.prev,l=t.next;if(a?Xn(t,n,i,a):zn(t))e.push(c.i,t.i,l.i),ri(t),t=l.next,s=l.next;else if((t=l)===s){o?1===o?Yn(t=Gn(On(t),e),e,r,n,i,a,2):2===o&&Zn(t,e,r,n,i,a):Yn(On(t),e,r,n,i,a,1);break}}}function zn(t){const e=t.prev,r=t,n=t.next;if(Wn(e,r,n)>=0)return!1;const i=e.x,a=r.x,o=n.x,s=e.y,c=r.y,l=n.y,u=Math.min(i,a,o),h=Math.min(s,c,l),f=Math.max(i,a,o),m=Math.max(s,c,l);let d=n.next;for(;d!==e;){if(d.x>=u&&d.x<=f&&d.y>=h&&d.y<=m&&$n(i,s,a,c,o,l,d.x,d.y)&&Wn(d.prev,d,d.next)>=0)return!1;d=d.next}return!0}function Xn(t,e,r,n){const i=t.prev,a=t,o=t.next;if(Wn(i,a,o)>=0)return!1;const s=i.x,c=a.x,l=o.x,u=i.y,h=a.y,f=o.y,m=Math.min(s,c,l),d=Math.min(u,h,f),x=Math.max(s,c,l),g=Math.max(u,h,f),p=Vn(m,d,e,r,n),y=Vn(x,g,e,r,n);let _=t.prevZ,b=t.nextZ;for(;_&&_.z>=p&&b&&b.z<=y;){if(_.x>=m&&_.x<=x&&_.y>=d&&_.y<=g&&_!==i&&_!==o&&$n(s,u,c,h,l,f,_.x,_.y)&&Wn(_.prev,_,_.next)>=0)return!1;if(_=_.prevZ,b.x>=m&&b.x<=x&&b.y>=d&&b.y<=g&&b!==i&&b!==o&&$n(s,u,c,h,l,f,b.x,b.y)&&Wn(b.prev,b,b.next)>=0)return!1;b=b.nextZ}for(;_&&_.z>=p;){if(_.x>=m&&_.x<=x&&_.y>=d&&_.y<=g&&_!==i&&_!==o&&$n(s,u,c,h,l,f,_.x,_.y)&&Wn(_.prev,_,_.next)>=0)return!1;_=_.prevZ}for(;b&&b.z<=y;){if(b.x>=m&&b.x<=x&&b.y>=d&&b.y<=g&&b!==i&&b!==o&&$n(s,u,c,h,l,f,b.x,b.y)&&Wn(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function Gn(t,e){let r=t;do{const n=r.prev,i=r.next.next;!qn(n,i)&&jn(n,r,r.next,i)&&Qn(n,i)&&Qn(i,n)&&(e.push(n.i,r.i,i.i),ri(r),ri(r.next),r=t=i),r=r.next}while(r!==t);return On(r)}function Zn(t,e,r,n,i,a){let o=t;do{let t=o.next.next;for(;t!==o.prev;){if(o.i!==t.i&&Hn(o,t)){let s=ti(o,t);return o=On(o,o.next),s=On(s,s.next),Yn(o,e,r,n,i,a,0),void Yn(s,e,r,n,i,a,0)}t=t.next}o=o.next}while(o!==t)}function Vn(t,e,r,n,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function $n(t,e,r,n,i,a,o,s){return!(t===o&&e===s)&&function(t,e,r,n,i,a,o,s){return(i-o)*(e-s)>=(t-o)*(a-s)&&(t-o)*(n-s)>=(r-o)*(e-s)&&(r-o)*(a-s)>=(i-o)*(n-s)}(t,e,r,n,i,a,o,s)}function Hn(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&jn(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}(t,e)&&(Qn(t,e)&&Qn(e,t)&&function(t,e){let r=t,n=!1;const i=(t.x+e.x)/2,a=(t.y+e.y)/2;do{r.y>a!=r.next.y>a&&r.next.y!==r.y&&i<(r.next.x-r.x)*(a-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}(t,e)&&(Wn(t.prev,t,e.prev)||Wn(t,e.prev,e))||qn(t,e)&&Wn(t.prev,t,t.next)>0&&Wn(e.prev,e,e.next)>0)}function Wn(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function qn(t,e){return t.x===e.x&&t.y===e.y}function jn(t,e,r,n){const i=Jn(Wn(t,e,r)),a=Jn(Wn(t,e,n)),o=Jn(Wn(r,n,t)),s=Jn(Wn(r,n,e));return i!==a&&o!==s||!(0!==i||!Kn(t,r,e))||!(0!==a||!Kn(t,n,e))||!(0!==o||!Kn(r,t,n))||!(0!==s||!Kn(r,e,n))}function Kn(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function Jn(t){return t>0?1:t<0?-1:0}function Qn(t,e){return Wn(t.prev,t,t.next)<0?Wn(t,e,t.next)>=0&&Wn(t,t.prev,e)>=0:Wn(t,e,t.prev)<0||Wn(t,t.next,e)<0}function ti(t,e){const r=ni(t.i,t.x,t.y),n=ni(e.i,e.x,e.y),i=t.next,a=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,a.next=n,n.prev=a,n}function ei(t,e,r,n){const i=ni(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function ri(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function ni(t,e,r){return{i:t,x:e,y:r,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}fe.prototype.fill=function(t=!1,e,r,n,i,a){let o=Pn();t&&(Cn(t,e),Fn(r,a),kn(n,i)),o.isActive&&(pt(),function(t){if(!T.fill.isActive||!T.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");Ln=t;const e=[...t.vertices],r=~~(.25*e.length*tt({1:5,2:10,3:60})),n=T.fill.bleed_strength,i=e.map((t,e)=>(e>r?1:.3)*W(.85,1.4)*n),a=K(0,e.length),o=[...e.slice(a),...e.slice(0,a)],s=function(t){if(0===t.length)return{x:0,y:0};if(t.length<8){const e=t.reduce((t,e)=>({x:t.x+e.x,y:t.y+e.y}),{x:0,y:0});return{x:e.x/t.length,y:e.y/t.length}}const e=[...t];e[0].x===e[e.length-1].x&&e[0].y===e[e.length-1].y||e.push(e[0]);let r=0,n=0,i=0;for(let t=0;t<e.length-1;t++){const a=e[t].x*e[t+1].y-e[t+1].x*e[t].y;r+=a,n+=(e[t].x+e[t+1].x)*a,i+=(e[t].y+e[t+1].y)*a}return r*=.5,r?{x:n/(6*r),y:i/(6*r)}:{x:e[0].x,y:e[0].y}}(o);new Un(o,i,s,[],!0).fill(T.fill.color,et(T.fill.opacity,0,255,0,1,!0),T.fill.texture_strength)}(this)),(t=>{T.fill={...t}})(o)},me.prototype.fill=function(t,e,r){Pn().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,T.fill.bleed_strength<.06?0:et(T.fill.bleed_strength,0,.6,.2,.6,!0)),this.pol.fill())};let ii=null,ai=null,oi=null,si=null,ci=null,li=0,ui=0,hi=0;const fi={},mi={};function di(t,e,r,n){h(),T.wash.opacity=(arguments.length<4?e:n)??150,T.wash.color=arguments.length<3?s(t):s(t,e,r),T.wash.isActive=!0}function xi(){T.wash.isActive=!1}function gi(t,e){const r=c();return[r.a*t+r.c*e+r.x+li/2,r.b*t+r.d*e+r.y+ui/2]}function pi(t,e,r){const n=e.isEnabled(e.DEPTH_TEST);return n&&e.disable(e.DEPTH_TEST),e.bindFramebuffer(e.FRAMEBUFFER,r.framebuffer),e.viewport(0,0,r.width*r.density,r.height*r.density),{hadDepthTest:n}}function yi(t,n,a){a?.hadDepthTest&&n.enable(n.DEPTH_TEST),n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,Math.max(1,Math.round(e*i)),Math.max(1,Math.round(r*i)))}function _i(t,e){e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,null),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA)}function bi(t,e,r){if(!e)return;if(r(e)){const r=t.drawingContext,n=r.getParameter(r.FRAMEBUFFER_BINDING),i=r.getParameter(r.VIEWPORT);return r.bindFramebuffer(r.FRAMEBUFFER,e.framebuffer),r.viewport(0,0,e.width*e.density,e.height*e.density),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.bindFramebuffer(r.FRAMEBUFFER,n),void r.viewport(i[0],i[1],i[2],i[3])}const n=e.drawingContext;n.save(),n.setTransform(1,0,0,1,0,0),n.clearRect(0,0,e.width,e.height),n.restore()}function vi(t,e,r){return t.shaderProgram??=function(t,e,r){const n=Pe(t,e,r),i=new Map,a=t.createVertexArray(),o=t.getUniformLocation(n,"u_source"),s=t.getUniformLocation(n,"u_mask"),c=t.getUniformLocation(n,"u_color");return{program:n,quadVao:a,loc_source:o,loc_mask:s,loc_color:c,setUniform(e,r){const a=(e=>(i.has(e)||i.set(e,t.getUniformLocation(n,e)),i.get(e)))(e);a&&("boolean"!=typeof r?"number"!=typeof r?Array.isArray(r)&&(3===r.length?t.uniform3f(a,r[0],r[1],r[2]):4===r.length&&t.uniform4f(a,r[0],r[1],r[2],r[3])):t.uniform1f(a,r):t.uniform1i(a,r?1:0))}}}(t.drawingContext,e,r),t.shaderProgram}function Ri(t,e){const r=t.drawingContext,n=e.density??1,i=r.createFramebuffer(),a=Math.max(1,e.width),o=Math.max(1,e.height),s=Math.max(1,Math.round(a*n)),c=Math.max(1,Math.round(o*n)),l=function(t,e,r){const n=t.createTexture();return t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,r,0,t.RGBA,t.UNSIGNED_BYTE,null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.bindTexture(t.TEXTURE_2D,null),n}(r,s,c);return r.bindFramebuffer(r.FRAMEBUFFER,i),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,l,0),r.bindFramebuffer(r.FRAMEBUFFER,null),{__brushFramebuffer:!0,framebuffer:i,colorTexture:l,width:a,height:o,density:n,pixelDensity:()=>n,remove(){r.deleteFramebuffer(i),r.deleteTexture(l)}}}function wi(t,e,r,n,i){return e?.remove?.(),Ri(t,{width:r,height:n,density:i})}function Ei({renderer:t,shader:e,source:r,mask:n,color:i,isBrushMask:a,dirtyRect:o,targetIsFramebuffer:s,withScissor:c}){const l=t.drawingContext,u=l.isEnabled(l.DEPTH_TEST),h=l.getParameter(l.FRAMEBUFFER_BINDING),f=l.getParameter(l.CURRENT_PROGRAM),m=l.getParameter(l.VERTEX_ARRAY_BINDING);l.bindVertexArray(e.quadVao),l.useProgram(e.program),l.disable(l.DEPTH_TEST),l.enable(l.BLEND),l.blendEquation(l.FUNC_ADD),l.blendFunc(l.ONE,l.ONE_MINUS_SRC_ALPHA),l.activeTexture(l.TEXTURE0),l.bindTexture(l.TEXTURE_2D,r.colorTexture),l.uniform1i(e.loc_source,0),l.activeTexture(l.TEXTURE1),l.bindTexture(l.TEXTURE_2D,n.colorTexture),l.uniform1i(e.loc_mask,1),e.setUniform("u_targetIsFramebuffer",s),e.setUniform("u_isBrush",a),l.uniform3f(e.loc_color,i[0],i[1],i[2]),l.bindFramebuffer(l.FRAMEBUFFER,null),c(l,o,()=>{l.drawArrays(l.TRIANGLES,0,3)},!s),l.bindTexture(l.TEXTURE_2D,null),l.activeTexture(l.TEXTURE0),l.bindVertexArray(m),l.useProgram(f),l.bindFramebuffer(l.FRAMEBUFFER,h),u&&l.enable(l.DEPTH_TEST)}function Ai(t){return function({renderer:t,sourceFramebuffer:e,dirtyRect:r,getTargetPixelSize:n,toScissorBox:i}){const a=t.drawingContext,{width:o,height:s}=n(),c=r?i(r):null,l=a.getParameter(a.READ_FRAMEBUFFER_BINDING),u=a.getParameter(a.DRAW_FRAMEBUFFER_BINDING);return a.bindFramebuffer(a.READ_FRAMEBUFFER,null),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,e.framebuffer),a.clearColor(0,0,0,0),a.clear(a.COLOR_BUFFER_BIT),a.blitFramebuffer(c?.x??0,c?.y??0,c?c.x+c.width:o,c?c.y+c.height:s,c?.x??0,c?.y??0,c?c.x+c.width:o,c?c.y+c.height:s,a.COLOR_BUFFER_BIT,a.NEAREST),a.bindFramebuffer(a.READ_FRAMEBUFFER,l),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,u),e}(t)}function Mi(t){if("number"==typeof t){const e=Math.max(0,Math.min(255,t));return`rgb(${e} ${e} ${e})`}return t??"black"}function Ti(t){const e=((t,e=!1)=>(t.drawingContext??=t.getContext("2d",e?{willReadFrequently:!0}:void 0),t.drawingContext))(t,!0),r={canvas:t,drawingContext:e,width:t.width,height:t.height,pixels:null,_fillStyle:"#ffffff",_strokeStyle:"transparent",_lineWidth:1,pixelDensity:()=>1,background(r){e.save(),e.setTransform(1,0,0,1,0,0),e.fillStyle=Mi(r),e.fillRect(0,0,t.width,t.height),e.restore()},noSmooth(){e.imageSmoothingEnabled=!1},push(){e.save()},pop(){e.restore()},translate(t,r){e.translate(t,r)},scale(t,r=t){e.scale(t,r)},rotate(t){e.rotate(t)},noStroke(){r._strokeStyle="transparent"},stroke(t){r._strokeStyle=Mi(t)},noFill(){r._fillStyle="transparent"},fill(t){r._fillStyle=Mi(t)},strokeWeight(t){r._lineWidth=t},rect(t,n,i,a){e.beginPath(),e.rect(t,n,i,a),r._paint()},circle(t,n,i){e.beginPath(),e.arc(t,n,i/2,0,2*Math.PI),r._paint()},ellipse(t,n,i,a){e.beginPath(),e.ellipse(t,n,i/2,a/2,0,0,2*Math.PI),r._paint()},line(t,n,i,a){e.beginPath(),e.moveTo(t,n),e.lineTo(i,a),e.strokeStyle=r._strokeStyle,e.lineWidth=r._lineWidth,e.stroke()},beginShape(){e.beginPath(),r._shapeStarted=!1},vertex(t,n){r._shapeStarted?e.lineTo(t,n):(e.moveTo(t,n),r._shapeStarted=!0)},endShape(t=!1){t&&e.closePath(),r._paint()},loadPixels(){r.pixels=e.getImageData(0,0,t.width,t.height).data},updatePixels(){const n=e.getImageData(0,0,t.width,t.height);n.data.set(r.pixels),e.putImageData(n,0,0)},_paint(){"transparent"!==r._fillStyle&&(e.fillStyle=r._fillStyle,e.fill()),"transparent"!==r._strokeStyle&&(e.strokeStyle=r._strokeStyle,e.lineWidth=r._lineWidth,e.stroke())}};return r}function Si(t,e){return Ti(g(t,e,!0))}function Pi(t,e){return new Promise((r,n)=>{const i=globalThis.Image;if(!i)return void n(new Error("Standalone image brush loading requires Image support."));const a=new i;a.onload=()=>{const t=Ti(g(a.naturalWidth,a.naturalHeight,!0));t.drawingContext.drawImage(a,0,0),e(t),r(t)},a.onerror=()=>n(new Error(`Failed to load image tip: ${t}`)),a.crossOrigin="anonymous",a.src=t})}var Ci;T.wash={color:null,opacity:150,isActive:!1},fe.prototype.wash=function(t=!1,i){const a={...T.wash};!1!==t&&di(t,i),T.wash.isActive&&function(t){if(!T.wash?.isActive||!T.wash.color||t.vertices.length<3)return;C(),function(){const t=n.drawingContext;ci&&!(li!==e||ui!==r)||(li=e,ui=r,ci=new Float32Array([2/li,0,0,0,0,-2/ui,0,0,0,0,1,0,-1,1,0,1])),ii===t&&ai&&oi&&si||(ii=t,ai=Pe(ii,"#version 300 es\nin vec2 a_position;\nuniform mat4 u_matrix;\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n}","#version 300 es\nprecision highp float;\nuniform vec4 u_color;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(u_color.rgb * u_color.a, u_color.a);\n}"),fi.a_position=ii.getAttribLocation(ai,"a_position"),mi.u_matrix=ii.getUniformLocation(ai,"u_matrix"),mi.u_color=ii.getUniformLocation(ai,"u_color"),oi=ii.createVertexArray(),ii.bindVertexArray(oi),si=ii.createBuffer(),ii.bindBuffer(ii.ARRAY_BUFFER,si),ii.bufferData(ii.ARRAY_BUFFER,0,ii.DYNAMIC_DRAW),hi=0,ii.enableVertexAttribArray(fi.a_position),ii.vertexAttribPointer(fi.a_position,2,ii.FLOAT,!1,8,0),ii.bindVertexArray(null),ii.bindBuffer(ii.ARRAY_BUFFER,null))}();const{triangles:i,vertexCount:a}=function(t){const e=new Float32Array(2*t.vertices.length);for(let r=0;r<t.vertices.length;r++){const n=t.vertices[r];e[2*r]=n.x,e[2*r+1]=n.y}const r=function(t,e,r=2){const n=t.length;let i=function(t,e,r,n){let i;if(1==function(t,e,r,n){let i=0;for(let e=0,a=r-n;e<r;e+=n)i+=(t[a]-t[e])*(t[e+1]+t[a+1]),a=e;return i}(t,0,r,n)>0)for(let e=0;e<r;e+=n)i=ei(e/n|0,t[e],t[e+1],i);else for(let e=r-n;e>=0;e-=n)i=ei(e/n|0,t[e],t[e+1],i);return i&&qn(i,i.next)&&(ri(i),i=i.next),i}(t,0,n,r);const a=[];if(!i||i.next===i.prev)return a;let o,s,c;if(t.length>80*r){o=t[0],s=t[1];let e=o,i=s;for(let a=r;a<n;a+=r){const r=t[a],n=t[a+1];r<o&&(o=r),n<s&&(s=n),r>e&&(e=r),n>i&&(i=n)}c=Math.max(e-o,i-s),c=0!==c?32767/c:0}return Yn(i,a,r,o,s,c,0),a}(e),n=new Float32Array(2*r.length);for(let t=0;t<r.length;t++){const i=r[t],[a,o]=gi(e[2*i],e[2*i+1]);n[2*t]=a,n[2*t+1]=o}return{triangles:n,vertexCount:r.length}}(t),o=i.byteLength;ii.useProgram(ai),ii.enable(ii.BLEND),ii.blendEquation(ii.FUNC_ADD),ii.blendFunc(ii.ONE,ii.ONE_MINUS_SRC_ALPHA),ii.bindVertexArray(oi),ii.bindBuffer(ii.ARRAY_BUFFER,si),o>hi?(ii.bufferData(ii.ARRAY_BUFFER,i,ii.DYNAMIC_DRAW),hi=o):ii.bufferSubData(ii.ARRAY_BUFFER,0,i);const s=T.wash.color._array;ii.uniformMatrix4fv(mi.u_matrix,!1,ci),ii.uniform4f(mi.u_color,s[0],s[1],s[2],T.wash.opacity/255),ii.drawArrays(ii.TRIANGLES,0,a),ii.bindVertexArray(null),ii.bindBuffer(ii.ARRAY_BUFFER,null),Fe(n,ii)}(this),T.wash={...a}},me.prototype.wash=function(t,e,r){T.wash?.isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,0,-1),this.pol.wash())},Ci={load:function(t=ae){if(!function(t){return function(t){return"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement}(t)||function(t){return"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas}(t)}(t))throw new Error("Standalone brush.load(target) requires an HTMLCanvasElement or OffscreenCanvas.");ue(t,t.width,t.height,1)},syncDensity:function(){return u({Cwidth:ce,Cheight:le,Density:se}),se},isCanvasReady:function(){if(!oe)throw new Error("No standalone target loaded. Call brush.load(canvasOrOffscreenCanvas) first.")},instance:function(){},activateInstance:function(){},deactivateInstance:function(){},getActiveFramebuffer:function(){return null},isFramebufferTarget:function(){return!0===arguments[0]?.__brushFramebuffer}},l={...l,...Ci},Jt(),function(){var t;t={beginDirectMaskDraw:pi,endDirectMaskDraw:yi,resetDirectShaderTracking:_i},Ce={...Ce,...t}}(),function(){var t;t={clearTarget:bi,ensureBlendShaderProgram:vi,ensureBlendSourceFramebuffer:wi,createFramebuffer:Ri,runBlendShaderPass:Ei,blitSourceToFramebuffer:Ai},p={...p,...t}}(),function(){var t;t={createTipSurface:Si,loadImageTip:Pi},Te={...Te,...t}}();export{Zt as Color,Bt as DEGREES,me as Plot,fe as Polygon,yt as Position,Ut as RADIANS,Tr as add,Ft as addField,Vt as angleMode,pe as arc,_e as beginShape,Re as beginStroke,Sr as box,ge as circle,te as clear,Nr as clip,he as createCanvas,ve as endShape,Ee as endStroke,Pt as field,Cn as fill,Fn as fillBleed,kn as fillTexture,Qr as flowLine,$t as getAngleMode,on as hatch,hn as hatchArray,sn as hatchStyle,Jt as initStandaloneRuntime,f as instance,Jr as line,kt as listFields,F as load,fn as mass,we as move,Br as noClip,Ct as noField,In as noFill,cn as noHatch,mn as noMass,Dr as noStroke,xi as noWash,H as noiseSeed,Fr as pick,de as polygon,Wt as pop,Ht as push,xe as rect,St as refreshField,Qt as render,jt as rotate,Kt as scale,Cr as scaleBrushes,Z as seed,Lr as set,Ae as spline,kr as stroke,Ir as strokeWeight,qt as translate,be as vertex,tt as wRand,di as wash,It as wiggle};
+const t={a:1,b:0,c:0,d:1,x:0,y:0};let e,r,n,i,a=()=>!1,o=t=>t,s=()=>{throw new Error("No runtime color adapter registered.")},c=()=>t,l={load:()=>{throw new Error("No target runtime adapter registered.")},syncDensity:()=>i,isCanvasReady:()=>{throw new Error("No target runtime adapter registered.")},instance:t=>{},activateInstance:t=>{},deactivateInstance:()=>{},getActiveFramebuffer:()=>null,isFramebufferTarget:()=>!1};function u(t){"Cwidth"in t&&(e=t.Cwidth),"Cheight"in t&&(r=t.Cheight),"Instance"in t&&t.Instance,"Renderer"in t&&(n=t.Renderer),"Density"in t&&(i=t.Density)}const h=()=>l.isCanvasReady(),f=t=>l.instance(t),m=()=>l.getActiveFramebuffer(),d=t=>l.isFramebufferTarget(t),x=(t,e=0)=>t?{minX:t.minX-e,minY:t.minY-e,maxX:t.maxX+e,maxY:t.maxY+e}:null,g=(t,e,r=!1)=>{const n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(t,e):(()=>{const r=document.createElement("canvas");return r.width=t,r.height=e,r})();return n.drawingContext=n.getContext("2d",r?{willReadFrequently:!0}:void 0),n};let y={clearTarget:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendShaderProgram:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendSourceFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},createFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},runBlendShaderPass:()=>{throw new Error("No compositor runtime adapter registered.")},blitSourceToFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")}};const p=(...t)=>y.createFramebuffer(...t);let v=null,_=null;const b=t=>{((...t)=>{y.clearTarget(...t)})(n,t,d)},R=()=>({width:Math.max(1,Math.round(e*i)),height:Math.max(1,Math.round(r*i))}),w=t=>{if(!t)return null;const{width:e,height:r}=R();return((t,e,r)=>{if(!t)return null;const n=Math.max(0,Math.floor(Math.min(t.minX,t.maxX))),i=Math.max(0,Math.floor(Math.min(t.minY,t.maxY))),a=Math.min(e,Math.ceil(Math.max(t.minX,t.maxX))),o=Math.min(r,Math.ceil(Math.max(t.minY,t.maxY)));return a<=n||o<=i?null:{minX:n,minY:i,maxX:a,maxY:o}})(t,e,r)},E=()=>{const{width:t,height:e}=R();return((t,e)=>({minX:0,minY:0,maxX:t,maxY:e}))(t,e)},A=(t,e=!0)=>{const r=w(t);if(!r)return null;const{height:n}=R();return{x:r.minX,y:e?n-r.maxY:r.minY,width:r.maxX-r.minX,height:r.maxY-r.minY}},M=(t,e,r,n=!0)=>{const i=A(e,n);if(i){t.enable(t.SCISSOR_TEST),t.scissor(i.x,i.y,i.width,i.height);try{r()}finally{t.disable(t.SCISSOR_TEST)}}else r()},T={},S=()=>{n?.loaded||(h(),P.load())},P={isBlending:!1,cachedColor:null,markDirtyRect(t,e){const r=w(e);var n,i;t&&r&&(t.dirtyRect=(i=r,(n=t.dirtyRect)?i?{minX:Math.min(n.minX,i.minX),minY:Math.min(n.minY,i.minY),maxX:Math.max(n.maxX,i.maxX),maxY:Math.max(n.maxY,i.maxY)}:n:i),t.isDrawn=!0)},clearMask(t){if(!t)return;const e=t===this.glMask?v:_;e?.clearMask?.(t,b)},getCompositeRect(t,e){const r=e?v:_;return r?.getCompositeRect?.(t,m,E,x,w)},load(){l.syncDensity();const t=!n.blendSourceFramebuffer||n.blendSourceFramebuffer.width!==e||n.blendSourceFramebuffer.height!==r||"function"==typeof n.blendSourceFramebuffer.pixelDensity&&n.blendSourceFramebuffer.pixelDensity()!==i;((...t)=>{y.ensureBlendShaderProgram(...t)})(n,"#version 300 es\n#define GLSLIFY 1\nout vec2 p;void main(){vec3 v=vec3(-1);v[gl_VertexID]=3.;p=v.xy;gl_Position=vec4(v.x,-v.y,0,1);}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nuniform bool u_isBrush;uniform bool u_targetIsFramebuffer;uniform sampler2D u_source;uniform sampler2D u_mask;uniform vec3 u_color;in vec2 p;out vec4 outColor;const int SPECTRAL_SIZE=38;const float SPECTRAL_GAMMA=2.4;const float SPECTRAL_EPSILON=0.0000000000000001;float spectral_uncompand(float x){return(x<0.04045)? x/12.92 : pow((x+0.055)/1.055,SPECTRAL_GAMMA);}float spectral_compand(float x){return(x<0.0031308)? x*12.92 : 1.055*pow(x,1.0/SPECTRAL_GAMMA)-0.055;}vec3 spectral_srgb_to_linear(vec3 srgb){return vec3(spectral_uncompand(srgb[0]),spectral_uncompand(srgb[1]),spectral_uncompand(srgb[2]));}vec3 spectral_linear_to_srgb(vec3 lrgb){return clamp(vec3(spectral_compand(lrgb[0]),spectral_compand(lrgb[1]),spectral_compand(lrgb[2])),0.,1.);}void spectral_linear_to_reflectance(vec3 lrgb,inout float R[SPECTRAL_SIZE]){float w=min(lrgb.r,min(lrgb.g,lrgb.b));lrgb-=w;float c=min(lrgb.g,lrgb.b);float m=min(lrgb.r,lrgb.b);float y=min(lrgb.r,lrgb.g);float r=min(max(0.0,lrgb.r-lrgb.b),max(0.0,lrgb.r-lrgb.g));float g=min(max(0.0,lrgb.g-lrgb.b),max(0.0,lrgb.g-lrgb.r));float b=min(max(0.0,lrgb.b-lrgb.g),max(0.0,lrgb.b-lrgb.r));R[0]=max(SPECTRAL_EPSILON,w*1.0011607271876400+c*0.9705850013229620+m*0.9906735573199880+y*0.0210523371789306+r*0.0315605737777207+g*0.0095560747554212+b*0.9794047525020140);R[1]=max(SPECTRAL_EPSILON,w*1.0011606515972800+c*0.9705924981434250+m*0.9906715249619790+y*0.0210564627517414+r*0.0315520718330149+g*0.0095581580120851+b*0.9794007068431300);R[2]=max(SPECTRAL_EPSILON,w*1.0011603192274700+c*0.9706253487298910+m*0.9906625823534210+y*0.0210746178695038+r*0.0315148215513658+g*0.0095673245444588+b*0.9793829034702610);R[3]=max(SPECTRAL_EPSILON,w*1.0011586727078900+c*0.9707868061190170+m*0.9906181076447950+y*0.0211649058448753+r*0.0313318044982702+g*0.0096129126297349+b*0.9792943649455940);R[4]=max(SPECTRAL_EPSILON,w*1.0011525984455200+c*0.9713686732282480+m*0.9904514808787100+y*0.0215027957272504+r*0.0306729857725527+g*0.0097837090401843+b*0.9789630146085700);R[5]=max(SPECTRAL_EPSILON,w*1.0011325252899800+c*0.9731632306212520+m*0.9898710814002040+y*0.0226738799041561+r*0.0286480476989607+g*0.0103786227058710+b*0.9778144666940430);R[6]=max(SPECTRAL_EPSILON,w*1.0010850066332700+c*0.9767402231587650+m*0.9882866087596400+y*0.0258235649693629+r*0.0246450407045709+g*0.0120026452378567+b*0.9747243211338360);R[7]=max(SPECTRAL_EPSILON,w*1.0009968788945300+c*0.9815876054913770+m*0.9842906927975040+y*0.0334879385639851+r*0.0192960753663651+g*0.0160977721473922+b*0.9671984823439730);R[8]=max(SPECTRAL_EPSILON,w*1.0008652515227400+c*0.9862802656529490+m*0.9739349056253060+y*0.0519069663740307+r*0.0142066612220556+g*0.0267061902231680+b*0.9490796575305750);R[9]=max(SPECTRAL_EPSILON,w*1.0006962900094000+c*0.9899491476891340+m*0.9418178384601450+y*0.1007490148334730+r*0.0102942608878609+g*0.0595555440185881+b*0.9008501289409770);R[10]=max(SPECTRAL_EPSILON,w*1.0005049611488800+c*0.9924927015384200+m*0.8173903261951560+y*0.2391298997068470+r*0.0076191460521811+g*0.1860398265328260+b*0.7631504454622400);R[11]=max(SPECTRAL_EPSILON,w*1.0003080818799200+c*0.9941456804052560+m*0.4324728050657290+y*0.5348043122727480+r*0.0058980410835420+g*0.5705798201161590+b*0.4659221716493190);R[12]=max(SPECTRAL_EPSILON,w*1.0001196660201300+c*0.9951839750332120+m*0.1384539782588700+y*0.7978075786430300+r*0.0048233247781713+g*0.8614677684002920+b*0.2012632804510050);R[13]=max(SPECTRAL_EPSILON,w*0.9999527659684070+c*0.9957567501108180+m*0.0537347216940033+y*0.9114498940673840+r*0.0042298748350633+g*0.9458790897676580+b*0.0877524413419623);R[14]=max(SPECTRAL_EPSILON,w*0.9998218368992970+c*0.9959128182867100+m*0.0292174996673231+y*0.9537979630045070+r*0.0040599171299341+g*0.9704654864743050+b*0.0457176793291679);R[15]=max(SPECTRAL_EPSILON,w*0.9997386095575930+c*0.9956061578345280+m*0.0213136517508590+y*0.9712416154654290+r*0.0043533695594676+g*0.9784136302844500+b*0.0284706050521843);R[16]=max(SPECTRAL_EPSILON,w*0.9997095516396120+c*0.9945976009618540+m*0.0201349530181136+y*0.9793031238075880+r*0.0053434425970201+g*0.9795890314112240+b*0.0205271767569850);R[17]=max(SPECTRAL_EPSILON,w*0.9997319302106270+c*0.9922157154923700+m*0.0241323096280662+y*0.9833801195075750+r*0.0076917201010463+g*0.9755335369086320+b*0.0165302792310211);R[18]=max(SPECTRAL_EPSILON,w*0.9997994363461950+c*0.9862364527832490+m*0.0372236145223627+y*0.9854612465677550+r*0.0135969795736536+g*0.9622887553978130+b*0.0145135107212858);R[19]=max(SPECTRAL_EPSILON,w*0.9999003303166710+c*0.9679433372645410+m*0.0760506552706601+y*0.9864350469766050+r*0.0316975442661115+g*0.9231215745131200+b*0.0136003508637687);R[20]=max(SPECTRAL_EPSILON,w*1.0000204065261100+c*0.8912850042449430+m*0.2053754719423990+y*0.9867382506701410+r*0.1078611963552490+g*0.7934340189431110+b*0.0133604258769571);R[21]=max(SPECTRAL_EPSILON,w*1.0001447879365800+c*0.5362024778620530+m*0.5412689034604390+y*0.9866178824450320+r*0.4638126031687040+g*0.4592701359024290+b*0.0135488943145680);R[22]=max(SPECTRAL_EPSILON,w*1.0002599790341200+c*0.1541081190018780+m*0.8158416850864860+y*0.9862777767586430+r*0.8470554052720110+g*0.1855741036663030+b*0.0139594356366992);R[23]=max(SPECTRAL_EPSILON,w*1.0003557969708900+c*0.0574575093228929+m*0.9128177041239760+y*0.9858605924440560+r*0.9431854093939180+g*0.0881774959955372+b*0.0144434255753570);R[24]=max(SPECTRAL_EPSILON,w*1.0004275378026900+c*0.0315349873107007+m*0.9463398301669620+y*0.9854749276762100+r*0.9688621506965580+g*0.0543630228766700+b*0.0148854440621406);R[25]=max(SPECTRAL_EPSILON,w*1.0004762334488800+c*0.0222633920086335+m*0.9599276963319910+y*0.9851769347655580+r*0.9780306674736030+g*0.0406288447060719+b*0.0152254296999746);R[26]=max(SPECTRAL_EPSILON,w*1.0005072096750800+c*0.0182022841492439+m*0.9662605952303120+y*0.9849715740141810+r*0.9820436438543060+g*0.0342215204316970+b*0.0154592848180209);R[27]=max(SPECTRAL_EPSILON,w*1.0005251915637300+c*0.0162990559732640+m*0.9693259700584240+y*0.9848463034157120+r*0.9839236237187070+g*0.0311185790956966+b*0.0156018026485961);R[28]=max(SPECTRAL_EPSILON,w*1.0005350960689600+c*0.0153656239334613+m*0.9708545367213990+y*0.9847753518111990+r*0.9848454841543820+g*0.0295708898336134+b*0.0156824871281936);R[29]=max(SPECTRAL_EPSILON,w*1.0005402209748200+c*0.0149111568733976+m*0.9716050665281280+y*0.9847380666252650+r*0.9852942758145960+g*0.0288108739348928+b*0.0157248764360615);R[30]=max(SPECTRAL_EPSILON,w*1.0005427281678400+c*0.0146954339898235+m*0.9719627697573920+y*0.9847196483117650+r*0.9855072952198250+g*0.0284486271324597+b*0.0157458108784121);R[31]=max(SPECTRAL_EPSILON,w*1.0005438956908700+c*0.0145964146717719+m*0.9721272722745090+y*0.9847110233919390+r*0.9856050715398370+g*0.0282820301724731+b*0.0157556123350225);R[32]=max(SPECTRAL_EPSILON,w*1.0005444821215100+c*0.0145470156699655+m*0.9722094177458120+y*0.9847066833006760+r*0.9856538499335780+g*0.0281988376490237+b*0.0157605443964911);R[33]=max(SPECTRAL_EPSILON,w*1.0005447695999200+c*0.0145228771899495+m*0.9722495776784240+y*0.9847045543930910+r*0.9856776850338830+g*0.0281581655342037+b*0.0157629637515278);R[34]=max(SPECTRAL_EPSILON,w*1.0005448988776200+c*0.0145120341118965+m*0.9722676219987420+y*0.9847035963093700+r*0.9856883918061220+g*0.0281398910216386+b*0.0157640525629106);R[35]=max(SPECTRAL_EPSILON,w*1.0005449625468900+c*0.0145066940939832+m*0.9722765094621500+y*0.9847031240775520+r*0.9856936646900310+g*0.0281308901665811+b*0.0157645892329510);R[36]=max(SPECTRAL_EPSILON,w*1.0005449892705800+c*0.0145044507314479+m*0.9722802433068740+y*0.9847029256150900+r*0.9856958798482050+g*0.0281271086805816+b*0.0157648147772649);R[37]=max(SPECTRAL_EPSILON,w*1.0005449969930000+c*0.0145038009464639+m*0.9722813248265600+y*0.9847028681227950+r*0.9856965214637620+g*0.0281260133612096+b*0.0157648801149616);}vec3 spectral_xyz_to_srgb(vec3 xyz){mat3 XYZ_RGB;XYZ_RGB[0]=vec3(3.2409699419045200,-1.537383177570090,-0.4986107602930030);XYZ_RGB[1]=vec3(-0.9692436362808790,1.875967501507720,0.0415550574071756);XYZ_RGB[2]=vec3(0.0556300796969936,-0.203976958888976,1.0569715142428700);float r=dot(XYZ_RGB[0],xyz);float g=dot(XYZ_RGB[1],xyz);float b=dot(XYZ_RGB[2],xyz);return spectral_linear_to_srgb(vec3(r,g,b));}vec3 spectral_reflectance_to_xyz(float R[SPECTRAL_SIZE]){vec3 xyz=vec3(0.);xyz+=R[0]*vec3(0.0000646919989576,0.0000018442894440,0.0003050171476380);xyz+=R[1]*vec3(0.0002194098998132,0.0000062053235865,0.0010368066663574);xyz+=R[2]*vec3(0.0011205743509343,0.0000310096046799,0.0053131363323992);xyz+=R[3]*vec3(0.0037666134117111,0.0001047483849269,0.0179543925899536);xyz+=R[4]*vec3(0.0118805536037990,0.0003536405299538,0.0570775815345485);xyz+=R[5]*vec3(0.0232864424191771,0.0009514714056444,0.1136516189362870);xyz+=R[6]*vec3(0.0345594181969747,0.0022822631748318,0.1733587261835500);xyz+=R[7]*vec3(0.0372237901162006,0.0042073290434730,0.1962065755586570);xyz+=R[8]*vec3(0.0324183761091486,0.0066887983719014,0.1860823707062960);xyz+=R[9]*vec3(0.0212332056093810,0.0098883960193565,0.1399504753832070);xyz+=R[10]*vec3(0.0104909907685421,0.0152494514496311,0.0891745294268649);xyz+=R[11]*vec3(0.0032958375797931,0.0214183109449723,0.0478962113517075);xyz+=R[12]*vec3(0.0005070351633801,0.0334229301575068,0.0281456253957952);xyz+=R[13]*vec3(0.0009486742057141,0.0513100134918512,0.0161376622950514);xyz+=R[14]*vec3(0.0062737180998318,0.0704020839399490,0.0077591019215214);xyz+=R[15]*vec3(0.0168646241897775,0.0878387072603517,0.0042961483736618);xyz+=R[16]*vec3(0.0286896490259810,0.0942490536184085,0.0020055092122156);xyz+=R[17]*vec3(0.0426748124691731,0.0979566702718931,0.0008614711098802);xyz+=R[18]*vec3(0.0562547481311377,0.0941521856862608,0.0003690387177652);xyz+=R[19]*vec3(0.0694703972677158,0.0867810237486753,0.0001914287288574);xyz+=R[20]*vec3(0.0830531516998291,0.0788565338632013,0.0001495555858975);xyz+=R[21]*vec3(0.0861260963002257,0.0635267026203555,0.0000923109285104);xyz+=R[22]*vec3(0.0904661376847769,0.0537414167568200,0.0000681349182337);xyz+=R[23]*vec3(0.0850038650591277,0.0426460643574120,0.0000288263655696);xyz+=R[24]*vec3(0.0709066691074488,0.0316173492792708,0.0000157671820553);xyz+=R[25]*vec3(0.0506288916373645,0.0208852059213910,0.0000039406041027);xyz+=R[26]*vec3(0.0354739618852640,0.0138601101360152,0.0000015840125870);xyz+=R[27]*vec3(0.0214682102597065,0.0081026402038399,0.0000000000000000);xyz+=R[28]*vec3(0.0125164567619117,0.0046301022588030,0.0000000000000000);xyz+=R[29]*vec3(0.0068045816390165,0.0024913800051319,0.0000000000000000);xyz+=R[30]*vec3(0.0034645657946526,0.0012593033677378,0.0000000000000000);xyz+=R[31]*vec3(0.0014976097506959,0.0005416465221680,0.0000000000000000);xyz+=R[32]*vec3(0.0007697004809280,0.0002779528920067,0.0000000000000000);xyz+=R[33]*vec3(0.0004073680581315,0.0001471080673854,0.0000000000000000);xyz+=R[34]*vec3(0.0001690104031614,0.0000610327472927,0.0000000000000000);xyz+=R[35]*vec3(0.0000952245150365,0.0000343873229523,0.0000000000000000);xyz+=R[36]*vec3(0.0000490309872958,0.0000177059860053,0.0000000000000000);xyz+=R[37]*vec3(0.0000199961492222,0.0000072209749130,0.0000000000000000);return xyz;}float KS(float R){return pow(1.0-R,2.0)/(2.0*R);}float KM(float KS){return 1.0+KS-sqrt(pow(KS,2.0)+2.0*KS);}vec3 spectral_mix(vec3 color1,float tintingStrength1,float factor1,vec3 color2,float tintingStrength2,float factor2){vec3 lrgb1=spectral_srgb_to_linear(color1);vec3 lrgb2=spectral_srgb_to_linear(color2);float R1[SPECTRAL_SIZE];float R2[SPECTRAL_SIZE];spectral_linear_to_reflectance(lrgb1,R1);spectral_linear_to_reflectance(lrgb2,R2);float luminance1=spectral_reflectance_to_xyz(R1)[1];float luminance2=spectral_reflectance_to_xyz(R2)[1];float R[SPECTRAL_SIZE];for(int i=0;i<SPECTRAL_SIZE;i++){float concentration1=pow(factor1,2.)*pow(tintingStrength1,2.)*luminance1;float concentration2=pow(factor2,2.)*pow(tintingStrength2,2.)*luminance2;float totalConcentration=concentration1+concentration2;float ksMix=0.;ksMix+=KS(R1[i])*concentration1;ksMix+=KS(R2[i])*concentration2;R[i]=KM(ksMix/totalConcentration);}return spectral_xyz_to_srgb(spectral_reflectance_to_xyz(R));}vec3 spectral_mix(vec3 color1,vec3 color2,float factor){return spectral_mix(color1,1.,1.-factor,color2,1.,factor);}vec3 spectral_mix(vec3 color1,float factor1,vec3 color2,float factor2){return spectral_mix(color1,1.,factor1,color2,1.,factor2);}const float GAMMA=2.4,EPSILON=0.0001;const float DARKEN_THRESHOLD=0.7;const float EDGE_MIN=0.05,EDGE_MAX=0.35;void main(void){vec2 uv=0.5*p+0.5;vec2 sourceUV=vec2(uv.x,1.0-uv.y);vec2 maskUV=u_targetIsFramebuffer ? vec2(uv.x,1.0-uv.y): uv;vec4 source=texture(u_source,sourceUV);vec4 maskColor=texture(u_mask,maskUV);if(maskColor.a==0.0){outColor=source;return;}vec4 pigment=vec4(u_color.xyz,1.0);if(maskColor.a>DARKEN_THRESHOLD){float blacken=0.5*(min(maskColor.a,1.0)-DARKEN_THRESHOLD);pigment=pigment*(1.0-blacken)-vec4(0.5)*blacken;pigment.rgb=max(pigment.rgb,vec3(0.0));}float mixIntensity=min(maskColor.a,1.0);if(!u_isBrush){vec2 texelSize=1.0/vec2(textureSize(u_mask,0));float scaledAlpha=maskColor.a*15.0;float blurEdge=0.0;for(int i=-2;i<=2;i+=2){for(int j=-2;j<=2;j+=2){vec2 neighborUV=maskUV+vec2(float(i),float(j))*texelSize;float neighborAlpha=texture(u_mask,neighborUV).a*15.0;blurEdge+=smoothstep(EDGE_MIN,EDGE_MAX,length(vec2(dFdx(neighborAlpha),dFdy(neighborAlpha))));}}blurEdge/=9.0;mixIntensity=clamp(maskColor.a+blurEdge*0.1,0.0,1.0);}vec3 bgColor=mix(vec3(1.0),source.rgb,source.a);outColor=vec4(spectral_mix(bgColor,pigment.rgb,mixIntensity),1.);}"),this.glMask=v?.ensureResources?.(n,e,r,i);const a=_?.ensureResources?.(n,e,r,i,b)??{mask:null,ctx:null};t&&(n.blendSourceFramebuffer=((...t)=>y.ensureBlendSourceFramebuffer(...t))(n,n.blendSourceFramebuffer,e,r,i)),this.mask=a.mask,this.ctx=a.ctx},blend(t=!1,e=!1){S();const r=!0===this.isBrush,n=r?this.glMask:this.mask,i=r?this.mask:this.glMask,a=t?._array,o=!!a&&(this.cachedColor?.[0]!==a[0]||this.cachedColor?.[1]!==a[1]||this.cachedColor?.[2]!==a[2]||this.cachedColor?.[3]!==a[3]);!this.isBlending&&a&&(this.isBlending=!0,this.cachedColor=a,this.clearMask(this.glMask)),(e||o)&&(this.justChanged&&(this.applyShader(i,!r),this.justChanged=!1),this.isBlending&&this.applyShader(n,r),a&&(this.cachedColor=a),e&&(this.isBlending=!1,this.cachedColor=null))},applyShader(t,i){if(!t?.isDrawn)return;const a=this.getCompositeRect(t,i);if(!a)return void this.clearMask(t);n.drawingContext;const o=n.shaderProgram,s=m(),c=((...t)=>y.blitSourceToFramebuffer(...t))({renderer:n,sourceTarget:s??n,sourceFramebuffer:n.blendSourceFramebuffer,dirtyRect:a,isFramebufferTarget:d,Cwidth:e,Cheight:r,getTargetPixelSize:R,toScissorBox:A,withScissor:M}),l=!!s,u=(i?v:_).getShaderMask(n,t,a,E,b);((...t)=>{y.runBlendShaderPass(...t)})({renderer:n,shader:o,source:c,mask:u,color:this.cachedColor,isBrushMask:i,Cwidth:e,Cheight:r,dirtyRect:a,targetIsFramebuffer:l,withScissor:M}),this.clearMask(t)}},C=()=>{S(),P.blend(!1,!0),P.clearMask(P.glMask),P.clearMask(P.mask),P.justChanged=!1,P.isBlending=!1,P.isBrush=null,P.cachedColor=null},F=(t=!1)=>{((t=!1)=>{l.load(t)})(t),n.loaded&&P.load()},k=Math.sqrt(3),I=.5*(k-1),D=(3-k)/6,L=t=>0|Math.floor(t),N=new Float64Array([1,1,-1,1,1,-1,-1,-1,1,0,-1,0,1,0,-1,0,0,1,0,-1,0,1,0,-1]);function B(t=Math.random){const e=function(t){const e=new Uint8Array(512);for(let t=0;t<256;t++)e[t]=t;for(let r=0;r<255;r++){const n=r+~~(t()*(256-r)),i=e[r];e[r]=e[n],e[n]=i}for(let t=256;t<512;t++)e[t]=e[t-256];return e}(t),r=new Float64Array(e).map(t=>N[t%12*2]),n=new Float64Array(e).map(t=>N[t%12*2+1]);return function(t,i){let a=0,o=0,s=0;const c=(t+i)*I,l=L(t+c),u=L(i+c),h=(l+u)*D,f=t-(l-h),m=i-(u-h);let d,x;f>m?(d=1,x=0):(d=0,x=1);const g=f-d+D,y=m-x+D,p=f-1+2*D,v=m-1+2*D,_=255&l,b=255&u;let R=.5-f*f-m*m;if(R>=0){const t=_+e[b];R*=R,a=R*R*(r[t]*f+n[t]*m)}let w=.5-g*g-y*y;if(w>=0){const t=_+d+e[b+x];w*=w,o=w*w*(r[t]*g+n[t]*y)}let E=.5-p*p-v*v;if(E>=0){const t=_+1+e[b+1];E*=E,s=E*E*(r[t]*p+n[t]*v)}return 70*(a+o+s)}}function U(t,e){let r=new Y(t),n=()=>r.next();return n.double=()=>n()+11102230246251565e-32*(2097152*n()|0),n.int32=()=>4294967296*r.next()|0,n.quick=n,n}class Y{constructor(t){null==t&&(t=+new Date);let e=4022871197;function r(t){t=String(t);for(let r=0;r<t.length;r++){e+=t.charCodeAt(r);let n=.02519603282416938*e;e=n>>>0,n-=e,n*=e,e=n>>>0,n-=e,e+=4294967296*n}return 2.3283064365386963e-10*(e>>>0)}this.c=1,this.s0=r(" "),this.s1=r(" "),this.s2=r(" "),this.s0-=r(t),this.s0<0&&(this.s0+=1),this.s1-=r(t),this.s1<0&&(this.s1+=1),this.s2-=r(t),this.s2<0&&(this.s2+=1)}next(){let{c:t,s0:e,s1:r,s2:n}=this,i=2091639*e+2.3283064365386963e-10*t;return this.s0=r,this.s1=n,this.s2=i-(this.c=0|i)}copy(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}}let z=U(Math.random()),O=U(Math.random());const X=[],G=t=>X.push(t),Z=t=>{z=U(t),O=U(`${t}:2`);for(const t of X)t()};let V=B(U(Math.random())),H=B(U(Math.random()));const $=t=>{V=B(U(t)),H=B(U(`${t}:2`))},W=(t=0,e=1)=>t+z()*(e-t),q=(t=0,e=1)=>t+O()*(e-t),j=t=>t[~~(z()*t.length)],K=(t,e)=>~~W(t,e),J=(t,e)=>~~q(t,e),Q=(t=0,e=1)=>{const r=1-z(),n=z();return Math.sqrt(-2*Math.log(r))*ct(360*n)*e+t},tt=t=>{let e=0;const r=[];for(const n in t)e+=t[n],r.push({key:n,cumulative:e});const n=z()*e;for(const{key:t,cumulative:e}of r)if(n<e)return isNaN(t)?t:parseInt(t)},et=(t,e,r,n,i,a=!1)=>{let o=n+(t-e)/(r-e)*(i-n);return a?n<i?rt(o,n,i):rt(o,i,n):o},rt=(t,e,r)=>Math.max(Math.min(t,r),e),nt=t=>(t%=360)<0?t+360:t,it=1440,at=2*Math.PI/it,ot=new Float32Array(it).fill(NaN),st=new Float32Array(it).fill(NaN),ct=t=>{const e=~~(4*nt(t));let r=ot[e];return isNaN(r)&&(r=Math.cos(e*at),ot[e]=r),r},lt=t=>{const e=~~(4*nt(t));let r=st[e];return isNaN(r)&&(r=Math.sin(e*at),st[e]=r),r},ut=(t,e=!1)=>{if(e||a()){let e=180*t/Math.PI%360;return e<0?e+360:e}return t},ht=(t,e=!1)=>e||a()?180*t/Math.PI:t,ft=(t,e,r,n,i)=>{let a=ct(i),o=lt(i);return{x:a*(r-t)+o*(n-e)+t,y:a*(n-e)-o*(r-t)+e}},mt=(t,e,r,n)=>Math.hypot(r-t,n-e),dt=(t,e,r,n)=>ut(Math.atan2(-(n-e),r-t),!0),xt=(t,e,r,n,i=!1)=>{let a=t.x,o=t.y,s=e.x,c=e.y,l=r.x,u=r.y,h=n.x,f=n.y;if(a===s&&o===c||l===h&&u===f)return!1;let m=s-a,d=c-o,x=h-l,g=f-u,y=g*m-x*d;if(0===y)return!1;let p=(x*(o-u)-g*(a-l))/y,v=(m*(o-u)-d*(a-l))/y;return!(!i&&(v<0||v>1))&&{x:a+p*m,y:o+p*d}};let gt=!1;function yt(){gt||(S(),vt=.01*e,_t=-.5*e,bt=-.5*r,Rt=Math.round(2*e/vt),wt=Math.round(2*r/vt),Ft("hand",(t,e)=>{const r=q(.2,.8),n=J(5,10);return Dt(e,(e,i)=>.5*n*lt(r*i*e+J(15,25))*.2*ct(t)+H(e,i)*n*.7)}),Ft("curved",(t,e)=>{let r=J(-10,10);return J(0,100)%2==0&&(r*=-1),Dt(e,(e,n)=>3*et(H(.02*e+.03*t,.02*n+.03*t),0,1,-r,r))}),Ft("zigzag",(t,e)=>{let r=J(-30,-15)+Math.abs(44*lt(t));J(0,100)%2==0&&(r*=-1);let n=r,i=0;for(let t=0;t<Rt;t++){for(let r=0;r<wt;r++)e[t][r]=i,i+=n,n*=-1;i+=n,n*=-1}return e}),Ft("waves",(t,e)=>{const r=J(10,15)+5*lt(t),n=J(3,6)+3*ct(t),i=J(20,35);return Dt(e,(t,e)=>lt(r*t)*i*ct(e*n)+J(-3,3))}),Ft("seabed",(t,e)=>{const r=q(.4,.8),n=J(18,26);return Dt(e,(e,i)=>1.1*n*lt(r*i*e+J(15,20))*ct(t))}),Ft("spiral",(t,e)=>{const r=J(5,10),n=2*J(0,2)-1,i=J(65,80),a=Array.from({length:r},()=>({x:q(.1,.9)*Rt,y:q(.1,.9)*wt}));return Dt(e,(t,e)=>{let r=0,o=0;for(const s of a){const a=t-s.x,c=e-s.y,l=1/(a*a+c*c+1),u=Math.atan2(c,a)*(180/Math.PI),h=n*(u+i)*Math.PI/180;r+=l*Math.cos(h),o+=l*Math.sin(h)}return Math.atan2(o,r)*(180/Math.PI)})}),Ft("columns",(t,e)=>{const r=J(3,8),n=J(25,45);return Dt(e,(t,e)=>lt(t*r)*n)}),gt=!0)}class pt{constructor(t,e){yt();const r=c();this.mx=r.x,this.my=r.y,this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,T.field.isActive&&(this.colIdx=Math.round((t+this.mx-_t)/vt),this.rowIdx=Math.round((e+this.my-bt)/vt))}reset(){this.plotted=0}isIn(){return T.field.isActive?pt.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const t=e,n=r,i=this.x+this.mx,a=this.y+this.my;return i>=-.3*t&&i<=1.3*t&&a>=-.3*n&&a<=1.3*n}angle(t=!1){return T.field.isActive&&(t||this.isIn())?Et.get(T.field.current).field[this.colIdx][this.rowIdx]*T.field.wiggle:0}moveTo(t,e,r=1){this.movePos(ht(t),e,r)}_moveToDegrees(t,e,r=1){this.movePos(t,e,r)}plotTo(t,e,r,n=1,i=void 0){this.movePos(t,e,r,n,i)}movePos(t,e,r,n=!1,i=void 0){const a=n||1;if(!this.isIn())return void(this.plotted+=r/a);const o=e/r,s=T.field.isActive,c=!!n;for(let e=0;e<o;e++){const n=c&&void 0!==i&&0===e?i:c?t.angle(this.plotted):t,o=(s?this.angle(!0):0)-n;this.update(this.x+r*ct(o),this.y+r*lt(o)),this.plotted+=r/a}}static getRowIndex(t,e=1){const r=t+c().y-bt;return Math.round(r/vt/e)}static getColIndex(t,e=1){const r=t+c().x-_t;return Math.round(r/vt/e)}static isIn(t,e){return t>=0&&e>=0&&t<Rt&&e<wt}}T.field={isActive:!1,current:null,wiggle:1};let vt,_t,bt,Rt,wt,Et=new Map;const At=new Set(["degrees","radians"]);function Mt(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!At.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function Tt(t,e){return function(t,e){if("radians"!==e)return t;for(let e=0;e<t.length;e++)for(let r=0;r<t[e].length;r++)t[e][r]=ht(t[e][r],!0);return t}(t.gen(e,new Array(Rt).fill(null).map(()=>new Float32Array(wt))),t.angleMode)}function St(t=0){if(!T.field.isActive||!T.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=Et.get(T.field.current);e.field=Tt(e,t)}function Pt(t){if(T.field.wiggle||(T.field.wiggle=1),yt(),!Et.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(Et.keys()).join(", ")}.`);T.field.isActive=!0,T.field.current=t;const e=Et.get(t);e.field||(e.field=Tt(e,0))}function Ct(){yt(),T.field.isActive=!1}function Ft(t,e,r={}){Et.set(t,{gen:e,field:null,angleMode:Mt(r)})}function kt(){return yt(),Array.from(Et.keys())}function It(t=1){Pt("hand"),T.field.wiggle=t}function Dt(t,e){for(let r=0;r<Rt;r++)for(let n=0;n<wt;n++)t[r][n]=e(r,n);return t}const Lt=[],Nt=(t,e,r)=>Math.max(e,Math.min(t,r)),Bt="degrees",Ut="radians";let Yt=null,zt=Ut;const Ot=[];let Xt={a:1,b:0,c:0,d:1,x:0,y:0};function Gt(t,e){return{a:t.a*e.a+t.c*e.b,b:t.b*e.a+t.d*e.b,c:t.a*e.c+t.c*e.d,d:t.b*e.c+t.d*e.d,x:t.a*e.x+t.c*e.y+t.x,y:t.b*e.x+t.d*e.y+t.y}}class Zt{constructor(t,e,r){if(t?._array)return this.r=Math.round(255*t._array[0]),this.g=Math.round(255*t._array[1]),this.b=Math.round(255*t._array[2]),this.hex=this.rgbToHex(this.r,this.g,this.b),this._array=[...t._array],void(this.gl=this._array);if("string"==typeof t){const e=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)$/i.exec(t);if(e){this.r=Nt(parseInt(e[1]),0,255),this.g=Nt(parseInt(e[2]),0,255),this.b=Nt(parseInt(e[3]),0,255),this.hex=this.rgbToHex(this.r,this.g,this.b);const t=void 0!==e[4]?Nt(parseFloat(e[4]),0,1):1;return this._array=[this.r/255,this.g/255,this.b/255,t],void(this.gl=this._array)}this.hex=this.standardize(t);const r=this.hexToRgb(this.hex);this.r=r.r,this.g=r.g,this.b=r.b}else this.r=Nt(t??0,0,255),this.g=Nt(e??t??0,0,255),this.b=Nt(r??t??0,0,255),this.hex=this.rgbToHex(this.r,this.g,this.b);this._array=[this.r/255,this.g/255,this.b/255,1],this.gl=this._array}rgbToHex(t,e,r){return`#${(1<<24|t<<16|e<<8|r).toString(16).slice(1)}`}hexToRgb(t){t=t.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,(t,e,r,n)=>e+e+r+r+n+n);const e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(!e)throw new Error(`Invalid color value "${t}".`);return{r:parseInt(e[1],16),g:parseInt(e[2],16),b:parseInt(e[3],16)}}standardize(t){const e=function(){if(Yt)return Yt;if("undefined"!=typeof document)return Yt=document.createElement("canvas").getContext("2d"),Yt;if("undefined"!=typeof OffscreenCanvas)return Yt=new OffscreenCanvas(1,1).getContext("2d"),Yt;throw new Error("Standalone color parsing requires CanvasRenderingContext2D support.")}();return e.fillStyle=t,e.fillStyle}_getRed(){return this.r}_getGreen(){return this.g}_getBlue(){return this.b}}function Vt(t){if(t!==Bt&&t!==Ut)throw new Error(`Invalid angle mode "${t}". Use "degrees" or "radians".`);zt=t}function Ht(){return zt}function $t(){yt(),Lt.push({fill:{...T.fill},wash:T.wash?{...T.wash}:null,stroke:{...T.stroke},hatch:{...T.hatch},mass:T.mass?{...T.mass}:null,field:{...T.field}}),Ot.push({...Xt})}function Wt(){0!==Ot.length&&(Xt=Ot.pop(),function(){const t=Lt.pop();t&&(T.stroke={...t.stroke},T.field={...t.field},T.hatch={...t.hatch},T.fill={...t.fill},t.wash&&(T.wash={...t.wash}),t.mass?T.mass={...t.mass}:T.mass&&(T.mass={...T.mass,isActive:!1,brush:null,color:null,options:{}}))}())}function qt(t,e){Xt=Gt(Xt,{a:1,b:0,c:0,d:1,x:t,y:e})}function jt(t){const e=zt===Ut?t:t*Math.PI/180,r=Math.cos(e),n=Math.sin(e);Xt=Gt(Xt,{a:r,b:n,c:-n,d:r,x:0,y:0})}function Kt(t,e=t){Xt=Gt(Xt,{a:t,b:0,c:0,d:e,x:0,y:0})}function Jt(){var t;(t={usesRadians:()=>"radians"===zt,fromDegrees:t=>"radians"===zt?t*Math.PI/180:t,createColor:(...t)=>1===t.length&&t[0]?._array?t[0]:new Zt(...t),getAffineMatrix:()=>Xt}).usesRadians&&(a=t.usesRadians),t.fromDegrees&&(o=t.fromDegrees),t.createColor&&(s=t.createColor),t.getAffineMatrix&&(c=t.getAffineMatrix)}function Qt(){C()}function te(...t){h(),P.glMask&&P.clearMask(P.glMask),P.mask&&P.clearMask(P.mask),P.justChanged=!1,P.isBlending=!1,P.isBrush=null,P.cachedColor=null;const e=n.drawingContext,r=0===t.length?[1,1,1,0]:[...s(...t)._array.slice(0,3),1];e.bindFramebuffer(e.FRAMEBUFFER,null),e.disable(e.SCISSOR_TEST),e.clearColor(r[0],r[1],r[2],r[3]),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}let ee,re,ne,ie,ae=null,oe=!1,se=1,ce=0,le=0;function ue(t,e,r,n){ae=t,ce=e,le=r,se=n;const i=function(t,e,r,n){const i=function(t){return t.getContext("webgl2",{premultipliedAlpha:!0})??t.getContext("webgl2")}(t);if(!i)throw new Error("brush.load(target) requires a canvas with a WebGL2 context.");return{canvas:t,drawingContext:i,width:e,height:r,pixelDensity:()=>n}}(t,e,r,n);u({Renderer:i,Cwidth:e,Cheight:r,Density:n}),oe=!0}function he(t,e,r={}){if("undefined"==typeof document)throw new Error("brush.createCanvas() requires a browser document.");const n=Math.max(1,Math.round(t)),i=Math.max(1,Math.round(e)),a=Math.max(1,Number(r.pixelDensity)||1),o=document.createElement("canvas");if(o.width=Math.max(1,Math.round(n*a)),o.height=Math.max(1,Math.round(i*a)),o.style.width=`${n}px`,o.style.height=`${i}px`,r.id&&(o.id=r.id),r.parent){const t="string"==typeof r.parent?document.querySelector(r.parent):r.parent;if(!t)throw new Error(`Could not find parent "${r.parent}" for brush.createCanvas().`);t.appendChild(o)}return ue(o,n,i,a),o}class fe{constructor(t,e=!1){this.a=t,this.vertices=e?t:t.map(([t,e])=>({x:t,y:e})),this.sides=this.vertices.map((t,e,r)=>[t,r[(e+1)%r.length]]),this._intersectionCache={}}intersect(t){const e=`${t.point1.x},${t.point1.y}-${t.point2.x},${t.point2.y}`;if(this._intersectionCache[e])return this._intersectionCache[e];const r=[];for(const[e,n]of this.sides){const i=xt(t.point1,t.point2,e,n);i&&r.push(i)}return this._intersectionCache[e]=r,r}show(){T.wash&&this.wash(),T.fill&&this.fill(),T.mass&&this.mass(),T.hatch&&this.hatch(),T.stroke&&this.draw()}}class me{constructor(t){this.segments=[],this.angles=[],this.pres=[],this.type=t,this.dir=0,this.calcIndex(0),this.pol=!1}addSegment(t=0,e=0,r=1,n=!1){this.angles.length>0&&this.angles.pop(),t=n?(t%360+360)%360:ut(t),this.angles.push(t,t),this.pres.push(r),this.segments.push(e),this.length=this.segments.reduce((t,e)=>t+e,0)}endPlot(t=0,e=1,r=!1){t=r?(t%360+360)%360:ut(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=ut(t)}pressure(t){return t>this.length?this.pres[this.pres.length-1]:this.curving(this.pres,t)}angle(t){return t>this.length?this.angles[this.angles.length-1]:(this.calcIndex(t),"curve"===this.type?this.curving(this.angles,t)+this.dir:this.angles[this.index]+this.dir)}curving(t,e){let r=t[this.index],n=t[this.index+1]??r;return Math.abs(n-r)>180&&(n>r?n=-(360-n):r=-(360-r)),et(e-this.suma,0,this.segments[this.index],r,n,!0)}calcIndex(t){this.index=-1,this.suma=0;let e=0;for(;e<=t;)this.suma=e,e+=this.segments[this.index+1],this.index++;return this.index}genPol(t,n,i=1,a){yt();const o=a<0?4:1,s=[],c=Math.round(this.length/o),l=new pt(t+e/2,n+r/2);let u=0,h=0;for(let t=0;t<c;t++){l.plotTo(this,o,o);const t=this.calcIndex(l.plotted);u+=o,(u>=(a<=0?8:Math.max(this.segments[t]*a*q(.7,1.3),20))||t>=h)&&l.x&&(s.push([l.x-e/2,l.y-r/2]),u=0,t>=h&&h++)}return new fe(s)}show(t,e,r=1){T.wash&&this.wash(t,e,r),T.fill&&this.fill(t,e,r),T.mass&&this.mass(t,e,r),T.hatch&&this.hatch(t,e,r),T.stroke&&this.draw(t,e,r)}}function de(t){new fe(t).show()}function xe(t,e,r,n,i="corner"){"center"===i&&(t-=r/2,e-=n/2),ve(0),_e(t,e),_e(t+r,e),_e(t+r,e+n),_e(t,e+n),be(!0)}function ge(t,e,r,n=!1){const i=new me("curve"),a=Math.PI*r,o=q(0,360),s=n?()=>1+.2*n*q():()=>1;for(let t=0;t<4;t++){const e=-90*t+o;i.addSegment(e*s(),a/2*s(),1,!0)}if(n){const t=n*J(-5,5);i.addSegment(o,Math.abs(t)*(Math.PI/180)*r,1,!0),i.endPlot(t+o,1,!0)}else i.endPlot(o,1,!0);const c=t-r*lt(o),l=e-r*ct(-o);i.show(c,l,1)}function ye(t,e,r,n,i){const a=ht(n),o=((ht(i)-a)%360+360)%360;if(0===o)return;const s=new me("curve"),c=Math.max(1,Math.ceil(o/90)),l=o/c,u=Math.PI*r*l/180;for(let t=0;t<c;t++)s.addSegment(a+t*l+90,u,1,!0);s.endPlot(a+o+90,1,!0);const h=t+r*ct(a),f=e-r*lt(a);s.draw(h,f,1)}class pe{constructor(){this.isClosed=!1,this.curvature=re,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){Me(this.vert,this.curvature,this.isClosed).show()}}function ve(t=0){re=rt(t,0,1),ee=new pe}function _e(t,e,r=1){if(!ee)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");ee.vertex(t,e,r)}function be(t=!1){if(!ee)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(ee.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(ee.vertex(...ee.vert[0]),ee.isClosed=!0),ee.show(),ee=!1}function Re(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);ie=[e,r],ne=new me(t)}function we(t,e,r){if(!ne)throw new Error("move() called without beginStroke(). Call beginStroke() first.");ne.addSegment(t,e,r)}function Ee(t,e){if(!ne)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");ne.endPlot(t,e),ne.draw(ie[0],ie[1],1),ne=!1}function Ae(t,e=.5){if(!t||t.length<2)throw new Error("spline() requires at least 2 points. Each point should be [x, y, pressure].");Me(t,e).draw()}function Me(t,e=.5,r=!1){const n=new me(0===e?"segments":"curve"),i=2*Math.PI;if(r&&0!==e&&t.push(t[1]),t&&t.length>0){let a,o,s,c=0;for(let l=0;l<t.length-1;l++)if(e>0&&l<t.length-2){const u=t[l],h=t[l+1],f=t[l+2],m=mt(u[0],u[1],h[0],h[1]),d=mt(h[0],h[1],f[0],f[1]),x=dt(u[0],u[1],h[0],h[1]),g=dt(h[0],h[1],f[0],f[1]),y=e*Math.min(m,d,.5*Math.min(m,d)),p=Math.max(m,d),v=m-y,_=d-y;if(Math.floor(x)===Math.floor(g)){const e=r&&0===l?0:m-c,i=r?0===l?0:d-s:d;n.addSegment(x,e,u[2],!0),l===t.length-3&&n.addSegment(g,i,h[2],!0),c=0,0===l&&(a=m,s=y,o=t[1],c=0)}else{const e={x:h[0]-y*ct(-x),y:h[1]-y*lt(-x)},f={x:e.x+p*ct(90-x),y:e.y+p*lt(90-x)},m={x:h[0]+y*ct(-g),y:h[1]+y*lt(-g)},d={x:m.x+p*ct(90-g),y:m.y+p*lt(90-g)},b=xt(e,f,m,d,!0),R=mt(e.x,e.y,b.x,b.y),w=mt(e.x,e.y,m.x,m.y)/2,E=i*R*(2*Math.asin(w/R)*(180/Math.PI))/360,A=r&&0===l?0:v-c,M=l===t.length-3?r?a-y:_:0;n.addSegment(x,A,u[2],!0),n.addSegment(x,isNaN(E)?0:E,u[2],!0),n.addSegment(g,M,h[2],!0),c=y,0===l&&(a=v,s=y,o=[e.x,e.y])}l===t.length-3&&n.endPlot(g,h[2],!0)}else if(0===e){const e=t[l],r=t[l+1],i=mt(e[0],e[1],r[0],r[1]),a=dt(e[0],e[1],r[0],r[1]);n.addSegment(a,i,r[2],!0),l===t.length-2&&n.endPlot(a,1,!0)}n.origin=r&&0!==e?o:t[0]}return n}let Te={createTipSurface:()=>{throw new Error("No stroke runtime adapter registered.")},loadImageTip:()=>{throw new Error("No stroke runtime adapter registered.")}},Se=!1;const Pe=(t,e,r)=>{const n=t.createProgram();for(let[i,a]of[[t.VERTEX_SHADER,e],[t.FRAGMENT_SHADER,r]]){const e=t.createShader(i);t.shaderSource(e,a),t.compileShader(e),t.attachShader(n,e)}return t.linkProgram(n),n};let Ce={beginDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},endDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},resetDirectShaderTracking:()=>{}};const Fe=(t,e)=>Ce.resetDirectShaderTracking(t,e);let ke,Ie,De,Le,Ne,Be=!1,Ue=0,Ye=0,ze=null;const Oe={},Xe={};let Ge=1,Ze=0,Ve=0,He=1,$e=0,We=0,qe=0,je=0,Ke=1,Je=1,Qe=new Float32Array(8192),tr=0,er=2048,rr=32768,nr=null,ir=null,ar=null,or=null,sr=null;const cr={},lr={};let ur=0,hr=new Float32Array(1280),fr=0,mr=256,dr=null;const xr=new Map,gr=new Float32Array([-1,-1,1,-1,-1,1,1,1]);function yr(){return Ie}function pr(){return((t,e,r)=>Ce.beginDirectMaskDraw(t,e,r))(n,ke,P.glMask)}function vr(t){((t,e,r)=>{Ce.endDirectMaskDraw(t,e,r)})(n,ke,t)}function _r(t,e,r,n,i){return t?(e<t.minX&&(t.minX=e),r<t.minY&&(t.minY=r),n>t.maxX&&(t.maxX=n),i>t.maxY&&(t.maxY=i),t):{minX:e,minY:r,maxX:n,maxY:i}}function br(t,e,r,n){if(tr>=er){er*=2;const t=new Float32Array(4*er);t.set(Qe),Qe=t}const i=t-qe,a=e-je,o=4*tr,s=Ge*i+Ve*a+$e+qe,c=Ze*i+He*a+We+je,l=Je*r*Ke/2;Qe[o]=s,Qe[o+1]=c,Qe[o+2]=l,Qe[o+3]=n/255;const u=s*Je,h=c*Je;nr=_r(nr,u-l-1,h-l-1,u+l+1,h+l+1),tr++}function Rr(t,e){if(0===fr)return;P.glMask.isDrawn=!0;const r=pr();let i=xr.get(e);i||(i=ke.createTexture(),ke.bindTexture(ke.TEXTURE_2D,i),ke.texImage2D(ke.TEXTURE_2D,0,ke.RGBA,ke.RGBA,ke.UNSIGNED_BYTE,t.canvas),ke.texParameteri(ke.TEXTURE_2D,ke.TEXTURE_MIN_FILTER,ke.LINEAR),ke.texParameteri(ke.TEXTURE_2D,ke.TEXTURE_MAG_FILTER,ke.LINEAR),ke.texParameteri(ke.TEXTURE_2D,ke.TEXTURE_WRAP_S,ke.CLAMP_TO_EDGE),ke.texParameteri(ke.TEXTURE_2D,ke.TEXTURE_WRAP_T,ke.CLAMP_TO_EDGE),xr.set(e,i)),ke.useProgram(ir),ke.enable(ke.BLEND),ke.blendFunc(ke.ONE_MINUS_DST_ALPHA,ke.ONE),ke.activeTexture(ke.TEXTURE0),ke.bindTexture(ke.TEXTURE_2D,i),ke.uniform1i(lr.u_tex,0);const a=T.stroke.color._array;ke.uniform4f(lr.u_color,...a),ke.uniformMatrix4fv(lr.u_proj,!1,yr()),ke.bindVertexArray(ar),ke.bindBuffer(ke.ARRAY_BUFFER,sr);const o=5*fr*4,s=hr.subarray(0,5*fr);o>ur?(ke.bufferData(ke.ARRAY_BUFFER,hr,ke.DYNAMIC_DRAW),ur=hr.byteLength):ke.bufferSubData(ke.ARRAY_BUFFER,0,s),ke.drawArraysInstanced(ke.TRIANGLE_STRIP,0,4,fr),ke.bindVertexArray(null),ke.bindTexture(ke.TEXTURE_2D,null),vr(r),dr&&(P.markDirtyRect(P.glMask,dr),dr=null),fr=0,Fe(n,ke)}Se||(v={ensureResources:function(t,e,r,n){return function(t,e,r,n){return!t.glMask||t.glMask.width!==e||t.glMask.height!==r||"function"==typeof t.glMask.pixelDensity&&t.glMask.pixelDensity()!==n}(t,e,r,n)&&(t.glMask?.remove&&t.glMask.remove(),t.glMask=p(t,{width:e,height:r,density:n,antialias:!1,depth:!1,stencil:!1})),t.glMask.dirtyRect??=null,t.glMask.isDrawn??=!1,t.glMask},clearMask:function(t,e){t&&(e(t),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:function(t,e,r,n,i){return t?t.dirtyRect?e()?r():i(n(t.dirtyRect,2)):r():null},getShaderMask:function(t,e){return e}},Se=!0),T.stroke={color:null,weight:1,type:"HB",isActive:!1,opacity:1};let wr=new Map;const Er={offset:.08,scale:.08,warp:.06,tilt:.06};function Ar(){return{...T.stroke}}function Mr(t){T.stroke={...t}}function Tr(t,e){if(e.type=["marker","custom","image","spray"].includes(e.type)?e.type:"default",void 0===e.markerTip&&(e.markerTip=!0),void 0===e.noise&&(e.noise=.3),e.noise=Math.max(0,Math.min(1,e.noise)),void 0!==e.vibration&&void 0===e.scatter&&(e.scatter=e.vibration),void 0!==e.definition&&void 0===e.sharpness&&(e.sharpness=e.definition),void 0!==e.quality&&void 0===e.grain&&(e.grain=e.quality),e.pressure=function(t){if(!t)return t;if("function"==typeof t)return{type:"custom",min_max:[0,1],curve:t,variation:{...Er}};if("object"==typeof t&&!Array.isArray(t)){if("custom"===t.type||"custom"===t.mode){const{mode:e,...r}=t;return{...r,type:"custom",variation:{...Er,...r.variation??{}}}}return"gaussian"===t.type||"gaussian"===t.mode||Array.isArray(t.curve)&&Array.isArray(t.min_max)?{...t,type:"gaussian",curve:t.curve,min_max:t.min_max}:t}if(Array.isArray(t)){const[e,r,n]=2===t.length?[t[0],(t[0]+t[1])/2,t[1]]:t,i=Math.min(e,r,n),a=Math.max(e,r,n),o=a-i||1,[s,c,l]=[(e-i)/o,(r-i)/o,(n-i)/o];return{type:"custom",min_max:[i,a],variation:{...Er},curve:t=>t<.5?s+(c-s)*t*2:c+(l-c)*(t-.5)*2}}}(e.pressure),"custom"===e.type){if("function"!=typeof e.tip)throw new Error(`Brush "${t}" is type "custom" but is missing a tip function.`);const r=`custom::${t}`;!function(t){const e=xr.get(t);e&&ke&&ke.deleteTexture(e),xr.delete(t)}(r);const n=Te.createTipSurface(500,500);return n.pixelDensity(1),n.background(255),n.noSmooth(),n.push(),n.translate(250,250),n.scale(5),n.noStroke(),e.tip(n),n.pop(),on.imageToWhite(n),on.tips.set(r,n),e.tipKey=r,void wr.set(t,{param:e,colors:[],buffers:[]})}if("image"===e.type){if(!e.image||!e.image.src)throw new Error(`Brush "${t}" is type "image" but is missing params.image.src. Example: image: { src: "./tip.jpg" }`);return on.add(e.image.src),wr.set(t,{param:e,colors:[],buffers:[]}),on.load()}wr.set(t,{param:e,colors:[],buffers:[]})}function Sr(){return[...wr.keys()]}function Pr(t){return wr.get(t)?.param??null}function Cr(t){for(const{param:e}of wr.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)}function Fr(t){if(!wr.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...wr.keys()].join(", ")}.`);T.stroke.type=t}function kr(t,e,r){h(),T.stroke.color=s(...arguments),T.stroke.isActive=!0}function Ir(t){T.stroke.weight=t}function Dr(t,e,r=1){Fr(t),kr(e),Ir(r)}function Lr(){T.stroke.isActive=!1}function Nr(t){return h(),t}function Br(){}let Ur,Yr,zr,Or,Xr=0;const Gr={};function Zr(t,n,a,o=!1){!function(){const t=c();Ge=t.a,Ze=t.b,Ve=t.c,He=t.d,$e=t.x,We=t.y,qe=e/2,je=r/2,Ke=Math.sqrt(Ge*Ge+Ze*Ze),Je=i}(),Ur=new pt(t+e/2,n+r/2),Yr=a,zr=o,zr&&zr.calcIndex(0)}const Vr=[];function Hr(t,i){i||(Or=t),function(){Gr.seed=999999*W();const{param:t}=wr.get(T.stroke.type)??{};if(!t)return;Gr.p=t;const{pressure:i}=t;if(Gr.isCustomPressure="custom"===i.type,Gr.a=Gr.isCustomPressure?0:W(-1,1),Gr.b=Gr.isCustomPressure?0:W(1,1.5),Gr.isCustomPressure){const t=i.variation??Er;Gr.cp=W(-t.offset,t.offset),Gr.ct=W(-t.warp,t.warp),Gr.cs=W(1-t.scale,1+t.scale),Gr.ck=W(-t.tilt,t.tilt)}else Gr.cp=W(3,3.5),Gr.ct=0,Gr.cs=1,Gr.ck=0;[Gr.min,Gr.max]=i.min_max,Gr.noiseoffset=.05*Gr.p.noise,zr||(Gr.cos=ct(Or),Gr.sin=lt(Or)),function(){S(),function(){const t=n?.glMask;t&&(ze=t,ze.dirtyRect??=null,ze.isDrawn??=!1,P.glMask=ze)}();const t=n.drawingContext,i=!Be||ke!==t;(i||Ue!==e||Ye!==r)&&(Ie=new Float32Array([2/e,0,0,0,0,2/r,0,0,0,0,1,0,-1,-1,0,1]),Ue=e,Ye=r),i&&(ke=t,Ne=Pe(ke,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_position;in float a_radius;in float a_alpha;uniform mat4 u_matrix;out float v_alpha;void main(){gl_Position=u_matrix*vec4(a_position,0.0,1.0);v_alpha=a_alpha;gl_PointSize=a_radius*2.0;}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin float v_alpha;out vec4 outColor;uniform vec4 u_color;void main(){vec2 v=gl_PointCoord-vec2(0.5);float f=length(v);float a=fwidth(f);f=1.0-smoothstep(0.5-a,0.5+a,f);if(f<0.01){discard;}outColor=vec4(u_color.xyz,v_alpha*f);}"),ke.useProgram(Ne),ke.enable(ke.BLEND),ke.blendFunc(ke.ONE_MINUS_DST_ALPHA,ke.ONE),["a_position","a_radius","a_alpha"].forEach(t=>Oe[t]=ke.getAttribLocation(Ne,t)),["u_matrix","u_color"].forEach(t=>Xe[t]=ke.getUniformLocation(Ne,t)),De=ke.createVertexArray(),ke.bindVertexArray(De),Le=ke.createBuffer(),ke.bindBuffer(ke.ARRAY_BUFFER,Le),ke.bufferData(ke.ARRAY_BUFFER,Qe.byteLength,ke.DYNAMIC_DRAW),rr=Qe.byteLength,ke.enableVertexAttribArray(Oe.a_position),ke.vertexAttribPointer(Oe.a_position,2,ke.FLOAT,!1,16,0),ke.enableVertexAttribArray(Oe.a_radius),ke.vertexAttribPointer(Oe.a_radius,1,ke.FLOAT,!1,16,8),ke.enableVertexAttribArray(Oe.a_alpha),ke.vertexAttribPointer(Oe.a_alpha,1,ke.FLOAT,!1,16,12),ke.bindVertexArray(null),xr.clear(),ir=Pe(ke,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_corner;in vec2 a_pos;in float a_size;in float a_angle;in float a_alpha;uniform mat4 u_proj;out vec2 v_uv;out float v_alpha;void main(){float c=cos(a_angle);float s=sin(a_angle);vec2 rotated=vec2(c*a_corner.x-s*a_corner.y,s*a_corner.x+c*a_corner.y);gl_Position=u_proj*vec4(a_pos+rotated*a_size,0.0,1.0);v_uv=a_corner*0.5+0.5;v_alpha=a_alpha;}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin vec2 v_uv;in float v_alpha;uniform sampler2D u_tex;uniform vec4 u_color;out vec4 outColor;void main(){float inkAlpha=texture(u_tex,v_uv).a;if(inkAlpha<0.01)discard;outColor=vec4(u_color.rgb,inkAlpha*v_alpha);}"),["a_corner","a_pos","a_size","a_angle","a_alpha"].forEach(t=>cr[t]=ke.getAttribLocation(ir,t)),["u_proj","u_color","u_tex"].forEach(t=>lr[t]=ke.getUniformLocation(ir,t)),ar=ke.createVertexArray(),ke.bindVertexArray(ar),or=ke.createBuffer(),ke.bindBuffer(ke.ARRAY_BUFFER,or),ke.bufferData(ke.ARRAY_BUFFER,gr,ke.STATIC_DRAW),ke.enableVertexAttribArray(cr.a_corner),ke.vertexAttribPointer(cr.a_corner,2,ke.FLOAT,!1,0,0),sr=ke.createBuffer(),ke.bindBuffer(ke.ARRAY_BUFFER,sr),ke.bufferData(ke.ARRAY_BUFFER,hr.byteLength,ke.DYNAMIC_DRAW),ur=hr.byteLength,ke.enableVertexAttribArray(cr.a_pos),ke.vertexAttribPointer(cr.a_pos,2,ke.FLOAT,!1,20,0),ke.vertexAttribDivisor(cr.a_pos,1),ke.enableVertexAttribArray(cr.a_size),ke.vertexAttribPointer(cr.a_size,1,ke.FLOAT,!1,20,8),ke.vertexAttribDivisor(cr.a_size,1),ke.enableVertexAttribArray(cr.a_angle),ke.vertexAttribPointer(cr.a_angle,1,ke.FLOAT,!1,20,12),ke.vertexAttribDivisor(cr.a_angle,1),ke.enableVertexAttribArray(cr.a_alpha),ke.vertexAttribPointer(cr.a_alpha,1,ke.FLOAT,!1,20,16),ke.vertexAttribDivisor(cr.a_alpha,1),ke.bindVertexArray(null),Be=!0)}();const a=!0!==P.isBrush;P.isBrush=!0,a&&(P.justChanged=!0),P.blend(T.stroke.color),Gr.alpha=["default","spray"].includes(Gr.p.type)?Gr.p.opacity:Gr.p.opacity/Math.min(T.stroke.weight,1.3),Gr.overscan=function(){const t=Math.max(1,Gr.max??1),e=T.stroke.weight*Gr.p.scatter,r=T.stroke.weight*Gr.p.weight*t;return Math.max(8,1.5*e+.75*r)}(),Gr.drawFn="spray"===Gr.p.type?jr:"marker"===Gr.p.type?Kr:"custom"===Gr.p.type||"image"===Gr.p.type?Jr:Qr,tn()}();const a=Gr.p?.spacing??1,o=Math.round(Yr*(i?t:1)/a);Gr.pressureCount=10,Gr.cachedPressure=void 0,Gr.lineNoiseCount=5,Gr.cachedLineNoise=void 0;const s=2*o;for(;Vr.length<s;)Vr.push(Q());for(let e=0;e<o;e++)i&&(Xr=zr.angle(Ur.plotted)),$r(),i?Ur.plotTo(zr,a,a,t,Xr):Ur._moveToDegrees(t,a,a);!function(){tn(),function(){if(0===tr)return;P.glMask.isDrawn=!0;const t=pr(),e=T.stroke.color._array;ke.useProgram(Ne),ke.enable(ke.BLEND),ke.blendFunc(ke.ONE_MINUS_DST_ALPHA,ke.ONE),ke.bindVertexArray(De),ke.bindBuffer(ke.ARRAY_BUFFER,Le);const r=16*tr,i=Qe.subarray(0,4*tr);r>rr?(ke.bufferData(ke.ARRAY_BUFFER,Qe,ke.DYNAMIC_DRAW),rr=Qe.byteLength):ke.bufferSubData(ke.ARRAY_BUFFER,0,i),ke.uniform4f(Xe.u_color,...e),ke.uniformMatrix4fv(Xe.u_matrix,!1,yr()),ke.drawArrays(ke.POINTS,0,tr),ke.bindVertexArray(null),vr(t),nr&&(P.markDirtyRect(P.glMask,nr),nr=null),tr=0,Fe(n,ke)}();const t=Gr.p?.type;"image"===t?Rr(on.tips.get(Gr.p.image.src),Gr.p.image.src):"custom"===t&&Rr(on.tips.get(Gr.p.tipKey),Gr.p.tipKey)}()}function $r(){const t=Wr(),e=((Gr.lineNoiseCount>=10||void 0===Gr.cachedLineNoise)&&(Gr.cachedLineNoise=et(V(Gr.seed+.01*Ur.plotted,0),-1,1,1-Gr.noiseoffset,1+Gr.noiseoffset),Gr.lineNoiseCount=0),Gr.lineNoiseCount++,Gr.cachedLineNoise);e>W(1,1.02)&&W(0,1)<.7||Gr.drawFn(t*e)}function Wr(){return(Gr.pressureCount>=10||void 0===Gr.cachedPressure)&&(Gr.cachedPressure=zr?qr()*zr.pressure(Ur.plotted):qr(),Gr.pressureCount=0),Gr.pressureCount++,Gr.cachedPressure}function qr(){if(!Gr.isCustomPressure)return function(t=.5+Gr.p.pressure.curve[0]*Gr.a,e=1-Gr.p.pressure.curve[1]*Gr.b,r=Gr.cp,n=Gr.min,i=Gr.max){const a=t*Yr,o=(Ur.plotted<a?1.2*e:.8*e)*(Yr/2);return et(1/(1+Math.pow(Math.abs((Ur.plotted-a)/o),2*r)),0,1,n,i)}();const t=Ur.plotted/Yr;return et(Gr.p.pressure.curve(Math.max(0,Math.min(1,.5+(t-.5+Gr.ct)*Gr.cs)))+Gr.cp+Gr.ck*(t-.5),0,1,Gr.min,Gr.max,!0)}function jr(t){const e=T.stroke.weight*Gr.p.scatter*t+T.stroke.weight*j(Vr)*Gr.p.scatter/3,r=Gr.p.weight*W(.9,1.1),n=Math.ceil(Gr.p.grain/t);for(let t=0;t<n;t++){const t=W(.9,1.1),n=t*e*W(-1,1),i=W(-1,1),a=Math.sqrt((t*e)**2-n**2);br(Ur.x+n,Ur.y+i*a,r,Gr.alpha)}}function Kr(t,e=!0,r=Gr.alpha){const n=e?T.stroke.weight*Gr.p.scatter:0,i=e?n*W(-1,1):0,a=e?n*W(-1,1):0;br(Ur.x+i,Ur.y+a,T.stroke.weight*Gr.p.weight*t,r*Math.max(.8,t)*W(.9,1.1))}function Jr(t,e=Gr.alpha){const r=T.stroke.weight*Gr.p.scatter,n=r*W(-1,1),i=r*W(-1,1),a=Gr.p.weight*T.stroke.weight*t,o=Gr.overscan;let s=0;"random"===Gr.p.rotate?s=K(0,360)*(Math.PI/180):"natural"===Gr.p.rotate&&(s=((zr?-Xr:-Or)+Ur.angle())*(Math.PI/180)),function(t,e,r,n,i,a=0){if(fr>=mr){mr*=2;const t=new Float32Array(5*mr);t.set(hr),hr=t}const o=t-qe,s=e-je,c=Ge*o+Ve*s+$e+qe,l=Ze*o+He*s+We+je,u=Je*r*Ke/2,h=Je*a*Ke,f=5*fr;hr[f]=c,hr[f+1]=l,hr[f+2]=u,hr[f+3]=n,hr[f+4]=i/255;const m=c*Je,d=l*Je,x=1.42*u+h;dr=_r(dr,m-x-1,d-x-1,m+x+1,d+x+1),fr++}(Ur.x+n,Ur.y+i,a,s,e*Math.max(.8,t)*W(.9,1.1),o)}function Qr(t,e=1){const r=(e=et(e,0,1,.9,1.05))*T.stroke.weight*Gr.p.scatter*(Gr.p.sharpness+(1-Gr.p.sharpness)*j(Vr)/t);if(W(0,Gr.p.grain*t)>.4){let e,n;if(zr){const t=Xr,i=ct(t),a=lt(t),o=r*W(-1,1),s=.3*r*W(-1,1);e=o*a+s*i,n=o*i-s*a}else{const t=r*W(-1,1),i=.3*r*W(-1,1);e=t*Gr.sin+i*Gr.cos,n=t*Gr.cos-i*Gr.sin}const i=t*t*Gr.p.weight*W(.85,1.15)*T.stroke.weight,a=Math.max(.9,t)*Gr.alpha*W(.75,1.1);br(Ur.x+e,Ur.y+n,i,a)}}function tn(){if(!1===Gr.p.markerTip)return;let t=Wr(),e=Gr.alpha;if("marker"===Gr.p.type)for(let r=1;r<10;r++)Kr(t*r/10,!0,8*e);else if("custom"===Gr.p.type||"image"===Gr.p.type)for(let r=1;r<5;r++)Jr(t*r/10,2*e)}function en(t,e,r,n){if(!T.stroke.isActive||!T.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");yt();let i=mt(t,e,r,n);0!=i&&(Zr(t,e,i),Hr(dt(t,e,r,n),!1))}function rn(t,e,r,n){if(!T.stroke.isActive||!T.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");yt(),Zr(t,e,r),Hr(ut(n),!1)}G(()=>{Vr.length=0});const nn=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate","markerTip","noise"],an=[["pen",[.3,.15,.9,2,150,.1,{curve:[.15,.2],min_max:[1.2,1]}]],["rotring",[.15,.05,.7,15,210,.1,{curve:[.35,.2],min_max:[1.3,1]}]],["2B",[.3,.75,.45,15,180,.1,{curve:[.1,.3],min_max:[1.1,.9]}]],["HB",[.3,.6,.3,10,170,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["2H",[.2,.6,.3,4,120,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["cpencil",[.3,.55,.8,7,75,.1,{curve:[.15,.2],min_max:[.95,1.2]}]],["pastel",[2.05/3,13.4/3,.91,28,35,.085/3,{mode:"gaussian",curve:[.4,.05],min_max:[1.09,.93]},"default",void 0,"natural",!0,1]],["crayon",[.3,5.45/3,.75,250,159,.23/3,[1.1,.9],"default",void 0,"natural",!0,1]],["charcoal",[.35,1.5,.68,500,120,.03,{curve:[.15,.4],min_max:[1.1,.95]}]],["spray",[.2,6,15,40,90,.5,{curve:[.2,.35],min_max:[.7,1]},"spray"]],["marker",[2,.2,null,null,1,.03,{curve:[.35,.25],min_max:[1.2,.85]},"marker"]]];for(let t of an){let e={};for(let r=0;r<t[1].length;r++)e[nn[r]]=t[1][r];Tr(t[0],e)}fe.prototype.draw=function(t=!1,e,r){let n=Ar();if(t&&Dr(t,e,r),n.isActive)for(let t of this.sides)en(t[0].x,t[0].y,t[1].x,t[1].y);Mr(n)},me.prototype.draw=function(t,e,r){Ar().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,n){yt(),Zr(e,r,t.length,t),Hr(n,!0)}(this,t,e,r))};const on={tips:new Map,add(t){this.tips.has(t)||this.tips.set(t,!1)},imageToWhite(t){t.loadPixels();for(let e=0;e<4*t.width*t.height;e+=4){let r=(t.pixels[e]+t.pixels[e+1]+t.pixels[e+2])/3;t.pixels[e]=t.pixels[e+1]=t.pixels[e+2]=255,t.pixels[e+3]=255-r}t.updatePixels()},async load(){const t=[...this.tips.keys()].filter(t=>!this.tips.get(t));await Promise.all(t.map(t=>((t,e)=>Te.loadImageTip(t,e))(t,on.imageToWhite).then(e=>{this.tips.set(t,e)})))}};function sn(){return{...T.hatch}}function cn(t){T.hatch={...t}}function ln(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let n=T.hatch;n.isActive=!0,n.dist=t,n.angle=ht(e),n.options=r}function un(t,e="black",r=1){T.hatch.hBrush={brush:t,color:e,weight:r}}function hn(){T.hatch.isActive=!1,T.hatch.hBrush=!1}function fn(t,e,r,n){const i=e*Math.PI/180,a=Math.cos(i),o=Math.sin(i),s=Math.cos(-i),c=Math.sin(-i),l=t.a,u=l.length,h=new Array(u);let f=Infinity,m=-Infinity;for(let t=0;t<u;t++){const e=l[t][0],r=l[t][1],n=[e*a-r*o,e*o+r*a];h[t]=n,n[1]<f&&(f=n[1]),n[1]>m&&(m=n[1])}const d=[];for(let t=0;t<u;t++){const e=h[t],r=h[(t+1)%u];e[1]!==r[1]&&d.push(e,r)}const x=d.length,g=[],y=[];let p=f+.5*r,v=r;for(;p<m;){y.length=0;for(let t=0;t<x;t+=2){const e=d[t][1],r=d[t+1][1];(e<=p&&p<r||r<=p&&p<e)&&y.push(d[t][0]+(p-e)/(r-e)*(d[t+1][0]-d[t][0]))}y.sort((t,e)=>t-e);for(let t=0;t<y.length-1;t+=2)g.push({scanY:p,x1:y[t]*s-p*c,y1:y[t]*c+p*s,x2:y[t+1]*s-p*c,y2:y[t+1]*c+p*s});p+=v,v*=n}return g}function mn(t){const{dist:e,options:r,segs:n}=function(t){const e=T.hatch.dist,r=(T.hatch.angle%180+180)%180,n=T.hatch.options,i=function(t,e,r,n){Array.isArray(t)||(t=[t]);const i=[];for(const a of t)for(const t of fn(a,r,e,n))i.push(t);return i.sort((t,e)=>t.scanY===e.scanY?t.x1-e.x1:t.scanY-e.scanY),i}(t,e,r,n.gradient?et(n.gradient,0,1,1,1.1,!0):1);return{dist:e,options:n,segs:i}}(t),i=r.rand||0,a=[];for(let t=0;t<n.length;t++){const o=n[t];let s=o.x1,c=o.y1,l=o.x2,u=o.y2;i&&(s+=2*i*e*W(-1,1),c+=2*i*e*W(-1,1),l+=2*i*e*W(-1,1),u+=2*i*e*W(-1,1));const h=r.continuous&&t%2==1?{x1:l,y1:u,x2:s,y2:c,scanY:o.scanY,isConnector:!1}:{x1:s,y1:c,x2:l,y2:u,scanY:o.scanY,isConnector:!1};if(a.push(h),t>0&&r.continuous){const t=a[a.length-2];a.push({x1:t.x2,y1:t.y2,x2:h.x1,y2:h.y1,scanY:o.scanY,isConnector:!0})}}return a}function dn(t){!function(t,e){const r=mn(t);!function(){const t=Ar();T.hatch.hBrush&&Dr(...Object.values(T.hatch.hBrush)),(()=>{for(let t=0;t<r.length;t++){const n=r[t];e(n.x1,n.y1,n.x2,n.y2,t,r)}})(),Mr(t)}()}(t,(t,e,r,n)=>{en(t,e,r,n)})}function xn(t,e,r={}){T.mass.brush=t,T.mass.color=e,T.mass.options=r,T.mass.isActive=!0}function gn(){T.mass.isActive=!1,T.mass.brush=null,T.mass.color=null,T.mass.options={}}function yn(t,e,r){return new fe(t.vertices.map(t=>[t.x+e,t.y+r]))}function pn(t,e,r,n,i){const a=(e+n)/2,o=(r+i)/2,s=n-e,c=i-r,l=Math.hypot(s,c);if(!l)return null;const u=-c/l,h=s/l,f=(t.x-a)*u+(t.y-o)*h;return{x:a+u*f,y:o+h*f}}function vn(t,e,r,n,i,a,o){let s=dt(t,e,r,n),c=dt(t,e,i,a);return((c-s)%360+360)%360>180&&([s,c]=[c,s]),[o(s),o(c)]}function _n(t){const e=q(.35,.65),r=t.x1+(t.x2-t.x1)*e,n=t.y1+(t.y2-t.y1)*e,i=t.x2-t.x1,a=t.y2-t.y1,o=Math.hypot(i,a)||1,s=q(.04,.1)*o,c=i/o*s*.5,l=a/o*s*.5;return[{x1:t.x1,y1:t.y1,x2:r-c,y2:n-l},{x1:r+c,y1:n+l,x2:t.x2,y2:t.y2}]}function bn(t,e,r){const n=function(t,e){const r=function(t){const e=t?.a??[];let r=Infinity,n=Infinity,i=-Infinity,a=-Infinity;for(const[t,o]of e)t<r&&(r=t),o<n&&(n=o),t>i&&(i=t),o>a&&(a=o);return{minX:r,minY:n,maxX:i,maxY:a,cx:(r+i)/2,cy:(n+a)/2,size:Math.hypot(i-r,a-n)}}(t),n=r.size*q(.6,1.4),[i,a]=e;return{x:r.cx+i*n,y:r.cy+a*n}}(t,e);for(const e of mn(t)){const t=!e.isConnector&&q()<.35?_n(e):[e];for(const e of t){const t=pn(n,e.x1,e.y1,e.x2,e.y2);if(!t)continue;const i=mt(t.x,t.y,e.x1,e.y1);if(!i)continue;const[a,o]=vn(t.x,t.y,e.x1,e.y1,e.x2,e.y2,r);ye(t.x,t.y,i,a,o)}}}function Rn(t,e,r,n,i,a){ln(e,r,n),bn(t,i,a)}function wn(t,e,r,n){const i=function(t,e,r,n){const i=!1===e,a=Pr(T.mass.brush)?.scatter??0,o=i?t:t.genPol(e,r,n,.15),s=Math.min(2*a,5),c=[[q(-s,s),q(-s,s)],[q(-s,s),q(-s,s)]];return[o,yn(o,c[0][0],c[0][1]),yn(o,c[1][0],c[1][1])]}(t,e,r,n),s=sn(),c=Ar(),l={...T.field},u=T.mass.options?.precision??.5,h=T.mass.options?.strength??1,f=T.mass.options?.gradient??.1,m=T.mass.options?.outline??!1,d=Pr(T.mass.brush)?.scatter??0,x=1.6*q(.65*d,.85*d)-.4*f,g=q(-90,90),y=((g+90)%180+180)%180-90>=0?q()<.5?[1,1]:[-1,-1]:q()<.5?[-1,1]:[1,-1],p=a()?t=>t*Math.PI/180:t=>t;Dr(T.mass.brush,T.mass.color,1),It(2-u),m&&i[0].draw(),Rn(i[0],.9*x,o(g),{gradient:f,rand:2-2*u,continuous:!0},y,p),h>.33&&Rn(i[1],x,o(g+20*q(-1,1)),{gradient:f,rand:.6-.6*u,continuous:!0},y,p),h>.66&&Rn(i[2],.8*x,o(g+15*q(-1,1)),{gradient:f,rand:.6-.6*u,continuous:!0},y,p),Mr(c),cn(s),T.field={...l}}function En(t,e,r){const n=2*Math.PI,i=P.ctx,a=r/2;i.moveTo(t+a,e),i.arc(t,e,a,0,n)}T.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},fe.prototype.hatch=function(t=!1,e,r){let n=sn();t&&ln(t,e,r),T.hatch.isActive&&dn(this),cn(n)},me.prototype.hatch=function(t,e,r){sn().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,.3),this.pol.hatch())},T.mass={isActive:!1,brush:null,color:null,options:{}},fe.prototype.mass=function(){T.mass?.isActive&&wn(this,!1)},me.prototype.mass=function(t,e,r){T.mass?.isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),wn(this,t,e,r))};let An=null,Mn=!1;Mn||(_={ensureResources:function(t,e,r,n,i){const a=Math.max(1,Math.round(e*n)),o=Math.max(1,Math.round(r*n));return function(t,e,r){return!t.mask||t.mask.width!==e||t.mask.height!==r}(t,a,o)&&(t.mask=g(a,o)),function(t,e,r,n){return!t.fillMaskFramebuffer||t.fillMaskFramebuffer.width!==e||t.fillMaskFramebuffer.height!==r||"function"==typeof t.fillMaskFramebuffer.pixelDensity&&t.fillMaskFramebuffer.pixelDensity()!==n}(t,e,r,n)&&(t.fillMaskFramebuffer?.remove&&t.fillMaskFramebuffer.remove(),t.fillMaskFramebuffer=p(t,{width:e,height:r,density:n,antialias:!1,depth:!1,stencil:!1}),i(t.fillMaskFramebuffer)),t.mask.dirtyRect??=null,t.mask.isDrawn??=!1,t.mask.drawingContext.imageSmoothingEnabled=!1,{mask:t.mask,ctx:t.mask.drawingContext}},clearMask:function(t,e){t&&(e(t),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:function(t,e,r,n,i){return t?t.dirtyRect?i(n(t.dirtyRect,4)):r():null},getShaderMask:function(t,e,r,n,i){const a=t.fillMaskFramebuffer,o=t.drawingContext,s=r??n(),c=s.maxX-s.minX,l=s.maxY-s.minY;An&&An.width===c&&An.height===l||(An=g(c,l));const u=An.drawingContext;return u.clearRect(0,0,c,l),u.drawImage(e,s.minX,s.minY,c,l,0,0,c,l),i(a),o.bindTexture(o.TEXTURE_2D,a.colorTexture),o.texSubImage2D(o.TEXTURE_2D,0,s.minX,s.minY,o.RGBA,o.UNSIGNED_BYTE,An),a}},Mn=!0);let Tn,Sn=[],Pn=[],Cn=[],Fn=[];T.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const kn=()=>({...T.fill});function In(t,e,r,n){T.fill.opacity=(arguments.length<4?e:n)||150,T.fill.color=arguments.length<3?s(t):s(t,e,r),T.fill.isActive=!0}function Dn(t,e="out"){T.fill.bleed_strength=rt(t,0,1),T.fill.direction=e}function Ln(t=.4,e=.4){T.fill.texture_strength=rt(t,0,1),T.fill.border_strength=rt(e,0,1)}function Nn(){T.fill.isActive=!1}let Bn,Un,Yn,zn,On;const Xn=[[],[]];function Gn(){for(let t=0;t<512;t++)Xn[0][t]=Q(.5,.2),Xn[1][t]=Q(0,.02)}G(Gn);class Zn{constructor(t,e,r,n=[],i=!1,a,o){if(this.v=t,this.m=e,this.dir=n,this.midP=r,i){let e=0,n=0;const i=[];for(let a=0;a<t.length;a++){const o=Math.abs(r.x-t[a].x),s=Math.abs(r.y-t[a].y);e=Math.max(e,o),n=Math.max(n,s);const c=t[a],l=t[(a+1)%t.length],u={x:l.x-c.x,y:l.y-c.y},h=ft(0,0,u.x,u.y,90),f={x:c.x+u.x/2,y:c.y+u.y/2};i.push({v1:c,v2:l,ray:{point1:f,point2:{x:f.x+h.x,y:f.y+h.y}}})}this.sizeX=e,this.sizeY=n;const a=Bn.sides;this.dir=Array(t.length);for(let t=0;t<i.length;t++){const e=i[t],r=e.ray.point1.x,n=e.ray.point1.y,o=e.ray.point2.x-r,s=e.ray.point2.y-n;let c=0;for(let t=0;t<a.length;t++){const i=a[t][0],l=a[t][1],u=l.x-i.x,h=l.y-i.y,f=h*o-u*s;if(0===f)continue;const m=(o*(n-i.y)-s*(r-i.x))/f;if(m<0||m>1)continue;const d=(u*(n-i.y)-h*(r-i.x))/f,x=r+d*o,g=n+d*s;(e.v2.x-e.v1.x)*(g-e.v1.y)-(e.v2.y-e.v1.y)*(x-e.v1.x)>.01&&c++}this.dir[t]=c%2==0}const o=W(-.6,.6)*e,s=W(-.6,.6)*n;this.midP={x:r.x+o,y:r.y+s}}else this.sizeX=a,this.sizeY=o}trim(t=1){if(t>=1||t<0||this.v.length<=8)return{v:this.v,m:this.m,dir:this.dir};const e=~~((1-t)*this.v.length),r=~~(this.v.length/2-e/2),n=this.v.length-e,i=new Array(n),a=new Array(n),o=new Array(n);let s=0;for(let t=0;t<r;t++,s++)i[s]=this.v[t],a[s]=this.m[t],o[s]=this.dir[t];for(let t=r+e;t<this.v.length;t++,s++)i[s]=this.v[t],a[s]=this.m[t],o[s]=this.dir[t];const c=r,l=r+e,u=this.v[(c-1+this.v.length)%this.v.length],h=this.v[l%this.v.length],f=h.x-u.x,m=h.y-u.y;for(let t=0;t<2;t++){const e=W(.25,.75),n={x:u.x+f*e,y:u.y+m*e},s=r+t;i.splice(s,0,n),a.splice(s,0,W(.4,.7)),o.splice(s,0,this.dir[c%this.dir.length])}return{v:i,m:a,dir:o}}scatter(t=.3){const e=this.v.length,r=Math.max(3,~~(e*t)),n=[],i=e/r;for(let t=0;t<r;t++)n.push(~~(t*i+W(0,.8*i)));const a=[],o=[],s=[],c=this.midP,l=Bn.sides;for(const t of n){const r=t%e;let n=this.v[r],i=!1;if(n.x<Un||n.x>zn||n.y<Yn||n.y>On)i=!0;else{let t=0;for(const[e,r]of l){const i=e.y,a=r.y;if(i>n.y==a>n.y)continue;const o=(n.y-i)/(a-i);n.x<e.x+o*(r.x-e.x)&&t++}i=t%2==0}i&&(n={x:c.x+(n.x-c.x)*W(.3,.6),y:c.y+(n.y-c.y)*W(.3,.6)}),a.push(n),o.push(this.m[r]),s.push(!this.dir[r])}return new Zn(a,o,this.midP,s,!1,this.sizeX,this.sizeY)}flipDirs(){return new Zn(this.v,this.m,this.midP,this.dir.map(t=>!t),!1,this.sizeX,this.sizeY)}grow(t=1){const{v:e,m:r,dir:n}=this.trim(t),i=e.length,a=2*i;Sn.length<i&&(Sn=new Array(i),Pn=new Array(i)),Cn.length<a&&(Cn=new Array(a),Fn=new Array(a));const o=Sn,s=Pn,c=Cn,l=Fn,u="out"===T.fill.direction?-90:90;0===Xn[0].length&&Gn();const h=Xn[0],f=h.length,m=Xn[1],d=m.length;let x,g,y,p=0,v=0,_=999===t?W(.6,.8):T.fill.bleed_strength;for(let a=0;a<i;a++){const x=e[a],g=e[a+1<i?a+1:0],y=r[a],b=n[a];if(t<997&&(_=y),_<.05){c[p]=y,l[p]=b,p++,o[v]=(x.x+g.x)/2,s[v]=(x.y+g.y)/2,c[p]=y,l[p]=b,p++,v++;continue}const R=(b?u:-u)+5*W(-1,1),w=ct(R),E=lt(R),A=g.x-x.x,M=g.y-x.y,T=w*A+E*M,S=w*M-E*A,P=h[~~(W(0,1)*f)]*W(.65,1.35)*_,C=y+m[~~(W(0,1)*d)];c[p]=y,l[p]=b,p++,o[v]=x.x+.5*A+T*P,s[v]=x.y+.5*M+S*P,c[p]=C,l[p]=b,p++,v++}if(Tn&&p>Tn){const t=Math.ceil(p/Tn),r=Math.ceil(p/t);x=new Array(r),g=new Array(r),y=new Array(r);let n=0;for(let r=0;r<p;r+=t,n++)x[n]=r%2==0?e[r>>1]:{x:o[r>>1],y:s[r>>1]},g[n]=c[r],y[n]=l[r]}else{x=new Array(p);for(let t=0;t<p;t++)x[t]=t%2==0?e[t>>1]:{x:o[t>>1],y:s[t>>1]};g=c.slice(0,p),y=l.slice(0,p)}return new Zn(x,g,this.midP,y,!1,this.sizeX,this.sizeY)}fill(t,n,a){const o=3*a,s=2*n*(1+a/2),l=!1!==P.isBrush;P.isBrush=!1,l&&(P.justChanged=!0),P.blend(t);const u=c();P.ctx.save(),P.ctx.setTransform(i*u.a,i*u.b,i*u.c,i*u.d,i*(u.x+e/2),i*(u.y+r/2));const h=`rgb(${t._getRed()} ${t._getGreen()} ${t._getBlue()} / `;P.ctx.strokeStyle=h+.005*T.fill.border_strength+")",P.ctx.lineCap="round",Tn=2024*Math.max(.1,2*T.fill.bleed_strength);const f=P.ctx.getTransform(),m=Math.max(this.sizeX,this.sizeY),d=W(.15,.7);let x=this.grow();const g=this.scatter(.1).grow().scatter(.75).flipDirs();let y;for(let e=0;e<20;e++){e%4==0&&(x=x.grow()),e%2==0&&(y=[x.grow(1-.0125*e),x.grow(.7-.0125*e),x.grow(.4-.0125*e)]);for(const t of y)t.grow(999).grow(997).layer(e,m,s,h,f);g.grow(999).flipDirs().grow(997).layer(e,m,s*o,h,f),e%2==0&&x.grow(d).grow(999).layer(e,m,2*s,h,f),e%8!=0&&19!==e||(0!==o&&x.erase(3*o,n),P.blend(t,!0))}P.ctx.restore()}layer(t,e,r,n,i=null){P.ctx.lineWidth=et(t,0,24,e/25,e/30,!0),P.ctx.fillStyle=n+r+"%)",function(t,e=null){const r=P.ctx;e||(e=r.getTransform());const n=e.a,i=e.b,a=e.c,o=e.d,s=e.e,c=e.f;let l=Infinity,u=Infinity,h=-Infinity,f=-Infinity;r.beginPath();const m=t[0];let d=n*m.x+a*m.y+s,x=i*m.x+o*m.y+c;l=h=d,u=f=x,r.moveTo(m.x,m.y);for(let e=1;e<t.length;e++){const m=t[e];d=n*m.x+a*m.y+s,x=i*m.x+o*m.y+c,l=Math.min(l,d),u=Math.min(u,x),h=Math.max(h,d),f=Math.max(f,x),r.lineTo(m.x,m.y)}r.closePath();const g=function(t,e){const r=t.lineWidth||0;return r<=0?1:1+r*Math.max(Math.hypot(e.a,e.c),Math.hypot(e.b,e.d))/2}(r,e);P.markDirtyRect(P.mask,{minX:l-g,minY:u-g,maxX:h+g,maxY:f+g})}(this.v,i),P.ctx.fill(),P.ctx.stroke()}erase(t,e){P.ctx.save();const r=~~(W(80,110)*et(t,0,1,2,3.5)),n=this.sizeX/1.3,i=this.sizeY/1.3,a=1.3*Math.min(this.sizeX,this.sizeY),o=.03*a,s=.45*a,{x:c,y:l}=this.midP;P.ctx.globalCompositeOperation="destination-out";const u=(5-et(e,80,100,.3,.7,!0))*t/255;P.ctx.fillStyle=`rgb(255 0 0 / ${u})`,P.ctx.lineWidth=0;for(let t=0;t<r;t++){const e=c+Q(0,n),r=l+Q(0,i),a=W(o,s);P.ctx.beginPath(),En(e,r,a),t%5!=0&&P.ctx.fill()}P.ctx.globalCompositeOperation="source-over",P.ctx.restore()}}function Vn(t,e){if(!t)return t;e||(e=t);let r,n=t;do{if(r=!1,n.steiner||!ei(n,n.next)&&0!==ti(n.prev,n,n.next))n=n.next;else{if(ci(n),n=e=n.prev,n===n.next)break;r=!0}}while(r||n!==e);return e}function Hn(t,e,r,n,i,a,o){if(!t)return;!o&&a&&function(t,e,r,n){let i=t;do{0===i.z&&(i.z=Kn(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){let e,r=1;do{let n,i=t;t=null;let a=null;for(e=0;i;){e++;let o=i,s=0;for(let t=0;t<r&&(s++,o=o.nextZ,o);t++);let c=r;for(;s>0||c>0&&o;)0!==s&&(0===c||!o||i.z<=o.z)?(n=i,i=i.nextZ,s--):(n=o,o=o.nextZ,c--),a?a.nextZ=n:t=n,n.prevZ=a,a=n;i=o}a.nextZ=null,r*=2}while(e>1)}(i)}(t,n,i,a);let s=t;for(;t.prev!==t.next;){const c=t.prev,l=t.next;if(a?Wn(t,n,i,a):$n(t))e.push(c.i,t.i,l.i),ci(t),t=l.next,s=l.next;else if((t=l)===s){o?1===o?Hn(t=qn(Vn(t),e),e,r,n,i,a,2):2===o&&jn(t,e,r,n,i,a):Hn(Vn(t),e,r,n,i,a,1);break}}}function $n(t){const e=t.prev,r=t,n=t.next;if(ti(e,r,n)>=0)return!1;const i=e.x,a=r.x,o=n.x,s=e.y,c=r.y,l=n.y,u=Math.min(i,a,o),h=Math.min(s,c,l),f=Math.max(i,a,o),m=Math.max(s,c,l);let d=n.next;for(;d!==e;){if(d.x>=u&&d.x<=f&&d.y>=h&&d.y<=m&&Jn(i,s,a,c,o,l,d.x,d.y)&&ti(d.prev,d,d.next)>=0)return!1;d=d.next}return!0}function Wn(t,e,r,n){const i=t.prev,a=t,o=t.next;if(ti(i,a,o)>=0)return!1;const s=i.x,c=a.x,l=o.x,u=i.y,h=a.y,f=o.y,m=Math.min(s,c,l),d=Math.min(u,h,f),x=Math.max(s,c,l),g=Math.max(u,h,f),y=Kn(m,d,e,r,n),p=Kn(x,g,e,r,n);let v=t.prevZ,_=t.nextZ;for(;v&&v.z>=y&&_&&_.z<=p;){if(v.x>=m&&v.x<=x&&v.y>=d&&v.y<=g&&v!==i&&v!==o&&Jn(s,u,c,h,l,f,v.x,v.y)&&ti(v.prev,v,v.next)>=0)return!1;if(v=v.prevZ,_.x>=m&&_.x<=x&&_.y>=d&&_.y<=g&&_!==i&&_!==o&&Jn(s,u,c,h,l,f,_.x,_.y)&&ti(_.prev,_,_.next)>=0)return!1;_=_.nextZ}for(;v&&v.z>=y;){if(v.x>=m&&v.x<=x&&v.y>=d&&v.y<=g&&v!==i&&v!==o&&Jn(s,u,c,h,l,f,v.x,v.y)&&ti(v.prev,v,v.next)>=0)return!1;v=v.prevZ}for(;_&&_.z<=p;){if(_.x>=m&&_.x<=x&&_.y>=d&&_.y<=g&&_!==i&&_!==o&&Jn(s,u,c,h,l,f,_.x,_.y)&&ti(_.prev,_,_.next)>=0)return!1;_=_.nextZ}return!0}function qn(t,e){let r=t;do{const n=r.prev,i=r.next.next;!ei(n,i)&&ri(n,r,r.next,i)&&ai(n,i)&&ai(i,n)&&(e.push(n.i,r.i,i.i),ci(r),ci(r.next),r=t=i),r=r.next}while(r!==t);return Vn(r)}function jn(t,e,r,n,i,a){let o=t;do{let t=o.next.next;for(;t!==o.prev;){if(o.i!==t.i&&Qn(o,t)){let s=oi(o,t);return o=Vn(o,o.next),s=Vn(s,s.next),Hn(o,e,r,n,i,a,0),void Hn(s,e,r,n,i,a,0)}t=t.next}o=o.next}while(o!==t)}function Kn(t,e,r,n,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function Jn(t,e,r,n,i,a,o,s){return!(t===o&&e===s)&&function(t,e,r,n,i,a,o,s){return(i-o)*(e-s)>=(t-o)*(a-s)&&(t-o)*(n-s)>=(r-o)*(e-s)&&(r-o)*(a-s)>=(i-o)*(n-s)}(t,e,r,n,i,a,o,s)}function Qn(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&ri(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}(t,e)&&(ai(t,e)&&ai(e,t)&&function(t,e){let r=t,n=!1;const i=(t.x+e.x)/2,a=(t.y+e.y)/2;do{r.y>a!=r.next.y>a&&r.next.y!==r.y&&i<(r.next.x-r.x)*(a-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}(t,e)&&(ti(t.prev,t,e.prev)||ti(t,e.prev,e))||ei(t,e)&&ti(t.prev,t,t.next)>0&&ti(e.prev,e,e.next)>0)}function ti(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function ei(t,e){return t.x===e.x&&t.y===e.y}function ri(t,e,r,n){const i=ii(ti(t,e,r)),a=ii(ti(t,e,n)),o=ii(ti(r,n,t)),s=ii(ti(r,n,e));return i!==a&&o!==s||!(0!==i||!ni(t,r,e))||!(0!==a||!ni(t,n,e))||!(0!==o||!ni(r,t,n))||!(0!==s||!ni(r,e,n))}function ni(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function ii(t){return t>0?1:t<0?-1:0}function ai(t,e){return ti(t.prev,t,t.next)<0?ti(t,e,t.next)>=0&&ti(t,t.prev,e)>=0:ti(t,e,t.prev)<0||ti(t,t.next,e)<0}function oi(t,e){const r=li(t.i,t.x,t.y),n=li(e.i,e.x,e.y),i=t.next,a=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,a.next=n,n.prev=a,n}function si(t,e,r,n){const i=li(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function ci(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function li(t,e,r){return{i:t,x:e,y:r,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}fe.prototype.fill=function(t=!1,e,r,n,i,a){let o=kn();t&&(In(t,e),Dn(r,a),Ln(n,i)),o.isActive&&(yt(),function(t){if(!T.fill.isActive||!T.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");Bn=t,Un=Infinity,Yn=Infinity,zn=-Infinity,On=-Infinity;for(const[e]of t.sides)e.x<Un&&(Un=e.x),e.x>zn&&(zn=e.x),e.y<Yn&&(Yn=e.y),e.y>On&&(On=e.y);const e=[...t.vertices],r=W(0,75),n=~~(.25*e.length*(r<5?1:r<15?2:3)),i=T.fill.bleed_strength,a=e.map((t,e)=>(e>n?1:.3)*W(.85,1.4)*i),o=K(0,e.length),s=e.length,c=new Array(s);for(let t=0;t<s;t++)c[t]=e[(t+o)%s];const l=function(t){if(0===t.length)return{x:0,y:0};if(t.length<8){let e=0,r=0;for(const n of t)e+=n.x,r+=n.y;return{x:e/t.length,y:r/t.length}}const e=[...t];e[0].x===e[e.length-1].x&&e[0].y===e[e.length-1].y||e.push(e[0]);let r=0,n=0,i=0;for(let t=0;t<e.length-1;t++){const a=e[t].x*e[t+1].y-e[t+1].x*e[t].y;r+=a,n+=(e[t].x+e[t+1].x)*a,i+=(e[t].y+e[t+1].y)*a}return r*=.5,r?{x:n/(6*r),y:i/(6*r)}:{x:e[0].x,y:e[0].y}}(c);new Zn(c,a,l,[],!0).fill(T.fill.color,et(T.fill.opacity,0,255,0,1,!0),T.fill.texture_strength)}(this)),(t=>{T.fill={...t}})(o)},me.prototype.fill=function(t,e,r){kn().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,T.fill.bleed_strength<.06?0:et(T.fill.bleed_strength,0,.6,.2,.6,!0)),this.pol.fill())};let ui=null,hi=null,fi=null,mi=null,di=null,xi=0,gi=0,yi=0;const pi={},vi={};function _i(t,e,r,n){h(),T.wash.opacity=(arguments.length<4?e:n)??150,T.wash.color=arguments.length<3?s(t):s(t,e,r),T.wash.isActive=!0}function bi(){T.wash.isActive=!1}function Ri(t,e){const r=c();return[r.a*t+r.c*e+r.x+xi/2,r.b*t+r.d*e+r.y+gi/2]}function wi(t,e,r){const n=e.isEnabled(e.DEPTH_TEST);return n&&e.disable(e.DEPTH_TEST),e.bindFramebuffer(e.FRAMEBUFFER,r.framebuffer),e.viewport(0,0,r.width*r.density,r.height*r.density),{hadDepthTest:n}}function Ei(t,n,a){a?.hadDepthTest&&n.enable(n.DEPTH_TEST),n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,Math.max(1,Math.round(e*i)),Math.max(1,Math.round(r*i)))}function Ai(t,e){e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,null),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA)}function Mi(t,e,r){if(!e)return;if(r(e)){const r=t.drawingContext,n=r.getParameter(r.FRAMEBUFFER_BINDING),i=r.getParameter(r.VIEWPORT);return r.bindFramebuffer(r.FRAMEBUFFER,e.framebuffer),r.viewport(0,0,e.width*e.density,e.height*e.density),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.bindFramebuffer(r.FRAMEBUFFER,n),void r.viewport(i[0],i[1],i[2],i[3])}const n=e.drawingContext;n.save(),n.setTransform(1,0,0,1,0,0),n.clearRect(0,0,e.width,e.height),n.restore()}function Ti(t,e,r){return t.shaderProgram??=function(t,e,r){const n=Pe(t,e,r),i=new Map,a=t.createVertexArray(),o=t.getUniformLocation(n,"u_source"),s=t.getUniformLocation(n,"u_mask"),c=t.getUniformLocation(n,"u_color");return{program:n,quadVao:a,loc_source:o,loc_mask:s,loc_color:c,setUniform(e,r){const a=(e=>(i.has(e)||i.set(e,t.getUniformLocation(n,e)),i.get(e)))(e);a&&("boolean"!=typeof r?"number"!=typeof r?Array.isArray(r)&&(3===r.length?t.uniform3f(a,r[0],r[1],r[2]):4===r.length&&t.uniform4f(a,r[0],r[1],r[2],r[3])):t.uniform1f(a,r):t.uniform1i(a,r?1:0))}}}(t.drawingContext,e,r),t.shaderProgram}function Si(t,e){const r=t.drawingContext,n=e.density??1,i=r.createFramebuffer(),a=Math.max(1,e.width),o=Math.max(1,e.height),s=Math.max(1,Math.round(a*n)),c=Math.max(1,Math.round(o*n)),l=function(t,e,r){const n=t.createTexture();return t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,r,0,t.RGBA,t.UNSIGNED_BYTE,null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.bindTexture(t.TEXTURE_2D,null),n}(r,s,c);return r.bindFramebuffer(r.FRAMEBUFFER,i),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,l,0),r.bindFramebuffer(r.FRAMEBUFFER,null),{__brushFramebuffer:!0,framebuffer:i,colorTexture:l,width:a,height:o,density:n,pixelDensity:()=>n,remove(){r.deleteFramebuffer(i),r.deleteTexture(l)}}}function Pi(t,e,r,n,i){return e?.remove?.(),Si(t,{width:r,height:n,density:i})}function Ci({renderer:t,shader:e,source:r,mask:n,color:i,isBrushMask:a,dirtyRect:o,targetIsFramebuffer:s,withScissor:c}){const l=t.drawingContext,u=l.isEnabled(l.DEPTH_TEST),h=l.getParameter(l.FRAMEBUFFER_BINDING),f=l.getParameter(l.CURRENT_PROGRAM),m=l.getParameter(l.VERTEX_ARRAY_BINDING);l.bindVertexArray(e.quadVao),l.useProgram(e.program),l.disable(l.DEPTH_TEST),l.enable(l.BLEND),l.blendEquation(l.FUNC_ADD),l.blendFunc(l.ONE,l.ONE_MINUS_SRC_ALPHA),l.activeTexture(l.TEXTURE0),l.bindTexture(l.TEXTURE_2D,r.colorTexture),l.uniform1i(e.loc_source,0),l.activeTexture(l.TEXTURE1),l.bindTexture(l.TEXTURE_2D,n.colorTexture),l.uniform1i(e.loc_mask,1),e.setUniform("u_targetIsFramebuffer",s),e.setUniform("u_isBrush",a),l.uniform3f(e.loc_color,i[0],i[1],i[2]),l.bindFramebuffer(l.FRAMEBUFFER,null),c(l,o,()=>{l.drawArrays(l.TRIANGLES,0,3)},!s),l.bindTexture(l.TEXTURE_2D,null),l.activeTexture(l.TEXTURE0),l.bindVertexArray(m),l.useProgram(f),l.bindFramebuffer(l.FRAMEBUFFER,h),u&&l.enable(l.DEPTH_TEST)}function Fi(t){return function({renderer:t,sourceFramebuffer:e,dirtyRect:r,getTargetPixelSize:n,toScissorBox:i}){const a=t.drawingContext,{width:o,height:s}=n(),c=r?i(r):null,l=a.getParameter(a.READ_FRAMEBUFFER_BINDING),u=a.getParameter(a.DRAW_FRAMEBUFFER_BINDING);return a.bindFramebuffer(a.READ_FRAMEBUFFER,null),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,e.framebuffer),a.blitFramebuffer(c?.x??0,c?.y??0,c?c.x+c.width:o,c?c.y+c.height:s,c?.x??0,c?.y??0,c?c.x+c.width:o,c?c.y+c.height:s,a.COLOR_BUFFER_BIT,a.NEAREST),a.bindFramebuffer(a.READ_FRAMEBUFFER,l),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,u),e}(t)}function ki(t){if("number"==typeof t){const e=Math.max(0,Math.min(255,t));return`rgb(${e} ${e} ${e})`}return t??"black"}function Ii(t){const e=((t,e=!1)=>(t.drawingContext??=t.getContext("2d",e?{willReadFrequently:!0}:void 0),t.drawingContext))(t,!0),r={canvas:t,drawingContext:e,width:t.width,height:t.height,pixels:null,_fillStyle:"#ffffff",_strokeStyle:"transparent",_lineWidth:1,pixelDensity:()=>1,background(r){e.save(),e.setTransform(1,0,0,1,0,0),e.fillStyle=ki(r),e.fillRect(0,0,t.width,t.height),e.restore()},noSmooth(){e.imageSmoothingEnabled=!1},push(){e.save()},pop(){e.restore()},translate(t,r){e.translate(t,r)},scale(t,r=t){e.scale(t,r)},rotate(t){e.rotate(t)},noStroke(){r._strokeStyle="transparent"},stroke(t){r._strokeStyle=ki(t)},noFill(){r._fillStyle="transparent"},fill(t){r._fillStyle=ki(t)},strokeWeight(t){r._lineWidth=t},rect(t,n,i,a){e.beginPath(),e.rect(t,n,i,a),r._paint()},circle(t,n,i){e.beginPath(),e.arc(t,n,i/2,0,2*Math.PI),r._paint()},ellipse(t,n,i,a){e.beginPath(),e.ellipse(t,n,i/2,a/2,0,0,2*Math.PI),r._paint()},line(t,n,i,a){e.beginPath(),e.moveTo(t,n),e.lineTo(i,a),e.strokeStyle=r._strokeStyle,e.lineWidth=r._lineWidth,e.stroke()},beginShape(){e.beginPath(),r._shapeStarted=!1},vertex(t,n){r._shapeStarted?e.lineTo(t,n):(e.moveTo(t,n),r._shapeStarted=!0)},endShape(t=!1){t&&e.closePath(),r._paint()},loadPixels(){r.pixels=e.getImageData(0,0,t.width,t.height).data},updatePixels(){const n=e.getImageData(0,0,t.width,t.height);n.data.set(r.pixels),e.putImageData(n,0,0)},_paint(){"transparent"!==r._fillStyle&&(e.fillStyle=r._fillStyle,e.fill()),"transparent"!==r._strokeStyle&&(e.strokeStyle=r._strokeStyle,e.lineWidth=r._lineWidth,e.stroke())}};return r}function Di(t,e){return Ii(g(t,e,!0))}function Li(t,e){return new Promise((r,n)=>{const i=globalThis.Image;if(!i)return void n(new Error("Standalone image brush loading requires Image support."));const a=new i;a.onload=()=>{const t=Ii(g(a.naturalWidth,a.naturalHeight,!0));t.drawingContext.drawImage(a,0,0),e(t),r(t)},a.onerror=()=>n(new Error(`Failed to load image tip: ${t}`)),a.crossOrigin="anonymous",a.src=t})}var Ni;T.wash={color:null,opacity:150,isActive:!1},fe.prototype.wash=function(t=!1,i){const a={...T.wash};!1!==t&&_i(t,i),T.wash.isActive&&function(t){if(!T.wash?.isActive||!T.wash.color||t.vertices.length<3)return;C(),function(){const t=n.drawingContext;di&&!(xi!==e||gi!==r)||(xi=e,gi=r,di=new Float32Array([2/xi,0,0,0,0,-2/gi,0,0,0,0,1,0,-1,1,0,1])),ui===t&&hi&&fi&&mi||(ui=t,hi=Pe(ui,"#version 300 es\nin vec2 a_position;\nuniform mat4 u_matrix;\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n}","#version 300 es\nprecision highp float;\nuniform vec4 u_color;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(u_color.rgb * u_color.a, u_color.a);\n}"),pi.a_position=ui.getAttribLocation(hi,"a_position"),vi.u_matrix=ui.getUniformLocation(hi,"u_matrix"),vi.u_color=ui.getUniformLocation(hi,"u_color"),fi=ui.createVertexArray(),ui.bindVertexArray(fi),mi=ui.createBuffer(),ui.bindBuffer(ui.ARRAY_BUFFER,mi),ui.bufferData(ui.ARRAY_BUFFER,0,ui.DYNAMIC_DRAW),yi=0,ui.enableVertexAttribArray(pi.a_position),ui.vertexAttribPointer(pi.a_position,2,ui.FLOAT,!1,8,0),ui.bindVertexArray(null),ui.bindBuffer(ui.ARRAY_BUFFER,null))}();const{triangles:i,vertexCount:a}=function(t){const e=new Float32Array(2*t.vertices.length);for(let r=0;r<t.vertices.length;r++){const n=t.vertices[r];e[2*r]=n.x,e[2*r+1]=n.y}const r=function(t,e,r=2){const n=t.length;let i=function(t,e,r,n){let i;if(1==function(t,e,r,n){let i=0;for(let e=0,a=r-n;e<r;e+=n)i+=(t[a]-t[e])*(t[e+1]+t[a+1]),a=e;return i}(t,0,r,n)>0)for(let e=0;e<r;e+=n)i=si(e/n|0,t[e],t[e+1],i);else for(let e=r-n;e>=0;e-=n)i=si(e/n|0,t[e],t[e+1],i);return i&&ei(i,i.next)&&(ci(i),i=i.next),i}(t,0,n,r);const a=[];if(!i||i.next===i.prev)return a;let o,s,c;if(t.length>80*r){o=t[0],s=t[1];let e=o,i=s;for(let a=r;a<n;a+=r){const r=t[a],n=t[a+1];r<o&&(o=r),n<s&&(s=n),r>e&&(e=r),n>i&&(i=n)}c=Math.max(e-o,i-s),c=0!==c?32767/c:0}return Hn(i,a,r,o,s,c,0),a}(e),n=new Float32Array(2*r.length);for(let t=0;t<r.length;t++){const i=r[t],[a,o]=Ri(e[2*i],e[2*i+1]);n[2*t]=a,n[2*t+1]=o}return{triangles:n,vertexCount:r.length}}(t),o=i.byteLength;ui.useProgram(hi),ui.enable(ui.BLEND),ui.blendEquation(ui.FUNC_ADD),ui.blendFunc(ui.ONE,ui.ONE_MINUS_SRC_ALPHA),ui.bindVertexArray(fi),ui.bindBuffer(ui.ARRAY_BUFFER,mi),o>yi?(ui.bufferData(ui.ARRAY_BUFFER,i,ui.DYNAMIC_DRAW),yi=o):ui.bufferSubData(ui.ARRAY_BUFFER,0,i);const s=T.wash.color._array;ui.uniformMatrix4fv(vi.u_matrix,!1,di),ui.uniform4f(vi.u_color,s[0],s[1],s[2],T.wash.opacity/255),ui.drawArrays(ui.TRIANGLES,0,a),ui.bindVertexArray(null),ui.bindBuffer(ui.ARRAY_BUFFER,null),Fe(n,ui)}(this),T.wash={...a}},me.prototype.wash=function(t,e,r){T.wash?.isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,0,-1),this.pol.wash())},Ni={load:function(t=ae){if(!function(t){return function(t){return"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement}(t)||function(t){return"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas}(t)}(t))throw new Error("Standalone brush.load(target) requires an HTMLCanvasElement or OffscreenCanvas.");ue(t,t.width,t.height,1)},syncDensity:function(){return u({Cwidth:ce,Cheight:le,Density:se}),se},isCanvasReady:function(){if(!oe)throw new Error("No standalone target loaded. Call brush.load(canvasOrOffscreenCanvas) first.")},instance:function(){},activateInstance:function(){},deactivateInstance:function(){},getActiveFramebuffer:function(){return null},isFramebufferTarget:function(){return!0===arguments[0]?.__brushFramebuffer}},l={...l,...Ni},Jt(),function(){var t;t={beginDirectMaskDraw:wi,endDirectMaskDraw:Ei,resetDirectShaderTracking:Ai},Ce={...Ce,...t}}(),function(){var t;t={clearTarget:Mi,ensureBlendShaderProgram:Ti,ensureBlendSourceFramebuffer:Pi,createFramebuffer:Si,runBlendShaderPass:Ci,blitSourceToFramebuffer:Fi},y={...y,...t}}(),function(){var t;t={createTipSurface:Di,loadImageTip:Li},Te={...Te,...t}}();export{Zt as Color,Bt as DEGREES,me as Plot,fe as Polygon,pt as Position,Ut as RADIANS,Tr as add,Ft as addField,Vt as angleMode,ye as arc,ve as beginShape,Re as beginStroke,Sr as box,ge as circle,te as clear,Nr as clip,he as createCanvas,be as endShape,Ee as endStroke,Pt as field,In as fill,Dn as fillBleed,Ln as fillTexture,rn as flowLine,Ht as getAngleMode,ln as hatch,dn as hatchArray,un as hatchStyle,Jt as initStandaloneRuntime,f as instance,en as line,kt as listFields,F as load,xn as mass,we as move,Br as noClip,Ct as noField,Nn as noFill,hn as noHatch,gn as noMass,Lr as noStroke,bi as noWash,$ as noiseSeed,Fr as pick,de as polygon,Wt as pop,$t as push,xe as rect,St as refreshField,Qt as render,jt as rotate,Kt as scale,Cr as scaleBrushes,Z as seed,Dr as set,Ae as spline,kr as stroke,Ir as strokeWeight,qt as translate,_e as vertex,tt as wRand,_i as wash,It as wiggle};
//# sourceMappingURL=brush.esm.js.map
diff --git a/dist/brush.esm.js.map b/dist/brush.esm.js.map
index c1800e1..4f9c7b4 100644
--- a/dist/brush.esm.js.map
+++ b/dist/brush.esm.js.map
@@ -1 +1 @@
-{"version":3,"file":"brush.esm.js","sources":["../src/core/runtime.js","../src/core/target.js","../src/core/dirty_rect.js","../src/core/compositor_runtime.js","../src/core/color.js","../node_modules/simplex-noise/dist/esm/simplex-noise.js","../node_modules/esm-seedrandom/esm/index.mjs","../src/core/utils.js","../src/core/flowfield.js","../src/core/save.js","../src/adapters/standalone/runtime.js","../src/adapters/standalone/frame.js","../src/adapters/standalone/target.js","../src/core/primitives.js","../src/core/polygon.js","../src/core/plot.js","../src/stroke/runtime.js","../src/stroke/composite.js","../src/core/gl/utils.js","../src/core/renderer_runtime.js","../src/stroke/gl_draw.js","../src/stroke/stroke.js","../src/hatch/hatch.js","../src/hatch/mass.js","../src/fill/mask.js","../src/fill/composite.js","../src/fill/fill.js","../node_modules/earcut/src/earcut.js","../src/fill/wash.js","../src/adapters/standalone/renderer.js","../src/adapters/standalone/compositor.js","../src/adapters/standalone/stroke.js","../src/index.standalone.js"],"sourcesContent":["// =============================================================================\n// Runtime Hooks\n// =============================================================================\n\nconst identityMatrix = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\n\nexport let usesRadians = () => false;\nexport let fromDegrees = (angle) => angle;\nexport let createColor = () => {\n throw new Error(\"No runtime color adapter registered.\");\n};\nexport let getAffineMatrix = () => identityMatrix;\n\n/**\n * Registers or updates host-runtime hooks used by core modules.\n *\n * @param {object} hooks\n */\nexport function setRuntime(hooks) {\n if (hooks.usesRadians) usesRadians = hooks.usesRadians;\n if (hooks.fromDegrees) fromDegrees = hooks.fromDegrees;\n if (hooks.createColor) createColor = hooks.createColor;\n if (hooks.getAffineMatrix) getAffineMatrix = hooks.getAffineMatrix;\n}\n","// =============================================================================\n// Target Runtime Hooks\n// =============================================================================\n\n/**\n * Shared target state exposed to core modules.\n *\n * Host adapters are expected to keep these bindings updated with the currently\n * active drawing target. The exact object type is adapter-defined, but core code\n * assumes the active renderer exposes:\n * - `drawingContext`: the active WebGL context\n * - target dimensions through `Cwidth` / `Cheight`\n * - pixel density through `Density`\n */\n\nexport let Cwidth, Cheight, Instance, Renderer, Density;\n\nlet targetRuntime = {\n load: () => {\n throw new Error(\"No target runtime adapter registered.\");\n },\n syncDensity: () => Density,\n isCanvasReady: () => {\n throw new Error(\"No target runtime adapter registered.\");\n },\n instance: (inst) => {\n Instance = inst;\n },\n activateInstance: (inst) => {\n Instance = inst;\n },\n deactivateInstance: () => {},\n getActiveFramebuffer: () => null,\n isFramebufferTarget: () => false,\n};\n\n/**\n * Updates the shared target state consumed by core modules.\n *\n * @param {object} state\n */\nexport function setTargetState(state) {\n if (\"Cwidth\" in state) Cwidth = state.Cwidth;\n if (\"Cheight\" in state) Cheight = state.Cheight;\n if (\"Instance\" in state) Instance = state.Instance;\n if (\"Renderer\" in state) Renderer = state.Renderer;\n if (\"Density\" in state) Density = state.Density;\n}\n\n/**\n * Registers or updates host target hooks used by core modules.\n *\n * @param {object} hooks\n */\nexport function setTargetRuntime(hooks) {\n targetRuntime = { ...targetRuntime, ...hooks };\n}\n\nexport const load = (buffer = false) => targetRuntime.load(buffer);\nexport const syncDensity = () => targetRuntime.syncDensity();\nexport const isCanvasReady = () => targetRuntime.isCanvasReady();\nexport const instance = (inst) => targetRuntime.instance(inst);\nexport const activateInstance = (inst) => targetRuntime.activateInstance(inst);\nexport const deactivateInstance = () => targetRuntime.deactivateInstance();\nexport const getActiveFramebuffer = () => targetRuntime.getActiveFramebuffer();\nexport const isFramebufferTarget = (target) =>\n targetRuntime.isFramebufferTarget(target);\n","// =============================================================================\n// Module: Dirty Rect Utilities\n// =============================================================================\n/**\n * Expands a dirty rectangle outward by a constant padding value.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Rect to expand.\n * @param {number} [padding=0] - Padding in pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Expanded rect.\n */\nexport const expandDirtyRect = (rect, padding = 0) =>\n rect\n ? {\n minX: rect.minX - padding,\n minY: rect.minY - padding,\n maxX: rect.maxX + padding,\n maxY: rect.maxY + padding,\n }\n : null;\n\n/**\n * Clamps a dirty rectangle to explicit target bounds.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Candidate rect.\n * @param {number} width - Target width in physical pixels.\n * @param {number} height - Target height in physical pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Clamped rect.\n */\nexport const normalizeDirtyRect = (rect, width, height) => {\n if (!rect) return null;\n\n const minX = Math.max(0, Math.floor(Math.min(rect.minX, rect.maxX)));\n const minY = Math.max(0, Math.floor(Math.min(rect.minY, rect.maxY)));\n const maxX = Math.min(width, Math.ceil(Math.max(rect.minX, rect.maxX)));\n const maxY = Math.min(height, Math.ceil(Math.max(rect.minY, rect.maxY)));\n\n if (maxX <= minX || maxY <= minY) return null;\n\n return { minX, minY, maxX, maxY };\n};\n\n/**\n * Returns the union of two dirty rectangles.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} a - First rect.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} b - Second rect.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Union rect.\n */\nexport const unionDirtyRect = (a, b) => {\n if (!a) return b;\n if (!b) return a;\n\n return {\n minX: Math.min(a.minX, b.minX),\n minY: Math.min(a.minY, b.minY),\n maxX: Math.max(a.maxX, b.maxX),\n maxY: Math.max(a.maxY, b.maxY),\n };\n};\n\n/**\n * Returns a dirty rectangle covering the full target bounds.\n *\n * @param {number} width - Target width in physical pixels.\n * @param {number} height - Target height in physical pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}} Full-target rect.\n */\nexport const getFullDirtyRect = (width, height) => ({\n minX: 0,\n minY: 0,\n maxX: width,\n maxY: height,\n});\n","// =============================================================================\n// Compositor Runtime Hooks\n// =============================================================================\n\n/**\n * Shared compositor helpers and host hooks.\n *\n * The shared code in this module assumes framebuffer-like targets expose:\n * - `framebuffer`: native WebGL framebuffer handle\n * - optional lifecycle methods supplied by the host adapter\n *\n * Higher-level core modules also attach their own bookkeeping fields onto the\n * active renderer and mask targets, such as:\n * - `shaderProgram`\n * - `blendSourceFramebuffer`\n * - `glMask`\n * - `fillMaskFramebuffer`\n * - `mask`\n *\n * These are library-level contract fields, not host-specific internals.\n */\n\nexport const create2DCanvas = (width, height, willReadFrequently = false) => {\n const canvas =\n typeof OffscreenCanvas !== \"undefined\"\n ? new OffscreenCanvas(width, height)\n : (() => {\n const element = document.createElement(\"canvas\");\n element.width = width;\n element.height = height;\n return element;\n })();\n canvas.drawingContext = canvas.getContext(\n \"2d\",\n willReadFrequently ? { willReadFrequently: true } : undefined,\n );\n return canvas;\n};\n\nexport const get2DContext = (canvas, willReadFrequently = false) => {\n canvas.drawingContext ??= canvas.getContext(\n \"2d\",\n willReadFrequently ? { willReadFrequently: true } : undefined,\n );\n return canvas.drawingContext;\n};\n\nexport function blitDefaultFramebufferSource({\n renderer,\n sourceFramebuffer,\n dirtyRect,\n getTargetPixelSize,\n toScissorBox,\n}) {\n const gl = renderer.drawingContext;\n const { width, height } = getTargetPixelSize();\n const sourceBox = dirtyRect ? toScissorBox(dirtyRect) : null;\n const previousReadFramebuffer = gl.getParameter(gl.READ_FRAMEBUFFER_BINDING);\n const previousDrawFramebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING);\n\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, sourceFramebuffer.framebuffer);\n gl.clearColor(0, 0, 0, 0);\n gl.clear(gl.COLOR_BUFFER_BIT);\n gl.blitFramebuffer(\n sourceBox?.x ?? 0,\n sourceBox?.y ?? 0,\n sourceBox ? sourceBox.x + sourceBox.width : width,\n sourceBox ? sourceBox.y + sourceBox.height : height,\n sourceBox?.x ?? 0,\n sourceBox?.y ?? 0,\n sourceBox ? sourceBox.x + sourceBox.width : width,\n sourceBox ? sourceBox.y + sourceBox.height : height,\n gl.COLOR_BUFFER_BIT,\n gl.NEAREST,\n );\n\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, previousReadFramebuffer);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, previousDrawFramebuffer);\n\n return sourceFramebuffer;\n}\n\nlet compositorRuntime = {\n clearTarget: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n ensureBlendShaderProgram: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n ensureBlendSourceFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n createFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n runBlendShaderPass: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n blitSourceToFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n};\n\n/**\n * Registers or updates host compositor hooks used by core compositing code.\n *\n * @param {object} hooks\n */\nexport function setCompositorRuntime(hooks) {\n compositorRuntime = { ...compositorRuntime, ...hooks };\n}\n\nexport const clearTarget = (...args) => compositorRuntime.clearTarget(...args);\nexport const ensureBlendShaderProgram = (...args) =>\n compositorRuntime.ensureBlendShaderProgram(...args);\nexport const ensureBlendSourceFramebuffer = (...args) =>\n compositorRuntime.ensureBlendSourceFramebuffer(...args);\nexport const createFramebuffer = (...args) =>\n compositorRuntime.createFramebuffer(...args);\nexport const runBlendShaderPass = (...args) =>\n compositorRuntime.runBlendShaderPass(...args);\nexport const blitSourceToFramebuffer = (...args) =>\n compositorRuntime.blitSourceToFramebuffer(...args);\n","import {\n Cwidth,\n Cheight,\n Renderer,\n Density,\n load as loadTarget,\n isCanvasReady,\n syncDensity,\n getActiveFramebuffer,\n isFramebufferTarget,\n} from \"./target.js\";\nimport {\n expandDirtyRect,\n normalizeDirtyRect as clampDirtyRect,\n unionDirtyRect,\n getFullDirtyRect as getFullRect,\n} from \"./dirty_rect.js\";\nimport {\n clearTarget as clearRenderTarget,\n ensureBlendShaderProgram,\n ensureBlendSourceFramebuffer,\n runBlendShaderPass,\n blitSourceToFramebuffer,\n} from \"./compositor_runtime.js\";\n\nimport vertSrc from \"./gl/shader.vert\";\nimport fragSrc from \"./gl/shader.frag\";\n\n// =============================================================================\n// Module: Configure and Initiate\n// =============================================================================\n/**\n * This module handles the configuration and initialization of the drawing system.\n * It manages canvas properties, ensures the system is ready for rendering, and\n * provides utilities for saving and restoring states.\n */\n\nlet strokeComposite = null;\nlet fillComposite = null;\n\nexport const registerStrokeComposite = (composite) => {\n strokeComposite = composite;\n};\n\nexport const registerFillComposite = (composite) => {\n fillComposite = composite;\n};\n\nconst clearTarget = (target) => {\n clearRenderTarget(Renderer, target, isFramebufferTarget);\n};\n\n// =============================================================================\n// Section: Dirty Rect Utilities\n// =============================================================================\n/**\n * Returns the current render target size in physical pixels.\n * @returns {{width: number, height: number}} Pixel size of the active target.\n */\nconst getTargetPixelSize = () => ({\n width: Math.max(1, Math.round(Cwidth * Density)),\n height: Math.max(1, Math.round(Cheight * Density)),\n});\n\nconst normalizeDirtyRect = (rect) => {\n if (!rect) return null;\n const { width, height } = getTargetPixelSize();\n return clampDirtyRect(rect, width, height);\n};\n\n/**\n * Returns a dirty rectangle covering the full active target.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}} Full-target rect.\n */\nconst getFullDirtyRect = () => {\n const { width, height } = getTargetPixelSize();\n return getFullRect(width, height);\n};\n\n// =============================================================================\n// Section: Scissor Helpers\n// =============================================================================\n/**\n * Converts a top-left-based dirty rectangle into a WebGL scissor box.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Dirty rect.\n * @returns {{x:number,y:number,width:number,height:number}|null} Scissor box or null.\n */\nconst toScissorBox = (rect, flipY = true) => {\n const normalized = normalizeDirtyRect(rect);\n if (!normalized) return null;\n\n const { height } = getTargetPixelSize();\n return {\n x: normalized.minX,\n y: flipY ? height - normalized.maxY : normalized.minY,\n width: normalized.maxX - normalized.minX,\n height: normalized.maxY - normalized.minY,\n };\n};\n\n/**\n * Runs a draw callback with a temporary scissor region.\n * @param {WebGL2RenderingContext} gl - Active WebGL context.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Dirty rect.\n * @param {Function} draw - Draw callback executed under the scissor box.\n */\nconst withScissor = (gl, rect, draw, flipY = true) => {\n const box = toScissorBox(rect, flipY);\n if (!box) {\n draw();\n return;\n }\n\n // Scissor is never nested in this module, so we can set/clear it directly\n // without saving previous GL state.\n gl.enable(gl.SCISSOR_TEST);\n gl.scissor(box.x, box.y, box.width, box.height);\n\n try {\n draw();\n } finally {\n gl.disable(gl.SCISSOR_TEST);\n }\n};\n\n/**\n * Stores the current state of the drawing system.\n * Can be used to save and restore configurations or canvas states.\n */\nexport const State = {};\n/**\n * Handles color blending using WebGL shaders. Implements advanced blending\n * effects based on Kubelka-Munk theory. Relies on spectral.js for blending logic.\n */\n\n// =============================================================================\n// Section: Color Blending / Rendering\n// =============================================================================\n/**\n * Ensures the Mix object is initialized and ready for blending.\n */\nexport const isMixReady = () => {\n if (!Renderer?.loaded) {\n isCanvasReady();\n Mix.load();\n }\n};\n\n/**\n * Manages blending operations with WebGL shaders.\n * @property {boolean} loaded - Indicates if shaders are loaded.\n * @property {boolean} isBlending - Indicates if blending is active.\n * @property {object} currentColor - Current color in WebGL format.\n * @property {function} load - Initializes blending resources.\n * @property {function} blend - Applies blending effects.\n */\nexport const Mix = {\n isBlending: false,\n cachedColor: null,\n\n /**\n * Merges a new dirty rectangle into the target's accumulated draw bounds.\n * @param {object} target - Mask buffer receiving draw output.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Rect to merge.\n */\n markDirtyRect(target, rect) {\n const normalized = normalizeDirtyRect(rect);\n if (!target || !normalized) return;\n target.dirtyRect = unionDirtyRect(target.dirtyRect, normalized);\n target.isDrawn = true;\n },\n\n /**\n * Clears a mask buffer and resets its dirty-rect tracking.\n * @param {object} target - Mask buffer to reset.\n */\n clearMask(target) {\n if (!target) return;\n const composite = target === this.glMask ? strokeComposite : fillComposite;\n composite?.clearMask?.(target, clearTarget);\n },\n\n /**\n * Resolves the region that should be composited back into the destination.\n * @param {object} target - Mask buffer being sampled.\n * @param {boolean} isBrushMask - True when compositing the GL brush mask.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\n getCompositeRect(target, isBrushMask) {\n const composite = isBrushMask ? strokeComposite : fillComposite;\n return composite?.getCompositeRect?.(\n target,\n getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n );\n },\n\n // =============================================================================\n // Section: Setup and load shaders\n // =============================================================================\n /**\n * Ensures the mask buffers and blend shader exist for the current renderer.\n */\n load() {\n syncDensity();\n const needsBlendSourceFramebuffer =\n !Renderer.blendSourceFramebuffer ||\n Renderer.blendSourceFramebuffer.width !== Cwidth ||\n Renderer.blendSourceFramebuffer.height !== Cheight ||\n (typeof Renderer.blendSourceFramebuffer.pixelDensity === \"function\" &&\n Renderer.blendSourceFramebuffer.pixelDensity() !== Density);\n ensureBlendShaderProgram(Renderer, vertSrc, fragSrc);\n\n this.glMask = strokeComposite?.ensureResources?.(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n );\n const fillResources = fillComposite?.ensureResources?.(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n clearTarget,\n ) ?? {\n mask: null,\n ctx: null,\n };\n\n if (needsBlendSourceFramebuffer) {\n Renderer.blendSourceFramebuffer = ensureBlendSourceFramebuffer(\n Renderer,\n Renderer.blendSourceFramebuffer,\n Cwidth,\n Cheight,\n Density,\n );\n }\n\n this.mask = fillResources.mask;\n this.ctx = fillResources.ctx;\n },\n\n // =============================================================================\n // Section: Compositing\n // =============================================================================\n /**\n * Flushes pending mask work when the blend color changes or a frame ends.\n * @param {Color|false} [_color=false] - New blend color.\n * @param {boolean} [_isLast=false] - True when this is the final blend flush.\n */\n blend(_color = false, _isLast = false) {\n isMixReady();\n // Only one mask is \"active\" for the current drawing mode; the other one\n // may still need flushing if the mode just changed mid-frame.\n const isBrushMask = this.isBrush === true;\n const mask = isBrushMask ? this.glMask : this.mask;\n const otherMask = isBrushMask ? this.mask : this.glMask;\n const nextColor = _color?._array;\n const colorChanged =\n !!nextColor &&\n (this.cachedColor?.[0] !== nextColor[0] ||\n this.cachedColor?.[1] !== nextColor[1] ||\n this.cachedColor?.[2] !== nextColor[2] ||\n this.cachedColor?.[3] !== nextColor[3]);\n if (!this.isBlending && nextColor) {\n this.isBlending = true;\n this.cachedColor = nextColor;\n // Reset the brush mask fully at the start of each blend cycle so stale\n // dirty-rect bookkeeping cannot leak an old stroke into the next color.\n this.clearMask(this.glMask);\n }\n\n if (_isLast || colorChanged) {\n if (this.justChanged) {\n this.applyShader(otherMask, !isBrushMask);\n this.justChanged = false;\n }\n if (this.isBlending) {\n this.applyShader(mask, isBrushMask);\n }\n if (nextColor) this.cachedColor = nextColor;\n if (_isLast) {\n this.isBlending = false;\n this.cachedColor = null;\n \n }\n }\n },\n\n /**\n * Runs the blend shader over a mask and composites the result into the active renderer.\n * @param {object} mask - Mask buffer to composite.\n * @param {boolean} isBrushMask - True when compositing the GL brush mask.\n */\n applyShader(mask, isBrushMask) {\n if (!mask?.isDrawn) return;\n\n const dirtyRect = this.getCompositeRect(mask, isBrushMask);\n if (!dirtyRect) {\n this.clearMask(mask);\n return;\n }\n\n const gl = Renderer.drawingContext;\n const shader = Renderer.shaderProgram;\n const activeFramebuffer = getActiveFramebuffer();\n const source = blitSourceToFramebuffer({\n renderer: Renderer,\n sourceTarget: activeFramebuffer ?? Renderer,\n sourceFramebuffer: Renderer.blendSourceFramebuffer,\n dirtyRect,\n isFramebufferTarget,\n Cwidth,\n Cheight,\n getTargetPixelSize,\n toScissorBox,\n withScissor,\n });\n const targetIsFramebuffer = !!activeFramebuffer;\n const composite = isBrushMask ? strokeComposite : fillComposite;\n const shaderMask = composite.getShaderMask(\n Renderer,\n mask,\n dirtyRect,\n normalizeDirtyRect,\n getFullDirtyRect,\n clearTarget,\n );\n\n runBlendShaderPass({\n renderer: Renderer,\n shader,\n source,\n mask: shaderMask,\n color: this.cachedColor,\n isBrushMask,\n Cwidth,\n Cheight,\n dirtyRect,\n targetIsFramebuffer,\n withScissor,\n });\n this.clearMask(mask);\n },\n};\n\n/**\n * Flushes any pending stroke/fill mask work into the current target and resets\n * the shared compositor back to its initial idle state.\n */\nexport const flushActiveComposite = () => {\n isMixReady();\n Mix.blend(false, true);\n Mix.clearMask(Mix.glMask);\n Mix.clearMask(Mix.mask);\n Mix.justChanged = false;\n Mix.isBlending = false;\n Mix.isBrush = null;\n Mix.cachedColor = null;\n};\n\n/**\n * Loads and initializes the drawing target, then refreshes compositing\n * resources if the renderer was already active.\n *\n * @param {object|false} [buffer=false] - Optional offscreen target.\n */\nexport const load = (buffer = false) => {\n loadTarget(buffer);\n if (Renderer.loaded) Mix.load();\n};\n","/*\n * A fast javascript implementation of simplex noise by Jonas Wagner\n\nBased on a speed-improved simplex noise algorithm for 2D, 3D and 4D in Java.\nWhich is based on example code by Stefan Gustavson ([email protected]).\nWith Optimisations by Peter Eastman ([email protected]).\nBetter rank ordering method by Stefan Gustavson in 2012.\n\n Copyright (c) 2024 Jonas Wagner\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n */\n// these __PURE__ comments help uglifyjs with dead code removal\n//\nconst SQRT3 = /*#__PURE__*/ Math.sqrt(3.0);\nconst SQRT5 = /*#__PURE__*/ Math.sqrt(5.0);\nconst F2 = 0.5 * (SQRT3 - 1.0);\nconst G2 = (3.0 - SQRT3) / 6.0;\nconst F3 = 1.0 / 3.0;\nconst G3 = 1.0 / 6.0;\nconst F4 = (SQRT5 - 1.0) / 4.0;\nconst G4 = (5.0 - SQRT5) / 20.0;\n// I'm really not sure why this | 0 (basically a coercion to int)\n// is making this faster but I get ~5 million ops/sec more on the\n// benchmarks across the board or a ~10% speedup.\nconst fastFloor = (x) => Math.floor(x) | 0;\nconst grad2 = /*#__PURE__*/ new Float64Array([1, 1,\n -1, 1,\n 1, -1,\n -1, -1,\n 1, 0,\n -1, 0,\n 1, 0,\n -1, 0,\n 0, 1,\n 0, -1,\n 0, 1,\n 0, -1]);\n// double seems to be faster than single or int's\n// probably because most operations are in double precision\nconst grad3 = /*#__PURE__*/ new Float64Array([1, 1, 0,\n -1, 1, 0,\n 1, -1, 0,\n -1, -1, 0,\n 1, 0, 1,\n -1, 0, 1,\n 1, 0, -1,\n -1, 0, -1,\n 0, 1, 1,\n 0, -1, 1,\n 0, 1, -1,\n 0, -1, -1]);\n// double is a bit quicker here as well\nconst grad4 = /*#__PURE__*/ new Float64Array([0, 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1,\n 0, -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1,\n 1, 0, 1, 1, 1, 0, 1, -1, 1, 0, -1, 1, 1, 0, -1, -1,\n -1, 0, 1, 1, -1, 0, 1, -1, -1, 0, -1, 1, -1, 0, -1, -1,\n 1, 1, 0, 1, 1, 1, 0, -1, 1, -1, 0, 1, 1, -1, 0, -1,\n -1, 1, 0, 1, -1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, -1,\n 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1, 0,\n -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1, 0]);\n/**\n * Creates a 2D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction2D}\n */\nexport function createNoise2D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating this yields a little ~3% performance improvement.\n const permGrad2x = new Float64Array(perm).map(v => grad2[(v % 12) * 2]);\n const permGrad2y = new Float64Array(perm).map(v => grad2[(v % 12) * 2 + 1]);\n return function noise2D(x, y) {\n // if(!isFinite(x) || !isFinite(y)) return 0;\n let n0 = 0; // Noise contributions from the three corners\n let n1 = 0;\n let n2 = 0;\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y) * F2; // Hairy factor for 2D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const t = (i + j) * G2;\n const X0 = i - t; // Unskew the cell origin back to (x,y) space\n const Y0 = j - t;\n const x0 = x - X0; // The x,y distances from the cell origin\n const y0 = y - Y0;\n // For the 2D case, the simplex shape is an equilateral triangle.\n // Determine which simplex we are in.\n let i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords\n if (x0 > y0) {\n i1 = 1;\n j1 = 0;\n } // lower triangle, XY order: (0,0)->(1,0)->(1,1)\n else {\n i1 = 0;\n j1 = 1;\n } // upper triangle, YX order: (0,0)->(0,1)->(1,1)\n // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and\n // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where\n // c = (3-sqrt(3))/6\n const x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords\n const y1 = y0 - j1 + G2;\n const x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords\n const y2 = y0 - 1.0 + 2.0 * G2;\n // Work out the hashed gradient indices of the three simplex corners\n const ii = i & 255;\n const jj = j & 255;\n // Calculate the contribution from the three corners\n let t0 = 0.5 - x0 * x0 - y0 * y0;\n if (t0 >= 0) {\n const gi0 = ii + perm[jj];\n const g0x = permGrad2x[gi0];\n const g0y = permGrad2y[gi0];\n t0 *= t0;\n // n0 = t0 * t0 * (grad2[gi0] * x0 + grad2[gi0 + 1] * y0); // (x,y) of grad3 used for 2D gradient\n n0 = t0 * t0 * (g0x * x0 + g0y * y0);\n }\n let t1 = 0.5 - x1 * x1 - y1 * y1;\n if (t1 >= 0) {\n const gi1 = ii + i1 + perm[jj + j1];\n const g1x = permGrad2x[gi1];\n const g1y = permGrad2y[gi1];\n t1 *= t1;\n // n1 = t1 * t1 * (grad2[gi1] * x1 + grad2[gi1 + 1] * y1);\n n1 = t1 * t1 * (g1x * x1 + g1y * y1);\n }\n let t2 = 0.5 - x2 * x2 - y2 * y2;\n if (t2 >= 0) {\n const gi2 = ii + 1 + perm[jj + 1];\n const g2x = permGrad2x[gi2];\n const g2y = permGrad2y[gi2];\n t2 *= t2;\n // n2 = t2 * t2 * (grad2[gi2] * x2 + grad2[gi2 + 1] * y2);\n n2 = t2 * t2 * (g2x * x2 + g2y * y2);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to return values in the interval [-1,1].\n return 70.0 * (n0 + n1 + n2);\n };\n}\n/**\n * Creates a 3D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction3D}\n */\nexport function createNoise3D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these seems to yield a speedup of over 15%\n const permGrad3x = new Float64Array(perm).map(v => grad3[(v % 12) * 3]);\n const permGrad3y = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 1]);\n const permGrad3z = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 2]);\n return function noise3D(x, y, z) {\n let n0, n1, n2, n3; // Noise contributions from the four corners\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y + z) * F3; // Very nice and simple skew factor for 3D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const t = (i + j + k) * G3;\n const X0 = i - t; // Unskew the cell origin back to (x,y,z) space\n const Y0 = j - t;\n const Z0 = k - t;\n const x0 = x - X0; // The x,y,z distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n // For the 3D case, the simplex shape is a slightly irregular tetrahedron.\n // Determine which simplex we are in.\n let i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords\n let i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords\n if (x0 >= y0) {\n if (y0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // X Y Z order\n else if (x0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // X Z Y order\n else {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // Z X Y order\n }\n else { // x0<y0\n if (y0 < z0) {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Z Y X order\n else if (x0 < z0) {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Y Z X order\n else {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // Y X Z order\n }\n // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),\n // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and\n // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where\n // c = 1/6.\n const x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords\n const y1 = y0 - j1 + G3;\n const z1 = z0 - k1 + G3;\n const x2 = x0 - i2 + 2.0 * G3; // Offsets for third corner in (x,y,z) coords\n const y2 = y0 - j2 + 2.0 * G3;\n const z2 = z0 - k2 + 2.0 * G3;\n const x3 = x0 - 1.0 + 3.0 * G3; // Offsets for last corner in (x,y,z) coords\n const y3 = y0 - 1.0 + 3.0 * G3;\n const z3 = z0 - 1.0 + 3.0 * G3;\n // Work out the hashed gradient indices of the four simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n // Calculate the contribution from the four corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad3x[gi0] * x0 + permGrad3y[gi0] * y0 + permGrad3z[gi0] * z0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad3x[gi1] * x1 + permGrad3y[gi1] * y1 + permGrad3z[gi1] * z1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad3x[gi2] * x2 + permGrad3y[gi2] * y2 + permGrad3z[gi2] * z2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + 1 + perm[jj + 1 + perm[kk + 1]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad3x[gi3] * x3 + permGrad3y[gi3] * y3 + permGrad3z[gi3] * z3);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to stay just inside [-1,1]\n return 32.0 * (n0 + n1 + n2 + n3);\n };\n}\n/**\n * Creates a 4D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction4D}\n */\nexport function createNoise4D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these leads to a ~10% speedup\n const permGrad4x = new Float64Array(perm).map(v => grad4[(v % 32) * 4]);\n const permGrad4y = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 1]);\n const permGrad4z = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 2]);\n const permGrad4w = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 3]);\n return function noise4D(x, y, z, w) {\n let n0, n1, n2, n3, n4; // Noise contributions from the five corners\n // Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in\n const s = (x + y + z + w) * F4; // Factor for 4D skewing\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const l = fastFloor(w + s);\n const t = (i + j + k + l) * G4; // Factor for 4D unskewing\n const X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space\n const Y0 = j - t;\n const Z0 = k - t;\n const W0 = l - t;\n const x0 = x - X0; // The x,y,z,w distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n const w0 = w - W0;\n // For the 4D case, the simplex is a 4D shape I won't even try to describe.\n // To find out which of the 24 possible simplices we're in, we need to\n // determine the magnitude ordering of x0, y0, z0 and w0.\n // Six pair-wise comparisons are performed between each possible pair\n // of the four coordinates, and the results are used to rank the numbers.\n let rankx = 0;\n let ranky = 0;\n let rankz = 0;\n let rankw = 0;\n if (x0 > y0)\n rankx++;\n else\n ranky++;\n if (x0 > z0)\n rankx++;\n else\n rankz++;\n if (x0 > w0)\n rankx++;\n else\n rankw++;\n if (y0 > z0)\n ranky++;\n else\n rankz++;\n if (y0 > w0)\n ranky++;\n else\n rankw++;\n if (z0 > w0)\n rankz++;\n else\n rankw++;\n // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order.\n // Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w and x<w\n // impossible. Only the 24 indices which have non-zero entries make any sense.\n // We use a thresholding to set the coordinates in turn from the largest magnitude.\n // Rank 3 denotes the largest coordinate.\n // Rank 2 denotes the second largest coordinate.\n // Rank 1 denotes the second smallest coordinate.\n // The integer offsets for the second simplex corner\n const i1 = rankx >= 3 ? 1 : 0;\n const j1 = ranky >= 3 ? 1 : 0;\n const k1 = rankz >= 3 ? 1 : 0;\n const l1 = rankw >= 3 ? 1 : 0;\n // The integer offsets for the third simplex corner\n const i2 = rankx >= 2 ? 1 : 0;\n const j2 = ranky >= 2 ? 1 : 0;\n const k2 = rankz >= 2 ? 1 : 0;\n const l2 = rankw >= 2 ? 1 : 0;\n // The integer offsets for the fourth simplex corner\n const i3 = rankx >= 1 ? 1 : 0;\n const j3 = ranky >= 1 ? 1 : 0;\n const k3 = rankz >= 1 ? 1 : 0;\n const l3 = rankw >= 1 ? 1 : 0;\n // The fifth corner has all coordinate offsets = 1, so no need to compute that.\n const x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords\n const y1 = y0 - j1 + G4;\n const z1 = z0 - k1 + G4;\n const w1 = w0 - l1 + G4;\n const x2 = x0 - i2 + 2.0 * G4; // Offsets for third corner in (x,y,z,w) coords\n const y2 = y0 - j2 + 2.0 * G4;\n const z2 = z0 - k2 + 2.0 * G4;\n const w2 = w0 - l2 + 2.0 * G4;\n const x3 = x0 - i3 + 3.0 * G4; // Offsets for fourth corner in (x,y,z,w) coords\n const y3 = y0 - j3 + 3.0 * G4;\n const z3 = z0 - k3 + 3.0 * G4;\n const w3 = w0 - l3 + 3.0 * G4;\n const x4 = x0 - 1.0 + 4.0 * G4; // Offsets for last corner in (x,y,z,w) coords\n const y4 = y0 - 1.0 + 4.0 * G4;\n const z4 = z0 - 1.0 + 4.0 * G4;\n const w4 = w0 - 1.0 + 4.0 * G4;\n // Work out the hashed gradient indices of the five simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n const ll = l & 255;\n // Calculate the contribution from the five corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk + perm[ll]]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad4x[gi0] * x0 + permGrad4y[gi0] * y0 + permGrad4z[gi0] * z0 + permGrad4w[gi0] * w0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad4x[gi1] * x1 + permGrad4y[gi1] * y1 + permGrad4z[gi1] * z1 + permGrad4w[gi1] * w1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad4x[gi2] * x2 + permGrad4y[gi2] * y2 + permGrad4z[gi2] * z2 + permGrad4w[gi2] * w2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad4x[gi3] * x3 + permGrad4y[gi3] * y3 + permGrad4z[gi3] * z3 + permGrad4w[gi3] * w3);\n }\n let t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4;\n if (t4 < 0)\n n4 = 0.0;\n else {\n const gi4 = ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]];\n t4 *= t4;\n n4 = t4 * t4 * (permGrad4x[gi4] * x4 + permGrad4y[gi4] * y4 + permGrad4z[gi4] * z4 + permGrad4w[gi4] * w4);\n }\n // Sum up and scale the result to cover the range [-1,1]\n return 27.0 * (n0 + n1 + n2 + n3 + n4);\n };\n}\n/**\n * Builds a random permutation table.\n * This is exported only for (internal) testing purposes.\n * Do not rely on this export.\n * @private\n */\nexport function buildPermutationTable(random) {\n const tableSize = 512;\n const p = new Uint8Array(tableSize);\n for (let i = 0; i < tableSize / 2; i++) {\n p[i] = i;\n }\n for (let i = 0; i < tableSize / 2 - 1; i++) {\n const r = i + ~~(random() * (256 - i));\n const aux = p[i];\n p[i] = p[r];\n p[r] = aux;\n }\n for (let i = 256; i < tableSize; i++) {\n p[i] = p[i - 256];\n }\n return p;\n}\n//# sourceMappingURL=simplex-noise.js.map","function _prng_restore(prng, xg, opts) {\n let state = opts && opts.state;\n if (state) {\n if (typeof(state) == 'object') xg.copy(state, xg);\n prng.state = () => xg.copy(xg, {});\n }\n}\n\nfunction _prng_xor_core(xg, opts) {\n let prng = () => (xg.next() >>> 0) / 0x100000000;\n\n prng.double = () => {\n let top, bot, result;\n do {\n top = xg.next() >>> 11;\n bot = (xg.next() >>> 0) / 0x100000000;\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n\n prng.int32 = () => xg.next() | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng;\n}\n\n// A port of an algorithm by Johannes Baagøe <[email protected]>, 2010\nfunction prng_alea(seed, opts) {\n let xg = new AleaGen(seed);\n\n let prng = () => xg.next();\n\n prng.double = () =>\n prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53\n\n prng.int32 = () => (xg.next() * 0x100000000) | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\nclass AleaGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let n = 0xefc8249d;\n\n // Apply the seeding algorithm from Baagoe.\n this.c = 1;\n this.s0 = mash(' ');\n this.s1 = mash(' ');\n this.s2 = mash(' ');\n this.s0 -= mash(seed);\n if (this.s0 < 0) { this.s0 += 1; }\n this.s1 -= mash(seed);\n if (this.s1 < 0) { this.s1 += 1; }\n this.s2 -= mash(seed);\n if (this.s2 < 0) { this.s2 += 1; }\n\n function mash(data) {\n data = String(data);\n for (let i = 0; i < data.length; i++) {\n n += data.charCodeAt(i);\n let h = 0.02519603282416938 * n;\n n = h >>> 0;\n h -= n;\n h *= n;\n n = h >>> 0;\n h -= n;\n n += h * 0x100000000; // 2^32\n }\n return (n >>> 0) * 2.3283064365386963e-10; // 2^-32\n }\n }\n\n next() {\n let {c,s0,s1,s2} = this;\n let t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32\n this.s0 = s1;\n this.s1 = s2;\n return this.s2 = t - (this.c = t | 0);\n }\n\n copy(f, t) {\n t.c = f.c;\n t.s0 = f.s0;\n t.s1 = f.s1;\n t.s2 = f.s2;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xor128\" prng algorithm by\nfunction prng_xor128(seed, opts) {\n let xg = new Xor128Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass Xor128Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w} = this;\n let t = x ^ (x << 11);\n this.x = y;\n this.y = z;\n this.z = w;\n return this.w = w ^ ((w >>> 19) ^ t ^ (t >>> 8));\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorwow\" prng algorithm by\nfunction prng_xorwow(seed, opts) {\n let xg = new XorWowGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass XorWowGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n this.v = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n if (k == strseed.length) {\n this.d = this.x << 10 ^ this.x >>> 4;\n }\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w,v,d} = this;\n let t = (x ^ (x >>> 2));\n this.x = y;\n this.y = z;\n this.z = w;\n this.w = v;\n return (this.d = (d + 362437 | 0)) +\n (this.v = (v ^ (v << 4)) ^ (t ^ (t << 1))) | 0;\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n t.v = f.v;\n t.d = f.d;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorshift7\" algorithm by\nfunction prng_xorshift7(seed, opts) {\n let xg = new XorShift7Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass XorShift7Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n var j, w, x = [];\n\n if (seed === (seed | 0)) {\n // Seed state array using a 32-bit integer.\n w = x[0] = seed;\n } else {\n // Seed state using a string.\n seed = '' + seed;\n for (j = 0; j < seed.length; ++j) {\n x[j & 7] = (x[j & 7] << 15) ^\n (seed.charCodeAt(j) + x[(j + 1) & 7] << 13);\n }\n }\n\n // Enforce an array length of 8, not all zeroes.\n while (x.length < 8) x.push(0);\n for (j = 0; j < 8 && x[j] === 0; ++j);\n if (j == 8) w = x[7] = -1; else w = x[j];\n\n this.x = x;\n this.i = 0;\n\n // Discard an initial 256 values.\n for (j = 256; j > 0; --j) {\n this.next();\n }\n }\n\n next() {\n // Update xor generator.\n let t, v, {x,i} = this;\n t = x[i]; t ^= (t >>> 7); v = t ^ (t << 24);\n t = x[(i + 1) & 7]; v ^= t ^ (t >>> 10);\n t = x[(i + 3) & 7]; v ^= t ^ (t >>> 3);\n t = x[(i + 4) & 7]; v ^= t ^ (t << 7);\n t = x[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);\n x[i] = v;\n this.i = (i + 1) & 7;\n return v;\n };\n\n copy(f, t) {\n t.x = [... f.x];\n t.i = f.i;\n return t;\n }\n}\n\n// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.\nfunction prng_xor4096(seed, opts) {\n let xg = new Xor4096Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass Xor4096Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let t, v, i, j, w, X = [], limit = 128;\n if (seed === (seed | 0)) {\n // Numeric seeds initialize v, which is used to generates X.\n v = seed;\n seed = null;\n } else {\n // String seeds are mixed into v and X one character at a time.\n seed = seed + '\\0';\n v = 0;\n limit = Math.max(limit, seed.length);\n }\n // Initialize circular array and weyl value.\n for (i = 0, j = -32; j < limit; ++j) {\n // Put the unicode characters into the array, and shuffle them.\n if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);\n // After 32 shuffles, take v as the starting w value.\n if (j === 0) w = v;\n v ^= v << 10;\n v ^= v >>> 15;\n v ^= v << 4;\n v ^= v >>> 13;\n if (j >= 0) {\n w = (w + 0x61c88647) | 0; // Weyl.\n t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array.\n i = (0 == t) ? i + 1 : 0; // Count zeroes.\n }\n }\n // We have detected all zeroes; make the key nonzero.\n if (i >= 128) {\n X[(seed && seed.length || 0) & 127] = -1;\n }\n // Run the generator 512 times to further mix the state before using it.\n // Factoring this as a function slows the main generator, so it is just\n // unrolled here. The weyl generator is not advanced while warming up.\n i = 127;\n for (j = 4 * 128; j > 0; --j) {\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n X[i] = v ^ t;\n }\n // Storing state as object members is faster than using closure variables.\n this.w = w;\n this.X = X;\n this.i = i;\n }\n\n next() {\n let t, v, {w, X, i} = this;\n // Update Weyl generator.\n this.w = w = (w + 0x61c88647) | 0;\n // Update xor generator.\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n // Update Xor generator array state.\n v = X[i] = v ^ t;\n this.i = i;\n // Result is the combination.\n return (v + (w ^ (w >>> 16))) | 0;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.w = f.w;\n t.X = [... f.X];\n return t;\n }\n}\n\n// A Javascript implementaion of the \"Tyche-i\" prng algorithm by\nfunction prng_tychei(seed, opts) {\n let xg = new TycheiGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass TycheiGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.a = 0;\n this.b = 0;\n this.c = 2654435769 | 0;\n this.d = 1367130551;\n\n if (seed === Math.floor(seed)) {\n // Integer seed.\n this.a = (seed / 0x100000000) | 0;\n this.b = seed | 0;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 20; k++) {\n this.b ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {a,b,c,d} = this;\n b = (b << 25) ^ (b >>> 7) ^ c;\n c = (c - d) | 0;\n d = (d << 24) ^ (d >>> 8) ^ a;\n a = (a - b) | 0;\n this.b = b = (b << 20) ^ (b >>> 12) ^ c;\n this.c = c = (c - d) | 0;\n this.d = (d << 16) ^ (c >>> 16) ^ a;\n return this.a = (a - b) | 0;\n };\n\n copy(f, t) {\n t.a = f.a;\n t.b = f.b;\n t.c = f.c;\n t.d = f.d;\n return t;\n }\n}\n\n\n/* The following is non-inverted tyche, which has better internal\n * bit diffusion, but which is about 25% slower than tyche-i in JS.\n *\n\nclass TycheiGenAlt extends TycheiGen {\n next() {\n let {a,b,c,d} = this\n a = (a + b | 0) >>> 0;\n d = d ^ a; d = d << 16 ^ d >>> 16;\n c = c + d | 0;\n b = b ^ c; b = b << 12 ^ d >>> 20;\n this.a = a = a + b | 0;\n d = d ^ a; this.d = d = d << 8 ^ d >>> 24;\n this.c = c = c + d | 0;\n b = b ^ c;\n return this.b = (b << 7 ^ b >>> 25);\n }\n}\n*/\n\n/*\nCopyright 2019 David Bau.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*/\nfunction prng_arc4(seed, opts) {\n let xg = new ARC4Gen(seed);\n let prng = () => xg.next();\n\n prng.double = prng;\n\n prng.int32 = () => xg.g(4) | 0;\n\n prng.quick = () => xg.g(4) / 0x100000000;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\n\n//\n// ARC4\n//\n// An ARC4 implementation. The constructor takes a key in the form of\n// an array of at most (width) integers that should be 0 <= x < (width).\n//\n// The g(count) method returns a pseudorandom integer that concatenates\n// the next (count) outputs from ARC4. Its return value is a number x\n// that is in the range 0 <= x < (width ^ count).\n//\n\n//\n// The following constants are related to IEEE 754 limits.\n//\n\n// const width = 256 // each RC4 output is 0 <= x < 256\n// const chunks = 6 // at least six RC4 outputs for each double\nconst _arc4_startdenom = 281474976710656; // 256 ** 6 == width ** chunks\nconst _arc4_significance = 4503599627370496; // 2 ** 52 significant digits in a double\nconst _arc4_overflow = 9007199254740992; // 2 ** 53 == significance * 2\n\n\nclass ARC4Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let key = this.mixkey(seed, []);\n let i,j,t, S=[], keylen = key.length;\n this.i = this.j = i = j = 0;\n this.S = S;\n\n // The empty key [] is treated as [0].\n if (!keylen) { key = [keylen++]; }\n\n // Set up S using the standard key scheduling algorithm.\n while (i <= 0xff) {\n S[i] = i++;\n }\n for (i = 0; i <= 0xff; i++) {\n S[i] = S[j = 0xff & (j + key[i % keylen] + (t = S[i]))];\n S[j] = t;\n }\n\n // For robust unpredictability, the function call below automatically\n // discards an initial batch of values. This is called RC4-drop[256].\n // See http://google.com/search?q=rsa+fluhrer+response&btnI\n this.g(256);\n }\n\n next() {\n // This function returns a random double in [0, 1) that contains\n // randomness in every bit of the mantissa of the IEEE 754 value.\n\n let n = this.g(6); // Start with a numerator n < 2 ^ 48\n let d = _arc4_startdenom; // and denominator d = 2 ^ 48.\n let x = 0; // and no 'extra last byte'.\n\n while (n < _arc4_significance) { // Fill up all significant digits (2 ** 52)\n n = (n + x) * 256; // by shifting numerator and\n d *= 256; // denominator and generating a\n x = this.g(1); // new least-significant-byte.\n }\n while (n >= _arc4_overflow) { // To avoid rounding past overflow, before adding\n n /= 2; // last byte, shift everything\n d /= 2; // right using integer math until\n x >>>= 1; // we have exactly the desired bits.\n }\n return (n + x) / d; // Form the number within [0, 1).\n }\n\n g(count) {\n // The \"g\" method returns the next (count) outputs as one number.\n let t, r = 0, {i,j,S} = this;\n while (count--) {\n t = S[i = 0xff & (i + 1)];\n r = r * 256 + S[0xff & ((S[i] = S[j = 0xff & (j + t)]) + (S[j] = t))];\n }\n this.i = i;\n this.j = j;\n return r;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.j = f.j;\n t.S = [... f.S];\n return t;\n }\n\n mixkey(seed, key) {\n seed = seed + '';\n let smear=0, j=0;\n while (j < seed.length) {\n key[0xff & j] =\n 0xff & ((smear ^= key[0xff & j] * 19) + seed.charCodeAt(j++));\n }\n return key\n }\n}\n\nexport { prng_alea, prng_arc4, prng_tychei, prng_xor128, prng_xor4096, prng_xorshift7, prng_xorwow };\n//# sourceMappingURL=index.mjs.map\n","import { usesRadians as runtimeUsesRadians } from \"./runtime.js\";\n\n// =============================================================================\n// Section: Randomness & Noise\n// =============================================================================\n\nimport { createNoise2D } from \"simplex-noise\";\nimport { prng_alea } from \"esm-seedrandom\";\n\n/**\n * A uniform PRNG function. Returns a float in [0,1).\n * @callback RNG\n * @returns {number}\n */\n/** @type {RNG} */\nlet rng = prng_alea(Math.random());\nlet rng2 = prng_alea(Math.random());\n\nconst _seedCallbacks = [];\n\n/**\n * Register a callback to be called whenever seed() is invoked.\n * Used internally by modules that maintain gaussian pools.\n * @param {Function} cb\n */\nexport const _onSeed = (cb) => _seedCallbacks.push(cb);\n\n/**\n * Seed the random number generator.\n * @param {number|string} s – The seed value.\n * @returns {void}\n */\nexport const seed = (s) => {\n rng = prng_alea(s);\n rng2 = prng_alea(`${s}:2`);\n for (const callback of _seedCallbacks) {\n callback();\n }\n};\n\n/**\n * Simplex‐noise 2D function.\n * @type {function(number, number): number}\n */\nexport let noise = createNoise2D(prng_alea(Math.random()));\nexport let noise2 = createNoise2D(prng_alea(Math.random()));\n\n/**\n * Seed the noise generator.\n * @param {number|string} s - The seed value.\n * @returns {void}\n */\nexport const noiseSeed = (s) => {\n noise = createNoise2D(prng_alea(s));\n noise2 = createNoise2D(prng_alea(`${s}:2`));\n};\n\n/**\n * Returns a random float in [min, max).\n * @param {number} [min=0]\n * @param {number} [max=1]\n * @returns {number}\n */\nexport const rr = (e = 0, r = 1) => e + rng() * (r - e);\nexport const rr2 = (e = 0, r = 1) => e + rng2() * (r - e);\n\n/**\n * Selects a random element from an array.\n * @param {T[]} array - Input array.\n * @returns {T}\n */\nexport const rArray = (array) => array[~~(rng() * array.length)];\n\n/**\n * Returns a random integer in [min, max).\n * @param {number} min\n * @param {number} max\n * @returns {number}\n */\nexport const randInt = (e, r) => ~~rr(e, r);\nexport const randInt2 = (e, r) => ~~rr2(e, r);\n\n/**\n * Gaussian (normal) random sample N(mean, stdev²).\n * @param {number} [mean=0]\n * @param {number} [stdev=1]\n * @returns {number}\n */\nexport const gaussian = (mean = 0, stdev = 1) => {\n const u = 1 - rng();\n const v = rng();\n const z = Math.sqrt(-2.0 * Math.log(u)) * cos(360 * v);\n return z * stdev + mean;\n};\n\n/**\n * Picks a key from an object according to weighted probabilities.\n * @param {Object<string|number, number>} weights\n * @returns {string|number}\n */\nexport const weightedRand = (weights) => {\n let totalWeight = 0;\n const entries = [];\n\n // Build cumulative weights array\n for (const key in weights) {\n totalWeight += weights[key];\n entries.push({ key, cumulative: totalWeight });\n }\n\n // Get a random number between 0 and totalWeight\n const rnd = rng() * totalWeight;\n\n // Pick the first entry where rnd is less than the cumulative weight\n for (const { key, cumulative } of entries) {\n if (rnd < cumulative) {\n return isNaN(key) ? key : parseInt(key);\n }\n }\n};\n\n// =============================================================================\n// Section: Numeric Mapping & Constraints\n// =============================================================================\n\n/**\n * Maps a value from range [a,b] to [c,d], optionally clamped.\n * @param {number} value\n * @param {number} a\n * @param {number} b\n * @param {number} c\n * @param {number} d\n * @param {boolean} [withinBounds=false]\n * @returns {number}\n */\nexport const map = (value, a, b, c, d, withinBounds = false) => {\n let r = c + ((value - a) / (b - a)) * (d - c);\n if (!withinBounds) return r;\n if (c < d) return constrain(r, c, d);\n else return constrain(r, d, c);\n};\n\n/**\n * Constrains a number within the provided bounds.\n * @param {number} n - The number.\n * @param {number} low - Lower bound.\n * @param {number} high - Upper bound.\n * @returns {number} The constrained number.\n */\nexport const constrain = (n, low, high) => Math.max(Math.min(n, high), low);\n\n// =============================================================================\n// Section: Trigonometry\n// =============================================================================\n\n/**\n * Normalize an angle in degrees to [0,360).\n * @param {number} angle\n * @returns {number}\n */\nconst nAngle = (angle) => {\n angle = angle % 360;\n return angle < 0 ? angle + 360 : angle;\n};\n\n// number of discrete steps (360° × 4 samples per degree)\nconst totalDegrees = 1440;\nconst radiansPerIndex = (2 * Math.PI) / totalDegrees;\n\n// lazy‐initialized lookup tables\nconst cLookup = new Float32Array(totalDegrees).fill(NaN);\nconst sLookup = new Float32Array(totalDegrees).fill(NaN);\n\n/**\n * Cosine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const cos = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = cLookup[idx];\n if (isNaN(v)) {\n v = Math.cos(idx * radiansPerIndex);\n cLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Sine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const sin = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = sLookup[idx];\n if (isNaN(v)) {\n v = Math.sin(idx * radiansPerIndex);\n sLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Converts radians to degrees, normalized to [0,360).\n * @param {number} rad\n * @returns {number}\n */\nexport const toDegrees = (rad, isRad = false) => {\n if (isRad || runtimeUsesRadians()) {\n let angle = ((rad * 180) / Math.PI) % 360;\n return angle < 0 ? angle + 360 : angle;\n } else {\n return rad;\n }\n};\n\n/**\n * Converts radians to degrees without wrapping the result.\n * Preserves signed angles so downstream scaling keeps its direction.\n * @param {number} angle\n * @param {boolean} [isRad=false]\n * @returns {number}\n */\nexport const toDegreesSigned = (angle, isRad = false) =>\n isRad || runtimeUsesRadians()\n ? (angle * 180) / Math.PI\n : angle;\n\n// =============================================================================\n// Section: Geometry & Transforms\n// =============================================================================\n\n/**\n * Rotates point (x,y) around center (cx,cy) by angle degrees.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x\n * @param {number} y\n * @param {number} angle - Degrees\n * @returns {{x:number,y:number}}\n */\nexport const rotate = (cx, cy, x, y, angle) => {\n let coseno = cos(angle),\n seno = sin(angle),\n nx = coseno * (x - cx) + seno * (y - cy) + cx,\n ny = coseno * (y - cy) - seno * (x - cx) + cy;\n return { x: nx, y: ny };\n};\n\n/**\n * Euclidean distance between two points.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const dist = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1);\n\n/**\n * Angle in degrees between two points, measured clockwise from +X.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const calcAngle = (x1, y1, x2, y2) =>\n toDegrees(Math.atan2(-(y2 - y1), x2 - x1), true);\n\n/**\n * Intersection of two line segments, or false if none.\n * @param {{x:number,y:number}} s1a\n * @param {{x:number,y:number}} s1b\n * @param {{x:number,y:number}} s2a\n * @param {{x:number,y:number}} s2b\n * @param {boolean} [includeSegmentExtension=false]\n * @returns {{x:number,y:number}|false}\n */\nexport const intersectLines = (\n s1a,\n s1b,\n s2a,\n s2b,\n includeSegmentExtension = false\n) => {\n // Extract coordinates from points\n let x1 = s1a.x,\n y1 = s1a.y;\n let x2 = s1b.x,\n y2 = s1b.y;\n let x3 = s2a.x,\n y3 = s2a.y;\n let x4 = s2b.x,\n y4 = s2b.y;\n // Early return if line segments are points or if the lines are parallel\n if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) {\n return false; // Segments are points\n }\n let deltaX1 = x2 - x1,\n deltaY1 = y2 - y1;\n let deltaX2 = x4 - x3,\n deltaY2 = y4 - y3;\n let denominator = deltaY2 * deltaX1 - deltaX2 * deltaY1;\n if (denominator === 0) {\n return false; // Lines are parallel\n }\n // Calculate the intersection point\n let ua = (deltaX2 * (y1 - y3) - deltaY2 * (x1 - x3)) / denominator;\n let ub = (deltaX1 * (y1 - y3) - deltaY1 * (x1 - x3)) / denominator;\n // Check if the intersection is within the bounds of the line segments\n if (!includeSegmentExtension && (ub < 0 || ub > 1)) {\n return false;\n }\n // Calculate the intersection coordinates\n let x = x1 + ua * deltaX1;\n let y = y1 + ua * deltaY1;\n return { x: x, y: y };\n};\n","import { Cwidth, Cheight } from \"./target.js\";\nimport { isMixReady, State } from \"./color.js\";\nimport { randInt2, noise2, rr2, sin, cos, map, toDegreesSigned } from \"./utils.js\";\nimport { getAffineMatrix } from \"./runtime.js\";\n\n// =============================================================================\n// Section: Matrix transformations\n// =============================================================================\n\n// =============================================================================\n// Section: Field Initialization\n// =============================================================================\n\nlet isLoaded = false;\n\n/**\n * Ensures the field system is initialized and ready for use.\n * If the field is not loaded, it initializes the mixing system and creates the field.\n */\nexport function isFieldReady() {\n if (!isLoaded) {\n isMixReady(); // Ensure the mixing system is ready\n createField(); // Initialize the field\n isLoaded = true;\n }\n}\n\n// =============================================================================\n// Section: Position Class\n// =============================================================================\n\n/**\n * The Position class represents a point within a two-dimensional space, which can interact with a vector field.\n * It provides methods to update the position based on the field's flow and to check whether the position is\n * within certain bounds (e.g., within the field or canvas).\n */\nexport class Position {\n /**\n * Constructs a new Position instance.\n * @param {number} x - The initial x-coordinate.\n * @param {number} y - The initial y-coordinate.\n */\n constructor(x, y) {\n isFieldReady();\n const m = getAffineMatrix();\n this.mx = m.x;\n this.my = m.y;\n this.update(x, y);\n this.plotted = 0; // Tracks the total distance plotted\n }\n\n /**\n * Updates the position's coordinates and calculates its offsets and indices within the flow field.\n * @param {number} x - The new x-coordinate.\n * @param {number} y - The new y-coordinate.\n */\n update(x, y) {\n this.x = x;\n this.y = y;\n this.colIdx = Math.round((x + this.mx - left_x) / resolution);\n this.rowIdx = Math.round((y + this.my - top_y) / resolution);\n }\n\n /**\n * Resets the 'plotted' property to 0.\n */\n reset() {\n this.plotted = 0;\n }\n\n /**\n * Checks if the position is within the active flow field's bounds.\n * @returns {boolean} - True if the position is within the flow field, false otherwise.\n */\n isIn() {\n return State.field.isActive\n ? Position.isIn(this.colIdx, this.rowIdx)\n : this.isInCanvas(this.x, this.y);\n }\n\n /**\n * Checks if the position is within the canvas bounds (with a margin).\n * @returns {boolean} - True if the position is within bounds, false otherwise.\n */\n isInCanvas() {\n const margin = 0.3;\n const w = Cwidth;\n const h = Cheight;\n const x = this.x + this.mx;\n const y = this.y + this.my;\n return (\n x >= -margin * w &&\n x <= (1 + margin) * w &&\n y >= -margin * h &&\n y <= (1 + margin) * h\n );\n }\n\n /**\n * Calculates the angle of the flow field at the position's current coordinates.\n * @returns {number} - The internal flow angle in degrees, or 0 if the position is not in the field or if no field is active.\n */\n angle(skipCheck = false) {\n if (!State.field.isActive) return 0;\n return (skipCheck || this.isIn())\n ? flow_field()[this.colIdx][this.rowIdx] * State.field.wiggle\n : 0;\n }\n\n /**\n * Moves the position along the flow field by a certain length.\n * @param {number} _dir - The direction of movement, interpreted using the current runtime angle units.\n * @param {number} _length - The length to move along the field.\n * @param {number} _step_length - The length of each step.\n */\n moveTo(_dir, _length, _step_length = 1) {\n this.movePos(toDegreesSigned(_dir), _length, _step_length);\n }\n\n /**\n * Internal variant of moveTo() that expects a degree value already normalized to the library's internal representation.\n */\n _moveToDegrees(_dir, _length, _step_length = 1) {\n this.movePos(_dir, _length, _step_length);\n }\n\n /**\n * Plots a point to another position within the flow field, following a Plot object\n * @param {Position} _plot - The Plot path object.\n * @param {number} _length - The length to move towards the target position.\n * @param {number} _step_length - The length of each step.\n * @param {number} _scale - The scaling factor for the plotting path.\n */\n plotTo(_plot, _length, _step_length, _scale = 1) {\n this.movePos(_plot, _length, _step_length, _scale);\n }\n\n movePos(_dirPlot, _length, _step, _scale = false) {\n const scaleFactor = _scale || 1;\n if (!this.isIn()) {\n this.plotted += _step / scaleFactor;\n return;\n }\n const steps = _length / _step;\n const fieldActive = State.field.isActive;\n const usePlot = !!_scale;\n for (let i = 0; i < steps; i++) {\n const angle =\n (fieldActive ? this.angle(true) : 0) - (usePlot ? _dirPlot.angle(this.plotted) : _dirPlot);\n // Calculate new position\n this.update(this.x + _step * cos(angle), this.y + _step * sin(angle));\n this.plotted += _step / scaleFactor;\n }\n }\n\n // Static Methods\n\n /**\n * Gets the row index for a given y-coordinate.\n * @param {number} y - The y-coordinate.\n * @returns {number} - The row index.\n */\n static getRowIndex(y, d = 1) {\n const y_offset = y + getAffineMatrix().y - top_y;\n return Math.round(y_offset / resolution / d);\n }\n\n /**\n * Gets the column index for a given x-coordinate.\n * @param {number} x - The x-coordinate.\n * @returns {number} - The column index.\n */\n static getColIndex(x, d = 1) {\n const x_offset = x + getAffineMatrix().x - left_x;\n return Math.round(x_offset / resolution / d);\n }\n\n /**\n * Checks if a column and row index are within the flow field bounds.\n * @param {number} col - The column index.\n * @param {number} row - The row index.\n * @returns {boolean} - True if the indices are within bounds, false otherwise.\n */\n static isIn(col, row) {\n return col >= 0 && row >= 0 && col < num_columns && row < num_rows;\n }\n}\n\n// =============================================================================\n// Section: VectorField\n// =============================================================================\n\n/**\n * Represents the state of the vector field.\n * @property {boolean} isActive - Indicates if the vector field is active.\n * @property {string|null} current - The name of the currently active vector field.\n */\nState.field = {\n isActive: false,\n current: null,\n wiggle: 1,\n};\n\n// Internal variables for field configuration\nlet list = new Map();\nlet resolution, left_x, top_y, num_columns, num_rows;\nconst FIELD_ANGLE_MODES = new Set([\"degrees\", \"radians\"]);\n\n/**\n * Initializes the field grid and sets up the vector field's structure based on the renderer's dimensions.\n */\nfunction createField() {\n resolution = Cwidth * 0.01; // Determine the resolution of the field grid\n left_x = -0.5 * Cwidth; // Left boundary of the field\n top_y = -0.5 * Cheight; // Top boundary of the field\n num_columns = Math.round((2 * Cwidth) / resolution); // Number of columns in the grid\n num_rows = Math.round((2 * Cheight) / resolution); // Number of columns in the grid\n addStandard(); // Add default vector field\n}\n\n/**\n * Retrieves the field values for the current vector field.\n * @returns {Float32Array[]} The current vector field grid.\n */\nfunction flow_field() {\n return list.get(State.field.current).field;\n}\n\nfunction normalizeFieldAngleMode(options = {}) {\n const config =\n typeof options === \"string\" ? { angleMode: options } : options || {};\n const angleMode = config.angleMode ?? \"degrees\";\n\n if (!FIELD_ANGLE_MODES.has(angleMode)) {\n throw new Error(\n `Invalid field angle mode \"${angleMode}\". Use \"degrees\" or \"radians\".`,\n );\n }\n\n return angleMode;\n}\n\nfunction normalizeFieldAngles(field, angleMode) {\n if (angleMode !== \"radians\") return field;\n\n for (let c = 0; c < field.length; c++) {\n for (let r = 0; r < field[c].length; r++) {\n field[c][r] = toDegreesSigned(field[c][r], true);\n }\n }\n\n return field;\n}\n\nfunction generateField(entry, t) {\n return normalizeFieldAngles(entry.gen(t, genField()), entry.angleMode);\n}\n\n/**\n * Regenerates the current vector field using its associated generator function.\n * @param {number} [t=0] - An optional time parameter that can affect field generation.\n */\nexport function refreshField(t = 0) {\n if (!State.field.isActive || !State.field.current) {\n throw new Error(\n \"No field is currently active. Call brush.field('name') to activate one before refreshing.\",\n );\n }\n const currentField = list.get(State.field.current);\n currentField.field = generateField(currentField, t);\n}\n\n/**\n * Generates an empty field array.\n * Reuses existing arrays to reduce memory allocation overhead.\n * @returns {Float32Array[]} Empty vector field grid.\n */\nfunction genField() {\n return new Array(num_columns)\n .fill(null)\n .map(() => new Float32Array(num_rows));\n}\n\n/**\n * Activates a specific vector field by name, ensuring it's ready for use.\n * @param {string} a - The name of the vector field to activate.\n */\nexport function field(a) {\n if (!State.field.wiggle) {\n State.field.wiggle = 1;\n } // Set default wiggle value\n isFieldReady();\n if (!list.has(a)) {\n throw new Error(\n `Field \"${a}\" does not exist. Available fields: ${Array.from(list.keys()).join(\", \")}.`,\n );\n }\n State.field.isActive = true;\n State.field.current = a;\n const entry = list.get(a);\n if (!entry.field) entry.field = generateField(entry, 0);\n}\n\n/**\n * Deactivates the current vector field.\n */\nexport function noField() {\n isFieldReady();\n State.field.isActive = false;\n}\n\n/**\n * Adds a new vector field to the field list with a unique name and a generator function.\n * @param {string} name - The unique name for the new vector field.\n * @param {Function} funct - The function that generates the field values.\n * @param {object} [options] - Optional field configuration.\n * @param {\"degrees\"|\"radians\"} [options.angleMode=\"degrees\"] - How the generator's output angles should be interpreted.\n */\nexport function addField(name, funct, options = {}) {\n list.set(name, {\n gen: funct,\n field: null,\n angleMode: normalizeFieldAngleMode(options),\n });\n}\n\n/**\n * Retrieves a list of all available vector field names.\n * @returns {string[]} An array of all the field names.\n */\nexport function listFields() {\n isFieldReady();\n return Array.from(list.keys());\n}\n\nexport function wiggle(a = 1) {\n field(\"hand\");\n State.field.wiggle = a;\n}\n\n/**\n * Fills every cell of a field grid using a callback (c, r) => angle.\n */\nfunction fillField(field, fn) {\n for (let c = 0; c < num_columns; c++)\n for (let r = 0; r < num_rows; r++) field[c][r] = fn(c, r);\n return field;\n}\n\n/**\n * Adds standard predefined vector fields to the list with unique behaviors.\n */\nfunction addStandard() {\n // Organic noise — basis for brush.wiggle()\n addField(\"hand\", (t, field) => {\n const bs = rr2(0.2, 0.8),\n ba = randInt2(5, 10);\n return fillField(field, (c, r) => {\n const angle = 0.5 * ba * sin(bs * r * c + randInt2(15, 25));\n return 0.2 * angle * cos(t) + noise2(c, r) * ba * 0.7;\n });\n });\n // Smooth large-scale noise curves\n addField(\"curved\", (t, field) => {\n let ar = randInt2(-10, 10);\n if (randInt2(0, 100) % 2 == 0) ar *= -1;\n return fillField(\n field,\n (c, r) =>\n 3 * map(noise2(c * 0.02 + t * 0.03, r * 0.02 + t * 0.03), 0, 1, -ar, ar),\n );\n });\n // Sharp alternating angles per cell — herringbone / wicker look\n addField(\"zigzag\", (t, field) => {\n let ar = randInt2(-30, -15) + Math.abs(44 * sin(t));\n if (randInt2(0, 100) % 2 == 0) ar *= -1;\n let dif = ar,\n angle = 0;\n for (let c = 0; c < num_columns; c++) {\n for (let r = 0; r < num_rows; r++) {\n field[c][r] = angle;\n angle += dif;\n dif *= -1;\n }\n angle += dif;\n dif *= -1;\n }\n return field;\n });\n // Sinusoidal wave bands\n addField(\"waves\", (t, field) => {\n const sr = randInt2(10, 15) + 5 * sin(t),\n cr = randInt2(3, 6) + 3 * cos(t),\n ba = randInt2(20, 35);\n return fillField(\n field,\n (c, r) => sin(sr * c) * ba * cos(r * cr) + randInt2(-3, 3),\n );\n });\n // Dense oscillation from row×col product\n addField(\"seabed\", (t, field) => {\n const bs = rr2(0.4, 0.8),\n ba = randInt2(18, 26);\n return fillField(\n field,\n (c, r) => 1.1 * ba * sin(bs * r * c + randInt2(15, 20)) * cos(t),\n );\n });\n // Radial vortex — angles spiral around the field centre\n addField(\"spiral\", (_t, field) => {\n const n = randInt2(5, 10);\n const dir = randInt2(0, 2) * 2 - 1;\n const offset = randInt2(65, 80); // <90 = inward spiral\n const attractors = Array.from({ length: n }, () => ({\n x: rr2(0.1, 0.9) * num_columns,\n y: rr2(0.1, 0.9) * num_rows,\n }));\n return fillField(field, (c, r) => {\n let wx = 0,\n wy = 0;\n for (const att of attractors) {\n const dx = c - att.x,\n dy = r - att.y;\n const w = 1 / (dx * dx + dy * dy + 1);\n const a = Math.atan2(dy, dx) * (180 / Math.PI);\n const angle = (dir * (a + offset) * Math.PI) / 180;\n wx += w * Math.cos(angle);\n wy += w * Math.sin(angle);\n }\n return Math.atan2(wy, wx) * (180 / Math.PI);\n });\n });\n // Column-banded stripes — parallel rake marks\n addField(\"columns\", (_t, field) => {\n const freq = randInt2(3, 8),\n amp = randInt2(25, 45);\n return fillField(field, (c, _r) => sin(c * freq) * amp);\n });\n}\n","import { State } from \"./color.js\";\nimport { isFieldReady } from \"./flowfield.js\";\n\n// =============================================================================\n// SAVE / RESTORE\n// =============================================================================\n\n/**\n * Stack of saved brush states for push/pop operations.\n * A stack (not a single slot) is required because applyShader() internally\n * calls Renderer.push()/pop(), which fires our hook — a flat object would be\n * overwritten mid-draw and pop() would restore the wrong state.\n */\nconst _stateStack = [];\n\n/**\n * Pushes the current brush state onto the stack.\n */\nexport function push() {\n isFieldReady();\n _stateStack.push({\n fill: { ...State.fill },\n wash: State.wash ? { ...State.wash } : null,\n stroke: { ...State.stroke },\n hatch: { ...State.hatch },\n mass: State.mass ? { ...State.mass } : null,\n field: { ...State.field },\n });\n}\n\n/**\n * Pops the top brush state from the stack and restores it.\n */\nexport function pop() {\n const saved = _stateStack.pop();\n if (!saved) return;\n State.stroke = { ...saved.stroke };\n State.field = { ...saved.field };\n State.hatch = { ...saved.hatch };\n State.fill = { ...saved.fill };\n if (saved.wash) State.wash = { ...saved.wash };\n if (saved.mass) {\n State.mass = { ...saved.mass };\n } else if (State.mass) {\n State.mass = {\n ...State.mass,\n isActive: false,\n brush: null,\n color: null,\n options: {},\n };\n }\n}\n","// =============================================================================\n// Adapter: Standalone Runtime Hooks\n// =============================================================================\n\nimport { setRuntime } from \"../../core/runtime.js\";\nimport { push as pushState, pop as popState } from \"../../core/save.js\";\n\nconst clamp = (value, min, max) => Math.max(min, Math.min(value, max));\n\nexport const DEGREES = \"degrees\";\nexport const RADIANS = \"radians\";\n\nlet colorContext = null;\nlet currentAngleMode = DEGREES;\nconst transformStack = [];\nlet currentTransform = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\n\nfunction getColorContext() {\n if (colorContext) return colorContext;\n\n if (typeof document !== \"undefined\") {\n colorContext = document.createElement(\"canvas\").getContext(\"2d\");\n return colorContext;\n }\n\n if (typeof OffscreenCanvas !== \"undefined\") {\n colorContext = new OffscreenCanvas(1, 1).getContext(\"2d\");\n return colorContext;\n }\n\n throw new Error(\"Standalone color parsing requires CanvasRenderingContext2D support.\");\n}\n\nfunction multiplyTransform(left, right) {\n return {\n a: left.a * right.a + left.c * right.b,\n b: left.b * right.a + left.d * right.b,\n c: left.a * right.c + left.c * right.d,\n d: left.b * right.c + left.d * right.d,\n x: left.a * right.x + left.c * right.y + left.x,\n y: left.b * right.x + left.d * right.y + left.y,\n };\n}\n\n/**\n * Runtime-native color object compatible with the expectations of core modules.\n */\nexport class Color {\n constructor(r, g, b) {\n if (r?._array) {\n this.r = Math.round(r._array[0] * 255);\n this.g = Math.round(r._array[1] * 255);\n this.b = Math.round(r._array[2] * 255);\n this.hex = this.rgbToHex(this.r, this.g, this.b);\n this._array = [...r._array];\n this.gl = this._array;\n return;\n }\n\n if (typeof r === \"string\") {\n const rgbaMatch = /^rgba?\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*(?:,\\s*([\\d.]+))?\\s*\\)$/i.exec(r);\n if (rgbaMatch) {\n this.r = clamp(parseInt(rgbaMatch[1]), 0, 255);\n this.g = clamp(parseInt(rgbaMatch[2]), 0, 255);\n this.b = clamp(parseInt(rgbaMatch[3]), 0, 255);\n this.hex = this.rgbToHex(this.r, this.g, this.b);\n const alpha = rgbaMatch[4] !== undefined ? clamp(parseFloat(rgbaMatch[4]), 0, 1) : 1;\n this._array = [this.r / 255, this.g / 255, this.b / 255, alpha];\n this.gl = this._array;\n return;\n }\n this.hex = this.standardize(r);\n const rgb = this.hexToRgb(this.hex);\n this.r = rgb.r;\n this.g = rgb.g;\n this.b = rgb.b;\n } else {\n this.r = clamp(r ?? 0, 0, 255);\n this.g = clamp(g ?? r ?? 0, 0, 255);\n this.b = clamp(b ?? r ?? 0, 0, 255);\n this.hex = this.rgbToHex(this.r, this.g, this.b);\n }\n\n this._array = [this.r / 255, this.g / 255, this.b / 255, 1];\n this.gl = this._array;\n }\n\n rgbToHex(r, g, b) {\n return `#${((1 << 24) | (r << 16) | (g << 8) | b).toString(16).slice(1)}`;\n }\n\n hexToRgb(hex) {\n hex = hex.replace(\n /^#?([a-f\\d])([a-f\\d])([a-f\\d])$/i,\n (_match, red, green, blue) => red + red + green + green + blue + blue,\n );\n const result = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\n if (!result) {\n throw new Error(`Invalid color value \"${hex}\".`);\n }\n return {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16),\n };\n }\n\n standardize(value) {\n const ctx = getColorContext();\n ctx.fillStyle = value;\n return ctx.fillStyle;\n }\n\n _getRed() {\n return this.r;\n }\n\n _getGreen() {\n return this.g;\n }\n\n _getBlue() {\n return this.b;\n }\n}\n\n/**\n * Sets the active standalone angle mode.\n *\n * @param {\"degrees\"|\"radians\"} mode\n */\nexport function angleMode(mode) {\n if (mode !== DEGREES && mode !== RADIANS) {\n throw new Error(`Invalid angle mode \"${mode}\". Use \"degrees\" or \"radians\".`);\n }\n currentAngleMode = mode;\n}\n\n/**\n * Returns the current standalone angle mode.\n *\n * @returns {\"degrees\"|\"radians\"}\n */\nexport function getAngleMode() {\n return currentAngleMode;\n}\n\n/**\n * Pushes the current standalone transform onto the stack.\n */\nexport function push() {\n pushState();\n transformStack.push({ ...currentTransform });\n}\n\n/**\n * Pops the last standalone transform from the stack.\n */\nexport function pop() {\n if (transformStack.length === 0) return;\n currentTransform = transformStack.pop();\n popState();\n}\n\n/**\n * Applies a translation to the current standalone transform.\n *\n * @param {number} x\n * @param {number} y\n */\nexport function translate(x, y) {\n currentTransform = multiplyTransform(currentTransform, {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x,\n y,\n });\n}\n\n/**\n * Applies a rotation to the current standalone transform.\n *\n * @param {number} angle\n */\nexport function rotate(angle) {\n const theta =\n currentAngleMode === RADIANS ? angle : (angle * Math.PI) / 180;\n const cosTheta = Math.cos(theta);\n const sinTheta = Math.sin(theta);\n currentTransform = multiplyTransform(currentTransform, {\n a: cosTheta,\n b: sinTheta,\n c: -sinTheta,\n d: cosTheta,\n x: 0,\n y: 0,\n });\n}\n\n/**\n * Applies a scale to the current standalone transform.\n *\n * @param {number} x\n * @param {number} [y=x]\n */\nexport function scale(x, y = x) {\n currentTransform = multiplyTransform(currentTransform, {\n a: x,\n b: 0,\n c: 0,\n d: y,\n x: 0,\n y: 0,\n });\n}\n\n/**\n * Installs the standalone runtime hooks used by core modules.\n */\nexport function initStandaloneRuntime() {\n setRuntime({\n usesRadians: () => currentAngleMode === \"radians\",\n fromDegrees: (angle) =>\n currentAngleMode === \"radians\" ? (angle * Math.PI) / 180 : angle,\n createColor: (...args) => {\n if (args.length === 1 && args[0]?._array) return args[0];\n return new Color(...args);\n },\n getAffineMatrix: () => currentTransform,\n });\n}\n","// =============================================================================\n// Adapter: Standalone Frame Helpers\n// =============================================================================\n\nimport { Renderer, isCanvasReady } from \"../../core/target.js\";\nimport { Mix, flushActiveComposite } from \"../../core/color.js\";\nimport { createColor } from \"../../core/runtime.js\";\n\nfunction resetCompositeState() {\n if (Mix.glMask) Mix.clearMask(Mix.glMask);\n if (Mix.mask) Mix.clearMask(Mix.mask);\n Mix.justChanged = false;\n Mix.isBlending = false;\n Mix.isBrush = null;\n Mix.cachedColor = null;\n}\n\n/**\n * Flushes any pending stroke/fill compositing into the active standalone target.\n *\n * Standalone users should call this at the end of a drawing pass or frame.\n */\nexport function render() {\n flushActiveComposite();\n}\n\n/**\n * Clears the active standalone target.\n *\n * With no arguments, clears to transparent white.\n * With a color, clears to that color at full opacity.\n *\n * @param {...*} args\n */\nexport function clear(...args) {\n isCanvasReady();\n resetCompositeState();\n\n const gl = Renderer.drawingContext;\n const color =\n args.length === 0\n ? [1, 1, 1, 0]\n : [...createColor(...args)._array.slice(0, 3), 1];\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.disable(gl.SCISSOR_TEST);\n gl.clearColor(color[0], color[1], color[2], color[3]);\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n}\n","// =============================================================================\n// Adapter: Standalone Target Hooks\n// =============================================================================\n\nimport {\n setTargetRuntime,\n setTargetState,\n} from \"../../core/target.js\";\n\nlet activeTarget = null;\nlet isLoaded = false;\nlet activeDensity = 1;\nlet activeWidth = 0;\nlet activeHeight = 0;\n\nfunction isCanvasTarget(target) {\n return (\n typeof HTMLCanvasElement !== \"undefined\" &&\n target instanceof HTMLCanvasElement\n );\n}\n\nfunction isOffscreenCanvasTarget(target) {\n return (\n typeof OffscreenCanvas !== \"undefined\" &&\n target instanceof OffscreenCanvas\n );\n}\n\nfunction isSupportedTarget(target) {\n return isCanvasTarget(target) || isOffscreenCanvasTarget(target);\n}\n\nfunction getTargetContext(target) {\n return (\n target.getContext(\"webgl2\", { premultipliedAlpha: true }) ??\n target.getContext(\"webgl2\")\n );\n}\n\nfunction createRenderer(target, width, height, density) {\n const drawingContext = getTargetContext(target);\n if (!drawingContext) {\n throw new Error(\"brush.load(target) requires a canvas with a WebGL2 context.\");\n }\n\n return {\n canvas: target,\n drawingContext,\n width,\n height,\n pixelDensity: () => density,\n };\n}\n\nfunction applyLoadedTarget(target, width, height, density) {\n activeTarget = target;\n activeWidth = width;\n activeHeight = height;\n activeDensity = density;\n\n const renderer = createRenderer(target, width, height, density);\n setTargetState({\n Renderer: renderer,\n Cwidth: width,\n Cheight: height,\n Density: density,\n });\n isLoaded = true;\n}\n\n/**\n * Loads a standalone draw target from a DOM canvas or OffscreenCanvas.\n *\n * @param {HTMLCanvasElement|OffscreenCanvas} target\n */\nexport function load(target = activeTarget) {\n if (!isSupportedTarget(target)) {\n throw new Error(\n \"Standalone brush.load(target) requires an HTMLCanvasElement or OffscreenCanvas.\",\n );\n }\n\n applyLoadedTarget(target, target.width, target.height, 1);\n}\n\n/**\n * Creates a standalone DOM canvas, configures its backing resolution according\n * to the provided pixel density, appends it optionally to the DOM, and loads it\n * as the active brush target.\n *\n * @param {number} width Logical canvas width.\n * @param {number} height Logical canvas height.\n * @param {{pixelDensity?: number, parent?: string|Element|null, id?: string}} [options]\n * @returns {HTMLCanvasElement}\n */\nexport function createCanvas(width, height, options = {}) {\n if (typeof document === \"undefined\") {\n throw new Error(\"brush.createCanvas() requires a browser document.\");\n }\n\n const logicalWidth = Math.max(1, Math.round(width));\n const logicalHeight = Math.max(1, Math.round(height));\n const density = Math.max(1, Number(options.pixelDensity) || 1);\n const canvas = document.createElement(\"canvas\");\n\n canvas.width = Math.max(1, Math.round(logicalWidth * density));\n canvas.height = Math.max(1, Math.round(logicalHeight * density));\n canvas.style.width = `${logicalWidth}px`;\n canvas.style.height = `${logicalHeight}px`;\n if (options.id) canvas.id = options.id;\n\n if (options.parent) {\n const parent =\n typeof options.parent === \"string\"\n ? document.querySelector(options.parent)\n : options.parent;\n if (!parent) {\n throw new Error(`Could not find parent \"${options.parent}\" for brush.createCanvas().`);\n }\n parent.appendChild(canvas);\n }\n\n applyLoadedTarget(canvas, logicalWidth, logicalHeight, density);\n return canvas;\n}\n\n/**\n * Refreshes the standalone target density.\n *\n * Standalone targets currently use a fixed density of 1.\n *\n * @returns {number}\n */\nexport function syncDensity() {\n setTargetState({\n Cwidth: activeWidth,\n Cheight: activeHeight,\n Density: activeDensity,\n });\n return activeDensity;\n}\n\n/**\n * Ensures a standalone target has been loaded.\n */\nexport function isCanvasReady() {\n if (!isLoaded) {\n throw new Error(\n \"No standalone target loaded. Call brush.load(canvasOrOffscreenCanvas) first.\",\n );\n }\n}\n\n/**\n * Standalone build does not use p5 instance switching, so these are no-ops.\n */\nexport function instance() {}\nexport function activateInstance() {}\nexport function deactivateInstance() {}\n\n/**\n * Standalone build does not yet support framebuffer targets.\n *\n * @returns {null}\n */\nexport function getActiveFramebuffer() {\n return null;\n}\n\n/**\n * Returns whether the given target behaves like a framebuffer target.\n *\n * Standalone targets currently only accept canvases and offscreen canvases.\n *\n * @returns {boolean}\n */\nexport function isFramebufferTarget() {\n return arguments[0]?.__brushFramebuffer === true;\n}\n\nexport function initStandaloneTargetRuntime() {\n setTargetRuntime({\n load,\n syncDensity,\n isCanvasReady,\n instance,\n activateInstance,\n deactivateInstance,\n getActiveFramebuffer,\n isFramebufferTarget,\n });\n}\n","import {\n rr2,\n randInt2,\n sin,\n cos,\n toDegreesSigned,\n constrain,\n dist,\n calcAngle,\n intersectLines,\n} from \"./utils.js\";\nimport { Polygon } from \"./polygon.js\";\nimport { Plot } from \"./plot.js\";\n\n// =============================================================================\n// Section: Primitives and Geommetry\n// =============================================================================\n\n/**\n * Creates a Polygon from an array of points and calls its show() method.\n * Polygons ignore fields and won't be good for fills and masses\n * @param {Array<Array<number>>} pointsArray - Array of points [x, y, pressure]\n */\nexport function polygon(pointsArray) {\n // Create a new Polygon instance\n const polygon = new Polygon(pointsArray);\n polygon.show();\n}\n\n/**\n * Draws a rectangle on the canvas using path functions.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} w - Width.\n * @param {number} h - Height.\n * @param {boolean} [mode=\"corner\"] - \"corner\" (default) or \"center\".\n */\nexport function rect(x, y, w, h, mode = \"corner\") {\n if (mode === \"center\") {\n x -= w / 2;\n y -= h / 2;\n }\n beginShape(0);\n vertex(x, y);\n vertex(x + w, y);\n vertex(x + w, y + h);\n vertex(x, y + h);\n endShape(true);\n}\n\n/**\n * Draws a circle on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Circle radius.\n * @param {boolean} [r=false] - Randomizes segment lengths if true.\n */\nexport function circle(x, y, radius, r = false) {\n const p = new Plot(\"curve\");\n const arcLength = Math.PI * radius;\n const angleOffset = rr2(0, 360);\n const randomFactor = r ? () => 1 + r * 0.2 * rr2() : () => 1;\n\n // Divide circle into 4 segments\n for (let i = 0; i < 4; i++) {\n const angle = -90 * i + angleOffset;\n p.addSegment(\n angle * randomFactor(),\n (arcLength / 2) * randomFactor(),\n 1,\n true,\n );\n }\n\n // Optionally add a random final angle for the last segment\n if (r) {\n const randomAngle = r * randInt2(-5, 5);\n p.addSegment(\n angleOffset,\n Math.abs(randomAngle) * (Math.PI / 180) * radius,\n 1,\n true,\n );\n p.endPlot(randomAngle + angleOffset, 1, true);\n } else {\n p.endPlot(angleOffset, 1, true);\n }\n\n // Draw the circle\n const offsetX = x - radius * sin(angleOffset);\n const offsetY = y - radius * cos(-angleOffset);\n p.show(offsetX, offsetY, 1);\n}\n\n/**\n * Draws an arc on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Radius.\n * @param {number} start - Start angle in the current runtime angle units.\n * @param {number} end - End angle in the current runtime angle units.\n */\nexport function arc(x, y, radius, start, end) {\n const startDeg = toDegreesSigned(start);\n const endDeg = toDegreesSigned(end);\n const sweepDeg = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweepDeg === 0) return;\n\n const p = new Plot(\"curve\");\n const segmentCount = Math.max(1, Math.ceil(sweepDeg / 90));\n const segmentSweep = sweepDeg / segmentCount;\n const arcLength = (Math.PI * radius * segmentSweep) / 180;\n\n for (let i = 0; i < segmentCount; i++) {\n p.addSegment(startDeg + i * segmentSweep + 90, arcLength, 1, true);\n }\n p.endPlot(startDeg + sweepDeg + 90, 1, true);\n\n const startX = x + radius * cos(startDeg);\n const startY = y - radius * sin(startDeg);\n p.draw(startX, startY, 1);\n}\n\n// Variables for managing paths and strokes\nlet _current;\nlet _curvature;\n\nclass SubPath {\n constructor() {\n this.isClosed = false;\n this.curvature = _curvature;\n this.vert = [];\n }\n /**\n * Adds a vertex to this subpath.\n * @param {number} x\n * @param {number} y\n * @param {number} pressure\n */\n vertex(x, y, pressure) {\n this.vert.push([x, y, pressure]);\n }\n /**\n * Renders the subpath by creating a spline from its vertices.\n */\n show() {\n let plot = _createSpline(this.vert, this.curvature, this.isClosed);\n plot.show();\n }\n}\n\n/**\n * Begins a new path with a specified curvature.\n * @param {number} [curvature=0] - Curvature from 0 to 1.\n */\nexport function beginShape(curvature = 0) {\n _curvature = constrain(curvature, 0, 1);\n _current = new SubPath();\n}\n\n/**\n * Adds a line segment from the current point to the given coordinates.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} [pressure=1] - Pressure value.\n */\nexport function vertex(x, y, pressure = 1) {\n if (!_current) {\n throw new Error(\n \"vertex() called outside of beginShape()/endShape(). Call beginShape() first.\",\n );\n }\n _current.vertex(x, y, pressure);\n}\n\n/**\n * Ends the current path and renders all subpaths.\n */\nexport function endShape(close = false) {\n if (!_current) {\n throw new Error(\n \"endShape() called without beginShape(). Call beginShape() first.\",\n );\n }\n if (_current.vert.length < 2) {\n throw new Error(\n \"endShape() requires at least 2 vertices. Add more with vertex().\",\n );\n }\n if (close) {\n _current.vertex(..._current.vert[0]);\n _current.isClosed = true;\n }\n _current.show();\n _current = false;\n}\n\nlet _strokeArray, _strokeOrigin;\n\n/**\n * Begins a new stroke with a given type and starting position.\n * @param {string} type - Stroke type.\n * @param {number} x - Starting x.\n * @param {number} y - Starting y.\n */\nexport function beginStroke(type, x, y) {\n if (type !== \"curve\" && type !== \"segments\") {\n throw new Error(\n `beginStroke() type must be \"curve\" or \"segments\", got \"${type}\".`,\n );\n }\n _strokeOrigin = [x, y];\n _strokeArray = new Plot(type);\n}\n\n/**\n * Adds a segment to the stroke.\n * @param {number} angle - Segment angle.\n * @param {number} length - Segment length.\n * @param {number} pressure - Segment pressure.\n */\nexport function move(angle, length, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"move() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.addSegment(angle, length, pressure);\n}\n\n/**\n * Completes and renders the stroke.\n * @param {number} angle - End angle.\n * @param {number} pressure - End pressure.\n */\nexport function endStroke(angle, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"endStroke() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.endPlot(angle, pressure);\n _strokeArray.draw(_strokeOrigin[0], _strokeOrigin[1], 1);\n _strokeArray = false;\n}\n\n/**\n * Creates and draws a spline curve from an array of points.\n * @param {Array<Array<number>>} array_points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature from 0 to 1.\n */\nexport function spline(_array_points, _curvature = 0.5) {\n if (!_array_points || _array_points.length < 2) {\n throw new Error(\n \"spline() requires at least 2 points. Each point should be [x, y, pressure].\",\n );\n }\n let p = _createSpline(_array_points, _curvature);\n p.draw();\n}\n\n/**\n * Creates a new Plot object representing a spline curve.\n *\n * For curved segments (curvature > 0) with at least 3 points available,\n * the function either treats segments as straight (if their angles match)\n * or calculates control points to compute a circular arc.\n *\n * If no curvature is specified, a simple straight segment is used.\n *\n * @param {Array<Array<number>>} points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature value between 0 and 1.\n * @param {boolean} [close=false] - Whether to close the spline.\n * @returns {Plot} - The generated Plot object.\n */\nfunction _createSpline(points, curvature = 0.5, close = false) {\n const plotType = curvature === 0 ? \"segments\" : \"curve\";\n const p = new Plot(plotType);\n const PI2 = Math.PI * 2;\n\n // If closing the spline, add the second point to the end\n if (close && curvature !== 0) {\n points.push(points[1]);\n }\n\n if (points && points.length > 0) {\n let done = 0; // Tracks excess length from previous segment\n let pep, tep, pep2; // Variables used for initial calibration\n\n for (let i = 0; i < points.length - 1; i++) {\n // For curved segments (if curvature > 0 and there is at least 3 points ahead)\n if (curvature > 0 && i < points.length - 2) {\n const p1 = points[i];\n const p2 = points[i + 1];\n const p3 = points[i + 2];\n\n const d1 = dist(p1[0], p1[1], p2[0], p2[1]);\n const d2 = dist(p2[0], p2[1], p3[0], p3[1]);\n const a1 = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n const a2 = calcAngle(p2[0], p2[1], p3[0], p3[1]);\n\n // Compute the adjustment length based on curvature\n const curvAdjust = curvature * Math.min(d1, d2, 0.5 * Math.min(d1, d2));\n const dmax = Math.max(d1, d2);\n const s1 = d1 - curvAdjust;\n const s2 = d2 - curvAdjust;\n\n if (Math.floor(a1) === Math.floor(a2)) {\n // If angles are nearly the same, treat as a straight segment\n const temp = close ? (i === 0 ? 0 : d1 - done) : d1 - done;\n const temp2 = close ? (i === 0 ? 0 : d2 - pep2) : d2;\n\n p.addSegment(a1, temp, p1[2], true);\n if (i === points.length - 3) {\n p.addSegment(a2, temp2, p2[2], true);\n }\n\n done = 0;\n if (i === 0) {\n pep = d1;\n pep2 = curvAdjust;\n tep = points[1];\n done = 0;\n }\n } else {\n // For a curved segment, compute control points and arc segment details\n const point1 = {\n x: p2[0] - curvAdjust * cos(-a1),\n y: p2[1] - curvAdjust * sin(-a1),\n };\n const point2 = {\n x: point1.x + dmax * cos(-a1 + 90),\n y: point1.y + dmax * sin(-a1 + 90),\n };\n const point3 = {\n x: p2[0] + curvAdjust * cos(-a2),\n y: p2[1] + curvAdjust * sin(-a2),\n };\n const point4 = {\n x: point3.x + dmax * cos(-a2 + 90),\n y: point3.y + dmax * sin(-a2 + 90),\n };\n\n const intPt = intersectLines(point1, point2, point3, point4, true);\n const radius = dist(point1.x, point1.y, intPt.x, intPt.y);\n const halfDist = dist(point1.x, point1.y, point3.x, point3.y) / 2;\n const arcAngle = 2 * Math.asin(halfDist / radius) * (180 / Math.PI);\n const arcLength = (PI2 * radius * arcAngle) / 360;\n\n const temp = close ? (i === 0 ? 0 : s1 - done) : s1 - done;\n const temp2 =\n i === points.length - 3 ? (close ? pep - curvAdjust : s2) : 0;\n\n p.addSegment(a1, temp, p1[2], true);\n p.addSegment(a1, isNaN(arcLength) ? 0 : arcLength, p1[2], true);\n p.addSegment(a2, temp2, p2[2], true);\n\n done = curvAdjust;\n if (i === 0) {\n pep = s1;\n pep2 = curvAdjust;\n tep = [point1.x, point1.y];\n }\n }\n\n if (i === points.length - 3) {\n p.endPlot(a2, p2[2], true);\n }\n } else if (curvature === 0) {\n // If no curvature, add a simple straight segment\n const p1 = points[i];\n const p2 = points[i + 1];\n const d = dist(p1[0], p1[1], p2[0], p2[1]);\n const a = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n\n p.addSegment(a, d, p2[2], true);\n if (i === points.length - 2) {\n p.endPlot(a, 1, true);\n }\n }\n }\n\n p.origin = close && curvature !== 0 ? tep : points[0];\n }\n\n return p;\n}\n","import { State } from \"./color.js\";\nimport { intersectLines } from \"./utils.js\";\n\n// =============================================================================\n// Section: Polygon Class\n// =============================================================================\n\n/**\n * Represents a polygon with a set of vertices and provides methods for\n * intersection, drawing, filling, and hatching.\n */\nexport class Polygon {\n /**\n * Constructs the Polygon object from an array of points.\n * @param {Array} pointsArray - An array of points, where each point is an array of two numbers [x, y].\n * @param {boolean} [useRawVertices=false] - If true, uses the raw array as vertices.\n */\n constructor(pointsArray, useRawVertices = false) {\n this.a = pointsArray;\n this.vertices = useRawVertices\n ? pointsArray\n : pointsArray.map(([x, y]) => ({ x, y }));\n this.sides = this.vertices.map((v, i, arr) => [\n v,\n arr[(i + 1) % arr.length],\n ]);\n this._intersectionCache = {}; // Cache for intersection results\n }\n\n /**\n * Intersects a given line with the polygon, returning all intersection points.\n * @param {Object} line - The line to intersect with the polygon, having two properties 'point1' and 'point2'.\n * @returns {Array} An array of intersection points (each with 'x' and 'y' properties) or an empty array if no intersections.\n */\n intersect(line) {\n // Check if the result has been cached\n const cacheKey = `${line.point1.x},${line.point1.y}-${line.point2.x},${line.point2.y}`;\n if (this._intersectionCache[cacheKey]) {\n return this._intersectionCache[cacheKey];\n }\n const points = [];\n for (const [start, end] of this.sides) {\n const intersection = intersectLines(line.point1, line.point2, start, end);\n if (intersection) points.push(intersection);\n }\n this._intersectionCache[cacheKey] = points; // Cache the result\n return points;\n }\n\n /**\n * Displays the polygon with optional stroke, hatch, and fill effects.\n */\n show() {\n if (State.wash) this.wash();\n if (State.fill) this.fill();\n if (State.mass) this.mass();\n if (State.hatch) this.hatch();\n if (State.stroke) this.draw();\n }\n}","import { Cwidth, Cheight } from \"./target.js\";\nimport { State } from \"./color.js\";\nimport { toDegrees, map, rr2 } from \"./utils.js\";\nimport { Position, isFieldReady } from \"./flowfield.js\";\nimport { Polygon } from \"./polygon.js\";\n\n// =============================================================================\n// Section: Plot Class\n// =============================================================================\n\n/**\n * The Plot class represents a collection of segments that define shapes or paths.\n * It supports operations like adding segments, calculating angles and pressures,\n * and generating polygons based on the plot's structure.\n */\nexport class Plot {\n /**\n * Creates a new Plot.\n * @param {string} _type - The type of plot, \"curve\" or \"segments\".\n */\n constructor(_type) {\n this.segments = [];\n this.angles = [];\n this.pres = [];\n this.type = _type;\n this.dir = 0;\n this.calcIndex(0);\n this.pol = false;\n }\n\n /**\n * Adds a segment to the plot with specified angle, length, and pressure.\n * @param {number} _a - The angle of the segment.\n * @param {number} _length - The length of the segment.\n * @param {number} _pres - The pressure of the segment.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n addSegment(_a = 0, _length = 0, _pres = 1, _degrees = false) {\n if (this.angles.length > 0) this.angles.pop(); // Remove the last angle\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a); // Normalize angle\n this.angles.push(_a, _a); // Push angle twice for continuity\n this.pres.push(_pres);\n this.segments.push(_length);\n this.length = this.segments.reduce((sum, len) => sum + len, 0); // Update total length\n }\n\n /**\n * Finalizes the plot by setting the last angle and pressure.\n * @param {number} _a - The final angle.\n * @param {number} _pres - The final pressure.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n endPlot(_a = 0, _pres = 1, _degrees = false) {\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a);\n this.angles[this.angles.length - 1] = _a; // Update the last angle\n this.pres.push(_pres);\n }\n\n /**\n * Rotates the entire plot by a given angle.\n * @param {number} _a - The angle to rotate the plot.\n */\n rotate(_a) {\n this.dir = toDegrees(_a);\n }\n\n /**\n * Calculates the pressure at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated pressure.\n */\n pressure(_d) {\n // If the distance exceeds the plot length, return the last pressure\n if (_d > this.length) return this.pres[this.pres.length - 1];\n // Otherwise, calculate the pressure using the curving function\n return this.curving(this.pres, _d);\n }\n\n /**\n * Calculates the angle at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The calculated angle.\n */\n angle(_d) {\n // If the distance exceeds the plot length, return the last angle\n if (_d > this.length) return this.angles[this.angles.length - 1];\n // Calculate the index for the given distance\n this.calcIndex(_d);\n // Return the angle, adjusted for the plot type and direction\n return this.type === \"curve\"\n ? this.curving(this.angles, _d) + this.dir\n : this.angles[this.index] + this.dir;\n }\n\n /**\n * Interpolates values between segments for smooth transitions.\n * @param {Array<number>} array - The array to interpolate within.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated value.\n */\n curving(array, _d) {\n let map0 = array[this.index];\n let map1 = array[this.index + 1] ?? map0;\n if (Math.abs(map1 - map0) > 180) {\n if (map1 > map0) map1 = -(360 - map1);\n else map0 = -(360 - map0);\n }\n return map(_d - this.suma, 0, this.segments[this.index], map0, map1, true);\n }\n\n /**\n * Calculates the current index of the plot based on the distance.\n * @param {number} _d - The distance along the plot.\n */\n calcIndex(_d) {\n this.index = -1;\n this.suma = 0;\n let d = 0;\n while (d <= _d) {\n this.suma = d;\n d += this.segments[this.index + 1];\n this.index++;\n }\n return this.index;\n }\n\n /**\n * Generates a polygon based on the plot.\n * @param {number} _x - The x-coordinate for the starting point.\n * @param {number} _y - The y-coordinate for the starting point.\n * @param {number} _scale - The scale factor for the polygon.\n * @param {number} _side - The side factor for the polygon.\n * @returns {Polygon} - The generated polygon.\n */\n genPol(_x, _y, _scale = 1, _side) {\n isFieldReady(); // Ensure that the drawing environment is prepared\n const step = _side < 0 ? 4 : 1;\n const vertices = [];\n const numSteps = Math.round(this.length / step);\n const pos = new Position(_x + Cwidth / 2, _y + Cheight / 2);\n let pside = 0;\n let prevIdx = 0;\n\n for (let i = 0; i < numSteps; i++) {\n pos.plotTo(this, step, step);\n const idx = this.calcIndex(pos.plotted);\n pside += step;\n let maxSize = _side <= 0 ? 8 : Math.max(this.segments[idx] * _side * rr2(0.7, 1.3), 20);\n if ((pside >= maxSize || idx >= prevIdx) && pos.x) {\n vertices.push([pos.x - Cwidth / 2, pos.y - Cheight / 2]);\n pside = 0;\n if (idx >= prevIdx) prevIdx++;\n }\n }\n return new Polygon(vertices);\n }\n\n /**\n * Displays the plot with optional stroke, hatch, and fill effects.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\n show(x, y, scale = 1) {\n if (State.wash) this.wash(x, y, scale);\n if (State.fill) this.fill(x, y, scale);\n if (State.mass) this.mass(x, y, scale);\n if (State.hatch) this.hatch(x, y, scale);\n if (State.stroke) this.draw(x, y, scale);\n }\n}\n","// =============================================================================\n// Stroke Runtime Hooks\n// =============================================================================\n\nlet strokeRuntime = {\n createTipSurface: () => {\n throw new Error(\"No stroke runtime adapter registered.\");\n },\n loadImageTip: () => {\n throw new Error(\"No stroke runtime adapter registered.\");\n },\n};\n\n/**\n * Registers or updates host stroke hooks used by brush-tip loading code.\n *\n * @param {object} hooks\n */\nexport function setStrokeRuntime(hooks) {\n strokeRuntime = { ...strokeRuntime, ...hooks };\n}\n\nexport const createTipSurface = (width, height) =>\n strokeRuntime.createTipSurface(width, height);\nexport const loadImageTip = (src, imageToWhite) =>\n strokeRuntime.loadImageTip(src, imageToWhite);\n","import * as Color from \"../core/color.js\";\nimport { createFramebuffer } from \"../core/compositor_runtime.js\";\n\nlet isStrokeCompositeRegistered = false;\nconst DIRTY_BRUSH_PADDING = 2;\n\n// =============================================================================\n// Section: Helpers\n// =============================================================================\n/**\n * Returns whether the current stroke mask framebuffer must be recreated.\n * This happens when the renderer has no mask yet, or when the canvas size or\n * pixel density changed since the last allocation.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {boolean} True when the stroke mask must be rebuilt.\n */\nfunction needsStrokeMask(Renderer, Cwidth, Cheight, Density) {\n return (\n !Renderer.glMask ||\n Renderer.glMask.width !== Cwidth ||\n Renderer.glMask.height !== Cheight ||\n (typeof Renderer.glMask.pixelDensity === \"function\" &&\n Renderer.glMask.pixelDensity() !== Density)\n );\n}\n\n// =============================================================================\n// Section: Resource Management\n// =============================================================================\n/**\n * Ensures the stroke compositor owns a framebuffer-backed mask with the current\n * canvas dimensions. Stroke stamps are rendered into this mask in WebGL before\n * being blended into the main target.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {object} The framebuffer used as stroke mask.\n */\nexport function ensureStrokeCompositeResources(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n) {\n if (needsStrokeMask(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.glMask?.remove) Renderer.glMask.remove();\n Renderer.glMask = createFramebuffer(Renderer, {\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n }\n\n Renderer.glMask.dirtyRect ??= null;\n Renderer.glMask.isDrawn ??= false;\n return Renderer.glMask;\n}\n\n// =============================================================================\n// Section: Mask Lifecycle\n// =============================================================================\n/**\n * Clears the current stroke mask and resets its bookkeeping flags.\n *\n * @param {object|null} target - Stroke mask framebuffer.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n */\nexport function clearStrokeMask(target, clearTarget) {\n if (!target) return;\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\n}\n\n// =============================================================================\n// Section: Composite Bounds\n// =============================================================================\n/**\n * Returns the rect that should be composited from the stroke mask into the\n * main canvas. Stroke bounds are normally tight dirty rects, but when drawing\n * into an active framebuffer we keep the result conservative and composite the\n * full target.\n *\n * @param {object|null} target - Stroke mask framebuffer.\n * @param {Function} getActiveFramebuffer - Returns the currently bound framebuffer.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} expandDirtyRect - Expands a rect by a constant padding.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @param {number} padding - Extra brush padding in pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\nexport function getStrokeCompositeRect(\n target,\n getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n if (getActiveFramebuffer()) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(target.dirtyRect, DIRTY_BRUSH_PADDING),\n );\n}\n\n/**\n * Returns the resource that should be bound to the blend shader's `u_mask`\n * uniform for stroke compositing.\n *\n * @param {object} _Renderer - Active host renderer.\n * @param {object} mask - Stroke mask framebuffer.\n * @returns {object} Stroke mask framebuffer.\n */\nexport function getStrokeShaderMask(_Renderer, mask) {\n return mask;\n}\n\n// =============================================================================\n// Section: Registration\n// =============================================================================\n/**\n * Registers the stroke compositor with the shared color/composite core.\n * Safe to call multiple times.\n */\nexport function initStrokeComposite() {\n if (isStrokeCompositeRegistered) return;\n Color.registerStrokeComposite?.({\n ensureResources: ensureStrokeCompositeResources,\n clearMask: clearStrokeMask,\n getCompositeRect: getStrokeCompositeRect,\n getShaderMask: getStrokeShaderMask,\n });\n isStrokeCompositeRegistered = true;\n}\n","/**\n * Compiles a shader program from the given vertex and fragment sources.\n * @param {WebGL2RenderingContext} gl - The WebGL2 context.\n * @param {string} vert - Vertex shader source.\n * @param {string} frag - Fragment shader source.\n * @returns {WebGLProgram} The compiled and linked program.\n */\nexport const createProgram = (gl, vert, frag) => {\n const p = gl.createProgram();\n for (let [t, src] of [\n [gl.VERTEX_SHADER, vert],\n [gl.FRAGMENT_SHADER, frag],\n ]) {\n const s = gl.createShader(t);\n gl.shaderSource(s, src);\n gl.compileShader(s);\n gl.attachShader(p, s);\n }\n gl.linkProgram(p);\n return p;\n};\n","// =============================================================================\n// Renderer Runtime Hooks\n// =============================================================================\n\n/**\n * Direct-render hooks used by modules that issue raw WebGL commands.\n *\n * These hooks are intentionally narrow:\n * - begin drawing into an offscreen GL mask target\n * - restore the previous draw target afterward\n * - reset any host-side shader/program bookkeeping after direct GL usage\n */\n\nlet rendererRuntime = {\n beginDirectMaskDraw: () => {\n throw new Error(\"No renderer runtime adapter registered.\");\n },\n endDirectMaskDraw: () => {\n throw new Error(\"No renderer runtime adapter registered.\");\n },\n resetDirectShaderTracking: () => {},\n};\n\n/**\n * Registers or updates host renderer hooks used by direct WebGL drawing paths.\n *\n * @param {object} hooks\n */\nexport function setRendererRuntime(hooks) {\n rendererRuntime = { ...rendererRuntime, ...hooks };\n}\n\nexport const beginDirectMaskDraw = (renderer, gl, target) =>\n rendererRuntime.beginDirectMaskDraw(renderer, gl, target);\nexport const endDirectMaskDraw = (renderer, gl, state) =>\n rendererRuntime.endDirectMaskDraw(renderer, gl, state);\nexport const resetDirectShaderTracking = (renderer, gl) =>\n rendererRuntime.resetDirectShaderTracking(renderer, gl);\n","// =============================================================================\n// Module: GL Draw\n// =============================================================================\n/**\n * The GL Draw module batches brush primitives for WebGL2 rendering. It initializes\n * the shader programs and buffers used by circle-based brushes and image-tip brushes,\n * then flushes those queues into the shared framebuffer-backed brush mask.\n */\n\nimport { Cwidth, Cheight, Density, Renderer } from \"../core/target.js\";\nimport {\n Mix,\n isMixReady,\n State,\n} from \"../core/color.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport {\n beginDirectMaskDraw,\n endDirectMaskDraw,\n resetDirectShaderTracking,\n} from \"../core/renderer_runtime.js\";\nimport { getAffineMatrix } from \"../core/runtime.js\";\nimport vertSrc from \"./shader.vert\";\nimport fragSrc from \"./shader.frag\";\nimport imgVertSrc from \"./image.vert\";\nimport imgFragSrc from \"./image.frag\";\n\n// =============================================================================\n// Section: Initialization and Setup\n// =============================================================================\n\n// Module state\nlet isLoaded = false,\n gl,\n framebufferProjMatrix,\n vao,\n buf,\n program;\nlet loadedWidth = 0,\n loadedHeight = 0;\nlet brushMaskTarget = null;\nconst Attr = {},\n Frag = {};\n\n// Cached matrix values — snapshotted once per stroke in snapshotMatrix()\nlet _ma = 1,\n _mb = 0,\n _mc = 0,\n _md = 1,\n _mx = 0,\n _my = 0,\n _halfW = 0,\n _halfH = 0,\n _scale = 1,\n _density = 1;\n\n/**\n * Snapshots the current runtime affine transform. Call once at the start of each stroke.\n */\nexport function snapshotMatrix() {\n const m = getAffineMatrix();\n _ma = m.a;\n _mb = m.b;\n _mc = m.c;\n _md = m.d;\n _mx = m.x;\n _my = m.y;\n _halfW = Cwidth / 2;\n _halfH = Cheight / 2;\n _scale = Math.sqrt(_ma * _ma + _mb * _mb);\n _density = Density;\n}\n\n// Pre-allocated flat buffer for circle data (x, y, radius, alpha per circle)\nconst INITIAL_CAPACITY = 2048;\nlet circleData = new Float32Array(INITIAL_CAPACITY * 4);\nlet circleCount = 0;\nlet bufferCapacity = INITIAL_CAPACITY;\nlet gpuBufferSize = INITIAL_CAPACITY * 4 * 4; // bytes allocated on GPU\nlet circleDirtyRect = null;\n\n// ---------------------------------------------------------------------------\n// Image instancing state\n// ---------------------------------------------------------------------------\nlet imgProgram = null;\nlet imgVao = null;\nlet imgCornerBuf = null;\nlet imgInstanceBuf = null;\nconst imgAttr = {};\nconst imgFrag = {};\nlet imgGpuSize = 0;\n\nconst IMG_FLOATS = 5; // screenX, screenY, halfSize, angle, alpha — per stamp\nconst IMG_INIT_CAP = 256;\nlet imgData = new Float32Array(IMG_INIT_CAP * IMG_FLOATS);\nlet imgCount = 0;\nlet imgCapacity = IMG_INIT_CAP;\nlet imgDirtyRect = null;\n\n// Texture cache: src string → WebGLTexture (cleared whenever the GL context changes)\nconst texCache = new Map();\n\n// Static unit-quad corners for gl.TRIANGLE_STRIP in quad-local space.\nconst QUAD_CORNERS = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]);\n\nfunction ensureBrushMaskTarget() {\n const rendererMask = Renderer?.glMask;\n if (!rendererMask) return null;\n brushMaskTarget = rendererMask;\n brushMaskTarget.dirtyRect ??= null;\n brushMaskTarget.isDrawn ??= false;\n Mix.glMask = brushMaskTarget;\n return brushMaskTarget;\n}\n\nfunction getProjectionMatrix() {\n return framebufferProjMatrix;\n}\n\nfunction beginMaskTarget() {\n return beginDirectMaskDraw(Renderer, gl, Mix.glMask);\n}\n\nfunction endMaskTarget(state) {\n endDirectMaskDraw(Renderer, gl, state);\n}\n\nfunction accumulateDirtyRect(currentRect, minX, minY, maxX, maxY) {\n if (!currentRect) return { minX, minY, maxX, maxY };\n if (minX < currentRect.minX) currentRect.minX = minX;\n if (minY < currentRect.minY) currentRect.minY = minY;\n if (maxX > currentRect.maxX) currentRect.maxX = maxX;\n if (maxY > currentRect.maxY) currentRect.maxY = maxY;\n return currentRect;\n}\n\n/**\n * Initializes WebGL objects if not done already.\n */\nexport function isReady() {\n isMixReady();\n ensureBrushMaskTarget();\n\n const nextGl = Renderer.drawingContext;\n const needsContextRefresh = !isLoaded || gl !== nextGl;\n const needsProjectionRefresh =\n needsContextRefresh || loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (needsProjectionRefresh) {\n framebufferProjMatrix = new Float32Array([\n 2 / Cwidth,\n 0,\n 0,\n 0,\n 0,\n 2 / Cheight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n -1,\n 0,\n 1,\n ]);\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n }\n\n if (!needsContextRefresh) return;\n\n gl = nextGl;\n\n // Create shader program and initialize\n program = createProgram(gl, vertSrc, fragSrc);\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n // Cache attribute and uniform locations\n [\"a_position\", \"a_radius\", \"a_alpha\"].forEach(\n (n) => (Attr[n] = gl.getAttribLocation(program, n)),\n );\n [\"u_matrix\", \"u_color\"].forEach(\n (n) => (Frag[n] = gl.getUniformLocation(program, n)),\n );\n\n // Create persistent VAO and VBO\n vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n\n buf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n gl.bufferData(gl.ARRAY_BUFFER, circleData.byteLength, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n\n // Set up vertex attributes (only needs to happen once with persistent VAO)\n const stride = 16; // 4 floats × 4 bytes\n gl.enableVertexAttribArray(Attr.a_position);\n gl.vertexAttribPointer(Attr.a_position, 2, gl.FLOAT, false, stride, 0);\n gl.enableVertexAttribArray(Attr.a_radius);\n gl.vertexAttribPointer(Attr.a_radius, 1, gl.FLOAT, false, stride, 8);\n gl.enableVertexAttribArray(Attr.a_alpha);\n gl.vertexAttribPointer(Attr.a_alpha, 1, gl.FLOAT, false, stride, 12);\n\n gl.bindVertexArray(null);\n\n // ------------------------------------------------------------------\n // Image-tip instancing program\n // ------------------------------------------------------------------\n texCache.clear();\n\n imgProgram = createProgram(gl, imgVertSrc, imgFragSrc);\n [\"a_corner\", \"a_pos\", \"a_size\", \"a_angle\", \"a_alpha\"].forEach(\n (n) => (imgAttr[n] = gl.getAttribLocation(imgProgram, n)),\n );\n [\"u_proj\", \"u_color\", \"u_tex\"].forEach(\n (n) => (imgFrag[n] = gl.getUniformLocation(imgProgram, n)),\n );\n\n imgVao = gl.createVertexArray();\n gl.bindVertexArray(imgVao);\n\n // Static corner VBO (per-vertex, no divisor)\n imgCornerBuf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, imgCornerBuf);\n gl.bufferData(gl.ARRAY_BUFFER, QUAD_CORNERS, gl.STATIC_DRAW);\n gl.enableVertexAttribArray(imgAttr.a_corner);\n gl.vertexAttribPointer(imgAttr.a_corner, 2, gl.FLOAT, false, 0, 0);\n\n // Instance data VBO (per-instance)\n imgInstanceBuf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, imgInstanceBuf);\n gl.bufferData(gl.ARRAY_BUFFER, imgData.byteLength, gl.DYNAMIC_DRAW);\n imgGpuSize = imgData.byteLength;\n\n const istride = IMG_FLOATS * 4; // 20 bytes\n gl.enableVertexAttribArray(imgAttr.a_pos);\n gl.vertexAttribPointer(imgAttr.a_pos, 2, gl.FLOAT, false, istride, 0);\n gl.vertexAttribDivisor(imgAttr.a_pos, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_size);\n gl.vertexAttribPointer(imgAttr.a_size, 1, gl.FLOAT, false, istride, 8);\n gl.vertexAttribDivisor(imgAttr.a_size, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_angle);\n gl.vertexAttribPointer(imgAttr.a_angle, 1, gl.FLOAT, false, istride, 12);\n gl.vertexAttribDivisor(imgAttr.a_angle, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_alpha);\n gl.vertexAttribPointer(imgAttr.a_alpha, 1, gl.FLOAT, false, istride, 16);\n gl.vertexAttribDivisor(imgAttr.a_alpha, 1);\n\n gl.bindVertexArray(null);\n\n isLoaded = true;\n}\n\n// =============================================================================\n// Section: Drawing Primitives\n// =============================================================================\n\n/**\n * Queue a circle to be drawn with the specified parameters.\n * Data is written directly into a flat Float32Array to avoid object allocation.\n * Applies the full 2D affine transform (rotation + scale + translation) from\n * the current runtime transform so that brush.rotate() and brush.scale() work correctly.\n */\nexport function circle(x, y, diameter, alpha) {\n // Grow buffer if needed\n if (circleCount >= bufferCapacity) {\n bufferCapacity *= 2;\n const newData = new Float32Array(bufferCapacity * 4);\n newData.set(circleData);\n circleData = newData;\n }\n\n // x/y arrive in \"position space\": user coords + (Cwidth/2, Cheight/2).\n // Subtract the offset to recover user coords, apply the full matrix, then re-add\n // the offset so the result is in screen pixel space [0..Cwidth, 0..Cheight].\n const px = x - _halfW;\n const py = y - _halfH;\n\n const offset = circleCount * 4;\n const screenX = _ma * px + _mc * py + _mx + _halfW;\n const screenY = _mb * px + _md * py + _my + _halfH;\n const radius = (_density * diameter * _scale) / 2;\n\n circleData[offset] = screenX;\n circleData[offset + 1] = screenY;\n // Scale the diameter by the matrix's scale factor (length of the transformed x-axis)\n circleData[offset + 2] = radius;\n circleData[offset + 3] = alpha / 255;\n\n const dScreenX = screenX * _density;\n const dScreenY = screenY * _density;\n circleDirtyRect = accumulateDirtyRect(\n circleDirtyRect,\n dScreenX - radius - 1,\n dScreenY - radius - 1,\n dScreenX + radius + 1,\n dScreenY + radius + 1,\n );\n\n circleCount++;\n}\n\n/**\n * Queue an image stamp to be drawn with instanced rendering.\n * Accepts the same coordinate conventions as circle(): x/y in position space\n * (user coords + Cwidth/2, Cheight/2), size in user-coord units, alpha in [0..255].\n * @param {number} x - X in position space.\n * @param {number} y - Y in position space.\n * @param {number} size - Full stamp diameter in user-coord units.\n * @param {number} angle - Rotation in radians.\n * @param {number} alpha - Opacity [0..255].\n * @param {number} [extraPadding=0] - Conservative extra padding in user units.\n */\nexport function stampImage(x, y, size, angle, alpha, extraPadding = 0) {\n if (imgCount >= imgCapacity) {\n imgCapacity *= 2;\n const next = new Float32Array(imgCapacity * IMG_FLOATS);\n next.set(imgData);\n imgData = next;\n }\n\n const px = x - _halfW;\n const py = y - _halfH;\n const screenX = _ma * px + _mc * py + _mx + _halfW;\n const screenY = _mb * px + _md * py + _my + _halfH;\n const halfSize = (_density * size * _scale) / 2;\n const extraRadius = _density * extraPadding * _scale;\n\n const base = imgCount * IMG_FLOATS;\n imgData[base] = screenX;\n imgData[base + 1] = screenY;\n imgData[base + 2] = halfSize;\n imgData[base + 3] = angle;\n imgData[base + 4] = alpha / 255;\n\n // Bounding box: rotated square worst-case = circle of radius halfSize * √2\n const dScreenX = screenX * _density;\n const dScreenY = screenY * _density;\n const boundsRadius = halfSize * 1.42 + extraRadius;\n imgDirtyRect = accumulateDirtyRect(\n imgDirtyRect,\n dScreenX - boundsRadius - 1,\n dScreenY - boundsRadius - 1,\n dScreenX + boundsRadius + 1,\n dScreenY + boundsRadius + 1,\n );\n\n imgCount++;\n}\n\n/**\n * Flush all queued image stamps in a single instanced draw call.\n * @param {object} p5img - The preprocessed brush-tip image/canvas (from T.tips).\n * @param {string} src - The image src string, used as the texture cache key.\n */\nexport function glDrawImages(p5img, src) {\n if (imgCount === 0) return;\n\n Mix.glMask.isDrawn = true;\n const targetState = beginMaskTarget();\n\n // Lazy-create the WebGL texture from the tip canvas on first use.\n let tex = texCache.get(src);\n if (!tex) {\n tex = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, p5img.canvas);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n texCache.set(src, tex);\n }\n\n gl.useProgram(imgProgram);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.uniform1i(imgFrag.u_tex, 0);\n\n const color = State.stroke.color._array;\n gl.uniform4f(imgFrag.u_color, ...color);\n gl.uniformMatrix4fv(imgFrag.u_proj, false, getProjectionMatrix());\n\n gl.bindVertexArray(imgVao);\n gl.bindBuffer(gl.ARRAY_BUFFER, imgInstanceBuf);\n\n const byteCount = imgCount * IMG_FLOATS * 4;\n const dataView = imgData.subarray(0, imgCount * IMG_FLOATS);\n if (byteCount > imgGpuSize) {\n gl.bufferData(gl.ARRAY_BUFFER, imgData, gl.DYNAMIC_DRAW);\n imgGpuSize = imgData.byteLength;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);\n }\n\n gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, imgCount);\n gl.flush();\n\n gl.bindVertexArray(null);\n gl.bindTexture(gl.TEXTURE_2D, null);\n endMaskTarget(targetState);\n\n if (imgDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, imgDirtyRect);\n imgDirtyRect = null;\n }\n\n imgCount = 0;\n\n // Let the host adapter know we changed the active program.\n resetDirectShaderTracking(Renderer, gl);\n}\n\n/**\n * Removes a cached GL texture by key, forcing re-upload on next draw.\n * Call this when a custom tip function changes after brush.add().\n */\nexport function invalidateTexEntry(key) {\n const tex = texCache.get(key);\n if (tex && gl) gl.deleteTexture(tex);\n texCache.delete(key);\n}\n\n/**\n * Draw all queued circles using WebGL\n */\nexport function glDraw() {\n if (circleCount === 0) return;\n\n Mix.glMask.isDrawn = true;\n const targetState = beginMaskTarget();\n\n const color = State.stroke.color._array;\n\n // Re-activate our shader in case host drawing switched programs.\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n gl.bindVertexArray(vao);\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n\n // Upload vertex data — reallocate GPU buffer only if needed\n const byteCount = circleCount * 16; // 4 floats × 4 bytes\n const dataView = circleData.subarray(0, circleCount * 4);\n if (byteCount > gpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, circleData, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);\n }\n\n // Set uniforms and draw\n gl.uniform4f(Frag.u_color, ...color);\n gl.uniformMatrix4fv(Frag.u_matrix, false, getProjectionMatrix());\n gl.drawArrays(gl.POINTS, 0, circleCount);\n gl.flush();\n\n gl.bindVertexArray(null);\n endMaskTarget(targetState);\n\n if (circleDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, circleDirtyRect);\n circleDirtyRect = null;\n }\n\n // Reset queue (no deallocation)\n circleCount = 0;\n\n // We called gl.useProgram() directly, bypassing host shader tracking.\n // Reset it so the host is forced to re-activate its own shader next time\n // it draws — otherwise it may skip gl.useProgram() and set uniforms on the\n // wrong active program, causing \"location is not from the associated program\".\n resetDirectShaderTracking(Renderer, gl);\n}\n","// =============================================================================\n// Module: Brush\n// =============================================================================\n/**\n * The Brush module provides a comprehensive set of functions and classes for\n * simulating various drawing tools ranging from pens, markers, pencils, to\n * custom image-based brushes. This module controls brush properties such as\n * weight, color, vibration, and spacing, and manages the drawing process through\n * stateful methods that enable features like pressure sensitivity, clipping, and\n * blending. By supporting multiple brush types and dynamic parameter adjustments,\n * the Brush module facilitates the creation of realistic and expressive stroke effects.\n */\n\n// Core imports\nimport { Cwidth, Cheight, Renderer, isCanvasReady } from \"../core/target.js\";\nimport {\n Mix,\n State,\n} from \"../core/color.js\";\nimport {\n rr,\n map,\n dist,\n randInt,\n calcAngle,\n toDegrees,\n gaussian,\n rArray,\n noise,\n _onSeed, \n cos,\n sin\n} from \"../core/utils.js\";\nimport { createColor } from \"../core/runtime.js\";\nimport { Position, isFieldReady } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { createTipSurface, loadImageTip } from \"./runtime.js\";\n\n// Internal module imports\nimport { initStrokeComposite } from \"./composite.js\";\nimport {\n isReady,\n glDraw,\n glDrawImages,\n circle,\n stampImage,\n invalidateTexEntry,\n snapshotMatrix,\n} from \"./gl_draw.js\";\n\ninitStrokeComposite(); // Register the stroke composite system for offscreen mask rendering and compositing.\n\n// ---------------------------------------------------------------------------\n// Brush State and Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Global stroke state settings.\n */\nState.stroke = {\n color: null,\n weight: 1,\n type: \"HB\",\n isActive: false,\n opacity: 1,\n};\n\nlet list = new Map();\n\nconst DEFAULT_CUSTOM_PRESSURE_VARIATION = {\n offset: 0.08,\n scale: 0.08,\n warp: 0.06,\n tilt: 0.06,\n};\n\n/**\n * Retrieves a shallow copy of the current stroke state.\n * @returns {object} The stroke state.\n */\nexport function BrushState() {\n return { ...State.stroke };\n}\n\n/**\n * Updates the stroke state.\n * @param {object} state - The new stroke state.\n */\nexport function BrushSetState(state) {\n State.stroke = { ...state };\n}\n\n// =============================================================================\n// Section: Brush Manager\n// =============================================================================\n\n/**\n * Adds a new brush with the specified parameters to the brush list.\n * @param {string} name - The unique name for the new brush.\n * @param {object} params - The parameters defining the brush behavior and appearance.\n */\n/**\n * Normalizes the pressure parameter to the internal { type, min_max, curve } format.\n * Accepts:\n * [start, end] — linear ramp between two pressure values\n * [start, mid, end] — piecewise linear (e.g. [1.5, 0.5, 1.5] for U-curve)\n * (t) => value — custom function, t ∈ [0,1], return value ∈ [0,1]\n * { mode: \"gaussian\", curve, min_max } — advanced built-in pressure profile\n * { curve, min_max } — legacy gaussian format, preserved for compatibility\n */\nexport function normalizePressure(p) {\n if (!p) return p;\n if (typeof p === \"function\")\n return {\n type: \"custom\",\n min_max: [0, 1],\n curve: p,\n variation: { ...DEFAULT_CUSTOM_PRESSURE_VARIATION },\n };\n if (typeof p === \"object\" && !Array.isArray(p)) {\n if (p.type === \"custom\" || p.mode === \"custom\") {\n const { mode, ...rest } = p;\n return {\n ...rest,\n type: \"custom\",\n variation: {\n ...DEFAULT_CUSTOM_PRESSURE_VARIATION,\n ...(rest.variation ?? {}),\n },\n };\n }\n if (\n p.type === \"gaussian\" ||\n p.mode === \"gaussian\" ||\n (Array.isArray(p.curve) && Array.isArray(p.min_max))\n ) {\n return {\n ...p,\n type: \"gaussian\",\n curve: p.curve,\n min_max: p.min_max,\n };\n }\n return p;\n }\n if (Array.isArray(p)) {\n const [s, m, e] = p.length === 2 ? [p[0], (p[0] + p[1]) / 2, p[1]] : p;\n const min = Math.min(s, m, e),\n max = Math.max(s, m, e);\n const range = max - min || 1;\n const [ns, nm, ne] = [\n (s - min) / range,\n (m - min) / range,\n (e - min) / range,\n ];\n return {\n type: \"custom\",\n min_max: [min, max],\n variation: { ...DEFAULT_CUSTOM_PRESSURE_VARIATION },\n curve: (t) =>\n t < 0.5 ? ns + (nm - ns) * t * 2 : nm + (ne - nm) * (t - 0.5) * 2,\n };\n }\n}\n\nexport function add(name, params) {\n const validTypes = [\"marker\", \"custom\", \"image\", \"spray\"];\n params.type = validTypes.includes(params.type) ? params.type : \"default\";\n if (params.markerTip === undefined) params.markerTip = true;\n if (params.noise === undefined) params.noise = 0.3;\n params.noise = Math.max(0, Math.min(1, params.noise));\n // Accept legacy param names for backward compatibility\n if (params.vibration !== undefined && params.scatter === undefined)\n params.scatter = params.vibration;\n if (params.definition !== undefined && params.sharpness === undefined)\n params.sharpness = params.definition;\n if (params.quality !== undefined && params.grain === undefined)\n params.grain = params.quality;\n params.pressure = normalizePressure(params.pressure);\n if (params.type === \"custom\") {\n if (typeof params.tip !== \"function\") {\n throw new Error(`Brush \"${name}\" is type \"custom\" but is missing a tip function.`);\n }\n // Rasterise the tip once into a 500×500 P2D buffer.\n // Users draw in a 100×100 coordinate space (origin at centre);\n // dark fills/strokes → high opacity, light/white → transparent.\n const key = `custom::${name}`;\n invalidateTexEntry(key); // discard stale GPU texture if tip changed\n const g = createTipSurface(500, 500);\n g.pixelDensity(1);\n g.background(255);\n g.noSmooth();\n g.push();\n g.translate(250, 250); // centre origin\n g.scale(5); // 100 user units → 500 px\n g.noStroke();\n params.tip(g);\n g.pop();\n T.imageToWhite(g); // dark → high alpha, RGB → white for tint\n T.tips.set(key, g);\n params.tipKey = key;\n list.set(name, { param: params, colors: [], buffers: [] });\n return;\n }\n if (params.type === \"image\") {\n if (!params.image || !params.image.src) {\n throw new Error(\n `Brush \"${name}\" is type \"image\" but is missing params.image.src. Example: image: { src: \"./tip.jpg\" }`,\n );\n }\n T.add(params.image.src);\n list.set(name, { param: params, colors: [], buffers: [] });\n return T.load(); // returns a Promise; only loads images not yet loaded\n }\n list.set(name, { param: params, colors: [], buffers: [] });\n}\n\n/**\n * Retrieves the list of available brush names.\n * @returns {Array<string>} Array of brush names.\n */\nexport function box() {\n return [...list.keys()];\n}\n\nexport function getBrushParams(brushName) {\n return list.get(brushName)?.param ?? null;\n}\n\n/**\n * Scales standard brush parameters by the provided factor.\n * @param {number} scaleFactor - The scaling factor to apply.\n */\nexport function scaleBrushes(scaleFactor) {\n for (const { param } of list.values()) {\n if (param) {\n param.weight *= scaleFactor;\n param.scatter *= scaleFactor;\n param.spacing *= scaleFactor;\n }\n }\n}\n\n/**\n * Sets the current brush type by name.\n * @param {string} brushName - The name of the brush.\n */\nexport function pick(brushName) {\n if (!list.has(brushName)) {\n throw new Error(\n `Brush \"${brushName}\" not found. Available brushes: ${[...list.keys()].join(\", \")}.`,\n );\n }\n State.stroke.type = brushName;\n}\n\n/**\n * Sets the stroke style (color) for the current brush.\n * @param {number|string|Color} r - Red component, CSS color string, or Color object.\n * @param {number} [g] - Green component.\n * @param {number} [b] - Blue component.\n */\nexport function stroke(r, g, b) {\n isCanvasReady();\n State.stroke.color = createColor(...arguments);\n State.stroke.isActive = true;\n}\n\n/**\n * Sets the brush weight (thickness).\n * @param {number} weight - The weight value.\n */\nexport function strokeWeight(weight) {\n State.stroke.weight = weight;\n}\n\n/**\n * Sets the current brush with name, color, and weight.\n * @param {string} brushName - The brush name.\n * @param {string|Color} color - The brush color.\n * @param {number} [weight=1] - The brush weight.\n */\nexport function set(brushName, color, weight = 1) {\n pick(brushName);\n stroke(color);\n strokeWeight(weight);\n}\n\n/**\n * Disables the stroke effect.\n */\nexport function noStroke() {\n State.stroke.isActive = false;\n}\n\n/**\n * Defines a clipping region for strokes.\n * The region uses the same coordinate space as brush drawing commands,\n * with the current runtime transform captured at call time.\n * @param {number[]} region - Array as [x1, y1, x2, y2] defining the clipping region.\n */\nexport function clip(region) {\n isCanvasReady();\n return region;\n}\n\n/**\n * Disables the clipping region.\n */\nexport function noClip() {\n return;\n}\n\n// ---------------------------------------------------------------------------\n// Drawing Variables and Functions\n// ---------------------------------------------------------------------------\nlet _position, _length, _plot, _dir;\nconst current = {};\n\n/**\n * Initializes the drawing state.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of stroke.\n * @param {Plot|false} [plot=false] - Plot object for path-following strokes.\n */\nfunction initializeDrawingState(x, y, length, plot = false) {\n snapshotMatrix();\n _position = new Position(x + Cwidth / 2, y + Cheight / 2);\n _length = length;\n _plot = plot;\n if (_plot) _plot.calcIndex(0);\n}\n\nconst gaussians = [];\n\n_onSeed(() => {\n gaussians.length = 0;\n});\n\n/**\n * Executes the drawing operation.\n * @param {number} angleScale - Angle (in degrees) or scaling factor.\n * @param {boolean} isPlot - True if plotting a shape.\n */\nfunction draw(angleScale, isPlot) {\n if (!isPlot) _dir = angleScale;\n saveState();\n\n const stepSize = spacing();\n const totalSteps = Math.round(\n (_length * (isPlot ? angleScale : 1)) / stepSize,\n );\n current.pressureCount = 10;\n current.cachedPressure = undefined;\n current.lineNoiseCount = 5;\n current.cachedLineNoise = undefined;\n\n for (let i = 0; i < totalSteps; i++) {\n if (gaussians.length < totalSteps * 2) {\n gaussians.push(gaussian());\n }\n tip();\n if (isPlot) {\n _position.plotTo(\n _plot,\n stepSize,\n stepSize,\n angleScale,\n i < 10 ? true : false,\n );\n } else {\n _position._moveToDegrees(angleScale, stepSize, stepSize);\n }\n }\n restoreState();\n}\n\n/**\n * Prepares the environment for a brush stroke.\n */\nfunction saveState() {\n current.seed = rr() * 999999;\n const { param } = list.get(State.stroke.type) ?? {};\n if (!param) return;\n current.p = param;\n\n // Set pressure values for the stroke\n const { pressure } = param;\n current.a = pressure.type !== \"custom\" ? rr(-1, 1) : 0;\n current.b = pressure.type !== \"custom\" ? rr(1, 1.5) : 0;\n if (pressure.type !== \"custom\") {\n current.cp = rr(3, 3.5);\n current.ct = 0;\n current.cs = 1;\n current.ck = 0;\n } else {\n const variation = pressure.variation ?? DEFAULT_CUSTOM_PRESSURE_VARIATION;\n current.cp = rr(-variation.offset, variation.offset);\n current.ct = rr(-variation.warp, variation.warp);\n current.cs = rr(1 - variation.scale, 1 + variation.scale);\n current.ck = rr(-variation.tilt, variation.tilt);\n }\n [current.min, current.max] = pressure.min_max;\n\n current.noiseoffset = 0.05 * current.p.noise;\n\n // Cache stroke direction for direction-aware dispersion (non-plot strokes only)\n if (!_plot) {\n current.cos = cos(_dir);\n current.sin = sin(_dir);\n }\n\n // Ensure GL is ready and blend state\n isReady();\n const switchingToBrush = Mix.isBrush !== true;\n Mix.isBrush = true;\n if (switchingToBrush) Mix.justChanged = true;\n Mix.blend(State.stroke.color);\n\n // Set additional state values\n current.alpha = calculateAlpha();\n\n markerTip();\n}\n\n/**\n * Restores drawing state after completing a stroke.\n */\nfunction restoreState() {\n markerTip();\n glDraw();\n const type = current.p?.type;\n if (type === \"image\") glDrawImages(T.tips.get(current.p.image.src), current.p.image.src);\n else if (type === \"custom\") glDrawImages(T.tips.get(current.p.tipKey), current.p.tipKey);\n}\n\n/**\n * Renders the brush tip based on current pressure and position.\n */\nfunction tip() {\n const pressure = calculatePressure();\n const lineNoise = calculateLineNoise();\n\n if (lineNoise > rr(1,1.02) && rr(0,1) < 0.7) return;\n switch (current.p.type) {\n case \"spray\":\n drawSpray(pressure * lineNoise);\n break;\n case \"marker\":\n drawMarker(pressure * lineNoise);\n break;\n case \"custom\":\n case \"image\":\n drawImageTip(pressure * lineNoise);\n break;\n default:\n drawDefault(pressure * lineNoise);\n break;\n }\n}\n\n/**\n * Calculates the effective brush pressure.\n * @returns {number} The calculated pressure.\n */\nfunction calculatePressure() {\n if (current.pressureCount >= 10 || current.cachedPressure === undefined) {\n current.cachedPressure = _plot\n ? simPressure() * _plot.pressure(_position.plotted)\n : simPressure();\n current.pressureCount = 0;\n }\n current.pressureCount++;\n return current.cachedPressure;\n}\n\nfunction calculateLineNoise() {\n if (current.lineNoiseCount >= 10 || current.cachedLineNoise === undefined) {\n current.cachedLineNoise = map(\n noise(current.seed + _position.plotted * 0.01, 0),\n -1,\n 1,\n 1 - current.noiseoffset,\n 1 + current.noiseoffset,\n );\n current.lineNoiseCount = 0;\n }\n current.lineNoiseCount++;\n return current.cachedLineNoise;\n}\n\n/**\n * Simulates brush pressure based on stroke parameters.\n * @returns {number} Simulated pressure value.\n */\nfunction simPressure() {\n const value = current.p.pressure.type === \"custom\"\n ? map(\n current.p.pressure.curve(\n Math.max(\n 0,\n Math.min(\n 1,\n 0.5 + ((_position.plotted / _length) - 0.5 + current.ct) * current.cs,\n ),\n ),\n ) +\n current.cp +\n current.ck * ((_position.plotted / _length) - 0.5),\n 0,\n 1,\n current.min,\n current.max,\n true,\n )\n : gauss();\n return value;\n}\n\n/**\n * Generates a Gaussian-based pressure value.\n * @param {number} [a] - Center parameter.\n * @param {number} [b] - Width parameter.\n * @param {number} [c] - Shape parameter.\n * @param {number} [min] - Minimum pressure.\n * @param {number} [max] - Maximum pressure.\n * @returns {number} Gaussian pressure value.\n */\nfunction gauss(\n a = 0.5 + current.p.pressure.curve[0] * current.a,\n b = 1 - current.p.pressure.curve[1] * current.b,\n c = current.cp,\n min = current.min,\n max = current.max,\n) {\n const peakPos = a * _length;\n const halfWidth =\n (_position.plotted < peakPos ? b * 1.2 : b * 0.8) * (_length / 2);\n return map(\n 1 /\n (1 +\n Math.pow(Math.abs((_position.plotted - peakPos) / halfWidth), 2 * c)),\n 0,\n 1,\n min,\n max,\n );\n}\n\n/**\n * Calculates the alpha (opacity) level for a brush stroke.\n * @returns {number} The calculated opacity.\n */\nfunction calculateAlpha() {\n return [\"default\", \"spray\"].includes(current.p.type)\n ? current.p.opacity\n : current.p.opacity / Math.min(State.stroke.weight, 1.3);\n}\n\n/**\n * Calculates the step spacing based on the current brush parameters.\n * @returns {number} The spacing value.\n */\nfunction spacing() {\n const { param } = list.get(State.stroke.type) ?? {};\n if (!param) return 1;\n return param.spacing;\n}\n\nfunction getImageTipOverscan() {\n const maxPressure = Math.max(1, current.max ?? 1);\n const scatterReach = State.stroke.weight * current.p.scatter;\n const tipReach = State.stroke.weight * current.p.weight * maxPressure;\n\n // Custom/image tips can extend beyond their nominal square because the tip\n // drawing itself may be large and because high scatter creates sparse large\n // stamps near the edge. Keep culling/dirty tracking conservative.\n return Math.max(8, scatterReach * 1.5 + tipReach * 0.75);\n}\n\n// ---------------------------------------------------------------------------\n// Brush Tip Rendering Methods\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the spray tip effect.\n * @param {number} pressure - Current pressure.\n */\nfunction drawSpray(pressure) {\n const vibration =\n State.stroke.weight * current.p.scatter * pressure +\n (State.stroke.weight * rArray(gaussians) * current.p.scatter) / 3;\n const sw = current.p.weight * rr(0.9, 1.1);\n const iterations = Math.ceil(current.p.grain / pressure);\n for (let j = 0; j < iterations; j++) {\n const r = rr(0.9, 1.1);\n const rX = r * vibration * rr(-1, 1);\n const yRandomFactor = rr(-1, 1);\n const sqrtPart = Math.sqrt((r * vibration) ** 2 - rX ** 2);\n circle(\n _position.x + rX,\n _position.y + yRandomFactor * sqrtPart,\n sw,\n current.alpha,\n );\n }\n}\n\n/**\n * Draws the marker tip effect.\n * @param {number} pressure - Current pressure.\n * @param {boolean} [vibrate=true] - Whether to apply vibration.\n */\nfunction drawMarker(pressure, vibrate = true, alpha = current.alpha) {\n const vibration = vibrate ? State.stroke.weight * current.p.scatter : 0;\n const rx = vibrate ? vibration * rr(-1, 1) : 0;\n const ry = vibrate ? vibration * rr(-1, 1) : 0;\n circle(\n _position.x + rx,\n _position.y + ry,\n State.stroke.weight * current.p.weight * pressure,\n alpha * Math.max(0.8, pressure) * rr(0.9,1.1),\n );\n}\n\n/**\n * Queues a stamp for instanced GL rendering.\n * Handles both \"image\" and \"custom\" tip types.\n * @param {number} pressure - Current pressure.\n * @param {number} alpha - Opacity [0..255].\n */\nfunction drawImageTip(pressure, alpha = current.alpha) {\n const vibration = State.stroke.weight * current.p.scatter;\n const rx = vibration * rr(-1, 1);\n const ry = vibration * rr(-1, 1);\n const size = current.p.weight * State.stroke.weight * pressure;\n const overscan = getImageTipOverscan();\n let angle = 0;\n if (current.p.rotate === \"random\") {\n angle = randInt(0, 360) * (Math.PI / 180);\n } else if (current.p.rotate === \"natural\") {\n angle = ((_plot ? -_plot.angle(_position.plotted) : -_dir) + _position.angle()) * (Math.PI / 180);\n }\n stampImage(\n _position.x + rx,\n _position.y + ry,\n size,\n angle,\n alpha * Math.max(0.8, pressure) * rr(0.9, 1.1),\n overscan,\n );\n}\n\n/**\n * Draws the default brush tip.\n * @param {number} pressure - Current pressure.\n */\nfunction drawDefault(pressure, wiggle = 1) {\n wiggle = map(wiggle, 0, 1, 0.9, 1.05);\n const vibration =\n wiggle *\n State.stroke.weight *\n current.p.scatter *\n (current.p.sharpness +\n ((1 - current.p.sharpness) * rArray(gaussians)) / pressure);\n const passesGate = rr(0, current.p.grain * pressure) > 0.4;\n if (passesGate) {\n let dx, dy;\n if (_plot) {\n const plotAngle = _plot.angle(_position.plotted);\n const plotCos = cos(plotAngle);\n const plotSin = sin(plotAngle);\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * plotSin + along * plotCos;\n dy = perp * plotCos - along * plotSin;\n } else {\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * current.sin + along * current.cos;\n dy = perp * current.cos - along * current.sin;\n }\n const diameter =\n pressure *\n pressure *\n current.p.weight *\n rr(0.85, 1.15) *\n State.stroke.weight;\n const alpha = Math.max(0.9, pressure) * current.alpha * rr(0.75, 1.1);\n circle(\n _position.x + dx,\n _position.y + dy,\n diameter,\n alpha,\n );\n }\n}\n\n/**\n * Draws the marker tip with a blend effect.\n */\nfunction markerTip() {\n if (current.p.markerTip === false) return;\n let pressure = calculatePressure();\n let alpha = current.alpha;\n if (current.p.type === \"marker\") {\n for (let s = 1; s < 10; s++) {\n drawMarker((pressure * s) / 10, true, alpha * 8);\n }\n } else if (current.p.type === \"custom\" || current.p.type === \"image\") {\n for (let s = 1; s < 5; s++) {\n drawImageTip((pressure * s) / 10, alpha * 2);\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Basic Drawing Operations\n// ---------------------------------------------------------------------------\n\n/**\n * Draws a line using the current brush.\n * @param {number} x1 - Start x-coordinate.\n * @param {number} y1 - Start y-coordinate.\n * @param {number} x2 - End x-coordinate.\n * @param {number} y2 - End y-coordinate.\n */\nexport function line(x1, y1, x2, y2) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n let d = dist(x1, y1, x2, y2);\n if (d == 0) return;\n initializeDrawingState(x1, y1, d);\n let angle = calcAngle(x1, y1, x2, y2);\n draw(angle, false);\n}\n\n/**\n * Draws a stroke from a starting point in a given direction.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of the stroke.\n * @param {number} dir - Direction, interpreted using the current runtime angle units.\n */\nexport function flowLine(x, y, length, dir) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n initializeDrawingState(x, y, length);\n draw(toDegrees(dir), false);\n}\n\n/**\n * Draws a predefined plot.\n * @param {object} p - Shape object representing the plot.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nfunction plot(p, x, y, scale) {\n isFieldReady();\n initializeDrawingState(x, y, p.length, p);\n draw(scale, true);\n}\n\n// ---------------------------------------------------------------------------\n// Standard Brushes Definition and Initialization\n// ---------------------------------------------------------------------------\n\n/**\n * Defines a set of standard brushes with specific characteristics. Each brush is defined\n * with properties such as weight, scatter, sharpness, grain, opacity, spacing, and\n * pressure sensitivity. Some brushes have additional properties like type, tip, and rotate.\n */\nconst _vals = [\n \"weight\",\n \"scatter\",\n \"sharpness\",\n \"grain\",\n \"opacity\",\n \"spacing\",\n \"pressure\",\n \"type\",\n \"tip\",\n \"rotate\",\n \"markerTip\",\n \"noise\",\n];\nconst _standard_brushes = [\n [\n \"pen\",\n [0.3, 0.15, 0.9, 2, 150, 0.1, { curve: [0.15, 0.2], min_max: [1.2, 1] }],\n ],\n [\n \"rotring\",\n [0.15, 0.05, 0.7, 15, 210, 0.1, { curve: [0.35, 0.2], min_max: [1.3, 1] }],\n ],\n [\n \"2B\",\n [0.3, 0.75, 0.45, 15, 180, 0.1, { curve: [0.1, 0.3], min_max: [1.1, 0.9] }],\n ],\n [\n \"HB\",\n [0.3, 0.6, 0.3, 10, 170, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"2H\",\n [0.2, 0.6, 0.3, 4, 120, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"cpencil\",\n [0.3, 0.55, 0.8, 7, 75, 0.1, { curve: [0.15, 0.2], min_max: [0.95, 1.2] }],\n ],\n [\n \"pastel\",\n [\n 2.05 / 3,\n 13.4 / 3,\n 0.91,\n 28,\n 35,\n 0.085 / 3,\n { mode: \"gaussian\", curve: [0.4, 0.05], min_max: [1.09, 0.93] },\n \"default\",\n undefined,\n \"natural\",\n true,\n 1,\n ],\n ],\n [\n \"crayon\",\n [\n 0.9 / 3,\n 5.45 / 3,\n 0.75,\n 250,\n 159,\n 0.23 / 3,\n [1.1, 0.9],\n \"default\",\n undefined,\n \"natural\",\n true,\n 1,\n ],\n ],\n [\n \"charcoal\",\n [\n 0.35,\n 1.5,\n 0.68,\n 500,\n 120,\n 0.03,\n { curve: [0.15, 0.4], min_max: [1.1, 0.95] },\n ],\n ],\n [\n \"spray\",\n [\n 0.2,\n 6,\n 15,\n 40,\n 90,\n 0.5,\n { curve: [0.2, 0.35], min_max: [0.7, 1] },\n \"spray\",\n ],\n ],\n [\n \"marker\",\n [\n 2,\n 0.2,\n null,\n null,\n 1,\n 0.03,\n { curve: [0.35, 0.25], min_max: [1.2, 0.85] },\n \"marker\",\n ],\n ],\n];\n\nfor (let s of _standard_brushes) {\n let obj = {};\n for (let i = 0; i < s[1].length; i++) obj[_vals[i]] = s[1][i];\n add(s[0], obj);\n}\n\n// ---------------------------------------------------------------------------\n// Extensions to Polygon and Plot Prototypes\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the polygon using the current brush.\n * @param {boolean} [_brush=false] - Optional brush name override.\n * @param {string|Color} [_color] - Optional color override.\n * @param {number} [_weight] - Optional weight override.\n */\nPolygon.prototype.draw = function (_brush = false, _color, _weight) {\n let state = BrushState();\n if (_brush) set(_brush, _color, _weight);\n if (state.isActive) {\n for (let s of this.sides) {\n line(s[0].x, s[0].y, s[1].x, s[1].y);\n }\n }\n BrushSetState(state);\n};\n\n/**\n * Draws the plot using the current brush.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nPlot.prototype.draw = function (x, y, scale) {\n if (BrushState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n plot(this, x, y, scale);\n }\n};\n\n// =============================================================================\n// Section: Loading Custom Image Tips\n// =============================================================================\n/**\n * This section defines the functionality for managing the loading and processing of image tips.\n * Images are loaded from specified source URLs, converted to a white tint for visual effects,\n * and then stored for future use. It includes methods to add new images, convert their color\n * scheme, and integrate them into the active host image pipeline.\n */\n\n/**\n * Manages loading and processing of image tips.\n * Images are converted to white with inverted alpha for tinting via shaders.\n */\nconst T = {\n tips: new Map(),\n\n /**\n * Registers an image source for later loading.\n * @param {string} src - The source URL of the image.\n */\n add(src) {\n if (!this.tips.has(src)) this.tips.set(src, false);\n },\n\n /**\n * Converts image to white with inverted alpha for tint-based rendering.\n * @param {object} image - The host image object to convert.\n */\n imageToWhite(image) {\n image.loadPixels();\n for (let i = 0; i < 4 * image.width * image.height; i += 4) {\n let average =\n (image.pixels[i] + image.pixels[i + 1] + image.pixels[i + 2]) / 3;\n image.pixels[i] = image.pixels[i + 1] = image.pixels[i + 2] = 255;\n image.pixels[i + 3] = 255 - average;\n }\n image.updatePixels();\n },\n\n /**\n * Loads all registered image tips. Returns a promise that resolves\n * when all images are loaded and processed.\n * @returns {Promise}\n */\n async load() {\n const entries = [...this.tips.keys()].filter((k) => !this.tips.get(k));\n await Promise.all(\n entries.map(\n (src) =>\n loadImageTip(src, T.imageToWhite).then((p5img) => {\n this.tips.set(src, p5img);\n }),\n ),\n );\n },\n};\n","import { State } from \"../core/color.js\";\nimport { toDegreesSigned, map, rr } from \"../core/utils.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { BrushState, BrushSetState, set, line } from \"../stroke/stroke.js\";\n\n// =============================================================================\n// Module: Classic Hatch\n// =============================================================================\n\n// ---------------------------------------------------------------------------\n// Hatch State\n// ---------------------------------------------------------------------------\n\nState.hatch = {\n isActive: false,\n dist: 5,\n angle: 45,\n options: {},\n hBrush: false,\n};\n\n/**\n * Returns a shallow snapshot of the current hatch modifier state.\n *\n * @returns {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}}\n */\nexport function HatchState() {\n return { ...State.hatch };\n}\n\n/**\n * Restores hatch modifier state from a previously captured snapshot.\n *\n * @param {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}} state\n */\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Activates classic scanline hatching for subsequent shapes.\n *\n * @param {number} [dist=5] Distance between scanlines.\n * @param {number} [angle=45] Hatch angle in the current runtime angle units.\n * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [options]\n */\nexport function hatch(\n dist = 5,\n angle = 45,\n options = { rand: false, continuous: false, gradient: false }\n) {\n let s = State.hatch;\n s.isActive = true;\n s.dist = dist;\n s.angle = toDegreesSigned(angle);\n s.options = options;\n}\n\n/**\n * Overrides the brush, color, and weight used specifically for hatch strokes.\n *\n * @param {string} brush\n * @param {string|object} [color=\"black\"]\n * @param {number} [weight=1]\n */\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\n/**\n * Deactivates hatching and clears any hatch-specific brush override.\n */\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Scanline Generation\n// ---------------------------------------------------------------------------\n\n/**\n * Computes hatch segments for one polygon by rotating it into scanline space,\n * intersecting horizontal scanlines against its edges, and rotating the\n * resulting segments back into canvas space.\n *\n * @param {Polygon} polygon\n * @param {number} angle Hatch angle in degrees.\n * @param {number} dist Base scanline spacing.\n * @param {number} gradient Multiplicative spacing growth per scanline.\n * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}\n */\nfunction scanlineHatch(polygon, angle, dist, gradient) {\n const rad = (angle * Math.PI) / 180;\n const cosA = Math.cos(rad),\n sinA = Math.sin(rad);\n const cosB = Math.cos(-rad),\n sinB = Math.sin(-rad);\n\n const verts = polygon.a,\n n = verts.length;\n\n // Rotate vertices; track Y extent\n const rotated = new Array(n);\n let minY = Infinity,\n maxY = -Infinity;\n for (let i = 0; i < n; i++) {\n const x = verts[i][0],\n y = verts[i][1];\n const r = [x * cosA - y * sinA, x * sinA + y * cosA];\n rotated[i] = r;\n if (r[1] < minY) minY = r[1];\n if (r[1] > maxY) maxY = r[1];\n }\n\n // Build edge list (skip horizontal edges)\n const edges = [];\n for (let i = 0; i < n; i++) {\n const a = rotated[i],\n b = rotated[(i + 1) % n];\n if (a[1] !== b[1]) edges.push(a, b);\n }\n const eLen = edges.length;\n\n // Scan, find crossings, rotate back\n const segments = [];\n const cx = [];\n let Y = minY + dist * 0.5,\n step = dist;\n while (Y < maxY) {\n cx.length = 0;\n for (let i = 0; i < eLen; i += 2) {\n const y1 = edges[i][1],\n y2 = edges[i + 1][1];\n if ((y1 <= Y && Y < y2) || (y2 <= Y && Y < y1))\n cx.push(\n edges[i][0] + ((Y - y1) / (y2 - y1)) * (edges[i + 1][0] - edges[i][0])\n );\n }\n cx.sort((a, b) => a - b);\n for (let i = 0; i < cx.length - 1; i += 2) {\n segments.push({\n scanY: Y,\n x1: cx[i] * cosB - Y * sinB,\n y1: cx[i] * sinB + Y * cosB,\n x2: cx[i + 1] * cosB - Y * sinB,\n y2: cx[i + 1] * sinB + Y * cosB,\n });\n }\n Y += step;\n step *= gradient;\n }\n return segments;\n}\n\n/**\n * Collects and orders hatch segments for one polygon or a polygon list.\n *\n * Segments are sorted in scanline traversal order so downstream rendering can\n * optionally connect them into a continuous serpentine path.\n *\n * @param {Polygon|Polygon[]} polygons\n * @param {number} dist\n * @param {number} angle\n * @param {number} gradient\n * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}\n */\nfunction getHatchSegments(polygons, dist, angle, gradient) {\n if (!Array.isArray(polygons)) polygons = [polygons];\n const segs = [];\n for (const poly of polygons) {\n for (const s of scanlineHatch(poly, angle, dist, gradient)) segs.push(s);\n }\n segs.sort((a, b) => (a.scanY === b.scanY ? a.x1 - b.x1 : a.scanY - b.scanY));\n return segs;\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Configuration\n// ---------------------------------------------------------------------------\n\n/**\n * Runs hatch drawing with the temporary hatch-specific brush style if one is active,\n * then restores the outer stroke state.\n *\n * @param {() => void} drawFn\n */\nfunction withHatchStyle(drawFn) {\n const save = BrushState();\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n drawFn();\n BrushSetState(save);\n}\n\n/**\n * Resolves the active hatch parameters and precomputes the ordered scanline segments.\n *\n * @param {Polygon|Polygon[]} polygons\n * @returns {{dist:number, options:Object, segs:Object[]}}\n */\nfunction getActiveHatchConfig(polygons) {\n const dist = State.hatch.dist;\n const angle = ((State.hatch.angle % 180) + 180) % 180;\n const options = State.hatch.options;\n const gradient = options.gradient ? map(options.gradient, 0, 1, 1, 1.1, true) : 1;\n const segs = getHatchSegments(polygons, dist, angle, gradient);\n return { dist, options, segs };\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Lines\n// ---------------------------------------------------------------------------\n\n/**\n * Expands ordered hatch segments into the actual line list that will be drawn.\n *\n * This includes endpoint jitter when `rand` is active and inserts the serpentine\n * connector lines when `continuous` is enabled.\n *\n * @param {Polygon|Polygon[]} polygons\n * @returns {{x1:number, y1:number, x2:number, y2:number, scanY:number, isConnector:boolean}[]}\n */\nexport function getHatchLines(polygons) {\n const { dist, options, segs } = getActiveHatchConfig(polygons);\n const r = options.rand || 0;\n const lines = [];\n\n for (let j = 0; j < segs.length; j++) {\n const s = segs[j];\n let x1 = s.x1, y1 = s.y1, x2 = s.x2, y2 = s.y2;\n if (r) {\n x1 += 2 * r * dist * rr(-1, 1);\n y1 += 2 * r * dist * rr(-1, 1);\n x2 += 2 * r * dist * rr(-1, 1);\n y2 += 2 * r * dist * rr(-1, 1);\n }\n const reverse = options.continuous && j % 2 === 1;\n const line = reverse\n ? { x1: x2, y1: y2, x2: x1, y2: y1, scanY: s.scanY, isConnector: false }\n : { x1, y1, x2, y2, scanY: s.scanY, isConnector: false };\n lines.push(line);\n if (j > 0 && options.continuous) {\n const prev = lines[lines.length - 2];\n lines.push({\n x1: prev.x2,\n y1: prev.y2,\n x2: line.x1,\n y2: line.y1,\n scanY: s.scanY,\n isConnector: true,\n });\n }\n }\n\n return lines;\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Rendering\n// ---------------------------------------------------------------------------\n\n/**\n * Iterates the generated hatch lines and delegates the actual rendering of each\n * segment to the provided callback.\n *\n * @param {Polygon|Polygon[]} polygons\n * @param {(x1:number, y1:number, x2:number, y2:number, index:number, segs:Object[]) => void} drawSegment\n */\nfunction renderHatchSegments(polygons, drawSegment) {\n const segs = getHatchLines(polygons);\n withHatchStyle(() => {\n for (let j = 0; j < segs.length; j++) {\n const s = segs[j];\n drawSegment(s.x1, s.y1, s.x2, s.y2, j, segs);\n }\n });\n}\n\n/**\n * Draws classic hatch lines over one polygon or an array of polygons.\n *\n * @param {Polygon|Polygon[]} polygons\n */\nexport function createHatch(polygons) {\n renderHatchSegments(polygons, (x1, y1, x2, y2) => {\n line(x1, y1, x2, y2);\n });\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Applies the currently active hatch modifier to a polygon, or temporarily\n * overrides hatch parameters for this call only.\n *\n * @param {number|false} [_dist=false]\n * @param {number} [_angle]\n * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [_options]\n */\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (State.hatch.isActive) createHatch(this);\n HatchSetState(state);\n};\n\n/**\n * Converts the plot to a polygon and applies the currently active hatch modifier.\n *\n * @param {number} x\n * @param {number} y\n * @param {number} scale\n */\nPlot.prototype.hatch = function (x, y, scale) {\n if (HatchState().isActive) {\n if (this.origin) (x = this.origin[0]), (y = this.origin[1]), (scale = 1);\n this.pol = this.genPol(x, y, scale, 0.3);\n this.pol.hatch();\n }\n};\n","// =============================================================================\n// Module: Mass\n// =============================================================================\n\nimport { State } from \"../core/color.js\";\nimport { arc } from \"../core/primitives.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { rr2, dist, calcAngle } from \"../core/utils.js\";\nimport { fromDegrees, usesRadians } from \"../core/runtime.js\";\nimport { HatchState, HatchSetState, hatch, getHatchLines } from \"./hatch.js\";\nimport { BrushState, BrushSetState, getBrushParams, set } from \"../stroke/stroke.js\";\nimport { wiggle } from \"../core/flowfield.js\";\n\n// ---------------------------------------------------------------------------\n// Mass State\n// ---------------------------------------------------------------------------\n\nState.mass = {\n isActive: false,\n brush: null,\n color: null,\n options: {},\n};\n\n/**\n * Returns a shallow copy of the current mass state.\n * @returns {object}\n */\nexport function MassState() {\n return { ...State.mass };\n}\n\n/**\n * Restores a previously saved mass state.\n * @param {object} state\n */\nexport function MassSetState(state) {\n State.mass = { ...state };\n}\n\n/**\n * Enables massing mode with a brush, color, and optional configuration.\n *\n * @param {string} brush - Brush name to use for the mass pass.\n * @param {string|Color} color - Color to use for the mass pass.\n * @param {object} [options={}] - Massing options such as precision, strength, gradient, and outline.\n */\nexport function mass(brush, color, options = {}) {\n State.mass.brush = brush;\n State.mass.color = color;\n State.mass.options = options;\n State.mass.isActive = true;\n}\n\n/**\n * Disables massing mode for subsequent geometry.\n */\nexport function noMass() {\n State.mass.isActive = false;\n State.mass.brush = null;\n State.mass.color = null;\n State.mass.options = {};\n}\n\n// ---------------------------------------------------------------------------\n// Polygon Preparation\n// ---------------------------------------------------------------------------\n\n/**\n * Returns a translated copy of a polygon.\n * Used to build the secondary mass layers from an existing base polygon.\n * @param {Polygon} polygon\n * @param {number} jitterX\n * @param {number} jitterY\n * @returns {Polygon}\n */\nfunction jitterPolygon(polygon, jitterX, jitterY) {\n return new Polygon(\n polygon.vertices.map((vertex) => [vertex.x + jitterX, vertex.y + jitterY]),\n );\n}\n\n/**\n * Builds the three polygons used for a mass pass.\n * Both polygon and plot inputs use one base polygon plus two translated copies,\n * so plot-based massing only needs a single `genPol(...)` call.\n * @param {Polygon|Plot} shape\n * @param {number|false} x\n * @param {number} y\n * @param {number} scale\n * @returns {Polygon[]}\n */\nfunction getMassPolygons(shape, x, y, scale) {\n const isPolygon = x === false;\n const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;\n const basePolygon = isPolygon ? shape : shape.genPol(x, y, scale, 0.15);\n const maxJitter = Math.min(scatter * 2, 5);\n const jitters = [\n [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],\n [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],\n ];\n\n return [\n basePolygon,\n jitterPolygon(basePolygon, jitters[0][0], jitters[0][1]),\n jitterPolygon(basePolygon, jitters[1][0], jitters[1][1]),\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Angle & Bounds Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Converts degree values into the current runtime angle units.\n * @param {number} angle\n * @returns {number}\n */\nfunction getAngleConverter() {\n return usesRadians()\n ? (angle) => (angle * Math.PI) / 180\n : (angle) => angle;\n}\n\n/**\n * Computes an axis-aligned bounding box for a polygon.\n * The diagonal is used as a size reference for pivot distance.\n * @param {Polygon} polygon\n * @returns {{minX:number,minY:number,maxX:number,maxY:number,cx:number,cy:number,size:number}}\n */\nfunction getPolygonBounds(polygon) {\n const points = polygon?.a ?? [];\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n for (const [x, y] of points) {\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n return {\n minX,\n minY,\n maxX,\n maxY,\n cx: (minX + maxX) / 2,\n cy: (minY + maxY) / 2,\n size: Math.hypot(maxX - minX, maxY - minY),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Pivot Geometry\n// ---------------------------------------------------------------------------\n\n/**\n * Chooses the diagonal corner family for a whole mass gesture.\n * Positive-angle hatching uses either bottom-right or top-left; negative-angle\n * hatching uses either bottom-left or top-right.\n * @param {number} angleDeg\n * @returns {[number, number]}\n */\nfunction getPivotBias(angleDeg) {\n const normalizedAngle = ((((angleDeg + 90) % 180) + 180) % 180) - 90;\n if (normalizedAngle >= 0) {\n return rr2() < 0.5 ? [1, 1] : [-1, -1];\n } else {\n return rr2() < 0.5 ? [-1, 1] : [1, -1];\n }\n}\n\n/**\n * Places the global pivot anchor outside the polygon, along the selected bias.\n * Distance varies per layer while the bias stays fixed for the whole mass.\n * @param {Polygon} polygon\n * @param {[number, number]} bias\n * @returns {{x:number,y:number}}\n */\nfunction getPivotAnchor(polygon, bias) {\n const bounds = getPolygonBounds(polygon);\n const offset = bounds.size * rr2(0.6, 1.4);\n const [sx, sy] = bias;\n return {\n x: bounds.cx + sx * offset,\n y: bounds.cy + sy * offset,\n };\n}\n\n/**\n * Projects the global pivot anchor onto the perpendicular bisector of a line.\n * This yields a valid circle center equidistant from both endpoints.\n * @param {{x:number,y:number}} anchor\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {{x:number,y:number}|null}\n */\nfunction projectAnchorToBisector(anchor, x1, y1, x2, y2) {\n const mx = (x1 + x2) / 2;\n const my = (y1 + y2) / 2;\n const dx = x2 - x1;\n const dy = y2 - y1;\n const length = Math.hypot(dx, dy);\n if (!length) return null;\n const nx = -dy / length;\n const ny = dx / length;\n const offset = (anchor.x - mx) * nx + (anchor.y - my) * ny;\n return {\n x: mx + nx * offset,\n y: my + ny * offset,\n };\n}\n\n/**\n * Returns the shortest arc between two endpoints around a given center.\n * The returned angles are already converted into the current runtime angle units.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {[number, number]}\n */\nfunction getShortArcAngles(cx, cy, x1, y1, x2, y2, toAngleUnit) {\n let startDeg = calcAngle(cx, cy, x1, y1);\n let endDeg = calcAngle(cx, cy, x2, y2);\n const sweep = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweep > 180) [startDeg, endDeg] = [endDeg, startDeg];\n return [\n toAngleUnit(startDeg),\n toAngleUnit(endDeg),\n ];\n}\n\n/**\n * Splits a hatch line into two slightly separated segments so some gestures\n * read as interrupted rather than perfectly continuous.\n * @param {{x1:number,y1:number,x2:number,y2:number}} seg\n * @returns {Array<{x1:number,y1:number,x2:number,y2:number}>}\n */\nfunction splitSegment(seg) {\n const t = rr2(0.35, 0.65);\n const mx = seg.x1 + (seg.x2 - seg.x1) * t;\n const my = seg.y1 + (seg.y2 - seg.y1) * t;\n const dx = seg.x2 - seg.x1;\n const dy = seg.y2 - seg.y1;\n const length = Math.hypot(dx, dy) || 1;\n const gap = rr2(0.04, 0.1) * length;\n const gx = (dx / length) * gap * 0.5;\n const gy = (dy / length) * gap * 0.5;\n return [\n { x1: seg.x1, y1: seg.y1, x2: mx - gx, y2: my - gy },\n { x1: mx + gx, y1: my + gy, x2: seg.x2, y2: seg.y2 },\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Mass Rendering\n// ---------------------------------------------------------------------------\n\n/**\n * Draws one polygon of the mass as a family of arcs derived from hatch lines.\n * The same pivot bias is used across layers, while each layer gets its own\n * anchor distance from the shape.\n * @param {Polygon} polygon\n * @param {[number, number]} pivotBias\n */\nfunction drawMassArcs(polygon, pivotBias, toAngleUnit) {\n const anchor = getPivotAnchor(polygon, pivotBias);\n for (const seg of getHatchLines(polygon)) {\n const parts = !seg.isConnector && rr2() < 0.35 ? splitSegment(seg) : [seg];\n for (const part of parts) {\n const center = projectAnchorToBisector(anchor, part.x1, part.y1, part.x2, part.y2);\n if (!center) continue;\n const radius = dist(center.x, center.y, part.x1, part.y1);\n if (!radius) continue;\n const [startAngle, endAngle] = getShortArcAngles(\n center.x,\n center.y,\n part.x1,\n part.y1,\n part.x2,\n part.y2,\n toAngleUnit,\n );\n arc(center.x, center.y, radius, startAngle, endAngle);\n }\n }\n}\n\n/**\n * Configures a hatch pass and immediately reinterprets the generated lines as arcs.\n * @param {Polygon} polygon\n * @param {number} dist\n * @param {number} angle\n * @param {object} options\n * @param {[number, number]} pivotBias\n */\nfunction drawMassPass(polygon, dist, angle, options, pivotBias, toAngleUnit) {\n hatch(dist, angle, options);\n drawMassArcs(polygon, pivotBias, toAngleUnit);\n}\n\n/**\n * Creates the built-in \"massing\" effect for a polygon or plot.\n * A mass is built from up to three jittered polygon layers, each hatched and\n * then redrawn as arc gestures around a shared pivot bias.\n * @param {Polygon|Plot} shape\n * @param {number|false} x\n * @param {number} y\n * @param {number} scale\n */\nexport function createMass(shape, x, y, scale) {\n const pols = getMassPolygons(shape, x, y, scale);\n const hatchState = HatchState();\n const brushState = BrushState();\n const fieldState = { ...State.field };\n const precision = State.mass.options?.precision ?? 0.5;\n const strength = State.mass.options?.strength ?? 1;\n const gradient = State.mass.options?.gradient ?? 0.1;\n const outline = State.mass.options?.outline ?? false;\n const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;\n const hatchDist = 1.6 * rr2(scatter * 0.65, scatter * 0.85) - 0.4 * gradient;\n const baseAngle = rr2(-90, 90);\n const pivotBias = getPivotBias(baseAngle);\n const toAngleUnit = getAngleConverter();\n\n set(State.mass.brush, State.mass.color, 1);\n wiggle(2 - precision);\n if (outline) pols[0].draw();\n\n drawMassPass(\n pols[0],\n hatchDist * 0.9,\n fromDegrees(baseAngle),\n {\n gradient,\n rand: 2 - 2 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n\n if (strength > 0.33) {\n drawMassPass(\n pols[1],\n hatchDist,\n fromDegrees(baseAngle + 20 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n }\n\n if (strength > 0.66) {\n drawMassPass(\n pols[2],\n hatchDist * 0.8,\n fromDegrees(baseAngle + 15 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n }\n\n BrushSetState(brushState);\n HatchSetState(hatchState);\n State.field = { ...fieldState };\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Applies massing to polygon geometry.\n */\nPolygon.prototype.mass = function () {\n if (State.mass?.isActive) {\n createMass(this, false);\n }\n};\n\n/**\n * Applies massing to plots by generating their polygon first.\n * @param {number} x\n * @param {number} y\n * @param {number} scale\n */\nPlot.prototype.mass = function (x, y, scale) {\n if (State.mass?.isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n createMass(this, x, y, scale);\n }\n};\n","import { Mix } from \"../core/color.js\";\n\nfunction strokePadding(ctx, matrix) {\n const lineWidth = ctx.lineWidth || 0;\n if (lineWidth <= 0) return 1;\n\n return (\n 1 +\n (lineWidth * Math.max(Math.hypot(matrix.a, matrix.c), Math.hypot(matrix.b, matrix.d))) /\n 2\n );\n}\n\n// =============================================================================\n// Section: Draw shapes to Mask Buffers\n// =============================================================================\n\n/**\n * Draws a polygon to the mask using the provided vertices.\n * @param {Array<{x: number, y: number}>} vertices - Array of vertex coordinates.\n */\nexport function drawPolygon(vertices) {\n const ctx = Mix.ctx;\n const matrix = ctx.getTransform();\n // Cache the current 2D transform once so the hot loop can stay numeric and\n // avoid repeated property reads while we build bounds.\n const a = matrix.a;\n const b = matrix.b;\n const c = matrix.c;\n const d = matrix.d;\n const e = matrix.e;\n const f = matrix.f;\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n\n ctx.beginPath();\n\n // Seed both the path and the transformed bounds from the first vertex so the\n // loop below only needs to append line segments.\n const first = vertices[0];\n let tx = a * first.x + c * first.y + e;\n let ty = b * first.x + d * first.y + f;\n minX = maxX = tx;\n minY = maxY = ty;\n\n ctx.moveTo(first.x, first.y);\n\n for (let i = 1; i < vertices.length; i++) {\n const v = vertices[i];\n\n // Track the transformed bounds in canvas space while we build the path so\n // dirty-rect bookkeeping does not need a second pass over the vertices.\n tx = a * v.x + c * v.y + e;\n ty = b * v.x + d * v.y + f;\n minX = Math.min(minX, tx);\n minY = Math.min(minY, ty);\n maxX = Math.max(maxX, tx);\n maxY = Math.max(maxY, ty);\n\n ctx.lineTo(v.x, v.y);\n }\n\n ctx.closePath();\n\n // Expand by stroke width so the later composite pass copies enough pixels\n // even when the polygon border extends outside the raw vertex bounds.\n const padding = strokePadding(ctx, matrix);\n Mix.markDirtyRect(Mix.mask, {\n minX: minX - padding,\n minY: minY - padding,\n maxX: maxX + padding,\n maxY: maxY + padding,\n });\n}\n\n/**\n * Draws a circle to the mask.\n * @param {number} x - X-coordinate of the circle's center.\n * @param {number} y - Y-coordinate of the circle's center.\n * @param {number} d - Diameter of the circle.\n */\nexport function circle(x, y, d) {\n const PI2 = Math.PI * 2;\n const ctx = Mix.ctx;\n const radius = d / 2;\n\n ctx.moveTo(x + radius, y);\n ctx.arc(x, y, radius, 0, PI2);\n}\n","import * as Color from \"../core/color.js\";\nimport {\n createFramebuffer,\n create2DCanvas,\n} from \"../core/compositor_runtime.js\";\n\n// Small staging canvas used to upload only the dirty fill sub-rect into the\n// framebuffer-backed mask mirror consumed by the blend shader.\nlet FillMaskUploadCanvas = null;\nlet isFillCompositeRegistered = false;\nconst DIRTY_FILL_PADDING = 4;\n\n// =============================================================================\n// Section: Helpers\n// =============================================================================\n/**\n * Returns whether the CPU-side 2D fill mask must be recreated.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} maskWidth - Mask width in physical pixels.\n * @param {number} maskHeight - Mask height in physical pixels.\n * @returns {boolean} True when the 2D fill mask needs reallocation.\n */\nfunction needsFillMaskCanvas(Renderer, maskWidth, maskHeight) {\n return (\n !Renderer.mask ||\n Renderer.mask.width !== maskWidth ||\n Renderer.mask.height !== maskHeight\n );\n}\n\n/**\n * Returns whether the framebuffer-backed fill mask mirror must be recreated.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {boolean} True when the fill mask framebuffer needs reallocation.\n */\nfunction needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density) {\n return (\n !Renderer.fillMaskFramebuffer ||\n Renderer.fillMaskFramebuffer.width !== Cwidth ||\n Renderer.fillMaskFramebuffer.height !== Cheight ||\n (typeof Renderer.fillMaskFramebuffer.pixelDensity === \"function\" &&\n Renderer.fillMaskFramebuffer.pixelDensity() !== Density)\n );\n}\n\n// =============================================================================\n// Section: Resource Management\n// =============================================================================\n/**\n * Ensures fill compositing resources exist for the active renderer.\n *\n * Fill draws first into a CPU-side 2D mask canvas. That mask is later uploaded,\n * dirty-rect by dirty-rect, into a framebuffer-backed mirror used by the final\n * blend shader pass.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n * @returns {{mask: object, ctx: CanvasRenderingContext2D}} Fill mask resources.\n */\nexport function ensureFillCompositeResources(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n clearTarget,\n) {\n const maskWidth = Math.max(1, Math.round(Cwidth * Density));\n const maskHeight = Math.max(1, Math.round(Cheight * Density));\n\n if (needsFillMaskCanvas(Renderer, maskWidth, maskHeight)) {\n Renderer.mask = create2DCanvas(maskWidth, maskHeight);\n }\n\n if (needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.fillMaskFramebuffer?.remove) {\n Renderer.fillMaskFramebuffer.remove();\n }\n Renderer.fillMaskFramebuffer = createFramebuffer(Renderer, {\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n clearTarget(Renderer.fillMaskFramebuffer);\n }\n\n Renderer.mask.dirtyRect ??= null;\n Renderer.mask.isDrawn ??= false;\n Renderer.mask.drawingContext.imageSmoothingEnabled = false;\n return {\n mask: Renderer.mask,\n ctx: Renderer.mask.drawingContext,\n };\n}\n\n// =============================================================================\n// Section: Mask Lifecycle\n// =============================================================================\n/**\n * Clears the current fill mask and resets its bookkeeping flags.\n *\n * @param {object|null} target - Fill mask canvas or framebuffer mirror.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n */\nexport function clearFillMask(target, clearTarget) {\n if (!target) return;\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\n}\n\n// =============================================================================\n// Section: Composite Bounds\n// =============================================================================\n/**\n * Returns the fill dirty rect to composite into the main target. Fill bounds are\n * taken directly from the accumulated 2D mask dirty area plus a small padding.\n *\n * @param {object|null} target - Fill mask canvas.\n * @param {Function} _getActiveFramebuffer - Unused for fill masks.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} expandDirtyRect - Expands a rect by a constant padding.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\nexport function getFillCompositeRect(\n target,\n _getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(target.dirtyRect, DIRTY_FILL_PADDING),\n );\n}\n\n// =============================================================================\n// Section: Upload\n// =============================================================================\n/**\n * Uploads only the dirty portion of the CPU-side 2D fill mask into the\n * framebuffer-backed fill mask mirror used by the shader compositor.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {object} mask - CPU-side 2D fill mask canvas.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} dirtyRect - Dirty rect to upload.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n * @returns {object} Framebuffer-backed fill mask mirror.\n */\nexport function getFillShaderMask(\n Renderer,\n mask,\n dirtyRect,\n normalizeDirtyRect,\n getFullDirtyRect,\n clearTarget,\n) {\n const target = Renderer.fillMaskFramebuffer;\n const gl = Renderer.drawingContext;\n const uploadRect = normalizeDirtyRect(dirtyRect) ?? getFullDirtyRect();\n const uploadWidth = uploadRect.maxX - uploadRect.minX;\n const uploadHeight = uploadRect.maxY - uploadRect.minY;\n\n if (\n !FillMaskUploadCanvas ||\n FillMaskUploadCanvas.width !== uploadWidth ||\n FillMaskUploadCanvas.height !== uploadHeight\n ) {\n FillMaskUploadCanvas = create2DCanvas(uploadWidth, uploadHeight);\n }\n\n const uploadContext = FillMaskUploadCanvas.drawingContext;\n uploadContext.clearRect(0, 0, uploadWidth, uploadHeight);\n uploadContext.drawImage(\n mask,\n uploadRect.minX,\n uploadRect.minY,\n uploadWidth,\n uploadHeight,\n 0,\n 0,\n uploadWidth,\n uploadHeight,\n );\n\n clearTarget(target);\n gl.bindTexture(gl.TEXTURE_2D, target.colorTexture);\n gl.texSubImage2D(\n gl.TEXTURE_2D,\n 0,\n uploadRect.minX,\n uploadRect.minY,\n gl.RGBA,\n gl.UNSIGNED_BYTE,\n FillMaskUploadCanvas,\n );\n return target;\n}\n\n// =============================================================================\n// Section: Registration\n// =============================================================================\n/**\n * Registers the fill compositor with the shared color/composite core.\n * Safe to call multiple times.\n */\nexport function initFillComposite() {\n if (isFillCompositeRegistered) return;\n Color.registerFillComposite?.({\n ensureResources: ensureFillCompositeResources,\n clearMask: clearFillMask,\n getCompositeRect: getFillCompositeRect,\n getShaderMask: getFillShaderMask,\n });\n isFillCompositeRegistered = true;\n}\n","// =============================================================================\n// Module: Fill\n// =============================================================================\n/**\n * The Fill module contains functions and classes dedicated to handling\n * the fill properties of shapes within the drawing context. It supports complex fill\n * operations with effects such as bleeding to simulate watercolor-like textures. The\n * methods provided allow for setting the fill color with opacity, controlling the\n * intensity of the bleed effect, and enabling or disabling the fill operation.\n *\n * The watercolor effect implementation is inspired by Tyler Hobbs'\n * techniques for simulating watercolor paints.\n */\n\n// Core imports\nimport { Renderer, Cwidth, Cheight, Density } from \"../core/target.js\";\nimport {\n Mix,\n State,\n} from \"../core/color.js\";\nimport { drawPolygon, circle } from \"./mask.js\";\nimport {\n constrain,\n weightedRand,\n rr,\n map,\n randInt,\n gaussian,\n rotate,\n cos,\n sin,\n _onSeed,\n} from \"../core/utils.js\";\nimport { isFieldReady } from \"../core/flowfield.js\";\nimport { createColor, getAffineMatrix } from \"../core/runtime.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\n\n// Internal module imports\nimport { initFillComposite } from \"./composite.js\";\n\ninitFillComposite(); // Register the fill composite with the core color module\n\n// =============================================================================\n// Fill State and helpers\n// =============================================================================\n\n// Vertex cap for grow() — set to 0 or false to disable\nconst GROW_MAX_VERTS = 2024;\nlet GROW_CAP;\n\n// Reusable scratch arrays for grow() — avoids 4 allocations per call (~15× per fill)\nlet _growInsX = [];\nlet _growInsY = [];\nlet _growMods = [];\nlet _growDirs = [];\n\n/**\n * Global fill state settings.\n */\nState.fill = {\n opacity: 150,\n bleed_strength: 0.07,\n texture_strength: 0.8,\n border_strength: 0.5,\n direction: \"out\",\n isActive: false,\n};\n\n// Cache the current state\nconst FillState = () => ({ ...State.fill });\nconst FillSetState = (state) => {\n State.fill = { ...state };\n};\n\n// ---------------------------------------------------------------------------\n// Fill Style Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Sets the fill color and opacity for subsequent drawing operations.\n * @param {number|string|Color} a - Either the red component, a CSS color string, or a Color object.\n * @param {number} [b] - The green component or the opacity if using grayscale.\n * @param {number} [c] - The blue component.\n * @param {number} [d] - The opacity.\n */\nexport function fill(a, b, c, d) {\n State.fill.opacity = (arguments.length < 4 ? b : d) || 150;\n State.fill.color = arguments.length < 3 ? createColor(a) : createColor(a, b, c);\n State.fill.isActive = true;\n}\n\n/**\n * Sets the bleed (watercolor) intensity and direction.\n * @param {number} _i - The bleed intensity (clamped to [0,1]).\n * @param {string} [_direction=\"out\"] - The bleeding direction.\n */\nexport function fillBleed(_i, _direction = \"out\") {\n State.fill.bleed_strength = constrain(_i, 0, 1);\n State.fill.direction = _direction;\n}\n\n/**\n * Sets the texture and border strengths for the fill.\n * @param {number} [_texture=0.4] - The texture strength (clamped to [0,1]).\n * @param {number} [_border=0.4] - The border strength (clamped to [0,1]).\n */\nexport function fillTexture(_texture = 0.4, _border = 0.4) {\n State.fill.texture_strength = constrain(_texture, 0, 1);\n State.fill.border_strength = constrain(_border, 0, 1);\n}\n\n/**\n * Disables fill for subsequent drawing operations.\n */\nexport function noFill() {\n State.fill.isActive = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fill Manager Functions\n// ---------------------------------------------------------------------------\n\nlet _polygon;\n\n// Pre-compute gaussians for reuse\nconst GAUSSIAN_POOL_SIZE = 512;\nconst _gaussians = [[], []]; // [a, b]\nfunction _fillGaussianPools() {\n for (let i = 0; i < GAUSSIAN_POOL_SIZE; i++) {\n _gaussians[0][i] = gaussian(0.5, 0.2);\n _gaussians[1][i] = gaussian(0, 0.02);\n }\n}\n_onSeed(_fillGaussianPools);\n\n// Helper for direction checking - extracted to reduce duplication\nfunction _isLeft(a, b, c) {\n return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) > 0.01;\n}\n\n/**\n * Calculates the centroid of a polygon from its vertices.\n * @param {Object[]} pts - Array of points with {x, y}.\n * @returns {Object} The center point {x, y}.\n */\nfunction _center(pts) {\n if (pts.length === 0) {\n return { x: 0, y: 0 };\n }\n\n if (pts.length < 8) {\n // Simple average for small polygons\n const sum = pts.reduce(\n (center, point) => ({ x: center.x + point.x, y: center.y + point.y }),\n { x: 0, y: 0 },\n );\n return { x: sum.x / pts.length, y: sum.y / pts.length };\n }\n\n // Close polygon if needed\n const v = [...pts];\n if (v[0].x !== v[v.length - 1].x || v[0].y !== v[v.length - 1].y)\n v.push(v[0]);\n\n // Calculate using shoelace formula (more efficient implementation)\n let area = 0,\n cx = 0,\n cy = 0;\n for (let i = 0; i < v.length - 1; i++) {\n const cross = v[i].x * v[i + 1].y - v[i + 1].x * v[i].y;\n area += cross;\n cx += (v[i].x + v[i + 1].x) * cross;\n cy += (v[i].y + v[i + 1].y) * cross;\n }\n\n area *= 0.5;\n return area\n ? { x: cx / (6 * area), y: cy / (6 * area) }\n : { x: v[0].x, y: v[0].y };\n}\n\n/**\n * Fills a given polygon with a watercolor effect.\n * @param {Polygon} polygon - The polygon to fill.\n */\nexport function createFill(polygon) {\n if (!State.fill.isActive || !State.fill.color) {\n throw new Error(\n \"No fill color set. Call brush.fill(color) before drawing shapes.\",\n );\n }\n _polygon = polygon;\n const v = [...polygon.vertices];\n const fluid = ~~(v.length * 0.25 * weightedRand({ 1: 5, 2: 10, 3: 60 }));\n const strength = State.fill.bleed_strength;\n const modifiers = v.map(\n (_, i) => (i > fluid ? 1 : 0.3) * rr(0.85, 1.4) * strength,\n );\n const shift = randInt(0, v.length);\n const shifted = [...v.slice(shift), ...v.slice(0, shift)];\n const center = _center(shifted);\n return new FillPoly(shifted, modifiers, center, [], true).fill(\n State.fill.color,\n map(State.fill.opacity, 0, 255, 0, 1, true),\n State.fill.texture_strength,\n );\n}\n\n// ---------------------------------------------------------------------------\n// FillPolygon Class\n// ---------------------------------------------------------------------------\n\n/**\n * The FillPolygon class is used to create and manage the properties of the polygons that produces\n * the watercolor effect. It includes methods to grow (expand) the polygon and apply layers\n * of color with varying intensity and erase parts to simulate a natural watercolor bleed.\n * The implementation follows Tyler Hobbs' guide to simulating watercolor:\n * https://tylerxhobbs.com/essays/2017/a-generative-approach-to-simulating-watercolor-paints\n */\nclass FillPoly {\n /**\n * Constructs a FillPolygon.\n * @param {Object[]} _v - Vertices of the polygon.\n * @param {number[]} _m - Multipliers for the bleed effect at each vertex.\n * @param {Object} _center - The polygon's center {x, y}.\n * @param {boolean[]} dir - Array indicating bleed direction per vertex.\n * @param {boolean} isFirst - True for initial polygon.\n */\n constructor(v, m, center, dir = [], isFirst = false, sx, sy) {\n // Initialize properties\n this.v = v;\n this.m = m;\n this.dir = dir;\n this.midP = center;\n\n // Initialize size and direction for first polygon\n if (isFirst) {\n // Calculate size bounds\n let maxX = 0,\n maxY = 0;\n const rayCalc = [];\n\n for (let i = 0; i < v.length; i++) {\n // Store vertex distances to center for size calculation\n const dx = Math.abs(center.x - v[i].x);\n const dy = Math.abs(center.y - v[i].y);\n maxX = Math.max(maxX, dx);\n maxY = Math.max(maxY, dy);\n\n // Store edge info for ray calculations\n const v1 = v[i],\n v2 = v[(i + 1) % v.length];\n const side = { x: v2.x - v1.x, y: v2.y - v1.y };\n const rt = rotate(0, 0, side.x, side.y, 90);\n const mid = { x: v1.x + side.x / 2, y: v1.y + side.y / 2 };\n\n rayCalc.push({\n v1,\n v2,\n ray: {\n point1: mid,\n point2: { x: mid.x + rt.x, y: mid.y + rt.y },\n },\n });\n }\n\n // Store sizes\n this.sizeX = maxX;\n this.sizeY = maxY;\n\n // Calculate directions\n this.dir = Array(v.length);\n rayCalc.forEach((rc, i) => {\n let count = 0;\n for (const isect of _polygon.intersect(rc.ray)) {\n if (_isLeft(rc.v1, rc.v2, isect)) count++;\n }\n this.dir[i] = count % 2 === 0;\n });\n\n // Randomize center (single calculation)\n const rx = rr(-0.6, 0.6) * maxX;\n const ry = rr(-0.6, 0.6) * maxY;\n this.midP = { x: center.x + rx, y: center.y + ry };\n } else {\n this.sizeX = sx;\n this.sizeY = sy;\n }\n }\n\n /**\n * Trims vertices from the polygon based on a factor.\n * @param {number} [factor=1] - Factor determining amount of trimming.\n * @returns {Object} An object containing trimmed vertices, multipliers, and direction.\n */\n trim(f = 1) {\n // Fast path for common case\n if (f >= 1 || f < 0 || this.v.length <= 8) {\n return { v: this.v, m: this.m, dir: this.dir };\n }\n\n // Trim from middle for balance\n const n = ~~((1 - f) * this.v.length);\n const s = ~~(this.v.length / 2 - n / 2);\n\n // Copy only the kept ranges instead of cloning the full arrays and splicing.\n const keep = this.v.length - n;\n const v = new Array(keep);\n const m = new Array(keep);\n const dir = new Array(keep);\n let dst = 0;\n\n for (let i = 0; i < s; i++, dst++) {\n v[dst] = this.v[i];\n m[dst] = this.m[i];\n dir[dst] = this.dir[i];\n }\n\n for (let i = s + n; i < this.v.length; i++, dst++) {\n v[dst] = this.v[i];\n m[dst] = this.m[i];\n dir[dst] = this.dir[i];\n }\n\n\n // We want to add at least two vertices to divide the new edge that appears after trimming, at random distances along its path\n const trimStart = s;\n const trimEnd = s + n;\n const edgeStart = this.v[(trimStart - 1 + this.v.length) % this.v.length];\n const edgeEnd = this.v[trimEnd % this.v.length];\n const edgeVec = { x: edgeEnd.x - edgeStart.x, y: edgeEnd.y - edgeStart.y };\n \n // Insert two new vertices at random positions along the new edge\n const insertCount = 2;\n for (let i = 0; i < insertCount; i++) {\n const t = rr(0.25, 0.75); // Random position between 25% and 75% along the edge\n const newVertex = { x: edgeStart.x + edgeVec.x * t, y: edgeStart.y + edgeVec.y * t };\n const insertIdx = s + i;\n v.splice(insertIdx, 0, newVertex);\n m.splice(insertIdx, 0, rr(0.4, 0.7));\n dir.splice(insertIdx, 0, this.dir[trimStart % this.dir.length]);\n }\n\n return { v, m, dir };\n }\n\n /**\n * Randomly samples a fraction of vertices, keeping their order.\n * Any sampled vertex outside the original polygon is pulled inward.\n * @param {number} [ratio=0.3] - Fraction of vertices to keep.\n * @returns {FillPoly} A new FillPoly with fewer vertices, guaranteed inside the original.\n */\n scatter(ratio = 0.3) {\n const L = this.v.length;\n const keep = Math.max(3, ~~(L * ratio));\n const indices = [];\n const step = L / keep;\n for (let i = 0; i < keep; i++) {\n indices.push(~~(i * step + rr(0, step * 0.8)));\n }\n\n const sv = [],\n sm = [],\n sd = [];\n const mid = this.midP;\n const sides = _polygon.sides;\n\n for (const idx of indices) {\n const j = idx % L;\n let p = this.v[j];\n let crossings = 0;\n for (const [a, b] of sides) {\n const ay = a.y,\n by = b.y;\n if ((ay > p.y) === (by > p.y)) continue;\n const t = (p.y - ay) / (by - ay);\n if (p.x < a.x + t * (b.x - a.x)) crossings++;\n }\n if (crossings % 2 === 0) {\n p = {\n x: mid.x + (p.x - mid.x) * rr(0.3, 0.6),\n y: mid.y + (p.y - mid.y) * rr(0.3, 0.6),\n };\n }\n sv.push(p);\n sm.push(this.m[j]);\n sd.push(!this.dir[j]);\n }\n\n return new FillPoly(sv, sm, this.midP, sd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Returns a copy with all bleed directions flipped.\n */\n flipDirs() {\n return new FillPoly(this.v, this.m, this.midP, this.dir.map(d => !d), false, this.sizeX, this.sizeY);\n }\n\n /**\n * Grows (or shrinks) the polygon vertices to simulate watercolor spread.\n * @param {number} [growthFactor=1] - Factor controlling growth.\n * @returns {FillPoly} A new FillPoly with adjusted vertices.\n */\n grow(f = 1) {\n const { v: tr_v, m: tr_m, dir: tr_dir } = this.trim(f);\n const len = tr_v.length;\n\n const outLen = len * 2;\n if (_growInsX.length < len) { _growInsX = new Array(len); _growInsY = new Array(len); }\n if (_growMods.length < outLen) { _growMods = new Array(outLen); _growDirs = new Array(outLen); }\n const insertedX = _growInsX;\n const insertedY = _growInsY;\n const newMods = _growMods;\n const newDirs = _growDirs;\n const bleedDirDeg = State.fill.direction === \"out\" ? -90 : 90;\n\n if (_gaussians[0].length === 0) _fillGaussianPools();\n const gPool = _gaussians[0],\n gPoolLen = gPool.length;\n const g2Pool = _gaussians[1],\n g2PoolLen = g2Pool.length;\n\n let idx = 0;\n let insertedIdx = 0;\n let mod = f === 999 ? rr(0.6, 0.8) : State.fill.bleed_strength;\n\n for (let i = 0; i < len; i++) {\n const cv = tr_v[i];\n const nv = tr_v[i + 1 < len ? i + 1 : 0];\n const mi = tr_m[i];\n const di = tr_dir[i];\n\n if (f < 997) mod = mi;\n\n // If mod is smaller than 0.02, skip growing math and just insert the middle vertex\n if (mod < 0.05) {\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n insertedX[insertedIdx] = (cv.x + nv.x) / 2;\n insertedY[insertedIdx] = (cv.y + nv.y) / 2;\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n insertedIdx++;\n continue;\n }\n\n const rotDeg = (di ? bleedDirDeg : -bleedDirDeg) + rr(-1, 1) * 5;\n const c = cos(rotDeg);\n const s = sin(rotDeg);\n\n const sideX = nv.x - cv.x;\n const sideY = nv.y - cv.y;\n const dirX = c * sideX + s * sideY;\n const dirY = c * sideY - s * sideX;\n\n const d = gPool[~~(rr(0, 1) * gPoolLen)] * rr(0.65, 1.35) * mod;\n const nextMod = mi + g2Pool[~~(rr(0, 1) * g2PoolLen)];\n\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n\n insertedX[insertedIdx] = cv.x + sideX * 0.5 + dirX * d;\n insertedY[insertedIdx] = cv.y + sideY * 0.5 + dirY * d;\n newMods[idx] = nextMod;\n newDirs[idx] = di;\n idx++;\n insertedIdx++;\n }\n\n let fv,\n fm,\n fd;\n \n if (GROW_CAP && idx > GROW_CAP) {\n const step = Math.ceil(idx / GROW_CAP);\n const kept = Math.ceil(idx / step);\n fv = new Array(kept);\n fm = new Array(kept);\n fd = new Array(kept);\n let dst = 0;\n for (let j = 0; j < idx; j += step, dst++) {\n fv[dst] =\n j % 2 === 0\n ? tr_v[j >> 1]\n : { x: insertedX[j >> 1], y: insertedY[j >> 1] };\n fm[dst] = newMods[j];\n fd[dst] = newDirs[j];\n }\n } else {\n fv = new Array(idx);\n for (let j = 0; j < idx; j++) {\n fv[j] =\n j % 2 === 0\n ? tr_v[j >> 1]\n : { x: insertedX[j >> 1], y: insertedY[j >> 1] };\n }\n fm = newMods.slice(0, idx);\n fd = newDirs.slice(0, idx);\n }\n return new FillPoly(fv, fm, this.midP, fd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Fills the polygon with multiple layers to simulate a watercolor effect.\n * @param {Color|string} color - The fill color.\n * @param {number} intensity - Opacity intensity (mapped from 0 to 1).\n * @param {number} tex - Texture factor.\n */\n fill(color, intensity, tex) {\n const numLayers = 20;\n const texture = tex * 3;\n const int = 2 * intensity * (1 + tex / 2);\n\n const switchingToFill = Mix.isBrush !== false;\n Mix.isBrush = false;\n if (switchingToFill) Mix.justChanged = true;\n Mix.blend(color);\n\n const m = getAffineMatrix();\n Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * m.a,\n Density * m.b,\n Density * m.c,\n Density * m.d,\n Density * (m.x + Cwidth / 2),\n Density * (m.y + Cheight / 2),\n );\n\n Mix.ctx.strokeStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${\n 0.005 * State.fill.border_strength\n })`;\n Mix.ctx.lineCap = \"round\";\n\n GROW_CAP = GROW_MAX_VERTS * Math.max(0.1, 2 * State.fill.bleed_strength);\n\n const size = Math.max(this.sizeX, this.sizeY);\n const darker = rr(0.15, 0.7);\n let pol = this.grow();\n const sparse = this.scatter(0.1).grow().scatter(0.75).flipDirs();\n let pols;\n\n for (let i = 0; i < numLayers; i++) {\n if (i % 4 === 0) {\n pol = pol.grow();\n }\n\n if (i % 2 === 0) {\n pols = [\n pol.grow(1 - 0.0125 * i),\n pol.grow(0.7 - 0.0125 * i),\n pol.grow(0.4 - 0.0125 * i),\n ];\n }\n\n for (const p of pols) {\n const grown = p.grow(999).grow(997);\n grown.layer(i, size, int, color);\n }\n const sparseLayer = sparse.grow(999).flipDirs().grow(997);\n sparseLayer.layer(i, size, int * texture, color);\n if (i % 2 === 0) {\n const darkerLayer = pol.grow(darker).grow(999);\n darkerLayer.layer(i, size, int * 2, color);\n }\n\n if (i % 8 === 0 || i === numLayers - 1) {\n if (texture !== 0) {\n pol.erase(texture * 3, intensity);\n }\n Mix.blend(color, true);\n }\n }\n\n Mix.ctx.restore();\n }\n\n /**\n * Draws a layer of the fill polygon with stroke and fill.\n * @param {number} i - The layer index.\n */\n layer(i, size, int, color) {\n Mix.ctx.lineWidth = map(i, 0, 24, size / 25, size / 30, true);\n\n Mix.ctx.fillStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${int}%)`;\n\n drawPolygon(this.v);\n Mix.ctx.fill();\n Mix.ctx.stroke();\n }\n\n /**\n * Erases parts of the polygon to create a natural watercolor texture.\n * @param {number} texture - Texture strength factor.\n * @param {number} intensity - Intensity value for size scaling.\n */\n erase(texture, intensity) {\n Mix.ctx.save();\n\n const numCircles = ~~(rr(80, 110) * map(texture, 0, 1, 2, 3.5));\n const halfSizeX = this.sizeX / 1.3;\n const halfSizeY = this.sizeY / 1.3;\n const minSize =\n Math.min(this.sizeX, this.sizeY) * (1.3);\n const minSizeFactor = 0.03 * minSize;\n const maxSizeFactor = 0.45 * minSize;\n const { x: midX, y: midY } = this.midP;\n\n Mix.ctx.globalCompositeOperation = \"destination-out\";\n\n const alpha =\n ((5 - map(intensity, 80, 100, 0.3, 0.7, true)) * texture) / 255;\n Mix.ctx.fillStyle = `rgb(255 0 0 / ${alpha})`;\n Mix.ctx.lineWidth = 0;\n\n for (let i = 0; i < numCircles; i++) {\n const x = midX + gaussian(0, halfSizeX);\n const y = midY + gaussian(0, halfSizeY);\n const radius = rr(minSizeFactor, maxSizeFactor);\n\n Mix.ctx.beginPath();\n circle(x, y, radius);\n if (i % 5 !== 0) {\n Mix.ctx.fill();\n }\n }\n\n Mix.ctx.globalCompositeOperation = \"source-over\";\n Mix.ctx.restore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Extend Polygon and Plot Prototypes for Fill\n// ---------------------------------------------------------------------------\n\n/**\n * Applies a fill effect to the polygon using the current fill state.\n * @param {Color|string} [_color] - The color for the fill.\n * @param {number} [_opacity] - The opacity value.\n * @param {number} [_bleed] - The bleed intensity.\n * @param {number} [_texture] - The texture strength.\n * @param {number} [_border] - The border strength.\n * @param {string} [_direction] - The bleed direction.\n */\nPolygon.prototype.fill = function (\n _color = false,\n _opacity,\n _bleed,\n _texture,\n _border,\n _direction,\n) {\n let state = FillState();\n if (_color) {\n fill(_color, _opacity);\n fillBleed(_bleed, _direction);\n fillTexture(_texture, _border);\n }\n if (state.isActive) {\n isFieldReady();\n createFill(this);\n }\n FillSetState(state);\n};\n\n/**\n * Fills a plot on the canvas by generating a polygon based on the provided coordinates.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - Scaling factor.\n */\nPlot.prototype.fill = function (x, y, scale) {\n if (FillState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n this.pol = this.genPol(\n x,\n y,\n scale,\n State.fill.bleed_strength < 0.06\n ? 0\n : map(State.fill.bleed_strength, 0, 0.6, 0.2, 0.60, true),\n );\n this.pol.fill();\n }\n};\n","\nexport default function earcut(data, holeIndices, dim = 2) {\n\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n let outerNode = linkedList(data, 0, outerLen, dim, true);\n const triangles = [];\n\n if (!outerNode || outerNode.next === outerNode.prev) return triangles;\n\n let minX, minY, invSize;\n\n if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);\n\n // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox\n if (data.length > 80 * dim) {\n minX = data[0];\n minY = data[1];\n let maxX = minX;\n let maxY = minY;\n\n for (let i = dim; i < outerLen; i += dim) {\n const x = data[i];\n const y = data[i + 1];\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n\n // minX, minY and invSize are later used to transform coords into integers for z-order calculation\n invSize = Math.max(maxX - minX, maxY - minY);\n invSize = invSize !== 0 ? 32767 / invSize : 0;\n }\n\n earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);\n\n return triangles;\n}\n\n// create a circular doubly linked list from polygon points in the specified winding order\nfunction linkedList(data, start, end, dim, clockwise) {\n let last;\n\n if (clockwise === (signedArea(data, start, end, dim) > 0)) {\n for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n } else {\n for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n }\n\n if (last && equals(last, last.next)) {\n removeNode(last);\n last = last.next;\n }\n\n return last;\n}\n\n// eliminate colinear or duplicate points\nfunction filterPoints(start, end) {\n if (!start) return start;\n if (!end) end = start;\n\n let p = start,\n again;\n do {\n again = false;\n\n if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {\n removeNode(p);\n p = end = p.prev;\n if (p === p.next) break;\n again = true;\n\n } else {\n p = p.next;\n }\n } while (again || p !== end);\n\n return end;\n}\n\n// main ear slicing loop which triangulates a polygon (given as a linked list)\nfunction earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {\n if (!ear) return;\n\n // interlink polygon nodes in z-order\n if (!pass && invSize) indexCurve(ear, minX, minY, invSize);\n\n let stop = ear;\n\n // iterate through ears, slicing them one by one\n while (ear.prev !== ear.next) {\n const prev = ear.prev;\n const next = ear.next;\n\n if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {\n triangles.push(prev.i, ear.i, next.i); // cut off the triangle\n\n removeNode(ear);\n\n // skipping the next vertex leads to less sliver triangles\n ear = next.next;\n stop = next.next;\n\n continue;\n }\n\n ear = next;\n\n // if we looped through the whole remaining polygon and can't find any more ears\n if (ear === stop) {\n // try filtering points and slicing again\n if (!pass) {\n earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);\n\n // if this didn't work, try curing all small self-intersections locally\n } else if (pass === 1) {\n ear = cureLocalIntersections(filterPoints(ear), triangles);\n earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);\n\n // as a last resort, try splitting the remaining polygon into two\n } else if (pass === 2) {\n splitEarcut(ear, triangles, dim, minX, minY, invSize);\n }\n\n break;\n }\n }\n}\n\n// check whether a polygon node forms a valid ear with adjacent nodes\nfunction isEar(ear) {\n const a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n // now make sure we don't have other points inside the potential ear\n const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox\n const x0 = Math.min(ax, bx, cx),\n y0 = Math.min(ay, by, cy),\n x1 = Math.max(ax, bx, cx),\n y1 = Math.max(ay, by, cy);\n\n let p = c.next;\n while (p !== a) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&\n area(p.prev, p, p.next) >= 0) return false;\n p = p.next;\n }\n\n return true;\n}\n\nfunction isEarHashed(ear, minX, minY, invSize) {\n const a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox\n const x0 = Math.min(ax, bx, cx),\n y0 = Math.min(ay, by, cy),\n x1 = Math.max(ax, bx, cx),\n y1 = Math.max(ay, by, cy);\n\n // z-order range for the current triangle bbox;\n const minZ = zOrder(x0, y0, minX, minY, invSize),\n maxZ = zOrder(x1, y1, minX, minY, invSize);\n\n let p = ear.prevZ,\n n = ear.nextZ;\n\n // look for points inside the triangle in both directions\n while (p && p.z >= minZ && n && n.z <= maxZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n // look for remaining points in decreasing z-order\n while (p && p.z >= minZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n }\n\n // look for remaining points in increasing z-order\n while (n && n.z <= maxZ) {\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n return true;\n}\n\n// go through all polygon nodes and cure small local self-intersections\nfunction cureLocalIntersections(start, triangles) {\n let p = start;\n do {\n const a = p.prev,\n b = p.next.next;\n\n if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {\n\n triangles.push(a.i, p.i, b.i);\n\n // remove two nodes involved\n removeNode(p);\n removeNode(p.next);\n\n p = start = b;\n }\n p = p.next;\n } while (p !== start);\n\n return filterPoints(p);\n}\n\n// try splitting polygon into two and triangulate them independently\nfunction splitEarcut(start, triangles, dim, minX, minY, invSize) {\n // look for a valid diagonal that divides the polygon into two\n let a = start;\n do {\n let b = a.next.next;\n while (b !== a.prev) {\n if (a.i !== b.i && isValidDiagonal(a, b)) {\n // split the polygon in two by the diagonal\n let c = splitPolygon(a, b);\n\n // filter colinear points around the cuts\n a = filterPoints(a, a.next);\n c = filterPoints(c, c.next);\n\n // run earcut on each half\n earcutLinked(a, triangles, dim, minX, minY, invSize, 0);\n earcutLinked(c, triangles, dim, minX, minY, invSize, 0);\n return;\n }\n b = b.next;\n }\n a = a.next;\n } while (a !== start);\n}\n\n// link every hole into the outer loop, producing a single-ring polygon without holes\nfunction eliminateHoles(data, holeIndices, outerNode, dim) {\n const queue = [];\n\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n const list = linkedList(data, start, end, dim, false);\n if (list === list.next) list.steiner = true;\n queue.push(getLeftmost(list));\n }\n\n queue.sort(compareXYSlope);\n\n // process holes from left to right\n for (let i = 0; i < queue.length; i++) {\n outerNode = eliminateHole(queue[i], outerNode);\n }\n\n return outerNode;\n}\n\nfunction compareXYSlope(a, b) {\n let result = a.x - b.x;\n // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find\n // the bridge to the outer shell is always the point that they meet at.\n if (result === 0) {\n result = a.y - b.y;\n if (result === 0) {\n const aSlope = (a.next.y - a.y) / (a.next.x - a.x);\n const bSlope = (b.next.y - b.y) / (b.next.x - b.x);\n result = aSlope - bSlope;\n }\n }\n return result;\n}\n\n// find a bridge between vertices that connects hole with an outer ring and link it\nfunction eliminateHole(hole, outerNode) {\n const bridge = findHoleBridge(hole, outerNode);\n if (!bridge) {\n return outerNode;\n }\n\n const bridgeReverse = splitPolygon(bridge, hole);\n\n // filter collinear points around the cuts\n filterPoints(bridgeReverse, bridgeReverse.next);\n return filterPoints(bridge, bridge.next);\n}\n\n// David Eberly's algorithm for finding a bridge between hole and outer polygon\nfunction findHoleBridge(hole, outerNode) {\n let p = outerNode;\n const hx = hole.x;\n const hy = hole.y;\n let qx = -Infinity;\n let m;\n\n // find a segment intersected by a ray from the hole's leftmost point to the left;\n // segment's endpoint with lesser x will be potential connection point\n // unless they intersect at a vertex, then choose the vertex\n if (equals(hole, p)) return p;\n do {\n if (equals(hole, p.next)) return p.next;\n else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {\n const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);\n if (x <= hx && x > qx) {\n qx = x;\n m = p.x < p.next.x ? p : p.next;\n if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint\n }\n }\n p = p.next;\n } while (p !== outerNode);\n\n if (!m) return null;\n\n // look for points inside the triangle of hole point, segment intersection and endpoint;\n // if there are no points found, we have a valid connection;\n // otherwise choose the point of the minimum angle with the ray as connection point\n\n const stop = m;\n const mx = m.x;\n const my = m.y;\n let tanMin = Infinity;\n\n p = m;\n\n do {\n if (hx >= p.x && p.x >= mx && hx !== p.x &&\n pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {\n\n const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential\n\n if (locallyInside(p, hole) &&\n (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {\n m = p;\n tanMin = tan;\n }\n }\n\n p = p.next;\n } while (p !== stop);\n\n return m;\n}\n\n// whether sector in vertex m contains sector in vertex p in the same coordinates\nfunction sectorContainsSector(m, p) {\n return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;\n}\n\n// interlink polygon nodes in z-order\nfunction indexCurve(start, minX, minY, invSize) {\n let p = start;\n do {\n if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);\n p.prevZ = p.prev;\n p.nextZ = p.next;\n p = p.next;\n } while (p !== start);\n\n p.prevZ.nextZ = null;\n p.prevZ = null;\n\n sortLinked(p);\n}\n\n// Simon Tatham's linked list merge sort algorithm\n// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html\nfunction sortLinked(list) {\n let numMerges;\n let inSize = 1;\n\n do {\n let p = list;\n let e;\n list = null;\n let tail = null;\n numMerges = 0;\n\n while (p) {\n numMerges++;\n let q = p;\n let pSize = 0;\n for (let i = 0; i < inSize; i++) {\n pSize++;\n q = q.nextZ;\n if (!q) break;\n }\n let qSize = inSize;\n\n while (pSize > 0 || (qSize > 0 && q)) {\n\n if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {\n e = p;\n p = p.nextZ;\n pSize--;\n } else {\n e = q;\n q = q.nextZ;\n qSize--;\n }\n\n if (tail) tail.nextZ = e;\n else list = e;\n\n e.prevZ = tail;\n tail = e;\n }\n\n p = q;\n }\n\n tail.nextZ = null;\n inSize *= 2;\n\n } while (numMerges > 1);\n\n return list;\n}\n\n// z-order of a point given coords and inverse of the longer side of data bbox\nfunction zOrder(x, y, minX, minY, invSize) {\n // coords are transformed into non-negative 15-bit integer range\n x = (x - minX) * invSize | 0;\n y = (y - minY) * invSize | 0;\n\n x = (x | (x << 8)) & 0x00FF00FF;\n x = (x | (x << 4)) & 0x0F0F0F0F;\n x = (x | (x << 2)) & 0x33333333;\n x = (x | (x << 1)) & 0x55555555;\n\n y = (y | (y << 8)) & 0x00FF00FF;\n y = (y | (y << 4)) & 0x0F0F0F0F;\n y = (y | (y << 2)) & 0x33333333;\n y = (y | (y << 1)) & 0x55555555;\n\n return x | (y << 1);\n}\n\n// find the leftmost node of a polygon ring\nfunction getLeftmost(start) {\n let p = start,\n leftmost = start;\n do {\n if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;\n p = p.next;\n } while (p !== start);\n\n return leftmost;\n}\n\n// check if a point lies within a convex triangle\nfunction pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {\n return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&\n (ax - px) * (by - py) >= (bx - px) * (ay - py) &&\n (bx - px) * (cy - py) >= (cx - px) * (by - py);\n}\n\n// check if a point lies within a convex triangle but false if its equal to the first point of the triangle\nfunction pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {\n return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);\n}\n\n// check if a diagonal between two polygon nodes is valid (lies in polygon interior)\nfunction isValidDiagonal(a, b) {\n return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges\n (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible\n (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors\n equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case\n}\n\n// signed area of a triangle\nfunction area(p, q, r) {\n return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);\n}\n\n// check if two points are equal\nfunction equals(p1, p2) {\n return p1.x === p2.x && p1.y === p2.y;\n}\n\n// check if two segments intersect\nfunction intersects(p1, q1, p2, q2) {\n const o1 = sign(area(p1, q1, p2));\n const o2 = sign(area(p1, q1, q2));\n const o3 = sign(area(p2, q2, p1));\n const o4 = sign(area(p2, q2, q1));\n\n if (o1 !== o2 && o3 !== o4) return true; // general case\n\n if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1\n if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1\n if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2\n if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2\n\n return false;\n}\n\n// for collinear points p, q, r, check if point q lies on segment pr\nfunction onSegment(p, q, r) {\n return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);\n}\n\nfunction sign(num) {\n return num > 0 ? 1 : num < 0 ? -1 : 0;\n}\n\n// check if a polygon diagonal intersects any polygon segments\nfunction intersectsPolygon(a, b) {\n let p = a;\n do {\n if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&\n intersects(p, p.next, a, b)) return true;\n p = p.next;\n } while (p !== a);\n\n return false;\n}\n\n// check if a polygon diagonal is locally inside the polygon\nfunction locallyInside(a, b) {\n return area(a.prev, a, a.next) < 0 ?\n area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :\n area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;\n}\n\n// check if the middle point of a polygon diagonal is inside the polygon\nfunction middleInside(a, b) {\n let p = a;\n let inside = false;\n const px = (a.x + b.x) / 2;\n const py = (a.y + b.y) / 2;\n do {\n if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&\n (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))\n inside = !inside;\n p = p.next;\n } while (p !== a);\n\n return inside;\n}\n\n// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;\n// if one belongs to the outer ring and another to a hole, it merges it into a single ring\nfunction splitPolygon(a, b) {\n const a2 = createNode(a.i, a.x, a.y),\n b2 = createNode(b.i, b.x, b.y),\n an = a.next,\n bp = b.prev;\n\n a.next = b;\n b.prev = a;\n\n a2.next = an;\n an.prev = a2;\n\n b2.next = a2;\n a2.prev = b2;\n\n bp.next = b2;\n b2.prev = bp;\n\n return b2;\n}\n\n// create a node and optionally link it with previous one (in a circular doubly linked list)\nfunction insertNode(i, x, y, last) {\n const p = createNode(i, x, y);\n\n if (!last) {\n p.prev = p;\n p.next = p;\n\n } else {\n p.next = last.next;\n p.prev = last;\n last.next.prev = p;\n last.next = p;\n }\n return p;\n}\n\nfunction removeNode(p) {\n p.next.prev = p.prev;\n p.prev.next = p.next;\n\n if (p.prevZ) p.prevZ.nextZ = p.nextZ;\n if (p.nextZ) p.nextZ.prevZ = p.prevZ;\n}\n\nfunction createNode(i, x, y) {\n return {\n i, // vertex index in coordinates array\n x, y, // vertex coordinates\n prev: null, // previous and next vertex nodes in a polygon ring\n next: null,\n z: 0, // z-order curve value\n prevZ: null, // previous and next nodes in z-order\n nextZ: null,\n steiner: false // indicates whether this is a steiner point\n };\n}\n\n// return a percentage difference between the polygon area and its triangulation area;\n// used to verify correctness of triangulation\nexport function deviation(data, holeIndices, dim, triangles) {\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n\n let polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));\n if (hasHoles) {\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n polygonArea -= Math.abs(signedArea(data, start, end, dim));\n }\n }\n\n let trianglesArea = 0;\n for (let i = 0; i < triangles.length; i += 3) {\n const a = triangles[i] * dim;\n const b = triangles[i + 1] * dim;\n const c = triangles[i + 2] * dim;\n trianglesArea += Math.abs(\n (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -\n (data[a] - data[b]) * (data[c + 1] - data[a + 1]));\n }\n\n return polygonArea === 0 && trianglesArea === 0 ? 0 :\n Math.abs((trianglesArea - polygonArea) / polygonArea);\n}\n\nfunction signedArea(data, start, end, dim) {\n let sum = 0;\n for (let i = start, j = end - dim; i < end; i += dim) {\n sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);\n j = i;\n }\n return sum;\n}\n\n// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts\nexport function flatten(data) {\n const vertices = [];\n const holes = [];\n const dimensions = data[0][0].length;\n let holeIndex = 0;\n let prevLen = 0;\n\n for (const ring of data) {\n for (const p of ring) {\n for (let d = 0; d < dimensions; d++) vertices.push(p[d]);\n }\n if (prevLen) {\n holeIndex += prevLen;\n holes.push(holeIndex);\n }\n prevLen = ring.length;\n }\n return {vertices, holes, dimensions};\n}\n","// =============================================================================\n// Module: Wash\n// =============================================================================\n/**\n * Minimal stateful API for the `wash()` fill modifier.\n */\n\nimport earcut from \"earcut\";\nimport { Renderer, Cwidth, Cheight, isCanvasReady } from \"../core/target.js\";\nimport { State, flushActiveComposite } from \"../core/color.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { getAffineMatrix } from \"../core/runtime.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport { createColor } from \"../core/runtime.js\";\nimport { resetDirectShaderTracking } from \"../core/renderer_runtime.js\";\n\nlet gl = null;\nlet washProgram = null;\nlet washVao = null;\nlet washBuffer = null;\nlet washProjection = null;\nlet loadedWidth = 0;\nlet loadedHeight = 0;\nlet washGpuBufferSize = 0;\n\nconst WashAttr = {};\nconst WashUniform = {};\n\nconst washVertSrc = `#version 300 es\nin vec2 a_position;\nuniform mat4 u_matrix;\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n}`;\n\nconst washFragSrc = `#version 300 es\nprecision highp float;\nuniform vec4 u_color;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(u_color.rgb * u_color.a, u_color.a);\n}`;\n\nState.wash = {\n color: null,\n opacity: 150,\n isActive: false,\n};\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Enables wash mode with a color and opacity.\n *\n * @param {number|string|Color} a - Either the red component, a CSS color string, or a Color object.\n * @param {number} [b] - The green component or the opacity if using grayscale.\n * @param {number} [c] - The blue component.\n * @param {number} [d] - The opacity.\n */\nexport function wash(a, b, c, d) {\n isCanvasReady();\n State.wash.opacity = (arguments.length < 4 ? b : d) ?? 150;\n State.wash.color = arguments.length < 3 ? createColor(a) : createColor(a, b, c);\n State.wash.isActive = true;\n}\n\n/**\n * Disables wash mode for subsequent drawing operations.\n */\nexport function noWash() {\n State.wash.isActive = false;\n}\n\n// =============================================================================\n// GL helpers\n// =============================================================================\n\n/**\n * Lazily creates the reusable program/buffer state for solid wash drawing and\n * refreshes the orthographic projection when the active target size changes.\n */\nfunction ensureWashReady() {\n const nextGl = Renderer.drawingContext;\n const sizeChanged = loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (!washProjection || sizeChanged) {\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n washProjection = new Float32Array([\n 2 / loadedWidth,\n 0,\n 0,\n 0,\n 0,\n -2 / loadedHeight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n 1,\n 0,\n 1,\n ]);\n }\n\n if (gl === nextGl && washProgram && washVao && washBuffer) return;\n\n gl = nextGl;\n washProgram = createProgram(gl, washVertSrc, washFragSrc);\n WashAttr.a_position = gl.getAttribLocation(washProgram, \"a_position\");\n WashUniform.u_matrix = gl.getUniformLocation(washProgram, \"u_matrix\");\n WashUniform.u_color = gl.getUniformLocation(washProgram, \"u_color\");\n\n washVao = gl.createVertexArray();\n gl.bindVertexArray(washVao);\n\n washBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, 0, gl.DYNAMIC_DRAW);\n washGpuBufferSize = 0;\n\n gl.enableVertexAttribArray(WashAttr.a_position);\n gl.vertexAttribPointer(WashAttr.a_position, 2, gl.FLOAT, false, 8, 0);\n\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n}\n\n/**\n * Applies the current runtime affine transform and converts the result into\n * the screen-space coordinates used by the direct GL wash pipeline.\n *\n * @param {number} x - The source x-coordinate in brush drawing space.\n * @param {number} y - The source y-coordinate in brush drawing space.\n * @returns {[number, number]} The transformed screen-space position.\n */\nfunction transformVertexToScreen(x, y) {\n const m = getAffineMatrix();\n return [\n m.a * x + m.c * y + m.x + loadedWidth / 2,\n m.b * x + m.d * y + m.y + loadedHeight / 2,\n ];\n}\n\n/**\n * Triangulates a polygon in local space and returns the transformed triangle\n * vertex buffer ready for upload to the GPU.\n *\n * @param {Polygon} polygon - The polygon to triangulate.\n * @returns {{ triangles: Float32Array, vertexCount: number }} Screen-space\n * triangle vertices plus the number of vertices to draw.\n */\nfunction buildTriangleBuffer(polygon) {\n const flat = new Float32Array(polygon.vertices.length * 2);\n for (let i = 0; i < polygon.vertices.length; i++) {\n const vertex = polygon.vertices[i];\n flat[i * 2] = vertex.x;\n flat[i * 2 + 1] = vertex.y;\n }\n\n const indices = earcut(flat);\n const triangles = new Float32Array(indices.length * 2);\n for (let i = 0; i < indices.length; i++) {\n const idx = indices[i];\n const [screenX, screenY] = transformVertexToScreen(flat[idx * 2], flat[idx * 2 + 1]);\n triangles[i * 2] = screenX;\n triangles[i * 2 + 1] = screenY;\n }\n\n return {\n triangles,\n vertexCount: indices.length,\n };\n}\n\n/**\n * Draws a triangulated solid wash directly to the current GL target.\n *\n * @param {Polygon} polygon - The polygon to fill with the current wash state.\n */\nfunction drawWashPolygon(polygon) {\n if (!State.wash?.isActive || !State.wash.color || polygon.vertices.length < 3) return;\n\n flushActiveComposite();\n ensureWashReady();\n const { triangles, vertexCount } = buildTriangleBuffer(polygon);\n const byteCount = triangles.byteLength;\n gl.useProgram(washProgram);\n gl.enable(gl.BLEND);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n gl.bindVertexArray(washVao);\n gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);\n if (byteCount > washGpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, triangles, gl.DYNAMIC_DRAW);\n washGpuBufferSize = byteCount;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, triangles);\n }\n const color = State.wash.color._array;\n gl.uniformMatrix4fv(WashUniform.u_matrix, false, washProjection);\n gl.uniform4f(\n WashUniform.u_color,\n color[0],\n color[1],\n color[2],\n State.wash.opacity / 255,\n );\n\n gl.drawArrays(gl.TRIANGLES, 0, vertexCount);\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n resetDirectShaderTracking(Renderer, gl);\n}\n\n// =============================================================================\n// Prototype methods\n// =============================================================================\n\n/**\n * Applies a direct GL wash fill to the polygon using the current wash state.\n *\n * @param {Color|string|false} [_color] - Optional override color for this call.\n * @param {number} [_opacity] - Optional override opacity for this call.\n */\nPolygon.prototype.wash = function (_color = false, _opacity) {\n const state = { ...State.wash };\n if (_color !== false) wash(_color, _opacity);\n\n if (State.wash.isActive) {\n drawWashPolygon(this);\n }\n\n State.wash = { ...state };\n};\n\n/**\n * Applies wash to a plot by first generating the plot polygon, mirroring the\n * existing fill-path behavior, and then drawing that polygon with wash.\n *\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\nPlot.prototype.wash = function (x, y, scale) {\n if (!State.wash?.isActive) return;\n if (this.origin) {\n x = this.origin[0];\n y = this.origin[1];\n scale = 1;\n }\n this.pol = this.genPol(x, y, scale, 0, -1);\n this.pol.wash();\n};\n","// =============================================================================\n// Adapter: Standalone Renderer Hooks\n// =============================================================================\n\nimport { Cwidth, Cheight, Density } from \"../../core/target.js\";\nimport { setRendererRuntime } from \"../../core/renderer_runtime.js\";\n\nfunction beginDirectMaskDraw(_renderer, gl, target) {\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n if (hadDepthTest) gl.disable(gl.DEPTH_TEST);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, target.framebuffer);\n gl.viewport(0, 0, target.width * target.density, target.height * target.density);\n\n return { hadDepthTest };\n}\n\nfunction endDirectMaskDraw(renderer, gl, state) {\n if (state?.hadDepthTest) gl.enable(gl.DEPTH_TEST);\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.viewport(\n 0,\n 0,\n Math.max(1, Math.round(Cwidth * Density)),\n Math.max(1, Math.round(Cheight * Density)),\n );\n}\n\nfunction resetStandaloneShaderTracking(_renderer, gl) {\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n}\n\nexport function initStandaloneRendererRuntime() {\n setRendererRuntime({\n beginDirectMaskDraw,\n endDirectMaskDraw,\n resetDirectShaderTracking: resetStandaloneShaderTracking,\n });\n}\n","// =============================================================================\n// Adapter: Standalone Compositor Hooks\n// =============================================================================\n\nimport { createProgram } from \"../../core/gl/utils.js\";\nimport {\n setCompositorRuntime,\n blitDefaultFramebufferSource,\n} from \"../../core/compositor_runtime.js\";\n\nfunction clearTarget(renderer, target, isFramebufferTarget) {\n if (!target) return;\n\n if (isFramebufferTarget(target)) {\n const gl = renderer.drawingContext;\n const previousFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);\n const previousViewport = gl.getParameter(gl.VIEWPORT);\n gl.bindFramebuffer(gl.FRAMEBUFFER, target.framebuffer);\n gl.viewport(0, 0, target.width * target.density, target.height * target.density);\n gl.clearColor(0, 0, 0, 0);\n gl.clear(gl.COLOR_BUFFER_BIT);\n gl.bindFramebuffer(gl.FRAMEBUFFER, previousFramebuffer);\n gl.viewport(\n previousViewport[0],\n previousViewport[1],\n previousViewport[2],\n previousViewport[3],\n );\n return;\n }\n\n const ctx = target.drawingContext;\n ctx.save();\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.clearRect(0, 0, target.width, target.height);\n ctx.restore();\n}\n\nfunction makeShader(gl, vertSrc, fragSrc) {\n const program = createProgram(gl, vertSrc, fragSrc);\n const uniformCache = new Map();\n\n // Persistent VAO for fullscreen-triangle draws (avoids create/delete per pass)\n const quadVao = gl.createVertexArray();\n\n const getUniformLocation = (name) => {\n if (!uniformCache.has(name)) {\n uniformCache.set(name, gl.getUniformLocation(program, name));\n }\n return uniformCache.get(name);\n };\n\n // Pre-cache sampler and color uniform locations (called every blend pass)\n const loc_source = gl.getUniformLocation(program, \"u_source\");\n const loc_mask = gl.getUniformLocation(program, \"u_mask\");\n const loc_color = gl.getUniformLocation(program, \"u_color\");\n\n return {\n program,\n quadVao,\n loc_source,\n loc_mask,\n loc_color,\n setUniform(name, value) {\n const location = getUniformLocation(name);\n if (!location) return;\n if (typeof value === \"boolean\") {\n gl.uniform1i(location, value ? 1 : 0);\n return;\n }\n if (typeof value === \"number\") {\n gl.uniform1f(location, value);\n return;\n }\n if (Array.isArray(value)) {\n if (value.length === 3) gl.uniform3f(location, value[0], value[1], value[2]);\n else if (value.length === 4) gl.uniform4f(location, value[0], value[1], value[2], value[3]);\n return;\n }\n },\n };\n}\n\nfunction ensureBlendShaderProgram(renderer, vertSrc, fragSrc) {\n renderer.shaderProgram ??= makeShader(renderer.drawingContext, vertSrc, fragSrc);\n return renderer.shaderProgram;\n}\n\nfunction createFramebufferTexture(gl, width, height) {\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(\n gl.TEXTURE_2D,\n 0,\n gl.RGBA,\n width,\n height,\n 0,\n gl.RGBA,\n gl.UNSIGNED_BYTE,\n null,\n );\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.bindTexture(gl.TEXTURE_2D, null);\n return texture;\n}\n\nfunction createFramebuffer(renderer, options) {\n const gl = renderer.drawingContext;\n const density = options.density ?? 1;\n const framebuffer = gl.createFramebuffer();\n const width = Math.max(1, options.width);\n const height = Math.max(1, options.height);\n const pixelWidth = Math.max(1, Math.round(width * density));\n const pixelHeight = Math.max(1, Math.round(height * density));\n const colorTexture = createFramebufferTexture(gl, pixelWidth, pixelHeight);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);\n gl.framebufferTexture2D(\n gl.FRAMEBUFFER,\n gl.COLOR_ATTACHMENT0,\n gl.TEXTURE_2D,\n colorTexture,\n 0,\n );\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n\n return {\n __brushFramebuffer: true,\n framebuffer,\n colorTexture,\n width,\n height,\n density,\n pixelDensity: () => density,\n remove() {\n gl.deleteFramebuffer(framebuffer);\n gl.deleteTexture(colorTexture);\n },\n };\n}\n\nfunction ensureBlendSourceFramebuffer(\n renderer,\n currentFramebuffer,\n width,\n height,\n density,\n) {\n currentFramebuffer?.remove?.();\n return createFramebuffer(renderer, {\n width,\n height,\n density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n}\n\nfunction runBlendShaderPass({\n renderer,\n shader,\n source,\n mask,\n color,\n isBrushMask,\n dirtyRect,\n targetIsFramebuffer,\n withScissor,\n}) {\n const gl = renderer.drawingContext;\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n const previousFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);\n const previousProgram = gl.getParameter(gl.CURRENT_PROGRAM);\n const previousVao = gl.getParameter(gl.VERTEX_ARRAY_BINDING);\n\n gl.bindVertexArray(shader.quadVao);\n gl.useProgram(shader.program);\n gl.disable(gl.DEPTH_TEST);\n gl.enable(gl.BLEND);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, source.colorTexture);\n gl.uniform1i(shader.loc_source, 0);\n\n gl.activeTexture(gl.TEXTURE1);\n gl.bindTexture(gl.TEXTURE_2D, mask.colorTexture);\n gl.uniform1i(shader.loc_mask, 1);\n\n shader.setUniform(\"u_targetIsFramebuffer\", targetIsFramebuffer);\n shader.setUniform(\"u_isBrush\", isBrushMask);\n gl.uniform3f(shader.loc_color, color[0], color[1], color[2]);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n withScissor(\n gl,\n dirtyRect,\n () => {\n gl.drawArrays(gl.TRIANGLES, 0, 3);\n },\n !targetIsFramebuffer,\n );\n\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.activeTexture(gl.TEXTURE0);\n gl.bindVertexArray(previousVao);\n gl.useProgram(previousProgram);\n gl.bindFramebuffer(gl.FRAMEBUFFER, previousFramebuffer);\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n}\n\nfunction blitSourceToFramebuffer(args) {\n return blitDefaultFramebufferSource(args);\n}\n\nexport function initStandaloneCompositorRuntime() {\n setCompositorRuntime({\n clearTarget,\n ensureBlendShaderProgram,\n ensureBlendSourceFramebuffer,\n createFramebuffer,\n runBlendShaderPass,\n blitSourceToFramebuffer,\n });\n}\n","// =============================================================================\n// Adapter: Standalone Stroke Hooks\n// =============================================================================\n\nimport { create2DCanvas, get2DContext } from \"../../core/compositor_runtime.js\";\nimport { setStrokeRuntime } from \"../../stroke/runtime.js\";\n\nfunction cssColor(value) {\n if (typeof value === \"number\") {\n const c = Math.max(0, Math.min(255, value));\n return `rgb(${c} ${c} ${c})`;\n }\n return value ?? \"black\";\n}\n\nfunction buildTipSurface(canvas) {\n const ctx = get2DContext(canvas, true);\n const surface = {\n canvas,\n drawingContext: ctx,\n width: canvas.width,\n height: canvas.height,\n pixels: null,\n _fillStyle: \"#ffffff\",\n _strokeStyle: \"transparent\",\n _lineWidth: 1,\n\n pixelDensity() {\n return 1;\n },\n\n background(value) {\n ctx.save();\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.fillStyle = cssColor(value);\n ctx.fillRect(0, 0, canvas.width, canvas.height);\n ctx.restore();\n },\n\n noSmooth() {\n ctx.imageSmoothingEnabled = false;\n },\n\n push() {\n ctx.save();\n },\n\n pop() {\n ctx.restore();\n },\n\n translate(x, y) {\n ctx.translate(x, y);\n },\n\n scale(x, y = x) {\n ctx.scale(x, y);\n },\n\n rotate(angle) {\n ctx.rotate(angle);\n },\n\n noStroke() {\n surface._strokeStyle = \"transparent\";\n },\n\n stroke(value) {\n surface._strokeStyle = cssColor(value);\n },\n\n noFill() {\n surface._fillStyle = \"transparent\";\n },\n\n fill(value) {\n surface._fillStyle = cssColor(value);\n },\n\n strokeWeight(value) {\n surface._lineWidth = value;\n },\n\n rect(x, y, w, h) {\n ctx.beginPath();\n ctx.rect(x, y, w, h);\n surface._paint();\n },\n\n circle(x, y, d) {\n ctx.beginPath();\n ctx.arc(x, y, d / 2, 0, Math.PI * 2);\n surface._paint();\n },\n\n ellipse(x, y, w, h) {\n ctx.beginPath();\n ctx.ellipse(x, y, w / 2, h / 2, 0, 0, Math.PI * 2);\n surface._paint();\n },\n\n line(x1, y1, x2, y2) {\n ctx.beginPath();\n ctx.moveTo(x1, y1);\n ctx.lineTo(x2, y2);\n ctx.strokeStyle = surface._strokeStyle;\n ctx.lineWidth = surface._lineWidth;\n ctx.stroke();\n },\n\n beginShape() {\n ctx.beginPath();\n surface._shapeStarted = false;\n },\n\n vertex(x, y) {\n if (!surface._shapeStarted) {\n ctx.moveTo(x, y);\n surface._shapeStarted = true;\n } else {\n ctx.lineTo(x, y);\n }\n },\n\n endShape(close = false) {\n if (close) ctx.closePath();\n surface._paint();\n },\n\n loadPixels() {\n surface.pixels = ctx.getImageData(0, 0, canvas.width, canvas.height).data;\n },\n\n updatePixels() {\n const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);\n imageData.data.set(surface.pixels);\n ctx.putImageData(imageData, 0, 0);\n },\n\n _paint() {\n if (surface._fillStyle !== \"transparent\") {\n ctx.fillStyle = surface._fillStyle;\n ctx.fill();\n }\n if (surface._strokeStyle !== \"transparent\") {\n ctx.strokeStyle = surface._strokeStyle;\n ctx.lineWidth = surface._lineWidth;\n ctx.stroke();\n }\n },\n };\n\n return surface;\n}\n\nfunction createTipSurface(width, height) {\n return buildTipSurface(create2DCanvas(width, height, true));\n}\n\nfunction loadImageTip(src, imageToWhite) {\n return new Promise((resolve, reject) => {\n const NativeImage = globalThis.Image;\n if (!NativeImage) {\n reject(new Error(\"Standalone image brush loading requires Image support.\"));\n return;\n }\n\n const nativeImg = new NativeImage();\n nativeImg.onload = () => {\n const surface = buildTipSurface(\n create2DCanvas(nativeImg.naturalWidth, nativeImg.naturalHeight, true),\n );\n surface.drawingContext.drawImage(nativeImg, 0, 0);\n imageToWhite(surface);\n resolve(surface);\n };\n nativeImg.onerror = () =>\n reject(new Error(`Failed to load image tip: ${src}`));\n nativeImg.crossOrigin = \"anonymous\";\n nativeImg.src = src;\n });\n}\n\nexport function initStandaloneStrokeRuntime() {\n setStrokeRuntime({\n createTipSurface,\n loadImageTip,\n });\n}\n","/**\n * @fileoverview Standalone entry point for brush.\n */\n\nexport * from \"./adapters/standalone/runtime.js\";\nexport * from \"./adapters/standalone/frame.js\";\nexport { createCanvas } from \"./adapters/standalone/target.js\";\nexport * from \"./index.shared.js\";\n\nimport { initStandaloneTargetRuntime } from \"./adapters/standalone/target.js\";\nimport { initStandaloneRendererRuntime } from \"./adapters/standalone/renderer.js\";\nimport { initStandaloneCompositorRuntime } from \"./adapters/standalone/compositor.js\";\nimport { initStandaloneStrokeRuntime } from \"./adapters/standalone/stroke.js\";\nimport { initStandaloneRuntime } from \"./adapters/standalone/runtime.js\";\n\ninitStandaloneTargetRuntime();\ninitStandaloneRuntime();\ninitStandaloneRendererRuntime();\ninitStandaloneCompositorRuntime();\ninitStandaloneStrokeRuntime();\n"],"names":["identityMatrix","a","b","c","d","x","y","Cwidth","Cheight","Renderer","Density","usesRadians","fromDegrees","angle","createColor","Error","getAffineMatrix","targetRuntime","load","syncDensity","isCanvasReady","instance","inst","activateInstance","deactivateInstance","getActiveFramebuffer","isFramebufferTarget","setTargetState","state","Instance","target","expandDirtyRect","rect","padding","minX","minY","maxX","maxY","create2DCanvas","width","height","willReadFrequently","canvas","OffscreenCanvas","element","document","createElement","drawingContext","getContext","undefined","compositorRuntime","clearTarget","ensureBlendShaderProgram","ensureBlendSourceFramebuffer","createFramebuffer","runBlendShaderPass","blitSourceToFramebuffer","args","strokeComposite","fillComposite","clearRenderTarget","getTargetPixelSize","Math","max","round","normalizeDirtyRect","floor","min","ceil","clampDirtyRect","getFullDirtyRect","getFullRect","toScissorBox","flipY","normalized","withScissor","gl","draw","box","enable","SCISSOR_TEST","scissor","disable","State","isMixReady","loaded","Mix","isBlending","cachedColor","markDirtyRect","dirtyRect","isDrawn","clearMask","composite","this","glMask","getCompositeRect","isBrushMask","needsBlendSourceFramebuffer","blendSourceFramebuffer","pixelDensity","ensureResources","fillResources","mask","ctx","blend","_color","_isLast","isBrush","otherMask","nextColor","_array","colorChanged","justChanged","applyShader","shader","shaderProgram","activeFramebuffer","source","renderer","sourceTarget","sourceFramebuffer","targetIsFramebuffer","shaderMask","getShaderMask","color","flushActiveComposite","buffer","loadTarget","SQRT3","sqrt","F2","G2","fastFloor","grad2","Float64Array","createNoise2D","random","perm","p","Uint8Array","i","tableSize","r","aux","buildPermutationTable","permGrad2x","map","v","permGrad2y","n0","n1","n2","s","j","t","x0","y0","i1","j1","x1","y1","x2","y2","ii","jj","t0","gi0","t1","gi1","t2","gi2","prng_alea","seed","opts","xg","AleaGen","prng","next","double","int32","quick","constructor","Date","n","mash","data","String","length","charCodeAt","h","s0","s1","s2","copy","f","rng","rng2","_seedCallbacks","_onSeed","cb","push","callback","noise","noise2","noiseSeed","rr","e","rr2","rArray","array","randInt","randInt2","gaussian","mean","stdev","u","log","cos","weightedRand","weights","totalWeight","entries","key","cumulative","rnd","isNaN","parseInt","value","withinBounds","constrain","low","high","nAngle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","fill","NaN","sLookup","idx","sin","toDegrees","rad","isRad","runtimeUsesRadians","toDegreesSigned","rotate","cx","cy","coseno","seno","dist","hypot","calcAngle","atan2","intersectLines","s1a","s1b","s2a","s2b","includeSegmentExtension","x3","y3","x4","y4","deltaX1","deltaY1","deltaX2","deltaY2","denominator","ua","ub","isLoaded","isFieldReady","resolution","left_x","top_y","num_columns","num_rows","addField","field","bs","ba","fillField","ar","abs","dif","sr","cr","_t","dir","offset","attractors","Array","from","wx","wy","att","dx","dy","w","freq","amp","_r","Position","m","mx","my","update","plotted","colIdx","rowIdx","reset","isIn","isActive","isInCanvas","skipCheck","list","get","current","wiggle","moveTo","_dir","_length","_step_length","movePos","_moveToDegrees","plotTo","_plot","_scale","_dirPlot","_step","scaleFactor","steps","fieldActive","usePlot","getRowIndex","y_offset","getColIndex","x_offset","col","row","Map","FIELD_ANGLE_MODES","Set","normalizeFieldAngleMode","options","angleMode","has","generateField","entry","normalizeFieldAngles","gen","refreshField","currentField","keys","join","noField","name","funct","set","listFields","fn","_stateStack","clamp","DEGREES","RADIANS","colorContext","currentAngleMode","transformStack","currentTransform","multiplyTransform","left","right","Color","g","hex","rgbToHex","rgbaMatch","exec","alpha","parseFloat","standardize","rgb","hexToRgb","toString","slice","replace","_match","red","green","blue","result","getColorContext","fillStyle","_getRed","_getGreen","_getBlue","mode","getAngleMode","wash","stroke","hatch","mass","pop","saved","brush","popState","translate","theta","cosTheta","sinTheta","scale","initStandaloneRuntime","hooks","render","clear","bindFramebuffer","FRAMEBUFFER","clearColor","COLOR_BUFFER_BIT","DEPTH_BUFFER_BIT","_current","_curvature","_strokeArray","_strokeOrigin","activeTarget","activeDensity","activeWidth","activeHeight","applyLoadedTarget","density","premultipliedAlpha","getTargetContext","createRenderer","createCanvas","logicalWidth","logicalHeight","Number","style","id","parent","querySelector","appendChild","Polygon","pointsArray","useRawVertices","vertices","sides","arr","_intersectionCache","intersect","line","cacheKey","point1","point2","points","start","end","intersection","show","Plot","_type","segments","angles","pres","type","calcIndex","pol","addSegment","_a","_pres","_degrees","reduce","sum","len","endPlot","pressure","_d","curving","index","map0","map1","suma","genPol","_x","_y","_side","step","numSteps","pos","pside","prevIdx","polygon","beginShape","vertex","endShape","circle","radius","arcLength","angleOffset","randomFactor","randomAngle","offsetX","offsetY","arc","startDeg","sweepDeg","segmentCount","segmentSweep","startX","startY","SubPath","isClosed","curvature","vert","_createSpline","close","beginStroke","move","endStroke","spline","_array_points","PI2","pep","tep","pep2","done","p1","p2","p3","d1","d2","a1","a2","curvAdjust","dmax","temp","temp2","point3","point4","intPt","halfDist","asin","origin","strokeRuntime","createTipSurface","loadImageTip","isStrokeCompositeRegistered","createProgram","frag","src","VERTEX_SHADER","FRAGMENT_SHADER","createShader","shaderSource","compileShader","attachShader","linkProgram","rendererRuntime","beginDirectMaskDraw","endDirectMaskDraw","resetDirectShaderTracking","framebufferProjMatrix","vao","buf","program","loadedWidth","loadedHeight","brushMaskTarget","Attr","Frag","_ma","_mb","_mc","_md","_mx","_my","_halfW","_halfH","_density","circleData","INITIAL_CAPACITY","circleCount","bufferCapacity","gpuBufferSize","circleDirtyRect","imgProgram","imgVao","imgCornerBuf","imgInstanceBuf","imgAttr","imgFrag","imgGpuSize","imgData","IMG_INIT_CAP","imgCount","imgCapacity","imgDirtyRect","texCache","QUAD_CORNERS","getProjectionMatrix","beginMaskTarget","endMaskTarget","accumulateDirtyRect","currentRect","diameter","newData","px","py","screenX","screenY","dScreenX","dScreenY","glDrawImages","p5img","targetState","tex","createTexture","bindTexture","TEXTURE_2D","texImage2D","RGBA","UNSIGNED_BYTE","texParameteri","TEXTURE_MIN_FILTER","LINEAR","TEXTURE_MAG_FILTER","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","useProgram","BLEND","blendFunc","ONE_MINUS_DST_ALPHA","ONE","activeTexture","TEXTURE0","uniform1i","u_tex","uniform4f","u_color","uniformMatrix4fv","u_proj","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","drawArraysInstanced","TRIANGLE_STRIP","flush","needsStrokeMask","remove","antialias","depth","stencil","_Renderer","weight","opacity","DEFAULT_CUSTOM_PRESSURE_VARIATION","warp","tilt","BrushState","BrushSetState","add","params","includes","markerTip","vibration","scatter","definition","sharpness","quality","grain","min_max","curve","variation","isArray","rest","range","ns","nm","ne","normalizePressure","tip","deleteTexture","delete","invalidateTexEntry","background","noSmooth","noStroke","T","imageToWhite","tips","tipKey","param","colors","buffers","image","getBrushParams","brushName","scaleBrushes","values","spacing","pick","arguments","strokeWeight","clip","region","noClip","_position","initializeDrawingState","plot","snapshotMatrix","gaussians","angleScale","isPlot","cp","ct","cs","ck","noiseoffset","rendererMask","ensureBrushMaskTarget","nextGl","needsContextRefresh","forEach","getAttribLocation","getUniformLocation","createVertexArray","createBuffer","enableVertexAttribArray","a_position","vertexAttribPointer","FLOAT","a_radius","a_alpha","STATIC_DRAW","a_corner","a_pos","IMG_FLOATS","vertexAttribDivisor","a_size","a_angle","isReady","switchingToBrush","saveState","stepSize","totalSteps","pressureCount","cachedPressure","lineNoiseCount","cachedLineNoise","u_matrix","drawArrays","POINTS","glDraw","restoreState","calculatePressure","lineNoise","sw","iterations","rX","yRandomFactor","sqrtPart","drawSpray","drawMarker","drawImageTip","plotAngle","plotCos","plotSin","perp","along","drawDefault","simPressure","peakPos","halfWidth","pow","gauss","vibrate","rx","ry","size","overscan","maxPressure","scatterReach","tipReach","getImageTipOverscan","extraPadding","halfSize","extraRadius","base","boundsRadius","stampImage","flowLine","_vals","_standard_brushes","obj","prototype","_brush","_weight","loadPixels","average","pixels","updatePixels","filter","k","Promise","all","then","HatchState","HatchSetState","rand","continuous","gradient","hatchStyle","hBrush","noHatch","scanlineHatch","cosA","sinA","cosB","sinB","verts","rotated","Infinity","edges","eLen","Y","sort","scanY","getHatchLines","polygons","segs","poly","getHatchSegments","getActiveHatchConfig","lines","isConnector","prev","createHatch","drawSegment","save","Object","drawFn","withHatchStyle","renderHatchSegments","noMass","jitterPolygon","jitterX","jitterY","projectAnchorToBisector","anchor","nx","ny","getShortArcAngles","toAngleUnit","endDeg","splitSegment","seg","gap","gx","gy","drawMassArcs","pivotBias","bias","bounds","getPolygonBounds","sx","sy","getPivotAnchor","parts","part","center","startAngle","endAngle","drawMassPass","createMass","shape","pols","isPolygon","basePolygon","maxJitter","jitters","getMassPolygons","hatchState","brushState","fieldState","precision","strength","outline","hatchDist","baseAngle","_dist","_angle","_options","FillMaskUploadCanvas","isFillCompositeRegistered","maskWidth","maskHeight","needsFillMaskCanvas","fillMaskFramebuffer","needsFillMaskFramebuffer","imageSmoothingEnabled","_getActiveFramebuffer","uploadRect","uploadWidth","uploadHeight","uploadContext","clearRect","drawImage","colorTexture","texSubImage2D","GROW_CAP","_growInsX","_growInsY","_growMods","_growDirs","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","noFill","_polygon","_gaussians","_fillGaussianPools","_isLeft","FillPoly","isFirst","midP","rayCalc","v1","v2","side","rt","mid","ray","sizeX","sizeY","rc","count","isect","trim","keep","dst","trimStart","trimEnd","edgeStart","edgeEnd","edgeVec","newVertex","insertIdx","splice","ratio","L","indices","sv","sm","sd","crossings","ay","by","flipDirs","grow","tr_v","tr_m","tr_dir","outLen","insertedX","insertedY","newMods","newDirs","bleedDirDeg","gPool","gPoolLen","g2Pool","g2PoolLen","fv","fm","fd","insertedIdx","mod","cv","nv","mi","di","rotDeg","sideX","sideY","dirX","dirY","nextMod","kept","intensity","texture","int","switchingToFill","setTransform","strokeStyle","lineCap","darker","sparse","layer","numLayers","erase","restore","lineWidth","matrix","getTransform","beginPath","first","tx","ty","lineTo","closePath","strokePadding","drawPolygon","numCircles","halfSizeX","halfSizeY","minSize","minSizeFactor","maxSizeFactor","midX","midY","globalCompositeOperation","filterPoints","again","steiner","equals","area","removeNode","earcutLinked","ear","triangles","dim","invSize","pass","z","zOrder","prevZ","nextZ","numMerges","inSize","tail","q","pSize","qSize","sortLinked","indexCurve","stop","isEarHashed","isEar","cureLocalIntersections","splitEarcut","ax","bx","pointInTriangleExceptFirst","minZ","maxZ","intersects","locallyInside","isValidDiagonal","splitPolygon","pointInTriangle","intersectsPolygon","inside","middleInside","q1","q2","o1","sign","o2","o3","o4","onSegment","num","createNode","b2","an","bp","insertNode","last","_opacity","_bleed","fluid","modifiers","_","shift","shifted","pts","point","cross","_center","createFill","FillSetState","washProgram","washVao","washBuffer","washProjection","washGpuBufferSize","WashAttr","WashUniform","noWash","transformVertexToScreen","_renderer","hadDepthTest","isEnabled","DEPTH_TEST","framebuffer","viewport","resetStandaloneShaderTracking","blendEquation","FUNC_ADD","ONE_MINUS_SRC_ALPHA","previousFramebuffer","getParameter","FRAMEBUFFER_BINDING","previousViewport","VIEWPORT","vertSrc","fragSrc","uniformCache","quadVao","loc_source","loc_mask","loc_color","setUniform","location","uniform3f","uniform1f","makeShader","pixelWidth","pixelHeight","createFramebufferTexture","framebufferTexture2D","COLOR_ATTACHMENT0","__brushFramebuffer","deleteFramebuffer","currentFramebuffer","previousProgram","CURRENT_PROGRAM","previousVao","VERTEX_ARRAY_BINDING","TEXTURE1","TRIANGLES","sourceBox","previousReadFramebuffer","READ_FRAMEBUFFER_BINDING","previousDrawFramebuffer","DRAW_FRAMEBUFFER_BINDING","READ_FRAMEBUFFER","DRAW_FRAMEBUFFER","blitFramebuffer","NEAREST","blitDefaultFramebufferSource","cssColor","buildTipSurface","get2DContext","surface","_fillStyle","_strokeStyle","_lineWidth","fillRect","_paint","ellipse","_shapeStarted","getImageData","imageData","putImageData","resolve","reject","NativeImage","globalThis","Image","nativeImg","onload","naturalWidth","naturalHeight","onerror","crossOrigin","ensureWashReady","vertexCount","flat","holeIndices","outerLen","outerNode","signedArea","linkedList","earcut","buildTriangleBuffer","drawWashPolygon","HTMLCanvasElement","isCanvasTarget","isOffscreenCanvasTarget","isSupportedTarget","initStandaloneRendererRuntime","initStandaloneCompositorRuntime","initStandaloneStrokeRuntime"],"mappings":"AAIA,MAAMA,EAAiB,CACrBC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,GAGE,ICEIC,EAAQC,EAAmBC,EAAUC,EDFrCC,EAAc,KAAM,EACpBC,EAAeC,GAAUA,EACzBC,EAAc,KACvB,MAAM,IAAIC,MAAM,yCAEPC,EAAkB,IAAMhB,ECD/BiB,EAAgB,CAClBC,KAAM,KACJ,MAAM,IAAIH,MAAM,0CAElBI,YAAa,IAAMT,EACnBU,cAAe,KACb,MAAM,IAAIL,MAAM,0CAElBM,SAAWC,MAGXC,iBAAmBD,MAGnBE,mBAAoB,OACpBC,qBAAsB,IAAM,KAC5BC,oBAAqB,KAAM,GAQtB,SAASC,EAAeC,GACzB,WAAYA,IAAOrB,EAASqB,EAAMrB,QAClC,YAAaqB,IAAOpB,EAAUoB,EAAMpB,SACpC,aAAcoB,GAAkBA,EAAMC,SACtC,aAAcD,IAAOnB,EAAWmB,EAAMnB,UACtC,YAAamB,IAAOlB,EAAUkB,EAAMlB,QAC1C,CAWO,MAEMU,EAAgB,IAAMH,EAAcG,gBACpCC,EAAYC,GAASL,EAAcI,SAASC,GAG5CG,EAAuB,IAAMR,EAAcQ,uBAC3CC,EAAuBI,GAClCb,EAAcS,oBAAoBI,GCxDvBC,EAAkB,CAACC,EAAMC,EAAU,IAC9CD,EACI,CACEE,KAAMF,EAAKE,KAAOD,EAClBE,KAAMH,EAAKG,KAAOF,EAClBG,KAAMJ,EAAKI,KAAOH,EAClBI,KAAML,EAAKK,KAAOJ,GAEpB,KCIOK,EAAiB,CAACC,EAAOC,EAAQC,GAAqB,KACjE,MAAMC,EACuB,oBAApBC,gBACH,IAA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b,aAAkBa,eAEtB,CAGmC+oC,CAAwB5pC,EAC3D,CA8CO6pC,CAAkB7pC,GACrB,MAAM,IAAIf,MACR,mFAIJka,GAAkBnZ,EAAQA,EAAOS,MAAOT,EAAOU,OAAQ,EACzD,EAoGIrB,YAlDG,WAML,OALAQ,EAAe,CACbpB,OAAQwa,GACRva,QAASwa,GACTta,QAASoa,KAEJA,EACT,EA4CI1Z,cAvCG,WACL,IAAK+P,GACH,MAAM,IAAIpQ,MACR,+EAGN,EAkCIM,SA7BG,WAAqB,EA8BxBE,iBA7BG,WAA6B,EA8BhCC,mBA7BG,WAA+B,EA8BlCC,qBAvBG,WACL,OAAO,IACT,EAsBIC,oBAbG,WACL,OAA4C,IAArCgrB,UAAU,IAAIub,kBACvB,GX5HEhnC,EAAgB,IAAKA,KAAkBgZ,I+BvCzCD,KHmBO,WVPA,IAA4BC,IUQd,CACjBkJ,uBACAC,qBACAC,0BAA2BkjB,IVV7BrjB,GAAkB,IAAKA,MAAoBjJ,EUY7C,CGxBA2xB,GF4MO,W3BhHA,IAA8B3xB,I2BiHd,CACnB9W,eACAC,4BACAC,gCACAC,qBACAC,sBACAC,4B3BtHFN,EAAoB,IAAKA,KAAsB+W,E2BwHjD,CEpNA4xB,GDqKO,WfrKA,IAA0B5xB,IesKd,CACfoI,oBACAC,iBfvKFF,GAAgB,IAAKA,MAAkBnI,EeyKzC,CCzKA6xB","x_google_ignoreList":[5,6,27]}
\ No newline at end of file
+{"version":3,"file":"brush.esm.js","sources":["../src/core/runtime.js","../src/core/target.js","../src/core/dirty_rect.js","../src/core/compositor_runtime.js","../src/core/color.js","../node_modules/simplex-noise/dist/esm/simplex-noise.js","../node_modules/esm-seedrandom/esm/index.mjs","../src/core/utils.js","../src/core/flowfield.js","../src/core/save.js","../src/adapters/standalone/runtime.js","../src/adapters/standalone/frame.js","../src/adapters/standalone/target.js","../src/core/primitives.js","../src/core/polygon.js","../src/core/plot.js","../src/stroke/runtime.js","../src/stroke/composite.js","../src/core/gl/utils.js","../src/core/renderer_runtime.js","../src/stroke/gl_draw.js","../src/stroke/stroke.js","../src/hatch/hatch.js","../src/hatch/mass.js","../src/fill/mask.js","../src/fill/composite.js","../src/fill/fill.js","../node_modules/earcut/src/earcut.js","../src/fill/wash.js","../src/adapters/standalone/renderer.js","../src/adapters/standalone/compositor.js","../src/adapters/standalone/stroke.js","../src/index.standalone.js"],"sourcesContent":["// =============================================================================\n// Runtime Hooks\n// =============================================================================\n\nconst identityMatrix = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\n\nexport let usesRadians = () => false;\nexport let fromDegrees = (angle) => angle;\nexport let createColor = () => {\n throw new Error(\"No runtime color adapter registered.\");\n};\nexport let getAffineMatrix = () => identityMatrix;\n\n/**\n * Registers or updates host-runtime hooks used by core modules.\n *\n * @param {object} hooks\n */\nexport function setRuntime(hooks) {\n if (hooks.usesRadians) usesRadians = hooks.usesRadians;\n if (hooks.fromDegrees) fromDegrees = hooks.fromDegrees;\n if (hooks.createColor) createColor = hooks.createColor;\n if (hooks.getAffineMatrix) getAffineMatrix = hooks.getAffineMatrix;\n}\n","// =============================================================================\n// Target Runtime Hooks\n// =============================================================================\n\n/**\n * Shared target state exposed to core modules.\n *\n * Host adapters are expected to keep these bindings updated with the currently\n * active drawing target. The exact object type is adapter-defined, but core code\n * assumes the active renderer exposes:\n * - `drawingContext`: the active WebGL context\n * - target dimensions through `Cwidth` / `Cheight`\n * - pixel density through `Density`\n */\n\nexport let Cwidth, Cheight, Instance, Renderer, Density;\n\nlet targetRuntime = {\n load: () => {\n throw new Error(\"No target runtime adapter registered.\");\n },\n syncDensity: () => Density,\n isCanvasReady: () => {\n throw new Error(\"No target runtime adapter registered.\");\n },\n instance: (inst) => {\n Instance = inst;\n },\n activateInstance: (inst) => {\n Instance = inst;\n },\n deactivateInstance: () => {},\n getActiveFramebuffer: () => null,\n isFramebufferTarget: () => false,\n};\n\n/**\n * Updates the shared target state consumed by core modules.\n *\n * @param {object} state\n */\nexport function setTargetState(state) {\n if (\"Cwidth\" in state) Cwidth = state.Cwidth;\n if (\"Cheight\" in state) Cheight = state.Cheight;\n if (\"Instance\" in state) Instance = state.Instance;\n if (\"Renderer\" in state) Renderer = state.Renderer;\n if (\"Density\" in state) Density = state.Density;\n}\n\n/**\n * Registers or updates host target hooks used by core modules.\n *\n * @param {object} hooks\n */\nexport function setTargetRuntime(hooks) {\n targetRuntime = { ...targetRuntime, ...hooks };\n}\n\nexport const load = (buffer = false) => targetRuntime.load(buffer);\nexport const syncDensity = () => targetRuntime.syncDensity();\nexport const isCanvasReady = () => targetRuntime.isCanvasReady();\nexport const instance = (inst) => targetRuntime.instance(inst);\nexport const activateInstance = (inst) => targetRuntime.activateInstance(inst);\nexport const deactivateInstance = () => targetRuntime.deactivateInstance();\nexport const getActiveFramebuffer = () => targetRuntime.getActiveFramebuffer();\nexport const isFramebufferTarget = (target) =>\n targetRuntime.isFramebufferTarget(target);\n","// =============================================================================\n// Module: Dirty Rect Utilities\n// =============================================================================\n/**\n * Expands a dirty rectangle outward by a constant padding value.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Rect to expand.\n * @param {number} [padding=0] - Padding in pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Expanded rect.\n */\nexport const expandDirtyRect = (rect, padding = 0) =>\n rect\n ? {\n minX: rect.minX - padding,\n minY: rect.minY - padding,\n maxX: rect.maxX + padding,\n maxY: rect.maxY + padding,\n }\n : null;\n\n/**\n * Clamps a dirty rectangle to explicit target bounds.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Candidate rect.\n * @param {number} width - Target width in physical pixels.\n * @param {number} height - Target height in physical pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Clamped rect.\n */\nexport const normalizeDirtyRect = (rect, width, height) => {\n if (!rect) return null;\n\n const minX = Math.max(0, Math.floor(Math.min(rect.minX, rect.maxX)));\n const minY = Math.max(0, Math.floor(Math.min(rect.minY, rect.maxY)));\n const maxX = Math.min(width, Math.ceil(Math.max(rect.minX, rect.maxX)));\n const maxY = Math.min(height, Math.ceil(Math.max(rect.minY, rect.maxY)));\n\n if (maxX <= minX || maxY <= minY) return null;\n\n return { minX, minY, maxX, maxY };\n};\n\n/**\n * Returns the union of two dirty rectangles.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} a - First rect.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} b - Second rect.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Union rect.\n */\nexport const unionDirtyRect = (a, b) => {\n if (!a) return b;\n if (!b) return a;\n\n return {\n minX: Math.min(a.minX, b.minX),\n minY: Math.min(a.minY, b.minY),\n maxX: Math.max(a.maxX, b.maxX),\n maxY: Math.max(a.maxY, b.maxY),\n };\n};\n\n/**\n * Returns a dirty rectangle covering the full target bounds.\n *\n * @param {number} width - Target width in physical pixels.\n * @param {number} height - Target height in physical pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}} Full-target rect.\n */\nexport const getFullDirtyRect = (width, height) => ({\n minX: 0,\n minY: 0,\n maxX: width,\n maxY: height,\n});\n","// =============================================================================\n// Compositor Runtime Hooks\n// =============================================================================\n\n/**\n * Shared compositor helpers and host hooks.\n *\n * The shared code in this module assumes framebuffer-like targets expose:\n * - `framebuffer`: native WebGL framebuffer handle\n * - optional lifecycle methods supplied by the host adapter\n *\n * Higher-level core modules also attach their own bookkeeping fields onto the\n * active renderer and mask targets, such as:\n * - `shaderProgram`\n * - `blendSourceFramebuffer`\n * - `glMask`\n * - `fillMaskFramebuffer`\n * - `mask`\n *\n * These are library-level contract fields, not host-specific internals.\n */\n\nexport const create2DCanvas = (width, height, willReadFrequently = false) => {\n const canvas =\n typeof OffscreenCanvas !== \"undefined\"\n ? new OffscreenCanvas(width, height)\n : (() => {\n const element = document.createElement(\"canvas\");\n element.width = width;\n element.height = height;\n return element;\n })();\n canvas.drawingContext = canvas.getContext(\n \"2d\",\n willReadFrequently ? { willReadFrequently: true } : undefined,\n );\n return canvas;\n};\n\nexport const get2DContext = (canvas, willReadFrequently = false) => {\n canvas.drawingContext ??= canvas.getContext(\n \"2d\",\n willReadFrequently ? { willReadFrequently: true } : undefined,\n );\n return canvas.drawingContext;\n};\n\nexport function blitDefaultFramebufferSource({\n renderer,\n sourceFramebuffer,\n dirtyRect,\n getTargetPixelSize,\n toScissorBox,\n}) {\n const gl = renderer.drawingContext;\n const { width, height } = getTargetPixelSize();\n const sourceBox = dirtyRect ? toScissorBox(dirtyRect) : null;\n const previousReadFramebuffer = gl.getParameter(gl.READ_FRAMEBUFFER_BINDING);\n const previousDrawFramebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING);\n\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, sourceFramebuffer.framebuffer);\n gl.blitFramebuffer(\n sourceBox?.x ?? 0,\n sourceBox?.y ?? 0,\n sourceBox ? sourceBox.x + sourceBox.width : width,\n sourceBox ? sourceBox.y + sourceBox.height : height,\n sourceBox?.x ?? 0,\n sourceBox?.y ?? 0,\n sourceBox ? sourceBox.x + sourceBox.width : width,\n sourceBox ? sourceBox.y + sourceBox.height : height,\n gl.COLOR_BUFFER_BIT,\n gl.NEAREST,\n );\n\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, previousReadFramebuffer);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, previousDrawFramebuffer);\n\n return sourceFramebuffer;\n}\n\nlet compositorRuntime = {\n clearTarget: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n ensureBlendShaderProgram: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n ensureBlendSourceFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n createFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n runBlendShaderPass: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n blitSourceToFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n};\n\n/**\n * Registers or updates host compositor hooks used by core compositing code.\n *\n * @param {object} hooks\n */\nexport function setCompositorRuntime(hooks) {\n compositorRuntime = { ...compositorRuntime, ...hooks };\n}\n\nexport const clearTarget = (...args) => compositorRuntime.clearTarget(...args);\nexport const ensureBlendShaderProgram = (...args) =>\n compositorRuntime.ensureBlendShaderProgram(...args);\nexport const ensureBlendSourceFramebuffer = (...args) =>\n compositorRuntime.ensureBlendSourceFramebuffer(...args);\nexport const createFramebuffer = (...args) =>\n compositorRuntime.createFramebuffer(...args);\nexport const runBlendShaderPass = (...args) =>\n compositorRuntime.runBlendShaderPass(...args);\nexport const blitSourceToFramebuffer = (...args) =>\n compositorRuntime.blitSourceToFramebuffer(...args);\n","import {\n Cwidth,\n Cheight,\n Renderer,\n Density,\n load as loadTarget,\n isCanvasReady,\n syncDensity,\n getActiveFramebuffer,\n isFramebufferTarget,\n} from \"./target.js\";\nimport {\n expandDirtyRect,\n normalizeDirtyRect as clampDirtyRect,\n unionDirtyRect,\n getFullDirtyRect as getFullRect,\n} from \"./dirty_rect.js\";\nimport {\n clearTarget as clearRenderTarget,\n ensureBlendShaderProgram,\n ensureBlendSourceFramebuffer,\n runBlendShaderPass,\n blitSourceToFramebuffer,\n} from \"./compositor_runtime.js\";\n\nimport vertSrc from \"./gl/shader.vert\";\nimport fragSrc from \"./gl/shader.frag\";\n\n// =============================================================================\n// Module: Configure and Initiate\n// =============================================================================\n/**\n * This module handles the configuration and initialization of the drawing system.\n * It manages canvas properties, ensures the system is ready for rendering, and\n * provides utilities for saving and restoring states.\n */\n\nlet strokeComposite = null;\nlet fillComposite = null;\n\nexport const registerStrokeComposite = (composite) => {\n strokeComposite = composite;\n};\n\nexport const registerFillComposite = (composite) => {\n fillComposite = composite;\n};\n\nconst clearTarget = (target) => {\n clearRenderTarget(Renderer, target, isFramebufferTarget);\n};\n\n// =============================================================================\n// Section: Dirty Rect Utilities\n// =============================================================================\n/**\n * Returns the current render target size in physical pixels.\n * @returns {{width: number, height: number}} Pixel size of the active target.\n */\nconst getTargetPixelSize = () => ({\n width: Math.max(1, Math.round(Cwidth * Density)),\n height: Math.max(1, Math.round(Cheight * Density)),\n});\n\nconst normalizeDirtyRect = (rect) => {\n if (!rect) return null;\n const { width, height } = getTargetPixelSize();\n return clampDirtyRect(rect, width, height);\n};\n\n/**\n * Returns a dirty rectangle covering the full active target.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}} Full-target rect.\n */\nconst getFullDirtyRect = () => {\n const { width, height } = getTargetPixelSize();\n return getFullRect(width, height);\n};\n\n// =============================================================================\n// Section: Scissor Helpers\n// =============================================================================\n/**\n * Converts a top-left-based dirty rectangle into a WebGL scissor box.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Dirty rect.\n * @returns {{x:number,y:number,width:number,height:number}|null} Scissor box or null.\n */\nconst toScissorBox = (rect, flipY = true) => {\n const normalized = normalizeDirtyRect(rect);\n if (!normalized) return null;\n\n const { height } = getTargetPixelSize();\n return {\n x: normalized.minX,\n y: flipY ? height - normalized.maxY : normalized.minY,\n width: normalized.maxX - normalized.minX,\n height: normalized.maxY - normalized.minY,\n };\n};\n\n/**\n * Runs a draw callback with a temporary scissor region.\n * @param {WebGL2RenderingContext} gl - Active WebGL context.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Dirty rect.\n * @param {Function} draw - Draw callback executed under the scissor box.\n */\nconst withScissor = (gl, rect, draw, flipY = true) => {\n const box = toScissorBox(rect, flipY);\n if (!box) {\n draw();\n return;\n }\n\n // Scissor is never nested in this module, so we can set/clear it directly\n // without saving previous GL state.\n gl.enable(gl.SCISSOR_TEST);\n gl.scissor(box.x, box.y, box.width, box.height);\n\n try {\n draw();\n } finally {\n gl.disable(gl.SCISSOR_TEST);\n }\n};\n\n/**\n * Stores the current state of the drawing system.\n * Can be used to save and restore configurations or canvas states.\n */\nexport const State = {};\n/**\n * Handles color blending using WebGL shaders. Implements advanced blending\n * effects based on Kubelka-Munk theory. Relies on spectral.js for blending logic.\n */\n\n// =============================================================================\n// Section: Color Blending / Rendering\n// =============================================================================\n/**\n * Ensures the Mix object is initialized and ready for blending.\n */\nexport const isMixReady = () => {\n if (!Renderer?.loaded) {\n isCanvasReady();\n Mix.load();\n }\n};\n\n/**\n * Manages blending operations with WebGL shaders.\n * @property {boolean} loaded - Indicates if shaders are loaded.\n * @property {boolean} isBlending - Indicates if blending is active.\n * @property {object} currentColor - Current color in WebGL format.\n * @property {function} load - Initializes blending resources.\n * @property {function} blend - Applies blending effects.\n */\nexport const Mix = {\n isBlending: false,\n cachedColor: null,\n\n /**\n * Merges a new dirty rectangle into the target's accumulated draw bounds.\n * @param {object} target - Mask buffer receiving draw output.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Rect to merge.\n */\n markDirtyRect(target, rect) {\n const normalized = normalizeDirtyRect(rect);\n if (!target || !normalized) return;\n target.dirtyRect = unionDirtyRect(target.dirtyRect, normalized);\n target.isDrawn = true;\n },\n\n /**\n * Clears a mask buffer and resets its dirty-rect tracking.\n * @param {object} target - Mask buffer to reset.\n */\n clearMask(target) {\n if (!target) return;\n const composite = target === this.glMask ? strokeComposite : fillComposite;\n composite?.clearMask?.(target, clearTarget);\n },\n\n /**\n * Resolves the region that should be composited back into the destination.\n * @param {object} target - Mask buffer being sampled.\n * @param {boolean} isBrushMask - True when compositing the GL brush mask.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\n getCompositeRect(target, isBrushMask) {\n const composite = isBrushMask ? strokeComposite : fillComposite;\n return composite?.getCompositeRect?.(\n target,\n getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n );\n },\n\n // =============================================================================\n // Section: Setup and load shaders\n // =============================================================================\n /**\n * Ensures the mask buffers and blend shader exist for the current renderer.\n */\n load() {\n syncDensity();\n const needsBlendSourceFramebuffer =\n !Renderer.blendSourceFramebuffer ||\n Renderer.blendSourceFramebuffer.width !== Cwidth ||\n Renderer.blendSourceFramebuffer.height !== Cheight ||\n (typeof Renderer.blendSourceFramebuffer.pixelDensity === \"function\" &&\n Renderer.blendSourceFramebuffer.pixelDensity() !== Density);\n ensureBlendShaderProgram(Renderer, vertSrc, fragSrc);\n\n this.glMask = strokeComposite?.ensureResources?.(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n );\n const fillResources = fillComposite?.ensureResources?.(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n clearTarget,\n ) ?? {\n mask: null,\n ctx: null,\n };\n\n if (needsBlendSourceFramebuffer) {\n Renderer.blendSourceFramebuffer = ensureBlendSourceFramebuffer(\n Renderer,\n Renderer.blendSourceFramebuffer,\n Cwidth,\n Cheight,\n Density,\n );\n }\n\n this.mask = fillResources.mask;\n this.ctx = fillResources.ctx;\n },\n\n // =============================================================================\n // Section: Compositing\n // =============================================================================\n /**\n * Flushes pending mask work when the blend color changes or a frame ends.\n * @param {Color|false} [_color=false] - New blend color.\n * @param {boolean} [_isLast=false] - True when this is the final blend flush.\n */\n blend(_color = false, _isLast = false) {\n isMixReady();\n // Only one mask is \"active\" for the current drawing mode; the other one\n // may still need flushing if the mode just changed mid-frame.\n const isBrushMask = this.isBrush === true;\n const mask = isBrushMask ? this.glMask : this.mask;\n const otherMask = isBrushMask ? this.mask : this.glMask;\n const nextColor = _color?._array;\n const colorChanged =\n !!nextColor &&\n (this.cachedColor?.[0] !== nextColor[0] ||\n this.cachedColor?.[1] !== nextColor[1] ||\n this.cachedColor?.[2] !== nextColor[2] ||\n this.cachedColor?.[3] !== nextColor[3]);\n if (!this.isBlending && nextColor) {\n this.isBlending = true;\n this.cachedColor = nextColor;\n // Reset the brush mask fully at the start of each blend cycle so stale\n // dirty-rect bookkeeping cannot leak an old stroke into the next color.\n this.clearMask(this.glMask);\n }\n\n if (_isLast || colorChanged) {\n if (this.justChanged) {\n this.applyShader(otherMask, !isBrushMask);\n this.justChanged = false;\n }\n if (this.isBlending) {\n this.applyShader(mask, isBrushMask);\n }\n if (nextColor) this.cachedColor = nextColor;\n if (_isLast) {\n this.isBlending = false;\n this.cachedColor = null;\n \n }\n }\n },\n\n /**\n * Runs the blend shader over a mask and composites the result into the active renderer.\n * @param {object} mask - Mask buffer to composite.\n * @param {boolean} isBrushMask - True when compositing the GL brush mask.\n */\n applyShader(mask, isBrushMask) {\n if (!mask?.isDrawn) return;\n\n const dirtyRect = this.getCompositeRect(mask, isBrushMask);\n if (!dirtyRect) {\n this.clearMask(mask);\n return;\n }\n\n const gl = Renderer.drawingContext;\n const shader = Renderer.shaderProgram;\n const activeFramebuffer = getActiveFramebuffer();\n const source = blitSourceToFramebuffer({\n renderer: Renderer,\n sourceTarget: activeFramebuffer ?? Renderer,\n sourceFramebuffer: Renderer.blendSourceFramebuffer,\n dirtyRect,\n isFramebufferTarget,\n Cwidth,\n Cheight,\n getTargetPixelSize,\n toScissorBox,\n withScissor,\n });\n const targetIsFramebuffer = !!activeFramebuffer;\n const composite = isBrushMask ? strokeComposite : fillComposite;\n const shaderMask = composite.getShaderMask(\n Renderer,\n mask,\n dirtyRect,\n getFullDirtyRect,\n clearTarget,\n );\n\n runBlendShaderPass({\n renderer: Renderer,\n shader,\n source,\n mask: shaderMask,\n color: this.cachedColor,\n isBrushMask,\n Cwidth,\n Cheight,\n dirtyRect,\n targetIsFramebuffer,\n withScissor,\n });\n this.clearMask(mask);\n },\n};\n\n/**\n * Flushes any pending stroke/fill mask work into the current target and resets\n * the shared compositor back to its initial idle state.\n */\nexport const flushActiveComposite = () => {\n isMixReady();\n Mix.blend(false, true);\n Mix.clearMask(Mix.glMask);\n Mix.clearMask(Mix.mask);\n Mix.justChanged = false;\n Mix.isBlending = false;\n Mix.isBrush = null;\n Mix.cachedColor = null;\n};\n\n/**\n * Loads and initializes the drawing target, then refreshes compositing\n * resources if the renderer was already active.\n *\n * @param {object|false} [buffer=false] - Optional offscreen target.\n */\nexport const load = (buffer = false) => {\n loadTarget(buffer);\n if (Renderer.loaded) Mix.load();\n};\n","/*\n * A fast javascript implementation of simplex noise by Jonas Wagner\n\nBased on a speed-improved simplex noise algorithm for 2D, 3D and 4D in Java.\nWhich is based on example code by Stefan Gustavson ([email protected]).\nWith Optimisations by Peter Eastman ([email protected]).\nBetter rank ordering method by Stefan Gustavson in 2012.\n\n Copyright (c) 2024 Jonas Wagner\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n */\n// these __PURE__ comments help uglifyjs with dead code removal\n//\nconst SQRT3 = /*#__PURE__*/ Math.sqrt(3.0);\nconst SQRT5 = /*#__PURE__*/ Math.sqrt(5.0);\nconst F2 = 0.5 * (SQRT3 - 1.0);\nconst G2 = (3.0 - SQRT3) / 6.0;\nconst F3 = 1.0 / 3.0;\nconst G3 = 1.0 / 6.0;\nconst F4 = (SQRT5 - 1.0) / 4.0;\nconst G4 = (5.0 - SQRT5) / 20.0;\n// I'm really not sure why this | 0 (basically a coercion to int)\n// is making this faster but I get ~5 million ops/sec more on the\n// benchmarks across the board or a ~10% speedup.\nconst fastFloor = (x) => Math.floor(x) | 0;\nconst grad2 = /*#__PURE__*/ new Float64Array([1, 1,\n -1, 1,\n 1, -1,\n -1, -1,\n 1, 0,\n -1, 0,\n 1, 0,\n -1, 0,\n 0, 1,\n 0, -1,\n 0, 1,\n 0, -1]);\n// double seems to be faster than single or int's\n// probably because most operations are in double precision\nconst grad3 = /*#__PURE__*/ new Float64Array([1, 1, 0,\n -1, 1, 0,\n 1, -1, 0,\n -1, -1, 0,\n 1, 0, 1,\n -1, 0, 1,\n 1, 0, -1,\n -1, 0, -1,\n 0, 1, 1,\n 0, -1, 1,\n 0, 1, -1,\n 0, -1, -1]);\n// double is a bit quicker here as well\nconst grad4 = /*#__PURE__*/ new Float64Array([0, 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1,\n 0, -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1,\n 1, 0, 1, 1, 1, 0, 1, -1, 1, 0, -1, 1, 1, 0, -1, -1,\n -1, 0, 1, 1, -1, 0, 1, -1, -1, 0, -1, 1, -1, 0, -1, -1,\n 1, 1, 0, 1, 1, 1, 0, -1, 1, -1, 0, 1, 1, -1, 0, -1,\n -1, 1, 0, 1, -1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, -1,\n 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1, 0,\n -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1, 0]);\n/**\n * Creates a 2D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction2D}\n */\nexport function createNoise2D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating this yields a little ~3% performance improvement.\n const permGrad2x = new Float64Array(perm).map(v => grad2[(v % 12) * 2]);\n const permGrad2y = new Float64Array(perm).map(v => grad2[(v % 12) * 2 + 1]);\n return function noise2D(x, y) {\n // if(!isFinite(x) || !isFinite(y)) return 0;\n let n0 = 0; // Noise contributions from the three corners\n let n1 = 0;\n let n2 = 0;\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y) * F2; // Hairy factor for 2D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const t = (i + j) * G2;\n const X0 = i - t; // Unskew the cell origin back to (x,y) space\n const Y0 = j - t;\n const x0 = x - X0; // The x,y distances from the cell origin\n const y0 = y - Y0;\n // For the 2D case, the simplex shape is an equilateral triangle.\n // Determine which simplex we are in.\n let i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords\n if (x0 > y0) {\n i1 = 1;\n j1 = 0;\n } // lower triangle, XY order: (0,0)->(1,0)->(1,1)\n else {\n i1 = 0;\n j1 = 1;\n } // upper triangle, YX order: (0,0)->(0,1)->(1,1)\n // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and\n // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where\n // c = (3-sqrt(3))/6\n const x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords\n const y1 = y0 - j1 + G2;\n const x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords\n const y2 = y0 - 1.0 + 2.0 * G2;\n // Work out the hashed gradient indices of the three simplex corners\n const ii = i & 255;\n const jj = j & 255;\n // Calculate the contribution from the three corners\n let t0 = 0.5 - x0 * x0 - y0 * y0;\n if (t0 >= 0) {\n const gi0 = ii + perm[jj];\n const g0x = permGrad2x[gi0];\n const g0y = permGrad2y[gi0];\n t0 *= t0;\n // n0 = t0 * t0 * (grad2[gi0] * x0 + grad2[gi0 + 1] * y0); // (x,y) of grad3 used for 2D gradient\n n0 = t0 * t0 * (g0x * x0 + g0y * y0);\n }\n let t1 = 0.5 - x1 * x1 - y1 * y1;\n if (t1 >= 0) {\n const gi1 = ii + i1 + perm[jj + j1];\n const g1x = permGrad2x[gi1];\n const g1y = permGrad2y[gi1];\n t1 *= t1;\n // n1 = t1 * t1 * (grad2[gi1] * x1 + grad2[gi1 + 1] * y1);\n n1 = t1 * t1 * (g1x * x1 + g1y * y1);\n }\n let t2 = 0.5 - x2 * x2 - y2 * y2;\n if (t2 >= 0) {\n const gi2 = ii + 1 + perm[jj + 1];\n const g2x = permGrad2x[gi2];\n const g2y = permGrad2y[gi2];\n t2 *= t2;\n // n2 = t2 * t2 * (grad2[gi2] * x2 + grad2[gi2 + 1] * y2);\n n2 = t2 * t2 * (g2x * x2 + g2y * y2);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to return values in the interval [-1,1].\n return 70.0 * (n0 + n1 + n2);\n };\n}\n/**\n * Creates a 3D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction3D}\n */\nexport function createNoise3D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these seems to yield a speedup of over 15%\n const permGrad3x = new Float64Array(perm).map(v => grad3[(v % 12) * 3]);\n const permGrad3y = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 1]);\n const permGrad3z = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 2]);\n return function noise3D(x, y, z) {\n let n0, n1, n2, n3; // Noise contributions from the four corners\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y + z) * F3; // Very nice and simple skew factor for 3D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const t = (i + j + k) * G3;\n const X0 = i - t; // Unskew the cell origin back to (x,y,z) space\n const Y0 = j - t;\n const Z0 = k - t;\n const x0 = x - X0; // The x,y,z distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n // For the 3D case, the simplex shape is a slightly irregular tetrahedron.\n // Determine which simplex we are in.\n let i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords\n let i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords\n if (x0 >= y0) {\n if (y0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // X Y Z order\n else if (x0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // X Z Y order\n else {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // Z X Y order\n }\n else { // x0<y0\n if (y0 < z0) {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Z Y X order\n else if (x0 < z0) {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Y Z X order\n else {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // Y X Z order\n }\n // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),\n // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and\n // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where\n // c = 1/6.\n const x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords\n const y1 = y0 - j1 + G3;\n const z1 = z0 - k1 + G3;\n const x2 = x0 - i2 + 2.0 * G3; // Offsets for third corner in (x,y,z) coords\n const y2 = y0 - j2 + 2.0 * G3;\n const z2 = z0 - k2 + 2.0 * G3;\n const x3 = x0 - 1.0 + 3.0 * G3; // Offsets for last corner in (x,y,z) coords\n const y3 = y0 - 1.0 + 3.0 * G3;\n const z3 = z0 - 1.0 + 3.0 * G3;\n // Work out the hashed gradient indices of the four simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n // Calculate the contribution from the four corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad3x[gi0] * x0 + permGrad3y[gi0] * y0 + permGrad3z[gi0] * z0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad3x[gi1] * x1 + permGrad3y[gi1] * y1 + permGrad3z[gi1] * z1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad3x[gi2] * x2 + permGrad3y[gi2] * y2 + permGrad3z[gi2] * z2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + 1 + perm[jj + 1 + perm[kk + 1]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad3x[gi3] * x3 + permGrad3y[gi3] * y3 + permGrad3z[gi3] * z3);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to stay just inside [-1,1]\n return 32.0 * (n0 + n1 + n2 + n3);\n };\n}\n/**\n * Creates a 4D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction4D}\n */\nexport function createNoise4D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these leads to a ~10% speedup\n const permGrad4x = new Float64Array(perm).map(v => grad4[(v % 32) * 4]);\n const permGrad4y = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 1]);\n const permGrad4z = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 2]);\n const permGrad4w = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 3]);\n return function noise4D(x, y, z, w) {\n let n0, n1, n2, n3, n4; // Noise contributions from the five corners\n // Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in\n const s = (x + y + z + w) * F4; // Factor for 4D skewing\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const l = fastFloor(w + s);\n const t = (i + j + k + l) * G4; // Factor for 4D unskewing\n const X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space\n const Y0 = j - t;\n const Z0 = k - t;\n const W0 = l - t;\n const x0 = x - X0; // The x,y,z,w distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n const w0 = w - W0;\n // For the 4D case, the simplex is a 4D shape I won't even try to describe.\n // To find out which of the 24 possible simplices we're in, we need to\n // determine the magnitude ordering of x0, y0, z0 and w0.\n // Six pair-wise comparisons are performed between each possible pair\n // of the four coordinates, and the results are used to rank the numbers.\n let rankx = 0;\n let ranky = 0;\n let rankz = 0;\n let rankw = 0;\n if (x0 > y0)\n rankx++;\n else\n ranky++;\n if (x0 > z0)\n rankx++;\n else\n rankz++;\n if (x0 > w0)\n rankx++;\n else\n rankw++;\n if (y0 > z0)\n ranky++;\n else\n rankz++;\n if (y0 > w0)\n ranky++;\n else\n rankw++;\n if (z0 > w0)\n rankz++;\n else\n rankw++;\n // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order.\n // Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w and x<w\n // impossible. Only the 24 indices which have non-zero entries make any sense.\n // We use a thresholding to set the coordinates in turn from the largest magnitude.\n // Rank 3 denotes the largest coordinate.\n // Rank 2 denotes the second largest coordinate.\n // Rank 1 denotes the second smallest coordinate.\n // The integer offsets for the second simplex corner\n const i1 = rankx >= 3 ? 1 : 0;\n const j1 = ranky >= 3 ? 1 : 0;\n const k1 = rankz >= 3 ? 1 : 0;\n const l1 = rankw >= 3 ? 1 : 0;\n // The integer offsets for the third simplex corner\n const i2 = rankx >= 2 ? 1 : 0;\n const j2 = ranky >= 2 ? 1 : 0;\n const k2 = rankz >= 2 ? 1 : 0;\n const l2 = rankw >= 2 ? 1 : 0;\n // The integer offsets for the fourth simplex corner\n const i3 = rankx >= 1 ? 1 : 0;\n const j3 = ranky >= 1 ? 1 : 0;\n const k3 = rankz >= 1 ? 1 : 0;\n const l3 = rankw >= 1 ? 1 : 0;\n // The fifth corner has all coordinate offsets = 1, so no need to compute that.\n const x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords\n const y1 = y0 - j1 + G4;\n const z1 = z0 - k1 + G4;\n const w1 = w0 - l1 + G4;\n const x2 = x0 - i2 + 2.0 * G4; // Offsets for third corner in (x,y,z,w) coords\n const y2 = y0 - j2 + 2.0 * G4;\n const z2 = z0 - k2 + 2.0 * G4;\n const w2 = w0 - l2 + 2.0 * G4;\n const x3 = x0 - i3 + 3.0 * G4; // Offsets for fourth corner in (x,y,z,w) coords\n const y3 = y0 - j3 + 3.0 * G4;\n const z3 = z0 - k3 + 3.0 * G4;\n const w3 = w0 - l3 + 3.0 * G4;\n const x4 = x0 - 1.0 + 4.0 * G4; // Offsets for last corner in (x,y,z,w) coords\n const y4 = y0 - 1.0 + 4.0 * G4;\n const z4 = z0 - 1.0 + 4.0 * G4;\n const w4 = w0 - 1.0 + 4.0 * G4;\n // Work out the hashed gradient indices of the five simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n const ll = l & 255;\n // Calculate the contribution from the five corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk + perm[ll]]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad4x[gi0] * x0 + permGrad4y[gi0] * y0 + permGrad4z[gi0] * z0 + permGrad4w[gi0] * w0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad4x[gi1] * x1 + permGrad4y[gi1] * y1 + permGrad4z[gi1] * z1 + permGrad4w[gi1] * w1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad4x[gi2] * x2 + permGrad4y[gi2] * y2 + permGrad4z[gi2] * z2 + permGrad4w[gi2] * w2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad4x[gi3] * x3 + permGrad4y[gi3] * y3 + permGrad4z[gi3] * z3 + permGrad4w[gi3] * w3);\n }\n let t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4;\n if (t4 < 0)\n n4 = 0.0;\n else {\n const gi4 = ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]];\n t4 *= t4;\n n4 = t4 * t4 * (permGrad4x[gi4] * x4 + permGrad4y[gi4] * y4 + permGrad4z[gi4] * z4 + permGrad4w[gi4] * w4);\n }\n // Sum up and scale the result to cover the range [-1,1]\n return 27.0 * (n0 + n1 + n2 + n3 + n4);\n };\n}\n/**\n * Builds a random permutation table.\n * This is exported only for (internal) testing purposes.\n * Do not rely on this export.\n * @private\n */\nexport function buildPermutationTable(random) {\n const tableSize = 512;\n const p = new Uint8Array(tableSize);\n for (let i = 0; i < tableSize / 2; i++) {\n p[i] = i;\n }\n for (let i = 0; i < tableSize / 2 - 1; i++) {\n const r = i + ~~(random() * (256 - i));\n const aux = p[i];\n p[i] = p[r];\n p[r] = aux;\n }\n for (let i = 256; i < tableSize; i++) {\n p[i] = p[i - 256];\n }\n return p;\n}\n//# sourceMappingURL=simplex-noise.js.map","function _prng_restore(prng, xg, opts) {\n let state = opts && opts.state;\n if (state) {\n if (typeof(state) == 'object') xg.copy(state, xg);\n prng.state = () => xg.copy(xg, {});\n }\n}\n\nfunction _prng_xor_core(xg, opts) {\n let prng = () => (xg.next() >>> 0) / 0x100000000;\n\n prng.double = () => {\n let top, bot, result;\n do {\n top = xg.next() >>> 11;\n bot = (xg.next() >>> 0) / 0x100000000;\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n\n prng.int32 = () => xg.next() | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng;\n}\n\n// A port of an algorithm by Johannes Baagøe <[email protected]>, 2010\nfunction prng_alea(seed, opts) {\n let xg = new AleaGen(seed);\n\n let prng = () => xg.next();\n\n prng.double = () =>\n prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53\n\n prng.int32 = () => (xg.next() * 0x100000000) | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\nclass AleaGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let n = 0xefc8249d;\n\n // Apply the seeding algorithm from Baagoe.\n this.c = 1;\n this.s0 = mash(' ');\n this.s1 = mash(' ');\n this.s2 = mash(' ');\n this.s0 -= mash(seed);\n if (this.s0 < 0) { this.s0 += 1; }\n this.s1 -= mash(seed);\n if (this.s1 < 0) { this.s1 += 1; }\n this.s2 -= mash(seed);\n if (this.s2 < 0) { this.s2 += 1; }\n\n function mash(data) {\n data = String(data);\n for (let i = 0; i < data.length; i++) {\n n += data.charCodeAt(i);\n let h = 0.02519603282416938 * n;\n n = h >>> 0;\n h -= n;\n h *= n;\n n = h >>> 0;\n h -= n;\n n += h * 0x100000000; // 2^32\n }\n return (n >>> 0) * 2.3283064365386963e-10; // 2^-32\n }\n }\n\n next() {\n let {c,s0,s1,s2} = this;\n let t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32\n this.s0 = s1;\n this.s1 = s2;\n return this.s2 = t - (this.c = t | 0);\n }\n\n copy(f, t) {\n t.c = f.c;\n t.s0 = f.s0;\n t.s1 = f.s1;\n t.s2 = f.s2;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xor128\" prng algorithm by\nfunction prng_xor128(seed, opts) {\n let xg = new Xor128Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass Xor128Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w} = this;\n let t = x ^ (x << 11);\n this.x = y;\n this.y = z;\n this.z = w;\n return this.w = w ^ ((w >>> 19) ^ t ^ (t >>> 8));\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorwow\" prng algorithm by\nfunction prng_xorwow(seed, opts) {\n let xg = new XorWowGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass XorWowGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n this.v = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n if (k == strseed.length) {\n this.d = this.x << 10 ^ this.x >>> 4;\n }\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w,v,d} = this;\n let t = (x ^ (x >>> 2));\n this.x = y;\n this.y = z;\n this.z = w;\n this.w = v;\n return (this.d = (d + 362437 | 0)) +\n (this.v = (v ^ (v << 4)) ^ (t ^ (t << 1))) | 0;\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n t.v = f.v;\n t.d = f.d;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorshift7\" algorithm by\nfunction prng_xorshift7(seed, opts) {\n let xg = new XorShift7Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass XorShift7Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n var j, w, x = [];\n\n if (seed === (seed | 0)) {\n // Seed state array using a 32-bit integer.\n w = x[0] = seed;\n } else {\n // Seed state using a string.\n seed = '' + seed;\n for (j = 0; j < seed.length; ++j) {\n x[j & 7] = (x[j & 7] << 15) ^\n (seed.charCodeAt(j) + x[(j + 1) & 7] << 13);\n }\n }\n\n // Enforce an array length of 8, not all zeroes.\n while (x.length < 8) x.push(0);\n for (j = 0; j < 8 && x[j] === 0; ++j);\n if (j == 8) w = x[7] = -1; else w = x[j];\n\n this.x = x;\n this.i = 0;\n\n // Discard an initial 256 values.\n for (j = 256; j > 0; --j) {\n this.next();\n }\n }\n\n next() {\n // Update xor generator.\n let t, v, {x,i} = this;\n t = x[i]; t ^= (t >>> 7); v = t ^ (t << 24);\n t = x[(i + 1) & 7]; v ^= t ^ (t >>> 10);\n t = x[(i + 3) & 7]; v ^= t ^ (t >>> 3);\n t = x[(i + 4) & 7]; v ^= t ^ (t << 7);\n t = x[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);\n x[i] = v;\n this.i = (i + 1) & 7;\n return v;\n };\n\n copy(f, t) {\n t.x = [... f.x];\n t.i = f.i;\n return t;\n }\n}\n\n// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.\nfunction prng_xor4096(seed, opts) {\n let xg = new Xor4096Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass Xor4096Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let t, v, i, j, w, X = [], limit = 128;\n if (seed === (seed | 0)) {\n // Numeric seeds initialize v, which is used to generates X.\n v = seed;\n seed = null;\n } else {\n // String seeds are mixed into v and X one character at a time.\n seed = seed + '\\0';\n v = 0;\n limit = Math.max(limit, seed.length);\n }\n // Initialize circular array and weyl value.\n for (i = 0, j = -32; j < limit; ++j) {\n // Put the unicode characters into the array, and shuffle them.\n if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);\n // After 32 shuffles, take v as the starting w value.\n if (j === 0) w = v;\n v ^= v << 10;\n v ^= v >>> 15;\n v ^= v << 4;\n v ^= v >>> 13;\n if (j >= 0) {\n w = (w + 0x61c88647) | 0; // Weyl.\n t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array.\n i = (0 == t) ? i + 1 : 0; // Count zeroes.\n }\n }\n // We have detected all zeroes; make the key nonzero.\n if (i >= 128) {\n X[(seed && seed.length || 0) & 127] = -1;\n }\n // Run the generator 512 times to further mix the state before using it.\n // Factoring this as a function slows the main generator, so it is just\n // unrolled here. The weyl generator is not advanced while warming up.\n i = 127;\n for (j = 4 * 128; j > 0; --j) {\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n X[i] = v ^ t;\n }\n // Storing state as object members is faster than using closure variables.\n this.w = w;\n this.X = X;\n this.i = i;\n }\n\n next() {\n let t, v, {w, X, i} = this;\n // Update Weyl generator.\n this.w = w = (w + 0x61c88647) | 0;\n // Update xor generator.\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n // Update Xor generator array state.\n v = X[i] = v ^ t;\n this.i = i;\n // Result is the combination.\n return (v + (w ^ (w >>> 16))) | 0;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.w = f.w;\n t.X = [... f.X];\n return t;\n }\n}\n\n// A Javascript implementaion of the \"Tyche-i\" prng algorithm by\nfunction prng_tychei(seed, opts) {\n let xg = new TycheiGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass TycheiGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.a = 0;\n this.b = 0;\n this.c = 2654435769 | 0;\n this.d = 1367130551;\n\n if (seed === Math.floor(seed)) {\n // Integer seed.\n this.a = (seed / 0x100000000) | 0;\n this.b = seed | 0;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 20; k++) {\n this.b ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {a,b,c,d} = this;\n b = (b << 25) ^ (b >>> 7) ^ c;\n c = (c - d) | 0;\n d = (d << 24) ^ (d >>> 8) ^ a;\n a = (a - b) | 0;\n this.b = b = (b << 20) ^ (b >>> 12) ^ c;\n this.c = c = (c - d) | 0;\n this.d = (d << 16) ^ (c >>> 16) ^ a;\n return this.a = (a - b) | 0;\n };\n\n copy(f, t) {\n t.a = f.a;\n t.b = f.b;\n t.c = f.c;\n t.d = f.d;\n return t;\n }\n}\n\n\n/* The following is non-inverted tyche, which has better internal\n * bit diffusion, but which is about 25% slower than tyche-i in JS.\n *\n\nclass TycheiGenAlt extends TycheiGen {\n next() {\n let {a,b,c,d} = this\n a = (a + b | 0) >>> 0;\n d = d ^ a; d = d << 16 ^ d >>> 16;\n c = c + d | 0;\n b = b ^ c; b = b << 12 ^ d >>> 20;\n this.a = a = a + b | 0;\n d = d ^ a; this.d = d = d << 8 ^ d >>> 24;\n this.c = c = c + d | 0;\n b = b ^ c;\n return this.b = (b << 7 ^ b >>> 25);\n }\n}\n*/\n\n/*\nCopyright 2019 David Bau.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*/\nfunction prng_arc4(seed, opts) {\n let xg = new ARC4Gen(seed);\n let prng = () => xg.next();\n\n prng.double = prng;\n\n prng.int32 = () => xg.g(4) | 0;\n\n prng.quick = () => xg.g(4) / 0x100000000;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\n\n//\n// ARC4\n//\n// An ARC4 implementation. The constructor takes a key in the form of\n// an array of at most (width) integers that should be 0 <= x < (width).\n//\n// The g(count) method returns a pseudorandom integer that concatenates\n// the next (count) outputs from ARC4. Its return value is a number x\n// that is in the range 0 <= x < (width ^ count).\n//\n\n//\n// The following constants are related to IEEE 754 limits.\n//\n\n// const width = 256 // each RC4 output is 0 <= x < 256\n// const chunks = 6 // at least six RC4 outputs for each double\nconst _arc4_startdenom = 281474976710656; // 256 ** 6 == width ** chunks\nconst _arc4_significance = 4503599627370496; // 2 ** 52 significant digits in a double\nconst _arc4_overflow = 9007199254740992; // 2 ** 53 == significance * 2\n\n\nclass ARC4Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let key = this.mixkey(seed, []);\n let i,j,t, S=[], keylen = key.length;\n this.i = this.j = i = j = 0;\n this.S = S;\n\n // The empty key [] is treated as [0].\n if (!keylen) { key = [keylen++]; }\n\n // Set up S using the standard key scheduling algorithm.\n while (i <= 0xff) {\n S[i] = i++;\n }\n for (i = 0; i <= 0xff; i++) {\n S[i] = S[j = 0xff & (j + key[i % keylen] + (t = S[i]))];\n S[j] = t;\n }\n\n // For robust unpredictability, the function call below automatically\n // discards an initial batch of values. This is called RC4-drop[256].\n // See http://google.com/search?q=rsa+fluhrer+response&btnI\n this.g(256);\n }\n\n next() {\n // This function returns a random double in [0, 1) that contains\n // randomness in every bit of the mantissa of the IEEE 754 value.\n\n let n = this.g(6); // Start with a numerator n < 2 ^ 48\n let d = _arc4_startdenom; // and denominator d = 2 ^ 48.\n let x = 0; // and no 'extra last byte'.\n\n while (n < _arc4_significance) { // Fill up all significant digits (2 ** 52)\n n = (n + x) * 256; // by shifting numerator and\n d *= 256; // denominator and generating a\n x = this.g(1); // new least-significant-byte.\n }\n while (n >= _arc4_overflow) { // To avoid rounding past overflow, before adding\n n /= 2; // last byte, shift everything\n d /= 2; // right using integer math until\n x >>>= 1; // we have exactly the desired bits.\n }\n return (n + x) / d; // Form the number within [0, 1).\n }\n\n g(count) {\n // The \"g\" method returns the next (count) outputs as one number.\n let t, r = 0, {i,j,S} = this;\n while (count--) {\n t = S[i = 0xff & (i + 1)];\n r = r * 256 + S[0xff & ((S[i] = S[j = 0xff & (j + t)]) + (S[j] = t))];\n }\n this.i = i;\n this.j = j;\n return r;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.j = f.j;\n t.S = [... f.S];\n return t;\n }\n\n mixkey(seed, key) {\n seed = seed + '';\n let smear=0, j=0;\n while (j < seed.length) {\n key[0xff & j] =\n 0xff & ((smear ^= key[0xff & j] * 19) + seed.charCodeAt(j++));\n }\n return key\n }\n}\n\nexport { prng_alea, prng_arc4, prng_tychei, prng_xor128, prng_xor4096, prng_xorshift7, prng_xorwow };\n//# sourceMappingURL=index.mjs.map\n","import { usesRadians as runtimeUsesRadians } from \"./runtime.js\";\n\n// =============================================================================\n// Section: Randomness & Noise\n// =============================================================================\n\nimport { createNoise2D } from \"simplex-noise\";\nimport { prng_alea } from \"esm-seedrandom\";\n\n/**\n * A uniform PRNG function. Returns a float in [0,1).\n * @callback RNG\n * @returns {number}\n */\n/** @type {RNG} */\nlet rng = prng_alea(Math.random());\nlet rng2 = prng_alea(Math.random());\n\nconst _seedCallbacks = [];\n\n/**\n * Register a callback to be called whenever seed() is invoked.\n * Used internally by modules that maintain gaussian pools.\n * @param {Function} cb\n */\nexport const _onSeed = (cb) => _seedCallbacks.push(cb);\n\n/**\n * Seed the random number generator.\n * @param {number|string} s – The seed value.\n * @returns {void}\n */\nexport const seed = (s) => {\n rng = prng_alea(s);\n rng2 = prng_alea(`${s}:2`);\n for (const callback of _seedCallbacks) {\n callback();\n }\n};\n\n/**\n * Simplex‐noise 2D function.\n * @type {function(number, number): number}\n */\nexport let noise = createNoise2D(prng_alea(Math.random()));\nexport let noise2 = createNoise2D(prng_alea(Math.random()));\n\n/**\n * Seed the noise generator.\n * @param {number|string} s - The seed value.\n * @returns {void}\n */\nexport const noiseSeed = (s) => {\n noise = createNoise2D(prng_alea(s));\n noise2 = createNoise2D(prng_alea(`${s}:2`));\n};\n\n/**\n * Returns a random float in [min, max).\n * @param {number} [min=0]\n * @param {number} [max=1]\n * @returns {number}\n */\nexport const rr = (e = 0, r = 1) => e + rng() * (r - e);\nexport const rr2 = (e = 0, r = 1) => e + rng2() * (r - e);\n\n/**\n * Selects a random element from an array.\n * @param {T[]} array - Input array.\n * @returns {T}\n */\nexport const rArray = (array) => array[~~(rng() * array.length)];\n\n/**\n * Returns a random integer in [min, max).\n * @param {number} min\n * @param {number} max\n * @returns {number}\n */\nexport const randInt = (e, r) => ~~rr(e, r);\nexport const randInt2 = (e, r) => ~~rr2(e, r);\n\n/**\n * Gaussian (normal) random sample N(mean, stdev²).\n * @param {number} [mean=0]\n * @param {number} [stdev=1]\n * @returns {number}\n */\nexport const gaussian = (mean = 0, stdev = 1) => {\n const u = 1 - rng();\n const v = rng();\n const z = Math.sqrt(-2.0 * Math.log(u)) * cos(360 * v);\n return z * stdev + mean;\n};\n\n/**\n * Picks a key from an object according to weighted probabilities.\n * @param {Object<string|number, number>} weights\n * @returns {string|number}\n */\nexport const weightedRand = (weights) => {\n let totalWeight = 0;\n const entries = [];\n\n // Build cumulative weights array\n for (const key in weights) {\n totalWeight += weights[key];\n entries.push({ key, cumulative: totalWeight });\n }\n\n // Get a random number between 0 and totalWeight\n const rnd = rng() * totalWeight;\n\n // Pick the first entry where rnd is less than the cumulative weight\n for (const { key, cumulative } of entries) {\n if (rnd < cumulative) {\n return isNaN(key) ? key : parseInt(key);\n }\n }\n};\n\n// =============================================================================\n// Section: Numeric Mapping & Constraints\n// =============================================================================\n\n/**\n * Maps a value from range [a,b] to [c,d], optionally clamped.\n * @param {number} value\n * @param {number} a\n * @param {number} b\n * @param {number} c\n * @param {number} d\n * @param {boolean} [withinBounds=false]\n * @returns {number}\n */\nexport const map = (value, a, b, c, d, withinBounds = false) => {\n let r = c + ((value - a) / (b - a)) * (d - c);\n if (!withinBounds) return r;\n if (c < d) return constrain(r, c, d);\n else return constrain(r, d, c);\n};\n\n/**\n * Constrains a number within the provided bounds.\n * @param {number} n - The number.\n * @param {number} low - Lower bound.\n * @param {number} high - Upper bound.\n * @returns {number} The constrained number.\n */\nexport const constrain = (n, low, high) => Math.max(Math.min(n, high), low);\n\n// =============================================================================\n// Section: Trigonometry\n// =============================================================================\n\n/**\n * Normalize an angle in degrees to [0,360).\n * @param {number} angle\n * @returns {number}\n */\nconst nAngle = (angle) => {\n angle = angle % 360;\n return angle < 0 ? angle + 360 : angle;\n};\n\n// number of discrete steps (360° × 4 samples per degree)\nconst totalDegrees = 1440;\nconst radiansPerIndex = (2 * Math.PI) / totalDegrees;\n\n// lazy‐initialized lookup tables\nconst cLookup = new Float32Array(totalDegrees).fill(NaN);\nconst sLookup = new Float32Array(totalDegrees).fill(NaN);\n\n/**\n * Cosine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const cos = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = cLookup[idx];\n if (isNaN(v)) {\n v = Math.cos(idx * radiansPerIndex);\n cLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Sine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const sin = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = sLookup[idx];\n if (isNaN(v)) {\n v = Math.sin(idx * radiansPerIndex);\n sLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Converts radians to degrees, normalized to [0,360).\n * @param {number} rad\n * @returns {number}\n */\nexport const toDegrees = (rad, isRad = false) => {\n if (isRad || runtimeUsesRadians()) {\n let angle = ((rad * 180) / Math.PI) % 360;\n return angle < 0 ? angle + 360 : angle;\n } else {\n return rad;\n }\n};\n\n/**\n * Converts radians to degrees without wrapping the result.\n * Preserves signed angles so downstream scaling keeps its direction.\n * @param {number} angle\n * @param {boolean} [isRad=false]\n * @returns {number}\n */\nexport const toDegreesSigned = (angle, isRad = false) =>\n isRad || runtimeUsesRadians()\n ? (angle * 180) / Math.PI\n : angle;\n\n// =============================================================================\n// Section: Geometry & Transforms\n// =============================================================================\n\n/**\n * Rotates point (x,y) around center (cx,cy) by angle degrees.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x\n * @param {number} y\n * @param {number} angle - Degrees\n * @returns {{x:number,y:number}}\n */\nexport const rotate = (cx, cy, x, y, angle) => {\n let coseno = cos(angle),\n seno = sin(angle),\n nx = coseno * (x - cx) + seno * (y - cy) + cx,\n ny = coseno * (y - cy) - seno * (x - cx) + cy;\n return { x: nx, y: ny };\n};\n\n/**\n * Euclidean distance between two points.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const dist = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1);\n\n/**\n * Angle in degrees between two points, measured clockwise from +X.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const calcAngle = (x1, y1, x2, y2) =>\n toDegrees(Math.atan2(-(y2 - y1), x2 - x1), true);\n\n/**\n * Intersection of two line segments, or false if none.\n * @param {{x:number,y:number}} s1a\n * @param {{x:number,y:number}} s1b\n * @param {{x:number,y:number}} s2a\n * @param {{x:number,y:number}} s2b\n * @param {boolean} [includeSegmentExtension=false]\n * @returns {{x:number,y:number}|false}\n */\nexport const intersectLines = (\n s1a,\n s1b,\n s2a,\n s2b,\n includeSegmentExtension = false\n) => {\n // Extract coordinates from points\n let x1 = s1a.x,\n y1 = s1a.y;\n let x2 = s1b.x,\n y2 = s1b.y;\n let x3 = s2a.x,\n y3 = s2a.y;\n let x4 = s2b.x,\n y4 = s2b.y;\n // Early return if line segments are points or if the lines are parallel\n if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) {\n return false; // Segments are points\n }\n let deltaX1 = x2 - x1,\n deltaY1 = y2 - y1;\n let deltaX2 = x4 - x3,\n deltaY2 = y4 - y3;\n let denominator = deltaY2 * deltaX1 - deltaX2 * deltaY1;\n if (denominator === 0) {\n return false; // Lines are parallel\n }\n // Calculate the intersection point\n let ua = (deltaX2 * (y1 - y3) - deltaY2 * (x1 - x3)) / denominator;\n let ub = (deltaX1 * (y1 - y3) - deltaY1 * (x1 - x3)) / denominator;\n // Check if the intersection is within the bounds of the line segments\n if (!includeSegmentExtension && (ub < 0 || ub > 1)) {\n return false;\n }\n // Calculate the intersection coordinates\n let x = x1 + ua * deltaX1;\n let y = y1 + ua * deltaY1;\n return { x: x, y: y };\n};\n","import { Cwidth, Cheight } from \"./target.js\";\nimport { isMixReady, State } from \"./color.js\";\nimport { randInt2, noise2, rr2, sin, cos, map, toDegreesSigned } from \"./utils.js\";\nimport { getAffineMatrix } from \"./runtime.js\";\n\n// =============================================================================\n// Section: Matrix transformations\n// =============================================================================\n\n// =============================================================================\n// Section: Field Initialization\n// =============================================================================\n\nlet isLoaded = false;\n\n/**\n * Ensures the field system is initialized and ready for use.\n * If the field is not loaded, it initializes the mixing system and creates the field.\n */\nexport function isFieldReady() {\n if (!isLoaded) {\n isMixReady(); // Ensure the mixing system is ready\n createField(); // Initialize the field\n isLoaded = true;\n }\n}\n\n// =============================================================================\n// Section: Position Class\n// =============================================================================\n\n/**\n * The Position class represents a point within a two-dimensional space, which can interact with a vector field.\n * It provides methods to update the position based on the field's flow and to check whether the position is\n * within certain bounds (e.g., within the field or canvas).\n */\nexport class Position {\n /**\n * Constructs a new Position instance.\n * @param {number} x - The initial x-coordinate.\n * @param {number} y - The initial y-coordinate.\n */\n constructor(x, y) {\n isFieldReady();\n const m = getAffineMatrix();\n this.mx = m.x;\n this.my = m.y;\n this.update(x, y);\n this.plotted = 0; // Tracks the total distance plotted\n }\n\n /**\n * Updates the position's coordinates and calculates its offsets and indices within the flow field.\n * @param {number} x - The new x-coordinate.\n * @param {number} y - The new y-coordinate.\n */\n update(x, y) {\n this.x = x;\n this.y = y;\n if (State.field.isActive) {\n this.colIdx = Math.round((x + this.mx - left_x) / resolution);\n this.rowIdx = Math.round((y + this.my - top_y) / resolution);\n }\n }\n\n /**\n * Resets the 'plotted' property to 0.\n */\n reset() {\n this.plotted = 0;\n }\n\n /**\n * Checks if the position is within the active flow field's bounds.\n * @returns {boolean} - True if the position is within the flow field, false otherwise.\n */\n isIn() {\n return State.field.isActive\n ? Position.isIn(this.colIdx, this.rowIdx)\n : this.isInCanvas(this.x, this.y);\n }\n\n /**\n * Checks if the position is within the canvas bounds (with a margin).\n * @returns {boolean} - True if the position is within bounds, false otherwise.\n */\n isInCanvas() {\n const margin = 0.3;\n const w = Cwidth;\n const h = Cheight;\n const x = this.x + this.mx;\n const y = this.y + this.my;\n return (\n x >= -margin * w &&\n x <= (1 + margin) * w &&\n y >= -margin * h &&\n y <= (1 + margin) * h\n );\n }\n\n /**\n * Calculates the angle of the flow field at the position's current coordinates.\n * @returns {number} - The internal flow angle in degrees, or 0 if the position is not in the field or if no field is active.\n */\n angle(skipCheck = false) {\n if (!State.field.isActive) return 0;\n return (skipCheck || this.isIn())\n ? flow_field()[this.colIdx][this.rowIdx] * State.field.wiggle\n : 0;\n }\n\n /**\n * Moves the position along the flow field by a certain length.\n * @param {number} _dir - The direction of movement, interpreted using the current runtime angle units.\n * @param {number} _length - The length to move along the field.\n * @param {number} _step_length - The length of each step.\n */\n moveTo(_dir, _length, _step_length = 1) {\n this.movePos(toDegreesSigned(_dir), _length, _step_length);\n }\n\n /**\n * Internal variant of moveTo() that expects a degree value already normalized to the library's internal representation.\n */\n _moveToDegrees(_dir, _length, _step_length = 1) {\n this.movePos(_dir, _length, _step_length);\n }\n\n /**\n * Plots a point to another position within the flow field, following a Plot object\n * @param {Position} _plot - The Plot path object.\n * @param {number} _length - The length to move towards the target position.\n * @param {number} _step_length - The length of each step.\n * @param {number} _scale - The scaling factor for the plotting path.\n */\n plotTo(_plot, _length, _step_length, _scale = 1, precomputedAngle = undefined) {\n this.movePos(_plot, _length, _step_length, _scale, precomputedAngle);\n }\n\n movePos(_dirPlot, _length, _step, _scale = false, precomputedAngle = undefined) {\n const scaleFactor = _scale || 1;\n if (!this.isIn()) {\n this.plotted += _step / scaleFactor;\n return;\n }\n const steps = _length / _step;\n const fieldActive = State.field.isActive;\n const usePlot = !!_scale;\n for (let i = 0; i < steps; i++) {\n const plotAngle = (usePlot && precomputedAngle !== undefined && i === 0)\n ? precomputedAngle\n : (usePlot ? _dirPlot.angle(this.plotted) : _dirPlot);\n const angle = (fieldActive ? this.angle(true) : 0) - plotAngle;\n // Calculate new position\n this.update(this.x + _step * cos(angle), this.y + _step * sin(angle));\n this.plotted += _step / scaleFactor;\n }\n }\n\n // Static Methods\n\n /**\n * Gets the row index for a given y-coordinate.\n * @param {number} y - The y-coordinate.\n * @returns {number} - The row index.\n */\n static getRowIndex(y, d = 1) {\n const y_offset = y + getAffineMatrix().y - top_y;\n return Math.round(y_offset / resolution / d);\n }\n\n /**\n * Gets the column index for a given x-coordinate.\n * @param {number} x - The x-coordinate.\n * @returns {number} - The column index.\n */\n static getColIndex(x, d = 1) {\n const x_offset = x + getAffineMatrix().x - left_x;\n return Math.round(x_offset / resolution / d);\n }\n\n /**\n * Checks if a column and row index are within the flow field bounds.\n * @param {number} col - The column index.\n * @param {number} row - The row index.\n * @returns {boolean} - True if the indices are within bounds, false otherwise.\n */\n static isIn(col, row) {\n return col >= 0 && row >= 0 && col < num_columns && row < num_rows;\n }\n}\n\n// =============================================================================\n// Section: VectorField\n// =============================================================================\n\n/**\n * Represents the state of the vector field.\n * @property {boolean} isActive - Indicates if the vector field is active.\n * @property {string|null} current - The name of the currently active vector field.\n */\nState.field = {\n isActive: false,\n current: null,\n wiggle: 1,\n};\n\n// Internal variables for field configuration\nlet list = new Map();\nlet resolution, left_x, top_y, num_columns, num_rows;\nconst FIELD_ANGLE_MODES = new Set([\"degrees\", \"radians\"]);\n\n/**\n * Initializes the field grid and sets up the vector field's structure based on the renderer's dimensions.\n */\nfunction createField() {\n resolution = Cwidth * 0.01; // Determine the resolution of the field grid\n left_x = -0.5 * Cwidth; // Left boundary of the field\n top_y = -0.5 * Cheight; // Top boundary of the field\n num_columns = Math.round((2 * Cwidth) / resolution); // Number of columns in the grid\n num_rows = Math.round((2 * Cheight) / resolution); // Number of columns in the grid\n addStandard(); // Add default vector field\n}\n\n/**\n * Retrieves the field values for the current vector field.\n * @returns {Float32Array[]} The current vector field grid.\n */\nfunction flow_field() {\n return list.get(State.field.current).field;\n}\n\nfunction normalizeFieldAngleMode(options = {}) {\n const config =\n typeof options === \"string\" ? { angleMode: options } : options || {};\n const angleMode = config.angleMode ?? \"degrees\";\n\n if (!FIELD_ANGLE_MODES.has(angleMode)) {\n throw new Error(\n `Invalid field angle mode \"${angleMode}\". Use \"degrees\" or \"radians\".`,\n );\n }\n\n return angleMode;\n}\n\nfunction normalizeFieldAngles(field, angleMode) {\n if (angleMode !== \"radians\") return field;\n\n for (let c = 0; c < field.length; c++) {\n for (let r = 0; r < field[c].length; r++) {\n field[c][r] = toDegreesSigned(field[c][r], true);\n }\n }\n\n return field;\n}\n\nfunction generateField(entry, t) {\n return normalizeFieldAngles(entry.gen(t, genField()), entry.angleMode);\n}\n\n/**\n * Regenerates the current vector field using its associated generator function.\n * @param {number} [t=0] - An optional time parameter that can affect field generation.\n */\nexport function refreshField(t = 0) {\n if (!State.field.isActive || !State.field.current) {\n throw new Error(\n \"No field is currently active. Call brush.field('name') to activate one before refreshing.\",\n );\n }\n const currentField = list.get(State.field.current);\n currentField.field = generateField(currentField, t);\n}\n\n/**\n * Generates an empty field array.\n * Reuses existing arrays to reduce memory allocation overhead.\n * @returns {Float32Array[]} Empty vector field grid.\n */\nfunction genField() {\n return new Array(num_columns)\n .fill(null)\n .map(() => new Float32Array(num_rows));\n}\n\n/**\n * Activates a specific vector field by name, ensuring it's ready for use.\n * @param {string} a - The name of the vector field to activate.\n */\nexport function field(a) {\n if (!State.field.wiggle) {\n State.field.wiggle = 1;\n } // Set default wiggle value\n isFieldReady();\n if (!list.has(a)) {\n throw new Error(\n `Field \"${a}\" does not exist. Available fields: ${Array.from(list.keys()).join(\", \")}.`,\n );\n }\n State.field.isActive = true;\n State.field.current = a;\n const entry = list.get(a);\n if (!entry.field) entry.field = generateField(entry, 0);\n}\n\n/**\n * Deactivates the current vector field.\n */\nexport function noField() {\n isFieldReady();\n State.field.isActive = false;\n}\n\n/**\n * Adds a new vector field to the field list with a unique name and a generator function.\n * @param {string} name - The unique name for the new vector field.\n * @param {Function} funct - The function that generates the field values.\n * @param {object} [options] - Optional field configuration.\n * @param {\"degrees\"|\"radians\"} [options.angleMode=\"degrees\"] - How the generator's output angles should be interpreted.\n */\nexport function addField(name, funct, options = {}) {\n list.set(name, {\n gen: funct,\n field: null,\n angleMode: normalizeFieldAngleMode(options),\n });\n}\n\n/**\n * Retrieves a list of all available vector field names.\n * @returns {string[]} An array of all the field names.\n */\nexport function listFields() {\n isFieldReady();\n return Array.from(list.keys());\n}\n\nexport function wiggle(a = 1) {\n field(\"hand\");\n State.field.wiggle = a;\n}\n\n/**\n * Fills every cell of a field grid using a callback (c, r) => angle.\n */\nfunction fillField(field, fn) {\n for (let c = 0; c < num_columns; c++)\n for (let r = 0; r < num_rows; r++) field[c][r] = fn(c, r);\n return field;\n}\n\n/**\n * Adds standard predefined vector fields to the list with unique behaviors.\n */\nfunction addStandard() {\n // Organic noise — basis for brush.wiggle()\n addField(\"hand\", (t, field) => {\n const bs = rr2(0.2, 0.8),\n ba = randInt2(5, 10);\n return fillField(field, (c, r) => {\n const angle = 0.5 * ba * sin(bs * r * c + randInt2(15, 25));\n return 0.2 * angle * cos(t) + noise2(c, r) * ba * 0.7;\n });\n });\n // Smooth large-scale noise curves\n addField(\"curved\", (t, field) => {\n let ar = randInt2(-10, 10);\n if (randInt2(0, 100) % 2 == 0) ar *= -1;\n return fillField(\n field,\n (c, r) =>\n 3 * map(noise2(c * 0.02 + t * 0.03, r * 0.02 + t * 0.03), 0, 1, -ar, ar),\n );\n });\n // Sharp alternating angles per cell — herringbone / wicker look\n addField(\"zigzag\", (t, field) => {\n let ar = randInt2(-30, -15) + Math.abs(44 * sin(t));\n if (randInt2(0, 100) % 2 == 0) ar *= -1;\n let dif = ar,\n angle = 0;\n for (let c = 0; c < num_columns; c++) {\n for (let r = 0; r < num_rows; r++) {\n field[c][r] = angle;\n angle += dif;\n dif *= -1;\n }\n angle += dif;\n dif *= -1;\n }\n return field;\n });\n // Sinusoidal wave bands\n addField(\"waves\", (t, field) => {\n const sr = randInt2(10, 15) + 5 * sin(t),\n cr = randInt2(3, 6) + 3 * cos(t),\n ba = randInt2(20, 35);\n return fillField(\n field,\n (c, r) => sin(sr * c) * ba * cos(r * cr) + randInt2(-3, 3),\n );\n });\n // Dense oscillation from row×col product\n addField(\"seabed\", (t, field) => {\n const bs = rr2(0.4, 0.8),\n ba = randInt2(18, 26);\n return fillField(\n field,\n (c, r) => 1.1 * ba * sin(bs * r * c + randInt2(15, 20)) * cos(t),\n );\n });\n // Radial vortex — angles spiral around the field centre\n addField(\"spiral\", (_t, field) => {\n const n = randInt2(5, 10);\n const dir = randInt2(0, 2) * 2 - 1;\n const offset = randInt2(65, 80); // <90 = inward spiral\n const attractors = Array.from({ length: n }, () => ({\n x: rr2(0.1, 0.9) * num_columns,\n y: rr2(0.1, 0.9) * num_rows,\n }));\n return fillField(field, (c, r) => {\n let wx = 0,\n wy = 0;\n for (const att of attractors) {\n const dx = c - att.x,\n dy = r - att.y;\n const w = 1 / (dx * dx + dy * dy + 1);\n const a = Math.atan2(dy, dx) * (180 / Math.PI);\n const angle = (dir * (a + offset) * Math.PI) / 180;\n wx += w * Math.cos(angle);\n wy += w * Math.sin(angle);\n }\n return Math.atan2(wy, wx) * (180 / Math.PI);\n });\n });\n // Column-banded stripes — parallel rake marks\n addField(\"columns\", (_t, field) => {\n const freq = randInt2(3, 8),\n amp = randInt2(25, 45);\n return fillField(field, (c, _r) => sin(c * freq) * amp);\n });\n}\n","import { State } from \"./color.js\";\nimport { isFieldReady } from \"./flowfield.js\";\n\n// =============================================================================\n// SAVE / RESTORE\n// =============================================================================\n\n/**\n * Stack of saved brush states for push/pop operations.\n * A stack (not a single slot) is required because applyShader() internally\n * calls Renderer.push()/pop(), which fires our hook — a flat object would be\n * overwritten mid-draw and pop() would restore the wrong state.\n */\nconst _stateStack = [];\n\n/**\n * Pushes the current brush state onto the stack.\n */\nexport function push() {\n isFieldReady();\n _stateStack.push({\n fill: { ...State.fill },\n wash: State.wash ? { ...State.wash } : null,\n stroke: { ...State.stroke },\n hatch: { ...State.hatch },\n mass: State.mass ? { ...State.mass } : null,\n field: { ...State.field },\n });\n}\n\n/**\n * Pops the top brush state from the stack and restores it.\n */\nexport function pop() {\n const saved = _stateStack.pop();\n if (!saved) return;\n State.stroke = { ...saved.stroke };\n State.field = { ...saved.field };\n State.hatch = { ...saved.hatch };\n State.fill = { ...saved.fill };\n if (saved.wash) State.wash = { ...saved.wash };\n if (saved.mass) {\n State.mass = { ...saved.mass };\n } else if (State.mass) {\n State.mass = {\n ...State.mass,\n isActive: false,\n brush: null,\n color: null,\n options: {},\n };\n }\n}\n","// =============================================================================\n// Adapter: Standalone Runtime Hooks\n// =============================================================================\n\nimport { setRuntime } from \"../../core/runtime.js\";\nimport { push as pushState, pop as popState } from \"../../core/save.js\";\n\nconst clamp = (value, min, max) => Math.max(min, Math.min(value, max));\n\nexport const DEGREES = \"degrees\";\nexport const RADIANS = \"radians\";\n\nlet colorContext = null;\nlet currentAngleMode = RADIANS;\nconst transformStack = [];\nlet currentTransform = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\n\nfunction getColorContext() {\n if (colorContext) return colorContext;\n\n if (typeof document !== \"undefined\") {\n colorContext = document.createElement(\"canvas\").getContext(\"2d\");\n return colorContext;\n }\n\n if (typeof OffscreenCanvas !== \"undefined\") {\n colorContext = new OffscreenCanvas(1, 1).getContext(\"2d\");\n return colorContext;\n }\n\n throw new Error(\"Standalone color parsing requires CanvasRenderingContext2D support.\");\n}\n\nfunction multiplyTransform(left, right) {\n return {\n a: left.a * right.a + left.c * right.b,\n b: left.b * right.a + left.d * right.b,\n c: left.a * right.c + left.c * right.d,\n d: left.b * right.c + left.d * right.d,\n x: left.a * right.x + left.c * right.y + left.x,\n y: left.b * right.x + left.d * right.y + left.y,\n };\n}\n\n/**\n * Runtime-native color object compatible with the expectations of core modules.\n */\nexport class Color {\n constructor(r, g, b) {\n if (r?._array) {\n this.r = Math.round(r._array[0] * 255);\n this.g = Math.round(r._array[1] * 255);\n this.b = Math.round(r._array[2] * 255);\n this.hex = this.rgbToHex(this.r, this.g, this.b);\n this._array = [...r._array];\n this.gl = this._array;\n return;\n }\n\n if (typeof r === \"string\") {\n const rgbaMatch = /^rgba?\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*(?:,\\s*([\\d.]+))?\\s*\\)$/i.exec(r);\n if (rgbaMatch) {\n this.r = clamp(parseInt(rgbaMatch[1]), 0, 255);\n this.g = clamp(parseInt(rgbaMatch[2]), 0, 255);\n this.b = clamp(parseInt(rgbaMatch[3]), 0, 255);\n this.hex = this.rgbToHex(this.r, this.g, this.b);\n const alpha = rgbaMatch[4] !== undefined ? clamp(parseFloat(rgbaMatch[4]), 0, 1) : 1;\n this._array = [this.r / 255, this.g / 255, this.b / 255, alpha];\n this.gl = this._array;\n return;\n }\n this.hex = this.standardize(r);\n const rgb = this.hexToRgb(this.hex);\n this.r = rgb.r;\n this.g = rgb.g;\n this.b = rgb.b;\n } else {\n this.r = clamp(r ?? 0, 0, 255);\n this.g = clamp(g ?? r ?? 0, 0, 255);\n this.b = clamp(b ?? r ?? 0, 0, 255);\n this.hex = this.rgbToHex(this.r, this.g, this.b);\n }\n\n this._array = [this.r / 255, this.g / 255, this.b / 255, 1];\n this.gl = this._array;\n }\n\n rgbToHex(r, g, b) {\n return `#${((1 << 24) | (r << 16) | (g << 8) | b).toString(16).slice(1)}`;\n }\n\n hexToRgb(hex) {\n hex = hex.replace(\n /^#?([a-f\\d])([a-f\\d])([a-f\\d])$/i,\n (_match, red, green, blue) => red + red + green + green + blue + blue,\n );\n const result = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\n if (!result) {\n throw new Error(`Invalid color value \"${hex}\".`);\n }\n return {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16),\n };\n }\n\n standardize(value) {\n const ctx = getColorContext();\n ctx.fillStyle = value;\n return ctx.fillStyle;\n }\n\n _getRed() {\n return this.r;\n }\n\n _getGreen() {\n return this.g;\n }\n\n _getBlue() {\n return this.b;\n }\n}\n\n/**\n * Sets the active standalone angle mode.\n *\n * @param {\"degrees\"|\"radians\"} mode\n */\nexport function angleMode(mode) {\n if (mode !== DEGREES && mode !== RADIANS) {\n throw new Error(`Invalid angle mode \"${mode}\". Use \"degrees\" or \"radians\".`);\n }\n currentAngleMode = mode;\n}\n\n/**\n * Returns the current standalone angle mode.\n *\n * @returns {\"degrees\"|\"radians\"}\n */\nexport function getAngleMode() {\n return currentAngleMode;\n}\n\n/**\n * Pushes the current standalone transform onto the stack.\n */\nexport function push() {\n pushState();\n transformStack.push({ ...currentTransform });\n}\n\n/**\n * Pops the last standalone transform from the stack.\n */\nexport function pop() {\n if (transformStack.length === 0) return;\n currentTransform = transformStack.pop();\n popState();\n}\n\n/**\n * Applies a translation to the current standalone transform.\n *\n * @param {number} x\n * @param {number} y\n */\nexport function translate(x, y) {\n currentTransform = multiplyTransform(currentTransform, {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x,\n y,\n });\n}\n\n/**\n * Applies a rotation to the current standalone transform.\n *\n * @param {number} angle\n */\nexport function rotate(angle) {\n const theta =\n currentAngleMode === RADIANS ? angle : (angle * Math.PI) / 180;\n const cosTheta = Math.cos(theta);\n const sinTheta = Math.sin(theta);\n currentTransform = multiplyTransform(currentTransform, {\n a: cosTheta,\n b: sinTheta,\n c: -sinTheta,\n d: cosTheta,\n x: 0,\n y: 0,\n });\n}\n\n/**\n * Applies a scale to the current standalone transform.\n *\n * @param {number} x\n * @param {number} [y=x]\n */\nexport function scale(x, y = x) {\n currentTransform = multiplyTransform(currentTransform, {\n a: x,\n b: 0,\n c: 0,\n d: y,\n x: 0,\n y: 0,\n });\n}\n\n/**\n * Installs the standalone runtime hooks used by core modules.\n */\nexport function initStandaloneRuntime() {\n setRuntime({\n usesRadians: () => currentAngleMode === \"radians\",\n fromDegrees: (angle) =>\n currentAngleMode === \"radians\" ? (angle * Math.PI) / 180 : angle,\n createColor: (...args) => {\n if (args.length === 1 && args[0]?._array) return args[0];\n return new Color(...args);\n },\n getAffineMatrix: () => currentTransform,\n });\n}\n","// =============================================================================\n// Adapter: Standalone Frame Helpers\n// =============================================================================\n\nimport { Renderer, isCanvasReady } from \"../../core/target.js\";\nimport { Mix, flushActiveComposite } from \"../../core/color.js\";\nimport { createColor } from \"../../core/runtime.js\";\n\nfunction resetCompositeState() {\n if (Mix.glMask) Mix.clearMask(Mix.glMask);\n if (Mix.mask) Mix.clearMask(Mix.mask);\n Mix.justChanged = false;\n Mix.isBlending = false;\n Mix.isBrush = null;\n Mix.cachedColor = null;\n}\n\n/**\n * Flushes any pending stroke/fill compositing into the active standalone target.\n *\n * Standalone users should call this at the end of a drawing pass or frame.\n */\nexport function render() {\n flushActiveComposite();\n}\n\n/**\n * Clears the active standalone target.\n *\n * With no arguments, clears to transparent white.\n * With a color, clears to that color at full opacity.\n *\n * @param {...*} args\n */\nexport function clear(...args) {\n isCanvasReady();\n resetCompositeState();\n\n const gl = Renderer.drawingContext;\n const color =\n args.length === 0\n ? [1, 1, 1, 0]\n : [...createColor(...args)._array.slice(0, 3), 1];\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.disable(gl.SCISSOR_TEST);\n gl.clearColor(color[0], color[1], color[2], color[3]);\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n}\n","// =============================================================================\n// Adapter: Standalone Target Hooks\n// =============================================================================\n\nimport {\n setTargetRuntime,\n setTargetState,\n} from \"../../core/target.js\";\n\nlet activeTarget = null;\nlet isLoaded = false;\nlet activeDensity = 1;\nlet activeWidth = 0;\nlet activeHeight = 0;\n\nfunction isCanvasTarget(target) {\n return (\n typeof HTMLCanvasElement !== \"undefined\" &&\n target instanceof HTMLCanvasElement\n );\n}\n\nfunction isOffscreenCanvasTarget(target) {\n return (\n typeof OffscreenCanvas !== \"undefined\" &&\n target instanceof OffscreenCanvas\n );\n}\n\nfunction isSupportedTarget(target) {\n return isCanvasTarget(target) || isOffscreenCanvasTarget(target);\n}\n\nfunction getTargetContext(target) {\n return (\n target.getContext(\"webgl2\", { premultipliedAlpha: true }) ??\n target.getContext(\"webgl2\")\n );\n}\n\nfunction createRenderer(target, width, height, density) {\n const drawingContext = getTargetContext(target);\n if (!drawingContext) {\n throw new Error(\"brush.load(target) requires a canvas with a WebGL2 context.\");\n }\n\n return {\n canvas: target,\n drawingContext,\n width,\n height,\n pixelDensity: () => density,\n };\n}\n\nfunction applyLoadedTarget(target, width, height, density) {\n activeTarget = target;\n activeWidth = width;\n activeHeight = height;\n activeDensity = density;\n\n const renderer = createRenderer(target, width, height, density);\n setTargetState({\n Renderer: renderer,\n Cwidth: width,\n Cheight: height,\n Density: density,\n });\n isLoaded = true;\n}\n\n/**\n * Loads a standalone draw target from a DOM canvas or OffscreenCanvas.\n *\n * @param {HTMLCanvasElement|OffscreenCanvas} target\n */\nexport function load(target = activeTarget) {\n if (!isSupportedTarget(target)) {\n throw new Error(\n \"Standalone brush.load(target) requires an HTMLCanvasElement or OffscreenCanvas.\",\n );\n }\n\n applyLoadedTarget(target, target.width, target.height, 1);\n}\n\n/**\n * Creates a standalone DOM canvas, configures its backing resolution according\n * to the provided pixel density, appends it optionally to the DOM, and loads it\n * as the active brush target.\n *\n * @param {number} width Logical canvas width.\n * @param {number} height Logical canvas height.\n * @param {{pixelDensity?: number, parent?: string|Element|null, id?: string}} [options]\n * @returns {HTMLCanvasElement}\n */\nexport function createCanvas(width, height, options = {}) {\n if (typeof document === \"undefined\") {\n throw new Error(\"brush.createCanvas() requires a browser document.\");\n }\n\n const logicalWidth = Math.max(1, Math.round(width));\n const logicalHeight = Math.max(1, Math.round(height));\n const density = Math.max(1, Number(options.pixelDensity) || 1);\n const canvas = document.createElement(\"canvas\");\n\n canvas.width = Math.max(1, Math.round(logicalWidth * density));\n canvas.height = Math.max(1, Math.round(logicalHeight * density));\n canvas.style.width = `${logicalWidth}px`;\n canvas.style.height = `${logicalHeight}px`;\n if (options.id) canvas.id = options.id;\n\n if (options.parent) {\n const parent =\n typeof options.parent === \"string\"\n ? document.querySelector(options.parent)\n : options.parent;\n if (!parent) {\n throw new Error(`Could not find parent \"${options.parent}\" for brush.createCanvas().`);\n }\n parent.appendChild(canvas);\n }\n\n applyLoadedTarget(canvas, logicalWidth, logicalHeight, density);\n return canvas;\n}\n\n/**\n * Refreshes the standalone target density.\n *\n * Standalone targets currently use a fixed density of 1.\n *\n * @returns {number}\n */\nexport function syncDensity() {\n setTargetState({\n Cwidth: activeWidth,\n Cheight: activeHeight,\n Density: activeDensity,\n });\n return activeDensity;\n}\n\n/**\n * Ensures a standalone target has been loaded.\n */\nexport function isCanvasReady() {\n if (!isLoaded) {\n throw new Error(\n \"No standalone target loaded. Call brush.load(canvasOrOffscreenCanvas) first.\",\n );\n }\n}\n\n/**\n * Standalone build does not use p5 instance switching, so these are no-ops.\n */\nexport function instance() {}\nexport function activateInstance() {}\nexport function deactivateInstance() {}\n\n/**\n * Standalone build does not yet support framebuffer targets.\n *\n * @returns {null}\n */\nexport function getActiveFramebuffer() {\n return null;\n}\n\n/**\n * Returns whether the given target behaves like a framebuffer target.\n *\n * Standalone targets currently only accept canvases and offscreen canvases.\n *\n * @returns {boolean}\n */\nexport function isFramebufferTarget() {\n return arguments[0]?.__brushFramebuffer === true;\n}\n\nexport function initStandaloneTargetRuntime() {\n setTargetRuntime({\n load,\n syncDensity,\n isCanvasReady,\n instance,\n activateInstance,\n deactivateInstance,\n getActiveFramebuffer,\n isFramebufferTarget,\n });\n}\n","import {\n rr2,\n randInt2,\n sin,\n cos,\n toDegreesSigned,\n constrain,\n dist,\n calcAngle,\n intersectLines,\n} from \"./utils.js\";\nimport { Polygon } from \"./polygon.js\";\nimport { Plot } from \"./plot.js\";\n\n// =============================================================================\n// Section: Primitives and Geommetry\n// =============================================================================\n\n/**\n * Creates a Polygon from an array of points and calls its show() method.\n * Polygons ignore fields and won't be good for fills and masses\n * @param {Array<Array<number>>} pointsArray - Array of points [x, y, pressure]\n */\nexport function polygon(pointsArray) {\n // Create a new Polygon instance\n const polygon = new Polygon(pointsArray);\n polygon.show();\n}\n\n/**\n * Draws a rectangle on the canvas using path functions.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} w - Width.\n * @param {number} h - Height.\n * @param {boolean} [mode=\"corner\"] - \"corner\" (default) or \"center\".\n */\nexport function rect(x, y, w, h, mode = \"corner\") {\n if (mode === \"center\") {\n x -= w / 2;\n y -= h / 2;\n }\n beginShape(0);\n vertex(x, y);\n vertex(x + w, y);\n vertex(x + w, y + h);\n vertex(x, y + h);\n endShape(true);\n}\n\n/**\n * Draws a circle on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Circle radius.\n * @param {boolean} [r=false] - Randomizes segment lengths if true.\n */\nexport function circle(x, y, radius, r = false) {\n const p = new Plot(\"curve\");\n const arcLength = Math.PI * radius;\n const angleOffset = rr2(0, 360);\n const randomFactor = r ? () => 1 + r * 0.2 * rr2() : () => 1;\n\n // Divide circle into 4 segments\n for (let i = 0; i < 4; i++) {\n const angle = -90 * i + angleOffset;\n p.addSegment(\n angle * randomFactor(),\n (arcLength / 2) * randomFactor(),\n 1,\n true,\n );\n }\n\n // Optionally add a random final angle for the last segment\n if (r) {\n const randomAngle = r * randInt2(-5, 5);\n p.addSegment(\n angleOffset,\n Math.abs(randomAngle) * (Math.PI / 180) * radius,\n 1,\n true,\n );\n p.endPlot(randomAngle + angleOffset, 1, true);\n } else {\n p.endPlot(angleOffset, 1, true);\n }\n\n // Draw the circle\n const offsetX = x - radius * sin(angleOffset);\n const offsetY = y - radius * cos(-angleOffset);\n p.show(offsetX, offsetY, 1);\n}\n\n/**\n * Draws an arc on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Radius.\n * @param {number} start - Start angle in the current runtime angle units.\n * @param {number} end - End angle in the current runtime angle units.\n */\nexport function arc(x, y, radius, start, end) {\n const startDeg = toDegreesSigned(start);\n const endDeg = toDegreesSigned(end);\n const sweepDeg = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweepDeg === 0) return;\n\n const p = new Plot(\"curve\");\n const segmentCount = Math.max(1, Math.ceil(sweepDeg / 90));\n const segmentSweep = sweepDeg / segmentCount;\n const arcLength = (Math.PI * radius * segmentSweep) / 180;\n\n for (let i = 0; i < segmentCount; i++) {\n p.addSegment(startDeg + i * segmentSweep + 90, arcLength, 1, true);\n }\n p.endPlot(startDeg + sweepDeg + 90, 1, true);\n\n const startX = x + radius * cos(startDeg);\n const startY = y - radius * sin(startDeg);\n p.draw(startX, startY, 1);\n}\n\n// Variables for managing paths and strokes\nlet _current;\nlet _curvature;\n\nclass SubPath {\n constructor() {\n this.isClosed = false;\n this.curvature = _curvature;\n this.vert = [];\n }\n /**\n * Adds a vertex to this subpath.\n * @param {number} x\n * @param {number} y\n * @param {number} pressure\n */\n vertex(x, y, pressure) {\n this.vert.push([x, y, pressure]);\n }\n /**\n * Renders the subpath by creating a spline from its vertices.\n */\n show() {\n let plot = _createSpline(this.vert, this.curvature, this.isClosed);\n plot.show();\n }\n}\n\n/**\n * Begins a new path with a specified curvature.\n * @param {number} [curvature=0] - Curvature from 0 to 1.\n */\nexport function beginShape(curvature = 0) {\n _curvature = constrain(curvature, 0, 1);\n _current = new SubPath();\n}\n\n/**\n * Adds a line segment from the current point to the given coordinates.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} [pressure=1] - Pressure value.\n */\nexport function vertex(x, y, pressure = 1) {\n if (!_current) {\n throw new Error(\n \"vertex() called outside of beginShape()/endShape(). Call beginShape() first.\",\n );\n }\n _current.vertex(x, y, pressure);\n}\n\n/**\n * Ends the current path and renders all subpaths.\n */\nexport function endShape(close = false) {\n if (!_current) {\n throw new Error(\n \"endShape() called without beginShape(). Call beginShape() first.\",\n );\n }\n if (_current.vert.length < 2) {\n throw new Error(\n \"endShape() requires at least 2 vertices. Add more with vertex().\",\n );\n }\n if (close) {\n _current.vertex(..._current.vert[0]);\n _current.isClosed = true;\n }\n _current.show();\n _current = false;\n}\n\nlet _strokeArray, _strokeOrigin;\n\n/**\n * Begins a new stroke with a given type and starting position.\n * @param {string} type - Stroke type.\n * @param {number} x - Starting x.\n * @param {number} y - Starting y.\n */\nexport function beginStroke(type, x, y) {\n if (type !== \"curve\" && type !== \"segments\") {\n throw new Error(\n `beginStroke() type must be \"curve\" or \"segments\", got \"${type}\".`,\n );\n }\n _strokeOrigin = [x, y];\n _strokeArray = new Plot(type);\n}\n\n/**\n * Adds a segment to the stroke.\n * @param {number} angle - Segment angle.\n * @param {number} length - Segment length.\n * @param {number} pressure - Segment pressure.\n */\nexport function move(angle, length, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"move() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.addSegment(angle, length, pressure);\n}\n\n/**\n * Completes and renders the stroke.\n * @param {number} angle - End angle.\n * @param {number} pressure - End pressure.\n */\nexport function endStroke(angle, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"endStroke() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.endPlot(angle, pressure);\n _strokeArray.draw(_strokeOrigin[0], _strokeOrigin[1], 1);\n _strokeArray = false;\n}\n\n/**\n * Creates and draws a spline curve from an array of points.\n * @param {Array<Array<number>>} array_points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature from 0 to 1.\n */\nexport function spline(_array_points, _curvature = 0.5) {\n if (!_array_points || _array_points.length < 2) {\n throw new Error(\n \"spline() requires at least 2 points. Each point should be [x, y, pressure].\",\n );\n }\n let p = _createSpline(_array_points, _curvature);\n p.draw();\n}\n\n/**\n * Creates a new Plot object representing a spline curve.\n *\n * For curved segments (curvature > 0) with at least 3 points available,\n * the function either treats segments as straight (if their angles match)\n * or calculates control points to compute a circular arc.\n *\n * If no curvature is specified, a simple straight segment is used.\n *\n * @param {Array<Array<number>>} points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature value between 0 and 1.\n * @param {boolean} [close=false] - Whether to close the spline.\n * @returns {Plot} - The generated Plot object.\n */\nfunction _createSpline(points, curvature = 0.5, close = false) {\n const plotType = curvature === 0 ? \"segments\" : \"curve\";\n const p = new Plot(plotType);\n const PI2 = Math.PI * 2;\n\n // If closing the spline, add the second point to the end\n if (close && curvature !== 0) {\n points.push(points[1]);\n }\n\n if (points && points.length > 0) {\n let done = 0; // Tracks excess length from previous segment\n let pep, tep, pep2; // Variables used for initial calibration\n\n for (let i = 0; i < points.length - 1; i++) {\n // For curved segments (if curvature > 0 and there is at least 3 points ahead)\n if (curvature > 0 && i < points.length - 2) {\n const p1 = points[i];\n const p2 = points[i + 1];\n const p3 = points[i + 2];\n\n const d1 = dist(p1[0], p1[1], p2[0], p2[1]);\n const d2 = dist(p2[0], p2[1], p3[0], p3[1]);\n const a1 = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n const a2 = calcAngle(p2[0], p2[1], p3[0], p3[1]);\n\n // Compute the adjustment length based on curvature\n const curvAdjust = curvature * Math.min(d1, d2, 0.5 * Math.min(d1, d2));\n const dmax = Math.max(d1, d2);\n const s1 = d1 - curvAdjust;\n const s2 = d2 - curvAdjust;\n\n if (Math.floor(a1) === Math.floor(a2)) {\n // If angles are nearly the same, treat as a straight segment\n const temp = close ? (i === 0 ? 0 : d1 - done) : d1 - done;\n const temp2 = close ? (i === 0 ? 0 : d2 - pep2) : d2;\n\n p.addSegment(a1, temp, p1[2], true);\n if (i === points.length - 3) {\n p.addSegment(a2, temp2, p2[2], true);\n }\n\n done = 0;\n if (i === 0) {\n pep = d1;\n pep2 = curvAdjust;\n tep = points[1];\n done = 0;\n }\n } else {\n // For a curved segment, compute control points and arc segment details\n const point1 = {\n x: p2[0] - curvAdjust * cos(-a1),\n y: p2[1] - curvAdjust * sin(-a1),\n };\n const point2 = {\n x: point1.x + dmax * cos(-a1 + 90),\n y: point1.y + dmax * sin(-a1 + 90),\n };\n const point3 = {\n x: p2[0] + curvAdjust * cos(-a2),\n y: p2[1] + curvAdjust * sin(-a2),\n };\n const point4 = {\n x: point3.x + dmax * cos(-a2 + 90),\n y: point3.y + dmax * sin(-a2 + 90),\n };\n\n const intPt = intersectLines(point1, point2, point3, point4, true);\n const radius = dist(point1.x, point1.y, intPt.x, intPt.y);\n const halfDist = dist(point1.x, point1.y, point3.x, point3.y) / 2;\n const arcAngle = 2 * Math.asin(halfDist / radius) * (180 / Math.PI);\n const arcLength = (PI2 * radius * arcAngle) / 360;\n\n const temp = close ? (i === 0 ? 0 : s1 - done) : s1 - done;\n const temp2 =\n i === points.length - 3 ? (close ? pep - curvAdjust : s2) : 0;\n\n p.addSegment(a1, temp, p1[2], true);\n p.addSegment(a1, isNaN(arcLength) ? 0 : arcLength, p1[2], true);\n p.addSegment(a2, temp2, p2[2], true);\n\n done = curvAdjust;\n if (i === 0) {\n pep = s1;\n pep2 = curvAdjust;\n tep = [point1.x, point1.y];\n }\n }\n\n if (i === points.length - 3) {\n p.endPlot(a2, p2[2], true);\n }\n } else if (curvature === 0) {\n // If no curvature, add a simple straight segment\n const p1 = points[i];\n const p2 = points[i + 1];\n const d = dist(p1[0], p1[1], p2[0], p2[1]);\n const a = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n\n p.addSegment(a, d, p2[2], true);\n if (i === points.length - 2) {\n p.endPlot(a, 1, true);\n }\n }\n }\n\n p.origin = close && curvature !== 0 ? tep : points[0];\n }\n\n return p;\n}\n","import { State } from \"./color.js\";\nimport { intersectLines } from \"./utils.js\";\n\n// =============================================================================\n// Section: Polygon Class\n// =============================================================================\n\n/**\n * Represents a polygon with a set of vertices and provides methods for\n * intersection, drawing, filling, and hatching.\n */\nexport class Polygon {\n /**\n * Constructs the Polygon object from an array of points.\n * @param {Array} pointsArray - An array of points, where each point is an array of two numbers [x, y].\n * @param {boolean} [useRawVertices=false] - If true, uses the raw array as vertices.\n */\n constructor(pointsArray, useRawVertices = false) {\n this.a = pointsArray;\n this.vertices = useRawVertices\n ? pointsArray\n : pointsArray.map(([x, y]) => ({ x, y }));\n this.sides = this.vertices.map((v, i, arr) => [\n v,\n arr[(i + 1) % arr.length],\n ]);\n this._intersectionCache = {}; // Cache for intersection results\n }\n\n /**\n * Intersects a given line with the polygon, returning all intersection points.\n * @param {Object} line - The line to intersect with the polygon, having two properties 'point1' and 'point2'.\n * @returns {Array} An array of intersection points (each with 'x' and 'y' properties) or an empty array if no intersections.\n */\n intersect(line) {\n // Check if the result has been cached\n const cacheKey = `${line.point1.x},${line.point1.y}-${line.point2.x},${line.point2.y}`;\n if (this._intersectionCache[cacheKey]) {\n return this._intersectionCache[cacheKey];\n }\n const points = [];\n for (const [start, end] of this.sides) {\n const intersection = intersectLines(line.point1, line.point2, start, end);\n if (intersection) points.push(intersection);\n }\n this._intersectionCache[cacheKey] = points; // Cache the result\n return points;\n }\n\n /**\n * Displays the polygon with optional stroke, hatch, and fill effects.\n */\n show() {\n if (State.wash) this.wash();\n if (State.fill) this.fill();\n if (State.mass) this.mass();\n if (State.hatch) this.hatch();\n if (State.stroke) this.draw();\n }\n}","import { Cwidth, Cheight } from \"./target.js\";\nimport { State } from \"./color.js\";\nimport { toDegrees, map, rr2 } from \"./utils.js\";\nimport { Position, isFieldReady } from \"./flowfield.js\";\nimport { Polygon } from \"./polygon.js\";\n\n// =============================================================================\n// Section: Plot Class\n// =============================================================================\n\n/**\n * The Plot class represents a collection of segments that define shapes or paths.\n * It supports operations like adding segments, calculating angles and pressures,\n * and generating polygons based on the plot's structure.\n */\nexport class Plot {\n /**\n * Creates a new Plot.\n * @param {string} _type - The type of plot, \"curve\" or \"segments\".\n */\n constructor(_type) {\n this.segments = [];\n this.angles = [];\n this.pres = [];\n this.type = _type;\n this.dir = 0;\n this.calcIndex(0);\n this.pol = false;\n }\n\n /**\n * Adds a segment to the plot with specified angle, length, and pressure.\n * @param {number} _a - The angle of the segment.\n * @param {number} _length - The length of the segment.\n * @param {number} _pres - The pressure of the segment.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n addSegment(_a = 0, _length = 0, _pres = 1, _degrees = false) {\n if (this.angles.length > 0) this.angles.pop(); // Remove the last angle\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a); // Normalize angle\n this.angles.push(_a, _a); // Push angle twice for continuity\n this.pres.push(_pres);\n this.segments.push(_length);\n this.length = this.segments.reduce((sum, len) => sum + len, 0); // Update total length\n }\n\n /**\n * Finalizes the plot by setting the last angle and pressure.\n * @param {number} _a - The final angle.\n * @param {number} _pres - The final pressure.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n endPlot(_a = 0, _pres = 1, _degrees = false) {\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a);\n this.angles[this.angles.length - 1] = _a; // Update the last angle\n this.pres.push(_pres);\n }\n\n /**\n * Rotates the entire plot by a given angle.\n * @param {number} _a - The angle to rotate the plot.\n */\n rotate(_a) {\n this.dir = toDegrees(_a);\n }\n\n /**\n * Calculates the pressure at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated pressure.\n */\n pressure(_d) {\n // If the distance exceeds the plot length, return the last pressure\n if (_d > this.length) return this.pres[this.pres.length - 1];\n // Otherwise, calculate the pressure using the curving function\n return this.curving(this.pres, _d);\n }\n\n /**\n * Calculates the angle at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The calculated angle.\n */\n angle(_d) {\n // If the distance exceeds the plot length, return the last angle\n if (_d > this.length) return this.angles[this.angles.length - 1];\n // Calculate the index for the given distance\n this.calcIndex(_d);\n // Return the angle, adjusted for the plot type and direction\n return this.type === \"curve\"\n ? this.curving(this.angles, _d) + this.dir\n : this.angles[this.index] + this.dir;\n }\n\n /**\n * Interpolates values between segments for smooth transitions.\n * @param {Array<number>} array - The array to interpolate within.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated value.\n */\n curving(array, _d) {\n let map0 = array[this.index];\n let map1 = array[this.index + 1] ?? map0;\n if (Math.abs(map1 - map0) > 180) {\n if (map1 > map0) map1 = -(360 - map1);\n else map0 = -(360 - map0);\n }\n return map(_d - this.suma, 0, this.segments[this.index], map0, map1, true);\n }\n\n /**\n * Calculates the current index of the plot based on the distance.\n * @param {number} _d - The distance along the plot.\n */\n calcIndex(_d) {\n this.index = -1;\n this.suma = 0;\n let d = 0;\n while (d <= _d) {\n this.suma = d;\n d += this.segments[this.index + 1];\n this.index++;\n }\n return this.index;\n }\n\n /**\n * Generates a polygon based on the plot.\n * @param {number} _x - The x-coordinate for the starting point.\n * @param {number} _y - The y-coordinate for the starting point.\n * @param {number} _scale - The scale factor for the polygon.\n * @param {number} _side - The side factor for the polygon.\n * @returns {Polygon} - The generated polygon.\n */\n genPol(_x, _y, _scale = 1, _side) {\n isFieldReady(); // Ensure that the drawing environment is prepared\n const step = _side < 0 ? 4 : 1;\n const vertices = [];\n const numSteps = Math.round(this.length / step);\n const pos = new Position(_x + Cwidth / 2, _y + Cheight / 2);\n let pside = 0;\n let prevIdx = 0;\n\n for (let i = 0; i < numSteps; i++) {\n pos.plotTo(this, step, step);\n const idx = this.calcIndex(pos.plotted);\n pside += step;\n let maxSize = _side <= 0 ? 8 : Math.max(this.segments[idx] * _side * rr2(0.7, 1.3), 20);\n if ((pside >= maxSize || idx >= prevIdx) && pos.x) {\n vertices.push([pos.x - Cwidth / 2, pos.y - Cheight / 2]);\n pside = 0;\n if (idx >= prevIdx) prevIdx++;\n }\n }\n return new Polygon(vertices);\n }\n\n /**\n * Displays the plot with optional stroke, hatch, and fill effects.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\n show(x, y, scale = 1) {\n if (State.wash) this.wash(x, y, scale);\n if (State.fill) this.fill(x, y, scale);\n if (State.mass) this.mass(x, y, scale);\n if (State.hatch) this.hatch(x, y, scale);\n if (State.stroke) this.draw(x, y, scale);\n }\n}\n","// =============================================================================\n// Stroke Runtime Hooks\n// =============================================================================\n\nlet strokeRuntime = {\n createTipSurface: () => {\n throw new Error(\"No stroke runtime adapter registered.\");\n },\n loadImageTip: () => {\n throw new Error(\"No stroke runtime adapter registered.\");\n },\n};\n\n/**\n * Registers or updates host stroke hooks used by brush-tip loading code.\n *\n * @param {object} hooks\n */\nexport function setStrokeRuntime(hooks) {\n strokeRuntime = { ...strokeRuntime, ...hooks };\n}\n\nexport const createTipSurface = (width, height) =>\n strokeRuntime.createTipSurface(width, height);\nexport const loadImageTip = (src, imageToWhite) =>\n strokeRuntime.loadImageTip(src, imageToWhite);\n","import * as Color from \"../core/color.js\";\nimport { createFramebuffer } from \"../core/compositor_runtime.js\";\n\nlet isStrokeCompositeRegistered = false;\nconst DIRTY_BRUSH_PADDING = 2;\n\n// =============================================================================\n// Section: Helpers\n// =============================================================================\n/**\n * Returns whether the current stroke mask framebuffer must be recreated.\n * This happens when the renderer has no mask yet, or when the canvas size or\n * pixel density changed since the last allocation.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {boolean} True when the stroke mask must be rebuilt.\n */\nfunction needsStrokeMask(Renderer, Cwidth, Cheight, Density) {\n return (\n !Renderer.glMask ||\n Renderer.glMask.width !== Cwidth ||\n Renderer.glMask.height !== Cheight ||\n (typeof Renderer.glMask.pixelDensity === \"function\" &&\n Renderer.glMask.pixelDensity() !== Density)\n );\n}\n\n// =============================================================================\n// Section: Resource Management\n// =============================================================================\n/**\n * Ensures the stroke compositor owns a framebuffer-backed mask with the current\n * canvas dimensions. Stroke stamps are rendered into this mask in WebGL before\n * being blended into the main target.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {object} The framebuffer used as stroke mask.\n */\nexport function ensureStrokeCompositeResources(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n) {\n if (needsStrokeMask(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.glMask?.remove) Renderer.glMask.remove();\n Renderer.glMask = createFramebuffer(Renderer, {\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n }\n\n Renderer.glMask.dirtyRect ??= null;\n Renderer.glMask.isDrawn ??= false;\n return Renderer.glMask;\n}\n\n// =============================================================================\n// Section: Mask Lifecycle\n// =============================================================================\n/**\n * Clears the current stroke mask and resets its bookkeeping flags.\n *\n * @param {object|null} target - Stroke mask framebuffer.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n */\nexport function clearStrokeMask(target, clearTarget) {\n if (!target) return;\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\n}\n\n// =============================================================================\n// Section: Composite Bounds\n// =============================================================================\n/**\n * Returns the rect that should be composited from the stroke mask into the\n * main canvas. Stroke bounds are normally tight dirty rects, but when drawing\n * into an active framebuffer we keep the result conservative and composite the\n * full target.\n *\n * @param {object|null} target - Stroke mask framebuffer.\n * @param {Function} getActiveFramebuffer - Returns the currently bound framebuffer.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} expandDirtyRect - Expands a rect by a constant padding.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @param {number} padding - Extra brush padding in pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\nexport function getStrokeCompositeRect(\n target,\n getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n if (getActiveFramebuffer()) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(target.dirtyRect, DIRTY_BRUSH_PADDING),\n );\n}\n\n/**\n * Returns the resource that should be bound to the blend shader's `u_mask`\n * uniform for stroke compositing.\n *\n * @param {object} _Renderer - Active host renderer.\n * @param {object} mask - Stroke mask framebuffer.\n * @returns {object} Stroke mask framebuffer.\n */\nexport function getStrokeShaderMask(_Renderer, mask) {\n return mask;\n}\n\n// =============================================================================\n// Section: Registration\n// =============================================================================\n/**\n * Registers the stroke compositor with the shared color/composite core.\n * Safe to call multiple times.\n */\nexport function initStrokeComposite() {\n if (isStrokeCompositeRegistered) return;\n Color.registerStrokeComposite?.({\n ensureResources: ensureStrokeCompositeResources,\n clearMask: clearStrokeMask,\n getCompositeRect: getStrokeCompositeRect,\n getShaderMask: getStrokeShaderMask,\n });\n isStrokeCompositeRegistered = true;\n}\n","/**\n * Compiles a shader program from the given vertex and fragment sources.\n * @param {WebGL2RenderingContext} gl - The WebGL2 context.\n * @param {string} vert - Vertex shader source.\n * @param {string} frag - Fragment shader source.\n * @returns {WebGLProgram} The compiled and linked program.\n */\nexport const createProgram = (gl, vert, frag) => {\n const p = gl.createProgram();\n for (let [t, src] of [\n [gl.VERTEX_SHADER, vert],\n [gl.FRAGMENT_SHADER, frag],\n ]) {\n const s = gl.createShader(t);\n gl.shaderSource(s, src);\n gl.compileShader(s);\n gl.attachShader(p, s);\n }\n gl.linkProgram(p);\n return p;\n};\n","// =============================================================================\n// Renderer Runtime Hooks\n// =============================================================================\n\n/**\n * Direct-render hooks used by modules that issue raw WebGL commands.\n *\n * These hooks are intentionally narrow:\n * - begin drawing into an offscreen GL mask target\n * - restore the previous draw target afterward\n * - reset any host-side shader/program bookkeeping after direct GL usage\n */\n\nlet rendererRuntime = {\n beginDirectMaskDraw: () => {\n throw new Error(\"No renderer runtime adapter registered.\");\n },\n endDirectMaskDraw: () => {\n throw new Error(\"No renderer runtime adapter registered.\");\n },\n resetDirectShaderTracking: () => {},\n};\n\n/**\n * Registers or updates host renderer hooks used by direct WebGL drawing paths.\n *\n * @param {object} hooks\n */\nexport function setRendererRuntime(hooks) {\n rendererRuntime = { ...rendererRuntime, ...hooks };\n}\n\nexport const beginDirectMaskDraw = (renderer, gl, target) =>\n rendererRuntime.beginDirectMaskDraw(renderer, gl, target);\nexport const endDirectMaskDraw = (renderer, gl, state) =>\n rendererRuntime.endDirectMaskDraw(renderer, gl, state);\nexport const resetDirectShaderTracking = (renderer, gl) =>\n rendererRuntime.resetDirectShaderTracking(renderer, gl);\n","// =============================================================================\n// Module: GL Draw\n// =============================================================================\n/**\n * The GL Draw module batches brush primitives for WebGL2 rendering. It initializes\n * the shader programs and buffers used by circle-based brushes and image-tip brushes,\n * then flushes those queues into the shared framebuffer-backed brush mask.\n */\n\nimport { Cwidth, Cheight, Density, Renderer } from \"../core/target.js\";\nimport {\n Mix,\n isMixReady,\n State,\n} from \"../core/color.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport {\n beginDirectMaskDraw,\n endDirectMaskDraw,\n resetDirectShaderTracking,\n} from \"../core/renderer_runtime.js\";\nimport { getAffineMatrix } from \"../core/runtime.js\";\nimport vertSrc from \"./shader.vert\";\nimport fragSrc from \"./shader.frag\";\nimport imgVertSrc from \"./image.vert\";\nimport imgFragSrc from \"./image.frag\";\n\n// =============================================================================\n// Section: Initialization and Setup\n// =============================================================================\n\n// Module state\nlet isLoaded = false,\n gl,\n framebufferProjMatrix,\n vao,\n buf,\n program;\nlet loadedWidth = 0,\n loadedHeight = 0;\nlet brushMaskTarget = null;\nconst Attr = {},\n Frag = {};\n\n// Cached matrix values — snapshotted once per stroke in snapshotMatrix()\nlet _ma = 1,\n _mb = 0,\n _mc = 0,\n _md = 1,\n _mx = 0,\n _my = 0,\n _halfW = 0,\n _halfH = 0,\n _scale = 1,\n _density = 1;\n\n/**\n * Snapshots the current runtime affine transform. Call once at the start of each stroke.\n */\nexport function snapshotMatrix() {\n const m = getAffineMatrix();\n _ma = m.a;\n _mb = m.b;\n _mc = m.c;\n _md = m.d;\n _mx = m.x;\n _my = m.y;\n _halfW = Cwidth / 2;\n _halfH = Cheight / 2;\n _scale = Math.sqrt(_ma * _ma + _mb * _mb);\n _density = Density;\n}\n\n// Pre-allocated flat buffer for circle data (x, y, radius, alpha per circle)\nconst INITIAL_CAPACITY = 2048;\nlet circleData = new Float32Array(INITIAL_CAPACITY * 4);\nlet circleCount = 0;\nlet bufferCapacity = INITIAL_CAPACITY;\nlet gpuBufferSize = INITIAL_CAPACITY * 4 * 4; // bytes allocated on GPU\nlet circleDirtyRect = null;\n\n// ---------------------------------------------------------------------------\n// Image instancing state\n// ---------------------------------------------------------------------------\nlet imgProgram = null;\nlet imgVao = null;\nlet imgCornerBuf = null;\nlet imgInstanceBuf = null;\nconst imgAttr = {};\nconst imgFrag = {};\nlet imgGpuSize = 0;\n\nconst IMG_FLOATS = 5; // screenX, screenY, halfSize, angle, alpha — per stamp\nconst IMG_INIT_CAP = 256;\nlet imgData = new Float32Array(IMG_INIT_CAP * IMG_FLOATS);\nlet imgCount = 0;\nlet imgCapacity = IMG_INIT_CAP;\nlet imgDirtyRect = null;\n\n// Texture cache: src string → WebGLTexture (cleared whenever the GL context changes)\nconst texCache = new Map();\n\n// Static unit-quad corners for gl.TRIANGLE_STRIP in quad-local space.\nconst QUAD_CORNERS = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]);\n\nfunction ensureBrushMaskTarget() {\n const rendererMask = Renderer?.glMask;\n if (!rendererMask) return null;\n brushMaskTarget = rendererMask;\n brushMaskTarget.dirtyRect ??= null;\n brushMaskTarget.isDrawn ??= false;\n Mix.glMask = brushMaskTarget;\n return brushMaskTarget;\n}\n\nfunction getProjectionMatrix() {\n return framebufferProjMatrix;\n}\n\nfunction beginMaskTarget() {\n return beginDirectMaskDraw(Renderer, gl, Mix.glMask);\n}\n\nfunction endMaskTarget(state) {\n endDirectMaskDraw(Renderer, gl, state);\n}\n\nfunction accumulateDirtyRect(currentRect, minX, minY, maxX, maxY) {\n if (!currentRect) return { minX, minY, maxX, maxY };\n if (minX < currentRect.minX) currentRect.minX = minX;\n if (minY < currentRect.minY) currentRect.minY = minY;\n if (maxX > currentRect.maxX) currentRect.maxX = maxX;\n if (maxY > currentRect.maxY) currentRect.maxY = maxY;\n return currentRect;\n}\n\n/**\n * Initializes WebGL objects if not done already.\n */\nexport function isReady() {\n isMixReady();\n ensureBrushMaskTarget();\n\n const nextGl = Renderer.drawingContext;\n const needsContextRefresh = !isLoaded || gl !== nextGl;\n const needsProjectionRefresh =\n needsContextRefresh || loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (needsProjectionRefresh) {\n framebufferProjMatrix = new Float32Array([\n 2 / Cwidth,\n 0,\n 0,\n 0,\n 0,\n 2 / Cheight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n -1,\n 0,\n 1,\n ]);\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n }\n\n if (!needsContextRefresh) return;\n\n gl = nextGl;\n\n // Create shader program and initialize\n program = createProgram(gl, vertSrc, fragSrc);\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n // Cache attribute and uniform locations\n [\"a_position\", \"a_radius\", \"a_alpha\"].forEach(\n (n) => (Attr[n] = gl.getAttribLocation(program, n)),\n );\n [\"u_matrix\", \"u_color\"].forEach(\n (n) => (Frag[n] = gl.getUniformLocation(program, n)),\n );\n\n // Create persistent VAO and VBO\n vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n\n buf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n gl.bufferData(gl.ARRAY_BUFFER, circleData.byteLength, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n\n // Set up vertex attributes (only needs to happen once with persistent VAO)\n const stride = 16; // 4 floats × 4 bytes\n gl.enableVertexAttribArray(Attr.a_position);\n gl.vertexAttribPointer(Attr.a_position, 2, gl.FLOAT, false, stride, 0);\n gl.enableVertexAttribArray(Attr.a_radius);\n gl.vertexAttribPointer(Attr.a_radius, 1, gl.FLOAT, false, stride, 8);\n gl.enableVertexAttribArray(Attr.a_alpha);\n gl.vertexAttribPointer(Attr.a_alpha, 1, gl.FLOAT, false, stride, 12);\n\n gl.bindVertexArray(null);\n\n // ------------------------------------------------------------------\n // Image-tip instancing program\n // ------------------------------------------------------------------\n texCache.clear();\n\n imgProgram = createProgram(gl, imgVertSrc, imgFragSrc);\n [\"a_corner\", \"a_pos\", \"a_size\", \"a_angle\", \"a_alpha\"].forEach(\n (n) => (imgAttr[n] = gl.getAttribLocation(imgProgram, n)),\n );\n [\"u_proj\", \"u_color\", \"u_tex\"].forEach(\n (n) => (imgFrag[n] = gl.getUniformLocation(imgProgram, n)),\n );\n\n imgVao = gl.createVertexArray();\n gl.bindVertexArray(imgVao);\n\n // Static corner VBO (per-vertex, no divisor)\n imgCornerBuf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, imgCornerBuf);\n gl.bufferData(gl.ARRAY_BUFFER, QUAD_CORNERS, gl.STATIC_DRAW);\n gl.enableVertexAttribArray(imgAttr.a_corner);\n gl.vertexAttribPointer(imgAttr.a_corner, 2, gl.FLOAT, false, 0, 0);\n\n // Instance data VBO (per-instance)\n imgInstanceBuf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, imgInstanceBuf);\n gl.bufferData(gl.ARRAY_BUFFER, imgData.byteLength, gl.DYNAMIC_DRAW);\n imgGpuSize = imgData.byteLength;\n\n const istride = IMG_FLOATS * 4; // 20 bytes\n gl.enableVertexAttribArray(imgAttr.a_pos);\n gl.vertexAttribPointer(imgAttr.a_pos, 2, gl.FLOAT, false, istride, 0);\n gl.vertexAttribDivisor(imgAttr.a_pos, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_size);\n gl.vertexAttribPointer(imgAttr.a_size, 1, gl.FLOAT, false, istride, 8);\n gl.vertexAttribDivisor(imgAttr.a_size, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_angle);\n gl.vertexAttribPointer(imgAttr.a_angle, 1, gl.FLOAT, false, istride, 12);\n gl.vertexAttribDivisor(imgAttr.a_angle, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_alpha);\n gl.vertexAttribPointer(imgAttr.a_alpha, 1, gl.FLOAT, false, istride, 16);\n gl.vertexAttribDivisor(imgAttr.a_alpha, 1);\n\n gl.bindVertexArray(null);\n\n isLoaded = true;\n}\n\n// =============================================================================\n// Section: Drawing Primitives\n// =============================================================================\n\n/**\n * Queue a circle to be drawn with the specified parameters.\n * Data is written directly into a flat Float32Array to avoid object allocation.\n * Applies the full 2D affine transform (rotation + scale + translation) from\n * the current runtime transform so that brush.rotate() and brush.scale() work correctly.\n */\nexport function circle(x, y, diameter, alpha) {\n // Grow buffer if needed\n if (circleCount >= bufferCapacity) {\n bufferCapacity *= 2;\n const newData = new Float32Array(bufferCapacity * 4);\n newData.set(circleData);\n circleData = newData;\n }\n\n // x/y arrive in \"position space\": user coords + (Cwidth/2, Cheight/2).\n // Subtract the offset to recover user coords, apply the full matrix, then re-add\n // the offset so the result is in screen pixel space [0..Cwidth, 0..Cheight].\n const px = x - _halfW;\n const py = y - _halfH;\n\n const offset = circleCount * 4;\n const screenX = _ma * px + _mc * py + _mx + _halfW;\n const screenY = _mb * px + _md * py + _my + _halfH;\n const radius = (_density * diameter * _scale) / 2;\n\n circleData[offset] = screenX;\n circleData[offset + 1] = screenY;\n // Scale the diameter by the matrix's scale factor (length of the transformed x-axis)\n circleData[offset + 2] = radius;\n circleData[offset + 3] = alpha / 255;\n\n const dScreenX = screenX * _density;\n const dScreenY = screenY * _density;\n circleDirtyRect = accumulateDirtyRect(\n circleDirtyRect,\n dScreenX - radius - 1,\n dScreenY - radius - 1,\n dScreenX + radius + 1,\n dScreenY + radius + 1,\n );\n\n circleCount++;\n}\n\n/**\n * Queue an image stamp to be drawn with instanced rendering.\n * Accepts the same coordinate conventions as circle(): x/y in position space\n * (user coords + Cwidth/2, Cheight/2), size in user-coord units, alpha in [0..255].\n * @param {number} x - X in position space.\n * @param {number} y - Y in position space.\n * @param {number} size - Full stamp diameter in user-coord units.\n * @param {number} angle - Rotation in radians.\n * @param {number} alpha - Opacity [0..255].\n * @param {number} [extraPadding=0] - Conservative extra padding in user units.\n */\nexport function stampImage(x, y, size, angle, alpha, extraPadding = 0) {\n if (imgCount >= imgCapacity) {\n imgCapacity *= 2;\n const next = new Float32Array(imgCapacity * IMG_FLOATS);\n next.set(imgData);\n imgData = next;\n }\n\n const px = x - _halfW;\n const py = y - _halfH;\n const screenX = _ma * px + _mc * py + _mx + _halfW;\n const screenY = _mb * px + _md * py + _my + _halfH;\n const halfSize = (_density * size * _scale) / 2;\n const extraRadius = _density * extraPadding * _scale;\n\n const base = imgCount * IMG_FLOATS;\n imgData[base] = screenX;\n imgData[base + 1] = screenY;\n imgData[base + 2] = halfSize;\n imgData[base + 3] = angle;\n imgData[base + 4] = alpha / 255;\n\n // Bounding box: rotated square worst-case = circle of radius halfSize * √2\n const dScreenX = screenX * _density;\n const dScreenY = screenY * _density;\n const boundsRadius = halfSize * 1.42 + extraRadius;\n imgDirtyRect = accumulateDirtyRect(\n imgDirtyRect,\n dScreenX - boundsRadius - 1,\n dScreenY - boundsRadius - 1,\n dScreenX + boundsRadius + 1,\n dScreenY + boundsRadius + 1,\n );\n\n imgCount++;\n}\n\n/**\n * Flush all queued image stamps in a single instanced draw call.\n * @param {object} p5img - The preprocessed brush-tip image/canvas (from T.tips).\n * @param {string} src - The image src string, used as the texture cache key.\n */\nexport function glDrawImages(p5img, src) {\n if (imgCount === 0) return;\n\n Mix.glMask.isDrawn = true;\n const targetState = beginMaskTarget();\n\n // Lazy-create the WebGL texture from the tip canvas on first use.\n let tex = texCache.get(src);\n if (!tex) {\n tex = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, p5img.canvas);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n texCache.set(src, tex);\n }\n\n gl.useProgram(imgProgram);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.uniform1i(imgFrag.u_tex, 0);\n\n const color = State.stroke.color._array;\n gl.uniform4f(imgFrag.u_color, ...color);\n gl.uniformMatrix4fv(imgFrag.u_proj, false, getProjectionMatrix());\n\n gl.bindVertexArray(imgVao);\n gl.bindBuffer(gl.ARRAY_BUFFER, imgInstanceBuf);\n\n const byteCount = imgCount * IMG_FLOATS * 4;\n const dataView = imgData.subarray(0, imgCount * IMG_FLOATS);\n if (byteCount > imgGpuSize) {\n gl.bufferData(gl.ARRAY_BUFFER, imgData, gl.DYNAMIC_DRAW);\n imgGpuSize = imgData.byteLength;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);\n }\n\n gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, imgCount);\n\n gl.bindVertexArray(null);\n gl.bindTexture(gl.TEXTURE_2D, null);\n endMaskTarget(targetState);\n\n if (imgDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, imgDirtyRect);\n imgDirtyRect = null;\n }\n\n imgCount = 0;\n\n // Let the host adapter know we changed the active program.\n resetDirectShaderTracking(Renderer, gl);\n}\n\n/**\n * Removes a cached GL texture by key, forcing re-upload on next draw.\n * Call this when a custom tip function changes after brush.add().\n */\nexport function invalidateTexEntry(key) {\n const tex = texCache.get(key);\n if (tex && gl) gl.deleteTexture(tex);\n texCache.delete(key);\n}\n\n/**\n * Draw all queued circles using WebGL\n */\nexport function glDraw() {\n if (circleCount === 0) return;\n\n Mix.glMask.isDrawn = true;\n const targetState = beginMaskTarget();\n\n const color = State.stroke.color._array;\n\n // Re-activate our shader in case host drawing switched programs.\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n gl.bindVertexArray(vao);\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n\n // Upload vertex data — reallocate GPU buffer only if needed\n const byteCount = circleCount * 16; // 4 floats × 4 bytes\n const dataView = circleData.subarray(0, circleCount * 4);\n if (byteCount > gpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, circleData, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);\n }\n\n // Set uniforms and draw\n gl.uniform4f(Frag.u_color, ...color);\n gl.uniformMatrix4fv(Frag.u_matrix, false, getProjectionMatrix());\n gl.drawArrays(gl.POINTS, 0, circleCount);\n\n gl.bindVertexArray(null);\n endMaskTarget(targetState);\n\n if (circleDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, circleDirtyRect);\n circleDirtyRect = null;\n }\n\n // Reset queue (no deallocation)\n circleCount = 0;\n\n // We called gl.useProgram() directly, bypassing host shader tracking.\n // Reset it so the host is forced to re-activate its own shader next time\n // it draws — otherwise it may skip gl.useProgram() and set uniforms on the\n // wrong active program, causing \"location is not from the associated program\".\n resetDirectShaderTracking(Renderer, gl);\n}\n","// =============================================================================\n// Module: Brush\n// =============================================================================\n/**\n * The Brush module provides a comprehensive set of functions and classes for\n * simulating various drawing tools ranging from pens, markers, pencils, to\n * custom image-based brushes. This module controls brush properties such as\n * weight, color, vibration, and spacing, and manages the drawing process through\n * stateful methods that enable features like pressure sensitivity, clipping, and\n * blending. By supporting multiple brush types and dynamic parameter adjustments,\n * the Brush module facilitates the creation of realistic and expressive stroke effects.\n */\n\n// Core imports\nimport { Cwidth, Cheight, Renderer, isCanvasReady } from \"../core/target.js\";\nimport {\n Mix,\n State,\n} from \"../core/color.js\";\nimport {\n rr,\n map,\n dist,\n randInt,\n calcAngle,\n toDegrees,\n gaussian,\n rArray,\n noise,\n _onSeed, \n cos,\n sin\n} from \"../core/utils.js\";\nimport { createColor } from \"../core/runtime.js\";\nimport { Position, isFieldReady } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { createTipSurface, loadImageTip } from \"./runtime.js\";\n\n// Internal module imports\nimport { initStrokeComposite } from \"./composite.js\";\nimport {\n isReady,\n glDraw,\n glDrawImages,\n circle,\n stampImage,\n invalidateTexEntry,\n snapshotMatrix,\n} from \"./gl_draw.js\";\n\ninitStrokeComposite(); // Register the stroke composite system for offscreen mask rendering and compositing.\n\n// ---------------------------------------------------------------------------\n// Brush State and Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Global stroke state settings.\n */\nState.stroke = {\n color: null,\n weight: 1,\n type: \"HB\",\n isActive: false,\n opacity: 1,\n};\n\nlet list = new Map();\n\nconst DEFAULT_CUSTOM_PRESSURE_VARIATION = {\n offset: 0.08,\n scale: 0.08,\n warp: 0.06,\n tilt: 0.06,\n};\n\n/**\n * Retrieves a shallow copy of the current stroke state.\n * @returns {object} The stroke state.\n */\nexport function BrushState() {\n return { ...State.stroke };\n}\n\n/**\n * Updates the stroke state.\n * @param {object} state - The new stroke state.\n */\nexport function BrushSetState(state) {\n State.stroke = { ...state };\n}\n\n// =============================================================================\n// Section: Brush Manager\n// =============================================================================\n\n/**\n * Adds a new brush with the specified parameters to the brush list.\n * @param {string} name - The unique name for the new brush.\n * @param {object} params - The parameters defining the brush behavior and appearance.\n */\n/**\n * Normalizes the pressure parameter to the internal { type, min_max, curve } format.\n * Accepts:\n * [start, end] — linear ramp between two pressure values\n * [start, mid, end] — piecewise linear (e.g. [1.5, 0.5, 1.5] for U-curve)\n * (t) => value — custom function, t ∈ [0,1], return value ∈ [0,1]\n * { mode: \"gaussian\", curve, min_max } — advanced built-in pressure profile\n * { curve, min_max } — legacy gaussian format, preserved for compatibility\n */\nexport function normalizePressure(p) {\n if (!p) return p;\n if (typeof p === \"function\")\n return {\n type: \"custom\",\n min_max: [0, 1],\n curve: p,\n variation: { ...DEFAULT_CUSTOM_PRESSURE_VARIATION },\n };\n if (typeof p === \"object\" && !Array.isArray(p)) {\n if (p.type === \"custom\" || p.mode === \"custom\") {\n const { mode, ...rest } = p;\n return {\n ...rest,\n type: \"custom\",\n variation: {\n ...DEFAULT_CUSTOM_PRESSURE_VARIATION,\n ...(rest.variation ?? {}),\n },\n };\n }\n if (\n p.type === \"gaussian\" ||\n p.mode === \"gaussian\" ||\n (Array.isArray(p.curve) && Array.isArray(p.min_max))\n ) {\n return {\n ...p,\n type: \"gaussian\",\n curve: p.curve,\n min_max: p.min_max,\n };\n }\n return p;\n }\n if (Array.isArray(p)) {\n const [s, m, e] = p.length === 2 ? [p[0], (p[0] + p[1]) / 2, p[1]] : p;\n const min = Math.min(s, m, e),\n max = Math.max(s, m, e);\n const range = max - min || 1;\n const [ns, nm, ne] = [\n (s - min) / range,\n (m - min) / range,\n (e - min) / range,\n ];\n return {\n type: \"custom\",\n min_max: [min, max],\n variation: { ...DEFAULT_CUSTOM_PRESSURE_VARIATION },\n curve: (t) =>\n t < 0.5 ? ns + (nm - ns) * t * 2 : nm + (ne - nm) * (t - 0.5) * 2,\n };\n }\n}\n\nexport function add(name, params) {\n const validTypes = [\"marker\", \"custom\", \"image\", \"spray\"];\n params.type = validTypes.includes(params.type) ? params.type : \"default\";\n if (params.markerTip === undefined) params.markerTip = true;\n if (params.noise === undefined) params.noise = 0.3;\n params.noise = Math.max(0, Math.min(1, params.noise));\n // Accept legacy param names for backward compatibility\n if (params.vibration !== undefined && params.scatter === undefined)\n params.scatter = params.vibration;\n if (params.definition !== undefined && params.sharpness === undefined)\n params.sharpness = params.definition;\n if (params.quality !== undefined && params.grain === undefined)\n params.grain = params.quality;\n params.pressure = normalizePressure(params.pressure);\n if (params.type === \"custom\") {\n if (typeof params.tip !== \"function\") {\n throw new Error(`Brush \"${name}\" is type \"custom\" but is missing a tip function.`);\n }\n // Rasterise the tip once into a 500×500 P2D buffer.\n // Users draw in a 100×100 coordinate space (origin at centre);\n // dark fills/strokes → high opacity, light/white → transparent.\n const key = `custom::${name}`;\n invalidateTexEntry(key); // discard stale GPU texture if tip changed\n const g = createTipSurface(500, 500);\n g.pixelDensity(1);\n g.background(255);\n g.noSmooth();\n g.push();\n g.translate(250, 250); // centre origin\n g.scale(5); // 100 user units → 500 px\n g.noStroke();\n params.tip(g);\n g.pop();\n T.imageToWhite(g); // dark → high alpha, RGB → white for tint\n T.tips.set(key, g);\n params.tipKey = key;\n list.set(name, { param: params, colors: [], buffers: [] });\n return;\n }\n if (params.type === \"image\") {\n if (!params.image || !params.image.src) {\n throw new Error(\n `Brush \"${name}\" is type \"image\" but is missing params.image.src. Example: image: { src: \"./tip.jpg\" }`,\n );\n }\n T.add(params.image.src);\n list.set(name, { param: params, colors: [], buffers: [] });\n return T.load(); // returns a Promise; only loads images not yet loaded\n }\n list.set(name, { param: params, colors: [], buffers: [] });\n}\n\n/**\n * Retrieves the list of available brush names.\n * @returns {Array<string>} Array of brush names.\n */\nexport function box() {\n return [...list.keys()];\n}\n\nexport function getBrushParams(brushName) {\n return list.get(brushName)?.param ?? null;\n}\n\n/**\n * Scales standard brush parameters by the provided factor.\n * @param {number} scaleFactor - The scaling factor to apply.\n */\nexport function scaleBrushes(scaleFactor) {\n for (const { param } of list.values()) {\n if (param) {\n param.weight *= scaleFactor;\n param.scatter *= scaleFactor;\n param.spacing *= scaleFactor;\n }\n }\n}\n\n/**\n * Sets the current brush type by name.\n * @param {string} brushName - The name of the brush.\n */\nexport function pick(brushName) {\n if (!list.has(brushName)) {\n throw new Error(\n `Brush \"${brushName}\" not found. Available brushes: ${[...list.keys()].join(\", \")}.`,\n );\n }\n State.stroke.type = brushName;\n}\n\n/**\n * Sets the stroke style (color) for the current brush.\n * @param {number|string|Color} r - Red component, CSS color string, or Color object.\n * @param {number} [g] - Green component.\n * @param {number} [b] - Blue component.\n */\nexport function stroke(r, g, b) {\n isCanvasReady();\n State.stroke.color = createColor(...arguments);\n State.stroke.isActive = true;\n}\n\n/**\n * Sets the brush weight (thickness).\n * @param {number} weight - The weight value.\n */\nexport function strokeWeight(weight) {\n State.stroke.weight = weight;\n}\n\n/**\n * Sets the current brush with name, color, and weight.\n * @param {string} brushName - The brush name.\n * @param {string|Color} color - The brush color.\n * @param {number} [weight=1] - The brush weight.\n */\nexport function set(brushName, color, weight = 1) {\n pick(brushName);\n stroke(color);\n strokeWeight(weight);\n}\n\n/**\n * Disables the stroke effect.\n */\nexport function noStroke() {\n State.stroke.isActive = false;\n}\n\n/**\n * Defines a clipping region for strokes.\n * The region uses the same coordinate space as brush drawing commands,\n * with the current runtime transform captured at call time.\n * @param {number[]} region - Array as [x1, y1, x2, y2] defining the clipping region.\n */\nexport function clip(region) {\n isCanvasReady();\n return region;\n}\n\n/**\n * Disables the clipping region.\n */\nexport function noClip() {\n return;\n}\n\n// ---------------------------------------------------------------------------\n// Drawing Variables and Functions\n// ---------------------------------------------------------------------------\nlet _position, _length, _plot, _dir;\nlet _cachedPlotAngle = 0;\nconst current = {};\n\n/**\n * Initializes the drawing state.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of stroke.\n * @param {Plot|false} [plot=false] - Plot object for path-following strokes.\n */\nfunction initializeDrawingState(x, y, length, plot = false) {\n snapshotMatrix();\n _position = new Position(x + Cwidth / 2, y + Cheight / 2);\n _length = length;\n _plot = plot;\n if (_plot) _plot.calcIndex(0);\n}\n\nconst gaussians = [];\n\n_onSeed(() => {\n gaussians.length = 0;\n});\n\n/**\n * Executes the drawing operation.\n * @param {number} angleScale - Angle (in degrees) or scaling factor.\n * @param {boolean} isPlot - True if plotting a shape.\n */\nfunction draw(angleScale, isPlot) {\n if (!isPlot) _dir = angleScale;\n saveState();\n\n const stepSize = spacing();\n const totalSteps = Math.round(\n (_length * (isPlot ? angleScale : 1)) / stepSize,\n );\n current.pressureCount = 10;\n current.cachedPressure = undefined;\n current.lineNoiseCount = 5;\n current.cachedLineNoise = undefined;\n\n const neededGaussians = totalSteps * 2;\n while (gaussians.length < neededGaussians) {\n gaussians.push(gaussian());\n }\n\n for (let i = 0; i < totalSteps; i++) {\n if (isPlot) _cachedPlotAngle = _plot.angle(_position.plotted);\n tip();\n if (isPlot) {\n _position.plotTo(_plot, stepSize, stepSize, angleScale, _cachedPlotAngle);\n } else {\n _position._moveToDegrees(angleScale, stepSize, stepSize);\n }\n }\n restoreState();\n}\n\n/**\n * Prepares the environment for a brush stroke.\n */\nfunction saveState() {\n current.seed = rr() * 999999;\n const { param } = list.get(State.stroke.type) ?? {};\n if (!param) return;\n current.p = param;\n\n // Set pressure values for the stroke\n const { pressure } = param;\n current.isCustomPressure = pressure.type === \"custom\";\n current.a = !current.isCustomPressure ? rr(-1, 1) : 0;\n current.b = !current.isCustomPressure ? rr(1, 1.5) : 0;\n if (!current.isCustomPressure) {\n current.cp = rr(3, 3.5);\n current.ct = 0;\n current.cs = 1;\n current.ck = 0;\n } else {\n const variation = pressure.variation ?? DEFAULT_CUSTOM_PRESSURE_VARIATION;\n current.cp = rr(-variation.offset, variation.offset);\n current.ct = rr(-variation.warp, variation.warp);\n current.cs = rr(1 - variation.scale, 1 + variation.scale);\n current.ck = rr(-variation.tilt, variation.tilt);\n }\n [current.min, current.max] = pressure.min_max;\n\n current.noiseoffset = 0.05 * current.p.noise;\n\n // Cache stroke direction for direction-aware dispersion (non-plot strokes only)\n if (!_plot) {\n current.cos = cos(_dir);\n current.sin = sin(_dir);\n }\n\n // Ensure GL is ready and blend state\n isReady();\n const switchingToBrush = Mix.isBrush !== true;\n Mix.isBrush = true;\n if (switchingToBrush) Mix.justChanged = true;\n Mix.blend(State.stroke.color);\n\n // Set additional state values\n current.alpha = calculateAlpha();\n current.overscan = getImageTipOverscan();\n current.drawFn =\n current.p.type === \"spray\" ? drawSpray :\n current.p.type === \"marker\" ? drawMarker :\n (current.p.type === \"custom\" || current.p.type === \"image\") ? drawImageTip :\n drawDefault;\n\n markerTip();\n}\n\n/**\n * Restores drawing state after completing a stroke.\n */\nfunction restoreState() {\n markerTip();\n glDraw();\n const type = current.p?.type;\n if (type === \"image\") glDrawImages(T.tips.get(current.p.image.src), current.p.image.src);\n else if (type === \"custom\") glDrawImages(T.tips.get(current.p.tipKey), current.p.tipKey);\n}\n\n/**\n * Renders the brush tip based on current pressure and position.\n */\nfunction tip() {\n const pressure = calculatePressure();\n const lineNoise = calculateLineNoise();\n\n if (lineNoise > rr(1,1.02) && rr(0,1) < 0.7) return;\n current.drawFn(pressure * lineNoise);\n}\n\n/**\n * Calculates the effective brush pressure.\n * @returns {number} The calculated pressure.\n */\nfunction calculatePressure() {\n if (current.pressureCount >= 10 || current.cachedPressure === undefined) {\n current.cachedPressure = _plot\n ? simPressure() * _plot.pressure(_position.plotted)\n : simPressure();\n current.pressureCount = 0;\n }\n current.pressureCount++;\n return current.cachedPressure;\n}\n\nfunction calculateLineNoise() {\n if (current.lineNoiseCount >= 10 || current.cachedLineNoise === undefined) {\n current.cachedLineNoise = map(\n noise(current.seed + _position.plotted * 0.01, 0),\n -1,\n 1,\n 1 - current.noiseoffset,\n 1 + current.noiseoffset,\n );\n current.lineNoiseCount = 0;\n }\n current.lineNoiseCount++;\n return current.cachedLineNoise;\n}\n\n/**\n * Simulates brush pressure based on stroke parameters.\n * @returns {number} Simulated pressure value.\n */\nfunction simPressure() {\n if (!current.isCustomPressure) return gauss();\n const t = _position.plotted / _length;\n return map(\n current.p.pressure.curve(\n Math.max(0, Math.min(1, 0.5 + (t - 0.5 + current.ct) * current.cs)),\n ) +\n current.cp +\n current.ck * (t - 0.5),\n 0,\n 1,\n current.min,\n current.max,\n true,\n );\n}\n\n/**\n * Generates a Gaussian-based pressure value.\n * @param {number} [a] - Center parameter.\n * @param {number} [b] - Width parameter.\n * @param {number} [c] - Shape parameter.\n * @param {number} [min] - Minimum pressure.\n * @param {number} [max] - Maximum pressure.\n * @returns {number} Gaussian pressure value.\n */\nfunction gauss(\n a = 0.5 + current.p.pressure.curve[0] * current.a,\n b = 1 - current.p.pressure.curve[1] * current.b,\n c = current.cp,\n min = current.min,\n max = current.max,\n) {\n const peakPos = a * _length;\n const halfWidth =\n (_position.plotted < peakPos ? b * 1.2 : b * 0.8) * (_length / 2);\n return map(\n 1 /\n (1 +\n Math.pow(Math.abs((_position.plotted - peakPos) / halfWidth), 2 * c)),\n 0,\n 1,\n min,\n max,\n );\n}\n\n/**\n * Calculates the alpha (opacity) level for a brush stroke.\n * @returns {number} The calculated opacity.\n */\nfunction calculateAlpha() {\n return [\"default\", \"spray\"].includes(current.p.type)\n ? current.p.opacity\n : current.p.opacity / Math.min(State.stroke.weight, 1.3);\n}\n\n/**\n * Calculates the step spacing based on the current brush parameters.\n * @returns {number} The spacing value.\n */\nfunction spacing() {\n return current.p?.spacing ?? 1;\n}\n\nfunction getImageTipOverscan() {\n const maxPressure = Math.max(1, current.max ?? 1);\n const scatterReach = State.stroke.weight * current.p.scatter;\n const tipReach = State.stroke.weight * current.p.weight * maxPressure;\n\n // Custom/image tips can extend beyond their nominal square because the tip\n // drawing itself may be large and because high scatter creates sparse large\n // stamps near the edge. Keep culling/dirty tracking conservative.\n return Math.max(8, scatterReach * 1.5 + tipReach * 0.75);\n}\n\n// ---------------------------------------------------------------------------\n// Brush Tip Rendering Methods\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the spray tip effect.\n * @param {number} pressure - Current pressure.\n */\nfunction drawSpray(pressure) {\n const vibration =\n State.stroke.weight * current.p.scatter * pressure +\n (State.stroke.weight * rArray(gaussians) * current.p.scatter) / 3;\n const sw = current.p.weight * rr(0.9, 1.1);\n const iterations = Math.ceil(current.p.grain / pressure);\n for (let j = 0; j < iterations; j++) {\n const r = rr(0.9, 1.1);\n const rX = r * vibration * rr(-1, 1);\n const yRandomFactor = rr(-1, 1);\n const sqrtPart = Math.sqrt((r * vibration) ** 2 - rX ** 2);\n circle(\n _position.x + rX,\n _position.y + yRandomFactor * sqrtPart,\n sw,\n current.alpha,\n );\n }\n}\n\n/**\n * Draws the marker tip effect.\n * @param {number} pressure - Current pressure.\n * @param {boolean} [vibrate=true] - Whether to apply vibration.\n */\nfunction drawMarker(pressure, vibrate = true, alpha = current.alpha) {\n const vibration = vibrate ? State.stroke.weight * current.p.scatter : 0;\n const rx = vibrate ? vibration * rr(-1, 1) : 0;\n const ry = vibrate ? vibration * rr(-1, 1) : 0;\n circle(\n _position.x + rx,\n _position.y + ry,\n State.stroke.weight * current.p.weight * pressure,\n alpha * Math.max(0.8, pressure) * rr(0.9,1.1),\n );\n}\n\n/**\n * Queues a stamp for instanced GL rendering.\n * Handles both \"image\" and \"custom\" tip types.\n * @param {number} pressure - Current pressure.\n * @param {number} alpha - Opacity [0..255].\n */\nfunction drawImageTip(pressure, alpha = current.alpha) {\n const vibration = State.stroke.weight * current.p.scatter;\n const rx = vibration * rr(-1, 1);\n const ry = vibration * rr(-1, 1);\n const size = current.p.weight * State.stroke.weight * pressure;\n const overscan = current.overscan;\n let angle = 0;\n if (current.p.rotate === \"random\") {\n angle = randInt(0, 360) * (Math.PI / 180);\n } else if (current.p.rotate === \"natural\") {\n angle = ((_plot ? -_cachedPlotAngle : -_dir) + _position.angle()) * (Math.PI / 180);\n }\n stampImage(\n _position.x + rx,\n _position.y + ry,\n size,\n angle,\n alpha * Math.max(0.8, pressure) * rr(0.9, 1.1),\n overscan,\n );\n}\n\n/**\n * Draws the default brush tip.\n * @param {number} pressure - Current pressure.\n */\nfunction drawDefault(pressure, wiggle = 1) {\n wiggle = map(wiggle, 0, 1, 0.9, 1.05);\n const vibration =\n wiggle *\n State.stroke.weight *\n current.p.scatter *\n (current.p.sharpness +\n ((1 - current.p.sharpness) * rArray(gaussians)) / pressure);\n const passesGate = rr(0, current.p.grain * pressure) > 0.4;\n if (passesGate) {\n let dx, dy;\n if (_plot) {\n const plotAngle = _cachedPlotAngle;\n const plotCos = cos(plotAngle);\n const plotSin = sin(plotAngle);\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * plotSin + along * plotCos;\n dy = perp * plotCos - along * plotSin;\n } else {\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * current.sin + along * current.cos;\n dy = perp * current.cos - along * current.sin;\n }\n const diameter =\n pressure *\n pressure *\n current.p.weight *\n rr(0.85, 1.15) *\n State.stroke.weight;\n const alpha = Math.max(0.9, pressure) * current.alpha * rr(0.75, 1.1);\n circle(\n _position.x + dx,\n _position.y + dy,\n diameter,\n alpha,\n );\n }\n}\n\n/**\n * Draws the marker tip with a blend effect.\n */\nfunction markerTip() {\n if (current.p.markerTip === false) return;\n let pressure = calculatePressure();\n let alpha = current.alpha;\n if (current.p.type === \"marker\") {\n for (let s = 1; s < 10; s++) {\n drawMarker((pressure * s) / 10, true, alpha * 8);\n }\n } else if (current.p.type === \"custom\" || current.p.type === \"image\") {\n for (let s = 1; s < 5; s++) {\n drawImageTip((pressure * s) / 10, alpha * 2);\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Basic Drawing Operations\n// ---------------------------------------------------------------------------\n\n/**\n * Draws a line using the current brush.\n * @param {number} x1 - Start x-coordinate.\n * @param {number} y1 - Start y-coordinate.\n * @param {number} x2 - End x-coordinate.\n * @param {number} y2 - End y-coordinate.\n */\nexport function line(x1, y1, x2, y2) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n let d = dist(x1, y1, x2, y2);\n if (d == 0) return;\n initializeDrawingState(x1, y1, d);\n let angle = calcAngle(x1, y1, x2, y2);\n draw(angle, false);\n}\n\n/**\n * Draws a stroke from a starting point in a given direction.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of the stroke.\n * @param {number} dir - Direction, interpreted using the current runtime angle units.\n */\nexport function flowLine(x, y, length, dir) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n initializeDrawingState(x, y, length);\n draw(toDegrees(dir), false);\n}\n\n/**\n * Draws a predefined plot.\n * @param {object} p - Shape object representing the plot.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nfunction plot(p, x, y, scale) {\n isFieldReady();\n initializeDrawingState(x, y, p.length, p);\n draw(scale, true);\n}\n\n// ---------------------------------------------------------------------------\n// Standard Brushes Definition and Initialization\n// ---------------------------------------------------------------------------\n\n/**\n * Defines a set of standard brushes with specific characteristics. Each brush is defined\n * with properties such as weight, scatter, sharpness, grain, opacity, spacing, and\n * pressure sensitivity. Some brushes have additional properties like type, tip, and rotate.\n */\nconst _vals = [\n \"weight\",\n \"scatter\",\n \"sharpness\",\n \"grain\",\n \"opacity\",\n \"spacing\",\n \"pressure\",\n \"type\",\n \"tip\",\n \"rotate\",\n \"markerTip\",\n \"noise\",\n];\nconst _standard_brushes = [\n [\n \"pen\",\n [0.3, 0.15, 0.9, 2, 150, 0.1, { curve: [0.15, 0.2], min_max: [1.2, 1] }],\n ],\n [\n \"rotring\",\n [0.15, 0.05, 0.7, 15, 210, 0.1, { curve: [0.35, 0.2], min_max: [1.3, 1] }],\n ],\n [\n \"2B\",\n [0.3, 0.75, 0.45, 15, 180, 0.1, { curve: [0.1, 0.3], min_max: [1.1, 0.9] }],\n ],\n [\n \"HB\",\n [0.3, 0.6, 0.3, 10, 170, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"2H\",\n [0.2, 0.6, 0.3, 4, 120, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"cpencil\",\n [0.3, 0.55, 0.8, 7, 75, 0.1, { curve: [0.15, 0.2], min_max: [0.95, 1.2] }],\n ],\n [\n \"pastel\",\n [\n 2.05 / 3,\n 13.4 / 3,\n 0.91,\n 28,\n 35,\n 0.085 / 3,\n { mode: \"gaussian\", curve: [0.4, 0.05], min_max: [1.09, 0.93] },\n \"default\",\n undefined,\n \"natural\",\n true,\n 1,\n ],\n ],\n [\n \"crayon\",\n [\n 0.9 / 3,\n 5.45 / 3,\n 0.75,\n 250,\n 159,\n 0.23 / 3,\n [1.1, 0.9],\n \"default\",\n undefined,\n \"natural\",\n true,\n 1,\n ],\n ],\n [\n \"charcoal\",\n [\n 0.35,\n 1.5,\n 0.68,\n 500,\n 120,\n 0.03,\n { curve: [0.15, 0.4], min_max: [1.1, 0.95] },\n ],\n ],\n [\n \"spray\",\n [\n 0.2,\n 6,\n 15,\n 40,\n 90,\n 0.5,\n { curve: [0.2, 0.35], min_max: [0.7, 1] },\n \"spray\",\n ],\n ],\n [\n \"marker\",\n [\n 2,\n 0.2,\n null,\n null,\n 1,\n 0.03,\n { curve: [0.35, 0.25], min_max: [1.2, 0.85] },\n \"marker\",\n ],\n ],\n];\n\nfor (let s of _standard_brushes) {\n let obj = {};\n for (let i = 0; i < s[1].length; i++) obj[_vals[i]] = s[1][i];\n add(s[0], obj);\n}\n\n// ---------------------------------------------------------------------------\n// Extensions to Polygon and Plot Prototypes\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the polygon using the current brush.\n * @param {boolean} [_brush=false] - Optional brush name override.\n * @param {string|Color} [_color] - Optional color override.\n * @param {number} [_weight] - Optional weight override.\n */\nPolygon.prototype.draw = function (_brush = false, _color, _weight) {\n let state = BrushState();\n if (_brush) set(_brush, _color, _weight);\n if (state.isActive) {\n for (let s of this.sides) {\n line(s[0].x, s[0].y, s[1].x, s[1].y);\n }\n }\n BrushSetState(state);\n};\n\n/**\n * Draws the plot using the current brush.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nPlot.prototype.draw = function (x, y, scale) {\n if (BrushState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n plot(this, x, y, scale);\n }\n};\n\n// =============================================================================\n// Section: Loading Custom Image Tips\n// =============================================================================\n/**\n * This section defines the functionality for managing the loading and processing of image tips.\n * Images are loaded from specified source URLs, converted to a white tint for visual effects,\n * and then stored for future use. It includes methods to add new images, convert their color\n * scheme, and integrate them into the active host image pipeline.\n */\n\n/**\n * Manages loading and processing of image tips.\n * Images are converted to white with inverted alpha for tinting via shaders.\n */\nconst T = {\n tips: new Map(),\n\n /**\n * Registers an image source for later loading.\n * @param {string} src - The source URL of the image.\n */\n add(src) {\n if (!this.tips.has(src)) this.tips.set(src, false);\n },\n\n /**\n * Converts image to white with inverted alpha for tint-based rendering.\n * @param {object} image - The host image object to convert.\n */\n imageToWhite(image) {\n image.loadPixels();\n for (let i = 0; i < 4 * image.width * image.height; i += 4) {\n let average =\n (image.pixels[i] + image.pixels[i + 1] + image.pixels[i + 2]) / 3;\n image.pixels[i] = image.pixels[i + 1] = image.pixels[i + 2] = 255;\n image.pixels[i + 3] = 255 - average;\n }\n image.updatePixels();\n },\n\n /**\n * Loads all registered image tips. Returns a promise that resolves\n * when all images are loaded and processed.\n * @returns {Promise}\n */\n async load() {\n const entries = [...this.tips.keys()].filter((k) => !this.tips.get(k));\n await Promise.all(\n entries.map(\n (src) =>\n loadImageTip(src, T.imageToWhite).then((p5img) => {\n this.tips.set(src, p5img);\n }),\n ),\n );\n },\n};\n","import { State } from \"../core/color.js\";\nimport { toDegreesSigned, map, rr } from \"../core/utils.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { BrushState, BrushSetState, set, line } from \"../stroke/stroke.js\";\n\n// =============================================================================\n// Module: Classic Hatch\n// =============================================================================\n\n// ---------------------------------------------------------------------------\n// Hatch State\n// ---------------------------------------------------------------------------\n\nState.hatch = {\n isActive: false,\n dist: 5,\n angle: 45,\n options: {},\n hBrush: false,\n};\n\n/**\n * Returns a shallow snapshot of the current hatch modifier state.\n *\n * @returns {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}}\n */\nexport function HatchState() {\n return { ...State.hatch };\n}\n\n/**\n * Restores hatch modifier state from a previously captured snapshot.\n *\n * @param {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}} state\n */\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Activates classic scanline hatching for subsequent shapes.\n *\n * @param {number} [dist=5] Distance between scanlines.\n * @param {number} [angle=45] Hatch angle in the current runtime angle units.\n * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [options]\n */\nexport function hatch(\n dist = 5,\n angle = 45,\n options = { rand: false, continuous: false, gradient: false }\n) {\n let s = State.hatch;\n s.isActive = true;\n s.dist = dist;\n s.angle = toDegreesSigned(angle);\n s.options = options;\n}\n\n/**\n * Overrides the brush, color, and weight used specifically for hatch strokes.\n *\n * @param {string} brush\n * @param {string|object} [color=\"black\"]\n * @param {number} [weight=1]\n */\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\n/**\n * Deactivates hatching and clears any hatch-specific brush override.\n */\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Scanline Generation\n// ---------------------------------------------------------------------------\n\n/**\n * Computes hatch segments for one polygon by rotating it into scanline space,\n * intersecting horizontal scanlines against its edges, and rotating the\n * resulting segments back into canvas space.\n *\n * @param {Polygon} polygon\n * @param {number} angle Hatch angle in degrees.\n * @param {number} dist Base scanline spacing.\n * @param {number} gradient Multiplicative spacing growth per scanline.\n * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}\n */\nfunction scanlineHatch(polygon, angle, dist, gradient) {\n const rad = (angle * Math.PI) / 180;\n const cosA = Math.cos(rad),\n sinA = Math.sin(rad);\n const cosB = Math.cos(-rad),\n sinB = Math.sin(-rad);\n\n const verts = polygon.a,\n n = verts.length;\n\n // Rotate vertices; track Y extent\n const rotated = new Array(n);\n let minY = Infinity,\n maxY = -Infinity;\n for (let i = 0; i < n; i++) {\n const x = verts[i][0],\n y = verts[i][1];\n const r = [x * cosA - y * sinA, x * sinA + y * cosA];\n rotated[i] = r;\n if (r[1] < minY) minY = r[1];\n if (r[1] > maxY) maxY = r[1];\n }\n\n // Build edge list (skip horizontal edges)\n const edges = [];\n for (let i = 0; i < n; i++) {\n const a = rotated[i],\n b = rotated[(i + 1) % n];\n if (a[1] !== b[1]) edges.push(a, b);\n }\n const eLen = edges.length;\n\n // Scan, find crossings, rotate back\n const segments = [];\n const cx = [];\n let Y = minY + dist * 0.5,\n step = dist;\n while (Y < maxY) {\n cx.length = 0;\n for (let i = 0; i < eLen; i += 2) {\n const y1 = edges[i][1],\n y2 = edges[i + 1][1];\n if ((y1 <= Y && Y < y2) || (y2 <= Y && Y < y1))\n cx.push(\n edges[i][0] + ((Y - y1) / (y2 - y1)) * (edges[i + 1][0] - edges[i][0])\n );\n }\n cx.sort((a, b) => a - b);\n for (let i = 0; i < cx.length - 1; i += 2) {\n segments.push({\n scanY: Y,\n x1: cx[i] * cosB - Y * sinB,\n y1: cx[i] * sinB + Y * cosB,\n x2: cx[i + 1] * cosB - Y * sinB,\n y2: cx[i + 1] * sinB + Y * cosB,\n });\n }\n Y += step;\n step *= gradient;\n }\n return segments;\n}\n\n/**\n * Collects and orders hatch segments for one polygon or a polygon list.\n *\n * Segments are sorted in scanline traversal order so downstream rendering can\n * optionally connect them into a continuous serpentine path.\n *\n * @param {Polygon|Polygon[]} polygons\n * @param {number} dist\n * @param {number} angle\n * @param {number} gradient\n * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}\n */\nfunction getHatchSegments(polygons, dist, angle, gradient) {\n if (!Array.isArray(polygons)) polygons = [polygons];\n const segs = [];\n for (const poly of polygons) {\n for (const s of scanlineHatch(poly, angle, dist, gradient)) segs.push(s);\n }\n segs.sort((a, b) => (a.scanY === b.scanY ? a.x1 - b.x1 : a.scanY - b.scanY));\n return segs;\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Configuration\n// ---------------------------------------------------------------------------\n\n/**\n * Runs hatch drawing with the temporary hatch-specific brush style if one is active,\n * then restores the outer stroke state.\n *\n * @param {() => void} drawFn\n */\nfunction withHatchStyle(drawFn) {\n const save = BrushState();\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n drawFn();\n BrushSetState(save);\n}\n\n/**\n * Resolves the active hatch parameters and precomputes the ordered scanline segments.\n *\n * @param {Polygon|Polygon[]} polygons\n * @returns {{dist:number, options:Object, segs:Object[]}}\n */\nfunction getActiveHatchConfig(polygons) {\n const dist = State.hatch.dist;\n const angle = ((State.hatch.angle % 180) + 180) % 180;\n const options = State.hatch.options;\n const gradient = options.gradient ? map(options.gradient, 0, 1, 1, 1.1, true) : 1;\n const segs = getHatchSegments(polygons, dist, angle, gradient);\n return { dist, options, segs };\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Lines\n// ---------------------------------------------------------------------------\n\n/**\n * Expands ordered hatch segments into the actual line list that will be drawn.\n *\n * This includes endpoint jitter when `rand` is active and inserts the serpentine\n * connector lines when `continuous` is enabled.\n *\n * @param {Polygon|Polygon[]} polygons\n * @returns {{x1:number, y1:number, x2:number, y2:number, scanY:number, isConnector:boolean}[]}\n */\nexport function getHatchLines(polygons) {\n const { dist, options, segs } = getActiveHatchConfig(polygons);\n const r = options.rand || 0;\n const lines = [];\n\n for (let j = 0; j < segs.length; j++) {\n const s = segs[j];\n let x1 = s.x1, y1 = s.y1, x2 = s.x2, y2 = s.y2;\n if (r) {\n x1 += 2 * r * dist * rr(-1, 1);\n y1 += 2 * r * dist * rr(-1, 1);\n x2 += 2 * r * dist * rr(-1, 1);\n y2 += 2 * r * dist * rr(-1, 1);\n }\n const reverse = options.continuous && j % 2 === 1;\n const line = reverse\n ? { x1: x2, y1: y2, x2: x1, y2: y1, scanY: s.scanY, isConnector: false }\n : { x1, y1, x2, y2, scanY: s.scanY, isConnector: false };\n lines.push(line);\n if (j > 0 && options.continuous) {\n const prev = lines[lines.length - 2];\n lines.push({\n x1: prev.x2,\n y1: prev.y2,\n x2: line.x1,\n y2: line.y1,\n scanY: s.scanY,\n isConnector: true,\n });\n }\n }\n\n return lines;\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Rendering\n// ---------------------------------------------------------------------------\n\n/**\n * Iterates the generated hatch lines and delegates the actual rendering of each\n * segment to the provided callback.\n *\n * @param {Polygon|Polygon[]} polygons\n * @param {(x1:number, y1:number, x2:number, y2:number, index:number, segs:Object[]) => void} drawSegment\n */\nfunction renderHatchSegments(polygons, drawSegment) {\n const segs = getHatchLines(polygons);\n withHatchStyle(() => {\n for (let j = 0; j < segs.length; j++) {\n const s = segs[j];\n drawSegment(s.x1, s.y1, s.x2, s.y2, j, segs);\n }\n });\n}\n\n/**\n * Draws classic hatch lines over one polygon or an array of polygons.\n *\n * @param {Polygon|Polygon[]} polygons\n */\nexport function createHatch(polygons) {\n renderHatchSegments(polygons, (x1, y1, x2, y2) => {\n line(x1, y1, x2, y2);\n });\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Applies the currently active hatch modifier to a polygon, or temporarily\n * overrides hatch parameters for this call only.\n *\n * @param {number|false} [_dist=false]\n * @param {number} [_angle]\n * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [_options]\n */\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (State.hatch.isActive) createHatch(this);\n HatchSetState(state);\n};\n\n/**\n * Converts the plot to a polygon and applies the currently active hatch modifier.\n *\n * @param {number} x\n * @param {number} y\n * @param {number} scale\n */\nPlot.prototype.hatch = function (x, y, scale) {\n if (HatchState().isActive) {\n if (this.origin) (x = this.origin[0]), (y = this.origin[1]), (scale = 1);\n this.pol = this.genPol(x, y, scale, 0.3);\n this.pol.hatch();\n }\n};\n","// =============================================================================\n// Module: Mass\n// =============================================================================\n\nimport { State } from \"../core/color.js\";\nimport { arc } from \"../core/primitives.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { rr2, dist, calcAngle } from \"../core/utils.js\";\nimport { fromDegrees, usesRadians } from \"../core/runtime.js\";\nimport { HatchState, HatchSetState, hatch, getHatchLines } from \"./hatch.js\";\nimport { BrushState, BrushSetState, getBrushParams, set } from \"../stroke/stroke.js\";\nimport { wiggle } from \"../core/flowfield.js\";\n\n// ---------------------------------------------------------------------------\n// Mass State\n// ---------------------------------------------------------------------------\n\nState.mass = {\n isActive: false,\n brush: null,\n color: null,\n options: {},\n};\n\n/**\n * Returns a shallow copy of the current mass state.\n * @returns {object}\n */\nexport function MassState() {\n return { ...State.mass };\n}\n\n/**\n * Restores a previously saved mass state.\n * @param {object} state\n */\nexport function MassSetState(state) {\n State.mass = { ...state };\n}\n\n/**\n * Enables massing mode with a brush, color, and optional configuration.\n *\n * @param {string} brush - Brush name to use for the mass pass.\n * @param {string|Color} color - Color to use for the mass pass.\n * @param {object} [options={}] - Massing options such as precision, strength, gradient, and outline.\n */\nexport function mass(brush, color, options = {}) {\n State.mass.brush = brush;\n State.mass.color = color;\n State.mass.options = options;\n State.mass.isActive = true;\n}\n\n/**\n * Disables massing mode for subsequent geometry.\n */\nexport function noMass() {\n State.mass.isActive = false;\n State.mass.brush = null;\n State.mass.color = null;\n State.mass.options = {};\n}\n\n// ---------------------------------------------------------------------------\n// Polygon Preparation\n// ---------------------------------------------------------------------------\n\n/**\n * Returns a translated copy of a polygon.\n * Used to build the secondary mass layers from an existing base polygon.\n * @param {Polygon} polygon\n * @param {number} jitterX\n * @param {number} jitterY\n * @returns {Polygon}\n */\nfunction jitterPolygon(polygon, jitterX, jitterY) {\n return new Polygon(\n polygon.vertices.map((vertex) => [vertex.x + jitterX, vertex.y + jitterY]),\n );\n}\n\n/**\n * Builds the three polygons used for a mass pass.\n * Both polygon and plot inputs use one base polygon plus two translated copies,\n * so plot-based massing only needs a single `genPol(...)` call.\n * @param {Polygon|Plot} shape\n * @param {number|false} x\n * @param {number} y\n * @param {number} scale\n * @returns {Polygon[]}\n */\nfunction getMassPolygons(shape, x, y, scale) {\n const isPolygon = x === false;\n const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;\n const basePolygon = isPolygon ? shape : shape.genPol(x, y, scale, 0.15);\n const maxJitter = Math.min(scatter * 2, 5);\n const jitters = [\n [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],\n [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],\n ];\n\n return [\n basePolygon,\n jitterPolygon(basePolygon, jitters[0][0], jitters[0][1]),\n jitterPolygon(basePolygon, jitters[1][0], jitters[1][1]),\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Angle & Bounds Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Converts degree values into the current runtime angle units.\n * @param {number} angle\n * @returns {number}\n */\nfunction getAngleConverter() {\n return usesRadians()\n ? (angle) => (angle * Math.PI) / 180\n : (angle) => angle;\n}\n\n/**\n * Computes an axis-aligned bounding box for a polygon.\n * The diagonal is used as a size reference for pivot distance.\n * @param {Polygon} polygon\n * @returns {{minX:number,minY:number,maxX:number,maxY:number,cx:number,cy:number,size:number}}\n */\nfunction getPolygonBounds(polygon) {\n const points = polygon?.a ?? [];\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n for (const [x, y] of points) {\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n return {\n minX,\n minY,\n maxX,\n maxY,\n cx: (minX + maxX) / 2,\n cy: (minY + maxY) / 2,\n size: Math.hypot(maxX - minX, maxY - minY),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Pivot Geometry\n// ---------------------------------------------------------------------------\n\n/**\n * Chooses the diagonal corner family for a whole mass gesture.\n * Positive-angle hatching uses either bottom-right or top-left; negative-angle\n * hatching uses either bottom-left or top-right.\n * @param {number} angleDeg\n * @returns {[number, number]}\n */\nfunction getPivotBias(angleDeg) {\n const normalizedAngle = ((((angleDeg + 90) % 180) + 180) % 180) - 90;\n if (normalizedAngle >= 0) {\n return rr2() < 0.5 ? [1, 1] : [-1, -1];\n } else {\n return rr2() < 0.5 ? [-1, 1] : [1, -1];\n }\n}\n\n/**\n * Places the global pivot anchor outside the polygon, along the selected bias.\n * Distance varies per layer while the bias stays fixed for the whole mass.\n * @param {Polygon} polygon\n * @param {[number, number]} bias\n * @returns {{x:number,y:number}}\n */\nfunction getPivotAnchor(polygon, bias) {\n const bounds = getPolygonBounds(polygon);\n const offset = bounds.size * rr2(0.6, 1.4);\n const [sx, sy] = bias;\n return {\n x: bounds.cx + sx * offset,\n y: bounds.cy + sy * offset,\n };\n}\n\n/**\n * Projects the global pivot anchor onto the perpendicular bisector of a line.\n * This yields a valid circle center equidistant from both endpoints.\n * @param {{x:number,y:number}} anchor\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {{x:number,y:number}|null}\n */\nfunction projectAnchorToBisector(anchor, x1, y1, x2, y2) {\n const mx = (x1 + x2) / 2;\n const my = (y1 + y2) / 2;\n const dx = x2 - x1;\n const dy = y2 - y1;\n const length = Math.hypot(dx, dy);\n if (!length) return null;\n const nx = -dy / length;\n const ny = dx / length;\n const offset = (anchor.x - mx) * nx + (anchor.y - my) * ny;\n return {\n x: mx + nx * offset,\n y: my + ny * offset,\n };\n}\n\n/**\n * Returns the shortest arc between two endpoints around a given center.\n * The returned angles are already converted into the current runtime angle units.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {[number, number]}\n */\nfunction getShortArcAngles(cx, cy, x1, y1, x2, y2, toAngleUnit) {\n let startDeg = calcAngle(cx, cy, x1, y1);\n let endDeg = calcAngle(cx, cy, x2, y2);\n const sweep = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweep > 180) [startDeg, endDeg] = [endDeg, startDeg];\n return [\n toAngleUnit(startDeg),\n toAngleUnit(endDeg),\n ];\n}\n\n/**\n * Splits a hatch line into two slightly separated segments so some gestures\n * read as interrupted rather than perfectly continuous.\n * @param {{x1:number,y1:number,x2:number,y2:number}} seg\n * @returns {Array<{x1:number,y1:number,x2:number,y2:number}>}\n */\nfunction splitSegment(seg) {\n const t = rr2(0.35, 0.65);\n const mx = seg.x1 + (seg.x2 - seg.x1) * t;\n const my = seg.y1 + (seg.y2 - seg.y1) * t;\n const dx = seg.x2 - seg.x1;\n const dy = seg.y2 - seg.y1;\n const length = Math.hypot(dx, dy) || 1;\n const gap = rr2(0.04, 0.1) * length;\n const gx = (dx / length) * gap * 0.5;\n const gy = (dy / length) * gap * 0.5;\n return [\n { x1: seg.x1, y1: seg.y1, x2: mx - gx, y2: my - gy },\n { x1: mx + gx, y1: my + gy, x2: seg.x2, y2: seg.y2 },\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Mass Rendering\n// ---------------------------------------------------------------------------\n\n/**\n * Draws one polygon of the mass as a family of arcs derived from hatch lines.\n * The same pivot bias is used across layers, while each layer gets its own\n * anchor distance from the shape.\n * @param {Polygon} polygon\n * @param {[number, number]} pivotBias\n */\nfunction drawMassArcs(polygon, pivotBias, toAngleUnit) {\n const anchor = getPivotAnchor(polygon, pivotBias);\n for (const seg of getHatchLines(polygon)) {\n const parts = !seg.isConnector && rr2() < 0.35 ? splitSegment(seg) : [seg];\n for (const part of parts) {\n const center = projectAnchorToBisector(anchor, part.x1, part.y1, part.x2, part.y2);\n if (!center) continue;\n const radius = dist(center.x, center.y, part.x1, part.y1);\n if (!radius) continue;\n const [startAngle, endAngle] = getShortArcAngles(\n center.x,\n center.y,\n part.x1,\n part.y1,\n part.x2,\n part.y2,\n toAngleUnit,\n );\n arc(center.x, center.y, radius, startAngle, endAngle);\n }\n }\n}\n\n/**\n * Configures a hatch pass and immediately reinterprets the generated lines as arcs.\n * @param {Polygon} polygon\n * @param {number} dist\n * @param {number} angle\n * @param {object} options\n * @param {[number, number]} pivotBias\n */\nfunction drawMassPass(polygon, dist, angle, options, pivotBias, toAngleUnit) {\n hatch(dist, angle, options);\n drawMassArcs(polygon, pivotBias, toAngleUnit);\n}\n\n/**\n * Creates the built-in \"massing\" effect for a polygon or plot.\n * A mass is built from up to three jittered polygon layers, each hatched and\n * then redrawn as arc gestures around a shared pivot bias.\n * @param {Polygon|Plot} shape\n * @param {number|false} x\n * @param {number} y\n * @param {number} scale\n */\nexport function createMass(shape, x, y, scale) {\n const pols = getMassPolygons(shape, x, y, scale);\n const hatchState = HatchState();\n const brushState = BrushState();\n const fieldState = { ...State.field };\n const precision = State.mass.options?.precision ?? 0.5;\n const strength = State.mass.options?.strength ?? 1;\n const gradient = State.mass.options?.gradient ?? 0.1;\n const outline = State.mass.options?.outline ?? false;\n const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;\n const hatchDist = 1.6 * rr2(scatter * 0.65, scatter * 0.85) - 0.4 * gradient;\n const baseAngle = rr2(-90, 90);\n const pivotBias = getPivotBias(baseAngle);\n const toAngleUnit = getAngleConverter();\n\n set(State.mass.brush, State.mass.color, 1);\n wiggle(2 - precision);\n if (outline) pols[0].draw();\n\n drawMassPass(\n pols[0],\n hatchDist * 0.9,\n fromDegrees(baseAngle),\n {\n gradient,\n rand: 2 - 2 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n\n if (strength > 0.33) {\n drawMassPass(\n pols[1],\n hatchDist,\n fromDegrees(baseAngle + 20 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n }\n\n if (strength > 0.66) {\n drawMassPass(\n pols[2],\n hatchDist * 0.8,\n fromDegrees(baseAngle + 15 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n }\n\n BrushSetState(brushState);\n HatchSetState(hatchState);\n State.field = { ...fieldState };\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Applies massing to polygon geometry.\n */\nPolygon.prototype.mass = function () {\n if (State.mass?.isActive) {\n createMass(this, false);\n }\n};\n\n/**\n * Applies massing to plots by generating their polygon first.\n * @param {number} x\n * @param {number} y\n * @param {number} scale\n */\nPlot.prototype.mass = function (x, y, scale) {\n if (State.mass?.isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n createMass(this, x, y, scale);\n }\n};\n","import { Mix } from \"../core/color.js\";\n\nfunction strokePadding(ctx, matrix) {\n const lineWidth = ctx.lineWidth || 0;\n if (lineWidth <= 0) return 1;\n\n return (\n 1 +\n (lineWidth * Math.max(Math.hypot(matrix.a, matrix.c), Math.hypot(matrix.b, matrix.d))) /\n 2\n );\n}\n\n// =============================================================================\n// Section: Draw shapes to Mask Buffers\n// =============================================================================\n\n/**\n * Draws a polygon to the mask using the provided vertices.\n * @param {Array<{x: number, y: number}>} vertices - Array of vertex coordinates.\n */\nexport function drawPolygon(vertices, matrix = null) {\n const ctx = Mix.ctx;\n if (!matrix) matrix = ctx.getTransform();\n // Cache the current 2D transform once so the hot loop can stay numeric and\n // avoid repeated property reads while we build bounds.\n const a = matrix.a;\n const b = matrix.b;\n const c = matrix.c;\n const d = matrix.d;\n const e = matrix.e;\n const f = matrix.f;\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n\n ctx.beginPath();\n\n // Seed both the path and the transformed bounds from the first vertex so the\n // loop below only needs to append line segments.\n const first = vertices[0];\n let tx = a * first.x + c * first.y + e;\n let ty = b * first.x + d * first.y + f;\n minX = maxX = tx;\n minY = maxY = ty;\n\n ctx.moveTo(first.x, first.y);\n\n for (let i = 1; i < vertices.length; i++) {\n const v = vertices[i];\n\n // Track the transformed bounds in canvas space while we build the path so\n // dirty-rect bookkeeping does not need a second pass over the vertices.\n tx = a * v.x + c * v.y + e;\n ty = b * v.x + d * v.y + f;\n minX = Math.min(minX, tx);\n minY = Math.min(minY, ty);\n maxX = Math.max(maxX, tx);\n maxY = Math.max(maxY, ty);\n\n ctx.lineTo(v.x, v.y);\n }\n\n ctx.closePath();\n\n // Expand by stroke width so the later composite pass copies enough pixels\n // even when the polygon border extends outside the raw vertex bounds.\n const padding = strokePadding(ctx, matrix);\n Mix.markDirtyRect(Mix.mask, {\n minX: minX - padding,\n minY: minY - padding,\n maxX: maxX + padding,\n maxY: maxY + padding,\n });\n}\n\n/**\n * Draws a circle to the mask.\n * @param {number} x - X-coordinate of the circle's center.\n * @param {number} y - Y-coordinate of the circle's center.\n * @param {number} d - Diameter of the circle.\n */\nexport function circle(x, y, d) {\n const PI2 = Math.PI * 2;\n const ctx = Mix.ctx;\n const radius = d / 2;\n\n ctx.moveTo(x + radius, y);\n ctx.arc(x, y, radius, 0, PI2);\n}\n","import * as Color from \"../core/color.js\";\nimport {\n createFramebuffer,\n create2DCanvas,\n} from \"../core/compositor_runtime.js\";\n\n// Small staging canvas used to upload only the dirty fill sub-rect into the\n// framebuffer-backed mask mirror consumed by the blend shader.\nlet FillMaskUploadCanvas = null;\nlet isFillCompositeRegistered = false;\nconst DIRTY_FILL_PADDING = 4;\n\n// =============================================================================\n// Section: Helpers\n// =============================================================================\n/**\n * Returns whether the CPU-side 2D fill mask must be recreated.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} maskWidth - Mask width in physical pixels.\n * @param {number} maskHeight - Mask height in physical pixels.\n * @returns {boolean} True when the 2D fill mask needs reallocation.\n */\nfunction needsFillMaskCanvas(Renderer, maskWidth, maskHeight) {\n return (\n !Renderer.mask ||\n Renderer.mask.width !== maskWidth ||\n Renderer.mask.height !== maskHeight\n );\n}\n\n/**\n * Returns whether the framebuffer-backed fill mask mirror must be recreated.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {boolean} True when the fill mask framebuffer needs reallocation.\n */\nfunction needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density) {\n return (\n !Renderer.fillMaskFramebuffer ||\n Renderer.fillMaskFramebuffer.width !== Cwidth ||\n Renderer.fillMaskFramebuffer.height !== Cheight ||\n (typeof Renderer.fillMaskFramebuffer.pixelDensity === \"function\" &&\n Renderer.fillMaskFramebuffer.pixelDensity() !== Density)\n );\n}\n\n// =============================================================================\n// Section: Resource Management\n// =============================================================================\n/**\n * Ensures fill compositing resources exist for the active renderer.\n *\n * Fill draws first into a CPU-side 2D mask canvas. That mask is later uploaded,\n * dirty-rect by dirty-rect, into a framebuffer-backed mirror used by the final\n * blend shader pass.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n * @returns {{mask: object, ctx: CanvasRenderingContext2D}} Fill mask resources.\n */\nexport function ensureFillCompositeResources(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n clearTarget,\n) {\n const maskWidth = Math.max(1, Math.round(Cwidth * Density));\n const maskHeight = Math.max(1, Math.round(Cheight * Density));\n\n if (needsFillMaskCanvas(Renderer, maskWidth, maskHeight)) {\n Renderer.mask = create2DCanvas(maskWidth, maskHeight);\n }\n\n if (needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.fillMaskFramebuffer?.remove) {\n Renderer.fillMaskFramebuffer.remove();\n }\n Renderer.fillMaskFramebuffer = createFramebuffer(Renderer, {\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n clearTarget(Renderer.fillMaskFramebuffer);\n }\n\n Renderer.mask.dirtyRect ??= null;\n Renderer.mask.isDrawn ??= false;\n Renderer.mask.drawingContext.imageSmoothingEnabled = false;\n return {\n mask: Renderer.mask,\n ctx: Renderer.mask.drawingContext,\n };\n}\n\n// =============================================================================\n// Section: Mask Lifecycle\n// =============================================================================\n/**\n * Clears the current fill mask and resets its bookkeeping flags.\n *\n * @param {object|null} target - Fill mask canvas or framebuffer mirror.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n */\nexport function clearFillMask(target, clearTarget) {\n if (!target) return;\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\n}\n\n// =============================================================================\n// Section: Composite Bounds\n// =============================================================================\n/**\n * Returns the fill dirty rect to composite into the main target. Fill bounds are\n * taken directly from the accumulated 2D mask dirty area plus a small padding.\n *\n * @param {object|null} target - Fill mask canvas.\n * @param {Function} _getActiveFramebuffer - Unused for fill masks.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} expandDirtyRect - Expands a rect by a constant padding.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\nexport function getFillCompositeRect(\n target,\n _getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(target.dirtyRect, DIRTY_FILL_PADDING),\n );\n}\n\n// =============================================================================\n// Section: Upload\n// =============================================================================\n/**\n * Uploads only the dirty portion of the CPU-side 2D fill mask into the\n * framebuffer-backed fill mask mirror used by the shader compositor.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {object} mask - CPU-side 2D fill mask canvas.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} dirtyRect - Dirty rect to upload.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n * @returns {object} Framebuffer-backed fill mask mirror.\n */\nexport function getFillShaderMask(\n Renderer,\n mask,\n dirtyRect,\n getFullDirtyRect,\n clearTarget,\n) {\n const target = Renderer.fillMaskFramebuffer;\n const gl = Renderer.drawingContext;\n const uploadRect = dirtyRect ?? getFullDirtyRect();\n const uploadWidth = uploadRect.maxX - uploadRect.minX;\n const uploadHeight = uploadRect.maxY - uploadRect.minY;\n\n if (\n !FillMaskUploadCanvas ||\n FillMaskUploadCanvas.width !== uploadWidth ||\n FillMaskUploadCanvas.height !== uploadHeight\n ) {\n FillMaskUploadCanvas = create2DCanvas(uploadWidth, uploadHeight);\n }\n\n const uploadContext = FillMaskUploadCanvas.drawingContext;\n uploadContext.clearRect(0, 0, uploadWidth, uploadHeight);\n uploadContext.drawImage(\n mask,\n uploadRect.minX,\n uploadRect.minY,\n uploadWidth,\n uploadHeight,\n 0,\n 0,\n uploadWidth,\n uploadHeight,\n );\n\n clearTarget(target);\n gl.bindTexture(gl.TEXTURE_2D, target.colorTexture);\n gl.texSubImage2D(\n gl.TEXTURE_2D,\n 0,\n uploadRect.minX,\n uploadRect.minY,\n gl.RGBA,\n gl.UNSIGNED_BYTE,\n FillMaskUploadCanvas,\n );\n return target;\n}\n\n// =============================================================================\n// Section: Registration\n// =============================================================================\n/**\n * Registers the fill compositor with the shared color/composite core.\n * Safe to call multiple times.\n */\nexport function initFillComposite() {\n if (isFillCompositeRegistered) return;\n Color.registerFillComposite?.({\n ensureResources: ensureFillCompositeResources,\n clearMask: clearFillMask,\n getCompositeRect: getFillCompositeRect,\n getShaderMask: getFillShaderMask,\n });\n isFillCompositeRegistered = true;\n}\n","// =============================================================================\n// Module: Fill\n// =============================================================================\n/**\n * The Fill module contains functions and classes dedicated to handling\n * the fill properties of shapes within the drawing context. It supports complex fill\n * operations with effects such as bleeding to simulate watercolor-like textures. The\n * methods provided allow for setting the fill color with opacity, controlling the\n * intensity of the bleed effect, and enabling or disabling the fill operation.\n *\n * The watercolor effect implementation is inspired by Tyler Hobbs'\n * techniques for simulating watercolor paints.\n */\n\n// Core imports\nimport { Renderer, Cwidth, Cheight, Density } from \"../core/target.js\";\nimport {\n Mix,\n State,\n} from \"../core/color.js\";\nimport { drawPolygon, circle } from \"./mask.js\";\nimport {\n constrain,\n rr,\n map,\n randInt,\n gaussian,\n rotate,\n cos,\n sin,\n _onSeed,\n} from \"../core/utils.js\";\nimport { isFieldReady } from \"../core/flowfield.js\";\nimport { createColor, getAffineMatrix } from \"../core/runtime.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\n\n// Internal module imports\nimport { initFillComposite } from \"./composite.js\";\n\ninitFillComposite(); // Register the fill composite with the core color module\n\n// =============================================================================\n// Fill State and helpers\n// =============================================================================\n\n// Vertex cap for grow() — set to 0 or false to disable\nconst GROW_MAX_VERTS = 2024;\nlet GROW_CAP;\n\n// Reusable scratch arrays for grow() — avoids 4 allocations per call (~15× per fill)\nlet _growInsX = [];\nlet _growInsY = [];\nlet _growMods = [];\nlet _growDirs = [];\n\n/**\n * Global fill state settings.\n */\nState.fill = {\n opacity: 150,\n bleed_strength: 0.07,\n texture_strength: 0.8,\n border_strength: 0.5,\n direction: \"out\",\n isActive: false,\n};\n\n// Cache the current state\nconst FillState = () => ({ ...State.fill });\nconst FillSetState = (state) => {\n State.fill = { ...state };\n};\n\n// ---------------------------------------------------------------------------\n// Fill Style Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Sets the fill color and opacity for subsequent drawing operations.\n * @param {number|string|Color} a - Either the red component, a CSS color string, or a Color object.\n * @param {number} [b] - The green component or the opacity if using grayscale.\n * @param {number} [c] - The blue component.\n * @param {number} [d] - The opacity.\n */\nexport function fill(a, b, c, d) {\n State.fill.opacity = (arguments.length < 4 ? b : d) || 150;\n State.fill.color = arguments.length < 3 ? createColor(a) : createColor(a, b, c);\n State.fill.isActive = true;\n}\n\n/**\n * Sets the bleed (watercolor) intensity and direction.\n * @param {number} _i - The bleed intensity (clamped to [0,1]).\n * @param {string} [_direction=\"out\"] - The bleeding direction.\n */\nexport function fillBleed(_i, _direction = \"out\") {\n State.fill.bleed_strength = constrain(_i, 0, 1);\n State.fill.direction = _direction;\n}\n\n/**\n * Sets the texture and border strengths for the fill.\n * @param {number} [_texture=0.4] - The texture strength (clamped to [0,1]).\n * @param {number} [_border=0.4] - The border strength (clamped to [0,1]).\n */\nexport function fillTexture(_texture = 0.4, _border = 0.4) {\n State.fill.texture_strength = constrain(_texture, 0, 1);\n State.fill.border_strength = constrain(_border, 0, 1);\n}\n\n/**\n * Disables fill for subsequent drawing operations.\n */\nexport function noFill() {\n State.fill.isActive = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fill Manager Functions\n// ---------------------------------------------------------------------------\n\nlet _polygon;\nlet _bbMinX, _bbMinY, _bbMaxX, _bbMaxY;\n\n// Pre-compute gaussians for reuse\nconst GAUSSIAN_POOL_SIZE = 512;\nconst _gaussians = [[], []]; // [a, b]\nfunction _fillGaussianPools() {\n for (let i = 0; i < GAUSSIAN_POOL_SIZE; i++) {\n _gaussians[0][i] = gaussian(0.5, 0.2);\n _gaussians[1][i] = gaussian(0, 0.02);\n }\n}\n_onSeed(_fillGaussianPools);\n\n// Helper for direction checking - extracted to reduce duplication\nfunction _isLeft(a, b, c) {\n return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) > 0.01;\n}\n\n/**\n * Calculates the centroid of a polygon from its vertices.\n * @param {Object[]} pts - Array of points with {x, y}.\n * @returns {Object} The center point {x, y}.\n */\nfunction _center(pts) {\n if (pts.length === 0) {\n return { x: 0, y: 0 };\n }\n\n if (pts.length < 8) {\n // Simple average for small polygons\n let sumX = 0, sumY = 0;\n for (const pt of pts) { sumX += pt.x; sumY += pt.y; }\n return { x: sumX / pts.length, y: sumY / pts.length };\n }\n\n // Close polygon if needed\n const v = [...pts];\n if (v[0].x !== v[v.length - 1].x || v[0].y !== v[v.length - 1].y)\n v.push(v[0]);\n\n // Calculate using shoelace formula (more efficient implementation)\n let area = 0,\n cx = 0,\n cy = 0;\n for (let i = 0; i < v.length - 1; i++) {\n const cross = v[i].x * v[i + 1].y - v[i + 1].x * v[i].y;\n area += cross;\n cx += (v[i].x + v[i + 1].x) * cross;\n cy += (v[i].y + v[i + 1].y) * cross;\n }\n\n area *= 0.5;\n return area\n ? { x: cx / (6 * area), y: cy / (6 * area) }\n : { x: v[0].x, y: v[0].y };\n}\n\n/**\n * Fills a given polygon with a watercolor effect.\n * @param {Polygon} polygon - The polygon to fill.\n */\nexport function createFill(polygon) {\n if (!State.fill.isActive || !State.fill.color) {\n throw new Error(\n \"No fill color set. Call brush.fill(color) before drawing shapes.\",\n );\n }\n _polygon = polygon;\n _bbMinX = Infinity; _bbMinY = Infinity; _bbMaxX = -Infinity; _bbMaxY = -Infinity;\n for (const [a] of polygon.sides) {\n if (a.x < _bbMinX) _bbMinX = a.x;\n if (a.x > _bbMaxX) _bbMaxX = a.x;\n if (a.y < _bbMinY) _bbMinY = a.y;\n if (a.y > _bbMaxY) _bbMaxY = a.y;\n }\n const v = [...polygon.vertices];\n const _wr = rr(0, 75);\n const fluid = ~~(v.length * 0.25 * (_wr < 5 ? 1 : _wr < 15 ? 2 : 3));\n const strength = State.fill.bleed_strength;\n const modifiers = v.map(\n (_, i) => (i > fluid ? 1 : 0.3) * rr(0.85, 1.4) * strength,\n );\n const shift = randInt(0, v.length);\n const n = v.length;\n const shifted = new Array(n);\n for (let i = 0; i < n; i++) shifted[i] = v[(i + shift) % n];\n const center = _center(shifted);\n return new FillPoly(shifted, modifiers, center, [], true).fill(\n State.fill.color,\n map(State.fill.opacity, 0, 255, 0, 1, true),\n State.fill.texture_strength,\n );\n}\n\n// ---------------------------------------------------------------------------\n// FillPolygon Class\n// ---------------------------------------------------------------------------\n\n/**\n * The FillPolygon class is used to create and manage the properties of the polygons that produces\n * the watercolor effect. It includes methods to grow (expand) the polygon and apply layers\n * of color with varying intensity and erase parts to simulate a natural watercolor bleed.\n * The implementation follows Tyler Hobbs' guide to simulating watercolor:\n * https://tylerxhobbs.com/essays/2017/a-generative-approach-to-simulating-watercolor-paints\n */\nclass FillPoly {\n /**\n * Constructs a FillPolygon.\n * @param {Object[]} _v - Vertices of the polygon.\n * @param {number[]} _m - Multipliers for the bleed effect at each vertex.\n * @param {Object} _center - The polygon's center {x, y}.\n * @param {boolean[]} dir - Array indicating bleed direction per vertex.\n * @param {boolean} isFirst - True for initial polygon.\n */\n constructor(v, m, center, dir = [], isFirst = false, sx, sy) {\n // Initialize properties\n this.v = v;\n this.m = m;\n this.dir = dir;\n this.midP = center;\n\n // Initialize size and direction for first polygon\n if (isFirst) {\n // Calculate size bounds\n let maxX = 0,\n maxY = 0;\n const rayCalc = [];\n\n for (let i = 0; i < v.length; i++) {\n // Store vertex distances to center for size calculation\n const dx = Math.abs(center.x - v[i].x);\n const dy = Math.abs(center.y - v[i].y);\n maxX = Math.max(maxX, dx);\n maxY = Math.max(maxY, dy);\n\n // Store edge info for ray calculations\n const v1 = v[i],\n v2 = v[(i + 1) % v.length];\n const side = { x: v2.x - v1.x, y: v2.y - v1.y };\n const rt = rotate(0, 0, side.x, side.y, 90);\n const mid = { x: v1.x + side.x / 2, y: v1.y + side.y / 2 };\n\n rayCalc.push({\n v1,\n v2,\n ray: {\n point1: mid,\n point2: { x: mid.x + rt.x, y: mid.y + rt.y },\n },\n });\n }\n\n // Store sizes\n this.sizeX = maxX;\n this.sizeY = maxY;\n\n // Calculate directions — inline ray-polygon intersection to avoid\n // O(n) overhead of Polygon.intersect() (cache-key string building,\n // object allocation, intersectLines wrapper) per edge.\n const polySides = _polygon.sides;\n this.dir = Array(v.length);\n for (let i = 0; i < rayCalc.length; i++) {\n const rc = rayCalc[i];\n const r1x = rc.ray.point1.x, r1y = rc.ray.point1.y;\n const r2x = rc.ray.point2.x, r2y = rc.ray.point2.y;\n const rdx = r2x - r1x, rdy = r2y - r1y;\n let count = 0;\n for (let j = 0; j < polySides.length; j++) {\n const sa = polySides[j][0], sb = polySides[j][1];\n const sdx = sb.x - sa.x, sdy = sb.y - sa.y;\n const denom = sdy * rdx - sdx * rdy;\n if (denom === 0) continue;\n const ub = (rdx * (r1y - sa.y) - rdy * (r1x - sa.x)) / denom;\n if (ub < 0 || ub > 1) continue;\n // Compute intersection point inline\n const ua = (sdx * (r1y - sa.y) - sdy * (r1x - sa.x)) / denom;\n const ix = r1x + ua * rdx;\n const iy = r1y + ua * rdy;\n // _isLeft check inline: (v2-v1) × (isect-v1) > 0.01\n if ((rc.v2.x - rc.v1.x) * (iy - rc.v1.y) - (rc.v2.y - rc.v1.y) * (ix - rc.v1.x) > 0.01) {\n count++;\n }\n }\n this.dir[i] = count % 2 === 0;\n }\n\n // Randomize center (single calculation)\n const rx = rr(-0.6, 0.6) * maxX;\n const ry = rr(-0.6, 0.6) * maxY;\n this.midP = { x: center.x + rx, y: center.y + ry };\n } else {\n this.sizeX = sx;\n this.sizeY = sy;\n }\n }\n\n /**\n * Trims vertices from the polygon based on a factor.\n * @param {number} [factor=1] - Factor determining amount of trimming.\n * @returns {Object} An object containing trimmed vertices, multipliers, and direction.\n */\n trim(f = 1) {\n // Fast path for common case\n if (f >= 1 || f < 0 || this.v.length <= 8) {\n return { v: this.v, m: this.m, dir: this.dir };\n }\n\n // Trim from middle for balance\n const n = ~~((1 - f) * this.v.length);\n const s = ~~(this.v.length / 2 - n / 2);\n\n // Copy only the kept ranges instead of cloning the full arrays and splicing.\n const keep = this.v.length - n;\n const v = new Array(keep);\n const m = new Array(keep);\n const dir = new Array(keep);\n let dst = 0;\n\n for (let i = 0; i < s; i++, dst++) {\n v[dst] = this.v[i];\n m[dst] = this.m[i];\n dir[dst] = this.dir[i];\n }\n\n for (let i = s + n; i < this.v.length; i++, dst++) {\n v[dst] = this.v[i];\n m[dst] = this.m[i];\n dir[dst] = this.dir[i];\n }\n\n\n // We want to add at least two vertices to divide the new edge that appears after trimming, at random distances along its path\n const trimStart = s;\n const trimEnd = s + n;\n const edgeStart = this.v[(trimStart - 1 + this.v.length) % this.v.length];\n const edgeEnd = this.v[trimEnd % this.v.length];\n const edgeVec = { x: edgeEnd.x - edgeStart.x, y: edgeEnd.y - edgeStart.y };\n \n // Insert two new vertices at random positions along the new edge\n const insertCount = 2;\n for (let i = 0; i < insertCount; i++) {\n const t = rr(0.25, 0.75); // Random position between 25% and 75% along the edge\n const newVertex = { x: edgeStart.x + edgeVec.x * t, y: edgeStart.y + edgeVec.y * t };\n const insertIdx = s + i;\n v.splice(insertIdx, 0, newVertex);\n m.splice(insertIdx, 0, rr(0.4, 0.7));\n dir.splice(insertIdx, 0, this.dir[trimStart % this.dir.length]);\n }\n\n return { v, m, dir };\n }\n\n /**\n * Randomly samples a fraction of vertices, keeping their order.\n * Any sampled vertex outside the original polygon is pulled inward.\n * @param {number} [ratio=0.3] - Fraction of vertices to keep.\n * @returns {FillPoly} A new FillPoly with fewer vertices, guaranteed inside the original.\n */\n scatter(ratio = 0.3) {\n const L = this.v.length;\n const keep = Math.max(3, ~~(L * ratio));\n const indices = [];\n const step = L / keep;\n for (let i = 0; i < keep; i++) {\n indices.push(~~(i * step + rr(0, step * 0.8)));\n }\n\n const sv = [],\n sm = [],\n sd = [];\n const mid = this.midP;\n const sides = _polygon.sides;\n\n for (const idx of indices) {\n const j = idx % L;\n let p = this.v[j];\n let outside = false;\n // Bounding box reject — vertex outside AABB is definitely outside polygon\n if (p.x < _bbMinX || p.x > _bbMaxX || p.y < _bbMinY || p.y > _bbMaxY) {\n outside = true;\n } else {\n let crossings = 0;\n for (const [a, b] of sides) {\n const ay = a.y,\n by = b.y;\n if ((ay > p.y) === (by > p.y)) continue;\n const t = (p.y - ay) / (by - ay);\n if (p.x < a.x + t * (b.x - a.x)) crossings++;\n }\n outside = crossings % 2 === 0;\n }\n if (outside) {\n p = {\n x: mid.x + (p.x - mid.x) * rr(0.3, 0.6),\n y: mid.y + (p.y - mid.y) * rr(0.3, 0.6),\n };\n }\n sv.push(p);\n sm.push(this.m[j]);\n sd.push(!this.dir[j]);\n }\n\n return new FillPoly(sv, sm, this.midP, sd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Returns a copy with all bleed directions flipped.\n */\n flipDirs() {\n return new FillPoly(this.v, this.m, this.midP, this.dir.map(d => !d), false, this.sizeX, this.sizeY);\n }\n\n /**\n * Grows (or shrinks) the polygon vertices to simulate watercolor spread.\n * @param {number} [growthFactor=1] - Factor controlling growth.\n * @returns {FillPoly} A new FillPoly with adjusted vertices.\n */\n grow(f = 1) {\n const { v: tr_v, m: tr_m, dir: tr_dir } = this.trim(f);\n const len = tr_v.length;\n\n const outLen = len * 2;\n if (_growInsX.length < len) { _growInsX = new Array(len); _growInsY = new Array(len); }\n if (_growMods.length < outLen) { _growMods = new Array(outLen); _growDirs = new Array(outLen); }\n const insertedX = _growInsX;\n const insertedY = _growInsY;\n const newMods = _growMods;\n const newDirs = _growDirs;\n const bleedDirDeg = State.fill.direction === \"out\" ? -90 : 90;\n\n if (_gaussians[0].length === 0) _fillGaussianPools();\n const gPool = _gaussians[0],\n gPoolLen = gPool.length;\n const g2Pool = _gaussians[1],\n g2PoolLen = g2Pool.length;\n\n let idx = 0;\n let insertedIdx = 0;\n let mod = f === 999 ? rr(0.6, 0.8) : State.fill.bleed_strength;\n\n for (let i = 0; i < len; i++) {\n const cv = tr_v[i];\n const nv = tr_v[i + 1 < len ? i + 1 : 0];\n const mi = tr_m[i];\n const di = tr_dir[i];\n\n if (f < 997) mod = mi;\n\n // If mod is smaller than 0.02, skip growing math and just insert the middle vertex\n if (mod < 0.05) {\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n insertedX[insertedIdx] = (cv.x + nv.x) / 2;\n insertedY[insertedIdx] = (cv.y + nv.y) / 2;\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n insertedIdx++;\n continue;\n }\n\n const rotDeg = (di ? bleedDirDeg : -bleedDirDeg) + rr(-1, 1) * 5;\n const c = cos(rotDeg);\n const s = sin(rotDeg);\n\n const sideX = nv.x - cv.x;\n const sideY = nv.y - cv.y;\n const dirX = c * sideX + s * sideY;\n const dirY = c * sideY - s * sideX;\n\n const d = gPool[~~(rr(0, 1) * gPoolLen)] * rr(0.65, 1.35) * mod;\n const nextMod = mi + g2Pool[~~(rr(0, 1) * g2PoolLen)];\n\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n\n insertedX[insertedIdx] = cv.x + sideX * 0.5 + dirX * d;\n insertedY[insertedIdx] = cv.y + sideY * 0.5 + dirY * d;\n newMods[idx] = nextMod;\n newDirs[idx] = di;\n idx++;\n insertedIdx++;\n }\n\n let fv,\n fm,\n fd;\n \n if (GROW_CAP && idx > GROW_CAP) {\n const step = Math.ceil(idx / GROW_CAP);\n const kept = Math.ceil(idx / step);\n fv = new Array(kept);\n fm = new Array(kept);\n fd = new Array(kept);\n let dst = 0;\n for (let j = 0; j < idx; j += step, dst++) {\n fv[dst] =\n j % 2 === 0\n ? tr_v[j >> 1]\n : { x: insertedX[j >> 1], y: insertedY[j >> 1] };\n fm[dst] = newMods[j];\n fd[dst] = newDirs[j];\n }\n } else {\n fv = new Array(idx);\n for (let j = 0; j < idx; j++) {\n fv[j] =\n j % 2 === 0\n ? tr_v[j >> 1]\n : { x: insertedX[j >> 1], y: insertedY[j >> 1] };\n }\n fm = newMods.slice(0, idx);\n fd = newDirs.slice(0, idx);\n }\n return new FillPoly(fv, fm, this.midP, fd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Fills the polygon with multiple layers to simulate a watercolor effect.\n * @param {Color|string} color - The fill color.\n * @param {number} intensity - Opacity intensity (mapped from 0 to 1).\n * @param {number} tex - Texture factor.\n */\n fill(color, intensity, tex) {\n const numLayers = 20;\n const texture = tex * 3;\n const int = 2 * intensity * (1 + tex / 2);\n\n const switchingToFill = Mix.isBrush !== false;\n Mix.isBrush = false;\n if (switchingToFill) Mix.justChanged = true;\n Mix.blend(color);\n\n const m = getAffineMatrix();\n Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * m.a,\n Density * m.b,\n Density * m.c,\n Density * m.d,\n Density * (m.x + Cwidth / 2),\n Density * (m.y + Cheight / 2),\n );\n\n const fillColorBase = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / `;\n Mix.ctx.strokeStyle = fillColorBase + (0.005 * State.fill.border_strength) + \")\";\n Mix.ctx.lineCap = \"round\";\n\n GROW_CAP = GROW_MAX_VERTS * Math.max(0.1, 2 * State.fill.bleed_strength);\n\n const fillMatrix = Mix.ctx.getTransform();\n const size = Math.max(this.sizeX, this.sizeY);\n const darker = rr(0.15, 0.7);\n let pol = this.grow();\n const sparse = this.scatter(0.1).grow().scatter(0.75).flipDirs();\n let pols;\n\n for (let i = 0; i < numLayers; i++) {\n if (i % 4 === 0) {\n pol = pol.grow();\n }\n\n if (i % 2 === 0) {\n pols = [\n pol.grow(1 - 0.0125 * i),\n pol.grow(0.7 - 0.0125 * i),\n pol.grow(0.4 - 0.0125 * i),\n ];\n }\n\n for (const p of pols) {\n const grown = p.grow(999).grow(997);\n grown.layer(i, size, int, fillColorBase, fillMatrix);\n }\n const sparseLayer = sparse.grow(999).flipDirs().grow(997);\n sparseLayer.layer(i, size, int * texture, fillColorBase, fillMatrix);\n if (i % 2 === 0) {\n const darkerLayer = pol.grow(darker).grow(999);\n darkerLayer.layer(i, size, int * 2, fillColorBase, fillMatrix);\n }\n\n if (i % 8 === 0 || i === numLayers - 1) {\n if (texture !== 0) {\n pol.erase(texture * 3, intensity);\n }\n Mix.blend(color, true);\n }\n }\n\n Mix.ctx.restore();\n }\n\n /**\n * Draws a layer of the fill polygon with stroke and fill.\n * @param {number} i - The layer index.\n */\n layer(i, size, int, colorBase, matrix = null) {\n Mix.ctx.lineWidth = map(i, 0, 24, size / 25, size / 30, true);\n\n Mix.ctx.fillStyle = colorBase + int + \"%)\";\n\n drawPolygon(this.v, matrix);\n Mix.ctx.fill();\n Mix.ctx.stroke();\n }\n\n /**\n * Erases parts of the polygon to create a natural watercolor texture.\n * @param {number} texture - Texture strength factor.\n * @param {number} intensity - Intensity value for size scaling.\n */\n erase(texture, intensity) {\n Mix.ctx.save();\n\n const numCircles = ~~(rr(80, 110) * map(texture, 0, 1, 2, 3.5));\n const halfSizeX = this.sizeX / 1.3;\n const halfSizeY = this.sizeY / 1.3;\n const minSize =\n Math.min(this.sizeX, this.sizeY) * (1.3);\n const minSizeFactor = 0.03 * minSize;\n const maxSizeFactor = 0.45 * minSize;\n const { x: midX, y: midY } = this.midP;\n\n Mix.ctx.globalCompositeOperation = \"destination-out\";\n\n const alpha =\n ((5 - map(intensity, 80, 100, 0.3, 0.7, true)) * texture) / 255;\n Mix.ctx.fillStyle = `rgb(255 0 0 / ${alpha})`;\n Mix.ctx.lineWidth = 0;\n\n for (let i = 0; i < numCircles; i++) {\n const x = midX + gaussian(0, halfSizeX);\n const y = midY + gaussian(0, halfSizeY);\n const radius = rr(minSizeFactor, maxSizeFactor);\n\n Mix.ctx.beginPath();\n circle(x, y, radius);\n if (i % 5 !== 0) {\n Mix.ctx.fill();\n }\n }\n\n Mix.ctx.globalCompositeOperation = \"source-over\";\n Mix.ctx.restore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Extend Polygon and Plot Prototypes for Fill\n// ---------------------------------------------------------------------------\n\n/**\n * Applies a fill effect to the polygon using the current fill state.\n * @param {Color|string} [_color] - The color for the fill.\n * @param {number} [_opacity] - The opacity value.\n * @param {number} [_bleed] - The bleed intensity.\n * @param {number} [_texture] - The texture strength.\n * @param {number} [_border] - The border strength.\n * @param {string} [_direction] - The bleed direction.\n */\nPolygon.prototype.fill = function (\n _color = false,\n _opacity,\n _bleed,\n _texture,\n _border,\n _direction,\n) {\n let state = FillState();\n if (_color) {\n fill(_color, _opacity);\n fillBleed(_bleed, _direction);\n fillTexture(_texture, _border);\n }\n if (state.isActive) {\n isFieldReady();\n createFill(this);\n }\n FillSetState(state);\n};\n\n/**\n * Fills a plot on the canvas by generating a polygon based on the provided coordinates.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - Scaling factor.\n */\nPlot.prototype.fill = function (x, y, scale) {\n if (FillState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n this.pol = this.genPol(\n x,\n y,\n scale,\n State.fill.bleed_strength < 0.06\n ? 0\n : map(State.fill.bleed_strength, 0, 0.6, 0.2, 0.60, true),\n );\n this.pol.fill();\n }\n};\n","\nexport default function earcut(data, holeIndices, dim = 2) {\n\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n let outerNode = linkedList(data, 0, outerLen, dim, true);\n const triangles = [];\n\n if (!outerNode || outerNode.next === outerNode.prev) return triangles;\n\n let minX, minY, invSize;\n\n if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);\n\n // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox\n if (data.length > 80 * dim) {\n minX = data[0];\n minY = data[1];\n let maxX = minX;\n let maxY = minY;\n\n for (let i = dim; i < outerLen; i += dim) {\n const x = data[i];\n const y = data[i + 1];\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n\n // minX, minY and invSize are later used to transform coords into integers for z-order calculation\n invSize = Math.max(maxX - minX, maxY - minY);\n invSize = invSize !== 0 ? 32767 / invSize : 0;\n }\n\n earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);\n\n return triangles;\n}\n\n// create a circular doubly linked list from polygon points in the specified winding order\nfunction linkedList(data, start, end, dim, clockwise) {\n let last;\n\n if (clockwise === (signedArea(data, start, end, dim) > 0)) {\n for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n } else {\n for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n }\n\n if (last && equals(last, last.next)) {\n removeNode(last);\n last = last.next;\n }\n\n return last;\n}\n\n// eliminate colinear or duplicate points\nfunction filterPoints(start, end) {\n if (!start) return start;\n if (!end) end = start;\n\n let p = start,\n again;\n do {\n again = false;\n\n if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {\n removeNode(p);\n p = end = p.prev;\n if (p === p.next) break;\n again = true;\n\n } else {\n p = p.next;\n }\n } while (again || p !== end);\n\n return end;\n}\n\n// main ear slicing loop which triangulates a polygon (given as a linked list)\nfunction earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {\n if (!ear) return;\n\n // interlink polygon nodes in z-order\n if (!pass && invSize) indexCurve(ear, minX, minY, invSize);\n\n let stop = ear;\n\n // iterate through ears, slicing them one by one\n while (ear.prev !== ear.next) {\n const prev = ear.prev;\n const next = ear.next;\n\n if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {\n triangles.push(prev.i, ear.i, next.i); // cut off the triangle\n\n removeNode(ear);\n\n // skipping the next vertex leads to less sliver triangles\n ear = next.next;\n stop = next.next;\n\n continue;\n }\n\n ear = next;\n\n // if we looped through the whole remaining polygon and can't find any more ears\n if (ear === stop) {\n // try filtering points and slicing again\n if (!pass) {\n earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);\n\n // if this didn't work, try curing all small self-intersections locally\n } else if (pass === 1) {\n ear = cureLocalIntersections(filterPoints(ear), triangles);\n earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);\n\n // as a last resort, try splitting the remaining polygon into two\n } else if (pass === 2) {\n splitEarcut(ear, triangles, dim, minX, minY, invSize);\n }\n\n break;\n }\n }\n}\n\n// check whether a polygon node forms a valid ear with adjacent nodes\nfunction isEar(ear) {\n const a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n // now make sure we don't have other points inside the potential ear\n const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox\n const x0 = Math.min(ax, bx, cx),\n y0 = Math.min(ay, by, cy),\n x1 = Math.max(ax, bx, cx),\n y1 = Math.max(ay, by, cy);\n\n let p = c.next;\n while (p !== a) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&\n area(p.prev, p, p.next) >= 0) return false;\n p = p.next;\n }\n\n return true;\n}\n\nfunction isEarHashed(ear, minX, minY, invSize) {\n const a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox\n const x0 = Math.min(ax, bx, cx),\n y0 = Math.min(ay, by, cy),\n x1 = Math.max(ax, bx, cx),\n y1 = Math.max(ay, by, cy);\n\n // z-order range for the current triangle bbox;\n const minZ = zOrder(x0, y0, minX, minY, invSize),\n maxZ = zOrder(x1, y1, minX, minY, invSize);\n\n let p = ear.prevZ,\n n = ear.nextZ;\n\n // look for points inside the triangle in both directions\n while (p && p.z >= minZ && n && n.z <= maxZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n // look for remaining points in decreasing z-order\n while (p && p.z >= minZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n }\n\n // look for remaining points in increasing z-order\n while (n && n.z <= maxZ) {\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n return true;\n}\n\n// go through all polygon nodes and cure small local self-intersections\nfunction cureLocalIntersections(start, triangles) {\n let p = start;\n do {\n const a = p.prev,\n b = p.next.next;\n\n if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {\n\n triangles.push(a.i, p.i, b.i);\n\n // remove two nodes involved\n removeNode(p);\n removeNode(p.next);\n\n p = start = b;\n }\n p = p.next;\n } while (p !== start);\n\n return filterPoints(p);\n}\n\n// try splitting polygon into two and triangulate them independently\nfunction splitEarcut(start, triangles, dim, minX, minY, invSize) {\n // look for a valid diagonal that divides the polygon into two\n let a = start;\n do {\n let b = a.next.next;\n while (b !== a.prev) {\n if (a.i !== b.i && isValidDiagonal(a, b)) {\n // split the polygon in two by the diagonal\n let c = splitPolygon(a, b);\n\n // filter colinear points around the cuts\n a = filterPoints(a, a.next);\n c = filterPoints(c, c.next);\n\n // run earcut on each half\n earcutLinked(a, triangles, dim, minX, minY, invSize, 0);\n earcutLinked(c, triangles, dim, minX, minY, invSize, 0);\n return;\n }\n b = b.next;\n }\n a = a.next;\n } while (a !== start);\n}\n\n// link every hole into the outer loop, producing a single-ring polygon without holes\nfunction eliminateHoles(data, holeIndices, outerNode, dim) {\n const queue = [];\n\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n const list = linkedList(data, start, end, dim, false);\n if (list === list.next) list.steiner = true;\n queue.push(getLeftmost(list));\n }\n\n queue.sort(compareXYSlope);\n\n // process holes from left to right\n for (let i = 0; i < queue.length; i++) {\n outerNode = eliminateHole(queue[i], outerNode);\n }\n\n return outerNode;\n}\n\nfunction compareXYSlope(a, b) {\n let result = a.x - b.x;\n // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find\n // the bridge to the outer shell is always the point that they meet at.\n if (result === 0) {\n result = a.y - b.y;\n if (result === 0) {\n const aSlope = (a.next.y - a.y) / (a.next.x - a.x);\n const bSlope = (b.next.y - b.y) / (b.next.x - b.x);\n result = aSlope - bSlope;\n }\n }\n return result;\n}\n\n// find a bridge between vertices that connects hole with an outer ring and link it\nfunction eliminateHole(hole, outerNode) {\n const bridge = findHoleBridge(hole, outerNode);\n if (!bridge) {\n return outerNode;\n }\n\n const bridgeReverse = splitPolygon(bridge, hole);\n\n // filter collinear points around the cuts\n filterPoints(bridgeReverse, bridgeReverse.next);\n return filterPoints(bridge, bridge.next);\n}\n\n// David Eberly's algorithm for finding a bridge between hole and outer polygon\nfunction findHoleBridge(hole, outerNode) {\n let p = outerNode;\n const hx = hole.x;\n const hy = hole.y;\n let qx = -Infinity;\n let m;\n\n // find a segment intersected by a ray from the hole's leftmost point to the left;\n // segment's endpoint with lesser x will be potential connection point\n // unless they intersect at a vertex, then choose the vertex\n if (equals(hole, p)) return p;\n do {\n if (equals(hole, p.next)) return p.next;\n else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {\n const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);\n if (x <= hx && x > qx) {\n qx = x;\n m = p.x < p.next.x ? p : p.next;\n if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint\n }\n }\n p = p.next;\n } while (p !== outerNode);\n\n if (!m) return null;\n\n // look for points inside the triangle of hole point, segment intersection and endpoint;\n // if there are no points found, we have a valid connection;\n // otherwise choose the point of the minimum angle with the ray as connection point\n\n const stop = m;\n const mx = m.x;\n const my = m.y;\n let tanMin = Infinity;\n\n p = m;\n\n do {\n if (hx >= p.x && p.x >= mx && hx !== p.x &&\n pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {\n\n const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential\n\n if (locallyInside(p, hole) &&\n (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {\n m = p;\n tanMin = tan;\n }\n }\n\n p = p.next;\n } while (p !== stop);\n\n return m;\n}\n\n// whether sector in vertex m contains sector in vertex p in the same coordinates\nfunction sectorContainsSector(m, p) {\n return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;\n}\n\n// interlink polygon nodes in z-order\nfunction indexCurve(start, minX, minY, invSize) {\n let p = start;\n do {\n if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);\n p.prevZ = p.prev;\n p.nextZ = p.next;\n p = p.next;\n } while (p !== start);\n\n p.prevZ.nextZ = null;\n p.prevZ = null;\n\n sortLinked(p);\n}\n\n// Simon Tatham's linked list merge sort algorithm\n// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html\nfunction sortLinked(list) {\n let numMerges;\n let inSize = 1;\n\n do {\n let p = list;\n let e;\n list = null;\n let tail = null;\n numMerges = 0;\n\n while (p) {\n numMerges++;\n let q = p;\n let pSize = 0;\n for (let i = 0; i < inSize; i++) {\n pSize++;\n q = q.nextZ;\n if (!q) break;\n }\n let qSize = inSize;\n\n while (pSize > 0 || (qSize > 0 && q)) {\n\n if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {\n e = p;\n p = p.nextZ;\n pSize--;\n } else {\n e = q;\n q = q.nextZ;\n qSize--;\n }\n\n if (tail) tail.nextZ = e;\n else list = e;\n\n e.prevZ = tail;\n tail = e;\n }\n\n p = q;\n }\n\n tail.nextZ = null;\n inSize *= 2;\n\n } while (numMerges > 1);\n\n return list;\n}\n\n// z-order of a point given coords and inverse of the longer side of data bbox\nfunction zOrder(x, y, minX, minY, invSize) {\n // coords are transformed into non-negative 15-bit integer range\n x = (x - minX) * invSize | 0;\n y = (y - minY) * invSize | 0;\n\n x = (x | (x << 8)) & 0x00FF00FF;\n x = (x | (x << 4)) & 0x0F0F0F0F;\n x = (x | (x << 2)) & 0x33333333;\n x = (x | (x << 1)) & 0x55555555;\n\n y = (y | (y << 8)) & 0x00FF00FF;\n y = (y | (y << 4)) & 0x0F0F0F0F;\n y = (y | (y << 2)) & 0x33333333;\n y = (y | (y << 1)) & 0x55555555;\n\n return x | (y << 1);\n}\n\n// find the leftmost node of a polygon ring\nfunction getLeftmost(start) {\n let p = start,\n leftmost = start;\n do {\n if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;\n p = p.next;\n } while (p !== start);\n\n return leftmost;\n}\n\n// check if a point lies within a convex triangle\nfunction pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {\n return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&\n (ax - px) * (by - py) >= (bx - px) * (ay - py) &&\n (bx - px) * (cy - py) >= (cx - px) * (by - py);\n}\n\n// check if a point lies within a convex triangle but false if its equal to the first point of the triangle\nfunction pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {\n return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);\n}\n\n// check if a diagonal between two polygon nodes is valid (lies in polygon interior)\nfunction isValidDiagonal(a, b) {\n return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges\n (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible\n (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors\n equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case\n}\n\n// signed area of a triangle\nfunction area(p, q, r) {\n return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);\n}\n\n// check if two points are equal\nfunction equals(p1, p2) {\n return p1.x === p2.x && p1.y === p2.y;\n}\n\n// check if two segments intersect\nfunction intersects(p1, q1, p2, q2) {\n const o1 = sign(area(p1, q1, p2));\n const o2 = sign(area(p1, q1, q2));\n const o3 = sign(area(p2, q2, p1));\n const o4 = sign(area(p2, q2, q1));\n\n if (o1 !== o2 && o3 !== o4) return true; // general case\n\n if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1\n if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1\n if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2\n if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2\n\n return false;\n}\n\n// for collinear points p, q, r, check if point q lies on segment pr\nfunction onSegment(p, q, r) {\n return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);\n}\n\nfunction sign(num) {\n return num > 0 ? 1 : num < 0 ? -1 : 0;\n}\n\n// check if a polygon diagonal intersects any polygon segments\nfunction intersectsPolygon(a, b) {\n let p = a;\n do {\n if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&\n intersects(p, p.next, a, b)) return true;\n p = p.next;\n } while (p !== a);\n\n return false;\n}\n\n// check if a polygon diagonal is locally inside the polygon\nfunction locallyInside(a, b) {\n return area(a.prev, a, a.next) < 0 ?\n area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :\n area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;\n}\n\n// check if the middle point of a polygon diagonal is inside the polygon\nfunction middleInside(a, b) {\n let p = a;\n let inside = false;\n const px = (a.x + b.x) / 2;\n const py = (a.y + b.y) / 2;\n do {\n if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&\n (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))\n inside = !inside;\n p = p.next;\n } while (p !== a);\n\n return inside;\n}\n\n// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;\n// if one belongs to the outer ring and another to a hole, it merges it into a single ring\nfunction splitPolygon(a, b) {\n const a2 = createNode(a.i, a.x, a.y),\n b2 = createNode(b.i, b.x, b.y),\n an = a.next,\n bp = b.prev;\n\n a.next = b;\n b.prev = a;\n\n a2.next = an;\n an.prev = a2;\n\n b2.next = a2;\n a2.prev = b2;\n\n bp.next = b2;\n b2.prev = bp;\n\n return b2;\n}\n\n// create a node and optionally link it with previous one (in a circular doubly linked list)\nfunction insertNode(i, x, y, last) {\n const p = createNode(i, x, y);\n\n if (!last) {\n p.prev = p;\n p.next = p;\n\n } else {\n p.next = last.next;\n p.prev = last;\n last.next.prev = p;\n last.next = p;\n }\n return p;\n}\n\nfunction removeNode(p) {\n p.next.prev = p.prev;\n p.prev.next = p.next;\n\n if (p.prevZ) p.prevZ.nextZ = p.nextZ;\n if (p.nextZ) p.nextZ.prevZ = p.prevZ;\n}\n\nfunction createNode(i, x, y) {\n return {\n i, // vertex index in coordinates array\n x, y, // vertex coordinates\n prev: null, // previous and next vertex nodes in a polygon ring\n next: null,\n z: 0, // z-order curve value\n prevZ: null, // previous and next nodes in z-order\n nextZ: null,\n steiner: false // indicates whether this is a steiner point\n };\n}\n\n// return a percentage difference between the polygon area and its triangulation area;\n// used to verify correctness of triangulation\nexport function deviation(data, holeIndices, dim, triangles) {\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n\n let polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));\n if (hasHoles) {\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n polygonArea -= Math.abs(signedArea(data, start, end, dim));\n }\n }\n\n let trianglesArea = 0;\n for (let i = 0; i < triangles.length; i += 3) {\n const a = triangles[i] * dim;\n const b = triangles[i + 1] * dim;\n const c = triangles[i + 2] * dim;\n trianglesArea += Math.abs(\n (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -\n (data[a] - data[b]) * (data[c + 1] - data[a + 1]));\n }\n\n return polygonArea === 0 && trianglesArea === 0 ? 0 :\n Math.abs((trianglesArea - polygonArea) / polygonArea);\n}\n\nfunction signedArea(data, start, end, dim) {\n let sum = 0;\n for (let i = start, j = end - dim; i < end; i += dim) {\n sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);\n j = i;\n }\n return sum;\n}\n\n// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts\nexport function flatten(data) {\n const vertices = [];\n const holes = [];\n const dimensions = data[0][0].length;\n let holeIndex = 0;\n let prevLen = 0;\n\n for (const ring of data) {\n for (const p of ring) {\n for (let d = 0; d < dimensions; d++) vertices.push(p[d]);\n }\n if (prevLen) {\n holeIndex += prevLen;\n holes.push(holeIndex);\n }\n prevLen = ring.length;\n }\n return {vertices, holes, dimensions};\n}\n","// =============================================================================\n// Module: Wash\n// =============================================================================\n/**\n * Minimal stateful API for the `wash()` fill modifier.\n */\n\nimport earcut from \"earcut\";\nimport { Renderer, Cwidth, Cheight, isCanvasReady } from \"../core/target.js\";\nimport { State, flushActiveComposite } from \"../core/color.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { getAffineMatrix } from \"../core/runtime.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport { createColor } from \"../core/runtime.js\";\nimport { resetDirectShaderTracking } from \"../core/renderer_runtime.js\";\n\nlet gl = null;\nlet washProgram = null;\nlet washVao = null;\nlet washBuffer = null;\nlet washProjection = null;\nlet loadedWidth = 0;\nlet loadedHeight = 0;\nlet washGpuBufferSize = 0;\n\nconst WashAttr = {};\nconst WashUniform = {};\n\nconst washVertSrc = `#version 300 es\nin vec2 a_position;\nuniform mat4 u_matrix;\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n}`;\n\nconst washFragSrc = `#version 300 es\nprecision highp float;\nuniform vec4 u_color;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(u_color.rgb * u_color.a, u_color.a);\n}`;\n\nState.wash = {\n color: null,\n opacity: 150,\n isActive: false,\n};\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Enables wash mode with a color and opacity.\n *\n * @param {number|string|Color} a - Either the red component, a CSS color string, or a Color object.\n * @param {number} [b] - The green component or the opacity if using grayscale.\n * @param {number} [c] - The blue component.\n * @param {number} [d] - The opacity.\n */\nexport function wash(a, b, c, d) {\n isCanvasReady();\n State.wash.opacity = (arguments.length < 4 ? b : d) ?? 150;\n State.wash.color = arguments.length < 3 ? createColor(a) : createColor(a, b, c);\n State.wash.isActive = true;\n}\n\n/**\n * Disables wash mode for subsequent drawing operations.\n */\nexport function noWash() {\n State.wash.isActive = false;\n}\n\n// =============================================================================\n// GL helpers\n// =============================================================================\n\n/**\n * Lazily creates the reusable program/buffer state for solid wash drawing and\n * refreshes the orthographic projection when the active target size changes.\n */\nfunction ensureWashReady() {\n const nextGl = Renderer.drawingContext;\n const sizeChanged = loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (!washProjection || sizeChanged) {\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n washProjection = new Float32Array([\n 2 / loadedWidth,\n 0,\n 0,\n 0,\n 0,\n -2 / loadedHeight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n 1,\n 0,\n 1,\n ]);\n }\n\n if (gl === nextGl && washProgram && washVao && washBuffer) return;\n\n gl = nextGl;\n washProgram = createProgram(gl, washVertSrc, washFragSrc);\n WashAttr.a_position = gl.getAttribLocation(washProgram, \"a_position\");\n WashUniform.u_matrix = gl.getUniformLocation(washProgram, \"u_matrix\");\n WashUniform.u_color = gl.getUniformLocation(washProgram, \"u_color\");\n\n washVao = gl.createVertexArray();\n gl.bindVertexArray(washVao);\n\n washBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, 0, gl.DYNAMIC_DRAW);\n washGpuBufferSize = 0;\n\n gl.enableVertexAttribArray(WashAttr.a_position);\n gl.vertexAttribPointer(WashAttr.a_position, 2, gl.FLOAT, false, 8, 0);\n\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n}\n\n/**\n * Applies the current runtime affine transform and converts the result into\n * the screen-space coordinates used by the direct GL wash pipeline.\n *\n * @param {number} x - The source x-coordinate in brush drawing space.\n * @param {number} y - The source y-coordinate in brush drawing space.\n * @returns {[number, number]} The transformed screen-space position.\n */\nfunction transformVertexToScreen(x, y) {\n const m = getAffineMatrix();\n return [\n m.a * x + m.c * y + m.x + loadedWidth / 2,\n m.b * x + m.d * y + m.y + loadedHeight / 2,\n ];\n}\n\n/**\n * Triangulates a polygon in local space and returns the transformed triangle\n * vertex buffer ready for upload to the GPU.\n *\n * @param {Polygon} polygon - The polygon to triangulate.\n * @returns {{ triangles: Float32Array, vertexCount: number }} Screen-space\n * triangle vertices plus the number of vertices to draw.\n */\nfunction buildTriangleBuffer(polygon) {\n const flat = new Float32Array(polygon.vertices.length * 2);\n for (let i = 0; i < polygon.vertices.length; i++) {\n const vertex = polygon.vertices[i];\n flat[i * 2] = vertex.x;\n flat[i * 2 + 1] = vertex.y;\n }\n\n const indices = earcut(flat);\n const triangles = new Float32Array(indices.length * 2);\n for (let i = 0; i < indices.length; i++) {\n const idx = indices[i];\n const [screenX, screenY] = transformVertexToScreen(flat[idx * 2], flat[idx * 2 + 1]);\n triangles[i * 2] = screenX;\n triangles[i * 2 + 1] = screenY;\n }\n\n return {\n triangles,\n vertexCount: indices.length,\n };\n}\n\n/**\n * Draws a triangulated solid wash directly to the current GL target.\n *\n * @param {Polygon} polygon - The polygon to fill with the current wash state.\n */\nfunction drawWashPolygon(polygon) {\n if (!State.wash?.isActive || !State.wash.color || polygon.vertices.length < 3) return;\n\n flushActiveComposite();\n ensureWashReady();\n const { triangles, vertexCount } = buildTriangleBuffer(polygon);\n const byteCount = triangles.byteLength;\n gl.useProgram(washProgram);\n gl.enable(gl.BLEND);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n gl.bindVertexArray(washVao);\n gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);\n if (byteCount > washGpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, triangles, gl.DYNAMIC_DRAW);\n washGpuBufferSize = byteCount;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, triangles);\n }\n const color = State.wash.color._array;\n gl.uniformMatrix4fv(WashUniform.u_matrix, false, washProjection);\n gl.uniform4f(\n WashUniform.u_color,\n color[0],\n color[1],\n color[2],\n State.wash.opacity / 255,\n );\n\n gl.drawArrays(gl.TRIANGLES, 0, vertexCount);\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n resetDirectShaderTracking(Renderer, gl);\n}\n\n// =============================================================================\n// Prototype methods\n// =============================================================================\n\n/**\n * Applies a direct GL wash fill to the polygon using the current wash state.\n *\n * @param {Color|string|false} [_color] - Optional override color for this call.\n * @param {number} [_opacity] - Optional override opacity for this call.\n */\nPolygon.prototype.wash = function (_color = false, _opacity) {\n const state = { ...State.wash };\n if (_color !== false) wash(_color, _opacity);\n\n if (State.wash.isActive) {\n drawWashPolygon(this);\n }\n\n State.wash = { ...state };\n};\n\n/**\n * Applies wash to a plot by first generating the plot polygon, mirroring the\n * existing fill-path behavior, and then drawing that polygon with wash.\n *\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\nPlot.prototype.wash = function (x, y, scale) {\n if (!State.wash?.isActive) return;\n if (this.origin) {\n x = this.origin[0];\n y = this.origin[1];\n scale = 1;\n }\n this.pol = this.genPol(x, y, scale, 0, -1);\n this.pol.wash();\n};\n","// =============================================================================\n// Adapter: Standalone Renderer Hooks\n// =============================================================================\n\nimport { Cwidth, Cheight, Density } from \"../../core/target.js\";\nimport { setRendererRuntime } from \"../../core/renderer_runtime.js\";\n\nfunction beginDirectMaskDraw(_renderer, gl, target) {\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n if (hadDepthTest) gl.disable(gl.DEPTH_TEST);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, target.framebuffer);\n gl.viewport(0, 0, target.width * target.density, target.height * target.density);\n\n return { hadDepthTest };\n}\n\nfunction endDirectMaskDraw(renderer, gl, state) {\n if (state?.hadDepthTest) gl.enable(gl.DEPTH_TEST);\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.viewport(\n 0,\n 0,\n Math.max(1, Math.round(Cwidth * Density)),\n Math.max(1, Math.round(Cheight * Density)),\n );\n}\n\nfunction resetStandaloneShaderTracking(_renderer, gl) {\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n}\n\nexport function initStandaloneRendererRuntime() {\n setRendererRuntime({\n beginDirectMaskDraw,\n endDirectMaskDraw,\n resetDirectShaderTracking: resetStandaloneShaderTracking,\n });\n}\n","// =============================================================================\n// Adapter: Standalone Compositor Hooks\n// =============================================================================\n\nimport { createProgram } from \"../../core/gl/utils.js\";\nimport {\n setCompositorRuntime,\n blitDefaultFramebufferSource,\n} from \"../../core/compositor_runtime.js\";\n\nfunction clearTarget(renderer, target, isFramebufferTarget) {\n if (!target) return;\n\n if (isFramebufferTarget(target)) {\n const gl = renderer.drawingContext;\n const previousFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);\n const previousViewport = gl.getParameter(gl.VIEWPORT);\n gl.bindFramebuffer(gl.FRAMEBUFFER, target.framebuffer);\n gl.viewport(0, 0, target.width * target.density, target.height * target.density);\n gl.clearColor(0, 0, 0, 0);\n gl.clear(gl.COLOR_BUFFER_BIT);\n gl.bindFramebuffer(gl.FRAMEBUFFER, previousFramebuffer);\n gl.viewport(\n previousViewport[0],\n previousViewport[1],\n previousViewport[2],\n previousViewport[3],\n );\n return;\n }\n\n const ctx = target.drawingContext;\n ctx.save();\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.clearRect(0, 0, target.width, target.height);\n ctx.restore();\n}\n\nfunction makeShader(gl, vertSrc, fragSrc) {\n const program = createProgram(gl, vertSrc, fragSrc);\n const uniformCache = new Map();\n\n // Persistent VAO for fullscreen-triangle draws (avoids create/delete per pass)\n const quadVao = gl.createVertexArray();\n\n const getUniformLocation = (name) => {\n if (!uniformCache.has(name)) {\n uniformCache.set(name, gl.getUniformLocation(program, name));\n }\n return uniformCache.get(name);\n };\n\n // Pre-cache sampler and color uniform locations (called every blend pass)\n const loc_source = gl.getUniformLocation(program, \"u_source\");\n const loc_mask = gl.getUniformLocation(program, \"u_mask\");\n const loc_color = gl.getUniformLocation(program, \"u_color\");\n\n return {\n program,\n quadVao,\n loc_source,\n loc_mask,\n loc_color,\n setUniform(name, value) {\n const location = getUniformLocation(name);\n if (!location) return;\n if (typeof value === \"boolean\") {\n gl.uniform1i(location, value ? 1 : 0);\n return;\n }\n if (typeof value === \"number\") {\n gl.uniform1f(location, value);\n return;\n }\n if (Array.isArray(value)) {\n if (value.length === 3) gl.uniform3f(location, value[0], value[1], value[2]);\n else if (value.length === 4) gl.uniform4f(location, value[0], value[1], value[2], value[3]);\n return;\n }\n },\n };\n}\n\nfunction ensureBlendShaderProgram(renderer, vertSrc, fragSrc) {\n renderer.shaderProgram ??= makeShader(renderer.drawingContext, vertSrc, fragSrc);\n return renderer.shaderProgram;\n}\n\nfunction createFramebufferTexture(gl, width, height) {\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(\n gl.TEXTURE_2D,\n 0,\n gl.RGBA,\n width,\n height,\n 0,\n gl.RGBA,\n gl.UNSIGNED_BYTE,\n null,\n );\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.bindTexture(gl.TEXTURE_2D, null);\n return texture;\n}\n\nfunction createFramebuffer(renderer, options) {\n const gl = renderer.drawingContext;\n const density = options.density ?? 1;\n const framebuffer = gl.createFramebuffer();\n const width = Math.max(1, options.width);\n const height = Math.max(1, options.height);\n const pixelWidth = Math.max(1, Math.round(width * density));\n const pixelHeight = Math.max(1, Math.round(height * density));\n const colorTexture = createFramebufferTexture(gl, pixelWidth, pixelHeight);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);\n gl.framebufferTexture2D(\n gl.FRAMEBUFFER,\n gl.COLOR_ATTACHMENT0,\n gl.TEXTURE_2D,\n colorTexture,\n 0,\n );\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n\n return {\n __brushFramebuffer: true,\n framebuffer,\n colorTexture,\n width,\n height,\n density,\n pixelDensity: () => density,\n remove() {\n gl.deleteFramebuffer(framebuffer);\n gl.deleteTexture(colorTexture);\n },\n };\n}\n\nfunction ensureBlendSourceFramebuffer(\n renderer,\n currentFramebuffer,\n width,\n height,\n density,\n) {\n currentFramebuffer?.remove?.();\n return createFramebuffer(renderer, {\n width,\n height,\n density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n}\n\nfunction runBlendShaderPass({\n renderer,\n shader,\n source,\n mask,\n color,\n isBrushMask,\n dirtyRect,\n targetIsFramebuffer,\n withScissor,\n}) {\n const gl = renderer.drawingContext;\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n const previousFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);\n const previousProgram = gl.getParameter(gl.CURRENT_PROGRAM);\n const previousVao = gl.getParameter(gl.VERTEX_ARRAY_BINDING);\n\n gl.bindVertexArray(shader.quadVao);\n gl.useProgram(shader.program);\n gl.disable(gl.DEPTH_TEST);\n gl.enable(gl.BLEND);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, source.colorTexture);\n gl.uniform1i(shader.loc_source, 0);\n\n gl.activeTexture(gl.TEXTURE1);\n gl.bindTexture(gl.TEXTURE_2D, mask.colorTexture);\n gl.uniform1i(shader.loc_mask, 1);\n\n shader.setUniform(\"u_targetIsFramebuffer\", targetIsFramebuffer);\n shader.setUniform(\"u_isBrush\", isBrushMask);\n gl.uniform3f(shader.loc_color, color[0], color[1], color[2]);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n withScissor(\n gl,\n dirtyRect,\n () => {\n gl.drawArrays(gl.TRIANGLES, 0, 3);\n },\n !targetIsFramebuffer,\n );\n\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.activeTexture(gl.TEXTURE0);\n gl.bindVertexArray(previousVao);\n gl.useProgram(previousProgram);\n gl.bindFramebuffer(gl.FRAMEBUFFER, previousFramebuffer);\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n}\n\nfunction blitSourceToFramebuffer(args) {\n return blitDefaultFramebufferSource(args);\n}\n\nexport function initStandaloneCompositorRuntime() {\n setCompositorRuntime({\n clearTarget,\n ensureBlendShaderProgram,\n ensureBlendSourceFramebuffer,\n createFramebuffer,\n runBlendShaderPass,\n blitSourceToFramebuffer,\n });\n}\n","// =============================================================================\n// Adapter: Standalone Stroke Hooks\n// =============================================================================\n\nimport { create2DCanvas, get2DContext } from \"../../core/compositor_runtime.js\";\nimport { setStrokeRuntime } from \"../../stroke/runtime.js\";\n\nfunction cssColor(value) {\n if (typeof value === \"number\") {\n const c = Math.max(0, Math.min(255, value));\n return `rgb(${c} ${c} ${c})`;\n }\n return value ?? \"black\";\n}\n\nfunction buildTipSurface(canvas) {\n const ctx = get2DContext(canvas, true);\n const surface = {\n canvas,\n drawingContext: ctx,\n width: canvas.width,\n height: canvas.height,\n pixels: null,\n _fillStyle: \"#ffffff\",\n _strokeStyle: \"transparent\",\n _lineWidth: 1,\n\n pixelDensity() {\n return 1;\n },\n\n background(value) {\n ctx.save();\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.fillStyle = cssColor(value);\n ctx.fillRect(0, 0, canvas.width, canvas.height);\n ctx.restore();\n },\n\n noSmooth() {\n ctx.imageSmoothingEnabled = false;\n },\n\n push() {\n ctx.save();\n },\n\n pop() {\n ctx.restore();\n },\n\n translate(x, y) {\n ctx.translate(x, y);\n },\n\n scale(x, y = x) {\n ctx.scale(x, y);\n },\n\n rotate(angle) {\n ctx.rotate(angle);\n },\n\n noStroke() {\n surface._strokeStyle = \"transparent\";\n },\n\n stroke(value) {\n surface._strokeStyle = cssColor(value);\n },\n\n noFill() {\n surface._fillStyle = \"transparent\";\n },\n\n fill(value) {\n surface._fillStyle = cssColor(value);\n },\n\n strokeWeight(value) {\n surface._lineWidth = value;\n },\n\n rect(x, y, w, h) {\n ctx.beginPath();\n ctx.rect(x, y, w, h);\n surface._paint();\n },\n\n circle(x, y, d) {\n ctx.beginPath();\n ctx.arc(x, y, d / 2, 0, Math.PI * 2);\n surface._paint();\n },\n\n ellipse(x, y, w, h) {\n ctx.beginPath();\n ctx.ellipse(x, y, w / 2, h / 2, 0, 0, Math.PI * 2);\n surface._paint();\n },\n\n line(x1, y1, x2, y2) {\n ctx.beginPath();\n ctx.moveTo(x1, y1);\n ctx.lineTo(x2, y2);\n ctx.strokeStyle = surface._strokeStyle;\n ctx.lineWidth = surface._lineWidth;\n ctx.stroke();\n },\n\n beginShape() {\n ctx.beginPath();\n surface._shapeStarted = false;\n },\n\n vertex(x, y) {\n if (!surface._shapeStarted) {\n ctx.moveTo(x, y);\n surface._shapeStarted = true;\n } else {\n ctx.lineTo(x, y);\n }\n },\n\n endShape(close = false) {\n if (close) ctx.closePath();\n surface._paint();\n },\n\n loadPixels() {\n surface.pixels = ctx.getImageData(0, 0, canvas.width, canvas.height).data;\n },\n\n updatePixels() {\n const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);\n imageData.data.set(surface.pixels);\n ctx.putImageData(imageData, 0, 0);\n },\n\n _paint() {\n if (surface._fillStyle !== \"transparent\") {\n ctx.fillStyle = surface._fillStyle;\n ctx.fill();\n }\n if (surface._strokeStyle !== \"transparent\") {\n ctx.strokeStyle = surface._strokeStyle;\n ctx.lineWidth = surface._lineWidth;\n ctx.stroke();\n }\n },\n };\n\n return surface;\n}\n\nfunction createTipSurface(width, height) {\n return buildTipSurface(create2DCanvas(width, height, true));\n}\n\nfunction loadImageTip(src, imageToWhite) {\n return new Promise((resolve, reject) => {\n const NativeImage = globalThis.Image;\n if (!NativeImage) {\n reject(new Error(\"Standalone image brush loading requires Image support.\"));\n return;\n }\n\n const nativeImg = new NativeImage();\n nativeImg.onload = () => {\n const surface = buildTipSurface(\n create2DCanvas(nativeImg.naturalWidth, nativeImg.naturalHeight, true),\n );\n surface.drawingContext.drawImage(nativeImg, 0, 0);\n imageToWhite(surface);\n resolve(surface);\n };\n nativeImg.onerror = () =>\n reject(new Error(`Failed to load image tip: ${src}`));\n nativeImg.crossOrigin = \"anonymous\";\n nativeImg.src = src;\n });\n}\n\nexport function initStandaloneStrokeRuntime() {\n setStrokeRuntime({\n createTipSurface,\n loadImageTip,\n });\n}\n","/**\n * @fileoverview Standalone entry point for brush.\n */\n\nexport * from \"./adapters/standalone/runtime.js\";\nexport * from \"./adapters/standalone/frame.js\";\nexport { createCanvas } from \"./adapters/standalone/target.js\";\nexport * from \"./index.shared.js\";\n\nimport { initStandaloneTargetRuntime } from \"./adapters/standalone/target.js\";\nimport { initStandaloneRendererRuntime } from \"./adapters/standalone/renderer.js\";\nimport { initStandaloneCompositorRuntime } from \"./adapters/standalone/compositor.js\";\nimport { initStandaloneStrokeRuntime } from \"./adapters/standalone/stroke.js\";\nimport { initStandaloneRuntime } from \"./adapters/standalone/runtime.js\";\n\ninitStandaloneTargetRuntime();\ninitStandaloneRuntime();\ninitStandaloneRendererRuntime();\ninitStandaloneCompositorRuntime();\ninitStandaloneStrokeRuntime();\n"],"names":["identityMatrix","a","b","c","d","x","y","Cwidth","Cheight","Renderer","Density","usesRadians","fromDegrees","angle","createColor","Error","getAffineMatrix","targetRuntime","load","syncDensity","isCanvasReady","instance","inst","activateInstance","deactivateInstance","getActiveFramebuffer","isFramebufferTarget","setTargetState","state","Instance","target","expandDirtyRect","rect","padding","minX","minY","maxX","maxY","create2DCanvas","width","height","willReadFrequently","canvas","OffscreenCanvas","element","document","createElement","drawingContext","getContext","undefined","compositorRuntime","clearTarget","ensureBlendShaderProgram","ensureBlendSourceFramebuffer","createFramebuffer","runBlendShaderPass","blitSourceToFramebuffer","args","strokeComposite","fillComposite","clearRenderTarget","getTargetPixelSize","Math","max","round","normalizeDirtyRect","floor","min","ceil","clampDirtyRect","getFullDirtyRect","getFullRect","toScissorBox","flipY","normalized","withScissor","gl","draw","box","enable","SCISSOR_TEST","scissor","disable","State","isMixReady","loaded","Mix","isBlending","cachedColor","markDirtyRect","dirtyRect","isDrawn","clearMask","composite","this","glMask","getCompositeRect","isBrushMask","needsBlendSourceFramebuffer","blendSourceFramebuffer","pixelDensity","ensureResources","fillResources","mask","ctx","blend","_color","_isLast","isBrush","otherMask","nextColor","_array","colorChanged","justChanged","applyShader","shader","shaderProgram","activeFramebuffer","source","renderer","sourceTarget","sourceFramebuffer","targetIsFramebuffer","shaderMask","getShaderMask","color","flushActiveComposite","buffer","loadTarget","SQRT3","sqrt","F2","G2","fastFloor","grad2","Float64Array","createNoise2D","random","perm","p","Uint8Array","i","tableSize","r","aux","buildPermutationTable","permGrad2x","map","v","permGrad2y","n0","n1","n2","s","j","t","x0","y0","i1","j1","x1","y1","x2","y2","ii","jj","t0","gi0","t1","gi1","t2","gi2","prng_alea","seed","opts","xg","AleaGen","prng","next","double","int32","quick","constructor","Date","n","mash","data","String","length","charCodeAt","h","s0","s1","s2","copy","f","rng","rng2","_seedCallbacks","_onSeed","cb","push","callback","noise","noise2","noiseSeed","rr","e","rr2","rArray","array","randInt","randInt2","gaussian","mean","stdev","u","log","cos","weightedRand","weights","totalWeight","entries","key","cumulative","rnd","isNaN","parseInt","value","withinBounds","constrain","low","high","nAngle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","fill","NaN","sLookup","idx","sin","toDegrees","rad","isRad","runtimeUsesRadians","toDegreesSigned","rotate","cx","cy","coseno","seno","dist","hypot","calcAngle","atan2","intersectLines","s1a","s1b","s2a","s2b","includeSegmentExtension","x3","y3","x4","y4","deltaX1","deltaY1","deltaX2","deltaY2","denominator","ua","ub","isLoaded","isFieldReady","resolution","left_x","top_y","num_columns","num_rows","addField","field","bs","ba","fillField","ar","abs","dif","sr","cr","_t","dir","offset","attractors","Array","from","wx","wy","att","dx","dy","w","freq","amp","_r","Position","m","mx","my","update","plotted","isActive","colIdx","rowIdx","reset","isIn","isInCanvas","skipCheck","list","get","current","wiggle","moveTo","_dir","_length","_step_length","movePos","_moveToDegrees","plotTo","_plot","_scale","precomputedAngle","_dirPlot","_step","scaleFactor","steps","fieldActive","usePlot","plotAngle","getRowIndex","y_offset","getColIndex","x_offset","col","row","Map","FIELD_ANGLE_MODES","Set","normalizeFieldAngleMode","options","angleMode","has","generateField","entry","normalizeFieldAngles","gen","refreshField","currentField","keys","join","noField","name","funct","set","listFields","fn","_stateStack","clamp","DEGREES","RADIANS","colorContext","currentAngleMode","transformStack","currentTransform","multiplyTransform","left","right","Color","g","hex","rgbToHex","rgbaMatch","exec","alpha","parseFloat","standardize","rgb","hexToRgb","toString","slice","replace","_match","red","green","blue","result","getColorContext","fillStyle","_getRed","_getGreen","_getBlue","mode","getAngleMode","wash","stroke","hatch","mass","pop","saved","brush","popState","translate","theta","cosTheta","sinTheta","scale","initStandaloneRuntime","hooks","render","clear","bindFramebuffer","FRAMEBUFFER","clearColor","COLOR_BUFFER_BIT","DEPTH_BUFFER_BIT","_current","_curvature","_strokeArray","_strokeOrigin","activeTarget","activeDensity","activeWidth","activeHeight","applyLoadedTarget","density","premultipliedAlpha","getTargetContext","createRenderer","createCanvas","logicalWidth","logicalHeight","Number","style","id","parent","querySelector","appendChild","Polygon","pointsArray","useRawVertices","vertices","sides","arr","_intersectionCache","intersect","line","cacheKey","point1","point2","points","start","end","intersection","show","Plot","_type","segments","angles","pres","type","calcIndex","pol","addSegment","_a","_pres","_degrees","reduce","sum","len","endPlot","pressure","_d","curving","index","map0","map1","suma","genPol","_x","_y","_side","step","numSteps","pos","pside","prevIdx","polygon","beginShape","vertex","endShape","circle","radius","arcLength","angleOffset","randomFactor","randomAngle","offsetX","offsetY","arc","startDeg","sweepDeg","segmentCount","segmentSweep","startX","startY","SubPath","isClosed","curvature","vert","_createSpline","close","beginStroke","move","endStroke","spline","_array_points","PI2","pep","tep","pep2","done","p1","p2","p3","d1","d2","a1","a2","curvAdjust","dmax","temp","temp2","point3","point4","intPt","halfDist","asin","origin","strokeRuntime","createTipSurface","loadImageTip","isStrokeCompositeRegistered","createProgram","frag","src","VERTEX_SHADER","FRAGMENT_SHADER","createShader","shaderSource","compileShader","attachShader","linkProgram","rendererRuntime","beginDirectMaskDraw","endDirectMaskDraw","resetDirectShaderTracking","framebufferProjMatrix","vao","buf","program","loadedWidth","loadedHeight","brushMaskTarget","Attr","Frag","_ma","_mb","_mc","_md","_mx","_my","_halfW","_halfH","_density","circleData","INITIAL_CAPACITY","circleCount","bufferCapacity","gpuBufferSize","circleDirtyRect","imgProgram","imgVao","imgCornerBuf","imgInstanceBuf","imgAttr","imgFrag","imgGpuSize","imgData","IMG_INIT_CAP","imgCount","imgCapacity","imgDirtyRect","texCache","QUAD_CORNERS","getProjectionMatrix","beginMaskTarget","endMaskTarget","accumulateDirtyRect","currentRect","diameter","newData","px","py","screenX","screenY","dScreenX","dScreenY","glDrawImages","p5img","targetState","tex","createTexture","bindTexture","TEXTURE_2D","texImage2D","RGBA","UNSIGNED_BYTE","texParameteri","TEXTURE_MIN_FILTER","LINEAR","TEXTURE_MAG_FILTER","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","useProgram","BLEND","blendFunc","ONE_MINUS_DST_ALPHA","ONE","activeTexture","TEXTURE0","uniform1i","u_tex","uniform4f","u_color","uniformMatrix4fv","u_proj","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","drawArraysInstanced","TRIANGLE_STRIP","needsStrokeMask","remove","antialias","depth","stencil","_Renderer","weight","opacity","DEFAULT_CUSTOM_PRESSURE_VARIATION","warp","tilt","BrushState","BrushSetState","add","params","includes","markerTip","vibration","scatter","definition","sharpness","quality","grain","min_max","curve","variation","isArray","rest","range","ns","nm","ne","normalizePressure","tip","deleteTexture","delete","invalidateTexEntry","background","noSmooth","noStroke","T","imageToWhite","tips","tipKey","param","colors","buffers","image","getBrushParams","brushName","scaleBrushes","values","spacing","pick","arguments","strokeWeight","clip","region","noClip","_position","_cachedPlotAngle","initializeDrawingState","plot","snapshotMatrix","gaussians","angleScale","isPlot","isCustomPressure","cp","ct","cs","ck","noiseoffset","rendererMask","ensureBrushMaskTarget","nextGl","needsContextRefresh","forEach","getAttribLocation","getUniformLocation","createVertexArray","createBuffer","enableVertexAttribArray","a_position","vertexAttribPointer","FLOAT","a_radius","a_alpha","STATIC_DRAW","a_corner","a_pos","IMG_FLOATS","vertexAttribDivisor","a_size","a_angle","isReady","switchingToBrush","overscan","maxPressure","scatterReach","tipReach","getImageTipOverscan","drawFn","drawSpray","drawMarker","drawImageTip","drawDefault","saveState","stepSize","totalSteps","pressureCount","cachedPressure","lineNoiseCount","cachedLineNoise","neededGaussians","u_matrix","drawArrays","POINTS","glDraw","restoreState","calculatePressure","lineNoise","simPressure","peakPos","halfWidth","pow","gauss","sw","iterations","rX","yRandomFactor","sqrtPart","vibrate","rx","ry","size","extraPadding","halfSize","extraRadius","base","boundsRadius","stampImage","plotCos","plotSin","perp","along","flowLine","_vals","_standard_brushes","obj","prototype","_brush","_weight","loadPixels","average","pixels","updatePixels","filter","k","Promise","all","then","HatchState","HatchSetState","rand","continuous","gradient","hatchStyle","hBrush","noHatch","scanlineHatch","cosA","sinA","cosB","sinB","verts","rotated","Infinity","edges","eLen","Y","sort","scanY","getHatchLines","polygons","segs","poly","getHatchSegments","getActiveHatchConfig","lines","isConnector","prev","createHatch","drawSegment","save","Object","withHatchStyle","renderHatchSegments","noMass","jitterPolygon","jitterX","jitterY","projectAnchorToBisector","anchor","nx","ny","getShortArcAngles","toAngleUnit","endDeg","splitSegment","seg","gap","gx","gy","drawMassArcs","pivotBias","bias","bounds","getPolygonBounds","sx","sy","getPivotAnchor","parts","part","center","startAngle","endAngle","drawMassPass","createMass","shape","pols","isPolygon","basePolygon","maxJitter","jitters","getMassPolygons","hatchState","brushState","fieldState","precision","strength","outline","hatchDist","baseAngle","_dist","_angle","_options","FillMaskUploadCanvas","isFillCompositeRegistered","maskWidth","maskHeight","needsFillMaskCanvas","fillMaskFramebuffer","needsFillMaskFramebuffer","imageSmoothingEnabled","_getActiveFramebuffer","uploadRect","uploadWidth","uploadHeight","uploadContext","clearRect","drawImage","colorTexture","texSubImage2D","GROW_CAP","_growInsX","_growInsY","_growMods","_growDirs","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","noFill","_polygon","_bbMinX","_bbMinY","_bbMaxX","_bbMaxY","_gaussians","_fillGaussianPools","FillPoly","isFirst","midP","rayCalc","v1","v2","side","rt","mid","ray","sizeX","sizeY","polySides","rc","r1x","r1y","rdx","rdy","count","sa","sb","sdx","sdy","denom","ix","iy","trim","keep","dst","trimStart","trimEnd","edgeStart","edgeEnd","edgeVec","newVertex","insertIdx","splice","ratio","L","indices","sv","sm","sd","outside","crossings","ay","by","flipDirs","grow","tr_v","tr_m","tr_dir","outLen","insertedX","insertedY","newMods","newDirs","bleedDirDeg","gPool","gPoolLen","g2Pool","g2PoolLen","fv","fm","fd","insertedIdx","mod","cv","nv","mi","di","rotDeg","sideX","sideY","dirX","dirY","nextMod","kept","intensity","texture","int","switchingToFill","setTransform","fillColorBase","strokeStyle","lineCap","fillMatrix","getTransform","darker","sparse","layer","numLayers","erase","restore","colorBase","matrix","lineWidth","beginPath","first","tx","ty","lineTo","closePath","strokePadding","drawPolygon","numCircles","halfSizeX","halfSizeY","minSize","minSizeFactor","maxSizeFactor","midX","midY","globalCompositeOperation","filterPoints","again","steiner","equals","area","removeNode","earcutLinked","ear","triangles","dim","invSize","pass","z","zOrder","prevZ","nextZ","numMerges","inSize","tail","q","pSize","qSize","sortLinked","indexCurve","stop","isEarHashed","isEar","cureLocalIntersections","splitEarcut","ax","bx","pointInTriangleExceptFirst","minZ","maxZ","intersects","locallyInside","isValidDiagonal","splitPolygon","pointInTriangle","intersectsPolygon","inside","middleInside","q1","q2","o1","sign","o2","o3","o4","onSegment","num","createNode","b2","an","bp","insertNode","last","_opacity","_bleed","_wr","fluid","modifiers","_","shift","shifted","pts","sumX","sumY","pt","cross","_center","createFill","FillSetState","washProgram","washVao","washBuffer","washProjection","washGpuBufferSize","WashAttr","WashUniform","noWash","transformVertexToScreen","_renderer","hadDepthTest","isEnabled","DEPTH_TEST","framebuffer","viewport","resetStandaloneShaderTracking","blendEquation","FUNC_ADD","ONE_MINUS_SRC_ALPHA","previousFramebuffer","getParameter","FRAMEBUFFER_BINDING","previousViewport","VIEWPORT","vertSrc","fragSrc","uniformCache","quadVao","loc_source","loc_mask","loc_color","setUniform","location","uniform3f","uniform1f","makeShader","pixelWidth","pixelHeight","createFramebufferTexture","framebufferTexture2D","COLOR_ATTACHMENT0","__brushFramebuffer","deleteFramebuffer","currentFramebuffer","previousProgram","CURRENT_PROGRAM","previousVao","VERTEX_ARRAY_BINDING","TEXTURE1","TRIANGLES","sourceBox","previousReadFramebuffer","READ_FRAMEBUFFER_BINDING","previousDrawFramebuffer","DRAW_FRAMEBUFFER_BINDING","READ_FRAMEBUFFER","DRAW_FRAMEBUFFER","blitFramebuffer","NEAREST","blitDefaultFramebufferSource","cssColor","buildTipSurface","get2DContext","surface","_fillStyle","_strokeStyle","_lineWidth","fillRect","_paint","ellipse","_shapeStarted","getImageData","imageData","putImageData","resolve","reject","NativeImage","globalThis","Image","nativeImg","onload","naturalWidth","naturalHeight","onerror","crossOrigin","ensureWashReady","vertexCount","flat","holeIndices","outerLen","outerNode","signedArea","linkedList","earcut","buildTriangleBuffer","drawWashPolygon","HTMLCanvasElement","isCanvasTarget","isOffscreenCanvasTarget","isSupportedTarget","initStandaloneRendererRuntime","initStandaloneCompositorRuntime","initStandaloneStrokeRuntime"],"mappings":"AAIA,MAAMA,EAAiB,CACrBC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,GAGE,ICEIC,EAAQC,EAAmBC,EAAUC,EDFrCC,EAAc,KAAM,EACpBC,EAAeC,GAAUA,EACzBC,EAAc,KACvB,MAAM,IAAIC,MAAM,yCAEPC,EAAkB,IAAMhB,ECD/BiB,EAAgB,CAClBC,KAAM,KACJ,MAAM,IAAIH,MAAM,0CAElBI,YAAa,IAAMT,EACnBU,cAAe,KACb,MAAM,IAAIL,MAAM,0CAElBM,SAAWC,MAGXC,iBAAmBD,MAGnBE,mBAAoB,OACpBC,qBAAsB,IAAM,KAC5BC,oBAAqB,KAAM,GAQtB,SAASC,EAAeC,GACzB,WAAYA,IAAOrB,EAASqB,EAAMrB,QAClC,YAAaqB,IAAOpB,EAAUoB,EAAMpB,SACpC,aAAcoB,GAAkBA,EAAMC,SACtC,aAAcD,IAAOnB,EAAWmB,EAAMnB,UACtC,YAAamB,IAAOlB,EAAUkB,EAAMlB,QAC1C,CAWO,MAEMU,EAAgB,IAAMH,EAAcG,gBACpCC,EAAYC,GAASL,EAAcI,SAASC,GAG5CG,EAAuB,IAAMR,EAAcQ,uBAC3CC,EAAuBI,GAClCb,EAAcS,oBAAoBI,GCxDvBC,EAAkB,CAACC,EAAMC,EAAU,IAC9CD,EACI,CACEE,KAAMF,EAAKE,KAAOD,EAClBE,KAAMH,EAAKG,KAAOF,EAClBG,KAAMJ,EAAKI,KAAOH,EAClBI,KAAML,EAAKK,KAAOJ,GAEpB,KCIOK,EAAiB,CAACC,EAAOC,EAAQC,GAAqB,KACjE,MAAMC,EACuB,oBAApBC,gBACH,IAAIA,gBAAgBJ,EAAOC,GAC3B,MACE,MAAMI,EA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2Z,EAAO,MACpCnU,KAAK2X,IAAIpE,OACX,E3B7MiCc,GWgId,CACfjZ,KA3GG,SAAcY,EAASiZ,IAC5B,IAhDF,SAA2BjZ,GACzB,OAfF,SAAwBA,GACtB,MAC+B,oBAAtBkrC,mBACPlrC,aAAkBkrC,iBAEtB,CAUSC,CAAenrC,IARxB,SAAiCA,GAC/B,MAC6B,oBAApBa,iBACPb,aAAkBa,eAEtB,CAGmCuqC,CAAwBprC,EAC3D,CA8COqrC,CAAkBrrC,GACrB,MAAM,IAAIf,MACR,mFAIJoa,GAAkBrZ,EAAQA,EAAOS,MAAOT,EAAOU,OAAQ,EACzD,EAoGIrB,YAlDG,WAML,OALAQ,EAAe,CACbpB,OAAQ0a,GACRza,QAAS0a,GACTxa,QAASsa,KAEJA,EACT,EA4CI5Z,cAvCG,WACL,IAAK+P,GACH,MAAM,IAAIpQ,MACR,+EAGN,EAkCIM,SA7BG,WAAqB,EA8BxBE,iBA7BG,WAA6B,EA8BhCC,mBA7BG,WAA+B,EA8BlCC,qBAvBG,WACL,OAAO,IACT,EAsBIC,oBAbG,WACL,OAA4C,IAArCirB,UAAU,IAAI8c,kBACvB,GX5HExoC,EAAgB,IAAKA,KAAkBkZ,I+BvCzCD,KHmBO,WVPA,IAA4BC,IUQd,CACjBkJ,uBACAC,qBACAC,0BAA2BwkB,IVV7B3kB,GAAkB,IAAKA,MAAoBjJ,EUY7C,CGxBAizB,GF4MO,W3BlHA,IAA8BjzB,I2BmHd,CACnBhX,eACAC,4BACAC,gCACAC,qBACAC,sBACAC,4B3BxHFN,EAAoB,IAAKA,KAAsBiX,E2B0HjD,CEpNAkzB,GDqKO,WfrKA,IAA0BlzB,IesKd,CACfoI,oBACAC,iBfvKFF,GAAgB,IAAKA,MAAkBnI,EeyKzC,CCzKAmzB","x_google_ignoreList":[5,6,27]}
\ No newline at end of file
diff --git a/dist/brush.js b/dist/brush.js
index fb17f80..2faecbb 100644
--- a/dist/brush.js
+++ b/dist/brush.js
@@ -1,2 +1,2 @@
-var t,e;t=this,e=function(t){const e={a:1,b:0,c:0,d:1,x:0,y:0};let r,n,i,a,o=()=>!1,s=t=>t,c=()=>{throw new Error("No runtime color adapter registered.")},l=()=>e,u={load:()=>{throw new Error("No target runtime adapter registered.")},syncDensity:()=>a,isCanvasReady:()=>{throw new Error("No target runtime adapter registered.")},instance:t=>{},activateInstance:t=>{},deactivateInstance:()=>{},getActiveFramebuffer:()=>null,isFramebufferTarget:()=>!1};function h(t){"Cwidth"in t&&(r=t.Cwidth),"Cheight"in t&&(n=t.Cheight),"Instance"in t&&t.Instance,"Renderer"in t&&(i=t.Renderer),"Density"in t&&(a=t.Density)}const f=()=>u.isCanvasReady(),d=()=>u.getActiveFramebuffer(),m=t=>u.isFramebufferTarget(t),x=(t,e=0)=>t?{minX:t.minX-e,minY:t.minY-e,maxX:t.maxX+e,maxY:t.maxY+e}:null,g=(t,e,r=!1)=>{const n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(t,e):(()=>{const r=document.createElement("canvas");return r.width=t,r.height=e,r})();return n.drawingContext=n.getContext("2d",r?{willReadFrequently:!0}:void 0),n};let p={clearTarget:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendShaderProgram:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendSourceFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},createFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},runBlendShaderPass:()=>{throw new Error("No compositor runtime adapter registered.")},blitSourceToFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")}};const y=(...t)=>p.createFramebuffer(...t);let b=null,_=null;const v=t=>{((...t)=>{p.clearTarget(...t)})(i,t,m)},R=()=>({width:Math.max(1,Math.round(r*a)),height:Math.max(1,Math.round(n*a))}),w=t=>{if(!t)return null;const{width:e,height:r}=R();return((t,e,r)=>{if(!t)return null;const n=Math.max(0,Math.floor(Math.min(t.minX,t.maxX))),i=Math.max(0,Math.floor(Math.min(t.minY,t.maxY))),a=Math.min(e,Math.ceil(Math.max(t.minX,t.maxX))),o=Math.min(r,Math.ceil(Math.max(t.minY,t.maxY)));return a<=n||o<=i?null:{minX:n,minY:i,maxX:a,maxY:o}})(t,e,r)},E=()=>{const{width:t,height:e}=R();return((t,e)=>({minX:0,minY:0,maxX:t,maxY:e}))(t,e)},A=(t,e=!0)=>{const r=w(t);if(!r)return null;const{height:n}=R();return{x:r.minX,y:e?n-r.maxY:r.minY,width:r.maxX-r.minX,height:r.maxY-r.minY}},M=(t,e,r,n=!0)=>{const i=A(e,n);if(i){t.enable(t.SCISSOR_TEST),t.scissor(i.x,i.y,i.width,i.height);try{r()}finally{t.disable(t.SCISSOR_TEST)}}else r()},S={},T=()=>{i?.loaded||(f(),P.load())},P={isBlending:!1,cachedColor:null,markDirtyRect(t,e){const r=w(e);var n,i;t&&r&&(t.dirtyRect=(i=r,(n=t.dirtyRect)?i?{minX:Math.min(n.minX,i.minX),minY:Math.min(n.minY,i.minY),maxX:Math.max(n.maxX,i.maxX),maxY:Math.max(n.maxY,i.maxY)}:n:i),t.isDrawn=!0)},clearMask(t){if(!t)return;const e=t===this.glMask?b:_;e?.clearMask?.(t,v)},getCompositeRect(t,e){const r=e?b:_;return r?.getCompositeRect?.(t,d,E,x,w)},load(){u.syncDensity();const t=!i.blendSourceFramebuffer||i.blendSourceFramebuffer.width!==r||i.blendSourceFramebuffer.height!==n||"function"==typeof i.blendSourceFramebuffer.pixelDensity&&i.blendSourceFramebuffer.pixelDensity()!==a;((...t)=>{p.ensureBlendShaderProgram(...t)})(i,"#version 300 es\n#define GLSLIFY 1\nout vec2 p;void main(){vec3 v=vec3(-1);v[gl_VertexID]=3.;p=v.xy;gl_Position=vec4(v.x,-v.y,0,1);}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nuniform bool u_isBrush;uniform bool u_targetIsFramebuffer;uniform sampler2D u_source;uniform sampler2D u_mask;uniform vec3 u_color;in vec2 p;out vec4 outColor;const int SPECTRAL_SIZE=38;const float SPECTRAL_GAMMA=2.4;const float SPECTRAL_EPSILON=0.0000000000000001;float spectral_uncompand(float x){return(x<0.04045)? x/12.92 : pow((x+0.055)/1.055,SPECTRAL_GAMMA);}float spectral_compand(float x){return(x<0.0031308)? x*12.92 : 1.055*pow(x,1.0/SPECTRAL_GAMMA)-0.055;}vec3 spectral_srgb_to_linear(vec3 srgb){return vec3(spectral_uncompand(srgb[0]),spectral_uncompand(srgb[1]),spectral_uncompand(srgb[2]));}vec3 spectral_linear_to_srgb(vec3 lrgb){return clamp(vec3(spectral_compand(lrgb[0]),spectral_compand(lrgb[1]),spectral_compand(lrgb[2])),0.,1.);}void spectral_linear_to_reflectance(vec3 lrgb,inout float R[SPECTRAL_SIZE]){float w=min(lrgb.r,min(lrgb.g,lrgb.b));lrgb-=w;float c=min(lrgb.g,lrgb.b);float m=min(lrgb.r,lrgb.b);float y=min(lrgb.r,lrgb.g);float r=min(max(0.0,lrgb.r-lrgb.b),max(0.0,lrgb.r-lrgb.g));float g=min(max(0.0,lrgb.g-lrgb.b),max(0.0,lrgb.g-lrgb.r));float b=min(max(0.0,lrgb.b-lrgb.g),max(0.0,lrgb.b-lrgb.r));R[0]=max(SPECTRAL_EPSILON,w*1.0011607271876400+c*0.9705850013229620+m*0.9906735573199880+y*0.0210523371789306+r*0.0315605737777207+g*0.0095560747554212+b*0.9794047525020140);R[1]=max(SPECTRAL_EPSILON,w*1.0011606515972800+c*0.9705924981434250+m*0.9906715249619790+y*0.0210564627517414+r*0.0315520718330149+g*0.0095581580120851+b*0.9794007068431300);R[2]=max(SPECTRAL_EPSILON,w*1.0011603192274700+c*0.9706253487298910+m*0.9906625823534210+y*0.0210746178695038+r*0.0315148215513658+g*0.0095673245444588+b*0.9793829034702610);R[3]=max(SPECTRAL_EPSILON,w*1.0011586727078900+c*0.9707868061190170+m*0.9906181076447950+y*0.0211649058448753+r*0.0313318044982702+g*0.0096129126297349+b*0.9792943649455940);R[4]=max(SPECTRAL_EPSILON,w*1.0011525984455200+c*0.9713686732282480+m*0.9904514808787100+y*0.0215027957272504+r*0.0306729857725527+g*0.0097837090401843+b*0.9789630146085700);R[5]=max(SPECTRAL_EPSILON,w*1.0011325252899800+c*0.9731632306212520+m*0.9898710814002040+y*0.0226738799041561+r*0.0286480476989607+g*0.0103786227058710+b*0.9778144666940430);R[6]=max(SPECTRAL_EPSILON,w*1.0010850066332700+c*0.9767402231587650+m*0.9882866087596400+y*0.0258235649693629+r*0.0246450407045709+g*0.0120026452378567+b*0.9747243211338360);R[7]=max(SPECTRAL_EPSILON,w*1.0009968788945300+c*0.9815876054913770+m*0.9842906927975040+y*0.0334879385639851+r*0.0192960753663651+g*0.0160977721473922+b*0.9671984823439730);R[8]=max(SPECTRAL_EPSILON,w*1.0008652515227400+c*0.9862802656529490+m*0.9739349056253060+y*0.0519069663740307+r*0.0142066612220556+g*0.0267061902231680+b*0.9490796575305750);R[9]=max(SPECTRAL_EPSILON,w*1.0006962900094000+c*0.9899491476891340+m*0.9418178384601450+y*0.1007490148334730+r*0.0102942608878609+g*0.0595555440185881+b*0.9008501289409770);R[10]=max(SPECTRAL_EPSILON,w*1.0005049611488800+c*0.9924927015384200+m*0.8173903261951560+y*0.2391298997068470+r*0.0076191460521811+g*0.1860398265328260+b*0.7631504454622400);R[11]=max(SPECTRAL_EPSILON,w*1.0003080818799200+c*0.9941456804052560+m*0.4324728050657290+y*0.5348043122727480+r*0.0058980410835420+g*0.5705798201161590+b*0.4659221716493190);R[12]=max(SPECTRAL_EPSILON,w*1.0001196660201300+c*0.9951839750332120+m*0.1384539782588700+y*0.7978075786430300+r*0.0048233247781713+g*0.8614677684002920+b*0.2012632804510050);R[13]=max(SPECTRAL_EPSILON,w*0.9999527659684070+c*0.9957567501108180+m*0.0537347216940033+y*0.9114498940673840+r*0.0042298748350633+g*0.9458790897676580+b*0.0877524413419623);R[14]=max(SPECTRAL_EPSILON,w*0.9998218368992970+c*0.9959128182867100+m*0.0292174996673231+y*0.9537979630045070+r*0.0040599171299341+g*0.9704654864743050+b*0.0457176793291679);R[15]=max(SPECTRAL_EPSILON,w*0.9997386095575930+c*0.9956061578345280+m*0.0213136517508590+y*0.9712416154654290+r*0.0043533695594676+g*0.9784136302844500+b*0.0284706050521843);R[16]=max(SPECTRAL_EPSILON,w*0.9997095516396120+c*0.9945976009618540+m*0.0201349530181136+y*0.9793031238075880+r*0.0053434425970201+g*0.9795890314112240+b*0.0205271767569850);R[17]=max(SPECTRAL_EPSILON,w*0.9997319302106270+c*0.9922157154923700+m*0.0241323096280662+y*0.9833801195075750+r*0.0076917201010463+g*0.9755335369086320+b*0.0165302792310211);R[18]=max(SPECTRAL_EPSILON,w*0.9997994363461950+c*0.9862364527832490+m*0.0372236145223627+y*0.9854612465677550+r*0.0135969795736536+g*0.9622887553978130+b*0.0145135107212858);R[19]=max(SPECTRAL_EPSILON,w*0.9999003303166710+c*0.9679433372645410+m*0.0760506552706601+y*0.9864350469766050+r*0.0316975442661115+g*0.9231215745131200+b*0.0136003508637687);R[20]=max(SPECTRAL_EPSILON,w*1.0000204065261100+c*0.8912850042449430+m*0.2053754719423990+y*0.9867382506701410+r*0.1078611963552490+g*0.7934340189431110+b*0.0133604258769571);R[21]=max(SPECTRAL_EPSILON,w*1.0001447879365800+c*0.5362024778620530+m*0.5412689034604390+y*0.9866178824450320+r*0.4638126031687040+g*0.4592701359024290+b*0.0135488943145680);R[22]=max(SPECTRAL_EPSILON,w*1.0002599790341200+c*0.1541081190018780+m*0.8158416850864860+y*0.9862777767586430+r*0.8470554052720110+g*0.1855741036663030+b*0.0139594356366992);R[23]=max(SPECTRAL_EPSILON,w*1.0003557969708900+c*0.0574575093228929+m*0.9128177041239760+y*0.9858605924440560+r*0.9431854093939180+g*0.0881774959955372+b*0.0144434255753570);R[24]=max(SPECTRAL_EPSILON,w*1.0004275378026900+c*0.0315349873107007+m*0.9463398301669620+y*0.9854749276762100+r*0.9688621506965580+g*0.0543630228766700+b*0.0148854440621406);R[25]=max(SPECTRAL_EPSILON,w*1.0004762334488800+c*0.0222633920086335+m*0.9599276963319910+y*0.9851769347655580+r*0.9780306674736030+g*0.0406288447060719+b*0.0152254296999746);R[26]=max(SPECTRAL_EPSILON,w*1.0005072096750800+c*0.0182022841492439+m*0.9662605952303120+y*0.9849715740141810+r*0.9820436438543060+g*0.0342215204316970+b*0.0154592848180209);R[27]=max(SPECTRAL_EPSILON,w*1.0005251915637300+c*0.0162990559732640+m*0.9693259700584240+y*0.9848463034157120+r*0.9839236237187070+g*0.0311185790956966+b*0.0156018026485961);R[28]=max(SPECTRAL_EPSILON,w*1.0005350960689600+c*0.0153656239334613+m*0.9708545367213990+y*0.9847753518111990+r*0.9848454841543820+g*0.0295708898336134+b*0.0156824871281936);R[29]=max(SPECTRAL_EPSILON,w*1.0005402209748200+c*0.0149111568733976+m*0.9716050665281280+y*0.9847380666252650+r*0.9852942758145960+g*0.0288108739348928+b*0.0157248764360615);R[30]=max(SPECTRAL_EPSILON,w*1.0005427281678400+c*0.0146954339898235+m*0.9719627697573920+y*0.9847196483117650+r*0.9855072952198250+g*0.0284486271324597+b*0.0157458108784121);R[31]=max(SPECTRAL_EPSILON,w*1.0005438956908700+c*0.0145964146717719+m*0.9721272722745090+y*0.9847110233919390+r*0.9856050715398370+g*0.0282820301724731+b*0.0157556123350225);R[32]=max(SPECTRAL_EPSILON,w*1.0005444821215100+c*0.0145470156699655+m*0.9722094177458120+y*0.9847066833006760+r*0.9856538499335780+g*0.0281988376490237+b*0.0157605443964911);R[33]=max(SPECTRAL_EPSILON,w*1.0005447695999200+c*0.0145228771899495+m*0.9722495776784240+y*0.9847045543930910+r*0.9856776850338830+g*0.0281581655342037+b*0.0157629637515278);R[34]=max(SPECTRAL_EPSILON,w*1.0005448988776200+c*0.0145120341118965+m*0.9722676219987420+y*0.9847035963093700+r*0.9856883918061220+g*0.0281398910216386+b*0.0157640525629106);R[35]=max(SPECTRAL_EPSILON,w*1.0005449625468900+c*0.0145066940939832+m*0.9722765094621500+y*0.9847031240775520+r*0.9856936646900310+g*0.0281308901665811+b*0.0157645892329510);R[36]=max(SPECTRAL_EPSILON,w*1.0005449892705800+c*0.0145044507314479+m*0.9722802433068740+y*0.9847029256150900+r*0.9856958798482050+g*0.0281271086805816+b*0.0157648147772649);R[37]=max(SPECTRAL_EPSILON,w*1.0005449969930000+c*0.0145038009464639+m*0.9722813248265600+y*0.9847028681227950+r*0.9856965214637620+g*0.0281260133612096+b*0.0157648801149616);}vec3 spectral_xyz_to_srgb(vec3 xyz){mat3 XYZ_RGB;XYZ_RGB[0]=vec3(3.2409699419045200,-1.537383177570090,-0.4986107602930030);XYZ_RGB[1]=vec3(-0.9692436362808790,1.875967501507720,0.0415550574071756);XYZ_RGB[2]=vec3(0.0556300796969936,-0.203976958888976,1.0569715142428700);float r=dot(XYZ_RGB[0],xyz);float g=dot(XYZ_RGB[1],xyz);float b=dot(XYZ_RGB[2],xyz);return spectral_linear_to_srgb(vec3(r,g,b));}vec3 spectral_reflectance_to_xyz(float R[SPECTRAL_SIZE]){vec3 xyz=vec3(0.);xyz+=R[0]*vec3(0.0000646919989576,0.0000018442894440,0.0003050171476380);xyz+=R[1]*vec3(0.0002194098998132,0.0000062053235865,0.0010368066663574);xyz+=R[2]*vec3(0.0011205743509343,0.0000310096046799,0.0053131363323992);xyz+=R[3]*vec3(0.0037666134117111,0.0001047483849269,0.0179543925899536);xyz+=R[4]*vec3(0.0118805536037990,0.0003536405299538,0.0570775815345485);xyz+=R[5]*vec3(0.0232864424191771,0.0009514714056444,0.1136516189362870);xyz+=R[6]*vec3(0.0345594181969747,0.0022822631748318,0.1733587261835500);xyz+=R[7]*vec3(0.0372237901162006,0.0042073290434730,0.1962065755586570);xyz+=R[8]*vec3(0.0324183761091486,0.0066887983719014,0.1860823707062960);xyz+=R[9]*vec3(0.0212332056093810,0.0098883960193565,0.1399504753832070);xyz+=R[10]*vec3(0.0104909907685421,0.0152494514496311,0.0891745294268649);xyz+=R[11]*vec3(0.0032958375797931,0.0214183109449723,0.0478962113517075);xyz+=R[12]*vec3(0.0005070351633801,0.0334229301575068,0.0281456253957952);xyz+=R[13]*vec3(0.0009486742057141,0.0513100134918512,0.0161376622950514);xyz+=R[14]*vec3(0.0062737180998318,0.0704020839399490,0.0077591019215214);xyz+=R[15]*vec3(0.0168646241897775,0.0878387072603517,0.0042961483736618);xyz+=R[16]*vec3(0.0286896490259810,0.0942490536184085,0.0020055092122156);xyz+=R[17]*vec3(0.0426748124691731,0.0979566702718931,0.0008614711098802);xyz+=R[18]*vec3(0.0562547481311377,0.0941521856862608,0.0003690387177652);xyz+=R[19]*vec3(0.0694703972677158,0.0867810237486753,0.0001914287288574);xyz+=R[20]*vec3(0.0830531516998291,0.0788565338632013,0.0001495555858975);xyz+=R[21]*vec3(0.0861260963002257,0.0635267026203555,0.0000923109285104);xyz+=R[22]*vec3(0.0904661376847769,0.0537414167568200,0.0000681349182337);xyz+=R[23]*vec3(0.0850038650591277,0.0426460643574120,0.0000288263655696);xyz+=R[24]*vec3(0.0709066691074488,0.0316173492792708,0.0000157671820553);xyz+=R[25]*vec3(0.0506288916373645,0.0208852059213910,0.0000039406041027);xyz+=R[26]*vec3(0.0354739618852640,0.0138601101360152,0.0000015840125870);xyz+=R[27]*vec3(0.0214682102597065,0.0081026402038399,0.0000000000000000);xyz+=R[28]*vec3(0.0125164567619117,0.0046301022588030,0.0000000000000000);xyz+=R[29]*vec3(0.0068045816390165,0.0024913800051319,0.0000000000000000);xyz+=R[30]*vec3(0.0034645657946526,0.0012593033677378,0.0000000000000000);xyz+=R[31]*vec3(0.0014976097506959,0.0005416465221680,0.0000000000000000);xyz+=R[32]*vec3(0.0007697004809280,0.0002779528920067,0.0000000000000000);xyz+=R[33]*vec3(0.0004073680581315,0.0001471080673854,0.0000000000000000);xyz+=R[34]*vec3(0.0001690104031614,0.0000610327472927,0.0000000000000000);xyz+=R[35]*vec3(0.0000952245150365,0.0000343873229523,0.0000000000000000);xyz+=R[36]*vec3(0.0000490309872958,0.0000177059860053,0.0000000000000000);xyz+=R[37]*vec3(0.0000199961492222,0.0000072209749130,0.0000000000000000);return xyz;}float KS(float R){return pow(1.0-R,2.0)/(2.0*R);}float KM(float KS){return 1.0+KS-sqrt(pow(KS,2.0)+2.0*KS);}vec3 spectral_mix(vec3 color1,float tintingStrength1,float factor1,vec3 color2,float tintingStrength2,float factor2){vec3 lrgb1=spectral_srgb_to_linear(color1);vec3 lrgb2=spectral_srgb_to_linear(color2);float R1[SPECTRAL_SIZE];float R2[SPECTRAL_SIZE];spectral_linear_to_reflectance(lrgb1,R1);spectral_linear_to_reflectance(lrgb2,R2);float luminance1=spectral_reflectance_to_xyz(R1)[1];float luminance2=spectral_reflectance_to_xyz(R2)[1];float R[SPECTRAL_SIZE];for(int i=0;i<SPECTRAL_SIZE;i++){float concentration1=pow(factor1,2.)*pow(tintingStrength1,2.)*luminance1;float concentration2=pow(factor2,2.)*pow(tintingStrength2,2.)*luminance2;float totalConcentration=concentration1+concentration2;float ksMix=0.;ksMix+=KS(R1[i])*concentration1;ksMix+=KS(R2[i])*concentration2;R[i]=KM(ksMix/totalConcentration);}return spectral_xyz_to_srgb(spectral_reflectance_to_xyz(R));}vec3 spectral_mix(vec3 color1,vec3 color2,float factor){return spectral_mix(color1,1.,1.-factor,color2,1.,factor);}vec3 spectral_mix(vec3 color1,float factor1,vec3 color2,float factor2){return spectral_mix(color1,1.,factor1,color2,1.,factor2);}const float GAMMA=2.4,EPSILON=0.0001;const float DARKEN_THRESHOLD=0.7;const float EDGE_MIN=0.05,EDGE_MAX=0.35;void main(void){vec2 uv=0.5*p+0.5;vec2 sourceUV=vec2(uv.x,1.0-uv.y);vec2 maskUV=u_targetIsFramebuffer ? vec2(uv.x,1.0-uv.y): uv;vec4 source=texture(u_source,sourceUV);vec4 maskColor=texture(u_mask,maskUV);if(maskColor.a==0.0){outColor=source;return;}vec4 pigment=vec4(u_color.xyz,1.0);if(maskColor.a>DARKEN_THRESHOLD){float blacken=0.5*(min(maskColor.a,1.0)-DARKEN_THRESHOLD);pigment=pigment*(1.0-blacken)-vec4(0.5)*blacken;pigment.rgb=max(pigment.rgb,vec3(0.0));}float mixIntensity=min(maskColor.a,1.0);if(!u_isBrush){vec2 texelSize=1.0/vec2(textureSize(u_mask,0));float scaledAlpha=maskColor.a*15.0;float blurEdge=0.0;for(int i=-2;i<=2;i+=2){for(int j=-2;j<=2;j+=2){vec2 neighborUV=maskUV+vec2(float(i),float(j))*texelSize;float neighborAlpha=texture(u_mask,neighborUV).a*15.0;blurEdge+=smoothstep(EDGE_MIN,EDGE_MAX,length(vec2(dFdx(neighborAlpha),dFdy(neighborAlpha))));}}blurEdge/=9.0;mixIntensity=clamp(maskColor.a+blurEdge*0.1,0.0,1.0);}vec3 bgColor=mix(vec3(1.0),source.rgb,source.a);outColor=vec4(spectral_mix(bgColor,pigment.rgb,mixIntensity),1.);}"),this.glMask=b?.ensureResources?.(i,r,n,a);const e=_?.ensureResources?.(i,r,n,a,v)??{mask:null,ctx:null};t&&(i.blendSourceFramebuffer=((...t)=>p.ensureBlendSourceFramebuffer(...t))(i,i.blendSourceFramebuffer,r,n,a)),this.mask=e.mask,this.ctx=e.ctx},blend(t=!1,e=!1){T();const r=!0===this.isBrush,n=r?this.glMask:this.mask,i=r?this.mask:this.glMask,a=t?._array,o=!!a&&(this.cachedColor?.[0]!==a[0]||this.cachedColor?.[1]!==a[1]||this.cachedColor?.[2]!==a[2]||this.cachedColor?.[3]!==a[3]);!this.isBlending&&a&&(this.isBlending=!0,this.cachedColor=a,this.clearMask(this.glMask)),(e||o)&&(this.justChanged&&(this.applyShader(i,!r),this.justChanged=!1),this.isBlending&&this.applyShader(n,r),a&&(this.cachedColor=a),e&&(this.isBlending=!1,this.cachedColor=null))},applyShader(t,e){if(!t?.isDrawn)return;const a=this.getCompositeRect(t,e);if(!a)return void this.clearMask(t);i.drawingContext;const o=i.shaderProgram,s=d(),c=((...t)=>p.blitSourceToFramebuffer(...t))({renderer:i,sourceTarget:s??i,sourceFramebuffer:i.blendSourceFramebuffer,dirtyRect:a,isFramebufferTarget:m,Cwidth:r,Cheight:n,getTargetPixelSize:R,toScissorBox:A,withScissor:M}),l=!!s,u=(e?b:_).getShaderMask(i,t,a,w,E,v);((...t)=>{p.runBlendShaderPass(...t)})({renderer:i,shader:o,source:c,mask:u,color:this.cachedColor,isBrushMask:e,Cwidth:r,Cheight:n,dirtyRect:a,targetIsFramebuffer:l,withScissor:M}),this.clearMask(t)}},C=()=>{T(),P.blend(!1,!0),P.clearMask(P.glMask),P.clearMask(P.mask),P.justChanged=!1,P.isBlending=!1,P.isBrush=null,P.cachedColor=null},F=Math.sqrt(3),k=.5*(F-1),I=(3-F)/6,D=t=>0|Math.floor(t),L=new Float64Array([1,1,-1,1,1,-1,-1,-1,1,0,-1,0,1,0,-1,0,0,1,0,-1,0,1,0,-1]);function N(t=Math.random){const e=function(t){const e=new Uint8Array(512);for(let t=0;t<256;t++)e[t]=t;for(let r=0;r<255;r++){const n=r+~~(t()*(256-r)),i=e[r];e[r]=e[n],e[n]=i}for(let t=256;t<512;t++)e[t]=e[t-256];return e}(t),r=new Float64Array(e).map(t=>L[t%12*2]),n=new Float64Array(e).map(t=>L[t%12*2+1]);return function(t,i){let a=0,o=0,s=0;const c=(t+i)*k,l=D(t+c),u=D(i+c),h=(l+u)*I,f=t-(l-h),d=i-(u-h);let m,x;f>d?(m=1,x=0):(m=0,x=1);const g=f-m+I,p=d-x+I,y=f-1+2*I,b=d-1+2*I,_=255&l,v=255&u;let R=.5-f*f-d*d;if(R>=0){const t=_+e[v];R*=R,a=R*R*(r[t]*f+n[t]*d)}let w=.5-g*g-p*p;if(w>=0){const t=_+m+e[v+x];w*=w,o=w*w*(r[t]*g+n[t]*p)}let E=.5-y*y-b*b;if(E>=0){const t=_+1+e[v+1];E*=E,s=E*E*(r[t]*y+n[t]*b)}return 70*(a+o+s)}}function B(t,e){let r=new U(t),n=()=>r.next();return n.double=()=>n()+11102230246251565e-32*(2097152*n()|0),n.int32=()=>4294967296*r.next()|0,n.quick=n,n}class U{constructor(t){null==t&&(t=+new Date);let e=4022871197;function r(t){t=String(t);for(let r=0;r<t.length;r++){e+=t.charCodeAt(r);let n=.02519603282416938*e;e=n>>>0,n-=e,n*=e,e=n>>>0,n-=e,e+=4294967296*n}return 2.3283064365386963e-10*(e>>>0)}this.c=1,this.s0=r(" "),this.s1=r(" "),this.s2=r(" "),this.s0-=r(t),this.s0<0&&(this.s0+=1),this.s1-=r(t),this.s1<0&&(this.s1+=1),this.s2-=r(t),this.s2<0&&(this.s2+=1)}next(){let{c:t,s0:e,s1:r,s2:n}=this,i=2091639*e+2.3283064365386963e-10*t;return this.s0=r,this.s1=n,this.s2=i-(this.c=0|i)}copy(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}}let O=B(Math.random()),Y=B(Math.random());const z=[],X=t=>z.push(t);let G=N(B(Math.random())),Z=N(B(Math.random()));const V=(t=0,e=1)=>t+O()*(e-t),$=(t=0,e=1)=>t+Y()*(e-t),H=t=>t[~~(O()*t.length)],W=(t,e)=>~~V(t,e),q=(t,e)=>~~$(t,e),j=(t=0,e=1)=>{const r=1-O(),n=O();return Math.sqrt(-2*Math.log(r))*at(360*n)*e+t},K=t=>{let e=0;const r=[];for(const n in t)e+=t[n],r.push({key:n,cumulative:e});const n=O()*e;for(const{key:t,cumulative:e}of r)if(n<e)return isNaN(t)?t:parseInt(t)},J=(t,e,r,n,i,a=!1)=>{let o=n+(t-e)/(r-e)*(i-n);return a?n<i?Q(o,n,i):Q(o,i,n):o},Q=(t,e,r)=>Math.max(Math.min(t,r),e),tt=t=>(t%=360)<0?t+360:t,et=1440,rt=2*Math.PI/et,nt=new Float32Array(et).fill(NaN),it=new Float32Array(et).fill(NaN),at=t=>{const e=~~(4*tt(t));let r=nt[e];return isNaN(r)&&(r=Math.cos(e*rt),nt[e]=r),r},ot=t=>{const e=~~(4*tt(t));let r=it[e];return isNaN(r)&&(r=Math.sin(e*rt),it[e]=r),r},st=(t,e=!1)=>{if(e||o()){let e=180*t/Math.PI%360;return e<0?e+360:e}return t},ct=(t,e=!1)=>e||o()?180*t/Math.PI:t,lt=(t,e,r,n,i)=>{let a=at(i),o=ot(i);return{x:a*(r-t)+o*(n-e)+t,y:a*(n-e)-o*(r-t)+e}},ut=(t,e,r,n)=>Math.hypot(r-t,n-e),ht=(t,e,r,n)=>st(Math.atan2(-(n-e),r-t),!0),ft=(t,e,r,n,i=!1)=>{let a=t.x,o=t.y,s=e.x,c=e.y,l=r.x,u=r.y,h=n.x,f=n.y;if(a===s&&o===c||l===h&&u===f)return!1;let d=s-a,m=c-o,x=h-l,g=f-u,p=g*d-x*m;if(0===p)return!1;let y=(x*(o-u)-g*(a-l))/p,b=(d*(o-u)-m*(a-l))/p;return!(!i&&(b<0||b>1))&&{x:a+y*d,y:o+y*m}};let dt=!1;function mt(){dt||(T(),gt=.01*r,pt=-.5*r,yt=-.5*n,bt=Math.round(2*r/gt),_t=Math.round(2*n/gt),Mt("hand",(t,e)=>{const r=$(.2,.8),n=q(5,10);return Tt(e,(e,i)=>.5*n*ot(r*i*e+q(15,25))*.2*at(t)+Z(e,i)*n*.7)}),Mt("curved",(t,e)=>{let r=q(-10,10);return q(0,100)%2==0&&(r*=-1),Tt(e,(e,n)=>3*J(Z(.02*e+.03*t,.02*n+.03*t),0,1,-r,r))}),Mt("zigzag",(t,e)=>{let r=q(-30,-15)+Math.abs(44*ot(t));q(0,100)%2==0&&(r*=-1);let n=r,i=0;for(let t=0;t<bt;t++){for(let r=0;r<_t;r++)e[t][r]=i,i+=n,n*=-1;i+=n,n*=-1}return e}),Mt("waves",(t,e)=>{const r=q(10,15)+5*ot(t),n=q(3,6)+3*at(t),i=q(20,35);return Tt(e,(t,e)=>ot(r*t)*i*at(e*n)+q(-3,3))}),Mt("seabed",(t,e)=>{const r=$(.4,.8),n=q(18,26);return Tt(e,(e,i)=>1.1*n*ot(r*i*e+q(15,20))*at(t))}),Mt("spiral",(t,e)=>{const r=q(5,10),n=2*q(0,2)-1,i=q(65,80),a=Array.from({length:r},()=>({x:$(.1,.9)*bt,y:$(.1,.9)*_t}));return Tt(e,(t,e)=>{let r=0,o=0;for(const s of a){const a=t-s.x,c=e-s.y,l=1/(a*a+c*c+1),u=Math.atan2(c,a)*(180/Math.PI),h=n*(u+i)*Math.PI/180;r+=l*Math.cos(h),o+=l*Math.sin(h)}return Math.atan2(o,r)*(180/Math.PI)})}),Mt("columns",(t,e)=>{const r=q(3,8),n=q(25,45);return Tt(e,(t,e)=>ot(t*r)*n)}),dt=!0)}class xt{constructor(t,e){mt();const r=l();this.mx=r.x,this.my=r.y,this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=Math.round((t+this.mx-pt)/gt),this.rowIdx=Math.round((e+this.my-yt)/gt)}reset(){this.plotted=0}isIn(){return S.field.isActive?xt.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const t=r,e=n,i=this.x+this.mx,a=this.y+this.my;return i>=-.3*t&&i<=1.3*t&&a>=-.3*e&&a<=1.3*e}angle(t=!1){return S.field.isActive&&(t||this.isIn())?vt.get(S.field.current).field[this.colIdx][this.rowIdx]*S.field.wiggle:0}moveTo(t,e,r=1){this.movePos(ct(t),e,r)}_moveToDegrees(t,e,r=1){this.movePos(t,e,r)}plotTo(t,e,r,n=1){this.movePos(t,e,r,n)}movePos(t,e,r,n=!1){const i=n||1;if(!this.isIn())return void(this.plotted+=r/i);const a=e/r,o=S.field.isActive,s=!!n;for(let e=0;e<a;e++){const e=(o?this.angle(!0):0)-(s?t.angle(this.plotted):t);this.update(this.x+r*at(e),this.y+r*ot(e)),this.plotted+=r/i}}static getRowIndex(t,e=1){const r=t+l().y-yt;return Math.round(r/gt/e)}static getColIndex(t,e=1){const r=t+l().x-pt;return Math.round(r/gt/e)}static isIn(t,e){return t>=0&&e>=0&&t<bt&&e<_t}}S.field={isActive:!1,current:null,wiggle:1};let gt,pt,yt,bt,_t,vt=new Map;const Rt=new Set(["degrees","radians"]);function wt(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!Rt.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function Et(t,e){return function(t,e){if("radians"!==e)return t;for(let e=0;e<t.length;e++)for(let r=0;r<t[e].length;r++)t[e][r]=ct(t[e][r],!0);return t}(t.gen(e,new Array(bt).fill(null).map(()=>new Float32Array(_t))),t.angleMode)}function At(t){if(S.field.wiggle||(S.field.wiggle=1),mt(),!vt.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(vt.keys()).join(", ")}.`);S.field.isActive=!0,S.field.current=t;const e=vt.get(t);e.field||(e.field=Et(e,0))}function Mt(t,e,r={}){vt.set(t,{gen:e,field:null,angleMode:wt(r)})}function St(t=1){At("hand"),S.field.wiggle=t}function Tt(t,e){for(let r=0;r<bt;r++)for(let n=0;n<_t;n++)t[r][n]=e(r,n);return t}const Pt=[],Ct=(t,e,r)=>Math.max(e,Math.min(t,r)),Ft="degrees",kt="radians";let It=null,Dt=Ft;const Lt=[];let Nt={a:1,b:0,c:0,d:1,x:0,y:0};function Bt(t,e){return{a:t.a*e.a+t.c*e.b,b:t.b*e.a+t.d*e.b,c:t.a*e.c+t.c*e.d,d:t.b*e.c+t.d*e.d,x:t.a*e.x+t.c*e.y+t.x,y:t.b*e.x+t.d*e.y+t.y}}class Ut{constructor(t,e,r){if(t?._array)return this.r=Math.round(255*t._array[0]),this.g=Math.round(255*t._array[1]),this.b=Math.round(255*t._array[2]),this.hex=this.rgbToHex(this.r,this.g,this.b),this._array=[...t._array],void(this.gl=this._array);if("string"==typeof t){const e=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)$/i.exec(t);if(e){this.r=Ct(parseInt(e[1]),0,255),this.g=Ct(parseInt(e[2]),0,255),this.b=Ct(parseInt(e[3]),0,255),this.hex=this.rgbToHex(this.r,this.g,this.b);const t=void 0!==e[4]?Ct(parseFloat(e[4]),0,1):1;return this._array=[this.r/255,this.g/255,this.b/255,t],void(this.gl=this._array)}this.hex=this.standardize(t);const r=this.hexToRgb(this.hex);this.r=r.r,this.g=r.g,this.b=r.b}else this.r=Ct(t??0,0,255),this.g=Ct(e??t??0,0,255),this.b=Ct(r??t??0,0,255),this.hex=this.rgbToHex(this.r,this.g,this.b);this._array=[this.r/255,this.g/255,this.b/255,1],this.gl=this._array}rgbToHex(t,e,r){return`#${(1<<24|t<<16|e<<8|r).toString(16).slice(1)}`}hexToRgb(t){t=t.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,(t,e,r,n)=>e+e+r+r+n+n);const e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(!e)throw new Error(`Invalid color value "${t}".`);return{r:parseInt(e[1],16),g:parseInt(e[2],16),b:parseInt(e[3],16)}}standardize(t){const e=function(){if(It)return It;if("undefined"!=typeof document)return It=document.createElement("canvas").getContext("2d"),It;if("undefined"!=typeof OffscreenCanvas)return It=new OffscreenCanvas(1,1).getContext("2d"),It;throw new Error("Standalone color parsing requires CanvasRenderingContext2D support.")}();return e.fillStyle=t,e.fillStyle}_getRed(){return this.r}_getGreen(){return this.g}_getBlue(){return this.b}}function Ot(){var t;(t={usesRadians:()=>"radians"===Dt,fromDegrees:t=>"radians"===Dt?t*Math.PI/180:t,createColor:(...t)=>1===t.length&&t[0]?._array?t[0]:new Ut(...t),getAffineMatrix:()=>Nt}).usesRadians&&(o=t.usesRadians),t.fromDegrees&&(s=t.fromDegrees),t.createColor&&(c=t.createColor),t.getAffineMatrix&&(l=t.getAffineMatrix)}let Yt,zt,Xt,Gt,Zt=null,Vt=!1,$t=1,Ht=0,Wt=0;function qt(t,e,r,n){Zt=t,Ht=e,Wt=r,$t=n;const i=function(t,e,r,n){const i=function(t){return t.getContext("webgl2",{premultipliedAlpha:!0})??t.getContext("webgl2")}(t);if(!i)throw new Error("brush.load(target) requires a canvas with a WebGL2 context.");return{canvas:t,drawingContext:i,width:e,height:r,pixelDensity:()=>n}}(t,e,r,n);h({Renderer:i,Cwidth:e,Cheight:r,Density:n}),Vt=!0}class jt{constructor(t,e=!1){this.a=t,this.vertices=e?t:t.map(([t,e])=>({x:t,y:e})),this.sides=this.vertices.map((t,e,r)=>[t,r[(e+1)%r.length]]),this._intersectionCache={}}intersect(t){const e=`${t.point1.x},${t.point1.y}-${t.point2.x},${t.point2.y}`;if(this._intersectionCache[e])return this._intersectionCache[e];const r=[];for(const[e,n]of this.sides){const i=ft(t.point1,t.point2,e,n);i&&r.push(i)}return this._intersectionCache[e]=r,r}show(){S.wash&&this.wash(),S.fill&&this.fill(),S.mass&&this.mass(),S.hatch&&this.hatch(),S.stroke&&this.draw()}}class Kt{constructor(t){this.segments=[],this.angles=[],this.pres=[],this.type=t,this.dir=0,this.calcIndex(0),this.pol=!1}addSegment(t=0,e=0,r=1,n=!1){this.angles.length>0&&this.angles.pop(),t=n?(t%360+360)%360:st(t),this.angles.push(t,t),this.pres.push(r),this.segments.push(e),this.length=this.segments.reduce((t,e)=>t+e,0)}endPlot(t=0,e=1,r=!1){t=r?(t%360+360)%360:st(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=st(t)}pressure(t){return t>this.length?this.pres[this.pres.length-1]:this.curving(this.pres,t)}angle(t){return t>this.length?this.angles[this.angles.length-1]:(this.calcIndex(t),"curve"===this.type?this.curving(this.angles,t)+this.dir:this.angles[this.index]+this.dir)}curving(t,e){let r=t[this.index],n=t[this.index+1]??r;return Math.abs(n-r)>180&&(n>r?n=-(360-n):r=-(360-r)),J(e-this.suma,0,this.segments[this.index],r,n,!0)}calcIndex(t){this.index=-1,this.suma=0;let e=0;for(;e<=t;)this.suma=e,e+=this.segments[this.index+1],this.index++;return this.index}genPol(t,e,i=1,a){mt();const o=a<0?4:1,s=[],c=Math.round(this.length/o),l=new xt(t+r/2,e+n/2);let u=0,h=0;for(let t=0;t<c;t++){l.plotTo(this,o,o);const t=this.calcIndex(l.plotted);u+=o,(u>=(a<=0?8:Math.max(this.segments[t]*a*$(.7,1.3),20))||t>=h)&&l.x&&(s.push([l.x-r/2,l.y-n/2]),u=0,t>=h&&h++)}return new jt(s)}show(t,e,r=1){S.wash&&this.wash(t,e,r),S.fill&&this.fill(t,e,r),S.mass&&this.mass(t,e,r),S.hatch&&this.hatch(t,e,r),S.stroke&&this.draw(t,e,r)}}function Jt(t,e,r,n,i){const a=ct(n),o=((ct(i)-a)%360+360)%360;if(0===o)return;const s=new Kt("curve"),c=Math.max(1,Math.ceil(o/90)),l=o/c,u=Math.PI*r*l/180;for(let t=0;t<c;t++)s.addSegment(a+t*l+90,u,1,!0);s.endPlot(a+o+90,1,!0);const h=t+r*at(a),f=e-r*ot(a);s.draw(h,f,1)}class Qt{constructor(){this.isClosed=!1,this.curvature=zt,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){ne(this.vert,this.curvature,this.isClosed).show()}}function te(t=0){zt=Q(t,0,1),Yt=new Qt}function ee(t,e,r=1){if(!Yt)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");Yt.vertex(t,e,r)}function re(t=!1){if(!Yt)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(Yt.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(Yt.vertex(...Yt.vert[0]),Yt.isClosed=!0),Yt.show(),Yt=!1}function ne(t,e=.5,r=!1){const n=new Kt(0===e?"segments":"curve"),i=2*Math.PI;if(r&&0!==e&&t.push(t[1]),t&&t.length>0){let a,o,s,c=0;for(let l=0;l<t.length-1;l++)if(e>0&&l<t.length-2){const u=t[l],h=t[l+1],f=t[l+2],d=ut(u[0],u[1],h[0],h[1]),m=ut(h[0],h[1],f[0],f[1]),x=ht(u[0],u[1],h[0],h[1]),g=ht(h[0],h[1],f[0],f[1]),p=e*Math.min(d,m,.5*Math.min(d,m)),y=Math.max(d,m),b=d-p,_=m-p;if(Math.floor(x)===Math.floor(g)){const e=r&&0===l?0:d-c,i=r?0===l?0:m-s:m;n.addSegment(x,e,u[2],!0),l===t.length-3&&n.addSegment(g,i,h[2],!0),c=0,0===l&&(a=d,s=p,o=t[1],c=0)}else{const e={x:h[0]-p*at(-x),y:h[1]-p*ot(-x)},f={x:e.x+y*at(90-x),y:e.y+y*ot(90-x)},d={x:h[0]+p*at(-g),y:h[1]+p*ot(-g)},m={x:d.x+y*at(90-g),y:d.y+y*ot(90-g)},v=ft(e,f,d,m,!0),R=ut(e.x,e.y,v.x,v.y),w=ut(e.x,e.y,d.x,d.y)/2,E=i*R*(2*Math.asin(w/R)*(180/Math.PI))/360,A=r&&0===l?0:b-c,M=l===t.length-3?r?a-p:_:0;n.addSegment(x,A,u[2],!0),n.addSegment(x,isNaN(E)?0:E,u[2],!0),n.addSegment(g,M,h[2],!0),c=p,0===l&&(a=b,s=p,o=[e.x,e.y])}l===t.length-3&&n.endPlot(g,h[2],!0)}else if(0===e){const e=t[l],r=t[l+1],i=ut(e[0],e[1],r[0],r[1]),a=ht(e[0],e[1],r[0],r[1]);n.addSegment(a,i,r[2],!0),l===t.length-2&&n.endPlot(a,1,!0)}n.origin=r&&0!==e?o:t[0]}return n}let ie={createTipSurface:()=>{throw new Error("No stroke runtime adapter registered.")},loadImageTip:()=>{throw new Error("No stroke runtime adapter registered.")}},ae=!1;const oe=(t,e,r)=>{const n=t.createProgram();for(let[i,a]of[[t.VERTEX_SHADER,e],[t.FRAGMENT_SHADER,r]]){const e=t.createShader(i);t.shaderSource(e,a),t.compileShader(e),t.attachShader(n,e)}return t.linkProgram(n),n};let se={beginDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},endDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},resetDirectShaderTracking:()=>{}};const ce=(t,e)=>se.resetDirectShaderTracking(t,e);let le,ue,he,fe,de,me=!1,xe=0,ge=0,pe=null;const ye={},be={};let _e=1,ve=0,Re=0,we=1,Ee=0,Ae=0,Me=0,Se=0,Te=1,Pe=1,Ce=new Float32Array(8192),Fe=0,ke=2048,Ie=32768,De=null,Le=null,Ne=null,Be=null,Ue=null;const Oe={},Ye={};let ze=0,Xe=new Float32Array(1280),Ge=0,Ze=256,Ve=null;const $e=new Map,He=new Float32Array([-1,-1,1,-1,-1,1,1,1]);function We(){return ue}function qe(){return((t,e,r)=>se.beginDirectMaskDraw(t,e,r))(i,le,P.glMask)}function je(t){((t,e,r)=>{se.endDirectMaskDraw(t,e,r)})(i,le,t)}function Ke(t,e,r,n,i){return t?(e<t.minX&&(t.minX=e),r<t.minY&&(t.minY=r),n>t.maxX&&(t.maxX=n),i>t.maxY&&(t.maxY=i),t):{minX:e,minY:r,maxX:n,maxY:i}}function Je(t,e,r,n){if(Fe>=ke){ke*=2;const t=new Float32Array(4*ke);t.set(Ce),Ce=t}const i=t-Me,a=e-Se,o=4*Fe,s=_e*i+Re*a+Ee+Me,c=ve*i+we*a+Ae+Se,l=Pe*r*Te/2;Ce[o]=s,Ce[o+1]=c,Ce[o+2]=l,Ce[o+3]=n/255;const u=s*Pe,h=c*Pe;De=Ke(De,u-l-1,h-l-1,u+l+1,h+l+1),Fe++}function Qe(t,e){if(0===Ge)return;P.glMask.isDrawn=!0;const r=qe();let n=$e.get(e);n||(n=le.createTexture(),le.bindTexture(le.TEXTURE_2D,n),le.texImage2D(le.TEXTURE_2D,0,le.RGBA,le.RGBA,le.UNSIGNED_BYTE,t.canvas),le.texParameteri(le.TEXTURE_2D,le.TEXTURE_MIN_FILTER,le.LINEAR),le.texParameteri(le.TEXTURE_2D,le.TEXTURE_MAG_FILTER,le.LINEAR),le.texParameteri(le.TEXTURE_2D,le.TEXTURE_WRAP_S,le.CLAMP_TO_EDGE),le.texParameteri(le.TEXTURE_2D,le.TEXTURE_WRAP_T,le.CLAMP_TO_EDGE),$e.set(e,n)),le.useProgram(Le),le.enable(le.BLEND),le.blendFunc(le.ONE_MINUS_DST_ALPHA,le.ONE),le.activeTexture(le.TEXTURE0),le.bindTexture(le.TEXTURE_2D,n),le.uniform1i(Ye.u_tex,0);const a=S.stroke.color._array;le.uniform4f(Ye.u_color,...a),le.uniformMatrix4fv(Ye.u_proj,!1,We()),le.bindVertexArray(Ne),le.bindBuffer(le.ARRAY_BUFFER,Ue);const o=5*Ge*4,s=Xe.subarray(0,5*Ge);o>ze?(le.bufferData(le.ARRAY_BUFFER,Xe,le.DYNAMIC_DRAW),ze=Xe.byteLength):le.bufferSubData(le.ARRAY_BUFFER,0,s),le.drawArraysInstanced(le.TRIANGLE_STRIP,0,4,Ge),le.flush(),le.bindVertexArray(null),le.bindTexture(le.TEXTURE_2D,null),je(r),Ve&&(P.markDirtyRect(P.glMask,Ve),Ve=null),Ge=0,ce(i,le)}ae||(b={ensureResources:function(t,e,r,n){return function(t,e,r,n){return!t.glMask||t.glMask.width!==e||t.glMask.height!==r||"function"==typeof t.glMask.pixelDensity&&t.glMask.pixelDensity()!==n}(t,e,r,n)&&(t.glMask?.remove&&t.glMask.remove(),t.glMask=y(t,{width:e,height:r,density:n,antialias:!1,depth:!1,stencil:!1})),t.glMask.dirtyRect??=null,t.glMask.isDrawn??=!1,t.glMask},clearMask:function(t,e){t&&(e(t),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:function(t,e,r,n,i){return t?t.dirtyRect?e()?r():i(n(t.dirtyRect,2)):r():null},getShaderMask:function(t,e){return e}},ae=!0),S.stroke={color:null,weight:1,type:"HB",isActive:!1,opacity:1};let tr=new Map;const er={offset:.08,scale:.08,warp:.06,tilt:.06};function rr(){return{...S.stroke}}function nr(t){S.stroke={...t}}function ir(t,e){if(e.type=["marker","custom","image","spray"].includes(e.type)?e.type:"default",void 0===e.markerTip&&(e.markerTip=!0),void 0===e.noise&&(e.noise=.3),e.noise=Math.max(0,Math.min(1,e.noise)),void 0!==e.vibration&&void 0===e.scatter&&(e.scatter=e.vibration),void 0!==e.definition&&void 0===e.sharpness&&(e.sharpness=e.definition),void 0!==e.quality&&void 0===e.grain&&(e.grain=e.quality),e.pressure=function(t){if(!t)return t;if("function"==typeof t)return{type:"custom",min_max:[0,1],curve:t,variation:{...er}};if("object"==typeof t&&!Array.isArray(t)){if("custom"===t.type||"custom"===t.mode){const{mode:e,...r}=t;return{...r,type:"custom",variation:{...er,...r.variation??{}}}}return"gaussian"===t.type||"gaussian"===t.mode||Array.isArray(t.curve)&&Array.isArray(t.min_max)?{...t,type:"gaussian",curve:t.curve,min_max:t.min_max}:t}if(Array.isArray(t)){const[e,r,n]=2===t.length?[t[0],(t[0]+t[1])/2,t[1]]:t,i=Math.min(e,r,n),a=Math.max(e,r,n),o=a-i||1,[s,c,l]=[(e-i)/o,(r-i)/o,(n-i)/o];return{type:"custom",min_max:[i,a],variation:{...er},curve:t=>t<.5?s+(c-s)*t*2:c+(l-c)*(t-.5)*2}}}(e.pressure),"custom"===e.type){if("function"!=typeof e.tip)throw new Error(`Brush "${t}" is type "custom" but is missing a tip function.`);const r=`custom::${t}`;!function(t){const e=$e.get(t);e&&le&&le.deleteTexture(e),$e.delete(t)}(r);const n=ie.createTipSurface(500,500);return n.pixelDensity(1),n.background(255),n.noSmooth(),n.push(),n.translate(250,250),n.scale(5),n.noStroke(),e.tip(n),n.pop(),Sr.imageToWhite(n),Sr.tips.set(r,n),e.tipKey=r,void tr.set(t,{param:e,colors:[],buffers:[]})}if("image"===e.type){if(!e.image||!e.image.src)throw new Error(`Brush "${t}" is type "image" but is missing params.image.src. Example: image: { src: "./tip.jpg" }`);return Sr.add(e.image.src),tr.set(t,{param:e,colors:[],buffers:[]}),Sr.load()}tr.set(t,{param:e,colors:[],buffers:[]})}function ar(t){return tr.get(t)?.param??null}function or(t){if(!tr.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...tr.keys()].join(", ")}.`);S.stroke.type=t}function sr(t,e,r){f(),S.stroke.color=c(...arguments),S.stroke.isActive=!0}function cr(t){S.stroke.weight=t}function lr(t,e,r=1){or(t),sr(e),cr(r)}let ur,hr,fr,dr;const mr={};function xr(t,e,i,o=!1){!function(){const t=l();_e=t.a,ve=t.b,Re=t.c,we=t.d,Ee=t.x,Ae=t.y,Me=r/2,Se=n/2,Te=Math.sqrt(_e*_e+ve*ve),Pe=a}(),ur=new xt(t+r/2,e+n/2),hr=i,fr=o,fr&&fr.calcIndex(0)}const gr=[];function pr(t,e){e||(dr=t),function(){mr.seed=999999*V();const{param:t}=tr.get(S.stroke.type)??{};if(!t)return;mr.p=t;const{pressure:e}=t;if(mr.a="custom"!==e.type?V(-1,1):0,mr.b="custom"!==e.type?V(1,1.5):0,"custom"!==e.type)mr.cp=V(3,3.5),mr.ct=0,mr.cs=1,mr.ck=0;else{const t=e.variation??er;mr.cp=V(-t.offset,t.offset),mr.ct=V(-t.warp,t.warp),mr.cs=V(1-t.scale,1+t.scale),mr.ck=V(-t.tilt,t.tilt)}[mr.min,mr.max]=e.min_max,mr.noiseoffset=.05*mr.p.noise,fr||(mr.cos=at(dr),mr.sin=ot(dr)),function(){T(),function(){const t=i?.glMask;t&&(pe=t,pe.dirtyRect??=null,pe.isDrawn??=!1,P.glMask=pe)}();const t=i.drawingContext,e=!me||le!==t;(e||xe!==r||ge!==n)&&(ue=new Float32Array([2/r,0,0,0,0,2/n,0,0,0,0,1,0,-1,-1,0,1]),xe=r,ge=n),e&&(le=t,de=oe(le,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_position;in float a_radius;in float a_alpha;uniform mat4 u_matrix;out float v_alpha;void main(){gl_Position=u_matrix*vec4(a_position,0.0,1.0);v_alpha=a_alpha;gl_PointSize=a_radius*2.0;}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin float v_alpha;out vec4 outColor;uniform vec4 u_color;void main(){vec2 v=gl_PointCoord-vec2(0.5);float f=length(v);float a=fwidth(f);f=1.0-smoothstep(0.5-a,0.5+a,f);if(f<0.01){discard;}outColor=vec4(u_color.xyz,v_alpha*f);}"),le.useProgram(de),le.enable(le.BLEND),le.blendFunc(le.ONE_MINUS_DST_ALPHA,le.ONE),["a_position","a_radius","a_alpha"].forEach(t=>ye[t]=le.getAttribLocation(de,t)),["u_matrix","u_color"].forEach(t=>be[t]=le.getUniformLocation(de,t)),he=le.createVertexArray(),le.bindVertexArray(he),fe=le.createBuffer(),le.bindBuffer(le.ARRAY_BUFFER,fe),le.bufferData(le.ARRAY_BUFFER,Ce.byteLength,le.DYNAMIC_DRAW),Ie=Ce.byteLength,le.enableVertexAttribArray(ye.a_position),le.vertexAttribPointer(ye.a_position,2,le.FLOAT,!1,16,0),le.enableVertexAttribArray(ye.a_radius),le.vertexAttribPointer(ye.a_radius,1,le.FLOAT,!1,16,8),le.enableVertexAttribArray(ye.a_alpha),le.vertexAttribPointer(ye.a_alpha,1,le.FLOAT,!1,16,12),le.bindVertexArray(null),$e.clear(),Le=oe(le,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_corner;in vec2 a_pos;in float a_size;in float a_angle;in float a_alpha;uniform mat4 u_proj;out vec2 v_uv;out float v_alpha;void main(){float c=cos(a_angle);float s=sin(a_angle);vec2 rotated=vec2(c*a_corner.x-s*a_corner.y,s*a_corner.x+c*a_corner.y);gl_Position=u_proj*vec4(a_pos+rotated*a_size,0.0,1.0);v_uv=a_corner*0.5+0.5;v_alpha=a_alpha;}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin vec2 v_uv;in float v_alpha;uniform sampler2D u_tex;uniform vec4 u_color;out vec4 outColor;void main(){float inkAlpha=texture(u_tex,v_uv).a;if(inkAlpha<0.01)discard;outColor=vec4(u_color.rgb,inkAlpha*v_alpha);}"),["a_corner","a_pos","a_size","a_angle","a_alpha"].forEach(t=>Oe[t]=le.getAttribLocation(Le,t)),["u_proj","u_color","u_tex"].forEach(t=>Ye[t]=le.getUniformLocation(Le,t)),Ne=le.createVertexArray(),le.bindVertexArray(Ne),Be=le.createBuffer(),le.bindBuffer(le.ARRAY_BUFFER,Be),le.bufferData(le.ARRAY_BUFFER,He,le.STATIC_DRAW),le.enableVertexAttribArray(Oe.a_corner),le.vertexAttribPointer(Oe.a_corner,2,le.FLOAT,!1,0,0),Ue=le.createBuffer(),le.bindBuffer(le.ARRAY_BUFFER,Ue),le.bufferData(le.ARRAY_BUFFER,Xe.byteLength,le.DYNAMIC_DRAW),ze=Xe.byteLength,le.enableVertexAttribArray(Oe.a_pos),le.vertexAttribPointer(Oe.a_pos,2,le.FLOAT,!1,20,0),le.vertexAttribDivisor(Oe.a_pos,1),le.enableVertexAttribArray(Oe.a_size),le.vertexAttribPointer(Oe.a_size,1,le.FLOAT,!1,20,8),le.vertexAttribDivisor(Oe.a_size,1),le.enableVertexAttribArray(Oe.a_angle),le.vertexAttribPointer(Oe.a_angle,1,le.FLOAT,!1,20,12),le.vertexAttribDivisor(Oe.a_angle,1),le.enableVertexAttribArray(Oe.a_alpha),le.vertexAttribPointer(Oe.a_alpha,1,le.FLOAT,!1,20,16),le.vertexAttribDivisor(Oe.a_alpha,1),le.bindVertexArray(null),me=!0)}();const a=!0!==P.isBrush;P.isBrush=!0,a&&(P.justChanged=!0),P.blend(S.stroke.color),mr.alpha=["default","spray"].includes(mr.p.type)?mr.p.opacity:mr.p.opacity/Math.min(S.stroke.weight,1.3),wr()}();const a=function(){const{param:t}=tr.get(S.stroke.type)??{};return t?t.spacing:1}(),o=Math.round(hr*(e?t:1)/a);mr.pressureCount=10,mr.cachedPressure=void 0,mr.lineNoiseCount=5,mr.cachedLineNoise=void 0;for(let r=0;r<o;r++)gr.length<2*o&&gr.push(j()),yr(),e?ur.plotTo(fr,a,a,t,r<10):ur._moveToDegrees(t,a,a);!function(){wr(),function(){if(0===Fe)return;P.glMask.isDrawn=!0;const t=qe(),e=S.stroke.color._array;le.useProgram(de),le.enable(le.BLEND),le.blendFunc(le.ONE_MINUS_DST_ALPHA,le.ONE),le.bindVertexArray(he),le.bindBuffer(le.ARRAY_BUFFER,fe);const r=16*Fe,n=Ce.subarray(0,4*Fe);r>Ie?(le.bufferData(le.ARRAY_BUFFER,Ce,le.DYNAMIC_DRAW),Ie=Ce.byteLength):le.bufferSubData(le.ARRAY_BUFFER,0,n),le.uniform4f(be.u_color,...e),le.uniformMatrix4fv(be.u_matrix,!1,We()),le.drawArrays(le.POINTS,0,Fe),le.flush(),le.bindVertexArray(null),je(t),De&&(P.markDirtyRect(P.glMask,De),De=null),Fe=0,ce(i,le)}();const t=mr.p?.type;"image"===t?Qe(Sr.tips.get(mr.p.image.src),mr.p.image.src):"custom"===t&&Qe(Sr.tips.get(mr.p.tipKey),mr.p.tipKey)}()}function yr(){const t=br(),e=((mr.lineNoiseCount>=10||void 0===mr.cachedLineNoise)&&(mr.cachedLineNoise=J(G(mr.seed+.01*ur.plotted,0),-1,1,1-mr.noiseoffset,1+mr.noiseoffset),mr.lineNoiseCount=0),mr.lineNoiseCount++,mr.cachedLineNoise);if(!(e>V(1,1.02)&&V(0,1)<.7))switch(mr.p.type){case"spray":!function(t){const e=S.stroke.weight*mr.p.scatter*t+S.stroke.weight*H(gr)*mr.p.scatter/3,r=mr.p.weight*V(.9,1.1),n=Math.ceil(mr.p.grain/t);for(let t=0;t<n;t++){const t=V(.9,1.1),n=t*e*V(-1,1),i=V(-1,1),a=Math.sqrt((t*e)**2-n**2);Je(ur.x+n,ur.y+i*a,r,mr.alpha)}}(t*e);break;case"marker":vr(t*e);break;case"custom":case"image":Rr(t*e);break;default:!function(t,e=1){const r=(e=J(e,0,1,.9,1.05))*S.stroke.weight*mr.p.scatter*(mr.p.sharpness+(1-mr.p.sharpness)*H(gr)/t);if(V(0,mr.p.grain*t)>.4){let e,n;if(fr){const t=fr.angle(ur.plotted),i=at(t),a=ot(t),o=r*V(-1,1),s=.3*r*V(-1,1);e=o*a+s*i,n=o*i-s*a}else{const t=r*V(-1,1),i=.3*r*V(-1,1);e=t*mr.sin+i*mr.cos,n=t*mr.cos-i*mr.sin}const i=t*t*mr.p.weight*V(.85,1.15)*S.stroke.weight,a=Math.max(.9,t)*mr.alpha*V(.75,1.1);Je(ur.x+e,ur.y+n,i,a)}}(t*e)}}function br(){return(mr.pressureCount>=10||void 0===mr.cachedPressure)&&(mr.cachedPressure=fr?_r()*fr.pressure(ur.plotted):_r(),mr.pressureCount=0),mr.pressureCount++,mr.cachedPressure}function _r(){return"custom"===mr.p.pressure.type?J(mr.p.pressure.curve(Math.max(0,Math.min(1,.5+(ur.plotted/hr-.5+mr.ct)*mr.cs)))+mr.cp+mr.ck*(ur.plotted/hr-.5),0,1,mr.min,mr.max,!0):function(t=.5+mr.p.pressure.curve[0]*mr.a,e=1-mr.p.pressure.curve[1]*mr.b,r=mr.cp,n=mr.min,i=mr.max){const a=t*hr,o=(ur.plotted<a?1.2*e:.8*e)*(hr/2);return J(1/(1+Math.pow(Math.abs((ur.plotted-a)/o),2*r)),0,1,n,i)}()}function vr(t,e=!0,r=mr.alpha){const n=e?S.stroke.weight*mr.p.scatter:0,i=e?n*V(-1,1):0,a=e?n*V(-1,1):0;Je(ur.x+i,ur.y+a,S.stroke.weight*mr.p.weight*t,r*Math.max(.8,t)*V(.9,1.1))}function Rr(t,e=mr.alpha){const r=S.stroke.weight*mr.p.scatter,n=r*V(-1,1),i=r*V(-1,1),a=mr.p.weight*S.stroke.weight*t,o=function(){const t=Math.max(1,mr.max??1),e=S.stroke.weight*mr.p.scatter,r=S.stroke.weight*mr.p.weight*t;return Math.max(8,1.5*e+.75*r)}();let s=0;"random"===mr.p.rotate?s=W(0,360)*(Math.PI/180):"natural"===mr.p.rotate&&(s=((fr?-fr.angle(ur.plotted):-dr)+ur.angle())*(Math.PI/180)),function(t,e,r,n,i,a=0){if(Ge>=Ze){Ze*=2;const t=new Float32Array(5*Ze);t.set(Xe),Xe=t}const o=t-Me,s=e-Se,c=_e*o+Re*s+Ee+Me,l=ve*o+we*s+Ae+Se,u=Pe*r*Te/2,h=Pe*a*Te,f=5*Ge;Xe[f]=c,Xe[f+1]=l,Xe[f+2]=u,Xe[f+3]=n,Xe[f+4]=i/255;const d=c*Pe,m=l*Pe,x=1.42*u+h;Ve=Ke(Ve,d-x-1,m-x-1,d+x+1,m+x+1),Ge++}(ur.x+n,ur.y+i,a,s,e*Math.max(.8,t)*V(.9,1.1),o)}function wr(){if(!1===mr.p.markerTip)return;let t=br(),e=mr.alpha;if("marker"===mr.p.type)for(let r=1;r<10;r++)vr(t*r/10,!0,8*e);else if("custom"===mr.p.type||"image"===mr.p.type)for(let r=1;r<5;r++)Rr(t*r/10,2*e)}function Er(t,e,r,n){if(!S.stroke.isActive||!S.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");mt();let i=ut(t,e,r,n);0!=i&&(xr(t,e,i),pr(ht(t,e,r,n),!1))}X(()=>{gr.length=0});const Ar=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate","markerTip","noise"],Mr=[["pen",[.3,.15,.9,2,150,.1,{curve:[.15,.2],min_max:[1.2,1]}]],["rotring",[.15,.05,.7,15,210,.1,{curve:[.35,.2],min_max:[1.3,1]}]],["2B",[.3,.75,.45,15,180,.1,{curve:[.1,.3],min_max:[1.1,.9]}]],["HB",[.3,.6,.3,10,170,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["2H",[.2,.6,.3,4,120,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["cpencil",[.3,.55,.8,7,75,.1,{curve:[.15,.2],min_max:[.95,1.2]}]],["pastel",[2.05/3,13.4/3,.91,28,35,.085/3,{mode:"gaussian",curve:[.4,.05],min_max:[1.09,.93]},"default",void 0,"natural",!0,1]],["crayon",[.3,5.45/3,.75,250,159,.23/3,[1.1,.9],"default",void 0,"natural",!0,1]],["charcoal",[.35,1.5,.68,500,120,.03,{curve:[.15,.4],min_max:[1.1,.95]}]],["spray",[.2,6,15,40,90,.5,{curve:[.2,.35],min_max:[.7,1]},"spray"]],["marker",[2,.2,null,null,1,.03,{curve:[.35,.25],min_max:[1.2,.85]},"marker"]]];for(let t of Mr){let e={};for(let r=0;r<t[1].length;r++)e[Ar[r]]=t[1][r];ir(t[0],e)}jt.prototype.draw=function(t=!1,e,r){let n=rr();if(t&&lr(t,e,r),n.isActive)for(let t of this.sides)Er(t[0].x,t[0].y,t[1].x,t[1].y);nr(n)},Kt.prototype.draw=function(t,e,r){rr().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,n){mt(),xr(e,r,t.length,t),pr(n,!0)}(this,t,e,r))};const Sr={tips:new Map,add(t){this.tips.has(t)||this.tips.set(t,!1)},imageToWhite(t){t.loadPixels();for(let e=0;e<4*t.width*t.height;e+=4){let r=(t.pixels[e]+t.pixels[e+1]+t.pixels[e+2])/3;t.pixels[e]=t.pixels[e+1]=t.pixels[e+2]=255,t.pixels[e+3]=255-r}t.updatePixels()},async load(){const t=[...this.tips.keys()].filter(t=>!this.tips.get(t));await Promise.all(t.map(t=>((t,e)=>ie.loadImageTip(t,e))(t,Sr.imageToWhite).then(e=>{this.tips.set(t,e)})))}};function Tr(){return{...S.hatch}}function Pr(t){S.hatch={...t}}function Cr(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let n=S.hatch;n.isActive=!0,n.dist=t,n.angle=ct(e),n.options=r}function Fr(t,e,r,n){const i=e*Math.PI/180,a=Math.cos(i),o=Math.sin(i),s=Math.cos(-i),c=Math.sin(-i),l=t.a,u=l.length,h=new Array(u);let f=Infinity,d=-Infinity;for(let t=0;t<u;t++){const e=l[t][0],r=l[t][1],n=[e*a-r*o,e*o+r*a];h[t]=n,n[1]<f&&(f=n[1]),n[1]>d&&(d=n[1])}const m=[];for(let t=0;t<u;t++){const e=h[t],r=h[(t+1)%u];e[1]!==r[1]&&m.push(e,r)}const x=m.length,g=[],p=[];let y=f+.5*r,b=r;for(;y<d;){p.length=0;for(let t=0;t<x;t+=2){const e=m[t][1],r=m[t+1][1];(e<=y&&y<r||r<=y&&y<e)&&p.push(m[t][0]+(y-e)/(r-e)*(m[t+1][0]-m[t][0]))}p.sort((t,e)=>t-e);for(let t=0;t<p.length-1;t+=2)g.push({scanY:y,x1:p[t]*s-y*c,y1:p[t]*c+y*s,x2:p[t+1]*s-y*c,y2:p[t+1]*c+y*s});y+=b,b*=n}return g}function kr(t){const{dist:e,options:r,segs:n}=function(t){const e=S.hatch.dist,r=(S.hatch.angle%180+180)%180,n=S.hatch.options,i=function(t,e,r,n){Array.isArray(t)||(t=[t]);const i=[];for(const a of t)for(const t of Fr(a,r,e,n))i.push(t);return i.sort((t,e)=>t.scanY===e.scanY?t.x1-e.x1:t.scanY-e.scanY),i}(t,e,r,n.gradient?J(n.gradient,0,1,1,1.1,!0):1);return{dist:e,options:n,segs:i}}(t),i=r.rand||0,a=[];for(let t=0;t<n.length;t++){const o=n[t];let s=o.x1,c=o.y1,l=o.x2,u=o.y2;i&&(s+=2*i*e*V(-1,1),c+=2*i*e*V(-1,1),l+=2*i*e*V(-1,1),u+=2*i*e*V(-1,1));const h=r.continuous&&t%2==1?{x1:l,y1:u,x2:s,y2:c,scanY:o.scanY,isConnector:!1}:{x1:s,y1:c,x2:l,y2:u,scanY:o.scanY,isConnector:!1};if(a.push(h),t>0&&r.continuous){const t=a[a.length-2];a.push({x1:t.x2,y1:t.y2,x2:h.x1,y2:h.y1,scanY:o.scanY,isConnector:!0})}}return a}function Ir(t){!function(t,e){const r=kr(t);!function(){const t=rr();S.hatch.hBrush&&lr(...Object.values(S.hatch.hBrush)),(()=>{for(let t=0;t<r.length;t++){const n=r[t];e(n.x1,n.y1,n.x2,n.y2,t,r)}})(),nr(t)}()}(t,(t,e,r,n)=>{Er(t,e,r,n)})}function Dr(t,e,r){return new jt(t.vertices.map(t=>[t.x+e,t.y+r]))}function Lr(t,e,r,n,i){const a=(e+n)/2,o=(r+i)/2,s=n-e,c=i-r,l=Math.hypot(s,c);if(!l)return null;const u=-c/l,h=s/l,f=(t.x-a)*u+(t.y-o)*h;return{x:a+u*f,y:o+h*f}}function Nr(t,e,r,n,i,a,o){let s=ht(t,e,r,n),c=ht(t,e,i,a);return((c-s)%360+360)%360>180&&([s,c]=[c,s]),[o(s),o(c)]}function Br(t){const e=$(.35,.65),r=t.x1+(t.x2-t.x1)*e,n=t.y1+(t.y2-t.y1)*e,i=t.x2-t.x1,a=t.y2-t.y1,o=Math.hypot(i,a)||1,s=$(.04,.1)*o,c=i/o*s*.5,l=a/o*s*.5;return[{x1:t.x1,y1:t.y1,x2:r-c,y2:n-l},{x1:r+c,y1:n+l,x2:t.x2,y2:t.y2}]}function Ur(t,e,r){const n=function(t,e){const r=function(t){const e=t?.a??[];let r=Infinity,n=Infinity,i=-Infinity,a=-Infinity;for(const[t,o]of e)t<r&&(r=t),o<n&&(n=o),t>i&&(i=t),o>a&&(a=o);return{minX:r,minY:n,maxX:i,maxY:a,cx:(r+i)/2,cy:(n+a)/2,size:Math.hypot(i-r,a-n)}}(t),n=r.size*$(.6,1.4),[i,a]=e;return{x:r.cx+i*n,y:r.cy+a*n}}(t,e);for(const e of kr(t)){const t=!e.isConnector&&$()<.35?Br(e):[e];for(const e of t){const t=Lr(n,e.x1,e.y1,e.x2,e.y2);if(!t)continue;const i=ut(t.x,t.y,e.x1,e.y1);if(!i)continue;const[a,o]=Nr(t.x,t.y,e.x1,e.y1,e.x2,e.y2,r);Jt(t.x,t.y,i,a,o)}}}function Or(t,e,r,n,i,a){Cr(e,r,n),Ur(t,i,a)}function Yr(t,e,r,n){const i=function(t,e,r,n){const i=!1===e,a=ar(S.mass.brush)?.scatter??0,o=i?t:t.genPol(e,r,n,.15),s=Math.min(2*a,5),c=[[$(-s,s),$(-s,s)],[$(-s,s),$(-s,s)]];return[o,Dr(o,c[0][0],c[0][1]),Dr(o,c[1][0],c[1][1])]}(t,e,r,n),a=Tr(),c=rr(),l={...S.field},u=S.mass.options?.precision??.5,h=S.mass.options?.strength??1,f=S.mass.options?.gradient??.1,d=S.mass.options?.outline??!1,m=ar(S.mass.brush)?.scatter??0,x=1.6*$(.65*m,.85*m)-.4*f,g=$(-90,90),p=((g+90)%180+180)%180-90>=0?$()<.5?[1,1]:[-1,-1]:$()<.5?[-1,1]:[1,-1],y=o()?t=>t*Math.PI/180:t=>t;lr(S.mass.brush,S.mass.color,1),St(2-u),d&&i[0].draw(),Or(i[0],.9*x,s(g),{gradient:f,rand:2-2*u,continuous:!0},p,y),h>.33&&Or(i[1],x,s(g+20*$(-1,1)),{gradient:f,rand:.6-.6*u,continuous:!0},p,y),h>.66&&Or(i[2],.8*x,s(g+15*$(-1,1)),{gradient:f,rand:.6-.6*u,continuous:!0},p,y),nr(c),Pr(a),S.field={...l}}function zr(t,e,r){const n=2*Math.PI,i=P.ctx,a=r/2;i.moveTo(t+a,e),i.arc(t,e,a,0,n)}S.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},jt.prototype.hatch=function(t=!1,e,r){let n=Tr();t&&Cr(t,e,r),S.hatch.isActive&&Ir(this),Pr(n)},Kt.prototype.hatch=function(t,e,r){Tr().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,.3),this.pol.hatch())},S.mass={isActive:!1,brush:null,color:null,options:{}},jt.prototype.mass=function(){S.mass?.isActive&&Yr(this,!1)},Kt.prototype.mass=function(t,e,r){S.mass?.isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),Yr(this,t,e,r))};let Xr=null,Gr=!1;Gr||(_={ensureResources:function(t,e,r,n,i){const a=Math.max(1,Math.round(e*n)),o=Math.max(1,Math.round(r*n));return function(t,e,r){return!t.mask||t.mask.width!==e||t.mask.height!==r}(t,a,o)&&(t.mask=g(a,o)),function(t,e,r,n){return!t.fillMaskFramebuffer||t.fillMaskFramebuffer.width!==e||t.fillMaskFramebuffer.height!==r||"function"==typeof t.fillMaskFramebuffer.pixelDensity&&t.fillMaskFramebuffer.pixelDensity()!==n}(t,e,r,n)&&(t.fillMaskFramebuffer?.remove&&t.fillMaskFramebuffer.remove(),t.fillMaskFramebuffer=y(t,{width:e,height:r,density:n,antialias:!1,depth:!1,stencil:!1}),i(t.fillMaskFramebuffer)),t.mask.dirtyRect??=null,t.mask.isDrawn??=!1,t.mask.drawingContext.imageSmoothingEnabled=!1,{mask:t.mask,ctx:t.mask.drawingContext}},clearMask:function(t,e){t&&(e(t),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:function(t,e,r,n,i){return t?t.dirtyRect?i(n(t.dirtyRect,4)):r():null},getShaderMask:function(t,e,r,n,i,a){const o=t.fillMaskFramebuffer,s=t.drawingContext,c=n(r)??i(),l=c.maxX-c.minX,u=c.maxY-c.minY;Xr&&Xr.width===l&&Xr.height===u||(Xr=g(l,u));const h=Xr.drawingContext;return h.clearRect(0,0,l,u),h.drawImage(e,c.minX,c.minY,l,u,0,0,l,u),a(o),s.bindTexture(s.TEXTURE_2D,o.colorTexture),s.texSubImage2D(s.TEXTURE_2D,0,c.minX,c.minY,s.RGBA,s.UNSIGNED_BYTE,Xr),o}},Gr=!0);let Zr,Vr=[],$r=[],Hr=[],Wr=[];S.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const qr=()=>({...S.fill});function jr(t,e,r,n){S.fill.opacity=(arguments.length<4?e:n)||150,S.fill.color=arguments.length<3?c(t):c(t,e,r),S.fill.isActive=!0}function Kr(t,e="out"){S.fill.bleed_strength=Q(t,0,1),S.fill.direction=e}function Jr(t=.4,e=.4){S.fill.texture_strength=Q(t,0,1),S.fill.border_strength=Q(e,0,1)}let Qr;const tn=[[],[]];function en(){for(let t=0;t<512;t++)tn[0][t]=j(.5,.2),tn[1][t]=j(0,.02)}function rn(t,e,r){return(e.x-t.x)*(r.y-t.y)-(e.y-t.y)*(r.x-t.x)>.01}X(en);class nn{constructor(t,e,r,n=[],i=!1,a,o){if(this.v=t,this.m=e,this.dir=n,this.midP=r,i){let e=0,n=0;const i=[];for(let a=0;a<t.length;a++){const o=Math.abs(r.x-t[a].x),s=Math.abs(r.y-t[a].y);e=Math.max(e,o),n=Math.max(n,s);const c=t[a],l=t[(a+1)%t.length],u={x:l.x-c.x,y:l.y-c.y},h=lt(0,0,u.x,u.y,90),f={x:c.x+u.x/2,y:c.y+u.y/2};i.push({v1:c,v2:l,ray:{point1:f,point2:{x:f.x+h.x,y:f.y+h.y}}})}this.sizeX=e,this.sizeY=n,this.dir=Array(t.length),i.forEach((t,e)=>{let r=0;for(const e of Qr.intersect(t.ray))rn(t.v1,t.v2,e)&&r++;this.dir[e]=r%2==0});const a=V(-.6,.6)*e,o=V(-.6,.6)*n;this.midP={x:r.x+a,y:r.y+o}}else this.sizeX=a,this.sizeY=o}trim(t=1){if(t>=1||t<0||this.v.length<=8)return{v:this.v,m:this.m,dir:this.dir};const e=~~((1-t)*this.v.length),r=~~(this.v.length/2-e/2),n=this.v.length-e,i=new Array(n),a=new Array(n),o=new Array(n);let s=0;for(let t=0;t<r;t++,s++)i[s]=this.v[t],a[s]=this.m[t],o[s]=this.dir[t];for(let t=r+e;t<this.v.length;t++,s++)i[s]=this.v[t],a[s]=this.m[t],o[s]=this.dir[t];const c=r,l=r+e,u=this.v[(c-1+this.v.length)%this.v.length],h=this.v[l%this.v.length],f=h.x-u.x,d=h.y-u.y;for(let t=0;t<2;t++){const e=V(.25,.75),n={x:u.x+f*e,y:u.y+d*e},s=r+t;i.splice(s,0,n),a.splice(s,0,V(.4,.7)),o.splice(s,0,this.dir[c%this.dir.length])}return{v:i,m:a,dir:o}}scatter(t=.3){const e=this.v.length,r=Math.max(3,~~(e*t)),n=[],i=e/r;for(let t=0;t<r;t++)n.push(~~(t*i+V(0,.8*i)));const a=[],o=[],s=[],c=this.midP,l=Qr.sides;for(const t of n){const r=t%e;let n=this.v[r],i=0;for(const[t,e]of l){const r=t.y,a=e.y;if(r>n.y==a>n.y)continue;const o=(n.y-r)/(a-r);n.x<t.x+o*(e.x-t.x)&&i++}i%2==0&&(n={x:c.x+(n.x-c.x)*V(.3,.6),y:c.y+(n.y-c.y)*V(.3,.6)}),a.push(n),o.push(this.m[r]),s.push(!this.dir[r])}return new nn(a,o,this.midP,s,!1,this.sizeX,this.sizeY)}flipDirs(){return new nn(this.v,this.m,this.midP,this.dir.map(t=>!t),!1,this.sizeX,this.sizeY)}grow(t=1){const{v:e,m:r,dir:n}=this.trim(t),i=e.length,a=2*i;Vr.length<i&&(Vr=new Array(i),$r=new Array(i)),Hr.length<a&&(Hr=new Array(a),Wr=new Array(a));const o=Vr,s=$r,c=Hr,l=Wr,u="out"===S.fill.direction?-90:90;0===tn[0].length&&en();const h=tn[0],f=h.length,d=tn[1],m=d.length;let x,g,p,y=0,b=0,_=999===t?V(.6,.8):S.fill.bleed_strength;for(let a=0;a<i;a++){const x=e[a],g=e[a+1<i?a+1:0],p=r[a],v=n[a];if(t<997&&(_=p),_<.05){c[y]=p,l[y]=v,y++,o[b]=(x.x+g.x)/2,s[b]=(x.y+g.y)/2,c[y]=p,l[y]=v,y++,b++;continue}const R=(v?u:-u)+5*V(-1,1),w=at(R),E=ot(R),A=g.x-x.x,M=g.y-x.y,S=w*A+E*M,T=w*M-E*A,P=h[~~(V(0,1)*f)]*V(.65,1.35)*_,C=p+d[~~(V(0,1)*m)];c[y]=p,l[y]=v,y++,o[b]=x.x+.5*A+S*P,s[b]=x.y+.5*M+T*P,c[y]=C,l[y]=v,y++,b++}if(Zr&&y>Zr){const t=Math.ceil(y/Zr),r=Math.ceil(y/t);x=new Array(r),g=new Array(r),p=new Array(r);let n=0;for(let r=0;r<y;r+=t,n++)x[n]=r%2==0?e[r>>1]:{x:o[r>>1],y:s[r>>1]},g[n]=c[r],p[n]=l[r]}else{x=new Array(y);for(let t=0;t<y;t++)x[t]=t%2==0?e[t>>1]:{x:o[t>>1],y:s[t>>1]};g=c.slice(0,y),p=l.slice(0,y)}return new nn(x,g,this.midP,p,!1,this.sizeX,this.sizeY)}fill(t,e,i){const o=3*i,s=2*e*(1+i/2),c=!1!==P.isBrush;P.isBrush=!1,c&&(P.justChanged=!0),P.blend(t);const u=l();P.ctx.save(),P.ctx.setTransform(a*u.a,a*u.b,a*u.c,a*u.d,a*(u.x+r/2),a*(u.y+n/2)),P.ctx.strokeStyle=`rgb(${t._getRed()} ${t._getGreen()} ${t._getBlue()} / ${.005*S.fill.border_strength})`,P.ctx.lineCap="round",Zr=2024*Math.max(.1,2*S.fill.bleed_strength);const h=Math.max(this.sizeX,this.sizeY),f=V(.15,.7);let d=this.grow();const m=this.scatter(.1).grow().scatter(.75).flipDirs();let x;for(let r=0;r<20;r++){r%4==0&&(d=d.grow()),r%2==0&&(x=[d.grow(1-.0125*r),d.grow(.7-.0125*r),d.grow(.4-.0125*r)]);for(const e of x)e.grow(999).grow(997).layer(r,h,s,t);m.grow(999).flipDirs().grow(997).layer(r,h,s*o,t),r%2==0&&d.grow(f).grow(999).layer(r,h,2*s,t),r%8!=0&&19!==r||(0!==o&&d.erase(3*o,e),P.blend(t,!0))}P.ctx.restore()}layer(t,e,r,n){P.ctx.lineWidth=J(t,0,24,e/25,e/30,!0),P.ctx.fillStyle=`rgb(${n._getRed()} ${n._getGreen()} ${n._getBlue()} / ${r}%)`,function(t){const e=P.ctx,r=e.getTransform(),n=r.a,i=r.b,a=r.c,o=r.d,s=r.e,c=r.f;let l=Infinity,u=Infinity,h=-Infinity,f=-Infinity;e.beginPath();const d=t[0];let m=n*d.x+a*d.y+s,x=i*d.x+o*d.y+c;l=h=m,u=f=x,e.moveTo(d.x,d.y);for(let r=1;r<t.length;r++){const d=t[r];m=n*d.x+a*d.y+s,x=i*d.x+o*d.y+c,l=Math.min(l,m),u=Math.min(u,x),h=Math.max(h,m),f=Math.max(f,x),e.lineTo(d.x,d.y)}e.closePath();const g=function(t,e){const r=t.lineWidth||0;return r<=0?1:1+r*Math.max(Math.hypot(e.a,e.c),Math.hypot(e.b,e.d))/2}(e,r);P.markDirtyRect(P.mask,{minX:l-g,minY:u-g,maxX:h+g,maxY:f+g})}(this.v),P.ctx.fill(),P.ctx.stroke()}erase(t,e){P.ctx.save();const r=~~(V(80,110)*J(t,0,1,2,3.5)),n=this.sizeX/1.3,i=this.sizeY/1.3,a=1.3*Math.min(this.sizeX,this.sizeY),o=.03*a,s=.45*a,{x:c,y:l}=this.midP;P.ctx.globalCompositeOperation="destination-out";const u=(5-J(e,80,100,.3,.7,!0))*t/255;P.ctx.fillStyle=`rgb(255 0 0 / ${u})`,P.ctx.lineWidth=0;for(let t=0;t<r;t++){const e=c+j(0,n),r=l+j(0,i),a=V(o,s);P.ctx.beginPath(),zr(e,r,a),t%5!=0&&P.ctx.fill()}P.ctx.globalCompositeOperation="source-over",P.ctx.restore()}}function an(t,e){if(!t)return t;e||(e=t);let r,n=t;do{if(r=!1,n.steiner||!xn(n,n.next)&&0!==mn(n.prev,n,n.next))n=n.next;else{if(Rn(n),n=e=n.prev,n===n.next)break;r=!0}}while(r||n!==e);return e}function on(t,e,r,n,i,a,o){if(!t)return;!o&&a&&function(t,e,r,n){let i=t;do{0===i.z&&(i.z=hn(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){let e,r=1;do{let n,i=t;t=null;let a=null;for(e=0;i;){e++;let o=i,s=0;for(let t=0;t<r&&(s++,o=o.nextZ,o);t++);let c=r;for(;s>0||c>0&&o;)0!==s&&(0===c||!o||i.z<=o.z)?(n=i,i=i.nextZ,s--):(n=o,o=o.nextZ,c--),a?a.nextZ=n:t=n,n.prevZ=a,a=n;i=o}a.nextZ=null,r*=2}while(e>1)}(i)}(t,n,i,a);let s=t;for(;t.prev!==t.next;){const c=t.prev,l=t.next;if(a?cn(t,n,i,a):sn(t))e.push(c.i,t.i,l.i),Rn(t),t=l.next,s=l.next;else if((t=l)===s){o?1===o?on(t=ln(an(t),e),e,r,n,i,a,2):2===o&&un(t,e,r,n,i,a):on(an(t),e,r,n,i,a,1);break}}}function sn(t){const e=t.prev,r=t,n=t.next;if(mn(e,r,n)>=0)return!1;const i=e.x,a=r.x,o=n.x,s=e.y,c=r.y,l=n.y,u=Math.min(i,a,o),h=Math.min(s,c,l),f=Math.max(i,a,o),d=Math.max(s,c,l);let m=n.next;for(;m!==e;){if(m.x>=u&&m.x<=f&&m.y>=h&&m.y<=d&&fn(i,s,a,c,o,l,m.x,m.y)&&mn(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function cn(t,e,r,n){const i=t.prev,a=t,o=t.next;if(mn(i,a,o)>=0)return!1;const s=i.x,c=a.x,l=o.x,u=i.y,h=a.y,f=o.y,d=Math.min(s,c,l),m=Math.min(u,h,f),x=Math.max(s,c,l),g=Math.max(u,h,f),p=hn(d,m,e,r,n),y=hn(x,g,e,r,n);let b=t.prevZ,_=t.nextZ;for(;b&&b.z>=p&&_&&_.z<=y;){if(b.x>=d&&b.x<=x&&b.y>=m&&b.y<=g&&b!==i&&b!==o&&fn(s,u,c,h,l,f,b.x,b.y)&&mn(b.prev,b,b.next)>=0)return!1;if(b=b.prevZ,_.x>=d&&_.x<=x&&_.y>=m&&_.y<=g&&_!==i&&_!==o&&fn(s,u,c,h,l,f,_.x,_.y)&&mn(_.prev,_,_.next)>=0)return!1;_=_.nextZ}for(;b&&b.z>=p;){if(b.x>=d&&b.x<=x&&b.y>=m&&b.y<=g&&b!==i&&b!==o&&fn(s,u,c,h,l,f,b.x,b.y)&&mn(b.prev,b,b.next)>=0)return!1;b=b.prevZ}for(;_&&_.z<=y;){if(_.x>=d&&_.x<=x&&_.y>=m&&_.y<=g&&_!==i&&_!==o&&fn(s,u,c,h,l,f,_.x,_.y)&&mn(_.prev,_,_.next)>=0)return!1;_=_.nextZ}return!0}function ln(t,e){let r=t;do{const n=r.prev,i=r.next.next;!xn(n,i)&&gn(n,r,r.next,i)&&bn(n,i)&&bn(i,n)&&(e.push(n.i,r.i,i.i),Rn(r),Rn(r.next),r=t=i),r=r.next}while(r!==t);return an(r)}function un(t,e,r,n,i,a){let o=t;do{let t=o.next.next;for(;t!==o.prev;){if(o.i!==t.i&&dn(o,t)){let s=_n(o,t);return o=an(o,o.next),s=an(s,s.next),on(o,e,r,n,i,a,0),void on(s,e,r,n,i,a,0)}t=t.next}o=o.next}while(o!==t)}function hn(t,e,r,n,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function fn(t,e,r,n,i,a,o,s){return!(t===o&&e===s)&&function(t,e,r,n,i,a,o,s){return(i-o)*(e-s)>=(t-o)*(a-s)&&(t-o)*(n-s)>=(r-o)*(e-s)&&(r-o)*(a-s)>=(i-o)*(n-s)}(t,e,r,n,i,a,o,s)}function dn(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&gn(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}(t,e)&&(bn(t,e)&&bn(e,t)&&function(t,e){let r=t,n=!1;const i=(t.x+e.x)/2,a=(t.y+e.y)/2;do{r.y>a!=r.next.y>a&&r.next.y!==r.y&&i<(r.next.x-r.x)*(a-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}(t,e)&&(mn(t.prev,t,e.prev)||mn(t,e.prev,e))||xn(t,e)&&mn(t.prev,t,t.next)>0&&mn(e.prev,e,e.next)>0)}function mn(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function xn(t,e){return t.x===e.x&&t.y===e.y}function gn(t,e,r,n){const i=yn(mn(t,e,r)),a=yn(mn(t,e,n)),o=yn(mn(r,n,t)),s=yn(mn(r,n,e));return i!==a&&o!==s||!(0!==i||!pn(t,r,e))||!(0!==a||!pn(t,n,e))||!(0!==o||!pn(r,t,n))||!(0!==s||!pn(r,e,n))}function pn(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function yn(t){return t>0?1:t<0?-1:0}function bn(t,e){return mn(t.prev,t,t.next)<0?mn(t,e,t.next)>=0&&mn(t,t.prev,e)>=0:mn(t,e,t.prev)<0||mn(t,t.next,e)<0}function _n(t,e){const r=wn(t.i,t.x,t.y),n=wn(e.i,e.x,e.y),i=t.next,a=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,a.next=n,n.prev=a,n}function vn(t,e,r,n){const i=wn(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Rn(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function wn(t,e,r){return{i:t,x:e,y:r,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}jt.prototype.fill=function(t=!1,e,r,n,i,a){let o=qr();t&&(jr(t,e),Kr(r,a),Jr(n,i)),o.isActive&&(mt(),function(t){if(!S.fill.isActive||!S.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");Qr=t;const e=[...t.vertices],r=~~(.25*e.length*K({1:5,2:10,3:60})),n=S.fill.bleed_strength,i=e.map((t,e)=>(e>r?1:.3)*V(.85,1.4)*n),a=W(0,e.length),o=[...e.slice(a),...e.slice(0,a)],s=function(t){if(0===t.length)return{x:0,y:0};if(t.length<8){const e=t.reduce((t,e)=>({x:t.x+e.x,y:t.y+e.y}),{x:0,y:0});return{x:e.x/t.length,y:e.y/t.length}}const e=[...t];e[0].x===e[e.length-1].x&&e[0].y===e[e.length-1].y||e.push(e[0]);let r=0,n=0,i=0;for(let t=0;t<e.length-1;t++){const a=e[t].x*e[t+1].y-e[t+1].x*e[t].y;r+=a,n+=(e[t].x+e[t+1].x)*a,i+=(e[t].y+e[t+1].y)*a}return r*=.5,r?{x:n/(6*r),y:i/(6*r)}:{x:e[0].x,y:e[0].y}}(o);new nn(o,i,s,[],!0).fill(S.fill.color,J(S.fill.opacity,0,255,0,1,!0),S.fill.texture_strength)}(this)),(t=>{S.fill={...t}})(o)},Kt.prototype.fill=function(t,e,r){qr().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,S.fill.bleed_strength<.06?0:J(S.fill.bleed_strength,0,.6,.2,.6,!0)),this.pol.fill())};let En=null,An=null,Mn=null,Sn=null,Tn=null,Pn=0,Cn=0,Fn=0;const kn={},In={};function Dn(t,e,r,n){f(),S.wash.opacity=(arguments.length<4?e:n)??150,S.wash.color=arguments.length<3?c(t):c(t,e,r),S.wash.isActive=!0}function Ln(t,e){const r=l();return[r.a*t+r.c*e+r.x+Pn/2,r.b*t+r.d*e+r.y+Cn/2]}function Nn(t,e,r){const n=e.isEnabled(e.DEPTH_TEST);return n&&e.disable(e.DEPTH_TEST),e.bindFramebuffer(e.FRAMEBUFFER,r.framebuffer),e.viewport(0,0,r.width*r.density,r.height*r.density),{hadDepthTest:n}}function Bn(t,e,i){i?.hadDepthTest&&e.enable(e.DEPTH_TEST),e.bindFramebuffer(e.FRAMEBUFFER,null),e.viewport(0,0,Math.max(1,Math.round(r*a)),Math.max(1,Math.round(n*a)))}function Un(t,e){e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,null),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA)}function On(t,e,r){if(!e)return;if(r(e)){const r=t.drawingContext,n=r.getParameter(r.FRAMEBUFFER_BINDING),i=r.getParameter(r.VIEWPORT);return r.bindFramebuffer(r.FRAMEBUFFER,e.framebuffer),r.viewport(0,0,e.width*e.density,e.height*e.density),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.bindFramebuffer(r.FRAMEBUFFER,n),void r.viewport(i[0],i[1],i[2],i[3])}const n=e.drawingContext;n.save(),n.setTransform(1,0,0,1,0,0),n.clearRect(0,0,e.width,e.height),n.restore()}function Yn(t,e,r){return t.shaderProgram??=function(t,e,r){const n=oe(t,e,r),i=new Map,a=t.createVertexArray(),o=t.getUniformLocation(n,"u_source"),s=t.getUniformLocation(n,"u_mask"),c=t.getUniformLocation(n,"u_color");return{program:n,quadVao:a,loc_source:o,loc_mask:s,loc_color:c,setUniform(e,r){const a=(e=>(i.has(e)||i.set(e,t.getUniformLocation(n,e)),i.get(e)))(e);a&&("boolean"!=typeof r?"number"!=typeof r?Array.isArray(r)&&(3===r.length?t.uniform3f(a,r[0],r[1],r[2]):4===r.length&&t.uniform4f(a,r[0],r[1],r[2],r[3])):t.uniform1f(a,r):t.uniform1i(a,r?1:0))}}}(t.drawingContext,e,r),t.shaderProgram}function zn(t,e){const r=t.drawingContext,n=e.density??1,i=r.createFramebuffer(),a=Math.max(1,e.width),o=Math.max(1,e.height),s=Math.max(1,Math.round(a*n)),c=Math.max(1,Math.round(o*n)),l=function(t,e,r){const n=t.createTexture();return t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,r,0,t.RGBA,t.UNSIGNED_BYTE,null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.bindTexture(t.TEXTURE_2D,null),n}(r,s,c);return r.bindFramebuffer(r.FRAMEBUFFER,i),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,l,0),r.bindFramebuffer(r.FRAMEBUFFER,null),{__brushFramebuffer:!0,framebuffer:i,colorTexture:l,width:a,height:o,density:n,pixelDensity:()=>n,remove(){r.deleteFramebuffer(i),r.deleteTexture(l)}}}function Xn(t,e,r,n,i){return e?.remove?.(),zn(t,{width:r,height:n,density:i})}function Gn({renderer:t,shader:e,source:r,mask:n,color:i,isBrushMask:a,dirtyRect:o,targetIsFramebuffer:s,withScissor:c}){const l=t.drawingContext,u=l.isEnabled(l.DEPTH_TEST),h=l.getParameter(l.FRAMEBUFFER_BINDING),f=l.getParameter(l.CURRENT_PROGRAM),d=l.getParameter(l.VERTEX_ARRAY_BINDING);l.bindVertexArray(e.quadVao),l.useProgram(e.program),l.disable(l.DEPTH_TEST),l.enable(l.BLEND),l.blendEquation(l.FUNC_ADD),l.blendFunc(l.ONE,l.ONE_MINUS_SRC_ALPHA),l.activeTexture(l.TEXTURE0),l.bindTexture(l.TEXTURE_2D,r.colorTexture),l.uniform1i(e.loc_source,0),l.activeTexture(l.TEXTURE1),l.bindTexture(l.TEXTURE_2D,n.colorTexture),l.uniform1i(e.loc_mask,1),e.setUniform("u_targetIsFramebuffer",s),e.setUniform("u_isBrush",a),l.uniform3f(e.loc_color,i[0],i[1],i[2]),l.bindFramebuffer(l.FRAMEBUFFER,null),c(l,o,()=>{l.drawArrays(l.TRIANGLES,0,3)},!s),l.bindTexture(l.TEXTURE_2D,null),l.activeTexture(l.TEXTURE0),l.bindVertexArray(d),l.useProgram(f),l.bindFramebuffer(l.FRAMEBUFFER,h),u&&l.enable(l.DEPTH_TEST)}function Zn(t){return function({renderer:t,sourceFramebuffer:e,dirtyRect:r,getTargetPixelSize:n,toScissorBox:i}){const a=t.drawingContext,{width:o,height:s}=n(),c=r?i(r):null,l=a.getParameter(a.READ_FRAMEBUFFER_BINDING),u=a.getParameter(a.DRAW_FRAMEBUFFER_BINDING);return a.bindFramebuffer(a.READ_FRAMEBUFFER,null),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,e.framebuffer),a.clearColor(0,0,0,0),a.clear(a.COLOR_BUFFER_BIT),a.blitFramebuffer(c?.x??0,c?.y??0,c?c.x+c.width:o,c?c.y+c.height:s,c?.x??0,c?.y??0,c?c.x+c.width:o,c?c.y+c.height:s,a.COLOR_BUFFER_BIT,a.NEAREST),a.bindFramebuffer(a.READ_FRAMEBUFFER,l),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,u),e}(t)}function Vn(t){if("number"==typeof t){const e=Math.max(0,Math.min(255,t));return`rgb(${e} ${e} ${e})`}return t??"black"}function $n(t){const e=((t,e=!1)=>(t.drawingContext??=t.getContext("2d",e?{willReadFrequently:!0}:void 0),t.drawingContext))(t,!0),r={canvas:t,drawingContext:e,width:t.width,height:t.height,pixels:null,_fillStyle:"#ffffff",_strokeStyle:"transparent",_lineWidth:1,pixelDensity:()=>1,background(r){e.save(),e.setTransform(1,0,0,1,0,0),e.fillStyle=Vn(r),e.fillRect(0,0,t.width,t.height),e.restore()},noSmooth(){e.imageSmoothingEnabled=!1},push(){e.save()},pop(){e.restore()},translate(t,r){e.translate(t,r)},scale(t,r=t){e.scale(t,r)},rotate(t){e.rotate(t)},noStroke(){r._strokeStyle="transparent"},stroke(t){r._strokeStyle=Vn(t)},noFill(){r._fillStyle="transparent"},fill(t){r._fillStyle=Vn(t)},strokeWeight(t){r._lineWidth=t},rect(t,n,i,a){e.beginPath(),e.rect(t,n,i,a),r._paint()},circle(t,n,i){e.beginPath(),e.arc(t,n,i/2,0,2*Math.PI),r._paint()},ellipse(t,n,i,a){e.beginPath(),e.ellipse(t,n,i/2,a/2,0,0,2*Math.PI),r._paint()},line(t,n,i,a){e.beginPath(),e.moveTo(t,n),e.lineTo(i,a),e.strokeStyle=r._strokeStyle,e.lineWidth=r._lineWidth,e.stroke()},beginShape(){e.beginPath(),r._shapeStarted=!1},vertex(t,n){r._shapeStarted?e.lineTo(t,n):(e.moveTo(t,n),r._shapeStarted=!0)},endShape(t=!1){t&&e.closePath(),r._paint()},loadPixels(){r.pixels=e.getImageData(0,0,t.width,t.height).data},updatePixels(){const n=e.getImageData(0,0,t.width,t.height);n.data.set(r.pixels),e.putImageData(n,0,0)},_paint(){"transparent"!==r._fillStyle&&(e.fillStyle=r._fillStyle,e.fill()),"transparent"!==r._strokeStyle&&(e.strokeStyle=r._strokeStyle,e.lineWidth=r._lineWidth,e.stroke())}};return r}function Hn(t,e){return $n(g(t,e,!0))}function Wn(t,e){return new Promise((r,n)=>{const i=globalThis.Image;if(!i)return void n(new Error("Standalone image brush loading requires Image support."));const a=new i;a.onload=()=>{const t=$n(g(a.naturalWidth,a.naturalHeight,!0));t.drawingContext.drawImage(a,0,0),e(t),r(t)},a.onerror=()=>n(new Error(`Failed to load image tip: ${t}`)),a.crossOrigin="anonymous",a.src=t})}var qn;S.wash={color:null,opacity:150,isActive:!1},jt.prototype.wash=function(t=!1,e){const a={...S.wash};!1!==t&&Dn(t,e),S.wash.isActive&&function(t){if(!S.wash?.isActive||!S.wash.color||t.vertices.length<3)return;C(),function(){const t=i.drawingContext;Tn&&!(Pn!==r||Cn!==n)||(Pn=r,Cn=n,Tn=new Float32Array([2/Pn,0,0,0,0,-2/Cn,0,0,0,0,1,0,-1,1,0,1])),En===t&&An&&Mn&&Sn||(En=t,An=oe(En,"#version 300 es\nin vec2 a_position;\nuniform mat4 u_matrix;\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n}","#version 300 es\nprecision highp float;\nuniform vec4 u_color;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(u_color.rgb * u_color.a, u_color.a);\n}"),kn.a_position=En.getAttribLocation(An,"a_position"),In.u_matrix=En.getUniformLocation(An,"u_matrix"),In.u_color=En.getUniformLocation(An,"u_color"),Mn=En.createVertexArray(),En.bindVertexArray(Mn),Sn=En.createBuffer(),En.bindBuffer(En.ARRAY_BUFFER,Sn),En.bufferData(En.ARRAY_BUFFER,0,En.DYNAMIC_DRAW),Fn=0,En.enableVertexAttribArray(kn.a_position),En.vertexAttribPointer(kn.a_position,2,En.FLOAT,!1,8,0),En.bindVertexArray(null),En.bindBuffer(En.ARRAY_BUFFER,null))}();const{triangles:e,vertexCount:a}=function(t){const e=new Float32Array(2*t.vertices.length);for(let r=0;r<t.vertices.length;r++){const n=t.vertices[r];e[2*r]=n.x,e[2*r+1]=n.y}const r=function(t,e,r=2){const n=t.length;let i=function(t,e,r,n){let i;if(1==function(t,e,r,n){let i=0;for(let e=0,a=r-n;e<r;e+=n)i+=(t[a]-t[e])*(t[e+1]+t[a+1]),a=e;return i}(t,0,r,n)>0)for(let e=0;e<r;e+=n)i=vn(e/n|0,t[e],t[e+1],i);else for(let e=r-n;e>=0;e-=n)i=vn(e/n|0,t[e],t[e+1],i);return i&&xn(i,i.next)&&(Rn(i),i=i.next),i}(t,0,n,r);const a=[];if(!i||i.next===i.prev)return a;let o,s,c;if(t.length>80*r){o=t[0],s=t[1];let e=o,i=s;for(let a=r;a<n;a+=r){const r=t[a],n=t[a+1];r<o&&(o=r),n<s&&(s=n),r>e&&(e=r),n>i&&(i=n)}c=Math.max(e-o,i-s),c=0!==c?32767/c:0}return on(i,a,r,o,s,c,0),a}(e),n=new Float32Array(2*r.length);for(let t=0;t<r.length;t++){const i=r[t],[a,o]=Ln(e[2*i],e[2*i+1]);n[2*t]=a,n[2*t+1]=o}return{triangles:n,vertexCount:r.length}}(t),o=e.byteLength;En.useProgram(An),En.enable(En.BLEND),En.blendEquation(En.FUNC_ADD),En.blendFunc(En.ONE,En.ONE_MINUS_SRC_ALPHA),En.bindVertexArray(Mn),En.bindBuffer(En.ARRAY_BUFFER,Sn),o>Fn?(En.bufferData(En.ARRAY_BUFFER,e,En.DYNAMIC_DRAW),Fn=o):En.bufferSubData(En.ARRAY_BUFFER,0,e);const s=S.wash.color._array;En.uniformMatrix4fv(In.u_matrix,!1,Tn),En.uniform4f(In.u_color,s[0],s[1],s[2],S.wash.opacity/255),En.drawArrays(En.TRIANGLES,0,a),En.bindVertexArray(null),En.bindBuffer(En.ARRAY_BUFFER,null),ce(i,En)}(this),S.wash={...a}},Kt.prototype.wash=function(t,e,r){S.wash?.isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,0,-1),this.pol.wash())},qn={load:function(t=Zt){if(!function(t){return function(t){return"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement}(t)||function(t){return"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas}(t)}(t))throw new Error("Standalone brush.load(target) requires an HTMLCanvasElement or OffscreenCanvas.");qt(t,t.width,t.height,1)},syncDensity:function(){return h({Cwidth:Ht,Cheight:Wt,Density:$t}),$t},isCanvasReady:function(){if(!Vt)throw new Error("No standalone target loaded. Call brush.load(canvasOrOffscreenCanvas) first.")},instance:function(){},activateInstance:function(){},deactivateInstance:function(){},getActiveFramebuffer:function(){return null},isFramebufferTarget:function(){return!0===arguments[0]?.__brushFramebuffer}},u={...u,...qn},Ot(),function(){var t;t={beginDirectMaskDraw:Nn,endDirectMaskDraw:Bn,resetDirectShaderTracking:Un},se={...se,...t}}(),function(){var t;t={clearTarget:On,ensureBlendShaderProgram:Yn,ensureBlendSourceFramebuffer:Xn,createFramebuffer:zn,runBlendShaderPass:Gn,blitSourceToFramebuffer:Zn},p={...p,...t}}(),function(){var t;t={createTipSurface:Hn,loadImageTip:Wn},ie={...ie,...t}}(),t.Color=Ut,t.DEGREES=Ft,t.Plot=Kt,t.Polygon=jt,t.Position=xt,t.RADIANS=kt,t.add=ir,t.addField=Mt,t.angleMode=function(t){if(t!==Ft&&t!==kt)throw new Error(`Invalid angle mode "${t}". Use "degrees" or "radians".`);Dt=t},t.arc=Jt,t.beginShape=te,t.beginStroke=function(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);Gt=[e,r],Xt=new Kt(t)},t.box=function(){return[...tr.keys()]},t.circle=function(t,e,r,n=!1){const i=new Kt("curve"),a=Math.PI*r,o=$(0,360),s=n?()=>1+.2*n*$():()=>1;for(let t=0;t<4;t++){const e=-90*t+o;i.addSegment(e*s(),a/2*s(),1,!0)}if(n){const t=n*q(-5,5);i.addSegment(o,Math.abs(t)*(Math.PI/180)*r,1,!0),i.endPlot(t+o,1,!0)}else i.endPlot(o,1,!0);const c=t-r*ot(o),l=e-r*at(-o);i.show(c,l,1)},t.clear=function(...t){f(),P.glMask&&P.clearMask(P.glMask),P.mask&&P.clearMask(P.mask),P.justChanged=!1,P.isBlending=!1,P.isBrush=null,P.cachedColor=null;const e=i.drawingContext,r=0===t.length?[1,1,1,0]:[...c(...t)._array.slice(0,3),1];e.bindFramebuffer(e.FRAMEBUFFER,null),e.disable(e.SCISSOR_TEST),e.clearColor(r[0],r[1],r[2],r[3]),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)},t.clip=function(t){return f(),t},t.createCanvas=function(t,e,r={}){if("undefined"==typeof document)throw new Error("brush.createCanvas() requires a browser document.");const n=Math.max(1,Math.round(t)),i=Math.max(1,Math.round(e)),a=Math.max(1,Number(r.pixelDensity)||1),o=document.createElement("canvas");if(o.width=Math.max(1,Math.round(n*a)),o.height=Math.max(1,Math.round(i*a)),o.style.width=`${n}px`,o.style.height=`${i}px`,r.id&&(o.id=r.id),r.parent){const t="string"==typeof r.parent?document.querySelector(r.parent):r.parent;if(!t)throw new Error(`Could not find parent "${r.parent}" for brush.createCanvas().`);t.appendChild(o)}return qt(o,n,i,a),o},t.endShape=re,t.endStroke=function(t,e){if(!Xt)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");Xt.endPlot(t,e),Xt.draw(Gt[0],Gt[1],1),Xt=!1},t.field=At,t.fill=jr,t.fillBleed=Kr,t.fillTexture=Jr,t.flowLine=function(t,e,r,n){if(!S.stroke.isActive||!S.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");mt(),xr(t,e,r),pr(st(n),!1)},t.getAngleMode=function(){return Dt},t.hatch=Cr,t.hatchArray=Ir,t.hatchStyle=function(t,e="black",r=1){S.hatch.hBrush={brush:t,color:e,weight:r}},t.initStandaloneRuntime=Ot,t.instance=t=>u.instance(t),t.line=Er,t.listFields=function(){return mt(),Array.from(vt.keys())},t.load=(t=!1)=>{((t=!1)=>{u.load(t)})(t),i.loaded&&P.load()},t.mass=function(t,e,r={}){S.mass.brush=t,S.mass.color=e,S.mass.options=r,S.mass.isActive=!0},t.move=function(t,e,r){if(!Xt)throw new Error("move() called without beginStroke(). Call beginStroke() first.");Xt.addSegment(t,e,r)},t.noClip=function(){},t.noField=function(){mt(),S.field.isActive=!1},t.noFill=function(){S.fill.isActive=!1},t.noHatch=function(){S.hatch.isActive=!1,S.hatch.hBrush=!1},t.noMass=function(){S.mass.isActive=!1,S.mass.brush=null,S.mass.color=null,S.mass.options={}},t.noStroke=function(){S.stroke.isActive=!1},t.noWash=function(){S.wash.isActive=!1},t.noiseSeed=t=>{G=N(B(t)),Z=N(B(`${t}:2`))},t.pick=or,t.polygon=function(t){new jt(t).show()},t.pop=function(){0!==Lt.length&&(Nt=Lt.pop(),function(){const t=Pt.pop();t&&(S.stroke={...t.stroke},S.field={...t.field},S.hatch={...t.hatch},S.fill={...t.fill},t.wash&&(S.wash={...t.wash}),t.mass?S.mass={...t.mass}:S.mass&&(S.mass={...S.mass,isActive:!1,brush:null,color:null,options:{}}))}())},t.push=function(){mt(),Pt.push({fill:{...S.fill},wash:S.wash?{...S.wash}:null,stroke:{...S.stroke},hatch:{...S.hatch},mass:S.mass?{...S.mass}:null,field:{...S.field}}),Lt.push({...Nt})},t.rect=function(t,e,r,n,i="corner"){"center"===i&&(t-=r/2,e-=n/2),te(0),ee(t,e),ee(t+r,e),ee(t+r,e+n),ee(t,e+n),re(!0)},t.refreshField=function(t=0){if(!S.field.isActive||!S.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=vt.get(S.field.current);e.field=Et(e,t)},t.render=function(){C()},t.rotate=function(t){const e=Dt===kt?t:t*Math.PI/180,r=Math.cos(e),n=Math.sin(e);Nt=Bt(Nt,{a:r,b:n,c:-n,d:r,x:0,y:0})},t.scale=function(t,e=t){Nt=Bt(Nt,{a:t,b:0,c:0,d:e,x:0,y:0})},t.scaleBrushes=function(t){for(const{param:e}of tr.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)},t.seed=t=>{O=B(t),Y=B(`${t}:2`);for(const t of z)t()},t.set=lr,t.spline=function(t,e=.5){if(!t||t.length<2)throw new Error("spline() requires at least 2 points. Each point should be [x, y, pressure].");ne(t,e).draw()},t.stroke=sr,t.strokeWeight=cr,t.translate=function(t,e){Nt=Bt(Nt,{a:1,b:0,c:0,d:1,x:t,y:e})},t.vertex=ee,t.wRand=K,t.wash=Dn,t.wiggle=St},"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).brush={});
+var t,e;t=this,e=function(t){const e={a:1,b:0,c:0,d:1,x:0,y:0};let r,n,i,o,a=()=>!1,s=t=>t,c=()=>{throw new Error("No runtime color adapter registered.")},l=()=>e,u={load:()=>{throw new Error("No target runtime adapter registered.")},syncDensity:()=>o,isCanvasReady:()=>{throw new Error("No target runtime adapter registered.")},instance:t=>{},activateInstance:t=>{},deactivateInstance:()=>{},getActiveFramebuffer:()=>null,isFramebufferTarget:()=>!1};function h(t){"Cwidth"in t&&(r=t.Cwidth),"Cheight"in t&&(n=t.Cheight),"Instance"in t&&t.Instance,"Renderer"in t&&(i=t.Renderer),"Density"in t&&(o=t.Density)}const f=()=>u.isCanvasReady(),d=()=>u.getActiveFramebuffer(),m=t=>u.isFramebufferTarget(t),x=(t,e=0)=>t?{minX:t.minX-e,minY:t.minY-e,maxX:t.maxX+e,maxY:t.maxY+e}:null,g=(t,e,r=!1)=>{const n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(t,e):(()=>{const r=document.createElement("canvas");return r.width=t,r.height=e,r})();return n.drawingContext=n.getContext("2d",r?{willReadFrequently:!0}:void 0),n};let p={clearTarget:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendShaderProgram:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendSourceFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},createFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},runBlendShaderPass:()=>{throw new Error("No compositor runtime adapter registered.")},blitSourceToFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")}};const y=(...t)=>p.createFramebuffer(...t);let v=null,b=null;const _=t=>{((...t)=>{p.clearTarget(...t)})(i,t,m)},R=()=>({width:Math.max(1,Math.round(r*o)),height:Math.max(1,Math.round(n*o))}),w=t=>{if(!t)return null;const{width:e,height:r}=R();return((t,e,r)=>{if(!t)return null;const n=Math.max(0,Math.floor(Math.min(t.minX,t.maxX))),i=Math.max(0,Math.floor(Math.min(t.minY,t.maxY))),o=Math.min(e,Math.ceil(Math.max(t.minX,t.maxX))),a=Math.min(r,Math.ceil(Math.max(t.minY,t.maxY)));return o<=n||a<=i?null:{minX:n,minY:i,maxX:o,maxY:a}})(t,e,r)},E=()=>{const{width:t,height:e}=R();return((t,e)=>({minX:0,minY:0,maxX:t,maxY:e}))(t,e)},A=(t,e=!0)=>{const r=w(t);if(!r)return null;const{height:n}=R();return{x:r.minX,y:e?n-r.maxY:r.minY,width:r.maxX-r.minX,height:r.maxY-r.minY}},M=(t,e,r,n=!0)=>{const i=A(e,n);if(i){t.enable(t.SCISSOR_TEST),t.scissor(i.x,i.y,i.width,i.height);try{r()}finally{t.disable(t.SCISSOR_TEST)}}else r()},S={},T=()=>{i?.loaded||(f(),P.load())},P={isBlending:!1,cachedColor:null,markDirtyRect(t,e){const r=w(e);var n,i;t&&r&&(t.dirtyRect=(i=r,(n=t.dirtyRect)?i?{minX:Math.min(n.minX,i.minX),minY:Math.min(n.minY,i.minY),maxX:Math.max(n.maxX,i.maxX),maxY:Math.max(n.maxY,i.maxY)}:n:i),t.isDrawn=!0)},clearMask(t){if(!t)return;const e=t===this.glMask?v:b;e?.clearMask?.(t,_)},getCompositeRect(t,e){const r=e?v:b;return r?.getCompositeRect?.(t,d,E,x,w)},load(){u.syncDensity();const t=!i.blendSourceFramebuffer||i.blendSourceFramebuffer.width!==r||i.blendSourceFramebuffer.height!==n||"function"==typeof i.blendSourceFramebuffer.pixelDensity&&i.blendSourceFramebuffer.pixelDensity()!==o;((...t)=>{p.ensureBlendShaderProgram(...t)})(i,"#version 300 es\n#define GLSLIFY 1\nout vec2 p;void main(){vec3 v=vec3(-1);v[gl_VertexID]=3.;p=v.xy;gl_Position=vec4(v.x,-v.y,0,1);}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nuniform bool u_isBrush;uniform bool u_targetIsFramebuffer;uniform sampler2D u_source;uniform sampler2D u_mask;uniform vec3 u_color;in vec2 p;out vec4 outColor;const int SPECTRAL_SIZE=38;const float SPECTRAL_GAMMA=2.4;const float SPECTRAL_EPSILON=0.0000000000000001;float spectral_uncompand(float x){return(x<0.04045)? x/12.92 : pow((x+0.055)/1.055,SPECTRAL_GAMMA);}float spectral_compand(float x){return(x<0.0031308)? x*12.92 : 1.055*pow(x,1.0/SPECTRAL_GAMMA)-0.055;}vec3 spectral_srgb_to_linear(vec3 srgb){return vec3(spectral_uncompand(srgb[0]),spectral_uncompand(srgb[1]),spectral_uncompand(srgb[2]));}vec3 spectral_linear_to_srgb(vec3 lrgb){return clamp(vec3(spectral_compand(lrgb[0]),spectral_compand(lrgb[1]),spectral_compand(lrgb[2])),0.,1.);}void spectral_linear_to_reflectance(vec3 lrgb,inout float R[SPECTRAL_SIZE]){float w=min(lrgb.r,min(lrgb.g,lrgb.b));lrgb-=w;float c=min(lrgb.g,lrgb.b);float m=min(lrgb.r,lrgb.b);float y=min(lrgb.r,lrgb.g);float r=min(max(0.0,lrgb.r-lrgb.b),max(0.0,lrgb.r-lrgb.g));float g=min(max(0.0,lrgb.g-lrgb.b),max(0.0,lrgb.g-lrgb.r));float b=min(max(0.0,lrgb.b-lrgb.g),max(0.0,lrgb.b-lrgb.r));R[0]=max(SPECTRAL_EPSILON,w*1.0011607271876400+c*0.9705850013229620+m*0.9906735573199880+y*0.0210523371789306+r*0.0315605737777207+g*0.0095560747554212+b*0.9794047525020140);R[1]=max(SPECTRAL_EPSILON,w*1.0011606515972800+c*0.9705924981434250+m*0.9906715249619790+y*0.0210564627517414+r*0.0315520718330149+g*0.0095581580120851+b*0.9794007068431300);R[2]=max(SPECTRAL_EPSILON,w*1.0011603192274700+c*0.9706253487298910+m*0.9906625823534210+y*0.0210746178695038+r*0.0315148215513658+g*0.0095673245444588+b*0.9793829034702610);R[3]=max(SPECTRAL_EPSILON,w*1.0011586727078900+c*0.9707868061190170+m*0.9906181076447950+y*0.0211649058448753+r*0.0313318044982702+g*0.0096129126297349+b*0.9792943649455940);R[4]=max(SPECTRAL_EPSILON,w*1.0011525984455200+c*0.9713686732282480+m*0.9904514808787100+y*0.0215027957272504+r*0.0306729857725527+g*0.0097837090401843+b*0.9789630146085700);R[5]=max(SPECTRAL_EPSILON,w*1.0011325252899800+c*0.9731632306212520+m*0.9898710814002040+y*0.0226738799041561+r*0.0286480476989607+g*0.0103786227058710+b*0.9778144666940430);R[6]=max(SPECTRAL_EPSILON,w*1.0010850066332700+c*0.9767402231587650+m*0.9882866087596400+y*0.0258235649693629+r*0.0246450407045709+g*0.0120026452378567+b*0.9747243211338360);R[7]=max(SPECTRAL_EPSILON,w*1.0009968788945300+c*0.9815876054913770+m*0.9842906927975040+y*0.0334879385639851+r*0.0192960753663651+g*0.0160977721473922+b*0.9671984823439730);R[8]=max(SPECTRAL_EPSILON,w*1.0008652515227400+c*0.9862802656529490+m*0.9739349056253060+y*0.0519069663740307+r*0.0142066612220556+g*0.0267061902231680+b*0.9490796575305750);R[9]=max(SPECTRAL_EPSILON,w*1.0006962900094000+c*0.9899491476891340+m*0.9418178384601450+y*0.1007490148334730+r*0.0102942608878609+g*0.0595555440185881+b*0.9008501289409770);R[10]=max(SPECTRAL_EPSILON,w*1.0005049611488800+c*0.9924927015384200+m*0.8173903261951560+y*0.2391298997068470+r*0.0076191460521811+g*0.1860398265328260+b*0.7631504454622400);R[11]=max(SPECTRAL_EPSILON,w*1.0003080818799200+c*0.9941456804052560+m*0.4324728050657290+y*0.5348043122727480+r*0.0058980410835420+g*0.5705798201161590+b*0.4659221716493190);R[12]=max(SPECTRAL_EPSILON,w*1.0001196660201300+c*0.9951839750332120+m*0.1384539782588700+y*0.7978075786430300+r*0.0048233247781713+g*0.8614677684002920+b*0.2012632804510050);R[13]=max(SPECTRAL_EPSILON,w*0.9999527659684070+c*0.9957567501108180+m*0.0537347216940033+y*0.9114498940673840+r*0.0042298748350633+g*0.9458790897676580+b*0.0877524413419623);R[14]=max(SPECTRAL_EPSILON,w*0.9998218368992970+c*0.9959128182867100+m*0.0292174996673231+y*0.9537979630045070+r*0.0040599171299341+g*0.9704654864743050+b*0.0457176793291679);R[15]=max(SPECTRAL_EPSILON,w*0.9997386095575930+c*0.9956061578345280+m*0.0213136517508590+y*0.9712416154654290+r*0.0043533695594676+g*0.9784136302844500+b*0.0284706050521843);R[16]=max(SPECTRAL_EPSILON,w*0.9997095516396120+c*0.9945976009618540+m*0.0201349530181136+y*0.9793031238075880+r*0.0053434425970201+g*0.9795890314112240+b*0.0205271767569850);R[17]=max(SPECTRAL_EPSILON,w*0.9997319302106270+c*0.9922157154923700+m*0.0241323096280662+y*0.9833801195075750+r*0.0076917201010463+g*0.9755335369086320+b*0.0165302792310211);R[18]=max(SPECTRAL_EPSILON,w*0.9997994363461950+c*0.9862364527832490+m*0.0372236145223627+y*0.9854612465677550+r*0.0135969795736536+g*0.9622887553978130+b*0.0145135107212858);R[19]=max(SPECTRAL_EPSILON,w*0.9999003303166710+c*0.9679433372645410+m*0.0760506552706601+y*0.9864350469766050+r*0.0316975442661115+g*0.9231215745131200+b*0.0136003508637687);R[20]=max(SPECTRAL_EPSILON,w*1.0000204065261100+c*0.8912850042449430+m*0.2053754719423990+y*0.9867382506701410+r*0.1078611963552490+g*0.7934340189431110+b*0.0133604258769571);R[21]=max(SPECTRAL_EPSILON,w*1.0001447879365800+c*0.5362024778620530+m*0.5412689034604390+y*0.9866178824450320+r*0.4638126031687040+g*0.4592701359024290+b*0.0135488943145680);R[22]=max(SPECTRAL_EPSILON,w*1.0002599790341200+c*0.1541081190018780+m*0.8158416850864860+y*0.9862777767586430+r*0.8470554052720110+g*0.1855741036663030+b*0.0139594356366992);R[23]=max(SPECTRAL_EPSILON,w*1.0003557969708900+c*0.0574575093228929+m*0.9128177041239760+y*0.9858605924440560+r*0.9431854093939180+g*0.0881774959955372+b*0.0144434255753570);R[24]=max(SPECTRAL_EPSILON,w*1.0004275378026900+c*0.0315349873107007+m*0.9463398301669620+y*0.9854749276762100+r*0.9688621506965580+g*0.0543630228766700+b*0.0148854440621406);R[25]=max(SPECTRAL_EPSILON,w*1.0004762334488800+c*0.0222633920086335+m*0.9599276963319910+y*0.9851769347655580+r*0.9780306674736030+g*0.0406288447060719+b*0.0152254296999746);R[26]=max(SPECTRAL_EPSILON,w*1.0005072096750800+c*0.0182022841492439+m*0.9662605952303120+y*0.9849715740141810+r*0.9820436438543060+g*0.0342215204316970+b*0.0154592848180209);R[27]=max(SPECTRAL_EPSILON,w*1.0005251915637300+c*0.0162990559732640+m*0.9693259700584240+y*0.9848463034157120+r*0.9839236237187070+g*0.0311185790956966+b*0.0156018026485961);R[28]=max(SPECTRAL_EPSILON,w*1.0005350960689600+c*0.0153656239334613+m*0.9708545367213990+y*0.9847753518111990+r*0.9848454841543820+g*0.0295708898336134+b*0.0156824871281936);R[29]=max(SPECTRAL_EPSILON,w*1.0005402209748200+c*0.0149111568733976+m*0.9716050665281280+y*0.9847380666252650+r*0.9852942758145960+g*0.0288108739348928+b*0.0157248764360615);R[30]=max(SPECTRAL_EPSILON,w*1.0005427281678400+c*0.0146954339898235+m*0.9719627697573920+y*0.9847196483117650+r*0.9855072952198250+g*0.0284486271324597+b*0.0157458108784121);R[31]=max(SPECTRAL_EPSILON,w*1.0005438956908700+c*0.0145964146717719+m*0.9721272722745090+y*0.9847110233919390+r*0.9856050715398370+g*0.0282820301724731+b*0.0157556123350225);R[32]=max(SPECTRAL_EPSILON,w*1.0005444821215100+c*0.0145470156699655+m*0.9722094177458120+y*0.9847066833006760+r*0.9856538499335780+g*0.0281988376490237+b*0.0157605443964911);R[33]=max(SPECTRAL_EPSILON,w*1.0005447695999200+c*0.0145228771899495+m*0.9722495776784240+y*0.9847045543930910+r*0.9856776850338830+g*0.0281581655342037+b*0.0157629637515278);R[34]=max(SPECTRAL_EPSILON,w*1.0005448988776200+c*0.0145120341118965+m*0.9722676219987420+y*0.9847035963093700+r*0.9856883918061220+g*0.0281398910216386+b*0.0157640525629106);R[35]=max(SPECTRAL_EPSILON,w*1.0005449625468900+c*0.0145066940939832+m*0.9722765094621500+y*0.9847031240775520+r*0.9856936646900310+g*0.0281308901665811+b*0.0157645892329510);R[36]=max(SPECTRAL_EPSILON,w*1.0005449892705800+c*0.0145044507314479+m*0.9722802433068740+y*0.9847029256150900+r*0.9856958798482050+g*0.0281271086805816+b*0.0157648147772649);R[37]=max(SPECTRAL_EPSILON,w*1.0005449969930000+c*0.0145038009464639+m*0.9722813248265600+y*0.9847028681227950+r*0.9856965214637620+g*0.0281260133612096+b*0.0157648801149616);}vec3 spectral_xyz_to_srgb(vec3 xyz){mat3 XYZ_RGB;XYZ_RGB[0]=vec3(3.2409699419045200,-1.537383177570090,-0.4986107602930030);XYZ_RGB[1]=vec3(-0.9692436362808790,1.875967501507720,0.0415550574071756);XYZ_RGB[2]=vec3(0.0556300796969936,-0.203976958888976,1.0569715142428700);float r=dot(XYZ_RGB[0],xyz);float g=dot(XYZ_RGB[1],xyz);float b=dot(XYZ_RGB[2],xyz);return spectral_linear_to_srgb(vec3(r,g,b));}vec3 spectral_reflectance_to_xyz(float R[SPECTRAL_SIZE]){vec3 xyz=vec3(0.);xyz+=R[0]*vec3(0.0000646919989576,0.0000018442894440,0.0003050171476380);xyz+=R[1]*vec3(0.0002194098998132,0.0000062053235865,0.0010368066663574);xyz+=R[2]*vec3(0.0011205743509343,0.0000310096046799,0.0053131363323992);xyz+=R[3]*vec3(0.0037666134117111,0.0001047483849269,0.0179543925899536);xyz+=R[4]*vec3(0.0118805536037990,0.0003536405299538,0.0570775815345485);xyz+=R[5]*vec3(0.0232864424191771,0.0009514714056444,0.1136516189362870);xyz+=R[6]*vec3(0.0345594181969747,0.0022822631748318,0.1733587261835500);xyz+=R[7]*vec3(0.0372237901162006,0.0042073290434730,0.1962065755586570);xyz+=R[8]*vec3(0.0324183761091486,0.0066887983719014,0.1860823707062960);xyz+=R[9]*vec3(0.0212332056093810,0.0098883960193565,0.1399504753832070);xyz+=R[10]*vec3(0.0104909907685421,0.0152494514496311,0.0891745294268649);xyz+=R[11]*vec3(0.0032958375797931,0.0214183109449723,0.0478962113517075);xyz+=R[12]*vec3(0.0005070351633801,0.0334229301575068,0.0281456253957952);xyz+=R[13]*vec3(0.0009486742057141,0.0513100134918512,0.0161376622950514);xyz+=R[14]*vec3(0.0062737180998318,0.0704020839399490,0.0077591019215214);xyz+=R[15]*vec3(0.0168646241897775,0.0878387072603517,0.0042961483736618);xyz+=R[16]*vec3(0.0286896490259810,0.0942490536184085,0.0020055092122156);xyz+=R[17]*vec3(0.0426748124691731,0.0979566702718931,0.0008614711098802);xyz+=R[18]*vec3(0.0562547481311377,0.0941521856862608,0.0003690387177652);xyz+=R[19]*vec3(0.0694703972677158,0.0867810237486753,0.0001914287288574);xyz+=R[20]*vec3(0.0830531516998291,0.0788565338632013,0.0001495555858975);xyz+=R[21]*vec3(0.0861260963002257,0.0635267026203555,0.0000923109285104);xyz+=R[22]*vec3(0.0904661376847769,0.0537414167568200,0.0000681349182337);xyz+=R[23]*vec3(0.0850038650591277,0.0426460643574120,0.0000288263655696);xyz+=R[24]*vec3(0.0709066691074488,0.0316173492792708,0.0000157671820553);xyz+=R[25]*vec3(0.0506288916373645,0.0208852059213910,0.0000039406041027);xyz+=R[26]*vec3(0.0354739618852640,0.0138601101360152,0.0000015840125870);xyz+=R[27]*vec3(0.0214682102597065,0.0081026402038399,0.0000000000000000);xyz+=R[28]*vec3(0.0125164567619117,0.0046301022588030,0.0000000000000000);xyz+=R[29]*vec3(0.0068045816390165,0.0024913800051319,0.0000000000000000);xyz+=R[30]*vec3(0.0034645657946526,0.0012593033677378,0.0000000000000000);xyz+=R[31]*vec3(0.0014976097506959,0.0005416465221680,0.0000000000000000);xyz+=R[32]*vec3(0.0007697004809280,0.0002779528920067,0.0000000000000000);xyz+=R[33]*vec3(0.0004073680581315,0.0001471080673854,0.0000000000000000);xyz+=R[34]*vec3(0.0001690104031614,0.0000610327472927,0.0000000000000000);xyz+=R[35]*vec3(0.0000952245150365,0.0000343873229523,0.0000000000000000);xyz+=R[36]*vec3(0.0000490309872958,0.0000177059860053,0.0000000000000000);xyz+=R[37]*vec3(0.0000199961492222,0.0000072209749130,0.0000000000000000);return xyz;}float KS(float R){return pow(1.0-R,2.0)/(2.0*R);}float KM(float KS){return 1.0+KS-sqrt(pow(KS,2.0)+2.0*KS);}vec3 spectral_mix(vec3 color1,float tintingStrength1,float factor1,vec3 color2,float tintingStrength2,float factor2){vec3 lrgb1=spectral_srgb_to_linear(color1);vec3 lrgb2=spectral_srgb_to_linear(color2);float R1[SPECTRAL_SIZE];float R2[SPECTRAL_SIZE];spectral_linear_to_reflectance(lrgb1,R1);spectral_linear_to_reflectance(lrgb2,R2);float luminance1=spectral_reflectance_to_xyz(R1)[1];float luminance2=spectral_reflectance_to_xyz(R2)[1];float R[SPECTRAL_SIZE];for(int i=0;i<SPECTRAL_SIZE;i++){float concentration1=pow(factor1,2.)*pow(tintingStrength1,2.)*luminance1;float concentration2=pow(factor2,2.)*pow(tintingStrength2,2.)*luminance2;float totalConcentration=concentration1+concentration2;float ksMix=0.;ksMix+=KS(R1[i])*concentration1;ksMix+=KS(R2[i])*concentration2;R[i]=KM(ksMix/totalConcentration);}return spectral_xyz_to_srgb(spectral_reflectance_to_xyz(R));}vec3 spectral_mix(vec3 color1,vec3 color2,float factor){return spectral_mix(color1,1.,1.-factor,color2,1.,factor);}vec3 spectral_mix(vec3 color1,float factor1,vec3 color2,float factor2){return spectral_mix(color1,1.,factor1,color2,1.,factor2);}const float GAMMA=2.4,EPSILON=0.0001;const float DARKEN_THRESHOLD=0.7;const float EDGE_MIN=0.05,EDGE_MAX=0.35;void main(void){vec2 uv=0.5*p+0.5;vec2 sourceUV=vec2(uv.x,1.0-uv.y);vec2 maskUV=u_targetIsFramebuffer ? vec2(uv.x,1.0-uv.y): uv;vec4 source=texture(u_source,sourceUV);vec4 maskColor=texture(u_mask,maskUV);if(maskColor.a==0.0){outColor=source;return;}vec4 pigment=vec4(u_color.xyz,1.0);if(maskColor.a>DARKEN_THRESHOLD){float blacken=0.5*(min(maskColor.a,1.0)-DARKEN_THRESHOLD);pigment=pigment*(1.0-blacken)-vec4(0.5)*blacken;pigment.rgb=max(pigment.rgb,vec3(0.0));}float mixIntensity=min(maskColor.a,1.0);if(!u_isBrush){vec2 texelSize=1.0/vec2(textureSize(u_mask,0));float scaledAlpha=maskColor.a*15.0;float blurEdge=0.0;for(int i=-2;i<=2;i+=2){for(int j=-2;j<=2;j+=2){vec2 neighborUV=maskUV+vec2(float(i),float(j))*texelSize;float neighborAlpha=texture(u_mask,neighborUV).a*15.0;blurEdge+=smoothstep(EDGE_MIN,EDGE_MAX,length(vec2(dFdx(neighborAlpha),dFdy(neighborAlpha))));}}blurEdge/=9.0;mixIntensity=clamp(maskColor.a+blurEdge*0.1,0.0,1.0);}vec3 bgColor=mix(vec3(1.0),source.rgb,source.a);outColor=vec4(spectral_mix(bgColor,pigment.rgb,mixIntensity),1.);}"),this.glMask=v?.ensureResources?.(i,r,n,o);const e=b?.ensureResources?.(i,r,n,o,_)??{mask:null,ctx:null};t&&(i.blendSourceFramebuffer=((...t)=>p.ensureBlendSourceFramebuffer(...t))(i,i.blendSourceFramebuffer,r,n,o)),this.mask=e.mask,this.ctx=e.ctx},blend(t=!1,e=!1){T();const r=!0===this.isBrush,n=r?this.glMask:this.mask,i=r?this.mask:this.glMask,o=t?._array,a=!!o&&(this.cachedColor?.[0]!==o[0]||this.cachedColor?.[1]!==o[1]||this.cachedColor?.[2]!==o[2]||this.cachedColor?.[3]!==o[3]);!this.isBlending&&o&&(this.isBlending=!0,this.cachedColor=o,this.clearMask(this.glMask)),(e||a)&&(this.justChanged&&(this.applyShader(i,!r),this.justChanged=!1),this.isBlending&&this.applyShader(n,r),o&&(this.cachedColor=o),e&&(this.isBlending=!1,this.cachedColor=null))},applyShader(t,e){if(!t?.isDrawn)return;const o=this.getCompositeRect(t,e);if(!o)return void this.clearMask(t);i.drawingContext;const a=i.shaderProgram,s=d(),c=((...t)=>p.blitSourceToFramebuffer(...t))({renderer:i,sourceTarget:s??i,sourceFramebuffer:i.blendSourceFramebuffer,dirtyRect:o,isFramebufferTarget:m,Cwidth:r,Cheight:n,getTargetPixelSize:R,toScissorBox:A,withScissor:M}),l=!!s,u=(e?v:b).getShaderMask(i,t,o,E,_);((...t)=>{p.runBlendShaderPass(...t)})({renderer:i,shader:a,source:c,mask:u,color:this.cachedColor,isBrushMask:e,Cwidth:r,Cheight:n,dirtyRect:o,targetIsFramebuffer:l,withScissor:M}),this.clearMask(t)}},C=()=>{T(),P.blend(!1,!0),P.clearMask(P.glMask),P.clearMask(P.mask),P.justChanged=!1,P.isBlending=!1,P.isBrush=null,P.cachedColor=null},F=Math.sqrt(3),k=.5*(F-1),I=(3-F)/6,D=t=>0|Math.floor(t),L=new Float64Array([1,1,-1,1,1,-1,-1,-1,1,0,-1,0,1,0,-1,0,0,1,0,-1,0,1,0,-1]);function N(t=Math.random){const e=function(t){const e=new Uint8Array(512);for(let t=0;t<256;t++)e[t]=t;for(let r=0;r<255;r++){const n=r+~~(t()*(256-r)),i=e[r];e[r]=e[n],e[n]=i}for(let t=256;t<512;t++)e[t]=e[t-256];return e}(t),r=new Float64Array(e).map(t=>L[t%12*2]),n=new Float64Array(e).map(t=>L[t%12*2+1]);return function(t,i){let o=0,a=0,s=0;const c=(t+i)*k,l=D(t+c),u=D(i+c),h=(l+u)*I,f=t-(l-h),d=i-(u-h);let m,x;f>d?(m=1,x=0):(m=0,x=1);const g=f-m+I,p=d-x+I,y=f-1+2*I,v=d-1+2*I,b=255&l,_=255&u;let R=.5-f*f-d*d;if(R>=0){const t=b+e[_];R*=R,o=R*R*(r[t]*f+n[t]*d)}let w=.5-g*g-p*p;if(w>=0){const t=b+m+e[_+x];w*=w,a=w*w*(r[t]*g+n[t]*p)}let E=.5-y*y-v*v;if(E>=0){const t=b+1+e[_+1];E*=E,s=E*E*(r[t]*y+n[t]*v)}return 70*(o+a+s)}}function B(t,e){let r=new U(t),n=()=>r.next();return n.double=()=>n()+11102230246251565e-32*(2097152*n()|0),n.int32=()=>4294967296*r.next()|0,n.quick=n,n}class U{constructor(t){null==t&&(t=+new Date);let e=4022871197;function r(t){t=String(t);for(let r=0;r<t.length;r++){e+=t.charCodeAt(r);let n=.02519603282416938*e;e=n>>>0,n-=e,n*=e,e=n>>>0,n-=e,e+=4294967296*n}return 2.3283064365386963e-10*(e>>>0)}this.c=1,this.s0=r(" "),this.s1=r(" "),this.s2=r(" "),this.s0-=r(t),this.s0<0&&(this.s0+=1),this.s1-=r(t),this.s1<0&&(this.s1+=1),this.s2-=r(t),this.s2<0&&(this.s2+=1)}next(){let{c:t,s0:e,s1:r,s2:n}=this,i=2091639*e+2.3283064365386963e-10*t;return this.s0=r,this.s1=n,this.s2=i-(this.c=0|i)}copy(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}}let Y=B(Math.random()),z=B(Math.random());const O=[],X=t=>O.push(t);let G=N(B(Math.random())),Z=N(B(Math.random()));const V=(t=0,e=1)=>t+Y()*(e-t),H=(t=0,e=1)=>t+z()*(e-t),W=t=>t[~~(Y()*t.length)],$=(t,e)=>~~V(t,e),q=(t,e)=>~~H(t,e),j=(t=0,e=1)=>{const r=1-Y(),n=Y();return Math.sqrt(-2*Math.log(r))*it(360*n)*e+t},K=(t,e,r,n,i,o=!1)=>{let a=n+(t-e)/(r-e)*(i-n);return o?n<i?J(a,n,i):J(a,i,n):a},J=(t,e,r)=>Math.max(Math.min(t,r),e),Q=t=>(t%=360)<0?t+360:t,tt=1440,et=2*Math.PI/tt,rt=new Float32Array(tt).fill(NaN),nt=new Float32Array(tt).fill(NaN),it=t=>{const e=~~(4*Q(t));let r=rt[e];return isNaN(r)&&(r=Math.cos(e*et),rt[e]=r),r},ot=t=>{const e=~~(4*Q(t));let r=nt[e];return isNaN(r)&&(r=Math.sin(e*et),nt[e]=r),r},at=(t,e=!1)=>{if(e||a()){let e=180*t/Math.PI%360;return e<0?e+360:e}return t},st=(t,e=!1)=>e||a()?180*t/Math.PI:t,ct=(t,e,r,n,i)=>{let o=it(i),a=ot(i);return{x:o*(r-t)+a*(n-e)+t,y:o*(n-e)-a*(r-t)+e}},lt=(t,e,r,n)=>Math.hypot(r-t,n-e),ut=(t,e,r,n)=>at(Math.atan2(-(n-e),r-t),!0),ht=(t,e,r,n,i=!1)=>{let o=t.x,a=t.y,s=e.x,c=e.y,l=r.x,u=r.y,h=n.x,f=n.y;if(o===s&&a===c||l===h&&u===f)return!1;let d=s-o,m=c-a,x=h-l,g=f-u,p=g*d-x*m;if(0===p)return!1;let y=(x*(a-u)-g*(o-l))/p,v=(d*(a-u)-m*(o-l))/p;return!(!i&&(v<0||v>1))&&{x:o+y*d,y:a+y*m}};let ft=!1;function dt(){ft||(T(),xt=.01*r,gt=-.5*r,pt=-.5*n,yt=Math.round(2*r/xt),vt=Math.round(2*n/xt),At("hand",(t,e)=>{const r=H(.2,.8),n=q(5,10);return St(e,(e,i)=>.5*n*ot(r*i*e+q(15,25))*.2*it(t)+Z(e,i)*n*.7)}),At("curved",(t,e)=>{let r=q(-10,10);return q(0,100)%2==0&&(r*=-1),St(e,(e,n)=>3*K(Z(.02*e+.03*t,.02*n+.03*t),0,1,-r,r))}),At("zigzag",(t,e)=>{let r=q(-30,-15)+Math.abs(44*ot(t));q(0,100)%2==0&&(r*=-1);let n=r,i=0;for(let t=0;t<yt;t++){for(let r=0;r<vt;r++)e[t][r]=i,i+=n,n*=-1;i+=n,n*=-1}return e}),At("waves",(t,e)=>{const r=q(10,15)+5*ot(t),n=q(3,6)+3*it(t),i=q(20,35);return St(e,(t,e)=>ot(r*t)*i*it(e*n)+q(-3,3))}),At("seabed",(t,e)=>{const r=H(.4,.8),n=q(18,26);return St(e,(e,i)=>1.1*n*ot(r*i*e+q(15,20))*it(t))}),At("spiral",(t,e)=>{const r=q(5,10),n=2*q(0,2)-1,i=q(65,80),o=Array.from({length:r},()=>({x:H(.1,.9)*yt,y:H(.1,.9)*vt}));return St(e,(t,e)=>{let r=0,a=0;for(const s of o){const o=t-s.x,c=e-s.y,l=1/(o*o+c*c+1),u=Math.atan2(c,o)*(180/Math.PI),h=n*(u+i)*Math.PI/180;r+=l*Math.cos(h),a+=l*Math.sin(h)}return Math.atan2(a,r)*(180/Math.PI)})}),At("columns",(t,e)=>{const r=q(3,8),n=q(25,45);return St(e,(t,e)=>ot(t*r)*n)}),ft=!0)}class mt{constructor(t,e){dt();const r=l();this.mx=r.x,this.my=r.y,this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,S.field.isActive&&(this.colIdx=Math.round((t+this.mx-gt)/xt),this.rowIdx=Math.round((e+this.my-pt)/xt))}reset(){this.plotted=0}isIn(){return S.field.isActive?mt.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const t=r,e=n,i=this.x+this.mx,o=this.y+this.my;return i>=-.3*t&&i<=1.3*t&&o>=-.3*e&&o<=1.3*e}angle(t=!1){return S.field.isActive&&(t||this.isIn())?bt.get(S.field.current).field[this.colIdx][this.rowIdx]*S.field.wiggle:0}moveTo(t,e,r=1){this.movePos(st(t),e,r)}_moveToDegrees(t,e,r=1){this.movePos(t,e,r)}plotTo(t,e,r,n=1,i=void 0){this.movePos(t,e,r,n,i)}movePos(t,e,r,n=!1,i=void 0){const o=n||1;if(!this.isIn())return void(this.plotted+=r/o);const a=e/r,s=S.field.isActive,c=!!n;for(let e=0;e<a;e++){const n=c&&void 0!==i&&0===e?i:c?t.angle(this.plotted):t,a=(s?this.angle(!0):0)-n;this.update(this.x+r*it(a),this.y+r*ot(a)),this.plotted+=r/o}}static getRowIndex(t,e=1){const r=t+l().y-pt;return Math.round(r/xt/e)}static getColIndex(t,e=1){const r=t+l().x-gt;return Math.round(r/xt/e)}static isIn(t,e){return t>=0&&e>=0&&t<yt&&e<vt}}S.field={isActive:!1,current:null,wiggle:1};let xt,gt,pt,yt,vt,bt=new Map;const _t=new Set(["degrees","radians"]);function Rt(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!_t.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function wt(t,e){return function(t,e){if("radians"!==e)return t;for(let e=0;e<t.length;e++)for(let r=0;r<t[e].length;r++)t[e][r]=st(t[e][r],!0);return t}(t.gen(e,new Array(yt).fill(null).map(()=>new Float32Array(vt))),t.angleMode)}function Et(t){if(S.field.wiggle||(S.field.wiggle=1),dt(),!bt.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(bt.keys()).join(", ")}.`);S.field.isActive=!0,S.field.current=t;const e=bt.get(t);e.field||(e.field=wt(e,0))}function At(t,e,r={}){bt.set(t,{gen:e,field:null,angleMode:Rt(r)})}function Mt(t=1){Et("hand"),S.field.wiggle=t}function St(t,e){for(let r=0;r<yt;r++)for(let n=0;n<vt;n++)t[r][n]=e(r,n);return t}const Tt=[],Pt=(t,e,r)=>Math.max(e,Math.min(t,r)),Ct="degrees",Ft="radians";let kt=null,It=Ft;const Dt=[];let Lt={a:1,b:0,c:0,d:1,x:0,y:0};function Nt(t,e){return{a:t.a*e.a+t.c*e.b,b:t.b*e.a+t.d*e.b,c:t.a*e.c+t.c*e.d,d:t.b*e.c+t.d*e.d,x:t.a*e.x+t.c*e.y+t.x,y:t.b*e.x+t.d*e.y+t.y}}class Bt{constructor(t,e,r){if(t?._array)return this.r=Math.round(255*t._array[0]),this.g=Math.round(255*t._array[1]),this.b=Math.round(255*t._array[2]),this.hex=this.rgbToHex(this.r,this.g,this.b),this._array=[...t._array],void(this.gl=this._array);if("string"==typeof t){const e=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)$/i.exec(t);if(e){this.r=Pt(parseInt(e[1]),0,255),this.g=Pt(parseInt(e[2]),0,255),this.b=Pt(parseInt(e[3]),0,255),this.hex=this.rgbToHex(this.r,this.g,this.b);const t=void 0!==e[4]?Pt(parseFloat(e[4]),0,1):1;return this._array=[this.r/255,this.g/255,this.b/255,t],void(this.gl=this._array)}this.hex=this.standardize(t);const r=this.hexToRgb(this.hex);this.r=r.r,this.g=r.g,this.b=r.b}else this.r=Pt(t??0,0,255),this.g=Pt(e??t??0,0,255),this.b=Pt(r??t??0,0,255),this.hex=this.rgbToHex(this.r,this.g,this.b);this._array=[this.r/255,this.g/255,this.b/255,1],this.gl=this._array}rgbToHex(t,e,r){return`#${(1<<24|t<<16|e<<8|r).toString(16).slice(1)}`}hexToRgb(t){t=t.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,(t,e,r,n)=>e+e+r+r+n+n);const e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(!e)throw new Error(`Invalid color value "${t}".`);return{r:parseInt(e[1],16),g:parseInt(e[2],16),b:parseInt(e[3],16)}}standardize(t){const e=function(){if(kt)return kt;if("undefined"!=typeof document)return kt=document.createElement("canvas").getContext("2d"),kt;if("undefined"!=typeof OffscreenCanvas)return kt=new OffscreenCanvas(1,1).getContext("2d"),kt;throw new Error("Standalone color parsing requires CanvasRenderingContext2D support.")}();return e.fillStyle=t,e.fillStyle}_getRed(){return this.r}_getGreen(){return this.g}_getBlue(){return this.b}}function Ut(){var t;(t={usesRadians:()=>"radians"===It,fromDegrees:t=>"radians"===It?t*Math.PI/180:t,createColor:(...t)=>1===t.length&&t[0]?._array?t[0]:new Bt(...t),getAffineMatrix:()=>Lt}).usesRadians&&(a=t.usesRadians),t.fromDegrees&&(s=t.fromDegrees),t.createColor&&(c=t.createColor),t.getAffineMatrix&&(l=t.getAffineMatrix)}let Yt,zt,Ot,Xt,Gt=null,Zt=!1,Vt=1,Ht=0,Wt=0;function $t(t,e,r,n){Gt=t,Ht=e,Wt=r,Vt=n;const i=function(t,e,r,n){const i=function(t){return t.getContext("webgl2",{premultipliedAlpha:!0})??t.getContext("webgl2")}(t);if(!i)throw new Error("brush.load(target) requires a canvas with a WebGL2 context.");return{canvas:t,drawingContext:i,width:e,height:r,pixelDensity:()=>n}}(t,e,r,n);h({Renderer:i,Cwidth:e,Cheight:r,Density:n}),Zt=!0}class qt{constructor(t,e=!1){this.a=t,this.vertices=e?t:t.map(([t,e])=>({x:t,y:e})),this.sides=this.vertices.map((t,e,r)=>[t,r[(e+1)%r.length]]),this._intersectionCache={}}intersect(t){const e=`${t.point1.x},${t.point1.y}-${t.point2.x},${t.point2.y}`;if(this._intersectionCache[e])return this._intersectionCache[e];const r=[];for(const[e,n]of this.sides){const i=ht(t.point1,t.point2,e,n);i&&r.push(i)}return this._intersectionCache[e]=r,r}show(){S.wash&&this.wash(),S.fill&&this.fill(),S.mass&&this.mass(),S.hatch&&this.hatch(),S.stroke&&this.draw()}}class jt{constructor(t){this.segments=[],this.angles=[],this.pres=[],this.type=t,this.dir=0,this.calcIndex(0),this.pol=!1}addSegment(t=0,e=0,r=1,n=!1){this.angles.length>0&&this.angles.pop(),t=n?(t%360+360)%360:at(t),this.angles.push(t,t),this.pres.push(r),this.segments.push(e),this.length=this.segments.reduce((t,e)=>t+e,0)}endPlot(t=0,e=1,r=!1){t=r?(t%360+360)%360:at(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=at(t)}pressure(t){return t>this.length?this.pres[this.pres.length-1]:this.curving(this.pres,t)}angle(t){return t>this.length?this.angles[this.angles.length-1]:(this.calcIndex(t),"curve"===this.type?this.curving(this.angles,t)+this.dir:this.angles[this.index]+this.dir)}curving(t,e){let r=t[this.index],n=t[this.index+1]??r;return Math.abs(n-r)>180&&(n>r?n=-(360-n):r=-(360-r)),K(e-this.suma,0,this.segments[this.index],r,n,!0)}calcIndex(t){this.index=-1,this.suma=0;let e=0;for(;e<=t;)this.suma=e,e+=this.segments[this.index+1],this.index++;return this.index}genPol(t,e,i=1,o){dt();const a=o<0?4:1,s=[],c=Math.round(this.length/a),l=new mt(t+r/2,e+n/2);let u=0,h=0;for(let t=0;t<c;t++){l.plotTo(this,a,a);const t=this.calcIndex(l.plotted);u+=a,(u>=(o<=0?8:Math.max(this.segments[t]*o*H(.7,1.3),20))||t>=h)&&l.x&&(s.push([l.x-r/2,l.y-n/2]),u=0,t>=h&&h++)}return new qt(s)}show(t,e,r=1){S.wash&&this.wash(t,e,r),S.fill&&this.fill(t,e,r),S.mass&&this.mass(t,e,r),S.hatch&&this.hatch(t,e,r),S.stroke&&this.draw(t,e,r)}}function Kt(t,e,r,n,i){const o=st(n),a=((st(i)-o)%360+360)%360;if(0===a)return;const s=new jt("curve"),c=Math.max(1,Math.ceil(a/90)),l=a/c,u=Math.PI*r*l/180;for(let t=0;t<c;t++)s.addSegment(o+t*l+90,u,1,!0);s.endPlot(o+a+90,1,!0);const h=t+r*it(o),f=e-r*ot(o);s.draw(h,f,1)}class Jt{constructor(){this.isClosed=!1,this.curvature=zt,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){re(this.vert,this.curvature,this.isClosed).show()}}function Qt(t=0){zt=J(t,0,1),Yt=new Jt}function te(t,e,r=1){if(!Yt)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");Yt.vertex(t,e,r)}function ee(t=!1){if(!Yt)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(Yt.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(Yt.vertex(...Yt.vert[0]),Yt.isClosed=!0),Yt.show(),Yt=!1}function re(t,e=.5,r=!1){const n=new jt(0===e?"segments":"curve"),i=2*Math.PI;if(r&&0!==e&&t.push(t[1]),t&&t.length>0){let o,a,s,c=0;for(let l=0;l<t.length-1;l++)if(e>0&&l<t.length-2){const u=t[l],h=t[l+1],f=t[l+2],d=lt(u[0],u[1],h[0],h[1]),m=lt(h[0],h[1],f[0],f[1]),x=ut(u[0],u[1],h[0],h[1]),g=ut(h[0],h[1],f[0],f[1]),p=e*Math.min(d,m,.5*Math.min(d,m)),y=Math.max(d,m),v=d-p,b=m-p;if(Math.floor(x)===Math.floor(g)){const e=r&&0===l?0:d-c,i=r?0===l?0:m-s:m;n.addSegment(x,e,u[2],!0),l===t.length-3&&n.addSegment(g,i,h[2],!0),c=0,0===l&&(o=d,s=p,a=t[1],c=0)}else{const e={x:h[0]-p*it(-x),y:h[1]-p*ot(-x)},f={x:e.x+y*it(90-x),y:e.y+y*ot(90-x)},d={x:h[0]+p*it(-g),y:h[1]+p*ot(-g)},m={x:d.x+y*it(90-g),y:d.y+y*ot(90-g)},_=ht(e,f,d,m,!0),R=lt(e.x,e.y,_.x,_.y),w=lt(e.x,e.y,d.x,d.y)/2,E=i*R*(2*Math.asin(w/R)*(180/Math.PI))/360,A=r&&0===l?0:v-c,M=l===t.length-3?r?o-p:b:0;n.addSegment(x,A,u[2],!0),n.addSegment(x,isNaN(E)?0:E,u[2],!0),n.addSegment(g,M,h[2],!0),c=p,0===l&&(o=v,s=p,a=[e.x,e.y])}l===t.length-3&&n.endPlot(g,h[2],!0)}else if(0===e){const e=t[l],r=t[l+1],i=lt(e[0],e[1],r[0],r[1]),o=ut(e[0],e[1],r[0],r[1]);n.addSegment(o,i,r[2],!0),l===t.length-2&&n.endPlot(o,1,!0)}n.origin=r&&0!==e?a:t[0]}return n}let ne={createTipSurface:()=>{throw new Error("No stroke runtime adapter registered.")},loadImageTip:()=>{throw new Error("No stroke runtime adapter registered.")}},ie=!1;const oe=(t,e,r)=>{const n=t.createProgram();for(let[i,o]of[[t.VERTEX_SHADER,e],[t.FRAGMENT_SHADER,r]]){const e=t.createShader(i);t.shaderSource(e,o),t.compileShader(e),t.attachShader(n,e)}return t.linkProgram(n),n};let ae={beginDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},endDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},resetDirectShaderTracking:()=>{}};const se=(t,e)=>ae.resetDirectShaderTracking(t,e);let ce,le,ue,he,fe,de=!1,me=0,xe=0,ge=null;const pe={},ye={};let ve=1,be=0,_e=0,Re=1,we=0,Ee=0,Ae=0,Me=0,Se=1,Te=1,Pe=new Float32Array(8192),Ce=0,Fe=2048,ke=32768,Ie=null,De=null,Le=null,Ne=null,Be=null;const Ue={},Ye={};let ze=0,Oe=new Float32Array(1280),Xe=0,Ge=256,Ze=null;const Ve=new Map,He=new Float32Array([-1,-1,1,-1,-1,1,1,1]);function We(){return le}function $e(){return((t,e,r)=>ae.beginDirectMaskDraw(t,e,r))(i,ce,P.glMask)}function qe(t){((t,e,r)=>{ae.endDirectMaskDraw(t,e,r)})(i,ce,t)}function je(t,e,r,n,i){return t?(e<t.minX&&(t.minX=e),r<t.minY&&(t.minY=r),n>t.maxX&&(t.maxX=n),i>t.maxY&&(t.maxY=i),t):{minX:e,minY:r,maxX:n,maxY:i}}function Ke(t,e,r,n){if(Ce>=Fe){Fe*=2;const t=new Float32Array(4*Fe);t.set(Pe),Pe=t}const i=t-Ae,o=e-Me,a=4*Ce,s=ve*i+_e*o+we+Ae,c=be*i+Re*o+Ee+Me,l=Te*r*Se/2;Pe[a]=s,Pe[a+1]=c,Pe[a+2]=l,Pe[a+3]=n/255;const u=s*Te,h=c*Te;Ie=je(Ie,u-l-1,h-l-1,u+l+1,h+l+1),Ce++}function Je(t,e){if(0===Xe)return;P.glMask.isDrawn=!0;const r=$e();let n=Ve.get(e);n||(n=ce.createTexture(),ce.bindTexture(ce.TEXTURE_2D,n),ce.texImage2D(ce.TEXTURE_2D,0,ce.RGBA,ce.RGBA,ce.UNSIGNED_BYTE,t.canvas),ce.texParameteri(ce.TEXTURE_2D,ce.TEXTURE_MIN_FILTER,ce.LINEAR),ce.texParameteri(ce.TEXTURE_2D,ce.TEXTURE_MAG_FILTER,ce.LINEAR),ce.texParameteri(ce.TEXTURE_2D,ce.TEXTURE_WRAP_S,ce.CLAMP_TO_EDGE),ce.texParameteri(ce.TEXTURE_2D,ce.TEXTURE_WRAP_T,ce.CLAMP_TO_EDGE),Ve.set(e,n)),ce.useProgram(De),ce.enable(ce.BLEND),ce.blendFunc(ce.ONE_MINUS_DST_ALPHA,ce.ONE),ce.activeTexture(ce.TEXTURE0),ce.bindTexture(ce.TEXTURE_2D,n),ce.uniform1i(Ye.u_tex,0);const o=S.stroke.color._array;ce.uniform4f(Ye.u_color,...o),ce.uniformMatrix4fv(Ye.u_proj,!1,We()),ce.bindVertexArray(Le),ce.bindBuffer(ce.ARRAY_BUFFER,Be);const a=5*Xe*4,s=Oe.subarray(0,5*Xe);a>ze?(ce.bufferData(ce.ARRAY_BUFFER,Oe,ce.DYNAMIC_DRAW),ze=Oe.byteLength):ce.bufferSubData(ce.ARRAY_BUFFER,0,s),ce.drawArraysInstanced(ce.TRIANGLE_STRIP,0,4,Xe),ce.bindVertexArray(null),ce.bindTexture(ce.TEXTURE_2D,null),qe(r),Ze&&(P.markDirtyRect(P.glMask,Ze),Ze=null),Xe=0,se(i,ce)}ie||(v={ensureResources:function(t,e,r,n){return function(t,e,r,n){return!t.glMask||t.glMask.width!==e||t.glMask.height!==r||"function"==typeof t.glMask.pixelDensity&&t.glMask.pixelDensity()!==n}(t,e,r,n)&&(t.glMask?.remove&&t.glMask.remove(),t.glMask=y(t,{width:e,height:r,density:n,antialias:!1,depth:!1,stencil:!1})),t.glMask.dirtyRect??=null,t.glMask.isDrawn??=!1,t.glMask},clearMask:function(t,e){t&&(e(t),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:function(t,e,r,n,i){return t?t.dirtyRect?e()?r():i(n(t.dirtyRect,2)):r():null},getShaderMask:function(t,e){return e}},ie=!0),S.stroke={color:null,weight:1,type:"HB",isActive:!1,opacity:1};let Qe=new Map;const tr={offset:.08,scale:.08,warp:.06,tilt:.06};function er(){return{...S.stroke}}function rr(t){S.stroke={...t}}function nr(t,e){if(e.type=["marker","custom","image","spray"].includes(e.type)?e.type:"default",void 0===e.markerTip&&(e.markerTip=!0),void 0===e.noise&&(e.noise=.3),e.noise=Math.max(0,Math.min(1,e.noise)),void 0!==e.vibration&&void 0===e.scatter&&(e.scatter=e.vibration),void 0!==e.definition&&void 0===e.sharpness&&(e.sharpness=e.definition),void 0!==e.quality&&void 0===e.grain&&(e.grain=e.quality),e.pressure=function(t){if(!t)return t;if("function"==typeof t)return{type:"custom",min_max:[0,1],curve:t,variation:{...tr}};if("object"==typeof t&&!Array.isArray(t)){if("custom"===t.type||"custom"===t.mode){const{mode:e,...r}=t;return{...r,type:"custom",variation:{...tr,...r.variation??{}}}}return"gaussian"===t.type||"gaussian"===t.mode||Array.isArray(t.curve)&&Array.isArray(t.min_max)?{...t,type:"gaussian",curve:t.curve,min_max:t.min_max}:t}if(Array.isArray(t)){const[e,r,n]=2===t.length?[t[0],(t[0]+t[1])/2,t[1]]:t,i=Math.min(e,r,n),o=Math.max(e,r,n),a=o-i||1,[s,c,l]=[(e-i)/a,(r-i)/a,(n-i)/a];return{type:"custom",min_max:[i,o],variation:{...tr},curve:t=>t<.5?s+(c-s)*t*2:c+(l-c)*(t-.5)*2}}}(e.pressure),"custom"===e.type){if("function"!=typeof e.tip)throw new Error(`Brush "${t}" is type "custom" but is missing a tip function.`);const r=`custom::${t}`;!function(t){const e=Ve.get(t);e&&ce&&ce.deleteTexture(e),Ve.delete(t)}(r);const n=ne.createTipSurface(500,500);return n.pixelDensity(1),n.background(255),n.noSmooth(),n.push(),n.translate(250,250),n.scale(5),n.noStroke(),e.tip(n),n.pop(),Pr.imageToWhite(n),Pr.tips.set(r,n),e.tipKey=r,void Qe.set(t,{param:e,colors:[],buffers:[]})}if("image"===e.type){if(!e.image||!e.image.src)throw new Error(`Brush "${t}" is type "image" but is missing params.image.src. Example: image: { src: "./tip.jpg" }`);return Pr.add(e.image.src),Qe.set(t,{param:e,colors:[],buffers:[]}),Pr.load()}Qe.set(t,{param:e,colors:[],buffers:[]})}function ir(t){return Qe.get(t)?.param??null}function or(t){if(!Qe.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...Qe.keys()].join(", ")}.`);S.stroke.type=t}function ar(t,e,r){f(),S.stroke.color=c(...arguments),S.stroke.isActive=!0}function sr(t){S.stroke.weight=t}function cr(t,e,r=1){or(t),ar(e),sr(r)}let lr,ur,hr,fr,dr=0;const mr={};function xr(t,e,i,a=!1){!function(){const t=l();ve=t.a,be=t.b,_e=t.c,Re=t.d,we=t.x,Ee=t.y,Ae=r/2,Me=n/2,Se=Math.sqrt(ve*ve+be*be),Te=o}(),lr=new mt(t+r/2,e+n/2),ur=i,hr=a,hr&&hr.calcIndex(0)}const gr=[];function pr(t,e){e||(fr=t),function(){mr.seed=999999*V();const{param:t}=Qe.get(S.stroke.type)??{};if(!t)return;mr.p=t;const{pressure:e}=t;if(mr.isCustomPressure="custom"===e.type,mr.a=mr.isCustomPressure?0:V(-1,1),mr.b=mr.isCustomPressure?0:V(1,1.5),mr.isCustomPressure){const t=e.variation??tr;mr.cp=V(-t.offset,t.offset),mr.ct=V(-t.warp,t.warp),mr.cs=V(1-t.scale,1+t.scale),mr.ck=V(-t.tilt,t.tilt)}else mr.cp=V(3,3.5),mr.ct=0,mr.cs=1,mr.ck=0;[mr.min,mr.max]=e.min_max,mr.noiseoffset=.05*mr.p.noise,hr||(mr.cos=it(fr),mr.sin=ot(fr)),function(){T(),function(){const t=i?.glMask;t&&(ge=t,ge.dirtyRect??=null,ge.isDrawn??=!1,P.glMask=ge)}();const t=i.drawingContext,e=!de||ce!==t;(e||me!==r||xe!==n)&&(le=new Float32Array([2/r,0,0,0,0,2/n,0,0,0,0,1,0,-1,-1,0,1]),me=r,xe=n),e&&(ce=t,fe=oe(ce,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_position;in float a_radius;in float a_alpha;uniform mat4 u_matrix;out float v_alpha;void main(){gl_Position=u_matrix*vec4(a_position,0.0,1.0);v_alpha=a_alpha;gl_PointSize=a_radius*2.0;}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin float v_alpha;out vec4 outColor;uniform vec4 u_color;void main(){vec2 v=gl_PointCoord-vec2(0.5);float f=length(v);float a=fwidth(f);f=1.0-smoothstep(0.5-a,0.5+a,f);if(f<0.01){discard;}outColor=vec4(u_color.xyz,v_alpha*f);}"),ce.useProgram(fe),ce.enable(ce.BLEND),ce.blendFunc(ce.ONE_MINUS_DST_ALPHA,ce.ONE),["a_position","a_radius","a_alpha"].forEach(t=>pe[t]=ce.getAttribLocation(fe,t)),["u_matrix","u_color"].forEach(t=>ye[t]=ce.getUniformLocation(fe,t)),ue=ce.createVertexArray(),ce.bindVertexArray(ue),he=ce.createBuffer(),ce.bindBuffer(ce.ARRAY_BUFFER,he),ce.bufferData(ce.ARRAY_BUFFER,Pe.byteLength,ce.DYNAMIC_DRAW),ke=Pe.byteLength,ce.enableVertexAttribArray(pe.a_position),ce.vertexAttribPointer(pe.a_position,2,ce.FLOAT,!1,16,0),ce.enableVertexAttribArray(pe.a_radius),ce.vertexAttribPointer(pe.a_radius,1,ce.FLOAT,!1,16,8),ce.enableVertexAttribArray(pe.a_alpha),ce.vertexAttribPointer(pe.a_alpha,1,ce.FLOAT,!1,16,12),ce.bindVertexArray(null),Ve.clear(),De=oe(ce,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_corner;in vec2 a_pos;in float a_size;in float a_angle;in float a_alpha;uniform mat4 u_proj;out vec2 v_uv;out float v_alpha;void main(){float c=cos(a_angle);float s=sin(a_angle);vec2 rotated=vec2(c*a_corner.x-s*a_corner.y,s*a_corner.x+c*a_corner.y);gl_Position=u_proj*vec4(a_pos+rotated*a_size,0.0,1.0);v_uv=a_corner*0.5+0.5;v_alpha=a_alpha;}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin vec2 v_uv;in float v_alpha;uniform sampler2D u_tex;uniform vec4 u_color;out vec4 outColor;void main(){float inkAlpha=texture(u_tex,v_uv).a;if(inkAlpha<0.01)discard;outColor=vec4(u_color.rgb,inkAlpha*v_alpha);}"),["a_corner","a_pos","a_size","a_angle","a_alpha"].forEach(t=>Ue[t]=ce.getAttribLocation(De,t)),["u_proj","u_color","u_tex"].forEach(t=>Ye[t]=ce.getUniformLocation(De,t)),Le=ce.createVertexArray(),ce.bindVertexArray(Le),Ne=ce.createBuffer(),ce.bindBuffer(ce.ARRAY_BUFFER,Ne),ce.bufferData(ce.ARRAY_BUFFER,He,ce.STATIC_DRAW),ce.enableVertexAttribArray(Ue.a_corner),ce.vertexAttribPointer(Ue.a_corner,2,ce.FLOAT,!1,0,0),Be=ce.createBuffer(),ce.bindBuffer(ce.ARRAY_BUFFER,Be),ce.bufferData(ce.ARRAY_BUFFER,Oe.byteLength,ce.DYNAMIC_DRAW),ze=Oe.byteLength,ce.enableVertexAttribArray(Ue.a_pos),ce.vertexAttribPointer(Ue.a_pos,2,ce.FLOAT,!1,20,0),ce.vertexAttribDivisor(Ue.a_pos,1),ce.enableVertexAttribArray(Ue.a_size),ce.vertexAttribPointer(Ue.a_size,1,ce.FLOAT,!1,20,8),ce.vertexAttribDivisor(Ue.a_size,1),ce.enableVertexAttribArray(Ue.a_angle),ce.vertexAttribPointer(Ue.a_angle,1,ce.FLOAT,!1,20,12),ce.vertexAttribDivisor(Ue.a_angle,1),ce.enableVertexAttribArray(Ue.a_alpha),ce.vertexAttribPointer(Ue.a_alpha,1,ce.FLOAT,!1,20,16),ce.vertexAttribDivisor(Ue.a_alpha,1),ce.bindVertexArray(null),de=!0)}();const o=!0!==P.isBrush;P.isBrush=!0,o&&(P.justChanged=!0),P.blend(S.stroke.color),mr.alpha=["default","spray"].includes(mr.p.type)?mr.p.opacity:mr.p.opacity/Math.min(S.stroke.weight,1.3),mr.overscan=function(){const t=Math.max(1,mr.max??1),e=S.stroke.weight*mr.p.scatter,r=S.stroke.weight*mr.p.weight*t;return Math.max(8,1.5*e+.75*r)}(),mr.drawFn="spray"===mr.p.type?_r:"marker"===mr.p.type?Rr:"custom"===mr.p.type||"image"===mr.p.type?wr:Er,Ar()}();const o=mr.p?.spacing??1,a=Math.round(ur*(e?t:1)/o);mr.pressureCount=10,mr.cachedPressure=void 0,mr.lineNoiseCount=5,mr.cachedLineNoise=void 0;const s=2*a;for(;gr.length<s;)gr.push(j());for(let r=0;r<a;r++)e&&(dr=hr.angle(lr.plotted)),yr(),e?lr.plotTo(hr,o,o,t,dr):lr._moveToDegrees(t,o,o);!function(){Ar(),function(){if(0===Ce)return;P.glMask.isDrawn=!0;const t=$e(),e=S.stroke.color._array;ce.useProgram(fe),ce.enable(ce.BLEND),ce.blendFunc(ce.ONE_MINUS_DST_ALPHA,ce.ONE),ce.bindVertexArray(ue),ce.bindBuffer(ce.ARRAY_BUFFER,he);const r=16*Ce,n=Pe.subarray(0,4*Ce);r>ke?(ce.bufferData(ce.ARRAY_BUFFER,Pe,ce.DYNAMIC_DRAW),ke=Pe.byteLength):ce.bufferSubData(ce.ARRAY_BUFFER,0,n),ce.uniform4f(ye.u_color,...e),ce.uniformMatrix4fv(ye.u_matrix,!1,We()),ce.drawArrays(ce.POINTS,0,Ce),ce.bindVertexArray(null),qe(t),Ie&&(P.markDirtyRect(P.glMask,Ie),Ie=null),Ce=0,se(i,ce)}();const t=mr.p?.type;"image"===t?Je(Pr.tips.get(mr.p.image.src),mr.p.image.src):"custom"===t&&Je(Pr.tips.get(mr.p.tipKey),mr.p.tipKey)}()}function yr(){const t=vr(),e=((mr.lineNoiseCount>=10||void 0===mr.cachedLineNoise)&&(mr.cachedLineNoise=K(G(mr.seed+.01*lr.plotted,0),-1,1,1-mr.noiseoffset,1+mr.noiseoffset),mr.lineNoiseCount=0),mr.lineNoiseCount++,mr.cachedLineNoise);e>V(1,1.02)&&V(0,1)<.7||mr.drawFn(t*e)}function vr(){return(mr.pressureCount>=10||void 0===mr.cachedPressure)&&(mr.cachedPressure=hr?br()*hr.pressure(lr.plotted):br(),mr.pressureCount=0),mr.pressureCount++,mr.cachedPressure}function br(){if(!mr.isCustomPressure)return function(t=.5+mr.p.pressure.curve[0]*mr.a,e=1-mr.p.pressure.curve[1]*mr.b,r=mr.cp,n=mr.min,i=mr.max){const o=t*ur,a=(lr.plotted<o?1.2*e:.8*e)*(ur/2);return K(1/(1+Math.pow(Math.abs((lr.plotted-o)/a),2*r)),0,1,n,i)}();const t=lr.plotted/ur;return K(mr.p.pressure.curve(Math.max(0,Math.min(1,.5+(t-.5+mr.ct)*mr.cs)))+mr.cp+mr.ck*(t-.5),0,1,mr.min,mr.max,!0)}function _r(t){const e=S.stroke.weight*mr.p.scatter*t+S.stroke.weight*W(gr)*mr.p.scatter/3,r=mr.p.weight*V(.9,1.1),n=Math.ceil(mr.p.grain/t);for(let t=0;t<n;t++){const t=V(.9,1.1),n=t*e*V(-1,1),i=V(-1,1),o=Math.sqrt((t*e)**2-n**2);Ke(lr.x+n,lr.y+i*o,r,mr.alpha)}}function Rr(t,e=!0,r=mr.alpha){const n=e?S.stroke.weight*mr.p.scatter:0,i=e?n*V(-1,1):0,o=e?n*V(-1,1):0;Ke(lr.x+i,lr.y+o,S.stroke.weight*mr.p.weight*t,r*Math.max(.8,t)*V(.9,1.1))}function wr(t,e=mr.alpha){const r=S.stroke.weight*mr.p.scatter,n=r*V(-1,1),i=r*V(-1,1),o=mr.p.weight*S.stroke.weight*t,a=mr.overscan;let s=0;"random"===mr.p.rotate?s=$(0,360)*(Math.PI/180):"natural"===mr.p.rotate&&(s=((hr?-dr:-fr)+lr.angle())*(Math.PI/180)),function(t,e,r,n,i,o=0){if(Xe>=Ge){Ge*=2;const t=new Float32Array(5*Ge);t.set(Oe),Oe=t}const a=t-Ae,s=e-Me,c=ve*a+_e*s+we+Ae,l=be*a+Re*s+Ee+Me,u=Te*r*Se/2,h=Te*o*Se,f=5*Xe;Oe[f]=c,Oe[f+1]=l,Oe[f+2]=u,Oe[f+3]=n,Oe[f+4]=i/255;const d=c*Te,m=l*Te,x=1.42*u+h;Ze=je(Ze,d-x-1,m-x-1,d+x+1,m+x+1),Xe++}(lr.x+n,lr.y+i,o,s,e*Math.max(.8,t)*V(.9,1.1),a)}function Er(t,e=1){const r=(e=K(e,0,1,.9,1.05))*S.stroke.weight*mr.p.scatter*(mr.p.sharpness+(1-mr.p.sharpness)*W(gr)/t);if(V(0,mr.p.grain*t)>.4){let e,n;if(hr){const t=dr,i=it(t),o=ot(t),a=r*V(-1,1),s=.3*r*V(-1,1);e=a*o+s*i,n=a*i-s*o}else{const t=r*V(-1,1),i=.3*r*V(-1,1);e=t*mr.sin+i*mr.cos,n=t*mr.cos-i*mr.sin}const i=t*t*mr.p.weight*V(.85,1.15)*S.stroke.weight,o=Math.max(.9,t)*mr.alpha*V(.75,1.1);Ke(lr.x+e,lr.y+n,i,o)}}function Ar(){if(!1===mr.p.markerTip)return;let t=vr(),e=mr.alpha;if("marker"===mr.p.type)for(let r=1;r<10;r++)Rr(t*r/10,!0,8*e);else if("custom"===mr.p.type||"image"===mr.p.type)for(let r=1;r<5;r++)wr(t*r/10,2*e)}function Mr(t,e,r,n){if(!S.stroke.isActive||!S.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");dt();let i=lt(t,e,r,n);0!=i&&(xr(t,e,i),pr(ut(t,e,r,n),!1))}X(()=>{gr.length=0});const Sr=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate","markerTip","noise"],Tr=[["pen",[.3,.15,.9,2,150,.1,{curve:[.15,.2],min_max:[1.2,1]}]],["rotring",[.15,.05,.7,15,210,.1,{curve:[.35,.2],min_max:[1.3,1]}]],["2B",[.3,.75,.45,15,180,.1,{curve:[.1,.3],min_max:[1.1,.9]}]],["HB",[.3,.6,.3,10,170,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["2H",[.2,.6,.3,4,120,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["cpencil",[.3,.55,.8,7,75,.1,{curve:[.15,.2],min_max:[.95,1.2]}]],["pastel",[2.05/3,13.4/3,.91,28,35,.085/3,{mode:"gaussian",curve:[.4,.05],min_max:[1.09,.93]},"default",void 0,"natural",!0,1]],["crayon",[.3,5.45/3,.75,250,159,.23/3,[1.1,.9],"default",void 0,"natural",!0,1]],["charcoal",[.35,1.5,.68,500,120,.03,{curve:[.15,.4],min_max:[1.1,.95]}]],["spray",[.2,6,15,40,90,.5,{curve:[.2,.35],min_max:[.7,1]},"spray"]],["marker",[2,.2,null,null,1,.03,{curve:[.35,.25],min_max:[1.2,.85]},"marker"]]];for(let t of Tr){let e={};for(let r=0;r<t[1].length;r++)e[Sr[r]]=t[1][r];nr(t[0],e)}qt.prototype.draw=function(t=!1,e,r){let n=er();if(t&&cr(t,e,r),n.isActive)for(let t of this.sides)Mr(t[0].x,t[0].y,t[1].x,t[1].y);rr(n)},jt.prototype.draw=function(t,e,r){er().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,n){dt(),xr(e,r,t.length,t),pr(n,!0)}(this,t,e,r))};const Pr={tips:new Map,add(t){this.tips.has(t)||this.tips.set(t,!1)},imageToWhite(t){t.loadPixels();for(let e=0;e<4*t.width*t.height;e+=4){let r=(t.pixels[e]+t.pixels[e+1]+t.pixels[e+2])/3;t.pixels[e]=t.pixels[e+1]=t.pixels[e+2]=255,t.pixels[e+3]=255-r}t.updatePixels()},async load(){const t=[...this.tips.keys()].filter(t=>!this.tips.get(t));await Promise.all(t.map(t=>((t,e)=>ne.loadImageTip(t,e))(t,Pr.imageToWhite).then(e=>{this.tips.set(t,e)})))}};function Cr(){return{...S.hatch}}function Fr(t){S.hatch={...t}}function kr(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let n=S.hatch;n.isActive=!0,n.dist=t,n.angle=st(e),n.options=r}function Ir(t,e,r,n){const i=e*Math.PI/180,o=Math.cos(i),a=Math.sin(i),s=Math.cos(-i),c=Math.sin(-i),l=t.a,u=l.length,h=new Array(u);let f=Infinity,d=-Infinity;for(let t=0;t<u;t++){const e=l[t][0],r=l[t][1],n=[e*o-r*a,e*a+r*o];h[t]=n,n[1]<f&&(f=n[1]),n[1]>d&&(d=n[1])}const m=[];for(let t=0;t<u;t++){const e=h[t],r=h[(t+1)%u];e[1]!==r[1]&&m.push(e,r)}const x=m.length,g=[],p=[];let y=f+.5*r,v=r;for(;y<d;){p.length=0;for(let t=0;t<x;t+=2){const e=m[t][1],r=m[t+1][1];(e<=y&&y<r||r<=y&&y<e)&&p.push(m[t][0]+(y-e)/(r-e)*(m[t+1][0]-m[t][0]))}p.sort((t,e)=>t-e);for(let t=0;t<p.length-1;t+=2)g.push({scanY:y,x1:p[t]*s-y*c,y1:p[t]*c+y*s,x2:p[t+1]*s-y*c,y2:p[t+1]*c+y*s});y+=v,v*=n}return g}function Dr(t){const{dist:e,options:r,segs:n}=function(t){const e=S.hatch.dist,r=(S.hatch.angle%180+180)%180,n=S.hatch.options,i=function(t,e,r,n){Array.isArray(t)||(t=[t]);const i=[];for(const o of t)for(const t of Ir(o,r,e,n))i.push(t);return i.sort((t,e)=>t.scanY===e.scanY?t.x1-e.x1:t.scanY-e.scanY),i}(t,e,r,n.gradient?K(n.gradient,0,1,1,1.1,!0):1);return{dist:e,options:n,segs:i}}(t),i=r.rand||0,o=[];for(let t=0;t<n.length;t++){const a=n[t];let s=a.x1,c=a.y1,l=a.x2,u=a.y2;i&&(s+=2*i*e*V(-1,1),c+=2*i*e*V(-1,1),l+=2*i*e*V(-1,1),u+=2*i*e*V(-1,1));const h=r.continuous&&t%2==1?{x1:l,y1:u,x2:s,y2:c,scanY:a.scanY,isConnector:!1}:{x1:s,y1:c,x2:l,y2:u,scanY:a.scanY,isConnector:!1};if(o.push(h),t>0&&r.continuous){const t=o[o.length-2];o.push({x1:t.x2,y1:t.y2,x2:h.x1,y2:h.y1,scanY:a.scanY,isConnector:!0})}}return o}function Lr(t){!function(t,e){const r=Dr(t);!function(){const t=er();S.hatch.hBrush&&cr(...Object.values(S.hatch.hBrush)),(()=>{for(let t=0;t<r.length;t++){const n=r[t];e(n.x1,n.y1,n.x2,n.y2,t,r)}})(),rr(t)}()}(t,(t,e,r,n)=>{Mr(t,e,r,n)})}function Nr(t,e,r){return new qt(t.vertices.map(t=>[t.x+e,t.y+r]))}function Br(t,e,r,n,i){const o=(e+n)/2,a=(r+i)/2,s=n-e,c=i-r,l=Math.hypot(s,c);if(!l)return null;const u=-c/l,h=s/l,f=(t.x-o)*u+(t.y-a)*h;return{x:o+u*f,y:a+h*f}}function Ur(t,e,r,n,i,o,a){let s=ut(t,e,r,n),c=ut(t,e,i,o);return((c-s)%360+360)%360>180&&([s,c]=[c,s]),[a(s),a(c)]}function Yr(t){const e=H(.35,.65),r=t.x1+(t.x2-t.x1)*e,n=t.y1+(t.y2-t.y1)*e,i=t.x2-t.x1,o=t.y2-t.y1,a=Math.hypot(i,o)||1,s=H(.04,.1)*a,c=i/a*s*.5,l=o/a*s*.5;return[{x1:t.x1,y1:t.y1,x2:r-c,y2:n-l},{x1:r+c,y1:n+l,x2:t.x2,y2:t.y2}]}function zr(t,e,r){const n=function(t,e){const r=function(t){const e=t?.a??[];let r=Infinity,n=Infinity,i=-Infinity,o=-Infinity;for(const[t,a]of e)t<r&&(r=t),a<n&&(n=a),t>i&&(i=t),a>o&&(o=a);return{minX:r,minY:n,maxX:i,maxY:o,cx:(r+i)/2,cy:(n+o)/2,size:Math.hypot(i-r,o-n)}}(t),n=r.size*H(.6,1.4),[i,o]=e;return{x:r.cx+i*n,y:r.cy+o*n}}(t,e);for(const e of Dr(t)){const t=!e.isConnector&&H()<.35?Yr(e):[e];for(const e of t){const t=Br(n,e.x1,e.y1,e.x2,e.y2);if(!t)continue;const i=lt(t.x,t.y,e.x1,e.y1);if(!i)continue;const[o,a]=Ur(t.x,t.y,e.x1,e.y1,e.x2,e.y2,r);Kt(t.x,t.y,i,o,a)}}}function Or(t,e,r,n,i,o){kr(e,r,n),zr(t,i,o)}function Xr(t,e,r,n){const i=function(t,e,r,n){const i=!1===e,o=ir(S.mass.brush)?.scatter??0,a=i?t:t.genPol(e,r,n,.15),s=Math.min(2*o,5),c=[[H(-s,s),H(-s,s)],[H(-s,s),H(-s,s)]];return[a,Nr(a,c[0][0],c[0][1]),Nr(a,c[1][0],c[1][1])]}(t,e,r,n),o=Cr(),c=er(),l={...S.field},u=S.mass.options?.precision??.5,h=S.mass.options?.strength??1,f=S.mass.options?.gradient??.1,d=S.mass.options?.outline??!1,m=ir(S.mass.brush)?.scatter??0,x=1.6*H(.65*m,.85*m)-.4*f,g=H(-90,90),p=((g+90)%180+180)%180-90>=0?H()<.5?[1,1]:[-1,-1]:H()<.5?[-1,1]:[1,-1],y=a()?t=>t*Math.PI/180:t=>t;cr(S.mass.brush,S.mass.color,1),Mt(2-u),d&&i[0].draw(),Or(i[0],.9*x,s(g),{gradient:f,rand:2-2*u,continuous:!0},p,y),h>.33&&Or(i[1],x,s(g+20*H(-1,1)),{gradient:f,rand:.6-.6*u,continuous:!0},p,y),h>.66&&Or(i[2],.8*x,s(g+15*H(-1,1)),{gradient:f,rand:.6-.6*u,continuous:!0},p,y),rr(c),Fr(o),S.field={...l}}function Gr(t,e,r){const n=2*Math.PI,i=P.ctx,o=r/2;i.moveTo(t+o,e),i.arc(t,e,o,0,n)}S.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},qt.prototype.hatch=function(t=!1,e,r){let n=Cr();t&&kr(t,e,r),S.hatch.isActive&&Lr(this),Fr(n)},jt.prototype.hatch=function(t,e,r){Cr().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,.3),this.pol.hatch())},S.mass={isActive:!1,brush:null,color:null,options:{}},qt.prototype.mass=function(){S.mass?.isActive&&Xr(this,!1)},jt.prototype.mass=function(t,e,r){S.mass?.isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),Xr(this,t,e,r))};let Zr=null,Vr=!1;Vr||(b={ensureResources:function(t,e,r,n,i){const o=Math.max(1,Math.round(e*n)),a=Math.max(1,Math.round(r*n));return function(t,e,r){return!t.mask||t.mask.width!==e||t.mask.height!==r}(t,o,a)&&(t.mask=g(o,a)),function(t,e,r,n){return!t.fillMaskFramebuffer||t.fillMaskFramebuffer.width!==e||t.fillMaskFramebuffer.height!==r||"function"==typeof t.fillMaskFramebuffer.pixelDensity&&t.fillMaskFramebuffer.pixelDensity()!==n}(t,e,r,n)&&(t.fillMaskFramebuffer?.remove&&t.fillMaskFramebuffer.remove(),t.fillMaskFramebuffer=y(t,{width:e,height:r,density:n,antialias:!1,depth:!1,stencil:!1}),i(t.fillMaskFramebuffer)),t.mask.dirtyRect??=null,t.mask.isDrawn??=!1,t.mask.drawingContext.imageSmoothingEnabled=!1,{mask:t.mask,ctx:t.mask.drawingContext}},clearMask:function(t,e){t&&(e(t),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:function(t,e,r,n,i){return t?t.dirtyRect?i(n(t.dirtyRect,4)):r():null},getShaderMask:function(t,e,r,n,i){const o=t.fillMaskFramebuffer,a=t.drawingContext,s=r??n(),c=s.maxX-s.minX,l=s.maxY-s.minY;Zr&&Zr.width===c&&Zr.height===l||(Zr=g(c,l));const u=Zr.drawingContext;return u.clearRect(0,0,c,l),u.drawImage(e,s.minX,s.minY,c,l,0,0,c,l),i(o),a.bindTexture(a.TEXTURE_2D,o.colorTexture),a.texSubImage2D(a.TEXTURE_2D,0,s.minX,s.minY,a.RGBA,a.UNSIGNED_BYTE,Zr),o}},Vr=!0);let Hr,Wr=[],$r=[],qr=[],jr=[];S.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const Kr=()=>({...S.fill});function Jr(t,e,r,n){S.fill.opacity=(arguments.length<4?e:n)||150,S.fill.color=arguments.length<3?c(t):c(t,e,r),S.fill.isActive=!0}function Qr(t,e="out"){S.fill.bleed_strength=J(t,0,1),S.fill.direction=e}function tn(t=.4,e=.4){S.fill.texture_strength=J(t,0,1),S.fill.border_strength=J(e,0,1)}let en,rn,nn,on,an;const sn=[[],[]];function cn(){for(let t=0;t<512;t++)sn[0][t]=j(.5,.2),sn[1][t]=j(0,.02)}X(cn);class ln{constructor(t,e,r,n=[],i=!1,o,a){if(this.v=t,this.m=e,this.dir=n,this.midP=r,i){let e=0,n=0;const i=[];for(let o=0;o<t.length;o++){const a=Math.abs(r.x-t[o].x),s=Math.abs(r.y-t[o].y);e=Math.max(e,a),n=Math.max(n,s);const c=t[o],l=t[(o+1)%t.length],u={x:l.x-c.x,y:l.y-c.y},h=ct(0,0,u.x,u.y,90),f={x:c.x+u.x/2,y:c.y+u.y/2};i.push({v1:c,v2:l,ray:{point1:f,point2:{x:f.x+h.x,y:f.y+h.y}}})}this.sizeX=e,this.sizeY=n;const o=en.sides;this.dir=Array(t.length);for(let t=0;t<i.length;t++){const e=i[t],r=e.ray.point1.x,n=e.ray.point1.y,a=e.ray.point2.x-r,s=e.ray.point2.y-n;let c=0;for(let t=0;t<o.length;t++){const i=o[t][0],l=o[t][1],u=l.x-i.x,h=l.y-i.y,f=h*a-u*s;if(0===f)continue;const d=(a*(n-i.y)-s*(r-i.x))/f;if(d<0||d>1)continue;const m=(u*(n-i.y)-h*(r-i.x))/f,x=r+m*a,g=n+m*s;(e.v2.x-e.v1.x)*(g-e.v1.y)-(e.v2.y-e.v1.y)*(x-e.v1.x)>.01&&c++}this.dir[t]=c%2==0}const a=V(-.6,.6)*e,s=V(-.6,.6)*n;this.midP={x:r.x+a,y:r.y+s}}else this.sizeX=o,this.sizeY=a}trim(t=1){if(t>=1||t<0||this.v.length<=8)return{v:this.v,m:this.m,dir:this.dir};const e=~~((1-t)*this.v.length),r=~~(this.v.length/2-e/2),n=this.v.length-e,i=new Array(n),o=new Array(n),a=new Array(n);let s=0;for(let t=0;t<r;t++,s++)i[s]=this.v[t],o[s]=this.m[t],a[s]=this.dir[t];for(let t=r+e;t<this.v.length;t++,s++)i[s]=this.v[t],o[s]=this.m[t],a[s]=this.dir[t];const c=r,l=r+e,u=this.v[(c-1+this.v.length)%this.v.length],h=this.v[l%this.v.length],f=h.x-u.x,d=h.y-u.y;for(let t=0;t<2;t++){const e=V(.25,.75),n={x:u.x+f*e,y:u.y+d*e},s=r+t;i.splice(s,0,n),o.splice(s,0,V(.4,.7)),a.splice(s,0,this.dir[c%this.dir.length])}return{v:i,m:o,dir:a}}scatter(t=.3){const e=this.v.length,r=Math.max(3,~~(e*t)),n=[],i=e/r;for(let t=0;t<r;t++)n.push(~~(t*i+V(0,.8*i)));const o=[],a=[],s=[],c=this.midP,l=en.sides;for(const t of n){const r=t%e;let n=this.v[r],i=!1;if(n.x<rn||n.x>on||n.y<nn||n.y>an)i=!0;else{let t=0;for(const[e,r]of l){const i=e.y,o=r.y;if(i>n.y==o>n.y)continue;const a=(n.y-i)/(o-i);n.x<e.x+a*(r.x-e.x)&&t++}i=t%2==0}i&&(n={x:c.x+(n.x-c.x)*V(.3,.6),y:c.y+(n.y-c.y)*V(.3,.6)}),o.push(n),a.push(this.m[r]),s.push(!this.dir[r])}return new ln(o,a,this.midP,s,!1,this.sizeX,this.sizeY)}flipDirs(){return new ln(this.v,this.m,this.midP,this.dir.map(t=>!t),!1,this.sizeX,this.sizeY)}grow(t=1){const{v:e,m:r,dir:n}=this.trim(t),i=e.length,o=2*i;Wr.length<i&&(Wr=new Array(i),$r=new Array(i)),qr.length<o&&(qr=new Array(o),jr=new Array(o));const a=Wr,s=$r,c=qr,l=jr,u="out"===S.fill.direction?-90:90;0===sn[0].length&&cn();const h=sn[0],f=h.length,d=sn[1],m=d.length;let x,g,p,y=0,v=0,b=999===t?V(.6,.8):S.fill.bleed_strength;for(let o=0;o<i;o++){const x=e[o],g=e[o+1<i?o+1:0],p=r[o],_=n[o];if(t<997&&(b=p),b<.05){c[y]=p,l[y]=_,y++,a[v]=(x.x+g.x)/2,s[v]=(x.y+g.y)/2,c[y]=p,l[y]=_,y++,v++;continue}const R=(_?u:-u)+5*V(-1,1),w=it(R),E=ot(R),A=g.x-x.x,M=g.y-x.y,S=w*A+E*M,T=w*M-E*A,P=h[~~(V(0,1)*f)]*V(.65,1.35)*b,C=p+d[~~(V(0,1)*m)];c[y]=p,l[y]=_,y++,a[v]=x.x+.5*A+S*P,s[v]=x.y+.5*M+T*P,c[y]=C,l[y]=_,y++,v++}if(Hr&&y>Hr){const t=Math.ceil(y/Hr),r=Math.ceil(y/t);x=new Array(r),g=new Array(r),p=new Array(r);let n=0;for(let r=0;r<y;r+=t,n++)x[n]=r%2==0?e[r>>1]:{x:a[r>>1],y:s[r>>1]},g[n]=c[r],p[n]=l[r]}else{x=new Array(y);for(let t=0;t<y;t++)x[t]=t%2==0?e[t>>1]:{x:a[t>>1],y:s[t>>1]};g=c.slice(0,y),p=l.slice(0,y)}return new ln(x,g,this.midP,p,!1,this.sizeX,this.sizeY)}fill(t,e,i){const a=3*i,s=2*e*(1+i/2),c=!1!==P.isBrush;P.isBrush=!1,c&&(P.justChanged=!0),P.blend(t);const u=l();P.ctx.save(),P.ctx.setTransform(o*u.a,o*u.b,o*u.c,o*u.d,o*(u.x+r/2),o*(u.y+n/2));const h=`rgb(${t._getRed()} ${t._getGreen()} ${t._getBlue()} / `;P.ctx.strokeStyle=h+.005*S.fill.border_strength+")",P.ctx.lineCap="round",Hr=2024*Math.max(.1,2*S.fill.bleed_strength);const f=P.ctx.getTransform(),d=Math.max(this.sizeX,this.sizeY),m=V(.15,.7);let x=this.grow();const g=this.scatter(.1).grow().scatter(.75).flipDirs();let p;for(let r=0;r<20;r++){r%4==0&&(x=x.grow()),r%2==0&&(p=[x.grow(1-.0125*r),x.grow(.7-.0125*r),x.grow(.4-.0125*r)]);for(const t of p)t.grow(999).grow(997).layer(r,d,s,h,f);g.grow(999).flipDirs().grow(997).layer(r,d,s*a,h,f),r%2==0&&x.grow(m).grow(999).layer(r,d,2*s,h,f),r%8!=0&&19!==r||(0!==a&&x.erase(3*a,e),P.blend(t,!0))}P.ctx.restore()}layer(t,e,r,n,i=null){P.ctx.lineWidth=K(t,0,24,e/25,e/30,!0),P.ctx.fillStyle=n+r+"%)",function(t,e=null){const r=P.ctx;e||(e=r.getTransform());const n=e.a,i=e.b,o=e.c,a=e.d,s=e.e,c=e.f;let l=Infinity,u=Infinity,h=-Infinity,f=-Infinity;r.beginPath();const d=t[0];let m=n*d.x+o*d.y+s,x=i*d.x+a*d.y+c;l=h=m,u=f=x,r.moveTo(d.x,d.y);for(let e=1;e<t.length;e++){const d=t[e];m=n*d.x+o*d.y+s,x=i*d.x+a*d.y+c,l=Math.min(l,m),u=Math.min(u,x),h=Math.max(h,m),f=Math.max(f,x),r.lineTo(d.x,d.y)}r.closePath();const g=function(t,e){const r=t.lineWidth||0;return r<=0?1:1+r*Math.max(Math.hypot(e.a,e.c),Math.hypot(e.b,e.d))/2}(r,e);P.markDirtyRect(P.mask,{minX:l-g,minY:u-g,maxX:h+g,maxY:f+g})}(this.v,i),P.ctx.fill(),P.ctx.stroke()}erase(t,e){P.ctx.save();const r=~~(V(80,110)*K(t,0,1,2,3.5)),n=this.sizeX/1.3,i=this.sizeY/1.3,o=1.3*Math.min(this.sizeX,this.sizeY),a=.03*o,s=.45*o,{x:c,y:l}=this.midP;P.ctx.globalCompositeOperation="destination-out";const u=(5-K(e,80,100,.3,.7,!0))*t/255;P.ctx.fillStyle=`rgb(255 0 0 / ${u})`,P.ctx.lineWidth=0;for(let t=0;t<r;t++){const e=c+j(0,n),r=l+j(0,i),o=V(a,s);P.ctx.beginPath(),Gr(e,r,o),t%5!=0&&P.ctx.fill()}P.ctx.globalCompositeOperation="source-over",P.ctx.restore()}}function un(t,e){if(!t)return t;e||(e=t);let r,n=t;do{if(r=!1,n.steiner||!bn(n,n.next)&&0!==vn(n.prev,n,n.next))n=n.next;else{if(Sn(n),n=e=n.prev,n===n.next)break;r=!0}}while(r||n!==e);return e}function hn(t,e,r,n,i,o,a){if(!t)return;!a&&o&&function(t,e,r,n){let i=t;do{0===i.z&&(i.z=gn(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){let e,r=1;do{let n,i=t;t=null;let o=null;for(e=0;i;){e++;let a=i,s=0;for(let t=0;t<r&&(s++,a=a.nextZ,a);t++);let c=r;for(;s>0||c>0&&a;)0!==s&&(0===c||!a||i.z<=a.z)?(n=i,i=i.nextZ,s--):(n=a,a=a.nextZ,c--),o?o.nextZ=n:t=n,n.prevZ=o,o=n;i=a}o.nextZ=null,r*=2}while(e>1)}(i)}(t,n,i,o);let s=t;for(;t.prev!==t.next;){const c=t.prev,l=t.next;if(o?dn(t,n,i,o):fn(t))e.push(c.i,t.i,l.i),Sn(t),t=l.next,s=l.next;else if((t=l)===s){a?1===a?hn(t=mn(un(t),e),e,r,n,i,o,2):2===a&&xn(t,e,r,n,i,o):hn(un(t),e,r,n,i,o,1);break}}}function fn(t){const e=t.prev,r=t,n=t.next;if(vn(e,r,n)>=0)return!1;const i=e.x,o=r.x,a=n.x,s=e.y,c=r.y,l=n.y,u=Math.min(i,o,a),h=Math.min(s,c,l),f=Math.max(i,o,a),d=Math.max(s,c,l);let m=n.next;for(;m!==e;){if(m.x>=u&&m.x<=f&&m.y>=h&&m.y<=d&&pn(i,s,o,c,a,l,m.x,m.y)&&vn(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function dn(t,e,r,n){const i=t.prev,o=t,a=t.next;if(vn(i,o,a)>=0)return!1;const s=i.x,c=o.x,l=a.x,u=i.y,h=o.y,f=a.y,d=Math.min(s,c,l),m=Math.min(u,h,f),x=Math.max(s,c,l),g=Math.max(u,h,f),p=gn(d,m,e,r,n),y=gn(x,g,e,r,n);let v=t.prevZ,b=t.nextZ;for(;v&&v.z>=p&&b&&b.z<=y;){if(v.x>=d&&v.x<=x&&v.y>=m&&v.y<=g&&v!==i&&v!==a&&pn(s,u,c,h,l,f,v.x,v.y)&&vn(v.prev,v,v.next)>=0)return!1;if(v=v.prevZ,b.x>=d&&b.x<=x&&b.y>=m&&b.y<=g&&b!==i&&b!==a&&pn(s,u,c,h,l,f,b.x,b.y)&&vn(b.prev,b,b.next)>=0)return!1;b=b.nextZ}for(;v&&v.z>=p;){if(v.x>=d&&v.x<=x&&v.y>=m&&v.y<=g&&v!==i&&v!==a&&pn(s,u,c,h,l,f,v.x,v.y)&&vn(v.prev,v,v.next)>=0)return!1;v=v.prevZ}for(;b&&b.z<=y;){if(b.x>=d&&b.x<=x&&b.y>=m&&b.y<=g&&b!==i&&b!==a&&pn(s,u,c,h,l,f,b.x,b.y)&&vn(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function mn(t,e){let r=t;do{const n=r.prev,i=r.next.next;!bn(n,i)&&_n(n,r,r.next,i)&&En(n,i)&&En(i,n)&&(e.push(n.i,r.i,i.i),Sn(r),Sn(r.next),r=t=i),r=r.next}while(r!==t);return un(r)}function xn(t,e,r,n,i,o){let a=t;do{let t=a.next.next;for(;t!==a.prev;){if(a.i!==t.i&&yn(a,t)){let s=An(a,t);return a=un(a,a.next),s=un(s,s.next),hn(a,e,r,n,i,o,0),void hn(s,e,r,n,i,o,0)}t=t.next}a=a.next}while(a!==t)}function gn(t,e,r,n,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function pn(t,e,r,n,i,o,a,s){return!(t===a&&e===s)&&function(t,e,r,n,i,o,a,s){return(i-a)*(e-s)>=(t-a)*(o-s)&&(t-a)*(n-s)>=(r-a)*(e-s)&&(r-a)*(o-s)>=(i-a)*(n-s)}(t,e,r,n,i,o,a,s)}function yn(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&_n(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}(t,e)&&(En(t,e)&&En(e,t)&&function(t,e){let r=t,n=!1;const i=(t.x+e.x)/2,o=(t.y+e.y)/2;do{r.y>o!=r.next.y>o&&r.next.y!==r.y&&i<(r.next.x-r.x)*(o-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}(t,e)&&(vn(t.prev,t,e.prev)||vn(t,e.prev,e))||bn(t,e)&&vn(t.prev,t,t.next)>0&&vn(e.prev,e,e.next)>0)}function vn(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function bn(t,e){return t.x===e.x&&t.y===e.y}function _n(t,e,r,n){const i=wn(vn(t,e,r)),o=wn(vn(t,e,n)),a=wn(vn(r,n,t)),s=wn(vn(r,n,e));return i!==o&&a!==s||!(0!==i||!Rn(t,r,e))||!(0!==o||!Rn(t,n,e))||!(0!==a||!Rn(r,t,n))||!(0!==s||!Rn(r,e,n))}function Rn(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function wn(t){return t>0?1:t<0?-1:0}function En(t,e){return vn(t.prev,t,t.next)<0?vn(t,e,t.next)>=0&&vn(t,t.prev,e)>=0:vn(t,e,t.prev)<0||vn(t,t.next,e)<0}function An(t,e){const r=Tn(t.i,t.x,t.y),n=Tn(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,o.next=n,n.prev=o,n}function Mn(t,e,r,n){const i=Tn(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Sn(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function Tn(t,e,r){return{i:t,x:e,y:r,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}qt.prototype.fill=function(t=!1,e,r,n,i,o){let a=Kr();t&&(Jr(t,e),Qr(r,o),tn(n,i)),a.isActive&&(dt(),function(t){if(!S.fill.isActive||!S.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");en=t,rn=Infinity,nn=Infinity,on=-Infinity,an=-Infinity;for(const[e]of t.sides)e.x<rn&&(rn=e.x),e.x>on&&(on=e.x),e.y<nn&&(nn=e.y),e.y>an&&(an=e.y);const e=[...t.vertices],r=V(0,75),n=~~(.25*e.length*(r<5?1:r<15?2:3)),i=S.fill.bleed_strength,o=e.map((t,e)=>(e>n?1:.3)*V(.85,1.4)*i),a=$(0,e.length),s=e.length,c=new Array(s);for(let t=0;t<s;t++)c[t]=e[(t+a)%s];const l=function(t){if(0===t.length)return{x:0,y:0};if(t.length<8){let e=0,r=0;for(const n of t)e+=n.x,r+=n.y;return{x:e/t.length,y:r/t.length}}const e=[...t];e[0].x===e[e.length-1].x&&e[0].y===e[e.length-1].y||e.push(e[0]);let r=0,n=0,i=0;for(let t=0;t<e.length-1;t++){const o=e[t].x*e[t+1].y-e[t+1].x*e[t].y;r+=o,n+=(e[t].x+e[t+1].x)*o,i+=(e[t].y+e[t+1].y)*o}return r*=.5,r?{x:n/(6*r),y:i/(6*r)}:{x:e[0].x,y:e[0].y}}(c);new ln(c,o,l,[],!0).fill(S.fill.color,K(S.fill.opacity,0,255,0,1,!0),S.fill.texture_strength)}(this)),(t=>{S.fill={...t}})(a)},jt.prototype.fill=function(t,e,r){Kr().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,S.fill.bleed_strength<.06?0:K(S.fill.bleed_strength,0,.6,.2,.6,!0)),this.pol.fill())};let Pn=null,Cn=null,Fn=null,kn=null,In=null,Dn=0,Ln=0,Nn=0;const Bn={},Un={};function Yn(t,e,r,n){f(),S.wash.opacity=(arguments.length<4?e:n)??150,S.wash.color=arguments.length<3?c(t):c(t,e,r),S.wash.isActive=!0}function zn(t,e){const r=l();return[r.a*t+r.c*e+r.x+Dn/2,r.b*t+r.d*e+r.y+Ln/2]}function On(t,e,r){const n=e.isEnabled(e.DEPTH_TEST);return n&&e.disable(e.DEPTH_TEST),e.bindFramebuffer(e.FRAMEBUFFER,r.framebuffer),e.viewport(0,0,r.width*r.density,r.height*r.density),{hadDepthTest:n}}function Xn(t,e,i){i?.hadDepthTest&&e.enable(e.DEPTH_TEST),e.bindFramebuffer(e.FRAMEBUFFER,null),e.viewport(0,0,Math.max(1,Math.round(r*o)),Math.max(1,Math.round(n*o)))}function Gn(t,e){e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,null),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA)}function Zn(t,e,r){if(!e)return;if(r(e)){const r=t.drawingContext,n=r.getParameter(r.FRAMEBUFFER_BINDING),i=r.getParameter(r.VIEWPORT);return r.bindFramebuffer(r.FRAMEBUFFER,e.framebuffer),r.viewport(0,0,e.width*e.density,e.height*e.density),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.bindFramebuffer(r.FRAMEBUFFER,n),void r.viewport(i[0],i[1],i[2],i[3])}const n=e.drawingContext;n.save(),n.setTransform(1,0,0,1,0,0),n.clearRect(0,0,e.width,e.height),n.restore()}function Vn(t,e,r){return t.shaderProgram??=function(t,e,r){const n=oe(t,e,r),i=new Map,o=t.createVertexArray(),a=t.getUniformLocation(n,"u_source"),s=t.getUniformLocation(n,"u_mask"),c=t.getUniformLocation(n,"u_color");return{program:n,quadVao:o,loc_source:a,loc_mask:s,loc_color:c,setUniform(e,r){const o=(e=>(i.has(e)||i.set(e,t.getUniformLocation(n,e)),i.get(e)))(e);o&&("boolean"!=typeof r?"number"!=typeof r?Array.isArray(r)&&(3===r.length?t.uniform3f(o,r[0],r[1],r[2]):4===r.length&&t.uniform4f(o,r[0],r[1],r[2],r[3])):t.uniform1f(o,r):t.uniform1i(o,r?1:0))}}}(t.drawingContext,e,r),t.shaderProgram}function Hn(t,e){const r=t.drawingContext,n=e.density??1,i=r.createFramebuffer(),o=Math.max(1,e.width),a=Math.max(1,e.height),s=Math.max(1,Math.round(o*n)),c=Math.max(1,Math.round(a*n)),l=function(t,e,r){const n=t.createTexture();return t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,r,0,t.RGBA,t.UNSIGNED_BYTE,null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.bindTexture(t.TEXTURE_2D,null),n}(r,s,c);return r.bindFramebuffer(r.FRAMEBUFFER,i),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,l,0),r.bindFramebuffer(r.FRAMEBUFFER,null),{__brushFramebuffer:!0,framebuffer:i,colorTexture:l,width:o,height:a,density:n,pixelDensity:()=>n,remove(){r.deleteFramebuffer(i),r.deleteTexture(l)}}}function Wn(t,e,r,n,i){return e?.remove?.(),Hn(t,{width:r,height:n,density:i})}function $n({renderer:t,shader:e,source:r,mask:n,color:i,isBrushMask:o,dirtyRect:a,targetIsFramebuffer:s,withScissor:c}){const l=t.drawingContext,u=l.isEnabled(l.DEPTH_TEST),h=l.getParameter(l.FRAMEBUFFER_BINDING),f=l.getParameter(l.CURRENT_PROGRAM),d=l.getParameter(l.VERTEX_ARRAY_BINDING);l.bindVertexArray(e.quadVao),l.useProgram(e.program),l.disable(l.DEPTH_TEST),l.enable(l.BLEND),l.blendEquation(l.FUNC_ADD),l.blendFunc(l.ONE,l.ONE_MINUS_SRC_ALPHA),l.activeTexture(l.TEXTURE0),l.bindTexture(l.TEXTURE_2D,r.colorTexture),l.uniform1i(e.loc_source,0),l.activeTexture(l.TEXTURE1),l.bindTexture(l.TEXTURE_2D,n.colorTexture),l.uniform1i(e.loc_mask,1),e.setUniform("u_targetIsFramebuffer",s),e.setUniform("u_isBrush",o),l.uniform3f(e.loc_color,i[0],i[1],i[2]),l.bindFramebuffer(l.FRAMEBUFFER,null),c(l,a,()=>{l.drawArrays(l.TRIANGLES,0,3)},!s),l.bindTexture(l.TEXTURE_2D,null),l.activeTexture(l.TEXTURE0),l.bindVertexArray(d),l.useProgram(f),l.bindFramebuffer(l.FRAMEBUFFER,h),u&&l.enable(l.DEPTH_TEST)}function qn(t){return function({renderer:t,sourceFramebuffer:e,dirtyRect:r,getTargetPixelSize:n,toScissorBox:i}){const o=t.drawingContext,{width:a,height:s}=n(),c=r?i(r):null,l=o.getParameter(o.READ_FRAMEBUFFER_BINDING),u=o.getParameter(o.DRAW_FRAMEBUFFER_BINDING);return o.bindFramebuffer(o.READ_FRAMEBUFFER,null),o.bindFramebuffer(o.DRAW_FRAMEBUFFER,e.framebuffer),o.blitFramebuffer(c?.x??0,c?.y??0,c?c.x+c.width:a,c?c.y+c.height:s,c?.x??0,c?.y??0,c?c.x+c.width:a,c?c.y+c.height:s,o.COLOR_BUFFER_BIT,o.NEAREST),o.bindFramebuffer(o.READ_FRAMEBUFFER,l),o.bindFramebuffer(o.DRAW_FRAMEBUFFER,u),e}(t)}function jn(t){if("number"==typeof t){const e=Math.max(0,Math.min(255,t));return`rgb(${e} ${e} ${e})`}return t??"black"}function Kn(t){const e=((t,e=!1)=>(t.drawingContext??=t.getContext("2d",e?{willReadFrequently:!0}:void 0),t.drawingContext))(t,!0),r={canvas:t,drawingContext:e,width:t.width,height:t.height,pixels:null,_fillStyle:"#ffffff",_strokeStyle:"transparent",_lineWidth:1,pixelDensity:()=>1,background(r){e.save(),e.setTransform(1,0,0,1,0,0),e.fillStyle=jn(r),e.fillRect(0,0,t.width,t.height),e.restore()},noSmooth(){e.imageSmoothingEnabled=!1},push(){e.save()},pop(){e.restore()},translate(t,r){e.translate(t,r)},scale(t,r=t){e.scale(t,r)},rotate(t){e.rotate(t)},noStroke(){r._strokeStyle="transparent"},stroke(t){r._strokeStyle=jn(t)},noFill(){r._fillStyle="transparent"},fill(t){r._fillStyle=jn(t)},strokeWeight(t){r._lineWidth=t},rect(t,n,i,o){e.beginPath(),e.rect(t,n,i,o),r._paint()},circle(t,n,i){e.beginPath(),e.arc(t,n,i/2,0,2*Math.PI),r._paint()},ellipse(t,n,i,o){e.beginPath(),e.ellipse(t,n,i/2,o/2,0,0,2*Math.PI),r._paint()},line(t,n,i,o){e.beginPath(),e.moveTo(t,n),e.lineTo(i,o),e.strokeStyle=r._strokeStyle,e.lineWidth=r._lineWidth,e.stroke()},beginShape(){e.beginPath(),r._shapeStarted=!1},vertex(t,n){r._shapeStarted?e.lineTo(t,n):(e.moveTo(t,n),r._shapeStarted=!0)},endShape(t=!1){t&&e.closePath(),r._paint()},loadPixels(){r.pixels=e.getImageData(0,0,t.width,t.height).data},updatePixels(){const n=e.getImageData(0,0,t.width,t.height);n.data.set(r.pixels),e.putImageData(n,0,0)},_paint(){"transparent"!==r._fillStyle&&(e.fillStyle=r._fillStyle,e.fill()),"transparent"!==r._strokeStyle&&(e.strokeStyle=r._strokeStyle,e.lineWidth=r._lineWidth,e.stroke())}};return r}function Jn(t,e){return Kn(g(t,e,!0))}function Qn(t,e){return new Promise((r,n)=>{const i=globalThis.Image;if(!i)return void n(new Error("Standalone image brush loading requires Image support."));const o=new i;o.onload=()=>{const t=Kn(g(o.naturalWidth,o.naturalHeight,!0));t.drawingContext.drawImage(o,0,0),e(t),r(t)},o.onerror=()=>n(new Error(`Failed to load image tip: ${t}`)),o.crossOrigin="anonymous",o.src=t})}var ti;S.wash={color:null,opacity:150,isActive:!1},qt.prototype.wash=function(t=!1,e){const o={...S.wash};!1!==t&&Yn(t,e),S.wash.isActive&&function(t){if(!S.wash?.isActive||!S.wash.color||t.vertices.length<3)return;C(),function(){const t=i.drawingContext;In&&!(Dn!==r||Ln!==n)||(Dn=r,Ln=n,In=new Float32Array([2/Dn,0,0,0,0,-2/Ln,0,0,0,0,1,0,-1,1,0,1])),Pn===t&&Cn&&Fn&&kn||(Pn=t,Cn=oe(Pn,"#version 300 es\nin vec2 a_position;\nuniform mat4 u_matrix;\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n}","#version 300 es\nprecision highp float;\nuniform vec4 u_color;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(u_color.rgb * u_color.a, u_color.a);\n}"),Bn.a_position=Pn.getAttribLocation(Cn,"a_position"),Un.u_matrix=Pn.getUniformLocation(Cn,"u_matrix"),Un.u_color=Pn.getUniformLocation(Cn,"u_color"),Fn=Pn.createVertexArray(),Pn.bindVertexArray(Fn),kn=Pn.createBuffer(),Pn.bindBuffer(Pn.ARRAY_BUFFER,kn),Pn.bufferData(Pn.ARRAY_BUFFER,0,Pn.DYNAMIC_DRAW),Nn=0,Pn.enableVertexAttribArray(Bn.a_position),Pn.vertexAttribPointer(Bn.a_position,2,Pn.FLOAT,!1,8,0),Pn.bindVertexArray(null),Pn.bindBuffer(Pn.ARRAY_BUFFER,null))}();const{triangles:e,vertexCount:o}=function(t){const e=new Float32Array(2*t.vertices.length);for(let r=0;r<t.vertices.length;r++){const n=t.vertices[r];e[2*r]=n.x,e[2*r+1]=n.y}const r=function(t,e,r=2){const n=t.length;let i=function(t,e,r,n){let i;if(1==function(t,e,r,n){let i=0;for(let e=0,o=r-n;e<r;e+=n)i+=(t[o]-t[e])*(t[e+1]+t[o+1]),o=e;return i}(t,0,r,n)>0)for(let e=0;e<r;e+=n)i=Mn(e/n|0,t[e],t[e+1],i);else for(let e=r-n;e>=0;e-=n)i=Mn(e/n|0,t[e],t[e+1],i);return i&&bn(i,i.next)&&(Sn(i),i=i.next),i}(t,0,n,r);const o=[];if(!i||i.next===i.prev)return o;let a,s,c;if(t.length>80*r){a=t[0],s=t[1];let e=a,i=s;for(let o=r;o<n;o+=r){const r=t[o],n=t[o+1];r<a&&(a=r),n<s&&(s=n),r>e&&(e=r),n>i&&(i=n)}c=Math.max(e-a,i-s),c=0!==c?32767/c:0}return hn(i,o,r,a,s,c,0),o}(e),n=new Float32Array(2*r.length);for(let t=0;t<r.length;t++){const i=r[t],[o,a]=zn(e[2*i],e[2*i+1]);n[2*t]=o,n[2*t+1]=a}return{triangles:n,vertexCount:r.length}}(t),a=e.byteLength;Pn.useProgram(Cn),Pn.enable(Pn.BLEND),Pn.blendEquation(Pn.FUNC_ADD),Pn.blendFunc(Pn.ONE,Pn.ONE_MINUS_SRC_ALPHA),Pn.bindVertexArray(Fn),Pn.bindBuffer(Pn.ARRAY_BUFFER,kn),a>Nn?(Pn.bufferData(Pn.ARRAY_BUFFER,e,Pn.DYNAMIC_DRAW),Nn=a):Pn.bufferSubData(Pn.ARRAY_BUFFER,0,e);const s=S.wash.color._array;Pn.uniformMatrix4fv(Un.u_matrix,!1,In),Pn.uniform4f(Un.u_color,s[0],s[1],s[2],S.wash.opacity/255),Pn.drawArrays(Pn.TRIANGLES,0,o),Pn.bindVertexArray(null),Pn.bindBuffer(Pn.ARRAY_BUFFER,null),se(i,Pn)}(this),S.wash={...o}},jt.prototype.wash=function(t,e,r){S.wash?.isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,0,-1),this.pol.wash())},ti={load:function(t=Gt){if(!function(t){return function(t){return"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement}(t)||function(t){return"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas}(t)}(t))throw new Error("Standalone brush.load(target) requires an HTMLCanvasElement or OffscreenCanvas.");$t(t,t.width,t.height,1)},syncDensity:function(){return h({Cwidth:Ht,Cheight:Wt,Density:Vt}),Vt},isCanvasReady:function(){if(!Zt)throw new Error("No standalone target loaded. Call brush.load(canvasOrOffscreenCanvas) first.")},instance:function(){},activateInstance:function(){},deactivateInstance:function(){},getActiveFramebuffer:function(){return null},isFramebufferTarget:function(){return!0===arguments[0]?.__brushFramebuffer}},u={...u,...ti},Ut(),function(){var t;t={beginDirectMaskDraw:On,endDirectMaskDraw:Xn,resetDirectShaderTracking:Gn},ae={...ae,...t}}(),function(){var t;t={clearTarget:Zn,ensureBlendShaderProgram:Vn,ensureBlendSourceFramebuffer:Wn,createFramebuffer:Hn,runBlendShaderPass:$n,blitSourceToFramebuffer:qn},p={...p,...t}}(),function(){var t;t={createTipSurface:Jn,loadImageTip:Qn},ne={...ne,...t}}(),t.Color=Bt,t.DEGREES=Ct,t.Plot=jt,t.Polygon=qt,t.Position=mt,t.RADIANS=Ft,t.add=nr,t.addField=At,t.angleMode=function(t){if(t!==Ct&&t!==Ft)throw new Error(`Invalid angle mode "${t}". Use "degrees" or "radians".`);It=t},t.arc=Kt,t.beginShape=Qt,t.beginStroke=function(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);Xt=[e,r],Ot=new jt(t)},t.box=function(){return[...Qe.keys()]},t.circle=function(t,e,r,n=!1){const i=new jt("curve"),o=Math.PI*r,a=H(0,360),s=n?()=>1+.2*n*H():()=>1;for(let t=0;t<4;t++){const e=-90*t+a;i.addSegment(e*s(),o/2*s(),1,!0)}if(n){const t=n*q(-5,5);i.addSegment(a,Math.abs(t)*(Math.PI/180)*r,1,!0),i.endPlot(t+a,1,!0)}else i.endPlot(a,1,!0);const c=t-r*ot(a),l=e-r*it(-a);i.show(c,l,1)},t.clear=function(...t){f(),P.glMask&&P.clearMask(P.glMask),P.mask&&P.clearMask(P.mask),P.justChanged=!1,P.isBlending=!1,P.isBrush=null,P.cachedColor=null;const e=i.drawingContext,r=0===t.length?[1,1,1,0]:[...c(...t)._array.slice(0,3),1];e.bindFramebuffer(e.FRAMEBUFFER,null),e.disable(e.SCISSOR_TEST),e.clearColor(r[0],r[1],r[2],r[3]),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)},t.clip=function(t){return f(),t},t.createCanvas=function(t,e,r={}){if("undefined"==typeof document)throw new Error("brush.createCanvas() requires a browser document.");const n=Math.max(1,Math.round(t)),i=Math.max(1,Math.round(e)),o=Math.max(1,Number(r.pixelDensity)||1),a=document.createElement("canvas");if(a.width=Math.max(1,Math.round(n*o)),a.height=Math.max(1,Math.round(i*o)),a.style.width=`${n}px`,a.style.height=`${i}px`,r.id&&(a.id=r.id),r.parent){const t="string"==typeof r.parent?document.querySelector(r.parent):r.parent;if(!t)throw new Error(`Could not find parent "${r.parent}" for brush.createCanvas().`);t.appendChild(a)}return $t(a,n,i,o),a},t.endShape=ee,t.endStroke=function(t,e){if(!Ot)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");Ot.endPlot(t,e),Ot.draw(Xt[0],Xt[1],1),Ot=!1},t.field=Et,t.fill=Jr,t.fillBleed=Qr,t.fillTexture=tn,t.flowLine=function(t,e,r,n){if(!S.stroke.isActive||!S.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");dt(),xr(t,e,r),pr(at(n),!1)},t.getAngleMode=function(){return It},t.hatch=kr,t.hatchArray=Lr,t.hatchStyle=function(t,e="black",r=1){S.hatch.hBrush={brush:t,color:e,weight:r}},t.initStandaloneRuntime=Ut,t.instance=t=>u.instance(t),t.line=Mr,t.listFields=function(){return dt(),Array.from(bt.keys())},t.load=(t=!1)=>{((t=!1)=>{u.load(t)})(t),i.loaded&&P.load()},t.mass=function(t,e,r={}){S.mass.brush=t,S.mass.color=e,S.mass.options=r,S.mass.isActive=!0},t.move=function(t,e,r){if(!Ot)throw new Error("move() called without beginStroke(). Call beginStroke() first.");Ot.addSegment(t,e,r)},t.noClip=function(){},t.noField=function(){dt(),S.field.isActive=!1},t.noFill=function(){S.fill.isActive=!1},t.noHatch=function(){S.hatch.isActive=!1,S.hatch.hBrush=!1},t.noMass=function(){S.mass.isActive=!1,S.mass.brush=null,S.mass.color=null,S.mass.options={}},t.noStroke=function(){S.stroke.isActive=!1},t.noWash=function(){S.wash.isActive=!1},t.noiseSeed=t=>{G=N(B(t)),Z=N(B(`${t}:2`))},t.pick=or,t.polygon=function(t){new qt(t).show()},t.pop=function(){0!==Dt.length&&(Lt=Dt.pop(),function(){const t=Tt.pop();t&&(S.stroke={...t.stroke},S.field={...t.field},S.hatch={...t.hatch},S.fill={...t.fill},t.wash&&(S.wash={...t.wash}),t.mass?S.mass={...t.mass}:S.mass&&(S.mass={...S.mass,isActive:!1,brush:null,color:null,options:{}}))}())},t.push=function(){dt(),Tt.push({fill:{...S.fill},wash:S.wash?{...S.wash}:null,stroke:{...S.stroke},hatch:{...S.hatch},mass:S.mass?{...S.mass}:null,field:{...S.field}}),Dt.push({...Lt})},t.rect=function(t,e,r,n,i="corner"){"center"===i&&(t-=r/2,e-=n/2),Qt(0),te(t,e),te(t+r,e),te(t+r,e+n),te(t,e+n),ee(!0)},t.refreshField=function(t=0){if(!S.field.isActive||!S.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=bt.get(S.field.current);e.field=wt(e,t)},t.render=function(){C()},t.rotate=function(t){const e=It===Ft?t:t*Math.PI/180,r=Math.cos(e),n=Math.sin(e);Lt=Nt(Lt,{a:r,b:n,c:-n,d:r,x:0,y:0})},t.scale=function(t,e=t){Lt=Nt(Lt,{a:t,b:0,c:0,d:e,x:0,y:0})},t.scaleBrushes=function(t){for(const{param:e}of Qe.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)},t.seed=t=>{Y=B(t),z=B(`${t}:2`);for(const t of O)t()},t.set=cr,t.spline=function(t,e=.5){if(!t||t.length<2)throw new Error("spline() requires at least 2 points. Each point should be [x, y, pressure].");re(t,e).draw()},t.stroke=ar,t.strokeWeight=sr,t.translate=function(t,e){Lt=Nt(Lt,{a:1,b:0,c:0,d:1,x:t,y:e})},t.vertex=te,t.wRand=t=>{let e=0;const r=[];for(const n in t)e+=t[n],r.push({key:n,cumulative:e});const n=Y()*e;for(const{key:t,cumulative:e}of r)if(n<e)return isNaN(t)?t:parseInt(t)},t.wash=Yn,t.wiggle=Mt},"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).brush={});
//# sourceMappingURL=brush.js.map
diff --git a/dist/brush.js.map b/dist/brush.js.map
index fecb923..afe8269 100644
--- a/dist/brush.js.map
+++ b/dist/brush.js.map
@@ -1 +1 @@
-{"version":3,"file":"brush.js","sources":["../src/core/runtime.js","../src/core/target.js","../src/core/dirty_rect.js","../src/core/compositor_runtime.js","../src/core/color.js","../node_modules/simplex-noise/dist/esm/simplex-noise.js","../node_modules/esm-seedrandom/esm/index.mjs","../src/core/utils.js","../src/core/flowfield.js","../src/core/save.js","../src/adapters/standalone/runtime.js","../src/adapters/standalone/target.js","../src/core/primitives.js","../src/core/polygon.js","../src/core/plot.js","../src/stroke/runtime.js","../src/stroke/composite.js","../src/core/gl/utils.js","../src/core/renderer_runtime.js","../src/stroke/gl_draw.js","../src/stroke/stroke.js","../src/hatch/hatch.js","../src/hatch/mass.js","../src/fill/mask.js","../src/fill/composite.js","../src/fill/fill.js","../node_modules/earcut/src/earcut.js","../src/fill/wash.js","../src/adapters/standalone/renderer.js","../src/adapters/standalone/compositor.js","../src/adapters/standalone/stroke.js","../src/index.standalone.js","../src/adapters/standalone/frame.js"],"sourcesContent":["// =============================================================================\n// Runtime Hooks\n// =============================================================================\n\nconst identityMatrix = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\n\nexport let usesRadians = () => false;\nexport let fromDegrees = (angle) => angle;\nexport let createColor = () => {\n throw new Error(\"No runtime color adapter registered.\");\n};\nexport let getAffineMatrix = () => identityMatrix;\n\n/**\n * Registers or updates host-runtime hooks used by core modules.\n *\n * @param {object} hooks\n */\nexport function setRuntime(hooks) {\n if (hooks.usesRadians) usesRadians = hooks.usesRadians;\n if (hooks.fromDegrees) fromDegrees = hooks.fromDegrees;\n if (hooks.createColor) createColor = hooks.createColor;\n if (hooks.getAffineMatrix) getAffineMatrix = hooks.getAffineMatrix;\n}\n","// =============================================================================\n// Target Runtime Hooks\n// =============================================================================\n\n/**\n * Shared target state exposed to core modules.\n *\n * Host adapters are expected to keep these bindings updated with the currently\n * active drawing target. The exact object type is adapter-defined, but core code\n * assumes the active renderer exposes:\n * - `drawingContext`: the active WebGL context\n * - target dimensions through `Cwidth` / `Cheight`\n * - pixel density through `Density`\n */\n\nexport let Cwidth, Cheight, Instance, Renderer, Density;\n\nlet targetRuntime = {\n load: () => {\n throw new Error(\"No target runtime adapter registered.\");\n },\n syncDensity: () => Density,\n isCanvasReady: () => {\n throw new Error(\"No target runtime adapter registered.\");\n },\n instance: (inst) => {\n Instance = inst;\n },\n activateInstance: (inst) => {\n Instance = inst;\n },\n deactivateInstance: () => {},\n getActiveFramebuffer: () => null,\n isFramebufferTarget: () => false,\n};\n\n/**\n * Updates the shared target state consumed by core modules.\n *\n * @param {object} state\n */\nexport function setTargetState(state) {\n if (\"Cwidth\" in state) Cwidth = state.Cwidth;\n if (\"Cheight\" in state) Cheight = state.Cheight;\n if (\"Instance\" in state) Instance = state.Instance;\n if (\"Renderer\" in state) Renderer = state.Renderer;\n if (\"Density\" in state) Density = state.Density;\n}\n\n/**\n * Registers or updates host target hooks used by core modules.\n *\n * @param {object} hooks\n */\nexport function setTargetRuntime(hooks) {\n targetRuntime = { ...targetRuntime, ...hooks };\n}\n\nexport const load = (buffer = false) => targetRuntime.load(buffer);\nexport const syncDensity = () => targetRuntime.syncDensity();\nexport const isCanvasReady = () => targetRuntime.isCanvasReady();\nexport const instance = (inst) => targetRuntime.instance(inst);\nexport const activateInstance = (inst) => targetRuntime.activateInstance(inst);\nexport const deactivateInstance = () => targetRuntime.deactivateInstance();\nexport const getActiveFramebuffer = () => targetRuntime.getActiveFramebuffer();\nexport const isFramebufferTarget = (target) =>\n targetRuntime.isFramebufferTarget(target);\n","// =============================================================================\n// Module: Dirty Rect Utilities\n// =============================================================================\n/**\n * Expands a dirty rectangle outward by a constant padding value.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Rect to expand.\n * @param {number} [padding=0] - Padding in pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Expanded rect.\n */\nexport const expandDirtyRect = (rect, padding = 0) =>\n rect\n ? {\n minX: rect.minX - padding,\n minY: rect.minY - padding,\n maxX: rect.maxX + padding,\n maxY: rect.maxY + padding,\n }\n : null;\n\n/**\n * Clamps a dirty rectangle to explicit target bounds.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Candidate rect.\n * @param {number} width - Target width in physical pixels.\n * @param {number} height - Target height in physical pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Clamped rect.\n */\nexport const normalizeDirtyRect = (rect, width, height) => {\n if (!rect) return null;\n\n const minX = Math.max(0, Math.floor(Math.min(rect.minX, rect.maxX)));\n const minY = Math.max(0, Math.floor(Math.min(rect.minY, rect.maxY)));\n const maxX = Math.min(width, Math.ceil(Math.max(rect.minX, rect.maxX)));\n const maxY = Math.min(height, Math.ceil(Math.max(rect.minY, rect.maxY)));\n\n if (maxX <= minX || maxY <= minY) return null;\n\n return { minX, minY, maxX, maxY };\n};\n\n/**\n * Returns the union of two dirty rectangles.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} a - First rect.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} b - Second rect.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Union rect.\n */\nexport const unionDirtyRect = (a, b) => {\n if (!a) return b;\n if (!b) return a;\n\n return {\n minX: Math.min(a.minX, b.minX),\n minY: Math.min(a.minY, b.minY),\n maxX: Math.max(a.maxX, b.maxX),\n maxY: Math.max(a.maxY, b.maxY),\n };\n};\n\n/**\n * Returns a dirty rectangle covering the full target bounds.\n *\n * @param {number} width - Target width in physical pixels.\n * @param {number} height - Target height in physical pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}} Full-target rect.\n */\nexport const getFullDirtyRect = (width, height) => ({\n minX: 0,\n minY: 0,\n maxX: width,\n maxY: height,\n});\n","// =============================================================================\n// Compositor Runtime Hooks\n// =============================================================================\n\n/**\n * Shared compositor helpers and host hooks.\n *\n * The shared code in this module assumes framebuffer-like targets expose:\n * - `framebuffer`: native WebGL framebuffer handle\n * - optional lifecycle methods supplied by the host adapter\n *\n * Higher-level core modules also attach their own bookkeeping fields onto the\n * active renderer and mask targets, such as:\n * - `shaderProgram`\n * - `blendSourceFramebuffer`\n * - `glMask`\n * - `fillMaskFramebuffer`\n * - `mask`\n *\n * These are library-level contract fields, not host-specific internals.\n */\n\nexport const create2DCanvas = (width, height, willReadFrequently = false) => {\n const canvas =\n typeof OffscreenCanvas !== \"undefined\"\n ? new OffscreenCanvas(width, height)\n : (() => {\n const element = document.createElement(\"canvas\");\n element.width = width;\n element.height = height;\n return element;\n })();\n canvas.drawingContext = canvas.getContext(\n \"2d\",\n willReadFrequently ? { willReadFrequently: true } : undefined,\n );\n return canvas;\n};\n\nexport const get2DContext = (canvas, willReadFrequently = false) => {\n canvas.drawingContext ??= canvas.getContext(\n \"2d\",\n willReadFrequently ? { willReadFrequently: true } : undefined,\n );\n return canvas.drawingContext;\n};\n\nexport function blitDefaultFramebufferSource({\n renderer,\n sourceFramebuffer,\n dirtyRect,\n getTargetPixelSize,\n toScissorBox,\n}) {\n const gl = renderer.drawingContext;\n const { width, height } = getTargetPixelSize();\n const sourceBox = dirtyRect ? toScissorBox(dirtyRect) : null;\n const previousReadFramebuffer = gl.getParameter(gl.READ_FRAMEBUFFER_BINDING);\n const previousDrawFramebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING);\n\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, sourceFramebuffer.framebuffer);\n gl.clearColor(0, 0, 0, 0);\n gl.clear(gl.COLOR_BUFFER_BIT);\n gl.blitFramebuffer(\n sourceBox?.x ?? 0,\n sourceBox?.y ?? 0,\n sourceBox ? sourceBox.x + sourceBox.width : width,\n sourceBox ? sourceBox.y + sourceBox.height : height,\n sourceBox?.x ?? 0,\n sourceBox?.y ?? 0,\n sourceBox ? sourceBox.x + sourceBox.width : width,\n sourceBox ? sourceBox.y + sourceBox.height : height,\n gl.COLOR_BUFFER_BIT,\n gl.NEAREST,\n );\n\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, previousReadFramebuffer);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, previousDrawFramebuffer);\n\n return sourceFramebuffer;\n}\n\nlet compositorRuntime = {\n clearTarget: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n ensureBlendShaderProgram: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n ensureBlendSourceFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n createFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n runBlendShaderPass: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n blitSourceToFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n};\n\n/**\n * Registers or updates host compositor hooks used by core compositing code.\n *\n * @param {object} hooks\n */\nexport function setCompositorRuntime(hooks) {\n compositorRuntime = { ...compositorRuntime, ...hooks };\n}\n\nexport const clearTarget = (...args) => compositorRuntime.clearTarget(...args);\nexport const ensureBlendShaderProgram = (...args) =>\n compositorRuntime.ensureBlendShaderProgram(...args);\nexport const ensureBlendSourceFramebuffer = (...args) =>\n compositorRuntime.ensureBlendSourceFramebuffer(...args);\nexport const createFramebuffer = (...args) =>\n compositorRuntime.createFramebuffer(...args);\nexport const runBlendShaderPass = (...args) =>\n compositorRuntime.runBlendShaderPass(...args);\nexport const blitSourceToFramebuffer = (...args) =>\n compositorRuntime.blitSourceToFramebuffer(...args);\n","import {\n Cwidth,\n Cheight,\n Renderer,\n Density,\n load as loadTarget,\n isCanvasReady,\n syncDensity,\n getActiveFramebuffer,\n isFramebufferTarget,\n} from \"./target.js\";\nimport {\n expandDirtyRect,\n normalizeDirtyRect as clampDirtyRect,\n unionDirtyRect,\n getFullDirtyRect as getFullRect,\n} from \"./dirty_rect.js\";\nimport {\n clearTarget as clearRenderTarget,\n ensureBlendShaderProgram,\n ensureBlendSourceFramebuffer,\n runBlendShaderPass,\n blitSourceToFramebuffer,\n} from \"./compositor_runtime.js\";\n\nimport vertSrc from \"./gl/shader.vert\";\nimport fragSrc from \"./gl/shader.frag\";\n\n// =============================================================================\n// Module: Configure and Initiate\n// =============================================================================\n/**\n * This module handles the configuration and initialization of the drawing system.\n * It manages canvas properties, ensures the system is ready for rendering, and\n * provides utilities for saving and restoring states.\n */\n\nlet strokeComposite = null;\nlet fillComposite = null;\n\nexport const registerStrokeComposite = (composite) => {\n strokeComposite = composite;\n};\n\nexport const registerFillComposite = (composite) => {\n fillComposite = composite;\n};\n\nconst clearTarget = (target) => {\n clearRenderTarget(Renderer, target, isFramebufferTarget);\n};\n\n// =============================================================================\n// Section: Dirty Rect Utilities\n// =============================================================================\n/**\n * Returns the current render target size in physical pixels.\n * @returns {{width: number, height: number}} Pixel size of the active target.\n */\nconst getTargetPixelSize = () => ({\n width: Math.max(1, Math.round(Cwidth * Density)),\n height: Math.max(1, Math.round(Cheight * Density)),\n});\n\nconst normalizeDirtyRect = (rect) => {\n if (!rect) return null;\n const { width, height } = getTargetPixelSize();\n return clampDirtyRect(rect, width, height);\n};\n\n/**\n * Returns a dirty rectangle covering the full active target.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}} Full-target rect.\n */\nconst getFullDirtyRect = () => {\n const { width, height } = getTargetPixelSize();\n return getFullRect(width, height);\n};\n\n// =============================================================================\n// Section: Scissor Helpers\n// =============================================================================\n/**\n * Converts a top-left-based dirty rectangle into a WebGL scissor box.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Dirty rect.\n * @returns {{x:number,y:number,width:number,height:number}|null} Scissor box or null.\n */\nconst toScissorBox = (rect, flipY = true) => {\n const normalized = normalizeDirtyRect(rect);\n if (!normalized) return null;\n\n const { height } = getTargetPixelSize();\n return {\n x: normalized.minX,\n y: flipY ? height - normalized.maxY : normalized.minY,\n width: normalized.maxX - normalized.minX,\n height: normalized.maxY - normalized.minY,\n };\n};\n\n/**\n * Runs a draw callback with a temporary scissor region.\n * @param {WebGL2RenderingContext} gl - Active WebGL context.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Dirty rect.\n * @param {Function} draw - Draw callback executed under the scissor box.\n */\nconst withScissor = (gl, rect, draw, flipY = true) => {\n const box = toScissorBox(rect, flipY);\n if (!box) {\n draw();\n return;\n }\n\n // Scissor is never nested in this module, so we can set/clear it directly\n // without saving previous GL state.\n gl.enable(gl.SCISSOR_TEST);\n gl.scissor(box.x, box.y, box.width, box.height);\n\n try {\n draw();\n } finally {\n gl.disable(gl.SCISSOR_TEST);\n }\n};\n\n/**\n * Stores the current state of the drawing system.\n * Can be used to save and restore configurations or canvas states.\n */\nexport const State = {};\n/**\n * Handles color blending using WebGL shaders. Implements advanced blending\n * effects based on Kubelka-Munk theory. Relies on spectral.js for blending logic.\n */\n\n// =============================================================================\n// Section: Color Blending / Rendering\n// =============================================================================\n/**\n * Ensures the Mix object is initialized and ready for blending.\n */\nexport const isMixReady = () => {\n if (!Renderer?.loaded) {\n isCanvasReady();\n Mix.load();\n }\n};\n\n/**\n * Manages blending operations with WebGL shaders.\n * @property {boolean} loaded - Indicates if shaders are loaded.\n * @property {boolean} isBlending - Indicates if blending is active.\n * @property {object} currentColor - Current color in WebGL format.\n * @property {function} load - Initializes blending resources.\n * @property {function} blend - Applies blending effects.\n */\nexport const Mix = {\n isBlending: false,\n cachedColor: null,\n\n /**\n * Merges a new dirty rectangle into the target's accumulated draw bounds.\n * @param {object} target - Mask buffer receiving draw output.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Rect to merge.\n */\n markDirtyRect(target, rect) {\n const normalized = normalizeDirtyRect(rect);\n if (!target || !normalized) return;\n target.dirtyRect = unionDirtyRect(target.dirtyRect, normalized);\n target.isDrawn = true;\n },\n\n /**\n * Clears a mask buffer and resets its dirty-rect tracking.\n * @param {object} target - Mask buffer to reset.\n */\n clearMask(target) {\n if (!target) return;\n const composite = target === this.glMask ? strokeComposite : fillComposite;\n composite?.clearMask?.(target, clearTarget);\n },\n\n /**\n * Resolves the region that should be composited back into the destination.\n * @param {object} target - Mask buffer being sampled.\n * @param {boolean} isBrushMask - True when compositing the GL brush mask.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\n getCompositeRect(target, isBrushMask) {\n const composite = isBrushMask ? strokeComposite : fillComposite;\n return composite?.getCompositeRect?.(\n target,\n getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n );\n },\n\n // =============================================================================\n // Section: Setup and load shaders\n // =============================================================================\n /**\n * Ensures the mask buffers and blend shader exist for the current renderer.\n */\n load() {\n syncDensity();\n const needsBlendSourceFramebuffer =\n !Renderer.blendSourceFramebuffer ||\n Renderer.blendSourceFramebuffer.width !== Cwidth ||\n Renderer.blendSourceFramebuffer.height !== Cheight ||\n (typeof Renderer.blendSourceFramebuffer.pixelDensity === \"function\" &&\n Renderer.blendSourceFramebuffer.pixelDensity() !== Density);\n ensureBlendShaderProgram(Renderer, vertSrc, fragSrc);\n\n this.glMask = strokeComposite?.ensureResources?.(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n );\n const fillResources = fillComposite?.ensureResources?.(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n clearTarget,\n ) ?? {\n mask: null,\n ctx: null,\n };\n\n if (needsBlendSourceFramebuffer) {\n Renderer.blendSourceFramebuffer = ensureBlendSourceFramebuffer(\n Renderer,\n Renderer.blendSourceFramebuffer,\n Cwidth,\n Cheight,\n Density,\n );\n }\n\n this.mask = fillResources.mask;\n this.ctx = fillResources.ctx;\n },\n\n // =============================================================================\n // Section: Compositing\n // =============================================================================\n /**\n * Flushes pending mask work when the blend color changes or a frame ends.\n * @param {Color|false} [_color=false] - New blend color.\n * @param {boolean} [_isLast=false] - True when this is the final blend flush.\n */\n blend(_color = false, _isLast = false) {\n isMixReady();\n // Only one mask is \"active\" for the current drawing mode; the other one\n // may still need flushing if the mode just changed mid-frame.\n const isBrushMask = this.isBrush === true;\n const mask = isBrushMask ? this.glMask : this.mask;\n const otherMask = isBrushMask ? this.mask : this.glMask;\n const nextColor = _color?._array;\n const colorChanged =\n !!nextColor &&\n (this.cachedColor?.[0] !== nextColor[0] ||\n this.cachedColor?.[1] !== nextColor[1] ||\n this.cachedColor?.[2] !== nextColor[2] ||\n this.cachedColor?.[3] !== nextColor[3]);\n if (!this.isBlending && nextColor) {\n this.isBlending = true;\n this.cachedColor = nextColor;\n // Reset the brush mask fully at the start of each blend cycle so stale\n // dirty-rect bookkeeping cannot leak an old stroke into the next color.\n this.clearMask(this.glMask);\n }\n\n if (_isLast || colorChanged) {\n if (this.justChanged) {\n this.applyShader(otherMask, !isBrushMask);\n this.justChanged = false;\n }\n if (this.isBlending) {\n this.applyShader(mask, isBrushMask);\n }\n if (nextColor) this.cachedColor = nextColor;\n if (_isLast) {\n this.isBlending = false;\n this.cachedColor = null;\n \n }\n }\n },\n\n /**\n * Runs the blend shader over a mask and composites the result into the active renderer.\n * @param {object} mask - Mask buffer to composite.\n * @param {boolean} isBrushMask - True when compositing the GL brush mask.\n */\n applyShader(mask, isBrushMask) {\n if (!mask?.isDrawn) return;\n\n const dirtyRect = this.getCompositeRect(mask, isBrushMask);\n if (!dirtyRect) {\n this.clearMask(mask);\n return;\n }\n\n const gl = Renderer.drawingContext;\n const shader = Renderer.shaderProgram;\n const activeFramebuffer = getActiveFramebuffer();\n const source = blitSourceToFramebuffer({\n renderer: Renderer,\n sourceTarget: activeFramebuffer ?? Renderer,\n sourceFramebuffer: Renderer.blendSourceFramebuffer,\n dirtyRect,\n isFramebufferTarget,\n Cwidth,\n Cheight,\n getTargetPixelSize,\n toScissorBox,\n withScissor,\n });\n const targetIsFramebuffer = !!activeFramebuffer;\n const composite = isBrushMask ? strokeComposite : fillComposite;\n const shaderMask = composite.getShaderMask(\n Renderer,\n mask,\n dirtyRect,\n normalizeDirtyRect,\n getFullDirtyRect,\n clearTarget,\n );\n\n runBlendShaderPass({\n renderer: Renderer,\n shader,\n source,\n mask: shaderMask,\n color: this.cachedColor,\n isBrushMask,\n Cwidth,\n Cheight,\n dirtyRect,\n targetIsFramebuffer,\n withScissor,\n });\n this.clearMask(mask);\n },\n};\n\n/**\n * Flushes any pending stroke/fill mask work into the current target and resets\n * the shared compositor back to its initial idle state.\n */\nexport const flushActiveComposite = () => {\n isMixReady();\n Mix.blend(false, true);\n Mix.clearMask(Mix.glMask);\n Mix.clearMask(Mix.mask);\n Mix.justChanged = false;\n Mix.isBlending = false;\n Mix.isBrush = null;\n Mix.cachedColor = null;\n};\n\n/**\n * Loads and initializes the drawing target, then refreshes compositing\n * resources if the renderer was already active.\n *\n * @param {object|false} [buffer=false] - Optional offscreen target.\n */\nexport const load = (buffer = false) => {\n loadTarget(buffer);\n if (Renderer.loaded) Mix.load();\n};\n","/*\n * A fast javascript implementation of simplex noise by Jonas Wagner\n\nBased on a speed-improved simplex noise algorithm for 2D, 3D and 4D in Java.\nWhich is based on example code by Stefan Gustavson ([email protected]).\nWith Optimisations by Peter Eastman ([email protected]).\nBetter rank ordering method by Stefan Gustavson in 2012.\n\n Copyright (c) 2024 Jonas Wagner\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n */\n// these __PURE__ comments help uglifyjs with dead code removal\n//\nconst SQRT3 = /*#__PURE__*/ Math.sqrt(3.0);\nconst SQRT5 = /*#__PURE__*/ Math.sqrt(5.0);\nconst F2 = 0.5 * (SQRT3 - 1.0);\nconst G2 = (3.0 - SQRT3) / 6.0;\nconst F3 = 1.0 / 3.0;\nconst G3 = 1.0 / 6.0;\nconst F4 = (SQRT5 - 1.0) / 4.0;\nconst G4 = (5.0 - SQRT5) / 20.0;\n// I'm really not sure why this | 0 (basically a coercion to int)\n// is making this faster but I get ~5 million ops/sec more on the\n// benchmarks across the board or a ~10% speedup.\nconst fastFloor = (x) => Math.floor(x) | 0;\nconst grad2 = /*#__PURE__*/ new Float64Array([1, 1,\n -1, 1,\n 1, -1,\n -1, -1,\n 1, 0,\n -1, 0,\n 1, 0,\n -1, 0,\n 0, 1,\n 0, -1,\n 0, 1,\n 0, -1]);\n// double seems to be faster than single or int's\n// probably because most operations are in double precision\nconst grad3 = /*#__PURE__*/ new Float64Array([1, 1, 0,\n -1, 1, 0,\n 1, -1, 0,\n -1, -1, 0,\n 1, 0, 1,\n -1, 0, 1,\n 1, 0, -1,\n -1, 0, -1,\n 0, 1, 1,\n 0, -1, 1,\n 0, 1, -1,\n 0, -1, -1]);\n// double is a bit quicker here as well\nconst grad4 = /*#__PURE__*/ new Float64Array([0, 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1,\n 0, -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1,\n 1, 0, 1, 1, 1, 0, 1, -1, 1, 0, -1, 1, 1, 0, -1, -1,\n -1, 0, 1, 1, -1, 0, 1, -1, -1, 0, -1, 1, -1, 0, -1, -1,\n 1, 1, 0, 1, 1, 1, 0, -1, 1, -1, 0, 1, 1, -1, 0, -1,\n -1, 1, 0, 1, -1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, -1,\n 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1, 0,\n -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1, 0]);\n/**\n * Creates a 2D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction2D}\n */\nexport function createNoise2D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating this yields a little ~3% performance improvement.\n const permGrad2x = new Float64Array(perm).map(v => grad2[(v % 12) * 2]);\n const permGrad2y = new Float64Array(perm).map(v => grad2[(v % 12) * 2 + 1]);\n return function noise2D(x, y) {\n // if(!isFinite(x) || !isFinite(y)) return 0;\n let n0 = 0; // Noise contributions from the three corners\n let n1 = 0;\n let n2 = 0;\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y) * F2; // Hairy factor for 2D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const t = (i + j) * G2;\n const X0 = i - t; // Unskew the cell origin back to (x,y) space\n const Y0 = j - t;\n const x0 = x - X0; // The x,y distances from the cell origin\n const y0 = y - Y0;\n // For the 2D case, the simplex shape is an equilateral triangle.\n // Determine which simplex we are in.\n let i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords\n if (x0 > y0) {\n i1 = 1;\n j1 = 0;\n } // lower triangle, XY order: (0,0)->(1,0)->(1,1)\n else {\n i1 = 0;\n j1 = 1;\n } // upper triangle, YX order: (0,0)->(0,1)->(1,1)\n // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and\n // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where\n // c = (3-sqrt(3))/6\n const x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords\n const y1 = y0 - j1 + G2;\n const x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords\n const y2 = y0 - 1.0 + 2.0 * G2;\n // Work out the hashed gradient indices of the three simplex corners\n const ii = i & 255;\n const jj = j & 255;\n // Calculate the contribution from the three corners\n let t0 = 0.5 - x0 * x0 - y0 * y0;\n if (t0 >= 0) {\n const gi0 = ii + perm[jj];\n const g0x = permGrad2x[gi0];\n const g0y = permGrad2y[gi0];\n t0 *= t0;\n // n0 = t0 * t0 * (grad2[gi0] * x0 + grad2[gi0 + 1] * y0); // (x,y) of grad3 used for 2D gradient\n n0 = t0 * t0 * (g0x * x0 + g0y * y0);\n }\n let t1 = 0.5 - x1 * x1 - y1 * y1;\n if (t1 >= 0) {\n const gi1 = ii + i1 + perm[jj + j1];\n const g1x = permGrad2x[gi1];\n const g1y = permGrad2y[gi1];\n t1 *= t1;\n // n1 = t1 * t1 * (grad2[gi1] * x1 + grad2[gi1 + 1] * y1);\n n1 = t1 * t1 * (g1x * x1 + g1y * y1);\n }\n let t2 = 0.5 - x2 * x2 - y2 * y2;\n if (t2 >= 0) {\n const gi2 = ii + 1 + perm[jj + 1];\n const g2x = permGrad2x[gi2];\n const g2y = permGrad2y[gi2];\n t2 *= t2;\n // n2 = t2 * t2 * (grad2[gi2] * x2 + grad2[gi2 + 1] * y2);\n n2 = t2 * t2 * (g2x * x2 + g2y * y2);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to return values in the interval [-1,1].\n return 70.0 * (n0 + n1 + n2);\n };\n}\n/**\n * Creates a 3D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction3D}\n */\nexport function createNoise3D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these seems to yield a speedup of over 15%\n const permGrad3x = new Float64Array(perm).map(v => grad3[(v % 12) * 3]);\n const permGrad3y = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 1]);\n const permGrad3z = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 2]);\n return function noise3D(x, y, z) {\n let n0, n1, n2, n3; // Noise contributions from the four corners\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y + z) * F3; // Very nice and simple skew factor for 3D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const t = (i + j + k) * G3;\n const X0 = i - t; // Unskew the cell origin back to (x,y,z) space\n const Y0 = j - t;\n const Z0 = k - t;\n const x0 = x - X0; // The x,y,z distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n // For the 3D case, the simplex shape is a slightly irregular tetrahedron.\n // Determine which simplex we are in.\n let i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords\n let i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords\n if (x0 >= y0) {\n if (y0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // X Y Z order\n else if (x0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // X Z Y order\n else {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // Z X Y order\n }\n else { // x0<y0\n if (y0 < z0) {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Z Y X order\n else if (x0 < z0) {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Y Z X order\n else {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // Y X Z order\n }\n // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),\n // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and\n // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where\n // c = 1/6.\n const x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords\n const y1 = y0 - j1 + G3;\n const z1 = z0 - k1 + G3;\n const x2 = x0 - i2 + 2.0 * G3; // Offsets for third corner in (x,y,z) coords\n const y2 = y0 - j2 + 2.0 * G3;\n const z2 = z0 - k2 + 2.0 * G3;\n const x3 = x0 - 1.0 + 3.0 * G3; // Offsets for last corner in (x,y,z) coords\n const y3 = y0 - 1.0 + 3.0 * G3;\n const z3 = z0 - 1.0 + 3.0 * G3;\n // Work out the hashed gradient indices of the four simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n // Calculate the contribution from the four corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad3x[gi0] * x0 + permGrad3y[gi0] * y0 + permGrad3z[gi0] * z0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad3x[gi1] * x1 + permGrad3y[gi1] * y1 + permGrad3z[gi1] * z1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad3x[gi2] * x2 + permGrad3y[gi2] * y2 + permGrad3z[gi2] * z2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + 1 + perm[jj + 1 + perm[kk + 1]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad3x[gi3] * x3 + permGrad3y[gi3] * y3 + permGrad3z[gi3] * z3);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to stay just inside [-1,1]\n return 32.0 * (n0 + n1 + n2 + n3);\n };\n}\n/**\n * Creates a 4D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction4D}\n */\nexport function createNoise4D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these leads to a ~10% speedup\n const permGrad4x = new Float64Array(perm).map(v => grad4[(v % 32) * 4]);\n const permGrad4y = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 1]);\n const permGrad4z = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 2]);\n const permGrad4w = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 3]);\n return function noise4D(x, y, z, w) {\n let n0, n1, n2, n3, n4; // Noise contributions from the five corners\n // Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in\n const s = (x + y + z + w) * F4; // Factor for 4D skewing\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const l = fastFloor(w + s);\n const t = (i + j + k + l) * G4; // Factor for 4D unskewing\n const X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space\n const Y0 = j - t;\n const Z0 = k - t;\n const W0 = l - t;\n const x0 = x - X0; // The x,y,z,w distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n const w0 = w - W0;\n // For the 4D case, the simplex is a 4D shape I won't even try to describe.\n // To find out which of the 24 possible simplices we're in, we need to\n // determine the magnitude ordering of x0, y0, z0 and w0.\n // Six pair-wise comparisons are performed between each possible pair\n // of the four coordinates, and the results are used to rank the numbers.\n let rankx = 0;\n let ranky = 0;\n let rankz = 0;\n let rankw = 0;\n if (x0 > y0)\n rankx++;\n else\n ranky++;\n if (x0 > z0)\n rankx++;\n else\n rankz++;\n if (x0 > w0)\n rankx++;\n else\n rankw++;\n if (y0 > z0)\n ranky++;\n else\n rankz++;\n if (y0 > w0)\n ranky++;\n else\n rankw++;\n if (z0 > w0)\n rankz++;\n else\n rankw++;\n // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order.\n // Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w and x<w\n // impossible. Only the 24 indices which have non-zero entries make any sense.\n // We use a thresholding to set the coordinates in turn from the largest magnitude.\n // Rank 3 denotes the largest coordinate.\n // Rank 2 denotes the second largest coordinate.\n // Rank 1 denotes the second smallest coordinate.\n // The integer offsets for the second simplex corner\n const i1 = rankx >= 3 ? 1 : 0;\n const j1 = ranky >= 3 ? 1 : 0;\n const k1 = rankz >= 3 ? 1 : 0;\n const l1 = rankw >= 3 ? 1 : 0;\n // The integer offsets for the third simplex corner\n const i2 = rankx >= 2 ? 1 : 0;\n const j2 = ranky >= 2 ? 1 : 0;\n const k2 = rankz >= 2 ? 1 : 0;\n const l2 = rankw >= 2 ? 1 : 0;\n // The integer offsets for the fourth simplex corner\n const i3 = rankx >= 1 ? 1 : 0;\n const j3 = ranky >= 1 ? 1 : 0;\n const k3 = rankz >= 1 ? 1 : 0;\n const l3 = rankw >= 1 ? 1 : 0;\n // The fifth corner has all coordinate offsets = 1, so no need to compute that.\n const x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords\n const y1 = y0 - j1 + G4;\n const z1 = z0 - k1 + G4;\n const w1 = w0 - l1 + G4;\n const x2 = x0 - i2 + 2.0 * G4; // Offsets for third corner in (x,y,z,w) coords\n const y2 = y0 - j2 + 2.0 * G4;\n const z2 = z0 - k2 + 2.0 * G4;\n const w2 = w0 - l2 + 2.0 * G4;\n const x3 = x0 - i3 + 3.0 * G4; // Offsets for fourth corner in (x,y,z,w) coords\n const y3 = y0 - j3 + 3.0 * G4;\n const z3 = z0 - k3 + 3.0 * G4;\n const w3 = w0 - l3 + 3.0 * G4;\n const x4 = x0 - 1.0 + 4.0 * G4; // Offsets for last corner in (x,y,z,w) coords\n const y4 = y0 - 1.0 + 4.0 * G4;\n const z4 = z0 - 1.0 + 4.0 * G4;\n const w4 = w0 - 1.0 + 4.0 * G4;\n // Work out the hashed gradient indices of the five simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n const ll = l & 255;\n // Calculate the contribution from the five corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk + perm[ll]]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad4x[gi0] * x0 + permGrad4y[gi0] * y0 + permGrad4z[gi0] * z0 + permGrad4w[gi0] * w0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad4x[gi1] * x1 + permGrad4y[gi1] * y1 + permGrad4z[gi1] * z1 + permGrad4w[gi1] * w1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad4x[gi2] * x2 + permGrad4y[gi2] * y2 + permGrad4z[gi2] * z2 + permGrad4w[gi2] * w2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad4x[gi3] * x3 + permGrad4y[gi3] * y3 + permGrad4z[gi3] * z3 + permGrad4w[gi3] * w3);\n }\n let t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4;\n if (t4 < 0)\n n4 = 0.0;\n else {\n const gi4 = ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]];\n t4 *= t4;\n n4 = t4 * t4 * (permGrad4x[gi4] * x4 + permGrad4y[gi4] * y4 + permGrad4z[gi4] * z4 + permGrad4w[gi4] * w4);\n }\n // Sum up and scale the result to cover the range [-1,1]\n return 27.0 * (n0 + n1 + n2 + n3 + n4);\n };\n}\n/**\n * Builds a random permutation table.\n * This is exported only for (internal) testing purposes.\n * Do not rely on this export.\n * @private\n */\nexport function buildPermutationTable(random) {\n const tableSize = 512;\n const p = new Uint8Array(tableSize);\n for (let i = 0; i < tableSize / 2; i++) {\n p[i] = i;\n }\n for (let i = 0; i < tableSize / 2 - 1; i++) {\n const r = i + ~~(random() * (256 - i));\n const aux = p[i];\n p[i] = p[r];\n p[r] = aux;\n }\n for (let i = 256; i < tableSize; i++) {\n p[i] = p[i - 256];\n }\n return p;\n}\n//# sourceMappingURL=simplex-noise.js.map","function _prng_restore(prng, xg, opts) {\n let state = opts && opts.state;\n if (state) {\n if (typeof(state) == 'object') xg.copy(state, xg);\n prng.state = () => xg.copy(xg, {});\n }\n}\n\nfunction _prng_xor_core(xg, opts) {\n let prng = () => (xg.next() >>> 0) / 0x100000000;\n\n prng.double = () => {\n let top, bot, result;\n do {\n top = xg.next() >>> 11;\n bot = (xg.next() >>> 0) / 0x100000000;\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n\n prng.int32 = () => xg.next() | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng;\n}\n\n// A port of an algorithm by Johannes Baagøe <[email protected]>, 2010\nfunction prng_alea(seed, opts) {\n let xg = new AleaGen(seed);\n\n let prng = () => xg.next();\n\n prng.double = () =>\n prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53\n\n prng.int32 = () => (xg.next() * 0x100000000) | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\nclass AleaGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let n = 0xefc8249d;\n\n // Apply the seeding algorithm from Baagoe.\n this.c = 1;\n this.s0 = mash(' ');\n this.s1 = mash(' ');\n this.s2 = mash(' ');\n this.s0 -= mash(seed);\n if (this.s0 < 0) { this.s0 += 1; }\n this.s1 -= mash(seed);\n if (this.s1 < 0) { this.s1 += 1; }\n this.s2 -= mash(seed);\n if (this.s2 < 0) { this.s2 += 1; }\n\n function mash(data) {\n data = String(data);\n for (let i = 0; i < data.length; i++) {\n n += data.charCodeAt(i);\n let h = 0.02519603282416938 * n;\n n = h >>> 0;\n h -= n;\n h *= n;\n n = h >>> 0;\n h -= n;\n n += h * 0x100000000; // 2^32\n }\n return (n >>> 0) * 2.3283064365386963e-10; // 2^-32\n }\n }\n\n next() {\n let {c,s0,s1,s2} = this;\n let t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32\n this.s0 = s1;\n this.s1 = s2;\n return this.s2 = t - (this.c = t | 0);\n }\n\n copy(f, t) {\n t.c = f.c;\n t.s0 = f.s0;\n t.s1 = f.s1;\n t.s2 = f.s2;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xor128\" prng algorithm by\nfunction prng_xor128(seed, opts) {\n let xg = new Xor128Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass Xor128Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w} = this;\n let t = x ^ (x << 11);\n this.x = y;\n this.y = z;\n this.z = w;\n return this.w = w ^ ((w >>> 19) ^ t ^ (t >>> 8));\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorwow\" prng algorithm by\nfunction prng_xorwow(seed, opts) {\n let xg = new XorWowGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass XorWowGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n this.v = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n if (k == strseed.length) {\n this.d = this.x << 10 ^ this.x >>> 4;\n }\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w,v,d} = this;\n let t = (x ^ (x >>> 2));\n this.x = y;\n this.y = z;\n this.z = w;\n this.w = v;\n return (this.d = (d + 362437 | 0)) +\n (this.v = (v ^ (v << 4)) ^ (t ^ (t << 1))) | 0;\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n t.v = f.v;\n t.d = f.d;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorshift7\" algorithm by\nfunction prng_xorshift7(seed, opts) {\n let xg = new XorShift7Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass XorShift7Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n var j, w, x = [];\n\n if (seed === (seed | 0)) {\n // Seed state array using a 32-bit integer.\n w = x[0] = seed;\n } else {\n // Seed state using a string.\n seed = '' + seed;\n for (j = 0; j < seed.length; ++j) {\n x[j & 7] = (x[j & 7] << 15) ^\n (seed.charCodeAt(j) + x[(j + 1) & 7] << 13);\n }\n }\n\n // Enforce an array length of 8, not all zeroes.\n while (x.length < 8) x.push(0);\n for (j = 0; j < 8 && x[j] === 0; ++j);\n if (j == 8) w = x[7] = -1; else w = x[j];\n\n this.x = x;\n this.i = 0;\n\n // Discard an initial 256 values.\n for (j = 256; j > 0; --j) {\n this.next();\n }\n }\n\n next() {\n // Update xor generator.\n let t, v, {x,i} = this;\n t = x[i]; t ^= (t >>> 7); v = t ^ (t << 24);\n t = x[(i + 1) & 7]; v ^= t ^ (t >>> 10);\n t = x[(i + 3) & 7]; v ^= t ^ (t >>> 3);\n t = x[(i + 4) & 7]; v ^= t ^ (t << 7);\n t = x[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);\n x[i] = v;\n this.i = (i + 1) & 7;\n return v;\n };\n\n copy(f, t) {\n t.x = [... f.x];\n t.i = f.i;\n return t;\n }\n}\n\n// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.\nfunction prng_xor4096(seed, opts) {\n let xg = new Xor4096Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass Xor4096Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let t, v, i, j, w, X = [], limit = 128;\n if (seed === (seed | 0)) {\n // Numeric seeds initialize v, which is used to generates X.\n v = seed;\n seed = null;\n } else {\n // String seeds are mixed into v and X one character at a time.\n seed = seed + '\\0';\n v = 0;\n limit = Math.max(limit, seed.length);\n }\n // Initialize circular array and weyl value.\n for (i = 0, j = -32; j < limit; ++j) {\n // Put the unicode characters into the array, and shuffle them.\n if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);\n // After 32 shuffles, take v as the starting w value.\n if (j === 0) w = v;\n v ^= v << 10;\n v ^= v >>> 15;\n v ^= v << 4;\n v ^= v >>> 13;\n if (j >= 0) {\n w = (w + 0x61c88647) | 0; // Weyl.\n t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array.\n i = (0 == t) ? i + 1 : 0; // Count zeroes.\n }\n }\n // We have detected all zeroes; make the key nonzero.\n if (i >= 128) {\n X[(seed && seed.length || 0) & 127] = -1;\n }\n // Run the generator 512 times to further mix the state before using it.\n // Factoring this as a function slows the main generator, so it is just\n // unrolled here. The weyl generator is not advanced while warming up.\n i = 127;\n for (j = 4 * 128; j > 0; --j) {\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n X[i] = v ^ t;\n }\n // Storing state as object members is faster than using closure variables.\n this.w = w;\n this.X = X;\n this.i = i;\n }\n\n next() {\n let t, v, {w, X, i} = this;\n // Update Weyl generator.\n this.w = w = (w + 0x61c88647) | 0;\n // Update xor generator.\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n // Update Xor generator array state.\n v = X[i] = v ^ t;\n this.i = i;\n // Result is the combination.\n return (v + (w ^ (w >>> 16))) | 0;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.w = f.w;\n t.X = [... f.X];\n return t;\n }\n}\n\n// A Javascript implementaion of the \"Tyche-i\" prng algorithm by\nfunction prng_tychei(seed, opts) {\n let xg = new TycheiGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass TycheiGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.a = 0;\n this.b = 0;\n this.c = 2654435769 | 0;\n this.d = 1367130551;\n\n if (seed === Math.floor(seed)) {\n // Integer seed.\n this.a = (seed / 0x100000000) | 0;\n this.b = seed | 0;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 20; k++) {\n this.b ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {a,b,c,d} = this;\n b = (b << 25) ^ (b >>> 7) ^ c;\n c = (c - d) | 0;\n d = (d << 24) ^ (d >>> 8) ^ a;\n a = (a - b) | 0;\n this.b = b = (b << 20) ^ (b >>> 12) ^ c;\n this.c = c = (c - d) | 0;\n this.d = (d << 16) ^ (c >>> 16) ^ a;\n return this.a = (a - b) | 0;\n };\n\n copy(f, t) {\n t.a = f.a;\n t.b = f.b;\n t.c = f.c;\n t.d = f.d;\n return t;\n }\n}\n\n\n/* The following is non-inverted tyche, which has better internal\n * bit diffusion, but which is about 25% slower than tyche-i in JS.\n *\n\nclass TycheiGenAlt extends TycheiGen {\n next() {\n let {a,b,c,d} = this\n a = (a + b | 0) >>> 0;\n d = d ^ a; d = d << 16 ^ d >>> 16;\n c = c + d | 0;\n b = b ^ c; b = b << 12 ^ d >>> 20;\n this.a = a = a + b | 0;\n d = d ^ a; this.d = d = d << 8 ^ d >>> 24;\n this.c = c = c + d | 0;\n b = b ^ c;\n return this.b = (b << 7 ^ b >>> 25);\n }\n}\n*/\n\n/*\nCopyright 2019 David Bau.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*/\nfunction prng_arc4(seed, opts) {\n let xg = new ARC4Gen(seed);\n let prng = () => xg.next();\n\n prng.double = prng;\n\n prng.int32 = () => xg.g(4) | 0;\n\n prng.quick = () => xg.g(4) / 0x100000000;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\n\n//\n// ARC4\n//\n// An ARC4 implementation. The constructor takes a key in the form of\n// an array of at most (width) integers that should be 0 <= x < (width).\n//\n// The g(count) method returns a pseudorandom integer that concatenates\n// the next (count) outputs from ARC4. Its return value is a number x\n// that is in the range 0 <= x < (width ^ count).\n//\n\n//\n// The following constants are related to IEEE 754 limits.\n//\n\n// const width = 256 // each RC4 output is 0 <= x < 256\n// const chunks = 6 // at least six RC4 outputs for each double\nconst _arc4_startdenom = 281474976710656; // 256 ** 6 == width ** chunks\nconst _arc4_significance = 4503599627370496; // 2 ** 52 significant digits in a double\nconst _arc4_overflow = 9007199254740992; // 2 ** 53 == significance * 2\n\n\nclass ARC4Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let key = this.mixkey(seed, []);\n let i,j,t, S=[], keylen = key.length;\n this.i = this.j = i = j = 0;\n this.S = S;\n\n // The empty key [] is treated as [0].\n if (!keylen) { key = [keylen++]; }\n\n // Set up S using the standard key scheduling algorithm.\n while (i <= 0xff) {\n S[i] = i++;\n }\n for (i = 0; i <= 0xff; i++) {\n S[i] = S[j = 0xff & (j + key[i % keylen] + (t = S[i]))];\n S[j] = t;\n }\n\n // For robust unpredictability, the function call below automatically\n // discards an initial batch of values. This is called RC4-drop[256].\n // See http://google.com/search?q=rsa+fluhrer+response&btnI\n this.g(256);\n }\n\n next() {\n // This function returns a random double in [0, 1) that contains\n // randomness in every bit of the mantissa of the IEEE 754 value.\n\n let n = this.g(6); // Start with a numerator n < 2 ^ 48\n let d = _arc4_startdenom; // and denominator d = 2 ^ 48.\n let x = 0; // and no 'extra last byte'.\n\n while (n < _arc4_significance) { // Fill up all significant digits (2 ** 52)\n n = (n + x) * 256; // by shifting numerator and\n d *= 256; // denominator and generating a\n x = this.g(1); // new least-significant-byte.\n }\n while (n >= _arc4_overflow) { // To avoid rounding past overflow, before adding\n n /= 2; // last byte, shift everything\n d /= 2; // right using integer math until\n x >>>= 1; // we have exactly the desired bits.\n }\n return (n + x) / d; // Form the number within [0, 1).\n }\n\n g(count) {\n // The \"g\" method returns the next (count) outputs as one number.\n let t, r = 0, {i,j,S} = this;\n while (count--) {\n t = S[i = 0xff & (i + 1)];\n r = r * 256 + S[0xff & ((S[i] = S[j = 0xff & (j + t)]) + (S[j] = t))];\n }\n this.i = i;\n this.j = j;\n return r;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.j = f.j;\n t.S = [... f.S];\n return t;\n }\n\n mixkey(seed, key) {\n seed = seed + '';\n let smear=0, j=0;\n while (j < seed.length) {\n key[0xff & j] =\n 0xff & ((smear ^= key[0xff & j] * 19) + seed.charCodeAt(j++));\n }\n return key\n }\n}\n\nexport { prng_alea, prng_arc4, prng_tychei, prng_xor128, prng_xor4096, prng_xorshift7, prng_xorwow };\n//# sourceMappingURL=index.mjs.map\n","import { usesRadians as runtimeUsesRadians } from \"./runtime.js\";\n\n// =============================================================================\n// Section: Randomness & Noise\n// =============================================================================\n\nimport { createNoise2D } from \"simplex-noise\";\nimport { prng_alea } from \"esm-seedrandom\";\n\n/**\n * A uniform PRNG function. Returns a float in [0,1).\n * @callback RNG\n * @returns {number}\n */\n/** @type {RNG} */\nlet rng = prng_alea(Math.random());\nlet rng2 = prng_alea(Math.random());\n\nconst _seedCallbacks = [];\n\n/**\n * Register a callback to be called whenever seed() is invoked.\n * Used internally by modules that maintain gaussian pools.\n * @param {Function} cb\n */\nexport const _onSeed = (cb) => _seedCallbacks.push(cb);\n\n/**\n * Seed the random number generator.\n * @param {number|string} s – The seed value.\n * @returns {void}\n */\nexport const seed = (s) => {\n rng = prng_alea(s);\n rng2 = prng_alea(`${s}:2`);\n for (const callback of _seedCallbacks) {\n callback();\n }\n};\n\n/**\n * Simplex‐noise 2D function.\n * @type {function(number, number): number}\n */\nexport let noise = createNoise2D(prng_alea(Math.random()));\nexport let noise2 = createNoise2D(prng_alea(Math.random()));\n\n/**\n * Seed the noise generator.\n * @param {number|string} s - The seed value.\n * @returns {void}\n */\nexport const noiseSeed = (s) => {\n noise = createNoise2D(prng_alea(s));\n noise2 = createNoise2D(prng_alea(`${s}:2`));\n};\n\n/**\n * Returns a random float in [min, max).\n * @param {number} [min=0]\n * @param {number} [max=1]\n * @returns {number}\n */\nexport const rr = (e = 0, r = 1) => e + rng() * (r - e);\nexport const rr2 = (e = 0, r = 1) => e + rng2() * (r - e);\n\n/**\n * Selects a random element from an array.\n * @param {T[]} array - Input array.\n * @returns {T}\n */\nexport const rArray = (array) => array[~~(rng() * array.length)];\n\n/**\n * Returns a random integer in [min, max).\n * @param {number} min\n * @param {number} max\n * @returns {number}\n */\nexport const randInt = (e, r) => ~~rr(e, r);\nexport const randInt2 = (e, r) => ~~rr2(e, r);\n\n/**\n * Gaussian (normal) random sample N(mean, stdev²).\n * @param {number} [mean=0]\n * @param {number} [stdev=1]\n * @returns {number}\n */\nexport const gaussian = (mean = 0, stdev = 1) => {\n const u = 1 - rng();\n const v = rng();\n const z = Math.sqrt(-2.0 * Math.log(u)) * cos(360 * v);\n return z * stdev + mean;\n};\n\n/**\n * Picks a key from an object according to weighted probabilities.\n * @param {Object<string|number, number>} weights\n * @returns {string|number}\n */\nexport const weightedRand = (weights) => {\n let totalWeight = 0;\n const entries = [];\n\n // Build cumulative weights array\n for (const key in weights) {\n totalWeight += weights[key];\n entries.push({ key, cumulative: totalWeight });\n }\n\n // Get a random number between 0 and totalWeight\n const rnd = rng() * totalWeight;\n\n // Pick the first entry where rnd is less than the cumulative weight\n for (const { key, cumulative } of entries) {\n if (rnd < cumulative) {\n return isNaN(key) ? key : parseInt(key);\n }\n }\n};\n\n// =============================================================================\n// Section: Numeric Mapping & Constraints\n// =============================================================================\n\n/**\n * Maps a value from range [a,b] to [c,d], optionally clamped.\n * @param {number} value\n * @param {number} a\n * @param {number} b\n * @param {number} c\n * @param {number} d\n * @param {boolean} [withinBounds=false]\n * @returns {number}\n */\nexport const map = (value, a, b, c, d, withinBounds = false) => {\n let r = c + ((value - a) / (b - a)) * (d - c);\n if (!withinBounds) return r;\n if (c < d) return constrain(r, c, d);\n else return constrain(r, d, c);\n};\n\n/**\n * Constrains a number within the provided bounds.\n * @param {number} n - The number.\n * @param {number} low - Lower bound.\n * @param {number} high - Upper bound.\n * @returns {number} The constrained number.\n */\nexport const constrain = (n, low, high) => Math.max(Math.min(n, high), low);\n\n// =============================================================================\n// Section: Trigonometry\n// =============================================================================\n\n/**\n * Normalize an angle in degrees to [0,360).\n * @param {number} angle\n * @returns {number}\n */\nconst nAngle = (angle) => {\n angle = angle % 360;\n return angle < 0 ? angle + 360 : angle;\n};\n\n// number of discrete steps (360° × 4 samples per degree)\nconst totalDegrees = 1440;\nconst radiansPerIndex = (2 * Math.PI) / totalDegrees;\n\n// lazy‐initialized lookup tables\nconst cLookup = new Float32Array(totalDegrees).fill(NaN);\nconst sLookup = new Float32Array(totalDegrees).fill(NaN);\n\n/**\n * Cosine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const cos = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = cLookup[idx];\n if (isNaN(v)) {\n v = Math.cos(idx * radiansPerIndex);\n cLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Sine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const sin = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = sLookup[idx];\n if (isNaN(v)) {\n v = Math.sin(idx * radiansPerIndex);\n sLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Converts radians to degrees, normalized to [0,360).\n * @param {number} rad\n * @returns {number}\n */\nexport const toDegrees = (rad, isRad = false) => {\n if (isRad || runtimeUsesRadians()) {\n let angle = ((rad * 180) / Math.PI) % 360;\n return angle < 0 ? angle + 360 : angle;\n } else {\n return rad;\n }\n};\n\n/**\n * Converts radians to degrees without wrapping the result.\n * Preserves signed angles so downstream scaling keeps its direction.\n * @param {number} angle\n * @param {boolean} [isRad=false]\n * @returns {number}\n */\nexport const toDegreesSigned = (angle, isRad = false) =>\n isRad || runtimeUsesRadians()\n ? (angle * 180) / Math.PI\n : angle;\n\n// =============================================================================\n// Section: Geometry & Transforms\n// =============================================================================\n\n/**\n * Rotates point (x,y) around center (cx,cy) by angle degrees.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x\n * @param {number} y\n * @param {number} angle - Degrees\n * @returns {{x:number,y:number}}\n */\nexport const rotate = (cx, cy, x, y, angle) => {\n let coseno = cos(angle),\n seno = sin(angle),\n nx = coseno * (x - cx) + seno * (y - cy) + cx,\n ny = coseno * (y - cy) - seno * (x - cx) + cy;\n return { x: nx, y: ny };\n};\n\n/**\n * Euclidean distance between two points.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const dist = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1);\n\n/**\n * Angle in degrees between two points, measured clockwise from +X.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const calcAngle = (x1, y1, x2, y2) =>\n toDegrees(Math.atan2(-(y2 - y1), x2 - x1), true);\n\n/**\n * Intersection of two line segments, or false if none.\n * @param {{x:number,y:number}} s1a\n * @param {{x:number,y:number}} s1b\n * @param {{x:number,y:number}} s2a\n * @param {{x:number,y:number}} s2b\n * @param {boolean} [includeSegmentExtension=false]\n * @returns {{x:number,y:number}|false}\n */\nexport const intersectLines = (\n s1a,\n s1b,\n s2a,\n s2b,\n includeSegmentExtension = false\n) => {\n // Extract coordinates from points\n let x1 = s1a.x,\n y1 = s1a.y;\n let x2 = s1b.x,\n y2 = s1b.y;\n let x3 = s2a.x,\n y3 = s2a.y;\n let x4 = s2b.x,\n y4 = s2b.y;\n // Early return if line segments are points or if the lines are parallel\n if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) {\n return false; // Segments are points\n }\n let deltaX1 = x2 - x1,\n deltaY1 = y2 - y1;\n let deltaX2 = x4 - x3,\n deltaY2 = y4 - y3;\n let denominator = deltaY2 * deltaX1 - deltaX2 * deltaY1;\n if (denominator === 0) {\n return false; // Lines are parallel\n }\n // Calculate the intersection point\n let ua = (deltaX2 * (y1 - y3) - deltaY2 * (x1 - x3)) / denominator;\n let ub = (deltaX1 * (y1 - y3) - deltaY1 * (x1 - x3)) / denominator;\n // Check if the intersection is within the bounds of the line segments\n if (!includeSegmentExtension && (ub < 0 || ub > 1)) {\n return false;\n }\n // Calculate the intersection coordinates\n let x = x1 + ua * deltaX1;\n let y = y1 + ua * deltaY1;\n return { x: x, y: y };\n};\n","import { Cwidth, Cheight } from \"./target.js\";\nimport { isMixReady, State } from \"./color.js\";\nimport { randInt2, noise2, rr2, sin, cos, map, toDegreesSigned } from \"./utils.js\";\nimport { getAffineMatrix } from \"./runtime.js\";\n\n// =============================================================================\n// Section: Matrix transformations\n// =============================================================================\n\n// =============================================================================\n// Section: Field Initialization\n// =============================================================================\n\nlet isLoaded = false;\n\n/**\n * Ensures the field system is initialized and ready for use.\n * If the field is not loaded, it initializes the mixing system and creates the field.\n */\nexport function isFieldReady() {\n if (!isLoaded) {\n isMixReady(); // Ensure the mixing system is ready\n createField(); // Initialize the field\n isLoaded = true;\n }\n}\n\n// =============================================================================\n// Section: Position Class\n// =============================================================================\n\n/**\n * The Position class represents a point within a two-dimensional space, which can interact with a vector field.\n * It provides methods to update the position based on the field's flow and to check whether the position is\n * within certain bounds (e.g., within the field or canvas).\n */\nexport class Position {\n /**\n * Constructs a new Position instance.\n * @param {number} x - The initial x-coordinate.\n * @param {number} y - The initial y-coordinate.\n */\n constructor(x, y) {\n isFieldReady();\n const m = getAffineMatrix();\n this.mx = m.x;\n this.my = m.y;\n this.update(x, y);\n this.plotted = 0; // Tracks the total distance plotted\n }\n\n /**\n * Updates the position's coordinates and calculates its offsets and indices within the flow field.\n * @param {number} x - The new x-coordinate.\n * @param {number} y - The new y-coordinate.\n */\n update(x, y) {\n this.x = x;\n this.y = y;\n this.colIdx = Math.round((x + this.mx - left_x) / resolution);\n this.rowIdx = Math.round((y + this.my - top_y) / resolution);\n }\n\n /**\n * Resets the 'plotted' property to 0.\n */\n reset() {\n this.plotted = 0;\n }\n\n /**\n * Checks if the position is within the active flow field's bounds.\n * @returns {boolean} - True if the position is within the flow field, false otherwise.\n */\n isIn() {\n return State.field.isActive\n ? Position.isIn(this.colIdx, this.rowIdx)\n : this.isInCanvas(this.x, this.y);\n }\n\n /**\n * Checks if the position is within the canvas bounds (with a margin).\n * @returns {boolean} - True if the position is within bounds, false otherwise.\n */\n isInCanvas() {\n const margin = 0.3;\n const w = Cwidth;\n const h = Cheight;\n const x = this.x + this.mx;\n const y = this.y + this.my;\n return (\n x >= -margin * w &&\n x <= (1 + margin) * w &&\n y >= -margin * h &&\n y <= (1 + margin) * h\n );\n }\n\n /**\n * Calculates the angle of the flow field at the position's current coordinates.\n * @returns {number} - The internal flow angle in degrees, or 0 if the position is not in the field or if no field is active.\n */\n angle(skipCheck = false) {\n if (!State.field.isActive) return 0;\n return (skipCheck || this.isIn())\n ? flow_field()[this.colIdx][this.rowIdx] * State.field.wiggle\n : 0;\n }\n\n /**\n * Moves the position along the flow field by a certain length.\n * @param {number} _dir - The direction of movement, interpreted using the current runtime angle units.\n * @param {number} _length - The length to move along the field.\n * @param {number} _step_length - The length of each step.\n */\n moveTo(_dir, _length, _step_length = 1) {\n this.movePos(toDegreesSigned(_dir), _length, _step_length);\n }\n\n /**\n * Internal variant of moveTo() that expects a degree value already normalized to the library's internal representation.\n */\n _moveToDegrees(_dir, _length, _step_length = 1) {\n this.movePos(_dir, _length, _step_length);\n }\n\n /**\n * Plots a point to another position within the flow field, following a Plot object\n * @param {Position} _plot - The Plot path object.\n * @param {number} _length - The length to move towards the target position.\n * @param {number} _step_length - The length of each step.\n * @param {number} _scale - The scaling factor for the plotting path.\n */\n plotTo(_plot, _length, _step_length, _scale = 1) {\n this.movePos(_plot, _length, _step_length, _scale);\n }\n\n movePos(_dirPlot, _length, _step, _scale = false) {\n const scaleFactor = _scale || 1;\n if (!this.isIn()) {\n this.plotted += _step / scaleFactor;\n return;\n }\n const steps = _length / _step;\n const fieldActive = State.field.isActive;\n const usePlot = !!_scale;\n for (let i = 0; i < steps; i++) {\n const angle =\n (fieldActive ? this.angle(true) : 0) - (usePlot ? _dirPlot.angle(this.plotted) : _dirPlot);\n // Calculate new position\n this.update(this.x + _step * cos(angle), this.y + _step * sin(angle));\n this.plotted += _step / scaleFactor;\n }\n }\n\n // Static Methods\n\n /**\n * Gets the row index for a given y-coordinate.\n * @param {number} y - The y-coordinate.\n * @returns {number} - The row index.\n */\n static getRowIndex(y, d = 1) {\n const y_offset = y + getAffineMatrix().y - top_y;\n return Math.round(y_offset / resolution / d);\n }\n\n /**\n * Gets the column index for a given x-coordinate.\n * @param {number} x - The x-coordinate.\n * @returns {number} - The column index.\n */\n static getColIndex(x, d = 1) {\n const x_offset = x + getAffineMatrix().x - left_x;\n return Math.round(x_offset / resolution / d);\n }\n\n /**\n * Checks if a column and row index are within the flow field bounds.\n * @param {number} col - The column index.\n * @param {number} row - The row index.\n * @returns {boolean} - True if the indices are within bounds, false otherwise.\n */\n static isIn(col, row) {\n return col >= 0 && row >= 0 && col < num_columns && row < num_rows;\n }\n}\n\n// =============================================================================\n// Section: VectorField\n// =============================================================================\n\n/**\n * Represents the state of the vector field.\n * @property {boolean} isActive - Indicates if the vector field is active.\n * @property {string|null} current - The name of the currently active vector field.\n */\nState.field = {\n isActive: false,\n current: null,\n wiggle: 1,\n};\n\n// Internal variables for field configuration\nlet list = new Map();\nlet resolution, left_x, top_y, num_columns, num_rows;\nconst FIELD_ANGLE_MODES = new Set([\"degrees\", \"radians\"]);\n\n/**\n * Initializes the field grid and sets up the vector field's structure based on the renderer's dimensions.\n */\nfunction createField() {\n resolution = Cwidth * 0.01; // Determine the resolution of the field grid\n left_x = -0.5 * Cwidth; // Left boundary of the field\n top_y = -0.5 * Cheight; // Top boundary of the field\n num_columns = Math.round((2 * Cwidth) / resolution); // Number of columns in the grid\n num_rows = Math.round((2 * Cheight) / resolution); // Number of columns in the grid\n addStandard(); // Add default vector field\n}\n\n/**\n * Retrieves the field values for the current vector field.\n * @returns {Float32Array[]} The current vector field grid.\n */\nfunction flow_field() {\n return list.get(State.field.current).field;\n}\n\nfunction normalizeFieldAngleMode(options = {}) {\n const config =\n typeof options === \"string\" ? { angleMode: options } : options || {};\n const angleMode = config.angleMode ?? \"degrees\";\n\n if (!FIELD_ANGLE_MODES.has(angleMode)) {\n throw new Error(\n `Invalid field angle mode \"${angleMode}\". Use \"degrees\" or \"radians\".`,\n );\n }\n\n return angleMode;\n}\n\nfunction normalizeFieldAngles(field, angleMode) {\n if (angleMode !== \"radians\") return field;\n\n for (let c = 0; c < field.length; c++) {\n for (let r = 0; r < field[c].length; r++) {\n field[c][r] = toDegreesSigned(field[c][r], true);\n }\n }\n\n return field;\n}\n\nfunction generateField(entry, t) {\n return normalizeFieldAngles(entry.gen(t, genField()), entry.angleMode);\n}\n\n/**\n * Regenerates the current vector field using its associated generator function.\n * @param {number} [t=0] - An optional time parameter that can affect field generation.\n */\nexport function refreshField(t = 0) {\n if (!State.field.isActive || !State.field.current) {\n throw new Error(\n \"No field is currently active. Call brush.field('name') to activate one before refreshing.\",\n );\n }\n const currentField = list.get(State.field.current);\n currentField.field = generateField(currentField, t);\n}\n\n/**\n * Generates an empty field array.\n * Reuses existing arrays to reduce memory allocation overhead.\n * @returns {Float32Array[]} Empty vector field grid.\n */\nfunction genField() {\n return new Array(num_columns)\n .fill(null)\n .map(() => new Float32Array(num_rows));\n}\n\n/**\n * Activates a specific vector field by name, ensuring it's ready for use.\n * @param {string} a - The name of the vector field to activate.\n */\nexport function field(a) {\n if (!State.field.wiggle) {\n State.field.wiggle = 1;\n } // Set default wiggle value\n isFieldReady();\n if (!list.has(a)) {\n throw new Error(\n `Field \"${a}\" does not exist. Available fields: ${Array.from(list.keys()).join(\", \")}.`,\n );\n }\n State.field.isActive = true;\n State.field.current = a;\n const entry = list.get(a);\n if (!entry.field) entry.field = generateField(entry, 0);\n}\n\n/**\n * Deactivates the current vector field.\n */\nexport function noField() {\n isFieldReady();\n State.field.isActive = false;\n}\n\n/**\n * Adds a new vector field to the field list with a unique name and a generator function.\n * @param {string} name - The unique name for the new vector field.\n * @param {Function} funct - The function that generates the field values.\n * @param {object} [options] - Optional field configuration.\n * @param {\"degrees\"|\"radians\"} [options.angleMode=\"degrees\"] - How the generator's output angles should be interpreted.\n */\nexport function addField(name, funct, options = {}) {\n list.set(name, {\n gen: funct,\n field: null,\n angleMode: normalizeFieldAngleMode(options),\n });\n}\n\n/**\n * Retrieves a list of all available vector field names.\n * @returns {string[]} An array of all the field names.\n */\nexport function listFields() {\n isFieldReady();\n return Array.from(list.keys());\n}\n\nexport function wiggle(a = 1) {\n field(\"hand\");\n State.field.wiggle = a;\n}\n\n/**\n * Fills every cell of a field grid using a callback (c, r) => angle.\n */\nfunction fillField(field, fn) {\n for (let c = 0; c < num_columns; c++)\n for (let r = 0; r < num_rows; r++) field[c][r] = fn(c, r);\n return field;\n}\n\n/**\n * Adds standard predefined vector fields to the list with unique behaviors.\n */\nfunction addStandard() {\n // Organic noise — basis for brush.wiggle()\n addField(\"hand\", (t, field) => {\n const bs = rr2(0.2, 0.8),\n ba = randInt2(5, 10);\n return fillField(field, (c, r) => {\n const angle = 0.5 * ba * sin(bs * r * c + randInt2(15, 25));\n return 0.2 * angle * cos(t) + noise2(c, r) * ba * 0.7;\n });\n });\n // Smooth large-scale noise curves\n addField(\"curved\", (t, field) => {\n let ar = randInt2(-10, 10);\n if (randInt2(0, 100) % 2 == 0) ar *= -1;\n return fillField(\n field,\n (c, r) =>\n 3 * map(noise2(c * 0.02 + t * 0.03, r * 0.02 + t * 0.03), 0, 1, -ar, ar),\n );\n });\n // Sharp alternating angles per cell — herringbone / wicker look\n addField(\"zigzag\", (t, field) => {\n let ar = randInt2(-30, -15) + Math.abs(44 * sin(t));\n if (randInt2(0, 100) % 2 == 0) ar *= -1;\n let dif = ar,\n angle = 0;\n for (let c = 0; c < num_columns; c++) {\n for (let r = 0; r < num_rows; r++) {\n field[c][r] = angle;\n angle += dif;\n dif *= -1;\n }\n angle += dif;\n dif *= -1;\n }\n return field;\n });\n // Sinusoidal wave bands\n addField(\"waves\", (t, field) => {\n const sr = randInt2(10, 15) + 5 * sin(t),\n cr = randInt2(3, 6) + 3 * cos(t),\n ba = randInt2(20, 35);\n return fillField(\n field,\n (c, r) => sin(sr * c) * ba * cos(r * cr) + randInt2(-3, 3),\n );\n });\n // Dense oscillation from row×col product\n addField(\"seabed\", (t, field) => {\n const bs = rr2(0.4, 0.8),\n ba = randInt2(18, 26);\n return fillField(\n field,\n (c, r) => 1.1 * ba * sin(bs * r * c + randInt2(15, 20)) * cos(t),\n );\n });\n // Radial vortex — angles spiral around the field centre\n addField(\"spiral\", (_t, field) => {\n const n = randInt2(5, 10);\n const dir = randInt2(0, 2) * 2 - 1;\n const offset = randInt2(65, 80); // <90 = inward spiral\n const attractors = Array.from({ length: n }, () => ({\n x: rr2(0.1, 0.9) * num_columns,\n y: rr2(0.1, 0.9) * num_rows,\n }));\n return fillField(field, (c, r) => {\n let wx = 0,\n wy = 0;\n for (const att of attractors) {\n const dx = c - att.x,\n dy = r - att.y;\n const w = 1 / (dx * dx + dy * dy + 1);\n const a = Math.atan2(dy, dx) * (180 / Math.PI);\n const angle = (dir * (a + offset) * Math.PI) / 180;\n wx += w * Math.cos(angle);\n wy += w * Math.sin(angle);\n }\n return Math.atan2(wy, wx) * (180 / Math.PI);\n });\n });\n // Column-banded stripes — parallel rake marks\n addField(\"columns\", (_t, field) => {\n const freq = randInt2(3, 8),\n amp = randInt2(25, 45);\n return fillField(field, (c, _r) => sin(c * freq) * amp);\n });\n}\n","import { State } from \"./color.js\";\nimport { isFieldReady } from \"./flowfield.js\";\n\n// =============================================================================\n// SAVE / RESTORE\n// =============================================================================\n\n/**\n * Stack of saved brush states for push/pop operations.\n * A stack (not a single slot) is required because applyShader() internally\n * calls Renderer.push()/pop(), which fires our hook — a flat object would be\n * overwritten mid-draw and pop() would restore the wrong state.\n */\nconst _stateStack = [];\n\n/**\n * Pushes the current brush state onto the stack.\n */\nexport function push() {\n isFieldReady();\n _stateStack.push({\n fill: { ...State.fill },\n wash: State.wash ? { ...State.wash } : null,\n stroke: { ...State.stroke },\n hatch: { ...State.hatch },\n mass: State.mass ? { ...State.mass } : null,\n field: { ...State.field },\n });\n}\n\n/**\n * Pops the top brush state from the stack and restores it.\n */\nexport function pop() {\n const saved = _stateStack.pop();\n if (!saved) return;\n State.stroke = { ...saved.stroke };\n State.field = { ...saved.field };\n State.hatch = { ...saved.hatch };\n State.fill = { ...saved.fill };\n if (saved.wash) State.wash = { ...saved.wash };\n if (saved.mass) {\n State.mass = { ...saved.mass };\n } else if (State.mass) {\n State.mass = {\n ...State.mass,\n isActive: false,\n brush: null,\n color: null,\n options: {},\n };\n }\n}\n","// =============================================================================\n// Adapter: Standalone Runtime Hooks\n// =============================================================================\n\nimport { setRuntime } from \"../../core/runtime.js\";\nimport { push as pushState, pop as popState } from \"../../core/save.js\";\n\nconst clamp = (value, min, max) => Math.max(min, Math.min(value, max));\n\nexport const DEGREES = \"degrees\";\nexport const RADIANS = \"radians\";\n\nlet colorContext = null;\nlet currentAngleMode = DEGREES;\nconst transformStack = [];\nlet currentTransform = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\n\nfunction getColorContext() {\n if (colorContext) return colorContext;\n\n if (typeof document !== \"undefined\") {\n colorContext = document.createElement(\"canvas\").getContext(\"2d\");\n return colorContext;\n }\n\n if (typeof OffscreenCanvas !== \"undefined\") {\n colorContext = new OffscreenCanvas(1, 1).getContext(\"2d\");\n return colorContext;\n }\n\n throw new Error(\"Standalone color parsing requires CanvasRenderingContext2D support.\");\n}\n\nfunction multiplyTransform(left, right) {\n return {\n a: left.a * right.a + left.c * right.b,\n b: left.b * right.a + left.d * right.b,\n c: left.a * right.c + left.c * right.d,\n d: left.b * right.c + left.d * right.d,\n x: left.a * right.x + left.c * right.y + left.x,\n y: left.b * right.x + left.d * right.y + left.y,\n };\n}\n\n/**\n * Runtime-native color object compatible with the expectations of core modules.\n */\nexport class Color {\n constructor(r, g, b) {\n if (r?._array) {\n this.r = Math.round(r._array[0] * 255);\n this.g = Math.round(r._array[1] * 255);\n this.b = Math.round(r._array[2] * 255);\n this.hex = this.rgbToHex(this.r, this.g, this.b);\n this._array = [...r._array];\n this.gl = this._array;\n return;\n }\n\n if (typeof r === \"string\") {\n const rgbaMatch = /^rgba?\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*(?:,\\s*([\\d.]+))?\\s*\\)$/i.exec(r);\n if (rgbaMatch) {\n this.r = clamp(parseInt(rgbaMatch[1]), 0, 255);\n this.g = clamp(parseInt(rgbaMatch[2]), 0, 255);\n this.b = clamp(parseInt(rgbaMatch[3]), 0, 255);\n this.hex = this.rgbToHex(this.r, this.g, this.b);\n const alpha = rgbaMatch[4] !== undefined ? clamp(parseFloat(rgbaMatch[4]), 0, 1) : 1;\n this._array = [this.r / 255, this.g / 255, this.b / 255, alpha];\n this.gl = this._array;\n return;\n }\n this.hex = this.standardize(r);\n const rgb = this.hexToRgb(this.hex);\n this.r = rgb.r;\n this.g = rgb.g;\n this.b = rgb.b;\n } else {\n this.r = clamp(r ?? 0, 0, 255);\n this.g = clamp(g ?? r ?? 0, 0, 255);\n this.b = clamp(b ?? r ?? 0, 0, 255);\n this.hex = this.rgbToHex(this.r, this.g, this.b);\n }\n\n this._array = [this.r / 255, this.g / 255, this.b / 255, 1];\n this.gl = this._array;\n }\n\n rgbToHex(r, g, b) {\n return `#${((1 << 24) | (r << 16) | (g << 8) | b).toString(16).slice(1)}`;\n }\n\n hexToRgb(hex) {\n hex = hex.replace(\n /^#?([a-f\\d])([a-f\\d])([a-f\\d])$/i,\n (_match, red, green, blue) => red + red + green + green + blue + blue,\n );\n const result = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\n if (!result) {\n throw new Error(`Invalid color value \"${hex}\".`);\n }\n return {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16),\n };\n }\n\n standardize(value) {\n const ctx = getColorContext();\n ctx.fillStyle = value;\n return ctx.fillStyle;\n }\n\n _getRed() {\n return this.r;\n }\n\n _getGreen() {\n return this.g;\n }\n\n _getBlue() {\n return this.b;\n }\n}\n\n/**\n * Sets the active standalone angle mode.\n *\n * @param {\"degrees\"|\"radians\"} mode\n */\nexport function angleMode(mode) {\n if (mode !== DEGREES && mode !== RADIANS) {\n throw new Error(`Invalid angle mode \"${mode}\". Use \"degrees\" or \"radians\".`);\n }\n currentAngleMode = mode;\n}\n\n/**\n * Returns the current standalone angle mode.\n *\n * @returns {\"degrees\"|\"radians\"}\n */\nexport function getAngleMode() {\n return currentAngleMode;\n}\n\n/**\n * Pushes the current standalone transform onto the stack.\n */\nexport function push() {\n pushState();\n transformStack.push({ ...currentTransform });\n}\n\n/**\n * Pops the last standalone transform from the stack.\n */\nexport function pop() {\n if (transformStack.length === 0) return;\n currentTransform = transformStack.pop();\n popState();\n}\n\n/**\n * Applies a translation to the current standalone transform.\n *\n * @param {number} x\n * @param {number} y\n */\nexport function translate(x, y) {\n currentTransform = multiplyTransform(currentTransform, {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x,\n y,\n });\n}\n\n/**\n * Applies a rotation to the current standalone transform.\n *\n * @param {number} angle\n */\nexport function rotate(angle) {\n const theta =\n currentAngleMode === RADIANS ? angle : (angle * Math.PI) / 180;\n const cosTheta = Math.cos(theta);\n const sinTheta = Math.sin(theta);\n currentTransform = multiplyTransform(currentTransform, {\n a: cosTheta,\n b: sinTheta,\n c: -sinTheta,\n d: cosTheta,\n x: 0,\n y: 0,\n });\n}\n\n/**\n * Applies a scale to the current standalone transform.\n *\n * @param {number} x\n * @param {number} [y=x]\n */\nexport function scale(x, y = x) {\n currentTransform = multiplyTransform(currentTransform, {\n a: x,\n b: 0,\n c: 0,\n d: y,\n x: 0,\n y: 0,\n });\n}\n\n/**\n * Installs the standalone runtime hooks used by core modules.\n */\nexport function initStandaloneRuntime() {\n setRuntime({\n usesRadians: () => currentAngleMode === \"radians\",\n fromDegrees: (angle) =>\n currentAngleMode === \"radians\" ? (angle * Math.PI) / 180 : angle,\n createColor: (...args) => {\n if (args.length === 1 && args[0]?._array) return args[0];\n return new Color(...args);\n },\n getAffineMatrix: () => currentTransform,\n });\n}\n","// =============================================================================\n// Adapter: Standalone Target Hooks\n// =============================================================================\n\nimport {\n setTargetRuntime,\n setTargetState,\n} from \"../../core/target.js\";\n\nlet activeTarget = null;\nlet isLoaded = false;\nlet activeDensity = 1;\nlet activeWidth = 0;\nlet activeHeight = 0;\n\nfunction isCanvasTarget(target) {\n return (\n typeof HTMLCanvasElement !== \"undefined\" &&\n target instanceof HTMLCanvasElement\n );\n}\n\nfunction isOffscreenCanvasTarget(target) {\n return (\n typeof OffscreenCanvas !== \"undefined\" &&\n target instanceof OffscreenCanvas\n );\n}\n\nfunction isSupportedTarget(target) {\n return isCanvasTarget(target) || isOffscreenCanvasTarget(target);\n}\n\nfunction getTargetContext(target) {\n return (\n target.getContext(\"webgl2\", { premultipliedAlpha: true }) ??\n target.getContext(\"webgl2\")\n );\n}\n\nfunction createRenderer(target, width, height, density) {\n const drawingContext = getTargetContext(target);\n if (!drawingContext) {\n throw new Error(\"brush.load(target) requires a canvas with a WebGL2 context.\");\n }\n\n return {\n canvas: target,\n drawingContext,\n width,\n height,\n pixelDensity: () => density,\n };\n}\n\nfunction applyLoadedTarget(target, width, height, density) {\n activeTarget = target;\n activeWidth = width;\n activeHeight = height;\n activeDensity = density;\n\n const renderer = createRenderer(target, width, height, density);\n setTargetState({\n Renderer: renderer,\n Cwidth: width,\n Cheight: height,\n Density: density,\n });\n isLoaded = true;\n}\n\n/**\n * Loads a standalone draw target from a DOM canvas or OffscreenCanvas.\n *\n * @param {HTMLCanvasElement|OffscreenCanvas} target\n */\nexport function load(target = activeTarget) {\n if (!isSupportedTarget(target)) {\n throw new Error(\n \"Standalone brush.load(target) requires an HTMLCanvasElement or OffscreenCanvas.\",\n );\n }\n\n applyLoadedTarget(target, target.width, target.height, 1);\n}\n\n/**\n * Creates a standalone DOM canvas, configures its backing resolution according\n * to the provided pixel density, appends it optionally to the DOM, and loads it\n * as the active brush target.\n *\n * @param {number} width Logical canvas width.\n * @param {number} height Logical canvas height.\n * @param {{pixelDensity?: number, parent?: string|Element|null, id?: string}} [options]\n * @returns {HTMLCanvasElement}\n */\nexport function createCanvas(width, height, options = {}) {\n if (typeof document === \"undefined\") {\n throw new Error(\"brush.createCanvas() requires a browser document.\");\n }\n\n const logicalWidth = Math.max(1, Math.round(width));\n const logicalHeight = Math.max(1, Math.round(height));\n const density = Math.max(1, Number(options.pixelDensity) || 1);\n const canvas = document.createElement(\"canvas\");\n\n canvas.width = Math.max(1, Math.round(logicalWidth * density));\n canvas.height = Math.max(1, Math.round(logicalHeight * density));\n canvas.style.width = `${logicalWidth}px`;\n canvas.style.height = `${logicalHeight}px`;\n if (options.id) canvas.id = options.id;\n\n if (options.parent) {\n const parent =\n typeof options.parent === \"string\"\n ? document.querySelector(options.parent)\n : options.parent;\n if (!parent) {\n throw new Error(`Could not find parent \"${options.parent}\" for brush.createCanvas().`);\n }\n parent.appendChild(canvas);\n }\n\n applyLoadedTarget(canvas, logicalWidth, logicalHeight, density);\n return canvas;\n}\n\n/**\n * Refreshes the standalone target density.\n *\n * Standalone targets currently use a fixed density of 1.\n *\n * @returns {number}\n */\nexport function syncDensity() {\n setTargetState({\n Cwidth: activeWidth,\n Cheight: activeHeight,\n Density: activeDensity,\n });\n return activeDensity;\n}\n\n/**\n * Ensures a standalone target has been loaded.\n */\nexport function isCanvasReady() {\n if (!isLoaded) {\n throw new Error(\n \"No standalone target loaded. Call brush.load(canvasOrOffscreenCanvas) first.\",\n );\n }\n}\n\n/**\n * Standalone build does not use p5 instance switching, so these are no-ops.\n */\nexport function instance() {}\nexport function activateInstance() {}\nexport function deactivateInstance() {}\n\n/**\n * Standalone build does not yet support framebuffer targets.\n *\n * @returns {null}\n */\nexport function getActiveFramebuffer() {\n return null;\n}\n\n/**\n * Returns whether the given target behaves like a framebuffer target.\n *\n * Standalone targets currently only accept canvases and offscreen canvases.\n *\n * @returns {boolean}\n */\nexport function isFramebufferTarget() {\n return arguments[0]?.__brushFramebuffer === true;\n}\n\nexport function initStandaloneTargetRuntime() {\n setTargetRuntime({\n load,\n syncDensity,\n isCanvasReady,\n instance,\n activateInstance,\n deactivateInstance,\n getActiveFramebuffer,\n isFramebufferTarget,\n });\n}\n","import {\n rr2,\n randInt2,\n sin,\n cos,\n toDegreesSigned,\n constrain,\n dist,\n calcAngle,\n intersectLines,\n} from \"./utils.js\";\nimport { Polygon } from \"./polygon.js\";\nimport { Plot } from \"./plot.js\";\n\n// =============================================================================\n// Section: Primitives and Geommetry\n// =============================================================================\n\n/**\n * Creates a Polygon from an array of points and calls its show() method.\n * Polygons ignore fields and won't be good for fills and masses\n * @param {Array<Array<number>>} pointsArray - Array of points [x, y, pressure]\n */\nexport function polygon(pointsArray) {\n // Create a new Polygon instance\n const polygon = new Polygon(pointsArray);\n polygon.show();\n}\n\n/**\n * Draws a rectangle on the canvas using path functions.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} w - Width.\n * @param {number} h - Height.\n * @param {boolean} [mode=\"corner\"] - \"corner\" (default) or \"center\".\n */\nexport function rect(x, y, w, h, mode = \"corner\") {\n if (mode === \"center\") {\n x -= w / 2;\n y -= h / 2;\n }\n beginShape(0);\n vertex(x, y);\n vertex(x + w, y);\n vertex(x + w, y + h);\n vertex(x, y + h);\n endShape(true);\n}\n\n/**\n * Draws a circle on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Circle radius.\n * @param {boolean} [r=false] - Randomizes segment lengths if true.\n */\nexport function circle(x, y, radius, r = false) {\n const p = new Plot(\"curve\");\n const arcLength = Math.PI * radius;\n const angleOffset = rr2(0, 360);\n const randomFactor = r ? () => 1 + r * 0.2 * rr2() : () => 1;\n\n // Divide circle into 4 segments\n for (let i = 0; i < 4; i++) {\n const angle = -90 * i + angleOffset;\n p.addSegment(\n angle * randomFactor(),\n (arcLength / 2) * randomFactor(),\n 1,\n true,\n );\n }\n\n // Optionally add a random final angle for the last segment\n if (r) {\n const randomAngle = r * randInt2(-5, 5);\n p.addSegment(\n angleOffset,\n Math.abs(randomAngle) * (Math.PI / 180) * radius,\n 1,\n true,\n );\n p.endPlot(randomAngle + angleOffset, 1, true);\n } else {\n p.endPlot(angleOffset, 1, true);\n }\n\n // Draw the circle\n const offsetX = x - radius * sin(angleOffset);\n const offsetY = y - radius * cos(-angleOffset);\n p.show(offsetX, offsetY, 1);\n}\n\n/**\n * Draws an arc on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Radius.\n * @param {number} start - Start angle in the current runtime angle units.\n * @param {number} end - End angle in the current runtime angle units.\n */\nexport function arc(x, y, radius, start, end) {\n const startDeg = toDegreesSigned(start);\n const endDeg = toDegreesSigned(end);\n const sweepDeg = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweepDeg === 0) return;\n\n const p = new Plot(\"curve\");\n const segmentCount = Math.max(1, Math.ceil(sweepDeg / 90));\n const segmentSweep = sweepDeg / segmentCount;\n const arcLength = (Math.PI * radius * segmentSweep) / 180;\n\n for (let i = 0; i < segmentCount; i++) {\n p.addSegment(startDeg + i * segmentSweep + 90, arcLength, 1, true);\n }\n p.endPlot(startDeg + sweepDeg + 90, 1, true);\n\n const startX = x + radius * cos(startDeg);\n const startY = y - radius * sin(startDeg);\n p.draw(startX, startY, 1);\n}\n\n// Variables for managing paths and strokes\nlet _current;\nlet _curvature;\n\nclass SubPath {\n constructor() {\n this.isClosed = false;\n this.curvature = _curvature;\n this.vert = [];\n }\n /**\n * Adds a vertex to this subpath.\n * @param {number} x\n * @param {number} y\n * @param {number} pressure\n */\n vertex(x, y, pressure) {\n this.vert.push([x, y, pressure]);\n }\n /**\n * Renders the subpath by creating a spline from its vertices.\n */\n show() {\n let plot = _createSpline(this.vert, this.curvature, this.isClosed);\n plot.show();\n }\n}\n\n/**\n * Begins a new path with a specified curvature.\n * @param {number} [curvature=0] - Curvature from 0 to 1.\n */\nexport function beginShape(curvature = 0) {\n _curvature = constrain(curvature, 0, 1);\n _current = new SubPath();\n}\n\n/**\n * Adds a line segment from the current point to the given coordinates.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} [pressure=1] - Pressure value.\n */\nexport function vertex(x, y, pressure = 1) {\n if (!_current) {\n throw new Error(\n \"vertex() called outside of beginShape()/endShape(). Call beginShape() first.\",\n );\n }\n _current.vertex(x, y, pressure);\n}\n\n/**\n * Ends the current path and renders all subpaths.\n */\nexport function endShape(close = false) {\n if (!_current) {\n throw new Error(\n \"endShape() called without beginShape(). Call beginShape() first.\",\n );\n }\n if (_current.vert.length < 2) {\n throw new Error(\n \"endShape() requires at least 2 vertices. Add more with vertex().\",\n );\n }\n if (close) {\n _current.vertex(..._current.vert[0]);\n _current.isClosed = true;\n }\n _current.show();\n _current = false;\n}\n\nlet _strokeArray, _strokeOrigin;\n\n/**\n * Begins a new stroke with a given type and starting position.\n * @param {string} type - Stroke type.\n * @param {number} x - Starting x.\n * @param {number} y - Starting y.\n */\nexport function beginStroke(type, x, y) {\n if (type !== \"curve\" && type !== \"segments\") {\n throw new Error(\n `beginStroke() type must be \"curve\" or \"segments\", got \"${type}\".`,\n );\n }\n _strokeOrigin = [x, y];\n _strokeArray = new Plot(type);\n}\n\n/**\n * Adds a segment to the stroke.\n * @param {number} angle - Segment angle.\n * @param {number} length - Segment length.\n * @param {number} pressure - Segment pressure.\n */\nexport function move(angle, length, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"move() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.addSegment(angle, length, pressure);\n}\n\n/**\n * Completes and renders the stroke.\n * @param {number} angle - End angle.\n * @param {number} pressure - End pressure.\n */\nexport function endStroke(angle, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"endStroke() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.endPlot(angle, pressure);\n _strokeArray.draw(_strokeOrigin[0], _strokeOrigin[1], 1);\n _strokeArray = false;\n}\n\n/**\n * Creates and draws a spline curve from an array of points.\n * @param {Array<Array<number>>} array_points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature from 0 to 1.\n */\nexport function spline(_array_points, _curvature = 0.5) {\n if (!_array_points || _array_points.length < 2) {\n throw new Error(\n \"spline() requires at least 2 points. Each point should be [x, y, pressure].\",\n );\n }\n let p = _createSpline(_array_points, _curvature);\n p.draw();\n}\n\n/**\n * Creates a new Plot object representing a spline curve.\n *\n * For curved segments (curvature > 0) with at least 3 points available,\n * the function either treats segments as straight (if their angles match)\n * or calculates control points to compute a circular arc.\n *\n * If no curvature is specified, a simple straight segment is used.\n *\n * @param {Array<Array<number>>} points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature value between 0 and 1.\n * @param {boolean} [close=false] - Whether to close the spline.\n * @returns {Plot} - The generated Plot object.\n */\nfunction _createSpline(points, curvature = 0.5, close = false) {\n const plotType = curvature === 0 ? \"segments\" : \"curve\";\n const p = new Plot(plotType);\n const PI2 = Math.PI * 2;\n\n // If closing the spline, add the second point to the end\n if (close && curvature !== 0) {\n points.push(points[1]);\n }\n\n if (points && points.length > 0) {\n let done = 0; // Tracks excess length from previous segment\n let pep, tep, pep2; // Variables used for initial calibration\n\n for (let i = 0; i < points.length - 1; i++) {\n // For curved segments (if curvature > 0 and there is at least 3 points ahead)\n if (curvature > 0 && i < points.length - 2) {\n const p1 = points[i];\n const p2 = points[i + 1];\n const p3 = points[i + 2];\n\n const d1 = dist(p1[0], p1[1], p2[0], p2[1]);\n const d2 = dist(p2[0], p2[1], p3[0], p3[1]);\n const a1 = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n const a2 = calcAngle(p2[0], p2[1], p3[0], p3[1]);\n\n // Compute the adjustment length based on curvature\n const curvAdjust = curvature * Math.min(d1, d2, 0.5 * Math.min(d1, d2));\n const dmax = Math.max(d1, d2);\n const s1 = d1 - curvAdjust;\n const s2 = d2 - curvAdjust;\n\n if (Math.floor(a1) === Math.floor(a2)) {\n // If angles are nearly the same, treat as a straight segment\n const temp = close ? (i === 0 ? 0 : d1 - done) : d1 - done;\n const temp2 = close ? (i === 0 ? 0 : d2 - pep2) : d2;\n\n p.addSegment(a1, temp, p1[2], true);\n if (i === points.length - 3) {\n p.addSegment(a2, temp2, p2[2], true);\n }\n\n done = 0;\n if (i === 0) {\n pep = d1;\n pep2 = curvAdjust;\n tep = points[1];\n done = 0;\n }\n } else {\n // For a curved segment, compute control points and arc segment details\n const point1 = {\n x: p2[0] - curvAdjust * cos(-a1),\n y: p2[1] - curvAdjust * sin(-a1),\n };\n const point2 = {\n x: point1.x + dmax * cos(-a1 + 90),\n y: point1.y + dmax * sin(-a1 + 90),\n };\n const point3 = {\n x: p2[0] + curvAdjust * cos(-a2),\n y: p2[1] + curvAdjust * sin(-a2),\n };\n const point4 = {\n x: point3.x + dmax * cos(-a2 + 90),\n y: point3.y + dmax * sin(-a2 + 90),\n };\n\n const intPt = intersectLines(point1, point2, point3, point4, true);\n const radius = dist(point1.x, point1.y, intPt.x, intPt.y);\n const halfDist = dist(point1.x, point1.y, point3.x, point3.y) / 2;\n const arcAngle = 2 * Math.asin(halfDist / radius) * (180 / Math.PI);\n const arcLength = (PI2 * radius * arcAngle) / 360;\n\n const temp = close ? (i === 0 ? 0 : s1 - done) : s1 - done;\n const temp2 =\n i === points.length - 3 ? (close ? pep - curvAdjust : s2) : 0;\n\n p.addSegment(a1, temp, p1[2], true);\n p.addSegment(a1, isNaN(arcLength) ? 0 : arcLength, p1[2], true);\n p.addSegment(a2, temp2, p2[2], true);\n\n done = curvAdjust;\n if (i === 0) {\n pep = s1;\n pep2 = curvAdjust;\n tep = [point1.x, point1.y];\n }\n }\n\n if (i === points.length - 3) {\n p.endPlot(a2, p2[2], true);\n }\n } else if (curvature === 0) {\n // If no curvature, add a simple straight segment\n const p1 = points[i];\n const p2 = points[i + 1];\n const d = dist(p1[0], p1[1], p2[0], p2[1]);\n const a = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n\n p.addSegment(a, d, p2[2], true);\n if (i === points.length - 2) {\n p.endPlot(a, 1, true);\n }\n }\n }\n\n p.origin = close && curvature !== 0 ? tep : points[0];\n }\n\n return p;\n}\n","import { State } from \"./color.js\";\nimport { intersectLines } from \"./utils.js\";\n\n// =============================================================================\n// Section: Polygon Class\n// =============================================================================\n\n/**\n * Represents a polygon with a set of vertices and provides methods for\n * intersection, drawing, filling, and hatching.\n */\nexport class Polygon {\n /**\n * Constructs the Polygon object from an array of points.\n * @param {Array} pointsArray - An array of points, where each point is an array of two numbers [x, y].\n * @param {boolean} [useRawVertices=false] - If true, uses the raw array as vertices.\n */\n constructor(pointsArray, useRawVertices = false) {\n this.a = pointsArray;\n this.vertices = useRawVertices\n ? pointsArray\n : pointsArray.map(([x, y]) => ({ x, y }));\n this.sides = this.vertices.map((v, i, arr) => [\n v,\n arr[(i + 1) % arr.length],\n ]);\n this._intersectionCache = {}; // Cache for intersection results\n }\n\n /**\n * Intersects a given line with the polygon, returning all intersection points.\n * @param {Object} line - The line to intersect with the polygon, having two properties 'point1' and 'point2'.\n * @returns {Array} An array of intersection points (each with 'x' and 'y' properties) or an empty array if no intersections.\n */\n intersect(line) {\n // Check if the result has been cached\n const cacheKey = `${line.point1.x},${line.point1.y}-${line.point2.x},${line.point2.y}`;\n if (this._intersectionCache[cacheKey]) {\n return this._intersectionCache[cacheKey];\n }\n const points = [];\n for (const [start, end] of this.sides) {\n const intersection = intersectLines(line.point1, line.point2, start, end);\n if (intersection) points.push(intersection);\n }\n this._intersectionCache[cacheKey] = points; // Cache the result\n return points;\n }\n\n /**\n * Displays the polygon with optional stroke, hatch, and fill effects.\n */\n show() {\n if (State.wash) this.wash();\n if (State.fill) this.fill();\n if (State.mass) this.mass();\n if (State.hatch) this.hatch();\n if (State.stroke) this.draw();\n }\n}","import { Cwidth, Cheight } from \"./target.js\";\nimport { State } from \"./color.js\";\nimport { toDegrees, map, rr2 } from \"./utils.js\";\nimport { Position, isFieldReady } from \"./flowfield.js\";\nimport { Polygon } from \"./polygon.js\";\n\n// =============================================================================\n// Section: Plot Class\n// =============================================================================\n\n/**\n * The Plot class represents a collection of segments that define shapes or paths.\n * It supports operations like adding segments, calculating angles and pressures,\n * and generating polygons based on the plot's structure.\n */\nexport class Plot {\n /**\n * Creates a new Plot.\n * @param {string} _type - The type of plot, \"curve\" or \"segments\".\n */\n constructor(_type) {\n this.segments = [];\n this.angles = [];\n this.pres = [];\n this.type = _type;\n this.dir = 0;\n this.calcIndex(0);\n this.pol = false;\n }\n\n /**\n * Adds a segment to the plot with specified angle, length, and pressure.\n * @param {number} _a - The angle of the segment.\n * @param {number} _length - The length of the segment.\n * @param {number} _pres - The pressure of the segment.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n addSegment(_a = 0, _length = 0, _pres = 1, _degrees = false) {\n if (this.angles.length > 0) this.angles.pop(); // Remove the last angle\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a); // Normalize angle\n this.angles.push(_a, _a); // Push angle twice for continuity\n this.pres.push(_pres);\n this.segments.push(_length);\n this.length = this.segments.reduce((sum, len) => sum + len, 0); // Update total length\n }\n\n /**\n * Finalizes the plot by setting the last angle and pressure.\n * @param {number} _a - The final angle.\n * @param {number} _pres - The final pressure.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n endPlot(_a = 0, _pres = 1, _degrees = false) {\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a);\n this.angles[this.angles.length - 1] = _a; // Update the last angle\n this.pres.push(_pres);\n }\n\n /**\n * Rotates the entire plot by a given angle.\n * @param {number} _a - The angle to rotate the plot.\n */\n rotate(_a) {\n this.dir = toDegrees(_a);\n }\n\n /**\n * Calculates the pressure at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated pressure.\n */\n pressure(_d) {\n // If the distance exceeds the plot length, return the last pressure\n if (_d > this.length) return this.pres[this.pres.length - 1];\n // Otherwise, calculate the pressure using the curving function\n return this.curving(this.pres, _d);\n }\n\n /**\n * Calculates the angle at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The calculated angle.\n */\n angle(_d) {\n // If the distance exceeds the plot length, return the last angle\n if (_d > this.length) return this.angles[this.angles.length - 1];\n // Calculate the index for the given distance\n this.calcIndex(_d);\n // Return the angle, adjusted for the plot type and direction\n return this.type === \"curve\"\n ? this.curving(this.angles, _d) + this.dir\n : this.angles[this.index] + this.dir;\n }\n\n /**\n * Interpolates values between segments for smooth transitions.\n * @param {Array<number>} array - The array to interpolate within.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated value.\n */\n curving(array, _d) {\n let map0 = array[this.index];\n let map1 = array[this.index + 1] ?? map0;\n if (Math.abs(map1 - map0) > 180) {\n if (map1 > map0) map1 = -(360 - map1);\n else map0 = -(360 - map0);\n }\n return map(_d - this.suma, 0, this.segments[this.index], map0, map1, true);\n }\n\n /**\n * Calculates the current index of the plot based on the distance.\n * @param {number} _d - The distance along the plot.\n */\n calcIndex(_d) {\n this.index = -1;\n this.suma = 0;\n let d = 0;\n while (d <= _d) {\n this.suma = d;\n d += this.segments[this.index + 1];\n this.index++;\n }\n return this.index;\n }\n\n /**\n * Generates a polygon based on the plot.\n * @param {number} _x - The x-coordinate for the starting point.\n * @param {number} _y - The y-coordinate for the starting point.\n * @param {number} _scale - The scale factor for the polygon.\n * @param {number} _side - The side factor for the polygon.\n * @returns {Polygon} - The generated polygon.\n */\n genPol(_x, _y, _scale = 1, _side) {\n isFieldReady(); // Ensure that the drawing environment is prepared\n const step = _side < 0 ? 4 : 1;\n const vertices = [];\n const numSteps = Math.round(this.length / step);\n const pos = new Position(_x + Cwidth / 2, _y + Cheight / 2);\n let pside = 0;\n let prevIdx = 0;\n\n for (let i = 0; i < numSteps; i++) {\n pos.plotTo(this, step, step);\n const idx = this.calcIndex(pos.plotted);\n pside += step;\n let maxSize = _side <= 0 ? 8 : Math.max(this.segments[idx] * _side * rr2(0.7, 1.3), 20);\n if ((pside >= maxSize || idx >= prevIdx) && pos.x) {\n vertices.push([pos.x - Cwidth / 2, pos.y - Cheight / 2]);\n pside = 0;\n if (idx >= prevIdx) prevIdx++;\n }\n }\n return new Polygon(vertices);\n }\n\n /**\n * Displays the plot with optional stroke, hatch, and fill effects.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\n show(x, y, scale = 1) {\n if (State.wash) this.wash(x, y, scale);\n if (State.fill) this.fill(x, y, scale);\n if (State.mass) this.mass(x, y, scale);\n if (State.hatch) this.hatch(x, y, scale);\n if (State.stroke) this.draw(x, y, scale);\n }\n}\n","// =============================================================================\n// Stroke Runtime Hooks\n// =============================================================================\n\nlet strokeRuntime = {\n createTipSurface: () => {\n throw new Error(\"No stroke runtime adapter registered.\");\n },\n loadImageTip: () => {\n throw new Error(\"No stroke runtime adapter registered.\");\n },\n};\n\n/**\n * Registers or updates host stroke hooks used by brush-tip loading code.\n *\n * @param {object} hooks\n */\nexport function setStrokeRuntime(hooks) {\n strokeRuntime = { ...strokeRuntime, ...hooks };\n}\n\nexport const createTipSurface = (width, height) =>\n strokeRuntime.createTipSurface(width, height);\nexport const loadImageTip = (src, imageToWhite) =>\n strokeRuntime.loadImageTip(src, imageToWhite);\n","import * as Color from \"../core/color.js\";\nimport { createFramebuffer } from \"../core/compositor_runtime.js\";\n\nlet isStrokeCompositeRegistered = false;\nconst DIRTY_BRUSH_PADDING = 2;\n\n// =============================================================================\n// Section: Helpers\n// =============================================================================\n/**\n * Returns whether the current stroke mask framebuffer must be recreated.\n * This happens when the renderer has no mask yet, or when the canvas size or\n * pixel density changed since the last allocation.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {boolean} True when the stroke mask must be rebuilt.\n */\nfunction needsStrokeMask(Renderer, Cwidth, Cheight, Density) {\n return (\n !Renderer.glMask ||\n Renderer.glMask.width !== Cwidth ||\n Renderer.glMask.height !== Cheight ||\n (typeof Renderer.glMask.pixelDensity === \"function\" &&\n Renderer.glMask.pixelDensity() !== Density)\n );\n}\n\n// =============================================================================\n// Section: Resource Management\n// =============================================================================\n/**\n * Ensures the stroke compositor owns a framebuffer-backed mask with the current\n * canvas dimensions. Stroke stamps are rendered into this mask in WebGL before\n * being blended into the main target.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {object} The framebuffer used as stroke mask.\n */\nexport function ensureStrokeCompositeResources(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n) {\n if (needsStrokeMask(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.glMask?.remove) Renderer.glMask.remove();\n Renderer.glMask = createFramebuffer(Renderer, {\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n }\n\n Renderer.glMask.dirtyRect ??= null;\n Renderer.glMask.isDrawn ??= false;\n return Renderer.glMask;\n}\n\n// =============================================================================\n// Section: Mask Lifecycle\n// =============================================================================\n/**\n * Clears the current stroke mask and resets its bookkeeping flags.\n *\n * @param {object|null} target - Stroke mask framebuffer.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n */\nexport function clearStrokeMask(target, clearTarget) {\n if (!target) return;\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\n}\n\n// =============================================================================\n// Section: Composite Bounds\n// =============================================================================\n/**\n * Returns the rect that should be composited from the stroke mask into the\n * main canvas. Stroke bounds are normally tight dirty rects, but when drawing\n * into an active framebuffer we keep the result conservative and composite the\n * full target.\n *\n * @param {object|null} target - Stroke mask framebuffer.\n * @param {Function} getActiveFramebuffer - Returns the currently bound framebuffer.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} expandDirtyRect - Expands a rect by a constant padding.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @param {number} padding - Extra brush padding in pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\nexport function getStrokeCompositeRect(\n target,\n getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n if (getActiveFramebuffer()) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(target.dirtyRect, DIRTY_BRUSH_PADDING),\n );\n}\n\n/**\n * Returns the resource that should be bound to the blend shader's `u_mask`\n * uniform for stroke compositing.\n *\n * @param {object} _Renderer - Active host renderer.\n * @param {object} mask - Stroke mask framebuffer.\n * @returns {object} Stroke mask framebuffer.\n */\nexport function getStrokeShaderMask(_Renderer, mask) {\n return mask;\n}\n\n// =============================================================================\n// Section: Registration\n// =============================================================================\n/**\n * Registers the stroke compositor with the shared color/composite core.\n * Safe to call multiple times.\n */\nexport function initStrokeComposite() {\n if (isStrokeCompositeRegistered) return;\n Color.registerStrokeComposite?.({\n ensureResources: ensureStrokeCompositeResources,\n clearMask: clearStrokeMask,\n getCompositeRect: getStrokeCompositeRect,\n getShaderMask: getStrokeShaderMask,\n });\n isStrokeCompositeRegistered = true;\n}\n","/**\n * Compiles a shader program from the given vertex and fragment sources.\n * @param {WebGL2RenderingContext} gl - The WebGL2 context.\n * @param {string} vert - Vertex shader source.\n * @param {string} frag - Fragment shader source.\n * @returns {WebGLProgram} The compiled and linked program.\n */\nexport const createProgram = (gl, vert, frag) => {\n const p = gl.createProgram();\n for (let [t, src] of [\n [gl.VERTEX_SHADER, vert],\n [gl.FRAGMENT_SHADER, frag],\n ]) {\n const s = gl.createShader(t);\n gl.shaderSource(s, src);\n gl.compileShader(s);\n gl.attachShader(p, s);\n }\n gl.linkProgram(p);\n return p;\n};\n","// =============================================================================\n// Renderer Runtime Hooks\n// =============================================================================\n\n/**\n * Direct-render hooks used by modules that issue raw WebGL commands.\n *\n * These hooks are intentionally narrow:\n * - begin drawing into an offscreen GL mask target\n * - restore the previous draw target afterward\n * - reset any host-side shader/program bookkeeping after direct GL usage\n */\n\nlet rendererRuntime = {\n beginDirectMaskDraw: () => {\n throw new Error(\"No renderer runtime adapter registered.\");\n },\n endDirectMaskDraw: () => {\n throw new Error(\"No renderer runtime adapter registered.\");\n },\n resetDirectShaderTracking: () => {},\n};\n\n/**\n * Registers or updates host renderer hooks used by direct WebGL drawing paths.\n *\n * @param {object} hooks\n */\nexport function setRendererRuntime(hooks) {\n rendererRuntime = { ...rendererRuntime, ...hooks };\n}\n\nexport const beginDirectMaskDraw = (renderer, gl, target) =>\n rendererRuntime.beginDirectMaskDraw(renderer, gl, target);\nexport const endDirectMaskDraw = (renderer, gl, state) =>\n rendererRuntime.endDirectMaskDraw(renderer, gl, state);\nexport const resetDirectShaderTracking = (renderer, gl) =>\n rendererRuntime.resetDirectShaderTracking(renderer, gl);\n","// =============================================================================\n// Module: GL Draw\n// =============================================================================\n/**\n * The GL Draw module batches brush primitives for WebGL2 rendering. It initializes\n * the shader programs and buffers used by circle-based brushes and image-tip brushes,\n * then flushes those queues into the shared framebuffer-backed brush mask.\n */\n\nimport { Cwidth, Cheight, Density, Renderer } from \"../core/target.js\";\nimport {\n Mix,\n isMixReady,\n State,\n} from \"../core/color.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport {\n beginDirectMaskDraw,\n endDirectMaskDraw,\n resetDirectShaderTracking,\n} from \"../core/renderer_runtime.js\";\nimport { getAffineMatrix } from \"../core/runtime.js\";\nimport vertSrc from \"./shader.vert\";\nimport fragSrc from \"./shader.frag\";\nimport imgVertSrc from \"./image.vert\";\nimport imgFragSrc from \"./image.frag\";\n\n// =============================================================================\n// Section: Initialization and Setup\n// =============================================================================\n\n// Module state\nlet isLoaded = false,\n gl,\n framebufferProjMatrix,\n vao,\n buf,\n program;\nlet loadedWidth = 0,\n loadedHeight = 0;\nlet brushMaskTarget = null;\nconst Attr = {},\n Frag = {};\n\n// Cached matrix values — snapshotted once per stroke in snapshotMatrix()\nlet _ma = 1,\n _mb = 0,\n _mc = 0,\n _md = 1,\n _mx = 0,\n _my = 0,\n _halfW = 0,\n _halfH = 0,\n _scale = 1,\n _density = 1;\n\n/**\n * Snapshots the current runtime affine transform. Call once at the start of each stroke.\n */\nexport function snapshotMatrix() {\n const m = getAffineMatrix();\n _ma = m.a;\n _mb = m.b;\n _mc = m.c;\n _md = m.d;\n _mx = m.x;\n _my = m.y;\n _halfW = Cwidth / 2;\n _halfH = Cheight / 2;\n _scale = Math.sqrt(_ma * _ma + _mb * _mb);\n _density = Density;\n}\n\n// Pre-allocated flat buffer for circle data (x, y, radius, alpha per circle)\nconst INITIAL_CAPACITY = 2048;\nlet circleData = new Float32Array(INITIAL_CAPACITY * 4);\nlet circleCount = 0;\nlet bufferCapacity = INITIAL_CAPACITY;\nlet gpuBufferSize = INITIAL_CAPACITY * 4 * 4; // bytes allocated on GPU\nlet circleDirtyRect = null;\n\n// ---------------------------------------------------------------------------\n// Image instancing state\n// ---------------------------------------------------------------------------\nlet imgProgram = null;\nlet imgVao = null;\nlet imgCornerBuf = null;\nlet imgInstanceBuf = null;\nconst imgAttr = {};\nconst imgFrag = {};\nlet imgGpuSize = 0;\n\nconst IMG_FLOATS = 5; // screenX, screenY, halfSize, angle, alpha — per stamp\nconst IMG_INIT_CAP = 256;\nlet imgData = new Float32Array(IMG_INIT_CAP * IMG_FLOATS);\nlet imgCount = 0;\nlet imgCapacity = IMG_INIT_CAP;\nlet imgDirtyRect = null;\n\n// Texture cache: src string → WebGLTexture (cleared whenever the GL context changes)\nconst texCache = new Map();\n\n// Static unit-quad corners for gl.TRIANGLE_STRIP in quad-local space.\nconst QUAD_CORNERS = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]);\n\nfunction ensureBrushMaskTarget() {\n const rendererMask = Renderer?.glMask;\n if (!rendererMask) return null;\n brushMaskTarget = rendererMask;\n brushMaskTarget.dirtyRect ??= null;\n brushMaskTarget.isDrawn ??= false;\n Mix.glMask = brushMaskTarget;\n return brushMaskTarget;\n}\n\nfunction getProjectionMatrix() {\n return framebufferProjMatrix;\n}\n\nfunction beginMaskTarget() {\n return beginDirectMaskDraw(Renderer, gl, Mix.glMask);\n}\n\nfunction endMaskTarget(state) {\n endDirectMaskDraw(Renderer, gl, state);\n}\n\nfunction accumulateDirtyRect(currentRect, minX, minY, maxX, maxY) {\n if (!currentRect) return { minX, minY, maxX, maxY };\n if (minX < currentRect.minX) currentRect.minX = minX;\n if (minY < currentRect.minY) currentRect.minY = minY;\n if (maxX > currentRect.maxX) currentRect.maxX = maxX;\n if (maxY > currentRect.maxY) currentRect.maxY = maxY;\n return currentRect;\n}\n\n/**\n * Initializes WebGL objects if not done already.\n */\nexport function isReady() {\n isMixReady();\n ensureBrushMaskTarget();\n\n const nextGl = Renderer.drawingContext;\n const needsContextRefresh = !isLoaded || gl !== nextGl;\n const needsProjectionRefresh =\n needsContextRefresh || loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (needsProjectionRefresh) {\n framebufferProjMatrix = new Float32Array([\n 2 / Cwidth,\n 0,\n 0,\n 0,\n 0,\n 2 / Cheight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n -1,\n 0,\n 1,\n ]);\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n }\n\n if (!needsContextRefresh) return;\n\n gl = nextGl;\n\n // Create shader program and initialize\n program = createProgram(gl, vertSrc, fragSrc);\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n // Cache attribute and uniform locations\n [\"a_position\", \"a_radius\", \"a_alpha\"].forEach(\n (n) => (Attr[n] = gl.getAttribLocation(program, n)),\n );\n [\"u_matrix\", \"u_color\"].forEach(\n (n) => (Frag[n] = gl.getUniformLocation(program, n)),\n );\n\n // Create persistent VAO and VBO\n vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n\n buf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n gl.bufferData(gl.ARRAY_BUFFER, circleData.byteLength, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n\n // Set up vertex attributes (only needs to happen once with persistent VAO)\n const stride = 16; // 4 floats × 4 bytes\n gl.enableVertexAttribArray(Attr.a_position);\n gl.vertexAttribPointer(Attr.a_position, 2, gl.FLOAT, false, stride, 0);\n gl.enableVertexAttribArray(Attr.a_radius);\n gl.vertexAttribPointer(Attr.a_radius, 1, gl.FLOAT, false, stride, 8);\n gl.enableVertexAttribArray(Attr.a_alpha);\n gl.vertexAttribPointer(Attr.a_alpha, 1, gl.FLOAT, false, stride, 12);\n\n gl.bindVertexArray(null);\n\n // ------------------------------------------------------------------\n // Image-tip instancing program\n // ------------------------------------------------------------------\n texCache.clear();\n\n imgProgram = createProgram(gl, imgVertSrc, imgFragSrc);\n [\"a_corner\", \"a_pos\", \"a_size\", \"a_angle\", \"a_alpha\"].forEach(\n (n) => (imgAttr[n] = gl.getAttribLocation(imgProgram, n)),\n );\n [\"u_proj\", \"u_color\", \"u_tex\"].forEach(\n (n) => (imgFrag[n] = gl.getUniformLocation(imgProgram, n)),\n );\n\n imgVao = gl.createVertexArray();\n gl.bindVertexArray(imgVao);\n\n // Static corner VBO (per-vertex, no divisor)\n imgCornerBuf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, imgCornerBuf);\n gl.bufferData(gl.ARRAY_BUFFER, QUAD_CORNERS, gl.STATIC_DRAW);\n gl.enableVertexAttribArray(imgAttr.a_corner);\n gl.vertexAttribPointer(imgAttr.a_corner, 2, gl.FLOAT, false, 0, 0);\n\n // Instance data VBO (per-instance)\n imgInstanceBuf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, imgInstanceBuf);\n gl.bufferData(gl.ARRAY_BUFFER, imgData.byteLength, gl.DYNAMIC_DRAW);\n imgGpuSize = imgData.byteLength;\n\n const istride = IMG_FLOATS * 4; // 20 bytes\n gl.enableVertexAttribArray(imgAttr.a_pos);\n gl.vertexAttribPointer(imgAttr.a_pos, 2, gl.FLOAT, false, istride, 0);\n gl.vertexAttribDivisor(imgAttr.a_pos, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_size);\n gl.vertexAttribPointer(imgAttr.a_size, 1, gl.FLOAT, false, istride, 8);\n gl.vertexAttribDivisor(imgAttr.a_size, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_angle);\n gl.vertexAttribPointer(imgAttr.a_angle, 1, gl.FLOAT, false, istride, 12);\n gl.vertexAttribDivisor(imgAttr.a_angle, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_alpha);\n gl.vertexAttribPointer(imgAttr.a_alpha, 1, gl.FLOAT, false, istride, 16);\n gl.vertexAttribDivisor(imgAttr.a_alpha, 1);\n\n gl.bindVertexArray(null);\n\n isLoaded = true;\n}\n\n// =============================================================================\n// Section: Drawing Primitives\n// =============================================================================\n\n/**\n * Queue a circle to be drawn with the specified parameters.\n * Data is written directly into a flat Float32Array to avoid object allocation.\n * Applies the full 2D affine transform (rotation + scale + translation) from\n * the current runtime transform so that brush.rotate() and brush.scale() work correctly.\n */\nexport function circle(x, y, diameter, alpha) {\n // Grow buffer if needed\n if (circleCount >= bufferCapacity) {\n bufferCapacity *= 2;\n const newData = new Float32Array(bufferCapacity * 4);\n newData.set(circleData);\n circleData = newData;\n }\n\n // x/y arrive in \"position space\": user coords + (Cwidth/2, Cheight/2).\n // Subtract the offset to recover user coords, apply the full matrix, then re-add\n // the offset so the result is in screen pixel space [0..Cwidth, 0..Cheight].\n const px = x - _halfW;\n const py = y - _halfH;\n\n const offset = circleCount * 4;\n const screenX = _ma * px + _mc * py + _mx + _halfW;\n const screenY = _mb * px + _md * py + _my + _halfH;\n const radius = (_density * diameter * _scale) / 2;\n\n circleData[offset] = screenX;\n circleData[offset + 1] = screenY;\n // Scale the diameter by the matrix's scale factor (length of the transformed x-axis)\n circleData[offset + 2] = radius;\n circleData[offset + 3] = alpha / 255;\n\n const dScreenX = screenX * _density;\n const dScreenY = screenY * _density;\n circleDirtyRect = accumulateDirtyRect(\n circleDirtyRect,\n dScreenX - radius - 1,\n dScreenY - radius - 1,\n dScreenX + radius + 1,\n dScreenY + radius + 1,\n );\n\n circleCount++;\n}\n\n/**\n * Queue an image stamp to be drawn with instanced rendering.\n * Accepts the same coordinate conventions as circle(): x/y in position space\n * (user coords + Cwidth/2, Cheight/2), size in user-coord units, alpha in [0..255].\n * @param {number} x - X in position space.\n * @param {number} y - Y in position space.\n * @param {number} size - Full stamp diameter in user-coord units.\n * @param {number} angle - Rotation in radians.\n * @param {number} alpha - Opacity [0..255].\n * @param {number} [extraPadding=0] - Conservative extra padding in user units.\n */\nexport function stampImage(x, y, size, angle, alpha, extraPadding = 0) {\n if (imgCount >= imgCapacity) {\n imgCapacity *= 2;\n const next = new Float32Array(imgCapacity * IMG_FLOATS);\n next.set(imgData);\n imgData = next;\n }\n\n const px = x - _halfW;\n const py = y - _halfH;\n const screenX = _ma * px + _mc * py + _mx + _halfW;\n const screenY = _mb * px + _md * py + _my + _halfH;\n const halfSize = (_density * size * _scale) / 2;\n const extraRadius = _density * extraPadding * _scale;\n\n const base = imgCount * IMG_FLOATS;\n imgData[base] = screenX;\n imgData[base + 1] = screenY;\n imgData[base + 2] = halfSize;\n imgData[base + 3] = angle;\n imgData[base + 4] = alpha / 255;\n\n // Bounding box: rotated square worst-case = circle of radius halfSize * √2\n const dScreenX = screenX * _density;\n const dScreenY = screenY * _density;\n const boundsRadius = halfSize * 1.42 + extraRadius;\n imgDirtyRect = accumulateDirtyRect(\n imgDirtyRect,\n dScreenX - boundsRadius - 1,\n dScreenY - boundsRadius - 1,\n dScreenX + boundsRadius + 1,\n dScreenY + boundsRadius + 1,\n );\n\n imgCount++;\n}\n\n/**\n * Flush all queued image stamps in a single instanced draw call.\n * @param {object} p5img - The preprocessed brush-tip image/canvas (from T.tips).\n * @param {string} src - The image src string, used as the texture cache key.\n */\nexport function glDrawImages(p5img, src) {\n if (imgCount === 0) return;\n\n Mix.glMask.isDrawn = true;\n const targetState = beginMaskTarget();\n\n // Lazy-create the WebGL texture from the tip canvas on first use.\n let tex = texCache.get(src);\n if (!tex) {\n tex = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, p5img.canvas);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n texCache.set(src, tex);\n }\n\n gl.useProgram(imgProgram);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.uniform1i(imgFrag.u_tex, 0);\n\n const color = State.stroke.color._array;\n gl.uniform4f(imgFrag.u_color, ...color);\n gl.uniformMatrix4fv(imgFrag.u_proj, false, getProjectionMatrix());\n\n gl.bindVertexArray(imgVao);\n gl.bindBuffer(gl.ARRAY_BUFFER, imgInstanceBuf);\n\n const byteCount = imgCount * IMG_FLOATS * 4;\n const dataView = imgData.subarray(0, imgCount * IMG_FLOATS);\n if (byteCount > imgGpuSize) {\n gl.bufferData(gl.ARRAY_BUFFER, imgData, gl.DYNAMIC_DRAW);\n imgGpuSize = imgData.byteLength;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);\n }\n\n gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, imgCount);\n gl.flush();\n\n gl.bindVertexArray(null);\n gl.bindTexture(gl.TEXTURE_2D, null);\n endMaskTarget(targetState);\n\n if (imgDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, imgDirtyRect);\n imgDirtyRect = null;\n }\n\n imgCount = 0;\n\n // Let the host adapter know we changed the active program.\n resetDirectShaderTracking(Renderer, gl);\n}\n\n/**\n * Removes a cached GL texture by key, forcing re-upload on next draw.\n * Call this when a custom tip function changes after brush.add().\n */\nexport function invalidateTexEntry(key) {\n const tex = texCache.get(key);\n if (tex && gl) gl.deleteTexture(tex);\n texCache.delete(key);\n}\n\n/**\n * Draw all queued circles using WebGL\n */\nexport function glDraw() {\n if (circleCount === 0) return;\n\n Mix.glMask.isDrawn = true;\n const targetState = beginMaskTarget();\n\n const color = State.stroke.color._array;\n\n // Re-activate our shader in case host drawing switched programs.\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n gl.bindVertexArray(vao);\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n\n // Upload vertex data — reallocate GPU buffer only if needed\n const byteCount = circleCount * 16; // 4 floats × 4 bytes\n const dataView = circleData.subarray(0, circleCount * 4);\n if (byteCount > gpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, circleData, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);\n }\n\n // Set uniforms and draw\n gl.uniform4f(Frag.u_color, ...color);\n gl.uniformMatrix4fv(Frag.u_matrix, false, getProjectionMatrix());\n gl.drawArrays(gl.POINTS, 0, circleCount);\n gl.flush();\n\n gl.bindVertexArray(null);\n endMaskTarget(targetState);\n\n if (circleDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, circleDirtyRect);\n circleDirtyRect = null;\n }\n\n // Reset queue (no deallocation)\n circleCount = 0;\n\n // We called gl.useProgram() directly, bypassing host shader tracking.\n // Reset it so the host is forced to re-activate its own shader next time\n // it draws — otherwise it may skip gl.useProgram() and set uniforms on the\n // wrong active program, causing \"location is not from the associated program\".\n resetDirectShaderTracking(Renderer, gl);\n}\n","// =============================================================================\n// Module: Brush\n// =============================================================================\n/**\n * The Brush module provides a comprehensive set of functions and classes for\n * simulating various drawing tools ranging from pens, markers, pencils, to\n * custom image-based brushes. This module controls brush properties such as\n * weight, color, vibration, and spacing, and manages the drawing process through\n * stateful methods that enable features like pressure sensitivity, clipping, and\n * blending. By supporting multiple brush types and dynamic parameter adjustments,\n * the Brush module facilitates the creation of realistic and expressive stroke effects.\n */\n\n// Core imports\nimport { Cwidth, Cheight, Renderer, isCanvasReady } from \"../core/target.js\";\nimport {\n Mix,\n State,\n} from \"../core/color.js\";\nimport {\n rr,\n map,\n dist,\n randInt,\n calcAngle,\n toDegrees,\n gaussian,\n rArray,\n noise,\n _onSeed, \n cos,\n sin\n} from \"../core/utils.js\";\nimport { createColor } from \"../core/runtime.js\";\nimport { Position, isFieldReady } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { createTipSurface, loadImageTip } from \"./runtime.js\";\n\n// Internal module imports\nimport { initStrokeComposite } from \"./composite.js\";\nimport {\n isReady,\n glDraw,\n glDrawImages,\n circle,\n stampImage,\n invalidateTexEntry,\n snapshotMatrix,\n} from \"./gl_draw.js\";\n\ninitStrokeComposite(); // Register the stroke composite system for offscreen mask rendering and compositing.\n\n// ---------------------------------------------------------------------------\n// Brush State and Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Global stroke state settings.\n */\nState.stroke = {\n color: null,\n weight: 1,\n type: \"HB\",\n isActive: false,\n opacity: 1,\n};\n\nlet list = new Map();\n\nconst DEFAULT_CUSTOM_PRESSURE_VARIATION = {\n offset: 0.08,\n scale: 0.08,\n warp: 0.06,\n tilt: 0.06,\n};\n\n/**\n * Retrieves a shallow copy of the current stroke state.\n * @returns {object} The stroke state.\n */\nexport function BrushState() {\n return { ...State.stroke };\n}\n\n/**\n * Updates the stroke state.\n * @param {object} state - The new stroke state.\n */\nexport function BrushSetState(state) {\n State.stroke = { ...state };\n}\n\n// =============================================================================\n// Section: Brush Manager\n// =============================================================================\n\n/**\n * Adds a new brush with the specified parameters to the brush list.\n * @param {string} name - The unique name for the new brush.\n * @param {object} params - The parameters defining the brush behavior and appearance.\n */\n/**\n * Normalizes the pressure parameter to the internal { type, min_max, curve } format.\n * Accepts:\n * [start, end] — linear ramp between two pressure values\n * [start, mid, end] — piecewise linear (e.g. [1.5, 0.5, 1.5] for U-curve)\n * (t) => value — custom function, t ∈ [0,1], return value ∈ [0,1]\n * { mode: \"gaussian\", curve, min_max } — advanced built-in pressure profile\n * { curve, min_max } — legacy gaussian format, preserved for compatibility\n */\nexport function normalizePressure(p) {\n if (!p) return p;\n if (typeof p === \"function\")\n return {\n type: \"custom\",\n min_max: [0, 1],\n curve: p,\n variation: { ...DEFAULT_CUSTOM_PRESSURE_VARIATION },\n };\n if (typeof p === \"object\" && !Array.isArray(p)) {\n if (p.type === \"custom\" || p.mode === \"custom\") {\n const { mode, ...rest } = p;\n return {\n ...rest,\n type: \"custom\",\n variation: {\n ...DEFAULT_CUSTOM_PRESSURE_VARIATION,\n ...(rest.variation ?? {}),\n },\n };\n }\n if (\n p.type === \"gaussian\" ||\n p.mode === \"gaussian\" ||\n (Array.isArray(p.curve) && Array.isArray(p.min_max))\n ) {\n return {\n ...p,\n type: \"gaussian\",\n curve: p.curve,\n min_max: p.min_max,\n };\n }\n return p;\n }\n if (Array.isArray(p)) {\n const [s, m, e] = p.length === 2 ? [p[0], (p[0] + p[1]) / 2, p[1]] : p;\n const min = Math.min(s, m, e),\n max = Math.max(s, m, e);\n const range = max - min || 1;\n const [ns, nm, ne] = [\n (s - min) / range,\n (m - min) / range,\n (e - min) / range,\n ];\n return {\n type: \"custom\",\n min_max: [min, max],\n variation: { ...DEFAULT_CUSTOM_PRESSURE_VARIATION },\n curve: (t) =>\n t < 0.5 ? ns + (nm - ns) * t * 2 : nm + (ne - nm) * (t - 0.5) * 2,\n };\n }\n}\n\nexport function add(name, params) {\n const validTypes = [\"marker\", \"custom\", \"image\", \"spray\"];\n params.type = validTypes.includes(params.type) ? params.type : \"default\";\n if (params.markerTip === undefined) params.markerTip = true;\n if (params.noise === undefined) params.noise = 0.3;\n params.noise = Math.max(0, Math.min(1, params.noise));\n // Accept legacy param names for backward compatibility\n if (params.vibration !== undefined && params.scatter === undefined)\n params.scatter = params.vibration;\n if (params.definition !== undefined && params.sharpness === undefined)\n params.sharpness = params.definition;\n if (params.quality !== undefined && params.grain === undefined)\n params.grain = params.quality;\n params.pressure = normalizePressure(params.pressure);\n if (params.type === \"custom\") {\n if (typeof params.tip !== \"function\") {\n throw new Error(`Brush \"${name}\" is type \"custom\" but is missing a tip function.`);\n }\n // Rasterise the tip once into a 500×500 P2D buffer.\n // Users draw in a 100×100 coordinate space (origin at centre);\n // dark fills/strokes → high opacity, light/white → transparent.\n const key = `custom::${name}`;\n invalidateTexEntry(key); // discard stale GPU texture if tip changed\n const g = createTipSurface(500, 500);\n g.pixelDensity(1);\n g.background(255);\n g.noSmooth();\n g.push();\n g.translate(250, 250); // centre origin\n g.scale(5); // 100 user units → 500 px\n g.noStroke();\n params.tip(g);\n g.pop();\n T.imageToWhite(g); // dark → high alpha, RGB → white for tint\n T.tips.set(key, g);\n params.tipKey = key;\n list.set(name, { param: params, colors: [], buffers: [] });\n return;\n }\n if (params.type === \"image\") {\n if (!params.image || !params.image.src) {\n throw new Error(\n `Brush \"${name}\" is type \"image\" but is missing params.image.src. Example: image: { src: \"./tip.jpg\" }`,\n );\n }\n T.add(params.image.src);\n list.set(name, { param: params, colors: [], buffers: [] });\n return T.load(); // returns a Promise; only loads images not yet loaded\n }\n list.set(name, { param: params, colors: [], buffers: [] });\n}\n\n/**\n * Retrieves the list of available brush names.\n * @returns {Array<string>} Array of brush names.\n */\nexport function box() {\n return [...list.keys()];\n}\n\nexport function getBrushParams(brushName) {\n return list.get(brushName)?.param ?? null;\n}\n\n/**\n * Scales standard brush parameters by the provided factor.\n * @param {number} scaleFactor - The scaling factor to apply.\n */\nexport function scaleBrushes(scaleFactor) {\n for (const { param } of list.values()) {\n if (param) {\n param.weight *= scaleFactor;\n param.scatter *= scaleFactor;\n param.spacing *= scaleFactor;\n }\n }\n}\n\n/**\n * Sets the current brush type by name.\n * @param {string} brushName - The name of the brush.\n */\nexport function pick(brushName) {\n if (!list.has(brushName)) {\n throw new Error(\n `Brush \"${brushName}\" not found. Available brushes: ${[...list.keys()].join(\", \")}.`,\n );\n }\n State.stroke.type = brushName;\n}\n\n/**\n * Sets the stroke style (color) for the current brush.\n * @param {number|string|Color} r - Red component, CSS color string, or Color object.\n * @param {number} [g] - Green component.\n * @param {number} [b] - Blue component.\n */\nexport function stroke(r, g, b) {\n isCanvasReady();\n State.stroke.color = createColor(...arguments);\n State.stroke.isActive = true;\n}\n\n/**\n * Sets the brush weight (thickness).\n * @param {number} weight - The weight value.\n */\nexport function strokeWeight(weight) {\n State.stroke.weight = weight;\n}\n\n/**\n * Sets the current brush with name, color, and weight.\n * @param {string} brushName - The brush name.\n * @param {string|Color} color - The brush color.\n * @param {number} [weight=1] - The brush weight.\n */\nexport function set(brushName, color, weight = 1) {\n pick(brushName);\n stroke(color);\n strokeWeight(weight);\n}\n\n/**\n * Disables the stroke effect.\n */\nexport function noStroke() {\n State.stroke.isActive = false;\n}\n\n/**\n * Defines a clipping region for strokes.\n * The region uses the same coordinate space as brush drawing commands,\n * with the current runtime transform captured at call time.\n * @param {number[]} region - Array as [x1, y1, x2, y2] defining the clipping region.\n */\nexport function clip(region) {\n isCanvasReady();\n return region;\n}\n\n/**\n * Disables the clipping region.\n */\nexport function noClip() {\n return;\n}\n\n// ---------------------------------------------------------------------------\n// Drawing Variables and Functions\n// ---------------------------------------------------------------------------\nlet _position, _length, _plot, _dir;\nconst current = {};\n\n/**\n * Initializes the drawing state.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of stroke.\n * @param {Plot|false} [plot=false] - Plot object for path-following strokes.\n */\nfunction initializeDrawingState(x, y, length, plot = false) {\n snapshotMatrix();\n _position = new Position(x + Cwidth / 2, y + Cheight / 2);\n _length = length;\n _plot = plot;\n if (_plot) _plot.calcIndex(0);\n}\n\nconst gaussians = [];\n\n_onSeed(() => {\n gaussians.length = 0;\n});\n\n/**\n * Executes the drawing operation.\n * @param {number} angleScale - Angle (in degrees) or scaling factor.\n * @param {boolean} isPlot - True if plotting a shape.\n */\nfunction draw(angleScale, isPlot) {\n if (!isPlot) _dir = angleScale;\n saveState();\n\n const stepSize = spacing();\n const totalSteps = Math.round(\n (_length * (isPlot ? angleScale : 1)) / stepSize,\n );\n current.pressureCount = 10;\n current.cachedPressure = undefined;\n current.lineNoiseCount = 5;\n current.cachedLineNoise = undefined;\n\n for (let i = 0; i < totalSteps; i++) {\n if (gaussians.length < totalSteps * 2) {\n gaussians.push(gaussian());\n }\n tip();\n if (isPlot) {\n _position.plotTo(\n _plot,\n stepSize,\n stepSize,\n angleScale,\n i < 10 ? true : false,\n );\n } else {\n _position._moveToDegrees(angleScale, stepSize, stepSize);\n }\n }\n restoreState();\n}\n\n/**\n * Prepares the environment for a brush stroke.\n */\nfunction saveState() {\n current.seed = rr() * 999999;\n const { param } = list.get(State.stroke.type) ?? {};\n if (!param) return;\n current.p = param;\n\n // Set pressure values for the stroke\n const { pressure } = param;\n current.a = pressure.type !== \"custom\" ? rr(-1, 1) : 0;\n current.b = pressure.type !== \"custom\" ? rr(1, 1.5) : 0;\n if (pressure.type !== \"custom\") {\n current.cp = rr(3, 3.5);\n current.ct = 0;\n current.cs = 1;\n current.ck = 0;\n } else {\n const variation = pressure.variation ?? DEFAULT_CUSTOM_PRESSURE_VARIATION;\n current.cp = rr(-variation.offset, variation.offset);\n current.ct = rr(-variation.warp, variation.warp);\n current.cs = rr(1 - variation.scale, 1 + variation.scale);\n current.ck = rr(-variation.tilt, variation.tilt);\n }\n [current.min, current.max] = pressure.min_max;\n\n current.noiseoffset = 0.05 * current.p.noise;\n\n // Cache stroke direction for direction-aware dispersion (non-plot strokes only)\n if (!_plot) {\n current.cos = cos(_dir);\n current.sin = sin(_dir);\n }\n\n // Ensure GL is ready and blend state\n isReady();\n const switchingToBrush = Mix.isBrush !== true;\n Mix.isBrush = true;\n if (switchingToBrush) Mix.justChanged = true;\n Mix.blend(State.stroke.color);\n\n // Set additional state values\n current.alpha = calculateAlpha();\n\n markerTip();\n}\n\n/**\n * Restores drawing state after completing a stroke.\n */\nfunction restoreState() {\n markerTip();\n glDraw();\n const type = current.p?.type;\n if (type === \"image\") glDrawImages(T.tips.get(current.p.image.src), current.p.image.src);\n else if (type === \"custom\") glDrawImages(T.tips.get(current.p.tipKey), current.p.tipKey);\n}\n\n/**\n * Renders the brush tip based on current pressure and position.\n */\nfunction tip() {\n const pressure = calculatePressure();\n const lineNoise = calculateLineNoise();\n\n if (lineNoise > rr(1,1.02) && rr(0,1) < 0.7) return;\n switch (current.p.type) {\n case \"spray\":\n drawSpray(pressure * lineNoise);\n break;\n case \"marker\":\n drawMarker(pressure * lineNoise);\n break;\n case \"custom\":\n case \"image\":\n drawImageTip(pressure * lineNoise);\n break;\n default:\n drawDefault(pressure * lineNoise);\n break;\n }\n}\n\n/**\n * Calculates the effective brush pressure.\n * @returns {number} The calculated pressure.\n */\nfunction calculatePressure() {\n if (current.pressureCount >= 10 || current.cachedPressure === undefined) {\n current.cachedPressure = _plot\n ? simPressure() * _plot.pressure(_position.plotted)\n : simPressure();\n current.pressureCount = 0;\n }\n current.pressureCount++;\n return current.cachedPressure;\n}\n\nfunction calculateLineNoise() {\n if (current.lineNoiseCount >= 10 || current.cachedLineNoise === undefined) {\n current.cachedLineNoise = map(\n noise(current.seed + _position.plotted * 0.01, 0),\n -1,\n 1,\n 1 - current.noiseoffset,\n 1 + current.noiseoffset,\n );\n current.lineNoiseCount = 0;\n }\n current.lineNoiseCount++;\n return current.cachedLineNoise;\n}\n\n/**\n * Simulates brush pressure based on stroke parameters.\n * @returns {number} Simulated pressure value.\n */\nfunction simPressure() {\n const value = current.p.pressure.type === \"custom\"\n ? map(\n current.p.pressure.curve(\n Math.max(\n 0,\n Math.min(\n 1,\n 0.5 + ((_position.plotted / _length) - 0.5 + current.ct) * current.cs,\n ),\n ),\n ) +\n current.cp +\n current.ck * ((_position.plotted / _length) - 0.5),\n 0,\n 1,\n current.min,\n current.max,\n true,\n )\n : gauss();\n return value;\n}\n\n/**\n * Generates a Gaussian-based pressure value.\n * @param {number} [a] - Center parameter.\n * @param {number} [b] - Width parameter.\n * @param {number} [c] - Shape parameter.\n * @param {number} [min] - Minimum pressure.\n * @param {number} [max] - Maximum pressure.\n * @returns {number} Gaussian pressure value.\n */\nfunction gauss(\n a = 0.5 + current.p.pressure.curve[0] * current.a,\n b = 1 - current.p.pressure.curve[1] * current.b,\n c = current.cp,\n min = current.min,\n max = current.max,\n) {\n const peakPos = a * _length;\n const halfWidth =\n (_position.plotted < peakPos ? b * 1.2 : b * 0.8) * (_length / 2);\n return map(\n 1 /\n (1 +\n Math.pow(Math.abs((_position.plotted - peakPos) / halfWidth), 2 * c)),\n 0,\n 1,\n min,\n max,\n );\n}\n\n/**\n * Calculates the alpha (opacity) level for a brush stroke.\n * @returns {number} The calculated opacity.\n */\nfunction calculateAlpha() {\n return [\"default\", \"spray\"].includes(current.p.type)\n ? current.p.opacity\n : current.p.opacity / Math.min(State.stroke.weight, 1.3);\n}\n\n/**\n * Calculates the step spacing based on the current brush parameters.\n * @returns {number} The spacing value.\n */\nfunction spacing() {\n const { param } = list.get(State.stroke.type) ?? {};\n if (!param) return 1;\n return param.spacing;\n}\n\nfunction getImageTipOverscan() {\n const maxPressure = Math.max(1, current.max ?? 1);\n const scatterReach = State.stroke.weight * current.p.scatter;\n const tipReach = State.stroke.weight * current.p.weight * maxPressure;\n\n // Custom/image tips can extend beyond their nominal square because the tip\n // drawing itself may be large and because high scatter creates sparse large\n // stamps near the edge. Keep culling/dirty tracking conservative.\n return Math.max(8, scatterReach * 1.5 + tipReach * 0.75);\n}\n\n// ---------------------------------------------------------------------------\n// Brush Tip Rendering Methods\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the spray tip effect.\n * @param {number} pressure - Current pressure.\n */\nfunction drawSpray(pressure) {\n const vibration =\n State.stroke.weight * current.p.scatter * pressure +\n (State.stroke.weight * rArray(gaussians) * current.p.scatter) / 3;\n const sw = current.p.weight * rr(0.9, 1.1);\n const iterations = Math.ceil(current.p.grain / pressure);\n for (let j = 0; j < iterations; j++) {\n const r = rr(0.9, 1.1);\n const rX = r * vibration * rr(-1, 1);\n const yRandomFactor = rr(-1, 1);\n const sqrtPart = Math.sqrt((r * vibration) ** 2 - rX ** 2);\n circle(\n _position.x + rX,\n _position.y + yRandomFactor * sqrtPart,\n sw,\n current.alpha,\n );\n }\n}\n\n/**\n * Draws the marker tip effect.\n * @param {number} pressure - Current pressure.\n * @param {boolean} [vibrate=true] - Whether to apply vibration.\n */\nfunction drawMarker(pressure, vibrate = true, alpha = current.alpha) {\n const vibration = vibrate ? State.stroke.weight * current.p.scatter : 0;\n const rx = vibrate ? vibration * rr(-1, 1) : 0;\n const ry = vibrate ? vibration * rr(-1, 1) : 0;\n circle(\n _position.x + rx,\n _position.y + ry,\n State.stroke.weight * current.p.weight * pressure,\n alpha * Math.max(0.8, pressure) * rr(0.9,1.1),\n );\n}\n\n/**\n * Queues a stamp for instanced GL rendering.\n * Handles both \"image\" and \"custom\" tip types.\n * @param {number} pressure - Current pressure.\n * @param {number} alpha - Opacity [0..255].\n */\nfunction drawImageTip(pressure, alpha = current.alpha) {\n const vibration = State.stroke.weight * current.p.scatter;\n const rx = vibration * rr(-1, 1);\n const ry = vibration * rr(-1, 1);\n const size = current.p.weight * State.stroke.weight * pressure;\n const overscan = getImageTipOverscan();\n let angle = 0;\n if (current.p.rotate === \"random\") {\n angle = randInt(0, 360) * (Math.PI / 180);\n } else if (current.p.rotate === \"natural\") {\n angle = ((_plot ? -_plot.angle(_position.plotted) : -_dir) + _position.angle()) * (Math.PI / 180);\n }\n stampImage(\n _position.x + rx,\n _position.y + ry,\n size,\n angle,\n alpha * Math.max(0.8, pressure) * rr(0.9, 1.1),\n overscan,\n );\n}\n\n/**\n * Draws the default brush tip.\n * @param {number} pressure - Current pressure.\n */\nfunction drawDefault(pressure, wiggle = 1) {\n wiggle = map(wiggle, 0, 1, 0.9, 1.05);\n const vibration =\n wiggle *\n State.stroke.weight *\n current.p.scatter *\n (current.p.sharpness +\n ((1 - current.p.sharpness) * rArray(gaussians)) / pressure);\n const passesGate = rr(0, current.p.grain * pressure) > 0.4;\n if (passesGate) {\n let dx, dy;\n if (_plot) {\n const plotAngle = _plot.angle(_position.plotted);\n const plotCos = cos(plotAngle);\n const plotSin = sin(plotAngle);\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * plotSin + along * plotCos;\n dy = perp * plotCos - along * plotSin;\n } else {\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * current.sin + along * current.cos;\n dy = perp * current.cos - along * current.sin;\n }\n const diameter =\n pressure *\n pressure *\n current.p.weight *\n rr(0.85, 1.15) *\n State.stroke.weight;\n const alpha = Math.max(0.9, pressure) * current.alpha * rr(0.75, 1.1);\n circle(\n _position.x + dx,\n _position.y + dy,\n diameter,\n alpha,\n );\n }\n}\n\n/**\n * Draws the marker tip with a blend effect.\n */\nfunction markerTip() {\n if (current.p.markerTip === false) return;\n let pressure = calculatePressure();\n let alpha = current.alpha;\n if (current.p.type === \"marker\") {\n for (let s = 1; s < 10; s++) {\n drawMarker((pressure * s) / 10, true, alpha * 8);\n }\n } else if (current.p.type === \"custom\" || current.p.type === \"image\") {\n for (let s = 1; s < 5; s++) {\n drawImageTip((pressure * s) / 10, alpha * 2);\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Basic Drawing Operations\n// ---------------------------------------------------------------------------\n\n/**\n * Draws a line using the current brush.\n * @param {number} x1 - Start x-coordinate.\n * @param {number} y1 - Start y-coordinate.\n * @param {number} x2 - End x-coordinate.\n * @param {number} y2 - End y-coordinate.\n */\nexport function line(x1, y1, x2, y2) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n let d = dist(x1, y1, x2, y2);\n if (d == 0) return;\n initializeDrawingState(x1, y1, d);\n let angle = calcAngle(x1, y1, x2, y2);\n draw(angle, false);\n}\n\n/**\n * Draws a stroke from a starting point in a given direction.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of the stroke.\n * @param {number} dir - Direction, interpreted using the current runtime angle units.\n */\nexport function flowLine(x, y, length, dir) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n initializeDrawingState(x, y, length);\n draw(toDegrees(dir), false);\n}\n\n/**\n * Draws a predefined plot.\n * @param {object} p - Shape object representing the plot.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nfunction plot(p, x, y, scale) {\n isFieldReady();\n initializeDrawingState(x, y, p.length, p);\n draw(scale, true);\n}\n\n// ---------------------------------------------------------------------------\n// Standard Brushes Definition and Initialization\n// ---------------------------------------------------------------------------\n\n/**\n * Defines a set of standard brushes with specific characteristics. Each brush is defined\n * with properties such as weight, scatter, sharpness, grain, opacity, spacing, and\n * pressure sensitivity. Some brushes have additional properties like type, tip, and rotate.\n */\nconst _vals = [\n \"weight\",\n \"scatter\",\n \"sharpness\",\n \"grain\",\n \"opacity\",\n \"spacing\",\n \"pressure\",\n \"type\",\n \"tip\",\n \"rotate\",\n \"markerTip\",\n \"noise\",\n];\nconst _standard_brushes = [\n [\n \"pen\",\n [0.3, 0.15, 0.9, 2, 150, 0.1, { curve: [0.15, 0.2], min_max: [1.2, 1] }],\n ],\n [\n \"rotring\",\n [0.15, 0.05, 0.7, 15, 210, 0.1, { curve: [0.35, 0.2], min_max: [1.3, 1] }],\n ],\n [\n \"2B\",\n [0.3, 0.75, 0.45, 15, 180, 0.1, { curve: [0.1, 0.3], min_max: [1.1, 0.9] }],\n ],\n [\n \"HB\",\n [0.3, 0.6, 0.3, 10, 170, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"2H\",\n [0.2, 0.6, 0.3, 4, 120, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"cpencil\",\n [0.3, 0.55, 0.8, 7, 75, 0.1, { curve: [0.15, 0.2], min_max: [0.95, 1.2] }],\n ],\n [\n \"pastel\",\n [\n 2.05 / 3,\n 13.4 / 3,\n 0.91,\n 28,\n 35,\n 0.085 / 3,\n { mode: \"gaussian\", curve: [0.4, 0.05], min_max: [1.09, 0.93] },\n \"default\",\n undefined,\n \"natural\",\n true,\n 1,\n ],\n ],\n [\n \"crayon\",\n [\n 0.9 / 3,\n 5.45 / 3,\n 0.75,\n 250,\n 159,\n 0.23 / 3,\n [1.1, 0.9],\n \"default\",\n undefined,\n \"natural\",\n true,\n 1,\n ],\n ],\n [\n \"charcoal\",\n [\n 0.35,\n 1.5,\n 0.68,\n 500,\n 120,\n 0.03,\n { curve: [0.15, 0.4], min_max: [1.1, 0.95] },\n ],\n ],\n [\n \"spray\",\n [\n 0.2,\n 6,\n 15,\n 40,\n 90,\n 0.5,\n { curve: [0.2, 0.35], min_max: [0.7, 1] },\n \"spray\",\n ],\n ],\n [\n \"marker\",\n [\n 2,\n 0.2,\n null,\n null,\n 1,\n 0.03,\n { curve: [0.35, 0.25], min_max: [1.2, 0.85] },\n \"marker\",\n ],\n ],\n];\n\nfor (let s of _standard_brushes) {\n let obj = {};\n for (let i = 0; i < s[1].length; i++) obj[_vals[i]] = s[1][i];\n add(s[0], obj);\n}\n\n// ---------------------------------------------------------------------------\n// Extensions to Polygon and Plot Prototypes\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the polygon using the current brush.\n * @param {boolean} [_brush=false] - Optional brush name override.\n * @param {string|Color} [_color] - Optional color override.\n * @param {number} [_weight] - Optional weight override.\n */\nPolygon.prototype.draw = function (_brush = false, _color, _weight) {\n let state = BrushState();\n if (_brush) set(_brush, _color, _weight);\n if (state.isActive) {\n for (let s of this.sides) {\n line(s[0].x, s[0].y, s[1].x, s[1].y);\n }\n }\n BrushSetState(state);\n};\n\n/**\n * Draws the plot using the current brush.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nPlot.prototype.draw = function (x, y, scale) {\n if (BrushState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n plot(this, x, y, scale);\n }\n};\n\n// =============================================================================\n// Section: Loading Custom Image Tips\n// =============================================================================\n/**\n * This section defines the functionality for managing the loading and processing of image tips.\n * Images are loaded from specified source URLs, converted to a white tint for visual effects,\n * and then stored for future use. It includes methods to add new images, convert their color\n * scheme, and integrate them into the active host image pipeline.\n */\n\n/**\n * Manages loading and processing of image tips.\n * Images are converted to white with inverted alpha for tinting via shaders.\n */\nconst T = {\n tips: new Map(),\n\n /**\n * Registers an image source for later loading.\n * @param {string} src - The source URL of the image.\n */\n add(src) {\n if (!this.tips.has(src)) this.tips.set(src, false);\n },\n\n /**\n * Converts image to white with inverted alpha for tint-based rendering.\n * @param {object} image - The host image object to convert.\n */\n imageToWhite(image) {\n image.loadPixels();\n for (let i = 0; i < 4 * image.width * image.height; i += 4) {\n let average =\n (image.pixels[i] + image.pixels[i + 1] + image.pixels[i + 2]) / 3;\n image.pixels[i] = image.pixels[i + 1] = image.pixels[i + 2] = 255;\n image.pixels[i + 3] = 255 - average;\n }\n image.updatePixels();\n },\n\n /**\n * Loads all registered image tips. Returns a promise that resolves\n * when all images are loaded and processed.\n * @returns {Promise}\n */\n async load() {\n const entries = [...this.tips.keys()].filter((k) => !this.tips.get(k));\n await Promise.all(\n entries.map(\n (src) =>\n loadImageTip(src, T.imageToWhite).then((p5img) => {\n this.tips.set(src, p5img);\n }),\n ),\n );\n },\n};\n","import { State } from \"../core/color.js\";\nimport { toDegreesSigned, map, rr } from \"../core/utils.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { BrushState, BrushSetState, set, line } from \"../stroke/stroke.js\";\n\n// =============================================================================\n// Module: Classic Hatch\n// =============================================================================\n\n// ---------------------------------------------------------------------------\n// Hatch State\n// ---------------------------------------------------------------------------\n\nState.hatch = {\n isActive: false,\n dist: 5,\n angle: 45,\n options: {},\n hBrush: false,\n};\n\n/**\n * Returns a shallow snapshot of the current hatch modifier state.\n *\n * @returns {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}}\n */\nexport function HatchState() {\n return { ...State.hatch };\n}\n\n/**\n * Restores hatch modifier state from a previously captured snapshot.\n *\n * @param {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}} state\n */\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Activates classic scanline hatching for subsequent shapes.\n *\n * @param {number} [dist=5] Distance between scanlines.\n * @param {number} [angle=45] Hatch angle in the current runtime angle units.\n * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [options]\n */\nexport function hatch(\n dist = 5,\n angle = 45,\n options = { rand: false, continuous: false, gradient: false }\n) {\n let s = State.hatch;\n s.isActive = true;\n s.dist = dist;\n s.angle = toDegreesSigned(angle);\n s.options = options;\n}\n\n/**\n * Overrides the brush, color, and weight used specifically for hatch strokes.\n *\n * @param {string} brush\n * @param {string|object} [color=\"black\"]\n * @param {number} [weight=1]\n */\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\n/**\n * Deactivates hatching and clears any hatch-specific brush override.\n */\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Scanline Generation\n// ---------------------------------------------------------------------------\n\n/**\n * Computes hatch segments for one polygon by rotating it into scanline space,\n * intersecting horizontal scanlines against its edges, and rotating the\n * resulting segments back into canvas space.\n *\n * @param {Polygon} polygon\n * @param {number} angle Hatch angle in degrees.\n * @param {number} dist Base scanline spacing.\n * @param {number} gradient Multiplicative spacing growth per scanline.\n * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}\n */\nfunction scanlineHatch(polygon, angle, dist, gradient) {\n const rad = (angle * Math.PI) / 180;\n const cosA = Math.cos(rad),\n sinA = Math.sin(rad);\n const cosB = Math.cos(-rad),\n sinB = Math.sin(-rad);\n\n const verts = polygon.a,\n n = verts.length;\n\n // Rotate vertices; track Y extent\n const rotated = new Array(n);\n let minY = Infinity,\n maxY = -Infinity;\n for (let i = 0; i < n; i++) {\n const x = verts[i][0],\n y = verts[i][1];\n const r = [x * cosA - y * sinA, x * sinA + y * cosA];\n rotated[i] = r;\n if (r[1] < minY) minY = r[1];\n if (r[1] > maxY) maxY = r[1];\n }\n\n // Build edge list (skip horizontal edges)\n const edges = [];\n for (let i = 0; i < n; i++) {\n const a = rotated[i],\n b = rotated[(i + 1) % n];\n if (a[1] !== b[1]) edges.push(a, b);\n }\n const eLen = edges.length;\n\n // Scan, find crossings, rotate back\n const segments = [];\n const cx = [];\n let Y = minY + dist * 0.5,\n step = dist;\n while (Y < maxY) {\n cx.length = 0;\n for (let i = 0; i < eLen; i += 2) {\n const y1 = edges[i][1],\n y2 = edges[i + 1][1];\n if ((y1 <= Y && Y < y2) || (y2 <= Y && Y < y1))\n cx.push(\n edges[i][0] + ((Y - y1) / (y2 - y1)) * (edges[i + 1][0] - edges[i][0])\n );\n }\n cx.sort((a, b) => a - b);\n for (let i = 0; i < cx.length - 1; i += 2) {\n segments.push({\n scanY: Y,\n x1: cx[i] * cosB - Y * sinB,\n y1: cx[i] * sinB + Y * cosB,\n x2: cx[i + 1] * cosB - Y * sinB,\n y2: cx[i + 1] * sinB + Y * cosB,\n });\n }\n Y += step;\n step *= gradient;\n }\n return segments;\n}\n\n/**\n * Collects and orders hatch segments for one polygon or a polygon list.\n *\n * Segments are sorted in scanline traversal order so downstream rendering can\n * optionally connect them into a continuous serpentine path.\n *\n * @param {Polygon|Polygon[]} polygons\n * @param {number} dist\n * @param {number} angle\n * @param {number} gradient\n * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}\n */\nfunction getHatchSegments(polygons, dist, angle, gradient) {\n if (!Array.isArray(polygons)) polygons = [polygons];\n const segs = [];\n for (const poly of polygons) {\n for (const s of scanlineHatch(poly, angle, dist, gradient)) segs.push(s);\n }\n segs.sort((a, b) => (a.scanY === b.scanY ? a.x1 - b.x1 : a.scanY - b.scanY));\n return segs;\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Configuration\n// ---------------------------------------------------------------------------\n\n/**\n * Runs hatch drawing with the temporary hatch-specific brush style if one is active,\n * then restores the outer stroke state.\n *\n * @param {() => void} drawFn\n */\nfunction withHatchStyle(drawFn) {\n const save = BrushState();\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n drawFn();\n BrushSetState(save);\n}\n\n/**\n * Resolves the active hatch parameters and precomputes the ordered scanline segments.\n *\n * @param {Polygon|Polygon[]} polygons\n * @returns {{dist:number, options:Object, segs:Object[]}}\n */\nfunction getActiveHatchConfig(polygons) {\n const dist = State.hatch.dist;\n const angle = ((State.hatch.angle % 180) + 180) % 180;\n const options = State.hatch.options;\n const gradient = options.gradient ? map(options.gradient, 0, 1, 1, 1.1, true) : 1;\n const segs = getHatchSegments(polygons, dist, angle, gradient);\n return { dist, options, segs };\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Lines\n// ---------------------------------------------------------------------------\n\n/**\n * Expands ordered hatch segments into the actual line list that will be drawn.\n *\n * This includes endpoint jitter when `rand` is active and inserts the serpentine\n * connector lines when `continuous` is enabled.\n *\n * @param {Polygon|Polygon[]} polygons\n * @returns {{x1:number, y1:number, x2:number, y2:number, scanY:number, isConnector:boolean}[]}\n */\nexport function getHatchLines(polygons) {\n const { dist, options, segs } = getActiveHatchConfig(polygons);\n const r = options.rand || 0;\n const lines = [];\n\n for (let j = 0; j < segs.length; j++) {\n const s = segs[j];\n let x1 = s.x1, y1 = s.y1, x2 = s.x2, y2 = s.y2;\n if (r) {\n x1 += 2 * r * dist * rr(-1, 1);\n y1 += 2 * r * dist * rr(-1, 1);\n x2 += 2 * r * dist * rr(-1, 1);\n y2 += 2 * r * dist * rr(-1, 1);\n }\n const reverse = options.continuous && j % 2 === 1;\n const line = reverse\n ? { x1: x2, y1: y2, x2: x1, y2: y1, scanY: s.scanY, isConnector: false }\n : { x1, y1, x2, y2, scanY: s.scanY, isConnector: false };\n lines.push(line);\n if (j > 0 && options.continuous) {\n const prev = lines[lines.length - 2];\n lines.push({\n x1: prev.x2,\n y1: prev.y2,\n x2: line.x1,\n y2: line.y1,\n scanY: s.scanY,\n isConnector: true,\n });\n }\n }\n\n return lines;\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Rendering\n// ---------------------------------------------------------------------------\n\n/**\n * Iterates the generated hatch lines and delegates the actual rendering of each\n * segment to the provided callback.\n *\n * @param {Polygon|Polygon[]} polygons\n * @param {(x1:number, y1:number, x2:number, y2:number, index:number, segs:Object[]) => void} drawSegment\n */\nfunction renderHatchSegments(polygons, drawSegment) {\n const segs = getHatchLines(polygons);\n withHatchStyle(() => {\n for (let j = 0; j < segs.length; j++) {\n const s = segs[j];\n drawSegment(s.x1, s.y1, s.x2, s.y2, j, segs);\n }\n });\n}\n\n/**\n * Draws classic hatch lines over one polygon or an array of polygons.\n *\n * @param {Polygon|Polygon[]} polygons\n */\nexport function createHatch(polygons) {\n renderHatchSegments(polygons, (x1, y1, x2, y2) => {\n line(x1, y1, x2, y2);\n });\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Applies the currently active hatch modifier to a polygon, or temporarily\n * overrides hatch parameters for this call only.\n *\n * @param {number|false} [_dist=false]\n * @param {number} [_angle]\n * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [_options]\n */\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (State.hatch.isActive) createHatch(this);\n HatchSetState(state);\n};\n\n/**\n * Converts the plot to a polygon and applies the currently active hatch modifier.\n *\n * @param {number} x\n * @param {number} y\n * @param {number} scale\n */\nPlot.prototype.hatch = function (x, y, scale) {\n if (HatchState().isActive) {\n if (this.origin) (x = this.origin[0]), (y = this.origin[1]), (scale = 1);\n this.pol = this.genPol(x, y, scale, 0.3);\n this.pol.hatch();\n }\n};\n","// =============================================================================\n// Module: Mass\n// =============================================================================\n\nimport { State } from \"../core/color.js\";\nimport { arc } from \"../core/primitives.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { rr2, dist, calcAngle } from \"../core/utils.js\";\nimport { fromDegrees, usesRadians } from \"../core/runtime.js\";\nimport { HatchState, HatchSetState, hatch, getHatchLines } from \"./hatch.js\";\nimport { BrushState, BrushSetState, getBrushParams, set } from \"../stroke/stroke.js\";\nimport { wiggle } from \"../core/flowfield.js\";\n\n// ---------------------------------------------------------------------------\n// Mass State\n// ---------------------------------------------------------------------------\n\nState.mass = {\n isActive: false,\n brush: null,\n color: null,\n options: {},\n};\n\n/**\n * Returns a shallow copy of the current mass state.\n * @returns {object}\n */\nexport function MassState() {\n return { ...State.mass };\n}\n\n/**\n * Restores a previously saved mass state.\n * @param {object} state\n */\nexport function MassSetState(state) {\n State.mass = { ...state };\n}\n\n/**\n * Enables massing mode with a brush, color, and optional configuration.\n *\n * @param {string} brush - Brush name to use for the mass pass.\n * @param {string|Color} color - Color to use for the mass pass.\n * @param {object} [options={}] - Massing options such as precision, strength, gradient, and outline.\n */\nexport function mass(brush, color, options = {}) {\n State.mass.brush = brush;\n State.mass.color = color;\n State.mass.options = options;\n State.mass.isActive = true;\n}\n\n/**\n * Disables massing mode for subsequent geometry.\n */\nexport function noMass() {\n State.mass.isActive = false;\n State.mass.brush = null;\n State.mass.color = null;\n State.mass.options = {};\n}\n\n// ---------------------------------------------------------------------------\n// Polygon Preparation\n// ---------------------------------------------------------------------------\n\n/**\n * Returns a translated copy of a polygon.\n * Used to build the secondary mass layers from an existing base polygon.\n * @param {Polygon} polygon\n * @param {number} jitterX\n * @param {number} jitterY\n * @returns {Polygon}\n */\nfunction jitterPolygon(polygon, jitterX, jitterY) {\n return new Polygon(\n polygon.vertices.map((vertex) => [vertex.x + jitterX, vertex.y + jitterY]),\n );\n}\n\n/**\n * Builds the three polygons used for a mass pass.\n * Both polygon and plot inputs use one base polygon plus two translated copies,\n * so plot-based massing only needs a single `genPol(...)` call.\n * @param {Polygon|Plot} shape\n * @param {number|false} x\n * @param {number} y\n * @param {number} scale\n * @returns {Polygon[]}\n */\nfunction getMassPolygons(shape, x, y, scale) {\n const isPolygon = x === false;\n const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;\n const basePolygon = isPolygon ? shape : shape.genPol(x, y, scale, 0.15);\n const maxJitter = Math.min(scatter * 2, 5);\n const jitters = [\n [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],\n [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],\n ];\n\n return [\n basePolygon,\n jitterPolygon(basePolygon, jitters[0][0], jitters[0][1]),\n jitterPolygon(basePolygon, jitters[1][0], jitters[1][1]),\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Angle & Bounds Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Converts degree values into the current runtime angle units.\n * @param {number} angle\n * @returns {number}\n */\nfunction getAngleConverter() {\n return usesRadians()\n ? (angle) => (angle * Math.PI) / 180\n : (angle) => angle;\n}\n\n/**\n * Computes an axis-aligned bounding box for a polygon.\n * The diagonal is used as a size reference for pivot distance.\n * @param {Polygon} polygon\n * @returns {{minX:number,minY:number,maxX:number,maxY:number,cx:number,cy:number,size:number}}\n */\nfunction getPolygonBounds(polygon) {\n const points = polygon?.a ?? [];\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n for (const [x, y] of points) {\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n return {\n minX,\n minY,\n maxX,\n maxY,\n cx: (minX + maxX) / 2,\n cy: (minY + maxY) / 2,\n size: Math.hypot(maxX - minX, maxY - minY),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Pivot Geometry\n// ---------------------------------------------------------------------------\n\n/**\n * Chooses the diagonal corner family for a whole mass gesture.\n * Positive-angle hatching uses either bottom-right or top-left; negative-angle\n * hatching uses either bottom-left or top-right.\n * @param {number} angleDeg\n * @returns {[number, number]}\n */\nfunction getPivotBias(angleDeg) {\n const normalizedAngle = ((((angleDeg + 90) % 180) + 180) % 180) - 90;\n if (normalizedAngle >= 0) {\n return rr2() < 0.5 ? [1, 1] : [-1, -1];\n } else {\n return rr2() < 0.5 ? [-1, 1] : [1, -1];\n }\n}\n\n/**\n * Places the global pivot anchor outside the polygon, along the selected bias.\n * Distance varies per layer while the bias stays fixed for the whole mass.\n * @param {Polygon} polygon\n * @param {[number, number]} bias\n * @returns {{x:number,y:number}}\n */\nfunction getPivotAnchor(polygon, bias) {\n const bounds = getPolygonBounds(polygon);\n const offset = bounds.size * rr2(0.6, 1.4);\n const [sx, sy] = bias;\n return {\n x: bounds.cx + sx * offset,\n y: bounds.cy + sy * offset,\n };\n}\n\n/**\n * Projects the global pivot anchor onto the perpendicular bisector of a line.\n * This yields a valid circle center equidistant from both endpoints.\n * @param {{x:number,y:number}} anchor\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {{x:number,y:number}|null}\n */\nfunction projectAnchorToBisector(anchor, x1, y1, x2, y2) {\n const mx = (x1 + x2) / 2;\n const my = (y1 + y2) / 2;\n const dx = x2 - x1;\n const dy = y2 - y1;\n const length = Math.hypot(dx, dy);\n if (!length) return null;\n const nx = -dy / length;\n const ny = dx / length;\n const offset = (anchor.x - mx) * nx + (anchor.y - my) * ny;\n return {\n x: mx + nx * offset,\n y: my + ny * offset,\n };\n}\n\n/**\n * Returns the shortest arc between two endpoints around a given center.\n * The returned angles are already converted into the current runtime angle units.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {[number, number]}\n */\nfunction getShortArcAngles(cx, cy, x1, y1, x2, y2, toAngleUnit) {\n let startDeg = calcAngle(cx, cy, x1, y1);\n let endDeg = calcAngle(cx, cy, x2, y2);\n const sweep = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweep > 180) [startDeg, endDeg] = [endDeg, startDeg];\n return [\n toAngleUnit(startDeg),\n toAngleUnit(endDeg),\n ];\n}\n\n/**\n * Splits a hatch line into two slightly separated segments so some gestures\n * read as interrupted rather than perfectly continuous.\n * @param {{x1:number,y1:number,x2:number,y2:number}} seg\n * @returns {Array<{x1:number,y1:number,x2:number,y2:number}>}\n */\nfunction splitSegment(seg) {\n const t = rr2(0.35, 0.65);\n const mx = seg.x1 + (seg.x2 - seg.x1) * t;\n const my = seg.y1 + (seg.y2 - seg.y1) * t;\n const dx = seg.x2 - seg.x1;\n const dy = seg.y2 - seg.y1;\n const length = Math.hypot(dx, dy) || 1;\n const gap = rr2(0.04, 0.1) * length;\n const gx = (dx / length) * gap * 0.5;\n const gy = (dy / length) * gap * 0.5;\n return [\n { x1: seg.x1, y1: seg.y1, x2: mx - gx, y2: my - gy },\n { x1: mx + gx, y1: my + gy, x2: seg.x2, y2: seg.y2 },\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Mass Rendering\n// ---------------------------------------------------------------------------\n\n/**\n * Draws one polygon of the mass as a family of arcs derived from hatch lines.\n * The same pivot bias is used across layers, while each layer gets its own\n * anchor distance from the shape.\n * @param {Polygon} polygon\n * @param {[number, number]} pivotBias\n */\nfunction drawMassArcs(polygon, pivotBias, toAngleUnit) {\n const anchor = getPivotAnchor(polygon, pivotBias);\n for (const seg of getHatchLines(polygon)) {\n const parts = !seg.isConnector && rr2() < 0.35 ? splitSegment(seg) : [seg];\n for (const part of parts) {\n const center = projectAnchorToBisector(anchor, part.x1, part.y1, part.x2, part.y2);\n if (!center) continue;\n const radius = dist(center.x, center.y, part.x1, part.y1);\n if (!radius) continue;\n const [startAngle, endAngle] = getShortArcAngles(\n center.x,\n center.y,\n part.x1,\n part.y1,\n part.x2,\n part.y2,\n toAngleUnit,\n );\n arc(center.x, center.y, radius, startAngle, endAngle);\n }\n }\n}\n\n/**\n * Configures a hatch pass and immediately reinterprets the generated lines as arcs.\n * @param {Polygon} polygon\n * @param {number} dist\n * @param {number} angle\n * @param {object} options\n * @param {[number, number]} pivotBias\n */\nfunction drawMassPass(polygon, dist, angle, options, pivotBias, toAngleUnit) {\n hatch(dist, angle, options);\n drawMassArcs(polygon, pivotBias, toAngleUnit);\n}\n\n/**\n * Creates the built-in \"massing\" effect for a polygon or plot.\n * A mass is built from up to three jittered polygon layers, each hatched and\n * then redrawn as arc gestures around a shared pivot bias.\n * @param {Polygon|Plot} shape\n * @param {number|false} x\n * @param {number} y\n * @param {number} scale\n */\nexport function createMass(shape, x, y, scale) {\n const pols = getMassPolygons(shape, x, y, scale);\n const hatchState = HatchState();\n const brushState = BrushState();\n const fieldState = { ...State.field };\n const precision = State.mass.options?.precision ?? 0.5;\n const strength = State.mass.options?.strength ?? 1;\n const gradient = State.mass.options?.gradient ?? 0.1;\n const outline = State.mass.options?.outline ?? false;\n const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;\n const hatchDist = 1.6 * rr2(scatter * 0.65, scatter * 0.85) - 0.4 * gradient;\n const baseAngle = rr2(-90, 90);\n const pivotBias = getPivotBias(baseAngle);\n const toAngleUnit = getAngleConverter();\n\n set(State.mass.brush, State.mass.color, 1);\n wiggle(2 - precision);\n if (outline) pols[0].draw();\n\n drawMassPass(\n pols[0],\n hatchDist * 0.9,\n fromDegrees(baseAngle),\n {\n gradient,\n rand: 2 - 2 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n\n if (strength > 0.33) {\n drawMassPass(\n pols[1],\n hatchDist,\n fromDegrees(baseAngle + 20 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n }\n\n if (strength > 0.66) {\n drawMassPass(\n pols[2],\n hatchDist * 0.8,\n fromDegrees(baseAngle + 15 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n }\n\n BrushSetState(brushState);\n HatchSetState(hatchState);\n State.field = { ...fieldState };\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Applies massing to polygon geometry.\n */\nPolygon.prototype.mass = function () {\n if (State.mass?.isActive) {\n createMass(this, false);\n }\n};\n\n/**\n * Applies massing to plots by generating their polygon first.\n * @param {number} x\n * @param {number} y\n * @param {number} scale\n */\nPlot.prototype.mass = function (x, y, scale) {\n if (State.mass?.isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n createMass(this, x, y, scale);\n }\n};\n","import { Mix } from \"../core/color.js\";\n\nfunction strokePadding(ctx, matrix) {\n const lineWidth = ctx.lineWidth || 0;\n if (lineWidth <= 0) return 1;\n\n return (\n 1 +\n (lineWidth * Math.max(Math.hypot(matrix.a, matrix.c), Math.hypot(matrix.b, matrix.d))) /\n 2\n );\n}\n\n// =============================================================================\n// Section: Draw shapes to Mask Buffers\n// =============================================================================\n\n/**\n * Draws a polygon to the mask using the provided vertices.\n * @param {Array<{x: number, y: number}>} vertices - Array of vertex coordinates.\n */\nexport function drawPolygon(vertices) {\n const ctx = Mix.ctx;\n const matrix = ctx.getTransform();\n // Cache the current 2D transform once so the hot loop can stay numeric and\n // avoid repeated property reads while we build bounds.\n const a = matrix.a;\n const b = matrix.b;\n const c = matrix.c;\n const d = matrix.d;\n const e = matrix.e;\n const f = matrix.f;\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n\n ctx.beginPath();\n\n // Seed both the path and the transformed bounds from the first vertex so the\n // loop below only needs to append line segments.\n const first = vertices[0];\n let tx = a * first.x + c * first.y + e;\n let ty = b * first.x + d * first.y + f;\n minX = maxX = tx;\n minY = maxY = ty;\n\n ctx.moveTo(first.x, first.y);\n\n for (let i = 1; i < vertices.length; i++) {\n const v = vertices[i];\n\n // Track the transformed bounds in canvas space while we build the path so\n // dirty-rect bookkeeping does not need a second pass over the vertices.\n tx = a * v.x + c * v.y + e;\n ty = b * v.x + d * v.y + f;\n minX = Math.min(minX, tx);\n minY = Math.min(minY, ty);\n maxX = Math.max(maxX, tx);\n maxY = Math.max(maxY, ty);\n\n ctx.lineTo(v.x, v.y);\n }\n\n ctx.closePath();\n\n // Expand by stroke width so the later composite pass copies enough pixels\n // even when the polygon border extends outside the raw vertex bounds.\n const padding = strokePadding(ctx, matrix);\n Mix.markDirtyRect(Mix.mask, {\n minX: minX - padding,\n minY: minY - padding,\n maxX: maxX + padding,\n maxY: maxY + padding,\n });\n}\n\n/**\n * Draws a circle to the mask.\n * @param {number} x - X-coordinate of the circle's center.\n * @param {number} y - Y-coordinate of the circle's center.\n * @param {number} d - Diameter of the circle.\n */\nexport function circle(x, y, d) {\n const PI2 = Math.PI * 2;\n const ctx = Mix.ctx;\n const radius = d / 2;\n\n ctx.moveTo(x + radius, y);\n ctx.arc(x, y, radius, 0, PI2);\n}\n","import * as Color from \"../core/color.js\";\nimport {\n createFramebuffer,\n create2DCanvas,\n} from \"../core/compositor_runtime.js\";\n\n// Small staging canvas used to upload only the dirty fill sub-rect into the\n// framebuffer-backed mask mirror consumed by the blend shader.\nlet FillMaskUploadCanvas = null;\nlet isFillCompositeRegistered = false;\nconst DIRTY_FILL_PADDING = 4;\n\n// =============================================================================\n// Section: Helpers\n// =============================================================================\n/**\n * Returns whether the CPU-side 2D fill mask must be recreated.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} maskWidth - Mask width in physical pixels.\n * @param {number} maskHeight - Mask height in physical pixels.\n * @returns {boolean} True when the 2D fill mask needs reallocation.\n */\nfunction needsFillMaskCanvas(Renderer, maskWidth, maskHeight) {\n return (\n !Renderer.mask ||\n Renderer.mask.width !== maskWidth ||\n Renderer.mask.height !== maskHeight\n );\n}\n\n/**\n * Returns whether the framebuffer-backed fill mask mirror must be recreated.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {boolean} True when the fill mask framebuffer needs reallocation.\n */\nfunction needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density) {\n return (\n !Renderer.fillMaskFramebuffer ||\n Renderer.fillMaskFramebuffer.width !== Cwidth ||\n Renderer.fillMaskFramebuffer.height !== Cheight ||\n (typeof Renderer.fillMaskFramebuffer.pixelDensity === \"function\" &&\n Renderer.fillMaskFramebuffer.pixelDensity() !== Density)\n );\n}\n\n// =============================================================================\n// Section: Resource Management\n// =============================================================================\n/**\n * Ensures fill compositing resources exist for the active renderer.\n *\n * Fill draws first into a CPU-side 2D mask canvas. That mask is later uploaded,\n * dirty-rect by dirty-rect, into a framebuffer-backed mirror used by the final\n * blend shader pass.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n * @returns {{mask: object, ctx: CanvasRenderingContext2D}} Fill mask resources.\n */\nexport function ensureFillCompositeResources(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n clearTarget,\n) {\n const maskWidth = Math.max(1, Math.round(Cwidth * Density));\n const maskHeight = Math.max(1, Math.round(Cheight * Density));\n\n if (needsFillMaskCanvas(Renderer, maskWidth, maskHeight)) {\n Renderer.mask = create2DCanvas(maskWidth, maskHeight);\n }\n\n if (needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.fillMaskFramebuffer?.remove) {\n Renderer.fillMaskFramebuffer.remove();\n }\n Renderer.fillMaskFramebuffer = createFramebuffer(Renderer, {\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n clearTarget(Renderer.fillMaskFramebuffer);\n }\n\n Renderer.mask.dirtyRect ??= null;\n Renderer.mask.isDrawn ??= false;\n Renderer.mask.drawingContext.imageSmoothingEnabled = false;\n return {\n mask: Renderer.mask,\n ctx: Renderer.mask.drawingContext,\n };\n}\n\n// =============================================================================\n// Section: Mask Lifecycle\n// =============================================================================\n/**\n * Clears the current fill mask and resets its bookkeeping flags.\n *\n * @param {object|null} target - Fill mask canvas or framebuffer mirror.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n */\nexport function clearFillMask(target, clearTarget) {\n if (!target) return;\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\n}\n\n// =============================================================================\n// Section: Composite Bounds\n// =============================================================================\n/**\n * Returns the fill dirty rect to composite into the main target. Fill bounds are\n * taken directly from the accumulated 2D mask dirty area plus a small padding.\n *\n * @param {object|null} target - Fill mask canvas.\n * @param {Function} _getActiveFramebuffer - Unused for fill masks.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} expandDirtyRect - Expands a rect by a constant padding.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\nexport function getFillCompositeRect(\n target,\n _getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(target.dirtyRect, DIRTY_FILL_PADDING),\n );\n}\n\n// =============================================================================\n// Section: Upload\n// =============================================================================\n/**\n * Uploads only the dirty portion of the CPU-side 2D fill mask into the\n * framebuffer-backed fill mask mirror used by the shader compositor.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {object} mask - CPU-side 2D fill mask canvas.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} dirtyRect - Dirty rect to upload.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n * @returns {object} Framebuffer-backed fill mask mirror.\n */\nexport function getFillShaderMask(\n Renderer,\n mask,\n dirtyRect,\n normalizeDirtyRect,\n getFullDirtyRect,\n clearTarget,\n) {\n const target = Renderer.fillMaskFramebuffer;\n const gl = Renderer.drawingContext;\n const uploadRect = normalizeDirtyRect(dirtyRect) ?? getFullDirtyRect();\n const uploadWidth = uploadRect.maxX - uploadRect.minX;\n const uploadHeight = uploadRect.maxY - uploadRect.minY;\n\n if (\n !FillMaskUploadCanvas ||\n FillMaskUploadCanvas.width !== uploadWidth ||\n FillMaskUploadCanvas.height !== uploadHeight\n ) {\n FillMaskUploadCanvas = create2DCanvas(uploadWidth, uploadHeight);\n }\n\n const uploadContext = FillMaskUploadCanvas.drawingContext;\n uploadContext.clearRect(0, 0, uploadWidth, uploadHeight);\n uploadContext.drawImage(\n mask,\n uploadRect.minX,\n uploadRect.minY,\n uploadWidth,\n uploadHeight,\n 0,\n 0,\n uploadWidth,\n uploadHeight,\n );\n\n clearTarget(target);\n gl.bindTexture(gl.TEXTURE_2D, target.colorTexture);\n gl.texSubImage2D(\n gl.TEXTURE_2D,\n 0,\n uploadRect.minX,\n uploadRect.minY,\n gl.RGBA,\n gl.UNSIGNED_BYTE,\n FillMaskUploadCanvas,\n );\n return target;\n}\n\n// =============================================================================\n// Section: Registration\n// =============================================================================\n/**\n * Registers the fill compositor with the shared color/composite core.\n * Safe to call multiple times.\n */\nexport function initFillComposite() {\n if (isFillCompositeRegistered) return;\n Color.registerFillComposite?.({\n ensureResources: ensureFillCompositeResources,\n clearMask: clearFillMask,\n getCompositeRect: getFillCompositeRect,\n getShaderMask: getFillShaderMask,\n });\n isFillCompositeRegistered = true;\n}\n","// =============================================================================\n// Module: Fill\n// =============================================================================\n/**\n * The Fill module contains functions and classes dedicated to handling\n * the fill properties of shapes within the drawing context. It supports complex fill\n * operations with effects such as bleeding to simulate watercolor-like textures. The\n * methods provided allow for setting the fill color with opacity, controlling the\n * intensity of the bleed effect, and enabling or disabling the fill operation.\n *\n * The watercolor effect implementation is inspired by Tyler Hobbs'\n * techniques for simulating watercolor paints.\n */\n\n// Core imports\nimport { Renderer, Cwidth, Cheight, Density } from \"../core/target.js\";\nimport {\n Mix,\n State,\n} from \"../core/color.js\";\nimport { drawPolygon, circle } from \"./mask.js\";\nimport {\n constrain,\n weightedRand,\n rr,\n map,\n randInt,\n gaussian,\n rotate,\n cos,\n sin,\n _onSeed,\n} from \"../core/utils.js\";\nimport { isFieldReady } from \"../core/flowfield.js\";\nimport { createColor, getAffineMatrix } from \"../core/runtime.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\n\n// Internal module imports\nimport { initFillComposite } from \"./composite.js\";\n\ninitFillComposite(); // Register the fill composite with the core color module\n\n// =============================================================================\n// Fill State and helpers\n// =============================================================================\n\n// Vertex cap for grow() — set to 0 or false to disable\nconst GROW_MAX_VERTS = 2024;\nlet GROW_CAP;\n\n// Reusable scratch arrays for grow() — avoids 4 allocations per call (~15× per fill)\nlet _growInsX = [];\nlet _growInsY = [];\nlet _growMods = [];\nlet _growDirs = [];\n\n/**\n * Global fill state settings.\n */\nState.fill = {\n opacity: 150,\n bleed_strength: 0.07,\n texture_strength: 0.8,\n border_strength: 0.5,\n direction: \"out\",\n isActive: false,\n};\n\n// Cache the current state\nconst FillState = () => ({ ...State.fill });\nconst FillSetState = (state) => {\n State.fill = { ...state };\n};\n\n// ---------------------------------------------------------------------------\n// Fill Style Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Sets the fill color and opacity for subsequent drawing operations.\n * @param {number|string|Color} a - Either the red component, a CSS color string, or a Color object.\n * @param {number} [b] - The green component or the opacity if using grayscale.\n * @param {number} [c] - The blue component.\n * @param {number} [d] - The opacity.\n */\nexport function fill(a, b, c, d) {\n State.fill.opacity = (arguments.length < 4 ? b : d) || 150;\n State.fill.color = arguments.length < 3 ? createColor(a) : createColor(a, b, c);\n State.fill.isActive = true;\n}\n\n/**\n * Sets the bleed (watercolor) intensity and direction.\n * @param {number} _i - The bleed intensity (clamped to [0,1]).\n * @param {string} [_direction=\"out\"] - The bleeding direction.\n */\nexport function fillBleed(_i, _direction = \"out\") {\n State.fill.bleed_strength = constrain(_i, 0, 1);\n State.fill.direction = _direction;\n}\n\n/**\n * Sets the texture and border strengths for the fill.\n * @param {number} [_texture=0.4] - The texture strength (clamped to [0,1]).\n * @param {number} [_border=0.4] - The border strength (clamped to [0,1]).\n */\nexport function fillTexture(_texture = 0.4, _border = 0.4) {\n State.fill.texture_strength = constrain(_texture, 0, 1);\n State.fill.border_strength = constrain(_border, 0, 1);\n}\n\n/**\n * Disables fill for subsequent drawing operations.\n */\nexport function noFill() {\n State.fill.isActive = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fill Manager Functions\n// ---------------------------------------------------------------------------\n\nlet _polygon;\n\n// Pre-compute gaussians for reuse\nconst GAUSSIAN_POOL_SIZE = 512;\nconst _gaussians = [[], []]; // [a, b]\nfunction _fillGaussianPools() {\n for (let i = 0; i < GAUSSIAN_POOL_SIZE; i++) {\n _gaussians[0][i] = gaussian(0.5, 0.2);\n _gaussians[1][i] = gaussian(0, 0.02);\n }\n}\n_onSeed(_fillGaussianPools);\n\n// Helper for direction checking - extracted to reduce duplication\nfunction _isLeft(a, b, c) {\n return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) > 0.01;\n}\n\n/**\n * Calculates the centroid of a polygon from its vertices.\n * @param {Object[]} pts - Array of points with {x, y}.\n * @returns {Object} The center point {x, y}.\n */\nfunction _center(pts) {\n if (pts.length === 0) {\n return { x: 0, y: 0 };\n }\n\n if (pts.length < 8) {\n // Simple average for small polygons\n const sum = pts.reduce(\n (center, point) => ({ x: center.x + point.x, y: center.y + point.y }),\n { x: 0, y: 0 },\n );\n return { x: sum.x / pts.length, y: sum.y / pts.length };\n }\n\n // Close polygon if needed\n const v = [...pts];\n if (v[0].x !== v[v.length - 1].x || v[0].y !== v[v.length - 1].y)\n v.push(v[0]);\n\n // Calculate using shoelace formula (more efficient implementation)\n let area = 0,\n cx = 0,\n cy = 0;\n for (let i = 0; i < v.length - 1; i++) {\n const cross = v[i].x * v[i + 1].y - v[i + 1].x * v[i].y;\n area += cross;\n cx += (v[i].x + v[i + 1].x) * cross;\n cy += (v[i].y + v[i + 1].y) * cross;\n }\n\n area *= 0.5;\n return area\n ? { x: cx / (6 * area), y: cy / (6 * area) }\n : { x: v[0].x, y: v[0].y };\n}\n\n/**\n * Fills a given polygon with a watercolor effect.\n * @param {Polygon} polygon - The polygon to fill.\n */\nexport function createFill(polygon) {\n if (!State.fill.isActive || !State.fill.color) {\n throw new Error(\n \"No fill color set. Call brush.fill(color) before drawing shapes.\",\n );\n }\n _polygon = polygon;\n const v = [...polygon.vertices];\n const fluid = ~~(v.length * 0.25 * weightedRand({ 1: 5, 2: 10, 3: 60 }));\n const strength = State.fill.bleed_strength;\n const modifiers = v.map(\n (_, i) => (i > fluid ? 1 : 0.3) * rr(0.85, 1.4) * strength,\n );\n const shift = randInt(0, v.length);\n const shifted = [...v.slice(shift), ...v.slice(0, shift)];\n const center = _center(shifted);\n return new FillPoly(shifted, modifiers, center, [], true).fill(\n State.fill.color,\n map(State.fill.opacity, 0, 255, 0, 1, true),\n State.fill.texture_strength,\n );\n}\n\n// ---------------------------------------------------------------------------\n// FillPolygon Class\n// ---------------------------------------------------------------------------\n\n/**\n * The FillPolygon class is used to create and manage the properties of the polygons that produces\n * the watercolor effect. It includes methods to grow (expand) the polygon and apply layers\n * of color with varying intensity and erase parts to simulate a natural watercolor bleed.\n * The implementation follows Tyler Hobbs' guide to simulating watercolor:\n * https://tylerxhobbs.com/essays/2017/a-generative-approach-to-simulating-watercolor-paints\n */\nclass FillPoly {\n /**\n * Constructs a FillPolygon.\n * @param {Object[]} _v - Vertices of the polygon.\n * @param {number[]} _m - Multipliers for the bleed effect at each vertex.\n * @param {Object} _center - The polygon's center {x, y}.\n * @param {boolean[]} dir - Array indicating bleed direction per vertex.\n * @param {boolean} isFirst - True for initial polygon.\n */\n constructor(v, m, center, dir = [], isFirst = false, sx, sy) {\n // Initialize properties\n this.v = v;\n this.m = m;\n this.dir = dir;\n this.midP = center;\n\n // Initialize size and direction for first polygon\n if (isFirst) {\n // Calculate size bounds\n let maxX = 0,\n maxY = 0;\n const rayCalc = [];\n\n for (let i = 0; i < v.length; i++) {\n // Store vertex distances to center for size calculation\n const dx = Math.abs(center.x - v[i].x);\n const dy = Math.abs(center.y - v[i].y);\n maxX = Math.max(maxX, dx);\n maxY = Math.max(maxY, dy);\n\n // Store edge info for ray calculations\n const v1 = v[i],\n v2 = v[(i + 1) % v.length];\n const side = { x: v2.x - v1.x, y: v2.y - v1.y };\n const rt = rotate(0, 0, side.x, side.y, 90);\n const mid = { x: v1.x + side.x / 2, y: v1.y + side.y / 2 };\n\n rayCalc.push({\n v1,\n v2,\n ray: {\n point1: mid,\n point2: { x: mid.x + rt.x, y: mid.y + rt.y },\n },\n });\n }\n\n // Store sizes\n this.sizeX = maxX;\n this.sizeY = maxY;\n\n // Calculate directions\n this.dir = Array(v.length);\n rayCalc.forEach((rc, i) => {\n let count = 0;\n for (const isect of _polygon.intersect(rc.ray)) {\n if (_isLeft(rc.v1, rc.v2, isect)) count++;\n }\n this.dir[i] = count % 2 === 0;\n });\n\n // Randomize center (single calculation)\n const rx = rr(-0.6, 0.6) * maxX;\n const ry = rr(-0.6, 0.6) * maxY;\n this.midP = { x: center.x + rx, y: center.y + ry };\n } else {\n this.sizeX = sx;\n this.sizeY = sy;\n }\n }\n\n /**\n * Trims vertices from the polygon based on a factor.\n * @param {number} [factor=1] - Factor determining amount of trimming.\n * @returns {Object} An object containing trimmed vertices, multipliers, and direction.\n */\n trim(f = 1) {\n // Fast path for common case\n if (f >= 1 || f < 0 || this.v.length <= 8) {\n return { v: this.v, m: this.m, dir: this.dir };\n }\n\n // Trim from middle for balance\n const n = ~~((1 - f) * this.v.length);\n const s = ~~(this.v.length / 2 - n / 2);\n\n // Copy only the kept ranges instead of cloning the full arrays and splicing.\n const keep = this.v.length - n;\n const v = new Array(keep);\n const m = new Array(keep);\n const dir = new Array(keep);\n let dst = 0;\n\n for (let i = 0; i < s; i++, dst++) {\n v[dst] = this.v[i];\n m[dst] = this.m[i];\n dir[dst] = this.dir[i];\n }\n\n for (let i = s + n; i < this.v.length; i++, dst++) {\n v[dst] = this.v[i];\n m[dst] = this.m[i];\n dir[dst] = this.dir[i];\n }\n\n\n // We want to add at least two vertices to divide the new edge that appears after trimming, at random distances along its path\n const trimStart = s;\n const trimEnd = s + n;\n const edgeStart = this.v[(trimStart - 1 + this.v.length) % this.v.length];\n const edgeEnd = this.v[trimEnd % this.v.length];\n const edgeVec = { x: edgeEnd.x - edgeStart.x, y: edgeEnd.y - edgeStart.y };\n \n // Insert two new vertices at random positions along the new edge\n const insertCount = 2;\n for (let i = 0; i < insertCount; i++) {\n const t = rr(0.25, 0.75); // Random position between 25% and 75% along the edge\n const newVertex = { x: edgeStart.x + edgeVec.x * t, y: edgeStart.y + edgeVec.y * t };\n const insertIdx = s + i;\n v.splice(insertIdx, 0, newVertex);\n m.splice(insertIdx, 0, rr(0.4, 0.7));\n dir.splice(insertIdx, 0, this.dir[trimStart % this.dir.length]);\n }\n\n return { v, m, dir };\n }\n\n /**\n * Randomly samples a fraction of vertices, keeping their order.\n * Any sampled vertex outside the original polygon is pulled inward.\n * @param {number} [ratio=0.3] - Fraction of vertices to keep.\n * @returns {FillPoly} A new FillPoly with fewer vertices, guaranteed inside the original.\n */\n scatter(ratio = 0.3) {\n const L = this.v.length;\n const keep = Math.max(3, ~~(L * ratio));\n const indices = [];\n const step = L / keep;\n for (let i = 0; i < keep; i++) {\n indices.push(~~(i * step + rr(0, step * 0.8)));\n }\n\n const sv = [],\n sm = [],\n sd = [];\n const mid = this.midP;\n const sides = _polygon.sides;\n\n for (const idx of indices) {\n const j = idx % L;\n let p = this.v[j];\n let crossings = 0;\n for (const [a, b] of sides) {\n const ay = a.y,\n by = b.y;\n if ((ay > p.y) === (by > p.y)) continue;\n const t = (p.y - ay) / (by - ay);\n if (p.x < a.x + t * (b.x - a.x)) crossings++;\n }\n if (crossings % 2 === 0) {\n p = {\n x: mid.x + (p.x - mid.x) * rr(0.3, 0.6),\n y: mid.y + (p.y - mid.y) * rr(0.3, 0.6),\n };\n }\n sv.push(p);\n sm.push(this.m[j]);\n sd.push(!this.dir[j]);\n }\n\n return new FillPoly(sv, sm, this.midP, sd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Returns a copy with all bleed directions flipped.\n */\n flipDirs() {\n return new FillPoly(this.v, this.m, this.midP, this.dir.map(d => !d), false, this.sizeX, this.sizeY);\n }\n\n /**\n * Grows (or shrinks) the polygon vertices to simulate watercolor spread.\n * @param {number} [growthFactor=1] - Factor controlling growth.\n * @returns {FillPoly} A new FillPoly with adjusted vertices.\n */\n grow(f = 1) {\n const { v: tr_v, m: tr_m, dir: tr_dir } = this.trim(f);\n const len = tr_v.length;\n\n const outLen = len * 2;\n if (_growInsX.length < len) { _growInsX = new Array(len); _growInsY = new Array(len); }\n if (_growMods.length < outLen) { _growMods = new Array(outLen); _growDirs = new Array(outLen); }\n const insertedX = _growInsX;\n const insertedY = _growInsY;\n const newMods = _growMods;\n const newDirs = _growDirs;\n const bleedDirDeg = State.fill.direction === \"out\" ? -90 : 90;\n\n if (_gaussians[0].length === 0) _fillGaussianPools();\n const gPool = _gaussians[0],\n gPoolLen = gPool.length;\n const g2Pool = _gaussians[1],\n g2PoolLen = g2Pool.length;\n\n let idx = 0;\n let insertedIdx = 0;\n let mod = f === 999 ? rr(0.6, 0.8) : State.fill.bleed_strength;\n\n for (let i = 0; i < len; i++) {\n const cv = tr_v[i];\n const nv = tr_v[i + 1 < len ? i + 1 : 0];\n const mi = tr_m[i];\n const di = tr_dir[i];\n\n if (f < 997) mod = mi;\n\n // If mod is smaller than 0.02, skip growing math and just insert the middle vertex\n if (mod < 0.05) {\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n insertedX[insertedIdx] = (cv.x + nv.x) / 2;\n insertedY[insertedIdx] = (cv.y + nv.y) / 2;\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n insertedIdx++;\n continue;\n }\n\n const rotDeg = (di ? bleedDirDeg : -bleedDirDeg) + rr(-1, 1) * 5;\n const c = cos(rotDeg);\n const s = sin(rotDeg);\n\n const sideX = nv.x - cv.x;\n const sideY = nv.y - cv.y;\n const dirX = c * sideX + s * sideY;\n const dirY = c * sideY - s * sideX;\n\n const d = gPool[~~(rr(0, 1) * gPoolLen)] * rr(0.65, 1.35) * mod;\n const nextMod = mi + g2Pool[~~(rr(0, 1) * g2PoolLen)];\n\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n\n insertedX[insertedIdx] = cv.x + sideX * 0.5 + dirX * d;\n insertedY[insertedIdx] = cv.y + sideY * 0.5 + dirY * d;\n newMods[idx] = nextMod;\n newDirs[idx] = di;\n idx++;\n insertedIdx++;\n }\n\n let fv,\n fm,\n fd;\n \n if (GROW_CAP && idx > GROW_CAP) {\n const step = Math.ceil(idx / GROW_CAP);\n const kept = Math.ceil(idx / step);\n fv = new Array(kept);\n fm = new Array(kept);\n fd = new Array(kept);\n let dst = 0;\n for (let j = 0; j < idx; j += step, dst++) {\n fv[dst] =\n j % 2 === 0\n ? tr_v[j >> 1]\n : { x: insertedX[j >> 1], y: insertedY[j >> 1] };\n fm[dst] = newMods[j];\n fd[dst] = newDirs[j];\n }\n } else {\n fv = new Array(idx);\n for (let j = 0; j < idx; j++) {\n fv[j] =\n j % 2 === 0\n ? tr_v[j >> 1]\n : { x: insertedX[j >> 1], y: insertedY[j >> 1] };\n }\n fm = newMods.slice(0, idx);\n fd = newDirs.slice(0, idx);\n }\n return new FillPoly(fv, fm, this.midP, fd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Fills the polygon with multiple layers to simulate a watercolor effect.\n * @param {Color|string} color - The fill color.\n * @param {number} intensity - Opacity intensity (mapped from 0 to 1).\n * @param {number} tex - Texture factor.\n */\n fill(color, intensity, tex) {\n const numLayers = 20;\n const texture = tex * 3;\n const int = 2 * intensity * (1 + tex / 2);\n\n const switchingToFill = Mix.isBrush !== false;\n Mix.isBrush = false;\n if (switchingToFill) Mix.justChanged = true;\n Mix.blend(color);\n\n const m = getAffineMatrix();\n Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * m.a,\n Density * m.b,\n Density * m.c,\n Density * m.d,\n Density * (m.x + Cwidth / 2),\n Density * (m.y + Cheight / 2),\n );\n\n Mix.ctx.strokeStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${\n 0.005 * State.fill.border_strength\n })`;\n Mix.ctx.lineCap = \"round\";\n\n GROW_CAP = GROW_MAX_VERTS * Math.max(0.1, 2 * State.fill.bleed_strength);\n\n const size = Math.max(this.sizeX, this.sizeY);\n const darker = rr(0.15, 0.7);\n let pol = this.grow();\n const sparse = this.scatter(0.1).grow().scatter(0.75).flipDirs();\n let pols;\n\n for (let i = 0; i < numLayers; i++) {\n if (i % 4 === 0) {\n pol = pol.grow();\n }\n\n if (i % 2 === 0) {\n pols = [\n pol.grow(1 - 0.0125 * i),\n pol.grow(0.7 - 0.0125 * i),\n pol.grow(0.4 - 0.0125 * i),\n ];\n }\n\n for (const p of pols) {\n const grown = p.grow(999).grow(997);\n grown.layer(i, size, int, color);\n }\n const sparseLayer = sparse.grow(999).flipDirs().grow(997);\n sparseLayer.layer(i, size, int * texture, color);\n if (i % 2 === 0) {\n const darkerLayer = pol.grow(darker).grow(999);\n darkerLayer.layer(i, size, int * 2, color);\n }\n\n if (i % 8 === 0 || i === numLayers - 1) {\n if (texture !== 0) {\n pol.erase(texture * 3, intensity);\n }\n Mix.blend(color, true);\n }\n }\n\n Mix.ctx.restore();\n }\n\n /**\n * Draws a layer of the fill polygon with stroke and fill.\n * @param {number} i - The layer index.\n */\n layer(i, size, int, color) {\n Mix.ctx.lineWidth = map(i, 0, 24, size / 25, size / 30, true);\n\n Mix.ctx.fillStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${int}%)`;\n\n drawPolygon(this.v);\n Mix.ctx.fill();\n Mix.ctx.stroke();\n }\n\n /**\n * Erases parts of the polygon to create a natural watercolor texture.\n * @param {number} texture - Texture strength factor.\n * @param {number} intensity - Intensity value for size scaling.\n */\n erase(texture, intensity) {\n Mix.ctx.save();\n\n const numCircles = ~~(rr(80, 110) * map(texture, 0, 1, 2, 3.5));\n const halfSizeX = this.sizeX / 1.3;\n const halfSizeY = this.sizeY / 1.3;\n const minSize =\n Math.min(this.sizeX, this.sizeY) * (1.3);\n const minSizeFactor = 0.03 * minSize;\n const maxSizeFactor = 0.45 * minSize;\n const { x: midX, y: midY } = this.midP;\n\n Mix.ctx.globalCompositeOperation = \"destination-out\";\n\n const alpha =\n ((5 - map(intensity, 80, 100, 0.3, 0.7, true)) * texture) / 255;\n Mix.ctx.fillStyle = `rgb(255 0 0 / ${alpha})`;\n Mix.ctx.lineWidth = 0;\n\n for (let i = 0; i < numCircles; i++) {\n const x = midX + gaussian(0, halfSizeX);\n const y = midY + gaussian(0, halfSizeY);\n const radius = rr(minSizeFactor, maxSizeFactor);\n\n Mix.ctx.beginPath();\n circle(x, y, radius);\n if (i % 5 !== 0) {\n Mix.ctx.fill();\n }\n }\n\n Mix.ctx.globalCompositeOperation = \"source-over\";\n Mix.ctx.restore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Extend Polygon and Plot Prototypes for Fill\n// ---------------------------------------------------------------------------\n\n/**\n * Applies a fill effect to the polygon using the current fill state.\n * @param {Color|string} [_color] - The color for the fill.\n * @param {number} [_opacity] - The opacity value.\n * @param {number} [_bleed] - The bleed intensity.\n * @param {number} [_texture] - The texture strength.\n * @param {number} [_border] - The border strength.\n * @param {string} [_direction] - The bleed direction.\n */\nPolygon.prototype.fill = function (\n _color = false,\n _opacity,\n _bleed,\n _texture,\n _border,\n _direction,\n) {\n let state = FillState();\n if (_color) {\n fill(_color, _opacity);\n fillBleed(_bleed, _direction);\n fillTexture(_texture, _border);\n }\n if (state.isActive) {\n isFieldReady();\n createFill(this);\n }\n FillSetState(state);\n};\n\n/**\n * Fills a plot on the canvas by generating a polygon based on the provided coordinates.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - Scaling factor.\n */\nPlot.prototype.fill = function (x, y, scale) {\n if (FillState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n this.pol = this.genPol(\n x,\n y,\n scale,\n State.fill.bleed_strength < 0.06\n ? 0\n : map(State.fill.bleed_strength, 0, 0.6, 0.2, 0.60, true),\n );\n this.pol.fill();\n }\n};\n","\nexport default function earcut(data, holeIndices, dim = 2) {\n\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n let outerNode = linkedList(data, 0, outerLen, dim, true);\n const triangles = [];\n\n if (!outerNode || outerNode.next === outerNode.prev) return triangles;\n\n let minX, minY, invSize;\n\n if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);\n\n // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox\n if (data.length > 80 * dim) {\n minX = data[0];\n minY = data[1];\n let maxX = minX;\n let maxY = minY;\n\n for (let i = dim; i < outerLen; i += dim) {\n const x = data[i];\n const y = data[i + 1];\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n\n // minX, minY and invSize are later used to transform coords into integers for z-order calculation\n invSize = Math.max(maxX - minX, maxY - minY);\n invSize = invSize !== 0 ? 32767 / invSize : 0;\n }\n\n earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);\n\n return triangles;\n}\n\n// create a circular doubly linked list from polygon points in the specified winding order\nfunction linkedList(data, start, end, dim, clockwise) {\n let last;\n\n if (clockwise === (signedArea(data, start, end, dim) > 0)) {\n for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n } else {\n for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n }\n\n if (last && equals(last, last.next)) {\n removeNode(last);\n last = last.next;\n }\n\n return last;\n}\n\n// eliminate colinear or duplicate points\nfunction filterPoints(start, end) {\n if (!start) return start;\n if (!end) end = start;\n\n let p = start,\n again;\n do {\n again = false;\n\n if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {\n removeNode(p);\n p = end = p.prev;\n if (p === p.next) break;\n again = true;\n\n } else {\n p = p.next;\n }\n } while (again || p !== end);\n\n return end;\n}\n\n// main ear slicing loop which triangulates a polygon (given as a linked list)\nfunction earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {\n if (!ear) return;\n\n // interlink polygon nodes in z-order\n if (!pass && invSize) indexCurve(ear, minX, minY, invSize);\n\n let stop = ear;\n\n // iterate through ears, slicing them one by one\n while (ear.prev !== ear.next) {\n const prev = ear.prev;\n const next = ear.next;\n\n if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {\n triangles.push(prev.i, ear.i, next.i); // cut off the triangle\n\n removeNode(ear);\n\n // skipping the next vertex leads to less sliver triangles\n ear = next.next;\n stop = next.next;\n\n continue;\n }\n\n ear = next;\n\n // if we looped through the whole remaining polygon and can't find any more ears\n if (ear === stop) {\n // try filtering points and slicing again\n if (!pass) {\n earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);\n\n // if this didn't work, try curing all small self-intersections locally\n } else if (pass === 1) {\n ear = cureLocalIntersections(filterPoints(ear), triangles);\n earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);\n\n // as a last resort, try splitting the remaining polygon into two\n } else if (pass === 2) {\n splitEarcut(ear, triangles, dim, minX, minY, invSize);\n }\n\n break;\n }\n }\n}\n\n// check whether a polygon node forms a valid ear with adjacent nodes\nfunction isEar(ear) {\n const a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n // now make sure we don't have other points inside the potential ear\n const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox\n const x0 = Math.min(ax, bx, cx),\n y0 = Math.min(ay, by, cy),\n x1 = Math.max(ax, bx, cx),\n y1 = Math.max(ay, by, cy);\n\n let p = c.next;\n while (p !== a) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&\n area(p.prev, p, p.next) >= 0) return false;\n p = p.next;\n }\n\n return true;\n}\n\nfunction isEarHashed(ear, minX, minY, invSize) {\n const a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox\n const x0 = Math.min(ax, bx, cx),\n y0 = Math.min(ay, by, cy),\n x1 = Math.max(ax, bx, cx),\n y1 = Math.max(ay, by, cy);\n\n // z-order range for the current triangle bbox;\n const minZ = zOrder(x0, y0, minX, minY, invSize),\n maxZ = zOrder(x1, y1, minX, minY, invSize);\n\n let p = ear.prevZ,\n n = ear.nextZ;\n\n // look for points inside the triangle in both directions\n while (p && p.z >= minZ && n && n.z <= maxZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n // look for remaining points in decreasing z-order\n while (p && p.z >= minZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n }\n\n // look for remaining points in increasing z-order\n while (n && n.z <= maxZ) {\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n return true;\n}\n\n// go through all polygon nodes and cure small local self-intersections\nfunction cureLocalIntersections(start, triangles) {\n let p = start;\n do {\n const a = p.prev,\n b = p.next.next;\n\n if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {\n\n triangles.push(a.i, p.i, b.i);\n\n // remove two nodes involved\n removeNode(p);\n removeNode(p.next);\n\n p = start = b;\n }\n p = p.next;\n } while (p !== start);\n\n return filterPoints(p);\n}\n\n// try splitting polygon into two and triangulate them independently\nfunction splitEarcut(start, triangles, dim, minX, minY, invSize) {\n // look for a valid diagonal that divides the polygon into two\n let a = start;\n do {\n let b = a.next.next;\n while (b !== a.prev) {\n if (a.i !== b.i && isValidDiagonal(a, b)) {\n // split the polygon in two by the diagonal\n let c = splitPolygon(a, b);\n\n // filter colinear points around the cuts\n a = filterPoints(a, a.next);\n c = filterPoints(c, c.next);\n\n // run earcut on each half\n earcutLinked(a, triangles, dim, minX, minY, invSize, 0);\n earcutLinked(c, triangles, dim, minX, minY, invSize, 0);\n return;\n }\n b = b.next;\n }\n a = a.next;\n } while (a !== start);\n}\n\n// link every hole into the outer loop, producing a single-ring polygon without holes\nfunction eliminateHoles(data, holeIndices, outerNode, dim) {\n const queue = [];\n\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n const list = linkedList(data, start, end, dim, false);\n if (list === list.next) list.steiner = true;\n queue.push(getLeftmost(list));\n }\n\n queue.sort(compareXYSlope);\n\n // process holes from left to right\n for (let i = 0; i < queue.length; i++) {\n outerNode = eliminateHole(queue[i], outerNode);\n }\n\n return outerNode;\n}\n\nfunction compareXYSlope(a, b) {\n let result = a.x - b.x;\n // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find\n // the bridge to the outer shell is always the point that they meet at.\n if (result === 0) {\n result = a.y - b.y;\n if (result === 0) {\n const aSlope = (a.next.y - a.y) / (a.next.x - a.x);\n const bSlope = (b.next.y - b.y) / (b.next.x - b.x);\n result = aSlope - bSlope;\n }\n }\n return result;\n}\n\n// find a bridge between vertices that connects hole with an outer ring and link it\nfunction eliminateHole(hole, outerNode) {\n const bridge = findHoleBridge(hole, outerNode);\n if (!bridge) {\n return outerNode;\n }\n\n const bridgeReverse = splitPolygon(bridge, hole);\n\n // filter collinear points around the cuts\n filterPoints(bridgeReverse, bridgeReverse.next);\n return filterPoints(bridge, bridge.next);\n}\n\n// David Eberly's algorithm for finding a bridge between hole and outer polygon\nfunction findHoleBridge(hole, outerNode) {\n let p = outerNode;\n const hx = hole.x;\n const hy = hole.y;\n let qx = -Infinity;\n let m;\n\n // find a segment intersected by a ray from the hole's leftmost point to the left;\n // segment's endpoint with lesser x will be potential connection point\n // unless they intersect at a vertex, then choose the vertex\n if (equals(hole, p)) return p;\n do {\n if (equals(hole, p.next)) return p.next;\n else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {\n const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);\n if (x <= hx && x > qx) {\n qx = x;\n m = p.x < p.next.x ? p : p.next;\n if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint\n }\n }\n p = p.next;\n } while (p !== outerNode);\n\n if (!m) return null;\n\n // look for points inside the triangle of hole point, segment intersection and endpoint;\n // if there are no points found, we have a valid connection;\n // otherwise choose the point of the minimum angle with the ray as connection point\n\n const stop = m;\n const mx = m.x;\n const my = m.y;\n let tanMin = Infinity;\n\n p = m;\n\n do {\n if (hx >= p.x && p.x >= mx && hx !== p.x &&\n pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {\n\n const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential\n\n if (locallyInside(p, hole) &&\n (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {\n m = p;\n tanMin = tan;\n }\n }\n\n p = p.next;\n } while (p !== stop);\n\n return m;\n}\n\n// whether sector in vertex m contains sector in vertex p in the same coordinates\nfunction sectorContainsSector(m, p) {\n return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;\n}\n\n// interlink polygon nodes in z-order\nfunction indexCurve(start, minX, minY, invSize) {\n let p = start;\n do {\n if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);\n p.prevZ = p.prev;\n p.nextZ = p.next;\n p = p.next;\n } while (p !== start);\n\n p.prevZ.nextZ = null;\n p.prevZ = null;\n\n sortLinked(p);\n}\n\n// Simon Tatham's linked list merge sort algorithm\n// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html\nfunction sortLinked(list) {\n let numMerges;\n let inSize = 1;\n\n do {\n let p = list;\n let e;\n list = null;\n let tail = null;\n numMerges = 0;\n\n while (p) {\n numMerges++;\n let q = p;\n let pSize = 0;\n for (let i = 0; i < inSize; i++) {\n pSize++;\n q = q.nextZ;\n if (!q) break;\n }\n let qSize = inSize;\n\n while (pSize > 0 || (qSize > 0 && q)) {\n\n if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {\n e = p;\n p = p.nextZ;\n pSize--;\n } else {\n e = q;\n q = q.nextZ;\n qSize--;\n }\n\n if (tail) tail.nextZ = e;\n else list = e;\n\n e.prevZ = tail;\n tail = e;\n }\n\n p = q;\n }\n\n tail.nextZ = null;\n inSize *= 2;\n\n } while (numMerges > 1);\n\n return list;\n}\n\n// z-order of a point given coords and inverse of the longer side of data bbox\nfunction zOrder(x, y, minX, minY, invSize) {\n // coords are transformed into non-negative 15-bit integer range\n x = (x - minX) * invSize | 0;\n y = (y - minY) * invSize | 0;\n\n x = (x | (x << 8)) & 0x00FF00FF;\n x = (x | (x << 4)) & 0x0F0F0F0F;\n x = (x | (x << 2)) & 0x33333333;\n x = (x | (x << 1)) & 0x55555555;\n\n y = (y | (y << 8)) & 0x00FF00FF;\n y = (y | (y << 4)) & 0x0F0F0F0F;\n y = (y | (y << 2)) & 0x33333333;\n y = (y | (y << 1)) & 0x55555555;\n\n return x | (y << 1);\n}\n\n// find the leftmost node of a polygon ring\nfunction getLeftmost(start) {\n let p = start,\n leftmost = start;\n do {\n if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;\n p = p.next;\n } while (p !== start);\n\n return leftmost;\n}\n\n// check if a point lies within a convex triangle\nfunction pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {\n return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&\n (ax - px) * (by - py) >= (bx - px) * (ay - py) &&\n (bx - px) * (cy - py) >= (cx - px) * (by - py);\n}\n\n// check if a point lies within a convex triangle but false if its equal to the first point of the triangle\nfunction pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {\n return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);\n}\n\n// check if a diagonal between two polygon nodes is valid (lies in polygon interior)\nfunction isValidDiagonal(a, b) {\n return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges\n (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible\n (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors\n equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case\n}\n\n// signed area of a triangle\nfunction area(p, q, r) {\n return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);\n}\n\n// check if two points are equal\nfunction equals(p1, p2) {\n return p1.x === p2.x && p1.y === p2.y;\n}\n\n// check if two segments intersect\nfunction intersects(p1, q1, p2, q2) {\n const o1 = sign(area(p1, q1, p2));\n const o2 = sign(area(p1, q1, q2));\n const o3 = sign(area(p2, q2, p1));\n const o4 = sign(area(p2, q2, q1));\n\n if (o1 !== o2 && o3 !== o4) return true; // general case\n\n if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1\n if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1\n if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2\n if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2\n\n return false;\n}\n\n// for collinear points p, q, r, check if point q lies on segment pr\nfunction onSegment(p, q, r) {\n return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);\n}\n\nfunction sign(num) {\n return num > 0 ? 1 : num < 0 ? -1 : 0;\n}\n\n// check if a polygon diagonal intersects any polygon segments\nfunction intersectsPolygon(a, b) {\n let p = a;\n do {\n if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&\n intersects(p, p.next, a, b)) return true;\n p = p.next;\n } while (p !== a);\n\n return false;\n}\n\n// check if a polygon diagonal is locally inside the polygon\nfunction locallyInside(a, b) {\n return area(a.prev, a, a.next) < 0 ?\n area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :\n area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;\n}\n\n// check if the middle point of a polygon diagonal is inside the polygon\nfunction middleInside(a, b) {\n let p = a;\n let inside = false;\n const px = (a.x + b.x) / 2;\n const py = (a.y + b.y) / 2;\n do {\n if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&\n (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))\n inside = !inside;\n p = p.next;\n } while (p !== a);\n\n return inside;\n}\n\n// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;\n// if one belongs to the outer ring and another to a hole, it merges it into a single ring\nfunction splitPolygon(a, b) {\n const a2 = createNode(a.i, a.x, a.y),\n b2 = createNode(b.i, b.x, b.y),\n an = a.next,\n bp = b.prev;\n\n a.next = b;\n b.prev = a;\n\n a2.next = an;\n an.prev = a2;\n\n b2.next = a2;\n a2.prev = b2;\n\n bp.next = b2;\n b2.prev = bp;\n\n return b2;\n}\n\n// create a node and optionally link it with previous one (in a circular doubly linked list)\nfunction insertNode(i, x, y, last) {\n const p = createNode(i, x, y);\n\n if (!last) {\n p.prev = p;\n p.next = p;\n\n } else {\n p.next = last.next;\n p.prev = last;\n last.next.prev = p;\n last.next = p;\n }\n return p;\n}\n\nfunction removeNode(p) {\n p.next.prev = p.prev;\n p.prev.next = p.next;\n\n if (p.prevZ) p.prevZ.nextZ = p.nextZ;\n if (p.nextZ) p.nextZ.prevZ = p.prevZ;\n}\n\nfunction createNode(i, x, y) {\n return {\n i, // vertex index in coordinates array\n x, y, // vertex coordinates\n prev: null, // previous and next vertex nodes in a polygon ring\n next: null,\n z: 0, // z-order curve value\n prevZ: null, // previous and next nodes in z-order\n nextZ: null,\n steiner: false // indicates whether this is a steiner point\n };\n}\n\n// return a percentage difference between the polygon area and its triangulation area;\n// used to verify correctness of triangulation\nexport function deviation(data, holeIndices, dim, triangles) {\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n\n let polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));\n if (hasHoles) {\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n polygonArea -= Math.abs(signedArea(data, start, end, dim));\n }\n }\n\n let trianglesArea = 0;\n for (let i = 0; i < triangles.length; i += 3) {\n const a = triangles[i] * dim;\n const b = triangles[i + 1] * dim;\n const c = triangles[i + 2] * dim;\n trianglesArea += Math.abs(\n (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -\n (data[a] - data[b]) * (data[c + 1] - data[a + 1]));\n }\n\n return polygonArea === 0 && trianglesArea === 0 ? 0 :\n Math.abs((trianglesArea - polygonArea) / polygonArea);\n}\n\nfunction signedArea(data, start, end, dim) {\n let sum = 0;\n for (let i = start, j = end - dim; i < end; i += dim) {\n sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);\n j = i;\n }\n return sum;\n}\n\n// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts\nexport function flatten(data) {\n const vertices = [];\n const holes = [];\n const dimensions = data[0][0].length;\n let holeIndex = 0;\n let prevLen = 0;\n\n for (const ring of data) {\n for (const p of ring) {\n for (let d = 0; d < dimensions; d++) vertices.push(p[d]);\n }\n if (prevLen) {\n holeIndex += prevLen;\n holes.push(holeIndex);\n }\n prevLen = ring.length;\n }\n return {vertices, holes, dimensions};\n}\n","// =============================================================================\n// Module: Wash\n// =============================================================================\n/**\n * Minimal stateful API for the `wash()` fill modifier.\n */\n\nimport earcut from \"earcut\";\nimport { Renderer, Cwidth, Cheight, isCanvasReady } from \"../core/target.js\";\nimport { State, flushActiveComposite } from \"../core/color.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { getAffineMatrix } from \"../core/runtime.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport { createColor } from \"../core/runtime.js\";\nimport { resetDirectShaderTracking } from \"../core/renderer_runtime.js\";\n\nlet gl = null;\nlet washProgram = null;\nlet washVao = null;\nlet washBuffer = null;\nlet washProjection = null;\nlet loadedWidth = 0;\nlet loadedHeight = 0;\nlet washGpuBufferSize = 0;\n\nconst WashAttr = {};\nconst WashUniform = {};\n\nconst washVertSrc = `#version 300 es\nin vec2 a_position;\nuniform mat4 u_matrix;\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n}`;\n\nconst washFragSrc = `#version 300 es\nprecision highp float;\nuniform vec4 u_color;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(u_color.rgb * u_color.a, u_color.a);\n}`;\n\nState.wash = {\n color: null,\n opacity: 150,\n isActive: false,\n};\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Enables wash mode with a color and opacity.\n *\n * @param {number|string|Color} a - Either the red component, a CSS color string, or a Color object.\n * @param {number} [b] - The green component or the opacity if using grayscale.\n * @param {number} [c] - The blue component.\n * @param {number} [d] - The opacity.\n */\nexport function wash(a, b, c, d) {\n isCanvasReady();\n State.wash.opacity = (arguments.length < 4 ? b : d) ?? 150;\n State.wash.color = arguments.length < 3 ? createColor(a) : createColor(a, b, c);\n State.wash.isActive = true;\n}\n\n/**\n * Disables wash mode for subsequent drawing operations.\n */\nexport function noWash() {\n State.wash.isActive = false;\n}\n\n// =============================================================================\n// GL helpers\n// =============================================================================\n\n/**\n * Lazily creates the reusable program/buffer state for solid wash drawing and\n * refreshes the orthographic projection when the active target size changes.\n */\nfunction ensureWashReady() {\n const nextGl = Renderer.drawingContext;\n const sizeChanged = loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (!washProjection || sizeChanged) {\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n washProjection = new Float32Array([\n 2 / loadedWidth,\n 0,\n 0,\n 0,\n 0,\n -2 / loadedHeight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n 1,\n 0,\n 1,\n ]);\n }\n\n if (gl === nextGl && washProgram && washVao && washBuffer) return;\n\n gl = nextGl;\n washProgram = createProgram(gl, washVertSrc, washFragSrc);\n WashAttr.a_position = gl.getAttribLocation(washProgram, \"a_position\");\n WashUniform.u_matrix = gl.getUniformLocation(washProgram, \"u_matrix\");\n WashUniform.u_color = gl.getUniformLocation(washProgram, \"u_color\");\n\n washVao = gl.createVertexArray();\n gl.bindVertexArray(washVao);\n\n washBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, 0, gl.DYNAMIC_DRAW);\n washGpuBufferSize = 0;\n\n gl.enableVertexAttribArray(WashAttr.a_position);\n gl.vertexAttribPointer(WashAttr.a_position, 2, gl.FLOAT, false, 8, 0);\n\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n}\n\n/**\n * Applies the current runtime affine transform and converts the result into\n * the screen-space coordinates used by the direct GL wash pipeline.\n *\n * @param {number} x - The source x-coordinate in brush drawing space.\n * @param {number} y - The source y-coordinate in brush drawing space.\n * @returns {[number, number]} The transformed screen-space position.\n */\nfunction transformVertexToScreen(x, y) {\n const m = getAffineMatrix();\n return [\n m.a * x + m.c * y + m.x + loadedWidth / 2,\n m.b * x + m.d * y + m.y + loadedHeight / 2,\n ];\n}\n\n/**\n * Triangulates a polygon in local space and returns the transformed triangle\n * vertex buffer ready for upload to the GPU.\n *\n * @param {Polygon} polygon - The polygon to triangulate.\n * @returns {{ triangles: Float32Array, vertexCount: number }} Screen-space\n * triangle vertices plus the number of vertices to draw.\n */\nfunction buildTriangleBuffer(polygon) {\n const flat = new Float32Array(polygon.vertices.length * 2);\n for (let i = 0; i < polygon.vertices.length; i++) {\n const vertex = polygon.vertices[i];\n flat[i * 2] = vertex.x;\n flat[i * 2 + 1] = vertex.y;\n }\n\n const indices = earcut(flat);\n const triangles = new Float32Array(indices.length * 2);\n for (let i = 0; i < indices.length; i++) {\n const idx = indices[i];\n const [screenX, screenY] = transformVertexToScreen(flat[idx * 2], flat[idx * 2 + 1]);\n triangles[i * 2] = screenX;\n triangles[i * 2 + 1] = screenY;\n }\n\n return {\n triangles,\n vertexCount: indices.length,\n };\n}\n\n/**\n * Draws a triangulated solid wash directly to the current GL target.\n *\n * @param {Polygon} polygon - The polygon to fill with the current wash state.\n */\nfunction drawWashPolygon(polygon) {\n if (!State.wash?.isActive || !State.wash.color || polygon.vertices.length < 3) return;\n\n flushActiveComposite();\n ensureWashReady();\n const { triangles, vertexCount } = buildTriangleBuffer(polygon);\n const byteCount = triangles.byteLength;\n gl.useProgram(washProgram);\n gl.enable(gl.BLEND);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n gl.bindVertexArray(washVao);\n gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);\n if (byteCount > washGpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, triangles, gl.DYNAMIC_DRAW);\n washGpuBufferSize = byteCount;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, triangles);\n }\n const color = State.wash.color._array;\n gl.uniformMatrix4fv(WashUniform.u_matrix, false, washProjection);\n gl.uniform4f(\n WashUniform.u_color,\n color[0],\n color[1],\n color[2],\n State.wash.opacity / 255,\n );\n\n gl.drawArrays(gl.TRIANGLES, 0, vertexCount);\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n resetDirectShaderTracking(Renderer, gl);\n}\n\n// =============================================================================\n// Prototype methods\n// =============================================================================\n\n/**\n * Applies a direct GL wash fill to the polygon using the current wash state.\n *\n * @param {Color|string|false} [_color] - Optional override color for this call.\n * @param {number} [_opacity] - Optional override opacity for this call.\n */\nPolygon.prototype.wash = function (_color = false, _opacity) {\n const state = { ...State.wash };\n if (_color !== false) wash(_color, _opacity);\n\n if (State.wash.isActive) {\n drawWashPolygon(this);\n }\n\n State.wash = { ...state };\n};\n\n/**\n * Applies wash to a plot by first generating the plot polygon, mirroring the\n * existing fill-path behavior, and then drawing that polygon with wash.\n *\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\nPlot.prototype.wash = function (x, y, scale) {\n if (!State.wash?.isActive) return;\n if (this.origin) {\n x = this.origin[0];\n y = this.origin[1];\n scale = 1;\n }\n this.pol = this.genPol(x, y, scale, 0, -1);\n this.pol.wash();\n};\n","// =============================================================================\n// Adapter: Standalone Renderer Hooks\n// =============================================================================\n\nimport { Cwidth, Cheight, Density } from \"../../core/target.js\";\nimport { setRendererRuntime } from \"../../core/renderer_runtime.js\";\n\nfunction beginDirectMaskDraw(_renderer, gl, target) {\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n if (hadDepthTest) gl.disable(gl.DEPTH_TEST);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, target.framebuffer);\n gl.viewport(0, 0, target.width * target.density, target.height * target.density);\n\n return { hadDepthTest };\n}\n\nfunction endDirectMaskDraw(renderer, gl, state) {\n if (state?.hadDepthTest) gl.enable(gl.DEPTH_TEST);\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.viewport(\n 0,\n 0,\n Math.max(1, Math.round(Cwidth * Density)),\n Math.max(1, Math.round(Cheight * Density)),\n );\n}\n\nfunction resetStandaloneShaderTracking(_renderer, gl) {\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n}\n\nexport function initStandaloneRendererRuntime() {\n setRendererRuntime({\n beginDirectMaskDraw,\n endDirectMaskDraw,\n resetDirectShaderTracking: resetStandaloneShaderTracking,\n });\n}\n","// =============================================================================\n// Adapter: Standalone Compositor Hooks\n// =============================================================================\n\nimport { createProgram } from \"../../core/gl/utils.js\";\nimport {\n setCompositorRuntime,\n blitDefaultFramebufferSource,\n} from \"../../core/compositor_runtime.js\";\n\nfunction clearTarget(renderer, target, isFramebufferTarget) {\n if (!target) return;\n\n if (isFramebufferTarget(target)) {\n const gl = renderer.drawingContext;\n const previousFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);\n const previousViewport = gl.getParameter(gl.VIEWPORT);\n gl.bindFramebuffer(gl.FRAMEBUFFER, target.framebuffer);\n gl.viewport(0, 0, target.width * target.density, target.height * target.density);\n gl.clearColor(0, 0, 0, 0);\n gl.clear(gl.COLOR_BUFFER_BIT);\n gl.bindFramebuffer(gl.FRAMEBUFFER, previousFramebuffer);\n gl.viewport(\n previousViewport[0],\n previousViewport[1],\n previousViewport[2],\n previousViewport[3],\n );\n return;\n }\n\n const ctx = target.drawingContext;\n ctx.save();\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.clearRect(0, 0, target.width, target.height);\n ctx.restore();\n}\n\nfunction makeShader(gl, vertSrc, fragSrc) {\n const program = createProgram(gl, vertSrc, fragSrc);\n const uniformCache = new Map();\n\n // Persistent VAO for fullscreen-triangle draws (avoids create/delete per pass)\n const quadVao = gl.createVertexArray();\n\n const getUniformLocation = (name) => {\n if (!uniformCache.has(name)) {\n uniformCache.set(name, gl.getUniformLocation(program, name));\n }\n return uniformCache.get(name);\n };\n\n // Pre-cache sampler and color uniform locations (called every blend pass)\n const loc_source = gl.getUniformLocation(program, \"u_source\");\n const loc_mask = gl.getUniformLocation(program, \"u_mask\");\n const loc_color = gl.getUniformLocation(program, \"u_color\");\n\n return {\n program,\n quadVao,\n loc_source,\n loc_mask,\n loc_color,\n setUniform(name, value) {\n const location = getUniformLocation(name);\n if (!location) return;\n if (typeof value === \"boolean\") {\n gl.uniform1i(location, value ? 1 : 0);\n return;\n }\n if (typeof value === \"number\") {\n gl.uniform1f(location, value);\n return;\n }\n if (Array.isArray(value)) {\n if (value.length === 3) gl.uniform3f(location, value[0], value[1], value[2]);\n else if (value.length === 4) gl.uniform4f(location, value[0], value[1], value[2], value[3]);\n return;\n }\n },\n };\n}\n\nfunction ensureBlendShaderProgram(renderer, vertSrc, fragSrc) {\n renderer.shaderProgram ??= makeShader(renderer.drawingContext, vertSrc, fragSrc);\n return renderer.shaderProgram;\n}\n\nfunction createFramebufferTexture(gl, width, height) {\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(\n gl.TEXTURE_2D,\n 0,\n gl.RGBA,\n width,\n height,\n 0,\n gl.RGBA,\n gl.UNSIGNED_BYTE,\n null,\n );\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.bindTexture(gl.TEXTURE_2D, null);\n return texture;\n}\n\nfunction createFramebuffer(renderer, options) {\n const gl = renderer.drawingContext;\n const density = options.density ?? 1;\n const framebuffer = gl.createFramebuffer();\n const width = Math.max(1, options.width);\n const height = Math.max(1, options.height);\n const pixelWidth = Math.max(1, Math.round(width * density));\n const pixelHeight = Math.max(1, Math.round(height * density));\n const colorTexture = createFramebufferTexture(gl, pixelWidth, pixelHeight);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);\n gl.framebufferTexture2D(\n gl.FRAMEBUFFER,\n gl.COLOR_ATTACHMENT0,\n gl.TEXTURE_2D,\n colorTexture,\n 0,\n );\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n\n return {\n __brushFramebuffer: true,\n framebuffer,\n colorTexture,\n width,\n height,\n density,\n pixelDensity: () => density,\n remove() {\n gl.deleteFramebuffer(framebuffer);\n gl.deleteTexture(colorTexture);\n },\n };\n}\n\nfunction ensureBlendSourceFramebuffer(\n renderer,\n currentFramebuffer,\n width,\n height,\n density,\n) {\n currentFramebuffer?.remove?.();\n return createFramebuffer(renderer, {\n width,\n height,\n density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n}\n\nfunction runBlendShaderPass({\n renderer,\n shader,\n source,\n mask,\n color,\n isBrushMask,\n dirtyRect,\n targetIsFramebuffer,\n withScissor,\n}) {\n const gl = renderer.drawingContext;\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n const previousFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);\n const previousProgram = gl.getParameter(gl.CURRENT_PROGRAM);\n const previousVao = gl.getParameter(gl.VERTEX_ARRAY_BINDING);\n\n gl.bindVertexArray(shader.quadVao);\n gl.useProgram(shader.program);\n gl.disable(gl.DEPTH_TEST);\n gl.enable(gl.BLEND);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, source.colorTexture);\n gl.uniform1i(shader.loc_source, 0);\n\n gl.activeTexture(gl.TEXTURE1);\n gl.bindTexture(gl.TEXTURE_2D, mask.colorTexture);\n gl.uniform1i(shader.loc_mask, 1);\n\n shader.setUniform(\"u_targetIsFramebuffer\", targetIsFramebuffer);\n shader.setUniform(\"u_isBrush\", isBrushMask);\n gl.uniform3f(shader.loc_color, color[0], color[1], color[2]);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n withScissor(\n gl,\n dirtyRect,\n () => {\n gl.drawArrays(gl.TRIANGLES, 0, 3);\n },\n !targetIsFramebuffer,\n );\n\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.activeTexture(gl.TEXTURE0);\n gl.bindVertexArray(previousVao);\n gl.useProgram(previousProgram);\n gl.bindFramebuffer(gl.FRAMEBUFFER, previousFramebuffer);\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n}\n\nfunction blitSourceToFramebuffer(args) {\n return blitDefaultFramebufferSource(args);\n}\n\nexport function initStandaloneCompositorRuntime() {\n setCompositorRuntime({\n clearTarget,\n ensureBlendShaderProgram,\n ensureBlendSourceFramebuffer,\n createFramebuffer,\n runBlendShaderPass,\n blitSourceToFramebuffer,\n });\n}\n","// =============================================================================\n// Adapter: Standalone Stroke Hooks\n// =============================================================================\n\nimport { create2DCanvas, get2DContext } from \"../../core/compositor_runtime.js\";\nimport { setStrokeRuntime } from \"../../stroke/runtime.js\";\n\nfunction cssColor(value) {\n if (typeof value === \"number\") {\n const c = Math.max(0, Math.min(255, value));\n return `rgb(${c} ${c} ${c})`;\n }\n return value ?? \"black\";\n}\n\nfunction buildTipSurface(canvas) {\n const ctx = get2DContext(canvas, true);\n const surface = {\n canvas,\n drawingContext: ctx,\n width: canvas.width,\n height: canvas.height,\n pixels: null,\n _fillStyle: \"#ffffff\",\n _strokeStyle: \"transparent\",\n _lineWidth: 1,\n\n pixelDensity() {\n return 1;\n },\n\n background(value) {\n ctx.save();\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.fillStyle = cssColor(value);\n ctx.fillRect(0, 0, canvas.width, canvas.height);\n ctx.restore();\n },\n\n noSmooth() {\n ctx.imageSmoothingEnabled = false;\n },\n\n push() {\n ctx.save();\n },\n\n pop() {\n ctx.restore();\n },\n\n translate(x, y) {\n ctx.translate(x, y);\n },\n\n scale(x, y = x) {\n ctx.scale(x, y);\n },\n\n rotate(angle) {\n ctx.rotate(angle);\n },\n\n noStroke() {\n surface._strokeStyle = \"transparent\";\n },\n\n stroke(value) {\n surface._strokeStyle = cssColor(value);\n },\n\n noFill() {\n surface._fillStyle = \"transparent\";\n },\n\n fill(value) {\n surface._fillStyle = cssColor(value);\n },\n\n strokeWeight(value) {\n surface._lineWidth = value;\n },\n\n rect(x, y, w, h) {\n ctx.beginPath();\n ctx.rect(x, y, w, h);\n surface._paint();\n },\n\n circle(x, y, d) {\n ctx.beginPath();\n ctx.arc(x, y, d / 2, 0, Math.PI * 2);\n surface._paint();\n },\n\n ellipse(x, y, w, h) {\n ctx.beginPath();\n ctx.ellipse(x, y, w / 2, h / 2, 0, 0, Math.PI * 2);\n surface._paint();\n },\n\n line(x1, y1, x2, y2) {\n ctx.beginPath();\n ctx.moveTo(x1, y1);\n ctx.lineTo(x2, y2);\n ctx.strokeStyle = surface._strokeStyle;\n ctx.lineWidth = surface._lineWidth;\n ctx.stroke();\n },\n\n beginShape() {\n ctx.beginPath();\n surface._shapeStarted = false;\n },\n\n vertex(x, y) {\n if (!surface._shapeStarted) {\n ctx.moveTo(x, y);\n surface._shapeStarted = true;\n } else {\n ctx.lineTo(x, y);\n }\n },\n\n endShape(close = false) {\n if (close) ctx.closePath();\n surface._paint();\n },\n\n loadPixels() {\n surface.pixels = ctx.getImageData(0, 0, canvas.width, canvas.height).data;\n },\n\n updatePixels() {\n const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);\n imageData.data.set(surface.pixels);\n ctx.putImageData(imageData, 0, 0);\n },\n\n _paint() {\n if (surface._fillStyle !== \"transparent\") {\n ctx.fillStyle = surface._fillStyle;\n ctx.fill();\n }\n if (surface._strokeStyle !== \"transparent\") {\n ctx.strokeStyle = surface._strokeStyle;\n ctx.lineWidth = surface._lineWidth;\n ctx.stroke();\n }\n },\n };\n\n return surface;\n}\n\nfunction createTipSurface(width, height) {\n return buildTipSurface(create2DCanvas(width, height, true));\n}\n\nfunction loadImageTip(src, imageToWhite) {\n return new Promise((resolve, reject) => {\n const NativeImage = globalThis.Image;\n if (!NativeImage) {\n reject(new Error(\"Standalone image brush loading requires Image support.\"));\n return;\n }\n\n const nativeImg = new NativeImage();\n nativeImg.onload = () => {\n const surface = buildTipSurface(\n create2DCanvas(nativeImg.naturalWidth, nativeImg.naturalHeight, true),\n );\n surface.drawingContext.drawImage(nativeImg, 0, 0);\n imageToWhite(surface);\n resolve(surface);\n };\n nativeImg.onerror = () =>\n reject(new Error(`Failed to load image tip: ${src}`));\n nativeImg.crossOrigin = \"anonymous\";\n nativeImg.src = src;\n });\n}\n\nexport function initStandaloneStrokeRuntime() {\n setStrokeRuntime({\n createTipSurface,\n loadImageTip,\n });\n}\n","/**\n * @fileoverview Standalone entry point for brush.\n */\n\nexport * from \"./adapters/standalone/runtime.js\";\nexport * from \"./adapters/standalone/frame.js\";\nexport { createCanvas } from \"./adapters/standalone/target.js\";\nexport * from \"./index.shared.js\";\n\nimport { initStandaloneTargetRuntime } from \"./adapters/standalone/target.js\";\nimport { initStandaloneRendererRuntime } from \"./adapters/standalone/renderer.js\";\nimport { initStandaloneCompositorRuntime } from \"./adapters/standalone/compositor.js\";\nimport { initStandaloneStrokeRuntime } from \"./adapters/standalone/stroke.js\";\nimport { initStandaloneRuntime } from \"./adapters/standalone/runtime.js\";\n\ninitStandaloneTargetRuntime();\ninitStandaloneRuntime();\ninitStandaloneRendererRuntime();\ninitStandaloneCompositorRuntime();\ninitStandaloneStrokeRuntime();\n","// =============================================================================\n// Adapter: Standalone Frame Helpers\n// =============================================================================\n\nimport { Renderer, isCanvasReady } from \"../../core/target.js\";\nimport { Mix, flushActiveComposite } from \"../../core/color.js\";\nimport { createColor } from \"../../core/runtime.js\";\n\nfunction resetCompositeState() {\n if (Mix.glMask) Mix.clearMask(Mix.glMask);\n if (Mix.mask) Mix.clearMask(Mix.mask);\n Mix.justChanged = false;\n Mix.isBlending = false;\n Mix.isBrush = null;\n Mix.cachedColor = null;\n}\n\n/**\n * Flushes any pending stroke/fill compositing into the active standalone target.\n *\n * Standalone users should call this at the end of a drawing pass or frame.\n */\nexport function render() {\n flushActiveComposite();\n}\n\n/**\n * Clears the active standalone target.\n *\n * With no arguments, clears to transparent white.\n * With a color, clears to that color at full opacity.\n *\n * @param {...*} args\n */\nexport function clear(...args) {\n isCanvasReady();\n resetCompositeState();\n\n const gl = Renderer.drawingContext;\n const color =\n args.length === 0\n ? [1, 1, 1, 0]\n : [...createColor(...args)._array.slice(0, 3), 1];\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.disable(gl.SCISSOR_TEST);\n gl.clearColor(color[0], color[1], color[2], color[3]);\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n}\n"],"names":["identityMatrix","a","b","c","d","x","y","Cwidth","Cheight","Renderer","Density","usesRadians","fromDegrees","angle","createColor","Error","getAffineMatrix","targetRuntime","load","syncDensity","isCanvasReady","instance","inst","activateInstance","deactivateInstance","getActiveFramebuffer","isFramebufferTarget","setTargetState","state","Instance","target","expandDirtyRect","rect","padding","minX","minY","maxX","maxY","create2DCanvas","width","height","willReadFrequently","canvas","OffscreenCanvas","element","document","createElement","drawingContext","getContext","undefined","compositorRuntime","clearTarget","ensureBlendShaderProgram","ensureBlendSourceFramebuffer","createFramebuffer","runBlendShaderPass","blitSourceToFramebuffer","args","strokeComposite","fillComposite","clearRenderTarget","getTargetPixelSize","Math","max","round","normalizeDirtyRect","floor","min","ceil","clampDirtyRect","getFullDirtyRect","getFullRect","toScissorBox","flipY","normalized","withScissor","gl","draw","box","enable","SCISSOR_TEST","scissor","disable","State","isMixReady","loaded","Mix","isBlending","cachedColor","markDirtyRect","dirtyRect","isDrawn","clearMask","composite","this","glMask","getCompositeRect","isBrushMask","needsBlendSourceFramebuffer","blendSourceFramebuffer","pixelDensity","ensureResources","fillResources","mask","ctx","blend","_color","_isLast","isBrush","otherMask","nextColor","_array","colorChanged","justChanged","applyShader","shader","shaderProgram","activeFramebuffer","source","renderer","sourceTarget","sourceFramebuffer","targetIsFramebuffer","shaderMask","getShaderMask","color","flushActiveComposite","SQRT3","sqrt","F2","G2","fastFloor","grad2","Float64Array","createNoise2D","random","perm","p","Uint8Array","i","tableSize","r","aux","buildPermutationTable","permGrad2x","map","v","permGrad2y","n0","n1","n2","s","j","t","x0","y0","i1","j1","x1","y1","x2","y2","ii","jj","t0","gi0","t1","gi1","t2","gi2","prng_alea","seed","opts","xg","AleaGen","prng","next","double","int32","quick","constructor","Date","n","mash","data","String","length","charCodeAt","h","s0","s1","s2","copy","f","rng","rng2","_seedCallbacks","_onSeed","cb","push","noise","noise2","rr","e","rr2","rArray","array","randInt","randInt2","gaussian","mean","stdev","u","log","cos","weightedRand","weights","totalWeight","entries","key","cumulative","rnd","isNaN","parseInt","value","withinBounds","constrain","low","high","nAngle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","fill","NaN","sLookup","idx","sin","toDegrees","rad","isRad","runtimeUsesRadians","toDegreesSigned","rotate","cx","cy","coseno","seno","dist","hypot","calcAngle","atan2","intersectLines","s1a","s1b","s2a","s2b","includeSegmentExtension","x3","y3","x4","y4","deltaX1","deltaY1","deltaX2","deltaY2","denominator","ua","ub","isLoaded","isFieldReady","resolution","left_x","top_y","num_columns","num_rows","addField","field","bs","ba","fillField","ar","abs","dif","sr","cr","_t","dir","offset","attractors","Array","from","wx","wy","att","dx","dy","w","freq","amp","_r","Position","m","mx","my","update","plotted","colIdx","rowIdx","reset","isIn","isActive","isInCanvas","skipCheck","list","get","current","wiggle","moveTo","_dir","_length","_step_length","movePos","_moveToDegrees","plotTo","_plot","_scale","_dirPlot","_step","scaleFactor","steps","fieldActive","usePlot","getRowIndex","y_offset","getColIndex","x_offset","col","row","Map","FIELD_ANGLE_MODES","Set","normalizeFieldAngleMode","options","angleMode","has","generateField","entry","normalizeFieldAngles","gen","keys","join","name","funct","set","fn","_stateStack","clamp","DEGREES","RADIANS","colorContext","currentAngleMode","transformStack","currentTransform","multiplyTransform","left","right","Color","g","hex","rgbToHex","rgbaMatch","exec","alpha","parseFloat","standardize","rgb","hexToRgb","toString","slice","replace","_match","red","green","blue","result","getColorContext","fillStyle","_getRed","_getGreen","_getBlue","initStandaloneRuntime","hooks","_current","_curvature","_strokeArray","_strokeOrigin","activeTarget","activeDensity","activeWidth","activeHeight","applyLoadedTarget","density","premultipliedAlpha","getTargetContext","createRenderer","Polygon","pointsArray","useRawVertices","vertices","sides","arr","_intersectionCache","intersect","line","cacheKey","point1","point2","points","start","end","intersection","show","wash","mass","hatch","stroke","Plot","_type","segments","angles","pres","type","calcIndex","pol","addSegment","_a","_pres","_degrees","pop","reduce","sum","len","endPlot","pressure","_d","curving","index","map0","map1","suma","genPol","_x","_y","_side","step","numSteps","pos","pside","prevIdx","scale","arc","radius","startDeg","sweepDeg","segmentCount","segmentSweep","arcLength","startX","startY","SubPath","isClosed","curvature","vert","vertex","_createSpline","beginShape","endShape","close","PI2","pep","tep","pep2","done","p1","p2","p3","d1","d2","a1","a2","curvAdjust","dmax","temp","temp2","point3","point4","intPt","halfDist","asin","origin","strokeRuntime","createTipSurface","loadImageTip","isStrokeCompositeRegistered","createProgram","frag","src","VERTEX_SHADER","FRAGMENT_SHADER","createShader","shaderSource","compileShader","attachShader","linkProgram","rendererRuntime","beginDirectMaskDraw","endDirectMaskDraw","resetDirectShaderTracking","framebufferProjMatrix","vao","buf","program","loadedWidth","loadedHeight","brushMaskTarget","Attr","Frag","_ma","_mb","_mc","_md","_mx","_my","_halfW","_halfH","_density","circleData","INITIAL_CAPACITY","circleCount","bufferCapacity","gpuBufferSize","circleDirtyRect","imgProgram","imgVao","imgCornerBuf","imgInstanceBuf","imgAttr","imgFrag","imgGpuSize","imgData","IMG_INIT_CAP","imgCount","imgCapacity","imgDirtyRect","texCache","QUAD_CORNERS","getProjectionMatrix","beginMaskTarget","endMaskTarget","accumulateDirtyRect","currentRect","circle","diameter","newData","px","py","screenX","screenY","dScreenX","dScreenY","glDrawImages","p5img","targetState","tex","createTexture","bindTexture","TEXTURE_2D","texImage2D","RGBA","UNSIGNED_BYTE","texParameteri","TEXTURE_MIN_FILTER","LINEAR","TEXTURE_MAG_FILTER","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","useProgram","BLEND","blendFunc","ONE_MINUS_DST_ALPHA","ONE","activeTexture","TEXTURE0","uniform1i","u_tex","uniform4f","u_color","uniformMatrix4fv","u_proj","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","drawArraysInstanced","TRIANGLE_STRIP","flush","needsStrokeMask","remove","antialias","depth","stencil","_Renderer","weight","opacity","DEFAULT_CUSTOM_PRESSURE_VARIATION","warp","tilt","BrushState","BrushSetState","add","params","includes","markerTip","vibration","scatter","definition","sharpness","quality","grain","min_max","curve","variation","isArray","mode","rest","range","ns","nm","ne","normalizePressure","tip","deleteTexture","delete","invalidateTexEntry","background","noSmooth","translate","noStroke","T","imageToWhite","tips","tipKey","param","colors","buffers","image","getBrushParams","brushName","pick","arguments","strokeWeight","_position","initializeDrawingState","plot","snapshotMatrix","gaussians","angleScale","isPlot","cp","ct","cs","ck","noiseoffset","rendererMask","ensureBrushMaskTarget","nextGl","needsContextRefresh","forEach","getAttribLocation","getUniformLocation","createVertexArray","createBuffer","enableVertexAttribArray","a_position","vertexAttribPointer","FLOAT","a_radius","a_alpha","clear","STATIC_DRAW","a_corner","a_pos","IMG_FLOATS","vertexAttribDivisor","a_size","a_angle","isReady","switchingToBrush","saveState","stepSize","spacing","totalSteps","pressureCount","cachedPressure","lineNoiseCount","cachedLineNoise","u_matrix","drawArrays","POINTS","glDraw","restoreState","calculatePressure","lineNoise","sw","iterations","rX","yRandomFactor","sqrtPart","drawSpray","drawMarker","drawImageTip","plotAngle","plotCos","plotSin","perp","along","drawDefault","simPressure","peakPos","halfWidth","pow","gauss","vibrate","rx","ry","size","overscan","maxPressure","scatterReach","tipReach","getImageTipOverscan","extraPadding","halfSize","extraRadius","base","boundsRadius","stampImage","_vals","_standard_brushes","obj","prototype","_brush","_weight","loadPixels","average","pixels","updatePixels","filter","k","Promise","all","then","HatchState","HatchSetState","rand","continuous","gradient","scanlineHatch","polygon","cosA","sinA","cosB","sinB","verts","rotated","Infinity","edges","eLen","Y","sort","scanY","getHatchLines","polygons","segs","poly","getHatchSegments","getActiveHatchConfig","lines","isConnector","prev","createHatch","drawSegment","save","hBrush","Object","values","drawFn","withHatchStyle","renderHatchSegments","jitterPolygon","jitterX","jitterY","projectAnchorToBisector","anchor","nx","ny","getShortArcAngles","toAngleUnit","endDeg","splitSegment","seg","gap","gx","gy","drawMassArcs","pivotBias","bias","bounds","getPolygonBounds","sx","sy","getPivotAnchor","parts","part","center","startAngle","endAngle","drawMassPass","createMass","shape","pols","isPolygon","brush","basePolygon","maxJitter","jitters","getMassPolygons","hatchState","brushState","fieldState","precision","strength","outline","hatchDist","baseAngle","_dist","_angle","_options","FillMaskUploadCanvas","isFillCompositeRegistered","maskWidth","maskHeight","needsFillMaskCanvas","fillMaskFramebuffer","needsFillMaskFramebuffer","imageSmoothingEnabled","_getActiveFramebuffer","uploadRect","uploadWidth","uploadHeight","uploadContext","clearRect","drawImage","colorTexture","texSubImage2D","GROW_CAP","_growInsX","_growInsY","_growMods","_growDirs","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","_polygon","_gaussians","_fillGaussianPools","_isLeft","FillPoly","isFirst","midP","rayCalc","v1","v2","side","rt","mid","ray","sizeX","sizeY","rc","count","isect","trim","keep","dst","trimStart","trimEnd","edgeStart","edgeEnd","edgeVec","newVertex","insertIdx","splice","ratio","L","indices","sv","sm","sd","crossings","ay","by","flipDirs","grow","tr_v","tr_m","tr_dir","outLen","insertedX","insertedY","newMods","newDirs","bleedDirDeg","gPool","gPoolLen","g2Pool","g2PoolLen","fv","fm","fd","insertedIdx","mod","cv","nv","mi","di","rotDeg","sideX","sideY","dirX","dirY","nextMod","kept","intensity","texture","int","switchingToFill","setTransform","strokeStyle","lineCap","darker","sparse","layer","numLayers","erase","restore","lineWidth","matrix","getTransform","beginPath","first","tx","ty","lineTo","closePath","strokePadding","drawPolygon","numCircles","halfSizeX","halfSizeY","minSize","minSizeFactor","maxSizeFactor","midX","midY","globalCompositeOperation","filterPoints","again","steiner","equals","area","removeNode","earcutLinked","ear","triangles","dim","invSize","pass","z","zOrder","prevZ","nextZ","numMerges","inSize","tail","q","pSize","qSize","sortLinked","indexCurve","stop","isEarHashed","isEar","cureLocalIntersections","splitEarcut","ax","bx","pointInTriangleExceptFirst","minZ","maxZ","intersects","locallyInside","isValidDiagonal","splitPolygon","pointInTriangle","intersectsPolygon","inside","middleInside","q1","q2","o1","sign","o2","o3","o4","onSegment","num","createNode","b2","an","bp","insertNode","last","_opacity","_bleed","fluid","modifiers","_","shift","shifted","pts","point","cross","_center","createFill","FillSetState","washProgram","washVao","washBuffer","washProjection","washGpuBufferSize","WashAttr","WashUniform","transformVertexToScreen","_renderer","hadDepthTest","isEnabled","DEPTH_TEST","bindFramebuffer","FRAMEBUFFER","framebuffer","viewport","resetStandaloneShaderTracking","blendEquation","FUNC_ADD","ONE_MINUS_SRC_ALPHA","previousFramebuffer","getParameter","FRAMEBUFFER_BINDING","previousViewport","VIEWPORT","clearColor","COLOR_BUFFER_BIT","vertSrc","fragSrc","uniformCache","quadVao","loc_source","loc_mask","loc_color","setUniform","location","uniform3f","uniform1f","makeShader","pixelWidth","pixelHeight","createFramebufferTexture","framebufferTexture2D","COLOR_ATTACHMENT0","__brushFramebuffer","deleteFramebuffer","currentFramebuffer","previousProgram","CURRENT_PROGRAM","previousVao","VERTEX_ARRAY_BINDING","TEXTURE1","TRIANGLES","sourceBox","previousReadFramebuffer","READ_FRAMEBUFFER_BINDING","previousDrawFramebuffer","DRAW_FRAMEBUFFER_BINDING","READ_FRAMEBUFFER","DRAW_FRAMEBUFFER","blitFramebuffer","NEAREST","blitDefaultFramebufferSource","cssColor","buildTipSurface","get2DContext","surface","_fillStyle","_strokeStyle","_lineWidth","fillRect","noFill","_paint","ellipse","_shapeStarted","getImageData","imageData","putImageData","resolve","reject","NativeImage","globalThis","Image","nativeImg","onload","naturalWidth","naturalHeight","onerror","crossOrigin","ensureWashReady","vertexCount","flat","holeIndices","outerLen","outerNode","signedArea","linkedList","earcut","buildTriangleBuffer","drawWashPolygon","HTMLCanvasElement","isCanvasTarget","isOffscreenCanvasTarget","isSupportedTarget","initStandaloneRendererRuntime","initStandaloneCompositorRuntime","initStandaloneStrokeRuntime","angleOffset","randomFactor","randomAngle","offsetX","offsetY","DEPTH_BUFFER_BIT","region","logicalWidth","logicalHeight","Number","style","id","parent","querySelector","appendChild","buffer","loadTarget","saved","popState","currentField","theta","cosTheta","sinTheta","callback","_array_points"],"mappings":"6BAIA,MAAMA,EAAiB,CACrBC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,GAGE,ICEIC,EAAQC,EAAmBC,EAAUC,EDFrCC,EAAc,KAAM,EACpBC,EAAeC,GAAUA,EACzBC,EAAc,KACvB,MAAM,IAAIC,MAAM,yCAEPC,EAAkB,IAAMhB,ECD/BiB,EAAgB,CAClBC,KAAM,KACJ,MAAM,IAAIH,MAAM,0CAElBI,YAAa,IAAMT,EACnBU,cAAe,KACb,MAAM,IAAIL,MAAM,0CAElBM,SAAWC,MAGXC,iBAAmBD,MAGnBE,mBAAoB,OACpBC,qBAAsB,IAAM,KAC5BC,oBAAqB,KAAM,GAQtB,SAASC,EAAeC,GACzB,WAAYA,IAAOrB,EAASqB,EAAMrB,QAClC,YAAaqB,IAAOpB,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,MAAMkC,WAAatO,EAAMoM,MAAMuC,QACxC,MAAM,IAAI/S,MACR,6FAGJ,MAAMupC,EAAe12B,GAAKC,IAAI1O,EAAMoM,MAAMuC,SAC1Cw2B,EAAa/4B,MAAQqE,GAAc00B,EAAc7gC,EACnD,WwBxPO,WACL3B,GACF,WtByKO,SAAgBjH,GACrB,MAAM0pC,EACJ5zB,KAAqBF,GAAU5V,EAASA,EAAQiD,KAAK0K,GAAM,IACvDg8B,EAAW1mC,KAAKwJ,IAAIi9B,GACpBE,EAAW3mC,KAAKiL,IAAIw7B,GAC1B1zB,GAAmBC,GAAkBD,GAAkB,CACrD5W,EAAGuqC,EACHtqC,EAAGuqC,EACHtqC,GAAIsqC,EACJrqC,EAAGoqC,EACHnqC,EAAG,EACHC,EAAG,GAEP,UAQO,SAAeD,EAAGC,EAAID,GAC3BwW,GAAmBC,GAAkBD,GAAkB,CACrD5W,EAAGI,EACHH,EAAG,EACHC,EAAG,EACHC,EAAGE,EACHD,EAAG,EACHC,EAAG,GAEP,iBUWO,SAAsBqU,GAC3B,IAAK,MAAM2U,MAAEA,KAAW1V,GAAKye,SACvB/I,IACFA,EAAMxC,QAAUnS,EAChB2U,EAAM5B,SAAW/S,EACjB2U,EAAMgD,SAAW3X,EAGvB,SblNqBpL,IACnB2C,EAAMxB,EAAUnB,GAChB4C,EAAOzB,EAAU,GAAGnB,OACpB,IAAK,MAAMmhC,KAAYt+B,EACrBs+B,uBKuNG,SAAgBC,EAAe/xB,EAAa,IACjD,IAAK+xB,GAAiBA,EAAcj/B,OAAS,EAC3C,MAAM,IAAI3K,MACR,+EAGI8c,GAAc8sB,EAAe/xB,GACnC/T,MACJ,4CFlFO,SAAmBxE,EAAGC,GAC3BuW,GAAmBC,GAAkBD,GAAkB,CACrD5W,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,IACAC,KAEJ","x_google_ignoreList":[5,6,26]}
\ No newline at end of file
+{"version":3,"file":"brush.js","sources":["../src/core/runtime.js","../src/core/target.js","../src/core/dirty_rect.js","../src/core/compositor_runtime.js","../src/core/color.js","../node_modules/simplex-noise/dist/esm/simplex-noise.js","../node_modules/esm-seedrandom/esm/index.mjs","../src/core/utils.js","../src/core/flowfield.js","../src/core/save.js","../src/adapters/standalone/runtime.js","../src/adapters/standalone/target.js","../src/core/primitives.js","../src/core/polygon.js","../src/core/plot.js","../src/stroke/runtime.js","../src/stroke/composite.js","../src/core/gl/utils.js","../src/core/renderer_runtime.js","../src/stroke/gl_draw.js","../src/stroke/stroke.js","../src/hatch/hatch.js","../src/hatch/mass.js","../src/fill/mask.js","../src/fill/composite.js","../src/fill/fill.js","../node_modules/earcut/src/earcut.js","../src/fill/wash.js","../src/adapters/standalone/renderer.js","../src/adapters/standalone/compositor.js","../src/adapters/standalone/stroke.js","../src/index.standalone.js","../src/adapters/standalone/frame.js"],"sourcesContent":["// =============================================================================\n// Runtime Hooks\n// =============================================================================\n\nconst identityMatrix = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\n\nexport let usesRadians = () => false;\nexport let fromDegrees = (angle) => angle;\nexport let createColor = () => {\n throw new Error(\"No runtime color adapter registered.\");\n};\nexport let getAffineMatrix = () => identityMatrix;\n\n/**\n * Registers or updates host-runtime hooks used by core modules.\n *\n * @param {object} hooks\n */\nexport function setRuntime(hooks) {\n if (hooks.usesRadians) usesRadians = hooks.usesRadians;\n if (hooks.fromDegrees) fromDegrees = hooks.fromDegrees;\n if (hooks.createColor) createColor = hooks.createColor;\n if (hooks.getAffineMatrix) getAffineMatrix = hooks.getAffineMatrix;\n}\n","// =============================================================================\n// Target Runtime Hooks\n// =============================================================================\n\n/**\n * Shared target state exposed to core modules.\n *\n * Host adapters are expected to keep these bindings updated with the currently\n * active drawing target. The exact object type is adapter-defined, but core code\n * assumes the active renderer exposes:\n * - `drawingContext`: the active WebGL context\n * - target dimensions through `Cwidth` / `Cheight`\n * - pixel density through `Density`\n */\n\nexport let Cwidth, Cheight, Instance, Renderer, Density;\n\nlet targetRuntime = {\n load: () => {\n throw new Error(\"No target runtime adapter registered.\");\n },\n syncDensity: () => Density,\n isCanvasReady: () => {\n throw new Error(\"No target runtime adapter registered.\");\n },\n instance: (inst) => {\n Instance = inst;\n },\n activateInstance: (inst) => {\n Instance = inst;\n },\n deactivateInstance: () => {},\n getActiveFramebuffer: () => null,\n isFramebufferTarget: () => false,\n};\n\n/**\n * Updates the shared target state consumed by core modules.\n *\n * @param {object} state\n */\nexport function setTargetState(state) {\n if (\"Cwidth\" in state) Cwidth = state.Cwidth;\n if (\"Cheight\" in state) Cheight = state.Cheight;\n if (\"Instance\" in state) Instance = state.Instance;\n if (\"Renderer\" in state) Renderer = state.Renderer;\n if (\"Density\" in state) Density = state.Density;\n}\n\n/**\n * Registers or updates host target hooks used by core modules.\n *\n * @param {object} hooks\n */\nexport function setTargetRuntime(hooks) {\n targetRuntime = { ...targetRuntime, ...hooks };\n}\n\nexport const load = (buffer = false) => targetRuntime.load(buffer);\nexport const syncDensity = () => targetRuntime.syncDensity();\nexport const isCanvasReady = () => targetRuntime.isCanvasReady();\nexport const instance = (inst) => targetRuntime.instance(inst);\nexport const activateInstance = (inst) => targetRuntime.activateInstance(inst);\nexport const deactivateInstance = () => targetRuntime.deactivateInstance();\nexport const getActiveFramebuffer = () => targetRuntime.getActiveFramebuffer();\nexport const isFramebufferTarget = (target) =>\n targetRuntime.isFramebufferTarget(target);\n","// =============================================================================\n// Module: Dirty Rect Utilities\n// =============================================================================\n/**\n * Expands a dirty rectangle outward by a constant padding value.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Rect to expand.\n * @param {number} [padding=0] - Padding in pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Expanded rect.\n */\nexport const expandDirtyRect = (rect, padding = 0) =>\n rect\n ? {\n minX: rect.minX - padding,\n minY: rect.minY - padding,\n maxX: rect.maxX + padding,\n maxY: rect.maxY + padding,\n }\n : null;\n\n/**\n * Clamps a dirty rectangle to explicit target bounds.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Candidate rect.\n * @param {number} width - Target width in physical pixels.\n * @param {number} height - Target height in physical pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Clamped rect.\n */\nexport const normalizeDirtyRect = (rect, width, height) => {\n if (!rect) return null;\n\n const minX = Math.max(0, Math.floor(Math.min(rect.minX, rect.maxX)));\n const minY = Math.max(0, Math.floor(Math.min(rect.minY, rect.maxY)));\n const maxX = Math.min(width, Math.ceil(Math.max(rect.minX, rect.maxX)));\n const maxY = Math.min(height, Math.ceil(Math.max(rect.minY, rect.maxY)));\n\n if (maxX <= minX || maxY <= minY) return null;\n\n return { minX, minY, maxX, maxY };\n};\n\n/**\n * Returns the union of two dirty rectangles.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} a - First rect.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} b - Second rect.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Union rect.\n */\nexport const unionDirtyRect = (a, b) => {\n if (!a) return b;\n if (!b) return a;\n\n return {\n minX: Math.min(a.minX, b.minX),\n minY: Math.min(a.minY, b.minY),\n maxX: Math.max(a.maxX, b.maxX),\n maxY: Math.max(a.maxY, b.maxY),\n };\n};\n\n/**\n * Returns a dirty rectangle covering the full target bounds.\n *\n * @param {number} width - Target width in physical pixels.\n * @param {number} height - Target height in physical pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}} Full-target rect.\n */\nexport const getFullDirtyRect = (width, height) => ({\n minX: 0,\n minY: 0,\n maxX: width,\n maxY: height,\n});\n","// =============================================================================\n// Compositor Runtime Hooks\n// =============================================================================\n\n/**\n * Shared compositor helpers and host hooks.\n *\n * The shared code in this module assumes framebuffer-like targets expose:\n * - `framebuffer`: native WebGL framebuffer handle\n * - optional lifecycle methods supplied by the host adapter\n *\n * Higher-level core modules also attach their own bookkeeping fields onto the\n * active renderer and mask targets, such as:\n * - `shaderProgram`\n * - `blendSourceFramebuffer`\n * - `glMask`\n * - `fillMaskFramebuffer`\n * - `mask`\n *\n * These are library-level contract fields, not host-specific internals.\n */\n\nexport const create2DCanvas = (width, height, willReadFrequently = false) => {\n const canvas =\n typeof OffscreenCanvas !== \"undefined\"\n ? new OffscreenCanvas(width, height)\n : (() => {\n const element = document.createElement(\"canvas\");\n element.width = width;\n element.height = height;\n return element;\n })();\n canvas.drawingContext = canvas.getContext(\n \"2d\",\n willReadFrequently ? { willReadFrequently: true } : undefined,\n );\n return canvas;\n};\n\nexport const get2DContext = (canvas, willReadFrequently = false) => {\n canvas.drawingContext ??= canvas.getContext(\n \"2d\",\n willReadFrequently ? { willReadFrequently: true } : undefined,\n );\n return canvas.drawingContext;\n};\n\nexport function blitDefaultFramebufferSource({\n renderer,\n sourceFramebuffer,\n dirtyRect,\n getTargetPixelSize,\n toScissorBox,\n}) {\n const gl = renderer.drawingContext;\n const { width, height } = getTargetPixelSize();\n const sourceBox = dirtyRect ? toScissorBox(dirtyRect) : null;\n const previousReadFramebuffer = gl.getParameter(gl.READ_FRAMEBUFFER_BINDING);\n const previousDrawFramebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING);\n\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, sourceFramebuffer.framebuffer);\n gl.blitFramebuffer(\n sourceBox?.x ?? 0,\n sourceBox?.y ?? 0,\n sourceBox ? sourceBox.x + sourceBox.width : width,\n sourceBox ? sourceBox.y + sourceBox.height : height,\n sourceBox?.x ?? 0,\n sourceBox?.y ?? 0,\n sourceBox ? sourceBox.x + sourceBox.width : width,\n sourceBox ? sourceBox.y + sourceBox.height : height,\n gl.COLOR_BUFFER_BIT,\n gl.NEAREST,\n );\n\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, previousReadFramebuffer);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, previousDrawFramebuffer);\n\n return sourceFramebuffer;\n}\n\nlet compositorRuntime = {\n clearTarget: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n ensureBlendShaderProgram: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n ensureBlendSourceFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n createFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n runBlendShaderPass: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n blitSourceToFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n};\n\n/**\n * Registers or updates host compositor hooks used by core compositing code.\n *\n * @param {object} hooks\n */\nexport function setCompositorRuntime(hooks) {\n compositorRuntime = { ...compositorRuntime, ...hooks };\n}\n\nexport const clearTarget = (...args) => compositorRuntime.clearTarget(...args);\nexport const ensureBlendShaderProgram = (...args) =>\n compositorRuntime.ensureBlendShaderProgram(...args);\nexport const ensureBlendSourceFramebuffer = (...args) =>\n compositorRuntime.ensureBlendSourceFramebuffer(...args);\nexport const createFramebuffer = (...args) =>\n compositorRuntime.createFramebuffer(...args);\nexport const runBlendShaderPass = (...args) =>\n compositorRuntime.runBlendShaderPass(...args);\nexport const blitSourceToFramebuffer = (...args) =>\n compositorRuntime.blitSourceToFramebuffer(...args);\n","import {\n Cwidth,\n Cheight,\n Renderer,\n Density,\n load as loadTarget,\n isCanvasReady,\n syncDensity,\n getActiveFramebuffer,\n isFramebufferTarget,\n} from \"./target.js\";\nimport {\n expandDirtyRect,\n normalizeDirtyRect as clampDirtyRect,\n unionDirtyRect,\n getFullDirtyRect as getFullRect,\n} from \"./dirty_rect.js\";\nimport {\n clearTarget as clearRenderTarget,\n ensureBlendShaderProgram,\n ensureBlendSourceFramebuffer,\n runBlendShaderPass,\n blitSourceToFramebuffer,\n} from \"./compositor_runtime.js\";\n\nimport vertSrc from \"./gl/shader.vert\";\nimport fragSrc from \"./gl/shader.frag\";\n\n// =============================================================================\n// Module: Configure and Initiate\n// =============================================================================\n/**\n * This module handles the configuration and initialization of the drawing system.\n * It manages canvas properties, ensures the system is ready for rendering, and\n * provides utilities for saving and restoring states.\n */\n\nlet strokeComposite = null;\nlet fillComposite = null;\n\nexport const registerStrokeComposite = (composite) => {\n strokeComposite = composite;\n};\n\nexport const registerFillComposite = (composite) => {\n fillComposite = composite;\n};\n\nconst clearTarget = (target) => {\n clearRenderTarget(Renderer, target, isFramebufferTarget);\n};\n\n// =============================================================================\n// Section: Dirty Rect Utilities\n// =============================================================================\n/**\n * Returns the current render target size in physical pixels.\n * @returns {{width: number, height: number}} Pixel size of the active target.\n */\nconst getTargetPixelSize = () => ({\n width: Math.max(1, Math.round(Cwidth * Density)),\n height: Math.max(1, Math.round(Cheight * Density)),\n});\n\nconst normalizeDirtyRect = (rect) => {\n if (!rect) return null;\n const { width, height } = getTargetPixelSize();\n return clampDirtyRect(rect, width, height);\n};\n\n/**\n * Returns a dirty rectangle covering the full active target.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}} Full-target rect.\n */\nconst getFullDirtyRect = () => {\n const { width, height } = getTargetPixelSize();\n return getFullRect(width, height);\n};\n\n// =============================================================================\n// Section: Scissor Helpers\n// =============================================================================\n/**\n * Converts a top-left-based dirty rectangle into a WebGL scissor box.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Dirty rect.\n * @returns {{x:number,y:number,width:number,height:number}|null} Scissor box or null.\n */\nconst toScissorBox = (rect, flipY = true) => {\n const normalized = normalizeDirtyRect(rect);\n if (!normalized) return null;\n\n const { height } = getTargetPixelSize();\n return {\n x: normalized.minX,\n y: flipY ? height - normalized.maxY : normalized.minY,\n width: normalized.maxX - normalized.minX,\n height: normalized.maxY - normalized.minY,\n };\n};\n\n/**\n * Runs a draw callback with a temporary scissor region.\n * @param {WebGL2RenderingContext} gl - Active WebGL context.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Dirty rect.\n * @param {Function} draw - Draw callback executed under the scissor box.\n */\nconst withScissor = (gl, rect, draw, flipY = true) => {\n const box = toScissorBox(rect, flipY);\n if (!box) {\n draw();\n return;\n }\n\n // Scissor is never nested in this module, so we can set/clear it directly\n // without saving previous GL state.\n gl.enable(gl.SCISSOR_TEST);\n gl.scissor(box.x, box.y, box.width, box.height);\n\n try {\n draw();\n } finally {\n gl.disable(gl.SCISSOR_TEST);\n }\n};\n\n/**\n * Stores the current state of the drawing system.\n * Can be used to save and restore configurations or canvas states.\n */\nexport const State = {};\n/**\n * Handles color blending using WebGL shaders. Implements advanced blending\n * effects based on Kubelka-Munk theory. Relies on spectral.js for blending logic.\n */\n\n// =============================================================================\n// Section: Color Blending / Rendering\n// =============================================================================\n/**\n * Ensures the Mix object is initialized and ready for blending.\n */\nexport const isMixReady = () => {\n if (!Renderer?.loaded) {\n isCanvasReady();\n Mix.load();\n }\n};\n\n/**\n * Manages blending operations with WebGL shaders.\n * @property {boolean} loaded - Indicates if shaders are loaded.\n * @property {boolean} isBlending - Indicates if blending is active.\n * @property {object} currentColor - Current color in WebGL format.\n * @property {function} load - Initializes blending resources.\n * @property {function} blend - Applies blending effects.\n */\nexport const Mix = {\n isBlending: false,\n cachedColor: null,\n\n /**\n * Merges a new dirty rectangle into the target's accumulated draw bounds.\n * @param {object} target - Mask buffer receiving draw output.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Rect to merge.\n */\n markDirtyRect(target, rect) {\n const normalized = normalizeDirtyRect(rect);\n if (!target || !normalized) return;\n target.dirtyRect = unionDirtyRect(target.dirtyRect, normalized);\n target.isDrawn = true;\n },\n\n /**\n * Clears a mask buffer and resets its dirty-rect tracking.\n * @param {object} target - Mask buffer to reset.\n */\n clearMask(target) {\n if (!target) return;\n const composite = target === this.glMask ? strokeComposite : fillComposite;\n composite?.clearMask?.(target, clearTarget);\n },\n\n /**\n * Resolves the region that should be composited back into the destination.\n * @param {object} target - Mask buffer being sampled.\n * @param {boolean} isBrushMask - True when compositing the GL brush mask.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\n getCompositeRect(target, isBrushMask) {\n const composite = isBrushMask ? strokeComposite : fillComposite;\n return composite?.getCompositeRect?.(\n target,\n getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n );\n },\n\n // =============================================================================\n // Section: Setup and load shaders\n // =============================================================================\n /**\n * Ensures the mask buffers and blend shader exist for the current renderer.\n */\n load() {\n syncDensity();\n const needsBlendSourceFramebuffer =\n !Renderer.blendSourceFramebuffer ||\n Renderer.blendSourceFramebuffer.width !== Cwidth ||\n Renderer.blendSourceFramebuffer.height !== Cheight ||\n (typeof Renderer.blendSourceFramebuffer.pixelDensity === \"function\" &&\n Renderer.blendSourceFramebuffer.pixelDensity() !== Density);\n ensureBlendShaderProgram(Renderer, vertSrc, fragSrc);\n\n this.glMask = strokeComposite?.ensureResources?.(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n );\n const fillResources = fillComposite?.ensureResources?.(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n clearTarget,\n ) ?? {\n mask: null,\n ctx: null,\n };\n\n if (needsBlendSourceFramebuffer) {\n Renderer.blendSourceFramebuffer = ensureBlendSourceFramebuffer(\n Renderer,\n Renderer.blendSourceFramebuffer,\n Cwidth,\n Cheight,\n Density,\n );\n }\n\n this.mask = fillResources.mask;\n this.ctx = fillResources.ctx;\n },\n\n // =============================================================================\n // Section: Compositing\n // =============================================================================\n /**\n * Flushes pending mask work when the blend color changes or a frame ends.\n * @param {Color|false} [_color=false] - New blend color.\n * @param {boolean} [_isLast=false] - True when this is the final blend flush.\n */\n blend(_color = false, _isLast = false) {\n isMixReady();\n // Only one mask is \"active\" for the current drawing mode; the other one\n // may still need flushing if the mode just changed mid-frame.\n const isBrushMask = this.isBrush === true;\n const mask = isBrushMask ? this.glMask : this.mask;\n const otherMask = isBrushMask ? this.mask : this.glMask;\n const nextColor = _color?._array;\n const colorChanged =\n !!nextColor &&\n (this.cachedColor?.[0] !== nextColor[0] ||\n this.cachedColor?.[1] !== nextColor[1] ||\n this.cachedColor?.[2] !== nextColor[2] ||\n this.cachedColor?.[3] !== nextColor[3]);\n if (!this.isBlending && nextColor) {\n this.isBlending = true;\n this.cachedColor = nextColor;\n // Reset the brush mask fully at the start of each blend cycle so stale\n // dirty-rect bookkeeping cannot leak an old stroke into the next color.\n this.clearMask(this.glMask);\n }\n\n if (_isLast || colorChanged) {\n if (this.justChanged) {\n this.applyShader(otherMask, !isBrushMask);\n this.justChanged = false;\n }\n if (this.isBlending) {\n this.applyShader(mask, isBrushMask);\n }\n if (nextColor) this.cachedColor = nextColor;\n if (_isLast) {\n this.isBlending = false;\n this.cachedColor = null;\n \n }\n }\n },\n\n /**\n * Runs the blend shader over a mask and composites the result into the active renderer.\n * @param {object} mask - Mask buffer to composite.\n * @param {boolean} isBrushMask - True when compositing the GL brush mask.\n */\n applyShader(mask, isBrushMask) {\n if (!mask?.isDrawn) return;\n\n const dirtyRect = this.getCompositeRect(mask, isBrushMask);\n if (!dirtyRect) {\n this.clearMask(mask);\n return;\n }\n\n const gl = Renderer.drawingContext;\n const shader = Renderer.shaderProgram;\n const activeFramebuffer = getActiveFramebuffer();\n const source = blitSourceToFramebuffer({\n renderer: Renderer,\n sourceTarget: activeFramebuffer ?? Renderer,\n sourceFramebuffer: Renderer.blendSourceFramebuffer,\n dirtyRect,\n isFramebufferTarget,\n Cwidth,\n Cheight,\n getTargetPixelSize,\n toScissorBox,\n withScissor,\n });\n const targetIsFramebuffer = !!activeFramebuffer;\n const composite = isBrushMask ? strokeComposite : fillComposite;\n const shaderMask = composite.getShaderMask(\n Renderer,\n mask,\n dirtyRect,\n getFullDirtyRect,\n clearTarget,\n );\n\n runBlendShaderPass({\n renderer: Renderer,\n shader,\n source,\n mask: shaderMask,\n color: this.cachedColor,\n isBrushMask,\n Cwidth,\n Cheight,\n dirtyRect,\n targetIsFramebuffer,\n withScissor,\n });\n this.clearMask(mask);\n },\n};\n\n/**\n * Flushes any pending stroke/fill mask work into the current target and resets\n * the shared compositor back to its initial idle state.\n */\nexport const flushActiveComposite = () => {\n isMixReady();\n Mix.blend(false, true);\n Mix.clearMask(Mix.glMask);\n Mix.clearMask(Mix.mask);\n Mix.justChanged = false;\n Mix.isBlending = false;\n Mix.isBrush = null;\n Mix.cachedColor = null;\n};\n\n/**\n * Loads and initializes the drawing target, then refreshes compositing\n * resources if the renderer was already active.\n *\n * @param {object|false} [buffer=false] - Optional offscreen target.\n */\nexport const load = (buffer = false) => {\n loadTarget(buffer);\n if (Renderer.loaded) Mix.load();\n};\n","/*\n * A fast javascript implementation of simplex noise by Jonas Wagner\n\nBased on a speed-improved simplex noise algorithm for 2D, 3D and 4D in Java.\nWhich is based on example code by Stefan Gustavson ([email protected]).\nWith Optimisations by Peter Eastman ([email protected]).\nBetter rank ordering method by Stefan Gustavson in 2012.\n\n Copyright (c) 2024 Jonas Wagner\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n */\n// these __PURE__ comments help uglifyjs with dead code removal\n//\nconst SQRT3 = /*#__PURE__*/ Math.sqrt(3.0);\nconst SQRT5 = /*#__PURE__*/ Math.sqrt(5.0);\nconst F2 = 0.5 * (SQRT3 - 1.0);\nconst G2 = (3.0 - SQRT3) / 6.0;\nconst F3 = 1.0 / 3.0;\nconst G3 = 1.0 / 6.0;\nconst F4 = (SQRT5 - 1.0) / 4.0;\nconst G4 = (5.0 - SQRT5) / 20.0;\n// I'm really not sure why this | 0 (basically a coercion to int)\n// is making this faster but I get ~5 million ops/sec more on the\n// benchmarks across the board or a ~10% speedup.\nconst fastFloor = (x) => Math.floor(x) | 0;\nconst grad2 = /*#__PURE__*/ new Float64Array([1, 1,\n -1, 1,\n 1, -1,\n -1, -1,\n 1, 0,\n -1, 0,\n 1, 0,\n -1, 0,\n 0, 1,\n 0, -1,\n 0, 1,\n 0, -1]);\n// double seems to be faster than single or int's\n// probably because most operations are in double precision\nconst grad3 = /*#__PURE__*/ new Float64Array([1, 1, 0,\n -1, 1, 0,\n 1, -1, 0,\n -1, -1, 0,\n 1, 0, 1,\n -1, 0, 1,\n 1, 0, -1,\n -1, 0, -1,\n 0, 1, 1,\n 0, -1, 1,\n 0, 1, -1,\n 0, -1, -1]);\n// double is a bit quicker here as well\nconst grad4 = /*#__PURE__*/ new Float64Array([0, 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1,\n 0, -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1,\n 1, 0, 1, 1, 1, 0, 1, -1, 1, 0, -1, 1, 1, 0, -1, -1,\n -1, 0, 1, 1, -1, 0, 1, -1, -1, 0, -1, 1, -1, 0, -1, -1,\n 1, 1, 0, 1, 1, 1, 0, -1, 1, -1, 0, 1, 1, -1, 0, -1,\n -1, 1, 0, 1, -1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, -1,\n 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1, 0,\n -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1, 0]);\n/**\n * Creates a 2D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction2D}\n */\nexport function createNoise2D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating this yields a little ~3% performance improvement.\n const permGrad2x = new Float64Array(perm).map(v => grad2[(v % 12) * 2]);\n const permGrad2y = new Float64Array(perm).map(v => grad2[(v % 12) * 2 + 1]);\n return function noise2D(x, y) {\n // if(!isFinite(x) || !isFinite(y)) return 0;\n let n0 = 0; // Noise contributions from the three corners\n let n1 = 0;\n let n2 = 0;\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y) * F2; // Hairy factor for 2D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const t = (i + j) * G2;\n const X0 = i - t; // Unskew the cell origin back to (x,y) space\n const Y0 = j - t;\n const x0 = x - X0; // The x,y distances from the cell origin\n const y0 = y - Y0;\n // For the 2D case, the simplex shape is an equilateral triangle.\n // Determine which simplex we are in.\n let i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords\n if (x0 > y0) {\n i1 = 1;\n j1 = 0;\n } // lower triangle, XY order: (0,0)->(1,0)->(1,1)\n else {\n i1 = 0;\n j1 = 1;\n } // upper triangle, YX order: (0,0)->(0,1)->(1,1)\n // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and\n // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where\n // c = (3-sqrt(3))/6\n const x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords\n const y1 = y0 - j1 + G2;\n const x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords\n const y2 = y0 - 1.0 + 2.0 * G2;\n // Work out the hashed gradient indices of the three simplex corners\n const ii = i & 255;\n const jj = j & 255;\n // Calculate the contribution from the three corners\n let t0 = 0.5 - x0 * x0 - y0 * y0;\n if (t0 >= 0) {\n const gi0 = ii + perm[jj];\n const g0x = permGrad2x[gi0];\n const g0y = permGrad2y[gi0];\n t0 *= t0;\n // n0 = t0 * t0 * (grad2[gi0] * x0 + grad2[gi0 + 1] * y0); // (x,y) of grad3 used for 2D gradient\n n0 = t0 * t0 * (g0x * x0 + g0y * y0);\n }\n let t1 = 0.5 - x1 * x1 - y1 * y1;\n if (t1 >= 0) {\n const gi1 = ii + i1 + perm[jj + j1];\n const g1x = permGrad2x[gi1];\n const g1y = permGrad2y[gi1];\n t1 *= t1;\n // n1 = t1 * t1 * (grad2[gi1] * x1 + grad2[gi1 + 1] * y1);\n n1 = t1 * t1 * (g1x * x1 + g1y * y1);\n }\n let t2 = 0.5 - x2 * x2 - y2 * y2;\n if (t2 >= 0) {\n const gi2 = ii + 1 + perm[jj + 1];\n const g2x = permGrad2x[gi2];\n const g2y = permGrad2y[gi2];\n t2 *= t2;\n // n2 = t2 * t2 * (grad2[gi2] * x2 + grad2[gi2 + 1] * y2);\n n2 = t2 * t2 * (g2x * x2 + g2y * y2);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to return values in the interval [-1,1].\n return 70.0 * (n0 + n1 + n2);\n };\n}\n/**\n * Creates a 3D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction3D}\n */\nexport function createNoise3D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these seems to yield a speedup of over 15%\n const permGrad3x = new Float64Array(perm).map(v => grad3[(v % 12) * 3]);\n const permGrad3y = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 1]);\n const permGrad3z = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 2]);\n return function noise3D(x, y, z) {\n let n0, n1, n2, n3; // Noise contributions from the four corners\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y + z) * F3; // Very nice and simple skew factor for 3D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const t = (i + j + k) * G3;\n const X0 = i - t; // Unskew the cell origin back to (x,y,z) space\n const Y0 = j - t;\n const Z0 = k - t;\n const x0 = x - X0; // The x,y,z distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n // For the 3D case, the simplex shape is a slightly irregular tetrahedron.\n // Determine which simplex we are in.\n let i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords\n let i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords\n if (x0 >= y0) {\n if (y0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // X Y Z order\n else if (x0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // X Z Y order\n else {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // Z X Y order\n }\n else { // x0<y0\n if (y0 < z0) {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Z Y X order\n else if (x0 < z0) {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Y Z X order\n else {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // Y X Z order\n }\n // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),\n // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and\n // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where\n // c = 1/6.\n const x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords\n const y1 = y0 - j1 + G3;\n const z1 = z0 - k1 + G3;\n const x2 = x0 - i2 + 2.0 * G3; // Offsets for third corner in (x,y,z) coords\n const y2 = y0 - j2 + 2.0 * G3;\n const z2 = z0 - k2 + 2.0 * G3;\n const x3 = x0 - 1.0 + 3.0 * G3; // Offsets for last corner in (x,y,z) coords\n const y3 = y0 - 1.0 + 3.0 * G3;\n const z3 = z0 - 1.0 + 3.0 * G3;\n // Work out the hashed gradient indices of the four simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n // Calculate the contribution from the four corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad3x[gi0] * x0 + permGrad3y[gi0] * y0 + permGrad3z[gi0] * z0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad3x[gi1] * x1 + permGrad3y[gi1] * y1 + permGrad3z[gi1] * z1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad3x[gi2] * x2 + permGrad3y[gi2] * y2 + permGrad3z[gi2] * z2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + 1 + perm[jj + 1 + perm[kk + 1]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad3x[gi3] * x3 + permGrad3y[gi3] * y3 + permGrad3z[gi3] * z3);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to stay just inside [-1,1]\n return 32.0 * (n0 + n1 + n2 + n3);\n };\n}\n/**\n * Creates a 4D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction4D}\n */\nexport function createNoise4D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these leads to a ~10% speedup\n const permGrad4x = new Float64Array(perm).map(v => grad4[(v % 32) * 4]);\n const permGrad4y = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 1]);\n const permGrad4z = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 2]);\n const permGrad4w = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 3]);\n return function noise4D(x, y, z, w) {\n let n0, n1, n2, n3, n4; // Noise contributions from the five corners\n // Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in\n const s = (x + y + z + w) * F4; // Factor for 4D skewing\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const l = fastFloor(w + s);\n const t = (i + j + k + l) * G4; // Factor for 4D unskewing\n const X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space\n const Y0 = j - t;\n const Z0 = k - t;\n const W0 = l - t;\n const x0 = x - X0; // The x,y,z,w distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n const w0 = w - W0;\n // For the 4D case, the simplex is a 4D shape I won't even try to describe.\n // To find out which of the 24 possible simplices we're in, we need to\n // determine the magnitude ordering of x0, y0, z0 and w0.\n // Six pair-wise comparisons are performed between each possible pair\n // of the four coordinates, and the results are used to rank the numbers.\n let rankx = 0;\n let ranky = 0;\n let rankz = 0;\n let rankw = 0;\n if (x0 > y0)\n rankx++;\n else\n ranky++;\n if (x0 > z0)\n rankx++;\n else\n rankz++;\n if (x0 > w0)\n rankx++;\n else\n rankw++;\n if (y0 > z0)\n ranky++;\n else\n rankz++;\n if (y0 > w0)\n ranky++;\n else\n rankw++;\n if (z0 > w0)\n rankz++;\n else\n rankw++;\n // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order.\n // Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w and x<w\n // impossible. Only the 24 indices which have non-zero entries make any sense.\n // We use a thresholding to set the coordinates in turn from the largest magnitude.\n // Rank 3 denotes the largest coordinate.\n // Rank 2 denotes the second largest coordinate.\n // Rank 1 denotes the second smallest coordinate.\n // The integer offsets for the second simplex corner\n const i1 = rankx >= 3 ? 1 : 0;\n const j1 = ranky >= 3 ? 1 : 0;\n const k1 = rankz >= 3 ? 1 : 0;\n const l1 = rankw >= 3 ? 1 : 0;\n // The integer offsets for the third simplex corner\n const i2 = rankx >= 2 ? 1 : 0;\n const j2 = ranky >= 2 ? 1 : 0;\n const k2 = rankz >= 2 ? 1 : 0;\n const l2 = rankw >= 2 ? 1 : 0;\n // The integer offsets for the fourth simplex corner\n const i3 = rankx >= 1 ? 1 : 0;\n const j3 = ranky >= 1 ? 1 : 0;\n const k3 = rankz >= 1 ? 1 : 0;\n const l3 = rankw >= 1 ? 1 : 0;\n // The fifth corner has all coordinate offsets = 1, so no need to compute that.\n const x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords\n const y1 = y0 - j1 + G4;\n const z1 = z0 - k1 + G4;\n const w1 = w0 - l1 + G4;\n const x2 = x0 - i2 + 2.0 * G4; // Offsets for third corner in (x,y,z,w) coords\n const y2 = y0 - j2 + 2.0 * G4;\n const z2 = z0 - k2 + 2.0 * G4;\n const w2 = w0 - l2 + 2.0 * G4;\n const x3 = x0 - i3 + 3.0 * G4; // Offsets for fourth corner in (x,y,z,w) coords\n const y3 = y0 - j3 + 3.0 * G4;\n const z3 = z0 - k3 + 3.0 * G4;\n const w3 = w0 - l3 + 3.0 * G4;\n const x4 = x0 - 1.0 + 4.0 * G4; // Offsets for last corner in (x,y,z,w) coords\n const y4 = y0 - 1.0 + 4.0 * G4;\n const z4 = z0 - 1.0 + 4.0 * G4;\n const w4 = w0 - 1.0 + 4.0 * G4;\n // Work out the hashed gradient indices of the five simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n const ll = l & 255;\n // Calculate the contribution from the five corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk + perm[ll]]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad4x[gi0] * x0 + permGrad4y[gi0] * y0 + permGrad4z[gi0] * z0 + permGrad4w[gi0] * w0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad4x[gi1] * x1 + permGrad4y[gi1] * y1 + permGrad4z[gi1] * z1 + permGrad4w[gi1] * w1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad4x[gi2] * x2 + permGrad4y[gi2] * y2 + permGrad4z[gi2] * z2 + permGrad4w[gi2] * w2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad4x[gi3] * x3 + permGrad4y[gi3] * y3 + permGrad4z[gi3] * z3 + permGrad4w[gi3] * w3);\n }\n let t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4;\n if (t4 < 0)\n n4 = 0.0;\n else {\n const gi4 = ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]];\n t4 *= t4;\n n4 = t4 * t4 * (permGrad4x[gi4] * x4 + permGrad4y[gi4] * y4 + permGrad4z[gi4] * z4 + permGrad4w[gi4] * w4);\n }\n // Sum up and scale the result to cover the range [-1,1]\n return 27.0 * (n0 + n1 + n2 + n3 + n4);\n };\n}\n/**\n * Builds a random permutation table.\n * This is exported only for (internal) testing purposes.\n * Do not rely on this export.\n * @private\n */\nexport function buildPermutationTable(random) {\n const tableSize = 512;\n const p = new Uint8Array(tableSize);\n for (let i = 0; i < tableSize / 2; i++) {\n p[i] = i;\n }\n for (let i = 0; i < tableSize / 2 - 1; i++) {\n const r = i + ~~(random() * (256 - i));\n const aux = p[i];\n p[i] = p[r];\n p[r] = aux;\n }\n for (let i = 256; i < tableSize; i++) {\n p[i] = p[i - 256];\n }\n return p;\n}\n//# sourceMappingURL=simplex-noise.js.map","function _prng_restore(prng, xg, opts) {\n let state = opts && opts.state;\n if (state) {\n if (typeof(state) == 'object') xg.copy(state, xg);\n prng.state = () => xg.copy(xg, {});\n }\n}\n\nfunction _prng_xor_core(xg, opts) {\n let prng = () => (xg.next() >>> 0) / 0x100000000;\n\n prng.double = () => {\n let top, bot, result;\n do {\n top = xg.next() >>> 11;\n bot = (xg.next() >>> 0) / 0x100000000;\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n\n prng.int32 = () => xg.next() | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng;\n}\n\n// A port of an algorithm by Johannes Baagøe <[email protected]>, 2010\nfunction prng_alea(seed, opts) {\n let xg = new AleaGen(seed);\n\n let prng = () => xg.next();\n\n prng.double = () =>\n prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53\n\n prng.int32 = () => (xg.next() * 0x100000000) | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\nclass AleaGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let n = 0xefc8249d;\n\n // Apply the seeding algorithm from Baagoe.\n this.c = 1;\n this.s0 = mash(' ');\n this.s1 = mash(' ');\n this.s2 = mash(' ');\n this.s0 -= mash(seed);\n if (this.s0 < 0) { this.s0 += 1; }\n this.s1 -= mash(seed);\n if (this.s1 < 0) { this.s1 += 1; }\n this.s2 -= mash(seed);\n if (this.s2 < 0) { this.s2 += 1; }\n\n function mash(data) {\n data = String(data);\n for (let i = 0; i < data.length; i++) {\n n += data.charCodeAt(i);\n let h = 0.02519603282416938 * n;\n n = h >>> 0;\n h -= n;\n h *= n;\n n = h >>> 0;\n h -= n;\n n += h * 0x100000000; // 2^32\n }\n return (n >>> 0) * 2.3283064365386963e-10; // 2^-32\n }\n }\n\n next() {\n let {c,s0,s1,s2} = this;\n let t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32\n this.s0 = s1;\n this.s1 = s2;\n return this.s2 = t - (this.c = t | 0);\n }\n\n copy(f, t) {\n t.c = f.c;\n t.s0 = f.s0;\n t.s1 = f.s1;\n t.s2 = f.s2;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xor128\" prng algorithm by\nfunction prng_xor128(seed, opts) {\n let xg = new Xor128Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass Xor128Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w} = this;\n let t = x ^ (x << 11);\n this.x = y;\n this.y = z;\n this.z = w;\n return this.w = w ^ ((w >>> 19) ^ t ^ (t >>> 8));\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorwow\" prng algorithm by\nfunction prng_xorwow(seed, opts) {\n let xg = new XorWowGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass XorWowGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n this.v = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n if (k == strseed.length) {\n this.d = this.x << 10 ^ this.x >>> 4;\n }\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w,v,d} = this;\n let t = (x ^ (x >>> 2));\n this.x = y;\n this.y = z;\n this.z = w;\n this.w = v;\n return (this.d = (d + 362437 | 0)) +\n (this.v = (v ^ (v << 4)) ^ (t ^ (t << 1))) | 0;\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n t.v = f.v;\n t.d = f.d;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorshift7\" algorithm by\nfunction prng_xorshift7(seed, opts) {\n let xg = new XorShift7Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass XorShift7Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n var j, w, x = [];\n\n if (seed === (seed | 0)) {\n // Seed state array using a 32-bit integer.\n w = x[0] = seed;\n } else {\n // Seed state using a string.\n seed = '' + seed;\n for (j = 0; j < seed.length; ++j) {\n x[j & 7] = (x[j & 7] << 15) ^\n (seed.charCodeAt(j) + x[(j + 1) & 7] << 13);\n }\n }\n\n // Enforce an array length of 8, not all zeroes.\n while (x.length < 8) x.push(0);\n for (j = 0; j < 8 && x[j] === 0; ++j);\n if (j == 8) w = x[7] = -1; else w = x[j];\n\n this.x = x;\n this.i = 0;\n\n // Discard an initial 256 values.\n for (j = 256; j > 0; --j) {\n this.next();\n }\n }\n\n next() {\n // Update xor generator.\n let t, v, {x,i} = this;\n t = x[i]; t ^= (t >>> 7); v = t ^ (t << 24);\n t = x[(i + 1) & 7]; v ^= t ^ (t >>> 10);\n t = x[(i + 3) & 7]; v ^= t ^ (t >>> 3);\n t = x[(i + 4) & 7]; v ^= t ^ (t << 7);\n t = x[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);\n x[i] = v;\n this.i = (i + 1) & 7;\n return v;\n };\n\n copy(f, t) {\n t.x = [... f.x];\n t.i = f.i;\n return t;\n }\n}\n\n// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.\nfunction prng_xor4096(seed, opts) {\n let xg = new Xor4096Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass Xor4096Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let t, v, i, j, w, X = [], limit = 128;\n if (seed === (seed | 0)) {\n // Numeric seeds initialize v, which is used to generates X.\n v = seed;\n seed = null;\n } else {\n // String seeds are mixed into v and X one character at a time.\n seed = seed + '\\0';\n v = 0;\n limit = Math.max(limit, seed.length);\n }\n // Initialize circular array and weyl value.\n for (i = 0, j = -32; j < limit; ++j) {\n // Put the unicode characters into the array, and shuffle them.\n if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);\n // After 32 shuffles, take v as the starting w value.\n if (j === 0) w = v;\n v ^= v << 10;\n v ^= v >>> 15;\n v ^= v << 4;\n v ^= v >>> 13;\n if (j >= 0) {\n w = (w + 0x61c88647) | 0; // Weyl.\n t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array.\n i = (0 == t) ? i + 1 : 0; // Count zeroes.\n }\n }\n // We have detected all zeroes; make the key nonzero.\n if (i >= 128) {\n X[(seed && seed.length || 0) & 127] = -1;\n }\n // Run the generator 512 times to further mix the state before using it.\n // Factoring this as a function slows the main generator, so it is just\n // unrolled here. The weyl generator is not advanced while warming up.\n i = 127;\n for (j = 4 * 128; j > 0; --j) {\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n X[i] = v ^ t;\n }\n // Storing state as object members is faster than using closure variables.\n this.w = w;\n this.X = X;\n this.i = i;\n }\n\n next() {\n let t, v, {w, X, i} = this;\n // Update Weyl generator.\n this.w = w = (w + 0x61c88647) | 0;\n // Update xor generator.\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n // Update Xor generator array state.\n v = X[i] = v ^ t;\n this.i = i;\n // Result is the combination.\n return (v + (w ^ (w >>> 16))) | 0;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.w = f.w;\n t.X = [... f.X];\n return t;\n }\n}\n\n// A Javascript implementaion of the \"Tyche-i\" prng algorithm by\nfunction prng_tychei(seed, opts) {\n let xg = new TycheiGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass TycheiGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.a = 0;\n this.b = 0;\n this.c = 2654435769 | 0;\n this.d = 1367130551;\n\n if (seed === Math.floor(seed)) {\n // Integer seed.\n this.a = (seed / 0x100000000) | 0;\n this.b = seed | 0;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 20; k++) {\n this.b ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {a,b,c,d} = this;\n b = (b << 25) ^ (b >>> 7) ^ c;\n c = (c - d) | 0;\n d = (d << 24) ^ (d >>> 8) ^ a;\n a = (a - b) | 0;\n this.b = b = (b << 20) ^ (b >>> 12) ^ c;\n this.c = c = (c - d) | 0;\n this.d = (d << 16) ^ (c >>> 16) ^ a;\n return this.a = (a - b) | 0;\n };\n\n copy(f, t) {\n t.a = f.a;\n t.b = f.b;\n t.c = f.c;\n t.d = f.d;\n return t;\n }\n}\n\n\n/* The following is non-inverted tyche, which has better internal\n * bit diffusion, but which is about 25% slower than tyche-i in JS.\n *\n\nclass TycheiGenAlt extends TycheiGen {\n next() {\n let {a,b,c,d} = this\n a = (a + b | 0) >>> 0;\n d = d ^ a; d = d << 16 ^ d >>> 16;\n c = c + d | 0;\n b = b ^ c; b = b << 12 ^ d >>> 20;\n this.a = a = a + b | 0;\n d = d ^ a; this.d = d = d << 8 ^ d >>> 24;\n this.c = c = c + d | 0;\n b = b ^ c;\n return this.b = (b << 7 ^ b >>> 25);\n }\n}\n*/\n\n/*\nCopyright 2019 David Bau.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*/\nfunction prng_arc4(seed, opts) {\n let xg = new ARC4Gen(seed);\n let prng = () => xg.next();\n\n prng.double = prng;\n\n prng.int32 = () => xg.g(4) | 0;\n\n prng.quick = () => xg.g(4) / 0x100000000;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\n\n//\n// ARC4\n//\n// An ARC4 implementation. The constructor takes a key in the form of\n// an array of at most (width) integers that should be 0 <= x < (width).\n//\n// The g(count) method returns a pseudorandom integer that concatenates\n// the next (count) outputs from ARC4. Its return value is a number x\n// that is in the range 0 <= x < (width ^ count).\n//\n\n//\n// The following constants are related to IEEE 754 limits.\n//\n\n// const width = 256 // each RC4 output is 0 <= x < 256\n// const chunks = 6 // at least six RC4 outputs for each double\nconst _arc4_startdenom = 281474976710656; // 256 ** 6 == width ** chunks\nconst _arc4_significance = 4503599627370496; // 2 ** 52 significant digits in a double\nconst _arc4_overflow = 9007199254740992; // 2 ** 53 == significance * 2\n\n\nclass ARC4Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let key = this.mixkey(seed, []);\n let i,j,t, S=[], keylen = key.length;\n this.i = this.j = i = j = 0;\n this.S = S;\n\n // The empty key [] is treated as [0].\n if (!keylen) { key = [keylen++]; }\n\n // Set up S using the standard key scheduling algorithm.\n while (i <= 0xff) {\n S[i] = i++;\n }\n for (i = 0; i <= 0xff; i++) {\n S[i] = S[j = 0xff & (j + key[i % keylen] + (t = S[i]))];\n S[j] = t;\n }\n\n // For robust unpredictability, the function call below automatically\n // discards an initial batch of values. This is called RC4-drop[256].\n // See http://google.com/search?q=rsa+fluhrer+response&btnI\n this.g(256);\n }\n\n next() {\n // This function returns a random double in [0, 1) that contains\n // randomness in every bit of the mantissa of the IEEE 754 value.\n\n let n = this.g(6); // Start with a numerator n < 2 ^ 48\n let d = _arc4_startdenom; // and denominator d = 2 ^ 48.\n let x = 0; // and no 'extra last byte'.\n\n while (n < _arc4_significance) { // Fill up all significant digits (2 ** 52)\n n = (n + x) * 256; // by shifting numerator and\n d *= 256; // denominator and generating a\n x = this.g(1); // new least-significant-byte.\n }\n while (n >= _arc4_overflow) { // To avoid rounding past overflow, before adding\n n /= 2; // last byte, shift everything\n d /= 2; // right using integer math until\n x >>>= 1; // we have exactly the desired bits.\n }\n return (n + x) / d; // Form the number within [0, 1).\n }\n\n g(count) {\n // The \"g\" method returns the next (count) outputs as one number.\n let t, r = 0, {i,j,S} = this;\n while (count--) {\n t = S[i = 0xff & (i + 1)];\n r = r * 256 + S[0xff & ((S[i] = S[j = 0xff & (j + t)]) + (S[j] = t))];\n }\n this.i = i;\n this.j = j;\n return r;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.j = f.j;\n t.S = [... f.S];\n return t;\n }\n\n mixkey(seed, key) {\n seed = seed + '';\n let smear=0, j=0;\n while (j < seed.length) {\n key[0xff & j] =\n 0xff & ((smear ^= key[0xff & j] * 19) + seed.charCodeAt(j++));\n }\n return key\n }\n}\n\nexport { prng_alea, prng_arc4, prng_tychei, prng_xor128, prng_xor4096, prng_xorshift7, prng_xorwow };\n//# sourceMappingURL=index.mjs.map\n","import { usesRadians as runtimeUsesRadians } from \"./runtime.js\";\n\n// =============================================================================\n// Section: Randomness & Noise\n// =============================================================================\n\nimport { createNoise2D } from \"simplex-noise\";\nimport { prng_alea } from \"esm-seedrandom\";\n\n/**\n * A uniform PRNG function. Returns a float in [0,1).\n * @callback RNG\n * @returns {number}\n */\n/** @type {RNG} */\nlet rng = prng_alea(Math.random());\nlet rng2 = prng_alea(Math.random());\n\nconst _seedCallbacks = [];\n\n/**\n * Register a callback to be called whenever seed() is invoked.\n * Used internally by modules that maintain gaussian pools.\n * @param {Function} cb\n */\nexport const _onSeed = (cb) => _seedCallbacks.push(cb);\n\n/**\n * Seed the random number generator.\n * @param {number|string} s – The seed value.\n * @returns {void}\n */\nexport const seed = (s) => {\n rng = prng_alea(s);\n rng2 = prng_alea(`${s}:2`);\n for (const callback of _seedCallbacks) {\n callback();\n }\n};\n\n/**\n * Simplex‐noise 2D function.\n * @type {function(number, number): number}\n */\nexport let noise = createNoise2D(prng_alea(Math.random()));\nexport let noise2 = createNoise2D(prng_alea(Math.random()));\n\n/**\n * Seed the noise generator.\n * @param {number|string} s - The seed value.\n * @returns {void}\n */\nexport const noiseSeed = (s) => {\n noise = createNoise2D(prng_alea(s));\n noise2 = createNoise2D(prng_alea(`${s}:2`));\n};\n\n/**\n * Returns a random float in [min, max).\n * @param {number} [min=0]\n * @param {number} [max=1]\n * @returns {number}\n */\nexport const rr = (e = 0, r = 1) => e + rng() * (r - e);\nexport const rr2 = (e = 0, r = 1) => e + rng2() * (r - e);\n\n/**\n * Selects a random element from an array.\n * @param {T[]} array - Input array.\n * @returns {T}\n */\nexport const rArray = (array) => array[~~(rng() * array.length)];\n\n/**\n * Returns a random integer in [min, max).\n * @param {number} min\n * @param {number} max\n * @returns {number}\n */\nexport const randInt = (e, r) => ~~rr(e, r);\nexport const randInt2 = (e, r) => ~~rr2(e, r);\n\n/**\n * Gaussian (normal) random sample N(mean, stdev²).\n * @param {number} [mean=0]\n * @param {number} [stdev=1]\n * @returns {number}\n */\nexport const gaussian = (mean = 0, stdev = 1) => {\n const u = 1 - rng();\n const v = rng();\n const z = Math.sqrt(-2.0 * Math.log(u)) * cos(360 * v);\n return z * stdev + mean;\n};\n\n/**\n * Picks a key from an object according to weighted probabilities.\n * @param {Object<string|number, number>} weights\n * @returns {string|number}\n */\nexport const weightedRand = (weights) => {\n let totalWeight = 0;\n const entries = [];\n\n // Build cumulative weights array\n for (const key in weights) {\n totalWeight += weights[key];\n entries.push({ key, cumulative: totalWeight });\n }\n\n // Get a random number between 0 and totalWeight\n const rnd = rng() * totalWeight;\n\n // Pick the first entry where rnd is less than the cumulative weight\n for (const { key, cumulative } of entries) {\n if (rnd < cumulative) {\n return isNaN(key) ? key : parseInt(key);\n }\n }\n};\n\n// =============================================================================\n// Section: Numeric Mapping & Constraints\n// =============================================================================\n\n/**\n * Maps a value from range [a,b] to [c,d], optionally clamped.\n * @param {number} value\n * @param {number} a\n * @param {number} b\n * @param {number} c\n * @param {number} d\n * @param {boolean} [withinBounds=false]\n * @returns {number}\n */\nexport const map = (value, a, b, c, d, withinBounds = false) => {\n let r = c + ((value - a) / (b - a)) * (d - c);\n if (!withinBounds) return r;\n if (c < d) return constrain(r, c, d);\n else return constrain(r, d, c);\n};\n\n/**\n * Constrains a number within the provided bounds.\n * @param {number} n - The number.\n * @param {number} low - Lower bound.\n * @param {number} high - Upper bound.\n * @returns {number} The constrained number.\n */\nexport const constrain = (n, low, high) => Math.max(Math.min(n, high), low);\n\n// =============================================================================\n// Section: Trigonometry\n// =============================================================================\n\n/**\n * Normalize an angle in degrees to [0,360).\n * @param {number} angle\n * @returns {number}\n */\nconst nAngle = (angle) => {\n angle = angle % 360;\n return angle < 0 ? angle + 360 : angle;\n};\n\n// number of discrete steps (360° × 4 samples per degree)\nconst totalDegrees = 1440;\nconst radiansPerIndex = (2 * Math.PI) / totalDegrees;\n\n// lazy‐initialized lookup tables\nconst cLookup = new Float32Array(totalDegrees).fill(NaN);\nconst sLookup = new Float32Array(totalDegrees).fill(NaN);\n\n/**\n * Cosine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const cos = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = cLookup[idx];\n if (isNaN(v)) {\n v = Math.cos(idx * radiansPerIndex);\n cLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Sine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const sin = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = sLookup[idx];\n if (isNaN(v)) {\n v = Math.sin(idx * radiansPerIndex);\n sLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Converts radians to degrees, normalized to [0,360).\n * @param {number} rad\n * @returns {number}\n */\nexport const toDegrees = (rad, isRad = false) => {\n if (isRad || runtimeUsesRadians()) {\n let angle = ((rad * 180) / Math.PI) % 360;\n return angle < 0 ? angle + 360 : angle;\n } else {\n return rad;\n }\n};\n\n/**\n * Converts radians to degrees without wrapping the result.\n * Preserves signed angles so downstream scaling keeps its direction.\n * @param {number} angle\n * @param {boolean} [isRad=false]\n * @returns {number}\n */\nexport const toDegreesSigned = (angle, isRad = false) =>\n isRad || runtimeUsesRadians()\n ? (angle * 180) / Math.PI\n : angle;\n\n// =============================================================================\n// Section: Geometry & Transforms\n// =============================================================================\n\n/**\n * Rotates point (x,y) around center (cx,cy) by angle degrees.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x\n * @param {number} y\n * @param {number} angle - Degrees\n * @returns {{x:number,y:number}}\n */\nexport const rotate = (cx, cy, x, y, angle) => {\n let coseno = cos(angle),\n seno = sin(angle),\n nx = coseno * (x - cx) + seno * (y - cy) + cx,\n ny = coseno * (y - cy) - seno * (x - cx) + cy;\n return { x: nx, y: ny };\n};\n\n/**\n * Euclidean distance between two points.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const dist = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1);\n\n/**\n * Angle in degrees between two points, measured clockwise from +X.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const calcAngle = (x1, y1, x2, y2) =>\n toDegrees(Math.atan2(-(y2 - y1), x2 - x1), true);\n\n/**\n * Intersection of two line segments, or false if none.\n * @param {{x:number,y:number}} s1a\n * @param {{x:number,y:number}} s1b\n * @param {{x:number,y:number}} s2a\n * @param {{x:number,y:number}} s2b\n * @param {boolean} [includeSegmentExtension=false]\n * @returns {{x:number,y:number}|false}\n */\nexport const intersectLines = (\n s1a,\n s1b,\n s2a,\n s2b,\n includeSegmentExtension = false\n) => {\n // Extract coordinates from points\n let x1 = s1a.x,\n y1 = s1a.y;\n let x2 = s1b.x,\n y2 = s1b.y;\n let x3 = s2a.x,\n y3 = s2a.y;\n let x4 = s2b.x,\n y4 = s2b.y;\n // Early return if line segments are points or if the lines are parallel\n if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) {\n return false; // Segments are points\n }\n let deltaX1 = x2 - x1,\n deltaY1 = y2 - y1;\n let deltaX2 = x4 - x3,\n deltaY2 = y4 - y3;\n let denominator = deltaY2 * deltaX1 - deltaX2 * deltaY1;\n if (denominator === 0) {\n return false; // Lines are parallel\n }\n // Calculate the intersection point\n let ua = (deltaX2 * (y1 - y3) - deltaY2 * (x1 - x3)) / denominator;\n let ub = (deltaX1 * (y1 - y3) - deltaY1 * (x1 - x3)) / denominator;\n // Check if the intersection is within the bounds of the line segments\n if (!includeSegmentExtension && (ub < 0 || ub > 1)) {\n return false;\n }\n // Calculate the intersection coordinates\n let x = x1 + ua * deltaX1;\n let y = y1 + ua * deltaY1;\n return { x: x, y: y };\n};\n","import { Cwidth, Cheight } from \"./target.js\";\nimport { isMixReady, State } from \"./color.js\";\nimport { randInt2, noise2, rr2, sin, cos, map, toDegreesSigned } from \"./utils.js\";\nimport { getAffineMatrix } from \"./runtime.js\";\n\n// =============================================================================\n// Section: Matrix transformations\n// =============================================================================\n\n// =============================================================================\n// Section: Field Initialization\n// =============================================================================\n\nlet isLoaded = false;\n\n/**\n * Ensures the field system is initialized and ready for use.\n * If the field is not loaded, it initializes the mixing system and creates the field.\n */\nexport function isFieldReady() {\n if (!isLoaded) {\n isMixReady(); // Ensure the mixing system is ready\n createField(); // Initialize the field\n isLoaded = true;\n }\n}\n\n// =============================================================================\n// Section: Position Class\n// =============================================================================\n\n/**\n * The Position class represents a point within a two-dimensional space, which can interact with a vector field.\n * It provides methods to update the position based on the field's flow and to check whether the position is\n * within certain bounds (e.g., within the field or canvas).\n */\nexport class Position {\n /**\n * Constructs a new Position instance.\n * @param {number} x - The initial x-coordinate.\n * @param {number} y - The initial y-coordinate.\n */\n constructor(x, y) {\n isFieldReady();\n const m = getAffineMatrix();\n this.mx = m.x;\n this.my = m.y;\n this.update(x, y);\n this.plotted = 0; // Tracks the total distance plotted\n }\n\n /**\n * Updates the position's coordinates and calculates its offsets and indices within the flow field.\n * @param {number} x - The new x-coordinate.\n * @param {number} y - The new y-coordinate.\n */\n update(x, y) {\n this.x = x;\n this.y = y;\n if (State.field.isActive) {\n this.colIdx = Math.round((x + this.mx - left_x) / resolution);\n this.rowIdx = Math.round((y + this.my - top_y) / resolution);\n }\n }\n\n /**\n * Resets the 'plotted' property to 0.\n */\n reset() {\n this.plotted = 0;\n }\n\n /**\n * Checks if the position is within the active flow field's bounds.\n * @returns {boolean} - True if the position is within the flow field, false otherwise.\n */\n isIn() {\n return State.field.isActive\n ? Position.isIn(this.colIdx, this.rowIdx)\n : this.isInCanvas(this.x, this.y);\n }\n\n /**\n * Checks if the position is within the canvas bounds (with a margin).\n * @returns {boolean} - True if the position is within bounds, false otherwise.\n */\n isInCanvas() {\n const margin = 0.3;\n const w = Cwidth;\n const h = Cheight;\n const x = this.x + this.mx;\n const y = this.y + this.my;\n return (\n x >= -margin * w &&\n x <= (1 + margin) * w &&\n y >= -margin * h &&\n y <= (1 + margin) * h\n );\n }\n\n /**\n * Calculates the angle of the flow field at the position's current coordinates.\n * @returns {number} - The internal flow angle in degrees, or 0 if the position is not in the field or if no field is active.\n */\n angle(skipCheck = false) {\n if (!State.field.isActive) return 0;\n return (skipCheck || this.isIn())\n ? flow_field()[this.colIdx][this.rowIdx] * State.field.wiggle\n : 0;\n }\n\n /**\n * Moves the position along the flow field by a certain length.\n * @param {number} _dir - The direction of movement, interpreted using the current runtime angle units.\n * @param {number} _length - The length to move along the field.\n * @param {number} _step_length - The length of each step.\n */\n moveTo(_dir, _length, _step_length = 1) {\n this.movePos(toDegreesSigned(_dir), _length, _step_length);\n }\n\n /**\n * Internal variant of moveTo() that expects a degree value already normalized to the library's internal representation.\n */\n _moveToDegrees(_dir, _length, _step_length = 1) {\n this.movePos(_dir, _length, _step_length);\n }\n\n /**\n * Plots a point to another position within the flow field, following a Plot object\n * @param {Position} _plot - The Plot path object.\n * @param {number} _length - The length to move towards the target position.\n * @param {number} _step_length - The length of each step.\n * @param {number} _scale - The scaling factor for the plotting path.\n */\n plotTo(_plot, _length, _step_length, _scale = 1, precomputedAngle = undefined) {\n this.movePos(_plot, _length, _step_length, _scale, precomputedAngle);\n }\n\n movePos(_dirPlot, _length, _step, _scale = false, precomputedAngle = undefined) {\n const scaleFactor = _scale || 1;\n if (!this.isIn()) {\n this.plotted += _step / scaleFactor;\n return;\n }\n const steps = _length / _step;\n const fieldActive = State.field.isActive;\n const usePlot = !!_scale;\n for (let i = 0; i < steps; i++) {\n const plotAngle = (usePlot && precomputedAngle !== undefined && i === 0)\n ? precomputedAngle\n : (usePlot ? _dirPlot.angle(this.plotted) : _dirPlot);\n const angle = (fieldActive ? this.angle(true) : 0) - plotAngle;\n // Calculate new position\n this.update(this.x + _step * cos(angle), this.y + _step * sin(angle));\n this.plotted += _step / scaleFactor;\n }\n }\n\n // Static Methods\n\n /**\n * Gets the row index for a given y-coordinate.\n * @param {number} y - The y-coordinate.\n * @returns {number} - The row index.\n */\n static getRowIndex(y, d = 1) {\n const y_offset = y + getAffineMatrix().y - top_y;\n return Math.round(y_offset / resolution / d);\n }\n\n /**\n * Gets the column index for a given x-coordinate.\n * @param {number} x - The x-coordinate.\n * @returns {number} - The column index.\n */\n static getColIndex(x, d = 1) {\n const x_offset = x + getAffineMatrix().x - left_x;\n return Math.round(x_offset / resolution / d);\n }\n\n /**\n * Checks if a column and row index are within the flow field bounds.\n * @param {number} col - The column index.\n * @param {number} row - The row index.\n * @returns {boolean} - True if the indices are within bounds, false otherwise.\n */\n static isIn(col, row) {\n return col >= 0 && row >= 0 && col < num_columns && row < num_rows;\n }\n}\n\n// =============================================================================\n// Section: VectorField\n// =============================================================================\n\n/**\n * Represents the state of the vector field.\n * @property {boolean} isActive - Indicates if the vector field is active.\n * @property {string|null} current - The name of the currently active vector field.\n */\nState.field = {\n isActive: false,\n current: null,\n wiggle: 1,\n};\n\n// Internal variables for field configuration\nlet list = new Map();\nlet resolution, left_x, top_y, num_columns, num_rows;\nconst FIELD_ANGLE_MODES = new Set([\"degrees\", \"radians\"]);\n\n/**\n * Initializes the field grid and sets up the vector field's structure based on the renderer's dimensions.\n */\nfunction createField() {\n resolution = Cwidth * 0.01; // Determine the resolution of the field grid\n left_x = -0.5 * Cwidth; // Left boundary of the field\n top_y = -0.5 * Cheight; // Top boundary of the field\n num_columns = Math.round((2 * Cwidth) / resolution); // Number of columns in the grid\n num_rows = Math.round((2 * Cheight) / resolution); // Number of columns in the grid\n addStandard(); // Add default vector field\n}\n\n/**\n * Retrieves the field values for the current vector field.\n * @returns {Float32Array[]} The current vector field grid.\n */\nfunction flow_field() {\n return list.get(State.field.current).field;\n}\n\nfunction normalizeFieldAngleMode(options = {}) {\n const config =\n typeof options === \"string\" ? { angleMode: options } : options || {};\n const angleMode = config.angleMode ?? \"degrees\";\n\n if (!FIELD_ANGLE_MODES.has(angleMode)) {\n throw new Error(\n `Invalid field angle mode \"${angleMode}\". Use \"degrees\" or \"radians\".`,\n );\n }\n\n return angleMode;\n}\n\nfunction normalizeFieldAngles(field, angleMode) {\n if (angleMode !== \"radians\") return field;\n\n for (let c = 0; c < field.length; c++) {\n for (let r = 0; r < field[c].length; r++) {\n field[c][r] = toDegreesSigned(field[c][r], true);\n }\n }\n\n return field;\n}\n\nfunction generateField(entry, t) {\n return normalizeFieldAngles(entry.gen(t, genField()), entry.angleMode);\n}\n\n/**\n * Regenerates the current vector field using its associated generator function.\n * @param {number} [t=0] - An optional time parameter that can affect field generation.\n */\nexport function refreshField(t = 0) {\n if (!State.field.isActive || !State.field.current) {\n throw new Error(\n \"No field is currently active. Call brush.field('name') to activate one before refreshing.\",\n );\n }\n const currentField = list.get(State.field.current);\n currentField.field = generateField(currentField, t);\n}\n\n/**\n * Generates an empty field array.\n * Reuses existing arrays to reduce memory allocation overhead.\n * @returns {Float32Array[]} Empty vector field grid.\n */\nfunction genField() {\n return new Array(num_columns)\n .fill(null)\n .map(() => new Float32Array(num_rows));\n}\n\n/**\n * Activates a specific vector field by name, ensuring it's ready for use.\n * @param {string} a - The name of the vector field to activate.\n */\nexport function field(a) {\n if (!State.field.wiggle) {\n State.field.wiggle = 1;\n } // Set default wiggle value\n isFieldReady();\n if (!list.has(a)) {\n throw new Error(\n `Field \"${a}\" does not exist. Available fields: ${Array.from(list.keys()).join(\", \")}.`,\n );\n }\n State.field.isActive = true;\n State.field.current = a;\n const entry = list.get(a);\n if (!entry.field) entry.field = generateField(entry, 0);\n}\n\n/**\n * Deactivates the current vector field.\n */\nexport function noField() {\n isFieldReady();\n State.field.isActive = false;\n}\n\n/**\n * Adds a new vector field to the field list with a unique name and a generator function.\n * @param {string} name - The unique name for the new vector field.\n * @param {Function} funct - The function that generates the field values.\n * @param {object} [options] - Optional field configuration.\n * @param {\"degrees\"|\"radians\"} [options.angleMode=\"degrees\"] - How the generator's output angles should be interpreted.\n */\nexport function addField(name, funct, options = {}) {\n list.set(name, {\n gen: funct,\n field: null,\n angleMode: normalizeFieldAngleMode(options),\n });\n}\n\n/**\n * Retrieves a list of all available vector field names.\n * @returns {string[]} An array of all the field names.\n */\nexport function listFields() {\n isFieldReady();\n return Array.from(list.keys());\n}\n\nexport function wiggle(a = 1) {\n field(\"hand\");\n State.field.wiggle = a;\n}\n\n/**\n * Fills every cell of a field grid using a callback (c, r) => angle.\n */\nfunction fillField(field, fn) {\n for (let c = 0; c < num_columns; c++)\n for (let r = 0; r < num_rows; r++) field[c][r] = fn(c, r);\n return field;\n}\n\n/**\n * Adds standard predefined vector fields to the list with unique behaviors.\n */\nfunction addStandard() {\n // Organic noise — basis for brush.wiggle()\n addField(\"hand\", (t, field) => {\n const bs = rr2(0.2, 0.8),\n ba = randInt2(5, 10);\n return fillField(field, (c, r) => {\n const angle = 0.5 * ba * sin(bs * r * c + randInt2(15, 25));\n return 0.2 * angle * cos(t) + noise2(c, r) * ba * 0.7;\n });\n });\n // Smooth large-scale noise curves\n addField(\"curved\", (t, field) => {\n let ar = randInt2(-10, 10);\n if (randInt2(0, 100) % 2 == 0) ar *= -1;\n return fillField(\n field,\n (c, r) =>\n 3 * map(noise2(c * 0.02 + t * 0.03, r * 0.02 + t * 0.03), 0, 1, -ar, ar),\n );\n });\n // Sharp alternating angles per cell — herringbone / wicker look\n addField(\"zigzag\", (t, field) => {\n let ar = randInt2(-30, -15) + Math.abs(44 * sin(t));\n if (randInt2(0, 100) % 2 == 0) ar *= -1;\n let dif = ar,\n angle = 0;\n for (let c = 0; c < num_columns; c++) {\n for (let r = 0; r < num_rows; r++) {\n field[c][r] = angle;\n angle += dif;\n dif *= -1;\n }\n angle += dif;\n dif *= -1;\n }\n return field;\n });\n // Sinusoidal wave bands\n addField(\"waves\", (t, field) => {\n const sr = randInt2(10, 15) + 5 * sin(t),\n cr = randInt2(3, 6) + 3 * cos(t),\n ba = randInt2(20, 35);\n return fillField(\n field,\n (c, r) => sin(sr * c) * ba * cos(r * cr) + randInt2(-3, 3),\n );\n });\n // Dense oscillation from row×col product\n addField(\"seabed\", (t, field) => {\n const bs = rr2(0.4, 0.8),\n ba = randInt2(18, 26);\n return fillField(\n field,\n (c, r) => 1.1 * ba * sin(bs * r * c + randInt2(15, 20)) * cos(t),\n );\n });\n // Radial vortex — angles spiral around the field centre\n addField(\"spiral\", (_t, field) => {\n const n = randInt2(5, 10);\n const dir = randInt2(0, 2) * 2 - 1;\n const offset = randInt2(65, 80); // <90 = inward spiral\n const attractors = Array.from({ length: n }, () => ({\n x: rr2(0.1, 0.9) * num_columns,\n y: rr2(0.1, 0.9) * num_rows,\n }));\n return fillField(field, (c, r) => {\n let wx = 0,\n wy = 0;\n for (const att of attractors) {\n const dx = c - att.x,\n dy = r - att.y;\n const w = 1 / (dx * dx + dy * dy + 1);\n const a = Math.atan2(dy, dx) * (180 / Math.PI);\n const angle = (dir * (a + offset) * Math.PI) / 180;\n wx += w * Math.cos(angle);\n wy += w * Math.sin(angle);\n }\n return Math.atan2(wy, wx) * (180 / Math.PI);\n });\n });\n // Column-banded stripes — parallel rake marks\n addField(\"columns\", (_t, field) => {\n const freq = randInt2(3, 8),\n amp = randInt2(25, 45);\n return fillField(field, (c, _r) => sin(c * freq) * amp);\n });\n}\n","import { State } from \"./color.js\";\nimport { isFieldReady } from \"./flowfield.js\";\n\n// =============================================================================\n// SAVE / RESTORE\n// =============================================================================\n\n/**\n * Stack of saved brush states for push/pop operations.\n * A stack (not a single slot) is required because applyShader() internally\n * calls Renderer.push()/pop(), which fires our hook — a flat object would be\n * overwritten mid-draw and pop() would restore the wrong state.\n */\nconst _stateStack = [];\n\n/**\n * Pushes the current brush state onto the stack.\n */\nexport function push() {\n isFieldReady();\n _stateStack.push({\n fill: { ...State.fill },\n wash: State.wash ? { ...State.wash } : null,\n stroke: { ...State.stroke },\n hatch: { ...State.hatch },\n mass: State.mass ? { ...State.mass } : null,\n field: { ...State.field },\n });\n}\n\n/**\n * Pops the top brush state from the stack and restores it.\n */\nexport function pop() {\n const saved = _stateStack.pop();\n if (!saved) return;\n State.stroke = { ...saved.stroke };\n State.field = { ...saved.field };\n State.hatch = { ...saved.hatch };\n State.fill = { ...saved.fill };\n if (saved.wash) State.wash = { ...saved.wash };\n if (saved.mass) {\n State.mass = { ...saved.mass };\n } else if (State.mass) {\n State.mass = {\n ...State.mass,\n isActive: false,\n brush: null,\n color: null,\n options: {},\n };\n }\n}\n","// =============================================================================\n// Adapter: Standalone Runtime Hooks\n// =============================================================================\n\nimport { setRuntime } from \"../../core/runtime.js\";\nimport { push as pushState, pop as popState } from \"../../core/save.js\";\n\nconst clamp = (value, min, max) => Math.max(min, Math.min(value, max));\n\nexport const DEGREES = \"degrees\";\nexport const RADIANS = \"radians\";\n\nlet colorContext = null;\nlet currentAngleMode = RADIANS;\nconst transformStack = [];\nlet currentTransform = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\n\nfunction getColorContext() {\n if (colorContext) return colorContext;\n\n if (typeof document !== \"undefined\") {\n colorContext = document.createElement(\"canvas\").getContext(\"2d\");\n return colorContext;\n }\n\n if (typeof OffscreenCanvas !== \"undefined\") {\n colorContext = new OffscreenCanvas(1, 1).getContext(\"2d\");\n return colorContext;\n }\n\n throw new Error(\"Standalone color parsing requires CanvasRenderingContext2D support.\");\n}\n\nfunction multiplyTransform(left, right) {\n return {\n a: left.a * right.a + left.c * right.b,\n b: left.b * right.a + left.d * right.b,\n c: left.a * right.c + left.c * right.d,\n d: left.b * right.c + left.d * right.d,\n x: left.a * right.x + left.c * right.y + left.x,\n y: left.b * right.x + left.d * right.y + left.y,\n };\n}\n\n/**\n * Runtime-native color object compatible with the expectations of core modules.\n */\nexport class Color {\n constructor(r, g, b) {\n if (r?._array) {\n this.r = Math.round(r._array[0] * 255);\n this.g = Math.round(r._array[1] * 255);\n this.b = Math.round(r._array[2] * 255);\n this.hex = this.rgbToHex(this.r, this.g, this.b);\n this._array = [...r._array];\n this.gl = this._array;\n return;\n }\n\n if (typeof r === \"string\") {\n const rgbaMatch = /^rgba?\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*(?:,\\s*([\\d.]+))?\\s*\\)$/i.exec(r);\n if (rgbaMatch) {\n this.r = clamp(parseInt(rgbaMatch[1]), 0, 255);\n this.g = clamp(parseInt(rgbaMatch[2]), 0, 255);\n this.b = clamp(parseInt(rgbaMatch[3]), 0, 255);\n this.hex = this.rgbToHex(this.r, this.g, this.b);\n const alpha = rgbaMatch[4] !== undefined ? clamp(parseFloat(rgbaMatch[4]), 0, 1) : 1;\n this._array = [this.r / 255, this.g / 255, this.b / 255, alpha];\n this.gl = this._array;\n return;\n }\n this.hex = this.standardize(r);\n const rgb = this.hexToRgb(this.hex);\n this.r = rgb.r;\n this.g = rgb.g;\n this.b = rgb.b;\n } else {\n this.r = clamp(r ?? 0, 0, 255);\n this.g = clamp(g ?? r ?? 0, 0, 255);\n this.b = clamp(b ?? r ?? 0, 0, 255);\n this.hex = this.rgbToHex(this.r, this.g, this.b);\n }\n\n this._array = [this.r / 255, this.g / 255, this.b / 255, 1];\n this.gl = this._array;\n }\n\n rgbToHex(r, g, b) {\n return `#${((1 << 24) | (r << 16) | (g << 8) | b).toString(16).slice(1)}`;\n }\n\n hexToRgb(hex) {\n hex = hex.replace(\n /^#?([a-f\\d])([a-f\\d])([a-f\\d])$/i,\n (_match, red, green, blue) => red + red + green + green + blue + blue,\n );\n const result = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\n if (!result) {\n throw new Error(`Invalid color value \"${hex}\".`);\n }\n return {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16),\n };\n }\n\n standardize(value) {\n const ctx = getColorContext();\n ctx.fillStyle = value;\n return ctx.fillStyle;\n }\n\n _getRed() {\n return this.r;\n }\n\n _getGreen() {\n return this.g;\n }\n\n _getBlue() {\n return this.b;\n }\n}\n\n/**\n * Sets the active standalone angle mode.\n *\n * @param {\"degrees\"|\"radians\"} mode\n */\nexport function angleMode(mode) {\n if (mode !== DEGREES && mode !== RADIANS) {\n throw new Error(`Invalid angle mode \"${mode}\". Use \"degrees\" or \"radians\".`);\n }\n currentAngleMode = mode;\n}\n\n/**\n * Returns the current standalone angle mode.\n *\n * @returns {\"degrees\"|\"radians\"}\n */\nexport function getAngleMode() {\n return currentAngleMode;\n}\n\n/**\n * Pushes the current standalone transform onto the stack.\n */\nexport function push() {\n pushState();\n transformStack.push({ ...currentTransform });\n}\n\n/**\n * Pops the last standalone transform from the stack.\n */\nexport function pop() {\n if (transformStack.length === 0) return;\n currentTransform = transformStack.pop();\n popState();\n}\n\n/**\n * Applies a translation to the current standalone transform.\n *\n * @param {number} x\n * @param {number} y\n */\nexport function translate(x, y) {\n currentTransform = multiplyTransform(currentTransform, {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x,\n y,\n });\n}\n\n/**\n * Applies a rotation to the current standalone transform.\n *\n * @param {number} angle\n */\nexport function rotate(angle) {\n const theta =\n currentAngleMode === RADIANS ? angle : (angle * Math.PI) / 180;\n const cosTheta = Math.cos(theta);\n const sinTheta = Math.sin(theta);\n currentTransform = multiplyTransform(currentTransform, {\n a: cosTheta,\n b: sinTheta,\n c: -sinTheta,\n d: cosTheta,\n x: 0,\n y: 0,\n });\n}\n\n/**\n * Applies a scale to the current standalone transform.\n *\n * @param {number} x\n * @param {number} [y=x]\n */\nexport function scale(x, y = x) {\n currentTransform = multiplyTransform(currentTransform, {\n a: x,\n b: 0,\n c: 0,\n d: y,\n x: 0,\n y: 0,\n });\n}\n\n/**\n * Installs the standalone runtime hooks used by core modules.\n */\nexport function initStandaloneRuntime() {\n setRuntime({\n usesRadians: () => currentAngleMode === \"radians\",\n fromDegrees: (angle) =>\n currentAngleMode === \"radians\" ? (angle * Math.PI) / 180 : angle,\n createColor: (...args) => {\n if (args.length === 1 && args[0]?._array) return args[0];\n return new Color(...args);\n },\n getAffineMatrix: () => currentTransform,\n });\n}\n","// =============================================================================\n// Adapter: Standalone Target Hooks\n// =============================================================================\n\nimport {\n setTargetRuntime,\n setTargetState,\n} from \"../../core/target.js\";\n\nlet activeTarget = null;\nlet isLoaded = false;\nlet activeDensity = 1;\nlet activeWidth = 0;\nlet activeHeight = 0;\n\nfunction isCanvasTarget(target) {\n return (\n typeof HTMLCanvasElement !== \"undefined\" &&\n target instanceof HTMLCanvasElement\n );\n}\n\nfunction isOffscreenCanvasTarget(target) {\n return (\n typeof OffscreenCanvas !== \"undefined\" &&\n target instanceof OffscreenCanvas\n );\n}\n\nfunction isSupportedTarget(target) {\n return isCanvasTarget(target) || isOffscreenCanvasTarget(target);\n}\n\nfunction getTargetContext(target) {\n return (\n target.getContext(\"webgl2\", { premultipliedAlpha: true }) ??\n target.getContext(\"webgl2\")\n );\n}\n\nfunction createRenderer(target, width, height, density) {\n const drawingContext = getTargetContext(target);\n if (!drawingContext) {\n throw new Error(\"brush.load(target) requires a canvas with a WebGL2 context.\");\n }\n\n return {\n canvas: target,\n drawingContext,\n width,\n height,\n pixelDensity: () => density,\n };\n}\n\nfunction applyLoadedTarget(target, width, height, density) {\n activeTarget = target;\n activeWidth = width;\n activeHeight = height;\n activeDensity = density;\n\n const renderer = createRenderer(target, width, height, density);\n setTargetState({\n Renderer: renderer,\n Cwidth: width,\n Cheight: height,\n Density: density,\n });\n isLoaded = true;\n}\n\n/**\n * Loads a standalone draw target from a DOM canvas or OffscreenCanvas.\n *\n * @param {HTMLCanvasElement|OffscreenCanvas} target\n */\nexport function load(target = activeTarget) {\n if (!isSupportedTarget(target)) {\n throw new Error(\n \"Standalone brush.load(target) requires an HTMLCanvasElement or OffscreenCanvas.\",\n );\n }\n\n applyLoadedTarget(target, target.width, target.height, 1);\n}\n\n/**\n * Creates a standalone DOM canvas, configures its backing resolution according\n * to the provided pixel density, appends it optionally to the DOM, and loads it\n * as the active brush target.\n *\n * @param {number} width Logical canvas width.\n * @param {number} height Logical canvas height.\n * @param {{pixelDensity?: number, parent?: string|Element|null, id?: string}} [options]\n * @returns {HTMLCanvasElement}\n */\nexport function createCanvas(width, height, options = {}) {\n if (typeof document === \"undefined\") {\n throw new Error(\"brush.createCanvas() requires a browser document.\");\n }\n\n const logicalWidth = Math.max(1, Math.round(width));\n const logicalHeight = Math.max(1, Math.round(height));\n const density = Math.max(1, Number(options.pixelDensity) || 1);\n const canvas = document.createElement(\"canvas\");\n\n canvas.width = Math.max(1, Math.round(logicalWidth * density));\n canvas.height = Math.max(1, Math.round(logicalHeight * density));\n canvas.style.width = `${logicalWidth}px`;\n canvas.style.height = `${logicalHeight}px`;\n if (options.id) canvas.id = options.id;\n\n if (options.parent) {\n const parent =\n typeof options.parent === \"string\"\n ? document.querySelector(options.parent)\n : options.parent;\n if (!parent) {\n throw new Error(`Could not find parent \"${options.parent}\" for brush.createCanvas().`);\n }\n parent.appendChild(canvas);\n }\n\n applyLoadedTarget(canvas, logicalWidth, logicalHeight, density);\n return canvas;\n}\n\n/**\n * Refreshes the standalone target density.\n *\n * Standalone targets currently use a fixed density of 1.\n *\n * @returns {number}\n */\nexport function syncDensity() {\n setTargetState({\n Cwidth: activeWidth,\n Cheight: activeHeight,\n Density: activeDensity,\n });\n return activeDensity;\n}\n\n/**\n * Ensures a standalone target has been loaded.\n */\nexport function isCanvasReady() {\n if (!isLoaded) {\n throw new Error(\n \"No standalone target loaded. Call brush.load(canvasOrOffscreenCanvas) first.\",\n );\n }\n}\n\n/**\n * Standalone build does not use p5 instance switching, so these are no-ops.\n */\nexport function instance() {}\nexport function activateInstance() {}\nexport function deactivateInstance() {}\n\n/**\n * Standalone build does not yet support framebuffer targets.\n *\n * @returns {null}\n */\nexport function getActiveFramebuffer() {\n return null;\n}\n\n/**\n * Returns whether the given target behaves like a framebuffer target.\n *\n * Standalone targets currently only accept canvases and offscreen canvases.\n *\n * @returns {boolean}\n */\nexport function isFramebufferTarget() {\n return arguments[0]?.__brushFramebuffer === true;\n}\n\nexport function initStandaloneTargetRuntime() {\n setTargetRuntime({\n load,\n syncDensity,\n isCanvasReady,\n instance,\n activateInstance,\n deactivateInstance,\n getActiveFramebuffer,\n isFramebufferTarget,\n });\n}\n","import {\n rr2,\n randInt2,\n sin,\n cos,\n toDegreesSigned,\n constrain,\n dist,\n calcAngle,\n intersectLines,\n} from \"./utils.js\";\nimport { Polygon } from \"./polygon.js\";\nimport { Plot } from \"./plot.js\";\n\n// =============================================================================\n// Section: Primitives and Geommetry\n// =============================================================================\n\n/**\n * Creates a Polygon from an array of points and calls its show() method.\n * Polygons ignore fields and won't be good for fills and masses\n * @param {Array<Array<number>>} pointsArray - Array of points [x, y, pressure]\n */\nexport function polygon(pointsArray) {\n // Create a new Polygon instance\n const polygon = new Polygon(pointsArray);\n polygon.show();\n}\n\n/**\n * Draws a rectangle on the canvas using path functions.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} w - Width.\n * @param {number} h - Height.\n * @param {boolean} [mode=\"corner\"] - \"corner\" (default) or \"center\".\n */\nexport function rect(x, y, w, h, mode = \"corner\") {\n if (mode === \"center\") {\n x -= w / 2;\n y -= h / 2;\n }\n beginShape(0);\n vertex(x, y);\n vertex(x + w, y);\n vertex(x + w, y + h);\n vertex(x, y + h);\n endShape(true);\n}\n\n/**\n * Draws a circle on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Circle radius.\n * @param {boolean} [r=false] - Randomizes segment lengths if true.\n */\nexport function circle(x, y, radius, r = false) {\n const p = new Plot(\"curve\");\n const arcLength = Math.PI * radius;\n const angleOffset = rr2(0, 360);\n const randomFactor = r ? () => 1 + r * 0.2 * rr2() : () => 1;\n\n // Divide circle into 4 segments\n for (let i = 0; i < 4; i++) {\n const angle = -90 * i + angleOffset;\n p.addSegment(\n angle * randomFactor(),\n (arcLength / 2) * randomFactor(),\n 1,\n true,\n );\n }\n\n // Optionally add a random final angle for the last segment\n if (r) {\n const randomAngle = r * randInt2(-5, 5);\n p.addSegment(\n angleOffset,\n Math.abs(randomAngle) * (Math.PI / 180) * radius,\n 1,\n true,\n );\n p.endPlot(randomAngle + angleOffset, 1, true);\n } else {\n p.endPlot(angleOffset, 1, true);\n }\n\n // Draw the circle\n const offsetX = x - radius * sin(angleOffset);\n const offsetY = y - radius * cos(-angleOffset);\n p.show(offsetX, offsetY, 1);\n}\n\n/**\n * Draws an arc on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Radius.\n * @param {number} start - Start angle in the current runtime angle units.\n * @param {number} end - End angle in the current runtime angle units.\n */\nexport function arc(x, y, radius, start, end) {\n const startDeg = toDegreesSigned(start);\n const endDeg = toDegreesSigned(end);\n const sweepDeg = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweepDeg === 0) return;\n\n const p = new Plot(\"curve\");\n const segmentCount = Math.max(1, Math.ceil(sweepDeg / 90));\n const segmentSweep = sweepDeg / segmentCount;\n const arcLength = (Math.PI * radius * segmentSweep) / 180;\n\n for (let i = 0; i < segmentCount; i++) {\n p.addSegment(startDeg + i * segmentSweep + 90, arcLength, 1, true);\n }\n p.endPlot(startDeg + sweepDeg + 90, 1, true);\n\n const startX = x + radius * cos(startDeg);\n const startY = y - radius * sin(startDeg);\n p.draw(startX, startY, 1);\n}\n\n// Variables for managing paths and strokes\nlet _current;\nlet _curvature;\n\nclass SubPath {\n constructor() {\n this.isClosed = false;\n this.curvature = _curvature;\n this.vert = [];\n }\n /**\n * Adds a vertex to this subpath.\n * @param {number} x\n * @param {number} y\n * @param {number} pressure\n */\n vertex(x, y, pressure) {\n this.vert.push([x, y, pressure]);\n }\n /**\n * Renders the subpath by creating a spline from its vertices.\n */\n show() {\n let plot = _createSpline(this.vert, this.curvature, this.isClosed);\n plot.show();\n }\n}\n\n/**\n * Begins a new path with a specified curvature.\n * @param {number} [curvature=0] - Curvature from 0 to 1.\n */\nexport function beginShape(curvature = 0) {\n _curvature = constrain(curvature, 0, 1);\n _current = new SubPath();\n}\n\n/**\n * Adds a line segment from the current point to the given coordinates.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} [pressure=1] - Pressure value.\n */\nexport function vertex(x, y, pressure = 1) {\n if (!_current) {\n throw new Error(\n \"vertex() called outside of beginShape()/endShape(). Call beginShape() first.\",\n );\n }\n _current.vertex(x, y, pressure);\n}\n\n/**\n * Ends the current path and renders all subpaths.\n */\nexport function endShape(close = false) {\n if (!_current) {\n throw new Error(\n \"endShape() called without beginShape(). Call beginShape() first.\",\n );\n }\n if (_current.vert.length < 2) {\n throw new Error(\n \"endShape() requires at least 2 vertices. Add more with vertex().\",\n );\n }\n if (close) {\n _current.vertex(..._current.vert[0]);\n _current.isClosed = true;\n }\n _current.show();\n _current = false;\n}\n\nlet _strokeArray, _strokeOrigin;\n\n/**\n * Begins a new stroke with a given type and starting position.\n * @param {string} type - Stroke type.\n * @param {number} x - Starting x.\n * @param {number} y - Starting y.\n */\nexport function beginStroke(type, x, y) {\n if (type !== \"curve\" && type !== \"segments\") {\n throw new Error(\n `beginStroke() type must be \"curve\" or \"segments\", got \"${type}\".`,\n );\n }\n _strokeOrigin = [x, y];\n _strokeArray = new Plot(type);\n}\n\n/**\n * Adds a segment to the stroke.\n * @param {number} angle - Segment angle.\n * @param {number} length - Segment length.\n * @param {number} pressure - Segment pressure.\n */\nexport function move(angle, length, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"move() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.addSegment(angle, length, pressure);\n}\n\n/**\n * Completes and renders the stroke.\n * @param {number} angle - End angle.\n * @param {number} pressure - End pressure.\n */\nexport function endStroke(angle, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"endStroke() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.endPlot(angle, pressure);\n _strokeArray.draw(_strokeOrigin[0], _strokeOrigin[1], 1);\n _strokeArray = false;\n}\n\n/**\n * Creates and draws a spline curve from an array of points.\n * @param {Array<Array<number>>} array_points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature from 0 to 1.\n */\nexport function spline(_array_points, _curvature = 0.5) {\n if (!_array_points || _array_points.length < 2) {\n throw new Error(\n \"spline() requires at least 2 points. Each point should be [x, y, pressure].\",\n );\n }\n let p = _createSpline(_array_points, _curvature);\n p.draw();\n}\n\n/**\n * Creates a new Plot object representing a spline curve.\n *\n * For curved segments (curvature > 0) with at least 3 points available,\n * the function either treats segments as straight (if their angles match)\n * or calculates control points to compute a circular arc.\n *\n * If no curvature is specified, a simple straight segment is used.\n *\n * @param {Array<Array<number>>} points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature value between 0 and 1.\n * @param {boolean} [close=false] - Whether to close the spline.\n * @returns {Plot} - The generated Plot object.\n */\nfunction _createSpline(points, curvature = 0.5, close = false) {\n const plotType = curvature === 0 ? \"segments\" : \"curve\";\n const p = new Plot(plotType);\n const PI2 = Math.PI * 2;\n\n // If closing the spline, add the second point to the end\n if (close && curvature !== 0) {\n points.push(points[1]);\n }\n\n if (points && points.length > 0) {\n let done = 0; // Tracks excess length from previous segment\n let pep, tep, pep2; // Variables used for initial calibration\n\n for (let i = 0; i < points.length - 1; i++) {\n // For curved segments (if curvature > 0 and there is at least 3 points ahead)\n if (curvature > 0 && i < points.length - 2) {\n const p1 = points[i];\n const p2 = points[i + 1];\n const p3 = points[i + 2];\n\n const d1 = dist(p1[0], p1[1], p2[0], p2[1]);\n const d2 = dist(p2[0], p2[1], p3[0], p3[1]);\n const a1 = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n const a2 = calcAngle(p2[0], p2[1], p3[0], p3[1]);\n\n // Compute the adjustment length based on curvature\n const curvAdjust = curvature * Math.min(d1, d2, 0.5 * Math.min(d1, d2));\n const dmax = Math.max(d1, d2);\n const s1 = d1 - curvAdjust;\n const s2 = d2 - curvAdjust;\n\n if (Math.floor(a1) === Math.floor(a2)) {\n // If angles are nearly the same, treat as a straight segment\n const temp = close ? (i === 0 ? 0 : d1 - done) : d1 - done;\n const temp2 = close ? (i === 0 ? 0 : d2 - pep2) : d2;\n\n p.addSegment(a1, temp, p1[2], true);\n if (i === points.length - 3) {\n p.addSegment(a2, temp2, p2[2], true);\n }\n\n done = 0;\n if (i === 0) {\n pep = d1;\n pep2 = curvAdjust;\n tep = points[1];\n done = 0;\n }\n } else {\n // For a curved segment, compute control points and arc segment details\n const point1 = {\n x: p2[0] - curvAdjust * cos(-a1),\n y: p2[1] - curvAdjust * sin(-a1),\n };\n const point2 = {\n x: point1.x + dmax * cos(-a1 + 90),\n y: point1.y + dmax * sin(-a1 + 90),\n };\n const point3 = {\n x: p2[0] + curvAdjust * cos(-a2),\n y: p2[1] + curvAdjust * sin(-a2),\n };\n const point4 = {\n x: point3.x + dmax * cos(-a2 + 90),\n y: point3.y + dmax * sin(-a2 + 90),\n };\n\n const intPt = intersectLines(point1, point2, point3, point4, true);\n const radius = dist(point1.x, point1.y, intPt.x, intPt.y);\n const halfDist = dist(point1.x, point1.y, point3.x, point3.y) / 2;\n const arcAngle = 2 * Math.asin(halfDist / radius) * (180 / Math.PI);\n const arcLength = (PI2 * radius * arcAngle) / 360;\n\n const temp = close ? (i === 0 ? 0 : s1 - done) : s1 - done;\n const temp2 =\n i === points.length - 3 ? (close ? pep - curvAdjust : s2) : 0;\n\n p.addSegment(a1, temp, p1[2], true);\n p.addSegment(a1, isNaN(arcLength) ? 0 : arcLength, p1[2], true);\n p.addSegment(a2, temp2, p2[2], true);\n\n done = curvAdjust;\n if (i === 0) {\n pep = s1;\n pep2 = curvAdjust;\n tep = [point1.x, point1.y];\n }\n }\n\n if (i === points.length - 3) {\n p.endPlot(a2, p2[2], true);\n }\n } else if (curvature === 0) {\n // If no curvature, add a simple straight segment\n const p1 = points[i];\n const p2 = points[i + 1];\n const d = dist(p1[0], p1[1], p2[0], p2[1]);\n const a = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n\n p.addSegment(a, d, p2[2], true);\n if (i === points.length - 2) {\n p.endPlot(a, 1, true);\n }\n }\n }\n\n p.origin = close && curvature !== 0 ? tep : points[0];\n }\n\n return p;\n}\n","import { State } from \"./color.js\";\nimport { intersectLines } from \"./utils.js\";\n\n// =============================================================================\n// Section: Polygon Class\n// =============================================================================\n\n/**\n * Represents a polygon with a set of vertices and provides methods for\n * intersection, drawing, filling, and hatching.\n */\nexport class Polygon {\n /**\n * Constructs the Polygon object from an array of points.\n * @param {Array} pointsArray - An array of points, where each point is an array of two numbers [x, y].\n * @param {boolean} [useRawVertices=false] - If true, uses the raw array as vertices.\n */\n constructor(pointsArray, useRawVertices = false) {\n this.a = pointsArray;\n this.vertices = useRawVertices\n ? pointsArray\n : pointsArray.map(([x, y]) => ({ x, y }));\n this.sides = this.vertices.map((v, i, arr) => [\n v,\n arr[(i + 1) % arr.length],\n ]);\n this._intersectionCache = {}; // Cache for intersection results\n }\n\n /**\n * Intersects a given line with the polygon, returning all intersection points.\n * @param {Object} line - The line to intersect with the polygon, having two properties 'point1' and 'point2'.\n * @returns {Array} An array of intersection points (each with 'x' and 'y' properties) or an empty array if no intersections.\n */\n intersect(line) {\n // Check if the result has been cached\n const cacheKey = `${line.point1.x},${line.point1.y}-${line.point2.x},${line.point2.y}`;\n if (this._intersectionCache[cacheKey]) {\n return this._intersectionCache[cacheKey];\n }\n const points = [];\n for (const [start, end] of this.sides) {\n const intersection = intersectLines(line.point1, line.point2, start, end);\n if (intersection) points.push(intersection);\n }\n this._intersectionCache[cacheKey] = points; // Cache the result\n return points;\n }\n\n /**\n * Displays the polygon with optional stroke, hatch, and fill effects.\n */\n show() {\n if (State.wash) this.wash();\n if (State.fill) this.fill();\n if (State.mass) this.mass();\n if (State.hatch) this.hatch();\n if (State.stroke) this.draw();\n }\n}","import { Cwidth, Cheight } from \"./target.js\";\nimport { State } from \"./color.js\";\nimport { toDegrees, map, rr2 } from \"./utils.js\";\nimport { Position, isFieldReady } from \"./flowfield.js\";\nimport { Polygon } from \"./polygon.js\";\n\n// =============================================================================\n// Section: Plot Class\n// =============================================================================\n\n/**\n * The Plot class represents a collection of segments that define shapes or paths.\n * It supports operations like adding segments, calculating angles and pressures,\n * and generating polygons based on the plot's structure.\n */\nexport class Plot {\n /**\n * Creates a new Plot.\n * @param {string} _type - The type of plot, \"curve\" or \"segments\".\n */\n constructor(_type) {\n this.segments = [];\n this.angles = [];\n this.pres = [];\n this.type = _type;\n this.dir = 0;\n this.calcIndex(0);\n this.pol = false;\n }\n\n /**\n * Adds a segment to the plot with specified angle, length, and pressure.\n * @param {number} _a - The angle of the segment.\n * @param {number} _length - The length of the segment.\n * @param {number} _pres - The pressure of the segment.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n addSegment(_a = 0, _length = 0, _pres = 1, _degrees = false) {\n if (this.angles.length > 0) this.angles.pop(); // Remove the last angle\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a); // Normalize angle\n this.angles.push(_a, _a); // Push angle twice for continuity\n this.pres.push(_pres);\n this.segments.push(_length);\n this.length = this.segments.reduce((sum, len) => sum + len, 0); // Update total length\n }\n\n /**\n * Finalizes the plot by setting the last angle and pressure.\n * @param {number} _a - The final angle.\n * @param {number} _pres - The final pressure.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n endPlot(_a = 0, _pres = 1, _degrees = false) {\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a);\n this.angles[this.angles.length - 1] = _a; // Update the last angle\n this.pres.push(_pres);\n }\n\n /**\n * Rotates the entire plot by a given angle.\n * @param {number} _a - The angle to rotate the plot.\n */\n rotate(_a) {\n this.dir = toDegrees(_a);\n }\n\n /**\n * Calculates the pressure at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated pressure.\n */\n pressure(_d) {\n // If the distance exceeds the plot length, return the last pressure\n if (_d > this.length) return this.pres[this.pres.length - 1];\n // Otherwise, calculate the pressure using the curving function\n return this.curving(this.pres, _d);\n }\n\n /**\n * Calculates the angle at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The calculated angle.\n */\n angle(_d) {\n // If the distance exceeds the plot length, return the last angle\n if (_d > this.length) return this.angles[this.angles.length - 1];\n // Calculate the index for the given distance\n this.calcIndex(_d);\n // Return the angle, adjusted for the plot type and direction\n return this.type === \"curve\"\n ? this.curving(this.angles, _d) + this.dir\n : this.angles[this.index] + this.dir;\n }\n\n /**\n * Interpolates values between segments for smooth transitions.\n * @param {Array<number>} array - The array to interpolate within.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated value.\n */\n curving(array, _d) {\n let map0 = array[this.index];\n let map1 = array[this.index + 1] ?? map0;\n if (Math.abs(map1 - map0) > 180) {\n if (map1 > map0) map1 = -(360 - map1);\n else map0 = -(360 - map0);\n }\n return map(_d - this.suma, 0, this.segments[this.index], map0, map1, true);\n }\n\n /**\n * Calculates the current index of the plot based on the distance.\n * @param {number} _d - The distance along the plot.\n */\n calcIndex(_d) {\n this.index = -1;\n this.suma = 0;\n let d = 0;\n while (d <= _d) {\n this.suma = d;\n d += this.segments[this.index + 1];\n this.index++;\n }\n return this.index;\n }\n\n /**\n * Generates a polygon based on the plot.\n * @param {number} _x - The x-coordinate for the starting point.\n * @param {number} _y - The y-coordinate for the starting point.\n * @param {number} _scale - The scale factor for the polygon.\n * @param {number} _side - The side factor for the polygon.\n * @returns {Polygon} - The generated polygon.\n */\n genPol(_x, _y, _scale = 1, _side) {\n isFieldReady(); // Ensure that the drawing environment is prepared\n const step = _side < 0 ? 4 : 1;\n const vertices = [];\n const numSteps = Math.round(this.length / step);\n const pos = new Position(_x + Cwidth / 2, _y + Cheight / 2);\n let pside = 0;\n let prevIdx = 0;\n\n for (let i = 0; i < numSteps; i++) {\n pos.plotTo(this, step, step);\n const idx = this.calcIndex(pos.plotted);\n pside += step;\n let maxSize = _side <= 0 ? 8 : Math.max(this.segments[idx] * _side * rr2(0.7, 1.3), 20);\n if ((pside >= maxSize || idx >= prevIdx) && pos.x) {\n vertices.push([pos.x - Cwidth / 2, pos.y - Cheight / 2]);\n pside = 0;\n if (idx >= prevIdx) prevIdx++;\n }\n }\n return new Polygon(vertices);\n }\n\n /**\n * Displays the plot with optional stroke, hatch, and fill effects.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\n show(x, y, scale = 1) {\n if (State.wash) this.wash(x, y, scale);\n if (State.fill) this.fill(x, y, scale);\n if (State.mass) this.mass(x, y, scale);\n if (State.hatch) this.hatch(x, y, scale);\n if (State.stroke) this.draw(x, y, scale);\n }\n}\n","// =============================================================================\n// Stroke Runtime Hooks\n// =============================================================================\n\nlet strokeRuntime = {\n createTipSurface: () => {\n throw new Error(\"No stroke runtime adapter registered.\");\n },\n loadImageTip: () => {\n throw new Error(\"No stroke runtime adapter registered.\");\n },\n};\n\n/**\n * Registers or updates host stroke hooks used by brush-tip loading code.\n *\n * @param {object} hooks\n */\nexport function setStrokeRuntime(hooks) {\n strokeRuntime = { ...strokeRuntime, ...hooks };\n}\n\nexport const createTipSurface = (width, height) =>\n strokeRuntime.createTipSurface(width, height);\nexport const loadImageTip = (src, imageToWhite) =>\n strokeRuntime.loadImageTip(src, imageToWhite);\n","import * as Color from \"../core/color.js\";\nimport { createFramebuffer } from \"../core/compositor_runtime.js\";\n\nlet isStrokeCompositeRegistered = false;\nconst DIRTY_BRUSH_PADDING = 2;\n\n// =============================================================================\n// Section: Helpers\n// =============================================================================\n/**\n * Returns whether the current stroke mask framebuffer must be recreated.\n * This happens when the renderer has no mask yet, or when the canvas size or\n * pixel density changed since the last allocation.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {boolean} True when the stroke mask must be rebuilt.\n */\nfunction needsStrokeMask(Renderer, Cwidth, Cheight, Density) {\n return (\n !Renderer.glMask ||\n Renderer.glMask.width !== Cwidth ||\n Renderer.glMask.height !== Cheight ||\n (typeof Renderer.glMask.pixelDensity === \"function\" &&\n Renderer.glMask.pixelDensity() !== Density)\n );\n}\n\n// =============================================================================\n// Section: Resource Management\n// =============================================================================\n/**\n * Ensures the stroke compositor owns a framebuffer-backed mask with the current\n * canvas dimensions. Stroke stamps are rendered into this mask in WebGL before\n * being blended into the main target.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {object} The framebuffer used as stroke mask.\n */\nexport function ensureStrokeCompositeResources(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n) {\n if (needsStrokeMask(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.glMask?.remove) Renderer.glMask.remove();\n Renderer.glMask = createFramebuffer(Renderer, {\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n }\n\n Renderer.glMask.dirtyRect ??= null;\n Renderer.glMask.isDrawn ??= false;\n return Renderer.glMask;\n}\n\n// =============================================================================\n// Section: Mask Lifecycle\n// =============================================================================\n/**\n * Clears the current stroke mask and resets its bookkeeping flags.\n *\n * @param {object|null} target - Stroke mask framebuffer.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n */\nexport function clearStrokeMask(target, clearTarget) {\n if (!target) return;\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\n}\n\n// =============================================================================\n// Section: Composite Bounds\n// =============================================================================\n/**\n * Returns the rect that should be composited from the stroke mask into the\n * main canvas. Stroke bounds are normally tight dirty rects, but when drawing\n * into an active framebuffer we keep the result conservative and composite the\n * full target.\n *\n * @param {object|null} target - Stroke mask framebuffer.\n * @param {Function} getActiveFramebuffer - Returns the currently bound framebuffer.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} expandDirtyRect - Expands a rect by a constant padding.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @param {number} padding - Extra brush padding in pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\nexport function getStrokeCompositeRect(\n target,\n getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n if (getActiveFramebuffer()) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(target.dirtyRect, DIRTY_BRUSH_PADDING),\n );\n}\n\n/**\n * Returns the resource that should be bound to the blend shader's `u_mask`\n * uniform for stroke compositing.\n *\n * @param {object} _Renderer - Active host renderer.\n * @param {object} mask - Stroke mask framebuffer.\n * @returns {object} Stroke mask framebuffer.\n */\nexport function getStrokeShaderMask(_Renderer, mask) {\n return mask;\n}\n\n// =============================================================================\n// Section: Registration\n// =============================================================================\n/**\n * Registers the stroke compositor with the shared color/composite core.\n * Safe to call multiple times.\n */\nexport function initStrokeComposite() {\n if (isStrokeCompositeRegistered) return;\n Color.registerStrokeComposite?.({\n ensureResources: ensureStrokeCompositeResources,\n clearMask: clearStrokeMask,\n getCompositeRect: getStrokeCompositeRect,\n getShaderMask: getStrokeShaderMask,\n });\n isStrokeCompositeRegistered = true;\n}\n","/**\n * Compiles a shader program from the given vertex and fragment sources.\n * @param {WebGL2RenderingContext} gl - The WebGL2 context.\n * @param {string} vert - Vertex shader source.\n * @param {string} frag - Fragment shader source.\n * @returns {WebGLProgram} The compiled and linked program.\n */\nexport const createProgram = (gl, vert, frag) => {\n const p = gl.createProgram();\n for (let [t, src] of [\n [gl.VERTEX_SHADER, vert],\n [gl.FRAGMENT_SHADER, frag],\n ]) {\n const s = gl.createShader(t);\n gl.shaderSource(s, src);\n gl.compileShader(s);\n gl.attachShader(p, s);\n }\n gl.linkProgram(p);\n return p;\n};\n","// =============================================================================\n// Renderer Runtime Hooks\n// =============================================================================\n\n/**\n * Direct-render hooks used by modules that issue raw WebGL commands.\n *\n * These hooks are intentionally narrow:\n * - begin drawing into an offscreen GL mask target\n * - restore the previous draw target afterward\n * - reset any host-side shader/program bookkeeping after direct GL usage\n */\n\nlet rendererRuntime = {\n beginDirectMaskDraw: () => {\n throw new Error(\"No renderer runtime adapter registered.\");\n },\n endDirectMaskDraw: () => {\n throw new Error(\"No renderer runtime adapter registered.\");\n },\n resetDirectShaderTracking: () => {},\n};\n\n/**\n * Registers or updates host renderer hooks used by direct WebGL drawing paths.\n *\n * @param {object} hooks\n */\nexport function setRendererRuntime(hooks) {\n rendererRuntime = { ...rendererRuntime, ...hooks };\n}\n\nexport const beginDirectMaskDraw = (renderer, gl, target) =>\n rendererRuntime.beginDirectMaskDraw(renderer, gl, target);\nexport const endDirectMaskDraw = (renderer, gl, state) =>\n rendererRuntime.endDirectMaskDraw(renderer, gl, state);\nexport const resetDirectShaderTracking = (renderer, gl) =>\n rendererRuntime.resetDirectShaderTracking(renderer, gl);\n","// =============================================================================\n// Module: GL Draw\n// =============================================================================\n/**\n * The GL Draw module batches brush primitives for WebGL2 rendering. It initializes\n * the shader programs and buffers used by circle-based brushes and image-tip brushes,\n * then flushes those queues into the shared framebuffer-backed brush mask.\n */\n\nimport { Cwidth, Cheight, Density, Renderer } from \"../core/target.js\";\nimport {\n Mix,\n isMixReady,\n State,\n} from \"../core/color.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport {\n beginDirectMaskDraw,\n endDirectMaskDraw,\n resetDirectShaderTracking,\n} from \"../core/renderer_runtime.js\";\nimport { getAffineMatrix } from \"../core/runtime.js\";\nimport vertSrc from \"./shader.vert\";\nimport fragSrc from \"./shader.frag\";\nimport imgVertSrc from \"./image.vert\";\nimport imgFragSrc from \"./image.frag\";\n\n// =============================================================================\n// Section: Initialization and Setup\n// =============================================================================\n\n// Module state\nlet isLoaded = false,\n gl,\n framebufferProjMatrix,\n vao,\n buf,\n program;\nlet loadedWidth = 0,\n loadedHeight = 0;\nlet brushMaskTarget = null;\nconst Attr = {},\n Frag = {};\n\n// Cached matrix values — snapshotted once per stroke in snapshotMatrix()\nlet _ma = 1,\n _mb = 0,\n _mc = 0,\n _md = 1,\n _mx = 0,\n _my = 0,\n _halfW = 0,\n _halfH = 0,\n _scale = 1,\n _density = 1;\n\n/**\n * Snapshots the current runtime affine transform. Call once at the start of each stroke.\n */\nexport function snapshotMatrix() {\n const m = getAffineMatrix();\n _ma = m.a;\n _mb = m.b;\n _mc = m.c;\n _md = m.d;\n _mx = m.x;\n _my = m.y;\n _halfW = Cwidth / 2;\n _halfH = Cheight / 2;\n _scale = Math.sqrt(_ma * _ma + _mb * _mb);\n _density = Density;\n}\n\n// Pre-allocated flat buffer for circle data (x, y, radius, alpha per circle)\nconst INITIAL_CAPACITY = 2048;\nlet circleData = new Float32Array(INITIAL_CAPACITY * 4);\nlet circleCount = 0;\nlet bufferCapacity = INITIAL_CAPACITY;\nlet gpuBufferSize = INITIAL_CAPACITY * 4 * 4; // bytes allocated on GPU\nlet circleDirtyRect = null;\n\n// ---------------------------------------------------------------------------\n// Image instancing state\n// ---------------------------------------------------------------------------\nlet imgProgram = null;\nlet imgVao = null;\nlet imgCornerBuf = null;\nlet imgInstanceBuf = null;\nconst imgAttr = {};\nconst imgFrag = {};\nlet imgGpuSize = 0;\n\nconst IMG_FLOATS = 5; // screenX, screenY, halfSize, angle, alpha — per stamp\nconst IMG_INIT_CAP = 256;\nlet imgData = new Float32Array(IMG_INIT_CAP * IMG_FLOATS);\nlet imgCount = 0;\nlet imgCapacity = IMG_INIT_CAP;\nlet imgDirtyRect = null;\n\n// Texture cache: src string → WebGLTexture (cleared whenever the GL context changes)\nconst texCache = new Map();\n\n// Static unit-quad corners for gl.TRIANGLE_STRIP in quad-local space.\nconst QUAD_CORNERS = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]);\n\nfunction ensureBrushMaskTarget() {\n const rendererMask = Renderer?.glMask;\n if (!rendererMask) return null;\n brushMaskTarget = rendererMask;\n brushMaskTarget.dirtyRect ??= null;\n brushMaskTarget.isDrawn ??= false;\n Mix.glMask = brushMaskTarget;\n return brushMaskTarget;\n}\n\nfunction getProjectionMatrix() {\n return framebufferProjMatrix;\n}\n\nfunction beginMaskTarget() {\n return beginDirectMaskDraw(Renderer, gl, Mix.glMask);\n}\n\nfunction endMaskTarget(state) {\n endDirectMaskDraw(Renderer, gl, state);\n}\n\nfunction accumulateDirtyRect(currentRect, minX, minY, maxX, maxY) {\n if (!currentRect) return { minX, minY, maxX, maxY };\n if (minX < currentRect.minX) currentRect.minX = minX;\n if (minY < currentRect.minY) currentRect.minY = minY;\n if (maxX > currentRect.maxX) currentRect.maxX = maxX;\n if (maxY > currentRect.maxY) currentRect.maxY = maxY;\n return currentRect;\n}\n\n/**\n * Initializes WebGL objects if not done already.\n */\nexport function isReady() {\n isMixReady();\n ensureBrushMaskTarget();\n\n const nextGl = Renderer.drawingContext;\n const needsContextRefresh = !isLoaded || gl !== nextGl;\n const needsProjectionRefresh =\n needsContextRefresh || loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (needsProjectionRefresh) {\n framebufferProjMatrix = new Float32Array([\n 2 / Cwidth,\n 0,\n 0,\n 0,\n 0,\n 2 / Cheight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n -1,\n 0,\n 1,\n ]);\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n }\n\n if (!needsContextRefresh) return;\n\n gl = nextGl;\n\n // Create shader program and initialize\n program = createProgram(gl, vertSrc, fragSrc);\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n // Cache attribute and uniform locations\n [\"a_position\", \"a_radius\", \"a_alpha\"].forEach(\n (n) => (Attr[n] = gl.getAttribLocation(program, n)),\n );\n [\"u_matrix\", \"u_color\"].forEach(\n (n) => (Frag[n] = gl.getUniformLocation(program, n)),\n );\n\n // Create persistent VAO and VBO\n vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n\n buf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n gl.bufferData(gl.ARRAY_BUFFER, circleData.byteLength, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n\n // Set up vertex attributes (only needs to happen once with persistent VAO)\n const stride = 16; // 4 floats × 4 bytes\n gl.enableVertexAttribArray(Attr.a_position);\n gl.vertexAttribPointer(Attr.a_position, 2, gl.FLOAT, false, stride, 0);\n gl.enableVertexAttribArray(Attr.a_radius);\n gl.vertexAttribPointer(Attr.a_radius, 1, gl.FLOAT, false, stride, 8);\n gl.enableVertexAttribArray(Attr.a_alpha);\n gl.vertexAttribPointer(Attr.a_alpha, 1, gl.FLOAT, false, stride, 12);\n\n gl.bindVertexArray(null);\n\n // ------------------------------------------------------------------\n // Image-tip instancing program\n // ------------------------------------------------------------------\n texCache.clear();\n\n imgProgram = createProgram(gl, imgVertSrc, imgFragSrc);\n [\"a_corner\", \"a_pos\", \"a_size\", \"a_angle\", \"a_alpha\"].forEach(\n (n) => (imgAttr[n] = gl.getAttribLocation(imgProgram, n)),\n );\n [\"u_proj\", \"u_color\", \"u_tex\"].forEach(\n (n) => (imgFrag[n] = gl.getUniformLocation(imgProgram, n)),\n );\n\n imgVao = gl.createVertexArray();\n gl.bindVertexArray(imgVao);\n\n // Static corner VBO (per-vertex, no divisor)\n imgCornerBuf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, imgCornerBuf);\n gl.bufferData(gl.ARRAY_BUFFER, QUAD_CORNERS, gl.STATIC_DRAW);\n gl.enableVertexAttribArray(imgAttr.a_corner);\n gl.vertexAttribPointer(imgAttr.a_corner, 2, gl.FLOAT, false, 0, 0);\n\n // Instance data VBO (per-instance)\n imgInstanceBuf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, imgInstanceBuf);\n gl.bufferData(gl.ARRAY_BUFFER, imgData.byteLength, gl.DYNAMIC_DRAW);\n imgGpuSize = imgData.byteLength;\n\n const istride = IMG_FLOATS * 4; // 20 bytes\n gl.enableVertexAttribArray(imgAttr.a_pos);\n gl.vertexAttribPointer(imgAttr.a_pos, 2, gl.FLOAT, false, istride, 0);\n gl.vertexAttribDivisor(imgAttr.a_pos, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_size);\n gl.vertexAttribPointer(imgAttr.a_size, 1, gl.FLOAT, false, istride, 8);\n gl.vertexAttribDivisor(imgAttr.a_size, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_angle);\n gl.vertexAttribPointer(imgAttr.a_angle, 1, gl.FLOAT, false, istride, 12);\n gl.vertexAttribDivisor(imgAttr.a_angle, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_alpha);\n gl.vertexAttribPointer(imgAttr.a_alpha, 1, gl.FLOAT, false, istride, 16);\n gl.vertexAttribDivisor(imgAttr.a_alpha, 1);\n\n gl.bindVertexArray(null);\n\n isLoaded = true;\n}\n\n// =============================================================================\n// Section: Drawing Primitives\n// =============================================================================\n\n/**\n * Queue a circle to be drawn with the specified parameters.\n * Data is written directly into a flat Float32Array to avoid object allocation.\n * Applies the full 2D affine transform (rotation + scale + translation) from\n * the current runtime transform so that brush.rotate() and brush.scale() work correctly.\n */\nexport function circle(x, y, diameter, alpha) {\n // Grow buffer if needed\n if (circleCount >= bufferCapacity) {\n bufferCapacity *= 2;\n const newData = new Float32Array(bufferCapacity * 4);\n newData.set(circleData);\n circleData = newData;\n }\n\n // x/y arrive in \"position space\": user coords + (Cwidth/2, Cheight/2).\n // Subtract the offset to recover user coords, apply the full matrix, then re-add\n // the offset so the result is in screen pixel space [0..Cwidth, 0..Cheight].\n const px = x - _halfW;\n const py = y - _halfH;\n\n const offset = circleCount * 4;\n const screenX = _ma * px + _mc * py + _mx + _halfW;\n const screenY = _mb * px + _md * py + _my + _halfH;\n const radius = (_density * diameter * _scale) / 2;\n\n circleData[offset] = screenX;\n circleData[offset + 1] = screenY;\n // Scale the diameter by the matrix's scale factor (length of the transformed x-axis)\n circleData[offset + 2] = radius;\n circleData[offset + 3] = alpha / 255;\n\n const dScreenX = screenX * _density;\n const dScreenY = screenY * _density;\n circleDirtyRect = accumulateDirtyRect(\n circleDirtyRect,\n dScreenX - radius - 1,\n dScreenY - radius - 1,\n dScreenX + radius + 1,\n dScreenY + radius + 1,\n );\n\n circleCount++;\n}\n\n/**\n * Queue an image stamp to be drawn with instanced rendering.\n * Accepts the same coordinate conventions as circle(): x/y in position space\n * (user coords + Cwidth/2, Cheight/2), size in user-coord units, alpha in [0..255].\n * @param {number} x - X in position space.\n * @param {number} y - Y in position space.\n * @param {number} size - Full stamp diameter in user-coord units.\n * @param {number} angle - Rotation in radians.\n * @param {number} alpha - Opacity [0..255].\n * @param {number} [extraPadding=0] - Conservative extra padding in user units.\n */\nexport function stampImage(x, y, size, angle, alpha, extraPadding = 0) {\n if (imgCount >= imgCapacity) {\n imgCapacity *= 2;\n const next = new Float32Array(imgCapacity * IMG_FLOATS);\n next.set(imgData);\n imgData = next;\n }\n\n const px = x - _halfW;\n const py = y - _halfH;\n const screenX = _ma * px + _mc * py + _mx + _halfW;\n const screenY = _mb * px + _md * py + _my + _halfH;\n const halfSize = (_density * size * _scale) / 2;\n const extraRadius = _density * extraPadding * _scale;\n\n const base = imgCount * IMG_FLOATS;\n imgData[base] = screenX;\n imgData[base + 1] = screenY;\n imgData[base + 2] = halfSize;\n imgData[base + 3] = angle;\n imgData[base + 4] = alpha / 255;\n\n // Bounding box: rotated square worst-case = circle of radius halfSize * √2\n const dScreenX = screenX * _density;\n const dScreenY = screenY * _density;\n const boundsRadius = halfSize * 1.42 + extraRadius;\n imgDirtyRect = accumulateDirtyRect(\n imgDirtyRect,\n dScreenX - boundsRadius - 1,\n dScreenY - boundsRadius - 1,\n dScreenX + boundsRadius + 1,\n dScreenY + boundsRadius + 1,\n );\n\n imgCount++;\n}\n\n/**\n * Flush all queued image stamps in a single instanced draw call.\n * @param {object} p5img - The preprocessed brush-tip image/canvas (from T.tips).\n * @param {string} src - The image src string, used as the texture cache key.\n */\nexport function glDrawImages(p5img, src) {\n if (imgCount === 0) return;\n\n Mix.glMask.isDrawn = true;\n const targetState = beginMaskTarget();\n\n // Lazy-create the WebGL texture from the tip canvas on first use.\n let tex = texCache.get(src);\n if (!tex) {\n tex = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, p5img.canvas);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n texCache.set(src, tex);\n }\n\n gl.useProgram(imgProgram);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.uniform1i(imgFrag.u_tex, 0);\n\n const color = State.stroke.color._array;\n gl.uniform4f(imgFrag.u_color, ...color);\n gl.uniformMatrix4fv(imgFrag.u_proj, false, getProjectionMatrix());\n\n gl.bindVertexArray(imgVao);\n gl.bindBuffer(gl.ARRAY_BUFFER, imgInstanceBuf);\n\n const byteCount = imgCount * IMG_FLOATS * 4;\n const dataView = imgData.subarray(0, imgCount * IMG_FLOATS);\n if (byteCount > imgGpuSize) {\n gl.bufferData(gl.ARRAY_BUFFER, imgData, gl.DYNAMIC_DRAW);\n imgGpuSize = imgData.byteLength;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);\n }\n\n gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, imgCount);\n\n gl.bindVertexArray(null);\n gl.bindTexture(gl.TEXTURE_2D, null);\n endMaskTarget(targetState);\n\n if (imgDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, imgDirtyRect);\n imgDirtyRect = null;\n }\n\n imgCount = 0;\n\n // Let the host adapter know we changed the active program.\n resetDirectShaderTracking(Renderer, gl);\n}\n\n/**\n * Removes a cached GL texture by key, forcing re-upload on next draw.\n * Call this when a custom tip function changes after brush.add().\n */\nexport function invalidateTexEntry(key) {\n const tex = texCache.get(key);\n if (tex && gl) gl.deleteTexture(tex);\n texCache.delete(key);\n}\n\n/**\n * Draw all queued circles using WebGL\n */\nexport function glDraw() {\n if (circleCount === 0) return;\n\n Mix.glMask.isDrawn = true;\n const targetState = beginMaskTarget();\n\n const color = State.stroke.color._array;\n\n // Re-activate our shader in case host drawing switched programs.\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n gl.bindVertexArray(vao);\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n\n // Upload vertex data — reallocate GPU buffer only if needed\n const byteCount = circleCount * 16; // 4 floats × 4 bytes\n const dataView = circleData.subarray(0, circleCount * 4);\n if (byteCount > gpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, circleData, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);\n }\n\n // Set uniforms and draw\n gl.uniform4f(Frag.u_color, ...color);\n gl.uniformMatrix4fv(Frag.u_matrix, false, getProjectionMatrix());\n gl.drawArrays(gl.POINTS, 0, circleCount);\n\n gl.bindVertexArray(null);\n endMaskTarget(targetState);\n\n if (circleDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, circleDirtyRect);\n circleDirtyRect = null;\n }\n\n // Reset queue (no deallocation)\n circleCount = 0;\n\n // We called gl.useProgram() directly, bypassing host shader tracking.\n // Reset it so the host is forced to re-activate its own shader next time\n // it draws — otherwise it may skip gl.useProgram() and set uniforms on the\n // wrong active program, causing \"location is not from the associated program\".\n resetDirectShaderTracking(Renderer, gl);\n}\n","// =============================================================================\n// Module: Brush\n// =============================================================================\n/**\n * The Brush module provides a comprehensive set of functions and classes for\n * simulating various drawing tools ranging from pens, markers, pencils, to\n * custom image-based brushes. This module controls brush properties such as\n * weight, color, vibration, and spacing, and manages the drawing process through\n * stateful methods that enable features like pressure sensitivity, clipping, and\n * blending. By supporting multiple brush types and dynamic parameter adjustments,\n * the Brush module facilitates the creation of realistic and expressive stroke effects.\n */\n\n// Core imports\nimport { Cwidth, Cheight, Renderer, isCanvasReady } from \"../core/target.js\";\nimport {\n Mix,\n State,\n} from \"../core/color.js\";\nimport {\n rr,\n map,\n dist,\n randInt,\n calcAngle,\n toDegrees,\n gaussian,\n rArray,\n noise,\n _onSeed, \n cos,\n sin\n} from \"../core/utils.js\";\nimport { createColor } from \"../core/runtime.js\";\nimport { Position, isFieldReady } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { createTipSurface, loadImageTip } from \"./runtime.js\";\n\n// Internal module imports\nimport { initStrokeComposite } from \"./composite.js\";\nimport {\n isReady,\n glDraw,\n glDrawImages,\n circle,\n stampImage,\n invalidateTexEntry,\n snapshotMatrix,\n} from \"./gl_draw.js\";\n\ninitStrokeComposite(); // Register the stroke composite system for offscreen mask rendering and compositing.\n\n// ---------------------------------------------------------------------------\n// Brush State and Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Global stroke state settings.\n */\nState.stroke = {\n color: null,\n weight: 1,\n type: \"HB\",\n isActive: false,\n opacity: 1,\n};\n\nlet list = new Map();\n\nconst DEFAULT_CUSTOM_PRESSURE_VARIATION = {\n offset: 0.08,\n scale: 0.08,\n warp: 0.06,\n tilt: 0.06,\n};\n\n/**\n * Retrieves a shallow copy of the current stroke state.\n * @returns {object} The stroke state.\n */\nexport function BrushState() {\n return { ...State.stroke };\n}\n\n/**\n * Updates the stroke state.\n * @param {object} state - The new stroke state.\n */\nexport function BrushSetState(state) {\n State.stroke = { ...state };\n}\n\n// =============================================================================\n// Section: Brush Manager\n// =============================================================================\n\n/**\n * Adds a new brush with the specified parameters to the brush list.\n * @param {string} name - The unique name for the new brush.\n * @param {object} params - The parameters defining the brush behavior and appearance.\n */\n/**\n * Normalizes the pressure parameter to the internal { type, min_max, curve } format.\n * Accepts:\n * [start, end] — linear ramp between two pressure values\n * [start, mid, end] — piecewise linear (e.g. [1.5, 0.5, 1.5] for U-curve)\n * (t) => value — custom function, t ∈ [0,1], return value ∈ [0,1]\n * { mode: \"gaussian\", curve, min_max } — advanced built-in pressure profile\n * { curve, min_max } — legacy gaussian format, preserved for compatibility\n */\nexport function normalizePressure(p) {\n if (!p) return p;\n if (typeof p === \"function\")\n return {\n type: \"custom\",\n min_max: [0, 1],\n curve: p,\n variation: { ...DEFAULT_CUSTOM_PRESSURE_VARIATION },\n };\n if (typeof p === \"object\" && !Array.isArray(p)) {\n if (p.type === \"custom\" || p.mode === \"custom\") {\n const { mode, ...rest } = p;\n return {\n ...rest,\n type: \"custom\",\n variation: {\n ...DEFAULT_CUSTOM_PRESSURE_VARIATION,\n ...(rest.variation ?? {}),\n },\n };\n }\n if (\n p.type === \"gaussian\" ||\n p.mode === \"gaussian\" ||\n (Array.isArray(p.curve) && Array.isArray(p.min_max))\n ) {\n return {\n ...p,\n type: \"gaussian\",\n curve: p.curve,\n min_max: p.min_max,\n };\n }\n return p;\n }\n if (Array.isArray(p)) {\n const [s, m, e] = p.length === 2 ? [p[0], (p[0] + p[1]) / 2, p[1]] : p;\n const min = Math.min(s, m, e),\n max = Math.max(s, m, e);\n const range = max - min || 1;\n const [ns, nm, ne] = [\n (s - min) / range,\n (m - min) / range,\n (e - min) / range,\n ];\n return {\n type: \"custom\",\n min_max: [min, max],\n variation: { ...DEFAULT_CUSTOM_PRESSURE_VARIATION },\n curve: (t) =>\n t < 0.5 ? ns + (nm - ns) * t * 2 : nm + (ne - nm) * (t - 0.5) * 2,\n };\n }\n}\n\nexport function add(name, params) {\n const validTypes = [\"marker\", \"custom\", \"image\", \"spray\"];\n params.type = validTypes.includes(params.type) ? params.type : \"default\";\n if (params.markerTip === undefined) params.markerTip = true;\n if (params.noise === undefined) params.noise = 0.3;\n params.noise = Math.max(0, Math.min(1, params.noise));\n // Accept legacy param names for backward compatibility\n if (params.vibration !== undefined && params.scatter === undefined)\n params.scatter = params.vibration;\n if (params.definition !== undefined && params.sharpness === undefined)\n params.sharpness = params.definition;\n if (params.quality !== undefined && params.grain === undefined)\n params.grain = params.quality;\n params.pressure = normalizePressure(params.pressure);\n if (params.type === \"custom\") {\n if (typeof params.tip !== \"function\") {\n throw new Error(`Brush \"${name}\" is type \"custom\" but is missing a tip function.`);\n }\n // Rasterise the tip once into a 500×500 P2D buffer.\n // Users draw in a 100×100 coordinate space (origin at centre);\n // dark fills/strokes → high opacity, light/white → transparent.\n const key = `custom::${name}`;\n invalidateTexEntry(key); // discard stale GPU texture if tip changed\n const g = createTipSurface(500, 500);\n g.pixelDensity(1);\n g.background(255);\n g.noSmooth();\n g.push();\n g.translate(250, 250); // centre origin\n g.scale(5); // 100 user units → 500 px\n g.noStroke();\n params.tip(g);\n g.pop();\n T.imageToWhite(g); // dark → high alpha, RGB → white for tint\n T.tips.set(key, g);\n params.tipKey = key;\n list.set(name, { param: params, colors: [], buffers: [] });\n return;\n }\n if (params.type === \"image\") {\n if (!params.image || !params.image.src) {\n throw new Error(\n `Brush \"${name}\" is type \"image\" but is missing params.image.src. Example: image: { src: \"./tip.jpg\" }`,\n );\n }\n T.add(params.image.src);\n list.set(name, { param: params, colors: [], buffers: [] });\n return T.load(); // returns a Promise; only loads images not yet loaded\n }\n list.set(name, { param: params, colors: [], buffers: [] });\n}\n\n/**\n * Retrieves the list of available brush names.\n * @returns {Array<string>} Array of brush names.\n */\nexport function box() {\n return [...list.keys()];\n}\n\nexport function getBrushParams(brushName) {\n return list.get(brushName)?.param ?? null;\n}\n\n/**\n * Scales standard brush parameters by the provided factor.\n * @param {number} scaleFactor - The scaling factor to apply.\n */\nexport function scaleBrushes(scaleFactor) {\n for (const { param } of list.values()) {\n if (param) {\n param.weight *= scaleFactor;\n param.scatter *= scaleFactor;\n param.spacing *= scaleFactor;\n }\n }\n}\n\n/**\n * Sets the current brush type by name.\n * @param {string} brushName - The name of the brush.\n */\nexport function pick(brushName) {\n if (!list.has(brushName)) {\n throw new Error(\n `Brush \"${brushName}\" not found. Available brushes: ${[...list.keys()].join(\", \")}.`,\n );\n }\n State.stroke.type = brushName;\n}\n\n/**\n * Sets the stroke style (color) for the current brush.\n * @param {number|string|Color} r - Red component, CSS color string, or Color object.\n * @param {number} [g] - Green component.\n * @param {number} [b] - Blue component.\n */\nexport function stroke(r, g, b) {\n isCanvasReady();\n State.stroke.color = createColor(...arguments);\n State.stroke.isActive = true;\n}\n\n/**\n * Sets the brush weight (thickness).\n * @param {number} weight - The weight value.\n */\nexport function strokeWeight(weight) {\n State.stroke.weight = weight;\n}\n\n/**\n * Sets the current brush with name, color, and weight.\n * @param {string} brushName - The brush name.\n * @param {string|Color} color - The brush color.\n * @param {number} [weight=1] - The brush weight.\n */\nexport function set(brushName, color, weight = 1) {\n pick(brushName);\n stroke(color);\n strokeWeight(weight);\n}\n\n/**\n * Disables the stroke effect.\n */\nexport function noStroke() {\n State.stroke.isActive = false;\n}\n\n/**\n * Defines a clipping region for strokes.\n * The region uses the same coordinate space as brush drawing commands,\n * with the current runtime transform captured at call time.\n * @param {number[]} region - Array as [x1, y1, x2, y2] defining the clipping region.\n */\nexport function clip(region) {\n isCanvasReady();\n return region;\n}\n\n/**\n * Disables the clipping region.\n */\nexport function noClip() {\n return;\n}\n\n// ---------------------------------------------------------------------------\n// Drawing Variables and Functions\n// ---------------------------------------------------------------------------\nlet _position, _length, _plot, _dir;\nlet _cachedPlotAngle = 0;\nconst current = {};\n\n/**\n * Initializes the drawing state.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of stroke.\n * @param {Plot|false} [plot=false] - Plot object for path-following strokes.\n */\nfunction initializeDrawingState(x, y, length, plot = false) {\n snapshotMatrix();\n _position = new Position(x + Cwidth / 2, y + Cheight / 2);\n _length = length;\n _plot = plot;\n if (_plot) _plot.calcIndex(0);\n}\n\nconst gaussians = [];\n\n_onSeed(() => {\n gaussians.length = 0;\n});\n\n/**\n * Executes the drawing operation.\n * @param {number} angleScale - Angle (in degrees) or scaling factor.\n * @param {boolean} isPlot - True if plotting a shape.\n */\nfunction draw(angleScale, isPlot) {\n if (!isPlot) _dir = angleScale;\n saveState();\n\n const stepSize = spacing();\n const totalSteps = Math.round(\n (_length * (isPlot ? angleScale : 1)) / stepSize,\n );\n current.pressureCount = 10;\n current.cachedPressure = undefined;\n current.lineNoiseCount = 5;\n current.cachedLineNoise = undefined;\n\n const neededGaussians = totalSteps * 2;\n while (gaussians.length < neededGaussians) {\n gaussians.push(gaussian());\n }\n\n for (let i = 0; i < totalSteps; i++) {\n if (isPlot) _cachedPlotAngle = _plot.angle(_position.plotted);\n tip();\n if (isPlot) {\n _position.plotTo(_plot, stepSize, stepSize, angleScale, _cachedPlotAngle);\n } else {\n _position._moveToDegrees(angleScale, stepSize, stepSize);\n }\n }\n restoreState();\n}\n\n/**\n * Prepares the environment for a brush stroke.\n */\nfunction saveState() {\n current.seed = rr() * 999999;\n const { param } = list.get(State.stroke.type) ?? {};\n if (!param) return;\n current.p = param;\n\n // Set pressure values for the stroke\n const { pressure } = param;\n current.isCustomPressure = pressure.type === \"custom\";\n current.a = !current.isCustomPressure ? rr(-1, 1) : 0;\n current.b = !current.isCustomPressure ? rr(1, 1.5) : 0;\n if (!current.isCustomPressure) {\n current.cp = rr(3, 3.5);\n current.ct = 0;\n current.cs = 1;\n current.ck = 0;\n } else {\n const variation = pressure.variation ?? DEFAULT_CUSTOM_PRESSURE_VARIATION;\n current.cp = rr(-variation.offset, variation.offset);\n current.ct = rr(-variation.warp, variation.warp);\n current.cs = rr(1 - variation.scale, 1 + variation.scale);\n current.ck = rr(-variation.tilt, variation.tilt);\n }\n [current.min, current.max] = pressure.min_max;\n\n current.noiseoffset = 0.05 * current.p.noise;\n\n // Cache stroke direction for direction-aware dispersion (non-plot strokes only)\n if (!_plot) {\n current.cos = cos(_dir);\n current.sin = sin(_dir);\n }\n\n // Ensure GL is ready and blend state\n isReady();\n const switchingToBrush = Mix.isBrush !== true;\n Mix.isBrush = true;\n if (switchingToBrush) Mix.justChanged = true;\n Mix.blend(State.stroke.color);\n\n // Set additional state values\n current.alpha = calculateAlpha();\n current.overscan = getImageTipOverscan();\n current.drawFn =\n current.p.type === \"spray\" ? drawSpray :\n current.p.type === \"marker\" ? drawMarker :\n (current.p.type === \"custom\" || current.p.type === \"image\") ? drawImageTip :\n drawDefault;\n\n markerTip();\n}\n\n/**\n * Restores drawing state after completing a stroke.\n */\nfunction restoreState() {\n markerTip();\n glDraw();\n const type = current.p?.type;\n if (type === \"image\") glDrawImages(T.tips.get(current.p.image.src), current.p.image.src);\n else if (type === \"custom\") glDrawImages(T.tips.get(current.p.tipKey), current.p.tipKey);\n}\n\n/**\n * Renders the brush tip based on current pressure and position.\n */\nfunction tip() {\n const pressure = calculatePressure();\n const lineNoise = calculateLineNoise();\n\n if (lineNoise > rr(1,1.02) && rr(0,1) < 0.7) return;\n current.drawFn(pressure * lineNoise);\n}\n\n/**\n * Calculates the effective brush pressure.\n * @returns {number} The calculated pressure.\n */\nfunction calculatePressure() {\n if (current.pressureCount >= 10 || current.cachedPressure === undefined) {\n current.cachedPressure = _plot\n ? simPressure() * _plot.pressure(_position.plotted)\n : simPressure();\n current.pressureCount = 0;\n }\n current.pressureCount++;\n return current.cachedPressure;\n}\n\nfunction calculateLineNoise() {\n if (current.lineNoiseCount >= 10 || current.cachedLineNoise === undefined) {\n current.cachedLineNoise = map(\n noise(current.seed + _position.plotted * 0.01, 0),\n -1,\n 1,\n 1 - current.noiseoffset,\n 1 + current.noiseoffset,\n );\n current.lineNoiseCount = 0;\n }\n current.lineNoiseCount++;\n return current.cachedLineNoise;\n}\n\n/**\n * Simulates brush pressure based on stroke parameters.\n * @returns {number} Simulated pressure value.\n */\nfunction simPressure() {\n if (!current.isCustomPressure) return gauss();\n const t = _position.plotted / _length;\n return map(\n current.p.pressure.curve(\n Math.max(0, Math.min(1, 0.5 + (t - 0.5 + current.ct) * current.cs)),\n ) +\n current.cp +\n current.ck * (t - 0.5),\n 0,\n 1,\n current.min,\n current.max,\n true,\n );\n}\n\n/**\n * Generates a Gaussian-based pressure value.\n * @param {number} [a] - Center parameter.\n * @param {number} [b] - Width parameter.\n * @param {number} [c] - Shape parameter.\n * @param {number} [min] - Minimum pressure.\n * @param {number} [max] - Maximum pressure.\n * @returns {number} Gaussian pressure value.\n */\nfunction gauss(\n a = 0.5 + current.p.pressure.curve[0] * current.a,\n b = 1 - current.p.pressure.curve[1] * current.b,\n c = current.cp,\n min = current.min,\n max = current.max,\n) {\n const peakPos = a * _length;\n const halfWidth =\n (_position.plotted < peakPos ? b * 1.2 : b * 0.8) * (_length / 2);\n return map(\n 1 /\n (1 +\n Math.pow(Math.abs((_position.plotted - peakPos) / halfWidth), 2 * c)),\n 0,\n 1,\n min,\n max,\n );\n}\n\n/**\n * Calculates the alpha (opacity) level for a brush stroke.\n * @returns {number} The calculated opacity.\n */\nfunction calculateAlpha() {\n return [\"default\", \"spray\"].includes(current.p.type)\n ? current.p.opacity\n : current.p.opacity / Math.min(State.stroke.weight, 1.3);\n}\n\n/**\n * Calculates the step spacing based on the current brush parameters.\n * @returns {number} The spacing value.\n */\nfunction spacing() {\n return current.p?.spacing ?? 1;\n}\n\nfunction getImageTipOverscan() {\n const maxPressure = Math.max(1, current.max ?? 1);\n const scatterReach = State.stroke.weight * current.p.scatter;\n const tipReach = State.stroke.weight * current.p.weight * maxPressure;\n\n // Custom/image tips can extend beyond their nominal square because the tip\n // drawing itself may be large and because high scatter creates sparse large\n // stamps near the edge. Keep culling/dirty tracking conservative.\n return Math.max(8, scatterReach * 1.5 + tipReach * 0.75);\n}\n\n// ---------------------------------------------------------------------------\n// Brush Tip Rendering Methods\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the spray tip effect.\n * @param {number} pressure - Current pressure.\n */\nfunction drawSpray(pressure) {\n const vibration =\n State.stroke.weight * current.p.scatter * pressure +\n (State.stroke.weight * rArray(gaussians) * current.p.scatter) / 3;\n const sw = current.p.weight * rr(0.9, 1.1);\n const iterations = Math.ceil(current.p.grain / pressure);\n for (let j = 0; j < iterations; j++) {\n const r = rr(0.9, 1.1);\n const rX = r * vibration * rr(-1, 1);\n const yRandomFactor = rr(-1, 1);\n const sqrtPart = Math.sqrt((r * vibration) ** 2 - rX ** 2);\n circle(\n _position.x + rX,\n _position.y + yRandomFactor * sqrtPart,\n sw,\n current.alpha,\n );\n }\n}\n\n/**\n * Draws the marker tip effect.\n * @param {number} pressure - Current pressure.\n * @param {boolean} [vibrate=true] - Whether to apply vibration.\n */\nfunction drawMarker(pressure, vibrate = true, alpha = current.alpha) {\n const vibration = vibrate ? State.stroke.weight * current.p.scatter : 0;\n const rx = vibrate ? vibration * rr(-1, 1) : 0;\n const ry = vibrate ? vibration * rr(-1, 1) : 0;\n circle(\n _position.x + rx,\n _position.y + ry,\n State.stroke.weight * current.p.weight * pressure,\n alpha * Math.max(0.8, pressure) * rr(0.9,1.1),\n );\n}\n\n/**\n * Queues a stamp for instanced GL rendering.\n * Handles both \"image\" and \"custom\" tip types.\n * @param {number} pressure - Current pressure.\n * @param {number} alpha - Opacity [0..255].\n */\nfunction drawImageTip(pressure, alpha = current.alpha) {\n const vibration = State.stroke.weight * current.p.scatter;\n const rx = vibration * rr(-1, 1);\n const ry = vibration * rr(-1, 1);\n const size = current.p.weight * State.stroke.weight * pressure;\n const overscan = current.overscan;\n let angle = 0;\n if (current.p.rotate === \"random\") {\n angle = randInt(0, 360) * (Math.PI / 180);\n } else if (current.p.rotate === \"natural\") {\n angle = ((_plot ? -_cachedPlotAngle : -_dir) + _position.angle()) * (Math.PI / 180);\n }\n stampImage(\n _position.x + rx,\n _position.y + ry,\n size,\n angle,\n alpha * Math.max(0.8, pressure) * rr(0.9, 1.1),\n overscan,\n );\n}\n\n/**\n * Draws the default brush tip.\n * @param {number} pressure - Current pressure.\n */\nfunction drawDefault(pressure, wiggle = 1) {\n wiggle = map(wiggle, 0, 1, 0.9, 1.05);\n const vibration =\n wiggle *\n State.stroke.weight *\n current.p.scatter *\n (current.p.sharpness +\n ((1 - current.p.sharpness) * rArray(gaussians)) / pressure);\n const passesGate = rr(0, current.p.grain * pressure) > 0.4;\n if (passesGate) {\n let dx, dy;\n if (_plot) {\n const plotAngle = _cachedPlotAngle;\n const plotCos = cos(plotAngle);\n const plotSin = sin(plotAngle);\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * plotSin + along * plotCos;\n dy = perp * plotCos - along * plotSin;\n } else {\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * current.sin + along * current.cos;\n dy = perp * current.cos - along * current.sin;\n }\n const diameter =\n pressure *\n pressure *\n current.p.weight *\n rr(0.85, 1.15) *\n State.stroke.weight;\n const alpha = Math.max(0.9, pressure) * current.alpha * rr(0.75, 1.1);\n circle(\n _position.x + dx,\n _position.y + dy,\n diameter,\n alpha,\n );\n }\n}\n\n/**\n * Draws the marker tip with a blend effect.\n */\nfunction markerTip() {\n if (current.p.markerTip === false) return;\n let pressure = calculatePressure();\n let alpha = current.alpha;\n if (current.p.type === \"marker\") {\n for (let s = 1; s < 10; s++) {\n drawMarker((pressure * s) / 10, true, alpha * 8);\n }\n } else if (current.p.type === \"custom\" || current.p.type === \"image\") {\n for (let s = 1; s < 5; s++) {\n drawImageTip((pressure * s) / 10, alpha * 2);\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Basic Drawing Operations\n// ---------------------------------------------------------------------------\n\n/**\n * Draws a line using the current brush.\n * @param {number} x1 - Start x-coordinate.\n * @param {number} y1 - Start y-coordinate.\n * @param {number} x2 - End x-coordinate.\n * @param {number} y2 - End y-coordinate.\n */\nexport function line(x1, y1, x2, y2) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n let d = dist(x1, y1, x2, y2);\n if (d == 0) return;\n initializeDrawingState(x1, y1, d);\n let angle = calcAngle(x1, y1, x2, y2);\n draw(angle, false);\n}\n\n/**\n * Draws a stroke from a starting point in a given direction.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of the stroke.\n * @param {number} dir - Direction, interpreted using the current runtime angle units.\n */\nexport function flowLine(x, y, length, dir) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n initializeDrawingState(x, y, length);\n draw(toDegrees(dir), false);\n}\n\n/**\n * Draws a predefined plot.\n * @param {object} p - Shape object representing the plot.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nfunction plot(p, x, y, scale) {\n isFieldReady();\n initializeDrawingState(x, y, p.length, p);\n draw(scale, true);\n}\n\n// ---------------------------------------------------------------------------\n// Standard Brushes Definition and Initialization\n// ---------------------------------------------------------------------------\n\n/**\n * Defines a set of standard brushes with specific characteristics. Each brush is defined\n * with properties such as weight, scatter, sharpness, grain, opacity, spacing, and\n * pressure sensitivity. Some brushes have additional properties like type, tip, and rotate.\n */\nconst _vals = [\n \"weight\",\n \"scatter\",\n \"sharpness\",\n \"grain\",\n \"opacity\",\n \"spacing\",\n \"pressure\",\n \"type\",\n \"tip\",\n \"rotate\",\n \"markerTip\",\n \"noise\",\n];\nconst _standard_brushes = [\n [\n \"pen\",\n [0.3, 0.15, 0.9, 2, 150, 0.1, { curve: [0.15, 0.2], min_max: [1.2, 1] }],\n ],\n [\n \"rotring\",\n [0.15, 0.05, 0.7, 15, 210, 0.1, { curve: [0.35, 0.2], min_max: [1.3, 1] }],\n ],\n [\n \"2B\",\n [0.3, 0.75, 0.45, 15, 180, 0.1, { curve: [0.1, 0.3], min_max: [1.1, 0.9] }],\n ],\n [\n \"HB\",\n [0.3, 0.6, 0.3, 10, 170, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"2H\",\n [0.2, 0.6, 0.3, 4, 120, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"cpencil\",\n [0.3, 0.55, 0.8, 7, 75, 0.1, { curve: [0.15, 0.2], min_max: [0.95, 1.2] }],\n ],\n [\n \"pastel\",\n [\n 2.05 / 3,\n 13.4 / 3,\n 0.91,\n 28,\n 35,\n 0.085 / 3,\n { mode: \"gaussian\", curve: [0.4, 0.05], min_max: [1.09, 0.93] },\n \"default\",\n undefined,\n \"natural\",\n true,\n 1,\n ],\n ],\n [\n \"crayon\",\n [\n 0.9 / 3,\n 5.45 / 3,\n 0.75,\n 250,\n 159,\n 0.23 / 3,\n [1.1, 0.9],\n \"default\",\n undefined,\n \"natural\",\n true,\n 1,\n ],\n ],\n [\n \"charcoal\",\n [\n 0.35,\n 1.5,\n 0.68,\n 500,\n 120,\n 0.03,\n { curve: [0.15, 0.4], min_max: [1.1, 0.95] },\n ],\n ],\n [\n \"spray\",\n [\n 0.2,\n 6,\n 15,\n 40,\n 90,\n 0.5,\n { curve: [0.2, 0.35], min_max: [0.7, 1] },\n \"spray\",\n ],\n ],\n [\n \"marker\",\n [\n 2,\n 0.2,\n null,\n null,\n 1,\n 0.03,\n { curve: [0.35, 0.25], min_max: [1.2, 0.85] },\n \"marker\",\n ],\n ],\n];\n\nfor (let s of _standard_brushes) {\n let obj = {};\n for (let i = 0; i < s[1].length; i++) obj[_vals[i]] = s[1][i];\n add(s[0], obj);\n}\n\n// ---------------------------------------------------------------------------\n// Extensions to Polygon and Plot Prototypes\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the polygon using the current brush.\n * @param {boolean} [_brush=false] - Optional brush name override.\n * @param {string|Color} [_color] - Optional color override.\n * @param {number} [_weight] - Optional weight override.\n */\nPolygon.prototype.draw = function (_brush = false, _color, _weight) {\n let state = BrushState();\n if (_brush) set(_brush, _color, _weight);\n if (state.isActive) {\n for (let s of this.sides) {\n line(s[0].x, s[0].y, s[1].x, s[1].y);\n }\n }\n BrushSetState(state);\n};\n\n/**\n * Draws the plot using the current brush.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nPlot.prototype.draw = function (x, y, scale) {\n if (BrushState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n plot(this, x, y, scale);\n }\n};\n\n// =============================================================================\n// Section: Loading Custom Image Tips\n// =============================================================================\n/**\n * This section defines the functionality for managing the loading and processing of image tips.\n * Images are loaded from specified source URLs, converted to a white tint for visual effects,\n * and then stored for future use. It includes methods to add new images, convert their color\n * scheme, and integrate them into the active host image pipeline.\n */\n\n/**\n * Manages loading and processing of image tips.\n * Images are converted to white with inverted alpha for tinting via shaders.\n */\nconst T = {\n tips: new Map(),\n\n /**\n * Registers an image source for later loading.\n * @param {string} src - The source URL of the image.\n */\n add(src) {\n if (!this.tips.has(src)) this.tips.set(src, false);\n },\n\n /**\n * Converts image to white with inverted alpha for tint-based rendering.\n * @param {object} image - The host image object to convert.\n */\n imageToWhite(image) {\n image.loadPixels();\n for (let i = 0; i < 4 * image.width * image.height; i += 4) {\n let average =\n (image.pixels[i] + image.pixels[i + 1] + image.pixels[i + 2]) / 3;\n image.pixels[i] = image.pixels[i + 1] = image.pixels[i + 2] = 255;\n image.pixels[i + 3] = 255 - average;\n }\n image.updatePixels();\n },\n\n /**\n * Loads all registered image tips. Returns a promise that resolves\n * when all images are loaded and processed.\n * @returns {Promise}\n */\n async load() {\n const entries = [...this.tips.keys()].filter((k) => !this.tips.get(k));\n await Promise.all(\n entries.map(\n (src) =>\n loadImageTip(src, T.imageToWhite).then((p5img) => {\n this.tips.set(src, p5img);\n }),\n ),\n );\n },\n};\n","import { State } from \"../core/color.js\";\nimport { toDegreesSigned, map, rr } from \"../core/utils.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { BrushState, BrushSetState, set, line } from \"../stroke/stroke.js\";\n\n// =============================================================================\n// Module: Classic Hatch\n// =============================================================================\n\n// ---------------------------------------------------------------------------\n// Hatch State\n// ---------------------------------------------------------------------------\n\nState.hatch = {\n isActive: false,\n dist: 5,\n angle: 45,\n options: {},\n hBrush: false,\n};\n\n/**\n * Returns a shallow snapshot of the current hatch modifier state.\n *\n * @returns {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}}\n */\nexport function HatchState() {\n return { ...State.hatch };\n}\n\n/**\n * Restores hatch modifier state from a previously captured snapshot.\n *\n * @param {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}} state\n */\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Activates classic scanline hatching for subsequent shapes.\n *\n * @param {number} [dist=5] Distance between scanlines.\n * @param {number} [angle=45] Hatch angle in the current runtime angle units.\n * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [options]\n */\nexport function hatch(\n dist = 5,\n angle = 45,\n options = { rand: false, continuous: false, gradient: false }\n) {\n let s = State.hatch;\n s.isActive = true;\n s.dist = dist;\n s.angle = toDegreesSigned(angle);\n s.options = options;\n}\n\n/**\n * Overrides the brush, color, and weight used specifically for hatch strokes.\n *\n * @param {string} brush\n * @param {string|object} [color=\"black\"]\n * @param {number} [weight=1]\n */\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\n/**\n * Deactivates hatching and clears any hatch-specific brush override.\n */\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Scanline Generation\n// ---------------------------------------------------------------------------\n\n/**\n * Computes hatch segments for one polygon by rotating it into scanline space,\n * intersecting horizontal scanlines against its edges, and rotating the\n * resulting segments back into canvas space.\n *\n * @param {Polygon} polygon\n * @param {number} angle Hatch angle in degrees.\n * @param {number} dist Base scanline spacing.\n * @param {number} gradient Multiplicative spacing growth per scanline.\n * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}\n */\nfunction scanlineHatch(polygon, angle, dist, gradient) {\n const rad = (angle * Math.PI) / 180;\n const cosA = Math.cos(rad),\n sinA = Math.sin(rad);\n const cosB = Math.cos(-rad),\n sinB = Math.sin(-rad);\n\n const verts = polygon.a,\n n = verts.length;\n\n // Rotate vertices; track Y extent\n const rotated = new Array(n);\n let minY = Infinity,\n maxY = -Infinity;\n for (let i = 0; i < n; i++) {\n const x = verts[i][0],\n y = verts[i][1];\n const r = [x * cosA - y * sinA, x * sinA + y * cosA];\n rotated[i] = r;\n if (r[1] < minY) minY = r[1];\n if (r[1] > maxY) maxY = r[1];\n }\n\n // Build edge list (skip horizontal edges)\n const edges = [];\n for (let i = 0; i < n; i++) {\n const a = rotated[i],\n b = rotated[(i + 1) % n];\n if (a[1] !== b[1]) edges.push(a, b);\n }\n const eLen = edges.length;\n\n // Scan, find crossings, rotate back\n const segments = [];\n const cx = [];\n let Y = minY + dist * 0.5,\n step = dist;\n while (Y < maxY) {\n cx.length = 0;\n for (let i = 0; i < eLen; i += 2) {\n const y1 = edges[i][1],\n y2 = edges[i + 1][1];\n if ((y1 <= Y && Y < y2) || (y2 <= Y && Y < y1))\n cx.push(\n edges[i][0] + ((Y - y1) / (y2 - y1)) * (edges[i + 1][0] - edges[i][0])\n );\n }\n cx.sort((a, b) => a - b);\n for (let i = 0; i < cx.length - 1; i += 2) {\n segments.push({\n scanY: Y,\n x1: cx[i] * cosB - Y * sinB,\n y1: cx[i] * sinB + Y * cosB,\n x2: cx[i + 1] * cosB - Y * sinB,\n y2: cx[i + 1] * sinB + Y * cosB,\n });\n }\n Y += step;\n step *= gradient;\n }\n return segments;\n}\n\n/**\n * Collects and orders hatch segments for one polygon or a polygon list.\n *\n * Segments are sorted in scanline traversal order so downstream rendering can\n * optionally connect them into a continuous serpentine path.\n *\n * @param {Polygon|Polygon[]} polygons\n * @param {number} dist\n * @param {number} angle\n * @param {number} gradient\n * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}\n */\nfunction getHatchSegments(polygons, dist, angle, gradient) {\n if (!Array.isArray(polygons)) polygons = [polygons];\n const segs = [];\n for (const poly of polygons) {\n for (const s of scanlineHatch(poly, angle, dist, gradient)) segs.push(s);\n }\n segs.sort((a, b) => (a.scanY === b.scanY ? a.x1 - b.x1 : a.scanY - b.scanY));\n return segs;\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Configuration\n// ---------------------------------------------------------------------------\n\n/**\n * Runs hatch drawing with the temporary hatch-specific brush style if one is active,\n * then restores the outer stroke state.\n *\n * @param {() => void} drawFn\n */\nfunction withHatchStyle(drawFn) {\n const save = BrushState();\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n drawFn();\n BrushSetState(save);\n}\n\n/**\n * Resolves the active hatch parameters and precomputes the ordered scanline segments.\n *\n * @param {Polygon|Polygon[]} polygons\n * @returns {{dist:number, options:Object, segs:Object[]}}\n */\nfunction getActiveHatchConfig(polygons) {\n const dist = State.hatch.dist;\n const angle = ((State.hatch.angle % 180) + 180) % 180;\n const options = State.hatch.options;\n const gradient = options.gradient ? map(options.gradient, 0, 1, 1, 1.1, true) : 1;\n const segs = getHatchSegments(polygons, dist, angle, gradient);\n return { dist, options, segs };\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Lines\n// ---------------------------------------------------------------------------\n\n/**\n * Expands ordered hatch segments into the actual line list that will be drawn.\n *\n * This includes endpoint jitter when `rand` is active and inserts the serpentine\n * connector lines when `continuous` is enabled.\n *\n * @param {Polygon|Polygon[]} polygons\n * @returns {{x1:number, y1:number, x2:number, y2:number, scanY:number, isConnector:boolean}[]}\n */\nexport function getHatchLines(polygons) {\n const { dist, options, segs } = getActiveHatchConfig(polygons);\n const r = options.rand || 0;\n const lines = [];\n\n for (let j = 0; j < segs.length; j++) {\n const s = segs[j];\n let x1 = s.x1, y1 = s.y1, x2 = s.x2, y2 = s.y2;\n if (r) {\n x1 += 2 * r * dist * rr(-1, 1);\n y1 += 2 * r * dist * rr(-1, 1);\n x2 += 2 * r * dist * rr(-1, 1);\n y2 += 2 * r * dist * rr(-1, 1);\n }\n const reverse = options.continuous && j % 2 === 1;\n const line = reverse\n ? { x1: x2, y1: y2, x2: x1, y2: y1, scanY: s.scanY, isConnector: false }\n : { x1, y1, x2, y2, scanY: s.scanY, isConnector: false };\n lines.push(line);\n if (j > 0 && options.continuous) {\n const prev = lines[lines.length - 2];\n lines.push({\n x1: prev.x2,\n y1: prev.y2,\n x2: line.x1,\n y2: line.y1,\n scanY: s.scanY,\n isConnector: true,\n });\n }\n }\n\n return lines;\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Rendering\n// ---------------------------------------------------------------------------\n\n/**\n * Iterates the generated hatch lines and delegates the actual rendering of each\n * segment to the provided callback.\n *\n * @param {Polygon|Polygon[]} polygons\n * @param {(x1:number, y1:number, x2:number, y2:number, index:number, segs:Object[]) => void} drawSegment\n */\nfunction renderHatchSegments(polygons, drawSegment) {\n const segs = getHatchLines(polygons);\n withHatchStyle(() => {\n for (let j = 0; j < segs.length; j++) {\n const s = segs[j];\n drawSegment(s.x1, s.y1, s.x2, s.y2, j, segs);\n }\n });\n}\n\n/**\n * Draws classic hatch lines over one polygon or an array of polygons.\n *\n * @param {Polygon|Polygon[]} polygons\n */\nexport function createHatch(polygons) {\n renderHatchSegments(polygons, (x1, y1, x2, y2) => {\n line(x1, y1, x2, y2);\n });\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Applies the currently active hatch modifier to a polygon, or temporarily\n * overrides hatch parameters for this call only.\n *\n * @param {number|false} [_dist=false]\n * @param {number} [_angle]\n * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [_options]\n */\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (State.hatch.isActive) createHatch(this);\n HatchSetState(state);\n};\n\n/**\n * Converts the plot to a polygon and applies the currently active hatch modifier.\n *\n * @param {number} x\n * @param {number} y\n * @param {number} scale\n */\nPlot.prototype.hatch = function (x, y, scale) {\n if (HatchState().isActive) {\n if (this.origin) (x = this.origin[0]), (y = this.origin[1]), (scale = 1);\n this.pol = this.genPol(x, y, scale, 0.3);\n this.pol.hatch();\n }\n};\n","// =============================================================================\n// Module: Mass\n// =============================================================================\n\nimport { State } from \"../core/color.js\";\nimport { arc } from \"../core/primitives.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { rr2, dist, calcAngle } from \"../core/utils.js\";\nimport { fromDegrees, usesRadians } from \"../core/runtime.js\";\nimport { HatchState, HatchSetState, hatch, getHatchLines } from \"./hatch.js\";\nimport { BrushState, BrushSetState, getBrushParams, set } from \"../stroke/stroke.js\";\nimport { wiggle } from \"../core/flowfield.js\";\n\n// ---------------------------------------------------------------------------\n// Mass State\n// ---------------------------------------------------------------------------\n\nState.mass = {\n isActive: false,\n brush: null,\n color: null,\n options: {},\n};\n\n/**\n * Returns a shallow copy of the current mass state.\n * @returns {object}\n */\nexport function MassState() {\n return { ...State.mass };\n}\n\n/**\n * Restores a previously saved mass state.\n * @param {object} state\n */\nexport function MassSetState(state) {\n State.mass = { ...state };\n}\n\n/**\n * Enables massing mode with a brush, color, and optional configuration.\n *\n * @param {string} brush - Brush name to use for the mass pass.\n * @param {string|Color} color - Color to use for the mass pass.\n * @param {object} [options={}] - Massing options such as precision, strength, gradient, and outline.\n */\nexport function mass(brush, color, options = {}) {\n State.mass.brush = brush;\n State.mass.color = color;\n State.mass.options = options;\n State.mass.isActive = true;\n}\n\n/**\n * Disables massing mode for subsequent geometry.\n */\nexport function noMass() {\n State.mass.isActive = false;\n State.mass.brush = null;\n State.mass.color = null;\n State.mass.options = {};\n}\n\n// ---------------------------------------------------------------------------\n// Polygon Preparation\n// ---------------------------------------------------------------------------\n\n/**\n * Returns a translated copy of a polygon.\n * Used to build the secondary mass layers from an existing base polygon.\n * @param {Polygon} polygon\n * @param {number} jitterX\n * @param {number} jitterY\n * @returns {Polygon}\n */\nfunction jitterPolygon(polygon, jitterX, jitterY) {\n return new Polygon(\n polygon.vertices.map((vertex) => [vertex.x + jitterX, vertex.y + jitterY]),\n );\n}\n\n/**\n * Builds the three polygons used for a mass pass.\n * Both polygon and plot inputs use one base polygon plus two translated copies,\n * so plot-based massing only needs a single `genPol(...)` call.\n * @param {Polygon|Plot} shape\n * @param {number|false} x\n * @param {number} y\n * @param {number} scale\n * @returns {Polygon[]}\n */\nfunction getMassPolygons(shape, x, y, scale) {\n const isPolygon = x === false;\n const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;\n const basePolygon = isPolygon ? shape : shape.genPol(x, y, scale, 0.15);\n const maxJitter = Math.min(scatter * 2, 5);\n const jitters = [\n [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],\n [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],\n ];\n\n return [\n basePolygon,\n jitterPolygon(basePolygon, jitters[0][0], jitters[0][1]),\n jitterPolygon(basePolygon, jitters[1][0], jitters[1][1]),\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Angle & Bounds Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Converts degree values into the current runtime angle units.\n * @param {number} angle\n * @returns {number}\n */\nfunction getAngleConverter() {\n return usesRadians()\n ? (angle) => (angle * Math.PI) / 180\n : (angle) => angle;\n}\n\n/**\n * Computes an axis-aligned bounding box for a polygon.\n * The diagonal is used as a size reference for pivot distance.\n * @param {Polygon} polygon\n * @returns {{minX:number,minY:number,maxX:number,maxY:number,cx:number,cy:number,size:number}}\n */\nfunction getPolygonBounds(polygon) {\n const points = polygon?.a ?? [];\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n for (const [x, y] of points) {\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n return {\n minX,\n minY,\n maxX,\n maxY,\n cx: (minX + maxX) / 2,\n cy: (minY + maxY) / 2,\n size: Math.hypot(maxX - minX, maxY - minY),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Pivot Geometry\n// ---------------------------------------------------------------------------\n\n/**\n * Chooses the diagonal corner family for a whole mass gesture.\n * Positive-angle hatching uses either bottom-right or top-left; negative-angle\n * hatching uses either bottom-left or top-right.\n * @param {number} angleDeg\n * @returns {[number, number]}\n */\nfunction getPivotBias(angleDeg) {\n const normalizedAngle = ((((angleDeg + 90) % 180) + 180) % 180) - 90;\n if (normalizedAngle >= 0) {\n return rr2() < 0.5 ? [1, 1] : [-1, -1];\n } else {\n return rr2() < 0.5 ? [-1, 1] : [1, -1];\n }\n}\n\n/**\n * Places the global pivot anchor outside the polygon, along the selected bias.\n * Distance varies per layer while the bias stays fixed for the whole mass.\n * @param {Polygon} polygon\n * @param {[number, number]} bias\n * @returns {{x:number,y:number}}\n */\nfunction getPivotAnchor(polygon, bias) {\n const bounds = getPolygonBounds(polygon);\n const offset = bounds.size * rr2(0.6, 1.4);\n const [sx, sy] = bias;\n return {\n x: bounds.cx + sx * offset,\n y: bounds.cy + sy * offset,\n };\n}\n\n/**\n * Projects the global pivot anchor onto the perpendicular bisector of a line.\n * This yields a valid circle center equidistant from both endpoints.\n * @param {{x:number,y:number}} anchor\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {{x:number,y:number}|null}\n */\nfunction projectAnchorToBisector(anchor, x1, y1, x2, y2) {\n const mx = (x1 + x2) / 2;\n const my = (y1 + y2) / 2;\n const dx = x2 - x1;\n const dy = y2 - y1;\n const length = Math.hypot(dx, dy);\n if (!length) return null;\n const nx = -dy / length;\n const ny = dx / length;\n const offset = (anchor.x - mx) * nx + (anchor.y - my) * ny;\n return {\n x: mx + nx * offset,\n y: my + ny * offset,\n };\n}\n\n/**\n * Returns the shortest arc between two endpoints around a given center.\n * The returned angles are already converted into the current runtime angle units.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {[number, number]}\n */\nfunction getShortArcAngles(cx, cy, x1, y1, x2, y2, toAngleUnit) {\n let startDeg = calcAngle(cx, cy, x1, y1);\n let endDeg = calcAngle(cx, cy, x2, y2);\n const sweep = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweep > 180) [startDeg, endDeg] = [endDeg, startDeg];\n return [\n toAngleUnit(startDeg),\n toAngleUnit(endDeg),\n ];\n}\n\n/**\n * Splits a hatch line into two slightly separated segments so some gestures\n * read as interrupted rather than perfectly continuous.\n * @param {{x1:number,y1:number,x2:number,y2:number}} seg\n * @returns {Array<{x1:number,y1:number,x2:number,y2:number}>}\n */\nfunction splitSegment(seg) {\n const t = rr2(0.35, 0.65);\n const mx = seg.x1 + (seg.x2 - seg.x1) * t;\n const my = seg.y1 + (seg.y2 - seg.y1) * t;\n const dx = seg.x2 - seg.x1;\n const dy = seg.y2 - seg.y1;\n const length = Math.hypot(dx, dy) || 1;\n const gap = rr2(0.04, 0.1) * length;\n const gx = (dx / length) * gap * 0.5;\n const gy = (dy / length) * gap * 0.5;\n return [\n { x1: seg.x1, y1: seg.y1, x2: mx - gx, y2: my - gy },\n { x1: mx + gx, y1: my + gy, x2: seg.x2, y2: seg.y2 },\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Mass Rendering\n// ---------------------------------------------------------------------------\n\n/**\n * Draws one polygon of the mass as a family of arcs derived from hatch lines.\n * The same pivot bias is used across layers, while each layer gets its own\n * anchor distance from the shape.\n * @param {Polygon} polygon\n * @param {[number, number]} pivotBias\n */\nfunction drawMassArcs(polygon, pivotBias, toAngleUnit) {\n const anchor = getPivotAnchor(polygon, pivotBias);\n for (const seg of getHatchLines(polygon)) {\n const parts = !seg.isConnector && rr2() < 0.35 ? splitSegment(seg) : [seg];\n for (const part of parts) {\n const center = projectAnchorToBisector(anchor, part.x1, part.y1, part.x2, part.y2);\n if (!center) continue;\n const radius = dist(center.x, center.y, part.x1, part.y1);\n if (!radius) continue;\n const [startAngle, endAngle] = getShortArcAngles(\n center.x,\n center.y,\n part.x1,\n part.y1,\n part.x2,\n part.y2,\n toAngleUnit,\n );\n arc(center.x, center.y, radius, startAngle, endAngle);\n }\n }\n}\n\n/**\n * Configures a hatch pass and immediately reinterprets the generated lines as arcs.\n * @param {Polygon} polygon\n * @param {number} dist\n * @param {number} angle\n * @param {object} options\n * @param {[number, number]} pivotBias\n */\nfunction drawMassPass(polygon, dist, angle, options, pivotBias, toAngleUnit) {\n hatch(dist, angle, options);\n drawMassArcs(polygon, pivotBias, toAngleUnit);\n}\n\n/**\n * Creates the built-in \"massing\" effect for a polygon or plot.\n * A mass is built from up to three jittered polygon layers, each hatched and\n * then redrawn as arc gestures around a shared pivot bias.\n * @param {Polygon|Plot} shape\n * @param {number|false} x\n * @param {number} y\n * @param {number} scale\n */\nexport function createMass(shape, x, y, scale) {\n const pols = getMassPolygons(shape, x, y, scale);\n const hatchState = HatchState();\n const brushState = BrushState();\n const fieldState = { ...State.field };\n const precision = State.mass.options?.precision ?? 0.5;\n const strength = State.mass.options?.strength ?? 1;\n const gradient = State.mass.options?.gradient ?? 0.1;\n const outline = State.mass.options?.outline ?? false;\n const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;\n const hatchDist = 1.6 * rr2(scatter * 0.65, scatter * 0.85) - 0.4 * gradient;\n const baseAngle = rr2(-90, 90);\n const pivotBias = getPivotBias(baseAngle);\n const toAngleUnit = getAngleConverter();\n\n set(State.mass.brush, State.mass.color, 1);\n wiggle(2 - precision);\n if (outline) pols[0].draw();\n\n drawMassPass(\n pols[0],\n hatchDist * 0.9,\n fromDegrees(baseAngle),\n {\n gradient,\n rand: 2 - 2 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n\n if (strength > 0.33) {\n drawMassPass(\n pols[1],\n hatchDist,\n fromDegrees(baseAngle + 20 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n }\n\n if (strength > 0.66) {\n drawMassPass(\n pols[2],\n hatchDist * 0.8,\n fromDegrees(baseAngle + 15 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n }\n\n BrushSetState(brushState);\n HatchSetState(hatchState);\n State.field = { ...fieldState };\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Applies massing to polygon geometry.\n */\nPolygon.prototype.mass = function () {\n if (State.mass?.isActive) {\n createMass(this, false);\n }\n};\n\n/**\n * Applies massing to plots by generating their polygon first.\n * @param {number} x\n * @param {number} y\n * @param {number} scale\n */\nPlot.prototype.mass = function (x, y, scale) {\n if (State.mass?.isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n createMass(this, x, y, scale);\n }\n};\n","import { Mix } from \"../core/color.js\";\n\nfunction strokePadding(ctx, matrix) {\n const lineWidth = ctx.lineWidth || 0;\n if (lineWidth <= 0) return 1;\n\n return (\n 1 +\n (lineWidth * Math.max(Math.hypot(matrix.a, matrix.c), Math.hypot(matrix.b, matrix.d))) /\n 2\n );\n}\n\n// =============================================================================\n// Section: Draw shapes to Mask Buffers\n// =============================================================================\n\n/**\n * Draws a polygon to the mask using the provided vertices.\n * @param {Array<{x: number, y: number}>} vertices - Array of vertex coordinates.\n */\nexport function drawPolygon(vertices, matrix = null) {\n const ctx = Mix.ctx;\n if (!matrix) matrix = ctx.getTransform();\n // Cache the current 2D transform once so the hot loop can stay numeric and\n // avoid repeated property reads while we build bounds.\n const a = matrix.a;\n const b = matrix.b;\n const c = matrix.c;\n const d = matrix.d;\n const e = matrix.e;\n const f = matrix.f;\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n\n ctx.beginPath();\n\n // Seed both the path and the transformed bounds from the first vertex so the\n // loop below only needs to append line segments.\n const first = vertices[0];\n let tx = a * first.x + c * first.y + e;\n let ty = b * first.x + d * first.y + f;\n minX = maxX = tx;\n minY = maxY = ty;\n\n ctx.moveTo(first.x, first.y);\n\n for (let i = 1; i < vertices.length; i++) {\n const v = vertices[i];\n\n // Track the transformed bounds in canvas space while we build the path so\n // dirty-rect bookkeeping does not need a second pass over the vertices.\n tx = a * v.x + c * v.y + e;\n ty = b * v.x + d * v.y + f;\n minX = Math.min(minX, tx);\n minY = Math.min(minY, ty);\n maxX = Math.max(maxX, tx);\n maxY = Math.max(maxY, ty);\n\n ctx.lineTo(v.x, v.y);\n }\n\n ctx.closePath();\n\n // Expand by stroke width so the later composite pass copies enough pixels\n // even when the polygon border extends outside the raw vertex bounds.\n const padding = strokePadding(ctx, matrix);\n Mix.markDirtyRect(Mix.mask, {\n minX: minX - padding,\n minY: minY - padding,\n maxX: maxX + padding,\n maxY: maxY + padding,\n });\n}\n\n/**\n * Draws a circle to the mask.\n * @param {number} x - X-coordinate of the circle's center.\n * @param {number} y - Y-coordinate of the circle's center.\n * @param {number} d - Diameter of the circle.\n */\nexport function circle(x, y, d) {\n const PI2 = Math.PI * 2;\n const ctx = Mix.ctx;\n const radius = d / 2;\n\n ctx.moveTo(x + radius, y);\n ctx.arc(x, y, radius, 0, PI2);\n}\n","import * as Color from \"../core/color.js\";\nimport {\n createFramebuffer,\n create2DCanvas,\n} from \"../core/compositor_runtime.js\";\n\n// Small staging canvas used to upload only the dirty fill sub-rect into the\n// framebuffer-backed mask mirror consumed by the blend shader.\nlet FillMaskUploadCanvas = null;\nlet isFillCompositeRegistered = false;\nconst DIRTY_FILL_PADDING = 4;\n\n// =============================================================================\n// Section: Helpers\n// =============================================================================\n/**\n * Returns whether the CPU-side 2D fill mask must be recreated.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} maskWidth - Mask width in physical pixels.\n * @param {number} maskHeight - Mask height in physical pixels.\n * @returns {boolean} True when the 2D fill mask needs reallocation.\n */\nfunction needsFillMaskCanvas(Renderer, maskWidth, maskHeight) {\n return (\n !Renderer.mask ||\n Renderer.mask.width !== maskWidth ||\n Renderer.mask.height !== maskHeight\n );\n}\n\n/**\n * Returns whether the framebuffer-backed fill mask mirror must be recreated.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {boolean} True when the fill mask framebuffer needs reallocation.\n */\nfunction needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density) {\n return (\n !Renderer.fillMaskFramebuffer ||\n Renderer.fillMaskFramebuffer.width !== Cwidth ||\n Renderer.fillMaskFramebuffer.height !== Cheight ||\n (typeof Renderer.fillMaskFramebuffer.pixelDensity === \"function\" &&\n Renderer.fillMaskFramebuffer.pixelDensity() !== Density)\n );\n}\n\n// =============================================================================\n// Section: Resource Management\n// =============================================================================\n/**\n * Ensures fill compositing resources exist for the active renderer.\n *\n * Fill draws first into a CPU-side 2D mask canvas. That mask is later uploaded,\n * dirty-rect by dirty-rect, into a framebuffer-backed mirror used by the final\n * blend shader pass.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n * @returns {{mask: object, ctx: CanvasRenderingContext2D}} Fill mask resources.\n */\nexport function ensureFillCompositeResources(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n clearTarget,\n) {\n const maskWidth = Math.max(1, Math.round(Cwidth * Density));\n const maskHeight = Math.max(1, Math.round(Cheight * Density));\n\n if (needsFillMaskCanvas(Renderer, maskWidth, maskHeight)) {\n Renderer.mask = create2DCanvas(maskWidth, maskHeight);\n }\n\n if (needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.fillMaskFramebuffer?.remove) {\n Renderer.fillMaskFramebuffer.remove();\n }\n Renderer.fillMaskFramebuffer = createFramebuffer(Renderer, {\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n clearTarget(Renderer.fillMaskFramebuffer);\n }\n\n Renderer.mask.dirtyRect ??= null;\n Renderer.mask.isDrawn ??= false;\n Renderer.mask.drawingContext.imageSmoothingEnabled = false;\n return {\n mask: Renderer.mask,\n ctx: Renderer.mask.drawingContext,\n };\n}\n\n// =============================================================================\n// Section: Mask Lifecycle\n// =============================================================================\n/**\n * Clears the current fill mask and resets its bookkeeping flags.\n *\n * @param {object|null} target - Fill mask canvas or framebuffer mirror.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n */\nexport function clearFillMask(target, clearTarget) {\n if (!target) return;\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\n}\n\n// =============================================================================\n// Section: Composite Bounds\n// =============================================================================\n/**\n * Returns the fill dirty rect to composite into the main target. Fill bounds are\n * taken directly from the accumulated 2D mask dirty area plus a small padding.\n *\n * @param {object|null} target - Fill mask canvas.\n * @param {Function} _getActiveFramebuffer - Unused for fill masks.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} expandDirtyRect - Expands a rect by a constant padding.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\nexport function getFillCompositeRect(\n target,\n _getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(target.dirtyRect, DIRTY_FILL_PADDING),\n );\n}\n\n// =============================================================================\n// Section: Upload\n// =============================================================================\n/**\n * Uploads only the dirty portion of the CPU-side 2D fill mask into the\n * framebuffer-backed fill mask mirror used by the shader compositor.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {object} mask - CPU-side 2D fill mask canvas.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} dirtyRect - Dirty rect to upload.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n * @returns {object} Framebuffer-backed fill mask mirror.\n */\nexport function getFillShaderMask(\n Renderer,\n mask,\n dirtyRect,\n getFullDirtyRect,\n clearTarget,\n) {\n const target = Renderer.fillMaskFramebuffer;\n const gl = Renderer.drawingContext;\n const uploadRect = dirtyRect ?? getFullDirtyRect();\n const uploadWidth = uploadRect.maxX - uploadRect.minX;\n const uploadHeight = uploadRect.maxY - uploadRect.minY;\n\n if (\n !FillMaskUploadCanvas ||\n FillMaskUploadCanvas.width !== uploadWidth ||\n FillMaskUploadCanvas.height !== uploadHeight\n ) {\n FillMaskUploadCanvas = create2DCanvas(uploadWidth, uploadHeight);\n }\n\n const uploadContext = FillMaskUploadCanvas.drawingContext;\n uploadContext.clearRect(0, 0, uploadWidth, uploadHeight);\n uploadContext.drawImage(\n mask,\n uploadRect.minX,\n uploadRect.minY,\n uploadWidth,\n uploadHeight,\n 0,\n 0,\n uploadWidth,\n uploadHeight,\n );\n\n clearTarget(target);\n gl.bindTexture(gl.TEXTURE_2D, target.colorTexture);\n gl.texSubImage2D(\n gl.TEXTURE_2D,\n 0,\n uploadRect.minX,\n uploadRect.minY,\n gl.RGBA,\n gl.UNSIGNED_BYTE,\n FillMaskUploadCanvas,\n );\n return target;\n}\n\n// =============================================================================\n// Section: Registration\n// =============================================================================\n/**\n * Registers the fill compositor with the shared color/composite core.\n * Safe to call multiple times.\n */\nexport function initFillComposite() {\n if (isFillCompositeRegistered) return;\n Color.registerFillComposite?.({\n ensureResources: ensureFillCompositeResources,\n clearMask: clearFillMask,\n getCompositeRect: getFillCompositeRect,\n getShaderMask: getFillShaderMask,\n });\n isFillCompositeRegistered = true;\n}\n","// =============================================================================\n// Module: Fill\n// =============================================================================\n/**\n * The Fill module contains functions and classes dedicated to handling\n * the fill properties of shapes within the drawing context. It supports complex fill\n * operations with effects such as bleeding to simulate watercolor-like textures. The\n * methods provided allow for setting the fill color with opacity, controlling the\n * intensity of the bleed effect, and enabling or disabling the fill operation.\n *\n * The watercolor effect implementation is inspired by Tyler Hobbs'\n * techniques for simulating watercolor paints.\n */\n\n// Core imports\nimport { Renderer, Cwidth, Cheight, Density } from \"../core/target.js\";\nimport {\n Mix,\n State,\n} from \"../core/color.js\";\nimport { drawPolygon, circle } from \"./mask.js\";\nimport {\n constrain,\n rr,\n map,\n randInt,\n gaussian,\n rotate,\n cos,\n sin,\n _onSeed,\n} from \"../core/utils.js\";\nimport { isFieldReady } from \"../core/flowfield.js\";\nimport { createColor, getAffineMatrix } from \"../core/runtime.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\n\n// Internal module imports\nimport { initFillComposite } from \"./composite.js\";\n\ninitFillComposite(); // Register the fill composite with the core color module\n\n// =============================================================================\n// Fill State and helpers\n// =============================================================================\n\n// Vertex cap for grow() — set to 0 or false to disable\nconst GROW_MAX_VERTS = 2024;\nlet GROW_CAP;\n\n// Reusable scratch arrays for grow() — avoids 4 allocations per call (~15× per fill)\nlet _growInsX = [];\nlet _growInsY = [];\nlet _growMods = [];\nlet _growDirs = [];\n\n/**\n * Global fill state settings.\n */\nState.fill = {\n opacity: 150,\n bleed_strength: 0.07,\n texture_strength: 0.8,\n border_strength: 0.5,\n direction: \"out\",\n isActive: false,\n};\n\n// Cache the current state\nconst FillState = () => ({ ...State.fill });\nconst FillSetState = (state) => {\n State.fill = { ...state };\n};\n\n// ---------------------------------------------------------------------------\n// Fill Style Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Sets the fill color and opacity for subsequent drawing operations.\n * @param {number|string|Color} a - Either the red component, a CSS color string, or a Color object.\n * @param {number} [b] - The green component or the opacity if using grayscale.\n * @param {number} [c] - The blue component.\n * @param {number} [d] - The opacity.\n */\nexport function fill(a, b, c, d) {\n State.fill.opacity = (arguments.length < 4 ? b : d) || 150;\n State.fill.color = arguments.length < 3 ? createColor(a) : createColor(a, b, c);\n State.fill.isActive = true;\n}\n\n/**\n * Sets the bleed (watercolor) intensity and direction.\n * @param {number} _i - The bleed intensity (clamped to [0,1]).\n * @param {string} [_direction=\"out\"] - The bleeding direction.\n */\nexport function fillBleed(_i, _direction = \"out\") {\n State.fill.bleed_strength = constrain(_i, 0, 1);\n State.fill.direction = _direction;\n}\n\n/**\n * Sets the texture and border strengths for the fill.\n * @param {number} [_texture=0.4] - The texture strength (clamped to [0,1]).\n * @param {number} [_border=0.4] - The border strength (clamped to [0,1]).\n */\nexport function fillTexture(_texture = 0.4, _border = 0.4) {\n State.fill.texture_strength = constrain(_texture, 0, 1);\n State.fill.border_strength = constrain(_border, 0, 1);\n}\n\n/**\n * Disables fill for subsequent drawing operations.\n */\nexport function noFill() {\n State.fill.isActive = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fill Manager Functions\n// ---------------------------------------------------------------------------\n\nlet _polygon;\nlet _bbMinX, _bbMinY, _bbMaxX, _bbMaxY;\n\n// Pre-compute gaussians for reuse\nconst GAUSSIAN_POOL_SIZE = 512;\nconst _gaussians = [[], []]; // [a, b]\nfunction _fillGaussianPools() {\n for (let i = 0; i < GAUSSIAN_POOL_SIZE; i++) {\n _gaussians[0][i] = gaussian(0.5, 0.2);\n _gaussians[1][i] = gaussian(0, 0.02);\n }\n}\n_onSeed(_fillGaussianPools);\n\n// Helper for direction checking - extracted to reduce duplication\nfunction _isLeft(a, b, c) {\n return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) > 0.01;\n}\n\n/**\n * Calculates the centroid of a polygon from its vertices.\n * @param {Object[]} pts - Array of points with {x, y}.\n * @returns {Object} The center point {x, y}.\n */\nfunction _center(pts) {\n if (pts.length === 0) {\n return { x: 0, y: 0 };\n }\n\n if (pts.length < 8) {\n // Simple average for small polygons\n let sumX = 0, sumY = 0;\n for (const pt of pts) { sumX += pt.x; sumY += pt.y; }\n return { x: sumX / pts.length, y: sumY / pts.length };\n }\n\n // Close polygon if needed\n const v = [...pts];\n if (v[0].x !== v[v.length - 1].x || v[0].y !== v[v.length - 1].y)\n v.push(v[0]);\n\n // Calculate using shoelace formula (more efficient implementation)\n let area = 0,\n cx = 0,\n cy = 0;\n for (let i = 0; i < v.length - 1; i++) {\n const cross = v[i].x * v[i + 1].y - v[i + 1].x * v[i].y;\n area += cross;\n cx += (v[i].x + v[i + 1].x) * cross;\n cy += (v[i].y + v[i + 1].y) * cross;\n }\n\n area *= 0.5;\n return area\n ? { x: cx / (6 * area), y: cy / (6 * area) }\n : { x: v[0].x, y: v[0].y };\n}\n\n/**\n * Fills a given polygon with a watercolor effect.\n * @param {Polygon} polygon - The polygon to fill.\n */\nexport function createFill(polygon) {\n if (!State.fill.isActive || !State.fill.color) {\n throw new Error(\n \"No fill color set. Call brush.fill(color) before drawing shapes.\",\n );\n }\n _polygon = polygon;\n _bbMinX = Infinity; _bbMinY = Infinity; _bbMaxX = -Infinity; _bbMaxY = -Infinity;\n for (const [a] of polygon.sides) {\n if (a.x < _bbMinX) _bbMinX = a.x;\n if (a.x > _bbMaxX) _bbMaxX = a.x;\n if (a.y < _bbMinY) _bbMinY = a.y;\n if (a.y > _bbMaxY) _bbMaxY = a.y;\n }\n const v = [...polygon.vertices];\n const _wr = rr(0, 75);\n const fluid = ~~(v.length * 0.25 * (_wr < 5 ? 1 : _wr < 15 ? 2 : 3));\n const strength = State.fill.bleed_strength;\n const modifiers = v.map(\n (_, i) => (i > fluid ? 1 : 0.3) * rr(0.85, 1.4) * strength,\n );\n const shift = randInt(0, v.length);\n const n = v.length;\n const shifted = new Array(n);\n for (let i = 0; i < n; i++) shifted[i] = v[(i + shift) % n];\n const center = _center(shifted);\n return new FillPoly(shifted, modifiers, center, [], true).fill(\n State.fill.color,\n map(State.fill.opacity, 0, 255, 0, 1, true),\n State.fill.texture_strength,\n );\n}\n\n// ---------------------------------------------------------------------------\n// FillPolygon Class\n// ---------------------------------------------------------------------------\n\n/**\n * The FillPolygon class is used to create and manage the properties of the polygons that produces\n * the watercolor effect. It includes methods to grow (expand) the polygon and apply layers\n * of color with varying intensity and erase parts to simulate a natural watercolor bleed.\n * The implementation follows Tyler Hobbs' guide to simulating watercolor:\n * https://tylerxhobbs.com/essays/2017/a-generative-approach-to-simulating-watercolor-paints\n */\nclass FillPoly {\n /**\n * Constructs a FillPolygon.\n * @param {Object[]} _v - Vertices of the polygon.\n * @param {number[]} _m - Multipliers for the bleed effect at each vertex.\n * @param {Object} _center - The polygon's center {x, y}.\n * @param {boolean[]} dir - Array indicating bleed direction per vertex.\n * @param {boolean} isFirst - True for initial polygon.\n */\n constructor(v, m, center, dir = [], isFirst = false, sx, sy) {\n // Initialize properties\n this.v = v;\n this.m = m;\n this.dir = dir;\n this.midP = center;\n\n // Initialize size and direction for first polygon\n if (isFirst) {\n // Calculate size bounds\n let maxX = 0,\n maxY = 0;\n const rayCalc = [];\n\n for (let i = 0; i < v.length; i++) {\n // Store vertex distances to center for size calculation\n const dx = Math.abs(center.x - v[i].x);\n const dy = Math.abs(center.y - v[i].y);\n maxX = Math.max(maxX, dx);\n maxY = Math.max(maxY, dy);\n\n // Store edge info for ray calculations\n const v1 = v[i],\n v2 = v[(i + 1) % v.length];\n const side = { x: v2.x - v1.x, y: v2.y - v1.y };\n const rt = rotate(0, 0, side.x, side.y, 90);\n const mid = { x: v1.x + side.x / 2, y: v1.y + side.y / 2 };\n\n rayCalc.push({\n v1,\n v2,\n ray: {\n point1: mid,\n point2: { x: mid.x + rt.x, y: mid.y + rt.y },\n },\n });\n }\n\n // Store sizes\n this.sizeX = maxX;\n this.sizeY = maxY;\n\n // Calculate directions — inline ray-polygon intersection to avoid\n // O(n) overhead of Polygon.intersect() (cache-key string building,\n // object allocation, intersectLines wrapper) per edge.\n const polySides = _polygon.sides;\n this.dir = Array(v.length);\n for (let i = 0; i < rayCalc.length; i++) {\n const rc = rayCalc[i];\n const r1x = rc.ray.point1.x, r1y = rc.ray.point1.y;\n const r2x = rc.ray.point2.x, r2y = rc.ray.point2.y;\n const rdx = r2x - r1x, rdy = r2y - r1y;\n let count = 0;\n for (let j = 0; j < polySides.length; j++) {\n const sa = polySides[j][0], sb = polySides[j][1];\n const sdx = sb.x - sa.x, sdy = sb.y - sa.y;\n const denom = sdy * rdx - sdx * rdy;\n if (denom === 0) continue;\n const ub = (rdx * (r1y - sa.y) - rdy * (r1x - sa.x)) / denom;\n if (ub < 0 || ub > 1) continue;\n // Compute intersection point inline\n const ua = (sdx * (r1y - sa.y) - sdy * (r1x - sa.x)) / denom;\n const ix = r1x + ua * rdx;\n const iy = r1y + ua * rdy;\n // _isLeft check inline: (v2-v1) × (isect-v1) > 0.01\n if ((rc.v2.x - rc.v1.x) * (iy - rc.v1.y) - (rc.v2.y - rc.v1.y) * (ix - rc.v1.x) > 0.01) {\n count++;\n }\n }\n this.dir[i] = count % 2 === 0;\n }\n\n // Randomize center (single calculation)\n const rx = rr(-0.6, 0.6) * maxX;\n const ry = rr(-0.6, 0.6) * maxY;\n this.midP = { x: center.x + rx, y: center.y + ry };\n } else {\n this.sizeX = sx;\n this.sizeY = sy;\n }\n }\n\n /**\n * Trims vertices from the polygon based on a factor.\n * @param {number} [factor=1] - Factor determining amount of trimming.\n * @returns {Object} An object containing trimmed vertices, multipliers, and direction.\n */\n trim(f = 1) {\n // Fast path for common case\n if (f >= 1 || f < 0 || this.v.length <= 8) {\n return { v: this.v, m: this.m, dir: this.dir };\n }\n\n // Trim from middle for balance\n const n = ~~((1 - f) * this.v.length);\n const s = ~~(this.v.length / 2 - n / 2);\n\n // Copy only the kept ranges instead of cloning the full arrays and splicing.\n const keep = this.v.length - n;\n const v = new Array(keep);\n const m = new Array(keep);\n const dir = new Array(keep);\n let dst = 0;\n\n for (let i = 0; i < s; i++, dst++) {\n v[dst] = this.v[i];\n m[dst] = this.m[i];\n dir[dst] = this.dir[i];\n }\n\n for (let i = s + n; i < this.v.length; i++, dst++) {\n v[dst] = this.v[i];\n m[dst] = this.m[i];\n dir[dst] = this.dir[i];\n }\n\n\n // We want to add at least two vertices to divide the new edge that appears after trimming, at random distances along its path\n const trimStart = s;\n const trimEnd = s + n;\n const edgeStart = this.v[(trimStart - 1 + this.v.length) % this.v.length];\n const edgeEnd = this.v[trimEnd % this.v.length];\n const edgeVec = { x: edgeEnd.x - edgeStart.x, y: edgeEnd.y - edgeStart.y };\n \n // Insert two new vertices at random positions along the new edge\n const insertCount = 2;\n for (let i = 0; i < insertCount; i++) {\n const t = rr(0.25, 0.75); // Random position between 25% and 75% along the edge\n const newVertex = { x: edgeStart.x + edgeVec.x * t, y: edgeStart.y + edgeVec.y * t };\n const insertIdx = s + i;\n v.splice(insertIdx, 0, newVertex);\n m.splice(insertIdx, 0, rr(0.4, 0.7));\n dir.splice(insertIdx, 0, this.dir[trimStart % this.dir.length]);\n }\n\n return { v, m, dir };\n }\n\n /**\n * Randomly samples a fraction of vertices, keeping their order.\n * Any sampled vertex outside the original polygon is pulled inward.\n * @param {number} [ratio=0.3] - Fraction of vertices to keep.\n * @returns {FillPoly} A new FillPoly with fewer vertices, guaranteed inside the original.\n */\n scatter(ratio = 0.3) {\n const L = this.v.length;\n const keep = Math.max(3, ~~(L * ratio));\n const indices = [];\n const step = L / keep;\n for (let i = 0; i < keep; i++) {\n indices.push(~~(i * step + rr(0, step * 0.8)));\n }\n\n const sv = [],\n sm = [],\n sd = [];\n const mid = this.midP;\n const sides = _polygon.sides;\n\n for (const idx of indices) {\n const j = idx % L;\n let p = this.v[j];\n let outside = false;\n // Bounding box reject — vertex outside AABB is definitely outside polygon\n if (p.x < _bbMinX || p.x > _bbMaxX || p.y < _bbMinY || p.y > _bbMaxY) {\n outside = true;\n } else {\n let crossings = 0;\n for (const [a, b] of sides) {\n const ay = a.y,\n by = b.y;\n if ((ay > p.y) === (by > p.y)) continue;\n const t = (p.y - ay) / (by - ay);\n if (p.x < a.x + t * (b.x - a.x)) crossings++;\n }\n outside = crossings % 2 === 0;\n }\n if (outside) {\n p = {\n x: mid.x + (p.x - mid.x) * rr(0.3, 0.6),\n y: mid.y + (p.y - mid.y) * rr(0.3, 0.6),\n };\n }\n sv.push(p);\n sm.push(this.m[j]);\n sd.push(!this.dir[j]);\n }\n\n return new FillPoly(sv, sm, this.midP, sd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Returns a copy with all bleed directions flipped.\n */\n flipDirs() {\n return new FillPoly(this.v, this.m, this.midP, this.dir.map(d => !d), false, this.sizeX, this.sizeY);\n }\n\n /**\n * Grows (or shrinks) the polygon vertices to simulate watercolor spread.\n * @param {number} [growthFactor=1] - Factor controlling growth.\n * @returns {FillPoly} A new FillPoly with adjusted vertices.\n */\n grow(f = 1) {\n const { v: tr_v, m: tr_m, dir: tr_dir } = this.trim(f);\n const len = tr_v.length;\n\n const outLen = len * 2;\n if (_growInsX.length < len) { _growInsX = new Array(len); _growInsY = new Array(len); }\n if (_growMods.length < outLen) { _growMods = new Array(outLen); _growDirs = new Array(outLen); }\n const insertedX = _growInsX;\n const insertedY = _growInsY;\n const newMods = _growMods;\n const newDirs = _growDirs;\n const bleedDirDeg = State.fill.direction === \"out\" ? -90 : 90;\n\n if (_gaussians[0].length === 0) _fillGaussianPools();\n const gPool = _gaussians[0],\n gPoolLen = gPool.length;\n const g2Pool = _gaussians[1],\n g2PoolLen = g2Pool.length;\n\n let idx = 0;\n let insertedIdx = 0;\n let mod = f === 999 ? rr(0.6, 0.8) : State.fill.bleed_strength;\n\n for (let i = 0; i < len; i++) {\n const cv = tr_v[i];\n const nv = tr_v[i + 1 < len ? i + 1 : 0];\n const mi = tr_m[i];\n const di = tr_dir[i];\n\n if (f < 997) mod = mi;\n\n // If mod is smaller than 0.02, skip growing math and just insert the middle vertex\n if (mod < 0.05) {\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n insertedX[insertedIdx] = (cv.x + nv.x) / 2;\n insertedY[insertedIdx] = (cv.y + nv.y) / 2;\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n insertedIdx++;\n continue;\n }\n\n const rotDeg = (di ? bleedDirDeg : -bleedDirDeg) + rr(-1, 1) * 5;\n const c = cos(rotDeg);\n const s = sin(rotDeg);\n\n const sideX = nv.x - cv.x;\n const sideY = nv.y - cv.y;\n const dirX = c * sideX + s * sideY;\n const dirY = c * sideY - s * sideX;\n\n const d = gPool[~~(rr(0, 1) * gPoolLen)] * rr(0.65, 1.35) * mod;\n const nextMod = mi + g2Pool[~~(rr(0, 1) * g2PoolLen)];\n\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n\n insertedX[insertedIdx] = cv.x + sideX * 0.5 + dirX * d;\n insertedY[insertedIdx] = cv.y + sideY * 0.5 + dirY * d;\n newMods[idx] = nextMod;\n newDirs[idx] = di;\n idx++;\n insertedIdx++;\n }\n\n let fv,\n fm,\n fd;\n \n if (GROW_CAP && idx > GROW_CAP) {\n const step = Math.ceil(idx / GROW_CAP);\n const kept = Math.ceil(idx / step);\n fv = new Array(kept);\n fm = new Array(kept);\n fd = new Array(kept);\n let dst = 0;\n for (let j = 0; j < idx; j += step, dst++) {\n fv[dst] =\n j % 2 === 0\n ? tr_v[j >> 1]\n : { x: insertedX[j >> 1], y: insertedY[j >> 1] };\n fm[dst] = newMods[j];\n fd[dst] = newDirs[j];\n }\n } else {\n fv = new Array(idx);\n for (let j = 0; j < idx; j++) {\n fv[j] =\n j % 2 === 0\n ? tr_v[j >> 1]\n : { x: insertedX[j >> 1], y: insertedY[j >> 1] };\n }\n fm = newMods.slice(0, idx);\n fd = newDirs.slice(0, idx);\n }\n return new FillPoly(fv, fm, this.midP, fd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Fills the polygon with multiple layers to simulate a watercolor effect.\n * @param {Color|string} color - The fill color.\n * @param {number} intensity - Opacity intensity (mapped from 0 to 1).\n * @param {number} tex - Texture factor.\n */\n fill(color, intensity, tex) {\n const numLayers = 20;\n const texture = tex * 3;\n const int = 2 * intensity * (1 + tex / 2);\n\n const switchingToFill = Mix.isBrush !== false;\n Mix.isBrush = false;\n if (switchingToFill) Mix.justChanged = true;\n Mix.blend(color);\n\n const m = getAffineMatrix();\n Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * m.a,\n Density * m.b,\n Density * m.c,\n Density * m.d,\n Density * (m.x + Cwidth / 2),\n Density * (m.y + Cheight / 2),\n );\n\n const fillColorBase = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / `;\n Mix.ctx.strokeStyle = fillColorBase + (0.005 * State.fill.border_strength) + \")\";\n Mix.ctx.lineCap = \"round\";\n\n GROW_CAP = GROW_MAX_VERTS * Math.max(0.1, 2 * State.fill.bleed_strength);\n\n const fillMatrix = Mix.ctx.getTransform();\n const size = Math.max(this.sizeX, this.sizeY);\n const darker = rr(0.15, 0.7);\n let pol = this.grow();\n const sparse = this.scatter(0.1).grow().scatter(0.75).flipDirs();\n let pols;\n\n for (let i = 0; i < numLayers; i++) {\n if (i % 4 === 0) {\n pol = pol.grow();\n }\n\n if (i % 2 === 0) {\n pols = [\n pol.grow(1 - 0.0125 * i),\n pol.grow(0.7 - 0.0125 * i),\n pol.grow(0.4 - 0.0125 * i),\n ];\n }\n\n for (const p of pols) {\n const grown = p.grow(999).grow(997);\n grown.layer(i, size, int, fillColorBase, fillMatrix);\n }\n const sparseLayer = sparse.grow(999).flipDirs().grow(997);\n sparseLayer.layer(i, size, int * texture, fillColorBase, fillMatrix);\n if (i % 2 === 0) {\n const darkerLayer = pol.grow(darker).grow(999);\n darkerLayer.layer(i, size, int * 2, fillColorBase, fillMatrix);\n }\n\n if (i % 8 === 0 || i === numLayers - 1) {\n if (texture !== 0) {\n pol.erase(texture * 3, intensity);\n }\n Mix.blend(color, true);\n }\n }\n\n Mix.ctx.restore();\n }\n\n /**\n * Draws a layer of the fill polygon with stroke and fill.\n * @param {number} i - The layer index.\n */\n layer(i, size, int, colorBase, matrix = null) {\n Mix.ctx.lineWidth = map(i, 0, 24, size / 25, size / 30, true);\n\n Mix.ctx.fillStyle = colorBase + int + \"%)\";\n\n drawPolygon(this.v, matrix);\n Mix.ctx.fill();\n Mix.ctx.stroke();\n }\n\n /**\n * Erases parts of the polygon to create a natural watercolor texture.\n * @param {number} texture - Texture strength factor.\n * @param {number} intensity - Intensity value for size scaling.\n */\n erase(texture, intensity) {\n Mix.ctx.save();\n\n const numCircles = ~~(rr(80, 110) * map(texture, 0, 1, 2, 3.5));\n const halfSizeX = this.sizeX / 1.3;\n const halfSizeY = this.sizeY / 1.3;\n const minSize =\n Math.min(this.sizeX, this.sizeY) * (1.3);\n const minSizeFactor = 0.03 * minSize;\n const maxSizeFactor = 0.45 * minSize;\n const { x: midX, y: midY } = this.midP;\n\n Mix.ctx.globalCompositeOperation = \"destination-out\";\n\n const alpha =\n ((5 - map(intensity, 80, 100, 0.3, 0.7, true)) * texture) / 255;\n Mix.ctx.fillStyle = `rgb(255 0 0 / ${alpha})`;\n Mix.ctx.lineWidth = 0;\n\n for (let i = 0; i < numCircles; i++) {\n const x = midX + gaussian(0, halfSizeX);\n const y = midY + gaussian(0, halfSizeY);\n const radius = rr(minSizeFactor, maxSizeFactor);\n\n Mix.ctx.beginPath();\n circle(x, y, radius);\n if (i % 5 !== 0) {\n Mix.ctx.fill();\n }\n }\n\n Mix.ctx.globalCompositeOperation = \"source-over\";\n Mix.ctx.restore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Extend Polygon and Plot Prototypes for Fill\n// ---------------------------------------------------------------------------\n\n/**\n * Applies a fill effect to the polygon using the current fill state.\n * @param {Color|string} [_color] - The color for the fill.\n * @param {number} [_opacity] - The opacity value.\n * @param {number} [_bleed] - The bleed intensity.\n * @param {number} [_texture] - The texture strength.\n * @param {number} [_border] - The border strength.\n * @param {string} [_direction] - The bleed direction.\n */\nPolygon.prototype.fill = function (\n _color = false,\n _opacity,\n _bleed,\n _texture,\n _border,\n _direction,\n) {\n let state = FillState();\n if (_color) {\n fill(_color, _opacity);\n fillBleed(_bleed, _direction);\n fillTexture(_texture, _border);\n }\n if (state.isActive) {\n isFieldReady();\n createFill(this);\n }\n FillSetState(state);\n};\n\n/**\n * Fills a plot on the canvas by generating a polygon based on the provided coordinates.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - Scaling factor.\n */\nPlot.prototype.fill = function (x, y, scale) {\n if (FillState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n this.pol = this.genPol(\n x,\n y,\n scale,\n State.fill.bleed_strength < 0.06\n ? 0\n : map(State.fill.bleed_strength, 0, 0.6, 0.2, 0.60, true),\n );\n this.pol.fill();\n }\n};\n","\nexport default function earcut(data, holeIndices, dim = 2) {\n\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n let outerNode = linkedList(data, 0, outerLen, dim, true);\n const triangles = [];\n\n if (!outerNode || outerNode.next === outerNode.prev) return triangles;\n\n let minX, minY, invSize;\n\n if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);\n\n // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox\n if (data.length > 80 * dim) {\n minX = data[0];\n minY = data[1];\n let maxX = minX;\n let maxY = minY;\n\n for (let i = dim; i < outerLen; i += dim) {\n const x = data[i];\n const y = data[i + 1];\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n\n // minX, minY and invSize are later used to transform coords into integers for z-order calculation\n invSize = Math.max(maxX - minX, maxY - minY);\n invSize = invSize !== 0 ? 32767 / invSize : 0;\n }\n\n earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);\n\n return triangles;\n}\n\n// create a circular doubly linked list from polygon points in the specified winding order\nfunction linkedList(data, start, end, dim, clockwise) {\n let last;\n\n if (clockwise === (signedArea(data, start, end, dim) > 0)) {\n for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n } else {\n for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n }\n\n if (last && equals(last, last.next)) {\n removeNode(last);\n last = last.next;\n }\n\n return last;\n}\n\n// eliminate colinear or duplicate points\nfunction filterPoints(start, end) {\n if (!start) return start;\n if (!end) end = start;\n\n let p = start,\n again;\n do {\n again = false;\n\n if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {\n removeNode(p);\n p = end = p.prev;\n if (p === p.next) break;\n again = true;\n\n } else {\n p = p.next;\n }\n } while (again || p !== end);\n\n return end;\n}\n\n// main ear slicing loop which triangulates a polygon (given as a linked list)\nfunction earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {\n if (!ear) return;\n\n // interlink polygon nodes in z-order\n if (!pass && invSize) indexCurve(ear, minX, minY, invSize);\n\n let stop = ear;\n\n // iterate through ears, slicing them one by one\n while (ear.prev !== ear.next) {\n const prev = ear.prev;\n const next = ear.next;\n\n if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {\n triangles.push(prev.i, ear.i, next.i); // cut off the triangle\n\n removeNode(ear);\n\n // skipping the next vertex leads to less sliver triangles\n ear = next.next;\n stop = next.next;\n\n continue;\n }\n\n ear = next;\n\n // if we looped through the whole remaining polygon and can't find any more ears\n if (ear === stop) {\n // try filtering points and slicing again\n if (!pass) {\n earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);\n\n // if this didn't work, try curing all small self-intersections locally\n } else if (pass === 1) {\n ear = cureLocalIntersections(filterPoints(ear), triangles);\n earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);\n\n // as a last resort, try splitting the remaining polygon into two\n } else if (pass === 2) {\n splitEarcut(ear, triangles, dim, minX, minY, invSize);\n }\n\n break;\n }\n }\n}\n\n// check whether a polygon node forms a valid ear with adjacent nodes\nfunction isEar(ear) {\n const a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n // now make sure we don't have other points inside the potential ear\n const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox\n const x0 = Math.min(ax, bx, cx),\n y0 = Math.min(ay, by, cy),\n x1 = Math.max(ax, bx, cx),\n y1 = Math.max(ay, by, cy);\n\n let p = c.next;\n while (p !== a) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&\n area(p.prev, p, p.next) >= 0) return false;\n p = p.next;\n }\n\n return true;\n}\n\nfunction isEarHashed(ear, minX, minY, invSize) {\n const a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox\n const x0 = Math.min(ax, bx, cx),\n y0 = Math.min(ay, by, cy),\n x1 = Math.max(ax, bx, cx),\n y1 = Math.max(ay, by, cy);\n\n // z-order range for the current triangle bbox;\n const minZ = zOrder(x0, y0, minX, minY, invSize),\n maxZ = zOrder(x1, y1, minX, minY, invSize);\n\n let p = ear.prevZ,\n n = ear.nextZ;\n\n // look for points inside the triangle in both directions\n while (p && p.z >= minZ && n && n.z <= maxZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n // look for remaining points in decreasing z-order\n while (p && p.z >= minZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n }\n\n // look for remaining points in increasing z-order\n while (n && n.z <= maxZ) {\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n return true;\n}\n\n// go through all polygon nodes and cure small local self-intersections\nfunction cureLocalIntersections(start, triangles) {\n let p = start;\n do {\n const a = p.prev,\n b = p.next.next;\n\n if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {\n\n triangles.push(a.i, p.i, b.i);\n\n // remove two nodes involved\n removeNode(p);\n removeNode(p.next);\n\n p = start = b;\n }\n p = p.next;\n } while (p !== start);\n\n return filterPoints(p);\n}\n\n// try splitting polygon into two and triangulate them independently\nfunction splitEarcut(start, triangles, dim, minX, minY, invSize) {\n // look for a valid diagonal that divides the polygon into two\n let a = start;\n do {\n let b = a.next.next;\n while (b !== a.prev) {\n if (a.i !== b.i && isValidDiagonal(a, b)) {\n // split the polygon in two by the diagonal\n let c = splitPolygon(a, b);\n\n // filter colinear points around the cuts\n a = filterPoints(a, a.next);\n c = filterPoints(c, c.next);\n\n // run earcut on each half\n earcutLinked(a, triangles, dim, minX, minY, invSize, 0);\n earcutLinked(c, triangles, dim, minX, minY, invSize, 0);\n return;\n }\n b = b.next;\n }\n a = a.next;\n } while (a !== start);\n}\n\n// link every hole into the outer loop, producing a single-ring polygon without holes\nfunction eliminateHoles(data, holeIndices, outerNode, dim) {\n const queue = [];\n\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n const list = linkedList(data, start, end, dim, false);\n if (list === list.next) list.steiner = true;\n queue.push(getLeftmost(list));\n }\n\n queue.sort(compareXYSlope);\n\n // process holes from left to right\n for (let i = 0; i < queue.length; i++) {\n outerNode = eliminateHole(queue[i], outerNode);\n }\n\n return outerNode;\n}\n\nfunction compareXYSlope(a, b) {\n let result = a.x - b.x;\n // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find\n // the bridge to the outer shell is always the point that they meet at.\n if (result === 0) {\n result = a.y - b.y;\n if (result === 0) {\n const aSlope = (a.next.y - a.y) / (a.next.x - a.x);\n const bSlope = (b.next.y - b.y) / (b.next.x - b.x);\n result = aSlope - bSlope;\n }\n }\n return result;\n}\n\n// find a bridge between vertices that connects hole with an outer ring and link it\nfunction eliminateHole(hole, outerNode) {\n const bridge = findHoleBridge(hole, outerNode);\n if (!bridge) {\n return outerNode;\n }\n\n const bridgeReverse = splitPolygon(bridge, hole);\n\n // filter collinear points around the cuts\n filterPoints(bridgeReverse, bridgeReverse.next);\n return filterPoints(bridge, bridge.next);\n}\n\n// David Eberly's algorithm for finding a bridge between hole and outer polygon\nfunction findHoleBridge(hole, outerNode) {\n let p = outerNode;\n const hx = hole.x;\n const hy = hole.y;\n let qx = -Infinity;\n let m;\n\n // find a segment intersected by a ray from the hole's leftmost point to the left;\n // segment's endpoint with lesser x will be potential connection point\n // unless they intersect at a vertex, then choose the vertex\n if (equals(hole, p)) return p;\n do {\n if (equals(hole, p.next)) return p.next;\n else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {\n const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);\n if (x <= hx && x > qx) {\n qx = x;\n m = p.x < p.next.x ? p : p.next;\n if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint\n }\n }\n p = p.next;\n } while (p !== outerNode);\n\n if (!m) return null;\n\n // look for points inside the triangle of hole point, segment intersection and endpoint;\n // if there are no points found, we have a valid connection;\n // otherwise choose the point of the minimum angle with the ray as connection point\n\n const stop = m;\n const mx = m.x;\n const my = m.y;\n let tanMin = Infinity;\n\n p = m;\n\n do {\n if (hx >= p.x && p.x >= mx && hx !== p.x &&\n pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {\n\n const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential\n\n if (locallyInside(p, hole) &&\n (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {\n m = p;\n tanMin = tan;\n }\n }\n\n p = p.next;\n } while (p !== stop);\n\n return m;\n}\n\n// whether sector in vertex m contains sector in vertex p in the same coordinates\nfunction sectorContainsSector(m, p) {\n return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;\n}\n\n// interlink polygon nodes in z-order\nfunction indexCurve(start, minX, minY, invSize) {\n let p = start;\n do {\n if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);\n p.prevZ = p.prev;\n p.nextZ = p.next;\n p = p.next;\n } while (p !== start);\n\n p.prevZ.nextZ = null;\n p.prevZ = null;\n\n sortLinked(p);\n}\n\n// Simon Tatham's linked list merge sort algorithm\n// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html\nfunction sortLinked(list) {\n let numMerges;\n let inSize = 1;\n\n do {\n let p = list;\n let e;\n list = null;\n let tail = null;\n numMerges = 0;\n\n while (p) {\n numMerges++;\n let q = p;\n let pSize = 0;\n for (let i = 0; i < inSize; i++) {\n pSize++;\n q = q.nextZ;\n if (!q) break;\n }\n let qSize = inSize;\n\n while (pSize > 0 || (qSize > 0 && q)) {\n\n if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {\n e = p;\n p = p.nextZ;\n pSize--;\n } else {\n e = q;\n q = q.nextZ;\n qSize--;\n }\n\n if (tail) tail.nextZ = e;\n else list = e;\n\n e.prevZ = tail;\n tail = e;\n }\n\n p = q;\n }\n\n tail.nextZ = null;\n inSize *= 2;\n\n } while (numMerges > 1);\n\n return list;\n}\n\n// z-order of a point given coords and inverse of the longer side of data bbox\nfunction zOrder(x, y, minX, minY, invSize) {\n // coords are transformed into non-negative 15-bit integer range\n x = (x - minX) * invSize | 0;\n y = (y - minY) * invSize | 0;\n\n x = (x | (x << 8)) & 0x00FF00FF;\n x = (x | (x << 4)) & 0x0F0F0F0F;\n x = (x | (x << 2)) & 0x33333333;\n x = (x | (x << 1)) & 0x55555555;\n\n y = (y | (y << 8)) & 0x00FF00FF;\n y = (y | (y << 4)) & 0x0F0F0F0F;\n y = (y | (y << 2)) & 0x33333333;\n y = (y | (y << 1)) & 0x55555555;\n\n return x | (y << 1);\n}\n\n// find the leftmost node of a polygon ring\nfunction getLeftmost(start) {\n let p = start,\n leftmost = start;\n do {\n if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;\n p = p.next;\n } while (p !== start);\n\n return leftmost;\n}\n\n// check if a point lies within a convex triangle\nfunction pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {\n return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&\n (ax - px) * (by - py) >= (bx - px) * (ay - py) &&\n (bx - px) * (cy - py) >= (cx - px) * (by - py);\n}\n\n// check if a point lies within a convex triangle but false if its equal to the first point of the triangle\nfunction pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {\n return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);\n}\n\n// check if a diagonal between two polygon nodes is valid (lies in polygon interior)\nfunction isValidDiagonal(a, b) {\n return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges\n (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible\n (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors\n equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case\n}\n\n// signed area of a triangle\nfunction area(p, q, r) {\n return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);\n}\n\n// check if two points are equal\nfunction equals(p1, p2) {\n return p1.x === p2.x && p1.y === p2.y;\n}\n\n// check if two segments intersect\nfunction intersects(p1, q1, p2, q2) {\n const o1 = sign(area(p1, q1, p2));\n const o2 = sign(area(p1, q1, q2));\n const o3 = sign(area(p2, q2, p1));\n const o4 = sign(area(p2, q2, q1));\n\n if (o1 !== o2 && o3 !== o4) return true; // general case\n\n if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1\n if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1\n if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2\n if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2\n\n return false;\n}\n\n// for collinear points p, q, r, check if point q lies on segment pr\nfunction onSegment(p, q, r) {\n return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);\n}\n\nfunction sign(num) {\n return num > 0 ? 1 : num < 0 ? -1 : 0;\n}\n\n// check if a polygon diagonal intersects any polygon segments\nfunction intersectsPolygon(a, b) {\n let p = a;\n do {\n if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&\n intersects(p, p.next, a, b)) return true;\n p = p.next;\n } while (p !== a);\n\n return false;\n}\n\n// check if a polygon diagonal is locally inside the polygon\nfunction locallyInside(a, b) {\n return area(a.prev, a, a.next) < 0 ?\n area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :\n area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;\n}\n\n// check if the middle point of a polygon diagonal is inside the polygon\nfunction middleInside(a, b) {\n let p = a;\n let inside = false;\n const px = (a.x + b.x) / 2;\n const py = (a.y + b.y) / 2;\n do {\n if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&\n (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))\n inside = !inside;\n p = p.next;\n } while (p !== a);\n\n return inside;\n}\n\n// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;\n// if one belongs to the outer ring and another to a hole, it merges it into a single ring\nfunction splitPolygon(a, b) {\n const a2 = createNode(a.i, a.x, a.y),\n b2 = createNode(b.i, b.x, b.y),\n an = a.next,\n bp = b.prev;\n\n a.next = b;\n b.prev = a;\n\n a2.next = an;\n an.prev = a2;\n\n b2.next = a2;\n a2.prev = b2;\n\n bp.next = b2;\n b2.prev = bp;\n\n return b2;\n}\n\n// create a node and optionally link it with previous one (in a circular doubly linked list)\nfunction insertNode(i, x, y, last) {\n const p = createNode(i, x, y);\n\n if (!last) {\n p.prev = p;\n p.next = p;\n\n } else {\n p.next = last.next;\n p.prev = last;\n last.next.prev = p;\n last.next = p;\n }\n return p;\n}\n\nfunction removeNode(p) {\n p.next.prev = p.prev;\n p.prev.next = p.next;\n\n if (p.prevZ) p.prevZ.nextZ = p.nextZ;\n if (p.nextZ) p.nextZ.prevZ = p.prevZ;\n}\n\nfunction createNode(i, x, y) {\n return {\n i, // vertex index in coordinates array\n x, y, // vertex coordinates\n prev: null, // previous and next vertex nodes in a polygon ring\n next: null,\n z: 0, // z-order curve value\n prevZ: null, // previous and next nodes in z-order\n nextZ: null,\n steiner: false // indicates whether this is a steiner point\n };\n}\n\n// return a percentage difference between the polygon area and its triangulation area;\n// used to verify correctness of triangulation\nexport function deviation(data, holeIndices, dim, triangles) {\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n\n let polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));\n if (hasHoles) {\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n polygonArea -= Math.abs(signedArea(data, start, end, dim));\n }\n }\n\n let trianglesArea = 0;\n for (let i = 0; i < triangles.length; i += 3) {\n const a = triangles[i] * dim;\n const b = triangles[i + 1] * dim;\n const c = triangles[i + 2] * dim;\n trianglesArea += Math.abs(\n (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -\n (data[a] - data[b]) * (data[c + 1] - data[a + 1]));\n }\n\n return polygonArea === 0 && trianglesArea === 0 ? 0 :\n Math.abs((trianglesArea - polygonArea) / polygonArea);\n}\n\nfunction signedArea(data, start, end, dim) {\n let sum = 0;\n for (let i = start, j = end - dim; i < end; i += dim) {\n sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);\n j = i;\n }\n return sum;\n}\n\n// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts\nexport function flatten(data) {\n const vertices = [];\n const holes = [];\n const dimensions = data[0][0].length;\n let holeIndex = 0;\n let prevLen = 0;\n\n for (const ring of data) {\n for (const p of ring) {\n for (let d = 0; d < dimensions; d++) vertices.push(p[d]);\n }\n if (prevLen) {\n holeIndex += prevLen;\n holes.push(holeIndex);\n }\n prevLen = ring.length;\n }\n return {vertices, holes, dimensions};\n}\n","// =============================================================================\n// Module: Wash\n// =============================================================================\n/**\n * Minimal stateful API for the `wash()` fill modifier.\n */\n\nimport earcut from \"earcut\";\nimport { Renderer, Cwidth, Cheight, isCanvasReady } from \"../core/target.js\";\nimport { State, flushActiveComposite } from \"../core/color.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { getAffineMatrix } from \"../core/runtime.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport { createColor } from \"../core/runtime.js\";\nimport { resetDirectShaderTracking } from \"../core/renderer_runtime.js\";\n\nlet gl = null;\nlet washProgram = null;\nlet washVao = null;\nlet washBuffer = null;\nlet washProjection = null;\nlet loadedWidth = 0;\nlet loadedHeight = 0;\nlet washGpuBufferSize = 0;\n\nconst WashAttr = {};\nconst WashUniform = {};\n\nconst washVertSrc = `#version 300 es\nin vec2 a_position;\nuniform mat4 u_matrix;\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n}`;\n\nconst washFragSrc = `#version 300 es\nprecision highp float;\nuniform vec4 u_color;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(u_color.rgb * u_color.a, u_color.a);\n}`;\n\nState.wash = {\n color: null,\n opacity: 150,\n isActive: false,\n};\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Enables wash mode with a color and opacity.\n *\n * @param {number|string|Color} a - Either the red component, a CSS color string, or a Color object.\n * @param {number} [b] - The green component or the opacity if using grayscale.\n * @param {number} [c] - The blue component.\n * @param {number} [d] - The opacity.\n */\nexport function wash(a, b, c, d) {\n isCanvasReady();\n State.wash.opacity = (arguments.length < 4 ? b : d) ?? 150;\n State.wash.color = arguments.length < 3 ? createColor(a) : createColor(a, b, c);\n State.wash.isActive = true;\n}\n\n/**\n * Disables wash mode for subsequent drawing operations.\n */\nexport function noWash() {\n State.wash.isActive = false;\n}\n\n// =============================================================================\n// GL helpers\n// =============================================================================\n\n/**\n * Lazily creates the reusable program/buffer state for solid wash drawing and\n * refreshes the orthographic projection when the active target size changes.\n */\nfunction ensureWashReady() {\n const nextGl = Renderer.drawingContext;\n const sizeChanged = loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (!washProjection || sizeChanged) {\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n washProjection = new Float32Array([\n 2 / loadedWidth,\n 0,\n 0,\n 0,\n 0,\n -2 / loadedHeight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n 1,\n 0,\n 1,\n ]);\n }\n\n if (gl === nextGl && washProgram && washVao && washBuffer) return;\n\n gl = nextGl;\n washProgram = createProgram(gl, washVertSrc, washFragSrc);\n WashAttr.a_position = gl.getAttribLocation(washProgram, \"a_position\");\n WashUniform.u_matrix = gl.getUniformLocation(washProgram, \"u_matrix\");\n WashUniform.u_color = gl.getUniformLocation(washProgram, \"u_color\");\n\n washVao = gl.createVertexArray();\n gl.bindVertexArray(washVao);\n\n washBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, 0, gl.DYNAMIC_DRAW);\n washGpuBufferSize = 0;\n\n gl.enableVertexAttribArray(WashAttr.a_position);\n gl.vertexAttribPointer(WashAttr.a_position, 2, gl.FLOAT, false, 8, 0);\n\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n}\n\n/**\n * Applies the current runtime affine transform and converts the result into\n * the screen-space coordinates used by the direct GL wash pipeline.\n *\n * @param {number} x - The source x-coordinate in brush drawing space.\n * @param {number} y - The source y-coordinate in brush drawing space.\n * @returns {[number, number]} The transformed screen-space position.\n */\nfunction transformVertexToScreen(x, y) {\n const m = getAffineMatrix();\n return [\n m.a * x + m.c * y + m.x + loadedWidth / 2,\n m.b * x + m.d * y + m.y + loadedHeight / 2,\n ];\n}\n\n/**\n * Triangulates a polygon in local space and returns the transformed triangle\n * vertex buffer ready for upload to the GPU.\n *\n * @param {Polygon} polygon - The polygon to triangulate.\n * @returns {{ triangles: Float32Array, vertexCount: number }} Screen-space\n * triangle vertices plus the number of vertices to draw.\n */\nfunction buildTriangleBuffer(polygon) {\n const flat = new Float32Array(polygon.vertices.length * 2);\n for (let i = 0; i < polygon.vertices.length; i++) {\n const vertex = polygon.vertices[i];\n flat[i * 2] = vertex.x;\n flat[i * 2 + 1] = vertex.y;\n }\n\n const indices = earcut(flat);\n const triangles = new Float32Array(indices.length * 2);\n for (let i = 0; i < indices.length; i++) {\n const idx = indices[i];\n const [screenX, screenY] = transformVertexToScreen(flat[idx * 2], flat[idx * 2 + 1]);\n triangles[i * 2] = screenX;\n triangles[i * 2 + 1] = screenY;\n }\n\n return {\n triangles,\n vertexCount: indices.length,\n };\n}\n\n/**\n * Draws a triangulated solid wash directly to the current GL target.\n *\n * @param {Polygon} polygon - The polygon to fill with the current wash state.\n */\nfunction drawWashPolygon(polygon) {\n if (!State.wash?.isActive || !State.wash.color || polygon.vertices.length < 3) return;\n\n flushActiveComposite();\n ensureWashReady();\n const { triangles, vertexCount } = buildTriangleBuffer(polygon);\n const byteCount = triangles.byteLength;\n gl.useProgram(washProgram);\n gl.enable(gl.BLEND);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n gl.bindVertexArray(washVao);\n gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);\n if (byteCount > washGpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, triangles, gl.DYNAMIC_DRAW);\n washGpuBufferSize = byteCount;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, triangles);\n }\n const color = State.wash.color._array;\n gl.uniformMatrix4fv(WashUniform.u_matrix, false, washProjection);\n gl.uniform4f(\n WashUniform.u_color,\n color[0],\n color[1],\n color[2],\n State.wash.opacity / 255,\n );\n\n gl.drawArrays(gl.TRIANGLES, 0, vertexCount);\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n resetDirectShaderTracking(Renderer, gl);\n}\n\n// =============================================================================\n// Prototype methods\n// =============================================================================\n\n/**\n * Applies a direct GL wash fill to the polygon using the current wash state.\n *\n * @param {Color|string|false} [_color] - Optional override color for this call.\n * @param {number} [_opacity] - Optional override opacity for this call.\n */\nPolygon.prototype.wash = function (_color = false, _opacity) {\n const state = { ...State.wash };\n if (_color !== false) wash(_color, _opacity);\n\n if (State.wash.isActive) {\n drawWashPolygon(this);\n }\n\n State.wash = { ...state };\n};\n\n/**\n * Applies wash to a plot by first generating the plot polygon, mirroring the\n * existing fill-path behavior, and then drawing that polygon with wash.\n *\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\nPlot.prototype.wash = function (x, y, scale) {\n if (!State.wash?.isActive) return;\n if (this.origin) {\n x = this.origin[0];\n y = this.origin[1];\n scale = 1;\n }\n this.pol = this.genPol(x, y, scale, 0, -1);\n this.pol.wash();\n};\n","// =============================================================================\n// Adapter: Standalone Renderer Hooks\n// =============================================================================\n\nimport { Cwidth, Cheight, Density } from \"../../core/target.js\";\nimport { setRendererRuntime } from \"../../core/renderer_runtime.js\";\n\nfunction beginDirectMaskDraw(_renderer, gl, target) {\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n if (hadDepthTest) gl.disable(gl.DEPTH_TEST);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, target.framebuffer);\n gl.viewport(0, 0, target.width * target.density, target.height * target.density);\n\n return { hadDepthTest };\n}\n\nfunction endDirectMaskDraw(renderer, gl, state) {\n if (state?.hadDepthTest) gl.enable(gl.DEPTH_TEST);\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.viewport(\n 0,\n 0,\n Math.max(1, Math.round(Cwidth * Density)),\n Math.max(1, Math.round(Cheight * Density)),\n );\n}\n\nfunction resetStandaloneShaderTracking(_renderer, gl) {\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n}\n\nexport function initStandaloneRendererRuntime() {\n setRendererRuntime({\n beginDirectMaskDraw,\n endDirectMaskDraw,\n resetDirectShaderTracking: resetStandaloneShaderTracking,\n });\n}\n","// =============================================================================\n// Adapter: Standalone Compositor Hooks\n// =============================================================================\n\nimport { createProgram } from \"../../core/gl/utils.js\";\nimport {\n setCompositorRuntime,\n blitDefaultFramebufferSource,\n} from \"../../core/compositor_runtime.js\";\n\nfunction clearTarget(renderer, target, isFramebufferTarget) {\n if (!target) return;\n\n if (isFramebufferTarget(target)) {\n const gl = renderer.drawingContext;\n const previousFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);\n const previousViewport = gl.getParameter(gl.VIEWPORT);\n gl.bindFramebuffer(gl.FRAMEBUFFER, target.framebuffer);\n gl.viewport(0, 0, target.width * target.density, target.height * target.density);\n gl.clearColor(0, 0, 0, 0);\n gl.clear(gl.COLOR_BUFFER_BIT);\n gl.bindFramebuffer(gl.FRAMEBUFFER, previousFramebuffer);\n gl.viewport(\n previousViewport[0],\n previousViewport[1],\n previousViewport[2],\n previousViewport[3],\n );\n return;\n }\n\n const ctx = target.drawingContext;\n ctx.save();\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.clearRect(0, 0, target.width, target.height);\n ctx.restore();\n}\n\nfunction makeShader(gl, vertSrc, fragSrc) {\n const program = createProgram(gl, vertSrc, fragSrc);\n const uniformCache = new Map();\n\n // Persistent VAO for fullscreen-triangle draws (avoids create/delete per pass)\n const quadVao = gl.createVertexArray();\n\n const getUniformLocation = (name) => {\n if (!uniformCache.has(name)) {\n uniformCache.set(name, gl.getUniformLocation(program, name));\n }\n return uniformCache.get(name);\n };\n\n // Pre-cache sampler and color uniform locations (called every blend pass)\n const loc_source = gl.getUniformLocation(program, \"u_source\");\n const loc_mask = gl.getUniformLocation(program, \"u_mask\");\n const loc_color = gl.getUniformLocation(program, \"u_color\");\n\n return {\n program,\n quadVao,\n loc_source,\n loc_mask,\n loc_color,\n setUniform(name, value) {\n const location = getUniformLocation(name);\n if (!location) return;\n if (typeof value === \"boolean\") {\n gl.uniform1i(location, value ? 1 : 0);\n return;\n }\n if (typeof value === \"number\") {\n gl.uniform1f(location, value);\n return;\n }\n if (Array.isArray(value)) {\n if (value.length === 3) gl.uniform3f(location, value[0], value[1], value[2]);\n else if (value.length === 4) gl.uniform4f(location, value[0], value[1], value[2], value[3]);\n return;\n }\n },\n };\n}\n\nfunction ensureBlendShaderProgram(renderer, vertSrc, fragSrc) {\n renderer.shaderProgram ??= makeShader(renderer.drawingContext, vertSrc, fragSrc);\n return renderer.shaderProgram;\n}\n\nfunction createFramebufferTexture(gl, width, height) {\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(\n gl.TEXTURE_2D,\n 0,\n gl.RGBA,\n width,\n height,\n 0,\n gl.RGBA,\n gl.UNSIGNED_BYTE,\n null,\n );\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.bindTexture(gl.TEXTURE_2D, null);\n return texture;\n}\n\nfunction createFramebuffer(renderer, options) {\n const gl = renderer.drawingContext;\n const density = options.density ?? 1;\n const framebuffer = gl.createFramebuffer();\n const width = Math.max(1, options.width);\n const height = Math.max(1, options.height);\n const pixelWidth = Math.max(1, Math.round(width * density));\n const pixelHeight = Math.max(1, Math.round(height * density));\n const colorTexture = createFramebufferTexture(gl, pixelWidth, pixelHeight);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);\n gl.framebufferTexture2D(\n gl.FRAMEBUFFER,\n gl.COLOR_ATTACHMENT0,\n gl.TEXTURE_2D,\n colorTexture,\n 0,\n );\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n\n return {\n __brushFramebuffer: true,\n framebuffer,\n colorTexture,\n width,\n height,\n density,\n pixelDensity: () => density,\n remove() {\n gl.deleteFramebuffer(framebuffer);\n gl.deleteTexture(colorTexture);\n },\n };\n}\n\nfunction ensureBlendSourceFramebuffer(\n renderer,\n currentFramebuffer,\n width,\n height,\n density,\n) {\n currentFramebuffer?.remove?.();\n return createFramebuffer(renderer, {\n width,\n height,\n density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n}\n\nfunction runBlendShaderPass({\n renderer,\n shader,\n source,\n mask,\n color,\n isBrushMask,\n dirtyRect,\n targetIsFramebuffer,\n withScissor,\n}) {\n const gl = renderer.drawingContext;\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n const previousFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);\n const previousProgram = gl.getParameter(gl.CURRENT_PROGRAM);\n const previousVao = gl.getParameter(gl.VERTEX_ARRAY_BINDING);\n\n gl.bindVertexArray(shader.quadVao);\n gl.useProgram(shader.program);\n gl.disable(gl.DEPTH_TEST);\n gl.enable(gl.BLEND);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, source.colorTexture);\n gl.uniform1i(shader.loc_source, 0);\n\n gl.activeTexture(gl.TEXTURE1);\n gl.bindTexture(gl.TEXTURE_2D, mask.colorTexture);\n gl.uniform1i(shader.loc_mask, 1);\n\n shader.setUniform(\"u_targetIsFramebuffer\", targetIsFramebuffer);\n shader.setUniform(\"u_isBrush\", isBrushMask);\n gl.uniform3f(shader.loc_color, color[0], color[1], color[2]);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n withScissor(\n gl,\n dirtyRect,\n () => {\n gl.drawArrays(gl.TRIANGLES, 0, 3);\n },\n !targetIsFramebuffer,\n );\n\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.activeTexture(gl.TEXTURE0);\n gl.bindVertexArray(previousVao);\n gl.useProgram(previousProgram);\n gl.bindFramebuffer(gl.FRAMEBUFFER, previousFramebuffer);\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n}\n\nfunction blitSourceToFramebuffer(args) {\n return blitDefaultFramebufferSource(args);\n}\n\nexport function initStandaloneCompositorRuntime() {\n setCompositorRuntime({\n clearTarget,\n ensureBlendShaderProgram,\n ensureBlendSourceFramebuffer,\n createFramebuffer,\n runBlendShaderPass,\n blitSourceToFramebuffer,\n });\n}\n","// =============================================================================\n// Adapter: Standalone Stroke Hooks\n// =============================================================================\n\nimport { create2DCanvas, get2DContext } from \"../../core/compositor_runtime.js\";\nimport { setStrokeRuntime } from \"../../stroke/runtime.js\";\n\nfunction cssColor(value) {\n if (typeof value === \"number\") {\n const c = Math.max(0, Math.min(255, value));\n return `rgb(${c} ${c} ${c})`;\n }\n return value ?? \"black\";\n}\n\nfunction buildTipSurface(canvas) {\n const ctx = get2DContext(canvas, true);\n const surface = {\n canvas,\n drawingContext: ctx,\n width: canvas.width,\n height: canvas.height,\n pixels: null,\n _fillStyle: \"#ffffff\",\n _strokeStyle: \"transparent\",\n _lineWidth: 1,\n\n pixelDensity() {\n return 1;\n },\n\n background(value) {\n ctx.save();\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.fillStyle = cssColor(value);\n ctx.fillRect(0, 0, canvas.width, canvas.height);\n ctx.restore();\n },\n\n noSmooth() {\n ctx.imageSmoothingEnabled = false;\n },\n\n push() {\n ctx.save();\n },\n\n pop() {\n ctx.restore();\n },\n\n translate(x, y) {\n ctx.translate(x, y);\n },\n\n scale(x, y = x) {\n ctx.scale(x, y);\n },\n\n rotate(angle) {\n ctx.rotate(angle);\n },\n\n noStroke() {\n surface._strokeStyle = \"transparent\";\n },\n\n stroke(value) {\n surface._strokeStyle = cssColor(value);\n },\n\n noFill() {\n surface._fillStyle = \"transparent\";\n },\n\n fill(value) {\n surface._fillStyle = cssColor(value);\n },\n\n strokeWeight(value) {\n surface._lineWidth = value;\n },\n\n rect(x, y, w, h) {\n ctx.beginPath();\n ctx.rect(x, y, w, h);\n surface._paint();\n },\n\n circle(x, y, d) {\n ctx.beginPath();\n ctx.arc(x, y, d / 2, 0, Math.PI * 2);\n surface._paint();\n },\n\n ellipse(x, y, w, h) {\n ctx.beginPath();\n ctx.ellipse(x, y, w / 2, h / 2, 0, 0, Math.PI * 2);\n surface._paint();\n },\n\n line(x1, y1, x2, y2) {\n ctx.beginPath();\n ctx.moveTo(x1, y1);\n ctx.lineTo(x2, y2);\n ctx.strokeStyle = surface._strokeStyle;\n ctx.lineWidth = surface._lineWidth;\n ctx.stroke();\n },\n\n beginShape() {\n ctx.beginPath();\n surface._shapeStarted = false;\n },\n\n vertex(x, y) {\n if (!surface._shapeStarted) {\n ctx.moveTo(x, y);\n surface._shapeStarted = true;\n } else {\n ctx.lineTo(x, y);\n }\n },\n\n endShape(close = false) {\n if (close) ctx.closePath();\n surface._paint();\n },\n\n loadPixels() {\n surface.pixels = ctx.getImageData(0, 0, canvas.width, canvas.height).data;\n },\n\n updatePixels() {\n const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);\n imageData.data.set(surface.pixels);\n ctx.putImageData(imageData, 0, 0);\n },\n\n _paint() {\n if (surface._fillStyle !== \"transparent\") {\n ctx.fillStyle = surface._fillStyle;\n ctx.fill();\n }\n if (surface._strokeStyle !== \"transparent\") {\n ctx.strokeStyle = surface._strokeStyle;\n ctx.lineWidth = surface._lineWidth;\n ctx.stroke();\n }\n },\n };\n\n return surface;\n}\n\nfunction createTipSurface(width, height) {\n return buildTipSurface(create2DCanvas(width, height, true));\n}\n\nfunction loadImageTip(src, imageToWhite) {\n return new Promise((resolve, reject) => {\n const NativeImage = globalThis.Image;\n if (!NativeImage) {\n reject(new Error(\"Standalone image brush loading requires Image support.\"));\n return;\n }\n\n const nativeImg = new NativeImage();\n nativeImg.onload = () => {\n const surface = buildTipSurface(\n create2DCanvas(nativeImg.naturalWidth, nativeImg.naturalHeight, true),\n );\n surface.drawingContext.drawImage(nativeImg, 0, 0);\n imageToWhite(surface);\n resolve(surface);\n };\n nativeImg.onerror = () =>\n reject(new Error(`Failed to load image tip: ${src}`));\n nativeImg.crossOrigin = \"anonymous\";\n nativeImg.src = src;\n });\n}\n\nexport function initStandaloneStrokeRuntime() {\n setStrokeRuntime({\n createTipSurface,\n loadImageTip,\n });\n}\n","/**\n * @fileoverview Standalone entry point for brush.\n */\n\nexport * from \"./adapters/standalone/runtime.js\";\nexport * from \"./adapters/standalone/frame.js\";\nexport { createCanvas } from \"./adapters/standalone/target.js\";\nexport * from \"./index.shared.js\";\n\nimport { initStandaloneTargetRuntime } from \"./adapters/standalone/target.js\";\nimport { initStandaloneRendererRuntime } from \"./adapters/standalone/renderer.js\";\nimport { initStandaloneCompositorRuntime } from \"./adapters/standalone/compositor.js\";\nimport { initStandaloneStrokeRuntime } from \"./adapters/standalone/stroke.js\";\nimport { initStandaloneRuntime } from \"./adapters/standalone/runtime.js\";\n\ninitStandaloneTargetRuntime();\ninitStandaloneRuntime();\ninitStandaloneRendererRuntime();\ninitStandaloneCompositorRuntime();\ninitStandaloneStrokeRuntime();\n","// =============================================================================\n// Adapter: Standalone Frame Helpers\n// =============================================================================\n\nimport { Renderer, isCanvasReady } from \"../../core/target.js\";\nimport { Mix, flushActiveComposite } from \"../../core/color.js\";\nimport { createColor } from \"../../core/runtime.js\";\n\nfunction resetCompositeState() {\n if (Mix.glMask) Mix.clearMask(Mix.glMask);\n if (Mix.mask) Mix.clearMask(Mix.mask);\n Mix.justChanged = false;\n Mix.isBlending = false;\n Mix.isBrush = null;\n Mix.cachedColor = null;\n}\n\n/**\n * Flushes any pending stroke/fill compositing into the active standalone target.\n *\n * Standalone users should call this at the end of a drawing pass or frame.\n */\nexport function render() {\n flushActiveComposite();\n}\n\n/**\n * Clears the active standalone target.\n *\n * With no arguments, clears to transparent white.\n * With a color, clears to that color at full opacity.\n *\n * @param {...*} args\n */\nexport function clear(...args) {\n isCanvasReady();\n resetCompositeState();\n\n const gl = Renderer.drawingContext;\n const color =\n args.length === 0\n ? [1, 1, 1, 0]\n : [...createColor(...args)._array.slice(0, 3), 1];\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.disable(gl.SCISSOR_TEST);\n gl.clearColor(color[0], color[1], color[2], color[3]);\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n}\n"],"names":["identityMatrix","a","b","c","d","x","y","Cwidth","Cheight","Renderer","Density","usesRadians","fromDegrees","angle","createColor","Error","getAffineMatrix","targetRuntime","load","syncDensity","isCanvasReady","instance","inst","activateInstance","deactivateInstance","getActiveFramebuffer","isFramebufferTarget","setTargetState","state","Instance","target","expandDirtyRect","rect","padding","minX","minY","maxX","maxY","create2DCanvas","width","height","willReadFrequently","canvas","OffscreenCanvas","element","document","createElement","drawingContext","getContext","undefined","compositorRuntime","clearTarget","ensureBlendShaderProgram","ensureBlendSourceFramebuffer","createFramebuffer","runBlendShaderPass","blitSourceToFramebuffer","args","strokeComposite","fillComposite","clearRenderTarget","getTargetPixelSize","Math","max","round","normalizeDirtyRect","floor","min","ceil","clampDirtyRect","getFullDirtyRect","getFullRect","toScissorBox","flipY","normalized","withScissor","gl","draw","box","enable","SCISSOR_TEST","scissor","disable","State","isMixReady","loaded","Mix","isBlending","cachedColor","markDirtyRect","dirtyRect","isDrawn","clearMask","composite","this","glMask","getCompositeRect","isBrushMask","needsBlendSourceFramebuffer","blendSourceFramebuffer","pixelDensity","ensureResources","fillResources","mask","ctx","blend","_color","_isLast","isBrush","otherMask","nextColor","_array","colorChanged","justChanged","applyShader","shader","shaderProgram","activeFramebuffer","source","renderer","sourceTarget","sourceFramebuffer","targetIsFramebuffer","shaderMask","getShaderMask","color","flushActiveComposite","SQRT3","sqrt","F2","G2","fastFloor","grad2","Float64Array","createNoise2D","random","perm","p","Uint8Array","i","tableSize","r","aux","buildPermutationTable","permGrad2x","map","v","permGrad2y","n0","n1","n2","s","j","t","x0","y0","i1","j1","x1","y1","x2","y2","ii","jj","t0","gi0","t1","gi1","t2","gi2","prng_alea","seed","opts","xg","AleaGen","prng","next","double","int32","quick","constructor","Date","n","mash","data","String","length","charCodeAt","h","s0","s1","s2","copy","f","rng","rng2","_seedCallbacks","_onSeed","cb","push","noise","noise2","rr","e","rr2","rArray","array","randInt","randInt2","gaussian","mean","stdev","u","log","cos","value","withinBounds","constrain","low","high","nAngle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","fill","NaN","sLookup","idx","isNaN","sin","toDegrees","rad","isRad","runtimeUsesRadians","toDegreesSigned","rotate","cx","cy","coseno","seno","dist","hypot","calcAngle","atan2","intersectLines","s1a","s1b","s2a","s2b","includeSegmentExtension","x3","y3","x4","y4","deltaX1","deltaY1","deltaX2","deltaY2","denominator","ua","ub","isLoaded","isFieldReady","resolution","left_x","top_y","num_columns","num_rows","addField","field","bs","ba","fillField","ar","abs","dif","sr","cr","_t","dir","offset","attractors","Array","from","wx","wy","att","dx","dy","w","freq","amp","_r","Position","m","mx","my","update","plotted","isActive","colIdx","rowIdx","reset","isIn","isInCanvas","skipCheck","list","get","current","wiggle","moveTo","_dir","_length","_step_length","movePos","_moveToDegrees","plotTo","_plot","_scale","precomputedAngle","_dirPlot","_step","scaleFactor","steps","fieldActive","usePlot","plotAngle","getRowIndex","y_offset","getColIndex","x_offset","col","row","Map","FIELD_ANGLE_MODES","Set","normalizeFieldAngleMode","options","angleMode","has","generateField","entry","normalizeFieldAngles","gen","keys","join","name","funct","set","fn","_stateStack","clamp","DEGREES","RADIANS","colorContext","currentAngleMode","transformStack","currentTransform","multiplyTransform","left","right","Color","g","hex","rgbToHex","rgbaMatch","exec","parseInt","alpha","parseFloat","standardize","rgb","hexToRgb","toString","slice","replace","_match","red","green","blue","result","getColorContext","fillStyle","_getRed","_getGreen","_getBlue","initStandaloneRuntime","hooks","_current","_curvature","_strokeArray","_strokeOrigin","activeTarget","activeDensity","activeWidth","activeHeight","applyLoadedTarget","density","premultipliedAlpha","getTargetContext","createRenderer","Polygon","pointsArray","useRawVertices","vertices","sides","arr","_intersectionCache","intersect","line","cacheKey","point1","point2","points","start","end","intersection","show","wash","mass","hatch","stroke","Plot","_type","segments","angles","pres","type","calcIndex","pol","addSegment","_a","_pres","_degrees","pop","reduce","sum","len","endPlot","pressure","_d","curving","index","map0","map1","suma","genPol","_x","_y","_side","step","numSteps","pos","pside","prevIdx","scale","arc","radius","startDeg","sweepDeg","segmentCount","segmentSweep","arcLength","startX","startY","SubPath","isClosed","curvature","vert","vertex","_createSpline","beginShape","endShape","close","PI2","pep","tep","pep2","done","p1","p2","p3","d1","d2","a1","a2","curvAdjust","dmax","temp","temp2","point3","point4","intPt","halfDist","asin","origin","strokeRuntime","createTipSurface","loadImageTip","isStrokeCompositeRegistered","createProgram","frag","src","VERTEX_SHADER","FRAGMENT_SHADER","createShader","shaderSource","compileShader","attachShader","linkProgram","rendererRuntime","beginDirectMaskDraw","endDirectMaskDraw","resetDirectShaderTracking","framebufferProjMatrix","vao","buf","program","loadedWidth","loadedHeight","brushMaskTarget","Attr","Frag","_ma","_mb","_mc","_md","_mx","_my","_halfW","_halfH","_density","circleData","INITIAL_CAPACITY","circleCount","bufferCapacity","gpuBufferSize","circleDirtyRect","imgProgram","imgVao","imgCornerBuf","imgInstanceBuf","imgAttr","imgFrag","imgGpuSize","imgData","IMG_INIT_CAP","imgCount","imgCapacity","imgDirtyRect","texCache","QUAD_CORNERS","getProjectionMatrix","beginMaskTarget","endMaskTarget","accumulateDirtyRect","currentRect","circle","diameter","newData","px","py","screenX","screenY","dScreenX","dScreenY","glDrawImages","p5img","targetState","tex","createTexture","bindTexture","TEXTURE_2D","texImage2D","RGBA","UNSIGNED_BYTE","texParameteri","TEXTURE_MIN_FILTER","LINEAR","TEXTURE_MAG_FILTER","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","useProgram","BLEND","blendFunc","ONE_MINUS_DST_ALPHA","ONE","activeTexture","TEXTURE0","uniform1i","u_tex","uniform4f","u_color","uniformMatrix4fv","u_proj","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","drawArraysInstanced","TRIANGLE_STRIP","needsStrokeMask","remove","antialias","depth","stencil","_Renderer","weight","opacity","DEFAULT_CUSTOM_PRESSURE_VARIATION","warp","tilt","BrushState","BrushSetState","add","params","includes","markerTip","vibration","scatter","definition","sharpness","quality","grain","min_max","curve","variation","isArray","mode","rest","range","ns","nm","ne","normalizePressure","tip","key","deleteTexture","delete","invalidateTexEntry","background","noSmooth","translate","noStroke","T","imageToWhite","tips","tipKey","param","colors","buffers","image","getBrushParams","brushName","pick","arguments","strokeWeight","_position","_cachedPlotAngle","initializeDrawingState","plot","snapshotMatrix","gaussians","angleScale","isPlot","isCustomPressure","cp","ct","cs","ck","noiseoffset","rendererMask","ensureBrushMaskTarget","nextGl","needsContextRefresh","forEach","getAttribLocation","getUniformLocation","createVertexArray","createBuffer","enableVertexAttribArray","a_position","vertexAttribPointer","FLOAT","a_radius","a_alpha","clear","STATIC_DRAW","a_corner","a_pos","IMG_FLOATS","vertexAttribDivisor","a_size","a_angle","isReady","switchingToBrush","overscan","maxPressure","scatterReach","tipReach","getImageTipOverscan","drawFn","drawSpray","drawMarker","drawImageTip","drawDefault","saveState","stepSize","spacing","totalSteps","pressureCount","cachedPressure","lineNoiseCount","cachedLineNoise","neededGaussians","u_matrix","drawArrays","POINTS","glDraw","restoreState","calculatePressure","lineNoise","simPressure","peakPos","halfWidth","pow","gauss","sw","iterations","rX","yRandomFactor","sqrtPart","vibrate","rx","ry","size","extraPadding","halfSize","extraRadius","base","boundsRadius","stampImage","plotCos","plotSin","perp","along","_vals","_standard_brushes","obj","prototype","_brush","_weight","loadPixels","average","pixels","updatePixels","entries","filter","k","Promise","all","then","HatchState","HatchSetState","rand","continuous","gradient","scanlineHatch","polygon","cosA","sinA","cosB","sinB","verts","rotated","Infinity","edges","eLen","Y","sort","scanY","getHatchLines","polygons","segs","poly","getHatchSegments","getActiveHatchConfig","lines","isConnector","prev","createHatch","drawSegment","save","hBrush","Object","values","withHatchStyle","renderHatchSegments","jitterPolygon","jitterX","jitterY","projectAnchorToBisector","anchor","nx","ny","getShortArcAngles","toAngleUnit","endDeg","splitSegment","seg","gap","gx","gy","drawMassArcs","pivotBias","bias","bounds","getPolygonBounds","sx","sy","getPivotAnchor","parts","part","center","startAngle","endAngle","drawMassPass","createMass","shape","pols","isPolygon","brush","basePolygon","maxJitter","jitters","getMassPolygons","hatchState","brushState","fieldState","precision","strength","outline","hatchDist","baseAngle","_dist","_angle","_options","FillMaskUploadCanvas","isFillCompositeRegistered","maskWidth","maskHeight","needsFillMaskCanvas","fillMaskFramebuffer","needsFillMaskFramebuffer","imageSmoothingEnabled","_getActiveFramebuffer","uploadRect","uploadWidth","uploadHeight","uploadContext","clearRect","drawImage","colorTexture","texSubImage2D","GROW_CAP","_growInsX","_growInsY","_growMods","_growDirs","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","_polygon","_bbMinX","_bbMinY","_bbMaxX","_bbMaxY","_gaussians","_fillGaussianPools","FillPoly","isFirst","midP","rayCalc","v1","v2","side","rt","mid","ray","sizeX","sizeY","polySides","rc","r1x","r1y","rdx","rdy","count","sa","sb","sdx","sdy","denom","ix","iy","trim","keep","dst","trimStart","trimEnd","edgeStart","edgeEnd","edgeVec","newVertex","insertIdx","splice","ratio","L","indices","sv","sm","sd","outside","crossings","ay","by","flipDirs","grow","tr_v","tr_m","tr_dir","outLen","insertedX","insertedY","newMods","newDirs","bleedDirDeg","gPool","gPoolLen","g2Pool","g2PoolLen","fv","fm","fd","insertedIdx","mod","cv","nv","mi","di","rotDeg","sideX","sideY","dirX","dirY","nextMod","kept","intensity","texture","int","switchingToFill","setTransform","fillColorBase","strokeStyle","lineCap","fillMatrix","getTransform","darker","sparse","layer","numLayers","erase","restore","colorBase","matrix","lineWidth","beginPath","first","tx","ty","lineTo","closePath","strokePadding","drawPolygon","numCircles","halfSizeX","halfSizeY","minSize","minSizeFactor","maxSizeFactor","midX","midY","globalCompositeOperation","filterPoints","again","steiner","equals","area","removeNode","earcutLinked","ear","triangles","dim","invSize","pass","z","zOrder","prevZ","nextZ","numMerges","inSize","tail","q","pSize","qSize","sortLinked","indexCurve","stop","isEarHashed","isEar","cureLocalIntersections","splitEarcut","ax","bx","pointInTriangleExceptFirst","minZ","maxZ","intersects","locallyInside","isValidDiagonal","splitPolygon","pointInTriangle","intersectsPolygon","inside","middleInside","q1","q2","o1","sign","o2","o3","o4","onSegment","num","createNode","b2","an","bp","insertNode","last","_opacity","_bleed","_wr","fluid","modifiers","_","shift","shifted","pts","sumX","sumY","pt","cross","_center","createFill","FillSetState","washProgram","washVao","washBuffer","washProjection","washGpuBufferSize","WashAttr","WashUniform","transformVertexToScreen","_renderer","hadDepthTest","isEnabled","DEPTH_TEST","bindFramebuffer","FRAMEBUFFER","framebuffer","viewport","resetStandaloneShaderTracking","blendEquation","FUNC_ADD","ONE_MINUS_SRC_ALPHA","previousFramebuffer","getParameter","FRAMEBUFFER_BINDING","previousViewport","VIEWPORT","clearColor","COLOR_BUFFER_BIT","vertSrc","fragSrc","uniformCache","quadVao","loc_source","loc_mask","loc_color","setUniform","location","uniform3f","uniform1f","makeShader","pixelWidth","pixelHeight","createFramebufferTexture","framebufferTexture2D","COLOR_ATTACHMENT0","__brushFramebuffer","deleteFramebuffer","currentFramebuffer","previousProgram","CURRENT_PROGRAM","previousVao","VERTEX_ARRAY_BINDING","TEXTURE1","TRIANGLES","sourceBox","previousReadFramebuffer","READ_FRAMEBUFFER_BINDING","previousDrawFramebuffer","DRAW_FRAMEBUFFER_BINDING","READ_FRAMEBUFFER","DRAW_FRAMEBUFFER","blitFramebuffer","NEAREST","blitDefaultFramebufferSource","cssColor","buildTipSurface","get2DContext","surface","_fillStyle","_strokeStyle","_lineWidth","fillRect","noFill","_paint","ellipse","_shapeStarted","getImageData","imageData","putImageData","resolve","reject","NativeImage","globalThis","Image","nativeImg","onload","naturalWidth","naturalHeight","onerror","crossOrigin","ensureWashReady","vertexCount","flat","holeIndices","outerLen","outerNode","signedArea","linkedList","earcut","buildTriangleBuffer","drawWashPolygon","HTMLCanvasElement","isCanvasTarget","isOffscreenCanvasTarget","isSupportedTarget","initStandaloneRendererRuntime","initStandaloneCompositorRuntime","initStandaloneStrokeRuntime","angleOffset","randomFactor","randomAngle","offsetX","offsetY","DEPTH_BUFFER_BIT","region","logicalWidth","logicalHeight","Number","style","id","parent","querySelector","appendChild","buffer","loadTarget","saved","popState","currentField","theta","cosTheta","sinTheta","callback","_array_points","weights","totalWeight","cumulative","rnd"],"mappings":"6BAIA,MAAMA,EAAiB,CACrBC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,GAGE,ICEIC,EAAQC,EAAmBC,EAAUC,EDFrCC,EAAc,KAAM,EACpBC,EAAeC,GAAUA,EACzBC,EAAc,KACvB,MAAM,IAAIC,MAAM,yCAEPC,EAAkB,IAAMhB,ECD/BiB,EAAgB,CAClBC,KAAM,KACJ,MAAM,IAAIH,MAAM,0CAElBI,YAAa,IAAMT,EACnBU,cAAe,KACb,MAAM,IAAIL,MAAM,0CAElBM,SAAWC,MAGXC,iBAAmBD,MAGnBE,mBAAoB,OACpBC,qBAAsB,IAAM,KAC5BC,oBAAqB,KAAM,GAQtB,SAASC,EAAeC,GACzB,WAAYA,IAAOrB,EAASqB,EAAMrB,QAClC,YAAaqB,IAAOpB,EAAUoB,EAAMpB,SACpC,aAAcoB,GAAkBA,EAAMC,SACtC,aAAcD,IAAOnB,EAAWmB,EAAMnB,UACtC,YAAamB,IAAOlB,EAAUkB,EAAMlB,QAC1C,CAWO,MAEMU,EAAgB,IAAMH,EAAcG,gBAIpCK,EAAuB,IAAMR,EAAcQ,uBAC3CC,EAAuBI,GAClCb,EAAcS,oBAAoBI,GCxDvBC,EAAkB,CAACC,EAAMC,EAAU,IAC9CD,EACI,CACEE,KAAMF,EAAKE,KAAOD,EAClBE,KAAMH,EAAKG,KAAOF,EAClBG,KAAMJ,EAAKI,KAAOH,EAClBI,KAAML,EA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,EAAGI,EACHH,EAAG,EACHC,EAAG,EACHC,EAAGE,EACHD,EAAG,EACHC,EAAG,GAEP,iBUWO,SAAsB8T,GAC3B,IAAK,MAAM6U,MAAEA,KAAW7V,GAAKgf,SACvBnJ,IACFA,EAAMzC,QAAUpS,EAChB6U,EAAM7B,SAAWhT,EACjB6U,EAAM4D,SAAWzY,EAGvB,SblNqB7K,IACnB2C,EAAMxB,EAAUnB,GAChB4C,EAAOzB,EAAU,GAAGnB,OACpB,IAAK,MAAMsiC,KAAYz/B,EACrBy/B,uBKuNG,SAAgBC,EAAevzB,EAAa,IACjD,IAAKuzB,GAAiBA,EAAcpgC,OAAS,EAC3C,MAAM,IAAI3K,MACR,+EAGIyc,GAAcsuB,EAAevzB,GACnC1T,MACJ,4CFlFO,SAAmBxE,EAAGC,GAC3BiW,GAAmBC,GAAkBD,GAAkB,CACrDtW,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,IACAC,KAEJ,sBHtF6ByrC,IAC3B,IAAIC,EAAc,EAClB,MAAMnc,EAAU,GAGhB,IAAK,MAAMxH,KAAO0jB,EAChBC,GAAeD,EAAQ1jB,GACvBwH,EAAQtjB,KAAK,CAAE8b,MAAK4jB,WAAYD,IAIlC,MAAME,EAAMhgC,IAAQ8/B,EAGpB,IAAK,MAAM3jB,IAAEA,EAAG4jB,WAAEA,KAAgBpc,EAChC,GAAIqc,EAAMD,EACR,OAAO39B,MAAM+Z,GAAOA,EAAMpR,SAASoR","x_google_ignoreList":[5,6,26]}
\ No newline at end of file
diff --git a/dist/p5.brush.esm.js b/dist/p5.brush.esm.js
index 502fa81..a8dad7c 100644
--- a/dist/p5.brush.esm.js
+++ b/dist/p5.brush.esm.js
@@ -1,2 +1,2 @@
-const e={a:1,b:0,c:0,d:1,x:0,y:0};let t=()=>!1,r=e=>e,n=()=>{throw new Error("No runtime color adapter registered.")},i=()=>e;const o=Math.sqrt(3),s=.5*(o-1),a=(3-o)/6,c=e=>0|Math.floor(e),l=new Float64Array([1,1,-1,1,1,-1,-1,-1,1,0,-1,0,1,0,-1,0,0,1,0,-1,0,1,0,-1]);function u(e=Math.random){const t=function(e){const t=new Uint8Array(512);for(let e=0;e<256;e++)t[e]=e;for(let r=0;r<255;r++){const n=r+~~(e()*(256-r)),i=t[r];t[r]=t[n],t[n]=i}for(let e=256;e<512;e++)t[e]=t[e-256];return t}(e),r=new Float64Array(t).map(e=>l[e%12*2]),n=new Float64Array(t).map(e=>l[e%12*2+1]);return function(e,i){let o=0,l=0,u=0;const h=(e+i)*s,f=c(e+h),m=c(i+h),d=(f+m)*a,x=e-(f-d),g=i-(m-d);let p,y;x>g?(p=1,y=0):(p=0,y=1);const v=x-p+a,b=g-y+a,_=x-1+2*a,w=g-1+2*a,R=255&f,A=255&m;let E=.5-x*x-g*g;if(E>=0){const e=R+t[A];E*=E,o=E*E*(r[e]*x+n[e]*g)}let M=.5-v*v-b*b;if(M>=0){const e=R+p+t[A+y];M*=M,l=M*M*(r[e]*v+n[e]*b)}let S=.5-_*_-w*w;if(S>=0){const e=R+1+t[A+1];S*=S,u=S*S*(r[e]*_+n[e]*w)}return 70*(o+l+u)}}function h(e,t){let r=new f(e),n=()=>r.next();return n.double=()=>n()+11102230246251565e-32*(2097152*n()|0),n.int32=()=>4294967296*r.next()|0,n.quick=n,n}class f{constructor(e){null==e&&(e=+new Date);let t=4022871197;function r(e){e=String(e);for(let r=0;r<e.length;r++){t+=e.charCodeAt(r);let n=.02519603282416938*t;t=n>>>0,n-=t,n*=t,t=n>>>0,n-=t,t+=4294967296*n}return 2.3283064365386963e-10*(t>>>0)}this.c=1,this.s0=r(" "),this.s1=r(" "),this.s2=r(" "),this.s0-=r(e),this.s0<0&&(this.s0+=1),this.s1-=r(e),this.s1<0&&(this.s1+=1),this.s2-=r(e),this.s2<0&&(this.s2+=1)}next(){let{c:e,s0:t,s1:r,s2:n}=this,i=2091639*t+2.3283064365386963e-10*e;return this.s0=r,this.s1=n,this.s2=i-(this.c=0|i)}copy(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}}let m=h(Math.random()),d=h(Math.random());const x=[],g=e=>x.push(e),p=e=>{m=h(e),d=h(`${e}:2`);for(const e of x)e()};let y=u(h(Math.random())),v=u(h(Math.random()));const b=e=>{y=u(h(e)),v=u(h(`${e}:2`))},_=(e=0,t=1)=>e+m()*(t-e),w=(e=0,t=1)=>e+d()*(t-e),R=e=>e[~~(m()*e.length)],A=(e,t)=>~~_(e,t),E=(e,t)=>~~w(e,t),M=(e=0,t=1)=>{const r=1-m(),n=m();return Math.sqrt(-2*Math.log(r))*D(360*n)*t+e},S=e=>{let t=0;const r=[];for(const n in e)t+=e[n],r.push({key:n,cumulative:t});const n=m()*t;for(const{key:e,cumulative:t}of r)if(n<t)return isNaN(e)?e:parseInt(e)},T=(e,t,r,n,i,o=!1)=>{let s=n+(e-t)/(r-t)*(i-n);return o?n<i?P(s,n,i):P(s,i,n):s},P=(e,t,r)=>Math.max(Math.min(e,r),t),C=e=>(e%=360)<0?e+360:e,k=1440,F=2*Math.PI/k,I=new Float32Array(k).fill(NaN),L=new Float32Array(k).fill(NaN),D=e=>{const t=~~(4*C(e));let r=I[t];return isNaN(r)&&(r=Math.cos(t*F),I[t]=r),r},N=e=>{const t=~~(4*C(e));let r=L[t];return isNaN(r)&&(r=Math.sin(t*F),L[t]=r),r},B=(e,r=!1)=>{if(r||t()){let t=180*e/Math.PI%360;return t<0?t+360:t}return e},Y=(e,r=!1)=>r||t()?180*e/Math.PI:e,z=(e,t,r,n,i)=>{let o=D(i),s=N(i);return{x:o*(r-e)+s*(n-t)+e,y:o*(n-t)-s*(r-e)+t}},O=(e,t,r,n)=>Math.hypot(r-e,n-t),U=(e,t,r,n)=>B(Math.atan2(-(n-t),r-e),!0),X=(e,t,r,n,i=!1)=>{let o=e.x,s=e.y,a=t.x,c=t.y,l=r.x,u=r.y,h=n.x,f=n.y;if(o===a&&s===c||l===h&&u===f)return!1;let m=a-o,d=c-s,x=h-l,g=f-u,p=g*m-x*d;if(0===p)return!1;let y=(x*(s-u)-g*(o-l))/p,v=(m*(s-u)-d*(o-l))/p;return!(!i&&(v<0||v>1))&&{x:o+y*m,y:s+y*d}};let G,Z,V,$,H,W={load:()=>{throw new Error("No target runtime adapter registered.")},syncDensity:()=>H,isCanvasReady:()=>{throw new Error("No target runtime adapter registered.")},instance:e=>{V=e},activateInstance:e=>{V=e},deactivateInstance:()=>{},getActiveFramebuffer:()=>null,isFramebufferTarget:()=>!1};function j(e){"Cwidth"in e&&(G=e.Cwidth),"Cheight"in e&&(Z=e.Cheight),"Instance"in e&&(V=e.Instance),"Renderer"in e&&($=e.Renderer),"Density"in e&&(H=e.Density)}const q=()=>W.isCanvasReady(),K=e=>W.instance(e),J=e=>W.activateInstance(e),Q=()=>W.deactivateInstance(),ee=()=>W.getActiveFramebuffer(),te=e=>W.isFramebufferTarget(e),re=(e,t=0)=>e?{minX:e.minX-t,minY:e.minY-t,maxX:e.maxX+t,maxY:e.maxY+t}:null,ne=(e,t,r=!1)=>{const n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):(()=>{const r=document.createElement("canvas");return r.width=e,r.height=t,r})();return n.drawingContext=n.getContext("2d",r?{willReadFrequently:!0}:void 0),n};let ie={clearTarget:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendShaderProgram:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendSourceFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},createFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},runBlendShaderPass:()=>{throw new Error("No compositor runtime adapter registered.")},blitSourceToFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")}};const oe=(...e)=>ie.createFramebuffer(...e);let se=null,ae=null;const ce=e=>{((...e)=>{ie.clearTarget(...e)})($,e,te)},le=()=>({width:Math.max(1,Math.round(G*H)),height:Math.max(1,Math.round(Z*H))}),ue=e=>{if(!e)return null;const{width:t,height:r}=le();return((e,t,r)=>{if(!e)return null;const n=Math.max(0,Math.floor(Math.min(e.minX,e.maxX))),i=Math.max(0,Math.floor(Math.min(e.minY,e.maxY))),o=Math.min(t,Math.ceil(Math.max(e.minX,e.maxX))),s=Math.min(r,Math.ceil(Math.max(e.minY,e.maxY)));return o<=n||s<=i?null:{minX:n,minY:i,maxX:o,maxY:s}})(e,t,r)},he=()=>{const{width:e,height:t}=le();return((e,t)=>({minX:0,minY:0,maxX:e,maxY:t}))(e,t)},fe=(e,t=!0)=>{const r=ue(e);if(!r)return null;const{height:n}=le();return{x:r.minX,y:t?n-r.maxY:r.minY,width:r.maxX-r.minX,height:r.maxY-r.minY}},me=(e,t,r,n=!0)=>{const i=fe(t,n);if(i){e.enable(e.SCISSOR_TEST),e.scissor(i.x,i.y,i.width,i.height);try{r()}finally{e.disable(e.SCISSOR_TEST)}}else r()},de={},xe=()=>{$?.loaded||(q(),ge.load())},ge={isBlending:!1,cachedColor:null,markDirtyRect(e,t){const r=ue(t);var n,i;e&&r&&(e.dirtyRect=(i=r,(n=e.dirtyRect)?i?{minX:Math.min(n.minX,i.minX),minY:Math.min(n.minY,i.minY),maxX:Math.max(n.maxX,i.maxX),maxY:Math.max(n.maxY,i.maxY)}:n:i),e.isDrawn=!0)},clearMask(e){if(!e)return;const t=e===this.glMask?se:ae;t?.clearMask?.(e,ce)},getCompositeRect(e,t){const r=t?se:ae;return r?.getCompositeRect?.(e,ee,he,re,ue)},load(){W.syncDensity();const e=!$.blendSourceFramebuffer||$.blendSourceFramebuffer.width!==G||$.blendSourceFramebuffer.height!==Z||"function"==typeof $.blendSourceFramebuffer.pixelDensity&&$.blendSourceFramebuffer.pixelDensity()!==H;((...e)=>{ie.ensureBlendShaderProgram(...e)})($,"#version 300 es\n#define GLSLIFY 1\nout vec2 p;void main(){vec3 v=vec3(-1);v[gl_VertexID]=3.;p=v.xy;gl_Position=vec4(v.x,-v.y,0,1);}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nuniform bool u_isBrush;uniform bool u_targetIsFramebuffer;uniform sampler2D u_source;uniform sampler2D u_mask;uniform vec3 u_color;in vec2 p;out vec4 outColor;const int SPECTRAL_SIZE=38;const float SPECTRAL_GAMMA=2.4;const float SPECTRAL_EPSILON=0.0000000000000001;float spectral_uncompand(float x){return(x<0.04045)? x/12.92 : pow((x+0.055)/1.055,SPECTRAL_GAMMA);}float spectral_compand(float x){return(x<0.0031308)? x*12.92 : 1.055*pow(x,1.0/SPECTRAL_GAMMA)-0.055;}vec3 spectral_srgb_to_linear(vec3 srgb){return vec3(spectral_uncompand(srgb[0]),spectral_uncompand(srgb[1]),spectral_uncompand(srgb[2]));}vec3 spectral_linear_to_srgb(vec3 lrgb){return clamp(vec3(spectral_compand(lrgb[0]),spectral_compand(lrgb[1]),spectral_compand(lrgb[2])),0.,1.);}void spectral_linear_to_reflectance(vec3 lrgb,inout float R[SPECTRAL_SIZE]){float w=min(lrgb.r,min(lrgb.g,lrgb.b));lrgb-=w;float c=min(lrgb.g,lrgb.b);float m=min(lrgb.r,lrgb.b);float y=min(lrgb.r,lrgb.g);float r=min(max(0.0,lrgb.r-lrgb.b),max(0.0,lrgb.r-lrgb.g));float g=min(max(0.0,lrgb.g-lrgb.b),max(0.0,lrgb.g-lrgb.r));float b=min(max(0.0,lrgb.b-lrgb.g),max(0.0,lrgb.b-lrgb.r));R[0]=max(SPECTRAL_EPSILON,w*1.0011607271876400+c*0.9705850013229620+m*0.9906735573199880+y*0.0210523371789306+r*0.0315605737777207+g*0.0095560747554212+b*0.9794047525020140);R[1]=max(SPECTRAL_EPSILON,w*1.0011606515972800+c*0.9705924981434250+m*0.9906715249619790+y*0.0210564627517414+r*0.0315520718330149+g*0.0095581580120851+b*0.9794007068431300);R[2]=max(SPECTRAL_EPSILON,w*1.0011603192274700+c*0.9706253487298910+m*0.9906625823534210+y*0.0210746178695038+r*0.0315148215513658+g*0.0095673245444588+b*0.9793829034702610);R[3]=max(SPECTRAL_EPSILON,w*1.0011586727078900+c*0.9707868061190170+m*0.9906181076447950+y*0.0211649058448753+r*0.0313318044982702+g*0.0096129126297349+b*0.9792943649455940);R[4]=max(SPECTRAL_EPSILON,w*1.0011525984455200+c*0.9713686732282480+m*0.9904514808787100+y*0.0215027957272504+r*0.0306729857725527+g*0.0097837090401843+b*0.9789630146085700);R[5]=max(SPECTRAL_EPSILON,w*1.0011325252899800+c*0.9731632306212520+m*0.9898710814002040+y*0.0226738799041561+r*0.0286480476989607+g*0.0103786227058710+b*0.9778144666940430);R[6]=max(SPECTRAL_EPSILON,w*1.0010850066332700+c*0.9767402231587650+m*0.9882866087596400+y*0.0258235649693629+r*0.0246450407045709+g*0.0120026452378567+b*0.9747243211338360);R[7]=max(SPECTRAL_EPSILON,w*1.0009968788945300+c*0.9815876054913770+m*0.9842906927975040+y*0.0334879385639851+r*0.0192960753663651+g*0.0160977721473922+b*0.9671984823439730);R[8]=max(SPECTRAL_EPSILON,w*1.0008652515227400+c*0.9862802656529490+m*0.9739349056253060+y*0.0519069663740307+r*0.0142066612220556+g*0.0267061902231680+b*0.9490796575305750);R[9]=max(SPECTRAL_EPSILON,w*1.0006962900094000+c*0.9899491476891340+m*0.9418178384601450+y*0.1007490148334730+r*0.0102942608878609+g*0.0595555440185881+b*0.9008501289409770);R[10]=max(SPECTRAL_EPSILON,w*1.0005049611488800+c*0.9924927015384200+m*0.8173903261951560+y*0.2391298997068470+r*0.0076191460521811+g*0.1860398265328260+b*0.7631504454622400);R[11]=max(SPECTRAL_EPSILON,w*1.0003080818799200+c*0.9941456804052560+m*0.4324728050657290+y*0.5348043122727480+r*0.0058980410835420+g*0.5705798201161590+b*0.4659221716493190);R[12]=max(SPECTRAL_EPSILON,w*1.0001196660201300+c*0.9951839750332120+m*0.1384539782588700+y*0.7978075786430300+r*0.0048233247781713+g*0.8614677684002920+b*0.2012632804510050);R[13]=max(SPECTRAL_EPSILON,w*0.9999527659684070+c*0.9957567501108180+m*0.0537347216940033+y*0.9114498940673840+r*0.0042298748350633+g*0.9458790897676580+b*0.0877524413419623);R[14]=max(SPECTRAL_EPSILON,w*0.9998218368992970+c*0.9959128182867100+m*0.0292174996673231+y*0.9537979630045070+r*0.0040599171299341+g*0.9704654864743050+b*0.0457176793291679);R[15]=max(SPECTRAL_EPSILON,w*0.9997386095575930+c*0.9956061578345280+m*0.0213136517508590+y*0.9712416154654290+r*0.0043533695594676+g*0.9784136302844500+b*0.0284706050521843);R[16]=max(SPECTRAL_EPSILON,w*0.9997095516396120+c*0.9945976009618540+m*0.0201349530181136+y*0.9793031238075880+r*0.0053434425970201+g*0.9795890314112240+b*0.0205271767569850);R[17]=max(SPECTRAL_EPSILON,w*0.9997319302106270+c*0.9922157154923700+m*0.0241323096280662+y*0.9833801195075750+r*0.0076917201010463+g*0.9755335369086320+b*0.0165302792310211);R[18]=max(SPECTRAL_EPSILON,w*0.9997994363461950+c*0.9862364527832490+m*0.0372236145223627+y*0.9854612465677550+r*0.0135969795736536+g*0.9622887553978130+b*0.0145135107212858);R[19]=max(SPECTRAL_EPSILON,w*0.9999003303166710+c*0.9679433372645410+m*0.0760506552706601+y*0.9864350469766050+r*0.0316975442661115+g*0.9231215745131200+b*0.0136003508637687);R[20]=max(SPECTRAL_EPSILON,w*1.0000204065261100+c*0.8912850042449430+m*0.2053754719423990+y*0.9867382506701410+r*0.1078611963552490+g*0.7934340189431110+b*0.0133604258769571);R[21]=max(SPECTRAL_EPSILON,w*1.0001447879365800+c*0.5362024778620530+m*0.5412689034604390+y*0.9866178824450320+r*0.4638126031687040+g*0.4592701359024290+b*0.0135488943145680);R[22]=max(SPECTRAL_EPSILON,w*1.0002599790341200+c*0.1541081190018780+m*0.8158416850864860+y*0.9862777767586430+r*0.8470554052720110+g*0.1855741036663030+b*0.0139594356366992);R[23]=max(SPECTRAL_EPSILON,w*1.0003557969708900+c*0.0574575093228929+m*0.9128177041239760+y*0.9858605924440560+r*0.9431854093939180+g*0.0881774959955372+b*0.0144434255753570);R[24]=max(SPECTRAL_EPSILON,w*1.0004275378026900+c*0.0315349873107007+m*0.9463398301669620+y*0.9854749276762100+r*0.9688621506965580+g*0.0543630228766700+b*0.0148854440621406);R[25]=max(SPECTRAL_EPSILON,w*1.0004762334488800+c*0.0222633920086335+m*0.9599276963319910+y*0.9851769347655580+r*0.9780306674736030+g*0.0406288447060719+b*0.0152254296999746);R[26]=max(SPECTRAL_EPSILON,w*1.0005072096750800+c*0.0182022841492439+m*0.9662605952303120+y*0.9849715740141810+r*0.9820436438543060+g*0.0342215204316970+b*0.0154592848180209);R[27]=max(SPECTRAL_EPSILON,w*1.0005251915637300+c*0.0162990559732640+m*0.9693259700584240+y*0.9848463034157120+r*0.9839236237187070+g*0.0311185790956966+b*0.0156018026485961);R[28]=max(SPECTRAL_EPSILON,w*1.0005350960689600+c*0.0153656239334613+m*0.9708545367213990+y*0.9847753518111990+r*0.9848454841543820+g*0.0295708898336134+b*0.0156824871281936);R[29]=max(SPECTRAL_EPSILON,w*1.0005402209748200+c*0.0149111568733976+m*0.9716050665281280+y*0.9847380666252650+r*0.9852942758145960+g*0.0288108739348928+b*0.0157248764360615);R[30]=max(SPECTRAL_EPSILON,w*1.0005427281678400+c*0.0146954339898235+m*0.9719627697573920+y*0.9847196483117650+r*0.9855072952198250+g*0.0284486271324597+b*0.0157458108784121);R[31]=max(SPECTRAL_EPSILON,w*1.0005438956908700+c*0.0145964146717719+m*0.9721272722745090+y*0.9847110233919390+r*0.9856050715398370+g*0.0282820301724731+b*0.0157556123350225);R[32]=max(SPECTRAL_EPSILON,w*1.0005444821215100+c*0.0145470156699655+m*0.9722094177458120+y*0.9847066833006760+r*0.9856538499335780+g*0.0281988376490237+b*0.0157605443964911);R[33]=max(SPECTRAL_EPSILON,w*1.0005447695999200+c*0.0145228771899495+m*0.9722495776784240+y*0.9847045543930910+r*0.9856776850338830+g*0.0281581655342037+b*0.0157629637515278);R[34]=max(SPECTRAL_EPSILON,w*1.0005448988776200+c*0.0145120341118965+m*0.9722676219987420+y*0.9847035963093700+r*0.9856883918061220+g*0.0281398910216386+b*0.0157640525629106);R[35]=max(SPECTRAL_EPSILON,w*1.0005449625468900+c*0.0145066940939832+m*0.9722765094621500+y*0.9847031240775520+r*0.9856936646900310+g*0.0281308901665811+b*0.0157645892329510);R[36]=max(SPECTRAL_EPSILON,w*1.0005449892705800+c*0.0145044507314479+m*0.9722802433068740+y*0.9847029256150900+r*0.9856958798482050+g*0.0281271086805816+b*0.0157648147772649);R[37]=max(SPECTRAL_EPSILON,w*1.0005449969930000+c*0.0145038009464639+m*0.9722813248265600+y*0.9847028681227950+r*0.9856965214637620+g*0.0281260133612096+b*0.0157648801149616);}vec3 spectral_xyz_to_srgb(vec3 xyz){mat3 XYZ_RGB;XYZ_RGB[0]=vec3(3.2409699419045200,-1.537383177570090,-0.4986107602930030);XYZ_RGB[1]=vec3(-0.9692436362808790,1.875967501507720,0.0415550574071756);XYZ_RGB[2]=vec3(0.0556300796969936,-0.203976958888976,1.0569715142428700);float r=dot(XYZ_RGB[0],xyz);float g=dot(XYZ_RGB[1],xyz);float b=dot(XYZ_RGB[2],xyz);return spectral_linear_to_srgb(vec3(r,g,b));}vec3 spectral_reflectance_to_xyz(float R[SPECTRAL_SIZE]){vec3 xyz=vec3(0.);xyz+=R[0]*vec3(0.0000646919989576,0.0000018442894440,0.0003050171476380);xyz+=R[1]*vec3(0.0002194098998132,0.0000062053235865,0.0010368066663574);xyz+=R[2]*vec3(0.0011205743509343,0.0000310096046799,0.0053131363323992);xyz+=R[3]*vec3(0.0037666134117111,0.0001047483849269,0.0179543925899536);xyz+=R[4]*vec3(0.0118805536037990,0.0003536405299538,0.0570775815345485);xyz+=R[5]*vec3(0.0232864424191771,0.0009514714056444,0.1136516189362870);xyz+=R[6]*vec3(0.0345594181969747,0.0022822631748318,0.1733587261835500);xyz+=R[7]*vec3(0.0372237901162006,0.0042073290434730,0.1962065755586570);xyz+=R[8]*vec3(0.0324183761091486,0.0066887983719014,0.1860823707062960);xyz+=R[9]*vec3(0.0212332056093810,0.0098883960193565,0.1399504753832070);xyz+=R[10]*vec3(0.0104909907685421,0.0152494514496311,0.0891745294268649);xyz+=R[11]*vec3(0.0032958375797931,0.0214183109449723,0.0478962113517075);xyz+=R[12]*vec3(0.0005070351633801,0.0334229301575068,0.0281456253957952);xyz+=R[13]*vec3(0.0009486742057141,0.0513100134918512,0.0161376622950514);xyz+=R[14]*vec3(0.0062737180998318,0.0704020839399490,0.0077591019215214);xyz+=R[15]*vec3(0.0168646241897775,0.0878387072603517,0.0042961483736618);xyz+=R[16]*vec3(0.0286896490259810,0.0942490536184085,0.0020055092122156);xyz+=R[17]*vec3(0.0426748124691731,0.0979566702718931,0.0008614711098802);xyz+=R[18]*vec3(0.0562547481311377,0.0941521856862608,0.0003690387177652);xyz+=R[19]*vec3(0.0694703972677158,0.0867810237486753,0.0001914287288574);xyz+=R[20]*vec3(0.0830531516998291,0.0788565338632013,0.0001495555858975);xyz+=R[21]*vec3(0.0861260963002257,0.0635267026203555,0.0000923109285104);xyz+=R[22]*vec3(0.0904661376847769,0.0537414167568200,0.0000681349182337);xyz+=R[23]*vec3(0.0850038650591277,0.0426460643574120,0.0000288263655696);xyz+=R[24]*vec3(0.0709066691074488,0.0316173492792708,0.0000157671820553);xyz+=R[25]*vec3(0.0506288916373645,0.0208852059213910,0.0000039406041027);xyz+=R[26]*vec3(0.0354739618852640,0.0138601101360152,0.0000015840125870);xyz+=R[27]*vec3(0.0214682102597065,0.0081026402038399,0.0000000000000000);xyz+=R[28]*vec3(0.0125164567619117,0.0046301022588030,0.0000000000000000);xyz+=R[29]*vec3(0.0068045816390165,0.0024913800051319,0.0000000000000000);xyz+=R[30]*vec3(0.0034645657946526,0.0012593033677378,0.0000000000000000);xyz+=R[31]*vec3(0.0014976097506959,0.0005416465221680,0.0000000000000000);xyz+=R[32]*vec3(0.0007697004809280,0.0002779528920067,0.0000000000000000);xyz+=R[33]*vec3(0.0004073680581315,0.0001471080673854,0.0000000000000000);xyz+=R[34]*vec3(0.0001690104031614,0.0000610327472927,0.0000000000000000);xyz+=R[35]*vec3(0.0000952245150365,0.0000343873229523,0.0000000000000000);xyz+=R[36]*vec3(0.0000490309872958,0.0000177059860053,0.0000000000000000);xyz+=R[37]*vec3(0.0000199961492222,0.0000072209749130,0.0000000000000000);return xyz;}float KS(float R){return pow(1.0-R,2.0)/(2.0*R);}float KM(float KS){return 1.0+KS-sqrt(pow(KS,2.0)+2.0*KS);}vec3 spectral_mix(vec3 color1,float tintingStrength1,float factor1,vec3 color2,float tintingStrength2,float factor2){vec3 lrgb1=spectral_srgb_to_linear(color1);vec3 lrgb2=spectral_srgb_to_linear(color2);float R1[SPECTRAL_SIZE];float R2[SPECTRAL_SIZE];spectral_linear_to_reflectance(lrgb1,R1);spectral_linear_to_reflectance(lrgb2,R2);float luminance1=spectral_reflectance_to_xyz(R1)[1];float luminance2=spectral_reflectance_to_xyz(R2)[1];float R[SPECTRAL_SIZE];for(int i=0;i<SPECTRAL_SIZE;i++){float concentration1=pow(factor1,2.)*pow(tintingStrength1,2.)*luminance1;float concentration2=pow(factor2,2.)*pow(tintingStrength2,2.)*luminance2;float totalConcentration=concentration1+concentration2;float ksMix=0.;ksMix+=KS(R1[i])*concentration1;ksMix+=KS(R2[i])*concentration2;R[i]=KM(ksMix/totalConcentration);}return spectral_xyz_to_srgb(spectral_reflectance_to_xyz(R));}vec3 spectral_mix(vec3 color1,vec3 color2,float factor){return spectral_mix(color1,1.,1.-factor,color2,1.,factor);}vec3 spectral_mix(vec3 color1,float factor1,vec3 color2,float factor2){return spectral_mix(color1,1.,factor1,color2,1.,factor2);}const float GAMMA=2.4,EPSILON=0.0001;const float DARKEN_THRESHOLD=0.7;const float EDGE_MIN=0.05,EDGE_MAX=0.35;void main(void){vec2 uv=0.5*p+0.5;vec2 sourceUV=vec2(uv.x,1.0-uv.y);vec2 maskUV=u_targetIsFramebuffer ? vec2(uv.x,1.0-uv.y): uv;vec4 source=texture(u_source,sourceUV);vec4 maskColor=texture(u_mask,maskUV);if(maskColor.a==0.0){outColor=source;return;}vec4 pigment=vec4(u_color.xyz,1.0);if(maskColor.a>DARKEN_THRESHOLD){float blacken=0.5*(min(maskColor.a,1.0)-DARKEN_THRESHOLD);pigment=pigment*(1.0-blacken)-vec4(0.5)*blacken;pigment.rgb=max(pigment.rgb,vec3(0.0));}float mixIntensity=min(maskColor.a,1.0);if(!u_isBrush){vec2 texelSize=1.0/vec2(textureSize(u_mask,0));float scaledAlpha=maskColor.a*15.0;float blurEdge=0.0;for(int i=-2;i<=2;i+=2){for(int j=-2;j<=2;j+=2){vec2 neighborUV=maskUV+vec2(float(i),float(j))*texelSize;float neighborAlpha=texture(u_mask,neighborUV).a*15.0;blurEdge+=smoothstep(EDGE_MIN,EDGE_MAX,length(vec2(dFdx(neighborAlpha),dFdy(neighborAlpha))));}}blurEdge/=9.0;mixIntensity=clamp(maskColor.a+blurEdge*0.1,0.0,1.0);}vec3 bgColor=mix(vec3(1.0),source.rgb,source.a);outColor=vec4(spectral_mix(bgColor,pigment.rgb,mixIntensity),1.);}"),this.glMask=se?.ensureResources?.($,G,Z,H);const t=ae?.ensureResources?.($,G,Z,H,ce)??{mask:null,ctx:null};e&&($.blendSourceFramebuffer=((...e)=>ie.ensureBlendSourceFramebuffer(...e))($,$.blendSourceFramebuffer,G,Z,H)),this.mask=t.mask,this.ctx=t.ctx},blend(e=!1,t=!1){xe();const r=!0===this.isBrush,n=r?this.glMask:this.mask,i=r?this.mask:this.glMask,o=e?._array,s=!!o&&(this.cachedColor?.[0]!==o[0]||this.cachedColor?.[1]!==o[1]||this.cachedColor?.[2]!==o[2]||this.cachedColor?.[3]!==o[3]);!this.isBlending&&o&&(this.isBlending=!0,this.cachedColor=o,this.clearMask(this.glMask)),(t||s)&&(this.justChanged&&(this.applyShader(i,!r),this.justChanged=!1),this.isBlending&&this.applyShader(n,r),o&&(this.cachedColor=o),t&&(this.isBlending=!1,this.cachedColor=null))},applyShader(e,t){if(!e?.isDrawn)return;const r=this.getCompositeRect(e,t);if(!r)return void this.clearMask(e);$.drawingContext;const n=$.shaderProgram,i=ee(),o=((...e)=>ie.blitSourceToFramebuffer(...e))({renderer:$,sourceTarget:i??$,sourceFramebuffer:$.blendSourceFramebuffer,dirtyRect:r,isFramebufferTarget:te,Cwidth:G,Cheight:Z,getTargetPixelSize:le,toScissorBox:fe,withScissor:me}),s=!!i,a=(t?se:ae).getShaderMask($,e,r,ue,he,ce);((...e)=>{ie.runBlendShaderPass(...e)})({renderer:$,shader:n,source:o,mask:a,color:this.cachedColor,isBrushMask:t,Cwidth:G,Cheight:Z,dirtyRect:r,targetIsFramebuffer:s,withScissor:me}),this.clearMask(e)}},pe=()=>{xe(),ge.blend(!1,!0),ge.clearMask(ge.glMask),ge.clearMask(ge.mask),ge.justChanged=!1,ge.isBlending=!1,ge.isBrush=null,ge.cachedColor=null},ye=(e=!1)=>{((e=!1)=>{W.load(e)})(e),$.loaded&&ge.load()};let ve=!1;function be(){ve||(xe(),we=.01*G,Re=-.5*G,Ae=-.5*Z,Ee=Math.round(2*G/we),Me=Math.round(2*Z/we),Le("hand",(e,t)=>{const r=w(.2,.8),n=E(5,10);return Be(t,(t,i)=>.5*n*N(r*i*t+E(15,25))*.2*D(e)+v(t,i)*n*.7)}),Le("curved",(e,t)=>{let r=E(-10,10);return E(0,100)%2==0&&(r*=-1),Be(t,(t,n)=>3*T(v(.02*t+.03*e,.02*n+.03*e),0,1,-r,r))}),Le("zigzag",(e,t)=>{let r=E(-30,-15)+Math.abs(44*N(e));E(0,100)%2==0&&(r*=-1);let n=r,i=0;for(let e=0;e<Ee;e++){for(let r=0;r<Me;r++)t[e][r]=i,i+=n,n*=-1;i+=n,n*=-1}return t}),Le("waves",(e,t)=>{const r=E(10,15)+5*N(e),n=E(3,6)+3*D(e),i=E(20,35);return Be(t,(e,t)=>N(r*e)*i*D(t*n)+E(-3,3))}),Le("seabed",(e,t)=>{const r=w(.4,.8),n=E(18,26);return Be(t,(t,i)=>1.1*n*N(r*i*t+E(15,20))*D(e))}),Le("spiral",(e,t)=>{const r=E(5,10),n=2*E(0,2)-1,i=E(65,80),o=Array.from({length:r},()=>({x:w(.1,.9)*Ee,y:w(.1,.9)*Me}));return Be(t,(e,t)=>{let r=0,s=0;for(const a of o){const o=e-a.x,c=t-a.y,l=1/(o*o+c*c+1),u=Math.atan2(c,o)*(180/Math.PI),h=n*(u+i)*Math.PI/180;r+=l*Math.cos(h),s+=l*Math.sin(h)}return Math.atan2(s,r)*(180/Math.PI)})}),Le("columns",(e,t)=>{const r=E(3,8),n=E(25,45);return Be(t,(e,t)=>N(e*r)*n)}),ve=!0)}class _e{constructor(e,t){be();const r=i();this.mx=r.x,this.my=r.y,this.update(e,t),this.plotted=0}update(e,t){this.x=e,this.y=t,this.colIdx=Math.round((e+this.mx-Re)/we),this.rowIdx=Math.round((t+this.my-Ae)/we)}reset(){this.plotted=0}isIn(){return de.field.isActive?_e.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const e=G,t=Z,r=this.x+this.mx,n=this.y+this.my;return r>=-.3*e&&r<=1.3*e&&n>=-.3*t&&n<=1.3*t}angle(e=!1){return de.field.isActive&&(e||this.isIn())?Se.get(de.field.current).field[this.colIdx][this.rowIdx]*de.field.wiggle:0}moveTo(e,t,r=1){this.movePos(Y(e),t,r)}_moveToDegrees(e,t,r=1){this.movePos(e,t,r)}plotTo(e,t,r,n=1){this.movePos(e,t,r,n)}movePos(e,t,r,n=!1){const i=n||1;if(!this.isIn())return void(this.plotted+=r/i);const o=t/r,s=de.field.isActive,a=!!n;for(let t=0;t<o;t++){const t=(s?this.angle(!0):0)-(a?e.angle(this.plotted):e);this.update(this.x+r*D(t),this.y+r*N(t)),this.plotted+=r/i}}static getRowIndex(e,t=1){const r=e+i().y-Ae;return Math.round(r/we/t)}static getColIndex(e,t=1){const r=e+i().x-Re;return Math.round(r/we/t)}static isIn(e,t){return e>=0&&t>=0&&e<Ee&&t<Me}}de.field={isActive:!1,current:null,wiggle:1};let we,Re,Ae,Ee,Me,Se=new Map;const Te=new Set(["degrees","radians"]);function Pe(e={}){const t=("string"==typeof e?{angleMode:e}:e||{}).angleMode??"degrees";if(!Te.has(t))throw new Error(`Invalid field angle mode "${t}". Use "degrees" or "radians".`);return t}function Ce(e,t){return function(e,t){if("radians"!==t)return e;for(let t=0;t<e.length;t++)for(let r=0;r<e[t].length;r++)e[t][r]=Y(e[t][r],!0);return e}(e.gen(t,new Array(Ee).fill(null).map(()=>new Float32Array(Me))),e.angleMode)}function ke(e=0){if(!de.field.isActive||!de.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const t=Se.get(de.field.current);t.field=Ce(t,e)}function Fe(e){if(de.field.wiggle||(de.field.wiggle=1),be(),!Se.has(e))throw new Error(`Field "${e}" does not exist. Available fields: ${Array.from(Se.keys()).join(", ")}.`);de.field.isActive=!0,de.field.current=e;const t=Se.get(e);t.field||(t.field=Ce(t,0))}function Ie(){be(),de.field.isActive=!1}function Le(e,t,r={}){Se.set(e,{gen:t,field:null,angleMode:Pe(r)})}function De(){return be(),Array.from(Se.keys())}function Ne(e=1){Fe("hand"),de.field.wiggle=e}function Be(e,t){for(let r=0;r<Ee;r++)for(let n=0;n<Me;n++)e[r][n]=t(r,n);return e}class Ye{constructor(e,t=!1){this.a=e,this.vertices=t?e:e.map(([e,t])=>({x:e,y:t})),this.sides=this.vertices.map((e,t,r)=>[e,r[(t+1)%r.length]]),this._intersectionCache={}}intersect(e){const t=`${e.point1.x},${e.point1.y}-${e.point2.x},${e.point2.y}`;if(this._intersectionCache[t])return this._intersectionCache[t];const r=[];for(const[t,n]of this.sides){const i=X(e.point1,e.point2,t,n);i&&r.push(i)}return this._intersectionCache[t]=r,r}show(){de.wash&&this.wash(),de.fill&&this.fill(),de.mass&&this.mass(),de.hatch&&this.hatch(),de.stroke&&this.draw()}}class ze{constructor(e){this.segments=[],this.angles=[],this.pres=[],this.type=e,this.dir=0,this.calcIndex(0),this.pol=!1}addSegment(e=0,t=0,r=1,n=!1){this.angles.length>0&&this.angles.pop(),e=n?(e%360+360)%360:B(e),this.angles.push(e,e),this.pres.push(r),this.segments.push(t),this.length=this.segments.reduce((e,t)=>e+t,0)}endPlot(e=0,t=1,r=!1){e=r?(e%360+360)%360:B(e),this.angles[this.angles.length-1]=e,this.pres.push(t)}rotate(e){this.dir=B(e)}pressure(e){return e>this.length?this.pres[this.pres.length-1]:this.curving(this.pres,e)}angle(e){return e>this.length?this.angles[this.angles.length-1]:(this.calcIndex(e),"curve"===this.type?this.curving(this.angles,e)+this.dir:this.angles[this.index]+this.dir)}curving(e,t){let r=e[this.index],n=e[this.index+1]??r;return Math.abs(n-r)>180&&(n>r?n=-(360-n):r=-(360-r)),T(t-this.suma,0,this.segments[this.index],r,n,!0)}calcIndex(e){this.index=-1,this.suma=0;let t=0;for(;t<=e;)this.suma=t,t+=this.segments[this.index+1],this.index++;return this.index}genPol(e,t,r=1,n){be();const i=n<0?4:1,o=[],s=Math.round(this.length/i),a=new _e(e+G/2,t+Z/2);let c=0,l=0;for(let e=0;e<s;e++){a.plotTo(this,i,i);const e=this.calcIndex(a.plotted);c+=i,(c>=(n<=0?8:Math.max(this.segments[e]*n*w(.7,1.3),20))||e>=l)&&a.x&&(o.push([a.x-G/2,a.y-Z/2]),c=0,e>=l&&l++)}return new Ye(o)}show(e,t,r=1){de.wash&&this.wash(e,t,r),de.fill&&this.fill(e,t,r),de.mass&&this.mass(e,t,r),de.hatch&&this.hatch(e,t,r),de.stroke&&this.draw(e,t,r)}}function Oe(e){new Ye(e).show()}function Ue(e,t,r,n,i="corner"){"center"===i&&(e-=r/2,t-=n/2),je(0),qe(e,t),qe(e+r,t),qe(e+r,t+n),qe(e,t+n),Ke(!0)}function Xe(e,t,r,n=!1){const i=new ze("curve"),o=Math.PI*r,s=w(0,360),a=n?()=>1+.2*n*w():()=>1;for(let e=0;e<4;e++){const t=-90*e+s;i.addSegment(t*a(),o/2*a(),1,!0)}if(n){const e=n*E(-5,5);i.addSegment(s,Math.abs(e)*(Math.PI/180)*r,1,!0),i.endPlot(e+s,1,!0)}else i.endPlot(s,1,!0);const c=e-r*N(s),l=t-r*D(-s);i.show(c,l,1)}function Ge(e,t,r,n,i){const o=Y(n),s=((Y(i)-o)%360+360)%360;if(0===s)return;const a=new ze("curve"),c=Math.max(1,Math.ceil(s/90)),l=s/c,u=Math.PI*r*l/180;for(let e=0;e<c;e++)a.addSegment(o+e*l+90,u,1,!0);a.endPlot(o+s+90,1,!0);const h=e+r*D(o),f=t-r*N(o);a.draw(h,f,1)}let Ze,Ve,$e,He;class We{constructor(){this.isClosed=!1,this.curvature=Ve,this.vert=[]}vertex(e,t,r){this.vert.push([e,t,r])}show(){rt(this.vert,this.curvature,this.isClosed).show()}}function je(e=0){Ve=P(e,0,1),Ze=new We}function qe(e,t,r=1){if(!Ze)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");Ze.vertex(e,t,r)}function Ke(e=!1){if(!Ze)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(Ze.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");e&&(Ze.vertex(...Ze.vert[0]),Ze.isClosed=!0),Ze.show(),Ze=!1}function Je(e,t,r){if("curve"!==e&&"segments"!==e)throw new Error(`beginStroke() type must be "curve" or "segments", got "${e}".`);He=[t,r],$e=new ze(e)}function Qe(e,t,r){if(!$e)throw new Error("move() called without beginStroke(). Call beginStroke() first.");$e.addSegment(e,t,r)}function et(e,t){if(!$e)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");$e.endPlot(e,t),$e.draw(He[0],He[1],1),$e=!1}function tt(e,t=.5){if(!e||e.length<2)throw new Error("spline() requires at least 2 points. Each point should be [x, y, pressure].");rt(e,t).draw()}function rt(e,t=.5,r=!1){const n=new ze(0===t?"segments":"curve"),i=2*Math.PI;if(r&&0!==t&&e.push(e[1]),e&&e.length>0){let o,s,a,c=0;for(let l=0;l<e.length-1;l++)if(t>0&&l<e.length-2){const u=e[l],h=e[l+1],f=e[l+2],m=O(u[0],u[1],h[0],h[1]),d=O(h[0],h[1],f[0],f[1]),x=U(u[0],u[1],h[0],h[1]),g=U(h[0],h[1],f[0],f[1]),p=t*Math.min(m,d,.5*Math.min(m,d)),y=Math.max(m,d),v=m-p,b=d-p;if(Math.floor(x)===Math.floor(g)){const t=r&&0===l?0:m-c,i=r?0===l?0:d-a:d;n.addSegment(x,t,u[2],!0),l===e.length-3&&n.addSegment(g,i,h[2],!0),c=0,0===l&&(o=m,a=p,s=e[1],c=0)}else{const t={x:h[0]-p*D(-x),y:h[1]-p*N(-x)},f={x:t.x+y*D(90-x),y:t.y+y*N(90-x)},m={x:h[0]+p*D(-g),y:h[1]+p*N(-g)},d={x:m.x+y*D(90-g),y:m.y+y*N(90-g)},_=X(t,f,m,d,!0),w=O(t.x,t.y,_.x,_.y),R=O(t.x,t.y,m.x,m.y)/2,A=i*w*(2*Math.asin(R/w)*(180/Math.PI))/360,E=r&&0===l?0:v-c,M=l===e.length-3?r?o-p:b:0;n.addSegment(x,E,u[2],!0),n.addSegment(x,isNaN(A)?0:A,u[2],!0),n.addSegment(g,M,h[2],!0),c=p,0===l&&(o=v,a=p,s=[t.x,t.y])}l===e.length-3&&n.endPlot(g,h[2],!0)}else if(0===t){const t=e[l],r=e[l+1],i=O(t[0],t[1],r[0],r[1]),o=U(t[0],t[1],r[0],r[1]);n.addSegment(o,i,r[2],!0),l===e.length-2&&n.endPlot(o,1,!0)}n.origin=r&&0!==t?s:e[0]}return n}let nt={createTipSurface:()=>{throw new Error("No stroke runtime adapter registered.")},loadImageTip:()=>{throw new Error("No stroke runtime adapter registered.")}},it=!1;const ot=(e,t,r)=>{const n=e.createProgram();for(let[i,o]of[[e.VERTEX_SHADER,t],[e.FRAGMENT_SHADER,r]]){const t=e.createShader(i);e.shaderSource(t,o),e.compileShader(t),e.attachShader(n,t)}return e.linkProgram(n),n};let st={beginDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},endDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},resetDirectShaderTracking:()=>{}};const at=(e,t)=>st.resetDirectShaderTracking(e,t);let ct,lt,ut,ht,ft,mt=!1,dt=0,xt=0,gt=null;const pt={},yt={};let vt=1,bt=0,_t=0,wt=1,Rt=0,At=0,Et=0,Mt=0,St=1,Tt=1,Pt=new Float32Array(8192),Ct=0,kt=2048,Ft=32768,It=null,Lt=null,Dt=null,Nt=null,Bt=null;const Yt={},zt={};let Ot=0,Ut=new Float32Array(1280),Xt=0,Gt=256,Zt=null;const Vt=new Map,$t=new Float32Array([-1,-1,1,-1,-1,1,1,1]);function Ht(){return lt}function Wt(){return((e,t,r)=>st.beginDirectMaskDraw(e,t,r))($,ct,ge.glMask)}function jt(e){((e,t,r)=>{st.endDirectMaskDraw(e,t,r)})($,ct,e)}function qt(e,t,r,n,i){return e?(t<e.minX&&(e.minX=t),r<e.minY&&(e.minY=r),n>e.maxX&&(e.maxX=n),i>e.maxY&&(e.maxY=i),e):{minX:t,minY:r,maxX:n,maxY:i}}function Kt(e,t,r,n){if(Ct>=kt){kt*=2;const e=new Float32Array(4*kt);e.set(Pt),Pt=e}const i=e-Et,o=t-Mt,s=4*Ct,a=vt*i+_t*o+Rt+Et,c=bt*i+wt*o+At+Mt,l=Tt*r*St/2;Pt[s]=a,Pt[s+1]=c,Pt[s+2]=l,Pt[s+3]=n/255;const u=a*Tt,h=c*Tt;It=qt(It,u-l-1,h-l-1,u+l+1,h+l+1),Ct++}function Jt(e,t){if(0===Xt)return;ge.glMask.isDrawn=!0;const r=Wt();let n=Vt.get(t);n||(n=ct.createTexture(),ct.bindTexture(ct.TEXTURE_2D,n),ct.texImage2D(ct.TEXTURE_2D,0,ct.RGBA,ct.RGBA,ct.UNSIGNED_BYTE,e.canvas),ct.texParameteri(ct.TEXTURE_2D,ct.TEXTURE_MIN_FILTER,ct.LINEAR),ct.texParameteri(ct.TEXTURE_2D,ct.TEXTURE_MAG_FILTER,ct.LINEAR),ct.texParameteri(ct.TEXTURE_2D,ct.TEXTURE_WRAP_S,ct.CLAMP_TO_EDGE),ct.texParameteri(ct.TEXTURE_2D,ct.TEXTURE_WRAP_T,ct.CLAMP_TO_EDGE),Vt.set(t,n)),ct.useProgram(Lt),ct.enable(ct.BLEND),ct.blendFunc(ct.ONE_MINUS_DST_ALPHA,ct.ONE),ct.activeTexture(ct.TEXTURE0),ct.bindTexture(ct.TEXTURE_2D,n),ct.uniform1i(zt.u_tex,0);const i=de.stroke.color._array;ct.uniform4f(zt.u_color,...i),ct.uniformMatrix4fv(zt.u_proj,!1,Ht()),ct.bindVertexArray(Dt),ct.bindBuffer(ct.ARRAY_BUFFER,Bt);const o=5*Xt*4,s=Ut.subarray(0,5*Xt);o>Ot?(ct.bufferData(ct.ARRAY_BUFFER,Ut,ct.DYNAMIC_DRAW),Ot=Ut.byteLength):ct.bufferSubData(ct.ARRAY_BUFFER,0,s),ct.drawArraysInstanced(ct.TRIANGLE_STRIP,0,4,Xt),ct.flush(),ct.bindVertexArray(null),ct.bindTexture(ct.TEXTURE_2D,null),jt(r),Zt&&(ge.markDirtyRect(ge.glMask,Zt),Zt=null),Xt=0,at($,ct)}it||(se={ensureResources:function(e,t,r,n){return function(e,t,r,n){return!e.glMask||e.glMask.width!==t||e.glMask.height!==r||"function"==typeof e.glMask.pixelDensity&&e.glMask.pixelDensity()!==n}(e,t,r,n)&&(e.glMask?.remove&&e.glMask.remove(),e.glMask=oe(e,{width:t,height:r,density:n,antialias:!1,depth:!1,stencil:!1})),e.glMask.dirtyRect??=null,e.glMask.isDrawn??=!1,e.glMask},clearMask:function(e,t){e&&(t(e),e.isDrawn=!1,e.dirtyRect=null)},getCompositeRect:function(e,t,r,n,i){return e?e.dirtyRect?t()?r():i(n(e.dirtyRect,2)):r():null},getShaderMask:function(e,t){return t}},it=!0),de.stroke={color:null,weight:1,type:"HB",isActive:!1,opacity:1};let Qt=new Map;const er={offset:.08,scale:.08,warp:.06,tilt:.06};function tr(){return{...de.stroke}}function rr(e){de.stroke={...e}}function nr(e,t){if(t.type=["marker","custom","image","spray"].includes(t.type)?t.type:"default",void 0===t.markerTip&&(t.markerTip=!0),void 0===t.noise&&(t.noise=.3),t.noise=Math.max(0,Math.min(1,t.noise)),void 0!==t.vibration&&void 0===t.scatter&&(t.scatter=t.vibration),void 0!==t.definition&&void 0===t.sharpness&&(t.sharpness=t.definition),void 0!==t.quality&&void 0===t.grain&&(t.grain=t.quality),t.pressure=function(e){if(!e)return e;if("function"==typeof e)return{type:"custom",min_max:[0,1],curve:e,variation:{...er}};if("object"==typeof e&&!Array.isArray(e)){if("custom"===e.type||"custom"===e.mode){const{mode:t,...r}=e;return{...r,type:"custom",variation:{...er,...r.variation??{}}}}return"gaussian"===e.type||"gaussian"===e.mode||Array.isArray(e.curve)&&Array.isArray(e.min_max)?{...e,type:"gaussian",curve:e.curve,min_max:e.min_max}:e}if(Array.isArray(e)){const[t,r,n]=2===e.length?[e[0],(e[0]+e[1])/2,e[1]]:e,i=Math.min(t,r,n),o=Math.max(t,r,n),s=o-i||1,[a,c,l]=[(t-i)/s,(r-i)/s,(n-i)/s];return{type:"custom",min_max:[i,o],variation:{...er},curve:e=>e<.5?a+(c-a)*e*2:c+(l-c)*(e-.5)*2}}}(t.pressure),"custom"===t.type){if("function"!=typeof t.tip)throw new Error(`Brush "${e}" is type "custom" but is missing a tip function.`);const r=`custom::${e}`;!function(e){const t=Vt.get(e);t&&ct&&ct.deleteTexture(t),Vt.delete(e)}(r);const n=nt.createTipSurface(500,500);return n.pixelDensity(1),n.background(255),n.noSmooth(),n.push(),n.translate(250,250),n.scale(5),n.noStroke(),t.tip(n),n.pop(),Fr.imageToWhite(n),Fr.tips.set(r,n),t.tipKey=r,void Qt.set(e,{param:t,colors:[],buffers:[]})}if("image"===t.type){if(!t.image||!t.image.src)throw new Error(`Brush "${e}" is type "image" but is missing params.image.src. Example: image: { src: "./tip.jpg" }`);return Fr.add(t.image.src),Qt.set(e,{param:t,colors:[],buffers:[]}),Fr.load()}Qt.set(e,{param:t,colors:[],buffers:[]})}function ir(){return[...Qt.keys()]}function or(e){return Qt.get(e)?.param??null}function sr(e){for(const{param:t}of Qt.values())t&&(t.weight*=e,t.scatter*=e,t.spacing*=e)}function ar(e){if(!Qt.has(e))throw new Error(`Brush "${e}" not found. Available brushes: ${[...Qt.keys()].join(", ")}.`);de.stroke.type=e}function cr(e,t,r){q(),de.stroke.color=n(...arguments),de.stroke.isActive=!0}function lr(e){de.stroke.weight=e}function ur(e,t,r=1){ar(e),cr(t),lr(r)}function hr(){de.stroke.isActive=!1}function fr(e){return q(),e}function mr(){}let dr,xr,gr,pr;const yr={};function vr(e,t,r,n=!1){!function(){const e=i();vt=e.a,bt=e.b,_t=e.c,wt=e.d,Rt=e.x,At=e.y,Et=G/2,Mt=Z/2,St=Math.sqrt(vt*vt+bt*bt),Tt=H}(),dr=new _e(e+G/2,t+Z/2),xr=r,gr=n,gr&&gr.calcIndex(0)}const br=[];function _r(e,t){t||(pr=e),function(){yr.seed=999999*_();const{param:e}=Qt.get(de.stroke.type)??{};if(!e)return;yr.p=e;const{pressure:t}=e;if(yr.a="custom"!==t.type?_(-1,1):0,yr.b="custom"!==t.type?_(1,1.5):0,"custom"!==t.type)yr.cp=_(3,3.5),yr.ct=0,yr.cs=1,yr.ck=0;else{const e=t.variation??er;yr.cp=_(-e.offset,e.offset),yr.ct=_(-e.warp,e.warp),yr.cs=_(1-e.scale,1+e.scale),yr.ck=_(-e.tilt,e.tilt)}[yr.min,yr.max]=t.min_max,yr.noiseoffset=.05*yr.p.noise,gr||(yr.cos=D(pr),yr.sin=N(pr)),function(){xe(),function(){const e=$?.glMask;e&&(gt=e,gt.dirtyRect??=null,gt.isDrawn??=!1,ge.glMask=gt)}();const e=$.drawingContext,t=!mt||ct!==e;(t||dt!==G||xt!==Z)&&(lt=new Float32Array([2/G,0,0,0,0,2/Z,0,0,0,0,1,0,-1,-1,0,1]),dt=G,xt=Z),t&&(ct=e,ft=ot(ct,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_position;in float a_radius;in float a_alpha;uniform mat4 u_matrix;out float v_alpha;void main(){gl_Position=u_matrix*vec4(a_position,0.0,1.0);v_alpha=a_alpha;gl_PointSize=a_radius*2.0;}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin float v_alpha;out vec4 outColor;uniform vec4 u_color;void main(){vec2 v=gl_PointCoord-vec2(0.5);float f=length(v);float a=fwidth(f);f=1.0-smoothstep(0.5-a,0.5+a,f);if(f<0.01){discard;}outColor=vec4(u_color.xyz,v_alpha*f);}"),ct.useProgram(ft),ct.enable(ct.BLEND),ct.blendFunc(ct.ONE_MINUS_DST_ALPHA,ct.ONE),["a_position","a_radius","a_alpha"].forEach(e=>pt[e]=ct.getAttribLocation(ft,e)),["u_matrix","u_color"].forEach(e=>yt[e]=ct.getUniformLocation(ft,e)),ut=ct.createVertexArray(),ct.bindVertexArray(ut),ht=ct.createBuffer(),ct.bindBuffer(ct.ARRAY_BUFFER,ht),ct.bufferData(ct.ARRAY_BUFFER,Pt.byteLength,ct.DYNAMIC_DRAW),Ft=Pt.byteLength,ct.enableVertexAttribArray(pt.a_position),ct.vertexAttribPointer(pt.a_position,2,ct.FLOAT,!1,16,0),ct.enableVertexAttribArray(pt.a_radius),ct.vertexAttribPointer(pt.a_radius,1,ct.FLOAT,!1,16,8),ct.enableVertexAttribArray(pt.a_alpha),ct.vertexAttribPointer(pt.a_alpha,1,ct.FLOAT,!1,16,12),ct.bindVertexArray(null),Vt.clear(),Lt=ot(ct,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_corner;in vec2 a_pos;in float a_size;in float a_angle;in float a_alpha;uniform mat4 u_proj;out vec2 v_uv;out float v_alpha;void main(){float c=cos(a_angle);float s=sin(a_angle);vec2 rotated=vec2(c*a_corner.x-s*a_corner.y,s*a_corner.x+c*a_corner.y);gl_Position=u_proj*vec4(a_pos+rotated*a_size,0.0,1.0);v_uv=a_corner*0.5+0.5;v_alpha=a_alpha;}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin vec2 v_uv;in float v_alpha;uniform sampler2D u_tex;uniform vec4 u_color;out vec4 outColor;void main(){float inkAlpha=texture(u_tex,v_uv).a;if(inkAlpha<0.01)discard;outColor=vec4(u_color.rgb,inkAlpha*v_alpha);}"),["a_corner","a_pos","a_size","a_angle","a_alpha"].forEach(e=>Yt[e]=ct.getAttribLocation(Lt,e)),["u_proj","u_color","u_tex"].forEach(e=>zt[e]=ct.getUniformLocation(Lt,e)),Dt=ct.createVertexArray(),ct.bindVertexArray(Dt),Nt=ct.createBuffer(),ct.bindBuffer(ct.ARRAY_BUFFER,Nt),ct.bufferData(ct.ARRAY_BUFFER,$t,ct.STATIC_DRAW),ct.enableVertexAttribArray(Yt.a_corner),ct.vertexAttribPointer(Yt.a_corner,2,ct.FLOAT,!1,0,0),Bt=ct.createBuffer(),ct.bindBuffer(ct.ARRAY_BUFFER,Bt),ct.bufferData(ct.ARRAY_BUFFER,Ut.byteLength,ct.DYNAMIC_DRAW),Ot=Ut.byteLength,ct.enableVertexAttribArray(Yt.a_pos),ct.vertexAttribPointer(Yt.a_pos,2,ct.FLOAT,!1,20,0),ct.vertexAttribDivisor(Yt.a_pos,1),ct.enableVertexAttribArray(Yt.a_size),ct.vertexAttribPointer(Yt.a_size,1,ct.FLOAT,!1,20,8),ct.vertexAttribDivisor(Yt.a_size,1),ct.enableVertexAttribArray(Yt.a_angle),ct.vertexAttribPointer(Yt.a_angle,1,ct.FLOAT,!1,20,12),ct.vertexAttribDivisor(Yt.a_angle,1),ct.enableVertexAttribArray(Yt.a_alpha),ct.vertexAttribPointer(Yt.a_alpha,1,ct.FLOAT,!1,20,16),ct.vertexAttribDivisor(Yt.a_alpha,1),ct.bindVertexArray(null),mt=!0)}();const r=!0!==ge.isBrush;ge.isBrush=!0,r&&(ge.justChanged=!0),ge.blend(de.stroke.color),yr.alpha=["default","spray"].includes(yr.p.type)?yr.p.opacity:yr.p.opacity/Math.min(de.stroke.weight,1.3),Sr()}();const r=function(){const{param:e}=Qt.get(de.stroke.type)??{};return e?e.spacing:1}(),n=Math.round(xr*(t?e:1)/r);yr.pressureCount=10,yr.cachedPressure=void 0,yr.lineNoiseCount=5,yr.cachedLineNoise=void 0;for(let i=0;i<n;i++)br.length<2*n&&br.push(M()),wr(),t?dr.plotTo(gr,r,r,e,i<10):dr._moveToDegrees(e,r,r);!function(){Sr(),function(){if(0===Ct)return;ge.glMask.isDrawn=!0;const e=Wt(),t=de.stroke.color._array;ct.useProgram(ft),ct.enable(ct.BLEND),ct.blendFunc(ct.ONE_MINUS_DST_ALPHA,ct.ONE),ct.bindVertexArray(ut),ct.bindBuffer(ct.ARRAY_BUFFER,ht);const r=16*Ct,n=Pt.subarray(0,4*Ct);r>Ft?(ct.bufferData(ct.ARRAY_BUFFER,Pt,ct.DYNAMIC_DRAW),Ft=Pt.byteLength):ct.bufferSubData(ct.ARRAY_BUFFER,0,n),ct.uniform4f(yt.u_color,...t),ct.uniformMatrix4fv(yt.u_matrix,!1,Ht()),ct.drawArrays(ct.POINTS,0,Ct),ct.flush(),ct.bindVertexArray(null),jt(e),It&&(ge.markDirtyRect(ge.glMask,It),It=null),Ct=0,at($,ct)}();const e=yr.p?.type;"image"===e?Jt(Fr.tips.get(yr.p.image.src),yr.p.image.src):"custom"===e&&Jt(Fr.tips.get(yr.p.tipKey),yr.p.tipKey)}()}function wr(){const e=Rr(),t=((yr.lineNoiseCount>=10||void 0===yr.cachedLineNoise)&&(yr.cachedLineNoise=T(y(yr.seed+.01*dr.plotted,0),-1,1,1-yr.noiseoffset,1+yr.noiseoffset),yr.lineNoiseCount=0),yr.lineNoiseCount++,yr.cachedLineNoise);if(!(t>_(1,1.02)&&_(0,1)<.7))switch(yr.p.type){case"spray":!function(e){const t=de.stroke.weight*yr.p.scatter*e+de.stroke.weight*R(br)*yr.p.scatter/3,r=yr.p.weight*_(.9,1.1),n=Math.ceil(yr.p.grain/e);for(let e=0;e<n;e++){const e=_(.9,1.1),n=e*t*_(-1,1),i=_(-1,1),o=Math.sqrt((e*t)**2-n**2);Kt(dr.x+n,dr.y+i*o,r,yr.alpha)}}(e*t);break;case"marker":Er(e*t);break;case"custom":case"image":Mr(e*t);break;default:!function(e,t=1){const r=(t=T(t,0,1,.9,1.05))*de.stroke.weight*yr.p.scatter*(yr.p.sharpness+(1-yr.p.sharpness)*R(br)/e);if(_(0,yr.p.grain*e)>.4){let t,n;if(gr){const e=gr.angle(dr.plotted),i=D(e),o=N(e),s=r*_(-1,1),a=.3*r*_(-1,1);t=s*o+a*i,n=s*i-a*o}else{const e=r*_(-1,1),i=.3*r*_(-1,1);t=e*yr.sin+i*yr.cos,n=e*yr.cos-i*yr.sin}const i=e*e*yr.p.weight*_(.85,1.15)*de.stroke.weight,o=Math.max(.9,e)*yr.alpha*_(.75,1.1);Kt(dr.x+t,dr.y+n,i,o)}}(e*t)}}function Rr(){return(yr.pressureCount>=10||void 0===yr.cachedPressure)&&(yr.cachedPressure=gr?Ar()*gr.pressure(dr.plotted):Ar(),yr.pressureCount=0),yr.pressureCount++,yr.cachedPressure}function Ar(){return"custom"===yr.p.pressure.type?T(yr.p.pressure.curve(Math.max(0,Math.min(1,.5+(dr.plotted/xr-.5+yr.ct)*yr.cs)))+yr.cp+yr.ck*(dr.plotted/xr-.5),0,1,yr.min,yr.max,!0):function(e=.5+yr.p.pressure.curve[0]*yr.a,t=1-yr.p.pressure.curve[1]*yr.b,r=yr.cp,n=yr.min,i=yr.max){const o=e*xr,s=(dr.plotted<o?1.2*t:.8*t)*(xr/2);return T(1/(1+Math.pow(Math.abs((dr.plotted-o)/s),2*r)),0,1,n,i)}()}function Er(e,t=!0,r=yr.alpha){const n=t?de.stroke.weight*yr.p.scatter:0,i=t?n*_(-1,1):0,o=t?n*_(-1,1):0;Kt(dr.x+i,dr.y+o,de.stroke.weight*yr.p.weight*e,r*Math.max(.8,e)*_(.9,1.1))}function Mr(e,t=yr.alpha){const r=de.stroke.weight*yr.p.scatter,n=r*_(-1,1),i=r*_(-1,1),o=yr.p.weight*de.stroke.weight*e,s=function(){const e=Math.max(1,yr.max??1),t=de.stroke.weight*yr.p.scatter,r=de.stroke.weight*yr.p.weight*e;return Math.max(8,1.5*t+.75*r)}();let a=0;"random"===yr.p.rotate?a=A(0,360)*(Math.PI/180):"natural"===yr.p.rotate&&(a=((gr?-gr.angle(dr.plotted):-pr)+dr.angle())*(Math.PI/180)),function(e,t,r,n,i,o=0){if(Xt>=Gt){Gt*=2;const e=new Float32Array(5*Gt);e.set(Ut),Ut=e}const s=e-Et,a=t-Mt,c=vt*s+_t*a+Rt+Et,l=bt*s+wt*a+At+Mt,u=Tt*r*St/2,h=Tt*o*St,f=5*Xt;Ut[f]=c,Ut[f+1]=l,Ut[f+2]=u,Ut[f+3]=n,Ut[f+4]=i/255;const m=c*Tt,d=l*Tt,x=1.42*u+h;Zt=qt(Zt,m-x-1,d-x-1,m+x+1,d+x+1),Xt++}(dr.x+n,dr.y+i,o,a,t*Math.max(.8,e)*_(.9,1.1),s)}function Sr(){if(!1===yr.p.markerTip)return;let e=Rr(),t=yr.alpha;if("marker"===yr.p.type)for(let r=1;r<10;r++)Er(e*r/10,!0,8*t);else if("custom"===yr.p.type||"image"===yr.p.type)for(let r=1;r<5;r++)Mr(e*r/10,2*t)}function Tr(e,t,r,n){if(!de.stroke.isActive||!de.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");be();let i=O(e,t,r,n);0!=i&&(vr(e,t,i),_r(U(e,t,r,n),!1))}function Pr(e,t,r,n){if(!de.stroke.isActive||!de.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");be(),vr(e,t,r),_r(B(n),!1)}g(()=>{br.length=0});const Cr=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate","markerTip","noise"],kr=[["pen",[.3,.15,.9,2,150,.1,{curve:[.15,.2],min_max:[1.2,1]}]],["rotring",[.15,.05,.7,15,210,.1,{curve:[.35,.2],min_max:[1.3,1]}]],["2B",[.3,.75,.45,15,180,.1,{curve:[.1,.3],min_max:[1.1,.9]}]],["HB",[.3,.6,.3,10,170,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["2H",[.2,.6,.3,4,120,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["cpencil",[.3,.55,.8,7,75,.1,{curve:[.15,.2],min_max:[.95,1.2]}]],["pastel",[2.05/3,13.4/3,.91,28,35,.085/3,{mode:"gaussian",curve:[.4,.05],min_max:[1.09,.93]},"default",void 0,"natural",!0,1]],["crayon",[.3,5.45/3,.75,250,159,.23/3,[1.1,.9],"default",void 0,"natural",!0,1]],["charcoal",[.35,1.5,.68,500,120,.03,{curve:[.15,.4],min_max:[1.1,.95]}]],["spray",[.2,6,15,40,90,.5,{curve:[.2,.35],min_max:[.7,1]},"spray"]],["marker",[2,.2,null,null,1,.03,{curve:[.35,.25],min_max:[1.2,.85]},"marker"]]];for(let e of kr){let t={};for(let r=0;r<e[1].length;r++)t[Cr[r]]=e[1][r];nr(e[0],t)}Ye.prototype.draw=function(e=!1,t,r){let n=tr();if(e&&ur(e,t,r),n.isActive)for(let e of this.sides)Tr(e[0].x,e[0].y,e[1].x,e[1].y);rr(n)},ze.prototype.draw=function(e,t,r){tr().isActive&&(this.origin&&(e=this.origin[0],t=this.origin[1],r=1),function(e,t,r,n){be(),vr(t,r,e.length,e),_r(n,!0)}(this,e,t,r))};const Fr={tips:new Map,add(e){this.tips.has(e)||this.tips.set(e,!1)},imageToWhite(e){e.loadPixels();for(let t=0;t<4*e.width*e.height;t+=4){let r=(e.pixels[t]+e.pixels[t+1]+e.pixels[t+2])/3;e.pixels[t]=e.pixels[t+1]=e.pixels[t+2]=255,e.pixels[t+3]=255-r}e.updatePixels()},async load(){const e=[...this.tips.keys()].filter(e=>!this.tips.get(e));await Promise.all(e.map(e=>((e,t)=>nt.loadImageTip(e,t))(e,Fr.imageToWhite).then(t=>{this.tips.set(e,t)})))}};function Ir(){return{...de.hatch}}function Lr(e){de.hatch={...e}}function Dr(e=5,t=45,r={rand:!1,continuous:!1,gradient:!1}){let n=de.hatch;n.isActive=!0,n.dist=e,n.angle=Y(t),n.options=r}function Nr(e,t="black",r=1){de.hatch.hBrush={brush:e,color:t,weight:r}}function Br(){de.hatch.isActive=!1,de.hatch.hBrush=!1}function Yr(e,t,r,n){const i=t*Math.PI/180,o=Math.cos(i),s=Math.sin(i),a=Math.cos(-i),c=Math.sin(-i),l=e.a,u=l.length,h=new Array(u);let f=Infinity,m=-Infinity;for(let e=0;e<u;e++){const t=l[e][0],r=l[e][1],n=[t*o-r*s,t*s+r*o];h[e]=n,n[1]<f&&(f=n[1]),n[1]>m&&(m=n[1])}const d=[];for(let e=0;e<u;e++){const t=h[e],r=h[(e+1)%u];t[1]!==r[1]&&d.push(t,r)}const x=d.length,g=[],p=[];let y=f+.5*r,v=r;for(;y<m;){p.length=0;for(let e=0;e<x;e+=2){const t=d[e][1],r=d[e+1][1];(t<=y&&y<r||r<=y&&y<t)&&p.push(d[e][0]+(y-t)/(r-t)*(d[e+1][0]-d[e][0]))}p.sort((e,t)=>e-t);for(let e=0;e<p.length-1;e+=2)g.push({scanY:y,x1:p[e]*a-y*c,y1:p[e]*c+y*a,x2:p[e+1]*a-y*c,y2:p[e+1]*c+y*a});y+=v,v*=n}return g}function zr(e){const{dist:t,options:r,segs:n}=function(e){const t=de.hatch.dist,r=(de.hatch.angle%180+180)%180,n=de.hatch.options,i=function(e,t,r,n){Array.isArray(e)||(e=[e]);const i=[];for(const o of e)for(const e of Yr(o,r,t,n))i.push(e);return i.sort((e,t)=>e.scanY===t.scanY?e.x1-t.x1:e.scanY-t.scanY),i}(e,t,r,n.gradient?T(n.gradient,0,1,1,1.1,!0):1);return{dist:t,options:n,segs:i}}(e),i=r.rand||0,o=[];for(let e=0;e<n.length;e++){const s=n[e];let a=s.x1,c=s.y1,l=s.x2,u=s.y2;i&&(a+=2*i*t*_(-1,1),c+=2*i*t*_(-1,1),l+=2*i*t*_(-1,1),u+=2*i*t*_(-1,1));const h=r.continuous&&e%2==1?{x1:l,y1:u,x2:a,y2:c,scanY:s.scanY,isConnector:!1}:{x1:a,y1:c,x2:l,y2:u,scanY:s.scanY,isConnector:!1};if(o.push(h),e>0&&r.continuous){const e=o[o.length-2];o.push({x1:e.x2,y1:e.y2,x2:h.x1,y2:h.y1,scanY:s.scanY,isConnector:!0})}}return o}function Or(e){!function(e,t){const r=zr(e);!function(){const e=tr();de.hatch.hBrush&&ur(...Object.values(de.hatch.hBrush)),(()=>{for(let e=0;e<r.length;e++){const n=r[e];t(n.x1,n.y1,n.x2,n.y2,e,r)}})(),rr(e)}()}(e,(e,t,r,n)=>{Tr(e,t,r,n)})}function Ur(e,t,r={}){de.mass.brush=e,de.mass.color=t,de.mass.options=r,de.mass.isActive=!0}function Xr(){de.mass.isActive=!1,de.mass.brush=null,de.mass.color=null,de.mass.options={}}function Gr(e,t,r){return new Ye(e.vertices.map(e=>[e.x+t,e.y+r]))}function Zr(e,t,r,n,i){const o=(t+n)/2,s=(r+i)/2,a=n-t,c=i-r,l=Math.hypot(a,c);if(!l)return null;const u=-c/l,h=a/l,f=(e.x-o)*u+(e.y-s)*h;return{x:o+u*f,y:s+h*f}}function Vr(e,t,r,n,i,o,s){let a=U(e,t,r,n),c=U(e,t,i,o);return((c-a)%360+360)%360>180&&([a,c]=[c,a]),[s(a),s(c)]}function $r(e){const t=w(.35,.65),r=e.x1+(e.x2-e.x1)*t,n=e.y1+(e.y2-e.y1)*t,i=e.x2-e.x1,o=e.y2-e.y1,s=Math.hypot(i,o)||1,a=w(.04,.1)*s,c=i/s*a*.5,l=o/s*a*.5;return[{x1:e.x1,y1:e.y1,x2:r-c,y2:n-l},{x1:r+c,y1:n+l,x2:e.x2,y2:e.y2}]}function Hr(e,t,r){const n=function(e,t){const r=function(e){const t=e?.a??[];let r=Infinity,n=Infinity,i=-Infinity,o=-Infinity;for(const[e,s]of t)e<r&&(r=e),s<n&&(n=s),e>i&&(i=e),s>o&&(o=s);return{minX:r,minY:n,maxX:i,maxY:o,cx:(r+i)/2,cy:(n+o)/2,size:Math.hypot(i-r,o-n)}}(e),n=r.size*w(.6,1.4),[i,o]=t;return{x:r.cx+i*n,y:r.cy+o*n}}(e,t);for(const t of zr(e)){const e=!t.isConnector&&w()<.35?$r(t):[t];for(const t of e){const e=Zr(n,t.x1,t.y1,t.x2,t.y2);if(!e)continue;const i=O(e.x,e.y,t.x1,t.y1);if(!i)continue;const[o,s]=Vr(e.x,e.y,t.x1,t.y1,t.x2,t.y2,r);Ge(e.x,e.y,i,o,s)}}}function Wr(e,t,r,n,i,o){Dr(t,r,n),Hr(e,i,o)}function jr(e,n,i,o){const s=function(e,t,r,n){const i=!1===t,o=or(de.mass.brush)?.scatter??0,s=i?e:e.genPol(t,r,n,.15),a=Math.min(2*o,5),c=[[w(-a,a),w(-a,a)],[w(-a,a),w(-a,a)]];return[s,Gr(s,c[0][0],c[0][1]),Gr(s,c[1][0],c[1][1])]}(e,n,i,o),a=Ir(),c=tr(),l={...de.field},u=de.mass.options?.precision??.5,h=de.mass.options?.strength??1,f=de.mass.options?.gradient??.1,m=de.mass.options?.outline??!1,d=or(de.mass.brush)?.scatter??0,x=1.6*w(.65*d,.85*d)-.4*f,g=w(-90,90),p=((g+90)%180+180)%180-90>=0?w()<.5?[1,1]:[-1,-1]:w()<.5?[-1,1]:[1,-1],y=t()?e=>e*Math.PI/180:e=>e;ur(de.mass.brush,de.mass.color,1),Ne(2-u),m&&s[0].draw(),Wr(s[0],.9*x,r(g),{gradient:f,rand:2-2*u,continuous:!0},p,y),h>.33&&Wr(s[1],x,r(g+20*w(-1,1)),{gradient:f,rand:.6-.6*u,continuous:!0},p,y),h>.66&&Wr(s[2],.8*x,r(g+15*w(-1,1)),{gradient:f,rand:.6-.6*u,continuous:!0},p,y),rr(c),Lr(a),de.field={...l}}function qr(e,t,r){const n=2*Math.PI,i=ge.ctx,o=r/2;i.moveTo(e+o,t),i.arc(e,t,o,0,n)}de.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},Ye.prototype.hatch=function(e=!1,t,r){let n=Ir();e&&Dr(e,t,r),de.hatch.isActive&&Or(this),Lr(n)},ze.prototype.hatch=function(e,t,r){Ir().isActive&&(this.origin&&(e=this.origin[0],t=this.origin[1],r=1),this.pol=this.genPol(e,t,r,.3),this.pol.hatch())},de.mass={isActive:!1,brush:null,color:null,options:{}},Ye.prototype.mass=function(){de.mass?.isActive&&jr(this,!1)},ze.prototype.mass=function(e,t,r){de.mass?.isActive&&(this.origin&&(e=this.origin[0],t=this.origin[1],r=1),jr(this,e,t,r))};let Kr=null,Jr=!1;Jr||(ae={ensureResources:function(e,t,r,n,i){const o=Math.max(1,Math.round(t*n)),s=Math.max(1,Math.round(r*n));return function(e,t,r){return!e.mask||e.mask.width!==t||e.mask.height!==r}(e,o,s)&&(e.mask=ne(o,s)),function(e,t,r,n){return!e.fillMaskFramebuffer||e.fillMaskFramebuffer.width!==t||e.fillMaskFramebuffer.height!==r||"function"==typeof e.fillMaskFramebuffer.pixelDensity&&e.fillMaskFramebuffer.pixelDensity()!==n}(e,t,r,n)&&(e.fillMaskFramebuffer?.remove&&e.fillMaskFramebuffer.remove(),e.fillMaskFramebuffer=oe(e,{width:t,height:r,density:n,antialias:!1,depth:!1,stencil:!1}),i(e.fillMaskFramebuffer)),e.mask.dirtyRect??=null,e.mask.isDrawn??=!1,e.mask.drawingContext.imageSmoothingEnabled=!1,{mask:e.mask,ctx:e.mask.drawingContext}},clearMask:function(e,t){e&&(t(e),e.isDrawn=!1,e.dirtyRect=null)},getCompositeRect:function(e,t,r,n,i){return e?e.dirtyRect?i(n(e.dirtyRect,4)):r():null},getShaderMask:function(e,t,r,n,i,o){const s=e.fillMaskFramebuffer,a=e.drawingContext,c=n(r)??i(),l=c.maxX-c.minX,u=c.maxY-c.minY;Kr&&Kr.width===l&&Kr.height===u||(Kr=ne(l,u));const h=Kr.drawingContext;return h.clearRect(0,0,l,u),h.drawImage(t,c.minX,c.minY,l,u,0,0,l,u),o(s),a.bindTexture(a.TEXTURE_2D,s.colorTexture),a.texSubImage2D(a.TEXTURE_2D,0,c.minX,c.minY,a.RGBA,a.UNSIGNED_BYTE,Kr),s}},Jr=!0);let Qr,en=[],tn=[],rn=[],nn=[];de.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const on=()=>({...de.fill});function sn(e,t,r,i){de.fill.opacity=(arguments.length<4?t:i)||150,de.fill.color=arguments.length<3?n(e):n(e,t,r),de.fill.isActive=!0}function an(e,t="out"){de.fill.bleed_strength=P(e,0,1),de.fill.direction=t}function cn(e=.4,t=.4){de.fill.texture_strength=P(e,0,1),de.fill.border_strength=P(t,0,1)}function ln(){de.fill.isActive=!1}let un;const hn=[[],[]];function fn(){for(let e=0;e<512;e++)hn[0][e]=M(.5,.2),hn[1][e]=M(0,.02)}function mn(e,t,r){return(t.x-e.x)*(r.y-e.y)-(t.y-e.y)*(r.x-e.x)>.01}g(fn);class dn{constructor(e,t,r,n=[],i=!1,o,s){if(this.v=e,this.m=t,this.dir=n,this.midP=r,i){let t=0,n=0;const i=[];for(let o=0;o<e.length;o++){const s=Math.abs(r.x-e[o].x),a=Math.abs(r.y-e[o].y);t=Math.max(t,s),n=Math.max(n,a);const c=e[o],l=e[(o+1)%e.length],u={x:l.x-c.x,y:l.y-c.y},h=z(0,0,u.x,u.y,90),f={x:c.x+u.x/2,y:c.y+u.y/2};i.push({v1:c,v2:l,ray:{point1:f,point2:{x:f.x+h.x,y:f.y+h.y}}})}this.sizeX=t,this.sizeY=n,this.dir=Array(e.length),i.forEach((e,t)=>{let r=0;for(const t of un.intersect(e.ray))mn(e.v1,e.v2,t)&&r++;this.dir[t]=r%2==0});const o=_(-.6,.6)*t,s=_(-.6,.6)*n;this.midP={x:r.x+o,y:r.y+s}}else this.sizeX=o,this.sizeY=s}trim(e=1){if(e>=1||e<0||this.v.length<=8)return{v:this.v,m:this.m,dir:this.dir};const t=~~((1-e)*this.v.length),r=~~(this.v.length/2-t/2),n=this.v.length-t,i=new Array(n),o=new Array(n),s=new Array(n);let a=0;for(let e=0;e<r;e++,a++)i[a]=this.v[e],o[a]=this.m[e],s[a]=this.dir[e];for(let e=r+t;e<this.v.length;e++,a++)i[a]=this.v[e],o[a]=this.m[e],s[a]=this.dir[e];const c=r,l=r+t,u=this.v[(c-1+this.v.length)%this.v.length],h=this.v[l%this.v.length],f=h.x-u.x,m=h.y-u.y;for(let e=0;e<2;e++){const t=_(.25,.75),n={x:u.x+f*t,y:u.y+m*t},a=r+e;i.splice(a,0,n),o.splice(a,0,_(.4,.7)),s.splice(a,0,this.dir[c%this.dir.length])}return{v:i,m:o,dir:s}}scatter(e=.3){const t=this.v.length,r=Math.max(3,~~(t*e)),n=[],i=t/r;for(let e=0;e<r;e++)n.push(~~(e*i+_(0,.8*i)));const o=[],s=[],a=[],c=this.midP,l=un.sides;for(const e of n){const r=e%t;let n=this.v[r],i=0;for(const[e,t]of l){const r=e.y,o=t.y;if(r>n.y==o>n.y)continue;const s=(n.y-r)/(o-r);n.x<e.x+s*(t.x-e.x)&&i++}i%2==0&&(n={x:c.x+(n.x-c.x)*_(.3,.6),y:c.y+(n.y-c.y)*_(.3,.6)}),o.push(n),s.push(this.m[r]),a.push(!this.dir[r])}return new dn(o,s,this.midP,a,!1,this.sizeX,this.sizeY)}flipDirs(){return new dn(this.v,this.m,this.midP,this.dir.map(e=>!e),!1,this.sizeX,this.sizeY)}grow(e=1){const{v:t,m:r,dir:n}=this.trim(e),i=t.length,o=2*i;en.length<i&&(en=new Array(i),tn=new Array(i)),rn.length<o&&(rn=new Array(o),nn=new Array(o));const s=en,a=tn,c=rn,l=nn,u="out"===de.fill.direction?-90:90;0===hn[0].length&&fn();const h=hn[0],f=h.length,m=hn[1],d=m.length;let x,g,p,y=0,v=0,b=999===e?_(.6,.8):de.fill.bleed_strength;for(let o=0;o<i;o++){const x=t[o],g=t[o+1<i?o+1:0],p=r[o],w=n[o];if(e<997&&(b=p),b<.05){c[y]=p,l[y]=w,y++,s[v]=(x.x+g.x)/2,a[v]=(x.y+g.y)/2,c[y]=p,l[y]=w,y++,v++;continue}const R=(w?u:-u)+5*_(-1,1),A=D(R),E=N(R),M=g.x-x.x,S=g.y-x.y,T=A*M+E*S,P=A*S-E*M,C=h[~~(_(0,1)*f)]*_(.65,1.35)*b,k=p+m[~~(_(0,1)*d)];c[y]=p,l[y]=w,y++,s[v]=x.x+.5*M+T*C,a[v]=x.y+.5*S+P*C,c[y]=k,l[y]=w,y++,v++}if(Qr&&y>Qr){const e=Math.ceil(y/Qr),r=Math.ceil(y/e);x=new Array(r),g=new Array(r),p=new Array(r);let n=0;for(let r=0;r<y;r+=e,n++)x[n]=r%2==0?t[r>>1]:{x:s[r>>1],y:a[r>>1]},g[n]=c[r],p[n]=l[r]}else{x=new Array(y);for(let e=0;e<y;e++)x[e]=e%2==0?t[e>>1]:{x:s[e>>1],y:a[e>>1]};g=c.slice(0,y),p=l.slice(0,y)}return new dn(x,g,this.midP,p,!1,this.sizeX,this.sizeY)}fill(e,t,r){const n=3*r,o=2*t*(1+r/2),s=!1!==ge.isBrush;ge.isBrush=!1,s&&(ge.justChanged=!0),ge.blend(e);const a=i();ge.ctx.save(),ge.ctx.setTransform(H*a.a,H*a.b,H*a.c,H*a.d,H*(a.x+G/2),H*(a.y+Z/2)),ge.ctx.strokeStyle=`rgb(${e._getRed()} ${e._getGreen()} ${e._getBlue()} / ${.005*de.fill.border_strength})`,ge.ctx.lineCap="round",Qr=2024*Math.max(.1,2*de.fill.bleed_strength);const c=Math.max(this.sizeX,this.sizeY),l=_(.15,.7);let u=this.grow();const h=this.scatter(.1).grow().scatter(.75).flipDirs();let f;for(let r=0;r<20;r++){r%4==0&&(u=u.grow()),r%2==0&&(f=[u.grow(1-.0125*r),u.grow(.7-.0125*r),u.grow(.4-.0125*r)]);for(const t of f)t.grow(999).grow(997).layer(r,c,o,e);h.grow(999).flipDirs().grow(997).layer(r,c,o*n,e),r%2==0&&u.grow(l).grow(999).layer(r,c,2*o,e),r%8!=0&&19!==r||(0!==n&&u.erase(3*n,t),ge.blend(e,!0))}ge.ctx.restore()}layer(e,t,r,n){ge.ctx.lineWidth=T(e,0,24,t/25,t/30,!0),ge.ctx.fillStyle=`rgb(${n._getRed()} ${n._getGreen()} ${n._getBlue()} / ${r}%)`,function(e){const t=ge.ctx,r=t.getTransform(),n=r.a,i=r.b,o=r.c,s=r.d,a=r.e,c=r.f;let l=Infinity,u=Infinity,h=-Infinity,f=-Infinity;t.beginPath();const m=e[0];let d=n*m.x+o*m.y+a,x=i*m.x+s*m.y+c;l=h=d,u=f=x,t.moveTo(m.x,m.y);for(let r=1;r<e.length;r++){const m=e[r];d=n*m.x+o*m.y+a,x=i*m.x+s*m.y+c,l=Math.min(l,d),u=Math.min(u,x),h=Math.max(h,d),f=Math.max(f,x),t.lineTo(m.x,m.y)}t.closePath();const g=function(e,t){const r=e.lineWidth||0;return r<=0?1:1+r*Math.max(Math.hypot(t.a,t.c),Math.hypot(t.b,t.d))/2}(t,r);ge.markDirtyRect(ge.mask,{minX:l-g,minY:u-g,maxX:h+g,maxY:f+g})}(this.v),ge.ctx.fill(),ge.ctx.stroke()}erase(e,t){ge.ctx.save();const r=~~(_(80,110)*T(e,0,1,2,3.5)),n=this.sizeX/1.3,i=this.sizeY/1.3,o=1.3*Math.min(this.sizeX,this.sizeY),s=.03*o,a=.45*o,{x:c,y:l}=this.midP;ge.ctx.globalCompositeOperation="destination-out";const u=(5-T(t,80,100,.3,.7,!0))*e/255;ge.ctx.fillStyle=`rgb(255 0 0 / ${u})`,ge.ctx.lineWidth=0;for(let e=0;e<r;e++){const t=c+M(0,n),r=l+M(0,i),o=_(s,a);ge.ctx.beginPath(),qr(t,r,o),e%5!=0&&ge.ctx.fill()}ge.ctx.globalCompositeOperation="source-over",ge.ctx.restore()}}function xn(e,t){if(!e)return e;t||(t=e);let r,n=e;do{if(r=!1,n.steiner||!En(n,n.next)&&0!==An(n.prev,n,n.next))n=n.next;else{if(Fn(n),n=t=n.prev,n===n.next)break;r=!0}}while(r||n!==t);return t}function gn(e,t,r,n,i,o,s){if(!e)return;!s&&o&&function(e,t,r,n){let i=e;do{0===i.z&&(i.z=_n(i.x,i.y,t,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==e);i.prevZ.nextZ=null,i.prevZ=null,function(e){let t,r=1;do{let n,i=e;e=null;let o=null;for(t=0;i;){t++;let s=i,a=0;for(let e=0;e<r&&(a++,s=s.nextZ,s);e++);let c=r;for(;a>0||c>0&&s;)0!==a&&(0===c||!s||i.z<=s.z)?(n=i,i=i.nextZ,a--):(n=s,s=s.nextZ,c--),o?o.nextZ=n:e=n,n.prevZ=o,o=n;i=s}o.nextZ=null,r*=2}while(t>1)}(i)}(e,n,i,o);let a=e;for(;e.prev!==e.next;){const c=e.prev,l=e.next;if(o?yn(e,n,i,o):pn(e))t.push(c.i,e.i,l.i),Fn(e),e=l.next,a=l.next;else if((e=l)===a){s?1===s?gn(e=vn(xn(e),t),t,r,n,i,o,2):2===s&&bn(e,t,r,n,i,o):gn(xn(e),t,r,n,i,o,1);break}}}function pn(e){const t=e.prev,r=e,n=e.next;if(An(t,r,n)>=0)return!1;const i=t.x,o=r.x,s=n.x,a=t.y,c=r.y,l=n.y,u=Math.min(i,o,s),h=Math.min(a,c,l),f=Math.max(i,o,s),m=Math.max(a,c,l);let d=n.next;for(;d!==t;){if(d.x>=u&&d.x<=f&&d.y>=h&&d.y<=m&&wn(i,a,o,c,s,l,d.x,d.y)&&An(d.prev,d,d.next)>=0)return!1;d=d.next}return!0}function yn(e,t,r,n){const i=e.prev,o=e,s=e.next;if(An(i,o,s)>=0)return!1;const a=i.x,c=o.x,l=s.x,u=i.y,h=o.y,f=s.y,m=Math.min(a,c,l),d=Math.min(u,h,f),x=Math.max(a,c,l),g=Math.max(u,h,f),p=_n(m,d,t,r,n),y=_n(x,g,t,r,n);let v=e.prevZ,b=e.nextZ;for(;v&&v.z>=p&&b&&b.z<=y;){if(v.x>=m&&v.x<=x&&v.y>=d&&v.y<=g&&v!==i&&v!==s&&wn(a,u,c,h,l,f,v.x,v.y)&&An(v.prev,v,v.next)>=0)return!1;if(v=v.prevZ,b.x>=m&&b.x<=x&&b.y>=d&&b.y<=g&&b!==i&&b!==s&&wn(a,u,c,h,l,f,b.x,b.y)&&An(b.prev,b,b.next)>=0)return!1;b=b.nextZ}for(;v&&v.z>=p;){if(v.x>=m&&v.x<=x&&v.y>=d&&v.y<=g&&v!==i&&v!==s&&wn(a,u,c,h,l,f,v.x,v.y)&&An(v.prev,v,v.next)>=0)return!1;v=v.prevZ}for(;b&&b.z<=y;){if(b.x>=m&&b.x<=x&&b.y>=d&&b.y<=g&&b!==i&&b!==s&&wn(a,u,c,h,l,f,b.x,b.y)&&An(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function vn(e,t){let r=e;do{const n=r.prev,i=r.next.next;!En(n,i)&&Mn(n,r,r.next,i)&&Pn(n,i)&&Pn(i,n)&&(t.push(n.i,r.i,i.i),Fn(r),Fn(r.next),r=e=i),r=r.next}while(r!==e);return xn(r)}function bn(e,t,r,n,i,o){let s=e;do{let e=s.next.next;for(;e!==s.prev;){if(s.i!==e.i&&Rn(s,e)){let a=Cn(s,e);return s=xn(s,s.next),a=xn(a,a.next),gn(s,t,r,n,i,o,0),void gn(a,t,r,n,i,o,0)}e=e.next}s=s.next}while(s!==e)}function _n(e,t,r,n,i){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-r)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-n)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function wn(e,t,r,n,i,o,s,a){return!(e===s&&t===a)&&function(e,t,r,n,i,o,s,a){return(i-s)*(t-a)>=(e-s)*(o-a)&&(e-s)*(n-a)>=(r-s)*(t-a)&&(r-s)*(o-a)>=(i-s)*(n-a)}(e,t,r,n,i,o,s,a)}function Rn(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){let r=e;do{if(r.i!==e.i&&r.next.i!==e.i&&r.i!==t.i&&r.next.i!==t.i&&Mn(r,r.next,e,t))return!0;r=r.next}while(r!==e);return!1}(e,t)&&(Pn(e,t)&&Pn(t,e)&&function(e,t){let r=e,n=!1;const i=(e.x+t.x)/2,o=(e.y+t.y)/2;do{r.y>o!=r.next.y>o&&r.next.y!==r.y&&i<(r.next.x-r.x)*(o-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==e);return n}(e,t)&&(An(e.prev,e,t.prev)||An(e,t.prev,t))||En(e,t)&&An(e.prev,e,e.next)>0&&An(t.prev,t,t.next)>0)}function An(e,t,r){return(t.y-e.y)*(r.x-t.x)-(t.x-e.x)*(r.y-t.y)}function En(e,t){return e.x===t.x&&e.y===t.y}function Mn(e,t,r,n){const i=Tn(An(e,t,r)),o=Tn(An(e,t,n)),s=Tn(An(r,n,e)),a=Tn(An(r,n,t));return i!==o&&s!==a||!(0!==i||!Sn(e,r,t))||!(0!==o||!Sn(e,n,t))||!(0!==s||!Sn(r,e,n))||!(0!==a||!Sn(r,t,n))}function Sn(e,t,r){return t.x<=Math.max(e.x,r.x)&&t.x>=Math.min(e.x,r.x)&&t.y<=Math.max(e.y,r.y)&&t.y>=Math.min(e.y,r.y)}function Tn(e){return e>0?1:e<0?-1:0}function Pn(e,t){return An(e.prev,e,e.next)<0?An(e,t,e.next)>=0&&An(e,e.prev,t)>=0:An(e,t,e.prev)<0||An(e,e.next,t)<0}function Cn(e,t){const r=In(e.i,e.x,e.y),n=In(t.i,t.x,t.y),i=e.next,o=t.prev;return e.next=t,t.prev=e,r.next=i,i.prev=r,n.next=r,r.prev=n,o.next=n,n.prev=o,n}function kn(e,t,r,n){const i=In(e,t,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Fn(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function In(e,t,r){return{i:e,x:t,y:r,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}Ye.prototype.fill=function(e=!1,t,r,n,i,o){let s=on();e&&(sn(e,t),an(r,o),cn(n,i)),s.isActive&&(be(),function(e){if(!de.fill.isActive||!de.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");un=e;const t=[...e.vertices],r=~~(.25*t.length*S({1:5,2:10,3:60})),n=de.fill.bleed_strength,i=t.map((e,t)=>(t>r?1:.3)*_(.85,1.4)*n),o=A(0,t.length),s=[...t.slice(o),...t.slice(0,o)],a=function(e){if(0===e.length)return{x:0,y:0};if(e.length<8){const t=e.reduce((e,t)=>({x:e.x+t.x,y:e.y+t.y}),{x:0,y:0});return{x:t.x/e.length,y:t.y/e.length}}const t=[...e];t[0].x===t[t.length-1].x&&t[0].y===t[t.length-1].y||t.push(t[0]);let r=0,n=0,i=0;for(let e=0;e<t.length-1;e++){const o=t[e].x*t[e+1].y-t[e+1].x*t[e].y;r+=o,n+=(t[e].x+t[e+1].x)*o,i+=(t[e].y+t[e+1].y)*o}return r*=.5,r?{x:n/(6*r),y:i/(6*r)}:{x:t[0].x,y:t[0].y}}(s);new dn(s,i,a,[],!0).fill(de.fill.color,T(de.fill.opacity,0,255,0,1,!0),de.fill.texture_strength)}(this)),(e=>{de.fill={...e}})(s)},ze.prototype.fill=function(e,t,r){on().isActive&&(this.origin&&(e=this.origin[0],t=this.origin[1],r=1),this.pol=this.genPol(e,t,r,de.fill.bleed_strength<.06?0:T(de.fill.bleed_strength,0,.6,.2,.6,!0)),this.pol.fill())};let Ln=null,Dn=null,Nn=null,Bn=null,Yn=null,zn=0,On=0,Un=0;const Xn={},Gn={};function Zn(e,t,r,i){q(),de.wash.opacity=(arguments.length<4?t:i)??150,de.wash.color=arguments.length<3?n(e):n(e,t,r),de.wash.isActive=!0}function Vn(){de.wash.isActive=!1}function $n(e,t){const r=i();return[r.a*e+r.c*t+r.x+zn/2,r.b*e+r.d*t+r.y+On/2]}de.wash={color:null,opacity:150,isActive:!1},Ye.prototype.wash=function(e=!1,t){const r={...de.wash};!1!==e&&Zn(e,t),de.wash.isActive&&function(e){if(!de.wash?.isActive||!de.wash.color||e.vertices.length<3)return;pe(),function(){const e=$.drawingContext;Yn&&!(zn!==G||On!==Z)||(zn=G,On=Z,Yn=new Float32Array([2/zn,0,0,0,0,-2/On,0,0,0,0,1,0,-1,1,0,1])),Ln===e&&Dn&&Nn&&Bn||(Ln=e,Dn=ot(Ln,"#version 300 es\nin vec2 a_position;\nuniform mat4 u_matrix;\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n}","#version 300 es\nprecision highp float;\nuniform vec4 u_color;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(u_color.rgb * u_color.a, u_color.a);\n}"),Xn.a_position=Ln.getAttribLocation(Dn,"a_position"),Gn.u_matrix=Ln.getUniformLocation(Dn,"u_matrix"),Gn.u_color=Ln.getUniformLocation(Dn,"u_color"),Nn=Ln.createVertexArray(),Ln.bindVertexArray(Nn),Bn=Ln.createBuffer(),Ln.bindBuffer(Ln.ARRAY_BUFFER,Bn),Ln.bufferData(Ln.ARRAY_BUFFER,0,Ln.DYNAMIC_DRAW),Un=0,Ln.enableVertexAttribArray(Xn.a_position),Ln.vertexAttribPointer(Xn.a_position,2,Ln.FLOAT,!1,8,0),Ln.bindVertexArray(null),Ln.bindBuffer(Ln.ARRAY_BUFFER,null))}();const{triangles:t,vertexCount:r}=function(e){const t=new Float32Array(2*e.vertices.length);for(let r=0;r<e.vertices.length;r++){const n=e.vertices[r];t[2*r]=n.x,t[2*r+1]=n.y}const r=function(e,t,r=2){const n=e.length;let i=function(e,t,r,n){let i;if(1==function(e,t,r,n){let i=0;for(let t=0,o=r-n;t<r;t+=n)i+=(e[o]-e[t])*(e[t+1]+e[o+1]),o=t;return i}(e,0,r,n)>0)for(let t=0;t<r;t+=n)i=kn(t/n|0,e[t],e[t+1],i);else for(let t=r-n;t>=0;t-=n)i=kn(t/n|0,e[t],e[t+1],i);return i&&En(i,i.next)&&(Fn(i),i=i.next),i}(e,0,n,r);const o=[];if(!i||i.next===i.prev)return o;let s,a,c;if(e.length>80*r){s=e[0],a=e[1];let t=s,i=a;for(let o=r;o<n;o+=r){const r=e[o],n=e[o+1];r<s&&(s=r),n<a&&(a=n),r>t&&(t=r),n>i&&(i=n)}c=Math.max(t-s,i-a),c=0!==c?32767/c:0}return gn(i,o,r,s,a,c,0),o}(t),n=new Float32Array(2*r.length);for(let e=0;e<r.length;e++){const i=r[e],[o,s]=$n(t[2*i],t[2*i+1]);n[2*e]=o,n[2*e+1]=s}return{triangles:n,vertexCount:r.length}}(e),n=t.byteLength;Ln.useProgram(Dn),Ln.enable(Ln.BLEND),Ln.blendEquation(Ln.FUNC_ADD),Ln.blendFunc(Ln.ONE,Ln.ONE_MINUS_SRC_ALPHA),Ln.bindVertexArray(Nn),Ln.bindBuffer(Ln.ARRAY_BUFFER,Bn),n>Un?(Ln.bufferData(Ln.ARRAY_BUFFER,t,Ln.DYNAMIC_DRAW),Un=n):Ln.bufferSubData(Ln.ARRAY_BUFFER,0,t);const i=de.wash.color._array;Ln.uniformMatrix4fv(Gn.u_matrix,!1,Yn),Ln.uniform4f(Gn.u_color,i[0],i[1],i[2],de.wash.opacity/255),Ln.drawArrays(Ln.TRIANGLES,0,r),Ln.bindVertexArray(null),Ln.bindBuffer(Ln.ARRAY_BUFFER,null),at($,Ln)}(this),de.wash={...r}},ze.prototype.wash=function(e,t,r){de.wash?.isActive&&(this.origin&&(e=this.origin[0],t=this.origin[1],r=1),this.pol=this.genPol(e,t,r,0,-1),this.pol.wash())};let Hn=null,Wn=null;const jn=[];let qn=!1;const Kn=e=>!!e&&"function"==typeof e.begin&&"function"==typeof e.end&&!!e.renderer&&!!e.renderer._pInst,Jn=e=>"number"==typeof e&&Number.isFinite(e)&&e>0,Qn=e=>{try{return e()}catch(e){return}},ei=e=>!!e&&"function"==typeof e.pixelDensity&&"function"==typeof e.createFramebuffer&&Jn(Qn(()=>e.width))&&Jn(Qn(()=>e.height))&&"webgl2"===Qn(()=>e.webglVersion),ti=e=>(ei(e)&&(Hn=e),Hn),ri=()=>(Wn&&ei(Wn)?ti(Wn):null)||ti(window.self?.p5?.instance??null)||ti(V)||Hn,ni=(e=!1)=>{const t=((e=!1)=>{const t=ri();if(!e){if(!t)throw new Error("p5.brush could not resolve an active WEBGL sketch. Call brush.instance(p) and brush.load() after createCanvas(..., WEBGL).");return{renderer:t,width:t.width,height:t.height}}if(Kn(e)){const r=e.renderer._pInst;if(ti(r),t&&r!==t)throw new Error("p5.brush only supports p5.Framebuffer targets created from the active sketch");return{renderer:r,width:e.width,height:e.height}}return{renderer:e,width:e.width,height:e.height}})(e);if(j({Renderer:t.renderer}),ti(e?ri():$),"webgl2"!==$.webglVersion)throw new Error("p5.brush requires a WEBGL canvas");j({Cwidth:t.width,Cheight:t.height}),qn=!0},ii=e=>{j({Instance:e}),ti(e)},oi=()=>$??ri?.()??window.self?.p5?.instance??null,si={a:1,b:0,c:0,d:1,x:0,y:0},ai={a:1,b:0,c:0,d:1,x:0,y:0};function ci(){const e=oi();return!!e&&"function"==typeof e.angleMode&&e.angleMode()===e.RADIANS}function li(e,t,r){const n=t.isEnabled(t.DEPTH_TEST);n&&t.disable(t.DEPTH_TEST);const i=e._renderer.activeFramebuffer?.()??null;return i?._beforeEnd&&i._beforeEnd(),t.bindFramebuffer(t.FRAMEBUFFER,function(e){return e?"function"==typeof e._framebufferToBind?e._framebufferToBind():e.framebuffer??null:null}(r)),t.viewport(0,0,r.width*r.density,r.height*r.density),{hadDepthTest:n,previousTarget:i}}function ui(e,t,r){r?.hadDepthTest&&t.enable(t.DEPTH_TEST),r?.previousTarget?._beforeBegin?r.previousTarget._beforeBegin():(t.bindFramebuffer(t.FRAMEBUFFER,null),e._renderer.viewport(e._renderer._origViewport.width,e._renderer._origViewport.height),e._renderer._applyStencilTestIfClipping?.())}function hi(e,t){const r=e?._renderer;r&&(r._curShader=null,r._cachedBlendMode=null,r._isBlending=null,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,null),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA))}function fi(e,t,r){if(!t)return;if(r(t))return void t.draw(()=>e.clear());const n=t.drawingContext;n.save(),n.setTransform(1,0,0,1,0,0),n.clearRect(0,0,t.width,t.height),n.restore()}function mi(e,t,r){return e.loaded||(e.loaded=!0,e.shaderProgram??=e.createShader(t,r)),e.shaderProgram}function di(e,t,r,n,i){return t?.remove&&t.remove(),e.createFramebuffer({width:r,height:n,density:i,antialias:!1,depth:!1,stencil:!1})}const xi=(e,t)=>e.createFramebuffer(t);function gi({renderer:e,shader:t,source:r,mask:n,color:i,isBrushMask:o,Cwidth:s,Cheight:a,dirtyRect:c,targetIsFramebuffer:l,withScissor:u}){const h=e.drawingContext,f=h.isEnabled(h.DEPTH_TEST);h.disable(h.DEPTH_TEST),e.push(),e.translate(0,0),e.shader(t),t.setUniform("u_source",r),t.setUniform("u_targetIsFramebuffer",l),t.setUniform("u_isBrush",o),t.setUniform("u_mask",n),t.setUniform("u_color",i),u(h,c,()=>{e.fill(0,0,0,0),e.noStroke(),e.rect(-s/2,-a/2,s,a)},!l),e.pop(),e.resetShader(),f&&h.enable(h.DEPTH_TEST)}function pi(e){return e.isFramebufferTarget(e.sourceTarget)?((e.sourceTarget.renderer??e.renderer)._renderer?.flushDraw?.(),e.sourceFramebuffer.draw(()=>{e.withScissor(e.renderer.drawingContext,e.dirtyRect,()=>{e.renderer.clear(),e.renderer.push(),e.renderer.imageMode(e.renderer.CENTER),e.renderer.image(e.sourceTarget,0,0,e.Cwidth,e.Cheight),e.renderer.pop()},!1)}),e.sourceFramebuffer):(e.renderer._renderer?.flushDraw?.(),function({renderer:e,sourceFramebuffer:t,dirtyRect:r,getTargetPixelSize:n,toScissorBox:i}){const o=e.drawingContext,{width:s,height:a}=n(),c=r?i(r):null,l=o.getParameter(o.READ_FRAMEBUFFER_BINDING),u=o.getParameter(o.DRAW_FRAMEBUFFER_BINDING);return o.bindFramebuffer(o.READ_FRAMEBUFFER,null),o.bindFramebuffer(o.DRAW_FRAMEBUFFER,t.framebuffer),o.clearColor(0,0,0,0),o.clear(o.COLOR_BUFFER_BIT),o.blitFramebuffer(c?.x??0,c?.y??0,c?c.x+c.width:s,c?c.y+c.height:a,c?.x??0,c?.y??0,c?c.x+c.width:s,c?c.y+c.height:a,o.COLOR_BUFFER_BIT,o.NEAREST),o.bindFramebuffer(o.READ_FRAMEBUFFER,l),o.bindFramebuffer(o.DRAW_FRAMEBUFFER,u),t}(e))}const yi=()=>$??V??window.self?.p5?.instance;function vi(e,t){const r=yi();if(!r?.createGraphics)throw new Error("p5 stroke tip creation requires an active renderer or instance.");return r.createGraphics(e,t)}function bi(e,t){return new Promise((r,n)=>{const i=new window.Image;i.onload=()=>{const e=yi();if(!e?.createImage)return void n(new Error("p5 image tip loading requires an active renderer or instance."));const o=e.createImage(i.naturalWidth,i.naturalHeight);o.drawingContext.drawImage(i,0,0),t(o),r(o)},i.onerror=()=>n(new Error(`Failed to load image tip: ${e}`)),i.crossOrigin="anonymous",i.src=e})}const _i=[];var wi;wi={load:ni,syncDensity:()=>{const e=$.pixelDensity();return j({Density:e}),e},isCanvasReady:()=>{qn||ni()},instance:ii,activateInstance:e=>{jn.push(Wn),Wn=e,ii(e)},deactivateInstance:()=>{Wn=jn.pop()??null},getActiveFramebuffer:()=>$?._renderer?.activeFramebuffer?.()??null,isFramebufferTarget:Kn},W={...W,...wi},function(){var e;(e={usesRadians:ci,fromDegrees:e=>ci()?e*Math.PI/180:e,createColor:(...e)=>{const t=oi();if(!t?.color)throw new Error("p5 runtime color creation requires an active renderer.");return t.color(...e)},getAffineMatrix:()=>{const e=oi(),t=e?._renderer?.uModelMatrix?.mat4;return t?(ai.a=t[0],ai.b=t[1],ai.c=t[4],ai.d=t[5],ai.x=t[12],ai.y=t[13],ai):si}}).usesRadians&&(t=e.usesRadians),e.fromDegrees&&(r=e.fromDegrees),e.createColor&&(n=e.createColor),e.getAffineMatrix&&(i=e.getAffineMatrix)}(),function(){var e;e={beginDirectMaskDraw:li,endDirectMaskDraw:ui,resetDirectShaderTracking:hi},st={...st,...e}}(),function(){var e;e={clearTarget:fi,ensureBlendShaderProgram:mi,ensureBlendSourceFramebuffer:di,createFramebuffer:xi,runBlendShaderPass:gi,blitSourceToFramebuffer:pi},ie={...ie,...e}}(),function(){var e;e={createTipSurface:vi,loadImageTip:bi},nt={...nt,...e}}(),"undefined"!=typeof p5&&p5.registerAddon(function(e,t,r){r.presetup=function(){J(this)},r.predraw=function(){J(this)},r.postsetup=function(){K(this),pe(),Q()},r.postdraw=function(){K(this),pe(),Q()};const n=t.push,i=t.pop,o=t.randomSeed,s=t.noiseSeed;t.push=function(){n.call(this),be(),_i.push({fill:{...de.fill},wash:de.wash?{...de.wash}:null,stroke:{...de.stroke},hatch:{...de.hatch},mass:de.mass?{...de.mass}:null,field:{...de.field}})},t.pop=function(){i.call(this),function(){const e=_i.pop();e&&(de.stroke={...e.stroke},de.field={...e.field},de.hatch={...e.hatch},de.fill={...e.fill},e.wash&&(de.wash={...e.wash}),e.mass?de.mass={...e.mass}:de.mass&&(de.mass={...de.mass,isActive:!1,brush:null,color:null,options:{}}))}()},t.randomSeed=function(e){o.call(this,e),p(e)},t.noiseSeed=function(e){s.call(this,e),b(e)}});export{ze as Plot,Ye as Polygon,_e as Position,nr as add,Le as addField,Ge as arc,je as beginShape,Je as beginStroke,ir as box,Xe as circle,fr as clip,Ke as endShape,et as endStroke,Fe as field,sn as fill,an as fillBleed,cn as fillTexture,Pr as flowLine,Dr as hatch,Or as hatchArray,Nr as hatchStyle,K as instance,Tr as line,De as listFields,ye as load,Ur as mass,Qe as move,mr as noClip,Ie as noField,ln as noFill,Br as noHatch,Xr as noMass,hr as noStroke,Vn as noWash,b as noiseSeed,ar as pick,Oe as polygon,Ue as rect,ke as refreshField,sr as scaleBrushes,p as seed,ur as set,tt as spline,cr as stroke,lr as strokeWeight,qe as vertex,S as wRand,Zn as wash,Ne as wiggle};
+const e={a:1,b:0,c:0,d:1,x:0,y:0};let t=()=>!1,r=e=>e,n=()=>{throw new Error("No runtime color adapter registered.")},i=()=>e;const o=Math.sqrt(3),s=.5*(o-1),a=(3-o)/6,c=e=>0|Math.floor(e),l=new Float64Array([1,1,-1,1,1,-1,-1,-1,1,0,-1,0,1,0,-1,0,0,1,0,-1,0,1,0,-1]);function u(e=Math.random){const t=function(e){const t=new Uint8Array(512);for(let e=0;e<256;e++)t[e]=e;for(let r=0;r<255;r++){const n=r+~~(e()*(256-r)),i=t[r];t[r]=t[n],t[n]=i}for(let e=256;e<512;e++)t[e]=t[e-256];return t}(e),r=new Float64Array(t).map(e=>l[e%12*2]),n=new Float64Array(t).map(e=>l[e%12*2+1]);return function(e,i){let o=0,l=0,u=0;const h=(e+i)*s,f=c(e+h),m=c(i+h),d=(f+m)*a,x=e-(f-d),g=i-(m-d);let p,y;x>g?(p=1,y=0):(p=0,y=1);const v=x-p+a,b=g-y+a,_=x-1+2*a,w=g-1+2*a,R=255&f,A=255&m;let E=.5-x*x-g*g;if(E>=0){const e=R+t[A];E*=E,o=E*E*(r[e]*x+n[e]*g)}let M=.5-v*v-b*b;if(M>=0){const e=R+p+t[A+y];M*=M,l=M*M*(r[e]*v+n[e]*b)}let S=.5-_*_-w*w;if(S>=0){const e=R+1+t[A+1];S*=S,u=S*S*(r[e]*_+n[e]*w)}return 70*(o+l+u)}}function h(e,t){let r=new f(e),n=()=>r.next();return n.double=()=>n()+11102230246251565e-32*(2097152*n()|0),n.int32=()=>4294967296*r.next()|0,n.quick=n,n}class f{constructor(e){null==e&&(e=+new Date);let t=4022871197;function r(e){e=String(e);for(let r=0;r<e.length;r++){t+=e.charCodeAt(r);let n=.02519603282416938*t;t=n>>>0,n-=t,n*=t,t=n>>>0,n-=t,t+=4294967296*n}return 2.3283064365386963e-10*(t>>>0)}this.c=1,this.s0=r(" "),this.s1=r(" "),this.s2=r(" "),this.s0-=r(e),this.s0<0&&(this.s0+=1),this.s1-=r(e),this.s1<0&&(this.s1+=1),this.s2-=r(e),this.s2<0&&(this.s2+=1)}next(){let{c:e,s0:t,s1:r,s2:n}=this,i=2091639*t+2.3283064365386963e-10*e;return this.s0=r,this.s1=n,this.s2=i-(this.c=0|i)}copy(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}}let m=h(Math.random()),d=h(Math.random());const x=[],g=e=>x.push(e),p=e=>{m=h(e),d=h(`${e}:2`);for(const e of x)e()};let y=u(h(Math.random())),v=u(h(Math.random()));const b=e=>{y=u(h(e)),v=u(h(`${e}:2`))},_=(e=0,t=1)=>e+m()*(t-e),w=(e=0,t=1)=>e+d()*(t-e),R=e=>e[~~(m()*e.length)],A=(e,t)=>~~_(e,t),E=(e,t)=>~~w(e,t),M=(e=0,t=1)=>{const r=1-m(),n=m();return Math.sqrt(-2*Math.log(r))*D(360*n)*t+e},S=e=>{let t=0;const r=[];for(const n in e)t+=e[n],r.push({key:n,cumulative:t});const n=m()*t;for(const{key:e,cumulative:t}of r)if(n<t)return isNaN(e)?e:parseInt(e)},T=(e,t,r,n,i,o=!1)=>{let s=n+(e-t)/(r-t)*(i-n);return o?n<i?P(s,n,i):P(s,i,n):s},P=(e,t,r)=>Math.max(Math.min(e,r),t),C=e=>(e%=360)<0?e+360:e,k=1440,I=2*Math.PI/k,F=new Float32Array(k).fill(NaN),L=new Float32Array(k).fill(NaN),D=e=>{const t=~~(4*C(e));let r=F[t];return isNaN(r)&&(r=Math.cos(t*I),F[t]=r),r},N=e=>{const t=~~(4*C(e));let r=L[t];return isNaN(r)&&(r=Math.sin(t*I),L[t]=r),r},B=(e,r=!1)=>{if(r||t()){let t=180*e/Math.PI%360;return t<0?t+360:t}return e},Y=(e,r=!1)=>r||t()?180*e/Math.PI:e,z=(e,t,r,n,i)=>{let o=D(i),s=N(i);return{x:o*(r-e)+s*(n-t)+e,y:o*(n-t)-s*(r-e)+t}},O=(e,t,r,n)=>Math.hypot(r-e,n-t),U=(e,t,r,n)=>B(Math.atan2(-(n-t),r-e),!0),X=(e,t,r,n,i=!1)=>{let o=e.x,s=e.y,a=t.x,c=t.y,l=r.x,u=r.y,h=n.x,f=n.y;if(o===a&&s===c||l===h&&u===f)return!1;let m=a-o,d=c-s,x=h-l,g=f-u,p=g*m-x*d;if(0===p)return!1;let y=(x*(s-u)-g*(o-l))/p,v=(m*(s-u)-d*(o-l))/p;return!(!i&&(v<0||v>1))&&{x:o+y*m,y:s+y*d}};let Z,G,V,H,W,$={load:()=>{throw new Error("No target runtime adapter registered.")},syncDensity:()=>W,isCanvasReady:()=>{throw new Error("No target runtime adapter registered.")},instance:e=>{V=e},activateInstance:e=>{V=e},deactivateInstance:()=>{},getActiveFramebuffer:()=>null,isFramebufferTarget:()=>!1};function j(e){"Cwidth"in e&&(Z=e.Cwidth),"Cheight"in e&&(G=e.Cheight),"Instance"in e&&(V=e.Instance),"Renderer"in e&&(H=e.Renderer),"Density"in e&&(W=e.Density)}const q=()=>$.isCanvasReady(),K=e=>$.instance(e),J=e=>$.activateInstance(e),Q=()=>$.deactivateInstance(),ee=()=>$.getActiveFramebuffer(),te=e=>$.isFramebufferTarget(e),re=(e,t=0)=>e?{minX:e.minX-t,minY:e.minY-t,maxX:e.maxX+t,maxY:e.maxY+t}:null,ne=(e,t,r=!1)=>{const n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):(()=>{const r=document.createElement("canvas");return r.width=e,r.height=t,r})();return n.drawingContext=n.getContext("2d",r?{willReadFrequently:!0}:void 0),n};let ie={clearTarget:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendShaderProgram:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendSourceFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},createFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},runBlendShaderPass:()=>{throw new Error("No compositor runtime adapter registered.")},blitSourceToFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")}};const oe=(...e)=>ie.createFramebuffer(...e);let se=null,ae=null;const ce=e=>{((...e)=>{ie.clearTarget(...e)})(H,e,te)},le=()=>({width:Math.max(1,Math.round(Z*W)),height:Math.max(1,Math.round(G*W))}),ue=e=>{if(!e)return null;const{width:t,height:r}=le();return((e,t,r)=>{if(!e)return null;const n=Math.max(0,Math.floor(Math.min(e.minX,e.maxX))),i=Math.max(0,Math.floor(Math.min(e.minY,e.maxY))),o=Math.min(t,Math.ceil(Math.max(e.minX,e.maxX))),s=Math.min(r,Math.ceil(Math.max(e.minY,e.maxY)));return o<=n||s<=i?null:{minX:n,minY:i,maxX:o,maxY:s}})(e,t,r)},he=()=>{const{width:e,height:t}=le();return((e,t)=>({minX:0,minY:0,maxX:e,maxY:t}))(e,t)},fe=(e,t=!0)=>{const r=ue(e);if(!r)return null;const{height:n}=le();return{x:r.minX,y:t?n-r.maxY:r.minY,width:r.maxX-r.minX,height:r.maxY-r.minY}},me=(e,t,r,n=!0)=>{const i=fe(t,n);if(i){e.enable(e.SCISSOR_TEST),e.scissor(i.x,i.y,i.width,i.height);try{r()}finally{e.disable(e.SCISSOR_TEST)}}else r()},de={},xe=()=>{H?.loaded||(q(),ge.load())},ge={isBlending:!1,cachedColor:null,markDirtyRect(e,t){const r=ue(t);var n,i;e&&r&&(e.dirtyRect=(i=r,(n=e.dirtyRect)?i?{minX:Math.min(n.minX,i.minX),minY:Math.min(n.minY,i.minY),maxX:Math.max(n.maxX,i.maxX),maxY:Math.max(n.maxY,i.maxY)}:n:i),e.isDrawn=!0)},clearMask(e){if(!e)return;const t=e===this.glMask?se:ae;t?.clearMask?.(e,ce)},getCompositeRect(e,t){const r=t?se:ae;return r?.getCompositeRect?.(e,ee,he,re,ue)},load(){$.syncDensity();const e=!H.blendSourceFramebuffer||H.blendSourceFramebuffer.width!==Z||H.blendSourceFramebuffer.height!==G||"function"==typeof H.blendSourceFramebuffer.pixelDensity&&H.blendSourceFramebuffer.pixelDensity()!==W;((...e)=>{ie.ensureBlendShaderProgram(...e)})(H,"#version 300 es\n#define GLSLIFY 1\nout vec2 p;void main(){vec3 v=vec3(-1);v[gl_VertexID]=3.;p=v.xy;gl_Position=vec4(v.x,-v.y,0,1);}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nuniform bool u_isBrush;uniform bool u_targetIsFramebuffer;uniform sampler2D u_source;uniform sampler2D u_mask;uniform vec3 u_color;in vec2 p;out vec4 outColor;const int SPECTRAL_SIZE=38;const float SPECTRAL_GAMMA=2.4;const float SPECTRAL_EPSILON=0.0000000000000001;float spectral_uncompand(float x){return(x<0.04045)? x/12.92 : pow((x+0.055)/1.055,SPECTRAL_GAMMA);}float spectral_compand(float x){return(x<0.0031308)? x*12.92 : 1.055*pow(x,1.0/SPECTRAL_GAMMA)-0.055;}vec3 spectral_srgb_to_linear(vec3 srgb){return vec3(spectral_uncompand(srgb[0]),spectral_uncompand(srgb[1]),spectral_uncompand(srgb[2]));}vec3 spectral_linear_to_srgb(vec3 lrgb){return clamp(vec3(spectral_compand(lrgb[0]),spectral_compand(lrgb[1]),spectral_compand(lrgb[2])),0.,1.);}void spectral_linear_to_reflectance(vec3 lrgb,inout float R[SPECTRAL_SIZE]){float w=min(lrgb.r,min(lrgb.g,lrgb.b));lrgb-=w;float c=min(lrgb.g,lrgb.b);float m=min(lrgb.r,lrgb.b);float y=min(lrgb.r,lrgb.g);float r=min(max(0.0,lrgb.r-lrgb.b),max(0.0,lrgb.r-lrgb.g));float g=min(max(0.0,lrgb.g-lrgb.b),max(0.0,lrgb.g-lrgb.r));float b=min(max(0.0,lrgb.b-lrgb.g),max(0.0,lrgb.b-lrgb.r));R[0]=max(SPECTRAL_EPSILON,w*1.0011607271876400+c*0.9705850013229620+m*0.9906735573199880+y*0.0210523371789306+r*0.0315605737777207+g*0.0095560747554212+b*0.9794047525020140);R[1]=max(SPECTRAL_EPSILON,w*1.0011606515972800+c*0.9705924981434250+m*0.9906715249619790+y*0.0210564627517414+r*0.0315520718330149+g*0.0095581580120851+b*0.9794007068431300);R[2]=max(SPECTRAL_EPSILON,w*1.0011603192274700+c*0.9706253487298910+m*0.9906625823534210+y*0.0210746178695038+r*0.0315148215513658+g*0.0095673245444588+b*0.9793829034702610);R[3]=max(SPECTRAL_EPSILON,w*1.0011586727078900+c*0.9707868061190170+m*0.9906181076447950+y*0.0211649058448753+r*0.0313318044982702+g*0.0096129126297349+b*0.9792943649455940);R[4]=max(SPECTRAL_EPSILON,w*1.0011525984455200+c*0.9713686732282480+m*0.9904514808787100+y*0.0215027957272504+r*0.0306729857725527+g*0.0097837090401843+b*0.9789630146085700);R[5]=max(SPECTRAL_EPSILON,w*1.0011325252899800+c*0.9731632306212520+m*0.9898710814002040+y*0.0226738799041561+r*0.0286480476989607+g*0.0103786227058710+b*0.9778144666940430);R[6]=max(SPECTRAL_EPSILON,w*1.0010850066332700+c*0.9767402231587650+m*0.9882866087596400+y*0.0258235649693629+r*0.0246450407045709+g*0.0120026452378567+b*0.9747243211338360);R[7]=max(SPECTRAL_EPSILON,w*1.0009968788945300+c*0.9815876054913770+m*0.9842906927975040+y*0.0334879385639851+r*0.0192960753663651+g*0.0160977721473922+b*0.9671984823439730);R[8]=max(SPECTRAL_EPSILON,w*1.0008652515227400+c*0.9862802656529490+m*0.9739349056253060+y*0.0519069663740307+r*0.0142066612220556+g*0.0267061902231680+b*0.9490796575305750);R[9]=max(SPECTRAL_EPSILON,w*1.0006962900094000+c*0.9899491476891340+m*0.9418178384601450+y*0.1007490148334730+r*0.0102942608878609+g*0.0595555440185881+b*0.9008501289409770);R[10]=max(SPECTRAL_EPSILON,w*1.0005049611488800+c*0.9924927015384200+m*0.8173903261951560+y*0.2391298997068470+r*0.0076191460521811+g*0.1860398265328260+b*0.7631504454622400);R[11]=max(SPECTRAL_EPSILON,w*1.0003080818799200+c*0.9941456804052560+m*0.4324728050657290+y*0.5348043122727480+r*0.0058980410835420+g*0.5705798201161590+b*0.4659221716493190);R[12]=max(SPECTRAL_EPSILON,w*1.0001196660201300+c*0.9951839750332120+m*0.1384539782588700+y*0.7978075786430300+r*0.0048233247781713+g*0.8614677684002920+b*0.2012632804510050);R[13]=max(SPECTRAL_EPSILON,w*0.9999527659684070+c*0.9957567501108180+m*0.0537347216940033+y*0.9114498940673840+r*0.0042298748350633+g*0.9458790897676580+b*0.0877524413419623);R[14]=max(SPECTRAL_EPSILON,w*0.9998218368992970+c*0.9959128182867100+m*0.0292174996673231+y*0.9537979630045070+r*0.0040599171299341+g*0.9704654864743050+b*0.0457176793291679);R[15]=max(SPECTRAL_EPSILON,w*0.9997386095575930+c*0.9956061578345280+m*0.0213136517508590+y*0.9712416154654290+r*0.0043533695594676+g*0.9784136302844500+b*0.0284706050521843);R[16]=max(SPECTRAL_EPSILON,w*0.9997095516396120+c*0.9945976009618540+m*0.0201349530181136+y*0.9793031238075880+r*0.0053434425970201+g*0.9795890314112240+b*0.0205271767569850);R[17]=max(SPECTRAL_EPSILON,w*0.9997319302106270+c*0.9922157154923700+m*0.0241323096280662+y*0.9833801195075750+r*0.0076917201010463+g*0.9755335369086320+b*0.0165302792310211);R[18]=max(SPECTRAL_EPSILON,w*0.9997994363461950+c*0.9862364527832490+m*0.0372236145223627+y*0.9854612465677550+r*0.0135969795736536+g*0.9622887553978130+b*0.0145135107212858);R[19]=max(SPECTRAL_EPSILON,w*0.9999003303166710+c*0.9679433372645410+m*0.0760506552706601+y*0.9864350469766050+r*0.0316975442661115+g*0.9231215745131200+b*0.0136003508637687);R[20]=max(SPECTRAL_EPSILON,w*1.0000204065261100+c*0.8912850042449430+m*0.2053754719423990+y*0.9867382506701410+r*0.1078611963552490+g*0.7934340189431110+b*0.0133604258769571);R[21]=max(SPECTRAL_EPSILON,w*1.0001447879365800+c*0.5362024778620530+m*0.5412689034604390+y*0.9866178824450320+r*0.4638126031687040+g*0.4592701359024290+b*0.0135488943145680);R[22]=max(SPECTRAL_EPSILON,w*1.0002599790341200+c*0.1541081190018780+m*0.8158416850864860+y*0.9862777767586430+r*0.8470554052720110+g*0.1855741036663030+b*0.0139594356366992);R[23]=max(SPECTRAL_EPSILON,w*1.0003557969708900+c*0.0574575093228929+m*0.9128177041239760+y*0.9858605924440560+r*0.9431854093939180+g*0.0881774959955372+b*0.0144434255753570);R[24]=max(SPECTRAL_EPSILON,w*1.0004275378026900+c*0.0315349873107007+m*0.9463398301669620+y*0.9854749276762100+r*0.9688621506965580+g*0.0543630228766700+b*0.0148854440621406);R[25]=max(SPECTRAL_EPSILON,w*1.0004762334488800+c*0.0222633920086335+m*0.9599276963319910+y*0.9851769347655580+r*0.9780306674736030+g*0.0406288447060719+b*0.0152254296999746);R[26]=max(SPECTRAL_EPSILON,w*1.0005072096750800+c*0.0182022841492439+m*0.9662605952303120+y*0.9849715740141810+r*0.9820436438543060+g*0.0342215204316970+b*0.0154592848180209);R[27]=max(SPECTRAL_EPSILON,w*1.0005251915637300+c*0.0162990559732640+m*0.9693259700584240+y*0.9848463034157120+r*0.9839236237187070+g*0.0311185790956966+b*0.0156018026485961);R[28]=max(SPECTRAL_EPSILON,w*1.0005350960689600+c*0.0153656239334613+m*0.9708545367213990+y*0.9847753518111990+r*0.9848454841543820+g*0.0295708898336134+b*0.0156824871281936);R[29]=max(SPECTRAL_EPSILON,w*1.0005402209748200+c*0.0149111568733976+m*0.9716050665281280+y*0.9847380666252650+r*0.9852942758145960+g*0.0288108739348928+b*0.0157248764360615);R[30]=max(SPECTRAL_EPSILON,w*1.0005427281678400+c*0.0146954339898235+m*0.9719627697573920+y*0.9847196483117650+r*0.9855072952198250+g*0.0284486271324597+b*0.0157458108784121);R[31]=max(SPECTRAL_EPSILON,w*1.0005438956908700+c*0.0145964146717719+m*0.9721272722745090+y*0.9847110233919390+r*0.9856050715398370+g*0.0282820301724731+b*0.0157556123350225);R[32]=max(SPECTRAL_EPSILON,w*1.0005444821215100+c*0.0145470156699655+m*0.9722094177458120+y*0.9847066833006760+r*0.9856538499335780+g*0.0281988376490237+b*0.0157605443964911);R[33]=max(SPECTRAL_EPSILON,w*1.0005447695999200+c*0.0145228771899495+m*0.9722495776784240+y*0.9847045543930910+r*0.9856776850338830+g*0.0281581655342037+b*0.0157629637515278);R[34]=max(SPECTRAL_EPSILON,w*1.0005448988776200+c*0.0145120341118965+m*0.9722676219987420+y*0.9847035963093700+r*0.9856883918061220+g*0.0281398910216386+b*0.0157640525629106);R[35]=max(SPECTRAL_EPSILON,w*1.0005449625468900+c*0.0145066940939832+m*0.9722765094621500+y*0.9847031240775520+r*0.9856936646900310+g*0.0281308901665811+b*0.0157645892329510);R[36]=max(SPECTRAL_EPSILON,w*1.0005449892705800+c*0.0145044507314479+m*0.9722802433068740+y*0.9847029256150900+r*0.9856958798482050+g*0.0281271086805816+b*0.0157648147772649);R[37]=max(SPECTRAL_EPSILON,w*1.0005449969930000+c*0.0145038009464639+m*0.9722813248265600+y*0.9847028681227950+r*0.9856965214637620+g*0.0281260133612096+b*0.0157648801149616);}vec3 spectral_xyz_to_srgb(vec3 xyz){mat3 XYZ_RGB;XYZ_RGB[0]=vec3(3.2409699419045200,-1.537383177570090,-0.4986107602930030);XYZ_RGB[1]=vec3(-0.9692436362808790,1.875967501507720,0.0415550574071756);XYZ_RGB[2]=vec3(0.0556300796969936,-0.203976958888976,1.0569715142428700);float r=dot(XYZ_RGB[0],xyz);float g=dot(XYZ_RGB[1],xyz);float b=dot(XYZ_RGB[2],xyz);return spectral_linear_to_srgb(vec3(r,g,b));}vec3 spectral_reflectance_to_xyz(float R[SPECTRAL_SIZE]){vec3 xyz=vec3(0.);xyz+=R[0]*vec3(0.0000646919989576,0.0000018442894440,0.0003050171476380);xyz+=R[1]*vec3(0.0002194098998132,0.0000062053235865,0.0010368066663574);xyz+=R[2]*vec3(0.0011205743509343,0.0000310096046799,0.0053131363323992);xyz+=R[3]*vec3(0.0037666134117111,0.0001047483849269,0.0179543925899536);xyz+=R[4]*vec3(0.0118805536037990,0.0003536405299538,0.0570775815345485);xyz+=R[5]*vec3(0.0232864424191771,0.0009514714056444,0.1136516189362870);xyz+=R[6]*vec3(0.0345594181969747,0.0022822631748318,0.1733587261835500);xyz+=R[7]*vec3(0.0372237901162006,0.0042073290434730,0.1962065755586570);xyz+=R[8]*vec3(0.0324183761091486,0.0066887983719014,0.1860823707062960);xyz+=R[9]*vec3(0.0212332056093810,0.0098883960193565,0.1399504753832070);xyz+=R[10]*vec3(0.0104909907685421,0.0152494514496311,0.0891745294268649);xyz+=R[11]*vec3(0.0032958375797931,0.0214183109449723,0.0478962113517075);xyz+=R[12]*vec3(0.0005070351633801,0.0334229301575068,0.0281456253957952);xyz+=R[13]*vec3(0.0009486742057141,0.0513100134918512,0.0161376622950514);xyz+=R[14]*vec3(0.0062737180998318,0.0704020839399490,0.0077591019215214);xyz+=R[15]*vec3(0.0168646241897775,0.0878387072603517,0.0042961483736618);xyz+=R[16]*vec3(0.0286896490259810,0.0942490536184085,0.0020055092122156);xyz+=R[17]*vec3(0.0426748124691731,0.0979566702718931,0.0008614711098802);xyz+=R[18]*vec3(0.0562547481311377,0.0941521856862608,0.0003690387177652);xyz+=R[19]*vec3(0.0694703972677158,0.0867810237486753,0.0001914287288574);xyz+=R[20]*vec3(0.0830531516998291,0.0788565338632013,0.0001495555858975);xyz+=R[21]*vec3(0.0861260963002257,0.0635267026203555,0.0000923109285104);xyz+=R[22]*vec3(0.0904661376847769,0.0537414167568200,0.0000681349182337);xyz+=R[23]*vec3(0.0850038650591277,0.0426460643574120,0.0000288263655696);xyz+=R[24]*vec3(0.0709066691074488,0.0316173492792708,0.0000157671820553);xyz+=R[25]*vec3(0.0506288916373645,0.0208852059213910,0.0000039406041027);xyz+=R[26]*vec3(0.0354739618852640,0.0138601101360152,0.0000015840125870);xyz+=R[27]*vec3(0.0214682102597065,0.0081026402038399,0.0000000000000000);xyz+=R[28]*vec3(0.0125164567619117,0.0046301022588030,0.0000000000000000);xyz+=R[29]*vec3(0.0068045816390165,0.0024913800051319,0.0000000000000000);xyz+=R[30]*vec3(0.0034645657946526,0.0012593033677378,0.0000000000000000);xyz+=R[31]*vec3(0.0014976097506959,0.0005416465221680,0.0000000000000000);xyz+=R[32]*vec3(0.0007697004809280,0.0002779528920067,0.0000000000000000);xyz+=R[33]*vec3(0.0004073680581315,0.0001471080673854,0.0000000000000000);xyz+=R[34]*vec3(0.0001690104031614,0.0000610327472927,0.0000000000000000);xyz+=R[35]*vec3(0.0000952245150365,0.0000343873229523,0.0000000000000000);xyz+=R[36]*vec3(0.0000490309872958,0.0000177059860053,0.0000000000000000);xyz+=R[37]*vec3(0.0000199961492222,0.0000072209749130,0.0000000000000000);return xyz;}float KS(float R){return pow(1.0-R,2.0)/(2.0*R);}float KM(float KS){return 1.0+KS-sqrt(pow(KS,2.0)+2.0*KS);}vec3 spectral_mix(vec3 color1,float tintingStrength1,float factor1,vec3 color2,float tintingStrength2,float factor2){vec3 lrgb1=spectral_srgb_to_linear(color1);vec3 lrgb2=spectral_srgb_to_linear(color2);float R1[SPECTRAL_SIZE];float R2[SPECTRAL_SIZE];spectral_linear_to_reflectance(lrgb1,R1);spectral_linear_to_reflectance(lrgb2,R2);float luminance1=spectral_reflectance_to_xyz(R1)[1];float luminance2=spectral_reflectance_to_xyz(R2)[1];float R[SPECTRAL_SIZE];for(int i=0;i<SPECTRAL_SIZE;i++){float concentration1=pow(factor1,2.)*pow(tintingStrength1,2.)*luminance1;float concentration2=pow(factor2,2.)*pow(tintingStrength2,2.)*luminance2;float totalConcentration=concentration1+concentration2;float ksMix=0.;ksMix+=KS(R1[i])*concentration1;ksMix+=KS(R2[i])*concentration2;R[i]=KM(ksMix/totalConcentration);}return spectral_xyz_to_srgb(spectral_reflectance_to_xyz(R));}vec3 spectral_mix(vec3 color1,vec3 color2,float factor){return spectral_mix(color1,1.,1.-factor,color2,1.,factor);}vec3 spectral_mix(vec3 color1,float factor1,vec3 color2,float factor2){return spectral_mix(color1,1.,factor1,color2,1.,factor2);}const float GAMMA=2.4,EPSILON=0.0001;const float DARKEN_THRESHOLD=0.7;const float EDGE_MIN=0.05,EDGE_MAX=0.35;void main(void){vec2 uv=0.5*p+0.5;vec2 sourceUV=vec2(uv.x,1.0-uv.y);vec2 maskUV=u_targetIsFramebuffer ? vec2(uv.x,1.0-uv.y): uv;vec4 source=texture(u_source,sourceUV);vec4 maskColor=texture(u_mask,maskUV);if(maskColor.a==0.0){outColor=source;return;}vec4 pigment=vec4(u_color.xyz,1.0);if(maskColor.a>DARKEN_THRESHOLD){float blacken=0.5*(min(maskColor.a,1.0)-DARKEN_THRESHOLD);pigment=pigment*(1.0-blacken)-vec4(0.5)*blacken;pigment.rgb=max(pigment.rgb,vec3(0.0));}float mixIntensity=min(maskColor.a,1.0);if(!u_isBrush){vec2 texelSize=1.0/vec2(textureSize(u_mask,0));float scaledAlpha=maskColor.a*15.0;float blurEdge=0.0;for(int i=-2;i<=2;i+=2){for(int j=-2;j<=2;j+=2){vec2 neighborUV=maskUV+vec2(float(i),float(j))*texelSize;float neighborAlpha=texture(u_mask,neighborUV).a*15.0;blurEdge+=smoothstep(EDGE_MIN,EDGE_MAX,length(vec2(dFdx(neighborAlpha),dFdy(neighborAlpha))));}}blurEdge/=9.0;mixIntensity=clamp(maskColor.a+blurEdge*0.1,0.0,1.0);}vec3 bgColor=mix(vec3(1.0),source.rgb,source.a);outColor=vec4(spectral_mix(bgColor,pigment.rgb,mixIntensity),1.);}"),this.glMask=se?.ensureResources?.(H,Z,G,W);const t=ae?.ensureResources?.(H,Z,G,W,ce)??{mask:null,ctx:null};e&&(H.blendSourceFramebuffer=((...e)=>ie.ensureBlendSourceFramebuffer(...e))(H,H.blendSourceFramebuffer,Z,G,W)),this.mask=t.mask,this.ctx=t.ctx},blend(e=!1,t=!1){xe();const r=!0===this.isBrush,n=r?this.glMask:this.mask,i=r?this.mask:this.glMask,o=e?._array,s=!!o&&(this.cachedColor?.[0]!==o[0]||this.cachedColor?.[1]!==o[1]||this.cachedColor?.[2]!==o[2]||this.cachedColor?.[3]!==o[3]);!this.isBlending&&o&&(this.isBlending=!0,this.cachedColor=o,this.clearMask(this.glMask)),(t||s)&&(this.justChanged&&(this.applyShader(i,!r),this.justChanged=!1),this.isBlending&&this.applyShader(n,r),o&&(this.cachedColor=o),t&&(this.isBlending=!1,this.cachedColor=null))},applyShader(e,t){if(!e?.isDrawn)return;const r=this.getCompositeRect(e,t);if(!r)return void this.clearMask(e);H.drawingContext;const n=H.shaderProgram,i=ee(),o=((...e)=>ie.blitSourceToFramebuffer(...e))({renderer:H,sourceTarget:i??H,sourceFramebuffer:H.blendSourceFramebuffer,dirtyRect:r,isFramebufferTarget:te,Cwidth:Z,Cheight:G,getTargetPixelSize:le,toScissorBox:fe,withScissor:me}),s=!!i,a=(t?se:ae).getShaderMask(H,e,r,he,ce);((...e)=>{ie.runBlendShaderPass(...e)})({renderer:H,shader:n,source:o,mask:a,color:this.cachedColor,isBrushMask:t,Cwidth:Z,Cheight:G,dirtyRect:r,targetIsFramebuffer:s,withScissor:me}),this.clearMask(e)}},pe=()=>{xe(),ge.blend(!1,!0),ge.clearMask(ge.glMask),ge.clearMask(ge.mask),ge.justChanged=!1,ge.isBlending=!1,ge.isBrush=null,ge.cachedColor=null},ye=(e=!1)=>{((e=!1)=>{$.load(e)})(e),H.loaded&&ge.load()};let ve=!1;function be(){ve||(xe(),we=.01*Z,Re=-.5*Z,Ae=-.5*G,Ee=Math.round(2*Z/we),Me=Math.round(2*G/we),Le("hand",(e,t)=>{const r=w(.2,.8),n=E(5,10);return Be(t,(t,i)=>.5*n*N(r*i*t+E(15,25))*.2*D(e)+v(t,i)*n*.7)}),Le("curved",(e,t)=>{let r=E(-10,10);return E(0,100)%2==0&&(r*=-1),Be(t,(t,n)=>3*T(v(.02*t+.03*e,.02*n+.03*e),0,1,-r,r))}),Le("zigzag",(e,t)=>{let r=E(-30,-15)+Math.abs(44*N(e));E(0,100)%2==0&&(r*=-1);let n=r,i=0;for(let e=0;e<Ee;e++){for(let r=0;r<Me;r++)t[e][r]=i,i+=n,n*=-1;i+=n,n*=-1}return t}),Le("waves",(e,t)=>{const r=E(10,15)+5*N(e),n=E(3,6)+3*D(e),i=E(20,35);return Be(t,(e,t)=>N(r*e)*i*D(t*n)+E(-3,3))}),Le("seabed",(e,t)=>{const r=w(.4,.8),n=E(18,26);return Be(t,(t,i)=>1.1*n*N(r*i*t+E(15,20))*D(e))}),Le("spiral",(e,t)=>{const r=E(5,10),n=2*E(0,2)-1,i=E(65,80),o=Array.from({length:r},()=>({x:w(.1,.9)*Ee,y:w(.1,.9)*Me}));return Be(t,(e,t)=>{let r=0,s=0;for(const a of o){const o=e-a.x,c=t-a.y,l=1/(o*o+c*c+1),u=Math.atan2(c,o)*(180/Math.PI),h=n*(u+i)*Math.PI/180;r+=l*Math.cos(h),s+=l*Math.sin(h)}return Math.atan2(s,r)*(180/Math.PI)})}),Le("columns",(e,t)=>{const r=E(3,8),n=E(25,45);return Be(t,(e,t)=>N(e*r)*n)}),ve=!0)}class _e{constructor(e,t){be();const r=i();this.mx=r.x,this.my=r.y,this.update(e,t),this.plotted=0}update(e,t){this.x=e,this.y=t,de.field.isActive&&(this.colIdx=Math.round((e+this.mx-Re)/we),this.rowIdx=Math.round((t+this.my-Ae)/we))}reset(){this.plotted=0}isIn(){return de.field.isActive?_e.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const e=Z,t=G,r=this.x+this.mx,n=this.y+this.my;return r>=-.3*e&&r<=1.3*e&&n>=-.3*t&&n<=1.3*t}angle(e=!1){return de.field.isActive&&(e||this.isIn())?Se.get(de.field.current).field[this.colIdx][this.rowIdx]*de.field.wiggle:0}moveTo(e,t,r=1){this.movePos(Y(e),t,r)}_moveToDegrees(e,t,r=1){this.movePos(e,t,r)}plotTo(e,t,r,n=1,i=void 0){this.movePos(e,t,r,n,i)}movePos(e,t,r,n=!1,i=void 0){const o=n||1;if(!this.isIn())return void(this.plotted+=r/o);const s=t/r,a=de.field.isActive,c=!!n;for(let t=0;t<s;t++){const n=c&&void 0!==i&&0===t?i:c?e.angle(this.plotted):e,s=(a?this.angle(!0):0)-n;this.update(this.x+r*D(s),this.y+r*N(s)),this.plotted+=r/o}}static getRowIndex(e,t=1){const r=e+i().y-Ae;return Math.round(r/we/t)}static getColIndex(e,t=1){const r=e+i().x-Re;return Math.round(r/we/t)}static isIn(e,t){return e>=0&&t>=0&&e<Ee&&t<Me}}de.field={isActive:!1,current:null,wiggle:1};let we,Re,Ae,Ee,Me,Se=new Map;const Te=new Set(["degrees","radians"]);function Pe(e={}){const t=("string"==typeof e?{angleMode:e}:e||{}).angleMode??"degrees";if(!Te.has(t))throw new Error(`Invalid field angle mode "${t}". Use "degrees" or "radians".`);return t}function Ce(e,t){return function(e,t){if("radians"!==t)return e;for(let t=0;t<e.length;t++)for(let r=0;r<e[t].length;r++)e[t][r]=Y(e[t][r],!0);return e}(e.gen(t,new Array(Ee).fill(null).map(()=>new Float32Array(Me))),e.angleMode)}function ke(e=0){if(!de.field.isActive||!de.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const t=Se.get(de.field.current);t.field=Ce(t,e)}function Ie(e){if(de.field.wiggle||(de.field.wiggle=1),be(),!Se.has(e))throw new Error(`Field "${e}" does not exist. Available fields: ${Array.from(Se.keys()).join(", ")}.`);de.field.isActive=!0,de.field.current=e;const t=Se.get(e);t.field||(t.field=Ce(t,0))}function Fe(){be(),de.field.isActive=!1}function Le(e,t,r={}){Se.set(e,{gen:t,field:null,angleMode:Pe(r)})}function De(){return be(),Array.from(Se.keys())}function Ne(e=1){Ie("hand"),de.field.wiggle=e}function Be(e,t){for(let r=0;r<Ee;r++)for(let n=0;n<Me;n++)e[r][n]=t(r,n);return e}class Ye{constructor(e,t=!1){this.a=e,this.vertices=t?e:e.map(([e,t])=>({x:e,y:t})),this.sides=this.vertices.map((e,t,r)=>[e,r[(t+1)%r.length]]),this._intersectionCache={}}intersect(e){const t=`${e.point1.x},${e.point1.y}-${e.point2.x},${e.point2.y}`;if(this._intersectionCache[t])return this._intersectionCache[t];const r=[];for(const[t,n]of this.sides){const i=X(e.point1,e.point2,t,n);i&&r.push(i)}return this._intersectionCache[t]=r,r}show(){de.wash&&this.wash(),de.fill&&this.fill(),de.mass&&this.mass(),de.hatch&&this.hatch(),de.stroke&&this.draw()}}class ze{constructor(e){this.segments=[],this.angles=[],this.pres=[],this.type=e,this.dir=0,this.calcIndex(0),this.pol=!1}addSegment(e=0,t=0,r=1,n=!1){this.angles.length>0&&this.angles.pop(),e=n?(e%360+360)%360:B(e),this.angles.push(e,e),this.pres.push(r),this.segments.push(t),this.length=this.segments.reduce((e,t)=>e+t,0)}endPlot(e=0,t=1,r=!1){e=r?(e%360+360)%360:B(e),this.angles[this.angles.length-1]=e,this.pres.push(t)}rotate(e){this.dir=B(e)}pressure(e){return e>this.length?this.pres[this.pres.length-1]:this.curving(this.pres,e)}angle(e){return e>this.length?this.angles[this.angles.length-1]:(this.calcIndex(e),"curve"===this.type?this.curving(this.angles,e)+this.dir:this.angles[this.index]+this.dir)}curving(e,t){let r=e[this.index],n=e[this.index+1]??r;return Math.abs(n-r)>180&&(n>r?n=-(360-n):r=-(360-r)),T(t-this.suma,0,this.segments[this.index],r,n,!0)}calcIndex(e){this.index=-1,this.suma=0;let t=0;for(;t<=e;)this.suma=t,t+=this.segments[this.index+1],this.index++;return this.index}genPol(e,t,r=1,n){be();const i=n<0?4:1,o=[],s=Math.round(this.length/i),a=new _e(e+Z/2,t+G/2);let c=0,l=0;for(let e=0;e<s;e++){a.plotTo(this,i,i);const e=this.calcIndex(a.plotted);c+=i,(c>=(n<=0?8:Math.max(this.segments[e]*n*w(.7,1.3),20))||e>=l)&&a.x&&(o.push([a.x-Z/2,a.y-G/2]),c=0,e>=l&&l++)}return new Ye(o)}show(e,t,r=1){de.wash&&this.wash(e,t,r),de.fill&&this.fill(e,t,r),de.mass&&this.mass(e,t,r),de.hatch&&this.hatch(e,t,r),de.stroke&&this.draw(e,t,r)}}function Oe(e){new Ye(e).show()}function Ue(e,t,r,n,i="corner"){"center"===i&&(e-=r/2,t-=n/2),je(0),qe(e,t),qe(e+r,t),qe(e+r,t+n),qe(e,t+n),Ke(!0)}function Xe(e,t,r,n=!1){const i=new ze("curve"),o=Math.PI*r,s=w(0,360),a=n?()=>1+.2*n*w():()=>1;for(let e=0;e<4;e++){const t=-90*e+s;i.addSegment(t*a(),o/2*a(),1,!0)}if(n){const e=n*E(-5,5);i.addSegment(s,Math.abs(e)*(Math.PI/180)*r,1,!0),i.endPlot(e+s,1,!0)}else i.endPlot(s,1,!0);const c=e-r*N(s),l=t-r*D(-s);i.show(c,l,1)}function Ze(e,t,r,n,i){const o=Y(n),s=((Y(i)-o)%360+360)%360;if(0===s)return;const a=new ze("curve"),c=Math.max(1,Math.ceil(s/90)),l=s/c,u=Math.PI*r*l/180;for(let e=0;e<c;e++)a.addSegment(o+e*l+90,u,1,!0);a.endPlot(o+s+90,1,!0);const h=e+r*D(o),f=t-r*N(o);a.draw(h,f,1)}let Ge,Ve,He,We;class $e{constructor(){this.isClosed=!1,this.curvature=Ve,this.vert=[]}vertex(e,t,r){this.vert.push([e,t,r])}show(){rt(this.vert,this.curvature,this.isClosed).show()}}function je(e=0){Ve=P(e,0,1),Ge=new $e}function qe(e,t,r=1){if(!Ge)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");Ge.vertex(e,t,r)}function Ke(e=!1){if(!Ge)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(Ge.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");e&&(Ge.vertex(...Ge.vert[0]),Ge.isClosed=!0),Ge.show(),Ge=!1}function Je(e,t,r){if("curve"!==e&&"segments"!==e)throw new Error(`beginStroke() type must be "curve" or "segments", got "${e}".`);We=[t,r],He=new ze(e)}function Qe(e,t,r){if(!He)throw new Error("move() called without beginStroke(). Call beginStroke() first.");He.addSegment(e,t,r)}function et(e,t){if(!He)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");He.endPlot(e,t),He.draw(We[0],We[1],1),He=!1}function tt(e,t=.5){if(!e||e.length<2)throw new Error("spline() requires at least 2 points. Each point should be [x, y, pressure].");rt(e,t).draw()}function rt(e,t=.5,r=!1){const n=new ze(0===t?"segments":"curve"),i=2*Math.PI;if(r&&0!==t&&e.push(e[1]),e&&e.length>0){let o,s,a,c=0;for(let l=0;l<e.length-1;l++)if(t>0&&l<e.length-2){const u=e[l],h=e[l+1],f=e[l+2],m=O(u[0],u[1],h[0],h[1]),d=O(h[0],h[1],f[0],f[1]),x=U(u[0],u[1],h[0],h[1]),g=U(h[0],h[1],f[0],f[1]),p=t*Math.min(m,d,.5*Math.min(m,d)),y=Math.max(m,d),v=m-p,b=d-p;if(Math.floor(x)===Math.floor(g)){const t=r&&0===l?0:m-c,i=r?0===l?0:d-a:d;n.addSegment(x,t,u[2],!0),l===e.length-3&&n.addSegment(g,i,h[2],!0),c=0,0===l&&(o=m,a=p,s=e[1],c=0)}else{const t={x:h[0]-p*D(-x),y:h[1]-p*N(-x)},f={x:t.x+y*D(90-x),y:t.y+y*N(90-x)},m={x:h[0]+p*D(-g),y:h[1]+p*N(-g)},d={x:m.x+y*D(90-g),y:m.y+y*N(90-g)},_=X(t,f,m,d,!0),w=O(t.x,t.y,_.x,_.y),R=O(t.x,t.y,m.x,m.y)/2,A=i*w*(2*Math.asin(R/w)*(180/Math.PI))/360,E=r&&0===l?0:v-c,M=l===e.length-3?r?o-p:b:0;n.addSegment(x,E,u[2],!0),n.addSegment(x,isNaN(A)?0:A,u[2],!0),n.addSegment(g,M,h[2],!0),c=p,0===l&&(o=v,a=p,s=[t.x,t.y])}l===e.length-3&&n.endPlot(g,h[2],!0)}else if(0===t){const t=e[l],r=e[l+1],i=O(t[0],t[1],r[0],r[1]),o=U(t[0],t[1],r[0],r[1]);n.addSegment(o,i,r[2],!0),l===e.length-2&&n.endPlot(o,1,!0)}n.origin=r&&0!==t?s:e[0]}return n}let nt={createTipSurface:()=>{throw new Error("No stroke runtime adapter registered.")},loadImageTip:()=>{throw new Error("No stroke runtime adapter registered.")}},it=!1;const ot=(e,t,r)=>{const n=e.createProgram();for(let[i,o]of[[e.VERTEX_SHADER,t],[e.FRAGMENT_SHADER,r]]){const t=e.createShader(i);e.shaderSource(t,o),e.compileShader(t),e.attachShader(n,t)}return e.linkProgram(n),n};let st={beginDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},endDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},resetDirectShaderTracking:()=>{}};const at=(e,t)=>st.resetDirectShaderTracking(e,t);let ct,lt,ut,ht,ft,mt=!1,dt=0,xt=0,gt=null;const pt={},yt={};let vt=1,bt=0,_t=0,wt=1,Rt=0,At=0,Et=0,Mt=0,St=1,Tt=1,Pt=new Float32Array(8192),Ct=0,kt=2048,It=32768,Ft=null,Lt=null,Dt=null,Nt=null,Bt=null;const Yt={},zt={};let Ot=0,Ut=new Float32Array(1280),Xt=0,Zt=256,Gt=null;const Vt=new Map,Ht=new Float32Array([-1,-1,1,-1,-1,1,1,1]);function Wt(){return lt}function $t(){return((e,t,r)=>st.beginDirectMaskDraw(e,t,r))(H,ct,ge.glMask)}function jt(e){((e,t,r)=>{st.endDirectMaskDraw(e,t,r)})(H,ct,e)}function qt(e,t,r,n,i){return e?(t<e.minX&&(e.minX=t),r<e.minY&&(e.minY=r),n>e.maxX&&(e.maxX=n),i>e.maxY&&(e.maxY=i),e):{minX:t,minY:r,maxX:n,maxY:i}}function Kt(e,t,r,n){if(Ct>=kt){kt*=2;const e=new Float32Array(4*kt);e.set(Pt),Pt=e}const i=e-Et,o=t-Mt,s=4*Ct,a=vt*i+_t*o+Rt+Et,c=bt*i+wt*o+At+Mt,l=Tt*r*St/2;Pt[s]=a,Pt[s+1]=c,Pt[s+2]=l,Pt[s+3]=n/255;const u=a*Tt,h=c*Tt;Ft=qt(Ft,u-l-1,h-l-1,u+l+1,h+l+1),Ct++}function Jt(e,t){if(0===Xt)return;ge.glMask.isDrawn=!0;const r=$t();let n=Vt.get(t);n||(n=ct.createTexture(),ct.bindTexture(ct.TEXTURE_2D,n),ct.texImage2D(ct.TEXTURE_2D,0,ct.RGBA,ct.RGBA,ct.UNSIGNED_BYTE,e.canvas),ct.texParameteri(ct.TEXTURE_2D,ct.TEXTURE_MIN_FILTER,ct.LINEAR),ct.texParameteri(ct.TEXTURE_2D,ct.TEXTURE_MAG_FILTER,ct.LINEAR),ct.texParameteri(ct.TEXTURE_2D,ct.TEXTURE_WRAP_S,ct.CLAMP_TO_EDGE),ct.texParameteri(ct.TEXTURE_2D,ct.TEXTURE_WRAP_T,ct.CLAMP_TO_EDGE),Vt.set(t,n)),ct.useProgram(Lt),ct.enable(ct.BLEND),ct.blendFunc(ct.ONE_MINUS_DST_ALPHA,ct.ONE),ct.activeTexture(ct.TEXTURE0),ct.bindTexture(ct.TEXTURE_2D,n),ct.uniform1i(zt.u_tex,0);const i=de.stroke.color._array;ct.uniform4f(zt.u_color,...i),ct.uniformMatrix4fv(zt.u_proj,!1,Wt()),ct.bindVertexArray(Dt),ct.bindBuffer(ct.ARRAY_BUFFER,Bt);const o=5*Xt*4,s=Ut.subarray(0,5*Xt);o>Ot?(ct.bufferData(ct.ARRAY_BUFFER,Ut,ct.DYNAMIC_DRAW),Ot=Ut.byteLength):ct.bufferSubData(ct.ARRAY_BUFFER,0,s),ct.drawArraysInstanced(ct.TRIANGLE_STRIP,0,4,Xt),ct.bindVertexArray(null),ct.bindTexture(ct.TEXTURE_2D,null),jt(r),Gt&&(ge.markDirtyRect(ge.glMask,Gt),Gt=null),Xt=0,at(H,ct)}it||(se={ensureResources:function(e,t,r,n){return function(e,t,r,n){return!e.glMask||e.glMask.width!==t||e.glMask.height!==r||"function"==typeof e.glMask.pixelDensity&&e.glMask.pixelDensity()!==n}(e,t,r,n)&&(e.glMask?.remove&&e.glMask.remove(),e.glMask=oe(e,{width:t,height:r,density:n,antialias:!1,depth:!1,stencil:!1})),e.glMask.dirtyRect??=null,e.glMask.isDrawn??=!1,e.glMask},clearMask:function(e,t){e&&(t(e),e.isDrawn=!1,e.dirtyRect=null)},getCompositeRect:function(e,t,r,n,i){return e?e.dirtyRect?t()?r():i(n(e.dirtyRect,2)):r():null},getShaderMask:function(e,t){return t}},it=!0),de.stroke={color:null,weight:1,type:"HB",isActive:!1,opacity:1};let Qt=new Map;const er={offset:.08,scale:.08,warp:.06,tilt:.06};function tr(){return{...de.stroke}}function rr(e){de.stroke={...e}}function nr(e,t){if(t.type=["marker","custom","image","spray"].includes(t.type)?t.type:"default",void 0===t.markerTip&&(t.markerTip=!0),void 0===t.noise&&(t.noise=.3),t.noise=Math.max(0,Math.min(1,t.noise)),void 0!==t.vibration&&void 0===t.scatter&&(t.scatter=t.vibration),void 0!==t.definition&&void 0===t.sharpness&&(t.sharpness=t.definition),void 0!==t.quality&&void 0===t.grain&&(t.grain=t.quality),t.pressure=function(e){if(!e)return e;if("function"==typeof e)return{type:"custom",min_max:[0,1],curve:e,variation:{...er}};if("object"==typeof e&&!Array.isArray(e)){if("custom"===e.type||"custom"===e.mode){const{mode:t,...r}=e;return{...r,type:"custom",variation:{...er,...r.variation??{}}}}return"gaussian"===e.type||"gaussian"===e.mode||Array.isArray(e.curve)&&Array.isArray(e.min_max)?{...e,type:"gaussian",curve:e.curve,min_max:e.min_max}:e}if(Array.isArray(e)){const[t,r,n]=2===e.length?[e[0],(e[0]+e[1])/2,e[1]]:e,i=Math.min(t,r,n),o=Math.max(t,r,n),s=o-i||1,[a,c,l]=[(t-i)/s,(r-i)/s,(n-i)/s];return{type:"custom",min_max:[i,o],variation:{...er},curve:e=>e<.5?a+(c-a)*e*2:c+(l-c)*(e-.5)*2}}}(t.pressure),"custom"===t.type){if("function"!=typeof t.tip)throw new Error(`Brush "${e}" is type "custom" but is missing a tip function.`);const r=`custom::${e}`;!function(e){const t=Vt.get(e);t&&ct&&ct.deleteTexture(t),Vt.delete(e)}(r);const n=nt.createTipSurface(500,500);return n.pixelDensity(1),n.background(255),n.noSmooth(),n.push(),n.translate(250,250),n.scale(5),n.noStroke(),t.tip(n),n.pop(),Dr.imageToWhite(n),Dr.tips.set(r,n),t.tipKey=r,void Qt.set(e,{param:t,colors:[],buffers:[]})}if("image"===t.type){if(!t.image||!t.image.src)throw new Error(`Brush "${e}" is type "image" but is missing params.image.src. Example: image: { src: "./tip.jpg" }`);return Dr.add(t.image.src),Qt.set(e,{param:t,colors:[],buffers:[]}),Dr.load()}Qt.set(e,{param:t,colors:[],buffers:[]})}function ir(){return[...Qt.keys()]}function or(e){return Qt.get(e)?.param??null}function sr(e){for(const{param:t}of Qt.values())t&&(t.weight*=e,t.scatter*=e,t.spacing*=e)}function ar(e){if(!Qt.has(e))throw new Error(`Brush "${e}" not found. Available brushes: ${[...Qt.keys()].join(", ")}.`);de.stroke.type=e}function cr(e,t,r){q(),de.stroke.color=n(...arguments),de.stroke.isActive=!0}function lr(e){de.stroke.weight=e}function ur(e,t,r=1){ar(e),cr(t),lr(r)}function hr(){de.stroke.isActive=!1}function fr(e){return q(),e}function mr(){}let dr,xr,gr,pr,yr=0;const vr={};function br(e,t,r,n=!1){!function(){const e=i();vt=e.a,bt=e.b,_t=e.c,wt=e.d,Rt=e.x,At=e.y,Et=Z/2,Mt=G/2,St=Math.sqrt(vt*vt+bt*bt),Tt=W}(),dr=new _e(e+Z/2,t+G/2),xr=r,gr=n,gr&&gr.calcIndex(0)}const _r=[];function wr(e,t){t||(pr=e),function(){vr.seed=999999*_();const{param:e}=Qt.get(de.stroke.type)??{};if(!e)return;vr.p=e;const{pressure:t}=e;if(vr.isCustomPressure="custom"===t.type,vr.a=vr.isCustomPressure?0:_(-1,1),vr.b=vr.isCustomPressure?0:_(1,1.5),vr.isCustomPressure){const e=t.variation??er;vr.cp=_(-e.offset,e.offset),vr.ct=_(-e.warp,e.warp),vr.cs=_(1-e.scale,1+e.scale),vr.ck=_(-e.tilt,e.tilt)}else vr.cp=_(3,3.5),vr.ct=0,vr.cs=1,vr.ck=0;[vr.min,vr.max]=t.min_max,vr.noiseoffset=.05*vr.p.noise,gr||(vr.cos=D(pr),vr.sin=N(pr)),function(){xe(),function(){const e=H?.glMask;e&&(gt=e,gt.dirtyRect??=null,gt.isDrawn??=!1,ge.glMask=gt)}();const e=H.drawingContext,t=!mt||ct!==e;(t||dt!==Z||xt!==G)&&(lt=new Float32Array([2/Z,0,0,0,0,2/G,0,0,0,0,1,0,-1,-1,0,1]),dt=Z,xt=G),t&&(ct=e,ft=ot(ct,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_position;in float a_radius;in float a_alpha;uniform mat4 u_matrix;out float v_alpha;void main(){gl_Position=u_matrix*vec4(a_position,0.0,1.0);v_alpha=a_alpha;gl_PointSize=a_radius*2.0;}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin float v_alpha;out vec4 outColor;uniform vec4 u_color;void main(){vec2 v=gl_PointCoord-vec2(0.5);float f=length(v);float a=fwidth(f);f=1.0-smoothstep(0.5-a,0.5+a,f);if(f<0.01){discard;}outColor=vec4(u_color.xyz,v_alpha*f);}"),ct.useProgram(ft),ct.enable(ct.BLEND),ct.blendFunc(ct.ONE_MINUS_DST_ALPHA,ct.ONE),["a_position","a_radius","a_alpha"].forEach(e=>pt[e]=ct.getAttribLocation(ft,e)),["u_matrix","u_color"].forEach(e=>yt[e]=ct.getUniformLocation(ft,e)),ut=ct.createVertexArray(),ct.bindVertexArray(ut),ht=ct.createBuffer(),ct.bindBuffer(ct.ARRAY_BUFFER,ht),ct.bufferData(ct.ARRAY_BUFFER,Pt.byteLength,ct.DYNAMIC_DRAW),It=Pt.byteLength,ct.enableVertexAttribArray(pt.a_position),ct.vertexAttribPointer(pt.a_position,2,ct.FLOAT,!1,16,0),ct.enableVertexAttribArray(pt.a_radius),ct.vertexAttribPointer(pt.a_radius,1,ct.FLOAT,!1,16,8),ct.enableVertexAttribArray(pt.a_alpha),ct.vertexAttribPointer(pt.a_alpha,1,ct.FLOAT,!1,16,12),ct.bindVertexArray(null),Vt.clear(),Lt=ot(ct,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_corner;in vec2 a_pos;in float a_size;in float a_angle;in float a_alpha;uniform mat4 u_proj;out vec2 v_uv;out float v_alpha;void main(){float c=cos(a_angle);float s=sin(a_angle);vec2 rotated=vec2(c*a_corner.x-s*a_corner.y,s*a_corner.x+c*a_corner.y);gl_Position=u_proj*vec4(a_pos+rotated*a_size,0.0,1.0);v_uv=a_corner*0.5+0.5;v_alpha=a_alpha;}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin vec2 v_uv;in float v_alpha;uniform sampler2D u_tex;uniform vec4 u_color;out vec4 outColor;void main(){float inkAlpha=texture(u_tex,v_uv).a;if(inkAlpha<0.01)discard;outColor=vec4(u_color.rgb,inkAlpha*v_alpha);}"),["a_corner","a_pos","a_size","a_angle","a_alpha"].forEach(e=>Yt[e]=ct.getAttribLocation(Lt,e)),["u_proj","u_color","u_tex"].forEach(e=>zt[e]=ct.getUniformLocation(Lt,e)),Dt=ct.createVertexArray(),ct.bindVertexArray(Dt),Nt=ct.createBuffer(),ct.bindBuffer(ct.ARRAY_BUFFER,Nt),ct.bufferData(ct.ARRAY_BUFFER,Ht,ct.STATIC_DRAW),ct.enableVertexAttribArray(Yt.a_corner),ct.vertexAttribPointer(Yt.a_corner,2,ct.FLOAT,!1,0,0),Bt=ct.createBuffer(),ct.bindBuffer(ct.ARRAY_BUFFER,Bt),ct.bufferData(ct.ARRAY_BUFFER,Ut.byteLength,ct.DYNAMIC_DRAW),Ot=Ut.byteLength,ct.enableVertexAttribArray(Yt.a_pos),ct.vertexAttribPointer(Yt.a_pos,2,ct.FLOAT,!1,20,0),ct.vertexAttribDivisor(Yt.a_pos,1),ct.enableVertexAttribArray(Yt.a_size),ct.vertexAttribPointer(Yt.a_size,1,ct.FLOAT,!1,20,8),ct.vertexAttribDivisor(Yt.a_size,1),ct.enableVertexAttribArray(Yt.a_angle),ct.vertexAttribPointer(Yt.a_angle,1,ct.FLOAT,!1,20,12),ct.vertexAttribDivisor(Yt.a_angle,1),ct.enableVertexAttribArray(Yt.a_alpha),ct.vertexAttribPointer(Yt.a_alpha,1,ct.FLOAT,!1,20,16),ct.vertexAttribDivisor(Yt.a_alpha,1),ct.bindVertexArray(null),mt=!0)}();const r=!0!==ge.isBrush;ge.isBrush=!0,r&&(ge.justChanged=!0),ge.blend(de.stroke.color),vr.alpha=["default","spray"].includes(vr.p.type)?vr.p.opacity:vr.p.opacity/Math.min(de.stroke.weight,1.3),vr.overscan=function(){const e=Math.max(1,vr.max??1),t=de.stroke.weight*vr.p.scatter,r=de.stroke.weight*vr.p.weight*e;return Math.max(8,1.5*t+.75*r)}(),vr.drawFn="spray"===vr.p.type?Mr:"marker"===vr.p.type?Sr:"custom"===vr.p.type||"image"===vr.p.type?Tr:Pr,Cr()}();const r=vr.p?.spacing??1,n=Math.round(xr*(t?e:1)/r);vr.pressureCount=10,vr.cachedPressure=void 0,vr.lineNoiseCount=5,vr.cachedLineNoise=void 0;const i=2*n;for(;_r.length<i;)_r.push(M());for(let i=0;i<n;i++)t&&(yr=gr.angle(dr.plotted)),Rr(),t?dr.plotTo(gr,r,r,e,yr):dr._moveToDegrees(e,r,r);!function(){Cr(),function(){if(0===Ct)return;ge.glMask.isDrawn=!0;const e=$t(),t=de.stroke.color._array;ct.useProgram(ft),ct.enable(ct.BLEND),ct.blendFunc(ct.ONE_MINUS_DST_ALPHA,ct.ONE),ct.bindVertexArray(ut),ct.bindBuffer(ct.ARRAY_BUFFER,ht);const r=16*Ct,n=Pt.subarray(0,4*Ct);r>It?(ct.bufferData(ct.ARRAY_BUFFER,Pt,ct.DYNAMIC_DRAW),It=Pt.byteLength):ct.bufferSubData(ct.ARRAY_BUFFER,0,n),ct.uniform4f(yt.u_color,...t),ct.uniformMatrix4fv(yt.u_matrix,!1,Wt()),ct.drawArrays(ct.POINTS,0,Ct),ct.bindVertexArray(null),jt(e),Ft&&(ge.markDirtyRect(ge.glMask,Ft),Ft=null),Ct=0,at(H,ct)}();const e=vr.p?.type;"image"===e?Jt(Dr.tips.get(vr.p.image.src),vr.p.image.src):"custom"===e&&Jt(Dr.tips.get(vr.p.tipKey),vr.p.tipKey)}()}function Rr(){const e=Ar(),t=((vr.lineNoiseCount>=10||void 0===vr.cachedLineNoise)&&(vr.cachedLineNoise=T(y(vr.seed+.01*dr.plotted,0),-1,1,1-vr.noiseoffset,1+vr.noiseoffset),vr.lineNoiseCount=0),vr.lineNoiseCount++,vr.cachedLineNoise);t>_(1,1.02)&&_(0,1)<.7||vr.drawFn(e*t)}function Ar(){return(vr.pressureCount>=10||void 0===vr.cachedPressure)&&(vr.cachedPressure=gr?Er()*gr.pressure(dr.plotted):Er(),vr.pressureCount=0),vr.pressureCount++,vr.cachedPressure}function Er(){if(!vr.isCustomPressure)return function(e=.5+vr.p.pressure.curve[0]*vr.a,t=1-vr.p.pressure.curve[1]*vr.b,r=vr.cp,n=vr.min,i=vr.max){const o=e*xr,s=(dr.plotted<o?1.2*t:.8*t)*(xr/2);return T(1/(1+Math.pow(Math.abs((dr.plotted-o)/s),2*r)),0,1,n,i)}();const e=dr.plotted/xr;return T(vr.p.pressure.curve(Math.max(0,Math.min(1,.5+(e-.5+vr.ct)*vr.cs)))+vr.cp+vr.ck*(e-.5),0,1,vr.min,vr.max,!0)}function Mr(e){const t=de.stroke.weight*vr.p.scatter*e+de.stroke.weight*R(_r)*vr.p.scatter/3,r=vr.p.weight*_(.9,1.1),n=Math.ceil(vr.p.grain/e);for(let e=0;e<n;e++){const e=_(.9,1.1),n=e*t*_(-1,1),i=_(-1,1),o=Math.sqrt((e*t)**2-n**2);Kt(dr.x+n,dr.y+i*o,r,vr.alpha)}}function Sr(e,t=!0,r=vr.alpha){const n=t?de.stroke.weight*vr.p.scatter:0,i=t?n*_(-1,1):0,o=t?n*_(-1,1):0;Kt(dr.x+i,dr.y+o,de.stroke.weight*vr.p.weight*e,r*Math.max(.8,e)*_(.9,1.1))}function Tr(e,t=vr.alpha){const r=de.stroke.weight*vr.p.scatter,n=r*_(-1,1),i=r*_(-1,1),o=vr.p.weight*de.stroke.weight*e,s=vr.overscan;let a=0;"random"===vr.p.rotate?a=A(0,360)*(Math.PI/180):"natural"===vr.p.rotate&&(a=((gr?-yr:-pr)+dr.angle())*(Math.PI/180)),function(e,t,r,n,i,o=0){if(Xt>=Zt){Zt*=2;const e=new Float32Array(5*Zt);e.set(Ut),Ut=e}const s=e-Et,a=t-Mt,c=vt*s+_t*a+Rt+Et,l=bt*s+wt*a+At+Mt,u=Tt*r*St/2,h=Tt*o*St,f=5*Xt;Ut[f]=c,Ut[f+1]=l,Ut[f+2]=u,Ut[f+3]=n,Ut[f+4]=i/255;const m=c*Tt,d=l*Tt,x=1.42*u+h;Gt=qt(Gt,m-x-1,d-x-1,m+x+1,d+x+1),Xt++}(dr.x+n,dr.y+i,o,a,t*Math.max(.8,e)*_(.9,1.1),s)}function Pr(e,t=1){const r=(t=T(t,0,1,.9,1.05))*de.stroke.weight*vr.p.scatter*(vr.p.sharpness+(1-vr.p.sharpness)*R(_r)/e);if(_(0,vr.p.grain*e)>.4){let t,n;if(gr){const e=yr,i=D(e),o=N(e),s=r*_(-1,1),a=.3*r*_(-1,1);t=s*o+a*i,n=s*i-a*o}else{const e=r*_(-1,1),i=.3*r*_(-1,1);t=e*vr.sin+i*vr.cos,n=e*vr.cos-i*vr.sin}const i=e*e*vr.p.weight*_(.85,1.15)*de.stroke.weight,o=Math.max(.9,e)*vr.alpha*_(.75,1.1);Kt(dr.x+t,dr.y+n,i,o)}}function Cr(){if(!1===vr.p.markerTip)return;let e=Ar(),t=vr.alpha;if("marker"===vr.p.type)for(let r=1;r<10;r++)Sr(e*r/10,!0,8*t);else if("custom"===vr.p.type||"image"===vr.p.type)for(let r=1;r<5;r++)Tr(e*r/10,2*t)}function kr(e,t,r,n){if(!de.stroke.isActive||!de.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");be();let i=O(e,t,r,n);0!=i&&(br(e,t,i),wr(U(e,t,r,n),!1))}function Ir(e,t,r,n){if(!de.stroke.isActive||!de.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");be(),br(e,t,r),wr(B(n),!1)}g(()=>{_r.length=0});const Fr=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate","markerTip","noise"],Lr=[["pen",[.3,.15,.9,2,150,.1,{curve:[.15,.2],min_max:[1.2,1]}]],["rotring",[.15,.05,.7,15,210,.1,{curve:[.35,.2],min_max:[1.3,1]}]],["2B",[.3,.75,.45,15,180,.1,{curve:[.1,.3],min_max:[1.1,.9]}]],["HB",[.3,.6,.3,10,170,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["2H",[.2,.6,.3,4,120,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["cpencil",[.3,.55,.8,7,75,.1,{curve:[.15,.2],min_max:[.95,1.2]}]],["pastel",[2.05/3,13.4/3,.91,28,35,.085/3,{mode:"gaussian",curve:[.4,.05],min_max:[1.09,.93]},"default",void 0,"natural",!0,1]],["crayon",[.3,5.45/3,.75,250,159,.23/3,[1.1,.9],"default",void 0,"natural",!0,1]],["charcoal",[.35,1.5,.68,500,120,.03,{curve:[.15,.4],min_max:[1.1,.95]}]],["spray",[.2,6,15,40,90,.5,{curve:[.2,.35],min_max:[.7,1]},"spray"]],["marker",[2,.2,null,null,1,.03,{curve:[.35,.25],min_max:[1.2,.85]},"marker"]]];for(let e of Lr){let t={};for(let r=0;r<e[1].length;r++)t[Fr[r]]=e[1][r];nr(e[0],t)}Ye.prototype.draw=function(e=!1,t,r){let n=tr();if(e&&ur(e,t,r),n.isActive)for(let e of this.sides)kr(e[0].x,e[0].y,e[1].x,e[1].y);rr(n)},ze.prototype.draw=function(e,t,r){tr().isActive&&(this.origin&&(e=this.origin[0],t=this.origin[1],r=1),function(e,t,r,n){be(),br(t,r,e.length,e),wr(n,!0)}(this,e,t,r))};const Dr={tips:new Map,add(e){this.tips.has(e)||this.tips.set(e,!1)},imageToWhite(e){e.loadPixels();for(let t=0;t<4*e.width*e.height;t+=4){let r=(e.pixels[t]+e.pixels[t+1]+e.pixels[t+2])/3;e.pixels[t]=e.pixels[t+1]=e.pixels[t+2]=255,e.pixels[t+3]=255-r}e.updatePixels()},async load(){const e=[...this.tips.keys()].filter(e=>!this.tips.get(e));await Promise.all(e.map(e=>((e,t)=>nt.loadImageTip(e,t))(e,Dr.imageToWhite).then(t=>{this.tips.set(e,t)})))}};function Nr(){return{...de.hatch}}function Br(e){de.hatch={...e}}function Yr(e=5,t=45,r={rand:!1,continuous:!1,gradient:!1}){let n=de.hatch;n.isActive=!0,n.dist=e,n.angle=Y(t),n.options=r}function zr(e,t="black",r=1){de.hatch.hBrush={brush:e,color:t,weight:r}}function Or(){de.hatch.isActive=!1,de.hatch.hBrush=!1}function Ur(e,t,r,n){const i=t*Math.PI/180,o=Math.cos(i),s=Math.sin(i),a=Math.cos(-i),c=Math.sin(-i),l=e.a,u=l.length,h=new Array(u);let f=Infinity,m=-Infinity;for(let e=0;e<u;e++){const t=l[e][0],r=l[e][1],n=[t*o-r*s,t*s+r*o];h[e]=n,n[1]<f&&(f=n[1]),n[1]>m&&(m=n[1])}const d=[];for(let e=0;e<u;e++){const t=h[e],r=h[(e+1)%u];t[1]!==r[1]&&d.push(t,r)}const x=d.length,g=[],p=[];let y=f+.5*r,v=r;for(;y<m;){p.length=0;for(let e=0;e<x;e+=2){const t=d[e][1],r=d[e+1][1];(t<=y&&y<r||r<=y&&y<t)&&p.push(d[e][0]+(y-t)/(r-t)*(d[e+1][0]-d[e][0]))}p.sort((e,t)=>e-t);for(let e=0;e<p.length-1;e+=2)g.push({scanY:y,x1:p[e]*a-y*c,y1:p[e]*c+y*a,x2:p[e+1]*a-y*c,y2:p[e+1]*c+y*a});y+=v,v*=n}return g}function Xr(e){const{dist:t,options:r,segs:n}=function(e){const t=de.hatch.dist,r=(de.hatch.angle%180+180)%180,n=de.hatch.options,i=function(e,t,r,n){Array.isArray(e)||(e=[e]);const i=[];for(const o of e)for(const e of Ur(o,r,t,n))i.push(e);return i.sort((e,t)=>e.scanY===t.scanY?e.x1-t.x1:e.scanY-t.scanY),i}(e,t,r,n.gradient?T(n.gradient,0,1,1,1.1,!0):1);return{dist:t,options:n,segs:i}}(e),i=r.rand||0,o=[];for(let e=0;e<n.length;e++){const s=n[e];let a=s.x1,c=s.y1,l=s.x2,u=s.y2;i&&(a+=2*i*t*_(-1,1),c+=2*i*t*_(-1,1),l+=2*i*t*_(-1,1),u+=2*i*t*_(-1,1));const h=r.continuous&&e%2==1?{x1:l,y1:u,x2:a,y2:c,scanY:s.scanY,isConnector:!1}:{x1:a,y1:c,x2:l,y2:u,scanY:s.scanY,isConnector:!1};if(o.push(h),e>0&&r.continuous){const e=o[o.length-2];o.push({x1:e.x2,y1:e.y2,x2:h.x1,y2:h.y1,scanY:s.scanY,isConnector:!0})}}return o}function Zr(e){!function(e,t){const r=Xr(e);!function(){const e=tr();de.hatch.hBrush&&ur(...Object.values(de.hatch.hBrush)),(()=>{for(let e=0;e<r.length;e++){const n=r[e];t(n.x1,n.y1,n.x2,n.y2,e,r)}})(),rr(e)}()}(e,(e,t,r,n)=>{kr(e,t,r,n)})}function Gr(e,t,r={}){de.mass.brush=e,de.mass.color=t,de.mass.options=r,de.mass.isActive=!0}function Vr(){de.mass.isActive=!1,de.mass.brush=null,de.mass.color=null,de.mass.options={}}function Hr(e,t,r){return new Ye(e.vertices.map(e=>[e.x+t,e.y+r]))}function Wr(e,t,r,n,i){const o=(t+n)/2,s=(r+i)/2,a=n-t,c=i-r,l=Math.hypot(a,c);if(!l)return null;const u=-c/l,h=a/l,f=(e.x-o)*u+(e.y-s)*h;return{x:o+u*f,y:s+h*f}}function $r(e,t,r,n,i,o,s){let a=U(e,t,r,n),c=U(e,t,i,o);return((c-a)%360+360)%360>180&&([a,c]=[c,a]),[s(a),s(c)]}function jr(e){const t=w(.35,.65),r=e.x1+(e.x2-e.x1)*t,n=e.y1+(e.y2-e.y1)*t,i=e.x2-e.x1,o=e.y2-e.y1,s=Math.hypot(i,o)||1,a=w(.04,.1)*s,c=i/s*a*.5,l=o/s*a*.5;return[{x1:e.x1,y1:e.y1,x2:r-c,y2:n-l},{x1:r+c,y1:n+l,x2:e.x2,y2:e.y2}]}function qr(e,t,r){const n=function(e,t){const r=function(e){const t=e?.a??[];let r=Infinity,n=Infinity,i=-Infinity,o=-Infinity;for(const[e,s]of t)e<r&&(r=e),s<n&&(n=s),e>i&&(i=e),s>o&&(o=s);return{minX:r,minY:n,maxX:i,maxY:o,cx:(r+i)/2,cy:(n+o)/2,size:Math.hypot(i-r,o-n)}}(e),n=r.size*w(.6,1.4),[i,o]=t;return{x:r.cx+i*n,y:r.cy+o*n}}(e,t);for(const t of Xr(e)){const e=!t.isConnector&&w()<.35?jr(t):[t];for(const t of e){const e=Wr(n,t.x1,t.y1,t.x2,t.y2);if(!e)continue;const i=O(e.x,e.y,t.x1,t.y1);if(!i)continue;const[o,s]=$r(e.x,e.y,t.x1,t.y1,t.x2,t.y2,r);Ze(e.x,e.y,i,o,s)}}}function Kr(e,t,r,n,i,o){Yr(t,r,n),qr(e,i,o)}function Jr(e,n,i,o){const s=function(e,t,r,n){const i=!1===t,o=or(de.mass.brush)?.scatter??0,s=i?e:e.genPol(t,r,n,.15),a=Math.min(2*o,5),c=[[w(-a,a),w(-a,a)],[w(-a,a),w(-a,a)]];return[s,Hr(s,c[0][0],c[0][1]),Hr(s,c[1][0],c[1][1])]}(e,n,i,o),a=Nr(),c=tr(),l={...de.field},u=de.mass.options?.precision??.5,h=de.mass.options?.strength??1,f=de.mass.options?.gradient??.1,m=de.mass.options?.outline??!1,d=or(de.mass.brush)?.scatter??0,x=1.6*w(.65*d,.85*d)-.4*f,g=w(-90,90),p=((g+90)%180+180)%180-90>=0?w()<.5?[1,1]:[-1,-1]:w()<.5?[-1,1]:[1,-1],y=t()?e=>e*Math.PI/180:e=>e;ur(de.mass.brush,de.mass.color,1),Ne(2-u),m&&s[0].draw(),Kr(s[0],.9*x,r(g),{gradient:f,rand:2-2*u,continuous:!0},p,y),h>.33&&Kr(s[1],x,r(g+20*w(-1,1)),{gradient:f,rand:.6-.6*u,continuous:!0},p,y),h>.66&&Kr(s[2],.8*x,r(g+15*w(-1,1)),{gradient:f,rand:.6-.6*u,continuous:!0},p,y),rr(c),Br(a),de.field={...l}}function Qr(e,t,r){const n=2*Math.PI,i=ge.ctx,o=r/2;i.moveTo(e+o,t),i.arc(e,t,o,0,n)}de.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},Ye.prototype.hatch=function(e=!1,t,r){let n=Nr();e&&Yr(e,t,r),de.hatch.isActive&&Zr(this),Br(n)},ze.prototype.hatch=function(e,t,r){Nr().isActive&&(this.origin&&(e=this.origin[0],t=this.origin[1],r=1),this.pol=this.genPol(e,t,r,.3),this.pol.hatch())},de.mass={isActive:!1,brush:null,color:null,options:{}},Ye.prototype.mass=function(){de.mass?.isActive&&Jr(this,!1)},ze.prototype.mass=function(e,t,r){de.mass?.isActive&&(this.origin&&(e=this.origin[0],t=this.origin[1],r=1),Jr(this,e,t,r))};let en=null,tn=!1;tn||(ae={ensureResources:function(e,t,r,n,i){const o=Math.max(1,Math.round(t*n)),s=Math.max(1,Math.round(r*n));return function(e,t,r){return!e.mask||e.mask.width!==t||e.mask.height!==r}(e,o,s)&&(e.mask=ne(o,s)),function(e,t,r,n){return!e.fillMaskFramebuffer||e.fillMaskFramebuffer.width!==t||e.fillMaskFramebuffer.height!==r||"function"==typeof e.fillMaskFramebuffer.pixelDensity&&e.fillMaskFramebuffer.pixelDensity()!==n}(e,t,r,n)&&(e.fillMaskFramebuffer?.remove&&e.fillMaskFramebuffer.remove(),e.fillMaskFramebuffer=oe(e,{width:t,height:r,density:n,antialias:!1,depth:!1,stencil:!1}),i(e.fillMaskFramebuffer)),e.mask.dirtyRect??=null,e.mask.isDrawn??=!1,e.mask.drawingContext.imageSmoothingEnabled=!1,{mask:e.mask,ctx:e.mask.drawingContext}},clearMask:function(e,t){e&&(t(e),e.isDrawn=!1,e.dirtyRect=null)},getCompositeRect:function(e,t,r,n,i){return e?e.dirtyRect?i(n(e.dirtyRect,4)):r():null},getShaderMask:function(e,t,r,n,i){const o=e.fillMaskFramebuffer,s=e.drawingContext,a=r??n(),c=a.maxX-a.minX,l=a.maxY-a.minY;en&&en.width===c&&en.height===l||(en=ne(c,l));const u=en.drawingContext;return u.clearRect(0,0,c,l),u.drawImage(t,a.minX,a.minY,c,l,0,0,c,l),i(o),s.bindTexture(s.TEXTURE_2D,o.colorTexture),s.texSubImage2D(s.TEXTURE_2D,0,a.minX,a.minY,s.RGBA,s.UNSIGNED_BYTE,en),o}},tn=!0);let rn,nn=[],on=[],sn=[],an=[];de.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const cn=()=>({...de.fill});function ln(e,t,r,i){de.fill.opacity=(arguments.length<4?t:i)||150,de.fill.color=arguments.length<3?n(e):n(e,t,r),de.fill.isActive=!0}function un(e,t="out"){de.fill.bleed_strength=P(e,0,1),de.fill.direction=t}function hn(e=.4,t=.4){de.fill.texture_strength=P(e,0,1),de.fill.border_strength=P(t,0,1)}function fn(){de.fill.isActive=!1}let mn,dn,xn,gn,pn;const yn=[[],[]];function vn(){for(let e=0;e<512;e++)yn[0][e]=M(.5,.2),yn[1][e]=M(0,.02)}g(vn);class bn{constructor(e,t,r,n=[],i=!1,o,s){if(this.v=e,this.m=t,this.dir=n,this.midP=r,i){let t=0,n=0;const i=[];for(let o=0;o<e.length;o++){const s=Math.abs(r.x-e[o].x),a=Math.abs(r.y-e[o].y);t=Math.max(t,s),n=Math.max(n,a);const c=e[o],l=e[(o+1)%e.length],u={x:l.x-c.x,y:l.y-c.y},h=z(0,0,u.x,u.y,90),f={x:c.x+u.x/2,y:c.y+u.y/2};i.push({v1:c,v2:l,ray:{point1:f,point2:{x:f.x+h.x,y:f.y+h.y}}})}this.sizeX=t,this.sizeY=n;const o=mn.sides;this.dir=Array(e.length);for(let e=0;e<i.length;e++){const t=i[e],r=t.ray.point1.x,n=t.ray.point1.y,s=t.ray.point2.x-r,a=t.ray.point2.y-n;let c=0;for(let e=0;e<o.length;e++){const i=o[e][0],l=o[e][1],u=l.x-i.x,h=l.y-i.y,f=h*s-u*a;if(0===f)continue;const m=(s*(n-i.y)-a*(r-i.x))/f;if(m<0||m>1)continue;const d=(u*(n-i.y)-h*(r-i.x))/f,x=r+d*s,g=n+d*a;(t.v2.x-t.v1.x)*(g-t.v1.y)-(t.v2.y-t.v1.y)*(x-t.v1.x)>.01&&c++}this.dir[e]=c%2==0}const s=_(-.6,.6)*t,a=_(-.6,.6)*n;this.midP={x:r.x+s,y:r.y+a}}else this.sizeX=o,this.sizeY=s}trim(e=1){if(e>=1||e<0||this.v.length<=8)return{v:this.v,m:this.m,dir:this.dir};const t=~~((1-e)*this.v.length),r=~~(this.v.length/2-t/2),n=this.v.length-t,i=new Array(n),o=new Array(n),s=new Array(n);let a=0;for(let e=0;e<r;e++,a++)i[a]=this.v[e],o[a]=this.m[e],s[a]=this.dir[e];for(let e=r+t;e<this.v.length;e++,a++)i[a]=this.v[e],o[a]=this.m[e],s[a]=this.dir[e];const c=r,l=r+t,u=this.v[(c-1+this.v.length)%this.v.length],h=this.v[l%this.v.length],f=h.x-u.x,m=h.y-u.y;for(let e=0;e<2;e++){const t=_(.25,.75),n={x:u.x+f*t,y:u.y+m*t},a=r+e;i.splice(a,0,n),o.splice(a,0,_(.4,.7)),s.splice(a,0,this.dir[c%this.dir.length])}return{v:i,m:o,dir:s}}scatter(e=.3){const t=this.v.length,r=Math.max(3,~~(t*e)),n=[],i=t/r;for(let e=0;e<r;e++)n.push(~~(e*i+_(0,.8*i)));const o=[],s=[],a=[],c=this.midP,l=mn.sides;for(const e of n){const r=e%t;let n=this.v[r],i=!1;if(n.x<dn||n.x>gn||n.y<xn||n.y>pn)i=!0;else{let e=0;for(const[t,r]of l){const i=t.y,o=r.y;if(i>n.y==o>n.y)continue;const s=(n.y-i)/(o-i);n.x<t.x+s*(r.x-t.x)&&e++}i=e%2==0}i&&(n={x:c.x+(n.x-c.x)*_(.3,.6),y:c.y+(n.y-c.y)*_(.3,.6)}),o.push(n),s.push(this.m[r]),a.push(!this.dir[r])}return new bn(o,s,this.midP,a,!1,this.sizeX,this.sizeY)}flipDirs(){return new bn(this.v,this.m,this.midP,this.dir.map(e=>!e),!1,this.sizeX,this.sizeY)}grow(e=1){const{v:t,m:r,dir:n}=this.trim(e),i=t.length,o=2*i;nn.length<i&&(nn=new Array(i),on=new Array(i)),sn.length<o&&(sn=new Array(o),an=new Array(o));const s=nn,a=on,c=sn,l=an,u="out"===de.fill.direction?-90:90;0===yn[0].length&&vn();const h=yn[0],f=h.length,m=yn[1],d=m.length;let x,g,p,y=0,v=0,b=999===e?_(.6,.8):de.fill.bleed_strength;for(let o=0;o<i;o++){const x=t[o],g=t[o+1<i?o+1:0],p=r[o],w=n[o];if(e<997&&(b=p),b<.05){c[y]=p,l[y]=w,y++,s[v]=(x.x+g.x)/2,a[v]=(x.y+g.y)/2,c[y]=p,l[y]=w,y++,v++;continue}const R=(w?u:-u)+5*_(-1,1),A=D(R),E=N(R),M=g.x-x.x,S=g.y-x.y,T=A*M+E*S,P=A*S-E*M,C=h[~~(_(0,1)*f)]*_(.65,1.35)*b,k=p+m[~~(_(0,1)*d)];c[y]=p,l[y]=w,y++,s[v]=x.x+.5*M+T*C,a[v]=x.y+.5*S+P*C,c[y]=k,l[y]=w,y++,v++}if(rn&&y>rn){const e=Math.ceil(y/rn),r=Math.ceil(y/e);x=new Array(r),g=new Array(r),p=new Array(r);let n=0;for(let r=0;r<y;r+=e,n++)x[n]=r%2==0?t[r>>1]:{x:s[r>>1],y:a[r>>1]},g[n]=c[r],p[n]=l[r]}else{x=new Array(y);for(let e=0;e<y;e++)x[e]=e%2==0?t[e>>1]:{x:s[e>>1],y:a[e>>1]};g=c.slice(0,y),p=l.slice(0,y)}return new bn(x,g,this.midP,p,!1,this.sizeX,this.sizeY)}fill(e,t,r){const n=3*r,o=2*t*(1+r/2),s=!1!==ge.isBrush;ge.isBrush=!1,s&&(ge.justChanged=!0),ge.blend(e);const a=i();ge.ctx.save(),ge.ctx.setTransform(W*a.a,W*a.b,W*a.c,W*a.d,W*(a.x+Z/2),W*(a.y+G/2));const c=`rgb(${e._getRed()} ${e._getGreen()} ${e._getBlue()} / `;ge.ctx.strokeStyle=c+.005*de.fill.border_strength+")",ge.ctx.lineCap="round",rn=2024*Math.max(.1,2*de.fill.bleed_strength);const l=ge.ctx.getTransform(),u=Math.max(this.sizeX,this.sizeY),h=_(.15,.7);let f=this.grow();const m=this.scatter(.1).grow().scatter(.75).flipDirs();let d;for(let r=0;r<20;r++){r%4==0&&(f=f.grow()),r%2==0&&(d=[f.grow(1-.0125*r),f.grow(.7-.0125*r),f.grow(.4-.0125*r)]);for(const e of d)e.grow(999).grow(997).layer(r,u,o,c,l);m.grow(999).flipDirs().grow(997).layer(r,u,o*n,c,l),r%2==0&&f.grow(h).grow(999).layer(r,u,2*o,c,l),r%8!=0&&19!==r||(0!==n&&f.erase(3*n,t),ge.blend(e,!0))}ge.ctx.restore()}layer(e,t,r,n,i=null){ge.ctx.lineWidth=T(e,0,24,t/25,t/30,!0),ge.ctx.fillStyle=n+r+"%)",function(e,t=null){const r=ge.ctx;t||(t=r.getTransform());const n=t.a,i=t.b,o=t.c,s=t.d,a=t.e,c=t.f;let l=Infinity,u=Infinity,h=-Infinity,f=-Infinity;r.beginPath();const m=e[0];let d=n*m.x+o*m.y+a,x=i*m.x+s*m.y+c;l=h=d,u=f=x,r.moveTo(m.x,m.y);for(let t=1;t<e.length;t++){const m=e[t];d=n*m.x+o*m.y+a,x=i*m.x+s*m.y+c,l=Math.min(l,d),u=Math.min(u,x),h=Math.max(h,d),f=Math.max(f,x),r.lineTo(m.x,m.y)}r.closePath();const g=function(e,t){const r=e.lineWidth||0;return r<=0?1:1+r*Math.max(Math.hypot(t.a,t.c),Math.hypot(t.b,t.d))/2}(r,t);ge.markDirtyRect(ge.mask,{minX:l-g,minY:u-g,maxX:h+g,maxY:f+g})}(this.v,i),ge.ctx.fill(),ge.ctx.stroke()}erase(e,t){ge.ctx.save();const r=~~(_(80,110)*T(e,0,1,2,3.5)),n=this.sizeX/1.3,i=this.sizeY/1.3,o=1.3*Math.min(this.sizeX,this.sizeY),s=.03*o,a=.45*o,{x:c,y:l}=this.midP;ge.ctx.globalCompositeOperation="destination-out";const u=(5-T(t,80,100,.3,.7,!0))*e/255;ge.ctx.fillStyle=`rgb(255 0 0 / ${u})`,ge.ctx.lineWidth=0;for(let e=0;e<r;e++){const t=c+M(0,n),r=l+M(0,i),o=_(s,a);ge.ctx.beginPath(),Qr(t,r,o),e%5!=0&&ge.ctx.fill()}ge.ctx.globalCompositeOperation="source-over",ge.ctx.restore()}}function _n(e,t){if(!e)return e;t||(t=e);let r,n=e;do{if(r=!1,n.steiner||!kn(n,n.next)&&0!==Cn(n.prev,n,n.next))n=n.next;else{if(Yn(n),n=t=n.prev,n===n.next)break;r=!0}}while(r||n!==t);return t}function wn(e,t,r,n,i,o,s){if(!e)return;!s&&o&&function(e,t,r,n){let i=e;do{0===i.z&&(i.z=Sn(i.x,i.y,t,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==e);i.prevZ.nextZ=null,i.prevZ=null,function(e){let t,r=1;do{let n,i=e;e=null;let o=null;for(t=0;i;){t++;let s=i,a=0;for(let e=0;e<r&&(a++,s=s.nextZ,s);e++);let c=r;for(;a>0||c>0&&s;)0!==a&&(0===c||!s||i.z<=s.z)?(n=i,i=i.nextZ,a--):(n=s,s=s.nextZ,c--),o?o.nextZ=n:e=n,n.prevZ=o,o=n;i=s}o.nextZ=null,r*=2}while(t>1)}(i)}(e,n,i,o);let a=e;for(;e.prev!==e.next;){const c=e.prev,l=e.next;if(o?An(e,n,i,o):Rn(e))t.push(c.i,e.i,l.i),Yn(e),e=l.next,a=l.next;else if((e=l)===a){s?1===s?wn(e=En(_n(e),t),t,r,n,i,o,2):2===s&&Mn(e,t,r,n,i,o):wn(_n(e),t,r,n,i,o,1);break}}}function Rn(e){const t=e.prev,r=e,n=e.next;if(Cn(t,r,n)>=0)return!1;const i=t.x,o=r.x,s=n.x,a=t.y,c=r.y,l=n.y,u=Math.min(i,o,s),h=Math.min(a,c,l),f=Math.max(i,o,s),m=Math.max(a,c,l);let d=n.next;for(;d!==t;){if(d.x>=u&&d.x<=f&&d.y>=h&&d.y<=m&&Tn(i,a,o,c,s,l,d.x,d.y)&&Cn(d.prev,d,d.next)>=0)return!1;d=d.next}return!0}function An(e,t,r,n){const i=e.prev,o=e,s=e.next;if(Cn(i,o,s)>=0)return!1;const a=i.x,c=o.x,l=s.x,u=i.y,h=o.y,f=s.y,m=Math.min(a,c,l),d=Math.min(u,h,f),x=Math.max(a,c,l),g=Math.max(u,h,f),p=Sn(m,d,t,r,n),y=Sn(x,g,t,r,n);let v=e.prevZ,b=e.nextZ;for(;v&&v.z>=p&&b&&b.z<=y;){if(v.x>=m&&v.x<=x&&v.y>=d&&v.y<=g&&v!==i&&v!==s&&Tn(a,u,c,h,l,f,v.x,v.y)&&Cn(v.prev,v,v.next)>=0)return!1;if(v=v.prevZ,b.x>=m&&b.x<=x&&b.y>=d&&b.y<=g&&b!==i&&b!==s&&Tn(a,u,c,h,l,f,b.x,b.y)&&Cn(b.prev,b,b.next)>=0)return!1;b=b.nextZ}for(;v&&v.z>=p;){if(v.x>=m&&v.x<=x&&v.y>=d&&v.y<=g&&v!==i&&v!==s&&Tn(a,u,c,h,l,f,v.x,v.y)&&Cn(v.prev,v,v.next)>=0)return!1;v=v.prevZ}for(;b&&b.z<=y;){if(b.x>=m&&b.x<=x&&b.y>=d&&b.y<=g&&b!==i&&b!==s&&Tn(a,u,c,h,l,f,b.x,b.y)&&Cn(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function En(e,t){let r=e;do{const n=r.prev,i=r.next.next;!kn(n,i)&&In(n,r,r.next,i)&&Dn(n,i)&&Dn(i,n)&&(t.push(n.i,r.i,i.i),Yn(r),Yn(r.next),r=e=i),r=r.next}while(r!==e);return _n(r)}function Mn(e,t,r,n,i,o){let s=e;do{let e=s.next.next;for(;e!==s.prev;){if(s.i!==e.i&&Pn(s,e)){let a=Nn(s,e);return s=_n(s,s.next),a=_n(a,a.next),wn(s,t,r,n,i,o,0),void wn(a,t,r,n,i,o,0)}e=e.next}s=s.next}while(s!==e)}function Sn(e,t,r,n,i){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-r)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-n)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function Tn(e,t,r,n,i,o,s,a){return!(e===s&&t===a)&&function(e,t,r,n,i,o,s,a){return(i-s)*(t-a)>=(e-s)*(o-a)&&(e-s)*(n-a)>=(r-s)*(t-a)&&(r-s)*(o-a)>=(i-s)*(n-a)}(e,t,r,n,i,o,s,a)}function Pn(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){let r=e;do{if(r.i!==e.i&&r.next.i!==e.i&&r.i!==t.i&&r.next.i!==t.i&&In(r,r.next,e,t))return!0;r=r.next}while(r!==e);return!1}(e,t)&&(Dn(e,t)&&Dn(t,e)&&function(e,t){let r=e,n=!1;const i=(e.x+t.x)/2,o=(e.y+t.y)/2;do{r.y>o!=r.next.y>o&&r.next.y!==r.y&&i<(r.next.x-r.x)*(o-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==e);return n}(e,t)&&(Cn(e.prev,e,t.prev)||Cn(e,t.prev,t))||kn(e,t)&&Cn(e.prev,e,e.next)>0&&Cn(t.prev,t,t.next)>0)}function Cn(e,t,r){return(t.y-e.y)*(r.x-t.x)-(t.x-e.x)*(r.y-t.y)}function kn(e,t){return e.x===t.x&&e.y===t.y}function In(e,t,r,n){const i=Ln(Cn(e,t,r)),o=Ln(Cn(e,t,n)),s=Ln(Cn(r,n,e)),a=Ln(Cn(r,n,t));return i!==o&&s!==a||!(0!==i||!Fn(e,r,t))||!(0!==o||!Fn(e,n,t))||!(0!==s||!Fn(r,e,n))||!(0!==a||!Fn(r,t,n))}function Fn(e,t,r){return t.x<=Math.max(e.x,r.x)&&t.x>=Math.min(e.x,r.x)&&t.y<=Math.max(e.y,r.y)&&t.y>=Math.min(e.y,r.y)}function Ln(e){return e>0?1:e<0?-1:0}function Dn(e,t){return Cn(e.prev,e,e.next)<0?Cn(e,t,e.next)>=0&&Cn(e,e.prev,t)>=0:Cn(e,t,e.prev)<0||Cn(e,e.next,t)<0}function Nn(e,t){const r=zn(e.i,e.x,e.y),n=zn(t.i,t.x,t.y),i=e.next,o=t.prev;return e.next=t,t.prev=e,r.next=i,i.prev=r,n.next=r,r.prev=n,o.next=n,n.prev=o,n}function Bn(e,t,r,n){const i=zn(e,t,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Yn(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function zn(e,t,r){return{i:e,x:t,y:r,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}Ye.prototype.fill=function(e=!1,t,r,n,i,o){let s=cn();e&&(ln(e,t),un(r,o),hn(n,i)),s.isActive&&(be(),function(e){if(!de.fill.isActive||!de.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");mn=e,dn=Infinity,xn=Infinity,gn=-Infinity,pn=-Infinity;for(const[t]of e.sides)t.x<dn&&(dn=t.x),t.x>gn&&(gn=t.x),t.y<xn&&(xn=t.y),t.y>pn&&(pn=t.y);const t=[...e.vertices],r=_(0,75),n=~~(.25*t.length*(r<5?1:r<15?2:3)),i=de.fill.bleed_strength,o=t.map((e,t)=>(t>n?1:.3)*_(.85,1.4)*i),s=A(0,t.length),a=t.length,c=new Array(a);for(let e=0;e<a;e++)c[e]=t[(e+s)%a];const l=function(e){if(0===e.length)return{x:0,y:0};if(e.length<8){let t=0,r=0;for(const n of e)t+=n.x,r+=n.y;return{x:t/e.length,y:r/e.length}}const t=[...e];t[0].x===t[t.length-1].x&&t[0].y===t[t.length-1].y||t.push(t[0]);let r=0,n=0,i=0;for(let e=0;e<t.length-1;e++){const o=t[e].x*t[e+1].y-t[e+1].x*t[e].y;r+=o,n+=(t[e].x+t[e+1].x)*o,i+=(t[e].y+t[e+1].y)*o}return r*=.5,r?{x:n/(6*r),y:i/(6*r)}:{x:t[0].x,y:t[0].y}}(c);new bn(c,o,l,[],!0).fill(de.fill.color,T(de.fill.opacity,0,255,0,1,!0),de.fill.texture_strength)}(this)),(e=>{de.fill={...e}})(s)},ze.prototype.fill=function(e,t,r){cn().isActive&&(this.origin&&(e=this.origin[0],t=this.origin[1],r=1),this.pol=this.genPol(e,t,r,de.fill.bleed_strength<.06?0:T(de.fill.bleed_strength,0,.6,.2,.6,!0)),this.pol.fill())};let On=null,Un=null,Xn=null,Zn=null,Gn=null,Vn=0,Hn=0,Wn=0;const $n={},jn={};function qn(e,t,r,i){q(),de.wash.opacity=(arguments.length<4?t:i)??150,de.wash.color=arguments.length<3?n(e):n(e,t,r),de.wash.isActive=!0}function Kn(){de.wash.isActive=!1}function Jn(e,t){const r=i();return[r.a*e+r.c*t+r.x+Vn/2,r.b*e+r.d*t+r.y+Hn/2]}de.wash={color:null,opacity:150,isActive:!1},Ye.prototype.wash=function(e=!1,t){const r={...de.wash};!1!==e&&qn(e,t),de.wash.isActive&&function(e){if(!de.wash?.isActive||!de.wash.color||e.vertices.length<3)return;pe(),function(){const e=H.drawingContext;Gn&&!(Vn!==Z||Hn!==G)||(Vn=Z,Hn=G,Gn=new Float32Array([2/Vn,0,0,0,0,-2/Hn,0,0,0,0,1,0,-1,1,0,1])),On===e&&Un&&Xn&&Zn||(On=e,Un=ot(On,"#version 300 es\nin vec2 a_position;\nuniform mat4 u_matrix;\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n}","#version 300 es\nprecision highp float;\nuniform vec4 u_color;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(u_color.rgb * u_color.a, u_color.a);\n}"),$n.a_position=On.getAttribLocation(Un,"a_position"),jn.u_matrix=On.getUniformLocation(Un,"u_matrix"),jn.u_color=On.getUniformLocation(Un,"u_color"),Xn=On.createVertexArray(),On.bindVertexArray(Xn),Zn=On.createBuffer(),On.bindBuffer(On.ARRAY_BUFFER,Zn),On.bufferData(On.ARRAY_BUFFER,0,On.DYNAMIC_DRAW),Wn=0,On.enableVertexAttribArray($n.a_position),On.vertexAttribPointer($n.a_position,2,On.FLOAT,!1,8,0),On.bindVertexArray(null),On.bindBuffer(On.ARRAY_BUFFER,null))}();const{triangles:t,vertexCount:r}=function(e){const t=new Float32Array(2*e.vertices.length);for(let r=0;r<e.vertices.length;r++){const n=e.vertices[r];t[2*r]=n.x,t[2*r+1]=n.y}const r=function(e,t,r=2){const n=e.length;let i=function(e,t,r,n){let i;if(1==function(e,t,r,n){let i=0;for(let t=0,o=r-n;t<r;t+=n)i+=(e[o]-e[t])*(e[t+1]+e[o+1]),o=t;return i}(e,0,r,n)>0)for(let t=0;t<r;t+=n)i=Bn(t/n|0,e[t],e[t+1],i);else for(let t=r-n;t>=0;t-=n)i=Bn(t/n|0,e[t],e[t+1],i);return i&&kn(i,i.next)&&(Yn(i),i=i.next),i}(e,0,n,r);const o=[];if(!i||i.next===i.prev)return o;let s,a,c;if(e.length>80*r){s=e[0],a=e[1];let t=s,i=a;for(let o=r;o<n;o+=r){const r=e[o],n=e[o+1];r<s&&(s=r),n<a&&(a=n),r>t&&(t=r),n>i&&(i=n)}c=Math.max(t-s,i-a),c=0!==c?32767/c:0}return wn(i,o,r,s,a,c,0),o}(t),n=new Float32Array(2*r.length);for(let e=0;e<r.length;e++){const i=r[e],[o,s]=Jn(t[2*i],t[2*i+1]);n[2*e]=o,n[2*e+1]=s}return{triangles:n,vertexCount:r.length}}(e),n=t.byteLength;On.useProgram(Un),On.enable(On.BLEND),On.blendEquation(On.FUNC_ADD),On.blendFunc(On.ONE,On.ONE_MINUS_SRC_ALPHA),On.bindVertexArray(Xn),On.bindBuffer(On.ARRAY_BUFFER,Zn),n>Wn?(On.bufferData(On.ARRAY_BUFFER,t,On.DYNAMIC_DRAW),Wn=n):On.bufferSubData(On.ARRAY_BUFFER,0,t);const i=de.wash.color._array;On.uniformMatrix4fv(jn.u_matrix,!1,Gn),On.uniform4f(jn.u_color,i[0],i[1],i[2],de.wash.opacity/255),On.drawArrays(On.TRIANGLES,0,r),On.bindVertexArray(null),On.bindBuffer(On.ARRAY_BUFFER,null),at(H,On)}(this),de.wash={...r}},ze.prototype.wash=function(e,t,r){de.wash?.isActive&&(this.origin&&(e=this.origin[0],t=this.origin[1],r=1),this.pol=this.genPol(e,t,r,0,-1),this.pol.wash())};let Qn=null,ei=null;const ti=[];let ri=!1;const ni=e=>!!e&&"function"==typeof e.begin&&"function"==typeof e.end&&!!e.renderer&&!!e.renderer._pInst,ii=e=>"number"==typeof e&&Number.isFinite(e)&&e>0,oi=e=>{try{return e()}catch(e){return}},si=e=>!!e&&"function"==typeof e.pixelDensity&&"function"==typeof e.createFramebuffer&&ii(oi(()=>e.width))&&ii(oi(()=>e.height))&&"webgl2"===oi(()=>e.webglVersion),ai=e=>(si(e)&&(Qn=e),Qn),ci=()=>(ei&&si(ei)?ai(ei):null)||ai(window.self?.p5?.instance??null)||ai(V)||Qn,li=(e=!1)=>{const t=((e=!1)=>{const t=ci();if(!e){if(!t)throw new Error("p5.brush could not resolve an active WEBGL sketch. Call brush.instance(p) and brush.load() after createCanvas(..., WEBGL).");return{renderer:t,width:t.width,height:t.height}}if(ni(e)){const r=e.renderer._pInst;if(ai(r),t&&r!==t)throw new Error("p5.brush only supports p5.Framebuffer targets created from the active sketch");return{renderer:r,width:e.width,height:e.height}}return{renderer:e,width:e.width,height:e.height}})(e);if(j({Renderer:t.renderer}),ai(e?ci():H),"webgl2"!==H.webglVersion)throw new Error("p5.brush requires a WEBGL canvas");j({Cwidth:t.width,Cheight:t.height}),ri=!0},ui=e=>{j({Instance:e}),ai(e)},hi=()=>H??ci?.()??window.self?.p5?.instance??null,fi={a:1,b:0,c:0,d:1,x:0,y:0},mi={a:1,b:0,c:0,d:1,x:0,y:0};function di(){const e=hi();return!!e&&"function"==typeof e.angleMode&&e.angleMode()===e.RADIANS}function xi(e,t,r){const n=t.isEnabled(t.DEPTH_TEST);n&&t.disable(t.DEPTH_TEST);const i=e._renderer.activeFramebuffer?.()??null;return i?._beforeEnd&&i._beforeEnd(),t.bindFramebuffer(t.FRAMEBUFFER,function(e){return e?"function"==typeof e._framebufferToBind?e._framebufferToBind():e.framebuffer??null:null}(r)),t.viewport(0,0,r.width*r.density,r.height*r.density),{hadDepthTest:n,previousTarget:i}}function gi(e,t,r){r?.hadDepthTest&&t.enable(t.DEPTH_TEST),r?.previousTarget?._beforeBegin?r.previousTarget._beforeBegin():(t.bindFramebuffer(t.FRAMEBUFFER,null),e._renderer.viewport(e._renderer._origViewport.width,e._renderer._origViewport.height),e._renderer._applyStencilTestIfClipping?.())}function pi(e,t){const r=e?._renderer;r&&(r._curShader=null,r._cachedBlendMode=null,r._isBlending=null,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,null),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA))}function yi(e,t,r){if(!t)return;if(r(t))return void t.draw(()=>e.clear());const n=t.drawingContext;n.save(),n.setTransform(1,0,0,1,0,0),n.clearRect(0,0,t.width,t.height),n.restore()}function vi(e,t,r){return e.loaded||(e.loaded=!0,e.shaderProgram??=e.createShader(t,r)),e.shaderProgram}function bi(e,t,r,n,i){return t?.remove&&t.remove(),e.createFramebuffer({width:r,height:n,density:i,antialias:!1,depth:!1,stencil:!1})}const _i=(e,t)=>e.createFramebuffer(t);function wi({renderer:e,shader:t,source:r,mask:n,color:i,isBrushMask:o,Cwidth:s,Cheight:a,dirtyRect:c,targetIsFramebuffer:l,withScissor:u}){const h=e.drawingContext,f=h.isEnabled(h.DEPTH_TEST);h.disable(h.DEPTH_TEST),e.push(),e.translate(0,0),e.shader(t),t.setUniform("u_source",r),t.setUniform("u_targetIsFramebuffer",l),t.setUniform("u_isBrush",o),t.setUniform("u_mask",n),t.setUniform("u_color",i),u(h,c,()=>{e.fill(0,0,0,0),e.noStroke(),e.rect(-s/2,-a/2,s,a)},!l),e.pop(),e.resetShader(),f&&h.enable(h.DEPTH_TEST)}function Ri(e){return e.isFramebufferTarget(e.sourceTarget)?((e.sourceTarget.renderer??e.renderer)._renderer?.flushDraw?.(),e.sourceFramebuffer.draw(()=>{e.withScissor(e.renderer.drawingContext,e.dirtyRect,()=>{e.renderer.clear(),e.renderer.push(),e.renderer.imageMode(e.renderer.CENTER),e.renderer.image(e.sourceTarget,0,0,e.Cwidth,e.Cheight),e.renderer.pop()},!1)}),e.sourceFramebuffer):(e.renderer._renderer?.flushDraw?.(),function({renderer:e,sourceFramebuffer:t,dirtyRect:r,getTargetPixelSize:n,toScissorBox:i}){const o=e.drawingContext,{width:s,height:a}=n(),c=r?i(r):null,l=o.getParameter(o.READ_FRAMEBUFFER_BINDING),u=o.getParameter(o.DRAW_FRAMEBUFFER_BINDING);return o.bindFramebuffer(o.READ_FRAMEBUFFER,null),o.bindFramebuffer(o.DRAW_FRAMEBUFFER,t.framebuffer),o.blitFramebuffer(c?.x??0,c?.y??0,c?c.x+c.width:s,c?c.y+c.height:a,c?.x??0,c?.y??0,c?c.x+c.width:s,c?c.y+c.height:a,o.COLOR_BUFFER_BIT,o.NEAREST),o.bindFramebuffer(o.READ_FRAMEBUFFER,l),o.bindFramebuffer(o.DRAW_FRAMEBUFFER,u),t}(e))}const Ai=()=>H??V??window.self?.p5?.instance;function Ei(e,t){const r=Ai();if(!r?.createGraphics)throw new Error("p5 stroke tip creation requires an active renderer or instance.");return r.createGraphics(e,t)}function Mi(e,t){return new Promise((r,n)=>{const i=new window.Image;i.onload=()=>{const e=Ai();if(!e?.createImage)return void n(new Error("p5 image tip loading requires an active renderer or instance."));const o=e.createImage(i.naturalWidth,i.naturalHeight);o.drawingContext.drawImage(i,0,0),t(o),r(o)},i.onerror=()=>n(new Error(`Failed to load image tip: ${e}`)),i.crossOrigin="anonymous",i.src=e})}const Si=[];var Ti;Ti={load:li,syncDensity:()=>{const e=H.pixelDensity();return j({Density:e}),e},isCanvasReady:()=>{ri||li()},instance:ui,activateInstance:e=>{ti.push(ei),ei=e,ui(e)},deactivateInstance:()=>{ei=ti.pop()??null},getActiveFramebuffer:()=>H?._renderer?.activeFramebuffer?.()??null,isFramebufferTarget:ni},$={...$,...Ti},function(){var e;(e={usesRadians:di,fromDegrees:e=>di()?e*Math.PI/180:e,createColor:(...e)=>{const t=hi();if(!t?.color)throw new Error("p5 runtime color creation requires an active renderer.");return t.color(...e)},getAffineMatrix:()=>{const e=hi(),t=e?._renderer?.uModelMatrix?.mat4;return t?(mi.a=t[0],mi.b=t[1],mi.c=t[4],mi.d=t[5],mi.x=t[12],mi.y=t[13],mi):fi}}).usesRadians&&(t=e.usesRadians),e.fromDegrees&&(r=e.fromDegrees),e.createColor&&(n=e.createColor),e.getAffineMatrix&&(i=e.getAffineMatrix)}(),function(){var e;e={beginDirectMaskDraw:xi,endDirectMaskDraw:gi,resetDirectShaderTracking:pi},st={...st,...e}}(),function(){var e;e={clearTarget:yi,ensureBlendShaderProgram:vi,ensureBlendSourceFramebuffer:bi,createFramebuffer:_i,runBlendShaderPass:wi,blitSourceToFramebuffer:Ri},ie={...ie,...e}}(),function(){var e;e={createTipSurface:Ei,loadImageTip:Mi},nt={...nt,...e}}(),"undefined"!=typeof p5&&p5.registerAddon(function(e,t,r){r.presetup=function(){J(this)},r.predraw=function(){J(this)},r.postsetup=function(){K(this),pe(),Q()},r.postdraw=function(){K(this),pe(),Q()};const n=t.push,i=t.pop,o=t.randomSeed,s=t.noiseSeed;t.push=function(){n.call(this),be(),Si.push({fill:{...de.fill},wash:de.wash?{...de.wash}:null,stroke:{...de.stroke},hatch:{...de.hatch},mass:de.mass?{...de.mass}:null,field:{...de.field}})},t.pop=function(){i.call(this),function(){const e=Si.pop();e&&(de.stroke={...e.stroke},de.field={...e.field},de.hatch={...e.hatch},de.fill={...e.fill},e.wash&&(de.wash={...e.wash}),e.mass?de.mass={...e.mass}:de.mass&&(de.mass={...de.mass,isActive:!1,brush:null,color:null,options:{}}))}()},t.randomSeed=function(e){o.call(this,e),p(e)},t.noiseSeed=function(e){s.call(this,e),b(e)}});export{ze as Plot,Ye as Polygon,_e as Position,nr as add,Le as addField,Ze as arc,je as beginShape,Je as beginStroke,ir as box,Xe as circle,fr as clip,Ke as endShape,et as endStroke,Ie as field,ln as fill,un as fillBleed,hn as fillTexture,Ir as flowLine,Yr as hatch,Zr as hatchArray,zr as hatchStyle,K as instance,kr as line,De as listFields,ye as load,Gr as mass,Qe as move,mr as noClip,Fe as noField,fn as noFill,Or as noHatch,Vr as noMass,hr as noStroke,Kn as noWash,b as noiseSeed,ar as pick,Oe as polygon,Ue as rect,ke as refreshField,sr as scaleBrushes,p as seed,ur as set,tt as spline,cr as stroke,lr as strokeWeight,qe as vertex,S as wRand,qn as wash,Ne as wiggle};
//# sourceMappingURL=p5.brush.esm.js.map
diff --git a/dist/p5.brush.esm.js.map b/dist/p5.brush.esm.js.map
index 64698c5..db0abdf 100644
--- a/dist/p5.brush.esm.js.map
+++ b/dist/p5.brush.esm.js.map
@@ -1 +1 @@
-{"version":3,"file":"p5.brush.esm.js","sources":["../src/core/runtime.js","../node_modules/simplex-noise/dist/esm/simplex-noise.js","../node_modules/esm-seedrandom/esm/index.mjs","../src/core/utils.js","../src/core/target.js","../src/core/dirty_rect.js","../src/core/compositor_runtime.js","../src/core/color.js","../src/core/flowfield.js","../src/core/polygon.js","../src/core/plot.js","../src/core/primitives.js","../src/stroke/runtime.js","../src/stroke/composite.js","../src/core/gl/utils.js","../src/core/renderer_runtime.js","../src/stroke/gl_draw.js","../src/stroke/stroke.js","../src/hatch/hatch.js","../src/hatch/mass.js","../src/fill/mask.js","../src/fill/composite.js","../src/fill/fill.js","../node_modules/earcut/src/earcut.js","../src/fill/wash.js","../src/adapters/p5/target.js","../src/adapters/p5/runtime.js","../src/adapters/p5/renderer.js","../src/adapters/p5/compositor.js","../src/adapters/p5/stroke.js","../src/core/save.js","../src/index.p5.js","../src/adapters/p5/addon.js"],"sourcesContent":["// =============================================================================\n// Runtime Hooks\n// =============================================================================\n\nconst identityMatrix = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\n\nexport let usesRadians = () => false;\nexport let fromDegrees = (angle) => angle;\nexport let createColor = () => {\n throw new Error(\"No runtime color adapter registered.\");\n};\nexport let getAffineMatrix = () => identityMatrix;\n\n/**\n * Registers or updates host-runtime hooks used by core modules.\n *\n * @param {object} hooks\n */\nexport function setRuntime(hooks) {\n if (hooks.usesRadians) usesRadians = hooks.usesRadians;\n if (hooks.fromDegrees) fromDegrees = hooks.fromDegrees;\n if (hooks.createColor) createColor = hooks.createColor;\n if (hooks.getAffineMatrix) getAffineMatrix = hooks.getAffineMatrix;\n}\n","/*\n * A fast javascript implementation of simplex noise by Jonas Wagner\n\nBased on a speed-improved simplex noise algorithm for 2D, 3D and 4D in Java.\nWhich is based on example code by Stefan Gustavson ([email protected]).\nWith Optimisations by Peter Eastman ([email protected]).\nBetter rank ordering method by Stefan Gustavson in 2012.\n\n Copyright (c) 2024 Jonas Wagner\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n */\n// these __PURE__ comments help uglifyjs with dead code removal\n//\nconst SQRT3 = /*#__PURE__*/ Math.sqrt(3.0);\nconst SQRT5 = /*#__PURE__*/ Math.sqrt(5.0);\nconst F2 = 0.5 * (SQRT3 - 1.0);\nconst G2 = (3.0 - SQRT3) / 6.0;\nconst F3 = 1.0 / 3.0;\nconst G3 = 1.0 / 6.0;\nconst F4 = (SQRT5 - 1.0) / 4.0;\nconst G4 = (5.0 - SQRT5) / 20.0;\n// I'm really not sure why this | 0 (basically a coercion to int)\n// is making this faster but I get ~5 million ops/sec more on the\n// benchmarks across the board or a ~10% speedup.\nconst fastFloor = (x) => Math.floor(x) | 0;\nconst grad2 = /*#__PURE__*/ new Float64Array([1, 1,\n -1, 1,\n 1, -1,\n -1, -1,\n 1, 0,\n -1, 0,\n 1, 0,\n -1, 0,\n 0, 1,\n 0, -1,\n 0, 1,\n 0, -1]);\n// double seems to be faster than single or int's\n// probably because most operations are in double precision\nconst grad3 = /*#__PURE__*/ new Float64Array([1, 1, 0,\n -1, 1, 0,\n 1, -1, 0,\n -1, -1, 0,\n 1, 0, 1,\n -1, 0, 1,\n 1, 0, -1,\n -1, 0, -1,\n 0, 1, 1,\n 0, -1, 1,\n 0, 1, -1,\n 0, -1, -1]);\n// double is a bit quicker here as well\nconst grad4 = /*#__PURE__*/ new Float64Array([0, 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1,\n 0, -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1,\n 1, 0, 1, 1, 1, 0, 1, -1, 1, 0, -1, 1, 1, 0, -1, -1,\n -1, 0, 1, 1, -1, 0, 1, -1, -1, 0, -1, 1, -1, 0, -1, -1,\n 1, 1, 0, 1, 1, 1, 0, -1, 1, -1, 0, 1, 1, -1, 0, -1,\n -1, 1, 0, 1, -1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, -1,\n 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1, 0,\n -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1, 0]);\n/**\n * Creates a 2D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction2D}\n */\nexport function createNoise2D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating this yields a little ~3% performance improvement.\n const permGrad2x = new Float64Array(perm).map(v => grad2[(v % 12) * 2]);\n const permGrad2y = new Float64Array(perm).map(v => grad2[(v % 12) * 2 + 1]);\n return function noise2D(x, y) {\n // if(!isFinite(x) || !isFinite(y)) return 0;\n let n0 = 0; // Noise contributions from the three corners\n let n1 = 0;\n let n2 = 0;\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y) * F2; // Hairy factor for 2D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const t = (i + j) * G2;\n const X0 = i - t; // Unskew the cell origin back to (x,y) space\n const Y0 = j - t;\n const x0 = x - X0; // The x,y distances from the cell origin\n const y0 = y - Y0;\n // For the 2D case, the simplex shape is an equilateral triangle.\n // Determine which simplex we are in.\n let i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords\n if (x0 > y0) {\n i1 = 1;\n j1 = 0;\n } // lower triangle, XY order: (0,0)->(1,0)->(1,1)\n else {\n i1 = 0;\n j1 = 1;\n } // upper triangle, YX order: (0,0)->(0,1)->(1,1)\n // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and\n // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where\n // c = (3-sqrt(3))/6\n const x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords\n const y1 = y0 - j1 + G2;\n const x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords\n const y2 = y0 - 1.0 + 2.0 * G2;\n // Work out the hashed gradient indices of the three simplex corners\n const ii = i & 255;\n const jj = j & 255;\n // Calculate the contribution from the three corners\n let t0 = 0.5 - x0 * x0 - y0 * y0;\n if (t0 >= 0) {\n const gi0 = ii + perm[jj];\n const g0x = permGrad2x[gi0];\n const g0y = permGrad2y[gi0];\n t0 *= t0;\n // n0 = t0 * t0 * (grad2[gi0] * x0 + grad2[gi0 + 1] * y0); // (x,y) of grad3 used for 2D gradient\n n0 = t0 * t0 * (g0x * x0 + g0y * y0);\n }\n let t1 = 0.5 - x1 * x1 - y1 * y1;\n if (t1 >= 0) {\n const gi1 = ii + i1 + perm[jj + j1];\n const g1x = permGrad2x[gi1];\n const g1y = permGrad2y[gi1];\n t1 *= t1;\n // n1 = t1 * t1 * (grad2[gi1] * x1 + grad2[gi1 + 1] * y1);\n n1 = t1 * t1 * (g1x * x1 + g1y * y1);\n }\n let t2 = 0.5 - x2 * x2 - y2 * y2;\n if (t2 >= 0) {\n const gi2 = ii + 1 + perm[jj + 1];\n const g2x = permGrad2x[gi2];\n const g2y = permGrad2y[gi2];\n t2 *= t2;\n // n2 = t2 * t2 * (grad2[gi2] * x2 + grad2[gi2 + 1] * y2);\n n2 = t2 * t2 * (g2x * x2 + g2y * y2);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to return values in the interval [-1,1].\n return 70.0 * (n0 + n1 + n2);\n };\n}\n/**\n * Creates a 3D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction3D}\n */\nexport function createNoise3D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these seems to yield a speedup of over 15%\n const permGrad3x = new Float64Array(perm).map(v => grad3[(v % 12) * 3]);\n const permGrad3y = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 1]);\n const permGrad3z = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 2]);\n return function noise3D(x, y, z) {\n let n0, n1, n2, n3; // Noise contributions from the four corners\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y + z) * F3; // Very nice and simple skew factor for 3D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const t = (i + j + k) * G3;\n const X0 = i - t; // Unskew the cell origin back to (x,y,z) space\n const Y0 = j - t;\n const Z0 = k - t;\n const x0 = x - X0; // The x,y,z distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n // For the 3D case, the simplex shape is a slightly irregular tetrahedron.\n // Determine which simplex we are in.\n let i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords\n let i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords\n if (x0 >= y0) {\n if (y0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // X Y Z order\n else if (x0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // X Z Y order\n else {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // Z X Y order\n }\n else { // x0<y0\n if (y0 < z0) {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Z Y X order\n else if (x0 < z0) {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Y Z X order\n else {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // Y X Z order\n }\n // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),\n // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and\n // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where\n // c = 1/6.\n const x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords\n const y1 = y0 - j1 + G3;\n const z1 = z0 - k1 + G3;\n const x2 = x0 - i2 + 2.0 * G3; // Offsets for third corner in (x,y,z) coords\n const y2 = y0 - j2 + 2.0 * G3;\n const z2 = z0 - k2 + 2.0 * G3;\n const x3 = x0 - 1.0 + 3.0 * G3; // Offsets for last corner in (x,y,z) coords\n const y3 = y0 - 1.0 + 3.0 * G3;\n const z3 = z0 - 1.0 + 3.0 * G3;\n // Work out the hashed gradient indices of the four simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n // Calculate the contribution from the four corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad3x[gi0] * x0 + permGrad3y[gi0] * y0 + permGrad3z[gi0] * z0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad3x[gi1] * x1 + permGrad3y[gi1] * y1 + permGrad3z[gi1] * z1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad3x[gi2] * x2 + permGrad3y[gi2] * y2 + permGrad3z[gi2] * z2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + 1 + perm[jj + 1 + perm[kk + 1]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad3x[gi3] * x3 + permGrad3y[gi3] * y3 + permGrad3z[gi3] * z3);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to stay just inside [-1,1]\n return 32.0 * (n0 + n1 + n2 + n3);\n };\n}\n/**\n * Creates a 4D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction4D}\n */\nexport function createNoise4D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these leads to a ~10% speedup\n const permGrad4x = new Float64Array(perm).map(v => grad4[(v % 32) * 4]);\n const permGrad4y = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 1]);\n const permGrad4z = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 2]);\n const permGrad4w = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 3]);\n return function noise4D(x, y, z, w) {\n let n0, n1, n2, n3, n4; // Noise contributions from the five corners\n // Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in\n const s = (x + y + z + w) * F4; // Factor for 4D skewing\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const l = fastFloor(w + s);\n const t = (i + j + k + l) * G4; // Factor for 4D unskewing\n const X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space\n const Y0 = j - t;\n const Z0 = k - t;\n const W0 = l - t;\n const x0 = x - X0; // The x,y,z,w distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n const w0 = w - W0;\n // For the 4D case, the simplex is a 4D shape I won't even try to describe.\n // To find out which of the 24 possible simplices we're in, we need to\n // determine the magnitude ordering of x0, y0, z0 and w0.\n // Six pair-wise comparisons are performed between each possible pair\n // of the four coordinates, and the results are used to rank the numbers.\n let rankx = 0;\n let ranky = 0;\n let rankz = 0;\n let rankw = 0;\n if (x0 > y0)\n rankx++;\n else\n ranky++;\n if (x0 > z0)\n rankx++;\n else\n rankz++;\n if (x0 > w0)\n rankx++;\n else\n rankw++;\n if (y0 > z0)\n ranky++;\n else\n rankz++;\n if (y0 > w0)\n ranky++;\n else\n rankw++;\n if (z0 > w0)\n rankz++;\n else\n rankw++;\n // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order.\n // Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w and x<w\n // impossible. Only the 24 indices which have non-zero entries make any sense.\n // We use a thresholding to set the coordinates in turn from the largest magnitude.\n // Rank 3 denotes the largest coordinate.\n // Rank 2 denotes the second largest coordinate.\n // Rank 1 denotes the second smallest coordinate.\n // The integer offsets for the second simplex corner\n const i1 = rankx >= 3 ? 1 : 0;\n const j1 = ranky >= 3 ? 1 : 0;\n const k1 = rankz >= 3 ? 1 : 0;\n const l1 = rankw >= 3 ? 1 : 0;\n // The integer offsets for the third simplex corner\n const i2 = rankx >= 2 ? 1 : 0;\n const j2 = ranky >= 2 ? 1 : 0;\n const k2 = rankz >= 2 ? 1 : 0;\n const l2 = rankw >= 2 ? 1 : 0;\n // The integer offsets for the fourth simplex corner\n const i3 = rankx >= 1 ? 1 : 0;\n const j3 = ranky >= 1 ? 1 : 0;\n const k3 = rankz >= 1 ? 1 : 0;\n const l3 = rankw >= 1 ? 1 : 0;\n // The fifth corner has all coordinate offsets = 1, so no need to compute that.\n const x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords\n const y1 = y0 - j1 + G4;\n const z1 = z0 - k1 + G4;\n const w1 = w0 - l1 + G4;\n const x2 = x0 - i2 + 2.0 * G4; // Offsets for third corner in (x,y,z,w) coords\n const y2 = y0 - j2 + 2.0 * G4;\n const z2 = z0 - k2 + 2.0 * G4;\n const w2 = w0 - l2 + 2.0 * G4;\n const x3 = x0 - i3 + 3.0 * G4; // Offsets for fourth corner in (x,y,z,w) coords\n const y3 = y0 - j3 + 3.0 * G4;\n const z3 = z0 - k3 + 3.0 * G4;\n const w3 = w0 - l3 + 3.0 * G4;\n const x4 = x0 - 1.0 + 4.0 * G4; // Offsets for last corner in (x,y,z,w) coords\n const y4 = y0 - 1.0 + 4.0 * G4;\n const z4 = z0 - 1.0 + 4.0 * G4;\n const w4 = w0 - 1.0 + 4.0 * G4;\n // Work out the hashed gradient indices of the five simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n const ll = l & 255;\n // Calculate the contribution from the five corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk + perm[ll]]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad4x[gi0] * x0 + permGrad4y[gi0] * y0 + permGrad4z[gi0] * z0 + permGrad4w[gi0] * w0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad4x[gi1] * x1 + permGrad4y[gi1] * y1 + permGrad4z[gi1] * z1 + permGrad4w[gi1] * w1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad4x[gi2] * x2 + permGrad4y[gi2] * y2 + permGrad4z[gi2] * z2 + permGrad4w[gi2] * w2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad4x[gi3] * x3 + permGrad4y[gi3] * y3 + permGrad4z[gi3] * z3 + permGrad4w[gi3] * w3);\n }\n let t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4;\n if (t4 < 0)\n n4 = 0.0;\n else {\n const gi4 = ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]];\n t4 *= t4;\n n4 = t4 * t4 * (permGrad4x[gi4] * x4 + permGrad4y[gi4] * y4 + permGrad4z[gi4] * z4 + permGrad4w[gi4] * w4);\n }\n // Sum up and scale the result to cover the range [-1,1]\n return 27.0 * (n0 + n1 + n2 + n3 + n4);\n };\n}\n/**\n * Builds a random permutation table.\n * This is exported only for (internal) testing purposes.\n * Do not rely on this export.\n * @private\n */\nexport function buildPermutationTable(random) {\n const tableSize = 512;\n const p = new Uint8Array(tableSize);\n for (let i = 0; i < tableSize / 2; i++) {\n p[i] = i;\n }\n for (let i = 0; i < tableSize / 2 - 1; i++) {\n const r = i + ~~(random() * (256 - i));\n const aux = p[i];\n p[i] = p[r];\n p[r] = aux;\n }\n for (let i = 256; i < tableSize; i++) {\n p[i] = p[i - 256];\n }\n return p;\n}\n//# sourceMappingURL=simplex-noise.js.map","function _prng_restore(prng, xg, opts) {\n let state = opts && opts.state;\n if (state) {\n if (typeof(state) == 'object') xg.copy(state, xg);\n prng.state = () => xg.copy(xg, {});\n }\n}\n\nfunction _prng_xor_core(xg, opts) {\n let prng = () => (xg.next() >>> 0) / 0x100000000;\n\n prng.double = () => {\n let top, bot, result;\n do {\n top = xg.next() >>> 11;\n bot = (xg.next() >>> 0) / 0x100000000;\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n\n prng.int32 = () => xg.next() | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng;\n}\n\n// A port of an algorithm by Johannes Baagøe <[email protected]>, 2010\nfunction prng_alea(seed, opts) {\n let xg = new AleaGen(seed);\n\n let prng = () => xg.next();\n\n prng.double = () =>\n prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53\n\n prng.int32 = () => (xg.next() * 0x100000000) | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\nclass AleaGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let n = 0xefc8249d;\n\n // Apply the seeding algorithm from Baagoe.\n this.c = 1;\n this.s0 = mash(' ');\n this.s1 = mash(' ');\n this.s2 = mash(' ');\n this.s0 -= mash(seed);\n if (this.s0 < 0) { this.s0 += 1; }\n this.s1 -= mash(seed);\n if (this.s1 < 0) { this.s1 += 1; }\n this.s2 -= mash(seed);\n if (this.s2 < 0) { this.s2 += 1; }\n\n function mash(data) {\n data = String(data);\n for (let i = 0; i < data.length; i++) {\n n += data.charCodeAt(i);\n let h = 0.02519603282416938 * n;\n n = h >>> 0;\n h -= n;\n h *= n;\n n = h >>> 0;\n h -= n;\n n += h * 0x100000000; // 2^32\n }\n return (n >>> 0) * 2.3283064365386963e-10; // 2^-32\n }\n }\n\n next() {\n let {c,s0,s1,s2} = this;\n let t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32\n this.s0 = s1;\n this.s1 = s2;\n return this.s2 = t - (this.c = t | 0);\n }\n\n copy(f, t) {\n t.c = f.c;\n t.s0 = f.s0;\n t.s1 = f.s1;\n t.s2 = f.s2;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xor128\" prng algorithm by\nfunction prng_xor128(seed, opts) {\n let xg = new Xor128Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass Xor128Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w} = this;\n let t = x ^ (x << 11);\n this.x = y;\n this.y = z;\n this.z = w;\n return this.w = w ^ ((w >>> 19) ^ t ^ (t >>> 8));\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorwow\" prng algorithm by\nfunction prng_xorwow(seed, opts) {\n let xg = new XorWowGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass XorWowGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n this.v = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n if (k == strseed.length) {\n this.d = this.x << 10 ^ this.x >>> 4;\n }\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w,v,d} = this;\n let t = (x ^ (x >>> 2));\n this.x = y;\n this.y = z;\n this.z = w;\n this.w = v;\n return (this.d = (d + 362437 | 0)) +\n (this.v = (v ^ (v << 4)) ^ (t ^ (t << 1))) | 0;\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n t.v = f.v;\n t.d = f.d;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorshift7\" algorithm by\nfunction prng_xorshift7(seed, opts) {\n let xg = new XorShift7Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass XorShift7Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n var j, w, x = [];\n\n if (seed === (seed | 0)) {\n // Seed state array using a 32-bit integer.\n w = x[0] = seed;\n } else {\n // Seed state using a string.\n seed = '' + seed;\n for (j = 0; j < seed.length; ++j) {\n x[j & 7] = (x[j & 7] << 15) ^\n (seed.charCodeAt(j) + x[(j + 1) & 7] << 13);\n }\n }\n\n // Enforce an array length of 8, not all zeroes.\n while (x.length < 8) x.push(0);\n for (j = 0; j < 8 && x[j] === 0; ++j);\n if (j == 8) w = x[7] = -1; else w = x[j];\n\n this.x = x;\n this.i = 0;\n\n // Discard an initial 256 values.\n for (j = 256; j > 0; --j) {\n this.next();\n }\n }\n\n next() {\n // Update xor generator.\n let t, v, {x,i} = this;\n t = x[i]; t ^= (t >>> 7); v = t ^ (t << 24);\n t = x[(i + 1) & 7]; v ^= t ^ (t >>> 10);\n t = x[(i + 3) & 7]; v ^= t ^ (t >>> 3);\n t = x[(i + 4) & 7]; v ^= t ^ (t << 7);\n t = x[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);\n x[i] = v;\n this.i = (i + 1) & 7;\n return v;\n };\n\n copy(f, t) {\n t.x = [... f.x];\n t.i = f.i;\n return t;\n }\n}\n\n// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.\nfunction prng_xor4096(seed, opts) {\n let xg = new Xor4096Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass Xor4096Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let t, v, i, j, w, X = [], limit = 128;\n if (seed === (seed | 0)) {\n // Numeric seeds initialize v, which is used to generates X.\n v = seed;\n seed = null;\n } else {\n // String seeds are mixed into v and X one character at a time.\n seed = seed + '\\0';\n v = 0;\n limit = Math.max(limit, seed.length);\n }\n // Initialize circular array and weyl value.\n for (i = 0, j = -32; j < limit; ++j) {\n // Put the unicode characters into the array, and shuffle them.\n if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);\n // After 32 shuffles, take v as the starting w value.\n if (j === 0) w = v;\n v ^= v << 10;\n v ^= v >>> 15;\n v ^= v << 4;\n v ^= v >>> 13;\n if (j >= 0) {\n w = (w + 0x61c88647) | 0; // Weyl.\n t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array.\n i = (0 == t) ? i + 1 : 0; // Count zeroes.\n }\n }\n // We have detected all zeroes; make the key nonzero.\n if (i >= 128) {\n X[(seed && seed.length || 0) & 127] = -1;\n }\n // Run the generator 512 times to further mix the state before using it.\n // Factoring this as a function slows the main generator, so it is just\n // unrolled here. The weyl generator is not advanced while warming up.\n i = 127;\n for (j = 4 * 128; j > 0; --j) {\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n X[i] = v ^ t;\n }\n // Storing state as object members is faster than using closure variables.\n this.w = w;\n this.X = X;\n this.i = i;\n }\n\n next() {\n let t, v, {w, X, i} = this;\n // Update Weyl generator.\n this.w = w = (w + 0x61c88647) | 0;\n // Update xor generator.\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n // Update Xor generator array state.\n v = X[i] = v ^ t;\n this.i = i;\n // Result is the combination.\n return (v + (w ^ (w >>> 16))) | 0;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.w = f.w;\n t.X = [... f.X];\n return t;\n }\n}\n\n// A Javascript implementaion of the \"Tyche-i\" prng algorithm by\nfunction prng_tychei(seed, opts) {\n let xg = new TycheiGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass TycheiGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.a = 0;\n this.b = 0;\n this.c = 2654435769 | 0;\n this.d = 1367130551;\n\n if (seed === Math.floor(seed)) {\n // Integer seed.\n this.a = (seed / 0x100000000) | 0;\n this.b = seed | 0;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 20; k++) {\n this.b ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {a,b,c,d} = this;\n b = (b << 25) ^ (b >>> 7) ^ c;\n c = (c - d) | 0;\n d = (d << 24) ^ (d >>> 8) ^ a;\n a = (a - b) | 0;\n this.b = b = (b << 20) ^ (b >>> 12) ^ c;\n this.c = c = (c - d) | 0;\n this.d = (d << 16) ^ (c >>> 16) ^ a;\n return this.a = (a - b) | 0;\n };\n\n copy(f, t) {\n t.a = f.a;\n t.b = f.b;\n t.c = f.c;\n t.d = f.d;\n return t;\n }\n}\n\n\n/* The following is non-inverted tyche, which has better internal\n * bit diffusion, but which is about 25% slower than tyche-i in JS.\n *\n\nclass TycheiGenAlt extends TycheiGen {\n next() {\n let {a,b,c,d} = this\n a = (a + b | 0) >>> 0;\n d = d ^ a; d = d << 16 ^ d >>> 16;\n c = c + d | 0;\n b = b ^ c; b = b << 12 ^ d >>> 20;\n this.a = a = a + b | 0;\n d = d ^ a; this.d = d = d << 8 ^ d >>> 24;\n this.c = c = c + d | 0;\n b = b ^ c;\n return this.b = (b << 7 ^ b >>> 25);\n }\n}\n*/\n\n/*\nCopyright 2019 David Bau.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*/\nfunction prng_arc4(seed, opts) {\n let xg = new ARC4Gen(seed);\n let prng = () => xg.next();\n\n prng.double = prng;\n\n prng.int32 = () => xg.g(4) | 0;\n\n prng.quick = () => xg.g(4) / 0x100000000;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\n\n//\n// ARC4\n//\n// An ARC4 implementation. The constructor takes a key in the form of\n// an array of at most (width) integers that should be 0 <= x < (width).\n//\n// The g(count) method returns a pseudorandom integer that concatenates\n// the next (count) outputs from ARC4. Its return value is a number x\n// that is in the range 0 <= x < (width ^ count).\n//\n\n//\n// The following constants are related to IEEE 754 limits.\n//\n\n// const width = 256 // each RC4 output is 0 <= x < 256\n// const chunks = 6 // at least six RC4 outputs for each double\nconst _arc4_startdenom = 281474976710656; // 256 ** 6 == width ** chunks\nconst _arc4_significance = 4503599627370496; // 2 ** 52 significant digits in a double\nconst _arc4_overflow = 9007199254740992; // 2 ** 53 == significance * 2\n\n\nclass ARC4Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let key = this.mixkey(seed, []);\n let i,j,t, S=[], keylen = key.length;\n this.i = this.j = i = j = 0;\n this.S = S;\n\n // The empty key [] is treated as [0].\n if (!keylen) { key = [keylen++]; }\n\n // Set up S using the standard key scheduling algorithm.\n while (i <= 0xff) {\n S[i] = i++;\n }\n for (i = 0; i <= 0xff; i++) {\n S[i] = S[j = 0xff & (j + key[i % keylen] + (t = S[i]))];\n S[j] = t;\n }\n\n // For robust unpredictability, the function call below automatically\n // discards an initial batch of values. This is called RC4-drop[256].\n // See http://google.com/search?q=rsa+fluhrer+response&btnI\n this.g(256);\n }\n\n next() {\n // This function returns a random double in [0, 1) that contains\n // randomness in every bit of the mantissa of the IEEE 754 value.\n\n let n = this.g(6); // Start with a numerator n < 2 ^ 48\n let d = _arc4_startdenom; // and denominator d = 2 ^ 48.\n let x = 0; // and no 'extra last byte'.\n\n while (n < _arc4_significance) { // Fill up all significant digits (2 ** 52)\n n = (n + x) * 256; // by shifting numerator and\n d *= 256; // denominator and generating a\n x = this.g(1); // new least-significant-byte.\n }\n while (n >= _arc4_overflow) { // To avoid rounding past overflow, before adding\n n /= 2; // last byte, shift everything\n d /= 2; // right using integer math until\n x >>>= 1; // we have exactly the desired bits.\n }\n return (n + x) / d; // Form the number within [0, 1).\n }\n\n g(count) {\n // The \"g\" method returns the next (count) outputs as one number.\n let t, r = 0, {i,j,S} = this;\n while (count--) {\n t = S[i = 0xff & (i + 1)];\n r = r * 256 + S[0xff & ((S[i] = S[j = 0xff & (j + t)]) + (S[j] = t))];\n }\n this.i = i;\n this.j = j;\n return r;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.j = f.j;\n t.S = [... f.S];\n return t;\n }\n\n mixkey(seed, key) {\n seed = seed + '';\n let smear=0, j=0;\n while (j < seed.length) {\n key[0xff & j] =\n 0xff & ((smear ^= key[0xff & j] * 19) + seed.charCodeAt(j++));\n }\n return key\n }\n}\n\nexport { prng_alea, prng_arc4, prng_tychei, prng_xor128, prng_xor4096, prng_xorshift7, prng_xorwow };\n//# sourceMappingURL=index.mjs.map\n","import { usesRadians as runtimeUsesRadians } from \"./runtime.js\";\n\n// =============================================================================\n// Section: Randomness & Noise\n// =============================================================================\n\nimport { createNoise2D } from \"simplex-noise\";\nimport { prng_alea } from \"esm-seedrandom\";\n\n/**\n * A uniform PRNG function. Returns a float in [0,1).\n * @callback RNG\n * @returns {number}\n */\n/** @type {RNG} */\nlet rng = prng_alea(Math.random());\nlet rng2 = prng_alea(Math.random());\n\nconst _seedCallbacks = [];\n\n/**\n * Register a callback to be called whenever seed() is invoked.\n * Used internally by modules that maintain gaussian pools.\n * @param {Function} cb\n */\nexport const _onSeed = (cb) => _seedCallbacks.push(cb);\n\n/**\n * Seed the random number generator.\n * @param {number|string} s – The seed value.\n * @returns {void}\n */\nexport const seed = (s) => {\n rng = prng_alea(s);\n rng2 = prng_alea(`${s}:2`);\n for (const callback of _seedCallbacks) {\n callback();\n }\n};\n\n/**\n * Simplex‐noise 2D function.\n * @type {function(number, number): number}\n */\nexport let noise = createNoise2D(prng_alea(Math.random()));\nexport let noise2 = createNoise2D(prng_alea(Math.random()));\n\n/**\n * Seed the noise generator.\n * @param {number|string} s - The seed value.\n * @returns {void}\n */\nexport const noiseSeed = (s) => {\n noise = createNoise2D(prng_alea(s));\n noise2 = createNoise2D(prng_alea(`${s}:2`));\n};\n\n/**\n * Returns a random float in [min, max).\n * @param {number} [min=0]\n * @param {number} [max=1]\n * @returns {number}\n */\nexport const rr = (e = 0, r = 1) => e + rng() * (r - e);\nexport const rr2 = (e = 0, r = 1) => e + rng2() * (r - e);\n\n/**\n * Selects a random element from an array.\n * @param {T[]} array - Input array.\n * @returns {T}\n */\nexport const rArray = (array) => array[~~(rng() * array.length)];\n\n/**\n * Returns a random integer in [min, max).\n * @param {number} min\n * @param {number} max\n * @returns {number}\n */\nexport const randInt = (e, r) => ~~rr(e, r);\nexport const randInt2 = (e, r) => ~~rr2(e, r);\n\n/**\n * Gaussian (normal) random sample N(mean, stdev²).\n * @param {number} [mean=0]\n * @param {number} [stdev=1]\n * @returns {number}\n */\nexport const gaussian = (mean = 0, stdev = 1) => {\n const u = 1 - rng();\n const v = rng();\n const z = Math.sqrt(-2.0 * Math.log(u)) * cos(360 * v);\n return z * stdev + mean;\n};\n\n/**\n * Picks a key from an object according to weighted probabilities.\n * @param {Object<string|number, number>} weights\n * @returns {string|number}\n */\nexport const weightedRand = (weights) => {\n let totalWeight = 0;\n const entries = [];\n\n // Build cumulative weights array\n for (const key in weights) {\n totalWeight += weights[key];\n entries.push({ key, cumulative: totalWeight });\n }\n\n // Get a random number between 0 and totalWeight\n const rnd = rng() * totalWeight;\n\n // Pick the first entry where rnd is less than the cumulative weight\n for (const { key, cumulative } of entries) {\n if (rnd < cumulative) {\n return isNaN(key) ? key : parseInt(key);\n }\n }\n};\n\n// =============================================================================\n// Section: Numeric Mapping & Constraints\n// =============================================================================\n\n/**\n * Maps a value from range [a,b] to [c,d], optionally clamped.\n * @param {number} value\n * @param {number} a\n * @param {number} b\n * @param {number} c\n * @param {number} d\n * @param {boolean} [withinBounds=false]\n * @returns {number}\n */\nexport const map = (value, a, b, c, d, withinBounds = false) => {\n let r = c + ((value - a) / (b - a)) * (d - c);\n if (!withinBounds) return r;\n if (c < d) return constrain(r, c, d);\n else return constrain(r, d, c);\n};\n\n/**\n * Constrains a number within the provided bounds.\n * @param {number} n - The number.\n * @param {number} low - Lower bound.\n * @param {number} high - Upper bound.\n * @returns {number} The constrained number.\n */\nexport const constrain = (n, low, high) => Math.max(Math.min(n, high), low);\n\n// =============================================================================\n// Section: Trigonometry\n// =============================================================================\n\n/**\n * Normalize an angle in degrees to [0,360).\n * @param {number} angle\n * @returns {number}\n */\nconst nAngle = (angle) => {\n angle = angle % 360;\n return angle < 0 ? angle + 360 : angle;\n};\n\n// number of discrete steps (360° × 4 samples per degree)\nconst totalDegrees = 1440;\nconst radiansPerIndex = (2 * Math.PI) / totalDegrees;\n\n// lazy‐initialized lookup tables\nconst cLookup = new Float32Array(totalDegrees).fill(NaN);\nconst sLookup = new Float32Array(totalDegrees).fill(NaN);\n\n/**\n * Cosine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const cos = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = cLookup[idx];\n if (isNaN(v)) {\n v = Math.cos(idx * radiansPerIndex);\n cLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Sine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const sin = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = sLookup[idx];\n if (isNaN(v)) {\n v = Math.sin(idx * radiansPerIndex);\n sLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Converts radians to degrees, normalized to [0,360).\n * @param {number} rad\n * @returns {number}\n */\nexport const toDegrees = (rad, isRad = false) => {\n if (isRad || runtimeUsesRadians()) {\n let angle = ((rad * 180) / Math.PI) % 360;\n return angle < 0 ? angle + 360 : angle;\n } else {\n return rad;\n }\n};\n\n/**\n * Converts radians to degrees without wrapping the result.\n * Preserves signed angles so downstream scaling keeps its direction.\n * @param {number} angle\n * @param {boolean} [isRad=false]\n * @returns {number}\n */\nexport const toDegreesSigned = (angle, isRad = false) =>\n isRad || runtimeUsesRadians()\n ? (angle * 180) / Math.PI\n : angle;\n\n// =============================================================================\n// Section: Geometry & Transforms\n// =============================================================================\n\n/**\n * Rotates point (x,y) around center (cx,cy) by angle degrees.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x\n * @param {number} y\n * @param {number} angle - Degrees\n * @returns {{x:number,y:number}}\n */\nexport const rotate = (cx, cy, x, y, angle) => {\n let coseno = cos(angle),\n seno = sin(angle),\n nx = coseno * (x - cx) + seno * (y - cy) + cx,\n ny = coseno * (y - cy) - seno * (x - cx) + cy;\n return { x: nx, y: ny };\n};\n\n/**\n * Euclidean distance between two points.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const dist = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1);\n\n/**\n * Angle in degrees between two points, measured clockwise from +X.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const calcAngle = (x1, y1, x2, y2) =>\n toDegrees(Math.atan2(-(y2 - y1), x2 - x1), true);\n\n/**\n * Intersection of two line segments, or false if none.\n * @param {{x:number,y:number}} s1a\n * @param {{x:number,y:number}} s1b\n * @param {{x:number,y:number}} s2a\n * @param {{x:number,y:number}} s2b\n * @param {boolean} [includeSegmentExtension=false]\n * @returns {{x:number,y:number}|false}\n */\nexport const intersectLines = (\n s1a,\n s1b,\n s2a,\n s2b,\n includeSegmentExtension = false\n) => {\n // Extract coordinates from points\n let x1 = s1a.x,\n y1 = s1a.y;\n let x2 = s1b.x,\n y2 = s1b.y;\n let x3 = s2a.x,\n y3 = s2a.y;\n let x4 = s2b.x,\n y4 = s2b.y;\n // Early return if line segments are points or if the lines are parallel\n if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) {\n return false; // Segments are points\n }\n let deltaX1 = x2 - x1,\n deltaY1 = y2 - y1;\n let deltaX2 = x4 - x3,\n deltaY2 = y4 - y3;\n let denominator = deltaY2 * deltaX1 - deltaX2 * deltaY1;\n if (denominator === 0) {\n return false; // Lines are parallel\n }\n // Calculate the intersection point\n let ua = (deltaX2 * (y1 - y3) - deltaY2 * (x1 - x3)) / denominator;\n let ub = (deltaX1 * (y1 - y3) - deltaY1 * (x1 - x3)) / denominator;\n // Check if the intersection is within the bounds of the line segments\n if (!includeSegmentExtension && (ub < 0 || ub > 1)) {\n return false;\n }\n // Calculate the intersection coordinates\n let x = x1 + ua * deltaX1;\n let y = y1 + ua * deltaY1;\n return { x: x, y: y };\n};\n","// =============================================================================\n// Target Runtime Hooks\n// =============================================================================\n\n/**\n * Shared target state exposed to core modules.\n *\n * Host adapters are expected to keep these bindings updated with the currently\n * active drawing target. The exact object type is adapter-defined, but core code\n * assumes the active renderer exposes:\n * - `drawingContext`: the active WebGL context\n * - target dimensions through `Cwidth` / `Cheight`\n * - pixel density through `Density`\n */\n\nexport let Cwidth, Cheight, Instance, Renderer, Density;\n\nlet targetRuntime = {\n load: () => {\n throw new Error(\"No target runtime adapter registered.\");\n },\n syncDensity: () => Density,\n isCanvasReady: () => {\n throw new Error(\"No target runtime adapter registered.\");\n },\n instance: (inst) => {\n Instance = inst;\n },\n activateInstance: (inst) => {\n Instance = inst;\n },\n deactivateInstance: () => {},\n getActiveFramebuffer: () => null,\n isFramebufferTarget: () => false,\n};\n\n/**\n * Updates the shared target state consumed by core modules.\n *\n * @param {object} state\n */\nexport function setTargetState(state) {\n if (\"Cwidth\" in state) Cwidth = state.Cwidth;\n if (\"Cheight\" in state) Cheight = state.Cheight;\n if (\"Instance\" in state) Instance = state.Instance;\n if (\"Renderer\" in state) Renderer = state.Renderer;\n if (\"Density\" in state) Density = state.Density;\n}\n\n/**\n * Registers or updates host target hooks used by core modules.\n *\n * @param {object} hooks\n */\nexport function setTargetRuntime(hooks) {\n targetRuntime = { ...targetRuntime, ...hooks };\n}\n\nexport const load = (buffer = false) => targetRuntime.load(buffer);\nexport const syncDensity = () => targetRuntime.syncDensity();\nexport const isCanvasReady = () => targetRuntime.isCanvasReady();\nexport const instance = (inst) => targetRuntime.instance(inst);\nexport const activateInstance = (inst) => targetRuntime.activateInstance(inst);\nexport const deactivateInstance = () => targetRuntime.deactivateInstance();\nexport const getActiveFramebuffer = () => targetRuntime.getActiveFramebuffer();\nexport const isFramebufferTarget = (target) =>\n targetRuntime.isFramebufferTarget(target);\n","// =============================================================================\n// Module: Dirty Rect Utilities\n// =============================================================================\n/**\n * Expands a dirty rectangle outward by a constant padding value.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Rect to expand.\n * @param {number} [padding=0] - Padding in pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Expanded rect.\n */\nexport const expandDirtyRect = (rect, padding = 0) =>\n rect\n ? {\n minX: rect.minX - padding,\n minY: rect.minY - padding,\n maxX: rect.maxX + padding,\n maxY: rect.maxY + padding,\n }\n : null;\n\n/**\n * Clamps a dirty rectangle to explicit target bounds.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Candidate rect.\n * @param {number} width - Target width in physical pixels.\n * @param {number} height - Target height in physical pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Clamped rect.\n */\nexport const normalizeDirtyRect = (rect, width, height) => {\n if (!rect) return null;\n\n const minX = Math.max(0, Math.floor(Math.min(rect.minX, rect.maxX)));\n const minY = Math.max(0, Math.floor(Math.min(rect.minY, rect.maxY)));\n const maxX = Math.min(width, Math.ceil(Math.max(rect.minX, rect.maxX)));\n const maxY = Math.min(height, Math.ceil(Math.max(rect.minY, rect.maxY)));\n\n if (maxX <= minX || maxY <= minY) return null;\n\n return { minX, minY, maxX, maxY };\n};\n\n/**\n * Returns the union of two dirty rectangles.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} a - First rect.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} b - Second rect.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Union rect.\n */\nexport const unionDirtyRect = (a, b) => {\n if (!a) return b;\n if (!b) return a;\n\n return {\n minX: Math.min(a.minX, b.minX),\n minY: Math.min(a.minY, b.minY),\n maxX: Math.max(a.maxX, b.maxX),\n maxY: Math.max(a.maxY, b.maxY),\n };\n};\n\n/**\n * Returns a dirty rectangle covering the full target bounds.\n *\n * @param {number} width - Target width in physical pixels.\n * @param {number} height - Target height in physical pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}} Full-target rect.\n */\nexport const getFullDirtyRect = (width, height) => ({\n minX: 0,\n minY: 0,\n maxX: width,\n maxY: height,\n});\n","// =============================================================================\n// Compositor Runtime Hooks\n// =============================================================================\n\n/**\n * Shared compositor helpers and host hooks.\n *\n * The shared code in this module assumes framebuffer-like targets expose:\n * - `framebuffer`: native WebGL framebuffer handle\n * - optional lifecycle methods supplied by the host adapter\n *\n * Higher-level core modules also attach their own bookkeeping fields onto the\n * active renderer and mask targets, such as:\n * - `shaderProgram`\n * - `blendSourceFramebuffer`\n * - `glMask`\n * - `fillMaskFramebuffer`\n * - `mask`\n *\n * These are library-level contract fields, not host-specific internals.\n */\n\nexport const create2DCanvas = (width, height, willReadFrequently = false) => {\n const canvas =\n typeof OffscreenCanvas !== \"undefined\"\n ? new OffscreenCanvas(width, height)\n : (() => {\n const element = document.createElement(\"canvas\");\n element.width = width;\n element.height = height;\n return element;\n })();\n canvas.drawingContext = canvas.getContext(\n \"2d\",\n willReadFrequently ? { willReadFrequently: true } : undefined,\n );\n return canvas;\n};\n\nexport const get2DContext = (canvas, willReadFrequently = false) => {\n canvas.drawingContext ??= canvas.getContext(\n \"2d\",\n willReadFrequently ? { willReadFrequently: true } : undefined,\n );\n return canvas.drawingContext;\n};\n\nexport function blitDefaultFramebufferSource({\n renderer,\n sourceFramebuffer,\n dirtyRect,\n getTargetPixelSize,\n toScissorBox,\n}) {\n const gl = renderer.drawingContext;\n const { width, height } = getTargetPixelSize();\n const sourceBox = dirtyRect ? toScissorBox(dirtyRect) : null;\n const previousReadFramebuffer = gl.getParameter(gl.READ_FRAMEBUFFER_BINDING);\n const previousDrawFramebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING);\n\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, sourceFramebuffer.framebuffer);\n gl.clearColor(0, 0, 0, 0);\n gl.clear(gl.COLOR_BUFFER_BIT);\n gl.blitFramebuffer(\n sourceBox?.x ?? 0,\n sourceBox?.y ?? 0,\n sourceBox ? sourceBox.x + sourceBox.width : width,\n sourceBox ? sourceBox.y + sourceBox.height : height,\n sourceBox?.x ?? 0,\n sourceBox?.y ?? 0,\n sourceBox ? sourceBox.x + sourceBox.width : width,\n sourceBox ? sourceBox.y + sourceBox.height : height,\n gl.COLOR_BUFFER_BIT,\n gl.NEAREST,\n );\n\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, previousReadFramebuffer);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, previousDrawFramebuffer);\n\n return sourceFramebuffer;\n}\n\nlet compositorRuntime = {\n clearTarget: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n ensureBlendShaderProgram: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n ensureBlendSourceFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n createFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n runBlendShaderPass: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n blitSourceToFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n};\n\n/**\n * Registers or updates host compositor hooks used by core compositing code.\n *\n * @param {object} hooks\n */\nexport function setCompositorRuntime(hooks) {\n compositorRuntime = { ...compositorRuntime, ...hooks };\n}\n\nexport const clearTarget = (...args) => compositorRuntime.clearTarget(...args);\nexport const ensureBlendShaderProgram = (...args) =>\n compositorRuntime.ensureBlendShaderProgram(...args);\nexport const ensureBlendSourceFramebuffer = (...args) =>\n compositorRuntime.ensureBlendSourceFramebuffer(...args);\nexport const createFramebuffer = (...args) =>\n compositorRuntime.createFramebuffer(...args);\nexport const runBlendShaderPass = (...args) =>\n compositorRuntime.runBlendShaderPass(...args);\nexport const blitSourceToFramebuffer = (...args) =>\n compositorRuntime.blitSourceToFramebuffer(...args);\n","import {\n Cwidth,\n Cheight,\n Renderer,\n Density,\n load as loadTarget,\n isCanvasReady,\n syncDensity,\n getActiveFramebuffer,\n isFramebufferTarget,\n} from \"./target.js\";\nimport {\n expandDirtyRect,\n normalizeDirtyRect as clampDirtyRect,\n unionDirtyRect,\n getFullDirtyRect as getFullRect,\n} from \"./dirty_rect.js\";\nimport {\n clearTarget as clearRenderTarget,\n ensureBlendShaderProgram,\n ensureBlendSourceFramebuffer,\n runBlendShaderPass,\n blitSourceToFramebuffer,\n} from \"./compositor_runtime.js\";\n\nimport vertSrc from \"./gl/shader.vert\";\nimport fragSrc from \"./gl/shader.frag\";\n\n// =============================================================================\n// Module: Configure and Initiate\n// =============================================================================\n/**\n * This module handles the configuration and initialization of the drawing system.\n * It manages canvas properties, ensures the system is ready for rendering, and\n * provides utilities for saving and restoring states.\n */\n\nlet strokeComposite = null;\nlet fillComposite = null;\n\nexport const registerStrokeComposite = (composite) => {\n strokeComposite = composite;\n};\n\nexport const registerFillComposite = (composite) => {\n fillComposite = composite;\n};\n\nconst clearTarget = (target) => {\n clearRenderTarget(Renderer, target, isFramebufferTarget);\n};\n\n// =============================================================================\n// Section: Dirty Rect Utilities\n// =============================================================================\n/**\n * Returns the current render target size in physical pixels.\n * @returns {{width: number, height: number}} Pixel size of the active target.\n */\nconst getTargetPixelSize = () => ({\n width: Math.max(1, Math.round(Cwidth * Density)),\n height: Math.max(1, Math.round(Cheight * Density)),\n});\n\nconst normalizeDirtyRect = (rect) => {\n if (!rect) return null;\n const { width, height } = getTargetPixelSize();\n return clampDirtyRect(rect, width, height);\n};\n\n/**\n * Returns a dirty rectangle covering the full active target.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}} Full-target rect.\n */\nconst getFullDirtyRect = () => {\n const { width, height } = getTargetPixelSize();\n return getFullRect(width, height);\n};\n\n// =============================================================================\n// Section: Scissor Helpers\n// =============================================================================\n/**\n * Converts a top-left-based dirty rectangle into a WebGL scissor box.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Dirty rect.\n * @returns {{x:number,y:number,width:number,height:number}|null} Scissor box or null.\n */\nconst toScissorBox = (rect, flipY = true) => {\n const normalized = normalizeDirtyRect(rect);\n if (!normalized) return null;\n\n const { height } = getTargetPixelSize();\n return {\n x: normalized.minX,\n y: flipY ? height - normalized.maxY : normalized.minY,\n width: normalized.maxX - normalized.minX,\n height: normalized.maxY - normalized.minY,\n };\n};\n\n/**\n * Runs a draw callback with a temporary scissor region.\n * @param {WebGL2RenderingContext} gl - Active WebGL context.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Dirty rect.\n * @param {Function} draw - Draw callback executed under the scissor box.\n */\nconst withScissor = (gl, rect, draw, flipY = true) => {\n const box = toScissorBox(rect, flipY);\n if (!box) {\n draw();\n return;\n }\n\n // Scissor is never nested in this module, so we can set/clear it directly\n // without saving previous GL state.\n gl.enable(gl.SCISSOR_TEST);\n gl.scissor(box.x, box.y, box.width, box.height);\n\n try {\n draw();\n } finally {\n gl.disable(gl.SCISSOR_TEST);\n }\n};\n\n/**\n * Stores the current state of the drawing system.\n * Can be used to save and restore configurations or canvas states.\n */\nexport const State = {};\n/**\n * Handles color blending using WebGL shaders. Implements advanced blending\n * effects based on Kubelka-Munk theory. Relies on spectral.js for blending logic.\n */\n\n// =============================================================================\n// Section: Color Blending / Rendering\n// =============================================================================\n/**\n * Ensures the Mix object is initialized and ready for blending.\n */\nexport const isMixReady = () => {\n if (!Renderer?.loaded) {\n isCanvasReady();\n Mix.load();\n }\n};\n\n/**\n * Manages blending operations with WebGL shaders.\n * @property {boolean} loaded - Indicates if shaders are loaded.\n * @property {boolean} isBlending - Indicates if blending is active.\n * @property {object} currentColor - Current color in WebGL format.\n * @property {function} load - Initializes blending resources.\n * @property {function} blend - Applies blending effects.\n */\nexport const Mix = {\n isBlending: false,\n cachedColor: null,\n\n /**\n * Merges a new dirty rectangle into the target's accumulated draw bounds.\n * @param {object} target - Mask buffer receiving draw output.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Rect to merge.\n */\n markDirtyRect(target, rect) {\n const normalized = normalizeDirtyRect(rect);\n if (!target || !normalized) return;\n target.dirtyRect = unionDirtyRect(target.dirtyRect, normalized);\n target.isDrawn = true;\n },\n\n /**\n * Clears a mask buffer and resets its dirty-rect tracking.\n * @param {object} target - Mask buffer to reset.\n */\n clearMask(target) {\n if (!target) return;\n const composite = target === this.glMask ? strokeComposite : fillComposite;\n composite?.clearMask?.(target, clearTarget);\n },\n\n /**\n * Resolves the region that should be composited back into the destination.\n * @param {object} target - Mask buffer being sampled.\n * @param {boolean} isBrushMask - True when compositing the GL brush mask.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\n getCompositeRect(target, isBrushMask) {\n const composite = isBrushMask ? strokeComposite : fillComposite;\n return composite?.getCompositeRect?.(\n target,\n getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n );\n },\n\n // =============================================================================\n // Section: Setup and load shaders\n // =============================================================================\n /**\n * Ensures the mask buffers and blend shader exist for the current renderer.\n */\n load() {\n syncDensity();\n const needsBlendSourceFramebuffer =\n !Renderer.blendSourceFramebuffer ||\n Renderer.blendSourceFramebuffer.width !== Cwidth ||\n Renderer.blendSourceFramebuffer.height !== Cheight ||\n (typeof Renderer.blendSourceFramebuffer.pixelDensity === \"function\" &&\n Renderer.blendSourceFramebuffer.pixelDensity() !== Density);\n ensureBlendShaderProgram(Renderer, vertSrc, fragSrc);\n\n this.glMask = strokeComposite?.ensureResources?.(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n );\n const fillResources = fillComposite?.ensureResources?.(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n clearTarget,\n ) ?? {\n mask: null,\n ctx: null,\n };\n\n if (needsBlendSourceFramebuffer) {\n Renderer.blendSourceFramebuffer = ensureBlendSourceFramebuffer(\n Renderer,\n Renderer.blendSourceFramebuffer,\n Cwidth,\n Cheight,\n Density,\n );\n }\n\n this.mask = fillResources.mask;\n this.ctx = fillResources.ctx;\n },\n\n // =============================================================================\n // Section: Compositing\n // =============================================================================\n /**\n * Flushes pending mask work when the blend color changes or a frame ends.\n * @param {Color|false} [_color=false] - New blend color.\n * @param {boolean} [_isLast=false] - True when this is the final blend flush.\n */\n blend(_color = false, _isLast = false) {\n isMixReady();\n // Only one mask is \"active\" for the current drawing mode; the other one\n // may still need flushing if the mode just changed mid-frame.\n const isBrushMask = this.isBrush === true;\n const mask = isBrushMask ? this.glMask : this.mask;\n const otherMask = isBrushMask ? this.mask : this.glMask;\n const nextColor = _color?._array;\n const colorChanged =\n !!nextColor &&\n (this.cachedColor?.[0] !== nextColor[0] ||\n this.cachedColor?.[1] !== nextColor[1] ||\n this.cachedColor?.[2] !== nextColor[2] ||\n this.cachedColor?.[3] !== nextColor[3]);\n if (!this.isBlending && nextColor) {\n this.isBlending = true;\n this.cachedColor = nextColor;\n // Reset the brush mask fully at the start of each blend cycle so stale\n // dirty-rect bookkeeping cannot leak an old stroke into the next color.\n this.clearMask(this.glMask);\n }\n\n if (_isLast || colorChanged) {\n if (this.justChanged) {\n this.applyShader(otherMask, !isBrushMask);\n this.justChanged = false;\n }\n if (this.isBlending) {\n this.applyShader(mask, isBrushMask);\n }\n if (nextColor) this.cachedColor = nextColor;\n if (_isLast) {\n this.isBlending = false;\n this.cachedColor = null;\n \n }\n }\n },\n\n /**\n * Runs the blend shader over a mask and composites the result into the active renderer.\n * @param {object} mask - Mask buffer to composite.\n * @param {boolean} isBrushMask - True when compositing the GL brush mask.\n */\n applyShader(mask, isBrushMask) {\n if (!mask?.isDrawn) return;\n\n const dirtyRect = this.getCompositeRect(mask, isBrushMask);\n if (!dirtyRect) {\n this.clearMask(mask);\n return;\n }\n\n const gl = Renderer.drawingContext;\n const shader = Renderer.shaderProgram;\n const activeFramebuffer = getActiveFramebuffer();\n const source = blitSourceToFramebuffer({\n renderer: Renderer,\n sourceTarget: activeFramebuffer ?? Renderer,\n sourceFramebuffer: Renderer.blendSourceFramebuffer,\n dirtyRect,\n isFramebufferTarget,\n Cwidth,\n Cheight,\n getTargetPixelSize,\n toScissorBox,\n withScissor,\n });\n const targetIsFramebuffer = !!activeFramebuffer;\n const composite = isBrushMask ? strokeComposite : fillComposite;\n const shaderMask = composite.getShaderMask(\n Renderer,\n mask,\n dirtyRect,\n normalizeDirtyRect,\n getFullDirtyRect,\n clearTarget,\n );\n\n runBlendShaderPass({\n renderer: Renderer,\n shader,\n source,\n mask: shaderMask,\n color: this.cachedColor,\n isBrushMask,\n Cwidth,\n Cheight,\n dirtyRect,\n targetIsFramebuffer,\n withScissor,\n });\n this.clearMask(mask);\n },\n};\n\n/**\n * Flushes any pending stroke/fill mask work into the current target and resets\n * the shared compositor back to its initial idle state.\n */\nexport const flushActiveComposite = () => {\n isMixReady();\n Mix.blend(false, true);\n Mix.clearMask(Mix.glMask);\n Mix.clearMask(Mix.mask);\n Mix.justChanged = false;\n Mix.isBlending = false;\n Mix.isBrush = null;\n Mix.cachedColor = null;\n};\n\n/**\n * Loads and initializes the drawing target, then refreshes compositing\n * resources if the renderer was already active.\n *\n * @param {object|false} [buffer=false] - Optional offscreen target.\n */\nexport const load = (buffer = false) => {\n loadTarget(buffer);\n if (Renderer.loaded) Mix.load();\n};\n","import { Cwidth, Cheight } from \"./target.js\";\nimport { isMixReady, State } from \"./color.js\";\nimport { randInt2, noise2, rr2, sin, cos, map, toDegreesSigned } from \"./utils.js\";\nimport { getAffineMatrix } from \"./runtime.js\";\n\n// =============================================================================\n// Section: Matrix transformations\n// =============================================================================\n\n// =============================================================================\n// Section: Field Initialization\n// =============================================================================\n\nlet isLoaded = false;\n\n/**\n * Ensures the field system is initialized and ready for use.\n * If the field is not loaded, it initializes the mixing system and creates the field.\n */\nexport function isFieldReady() {\n if (!isLoaded) {\n isMixReady(); // Ensure the mixing system is ready\n createField(); // Initialize the field\n isLoaded = true;\n }\n}\n\n// =============================================================================\n// Section: Position Class\n// =============================================================================\n\n/**\n * The Position class represents a point within a two-dimensional space, which can interact with a vector field.\n * It provides methods to update the position based on the field's flow and to check whether the position is\n * within certain bounds (e.g., within the field or canvas).\n */\nexport class Position {\n /**\n * Constructs a new Position instance.\n * @param {number} x - The initial x-coordinate.\n * @param {number} y - The initial y-coordinate.\n */\n constructor(x, y) {\n isFieldReady();\n const m = getAffineMatrix();\n this.mx = m.x;\n this.my = m.y;\n this.update(x, y);\n this.plotted = 0; // Tracks the total distance plotted\n }\n\n /**\n * Updates the position's coordinates and calculates its offsets and indices within the flow field.\n * @param {number} x - The new x-coordinate.\n * @param {number} y - The new y-coordinate.\n */\n update(x, y) {\n this.x = x;\n this.y = y;\n this.colIdx = Math.round((x + this.mx - left_x) / resolution);\n this.rowIdx = Math.round((y + this.my - top_y) / resolution);\n }\n\n /**\n * Resets the 'plotted' property to 0.\n */\n reset() {\n this.plotted = 0;\n }\n\n /**\n * Checks if the position is within the active flow field's bounds.\n * @returns {boolean} - True if the position is within the flow field, false otherwise.\n */\n isIn() {\n return State.field.isActive\n ? Position.isIn(this.colIdx, this.rowIdx)\n : this.isInCanvas(this.x, this.y);\n }\n\n /**\n * Checks if the position is within the canvas bounds (with a margin).\n * @returns {boolean} - True if the position is within bounds, false otherwise.\n */\n isInCanvas() {\n const margin = 0.3;\n const w = Cwidth;\n const h = Cheight;\n const x = this.x + this.mx;\n const y = this.y + this.my;\n return (\n x >= -margin * w &&\n x <= (1 + margin) * w &&\n y >= -margin * h &&\n y <= (1 + margin) * h\n );\n }\n\n /**\n * Calculates the angle of the flow field at the position's current coordinates.\n * @returns {number} - The internal flow angle in degrees, or 0 if the position is not in the field or if no field is active.\n */\n angle(skipCheck = false) {\n if (!State.field.isActive) return 0;\n return (skipCheck || this.isIn())\n ? flow_field()[this.colIdx][this.rowIdx] * State.field.wiggle\n : 0;\n }\n\n /**\n * Moves the position along the flow field by a certain length.\n * @param {number} _dir - The direction of movement, interpreted using the current runtime angle units.\n * @param {number} _length - The length to move along the field.\n * @param {number} _step_length - The length of each step.\n */\n moveTo(_dir, _length, _step_length = 1) {\n this.movePos(toDegreesSigned(_dir), _length, _step_length);\n }\n\n /**\n * Internal variant of moveTo() that expects a degree value already normalized to the library's internal representation.\n */\n _moveToDegrees(_dir, _length, _step_length = 1) {\n this.movePos(_dir, _length, _step_length);\n }\n\n /**\n * Plots a point to another position within the flow field, following a Plot object\n * @param {Position} _plot - The Plot path object.\n * @param {number} _length - The length to move towards the target position.\n * @param {number} _step_length - The length of each step.\n * @param {number} _scale - The scaling factor for the plotting path.\n */\n plotTo(_plot, _length, _step_length, _scale = 1) {\n this.movePos(_plot, _length, _step_length, _scale);\n }\n\n movePos(_dirPlot, _length, _step, _scale = false) {\n const scaleFactor = _scale || 1;\n if (!this.isIn()) {\n this.plotted += _step / scaleFactor;\n return;\n }\n const steps = _length / _step;\n const fieldActive = State.field.isActive;\n const usePlot = !!_scale;\n for (let i = 0; i < steps; i++) {\n const angle =\n (fieldActive ? this.angle(true) : 0) - (usePlot ? _dirPlot.angle(this.plotted) : _dirPlot);\n // Calculate new position\n this.update(this.x + _step * cos(angle), this.y + _step * sin(angle));\n this.plotted += _step / scaleFactor;\n }\n }\n\n // Static Methods\n\n /**\n * Gets the row index for a given y-coordinate.\n * @param {number} y - The y-coordinate.\n * @returns {number} - The row index.\n */\n static getRowIndex(y, d = 1) {\n const y_offset = y + getAffineMatrix().y - top_y;\n return Math.round(y_offset / resolution / d);\n }\n\n /**\n * Gets the column index for a given x-coordinate.\n * @param {number} x - The x-coordinate.\n * @returns {number} - The column index.\n */\n static getColIndex(x, d = 1) {\n const x_offset = x + getAffineMatrix().x - left_x;\n return Math.round(x_offset / resolution / d);\n }\n\n /**\n * Checks if a column and row index are within the flow field bounds.\n * @param {number} col - The column index.\n * @param {number} row - The row index.\n * @returns {boolean} - True if the indices are within bounds, false otherwise.\n */\n static isIn(col, row) {\n return col >= 0 && row >= 0 && col < num_columns && row < num_rows;\n }\n}\n\n// =============================================================================\n// Section: VectorField\n// =============================================================================\n\n/**\n * Represents the state of the vector field.\n * @property {boolean} isActive - Indicates if the vector field is active.\n * @property {string|null} current - The name of the currently active vector field.\n */\nState.field = {\n isActive: false,\n current: null,\n wiggle: 1,\n};\n\n// Internal variables for field configuration\nlet list = new Map();\nlet resolution, left_x, top_y, num_columns, num_rows;\nconst FIELD_ANGLE_MODES = new Set([\"degrees\", \"radians\"]);\n\n/**\n * Initializes the field grid and sets up the vector field's structure based on the renderer's dimensions.\n */\nfunction createField() {\n resolution = Cwidth * 0.01; // Determine the resolution of the field grid\n left_x = -0.5 * Cwidth; // Left boundary of the field\n top_y = -0.5 * Cheight; // Top boundary of the field\n num_columns = Math.round((2 * Cwidth) / resolution); // Number of columns in the grid\n num_rows = Math.round((2 * Cheight) / resolution); // Number of columns in the grid\n addStandard(); // Add default vector field\n}\n\n/**\n * Retrieves the field values for the current vector field.\n * @returns {Float32Array[]} The current vector field grid.\n */\nfunction flow_field() {\n return list.get(State.field.current).field;\n}\n\nfunction normalizeFieldAngleMode(options = {}) {\n const config =\n typeof options === \"string\" ? { angleMode: options } : options || {};\n const angleMode = config.angleMode ?? \"degrees\";\n\n if (!FIELD_ANGLE_MODES.has(angleMode)) {\n throw new Error(\n `Invalid field angle mode \"${angleMode}\". Use \"degrees\" or \"radians\".`,\n );\n }\n\n return angleMode;\n}\n\nfunction normalizeFieldAngles(field, angleMode) {\n if (angleMode !== \"radians\") return field;\n\n for (let c = 0; c < field.length; c++) {\n for (let r = 0; r < field[c].length; r++) {\n field[c][r] = toDegreesSigned(field[c][r], true);\n }\n }\n\n return field;\n}\n\nfunction generateField(entry, t) {\n return normalizeFieldAngles(entry.gen(t, genField()), entry.angleMode);\n}\n\n/**\n * Regenerates the current vector field using its associated generator function.\n * @param {number} [t=0] - An optional time parameter that can affect field generation.\n */\nexport function refreshField(t = 0) {\n if (!State.field.isActive || !State.field.current) {\n throw new Error(\n \"No field is currently active. Call brush.field('name') to activate one before refreshing.\",\n );\n }\n const currentField = list.get(State.field.current);\n currentField.field = generateField(currentField, t);\n}\n\n/**\n * Generates an empty field array.\n * Reuses existing arrays to reduce memory allocation overhead.\n * @returns {Float32Array[]} Empty vector field grid.\n */\nfunction genField() {\n return new Array(num_columns)\n .fill(null)\n .map(() => new Float32Array(num_rows));\n}\n\n/**\n * Activates a specific vector field by name, ensuring it's ready for use.\n * @param {string} a - The name of the vector field to activate.\n */\nexport function field(a) {\n if (!State.field.wiggle) {\n State.field.wiggle = 1;\n } // Set default wiggle value\n isFieldReady();\n if (!list.has(a)) {\n throw new Error(\n `Field \"${a}\" does not exist. Available fields: ${Array.from(list.keys()).join(\", \")}.`,\n );\n }\n State.field.isActive = true;\n State.field.current = a;\n const entry = list.get(a);\n if (!entry.field) entry.field = generateField(entry, 0);\n}\n\n/**\n * Deactivates the current vector field.\n */\nexport function noField() {\n isFieldReady();\n State.field.isActive = false;\n}\n\n/**\n * Adds a new vector field to the field list with a unique name and a generator function.\n * @param {string} name - The unique name for the new vector field.\n * @param {Function} funct - The function that generates the field values.\n * @param {object} [options] - Optional field configuration.\n * @param {\"degrees\"|\"radians\"} [options.angleMode=\"degrees\"] - How the generator's output angles should be interpreted.\n */\nexport function addField(name, funct, options = {}) {\n list.set(name, {\n gen: funct,\n field: null,\n angleMode: normalizeFieldAngleMode(options),\n });\n}\n\n/**\n * Retrieves a list of all available vector field names.\n * @returns {string[]} An array of all the field names.\n */\nexport function listFields() {\n isFieldReady();\n return Array.from(list.keys());\n}\n\nexport function wiggle(a = 1) {\n field(\"hand\");\n State.field.wiggle = a;\n}\n\n/**\n * Fills every cell of a field grid using a callback (c, r) => angle.\n */\nfunction fillField(field, fn) {\n for (let c = 0; c < num_columns; c++)\n for (let r = 0; r < num_rows; r++) field[c][r] = fn(c, r);\n return field;\n}\n\n/**\n * Adds standard predefined vector fields to the list with unique behaviors.\n */\nfunction addStandard() {\n // Organic noise — basis for brush.wiggle()\n addField(\"hand\", (t, field) => {\n const bs = rr2(0.2, 0.8),\n ba = randInt2(5, 10);\n return fillField(field, (c, r) => {\n const angle = 0.5 * ba * sin(bs * r * c + randInt2(15, 25));\n return 0.2 * angle * cos(t) + noise2(c, r) * ba * 0.7;\n });\n });\n // Smooth large-scale noise curves\n addField(\"curved\", (t, field) => {\n let ar = randInt2(-10, 10);\n if (randInt2(0, 100) % 2 == 0) ar *= -1;\n return fillField(\n field,\n (c, r) =>\n 3 * map(noise2(c * 0.02 + t * 0.03, r * 0.02 + t * 0.03), 0, 1, -ar, ar),\n );\n });\n // Sharp alternating angles per cell — herringbone / wicker look\n addField(\"zigzag\", (t, field) => {\n let ar = randInt2(-30, -15) + Math.abs(44 * sin(t));\n if (randInt2(0, 100) % 2 == 0) ar *= -1;\n let dif = ar,\n angle = 0;\n for (let c = 0; c < num_columns; c++) {\n for (let r = 0; r < num_rows; r++) {\n field[c][r] = angle;\n angle += dif;\n dif *= -1;\n }\n angle += dif;\n dif *= -1;\n }\n return field;\n });\n // Sinusoidal wave bands\n addField(\"waves\", (t, field) => {\n const sr = randInt2(10, 15) + 5 * sin(t),\n cr = randInt2(3, 6) + 3 * cos(t),\n ba = randInt2(20, 35);\n return fillField(\n field,\n (c, r) => sin(sr * c) * ba * cos(r * cr) + randInt2(-3, 3),\n );\n });\n // Dense oscillation from row×col product\n addField(\"seabed\", (t, field) => {\n const bs = rr2(0.4, 0.8),\n ba = randInt2(18, 26);\n return fillField(\n field,\n (c, r) => 1.1 * ba * sin(bs * r * c + randInt2(15, 20)) * cos(t),\n );\n });\n // Radial vortex — angles spiral around the field centre\n addField(\"spiral\", (_t, field) => {\n const n = randInt2(5, 10);\n const dir = randInt2(0, 2) * 2 - 1;\n const offset = randInt2(65, 80); // <90 = inward spiral\n const attractors = Array.from({ length: n }, () => ({\n x: rr2(0.1, 0.9) * num_columns,\n y: rr2(0.1, 0.9) * num_rows,\n }));\n return fillField(field, (c, r) => {\n let wx = 0,\n wy = 0;\n for (const att of attractors) {\n const dx = c - att.x,\n dy = r - att.y;\n const w = 1 / (dx * dx + dy * dy + 1);\n const a = Math.atan2(dy, dx) * (180 / Math.PI);\n const angle = (dir * (a + offset) * Math.PI) / 180;\n wx += w * Math.cos(angle);\n wy += w * Math.sin(angle);\n }\n return Math.atan2(wy, wx) * (180 / Math.PI);\n });\n });\n // Column-banded stripes — parallel rake marks\n addField(\"columns\", (_t, field) => {\n const freq = randInt2(3, 8),\n amp = randInt2(25, 45);\n return fillField(field, (c, _r) => sin(c * freq) * amp);\n });\n}\n","import { State } from \"./color.js\";\nimport { intersectLines } from \"./utils.js\";\n\n// =============================================================================\n// Section: Polygon Class\n// =============================================================================\n\n/**\n * Represents a polygon with a set of vertices and provides methods for\n * intersection, drawing, filling, and hatching.\n */\nexport class Polygon {\n /**\n * Constructs the Polygon object from an array of points.\n * @param {Array} pointsArray - An array of points, where each point is an array of two numbers [x, y].\n * @param {boolean} [useRawVertices=false] - If true, uses the raw array as vertices.\n */\n constructor(pointsArray, useRawVertices = false) {\n this.a = pointsArray;\n this.vertices = useRawVertices\n ? pointsArray\n : pointsArray.map(([x, y]) => ({ x, y }));\n this.sides = this.vertices.map((v, i, arr) => [\n v,\n arr[(i + 1) % arr.length],\n ]);\n this._intersectionCache = {}; // Cache for intersection results\n }\n\n /**\n * Intersects a given line with the polygon, returning all intersection points.\n * @param {Object} line - The line to intersect with the polygon, having two properties 'point1' and 'point2'.\n * @returns {Array} An array of intersection points (each with 'x' and 'y' properties) or an empty array if no intersections.\n */\n intersect(line) {\n // Check if the result has been cached\n const cacheKey = `${line.point1.x},${line.point1.y}-${line.point2.x},${line.point2.y}`;\n if (this._intersectionCache[cacheKey]) {\n return this._intersectionCache[cacheKey];\n }\n const points = [];\n for (const [start, end] of this.sides) {\n const intersection = intersectLines(line.point1, line.point2, start, end);\n if (intersection) points.push(intersection);\n }\n this._intersectionCache[cacheKey] = points; // Cache the result\n return points;\n }\n\n /**\n * Displays the polygon with optional stroke, hatch, and fill effects.\n */\n show() {\n if (State.wash) this.wash();\n if (State.fill) this.fill();\n if (State.mass) this.mass();\n if (State.hatch) this.hatch();\n if (State.stroke) this.draw();\n }\n}","import { Cwidth, Cheight } from \"./target.js\";\nimport { State } from \"./color.js\";\nimport { toDegrees, map, rr2 } from \"./utils.js\";\nimport { Position, isFieldReady } from \"./flowfield.js\";\nimport { Polygon } from \"./polygon.js\";\n\n// =============================================================================\n// Section: Plot Class\n// =============================================================================\n\n/**\n * The Plot class represents a collection of segments that define shapes or paths.\n * It supports operations like adding segments, calculating angles and pressures,\n * and generating polygons based on the plot's structure.\n */\nexport class Plot {\n /**\n * Creates a new Plot.\n * @param {string} _type - The type of plot, \"curve\" or \"segments\".\n */\n constructor(_type) {\n this.segments = [];\n this.angles = [];\n this.pres = [];\n this.type = _type;\n this.dir = 0;\n this.calcIndex(0);\n this.pol = false;\n }\n\n /**\n * Adds a segment to the plot with specified angle, length, and pressure.\n * @param {number} _a - The angle of the segment.\n * @param {number} _length - The length of the segment.\n * @param {number} _pres - The pressure of the segment.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n addSegment(_a = 0, _length = 0, _pres = 1, _degrees = false) {\n if (this.angles.length > 0) this.angles.pop(); // Remove the last angle\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a); // Normalize angle\n this.angles.push(_a, _a); // Push angle twice for continuity\n this.pres.push(_pres);\n this.segments.push(_length);\n this.length = this.segments.reduce((sum, len) => sum + len, 0); // Update total length\n }\n\n /**\n * Finalizes the plot by setting the last angle and pressure.\n * @param {number} _a - The final angle.\n * @param {number} _pres - The final pressure.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n endPlot(_a = 0, _pres = 1, _degrees = false) {\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a);\n this.angles[this.angles.length - 1] = _a; // Update the last angle\n this.pres.push(_pres);\n }\n\n /**\n * Rotates the entire plot by a given angle.\n * @param {number} _a - The angle to rotate the plot.\n */\n rotate(_a) {\n this.dir = toDegrees(_a);\n }\n\n /**\n * Calculates the pressure at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated pressure.\n */\n pressure(_d) {\n // If the distance exceeds the plot length, return the last pressure\n if (_d > this.length) return this.pres[this.pres.length - 1];\n // Otherwise, calculate the pressure using the curving function\n return this.curving(this.pres, _d);\n }\n\n /**\n * Calculates the angle at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The calculated angle.\n */\n angle(_d) {\n // If the distance exceeds the plot length, return the last angle\n if (_d > this.length) return this.angles[this.angles.length - 1];\n // Calculate the index for the given distance\n this.calcIndex(_d);\n // Return the angle, adjusted for the plot type and direction\n return this.type === \"curve\"\n ? this.curving(this.angles, _d) + this.dir\n : this.angles[this.index] + this.dir;\n }\n\n /**\n * Interpolates values between segments for smooth transitions.\n * @param {Array<number>} array - The array to interpolate within.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated value.\n */\n curving(array, _d) {\n let map0 = array[this.index];\n let map1 = array[this.index + 1] ?? map0;\n if (Math.abs(map1 - map0) > 180) {\n if (map1 > map0) map1 = -(360 - map1);\n else map0 = -(360 - map0);\n }\n return map(_d - this.suma, 0, this.segments[this.index], map0, map1, true);\n }\n\n /**\n * Calculates the current index of the plot based on the distance.\n * @param {number} _d - The distance along the plot.\n */\n calcIndex(_d) {\n this.index = -1;\n this.suma = 0;\n let d = 0;\n while (d <= _d) {\n this.suma = d;\n d += this.segments[this.index + 1];\n this.index++;\n }\n return this.index;\n }\n\n /**\n * Generates a polygon based on the plot.\n * @param {number} _x - The x-coordinate for the starting point.\n * @param {number} _y - The y-coordinate for the starting point.\n * @param {number} _scale - The scale factor for the polygon.\n * @param {number} _side - The side factor for the polygon.\n * @returns {Polygon} - The generated polygon.\n */\n genPol(_x, _y, _scale = 1, _side) {\n isFieldReady(); // Ensure that the drawing environment is prepared\n const step = _side < 0 ? 4 : 1;\n const vertices = [];\n const numSteps = Math.round(this.length / step);\n const pos = new Position(_x + Cwidth / 2, _y + Cheight / 2);\n let pside = 0;\n let prevIdx = 0;\n\n for (let i = 0; i < numSteps; i++) {\n pos.plotTo(this, step, step);\n const idx = this.calcIndex(pos.plotted);\n pside += step;\n let maxSize = _side <= 0 ? 8 : Math.max(this.segments[idx] * _side * rr2(0.7, 1.3), 20);\n if ((pside >= maxSize || idx >= prevIdx) && pos.x) {\n vertices.push([pos.x - Cwidth / 2, pos.y - Cheight / 2]);\n pside = 0;\n if (idx >= prevIdx) prevIdx++;\n }\n }\n return new Polygon(vertices);\n }\n\n /**\n * Displays the plot with optional stroke, hatch, and fill effects.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\n show(x, y, scale = 1) {\n if (State.wash) this.wash(x, y, scale);\n if (State.fill) this.fill(x, y, scale);\n if (State.mass) this.mass(x, y, scale);\n if (State.hatch) this.hatch(x, y, scale);\n if (State.stroke) this.draw(x, y, scale);\n }\n}\n","import {\n rr2,\n randInt2,\n sin,\n cos,\n toDegreesSigned,\n constrain,\n dist,\n calcAngle,\n intersectLines,\n} from \"./utils.js\";\nimport { Polygon } from \"./polygon.js\";\nimport { Plot } from \"./plot.js\";\n\n// =============================================================================\n// Section: Primitives and Geommetry\n// =============================================================================\n\n/**\n * Creates a Polygon from an array of points and calls its show() method.\n * Polygons ignore fields and won't be good for fills and masses\n * @param {Array<Array<number>>} pointsArray - Array of points [x, y, pressure]\n */\nexport function polygon(pointsArray) {\n // Create a new Polygon instance\n const polygon = new Polygon(pointsArray);\n polygon.show();\n}\n\n/**\n * Draws a rectangle on the canvas using path functions.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} w - Width.\n * @param {number} h - Height.\n * @param {boolean} [mode=\"corner\"] - \"corner\" (default) or \"center\".\n */\nexport function rect(x, y, w, h, mode = \"corner\") {\n if (mode === \"center\") {\n x -= w / 2;\n y -= h / 2;\n }\n beginShape(0);\n vertex(x, y);\n vertex(x + w, y);\n vertex(x + w, y + h);\n vertex(x, y + h);\n endShape(true);\n}\n\n/**\n * Draws a circle on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Circle radius.\n * @param {boolean} [r=false] - Randomizes segment lengths if true.\n */\nexport function circle(x, y, radius, r = false) {\n const p = new Plot(\"curve\");\n const arcLength = Math.PI * radius;\n const angleOffset = rr2(0, 360);\n const randomFactor = r ? () => 1 + r * 0.2 * rr2() : () => 1;\n\n // Divide circle into 4 segments\n for (let i = 0; i < 4; i++) {\n const angle = -90 * i + angleOffset;\n p.addSegment(\n angle * randomFactor(),\n (arcLength / 2) * randomFactor(),\n 1,\n true,\n );\n }\n\n // Optionally add a random final angle for the last segment\n if (r) {\n const randomAngle = r * randInt2(-5, 5);\n p.addSegment(\n angleOffset,\n Math.abs(randomAngle) * (Math.PI / 180) * radius,\n 1,\n true,\n );\n p.endPlot(randomAngle + angleOffset, 1, true);\n } else {\n p.endPlot(angleOffset, 1, true);\n }\n\n // Draw the circle\n const offsetX = x - radius * sin(angleOffset);\n const offsetY = y - radius * cos(-angleOffset);\n p.show(offsetX, offsetY, 1);\n}\n\n/**\n * Draws an arc on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Radius.\n * @param {number} start - Start angle in the current runtime angle units.\n * @param {number} end - End angle in the current runtime angle units.\n */\nexport function arc(x, y, radius, start, end) {\n const startDeg = toDegreesSigned(start);\n const endDeg = toDegreesSigned(end);\n const sweepDeg = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweepDeg === 0) return;\n\n const p = new Plot(\"curve\");\n const segmentCount = Math.max(1, Math.ceil(sweepDeg / 90));\n const segmentSweep = sweepDeg / segmentCount;\n const arcLength = (Math.PI * radius * segmentSweep) / 180;\n\n for (let i = 0; i < segmentCount; i++) {\n p.addSegment(startDeg + i * segmentSweep + 90, arcLength, 1, true);\n }\n p.endPlot(startDeg + sweepDeg + 90, 1, true);\n\n const startX = x + radius * cos(startDeg);\n const startY = y - radius * sin(startDeg);\n p.draw(startX, startY, 1);\n}\n\n// Variables for managing paths and strokes\nlet _current;\nlet _curvature;\n\nclass SubPath {\n constructor() {\n this.isClosed = false;\n this.curvature = _curvature;\n this.vert = [];\n }\n /**\n * Adds a vertex to this subpath.\n * @param {number} x\n * @param {number} y\n * @param {number} pressure\n */\n vertex(x, y, pressure) {\n this.vert.push([x, y, pressure]);\n }\n /**\n * Renders the subpath by creating a spline from its vertices.\n */\n show() {\n let plot = _createSpline(this.vert, this.curvature, this.isClosed);\n plot.show();\n }\n}\n\n/**\n * Begins a new path with a specified curvature.\n * @param {number} [curvature=0] - Curvature from 0 to 1.\n */\nexport function beginShape(curvature = 0) {\n _curvature = constrain(curvature, 0, 1);\n _current = new SubPath();\n}\n\n/**\n * Adds a line segment from the current point to the given coordinates.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} [pressure=1] - Pressure value.\n */\nexport function vertex(x, y, pressure = 1) {\n if (!_current) {\n throw new Error(\n \"vertex() called outside of beginShape()/endShape(). Call beginShape() first.\",\n );\n }\n _current.vertex(x, y, pressure);\n}\n\n/**\n * Ends the current path and renders all subpaths.\n */\nexport function endShape(close = false) {\n if (!_current) {\n throw new Error(\n \"endShape() called without beginShape(). Call beginShape() first.\",\n );\n }\n if (_current.vert.length < 2) {\n throw new Error(\n \"endShape() requires at least 2 vertices. Add more with vertex().\",\n );\n }\n if (close) {\n _current.vertex(..._current.vert[0]);\n _current.isClosed = true;\n }\n _current.show();\n _current = false;\n}\n\nlet _strokeArray, _strokeOrigin;\n\n/**\n * Begins a new stroke with a given type and starting position.\n * @param {string} type - Stroke type.\n * @param {number} x - Starting x.\n * @param {number} y - Starting y.\n */\nexport function beginStroke(type, x, y) {\n if (type !== \"curve\" && type !== \"segments\") {\n throw new Error(\n `beginStroke() type must be \"curve\" or \"segments\", got \"${type}\".`,\n );\n }\n _strokeOrigin = [x, y];\n _strokeArray = new Plot(type);\n}\n\n/**\n * Adds a segment to the stroke.\n * @param {number} angle - Segment angle.\n * @param {number} length - Segment length.\n * @param {number} pressure - Segment pressure.\n */\nexport function move(angle, length, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"move() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.addSegment(angle, length, pressure);\n}\n\n/**\n * Completes and renders the stroke.\n * @param {number} angle - End angle.\n * @param {number} pressure - End pressure.\n */\nexport function endStroke(angle, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"endStroke() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.endPlot(angle, pressure);\n _strokeArray.draw(_strokeOrigin[0], _strokeOrigin[1], 1);\n _strokeArray = false;\n}\n\n/**\n * Creates and draws a spline curve from an array of points.\n * @param {Array<Array<number>>} array_points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature from 0 to 1.\n */\nexport function spline(_array_points, _curvature = 0.5) {\n if (!_array_points || _array_points.length < 2) {\n throw new Error(\n \"spline() requires at least 2 points. Each point should be [x, y, pressure].\",\n );\n }\n let p = _createSpline(_array_points, _curvature);\n p.draw();\n}\n\n/**\n * Creates a new Plot object representing a spline curve.\n *\n * For curved segments (curvature > 0) with at least 3 points available,\n * the function either treats segments as straight (if their angles match)\n * or calculates control points to compute a circular arc.\n *\n * If no curvature is specified, a simple straight segment is used.\n *\n * @param {Array<Array<number>>} points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature value between 0 and 1.\n * @param {boolean} [close=false] - Whether to close the spline.\n * @returns {Plot} - The generated Plot object.\n */\nfunction _createSpline(points, curvature = 0.5, close = false) {\n const plotType = curvature === 0 ? \"segments\" : \"curve\";\n const p = new Plot(plotType);\n const PI2 = Math.PI * 2;\n\n // If closing the spline, add the second point to the end\n if (close && curvature !== 0) {\n points.push(points[1]);\n }\n\n if (points && points.length > 0) {\n let done = 0; // Tracks excess length from previous segment\n let pep, tep, pep2; // Variables used for initial calibration\n\n for (let i = 0; i < points.length - 1; i++) {\n // For curved segments (if curvature > 0 and there is at least 3 points ahead)\n if (curvature > 0 && i < points.length - 2) {\n const p1 = points[i];\n const p2 = points[i + 1];\n const p3 = points[i + 2];\n\n const d1 = dist(p1[0], p1[1], p2[0], p2[1]);\n const d2 = dist(p2[0], p2[1], p3[0], p3[1]);\n const a1 = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n const a2 = calcAngle(p2[0], p2[1], p3[0], p3[1]);\n\n // Compute the adjustment length based on curvature\n const curvAdjust = curvature * Math.min(d1, d2, 0.5 * Math.min(d1, d2));\n const dmax = Math.max(d1, d2);\n const s1 = d1 - curvAdjust;\n const s2 = d2 - curvAdjust;\n\n if (Math.floor(a1) === Math.floor(a2)) {\n // If angles are nearly the same, treat as a straight segment\n const temp = close ? (i === 0 ? 0 : d1 - done) : d1 - done;\n const temp2 = close ? (i === 0 ? 0 : d2 - pep2) : d2;\n\n p.addSegment(a1, temp, p1[2], true);\n if (i === points.length - 3) {\n p.addSegment(a2, temp2, p2[2], true);\n }\n\n done = 0;\n if (i === 0) {\n pep = d1;\n pep2 = curvAdjust;\n tep = points[1];\n done = 0;\n }\n } else {\n // For a curved segment, compute control points and arc segment details\n const point1 = {\n x: p2[0] - curvAdjust * cos(-a1),\n y: p2[1] - curvAdjust * sin(-a1),\n };\n const point2 = {\n x: point1.x + dmax * cos(-a1 + 90),\n y: point1.y + dmax * sin(-a1 + 90),\n };\n const point3 = {\n x: p2[0] + curvAdjust * cos(-a2),\n y: p2[1] + curvAdjust * sin(-a2),\n };\n const point4 = {\n x: point3.x + dmax * cos(-a2 + 90),\n y: point3.y + dmax * sin(-a2 + 90),\n };\n\n const intPt = intersectLines(point1, point2, point3, point4, true);\n const radius = dist(point1.x, point1.y, intPt.x, intPt.y);\n const halfDist = dist(point1.x, point1.y, point3.x, point3.y) / 2;\n const arcAngle = 2 * Math.asin(halfDist / radius) * (180 / Math.PI);\n const arcLength = (PI2 * radius * arcAngle) / 360;\n\n const temp = close ? (i === 0 ? 0 : s1 - done) : s1 - done;\n const temp2 =\n i === points.length - 3 ? (close ? pep - curvAdjust : s2) : 0;\n\n p.addSegment(a1, temp, p1[2], true);\n p.addSegment(a1, isNaN(arcLength) ? 0 : arcLength, p1[2], true);\n p.addSegment(a2, temp2, p2[2], true);\n\n done = curvAdjust;\n if (i === 0) {\n pep = s1;\n pep2 = curvAdjust;\n tep = [point1.x, point1.y];\n }\n }\n\n if (i === points.length - 3) {\n p.endPlot(a2, p2[2], true);\n }\n } else if (curvature === 0) {\n // If no curvature, add a simple straight segment\n const p1 = points[i];\n const p2 = points[i + 1];\n const d = dist(p1[0], p1[1], p2[0], p2[1]);\n const a = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n\n p.addSegment(a, d, p2[2], true);\n if (i === points.length - 2) {\n p.endPlot(a, 1, true);\n }\n }\n }\n\n p.origin = close && curvature !== 0 ? tep : points[0];\n }\n\n return p;\n}\n","// =============================================================================\n// Stroke Runtime Hooks\n// =============================================================================\n\nlet strokeRuntime = {\n createTipSurface: () => {\n throw new Error(\"No stroke runtime adapter registered.\");\n },\n loadImageTip: () => {\n throw new Error(\"No stroke runtime adapter registered.\");\n },\n};\n\n/**\n * Registers or updates host stroke hooks used by brush-tip loading code.\n *\n * @param {object} hooks\n */\nexport function setStrokeRuntime(hooks) {\n strokeRuntime = { ...strokeRuntime, ...hooks };\n}\n\nexport const createTipSurface = (width, height) =>\n strokeRuntime.createTipSurface(width, height);\nexport const loadImageTip = (src, imageToWhite) =>\n strokeRuntime.loadImageTip(src, imageToWhite);\n","import * as Color from \"../core/color.js\";\nimport { createFramebuffer } from \"../core/compositor_runtime.js\";\n\nlet isStrokeCompositeRegistered = false;\nconst DIRTY_BRUSH_PADDING = 2;\n\n// =============================================================================\n// Section: Helpers\n// =============================================================================\n/**\n * Returns whether the current stroke mask framebuffer must be recreated.\n * This happens when the renderer has no mask yet, or when the canvas size or\n * pixel density changed since the last allocation.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {boolean} True when the stroke mask must be rebuilt.\n */\nfunction needsStrokeMask(Renderer, Cwidth, Cheight, Density) {\n return (\n !Renderer.glMask ||\n Renderer.glMask.width !== Cwidth ||\n Renderer.glMask.height !== Cheight ||\n (typeof Renderer.glMask.pixelDensity === \"function\" &&\n Renderer.glMask.pixelDensity() !== Density)\n );\n}\n\n// =============================================================================\n// Section: Resource Management\n// =============================================================================\n/**\n * Ensures the stroke compositor owns a framebuffer-backed mask with the current\n * canvas dimensions. Stroke stamps are rendered into this mask in WebGL before\n * being blended into the main target.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {object} The framebuffer used as stroke mask.\n */\nexport function ensureStrokeCompositeResources(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n) {\n if (needsStrokeMask(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.glMask?.remove) Renderer.glMask.remove();\n Renderer.glMask = createFramebuffer(Renderer, {\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n }\n\n Renderer.glMask.dirtyRect ??= null;\n Renderer.glMask.isDrawn ??= false;\n return Renderer.glMask;\n}\n\n// =============================================================================\n// Section: Mask Lifecycle\n// =============================================================================\n/**\n * Clears the current stroke mask and resets its bookkeeping flags.\n *\n * @param {object|null} target - Stroke mask framebuffer.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n */\nexport function clearStrokeMask(target, clearTarget) {\n if (!target) return;\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\n}\n\n// =============================================================================\n// Section: Composite Bounds\n// =============================================================================\n/**\n * Returns the rect that should be composited from the stroke mask into the\n * main canvas. Stroke bounds are normally tight dirty rects, but when drawing\n * into an active framebuffer we keep the result conservative and composite the\n * full target.\n *\n * @param {object|null} target - Stroke mask framebuffer.\n * @param {Function} getActiveFramebuffer - Returns the currently bound framebuffer.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} expandDirtyRect - Expands a rect by a constant padding.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @param {number} padding - Extra brush padding in pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\nexport function getStrokeCompositeRect(\n target,\n getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n if (getActiveFramebuffer()) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(target.dirtyRect, DIRTY_BRUSH_PADDING),\n );\n}\n\n/**\n * Returns the resource that should be bound to the blend shader's `u_mask`\n * uniform for stroke compositing.\n *\n * @param {object} _Renderer - Active host renderer.\n * @param {object} mask - Stroke mask framebuffer.\n * @returns {object} Stroke mask framebuffer.\n */\nexport function getStrokeShaderMask(_Renderer, mask) {\n return mask;\n}\n\n// =============================================================================\n// Section: Registration\n// =============================================================================\n/**\n * Registers the stroke compositor with the shared color/composite core.\n * Safe to call multiple times.\n */\nexport function initStrokeComposite() {\n if (isStrokeCompositeRegistered) return;\n Color.registerStrokeComposite?.({\n ensureResources: ensureStrokeCompositeResources,\n clearMask: clearStrokeMask,\n getCompositeRect: getStrokeCompositeRect,\n getShaderMask: getStrokeShaderMask,\n });\n isStrokeCompositeRegistered = true;\n}\n","/**\n * Compiles a shader program from the given vertex and fragment sources.\n * @param {WebGL2RenderingContext} gl - The WebGL2 context.\n * @param {string} vert - Vertex shader source.\n * @param {string} frag - Fragment shader source.\n * @returns {WebGLProgram} The compiled and linked program.\n */\nexport const createProgram = (gl, vert, frag) => {\n const p = gl.createProgram();\n for (let [t, src] of [\n [gl.VERTEX_SHADER, vert],\n [gl.FRAGMENT_SHADER, frag],\n ]) {\n const s = gl.createShader(t);\n gl.shaderSource(s, src);\n gl.compileShader(s);\n gl.attachShader(p, s);\n }\n gl.linkProgram(p);\n return p;\n};\n","// =============================================================================\n// Renderer Runtime Hooks\n// =============================================================================\n\n/**\n * Direct-render hooks used by modules that issue raw WebGL commands.\n *\n * These hooks are intentionally narrow:\n * - begin drawing into an offscreen GL mask target\n * - restore the previous draw target afterward\n * - reset any host-side shader/program bookkeeping after direct GL usage\n */\n\nlet rendererRuntime = {\n beginDirectMaskDraw: () => {\n throw new Error(\"No renderer runtime adapter registered.\");\n },\n endDirectMaskDraw: () => {\n throw new Error(\"No renderer runtime adapter registered.\");\n },\n resetDirectShaderTracking: () => {},\n};\n\n/**\n * Registers or updates host renderer hooks used by direct WebGL drawing paths.\n *\n * @param {object} hooks\n */\nexport function setRendererRuntime(hooks) {\n rendererRuntime = { ...rendererRuntime, ...hooks };\n}\n\nexport const beginDirectMaskDraw = (renderer, gl, target) =>\n rendererRuntime.beginDirectMaskDraw(renderer, gl, target);\nexport const endDirectMaskDraw = (renderer, gl, state) =>\n rendererRuntime.endDirectMaskDraw(renderer, gl, state);\nexport const resetDirectShaderTracking = (renderer, gl) =>\n rendererRuntime.resetDirectShaderTracking(renderer, gl);\n","// =============================================================================\n// Module: GL Draw\n// =============================================================================\n/**\n * The GL Draw module batches brush primitives for WebGL2 rendering. It initializes\n * the shader programs and buffers used by circle-based brushes and image-tip brushes,\n * then flushes those queues into the shared framebuffer-backed brush mask.\n */\n\nimport { Cwidth, Cheight, Density, Renderer } from \"../core/target.js\";\nimport {\n Mix,\n isMixReady,\n State,\n} from \"../core/color.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport {\n beginDirectMaskDraw,\n endDirectMaskDraw,\n resetDirectShaderTracking,\n} from \"../core/renderer_runtime.js\";\nimport { getAffineMatrix } from \"../core/runtime.js\";\nimport vertSrc from \"./shader.vert\";\nimport fragSrc from \"./shader.frag\";\nimport imgVertSrc from \"./image.vert\";\nimport imgFragSrc from \"./image.frag\";\n\n// =============================================================================\n// Section: Initialization and Setup\n// =============================================================================\n\n// Module state\nlet isLoaded = false,\n gl,\n framebufferProjMatrix,\n vao,\n buf,\n program;\nlet loadedWidth = 0,\n loadedHeight = 0;\nlet brushMaskTarget = null;\nconst Attr = {},\n Frag = {};\n\n// Cached matrix values — snapshotted once per stroke in snapshotMatrix()\nlet _ma = 1,\n _mb = 0,\n _mc = 0,\n _md = 1,\n _mx = 0,\n _my = 0,\n _halfW = 0,\n _halfH = 0,\n _scale = 1,\n _density = 1;\n\n/**\n * Snapshots the current runtime affine transform. Call once at the start of each stroke.\n */\nexport function snapshotMatrix() {\n const m = getAffineMatrix();\n _ma = m.a;\n _mb = m.b;\n _mc = m.c;\n _md = m.d;\n _mx = m.x;\n _my = m.y;\n _halfW = Cwidth / 2;\n _halfH = Cheight / 2;\n _scale = Math.sqrt(_ma * _ma + _mb * _mb);\n _density = Density;\n}\n\n// Pre-allocated flat buffer for circle data (x, y, radius, alpha per circle)\nconst INITIAL_CAPACITY = 2048;\nlet circleData = new Float32Array(INITIAL_CAPACITY * 4);\nlet circleCount = 0;\nlet bufferCapacity = INITIAL_CAPACITY;\nlet gpuBufferSize = INITIAL_CAPACITY * 4 * 4; // bytes allocated on GPU\nlet circleDirtyRect = null;\n\n// ---------------------------------------------------------------------------\n// Image instancing state\n// ---------------------------------------------------------------------------\nlet imgProgram = null;\nlet imgVao = null;\nlet imgCornerBuf = null;\nlet imgInstanceBuf = null;\nconst imgAttr = {};\nconst imgFrag = {};\nlet imgGpuSize = 0;\n\nconst IMG_FLOATS = 5; // screenX, screenY, halfSize, angle, alpha — per stamp\nconst IMG_INIT_CAP = 256;\nlet imgData = new Float32Array(IMG_INIT_CAP * IMG_FLOATS);\nlet imgCount = 0;\nlet imgCapacity = IMG_INIT_CAP;\nlet imgDirtyRect = null;\n\n// Texture cache: src string → WebGLTexture (cleared whenever the GL context changes)\nconst texCache = new Map();\n\n// Static unit-quad corners for gl.TRIANGLE_STRIP in quad-local space.\nconst QUAD_CORNERS = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]);\n\nfunction ensureBrushMaskTarget() {\n const rendererMask = Renderer?.glMask;\n if (!rendererMask) return null;\n brushMaskTarget = rendererMask;\n brushMaskTarget.dirtyRect ??= null;\n brushMaskTarget.isDrawn ??= false;\n Mix.glMask = brushMaskTarget;\n return brushMaskTarget;\n}\n\nfunction getProjectionMatrix() {\n return framebufferProjMatrix;\n}\n\nfunction beginMaskTarget() {\n return beginDirectMaskDraw(Renderer, gl, Mix.glMask);\n}\n\nfunction endMaskTarget(state) {\n endDirectMaskDraw(Renderer, gl, state);\n}\n\nfunction accumulateDirtyRect(currentRect, minX, minY, maxX, maxY) {\n if (!currentRect) return { minX, minY, maxX, maxY };\n if (minX < currentRect.minX) currentRect.minX = minX;\n if (minY < currentRect.minY) currentRect.minY = minY;\n if (maxX > currentRect.maxX) currentRect.maxX = maxX;\n if (maxY > currentRect.maxY) currentRect.maxY = maxY;\n return currentRect;\n}\n\n/**\n * Initializes WebGL objects if not done already.\n */\nexport function isReady() {\n isMixReady();\n ensureBrushMaskTarget();\n\n const nextGl = Renderer.drawingContext;\n const needsContextRefresh = !isLoaded || gl !== nextGl;\n const needsProjectionRefresh =\n needsContextRefresh || loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (needsProjectionRefresh) {\n framebufferProjMatrix = new Float32Array([\n 2 / Cwidth,\n 0,\n 0,\n 0,\n 0,\n 2 / Cheight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n -1,\n 0,\n 1,\n ]);\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n }\n\n if (!needsContextRefresh) return;\n\n gl = nextGl;\n\n // Create shader program and initialize\n program = createProgram(gl, vertSrc, fragSrc);\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n // Cache attribute and uniform locations\n [\"a_position\", \"a_radius\", \"a_alpha\"].forEach(\n (n) => (Attr[n] = gl.getAttribLocation(program, n)),\n );\n [\"u_matrix\", \"u_color\"].forEach(\n (n) => (Frag[n] = gl.getUniformLocation(program, n)),\n );\n\n // Create persistent VAO and VBO\n vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n\n buf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n gl.bufferData(gl.ARRAY_BUFFER, circleData.byteLength, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n\n // Set up vertex attributes (only needs to happen once with persistent VAO)\n const stride = 16; // 4 floats × 4 bytes\n gl.enableVertexAttribArray(Attr.a_position);\n gl.vertexAttribPointer(Attr.a_position, 2, gl.FLOAT, false, stride, 0);\n gl.enableVertexAttribArray(Attr.a_radius);\n gl.vertexAttribPointer(Attr.a_radius, 1, gl.FLOAT, false, stride, 8);\n gl.enableVertexAttribArray(Attr.a_alpha);\n gl.vertexAttribPointer(Attr.a_alpha, 1, gl.FLOAT, false, stride, 12);\n\n gl.bindVertexArray(null);\n\n // ------------------------------------------------------------------\n // Image-tip instancing program\n // ------------------------------------------------------------------\n texCache.clear();\n\n imgProgram = createProgram(gl, imgVertSrc, imgFragSrc);\n [\"a_corner\", \"a_pos\", \"a_size\", \"a_angle\", \"a_alpha\"].forEach(\n (n) => (imgAttr[n] = gl.getAttribLocation(imgProgram, n)),\n );\n [\"u_proj\", \"u_color\", \"u_tex\"].forEach(\n (n) => (imgFrag[n] = gl.getUniformLocation(imgProgram, n)),\n );\n\n imgVao = gl.createVertexArray();\n gl.bindVertexArray(imgVao);\n\n // Static corner VBO (per-vertex, no divisor)\n imgCornerBuf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, imgCornerBuf);\n gl.bufferData(gl.ARRAY_BUFFER, QUAD_CORNERS, gl.STATIC_DRAW);\n gl.enableVertexAttribArray(imgAttr.a_corner);\n gl.vertexAttribPointer(imgAttr.a_corner, 2, gl.FLOAT, false, 0, 0);\n\n // Instance data VBO (per-instance)\n imgInstanceBuf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, imgInstanceBuf);\n gl.bufferData(gl.ARRAY_BUFFER, imgData.byteLength, gl.DYNAMIC_DRAW);\n imgGpuSize = imgData.byteLength;\n\n const istride = IMG_FLOATS * 4; // 20 bytes\n gl.enableVertexAttribArray(imgAttr.a_pos);\n gl.vertexAttribPointer(imgAttr.a_pos, 2, gl.FLOAT, false, istride, 0);\n gl.vertexAttribDivisor(imgAttr.a_pos, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_size);\n gl.vertexAttribPointer(imgAttr.a_size, 1, gl.FLOAT, false, istride, 8);\n gl.vertexAttribDivisor(imgAttr.a_size, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_angle);\n gl.vertexAttribPointer(imgAttr.a_angle, 1, gl.FLOAT, false, istride, 12);\n gl.vertexAttribDivisor(imgAttr.a_angle, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_alpha);\n gl.vertexAttribPointer(imgAttr.a_alpha, 1, gl.FLOAT, false, istride, 16);\n gl.vertexAttribDivisor(imgAttr.a_alpha, 1);\n\n gl.bindVertexArray(null);\n\n isLoaded = true;\n}\n\n// =============================================================================\n// Section: Drawing Primitives\n// =============================================================================\n\n/**\n * Queue a circle to be drawn with the specified parameters.\n * Data is written directly into a flat Float32Array to avoid object allocation.\n * Applies the full 2D affine transform (rotation + scale + translation) from\n * the current runtime transform so that brush.rotate() and brush.scale() work correctly.\n */\nexport function circle(x, y, diameter, alpha) {\n // Grow buffer if needed\n if (circleCount >= bufferCapacity) {\n bufferCapacity *= 2;\n const newData = new Float32Array(bufferCapacity * 4);\n newData.set(circleData);\n circleData = newData;\n }\n\n // x/y arrive in \"position space\": user coords + (Cwidth/2, Cheight/2).\n // Subtract the offset to recover user coords, apply the full matrix, then re-add\n // the offset so the result is in screen pixel space [0..Cwidth, 0..Cheight].\n const px = x - _halfW;\n const py = y - _halfH;\n\n const offset = circleCount * 4;\n const screenX = _ma * px + _mc * py + _mx + _halfW;\n const screenY = _mb * px + _md * py + _my + _halfH;\n const radius = (_density * diameter * _scale) / 2;\n\n circleData[offset] = screenX;\n circleData[offset + 1] = screenY;\n // Scale the diameter by the matrix's scale factor (length of the transformed x-axis)\n circleData[offset + 2] = radius;\n circleData[offset + 3] = alpha / 255;\n\n const dScreenX = screenX * _density;\n const dScreenY = screenY * _density;\n circleDirtyRect = accumulateDirtyRect(\n circleDirtyRect,\n dScreenX - radius - 1,\n dScreenY - radius - 1,\n dScreenX + radius + 1,\n dScreenY + radius + 1,\n );\n\n circleCount++;\n}\n\n/**\n * Queue an image stamp to be drawn with instanced rendering.\n * Accepts the same coordinate conventions as circle(): x/y in position space\n * (user coords + Cwidth/2, Cheight/2), size in user-coord units, alpha in [0..255].\n * @param {number} x - X in position space.\n * @param {number} y - Y in position space.\n * @param {number} size - Full stamp diameter in user-coord units.\n * @param {number} angle - Rotation in radians.\n * @param {number} alpha - Opacity [0..255].\n * @param {number} [extraPadding=0] - Conservative extra padding in user units.\n */\nexport function stampImage(x, y, size, angle, alpha, extraPadding = 0) {\n if (imgCount >= imgCapacity) {\n imgCapacity *= 2;\n const next = new Float32Array(imgCapacity * IMG_FLOATS);\n next.set(imgData);\n imgData = next;\n }\n\n const px = x - _halfW;\n const py = y - _halfH;\n const screenX = _ma * px + _mc * py + _mx + _halfW;\n const screenY = _mb * px + _md * py + _my + _halfH;\n const halfSize = (_density * size * _scale) / 2;\n const extraRadius = _density * extraPadding * _scale;\n\n const base = imgCount * IMG_FLOATS;\n imgData[base] = screenX;\n imgData[base + 1] = screenY;\n imgData[base + 2] = halfSize;\n imgData[base + 3] = angle;\n imgData[base + 4] = alpha / 255;\n\n // Bounding box: rotated square worst-case = circle of radius halfSize * √2\n const dScreenX = screenX * _density;\n const dScreenY = screenY * _density;\n const boundsRadius = halfSize * 1.42 + extraRadius;\n imgDirtyRect = accumulateDirtyRect(\n imgDirtyRect,\n dScreenX - boundsRadius - 1,\n dScreenY - boundsRadius - 1,\n dScreenX + boundsRadius + 1,\n dScreenY + boundsRadius + 1,\n );\n\n imgCount++;\n}\n\n/**\n * Flush all queued image stamps in a single instanced draw call.\n * @param {object} p5img - The preprocessed brush-tip image/canvas (from T.tips).\n * @param {string} src - The image src string, used as the texture cache key.\n */\nexport function glDrawImages(p5img, src) {\n if (imgCount === 0) return;\n\n Mix.glMask.isDrawn = true;\n const targetState = beginMaskTarget();\n\n // Lazy-create the WebGL texture from the tip canvas on first use.\n let tex = texCache.get(src);\n if (!tex) {\n tex = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, p5img.canvas);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n texCache.set(src, tex);\n }\n\n gl.useProgram(imgProgram);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.uniform1i(imgFrag.u_tex, 0);\n\n const color = State.stroke.color._array;\n gl.uniform4f(imgFrag.u_color, ...color);\n gl.uniformMatrix4fv(imgFrag.u_proj, false, getProjectionMatrix());\n\n gl.bindVertexArray(imgVao);\n gl.bindBuffer(gl.ARRAY_BUFFER, imgInstanceBuf);\n\n const byteCount = imgCount * IMG_FLOATS * 4;\n const dataView = imgData.subarray(0, imgCount * IMG_FLOATS);\n if (byteCount > imgGpuSize) {\n gl.bufferData(gl.ARRAY_BUFFER, imgData, gl.DYNAMIC_DRAW);\n imgGpuSize = imgData.byteLength;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);\n }\n\n gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, imgCount);\n gl.flush();\n\n gl.bindVertexArray(null);\n gl.bindTexture(gl.TEXTURE_2D, null);\n endMaskTarget(targetState);\n\n if (imgDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, imgDirtyRect);\n imgDirtyRect = null;\n }\n\n imgCount = 0;\n\n // Let the host adapter know we changed the active program.\n resetDirectShaderTracking(Renderer, gl);\n}\n\n/**\n * Removes a cached GL texture by key, forcing re-upload on next draw.\n * Call this when a custom tip function changes after brush.add().\n */\nexport function invalidateTexEntry(key) {\n const tex = texCache.get(key);\n if (tex && gl) gl.deleteTexture(tex);\n texCache.delete(key);\n}\n\n/**\n * Draw all queued circles using WebGL\n */\nexport function glDraw() {\n if (circleCount === 0) return;\n\n Mix.glMask.isDrawn = true;\n const targetState = beginMaskTarget();\n\n const color = State.stroke.color._array;\n\n // Re-activate our shader in case host drawing switched programs.\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n gl.bindVertexArray(vao);\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n\n // Upload vertex data — reallocate GPU buffer only if needed\n const byteCount = circleCount * 16; // 4 floats × 4 bytes\n const dataView = circleData.subarray(0, circleCount * 4);\n if (byteCount > gpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, circleData, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);\n }\n\n // Set uniforms and draw\n gl.uniform4f(Frag.u_color, ...color);\n gl.uniformMatrix4fv(Frag.u_matrix, false, getProjectionMatrix());\n gl.drawArrays(gl.POINTS, 0, circleCount);\n gl.flush();\n\n gl.bindVertexArray(null);\n endMaskTarget(targetState);\n\n if (circleDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, circleDirtyRect);\n circleDirtyRect = null;\n }\n\n // Reset queue (no deallocation)\n circleCount = 0;\n\n // We called gl.useProgram() directly, bypassing host shader tracking.\n // Reset it so the host is forced to re-activate its own shader next time\n // it draws — otherwise it may skip gl.useProgram() and set uniforms on the\n // wrong active program, causing \"location is not from the associated program\".\n resetDirectShaderTracking(Renderer, gl);\n}\n","// =============================================================================\n// Module: Brush\n// =============================================================================\n/**\n * The Brush module provides a comprehensive set of functions and classes for\n * simulating various drawing tools ranging from pens, markers, pencils, to\n * custom image-based brushes. This module controls brush properties such as\n * weight, color, vibration, and spacing, and manages the drawing process through\n * stateful methods that enable features like pressure sensitivity, clipping, and\n * blending. By supporting multiple brush types and dynamic parameter adjustments,\n * the Brush module facilitates the creation of realistic and expressive stroke effects.\n */\n\n// Core imports\nimport { Cwidth, Cheight, Renderer, isCanvasReady } from \"../core/target.js\";\nimport {\n Mix,\n State,\n} from \"../core/color.js\";\nimport {\n rr,\n map,\n dist,\n randInt,\n calcAngle,\n toDegrees,\n gaussian,\n rArray,\n noise,\n _onSeed, \n cos,\n sin\n} from \"../core/utils.js\";\nimport { createColor } from \"../core/runtime.js\";\nimport { Position, isFieldReady } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { createTipSurface, loadImageTip } from \"./runtime.js\";\n\n// Internal module imports\nimport { initStrokeComposite } from \"./composite.js\";\nimport {\n isReady,\n glDraw,\n glDrawImages,\n circle,\n stampImage,\n invalidateTexEntry,\n snapshotMatrix,\n} from \"./gl_draw.js\";\n\ninitStrokeComposite(); // Register the stroke composite system for offscreen mask rendering and compositing.\n\n// ---------------------------------------------------------------------------\n// Brush State and Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Global stroke state settings.\n */\nState.stroke = {\n color: null,\n weight: 1,\n type: \"HB\",\n isActive: false,\n opacity: 1,\n};\n\nlet list = new Map();\n\nconst DEFAULT_CUSTOM_PRESSURE_VARIATION = {\n offset: 0.08,\n scale: 0.08,\n warp: 0.06,\n tilt: 0.06,\n};\n\n/**\n * Retrieves a shallow copy of the current stroke state.\n * @returns {object} The stroke state.\n */\nexport function BrushState() {\n return { ...State.stroke };\n}\n\n/**\n * Updates the stroke state.\n * @param {object} state - The new stroke state.\n */\nexport function BrushSetState(state) {\n State.stroke = { ...state };\n}\n\n// =============================================================================\n// Section: Brush Manager\n// =============================================================================\n\n/**\n * Adds a new brush with the specified parameters to the brush list.\n * @param {string} name - The unique name for the new brush.\n * @param {object} params - The parameters defining the brush behavior and appearance.\n */\n/**\n * Normalizes the pressure parameter to the internal { type, min_max, curve } format.\n * Accepts:\n * [start, end] — linear ramp between two pressure values\n * [start, mid, end] — piecewise linear (e.g. [1.5, 0.5, 1.5] for U-curve)\n * (t) => value — custom function, t ∈ [0,1], return value ∈ [0,1]\n * { mode: \"gaussian\", curve, min_max } — advanced built-in pressure profile\n * { curve, min_max } — legacy gaussian format, preserved for compatibility\n */\nexport function normalizePressure(p) {\n if (!p) return p;\n if (typeof p === \"function\")\n return {\n type: \"custom\",\n min_max: [0, 1],\n curve: p,\n variation: { ...DEFAULT_CUSTOM_PRESSURE_VARIATION },\n };\n if (typeof p === \"object\" && !Array.isArray(p)) {\n if (p.type === \"custom\" || p.mode === \"custom\") {\n const { mode, ...rest } = p;\n return {\n ...rest,\n type: \"custom\",\n variation: {\n ...DEFAULT_CUSTOM_PRESSURE_VARIATION,\n ...(rest.variation ?? {}),\n },\n };\n }\n if (\n p.type === \"gaussian\" ||\n p.mode === \"gaussian\" ||\n (Array.isArray(p.curve) && Array.isArray(p.min_max))\n ) {\n return {\n ...p,\n type: \"gaussian\",\n curve: p.curve,\n min_max: p.min_max,\n };\n }\n return p;\n }\n if (Array.isArray(p)) {\n const [s, m, e] = p.length === 2 ? [p[0], (p[0] + p[1]) / 2, p[1]] : p;\n const min = Math.min(s, m, e),\n max = Math.max(s, m, e);\n const range = max - min || 1;\n const [ns, nm, ne] = [\n (s - min) / range,\n (m - min) / range,\n (e - min) / range,\n ];\n return {\n type: \"custom\",\n min_max: [min, max],\n variation: { ...DEFAULT_CUSTOM_PRESSURE_VARIATION },\n curve: (t) =>\n t < 0.5 ? ns + (nm - ns) * t * 2 : nm + (ne - nm) * (t - 0.5) * 2,\n };\n }\n}\n\nexport function add(name, params) {\n const validTypes = [\"marker\", \"custom\", \"image\", \"spray\"];\n params.type = validTypes.includes(params.type) ? params.type : \"default\";\n if (params.markerTip === undefined) params.markerTip = true;\n if (params.noise === undefined) params.noise = 0.3;\n params.noise = Math.max(0, Math.min(1, params.noise));\n // Accept legacy param names for backward compatibility\n if (params.vibration !== undefined && params.scatter === undefined)\n params.scatter = params.vibration;\n if (params.definition !== undefined && params.sharpness === undefined)\n params.sharpness = params.definition;\n if (params.quality !== undefined && params.grain === undefined)\n params.grain = params.quality;\n params.pressure = normalizePressure(params.pressure);\n if (params.type === \"custom\") {\n if (typeof params.tip !== \"function\") {\n throw new Error(`Brush \"${name}\" is type \"custom\" but is missing a tip function.`);\n }\n // Rasterise the tip once into a 500×500 P2D buffer.\n // Users draw in a 100×100 coordinate space (origin at centre);\n // dark fills/strokes → high opacity, light/white → transparent.\n const key = `custom::${name}`;\n invalidateTexEntry(key); // discard stale GPU texture if tip changed\n const g = createTipSurface(500, 500);\n g.pixelDensity(1);\n g.background(255);\n g.noSmooth();\n g.push();\n g.translate(250, 250); // centre origin\n g.scale(5); // 100 user units → 500 px\n g.noStroke();\n params.tip(g);\n g.pop();\n T.imageToWhite(g); // dark → high alpha, RGB → white for tint\n T.tips.set(key, g);\n params.tipKey = key;\n list.set(name, { param: params, colors: [], buffers: [] });\n return;\n }\n if (params.type === \"image\") {\n if (!params.image || !params.image.src) {\n throw new Error(\n `Brush \"${name}\" is type \"image\" but is missing params.image.src. Example: image: { src: \"./tip.jpg\" }`,\n );\n }\n T.add(params.image.src);\n list.set(name, { param: params, colors: [], buffers: [] });\n return T.load(); // returns a Promise; only loads images not yet loaded\n }\n list.set(name, { param: params, colors: [], buffers: [] });\n}\n\n/**\n * Retrieves the list of available brush names.\n * @returns {Array<string>} Array of brush names.\n */\nexport function box() {\n return [...list.keys()];\n}\n\nexport function getBrushParams(brushName) {\n return list.get(brushName)?.param ?? null;\n}\n\n/**\n * Scales standard brush parameters by the provided factor.\n * @param {number} scaleFactor - The scaling factor to apply.\n */\nexport function scaleBrushes(scaleFactor) {\n for (const { param } of list.values()) {\n if (param) {\n param.weight *= scaleFactor;\n param.scatter *= scaleFactor;\n param.spacing *= scaleFactor;\n }\n }\n}\n\n/**\n * Sets the current brush type by name.\n * @param {string} brushName - The name of the brush.\n */\nexport function pick(brushName) {\n if (!list.has(brushName)) {\n throw new Error(\n `Brush \"${brushName}\" not found. Available brushes: ${[...list.keys()].join(\", \")}.`,\n );\n }\n State.stroke.type = brushName;\n}\n\n/**\n * Sets the stroke style (color) for the current brush.\n * @param {number|string|Color} r - Red component, CSS color string, or Color object.\n * @param {number} [g] - Green component.\n * @param {number} [b] - Blue component.\n */\nexport function stroke(r, g, b) {\n isCanvasReady();\n State.stroke.color = createColor(...arguments);\n State.stroke.isActive = true;\n}\n\n/**\n * Sets the brush weight (thickness).\n * @param {number} weight - The weight value.\n */\nexport function strokeWeight(weight) {\n State.stroke.weight = weight;\n}\n\n/**\n * Sets the current brush with name, color, and weight.\n * @param {string} brushName - The brush name.\n * @param {string|Color} color - The brush color.\n * @param {number} [weight=1] - The brush weight.\n */\nexport function set(brushName, color, weight = 1) {\n pick(brushName);\n stroke(color);\n strokeWeight(weight);\n}\n\n/**\n * Disables the stroke effect.\n */\nexport function noStroke() {\n State.stroke.isActive = false;\n}\n\n/**\n * Defines a clipping region for strokes.\n * The region uses the same coordinate space as brush drawing commands,\n * with the current runtime transform captured at call time.\n * @param {number[]} region - Array as [x1, y1, x2, y2] defining the clipping region.\n */\nexport function clip(region) {\n isCanvasReady();\n return region;\n}\n\n/**\n * Disables the clipping region.\n */\nexport function noClip() {\n return;\n}\n\n// ---------------------------------------------------------------------------\n// Drawing Variables and Functions\n// ---------------------------------------------------------------------------\nlet _position, _length, _plot, _dir;\nconst current = {};\n\n/**\n * Initializes the drawing state.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of stroke.\n * @param {Plot|false} [plot=false] - Plot object for path-following strokes.\n */\nfunction initializeDrawingState(x, y, length, plot = false) {\n snapshotMatrix();\n _position = new Position(x + Cwidth / 2, y + Cheight / 2);\n _length = length;\n _plot = plot;\n if (_plot) _plot.calcIndex(0);\n}\n\nconst gaussians = [];\n\n_onSeed(() => {\n gaussians.length = 0;\n});\n\n/**\n * Executes the drawing operation.\n * @param {number} angleScale - Angle (in degrees) or scaling factor.\n * @param {boolean} isPlot - True if plotting a shape.\n */\nfunction draw(angleScale, isPlot) {\n if (!isPlot) _dir = angleScale;\n saveState();\n\n const stepSize = spacing();\n const totalSteps = Math.round(\n (_length * (isPlot ? angleScale : 1)) / stepSize,\n );\n current.pressureCount = 10;\n current.cachedPressure = undefined;\n current.lineNoiseCount = 5;\n current.cachedLineNoise = undefined;\n\n for (let i = 0; i < totalSteps; i++) {\n if (gaussians.length < totalSteps * 2) {\n gaussians.push(gaussian());\n }\n tip();\n if (isPlot) {\n _position.plotTo(\n _plot,\n stepSize,\n stepSize,\n angleScale,\n i < 10 ? true : false,\n );\n } else {\n _position._moveToDegrees(angleScale, stepSize, stepSize);\n }\n }\n restoreState();\n}\n\n/**\n * Prepares the environment for a brush stroke.\n */\nfunction saveState() {\n current.seed = rr() * 999999;\n const { param } = list.get(State.stroke.type) ?? {};\n if (!param) return;\n current.p = param;\n\n // Set pressure values for the stroke\n const { pressure } = param;\n current.a = pressure.type !== \"custom\" ? rr(-1, 1) : 0;\n current.b = pressure.type !== \"custom\" ? rr(1, 1.5) : 0;\n if (pressure.type !== \"custom\") {\n current.cp = rr(3, 3.5);\n current.ct = 0;\n current.cs = 1;\n current.ck = 0;\n } else {\n const variation = pressure.variation ?? DEFAULT_CUSTOM_PRESSURE_VARIATION;\n current.cp = rr(-variation.offset, variation.offset);\n current.ct = rr(-variation.warp, variation.warp);\n current.cs = rr(1 - variation.scale, 1 + variation.scale);\n current.ck = rr(-variation.tilt, variation.tilt);\n }\n [current.min, current.max] = pressure.min_max;\n\n current.noiseoffset = 0.05 * current.p.noise;\n\n // Cache stroke direction for direction-aware dispersion (non-plot strokes only)\n if (!_plot) {\n current.cos = cos(_dir);\n current.sin = sin(_dir);\n }\n\n // Ensure GL is ready and blend state\n isReady();\n const switchingToBrush = Mix.isBrush !== true;\n Mix.isBrush = true;\n if (switchingToBrush) Mix.justChanged = true;\n Mix.blend(State.stroke.color);\n\n // Set additional state values\n current.alpha = calculateAlpha();\n\n markerTip();\n}\n\n/**\n * Restores drawing state after completing a stroke.\n */\nfunction restoreState() {\n markerTip();\n glDraw();\n const type = current.p?.type;\n if (type === \"image\") glDrawImages(T.tips.get(current.p.image.src), current.p.image.src);\n else if (type === \"custom\") glDrawImages(T.tips.get(current.p.tipKey), current.p.tipKey);\n}\n\n/**\n * Renders the brush tip based on current pressure and position.\n */\nfunction tip() {\n const pressure = calculatePressure();\n const lineNoise = calculateLineNoise();\n\n if (lineNoise > rr(1,1.02) && rr(0,1) < 0.7) return;\n switch (current.p.type) {\n case \"spray\":\n drawSpray(pressure * lineNoise);\n break;\n case \"marker\":\n drawMarker(pressure * lineNoise);\n break;\n case \"custom\":\n case \"image\":\n drawImageTip(pressure * lineNoise);\n break;\n default:\n drawDefault(pressure * lineNoise);\n break;\n }\n}\n\n/**\n * Calculates the effective brush pressure.\n * @returns {number} The calculated pressure.\n */\nfunction calculatePressure() {\n if (current.pressureCount >= 10 || current.cachedPressure === undefined) {\n current.cachedPressure = _plot\n ? simPressure() * _plot.pressure(_position.plotted)\n : simPressure();\n current.pressureCount = 0;\n }\n current.pressureCount++;\n return current.cachedPressure;\n}\n\nfunction calculateLineNoise() {\n if (current.lineNoiseCount >= 10 || current.cachedLineNoise === undefined) {\n current.cachedLineNoise = map(\n noise(current.seed + _position.plotted * 0.01, 0),\n -1,\n 1,\n 1 - current.noiseoffset,\n 1 + current.noiseoffset,\n );\n current.lineNoiseCount = 0;\n }\n current.lineNoiseCount++;\n return current.cachedLineNoise;\n}\n\n/**\n * Simulates brush pressure based on stroke parameters.\n * @returns {number} Simulated pressure value.\n */\nfunction simPressure() {\n const value = current.p.pressure.type === \"custom\"\n ? map(\n current.p.pressure.curve(\n Math.max(\n 0,\n Math.min(\n 1,\n 0.5 + ((_position.plotted / _length) - 0.5 + current.ct) * current.cs,\n ),\n ),\n ) +\n current.cp +\n current.ck * ((_position.plotted / _length) - 0.5),\n 0,\n 1,\n current.min,\n current.max,\n true,\n )\n : gauss();\n return value;\n}\n\n/**\n * Generates a Gaussian-based pressure value.\n * @param {number} [a] - Center parameter.\n * @param {number} [b] - Width parameter.\n * @param {number} [c] - Shape parameter.\n * @param {number} [min] - Minimum pressure.\n * @param {number} [max] - Maximum pressure.\n * @returns {number} Gaussian pressure value.\n */\nfunction gauss(\n a = 0.5 + current.p.pressure.curve[0] * current.a,\n b = 1 - current.p.pressure.curve[1] * current.b,\n c = current.cp,\n min = current.min,\n max = current.max,\n) {\n const peakPos = a * _length;\n const halfWidth =\n (_position.plotted < peakPos ? b * 1.2 : b * 0.8) * (_length / 2);\n return map(\n 1 /\n (1 +\n Math.pow(Math.abs((_position.plotted - peakPos) / halfWidth), 2 * c)),\n 0,\n 1,\n min,\n max,\n );\n}\n\n/**\n * Calculates the alpha (opacity) level for a brush stroke.\n * @returns {number} The calculated opacity.\n */\nfunction calculateAlpha() {\n return [\"default\", \"spray\"].includes(current.p.type)\n ? current.p.opacity\n : current.p.opacity / Math.min(State.stroke.weight, 1.3);\n}\n\n/**\n * Calculates the step spacing based on the current brush parameters.\n * @returns {number} The spacing value.\n */\nfunction spacing() {\n const { param } = list.get(State.stroke.type) ?? {};\n if (!param) return 1;\n return param.spacing;\n}\n\nfunction getImageTipOverscan() {\n const maxPressure = Math.max(1, current.max ?? 1);\n const scatterReach = State.stroke.weight * current.p.scatter;\n const tipReach = State.stroke.weight * current.p.weight * maxPressure;\n\n // Custom/image tips can extend beyond their nominal square because the tip\n // drawing itself may be large and because high scatter creates sparse large\n // stamps near the edge. Keep culling/dirty tracking conservative.\n return Math.max(8, scatterReach * 1.5 + tipReach * 0.75);\n}\n\n// ---------------------------------------------------------------------------\n// Brush Tip Rendering Methods\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the spray tip effect.\n * @param {number} pressure - Current pressure.\n */\nfunction drawSpray(pressure) {\n const vibration =\n State.stroke.weight * current.p.scatter * pressure +\n (State.stroke.weight * rArray(gaussians) * current.p.scatter) / 3;\n const sw = current.p.weight * rr(0.9, 1.1);\n const iterations = Math.ceil(current.p.grain / pressure);\n for (let j = 0; j < iterations; j++) {\n const r = rr(0.9, 1.1);\n const rX = r * vibration * rr(-1, 1);\n const yRandomFactor = rr(-1, 1);\n const sqrtPart = Math.sqrt((r * vibration) ** 2 - rX ** 2);\n circle(\n _position.x + rX,\n _position.y + yRandomFactor * sqrtPart,\n sw,\n current.alpha,\n );\n }\n}\n\n/**\n * Draws the marker tip effect.\n * @param {number} pressure - Current pressure.\n * @param {boolean} [vibrate=true] - Whether to apply vibration.\n */\nfunction drawMarker(pressure, vibrate = true, alpha = current.alpha) {\n const vibration = vibrate ? State.stroke.weight * current.p.scatter : 0;\n const rx = vibrate ? vibration * rr(-1, 1) : 0;\n const ry = vibrate ? vibration * rr(-1, 1) : 0;\n circle(\n _position.x + rx,\n _position.y + ry,\n State.stroke.weight * current.p.weight * pressure,\n alpha * Math.max(0.8, pressure) * rr(0.9,1.1),\n );\n}\n\n/**\n * Queues a stamp for instanced GL rendering.\n * Handles both \"image\" and \"custom\" tip types.\n * @param {number} pressure - Current pressure.\n * @param {number} alpha - Opacity [0..255].\n */\nfunction drawImageTip(pressure, alpha = current.alpha) {\n const vibration = State.stroke.weight * current.p.scatter;\n const rx = vibration * rr(-1, 1);\n const ry = vibration * rr(-1, 1);\n const size = current.p.weight * State.stroke.weight * pressure;\n const overscan = getImageTipOverscan();\n let angle = 0;\n if (current.p.rotate === \"random\") {\n angle = randInt(0, 360) * (Math.PI / 180);\n } else if (current.p.rotate === \"natural\") {\n angle = ((_plot ? -_plot.angle(_position.plotted) : -_dir) + _position.angle()) * (Math.PI / 180);\n }\n stampImage(\n _position.x + rx,\n _position.y + ry,\n size,\n angle,\n alpha * Math.max(0.8, pressure) * rr(0.9, 1.1),\n overscan,\n );\n}\n\n/**\n * Draws the default brush tip.\n * @param {number} pressure - Current pressure.\n */\nfunction drawDefault(pressure, wiggle = 1) {\n wiggle = map(wiggle, 0, 1, 0.9, 1.05);\n const vibration =\n wiggle *\n State.stroke.weight *\n current.p.scatter *\n (current.p.sharpness +\n ((1 - current.p.sharpness) * rArray(gaussians)) / pressure);\n const passesGate = rr(0, current.p.grain * pressure) > 0.4;\n if (passesGate) {\n let dx, dy;\n if (_plot) {\n const plotAngle = _plot.angle(_position.plotted);\n const plotCos = cos(plotAngle);\n const plotSin = sin(plotAngle);\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * plotSin + along * plotCos;\n dy = perp * plotCos - along * plotSin;\n } else {\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * current.sin + along * current.cos;\n dy = perp * current.cos - along * current.sin;\n }\n const diameter =\n pressure *\n pressure *\n current.p.weight *\n rr(0.85, 1.15) *\n State.stroke.weight;\n const alpha = Math.max(0.9, pressure) * current.alpha * rr(0.75, 1.1);\n circle(\n _position.x + dx,\n _position.y + dy,\n diameter,\n alpha,\n );\n }\n}\n\n/**\n * Draws the marker tip with a blend effect.\n */\nfunction markerTip() {\n if (current.p.markerTip === false) return;\n let pressure = calculatePressure();\n let alpha = current.alpha;\n if (current.p.type === \"marker\") {\n for (let s = 1; s < 10; s++) {\n drawMarker((pressure * s) / 10, true, alpha * 8);\n }\n } else if (current.p.type === \"custom\" || current.p.type === \"image\") {\n for (let s = 1; s < 5; s++) {\n drawImageTip((pressure * s) / 10, alpha * 2);\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Basic Drawing Operations\n// ---------------------------------------------------------------------------\n\n/**\n * Draws a line using the current brush.\n * @param {number} x1 - Start x-coordinate.\n * @param {number} y1 - Start y-coordinate.\n * @param {number} x2 - End x-coordinate.\n * @param {number} y2 - End y-coordinate.\n */\nexport function line(x1, y1, x2, y2) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n let d = dist(x1, y1, x2, y2);\n if (d == 0) return;\n initializeDrawingState(x1, y1, d);\n let angle = calcAngle(x1, y1, x2, y2);\n draw(angle, false);\n}\n\n/**\n * Draws a stroke from a starting point in a given direction.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of the stroke.\n * @param {number} dir - Direction, interpreted using the current runtime angle units.\n */\nexport function flowLine(x, y, length, dir) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n initializeDrawingState(x, y, length);\n draw(toDegrees(dir), false);\n}\n\n/**\n * Draws a predefined plot.\n * @param {object} p - Shape object representing the plot.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nfunction plot(p, x, y, scale) {\n isFieldReady();\n initializeDrawingState(x, y, p.length, p);\n draw(scale, true);\n}\n\n// ---------------------------------------------------------------------------\n// Standard Brushes Definition and Initialization\n// ---------------------------------------------------------------------------\n\n/**\n * Defines a set of standard brushes with specific characteristics. Each brush is defined\n * with properties such as weight, scatter, sharpness, grain, opacity, spacing, and\n * pressure sensitivity. Some brushes have additional properties like type, tip, and rotate.\n */\nconst _vals = [\n \"weight\",\n \"scatter\",\n \"sharpness\",\n \"grain\",\n \"opacity\",\n \"spacing\",\n \"pressure\",\n \"type\",\n \"tip\",\n \"rotate\",\n \"markerTip\",\n \"noise\",\n];\nconst _standard_brushes = [\n [\n \"pen\",\n [0.3, 0.15, 0.9, 2, 150, 0.1, { curve: [0.15, 0.2], min_max: [1.2, 1] }],\n ],\n [\n \"rotring\",\n [0.15, 0.05, 0.7, 15, 210, 0.1, { curve: [0.35, 0.2], min_max: [1.3, 1] }],\n ],\n [\n \"2B\",\n [0.3, 0.75, 0.45, 15, 180, 0.1, { curve: [0.1, 0.3], min_max: [1.1, 0.9] }],\n ],\n [\n \"HB\",\n [0.3, 0.6, 0.3, 10, 170, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"2H\",\n [0.2, 0.6, 0.3, 4, 120, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"cpencil\",\n [0.3, 0.55, 0.8, 7, 75, 0.1, { curve: [0.15, 0.2], min_max: [0.95, 1.2] }],\n ],\n [\n \"pastel\",\n [\n 2.05 / 3,\n 13.4 / 3,\n 0.91,\n 28,\n 35,\n 0.085 / 3,\n { mode: \"gaussian\", curve: [0.4, 0.05], min_max: [1.09, 0.93] },\n \"default\",\n undefined,\n \"natural\",\n true,\n 1,\n ],\n ],\n [\n \"crayon\",\n [\n 0.9 / 3,\n 5.45 / 3,\n 0.75,\n 250,\n 159,\n 0.23 / 3,\n [1.1, 0.9],\n \"default\",\n undefined,\n \"natural\",\n true,\n 1,\n ],\n ],\n [\n \"charcoal\",\n [\n 0.35,\n 1.5,\n 0.68,\n 500,\n 120,\n 0.03,\n { curve: [0.15, 0.4], min_max: [1.1, 0.95] },\n ],\n ],\n [\n \"spray\",\n [\n 0.2,\n 6,\n 15,\n 40,\n 90,\n 0.5,\n { curve: [0.2, 0.35], min_max: [0.7, 1] },\n \"spray\",\n ],\n ],\n [\n \"marker\",\n [\n 2,\n 0.2,\n null,\n null,\n 1,\n 0.03,\n { curve: [0.35, 0.25], min_max: [1.2, 0.85] },\n \"marker\",\n ],\n ],\n];\n\nfor (let s of _standard_brushes) {\n let obj = {};\n for (let i = 0; i < s[1].length; i++) obj[_vals[i]] = s[1][i];\n add(s[0], obj);\n}\n\n// ---------------------------------------------------------------------------\n// Extensions to Polygon and Plot Prototypes\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the polygon using the current brush.\n * @param {boolean} [_brush=false] - Optional brush name override.\n * @param {string|Color} [_color] - Optional color override.\n * @param {number} [_weight] - Optional weight override.\n */\nPolygon.prototype.draw = function (_brush = false, _color, _weight) {\n let state = BrushState();\n if (_brush) set(_brush, _color, _weight);\n if (state.isActive) {\n for (let s of this.sides) {\n line(s[0].x, s[0].y, s[1].x, s[1].y);\n }\n }\n BrushSetState(state);\n};\n\n/**\n * Draws the plot using the current brush.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nPlot.prototype.draw = function (x, y, scale) {\n if (BrushState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n plot(this, x, y, scale);\n }\n};\n\n// =============================================================================\n// Section: Loading Custom Image Tips\n// =============================================================================\n/**\n * This section defines the functionality for managing the loading and processing of image tips.\n * Images are loaded from specified source URLs, converted to a white tint for visual effects,\n * and then stored for future use. It includes methods to add new images, convert their color\n * scheme, and integrate them into the active host image pipeline.\n */\n\n/**\n * Manages loading and processing of image tips.\n * Images are converted to white with inverted alpha for tinting via shaders.\n */\nconst T = {\n tips: new Map(),\n\n /**\n * Registers an image source for later loading.\n * @param {string} src - The source URL of the image.\n */\n add(src) {\n if (!this.tips.has(src)) this.tips.set(src, false);\n },\n\n /**\n * Converts image to white with inverted alpha for tint-based rendering.\n * @param {object} image - The host image object to convert.\n */\n imageToWhite(image) {\n image.loadPixels();\n for (let i = 0; i < 4 * image.width * image.height; i += 4) {\n let average =\n (image.pixels[i] + image.pixels[i + 1] + image.pixels[i + 2]) / 3;\n image.pixels[i] = image.pixels[i + 1] = image.pixels[i + 2] = 255;\n image.pixels[i + 3] = 255 - average;\n }\n image.updatePixels();\n },\n\n /**\n * Loads all registered image tips. Returns a promise that resolves\n * when all images are loaded and processed.\n * @returns {Promise}\n */\n async load() {\n const entries = [...this.tips.keys()].filter((k) => !this.tips.get(k));\n await Promise.all(\n entries.map(\n (src) =>\n loadImageTip(src, T.imageToWhite).then((p5img) => {\n this.tips.set(src, p5img);\n }),\n ),\n );\n },\n};\n","import { State } from \"../core/color.js\";\nimport { toDegreesSigned, map, rr } from \"../core/utils.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { BrushState, BrushSetState, set, line } from \"../stroke/stroke.js\";\n\n// =============================================================================\n// Module: Classic Hatch\n// =============================================================================\n\n// ---------------------------------------------------------------------------\n// Hatch State\n// ---------------------------------------------------------------------------\n\nState.hatch = {\n isActive: false,\n dist: 5,\n angle: 45,\n options: {},\n hBrush: false,\n};\n\n/**\n * Returns a shallow snapshot of the current hatch modifier state.\n *\n * @returns {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}}\n */\nexport function HatchState() {\n return { ...State.hatch };\n}\n\n/**\n * Restores hatch modifier state from a previously captured snapshot.\n *\n * @param {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}} state\n */\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Activates classic scanline hatching for subsequent shapes.\n *\n * @param {number} [dist=5] Distance between scanlines.\n * @param {number} [angle=45] Hatch angle in the current runtime angle units.\n * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [options]\n */\nexport function hatch(\n dist = 5,\n angle = 45,\n options = { rand: false, continuous: false, gradient: false }\n) {\n let s = State.hatch;\n s.isActive = true;\n s.dist = dist;\n s.angle = toDegreesSigned(angle);\n s.options = options;\n}\n\n/**\n * Overrides the brush, color, and weight used specifically for hatch strokes.\n *\n * @param {string} brush\n * @param {string|object} [color=\"black\"]\n * @param {number} [weight=1]\n */\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\n/**\n * Deactivates hatching and clears any hatch-specific brush override.\n */\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Scanline Generation\n// ---------------------------------------------------------------------------\n\n/**\n * Computes hatch segments for one polygon by rotating it into scanline space,\n * intersecting horizontal scanlines against its edges, and rotating the\n * resulting segments back into canvas space.\n *\n * @param {Polygon} polygon\n * @param {number} angle Hatch angle in degrees.\n * @param {number} dist Base scanline spacing.\n * @param {number} gradient Multiplicative spacing growth per scanline.\n * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}\n */\nfunction scanlineHatch(polygon, angle, dist, gradient) {\n const rad = (angle * Math.PI) / 180;\n const cosA = Math.cos(rad),\n sinA = Math.sin(rad);\n const cosB = Math.cos(-rad),\n sinB = Math.sin(-rad);\n\n const verts = polygon.a,\n n = verts.length;\n\n // Rotate vertices; track Y extent\n const rotated = new Array(n);\n let minY = Infinity,\n maxY = -Infinity;\n for (let i = 0; i < n; i++) {\n const x = verts[i][0],\n y = verts[i][1];\n const r = [x * cosA - y * sinA, x * sinA + y * cosA];\n rotated[i] = r;\n if (r[1] < minY) minY = r[1];\n if (r[1] > maxY) maxY = r[1];\n }\n\n // Build edge list (skip horizontal edges)\n const edges = [];\n for (let i = 0; i < n; i++) {\n const a = rotated[i],\n b = rotated[(i + 1) % n];\n if (a[1] !== b[1]) edges.push(a, b);\n }\n const eLen = edges.length;\n\n // Scan, find crossings, rotate back\n const segments = [];\n const cx = [];\n let Y = minY + dist * 0.5,\n step = dist;\n while (Y < maxY) {\n cx.length = 0;\n for (let i = 0; i < eLen; i += 2) {\n const y1 = edges[i][1],\n y2 = edges[i + 1][1];\n if ((y1 <= Y && Y < y2) || (y2 <= Y && Y < y1))\n cx.push(\n edges[i][0] + ((Y - y1) / (y2 - y1)) * (edges[i + 1][0] - edges[i][0])\n );\n }\n cx.sort((a, b) => a - b);\n for (let i = 0; i < cx.length - 1; i += 2) {\n segments.push({\n scanY: Y,\n x1: cx[i] * cosB - Y * sinB,\n y1: cx[i] * sinB + Y * cosB,\n x2: cx[i + 1] * cosB - Y * sinB,\n y2: cx[i + 1] * sinB + Y * cosB,\n });\n }\n Y += step;\n step *= gradient;\n }\n return segments;\n}\n\n/**\n * Collects and orders hatch segments for one polygon or a polygon list.\n *\n * Segments are sorted in scanline traversal order so downstream rendering can\n * optionally connect them into a continuous serpentine path.\n *\n * @param {Polygon|Polygon[]} polygons\n * @param {number} dist\n * @param {number} angle\n * @param {number} gradient\n * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}\n */\nfunction getHatchSegments(polygons, dist, angle, gradient) {\n if (!Array.isArray(polygons)) polygons = [polygons];\n const segs = [];\n for (const poly of polygons) {\n for (const s of scanlineHatch(poly, angle, dist, gradient)) segs.push(s);\n }\n segs.sort((a, b) => (a.scanY === b.scanY ? a.x1 - b.x1 : a.scanY - b.scanY));\n return segs;\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Configuration\n// ---------------------------------------------------------------------------\n\n/**\n * Runs hatch drawing with the temporary hatch-specific brush style if one is active,\n * then restores the outer stroke state.\n *\n * @param {() => void} drawFn\n */\nfunction withHatchStyle(drawFn) {\n const save = BrushState();\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n drawFn();\n BrushSetState(save);\n}\n\n/**\n * Resolves the active hatch parameters and precomputes the ordered scanline segments.\n *\n * @param {Polygon|Polygon[]} polygons\n * @returns {{dist:number, options:Object, segs:Object[]}}\n */\nfunction getActiveHatchConfig(polygons) {\n const dist = State.hatch.dist;\n const angle = ((State.hatch.angle % 180) + 180) % 180;\n const options = State.hatch.options;\n const gradient = options.gradient ? map(options.gradient, 0, 1, 1, 1.1, true) : 1;\n const segs = getHatchSegments(polygons, dist, angle, gradient);\n return { dist, options, segs };\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Lines\n// ---------------------------------------------------------------------------\n\n/**\n * Expands ordered hatch segments into the actual line list that will be drawn.\n *\n * This includes endpoint jitter when `rand` is active and inserts the serpentine\n * connector lines when `continuous` is enabled.\n *\n * @param {Polygon|Polygon[]} polygons\n * @returns {{x1:number, y1:number, x2:number, y2:number, scanY:number, isConnector:boolean}[]}\n */\nexport function getHatchLines(polygons) {\n const { dist, options, segs } = getActiveHatchConfig(polygons);\n const r = options.rand || 0;\n const lines = [];\n\n for (let j = 0; j < segs.length; j++) {\n const s = segs[j];\n let x1 = s.x1, y1 = s.y1, x2 = s.x2, y2 = s.y2;\n if (r) {\n x1 += 2 * r * dist * rr(-1, 1);\n y1 += 2 * r * dist * rr(-1, 1);\n x2 += 2 * r * dist * rr(-1, 1);\n y2 += 2 * r * dist * rr(-1, 1);\n }\n const reverse = options.continuous && j % 2 === 1;\n const line = reverse\n ? { x1: x2, y1: y2, x2: x1, y2: y1, scanY: s.scanY, isConnector: false }\n : { x1, y1, x2, y2, scanY: s.scanY, isConnector: false };\n lines.push(line);\n if (j > 0 && options.continuous) {\n const prev = lines[lines.length - 2];\n lines.push({\n x1: prev.x2,\n y1: prev.y2,\n x2: line.x1,\n y2: line.y1,\n scanY: s.scanY,\n isConnector: true,\n });\n }\n }\n\n return lines;\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Rendering\n// ---------------------------------------------------------------------------\n\n/**\n * Iterates the generated hatch lines and delegates the actual rendering of each\n * segment to the provided callback.\n *\n * @param {Polygon|Polygon[]} polygons\n * @param {(x1:number, y1:number, x2:number, y2:number, index:number, segs:Object[]) => void} drawSegment\n */\nfunction renderHatchSegments(polygons, drawSegment) {\n const segs = getHatchLines(polygons);\n withHatchStyle(() => {\n for (let j = 0; j < segs.length; j++) {\n const s = segs[j];\n drawSegment(s.x1, s.y1, s.x2, s.y2, j, segs);\n }\n });\n}\n\n/**\n * Draws classic hatch lines over one polygon or an array of polygons.\n *\n * @param {Polygon|Polygon[]} polygons\n */\nexport function createHatch(polygons) {\n renderHatchSegments(polygons, (x1, y1, x2, y2) => {\n line(x1, y1, x2, y2);\n });\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Applies the currently active hatch modifier to a polygon, or temporarily\n * overrides hatch parameters for this call only.\n *\n * @param {number|false} [_dist=false]\n * @param {number} [_angle]\n * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [_options]\n */\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (State.hatch.isActive) createHatch(this);\n HatchSetState(state);\n};\n\n/**\n * Converts the plot to a polygon and applies the currently active hatch modifier.\n *\n * @param {number} x\n * @param {number} y\n * @param {number} scale\n */\nPlot.prototype.hatch = function (x, y, scale) {\n if (HatchState().isActive) {\n if (this.origin) (x = this.origin[0]), (y = this.origin[1]), (scale = 1);\n this.pol = this.genPol(x, y, scale, 0.3);\n this.pol.hatch();\n }\n};\n","// =============================================================================\n// Module: Mass\n// =============================================================================\n\nimport { State } from \"../core/color.js\";\nimport { arc } from \"../core/primitives.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { rr2, dist, calcAngle } from \"../core/utils.js\";\nimport { fromDegrees, usesRadians } from \"../core/runtime.js\";\nimport { HatchState, HatchSetState, hatch, getHatchLines } from \"./hatch.js\";\nimport { BrushState, BrushSetState, getBrushParams, set } from \"../stroke/stroke.js\";\nimport { wiggle } from \"../core/flowfield.js\";\n\n// ---------------------------------------------------------------------------\n// Mass State\n// ---------------------------------------------------------------------------\n\nState.mass = {\n isActive: false,\n brush: null,\n color: null,\n options: {},\n};\n\n/**\n * Returns a shallow copy of the current mass state.\n * @returns {object}\n */\nexport function MassState() {\n return { ...State.mass };\n}\n\n/**\n * Restores a previously saved mass state.\n * @param {object} state\n */\nexport function MassSetState(state) {\n State.mass = { ...state };\n}\n\n/**\n * Enables massing mode with a brush, color, and optional configuration.\n *\n * @param {string} brush - Brush name to use for the mass pass.\n * @param {string|Color} color - Color to use for the mass pass.\n * @param {object} [options={}] - Massing options such as precision, strength, gradient, and outline.\n */\nexport function mass(brush, color, options = {}) {\n State.mass.brush = brush;\n State.mass.color = color;\n State.mass.options = options;\n State.mass.isActive = true;\n}\n\n/**\n * Disables massing mode for subsequent geometry.\n */\nexport function noMass() {\n State.mass.isActive = false;\n State.mass.brush = null;\n State.mass.color = null;\n State.mass.options = {};\n}\n\n// ---------------------------------------------------------------------------\n// Polygon Preparation\n// ---------------------------------------------------------------------------\n\n/**\n * Returns a translated copy of a polygon.\n * Used to build the secondary mass layers from an existing base polygon.\n * @param {Polygon} polygon\n * @param {number} jitterX\n * @param {number} jitterY\n * @returns {Polygon}\n */\nfunction jitterPolygon(polygon, jitterX, jitterY) {\n return new Polygon(\n polygon.vertices.map((vertex) => [vertex.x + jitterX, vertex.y + jitterY]),\n );\n}\n\n/**\n * Builds the three polygons used for a mass pass.\n * Both polygon and plot inputs use one base polygon plus two translated copies,\n * so plot-based massing only needs a single `genPol(...)` call.\n * @param {Polygon|Plot} shape\n * @param {number|false} x\n * @param {number} y\n * @param {number} scale\n * @returns {Polygon[]}\n */\nfunction getMassPolygons(shape, x, y, scale) {\n const isPolygon = x === false;\n const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;\n const basePolygon = isPolygon ? shape : shape.genPol(x, y, scale, 0.15);\n const maxJitter = Math.min(scatter * 2, 5);\n const jitters = [\n [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],\n [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],\n ];\n\n return [\n basePolygon,\n jitterPolygon(basePolygon, jitters[0][0], jitters[0][1]),\n jitterPolygon(basePolygon, jitters[1][0], jitters[1][1]),\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Angle & Bounds Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Converts degree values into the current runtime angle units.\n * @param {number} angle\n * @returns {number}\n */\nfunction getAngleConverter() {\n return usesRadians()\n ? (angle) => (angle * Math.PI) / 180\n : (angle) => angle;\n}\n\n/**\n * Computes an axis-aligned bounding box for a polygon.\n * The diagonal is used as a size reference for pivot distance.\n * @param {Polygon} polygon\n * @returns {{minX:number,minY:number,maxX:number,maxY:number,cx:number,cy:number,size:number}}\n */\nfunction getPolygonBounds(polygon) {\n const points = polygon?.a ?? [];\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n for (const [x, y] of points) {\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n return {\n minX,\n minY,\n maxX,\n maxY,\n cx: (minX + maxX) / 2,\n cy: (minY + maxY) / 2,\n size: Math.hypot(maxX - minX, maxY - minY),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Pivot Geometry\n// ---------------------------------------------------------------------------\n\n/**\n * Chooses the diagonal corner family for a whole mass gesture.\n * Positive-angle hatching uses either bottom-right or top-left; negative-angle\n * hatching uses either bottom-left or top-right.\n * @param {number} angleDeg\n * @returns {[number, number]}\n */\nfunction getPivotBias(angleDeg) {\n const normalizedAngle = ((((angleDeg + 90) % 180) + 180) % 180) - 90;\n if (normalizedAngle >= 0) {\n return rr2() < 0.5 ? [1, 1] : [-1, -1];\n } else {\n return rr2() < 0.5 ? [-1, 1] : [1, -1];\n }\n}\n\n/**\n * Places the global pivot anchor outside the polygon, along the selected bias.\n * Distance varies per layer while the bias stays fixed for the whole mass.\n * @param {Polygon} polygon\n * @param {[number, number]} bias\n * @returns {{x:number,y:number}}\n */\nfunction getPivotAnchor(polygon, bias) {\n const bounds = getPolygonBounds(polygon);\n const offset = bounds.size * rr2(0.6, 1.4);\n const [sx, sy] = bias;\n return {\n x: bounds.cx + sx * offset,\n y: bounds.cy + sy * offset,\n };\n}\n\n/**\n * Projects the global pivot anchor onto the perpendicular bisector of a line.\n * This yields a valid circle center equidistant from both endpoints.\n * @param {{x:number,y:number}} anchor\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {{x:number,y:number}|null}\n */\nfunction projectAnchorToBisector(anchor, x1, y1, x2, y2) {\n const mx = (x1 + x2) / 2;\n const my = (y1 + y2) / 2;\n const dx = x2 - x1;\n const dy = y2 - y1;\n const length = Math.hypot(dx, dy);\n if (!length) return null;\n const nx = -dy / length;\n const ny = dx / length;\n const offset = (anchor.x - mx) * nx + (anchor.y - my) * ny;\n return {\n x: mx + nx * offset,\n y: my + ny * offset,\n };\n}\n\n/**\n * Returns the shortest arc between two endpoints around a given center.\n * The returned angles are already converted into the current runtime angle units.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {[number, number]}\n */\nfunction getShortArcAngles(cx, cy, x1, y1, x2, y2, toAngleUnit) {\n let startDeg = calcAngle(cx, cy, x1, y1);\n let endDeg = calcAngle(cx, cy, x2, y2);\n const sweep = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweep > 180) [startDeg, endDeg] = [endDeg, startDeg];\n return [\n toAngleUnit(startDeg),\n toAngleUnit(endDeg),\n ];\n}\n\n/**\n * Splits a hatch line into two slightly separated segments so some gestures\n * read as interrupted rather than perfectly continuous.\n * @param {{x1:number,y1:number,x2:number,y2:number}} seg\n * @returns {Array<{x1:number,y1:number,x2:number,y2:number}>}\n */\nfunction splitSegment(seg) {\n const t = rr2(0.35, 0.65);\n const mx = seg.x1 + (seg.x2 - seg.x1) * t;\n const my = seg.y1 + (seg.y2 - seg.y1) * t;\n const dx = seg.x2 - seg.x1;\n const dy = seg.y2 - seg.y1;\n const length = Math.hypot(dx, dy) || 1;\n const gap = rr2(0.04, 0.1) * length;\n const gx = (dx / length) * gap * 0.5;\n const gy = (dy / length) * gap * 0.5;\n return [\n { x1: seg.x1, y1: seg.y1, x2: mx - gx, y2: my - gy },\n { x1: mx + gx, y1: my + gy, x2: seg.x2, y2: seg.y2 },\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Mass Rendering\n// ---------------------------------------------------------------------------\n\n/**\n * Draws one polygon of the mass as a family of arcs derived from hatch lines.\n * The same pivot bias is used across layers, while each layer gets its own\n * anchor distance from the shape.\n * @param {Polygon} polygon\n * @param {[number, number]} pivotBias\n */\nfunction drawMassArcs(polygon, pivotBias, toAngleUnit) {\n const anchor = getPivotAnchor(polygon, pivotBias);\n for (const seg of getHatchLines(polygon)) {\n const parts = !seg.isConnector && rr2() < 0.35 ? splitSegment(seg) : [seg];\n for (const part of parts) {\n const center = projectAnchorToBisector(anchor, part.x1, part.y1, part.x2, part.y2);\n if (!center) continue;\n const radius = dist(center.x, center.y, part.x1, part.y1);\n if (!radius) continue;\n const [startAngle, endAngle] = getShortArcAngles(\n center.x,\n center.y,\n part.x1,\n part.y1,\n part.x2,\n part.y2,\n toAngleUnit,\n );\n arc(center.x, center.y, radius, startAngle, endAngle);\n }\n }\n}\n\n/**\n * Configures a hatch pass and immediately reinterprets the generated lines as arcs.\n * @param {Polygon} polygon\n * @param {number} dist\n * @param {number} angle\n * @param {object} options\n * @param {[number, number]} pivotBias\n */\nfunction drawMassPass(polygon, dist, angle, options, pivotBias, toAngleUnit) {\n hatch(dist, angle, options);\n drawMassArcs(polygon, pivotBias, toAngleUnit);\n}\n\n/**\n * Creates the built-in \"massing\" effect for a polygon or plot.\n * A mass is built from up to three jittered polygon layers, each hatched and\n * then redrawn as arc gestures around a shared pivot bias.\n * @param {Polygon|Plot} shape\n * @param {number|false} x\n * @param {number} y\n * @param {number} scale\n */\nexport function createMass(shape, x, y, scale) {\n const pols = getMassPolygons(shape, x, y, scale);\n const hatchState = HatchState();\n const brushState = BrushState();\n const fieldState = { ...State.field };\n const precision = State.mass.options?.precision ?? 0.5;\n const strength = State.mass.options?.strength ?? 1;\n const gradient = State.mass.options?.gradient ?? 0.1;\n const outline = State.mass.options?.outline ?? false;\n const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;\n const hatchDist = 1.6 * rr2(scatter * 0.65, scatter * 0.85) - 0.4 * gradient;\n const baseAngle = rr2(-90, 90);\n const pivotBias = getPivotBias(baseAngle);\n const toAngleUnit = getAngleConverter();\n\n set(State.mass.brush, State.mass.color, 1);\n wiggle(2 - precision);\n if (outline) pols[0].draw();\n\n drawMassPass(\n pols[0],\n hatchDist * 0.9,\n fromDegrees(baseAngle),\n {\n gradient,\n rand: 2 - 2 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n\n if (strength > 0.33) {\n drawMassPass(\n pols[1],\n hatchDist,\n fromDegrees(baseAngle + 20 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n }\n\n if (strength > 0.66) {\n drawMassPass(\n pols[2],\n hatchDist * 0.8,\n fromDegrees(baseAngle + 15 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n }\n\n BrushSetState(brushState);\n HatchSetState(hatchState);\n State.field = { ...fieldState };\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Applies massing to polygon geometry.\n */\nPolygon.prototype.mass = function () {\n if (State.mass?.isActive) {\n createMass(this, false);\n }\n};\n\n/**\n * Applies massing to plots by generating their polygon first.\n * @param {number} x\n * @param {number} y\n * @param {number} scale\n */\nPlot.prototype.mass = function (x, y, scale) {\n if (State.mass?.isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n createMass(this, x, y, scale);\n }\n};\n","import { Mix } from \"../core/color.js\";\n\nfunction strokePadding(ctx, matrix) {\n const lineWidth = ctx.lineWidth || 0;\n if (lineWidth <= 0) return 1;\n\n return (\n 1 +\n (lineWidth * Math.max(Math.hypot(matrix.a, matrix.c), Math.hypot(matrix.b, matrix.d))) /\n 2\n );\n}\n\n// =============================================================================\n// Section: Draw shapes to Mask Buffers\n// =============================================================================\n\n/**\n * Draws a polygon to the mask using the provided vertices.\n * @param {Array<{x: number, y: number}>} vertices - Array of vertex coordinates.\n */\nexport function drawPolygon(vertices) {\n const ctx = Mix.ctx;\n const matrix = ctx.getTransform();\n // Cache the current 2D transform once so the hot loop can stay numeric and\n // avoid repeated property reads while we build bounds.\n const a = matrix.a;\n const b = matrix.b;\n const c = matrix.c;\n const d = matrix.d;\n const e = matrix.e;\n const f = matrix.f;\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n\n ctx.beginPath();\n\n // Seed both the path and the transformed bounds from the first vertex so the\n // loop below only needs to append line segments.\n const first = vertices[0];\n let tx = a * first.x + c * first.y + e;\n let ty = b * first.x + d * first.y + f;\n minX = maxX = tx;\n minY = maxY = ty;\n\n ctx.moveTo(first.x, first.y);\n\n for (let i = 1; i < vertices.length; i++) {\n const v = vertices[i];\n\n // Track the transformed bounds in canvas space while we build the path so\n // dirty-rect bookkeeping does not need a second pass over the vertices.\n tx = a * v.x + c * v.y + e;\n ty = b * v.x + d * v.y + f;\n minX = Math.min(minX, tx);\n minY = Math.min(minY, ty);\n maxX = Math.max(maxX, tx);\n maxY = Math.max(maxY, ty);\n\n ctx.lineTo(v.x, v.y);\n }\n\n ctx.closePath();\n\n // Expand by stroke width so the later composite pass copies enough pixels\n // even when the polygon border extends outside the raw vertex bounds.\n const padding = strokePadding(ctx, matrix);\n Mix.markDirtyRect(Mix.mask, {\n minX: minX - padding,\n minY: minY - padding,\n maxX: maxX + padding,\n maxY: maxY + padding,\n });\n}\n\n/**\n * Draws a circle to the mask.\n * @param {number} x - X-coordinate of the circle's center.\n * @param {number} y - Y-coordinate of the circle's center.\n * @param {number} d - Diameter of the circle.\n */\nexport function circle(x, y, d) {\n const PI2 = Math.PI * 2;\n const ctx = Mix.ctx;\n const radius = d / 2;\n\n ctx.moveTo(x + radius, y);\n ctx.arc(x, y, radius, 0, PI2);\n}\n","import * as Color from \"../core/color.js\";\nimport {\n createFramebuffer,\n create2DCanvas,\n} from \"../core/compositor_runtime.js\";\n\n// Small staging canvas used to upload only the dirty fill sub-rect into the\n// framebuffer-backed mask mirror consumed by the blend shader.\nlet FillMaskUploadCanvas = null;\nlet isFillCompositeRegistered = false;\nconst DIRTY_FILL_PADDING = 4;\n\n// =============================================================================\n// Section: Helpers\n// =============================================================================\n/**\n * Returns whether the CPU-side 2D fill mask must be recreated.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} maskWidth - Mask width in physical pixels.\n * @param {number} maskHeight - Mask height in physical pixels.\n * @returns {boolean} True when the 2D fill mask needs reallocation.\n */\nfunction needsFillMaskCanvas(Renderer, maskWidth, maskHeight) {\n return (\n !Renderer.mask ||\n Renderer.mask.width !== maskWidth ||\n Renderer.mask.height !== maskHeight\n );\n}\n\n/**\n * Returns whether the framebuffer-backed fill mask mirror must be recreated.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {boolean} True when the fill mask framebuffer needs reallocation.\n */\nfunction needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density) {\n return (\n !Renderer.fillMaskFramebuffer ||\n Renderer.fillMaskFramebuffer.width !== Cwidth ||\n Renderer.fillMaskFramebuffer.height !== Cheight ||\n (typeof Renderer.fillMaskFramebuffer.pixelDensity === \"function\" &&\n Renderer.fillMaskFramebuffer.pixelDensity() !== Density)\n );\n}\n\n// =============================================================================\n// Section: Resource Management\n// =============================================================================\n/**\n * Ensures fill compositing resources exist for the active renderer.\n *\n * Fill draws first into a CPU-side 2D mask canvas. That mask is later uploaded,\n * dirty-rect by dirty-rect, into a framebuffer-backed mirror used by the final\n * blend shader pass.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n * @returns {{mask: object, ctx: CanvasRenderingContext2D}} Fill mask resources.\n */\nexport function ensureFillCompositeResources(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n clearTarget,\n) {\n const maskWidth = Math.max(1, Math.round(Cwidth * Density));\n const maskHeight = Math.max(1, Math.round(Cheight * Density));\n\n if (needsFillMaskCanvas(Renderer, maskWidth, maskHeight)) {\n Renderer.mask = create2DCanvas(maskWidth, maskHeight);\n }\n\n if (needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.fillMaskFramebuffer?.remove) {\n Renderer.fillMaskFramebuffer.remove();\n }\n Renderer.fillMaskFramebuffer = createFramebuffer(Renderer, {\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n clearTarget(Renderer.fillMaskFramebuffer);\n }\n\n Renderer.mask.dirtyRect ??= null;\n Renderer.mask.isDrawn ??= false;\n Renderer.mask.drawingContext.imageSmoothingEnabled = false;\n return {\n mask: Renderer.mask,\n ctx: Renderer.mask.drawingContext,\n };\n}\n\n// =============================================================================\n// Section: Mask Lifecycle\n// =============================================================================\n/**\n * Clears the current fill mask and resets its bookkeeping flags.\n *\n * @param {object|null} target - Fill mask canvas or framebuffer mirror.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n */\nexport function clearFillMask(target, clearTarget) {\n if (!target) return;\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\n}\n\n// =============================================================================\n// Section: Composite Bounds\n// =============================================================================\n/**\n * Returns the fill dirty rect to composite into the main target. Fill bounds are\n * taken directly from the accumulated 2D mask dirty area plus a small padding.\n *\n * @param {object|null} target - Fill mask canvas.\n * @param {Function} _getActiveFramebuffer - Unused for fill masks.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} expandDirtyRect - Expands a rect by a constant padding.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\nexport function getFillCompositeRect(\n target,\n _getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(target.dirtyRect, DIRTY_FILL_PADDING),\n );\n}\n\n// =============================================================================\n// Section: Upload\n// =============================================================================\n/**\n * Uploads only the dirty portion of the CPU-side 2D fill mask into the\n * framebuffer-backed fill mask mirror used by the shader compositor.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {object} mask - CPU-side 2D fill mask canvas.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} dirtyRect - Dirty rect to upload.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n * @returns {object} Framebuffer-backed fill mask mirror.\n */\nexport function getFillShaderMask(\n Renderer,\n mask,\n dirtyRect,\n normalizeDirtyRect,\n getFullDirtyRect,\n clearTarget,\n) {\n const target = Renderer.fillMaskFramebuffer;\n const gl = Renderer.drawingContext;\n const uploadRect = normalizeDirtyRect(dirtyRect) ?? getFullDirtyRect();\n const uploadWidth = uploadRect.maxX - uploadRect.minX;\n const uploadHeight = uploadRect.maxY - uploadRect.minY;\n\n if (\n !FillMaskUploadCanvas ||\n FillMaskUploadCanvas.width !== uploadWidth ||\n FillMaskUploadCanvas.height !== uploadHeight\n ) {\n FillMaskUploadCanvas = create2DCanvas(uploadWidth, uploadHeight);\n }\n\n const uploadContext = FillMaskUploadCanvas.drawingContext;\n uploadContext.clearRect(0, 0, uploadWidth, uploadHeight);\n uploadContext.drawImage(\n mask,\n uploadRect.minX,\n uploadRect.minY,\n uploadWidth,\n uploadHeight,\n 0,\n 0,\n uploadWidth,\n uploadHeight,\n );\n\n clearTarget(target);\n gl.bindTexture(gl.TEXTURE_2D, target.colorTexture);\n gl.texSubImage2D(\n gl.TEXTURE_2D,\n 0,\n uploadRect.minX,\n uploadRect.minY,\n gl.RGBA,\n gl.UNSIGNED_BYTE,\n FillMaskUploadCanvas,\n );\n return target;\n}\n\n// =============================================================================\n// Section: Registration\n// =============================================================================\n/**\n * Registers the fill compositor with the shared color/composite core.\n * Safe to call multiple times.\n */\nexport function initFillComposite() {\n if (isFillCompositeRegistered) return;\n Color.registerFillComposite?.({\n ensureResources: ensureFillCompositeResources,\n clearMask: clearFillMask,\n getCompositeRect: getFillCompositeRect,\n getShaderMask: getFillShaderMask,\n });\n isFillCompositeRegistered = true;\n}\n","// =============================================================================\n// Module: Fill\n// =============================================================================\n/**\n * The Fill module contains functions and classes dedicated to handling\n * the fill properties of shapes within the drawing context. It supports complex fill\n * operations with effects such as bleeding to simulate watercolor-like textures. The\n * methods provided allow for setting the fill color with opacity, controlling the\n * intensity of the bleed effect, and enabling or disabling the fill operation.\n *\n * The watercolor effect implementation is inspired by Tyler Hobbs'\n * techniques for simulating watercolor paints.\n */\n\n// Core imports\nimport { Renderer, Cwidth, Cheight, Density } from \"../core/target.js\";\nimport {\n Mix,\n State,\n} from \"../core/color.js\";\nimport { drawPolygon, circle } from \"./mask.js\";\nimport {\n constrain,\n weightedRand,\n rr,\n map,\n randInt,\n gaussian,\n rotate,\n cos,\n sin,\n _onSeed,\n} from \"../core/utils.js\";\nimport { isFieldReady } from \"../core/flowfield.js\";\nimport { createColor, getAffineMatrix } from \"../core/runtime.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\n\n// Internal module imports\nimport { initFillComposite } from \"./composite.js\";\n\ninitFillComposite(); // Register the fill composite with the core color module\n\n// =============================================================================\n// Fill State and helpers\n// =============================================================================\n\n// Vertex cap for grow() — set to 0 or false to disable\nconst GROW_MAX_VERTS = 2024;\nlet GROW_CAP;\n\n// Reusable scratch arrays for grow() — avoids 4 allocations per call (~15× per fill)\nlet _growInsX = [];\nlet _growInsY = [];\nlet _growMods = [];\nlet _growDirs = [];\n\n/**\n * Global fill state settings.\n */\nState.fill = {\n opacity: 150,\n bleed_strength: 0.07,\n texture_strength: 0.8,\n border_strength: 0.5,\n direction: \"out\",\n isActive: false,\n};\n\n// Cache the current state\nconst FillState = () => ({ ...State.fill });\nconst FillSetState = (state) => {\n State.fill = { ...state };\n};\n\n// ---------------------------------------------------------------------------\n// Fill Style Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Sets the fill color and opacity for subsequent drawing operations.\n * @param {number|string|Color} a - Either the red component, a CSS color string, or a Color object.\n * @param {number} [b] - The green component or the opacity if using grayscale.\n * @param {number} [c] - The blue component.\n * @param {number} [d] - The opacity.\n */\nexport function fill(a, b, c, d) {\n State.fill.opacity = (arguments.length < 4 ? b : d) || 150;\n State.fill.color = arguments.length < 3 ? createColor(a) : createColor(a, b, c);\n State.fill.isActive = true;\n}\n\n/**\n * Sets the bleed (watercolor) intensity and direction.\n * @param {number} _i - The bleed intensity (clamped to [0,1]).\n * @param {string} [_direction=\"out\"] - The bleeding direction.\n */\nexport function fillBleed(_i, _direction = \"out\") {\n State.fill.bleed_strength = constrain(_i, 0, 1);\n State.fill.direction = _direction;\n}\n\n/**\n * Sets the texture and border strengths for the fill.\n * @param {number} [_texture=0.4] - The texture strength (clamped to [0,1]).\n * @param {number} [_border=0.4] - The border strength (clamped to [0,1]).\n */\nexport function fillTexture(_texture = 0.4, _border = 0.4) {\n State.fill.texture_strength = constrain(_texture, 0, 1);\n State.fill.border_strength = constrain(_border, 0, 1);\n}\n\n/**\n * Disables fill for subsequent drawing operations.\n */\nexport function noFill() {\n State.fill.isActive = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fill Manager Functions\n// ---------------------------------------------------------------------------\n\nlet _polygon;\n\n// Pre-compute gaussians for reuse\nconst GAUSSIAN_POOL_SIZE = 512;\nconst _gaussians = [[], []]; // [a, b]\nfunction _fillGaussianPools() {\n for (let i = 0; i < GAUSSIAN_POOL_SIZE; i++) {\n _gaussians[0][i] = gaussian(0.5, 0.2);\n _gaussians[1][i] = gaussian(0, 0.02);\n }\n}\n_onSeed(_fillGaussianPools);\n\n// Helper for direction checking - extracted to reduce duplication\nfunction _isLeft(a, b, c) {\n return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) > 0.01;\n}\n\n/**\n * Calculates the centroid of a polygon from its vertices.\n * @param {Object[]} pts - Array of points with {x, y}.\n * @returns {Object} The center point {x, y}.\n */\nfunction _center(pts) {\n if (pts.length === 0) {\n return { x: 0, y: 0 };\n }\n\n if (pts.length < 8) {\n // Simple average for small polygons\n const sum = pts.reduce(\n (center, point) => ({ x: center.x + point.x, y: center.y + point.y }),\n { x: 0, y: 0 },\n );\n return { x: sum.x / pts.length, y: sum.y / pts.length };\n }\n\n // Close polygon if needed\n const v = [...pts];\n if (v[0].x !== v[v.length - 1].x || v[0].y !== v[v.length - 1].y)\n v.push(v[0]);\n\n // Calculate using shoelace formula (more efficient implementation)\n let area = 0,\n cx = 0,\n cy = 0;\n for (let i = 0; i < v.length - 1; i++) {\n const cross = v[i].x * v[i + 1].y - v[i + 1].x * v[i].y;\n area += cross;\n cx += (v[i].x + v[i + 1].x) * cross;\n cy += (v[i].y + v[i + 1].y) * cross;\n }\n\n area *= 0.5;\n return area\n ? { x: cx / (6 * area), y: cy / (6 * area) }\n : { x: v[0].x, y: v[0].y };\n}\n\n/**\n * Fills a given polygon with a watercolor effect.\n * @param {Polygon} polygon - The polygon to fill.\n */\nexport function createFill(polygon) {\n if (!State.fill.isActive || !State.fill.color) {\n throw new Error(\n \"No fill color set. Call brush.fill(color) before drawing shapes.\",\n );\n }\n _polygon = polygon;\n const v = [...polygon.vertices];\n const fluid = ~~(v.length * 0.25 * weightedRand({ 1: 5, 2: 10, 3: 60 }));\n const strength = State.fill.bleed_strength;\n const modifiers = v.map(\n (_, i) => (i > fluid ? 1 : 0.3) * rr(0.85, 1.4) * strength,\n );\n const shift = randInt(0, v.length);\n const shifted = [...v.slice(shift), ...v.slice(0, shift)];\n const center = _center(shifted);\n return new FillPoly(shifted, modifiers, center, [], true).fill(\n State.fill.color,\n map(State.fill.opacity, 0, 255, 0, 1, true),\n State.fill.texture_strength,\n );\n}\n\n// ---------------------------------------------------------------------------\n// FillPolygon Class\n// ---------------------------------------------------------------------------\n\n/**\n * The FillPolygon class is used to create and manage the properties of the polygons that produces\n * the watercolor effect. It includes methods to grow (expand) the polygon and apply layers\n * of color with varying intensity and erase parts to simulate a natural watercolor bleed.\n * The implementation follows Tyler Hobbs' guide to simulating watercolor:\n * https://tylerxhobbs.com/essays/2017/a-generative-approach-to-simulating-watercolor-paints\n */\nclass FillPoly {\n /**\n * Constructs a FillPolygon.\n * @param {Object[]} _v - Vertices of the polygon.\n * @param {number[]} _m - Multipliers for the bleed effect at each vertex.\n * @param {Object} _center - The polygon's center {x, y}.\n * @param {boolean[]} dir - Array indicating bleed direction per vertex.\n * @param {boolean} isFirst - True for initial polygon.\n */\n constructor(v, m, center, dir = [], isFirst = false, sx, sy) {\n // Initialize properties\n this.v = v;\n this.m = m;\n this.dir = dir;\n this.midP = center;\n\n // Initialize size and direction for first polygon\n if (isFirst) {\n // Calculate size bounds\n let maxX = 0,\n maxY = 0;\n const rayCalc = [];\n\n for (let i = 0; i < v.length; i++) {\n // Store vertex distances to center for size calculation\n const dx = Math.abs(center.x - v[i].x);\n const dy = Math.abs(center.y - v[i].y);\n maxX = Math.max(maxX, dx);\n maxY = Math.max(maxY, dy);\n\n // Store edge info for ray calculations\n const v1 = v[i],\n v2 = v[(i + 1) % v.length];\n const side = { x: v2.x - v1.x, y: v2.y - v1.y };\n const rt = rotate(0, 0, side.x, side.y, 90);\n const mid = { x: v1.x + side.x / 2, y: v1.y + side.y / 2 };\n\n rayCalc.push({\n v1,\n v2,\n ray: {\n point1: mid,\n point2: { x: mid.x + rt.x, y: mid.y + rt.y },\n },\n });\n }\n\n // Store sizes\n this.sizeX = maxX;\n this.sizeY = maxY;\n\n // Calculate directions\n this.dir = Array(v.length);\n rayCalc.forEach((rc, i) => {\n let count = 0;\n for (const isect of _polygon.intersect(rc.ray)) {\n if (_isLeft(rc.v1, rc.v2, isect)) count++;\n }\n this.dir[i] = count % 2 === 0;\n });\n\n // Randomize center (single calculation)\n const rx = rr(-0.6, 0.6) * maxX;\n const ry = rr(-0.6, 0.6) * maxY;\n this.midP = { x: center.x + rx, y: center.y + ry };\n } else {\n this.sizeX = sx;\n this.sizeY = sy;\n }\n }\n\n /**\n * Trims vertices from the polygon based on a factor.\n * @param {number} [factor=1] - Factor determining amount of trimming.\n * @returns {Object} An object containing trimmed vertices, multipliers, and direction.\n */\n trim(f = 1) {\n // Fast path for common case\n if (f >= 1 || f < 0 || this.v.length <= 8) {\n return { v: this.v, m: this.m, dir: this.dir };\n }\n\n // Trim from middle for balance\n const n = ~~((1 - f) * this.v.length);\n const s = ~~(this.v.length / 2 - n / 2);\n\n // Copy only the kept ranges instead of cloning the full arrays and splicing.\n const keep = this.v.length - n;\n const v = new Array(keep);\n const m = new Array(keep);\n const dir = new Array(keep);\n let dst = 0;\n\n for (let i = 0; i < s; i++, dst++) {\n v[dst] = this.v[i];\n m[dst] = this.m[i];\n dir[dst] = this.dir[i];\n }\n\n for (let i = s + n; i < this.v.length; i++, dst++) {\n v[dst] = this.v[i];\n m[dst] = this.m[i];\n dir[dst] = this.dir[i];\n }\n\n\n // We want to add at least two vertices to divide the new edge that appears after trimming, at random distances along its path\n const trimStart = s;\n const trimEnd = s + n;\n const edgeStart = this.v[(trimStart - 1 + this.v.length) % this.v.length];\n const edgeEnd = this.v[trimEnd % this.v.length];\n const edgeVec = { x: edgeEnd.x - edgeStart.x, y: edgeEnd.y - edgeStart.y };\n \n // Insert two new vertices at random positions along the new edge\n const insertCount = 2;\n for (let i = 0; i < insertCount; i++) {\n const t = rr(0.25, 0.75); // Random position between 25% and 75% along the edge\n const newVertex = { x: edgeStart.x + edgeVec.x * t, y: edgeStart.y + edgeVec.y * t };\n const insertIdx = s + i;\n v.splice(insertIdx, 0, newVertex);\n m.splice(insertIdx, 0, rr(0.4, 0.7));\n dir.splice(insertIdx, 0, this.dir[trimStart % this.dir.length]);\n }\n\n return { v, m, dir };\n }\n\n /**\n * Randomly samples a fraction of vertices, keeping their order.\n * Any sampled vertex outside the original polygon is pulled inward.\n * @param {number} [ratio=0.3] - Fraction of vertices to keep.\n * @returns {FillPoly} A new FillPoly with fewer vertices, guaranteed inside the original.\n */\n scatter(ratio = 0.3) {\n const L = this.v.length;\n const keep = Math.max(3, ~~(L * ratio));\n const indices = [];\n const step = L / keep;\n for (let i = 0; i < keep; i++) {\n indices.push(~~(i * step + rr(0, step * 0.8)));\n }\n\n const sv = [],\n sm = [],\n sd = [];\n const mid = this.midP;\n const sides = _polygon.sides;\n\n for (const idx of indices) {\n const j = idx % L;\n let p = this.v[j];\n let crossings = 0;\n for (const [a, b] of sides) {\n const ay = a.y,\n by = b.y;\n if ((ay > p.y) === (by > p.y)) continue;\n const t = (p.y - ay) / (by - ay);\n if (p.x < a.x + t * (b.x - a.x)) crossings++;\n }\n if (crossings % 2 === 0) {\n p = {\n x: mid.x + (p.x - mid.x) * rr(0.3, 0.6),\n y: mid.y + (p.y - mid.y) * rr(0.3, 0.6),\n };\n }\n sv.push(p);\n sm.push(this.m[j]);\n sd.push(!this.dir[j]);\n }\n\n return new FillPoly(sv, sm, this.midP, sd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Returns a copy with all bleed directions flipped.\n */\n flipDirs() {\n return new FillPoly(this.v, this.m, this.midP, this.dir.map(d => !d), false, this.sizeX, this.sizeY);\n }\n\n /**\n * Grows (or shrinks) the polygon vertices to simulate watercolor spread.\n * @param {number} [growthFactor=1] - Factor controlling growth.\n * @returns {FillPoly} A new FillPoly with adjusted vertices.\n */\n grow(f = 1) {\n const { v: tr_v, m: tr_m, dir: tr_dir } = this.trim(f);\n const len = tr_v.length;\n\n const outLen = len * 2;\n if (_growInsX.length < len) { _growInsX = new Array(len); _growInsY = new Array(len); }\n if (_growMods.length < outLen) { _growMods = new Array(outLen); _growDirs = new Array(outLen); }\n const insertedX = _growInsX;\n const insertedY = _growInsY;\n const newMods = _growMods;\n const newDirs = _growDirs;\n const bleedDirDeg = State.fill.direction === \"out\" ? -90 : 90;\n\n if (_gaussians[0].length === 0) _fillGaussianPools();\n const gPool = _gaussians[0],\n gPoolLen = gPool.length;\n const g2Pool = _gaussians[1],\n g2PoolLen = g2Pool.length;\n\n let idx = 0;\n let insertedIdx = 0;\n let mod = f === 999 ? rr(0.6, 0.8) : State.fill.bleed_strength;\n\n for (let i = 0; i < len; i++) {\n const cv = tr_v[i];\n const nv = tr_v[i + 1 < len ? i + 1 : 0];\n const mi = tr_m[i];\n const di = tr_dir[i];\n\n if (f < 997) mod = mi;\n\n // If mod is smaller than 0.02, skip growing math and just insert the middle vertex\n if (mod < 0.05) {\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n insertedX[insertedIdx] = (cv.x + nv.x) / 2;\n insertedY[insertedIdx] = (cv.y + nv.y) / 2;\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n insertedIdx++;\n continue;\n }\n\n const rotDeg = (di ? bleedDirDeg : -bleedDirDeg) + rr(-1, 1) * 5;\n const c = cos(rotDeg);\n const s = sin(rotDeg);\n\n const sideX = nv.x - cv.x;\n const sideY = nv.y - cv.y;\n const dirX = c * sideX + s * sideY;\n const dirY = c * sideY - s * sideX;\n\n const d = gPool[~~(rr(0, 1) * gPoolLen)] * rr(0.65, 1.35) * mod;\n const nextMod = mi + g2Pool[~~(rr(0, 1) * g2PoolLen)];\n\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n\n insertedX[insertedIdx] = cv.x + sideX * 0.5 + dirX * d;\n insertedY[insertedIdx] = cv.y + sideY * 0.5 + dirY * d;\n newMods[idx] = nextMod;\n newDirs[idx] = di;\n idx++;\n insertedIdx++;\n }\n\n let fv,\n fm,\n fd;\n \n if (GROW_CAP && idx > GROW_CAP) {\n const step = Math.ceil(idx / GROW_CAP);\n const kept = Math.ceil(idx / step);\n fv = new Array(kept);\n fm = new Array(kept);\n fd = new Array(kept);\n let dst = 0;\n for (let j = 0; j < idx; j += step, dst++) {\n fv[dst] =\n j % 2 === 0\n ? tr_v[j >> 1]\n : { x: insertedX[j >> 1], y: insertedY[j >> 1] };\n fm[dst] = newMods[j];\n fd[dst] = newDirs[j];\n }\n } else {\n fv = new Array(idx);\n for (let j = 0; j < idx; j++) {\n fv[j] =\n j % 2 === 0\n ? tr_v[j >> 1]\n : { x: insertedX[j >> 1], y: insertedY[j >> 1] };\n }\n fm = newMods.slice(0, idx);\n fd = newDirs.slice(0, idx);\n }\n return new FillPoly(fv, fm, this.midP, fd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Fills the polygon with multiple layers to simulate a watercolor effect.\n * @param {Color|string} color - The fill color.\n * @param {number} intensity - Opacity intensity (mapped from 0 to 1).\n * @param {number} tex - Texture factor.\n */\n fill(color, intensity, tex) {\n const numLayers = 20;\n const texture = tex * 3;\n const int = 2 * intensity * (1 + tex / 2);\n\n const switchingToFill = Mix.isBrush !== false;\n Mix.isBrush = false;\n if (switchingToFill) Mix.justChanged = true;\n Mix.blend(color);\n\n const m = getAffineMatrix();\n Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * m.a,\n Density * m.b,\n Density * m.c,\n Density * m.d,\n Density * (m.x + Cwidth / 2),\n Density * (m.y + Cheight / 2),\n );\n\n Mix.ctx.strokeStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${\n 0.005 * State.fill.border_strength\n })`;\n Mix.ctx.lineCap = \"round\";\n\n GROW_CAP = GROW_MAX_VERTS * Math.max(0.1, 2 * State.fill.bleed_strength);\n\n const size = Math.max(this.sizeX, this.sizeY);\n const darker = rr(0.15, 0.7);\n let pol = this.grow();\n const sparse = this.scatter(0.1).grow().scatter(0.75).flipDirs();\n let pols;\n\n for (let i = 0; i < numLayers; i++) {\n if (i % 4 === 0) {\n pol = pol.grow();\n }\n\n if (i % 2 === 0) {\n pols = [\n pol.grow(1 - 0.0125 * i),\n pol.grow(0.7 - 0.0125 * i),\n pol.grow(0.4 - 0.0125 * i),\n ];\n }\n\n for (const p of pols) {\n const grown = p.grow(999).grow(997);\n grown.layer(i, size, int, color);\n }\n const sparseLayer = sparse.grow(999).flipDirs().grow(997);\n sparseLayer.layer(i, size, int * texture, color);\n if (i % 2 === 0) {\n const darkerLayer = pol.grow(darker).grow(999);\n darkerLayer.layer(i, size, int * 2, color);\n }\n\n if (i % 8 === 0 || i === numLayers - 1) {\n if (texture !== 0) {\n pol.erase(texture * 3, intensity);\n }\n Mix.blend(color, true);\n }\n }\n\n Mix.ctx.restore();\n }\n\n /**\n * Draws a layer of the fill polygon with stroke and fill.\n * @param {number} i - The layer index.\n */\n layer(i, size, int, color) {\n Mix.ctx.lineWidth = map(i, 0, 24, size / 25, size / 30, true);\n\n Mix.ctx.fillStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${int}%)`;\n\n drawPolygon(this.v);\n Mix.ctx.fill();\n Mix.ctx.stroke();\n }\n\n /**\n * Erases parts of the polygon to create a natural watercolor texture.\n * @param {number} texture - Texture strength factor.\n * @param {number} intensity - Intensity value for size scaling.\n */\n erase(texture, intensity) {\n Mix.ctx.save();\n\n const numCircles = ~~(rr(80, 110) * map(texture, 0, 1, 2, 3.5));\n const halfSizeX = this.sizeX / 1.3;\n const halfSizeY = this.sizeY / 1.3;\n const minSize =\n Math.min(this.sizeX, this.sizeY) * (1.3);\n const minSizeFactor = 0.03 * minSize;\n const maxSizeFactor = 0.45 * minSize;\n const { x: midX, y: midY } = this.midP;\n\n Mix.ctx.globalCompositeOperation = \"destination-out\";\n\n const alpha =\n ((5 - map(intensity, 80, 100, 0.3, 0.7, true)) * texture) / 255;\n Mix.ctx.fillStyle = `rgb(255 0 0 / ${alpha})`;\n Mix.ctx.lineWidth = 0;\n\n for (let i = 0; i < numCircles; i++) {\n const x = midX + gaussian(0, halfSizeX);\n const y = midY + gaussian(0, halfSizeY);\n const radius = rr(minSizeFactor, maxSizeFactor);\n\n Mix.ctx.beginPath();\n circle(x, y, radius);\n if (i % 5 !== 0) {\n Mix.ctx.fill();\n }\n }\n\n Mix.ctx.globalCompositeOperation = \"source-over\";\n Mix.ctx.restore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Extend Polygon and Plot Prototypes for Fill\n// ---------------------------------------------------------------------------\n\n/**\n * Applies a fill effect to the polygon using the current fill state.\n * @param {Color|string} [_color] - The color for the fill.\n * @param {number} [_opacity] - The opacity value.\n * @param {number} [_bleed] - The bleed intensity.\n * @param {number} [_texture] - The texture strength.\n * @param {number} [_border] - The border strength.\n * @param {string} [_direction] - The bleed direction.\n */\nPolygon.prototype.fill = function (\n _color = false,\n _opacity,\n _bleed,\n _texture,\n _border,\n _direction,\n) {\n let state = FillState();\n if (_color) {\n fill(_color, _opacity);\n fillBleed(_bleed, _direction);\n fillTexture(_texture, _border);\n }\n if (state.isActive) {\n isFieldReady();\n createFill(this);\n }\n FillSetState(state);\n};\n\n/**\n * Fills a plot on the canvas by generating a polygon based on the provided coordinates.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - Scaling factor.\n */\nPlot.prototype.fill = function (x, y, scale) {\n if (FillState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n this.pol = this.genPol(\n x,\n y,\n scale,\n State.fill.bleed_strength < 0.06\n ? 0\n : map(State.fill.bleed_strength, 0, 0.6, 0.2, 0.60, true),\n );\n this.pol.fill();\n }\n};\n","\nexport default function earcut(data, holeIndices, dim = 2) {\n\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n let outerNode = linkedList(data, 0, outerLen, dim, true);\n const triangles = [];\n\n if (!outerNode || outerNode.next === outerNode.prev) return triangles;\n\n let minX, minY, invSize;\n\n if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);\n\n // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox\n if (data.length > 80 * dim) {\n minX = data[0];\n minY = data[1];\n let maxX = minX;\n let maxY = minY;\n\n for (let i = dim; i < outerLen; i += dim) {\n const x = data[i];\n const y = data[i + 1];\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n\n // minX, minY and invSize are later used to transform coords into integers for z-order calculation\n invSize = Math.max(maxX - minX, maxY - minY);\n invSize = invSize !== 0 ? 32767 / invSize : 0;\n }\n\n earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);\n\n return triangles;\n}\n\n// create a circular doubly linked list from polygon points in the specified winding order\nfunction linkedList(data, start, end, dim, clockwise) {\n let last;\n\n if (clockwise === (signedArea(data, start, end, dim) > 0)) {\n for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n } else {\n for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n }\n\n if (last && equals(last, last.next)) {\n removeNode(last);\n last = last.next;\n }\n\n return last;\n}\n\n// eliminate colinear or duplicate points\nfunction filterPoints(start, end) {\n if (!start) return start;\n if (!end) end = start;\n\n let p = start,\n again;\n do {\n again = false;\n\n if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {\n removeNode(p);\n p = end = p.prev;\n if (p === p.next) break;\n again = true;\n\n } else {\n p = p.next;\n }\n } while (again || p !== end);\n\n return end;\n}\n\n// main ear slicing loop which triangulates a polygon (given as a linked list)\nfunction earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {\n if (!ear) return;\n\n // interlink polygon nodes in z-order\n if (!pass && invSize) indexCurve(ear, minX, minY, invSize);\n\n let stop = ear;\n\n // iterate through ears, slicing them one by one\n while (ear.prev !== ear.next) {\n const prev = ear.prev;\n const next = ear.next;\n\n if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {\n triangles.push(prev.i, ear.i, next.i); // cut off the triangle\n\n removeNode(ear);\n\n // skipping the next vertex leads to less sliver triangles\n ear = next.next;\n stop = next.next;\n\n continue;\n }\n\n ear = next;\n\n // if we looped through the whole remaining polygon and can't find any more ears\n if (ear === stop) {\n // try filtering points and slicing again\n if (!pass) {\n earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);\n\n // if this didn't work, try curing all small self-intersections locally\n } else if (pass === 1) {\n ear = cureLocalIntersections(filterPoints(ear), triangles);\n earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);\n\n // as a last resort, try splitting the remaining polygon into two\n } else if (pass === 2) {\n splitEarcut(ear, triangles, dim, minX, minY, invSize);\n }\n\n break;\n }\n }\n}\n\n// check whether a polygon node forms a valid ear with adjacent nodes\nfunction isEar(ear) {\n const a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n // now make sure we don't have other points inside the potential ear\n const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox\n const x0 = Math.min(ax, bx, cx),\n y0 = Math.min(ay, by, cy),\n x1 = Math.max(ax, bx, cx),\n y1 = Math.max(ay, by, cy);\n\n let p = c.next;\n while (p !== a) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&\n area(p.prev, p, p.next) >= 0) return false;\n p = p.next;\n }\n\n return true;\n}\n\nfunction isEarHashed(ear, minX, minY, invSize) {\n const a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox\n const x0 = Math.min(ax, bx, cx),\n y0 = Math.min(ay, by, cy),\n x1 = Math.max(ax, bx, cx),\n y1 = Math.max(ay, by, cy);\n\n // z-order range for the current triangle bbox;\n const minZ = zOrder(x0, y0, minX, minY, invSize),\n maxZ = zOrder(x1, y1, minX, minY, invSize);\n\n let p = ear.prevZ,\n n = ear.nextZ;\n\n // look for points inside the triangle in both directions\n while (p && p.z >= minZ && n && n.z <= maxZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n // look for remaining points in decreasing z-order\n while (p && p.z >= minZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n }\n\n // look for remaining points in increasing z-order\n while (n && n.z <= maxZ) {\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n return true;\n}\n\n// go through all polygon nodes and cure small local self-intersections\nfunction cureLocalIntersections(start, triangles) {\n let p = start;\n do {\n const a = p.prev,\n b = p.next.next;\n\n if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {\n\n triangles.push(a.i, p.i, b.i);\n\n // remove two nodes involved\n removeNode(p);\n removeNode(p.next);\n\n p = start = b;\n }\n p = p.next;\n } while (p !== start);\n\n return filterPoints(p);\n}\n\n// try splitting polygon into two and triangulate them independently\nfunction splitEarcut(start, triangles, dim, minX, minY, invSize) {\n // look for a valid diagonal that divides the polygon into two\n let a = start;\n do {\n let b = a.next.next;\n while (b !== a.prev) {\n if (a.i !== b.i && isValidDiagonal(a, b)) {\n // split the polygon in two by the diagonal\n let c = splitPolygon(a, b);\n\n // filter colinear points around the cuts\n a = filterPoints(a, a.next);\n c = filterPoints(c, c.next);\n\n // run earcut on each half\n earcutLinked(a, triangles, dim, minX, minY, invSize, 0);\n earcutLinked(c, triangles, dim, minX, minY, invSize, 0);\n return;\n }\n b = b.next;\n }\n a = a.next;\n } while (a !== start);\n}\n\n// link every hole into the outer loop, producing a single-ring polygon without holes\nfunction eliminateHoles(data, holeIndices, outerNode, dim) {\n const queue = [];\n\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n const list = linkedList(data, start, end, dim, false);\n if (list === list.next) list.steiner = true;\n queue.push(getLeftmost(list));\n }\n\n queue.sort(compareXYSlope);\n\n // process holes from left to right\n for (let i = 0; i < queue.length; i++) {\n outerNode = eliminateHole(queue[i], outerNode);\n }\n\n return outerNode;\n}\n\nfunction compareXYSlope(a, b) {\n let result = a.x - b.x;\n // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find\n // the bridge to the outer shell is always the point that they meet at.\n if (result === 0) {\n result = a.y - b.y;\n if (result === 0) {\n const aSlope = (a.next.y - a.y) / (a.next.x - a.x);\n const bSlope = (b.next.y - b.y) / (b.next.x - b.x);\n result = aSlope - bSlope;\n }\n }\n return result;\n}\n\n// find a bridge between vertices that connects hole with an outer ring and link it\nfunction eliminateHole(hole, outerNode) {\n const bridge = findHoleBridge(hole, outerNode);\n if (!bridge) {\n return outerNode;\n }\n\n const bridgeReverse = splitPolygon(bridge, hole);\n\n // filter collinear points around the cuts\n filterPoints(bridgeReverse, bridgeReverse.next);\n return filterPoints(bridge, bridge.next);\n}\n\n// David Eberly's algorithm for finding a bridge between hole and outer polygon\nfunction findHoleBridge(hole, outerNode) {\n let p = outerNode;\n const hx = hole.x;\n const hy = hole.y;\n let qx = -Infinity;\n let m;\n\n // find a segment intersected by a ray from the hole's leftmost point to the left;\n // segment's endpoint with lesser x will be potential connection point\n // unless they intersect at a vertex, then choose the vertex\n if (equals(hole, p)) return p;\n do {\n if (equals(hole, p.next)) return p.next;\n else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {\n const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);\n if (x <= hx && x > qx) {\n qx = x;\n m = p.x < p.next.x ? p : p.next;\n if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint\n }\n }\n p = p.next;\n } while (p !== outerNode);\n\n if (!m) return null;\n\n // look for points inside the triangle of hole point, segment intersection and endpoint;\n // if there are no points found, we have a valid connection;\n // otherwise choose the point of the minimum angle with the ray as connection point\n\n const stop = m;\n const mx = m.x;\n const my = m.y;\n let tanMin = Infinity;\n\n p = m;\n\n do {\n if (hx >= p.x && p.x >= mx && hx !== p.x &&\n pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {\n\n const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential\n\n if (locallyInside(p, hole) &&\n (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {\n m = p;\n tanMin = tan;\n }\n }\n\n p = p.next;\n } while (p !== stop);\n\n return m;\n}\n\n// whether sector in vertex m contains sector in vertex p in the same coordinates\nfunction sectorContainsSector(m, p) {\n return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;\n}\n\n// interlink polygon nodes in z-order\nfunction indexCurve(start, minX, minY, invSize) {\n let p = start;\n do {\n if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);\n p.prevZ = p.prev;\n p.nextZ = p.next;\n p = p.next;\n } while (p !== start);\n\n p.prevZ.nextZ = null;\n p.prevZ = null;\n\n sortLinked(p);\n}\n\n// Simon Tatham's linked list merge sort algorithm\n// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html\nfunction sortLinked(list) {\n let numMerges;\n let inSize = 1;\n\n do {\n let p = list;\n let e;\n list = null;\n let tail = null;\n numMerges = 0;\n\n while (p) {\n numMerges++;\n let q = p;\n let pSize = 0;\n for (let i = 0; i < inSize; i++) {\n pSize++;\n q = q.nextZ;\n if (!q) break;\n }\n let qSize = inSize;\n\n while (pSize > 0 || (qSize > 0 && q)) {\n\n if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {\n e = p;\n p = p.nextZ;\n pSize--;\n } else {\n e = q;\n q = q.nextZ;\n qSize--;\n }\n\n if (tail) tail.nextZ = e;\n else list = e;\n\n e.prevZ = tail;\n tail = e;\n }\n\n p = q;\n }\n\n tail.nextZ = null;\n inSize *= 2;\n\n } while (numMerges > 1);\n\n return list;\n}\n\n// z-order of a point given coords and inverse of the longer side of data bbox\nfunction zOrder(x, y, minX, minY, invSize) {\n // coords are transformed into non-negative 15-bit integer range\n x = (x - minX) * invSize | 0;\n y = (y - minY) * invSize | 0;\n\n x = (x | (x << 8)) & 0x00FF00FF;\n x = (x | (x << 4)) & 0x0F0F0F0F;\n x = (x | (x << 2)) & 0x33333333;\n x = (x | (x << 1)) & 0x55555555;\n\n y = (y | (y << 8)) & 0x00FF00FF;\n y = (y | (y << 4)) & 0x0F0F0F0F;\n y = (y | (y << 2)) & 0x33333333;\n y = (y | (y << 1)) & 0x55555555;\n\n return x | (y << 1);\n}\n\n// find the leftmost node of a polygon ring\nfunction getLeftmost(start) {\n let p = start,\n leftmost = start;\n do {\n if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;\n p = p.next;\n } while (p !== start);\n\n return leftmost;\n}\n\n// check if a point lies within a convex triangle\nfunction pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {\n return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&\n (ax - px) * (by - py) >= (bx - px) * (ay - py) &&\n (bx - px) * (cy - py) >= (cx - px) * (by - py);\n}\n\n// check if a point lies within a convex triangle but false if its equal to the first point of the triangle\nfunction pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {\n return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);\n}\n\n// check if a diagonal between two polygon nodes is valid (lies in polygon interior)\nfunction isValidDiagonal(a, b) {\n return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges\n (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible\n (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors\n equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case\n}\n\n// signed area of a triangle\nfunction area(p, q, r) {\n return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);\n}\n\n// check if two points are equal\nfunction equals(p1, p2) {\n return p1.x === p2.x && p1.y === p2.y;\n}\n\n// check if two segments intersect\nfunction intersects(p1, q1, p2, q2) {\n const o1 = sign(area(p1, q1, p2));\n const o2 = sign(area(p1, q1, q2));\n const o3 = sign(area(p2, q2, p1));\n const o4 = sign(area(p2, q2, q1));\n\n if (o1 !== o2 && o3 !== o4) return true; // general case\n\n if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1\n if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1\n if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2\n if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2\n\n return false;\n}\n\n// for collinear points p, q, r, check if point q lies on segment pr\nfunction onSegment(p, q, r) {\n return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);\n}\n\nfunction sign(num) {\n return num > 0 ? 1 : num < 0 ? -1 : 0;\n}\n\n// check if a polygon diagonal intersects any polygon segments\nfunction intersectsPolygon(a, b) {\n let p = a;\n do {\n if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&\n intersects(p, p.next, a, b)) return true;\n p = p.next;\n } while (p !== a);\n\n return false;\n}\n\n// check if a polygon diagonal is locally inside the polygon\nfunction locallyInside(a, b) {\n return area(a.prev, a, a.next) < 0 ?\n area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :\n area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;\n}\n\n// check if the middle point of a polygon diagonal is inside the polygon\nfunction middleInside(a, b) {\n let p = a;\n let inside = false;\n const px = (a.x + b.x) / 2;\n const py = (a.y + b.y) / 2;\n do {\n if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&\n (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))\n inside = !inside;\n p = p.next;\n } while (p !== a);\n\n return inside;\n}\n\n// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;\n// if one belongs to the outer ring and another to a hole, it merges it into a single ring\nfunction splitPolygon(a, b) {\n const a2 = createNode(a.i, a.x, a.y),\n b2 = createNode(b.i, b.x, b.y),\n an = a.next,\n bp = b.prev;\n\n a.next = b;\n b.prev = a;\n\n a2.next = an;\n an.prev = a2;\n\n b2.next = a2;\n a2.prev = b2;\n\n bp.next = b2;\n b2.prev = bp;\n\n return b2;\n}\n\n// create a node and optionally link it with previous one (in a circular doubly linked list)\nfunction insertNode(i, x, y, last) {\n const p = createNode(i, x, y);\n\n if (!last) {\n p.prev = p;\n p.next = p;\n\n } else {\n p.next = last.next;\n p.prev = last;\n last.next.prev = p;\n last.next = p;\n }\n return p;\n}\n\nfunction removeNode(p) {\n p.next.prev = p.prev;\n p.prev.next = p.next;\n\n if (p.prevZ) p.prevZ.nextZ = p.nextZ;\n if (p.nextZ) p.nextZ.prevZ = p.prevZ;\n}\n\nfunction createNode(i, x, y) {\n return {\n i, // vertex index in coordinates array\n x, y, // vertex coordinates\n prev: null, // previous and next vertex nodes in a polygon ring\n next: null,\n z: 0, // z-order curve value\n prevZ: null, // previous and next nodes in z-order\n nextZ: null,\n steiner: false // indicates whether this is a steiner point\n };\n}\n\n// return a percentage difference between the polygon area and its triangulation area;\n// used to verify correctness of triangulation\nexport function deviation(data, holeIndices, dim, triangles) {\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n\n let polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));\n if (hasHoles) {\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n polygonArea -= Math.abs(signedArea(data, start, end, dim));\n }\n }\n\n let trianglesArea = 0;\n for (let i = 0; i < triangles.length; i += 3) {\n const a = triangles[i] * dim;\n const b = triangles[i + 1] * dim;\n const c = triangles[i + 2] * dim;\n trianglesArea += Math.abs(\n (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -\n (data[a] - data[b]) * (data[c + 1] - data[a + 1]));\n }\n\n return polygonArea === 0 && trianglesArea === 0 ? 0 :\n Math.abs((trianglesArea - polygonArea) / polygonArea);\n}\n\nfunction signedArea(data, start, end, dim) {\n let sum = 0;\n for (let i = start, j = end - dim; i < end; i += dim) {\n sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);\n j = i;\n }\n return sum;\n}\n\n// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts\nexport function flatten(data) {\n const vertices = [];\n const holes = [];\n const dimensions = data[0][0].length;\n let holeIndex = 0;\n let prevLen = 0;\n\n for (const ring of data) {\n for (const p of ring) {\n for (let d = 0; d < dimensions; d++) vertices.push(p[d]);\n }\n if (prevLen) {\n holeIndex += prevLen;\n holes.push(holeIndex);\n }\n prevLen = ring.length;\n }\n return {vertices, holes, dimensions};\n}\n","// =============================================================================\n// Module: Wash\n// =============================================================================\n/**\n * Minimal stateful API for the `wash()` fill modifier.\n */\n\nimport earcut from \"earcut\";\nimport { Renderer, Cwidth, Cheight, isCanvasReady } from \"../core/target.js\";\nimport { State, flushActiveComposite } from \"../core/color.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { getAffineMatrix } from \"../core/runtime.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport { createColor } from \"../core/runtime.js\";\nimport { resetDirectShaderTracking } from \"../core/renderer_runtime.js\";\n\nlet gl = null;\nlet washProgram = null;\nlet washVao = null;\nlet washBuffer = null;\nlet washProjection = null;\nlet loadedWidth = 0;\nlet loadedHeight = 0;\nlet washGpuBufferSize = 0;\n\nconst WashAttr = {};\nconst WashUniform = {};\n\nconst washVertSrc = `#version 300 es\nin vec2 a_position;\nuniform mat4 u_matrix;\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n}`;\n\nconst washFragSrc = `#version 300 es\nprecision highp float;\nuniform vec4 u_color;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(u_color.rgb * u_color.a, u_color.a);\n}`;\n\nState.wash = {\n color: null,\n opacity: 150,\n isActive: false,\n};\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Enables wash mode with a color and opacity.\n *\n * @param {number|string|Color} a - Either the red component, a CSS color string, or a Color object.\n * @param {number} [b] - The green component or the opacity if using grayscale.\n * @param {number} [c] - The blue component.\n * @param {number} [d] - The opacity.\n */\nexport function wash(a, b, c, d) {\n isCanvasReady();\n State.wash.opacity = (arguments.length < 4 ? b : d) ?? 150;\n State.wash.color = arguments.length < 3 ? createColor(a) : createColor(a, b, c);\n State.wash.isActive = true;\n}\n\n/**\n * Disables wash mode for subsequent drawing operations.\n */\nexport function noWash() {\n State.wash.isActive = false;\n}\n\n// =============================================================================\n// GL helpers\n// =============================================================================\n\n/**\n * Lazily creates the reusable program/buffer state for solid wash drawing and\n * refreshes the orthographic projection when the active target size changes.\n */\nfunction ensureWashReady() {\n const nextGl = Renderer.drawingContext;\n const sizeChanged = loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (!washProjection || sizeChanged) {\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n washProjection = new Float32Array([\n 2 / loadedWidth,\n 0,\n 0,\n 0,\n 0,\n -2 / loadedHeight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n 1,\n 0,\n 1,\n ]);\n }\n\n if (gl === nextGl && washProgram && washVao && washBuffer) return;\n\n gl = nextGl;\n washProgram = createProgram(gl, washVertSrc, washFragSrc);\n WashAttr.a_position = gl.getAttribLocation(washProgram, \"a_position\");\n WashUniform.u_matrix = gl.getUniformLocation(washProgram, \"u_matrix\");\n WashUniform.u_color = gl.getUniformLocation(washProgram, \"u_color\");\n\n washVao = gl.createVertexArray();\n gl.bindVertexArray(washVao);\n\n washBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, 0, gl.DYNAMIC_DRAW);\n washGpuBufferSize = 0;\n\n gl.enableVertexAttribArray(WashAttr.a_position);\n gl.vertexAttribPointer(WashAttr.a_position, 2, gl.FLOAT, false, 8, 0);\n\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n}\n\n/**\n * Applies the current runtime affine transform and converts the result into\n * the screen-space coordinates used by the direct GL wash pipeline.\n *\n * @param {number} x - The source x-coordinate in brush drawing space.\n * @param {number} y - The source y-coordinate in brush drawing space.\n * @returns {[number, number]} The transformed screen-space position.\n */\nfunction transformVertexToScreen(x, y) {\n const m = getAffineMatrix();\n return [\n m.a * x + m.c * y + m.x + loadedWidth / 2,\n m.b * x + m.d * y + m.y + loadedHeight / 2,\n ];\n}\n\n/**\n * Triangulates a polygon in local space and returns the transformed triangle\n * vertex buffer ready for upload to the GPU.\n *\n * @param {Polygon} polygon - The polygon to triangulate.\n * @returns {{ triangles: Float32Array, vertexCount: number }} Screen-space\n * triangle vertices plus the number of vertices to draw.\n */\nfunction buildTriangleBuffer(polygon) {\n const flat = new Float32Array(polygon.vertices.length * 2);\n for (let i = 0; i < polygon.vertices.length; i++) {\n const vertex = polygon.vertices[i];\n flat[i * 2] = vertex.x;\n flat[i * 2 + 1] = vertex.y;\n }\n\n const indices = earcut(flat);\n const triangles = new Float32Array(indices.length * 2);\n for (let i = 0; i < indices.length; i++) {\n const idx = indices[i];\n const [screenX, screenY] = transformVertexToScreen(flat[idx * 2], flat[idx * 2 + 1]);\n triangles[i * 2] = screenX;\n triangles[i * 2 + 1] = screenY;\n }\n\n return {\n triangles,\n vertexCount: indices.length,\n };\n}\n\n/**\n * Draws a triangulated solid wash directly to the current GL target.\n *\n * @param {Polygon} polygon - The polygon to fill with the current wash state.\n */\nfunction drawWashPolygon(polygon) {\n if (!State.wash?.isActive || !State.wash.color || polygon.vertices.length < 3) return;\n\n flushActiveComposite();\n ensureWashReady();\n const { triangles, vertexCount } = buildTriangleBuffer(polygon);\n const byteCount = triangles.byteLength;\n gl.useProgram(washProgram);\n gl.enable(gl.BLEND);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n gl.bindVertexArray(washVao);\n gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);\n if (byteCount > washGpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, triangles, gl.DYNAMIC_DRAW);\n washGpuBufferSize = byteCount;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, triangles);\n }\n const color = State.wash.color._array;\n gl.uniformMatrix4fv(WashUniform.u_matrix, false, washProjection);\n gl.uniform4f(\n WashUniform.u_color,\n color[0],\n color[1],\n color[2],\n State.wash.opacity / 255,\n );\n\n gl.drawArrays(gl.TRIANGLES, 0, vertexCount);\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n resetDirectShaderTracking(Renderer, gl);\n}\n\n// =============================================================================\n// Prototype methods\n// =============================================================================\n\n/**\n * Applies a direct GL wash fill to the polygon using the current wash state.\n *\n * @param {Color|string|false} [_color] - Optional override color for this call.\n * @param {number} [_opacity] - Optional override opacity for this call.\n */\nPolygon.prototype.wash = function (_color = false, _opacity) {\n const state = { ...State.wash };\n if (_color !== false) wash(_color, _opacity);\n\n if (State.wash.isActive) {\n drawWashPolygon(this);\n }\n\n State.wash = { ...state };\n};\n\n/**\n * Applies wash to a plot by first generating the plot polygon, mirroring the\n * existing fill-path behavior, and then drawing that polygon with wash.\n *\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\nPlot.prototype.wash = function (x, y, scale) {\n if (!State.wash?.isActive) return;\n if (this.origin) {\n x = this.origin[0];\n y = this.origin[1];\n scale = 1;\n }\n this.pol = this.genPol(x, y, scale, 0, -1);\n this.pol.wash();\n};\n","// =============================================================================\n// Adapter: p5 Runtime Target Resolution\n// =============================================================================\n/**\n * Owns the active renderer/instance selection used by p5.brush when running\n * on top of p5's WEBGL renderer.\n */\n\nimport {\n setTargetRuntime,\n setTargetState,\n Instance,\n Renderer,\n} from \"../../core/target.js\";\n\nlet ReadySketch = null;\nlet ActiveInstance = null;\nconst ActiveInstanceStack = [];\nlet _isReady = false;\n\n/**\n * Checks whether the given draw target is a p5.Framebuffer-like object.\n * @param {*} target - Candidate draw target.\n * @returns {boolean} True when the target behaves like a p5.Framebuffer.\n */\nexport const isFramebufferTarget = (target) =>\n !!target &&\n typeof target.begin === \"function\" &&\n typeof target.end === \"function\" &&\n !!target.renderer &&\n !!target.renderer._pInst;\n\nconst isFiniteSize = (value) =>\n typeof value === \"number\" && Number.isFinite(value) && value > 0;\n\nconst safeRead = (getter) => {\n try {\n return getter();\n } catch (_error) {\n return undefined;\n }\n};\n\nconst isReadyWebGLSketch = (candidate) =>\n !!candidate &&\n typeof candidate.pixelDensity === \"function\" &&\n typeof candidate.createFramebuffer === \"function\" &&\n isFiniteSize(safeRead(() => candidate.width)) &&\n isFiniteSize(safeRead(() => candidate.height)) &&\n safeRead(() => candidate.webglVersion) === \"webgl2\";\n\nconst getCurrentP5Instance = () => window.self?.p5?.instance ?? null;\n\nconst rememberReadySketch = (candidate) => {\n if (isReadyWebGLSketch(candidate)) ReadySketch = candidate;\n return ReadySketch;\n};\n\nconst getActiveSketchRenderer = () => {\n if (!ActiveInstance) return null;\n if (!isReadyWebGLSketch(ActiveInstance)) return null;\n return rememberReadySketch(ActiveInstance);\n};\n\n/**\n * Resolves the sketch renderer that owns the current drawing session.\n * Preference order:\n * 1. the sketch currently executing a p5 lifecycle callback\n * 2. the explicitly selected instance from brush.instance(p), if ready\n * 3. the last known-good ready sketch\n * @returns {p5|Window[\"p5\"][\"instance\"]|null} The active sketch renderer.\n */\nexport const getSketchRenderer = () =>\n getActiveSketchRenderer() ||\n rememberReadySketch(getCurrentP5Instance()) ||\n rememberReadySketch(Instance) ||\n ReadySketch;\n\n/**\n * Resolves the renderer and pixel size used by `brush.load()`.\n * @param {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional draw target.\n * @returns {{renderer: object, width: number, height: number}} Active renderer info.\n */\nconst resolveTarget = (buffer = false) => {\n const sketchRenderer = getSketchRenderer();\n\n if (!buffer) {\n if (!sketchRenderer) {\n throw new Error(\n \"p5.brush could not resolve an active WEBGL sketch. Call brush.instance(p) and brush.load() after createCanvas(..., WEBGL).\",\n );\n }\n return {\n renderer: sketchRenderer,\n width: sketchRenderer.width,\n height: sketchRenderer.height,\n };\n }\n\n if (isFramebufferTarget(buffer)) {\n const owner = buffer.renderer._pInst;\n rememberReadySketch(owner);\n\n if (sketchRenderer && owner !== sketchRenderer) {\n throw new Error(\n \"p5.brush only supports p5.Framebuffer targets created from the active sketch\",\n );\n }\n\n return {\n renderer: owner,\n width: buffer.width,\n height: buffer.height,\n };\n }\n\n return {\n renderer: buffer,\n width: buffer.width,\n height: buffer.height,\n };\n};\n\n/**\n * Returns the currently bound sketch framebuffer when drawing into one.\n * @returns {p5.Framebuffer|null} Active framebuffer or null.\n */\nexport const getActiveFramebuffer = () =>\n Renderer?._renderer?.activeFramebuffer?.() ?? null;\n\n/**\n * Loads and initializes a canvas for the drawing system.\n * @param {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional offscreen target.\n * Pass a framebuffer only while drawing inside its begin()/end() or draw() scope.\n * Framebuffers created from p5.Graphics are not supported.\n */\nexport const load = (buffer = false) => {\n const target = resolveTarget(buffer);\n setTargetState({ Renderer: target.renderer });\n rememberReadySketch(!buffer ? Renderer : getSketchRenderer());\n\n if (Renderer.webglVersion !== \"webgl2\") {\n throw new Error(\"p5.brush requires a WEBGL canvas\");\n }\n\n setTargetState({\n Cwidth: target.width,\n Cheight: target.height,\n });\n\n _isReady = true;\n};\n\n/**\n * Refreshes the stored pixel density for the active renderer.\n * @returns {number} Current renderer pixel density.\n */\nexport const syncDensity = () => {\n const density = Renderer.pixelDensity();\n setTargetState({ Density: density });\n return density;\n};\n\n/**\n * Ensures the drawing system is ready before any operation.\n */\nexport const isCanvasReady = () => {\n if (!_isReady) load();\n};\n\nexport const instance = (inst) => {\n setTargetState({ Instance: inst });\n rememberReadySketch(inst);\n};\n\nexport const activateInstance = (inst) => {\n ActiveInstanceStack.push(ActiveInstance);\n ActiveInstance = inst;\n instance(inst);\n};\n\nexport const deactivateInstance = () => {\n ActiveInstance = ActiveInstanceStack.pop() ?? null;\n};\n\nexport function initP5TargetRuntime() {\n setTargetRuntime({\n load,\n syncDensity,\n isCanvasReady,\n instance,\n activateInstance,\n deactivateInstance,\n getActiveFramebuffer,\n isFramebufferTarget,\n });\n}\n","// =============================================================================\n// Adapter: p5 Runtime Hooks\n// =============================================================================\n\nimport { setRuntime } from \"../../core/runtime.js\";\nimport { Renderer } from \"../../core/target.js\";\nimport { getSketchRenderer } from \"./target.js\";\n\nconst getP5RuntimeRenderer = () =>\n Renderer ?? getSketchRenderer?.() ?? window.self?.p5?.instance ?? null;\nconst identityMatrix = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\nconst affineMatrix = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\n\nfunction isRadians() {\n const renderer = getP5RuntimeRenderer();\n return !!renderer &&\n typeof renderer.angleMode === \"function\" &&\n renderer.angleMode() === renderer.RADIANS;\n}\n\nexport function initP5Runtime() {\n setRuntime({\n usesRadians: isRadians,\n\n fromDegrees: (angle) =>\n isRadians() ? (angle * Math.PI) / 180 : angle,\n\n createColor: (...args) => {\n const renderer = getP5RuntimeRenderer();\n if (!renderer?.color) {\n throw new Error(\"p5 runtime color creation requires an active renderer.\");\n }\n return renderer.color(...args);\n },\n\n getAffineMatrix: () => {\n const renderer = getP5RuntimeRenderer();\n const mat4 = renderer?._renderer?.uModelMatrix?.mat4;\n if (!mat4) return identityMatrix;\n\n affineMatrix.a = mat4[0];\n affineMatrix.b = mat4[1];\n affineMatrix.c = mat4[4];\n affineMatrix.d = mat4[5];\n affineMatrix.x = mat4[12];\n affineMatrix.y = mat4[13];\n return affineMatrix;\n },\n });\n}\n","// =============================================================================\n// Adapter: p5 Renderer Hooks\n// =============================================================================\n\nimport { setRendererRuntime } from \"../../core/renderer_runtime.js\";\n\nfunction getFramebufferHandle(target) {\n if (!target) return null;\n if (typeof target._framebufferToBind === \"function\") return target._framebufferToBind();\n return target.framebuffer ?? null;\n}\n\nfunction beginDirectMaskDraw(renderer, gl, target) {\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n if (hadDepthTest) gl.disable(gl.DEPTH_TEST);\n\n const previousTarget = renderer._renderer.activeFramebuffer?.() ?? null;\n if (previousTarget?._beforeEnd) previousTarget._beforeEnd();\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, getFramebufferHandle(target));\n gl.viewport(0, 0, target.width * target.density, target.height * target.density);\n\n return { hadDepthTest, previousTarget };\n}\n\nfunction endDirectMaskDraw(renderer, gl, state) {\n if (state?.hadDepthTest) gl.enable(gl.DEPTH_TEST);\n\n if (state?.previousTarget?._beforeBegin) {\n state.previousTarget._beforeBegin();\n return;\n }\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n renderer._renderer.viewport(\n renderer._renderer._origViewport.width,\n renderer._renderer._origViewport.height,\n );\n renderer._renderer._applyStencilTestIfClipping?.();\n}\n\nfunction resetP5ShaderTracking(renderer, gl) {\n const coreRenderer = renderer?._renderer;\n if (!coreRenderer) return;\n coreRenderer._curShader = null;\n coreRenderer._cachedBlendMode = null;\n coreRenderer._isBlending = null;\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n}\n\nexport function initP5RendererRuntime() {\n setRendererRuntime({\n beginDirectMaskDraw,\n endDirectMaskDraw,\n resetDirectShaderTracking: resetP5ShaderTracking,\n });\n}\n","// =============================================================================\n// Adapter: p5 Compositor Hooks\n// =============================================================================\n\nimport {\n setCompositorRuntime,\n blitDefaultFramebufferSource,\n} from \"../../core/compositor_runtime.js\";\n\nfunction clearTarget(renderer, target, isFramebufferTarget) {\n if (!target) return;\n\n if (isFramebufferTarget(target)) {\n target.draw(() => renderer.clear());\n return;\n }\n\n const ctx = target.drawingContext;\n ctx.save();\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.clearRect(0, 0, target.width, target.height);\n ctx.restore();\n}\n\nfunction ensureBlendShaderProgram(renderer, vertSrc, fragSrc) {\n if (!renderer.loaded) {\n renderer.loaded = true;\n renderer.shaderProgram ??= renderer.createShader(vertSrc, fragSrc);\n }\n return renderer.shaderProgram;\n}\n\nfunction ensureBlendSourceFramebuffer(\n renderer,\n currentFramebuffer,\n width,\n height,\n density,\n) {\n if (currentFramebuffer?.remove) currentFramebuffer.remove();\n const fb = renderer.createFramebuffer({\n width,\n height,\n density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n return fb;\n}\n\nconst createFramebuffer = (renderer, options) =>\n renderer.createFramebuffer(options);\n\nfunction runBlendShaderPass({\n renderer,\n shader,\n source,\n mask,\n color,\n isBrushMask,\n Cwidth,\n Cheight,\n dirtyRect,\n targetIsFramebuffer,\n withScissor,\n}) {\n const gl = renderer.drawingContext;\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n\n gl.disable(gl.DEPTH_TEST);\n\n renderer.push();\n renderer.translate(0, 0);\n renderer.shader(shader);\n\n shader.setUniform(\"u_source\", source);\n shader.setUniform(\"u_targetIsFramebuffer\", targetIsFramebuffer);\n shader.setUniform(\"u_isBrush\", isBrushMask);\n shader.setUniform(\"u_mask\", mask);\n shader.setUniform(\"u_color\", color);\n\n withScissor(\n gl,\n dirtyRect,\n () => {\n renderer.fill(0, 0, 0, 0);\n renderer.noStroke();\n renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);\n },\n !targetIsFramebuffer,\n );\n\n renderer.pop();\n renderer.resetShader();\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n}\n\nfunction blitSourceToFramebuffer(args) {\n if (args.isFramebufferTarget(args.sourceTarget)) {\n (args.sourceTarget.renderer ?? args.renderer)._renderer?.flushDraw?.();\n args.sourceFramebuffer.draw(() => {\n args.withScissor(\n args.renderer.drawingContext,\n args.dirtyRect,\n () => {\n args.renderer.clear();\n args.renderer.push();\n args.renderer.imageMode(args.renderer.CENTER);\n args.renderer.image(\n args.sourceTarget,\n 0,\n 0,\n args.Cwidth,\n args.Cheight,\n );\n args.renderer.pop();\n },\n false,\n );\n });\n return args.sourceFramebuffer;\n }\n\n args.renderer._renderer?.flushDraw?.();\n return blitDefaultFramebufferSource(args);\n}\n\nexport function initP5CompositorRuntime() {\n setCompositorRuntime({\n clearTarget,\n ensureBlendShaderProgram,\n ensureBlendSourceFramebuffer,\n createFramebuffer,\n runBlendShaderPass,\n blitSourceToFramebuffer,\n });\n}\n","// =============================================================================\n// Adapter: p5 Stroke Hooks\n// =============================================================================\n\nimport { Renderer, Instance } from \"../../core/target.js\";\nimport { setStrokeRuntime } from \"../../stroke/runtime.js\";\n\nconst getP5BrushFactory = () => Renderer ?? Instance ?? window.self?.p5?.instance;\n\nfunction createTipSurface(width, height) {\n const factory = getP5BrushFactory();\n if (!factory?.createGraphics) {\n throw new Error(\"p5 stroke tip creation requires an active renderer or instance.\");\n }\n return factory.createGraphics(width, height);\n}\n\nfunction loadImageTip(src, imageToWhite) {\n return new Promise((resolve, reject) => {\n const nativeImg = new window.Image();\n nativeImg.onload = () => {\n const factory = getP5BrushFactory();\n if (!factory?.createImage) {\n reject(new Error(\"p5 image tip loading requires an active renderer or instance.\"));\n return;\n }\n const p5img = factory.createImage(\n nativeImg.naturalWidth,\n nativeImg.naturalHeight,\n );\n p5img.drawingContext.drawImage(nativeImg, 0, 0);\n imageToWhite(p5img);\n resolve(p5img);\n };\n nativeImg.onerror = () =>\n reject(new Error(`Failed to load image tip: ${src}`));\n nativeImg.crossOrigin = \"anonymous\";\n nativeImg.src = src;\n });\n}\n\nexport function initP5StrokeRuntime() {\n setStrokeRuntime({\n createTipSurface,\n loadImageTip,\n });\n}\n","import { State } from \"./color.js\";\nimport { isFieldReady } from \"./flowfield.js\";\n\n// =============================================================================\n// SAVE / RESTORE\n// =============================================================================\n\n/**\n * Stack of saved brush states for push/pop operations.\n * A stack (not a single slot) is required because applyShader() internally\n * calls Renderer.push()/pop(), which fires our hook — a flat object would be\n * overwritten mid-draw and pop() would restore the wrong state.\n */\nconst _stateStack = [];\n\n/**\n * Pushes the current brush state onto the stack.\n */\nexport function push() {\n isFieldReady();\n _stateStack.push({\n fill: { ...State.fill },\n wash: State.wash ? { ...State.wash } : null,\n stroke: { ...State.stroke },\n hatch: { ...State.hatch },\n mass: State.mass ? { ...State.mass } : null,\n field: { ...State.field },\n });\n}\n\n/**\n * Pops the top brush state from the stack and restores it.\n */\nexport function pop() {\n const saved = _stateStack.pop();\n if (!saved) return;\n State.stroke = { ...saved.stroke };\n State.field = { ...saved.field };\n State.hatch = { ...saved.hatch };\n State.fill = { ...saved.fill };\n if (saved.wash) State.wash = { ...saved.wash };\n if (saved.mass) {\n State.mass = { ...saved.mass };\n } else if (State.mass) {\n State.mass = {\n ...State.mass,\n isActive: false,\n brush: null,\n color: null,\n options: {},\n };\n }\n}\n","/**\n * @fileoverview p5 entry point for p5.brush.\n */\n\nexport * from \"./index.shared.js\";\n\nimport { initP5TargetRuntime } from \"./adapters/p5/target.js\";\nimport { initP5Runtime } from \"./adapters/p5/runtime.js\";\nimport { initP5RendererRuntime } from \"./adapters/p5/renderer.js\";\nimport { initP5CompositorRuntime } from \"./adapters/p5/compositor.js\";\nimport { initP5StrokeRuntime } from \"./adapters/p5/stroke.js\";\nimport { registerP5Addon } from \"./adapters/p5/addon.js\";\n\ninitP5TargetRuntime();\ninitP5Runtime();\ninitP5RendererRuntime();\ninitP5CompositorRuntime();\ninitP5StrokeRuntime();\n\nif (typeof p5 !== \"undefined\") p5.registerAddon(registerP5Addon);\n","// =============================================================================\n// Adapter: p5 Addon Registration\n// =============================================================================\n\nimport { flushActiveComposite } from \"../../core/color.js\";\nimport {\n instance as bindInstance,\n activateInstance,\n deactivateInstance,\n} from \"../../core/target.js\";\nimport { push as brushPush, pop as brushPop } from \"../../core/save.js\";\nimport { seed as brushSeed, noiseSeed as brushNoiseSeed } from \"../../core/utils.js\";\n\n/**\n * Registers the p5 addon hooks that keep p5.brush in sync with p5's runtime.\n *\n * This stays in the p5 adapter layer so a future standalone build can provide\n * its own lifecycle integration without importing p5-specific globals.\n *\n * @param {*} _p5\n * @param {Object} fn\n * @param {Object} lifecycles\n */\nexport function registerP5Addon(_p5, fn, lifecycles) {\n lifecycles.presetup = function () {\n activateInstance(this);\n };\n\n lifecycles.predraw = function () {\n activateInstance(this);\n };\n\n lifecycles.postsetup = function () {\n bindInstance(this);\n flushActiveComposite();\n deactivateInstance();\n };\n\n lifecycles.postdraw = function () {\n bindInstance(this);\n flushActiveComposite();\n deactivateInstance();\n };\n\n const _push = fn.push;\n const _pop = fn.pop;\n const _randomSeed = fn.randomSeed;\n const _noiseSeed = fn.noiseSeed;\n\n fn.push = function () {\n _push.call(this);\n brushPush();\n };\n\n fn.pop = function () {\n _pop.call(this);\n brushPop();\n };\n\n fn.randomSeed = function (s) {\n _randomSeed.call(this, s);\n brushSeed(s);\n };\n\n fn.noiseSeed = function (s) {\n _noiseSeed.call(this, s);\n brushNoiseSeed(s);\n };\n}\n"],"names":["identityMatrix","a","b","c","d","x","y","usesRadians","fromDegrees","angle","createColor","Error","getAffineMatrix","SQRT3","Math","sqrt","F2","G2","fastFloor","floor","grad2","Float64Array","createNoise2D","random","perm","p","Uint8Array","i","tableSize","r","aux","buildPermutationTable","permGrad2x","map","v","permGrad2y","n0","n1","n2","s","j","t","x0","y0","i1","j1","x1","y1","x2","y2","ii","jj","t0","gi0","t1","gi1","t2","gi2","prng_alea","seed","opts","xg","AleaGen","prng","next","double","int32","quick","constructor","Date","n","mash","data","String","length","charCodeAt","h","this","s0","s1","s2","copy","f","rng","rng2","_seedCallbacks","_onSeed","cb","push","callback","noise","noise2","noiseSeed","rr","e","rr2","rArray","array","randInt","randInt2","gaussian","mean","stdev","u","log","cos","weightedRand","weights","totalWeight","entries","key","cumulative","rnd","isNaN","parseInt","value","withinBounds","constrain","low","high","max","min","nAngle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","fill","NaN","sLookup","idx","sin","toDegrees","rad","isRad","runtimeUsesRadians","toDegreesSigned","rotate","cx","cy","coseno","seno","dist","hypot","calcAngle","atan2","intersectLines","s1a","s1b","s2a","s2b","includeSegmentExtension","x3","y3","x4","y4","deltaX1","deltaY1","deltaX2","deltaY2","denominator","ua","ub","Cwidth","Cheight","Instance","Renderer","Density","targetRuntime","load","syncDensity","isCanvasReady","instance","inst","activateInstance","deactivateInstance","getActiveFramebuffer","isFramebufferTarget","setTargetState","state","target","expandDirtyRect","rect","padding","minX","minY","maxX","maxY","create2DCanvas","width","height","willReadFrequently","canvas","OffscreenCanvas","element","document","createElement","drawingContext","getContext","undefined","compositorRuntime","clearTarget","ensureBlendShaderProgram","ensureBlendSourceFramebuffer","createFramebuffer","runBlendShaderPass","blitSourceToFramebuffer","args","strokeComposite","fillComposite","clearRenderTarget","getTargetPixelSize","round","normalizeDirtyRect","ceil","clampDirtyRect","getFullDirtyRect","getFullRect","toScissorBox","flipY","normalized","withScissor","gl","draw","box","enable","SCISSOR_TEST","scissor","disable","State","isMixReady","loaded","Mix","isBlending","cachedColor","markDirtyRect","dirtyRect","isDrawn","clearMask","composite","glMask","getCompositeRect","isBrushMask","needsBlendSourceFramebuffer","blendSourceFramebuffer","pixelDensity","ensureResources","fillResources","mask","ctx","blend","_color","_isLast","isBrush","otherMask","nextColor","_array","colorChanged","justChanged","applyShader","shader","shaderProgram","activeFramebuffer","source","renderer","sourceTarget","sourceFramebuffer","targetIsFramebuffer","shaderMask","getShaderMask","color","flushActiveComposite","buffer","loadTarget","isLoaded","isFieldReady","resolution","left_x","top_y","num_columns","num_rows","addField","field","bs","ba","fillField","ar","abs","dif","sr","cr","_t","dir","offset","attractors","Array","from","wx","wy","att","dx","dy","w","freq","amp","_r","Position","m","mx","my","update","plotted","colIdx","rowIdx","reset","isIn","isActive","isInCanvas","skipCheck","list","get","current","wiggle","moveTo","_dir","_length","_step_length","movePos","_moveToDegrees","plotTo","_plot","_scale","_dirPlot","_step","scaleFactor","steps","fieldActive","usePlot","getRowIndex","y_offset","getColIndex","x_offset","col","row","Map","FIELD_ANGLE_MODES","Set","normalizeFieldAngleMode","options","angleMode","has","generateField","entry","normalizeFieldAngles","gen","refreshField","currentField","keys","join","noField","name","funct","set","listFields","fn","Polygon","pointsArray","useRawVertices","vertices","sides","arr","_intersectionCache","intersect","line","cacheKey","point1","point2","points","start","end","intersection","show","wash","mass","hatch","stroke","Plot","_type","segments","angles","pres","type","calcIndex","pol","addSegment","_a","_pres","_degrees","pop","reduce","sum","len","endPlot","pressure","_d","curving","index","map0","map1","suma","genPol","_x","_y","_side","step","numSteps","pos","pside","prevIdx","scale","polygon","mode","beginShape","vertex","endShape","circle","radius","arcLength","angleOffset","randomFactor","randomAngle","offsetX","offsetY","arc","startDeg","sweepDeg","segmentCount","segmentSweep","startX","startY","_current","_curvature","_strokeArray","_strokeOrigin","SubPath","isClosed","curvature","vert","_createSpline","close","beginStroke","move","endStroke","spline","_array_points","PI2","pep","tep","pep2","done","p1","p2","p3","d1","d2","a1","a2","curvAdjust","dmax","temp","temp2","point3","point4","intPt","halfDist","asin","origin","strokeRuntime","createTipSurface","loadImageTip","isStrokeCompositeRegistered","createProgram","frag","src","VERTEX_SHADER","FRAGMENT_SHADER","createShader","shaderSource","compileShader","attachShader","linkProgram","rendererRuntime","beginDirectMaskDraw","endDirectMaskDraw","resetDirectShaderTracking","framebufferProjMatrix","vao","buf","program","loadedWidth","loadedHeight","brushMaskTarget","Attr","Frag","_ma","_mb","_mc","_md","_mx","_my","_halfW","_halfH","_density","circleData","INITIAL_CAPACITY","circleCount","bufferCapacity","gpuBufferSize","circleDirtyRect","imgProgram","imgVao","imgCornerBuf","imgInstanceBuf","imgAttr","imgFrag","imgGpuSize","imgData","IMG_INIT_CAP","imgCount","imgCapacity","imgDirtyRect","texCache","QUAD_CORNERS","getProjectionMatrix","beginMaskTarget","endMaskTarget","accumulateDirtyRect","currentRect","diameter","alpha","newData","px","py","screenX","screenY","dScreenX","dScreenY","glDrawImages","p5img","targetState","tex","createTexture","bindTexture","TEXTURE_2D","texImage2D","RGBA","UNSIGNED_BYTE","texParameteri","TEXTURE_MIN_FILTER","LINEAR","TEXTURE_MAG_FILTER","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","useProgram","BLEND","blendFunc","ONE_MINUS_DST_ALPHA","ONE","activeTexture","TEXTURE0","uniform1i","u_tex","uniform4f","u_color","uniformMatrix4fv","u_proj","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","drawArraysInstanced","TRIANGLE_STRIP","flush","needsStrokeMask","remove","density","antialias","depth","stencil","_Renderer","weight","opacity","DEFAULT_CUSTOM_PRESSURE_VARIATION","warp","tilt","BrushState","BrushSetState","add","params","includes","markerTip","vibration","scatter","definition","sharpness","quality","grain","min_max","curve","variation","isArray","rest","range","ns","nm","ne","normalizePressure","tip","deleteTexture","delete","invalidateTexEntry","g","background","noSmooth","translate","noStroke","T","imageToWhite","tips","tipKey","param","colors","buffers","image","getBrushParams","brushName","scaleBrushes","values","spacing","pick","arguments","strokeWeight","clip","region","noClip","_position","initializeDrawingState","plot","snapshotMatrix","gaussians","angleScale","isPlot","cp","ct","cs","ck","noiseoffset","rendererMask","ensureBrushMaskTarget","nextGl","needsContextRefresh","forEach","getAttribLocation","getUniformLocation","createVertexArray","createBuffer","enableVertexAttribArray","a_position","vertexAttribPointer","FLOAT","a_radius","a_alpha","clear","STATIC_DRAW","a_corner","a_pos","IMG_FLOATS","vertexAttribDivisor","a_size","a_angle","isReady","switchingToBrush","saveState","stepSize","totalSteps","pressureCount","cachedPressure","lineNoiseCount","cachedLineNoise","u_matrix","drawArrays","POINTS","glDraw","restoreState","calculatePressure","lineNoise","sw","iterations","rX","yRandomFactor","sqrtPart","drawSpray","drawMarker","drawImageTip","plotAngle","plotCos","plotSin","perp","along","drawDefault","simPressure","peakPos","halfWidth","pow","gauss","vibrate","rx","ry","size","overscan","maxPressure","scatterReach","tipReach","getImageTipOverscan","extraPadding","halfSize","extraRadius","base","boundsRadius","stampImage","flowLine","_vals","_standard_brushes","obj","prototype","_brush","_weight","loadPixels","average","pixels","updatePixels","filter","k","Promise","all","then","HatchState","HatchSetState","rand","continuous","gradient","hatchStyle","brush","hBrush","noHatch","scanlineHatch","cosA","sinA","cosB","sinB","verts","rotated","Infinity","edges","eLen","Y","sort","scanY","getHatchLines","polygons","segs","poly","getHatchSegments","getActiveHatchConfig","lines","isConnector","prev","createHatch","drawSegment","save","Object","drawFn","withHatchStyle","renderHatchSegments","noMass","jitterPolygon","jitterX","jitterY","projectAnchorToBisector","anchor","nx","ny","getShortArcAngles","toAngleUnit","endDeg","splitSegment","seg","gap","gx","gy","drawMassArcs","pivotBias","bias","bounds","getPolygonBounds","sx","sy","getPivotAnchor","parts","part","center","startAngle","endAngle","drawMassPass","createMass","shape","pols","isPolygon","basePolygon","maxJitter","jitters","getMassPolygons","hatchState","brushState","fieldState","precision","strength","outline","hatchDist","baseAngle","_dist","_angle","_options","FillMaskUploadCanvas","isFillCompositeRegistered","maskWidth","maskHeight","needsFillMaskCanvas","fillMaskFramebuffer","needsFillMaskFramebuffer","imageSmoothingEnabled","_getActiveFramebuffer","uploadRect","uploadWidth","uploadHeight","uploadContext","clearRect","drawImage","colorTexture","texSubImage2D","GROW_CAP","_growInsX","_growInsY","_growMods","_growDirs","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","noFill","_polygon","_gaussians","_fillGaussianPools","_isLeft","FillPoly","isFirst","midP","rayCalc","v1","v2","side","rt","mid","ray","sizeX","sizeY","rc","count","isect","trim","keep","dst","trimStart","trimEnd","edgeStart","edgeEnd","edgeVec","newVertex","insertIdx","splice","ratio","L","indices","sv","sm","sd","crossings","ay","by","flipDirs","grow","tr_v","tr_m","tr_dir","outLen","insertedX","insertedY","newMods","newDirs","bleedDirDeg","gPool","gPoolLen","g2Pool","g2PoolLen","fv","fm","fd","insertedIdx","mod","cv","nv","mi","di","rotDeg","sideX","sideY","dirX","dirY","nextMod","kept","slice","intensity","texture","int","switchingToFill","setTransform","strokeStyle","_getRed","_getGreen","_getBlue","lineCap","darker","sparse","layer","numLayers","erase","restore","lineWidth","fillStyle","matrix","getTransform","beginPath","first","tx","ty","lineTo","closePath","strokePadding","drawPolygon","numCircles","halfSizeX","halfSizeY","minSize","minSizeFactor","maxSizeFactor","midX","midY","globalCompositeOperation","filterPoints","again","steiner","equals","area","removeNode","earcutLinked","ear","triangles","dim","invSize","pass","z","zOrder","prevZ","nextZ","numMerges","inSize","tail","q","pSize","qSize","sortLinked","indexCurve","stop","isEarHashed","isEar","cureLocalIntersections","splitEarcut","ax","bx","pointInTriangleExceptFirst","minZ","maxZ","intersects","locallyInside","isValidDiagonal","splitPolygon","pointInTriangle","intersectsPolygon","inside","middleInside","q1","q2","o1","sign","o2","o3","o4","onSegment","num","createNode","b2","an","bp","insertNode","last","_opacity","_bleed","fluid","modifiers","_","shift","shifted","pts","point","cross","_center","createFill","FillSetState","washProgram","washVao","washBuffer","washProjection","washGpuBufferSize","WashAttr","WashUniform","noWash","transformVertexToScreen","ensureWashReady","vertexCount","flat","holeIndices","outerLen","outerNode","signedArea","linkedList","earcut","buildTriangleBuffer","blendEquation","FUNC_ADD","ONE_MINUS_SRC_ALPHA","TRIANGLES","drawWashPolygon","ReadySketch","ActiveInstance","ActiveInstanceStack","_isReady","begin","_pInst","isFiniteSize","Number","isFinite","safeRead","getter","_error","isReadyWebGLSketch","candidate","webglVersion","rememberReadySketch","getSketchRenderer","window","self","p5","sketchRenderer","owner","resolveTarget","getP5RuntimeRenderer","affineMatrix","isRadians","RADIANS","hadDepthTest","isEnabled","DEPTH_TEST","previousTarget","_renderer","_beforeEnd","bindFramebuffer","FRAMEBUFFER","_framebufferToBind","framebuffer","getFramebufferHandle","viewport","_beforeBegin","_origViewport","_applyStencilTestIfClipping","resetP5ShaderTracking","coreRenderer","_curShader","_cachedBlendMode","_isBlending","vertSrc","fragSrc","currentFramebuffer","setUniform","resetShader","flushDraw","imageMode","CENTER","sourceBox","previousReadFramebuffer","getParameter","READ_FRAMEBUFFER_BINDING","previousDrawFramebuffer","DRAW_FRAMEBUFFER_BINDING","READ_FRAMEBUFFER","DRAW_FRAMEBUFFER","clearColor","COLOR_BUFFER_BIT","blitFramebuffer","NEAREST","blitDefaultFramebufferSource","getP5BrushFactory","factory","createGraphics","resolve","reject","nativeImg","Image","onload","createImage","naturalWidth","naturalHeight","onerror","crossOrigin","_stateStack","hooks","mat4","uModelMatrix","initP5Runtime","initP5RendererRuntime","initP5CompositorRuntime","initP5StrokeRuntime","registerAddon","_p5","lifecycles","presetup","predraw","postsetup","bindInstance","postdraw","_push","_pop","_randomSeed","randomSeed","_noiseSeed","call","saved","brushPop","brushSeed","brushNoiseSeed"],"mappings":"AAIA,MAAMA,EAAiB,CACrBC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,GAGE,IAAIC,EAAc,KAAM,EACpBC,EAAeC,GAAUA,EACzBC,EAAc,KACvB,MAAM,IAAIC,MAAM,yCAEPC,EAAkB,IAAMZ,ECYnC,MAAMa,EAAsBC,KAAKC,KAAK,GAEhCC,EAAK,IAAOH,EAAQ,GACpBI,GAAM,EAAMJ,GAAS,EAQrBK,EAAab,GAAsB,EAAhBS,KAAKK,MAAMd,GAC9Be,EAAsB,IAAIC,aAAa,CAAC,EAAG,GAC7C,EAAI,EACJ,GAAG,GACH,GAAI,EACJ,EAAG,GACH,EAAI,EACJ,EAAG,GACH,EAAI,EACJ,EAAG,EACH,GAAG,EACH,EAAG,EACH,GAAG,IA6BA,SAASC,EAAcC,EAAST,KAAKS,QACxC,MAAMC,EA6WH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,CACfwC,KAAM,IAAKsG,GAAMtG,MACjB+P,KAAMzJ,GAAMyJ,KAAO,IAAKzJ,GAAMyJ,MAAS,KACvCG,OAAQ,IAAK5J,GAAM4J,QACnBD,MAAO,IAAK3J,GAAM2J,OAClBD,KAAM1J,GAAM0J,KAAO,IAAK1J,GAAM0J,MAAS,KACvCrG,MAAO,IAAKrD,GAAMqD,QE0BpB,EAEAkF,EAAGkC,IAAM,WACPwwB,EAAKI,KAAK9kC,MFtBP,WACL,MAAM+kC,EAAQtB,GAAYvvB,MACrB6wB,IACLt7B,GAAM4J,OAAS,IAAK0xB,EAAM1xB,QAC1B5J,GAAMqD,MAAQ,IAAKi4B,EAAMj4B,OACzBrD,GAAM2J,MAAQ,IAAK2xB,EAAM3xB,OACzB3J,GAAMtG,KAAO,IAAK4hC,EAAM5hC,MACpB4hC,EAAM7xB,OAAMzJ,GAAMyJ,KAAO,IAAK6xB,EAAM7xB,OACpC6xB,EAAM5xB,KACR1J,GAAM0J,KAAO,IAAK4xB,EAAM5xB,MACf1J,GAAM0J,OACf1J,GAAM0J,KAAO,IACR1J,GAAM0J,KACTnE,UAAU,EACV2b,MAAO,KACPze,MAAO,KACP8E,QAAS,CAAA,IAGf,CEIIg0B,EACF,EAEAhzB,EAAG4yB,WAAa,SAAUlnC,GACxBinC,EAAYG,KAAK9kC,KAAMtC,GACvBunC,EAAUvnC,EACZ,EAEAsU,EAAGjR,UAAY,SAAUrD,GACvBmnC,EAAWC,KAAK9kC,KAAMtC,GACtBwnC,EAAexnC,EACjB,CACF","x_google_ignoreList":[1,2,23]}
\ No newline at end of file
+{"version":3,"file":"p5.brush.esm.js","sources":["../src/core/runtime.js","../node_modules/simplex-noise/dist/esm/simplex-noise.js","../node_modules/esm-seedrandom/esm/index.mjs","../src/core/utils.js","../src/core/target.js","../src/core/dirty_rect.js","../src/core/compositor_runtime.js","../src/core/color.js","../src/core/flowfield.js","../src/core/polygon.js","../src/core/plot.js","../src/core/primitives.js","../src/stroke/runtime.js","../src/stroke/composite.js","../src/core/gl/utils.js","../src/core/renderer_runtime.js","../src/stroke/gl_draw.js","../src/stroke/stroke.js","../src/hatch/hatch.js","../src/hatch/mass.js","../src/fill/mask.js","../src/fill/composite.js","../src/fill/fill.js","../node_modules/earcut/src/earcut.js","../src/fill/wash.js","../src/adapters/p5/target.js","../src/adapters/p5/runtime.js","../src/adapters/p5/renderer.js","../src/adapters/p5/compositor.js","../src/adapters/p5/stroke.js","../src/core/save.js","../src/index.p5.js","../src/adapters/p5/addon.js"],"sourcesContent":["// =============================================================================\n// Runtime Hooks\n// =============================================================================\n\nconst identityMatrix = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\n\nexport let usesRadians = () => false;\nexport let fromDegrees = (angle) => angle;\nexport let createColor = () => {\n throw new Error(\"No runtime color adapter registered.\");\n};\nexport let getAffineMatrix = () => identityMatrix;\n\n/**\n * Registers or updates host-runtime hooks used by core modules.\n *\n * @param {object} hooks\n */\nexport function setRuntime(hooks) {\n if (hooks.usesRadians) usesRadians = hooks.usesRadians;\n if (hooks.fromDegrees) fromDegrees = hooks.fromDegrees;\n if (hooks.createColor) createColor = hooks.createColor;\n if (hooks.getAffineMatrix) getAffineMatrix = hooks.getAffineMatrix;\n}\n","/*\n * A fast javascript implementation of simplex noise by Jonas Wagner\n\nBased on a speed-improved simplex noise algorithm for 2D, 3D and 4D in Java.\nWhich is based on example code by Stefan Gustavson ([email protected]).\nWith Optimisations by Peter Eastman ([email protected]).\nBetter rank ordering method by Stefan Gustavson in 2012.\n\n Copyright (c) 2024 Jonas Wagner\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n */\n// these __PURE__ comments help uglifyjs with dead code removal\n//\nconst SQRT3 = /*#__PURE__*/ Math.sqrt(3.0);\nconst SQRT5 = /*#__PURE__*/ Math.sqrt(5.0);\nconst F2 = 0.5 * (SQRT3 - 1.0);\nconst G2 = (3.0 - SQRT3) / 6.0;\nconst F3 = 1.0 / 3.0;\nconst G3 = 1.0 / 6.0;\nconst F4 = (SQRT5 - 1.0) / 4.0;\nconst G4 = (5.0 - SQRT5) / 20.0;\n// I'm really not sure why this | 0 (basically a coercion to int)\n// is making this faster but I get ~5 million ops/sec more on the\n// benchmarks across the board or a ~10% speedup.\nconst fastFloor = (x) => Math.floor(x) | 0;\nconst grad2 = /*#__PURE__*/ new Float64Array([1, 1,\n -1, 1,\n 1, -1,\n -1, -1,\n 1, 0,\n -1, 0,\n 1, 0,\n -1, 0,\n 0, 1,\n 0, -1,\n 0, 1,\n 0, -1]);\n// double seems to be faster than single or int's\n// probably because most operations are in double precision\nconst grad3 = /*#__PURE__*/ new Float64Array([1, 1, 0,\n -1, 1, 0,\n 1, -1, 0,\n -1, -1, 0,\n 1, 0, 1,\n -1, 0, 1,\n 1, 0, -1,\n -1, 0, -1,\n 0, 1, 1,\n 0, -1, 1,\n 0, 1, -1,\n 0, -1, -1]);\n// double is a bit quicker here as well\nconst grad4 = /*#__PURE__*/ new Float64Array([0, 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1,\n 0, -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1,\n 1, 0, 1, 1, 1, 0, 1, -1, 1, 0, -1, 1, 1, 0, -1, -1,\n -1, 0, 1, 1, -1, 0, 1, -1, -1, 0, -1, 1, -1, 0, -1, -1,\n 1, 1, 0, 1, 1, 1, 0, -1, 1, -1, 0, 1, 1, -1, 0, -1,\n -1, 1, 0, 1, -1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, -1,\n 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1, 0,\n -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1, 0]);\n/**\n * Creates a 2D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction2D}\n */\nexport function createNoise2D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating this yields a little ~3% performance improvement.\n const permGrad2x = new Float64Array(perm).map(v => grad2[(v % 12) * 2]);\n const permGrad2y = new Float64Array(perm).map(v => grad2[(v % 12) * 2 + 1]);\n return function noise2D(x, y) {\n // if(!isFinite(x) || !isFinite(y)) return 0;\n let n0 = 0; // Noise contributions from the three corners\n let n1 = 0;\n let n2 = 0;\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y) * F2; // Hairy factor for 2D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const t = (i + j) * G2;\n const X0 = i - t; // Unskew the cell origin back to (x,y) space\n const Y0 = j - t;\n const x0 = x - X0; // The x,y distances from the cell origin\n const y0 = y - Y0;\n // For the 2D case, the simplex shape is an equilateral triangle.\n // Determine which simplex we are in.\n let i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords\n if (x0 > y0) {\n i1 = 1;\n j1 = 0;\n } // lower triangle, XY order: (0,0)->(1,0)->(1,1)\n else {\n i1 = 0;\n j1 = 1;\n } // upper triangle, YX order: (0,0)->(0,1)->(1,1)\n // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and\n // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where\n // c = (3-sqrt(3))/6\n const x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords\n const y1 = y0 - j1 + G2;\n const x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords\n const y2 = y0 - 1.0 + 2.0 * G2;\n // Work out the hashed gradient indices of the three simplex corners\n const ii = i & 255;\n const jj = j & 255;\n // Calculate the contribution from the three corners\n let t0 = 0.5 - x0 * x0 - y0 * y0;\n if (t0 >= 0) {\n const gi0 = ii + perm[jj];\n const g0x = permGrad2x[gi0];\n const g0y = permGrad2y[gi0];\n t0 *= t0;\n // n0 = t0 * t0 * (grad2[gi0] * x0 + grad2[gi0 + 1] * y0); // (x,y) of grad3 used for 2D gradient\n n0 = t0 * t0 * (g0x * x0 + g0y * y0);\n }\n let t1 = 0.5 - x1 * x1 - y1 * y1;\n if (t1 >= 0) {\n const gi1 = ii + i1 + perm[jj + j1];\n const g1x = permGrad2x[gi1];\n const g1y = permGrad2y[gi1];\n t1 *= t1;\n // n1 = t1 * t1 * (grad2[gi1] * x1 + grad2[gi1 + 1] * y1);\n n1 = t1 * t1 * (g1x * x1 + g1y * y1);\n }\n let t2 = 0.5 - x2 * x2 - y2 * y2;\n if (t2 >= 0) {\n const gi2 = ii + 1 + perm[jj + 1];\n const g2x = permGrad2x[gi2];\n const g2y = permGrad2y[gi2];\n t2 *= t2;\n // n2 = t2 * t2 * (grad2[gi2] * x2 + grad2[gi2 + 1] * y2);\n n2 = t2 * t2 * (g2x * x2 + g2y * y2);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to return values in the interval [-1,1].\n return 70.0 * (n0 + n1 + n2);\n };\n}\n/**\n * Creates a 3D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction3D}\n */\nexport function createNoise3D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these seems to yield a speedup of over 15%\n const permGrad3x = new Float64Array(perm).map(v => grad3[(v % 12) * 3]);\n const permGrad3y = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 1]);\n const permGrad3z = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 2]);\n return function noise3D(x, y, z) {\n let n0, n1, n2, n3; // Noise contributions from the four corners\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y + z) * F3; // Very nice and simple skew factor for 3D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const t = (i + j + k) * G3;\n const X0 = i - t; // Unskew the cell origin back to (x,y,z) space\n const Y0 = j - t;\n const Z0 = k - t;\n const x0 = x - X0; // The x,y,z distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n // For the 3D case, the simplex shape is a slightly irregular tetrahedron.\n // Determine which simplex we are in.\n let i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords\n let i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords\n if (x0 >= y0) {\n if (y0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // X Y Z order\n else if (x0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // X Z Y order\n else {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // Z X Y order\n }\n else { // x0<y0\n if (y0 < z0) {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Z Y X order\n else if (x0 < z0) {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Y Z X order\n else {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // Y X Z order\n }\n // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),\n // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and\n // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where\n // c = 1/6.\n const x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords\n const y1 = y0 - j1 + G3;\n const z1 = z0 - k1 + G3;\n const x2 = x0 - i2 + 2.0 * G3; // Offsets for third corner in (x,y,z) coords\n const y2 = y0 - j2 + 2.0 * G3;\n const z2 = z0 - k2 + 2.0 * G3;\n const x3 = x0 - 1.0 + 3.0 * G3; // Offsets for last corner in (x,y,z) coords\n const y3 = y0 - 1.0 + 3.0 * G3;\n const z3 = z0 - 1.0 + 3.0 * G3;\n // Work out the hashed gradient indices of the four simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n // Calculate the contribution from the four corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad3x[gi0] * x0 + permGrad3y[gi0] * y0 + permGrad3z[gi0] * z0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad3x[gi1] * x1 + permGrad3y[gi1] * y1 + permGrad3z[gi1] * z1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad3x[gi2] * x2 + permGrad3y[gi2] * y2 + permGrad3z[gi2] * z2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + 1 + perm[jj + 1 + perm[kk + 1]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad3x[gi3] * x3 + permGrad3y[gi3] * y3 + permGrad3z[gi3] * z3);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to stay just inside [-1,1]\n return 32.0 * (n0 + n1 + n2 + n3);\n };\n}\n/**\n * Creates a 4D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction4D}\n */\nexport function createNoise4D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these leads to a ~10% speedup\n const permGrad4x = new Float64Array(perm).map(v => grad4[(v % 32) * 4]);\n const permGrad4y = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 1]);\n const permGrad4z = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 2]);\n const permGrad4w = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 3]);\n return function noise4D(x, y, z, w) {\n let n0, n1, n2, n3, n4; // Noise contributions from the five corners\n // Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in\n const s = (x + y + z + w) * F4; // Factor for 4D skewing\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const l = fastFloor(w + s);\n const t = (i + j + k + l) * G4; // Factor for 4D unskewing\n const X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space\n const Y0 = j - t;\n const Z0 = k - t;\n const W0 = l - t;\n const x0 = x - X0; // The x,y,z,w distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n const w0 = w - W0;\n // For the 4D case, the simplex is a 4D shape I won't even try to describe.\n // To find out which of the 24 possible simplices we're in, we need to\n // determine the magnitude ordering of x0, y0, z0 and w0.\n // Six pair-wise comparisons are performed between each possible pair\n // of the four coordinates, and the results are used to rank the numbers.\n let rankx = 0;\n let ranky = 0;\n let rankz = 0;\n let rankw = 0;\n if (x0 > y0)\n rankx++;\n else\n ranky++;\n if (x0 > z0)\n rankx++;\n else\n rankz++;\n if (x0 > w0)\n rankx++;\n else\n rankw++;\n if (y0 > z0)\n ranky++;\n else\n rankz++;\n if (y0 > w0)\n ranky++;\n else\n rankw++;\n if (z0 > w0)\n rankz++;\n else\n rankw++;\n // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order.\n // Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w and x<w\n // impossible. Only the 24 indices which have non-zero entries make any sense.\n // We use a thresholding to set the coordinates in turn from the largest magnitude.\n // Rank 3 denotes the largest coordinate.\n // Rank 2 denotes the second largest coordinate.\n // Rank 1 denotes the second smallest coordinate.\n // The integer offsets for the second simplex corner\n const i1 = rankx >= 3 ? 1 : 0;\n const j1 = ranky >= 3 ? 1 : 0;\n const k1 = rankz >= 3 ? 1 : 0;\n const l1 = rankw >= 3 ? 1 : 0;\n // The integer offsets for the third simplex corner\n const i2 = rankx >= 2 ? 1 : 0;\n const j2 = ranky >= 2 ? 1 : 0;\n const k2 = rankz >= 2 ? 1 : 0;\n const l2 = rankw >= 2 ? 1 : 0;\n // The integer offsets for the fourth simplex corner\n const i3 = rankx >= 1 ? 1 : 0;\n const j3 = ranky >= 1 ? 1 : 0;\n const k3 = rankz >= 1 ? 1 : 0;\n const l3 = rankw >= 1 ? 1 : 0;\n // The fifth corner has all coordinate offsets = 1, so no need to compute that.\n const x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords\n const y1 = y0 - j1 + G4;\n const z1 = z0 - k1 + G4;\n const w1 = w0 - l1 + G4;\n const x2 = x0 - i2 + 2.0 * G4; // Offsets for third corner in (x,y,z,w) coords\n const y2 = y0 - j2 + 2.0 * G4;\n const z2 = z0 - k2 + 2.0 * G4;\n const w2 = w0 - l2 + 2.0 * G4;\n const x3 = x0 - i3 + 3.0 * G4; // Offsets for fourth corner in (x,y,z,w) coords\n const y3 = y0 - j3 + 3.0 * G4;\n const z3 = z0 - k3 + 3.0 * G4;\n const w3 = w0 - l3 + 3.0 * G4;\n const x4 = x0 - 1.0 + 4.0 * G4; // Offsets for last corner in (x,y,z,w) coords\n const y4 = y0 - 1.0 + 4.0 * G4;\n const z4 = z0 - 1.0 + 4.0 * G4;\n const w4 = w0 - 1.0 + 4.0 * G4;\n // Work out the hashed gradient indices of the five simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n const ll = l & 255;\n // Calculate the contribution from the five corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk + perm[ll]]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad4x[gi0] * x0 + permGrad4y[gi0] * y0 + permGrad4z[gi0] * z0 + permGrad4w[gi0] * w0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad4x[gi1] * x1 + permGrad4y[gi1] * y1 + permGrad4z[gi1] * z1 + permGrad4w[gi1] * w1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad4x[gi2] * x2 + permGrad4y[gi2] * y2 + permGrad4z[gi2] * z2 + permGrad4w[gi2] * w2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad4x[gi3] * x3 + permGrad4y[gi3] * y3 + permGrad4z[gi3] * z3 + permGrad4w[gi3] * w3);\n }\n let t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4;\n if (t4 < 0)\n n4 = 0.0;\n else {\n const gi4 = ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]];\n t4 *= t4;\n n4 = t4 * t4 * (permGrad4x[gi4] * x4 + permGrad4y[gi4] * y4 + permGrad4z[gi4] * z4 + permGrad4w[gi4] * w4);\n }\n // Sum up and scale the result to cover the range [-1,1]\n return 27.0 * (n0 + n1 + n2 + n3 + n4);\n };\n}\n/**\n * Builds a random permutation table.\n * This is exported only for (internal) testing purposes.\n * Do not rely on this export.\n * @private\n */\nexport function buildPermutationTable(random) {\n const tableSize = 512;\n const p = new Uint8Array(tableSize);\n for (let i = 0; i < tableSize / 2; i++) {\n p[i] = i;\n }\n for (let i = 0; i < tableSize / 2 - 1; i++) {\n const r = i + ~~(random() * (256 - i));\n const aux = p[i];\n p[i] = p[r];\n p[r] = aux;\n }\n for (let i = 256; i < tableSize; i++) {\n p[i] = p[i - 256];\n }\n return p;\n}\n//# sourceMappingURL=simplex-noise.js.map","function _prng_restore(prng, xg, opts) {\n let state = opts && opts.state;\n if (state) {\n if (typeof(state) == 'object') xg.copy(state, xg);\n prng.state = () => xg.copy(xg, {});\n }\n}\n\nfunction _prng_xor_core(xg, opts) {\n let prng = () => (xg.next() >>> 0) / 0x100000000;\n\n prng.double = () => {\n let top, bot, result;\n do {\n top = xg.next() >>> 11;\n bot = (xg.next() >>> 0) / 0x100000000;\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n\n prng.int32 = () => xg.next() | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng;\n}\n\n// A port of an algorithm by Johannes Baagøe <[email protected]>, 2010\nfunction prng_alea(seed, opts) {\n let xg = new AleaGen(seed);\n\n let prng = () => xg.next();\n\n prng.double = () =>\n prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53\n\n prng.int32 = () => (xg.next() * 0x100000000) | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\nclass AleaGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let n = 0xefc8249d;\n\n // Apply the seeding algorithm from Baagoe.\n this.c = 1;\n this.s0 = mash(' ');\n this.s1 = mash(' ');\n this.s2 = mash(' ');\n this.s0 -= mash(seed);\n if (this.s0 < 0) { this.s0 += 1; }\n this.s1 -= mash(seed);\n if (this.s1 < 0) { this.s1 += 1; }\n this.s2 -= mash(seed);\n if (this.s2 < 0) { this.s2 += 1; }\n\n function mash(data) {\n data = String(data);\n for (let i = 0; i < data.length; i++) {\n n += data.charCodeAt(i);\n let h = 0.02519603282416938 * n;\n n = h >>> 0;\n h -= n;\n h *= n;\n n = h >>> 0;\n h -= n;\n n += h * 0x100000000; // 2^32\n }\n return (n >>> 0) * 2.3283064365386963e-10; // 2^-32\n }\n }\n\n next() {\n let {c,s0,s1,s2} = this;\n let t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32\n this.s0 = s1;\n this.s1 = s2;\n return this.s2 = t - (this.c = t | 0);\n }\n\n copy(f, t) {\n t.c = f.c;\n t.s0 = f.s0;\n t.s1 = f.s1;\n t.s2 = f.s2;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xor128\" prng algorithm by\nfunction prng_xor128(seed, opts) {\n let xg = new Xor128Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass Xor128Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w} = this;\n let t = x ^ (x << 11);\n this.x = y;\n this.y = z;\n this.z = w;\n return this.w = w ^ ((w >>> 19) ^ t ^ (t >>> 8));\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorwow\" prng algorithm by\nfunction prng_xorwow(seed, opts) {\n let xg = new XorWowGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass XorWowGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n this.v = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n if (k == strseed.length) {\n this.d = this.x << 10 ^ this.x >>> 4;\n }\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w,v,d} = this;\n let t = (x ^ (x >>> 2));\n this.x = y;\n this.y = z;\n this.z = w;\n this.w = v;\n return (this.d = (d + 362437 | 0)) +\n (this.v = (v ^ (v << 4)) ^ (t ^ (t << 1))) | 0;\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n t.v = f.v;\n t.d = f.d;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorshift7\" algorithm by\nfunction prng_xorshift7(seed, opts) {\n let xg = new XorShift7Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass XorShift7Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n var j, w, x = [];\n\n if (seed === (seed | 0)) {\n // Seed state array using a 32-bit integer.\n w = x[0] = seed;\n } else {\n // Seed state using a string.\n seed = '' + seed;\n for (j = 0; j < seed.length; ++j) {\n x[j & 7] = (x[j & 7] << 15) ^\n (seed.charCodeAt(j) + x[(j + 1) & 7] << 13);\n }\n }\n\n // Enforce an array length of 8, not all zeroes.\n while (x.length < 8) x.push(0);\n for (j = 0; j < 8 && x[j] === 0; ++j);\n if (j == 8) w = x[7] = -1; else w = x[j];\n\n this.x = x;\n this.i = 0;\n\n // Discard an initial 256 values.\n for (j = 256; j > 0; --j) {\n this.next();\n }\n }\n\n next() {\n // Update xor generator.\n let t, v, {x,i} = this;\n t = x[i]; t ^= (t >>> 7); v = t ^ (t << 24);\n t = x[(i + 1) & 7]; v ^= t ^ (t >>> 10);\n t = x[(i + 3) & 7]; v ^= t ^ (t >>> 3);\n t = x[(i + 4) & 7]; v ^= t ^ (t << 7);\n t = x[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);\n x[i] = v;\n this.i = (i + 1) & 7;\n return v;\n };\n\n copy(f, t) {\n t.x = [... f.x];\n t.i = f.i;\n return t;\n }\n}\n\n// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.\nfunction prng_xor4096(seed, opts) {\n let xg = new Xor4096Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass Xor4096Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let t, v, i, j, w, X = [], limit = 128;\n if (seed === (seed | 0)) {\n // Numeric seeds initialize v, which is used to generates X.\n v = seed;\n seed = null;\n } else {\n // String seeds are mixed into v and X one character at a time.\n seed = seed + '\\0';\n v = 0;\n limit = Math.max(limit, seed.length);\n }\n // Initialize circular array and weyl value.\n for (i = 0, j = -32; j < limit; ++j) {\n // Put the unicode characters into the array, and shuffle them.\n if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);\n // After 32 shuffles, take v as the starting w value.\n if (j === 0) w = v;\n v ^= v << 10;\n v ^= v >>> 15;\n v ^= v << 4;\n v ^= v >>> 13;\n if (j >= 0) {\n w = (w + 0x61c88647) | 0; // Weyl.\n t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array.\n i = (0 == t) ? i + 1 : 0; // Count zeroes.\n }\n }\n // We have detected all zeroes; make the key nonzero.\n if (i >= 128) {\n X[(seed && seed.length || 0) & 127] = -1;\n }\n // Run the generator 512 times to further mix the state before using it.\n // Factoring this as a function slows the main generator, so it is just\n // unrolled here. The weyl generator is not advanced while warming up.\n i = 127;\n for (j = 4 * 128; j > 0; --j) {\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n X[i] = v ^ t;\n }\n // Storing state as object members is faster than using closure variables.\n this.w = w;\n this.X = X;\n this.i = i;\n }\n\n next() {\n let t, v, {w, X, i} = this;\n // Update Weyl generator.\n this.w = w = (w + 0x61c88647) | 0;\n // Update xor generator.\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n // Update Xor generator array state.\n v = X[i] = v ^ t;\n this.i = i;\n // Result is the combination.\n return (v + (w ^ (w >>> 16))) | 0;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.w = f.w;\n t.X = [... f.X];\n return t;\n }\n}\n\n// A Javascript implementaion of the \"Tyche-i\" prng algorithm by\nfunction prng_tychei(seed, opts) {\n let xg = new TycheiGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass TycheiGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.a = 0;\n this.b = 0;\n this.c = 2654435769 | 0;\n this.d = 1367130551;\n\n if (seed === Math.floor(seed)) {\n // Integer seed.\n this.a = (seed / 0x100000000) | 0;\n this.b = seed | 0;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 20; k++) {\n this.b ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {a,b,c,d} = this;\n b = (b << 25) ^ (b >>> 7) ^ c;\n c = (c - d) | 0;\n d = (d << 24) ^ (d >>> 8) ^ a;\n a = (a - b) | 0;\n this.b = b = (b << 20) ^ (b >>> 12) ^ c;\n this.c = c = (c - d) | 0;\n this.d = (d << 16) ^ (c >>> 16) ^ a;\n return this.a = (a - b) | 0;\n };\n\n copy(f, t) {\n t.a = f.a;\n t.b = f.b;\n t.c = f.c;\n t.d = f.d;\n return t;\n }\n}\n\n\n/* The following is non-inverted tyche, which has better internal\n * bit diffusion, but which is about 25% slower than tyche-i in JS.\n *\n\nclass TycheiGenAlt extends TycheiGen {\n next() {\n let {a,b,c,d} = this\n a = (a + b | 0) >>> 0;\n d = d ^ a; d = d << 16 ^ d >>> 16;\n c = c + d | 0;\n b = b ^ c; b = b << 12 ^ d >>> 20;\n this.a = a = a + b | 0;\n d = d ^ a; this.d = d = d << 8 ^ d >>> 24;\n this.c = c = c + d | 0;\n b = b ^ c;\n return this.b = (b << 7 ^ b >>> 25);\n }\n}\n*/\n\n/*\nCopyright 2019 David Bau.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*/\nfunction prng_arc4(seed, opts) {\n let xg = new ARC4Gen(seed);\n let prng = () => xg.next();\n\n prng.double = prng;\n\n prng.int32 = () => xg.g(4) | 0;\n\n prng.quick = () => xg.g(4) / 0x100000000;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\n\n//\n// ARC4\n//\n// An ARC4 implementation. The constructor takes a key in the form of\n// an array of at most (width) integers that should be 0 <= x < (width).\n//\n// The g(count) method returns a pseudorandom integer that concatenates\n// the next (count) outputs from ARC4. Its return value is a number x\n// that is in the range 0 <= x < (width ^ count).\n//\n\n//\n// The following constants are related to IEEE 754 limits.\n//\n\n// const width = 256 // each RC4 output is 0 <= x < 256\n// const chunks = 6 // at least six RC4 outputs for each double\nconst _arc4_startdenom = 281474976710656; // 256 ** 6 == width ** chunks\nconst _arc4_significance = 4503599627370496; // 2 ** 52 significant digits in a double\nconst _arc4_overflow = 9007199254740992; // 2 ** 53 == significance * 2\n\n\nclass ARC4Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let key = this.mixkey(seed, []);\n let i,j,t, S=[], keylen = key.length;\n this.i = this.j = i = j = 0;\n this.S = S;\n\n // The empty key [] is treated as [0].\n if (!keylen) { key = [keylen++]; }\n\n // Set up S using the standard key scheduling algorithm.\n while (i <= 0xff) {\n S[i] = i++;\n }\n for (i = 0; i <= 0xff; i++) {\n S[i] = S[j = 0xff & (j + key[i % keylen] + (t = S[i]))];\n S[j] = t;\n }\n\n // For robust unpredictability, the function call below automatically\n // discards an initial batch of values. This is called RC4-drop[256].\n // See http://google.com/search?q=rsa+fluhrer+response&btnI\n this.g(256);\n }\n\n next() {\n // This function returns a random double in [0, 1) that contains\n // randomness in every bit of the mantissa of the IEEE 754 value.\n\n let n = this.g(6); // Start with a numerator n < 2 ^ 48\n let d = _arc4_startdenom; // and denominator d = 2 ^ 48.\n let x = 0; // and no 'extra last byte'.\n\n while (n < _arc4_significance) { // Fill up all significant digits (2 ** 52)\n n = (n + x) * 256; // by shifting numerator and\n d *= 256; // denominator and generating a\n x = this.g(1); // new least-significant-byte.\n }\n while (n >= _arc4_overflow) { // To avoid rounding past overflow, before adding\n n /= 2; // last byte, shift everything\n d /= 2; // right using integer math until\n x >>>= 1; // we have exactly the desired bits.\n }\n return (n + x) / d; // Form the number within [0, 1).\n }\n\n g(count) {\n // The \"g\" method returns the next (count) outputs as one number.\n let t, r = 0, {i,j,S} = this;\n while (count--) {\n t = S[i = 0xff & (i + 1)];\n r = r * 256 + S[0xff & ((S[i] = S[j = 0xff & (j + t)]) + (S[j] = t))];\n }\n this.i = i;\n this.j = j;\n return r;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.j = f.j;\n t.S = [... f.S];\n return t;\n }\n\n mixkey(seed, key) {\n seed = seed + '';\n let smear=0, j=0;\n while (j < seed.length) {\n key[0xff & j] =\n 0xff & ((smear ^= key[0xff & j] * 19) + seed.charCodeAt(j++));\n }\n return key\n }\n}\n\nexport { prng_alea, prng_arc4, prng_tychei, prng_xor128, prng_xor4096, prng_xorshift7, prng_xorwow };\n//# sourceMappingURL=index.mjs.map\n","import { usesRadians as runtimeUsesRadians } from \"./runtime.js\";\n\n// =============================================================================\n// Section: Randomness & Noise\n// =============================================================================\n\nimport { createNoise2D } from \"simplex-noise\";\nimport { prng_alea } from \"esm-seedrandom\";\n\n/**\n * A uniform PRNG function. Returns a float in [0,1).\n * @callback RNG\n * @returns {number}\n */\n/** @type {RNG} */\nlet rng = prng_alea(Math.random());\nlet rng2 = prng_alea(Math.random());\n\nconst _seedCallbacks = [];\n\n/**\n * Register a callback to be called whenever seed() is invoked.\n * Used internally by modules that maintain gaussian pools.\n * @param {Function} cb\n */\nexport const _onSeed = (cb) => _seedCallbacks.push(cb);\n\n/**\n * Seed the random number generator.\n * @param {number|string} s – The seed value.\n * @returns {void}\n */\nexport const seed = (s) => {\n rng = prng_alea(s);\n rng2 = prng_alea(`${s}:2`);\n for (const callback of _seedCallbacks) {\n callback();\n }\n};\n\n/**\n * Simplex‐noise 2D function.\n * @type {function(number, number): number}\n */\nexport let noise = createNoise2D(prng_alea(Math.random()));\nexport let noise2 = createNoise2D(prng_alea(Math.random()));\n\n/**\n * Seed the noise generator.\n * @param {number|string} s - The seed value.\n * @returns {void}\n */\nexport const noiseSeed = (s) => {\n noise = createNoise2D(prng_alea(s));\n noise2 = createNoise2D(prng_alea(`${s}:2`));\n};\n\n/**\n * Returns a random float in [min, max).\n * @param {number} [min=0]\n * @param {number} [max=1]\n * @returns {number}\n */\nexport const rr = (e = 0, r = 1) => e + rng() * (r - e);\nexport const rr2 = (e = 0, r = 1) => e + rng2() * (r - e);\n\n/**\n * Selects a random element from an array.\n * @param {T[]} array - Input array.\n * @returns {T}\n */\nexport const rArray = (array) => array[~~(rng() * array.length)];\n\n/**\n * Returns a random integer in [min, max).\n * @param {number} min\n * @param {number} max\n * @returns {number}\n */\nexport const randInt = (e, r) => ~~rr(e, r);\nexport const randInt2 = (e, r) => ~~rr2(e, r);\n\n/**\n * Gaussian (normal) random sample N(mean, stdev²).\n * @param {number} [mean=0]\n * @param {number} [stdev=1]\n * @returns {number}\n */\nexport const gaussian = (mean = 0, stdev = 1) => {\n const u = 1 - rng();\n const v = rng();\n const z = Math.sqrt(-2.0 * Math.log(u)) * cos(360 * v);\n return z * stdev + mean;\n};\n\n/**\n * Picks a key from an object according to weighted probabilities.\n * @param {Object<string|number, number>} weights\n * @returns {string|number}\n */\nexport const weightedRand = (weights) => {\n let totalWeight = 0;\n const entries = [];\n\n // Build cumulative weights array\n for (const key in weights) {\n totalWeight += weights[key];\n entries.push({ key, cumulative: totalWeight });\n }\n\n // Get a random number between 0 and totalWeight\n const rnd = rng() * totalWeight;\n\n // Pick the first entry where rnd is less than the cumulative weight\n for (const { key, cumulative } of entries) {\n if (rnd < cumulative) {\n return isNaN(key) ? key : parseInt(key);\n }\n }\n};\n\n// =============================================================================\n// Section: Numeric Mapping & Constraints\n// =============================================================================\n\n/**\n * Maps a value from range [a,b] to [c,d], optionally clamped.\n * @param {number} value\n * @param {number} a\n * @param {number} b\n * @param {number} c\n * @param {number} d\n * @param {boolean} [withinBounds=false]\n * @returns {number}\n */\nexport const map = (value, a, b, c, d, withinBounds = false) => {\n let r = c + ((value - a) / (b - a)) * (d - c);\n if (!withinBounds) return r;\n if (c < d) return constrain(r, c, d);\n else return constrain(r, d, c);\n};\n\n/**\n * Constrains a number within the provided bounds.\n * @param {number} n - The number.\n * @param {number} low - Lower bound.\n * @param {number} high - Upper bound.\n * @returns {number} The constrained number.\n */\nexport const constrain = (n, low, high) => Math.max(Math.min(n, high), low);\n\n// =============================================================================\n// Section: Trigonometry\n// =============================================================================\n\n/**\n * Normalize an angle in degrees to [0,360).\n * @param {number} angle\n * @returns {number}\n */\nconst nAngle = (angle) => {\n angle = angle % 360;\n return angle < 0 ? angle + 360 : angle;\n};\n\n// number of discrete steps (360° × 4 samples per degree)\nconst totalDegrees = 1440;\nconst radiansPerIndex = (2 * Math.PI) / totalDegrees;\n\n// lazy‐initialized lookup tables\nconst cLookup = new Float32Array(totalDegrees).fill(NaN);\nconst sLookup = new Float32Array(totalDegrees).fill(NaN);\n\n/**\n * Cosine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const cos = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = cLookup[idx];\n if (isNaN(v)) {\n v = Math.cos(idx * radiansPerIndex);\n cLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Sine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const sin = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = sLookup[idx];\n if (isNaN(v)) {\n v = Math.sin(idx * radiansPerIndex);\n sLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Converts radians to degrees, normalized to [0,360).\n * @param {number} rad\n * @returns {number}\n */\nexport const toDegrees = (rad, isRad = false) => {\n if (isRad || runtimeUsesRadians()) {\n let angle = ((rad * 180) / Math.PI) % 360;\n return angle < 0 ? angle + 360 : angle;\n } else {\n return rad;\n }\n};\n\n/**\n * Converts radians to degrees without wrapping the result.\n * Preserves signed angles so downstream scaling keeps its direction.\n * @param {number} angle\n * @param {boolean} [isRad=false]\n * @returns {number}\n */\nexport const toDegreesSigned = (angle, isRad = false) =>\n isRad || runtimeUsesRadians()\n ? (angle * 180) / Math.PI\n : angle;\n\n// =============================================================================\n// Section: Geometry & Transforms\n// =============================================================================\n\n/**\n * Rotates point (x,y) around center (cx,cy) by angle degrees.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x\n * @param {number} y\n * @param {number} angle - Degrees\n * @returns {{x:number,y:number}}\n */\nexport const rotate = (cx, cy, x, y, angle) => {\n let coseno = cos(angle),\n seno = sin(angle),\n nx = coseno * (x - cx) + seno * (y - cy) + cx,\n ny = coseno * (y - cy) - seno * (x - cx) + cy;\n return { x: nx, y: ny };\n};\n\n/**\n * Euclidean distance between two points.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const dist = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1);\n\n/**\n * Angle in degrees between two points, measured clockwise from +X.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const calcAngle = (x1, y1, x2, y2) =>\n toDegrees(Math.atan2(-(y2 - y1), x2 - x1), true);\n\n/**\n * Intersection of two line segments, or false if none.\n * @param {{x:number,y:number}} s1a\n * @param {{x:number,y:number}} s1b\n * @param {{x:number,y:number}} s2a\n * @param {{x:number,y:number}} s2b\n * @param {boolean} [includeSegmentExtension=false]\n * @returns {{x:number,y:number}|false}\n */\nexport const intersectLines = (\n s1a,\n s1b,\n s2a,\n s2b,\n includeSegmentExtension = false\n) => {\n // Extract coordinates from points\n let x1 = s1a.x,\n y1 = s1a.y;\n let x2 = s1b.x,\n y2 = s1b.y;\n let x3 = s2a.x,\n y3 = s2a.y;\n let x4 = s2b.x,\n y4 = s2b.y;\n // Early return if line segments are points or if the lines are parallel\n if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) {\n return false; // Segments are points\n }\n let deltaX1 = x2 - x1,\n deltaY1 = y2 - y1;\n let deltaX2 = x4 - x3,\n deltaY2 = y4 - y3;\n let denominator = deltaY2 * deltaX1 - deltaX2 * deltaY1;\n if (denominator === 0) {\n return false; // Lines are parallel\n }\n // Calculate the intersection point\n let ua = (deltaX2 * (y1 - y3) - deltaY2 * (x1 - x3)) / denominator;\n let ub = (deltaX1 * (y1 - y3) - deltaY1 * (x1 - x3)) / denominator;\n // Check if the intersection is within the bounds of the line segments\n if (!includeSegmentExtension && (ub < 0 || ub > 1)) {\n return false;\n }\n // Calculate the intersection coordinates\n let x = x1 + ua * deltaX1;\n let y = y1 + ua * deltaY1;\n return { x: x, y: y };\n};\n","// =============================================================================\n// Target Runtime Hooks\n// =============================================================================\n\n/**\n * Shared target state exposed to core modules.\n *\n * Host adapters are expected to keep these bindings updated with the currently\n * active drawing target. The exact object type is adapter-defined, but core code\n * assumes the active renderer exposes:\n * - `drawingContext`: the active WebGL context\n * - target dimensions through `Cwidth` / `Cheight`\n * - pixel density through `Density`\n */\n\nexport let Cwidth, Cheight, Instance, Renderer, Density;\n\nlet targetRuntime = {\n load: () => {\n throw new Error(\"No target runtime adapter registered.\");\n },\n syncDensity: () => Density,\n isCanvasReady: () => {\n throw new Error(\"No target runtime adapter registered.\");\n },\n instance: (inst) => {\n Instance = inst;\n },\n activateInstance: (inst) => {\n Instance = inst;\n },\n deactivateInstance: () => {},\n getActiveFramebuffer: () => null,\n isFramebufferTarget: () => false,\n};\n\n/**\n * Updates the shared target state consumed by core modules.\n *\n * @param {object} state\n */\nexport function setTargetState(state) {\n if (\"Cwidth\" in state) Cwidth = state.Cwidth;\n if (\"Cheight\" in state) Cheight = state.Cheight;\n if (\"Instance\" in state) Instance = state.Instance;\n if (\"Renderer\" in state) Renderer = state.Renderer;\n if (\"Density\" in state) Density = state.Density;\n}\n\n/**\n * Registers or updates host target hooks used by core modules.\n *\n * @param {object} hooks\n */\nexport function setTargetRuntime(hooks) {\n targetRuntime = { ...targetRuntime, ...hooks };\n}\n\nexport const load = (buffer = false) => targetRuntime.load(buffer);\nexport const syncDensity = () => targetRuntime.syncDensity();\nexport const isCanvasReady = () => targetRuntime.isCanvasReady();\nexport const instance = (inst) => targetRuntime.instance(inst);\nexport const activateInstance = (inst) => targetRuntime.activateInstance(inst);\nexport const deactivateInstance = () => targetRuntime.deactivateInstance();\nexport const getActiveFramebuffer = () => targetRuntime.getActiveFramebuffer();\nexport const isFramebufferTarget = (target) =>\n targetRuntime.isFramebufferTarget(target);\n","// =============================================================================\n// Module: Dirty Rect Utilities\n// =============================================================================\n/**\n * Expands a dirty rectangle outward by a constant padding value.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Rect to expand.\n * @param {number} [padding=0] - Padding in pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Expanded rect.\n */\nexport const expandDirtyRect = (rect, padding = 0) =>\n rect\n ? {\n minX: rect.minX - padding,\n minY: rect.minY - padding,\n maxX: rect.maxX + padding,\n maxY: rect.maxY + padding,\n }\n : null;\n\n/**\n * Clamps a dirty rectangle to explicit target bounds.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Candidate rect.\n * @param {number} width - Target width in physical pixels.\n * @param {number} height - Target height in physical pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Clamped rect.\n */\nexport const normalizeDirtyRect = (rect, width, height) => {\n if (!rect) return null;\n\n const minX = Math.max(0, Math.floor(Math.min(rect.minX, rect.maxX)));\n const minY = Math.max(0, Math.floor(Math.min(rect.minY, rect.maxY)));\n const maxX = Math.min(width, Math.ceil(Math.max(rect.minX, rect.maxX)));\n const maxY = Math.min(height, Math.ceil(Math.max(rect.minY, rect.maxY)));\n\n if (maxX <= minX || maxY <= minY) return null;\n\n return { minX, minY, maxX, maxY };\n};\n\n/**\n * Returns the union of two dirty rectangles.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} a - First rect.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} b - Second rect.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Union rect.\n */\nexport const unionDirtyRect = (a, b) => {\n if (!a) return b;\n if (!b) return a;\n\n return {\n minX: Math.min(a.minX, b.minX),\n minY: Math.min(a.minY, b.minY),\n maxX: Math.max(a.maxX, b.maxX),\n maxY: Math.max(a.maxY, b.maxY),\n };\n};\n\n/**\n * Returns a dirty rectangle covering the full target bounds.\n *\n * @param {number} width - Target width in physical pixels.\n * @param {number} height - Target height in physical pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}} Full-target rect.\n */\nexport const getFullDirtyRect = (width, height) => ({\n minX: 0,\n minY: 0,\n maxX: width,\n maxY: height,\n});\n","// =============================================================================\n// Compositor Runtime Hooks\n// =============================================================================\n\n/**\n * Shared compositor helpers and host hooks.\n *\n * The shared code in this module assumes framebuffer-like targets expose:\n * - `framebuffer`: native WebGL framebuffer handle\n * - optional lifecycle methods supplied by the host adapter\n *\n * Higher-level core modules also attach their own bookkeeping fields onto the\n * active renderer and mask targets, such as:\n * - `shaderProgram`\n * - `blendSourceFramebuffer`\n * - `glMask`\n * - `fillMaskFramebuffer`\n * - `mask`\n *\n * These are library-level contract fields, not host-specific internals.\n */\n\nexport const create2DCanvas = (width, height, willReadFrequently = false) => {\n const canvas =\n typeof OffscreenCanvas !== \"undefined\"\n ? new OffscreenCanvas(width, height)\n : (() => {\n const element = document.createElement(\"canvas\");\n element.width = width;\n element.height = height;\n return element;\n })();\n canvas.drawingContext = canvas.getContext(\n \"2d\",\n willReadFrequently ? { willReadFrequently: true } : undefined,\n );\n return canvas;\n};\n\nexport const get2DContext = (canvas, willReadFrequently = false) => {\n canvas.drawingContext ??= canvas.getContext(\n \"2d\",\n willReadFrequently ? { willReadFrequently: true } : undefined,\n );\n return canvas.drawingContext;\n};\n\nexport function blitDefaultFramebufferSource({\n renderer,\n sourceFramebuffer,\n dirtyRect,\n getTargetPixelSize,\n toScissorBox,\n}) {\n const gl = renderer.drawingContext;\n const { width, height } = getTargetPixelSize();\n const sourceBox = dirtyRect ? toScissorBox(dirtyRect) : null;\n const previousReadFramebuffer = gl.getParameter(gl.READ_FRAMEBUFFER_BINDING);\n const previousDrawFramebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING);\n\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, sourceFramebuffer.framebuffer);\n gl.blitFramebuffer(\n sourceBox?.x ?? 0,\n sourceBox?.y ?? 0,\n sourceBox ? sourceBox.x + sourceBox.width : width,\n sourceBox ? sourceBox.y + sourceBox.height : height,\n sourceBox?.x ?? 0,\n sourceBox?.y ?? 0,\n sourceBox ? sourceBox.x + sourceBox.width : width,\n sourceBox ? sourceBox.y + sourceBox.height : height,\n gl.COLOR_BUFFER_BIT,\n gl.NEAREST,\n );\n\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, previousReadFramebuffer);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, previousDrawFramebuffer);\n\n return sourceFramebuffer;\n}\n\nlet compositorRuntime = {\n clearTarget: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n ensureBlendShaderProgram: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n ensureBlendSourceFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n createFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n runBlendShaderPass: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n blitSourceToFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n};\n\n/**\n * Registers or updates host compositor hooks used by core compositing code.\n *\n * @param {object} hooks\n */\nexport function setCompositorRuntime(hooks) {\n compositorRuntime = { ...compositorRuntime, ...hooks };\n}\n\nexport const clearTarget = (...args) => compositorRuntime.clearTarget(...args);\nexport const ensureBlendShaderProgram = (...args) =>\n compositorRuntime.ensureBlendShaderProgram(...args);\nexport const ensureBlendSourceFramebuffer = (...args) =>\n compositorRuntime.ensureBlendSourceFramebuffer(...args);\nexport const createFramebuffer = (...args) =>\n compositorRuntime.createFramebuffer(...args);\nexport const runBlendShaderPass = (...args) =>\n compositorRuntime.runBlendShaderPass(...args);\nexport const blitSourceToFramebuffer = (...args) =>\n compositorRuntime.blitSourceToFramebuffer(...args);\n","import {\n Cwidth,\n Cheight,\n Renderer,\n Density,\n load as loadTarget,\n isCanvasReady,\n syncDensity,\n getActiveFramebuffer,\n isFramebufferTarget,\n} from \"./target.js\";\nimport {\n expandDirtyRect,\n normalizeDirtyRect as clampDirtyRect,\n unionDirtyRect,\n getFullDirtyRect as getFullRect,\n} from \"./dirty_rect.js\";\nimport {\n clearTarget as clearRenderTarget,\n ensureBlendShaderProgram,\n ensureBlendSourceFramebuffer,\n runBlendShaderPass,\n blitSourceToFramebuffer,\n} from \"./compositor_runtime.js\";\n\nimport vertSrc from \"./gl/shader.vert\";\nimport fragSrc from \"./gl/shader.frag\";\n\n// =============================================================================\n// Module: Configure and Initiate\n// =============================================================================\n/**\n * This module handles the configuration and initialization of the drawing system.\n * It manages canvas properties, ensures the system is ready for rendering, and\n * provides utilities for saving and restoring states.\n */\n\nlet strokeComposite = null;\nlet fillComposite = null;\n\nexport const registerStrokeComposite = (composite) => {\n strokeComposite = composite;\n};\n\nexport const registerFillComposite = (composite) => {\n fillComposite = composite;\n};\n\nconst clearTarget = (target) => {\n clearRenderTarget(Renderer, target, isFramebufferTarget);\n};\n\n// =============================================================================\n// Section: Dirty Rect Utilities\n// =============================================================================\n/**\n * Returns the current render target size in physical pixels.\n * @returns {{width: number, height: number}} Pixel size of the active target.\n */\nconst getTargetPixelSize = () => ({\n width: Math.max(1, Math.round(Cwidth * Density)),\n height: Math.max(1, Math.round(Cheight * Density)),\n});\n\nconst normalizeDirtyRect = (rect) => {\n if (!rect) return null;\n const { width, height } = getTargetPixelSize();\n return clampDirtyRect(rect, width, height);\n};\n\n/**\n * Returns a dirty rectangle covering the full active target.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}} Full-target rect.\n */\nconst getFullDirtyRect = () => {\n const { width, height } = getTargetPixelSize();\n return getFullRect(width, height);\n};\n\n// =============================================================================\n// Section: Scissor Helpers\n// =============================================================================\n/**\n * Converts a top-left-based dirty rectangle into a WebGL scissor box.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Dirty rect.\n * @returns {{x:number,y:number,width:number,height:number}|null} Scissor box or null.\n */\nconst toScissorBox = (rect, flipY = true) => {\n const normalized = normalizeDirtyRect(rect);\n if (!normalized) return null;\n\n const { height } = getTargetPixelSize();\n return {\n x: normalized.minX,\n y: flipY ? height - normalized.maxY : normalized.minY,\n width: normalized.maxX - normalized.minX,\n height: normalized.maxY - normalized.minY,\n };\n};\n\n/**\n * Runs a draw callback with a temporary scissor region.\n * @param {WebGL2RenderingContext} gl - Active WebGL context.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Dirty rect.\n * @param {Function} draw - Draw callback executed under the scissor box.\n */\nconst withScissor = (gl, rect, draw, flipY = true) => {\n const box = toScissorBox(rect, flipY);\n if (!box) {\n draw();\n return;\n }\n\n // Scissor is never nested in this module, so we can set/clear it directly\n // without saving previous GL state.\n gl.enable(gl.SCISSOR_TEST);\n gl.scissor(box.x, box.y, box.width, box.height);\n\n try {\n draw();\n } finally {\n gl.disable(gl.SCISSOR_TEST);\n }\n};\n\n/**\n * Stores the current state of the drawing system.\n * Can be used to save and restore configurations or canvas states.\n */\nexport const State = {};\n/**\n * Handles color blending using WebGL shaders. Implements advanced blending\n * effects based on Kubelka-Munk theory. Relies on spectral.js for blending logic.\n */\n\n// =============================================================================\n// Section: Color Blending / Rendering\n// =============================================================================\n/**\n * Ensures the Mix object is initialized and ready for blending.\n */\nexport const isMixReady = () => {\n if (!Renderer?.loaded) {\n isCanvasReady();\n Mix.load();\n }\n};\n\n/**\n * Manages blending operations with WebGL shaders.\n * @property {boolean} loaded - Indicates if shaders are loaded.\n * @property {boolean} isBlending - Indicates if blending is active.\n * @property {object} currentColor - Current color in WebGL format.\n * @property {function} load - Initializes blending resources.\n * @property {function} blend - Applies blending effects.\n */\nexport const Mix = {\n isBlending: false,\n cachedColor: null,\n\n /**\n * Merges a new dirty rectangle into the target's accumulated draw bounds.\n * @param {object} target - Mask buffer receiving draw output.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Rect to merge.\n */\n markDirtyRect(target, rect) {\n const normalized = normalizeDirtyRect(rect);\n if (!target || !normalized) return;\n target.dirtyRect = unionDirtyRect(target.dirtyRect, normalized);\n target.isDrawn = true;\n },\n\n /**\n * Clears a mask buffer and resets its dirty-rect tracking.\n * @param {object} target - Mask buffer to reset.\n */\n clearMask(target) {\n if (!target) return;\n const composite = target === this.glMask ? strokeComposite : fillComposite;\n composite?.clearMask?.(target, clearTarget);\n },\n\n /**\n * Resolves the region that should be composited back into the destination.\n * @param {object} target - Mask buffer being sampled.\n * @param {boolean} isBrushMask - True when compositing the GL brush mask.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\n getCompositeRect(target, isBrushMask) {\n const composite = isBrushMask ? strokeComposite : fillComposite;\n return composite?.getCompositeRect?.(\n target,\n getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n );\n },\n\n // =============================================================================\n // Section: Setup and load shaders\n // =============================================================================\n /**\n * Ensures the mask buffers and blend shader exist for the current renderer.\n */\n load() {\n syncDensity();\n const needsBlendSourceFramebuffer =\n !Renderer.blendSourceFramebuffer ||\n Renderer.blendSourceFramebuffer.width !== Cwidth ||\n Renderer.blendSourceFramebuffer.height !== Cheight ||\n (typeof Renderer.blendSourceFramebuffer.pixelDensity === \"function\" &&\n Renderer.blendSourceFramebuffer.pixelDensity() !== Density);\n ensureBlendShaderProgram(Renderer, vertSrc, fragSrc);\n\n this.glMask = strokeComposite?.ensureResources?.(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n );\n const fillResources = fillComposite?.ensureResources?.(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n clearTarget,\n ) ?? {\n mask: null,\n ctx: null,\n };\n\n if (needsBlendSourceFramebuffer) {\n Renderer.blendSourceFramebuffer = ensureBlendSourceFramebuffer(\n Renderer,\n Renderer.blendSourceFramebuffer,\n Cwidth,\n Cheight,\n Density,\n );\n }\n\n this.mask = fillResources.mask;\n this.ctx = fillResources.ctx;\n },\n\n // =============================================================================\n // Section: Compositing\n // =============================================================================\n /**\n * Flushes pending mask work when the blend color changes or a frame ends.\n * @param {Color|false} [_color=false] - New blend color.\n * @param {boolean} [_isLast=false] - True when this is the final blend flush.\n */\n blend(_color = false, _isLast = false) {\n isMixReady();\n // Only one mask is \"active\" for the current drawing mode; the other one\n // may still need flushing if the mode just changed mid-frame.\n const isBrushMask = this.isBrush === true;\n const mask = isBrushMask ? this.glMask : this.mask;\n const otherMask = isBrushMask ? this.mask : this.glMask;\n const nextColor = _color?._array;\n const colorChanged =\n !!nextColor &&\n (this.cachedColor?.[0] !== nextColor[0] ||\n this.cachedColor?.[1] !== nextColor[1] ||\n this.cachedColor?.[2] !== nextColor[2] ||\n this.cachedColor?.[3] !== nextColor[3]);\n if (!this.isBlending && nextColor) {\n this.isBlending = true;\n this.cachedColor = nextColor;\n // Reset the brush mask fully at the start of each blend cycle so stale\n // dirty-rect bookkeeping cannot leak an old stroke into the next color.\n this.clearMask(this.glMask);\n }\n\n if (_isLast || colorChanged) {\n if (this.justChanged) {\n this.applyShader(otherMask, !isBrushMask);\n this.justChanged = false;\n }\n if (this.isBlending) {\n this.applyShader(mask, isBrushMask);\n }\n if (nextColor) this.cachedColor = nextColor;\n if (_isLast) {\n this.isBlending = false;\n this.cachedColor = null;\n \n }\n }\n },\n\n /**\n * Runs the blend shader over a mask and composites the result into the active renderer.\n * @param {object} mask - Mask buffer to composite.\n * @param {boolean} isBrushMask - True when compositing the GL brush mask.\n */\n applyShader(mask, isBrushMask) {\n if (!mask?.isDrawn) return;\n\n const dirtyRect = this.getCompositeRect(mask, isBrushMask);\n if (!dirtyRect) {\n this.clearMask(mask);\n return;\n }\n\n const gl = Renderer.drawingContext;\n const shader = Renderer.shaderProgram;\n const activeFramebuffer = getActiveFramebuffer();\n const source = blitSourceToFramebuffer({\n renderer: Renderer,\n sourceTarget: activeFramebuffer ?? Renderer,\n sourceFramebuffer: Renderer.blendSourceFramebuffer,\n dirtyRect,\n isFramebufferTarget,\n Cwidth,\n Cheight,\n getTargetPixelSize,\n toScissorBox,\n withScissor,\n });\n const targetIsFramebuffer = !!activeFramebuffer;\n const composite = isBrushMask ? strokeComposite : fillComposite;\n const shaderMask = composite.getShaderMask(\n Renderer,\n mask,\n dirtyRect,\n getFullDirtyRect,\n clearTarget,\n );\n\n runBlendShaderPass({\n renderer: Renderer,\n shader,\n source,\n mask: shaderMask,\n color: this.cachedColor,\n isBrushMask,\n Cwidth,\n Cheight,\n dirtyRect,\n targetIsFramebuffer,\n withScissor,\n });\n this.clearMask(mask);\n },\n};\n\n/**\n * Flushes any pending stroke/fill mask work into the current target and resets\n * the shared compositor back to its initial idle state.\n */\nexport const flushActiveComposite = () => {\n isMixReady();\n Mix.blend(false, true);\n Mix.clearMask(Mix.glMask);\n Mix.clearMask(Mix.mask);\n Mix.justChanged = false;\n Mix.isBlending = false;\n Mix.isBrush = null;\n Mix.cachedColor = null;\n};\n\n/**\n * Loads and initializes the drawing target, then refreshes compositing\n * resources if the renderer was already active.\n *\n * @param {object|false} [buffer=false] - Optional offscreen target.\n */\nexport const load = (buffer = false) => {\n loadTarget(buffer);\n if (Renderer.loaded) Mix.load();\n};\n","import { Cwidth, Cheight } from \"./target.js\";\nimport { isMixReady, State } from \"./color.js\";\nimport { randInt2, noise2, rr2, sin, cos, map, toDegreesSigned } from \"./utils.js\";\nimport { getAffineMatrix } from \"./runtime.js\";\n\n// =============================================================================\n// Section: Matrix transformations\n// =============================================================================\n\n// =============================================================================\n// Section: Field Initialization\n// =============================================================================\n\nlet isLoaded = false;\n\n/**\n * Ensures the field system is initialized and ready for use.\n * If the field is not loaded, it initializes the mixing system and creates the field.\n */\nexport function isFieldReady() {\n if (!isLoaded) {\n isMixReady(); // Ensure the mixing system is ready\n createField(); // Initialize the field\n isLoaded = true;\n }\n}\n\n// =============================================================================\n// Section: Position Class\n// =============================================================================\n\n/**\n * The Position class represents a point within a two-dimensional space, which can interact with a vector field.\n * It provides methods to update the position based on the field's flow and to check whether the position is\n * within certain bounds (e.g., within the field or canvas).\n */\nexport class Position {\n /**\n * Constructs a new Position instance.\n * @param {number} x - The initial x-coordinate.\n * @param {number} y - The initial y-coordinate.\n */\n constructor(x, y) {\n isFieldReady();\n const m = getAffineMatrix();\n this.mx = m.x;\n this.my = m.y;\n this.update(x, y);\n this.plotted = 0; // Tracks the total distance plotted\n }\n\n /**\n * Updates the position's coordinates and calculates its offsets and indices within the flow field.\n * @param {number} x - The new x-coordinate.\n * @param {number} y - The new y-coordinate.\n */\n update(x, y) {\n this.x = x;\n this.y = y;\n if (State.field.isActive) {\n this.colIdx = Math.round((x + this.mx - left_x) / resolution);\n this.rowIdx = Math.round((y + this.my - top_y) / resolution);\n }\n }\n\n /**\n * Resets the 'plotted' property to 0.\n */\n reset() {\n this.plotted = 0;\n }\n\n /**\n * Checks if the position is within the active flow field's bounds.\n * @returns {boolean} - True if the position is within the flow field, false otherwise.\n */\n isIn() {\n return State.field.isActive\n ? Position.isIn(this.colIdx, this.rowIdx)\n : this.isInCanvas(this.x, this.y);\n }\n\n /**\n * Checks if the position is within the canvas bounds (with a margin).\n * @returns {boolean} - True if the position is within bounds, false otherwise.\n */\n isInCanvas() {\n const margin = 0.3;\n const w = Cwidth;\n const h = Cheight;\n const x = this.x + this.mx;\n const y = this.y + this.my;\n return (\n x >= -margin * w &&\n x <= (1 + margin) * w &&\n y >= -margin * h &&\n y <= (1 + margin) * h\n );\n }\n\n /**\n * Calculates the angle of the flow field at the position's current coordinates.\n * @returns {number} - The internal flow angle in degrees, or 0 if the position is not in the field or if no field is active.\n */\n angle(skipCheck = false) {\n if (!State.field.isActive) return 0;\n return (skipCheck || this.isIn())\n ? flow_field()[this.colIdx][this.rowIdx] * State.field.wiggle\n : 0;\n }\n\n /**\n * Moves the position along the flow field by a certain length.\n * @param {number} _dir - The direction of movement, interpreted using the current runtime angle units.\n * @param {number} _length - The length to move along the field.\n * @param {number} _step_length - The length of each step.\n */\n moveTo(_dir, _length, _step_length = 1) {\n this.movePos(toDegreesSigned(_dir), _length, _step_length);\n }\n\n /**\n * Internal variant of moveTo() that expects a degree value already normalized to the library's internal representation.\n */\n _moveToDegrees(_dir, _length, _step_length = 1) {\n this.movePos(_dir, _length, _step_length);\n }\n\n /**\n * Plots a point to another position within the flow field, following a Plot object\n * @param {Position} _plot - The Plot path object.\n * @param {number} _length - The length to move towards the target position.\n * @param {number} _step_length - The length of each step.\n * @param {number} _scale - The scaling factor for the plotting path.\n */\n plotTo(_plot, _length, _step_length, _scale = 1, precomputedAngle = undefined) {\n this.movePos(_plot, _length, _step_length, _scale, precomputedAngle);\n }\n\n movePos(_dirPlot, _length, _step, _scale = false, precomputedAngle = undefined) {\n const scaleFactor = _scale || 1;\n if (!this.isIn()) {\n this.plotted += _step / scaleFactor;\n return;\n }\n const steps = _length / _step;\n const fieldActive = State.field.isActive;\n const usePlot = !!_scale;\n for (let i = 0; i < steps; i++) {\n const plotAngle = (usePlot && precomputedAngle !== undefined && i === 0)\n ? precomputedAngle\n : (usePlot ? _dirPlot.angle(this.plotted) : _dirPlot);\n const angle = (fieldActive ? this.angle(true) : 0) - plotAngle;\n // Calculate new position\n this.update(this.x + _step * cos(angle), this.y + _step * sin(angle));\n this.plotted += _step / scaleFactor;\n }\n }\n\n // Static Methods\n\n /**\n * Gets the row index for a given y-coordinate.\n * @param {number} y - The y-coordinate.\n * @returns {number} - The row index.\n */\n static getRowIndex(y, d = 1) {\n const y_offset = y + getAffineMatrix().y - top_y;\n return Math.round(y_offset / resolution / d);\n }\n\n /**\n * Gets the column index for a given x-coordinate.\n * @param {number} x - The x-coordinate.\n * @returns {number} - The column index.\n */\n static getColIndex(x, d = 1) {\n const x_offset = x + getAffineMatrix().x - left_x;\n return Math.round(x_offset / resolution / d);\n }\n\n /**\n * Checks if a column and row index are within the flow field bounds.\n * @param {number} col - The column index.\n * @param {number} row - The row index.\n * @returns {boolean} - True if the indices are within bounds, false otherwise.\n */\n static isIn(col, row) {\n return col >= 0 && row >= 0 && col < num_columns && row < num_rows;\n }\n}\n\n// =============================================================================\n// Section: VectorField\n// =============================================================================\n\n/**\n * Represents the state of the vector field.\n * @property {boolean} isActive - Indicates if the vector field is active.\n * @property {string|null} current - The name of the currently active vector field.\n */\nState.field = {\n isActive: false,\n current: null,\n wiggle: 1,\n};\n\n// Internal variables for field configuration\nlet list = new Map();\nlet resolution, left_x, top_y, num_columns, num_rows;\nconst FIELD_ANGLE_MODES = new Set([\"degrees\", \"radians\"]);\n\n/**\n * Initializes the field grid and sets up the vector field's structure based on the renderer's dimensions.\n */\nfunction createField() {\n resolution = Cwidth * 0.01; // Determine the resolution of the field grid\n left_x = -0.5 * Cwidth; // Left boundary of the field\n top_y = -0.5 * Cheight; // Top boundary of the field\n num_columns = Math.round((2 * Cwidth) / resolution); // Number of columns in the grid\n num_rows = Math.round((2 * Cheight) / resolution); // Number of columns in the grid\n addStandard(); // Add default vector field\n}\n\n/**\n * Retrieves the field values for the current vector field.\n * @returns {Float32Array[]} The current vector field grid.\n */\nfunction flow_field() {\n return list.get(State.field.current).field;\n}\n\nfunction normalizeFieldAngleMode(options = {}) {\n const config =\n typeof options === \"string\" ? { angleMode: options } : options || {};\n const angleMode = config.angleMode ?? \"degrees\";\n\n if (!FIELD_ANGLE_MODES.has(angleMode)) {\n throw new Error(\n `Invalid field angle mode \"${angleMode}\". Use \"degrees\" or \"radians\".`,\n );\n }\n\n return angleMode;\n}\n\nfunction normalizeFieldAngles(field, angleMode) {\n if (angleMode !== \"radians\") return field;\n\n for (let c = 0; c < field.length; c++) {\n for (let r = 0; r < field[c].length; r++) {\n field[c][r] = toDegreesSigned(field[c][r], true);\n }\n }\n\n return field;\n}\n\nfunction generateField(entry, t) {\n return normalizeFieldAngles(entry.gen(t, genField()), entry.angleMode);\n}\n\n/**\n * Regenerates the current vector field using its associated generator function.\n * @param {number} [t=0] - An optional time parameter that can affect field generation.\n */\nexport function refreshField(t = 0) {\n if (!State.field.isActive || !State.field.current) {\n throw new Error(\n \"No field is currently active. Call brush.field('name') to activate one before refreshing.\",\n );\n }\n const currentField = list.get(State.field.current);\n currentField.field = generateField(currentField, t);\n}\n\n/**\n * Generates an empty field array.\n * Reuses existing arrays to reduce memory allocation overhead.\n * @returns {Float32Array[]} Empty vector field grid.\n */\nfunction genField() {\n return new Array(num_columns)\n .fill(null)\n .map(() => new Float32Array(num_rows));\n}\n\n/**\n * Activates a specific vector field by name, ensuring it's ready for use.\n * @param {string} a - The name of the vector field to activate.\n */\nexport function field(a) {\n if (!State.field.wiggle) {\n State.field.wiggle = 1;\n } // Set default wiggle value\n isFieldReady();\n if (!list.has(a)) {\n throw new Error(\n `Field \"${a}\" does not exist. Available fields: ${Array.from(list.keys()).join(\", \")}.`,\n );\n }\n State.field.isActive = true;\n State.field.current = a;\n const entry = list.get(a);\n if (!entry.field) entry.field = generateField(entry, 0);\n}\n\n/**\n * Deactivates the current vector field.\n */\nexport function noField() {\n isFieldReady();\n State.field.isActive = false;\n}\n\n/**\n * Adds a new vector field to the field list with a unique name and a generator function.\n * @param {string} name - The unique name for the new vector field.\n * @param {Function} funct - The function that generates the field values.\n * @param {object} [options] - Optional field configuration.\n * @param {\"degrees\"|\"radians\"} [options.angleMode=\"degrees\"] - How the generator's output angles should be interpreted.\n */\nexport function addField(name, funct, options = {}) {\n list.set(name, {\n gen: funct,\n field: null,\n angleMode: normalizeFieldAngleMode(options),\n });\n}\n\n/**\n * Retrieves a list of all available vector field names.\n * @returns {string[]} An array of all the field names.\n */\nexport function listFields() {\n isFieldReady();\n return Array.from(list.keys());\n}\n\nexport function wiggle(a = 1) {\n field(\"hand\");\n State.field.wiggle = a;\n}\n\n/**\n * Fills every cell of a field grid using a callback (c, r) => angle.\n */\nfunction fillField(field, fn) {\n for (let c = 0; c < num_columns; c++)\n for (let r = 0; r < num_rows; r++) field[c][r] = fn(c, r);\n return field;\n}\n\n/**\n * Adds standard predefined vector fields to the list with unique behaviors.\n */\nfunction addStandard() {\n // Organic noise — basis for brush.wiggle()\n addField(\"hand\", (t, field) => {\n const bs = rr2(0.2, 0.8),\n ba = randInt2(5, 10);\n return fillField(field, (c, r) => {\n const angle = 0.5 * ba * sin(bs * r * c + randInt2(15, 25));\n return 0.2 * angle * cos(t) + noise2(c, r) * ba * 0.7;\n });\n });\n // Smooth large-scale noise curves\n addField(\"curved\", (t, field) => {\n let ar = randInt2(-10, 10);\n if (randInt2(0, 100) % 2 == 0) ar *= -1;\n return fillField(\n field,\n (c, r) =>\n 3 * map(noise2(c * 0.02 + t * 0.03, r * 0.02 + t * 0.03), 0, 1, -ar, ar),\n );\n });\n // Sharp alternating angles per cell — herringbone / wicker look\n addField(\"zigzag\", (t, field) => {\n let ar = randInt2(-30, -15) + Math.abs(44 * sin(t));\n if (randInt2(0, 100) % 2 == 0) ar *= -1;\n let dif = ar,\n angle = 0;\n for (let c = 0; c < num_columns; c++) {\n for (let r = 0; r < num_rows; r++) {\n field[c][r] = angle;\n angle += dif;\n dif *= -1;\n }\n angle += dif;\n dif *= -1;\n }\n return field;\n });\n // Sinusoidal wave bands\n addField(\"waves\", (t, field) => {\n const sr = randInt2(10, 15) + 5 * sin(t),\n cr = randInt2(3, 6) + 3 * cos(t),\n ba = randInt2(20, 35);\n return fillField(\n field,\n (c, r) => sin(sr * c) * ba * cos(r * cr) + randInt2(-3, 3),\n );\n });\n // Dense oscillation from row×col product\n addField(\"seabed\", (t, field) => {\n const bs = rr2(0.4, 0.8),\n ba = randInt2(18, 26);\n return fillField(\n field,\n (c, r) => 1.1 * ba * sin(bs * r * c + randInt2(15, 20)) * cos(t),\n );\n });\n // Radial vortex — angles spiral around the field centre\n addField(\"spiral\", (_t, field) => {\n const n = randInt2(5, 10);\n const dir = randInt2(0, 2) * 2 - 1;\n const offset = randInt2(65, 80); // <90 = inward spiral\n const attractors = Array.from({ length: n }, () => ({\n x: rr2(0.1, 0.9) * num_columns,\n y: rr2(0.1, 0.9) * num_rows,\n }));\n return fillField(field, (c, r) => {\n let wx = 0,\n wy = 0;\n for (const att of attractors) {\n const dx = c - att.x,\n dy = r - att.y;\n const w = 1 / (dx * dx + dy * dy + 1);\n const a = Math.atan2(dy, dx) * (180 / Math.PI);\n const angle = (dir * (a + offset) * Math.PI) / 180;\n wx += w * Math.cos(angle);\n wy += w * Math.sin(angle);\n }\n return Math.atan2(wy, wx) * (180 / Math.PI);\n });\n });\n // Column-banded stripes — parallel rake marks\n addField(\"columns\", (_t, field) => {\n const freq = randInt2(3, 8),\n amp = randInt2(25, 45);\n return fillField(field, (c, _r) => sin(c * freq) * amp);\n });\n}\n","import { State } from \"./color.js\";\nimport { intersectLines } from \"./utils.js\";\n\n// =============================================================================\n// Section: Polygon Class\n// =============================================================================\n\n/**\n * Represents a polygon with a set of vertices and provides methods for\n * intersection, drawing, filling, and hatching.\n */\nexport class Polygon {\n /**\n * Constructs the Polygon object from an array of points.\n * @param {Array} pointsArray - An array of points, where each point is an array of two numbers [x, y].\n * @param {boolean} [useRawVertices=false] - If true, uses the raw array as vertices.\n */\n constructor(pointsArray, useRawVertices = false) {\n this.a = pointsArray;\n this.vertices = useRawVertices\n ? pointsArray\n : pointsArray.map(([x, y]) => ({ x, y }));\n this.sides = this.vertices.map((v, i, arr) => [\n v,\n arr[(i + 1) % arr.length],\n ]);\n this._intersectionCache = {}; // Cache for intersection results\n }\n\n /**\n * Intersects a given line with the polygon, returning all intersection points.\n * @param {Object} line - The line to intersect with the polygon, having two properties 'point1' and 'point2'.\n * @returns {Array} An array of intersection points (each with 'x' and 'y' properties) or an empty array if no intersections.\n */\n intersect(line) {\n // Check if the result has been cached\n const cacheKey = `${line.point1.x},${line.point1.y}-${line.point2.x},${line.point2.y}`;\n if (this._intersectionCache[cacheKey]) {\n return this._intersectionCache[cacheKey];\n }\n const points = [];\n for (const [start, end] of this.sides) {\n const intersection = intersectLines(line.point1, line.point2, start, end);\n if (intersection) points.push(intersection);\n }\n this._intersectionCache[cacheKey] = points; // Cache the result\n return points;\n }\n\n /**\n * Displays the polygon with optional stroke, hatch, and fill effects.\n */\n show() {\n if (State.wash) this.wash();\n if (State.fill) this.fill();\n if (State.mass) this.mass();\n if (State.hatch) this.hatch();\n if (State.stroke) this.draw();\n }\n}","import { Cwidth, Cheight } from \"./target.js\";\nimport { State } from \"./color.js\";\nimport { toDegrees, map, rr2 } from \"./utils.js\";\nimport { Position, isFieldReady } from \"./flowfield.js\";\nimport { Polygon } from \"./polygon.js\";\n\n// =============================================================================\n// Section: Plot Class\n// =============================================================================\n\n/**\n * The Plot class represents a collection of segments that define shapes or paths.\n * It supports operations like adding segments, calculating angles and pressures,\n * and generating polygons based on the plot's structure.\n */\nexport class Plot {\n /**\n * Creates a new Plot.\n * @param {string} _type - The type of plot, \"curve\" or \"segments\".\n */\n constructor(_type) {\n this.segments = [];\n this.angles = [];\n this.pres = [];\n this.type = _type;\n this.dir = 0;\n this.calcIndex(0);\n this.pol = false;\n }\n\n /**\n * Adds a segment to the plot with specified angle, length, and pressure.\n * @param {number} _a - The angle of the segment.\n * @param {number} _length - The length of the segment.\n * @param {number} _pres - The pressure of the segment.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n addSegment(_a = 0, _length = 0, _pres = 1, _degrees = false) {\n if (this.angles.length > 0) this.angles.pop(); // Remove the last angle\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a); // Normalize angle\n this.angles.push(_a, _a); // Push angle twice for continuity\n this.pres.push(_pres);\n this.segments.push(_length);\n this.length = this.segments.reduce((sum, len) => sum + len, 0); // Update total length\n }\n\n /**\n * Finalizes the plot by setting the last angle and pressure.\n * @param {number} _a - The final angle.\n * @param {number} _pres - The final pressure.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n endPlot(_a = 0, _pres = 1, _degrees = false) {\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a);\n this.angles[this.angles.length - 1] = _a; // Update the last angle\n this.pres.push(_pres);\n }\n\n /**\n * Rotates the entire plot by a given angle.\n * @param {number} _a - The angle to rotate the plot.\n */\n rotate(_a) {\n this.dir = toDegrees(_a);\n }\n\n /**\n * Calculates the pressure at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated pressure.\n */\n pressure(_d) {\n // If the distance exceeds the plot length, return the last pressure\n if (_d > this.length) return this.pres[this.pres.length - 1];\n // Otherwise, calculate the pressure using the curving function\n return this.curving(this.pres, _d);\n }\n\n /**\n * Calculates the angle at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The calculated angle.\n */\n angle(_d) {\n // If the distance exceeds the plot length, return the last angle\n if (_d > this.length) return this.angles[this.angles.length - 1];\n // Calculate the index for the given distance\n this.calcIndex(_d);\n // Return the angle, adjusted for the plot type and direction\n return this.type === \"curve\"\n ? this.curving(this.angles, _d) + this.dir\n : this.angles[this.index] + this.dir;\n }\n\n /**\n * Interpolates values between segments for smooth transitions.\n * @param {Array<number>} array - The array to interpolate within.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated value.\n */\n curving(array, _d) {\n let map0 = array[this.index];\n let map1 = array[this.index + 1] ?? map0;\n if (Math.abs(map1 - map0) > 180) {\n if (map1 > map0) map1 = -(360 - map1);\n else map0 = -(360 - map0);\n }\n return map(_d - this.suma, 0, this.segments[this.index], map0, map1, true);\n }\n\n /**\n * Calculates the current index of the plot based on the distance.\n * @param {number} _d - The distance along the plot.\n */\n calcIndex(_d) {\n this.index = -1;\n this.suma = 0;\n let d = 0;\n while (d <= _d) {\n this.suma = d;\n d += this.segments[this.index + 1];\n this.index++;\n }\n return this.index;\n }\n\n /**\n * Generates a polygon based on the plot.\n * @param {number} _x - The x-coordinate for the starting point.\n * @param {number} _y - The y-coordinate for the starting point.\n * @param {number} _scale - The scale factor for the polygon.\n * @param {number} _side - The side factor for the polygon.\n * @returns {Polygon} - The generated polygon.\n */\n genPol(_x, _y, _scale = 1, _side) {\n isFieldReady(); // Ensure that the drawing environment is prepared\n const step = _side < 0 ? 4 : 1;\n const vertices = [];\n const numSteps = Math.round(this.length / step);\n const pos = new Position(_x + Cwidth / 2, _y + Cheight / 2);\n let pside = 0;\n let prevIdx = 0;\n\n for (let i = 0; i < numSteps; i++) {\n pos.plotTo(this, step, step);\n const idx = this.calcIndex(pos.plotted);\n pside += step;\n let maxSize = _side <= 0 ? 8 : Math.max(this.segments[idx] * _side * rr2(0.7, 1.3), 20);\n if ((pside >= maxSize || idx >= prevIdx) && pos.x) {\n vertices.push([pos.x - Cwidth / 2, pos.y - Cheight / 2]);\n pside = 0;\n if (idx >= prevIdx) prevIdx++;\n }\n }\n return new Polygon(vertices);\n }\n\n /**\n * Displays the plot with optional stroke, hatch, and fill effects.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\n show(x, y, scale = 1) {\n if (State.wash) this.wash(x, y, scale);\n if (State.fill) this.fill(x, y, scale);\n if (State.mass) this.mass(x, y, scale);\n if (State.hatch) this.hatch(x, y, scale);\n if (State.stroke) this.draw(x, y, scale);\n }\n}\n","import {\n rr2,\n randInt2,\n sin,\n cos,\n toDegreesSigned,\n constrain,\n dist,\n calcAngle,\n intersectLines,\n} from \"./utils.js\";\nimport { Polygon } from \"./polygon.js\";\nimport { Plot } from \"./plot.js\";\n\n// =============================================================================\n// Section: Primitives and Geommetry\n// =============================================================================\n\n/**\n * Creates a Polygon from an array of points and calls its show() method.\n * Polygons ignore fields and won't be good for fills and masses\n * @param {Array<Array<number>>} pointsArray - Array of points [x, y, pressure]\n */\nexport function polygon(pointsArray) {\n // Create a new Polygon instance\n const polygon = new Polygon(pointsArray);\n polygon.show();\n}\n\n/**\n * Draws a rectangle on the canvas using path functions.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} w - Width.\n * @param {number} h - Height.\n * @param {boolean} [mode=\"corner\"] - \"corner\" (default) or \"center\".\n */\nexport function rect(x, y, w, h, mode = \"corner\") {\n if (mode === \"center\") {\n x -= w / 2;\n y -= h / 2;\n }\n beginShape(0);\n vertex(x, y);\n vertex(x + w, y);\n vertex(x + w, y + h);\n vertex(x, y + h);\n endShape(true);\n}\n\n/**\n * Draws a circle on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Circle radius.\n * @param {boolean} [r=false] - Randomizes segment lengths if true.\n */\nexport function circle(x, y, radius, r = false) {\n const p = new Plot(\"curve\");\n const arcLength = Math.PI * radius;\n const angleOffset = rr2(0, 360);\n const randomFactor = r ? () => 1 + r * 0.2 * rr2() : () => 1;\n\n // Divide circle into 4 segments\n for (let i = 0; i < 4; i++) {\n const angle = -90 * i + angleOffset;\n p.addSegment(\n angle * randomFactor(),\n (arcLength / 2) * randomFactor(),\n 1,\n true,\n );\n }\n\n // Optionally add a random final angle for the last segment\n if (r) {\n const randomAngle = r * randInt2(-5, 5);\n p.addSegment(\n angleOffset,\n Math.abs(randomAngle) * (Math.PI / 180) * radius,\n 1,\n true,\n );\n p.endPlot(randomAngle + angleOffset, 1, true);\n } else {\n p.endPlot(angleOffset, 1, true);\n }\n\n // Draw the circle\n const offsetX = x - radius * sin(angleOffset);\n const offsetY = y - radius * cos(-angleOffset);\n p.show(offsetX, offsetY, 1);\n}\n\n/**\n * Draws an arc on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Radius.\n * @param {number} start - Start angle in the current runtime angle units.\n * @param {number} end - End angle in the current runtime angle units.\n */\nexport function arc(x, y, radius, start, end) {\n const startDeg = toDegreesSigned(start);\n const endDeg = toDegreesSigned(end);\n const sweepDeg = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweepDeg === 0) return;\n\n const p = new Plot(\"curve\");\n const segmentCount = Math.max(1, Math.ceil(sweepDeg / 90));\n const segmentSweep = sweepDeg / segmentCount;\n const arcLength = (Math.PI * radius * segmentSweep) / 180;\n\n for (let i = 0; i < segmentCount; i++) {\n p.addSegment(startDeg + i * segmentSweep + 90, arcLength, 1, true);\n }\n p.endPlot(startDeg + sweepDeg + 90, 1, true);\n\n const startX = x + radius * cos(startDeg);\n const startY = y - radius * sin(startDeg);\n p.draw(startX, startY, 1);\n}\n\n// Variables for managing paths and strokes\nlet _current;\nlet _curvature;\n\nclass SubPath {\n constructor() {\n this.isClosed = false;\n this.curvature = _curvature;\n this.vert = [];\n }\n /**\n * Adds a vertex to this subpath.\n * @param {number} x\n * @param {number} y\n * @param {number} pressure\n */\n vertex(x, y, pressure) {\n this.vert.push([x, y, pressure]);\n }\n /**\n * Renders the subpath by creating a spline from its vertices.\n */\n show() {\n let plot = _createSpline(this.vert, this.curvature, this.isClosed);\n plot.show();\n }\n}\n\n/**\n * Begins a new path with a specified curvature.\n * @param {number} [curvature=0] - Curvature from 0 to 1.\n */\nexport function beginShape(curvature = 0) {\n _curvature = constrain(curvature, 0, 1);\n _current = new SubPath();\n}\n\n/**\n * Adds a line segment from the current point to the given coordinates.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} [pressure=1] - Pressure value.\n */\nexport function vertex(x, y, pressure = 1) {\n if (!_current) {\n throw new Error(\n \"vertex() called outside of beginShape()/endShape(). Call beginShape() first.\",\n );\n }\n _current.vertex(x, y, pressure);\n}\n\n/**\n * Ends the current path and renders all subpaths.\n */\nexport function endShape(close = false) {\n if (!_current) {\n throw new Error(\n \"endShape() called without beginShape(). Call beginShape() first.\",\n );\n }\n if (_current.vert.length < 2) {\n throw new Error(\n \"endShape() requires at least 2 vertices. Add more with vertex().\",\n );\n }\n if (close) {\n _current.vertex(..._current.vert[0]);\n _current.isClosed = true;\n }\n _current.show();\n _current = false;\n}\n\nlet _strokeArray, _strokeOrigin;\n\n/**\n * Begins a new stroke with a given type and starting position.\n * @param {string} type - Stroke type.\n * @param {number} x - Starting x.\n * @param {number} y - Starting y.\n */\nexport function beginStroke(type, x, y) {\n if (type !== \"curve\" && type !== \"segments\") {\n throw new Error(\n `beginStroke() type must be \"curve\" or \"segments\", got \"${type}\".`,\n );\n }\n _strokeOrigin = [x, y];\n _strokeArray = new Plot(type);\n}\n\n/**\n * Adds a segment to the stroke.\n * @param {number} angle - Segment angle.\n * @param {number} length - Segment length.\n * @param {number} pressure - Segment pressure.\n */\nexport function move(angle, length, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"move() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.addSegment(angle, length, pressure);\n}\n\n/**\n * Completes and renders the stroke.\n * @param {number} angle - End angle.\n * @param {number} pressure - End pressure.\n */\nexport function endStroke(angle, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"endStroke() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.endPlot(angle, pressure);\n _strokeArray.draw(_strokeOrigin[0], _strokeOrigin[1], 1);\n _strokeArray = false;\n}\n\n/**\n * Creates and draws a spline curve from an array of points.\n * @param {Array<Array<number>>} array_points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature from 0 to 1.\n */\nexport function spline(_array_points, _curvature = 0.5) {\n if (!_array_points || _array_points.length < 2) {\n throw new Error(\n \"spline() requires at least 2 points. Each point should be [x, y, pressure].\",\n );\n }\n let p = _createSpline(_array_points, _curvature);\n p.draw();\n}\n\n/**\n * Creates a new Plot object representing a spline curve.\n *\n * For curved segments (curvature > 0) with at least 3 points available,\n * the function either treats segments as straight (if their angles match)\n * or calculates control points to compute a circular arc.\n *\n * If no curvature is specified, a simple straight segment is used.\n *\n * @param {Array<Array<number>>} points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature value between 0 and 1.\n * @param {boolean} [close=false] - Whether to close the spline.\n * @returns {Plot} - The generated Plot object.\n */\nfunction _createSpline(points, curvature = 0.5, close = false) {\n const plotType = curvature === 0 ? \"segments\" : \"curve\";\n const p = new Plot(plotType);\n const PI2 = Math.PI * 2;\n\n // If closing the spline, add the second point to the end\n if (close && curvature !== 0) {\n points.push(points[1]);\n }\n\n if (points && points.length > 0) {\n let done = 0; // Tracks excess length from previous segment\n let pep, tep, pep2; // Variables used for initial calibration\n\n for (let i = 0; i < points.length - 1; i++) {\n // For curved segments (if curvature > 0 and there is at least 3 points ahead)\n if (curvature > 0 && i < points.length - 2) {\n const p1 = points[i];\n const p2 = points[i + 1];\n const p3 = points[i + 2];\n\n const d1 = dist(p1[0], p1[1], p2[0], p2[1]);\n const d2 = dist(p2[0], p2[1], p3[0], p3[1]);\n const a1 = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n const a2 = calcAngle(p2[0], p2[1], p3[0], p3[1]);\n\n // Compute the adjustment length based on curvature\n const curvAdjust = curvature * Math.min(d1, d2, 0.5 * Math.min(d1, d2));\n const dmax = Math.max(d1, d2);\n const s1 = d1 - curvAdjust;\n const s2 = d2 - curvAdjust;\n\n if (Math.floor(a1) === Math.floor(a2)) {\n // If angles are nearly the same, treat as a straight segment\n const temp = close ? (i === 0 ? 0 : d1 - done) : d1 - done;\n const temp2 = close ? (i === 0 ? 0 : d2 - pep2) : d2;\n\n p.addSegment(a1, temp, p1[2], true);\n if (i === points.length - 3) {\n p.addSegment(a2, temp2, p2[2], true);\n }\n\n done = 0;\n if (i === 0) {\n pep = d1;\n pep2 = curvAdjust;\n tep = points[1];\n done = 0;\n }\n } else {\n // For a curved segment, compute control points and arc segment details\n const point1 = {\n x: p2[0] - curvAdjust * cos(-a1),\n y: p2[1] - curvAdjust * sin(-a1),\n };\n const point2 = {\n x: point1.x + dmax * cos(-a1 + 90),\n y: point1.y + dmax * sin(-a1 + 90),\n };\n const point3 = {\n x: p2[0] + curvAdjust * cos(-a2),\n y: p2[1] + curvAdjust * sin(-a2),\n };\n const point4 = {\n x: point3.x + dmax * cos(-a2 + 90),\n y: point3.y + dmax * sin(-a2 + 90),\n };\n\n const intPt = intersectLines(point1, point2, point3, point4, true);\n const radius = dist(point1.x, point1.y, intPt.x, intPt.y);\n const halfDist = dist(point1.x, point1.y, point3.x, point3.y) / 2;\n const arcAngle = 2 * Math.asin(halfDist / radius) * (180 / Math.PI);\n const arcLength = (PI2 * radius * arcAngle) / 360;\n\n const temp = close ? (i === 0 ? 0 : s1 - done) : s1 - done;\n const temp2 =\n i === points.length - 3 ? (close ? pep - curvAdjust : s2) : 0;\n\n p.addSegment(a1, temp, p1[2], true);\n p.addSegment(a1, isNaN(arcLength) ? 0 : arcLength, p1[2], true);\n p.addSegment(a2, temp2, p2[2], true);\n\n done = curvAdjust;\n if (i === 0) {\n pep = s1;\n pep2 = curvAdjust;\n tep = [point1.x, point1.y];\n }\n }\n\n if (i === points.length - 3) {\n p.endPlot(a2, p2[2], true);\n }\n } else if (curvature === 0) {\n // If no curvature, add a simple straight segment\n const p1 = points[i];\n const p2 = points[i + 1];\n const d = dist(p1[0], p1[1], p2[0], p2[1]);\n const a = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n\n p.addSegment(a, d, p2[2], true);\n if (i === points.length - 2) {\n p.endPlot(a, 1, true);\n }\n }\n }\n\n p.origin = close && curvature !== 0 ? tep : points[0];\n }\n\n return p;\n}\n","// =============================================================================\n// Stroke Runtime Hooks\n// =============================================================================\n\nlet strokeRuntime = {\n createTipSurface: () => {\n throw new Error(\"No stroke runtime adapter registered.\");\n },\n loadImageTip: () => {\n throw new Error(\"No stroke runtime adapter registered.\");\n },\n};\n\n/**\n * Registers or updates host stroke hooks used by brush-tip loading code.\n *\n * @param {object} hooks\n */\nexport function setStrokeRuntime(hooks) {\n strokeRuntime = { ...strokeRuntime, ...hooks };\n}\n\nexport const createTipSurface = (width, height) =>\n strokeRuntime.createTipSurface(width, height);\nexport const loadImageTip = (src, imageToWhite) =>\n strokeRuntime.loadImageTip(src, imageToWhite);\n","import * as Color from \"../core/color.js\";\nimport { createFramebuffer } from \"../core/compositor_runtime.js\";\n\nlet isStrokeCompositeRegistered = false;\nconst DIRTY_BRUSH_PADDING = 2;\n\n// =============================================================================\n// Section: Helpers\n// =============================================================================\n/**\n * Returns whether the current stroke mask framebuffer must be recreated.\n * This happens when the renderer has no mask yet, or when the canvas size or\n * pixel density changed since the last allocation.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {boolean} True when the stroke mask must be rebuilt.\n */\nfunction needsStrokeMask(Renderer, Cwidth, Cheight, Density) {\n return (\n !Renderer.glMask ||\n Renderer.glMask.width !== Cwidth ||\n Renderer.glMask.height !== Cheight ||\n (typeof Renderer.glMask.pixelDensity === \"function\" &&\n Renderer.glMask.pixelDensity() !== Density)\n );\n}\n\n// =============================================================================\n// Section: Resource Management\n// =============================================================================\n/**\n * Ensures the stroke compositor owns a framebuffer-backed mask with the current\n * canvas dimensions. Stroke stamps are rendered into this mask in WebGL before\n * being blended into the main target.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {object} The framebuffer used as stroke mask.\n */\nexport function ensureStrokeCompositeResources(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n) {\n if (needsStrokeMask(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.glMask?.remove) Renderer.glMask.remove();\n Renderer.glMask = createFramebuffer(Renderer, {\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n }\n\n Renderer.glMask.dirtyRect ??= null;\n Renderer.glMask.isDrawn ??= false;\n return Renderer.glMask;\n}\n\n// =============================================================================\n// Section: Mask Lifecycle\n// =============================================================================\n/**\n * Clears the current stroke mask and resets its bookkeeping flags.\n *\n * @param {object|null} target - Stroke mask framebuffer.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n */\nexport function clearStrokeMask(target, clearTarget) {\n if (!target) return;\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\n}\n\n// =============================================================================\n// Section: Composite Bounds\n// =============================================================================\n/**\n * Returns the rect that should be composited from the stroke mask into the\n * main canvas. Stroke bounds are normally tight dirty rects, but when drawing\n * into an active framebuffer we keep the result conservative and composite the\n * full target.\n *\n * @param {object|null} target - Stroke mask framebuffer.\n * @param {Function} getActiveFramebuffer - Returns the currently bound framebuffer.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} expandDirtyRect - Expands a rect by a constant padding.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @param {number} padding - Extra brush padding in pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\nexport function getStrokeCompositeRect(\n target,\n getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n if (getActiveFramebuffer()) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(target.dirtyRect, DIRTY_BRUSH_PADDING),\n );\n}\n\n/**\n * Returns the resource that should be bound to the blend shader's `u_mask`\n * uniform for stroke compositing.\n *\n * @param {object} _Renderer - Active host renderer.\n * @param {object} mask - Stroke mask framebuffer.\n * @returns {object} Stroke mask framebuffer.\n */\nexport function getStrokeShaderMask(_Renderer, mask) {\n return mask;\n}\n\n// =============================================================================\n// Section: Registration\n// =============================================================================\n/**\n * Registers the stroke compositor with the shared color/composite core.\n * Safe to call multiple times.\n */\nexport function initStrokeComposite() {\n if (isStrokeCompositeRegistered) return;\n Color.registerStrokeComposite?.({\n ensureResources: ensureStrokeCompositeResources,\n clearMask: clearStrokeMask,\n getCompositeRect: getStrokeCompositeRect,\n getShaderMask: getStrokeShaderMask,\n });\n isStrokeCompositeRegistered = true;\n}\n","/**\n * Compiles a shader program from the given vertex and fragment sources.\n * @param {WebGL2RenderingContext} gl - The WebGL2 context.\n * @param {string} vert - Vertex shader source.\n * @param {string} frag - Fragment shader source.\n * @returns {WebGLProgram} The compiled and linked program.\n */\nexport const createProgram = (gl, vert, frag) => {\n const p = gl.createProgram();\n for (let [t, src] of [\n [gl.VERTEX_SHADER, vert],\n [gl.FRAGMENT_SHADER, frag],\n ]) {\n const s = gl.createShader(t);\n gl.shaderSource(s, src);\n gl.compileShader(s);\n gl.attachShader(p, s);\n }\n gl.linkProgram(p);\n return p;\n};\n","// =============================================================================\n// Renderer Runtime Hooks\n// =============================================================================\n\n/**\n * Direct-render hooks used by modules that issue raw WebGL commands.\n *\n * These hooks are intentionally narrow:\n * - begin drawing into an offscreen GL mask target\n * - restore the previous draw target afterward\n * - reset any host-side shader/program bookkeeping after direct GL usage\n */\n\nlet rendererRuntime = {\n beginDirectMaskDraw: () => {\n throw new Error(\"No renderer runtime adapter registered.\");\n },\n endDirectMaskDraw: () => {\n throw new Error(\"No renderer runtime adapter registered.\");\n },\n resetDirectShaderTracking: () => {},\n};\n\n/**\n * Registers or updates host renderer hooks used by direct WebGL drawing paths.\n *\n * @param {object} hooks\n */\nexport function setRendererRuntime(hooks) {\n rendererRuntime = { ...rendererRuntime, ...hooks };\n}\n\nexport const beginDirectMaskDraw = (renderer, gl, target) =>\n rendererRuntime.beginDirectMaskDraw(renderer, gl, target);\nexport const endDirectMaskDraw = (renderer, gl, state) =>\n rendererRuntime.endDirectMaskDraw(renderer, gl, state);\nexport const resetDirectShaderTracking = (renderer, gl) =>\n rendererRuntime.resetDirectShaderTracking(renderer, gl);\n","// =============================================================================\n// Module: GL Draw\n// =============================================================================\n/**\n * The GL Draw module batches brush primitives for WebGL2 rendering. It initializes\n * the shader programs and buffers used by circle-based brushes and image-tip brushes,\n * then flushes those queues into the shared framebuffer-backed brush mask.\n */\n\nimport { Cwidth, Cheight, Density, Renderer } from \"../core/target.js\";\nimport {\n Mix,\n isMixReady,\n State,\n} from \"../core/color.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport {\n beginDirectMaskDraw,\n endDirectMaskDraw,\n resetDirectShaderTracking,\n} from \"../core/renderer_runtime.js\";\nimport { getAffineMatrix } from \"../core/runtime.js\";\nimport vertSrc from \"./shader.vert\";\nimport fragSrc from \"./shader.frag\";\nimport imgVertSrc from \"./image.vert\";\nimport imgFragSrc from \"./image.frag\";\n\n// =============================================================================\n// Section: Initialization and Setup\n// =============================================================================\n\n// Module state\nlet isLoaded = false,\n gl,\n framebufferProjMatrix,\n vao,\n buf,\n program;\nlet loadedWidth = 0,\n loadedHeight = 0;\nlet brushMaskTarget = null;\nconst Attr = {},\n Frag = {};\n\n// Cached matrix values — snapshotted once per stroke in snapshotMatrix()\nlet _ma = 1,\n _mb = 0,\n _mc = 0,\n _md = 1,\n _mx = 0,\n _my = 0,\n _halfW = 0,\n _halfH = 0,\n _scale = 1,\n _density = 1;\n\n/**\n * Snapshots the current runtime affine transform. Call once at the start of each stroke.\n */\nexport function snapshotMatrix() {\n const m = getAffineMatrix();\n _ma = m.a;\n _mb = m.b;\n _mc = m.c;\n _md = m.d;\n _mx = m.x;\n _my = m.y;\n _halfW = Cwidth / 2;\n _halfH = Cheight / 2;\n _scale = Math.sqrt(_ma * _ma + _mb * _mb);\n _density = Density;\n}\n\n// Pre-allocated flat buffer for circle data (x, y, radius, alpha per circle)\nconst INITIAL_CAPACITY = 2048;\nlet circleData = new Float32Array(INITIAL_CAPACITY * 4);\nlet circleCount = 0;\nlet bufferCapacity = INITIAL_CAPACITY;\nlet gpuBufferSize = INITIAL_CAPACITY * 4 * 4; // bytes allocated on GPU\nlet circleDirtyRect = null;\n\n// ---------------------------------------------------------------------------\n// Image instancing state\n// ---------------------------------------------------------------------------\nlet imgProgram = null;\nlet imgVao = null;\nlet imgCornerBuf = null;\nlet imgInstanceBuf = null;\nconst imgAttr = {};\nconst imgFrag = {};\nlet imgGpuSize = 0;\n\nconst IMG_FLOATS = 5; // screenX, screenY, halfSize, angle, alpha — per stamp\nconst IMG_INIT_CAP = 256;\nlet imgData = new Float32Array(IMG_INIT_CAP * IMG_FLOATS);\nlet imgCount = 0;\nlet imgCapacity = IMG_INIT_CAP;\nlet imgDirtyRect = null;\n\n// Texture cache: src string → WebGLTexture (cleared whenever the GL context changes)\nconst texCache = new Map();\n\n// Static unit-quad corners for gl.TRIANGLE_STRIP in quad-local space.\nconst QUAD_CORNERS = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]);\n\nfunction ensureBrushMaskTarget() {\n const rendererMask = Renderer?.glMask;\n if (!rendererMask) return null;\n brushMaskTarget = rendererMask;\n brushMaskTarget.dirtyRect ??= null;\n brushMaskTarget.isDrawn ??= false;\n Mix.glMask = brushMaskTarget;\n return brushMaskTarget;\n}\n\nfunction getProjectionMatrix() {\n return framebufferProjMatrix;\n}\n\nfunction beginMaskTarget() {\n return beginDirectMaskDraw(Renderer, gl, Mix.glMask);\n}\n\nfunction endMaskTarget(state) {\n endDirectMaskDraw(Renderer, gl, state);\n}\n\nfunction accumulateDirtyRect(currentRect, minX, minY, maxX, maxY) {\n if (!currentRect) return { minX, minY, maxX, maxY };\n if (minX < currentRect.minX) currentRect.minX = minX;\n if (minY < currentRect.minY) currentRect.minY = minY;\n if (maxX > currentRect.maxX) currentRect.maxX = maxX;\n if (maxY > currentRect.maxY) currentRect.maxY = maxY;\n return currentRect;\n}\n\n/**\n * Initializes WebGL objects if not done already.\n */\nexport function isReady() {\n isMixReady();\n ensureBrushMaskTarget();\n\n const nextGl = Renderer.drawingContext;\n const needsContextRefresh = !isLoaded || gl !== nextGl;\n const needsProjectionRefresh =\n needsContextRefresh || loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (needsProjectionRefresh) {\n framebufferProjMatrix = new Float32Array([\n 2 / Cwidth,\n 0,\n 0,\n 0,\n 0,\n 2 / Cheight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n -1,\n 0,\n 1,\n ]);\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n }\n\n if (!needsContextRefresh) return;\n\n gl = nextGl;\n\n // Create shader program and initialize\n program = createProgram(gl, vertSrc, fragSrc);\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n // Cache attribute and uniform locations\n [\"a_position\", \"a_radius\", \"a_alpha\"].forEach(\n (n) => (Attr[n] = gl.getAttribLocation(program, n)),\n );\n [\"u_matrix\", \"u_color\"].forEach(\n (n) => (Frag[n] = gl.getUniformLocation(program, n)),\n );\n\n // Create persistent VAO and VBO\n vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n\n buf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n gl.bufferData(gl.ARRAY_BUFFER, circleData.byteLength, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n\n // Set up vertex attributes (only needs to happen once with persistent VAO)\n const stride = 16; // 4 floats × 4 bytes\n gl.enableVertexAttribArray(Attr.a_position);\n gl.vertexAttribPointer(Attr.a_position, 2, gl.FLOAT, false, stride, 0);\n gl.enableVertexAttribArray(Attr.a_radius);\n gl.vertexAttribPointer(Attr.a_radius, 1, gl.FLOAT, false, stride, 8);\n gl.enableVertexAttribArray(Attr.a_alpha);\n gl.vertexAttribPointer(Attr.a_alpha, 1, gl.FLOAT, false, stride, 12);\n\n gl.bindVertexArray(null);\n\n // ------------------------------------------------------------------\n // Image-tip instancing program\n // ------------------------------------------------------------------\n texCache.clear();\n\n imgProgram = createProgram(gl, imgVertSrc, imgFragSrc);\n [\"a_corner\", \"a_pos\", \"a_size\", \"a_angle\", \"a_alpha\"].forEach(\n (n) => (imgAttr[n] = gl.getAttribLocation(imgProgram, n)),\n );\n [\"u_proj\", \"u_color\", \"u_tex\"].forEach(\n (n) => (imgFrag[n] = gl.getUniformLocation(imgProgram, n)),\n );\n\n imgVao = gl.createVertexArray();\n gl.bindVertexArray(imgVao);\n\n // Static corner VBO (per-vertex, no divisor)\n imgCornerBuf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, imgCornerBuf);\n gl.bufferData(gl.ARRAY_BUFFER, QUAD_CORNERS, gl.STATIC_DRAW);\n gl.enableVertexAttribArray(imgAttr.a_corner);\n gl.vertexAttribPointer(imgAttr.a_corner, 2, gl.FLOAT, false, 0, 0);\n\n // Instance data VBO (per-instance)\n imgInstanceBuf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, imgInstanceBuf);\n gl.bufferData(gl.ARRAY_BUFFER, imgData.byteLength, gl.DYNAMIC_DRAW);\n imgGpuSize = imgData.byteLength;\n\n const istride = IMG_FLOATS * 4; // 20 bytes\n gl.enableVertexAttribArray(imgAttr.a_pos);\n gl.vertexAttribPointer(imgAttr.a_pos, 2, gl.FLOAT, false, istride, 0);\n gl.vertexAttribDivisor(imgAttr.a_pos, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_size);\n gl.vertexAttribPointer(imgAttr.a_size, 1, gl.FLOAT, false, istride, 8);\n gl.vertexAttribDivisor(imgAttr.a_size, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_angle);\n gl.vertexAttribPointer(imgAttr.a_angle, 1, gl.FLOAT, false, istride, 12);\n gl.vertexAttribDivisor(imgAttr.a_angle, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_alpha);\n gl.vertexAttribPointer(imgAttr.a_alpha, 1, gl.FLOAT, false, istride, 16);\n gl.vertexAttribDivisor(imgAttr.a_alpha, 1);\n\n gl.bindVertexArray(null);\n\n isLoaded = true;\n}\n\n// =============================================================================\n// Section: Drawing Primitives\n// =============================================================================\n\n/**\n * Queue a circle to be drawn with the specified parameters.\n * Data is written directly into a flat Float32Array to avoid object allocation.\n * Applies the full 2D affine transform (rotation + scale + translation) from\n * the current runtime transform so that brush.rotate() and brush.scale() work correctly.\n */\nexport function circle(x, y, diameter, alpha) {\n // Grow buffer if needed\n if (circleCount >= bufferCapacity) {\n bufferCapacity *= 2;\n const newData = new Float32Array(bufferCapacity * 4);\n newData.set(circleData);\n circleData = newData;\n }\n\n // x/y arrive in \"position space\": user coords + (Cwidth/2, Cheight/2).\n // Subtract the offset to recover user coords, apply the full matrix, then re-add\n // the offset so the result is in screen pixel space [0..Cwidth, 0..Cheight].\n const px = x - _halfW;\n const py = y - _halfH;\n\n const offset = circleCount * 4;\n const screenX = _ma * px + _mc * py + _mx + _halfW;\n const screenY = _mb * px + _md * py + _my + _halfH;\n const radius = (_density * diameter * _scale) / 2;\n\n circleData[offset] = screenX;\n circleData[offset + 1] = screenY;\n // Scale the diameter by the matrix's scale factor (length of the transformed x-axis)\n circleData[offset + 2] = radius;\n circleData[offset + 3] = alpha / 255;\n\n const dScreenX = screenX * _density;\n const dScreenY = screenY * _density;\n circleDirtyRect = accumulateDirtyRect(\n circleDirtyRect,\n dScreenX - radius - 1,\n dScreenY - radius - 1,\n dScreenX + radius + 1,\n dScreenY + radius + 1,\n );\n\n circleCount++;\n}\n\n/**\n * Queue an image stamp to be drawn with instanced rendering.\n * Accepts the same coordinate conventions as circle(): x/y in position space\n * (user coords + Cwidth/2, Cheight/2), size in user-coord units, alpha in [0..255].\n * @param {number} x - X in position space.\n * @param {number} y - Y in position space.\n * @param {number} size - Full stamp diameter in user-coord units.\n * @param {number} angle - Rotation in radians.\n * @param {number} alpha - Opacity [0..255].\n * @param {number} [extraPadding=0] - Conservative extra padding in user units.\n */\nexport function stampImage(x, y, size, angle, alpha, extraPadding = 0) {\n if (imgCount >= imgCapacity) {\n imgCapacity *= 2;\n const next = new Float32Array(imgCapacity * IMG_FLOATS);\n next.set(imgData);\n imgData = next;\n }\n\n const px = x - _halfW;\n const py = y - _halfH;\n const screenX = _ma * px + _mc * py + _mx + _halfW;\n const screenY = _mb * px + _md * py + _my + _halfH;\n const halfSize = (_density * size * _scale) / 2;\n const extraRadius = _density * extraPadding * _scale;\n\n const base = imgCount * IMG_FLOATS;\n imgData[base] = screenX;\n imgData[base + 1] = screenY;\n imgData[base + 2] = halfSize;\n imgData[base + 3] = angle;\n imgData[base + 4] = alpha / 255;\n\n // Bounding box: rotated square worst-case = circle of radius halfSize * √2\n const dScreenX = screenX * _density;\n const dScreenY = screenY * _density;\n const boundsRadius = halfSize * 1.42 + extraRadius;\n imgDirtyRect = accumulateDirtyRect(\n imgDirtyRect,\n dScreenX - boundsRadius - 1,\n dScreenY - boundsRadius - 1,\n dScreenX + boundsRadius + 1,\n dScreenY + boundsRadius + 1,\n );\n\n imgCount++;\n}\n\n/**\n * Flush all queued image stamps in a single instanced draw call.\n * @param {object} p5img - The preprocessed brush-tip image/canvas (from T.tips).\n * @param {string} src - The image src string, used as the texture cache key.\n */\nexport function glDrawImages(p5img, src) {\n if (imgCount === 0) return;\n\n Mix.glMask.isDrawn = true;\n const targetState = beginMaskTarget();\n\n // Lazy-create the WebGL texture from the tip canvas on first use.\n let tex = texCache.get(src);\n if (!tex) {\n tex = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, p5img.canvas);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n texCache.set(src, tex);\n }\n\n gl.useProgram(imgProgram);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.uniform1i(imgFrag.u_tex, 0);\n\n const color = State.stroke.color._array;\n gl.uniform4f(imgFrag.u_color, ...color);\n gl.uniformMatrix4fv(imgFrag.u_proj, false, getProjectionMatrix());\n\n gl.bindVertexArray(imgVao);\n gl.bindBuffer(gl.ARRAY_BUFFER, imgInstanceBuf);\n\n const byteCount = imgCount * IMG_FLOATS * 4;\n const dataView = imgData.subarray(0, imgCount * IMG_FLOATS);\n if (byteCount > imgGpuSize) {\n gl.bufferData(gl.ARRAY_BUFFER, imgData, gl.DYNAMIC_DRAW);\n imgGpuSize = imgData.byteLength;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);\n }\n\n gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, imgCount);\n\n gl.bindVertexArray(null);\n gl.bindTexture(gl.TEXTURE_2D, null);\n endMaskTarget(targetState);\n\n if (imgDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, imgDirtyRect);\n imgDirtyRect = null;\n }\n\n imgCount = 0;\n\n // Let the host adapter know we changed the active program.\n resetDirectShaderTracking(Renderer, gl);\n}\n\n/**\n * Removes a cached GL texture by key, forcing re-upload on next draw.\n * Call this when a custom tip function changes after brush.add().\n */\nexport function invalidateTexEntry(key) {\n const tex = texCache.get(key);\n if (tex && gl) gl.deleteTexture(tex);\n texCache.delete(key);\n}\n\n/**\n * Draw all queued circles using WebGL\n */\nexport function glDraw() {\n if (circleCount === 0) return;\n\n Mix.glMask.isDrawn = true;\n const targetState = beginMaskTarget();\n\n const color = State.stroke.color._array;\n\n // Re-activate our shader in case host drawing switched programs.\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n gl.bindVertexArray(vao);\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n\n // Upload vertex data — reallocate GPU buffer only if needed\n const byteCount = circleCount * 16; // 4 floats × 4 bytes\n const dataView = circleData.subarray(0, circleCount * 4);\n if (byteCount > gpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, circleData, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);\n }\n\n // Set uniforms and draw\n gl.uniform4f(Frag.u_color, ...color);\n gl.uniformMatrix4fv(Frag.u_matrix, false, getProjectionMatrix());\n gl.drawArrays(gl.POINTS, 0, circleCount);\n\n gl.bindVertexArray(null);\n endMaskTarget(targetState);\n\n if (circleDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, circleDirtyRect);\n circleDirtyRect = null;\n }\n\n // Reset queue (no deallocation)\n circleCount = 0;\n\n // We called gl.useProgram() directly, bypassing host shader tracking.\n // Reset it so the host is forced to re-activate its own shader next time\n // it draws — otherwise it may skip gl.useProgram() and set uniforms on the\n // wrong active program, causing \"location is not from the associated program\".\n resetDirectShaderTracking(Renderer, gl);\n}\n","// =============================================================================\n// Module: Brush\n// =============================================================================\n/**\n * The Brush module provides a comprehensive set of functions and classes for\n * simulating various drawing tools ranging from pens, markers, pencils, to\n * custom image-based brushes. This module controls brush properties such as\n * weight, color, vibration, and spacing, and manages the drawing process through\n * stateful methods that enable features like pressure sensitivity, clipping, and\n * blending. By supporting multiple brush types and dynamic parameter adjustments,\n * the Brush module facilitates the creation of realistic and expressive stroke effects.\n */\n\n// Core imports\nimport { Cwidth, Cheight, Renderer, isCanvasReady } from \"../core/target.js\";\nimport {\n Mix,\n State,\n} from \"../core/color.js\";\nimport {\n rr,\n map,\n dist,\n randInt,\n calcAngle,\n toDegrees,\n gaussian,\n rArray,\n noise,\n _onSeed, \n cos,\n sin\n} from \"../core/utils.js\";\nimport { createColor } from \"../core/runtime.js\";\nimport { Position, isFieldReady } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { createTipSurface, loadImageTip } from \"./runtime.js\";\n\n// Internal module imports\nimport { initStrokeComposite } from \"./composite.js\";\nimport {\n isReady,\n glDraw,\n glDrawImages,\n circle,\n stampImage,\n invalidateTexEntry,\n snapshotMatrix,\n} from \"./gl_draw.js\";\n\ninitStrokeComposite(); // Register the stroke composite system for offscreen mask rendering and compositing.\n\n// ---------------------------------------------------------------------------\n// Brush State and Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Global stroke state settings.\n */\nState.stroke = {\n color: null,\n weight: 1,\n type: \"HB\",\n isActive: false,\n opacity: 1,\n};\n\nlet list = new Map();\n\nconst DEFAULT_CUSTOM_PRESSURE_VARIATION = {\n offset: 0.08,\n scale: 0.08,\n warp: 0.06,\n tilt: 0.06,\n};\n\n/**\n * Retrieves a shallow copy of the current stroke state.\n * @returns {object} The stroke state.\n */\nexport function BrushState() {\n return { ...State.stroke };\n}\n\n/**\n * Updates the stroke state.\n * @param {object} state - The new stroke state.\n */\nexport function BrushSetState(state) {\n State.stroke = { ...state };\n}\n\n// =============================================================================\n// Section: Brush Manager\n// =============================================================================\n\n/**\n * Adds a new brush with the specified parameters to the brush list.\n * @param {string} name - The unique name for the new brush.\n * @param {object} params - The parameters defining the brush behavior and appearance.\n */\n/**\n * Normalizes the pressure parameter to the internal { type, min_max, curve } format.\n * Accepts:\n * [start, end] — linear ramp between two pressure values\n * [start, mid, end] — piecewise linear (e.g. [1.5, 0.5, 1.5] for U-curve)\n * (t) => value — custom function, t ∈ [0,1], return value ∈ [0,1]\n * { mode: \"gaussian\", curve, min_max } — advanced built-in pressure profile\n * { curve, min_max } — legacy gaussian format, preserved for compatibility\n */\nexport function normalizePressure(p) {\n if (!p) return p;\n if (typeof p === \"function\")\n return {\n type: \"custom\",\n min_max: [0, 1],\n curve: p,\n variation: { ...DEFAULT_CUSTOM_PRESSURE_VARIATION },\n };\n if (typeof p === \"object\" && !Array.isArray(p)) {\n if (p.type === \"custom\" || p.mode === \"custom\") {\n const { mode, ...rest } = p;\n return {\n ...rest,\n type: \"custom\",\n variation: {\n ...DEFAULT_CUSTOM_PRESSURE_VARIATION,\n ...(rest.variation ?? {}),\n },\n };\n }\n if (\n p.type === \"gaussian\" ||\n p.mode === \"gaussian\" ||\n (Array.isArray(p.curve) && Array.isArray(p.min_max))\n ) {\n return {\n ...p,\n type: \"gaussian\",\n curve: p.curve,\n min_max: p.min_max,\n };\n }\n return p;\n }\n if (Array.isArray(p)) {\n const [s, m, e] = p.length === 2 ? [p[0], (p[0] + p[1]) / 2, p[1]] : p;\n const min = Math.min(s, m, e),\n max = Math.max(s, m, e);\n const range = max - min || 1;\n const [ns, nm, ne] = [\n (s - min) / range,\n (m - min) / range,\n (e - min) / range,\n ];\n return {\n type: \"custom\",\n min_max: [min, max],\n variation: { ...DEFAULT_CUSTOM_PRESSURE_VARIATION },\n curve: (t) =>\n t < 0.5 ? ns + (nm - ns) * t * 2 : nm + (ne - nm) * (t - 0.5) * 2,\n };\n }\n}\n\nexport function add(name, params) {\n const validTypes = [\"marker\", \"custom\", \"image\", \"spray\"];\n params.type = validTypes.includes(params.type) ? params.type : \"default\";\n if (params.markerTip === undefined) params.markerTip = true;\n if (params.noise === undefined) params.noise = 0.3;\n params.noise = Math.max(0, Math.min(1, params.noise));\n // Accept legacy param names for backward compatibility\n if (params.vibration !== undefined && params.scatter === undefined)\n params.scatter = params.vibration;\n if (params.definition !== undefined && params.sharpness === undefined)\n params.sharpness = params.definition;\n if (params.quality !== undefined && params.grain === undefined)\n params.grain = params.quality;\n params.pressure = normalizePressure(params.pressure);\n if (params.type === \"custom\") {\n if (typeof params.tip !== \"function\") {\n throw new Error(`Brush \"${name}\" is type \"custom\" but is missing a tip function.`);\n }\n // Rasterise the tip once into a 500×500 P2D buffer.\n // Users draw in a 100×100 coordinate space (origin at centre);\n // dark fills/strokes → high opacity, light/white → transparent.\n const key = `custom::${name}`;\n invalidateTexEntry(key); // discard stale GPU texture if tip changed\n const g = createTipSurface(500, 500);\n g.pixelDensity(1);\n g.background(255);\n g.noSmooth();\n g.push();\n g.translate(250, 250); // centre origin\n g.scale(5); // 100 user units → 500 px\n g.noStroke();\n params.tip(g);\n g.pop();\n T.imageToWhite(g); // dark → high alpha, RGB → white for tint\n T.tips.set(key, g);\n params.tipKey = key;\n list.set(name, { param: params, colors: [], buffers: [] });\n return;\n }\n if (params.type === \"image\") {\n if (!params.image || !params.image.src) {\n throw new Error(\n `Brush \"${name}\" is type \"image\" but is missing params.image.src. Example: image: { src: \"./tip.jpg\" }`,\n );\n }\n T.add(params.image.src);\n list.set(name, { param: params, colors: [], buffers: [] });\n return T.load(); // returns a Promise; only loads images not yet loaded\n }\n list.set(name, { param: params, colors: [], buffers: [] });\n}\n\n/**\n * Retrieves the list of available brush names.\n * @returns {Array<string>} Array of brush names.\n */\nexport function box() {\n return [...list.keys()];\n}\n\nexport function getBrushParams(brushName) {\n return list.get(brushName)?.param ?? null;\n}\n\n/**\n * Scales standard brush parameters by the provided factor.\n * @param {number} scaleFactor - The scaling factor to apply.\n */\nexport function scaleBrushes(scaleFactor) {\n for (const { param } of list.values()) {\n if (param) {\n param.weight *= scaleFactor;\n param.scatter *= scaleFactor;\n param.spacing *= scaleFactor;\n }\n }\n}\n\n/**\n * Sets the current brush type by name.\n * @param {string} brushName - The name of the brush.\n */\nexport function pick(brushName) {\n if (!list.has(brushName)) {\n throw new Error(\n `Brush \"${brushName}\" not found. Available brushes: ${[...list.keys()].join(\", \")}.`,\n );\n }\n State.stroke.type = brushName;\n}\n\n/**\n * Sets the stroke style (color) for the current brush.\n * @param {number|string|Color} r - Red component, CSS color string, or Color object.\n * @param {number} [g] - Green component.\n * @param {number} [b] - Blue component.\n */\nexport function stroke(r, g, b) {\n isCanvasReady();\n State.stroke.color = createColor(...arguments);\n State.stroke.isActive = true;\n}\n\n/**\n * Sets the brush weight (thickness).\n * @param {number} weight - The weight value.\n */\nexport function strokeWeight(weight) {\n State.stroke.weight = weight;\n}\n\n/**\n * Sets the current brush with name, color, and weight.\n * @param {string} brushName - The brush name.\n * @param {string|Color} color - The brush color.\n * @param {number} [weight=1] - The brush weight.\n */\nexport function set(brushName, color, weight = 1) {\n pick(brushName);\n stroke(color);\n strokeWeight(weight);\n}\n\n/**\n * Disables the stroke effect.\n */\nexport function noStroke() {\n State.stroke.isActive = false;\n}\n\n/**\n * Defines a clipping region for strokes.\n * The region uses the same coordinate space as brush drawing commands,\n * with the current runtime transform captured at call time.\n * @param {number[]} region - Array as [x1, y1, x2, y2] defining the clipping region.\n */\nexport function clip(region) {\n isCanvasReady();\n return region;\n}\n\n/**\n * Disables the clipping region.\n */\nexport function noClip() {\n return;\n}\n\n// ---------------------------------------------------------------------------\n// Drawing Variables and Functions\n// ---------------------------------------------------------------------------\nlet _position, _length, _plot, _dir;\nlet _cachedPlotAngle = 0;\nconst current = {};\n\n/**\n * Initializes the drawing state.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of stroke.\n * @param {Plot|false} [plot=false] - Plot object for path-following strokes.\n */\nfunction initializeDrawingState(x, y, length, plot = false) {\n snapshotMatrix();\n _position = new Position(x + Cwidth / 2, y + Cheight / 2);\n _length = length;\n _plot = plot;\n if (_plot) _plot.calcIndex(0);\n}\n\nconst gaussians = [];\n\n_onSeed(() => {\n gaussians.length = 0;\n});\n\n/**\n * Executes the drawing operation.\n * @param {number} angleScale - Angle (in degrees) or scaling factor.\n * @param {boolean} isPlot - True if plotting a shape.\n */\nfunction draw(angleScale, isPlot) {\n if (!isPlot) _dir = angleScale;\n saveState();\n\n const stepSize = spacing();\n const totalSteps = Math.round(\n (_length * (isPlot ? angleScale : 1)) / stepSize,\n );\n current.pressureCount = 10;\n current.cachedPressure = undefined;\n current.lineNoiseCount = 5;\n current.cachedLineNoise = undefined;\n\n const neededGaussians = totalSteps * 2;\n while (gaussians.length < neededGaussians) {\n gaussians.push(gaussian());\n }\n\n for (let i = 0; i < totalSteps; i++) {\n if (isPlot) _cachedPlotAngle = _plot.angle(_position.plotted);\n tip();\n if (isPlot) {\n _position.plotTo(_plot, stepSize, stepSize, angleScale, _cachedPlotAngle);\n } else {\n _position._moveToDegrees(angleScale, stepSize, stepSize);\n }\n }\n restoreState();\n}\n\n/**\n * Prepares the environment for a brush stroke.\n */\nfunction saveState() {\n current.seed = rr() * 999999;\n const { param } = list.get(State.stroke.type) ?? {};\n if (!param) return;\n current.p = param;\n\n // Set pressure values for the stroke\n const { pressure } = param;\n current.isCustomPressure = pressure.type === \"custom\";\n current.a = !current.isCustomPressure ? rr(-1, 1) : 0;\n current.b = !current.isCustomPressure ? rr(1, 1.5) : 0;\n if (!current.isCustomPressure) {\n current.cp = rr(3, 3.5);\n current.ct = 0;\n current.cs = 1;\n current.ck = 0;\n } else {\n const variation = pressure.variation ?? DEFAULT_CUSTOM_PRESSURE_VARIATION;\n current.cp = rr(-variation.offset, variation.offset);\n current.ct = rr(-variation.warp, variation.warp);\n current.cs = rr(1 - variation.scale, 1 + variation.scale);\n current.ck = rr(-variation.tilt, variation.tilt);\n }\n [current.min, current.max] = pressure.min_max;\n\n current.noiseoffset = 0.05 * current.p.noise;\n\n // Cache stroke direction for direction-aware dispersion (non-plot strokes only)\n if (!_plot) {\n current.cos = cos(_dir);\n current.sin = sin(_dir);\n }\n\n // Ensure GL is ready and blend state\n isReady();\n const switchingToBrush = Mix.isBrush !== true;\n Mix.isBrush = true;\n if (switchingToBrush) Mix.justChanged = true;\n Mix.blend(State.stroke.color);\n\n // Set additional state values\n current.alpha = calculateAlpha();\n current.overscan = getImageTipOverscan();\n current.drawFn =\n current.p.type === \"spray\" ? drawSpray :\n current.p.type === \"marker\" ? drawMarker :\n (current.p.type === \"custom\" || current.p.type === \"image\") ? drawImageTip :\n drawDefault;\n\n markerTip();\n}\n\n/**\n * Restores drawing state after completing a stroke.\n */\nfunction restoreState() {\n markerTip();\n glDraw();\n const type = current.p?.type;\n if (type === \"image\") glDrawImages(T.tips.get(current.p.image.src), current.p.image.src);\n else if (type === \"custom\") glDrawImages(T.tips.get(current.p.tipKey), current.p.tipKey);\n}\n\n/**\n * Renders the brush tip based on current pressure and position.\n */\nfunction tip() {\n const pressure = calculatePressure();\n const lineNoise = calculateLineNoise();\n\n if (lineNoise > rr(1,1.02) && rr(0,1) < 0.7) return;\n current.drawFn(pressure * lineNoise);\n}\n\n/**\n * Calculates the effective brush pressure.\n * @returns {number} The calculated pressure.\n */\nfunction calculatePressure() {\n if (current.pressureCount >= 10 || current.cachedPressure === undefined) {\n current.cachedPressure = _plot\n ? simPressure() * _plot.pressure(_position.plotted)\n : simPressure();\n current.pressureCount = 0;\n }\n current.pressureCount++;\n return current.cachedPressure;\n}\n\nfunction calculateLineNoise() {\n if (current.lineNoiseCount >= 10 || current.cachedLineNoise === undefined) {\n current.cachedLineNoise = map(\n noise(current.seed + _position.plotted * 0.01, 0),\n -1,\n 1,\n 1 - current.noiseoffset,\n 1 + current.noiseoffset,\n );\n current.lineNoiseCount = 0;\n }\n current.lineNoiseCount++;\n return current.cachedLineNoise;\n}\n\n/**\n * Simulates brush pressure based on stroke parameters.\n * @returns {number} Simulated pressure value.\n */\nfunction simPressure() {\n if (!current.isCustomPressure) return gauss();\n const t = _position.plotted / _length;\n return map(\n current.p.pressure.curve(\n Math.max(0, Math.min(1, 0.5 + (t - 0.5 + current.ct) * current.cs)),\n ) +\n current.cp +\n current.ck * (t - 0.5),\n 0,\n 1,\n current.min,\n current.max,\n true,\n );\n}\n\n/**\n * Generates a Gaussian-based pressure value.\n * @param {number} [a] - Center parameter.\n * @param {number} [b] - Width parameter.\n * @param {number} [c] - Shape parameter.\n * @param {number} [min] - Minimum pressure.\n * @param {number} [max] - Maximum pressure.\n * @returns {number} Gaussian pressure value.\n */\nfunction gauss(\n a = 0.5 + current.p.pressure.curve[0] * current.a,\n b = 1 - current.p.pressure.curve[1] * current.b,\n c = current.cp,\n min = current.min,\n max = current.max,\n) {\n const peakPos = a * _length;\n const halfWidth =\n (_position.plotted < peakPos ? b * 1.2 : b * 0.8) * (_length / 2);\n return map(\n 1 /\n (1 +\n Math.pow(Math.abs((_position.plotted - peakPos) / halfWidth), 2 * c)),\n 0,\n 1,\n min,\n max,\n );\n}\n\n/**\n * Calculates the alpha (opacity) level for a brush stroke.\n * @returns {number} The calculated opacity.\n */\nfunction calculateAlpha() {\n return [\"default\", \"spray\"].includes(current.p.type)\n ? current.p.opacity\n : current.p.opacity / Math.min(State.stroke.weight, 1.3);\n}\n\n/**\n * Calculates the step spacing based on the current brush parameters.\n * @returns {number} The spacing value.\n */\nfunction spacing() {\n return current.p?.spacing ?? 1;\n}\n\nfunction getImageTipOverscan() {\n const maxPressure = Math.max(1, current.max ?? 1);\n const scatterReach = State.stroke.weight * current.p.scatter;\n const tipReach = State.stroke.weight * current.p.weight * maxPressure;\n\n // Custom/image tips can extend beyond their nominal square because the tip\n // drawing itself may be large and because high scatter creates sparse large\n // stamps near the edge. Keep culling/dirty tracking conservative.\n return Math.max(8, scatterReach * 1.5 + tipReach * 0.75);\n}\n\n// ---------------------------------------------------------------------------\n// Brush Tip Rendering Methods\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the spray tip effect.\n * @param {number} pressure - Current pressure.\n */\nfunction drawSpray(pressure) {\n const vibration =\n State.stroke.weight * current.p.scatter * pressure +\n (State.stroke.weight * rArray(gaussians) * current.p.scatter) / 3;\n const sw = current.p.weight * rr(0.9, 1.1);\n const iterations = Math.ceil(current.p.grain / pressure);\n for (let j = 0; j < iterations; j++) {\n const r = rr(0.9, 1.1);\n const rX = r * vibration * rr(-1, 1);\n const yRandomFactor = rr(-1, 1);\n const sqrtPart = Math.sqrt((r * vibration) ** 2 - rX ** 2);\n circle(\n _position.x + rX,\n _position.y + yRandomFactor * sqrtPart,\n sw,\n current.alpha,\n );\n }\n}\n\n/**\n * Draws the marker tip effect.\n * @param {number} pressure - Current pressure.\n * @param {boolean} [vibrate=true] - Whether to apply vibration.\n */\nfunction drawMarker(pressure, vibrate = true, alpha = current.alpha) {\n const vibration = vibrate ? State.stroke.weight * current.p.scatter : 0;\n const rx = vibrate ? vibration * rr(-1, 1) : 0;\n const ry = vibrate ? vibration * rr(-1, 1) : 0;\n circle(\n _position.x + rx,\n _position.y + ry,\n State.stroke.weight * current.p.weight * pressure,\n alpha * Math.max(0.8, pressure) * rr(0.9,1.1),\n );\n}\n\n/**\n * Queues a stamp for instanced GL rendering.\n * Handles both \"image\" and \"custom\" tip types.\n * @param {number} pressure - Current pressure.\n * @param {number} alpha - Opacity [0..255].\n */\nfunction drawImageTip(pressure, alpha = current.alpha) {\n const vibration = State.stroke.weight * current.p.scatter;\n const rx = vibration * rr(-1, 1);\n const ry = vibration * rr(-1, 1);\n const size = current.p.weight * State.stroke.weight * pressure;\n const overscan = current.overscan;\n let angle = 0;\n if (current.p.rotate === \"random\") {\n angle = randInt(0, 360) * (Math.PI / 180);\n } else if (current.p.rotate === \"natural\") {\n angle = ((_plot ? -_cachedPlotAngle : -_dir) + _position.angle()) * (Math.PI / 180);\n }\n stampImage(\n _position.x + rx,\n _position.y + ry,\n size,\n angle,\n alpha * Math.max(0.8, pressure) * rr(0.9, 1.1),\n overscan,\n );\n}\n\n/**\n * Draws the default brush tip.\n * @param {number} pressure - Current pressure.\n */\nfunction drawDefault(pressure, wiggle = 1) {\n wiggle = map(wiggle, 0, 1, 0.9, 1.05);\n const vibration =\n wiggle *\n State.stroke.weight *\n current.p.scatter *\n (current.p.sharpness +\n ((1 - current.p.sharpness) * rArray(gaussians)) / pressure);\n const passesGate = rr(0, current.p.grain * pressure) > 0.4;\n if (passesGate) {\n let dx, dy;\n if (_plot) {\n const plotAngle = _cachedPlotAngle;\n const plotCos = cos(plotAngle);\n const plotSin = sin(plotAngle);\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * plotSin + along * plotCos;\n dy = perp * plotCos - along * plotSin;\n } else {\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * current.sin + along * current.cos;\n dy = perp * current.cos - along * current.sin;\n }\n const diameter =\n pressure *\n pressure *\n current.p.weight *\n rr(0.85, 1.15) *\n State.stroke.weight;\n const alpha = Math.max(0.9, pressure) * current.alpha * rr(0.75, 1.1);\n circle(\n _position.x + dx,\n _position.y + dy,\n diameter,\n alpha,\n );\n }\n}\n\n/**\n * Draws the marker tip with a blend effect.\n */\nfunction markerTip() {\n if (current.p.markerTip === false) return;\n let pressure = calculatePressure();\n let alpha = current.alpha;\n if (current.p.type === \"marker\") {\n for (let s = 1; s < 10; s++) {\n drawMarker((pressure * s) / 10, true, alpha * 8);\n }\n } else if (current.p.type === \"custom\" || current.p.type === \"image\") {\n for (let s = 1; s < 5; s++) {\n drawImageTip((pressure * s) / 10, alpha * 2);\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Basic Drawing Operations\n// ---------------------------------------------------------------------------\n\n/**\n * Draws a line using the current brush.\n * @param {number} x1 - Start x-coordinate.\n * @param {number} y1 - Start y-coordinate.\n * @param {number} x2 - End x-coordinate.\n * @param {number} y2 - End y-coordinate.\n */\nexport function line(x1, y1, x2, y2) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n let d = dist(x1, y1, x2, y2);\n if (d == 0) return;\n initializeDrawingState(x1, y1, d);\n let angle = calcAngle(x1, y1, x2, y2);\n draw(angle, false);\n}\n\n/**\n * Draws a stroke from a starting point in a given direction.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of the stroke.\n * @param {number} dir - Direction, interpreted using the current runtime angle units.\n */\nexport function flowLine(x, y, length, dir) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n initializeDrawingState(x, y, length);\n draw(toDegrees(dir), false);\n}\n\n/**\n * Draws a predefined plot.\n * @param {object} p - Shape object representing the plot.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nfunction plot(p, x, y, scale) {\n isFieldReady();\n initializeDrawingState(x, y, p.length, p);\n draw(scale, true);\n}\n\n// ---------------------------------------------------------------------------\n// Standard Brushes Definition and Initialization\n// ---------------------------------------------------------------------------\n\n/**\n * Defines a set of standard brushes with specific characteristics. Each brush is defined\n * with properties such as weight, scatter, sharpness, grain, opacity, spacing, and\n * pressure sensitivity. Some brushes have additional properties like type, tip, and rotate.\n */\nconst _vals = [\n \"weight\",\n \"scatter\",\n \"sharpness\",\n \"grain\",\n \"opacity\",\n \"spacing\",\n \"pressure\",\n \"type\",\n \"tip\",\n \"rotate\",\n \"markerTip\",\n \"noise\",\n];\nconst _standard_brushes = [\n [\n \"pen\",\n [0.3, 0.15, 0.9, 2, 150, 0.1, { curve: [0.15, 0.2], min_max: [1.2, 1] }],\n ],\n [\n \"rotring\",\n [0.15, 0.05, 0.7, 15, 210, 0.1, { curve: [0.35, 0.2], min_max: [1.3, 1] }],\n ],\n [\n \"2B\",\n [0.3, 0.75, 0.45, 15, 180, 0.1, { curve: [0.1, 0.3], min_max: [1.1, 0.9] }],\n ],\n [\n \"HB\",\n [0.3, 0.6, 0.3, 10, 170, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"2H\",\n [0.2, 0.6, 0.3, 4, 120, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"cpencil\",\n [0.3, 0.55, 0.8, 7, 75, 0.1, { curve: [0.15, 0.2], min_max: [0.95, 1.2] }],\n ],\n [\n \"pastel\",\n [\n 2.05 / 3,\n 13.4 / 3,\n 0.91,\n 28,\n 35,\n 0.085 / 3,\n { mode: \"gaussian\", curve: [0.4, 0.05], min_max: [1.09, 0.93] },\n \"default\",\n undefined,\n \"natural\",\n true,\n 1,\n ],\n ],\n [\n \"crayon\",\n [\n 0.9 / 3,\n 5.45 / 3,\n 0.75,\n 250,\n 159,\n 0.23 / 3,\n [1.1, 0.9],\n \"default\",\n undefined,\n \"natural\",\n true,\n 1,\n ],\n ],\n [\n \"charcoal\",\n [\n 0.35,\n 1.5,\n 0.68,\n 500,\n 120,\n 0.03,\n { curve: [0.15, 0.4], min_max: [1.1, 0.95] },\n ],\n ],\n [\n \"spray\",\n [\n 0.2,\n 6,\n 15,\n 40,\n 90,\n 0.5,\n { curve: [0.2, 0.35], min_max: [0.7, 1] },\n \"spray\",\n ],\n ],\n [\n \"marker\",\n [\n 2,\n 0.2,\n null,\n null,\n 1,\n 0.03,\n { curve: [0.35, 0.25], min_max: [1.2, 0.85] },\n \"marker\",\n ],\n ],\n];\n\nfor (let s of _standard_brushes) {\n let obj = {};\n for (let i = 0; i < s[1].length; i++) obj[_vals[i]] = s[1][i];\n add(s[0], obj);\n}\n\n// ---------------------------------------------------------------------------\n// Extensions to Polygon and Plot Prototypes\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the polygon using the current brush.\n * @param {boolean} [_brush=false] - Optional brush name override.\n * @param {string|Color} [_color] - Optional color override.\n * @param {number} [_weight] - Optional weight override.\n */\nPolygon.prototype.draw = function (_brush = false, _color, _weight) {\n let state = BrushState();\n if (_brush) set(_brush, _color, _weight);\n if (state.isActive) {\n for (let s of this.sides) {\n line(s[0].x, s[0].y, s[1].x, s[1].y);\n }\n }\n BrushSetState(state);\n};\n\n/**\n * Draws the plot using the current brush.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nPlot.prototype.draw = function (x, y, scale) {\n if (BrushState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n plot(this, x, y, scale);\n }\n};\n\n// =============================================================================\n// Section: Loading Custom Image Tips\n// =============================================================================\n/**\n * This section defines the functionality for managing the loading and processing of image tips.\n * Images are loaded from specified source URLs, converted to a white tint for visual effects,\n * and then stored for future use. It includes methods to add new images, convert their color\n * scheme, and integrate them into the active host image pipeline.\n */\n\n/**\n * Manages loading and processing of image tips.\n * Images are converted to white with inverted alpha for tinting via shaders.\n */\nconst T = {\n tips: new Map(),\n\n /**\n * Registers an image source for later loading.\n * @param {string} src - The source URL of the image.\n */\n add(src) {\n if (!this.tips.has(src)) this.tips.set(src, false);\n },\n\n /**\n * Converts image to white with inverted alpha for tint-based rendering.\n * @param {object} image - The host image object to convert.\n */\n imageToWhite(image) {\n image.loadPixels();\n for (let i = 0; i < 4 * image.width * image.height; i += 4) {\n let average =\n (image.pixels[i] + image.pixels[i + 1] + image.pixels[i + 2]) / 3;\n image.pixels[i] = image.pixels[i + 1] = image.pixels[i + 2] = 255;\n image.pixels[i + 3] = 255 - average;\n }\n image.updatePixels();\n },\n\n /**\n * Loads all registered image tips. Returns a promise that resolves\n * when all images are loaded and processed.\n * @returns {Promise}\n */\n async load() {\n const entries = [...this.tips.keys()].filter((k) => !this.tips.get(k));\n await Promise.all(\n entries.map(\n (src) =>\n loadImageTip(src, T.imageToWhite).then((p5img) => {\n this.tips.set(src, p5img);\n }),\n ),\n );\n },\n};\n","import { State } from \"../core/color.js\";\nimport { toDegreesSigned, map, rr } from \"../core/utils.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { BrushState, BrushSetState, set, line } from \"../stroke/stroke.js\";\n\n// =============================================================================\n// Module: Classic Hatch\n// =============================================================================\n\n// ---------------------------------------------------------------------------\n// Hatch State\n// ---------------------------------------------------------------------------\n\nState.hatch = {\n isActive: false,\n dist: 5,\n angle: 45,\n options: {},\n hBrush: false,\n};\n\n/**\n * Returns a shallow snapshot of the current hatch modifier state.\n *\n * @returns {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}}\n */\nexport function HatchState() {\n return { ...State.hatch };\n}\n\n/**\n * Restores hatch modifier state from a previously captured snapshot.\n *\n * @param {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}} state\n */\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Activates classic scanline hatching for subsequent shapes.\n *\n * @param {number} [dist=5] Distance between scanlines.\n * @param {number} [angle=45] Hatch angle in the current runtime angle units.\n * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [options]\n */\nexport function hatch(\n dist = 5,\n angle = 45,\n options = { rand: false, continuous: false, gradient: false }\n) {\n let s = State.hatch;\n s.isActive = true;\n s.dist = dist;\n s.angle = toDegreesSigned(angle);\n s.options = options;\n}\n\n/**\n * Overrides the brush, color, and weight used specifically for hatch strokes.\n *\n * @param {string} brush\n * @param {string|object} [color=\"black\"]\n * @param {number} [weight=1]\n */\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\n/**\n * Deactivates hatching and clears any hatch-specific brush override.\n */\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Scanline Generation\n// ---------------------------------------------------------------------------\n\n/**\n * Computes hatch segments for one polygon by rotating it into scanline space,\n * intersecting horizontal scanlines against its edges, and rotating the\n * resulting segments back into canvas space.\n *\n * @param {Polygon} polygon\n * @param {number} angle Hatch angle in degrees.\n * @param {number} dist Base scanline spacing.\n * @param {number} gradient Multiplicative spacing growth per scanline.\n * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}\n */\nfunction scanlineHatch(polygon, angle, dist, gradient) {\n const rad = (angle * Math.PI) / 180;\n const cosA = Math.cos(rad),\n sinA = Math.sin(rad);\n const cosB = Math.cos(-rad),\n sinB = Math.sin(-rad);\n\n const verts = polygon.a,\n n = verts.length;\n\n // Rotate vertices; track Y extent\n const rotated = new Array(n);\n let minY = Infinity,\n maxY = -Infinity;\n for (let i = 0; i < n; i++) {\n const x = verts[i][0],\n y = verts[i][1];\n const r = [x * cosA - y * sinA, x * sinA + y * cosA];\n rotated[i] = r;\n if (r[1] < minY) minY = r[1];\n if (r[1] > maxY) maxY = r[1];\n }\n\n // Build edge list (skip horizontal edges)\n const edges = [];\n for (let i = 0; i < n; i++) {\n const a = rotated[i],\n b = rotated[(i + 1) % n];\n if (a[1] !== b[1]) edges.push(a, b);\n }\n const eLen = edges.length;\n\n // Scan, find crossings, rotate back\n const segments = [];\n const cx = [];\n let Y = minY + dist * 0.5,\n step = dist;\n while (Y < maxY) {\n cx.length = 0;\n for (let i = 0; i < eLen; i += 2) {\n const y1 = edges[i][1],\n y2 = edges[i + 1][1];\n if ((y1 <= Y && Y < y2) || (y2 <= Y && Y < y1))\n cx.push(\n edges[i][0] + ((Y - y1) / (y2 - y1)) * (edges[i + 1][0] - edges[i][0])\n );\n }\n cx.sort((a, b) => a - b);\n for (let i = 0; i < cx.length - 1; i += 2) {\n segments.push({\n scanY: Y,\n x1: cx[i] * cosB - Y * sinB,\n y1: cx[i] * sinB + Y * cosB,\n x2: cx[i + 1] * cosB - Y * sinB,\n y2: cx[i + 1] * sinB + Y * cosB,\n });\n }\n Y += step;\n step *= gradient;\n }\n return segments;\n}\n\n/**\n * Collects and orders hatch segments for one polygon or a polygon list.\n *\n * Segments are sorted in scanline traversal order so downstream rendering can\n * optionally connect them into a continuous serpentine path.\n *\n * @param {Polygon|Polygon[]} polygons\n * @param {number} dist\n * @param {number} angle\n * @param {number} gradient\n * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}\n */\nfunction getHatchSegments(polygons, dist, angle, gradient) {\n if (!Array.isArray(polygons)) polygons = [polygons];\n const segs = [];\n for (const poly of polygons) {\n for (const s of scanlineHatch(poly, angle, dist, gradient)) segs.push(s);\n }\n segs.sort((a, b) => (a.scanY === b.scanY ? a.x1 - b.x1 : a.scanY - b.scanY));\n return segs;\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Configuration\n// ---------------------------------------------------------------------------\n\n/**\n * Runs hatch drawing with the temporary hatch-specific brush style if one is active,\n * then restores the outer stroke state.\n *\n * @param {() => void} drawFn\n */\nfunction withHatchStyle(drawFn) {\n const save = BrushState();\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n drawFn();\n BrushSetState(save);\n}\n\n/**\n * Resolves the active hatch parameters and precomputes the ordered scanline segments.\n *\n * @param {Polygon|Polygon[]} polygons\n * @returns {{dist:number, options:Object, segs:Object[]}}\n */\nfunction getActiveHatchConfig(polygons) {\n const dist = State.hatch.dist;\n const angle = ((State.hatch.angle % 180) + 180) % 180;\n const options = State.hatch.options;\n const gradient = options.gradient ? map(options.gradient, 0, 1, 1, 1.1, true) : 1;\n const segs = getHatchSegments(polygons, dist, angle, gradient);\n return { dist, options, segs };\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Lines\n// ---------------------------------------------------------------------------\n\n/**\n * Expands ordered hatch segments into the actual line list that will be drawn.\n *\n * This includes endpoint jitter when `rand` is active and inserts the serpentine\n * connector lines when `continuous` is enabled.\n *\n * @param {Polygon|Polygon[]} polygons\n * @returns {{x1:number, y1:number, x2:number, y2:number, scanY:number, isConnector:boolean}[]}\n */\nexport function getHatchLines(polygons) {\n const { dist, options, segs } = getActiveHatchConfig(polygons);\n const r = options.rand || 0;\n const lines = [];\n\n for (let j = 0; j < segs.length; j++) {\n const s = segs[j];\n let x1 = s.x1, y1 = s.y1, x2 = s.x2, y2 = s.y2;\n if (r) {\n x1 += 2 * r * dist * rr(-1, 1);\n y1 += 2 * r * dist * rr(-1, 1);\n x2 += 2 * r * dist * rr(-1, 1);\n y2 += 2 * r * dist * rr(-1, 1);\n }\n const reverse = options.continuous && j % 2 === 1;\n const line = reverse\n ? { x1: x2, y1: y2, x2: x1, y2: y1, scanY: s.scanY, isConnector: false }\n : { x1, y1, x2, y2, scanY: s.scanY, isConnector: false };\n lines.push(line);\n if (j > 0 && options.continuous) {\n const prev = lines[lines.length - 2];\n lines.push({\n x1: prev.x2,\n y1: prev.y2,\n x2: line.x1,\n y2: line.y1,\n scanY: s.scanY,\n isConnector: true,\n });\n }\n }\n\n return lines;\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Rendering\n// ---------------------------------------------------------------------------\n\n/**\n * Iterates the generated hatch lines and delegates the actual rendering of each\n * segment to the provided callback.\n *\n * @param {Polygon|Polygon[]} polygons\n * @param {(x1:number, y1:number, x2:number, y2:number, index:number, segs:Object[]) => void} drawSegment\n */\nfunction renderHatchSegments(polygons, drawSegment) {\n const segs = getHatchLines(polygons);\n withHatchStyle(() => {\n for (let j = 0; j < segs.length; j++) {\n const s = segs[j];\n drawSegment(s.x1, s.y1, s.x2, s.y2, j, segs);\n }\n });\n}\n\n/**\n * Draws classic hatch lines over one polygon or an array of polygons.\n *\n * @param {Polygon|Polygon[]} polygons\n */\nexport function createHatch(polygons) {\n renderHatchSegments(polygons, (x1, y1, x2, y2) => {\n line(x1, y1, x2, y2);\n });\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Applies the currently active hatch modifier to a polygon, or temporarily\n * overrides hatch parameters for this call only.\n *\n * @param {number|false} [_dist=false]\n * @param {number} [_angle]\n * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [_options]\n */\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (State.hatch.isActive) createHatch(this);\n HatchSetState(state);\n};\n\n/**\n * Converts the plot to a polygon and applies the currently active hatch modifier.\n *\n * @param {number} x\n * @param {number} y\n * @param {number} scale\n */\nPlot.prototype.hatch = function (x, y, scale) {\n if (HatchState().isActive) {\n if (this.origin) (x = this.origin[0]), (y = this.origin[1]), (scale = 1);\n this.pol = this.genPol(x, y, scale, 0.3);\n this.pol.hatch();\n }\n};\n","// =============================================================================\n// Module: Mass\n// =============================================================================\n\nimport { State } from \"../core/color.js\";\nimport { arc } from \"../core/primitives.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { rr2, dist, calcAngle } from \"../core/utils.js\";\nimport { fromDegrees, usesRadians } from \"../core/runtime.js\";\nimport { HatchState, HatchSetState, hatch, getHatchLines } from \"./hatch.js\";\nimport { BrushState, BrushSetState, getBrushParams, set } from \"../stroke/stroke.js\";\nimport { wiggle } from \"../core/flowfield.js\";\n\n// ---------------------------------------------------------------------------\n// Mass State\n// ---------------------------------------------------------------------------\n\nState.mass = {\n isActive: false,\n brush: null,\n color: null,\n options: {},\n};\n\n/**\n * Returns a shallow copy of the current mass state.\n * @returns {object}\n */\nexport function MassState() {\n return { ...State.mass };\n}\n\n/**\n * Restores a previously saved mass state.\n * @param {object} state\n */\nexport function MassSetState(state) {\n State.mass = { ...state };\n}\n\n/**\n * Enables massing mode with a brush, color, and optional configuration.\n *\n * @param {string} brush - Brush name to use for the mass pass.\n * @param {string|Color} color - Color to use for the mass pass.\n * @param {object} [options={}] - Massing options such as precision, strength, gradient, and outline.\n */\nexport function mass(brush, color, options = {}) {\n State.mass.brush = brush;\n State.mass.color = color;\n State.mass.options = options;\n State.mass.isActive = true;\n}\n\n/**\n * Disables massing mode for subsequent geometry.\n */\nexport function noMass() {\n State.mass.isActive = false;\n State.mass.brush = null;\n State.mass.color = null;\n State.mass.options = {};\n}\n\n// ---------------------------------------------------------------------------\n// Polygon Preparation\n// ---------------------------------------------------------------------------\n\n/**\n * Returns a translated copy of a polygon.\n * Used to build the secondary mass layers from an existing base polygon.\n * @param {Polygon} polygon\n * @param {number} jitterX\n * @param {number} jitterY\n * @returns {Polygon}\n */\nfunction jitterPolygon(polygon, jitterX, jitterY) {\n return new Polygon(\n polygon.vertices.map((vertex) => [vertex.x + jitterX, vertex.y + jitterY]),\n );\n}\n\n/**\n * Builds the three polygons used for a mass pass.\n * Both polygon and plot inputs use one base polygon plus two translated copies,\n * so plot-based massing only needs a single `genPol(...)` call.\n * @param {Polygon|Plot} shape\n * @param {number|false} x\n * @param {number} y\n * @param {number} scale\n * @returns {Polygon[]}\n */\nfunction getMassPolygons(shape, x, y, scale) {\n const isPolygon = x === false;\n const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;\n const basePolygon = isPolygon ? shape : shape.genPol(x, y, scale, 0.15);\n const maxJitter = Math.min(scatter * 2, 5);\n const jitters = [\n [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],\n [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],\n ];\n\n return [\n basePolygon,\n jitterPolygon(basePolygon, jitters[0][0], jitters[0][1]),\n jitterPolygon(basePolygon, jitters[1][0], jitters[1][1]),\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Angle & Bounds Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Converts degree values into the current runtime angle units.\n * @param {number} angle\n * @returns {number}\n */\nfunction getAngleConverter() {\n return usesRadians()\n ? (angle) => (angle * Math.PI) / 180\n : (angle) => angle;\n}\n\n/**\n * Computes an axis-aligned bounding box for a polygon.\n * The diagonal is used as a size reference for pivot distance.\n * @param {Polygon} polygon\n * @returns {{minX:number,minY:number,maxX:number,maxY:number,cx:number,cy:number,size:number}}\n */\nfunction getPolygonBounds(polygon) {\n const points = polygon?.a ?? [];\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n for (const [x, y] of points) {\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n return {\n minX,\n minY,\n maxX,\n maxY,\n cx: (minX + maxX) / 2,\n cy: (minY + maxY) / 2,\n size: Math.hypot(maxX - minX, maxY - minY),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Pivot Geometry\n// ---------------------------------------------------------------------------\n\n/**\n * Chooses the diagonal corner family for a whole mass gesture.\n * Positive-angle hatching uses either bottom-right or top-left; negative-angle\n * hatching uses either bottom-left or top-right.\n * @param {number} angleDeg\n * @returns {[number, number]}\n */\nfunction getPivotBias(angleDeg) {\n const normalizedAngle = ((((angleDeg + 90) % 180) + 180) % 180) - 90;\n if (normalizedAngle >= 0) {\n return rr2() < 0.5 ? [1, 1] : [-1, -1];\n } else {\n return rr2() < 0.5 ? [-1, 1] : [1, -1];\n }\n}\n\n/**\n * Places the global pivot anchor outside the polygon, along the selected bias.\n * Distance varies per layer while the bias stays fixed for the whole mass.\n * @param {Polygon} polygon\n * @param {[number, number]} bias\n * @returns {{x:number,y:number}}\n */\nfunction getPivotAnchor(polygon, bias) {\n const bounds = getPolygonBounds(polygon);\n const offset = bounds.size * rr2(0.6, 1.4);\n const [sx, sy] = bias;\n return {\n x: bounds.cx + sx * offset,\n y: bounds.cy + sy * offset,\n };\n}\n\n/**\n * Projects the global pivot anchor onto the perpendicular bisector of a line.\n * This yields a valid circle center equidistant from both endpoints.\n * @param {{x:number,y:number}} anchor\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {{x:number,y:number}|null}\n */\nfunction projectAnchorToBisector(anchor, x1, y1, x2, y2) {\n const mx = (x1 + x2) / 2;\n const my = (y1 + y2) / 2;\n const dx = x2 - x1;\n const dy = y2 - y1;\n const length = Math.hypot(dx, dy);\n if (!length) return null;\n const nx = -dy / length;\n const ny = dx / length;\n const offset = (anchor.x - mx) * nx + (anchor.y - my) * ny;\n return {\n x: mx + nx * offset,\n y: my + ny * offset,\n };\n}\n\n/**\n * Returns the shortest arc between two endpoints around a given center.\n * The returned angles are already converted into the current runtime angle units.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {[number, number]}\n */\nfunction getShortArcAngles(cx, cy, x1, y1, x2, y2, toAngleUnit) {\n let startDeg = calcAngle(cx, cy, x1, y1);\n let endDeg = calcAngle(cx, cy, x2, y2);\n const sweep = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweep > 180) [startDeg, endDeg] = [endDeg, startDeg];\n return [\n toAngleUnit(startDeg),\n toAngleUnit(endDeg),\n ];\n}\n\n/**\n * Splits a hatch line into two slightly separated segments so some gestures\n * read as interrupted rather than perfectly continuous.\n * @param {{x1:number,y1:number,x2:number,y2:number}} seg\n * @returns {Array<{x1:number,y1:number,x2:number,y2:number}>}\n */\nfunction splitSegment(seg) {\n const t = rr2(0.35, 0.65);\n const mx = seg.x1 + (seg.x2 - seg.x1) * t;\n const my = seg.y1 + (seg.y2 - seg.y1) * t;\n const dx = seg.x2 - seg.x1;\n const dy = seg.y2 - seg.y1;\n const length = Math.hypot(dx, dy) || 1;\n const gap = rr2(0.04, 0.1) * length;\n const gx = (dx / length) * gap * 0.5;\n const gy = (dy / length) * gap * 0.5;\n return [\n { x1: seg.x1, y1: seg.y1, x2: mx - gx, y2: my - gy },\n { x1: mx + gx, y1: my + gy, x2: seg.x2, y2: seg.y2 },\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Mass Rendering\n// ---------------------------------------------------------------------------\n\n/**\n * Draws one polygon of the mass as a family of arcs derived from hatch lines.\n * The same pivot bias is used across layers, while each layer gets its own\n * anchor distance from the shape.\n * @param {Polygon} polygon\n * @param {[number, number]} pivotBias\n */\nfunction drawMassArcs(polygon, pivotBias, toAngleUnit) {\n const anchor = getPivotAnchor(polygon, pivotBias);\n for (const seg of getHatchLines(polygon)) {\n const parts = !seg.isConnector && rr2() < 0.35 ? splitSegment(seg) : [seg];\n for (const part of parts) {\n const center = projectAnchorToBisector(anchor, part.x1, part.y1, part.x2, part.y2);\n if (!center) continue;\n const radius = dist(center.x, center.y, part.x1, part.y1);\n if (!radius) continue;\n const [startAngle, endAngle] = getShortArcAngles(\n center.x,\n center.y,\n part.x1,\n part.y1,\n part.x2,\n part.y2,\n toAngleUnit,\n );\n arc(center.x, center.y, radius, startAngle, endAngle);\n }\n }\n}\n\n/**\n * Configures a hatch pass and immediately reinterprets the generated lines as arcs.\n * @param {Polygon} polygon\n * @param {number} dist\n * @param {number} angle\n * @param {object} options\n * @param {[number, number]} pivotBias\n */\nfunction drawMassPass(polygon, dist, angle, options, pivotBias, toAngleUnit) {\n hatch(dist, angle, options);\n drawMassArcs(polygon, pivotBias, toAngleUnit);\n}\n\n/**\n * Creates the built-in \"massing\" effect for a polygon or plot.\n * A mass is built from up to three jittered polygon layers, each hatched and\n * then redrawn as arc gestures around a shared pivot bias.\n * @param {Polygon|Plot} shape\n * @param {number|false} x\n * @param {number} y\n * @param {number} scale\n */\nexport function createMass(shape, x, y, scale) {\n const pols = getMassPolygons(shape, x, y, scale);\n const hatchState = HatchState();\n const brushState = BrushState();\n const fieldState = { ...State.field };\n const precision = State.mass.options?.precision ?? 0.5;\n const strength = State.mass.options?.strength ?? 1;\n const gradient = State.mass.options?.gradient ?? 0.1;\n const outline = State.mass.options?.outline ?? false;\n const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;\n const hatchDist = 1.6 * rr2(scatter * 0.65, scatter * 0.85) - 0.4 * gradient;\n const baseAngle = rr2(-90, 90);\n const pivotBias = getPivotBias(baseAngle);\n const toAngleUnit = getAngleConverter();\n\n set(State.mass.brush, State.mass.color, 1);\n wiggle(2 - precision);\n if (outline) pols[0].draw();\n\n drawMassPass(\n pols[0],\n hatchDist * 0.9,\n fromDegrees(baseAngle),\n {\n gradient,\n rand: 2 - 2 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n\n if (strength > 0.33) {\n drawMassPass(\n pols[1],\n hatchDist,\n fromDegrees(baseAngle + 20 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n }\n\n if (strength > 0.66) {\n drawMassPass(\n pols[2],\n hatchDist * 0.8,\n fromDegrees(baseAngle + 15 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n }\n\n BrushSetState(brushState);\n HatchSetState(hatchState);\n State.field = { ...fieldState };\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Applies massing to polygon geometry.\n */\nPolygon.prototype.mass = function () {\n if (State.mass?.isActive) {\n createMass(this, false);\n }\n};\n\n/**\n * Applies massing to plots by generating their polygon first.\n * @param {number} x\n * @param {number} y\n * @param {number} scale\n */\nPlot.prototype.mass = function (x, y, scale) {\n if (State.mass?.isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n createMass(this, x, y, scale);\n }\n};\n","import { Mix } from \"../core/color.js\";\n\nfunction strokePadding(ctx, matrix) {\n const lineWidth = ctx.lineWidth || 0;\n if (lineWidth <= 0) return 1;\n\n return (\n 1 +\n (lineWidth * Math.max(Math.hypot(matrix.a, matrix.c), Math.hypot(matrix.b, matrix.d))) /\n 2\n );\n}\n\n// =============================================================================\n// Section: Draw shapes to Mask Buffers\n// =============================================================================\n\n/**\n * Draws a polygon to the mask using the provided vertices.\n * @param {Array<{x: number, y: number}>} vertices - Array of vertex coordinates.\n */\nexport function drawPolygon(vertices, matrix = null) {\n const ctx = Mix.ctx;\n if (!matrix) matrix = ctx.getTransform();\n // Cache the current 2D transform once so the hot loop can stay numeric and\n // avoid repeated property reads while we build bounds.\n const a = matrix.a;\n const b = matrix.b;\n const c = matrix.c;\n const d = matrix.d;\n const e = matrix.e;\n const f = matrix.f;\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n\n ctx.beginPath();\n\n // Seed both the path and the transformed bounds from the first vertex so the\n // loop below only needs to append line segments.\n const first = vertices[0];\n let tx = a * first.x + c * first.y + e;\n let ty = b * first.x + d * first.y + f;\n minX = maxX = tx;\n minY = maxY = ty;\n\n ctx.moveTo(first.x, first.y);\n\n for (let i = 1; i < vertices.length; i++) {\n const v = vertices[i];\n\n // Track the transformed bounds in canvas space while we build the path so\n // dirty-rect bookkeeping does not need a second pass over the vertices.\n tx = a * v.x + c * v.y + e;\n ty = b * v.x + d * v.y + f;\n minX = Math.min(minX, tx);\n minY = Math.min(minY, ty);\n maxX = Math.max(maxX, tx);\n maxY = Math.max(maxY, ty);\n\n ctx.lineTo(v.x, v.y);\n }\n\n ctx.closePath();\n\n // Expand by stroke width so the later composite pass copies enough pixels\n // even when the polygon border extends outside the raw vertex bounds.\n const padding = strokePadding(ctx, matrix);\n Mix.markDirtyRect(Mix.mask, {\n minX: minX - padding,\n minY: minY - padding,\n maxX: maxX + padding,\n maxY: maxY + padding,\n });\n}\n\n/**\n * Draws a circle to the mask.\n * @param {number} x - X-coordinate of the circle's center.\n * @param {number} y - Y-coordinate of the circle's center.\n * @param {number} d - Diameter of the circle.\n */\nexport function circle(x, y, d) {\n const PI2 = Math.PI * 2;\n const ctx = Mix.ctx;\n const radius = d / 2;\n\n ctx.moveTo(x + radius, y);\n ctx.arc(x, y, radius, 0, PI2);\n}\n","import * as Color from \"../core/color.js\";\nimport {\n createFramebuffer,\n create2DCanvas,\n} from \"../core/compositor_runtime.js\";\n\n// Small staging canvas used to upload only the dirty fill sub-rect into the\n// framebuffer-backed mask mirror consumed by the blend shader.\nlet FillMaskUploadCanvas = null;\nlet isFillCompositeRegistered = false;\nconst DIRTY_FILL_PADDING = 4;\n\n// =============================================================================\n// Section: Helpers\n// =============================================================================\n/**\n * Returns whether the CPU-side 2D fill mask must be recreated.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} maskWidth - Mask width in physical pixels.\n * @param {number} maskHeight - Mask height in physical pixels.\n * @returns {boolean} True when the 2D fill mask needs reallocation.\n */\nfunction needsFillMaskCanvas(Renderer, maskWidth, maskHeight) {\n return (\n !Renderer.mask ||\n Renderer.mask.width !== maskWidth ||\n Renderer.mask.height !== maskHeight\n );\n}\n\n/**\n * Returns whether the framebuffer-backed fill mask mirror must be recreated.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {boolean} True when the fill mask framebuffer needs reallocation.\n */\nfunction needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density) {\n return (\n !Renderer.fillMaskFramebuffer ||\n Renderer.fillMaskFramebuffer.width !== Cwidth ||\n Renderer.fillMaskFramebuffer.height !== Cheight ||\n (typeof Renderer.fillMaskFramebuffer.pixelDensity === \"function\" &&\n Renderer.fillMaskFramebuffer.pixelDensity() !== Density)\n );\n}\n\n// =============================================================================\n// Section: Resource Management\n// =============================================================================\n/**\n * Ensures fill compositing resources exist for the active renderer.\n *\n * Fill draws first into a CPU-side 2D mask canvas. That mask is later uploaded,\n * dirty-rect by dirty-rect, into a framebuffer-backed mirror used by the final\n * blend shader pass.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n * @returns {{mask: object, ctx: CanvasRenderingContext2D}} Fill mask resources.\n */\nexport function ensureFillCompositeResources(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n clearTarget,\n) {\n const maskWidth = Math.max(1, Math.round(Cwidth * Density));\n const maskHeight = Math.max(1, Math.round(Cheight * Density));\n\n if (needsFillMaskCanvas(Renderer, maskWidth, maskHeight)) {\n Renderer.mask = create2DCanvas(maskWidth, maskHeight);\n }\n\n if (needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.fillMaskFramebuffer?.remove) {\n Renderer.fillMaskFramebuffer.remove();\n }\n Renderer.fillMaskFramebuffer = createFramebuffer(Renderer, {\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n clearTarget(Renderer.fillMaskFramebuffer);\n }\n\n Renderer.mask.dirtyRect ??= null;\n Renderer.mask.isDrawn ??= false;\n Renderer.mask.drawingContext.imageSmoothingEnabled = false;\n return {\n mask: Renderer.mask,\n ctx: Renderer.mask.drawingContext,\n };\n}\n\n// =============================================================================\n// Section: Mask Lifecycle\n// =============================================================================\n/**\n * Clears the current fill mask and resets its bookkeeping flags.\n *\n * @param {object|null} target - Fill mask canvas or framebuffer mirror.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n */\nexport function clearFillMask(target, clearTarget) {\n if (!target) return;\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\n}\n\n// =============================================================================\n// Section: Composite Bounds\n// =============================================================================\n/**\n * Returns the fill dirty rect to composite into the main target. Fill bounds are\n * taken directly from the accumulated 2D mask dirty area plus a small padding.\n *\n * @param {object|null} target - Fill mask canvas.\n * @param {Function} _getActiveFramebuffer - Unused for fill masks.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} expandDirtyRect - Expands a rect by a constant padding.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\nexport function getFillCompositeRect(\n target,\n _getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(target.dirtyRect, DIRTY_FILL_PADDING),\n );\n}\n\n// =============================================================================\n// Section: Upload\n// =============================================================================\n/**\n * Uploads only the dirty portion of the CPU-side 2D fill mask into the\n * framebuffer-backed fill mask mirror used by the shader compositor.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {object} mask - CPU-side 2D fill mask canvas.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} dirtyRect - Dirty rect to upload.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n * @returns {object} Framebuffer-backed fill mask mirror.\n */\nexport function getFillShaderMask(\n Renderer,\n mask,\n dirtyRect,\n getFullDirtyRect,\n clearTarget,\n) {\n const target = Renderer.fillMaskFramebuffer;\n const gl = Renderer.drawingContext;\n const uploadRect = dirtyRect ?? getFullDirtyRect();\n const uploadWidth = uploadRect.maxX - uploadRect.minX;\n const uploadHeight = uploadRect.maxY - uploadRect.minY;\n\n if (\n !FillMaskUploadCanvas ||\n FillMaskUploadCanvas.width !== uploadWidth ||\n FillMaskUploadCanvas.height !== uploadHeight\n ) {\n FillMaskUploadCanvas = create2DCanvas(uploadWidth, uploadHeight);\n }\n\n const uploadContext = FillMaskUploadCanvas.drawingContext;\n uploadContext.clearRect(0, 0, uploadWidth, uploadHeight);\n uploadContext.drawImage(\n mask,\n uploadRect.minX,\n uploadRect.minY,\n uploadWidth,\n uploadHeight,\n 0,\n 0,\n uploadWidth,\n uploadHeight,\n );\n\n clearTarget(target);\n gl.bindTexture(gl.TEXTURE_2D, target.colorTexture);\n gl.texSubImage2D(\n gl.TEXTURE_2D,\n 0,\n uploadRect.minX,\n uploadRect.minY,\n gl.RGBA,\n gl.UNSIGNED_BYTE,\n FillMaskUploadCanvas,\n );\n return target;\n}\n\n// =============================================================================\n// Section: Registration\n// =============================================================================\n/**\n * Registers the fill compositor with the shared color/composite core.\n * Safe to call multiple times.\n */\nexport function initFillComposite() {\n if (isFillCompositeRegistered) return;\n Color.registerFillComposite?.({\n ensureResources: ensureFillCompositeResources,\n clearMask: clearFillMask,\n getCompositeRect: getFillCompositeRect,\n getShaderMask: getFillShaderMask,\n });\n isFillCompositeRegistered = true;\n}\n","// =============================================================================\n// Module: Fill\n// =============================================================================\n/**\n * The Fill module contains functions and classes dedicated to handling\n * the fill properties of shapes within the drawing context. It supports complex fill\n * operations with effects such as bleeding to simulate watercolor-like textures. The\n * methods provided allow for setting the fill color with opacity, controlling the\n * intensity of the bleed effect, and enabling or disabling the fill operation.\n *\n * The watercolor effect implementation is inspired by Tyler Hobbs'\n * techniques for simulating watercolor paints.\n */\n\n// Core imports\nimport { Renderer, Cwidth, Cheight, Density } from \"../core/target.js\";\nimport {\n Mix,\n State,\n} from \"../core/color.js\";\nimport { drawPolygon, circle } from \"./mask.js\";\nimport {\n constrain,\n rr,\n map,\n randInt,\n gaussian,\n rotate,\n cos,\n sin,\n _onSeed,\n} from \"../core/utils.js\";\nimport { isFieldReady } from \"../core/flowfield.js\";\nimport { createColor, getAffineMatrix } from \"../core/runtime.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\n\n// Internal module imports\nimport { initFillComposite } from \"./composite.js\";\n\ninitFillComposite(); // Register the fill composite with the core color module\n\n// =============================================================================\n// Fill State and helpers\n// =============================================================================\n\n// Vertex cap for grow() — set to 0 or false to disable\nconst GROW_MAX_VERTS = 2024;\nlet GROW_CAP;\n\n// Reusable scratch arrays for grow() — avoids 4 allocations per call (~15× per fill)\nlet _growInsX = [];\nlet _growInsY = [];\nlet _growMods = [];\nlet _growDirs = [];\n\n/**\n * Global fill state settings.\n */\nState.fill = {\n opacity: 150,\n bleed_strength: 0.07,\n texture_strength: 0.8,\n border_strength: 0.5,\n direction: \"out\",\n isActive: false,\n};\n\n// Cache the current state\nconst FillState = () => ({ ...State.fill });\nconst FillSetState = (state) => {\n State.fill = { ...state };\n};\n\n// ---------------------------------------------------------------------------\n// Fill Style Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Sets the fill color and opacity for subsequent drawing operations.\n * @param {number|string|Color} a - Either the red component, a CSS color string, or a Color object.\n * @param {number} [b] - The green component or the opacity if using grayscale.\n * @param {number} [c] - The blue component.\n * @param {number} [d] - The opacity.\n */\nexport function fill(a, b, c, d) {\n State.fill.opacity = (arguments.length < 4 ? b : d) || 150;\n State.fill.color = arguments.length < 3 ? createColor(a) : createColor(a, b, c);\n State.fill.isActive = true;\n}\n\n/**\n * Sets the bleed (watercolor) intensity and direction.\n * @param {number} _i - The bleed intensity (clamped to [0,1]).\n * @param {string} [_direction=\"out\"] - The bleeding direction.\n */\nexport function fillBleed(_i, _direction = \"out\") {\n State.fill.bleed_strength = constrain(_i, 0, 1);\n State.fill.direction = _direction;\n}\n\n/**\n * Sets the texture and border strengths for the fill.\n * @param {number} [_texture=0.4] - The texture strength (clamped to [0,1]).\n * @param {number} [_border=0.4] - The border strength (clamped to [0,1]).\n */\nexport function fillTexture(_texture = 0.4, _border = 0.4) {\n State.fill.texture_strength = constrain(_texture, 0, 1);\n State.fill.border_strength = constrain(_border, 0, 1);\n}\n\n/**\n * Disables fill for subsequent drawing operations.\n */\nexport function noFill() {\n State.fill.isActive = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fill Manager Functions\n// ---------------------------------------------------------------------------\n\nlet _polygon;\nlet _bbMinX, _bbMinY, _bbMaxX, _bbMaxY;\n\n// Pre-compute gaussians for reuse\nconst GAUSSIAN_POOL_SIZE = 512;\nconst _gaussians = [[], []]; // [a, b]\nfunction _fillGaussianPools() {\n for (let i = 0; i < GAUSSIAN_POOL_SIZE; i++) {\n _gaussians[0][i] = gaussian(0.5, 0.2);\n _gaussians[1][i] = gaussian(0, 0.02);\n }\n}\n_onSeed(_fillGaussianPools);\n\n// Helper for direction checking - extracted to reduce duplication\nfunction _isLeft(a, b, c) {\n return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) > 0.01;\n}\n\n/**\n * Calculates the centroid of a polygon from its vertices.\n * @param {Object[]} pts - Array of points with {x, y}.\n * @returns {Object} The center point {x, y}.\n */\nfunction _center(pts) {\n if (pts.length === 0) {\n return { x: 0, y: 0 };\n }\n\n if (pts.length < 8) {\n // Simple average for small polygons\n let sumX = 0, sumY = 0;\n for (const pt of pts) { sumX += pt.x; sumY += pt.y; }\n return { x: sumX / pts.length, y: sumY / pts.length };\n }\n\n // Close polygon if needed\n const v = [...pts];\n if (v[0].x !== v[v.length - 1].x || v[0].y !== v[v.length - 1].y)\n v.push(v[0]);\n\n // Calculate using shoelace formula (more efficient implementation)\n let area = 0,\n cx = 0,\n cy = 0;\n for (let i = 0; i < v.length - 1; i++) {\n const cross = v[i].x * v[i + 1].y - v[i + 1].x * v[i].y;\n area += cross;\n cx += (v[i].x + v[i + 1].x) * cross;\n cy += (v[i].y + v[i + 1].y) * cross;\n }\n\n area *= 0.5;\n return area\n ? { x: cx / (6 * area), y: cy / (6 * area) }\n : { x: v[0].x, y: v[0].y };\n}\n\n/**\n * Fills a given polygon with a watercolor effect.\n * @param {Polygon} polygon - The polygon to fill.\n */\nexport function createFill(polygon) {\n if (!State.fill.isActive || !State.fill.color) {\n throw new Error(\n \"No fill color set. Call brush.fill(color) before drawing shapes.\",\n );\n }\n _polygon = polygon;\n _bbMinX = Infinity; _bbMinY = Infinity; _bbMaxX = -Infinity; _bbMaxY = -Infinity;\n for (const [a] of polygon.sides) {\n if (a.x < _bbMinX) _bbMinX = a.x;\n if (a.x > _bbMaxX) _bbMaxX = a.x;\n if (a.y < _bbMinY) _bbMinY = a.y;\n if (a.y > _bbMaxY) _bbMaxY = a.y;\n }\n const v = [...polygon.vertices];\n const _wr = rr(0, 75);\n const fluid = ~~(v.length * 0.25 * (_wr < 5 ? 1 : _wr < 15 ? 2 : 3));\n const strength = State.fill.bleed_strength;\n const modifiers = v.map(\n (_, i) => (i > fluid ? 1 : 0.3) * rr(0.85, 1.4) * strength,\n );\n const shift = randInt(0, v.length);\n const n = v.length;\n const shifted = new Array(n);\n for (let i = 0; i < n; i++) shifted[i] = v[(i + shift) % n];\n const center = _center(shifted);\n return new FillPoly(shifted, modifiers, center, [], true).fill(\n State.fill.color,\n map(State.fill.opacity, 0, 255, 0, 1, true),\n State.fill.texture_strength,\n );\n}\n\n// ---------------------------------------------------------------------------\n// FillPolygon Class\n// ---------------------------------------------------------------------------\n\n/**\n * The FillPolygon class is used to create and manage the properties of the polygons that produces\n * the watercolor effect. It includes methods to grow (expand) the polygon and apply layers\n * of color with varying intensity and erase parts to simulate a natural watercolor bleed.\n * The implementation follows Tyler Hobbs' guide to simulating watercolor:\n * https://tylerxhobbs.com/essays/2017/a-generative-approach-to-simulating-watercolor-paints\n */\nclass FillPoly {\n /**\n * Constructs a FillPolygon.\n * @param {Object[]} _v - Vertices of the polygon.\n * @param {number[]} _m - Multipliers for the bleed effect at each vertex.\n * @param {Object} _center - The polygon's center {x, y}.\n * @param {boolean[]} dir - Array indicating bleed direction per vertex.\n * @param {boolean} isFirst - True for initial polygon.\n */\n constructor(v, m, center, dir = [], isFirst = false, sx, sy) {\n // Initialize properties\n this.v = v;\n this.m = m;\n this.dir = dir;\n this.midP = center;\n\n // Initialize size and direction for first polygon\n if (isFirst) {\n // Calculate size bounds\n let maxX = 0,\n maxY = 0;\n const rayCalc = [];\n\n for (let i = 0; i < v.length; i++) {\n // Store vertex distances to center for size calculation\n const dx = Math.abs(center.x - v[i].x);\n const dy = Math.abs(center.y - v[i].y);\n maxX = Math.max(maxX, dx);\n maxY = Math.max(maxY, dy);\n\n // Store edge info for ray calculations\n const v1 = v[i],\n v2 = v[(i + 1) % v.length];\n const side = { x: v2.x - v1.x, y: v2.y - v1.y };\n const rt = rotate(0, 0, side.x, side.y, 90);\n const mid = { x: v1.x + side.x / 2, y: v1.y + side.y / 2 };\n\n rayCalc.push({\n v1,\n v2,\n ray: {\n point1: mid,\n point2: { x: mid.x + rt.x, y: mid.y + rt.y },\n },\n });\n }\n\n // Store sizes\n this.sizeX = maxX;\n this.sizeY = maxY;\n\n // Calculate directions — inline ray-polygon intersection to avoid\n // O(n) overhead of Polygon.intersect() (cache-key string building,\n // object allocation, intersectLines wrapper) per edge.\n const polySides = _polygon.sides;\n this.dir = Array(v.length);\n for (let i = 0; i < rayCalc.length; i++) {\n const rc = rayCalc[i];\n const r1x = rc.ray.point1.x, r1y = rc.ray.point1.y;\n const r2x = rc.ray.point2.x, r2y = rc.ray.point2.y;\n const rdx = r2x - r1x, rdy = r2y - r1y;\n let count = 0;\n for (let j = 0; j < polySides.length; j++) {\n const sa = polySides[j][0], sb = polySides[j][1];\n const sdx = sb.x - sa.x, sdy = sb.y - sa.y;\n const denom = sdy * rdx - sdx * rdy;\n if (denom === 0) continue;\n const ub = (rdx * (r1y - sa.y) - rdy * (r1x - sa.x)) / denom;\n if (ub < 0 || ub > 1) continue;\n // Compute intersection point inline\n const ua = (sdx * (r1y - sa.y) - sdy * (r1x - sa.x)) / denom;\n const ix = r1x + ua * rdx;\n const iy = r1y + ua * rdy;\n // _isLeft check inline: (v2-v1) × (isect-v1) > 0.01\n if ((rc.v2.x - rc.v1.x) * (iy - rc.v1.y) - (rc.v2.y - rc.v1.y) * (ix - rc.v1.x) > 0.01) {\n count++;\n }\n }\n this.dir[i] = count % 2 === 0;\n }\n\n // Randomize center (single calculation)\n const rx = rr(-0.6, 0.6) * maxX;\n const ry = rr(-0.6, 0.6) * maxY;\n this.midP = { x: center.x + rx, y: center.y + ry };\n } else {\n this.sizeX = sx;\n this.sizeY = sy;\n }\n }\n\n /**\n * Trims vertices from the polygon based on a factor.\n * @param {number} [factor=1] - Factor determining amount of trimming.\n * @returns {Object} An object containing trimmed vertices, multipliers, and direction.\n */\n trim(f = 1) {\n // Fast path for common case\n if (f >= 1 || f < 0 || this.v.length <= 8) {\n return { v: this.v, m: this.m, dir: this.dir };\n }\n\n // Trim from middle for balance\n const n = ~~((1 - f) * this.v.length);\n const s = ~~(this.v.length / 2 - n / 2);\n\n // Copy only the kept ranges instead of cloning the full arrays and splicing.\n const keep = this.v.length - n;\n const v = new Array(keep);\n const m = new Array(keep);\n const dir = new Array(keep);\n let dst = 0;\n\n for (let i = 0; i < s; i++, dst++) {\n v[dst] = this.v[i];\n m[dst] = this.m[i];\n dir[dst] = this.dir[i];\n }\n\n for (let i = s + n; i < this.v.length; i++, dst++) {\n v[dst] = this.v[i];\n m[dst] = this.m[i];\n dir[dst] = this.dir[i];\n }\n\n\n // We want to add at least two vertices to divide the new edge that appears after trimming, at random distances along its path\n const trimStart = s;\n const trimEnd = s + n;\n const edgeStart = this.v[(trimStart - 1 + this.v.length) % this.v.length];\n const edgeEnd = this.v[trimEnd % this.v.length];\n const edgeVec = { x: edgeEnd.x - edgeStart.x, y: edgeEnd.y - edgeStart.y };\n \n // Insert two new vertices at random positions along the new edge\n const insertCount = 2;\n for (let i = 0; i < insertCount; i++) {\n const t = rr(0.25, 0.75); // Random position between 25% and 75% along the edge\n const newVertex = { x: edgeStart.x + edgeVec.x * t, y: edgeStart.y + edgeVec.y * t };\n const insertIdx = s + i;\n v.splice(insertIdx, 0, newVertex);\n m.splice(insertIdx, 0, rr(0.4, 0.7));\n dir.splice(insertIdx, 0, this.dir[trimStart % this.dir.length]);\n }\n\n return { v, m, dir };\n }\n\n /**\n * Randomly samples a fraction of vertices, keeping their order.\n * Any sampled vertex outside the original polygon is pulled inward.\n * @param {number} [ratio=0.3] - Fraction of vertices to keep.\n * @returns {FillPoly} A new FillPoly with fewer vertices, guaranteed inside the original.\n */\n scatter(ratio = 0.3) {\n const L = this.v.length;\n const keep = Math.max(3, ~~(L * ratio));\n const indices = [];\n const step = L / keep;\n for (let i = 0; i < keep; i++) {\n indices.push(~~(i * step + rr(0, step * 0.8)));\n }\n\n const sv = [],\n sm = [],\n sd = [];\n const mid = this.midP;\n const sides = _polygon.sides;\n\n for (const idx of indices) {\n const j = idx % L;\n let p = this.v[j];\n let outside = false;\n // Bounding box reject — vertex outside AABB is definitely outside polygon\n if (p.x < _bbMinX || p.x > _bbMaxX || p.y < _bbMinY || p.y > _bbMaxY) {\n outside = true;\n } else {\n let crossings = 0;\n for (const [a, b] of sides) {\n const ay = a.y,\n by = b.y;\n if ((ay > p.y) === (by > p.y)) continue;\n const t = (p.y - ay) / (by - ay);\n if (p.x < a.x + t * (b.x - a.x)) crossings++;\n }\n outside = crossings % 2 === 0;\n }\n if (outside) {\n p = {\n x: mid.x + (p.x - mid.x) * rr(0.3, 0.6),\n y: mid.y + (p.y - mid.y) * rr(0.3, 0.6),\n };\n }\n sv.push(p);\n sm.push(this.m[j]);\n sd.push(!this.dir[j]);\n }\n\n return new FillPoly(sv, sm, this.midP, sd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Returns a copy with all bleed directions flipped.\n */\n flipDirs() {\n return new FillPoly(this.v, this.m, this.midP, this.dir.map(d => !d), false, this.sizeX, this.sizeY);\n }\n\n /**\n * Grows (or shrinks) the polygon vertices to simulate watercolor spread.\n * @param {number} [growthFactor=1] - Factor controlling growth.\n * @returns {FillPoly} A new FillPoly with adjusted vertices.\n */\n grow(f = 1) {\n const { v: tr_v, m: tr_m, dir: tr_dir } = this.trim(f);\n const len = tr_v.length;\n\n const outLen = len * 2;\n if (_growInsX.length < len) { _growInsX = new Array(len); _growInsY = new Array(len); }\n if (_growMods.length < outLen) { _growMods = new Array(outLen); _growDirs = new Array(outLen); }\n const insertedX = _growInsX;\n const insertedY = _growInsY;\n const newMods = _growMods;\n const newDirs = _growDirs;\n const bleedDirDeg = State.fill.direction === \"out\" ? -90 : 90;\n\n if (_gaussians[0].length === 0) _fillGaussianPools();\n const gPool = _gaussians[0],\n gPoolLen = gPool.length;\n const g2Pool = _gaussians[1],\n g2PoolLen = g2Pool.length;\n\n let idx = 0;\n let insertedIdx = 0;\n let mod = f === 999 ? rr(0.6, 0.8) : State.fill.bleed_strength;\n\n for (let i = 0; i < len; i++) {\n const cv = tr_v[i];\n const nv = tr_v[i + 1 < len ? i + 1 : 0];\n const mi = tr_m[i];\n const di = tr_dir[i];\n\n if (f < 997) mod = mi;\n\n // If mod is smaller than 0.02, skip growing math and just insert the middle vertex\n if (mod < 0.05) {\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n insertedX[insertedIdx] = (cv.x + nv.x) / 2;\n insertedY[insertedIdx] = (cv.y + nv.y) / 2;\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n insertedIdx++;\n continue;\n }\n\n const rotDeg = (di ? bleedDirDeg : -bleedDirDeg) + rr(-1, 1) * 5;\n const c = cos(rotDeg);\n const s = sin(rotDeg);\n\n const sideX = nv.x - cv.x;\n const sideY = nv.y - cv.y;\n const dirX = c * sideX + s * sideY;\n const dirY = c * sideY - s * sideX;\n\n const d = gPool[~~(rr(0, 1) * gPoolLen)] * rr(0.65, 1.35) * mod;\n const nextMod = mi + g2Pool[~~(rr(0, 1) * g2PoolLen)];\n\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n\n insertedX[insertedIdx] = cv.x + sideX * 0.5 + dirX * d;\n insertedY[insertedIdx] = cv.y + sideY * 0.5 + dirY * d;\n newMods[idx] = nextMod;\n newDirs[idx] = di;\n idx++;\n insertedIdx++;\n }\n\n let fv,\n fm,\n fd;\n \n if (GROW_CAP && idx > GROW_CAP) {\n const step = Math.ceil(idx / GROW_CAP);\n const kept = Math.ceil(idx / step);\n fv = new Array(kept);\n fm = new Array(kept);\n fd = new Array(kept);\n let dst = 0;\n for (let j = 0; j < idx; j += step, dst++) {\n fv[dst] =\n j % 2 === 0\n ? tr_v[j >> 1]\n : { x: insertedX[j >> 1], y: insertedY[j >> 1] };\n fm[dst] = newMods[j];\n fd[dst] = newDirs[j];\n }\n } else {\n fv = new Array(idx);\n for (let j = 0; j < idx; j++) {\n fv[j] =\n j % 2 === 0\n ? tr_v[j >> 1]\n : { x: insertedX[j >> 1], y: insertedY[j >> 1] };\n }\n fm = newMods.slice(0, idx);\n fd = newDirs.slice(0, idx);\n }\n return new FillPoly(fv, fm, this.midP, fd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Fills the polygon with multiple layers to simulate a watercolor effect.\n * @param {Color|string} color - The fill color.\n * @param {number} intensity - Opacity intensity (mapped from 0 to 1).\n * @param {number} tex - Texture factor.\n */\n fill(color, intensity, tex) {\n const numLayers = 20;\n const texture = tex * 3;\n const int = 2 * intensity * (1 + tex / 2);\n\n const switchingToFill = Mix.isBrush !== false;\n Mix.isBrush = false;\n if (switchingToFill) Mix.justChanged = true;\n Mix.blend(color);\n\n const m = getAffineMatrix();\n Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * m.a,\n Density * m.b,\n Density * m.c,\n Density * m.d,\n Density * (m.x + Cwidth / 2),\n Density * (m.y + Cheight / 2),\n );\n\n const fillColorBase = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / `;\n Mix.ctx.strokeStyle = fillColorBase + (0.005 * State.fill.border_strength) + \")\";\n Mix.ctx.lineCap = \"round\";\n\n GROW_CAP = GROW_MAX_VERTS * Math.max(0.1, 2 * State.fill.bleed_strength);\n\n const fillMatrix = Mix.ctx.getTransform();\n const size = Math.max(this.sizeX, this.sizeY);\n const darker = rr(0.15, 0.7);\n let pol = this.grow();\n const sparse = this.scatter(0.1).grow().scatter(0.75).flipDirs();\n let pols;\n\n for (let i = 0; i < numLayers; i++) {\n if (i % 4 === 0) {\n pol = pol.grow();\n }\n\n if (i % 2 === 0) {\n pols = [\n pol.grow(1 - 0.0125 * i),\n pol.grow(0.7 - 0.0125 * i),\n pol.grow(0.4 - 0.0125 * i),\n ];\n }\n\n for (const p of pols) {\n const grown = p.grow(999).grow(997);\n grown.layer(i, size, int, fillColorBase, fillMatrix);\n }\n const sparseLayer = sparse.grow(999).flipDirs().grow(997);\n sparseLayer.layer(i, size, int * texture, fillColorBase, fillMatrix);\n if (i % 2 === 0) {\n const darkerLayer = pol.grow(darker).grow(999);\n darkerLayer.layer(i, size, int * 2, fillColorBase, fillMatrix);\n }\n\n if (i % 8 === 0 || i === numLayers - 1) {\n if (texture !== 0) {\n pol.erase(texture * 3, intensity);\n }\n Mix.blend(color, true);\n }\n }\n\n Mix.ctx.restore();\n }\n\n /**\n * Draws a layer of the fill polygon with stroke and fill.\n * @param {number} i - The layer index.\n */\n layer(i, size, int, colorBase, matrix = null) {\n Mix.ctx.lineWidth = map(i, 0, 24, size / 25, size / 30, true);\n\n Mix.ctx.fillStyle = colorBase + int + \"%)\";\n\n drawPolygon(this.v, matrix);\n Mix.ctx.fill();\n Mix.ctx.stroke();\n }\n\n /**\n * Erases parts of the polygon to create a natural watercolor texture.\n * @param {number} texture - Texture strength factor.\n * @param {number} intensity - Intensity value for size scaling.\n */\n erase(texture, intensity) {\n Mix.ctx.save();\n\n const numCircles = ~~(rr(80, 110) * map(texture, 0, 1, 2, 3.5));\n const halfSizeX = this.sizeX / 1.3;\n const halfSizeY = this.sizeY / 1.3;\n const minSize =\n Math.min(this.sizeX, this.sizeY) * (1.3);\n const minSizeFactor = 0.03 * minSize;\n const maxSizeFactor = 0.45 * minSize;\n const { x: midX, y: midY } = this.midP;\n\n Mix.ctx.globalCompositeOperation = \"destination-out\";\n\n const alpha =\n ((5 - map(intensity, 80, 100, 0.3, 0.7, true)) * texture) / 255;\n Mix.ctx.fillStyle = `rgb(255 0 0 / ${alpha})`;\n Mix.ctx.lineWidth = 0;\n\n for (let i = 0; i < numCircles; i++) {\n const x = midX + gaussian(0, halfSizeX);\n const y = midY + gaussian(0, halfSizeY);\n const radius = rr(minSizeFactor, maxSizeFactor);\n\n Mix.ctx.beginPath();\n circle(x, y, radius);\n if (i % 5 !== 0) {\n Mix.ctx.fill();\n }\n }\n\n Mix.ctx.globalCompositeOperation = \"source-over\";\n Mix.ctx.restore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Extend Polygon and Plot Prototypes for Fill\n// ---------------------------------------------------------------------------\n\n/**\n * Applies a fill effect to the polygon using the current fill state.\n * @param {Color|string} [_color] - The color for the fill.\n * @param {number} [_opacity] - The opacity value.\n * @param {number} [_bleed] - The bleed intensity.\n * @param {number} [_texture] - The texture strength.\n * @param {number} [_border] - The border strength.\n * @param {string} [_direction] - The bleed direction.\n */\nPolygon.prototype.fill = function (\n _color = false,\n _opacity,\n _bleed,\n _texture,\n _border,\n _direction,\n) {\n let state = FillState();\n if (_color) {\n fill(_color, _opacity);\n fillBleed(_bleed, _direction);\n fillTexture(_texture, _border);\n }\n if (state.isActive) {\n isFieldReady();\n createFill(this);\n }\n FillSetState(state);\n};\n\n/**\n * Fills a plot on the canvas by generating a polygon based on the provided coordinates.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - Scaling factor.\n */\nPlot.prototype.fill = function (x, y, scale) {\n if (FillState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n this.pol = this.genPol(\n x,\n y,\n scale,\n State.fill.bleed_strength < 0.06\n ? 0\n : map(State.fill.bleed_strength, 0, 0.6, 0.2, 0.60, true),\n );\n this.pol.fill();\n }\n};\n","\nexport default function earcut(data, holeIndices, dim = 2) {\n\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n let outerNode = linkedList(data, 0, outerLen, dim, true);\n const triangles = [];\n\n if (!outerNode || outerNode.next === outerNode.prev) return triangles;\n\n let minX, minY, invSize;\n\n if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);\n\n // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox\n if (data.length > 80 * dim) {\n minX = data[0];\n minY = data[1];\n let maxX = minX;\n let maxY = minY;\n\n for (let i = dim; i < outerLen; i += dim) {\n const x = data[i];\n const y = data[i + 1];\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n\n // minX, minY and invSize are later used to transform coords into integers for z-order calculation\n invSize = Math.max(maxX - minX, maxY - minY);\n invSize = invSize !== 0 ? 32767 / invSize : 0;\n }\n\n earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);\n\n return triangles;\n}\n\n// create a circular doubly linked list from polygon points in the specified winding order\nfunction linkedList(data, start, end, dim, clockwise) {\n let last;\n\n if (clockwise === (signedArea(data, start, end, dim) > 0)) {\n for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n } else {\n for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n }\n\n if (last && equals(last, last.next)) {\n removeNode(last);\n last = last.next;\n }\n\n return last;\n}\n\n// eliminate colinear or duplicate points\nfunction filterPoints(start, end) {\n if (!start) return start;\n if (!end) end = start;\n\n let p = start,\n again;\n do {\n again = false;\n\n if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {\n removeNode(p);\n p = end = p.prev;\n if (p === p.next) break;\n again = true;\n\n } else {\n p = p.next;\n }\n } while (again || p !== end);\n\n return end;\n}\n\n// main ear slicing loop which triangulates a polygon (given as a linked list)\nfunction earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {\n if (!ear) return;\n\n // interlink polygon nodes in z-order\n if (!pass && invSize) indexCurve(ear, minX, minY, invSize);\n\n let stop = ear;\n\n // iterate through ears, slicing them one by one\n while (ear.prev !== ear.next) {\n const prev = ear.prev;\n const next = ear.next;\n\n if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {\n triangles.push(prev.i, ear.i, next.i); // cut off the triangle\n\n removeNode(ear);\n\n // skipping the next vertex leads to less sliver triangles\n ear = next.next;\n stop = next.next;\n\n continue;\n }\n\n ear = next;\n\n // if we looped through the whole remaining polygon and can't find any more ears\n if (ear === stop) {\n // try filtering points and slicing again\n if (!pass) {\n earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);\n\n // if this didn't work, try curing all small self-intersections locally\n } else if (pass === 1) {\n ear = cureLocalIntersections(filterPoints(ear), triangles);\n earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);\n\n // as a last resort, try splitting the remaining polygon into two\n } else if (pass === 2) {\n splitEarcut(ear, triangles, dim, minX, minY, invSize);\n }\n\n break;\n }\n }\n}\n\n// check whether a polygon node forms a valid ear with adjacent nodes\nfunction isEar(ear) {\n const a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n // now make sure we don't have other points inside the potential ear\n const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox\n const x0 = Math.min(ax, bx, cx),\n y0 = Math.min(ay, by, cy),\n x1 = Math.max(ax, bx, cx),\n y1 = Math.max(ay, by, cy);\n\n let p = c.next;\n while (p !== a) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&\n area(p.prev, p, p.next) >= 0) return false;\n p = p.next;\n }\n\n return true;\n}\n\nfunction isEarHashed(ear, minX, minY, invSize) {\n const a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox\n const x0 = Math.min(ax, bx, cx),\n y0 = Math.min(ay, by, cy),\n x1 = Math.max(ax, bx, cx),\n y1 = Math.max(ay, by, cy);\n\n // z-order range for the current triangle bbox;\n const minZ = zOrder(x0, y0, minX, minY, invSize),\n maxZ = zOrder(x1, y1, minX, minY, invSize);\n\n let p = ear.prevZ,\n n = ear.nextZ;\n\n // look for points inside the triangle in both directions\n while (p && p.z >= minZ && n && n.z <= maxZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n // look for remaining points in decreasing z-order\n while (p && p.z >= minZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n }\n\n // look for remaining points in increasing z-order\n while (n && n.z <= maxZ) {\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n return true;\n}\n\n// go through all polygon nodes and cure small local self-intersections\nfunction cureLocalIntersections(start, triangles) {\n let p = start;\n do {\n const a = p.prev,\n b = p.next.next;\n\n if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {\n\n triangles.push(a.i, p.i, b.i);\n\n // remove two nodes involved\n removeNode(p);\n removeNode(p.next);\n\n p = start = b;\n }\n p = p.next;\n } while (p !== start);\n\n return filterPoints(p);\n}\n\n// try splitting polygon into two and triangulate them independently\nfunction splitEarcut(start, triangles, dim, minX, minY, invSize) {\n // look for a valid diagonal that divides the polygon into two\n let a = start;\n do {\n let b = a.next.next;\n while (b !== a.prev) {\n if (a.i !== b.i && isValidDiagonal(a, b)) {\n // split the polygon in two by the diagonal\n let c = splitPolygon(a, b);\n\n // filter colinear points around the cuts\n a = filterPoints(a, a.next);\n c = filterPoints(c, c.next);\n\n // run earcut on each half\n earcutLinked(a, triangles, dim, minX, minY, invSize, 0);\n earcutLinked(c, triangles, dim, minX, minY, invSize, 0);\n return;\n }\n b = b.next;\n }\n a = a.next;\n } while (a !== start);\n}\n\n// link every hole into the outer loop, producing a single-ring polygon without holes\nfunction eliminateHoles(data, holeIndices, outerNode, dim) {\n const queue = [];\n\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n const list = linkedList(data, start, end, dim, false);\n if (list === list.next) list.steiner = true;\n queue.push(getLeftmost(list));\n }\n\n queue.sort(compareXYSlope);\n\n // process holes from left to right\n for (let i = 0; i < queue.length; i++) {\n outerNode = eliminateHole(queue[i], outerNode);\n }\n\n return outerNode;\n}\n\nfunction compareXYSlope(a, b) {\n let result = a.x - b.x;\n // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find\n // the bridge to the outer shell is always the point that they meet at.\n if (result === 0) {\n result = a.y - b.y;\n if (result === 0) {\n const aSlope = (a.next.y - a.y) / (a.next.x - a.x);\n const bSlope = (b.next.y - b.y) / (b.next.x - b.x);\n result = aSlope - bSlope;\n }\n }\n return result;\n}\n\n// find a bridge between vertices that connects hole with an outer ring and link it\nfunction eliminateHole(hole, outerNode) {\n const bridge = findHoleBridge(hole, outerNode);\n if (!bridge) {\n return outerNode;\n }\n\n const bridgeReverse = splitPolygon(bridge, hole);\n\n // filter collinear points around the cuts\n filterPoints(bridgeReverse, bridgeReverse.next);\n return filterPoints(bridge, bridge.next);\n}\n\n// David Eberly's algorithm for finding a bridge between hole and outer polygon\nfunction findHoleBridge(hole, outerNode) {\n let p = outerNode;\n const hx = hole.x;\n const hy = hole.y;\n let qx = -Infinity;\n let m;\n\n // find a segment intersected by a ray from the hole's leftmost point to the left;\n // segment's endpoint with lesser x will be potential connection point\n // unless they intersect at a vertex, then choose the vertex\n if (equals(hole, p)) return p;\n do {\n if (equals(hole, p.next)) return p.next;\n else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {\n const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);\n if (x <= hx && x > qx) {\n qx = x;\n m = p.x < p.next.x ? p : p.next;\n if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint\n }\n }\n p = p.next;\n } while (p !== outerNode);\n\n if (!m) return null;\n\n // look for points inside the triangle of hole point, segment intersection and endpoint;\n // if there are no points found, we have a valid connection;\n // otherwise choose the point of the minimum angle with the ray as connection point\n\n const stop = m;\n const mx = m.x;\n const my = m.y;\n let tanMin = Infinity;\n\n p = m;\n\n do {\n if (hx >= p.x && p.x >= mx && hx !== p.x &&\n pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {\n\n const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential\n\n if (locallyInside(p, hole) &&\n (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {\n m = p;\n tanMin = tan;\n }\n }\n\n p = p.next;\n } while (p !== stop);\n\n return m;\n}\n\n// whether sector in vertex m contains sector in vertex p in the same coordinates\nfunction sectorContainsSector(m, p) {\n return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;\n}\n\n// interlink polygon nodes in z-order\nfunction indexCurve(start, minX, minY, invSize) {\n let p = start;\n do {\n if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);\n p.prevZ = p.prev;\n p.nextZ = p.next;\n p = p.next;\n } while (p !== start);\n\n p.prevZ.nextZ = null;\n p.prevZ = null;\n\n sortLinked(p);\n}\n\n// Simon Tatham's linked list merge sort algorithm\n// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html\nfunction sortLinked(list) {\n let numMerges;\n let inSize = 1;\n\n do {\n let p = list;\n let e;\n list = null;\n let tail = null;\n numMerges = 0;\n\n while (p) {\n numMerges++;\n let q = p;\n let pSize = 0;\n for (let i = 0; i < inSize; i++) {\n pSize++;\n q = q.nextZ;\n if (!q) break;\n }\n let qSize = inSize;\n\n while (pSize > 0 || (qSize > 0 && q)) {\n\n if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {\n e = p;\n p = p.nextZ;\n pSize--;\n } else {\n e = q;\n q = q.nextZ;\n qSize--;\n }\n\n if (tail) tail.nextZ = e;\n else list = e;\n\n e.prevZ = tail;\n tail = e;\n }\n\n p = q;\n }\n\n tail.nextZ = null;\n inSize *= 2;\n\n } while (numMerges > 1);\n\n return list;\n}\n\n// z-order of a point given coords and inverse of the longer side of data bbox\nfunction zOrder(x, y, minX, minY, invSize) {\n // coords are transformed into non-negative 15-bit integer range\n x = (x - minX) * invSize | 0;\n y = (y - minY) * invSize | 0;\n\n x = (x | (x << 8)) & 0x00FF00FF;\n x = (x | (x << 4)) & 0x0F0F0F0F;\n x = (x | (x << 2)) & 0x33333333;\n x = (x | (x << 1)) & 0x55555555;\n\n y = (y | (y << 8)) & 0x00FF00FF;\n y = (y | (y << 4)) & 0x0F0F0F0F;\n y = (y | (y << 2)) & 0x33333333;\n y = (y | (y << 1)) & 0x55555555;\n\n return x | (y << 1);\n}\n\n// find the leftmost node of a polygon ring\nfunction getLeftmost(start) {\n let p = start,\n leftmost = start;\n do {\n if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;\n p = p.next;\n } while (p !== start);\n\n return leftmost;\n}\n\n// check if a point lies within a convex triangle\nfunction pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {\n return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&\n (ax - px) * (by - py) >= (bx - px) * (ay - py) &&\n (bx - px) * (cy - py) >= (cx - px) * (by - py);\n}\n\n// check if a point lies within a convex triangle but false if its equal to the first point of the triangle\nfunction pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {\n return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);\n}\n\n// check if a diagonal between two polygon nodes is valid (lies in polygon interior)\nfunction isValidDiagonal(a, b) {\n return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges\n (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible\n (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors\n equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case\n}\n\n// signed area of a triangle\nfunction area(p, q, r) {\n return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);\n}\n\n// check if two points are equal\nfunction equals(p1, p2) {\n return p1.x === p2.x && p1.y === p2.y;\n}\n\n// check if two segments intersect\nfunction intersects(p1, q1, p2, q2) {\n const o1 = sign(area(p1, q1, p2));\n const o2 = sign(area(p1, q1, q2));\n const o3 = sign(area(p2, q2, p1));\n const o4 = sign(area(p2, q2, q1));\n\n if (o1 !== o2 && o3 !== o4) return true; // general case\n\n if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1\n if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1\n if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2\n if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2\n\n return false;\n}\n\n// for collinear points p, q, r, check if point q lies on segment pr\nfunction onSegment(p, q, r) {\n return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);\n}\n\nfunction sign(num) {\n return num > 0 ? 1 : num < 0 ? -1 : 0;\n}\n\n// check if a polygon diagonal intersects any polygon segments\nfunction intersectsPolygon(a, b) {\n let p = a;\n do {\n if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&\n intersects(p, p.next, a, b)) return true;\n p = p.next;\n } while (p !== a);\n\n return false;\n}\n\n// check if a polygon diagonal is locally inside the polygon\nfunction locallyInside(a, b) {\n return area(a.prev, a, a.next) < 0 ?\n area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :\n area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;\n}\n\n// check if the middle point of a polygon diagonal is inside the polygon\nfunction middleInside(a, b) {\n let p = a;\n let inside = false;\n const px = (a.x + b.x) / 2;\n const py = (a.y + b.y) / 2;\n do {\n if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&\n (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))\n inside = !inside;\n p = p.next;\n } while (p !== a);\n\n return inside;\n}\n\n// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;\n// if one belongs to the outer ring and another to a hole, it merges it into a single ring\nfunction splitPolygon(a, b) {\n const a2 = createNode(a.i, a.x, a.y),\n b2 = createNode(b.i, b.x, b.y),\n an = a.next,\n bp = b.prev;\n\n a.next = b;\n b.prev = a;\n\n a2.next = an;\n an.prev = a2;\n\n b2.next = a2;\n a2.prev = b2;\n\n bp.next = b2;\n b2.prev = bp;\n\n return b2;\n}\n\n// create a node and optionally link it with previous one (in a circular doubly linked list)\nfunction insertNode(i, x, y, last) {\n const p = createNode(i, x, y);\n\n if (!last) {\n p.prev = p;\n p.next = p;\n\n } else {\n p.next = last.next;\n p.prev = last;\n last.next.prev = p;\n last.next = p;\n }\n return p;\n}\n\nfunction removeNode(p) {\n p.next.prev = p.prev;\n p.prev.next = p.next;\n\n if (p.prevZ) p.prevZ.nextZ = p.nextZ;\n if (p.nextZ) p.nextZ.prevZ = p.prevZ;\n}\n\nfunction createNode(i, x, y) {\n return {\n i, // vertex index in coordinates array\n x, y, // vertex coordinates\n prev: null, // previous and next vertex nodes in a polygon ring\n next: null,\n z: 0, // z-order curve value\n prevZ: null, // previous and next nodes in z-order\n nextZ: null,\n steiner: false // indicates whether this is a steiner point\n };\n}\n\n// return a percentage difference between the polygon area and its triangulation area;\n// used to verify correctness of triangulation\nexport function deviation(data, holeIndices, dim, triangles) {\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n\n let polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));\n if (hasHoles) {\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n polygonArea -= Math.abs(signedArea(data, start, end, dim));\n }\n }\n\n let trianglesArea = 0;\n for (let i = 0; i < triangles.length; i += 3) {\n const a = triangles[i] * dim;\n const b = triangles[i + 1] * dim;\n const c = triangles[i + 2] * dim;\n trianglesArea += Math.abs(\n (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -\n (data[a] - data[b]) * (data[c + 1] - data[a + 1]));\n }\n\n return polygonArea === 0 && trianglesArea === 0 ? 0 :\n Math.abs((trianglesArea - polygonArea) / polygonArea);\n}\n\nfunction signedArea(data, start, end, dim) {\n let sum = 0;\n for (let i = start, j = end - dim; i < end; i += dim) {\n sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);\n j = i;\n }\n return sum;\n}\n\n// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts\nexport function flatten(data) {\n const vertices = [];\n const holes = [];\n const dimensions = data[0][0].length;\n let holeIndex = 0;\n let prevLen = 0;\n\n for (const ring of data) {\n for (const p of ring) {\n for (let d = 0; d < dimensions; d++) vertices.push(p[d]);\n }\n if (prevLen) {\n holeIndex += prevLen;\n holes.push(holeIndex);\n }\n prevLen = ring.length;\n }\n return {vertices, holes, dimensions};\n}\n","// =============================================================================\n// Module: Wash\n// =============================================================================\n/**\n * Minimal stateful API for the `wash()` fill modifier.\n */\n\nimport earcut from \"earcut\";\nimport { Renderer, Cwidth, Cheight, isCanvasReady } from \"../core/target.js\";\nimport { State, flushActiveComposite } from \"../core/color.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { getAffineMatrix } from \"../core/runtime.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport { createColor } from \"../core/runtime.js\";\nimport { resetDirectShaderTracking } from \"../core/renderer_runtime.js\";\n\nlet gl = null;\nlet washProgram = null;\nlet washVao = null;\nlet washBuffer = null;\nlet washProjection = null;\nlet loadedWidth = 0;\nlet loadedHeight = 0;\nlet washGpuBufferSize = 0;\n\nconst WashAttr = {};\nconst WashUniform = {};\n\nconst washVertSrc = `#version 300 es\nin vec2 a_position;\nuniform mat4 u_matrix;\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n}`;\n\nconst washFragSrc = `#version 300 es\nprecision highp float;\nuniform vec4 u_color;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(u_color.rgb * u_color.a, u_color.a);\n}`;\n\nState.wash = {\n color: null,\n opacity: 150,\n isActive: false,\n};\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Enables wash mode with a color and opacity.\n *\n * @param {number|string|Color} a - Either the red component, a CSS color string, or a Color object.\n * @param {number} [b] - The green component or the opacity if using grayscale.\n * @param {number} [c] - The blue component.\n * @param {number} [d] - The opacity.\n */\nexport function wash(a, b, c, d) {\n isCanvasReady();\n State.wash.opacity = (arguments.length < 4 ? b : d) ?? 150;\n State.wash.color = arguments.length < 3 ? createColor(a) : createColor(a, b, c);\n State.wash.isActive = true;\n}\n\n/**\n * Disables wash mode for subsequent drawing operations.\n */\nexport function noWash() {\n State.wash.isActive = false;\n}\n\n// =============================================================================\n// GL helpers\n// =============================================================================\n\n/**\n * Lazily creates the reusable program/buffer state for solid wash drawing and\n * refreshes the orthographic projection when the active target size changes.\n */\nfunction ensureWashReady() {\n const nextGl = Renderer.drawingContext;\n const sizeChanged = loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (!washProjection || sizeChanged) {\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n washProjection = new Float32Array([\n 2 / loadedWidth,\n 0,\n 0,\n 0,\n 0,\n -2 / loadedHeight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n 1,\n 0,\n 1,\n ]);\n }\n\n if (gl === nextGl && washProgram && washVao && washBuffer) return;\n\n gl = nextGl;\n washProgram = createProgram(gl, washVertSrc, washFragSrc);\n WashAttr.a_position = gl.getAttribLocation(washProgram, \"a_position\");\n WashUniform.u_matrix = gl.getUniformLocation(washProgram, \"u_matrix\");\n WashUniform.u_color = gl.getUniformLocation(washProgram, \"u_color\");\n\n washVao = gl.createVertexArray();\n gl.bindVertexArray(washVao);\n\n washBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, 0, gl.DYNAMIC_DRAW);\n washGpuBufferSize = 0;\n\n gl.enableVertexAttribArray(WashAttr.a_position);\n gl.vertexAttribPointer(WashAttr.a_position, 2, gl.FLOAT, false, 8, 0);\n\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n}\n\n/**\n * Applies the current runtime affine transform and converts the result into\n * the screen-space coordinates used by the direct GL wash pipeline.\n *\n * @param {number} x - The source x-coordinate in brush drawing space.\n * @param {number} y - The source y-coordinate in brush drawing space.\n * @returns {[number, number]} The transformed screen-space position.\n */\nfunction transformVertexToScreen(x, y) {\n const m = getAffineMatrix();\n return [\n m.a * x + m.c * y + m.x + loadedWidth / 2,\n m.b * x + m.d * y + m.y + loadedHeight / 2,\n ];\n}\n\n/**\n * Triangulates a polygon in local space and returns the transformed triangle\n * vertex buffer ready for upload to the GPU.\n *\n * @param {Polygon} polygon - The polygon to triangulate.\n * @returns {{ triangles: Float32Array, vertexCount: number }} Screen-space\n * triangle vertices plus the number of vertices to draw.\n */\nfunction buildTriangleBuffer(polygon) {\n const flat = new Float32Array(polygon.vertices.length * 2);\n for (let i = 0; i < polygon.vertices.length; i++) {\n const vertex = polygon.vertices[i];\n flat[i * 2] = vertex.x;\n flat[i * 2 + 1] = vertex.y;\n }\n\n const indices = earcut(flat);\n const triangles = new Float32Array(indices.length * 2);\n for (let i = 0; i < indices.length; i++) {\n const idx = indices[i];\n const [screenX, screenY] = transformVertexToScreen(flat[idx * 2], flat[idx * 2 + 1]);\n triangles[i * 2] = screenX;\n triangles[i * 2 + 1] = screenY;\n }\n\n return {\n triangles,\n vertexCount: indices.length,\n };\n}\n\n/**\n * Draws a triangulated solid wash directly to the current GL target.\n *\n * @param {Polygon} polygon - The polygon to fill with the current wash state.\n */\nfunction drawWashPolygon(polygon) {\n if (!State.wash?.isActive || !State.wash.color || polygon.vertices.length < 3) return;\n\n flushActiveComposite();\n ensureWashReady();\n const { triangles, vertexCount } = buildTriangleBuffer(polygon);\n const byteCount = triangles.byteLength;\n gl.useProgram(washProgram);\n gl.enable(gl.BLEND);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n gl.bindVertexArray(washVao);\n gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);\n if (byteCount > washGpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, triangles, gl.DYNAMIC_DRAW);\n washGpuBufferSize = byteCount;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, triangles);\n }\n const color = State.wash.color._array;\n gl.uniformMatrix4fv(WashUniform.u_matrix, false, washProjection);\n gl.uniform4f(\n WashUniform.u_color,\n color[0],\n color[1],\n color[2],\n State.wash.opacity / 255,\n );\n\n gl.drawArrays(gl.TRIANGLES, 0, vertexCount);\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n resetDirectShaderTracking(Renderer, gl);\n}\n\n// =============================================================================\n// Prototype methods\n// =============================================================================\n\n/**\n * Applies a direct GL wash fill to the polygon using the current wash state.\n *\n * @param {Color|string|false} [_color] - Optional override color for this call.\n * @param {number} [_opacity] - Optional override opacity for this call.\n */\nPolygon.prototype.wash = function (_color = false, _opacity) {\n const state = { ...State.wash };\n if (_color !== false) wash(_color, _opacity);\n\n if (State.wash.isActive) {\n drawWashPolygon(this);\n }\n\n State.wash = { ...state };\n};\n\n/**\n * Applies wash to a plot by first generating the plot polygon, mirroring the\n * existing fill-path behavior, and then drawing that polygon with wash.\n *\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\nPlot.prototype.wash = function (x, y, scale) {\n if (!State.wash?.isActive) return;\n if (this.origin) {\n x = this.origin[0];\n y = this.origin[1];\n scale = 1;\n }\n this.pol = this.genPol(x, y, scale, 0, -1);\n this.pol.wash();\n};\n","// =============================================================================\n// Adapter: p5 Runtime Target Resolution\n// =============================================================================\n/**\n * Owns the active renderer/instance selection used by p5.brush when running\n * on top of p5's WEBGL renderer.\n */\n\nimport {\n setTargetRuntime,\n setTargetState,\n Instance,\n Renderer,\n} from \"../../core/target.js\";\n\nlet ReadySketch = null;\nlet ActiveInstance = null;\nconst ActiveInstanceStack = [];\nlet _isReady = false;\n\n/**\n * Checks whether the given draw target is a p5.Framebuffer-like object.\n * @param {*} target - Candidate draw target.\n * @returns {boolean} True when the target behaves like a p5.Framebuffer.\n */\nexport const isFramebufferTarget = (target) =>\n !!target &&\n typeof target.begin === \"function\" &&\n typeof target.end === \"function\" &&\n !!target.renderer &&\n !!target.renderer._pInst;\n\nconst isFiniteSize = (value) =>\n typeof value === \"number\" && Number.isFinite(value) && value > 0;\n\nconst safeRead = (getter) => {\n try {\n return getter();\n } catch (_error) {\n return undefined;\n }\n};\n\nconst isReadyWebGLSketch = (candidate) =>\n !!candidate &&\n typeof candidate.pixelDensity === \"function\" &&\n typeof candidate.createFramebuffer === \"function\" &&\n isFiniteSize(safeRead(() => candidate.width)) &&\n isFiniteSize(safeRead(() => candidate.height)) &&\n safeRead(() => candidate.webglVersion) === \"webgl2\";\n\nconst getCurrentP5Instance = () => window.self?.p5?.instance ?? null;\n\nconst rememberReadySketch = (candidate) => {\n if (isReadyWebGLSketch(candidate)) ReadySketch = candidate;\n return ReadySketch;\n};\n\nconst getActiveSketchRenderer = () => {\n if (!ActiveInstance) return null;\n if (!isReadyWebGLSketch(ActiveInstance)) return null;\n return rememberReadySketch(ActiveInstance);\n};\n\n/**\n * Resolves the sketch renderer that owns the current drawing session.\n * Preference order:\n * 1. the sketch currently executing a p5 lifecycle callback\n * 2. the explicitly selected instance from brush.instance(p), if ready\n * 3. the last known-good ready sketch\n * @returns {p5|Window[\"p5\"][\"instance\"]|null} The active sketch renderer.\n */\nexport const getSketchRenderer = () =>\n getActiveSketchRenderer() ||\n rememberReadySketch(getCurrentP5Instance()) ||\n rememberReadySketch(Instance) ||\n ReadySketch;\n\n/**\n * Resolves the renderer and pixel size used by `brush.load()`.\n * @param {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional draw target.\n * @returns {{renderer: object, width: number, height: number}} Active renderer info.\n */\nconst resolveTarget = (buffer = false) => {\n const sketchRenderer = getSketchRenderer();\n\n if (!buffer) {\n if (!sketchRenderer) {\n throw new Error(\n \"p5.brush could not resolve an active WEBGL sketch. Call brush.instance(p) and brush.load() after createCanvas(..., WEBGL).\",\n );\n }\n return {\n renderer: sketchRenderer,\n width: sketchRenderer.width,\n height: sketchRenderer.height,\n };\n }\n\n if (isFramebufferTarget(buffer)) {\n const owner = buffer.renderer._pInst;\n rememberReadySketch(owner);\n\n if (sketchRenderer && owner !== sketchRenderer) {\n throw new Error(\n \"p5.brush only supports p5.Framebuffer targets created from the active sketch\",\n );\n }\n\n return {\n renderer: owner,\n width: buffer.width,\n height: buffer.height,\n };\n }\n\n return {\n renderer: buffer,\n width: buffer.width,\n height: buffer.height,\n };\n};\n\n/**\n * Returns the currently bound sketch framebuffer when drawing into one.\n * @returns {p5.Framebuffer|null} Active framebuffer or null.\n */\nexport const getActiveFramebuffer = () =>\n Renderer?._renderer?.activeFramebuffer?.() ?? null;\n\n/**\n * Loads and initializes a canvas for the drawing system.\n * @param {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional offscreen target.\n * Pass a framebuffer only while drawing inside its begin()/end() or draw() scope.\n * Framebuffers created from p5.Graphics are not supported.\n */\nexport const load = (buffer = false) => {\n const target = resolveTarget(buffer);\n setTargetState({ Renderer: target.renderer });\n rememberReadySketch(!buffer ? Renderer : getSketchRenderer());\n\n if (Renderer.webglVersion !== \"webgl2\") {\n throw new Error(\"p5.brush requires a WEBGL canvas\");\n }\n\n setTargetState({\n Cwidth: target.width,\n Cheight: target.height,\n });\n\n _isReady = true;\n};\n\n/**\n * Refreshes the stored pixel density for the active renderer.\n * @returns {number} Current renderer pixel density.\n */\nexport const syncDensity = () => {\n const density = Renderer.pixelDensity();\n setTargetState({ Density: density });\n return density;\n};\n\n/**\n * Ensures the drawing system is ready before any operation.\n */\nexport const isCanvasReady = () => {\n if (!_isReady) load();\n};\n\nexport const instance = (inst) => {\n setTargetState({ Instance: inst });\n rememberReadySketch(inst);\n};\n\nexport const activateInstance = (inst) => {\n ActiveInstanceStack.push(ActiveInstance);\n ActiveInstance = inst;\n instance(inst);\n};\n\nexport const deactivateInstance = () => {\n ActiveInstance = ActiveInstanceStack.pop() ?? null;\n};\n\nexport function initP5TargetRuntime() {\n setTargetRuntime({\n load,\n syncDensity,\n isCanvasReady,\n instance,\n activateInstance,\n deactivateInstance,\n getActiveFramebuffer,\n isFramebufferTarget,\n });\n}\n","// =============================================================================\n// Adapter: p5 Runtime Hooks\n// =============================================================================\n\nimport { setRuntime } from \"../../core/runtime.js\";\nimport { Renderer } from \"../../core/target.js\";\nimport { getSketchRenderer } from \"./target.js\";\n\nconst getP5RuntimeRenderer = () =>\n Renderer ?? getSketchRenderer?.() ?? window.self?.p5?.instance ?? null;\nconst identityMatrix = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\nconst affineMatrix = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\n\nfunction isRadians() {\n const renderer = getP5RuntimeRenderer();\n return !!renderer &&\n typeof renderer.angleMode === \"function\" &&\n renderer.angleMode() === renderer.RADIANS;\n}\n\nexport function initP5Runtime() {\n setRuntime({\n usesRadians: isRadians,\n\n fromDegrees: (angle) =>\n isRadians() ? (angle * Math.PI) / 180 : angle,\n\n createColor: (...args) => {\n const renderer = getP5RuntimeRenderer();\n if (!renderer?.color) {\n throw new Error(\"p5 runtime color creation requires an active renderer.\");\n }\n return renderer.color(...args);\n },\n\n getAffineMatrix: () => {\n const renderer = getP5RuntimeRenderer();\n const mat4 = renderer?._renderer?.uModelMatrix?.mat4;\n if (!mat4) return identityMatrix;\n\n affineMatrix.a = mat4[0];\n affineMatrix.b = mat4[1];\n affineMatrix.c = mat4[4];\n affineMatrix.d = mat4[5];\n affineMatrix.x = mat4[12];\n affineMatrix.y = mat4[13];\n return affineMatrix;\n },\n });\n}\n","// =============================================================================\n// Adapter: p5 Renderer Hooks\n// =============================================================================\n\nimport { setRendererRuntime } from \"../../core/renderer_runtime.js\";\n\nfunction getFramebufferHandle(target) {\n if (!target) return null;\n if (typeof target._framebufferToBind === \"function\") return target._framebufferToBind();\n return target.framebuffer ?? null;\n}\n\nfunction beginDirectMaskDraw(renderer, gl, target) {\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n if (hadDepthTest) gl.disable(gl.DEPTH_TEST);\n\n const previousTarget = renderer._renderer.activeFramebuffer?.() ?? null;\n if (previousTarget?._beforeEnd) previousTarget._beforeEnd();\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, getFramebufferHandle(target));\n gl.viewport(0, 0, target.width * target.density, target.height * target.density);\n\n return { hadDepthTest, previousTarget };\n}\n\nfunction endDirectMaskDraw(renderer, gl, state) {\n if (state?.hadDepthTest) gl.enable(gl.DEPTH_TEST);\n\n if (state?.previousTarget?._beforeBegin) {\n state.previousTarget._beforeBegin();\n return;\n }\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n renderer._renderer.viewport(\n renderer._renderer._origViewport.width,\n renderer._renderer._origViewport.height,\n );\n renderer._renderer._applyStencilTestIfClipping?.();\n}\n\nfunction resetP5ShaderTracking(renderer, gl) {\n const coreRenderer = renderer?._renderer;\n if (!coreRenderer) return;\n coreRenderer._curShader = null;\n coreRenderer._cachedBlendMode = null;\n coreRenderer._isBlending = null;\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n}\n\nexport function initP5RendererRuntime() {\n setRendererRuntime({\n beginDirectMaskDraw,\n endDirectMaskDraw,\n resetDirectShaderTracking: resetP5ShaderTracking,\n });\n}\n","// =============================================================================\n// Adapter: p5 Compositor Hooks\n// =============================================================================\n\nimport {\n setCompositorRuntime,\n blitDefaultFramebufferSource,\n} from \"../../core/compositor_runtime.js\";\n\nfunction clearTarget(renderer, target, isFramebufferTarget) {\n if (!target) return;\n\n if (isFramebufferTarget(target)) {\n target.draw(() => renderer.clear());\n return;\n }\n\n const ctx = target.drawingContext;\n ctx.save();\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.clearRect(0, 0, target.width, target.height);\n ctx.restore();\n}\n\nfunction ensureBlendShaderProgram(renderer, vertSrc, fragSrc) {\n if (!renderer.loaded) {\n renderer.loaded = true;\n renderer.shaderProgram ??= renderer.createShader(vertSrc, fragSrc);\n }\n return renderer.shaderProgram;\n}\n\nfunction ensureBlendSourceFramebuffer(\n renderer,\n currentFramebuffer,\n width,\n height,\n density,\n) {\n if (currentFramebuffer?.remove) currentFramebuffer.remove();\n const fb = renderer.createFramebuffer({\n width,\n height,\n density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n return fb;\n}\n\nconst createFramebuffer = (renderer, options) =>\n renderer.createFramebuffer(options);\n\nfunction runBlendShaderPass({\n renderer,\n shader,\n source,\n mask,\n color,\n isBrushMask,\n Cwidth,\n Cheight,\n dirtyRect,\n targetIsFramebuffer,\n withScissor,\n}) {\n const gl = renderer.drawingContext;\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n\n gl.disable(gl.DEPTH_TEST);\n\n renderer.push();\n renderer.translate(0, 0);\n renderer.shader(shader);\n\n shader.setUniform(\"u_source\", source);\n shader.setUniform(\"u_targetIsFramebuffer\", targetIsFramebuffer);\n shader.setUniform(\"u_isBrush\", isBrushMask);\n shader.setUniform(\"u_mask\", mask);\n shader.setUniform(\"u_color\", color);\n\n withScissor(\n gl,\n dirtyRect,\n () => {\n renderer.fill(0, 0, 0, 0);\n renderer.noStroke();\n renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);\n },\n !targetIsFramebuffer,\n );\n\n renderer.pop();\n renderer.resetShader();\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n}\n\nfunction blitSourceToFramebuffer(args) {\n if (args.isFramebufferTarget(args.sourceTarget)) {\n (args.sourceTarget.renderer ?? args.renderer)._renderer?.flushDraw?.();\n args.sourceFramebuffer.draw(() => {\n args.withScissor(\n args.renderer.drawingContext,\n args.dirtyRect,\n () => {\n args.renderer.clear();\n args.renderer.push();\n args.renderer.imageMode(args.renderer.CENTER);\n args.renderer.image(\n args.sourceTarget,\n 0,\n 0,\n args.Cwidth,\n args.Cheight,\n );\n args.renderer.pop();\n },\n false,\n );\n });\n return args.sourceFramebuffer;\n }\n\n args.renderer._renderer?.flushDraw?.();\n return blitDefaultFramebufferSource(args);\n}\n\nexport function initP5CompositorRuntime() {\n setCompositorRuntime({\n clearTarget,\n ensureBlendShaderProgram,\n ensureBlendSourceFramebuffer,\n createFramebuffer,\n runBlendShaderPass,\n blitSourceToFramebuffer,\n });\n}\n","// =============================================================================\n// Adapter: p5 Stroke Hooks\n// =============================================================================\n\nimport { Renderer, Instance } from \"../../core/target.js\";\nimport { setStrokeRuntime } from \"../../stroke/runtime.js\";\n\nconst getP5BrushFactory = () => Renderer ?? Instance ?? window.self?.p5?.instance;\n\nfunction createTipSurface(width, height) {\n const factory = getP5BrushFactory();\n if (!factory?.createGraphics) {\n throw new Error(\"p5 stroke tip creation requires an active renderer or instance.\");\n }\n return factory.createGraphics(width, height);\n}\n\nfunction loadImageTip(src, imageToWhite) {\n return new Promise((resolve, reject) => {\n const nativeImg = new window.Image();\n nativeImg.onload = () => {\n const factory = getP5BrushFactory();\n if (!factory?.createImage) {\n reject(new Error(\"p5 image tip loading requires an active renderer or instance.\"));\n return;\n }\n const p5img = factory.createImage(\n nativeImg.naturalWidth,\n nativeImg.naturalHeight,\n );\n p5img.drawingContext.drawImage(nativeImg, 0, 0);\n imageToWhite(p5img);\n resolve(p5img);\n };\n nativeImg.onerror = () =>\n reject(new Error(`Failed to load image tip: ${src}`));\n nativeImg.crossOrigin = \"anonymous\";\n nativeImg.src = src;\n });\n}\n\nexport function initP5StrokeRuntime() {\n setStrokeRuntime({\n createTipSurface,\n loadImageTip,\n });\n}\n","import { State } from \"./color.js\";\nimport { isFieldReady } from \"./flowfield.js\";\n\n// =============================================================================\n// SAVE / RESTORE\n// =============================================================================\n\n/**\n * Stack of saved brush states for push/pop operations.\n * A stack (not a single slot) is required because applyShader() internally\n * calls Renderer.push()/pop(), which fires our hook — a flat object would be\n * overwritten mid-draw and pop() would restore the wrong state.\n */\nconst _stateStack = [];\n\n/**\n * Pushes the current brush state onto the stack.\n */\nexport function push() {\n isFieldReady();\n _stateStack.push({\n fill: { ...State.fill },\n wash: State.wash ? { ...State.wash } : null,\n stroke: { ...State.stroke },\n hatch: { ...State.hatch },\n mass: State.mass ? { ...State.mass } : null,\n field: { ...State.field },\n });\n}\n\n/**\n * Pops the top brush state from the stack and restores it.\n */\nexport function pop() {\n const saved = _stateStack.pop();\n if (!saved) return;\n State.stroke = { ...saved.stroke };\n State.field = { ...saved.field };\n State.hatch = { ...saved.hatch };\n State.fill = { ...saved.fill };\n if (saved.wash) State.wash = { ...saved.wash };\n if (saved.mass) {\n State.mass = { ...saved.mass };\n } else if (State.mass) {\n State.mass = {\n ...State.mass,\n isActive: false,\n brush: null,\n color: null,\n options: {},\n };\n }\n}\n","/**\n * @fileoverview p5 entry point for p5.brush.\n */\n\nexport * from \"./index.shared.js\";\n\nimport { initP5TargetRuntime } from \"./adapters/p5/target.js\";\nimport { initP5Runtime } from \"./adapters/p5/runtime.js\";\nimport { initP5RendererRuntime } from \"./adapters/p5/renderer.js\";\nimport { initP5CompositorRuntime } from \"./adapters/p5/compositor.js\";\nimport { initP5StrokeRuntime } from \"./adapters/p5/stroke.js\";\nimport { registerP5Addon } from \"./adapters/p5/addon.js\";\n\ninitP5TargetRuntime();\ninitP5Runtime();\ninitP5RendererRuntime();\ninitP5CompositorRuntime();\ninitP5StrokeRuntime();\n\nif (typeof p5 !== \"undefined\") p5.registerAddon(registerP5Addon);\n","// =============================================================================\n// Adapter: p5 Addon Registration\n// =============================================================================\n\nimport { flushActiveComposite } from \"../../core/color.js\";\nimport {\n instance as bindInstance,\n activateInstance,\n deactivateInstance,\n} from \"../../core/target.js\";\nimport { push as brushPush, pop as brushPop } from \"../../core/save.js\";\nimport { seed as brushSeed, noiseSeed as brushNoiseSeed } from \"../../core/utils.js\";\n\n/**\n * Registers the p5 addon hooks that keep p5.brush in sync with p5's runtime.\n *\n * This stays in the p5 adapter layer so a future standalone build can provide\n * its own lifecycle integration without importing p5-specific globals.\n *\n * @param {*} _p5\n * @param {Object} fn\n * @param {Object} lifecycles\n */\nexport function registerP5Addon(_p5, fn, lifecycles) {\n lifecycles.presetup = function () {\n activateInstance(this);\n };\n\n lifecycles.predraw = function () {\n activateInstance(this);\n };\n\n lifecycles.postsetup = function () {\n bindInstance(this);\n flushActiveComposite();\n deactivateInstance();\n };\n\n lifecycles.postdraw = function () {\n bindInstance(this);\n flushActiveComposite();\n deactivateInstance();\n };\n\n const _push = fn.push;\n const _pop = fn.pop;\n const _randomSeed = fn.randomSeed;\n const _noiseSeed = fn.noiseSeed;\n\n fn.push = function () {\n _push.call(this);\n brushPush();\n };\n\n fn.pop = function () {\n _pop.call(this);\n brushPop();\n };\n\n fn.randomSeed = function (s) {\n _randomSeed.call(this, s);\n brushSeed(s);\n };\n\n fn.noiseSeed = function (s) {\n _noiseSeed.call(this, s);\n brushNoiseSeed(s);\n };\n}\n"],"names":["identityMatrix","a","b","c","d","x","y","usesRadians","fromDegrees","angle","createColor","Error","getAffineMatrix","SQRT3","Math","sqrt","F2","G2","fastFloor","floor","grad2","Float64Array","createNoise2D","random","perm","p","Uint8Array","i","tableSize","r","aux","buildPermutationTable","permGrad2x","map","v","permGrad2y","n0","n1","n2","s","j","t","x0","y0","i1","j1","x1","y1","x2","y2","ii","jj","t0","gi0","t1","gi1","t2","gi2","prng_alea","seed","opts","xg","AleaGen","prng","next","double","int32","quick","constructor","Date","n","mash","data","String","length","charCodeAt","h","this","s0","s1","s2","copy","f","rng","rng2","_seedCallbacks","_onSeed","cb","push","callback","noise","noise2","noiseSeed","rr","e","rr2","rArray","array","randInt","randInt2","gaussian","mean","stdev","u","log","cos","weightedRand","weights","totalWeight","entries","key","cumulative","rnd","isNaN","parseInt","value","withinBounds","constrain","low","high","max","min","nAngle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","fill","NaN","sLookup","idx","sin","toDegrees","rad","isRad","runtimeUsesRadians","toDegreesSigned","rotate","cx","cy","coseno","seno","dist","hypot","calcAngle","atan2","intersectLines","s1a","s1b","s2a","s2b","includeSegmentExtension","x3","y3","x4","y4","deltaX1","deltaY1","deltaX2","deltaY2","denominator","ua","ub","Cwidth","Cheight","Instance","Renderer","Density","targetRuntime","load","syncDensity","isCanvasReady","instance","inst","activateInstance","deactivateInstance","getActiveFramebuffer","isFramebufferTarget","setTargetState","state","target","expandDirtyRect","rect","padding","minX","minY","maxX","maxY","create2DCanvas","width","height","willReadFrequently","canvas","OffscreenCanvas","element","document","createElement","drawingContext","getContext","undefined","compositorRuntime","clearTarget","ensureBlendShaderProgram","ensureBlendSourceFramebuffer","createFramebuffer","runBlendShaderPass","blitSourceToFramebuffer","args","strokeComposite","fillComposite","clearRenderTarget","getTargetPixelSize","round","normalizeDirtyRect","ceil","clampDirtyRect","getFullDirtyRect","getFullRect","toScissorBox","flipY","normalized","withScissor","gl","draw","box","enable","SCISSOR_TEST","scissor","disable","State","isMixReady","loaded","Mix","isBlending","cachedColor","markDirtyRect","dirtyRect","isDrawn","clearMask","composite","glMask","getCompositeRect","isBrushMask","needsBlendSourceFramebuffer","blendSourceFramebuffer","pixelDensity","ensureResources","fillResources","mask","ctx","blend","_color","_isLast","isBrush","otherMask","nextColor","_array","colorChanged","justChanged","applyShader","shader","shaderProgram","activeFramebuffer","source","renderer","sourceTarget","sourceFramebuffer","targetIsFramebuffer","shaderMask","getShaderMask","color","flushActiveComposite","buffer","loadTarget","isLoaded","isFieldReady","resolution","left_x","top_y","num_columns","num_rows","addField","field","bs","ba","fillField","ar","abs","dif","sr","cr","_t","dir","offset","attractors","Array","from","wx","wy","att","dx","dy","w","freq","amp","_r","Position","m","mx","my","update","plotted","isActive","colIdx","rowIdx","reset","isIn","isInCanvas","skipCheck","list","get","current","wiggle","moveTo","_dir","_length","_step_length","movePos","_moveToDegrees","plotTo","_plot","_scale","precomputedAngle","_dirPlot","_step","scaleFactor","steps","fieldActive","usePlot","plotAngle","getRowIndex","y_offset","getColIndex","x_offset","col","row","Map","FIELD_ANGLE_MODES","Set","normalizeFieldAngleMode","options","angleMode","has","generateField","entry","normalizeFieldAngles","gen","refreshField","currentField","keys","join","noField","name","funct","set","listFields","fn","Polygon","pointsArray","useRawVertices","vertices","sides","arr","_intersectionCache","intersect","line","cacheKey","point1","point2","points","start","end","intersection","show","wash","mass","hatch","stroke","Plot","_type","segments","angles","pres","type","calcIndex","pol","addSegment","_a","_pres","_degrees","pop","reduce","sum","len","endPlot","pressure","_d","curving","index","map0","map1","suma","genPol","_x","_y","_side","step","numSteps","pos","pside","prevIdx","scale","polygon","mode","beginShape","vertex","endShape","circle","radius","arcLength","angleOffset","randomFactor","randomAngle","offsetX","offsetY","arc","startDeg","sweepDeg","segmentCount","segmentSweep","startX","startY","_current","_curvature","_strokeArray","_strokeOrigin","SubPath","isClosed","curvature","vert","_createSpline","close","beginStroke","move","endStroke","spline","_array_points","PI2","pep","tep","pep2","done","p1","p2","p3","d1","d2","a1","a2","curvAdjust","dmax","temp","temp2","point3","point4","intPt","halfDist","asin","origin","strokeRuntime","createTipSurface","loadImageTip","isStrokeCompositeRegistered","createProgram","frag","src","VERTEX_SHADER","FRAGMENT_SHADER","createShader","shaderSource","compileShader","attachShader","linkProgram","rendererRuntime","beginDirectMaskDraw","endDirectMaskDraw","resetDirectShaderTracking","framebufferProjMatrix","vao","buf","program","loadedWidth","loadedHeight","brushMaskTarget","Attr","Frag","_ma","_mb","_mc","_md","_mx","_my","_halfW","_halfH","_density","circleData","INITIAL_CAPACITY","circleCount","bufferCapacity","gpuBufferSize","circleDirtyRect","imgProgram","imgVao","imgCornerBuf","imgInstanceBuf","imgAttr","imgFrag","imgGpuSize","imgData","IMG_INIT_CAP","imgCount","imgCapacity","imgDirtyRect","texCache","QUAD_CORNERS","getProjectionMatrix","beginMaskTarget","endMaskTarget","accumulateDirtyRect","currentRect","diameter","alpha","newData","px","py","screenX","screenY","dScreenX","dScreenY","glDrawImages","p5img","targetState","tex","createTexture","bindTexture","TEXTURE_2D","texImage2D","RGBA","UNSIGNED_BYTE","texParameteri","TEXTURE_MIN_FILTER","LINEAR","TEXTURE_MAG_FILTER","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","useProgram","BLEND","blendFunc","ONE_MINUS_DST_ALPHA","ONE","activeTexture","TEXTURE0","uniform1i","u_tex","uniform4f","u_color","uniformMatrix4fv","u_proj","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","drawArraysInstanced","TRIANGLE_STRIP","needsStrokeMask","remove","density","antialias","depth","stencil","_Renderer","weight","opacity","DEFAULT_CUSTOM_PRESSURE_VARIATION","warp","tilt","BrushState","BrushSetState","add","params","includes","markerTip","vibration","scatter","definition","sharpness","quality","grain","min_max","curve","variation","isArray","rest","range","ns","nm","ne","normalizePressure","tip","deleteTexture","delete","invalidateTexEntry","g","background","noSmooth","translate","noStroke","T","imageToWhite","tips","tipKey","param","colors","buffers","image","getBrushParams","brushName","scaleBrushes","values","spacing","pick","arguments","strokeWeight","clip","region","noClip","_position","_cachedPlotAngle","initializeDrawingState","plot","snapshotMatrix","gaussians","angleScale","isPlot","isCustomPressure","cp","ct","cs","ck","noiseoffset","rendererMask","ensureBrushMaskTarget","nextGl","needsContextRefresh","forEach","getAttribLocation","getUniformLocation","createVertexArray","createBuffer","enableVertexAttribArray","a_position","vertexAttribPointer","FLOAT","a_radius","a_alpha","clear","STATIC_DRAW","a_corner","a_pos","IMG_FLOATS","vertexAttribDivisor","a_size","a_angle","isReady","switchingToBrush","overscan","maxPressure","scatterReach","tipReach","getImageTipOverscan","drawFn","drawSpray","drawMarker","drawImageTip","drawDefault","saveState","stepSize","totalSteps","pressureCount","cachedPressure","lineNoiseCount","cachedLineNoise","neededGaussians","u_matrix","drawArrays","POINTS","glDraw","restoreState","calculatePressure","lineNoise","simPressure","peakPos","halfWidth","pow","gauss","sw","iterations","rX","yRandomFactor","sqrtPart","vibrate","rx","ry","size","extraPadding","halfSize","extraRadius","base","boundsRadius","stampImage","plotCos","plotSin","perp","along","flowLine","_vals","_standard_brushes","obj","prototype","_brush","_weight","loadPixels","average","pixels","updatePixels","filter","k","Promise","all","then","HatchState","HatchSetState","rand","continuous","gradient","hatchStyle","brush","hBrush","noHatch","scanlineHatch","cosA","sinA","cosB","sinB","verts","rotated","Infinity","edges","eLen","Y","sort","scanY","getHatchLines","polygons","segs","poly","getHatchSegments","getActiveHatchConfig","lines","isConnector","prev","createHatch","drawSegment","save","Object","withHatchStyle","renderHatchSegments","noMass","jitterPolygon","jitterX","jitterY","projectAnchorToBisector","anchor","nx","ny","getShortArcAngles","toAngleUnit","endDeg","splitSegment","seg","gap","gx","gy","drawMassArcs","pivotBias","bias","bounds","getPolygonBounds","sx","sy","getPivotAnchor","parts","part","center","startAngle","endAngle","drawMassPass","createMass","shape","pols","isPolygon","basePolygon","maxJitter","jitters","getMassPolygons","hatchState","brushState","fieldState","precision","strength","outline","hatchDist","baseAngle","_dist","_angle","_options","FillMaskUploadCanvas","isFillCompositeRegistered","maskWidth","maskHeight","needsFillMaskCanvas","fillMaskFramebuffer","needsFillMaskFramebuffer","imageSmoothingEnabled","_getActiveFramebuffer","uploadRect","uploadWidth","uploadHeight","uploadContext","clearRect","drawImage","colorTexture","texSubImage2D","GROW_CAP","_growInsX","_growInsY","_growMods","_growDirs","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","noFill","_polygon","_bbMinX","_bbMinY","_bbMaxX","_bbMaxY","_gaussians","_fillGaussianPools","FillPoly","isFirst","midP","rayCalc","v1","v2","side","rt","mid","ray","sizeX","sizeY","polySides","rc","r1x","r1y","rdx","rdy","count","sa","sb","sdx","sdy","denom","ix","iy","trim","keep","dst","trimStart","trimEnd","edgeStart","edgeEnd","edgeVec","newVertex","insertIdx","splice","ratio","L","indices","sv","sm","sd","outside","crossings","ay","by","flipDirs","grow","tr_v","tr_m","tr_dir","outLen","insertedX","insertedY","newMods","newDirs","bleedDirDeg","gPool","gPoolLen","g2Pool","g2PoolLen","fv","fm","fd","insertedIdx","mod","cv","nv","mi","di","rotDeg","sideX","sideY","dirX","dirY","nextMod","kept","slice","intensity","texture","int","switchingToFill","setTransform","fillColorBase","_getRed","_getGreen","_getBlue","strokeStyle","lineCap","fillMatrix","getTransform","darker","sparse","layer","numLayers","erase","restore","colorBase","matrix","lineWidth","fillStyle","beginPath","first","tx","ty","lineTo","closePath","strokePadding","drawPolygon","numCircles","halfSizeX","halfSizeY","minSize","minSizeFactor","maxSizeFactor","midX","midY","globalCompositeOperation","filterPoints","again","steiner","equals","area","removeNode","earcutLinked","ear","triangles","dim","invSize","pass","z","zOrder","prevZ","nextZ","numMerges","inSize","tail","q","pSize","qSize","sortLinked","indexCurve","stop","isEarHashed","isEar","cureLocalIntersections","splitEarcut","ax","bx","pointInTriangleExceptFirst","minZ","maxZ","intersects","locallyInside","isValidDiagonal","splitPolygon","pointInTriangle","intersectsPolygon","inside","middleInside","q1","q2","o1","sign","o2","o3","o4","onSegment","num","createNode","b2","an","bp","insertNode","last","_opacity","_bleed","_wr","fluid","modifiers","_","shift","shifted","pts","sumX","sumY","pt","cross","_center","createFill","FillSetState","washProgram","washVao","washBuffer","washProjection","washGpuBufferSize","WashAttr","WashUniform","noWash","transformVertexToScreen","ensureWashReady","vertexCount","flat","holeIndices","outerLen","outerNode","signedArea","linkedList","earcut","buildTriangleBuffer","blendEquation","FUNC_ADD","ONE_MINUS_SRC_ALPHA","TRIANGLES","drawWashPolygon","ReadySketch","ActiveInstance","ActiveInstanceStack","_isReady","begin","_pInst","isFiniteSize","Number","isFinite","safeRead","getter","_error","isReadyWebGLSketch","candidate","webglVersion","rememberReadySketch","getSketchRenderer","window","self","p5","sketchRenderer","owner","resolveTarget","getP5RuntimeRenderer","affineMatrix","isRadians","RADIANS","hadDepthTest","isEnabled","DEPTH_TEST","previousTarget","_renderer","_beforeEnd","bindFramebuffer","FRAMEBUFFER","_framebufferToBind","framebuffer","getFramebufferHandle","viewport","_beforeBegin","_origViewport","_applyStencilTestIfClipping","resetP5ShaderTracking","coreRenderer","_curShader","_cachedBlendMode","_isBlending","vertSrc","fragSrc","currentFramebuffer","setUniform","resetShader","flushDraw","imageMode","CENTER","sourceBox","previousReadFramebuffer","getParameter","READ_FRAMEBUFFER_BINDING","previousDrawFramebuffer","DRAW_FRAMEBUFFER_BINDING","READ_FRAMEBUFFER","DRAW_FRAMEBUFFER","blitFramebuffer","COLOR_BUFFER_BIT","NEAREST","blitDefaultFramebufferSource","getP5BrushFactory","factory","createGraphics","resolve","reject","nativeImg","Image","onload","createImage","naturalWidth","naturalHeight","onerror","crossOrigin","_stateStack","hooks","mat4","uModelMatrix","initP5Runtime","initP5RendererRuntime","initP5CompositorRuntime","initP5StrokeRuntime","registerAddon","_p5","lifecycles","presetup","predraw","postsetup","bindInstance","postdraw","_push","_pop","_randomSeed","randomSeed","_noiseSeed","call","saved","brushPop","brushSeed","brushNoiseSeed"],"mappings":"AAIA,MAAMA,EAAiB,CACrBC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,GAGE,IAAIC,EAAc,KAAM,EACpBC,EAAeC,GAAUA,EACzBC,EAAc,KACvB,MAAM,IAAIC,MAAM,yCAEPC,EAAkB,IAAMZ,ECYnC,MAAMa,EAAsBC,KAAKC,KAAK,GAEhCC,EAAK,IAAOH,EAAQ,GACpBI,GAAM,EAAMJ,GAAS,EAQrBK,EAAab,GAAsB,EAAhBS,KAAKK,MAAMd,GAC9Be,EAAsB,IAAIC,aAAa,CAAC,EAAG,GAC7C,EAAI,EACJ,GAAG,GACH,GAAI,EACJ,EAAG,GACH,EAAI,EACJ,EAAG,GACH,EAAI,EACJ,EAAG,EACH,GAAG,EACH,EAAG,EACH,GAAG,IA6BA,SAASC,EAAcC,EAAST,KAAKS,QACxC,MAAMC,EA6WH,SAA+BD,GAClC,MACME,EAAI,IAAIC,WADI,KAElB,IAAK,IAAIC,EAAI,EAAGA,EAAIC,IAAeD,IAC/BF,EAAEE,GAAKA,EAEX,IAAK,IAA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,EAAal0B,EAAGnR,UAEtBmR,EAAGvR,KAAO,WACRqlC,EAAMK,KAAKrmC,MF/BbuM,KACAy4B,GAAYrkC,KAAK,CACfwC,KAAM,IAAKsG,GAAMtG,MACjBiQ,KAAM3J,GAAM2J,KAAO,IAAK3J,GAAM2J,MAAS,KACvCG,OAAQ,IAAK9J,GAAM8J,QACnBD,MAAO,IAAK7J,GAAM6J,OAClBD,KAAM5J,GAAM4J,KAAO,IAAK5J,GAAM4J,MAAS,KACvCvG,MAAO,IAAKrD,GAAMqD,QE0BpB,EAEAoF,EAAGkC,IAAM,WACP6xB,EAAKI,KAAKrmC,MFtBP,WACL,MAAMsmC,EAAQtB,GAAY5wB,MACrBkyB,IACL78B,GAAM8J,OAAS,IAAK+yB,EAAM/yB,QAC1B9J,GAAMqD,MAAQ,IAAKw5B,EAAMx5B,OACzBrD,GAAM6J,MAAQ,IAAKgzB,EAAMhzB,OACzB7J,GAAMtG,KAAO,IAAKmjC,EAAMnjC,MACpBmjC,EAAMlzB,OAAM3J,GAAM2J,KAAO,IAAKkzB,EAAMlzB,OACpCkzB,EAAMjzB,KACR5J,GAAM4J,KAAO,IAAKizB,EAAMjzB,MACf5J,GAAM4J,OACf5J,GAAM4J,KAAO,IACR5J,GAAM4J,KACTzE,UAAU,EACVmc,MAAO,KACP7e,MAAO,KACPgF,QAAS,CAAA,IAGf,CEIIq1B,EACF,EAEAr0B,EAAGi0B,WAAa,SAAUzoC,GACxBwoC,EAAYG,KAAKrmC,KAAMtC,GACvB8oC,EAAU9oC,EACZ,EAEAwU,EAAGnR,UAAY,SAAUrD,GACvB0oC,EAAWC,KAAKrmC,KAAMtC,GACtB+oC,EAAe/oC,EACjB,CACF","x_google_ignoreList":[1,2,23]}
\ No newline at end of file
diff --git a/dist/p5.brush.js b/dist/p5.brush.js
index d9e8140..84574e7 100644
--- a/dist/p5.brush.js
+++ b/dist/p5.brush.js
@@ -1,2 +1,2 @@
-var e,t;e=this,t=function(e){const t={a:1,b:0,c:0,d:1,x:0,y:0};let r=()=>!1,n=e=>e,i=()=>{throw new Error("No runtime color adapter registered.")},o=()=>t;const s=Math.sqrt(3),a=.5*(s-1),c=(3-s)/6,l=e=>0|Math.floor(e),u=new Float64Array([1,1,-1,1,1,-1,-1,-1,1,0,-1,0,1,0,-1,0,0,1,0,-1,0,1,0,-1]);function h(e=Math.random){const t=function(e){const t=new Uint8Array(512);for(let e=0;e<256;e++)t[e]=e;for(let r=0;r<255;r++){const n=r+~~(e()*(256-r)),i=t[r];t[r]=t[n],t[n]=i}for(let e=256;e<512;e++)t[e]=t[e-256];return t}(e),r=new Float64Array(t).map(e=>u[e%12*2]),n=new Float64Array(t).map(e=>u[e%12*2+1]);return function(e,i){let o=0,s=0,u=0;const h=(e+i)*a,f=l(e+h),m=l(i+h),d=(f+m)*c,x=e-(f-d),g=i-(m-d);let p,y;x>g?(p=1,y=0):(p=0,y=1);const v=x-p+c,b=g-y+c,_=x-1+2*c,w=g-1+2*c,R=255&f,A=255&m;let E=.5-x*x-g*g;if(E>=0){const e=R+t[A];E*=E,o=E*E*(r[e]*x+n[e]*g)}let M=.5-v*v-b*b;if(M>=0){const e=R+p+t[A+y];M*=M,s=M*M*(r[e]*v+n[e]*b)}let S=.5-_*_-w*w;if(S>=0){const e=R+1+t[A+1];S*=S,u=S*S*(r[e]*_+n[e]*w)}return 70*(o+s+u)}}function f(e,t){let r=new m(e),n=()=>r.next();return n.double=()=>n()+11102230246251565e-32*(2097152*n()|0),n.int32=()=>4294967296*r.next()|0,n.quick=n,n}class m{constructor(e){null==e&&(e=+new Date);let t=4022871197;function r(e){e=String(e);for(let r=0;r<e.length;r++){t+=e.charCodeAt(r);let n=.02519603282416938*t;t=n>>>0,n-=t,n*=t,t=n>>>0,n-=t,t+=4294967296*n}return 2.3283064365386963e-10*(t>>>0)}this.c=1,this.s0=r(" "),this.s1=r(" "),this.s2=r(" "),this.s0-=r(e),this.s0<0&&(this.s0+=1),this.s1-=r(e),this.s1<0&&(this.s1+=1),this.s2-=r(e),this.s2<0&&(this.s2+=1)}next(){let{c:e,s0:t,s1:r,s2:n}=this,i=2091639*t+2.3283064365386963e-10*e;return this.s0=r,this.s1=n,this.s2=i-(this.c=0|i)}copy(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}}let d=f(Math.random()),x=f(Math.random());const g=[],p=e=>g.push(e),y=e=>{d=f(e),x=f(`${e}:2`);for(const e of g)e()};let v=h(f(Math.random())),b=h(f(Math.random()));const _=e=>{v=h(f(e)),b=h(f(`${e}:2`))},w=(e=0,t=1)=>e+d()*(t-e),R=(e=0,t=1)=>e+x()*(t-e),A=e=>e[~~(d()*e.length)],E=(e,t)=>~~w(e,t),M=(e,t)=>~~R(e,t),S=(e=0,t=1)=>{const r=1-d(),n=d();return Math.sqrt(-2*Math.log(r))*N(360*n)*t+e},T=e=>{let t=0;const r=[];for(const n in e)t+=e[n],r.push({key:n,cumulative:t});const n=d()*t;for(const{key:e,cumulative:t}of r)if(n<t)return isNaN(e)?e:parseInt(e)},P=(e,t,r,n,i,o=!1)=>{let s=n+(e-t)/(r-t)*(i-n);return o?n<i?k(s,n,i):k(s,i,n):s},k=(e,t,r)=>Math.max(Math.min(e,r),t),C=e=>(e%=360)<0?e+360:e,F=1440,I=2*Math.PI/F,L=new Float32Array(F).fill(NaN),D=new Float32Array(F).fill(NaN),N=e=>{const t=~~(4*C(e));let r=L[t];return isNaN(r)&&(r=Math.cos(t*I),L[t]=r),r},B=e=>{const t=~~(4*C(e));let r=D[t];return isNaN(r)&&(r=Math.sin(t*I),D[t]=r),r},Y=(e,t=!1)=>{if(t||r()){let t=180*e/Math.PI%360;return t<0?t+360:t}return e},z=(e,t=!1)=>t||r()?180*e/Math.PI:e,O=(e,t,r,n,i)=>{let o=N(i),s=B(i);return{x:o*(r-e)+s*(n-t)+e,y:o*(n-t)-s*(r-e)+t}},U=(e,t,r,n)=>Math.hypot(r-e,n-t),X=(e,t,r,n)=>Y(Math.atan2(-(n-t),r-e),!0),G=(e,t,r,n,i=!1)=>{let o=e.x,s=e.y,a=t.x,c=t.y,l=r.x,u=r.y,h=n.x,f=n.y;if(o===a&&s===c||l===h&&u===f)return!1;let m=a-o,d=c-s,x=h-l,g=f-u,p=g*m-x*d;if(0===p)return!1;let y=(x*(s-u)-g*(o-l))/p,v=(m*(s-u)-d*(o-l))/p;return!(!i&&(v<0||v>1))&&{x:o+y*m,y:s+y*d}};let Z,V,$,H,W,j={load:()=>{throw new Error("No target runtime adapter registered.")},syncDensity:()=>W,isCanvasReady:()=>{throw new Error("No target runtime adapter registered.")},instance:e=>{$=e},activateInstance:e=>{$=e},deactivateInstance:()=>{},getActiveFramebuffer:()=>null,isFramebufferTarget:()=>!1};function q(e){"Cwidth"in e&&(Z=e.Cwidth),"Cheight"in e&&(V=e.Cheight),"Instance"in e&&($=e.Instance),"Renderer"in e&&(H=e.Renderer),"Density"in e&&(W=e.Density)}const K=()=>j.isCanvasReady(),J=e=>j.instance(e),Q=e=>j.activateInstance(e),ee=()=>j.deactivateInstance(),te=()=>j.getActiveFramebuffer(),re=e=>j.isFramebufferTarget(e),ne=(e,t=0)=>e?{minX:e.minX-t,minY:e.minY-t,maxX:e.maxX+t,maxY:e.maxY+t}:null,ie=(e,t,r=!1)=>{const n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):(()=>{const r=document.createElement("canvas");return r.width=e,r.height=t,r})();return n.drawingContext=n.getContext("2d",r?{willReadFrequently:!0}:void 0),n};let oe={clearTarget:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendShaderProgram:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendSourceFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},createFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},runBlendShaderPass:()=>{throw new Error("No compositor runtime adapter registered.")},blitSourceToFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")}};const se=(...e)=>oe.createFramebuffer(...e);let ae=null,ce=null;const le=e=>{((...e)=>{oe.clearTarget(...e)})(H,e,re)},ue=()=>({width:Math.max(1,Math.round(Z*W)),height:Math.max(1,Math.round(V*W))}),he=e=>{if(!e)return null;const{width:t,height:r}=ue();return((e,t,r)=>{if(!e)return null;const n=Math.max(0,Math.floor(Math.min(e.minX,e.maxX))),i=Math.max(0,Math.floor(Math.min(e.minY,e.maxY))),o=Math.min(t,Math.ceil(Math.max(e.minX,e.maxX))),s=Math.min(r,Math.ceil(Math.max(e.minY,e.maxY)));return o<=n||s<=i?null:{minX:n,minY:i,maxX:o,maxY:s}})(e,t,r)},fe=()=>{const{width:e,height:t}=ue();return((e,t)=>({minX:0,minY:0,maxX:e,maxY:t}))(e,t)},me=(e,t=!0)=>{const r=he(e);if(!r)return null;const{height:n}=ue();return{x:r.minX,y:t?n-r.maxY:r.minY,width:r.maxX-r.minX,height:r.maxY-r.minY}},de=(e,t,r,n=!0)=>{const i=me(t,n);if(i){e.enable(e.SCISSOR_TEST),e.scissor(i.x,i.y,i.width,i.height);try{r()}finally{e.disable(e.SCISSOR_TEST)}}else r()},xe={},ge=()=>{H?.loaded||(K(),pe.load())},pe={isBlending:!1,cachedColor:null,markDirtyRect(e,t){const r=he(t);var n,i;e&&r&&(e.dirtyRect=(i=r,(n=e.dirtyRect)?i?{minX:Math.min(n.minX,i.minX),minY:Math.min(n.minY,i.minY),maxX:Math.max(n.maxX,i.maxX),maxY:Math.max(n.maxY,i.maxY)}:n:i),e.isDrawn=!0)},clearMask(e){if(!e)return;const t=e===this.glMask?ae:ce;t?.clearMask?.(e,le)},getCompositeRect(e,t){const r=t?ae:ce;return r?.getCompositeRect?.(e,te,fe,ne,he)},load(){j.syncDensity();const e=!H.blendSourceFramebuffer||H.blendSourceFramebuffer.width!==Z||H.blendSourceFramebuffer.height!==V||"function"==typeof H.blendSourceFramebuffer.pixelDensity&&H.blendSourceFramebuffer.pixelDensity()!==W;((...e)=>{oe.ensureBlendShaderProgram(...e)})(H,"#version 300 es\n#define GLSLIFY 1\nout vec2 p;void main(){vec3 v=vec3(-1);v[gl_VertexID]=3.;p=v.xy;gl_Position=vec4(v.x,-v.y,0,1);}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nuniform bool u_isBrush;uniform bool u_targetIsFramebuffer;uniform sampler2D u_source;uniform sampler2D u_mask;uniform vec3 u_color;in vec2 p;out vec4 outColor;const int SPECTRAL_SIZE=38;const float SPECTRAL_GAMMA=2.4;const float SPECTRAL_EPSILON=0.0000000000000001;float spectral_uncompand(float x){return(x<0.04045)? x/12.92 : pow((x+0.055)/1.055,SPECTRAL_GAMMA);}float spectral_compand(float x){return(x<0.0031308)? x*12.92 : 1.055*pow(x,1.0/SPECTRAL_GAMMA)-0.055;}vec3 spectral_srgb_to_linear(vec3 srgb){return vec3(spectral_uncompand(srgb[0]),spectral_uncompand(srgb[1]),spectral_uncompand(srgb[2]));}vec3 spectral_linear_to_srgb(vec3 lrgb){return clamp(vec3(spectral_compand(lrgb[0]),spectral_compand(lrgb[1]),spectral_compand(lrgb[2])),0.,1.);}void spectral_linear_to_reflectance(vec3 lrgb,inout float R[SPECTRAL_SIZE]){float w=min(lrgb.r,min(lrgb.g,lrgb.b));lrgb-=w;float c=min(lrgb.g,lrgb.b);float m=min(lrgb.r,lrgb.b);float y=min(lrgb.r,lrgb.g);float r=min(max(0.0,lrgb.r-lrgb.b),max(0.0,lrgb.r-lrgb.g));float g=min(max(0.0,lrgb.g-lrgb.b),max(0.0,lrgb.g-lrgb.r));float b=min(max(0.0,lrgb.b-lrgb.g),max(0.0,lrgb.b-lrgb.r));R[0]=max(SPECTRAL_EPSILON,w*1.0011607271876400+c*0.9705850013229620+m*0.9906735573199880+y*0.0210523371789306+r*0.0315605737777207+g*0.0095560747554212+b*0.9794047525020140);R[1]=max(SPECTRAL_EPSILON,w*1.0011606515972800+c*0.9705924981434250+m*0.9906715249619790+y*0.0210564627517414+r*0.0315520718330149+g*0.0095581580120851+b*0.9794007068431300);R[2]=max(SPECTRAL_EPSILON,w*1.0011603192274700+c*0.9706253487298910+m*0.9906625823534210+y*0.0210746178695038+r*0.0315148215513658+g*0.0095673245444588+b*0.9793829034702610);R[3]=max(SPECTRAL_EPSILON,w*1.0011586727078900+c*0.9707868061190170+m*0.9906181076447950+y*0.0211649058448753+r*0.0313318044982702+g*0.0096129126297349+b*0.9792943649455940);R[4]=max(SPECTRAL_EPSILON,w*1.0011525984455200+c*0.9713686732282480+m*0.9904514808787100+y*0.0215027957272504+r*0.0306729857725527+g*0.0097837090401843+b*0.9789630146085700);R[5]=max(SPECTRAL_EPSILON,w*1.0011325252899800+c*0.9731632306212520+m*0.9898710814002040+y*0.0226738799041561+r*0.0286480476989607+g*0.0103786227058710+b*0.9778144666940430);R[6]=max(SPECTRAL_EPSILON,w*1.0010850066332700+c*0.9767402231587650+m*0.9882866087596400+y*0.0258235649693629+r*0.0246450407045709+g*0.0120026452378567+b*0.9747243211338360);R[7]=max(SPECTRAL_EPSILON,w*1.0009968788945300+c*0.9815876054913770+m*0.9842906927975040+y*0.0334879385639851+r*0.0192960753663651+g*0.0160977721473922+b*0.9671984823439730);R[8]=max(SPECTRAL_EPSILON,w*1.0008652515227400+c*0.9862802656529490+m*0.9739349056253060+y*0.0519069663740307+r*0.0142066612220556+g*0.0267061902231680+b*0.9490796575305750);R[9]=max(SPECTRAL_EPSILON,w*1.0006962900094000+c*0.9899491476891340+m*0.9418178384601450+y*0.1007490148334730+r*0.0102942608878609+g*0.0595555440185881+b*0.9008501289409770);R[10]=max(SPECTRAL_EPSILON,w*1.0005049611488800+c*0.9924927015384200+m*0.8173903261951560+y*0.2391298997068470+r*0.0076191460521811+g*0.1860398265328260+b*0.7631504454622400);R[11]=max(SPECTRAL_EPSILON,w*1.0003080818799200+c*0.9941456804052560+m*0.4324728050657290+y*0.5348043122727480+r*0.0058980410835420+g*0.5705798201161590+b*0.4659221716493190);R[12]=max(SPECTRAL_EPSILON,w*1.0001196660201300+c*0.9951839750332120+m*0.1384539782588700+y*0.7978075786430300+r*0.0048233247781713+g*0.8614677684002920+b*0.2012632804510050);R[13]=max(SPECTRAL_EPSILON,w*0.9999527659684070+c*0.9957567501108180+m*0.0537347216940033+y*0.9114498940673840+r*0.0042298748350633+g*0.9458790897676580+b*0.0877524413419623);R[14]=max(SPECTRAL_EPSILON,w*0.9998218368992970+c*0.9959128182867100+m*0.0292174996673231+y*0.9537979630045070+r*0.0040599171299341+g*0.9704654864743050+b*0.0457176793291679);R[15]=max(SPECTRAL_EPSILON,w*0.9997386095575930+c*0.9956061578345280+m*0.0213136517508590+y*0.9712416154654290+r*0.0043533695594676+g*0.9784136302844500+b*0.0284706050521843);R[16]=max(SPECTRAL_EPSILON,w*0.9997095516396120+c*0.9945976009618540+m*0.0201349530181136+y*0.9793031238075880+r*0.0053434425970201+g*0.9795890314112240+b*0.0205271767569850);R[17]=max(SPECTRAL_EPSILON,w*0.9997319302106270+c*0.9922157154923700+m*0.0241323096280662+y*0.9833801195075750+r*0.0076917201010463+g*0.9755335369086320+b*0.0165302792310211);R[18]=max(SPECTRAL_EPSILON,w*0.9997994363461950+c*0.9862364527832490+m*0.0372236145223627+y*0.9854612465677550+r*0.0135969795736536+g*0.9622887553978130+b*0.0145135107212858);R[19]=max(SPECTRAL_EPSILON,w*0.9999003303166710+c*0.9679433372645410+m*0.0760506552706601+y*0.9864350469766050+r*0.0316975442661115+g*0.9231215745131200+b*0.0136003508637687);R[20]=max(SPECTRAL_EPSILON,w*1.0000204065261100+c*0.8912850042449430+m*0.2053754719423990+y*0.9867382506701410+r*0.1078611963552490+g*0.7934340189431110+b*0.0133604258769571);R[21]=max(SPECTRAL_EPSILON,w*1.0001447879365800+c*0.5362024778620530+m*0.5412689034604390+y*0.9866178824450320+r*0.4638126031687040+g*0.4592701359024290+b*0.0135488943145680);R[22]=max(SPECTRAL_EPSILON,w*1.0002599790341200+c*0.1541081190018780+m*0.8158416850864860+y*0.9862777767586430+r*0.8470554052720110+g*0.1855741036663030+b*0.0139594356366992);R[23]=max(SPECTRAL_EPSILON,w*1.0003557969708900+c*0.0574575093228929+m*0.9128177041239760+y*0.9858605924440560+r*0.9431854093939180+g*0.0881774959955372+b*0.0144434255753570);R[24]=max(SPECTRAL_EPSILON,w*1.0004275378026900+c*0.0315349873107007+m*0.9463398301669620+y*0.9854749276762100+r*0.9688621506965580+g*0.0543630228766700+b*0.0148854440621406);R[25]=max(SPECTRAL_EPSILON,w*1.0004762334488800+c*0.0222633920086335+m*0.9599276963319910+y*0.9851769347655580+r*0.9780306674736030+g*0.0406288447060719+b*0.0152254296999746);R[26]=max(SPECTRAL_EPSILON,w*1.0005072096750800+c*0.0182022841492439+m*0.9662605952303120+y*0.9849715740141810+r*0.9820436438543060+g*0.0342215204316970+b*0.0154592848180209);R[27]=max(SPECTRAL_EPSILON,w*1.0005251915637300+c*0.0162990559732640+m*0.9693259700584240+y*0.9848463034157120+r*0.9839236237187070+g*0.0311185790956966+b*0.0156018026485961);R[28]=max(SPECTRAL_EPSILON,w*1.0005350960689600+c*0.0153656239334613+m*0.9708545367213990+y*0.9847753518111990+r*0.9848454841543820+g*0.0295708898336134+b*0.0156824871281936);R[29]=max(SPECTRAL_EPSILON,w*1.0005402209748200+c*0.0149111568733976+m*0.9716050665281280+y*0.9847380666252650+r*0.9852942758145960+g*0.0288108739348928+b*0.0157248764360615);R[30]=max(SPECTRAL_EPSILON,w*1.0005427281678400+c*0.0146954339898235+m*0.9719627697573920+y*0.9847196483117650+r*0.9855072952198250+g*0.0284486271324597+b*0.0157458108784121);R[31]=max(SPECTRAL_EPSILON,w*1.0005438956908700+c*0.0145964146717719+m*0.9721272722745090+y*0.9847110233919390+r*0.9856050715398370+g*0.0282820301724731+b*0.0157556123350225);R[32]=max(SPECTRAL_EPSILON,w*1.0005444821215100+c*0.0145470156699655+m*0.9722094177458120+y*0.9847066833006760+r*0.9856538499335780+g*0.0281988376490237+b*0.0157605443964911);R[33]=max(SPECTRAL_EPSILON,w*1.0005447695999200+c*0.0145228771899495+m*0.9722495776784240+y*0.9847045543930910+r*0.9856776850338830+g*0.0281581655342037+b*0.0157629637515278);R[34]=max(SPECTRAL_EPSILON,w*1.0005448988776200+c*0.0145120341118965+m*0.9722676219987420+y*0.9847035963093700+r*0.9856883918061220+g*0.0281398910216386+b*0.0157640525629106);R[35]=max(SPECTRAL_EPSILON,w*1.0005449625468900+c*0.0145066940939832+m*0.9722765094621500+y*0.9847031240775520+r*0.9856936646900310+g*0.0281308901665811+b*0.0157645892329510);R[36]=max(SPECTRAL_EPSILON,w*1.0005449892705800+c*0.0145044507314479+m*0.9722802433068740+y*0.9847029256150900+r*0.9856958798482050+g*0.0281271086805816+b*0.0157648147772649);R[37]=max(SPECTRAL_EPSILON,w*1.0005449969930000+c*0.0145038009464639+m*0.9722813248265600+y*0.9847028681227950+r*0.9856965214637620+g*0.0281260133612096+b*0.0157648801149616);}vec3 spectral_xyz_to_srgb(vec3 xyz){mat3 XYZ_RGB;XYZ_RGB[0]=vec3(3.2409699419045200,-1.537383177570090,-0.4986107602930030);XYZ_RGB[1]=vec3(-0.9692436362808790,1.875967501507720,0.0415550574071756);XYZ_RGB[2]=vec3(0.0556300796969936,-0.203976958888976,1.0569715142428700);float r=dot(XYZ_RGB[0],xyz);float g=dot(XYZ_RGB[1],xyz);float b=dot(XYZ_RGB[2],xyz);return spectral_linear_to_srgb(vec3(r,g,b));}vec3 spectral_reflectance_to_xyz(float R[SPECTRAL_SIZE]){vec3 xyz=vec3(0.);xyz+=R[0]*vec3(0.0000646919989576,0.0000018442894440,0.0003050171476380);xyz+=R[1]*vec3(0.0002194098998132,0.0000062053235865,0.0010368066663574);xyz+=R[2]*vec3(0.0011205743509343,0.0000310096046799,0.0053131363323992);xyz+=R[3]*vec3(0.0037666134117111,0.0001047483849269,0.0179543925899536);xyz+=R[4]*vec3(0.0118805536037990,0.0003536405299538,0.0570775815345485);xyz+=R[5]*vec3(0.0232864424191771,0.0009514714056444,0.1136516189362870);xyz+=R[6]*vec3(0.0345594181969747,0.0022822631748318,0.1733587261835500);xyz+=R[7]*vec3(0.0372237901162006,0.0042073290434730,0.1962065755586570);xyz+=R[8]*vec3(0.0324183761091486,0.0066887983719014,0.1860823707062960);xyz+=R[9]*vec3(0.0212332056093810,0.0098883960193565,0.1399504753832070);xyz+=R[10]*vec3(0.0104909907685421,0.0152494514496311,0.0891745294268649);xyz+=R[11]*vec3(0.0032958375797931,0.0214183109449723,0.0478962113517075);xyz+=R[12]*vec3(0.0005070351633801,0.0334229301575068,0.0281456253957952);xyz+=R[13]*vec3(0.0009486742057141,0.0513100134918512,0.0161376622950514);xyz+=R[14]*vec3(0.0062737180998318,0.0704020839399490,0.0077591019215214);xyz+=R[15]*vec3(0.0168646241897775,0.0878387072603517,0.0042961483736618);xyz+=R[16]*vec3(0.0286896490259810,0.0942490536184085,0.0020055092122156);xyz+=R[17]*vec3(0.0426748124691731,0.0979566702718931,0.0008614711098802);xyz+=R[18]*vec3(0.0562547481311377,0.0941521856862608,0.0003690387177652);xyz+=R[19]*vec3(0.0694703972677158,0.0867810237486753,0.0001914287288574);xyz+=R[20]*vec3(0.0830531516998291,0.0788565338632013,0.0001495555858975);xyz+=R[21]*vec3(0.0861260963002257,0.0635267026203555,0.0000923109285104);xyz+=R[22]*vec3(0.0904661376847769,0.0537414167568200,0.0000681349182337);xyz+=R[23]*vec3(0.0850038650591277,0.0426460643574120,0.0000288263655696);xyz+=R[24]*vec3(0.0709066691074488,0.0316173492792708,0.0000157671820553);xyz+=R[25]*vec3(0.0506288916373645,0.0208852059213910,0.0000039406041027);xyz+=R[26]*vec3(0.0354739618852640,0.0138601101360152,0.0000015840125870);xyz+=R[27]*vec3(0.0214682102597065,0.0081026402038399,0.0000000000000000);xyz+=R[28]*vec3(0.0125164567619117,0.0046301022588030,0.0000000000000000);xyz+=R[29]*vec3(0.0068045816390165,0.0024913800051319,0.0000000000000000);xyz+=R[30]*vec3(0.0034645657946526,0.0012593033677378,0.0000000000000000);xyz+=R[31]*vec3(0.0014976097506959,0.0005416465221680,0.0000000000000000);xyz+=R[32]*vec3(0.0007697004809280,0.0002779528920067,0.0000000000000000);xyz+=R[33]*vec3(0.0004073680581315,0.0001471080673854,0.0000000000000000);xyz+=R[34]*vec3(0.0001690104031614,0.0000610327472927,0.0000000000000000);xyz+=R[35]*vec3(0.0000952245150365,0.0000343873229523,0.0000000000000000);xyz+=R[36]*vec3(0.0000490309872958,0.0000177059860053,0.0000000000000000);xyz+=R[37]*vec3(0.0000199961492222,0.0000072209749130,0.0000000000000000);return xyz;}float KS(float R){return pow(1.0-R,2.0)/(2.0*R);}float KM(float KS){return 1.0+KS-sqrt(pow(KS,2.0)+2.0*KS);}vec3 spectral_mix(vec3 color1,float tintingStrength1,float factor1,vec3 color2,float tintingStrength2,float factor2){vec3 lrgb1=spectral_srgb_to_linear(color1);vec3 lrgb2=spectral_srgb_to_linear(color2);float R1[SPECTRAL_SIZE];float R2[SPECTRAL_SIZE];spectral_linear_to_reflectance(lrgb1,R1);spectral_linear_to_reflectance(lrgb2,R2);float luminance1=spectral_reflectance_to_xyz(R1)[1];float luminance2=spectral_reflectance_to_xyz(R2)[1];float R[SPECTRAL_SIZE];for(int i=0;i<SPECTRAL_SIZE;i++){float concentration1=pow(factor1,2.)*pow(tintingStrength1,2.)*luminance1;float concentration2=pow(factor2,2.)*pow(tintingStrength2,2.)*luminance2;float totalConcentration=concentration1+concentration2;float ksMix=0.;ksMix+=KS(R1[i])*concentration1;ksMix+=KS(R2[i])*concentration2;R[i]=KM(ksMix/totalConcentration);}return spectral_xyz_to_srgb(spectral_reflectance_to_xyz(R));}vec3 spectral_mix(vec3 color1,vec3 color2,float factor){return spectral_mix(color1,1.,1.-factor,color2,1.,factor);}vec3 spectral_mix(vec3 color1,float factor1,vec3 color2,float factor2){return spectral_mix(color1,1.,factor1,color2,1.,factor2);}const float GAMMA=2.4,EPSILON=0.0001;const float DARKEN_THRESHOLD=0.7;const float EDGE_MIN=0.05,EDGE_MAX=0.35;void main(void){vec2 uv=0.5*p+0.5;vec2 sourceUV=vec2(uv.x,1.0-uv.y);vec2 maskUV=u_targetIsFramebuffer ? vec2(uv.x,1.0-uv.y): uv;vec4 source=texture(u_source,sourceUV);vec4 maskColor=texture(u_mask,maskUV);if(maskColor.a==0.0){outColor=source;return;}vec4 pigment=vec4(u_color.xyz,1.0);if(maskColor.a>DARKEN_THRESHOLD){float blacken=0.5*(min(maskColor.a,1.0)-DARKEN_THRESHOLD);pigment=pigment*(1.0-blacken)-vec4(0.5)*blacken;pigment.rgb=max(pigment.rgb,vec3(0.0));}float mixIntensity=min(maskColor.a,1.0);if(!u_isBrush){vec2 texelSize=1.0/vec2(textureSize(u_mask,0));float scaledAlpha=maskColor.a*15.0;float blurEdge=0.0;for(int i=-2;i<=2;i+=2){for(int j=-2;j<=2;j+=2){vec2 neighborUV=maskUV+vec2(float(i),float(j))*texelSize;float neighborAlpha=texture(u_mask,neighborUV).a*15.0;blurEdge+=smoothstep(EDGE_MIN,EDGE_MAX,length(vec2(dFdx(neighborAlpha),dFdy(neighborAlpha))));}}blurEdge/=9.0;mixIntensity=clamp(maskColor.a+blurEdge*0.1,0.0,1.0);}vec3 bgColor=mix(vec3(1.0),source.rgb,source.a);outColor=vec4(spectral_mix(bgColor,pigment.rgb,mixIntensity),1.);}"),this.glMask=ae?.ensureResources?.(H,Z,V,W);const t=ce?.ensureResources?.(H,Z,V,W,le)??{mask:null,ctx:null};e&&(H.blendSourceFramebuffer=((...e)=>oe.ensureBlendSourceFramebuffer(...e))(H,H.blendSourceFramebuffer,Z,V,W)),this.mask=t.mask,this.ctx=t.ctx},blend(e=!1,t=!1){ge();const r=!0===this.isBrush,n=r?this.glMask:this.mask,i=r?this.mask:this.glMask,o=e?._array,s=!!o&&(this.cachedColor?.[0]!==o[0]||this.cachedColor?.[1]!==o[1]||this.cachedColor?.[2]!==o[2]||this.cachedColor?.[3]!==o[3]);!this.isBlending&&o&&(this.isBlending=!0,this.cachedColor=o,this.clearMask(this.glMask)),(t||s)&&(this.justChanged&&(this.applyShader(i,!r),this.justChanged=!1),this.isBlending&&this.applyShader(n,r),o&&(this.cachedColor=o),t&&(this.isBlending=!1,this.cachedColor=null))},applyShader(e,t){if(!e?.isDrawn)return;const r=this.getCompositeRect(e,t);if(!r)return void this.clearMask(e);H.drawingContext;const n=H.shaderProgram,i=te(),o=((...e)=>oe.blitSourceToFramebuffer(...e))({renderer:H,sourceTarget:i??H,sourceFramebuffer:H.blendSourceFramebuffer,dirtyRect:r,isFramebufferTarget:re,Cwidth:Z,Cheight:V,getTargetPixelSize:ue,toScissorBox:me,withScissor:de}),s=!!i,a=(t?ae:ce).getShaderMask(H,e,r,he,fe,le);((...e)=>{oe.runBlendShaderPass(...e)})({renderer:H,shader:n,source:o,mask:a,color:this.cachedColor,isBrushMask:t,Cwidth:Z,Cheight:V,dirtyRect:r,targetIsFramebuffer:s,withScissor:de}),this.clearMask(e)}},ye=()=>{ge(),pe.blend(!1,!0),pe.clearMask(pe.glMask),pe.clearMask(pe.mask),pe.justChanged=!1,pe.isBlending=!1,pe.isBrush=null,pe.cachedColor=null};let ve=!1;function be(){ve||(ge(),we=.01*Z,Re=-.5*Z,Ae=-.5*V,Ee=Math.round(2*Z/we),Me=Math.round(2*V/we),Fe("hand",(e,t)=>{const r=R(.2,.8),n=M(5,10);return Le(t,(t,i)=>.5*n*B(r*i*t+M(15,25))*.2*N(e)+b(t,i)*n*.7)}),Fe("curved",(e,t)=>{let r=M(-10,10);return M(0,100)%2==0&&(r*=-1),Le(t,(t,n)=>3*P(b(.02*t+.03*e,.02*n+.03*e),0,1,-r,r))}),Fe("zigzag",(e,t)=>{let r=M(-30,-15)+Math.abs(44*B(e));M(0,100)%2==0&&(r*=-1);let n=r,i=0;for(let e=0;e<Ee;e++){for(let r=0;r<Me;r++)t[e][r]=i,i+=n,n*=-1;i+=n,n*=-1}return t}),Fe("waves",(e,t)=>{const r=M(10,15)+5*B(e),n=M(3,6)+3*N(e),i=M(20,35);return Le(t,(e,t)=>B(r*e)*i*N(t*n)+M(-3,3))}),Fe("seabed",(e,t)=>{const r=R(.4,.8),n=M(18,26);return Le(t,(t,i)=>1.1*n*B(r*i*t+M(15,20))*N(e))}),Fe("spiral",(e,t)=>{const r=M(5,10),n=2*M(0,2)-1,i=M(65,80),o=Array.from({length:r},()=>({x:R(.1,.9)*Ee,y:R(.1,.9)*Me}));return Le(t,(e,t)=>{let r=0,s=0;for(const a of o){const o=e-a.x,c=t-a.y,l=1/(o*o+c*c+1),u=Math.atan2(c,o)*(180/Math.PI),h=n*(u+i)*Math.PI/180;r+=l*Math.cos(h),s+=l*Math.sin(h)}return Math.atan2(s,r)*(180/Math.PI)})}),Fe("columns",(e,t)=>{const r=M(3,8),n=M(25,45);return Le(t,(e,t)=>B(e*r)*n)}),ve=!0)}class _e{constructor(e,t){be();const r=o();this.mx=r.x,this.my=r.y,this.update(e,t),this.plotted=0}update(e,t){this.x=e,this.y=t,this.colIdx=Math.round((e+this.mx-Re)/we),this.rowIdx=Math.round((t+this.my-Ae)/we)}reset(){this.plotted=0}isIn(){return xe.field.isActive?_e.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const e=Z,t=V,r=this.x+this.mx,n=this.y+this.my;return r>=-.3*e&&r<=1.3*e&&n>=-.3*t&&n<=1.3*t}angle(e=!1){return xe.field.isActive&&(e||this.isIn())?Se.get(xe.field.current).field[this.colIdx][this.rowIdx]*xe.field.wiggle:0}moveTo(e,t,r=1){this.movePos(z(e),t,r)}_moveToDegrees(e,t,r=1){this.movePos(e,t,r)}plotTo(e,t,r,n=1){this.movePos(e,t,r,n)}movePos(e,t,r,n=!1){const i=n||1;if(!this.isIn())return void(this.plotted+=r/i);const o=t/r,s=xe.field.isActive,a=!!n;for(let t=0;t<o;t++){const t=(s?this.angle(!0):0)-(a?e.angle(this.plotted):e);this.update(this.x+r*N(t),this.y+r*B(t)),this.plotted+=r/i}}static getRowIndex(e,t=1){const r=e+o().y-Ae;return Math.round(r/we/t)}static getColIndex(e,t=1){const r=e+o().x-Re;return Math.round(r/we/t)}static isIn(e,t){return e>=0&&t>=0&&e<Ee&&t<Me}}xe.field={isActive:!1,current:null,wiggle:1};let we,Re,Ae,Ee,Me,Se=new Map;const Te=new Set(["degrees","radians"]);function Pe(e={}){const t=("string"==typeof e?{angleMode:e}:e||{}).angleMode??"degrees";if(!Te.has(t))throw new Error(`Invalid field angle mode "${t}". Use "degrees" or "radians".`);return t}function ke(e,t){return function(e,t){if("radians"!==t)return e;for(let t=0;t<e.length;t++)for(let r=0;r<e[t].length;r++)e[t][r]=z(e[t][r],!0);return e}(e.gen(t,new Array(Ee).fill(null).map(()=>new Float32Array(Me))),e.angleMode)}function Ce(e){if(xe.field.wiggle||(xe.field.wiggle=1),be(),!Se.has(e))throw new Error(`Field "${e}" does not exist. Available fields: ${Array.from(Se.keys()).join(", ")}.`);xe.field.isActive=!0,xe.field.current=e;const t=Se.get(e);t.field||(t.field=ke(t,0))}function Fe(e,t,r={}){Se.set(e,{gen:t,field:null,angleMode:Pe(r)})}function Ie(e=1){Ce("hand"),xe.field.wiggle=e}function Le(e,t){for(let r=0;r<Ee;r++)for(let n=0;n<Me;n++)e[r][n]=t(r,n);return e}class De{constructor(e,t=!1){this.a=e,this.vertices=t?e:e.map(([e,t])=>({x:e,y:t})),this.sides=this.vertices.map((e,t,r)=>[e,r[(t+1)%r.length]]),this._intersectionCache={}}intersect(e){const t=`${e.point1.x},${e.point1.y}-${e.point2.x},${e.point2.y}`;if(this._intersectionCache[t])return this._intersectionCache[t];const r=[];for(const[t,n]of this.sides){const i=G(e.point1,e.point2,t,n);i&&r.push(i)}return this._intersectionCache[t]=r,r}show(){xe.wash&&this.wash(),xe.fill&&this.fill(),xe.mass&&this.mass(),xe.hatch&&this.hatch(),xe.stroke&&this.draw()}}class Ne{constructor(e){this.segments=[],this.angles=[],this.pres=[],this.type=e,this.dir=0,this.calcIndex(0),this.pol=!1}addSegment(e=0,t=0,r=1,n=!1){this.angles.length>0&&this.angles.pop(),e=n?(e%360+360)%360:Y(e),this.angles.push(e,e),this.pres.push(r),this.segments.push(t),this.length=this.segments.reduce((e,t)=>e+t,0)}endPlot(e=0,t=1,r=!1){e=r?(e%360+360)%360:Y(e),this.angles[this.angles.length-1]=e,this.pres.push(t)}rotate(e){this.dir=Y(e)}pressure(e){return e>this.length?this.pres[this.pres.length-1]:this.curving(this.pres,e)}angle(e){return e>this.length?this.angles[this.angles.length-1]:(this.calcIndex(e),"curve"===this.type?this.curving(this.angles,e)+this.dir:this.angles[this.index]+this.dir)}curving(e,t){let r=e[this.index],n=e[this.index+1]??r;return Math.abs(n-r)>180&&(n>r?n=-(360-n):r=-(360-r)),P(t-this.suma,0,this.segments[this.index],r,n,!0)}calcIndex(e){this.index=-1,this.suma=0;let t=0;for(;t<=e;)this.suma=t,t+=this.segments[this.index+1],this.index++;return this.index}genPol(e,t,r=1,n){be();const i=n<0?4:1,o=[],s=Math.round(this.length/i),a=new _e(e+Z/2,t+V/2);let c=0,l=0;for(let e=0;e<s;e++){a.plotTo(this,i,i);const e=this.calcIndex(a.plotted);c+=i,(c>=(n<=0?8:Math.max(this.segments[e]*n*R(.7,1.3),20))||e>=l)&&a.x&&(o.push([a.x-Z/2,a.y-V/2]),c=0,e>=l&&l++)}return new De(o)}show(e,t,r=1){xe.wash&&this.wash(e,t,r),xe.fill&&this.fill(e,t,r),xe.mass&&this.mass(e,t,r),xe.hatch&&this.hatch(e,t,r),xe.stroke&&this.draw(e,t,r)}}function Be(e,t,r,n,i){const o=z(n),s=((z(i)-o)%360+360)%360;if(0===s)return;const a=new Ne("curve"),c=Math.max(1,Math.ceil(s/90)),l=s/c,u=Math.PI*r*l/180;for(let e=0;e<c;e++)a.addSegment(o+e*l+90,u,1,!0);a.endPlot(o+s+90,1,!0);const h=e+r*N(o),f=t-r*B(o);a.draw(h,f,1)}let Ye,ze,Oe,Ue;class Xe{constructor(){this.isClosed=!1,this.curvature=ze,this.vert=[]}vertex(e,t,r){this.vert.push([e,t,r])}show(){$e(this.vert,this.curvature,this.isClosed).show()}}function Ge(e=0){ze=k(e,0,1),Ye=new Xe}function Ze(e,t,r=1){if(!Ye)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");Ye.vertex(e,t,r)}function Ve(e=!1){if(!Ye)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(Ye.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");e&&(Ye.vertex(...Ye.vert[0]),Ye.isClosed=!0),Ye.show(),Ye=!1}function $e(e,t=.5,r=!1){const n=new Ne(0===t?"segments":"curve"),i=2*Math.PI;if(r&&0!==t&&e.push(e[1]),e&&e.length>0){let o,s,a,c=0;for(let l=0;l<e.length-1;l++)if(t>0&&l<e.length-2){const u=e[l],h=e[l+1],f=e[l+2],m=U(u[0],u[1],h[0],h[1]),d=U(h[0],h[1],f[0],f[1]),x=X(u[0],u[1],h[0],h[1]),g=X(h[0],h[1],f[0],f[1]),p=t*Math.min(m,d,.5*Math.min(m,d)),y=Math.max(m,d),v=m-p,b=d-p;if(Math.floor(x)===Math.floor(g)){const t=r&&0===l?0:m-c,i=r?0===l?0:d-a:d;n.addSegment(x,t,u[2],!0),l===e.length-3&&n.addSegment(g,i,h[2],!0),c=0,0===l&&(o=m,a=p,s=e[1],c=0)}else{const t={x:h[0]-p*N(-x),y:h[1]-p*B(-x)},f={x:t.x+y*N(90-x),y:t.y+y*B(90-x)},m={x:h[0]+p*N(-g),y:h[1]+p*B(-g)},d={x:m.x+y*N(90-g),y:m.y+y*B(90-g)},_=G(t,f,m,d,!0),w=U(t.x,t.y,_.x,_.y),R=U(t.x,t.y,m.x,m.y)/2,A=i*w*(2*Math.asin(R/w)*(180/Math.PI))/360,E=r&&0===l?0:v-c,M=l===e.length-3?r?o-p:b:0;n.addSegment(x,E,u[2],!0),n.addSegment(x,isNaN(A)?0:A,u[2],!0),n.addSegment(g,M,h[2],!0),c=p,0===l&&(o=v,a=p,s=[t.x,t.y])}l===e.length-3&&n.endPlot(g,h[2],!0)}else if(0===t){const t=e[l],r=e[l+1],i=U(t[0],t[1],r[0],r[1]),o=X(t[0],t[1],r[0],r[1]);n.addSegment(o,i,r[2],!0),l===e.length-2&&n.endPlot(o,1,!0)}n.origin=r&&0!==t?s:e[0]}return n}let He={createTipSurface:()=>{throw new Error("No stroke runtime adapter registered.")},loadImageTip:()=>{throw new Error("No stroke runtime adapter registered.")}},We=!1;const je=(e,t,r)=>{const n=e.createProgram();for(let[i,o]of[[e.VERTEX_SHADER,t],[e.FRAGMENT_SHADER,r]]){const t=e.createShader(i);e.shaderSource(t,o),e.compileShader(t),e.attachShader(n,t)}return e.linkProgram(n),n};let qe={beginDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},endDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},resetDirectShaderTracking:()=>{}};const Ke=(e,t)=>qe.resetDirectShaderTracking(e,t);let Je,Qe,et,tt,rt,nt=!1,it=0,ot=0,st=null;const at={},ct={};let lt=1,ut=0,ht=0,ft=1,mt=0,dt=0,xt=0,gt=0,pt=1,yt=1,vt=new Float32Array(8192),bt=0,_t=2048,wt=32768,Rt=null,At=null,Et=null,Mt=null,St=null;const Tt={},Pt={};let kt=0,Ct=new Float32Array(1280),Ft=0,It=256,Lt=null;const Dt=new Map,Nt=new Float32Array([-1,-1,1,-1,-1,1,1,1]);function Bt(){return Qe}function Yt(){return((e,t,r)=>qe.beginDirectMaskDraw(e,t,r))(H,Je,pe.glMask)}function zt(e){((e,t,r)=>{qe.endDirectMaskDraw(e,t,r)})(H,Je,e)}function Ot(e,t,r,n,i){return e?(t<e.minX&&(e.minX=t),r<e.minY&&(e.minY=r),n>e.maxX&&(e.maxX=n),i>e.maxY&&(e.maxY=i),e):{minX:t,minY:r,maxX:n,maxY:i}}function Ut(e,t,r,n){if(bt>=_t){_t*=2;const e=new Float32Array(4*_t);e.set(vt),vt=e}const i=e-xt,o=t-gt,s=4*bt,a=lt*i+ht*o+mt+xt,c=ut*i+ft*o+dt+gt,l=yt*r*pt/2;vt[s]=a,vt[s+1]=c,vt[s+2]=l,vt[s+3]=n/255;const u=a*yt,h=c*yt;Rt=Ot(Rt,u-l-1,h-l-1,u+l+1,h+l+1),bt++}function Xt(e,t){if(0===Ft)return;pe.glMask.isDrawn=!0;const r=Yt();let n=Dt.get(t);n||(n=Je.createTexture(),Je.bindTexture(Je.TEXTURE_2D,n),Je.texImage2D(Je.TEXTURE_2D,0,Je.RGBA,Je.RGBA,Je.UNSIGNED_BYTE,e.canvas),Je.texParameteri(Je.TEXTURE_2D,Je.TEXTURE_MIN_FILTER,Je.LINEAR),Je.texParameteri(Je.TEXTURE_2D,Je.TEXTURE_MAG_FILTER,Je.LINEAR),Je.texParameteri(Je.TEXTURE_2D,Je.TEXTURE_WRAP_S,Je.CLAMP_TO_EDGE),Je.texParameteri(Je.TEXTURE_2D,Je.TEXTURE_WRAP_T,Je.CLAMP_TO_EDGE),Dt.set(t,n)),Je.useProgram(At),Je.enable(Je.BLEND),Je.blendFunc(Je.ONE_MINUS_DST_ALPHA,Je.ONE),Je.activeTexture(Je.TEXTURE0),Je.bindTexture(Je.TEXTURE_2D,n),Je.uniform1i(Pt.u_tex,0);const i=xe.stroke.color._array;Je.uniform4f(Pt.u_color,...i),Je.uniformMatrix4fv(Pt.u_proj,!1,Bt()),Je.bindVertexArray(Et),Je.bindBuffer(Je.ARRAY_BUFFER,St);const o=5*Ft*4,s=Ct.subarray(0,5*Ft);o>kt?(Je.bufferData(Je.ARRAY_BUFFER,Ct,Je.DYNAMIC_DRAW),kt=Ct.byteLength):Je.bufferSubData(Je.ARRAY_BUFFER,0,s),Je.drawArraysInstanced(Je.TRIANGLE_STRIP,0,4,Ft),Je.flush(),Je.bindVertexArray(null),Je.bindTexture(Je.TEXTURE_2D,null),zt(r),Lt&&(pe.markDirtyRect(pe.glMask,Lt),Lt=null),Ft=0,Ke(H,Je)}We||(ae={ensureResources:function(e,t,r,n){return function(e,t,r,n){return!e.glMask||e.glMask.width!==t||e.glMask.height!==r||"function"==typeof e.glMask.pixelDensity&&e.glMask.pixelDensity()!==n}(e,t,r,n)&&(e.glMask?.remove&&e.glMask.remove(),e.glMask=se(e,{width:t,height:r,density:n,antialias:!1,depth:!1,stencil:!1})),e.glMask.dirtyRect??=null,e.glMask.isDrawn??=!1,e.glMask},clearMask:function(e,t){e&&(t(e),e.isDrawn=!1,e.dirtyRect=null)},getCompositeRect:function(e,t,r,n,i){return e?e.dirtyRect?t()?r():i(n(e.dirtyRect,2)):r():null},getShaderMask:function(e,t){return t}},We=!0),xe.stroke={color:null,weight:1,type:"HB",isActive:!1,opacity:1};let Gt=new Map;const Zt={offset:.08,scale:.08,warp:.06,tilt:.06};function Vt(){return{...xe.stroke}}function $t(e){xe.stroke={...e}}function Ht(e,t){if(t.type=["marker","custom","image","spray"].includes(t.type)?t.type:"default",void 0===t.markerTip&&(t.markerTip=!0),void 0===t.noise&&(t.noise=.3),t.noise=Math.max(0,Math.min(1,t.noise)),void 0!==t.vibration&&void 0===t.scatter&&(t.scatter=t.vibration),void 0!==t.definition&&void 0===t.sharpness&&(t.sharpness=t.definition),void 0!==t.quality&&void 0===t.grain&&(t.grain=t.quality),t.pressure=function(e){if(!e)return e;if("function"==typeof e)return{type:"custom",min_max:[0,1],curve:e,variation:{...Zt}};if("object"==typeof e&&!Array.isArray(e)){if("custom"===e.type||"custom"===e.mode){const{mode:t,...r}=e;return{...r,type:"custom",variation:{...Zt,...r.variation??{}}}}return"gaussian"===e.type||"gaussian"===e.mode||Array.isArray(e.curve)&&Array.isArray(e.min_max)?{...e,type:"gaussian",curve:e.curve,min_max:e.min_max}:e}if(Array.isArray(e)){const[t,r,n]=2===e.length?[e[0],(e[0]+e[1])/2,e[1]]:e,i=Math.min(t,r,n),o=Math.max(t,r,n),s=o-i||1,[a,c,l]=[(t-i)/s,(r-i)/s,(n-i)/s];return{type:"custom",min_max:[i,o],variation:{...Zt},curve:e=>e<.5?a+(c-a)*e*2:c+(l-c)*(e-.5)*2}}}(t.pressure),"custom"===t.type){if("function"!=typeof t.tip)throw new Error(`Brush "${e}" is type "custom" but is missing a tip function.`);const r=`custom::${e}`;!function(e){const t=Dt.get(e);t&&Je&&Je.deleteTexture(t),Dt.delete(e)}(r);const n=He.createTipSurface(500,500);return n.pixelDensity(1),n.background(255),n.noSmooth(),n.push(),n.translate(250,250),n.scale(5),n.noStroke(),t.tip(n),n.pop(),gr.imageToWhite(n),gr.tips.set(r,n),t.tipKey=r,void Gt.set(e,{param:t,colors:[],buffers:[]})}if("image"===t.type){if(!t.image||!t.image.src)throw new Error(`Brush "${e}" is type "image" but is missing params.image.src. Example: image: { src: "./tip.jpg" }`);return gr.add(t.image.src),Gt.set(e,{param:t,colors:[],buffers:[]}),gr.load()}Gt.set(e,{param:t,colors:[],buffers:[]})}function Wt(e){return Gt.get(e)?.param??null}function jt(e){if(!Gt.has(e))throw new Error(`Brush "${e}" not found. Available brushes: ${[...Gt.keys()].join(", ")}.`);xe.stroke.type=e}function qt(e,t,r){K(),xe.stroke.color=i(...arguments),xe.stroke.isActive=!0}function Kt(e){xe.stroke.weight=e}function Jt(e,t,r=1){jt(e),qt(t),Kt(r)}let Qt,er,tr,rr;const nr={};function ir(e,t,r,n=!1){!function(){const e=o();lt=e.a,ut=e.b,ht=e.c,ft=e.d,mt=e.x,dt=e.y,xt=Z/2,gt=V/2,pt=Math.sqrt(lt*lt+ut*ut),yt=W}(),Qt=new _e(e+Z/2,t+V/2),er=r,tr=n,tr&&tr.calcIndex(0)}const or=[];function sr(e,t){t||(rr=e),function(){nr.seed=999999*w();const{param:e}=Gt.get(xe.stroke.type)??{};if(!e)return;nr.p=e;const{pressure:t}=e;if(nr.a="custom"!==t.type?w(-1,1):0,nr.b="custom"!==t.type?w(1,1.5):0,"custom"!==t.type)nr.cp=w(3,3.5),nr.ct=0,nr.cs=1,nr.ck=0;else{const e=t.variation??Zt;nr.cp=w(-e.offset,e.offset),nr.ct=w(-e.warp,e.warp),nr.cs=w(1-e.scale,1+e.scale),nr.ck=w(-e.tilt,e.tilt)}[nr.min,nr.max]=t.min_max,nr.noiseoffset=.05*nr.p.noise,tr||(nr.cos=N(rr),nr.sin=B(rr)),function(){ge(),function(){const e=H?.glMask;e&&(st=e,st.dirtyRect??=null,st.isDrawn??=!1,pe.glMask=st)}();const e=H.drawingContext,t=!nt||Je!==e;(t||it!==Z||ot!==V)&&(Qe=new Float32Array([2/Z,0,0,0,0,2/V,0,0,0,0,1,0,-1,-1,0,1]),it=Z,ot=V),t&&(Je=e,rt=je(Je,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_position;in float a_radius;in float a_alpha;uniform mat4 u_matrix;out float v_alpha;void main(){gl_Position=u_matrix*vec4(a_position,0.0,1.0);v_alpha=a_alpha;gl_PointSize=a_radius*2.0;}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin float v_alpha;out vec4 outColor;uniform vec4 u_color;void main(){vec2 v=gl_PointCoord-vec2(0.5);float f=length(v);float a=fwidth(f);f=1.0-smoothstep(0.5-a,0.5+a,f);if(f<0.01){discard;}outColor=vec4(u_color.xyz,v_alpha*f);}"),Je.useProgram(rt),Je.enable(Je.BLEND),Je.blendFunc(Je.ONE_MINUS_DST_ALPHA,Je.ONE),["a_position","a_radius","a_alpha"].forEach(e=>at[e]=Je.getAttribLocation(rt,e)),["u_matrix","u_color"].forEach(e=>ct[e]=Je.getUniformLocation(rt,e)),et=Je.createVertexArray(),Je.bindVertexArray(et),tt=Je.createBuffer(),Je.bindBuffer(Je.ARRAY_BUFFER,tt),Je.bufferData(Je.ARRAY_BUFFER,vt.byteLength,Je.DYNAMIC_DRAW),wt=vt.byteLength,Je.enableVertexAttribArray(at.a_position),Je.vertexAttribPointer(at.a_position,2,Je.FLOAT,!1,16,0),Je.enableVertexAttribArray(at.a_radius),Je.vertexAttribPointer(at.a_radius,1,Je.FLOAT,!1,16,8),Je.enableVertexAttribArray(at.a_alpha),Je.vertexAttribPointer(at.a_alpha,1,Je.FLOAT,!1,16,12),Je.bindVertexArray(null),Dt.clear(),At=je(Je,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_corner;in vec2 a_pos;in float a_size;in float a_angle;in float a_alpha;uniform mat4 u_proj;out vec2 v_uv;out float v_alpha;void main(){float c=cos(a_angle);float s=sin(a_angle);vec2 rotated=vec2(c*a_corner.x-s*a_corner.y,s*a_corner.x+c*a_corner.y);gl_Position=u_proj*vec4(a_pos+rotated*a_size,0.0,1.0);v_uv=a_corner*0.5+0.5;v_alpha=a_alpha;}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin vec2 v_uv;in float v_alpha;uniform sampler2D u_tex;uniform vec4 u_color;out vec4 outColor;void main(){float inkAlpha=texture(u_tex,v_uv).a;if(inkAlpha<0.01)discard;outColor=vec4(u_color.rgb,inkAlpha*v_alpha);}"),["a_corner","a_pos","a_size","a_angle","a_alpha"].forEach(e=>Tt[e]=Je.getAttribLocation(At,e)),["u_proj","u_color","u_tex"].forEach(e=>Pt[e]=Je.getUniformLocation(At,e)),Et=Je.createVertexArray(),Je.bindVertexArray(Et),Mt=Je.createBuffer(),Je.bindBuffer(Je.ARRAY_BUFFER,Mt),Je.bufferData(Je.ARRAY_BUFFER,Nt,Je.STATIC_DRAW),Je.enableVertexAttribArray(Tt.a_corner),Je.vertexAttribPointer(Tt.a_corner,2,Je.FLOAT,!1,0,0),St=Je.createBuffer(),Je.bindBuffer(Je.ARRAY_BUFFER,St),Je.bufferData(Je.ARRAY_BUFFER,Ct.byteLength,Je.DYNAMIC_DRAW),kt=Ct.byteLength,Je.enableVertexAttribArray(Tt.a_pos),Je.vertexAttribPointer(Tt.a_pos,2,Je.FLOAT,!1,20,0),Je.vertexAttribDivisor(Tt.a_pos,1),Je.enableVertexAttribArray(Tt.a_size),Je.vertexAttribPointer(Tt.a_size,1,Je.FLOAT,!1,20,8),Je.vertexAttribDivisor(Tt.a_size,1),Je.enableVertexAttribArray(Tt.a_angle),Je.vertexAttribPointer(Tt.a_angle,1,Je.FLOAT,!1,20,12),Je.vertexAttribDivisor(Tt.a_angle,1),Je.enableVertexAttribArray(Tt.a_alpha),Je.vertexAttribPointer(Tt.a_alpha,1,Je.FLOAT,!1,20,16),Je.vertexAttribDivisor(Tt.a_alpha,1),Je.bindVertexArray(null),nt=!0)}();const r=!0!==pe.isBrush;pe.isBrush=!0,r&&(pe.justChanged=!0),pe.blend(xe.stroke.color),nr.alpha=["default","spray"].includes(nr.p.type)?nr.p.opacity:nr.p.opacity/Math.min(xe.stroke.weight,1.3),fr()}();const r=function(){const{param:e}=Gt.get(xe.stroke.type)??{};return e?e.spacing:1}(),n=Math.round(er*(t?e:1)/r);nr.pressureCount=10,nr.cachedPressure=void 0,nr.lineNoiseCount=5,nr.cachedLineNoise=void 0;for(let i=0;i<n;i++)or.length<2*n&&or.push(S()),ar(),t?Qt.plotTo(tr,r,r,e,i<10):Qt._moveToDegrees(e,r,r);!function(){fr(),function(){if(0===bt)return;pe.glMask.isDrawn=!0;const e=Yt(),t=xe.stroke.color._array;Je.useProgram(rt),Je.enable(Je.BLEND),Je.blendFunc(Je.ONE_MINUS_DST_ALPHA,Je.ONE),Je.bindVertexArray(et),Je.bindBuffer(Je.ARRAY_BUFFER,tt);const r=16*bt,n=vt.subarray(0,4*bt);r>wt?(Je.bufferData(Je.ARRAY_BUFFER,vt,Je.DYNAMIC_DRAW),wt=vt.byteLength):Je.bufferSubData(Je.ARRAY_BUFFER,0,n),Je.uniform4f(ct.u_color,...t),Je.uniformMatrix4fv(ct.u_matrix,!1,Bt()),Je.drawArrays(Je.POINTS,0,bt),Je.flush(),Je.bindVertexArray(null),zt(e),Rt&&(pe.markDirtyRect(pe.glMask,Rt),Rt=null),bt=0,Ke(H,Je)}();const e=nr.p?.type;"image"===e?Xt(gr.tips.get(nr.p.image.src),nr.p.image.src):"custom"===e&&Xt(gr.tips.get(nr.p.tipKey),nr.p.tipKey)}()}function ar(){const e=cr(),t=((nr.lineNoiseCount>=10||void 0===nr.cachedLineNoise)&&(nr.cachedLineNoise=P(v(nr.seed+.01*Qt.plotted,0),-1,1,1-nr.noiseoffset,1+nr.noiseoffset),nr.lineNoiseCount=0),nr.lineNoiseCount++,nr.cachedLineNoise);if(!(t>w(1,1.02)&&w(0,1)<.7))switch(nr.p.type){case"spray":!function(e){const t=xe.stroke.weight*nr.p.scatter*e+xe.stroke.weight*A(or)*nr.p.scatter/3,r=nr.p.weight*w(.9,1.1),n=Math.ceil(nr.p.grain/e);for(let e=0;e<n;e++){const e=w(.9,1.1),n=e*t*w(-1,1),i=w(-1,1),o=Math.sqrt((e*t)**2-n**2);Ut(Qt.x+n,Qt.y+i*o,r,nr.alpha)}}(e*t);break;case"marker":ur(e*t);break;case"custom":case"image":hr(e*t);break;default:!function(e,t=1){const r=(t=P(t,0,1,.9,1.05))*xe.stroke.weight*nr.p.scatter*(nr.p.sharpness+(1-nr.p.sharpness)*A(or)/e);if(w(0,nr.p.grain*e)>.4){let t,n;if(tr){const e=tr.angle(Qt.plotted),i=N(e),o=B(e),s=r*w(-1,1),a=.3*r*w(-1,1);t=s*o+a*i,n=s*i-a*o}else{const e=r*w(-1,1),i=.3*r*w(-1,1);t=e*nr.sin+i*nr.cos,n=e*nr.cos-i*nr.sin}const i=e*e*nr.p.weight*w(.85,1.15)*xe.stroke.weight,o=Math.max(.9,e)*nr.alpha*w(.75,1.1);Ut(Qt.x+t,Qt.y+n,i,o)}}(e*t)}}function cr(){return(nr.pressureCount>=10||void 0===nr.cachedPressure)&&(nr.cachedPressure=tr?lr()*tr.pressure(Qt.plotted):lr(),nr.pressureCount=0),nr.pressureCount++,nr.cachedPressure}function lr(){return"custom"===nr.p.pressure.type?P(nr.p.pressure.curve(Math.max(0,Math.min(1,.5+(Qt.plotted/er-.5+nr.ct)*nr.cs)))+nr.cp+nr.ck*(Qt.plotted/er-.5),0,1,nr.min,nr.max,!0):function(e=.5+nr.p.pressure.curve[0]*nr.a,t=1-nr.p.pressure.curve[1]*nr.b,r=nr.cp,n=nr.min,i=nr.max){const o=e*er,s=(Qt.plotted<o?1.2*t:.8*t)*(er/2);return P(1/(1+Math.pow(Math.abs((Qt.plotted-o)/s),2*r)),0,1,n,i)}()}function ur(e,t=!0,r=nr.alpha){const n=t?xe.stroke.weight*nr.p.scatter:0,i=t?n*w(-1,1):0,o=t?n*w(-1,1):0;Ut(Qt.x+i,Qt.y+o,xe.stroke.weight*nr.p.weight*e,r*Math.max(.8,e)*w(.9,1.1))}function hr(e,t=nr.alpha){const r=xe.stroke.weight*nr.p.scatter,n=r*w(-1,1),i=r*w(-1,1),o=nr.p.weight*xe.stroke.weight*e,s=function(){const e=Math.max(1,nr.max??1),t=xe.stroke.weight*nr.p.scatter,r=xe.stroke.weight*nr.p.weight*e;return Math.max(8,1.5*t+.75*r)}();let a=0;"random"===nr.p.rotate?a=E(0,360)*(Math.PI/180):"natural"===nr.p.rotate&&(a=((tr?-tr.angle(Qt.plotted):-rr)+Qt.angle())*(Math.PI/180)),function(e,t,r,n,i,o=0){if(Ft>=It){It*=2;const e=new Float32Array(5*It);e.set(Ct),Ct=e}const s=e-xt,a=t-gt,c=lt*s+ht*a+mt+xt,l=ut*s+ft*a+dt+gt,u=yt*r*pt/2,h=yt*o*pt,f=5*Ft;Ct[f]=c,Ct[f+1]=l,Ct[f+2]=u,Ct[f+3]=n,Ct[f+4]=i/255;const m=c*yt,d=l*yt,x=1.42*u+h;Lt=Ot(Lt,m-x-1,d-x-1,m+x+1,d+x+1),Ft++}(Qt.x+n,Qt.y+i,o,a,t*Math.max(.8,e)*w(.9,1.1),s)}function fr(){if(!1===nr.p.markerTip)return;let e=cr(),t=nr.alpha;if("marker"===nr.p.type)for(let r=1;r<10;r++)ur(e*r/10,!0,8*t);else if("custom"===nr.p.type||"image"===nr.p.type)for(let r=1;r<5;r++)hr(e*r/10,2*t)}function mr(e,t,r,n){if(!xe.stroke.isActive||!xe.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");be();let i=U(e,t,r,n);0!=i&&(ir(e,t,i),sr(X(e,t,r,n),!1))}p(()=>{or.length=0});const dr=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate","markerTip","noise"],xr=[["pen",[.3,.15,.9,2,150,.1,{curve:[.15,.2],min_max:[1.2,1]}]],["rotring",[.15,.05,.7,15,210,.1,{curve:[.35,.2],min_max:[1.3,1]}]],["2B",[.3,.75,.45,15,180,.1,{curve:[.1,.3],min_max:[1.1,.9]}]],["HB",[.3,.6,.3,10,170,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["2H",[.2,.6,.3,4,120,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["cpencil",[.3,.55,.8,7,75,.1,{curve:[.15,.2],min_max:[.95,1.2]}]],["pastel",[2.05/3,13.4/3,.91,28,35,.085/3,{mode:"gaussian",curve:[.4,.05],min_max:[1.09,.93]},"default",void 0,"natural",!0,1]],["crayon",[.3,5.45/3,.75,250,159,.23/3,[1.1,.9],"default",void 0,"natural",!0,1]],["charcoal",[.35,1.5,.68,500,120,.03,{curve:[.15,.4],min_max:[1.1,.95]}]],["spray",[.2,6,15,40,90,.5,{curve:[.2,.35],min_max:[.7,1]},"spray"]],["marker",[2,.2,null,null,1,.03,{curve:[.35,.25],min_max:[1.2,.85]},"marker"]]];for(let e of xr){let t={};for(let r=0;r<e[1].length;r++)t[dr[r]]=e[1][r];Ht(e[0],t)}De.prototype.draw=function(e=!1,t,r){let n=Vt();if(e&&Jt(e,t,r),n.isActive)for(let e of this.sides)mr(e[0].x,e[0].y,e[1].x,e[1].y);$t(n)},Ne.prototype.draw=function(e,t,r){Vt().isActive&&(this.origin&&(e=this.origin[0],t=this.origin[1],r=1),function(e,t,r,n){be(),ir(t,r,e.length,e),sr(n,!0)}(this,e,t,r))};const gr={tips:new Map,add(e){this.tips.has(e)||this.tips.set(e,!1)},imageToWhite(e){e.loadPixels();for(let t=0;t<4*e.width*e.height;t+=4){let r=(e.pixels[t]+e.pixels[t+1]+e.pixels[t+2])/3;e.pixels[t]=e.pixels[t+1]=e.pixels[t+2]=255,e.pixels[t+3]=255-r}e.updatePixels()},async load(){const e=[...this.tips.keys()].filter(e=>!this.tips.get(e));await Promise.all(e.map(e=>((e,t)=>He.loadImageTip(e,t))(e,gr.imageToWhite).then(t=>{this.tips.set(e,t)})))}};function pr(){return{...xe.hatch}}function yr(e){xe.hatch={...e}}function vr(e=5,t=45,r={rand:!1,continuous:!1,gradient:!1}){let n=xe.hatch;n.isActive=!0,n.dist=e,n.angle=z(t),n.options=r}function br(e,t,r,n){const i=t*Math.PI/180,o=Math.cos(i),s=Math.sin(i),a=Math.cos(-i),c=Math.sin(-i),l=e.a,u=l.length,h=new Array(u);let f=Infinity,m=-Infinity;for(let e=0;e<u;e++){const t=l[e][0],r=l[e][1],n=[t*o-r*s,t*s+r*o];h[e]=n,n[1]<f&&(f=n[1]),n[1]>m&&(m=n[1])}const d=[];for(let e=0;e<u;e++){const t=h[e],r=h[(e+1)%u];t[1]!==r[1]&&d.push(t,r)}const x=d.length,g=[],p=[];let y=f+.5*r,v=r;for(;y<m;){p.length=0;for(let e=0;e<x;e+=2){const t=d[e][1],r=d[e+1][1];(t<=y&&y<r||r<=y&&y<t)&&p.push(d[e][0]+(y-t)/(r-t)*(d[e+1][0]-d[e][0]))}p.sort((e,t)=>e-t);for(let e=0;e<p.length-1;e+=2)g.push({scanY:y,x1:p[e]*a-y*c,y1:p[e]*c+y*a,x2:p[e+1]*a-y*c,y2:p[e+1]*c+y*a});y+=v,v*=n}return g}function _r(e){const{dist:t,options:r,segs:n}=function(e){const t=xe.hatch.dist,r=(xe.hatch.angle%180+180)%180,n=xe.hatch.options,i=function(e,t,r,n){Array.isArray(e)||(e=[e]);const i=[];for(const o of e)for(const e of br(o,r,t,n))i.push(e);return i.sort((e,t)=>e.scanY===t.scanY?e.x1-t.x1:e.scanY-t.scanY),i}(e,t,r,n.gradient?P(n.gradient,0,1,1,1.1,!0):1);return{dist:t,options:n,segs:i}}(e),i=r.rand||0,o=[];for(let e=0;e<n.length;e++){const s=n[e];let a=s.x1,c=s.y1,l=s.x2,u=s.y2;i&&(a+=2*i*t*w(-1,1),c+=2*i*t*w(-1,1),l+=2*i*t*w(-1,1),u+=2*i*t*w(-1,1));const h=r.continuous&&e%2==1?{x1:l,y1:u,x2:a,y2:c,scanY:s.scanY,isConnector:!1}:{x1:a,y1:c,x2:l,y2:u,scanY:s.scanY,isConnector:!1};if(o.push(h),e>0&&r.continuous){const e=o[o.length-2];o.push({x1:e.x2,y1:e.y2,x2:h.x1,y2:h.y1,scanY:s.scanY,isConnector:!0})}}return o}function wr(e){!function(e,t){const r=_r(e);!function(){const e=Vt();xe.hatch.hBrush&&Jt(...Object.values(xe.hatch.hBrush)),(()=>{for(let e=0;e<r.length;e++){const n=r[e];t(n.x1,n.y1,n.x2,n.y2,e,r)}})(),$t(e)}()}(e,(e,t,r,n)=>{mr(e,t,r,n)})}function Rr(e,t,r){return new De(e.vertices.map(e=>[e.x+t,e.y+r]))}function Ar(e,t,r,n,i){const o=(t+n)/2,s=(r+i)/2,a=n-t,c=i-r,l=Math.hypot(a,c);if(!l)return null;const u=-c/l,h=a/l,f=(e.x-o)*u+(e.y-s)*h;return{x:o+u*f,y:s+h*f}}function Er(e,t,r,n,i,o,s){let a=X(e,t,r,n),c=X(e,t,i,o);return((c-a)%360+360)%360>180&&([a,c]=[c,a]),[s(a),s(c)]}function Mr(e){const t=R(.35,.65),r=e.x1+(e.x2-e.x1)*t,n=e.y1+(e.y2-e.y1)*t,i=e.x2-e.x1,o=e.y2-e.y1,s=Math.hypot(i,o)||1,a=R(.04,.1)*s,c=i/s*a*.5,l=o/s*a*.5;return[{x1:e.x1,y1:e.y1,x2:r-c,y2:n-l},{x1:r+c,y1:n+l,x2:e.x2,y2:e.y2}]}function Sr(e,t,r){const n=function(e,t){const r=function(e){const t=e?.a??[];let r=Infinity,n=Infinity,i=-Infinity,o=-Infinity;for(const[e,s]of t)e<r&&(r=e),s<n&&(n=s),e>i&&(i=e),s>o&&(o=s);return{minX:r,minY:n,maxX:i,maxY:o,cx:(r+i)/2,cy:(n+o)/2,size:Math.hypot(i-r,o-n)}}(e),n=r.size*R(.6,1.4),[i,o]=t;return{x:r.cx+i*n,y:r.cy+o*n}}(e,t);for(const t of _r(e)){const e=!t.isConnector&&R()<.35?Mr(t):[t];for(const t of e){const e=Ar(n,t.x1,t.y1,t.x2,t.y2);if(!e)continue;const i=U(e.x,e.y,t.x1,t.y1);if(!i)continue;const[o,s]=Er(e.x,e.y,t.x1,t.y1,t.x2,t.y2,r);Be(e.x,e.y,i,o,s)}}}function Tr(e,t,r,n,i,o){vr(t,r,n),Sr(e,i,o)}function Pr(e,t,i,o){const s=function(e,t,r,n){const i=!1===t,o=Wt(xe.mass.brush)?.scatter??0,s=i?e:e.genPol(t,r,n,.15),a=Math.min(2*o,5),c=[[R(-a,a),R(-a,a)],[R(-a,a),R(-a,a)]];return[s,Rr(s,c[0][0],c[0][1]),Rr(s,c[1][0],c[1][1])]}(e,t,i,o),a=pr(),c=Vt(),l={...xe.field},u=xe.mass.options?.precision??.5,h=xe.mass.options?.strength??1,f=xe.mass.options?.gradient??.1,m=xe.mass.options?.outline??!1,d=Wt(xe.mass.brush)?.scatter??0,x=1.6*R(.65*d,.85*d)-.4*f,g=R(-90,90),p=((g+90)%180+180)%180-90>=0?R()<.5?[1,1]:[-1,-1]:R()<.5?[-1,1]:[1,-1],y=r()?e=>e*Math.PI/180:e=>e;Jt(xe.mass.brush,xe.mass.color,1),Ie(2-u),m&&s[0].draw(),Tr(s[0],.9*x,n(g),{gradient:f,rand:2-2*u,continuous:!0},p,y),h>.33&&Tr(s[1],x,n(g+20*R(-1,1)),{gradient:f,rand:.6-.6*u,continuous:!0},p,y),h>.66&&Tr(s[2],.8*x,n(g+15*R(-1,1)),{gradient:f,rand:.6-.6*u,continuous:!0},p,y),$t(c),yr(a),xe.field={...l}}function kr(e,t,r){const n=2*Math.PI,i=pe.ctx,o=r/2;i.moveTo(e+o,t),i.arc(e,t,o,0,n)}xe.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},De.prototype.hatch=function(e=!1,t,r){let n=pr();e&&vr(e,t,r),xe.hatch.isActive&&wr(this),yr(n)},Ne.prototype.hatch=function(e,t,r){pr().isActive&&(this.origin&&(e=this.origin[0],t=this.origin[1],r=1),this.pol=this.genPol(e,t,r,.3),this.pol.hatch())},xe.mass={isActive:!1,brush:null,color:null,options:{}},De.prototype.mass=function(){xe.mass?.isActive&&Pr(this,!1)},Ne.prototype.mass=function(e,t,r){xe.mass?.isActive&&(this.origin&&(e=this.origin[0],t=this.origin[1],r=1),Pr(this,e,t,r))};let Cr=null,Fr=!1;Fr||(ce={ensureResources:function(e,t,r,n,i){const o=Math.max(1,Math.round(t*n)),s=Math.max(1,Math.round(r*n));return function(e,t,r){return!e.mask||e.mask.width!==t||e.mask.height!==r}(e,o,s)&&(e.mask=ie(o,s)),function(e,t,r,n){return!e.fillMaskFramebuffer||e.fillMaskFramebuffer.width!==t||e.fillMaskFramebuffer.height!==r||"function"==typeof e.fillMaskFramebuffer.pixelDensity&&e.fillMaskFramebuffer.pixelDensity()!==n}(e,t,r,n)&&(e.fillMaskFramebuffer?.remove&&e.fillMaskFramebuffer.remove(),e.fillMaskFramebuffer=se(e,{width:t,height:r,density:n,antialias:!1,depth:!1,stencil:!1}),i(e.fillMaskFramebuffer)),e.mask.dirtyRect??=null,e.mask.isDrawn??=!1,e.mask.drawingContext.imageSmoothingEnabled=!1,{mask:e.mask,ctx:e.mask.drawingContext}},clearMask:function(e,t){e&&(t(e),e.isDrawn=!1,e.dirtyRect=null)},getCompositeRect:function(e,t,r,n,i){return e?e.dirtyRect?i(n(e.dirtyRect,4)):r():null},getShaderMask:function(e,t,r,n,i,o){const s=e.fillMaskFramebuffer,a=e.drawingContext,c=n(r)??i(),l=c.maxX-c.minX,u=c.maxY-c.minY;Cr&&Cr.width===l&&Cr.height===u||(Cr=ie(l,u));const h=Cr.drawingContext;return h.clearRect(0,0,l,u),h.drawImage(t,c.minX,c.minY,l,u,0,0,l,u),o(s),a.bindTexture(a.TEXTURE_2D,s.colorTexture),a.texSubImage2D(a.TEXTURE_2D,0,c.minX,c.minY,a.RGBA,a.UNSIGNED_BYTE,Cr),s}},Fr=!0);let Ir,Lr=[],Dr=[],Nr=[],Br=[];xe.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const Yr=()=>({...xe.fill});function zr(e,t,r,n){xe.fill.opacity=(arguments.length<4?t:n)||150,xe.fill.color=arguments.length<3?i(e):i(e,t,r),xe.fill.isActive=!0}function Or(e,t="out"){xe.fill.bleed_strength=k(e,0,1),xe.fill.direction=t}function Ur(e=.4,t=.4){xe.fill.texture_strength=k(e,0,1),xe.fill.border_strength=k(t,0,1)}let Xr;const Gr=[[],[]];function Zr(){for(let e=0;e<512;e++)Gr[0][e]=S(.5,.2),Gr[1][e]=S(0,.02)}function Vr(e,t,r){return(t.x-e.x)*(r.y-e.y)-(t.y-e.y)*(r.x-e.x)>.01}p(Zr);class $r{constructor(e,t,r,n=[],i=!1,o,s){if(this.v=e,this.m=t,this.dir=n,this.midP=r,i){let t=0,n=0;const i=[];for(let o=0;o<e.length;o++){const s=Math.abs(r.x-e[o].x),a=Math.abs(r.y-e[o].y);t=Math.max(t,s),n=Math.max(n,a);const c=e[o],l=e[(o+1)%e.length],u={x:l.x-c.x,y:l.y-c.y},h=O(0,0,u.x,u.y,90),f={x:c.x+u.x/2,y:c.y+u.y/2};i.push({v1:c,v2:l,ray:{point1:f,point2:{x:f.x+h.x,y:f.y+h.y}}})}this.sizeX=t,this.sizeY=n,this.dir=Array(e.length),i.forEach((e,t)=>{let r=0;for(const t of Xr.intersect(e.ray))Vr(e.v1,e.v2,t)&&r++;this.dir[t]=r%2==0});const o=w(-.6,.6)*t,s=w(-.6,.6)*n;this.midP={x:r.x+o,y:r.y+s}}else this.sizeX=o,this.sizeY=s}trim(e=1){if(e>=1||e<0||this.v.length<=8)return{v:this.v,m:this.m,dir:this.dir};const t=~~((1-e)*this.v.length),r=~~(this.v.length/2-t/2),n=this.v.length-t,i=new Array(n),o=new Array(n),s=new Array(n);let a=0;for(let e=0;e<r;e++,a++)i[a]=this.v[e],o[a]=this.m[e],s[a]=this.dir[e];for(let e=r+t;e<this.v.length;e++,a++)i[a]=this.v[e],o[a]=this.m[e],s[a]=this.dir[e];const c=r,l=r+t,u=this.v[(c-1+this.v.length)%this.v.length],h=this.v[l%this.v.length],f=h.x-u.x,m=h.y-u.y;for(let e=0;e<2;e++){const t=w(.25,.75),n={x:u.x+f*t,y:u.y+m*t},a=r+e;i.splice(a,0,n),o.splice(a,0,w(.4,.7)),s.splice(a,0,this.dir[c%this.dir.length])}return{v:i,m:o,dir:s}}scatter(e=.3){const t=this.v.length,r=Math.max(3,~~(t*e)),n=[],i=t/r;for(let e=0;e<r;e++)n.push(~~(e*i+w(0,.8*i)));const o=[],s=[],a=[],c=this.midP,l=Xr.sides;for(const e of n){const r=e%t;let n=this.v[r],i=0;for(const[e,t]of l){const r=e.y,o=t.y;if(r>n.y==o>n.y)continue;const s=(n.y-r)/(o-r);n.x<e.x+s*(t.x-e.x)&&i++}i%2==0&&(n={x:c.x+(n.x-c.x)*w(.3,.6),y:c.y+(n.y-c.y)*w(.3,.6)}),o.push(n),s.push(this.m[r]),a.push(!this.dir[r])}return new $r(o,s,this.midP,a,!1,this.sizeX,this.sizeY)}flipDirs(){return new $r(this.v,this.m,this.midP,this.dir.map(e=>!e),!1,this.sizeX,this.sizeY)}grow(e=1){const{v:t,m:r,dir:n}=this.trim(e),i=t.length,o=2*i;Lr.length<i&&(Lr=new Array(i),Dr=new Array(i)),Nr.length<o&&(Nr=new Array(o),Br=new Array(o));const s=Lr,a=Dr,c=Nr,l=Br,u="out"===xe.fill.direction?-90:90;0===Gr[0].length&&Zr();const h=Gr[0],f=h.length,m=Gr[1],d=m.length;let x,g,p,y=0,v=0,b=999===e?w(.6,.8):xe.fill.bleed_strength;for(let o=0;o<i;o++){const x=t[o],g=t[o+1<i?o+1:0],p=r[o],_=n[o];if(e<997&&(b=p),b<.05){c[y]=p,l[y]=_,y++,s[v]=(x.x+g.x)/2,a[v]=(x.y+g.y)/2,c[y]=p,l[y]=_,y++,v++;continue}const R=(_?u:-u)+5*w(-1,1),A=N(R),E=B(R),M=g.x-x.x,S=g.y-x.y,T=A*M+E*S,P=A*S-E*M,k=h[~~(w(0,1)*f)]*w(.65,1.35)*b,C=p+m[~~(w(0,1)*d)];c[y]=p,l[y]=_,y++,s[v]=x.x+.5*M+T*k,a[v]=x.y+.5*S+P*k,c[y]=C,l[y]=_,y++,v++}if(Ir&&y>Ir){const e=Math.ceil(y/Ir),r=Math.ceil(y/e);x=new Array(r),g=new Array(r),p=new Array(r);let n=0;for(let r=0;r<y;r+=e,n++)x[n]=r%2==0?t[r>>1]:{x:s[r>>1],y:a[r>>1]},g[n]=c[r],p[n]=l[r]}else{x=new Array(y);for(let e=0;e<y;e++)x[e]=e%2==0?t[e>>1]:{x:s[e>>1],y:a[e>>1]};g=c.slice(0,y),p=l.slice(0,y)}return new $r(x,g,this.midP,p,!1,this.sizeX,this.sizeY)}fill(e,t,r){const n=3*r,i=2*t*(1+r/2),s=!1!==pe.isBrush;pe.isBrush=!1,s&&(pe.justChanged=!0),pe.blend(e);const a=o();pe.ctx.save(),pe.ctx.setTransform(W*a.a,W*a.b,W*a.c,W*a.d,W*(a.x+Z/2),W*(a.y+V/2)),pe.ctx.strokeStyle=`rgb(${e._getRed()} ${e._getGreen()} ${e._getBlue()} / ${.005*xe.fill.border_strength})`,pe.ctx.lineCap="round",Ir=2024*Math.max(.1,2*xe.fill.bleed_strength);const c=Math.max(this.sizeX,this.sizeY),l=w(.15,.7);let u=this.grow();const h=this.scatter(.1).grow().scatter(.75).flipDirs();let f;for(let r=0;r<20;r++){r%4==0&&(u=u.grow()),r%2==0&&(f=[u.grow(1-.0125*r),u.grow(.7-.0125*r),u.grow(.4-.0125*r)]);for(const t of f)t.grow(999).grow(997).layer(r,c,i,e);h.grow(999).flipDirs().grow(997).layer(r,c,i*n,e),r%2==0&&u.grow(l).grow(999).layer(r,c,2*i,e),r%8!=0&&19!==r||(0!==n&&u.erase(3*n,t),pe.blend(e,!0))}pe.ctx.restore()}layer(e,t,r,n){pe.ctx.lineWidth=P(e,0,24,t/25,t/30,!0),pe.ctx.fillStyle=`rgb(${n._getRed()} ${n._getGreen()} ${n._getBlue()} / ${r}%)`,function(e){const t=pe.ctx,r=t.getTransform(),n=r.a,i=r.b,o=r.c,s=r.d,a=r.e,c=r.f;let l=Infinity,u=Infinity,h=-Infinity,f=-Infinity;t.beginPath();const m=e[0];let d=n*m.x+o*m.y+a,x=i*m.x+s*m.y+c;l=h=d,u=f=x,t.moveTo(m.x,m.y);for(let r=1;r<e.length;r++){const m=e[r];d=n*m.x+o*m.y+a,x=i*m.x+s*m.y+c,l=Math.min(l,d),u=Math.min(u,x),h=Math.max(h,d),f=Math.max(f,x),t.lineTo(m.x,m.y)}t.closePath();const g=function(e,t){const r=e.lineWidth||0;return r<=0?1:1+r*Math.max(Math.hypot(t.a,t.c),Math.hypot(t.b,t.d))/2}(t,r);pe.markDirtyRect(pe.mask,{minX:l-g,minY:u-g,maxX:h+g,maxY:f+g})}(this.v),pe.ctx.fill(),pe.ctx.stroke()}erase(e,t){pe.ctx.save();const r=~~(w(80,110)*P(e,0,1,2,3.5)),n=this.sizeX/1.3,i=this.sizeY/1.3,o=1.3*Math.min(this.sizeX,this.sizeY),s=.03*o,a=.45*o,{x:c,y:l}=this.midP;pe.ctx.globalCompositeOperation="destination-out";const u=(5-P(t,80,100,.3,.7,!0))*e/255;pe.ctx.fillStyle=`rgb(255 0 0 / ${u})`,pe.ctx.lineWidth=0;for(let e=0;e<r;e++){const t=c+S(0,n),r=l+S(0,i),o=w(s,a);pe.ctx.beginPath(),kr(t,r,o),e%5!=0&&pe.ctx.fill()}pe.ctx.globalCompositeOperation="source-over",pe.ctx.restore()}}function Hr(e,t){if(!e)return e;t||(t=e);let r,n=e;do{if(r=!1,n.steiner||!nn(n,n.next)&&0!==rn(n.prev,n,n.next))n=n.next;else{if(hn(n),n=t=n.prev,n===n.next)break;r=!0}}while(r||n!==t);return t}function Wr(e,t,r,n,i,o,s){if(!e)return;!s&&o&&function(e,t,r,n){let i=e;do{0===i.z&&(i.z=Qr(i.x,i.y,t,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==e);i.prevZ.nextZ=null,i.prevZ=null,function(e){let t,r=1;do{let n,i=e;e=null;let o=null;for(t=0;i;){t++;let s=i,a=0;for(let e=0;e<r&&(a++,s=s.nextZ,s);e++);let c=r;for(;a>0||c>0&&s;)0!==a&&(0===c||!s||i.z<=s.z)?(n=i,i=i.nextZ,a--):(n=s,s=s.nextZ,c--),o?o.nextZ=n:e=n,n.prevZ=o,o=n;i=s}o.nextZ=null,r*=2}while(t>1)}(i)}(e,n,i,o);let a=e;for(;e.prev!==e.next;){const c=e.prev,l=e.next;if(o?qr(e,n,i,o):jr(e))t.push(c.i,e.i,l.i),hn(e),e=l.next,a=l.next;else if((e=l)===a){s?1===s?Wr(e=Kr(Hr(e),t),t,r,n,i,o,2):2===s&&Jr(e,t,r,n,i,o):Wr(Hr(e),t,r,n,i,o,1);break}}}function jr(e){const t=e.prev,r=e,n=e.next;if(rn(t,r,n)>=0)return!1;const i=t.x,o=r.x,s=n.x,a=t.y,c=r.y,l=n.y,u=Math.min(i,o,s),h=Math.min(a,c,l),f=Math.max(i,o,s),m=Math.max(a,c,l);let d=n.next;for(;d!==t;){if(d.x>=u&&d.x<=f&&d.y>=h&&d.y<=m&&en(i,a,o,c,s,l,d.x,d.y)&&rn(d.prev,d,d.next)>=0)return!1;d=d.next}return!0}function qr(e,t,r,n){const i=e.prev,o=e,s=e.next;if(rn(i,o,s)>=0)return!1;const a=i.x,c=o.x,l=s.x,u=i.y,h=o.y,f=s.y,m=Math.min(a,c,l),d=Math.min(u,h,f),x=Math.max(a,c,l),g=Math.max(u,h,f),p=Qr(m,d,t,r,n),y=Qr(x,g,t,r,n);let v=e.prevZ,b=e.nextZ;for(;v&&v.z>=p&&b&&b.z<=y;){if(v.x>=m&&v.x<=x&&v.y>=d&&v.y<=g&&v!==i&&v!==s&&en(a,u,c,h,l,f,v.x,v.y)&&rn(v.prev,v,v.next)>=0)return!1;if(v=v.prevZ,b.x>=m&&b.x<=x&&b.y>=d&&b.y<=g&&b!==i&&b!==s&&en(a,u,c,h,l,f,b.x,b.y)&&rn(b.prev,b,b.next)>=0)return!1;b=b.nextZ}for(;v&&v.z>=p;){if(v.x>=m&&v.x<=x&&v.y>=d&&v.y<=g&&v!==i&&v!==s&&en(a,u,c,h,l,f,v.x,v.y)&&rn(v.prev,v,v.next)>=0)return!1;v=v.prevZ}for(;b&&b.z<=y;){if(b.x>=m&&b.x<=x&&b.y>=d&&b.y<=g&&b!==i&&b!==s&&en(a,u,c,h,l,f,b.x,b.y)&&rn(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function Kr(e,t){let r=e;do{const n=r.prev,i=r.next.next;!nn(n,i)&&on(n,r,r.next,i)&&cn(n,i)&&cn(i,n)&&(t.push(n.i,r.i,i.i),hn(r),hn(r.next),r=e=i),r=r.next}while(r!==e);return Hr(r)}function Jr(e,t,r,n,i,o){let s=e;do{let e=s.next.next;for(;e!==s.prev;){if(s.i!==e.i&&tn(s,e)){let a=ln(s,e);return s=Hr(s,s.next),a=Hr(a,a.next),Wr(s,t,r,n,i,o,0),void Wr(a,t,r,n,i,o,0)}e=e.next}s=s.next}while(s!==e)}function Qr(e,t,r,n,i){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-r)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-n)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function en(e,t,r,n,i,o,s,a){return!(e===s&&t===a)&&function(e,t,r,n,i,o,s,a){return(i-s)*(t-a)>=(e-s)*(o-a)&&(e-s)*(n-a)>=(r-s)*(t-a)&&(r-s)*(o-a)>=(i-s)*(n-a)}(e,t,r,n,i,o,s,a)}function tn(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){let r=e;do{if(r.i!==e.i&&r.next.i!==e.i&&r.i!==t.i&&r.next.i!==t.i&&on(r,r.next,e,t))return!0;r=r.next}while(r!==e);return!1}(e,t)&&(cn(e,t)&&cn(t,e)&&function(e,t){let r=e,n=!1;const i=(e.x+t.x)/2,o=(e.y+t.y)/2;do{r.y>o!=r.next.y>o&&r.next.y!==r.y&&i<(r.next.x-r.x)*(o-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==e);return n}(e,t)&&(rn(e.prev,e,t.prev)||rn(e,t.prev,t))||nn(e,t)&&rn(e.prev,e,e.next)>0&&rn(t.prev,t,t.next)>0)}function rn(e,t,r){return(t.y-e.y)*(r.x-t.x)-(t.x-e.x)*(r.y-t.y)}function nn(e,t){return e.x===t.x&&e.y===t.y}function on(e,t,r,n){const i=an(rn(e,t,r)),o=an(rn(e,t,n)),s=an(rn(r,n,e)),a=an(rn(r,n,t));return i!==o&&s!==a||!(0!==i||!sn(e,r,t))||!(0!==o||!sn(e,n,t))||!(0!==s||!sn(r,e,n))||!(0!==a||!sn(r,t,n))}function sn(e,t,r){return t.x<=Math.max(e.x,r.x)&&t.x>=Math.min(e.x,r.x)&&t.y<=Math.max(e.y,r.y)&&t.y>=Math.min(e.y,r.y)}function an(e){return e>0?1:e<0?-1:0}function cn(e,t){return rn(e.prev,e,e.next)<0?rn(e,t,e.next)>=0&&rn(e,e.prev,t)>=0:rn(e,t,e.prev)<0||rn(e,e.next,t)<0}function ln(e,t){const r=fn(e.i,e.x,e.y),n=fn(t.i,t.x,t.y),i=e.next,o=t.prev;return e.next=t,t.prev=e,r.next=i,i.prev=r,n.next=r,r.prev=n,o.next=n,n.prev=o,n}function un(e,t,r,n){const i=fn(e,t,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function hn(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function fn(e,t,r){return{i:e,x:t,y:r,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}De.prototype.fill=function(e=!1,t,r,n,i,o){let s=Yr();e&&(zr(e,t),Or(r,o),Ur(n,i)),s.isActive&&(be(),function(e){if(!xe.fill.isActive||!xe.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");Xr=e;const t=[...e.vertices],r=~~(.25*t.length*T({1:5,2:10,3:60})),n=xe.fill.bleed_strength,i=t.map((e,t)=>(t>r?1:.3)*w(.85,1.4)*n),o=E(0,t.length),s=[...t.slice(o),...t.slice(0,o)],a=function(e){if(0===e.length)return{x:0,y:0};if(e.length<8){const t=e.reduce((e,t)=>({x:e.x+t.x,y:e.y+t.y}),{x:0,y:0});return{x:t.x/e.length,y:t.y/e.length}}const t=[...e];t[0].x===t[t.length-1].x&&t[0].y===t[t.length-1].y||t.push(t[0]);let r=0,n=0,i=0;for(let e=0;e<t.length-1;e++){const o=t[e].x*t[e+1].y-t[e+1].x*t[e].y;r+=o,n+=(t[e].x+t[e+1].x)*o,i+=(t[e].y+t[e+1].y)*o}return r*=.5,r?{x:n/(6*r),y:i/(6*r)}:{x:t[0].x,y:t[0].y}}(s);new $r(s,i,a,[],!0).fill(xe.fill.color,P(xe.fill.opacity,0,255,0,1,!0),xe.fill.texture_strength)}(this)),(e=>{xe.fill={...e}})(s)},Ne.prototype.fill=function(e,t,r){Yr().isActive&&(this.origin&&(e=this.origin[0],t=this.origin[1],r=1),this.pol=this.genPol(e,t,r,xe.fill.bleed_strength<.06?0:P(xe.fill.bleed_strength,0,.6,.2,.6,!0)),this.pol.fill())};let mn=null,dn=null,xn=null,gn=null,pn=null,yn=0,vn=0,bn=0;const _n={},wn={};function Rn(e,t,r,n){K(),xe.wash.opacity=(arguments.length<4?t:n)??150,xe.wash.color=arguments.length<3?i(e):i(e,t,r),xe.wash.isActive=!0}function An(e,t){const r=o();return[r.a*e+r.c*t+r.x+yn/2,r.b*e+r.d*t+r.y+vn/2]}xe.wash={color:null,opacity:150,isActive:!1},De.prototype.wash=function(e=!1,t){const r={...xe.wash};!1!==e&&Rn(e,t),xe.wash.isActive&&function(e){if(!xe.wash?.isActive||!xe.wash.color||e.vertices.length<3)return;ye(),function(){const e=H.drawingContext;pn&&!(yn!==Z||vn!==V)||(yn=Z,vn=V,pn=new Float32Array([2/yn,0,0,0,0,-2/vn,0,0,0,0,1,0,-1,1,0,1])),mn===e&&dn&&xn&&gn||(mn=e,dn=je(mn,"#version 300 es\nin vec2 a_position;\nuniform mat4 u_matrix;\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n}","#version 300 es\nprecision highp float;\nuniform vec4 u_color;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(u_color.rgb * u_color.a, u_color.a);\n}"),_n.a_position=mn.getAttribLocation(dn,"a_position"),wn.u_matrix=mn.getUniformLocation(dn,"u_matrix"),wn.u_color=mn.getUniformLocation(dn,"u_color"),xn=mn.createVertexArray(),mn.bindVertexArray(xn),gn=mn.createBuffer(),mn.bindBuffer(mn.ARRAY_BUFFER,gn),mn.bufferData(mn.ARRAY_BUFFER,0,mn.DYNAMIC_DRAW),bn=0,mn.enableVertexAttribArray(_n.a_position),mn.vertexAttribPointer(_n.a_position,2,mn.FLOAT,!1,8,0),mn.bindVertexArray(null),mn.bindBuffer(mn.ARRAY_BUFFER,null))}();const{triangles:t,vertexCount:r}=function(e){const t=new Float32Array(2*e.vertices.length);for(let r=0;r<e.vertices.length;r++){const n=e.vertices[r];t[2*r]=n.x,t[2*r+1]=n.y}const r=function(e,t,r=2){const n=e.length;let i=function(e,t,r,n){let i;if(1==function(e,t,r,n){let i=0;for(let t=0,o=r-n;t<r;t+=n)i+=(e[o]-e[t])*(e[t+1]+e[o+1]),o=t;return i}(e,0,r,n)>0)for(let t=0;t<r;t+=n)i=un(t/n|0,e[t],e[t+1],i);else for(let t=r-n;t>=0;t-=n)i=un(t/n|0,e[t],e[t+1],i);return i&&nn(i,i.next)&&(hn(i),i=i.next),i}(e,0,n,r);const o=[];if(!i||i.next===i.prev)return o;let s,a,c;if(e.length>80*r){s=e[0],a=e[1];let t=s,i=a;for(let o=r;o<n;o+=r){const r=e[o],n=e[o+1];r<s&&(s=r),n<a&&(a=n),r>t&&(t=r),n>i&&(i=n)}c=Math.max(t-s,i-a),c=0!==c?32767/c:0}return Wr(i,o,r,s,a,c,0),o}(t),n=new Float32Array(2*r.length);for(let e=0;e<r.length;e++){const i=r[e],[o,s]=An(t[2*i],t[2*i+1]);n[2*e]=o,n[2*e+1]=s}return{triangles:n,vertexCount:r.length}}(e),n=t.byteLength;mn.useProgram(dn),mn.enable(mn.BLEND),mn.blendEquation(mn.FUNC_ADD),mn.blendFunc(mn.ONE,mn.ONE_MINUS_SRC_ALPHA),mn.bindVertexArray(xn),mn.bindBuffer(mn.ARRAY_BUFFER,gn),n>bn?(mn.bufferData(mn.ARRAY_BUFFER,t,mn.DYNAMIC_DRAW),bn=n):mn.bufferSubData(mn.ARRAY_BUFFER,0,t);const i=xe.wash.color._array;mn.uniformMatrix4fv(wn.u_matrix,!1,pn),mn.uniform4f(wn.u_color,i[0],i[1],i[2],xe.wash.opacity/255),mn.drawArrays(mn.TRIANGLES,0,r),mn.bindVertexArray(null),mn.bindBuffer(mn.ARRAY_BUFFER,null),Ke(H,mn)}(this),xe.wash={...r}},Ne.prototype.wash=function(e,t,r){xe.wash?.isActive&&(this.origin&&(e=this.origin[0],t=this.origin[1],r=1),this.pol=this.genPol(e,t,r,0,-1),this.pol.wash())};let En=null,Mn=null;const Sn=[];let Tn=!1;const Pn=e=>!!e&&"function"==typeof e.begin&&"function"==typeof e.end&&!!e.renderer&&!!e.renderer._pInst,kn=e=>"number"==typeof e&&Number.isFinite(e)&&e>0,Cn=e=>{try{return e()}catch(e){return}},Fn=e=>!!e&&"function"==typeof e.pixelDensity&&"function"==typeof e.createFramebuffer&&kn(Cn(()=>e.width))&&kn(Cn(()=>e.height))&&"webgl2"===Cn(()=>e.webglVersion),In=e=>(Fn(e)&&(En=e),En),Ln=()=>(Mn&&Fn(Mn)?In(Mn):null)||In(window.self?.p5?.instance??null)||In($)||En,Dn=(e=!1)=>{const t=((e=!1)=>{const t=Ln();if(!e){if(!t)throw new Error("p5.brush could not resolve an active WEBGL sketch. Call brush.instance(p) and brush.load() after createCanvas(..., WEBGL).");return{renderer:t,width:t.width,height:t.height}}if(Pn(e)){const r=e.renderer._pInst;if(In(r),t&&r!==t)throw new Error("p5.brush only supports p5.Framebuffer targets created from the active sketch");return{renderer:r,width:e.width,height:e.height}}return{renderer:e,width:e.width,height:e.height}})(e);if(q({Renderer:t.renderer}),In(e?Ln():H),"webgl2"!==H.webglVersion)throw new Error("p5.brush requires a WEBGL canvas");q({Cwidth:t.width,Cheight:t.height}),Tn=!0},Nn=e=>{q({Instance:e}),In(e)},Bn=()=>H??Ln?.()??window.self?.p5?.instance??null,Yn={a:1,b:0,c:0,d:1,x:0,y:0},zn={a:1,b:0,c:0,d:1,x:0,y:0};function On(){const e=Bn();return!!e&&"function"==typeof e.angleMode&&e.angleMode()===e.RADIANS}function Un(e,t,r){const n=t.isEnabled(t.DEPTH_TEST);n&&t.disable(t.DEPTH_TEST);const i=e._renderer.activeFramebuffer?.()??null;return i?._beforeEnd&&i._beforeEnd(),t.bindFramebuffer(t.FRAMEBUFFER,function(e){return e?"function"==typeof e._framebufferToBind?e._framebufferToBind():e.framebuffer??null:null}(r)),t.viewport(0,0,r.width*r.density,r.height*r.density),{hadDepthTest:n,previousTarget:i}}function Xn(e,t,r){r?.hadDepthTest&&t.enable(t.DEPTH_TEST),r?.previousTarget?._beforeBegin?r.previousTarget._beforeBegin():(t.bindFramebuffer(t.FRAMEBUFFER,null),e._renderer.viewport(e._renderer._origViewport.width,e._renderer._origViewport.height),e._renderer._applyStencilTestIfClipping?.())}function Gn(e,t){const r=e?._renderer;r&&(r._curShader=null,r._cachedBlendMode=null,r._isBlending=null,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,null),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA))}function Zn(e,t,r){if(!t)return;if(r(t))return void t.draw(()=>e.clear());const n=t.drawingContext;n.save(),n.setTransform(1,0,0,1,0,0),n.clearRect(0,0,t.width,t.height),n.restore()}function Vn(e,t,r){return e.loaded||(e.loaded=!0,e.shaderProgram??=e.createShader(t,r)),e.shaderProgram}function $n(e,t,r,n,i){return t?.remove&&t.remove(),e.createFramebuffer({width:r,height:n,density:i,antialias:!1,depth:!1,stencil:!1})}const Hn=(e,t)=>e.createFramebuffer(t);function Wn({renderer:e,shader:t,source:r,mask:n,color:i,isBrushMask:o,Cwidth:s,Cheight:a,dirtyRect:c,targetIsFramebuffer:l,withScissor:u}){const h=e.drawingContext,f=h.isEnabled(h.DEPTH_TEST);h.disable(h.DEPTH_TEST),e.push(),e.translate(0,0),e.shader(t),t.setUniform("u_source",r),t.setUniform("u_targetIsFramebuffer",l),t.setUniform("u_isBrush",o),t.setUniform("u_mask",n),t.setUniform("u_color",i),u(h,c,()=>{e.fill(0,0,0,0),e.noStroke(),e.rect(-s/2,-a/2,s,a)},!l),e.pop(),e.resetShader(),f&&h.enable(h.DEPTH_TEST)}function jn(e){return e.isFramebufferTarget(e.sourceTarget)?((e.sourceTarget.renderer??e.renderer)._renderer?.flushDraw?.(),e.sourceFramebuffer.draw(()=>{e.withScissor(e.renderer.drawingContext,e.dirtyRect,()=>{e.renderer.clear(),e.renderer.push(),e.renderer.imageMode(e.renderer.CENTER),e.renderer.image(e.sourceTarget,0,0,e.Cwidth,e.Cheight),e.renderer.pop()},!1)}),e.sourceFramebuffer):(e.renderer._renderer?.flushDraw?.(),function({renderer:e,sourceFramebuffer:t,dirtyRect:r,getTargetPixelSize:n,toScissorBox:i}){const o=e.drawingContext,{width:s,height:a}=n(),c=r?i(r):null,l=o.getParameter(o.READ_FRAMEBUFFER_BINDING),u=o.getParameter(o.DRAW_FRAMEBUFFER_BINDING);return o.bindFramebuffer(o.READ_FRAMEBUFFER,null),o.bindFramebuffer(o.DRAW_FRAMEBUFFER,t.framebuffer),o.clearColor(0,0,0,0),o.clear(o.COLOR_BUFFER_BIT),o.blitFramebuffer(c?.x??0,c?.y??0,c?c.x+c.width:s,c?c.y+c.height:a,c?.x??0,c?.y??0,c?c.x+c.width:s,c?c.y+c.height:a,o.COLOR_BUFFER_BIT,o.NEAREST),o.bindFramebuffer(o.READ_FRAMEBUFFER,l),o.bindFramebuffer(o.DRAW_FRAMEBUFFER,u),t}(e))}const qn=()=>H??$??window.self?.p5?.instance;function Kn(e,t){const r=qn();if(!r?.createGraphics)throw new Error("p5 stroke tip creation requires an active renderer or instance.");return r.createGraphics(e,t)}function Jn(e,t){return new Promise((r,n)=>{const i=new window.Image;i.onload=()=>{const e=qn();if(!e?.createImage)return void n(new Error("p5 image tip loading requires an active renderer or instance."));const o=e.createImage(i.naturalWidth,i.naturalHeight);o.drawingContext.drawImage(i,0,0),t(o),r(o)},i.onerror=()=>n(new Error(`Failed to load image tip: ${e}`)),i.crossOrigin="anonymous",i.src=e})}const Qn=[];var ei;ei={load:Dn,syncDensity:()=>{const e=H.pixelDensity();return q({Density:e}),e},isCanvasReady:()=>{Tn||Dn()},instance:Nn,activateInstance:e=>{Sn.push(Mn),Mn=e,Nn(e)},deactivateInstance:()=>{Mn=Sn.pop()??null},getActiveFramebuffer:()=>H?._renderer?.activeFramebuffer?.()??null,isFramebufferTarget:Pn},j={...j,...ei},function(){var e;(e={usesRadians:On,fromDegrees:e=>On()?e*Math.PI/180:e,createColor:(...e)=>{const t=Bn();if(!t?.color)throw new Error("p5 runtime color creation requires an active renderer.");return t.color(...e)},getAffineMatrix:()=>{const e=Bn(),t=e?._renderer?.uModelMatrix?.mat4;return t?(zn.a=t[0],zn.b=t[1],zn.c=t[4],zn.d=t[5],zn.x=t[12],zn.y=t[13],zn):Yn}}).usesRadians&&(r=e.usesRadians),e.fromDegrees&&(n=e.fromDegrees),e.createColor&&(i=e.createColor),e.getAffineMatrix&&(o=e.getAffineMatrix)}(),function(){var e;e={beginDirectMaskDraw:Un,endDirectMaskDraw:Xn,resetDirectShaderTracking:Gn},qe={...qe,...e}}(),function(){var e;e={clearTarget:Zn,ensureBlendShaderProgram:Vn,ensureBlendSourceFramebuffer:$n,createFramebuffer:Hn,runBlendShaderPass:Wn,blitSourceToFramebuffer:jn},oe={...oe,...e}}(),function(){var e;e={createTipSurface:Kn,loadImageTip:Jn},He={...He,...e}}(),"undefined"!=typeof p5&&p5.registerAddon(function(e,t,r){r.presetup=function(){Q(this)},r.predraw=function(){Q(this)},r.postsetup=function(){J(this),ye(),ee()},r.postdraw=function(){J(this),ye(),ee()};const n=t.push,i=t.pop,o=t.randomSeed,s=t.noiseSeed;t.push=function(){n.call(this),be(),Qn.push({fill:{...xe.fill},wash:xe.wash?{...xe.wash}:null,stroke:{...xe.stroke},hatch:{...xe.hatch},mass:xe.mass?{...xe.mass}:null,field:{...xe.field}})},t.pop=function(){i.call(this),function(){const e=Qn.pop();e&&(xe.stroke={...e.stroke},xe.field={...e.field},xe.hatch={...e.hatch},xe.fill={...e.fill},e.wash&&(xe.wash={...e.wash}),e.mass?xe.mass={...e.mass}:xe.mass&&(xe.mass={...xe.mass,isActive:!1,brush:null,color:null,options:{}}))}()},t.randomSeed=function(e){o.call(this,e),y(e)},t.noiseSeed=function(e){s.call(this,e),_(e)}}),e.Plot=Ne,e.Polygon=De,e.Position=_e,e.add=Ht,e.addField=Fe,e.arc=Be,e.beginShape=Ge,e.beginStroke=function(e,t,r){if("curve"!==e&&"segments"!==e)throw new Error(`beginStroke() type must be "curve" or "segments", got "${e}".`);Ue=[t,r],Oe=new Ne(e)},e.box=function(){return[...Gt.keys()]},e.circle=function(e,t,r,n=!1){const i=new Ne("curve"),o=Math.PI*r,s=R(0,360),a=n?()=>1+.2*n*R():()=>1;for(let e=0;e<4;e++){const t=-90*e+s;i.addSegment(t*a(),o/2*a(),1,!0)}if(n){const e=n*M(-5,5);i.addSegment(s,Math.abs(e)*(Math.PI/180)*r,1,!0),i.endPlot(e+s,1,!0)}else i.endPlot(s,1,!0);const c=e-r*B(s),l=t-r*N(-s);i.show(c,l,1)},e.clip=function(e){return K(),e},e.endShape=Ve,e.endStroke=function(e,t){if(!Oe)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");Oe.endPlot(e,t),Oe.draw(Ue[0],Ue[1],1),Oe=!1},e.field=Ce,e.fill=zr,e.fillBleed=Or,e.fillTexture=Ur,e.flowLine=function(e,t,r,n){if(!xe.stroke.isActive||!xe.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");be(),ir(e,t,r),sr(Y(n),!1)},e.hatch=vr,e.hatchArray=wr,e.hatchStyle=function(e,t="black",r=1){xe.hatch.hBrush={brush:e,color:t,weight:r}},e.instance=J,e.line=mr,e.listFields=function(){return be(),Array.from(Se.keys())},e.load=(e=!1)=>{((e=!1)=>{j.load(e)})(e),H.loaded&&pe.load()},e.mass=function(e,t,r={}){xe.mass.brush=e,xe.mass.color=t,xe.mass.options=r,xe.mass.isActive=!0},e.move=function(e,t,r){if(!Oe)throw new Error("move() called without beginStroke(). Call beginStroke() first.");Oe.addSegment(e,t,r)},e.noClip=function(){},e.noField=function(){be(),xe.field.isActive=!1},e.noFill=function(){xe.fill.isActive=!1},e.noHatch=function(){xe.hatch.isActive=!1,xe.hatch.hBrush=!1},e.noMass=function(){xe.mass.isActive=!1,xe.mass.brush=null,xe.mass.color=null,xe.mass.options={}},e.noStroke=function(){xe.stroke.isActive=!1},e.noWash=function(){xe.wash.isActive=!1},e.noiseSeed=_,e.pick=jt,e.polygon=function(e){new De(e).show()},e.rect=function(e,t,r,n,i="corner"){"center"===i&&(e-=r/2,t-=n/2),Ge(0),Ze(e,t),Ze(e+r,t),Ze(e+r,t+n),Ze(e,t+n),Ve(!0)},e.refreshField=function(e=0){if(!xe.field.isActive||!xe.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const t=Se.get(xe.field.current);t.field=ke(t,e)},e.scaleBrushes=function(e){for(const{param:t}of Gt.values())t&&(t.weight*=e,t.scatter*=e,t.spacing*=e)},e.seed=y,e.set=Jt,e.spline=function(e,t=.5){if(!e||e.length<2)throw new Error("spline() requires at least 2 points. Each point should be [x, y, pressure].");$e(e,t).draw()},e.stroke=qt,e.strokeWeight=Kt,e.vertex=Ze,e.wRand=T,e.wash=Rn,e.wiggle=Ie},"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).brush={});
+var e,t;e=this,t=function(e){const t={a:1,b:0,c:0,d:1,x:0,y:0};let r=()=>!1,n=e=>e,i=()=>{throw new Error("No runtime color adapter registered.")},o=()=>t;const s=Math.sqrt(3),a=.5*(s-1),c=(3-s)/6,l=e=>0|Math.floor(e),u=new Float64Array([1,1,-1,1,1,-1,-1,-1,1,0,-1,0,1,0,-1,0,0,1,0,-1,0,1,0,-1]);function h(e=Math.random){const t=function(e){const t=new Uint8Array(512);for(let e=0;e<256;e++)t[e]=e;for(let r=0;r<255;r++){const n=r+~~(e()*(256-r)),i=t[r];t[r]=t[n],t[n]=i}for(let e=256;e<512;e++)t[e]=t[e-256];return t}(e),r=new Float64Array(t).map(e=>u[e%12*2]),n=new Float64Array(t).map(e=>u[e%12*2+1]);return function(e,i){let o=0,s=0,u=0;const h=(e+i)*a,f=l(e+h),d=l(i+h),m=(f+d)*c,x=e-(f-m),g=i-(d-m);let p,y;x>g?(p=1,y=0):(p=0,y=1);const v=x-p+c,b=g-y+c,_=x-1+2*c,w=g-1+2*c,R=255&f,A=255&d;let E=.5-x*x-g*g;if(E>=0){const e=R+t[A];E*=E,o=E*E*(r[e]*x+n[e]*g)}let M=.5-v*v-b*b;if(M>=0){const e=R+p+t[A+y];M*=M,s=M*M*(r[e]*v+n[e]*b)}let S=.5-_*_-w*w;if(S>=0){const e=R+1+t[A+1];S*=S,u=S*S*(r[e]*_+n[e]*w)}return 70*(o+s+u)}}function f(e,t){let r=new d(e),n=()=>r.next();return n.double=()=>n()+11102230246251565e-32*(2097152*n()|0),n.int32=()=>4294967296*r.next()|0,n.quick=n,n}class d{constructor(e){null==e&&(e=+new Date);let t=4022871197;function r(e){e=String(e);for(let r=0;r<e.length;r++){t+=e.charCodeAt(r);let n=.02519603282416938*t;t=n>>>0,n-=t,n*=t,t=n>>>0,n-=t,t+=4294967296*n}return 2.3283064365386963e-10*(t>>>0)}this.c=1,this.s0=r(" "),this.s1=r(" "),this.s2=r(" "),this.s0-=r(e),this.s0<0&&(this.s0+=1),this.s1-=r(e),this.s1<0&&(this.s1+=1),this.s2-=r(e),this.s2<0&&(this.s2+=1)}next(){let{c:e,s0:t,s1:r,s2:n}=this,i=2091639*t+2.3283064365386963e-10*e;return this.s0=r,this.s1=n,this.s2=i-(this.c=0|i)}copy(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}}let m=f(Math.random()),x=f(Math.random());const g=[],p=e=>g.push(e),y=e=>{m=f(e),x=f(`${e}:2`);for(const e of g)e()};let v=h(f(Math.random())),b=h(f(Math.random()));const _=e=>{v=h(f(e)),b=h(f(`${e}:2`))},w=(e=0,t=1)=>e+m()*(t-e),R=(e=0,t=1)=>e+x()*(t-e),A=e=>e[~~(m()*e.length)],E=(e,t)=>~~w(e,t),M=(e,t)=>~~R(e,t),S=(e=0,t=1)=>{const r=1-m(),n=m();return Math.sqrt(-2*Math.log(r))*D(360*n)*t+e},T=(e,t,r,n,i,o=!1)=>{let s=n+(e-t)/(r-t)*(i-n);return o?n<i?P(s,n,i):P(s,i,n):s},P=(e,t,r)=>Math.max(Math.min(e,r),t),C=e=>(e%=360)<0?e+360:e,k=1440,F=2*Math.PI/k,I=new Float32Array(k).fill(NaN),L=new Float32Array(k).fill(NaN),D=e=>{const t=~~(4*C(e));let r=I[t];return isNaN(r)&&(r=Math.cos(t*F),I[t]=r),r},N=e=>{const t=~~(4*C(e));let r=L[t];return isNaN(r)&&(r=Math.sin(t*F),L[t]=r),r},B=(e,t=!1)=>{if(t||r()){let t=180*e/Math.PI%360;return t<0?t+360:t}return e},Y=(e,t=!1)=>t||r()?180*e/Math.PI:e,z=(e,t,r,n,i)=>{let o=D(i),s=N(i);return{x:o*(r-e)+s*(n-t)+e,y:o*(n-t)-s*(r-e)+t}},O=(e,t,r,n)=>Math.hypot(r-e,n-t),U=(e,t,r,n)=>B(Math.atan2(-(n-t),r-e),!0),X=(e,t,r,n,i=!1)=>{let o=e.x,s=e.y,a=t.x,c=t.y,l=r.x,u=r.y,h=n.x,f=n.y;if(o===a&&s===c||l===h&&u===f)return!1;let d=a-o,m=c-s,x=h-l,g=f-u,p=g*d-x*m;if(0===p)return!1;let y=(x*(s-u)-g*(o-l))/p,v=(d*(s-u)-m*(o-l))/p;return!(!i&&(v<0||v>1))&&{x:o+y*d,y:s+y*m}};let Z,G,V,H,W,$={load:()=>{throw new Error("No target runtime adapter registered.")},syncDensity:()=>W,isCanvasReady:()=>{throw new Error("No target runtime adapter registered.")},instance:e=>{V=e},activateInstance:e=>{V=e},deactivateInstance:()=>{},getActiveFramebuffer:()=>null,isFramebufferTarget:()=>!1};function j(e){"Cwidth"in e&&(Z=e.Cwidth),"Cheight"in e&&(G=e.Cheight),"Instance"in e&&(V=e.Instance),"Renderer"in e&&(H=e.Renderer),"Density"in e&&(W=e.Density)}const q=()=>$.isCanvasReady(),K=e=>$.instance(e),J=e=>$.activateInstance(e),Q=()=>$.deactivateInstance(),ee=()=>$.getActiveFramebuffer(),te=e=>$.isFramebufferTarget(e),re=(e,t=0)=>e?{minX:e.minX-t,minY:e.minY-t,maxX:e.maxX+t,maxY:e.maxY+t}:null,ne=(e,t,r=!1)=>{const n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):(()=>{const r=document.createElement("canvas");return r.width=e,r.height=t,r})();return n.drawingContext=n.getContext("2d",r?{willReadFrequently:!0}:void 0),n};let ie={clearTarget:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendShaderProgram:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendSourceFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},createFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},runBlendShaderPass:()=>{throw new Error("No compositor runtime adapter registered.")},blitSourceToFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")}};const oe=(...e)=>ie.createFramebuffer(...e);let se=null,ae=null;const ce=e=>{((...e)=>{ie.clearTarget(...e)})(H,e,te)},le=()=>({width:Math.max(1,Math.round(Z*W)),height:Math.max(1,Math.round(G*W))}),ue=e=>{if(!e)return null;const{width:t,height:r}=le();return((e,t,r)=>{if(!e)return null;const n=Math.max(0,Math.floor(Math.min(e.minX,e.maxX))),i=Math.max(0,Math.floor(Math.min(e.minY,e.maxY))),o=Math.min(t,Math.ceil(Math.max(e.minX,e.maxX))),s=Math.min(r,Math.ceil(Math.max(e.minY,e.maxY)));return o<=n||s<=i?null:{minX:n,minY:i,maxX:o,maxY:s}})(e,t,r)},he=()=>{const{width:e,height:t}=le();return((e,t)=>({minX:0,minY:0,maxX:e,maxY:t}))(e,t)},fe=(e,t=!0)=>{const r=ue(e);if(!r)return null;const{height:n}=le();return{x:r.minX,y:t?n-r.maxY:r.minY,width:r.maxX-r.minX,height:r.maxY-r.minY}},de=(e,t,r,n=!0)=>{const i=fe(t,n);if(i){e.enable(e.SCISSOR_TEST),e.scissor(i.x,i.y,i.width,i.height);try{r()}finally{e.disable(e.SCISSOR_TEST)}}else r()},me={},xe=()=>{H?.loaded||(q(),ge.load())},ge={isBlending:!1,cachedColor:null,markDirtyRect(e,t){const r=ue(t);var n,i;e&&r&&(e.dirtyRect=(i=r,(n=e.dirtyRect)?i?{minX:Math.min(n.minX,i.minX),minY:Math.min(n.minY,i.minY),maxX:Math.max(n.maxX,i.maxX),maxY:Math.max(n.maxY,i.maxY)}:n:i),e.isDrawn=!0)},clearMask(e){if(!e)return;const t=e===this.glMask?se:ae;t?.clearMask?.(e,ce)},getCompositeRect(e,t){const r=t?se:ae;return r?.getCompositeRect?.(e,ee,he,re,ue)},load(){$.syncDensity();const e=!H.blendSourceFramebuffer||H.blendSourceFramebuffer.width!==Z||H.blendSourceFramebuffer.height!==G||"function"==typeof H.blendSourceFramebuffer.pixelDensity&&H.blendSourceFramebuffer.pixelDensity()!==W;((...e)=>{ie.ensureBlendShaderProgram(...e)})(H,"#version 300 es\n#define GLSLIFY 1\nout vec2 p;void main(){vec3 v=vec3(-1);v[gl_VertexID]=3.;p=v.xy;gl_Position=vec4(v.x,-v.y,0,1);}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nuniform bool u_isBrush;uniform bool u_targetIsFramebuffer;uniform sampler2D u_source;uniform sampler2D u_mask;uniform vec3 u_color;in vec2 p;out vec4 outColor;const int SPECTRAL_SIZE=38;const float SPECTRAL_GAMMA=2.4;const float SPECTRAL_EPSILON=0.0000000000000001;float spectral_uncompand(float x){return(x<0.04045)? x/12.92 : pow((x+0.055)/1.055,SPECTRAL_GAMMA);}float spectral_compand(float x){return(x<0.0031308)? x*12.92 : 1.055*pow(x,1.0/SPECTRAL_GAMMA)-0.055;}vec3 spectral_srgb_to_linear(vec3 srgb){return vec3(spectral_uncompand(srgb[0]),spectral_uncompand(srgb[1]),spectral_uncompand(srgb[2]));}vec3 spectral_linear_to_srgb(vec3 lrgb){return clamp(vec3(spectral_compand(lrgb[0]),spectral_compand(lrgb[1]),spectral_compand(lrgb[2])),0.,1.);}void spectral_linear_to_reflectance(vec3 lrgb,inout float R[SPECTRAL_SIZE]){float w=min(lrgb.r,min(lrgb.g,lrgb.b));lrgb-=w;float c=min(lrgb.g,lrgb.b);float m=min(lrgb.r,lrgb.b);float y=min(lrgb.r,lrgb.g);float r=min(max(0.0,lrgb.r-lrgb.b),max(0.0,lrgb.r-lrgb.g));float g=min(max(0.0,lrgb.g-lrgb.b),max(0.0,lrgb.g-lrgb.r));float b=min(max(0.0,lrgb.b-lrgb.g),max(0.0,lrgb.b-lrgb.r));R[0]=max(SPECTRAL_EPSILON,w*1.0011607271876400+c*0.9705850013229620+m*0.9906735573199880+y*0.0210523371789306+r*0.0315605737777207+g*0.0095560747554212+b*0.9794047525020140);R[1]=max(SPECTRAL_EPSILON,w*1.0011606515972800+c*0.9705924981434250+m*0.9906715249619790+y*0.0210564627517414+r*0.0315520718330149+g*0.0095581580120851+b*0.9794007068431300);R[2]=max(SPECTRAL_EPSILON,w*1.0011603192274700+c*0.9706253487298910+m*0.9906625823534210+y*0.0210746178695038+r*0.0315148215513658+g*0.0095673245444588+b*0.9793829034702610);R[3]=max(SPECTRAL_EPSILON,w*1.0011586727078900+c*0.9707868061190170+m*0.9906181076447950+y*0.0211649058448753+r*0.0313318044982702+g*0.0096129126297349+b*0.9792943649455940);R[4]=max(SPECTRAL_EPSILON,w*1.0011525984455200+c*0.9713686732282480+m*0.9904514808787100+y*0.0215027957272504+r*0.0306729857725527+g*0.0097837090401843+b*0.9789630146085700);R[5]=max(SPECTRAL_EPSILON,w*1.0011325252899800+c*0.9731632306212520+m*0.9898710814002040+y*0.0226738799041561+r*0.0286480476989607+g*0.0103786227058710+b*0.9778144666940430);R[6]=max(SPECTRAL_EPSILON,w*1.0010850066332700+c*0.9767402231587650+m*0.9882866087596400+y*0.0258235649693629+r*0.0246450407045709+g*0.0120026452378567+b*0.9747243211338360);R[7]=max(SPECTRAL_EPSILON,w*1.0009968788945300+c*0.9815876054913770+m*0.9842906927975040+y*0.0334879385639851+r*0.0192960753663651+g*0.0160977721473922+b*0.9671984823439730);R[8]=max(SPECTRAL_EPSILON,w*1.0008652515227400+c*0.9862802656529490+m*0.9739349056253060+y*0.0519069663740307+r*0.0142066612220556+g*0.0267061902231680+b*0.9490796575305750);R[9]=max(SPECTRAL_EPSILON,w*1.0006962900094000+c*0.9899491476891340+m*0.9418178384601450+y*0.1007490148334730+r*0.0102942608878609+g*0.0595555440185881+b*0.9008501289409770);R[10]=max(SPECTRAL_EPSILON,w*1.0005049611488800+c*0.9924927015384200+m*0.8173903261951560+y*0.2391298997068470+r*0.0076191460521811+g*0.1860398265328260+b*0.7631504454622400);R[11]=max(SPECTRAL_EPSILON,w*1.0003080818799200+c*0.9941456804052560+m*0.4324728050657290+y*0.5348043122727480+r*0.0058980410835420+g*0.5705798201161590+b*0.4659221716493190);R[12]=max(SPECTRAL_EPSILON,w*1.0001196660201300+c*0.9951839750332120+m*0.1384539782588700+y*0.7978075786430300+r*0.0048233247781713+g*0.8614677684002920+b*0.2012632804510050);R[13]=max(SPECTRAL_EPSILON,w*0.9999527659684070+c*0.9957567501108180+m*0.0537347216940033+y*0.9114498940673840+r*0.0042298748350633+g*0.9458790897676580+b*0.0877524413419623);R[14]=max(SPECTRAL_EPSILON,w*0.9998218368992970+c*0.9959128182867100+m*0.0292174996673231+y*0.9537979630045070+r*0.0040599171299341+g*0.9704654864743050+b*0.0457176793291679);R[15]=max(SPECTRAL_EPSILON,w*0.9997386095575930+c*0.9956061578345280+m*0.0213136517508590+y*0.9712416154654290+r*0.0043533695594676+g*0.9784136302844500+b*0.0284706050521843);R[16]=max(SPECTRAL_EPSILON,w*0.9997095516396120+c*0.9945976009618540+m*0.0201349530181136+y*0.9793031238075880+r*0.0053434425970201+g*0.9795890314112240+b*0.0205271767569850);R[17]=max(SPECTRAL_EPSILON,w*0.9997319302106270+c*0.9922157154923700+m*0.0241323096280662+y*0.9833801195075750+r*0.0076917201010463+g*0.9755335369086320+b*0.0165302792310211);R[18]=max(SPECTRAL_EPSILON,w*0.9997994363461950+c*0.9862364527832490+m*0.0372236145223627+y*0.9854612465677550+r*0.0135969795736536+g*0.9622887553978130+b*0.0145135107212858);R[19]=max(SPECTRAL_EPSILON,w*0.9999003303166710+c*0.9679433372645410+m*0.0760506552706601+y*0.9864350469766050+r*0.0316975442661115+g*0.9231215745131200+b*0.0136003508637687);R[20]=max(SPECTRAL_EPSILON,w*1.0000204065261100+c*0.8912850042449430+m*0.2053754719423990+y*0.9867382506701410+r*0.1078611963552490+g*0.7934340189431110+b*0.0133604258769571);R[21]=max(SPECTRAL_EPSILON,w*1.0001447879365800+c*0.5362024778620530+m*0.5412689034604390+y*0.9866178824450320+r*0.4638126031687040+g*0.4592701359024290+b*0.0135488943145680);R[22]=max(SPECTRAL_EPSILON,w*1.0002599790341200+c*0.1541081190018780+m*0.8158416850864860+y*0.9862777767586430+r*0.8470554052720110+g*0.1855741036663030+b*0.0139594356366992);R[23]=max(SPECTRAL_EPSILON,w*1.0003557969708900+c*0.0574575093228929+m*0.9128177041239760+y*0.9858605924440560+r*0.9431854093939180+g*0.0881774959955372+b*0.0144434255753570);R[24]=max(SPECTRAL_EPSILON,w*1.0004275378026900+c*0.0315349873107007+m*0.9463398301669620+y*0.9854749276762100+r*0.9688621506965580+g*0.0543630228766700+b*0.0148854440621406);R[25]=max(SPECTRAL_EPSILON,w*1.0004762334488800+c*0.0222633920086335+m*0.9599276963319910+y*0.9851769347655580+r*0.9780306674736030+g*0.0406288447060719+b*0.0152254296999746);R[26]=max(SPECTRAL_EPSILON,w*1.0005072096750800+c*0.0182022841492439+m*0.9662605952303120+y*0.9849715740141810+r*0.9820436438543060+g*0.0342215204316970+b*0.0154592848180209);R[27]=max(SPECTRAL_EPSILON,w*1.0005251915637300+c*0.0162990559732640+m*0.9693259700584240+y*0.9848463034157120+r*0.9839236237187070+g*0.0311185790956966+b*0.0156018026485961);R[28]=max(SPECTRAL_EPSILON,w*1.0005350960689600+c*0.0153656239334613+m*0.9708545367213990+y*0.9847753518111990+r*0.9848454841543820+g*0.0295708898336134+b*0.0156824871281936);R[29]=max(SPECTRAL_EPSILON,w*1.0005402209748200+c*0.0149111568733976+m*0.9716050665281280+y*0.9847380666252650+r*0.9852942758145960+g*0.0288108739348928+b*0.0157248764360615);R[30]=max(SPECTRAL_EPSILON,w*1.0005427281678400+c*0.0146954339898235+m*0.9719627697573920+y*0.9847196483117650+r*0.9855072952198250+g*0.0284486271324597+b*0.0157458108784121);R[31]=max(SPECTRAL_EPSILON,w*1.0005438956908700+c*0.0145964146717719+m*0.9721272722745090+y*0.9847110233919390+r*0.9856050715398370+g*0.0282820301724731+b*0.0157556123350225);R[32]=max(SPECTRAL_EPSILON,w*1.0005444821215100+c*0.0145470156699655+m*0.9722094177458120+y*0.9847066833006760+r*0.9856538499335780+g*0.0281988376490237+b*0.0157605443964911);R[33]=max(SPECTRAL_EPSILON,w*1.0005447695999200+c*0.0145228771899495+m*0.9722495776784240+y*0.9847045543930910+r*0.9856776850338830+g*0.0281581655342037+b*0.0157629637515278);R[34]=max(SPECTRAL_EPSILON,w*1.0005448988776200+c*0.0145120341118965+m*0.9722676219987420+y*0.9847035963093700+r*0.9856883918061220+g*0.0281398910216386+b*0.0157640525629106);R[35]=max(SPECTRAL_EPSILON,w*1.0005449625468900+c*0.0145066940939832+m*0.9722765094621500+y*0.9847031240775520+r*0.9856936646900310+g*0.0281308901665811+b*0.0157645892329510);R[36]=max(SPECTRAL_EPSILON,w*1.0005449892705800+c*0.0145044507314479+m*0.9722802433068740+y*0.9847029256150900+r*0.9856958798482050+g*0.0281271086805816+b*0.0157648147772649);R[37]=max(SPECTRAL_EPSILON,w*1.0005449969930000+c*0.0145038009464639+m*0.9722813248265600+y*0.9847028681227950+r*0.9856965214637620+g*0.0281260133612096+b*0.0157648801149616);}vec3 spectral_xyz_to_srgb(vec3 xyz){mat3 XYZ_RGB;XYZ_RGB[0]=vec3(3.2409699419045200,-1.537383177570090,-0.4986107602930030);XYZ_RGB[1]=vec3(-0.9692436362808790,1.875967501507720,0.0415550574071756);XYZ_RGB[2]=vec3(0.0556300796969936,-0.203976958888976,1.0569715142428700);float r=dot(XYZ_RGB[0],xyz);float g=dot(XYZ_RGB[1],xyz);float b=dot(XYZ_RGB[2],xyz);return spectral_linear_to_srgb(vec3(r,g,b));}vec3 spectral_reflectance_to_xyz(float R[SPECTRAL_SIZE]){vec3 xyz=vec3(0.);xyz+=R[0]*vec3(0.0000646919989576,0.0000018442894440,0.0003050171476380);xyz+=R[1]*vec3(0.0002194098998132,0.0000062053235865,0.0010368066663574);xyz+=R[2]*vec3(0.0011205743509343,0.0000310096046799,0.0053131363323992);xyz+=R[3]*vec3(0.0037666134117111,0.0001047483849269,0.0179543925899536);xyz+=R[4]*vec3(0.0118805536037990,0.0003536405299538,0.0570775815345485);xyz+=R[5]*vec3(0.0232864424191771,0.0009514714056444,0.1136516189362870);xyz+=R[6]*vec3(0.0345594181969747,0.0022822631748318,0.1733587261835500);xyz+=R[7]*vec3(0.0372237901162006,0.0042073290434730,0.1962065755586570);xyz+=R[8]*vec3(0.0324183761091486,0.0066887983719014,0.1860823707062960);xyz+=R[9]*vec3(0.0212332056093810,0.0098883960193565,0.1399504753832070);xyz+=R[10]*vec3(0.0104909907685421,0.0152494514496311,0.0891745294268649);xyz+=R[11]*vec3(0.0032958375797931,0.0214183109449723,0.0478962113517075);xyz+=R[12]*vec3(0.0005070351633801,0.0334229301575068,0.0281456253957952);xyz+=R[13]*vec3(0.0009486742057141,0.0513100134918512,0.0161376622950514);xyz+=R[14]*vec3(0.0062737180998318,0.0704020839399490,0.0077591019215214);xyz+=R[15]*vec3(0.0168646241897775,0.0878387072603517,0.0042961483736618);xyz+=R[16]*vec3(0.0286896490259810,0.0942490536184085,0.0020055092122156);xyz+=R[17]*vec3(0.0426748124691731,0.0979566702718931,0.0008614711098802);xyz+=R[18]*vec3(0.0562547481311377,0.0941521856862608,0.0003690387177652);xyz+=R[19]*vec3(0.0694703972677158,0.0867810237486753,0.0001914287288574);xyz+=R[20]*vec3(0.0830531516998291,0.0788565338632013,0.0001495555858975);xyz+=R[21]*vec3(0.0861260963002257,0.0635267026203555,0.0000923109285104);xyz+=R[22]*vec3(0.0904661376847769,0.0537414167568200,0.0000681349182337);xyz+=R[23]*vec3(0.0850038650591277,0.0426460643574120,0.0000288263655696);xyz+=R[24]*vec3(0.0709066691074488,0.0316173492792708,0.0000157671820553);xyz+=R[25]*vec3(0.0506288916373645,0.0208852059213910,0.0000039406041027);xyz+=R[26]*vec3(0.0354739618852640,0.0138601101360152,0.0000015840125870);xyz+=R[27]*vec3(0.0214682102597065,0.0081026402038399,0.0000000000000000);xyz+=R[28]*vec3(0.0125164567619117,0.0046301022588030,0.0000000000000000);xyz+=R[29]*vec3(0.0068045816390165,0.0024913800051319,0.0000000000000000);xyz+=R[30]*vec3(0.0034645657946526,0.0012593033677378,0.0000000000000000);xyz+=R[31]*vec3(0.0014976097506959,0.0005416465221680,0.0000000000000000);xyz+=R[32]*vec3(0.0007697004809280,0.0002779528920067,0.0000000000000000);xyz+=R[33]*vec3(0.0004073680581315,0.0001471080673854,0.0000000000000000);xyz+=R[34]*vec3(0.0001690104031614,0.0000610327472927,0.0000000000000000);xyz+=R[35]*vec3(0.0000952245150365,0.0000343873229523,0.0000000000000000);xyz+=R[36]*vec3(0.0000490309872958,0.0000177059860053,0.0000000000000000);xyz+=R[37]*vec3(0.0000199961492222,0.0000072209749130,0.0000000000000000);return xyz;}float KS(float R){return pow(1.0-R,2.0)/(2.0*R);}float KM(float KS){return 1.0+KS-sqrt(pow(KS,2.0)+2.0*KS);}vec3 spectral_mix(vec3 color1,float tintingStrength1,float factor1,vec3 color2,float tintingStrength2,float factor2){vec3 lrgb1=spectral_srgb_to_linear(color1);vec3 lrgb2=spectral_srgb_to_linear(color2);float R1[SPECTRAL_SIZE];float R2[SPECTRAL_SIZE];spectral_linear_to_reflectance(lrgb1,R1);spectral_linear_to_reflectance(lrgb2,R2);float luminance1=spectral_reflectance_to_xyz(R1)[1];float luminance2=spectral_reflectance_to_xyz(R2)[1];float R[SPECTRAL_SIZE];for(int i=0;i<SPECTRAL_SIZE;i++){float concentration1=pow(factor1,2.)*pow(tintingStrength1,2.)*luminance1;float concentration2=pow(factor2,2.)*pow(tintingStrength2,2.)*luminance2;float totalConcentration=concentration1+concentration2;float ksMix=0.;ksMix+=KS(R1[i])*concentration1;ksMix+=KS(R2[i])*concentration2;R[i]=KM(ksMix/totalConcentration);}return spectral_xyz_to_srgb(spectral_reflectance_to_xyz(R));}vec3 spectral_mix(vec3 color1,vec3 color2,float factor){return spectral_mix(color1,1.,1.-factor,color2,1.,factor);}vec3 spectral_mix(vec3 color1,float factor1,vec3 color2,float factor2){return spectral_mix(color1,1.,factor1,color2,1.,factor2);}const float GAMMA=2.4,EPSILON=0.0001;const float DARKEN_THRESHOLD=0.7;const float EDGE_MIN=0.05,EDGE_MAX=0.35;void main(void){vec2 uv=0.5*p+0.5;vec2 sourceUV=vec2(uv.x,1.0-uv.y);vec2 maskUV=u_targetIsFramebuffer ? vec2(uv.x,1.0-uv.y): uv;vec4 source=texture(u_source,sourceUV);vec4 maskColor=texture(u_mask,maskUV);if(maskColor.a==0.0){outColor=source;return;}vec4 pigment=vec4(u_color.xyz,1.0);if(maskColor.a>DARKEN_THRESHOLD){float blacken=0.5*(min(maskColor.a,1.0)-DARKEN_THRESHOLD);pigment=pigment*(1.0-blacken)-vec4(0.5)*blacken;pigment.rgb=max(pigment.rgb,vec3(0.0));}float mixIntensity=min(maskColor.a,1.0);if(!u_isBrush){vec2 texelSize=1.0/vec2(textureSize(u_mask,0));float scaledAlpha=maskColor.a*15.0;float blurEdge=0.0;for(int i=-2;i<=2;i+=2){for(int j=-2;j<=2;j+=2){vec2 neighborUV=maskUV+vec2(float(i),float(j))*texelSize;float neighborAlpha=texture(u_mask,neighborUV).a*15.0;blurEdge+=smoothstep(EDGE_MIN,EDGE_MAX,length(vec2(dFdx(neighborAlpha),dFdy(neighborAlpha))));}}blurEdge/=9.0;mixIntensity=clamp(maskColor.a+blurEdge*0.1,0.0,1.0);}vec3 bgColor=mix(vec3(1.0),source.rgb,source.a);outColor=vec4(spectral_mix(bgColor,pigment.rgb,mixIntensity),1.);}"),this.glMask=se?.ensureResources?.(H,Z,G,W);const t=ae?.ensureResources?.(H,Z,G,W,ce)??{mask:null,ctx:null};e&&(H.blendSourceFramebuffer=((...e)=>ie.ensureBlendSourceFramebuffer(...e))(H,H.blendSourceFramebuffer,Z,G,W)),this.mask=t.mask,this.ctx=t.ctx},blend(e=!1,t=!1){xe();const r=!0===this.isBrush,n=r?this.glMask:this.mask,i=r?this.mask:this.glMask,o=e?._array,s=!!o&&(this.cachedColor?.[0]!==o[0]||this.cachedColor?.[1]!==o[1]||this.cachedColor?.[2]!==o[2]||this.cachedColor?.[3]!==o[3]);!this.isBlending&&o&&(this.isBlending=!0,this.cachedColor=o,this.clearMask(this.glMask)),(t||s)&&(this.justChanged&&(this.applyShader(i,!r),this.justChanged=!1),this.isBlending&&this.applyShader(n,r),o&&(this.cachedColor=o),t&&(this.isBlending=!1,this.cachedColor=null))},applyShader(e,t){if(!e?.isDrawn)return;const r=this.getCompositeRect(e,t);if(!r)return void this.clearMask(e);H.drawingContext;const n=H.shaderProgram,i=ee(),o=((...e)=>ie.blitSourceToFramebuffer(...e))({renderer:H,sourceTarget:i??H,sourceFramebuffer:H.blendSourceFramebuffer,dirtyRect:r,isFramebufferTarget:te,Cwidth:Z,Cheight:G,getTargetPixelSize:le,toScissorBox:fe,withScissor:de}),s=!!i,a=(t?se:ae).getShaderMask(H,e,r,he,ce);((...e)=>{ie.runBlendShaderPass(...e)})({renderer:H,shader:n,source:o,mask:a,color:this.cachedColor,isBrushMask:t,Cwidth:Z,Cheight:G,dirtyRect:r,targetIsFramebuffer:s,withScissor:de}),this.clearMask(e)}},pe=()=>{xe(),ge.blend(!1,!0),ge.clearMask(ge.glMask),ge.clearMask(ge.mask),ge.justChanged=!1,ge.isBlending=!1,ge.isBrush=null,ge.cachedColor=null};let ye=!1;function ve(){ye||(xe(),_e=.01*Z,we=-.5*Z,Re=-.5*G,Ae=Math.round(2*Z/_e),Ee=Math.round(2*G/_e),ke("hand",(e,t)=>{const r=R(.2,.8),n=M(5,10);return Ie(t,(t,i)=>.5*n*N(r*i*t+M(15,25))*.2*D(e)+b(t,i)*n*.7)}),ke("curved",(e,t)=>{let r=M(-10,10);return M(0,100)%2==0&&(r*=-1),Ie(t,(t,n)=>3*T(b(.02*t+.03*e,.02*n+.03*e),0,1,-r,r))}),ke("zigzag",(e,t)=>{let r=M(-30,-15)+Math.abs(44*N(e));M(0,100)%2==0&&(r*=-1);let n=r,i=0;for(let e=0;e<Ae;e++){for(let r=0;r<Ee;r++)t[e][r]=i,i+=n,n*=-1;i+=n,n*=-1}return t}),ke("waves",(e,t)=>{const r=M(10,15)+5*N(e),n=M(3,6)+3*D(e),i=M(20,35);return Ie(t,(e,t)=>N(r*e)*i*D(t*n)+M(-3,3))}),ke("seabed",(e,t)=>{const r=R(.4,.8),n=M(18,26);return Ie(t,(t,i)=>1.1*n*N(r*i*t+M(15,20))*D(e))}),ke("spiral",(e,t)=>{const r=M(5,10),n=2*M(0,2)-1,i=M(65,80),o=Array.from({length:r},()=>({x:R(.1,.9)*Ae,y:R(.1,.9)*Ee}));return Ie(t,(e,t)=>{let r=0,s=0;for(const a of o){const o=e-a.x,c=t-a.y,l=1/(o*o+c*c+1),u=Math.atan2(c,o)*(180/Math.PI),h=n*(u+i)*Math.PI/180;r+=l*Math.cos(h),s+=l*Math.sin(h)}return Math.atan2(s,r)*(180/Math.PI)})}),ke("columns",(e,t)=>{const r=M(3,8),n=M(25,45);return Ie(t,(e,t)=>N(e*r)*n)}),ye=!0)}class be{constructor(e,t){ve();const r=o();this.mx=r.x,this.my=r.y,this.update(e,t),this.plotted=0}update(e,t){this.x=e,this.y=t,me.field.isActive&&(this.colIdx=Math.round((e+this.mx-we)/_e),this.rowIdx=Math.round((t+this.my-Re)/_e))}reset(){this.plotted=0}isIn(){return me.field.isActive?be.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const e=Z,t=G,r=this.x+this.mx,n=this.y+this.my;return r>=-.3*e&&r<=1.3*e&&n>=-.3*t&&n<=1.3*t}angle(e=!1){return me.field.isActive&&(e||this.isIn())?Me.get(me.field.current).field[this.colIdx][this.rowIdx]*me.field.wiggle:0}moveTo(e,t,r=1){this.movePos(Y(e),t,r)}_moveToDegrees(e,t,r=1){this.movePos(e,t,r)}plotTo(e,t,r,n=1,i=void 0){this.movePos(e,t,r,n,i)}movePos(e,t,r,n=!1,i=void 0){const o=n||1;if(!this.isIn())return void(this.plotted+=r/o);const s=t/r,a=me.field.isActive,c=!!n;for(let t=0;t<s;t++){const n=c&&void 0!==i&&0===t?i:c?e.angle(this.plotted):e,s=(a?this.angle(!0):0)-n;this.update(this.x+r*D(s),this.y+r*N(s)),this.plotted+=r/o}}static getRowIndex(e,t=1){const r=e+o().y-Re;return Math.round(r/_e/t)}static getColIndex(e,t=1){const r=e+o().x-we;return Math.round(r/_e/t)}static isIn(e,t){return e>=0&&t>=0&&e<Ae&&t<Ee}}me.field={isActive:!1,current:null,wiggle:1};let _e,we,Re,Ae,Ee,Me=new Map;const Se=new Set(["degrees","radians"]);function Te(e={}){const t=("string"==typeof e?{angleMode:e}:e||{}).angleMode??"degrees";if(!Se.has(t))throw new Error(`Invalid field angle mode "${t}". Use "degrees" or "radians".`);return t}function Pe(e,t){return function(e,t){if("radians"!==t)return e;for(let t=0;t<e.length;t++)for(let r=0;r<e[t].length;r++)e[t][r]=Y(e[t][r],!0);return e}(e.gen(t,new Array(Ae).fill(null).map(()=>new Float32Array(Ee))),e.angleMode)}function Ce(e){if(me.field.wiggle||(me.field.wiggle=1),ve(),!Me.has(e))throw new Error(`Field "${e}" does not exist. Available fields: ${Array.from(Me.keys()).join(", ")}.`);me.field.isActive=!0,me.field.current=e;const t=Me.get(e);t.field||(t.field=Pe(t,0))}function ke(e,t,r={}){Me.set(e,{gen:t,field:null,angleMode:Te(r)})}function Fe(e=1){Ce("hand"),me.field.wiggle=e}function Ie(e,t){for(let r=0;r<Ae;r++)for(let n=0;n<Ee;n++)e[r][n]=t(r,n);return e}class Le{constructor(e,t=!1){this.a=e,this.vertices=t?e:e.map(([e,t])=>({x:e,y:t})),this.sides=this.vertices.map((e,t,r)=>[e,r[(t+1)%r.length]]),this._intersectionCache={}}intersect(e){const t=`${e.point1.x},${e.point1.y}-${e.point2.x},${e.point2.y}`;if(this._intersectionCache[t])return this._intersectionCache[t];const r=[];for(const[t,n]of this.sides){const i=X(e.point1,e.point2,t,n);i&&r.push(i)}return this._intersectionCache[t]=r,r}show(){me.wash&&this.wash(),me.fill&&this.fill(),me.mass&&this.mass(),me.hatch&&this.hatch(),me.stroke&&this.draw()}}class De{constructor(e){this.segments=[],this.angles=[],this.pres=[],this.type=e,this.dir=0,this.calcIndex(0),this.pol=!1}addSegment(e=0,t=0,r=1,n=!1){this.angles.length>0&&this.angles.pop(),e=n?(e%360+360)%360:B(e),this.angles.push(e,e),this.pres.push(r),this.segments.push(t),this.length=this.segments.reduce((e,t)=>e+t,0)}endPlot(e=0,t=1,r=!1){e=r?(e%360+360)%360:B(e),this.angles[this.angles.length-1]=e,this.pres.push(t)}rotate(e){this.dir=B(e)}pressure(e){return e>this.length?this.pres[this.pres.length-1]:this.curving(this.pres,e)}angle(e){return e>this.length?this.angles[this.angles.length-1]:(this.calcIndex(e),"curve"===this.type?this.curving(this.angles,e)+this.dir:this.angles[this.index]+this.dir)}curving(e,t){let r=e[this.index],n=e[this.index+1]??r;return Math.abs(n-r)>180&&(n>r?n=-(360-n):r=-(360-r)),T(t-this.suma,0,this.segments[this.index],r,n,!0)}calcIndex(e){this.index=-1,this.suma=0;let t=0;for(;t<=e;)this.suma=t,t+=this.segments[this.index+1],this.index++;return this.index}genPol(e,t,r=1,n){ve();const i=n<0?4:1,o=[],s=Math.round(this.length/i),a=new be(e+Z/2,t+G/2);let c=0,l=0;for(let e=0;e<s;e++){a.plotTo(this,i,i);const e=this.calcIndex(a.plotted);c+=i,(c>=(n<=0?8:Math.max(this.segments[e]*n*R(.7,1.3),20))||e>=l)&&a.x&&(o.push([a.x-Z/2,a.y-G/2]),c=0,e>=l&&l++)}return new Le(o)}show(e,t,r=1){me.wash&&this.wash(e,t,r),me.fill&&this.fill(e,t,r),me.mass&&this.mass(e,t,r),me.hatch&&this.hatch(e,t,r),me.stroke&&this.draw(e,t,r)}}function Ne(e,t,r,n,i){const o=Y(n),s=((Y(i)-o)%360+360)%360;if(0===s)return;const a=new De("curve"),c=Math.max(1,Math.ceil(s/90)),l=s/c,u=Math.PI*r*l/180;for(let e=0;e<c;e++)a.addSegment(o+e*l+90,u,1,!0);a.endPlot(o+s+90,1,!0);const h=e+r*D(o),f=t-r*N(o);a.draw(h,f,1)}let Be,Ye,ze,Oe;class Ue{constructor(){this.isClosed=!1,this.curvature=Ye,this.vert=[]}vertex(e,t,r){this.vert.push([e,t,r])}show(){Ve(this.vert,this.curvature,this.isClosed).show()}}function Xe(e=0){Ye=P(e,0,1),Be=new Ue}function Ze(e,t,r=1){if(!Be)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");Be.vertex(e,t,r)}function Ge(e=!1){if(!Be)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(Be.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");e&&(Be.vertex(...Be.vert[0]),Be.isClosed=!0),Be.show(),Be=!1}function Ve(e,t=.5,r=!1){const n=new De(0===t?"segments":"curve"),i=2*Math.PI;if(r&&0!==t&&e.push(e[1]),e&&e.length>0){let o,s,a,c=0;for(let l=0;l<e.length-1;l++)if(t>0&&l<e.length-2){const u=e[l],h=e[l+1],f=e[l+2],d=O(u[0],u[1],h[0],h[1]),m=O(h[0],h[1],f[0],f[1]),x=U(u[0],u[1],h[0],h[1]),g=U(h[0],h[1],f[0],f[1]),p=t*Math.min(d,m,.5*Math.min(d,m)),y=Math.max(d,m),v=d-p,b=m-p;if(Math.floor(x)===Math.floor(g)){const t=r&&0===l?0:d-c,i=r?0===l?0:m-a:m;n.addSegment(x,t,u[2],!0),l===e.length-3&&n.addSegment(g,i,h[2],!0),c=0,0===l&&(o=d,a=p,s=e[1],c=0)}else{const t={x:h[0]-p*D(-x),y:h[1]-p*N(-x)},f={x:t.x+y*D(90-x),y:t.y+y*N(90-x)},d={x:h[0]+p*D(-g),y:h[1]+p*N(-g)},m={x:d.x+y*D(90-g),y:d.y+y*N(90-g)},_=X(t,f,d,m,!0),w=O(t.x,t.y,_.x,_.y),R=O(t.x,t.y,d.x,d.y)/2,A=i*w*(2*Math.asin(R/w)*(180/Math.PI))/360,E=r&&0===l?0:v-c,M=l===e.length-3?r?o-p:b:0;n.addSegment(x,E,u[2],!0),n.addSegment(x,isNaN(A)?0:A,u[2],!0),n.addSegment(g,M,h[2],!0),c=p,0===l&&(o=v,a=p,s=[t.x,t.y])}l===e.length-3&&n.endPlot(g,h[2],!0)}else if(0===t){const t=e[l],r=e[l+1],i=O(t[0],t[1],r[0],r[1]),o=U(t[0],t[1],r[0],r[1]);n.addSegment(o,i,r[2],!0),l===e.length-2&&n.endPlot(o,1,!0)}n.origin=r&&0!==t?s:e[0]}return n}let He={createTipSurface:()=>{throw new Error("No stroke runtime adapter registered.")},loadImageTip:()=>{throw new Error("No stroke runtime adapter registered.")}},We=!1;const $e=(e,t,r)=>{const n=e.createProgram();for(let[i,o]of[[e.VERTEX_SHADER,t],[e.FRAGMENT_SHADER,r]]){const t=e.createShader(i);e.shaderSource(t,o),e.compileShader(t),e.attachShader(n,t)}return e.linkProgram(n),n};let je={beginDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},endDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},resetDirectShaderTracking:()=>{}};const qe=(e,t)=>je.resetDirectShaderTracking(e,t);let Ke,Je,Qe,et,tt,rt=!1,nt=0,it=0,ot=null;const st={},at={};let ct=1,lt=0,ut=0,ht=1,ft=0,dt=0,mt=0,xt=0,gt=1,pt=1,yt=new Float32Array(8192),vt=0,bt=2048,_t=32768,wt=null,Rt=null,At=null,Et=null,Mt=null;const St={},Tt={};let Pt=0,Ct=new Float32Array(1280),kt=0,Ft=256,It=null;const Lt=new Map,Dt=new Float32Array([-1,-1,1,-1,-1,1,1,1]);function Nt(){return Je}function Bt(){return((e,t,r)=>je.beginDirectMaskDraw(e,t,r))(H,Ke,ge.glMask)}function Yt(e){((e,t,r)=>{je.endDirectMaskDraw(e,t,r)})(H,Ke,e)}function zt(e,t,r,n,i){return e?(t<e.minX&&(e.minX=t),r<e.minY&&(e.minY=r),n>e.maxX&&(e.maxX=n),i>e.maxY&&(e.maxY=i),e):{minX:t,minY:r,maxX:n,maxY:i}}function Ot(e,t,r,n){if(vt>=bt){bt*=2;const e=new Float32Array(4*bt);e.set(yt),yt=e}const i=e-mt,o=t-xt,s=4*vt,a=ct*i+ut*o+ft+mt,c=lt*i+ht*o+dt+xt,l=pt*r*gt/2;yt[s]=a,yt[s+1]=c,yt[s+2]=l,yt[s+3]=n/255;const u=a*pt,h=c*pt;wt=zt(wt,u-l-1,h-l-1,u+l+1,h+l+1),vt++}function Ut(e,t){if(0===kt)return;ge.glMask.isDrawn=!0;const r=Bt();let n=Lt.get(t);n||(n=Ke.createTexture(),Ke.bindTexture(Ke.TEXTURE_2D,n),Ke.texImage2D(Ke.TEXTURE_2D,0,Ke.RGBA,Ke.RGBA,Ke.UNSIGNED_BYTE,e.canvas),Ke.texParameteri(Ke.TEXTURE_2D,Ke.TEXTURE_MIN_FILTER,Ke.LINEAR),Ke.texParameteri(Ke.TEXTURE_2D,Ke.TEXTURE_MAG_FILTER,Ke.LINEAR),Ke.texParameteri(Ke.TEXTURE_2D,Ke.TEXTURE_WRAP_S,Ke.CLAMP_TO_EDGE),Ke.texParameteri(Ke.TEXTURE_2D,Ke.TEXTURE_WRAP_T,Ke.CLAMP_TO_EDGE),Lt.set(t,n)),Ke.useProgram(Rt),Ke.enable(Ke.BLEND),Ke.blendFunc(Ke.ONE_MINUS_DST_ALPHA,Ke.ONE),Ke.activeTexture(Ke.TEXTURE0),Ke.bindTexture(Ke.TEXTURE_2D,n),Ke.uniform1i(Tt.u_tex,0);const i=me.stroke.color._array;Ke.uniform4f(Tt.u_color,...i),Ke.uniformMatrix4fv(Tt.u_proj,!1,Nt()),Ke.bindVertexArray(At),Ke.bindBuffer(Ke.ARRAY_BUFFER,Mt);const o=5*kt*4,s=Ct.subarray(0,5*kt);o>Pt?(Ke.bufferData(Ke.ARRAY_BUFFER,Ct,Ke.DYNAMIC_DRAW),Pt=Ct.byteLength):Ke.bufferSubData(Ke.ARRAY_BUFFER,0,s),Ke.drawArraysInstanced(Ke.TRIANGLE_STRIP,0,4,kt),Ke.bindVertexArray(null),Ke.bindTexture(Ke.TEXTURE_2D,null),Yt(r),It&&(ge.markDirtyRect(ge.glMask,It),It=null),kt=0,qe(H,Ke)}We||(se={ensureResources:function(e,t,r,n){return function(e,t,r,n){return!e.glMask||e.glMask.width!==t||e.glMask.height!==r||"function"==typeof e.glMask.pixelDensity&&e.glMask.pixelDensity()!==n}(e,t,r,n)&&(e.glMask?.remove&&e.glMask.remove(),e.glMask=oe(e,{width:t,height:r,density:n,antialias:!1,depth:!1,stencil:!1})),e.glMask.dirtyRect??=null,e.glMask.isDrawn??=!1,e.glMask},clearMask:function(e,t){e&&(t(e),e.isDrawn=!1,e.dirtyRect=null)},getCompositeRect:function(e,t,r,n,i){return e?e.dirtyRect?t()?r():i(n(e.dirtyRect,2)):r():null},getShaderMask:function(e,t){return t}},We=!0),me.stroke={color:null,weight:1,type:"HB",isActive:!1,opacity:1};let Xt=new Map;const Zt={offset:.08,scale:.08,warp:.06,tilt:.06};function Gt(){return{...me.stroke}}function Vt(e){me.stroke={...e}}function Ht(e,t){if(t.type=["marker","custom","image","spray"].includes(t.type)?t.type:"default",void 0===t.markerTip&&(t.markerTip=!0),void 0===t.noise&&(t.noise=.3),t.noise=Math.max(0,Math.min(1,t.noise)),void 0!==t.vibration&&void 0===t.scatter&&(t.scatter=t.vibration),void 0!==t.definition&&void 0===t.sharpness&&(t.sharpness=t.definition),void 0!==t.quality&&void 0===t.grain&&(t.grain=t.quality),t.pressure=function(e){if(!e)return e;if("function"==typeof e)return{type:"custom",min_max:[0,1],curve:e,variation:{...Zt}};if("object"==typeof e&&!Array.isArray(e)){if("custom"===e.type||"custom"===e.mode){const{mode:t,...r}=e;return{...r,type:"custom",variation:{...Zt,...r.variation??{}}}}return"gaussian"===e.type||"gaussian"===e.mode||Array.isArray(e.curve)&&Array.isArray(e.min_max)?{...e,type:"gaussian",curve:e.curve,min_max:e.min_max}:e}if(Array.isArray(e)){const[t,r,n]=2===e.length?[e[0],(e[0]+e[1])/2,e[1]]:e,i=Math.min(t,r,n),o=Math.max(t,r,n),s=o-i||1,[a,c,l]=[(t-i)/s,(r-i)/s,(n-i)/s];return{type:"custom",min_max:[i,o],variation:{...Zt},curve:e=>e<.5?a+(c-a)*e*2:c+(l-c)*(e-.5)*2}}}(t.pressure),"custom"===t.type){if("function"!=typeof t.tip)throw new Error(`Brush "${e}" is type "custom" but is missing a tip function.`);const r=`custom::${e}`;!function(e){const t=Lt.get(e);t&&Ke&&Ke.deleteTexture(t),Lt.delete(e)}(r);const n=He.createTipSurface(500,500);return n.pixelDensity(1),n.background(255),n.noSmooth(),n.push(),n.translate(250,250),n.scale(5),n.noStroke(),t.tip(n),n.pop(),yr.imageToWhite(n),yr.tips.set(r,n),t.tipKey=r,void Xt.set(e,{param:t,colors:[],buffers:[]})}if("image"===t.type){if(!t.image||!t.image.src)throw new Error(`Brush "${e}" is type "image" but is missing params.image.src. Example: image: { src: "./tip.jpg" }`);return yr.add(t.image.src),Xt.set(e,{param:t,colors:[],buffers:[]}),yr.load()}Xt.set(e,{param:t,colors:[],buffers:[]})}function Wt(e){return Xt.get(e)?.param??null}function $t(e){if(!Xt.has(e))throw new Error(`Brush "${e}" not found. Available brushes: ${[...Xt.keys()].join(", ")}.`);me.stroke.type=e}function jt(e,t,r){q(),me.stroke.color=i(...arguments),me.stroke.isActive=!0}function qt(e){me.stroke.weight=e}function Kt(e,t,r=1){$t(e),jt(t),qt(r)}let Jt,Qt,er,tr,rr=0;const nr={};function ir(e,t,r,n=!1){!function(){const e=o();ct=e.a,lt=e.b,ut=e.c,ht=e.d,ft=e.x,dt=e.y,mt=Z/2,xt=G/2,gt=Math.sqrt(ct*ct+lt*lt),pt=W}(),Jt=new be(e+Z/2,t+G/2),Qt=r,er=n,er&&er.calcIndex(0)}const or=[];function sr(e,t){t||(tr=e),function(){nr.seed=999999*w();const{param:e}=Xt.get(me.stroke.type)??{};if(!e)return;nr.p=e;const{pressure:t}=e;if(nr.isCustomPressure="custom"===t.type,nr.a=nr.isCustomPressure?0:w(-1,1),nr.b=nr.isCustomPressure?0:w(1,1.5),nr.isCustomPressure){const e=t.variation??Zt;nr.cp=w(-e.offset,e.offset),nr.ct=w(-e.warp,e.warp),nr.cs=w(1-e.scale,1+e.scale),nr.ck=w(-e.tilt,e.tilt)}else nr.cp=w(3,3.5),nr.ct=0,nr.cs=1,nr.ck=0;[nr.min,nr.max]=t.min_max,nr.noiseoffset=.05*nr.p.noise,er||(nr.cos=D(tr),nr.sin=N(tr)),function(){xe(),function(){const e=H?.glMask;e&&(ot=e,ot.dirtyRect??=null,ot.isDrawn??=!1,ge.glMask=ot)}();const e=H.drawingContext,t=!rt||Ke!==e;(t||nt!==Z||it!==G)&&(Je=new Float32Array([2/Z,0,0,0,0,2/G,0,0,0,0,1,0,-1,-1,0,1]),nt=Z,it=G),t&&(Ke=e,tt=$e(Ke,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_position;in float a_radius;in float a_alpha;uniform mat4 u_matrix;out float v_alpha;void main(){gl_Position=u_matrix*vec4(a_position,0.0,1.0);v_alpha=a_alpha;gl_PointSize=a_radius*2.0;}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin float v_alpha;out vec4 outColor;uniform vec4 u_color;void main(){vec2 v=gl_PointCoord-vec2(0.5);float f=length(v);float a=fwidth(f);f=1.0-smoothstep(0.5-a,0.5+a,f);if(f<0.01){discard;}outColor=vec4(u_color.xyz,v_alpha*f);}"),Ke.useProgram(tt),Ke.enable(Ke.BLEND),Ke.blendFunc(Ke.ONE_MINUS_DST_ALPHA,Ke.ONE),["a_position","a_radius","a_alpha"].forEach(e=>st[e]=Ke.getAttribLocation(tt,e)),["u_matrix","u_color"].forEach(e=>at[e]=Ke.getUniformLocation(tt,e)),Qe=Ke.createVertexArray(),Ke.bindVertexArray(Qe),et=Ke.createBuffer(),Ke.bindBuffer(Ke.ARRAY_BUFFER,et),Ke.bufferData(Ke.ARRAY_BUFFER,yt.byteLength,Ke.DYNAMIC_DRAW),_t=yt.byteLength,Ke.enableVertexAttribArray(st.a_position),Ke.vertexAttribPointer(st.a_position,2,Ke.FLOAT,!1,16,0),Ke.enableVertexAttribArray(st.a_radius),Ke.vertexAttribPointer(st.a_radius,1,Ke.FLOAT,!1,16,8),Ke.enableVertexAttribArray(st.a_alpha),Ke.vertexAttribPointer(st.a_alpha,1,Ke.FLOAT,!1,16,12),Ke.bindVertexArray(null),Lt.clear(),Rt=$e(Ke,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_corner;in vec2 a_pos;in float a_size;in float a_angle;in float a_alpha;uniform mat4 u_proj;out vec2 v_uv;out float v_alpha;void main(){float c=cos(a_angle);float s=sin(a_angle);vec2 rotated=vec2(c*a_corner.x-s*a_corner.y,s*a_corner.x+c*a_corner.y);gl_Position=u_proj*vec4(a_pos+rotated*a_size,0.0,1.0);v_uv=a_corner*0.5+0.5;v_alpha=a_alpha;}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin vec2 v_uv;in float v_alpha;uniform sampler2D u_tex;uniform vec4 u_color;out vec4 outColor;void main(){float inkAlpha=texture(u_tex,v_uv).a;if(inkAlpha<0.01)discard;outColor=vec4(u_color.rgb,inkAlpha*v_alpha);}"),["a_corner","a_pos","a_size","a_angle","a_alpha"].forEach(e=>St[e]=Ke.getAttribLocation(Rt,e)),["u_proj","u_color","u_tex"].forEach(e=>Tt[e]=Ke.getUniformLocation(Rt,e)),At=Ke.createVertexArray(),Ke.bindVertexArray(At),Et=Ke.createBuffer(),Ke.bindBuffer(Ke.ARRAY_BUFFER,Et),Ke.bufferData(Ke.ARRAY_BUFFER,Dt,Ke.STATIC_DRAW),Ke.enableVertexAttribArray(St.a_corner),Ke.vertexAttribPointer(St.a_corner,2,Ke.FLOAT,!1,0,0),Mt=Ke.createBuffer(),Ke.bindBuffer(Ke.ARRAY_BUFFER,Mt),Ke.bufferData(Ke.ARRAY_BUFFER,Ct.byteLength,Ke.DYNAMIC_DRAW),Pt=Ct.byteLength,Ke.enableVertexAttribArray(St.a_pos),Ke.vertexAttribPointer(St.a_pos,2,Ke.FLOAT,!1,20,0),Ke.vertexAttribDivisor(St.a_pos,1),Ke.enableVertexAttribArray(St.a_size),Ke.vertexAttribPointer(St.a_size,1,Ke.FLOAT,!1,20,8),Ke.vertexAttribDivisor(St.a_size,1),Ke.enableVertexAttribArray(St.a_angle),Ke.vertexAttribPointer(St.a_angle,1,Ke.FLOAT,!1,20,12),Ke.vertexAttribDivisor(St.a_angle,1),Ke.enableVertexAttribArray(St.a_alpha),Ke.vertexAttribPointer(St.a_alpha,1,Ke.FLOAT,!1,20,16),Ke.vertexAttribDivisor(St.a_alpha,1),Ke.bindVertexArray(null),rt=!0)}();const r=!0!==ge.isBrush;ge.isBrush=!0,r&&(ge.justChanged=!0),ge.blend(me.stroke.color),nr.alpha=["default","spray"].includes(nr.p.type)?nr.p.opacity:nr.p.opacity/Math.min(me.stroke.weight,1.3),nr.overscan=function(){const e=Math.max(1,nr.max??1),t=me.stroke.weight*nr.p.scatter,r=me.stroke.weight*nr.p.weight*e;return Math.max(8,1.5*t+.75*r)}(),nr.drawFn="spray"===nr.p.type?ur:"marker"===nr.p.type?hr:"custom"===nr.p.type||"image"===nr.p.type?fr:dr,mr()}();const r=nr.p?.spacing??1,n=Math.round(Qt*(t?e:1)/r);nr.pressureCount=10,nr.cachedPressure=void 0,nr.lineNoiseCount=5,nr.cachedLineNoise=void 0;const i=2*n;for(;or.length<i;)or.push(S());for(let i=0;i<n;i++)t&&(rr=er.angle(Jt.plotted)),ar(),t?Jt.plotTo(er,r,r,e,rr):Jt._moveToDegrees(e,r,r);!function(){mr(),function(){if(0===vt)return;ge.glMask.isDrawn=!0;const e=Bt(),t=me.stroke.color._array;Ke.useProgram(tt),Ke.enable(Ke.BLEND),Ke.blendFunc(Ke.ONE_MINUS_DST_ALPHA,Ke.ONE),Ke.bindVertexArray(Qe),Ke.bindBuffer(Ke.ARRAY_BUFFER,et);const r=16*vt,n=yt.subarray(0,4*vt);r>_t?(Ke.bufferData(Ke.ARRAY_BUFFER,yt,Ke.DYNAMIC_DRAW),_t=yt.byteLength):Ke.bufferSubData(Ke.ARRAY_BUFFER,0,n),Ke.uniform4f(at.u_color,...t),Ke.uniformMatrix4fv(at.u_matrix,!1,Nt()),Ke.drawArrays(Ke.POINTS,0,vt),Ke.bindVertexArray(null),Yt(e),wt&&(ge.markDirtyRect(ge.glMask,wt),wt=null),vt=0,qe(H,Ke)}();const e=nr.p?.type;"image"===e?Ut(yr.tips.get(nr.p.image.src),nr.p.image.src):"custom"===e&&Ut(yr.tips.get(nr.p.tipKey),nr.p.tipKey)}()}function ar(){const e=cr(),t=((nr.lineNoiseCount>=10||void 0===nr.cachedLineNoise)&&(nr.cachedLineNoise=T(v(nr.seed+.01*Jt.plotted,0),-1,1,1-nr.noiseoffset,1+nr.noiseoffset),nr.lineNoiseCount=0),nr.lineNoiseCount++,nr.cachedLineNoise);t>w(1,1.02)&&w(0,1)<.7||nr.drawFn(e*t)}function cr(){return(nr.pressureCount>=10||void 0===nr.cachedPressure)&&(nr.cachedPressure=er?lr()*er.pressure(Jt.plotted):lr(),nr.pressureCount=0),nr.pressureCount++,nr.cachedPressure}function lr(){if(!nr.isCustomPressure)return function(e=.5+nr.p.pressure.curve[0]*nr.a,t=1-nr.p.pressure.curve[1]*nr.b,r=nr.cp,n=nr.min,i=nr.max){const o=e*Qt,s=(Jt.plotted<o?1.2*t:.8*t)*(Qt/2);return T(1/(1+Math.pow(Math.abs((Jt.plotted-o)/s),2*r)),0,1,n,i)}();const e=Jt.plotted/Qt;return T(nr.p.pressure.curve(Math.max(0,Math.min(1,.5+(e-.5+nr.ct)*nr.cs)))+nr.cp+nr.ck*(e-.5),0,1,nr.min,nr.max,!0)}function ur(e){const t=me.stroke.weight*nr.p.scatter*e+me.stroke.weight*A(or)*nr.p.scatter/3,r=nr.p.weight*w(.9,1.1),n=Math.ceil(nr.p.grain/e);for(let e=0;e<n;e++){const e=w(.9,1.1),n=e*t*w(-1,1),i=w(-1,1),o=Math.sqrt((e*t)**2-n**2);Ot(Jt.x+n,Jt.y+i*o,r,nr.alpha)}}function hr(e,t=!0,r=nr.alpha){const n=t?me.stroke.weight*nr.p.scatter:0,i=t?n*w(-1,1):0,o=t?n*w(-1,1):0;Ot(Jt.x+i,Jt.y+o,me.stroke.weight*nr.p.weight*e,r*Math.max(.8,e)*w(.9,1.1))}function fr(e,t=nr.alpha){const r=me.stroke.weight*nr.p.scatter,n=r*w(-1,1),i=r*w(-1,1),o=nr.p.weight*me.stroke.weight*e,s=nr.overscan;let a=0;"random"===nr.p.rotate?a=E(0,360)*(Math.PI/180):"natural"===nr.p.rotate&&(a=((er?-rr:-tr)+Jt.angle())*(Math.PI/180)),function(e,t,r,n,i,o=0){if(kt>=Ft){Ft*=2;const e=new Float32Array(5*Ft);e.set(Ct),Ct=e}const s=e-mt,a=t-xt,c=ct*s+ut*a+ft+mt,l=lt*s+ht*a+dt+xt,u=pt*r*gt/2,h=pt*o*gt,f=5*kt;Ct[f]=c,Ct[f+1]=l,Ct[f+2]=u,Ct[f+3]=n,Ct[f+4]=i/255;const d=c*pt,m=l*pt,x=1.42*u+h;It=zt(It,d-x-1,m-x-1,d+x+1,m+x+1),kt++}(Jt.x+n,Jt.y+i,o,a,t*Math.max(.8,e)*w(.9,1.1),s)}function dr(e,t=1){const r=(t=T(t,0,1,.9,1.05))*me.stroke.weight*nr.p.scatter*(nr.p.sharpness+(1-nr.p.sharpness)*A(or)/e);if(w(0,nr.p.grain*e)>.4){let t,n;if(er){const e=rr,i=D(e),o=N(e),s=r*w(-1,1),a=.3*r*w(-1,1);t=s*o+a*i,n=s*i-a*o}else{const e=r*w(-1,1),i=.3*r*w(-1,1);t=e*nr.sin+i*nr.cos,n=e*nr.cos-i*nr.sin}const i=e*e*nr.p.weight*w(.85,1.15)*me.stroke.weight,o=Math.max(.9,e)*nr.alpha*w(.75,1.1);Ot(Jt.x+t,Jt.y+n,i,o)}}function mr(){if(!1===nr.p.markerTip)return;let e=cr(),t=nr.alpha;if("marker"===nr.p.type)for(let r=1;r<10;r++)hr(e*r/10,!0,8*t);else if("custom"===nr.p.type||"image"===nr.p.type)for(let r=1;r<5;r++)fr(e*r/10,2*t)}function xr(e,t,r,n){if(!me.stroke.isActive||!me.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");ve();let i=O(e,t,r,n);0!=i&&(ir(e,t,i),sr(U(e,t,r,n),!1))}p(()=>{or.length=0});const gr=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate","markerTip","noise"],pr=[["pen",[.3,.15,.9,2,150,.1,{curve:[.15,.2],min_max:[1.2,1]}]],["rotring",[.15,.05,.7,15,210,.1,{curve:[.35,.2],min_max:[1.3,1]}]],["2B",[.3,.75,.45,15,180,.1,{curve:[.1,.3],min_max:[1.1,.9]}]],["HB",[.3,.6,.3,10,170,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["2H",[.2,.6,.3,4,120,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["cpencil",[.3,.55,.8,7,75,.1,{curve:[.15,.2],min_max:[.95,1.2]}]],["pastel",[2.05/3,13.4/3,.91,28,35,.085/3,{mode:"gaussian",curve:[.4,.05],min_max:[1.09,.93]},"default",void 0,"natural",!0,1]],["crayon",[.3,5.45/3,.75,250,159,.23/3,[1.1,.9],"default",void 0,"natural",!0,1]],["charcoal",[.35,1.5,.68,500,120,.03,{curve:[.15,.4],min_max:[1.1,.95]}]],["spray",[.2,6,15,40,90,.5,{curve:[.2,.35],min_max:[.7,1]},"spray"]],["marker",[2,.2,null,null,1,.03,{curve:[.35,.25],min_max:[1.2,.85]},"marker"]]];for(let e of pr){let t={};for(let r=0;r<e[1].length;r++)t[gr[r]]=e[1][r];Ht(e[0],t)}Le.prototype.draw=function(e=!1,t,r){let n=Gt();if(e&&Kt(e,t,r),n.isActive)for(let e of this.sides)xr(e[0].x,e[0].y,e[1].x,e[1].y);Vt(n)},De.prototype.draw=function(e,t,r){Gt().isActive&&(this.origin&&(e=this.origin[0],t=this.origin[1],r=1),function(e,t,r,n){ve(),ir(t,r,e.length,e),sr(n,!0)}(this,e,t,r))};const yr={tips:new Map,add(e){this.tips.has(e)||this.tips.set(e,!1)},imageToWhite(e){e.loadPixels();for(let t=0;t<4*e.width*e.height;t+=4){let r=(e.pixels[t]+e.pixels[t+1]+e.pixels[t+2])/3;e.pixels[t]=e.pixels[t+1]=e.pixels[t+2]=255,e.pixels[t+3]=255-r}e.updatePixels()},async load(){const e=[...this.tips.keys()].filter(e=>!this.tips.get(e));await Promise.all(e.map(e=>((e,t)=>He.loadImageTip(e,t))(e,yr.imageToWhite).then(t=>{this.tips.set(e,t)})))}};function vr(){return{...me.hatch}}function br(e){me.hatch={...e}}function _r(e=5,t=45,r={rand:!1,continuous:!1,gradient:!1}){let n=me.hatch;n.isActive=!0,n.dist=e,n.angle=Y(t),n.options=r}function wr(e,t,r,n){const i=t*Math.PI/180,o=Math.cos(i),s=Math.sin(i),a=Math.cos(-i),c=Math.sin(-i),l=e.a,u=l.length,h=new Array(u);let f=Infinity,d=-Infinity;for(let e=0;e<u;e++){const t=l[e][0],r=l[e][1],n=[t*o-r*s,t*s+r*o];h[e]=n,n[1]<f&&(f=n[1]),n[1]>d&&(d=n[1])}const m=[];for(let e=0;e<u;e++){const t=h[e],r=h[(e+1)%u];t[1]!==r[1]&&m.push(t,r)}const x=m.length,g=[],p=[];let y=f+.5*r,v=r;for(;y<d;){p.length=0;for(let e=0;e<x;e+=2){const t=m[e][1],r=m[e+1][1];(t<=y&&y<r||r<=y&&y<t)&&p.push(m[e][0]+(y-t)/(r-t)*(m[e+1][0]-m[e][0]))}p.sort((e,t)=>e-t);for(let e=0;e<p.length-1;e+=2)g.push({scanY:y,x1:p[e]*a-y*c,y1:p[e]*c+y*a,x2:p[e+1]*a-y*c,y2:p[e+1]*c+y*a});y+=v,v*=n}return g}function Rr(e){const{dist:t,options:r,segs:n}=function(e){const t=me.hatch.dist,r=(me.hatch.angle%180+180)%180,n=me.hatch.options,i=function(e,t,r,n){Array.isArray(e)||(e=[e]);const i=[];for(const o of e)for(const e of wr(o,r,t,n))i.push(e);return i.sort((e,t)=>e.scanY===t.scanY?e.x1-t.x1:e.scanY-t.scanY),i}(e,t,r,n.gradient?T(n.gradient,0,1,1,1.1,!0):1);return{dist:t,options:n,segs:i}}(e),i=r.rand||0,o=[];for(let e=0;e<n.length;e++){const s=n[e];let a=s.x1,c=s.y1,l=s.x2,u=s.y2;i&&(a+=2*i*t*w(-1,1),c+=2*i*t*w(-1,1),l+=2*i*t*w(-1,1),u+=2*i*t*w(-1,1));const h=r.continuous&&e%2==1?{x1:l,y1:u,x2:a,y2:c,scanY:s.scanY,isConnector:!1}:{x1:a,y1:c,x2:l,y2:u,scanY:s.scanY,isConnector:!1};if(o.push(h),e>0&&r.continuous){const e=o[o.length-2];o.push({x1:e.x2,y1:e.y2,x2:h.x1,y2:h.y1,scanY:s.scanY,isConnector:!0})}}return o}function Ar(e){!function(e,t){const r=Rr(e);!function(){const e=Gt();me.hatch.hBrush&&Kt(...Object.values(me.hatch.hBrush)),(()=>{for(let e=0;e<r.length;e++){const n=r[e];t(n.x1,n.y1,n.x2,n.y2,e,r)}})(),Vt(e)}()}(e,(e,t,r,n)=>{xr(e,t,r,n)})}function Er(e,t,r){return new Le(e.vertices.map(e=>[e.x+t,e.y+r]))}function Mr(e,t,r,n,i){const o=(t+n)/2,s=(r+i)/2,a=n-t,c=i-r,l=Math.hypot(a,c);if(!l)return null;const u=-c/l,h=a/l,f=(e.x-o)*u+(e.y-s)*h;return{x:o+u*f,y:s+h*f}}function Sr(e,t,r,n,i,o,s){let a=U(e,t,r,n),c=U(e,t,i,o);return((c-a)%360+360)%360>180&&([a,c]=[c,a]),[s(a),s(c)]}function Tr(e){const t=R(.35,.65),r=e.x1+(e.x2-e.x1)*t,n=e.y1+(e.y2-e.y1)*t,i=e.x2-e.x1,o=e.y2-e.y1,s=Math.hypot(i,o)||1,a=R(.04,.1)*s,c=i/s*a*.5,l=o/s*a*.5;return[{x1:e.x1,y1:e.y1,x2:r-c,y2:n-l},{x1:r+c,y1:n+l,x2:e.x2,y2:e.y2}]}function Pr(e,t,r){const n=function(e,t){const r=function(e){const t=e?.a??[];let r=Infinity,n=Infinity,i=-Infinity,o=-Infinity;for(const[e,s]of t)e<r&&(r=e),s<n&&(n=s),e>i&&(i=e),s>o&&(o=s);return{minX:r,minY:n,maxX:i,maxY:o,cx:(r+i)/2,cy:(n+o)/2,size:Math.hypot(i-r,o-n)}}(e),n=r.size*R(.6,1.4),[i,o]=t;return{x:r.cx+i*n,y:r.cy+o*n}}(e,t);for(const t of Rr(e)){const e=!t.isConnector&&R()<.35?Tr(t):[t];for(const t of e){const e=Mr(n,t.x1,t.y1,t.x2,t.y2);if(!e)continue;const i=O(e.x,e.y,t.x1,t.y1);if(!i)continue;const[o,s]=Sr(e.x,e.y,t.x1,t.y1,t.x2,t.y2,r);Ne(e.x,e.y,i,o,s)}}}function Cr(e,t,r,n,i,o){_r(t,r,n),Pr(e,i,o)}function kr(e,t,i,o){const s=function(e,t,r,n){const i=!1===t,o=Wt(me.mass.brush)?.scatter??0,s=i?e:e.genPol(t,r,n,.15),a=Math.min(2*o,5),c=[[R(-a,a),R(-a,a)],[R(-a,a),R(-a,a)]];return[s,Er(s,c[0][0],c[0][1]),Er(s,c[1][0],c[1][1])]}(e,t,i,o),a=vr(),c=Gt(),l={...me.field},u=me.mass.options?.precision??.5,h=me.mass.options?.strength??1,f=me.mass.options?.gradient??.1,d=me.mass.options?.outline??!1,m=Wt(me.mass.brush)?.scatter??0,x=1.6*R(.65*m,.85*m)-.4*f,g=R(-90,90),p=((g+90)%180+180)%180-90>=0?R()<.5?[1,1]:[-1,-1]:R()<.5?[-1,1]:[1,-1],y=r()?e=>e*Math.PI/180:e=>e;Kt(me.mass.brush,me.mass.color,1),Fe(2-u),d&&s[0].draw(),Cr(s[0],.9*x,n(g),{gradient:f,rand:2-2*u,continuous:!0},p,y),h>.33&&Cr(s[1],x,n(g+20*R(-1,1)),{gradient:f,rand:.6-.6*u,continuous:!0},p,y),h>.66&&Cr(s[2],.8*x,n(g+15*R(-1,1)),{gradient:f,rand:.6-.6*u,continuous:!0},p,y),Vt(c),br(a),me.field={...l}}function Fr(e,t,r){const n=2*Math.PI,i=ge.ctx,o=r/2;i.moveTo(e+o,t),i.arc(e,t,o,0,n)}me.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},Le.prototype.hatch=function(e=!1,t,r){let n=vr();e&&_r(e,t,r),me.hatch.isActive&&Ar(this),br(n)},De.prototype.hatch=function(e,t,r){vr().isActive&&(this.origin&&(e=this.origin[0],t=this.origin[1],r=1),this.pol=this.genPol(e,t,r,.3),this.pol.hatch())},me.mass={isActive:!1,brush:null,color:null,options:{}},Le.prototype.mass=function(){me.mass?.isActive&&kr(this,!1)},De.prototype.mass=function(e,t,r){me.mass?.isActive&&(this.origin&&(e=this.origin[0],t=this.origin[1],r=1),kr(this,e,t,r))};let Ir=null,Lr=!1;Lr||(ae={ensureResources:function(e,t,r,n,i){const o=Math.max(1,Math.round(t*n)),s=Math.max(1,Math.round(r*n));return function(e,t,r){return!e.mask||e.mask.width!==t||e.mask.height!==r}(e,o,s)&&(e.mask=ne(o,s)),function(e,t,r,n){return!e.fillMaskFramebuffer||e.fillMaskFramebuffer.width!==t||e.fillMaskFramebuffer.height!==r||"function"==typeof e.fillMaskFramebuffer.pixelDensity&&e.fillMaskFramebuffer.pixelDensity()!==n}(e,t,r,n)&&(e.fillMaskFramebuffer?.remove&&e.fillMaskFramebuffer.remove(),e.fillMaskFramebuffer=oe(e,{width:t,height:r,density:n,antialias:!1,depth:!1,stencil:!1}),i(e.fillMaskFramebuffer)),e.mask.dirtyRect??=null,e.mask.isDrawn??=!1,e.mask.drawingContext.imageSmoothingEnabled=!1,{mask:e.mask,ctx:e.mask.drawingContext}},clearMask:function(e,t){e&&(t(e),e.isDrawn=!1,e.dirtyRect=null)},getCompositeRect:function(e,t,r,n,i){return e?e.dirtyRect?i(n(e.dirtyRect,4)):r():null},getShaderMask:function(e,t,r,n,i){const o=e.fillMaskFramebuffer,s=e.drawingContext,a=r??n(),c=a.maxX-a.minX,l=a.maxY-a.minY;Ir&&Ir.width===c&&Ir.height===l||(Ir=ne(c,l));const u=Ir.drawingContext;return u.clearRect(0,0,c,l),u.drawImage(t,a.minX,a.minY,c,l,0,0,c,l),i(o),s.bindTexture(s.TEXTURE_2D,o.colorTexture),s.texSubImage2D(s.TEXTURE_2D,0,a.minX,a.minY,s.RGBA,s.UNSIGNED_BYTE,Ir),o}},Lr=!0);let Dr,Nr=[],Br=[],Yr=[],zr=[];me.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const Or=()=>({...me.fill});function Ur(e,t,r,n){me.fill.opacity=(arguments.length<4?t:n)||150,me.fill.color=arguments.length<3?i(e):i(e,t,r),me.fill.isActive=!0}function Xr(e,t="out"){me.fill.bleed_strength=P(e,0,1),me.fill.direction=t}function Zr(e=.4,t=.4){me.fill.texture_strength=P(e,0,1),me.fill.border_strength=P(t,0,1)}let Gr,Vr,Hr,Wr,$r;const jr=[[],[]];function qr(){for(let e=0;e<512;e++)jr[0][e]=S(.5,.2),jr[1][e]=S(0,.02)}p(qr);class Kr{constructor(e,t,r,n=[],i=!1,o,s){if(this.v=e,this.m=t,this.dir=n,this.midP=r,i){let t=0,n=0;const i=[];for(let o=0;o<e.length;o++){const s=Math.abs(r.x-e[o].x),a=Math.abs(r.y-e[o].y);t=Math.max(t,s),n=Math.max(n,a);const c=e[o],l=e[(o+1)%e.length],u={x:l.x-c.x,y:l.y-c.y},h=z(0,0,u.x,u.y,90),f={x:c.x+u.x/2,y:c.y+u.y/2};i.push({v1:c,v2:l,ray:{point1:f,point2:{x:f.x+h.x,y:f.y+h.y}}})}this.sizeX=t,this.sizeY=n;const o=Gr.sides;this.dir=Array(e.length);for(let e=0;e<i.length;e++){const t=i[e],r=t.ray.point1.x,n=t.ray.point1.y,s=t.ray.point2.x-r,a=t.ray.point2.y-n;let c=0;for(let e=0;e<o.length;e++){const i=o[e][0],l=o[e][1],u=l.x-i.x,h=l.y-i.y,f=h*s-u*a;if(0===f)continue;const d=(s*(n-i.y)-a*(r-i.x))/f;if(d<0||d>1)continue;const m=(u*(n-i.y)-h*(r-i.x))/f,x=r+m*s,g=n+m*a;(t.v2.x-t.v1.x)*(g-t.v1.y)-(t.v2.y-t.v1.y)*(x-t.v1.x)>.01&&c++}this.dir[e]=c%2==0}const s=w(-.6,.6)*t,a=w(-.6,.6)*n;this.midP={x:r.x+s,y:r.y+a}}else this.sizeX=o,this.sizeY=s}trim(e=1){if(e>=1||e<0||this.v.length<=8)return{v:this.v,m:this.m,dir:this.dir};const t=~~((1-e)*this.v.length),r=~~(this.v.length/2-t/2),n=this.v.length-t,i=new Array(n),o=new Array(n),s=new Array(n);let a=0;for(let e=0;e<r;e++,a++)i[a]=this.v[e],o[a]=this.m[e],s[a]=this.dir[e];for(let e=r+t;e<this.v.length;e++,a++)i[a]=this.v[e],o[a]=this.m[e],s[a]=this.dir[e];const c=r,l=r+t,u=this.v[(c-1+this.v.length)%this.v.length],h=this.v[l%this.v.length],f=h.x-u.x,d=h.y-u.y;for(let e=0;e<2;e++){const t=w(.25,.75),n={x:u.x+f*t,y:u.y+d*t},a=r+e;i.splice(a,0,n),o.splice(a,0,w(.4,.7)),s.splice(a,0,this.dir[c%this.dir.length])}return{v:i,m:o,dir:s}}scatter(e=.3){const t=this.v.length,r=Math.max(3,~~(t*e)),n=[],i=t/r;for(let e=0;e<r;e++)n.push(~~(e*i+w(0,.8*i)));const o=[],s=[],a=[],c=this.midP,l=Gr.sides;for(const e of n){const r=e%t;let n=this.v[r],i=!1;if(n.x<Vr||n.x>Wr||n.y<Hr||n.y>$r)i=!0;else{let e=0;for(const[t,r]of l){const i=t.y,o=r.y;if(i>n.y==o>n.y)continue;const s=(n.y-i)/(o-i);n.x<t.x+s*(r.x-t.x)&&e++}i=e%2==0}i&&(n={x:c.x+(n.x-c.x)*w(.3,.6),y:c.y+(n.y-c.y)*w(.3,.6)}),o.push(n),s.push(this.m[r]),a.push(!this.dir[r])}return new Kr(o,s,this.midP,a,!1,this.sizeX,this.sizeY)}flipDirs(){return new Kr(this.v,this.m,this.midP,this.dir.map(e=>!e),!1,this.sizeX,this.sizeY)}grow(e=1){const{v:t,m:r,dir:n}=this.trim(e),i=t.length,o=2*i;Nr.length<i&&(Nr=new Array(i),Br=new Array(i)),Yr.length<o&&(Yr=new Array(o),zr=new Array(o));const s=Nr,a=Br,c=Yr,l=zr,u="out"===me.fill.direction?-90:90;0===jr[0].length&&qr();const h=jr[0],f=h.length,d=jr[1],m=d.length;let x,g,p,y=0,v=0,b=999===e?w(.6,.8):me.fill.bleed_strength;for(let o=0;o<i;o++){const x=t[o],g=t[o+1<i?o+1:0],p=r[o],_=n[o];if(e<997&&(b=p),b<.05){c[y]=p,l[y]=_,y++,s[v]=(x.x+g.x)/2,a[v]=(x.y+g.y)/2,c[y]=p,l[y]=_,y++,v++;continue}const R=(_?u:-u)+5*w(-1,1),A=D(R),E=N(R),M=g.x-x.x,S=g.y-x.y,T=A*M+E*S,P=A*S-E*M,C=h[~~(w(0,1)*f)]*w(.65,1.35)*b,k=p+d[~~(w(0,1)*m)];c[y]=p,l[y]=_,y++,s[v]=x.x+.5*M+T*C,a[v]=x.y+.5*S+P*C,c[y]=k,l[y]=_,y++,v++}if(Dr&&y>Dr){const e=Math.ceil(y/Dr),r=Math.ceil(y/e);x=new Array(r),g=new Array(r),p=new Array(r);let n=0;for(let r=0;r<y;r+=e,n++)x[n]=r%2==0?t[r>>1]:{x:s[r>>1],y:a[r>>1]},g[n]=c[r],p[n]=l[r]}else{x=new Array(y);for(let e=0;e<y;e++)x[e]=e%2==0?t[e>>1]:{x:s[e>>1],y:a[e>>1]};g=c.slice(0,y),p=l.slice(0,y)}return new Kr(x,g,this.midP,p,!1,this.sizeX,this.sizeY)}fill(e,t,r){const n=3*r,i=2*t*(1+r/2),s=!1!==ge.isBrush;ge.isBrush=!1,s&&(ge.justChanged=!0),ge.blend(e);const a=o();ge.ctx.save(),ge.ctx.setTransform(W*a.a,W*a.b,W*a.c,W*a.d,W*(a.x+Z/2),W*(a.y+G/2));const c=`rgb(${e._getRed()} ${e._getGreen()} ${e._getBlue()} / `;ge.ctx.strokeStyle=c+.005*me.fill.border_strength+")",ge.ctx.lineCap="round",Dr=2024*Math.max(.1,2*me.fill.bleed_strength);const l=ge.ctx.getTransform(),u=Math.max(this.sizeX,this.sizeY),h=w(.15,.7);let f=this.grow();const d=this.scatter(.1).grow().scatter(.75).flipDirs();let m;for(let r=0;r<20;r++){r%4==0&&(f=f.grow()),r%2==0&&(m=[f.grow(1-.0125*r),f.grow(.7-.0125*r),f.grow(.4-.0125*r)]);for(const e of m)e.grow(999).grow(997).layer(r,u,i,c,l);d.grow(999).flipDirs().grow(997).layer(r,u,i*n,c,l),r%2==0&&f.grow(h).grow(999).layer(r,u,2*i,c,l),r%8!=0&&19!==r||(0!==n&&f.erase(3*n,t),ge.blend(e,!0))}ge.ctx.restore()}layer(e,t,r,n,i=null){ge.ctx.lineWidth=T(e,0,24,t/25,t/30,!0),ge.ctx.fillStyle=n+r+"%)",function(e,t=null){const r=ge.ctx;t||(t=r.getTransform());const n=t.a,i=t.b,o=t.c,s=t.d,a=t.e,c=t.f;let l=Infinity,u=Infinity,h=-Infinity,f=-Infinity;r.beginPath();const d=e[0];let m=n*d.x+o*d.y+a,x=i*d.x+s*d.y+c;l=h=m,u=f=x,r.moveTo(d.x,d.y);for(let t=1;t<e.length;t++){const d=e[t];m=n*d.x+o*d.y+a,x=i*d.x+s*d.y+c,l=Math.min(l,m),u=Math.min(u,x),h=Math.max(h,m),f=Math.max(f,x),r.lineTo(d.x,d.y)}r.closePath();const g=function(e,t){const r=e.lineWidth||0;return r<=0?1:1+r*Math.max(Math.hypot(t.a,t.c),Math.hypot(t.b,t.d))/2}(r,t);ge.markDirtyRect(ge.mask,{minX:l-g,minY:u-g,maxX:h+g,maxY:f+g})}(this.v,i),ge.ctx.fill(),ge.ctx.stroke()}erase(e,t){ge.ctx.save();const r=~~(w(80,110)*T(e,0,1,2,3.5)),n=this.sizeX/1.3,i=this.sizeY/1.3,o=1.3*Math.min(this.sizeX,this.sizeY),s=.03*o,a=.45*o,{x:c,y:l}=this.midP;ge.ctx.globalCompositeOperation="destination-out";const u=(5-T(t,80,100,.3,.7,!0))*e/255;ge.ctx.fillStyle=`rgb(255 0 0 / ${u})`,ge.ctx.lineWidth=0;for(let e=0;e<r;e++){const t=c+S(0,n),r=l+S(0,i),o=w(s,a);ge.ctx.beginPath(),Fr(t,r,o),e%5!=0&&ge.ctx.fill()}ge.ctx.globalCompositeOperation="source-over",ge.ctx.restore()}}function Jr(e,t){if(!e)return e;t||(t=e);let r,n=e;do{if(r=!1,n.steiner||!ln(n,n.next)&&0!==cn(n.prev,n,n.next))n=n.next;else{if(gn(n),n=t=n.prev,n===n.next)break;r=!0}}while(r||n!==t);return t}function Qr(e,t,r,n,i,o,s){if(!e)return;!s&&o&&function(e,t,r,n){let i=e;do{0===i.z&&(i.z=on(i.x,i.y,t,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==e);i.prevZ.nextZ=null,i.prevZ=null,function(e){let t,r=1;do{let n,i=e;e=null;let o=null;for(t=0;i;){t++;let s=i,a=0;for(let e=0;e<r&&(a++,s=s.nextZ,s);e++);let c=r;for(;a>0||c>0&&s;)0!==a&&(0===c||!s||i.z<=s.z)?(n=i,i=i.nextZ,a--):(n=s,s=s.nextZ,c--),o?o.nextZ=n:e=n,n.prevZ=o,o=n;i=s}o.nextZ=null,r*=2}while(t>1)}(i)}(e,n,i,o);let a=e;for(;e.prev!==e.next;){const c=e.prev,l=e.next;if(o?tn(e,n,i,o):en(e))t.push(c.i,e.i,l.i),gn(e),e=l.next,a=l.next;else if((e=l)===a){s?1===s?Qr(e=rn(Jr(e),t),t,r,n,i,o,2):2===s&&nn(e,t,r,n,i,o):Qr(Jr(e),t,r,n,i,o,1);break}}}function en(e){const t=e.prev,r=e,n=e.next;if(cn(t,r,n)>=0)return!1;const i=t.x,o=r.x,s=n.x,a=t.y,c=r.y,l=n.y,u=Math.min(i,o,s),h=Math.min(a,c,l),f=Math.max(i,o,s),d=Math.max(a,c,l);let m=n.next;for(;m!==t;){if(m.x>=u&&m.x<=f&&m.y>=h&&m.y<=d&&sn(i,a,o,c,s,l,m.x,m.y)&&cn(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function tn(e,t,r,n){const i=e.prev,o=e,s=e.next;if(cn(i,o,s)>=0)return!1;const a=i.x,c=o.x,l=s.x,u=i.y,h=o.y,f=s.y,d=Math.min(a,c,l),m=Math.min(u,h,f),x=Math.max(a,c,l),g=Math.max(u,h,f),p=on(d,m,t,r,n),y=on(x,g,t,r,n);let v=e.prevZ,b=e.nextZ;for(;v&&v.z>=p&&b&&b.z<=y;){if(v.x>=d&&v.x<=x&&v.y>=m&&v.y<=g&&v!==i&&v!==s&&sn(a,u,c,h,l,f,v.x,v.y)&&cn(v.prev,v,v.next)>=0)return!1;if(v=v.prevZ,b.x>=d&&b.x<=x&&b.y>=m&&b.y<=g&&b!==i&&b!==s&&sn(a,u,c,h,l,f,b.x,b.y)&&cn(b.prev,b,b.next)>=0)return!1;b=b.nextZ}for(;v&&v.z>=p;){if(v.x>=d&&v.x<=x&&v.y>=m&&v.y<=g&&v!==i&&v!==s&&sn(a,u,c,h,l,f,v.x,v.y)&&cn(v.prev,v,v.next)>=0)return!1;v=v.prevZ}for(;b&&b.z<=y;){if(b.x>=d&&b.x<=x&&b.y>=m&&b.y<=g&&b!==i&&b!==s&&sn(a,u,c,h,l,f,b.x,b.y)&&cn(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function rn(e,t){let r=e;do{const n=r.prev,i=r.next.next;!ln(n,i)&&un(n,r,r.next,i)&&dn(n,i)&&dn(i,n)&&(t.push(n.i,r.i,i.i),gn(r),gn(r.next),r=e=i),r=r.next}while(r!==e);return Jr(r)}function nn(e,t,r,n,i,o){let s=e;do{let e=s.next.next;for(;e!==s.prev;){if(s.i!==e.i&&an(s,e)){let a=mn(s,e);return s=Jr(s,s.next),a=Jr(a,a.next),Qr(s,t,r,n,i,o,0),void Qr(a,t,r,n,i,o,0)}e=e.next}s=s.next}while(s!==e)}function on(e,t,r,n,i){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-r)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-n)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function sn(e,t,r,n,i,o,s,a){return!(e===s&&t===a)&&function(e,t,r,n,i,o,s,a){return(i-s)*(t-a)>=(e-s)*(o-a)&&(e-s)*(n-a)>=(r-s)*(t-a)&&(r-s)*(o-a)>=(i-s)*(n-a)}(e,t,r,n,i,o,s,a)}function an(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){let r=e;do{if(r.i!==e.i&&r.next.i!==e.i&&r.i!==t.i&&r.next.i!==t.i&&un(r,r.next,e,t))return!0;r=r.next}while(r!==e);return!1}(e,t)&&(dn(e,t)&&dn(t,e)&&function(e,t){let r=e,n=!1;const i=(e.x+t.x)/2,o=(e.y+t.y)/2;do{r.y>o!=r.next.y>o&&r.next.y!==r.y&&i<(r.next.x-r.x)*(o-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==e);return n}(e,t)&&(cn(e.prev,e,t.prev)||cn(e,t.prev,t))||ln(e,t)&&cn(e.prev,e,e.next)>0&&cn(t.prev,t,t.next)>0)}function cn(e,t,r){return(t.y-e.y)*(r.x-t.x)-(t.x-e.x)*(r.y-t.y)}function ln(e,t){return e.x===t.x&&e.y===t.y}function un(e,t,r,n){const i=fn(cn(e,t,r)),o=fn(cn(e,t,n)),s=fn(cn(r,n,e)),a=fn(cn(r,n,t));return i!==o&&s!==a||!(0!==i||!hn(e,r,t))||!(0!==o||!hn(e,n,t))||!(0!==s||!hn(r,e,n))||!(0!==a||!hn(r,t,n))}function hn(e,t,r){return t.x<=Math.max(e.x,r.x)&&t.x>=Math.min(e.x,r.x)&&t.y<=Math.max(e.y,r.y)&&t.y>=Math.min(e.y,r.y)}function fn(e){return e>0?1:e<0?-1:0}function dn(e,t){return cn(e.prev,e,e.next)<0?cn(e,t,e.next)>=0&&cn(e,e.prev,t)>=0:cn(e,t,e.prev)<0||cn(e,e.next,t)<0}function mn(e,t){const r=pn(e.i,e.x,e.y),n=pn(t.i,t.x,t.y),i=e.next,o=t.prev;return e.next=t,t.prev=e,r.next=i,i.prev=r,n.next=r,r.prev=n,o.next=n,n.prev=o,n}function xn(e,t,r,n){const i=pn(e,t,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function gn(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function pn(e,t,r){return{i:e,x:t,y:r,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}Le.prototype.fill=function(e=!1,t,r,n,i,o){let s=Or();e&&(Ur(e,t),Xr(r,o),Zr(n,i)),s.isActive&&(ve(),function(e){if(!me.fill.isActive||!me.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");Gr=e,Vr=Infinity,Hr=Infinity,Wr=-Infinity,$r=-Infinity;for(const[t]of e.sides)t.x<Vr&&(Vr=t.x),t.x>Wr&&(Wr=t.x),t.y<Hr&&(Hr=t.y),t.y>$r&&($r=t.y);const t=[...e.vertices],r=w(0,75),n=~~(.25*t.length*(r<5?1:r<15?2:3)),i=me.fill.bleed_strength,o=t.map((e,t)=>(t>n?1:.3)*w(.85,1.4)*i),s=E(0,t.length),a=t.length,c=new Array(a);for(let e=0;e<a;e++)c[e]=t[(e+s)%a];const l=function(e){if(0===e.length)return{x:0,y:0};if(e.length<8){let t=0,r=0;for(const n of e)t+=n.x,r+=n.y;return{x:t/e.length,y:r/e.length}}const t=[...e];t[0].x===t[t.length-1].x&&t[0].y===t[t.length-1].y||t.push(t[0]);let r=0,n=0,i=0;for(let e=0;e<t.length-1;e++){const o=t[e].x*t[e+1].y-t[e+1].x*t[e].y;r+=o,n+=(t[e].x+t[e+1].x)*o,i+=(t[e].y+t[e+1].y)*o}return r*=.5,r?{x:n/(6*r),y:i/(6*r)}:{x:t[0].x,y:t[0].y}}(c);new Kr(c,o,l,[],!0).fill(me.fill.color,T(me.fill.opacity,0,255,0,1,!0),me.fill.texture_strength)}(this)),(e=>{me.fill={...e}})(s)},De.prototype.fill=function(e,t,r){Or().isActive&&(this.origin&&(e=this.origin[0],t=this.origin[1],r=1),this.pol=this.genPol(e,t,r,me.fill.bleed_strength<.06?0:T(me.fill.bleed_strength,0,.6,.2,.6,!0)),this.pol.fill())};let yn=null,vn=null,bn=null,_n=null,wn=null,Rn=0,An=0,En=0;const Mn={},Sn={};function Tn(e,t,r,n){q(),me.wash.opacity=(arguments.length<4?t:n)??150,me.wash.color=arguments.length<3?i(e):i(e,t,r),me.wash.isActive=!0}function Pn(e,t){const r=o();return[r.a*e+r.c*t+r.x+Rn/2,r.b*e+r.d*t+r.y+An/2]}me.wash={color:null,opacity:150,isActive:!1},Le.prototype.wash=function(e=!1,t){const r={...me.wash};!1!==e&&Tn(e,t),me.wash.isActive&&function(e){if(!me.wash?.isActive||!me.wash.color||e.vertices.length<3)return;pe(),function(){const e=H.drawingContext;wn&&!(Rn!==Z||An!==G)||(Rn=Z,An=G,wn=new Float32Array([2/Rn,0,0,0,0,-2/An,0,0,0,0,1,0,-1,1,0,1])),yn===e&&vn&&bn&&_n||(yn=e,vn=$e(yn,"#version 300 es\nin vec2 a_position;\nuniform mat4 u_matrix;\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n}","#version 300 es\nprecision highp float;\nuniform vec4 u_color;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(u_color.rgb * u_color.a, u_color.a);\n}"),Mn.a_position=yn.getAttribLocation(vn,"a_position"),Sn.u_matrix=yn.getUniformLocation(vn,"u_matrix"),Sn.u_color=yn.getUniformLocation(vn,"u_color"),bn=yn.createVertexArray(),yn.bindVertexArray(bn),_n=yn.createBuffer(),yn.bindBuffer(yn.ARRAY_BUFFER,_n),yn.bufferData(yn.ARRAY_BUFFER,0,yn.DYNAMIC_DRAW),En=0,yn.enableVertexAttribArray(Mn.a_position),yn.vertexAttribPointer(Mn.a_position,2,yn.FLOAT,!1,8,0),yn.bindVertexArray(null),yn.bindBuffer(yn.ARRAY_BUFFER,null))}();const{triangles:t,vertexCount:r}=function(e){const t=new Float32Array(2*e.vertices.length);for(let r=0;r<e.vertices.length;r++){const n=e.vertices[r];t[2*r]=n.x,t[2*r+1]=n.y}const r=function(e,t,r=2){const n=e.length;let i=function(e,t,r,n){let i;if(1==function(e,t,r,n){let i=0;for(let t=0,o=r-n;t<r;t+=n)i+=(e[o]-e[t])*(e[t+1]+e[o+1]),o=t;return i}(e,0,r,n)>0)for(let t=0;t<r;t+=n)i=xn(t/n|0,e[t],e[t+1],i);else for(let t=r-n;t>=0;t-=n)i=xn(t/n|0,e[t],e[t+1],i);return i&&ln(i,i.next)&&(gn(i),i=i.next),i}(e,0,n,r);const o=[];if(!i||i.next===i.prev)return o;let s,a,c;if(e.length>80*r){s=e[0],a=e[1];let t=s,i=a;for(let o=r;o<n;o+=r){const r=e[o],n=e[o+1];r<s&&(s=r),n<a&&(a=n),r>t&&(t=r),n>i&&(i=n)}c=Math.max(t-s,i-a),c=0!==c?32767/c:0}return Qr(i,o,r,s,a,c,0),o}(t),n=new Float32Array(2*r.length);for(let e=0;e<r.length;e++){const i=r[e],[o,s]=Pn(t[2*i],t[2*i+1]);n[2*e]=o,n[2*e+1]=s}return{triangles:n,vertexCount:r.length}}(e),n=t.byteLength;yn.useProgram(vn),yn.enable(yn.BLEND),yn.blendEquation(yn.FUNC_ADD),yn.blendFunc(yn.ONE,yn.ONE_MINUS_SRC_ALPHA),yn.bindVertexArray(bn),yn.bindBuffer(yn.ARRAY_BUFFER,_n),n>En?(yn.bufferData(yn.ARRAY_BUFFER,t,yn.DYNAMIC_DRAW),En=n):yn.bufferSubData(yn.ARRAY_BUFFER,0,t);const i=me.wash.color._array;yn.uniformMatrix4fv(Sn.u_matrix,!1,wn),yn.uniform4f(Sn.u_color,i[0],i[1],i[2],me.wash.opacity/255),yn.drawArrays(yn.TRIANGLES,0,r),yn.bindVertexArray(null),yn.bindBuffer(yn.ARRAY_BUFFER,null),qe(H,yn)}(this),me.wash={...r}},De.prototype.wash=function(e,t,r){me.wash?.isActive&&(this.origin&&(e=this.origin[0],t=this.origin[1],r=1),this.pol=this.genPol(e,t,r,0,-1),this.pol.wash())};let Cn=null,kn=null;const Fn=[];let In=!1;const Ln=e=>!!e&&"function"==typeof e.begin&&"function"==typeof e.end&&!!e.renderer&&!!e.renderer._pInst,Dn=e=>"number"==typeof e&&Number.isFinite(e)&&e>0,Nn=e=>{try{return e()}catch(e){return}},Bn=e=>!!e&&"function"==typeof e.pixelDensity&&"function"==typeof e.createFramebuffer&&Dn(Nn(()=>e.width))&&Dn(Nn(()=>e.height))&&"webgl2"===Nn(()=>e.webglVersion),Yn=e=>(Bn(e)&&(Cn=e),Cn),zn=()=>(kn&&Bn(kn)?Yn(kn):null)||Yn(window.self?.p5?.instance??null)||Yn(V)||Cn,On=(e=!1)=>{const t=((e=!1)=>{const t=zn();if(!e){if(!t)throw new Error("p5.brush could not resolve an active WEBGL sketch. Call brush.instance(p) and brush.load() after createCanvas(..., WEBGL).");return{renderer:t,width:t.width,height:t.height}}if(Ln(e)){const r=e.renderer._pInst;if(Yn(r),t&&r!==t)throw new Error("p5.brush only supports p5.Framebuffer targets created from the active sketch");return{renderer:r,width:e.width,height:e.height}}return{renderer:e,width:e.width,height:e.height}})(e);if(j({Renderer:t.renderer}),Yn(e?zn():H),"webgl2"!==H.webglVersion)throw new Error("p5.brush requires a WEBGL canvas");j({Cwidth:t.width,Cheight:t.height}),In=!0},Un=e=>{j({Instance:e}),Yn(e)},Xn=()=>H??zn?.()??window.self?.p5?.instance??null,Zn={a:1,b:0,c:0,d:1,x:0,y:0},Gn={a:1,b:0,c:0,d:1,x:0,y:0};function Vn(){const e=Xn();return!!e&&"function"==typeof e.angleMode&&e.angleMode()===e.RADIANS}function Hn(e,t,r){const n=t.isEnabled(t.DEPTH_TEST);n&&t.disable(t.DEPTH_TEST);const i=e._renderer.activeFramebuffer?.()??null;return i?._beforeEnd&&i._beforeEnd(),t.bindFramebuffer(t.FRAMEBUFFER,function(e){return e?"function"==typeof e._framebufferToBind?e._framebufferToBind():e.framebuffer??null:null}(r)),t.viewport(0,0,r.width*r.density,r.height*r.density),{hadDepthTest:n,previousTarget:i}}function Wn(e,t,r){r?.hadDepthTest&&t.enable(t.DEPTH_TEST),r?.previousTarget?._beforeBegin?r.previousTarget._beforeBegin():(t.bindFramebuffer(t.FRAMEBUFFER,null),e._renderer.viewport(e._renderer._origViewport.width,e._renderer._origViewport.height),e._renderer._applyStencilTestIfClipping?.())}function $n(e,t){const r=e?._renderer;r&&(r._curShader=null,r._cachedBlendMode=null,r._isBlending=null,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,null),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA))}function jn(e,t,r){if(!t)return;if(r(t))return void t.draw(()=>e.clear());const n=t.drawingContext;n.save(),n.setTransform(1,0,0,1,0,0),n.clearRect(0,0,t.width,t.height),n.restore()}function qn(e,t,r){return e.loaded||(e.loaded=!0,e.shaderProgram??=e.createShader(t,r)),e.shaderProgram}function Kn(e,t,r,n,i){return t?.remove&&t.remove(),e.createFramebuffer({width:r,height:n,density:i,antialias:!1,depth:!1,stencil:!1})}const Jn=(e,t)=>e.createFramebuffer(t);function Qn({renderer:e,shader:t,source:r,mask:n,color:i,isBrushMask:o,Cwidth:s,Cheight:a,dirtyRect:c,targetIsFramebuffer:l,withScissor:u}){const h=e.drawingContext,f=h.isEnabled(h.DEPTH_TEST);h.disable(h.DEPTH_TEST),e.push(),e.translate(0,0),e.shader(t),t.setUniform("u_source",r),t.setUniform("u_targetIsFramebuffer",l),t.setUniform("u_isBrush",o),t.setUniform("u_mask",n),t.setUniform("u_color",i),u(h,c,()=>{e.fill(0,0,0,0),e.noStroke(),e.rect(-s/2,-a/2,s,a)},!l),e.pop(),e.resetShader(),f&&h.enable(h.DEPTH_TEST)}function ei(e){return e.isFramebufferTarget(e.sourceTarget)?((e.sourceTarget.renderer??e.renderer)._renderer?.flushDraw?.(),e.sourceFramebuffer.draw(()=>{e.withScissor(e.renderer.drawingContext,e.dirtyRect,()=>{e.renderer.clear(),e.renderer.push(),e.renderer.imageMode(e.renderer.CENTER),e.renderer.image(e.sourceTarget,0,0,e.Cwidth,e.Cheight),e.renderer.pop()},!1)}),e.sourceFramebuffer):(e.renderer._renderer?.flushDraw?.(),function({renderer:e,sourceFramebuffer:t,dirtyRect:r,getTargetPixelSize:n,toScissorBox:i}){const o=e.drawingContext,{width:s,height:a}=n(),c=r?i(r):null,l=o.getParameter(o.READ_FRAMEBUFFER_BINDING),u=o.getParameter(o.DRAW_FRAMEBUFFER_BINDING);return o.bindFramebuffer(o.READ_FRAMEBUFFER,null),o.bindFramebuffer(o.DRAW_FRAMEBUFFER,t.framebuffer),o.blitFramebuffer(c?.x??0,c?.y??0,c?c.x+c.width:s,c?c.y+c.height:a,c?.x??0,c?.y??0,c?c.x+c.width:s,c?c.y+c.height:a,o.COLOR_BUFFER_BIT,o.NEAREST),o.bindFramebuffer(o.READ_FRAMEBUFFER,l),o.bindFramebuffer(o.DRAW_FRAMEBUFFER,u),t}(e))}const ti=()=>H??V??window.self?.p5?.instance;function ri(e,t){const r=ti();if(!r?.createGraphics)throw new Error("p5 stroke tip creation requires an active renderer or instance.");return r.createGraphics(e,t)}function ni(e,t){return new Promise((r,n)=>{const i=new window.Image;i.onload=()=>{const e=ti();if(!e?.createImage)return void n(new Error("p5 image tip loading requires an active renderer or instance."));const o=e.createImage(i.naturalWidth,i.naturalHeight);o.drawingContext.drawImage(i,0,0),t(o),r(o)},i.onerror=()=>n(new Error(`Failed to load image tip: ${e}`)),i.crossOrigin="anonymous",i.src=e})}const ii=[];var oi;oi={load:On,syncDensity:()=>{const e=H.pixelDensity();return j({Density:e}),e},isCanvasReady:()=>{In||On()},instance:Un,activateInstance:e=>{Fn.push(kn),kn=e,Un(e)},deactivateInstance:()=>{kn=Fn.pop()??null},getActiveFramebuffer:()=>H?._renderer?.activeFramebuffer?.()??null,isFramebufferTarget:Ln},$={...$,...oi},function(){var e;(e={usesRadians:Vn,fromDegrees:e=>Vn()?e*Math.PI/180:e,createColor:(...e)=>{const t=Xn();if(!t?.color)throw new Error("p5 runtime color creation requires an active renderer.");return t.color(...e)},getAffineMatrix:()=>{const e=Xn(),t=e?._renderer?.uModelMatrix?.mat4;return t?(Gn.a=t[0],Gn.b=t[1],Gn.c=t[4],Gn.d=t[5],Gn.x=t[12],Gn.y=t[13],Gn):Zn}}).usesRadians&&(r=e.usesRadians),e.fromDegrees&&(n=e.fromDegrees),e.createColor&&(i=e.createColor),e.getAffineMatrix&&(o=e.getAffineMatrix)}(),function(){var e;e={beginDirectMaskDraw:Hn,endDirectMaskDraw:Wn,resetDirectShaderTracking:$n},je={...je,...e}}(),function(){var e;e={clearTarget:jn,ensureBlendShaderProgram:qn,ensureBlendSourceFramebuffer:Kn,createFramebuffer:Jn,runBlendShaderPass:Qn,blitSourceToFramebuffer:ei},ie={...ie,...e}}(),function(){var e;e={createTipSurface:ri,loadImageTip:ni},He={...He,...e}}(),"undefined"!=typeof p5&&p5.registerAddon(function(e,t,r){r.presetup=function(){J(this)},r.predraw=function(){J(this)},r.postsetup=function(){K(this),pe(),Q()},r.postdraw=function(){K(this),pe(),Q()};const n=t.push,i=t.pop,o=t.randomSeed,s=t.noiseSeed;t.push=function(){n.call(this),ve(),ii.push({fill:{...me.fill},wash:me.wash?{...me.wash}:null,stroke:{...me.stroke},hatch:{...me.hatch},mass:me.mass?{...me.mass}:null,field:{...me.field}})},t.pop=function(){i.call(this),function(){const e=ii.pop();e&&(me.stroke={...e.stroke},me.field={...e.field},me.hatch={...e.hatch},me.fill={...e.fill},e.wash&&(me.wash={...e.wash}),e.mass?me.mass={...e.mass}:me.mass&&(me.mass={...me.mass,isActive:!1,brush:null,color:null,options:{}}))}()},t.randomSeed=function(e){o.call(this,e),y(e)},t.noiseSeed=function(e){s.call(this,e),_(e)}}),e.Plot=De,e.Polygon=Le,e.Position=be,e.add=Ht,e.addField=ke,e.arc=Ne,e.beginShape=Xe,e.beginStroke=function(e,t,r){if("curve"!==e&&"segments"!==e)throw new Error(`beginStroke() type must be "curve" or "segments", got "${e}".`);Oe=[t,r],ze=new De(e)},e.box=function(){return[...Xt.keys()]},e.circle=function(e,t,r,n=!1){const i=new De("curve"),o=Math.PI*r,s=R(0,360),a=n?()=>1+.2*n*R():()=>1;for(let e=0;e<4;e++){const t=-90*e+s;i.addSegment(t*a(),o/2*a(),1,!0)}if(n){const e=n*M(-5,5);i.addSegment(s,Math.abs(e)*(Math.PI/180)*r,1,!0),i.endPlot(e+s,1,!0)}else i.endPlot(s,1,!0);const c=e-r*N(s),l=t-r*D(-s);i.show(c,l,1)},e.clip=function(e){return q(),e},e.endShape=Ge,e.endStroke=function(e,t){if(!ze)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");ze.endPlot(e,t),ze.draw(Oe[0],Oe[1],1),ze=!1},e.field=Ce,e.fill=Ur,e.fillBleed=Xr,e.fillTexture=Zr,e.flowLine=function(e,t,r,n){if(!me.stroke.isActive||!me.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");ve(),ir(e,t,r),sr(B(n),!1)},e.hatch=_r,e.hatchArray=Ar,e.hatchStyle=function(e,t="black",r=1){me.hatch.hBrush={brush:e,color:t,weight:r}},e.instance=K,e.line=xr,e.listFields=function(){return ve(),Array.from(Me.keys())},e.load=(e=!1)=>{((e=!1)=>{$.load(e)})(e),H.loaded&&ge.load()},e.mass=function(e,t,r={}){me.mass.brush=e,me.mass.color=t,me.mass.options=r,me.mass.isActive=!0},e.move=function(e,t,r){if(!ze)throw new Error("move() called without beginStroke(). Call beginStroke() first.");ze.addSegment(e,t,r)},e.noClip=function(){},e.noField=function(){ve(),me.field.isActive=!1},e.noFill=function(){me.fill.isActive=!1},e.noHatch=function(){me.hatch.isActive=!1,me.hatch.hBrush=!1},e.noMass=function(){me.mass.isActive=!1,me.mass.brush=null,me.mass.color=null,me.mass.options={}},e.noStroke=function(){me.stroke.isActive=!1},e.noWash=function(){me.wash.isActive=!1},e.noiseSeed=_,e.pick=$t,e.polygon=function(e){new Le(e).show()},e.rect=function(e,t,r,n,i="corner"){"center"===i&&(e-=r/2,t-=n/2),Xe(0),Ze(e,t),Ze(e+r,t),Ze(e+r,t+n),Ze(e,t+n),Ge(!0)},e.refreshField=function(e=0){if(!me.field.isActive||!me.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const t=Me.get(me.field.current);t.field=Pe(t,e)},e.scaleBrushes=function(e){for(const{param:t}of Xt.values())t&&(t.weight*=e,t.scatter*=e,t.spacing*=e)},e.seed=y,e.set=Kt,e.spline=function(e,t=.5){if(!e||e.length<2)throw new Error("spline() requires at least 2 points. Each point should be [x, y, pressure].");Ve(e,t).draw()},e.stroke=jt,e.strokeWeight=qt,e.vertex=Ze,e.wRand=e=>{let t=0;const r=[];for(const n in e)t+=e[n],r.push({key:n,cumulative:t});const n=m()*t;for(const{key:e,cumulative:t}of r)if(n<t)return isNaN(e)?e:parseInt(e)},e.wash=Tn,e.wiggle=Fe},"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).brush={});
//# sourceMappingURL=p5.brush.js.map
diff --git a/dist/p5.brush.js.map b/dist/p5.brush.js.map
index 276d965..02dde1f 100644
--- a/dist/p5.brush.js.map
+++ b/dist/p5.brush.js.map
@@ -1 +1 @@
-{"version":3,"file":"p5.brush.js","sources":["../src/core/runtime.js","../node_modules/simplex-noise/dist/esm/simplex-noise.js","../node_modules/esm-seedrandom/esm/index.mjs","../src/core/utils.js","../src/core/target.js","../src/core/dirty_rect.js","../src/core/compositor_runtime.js","../src/core/color.js","../src/core/flowfield.js","../src/core/polygon.js","../src/core/plot.js","../src/core/primitives.js","../src/stroke/runtime.js","../src/stroke/composite.js","../src/core/gl/utils.js","../src/core/renderer_runtime.js","../src/stroke/gl_draw.js","../src/stroke/stroke.js","../src/hatch/hatch.js","../src/hatch/mass.js","../src/fill/mask.js","../src/fill/composite.js","../src/fill/fill.js","../node_modules/earcut/src/earcut.js","../src/fill/wash.js","../src/adapters/p5/target.js","../src/adapters/p5/runtime.js","../src/adapters/p5/renderer.js","../src/adapters/p5/compositor.js","../src/adapters/p5/stroke.js","../src/core/save.js","../src/index.p5.js","../src/adapters/p5/addon.js"],"sourcesContent":["// =============================================================================\n// Runtime Hooks\n// =============================================================================\n\nconst identityMatrix = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\n\nexport let usesRadians = () => false;\nexport let fromDegrees = (angle) => angle;\nexport let createColor = () => {\n throw new Error(\"No runtime color adapter registered.\");\n};\nexport let getAffineMatrix = () => identityMatrix;\n\n/**\n * Registers or updates host-runtime hooks used by core modules.\n *\n * @param {object} hooks\n */\nexport function setRuntime(hooks) {\n if (hooks.usesRadians) usesRadians = hooks.usesRadians;\n if (hooks.fromDegrees) fromDegrees = hooks.fromDegrees;\n if (hooks.createColor) createColor = hooks.createColor;\n if (hooks.getAffineMatrix) getAffineMatrix = hooks.getAffineMatrix;\n}\n","/*\n * A fast javascript implementation of simplex noise by Jonas Wagner\n\nBased on a speed-improved simplex noise algorithm for 2D, 3D and 4D in Java.\nWhich is based on example code by Stefan Gustavson ([email protected]).\nWith Optimisations by Peter Eastman ([email protected]).\nBetter rank ordering method by Stefan Gustavson in 2012.\n\n Copyright (c) 2024 Jonas Wagner\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n */\n// these __PURE__ comments help uglifyjs with dead code removal\n//\nconst SQRT3 = /*#__PURE__*/ Math.sqrt(3.0);\nconst SQRT5 = /*#__PURE__*/ Math.sqrt(5.0);\nconst F2 = 0.5 * (SQRT3 - 1.0);\nconst G2 = (3.0 - SQRT3) / 6.0;\nconst F3 = 1.0 / 3.0;\nconst G3 = 1.0 / 6.0;\nconst F4 = (SQRT5 - 1.0) / 4.0;\nconst G4 = (5.0 - SQRT5) / 20.0;\n// I'm really not sure why this | 0 (basically a coercion to int)\n// is making this faster but I get ~5 million ops/sec more on the\n// benchmarks across the board or a ~10% speedup.\nconst fastFloor = (x) => Math.floor(x) | 0;\nconst grad2 = /*#__PURE__*/ new Float64Array([1, 1,\n -1, 1,\n 1, -1,\n -1, -1,\n 1, 0,\n -1, 0,\n 1, 0,\n -1, 0,\n 0, 1,\n 0, -1,\n 0, 1,\n 0, -1]);\n// double seems to be faster than single or int's\n// probably because most operations are in double precision\nconst grad3 = /*#__PURE__*/ new Float64Array([1, 1, 0,\n -1, 1, 0,\n 1, -1, 0,\n -1, -1, 0,\n 1, 0, 1,\n -1, 0, 1,\n 1, 0, -1,\n -1, 0, -1,\n 0, 1, 1,\n 0, -1, 1,\n 0, 1, -1,\n 0, -1, -1]);\n// double is a bit quicker here as well\nconst grad4 = /*#__PURE__*/ new Float64Array([0, 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1,\n 0, -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1,\n 1, 0, 1, 1, 1, 0, 1, -1, 1, 0, -1, 1, 1, 0, -1, -1,\n -1, 0, 1, 1, -1, 0, 1, -1, -1, 0, -1, 1, -1, 0, -1, -1,\n 1, 1, 0, 1, 1, 1, 0, -1, 1, -1, 0, 1, 1, -1, 0, -1,\n -1, 1, 0, 1, -1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, -1,\n 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1, 0,\n -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1, 0]);\n/**\n * Creates a 2D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction2D}\n */\nexport function createNoise2D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating this yields a little ~3% performance improvement.\n const permGrad2x = new Float64Array(perm).map(v => grad2[(v % 12) * 2]);\n const permGrad2y = new Float64Array(perm).map(v => grad2[(v % 12) * 2 + 1]);\n return function noise2D(x, y) {\n // if(!isFinite(x) || !isFinite(y)) return 0;\n let n0 = 0; // Noise contributions from the three corners\n let n1 = 0;\n let n2 = 0;\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y) * F2; // Hairy factor for 2D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const t = (i + j) * G2;\n const X0 = i - t; // Unskew the cell origin back to (x,y) space\n const Y0 = j - t;\n const x0 = x - X0; // The x,y distances from the cell origin\n const y0 = y - Y0;\n // For the 2D case, the simplex shape is an equilateral triangle.\n // Determine which simplex we are in.\n let i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords\n if (x0 > y0) {\n i1 = 1;\n j1 = 0;\n } // lower triangle, XY order: (0,0)->(1,0)->(1,1)\n else {\n i1 = 0;\n j1 = 1;\n } // upper triangle, YX order: (0,0)->(0,1)->(1,1)\n // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and\n // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where\n // c = (3-sqrt(3))/6\n const x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords\n const y1 = y0 - j1 + G2;\n const x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords\n const y2 = y0 - 1.0 + 2.0 * G2;\n // Work out the hashed gradient indices of the three simplex corners\n const ii = i & 255;\n const jj = j & 255;\n // Calculate the contribution from the three corners\n let t0 = 0.5 - x0 * x0 - y0 * y0;\n if (t0 >= 0) {\n const gi0 = ii + perm[jj];\n const g0x = permGrad2x[gi0];\n const g0y = permGrad2y[gi0];\n t0 *= t0;\n // n0 = t0 * t0 * (grad2[gi0] * x0 + grad2[gi0 + 1] * y0); // (x,y) of grad3 used for 2D gradient\n n0 = t0 * t0 * (g0x * x0 + g0y * y0);\n }\n let t1 = 0.5 - x1 * x1 - y1 * y1;\n if (t1 >= 0) {\n const gi1 = ii + i1 + perm[jj + j1];\n const g1x = permGrad2x[gi1];\n const g1y = permGrad2y[gi1];\n t1 *= t1;\n // n1 = t1 * t1 * (grad2[gi1] * x1 + grad2[gi1 + 1] * y1);\n n1 = t1 * t1 * (g1x * x1 + g1y * y1);\n }\n let t2 = 0.5 - x2 * x2 - y2 * y2;\n if (t2 >= 0) {\n const gi2 = ii + 1 + perm[jj + 1];\n const g2x = permGrad2x[gi2];\n const g2y = permGrad2y[gi2];\n t2 *= t2;\n // n2 = t2 * t2 * (grad2[gi2] * x2 + grad2[gi2 + 1] * y2);\n n2 = t2 * t2 * (g2x * x2 + g2y * y2);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to return values in the interval [-1,1].\n return 70.0 * (n0 + n1 + n2);\n };\n}\n/**\n * Creates a 3D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction3D}\n */\nexport function createNoise3D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these seems to yield a speedup of over 15%\n const permGrad3x = new Float64Array(perm).map(v => grad3[(v % 12) * 3]);\n const permGrad3y = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 1]);\n const permGrad3z = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 2]);\n return function noise3D(x, y, z) {\n let n0, n1, n2, n3; // Noise contributions from the four corners\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y + z) * F3; // Very nice and simple skew factor for 3D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const t = (i + j + k) * G3;\n const X0 = i - t; // Unskew the cell origin back to (x,y,z) space\n const Y0 = j - t;\n const Z0 = k - t;\n const x0 = x - X0; // The x,y,z distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n // For the 3D case, the simplex shape is a slightly irregular tetrahedron.\n // Determine which simplex we are in.\n let i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords\n let i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords\n if (x0 >= y0) {\n if (y0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // X Y Z order\n else if (x0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // X Z Y order\n else {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // Z X Y order\n }\n else { // x0<y0\n if (y0 < z0) {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Z Y X order\n else if (x0 < z0) {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Y Z X order\n else {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // Y X Z order\n }\n // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),\n // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and\n // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where\n // c = 1/6.\n const x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords\n const y1 = y0 - j1 + G3;\n const z1 = z0 - k1 + G3;\n const x2 = x0 - i2 + 2.0 * G3; // Offsets for third corner in (x,y,z) coords\n const y2 = y0 - j2 + 2.0 * G3;\n const z2 = z0 - k2 + 2.0 * G3;\n const x3 = x0 - 1.0 + 3.0 * G3; // Offsets for last corner in (x,y,z) coords\n const y3 = y0 - 1.0 + 3.0 * G3;\n const z3 = z0 - 1.0 + 3.0 * G3;\n // Work out the hashed gradient indices of the four simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n // Calculate the contribution from the four corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad3x[gi0] * x0 + permGrad3y[gi0] * y0 + permGrad3z[gi0] * z0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad3x[gi1] * x1 + permGrad3y[gi1] * y1 + permGrad3z[gi1] * z1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad3x[gi2] * x2 + permGrad3y[gi2] * y2 + permGrad3z[gi2] * z2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + 1 + perm[jj + 1 + perm[kk + 1]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad3x[gi3] * x3 + permGrad3y[gi3] * y3 + permGrad3z[gi3] * z3);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to stay just inside [-1,1]\n return 32.0 * (n0 + n1 + n2 + n3);\n };\n}\n/**\n * Creates a 4D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction4D}\n */\nexport function createNoise4D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these leads to a ~10% speedup\n const permGrad4x = new Float64Array(perm).map(v => grad4[(v % 32) * 4]);\n const permGrad4y = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 1]);\n const permGrad4z = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 2]);\n const permGrad4w = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 3]);\n return function noise4D(x, y, z, w) {\n let n0, n1, n2, n3, n4; // Noise contributions from the five corners\n // Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in\n const s = (x + y + z + w) * F4; // Factor for 4D skewing\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const l = fastFloor(w + s);\n const t = (i + j + k + l) * G4; // Factor for 4D unskewing\n const X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space\n const Y0 = j - t;\n const Z0 = k - t;\n const W0 = l - t;\n const x0 = x - X0; // The x,y,z,w distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n const w0 = w - W0;\n // For the 4D case, the simplex is a 4D shape I won't even try to describe.\n // To find out which of the 24 possible simplices we're in, we need to\n // determine the magnitude ordering of x0, y0, z0 and w0.\n // Six pair-wise comparisons are performed between each possible pair\n // of the four coordinates, and the results are used to rank the numbers.\n let rankx = 0;\n let ranky = 0;\n let rankz = 0;\n let rankw = 0;\n if (x0 > y0)\n rankx++;\n else\n ranky++;\n if (x0 > z0)\n rankx++;\n else\n rankz++;\n if (x0 > w0)\n rankx++;\n else\n rankw++;\n if (y0 > z0)\n ranky++;\n else\n rankz++;\n if (y0 > w0)\n ranky++;\n else\n rankw++;\n if (z0 > w0)\n rankz++;\n else\n rankw++;\n // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order.\n // Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w and x<w\n // impossible. Only the 24 indices which have non-zero entries make any sense.\n // We use a thresholding to set the coordinates in turn from the largest magnitude.\n // Rank 3 denotes the largest coordinate.\n // Rank 2 denotes the second largest coordinate.\n // Rank 1 denotes the second smallest coordinate.\n // The integer offsets for the second simplex corner\n const i1 = rankx >= 3 ? 1 : 0;\n const j1 = ranky >= 3 ? 1 : 0;\n const k1 = rankz >= 3 ? 1 : 0;\n const l1 = rankw >= 3 ? 1 : 0;\n // The integer offsets for the third simplex corner\n const i2 = rankx >= 2 ? 1 : 0;\n const j2 = ranky >= 2 ? 1 : 0;\n const k2 = rankz >= 2 ? 1 : 0;\n const l2 = rankw >= 2 ? 1 : 0;\n // The integer offsets for the fourth simplex corner\n const i3 = rankx >= 1 ? 1 : 0;\n const j3 = ranky >= 1 ? 1 : 0;\n const k3 = rankz >= 1 ? 1 : 0;\n const l3 = rankw >= 1 ? 1 : 0;\n // The fifth corner has all coordinate offsets = 1, so no need to compute that.\n const x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords\n const y1 = y0 - j1 + G4;\n const z1 = z0 - k1 + G4;\n const w1 = w0 - l1 + G4;\n const x2 = x0 - i2 + 2.0 * G4; // Offsets for third corner in (x,y,z,w) coords\n const y2 = y0 - j2 + 2.0 * G4;\n const z2 = z0 - k2 + 2.0 * G4;\n const w2 = w0 - l2 + 2.0 * G4;\n const x3 = x0 - i3 + 3.0 * G4; // Offsets for fourth corner in (x,y,z,w) coords\n const y3 = y0 - j3 + 3.0 * G4;\n const z3 = z0 - k3 + 3.0 * G4;\n const w3 = w0 - l3 + 3.0 * G4;\n const x4 = x0 - 1.0 + 4.0 * G4; // Offsets for last corner in (x,y,z,w) coords\n const y4 = y0 - 1.0 + 4.0 * G4;\n const z4 = z0 - 1.0 + 4.0 * G4;\n const w4 = w0 - 1.0 + 4.0 * G4;\n // Work out the hashed gradient indices of the five simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n const ll = l & 255;\n // Calculate the contribution from the five corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk + perm[ll]]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad4x[gi0] * x0 + permGrad4y[gi0] * y0 + permGrad4z[gi0] * z0 + permGrad4w[gi0] * w0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad4x[gi1] * x1 + permGrad4y[gi1] * y1 + permGrad4z[gi1] * z1 + permGrad4w[gi1] * w1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad4x[gi2] * x2 + permGrad4y[gi2] * y2 + permGrad4z[gi2] * z2 + permGrad4w[gi2] * w2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad4x[gi3] * x3 + permGrad4y[gi3] * y3 + permGrad4z[gi3] * z3 + permGrad4w[gi3] * w3);\n }\n let t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4;\n if (t4 < 0)\n n4 = 0.0;\n else {\n const gi4 = ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]];\n t4 *= t4;\n n4 = t4 * t4 * (permGrad4x[gi4] * x4 + permGrad4y[gi4] * y4 + permGrad4z[gi4] * z4 + permGrad4w[gi4] * w4);\n }\n // Sum up and scale the result to cover the range [-1,1]\n return 27.0 * (n0 + n1 + n2 + n3 + n4);\n };\n}\n/**\n * Builds a random permutation table.\n * This is exported only for (internal) testing purposes.\n * Do not rely on this export.\n * @private\n */\nexport function buildPermutationTable(random) {\n const tableSize = 512;\n const p = new Uint8Array(tableSize);\n for (let i = 0; i < tableSize / 2; i++) {\n p[i] = i;\n }\n for (let i = 0; i < tableSize / 2 - 1; i++) {\n const r = i + ~~(random() * (256 - i));\n const aux = p[i];\n p[i] = p[r];\n p[r] = aux;\n }\n for (let i = 256; i < tableSize; i++) {\n p[i] = p[i - 256];\n }\n return p;\n}\n//# sourceMappingURL=simplex-noise.js.map","function _prng_restore(prng, xg, opts) {\n let state = opts && opts.state;\n if (state) {\n if (typeof(state) == 'object') xg.copy(state, xg);\n prng.state = () => xg.copy(xg, {});\n }\n}\n\nfunction _prng_xor_core(xg, opts) {\n let prng = () => (xg.next() >>> 0) / 0x100000000;\n\n prng.double = () => {\n let top, bot, result;\n do {\n top = xg.next() >>> 11;\n bot = (xg.next() >>> 0) / 0x100000000;\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n\n prng.int32 = () => xg.next() | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng;\n}\n\n// A port of an algorithm by Johannes Baagøe <[email protected]>, 2010\nfunction prng_alea(seed, opts) {\n let xg = new AleaGen(seed);\n\n let prng = () => xg.next();\n\n prng.double = () =>\n prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53\n\n prng.int32 = () => (xg.next() * 0x100000000) | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\nclass AleaGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let n = 0xefc8249d;\n\n // Apply the seeding algorithm from Baagoe.\n this.c = 1;\n this.s0 = mash(' ');\n this.s1 = mash(' ');\n this.s2 = mash(' ');\n this.s0 -= mash(seed);\n if (this.s0 < 0) { this.s0 += 1; }\n this.s1 -= mash(seed);\n if (this.s1 < 0) { this.s1 += 1; }\n this.s2 -= mash(seed);\n if (this.s2 < 0) { this.s2 += 1; }\n\n function mash(data) {\n data = String(data);\n for (let i = 0; i < data.length; i++) {\n n += data.charCodeAt(i);\n let h = 0.02519603282416938 * n;\n n = h >>> 0;\n h -= n;\n h *= n;\n n = h >>> 0;\n h -= n;\n n += h * 0x100000000; // 2^32\n }\n return (n >>> 0) * 2.3283064365386963e-10; // 2^-32\n }\n }\n\n next() {\n let {c,s0,s1,s2} = this;\n let t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32\n this.s0 = s1;\n this.s1 = s2;\n return this.s2 = t - (this.c = t | 0);\n }\n\n copy(f, t) {\n t.c = f.c;\n t.s0 = f.s0;\n t.s1 = f.s1;\n t.s2 = f.s2;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xor128\" prng algorithm by\nfunction prng_xor128(seed, opts) {\n let xg = new Xor128Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass Xor128Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w} = this;\n let t = x ^ (x << 11);\n this.x = y;\n this.y = z;\n this.z = w;\n return this.w = w ^ ((w >>> 19) ^ t ^ (t >>> 8));\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorwow\" prng algorithm by\nfunction prng_xorwow(seed, opts) {\n let xg = new XorWowGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass XorWowGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n this.v = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n if (k == strseed.length) {\n this.d = this.x << 10 ^ this.x >>> 4;\n }\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w,v,d} = this;\n let t = (x ^ (x >>> 2));\n this.x = y;\n this.y = z;\n this.z = w;\n this.w = v;\n return (this.d = (d + 362437 | 0)) +\n (this.v = (v ^ (v << 4)) ^ (t ^ (t << 1))) | 0;\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n t.v = f.v;\n t.d = f.d;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorshift7\" algorithm by\nfunction prng_xorshift7(seed, opts) {\n let xg = new XorShift7Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass XorShift7Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n var j, w, x = [];\n\n if (seed === (seed | 0)) {\n // Seed state array using a 32-bit integer.\n w = x[0] = seed;\n } else {\n // Seed state using a string.\n seed = '' + seed;\n for (j = 0; j < seed.length; ++j) {\n x[j & 7] = (x[j & 7] << 15) ^\n (seed.charCodeAt(j) + x[(j + 1) & 7] << 13);\n }\n }\n\n // Enforce an array length of 8, not all zeroes.\n while (x.length < 8) x.push(0);\n for (j = 0; j < 8 && x[j] === 0; ++j);\n if (j == 8) w = x[7] = -1; else w = x[j];\n\n this.x = x;\n this.i = 0;\n\n // Discard an initial 256 values.\n for (j = 256; j > 0; --j) {\n this.next();\n }\n }\n\n next() {\n // Update xor generator.\n let t, v, {x,i} = this;\n t = x[i]; t ^= (t >>> 7); v = t ^ (t << 24);\n t = x[(i + 1) & 7]; v ^= t ^ (t >>> 10);\n t = x[(i + 3) & 7]; v ^= t ^ (t >>> 3);\n t = x[(i + 4) & 7]; v ^= t ^ (t << 7);\n t = x[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);\n x[i] = v;\n this.i = (i + 1) & 7;\n return v;\n };\n\n copy(f, t) {\n t.x = [... f.x];\n t.i = f.i;\n return t;\n }\n}\n\n// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.\nfunction prng_xor4096(seed, opts) {\n let xg = new Xor4096Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass Xor4096Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let t, v, i, j, w, X = [], limit = 128;\n if (seed === (seed | 0)) {\n // Numeric seeds initialize v, which is used to generates X.\n v = seed;\n seed = null;\n } else {\n // String seeds are mixed into v and X one character at a time.\n seed = seed + '\\0';\n v = 0;\n limit = Math.max(limit, seed.length);\n }\n // Initialize circular array and weyl value.\n for (i = 0, j = -32; j < limit; ++j) {\n // Put the unicode characters into the array, and shuffle them.\n if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);\n // After 32 shuffles, take v as the starting w value.\n if (j === 0) w = v;\n v ^= v << 10;\n v ^= v >>> 15;\n v ^= v << 4;\n v ^= v >>> 13;\n if (j >= 0) {\n w = (w + 0x61c88647) | 0; // Weyl.\n t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array.\n i = (0 == t) ? i + 1 : 0; // Count zeroes.\n }\n }\n // We have detected all zeroes; make the key nonzero.\n if (i >= 128) {\n X[(seed && seed.length || 0) & 127] = -1;\n }\n // Run the generator 512 times to further mix the state before using it.\n // Factoring this as a function slows the main generator, so it is just\n // unrolled here. The weyl generator is not advanced while warming up.\n i = 127;\n for (j = 4 * 128; j > 0; --j) {\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n X[i] = v ^ t;\n }\n // Storing state as object members is faster than using closure variables.\n this.w = w;\n this.X = X;\n this.i = i;\n }\n\n next() {\n let t, v, {w, X, i} = this;\n // Update Weyl generator.\n this.w = w = (w + 0x61c88647) | 0;\n // Update xor generator.\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n // Update Xor generator array state.\n v = X[i] = v ^ t;\n this.i = i;\n // Result is the combination.\n return (v + (w ^ (w >>> 16))) | 0;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.w = f.w;\n t.X = [... f.X];\n return t;\n }\n}\n\n// A Javascript implementaion of the \"Tyche-i\" prng algorithm by\nfunction prng_tychei(seed, opts) {\n let xg = new TycheiGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass TycheiGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.a = 0;\n this.b = 0;\n this.c = 2654435769 | 0;\n this.d = 1367130551;\n\n if (seed === Math.floor(seed)) {\n // Integer seed.\n this.a = (seed / 0x100000000) | 0;\n this.b = seed | 0;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 20; k++) {\n this.b ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {a,b,c,d} = this;\n b = (b << 25) ^ (b >>> 7) ^ c;\n c = (c - d) | 0;\n d = (d << 24) ^ (d >>> 8) ^ a;\n a = (a - b) | 0;\n this.b = b = (b << 20) ^ (b >>> 12) ^ c;\n this.c = c = (c - d) | 0;\n this.d = (d << 16) ^ (c >>> 16) ^ a;\n return this.a = (a - b) | 0;\n };\n\n copy(f, t) {\n t.a = f.a;\n t.b = f.b;\n t.c = f.c;\n t.d = f.d;\n return t;\n }\n}\n\n\n/* The following is non-inverted tyche, which has better internal\n * bit diffusion, but which is about 25% slower than tyche-i in JS.\n *\n\nclass TycheiGenAlt extends TycheiGen {\n next() {\n let {a,b,c,d} = this\n a = (a + b | 0) >>> 0;\n d = d ^ a; d = d << 16 ^ d >>> 16;\n c = c + d | 0;\n b = b ^ c; b = b << 12 ^ d >>> 20;\n this.a = a = a + b | 0;\n d = d ^ a; this.d = d = d << 8 ^ d >>> 24;\n this.c = c = c + d | 0;\n b = b ^ c;\n return this.b = (b << 7 ^ b >>> 25);\n }\n}\n*/\n\n/*\nCopyright 2019 David Bau.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*/\nfunction prng_arc4(seed, opts) {\n let xg = new ARC4Gen(seed);\n let prng = () => xg.next();\n\n prng.double = prng;\n\n prng.int32 = () => xg.g(4) | 0;\n\n prng.quick = () => xg.g(4) / 0x100000000;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\n\n//\n// ARC4\n//\n// An ARC4 implementation. The constructor takes a key in the form of\n// an array of at most (width) integers that should be 0 <= x < (width).\n//\n// The g(count) method returns a pseudorandom integer that concatenates\n// the next (count) outputs from ARC4. Its return value is a number x\n// that is in the range 0 <= x < (width ^ count).\n//\n\n//\n// The following constants are related to IEEE 754 limits.\n//\n\n// const width = 256 // each RC4 output is 0 <= x < 256\n// const chunks = 6 // at least six RC4 outputs for each double\nconst _arc4_startdenom = 281474976710656; // 256 ** 6 == width ** chunks\nconst _arc4_significance = 4503599627370496; // 2 ** 52 significant digits in a double\nconst _arc4_overflow = 9007199254740992; // 2 ** 53 == significance * 2\n\n\nclass ARC4Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let key = this.mixkey(seed, []);\n let i,j,t, S=[], keylen = key.length;\n this.i = this.j = i = j = 0;\n this.S = S;\n\n // The empty key [] is treated as [0].\n if (!keylen) { key = [keylen++]; }\n\n // Set up S using the standard key scheduling algorithm.\n while (i <= 0xff) {\n S[i] = i++;\n }\n for (i = 0; i <= 0xff; i++) {\n S[i] = S[j = 0xff & (j + key[i % keylen] + (t = S[i]))];\n S[j] = t;\n }\n\n // For robust unpredictability, the function call below automatically\n // discards an initial batch of values. This is called RC4-drop[256].\n // See http://google.com/search?q=rsa+fluhrer+response&btnI\n this.g(256);\n }\n\n next() {\n // This function returns a random double in [0, 1) that contains\n // randomness in every bit of the mantissa of the IEEE 754 value.\n\n let n = this.g(6); // Start with a numerator n < 2 ^ 48\n let d = _arc4_startdenom; // and denominator d = 2 ^ 48.\n let x = 0; // and no 'extra last byte'.\n\n while (n < _arc4_significance) { // Fill up all significant digits (2 ** 52)\n n = (n + x) * 256; // by shifting numerator and\n d *= 256; // denominator and generating a\n x = this.g(1); // new least-significant-byte.\n }\n while (n >= _arc4_overflow) { // To avoid rounding past overflow, before adding\n n /= 2; // last byte, shift everything\n d /= 2; // right using integer math until\n x >>>= 1; // we have exactly the desired bits.\n }\n return (n + x) / d; // Form the number within [0, 1).\n }\n\n g(count) {\n // The \"g\" method returns the next (count) outputs as one number.\n let t, r = 0, {i,j,S} = this;\n while (count--) {\n t = S[i = 0xff & (i + 1)];\n r = r * 256 + S[0xff & ((S[i] = S[j = 0xff & (j + t)]) + (S[j] = t))];\n }\n this.i = i;\n this.j = j;\n return r;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.j = f.j;\n t.S = [... f.S];\n return t;\n }\n\n mixkey(seed, key) {\n seed = seed + '';\n let smear=0, j=0;\n while (j < seed.length) {\n key[0xff & j] =\n 0xff & ((smear ^= key[0xff & j] * 19) + seed.charCodeAt(j++));\n }\n return key\n }\n}\n\nexport { prng_alea, prng_arc4, prng_tychei, prng_xor128, prng_xor4096, prng_xorshift7, prng_xorwow };\n//# sourceMappingURL=index.mjs.map\n","import { usesRadians as runtimeUsesRadians } from \"./runtime.js\";\n\n// =============================================================================\n// Section: Randomness & Noise\n// =============================================================================\n\nimport { createNoise2D } from \"simplex-noise\";\nimport { prng_alea } from \"esm-seedrandom\";\n\n/**\n * A uniform PRNG function. Returns a float in [0,1).\n * @callback RNG\n * @returns {number}\n */\n/** @type {RNG} */\nlet rng = prng_alea(Math.random());\nlet rng2 = prng_alea(Math.random());\n\nconst _seedCallbacks = [];\n\n/**\n * Register a callback to be called whenever seed() is invoked.\n * Used internally by modules that maintain gaussian pools.\n * @param {Function} cb\n */\nexport const _onSeed = (cb) => _seedCallbacks.push(cb);\n\n/**\n * Seed the random number generator.\n * @param {number|string} s – The seed value.\n * @returns {void}\n */\nexport const seed = (s) => {\n rng = prng_alea(s);\n rng2 = prng_alea(`${s}:2`);\n for (const callback of _seedCallbacks) {\n callback();\n }\n};\n\n/**\n * Simplex‐noise 2D function.\n * @type {function(number, number): number}\n */\nexport let noise = createNoise2D(prng_alea(Math.random()));\nexport let noise2 = createNoise2D(prng_alea(Math.random()));\n\n/**\n * Seed the noise generator.\n * @param {number|string} s - The seed value.\n * @returns {void}\n */\nexport const noiseSeed = (s) => {\n noise = createNoise2D(prng_alea(s));\n noise2 = createNoise2D(prng_alea(`${s}:2`));\n};\n\n/**\n * Returns a random float in [min, max).\n * @param {number} [min=0]\n * @param {number} [max=1]\n * @returns {number}\n */\nexport const rr = (e = 0, r = 1) => e + rng() * (r - e);\nexport const rr2 = (e = 0, r = 1) => e + rng2() * (r - e);\n\n/**\n * Selects a random element from an array.\n * @param {T[]} array - Input array.\n * @returns {T}\n */\nexport const rArray = (array) => array[~~(rng() * array.length)];\n\n/**\n * Returns a random integer in [min, max).\n * @param {number} min\n * @param {number} max\n * @returns {number}\n */\nexport const randInt = (e, r) => ~~rr(e, r);\nexport const randInt2 = (e, r) => ~~rr2(e, r);\n\n/**\n * Gaussian (normal) random sample N(mean, stdev²).\n * @param {number} [mean=0]\n * @param {number} [stdev=1]\n * @returns {number}\n */\nexport const gaussian = (mean = 0, stdev = 1) => {\n const u = 1 - rng();\n const v = rng();\n const z = Math.sqrt(-2.0 * Math.log(u)) * cos(360 * v);\n return z * stdev + mean;\n};\n\n/**\n * Picks a key from an object according to weighted probabilities.\n * @param {Object<string|number, number>} weights\n * @returns {string|number}\n */\nexport const weightedRand = (weights) => {\n let totalWeight = 0;\n const entries = [];\n\n // Build cumulative weights array\n for (const key in weights) {\n totalWeight += weights[key];\n entries.push({ key, cumulative: totalWeight });\n }\n\n // Get a random number between 0 and totalWeight\n const rnd = rng() * totalWeight;\n\n // Pick the first entry where rnd is less than the cumulative weight\n for (const { key, cumulative } of entries) {\n if (rnd < cumulative) {\n return isNaN(key) ? key : parseInt(key);\n }\n }\n};\n\n// =============================================================================\n// Section: Numeric Mapping & Constraints\n// =============================================================================\n\n/**\n * Maps a value from range [a,b] to [c,d], optionally clamped.\n * @param {number} value\n * @param {number} a\n * @param {number} b\n * @param {number} c\n * @param {number} d\n * @param {boolean} [withinBounds=false]\n * @returns {number}\n */\nexport const map = (value, a, b, c, d, withinBounds = false) => {\n let r = c + ((value - a) / (b - a)) * (d - c);\n if (!withinBounds) return r;\n if (c < d) return constrain(r, c, d);\n else return constrain(r, d, c);\n};\n\n/**\n * Constrains a number within the provided bounds.\n * @param {number} n - The number.\n * @param {number} low - Lower bound.\n * @param {number} high - Upper bound.\n * @returns {number} The constrained number.\n */\nexport const constrain = (n, low, high) => Math.max(Math.min(n, high), low);\n\n// =============================================================================\n// Section: Trigonometry\n// =============================================================================\n\n/**\n * Normalize an angle in degrees to [0,360).\n * @param {number} angle\n * @returns {number}\n */\nconst nAngle = (angle) => {\n angle = angle % 360;\n return angle < 0 ? angle + 360 : angle;\n};\n\n// number of discrete steps (360° × 4 samples per degree)\nconst totalDegrees = 1440;\nconst radiansPerIndex = (2 * Math.PI) / totalDegrees;\n\n// lazy‐initialized lookup tables\nconst cLookup = new Float32Array(totalDegrees).fill(NaN);\nconst sLookup = new Float32Array(totalDegrees).fill(NaN);\n\n/**\n * Cosine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const cos = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = cLookup[idx];\n if (isNaN(v)) {\n v = Math.cos(idx * radiansPerIndex);\n cLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Sine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const sin = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = sLookup[idx];\n if (isNaN(v)) {\n v = Math.sin(idx * radiansPerIndex);\n sLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Converts radians to degrees, normalized to [0,360).\n * @param {number} rad\n * @returns {number}\n */\nexport const toDegrees = (rad, isRad = false) => {\n if (isRad || runtimeUsesRadians()) {\n let angle = ((rad * 180) / Math.PI) % 360;\n return angle < 0 ? angle + 360 : angle;\n } else {\n return rad;\n }\n};\n\n/**\n * Converts radians to degrees without wrapping the result.\n * Preserves signed angles so downstream scaling keeps its direction.\n * @param {number} angle\n * @param {boolean} [isRad=false]\n * @returns {number}\n */\nexport const toDegreesSigned = (angle, isRad = false) =>\n isRad || runtimeUsesRadians()\n ? (angle * 180) / Math.PI\n : angle;\n\n// =============================================================================\n// Section: Geometry & Transforms\n// =============================================================================\n\n/**\n * Rotates point (x,y) around center (cx,cy) by angle degrees.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x\n * @param {number} y\n * @param {number} angle - Degrees\n * @returns {{x:number,y:number}}\n */\nexport const rotate = (cx, cy, x, y, angle) => {\n let coseno = cos(angle),\n seno = sin(angle),\n nx = coseno * (x - cx) + seno * (y - cy) + cx,\n ny = coseno * (y - cy) - seno * (x - cx) + cy;\n return { x: nx, y: ny };\n};\n\n/**\n * Euclidean distance between two points.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const dist = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1);\n\n/**\n * Angle in degrees between two points, measured clockwise from +X.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const calcAngle = (x1, y1, x2, y2) =>\n toDegrees(Math.atan2(-(y2 - y1), x2 - x1), true);\n\n/**\n * Intersection of two line segments, or false if none.\n * @param {{x:number,y:number}} s1a\n * @param {{x:number,y:number}} s1b\n * @param {{x:number,y:number}} s2a\n * @param {{x:number,y:number}} s2b\n * @param {boolean} [includeSegmentExtension=false]\n * @returns {{x:number,y:number}|false}\n */\nexport const intersectLines = (\n s1a,\n s1b,\n s2a,\n s2b,\n includeSegmentExtension = false\n) => {\n // Extract coordinates from points\n let x1 = s1a.x,\n y1 = s1a.y;\n let x2 = s1b.x,\n y2 = s1b.y;\n let x3 = s2a.x,\n y3 = s2a.y;\n let x4 = s2b.x,\n y4 = s2b.y;\n // Early return if line segments are points or if the lines are parallel\n if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) {\n return false; // Segments are points\n }\n let deltaX1 = x2 - x1,\n deltaY1 = y2 - y1;\n let deltaX2 = x4 - x3,\n deltaY2 = y4 - y3;\n let denominator = deltaY2 * deltaX1 - deltaX2 * deltaY1;\n if (denominator === 0) {\n return false; // Lines are parallel\n }\n // Calculate the intersection point\n let ua = (deltaX2 * (y1 - y3) - deltaY2 * (x1 - x3)) / denominator;\n let ub = (deltaX1 * (y1 - y3) - deltaY1 * (x1 - x3)) / denominator;\n // Check if the intersection is within the bounds of the line segments\n if (!includeSegmentExtension && (ub < 0 || ub > 1)) {\n return false;\n }\n // Calculate the intersection coordinates\n let x = x1 + ua * deltaX1;\n let y = y1 + ua * deltaY1;\n return { x: x, y: y };\n};\n","// =============================================================================\n// Target Runtime Hooks\n// =============================================================================\n\n/**\n * Shared target state exposed to core modules.\n *\n * Host adapters are expected to keep these bindings updated with the currently\n * active drawing target. The exact object type is adapter-defined, but core code\n * assumes the active renderer exposes:\n * - `drawingContext`: the active WebGL context\n * - target dimensions through `Cwidth` / `Cheight`\n * - pixel density through `Density`\n */\n\nexport let Cwidth, Cheight, Instance, Renderer, Density;\n\nlet targetRuntime = {\n load: () => {\n throw new Error(\"No target runtime adapter registered.\");\n },\n syncDensity: () => Density,\n isCanvasReady: () => {\n throw new Error(\"No target runtime adapter registered.\");\n },\n instance: (inst) => {\n Instance = inst;\n },\n activateInstance: (inst) => {\n Instance = inst;\n },\n deactivateInstance: () => {},\n getActiveFramebuffer: () => null,\n isFramebufferTarget: () => false,\n};\n\n/**\n * Updates the shared target state consumed by core modules.\n *\n * @param {object} state\n */\nexport function setTargetState(state) {\n if (\"Cwidth\" in state) Cwidth = state.Cwidth;\n if (\"Cheight\" in state) Cheight = state.Cheight;\n if (\"Instance\" in state) Instance = state.Instance;\n if (\"Renderer\" in state) Renderer = state.Renderer;\n if (\"Density\" in state) Density = state.Density;\n}\n\n/**\n * Registers or updates host target hooks used by core modules.\n *\n * @param {object} hooks\n */\nexport function setTargetRuntime(hooks) {\n targetRuntime = { ...targetRuntime, ...hooks };\n}\n\nexport const load = (buffer = false) => targetRuntime.load(buffer);\nexport const syncDensity = () => targetRuntime.syncDensity();\nexport const isCanvasReady = () => targetRuntime.isCanvasReady();\nexport const instance = (inst) => targetRuntime.instance(inst);\nexport const activateInstance = (inst) => targetRuntime.activateInstance(inst);\nexport const deactivateInstance = () => targetRuntime.deactivateInstance();\nexport const getActiveFramebuffer = () => targetRuntime.getActiveFramebuffer();\nexport const isFramebufferTarget = (target) =>\n targetRuntime.isFramebufferTarget(target);\n","// =============================================================================\n// Module: Dirty Rect Utilities\n// =============================================================================\n/**\n * Expands a dirty rectangle outward by a constant padding value.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Rect to expand.\n * @param {number} [padding=0] - Padding in pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Expanded rect.\n */\nexport const expandDirtyRect = (rect, padding = 0) =>\n rect\n ? {\n minX: rect.minX - padding,\n minY: rect.minY - padding,\n maxX: rect.maxX + padding,\n maxY: rect.maxY + padding,\n }\n : null;\n\n/**\n * Clamps a dirty rectangle to explicit target bounds.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Candidate rect.\n * @param {number} width - Target width in physical pixels.\n * @param {number} height - Target height in physical pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Clamped rect.\n */\nexport const normalizeDirtyRect = (rect, width, height) => {\n if (!rect) return null;\n\n const minX = Math.max(0, Math.floor(Math.min(rect.minX, rect.maxX)));\n const minY = Math.max(0, Math.floor(Math.min(rect.minY, rect.maxY)));\n const maxX = Math.min(width, Math.ceil(Math.max(rect.minX, rect.maxX)));\n const maxY = Math.min(height, Math.ceil(Math.max(rect.minY, rect.maxY)));\n\n if (maxX <= minX || maxY <= minY) return null;\n\n return { minX, minY, maxX, maxY };\n};\n\n/**\n * Returns the union of two dirty rectangles.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} a - First rect.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} b - Second rect.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Union rect.\n */\nexport const unionDirtyRect = (a, b) => {\n if (!a) return b;\n if (!b) return a;\n\n return {\n minX: Math.min(a.minX, b.minX),\n minY: Math.min(a.minY, b.minY),\n maxX: Math.max(a.maxX, b.maxX),\n maxY: Math.max(a.maxY, b.maxY),\n };\n};\n\n/**\n * Returns a dirty rectangle covering the full target bounds.\n *\n * @param {number} width - Target width in physical pixels.\n * @param {number} height - Target height in physical pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}} Full-target rect.\n */\nexport const getFullDirtyRect = (width, height) => ({\n minX: 0,\n minY: 0,\n maxX: width,\n maxY: height,\n});\n","// =============================================================================\n// Compositor Runtime Hooks\n// =============================================================================\n\n/**\n * Shared compositor helpers and host hooks.\n *\n * The shared code in this module assumes framebuffer-like targets expose:\n * - `framebuffer`: native WebGL framebuffer handle\n * - optional lifecycle methods supplied by the host adapter\n *\n * Higher-level core modules also attach their own bookkeeping fields onto the\n * active renderer and mask targets, such as:\n * - `shaderProgram`\n * - `blendSourceFramebuffer`\n * - `glMask`\n * - `fillMaskFramebuffer`\n * - `mask`\n *\n * These are library-level contract fields, not host-specific internals.\n */\n\nexport const create2DCanvas = (width, height, willReadFrequently = false) => {\n const canvas =\n typeof OffscreenCanvas !== \"undefined\"\n ? new OffscreenCanvas(width, height)\n : (() => {\n const element = document.createElement(\"canvas\");\n element.width = width;\n element.height = height;\n return element;\n })();\n canvas.drawingContext = canvas.getContext(\n \"2d\",\n willReadFrequently ? { willReadFrequently: true } : undefined,\n );\n return canvas;\n};\n\nexport const get2DContext = (canvas, willReadFrequently = false) => {\n canvas.drawingContext ??= canvas.getContext(\n \"2d\",\n willReadFrequently ? { willReadFrequently: true } : undefined,\n );\n return canvas.drawingContext;\n};\n\nexport function blitDefaultFramebufferSource({\n renderer,\n sourceFramebuffer,\n dirtyRect,\n getTargetPixelSize,\n toScissorBox,\n}) {\n const gl = renderer.drawingContext;\n const { width, height } = getTargetPixelSize();\n const sourceBox = dirtyRect ? toScissorBox(dirtyRect) : null;\n const previousReadFramebuffer = gl.getParameter(gl.READ_FRAMEBUFFER_BINDING);\n const previousDrawFramebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING);\n\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, sourceFramebuffer.framebuffer);\n gl.clearColor(0, 0, 0, 0);\n gl.clear(gl.COLOR_BUFFER_BIT);\n gl.blitFramebuffer(\n sourceBox?.x ?? 0,\n sourceBox?.y ?? 0,\n sourceBox ? sourceBox.x + sourceBox.width : width,\n sourceBox ? sourceBox.y + sourceBox.height : height,\n sourceBox?.x ?? 0,\n sourceBox?.y ?? 0,\n sourceBox ? sourceBox.x + sourceBox.width : width,\n sourceBox ? sourceBox.y + sourceBox.height : height,\n gl.COLOR_BUFFER_BIT,\n gl.NEAREST,\n );\n\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, previousReadFramebuffer);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, previousDrawFramebuffer);\n\n return sourceFramebuffer;\n}\n\nlet compositorRuntime = {\n clearTarget: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n ensureBlendShaderProgram: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n ensureBlendSourceFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n createFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n runBlendShaderPass: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n blitSourceToFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n};\n\n/**\n * Registers or updates host compositor hooks used by core compositing code.\n *\n * @param {object} hooks\n */\nexport function setCompositorRuntime(hooks) {\n compositorRuntime = { ...compositorRuntime, ...hooks };\n}\n\nexport const clearTarget = (...args) => compositorRuntime.clearTarget(...args);\nexport const ensureBlendShaderProgram = (...args) =>\n compositorRuntime.ensureBlendShaderProgram(...args);\nexport const ensureBlendSourceFramebuffer = (...args) =>\n compositorRuntime.ensureBlendSourceFramebuffer(...args);\nexport const createFramebuffer = (...args) =>\n compositorRuntime.createFramebuffer(...args);\nexport const runBlendShaderPass = (...args) =>\n compositorRuntime.runBlendShaderPass(...args);\nexport const blitSourceToFramebuffer = (...args) =>\n compositorRuntime.blitSourceToFramebuffer(...args);\n","import {\n Cwidth,\n Cheight,\n Renderer,\n Density,\n load as loadTarget,\n isCanvasReady,\n syncDensity,\n getActiveFramebuffer,\n isFramebufferTarget,\n} from \"./target.js\";\nimport {\n expandDirtyRect,\n normalizeDirtyRect as clampDirtyRect,\n unionDirtyRect,\n getFullDirtyRect as getFullRect,\n} from \"./dirty_rect.js\";\nimport {\n clearTarget as clearRenderTarget,\n ensureBlendShaderProgram,\n ensureBlendSourceFramebuffer,\n runBlendShaderPass,\n blitSourceToFramebuffer,\n} from \"./compositor_runtime.js\";\n\nimport vertSrc from \"./gl/shader.vert\";\nimport fragSrc from \"./gl/shader.frag\";\n\n// =============================================================================\n// Module: Configure and Initiate\n// =============================================================================\n/**\n * This module handles the configuration and initialization of the drawing system.\n * It manages canvas properties, ensures the system is ready for rendering, and\n * provides utilities for saving and restoring states.\n */\n\nlet strokeComposite = null;\nlet fillComposite = null;\n\nexport const registerStrokeComposite = (composite) => {\n strokeComposite = composite;\n};\n\nexport const registerFillComposite = (composite) => {\n fillComposite = composite;\n};\n\nconst clearTarget = (target) => {\n clearRenderTarget(Renderer, target, isFramebufferTarget);\n};\n\n// =============================================================================\n// Section: Dirty Rect Utilities\n// =============================================================================\n/**\n * Returns the current render target size in physical pixels.\n * @returns {{width: number, height: number}} Pixel size of the active target.\n */\nconst getTargetPixelSize = () => ({\n width: Math.max(1, Math.round(Cwidth * Density)),\n height: Math.max(1, Math.round(Cheight * Density)),\n});\n\nconst normalizeDirtyRect = (rect) => {\n if (!rect) return null;\n const { width, height } = getTargetPixelSize();\n return clampDirtyRect(rect, width, height);\n};\n\n/**\n * Returns a dirty rectangle covering the full active target.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}} Full-target rect.\n */\nconst getFullDirtyRect = () => {\n const { width, height } = getTargetPixelSize();\n return getFullRect(width, height);\n};\n\n// =============================================================================\n// Section: Scissor Helpers\n// =============================================================================\n/**\n * Converts a top-left-based dirty rectangle into a WebGL scissor box.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Dirty rect.\n * @returns {{x:number,y:number,width:number,height:number}|null} Scissor box or null.\n */\nconst toScissorBox = (rect, flipY = true) => {\n const normalized = normalizeDirtyRect(rect);\n if (!normalized) return null;\n\n const { height } = getTargetPixelSize();\n return {\n x: normalized.minX,\n y: flipY ? height - normalized.maxY : normalized.minY,\n width: normalized.maxX - normalized.minX,\n height: normalized.maxY - normalized.minY,\n };\n};\n\n/**\n * Runs a draw callback with a temporary scissor region.\n * @param {WebGL2RenderingContext} gl - Active WebGL context.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Dirty rect.\n * @param {Function} draw - Draw callback executed under the scissor box.\n */\nconst withScissor = (gl, rect, draw, flipY = true) => {\n const box = toScissorBox(rect, flipY);\n if (!box) {\n draw();\n return;\n }\n\n // Scissor is never nested in this module, so we can set/clear it directly\n // without saving previous GL state.\n gl.enable(gl.SCISSOR_TEST);\n gl.scissor(box.x, box.y, box.width, box.height);\n\n try {\n draw();\n } finally {\n gl.disable(gl.SCISSOR_TEST);\n }\n};\n\n/**\n * Stores the current state of the drawing system.\n * Can be used to save and restore configurations or canvas states.\n */\nexport const State = {};\n/**\n * Handles color blending using WebGL shaders. Implements advanced blending\n * effects based on Kubelka-Munk theory. Relies on spectral.js for blending logic.\n */\n\n// =============================================================================\n// Section: Color Blending / Rendering\n// =============================================================================\n/**\n * Ensures the Mix object is initialized and ready for blending.\n */\nexport const isMixReady = () => {\n if (!Renderer?.loaded) {\n isCanvasReady();\n Mix.load();\n }\n};\n\n/**\n * Manages blending operations with WebGL shaders.\n * @property {boolean} loaded - Indicates if shaders are loaded.\n * @property {boolean} isBlending - Indicates if blending is active.\n * @property {object} currentColor - Current color in WebGL format.\n * @property {function} load - Initializes blending resources.\n * @property {function} blend - Applies blending effects.\n */\nexport const Mix = {\n isBlending: false,\n cachedColor: null,\n\n /**\n * Merges a new dirty rectangle into the target's accumulated draw bounds.\n * @param {object} target - Mask buffer receiving draw output.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Rect to merge.\n */\n markDirtyRect(target, rect) {\n const normalized = normalizeDirtyRect(rect);\n if (!target || !normalized) return;\n target.dirtyRect = unionDirtyRect(target.dirtyRect, normalized);\n target.isDrawn = true;\n },\n\n /**\n * Clears a mask buffer and resets its dirty-rect tracking.\n * @param {object} target - Mask buffer to reset.\n */\n clearMask(target) {\n if (!target) return;\n const composite = target === this.glMask ? strokeComposite : fillComposite;\n composite?.clearMask?.(target, clearTarget);\n },\n\n /**\n * Resolves the region that should be composited back into the destination.\n * @param {object} target - Mask buffer being sampled.\n * @param {boolean} isBrushMask - True when compositing the GL brush mask.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\n getCompositeRect(target, isBrushMask) {\n const composite = isBrushMask ? strokeComposite : fillComposite;\n return composite?.getCompositeRect?.(\n target,\n getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n );\n },\n\n // =============================================================================\n // Section: Setup and load shaders\n // =============================================================================\n /**\n * Ensures the mask buffers and blend shader exist for the current renderer.\n */\n load() {\n syncDensity();\n const needsBlendSourceFramebuffer =\n !Renderer.blendSourceFramebuffer ||\n Renderer.blendSourceFramebuffer.width !== Cwidth ||\n Renderer.blendSourceFramebuffer.height !== Cheight ||\n (typeof Renderer.blendSourceFramebuffer.pixelDensity === \"function\" &&\n Renderer.blendSourceFramebuffer.pixelDensity() !== Density);\n ensureBlendShaderProgram(Renderer, vertSrc, fragSrc);\n\n this.glMask = strokeComposite?.ensureResources?.(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n );\n const fillResources = fillComposite?.ensureResources?.(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n clearTarget,\n ) ?? {\n mask: null,\n ctx: null,\n };\n\n if (needsBlendSourceFramebuffer) {\n Renderer.blendSourceFramebuffer = ensureBlendSourceFramebuffer(\n Renderer,\n Renderer.blendSourceFramebuffer,\n Cwidth,\n Cheight,\n Density,\n );\n }\n\n this.mask = fillResources.mask;\n this.ctx = fillResources.ctx;\n },\n\n // =============================================================================\n // Section: Compositing\n // =============================================================================\n /**\n * Flushes pending mask work when the blend color changes or a frame ends.\n * @param {Color|false} [_color=false] - New blend color.\n * @param {boolean} [_isLast=false] - True when this is the final blend flush.\n */\n blend(_color = false, _isLast = false) {\n isMixReady();\n // Only one mask is \"active\" for the current drawing mode; the other one\n // may still need flushing if the mode just changed mid-frame.\n const isBrushMask = this.isBrush === true;\n const mask = isBrushMask ? this.glMask : this.mask;\n const otherMask = isBrushMask ? this.mask : this.glMask;\n const nextColor = _color?._array;\n const colorChanged =\n !!nextColor &&\n (this.cachedColor?.[0] !== nextColor[0] ||\n this.cachedColor?.[1] !== nextColor[1] ||\n this.cachedColor?.[2] !== nextColor[2] ||\n this.cachedColor?.[3] !== nextColor[3]);\n if (!this.isBlending && nextColor) {\n this.isBlending = true;\n this.cachedColor = nextColor;\n // Reset the brush mask fully at the start of each blend cycle so stale\n // dirty-rect bookkeeping cannot leak an old stroke into the next color.\n this.clearMask(this.glMask);\n }\n\n if (_isLast || colorChanged) {\n if (this.justChanged) {\n this.applyShader(otherMask, !isBrushMask);\n this.justChanged = false;\n }\n if (this.isBlending) {\n this.applyShader(mask, isBrushMask);\n }\n if (nextColor) this.cachedColor = nextColor;\n if (_isLast) {\n this.isBlending = false;\n this.cachedColor = null;\n \n }\n }\n },\n\n /**\n * Runs the blend shader over a mask and composites the result into the active renderer.\n * @param {object} mask - Mask buffer to composite.\n * @param {boolean} isBrushMask - True when compositing the GL brush mask.\n */\n applyShader(mask, isBrushMask) {\n if (!mask?.isDrawn) return;\n\n const dirtyRect = this.getCompositeRect(mask, isBrushMask);\n if (!dirtyRect) {\n this.clearMask(mask);\n return;\n }\n\n const gl = Renderer.drawingContext;\n const shader = Renderer.shaderProgram;\n const activeFramebuffer = getActiveFramebuffer();\n const source = blitSourceToFramebuffer({\n renderer: Renderer,\n sourceTarget: activeFramebuffer ?? Renderer,\n sourceFramebuffer: Renderer.blendSourceFramebuffer,\n dirtyRect,\n isFramebufferTarget,\n Cwidth,\n Cheight,\n getTargetPixelSize,\n toScissorBox,\n withScissor,\n });\n const targetIsFramebuffer = !!activeFramebuffer;\n const composite = isBrushMask ? strokeComposite : fillComposite;\n const shaderMask = composite.getShaderMask(\n Renderer,\n mask,\n dirtyRect,\n normalizeDirtyRect,\n getFullDirtyRect,\n clearTarget,\n );\n\n runBlendShaderPass({\n renderer: Renderer,\n shader,\n source,\n mask: shaderMask,\n color: this.cachedColor,\n isBrushMask,\n Cwidth,\n Cheight,\n dirtyRect,\n targetIsFramebuffer,\n withScissor,\n });\n this.clearMask(mask);\n },\n};\n\n/**\n * Flushes any pending stroke/fill mask work into the current target and resets\n * the shared compositor back to its initial idle state.\n */\nexport const flushActiveComposite = () => {\n isMixReady();\n Mix.blend(false, true);\n Mix.clearMask(Mix.glMask);\n Mix.clearMask(Mix.mask);\n Mix.justChanged = false;\n Mix.isBlending = false;\n Mix.isBrush = null;\n Mix.cachedColor = null;\n};\n\n/**\n * Loads and initializes the drawing target, then refreshes compositing\n * resources if the renderer was already active.\n *\n * @param {object|false} [buffer=false] - Optional offscreen target.\n */\nexport const load = (buffer = false) => {\n loadTarget(buffer);\n if (Renderer.loaded) Mix.load();\n};\n","import { Cwidth, Cheight } from \"./target.js\";\nimport { isMixReady, State } from \"./color.js\";\nimport { randInt2, noise2, rr2, sin, cos, map, toDegreesSigned } from \"./utils.js\";\nimport { getAffineMatrix } from \"./runtime.js\";\n\n// =============================================================================\n// Section: Matrix transformations\n// =============================================================================\n\n// =============================================================================\n// Section: Field Initialization\n// =============================================================================\n\nlet isLoaded = false;\n\n/**\n * Ensures the field system is initialized and ready for use.\n * If the field is not loaded, it initializes the mixing system and creates the field.\n */\nexport function isFieldReady() {\n if (!isLoaded) {\n isMixReady(); // Ensure the mixing system is ready\n createField(); // Initialize the field\n isLoaded = true;\n }\n}\n\n// =============================================================================\n// Section: Position Class\n// =============================================================================\n\n/**\n * The Position class represents a point within a two-dimensional space, which can interact with a vector field.\n * It provides methods to update the position based on the field's flow and to check whether the position is\n * within certain bounds (e.g., within the field or canvas).\n */\nexport class Position {\n /**\n * Constructs a new Position instance.\n * @param {number} x - The initial x-coordinate.\n * @param {number} y - The initial y-coordinate.\n */\n constructor(x, y) {\n isFieldReady();\n const m = getAffineMatrix();\n this.mx = m.x;\n this.my = m.y;\n this.update(x, y);\n this.plotted = 0; // Tracks the total distance plotted\n }\n\n /**\n * Updates the position's coordinates and calculates its offsets and indices within the flow field.\n * @param {number} x - The new x-coordinate.\n * @param {number} y - The new y-coordinate.\n */\n update(x, y) {\n this.x = x;\n this.y = y;\n this.colIdx = Math.round((x + this.mx - left_x) / resolution);\n this.rowIdx = Math.round((y + this.my - top_y) / resolution);\n }\n\n /**\n * Resets the 'plotted' property to 0.\n */\n reset() {\n this.plotted = 0;\n }\n\n /**\n * Checks if the position is within the active flow field's bounds.\n * @returns {boolean} - True if the position is within the flow field, false otherwise.\n */\n isIn() {\n return State.field.isActive\n ? Position.isIn(this.colIdx, this.rowIdx)\n : this.isInCanvas(this.x, this.y);\n }\n\n /**\n * Checks if the position is within the canvas bounds (with a margin).\n * @returns {boolean} - True if the position is within bounds, false otherwise.\n */\n isInCanvas() {\n const margin = 0.3;\n const w = Cwidth;\n const h = Cheight;\n const x = this.x + this.mx;\n const y = this.y + this.my;\n return (\n x >= -margin * w &&\n x <= (1 + margin) * w &&\n y >= -margin * h &&\n y <= (1 + margin) * h\n );\n }\n\n /**\n * Calculates the angle of the flow field at the position's current coordinates.\n * @returns {number} - The internal flow angle in degrees, or 0 if the position is not in the field or if no field is active.\n */\n angle(skipCheck = false) {\n if (!State.field.isActive) return 0;\n return (skipCheck || this.isIn())\n ? flow_field()[this.colIdx][this.rowIdx] * State.field.wiggle\n : 0;\n }\n\n /**\n * Moves the position along the flow field by a certain length.\n * @param {number} _dir - The direction of movement, interpreted using the current runtime angle units.\n * @param {number} _length - The length to move along the field.\n * @param {number} _step_length - The length of each step.\n */\n moveTo(_dir, _length, _step_length = 1) {\n this.movePos(toDegreesSigned(_dir), _length, _step_length);\n }\n\n /**\n * Internal variant of moveTo() that expects a degree value already normalized to the library's internal representation.\n */\n _moveToDegrees(_dir, _length, _step_length = 1) {\n this.movePos(_dir, _length, _step_length);\n }\n\n /**\n * Plots a point to another position within the flow field, following a Plot object\n * @param {Position} _plot - The Plot path object.\n * @param {number} _length - The length to move towards the target position.\n * @param {number} _step_length - The length of each step.\n * @param {number} _scale - The scaling factor for the plotting path.\n */\n plotTo(_plot, _length, _step_length, _scale = 1) {\n this.movePos(_plot, _length, _step_length, _scale);\n }\n\n movePos(_dirPlot, _length, _step, _scale = false) {\n const scaleFactor = _scale || 1;\n if (!this.isIn()) {\n this.plotted += _step / scaleFactor;\n return;\n }\n const steps = _length / _step;\n const fieldActive = State.field.isActive;\n const usePlot = !!_scale;\n for (let i = 0; i < steps; i++) {\n const angle =\n (fieldActive ? this.angle(true) : 0) - (usePlot ? _dirPlot.angle(this.plotted) : _dirPlot);\n // Calculate new position\n this.update(this.x + _step * cos(angle), this.y + _step * sin(angle));\n this.plotted += _step / scaleFactor;\n }\n }\n\n // Static Methods\n\n /**\n * Gets the row index for a given y-coordinate.\n * @param {number} y - The y-coordinate.\n * @returns {number} - The row index.\n */\n static getRowIndex(y, d = 1) {\n const y_offset = y + getAffineMatrix().y - top_y;\n return Math.round(y_offset / resolution / d);\n }\n\n /**\n * Gets the column index for a given x-coordinate.\n * @param {number} x - The x-coordinate.\n * @returns {number} - The column index.\n */\n static getColIndex(x, d = 1) {\n const x_offset = x + getAffineMatrix().x - left_x;\n return Math.round(x_offset / resolution / d);\n }\n\n /**\n * Checks if a column and row index are within the flow field bounds.\n * @param {number} col - The column index.\n * @param {number} row - The row index.\n * @returns {boolean} - True if the indices are within bounds, false otherwise.\n */\n static isIn(col, row) {\n return col >= 0 && row >= 0 && col < num_columns && row < num_rows;\n }\n}\n\n// =============================================================================\n// Section: VectorField\n// =============================================================================\n\n/**\n * Represents the state of the vector field.\n * @property {boolean} isActive - Indicates if the vector field is active.\n * @property {string|null} current - The name of the currently active vector field.\n */\nState.field = {\n isActive: false,\n current: null,\n wiggle: 1,\n};\n\n// Internal variables for field configuration\nlet list = new Map();\nlet resolution, left_x, top_y, num_columns, num_rows;\nconst FIELD_ANGLE_MODES = new Set([\"degrees\", \"radians\"]);\n\n/**\n * Initializes the field grid and sets up the vector field's structure based on the renderer's dimensions.\n */\nfunction createField() {\n resolution = Cwidth * 0.01; // Determine the resolution of the field grid\n left_x = -0.5 * Cwidth; // Left boundary of the field\n top_y = -0.5 * Cheight; // Top boundary of the field\n num_columns = Math.round((2 * Cwidth) / resolution); // Number of columns in the grid\n num_rows = Math.round((2 * Cheight) / resolution); // Number of columns in the grid\n addStandard(); // Add default vector field\n}\n\n/**\n * Retrieves the field values for the current vector field.\n * @returns {Float32Array[]} The current vector field grid.\n */\nfunction flow_field() {\n return list.get(State.field.current).field;\n}\n\nfunction normalizeFieldAngleMode(options = {}) {\n const config =\n typeof options === \"string\" ? { angleMode: options } : options || {};\n const angleMode = config.angleMode ?? \"degrees\";\n\n if (!FIELD_ANGLE_MODES.has(angleMode)) {\n throw new Error(\n `Invalid field angle mode \"${angleMode}\". Use \"degrees\" or \"radians\".`,\n );\n }\n\n return angleMode;\n}\n\nfunction normalizeFieldAngles(field, angleMode) {\n if (angleMode !== \"radians\") return field;\n\n for (let c = 0; c < field.length; c++) {\n for (let r = 0; r < field[c].length; r++) {\n field[c][r] = toDegreesSigned(field[c][r], true);\n }\n }\n\n return field;\n}\n\nfunction generateField(entry, t) {\n return normalizeFieldAngles(entry.gen(t, genField()), entry.angleMode);\n}\n\n/**\n * Regenerates the current vector field using its associated generator function.\n * @param {number} [t=0] - An optional time parameter that can affect field generation.\n */\nexport function refreshField(t = 0) {\n if (!State.field.isActive || !State.field.current) {\n throw new Error(\n \"No field is currently active. Call brush.field('name') to activate one before refreshing.\",\n );\n }\n const currentField = list.get(State.field.current);\n currentField.field = generateField(currentField, t);\n}\n\n/**\n * Generates an empty field array.\n * Reuses existing arrays to reduce memory allocation overhead.\n * @returns {Float32Array[]} Empty vector field grid.\n */\nfunction genField() {\n return new Array(num_columns)\n .fill(null)\n .map(() => new Float32Array(num_rows));\n}\n\n/**\n * Activates a specific vector field by name, ensuring it's ready for use.\n * @param {string} a - The name of the vector field to activate.\n */\nexport function field(a) {\n if (!State.field.wiggle) {\n State.field.wiggle = 1;\n } // Set default wiggle value\n isFieldReady();\n if (!list.has(a)) {\n throw new Error(\n `Field \"${a}\" does not exist. Available fields: ${Array.from(list.keys()).join(\", \")}.`,\n );\n }\n State.field.isActive = true;\n State.field.current = a;\n const entry = list.get(a);\n if (!entry.field) entry.field = generateField(entry, 0);\n}\n\n/**\n * Deactivates the current vector field.\n */\nexport function noField() {\n isFieldReady();\n State.field.isActive = false;\n}\n\n/**\n * Adds a new vector field to the field list with a unique name and a generator function.\n * @param {string} name - The unique name for the new vector field.\n * @param {Function} funct - The function that generates the field values.\n * @param {object} [options] - Optional field configuration.\n * @param {\"degrees\"|\"radians\"} [options.angleMode=\"degrees\"] - How the generator's output angles should be interpreted.\n */\nexport function addField(name, funct, options = {}) {\n list.set(name, {\n gen: funct,\n field: null,\n angleMode: normalizeFieldAngleMode(options),\n });\n}\n\n/**\n * Retrieves a list of all available vector field names.\n * @returns {string[]} An array of all the field names.\n */\nexport function listFields() {\n isFieldReady();\n return Array.from(list.keys());\n}\n\nexport function wiggle(a = 1) {\n field(\"hand\");\n State.field.wiggle = a;\n}\n\n/**\n * Fills every cell of a field grid using a callback (c, r) => angle.\n */\nfunction fillField(field, fn) {\n for (let c = 0; c < num_columns; c++)\n for (let r = 0; r < num_rows; r++) field[c][r] = fn(c, r);\n return field;\n}\n\n/**\n * Adds standard predefined vector fields to the list with unique behaviors.\n */\nfunction addStandard() {\n // Organic noise — basis for brush.wiggle()\n addField(\"hand\", (t, field) => {\n const bs = rr2(0.2, 0.8),\n ba = randInt2(5, 10);\n return fillField(field, (c, r) => {\n const angle = 0.5 * ba * sin(bs * r * c + randInt2(15, 25));\n return 0.2 * angle * cos(t) + noise2(c, r) * ba * 0.7;\n });\n });\n // Smooth large-scale noise curves\n addField(\"curved\", (t, field) => {\n let ar = randInt2(-10, 10);\n if (randInt2(0, 100) % 2 == 0) ar *= -1;\n return fillField(\n field,\n (c, r) =>\n 3 * map(noise2(c * 0.02 + t * 0.03, r * 0.02 + t * 0.03), 0, 1, -ar, ar),\n );\n });\n // Sharp alternating angles per cell — herringbone / wicker look\n addField(\"zigzag\", (t, field) => {\n let ar = randInt2(-30, -15) + Math.abs(44 * sin(t));\n if (randInt2(0, 100) % 2 == 0) ar *= -1;\n let dif = ar,\n angle = 0;\n for (let c = 0; c < num_columns; c++) {\n for (let r = 0; r < num_rows; r++) {\n field[c][r] = angle;\n angle += dif;\n dif *= -1;\n }\n angle += dif;\n dif *= -1;\n }\n return field;\n });\n // Sinusoidal wave bands\n addField(\"waves\", (t, field) => {\n const sr = randInt2(10, 15) + 5 * sin(t),\n cr = randInt2(3, 6) + 3 * cos(t),\n ba = randInt2(20, 35);\n return fillField(\n field,\n (c, r) => sin(sr * c) * ba * cos(r * cr) + randInt2(-3, 3),\n );\n });\n // Dense oscillation from row×col product\n addField(\"seabed\", (t, field) => {\n const bs = rr2(0.4, 0.8),\n ba = randInt2(18, 26);\n return fillField(\n field,\n (c, r) => 1.1 * ba * sin(bs * r * c + randInt2(15, 20)) * cos(t),\n );\n });\n // Radial vortex — angles spiral around the field centre\n addField(\"spiral\", (_t, field) => {\n const n = randInt2(5, 10);\n const dir = randInt2(0, 2) * 2 - 1;\n const offset = randInt2(65, 80); // <90 = inward spiral\n const attractors = Array.from({ length: n }, () => ({\n x: rr2(0.1, 0.9) * num_columns,\n y: rr2(0.1, 0.9) * num_rows,\n }));\n return fillField(field, (c, r) => {\n let wx = 0,\n wy = 0;\n for (const att of attractors) {\n const dx = c - att.x,\n dy = r - att.y;\n const w = 1 / (dx * dx + dy * dy + 1);\n const a = Math.atan2(dy, dx) * (180 / Math.PI);\n const angle = (dir * (a + offset) * Math.PI) / 180;\n wx += w * Math.cos(angle);\n wy += w * Math.sin(angle);\n }\n return Math.atan2(wy, wx) * (180 / Math.PI);\n });\n });\n // Column-banded stripes — parallel rake marks\n addField(\"columns\", (_t, field) => {\n const freq = randInt2(3, 8),\n amp = randInt2(25, 45);\n return fillField(field, (c, _r) => sin(c * freq) * amp);\n });\n}\n","import { State } from \"./color.js\";\nimport { intersectLines } from \"./utils.js\";\n\n// =============================================================================\n// Section: Polygon Class\n// =============================================================================\n\n/**\n * Represents a polygon with a set of vertices and provides methods for\n * intersection, drawing, filling, and hatching.\n */\nexport class Polygon {\n /**\n * Constructs the Polygon object from an array of points.\n * @param {Array} pointsArray - An array of points, where each point is an array of two numbers [x, y].\n * @param {boolean} [useRawVertices=false] - If true, uses the raw array as vertices.\n */\n constructor(pointsArray, useRawVertices = false) {\n this.a = pointsArray;\n this.vertices = useRawVertices\n ? pointsArray\n : pointsArray.map(([x, y]) => ({ x, y }));\n this.sides = this.vertices.map((v, i, arr) => [\n v,\n arr[(i + 1) % arr.length],\n ]);\n this._intersectionCache = {}; // Cache for intersection results\n }\n\n /**\n * Intersects a given line with the polygon, returning all intersection points.\n * @param {Object} line - The line to intersect with the polygon, having two properties 'point1' and 'point2'.\n * @returns {Array} An array of intersection points (each with 'x' and 'y' properties) or an empty array if no intersections.\n */\n intersect(line) {\n // Check if the result has been cached\n const cacheKey = `${line.point1.x},${line.point1.y}-${line.point2.x},${line.point2.y}`;\n if (this._intersectionCache[cacheKey]) {\n return this._intersectionCache[cacheKey];\n }\n const points = [];\n for (const [start, end] of this.sides) {\n const intersection = intersectLines(line.point1, line.point2, start, end);\n if (intersection) points.push(intersection);\n }\n this._intersectionCache[cacheKey] = points; // Cache the result\n return points;\n }\n\n /**\n * Displays the polygon with optional stroke, hatch, and fill effects.\n */\n show() {\n if (State.wash) this.wash();\n if (State.fill) this.fill();\n if (State.mass) this.mass();\n if (State.hatch) this.hatch();\n if (State.stroke) this.draw();\n }\n}","import { Cwidth, Cheight } from \"./target.js\";\nimport { State } from \"./color.js\";\nimport { toDegrees, map, rr2 } from \"./utils.js\";\nimport { Position, isFieldReady } from \"./flowfield.js\";\nimport { Polygon } from \"./polygon.js\";\n\n// =============================================================================\n// Section: Plot Class\n// =============================================================================\n\n/**\n * The Plot class represents a collection of segments that define shapes or paths.\n * It supports operations like adding segments, calculating angles and pressures,\n * and generating polygons based on the plot's structure.\n */\nexport class Plot {\n /**\n * Creates a new Plot.\n * @param {string} _type - The type of plot, \"curve\" or \"segments\".\n */\n constructor(_type) {\n this.segments = [];\n this.angles = [];\n this.pres = [];\n this.type = _type;\n this.dir = 0;\n this.calcIndex(0);\n this.pol = false;\n }\n\n /**\n * Adds a segment to the plot with specified angle, length, and pressure.\n * @param {number} _a - The angle of the segment.\n * @param {number} _length - The length of the segment.\n * @param {number} _pres - The pressure of the segment.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n addSegment(_a = 0, _length = 0, _pres = 1, _degrees = false) {\n if (this.angles.length > 0) this.angles.pop(); // Remove the last angle\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a); // Normalize angle\n this.angles.push(_a, _a); // Push angle twice for continuity\n this.pres.push(_pres);\n this.segments.push(_length);\n this.length = this.segments.reduce((sum, len) => sum + len, 0); // Update total length\n }\n\n /**\n * Finalizes the plot by setting the last angle and pressure.\n * @param {number} _a - The final angle.\n * @param {number} _pres - The final pressure.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n endPlot(_a = 0, _pres = 1, _degrees = false) {\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a);\n this.angles[this.angles.length - 1] = _a; // Update the last angle\n this.pres.push(_pres);\n }\n\n /**\n * Rotates the entire plot by a given angle.\n * @param {number} _a - The angle to rotate the plot.\n */\n rotate(_a) {\n this.dir = toDegrees(_a);\n }\n\n /**\n * Calculates the pressure at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated pressure.\n */\n pressure(_d) {\n // If the distance exceeds the plot length, return the last pressure\n if (_d > this.length) return this.pres[this.pres.length - 1];\n // Otherwise, calculate the pressure using the curving function\n return this.curving(this.pres, _d);\n }\n\n /**\n * Calculates the angle at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The calculated angle.\n */\n angle(_d) {\n // If the distance exceeds the plot length, return the last angle\n if (_d > this.length) return this.angles[this.angles.length - 1];\n // Calculate the index for the given distance\n this.calcIndex(_d);\n // Return the angle, adjusted for the plot type and direction\n return this.type === \"curve\"\n ? this.curving(this.angles, _d) + this.dir\n : this.angles[this.index] + this.dir;\n }\n\n /**\n * Interpolates values between segments for smooth transitions.\n * @param {Array<number>} array - The array to interpolate within.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated value.\n */\n curving(array, _d) {\n let map0 = array[this.index];\n let map1 = array[this.index + 1] ?? map0;\n if (Math.abs(map1 - map0) > 180) {\n if (map1 > map0) map1 = -(360 - map1);\n else map0 = -(360 - map0);\n }\n return map(_d - this.suma, 0, this.segments[this.index], map0, map1, true);\n }\n\n /**\n * Calculates the current index of the plot based on the distance.\n * @param {number} _d - The distance along the plot.\n */\n calcIndex(_d) {\n this.index = -1;\n this.suma = 0;\n let d = 0;\n while (d <= _d) {\n this.suma = d;\n d += this.segments[this.index + 1];\n this.index++;\n }\n return this.index;\n }\n\n /**\n * Generates a polygon based on the plot.\n * @param {number} _x - The x-coordinate for the starting point.\n * @param {number} _y - The y-coordinate for the starting point.\n * @param {number} _scale - The scale factor for the polygon.\n * @param {number} _side - The side factor for the polygon.\n * @returns {Polygon} - The generated polygon.\n */\n genPol(_x, _y, _scale = 1, _side) {\n isFieldReady(); // Ensure that the drawing environment is prepared\n const step = _side < 0 ? 4 : 1;\n const vertices = [];\n const numSteps = Math.round(this.length / step);\n const pos = new Position(_x + Cwidth / 2, _y + Cheight / 2);\n let pside = 0;\n let prevIdx = 0;\n\n for (let i = 0; i < numSteps; i++) {\n pos.plotTo(this, step, step);\n const idx = this.calcIndex(pos.plotted);\n pside += step;\n let maxSize = _side <= 0 ? 8 : Math.max(this.segments[idx] * _side * rr2(0.7, 1.3), 20);\n if ((pside >= maxSize || idx >= prevIdx) && pos.x) {\n vertices.push([pos.x - Cwidth / 2, pos.y - Cheight / 2]);\n pside = 0;\n if (idx >= prevIdx) prevIdx++;\n }\n }\n return new Polygon(vertices);\n }\n\n /**\n * Displays the plot with optional stroke, hatch, and fill effects.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\n show(x, y, scale = 1) {\n if (State.wash) this.wash(x, y, scale);\n if (State.fill) this.fill(x, y, scale);\n if (State.mass) this.mass(x, y, scale);\n if (State.hatch) this.hatch(x, y, scale);\n if (State.stroke) this.draw(x, y, scale);\n }\n}\n","import {\n rr2,\n randInt2,\n sin,\n cos,\n toDegreesSigned,\n constrain,\n dist,\n calcAngle,\n intersectLines,\n} from \"./utils.js\";\nimport { Polygon } from \"./polygon.js\";\nimport { Plot } from \"./plot.js\";\n\n// =============================================================================\n// Section: Primitives and Geommetry\n// =============================================================================\n\n/**\n * Creates a Polygon from an array of points and calls its show() method.\n * Polygons ignore fields and won't be good for fills and masses\n * @param {Array<Array<number>>} pointsArray - Array of points [x, y, pressure]\n */\nexport function polygon(pointsArray) {\n // Create a new Polygon instance\n const polygon = new Polygon(pointsArray);\n polygon.show();\n}\n\n/**\n * Draws a rectangle on the canvas using path functions.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} w - Width.\n * @param {number} h - Height.\n * @param {boolean} [mode=\"corner\"] - \"corner\" (default) or \"center\".\n */\nexport function rect(x, y, w, h, mode = \"corner\") {\n if (mode === \"center\") {\n x -= w / 2;\n y -= h / 2;\n }\n beginShape(0);\n vertex(x, y);\n vertex(x + w, y);\n vertex(x + w, y + h);\n vertex(x, y + h);\n endShape(true);\n}\n\n/**\n * Draws a circle on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Circle radius.\n * @param {boolean} [r=false] - Randomizes segment lengths if true.\n */\nexport function circle(x, y, radius, r = false) {\n const p = new Plot(\"curve\");\n const arcLength = Math.PI * radius;\n const angleOffset = rr2(0, 360);\n const randomFactor = r ? () => 1 + r * 0.2 * rr2() : () => 1;\n\n // Divide circle into 4 segments\n for (let i = 0; i < 4; i++) {\n const angle = -90 * i + angleOffset;\n p.addSegment(\n angle * randomFactor(),\n (arcLength / 2) * randomFactor(),\n 1,\n true,\n );\n }\n\n // Optionally add a random final angle for the last segment\n if (r) {\n const randomAngle = r * randInt2(-5, 5);\n p.addSegment(\n angleOffset,\n Math.abs(randomAngle) * (Math.PI / 180) * radius,\n 1,\n true,\n );\n p.endPlot(randomAngle + angleOffset, 1, true);\n } else {\n p.endPlot(angleOffset, 1, true);\n }\n\n // Draw the circle\n const offsetX = x - radius * sin(angleOffset);\n const offsetY = y - radius * cos(-angleOffset);\n p.show(offsetX, offsetY, 1);\n}\n\n/**\n * Draws an arc on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Radius.\n * @param {number} start - Start angle in the current runtime angle units.\n * @param {number} end - End angle in the current runtime angle units.\n */\nexport function arc(x, y, radius, start, end) {\n const startDeg = toDegreesSigned(start);\n const endDeg = toDegreesSigned(end);\n const sweepDeg = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweepDeg === 0) return;\n\n const p = new Plot(\"curve\");\n const segmentCount = Math.max(1, Math.ceil(sweepDeg / 90));\n const segmentSweep = sweepDeg / segmentCount;\n const arcLength = (Math.PI * radius * segmentSweep) / 180;\n\n for (let i = 0; i < segmentCount; i++) {\n p.addSegment(startDeg + i * segmentSweep + 90, arcLength, 1, true);\n }\n p.endPlot(startDeg + sweepDeg + 90, 1, true);\n\n const startX = x + radius * cos(startDeg);\n const startY = y - radius * sin(startDeg);\n p.draw(startX, startY, 1);\n}\n\n// Variables for managing paths and strokes\nlet _current;\nlet _curvature;\n\nclass SubPath {\n constructor() {\n this.isClosed = false;\n this.curvature = _curvature;\n this.vert = [];\n }\n /**\n * Adds a vertex to this subpath.\n * @param {number} x\n * @param {number} y\n * @param {number} pressure\n */\n vertex(x, y, pressure) {\n this.vert.push([x, y, pressure]);\n }\n /**\n * Renders the subpath by creating a spline from its vertices.\n */\n show() {\n let plot = _createSpline(this.vert, this.curvature, this.isClosed);\n plot.show();\n }\n}\n\n/**\n * Begins a new path with a specified curvature.\n * @param {number} [curvature=0] - Curvature from 0 to 1.\n */\nexport function beginShape(curvature = 0) {\n _curvature = constrain(curvature, 0, 1);\n _current = new SubPath();\n}\n\n/**\n * Adds a line segment from the current point to the given coordinates.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} [pressure=1] - Pressure value.\n */\nexport function vertex(x, y, pressure = 1) {\n if (!_current) {\n throw new Error(\n \"vertex() called outside of beginShape()/endShape(). Call beginShape() first.\",\n );\n }\n _current.vertex(x, y, pressure);\n}\n\n/**\n * Ends the current path and renders all subpaths.\n */\nexport function endShape(close = false) {\n if (!_current) {\n throw new Error(\n \"endShape() called without beginShape(). Call beginShape() first.\",\n );\n }\n if (_current.vert.length < 2) {\n throw new Error(\n \"endShape() requires at least 2 vertices. Add more with vertex().\",\n );\n }\n if (close) {\n _current.vertex(..._current.vert[0]);\n _current.isClosed = true;\n }\n _current.show();\n _current = false;\n}\n\nlet _strokeArray, _strokeOrigin;\n\n/**\n * Begins a new stroke with a given type and starting position.\n * @param {string} type - Stroke type.\n * @param {number} x - Starting x.\n * @param {number} y - Starting y.\n */\nexport function beginStroke(type, x, y) {\n if (type !== \"curve\" && type !== \"segments\") {\n throw new Error(\n `beginStroke() type must be \"curve\" or \"segments\", got \"${type}\".`,\n );\n }\n _strokeOrigin = [x, y];\n _strokeArray = new Plot(type);\n}\n\n/**\n * Adds a segment to the stroke.\n * @param {number} angle - Segment angle.\n * @param {number} length - Segment length.\n * @param {number} pressure - Segment pressure.\n */\nexport function move(angle, length, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"move() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.addSegment(angle, length, pressure);\n}\n\n/**\n * Completes and renders the stroke.\n * @param {number} angle - End angle.\n * @param {number} pressure - End pressure.\n */\nexport function endStroke(angle, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"endStroke() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.endPlot(angle, pressure);\n _strokeArray.draw(_strokeOrigin[0], _strokeOrigin[1], 1);\n _strokeArray = false;\n}\n\n/**\n * Creates and draws a spline curve from an array of points.\n * @param {Array<Array<number>>} array_points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature from 0 to 1.\n */\nexport function spline(_array_points, _curvature = 0.5) {\n if (!_array_points || _array_points.length < 2) {\n throw new Error(\n \"spline() requires at least 2 points. Each point should be [x, y, pressure].\",\n );\n }\n let p = _createSpline(_array_points, _curvature);\n p.draw();\n}\n\n/**\n * Creates a new Plot object representing a spline curve.\n *\n * For curved segments (curvature > 0) with at least 3 points available,\n * the function either treats segments as straight (if their angles match)\n * or calculates control points to compute a circular arc.\n *\n * If no curvature is specified, a simple straight segment is used.\n *\n * @param {Array<Array<number>>} points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature value between 0 and 1.\n * @param {boolean} [close=false] - Whether to close the spline.\n * @returns {Plot} - The generated Plot object.\n */\nfunction _createSpline(points, curvature = 0.5, close = false) {\n const plotType = curvature === 0 ? \"segments\" : \"curve\";\n const p = new Plot(plotType);\n const PI2 = Math.PI * 2;\n\n // If closing the spline, add the second point to the end\n if (close && curvature !== 0) {\n points.push(points[1]);\n }\n\n if (points && points.length > 0) {\n let done = 0; // Tracks excess length from previous segment\n let pep, tep, pep2; // Variables used for initial calibration\n\n for (let i = 0; i < points.length - 1; i++) {\n // For curved segments (if curvature > 0 and there is at least 3 points ahead)\n if (curvature > 0 && i < points.length - 2) {\n const p1 = points[i];\n const p2 = points[i + 1];\n const p3 = points[i + 2];\n\n const d1 = dist(p1[0], p1[1], p2[0], p2[1]);\n const d2 = dist(p2[0], p2[1], p3[0], p3[1]);\n const a1 = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n const a2 = calcAngle(p2[0], p2[1], p3[0], p3[1]);\n\n // Compute the adjustment length based on curvature\n const curvAdjust = curvature * Math.min(d1, d2, 0.5 * Math.min(d1, d2));\n const dmax = Math.max(d1, d2);\n const s1 = d1 - curvAdjust;\n const s2 = d2 - curvAdjust;\n\n if (Math.floor(a1) === Math.floor(a2)) {\n // If angles are nearly the same, treat as a straight segment\n const temp = close ? (i === 0 ? 0 : d1 - done) : d1 - done;\n const temp2 = close ? (i === 0 ? 0 : d2 - pep2) : d2;\n\n p.addSegment(a1, temp, p1[2], true);\n if (i === points.length - 3) {\n p.addSegment(a2, temp2, p2[2], true);\n }\n\n done = 0;\n if (i === 0) {\n pep = d1;\n pep2 = curvAdjust;\n tep = points[1];\n done = 0;\n }\n } else {\n // For a curved segment, compute control points and arc segment details\n const point1 = {\n x: p2[0] - curvAdjust * cos(-a1),\n y: p2[1] - curvAdjust * sin(-a1),\n };\n const point2 = {\n x: point1.x + dmax * cos(-a1 + 90),\n y: point1.y + dmax * sin(-a1 + 90),\n };\n const point3 = {\n x: p2[0] + curvAdjust * cos(-a2),\n y: p2[1] + curvAdjust * sin(-a2),\n };\n const point4 = {\n x: point3.x + dmax * cos(-a2 + 90),\n y: point3.y + dmax * sin(-a2 + 90),\n };\n\n const intPt = intersectLines(point1, point2, point3, point4, true);\n const radius = dist(point1.x, point1.y, intPt.x, intPt.y);\n const halfDist = dist(point1.x, point1.y, point3.x, point3.y) / 2;\n const arcAngle = 2 * Math.asin(halfDist / radius) * (180 / Math.PI);\n const arcLength = (PI2 * radius * arcAngle) / 360;\n\n const temp = close ? (i === 0 ? 0 : s1 - done) : s1 - done;\n const temp2 =\n i === points.length - 3 ? (close ? pep - curvAdjust : s2) : 0;\n\n p.addSegment(a1, temp, p1[2], true);\n p.addSegment(a1, isNaN(arcLength) ? 0 : arcLength, p1[2], true);\n p.addSegment(a2, temp2, p2[2], true);\n\n done = curvAdjust;\n if (i === 0) {\n pep = s1;\n pep2 = curvAdjust;\n tep = [point1.x, point1.y];\n }\n }\n\n if (i === points.length - 3) {\n p.endPlot(a2, p2[2], true);\n }\n } else if (curvature === 0) {\n // If no curvature, add a simple straight segment\n const p1 = points[i];\n const p2 = points[i + 1];\n const d = dist(p1[0], p1[1], p2[0], p2[1]);\n const a = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n\n p.addSegment(a, d, p2[2], true);\n if (i === points.length - 2) {\n p.endPlot(a, 1, true);\n }\n }\n }\n\n p.origin = close && curvature !== 0 ? tep : points[0];\n }\n\n return p;\n}\n","// =============================================================================\n// Stroke Runtime Hooks\n// =============================================================================\n\nlet strokeRuntime = {\n createTipSurface: () => {\n throw new Error(\"No stroke runtime adapter registered.\");\n },\n loadImageTip: () => {\n throw new Error(\"No stroke runtime adapter registered.\");\n },\n};\n\n/**\n * Registers or updates host stroke hooks used by brush-tip loading code.\n *\n * @param {object} hooks\n */\nexport function setStrokeRuntime(hooks) {\n strokeRuntime = { ...strokeRuntime, ...hooks };\n}\n\nexport const createTipSurface = (width, height) =>\n strokeRuntime.createTipSurface(width, height);\nexport const loadImageTip = (src, imageToWhite) =>\n strokeRuntime.loadImageTip(src, imageToWhite);\n","import * as Color from \"../core/color.js\";\nimport { createFramebuffer } from \"../core/compositor_runtime.js\";\n\nlet isStrokeCompositeRegistered = false;\nconst DIRTY_BRUSH_PADDING = 2;\n\n// =============================================================================\n// Section: Helpers\n// =============================================================================\n/**\n * Returns whether the current stroke mask framebuffer must be recreated.\n * This happens when the renderer has no mask yet, or when the canvas size or\n * pixel density changed since the last allocation.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {boolean} True when the stroke mask must be rebuilt.\n */\nfunction needsStrokeMask(Renderer, Cwidth, Cheight, Density) {\n return (\n !Renderer.glMask ||\n Renderer.glMask.width !== Cwidth ||\n Renderer.glMask.height !== Cheight ||\n (typeof Renderer.glMask.pixelDensity === \"function\" &&\n Renderer.glMask.pixelDensity() !== Density)\n );\n}\n\n// =============================================================================\n// Section: Resource Management\n// =============================================================================\n/**\n * Ensures the stroke compositor owns a framebuffer-backed mask with the current\n * canvas dimensions. Stroke stamps are rendered into this mask in WebGL before\n * being blended into the main target.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {object} The framebuffer used as stroke mask.\n */\nexport function ensureStrokeCompositeResources(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n) {\n if (needsStrokeMask(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.glMask?.remove) Renderer.glMask.remove();\n Renderer.glMask = createFramebuffer(Renderer, {\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n }\n\n Renderer.glMask.dirtyRect ??= null;\n Renderer.glMask.isDrawn ??= false;\n return Renderer.glMask;\n}\n\n// =============================================================================\n// Section: Mask Lifecycle\n// =============================================================================\n/**\n * Clears the current stroke mask and resets its bookkeeping flags.\n *\n * @param {object|null} target - Stroke mask framebuffer.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n */\nexport function clearStrokeMask(target, clearTarget) {\n if (!target) return;\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\n}\n\n// =============================================================================\n// Section: Composite Bounds\n// =============================================================================\n/**\n * Returns the rect that should be composited from the stroke mask into the\n * main canvas. Stroke bounds are normally tight dirty rects, but when drawing\n * into an active framebuffer we keep the result conservative and composite the\n * full target.\n *\n * @param {object|null} target - Stroke mask framebuffer.\n * @param {Function} getActiveFramebuffer - Returns the currently bound framebuffer.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} expandDirtyRect - Expands a rect by a constant padding.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @param {number} padding - Extra brush padding in pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\nexport function getStrokeCompositeRect(\n target,\n getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n if (getActiveFramebuffer()) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(target.dirtyRect, DIRTY_BRUSH_PADDING),\n );\n}\n\n/**\n * Returns the resource that should be bound to the blend shader's `u_mask`\n * uniform for stroke compositing.\n *\n * @param {object} _Renderer - Active host renderer.\n * @param {object} mask - Stroke mask framebuffer.\n * @returns {object} Stroke mask framebuffer.\n */\nexport function getStrokeShaderMask(_Renderer, mask) {\n return mask;\n}\n\n// =============================================================================\n// Section: Registration\n// =============================================================================\n/**\n * Registers the stroke compositor with the shared color/composite core.\n * Safe to call multiple times.\n */\nexport function initStrokeComposite() {\n if (isStrokeCompositeRegistered) return;\n Color.registerStrokeComposite?.({\n ensureResources: ensureStrokeCompositeResources,\n clearMask: clearStrokeMask,\n getCompositeRect: getStrokeCompositeRect,\n getShaderMask: getStrokeShaderMask,\n });\n isStrokeCompositeRegistered = true;\n}\n","/**\n * Compiles a shader program from the given vertex and fragment sources.\n * @param {WebGL2RenderingContext} gl - The WebGL2 context.\n * @param {string} vert - Vertex shader source.\n * @param {string} frag - Fragment shader source.\n * @returns {WebGLProgram} The compiled and linked program.\n */\nexport const createProgram = (gl, vert, frag) => {\n const p = gl.createProgram();\n for (let [t, src] of [\n [gl.VERTEX_SHADER, vert],\n [gl.FRAGMENT_SHADER, frag],\n ]) {\n const s = gl.createShader(t);\n gl.shaderSource(s, src);\n gl.compileShader(s);\n gl.attachShader(p, s);\n }\n gl.linkProgram(p);\n return p;\n};\n","// =============================================================================\n// Renderer Runtime Hooks\n// =============================================================================\n\n/**\n * Direct-render hooks used by modules that issue raw WebGL commands.\n *\n * These hooks are intentionally narrow:\n * - begin drawing into an offscreen GL mask target\n * - restore the previous draw target afterward\n * - reset any host-side shader/program bookkeeping after direct GL usage\n */\n\nlet rendererRuntime = {\n beginDirectMaskDraw: () => {\n throw new Error(\"No renderer runtime adapter registered.\");\n },\n endDirectMaskDraw: () => {\n throw new Error(\"No renderer runtime adapter registered.\");\n },\n resetDirectShaderTracking: () => {},\n};\n\n/**\n * Registers or updates host renderer hooks used by direct WebGL drawing paths.\n *\n * @param {object} hooks\n */\nexport function setRendererRuntime(hooks) {\n rendererRuntime = { ...rendererRuntime, ...hooks };\n}\n\nexport const beginDirectMaskDraw = (renderer, gl, target) =>\n rendererRuntime.beginDirectMaskDraw(renderer, gl, target);\nexport const endDirectMaskDraw = (renderer, gl, state) =>\n rendererRuntime.endDirectMaskDraw(renderer, gl, state);\nexport const resetDirectShaderTracking = (renderer, gl) =>\n rendererRuntime.resetDirectShaderTracking(renderer, gl);\n","// =============================================================================\n// Module: GL Draw\n// =============================================================================\n/**\n * The GL Draw module batches brush primitives for WebGL2 rendering. It initializes\n * the shader programs and buffers used by circle-based brushes and image-tip brushes,\n * then flushes those queues into the shared framebuffer-backed brush mask.\n */\n\nimport { Cwidth, Cheight, Density, Renderer } from \"../core/target.js\";\nimport {\n Mix,\n isMixReady,\n State,\n} from \"../core/color.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport {\n beginDirectMaskDraw,\n endDirectMaskDraw,\n resetDirectShaderTracking,\n} from \"../core/renderer_runtime.js\";\nimport { getAffineMatrix } from \"../core/runtime.js\";\nimport vertSrc from \"./shader.vert\";\nimport fragSrc from \"./shader.frag\";\nimport imgVertSrc from \"./image.vert\";\nimport imgFragSrc from \"./image.frag\";\n\n// =============================================================================\n// Section: Initialization and Setup\n// =============================================================================\n\n// Module state\nlet isLoaded = false,\n gl,\n framebufferProjMatrix,\n vao,\n buf,\n program;\nlet loadedWidth = 0,\n loadedHeight = 0;\nlet brushMaskTarget = null;\nconst Attr = {},\n Frag = {};\n\n// Cached matrix values — snapshotted once per stroke in snapshotMatrix()\nlet _ma = 1,\n _mb = 0,\n _mc = 0,\n _md = 1,\n _mx = 0,\n _my = 0,\n _halfW = 0,\n _halfH = 0,\n _scale = 1,\n _density = 1;\n\n/**\n * Snapshots the current runtime affine transform. Call once at the start of each stroke.\n */\nexport function snapshotMatrix() {\n const m = getAffineMatrix();\n _ma = m.a;\n _mb = m.b;\n _mc = m.c;\n _md = m.d;\n _mx = m.x;\n _my = m.y;\n _halfW = Cwidth / 2;\n _halfH = Cheight / 2;\n _scale = Math.sqrt(_ma * _ma + _mb * _mb);\n _density = Density;\n}\n\n// Pre-allocated flat buffer for circle data (x, y, radius, alpha per circle)\nconst INITIAL_CAPACITY = 2048;\nlet circleData = new Float32Array(INITIAL_CAPACITY * 4);\nlet circleCount = 0;\nlet bufferCapacity = INITIAL_CAPACITY;\nlet gpuBufferSize = INITIAL_CAPACITY * 4 * 4; // bytes allocated on GPU\nlet circleDirtyRect = null;\n\n// ---------------------------------------------------------------------------\n// Image instancing state\n// ---------------------------------------------------------------------------\nlet imgProgram = null;\nlet imgVao = null;\nlet imgCornerBuf = null;\nlet imgInstanceBuf = null;\nconst imgAttr = {};\nconst imgFrag = {};\nlet imgGpuSize = 0;\n\nconst IMG_FLOATS = 5; // screenX, screenY, halfSize, angle, alpha — per stamp\nconst IMG_INIT_CAP = 256;\nlet imgData = new Float32Array(IMG_INIT_CAP * IMG_FLOATS);\nlet imgCount = 0;\nlet imgCapacity = IMG_INIT_CAP;\nlet imgDirtyRect = null;\n\n// Texture cache: src string → WebGLTexture (cleared whenever the GL context changes)\nconst texCache = new Map();\n\n// Static unit-quad corners for gl.TRIANGLE_STRIP in quad-local space.\nconst QUAD_CORNERS = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]);\n\nfunction ensureBrushMaskTarget() {\n const rendererMask = Renderer?.glMask;\n if (!rendererMask) return null;\n brushMaskTarget = rendererMask;\n brushMaskTarget.dirtyRect ??= null;\n brushMaskTarget.isDrawn ??= false;\n Mix.glMask = brushMaskTarget;\n return brushMaskTarget;\n}\n\nfunction getProjectionMatrix() {\n return framebufferProjMatrix;\n}\n\nfunction beginMaskTarget() {\n return beginDirectMaskDraw(Renderer, gl, Mix.glMask);\n}\n\nfunction endMaskTarget(state) {\n endDirectMaskDraw(Renderer, gl, state);\n}\n\nfunction accumulateDirtyRect(currentRect, minX, minY, maxX, maxY) {\n if (!currentRect) return { minX, minY, maxX, maxY };\n if (minX < currentRect.minX) currentRect.minX = minX;\n if (minY < currentRect.minY) currentRect.minY = minY;\n if (maxX > currentRect.maxX) currentRect.maxX = maxX;\n if (maxY > currentRect.maxY) currentRect.maxY = maxY;\n return currentRect;\n}\n\n/**\n * Initializes WebGL objects if not done already.\n */\nexport function isReady() {\n isMixReady();\n ensureBrushMaskTarget();\n\n const nextGl = Renderer.drawingContext;\n const needsContextRefresh = !isLoaded || gl !== nextGl;\n const needsProjectionRefresh =\n needsContextRefresh || loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (needsProjectionRefresh) {\n framebufferProjMatrix = new Float32Array([\n 2 / Cwidth,\n 0,\n 0,\n 0,\n 0,\n 2 / Cheight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n -1,\n 0,\n 1,\n ]);\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n }\n\n if (!needsContextRefresh) return;\n\n gl = nextGl;\n\n // Create shader program and initialize\n program = createProgram(gl, vertSrc, fragSrc);\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n // Cache attribute and uniform locations\n [\"a_position\", \"a_radius\", \"a_alpha\"].forEach(\n (n) => (Attr[n] = gl.getAttribLocation(program, n)),\n );\n [\"u_matrix\", \"u_color\"].forEach(\n (n) => (Frag[n] = gl.getUniformLocation(program, n)),\n );\n\n // Create persistent VAO and VBO\n vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n\n buf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n gl.bufferData(gl.ARRAY_BUFFER, circleData.byteLength, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n\n // Set up vertex attributes (only needs to happen once with persistent VAO)\n const stride = 16; // 4 floats × 4 bytes\n gl.enableVertexAttribArray(Attr.a_position);\n gl.vertexAttribPointer(Attr.a_position, 2, gl.FLOAT, false, stride, 0);\n gl.enableVertexAttribArray(Attr.a_radius);\n gl.vertexAttribPointer(Attr.a_radius, 1, gl.FLOAT, false, stride, 8);\n gl.enableVertexAttribArray(Attr.a_alpha);\n gl.vertexAttribPointer(Attr.a_alpha, 1, gl.FLOAT, false, stride, 12);\n\n gl.bindVertexArray(null);\n\n // ------------------------------------------------------------------\n // Image-tip instancing program\n // ------------------------------------------------------------------\n texCache.clear();\n\n imgProgram = createProgram(gl, imgVertSrc, imgFragSrc);\n [\"a_corner\", \"a_pos\", \"a_size\", \"a_angle\", \"a_alpha\"].forEach(\n (n) => (imgAttr[n] = gl.getAttribLocation(imgProgram, n)),\n );\n [\"u_proj\", \"u_color\", \"u_tex\"].forEach(\n (n) => (imgFrag[n] = gl.getUniformLocation(imgProgram, n)),\n );\n\n imgVao = gl.createVertexArray();\n gl.bindVertexArray(imgVao);\n\n // Static corner VBO (per-vertex, no divisor)\n imgCornerBuf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, imgCornerBuf);\n gl.bufferData(gl.ARRAY_BUFFER, QUAD_CORNERS, gl.STATIC_DRAW);\n gl.enableVertexAttribArray(imgAttr.a_corner);\n gl.vertexAttribPointer(imgAttr.a_corner, 2, gl.FLOAT, false, 0, 0);\n\n // Instance data VBO (per-instance)\n imgInstanceBuf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, imgInstanceBuf);\n gl.bufferData(gl.ARRAY_BUFFER, imgData.byteLength, gl.DYNAMIC_DRAW);\n imgGpuSize = imgData.byteLength;\n\n const istride = IMG_FLOATS * 4; // 20 bytes\n gl.enableVertexAttribArray(imgAttr.a_pos);\n gl.vertexAttribPointer(imgAttr.a_pos, 2, gl.FLOAT, false, istride, 0);\n gl.vertexAttribDivisor(imgAttr.a_pos, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_size);\n gl.vertexAttribPointer(imgAttr.a_size, 1, gl.FLOAT, false, istride, 8);\n gl.vertexAttribDivisor(imgAttr.a_size, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_angle);\n gl.vertexAttribPointer(imgAttr.a_angle, 1, gl.FLOAT, false, istride, 12);\n gl.vertexAttribDivisor(imgAttr.a_angle, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_alpha);\n gl.vertexAttribPointer(imgAttr.a_alpha, 1, gl.FLOAT, false, istride, 16);\n gl.vertexAttribDivisor(imgAttr.a_alpha, 1);\n\n gl.bindVertexArray(null);\n\n isLoaded = true;\n}\n\n// =============================================================================\n// Section: Drawing Primitives\n// =============================================================================\n\n/**\n * Queue a circle to be drawn with the specified parameters.\n * Data is written directly into a flat Float32Array to avoid object allocation.\n * Applies the full 2D affine transform (rotation + scale + translation) from\n * the current runtime transform so that brush.rotate() and brush.scale() work correctly.\n */\nexport function circle(x, y, diameter, alpha) {\n // Grow buffer if needed\n if (circleCount >= bufferCapacity) {\n bufferCapacity *= 2;\n const newData = new Float32Array(bufferCapacity * 4);\n newData.set(circleData);\n circleData = newData;\n }\n\n // x/y arrive in \"position space\": user coords + (Cwidth/2, Cheight/2).\n // Subtract the offset to recover user coords, apply the full matrix, then re-add\n // the offset so the result is in screen pixel space [0..Cwidth, 0..Cheight].\n const px = x - _halfW;\n const py = y - _halfH;\n\n const offset = circleCount * 4;\n const screenX = _ma * px + _mc * py + _mx + _halfW;\n const screenY = _mb * px + _md * py + _my + _halfH;\n const radius = (_density * diameter * _scale) / 2;\n\n circleData[offset] = screenX;\n circleData[offset + 1] = screenY;\n // Scale the diameter by the matrix's scale factor (length of the transformed x-axis)\n circleData[offset + 2] = radius;\n circleData[offset + 3] = alpha / 255;\n\n const dScreenX = screenX * _density;\n const dScreenY = screenY * _density;\n circleDirtyRect = accumulateDirtyRect(\n circleDirtyRect,\n dScreenX - radius - 1,\n dScreenY - radius - 1,\n dScreenX + radius + 1,\n dScreenY + radius + 1,\n );\n\n circleCount++;\n}\n\n/**\n * Queue an image stamp to be drawn with instanced rendering.\n * Accepts the same coordinate conventions as circle(): x/y in position space\n * (user coords + Cwidth/2, Cheight/2), size in user-coord units, alpha in [0..255].\n * @param {number} x - X in position space.\n * @param {number} y - Y in position space.\n * @param {number} size - Full stamp diameter in user-coord units.\n * @param {number} angle - Rotation in radians.\n * @param {number} alpha - Opacity [0..255].\n * @param {number} [extraPadding=0] - Conservative extra padding in user units.\n */\nexport function stampImage(x, y, size, angle, alpha, extraPadding = 0) {\n if (imgCount >= imgCapacity) {\n imgCapacity *= 2;\n const next = new Float32Array(imgCapacity * IMG_FLOATS);\n next.set(imgData);\n imgData = next;\n }\n\n const px = x - _halfW;\n const py = y - _halfH;\n const screenX = _ma * px + _mc * py + _mx + _halfW;\n const screenY = _mb * px + _md * py + _my + _halfH;\n const halfSize = (_density * size * _scale) / 2;\n const extraRadius = _density * extraPadding * _scale;\n\n const base = imgCount * IMG_FLOATS;\n imgData[base] = screenX;\n imgData[base + 1] = screenY;\n imgData[base + 2] = halfSize;\n imgData[base + 3] = angle;\n imgData[base + 4] = alpha / 255;\n\n // Bounding box: rotated square worst-case = circle of radius halfSize * √2\n const dScreenX = screenX * _density;\n const dScreenY = screenY * _density;\n const boundsRadius = halfSize * 1.42 + extraRadius;\n imgDirtyRect = accumulateDirtyRect(\n imgDirtyRect,\n dScreenX - boundsRadius - 1,\n dScreenY - boundsRadius - 1,\n dScreenX + boundsRadius + 1,\n dScreenY + boundsRadius + 1,\n );\n\n imgCount++;\n}\n\n/**\n * Flush all queued image stamps in a single instanced draw call.\n * @param {object} p5img - The preprocessed brush-tip image/canvas (from T.tips).\n * @param {string} src - The image src string, used as the texture cache key.\n */\nexport function glDrawImages(p5img, src) {\n if (imgCount === 0) return;\n\n Mix.glMask.isDrawn = true;\n const targetState = beginMaskTarget();\n\n // Lazy-create the WebGL texture from the tip canvas on first use.\n let tex = texCache.get(src);\n if (!tex) {\n tex = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, p5img.canvas);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n texCache.set(src, tex);\n }\n\n gl.useProgram(imgProgram);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.uniform1i(imgFrag.u_tex, 0);\n\n const color = State.stroke.color._array;\n gl.uniform4f(imgFrag.u_color, ...color);\n gl.uniformMatrix4fv(imgFrag.u_proj, false, getProjectionMatrix());\n\n gl.bindVertexArray(imgVao);\n gl.bindBuffer(gl.ARRAY_BUFFER, imgInstanceBuf);\n\n const byteCount = imgCount * IMG_FLOATS * 4;\n const dataView = imgData.subarray(0, imgCount * IMG_FLOATS);\n if (byteCount > imgGpuSize) {\n gl.bufferData(gl.ARRAY_BUFFER, imgData, gl.DYNAMIC_DRAW);\n imgGpuSize = imgData.byteLength;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);\n }\n\n gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, imgCount);\n gl.flush();\n\n gl.bindVertexArray(null);\n gl.bindTexture(gl.TEXTURE_2D, null);\n endMaskTarget(targetState);\n\n if (imgDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, imgDirtyRect);\n imgDirtyRect = null;\n }\n\n imgCount = 0;\n\n // Let the host adapter know we changed the active program.\n resetDirectShaderTracking(Renderer, gl);\n}\n\n/**\n * Removes a cached GL texture by key, forcing re-upload on next draw.\n * Call this when a custom tip function changes after brush.add().\n */\nexport function invalidateTexEntry(key) {\n const tex = texCache.get(key);\n if (tex && gl) gl.deleteTexture(tex);\n texCache.delete(key);\n}\n\n/**\n * Draw all queued circles using WebGL\n */\nexport function glDraw() {\n if (circleCount === 0) return;\n\n Mix.glMask.isDrawn = true;\n const targetState = beginMaskTarget();\n\n const color = State.stroke.color._array;\n\n // Re-activate our shader in case host drawing switched programs.\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n gl.bindVertexArray(vao);\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n\n // Upload vertex data — reallocate GPU buffer only if needed\n const byteCount = circleCount * 16; // 4 floats × 4 bytes\n const dataView = circleData.subarray(0, circleCount * 4);\n if (byteCount > gpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, circleData, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);\n }\n\n // Set uniforms and draw\n gl.uniform4f(Frag.u_color, ...color);\n gl.uniformMatrix4fv(Frag.u_matrix, false, getProjectionMatrix());\n gl.drawArrays(gl.POINTS, 0, circleCount);\n gl.flush();\n\n gl.bindVertexArray(null);\n endMaskTarget(targetState);\n\n if (circleDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, circleDirtyRect);\n circleDirtyRect = null;\n }\n\n // Reset queue (no deallocation)\n circleCount = 0;\n\n // We called gl.useProgram() directly, bypassing host shader tracking.\n // Reset it so the host is forced to re-activate its own shader next time\n // it draws — otherwise it may skip gl.useProgram() and set uniforms on the\n // wrong active program, causing \"location is not from the associated program\".\n resetDirectShaderTracking(Renderer, gl);\n}\n","// =============================================================================\n// Module: Brush\n// =============================================================================\n/**\n * The Brush module provides a comprehensive set of functions and classes for\n * simulating various drawing tools ranging from pens, markers, pencils, to\n * custom image-based brushes. This module controls brush properties such as\n * weight, color, vibration, and spacing, and manages the drawing process through\n * stateful methods that enable features like pressure sensitivity, clipping, and\n * blending. By supporting multiple brush types and dynamic parameter adjustments,\n * the Brush module facilitates the creation of realistic and expressive stroke effects.\n */\n\n// Core imports\nimport { Cwidth, Cheight, Renderer, isCanvasReady } from \"../core/target.js\";\nimport {\n Mix,\n State,\n} from \"../core/color.js\";\nimport {\n rr,\n map,\n dist,\n randInt,\n calcAngle,\n toDegrees,\n gaussian,\n rArray,\n noise,\n _onSeed, \n cos,\n sin\n} from \"../core/utils.js\";\nimport { createColor } from \"../core/runtime.js\";\nimport { Position, isFieldReady } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { createTipSurface, loadImageTip } from \"./runtime.js\";\n\n// Internal module imports\nimport { initStrokeComposite } from \"./composite.js\";\nimport {\n isReady,\n glDraw,\n glDrawImages,\n circle,\n stampImage,\n invalidateTexEntry,\n snapshotMatrix,\n} from \"./gl_draw.js\";\n\ninitStrokeComposite(); // Register the stroke composite system for offscreen mask rendering and compositing.\n\n// ---------------------------------------------------------------------------\n// Brush State and Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Global stroke state settings.\n */\nState.stroke = {\n color: null,\n weight: 1,\n type: \"HB\",\n isActive: false,\n opacity: 1,\n};\n\nlet list = new Map();\n\nconst DEFAULT_CUSTOM_PRESSURE_VARIATION = {\n offset: 0.08,\n scale: 0.08,\n warp: 0.06,\n tilt: 0.06,\n};\n\n/**\n * Retrieves a shallow copy of the current stroke state.\n * @returns {object} The stroke state.\n */\nexport function BrushState() {\n return { ...State.stroke };\n}\n\n/**\n * Updates the stroke state.\n * @param {object} state - The new stroke state.\n */\nexport function BrushSetState(state) {\n State.stroke = { ...state };\n}\n\n// =============================================================================\n// Section: Brush Manager\n// =============================================================================\n\n/**\n * Adds a new brush with the specified parameters to the brush list.\n * @param {string} name - The unique name for the new brush.\n * @param {object} params - The parameters defining the brush behavior and appearance.\n */\n/**\n * Normalizes the pressure parameter to the internal { type, min_max, curve } format.\n * Accepts:\n * [start, end] — linear ramp between two pressure values\n * [start, mid, end] — piecewise linear (e.g. [1.5, 0.5, 1.5] for U-curve)\n * (t) => value — custom function, t ∈ [0,1], return value ∈ [0,1]\n * { mode: \"gaussian\", curve, min_max } — advanced built-in pressure profile\n * { curve, min_max } — legacy gaussian format, preserved for compatibility\n */\nexport function normalizePressure(p) {\n if (!p) return p;\n if (typeof p === \"function\")\n return {\n type: \"custom\",\n min_max: [0, 1],\n curve: p,\n variation: { ...DEFAULT_CUSTOM_PRESSURE_VARIATION },\n };\n if (typeof p === \"object\" && !Array.isArray(p)) {\n if (p.type === \"custom\" || p.mode === \"custom\") {\n const { mode, ...rest } = p;\n return {\n ...rest,\n type: \"custom\",\n variation: {\n ...DEFAULT_CUSTOM_PRESSURE_VARIATION,\n ...(rest.variation ?? {}),\n },\n };\n }\n if (\n p.type === \"gaussian\" ||\n p.mode === \"gaussian\" ||\n (Array.isArray(p.curve) && Array.isArray(p.min_max))\n ) {\n return {\n ...p,\n type: \"gaussian\",\n curve: p.curve,\n min_max: p.min_max,\n };\n }\n return p;\n }\n if (Array.isArray(p)) {\n const [s, m, e] = p.length === 2 ? [p[0], (p[0] + p[1]) / 2, p[1]] : p;\n const min = Math.min(s, m, e),\n max = Math.max(s, m, e);\n const range = max - min || 1;\n const [ns, nm, ne] = [\n (s - min) / range,\n (m - min) / range,\n (e - min) / range,\n ];\n return {\n type: \"custom\",\n min_max: [min, max],\n variation: { ...DEFAULT_CUSTOM_PRESSURE_VARIATION },\n curve: (t) =>\n t < 0.5 ? ns + (nm - ns) * t * 2 : nm + (ne - nm) * (t - 0.5) * 2,\n };\n }\n}\n\nexport function add(name, params) {\n const validTypes = [\"marker\", \"custom\", \"image\", \"spray\"];\n params.type = validTypes.includes(params.type) ? params.type : \"default\";\n if (params.markerTip === undefined) params.markerTip = true;\n if (params.noise === undefined) params.noise = 0.3;\n params.noise = Math.max(0, Math.min(1, params.noise));\n // Accept legacy param names for backward compatibility\n if (params.vibration !== undefined && params.scatter === undefined)\n params.scatter = params.vibration;\n if (params.definition !== undefined && params.sharpness === undefined)\n params.sharpness = params.definition;\n if (params.quality !== undefined && params.grain === undefined)\n params.grain = params.quality;\n params.pressure = normalizePressure(params.pressure);\n if (params.type === \"custom\") {\n if (typeof params.tip !== \"function\") {\n throw new Error(`Brush \"${name}\" is type \"custom\" but is missing a tip function.`);\n }\n // Rasterise the tip once into a 500×500 P2D buffer.\n // Users draw in a 100×100 coordinate space (origin at centre);\n // dark fills/strokes → high opacity, light/white → transparent.\n const key = `custom::${name}`;\n invalidateTexEntry(key); // discard stale GPU texture if tip changed\n const g = createTipSurface(500, 500);\n g.pixelDensity(1);\n g.background(255);\n g.noSmooth();\n g.push();\n g.translate(250, 250); // centre origin\n g.scale(5); // 100 user units → 500 px\n g.noStroke();\n params.tip(g);\n g.pop();\n T.imageToWhite(g); // dark → high alpha, RGB → white for tint\n T.tips.set(key, g);\n params.tipKey = key;\n list.set(name, { param: params, colors: [], buffers: [] });\n return;\n }\n if (params.type === \"image\") {\n if (!params.image || !params.image.src) {\n throw new Error(\n `Brush \"${name}\" is type \"image\" but is missing params.image.src. Example: image: { src: \"./tip.jpg\" }`,\n );\n }\n T.add(params.image.src);\n list.set(name, { param: params, colors: [], buffers: [] });\n return T.load(); // returns a Promise; only loads images not yet loaded\n }\n list.set(name, { param: params, colors: [], buffers: [] });\n}\n\n/**\n * Retrieves the list of available brush names.\n * @returns {Array<string>} Array of brush names.\n */\nexport function box() {\n return [...list.keys()];\n}\n\nexport function getBrushParams(brushName) {\n return list.get(brushName)?.param ?? null;\n}\n\n/**\n * Scales standard brush parameters by the provided factor.\n * @param {number} scaleFactor - The scaling factor to apply.\n */\nexport function scaleBrushes(scaleFactor) {\n for (const { param } of list.values()) {\n if (param) {\n param.weight *= scaleFactor;\n param.scatter *= scaleFactor;\n param.spacing *= scaleFactor;\n }\n }\n}\n\n/**\n * Sets the current brush type by name.\n * @param {string} brushName - The name of the brush.\n */\nexport function pick(brushName) {\n if (!list.has(brushName)) {\n throw new Error(\n `Brush \"${brushName}\" not found. Available brushes: ${[...list.keys()].join(\", \")}.`,\n );\n }\n State.stroke.type = brushName;\n}\n\n/**\n * Sets the stroke style (color) for the current brush.\n * @param {number|string|Color} r - Red component, CSS color string, or Color object.\n * @param {number} [g] - Green component.\n * @param {number} [b] - Blue component.\n */\nexport function stroke(r, g, b) {\n isCanvasReady();\n State.stroke.color = createColor(...arguments);\n State.stroke.isActive = true;\n}\n\n/**\n * Sets the brush weight (thickness).\n * @param {number} weight - The weight value.\n */\nexport function strokeWeight(weight) {\n State.stroke.weight = weight;\n}\n\n/**\n * Sets the current brush with name, color, and weight.\n * @param {string} brushName - The brush name.\n * @param {string|Color} color - The brush color.\n * @param {number} [weight=1] - The brush weight.\n */\nexport function set(brushName, color, weight = 1) {\n pick(brushName);\n stroke(color);\n strokeWeight(weight);\n}\n\n/**\n * Disables the stroke effect.\n */\nexport function noStroke() {\n State.stroke.isActive = false;\n}\n\n/**\n * Defines a clipping region for strokes.\n * The region uses the same coordinate space as brush drawing commands,\n * with the current runtime transform captured at call time.\n * @param {number[]} region - Array as [x1, y1, x2, y2] defining the clipping region.\n */\nexport function clip(region) {\n isCanvasReady();\n return region;\n}\n\n/**\n * Disables the clipping region.\n */\nexport function noClip() {\n return;\n}\n\n// ---------------------------------------------------------------------------\n// Drawing Variables and Functions\n// ---------------------------------------------------------------------------\nlet _position, _length, _plot, _dir;\nconst current = {};\n\n/**\n * Initializes the drawing state.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of stroke.\n * @param {Plot|false} [plot=false] - Plot object for path-following strokes.\n */\nfunction initializeDrawingState(x, y, length, plot = false) {\n snapshotMatrix();\n _position = new Position(x + Cwidth / 2, y + Cheight / 2);\n _length = length;\n _plot = plot;\n if (_plot) _plot.calcIndex(0);\n}\n\nconst gaussians = [];\n\n_onSeed(() => {\n gaussians.length = 0;\n});\n\n/**\n * Executes the drawing operation.\n * @param {number} angleScale - Angle (in degrees) or scaling factor.\n * @param {boolean} isPlot - True if plotting a shape.\n */\nfunction draw(angleScale, isPlot) {\n if (!isPlot) _dir = angleScale;\n saveState();\n\n const stepSize = spacing();\n const totalSteps = Math.round(\n (_length * (isPlot ? angleScale : 1)) / stepSize,\n );\n current.pressureCount = 10;\n current.cachedPressure = undefined;\n current.lineNoiseCount = 5;\n current.cachedLineNoise = undefined;\n\n for (let i = 0; i < totalSteps; i++) {\n if (gaussians.length < totalSteps * 2) {\n gaussians.push(gaussian());\n }\n tip();\n if (isPlot) {\n _position.plotTo(\n _plot,\n stepSize,\n stepSize,\n angleScale,\n i < 10 ? true : false,\n );\n } else {\n _position._moveToDegrees(angleScale, stepSize, stepSize);\n }\n }\n restoreState();\n}\n\n/**\n * Prepares the environment for a brush stroke.\n */\nfunction saveState() {\n current.seed = rr() * 999999;\n const { param } = list.get(State.stroke.type) ?? {};\n if (!param) return;\n current.p = param;\n\n // Set pressure values for the stroke\n const { pressure } = param;\n current.a = pressure.type !== \"custom\" ? rr(-1, 1) : 0;\n current.b = pressure.type !== \"custom\" ? rr(1, 1.5) : 0;\n if (pressure.type !== \"custom\") {\n current.cp = rr(3, 3.5);\n current.ct = 0;\n current.cs = 1;\n current.ck = 0;\n } else {\n const variation = pressure.variation ?? DEFAULT_CUSTOM_PRESSURE_VARIATION;\n current.cp = rr(-variation.offset, variation.offset);\n current.ct = rr(-variation.warp, variation.warp);\n current.cs = rr(1 - variation.scale, 1 + variation.scale);\n current.ck = rr(-variation.tilt, variation.tilt);\n }\n [current.min, current.max] = pressure.min_max;\n\n current.noiseoffset = 0.05 * current.p.noise;\n\n // Cache stroke direction for direction-aware dispersion (non-plot strokes only)\n if (!_plot) {\n current.cos = cos(_dir);\n current.sin = sin(_dir);\n }\n\n // Ensure GL is ready and blend state\n isReady();\n const switchingToBrush = Mix.isBrush !== true;\n Mix.isBrush = true;\n if (switchingToBrush) Mix.justChanged = true;\n Mix.blend(State.stroke.color);\n\n // Set additional state values\n current.alpha = calculateAlpha();\n\n markerTip();\n}\n\n/**\n * Restores drawing state after completing a stroke.\n */\nfunction restoreState() {\n markerTip();\n glDraw();\n const type = current.p?.type;\n if (type === \"image\") glDrawImages(T.tips.get(current.p.image.src), current.p.image.src);\n else if (type === \"custom\") glDrawImages(T.tips.get(current.p.tipKey), current.p.tipKey);\n}\n\n/**\n * Renders the brush tip based on current pressure and position.\n */\nfunction tip() {\n const pressure = calculatePressure();\n const lineNoise = calculateLineNoise();\n\n if (lineNoise > rr(1,1.02) && rr(0,1) < 0.7) return;\n switch (current.p.type) {\n case \"spray\":\n drawSpray(pressure * lineNoise);\n break;\n case \"marker\":\n drawMarker(pressure * lineNoise);\n break;\n case \"custom\":\n case \"image\":\n drawImageTip(pressure * lineNoise);\n break;\n default:\n drawDefault(pressure * lineNoise);\n break;\n }\n}\n\n/**\n * Calculates the effective brush pressure.\n * @returns {number} The calculated pressure.\n */\nfunction calculatePressure() {\n if (current.pressureCount >= 10 || current.cachedPressure === undefined) {\n current.cachedPressure = _plot\n ? simPressure() * _plot.pressure(_position.plotted)\n : simPressure();\n current.pressureCount = 0;\n }\n current.pressureCount++;\n return current.cachedPressure;\n}\n\nfunction calculateLineNoise() {\n if (current.lineNoiseCount >= 10 || current.cachedLineNoise === undefined) {\n current.cachedLineNoise = map(\n noise(current.seed + _position.plotted * 0.01, 0),\n -1,\n 1,\n 1 - current.noiseoffset,\n 1 + current.noiseoffset,\n );\n current.lineNoiseCount = 0;\n }\n current.lineNoiseCount++;\n return current.cachedLineNoise;\n}\n\n/**\n * Simulates brush pressure based on stroke parameters.\n * @returns {number} Simulated pressure value.\n */\nfunction simPressure() {\n const value = current.p.pressure.type === \"custom\"\n ? map(\n current.p.pressure.curve(\n Math.max(\n 0,\n Math.min(\n 1,\n 0.5 + ((_position.plotted / _length) - 0.5 + current.ct) * current.cs,\n ),\n ),\n ) +\n current.cp +\n current.ck * ((_position.plotted / _length) - 0.5),\n 0,\n 1,\n current.min,\n current.max,\n true,\n )\n : gauss();\n return value;\n}\n\n/**\n * Generates a Gaussian-based pressure value.\n * @param {number} [a] - Center parameter.\n * @param {number} [b] - Width parameter.\n * @param {number} [c] - Shape parameter.\n * @param {number} [min] - Minimum pressure.\n * @param {number} [max] - Maximum pressure.\n * @returns {number} Gaussian pressure value.\n */\nfunction gauss(\n a = 0.5 + current.p.pressure.curve[0] * current.a,\n b = 1 - current.p.pressure.curve[1] * current.b,\n c = current.cp,\n min = current.min,\n max = current.max,\n) {\n const peakPos = a * _length;\n const halfWidth =\n (_position.plotted < peakPos ? b * 1.2 : b * 0.8) * (_length / 2);\n return map(\n 1 /\n (1 +\n Math.pow(Math.abs((_position.plotted - peakPos) / halfWidth), 2 * c)),\n 0,\n 1,\n min,\n max,\n );\n}\n\n/**\n * Calculates the alpha (opacity) level for a brush stroke.\n * @returns {number} The calculated opacity.\n */\nfunction calculateAlpha() {\n return [\"default\", \"spray\"].includes(current.p.type)\n ? current.p.opacity\n : current.p.opacity / Math.min(State.stroke.weight, 1.3);\n}\n\n/**\n * Calculates the step spacing based on the current brush parameters.\n * @returns {number} The spacing value.\n */\nfunction spacing() {\n const { param } = list.get(State.stroke.type) ?? {};\n if (!param) return 1;\n return param.spacing;\n}\n\nfunction getImageTipOverscan() {\n const maxPressure = Math.max(1, current.max ?? 1);\n const scatterReach = State.stroke.weight * current.p.scatter;\n const tipReach = State.stroke.weight * current.p.weight * maxPressure;\n\n // Custom/image tips can extend beyond their nominal square because the tip\n // drawing itself may be large and because high scatter creates sparse large\n // stamps near the edge. Keep culling/dirty tracking conservative.\n return Math.max(8, scatterReach * 1.5 + tipReach * 0.75);\n}\n\n// ---------------------------------------------------------------------------\n// Brush Tip Rendering Methods\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the spray tip effect.\n * @param {number} pressure - Current pressure.\n */\nfunction drawSpray(pressure) {\n const vibration =\n State.stroke.weight * current.p.scatter * pressure +\n (State.stroke.weight * rArray(gaussians) * current.p.scatter) / 3;\n const sw = current.p.weight * rr(0.9, 1.1);\n const iterations = Math.ceil(current.p.grain / pressure);\n for (let j = 0; j < iterations; j++) {\n const r = rr(0.9, 1.1);\n const rX = r * vibration * rr(-1, 1);\n const yRandomFactor = rr(-1, 1);\n const sqrtPart = Math.sqrt((r * vibration) ** 2 - rX ** 2);\n circle(\n _position.x + rX,\n _position.y + yRandomFactor * sqrtPart,\n sw,\n current.alpha,\n );\n }\n}\n\n/**\n * Draws the marker tip effect.\n * @param {number} pressure - Current pressure.\n * @param {boolean} [vibrate=true] - Whether to apply vibration.\n */\nfunction drawMarker(pressure, vibrate = true, alpha = current.alpha) {\n const vibration = vibrate ? State.stroke.weight * current.p.scatter : 0;\n const rx = vibrate ? vibration * rr(-1, 1) : 0;\n const ry = vibrate ? vibration * rr(-1, 1) : 0;\n circle(\n _position.x + rx,\n _position.y + ry,\n State.stroke.weight * current.p.weight * pressure,\n alpha * Math.max(0.8, pressure) * rr(0.9,1.1),\n );\n}\n\n/**\n * Queues a stamp for instanced GL rendering.\n * Handles both \"image\" and \"custom\" tip types.\n * @param {number} pressure - Current pressure.\n * @param {number} alpha - Opacity [0..255].\n */\nfunction drawImageTip(pressure, alpha = current.alpha) {\n const vibration = State.stroke.weight * current.p.scatter;\n const rx = vibration * rr(-1, 1);\n const ry = vibration * rr(-1, 1);\n const size = current.p.weight * State.stroke.weight * pressure;\n const overscan = getImageTipOverscan();\n let angle = 0;\n if (current.p.rotate === \"random\") {\n angle = randInt(0, 360) * (Math.PI / 180);\n } else if (current.p.rotate === \"natural\") {\n angle = ((_plot ? -_plot.angle(_position.plotted) : -_dir) + _position.angle()) * (Math.PI / 180);\n }\n stampImage(\n _position.x + rx,\n _position.y + ry,\n size,\n angle,\n alpha * Math.max(0.8, pressure) * rr(0.9, 1.1),\n overscan,\n );\n}\n\n/**\n * Draws the default brush tip.\n * @param {number} pressure - Current pressure.\n */\nfunction drawDefault(pressure, wiggle = 1) {\n wiggle = map(wiggle, 0, 1, 0.9, 1.05);\n const vibration =\n wiggle *\n State.stroke.weight *\n current.p.scatter *\n (current.p.sharpness +\n ((1 - current.p.sharpness) * rArray(gaussians)) / pressure);\n const passesGate = rr(0, current.p.grain * pressure) > 0.4;\n if (passesGate) {\n let dx, dy;\n if (_plot) {\n const plotAngle = _plot.angle(_position.plotted);\n const plotCos = cos(plotAngle);\n const plotSin = sin(plotAngle);\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * plotSin + along * plotCos;\n dy = perp * plotCos - along * plotSin;\n } else {\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * current.sin + along * current.cos;\n dy = perp * current.cos - along * current.sin;\n }\n const diameter =\n pressure *\n pressure *\n current.p.weight *\n rr(0.85, 1.15) *\n State.stroke.weight;\n const alpha = Math.max(0.9, pressure) * current.alpha * rr(0.75, 1.1);\n circle(\n _position.x + dx,\n _position.y + dy,\n diameter,\n alpha,\n );\n }\n}\n\n/**\n * Draws the marker tip with a blend effect.\n */\nfunction markerTip() {\n if (current.p.markerTip === false) return;\n let pressure = calculatePressure();\n let alpha = current.alpha;\n if (current.p.type === \"marker\") {\n for (let s = 1; s < 10; s++) {\n drawMarker((pressure * s) / 10, true, alpha * 8);\n }\n } else if (current.p.type === \"custom\" || current.p.type === \"image\") {\n for (let s = 1; s < 5; s++) {\n drawImageTip((pressure * s) / 10, alpha * 2);\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Basic Drawing Operations\n// ---------------------------------------------------------------------------\n\n/**\n * Draws a line using the current brush.\n * @param {number} x1 - Start x-coordinate.\n * @param {number} y1 - Start y-coordinate.\n * @param {number} x2 - End x-coordinate.\n * @param {number} y2 - End y-coordinate.\n */\nexport function line(x1, y1, x2, y2) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n let d = dist(x1, y1, x2, y2);\n if (d == 0) return;\n initializeDrawingState(x1, y1, d);\n let angle = calcAngle(x1, y1, x2, y2);\n draw(angle, false);\n}\n\n/**\n * Draws a stroke from a starting point in a given direction.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of the stroke.\n * @param {number} dir - Direction, interpreted using the current runtime angle units.\n */\nexport function flowLine(x, y, length, dir) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n initializeDrawingState(x, y, length);\n draw(toDegrees(dir), false);\n}\n\n/**\n * Draws a predefined plot.\n * @param {object} p - Shape object representing the plot.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nfunction plot(p, x, y, scale) {\n isFieldReady();\n initializeDrawingState(x, y, p.length, p);\n draw(scale, true);\n}\n\n// ---------------------------------------------------------------------------\n// Standard Brushes Definition and Initialization\n// ---------------------------------------------------------------------------\n\n/**\n * Defines a set of standard brushes with specific characteristics. Each brush is defined\n * with properties such as weight, scatter, sharpness, grain, opacity, spacing, and\n * pressure sensitivity. Some brushes have additional properties like type, tip, and rotate.\n */\nconst _vals = [\n \"weight\",\n \"scatter\",\n \"sharpness\",\n \"grain\",\n \"opacity\",\n \"spacing\",\n \"pressure\",\n \"type\",\n \"tip\",\n \"rotate\",\n \"markerTip\",\n \"noise\",\n];\nconst _standard_brushes = [\n [\n \"pen\",\n [0.3, 0.15, 0.9, 2, 150, 0.1, { curve: [0.15, 0.2], min_max: [1.2, 1] }],\n ],\n [\n \"rotring\",\n [0.15, 0.05, 0.7, 15, 210, 0.1, { curve: [0.35, 0.2], min_max: [1.3, 1] }],\n ],\n [\n \"2B\",\n [0.3, 0.75, 0.45, 15, 180, 0.1, { curve: [0.1, 0.3], min_max: [1.1, 0.9] }],\n ],\n [\n \"HB\",\n [0.3, 0.6, 0.3, 10, 170, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"2H\",\n [0.2, 0.6, 0.3, 4, 120, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"cpencil\",\n [0.3, 0.55, 0.8, 7, 75, 0.1, { curve: [0.15, 0.2], min_max: [0.95, 1.2] }],\n ],\n [\n \"pastel\",\n [\n 2.05 / 3,\n 13.4 / 3,\n 0.91,\n 28,\n 35,\n 0.085 / 3,\n { mode: \"gaussian\", curve: [0.4, 0.05], min_max: [1.09, 0.93] },\n \"default\",\n undefined,\n \"natural\",\n true,\n 1,\n ],\n ],\n [\n \"crayon\",\n [\n 0.9 / 3,\n 5.45 / 3,\n 0.75,\n 250,\n 159,\n 0.23 / 3,\n [1.1, 0.9],\n \"default\",\n undefined,\n \"natural\",\n true,\n 1,\n ],\n ],\n [\n \"charcoal\",\n [\n 0.35,\n 1.5,\n 0.68,\n 500,\n 120,\n 0.03,\n { curve: [0.15, 0.4], min_max: [1.1, 0.95] },\n ],\n ],\n [\n \"spray\",\n [\n 0.2,\n 6,\n 15,\n 40,\n 90,\n 0.5,\n { curve: [0.2, 0.35], min_max: [0.7, 1] },\n \"spray\",\n ],\n ],\n [\n \"marker\",\n [\n 2,\n 0.2,\n null,\n null,\n 1,\n 0.03,\n { curve: [0.35, 0.25], min_max: [1.2, 0.85] },\n \"marker\",\n ],\n ],\n];\n\nfor (let s of _standard_brushes) {\n let obj = {};\n for (let i = 0; i < s[1].length; i++) obj[_vals[i]] = s[1][i];\n add(s[0], obj);\n}\n\n// ---------------------------------------------------------------------------\n// Extensions to Polygon and Plot Prototypes\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the polygon using the current brush.\n * @param {boolean} [_brush=false] - Optional brush name override.\n * @param {string|Color} [_color] - Optional color override.\n * @param {number} [_weight] - Optional weight override.\n */\nPolygon.prototype.draw = function (_brush = false, _color, _weight) {\n let state = BrushState();\n if (_brush) set(_brush, _color, _weight);\n if (state.isActive) {\n for (let s of this.sides) {\n line(s[0].x, s[0].y, s[1].x, s[1].y);\n }\n }\n BrushSetState(state);\n};\n\n/**\n * Draws the plot using the current brush.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nPlot.prototype.draw = function (x, y, scale) {\n if (BrushState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n plot(this, x, y, scale);\n }\n};\n\n// =============================================================================\n// Section: Loading Custom Image Tips\n// =============================================================================\n/**\n * This section defines the functionality for managing the loading and processing of image tips.\n * Images are loaded from specified source URLs, converted to a white tint for visual effects,\n * and then stored for future use. It includes methods to add new images, convert their color\n * scheme, and integrate them into the active host image pipeline.\n */\n\n/**\n * Manages loading and processing of image tips.\n * Images are converted to white with inverted alpha for tinting via shaders.\n */\nconst T = {\n tips: new Map(),\n\n /**\n * Registers an image source for later loading.\n * @param {string} src - The source URL of the image.\n */\n add(src) {\n if (!this.tips.has(src)) this.tips.set(src, false);\n },\n\n /**\n * Converts image to white with inverted alpha for tint-based rendering.\n * @param {object} image - The host image object to convert.\n */\n imageToWhite(image) {\n image.loadPixels();\n for (let i = 0; i < 4 * image.width * image.height; i += 4) {\n let average =\n (image.pixels[i] + image.pixels[i + 1] + image.pixels[i + 2]) / 3;\n image.pixels[i] = image.pixels[i + 1] = image.pixels[i + 2] = 255;\n image.pixels[i + 3] = 255 - average;\n }\n image.updatePixels();\n },\n\n /**\n * Loads all registered image tips. Returns a promise that resolves\n * when all images are loaded and processed.\n * @returns {Promise}\n */\n async load() {\n const entries = [...this.tips.keys()].filter((k) => !this.tips.get(k));\n await Promise.all(\n entries.map(\n (src) =>\n loadImageTip(src, T.imageToWhite).then((p5img) => {\n this.tips.set(src, p5img);\n }),\n ),\n );\n },\n};\n","import { State } from \"../core/color.js\";\nimport { toDegreesSigned, map, rr } from \"../core/utils.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { BrushState, BrushSetState, set, line } from \"../stroke/stroke.js\";\n\n// =============================================================================\n// Module: Classic Hatch\n// =============================================================================\n\n// ---------------------------------------------------------------------------\n// Hatch State\n// ---------------------------------------------------------------------------\n\nState.hatch = {\n isActive: false,\n dist: 5,\n angle: 45,\n options: {},\n hBrush: false,\n};\n\n/**\n * Returns a shallow snapshot of the current hatch modifier state.\n *\n * @returns {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}}\n */\nexport function HatchState() {\n return { ...State.hatch };\n}\n\n/**\n * Restores hatch modifier state from a previously captured snapshot.\n *\n * @param {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}} state\n */\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Activates classic scanline hatching for subsequent shapes.\n *\n * @param {number} [dist=5] Distance between scanlines.\n * @param {number} [angle=45] Hatch angle in the current runtime angle units.\n * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [options]\n */\nexport function hatch(\n dist = 5,\n angle = 45,\n options = { rand: false, continuous: false, gradient: false }\n) {\n let s = State.hatch;\n s.isActive = true;\n s.dist = dist;\n s.angle = toDegreesSigned(angle);\n s.options = options;\n}\n\n/**\n * Overrides the brush, color, and weight used specifically for hatch strokes.\n *\n * @param {string} brush\n * @param {string|object} [color=\"black\"]\n * @param {number} [weight=1]\n */\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\n/**\n * Deactivates hatching and clears any hatch-specific brush override.\n */\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Scanline Generation\n// ---------------------------------------------------------------------------\n\n/**\n * Computes hatch segments for one polygon by rotating it into scanline space,\n * intersecting horizontal scanlines against its edges, and rotating the\n * resulting segments back into canvas space.\n *\n * @param {Polygon} polygon\n * @param {number} angle Hatch angle in degrees.\n * @param {number} dist Base scanline spacing.\n * @param {number} gradient Multiplicative spacing growth per scanline.\n * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}\n */\nfunction scanlineHatch(polygon, angle, dist, gradient) {\n const rad = (angle * Math.PI) / 180;\n const cosA = Math.cos(rad),\n sinA = Math.sin(rad);\n const cosB = Math.cos(-rad),\n sinB = Math.sin(-rad);\n\n const verts = polygon.a,\n n = verts.length;\n\n // Rotate vertices; track Y extent\n const rotated = new Array(n);\n let minY = Infinity,\n maxY = -Infinity;\n for (let i = 0; i < n; i++) {\n const x = verts[i][0],\n y = verts[i][1];\n const r = [x * cosA - y * sinA, x * sinA + y * cosA];\n rotated[i] = r;\n if (r[1] < minY) minY = r[1];\n if (r[1] > maxY) maxY = r[1];\n }\n\n // Build edge list (skip horizontal edges)\n const edges = [];\n for (let i = 0; i < n; i++) {\n const a = rotated[i],\n b = rotated[(i + 1) % n];\n if (a[1] !== b[1]) edges.push(a, b);\n }\n const eLen = edges.length;\n\n // Scan, find crossings, rotate back\n const segments = [];\n const cx = [];\n let Y = minY + dist * 0.5,\n step = dist;\n while (Y < maxY) {\n cx.length = 0;\n for (let i = 0; i < eLen; i += 2) {\n const y1 = edges[i][1],\n y2 = edges[i + 1][1];\n if ((y1 <= Y && Y < y2) || (y2 <= Y && Y < y1))\n cx.push(\n edges[i][0] + ((Y - y1) / (y2 - y1)) * (edges[i + 1][0] - edges[i][0])\n );\n }\n cx.sort((a, b) => a - b);\n for (let i = 0; i < cx.length - 1; i += 2) {\n segments.push({\n scanY: Y,\n x1: cx[i] * cosB - Y * sinB,\n y1: cx[i] * sinB + Y * cosB,\n x2: cx[i + 1] * cosB - Y * sinB,\n y2: cx[i + 1] * sinB + Y * cosB,\n });\n }\n Y += step;\n step *= gradient;\n }\n return segments;\n}\n\n/**\n * Collects and orders hatch segments for one polygon or a polygon list.\n *\n * Segments are sorted in scanline traversal order so downstream rendering can\n * optionally connect them into a continuous serpentine path.\n *\n * @param {Polygon|Polygon[]} polygons\n * @param {number} dist\n * @param {number} angle\n * @param {number} gradient\n * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}\n */\nfunction getHatchSegments(polygons, dist, angle, gradient) {\n if (!Array.isArray(polygons)) polygons = [polygons];\n const segs = [];\n for (const poly of polygons) {\n for (const s of scanlineHatch(poly, angle, dist, gradient)) segs.push(s);\n }\n segs.sort((a, b) => (a.scanY === b.scanY ? a.x1 - b.x1 : a.scanY - b.scanY));\n return segs;\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Configuration\n// ---------------------------------------------------------------------------\n\n/**\n * Runs hatch drawing with the temporary hatch-specific brush style if one is active,\n * then restores the outer stroke state.\n *\n * @param {() => void} drawFn\n */\nfunction withHatchStyle(drawFn) {\n const save = BrushState();\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n drawFn();\n BrushSetState(save);\n}\n\n/**\n * Resolves the active hatch parameters and precomputes the ordered scanline segments.\n *\n * @param {Polygon|Polygon[]} polygons\n * @returns {{dist:number, options:Object, segs:Object[]}}\n */\nfunction getActiveHatchConfig(polygons) {\n const dist = State.hatch.dist;\n const angle = ((State.hatch.angle % 180) + 180) % 180;\n const options = State.hatch.options;\n const gradient = options.gradient ? map(options.gradient, 0, 1, 1, 1.1, true) : 1;\n const segs = getHatchSegments(polygons, dist, angle, gradient);\n return { dist, options, segs };\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Lines\n// ---------------------------------------------------------------------------\n\n/**\n * Expands ordered hatch segments into the actual line list that will be drawn.\n *\n * This includes endpoint jitter when `rand` is active and inserts the serpentine\n * connector lines when `continuous` is enabled.\n *\n * @param {Polygon|Polygon[]} polygons\n * @returns {{x1:number, y1:number, x2:number, y2:number, scanY:number, isConnector:boolean}[]}\n */\nexport function getHatchLines(polygons) {\n const { dist, options, segs } = getActiveHatchConfig(polygons);\n const r = options.rand || 0;\n const lines = [];\n\n for (let j = 0; j < segs.length; j++) {\n const s = segs[j];\n let x1 = s.x1, y1 = s.y1, x2 = s.x2, y2 = s.y2;\n if (r) {\n x1 += 2 * r * dist * rr(-1, 1);\n y1 += 2 * r * dist * rr(-1, 1);\n x2 += 2 * r * dist * rr(-1, 1);\n y2 += 2 * r * dist * rr(-1, 1);\n }\n const reverse = options.continuous && j % 2 === 1;\n const line = reverse\n ? { x1: x2, y1: y2, x2: x1, y2: y1, scanY: s.scanY, isConnector: false }\n : { x1, y1, x2, y2, scanY: s.scanY, isConnector: false };\n lines.push(line);\n if (j > 0 && options.continuous) {\n const prev = lines[lines.length - 2];\n lines.push({\n x1: prev.x2,\n y1: prev.y2,\n x2: line.x1,\n y2: line.y1,\n scanY: s.scanY,\n isConnector: true,\n });\n }\n }\n\n return lines;\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Rendering\n// ---------------------------------------------------------------------------\n\n/**\n * Iterates the generated hatch lines and delegates the actual rendering of each\n * segment to the provided callback.\n *\n * @param {Polygon|Polygon[]} polygons\n * @param {(x1:number, y1:number, x2:number, y2:number, index:number, segs:Object[]) => void} drawSegment\n */\nfunction renderHatchSegments(polygons, drawSegment) {\n const segs = getHatchLines(polygons);\n withHatchStyle(() => {\n for (let j = 0; j < segs.length; j++) {\n const s = segs[j];\n drawSegment(s.x1, s.y1, s.x2, s.y2, j, segs);\n }\n });\n}\n\n/**\n * Draws classic hatch lines over one polygon or an array of polygons.\n *\n * @param {Polygon|Polygon[]} polygons\n */\nexport function createHatch(polygons) {\n renderHatchSegments(polygons, (x1, y1, x2, y2) => {\n line(x1, y1, x2, y2);\n });\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Applies the currently active hatch modifier to a polygon, or temporarily\n * overrides hatch parameters for this call only.\n *\n * @param {number|false} [_dist=false]\n * @param {number} [_angle]\n * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [_options]\n */\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (State.hatch.isActive) createHatch(this);\n HatchSetState(state);\n};\n\n/**\n * Converts the plot to a polygon and applies the currently active hatch modifier.\n *\n * @param {number} x\n * @param {number} y\n * @param {number} scale\n */\nPlot.prototype.hatch = function (x, y, scale) {\n if (HatchState().isActive) {\n if (this.origin) (x = this.origin[0]), (y = this.origin[1]), (scale = 1);\n this.pol = this.genPol(x, y, scale, 0.3);\n this.pol.hatch();\n }\n};\n","// =============================================================================\n// Module: Mass\n// =============================================================================\n\nimport { State } from \"../core/color.js\";\nimport { arc } from \"../core/primitives.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { rr2, dist, calcAngle } from \"../core/utils.js\";\nimport { fromDegrees, usesRadians } from \"../core/runtime.js\";\nimport { HatchState, HatchSetState, hatch, getHatchLines } from \"./hatch.js\";\nimport { BrushState, BrushSetState, getBrushParams, set } from \"../stroke/stroke.js\";\nimport { wiggle } from \"../core/flowfield.js\";\n\n// ---------------------------------------------------------------------------\n// Mass State\n// ---------------------------------------------------------------------------\n\nState.mass = {\n isActive: false,\n brush: null,\n color: null,\n options: {},\n};\n\n/**\n * Returns a shallow copy of the current mass state.\n * @returns {object}\n */\nexport function MassState() {\n return { ...State.mass };\n}\n\n/**\n * Restores a previously saved mass state.\n * @param {object} state\n */\nexport function MassSetState(state) {\n State.mass = { ...state };\n}\n\n/**\n * Enables massing mode with a brush, color, and optional configuration.\n *\n * @param {string} brush - Brush name to use for the mass pass.\n * @param {string|Color} color - Color to use for the mass pass.\n * @param {object} [options={}] - Massing options such as precision, strength, gradient, and outline.\n */\nexport function mass(brush, color, options = {}) {\n State.mass.brush = brush;\n State.mass.color = color;\n State.mass.options = options;\n State.mass.isActive = true;\n}\n\n/**\n * Disables massing mode for subsequent geometry.\n */\nexport function noMass() {\n State.mass.isActive = false;\n State.mass.brush = null;\n State.mass.color = null;\n State.mass.options = {};\n}\n\n// ---------------------------------------------------------------------------\n// Polygon Preparation\n// ---------------------------------------------------------------------------\n\n/**\n * Returns a translated copy of a polygon.\n * Used to build the secondary mass layers from an existing base polygon.\n * @param {Polygon} polygon\n * @param {number} jitterX\n * @param {number} jitterY\n * @returns {Polygon}\n */\nfunction jitterPolygon(polygon, jitterX, jitterY) {\n return new Polygon(\n polygon.vertices.map((vertex) => [vertex.x + jitterX, vertex.y + jitterY]),\n );\n}\n\n/**\n * Builds the three polygons used for a mass pass.\n * Both polygon and plot inputs use one base polygon plus two translated copies,\n * so plot-based massing only needs a single `genPol(...)` call.\n * @param {Polygon|Plot} shape\n * @param {number|false} x\n * @param {number} y\n * @param {number} scale\n * @returns {Polygon[]}\n */\nfunction getMassPolygons(shape, x, y, scale) {\n const isPolygon = x === false;\n const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;\n const basePolygon = isPolygon ? shape : shape.genPol(x, y, scale, 0.15);\n const maxJitter = Math.min(scatter * 2, 5);\n const jitters = [\n [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],\n [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],\n ];\n\n return [\n basePolygon,\n jitterPolygon(basePolygon, jitters[0][0], jitters[0][1]),\n jitterPolygon(basePolygon, jitters[1][0], jitters[1][1]),\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Angle & Bounds Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Converts degree values into the current runtime angle units.\n * @param {number} angle\n * @returns {number}\n */\nfunction getAngleConverter() {\n return usesRadians()\n ? (angle) => (angle * Math.PI) / 180\n : (angle) => angle;\n}\n\n/**\n * Computes an axis-aligned bounding box for a polygon.\n * The diagonal is used as a size reference for pivot distance.\n * @param {Polygon} polygon\n * @returns {{minX:number,minY:number,maxX:number,maxY:number,cx:number,cy:number,size:number}}\n */\nfunction getPolygonBounds(polygon) {\n const points = polygon?.a ?? [];\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n for (const [x, y] of points) {\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n return {\n minX,\n minY,\n maxX,\n maxY,\n cx: (minX + maxX) / 2,\n cy: (minY + maxY) / 2,\n size: Math.hypot(maxX - minX, maxY - minY),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Pivot Geometry\n// ---------------------------------------------------------------------------\n\n/**\n * Chooses the diagonal corner family for a whole mass gesture.\n * Positive-angle hatching uses either bottom-right or top-left; negative-angle\n * hatching uses either bottom-left or top-right.\n * @param {number} angleDeg\n * @returns {[number, number]}\n */\nfunction getPivotBias(angleDeg) {\n const normalizedAngle = ((((angleDeg + 90) % 180) + 180) % 180) - 90;\n if (normalizedAngle >= 0) {\n return rr2() < 0.5 ? [1, 1] : [-1, -1];\n } else {\n return rr2() < 0.5 ? [-1, 1] : [1, -1];\n }\n}\n\n/**\n * Places the global pivot anchor outside the polygon, along the selected bias.\n * Distance varies per layer while the bias stays fixed for the whole mass.\n * @param {Polygon} polygon\n * @param {[number, number]} bias\n * @returns {{x:number,y:number}}\n */\nfunction getPivotAnchor(polygon, bias) {\n const bounds = getPolygonBounds(polygon);\n const offset = bounds.size * rr2(0.6, 1.4);\n const [sx, sy] = bias;\n return {\n x: bounds.cx + sx * offset,\n y: bounds.cy + sy * offset,\n };\n}\n\n/**\n * Projects the global pivot anchor onto the perpendicular bisector of a line.\n * This yields a valid circle center equidistant from both endpoints.\n * @param {{x:number,y:number}} anchor\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {{x:number,y:number}|null}\n */\nfunction projectAnchorToBisector(anchor, x1, y1, x2, y2) {\n const mx = (x1 + x2) / 2;\n const my = (y1 + y2) / 2;\n const dx = x2 - x1;\n const dy = y2 - y1;\n const length = Math.hypot(dx, dy);\n if (!length) return null;\n const nx = -dy / length;\n const ny = dx / length;\n const offset = (anchor.x - mx) * nx + (anchor.y - my) * ny;\n return {\n x: mx + nx * offset,\n y: my + ny * offset,\n };\n}\n\n/**\n * Returns the shortest arc between two endpoints around a given center.\n * The returned angles are already converted into the current runtime angle units.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {[number, number]}\n */\nfunction getShortArcAngles(cx, cy, x1, y1, x2, y2, toAngleUnit) {\n let startDeg = calcAngle(cx, cy, x1, y1);\n let endDeg = calcAngle(cx, cy, x2, y2);\n const sweep = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweep > 180) [startDeg, endDeg] = [endDeg, startDeg];\n return [\n toAngleUnit(startDeg),\n toAngleUnit(endDeg),\n ];\n}\n\n/**\n * Splits a hatch line into two slightly separated segments so some gestures\n * read as interrupted rather than perfectly continuous.\n * @param {{x1:number,y1:number,x2:number,y2:number}} seg\n * @returns {Array<{x1:number,y1:number,x2:number,y2:number}>}\n */\nfunction splitSegment(seg) {\n const t = rr2(0.35, 0.65);\n const mx = seg.x1 + (seg.x2 - seg.x1) * t;\n const my = seg.y1 + (seg.y2 - seg.y1) * t;\n const dx = seg.x2 - seg.x1;\n const dy = seg.y2 - seg.y1;\n const length = Math.hypot(dx, dy) || 1;\n const gap = rr2(0.04, 0.1) * length;\n const gx = (dx / length) * gap * 0.5;\n const gy = (dy / length) * gap * 0.5;\n return [\n { x1: seg.x1, y1: seg.y1, x2: mx - gx, y2: my - gy },\n { x1: mx + gx, y1: my + gy, x2: seg.x2, y2: seg.y2 },\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Mass Rendering\n// ---------------------------------------------------------------------------\n\n/**\n * Draws one polygon of the mass as a family of arcs derived from hatch lines.\n * The same pivot bias is used across layers, while each layer gets its own\n * anchor distance from the shape.\n * @param {Polygon} polygon\n * @param {[number, number]} pivotBias\n */\nfunction drawMassArcs(polygon, pivotBias, toAngleUnit) {\n const anchor = getPivotAnchor(polygon, pivotBias);\n for (const seg of getHatchLines(polygon)) {\n const parts = !seg.isConnector && rr2() < 0.35 ? splitSegment(seg) : [seg];\n for (const part of parts) {\n const center = projectAnchorToBisector(anchor, part.x1, part.y1, part.x2, part.y2);\n if (!center) continue;\n const radius = dist(center.x, center.y, part.x1, part.y1);\n if (!radius) continue;\n const [startAngle, endAngle] = getShortArcAngles(\n center.x,\n center.y,\n part.x1,\n part.y1,\n part.x2,\n part.y2,\n toAngleUnit,\n );\n arc(center.x, center.y, radius, startAngle, endAngle);\n }\n }\n}\n\n/**\n * Configures a hatch pass and immediately reinterprets the generated lines as arcs.\n * @param {Polygon} polygon\n * @param {number} dist\n * @param {number} angle\n * @param {object} options\n * @param {[number, number]} pivotBias\n */\nfunction drawMassPass(polygon, dist, angle, options, pivotBias, toAngleUnit) {\n hatch(dist, angle, options);\n drawMassArcs(polygon, pivotBias, toAngleUnit);\n}\n\n/**\n * Creates the built-in \"massing\" effect for a polygon or plot.\n * A mass is built from up to three jittered polygon layers, each hatched and\n * then redrawn as arc gestures around a shared pivot bias.\n * @param {Polygon|Plot} shape\n * @param {number|false} x\n * @param {number} y\n * @param {number} scale\n */\nexport function createMass(shape, x, y, scale) {\n const pols = getMassPolygons(shape, x, y, scale);\n const hatchState = HatchState();\n const brushState = BrushState();\n const fieldState = { ...State.field };\n const precision = State.mass.options?.precision ?? 0.5;\n const strength = State.mass.options?.strength ?? 1;\n const gradient = State.mass.options?.gradient ?? 0.1;\n const outline = State.mass.options?.outline ?? false;\n const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;\n const hatchDist = 1.6 * rr2(scatter * 0.65, scatter * 0.85) - 0.4 * gradient;\n const baseAngle = rr2(-90, 90);\n const pivotBias = getPivotBias(baseAngle);\n const toAngleUnit = getAngleConverter();\n\n set(State.mass.brush, State.mass.color, 1);\n wiggle(2 - precision);\n if (outline) pols[0].draw();\n\n drawMassPass(\n pols[0],\n hatchDist * 0.9,\n fromDegrees(baseAngle),\n {\n gradient,\n rand: 2 - 2 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n\n if (strength > 0.33) {\n drawMassPass(\n pols[1],\n hatchDist,\n fromDegrees(baseAngle + 20 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n }\n\n if (strength > 0.66) {\n drawMassPass(\n pols[2],\n hatchDist * 0.8,\n fromDegrees(baseAngle + 15 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n }\n\n BrushSetState(brushState);\n HatchSetState(hatchState);\n State.field = { ...fieldState };\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Applies massing to polygon geometry.\n */\nPolygon.prototype.mass = function () {\n if (State.mass?.isActive) {\n createMass(this, false);\n }\n};\n\n/**\n * Applies massing to plots by generating their polygon first.\n * @param {number} x\n * @param {number} y\n * @param {number} scale\n */\nPlot.prototype.mass = function (x, y, scale) {\n if (State.mass?.isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n createMass(this, x, y, scale);\n }\n};\n","import { Mix } from \"../core/color.js\";\n\nfunction strokePadding(ctx, matrix) {\n const lineWidth = ctx.lineWidth || 0;\n if (lineWidth <= 0) return 1;\n\n return (\n 1 +\n (lineWidth * Math.max(Math.hypot(matrix.a, matrix.c), Math.hypot(matrix.b, matrix.d))) /\n 2\n );\n}\n\n// =============================================================================\n// Section: Draw shapes to Mask Buffers\n// =============================================================================\n\n/**\n * Draws a polygon to the mask using the provided vertices.\n * @param {Array<{x: number, y: number}>} vertices - Array of vertex coordinates.\n */\nexport function drawPolygon(vertices) {\n const ctx = Mix.ctx;\n const matrix = ctx.getTransform();\n // Cache the current 2D transform once so the hot loop can stay numeric and\n // avoid repeated property reads while we build bounds.\n const a = matrix.a;\n const b = matrix.b;\n const c = matrix.c;\n const d = matrix.d;\n const e = matrix.e;\n const f = matrix.f;\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n\n ctx.beginPath();\n\n // Seed both the path and the transformed bounds from the first vertex so the\n // loop below only needs to append line segments.\n const first = vertices[0];\n let tx = a * first.x + c * first.y + e;\n let ty = b * first.x + d * first.y + f;\n minX = maxX = tx;\n minY = maxY = ty;\n\n ctx.moveTo(first.x, first.y);\n\n for (let i = 1; i < vertices.length; i++) {\n const v = vertices[i];\n\n // Track the transformed bounds in canvas space while we build the path so\n // dirty-rect bookkeeping does not need a second pass over the vertices.\n tx = a * v.x + c * v.y + e;\n ty = b * v.x + d * v.y + f;\n minX = Math.min(minX, tx);\n minY = Math.min(minY, ty);\n maxX = Math.max(maxX, tx);\n maxY = Math.max(maxY, ty);\n\n ctx.lineTo(v.x, v.y);\n }\n\n ctx.closePath();\n\n // Expand by stroke width so the later composite pass copies enough pixels\n // even when the polygon border extends outside the raw vertex bounds.\n const padding = strokePadding(ctx, matrix);\n Mix.markDirtyRect(Mix.mask, {\n minX: minX - padding,\n minY: minY - padding,\n maxX: maxX + padding,\n maxY: maxY + padding,\n });\n}\n\n/**\n * Draws a circle to the mask.\n * @param {number} x - X-coordinate of the circle's center.\n * @param {number} y - Y-coordinate of the circle's center.\n * @param {number} d - Diameter of the circle.\n */\nexport function circle(x, y, d) {\n const PI2 = Math.PI * 2;\n const ctx = Mix.ctx;\n const radius = d / 2;\n\n ctx.moveTo(x + radius, y);\n ctx.arc(x, y, radius, 0, PI2);\n}\n","import * as Color from \"../core/color.js\";\nimport {\n createFramebuffer,\n create2DCanvas,\n} from \"../core/compositor_runtime.js\";\n\n// Small staging canvas used to upload only the dirty fill sub-rect into the\n// framebuffer-backed mask mirror consumed by the blend shader.\nlet FillMaskUploadCanvas = null;\nlet isFillCompositeRegistered = false;\nconst DIRTY_FILL_PADDING = 4;\n\n// =============================================================================\n// Section: Helpers\n// =============================================================================\n/**\n * Returns whether the CPU-side 2D fill mask must be recreated.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} maskWidth - Mask width in physical pixels.\n * @param {number} maskHeight - Mask height in physical pixels.\n * @returns {boolean} True when the 2D fill mask needs reallocation.\n */\nfunction needsFillMaskCanvas(Renderer, maskWidth, maskHeight) {\n return (\n !Renderer.mask ||\n Renderer.mask.width !== maskWidth ||\n Renderer.mask.height !== maskHeight\n );\n}\n\n/**\n * Returns whether the framebuffer-backed fill mask mirror must be recreated.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {boolean} True when the fill mask framebuffer needs reallocation.\n */\nfunction needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density) {\n return (\n !Renderer.fillMaskFramebuffer ||\n Renderer.fillMaskFramebuffer.width !== Cwidth ||\n Renderer.fillMaskFramebuffer.height !== Cheight ||\n (typeof Renderer.fillMaskFramebuffer.pixelDensity === \"function\" &&\n Renderer.fillMaskFramebuffer.pixelDensity() !== Density)\n );\n}\n\n// =============================================================================\n// Section: Resource Management\n// =============================================================================\n/**\n * Ensures fill compositing resources exist for the active renderer.\n *\n * Fill draws first into a CPU-side 2D mask canvas. That mask is later uploaded,\n * dirty-rect by dirty-rect, into a framebuffer-backed mirror used by the final\n * blend shader pass.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n * @returns {{mask: object, ctx: CanvasRenderingContext2D}} Fill mask resources.\n */\nexport function ensureFillCompositeResources(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n clearTarget,\n) {\n const maskWidth = Math.max(1, Math.round(Cwidth * Density));\n const maskHeight = Math.max(1, Math.round(Cheight * Density));\n\n if (needsFillMaskCanvas(Renderer, maskWidth, maskHeight)) {\n Renderer.mask = create2DCanvas(maskWidth, maskHeight);\n }\n\n if (needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.fillMaskFramebuffer?.remove) {\n Renderer.fillMaskFramebuffer.remove();\n }\n Renderer.fillMaskFramebuffer = createFramebuffer(Renderer, {\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n clearTarget(Renderer.fillMaskFramebuffer);\n }\n\n Renderer.mask.dirtyRect ??= null;\n Renderer.mask.isDrawn ??= false;\n Renderer.mask.drawingContext.imageSmoothingEnabled = false;\n return {\n mask: Renderer.mask,\n ctx: Renderer.mask.drawingContext,\n };\n}\n\n// =============================================================================\n// Section: Mask Lifecycle\n// =============================================================================\n/**\n * Clears the current fill mask and resets its bookkeeping flags.\n *\n * @param {object|null} target - Fill mask canvas or framebuffer mirror.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n */\nexport function clearFillMask(target, clearTarget) {\n if (!target) return;\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\n}\n\n// =============================================================================\n// Section: Composite Bounds\n// =============================================================================\n/**\n * Returns the fill dirty rect to composite into the main target. Fill bounds are\n * taken directly from the accumulated 2D mask dirty area plus a small padding.\n *\n * @param {object|null} target - Fill mask canvas.\n * @param {Function} _getActiveFramebuffer - Unused for fill masks.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} expandDirtyRect - Expands a rect by a constant padding.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\nexport function getFillCompositeRect(\n target,\n _getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(target.dirtyRect, DIRTY_FILL_PADDING),\n );\n}\n\n// =============================================================================\n// Section: Upload\n// =============================================================================\n/**\n * Uploads only the dirty portion of the CPU-side 2D fill mask into the\n * framebuffer-backed fill mask mirror used by the shader compositor.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {object} mask - CPU-side 2D fill mask canvas.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} dirtyRect - Dirty rect to upload.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n * @returns {object} Framebuffer-backed fill mask mirror.\n */\nexport function getFillShaderMask(\n Renderer,\n mask,\n dirtyRect,\n normalizeDirtyRect,\n getFullDirtyRect,\n clearTarget,\n) {\n const target = Renderer.fillMaskFramebuffer;\n const gl = Renderer.drawingContext;\n const uploadRect = normalizeDirtyRect(dirtyRect) ?? getFullDirtyRect();\n const uploadWidth = uploadRect.maxX - uploadRect.minX;\n const uploadHeight = uploadRect.maxY - uploadRect.minY;\n\n if (\n !FillMaskUploadCanvas ||\n FillMaskUploadCanvas.width !== uploadWidth ||\n FillMaskUploadCanvas.height !== uploadHeight\n ) {\n FillMaskUploadCanvas = create2DCanvas(uploadWidth, uploadHeight);\n }\n\n const uploadContext = FillMaskUploadCanvas.drawingContext;\n uploadContext.clearRect(0, 0, uploadWidth, uploadHeight);\n uploadContext.drawImage(\n mask,\n uploadRect.minX,\n uploadRect.minY,\n uploadWidth,\n uploadHeight,\n 0,\n 0,\n uploadWidth,\n uploadHeight,\n );\n\n clearTarget(target);\n gl.bindTexture(gl.TEXTURE_2D, target.colorTexture);\n gl.texSubImage2D(\n gl.TEXTURE_2D,\n 0,\n uploadRect.minX,\n uploadRect.minY,\n gl.RGBA,\n gl.UNSIGNED_BYTE,\n FillMaskUploadCanvas,\n );\n return target;\n}\n\n// =============================================================================\n// Section: Registration\n// =============================================================================\n/**\n * Registers the fill compositor with the shared color/composite core.\n * Safe to call multiple times.\n */\nexport function initFillComposite() {\n if (isFillCompositeRegistered) return;\n Color.registerFillComposite?.({\n ensureResources: ensureFillCompositeResources,\n clearMask: clearFillMask,\n getCompositeRect: getFillCompositeRect,\n getShaderMask: getFillShaderMask,\n });\n isFillCompositeRegistered = true;\n}\n","// =============================================================================\n// Module: Fill\n// =============================================================================\n/**\n * The Fill module contains functions and classes dedicated to handling\n * the fill properties of shapes within the drawing context. It supports complex fill\n * operations with effects such as bleeding to simulate watercolor-like textures. The\n * methods provided allow for setting the fill color with opacity, controlling the\n * intensity of the bleed effect, and enabling or disabling the fill operation.\n *\n * The watercolor effect implementation is inspired by Tyler Hobbs'\n * techniques for simulating watercolor paints.\n */\n\n// Core imports\nimport { Renderer, Cwidth, Cheight, Density } from \"../core/target.js\";\nimport {\n Mix,\n State,\n} from \"../core/color.js\";\nimport { drawPolygon, circle } from \"./mask.js\";\nimport {\n constrain,\n weightedRand,\n rr,\n map,\n randInt,\n gaussian,\n rotate,\n cos,\n sin,\n _onSeed,\n} from \"../core/utils.js\";\nimport { isFieldReady } from \"../core/flowfield.js\";\nimport { createColor, getAffineMatrix } from \"../core/runtime.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\n\n// Internal module imports\nimport { initFillComposite } from \"./composite.js\";\n\ninitFillComposite(); // Register the fill composite with the core color module\n\n// =============================================================================\n// Fill State and helpers\n// =============================================================================\n\n// Vertex cap for grow() — set to 0 or false to disable\nconst GROW_MAX_VERTS = 2024;\nlet GROW_CAP;\n\n// Reusable scratch arrays for grow() — avoids 4 allocations per call (~15× per fill)\nlet _growInsX = [];\nlet _growInsY = [];\nlet _growMods = [];\nlet _growDirs = [];\n\n/**\n * Global fill state settings.\n */\nState.fill = {\n opacity: 150,\n bleed_strength: 0.07,\n texture_strength: 0.8,\n border_strength: 0.5,\n direction: \"out\",\n isActive: false,\n};\n\n// Cache the current state\nconst FillState = () => ({ ...State.fill });\nconst FillSetState = (state) => {\n State.fill = { ...state };\n};\n\n// ---------------------------------------------------------------------------\n// Fill Style Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Sets the fill color and opacity for subsequent drawing operations.\n * @param {number|string|Color} a - Either the red component, a CSS color string, or a Color object.\n * @param {number} [b] - The green component or the opacity if using grayscale.\n * @param {number} [c] - The blue component.\n * @param {number} [d] - The opacity.\n */\nexport function fill(a, b, c, d) {\n State.fill.opacity = (arguments.length < 4 ? b : d) || 150;\n State.fill.color = arguments.length < 3 ? createColor(a) : createColor(a, b, c);\n State.fill.isActive = true;\n}\n\n/**\n * Sets the bleed (watercolor) intensity and direction.\n * @param {number} _i - The bleed intensity (clamped to [0,1]).\n * @param {string} [_direction=\"out\"] - The bleeding direction.\n */\nexport function fillBleed(_i, _direction = \"out\") {\n State.fill.bleed_strength = constrain(_i, 0, 1);\n State.fill.direction = _direction;\n}\n\n/**\n * Sets the texture and border strengths for the fill.\n * @param {number} [_texture=0.4] - The texture strength (clamped to [0,1]).\n * @param {number} [_border=0.4] - The border strength (clamped to [0,1]).\n */\nexport function fillTexture(_texture = 0.4, _border = 0.4) {\n State.fill.texture_strength = constrain(_texture, 0, 1);\n State.fill.border_strength = constrain(_border, 0, 1);\n}\n\n/**\n * Disables fill for subsequent drawing operations.\n */\nexport function noFill() {\n State.fill.isActive = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fill Manager Functions\n// ---------------------------------------------------------------------------\n\nlet _polygon;\n\n// Pre-compute gaussians for reuse\nconst GAUSSIAN_POOL_SIZE = 512;\nconst _gaussians = [[], []]; // [a, b]\nfunction _fillGaussianPools() {\n for (let i = 0; i < GAUSSIAN_POOL_SIZE; i++) {\n _gaussians[0][i] = gaussian(0.5, 0.2);\n _gaussians[1][i] = gaussian(0, 0.02);\n }\n}\n_onSeed(_fillGaussianPools);\n\n// Helper for direction checking - extracted to reduce duplication\nfunction _isLeft(a, b, c) {\n return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) > 0.01;\n}\n\n/**\n * Calculates the centroid of a polygon from its vertices.\n * @param {Object[]} pts - Array of points with {x, y}.\n * @returns {Object} The center point {x, y}.\n */\nfunction _center(pts) {\n if (pts.length === 0) {\n return { x: 0, y: 0 };\n }\n\n if (pts.length < 8) {\n // Simple average for small polygons\n const sum = pts.reduce(\n (center, point) => ({ x: center.x + point.x, y: center.y + point.y }),\n { x: 0, y: 0 },\n );\n return { x: sum.x / pts.length, y: sum.y / pts.length };\n }\n\n // Close polygon if needed\n const v = [...pts];\n if (v[0].x !== v[v.length - 1].x || v[0].y !== v[v.length - 1].y)\n v.push(v[0]);\n\n // Calculate using shoelace formula (more efficient implementation)\n let area = 0,\n cx = 0,\n cy = 0;\n for (let i = 0; i < v.length - 1; i++) {\n const cross = v[i].x * v[i + 1].y - v[i + 1].x * v[i].y;\n area += cross;\n cx += (v[i].x + v[i + 1].x) * cross;\n cy += (v[i].y + v[i + 1].y) * cross;\n }\n\n area *= 0.5;\n return area\n ? { x: cx / (6 * area), y: cy / (6 * area) }\n : { x: v[0].x, y: v[0].y };\n}\n\n/**\n * Fills a given polygon with a watercolor effect.\n * @param {Polygon} polygon - The polygon to fill.\n */\nexport function createFill(polygon) {\n if (!State.fill.isActive || !State.fill.color) {\n throw new Error(\n \"No fill color set. Call brush.fill(color) before drawing shapes.\",\n );\n }\n _polygon = polygon;\n const v = [...polygon.vertices];\n const fluid = ~~(v.length * 0.25 * weightedRand({ 1: 5, 2: 10, 3: 60 }));\n const strength = State.fill.bleed_strength;\n const modifiers = v.map(\n (_, i) => (i > fluid ? 1 : 0.3) * rr(0.85, 1.4) * strength,\n );\n const shift = randInt(0, v.length);\n const shifted = [...v.slice(shift), ...v.slice(0, shift)];\n const center = _center(shifted);\n return new FillPoly(shifted, modifiers, center, [], true).fill(\n State.fill.color,\n map(State.fill.opacity, 0, 255, 0, 1, true),\n State.fill.texture_strength,\n );\n}\n\n// ---------------------------------------------------------------------------\n// FillPolygon Class\n// ---------------------------------------------------------------------------\n\n/**\n * The FillPolygon class is used to create and manage the properties of the polygons that produces\n * the watercolor effect. It includes methods to grow (expand) the polygon and apply layers\n * of color with varying intensity and erase parts to simulate a natural watercolor bleed.\n * The implementation follows Tyler Hobbs' guide to simulating watercolor:\n * https://tylerxhobbs.com/essays/2017/a-generative-approach-to-simulating-watercolor-paints\n */\nclass FillPoly {\n /**\n * Constructs a FillPolygon.\n * @param {Object[]} _v - Vertices of the polygon.\n * @param {number[]} _m - Multipliers for the bleed effect at each vertex.\n * @param {Object} _center - The polygon's center {x, y}.\n * @param {boolean[]} dir - Array indicating bleed direction per vertex.\n * @param {boolean} isFirst - True for initial polygon.\n */\n constructor(v, m, center, dir = [], isFirst = false, sx, sy) {\n // Initialize properties\n this.v = v;\n this.m = m;\n this.dir = dir;\n this.midP = center;\n\n // Initialize size and direction for first polygon\n if (isFirst) {\n // Calculate size bounds\n let maxX = 0,\n maxY = 0;\n const rayCalc = [];\n\n for (let i = 0; i < v.length; i++) {\n // Store vertex distances to center for size calculation\n const dx = Math.abs(center.x - v[i].x);\n const dy = Math.abs(center.y - v[i].y);\n maxX = Math.max(maxX, dx);\n maxY = Math.max(maxY, dy);\n\n // Store edge info for ray calculations\n const v1 = v[i],\n v2 = v[(i + 1) % v.length];\n const side = { x: v2.x - v1.x, y: v2.y - v1.y };\n const rt = rotate(0, 0, side.x, side.y, 90);\n const mid = { x: v1.x + side.x / 2, y: v1.y + side.y / 2 };\n\n rayCalc.push({\n v1,\n v2,\n ray: {\n point1: mid,\n point2: { x: mid.x + rt.x, y: mid.y + rt.y },\n },\n });\n }\n\n // Store sizes\n this.sizeX = maxX;\n this.sizeY = maxY;\n\n // Calculate directions\n this.dir = Array(v.length);\n rayCalc.forEach((rc, i) => {\n let count = 0;\n for (const isect of _polygon.intersect(rc.ray)) {\n if (_isLeft(rc.v1, rc.v2, isect)) count++;\n }\n this.dir[i] = count % 2 === 0;\n });\n\n // Randomize center (single calculation)\n const rx = rr(-0.6, 0.6) * maxX;\n const ry = rr(-0.6, 0.6) * maxY;\n this.midP = { x: center.x + rx, y: center.y + ry };\n } else {\n this.sizeX = sx;\n this.sizeY = sy;\n }\n }\n\n /**\n * Trims vertices from the polygon based on a factor.\n * @param {number} [factor=1] - Factor determining amount of trimming.\n * @returns {Object} An object containing trimmed vertices, multipliers, and direction.\n */\n trim(f = 1) {\n // Fast path for common case\n if (f >= 1 || f < 0 || this.v.length <= 8) {\n return { v: this.v, m: this.m, dir: this.dir };\n }\n\n // Trim from middle for balance\n const n = ~~((1 - f) * this.v.length);\n const s = ~~(this.v.length / 2 - n / 2);\n\n // Copy only the kept ranges instead of cloning the full arrays and splicing.\n const keep = this.v.length - n;\n const v = new Array(keep);\n const m = new Array(keep);\n const dir = new Array(keep);\n let dst = 0;\n\n for (let i = 0; i < s; i++, dst++) {\n v[dst] = this.v[i];\n m[dst] = this.m[i];\n dir[dst] = this.dir[i];\n }\n\n for (let i = s + n; i < this.v.length; i++, dst++) {\n v[dst] = this.v[i];\n m[dst] = this.m[i];\n dir[dst] = this.dir[i];\n }\n\n\n // We want to add at least two vertices to divide the new edge that appears after trimming, at random distances along its path\n const trimStart = s;\n const trimEnd = s + n;\n const edgeStart = this.v[(trimStart - 1 + this.v.length) % this.v.length];\n const edgeEnd = this.v[trimEnd % this.v.length];\n const edgeVec = { x: edgeEnd.x - edgeStart.x, y: edgeEnd.y - edgeStart.y };\n \n // Insert two new vertices at random positions along the new edge\n const insertCount = 2;\n for (let i = 0; i < insertCount; i++) {\n const t = rr(0.25, 0.75); // Random position between 25% and 75% along the edge\n const newVertex = { x: edgeStart.x + edgeVec.x * t, y: edgeStart.y + edgeVec.y * t };\n const insertIdx = s + i;\n v.splice(insertIdx, 0, newVertex);\n m.splice(insertIdx, 0, rr(0.4, 0.7));\n dir.splice(insertIdx, 0, this.dir[trimStart % this.dir.length]);\n }\n\n return { v, m, dir };\n }\n\n /**\n * Randomly samples a fraction of vertices, keeping their order.\n * Any sampled vertex outside the original polygon is pulled inward.\n * @param {number} [ratio=0.3] - Fraction of vertices to keep.\n * @returns {FillPoly} A new FillPoly with fewer vertices, guaranteed inside the original.\n */\n scatter(ratio = 0.3) {\n const L = this.v.length;\n const keep = Math.max(3, ~~(L * ratio));\n const indices = [];\n const step = L / keep;\n for (let i = 0; i < keep; i++) {\n indices.push(~~(i * step + rr(0, step * 0.8)));\n }\n\n const sv = [],\n sm = [],\n sd = [];\n const mid = this.midP;\n const sides = _polygon.sides;\n\n for (const idx of indices) {\n const j = idx % L;\n let p = this.v[j];\n let crossings = 0;\n for (const [a, b] of sides) {\n const ay = a.y,\n by = b.y;\n if ((ay > p.y) === (by > p.y)) continue;\n const t = (p.y - ay) / (by - ay);\n if (p.x < a.x + t * (b.x - a.x)) crossings++;\n }\n if (crossings % 2 === 0) {\n p = {\n x: mid.x + (p.x - mid.x) * rr(0.3, 0.6),\n y: mid.y + (p.y - mid.y) * rr(0.3, 0.6),\n };\n }\n sv.push(p);\n sm.push(this.m[j]);\n sd.push(!this.dir[j]);\n }\n\n return new FillPoly(sv, sm, this.midP, sd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Returns a copy with all bleed directions flipped.\n */\n flipDirs() {\n return new FillPoly(this.v, this.m, this.midP, this.dir.map(d => !d), false, this.sizeX, this.sizeY);\n }\n\n /**\n * Grows (or shrinks) the polygon vertices to simulate watercolor spread.\n * @param {number} [growthFactor=1] - Factor controlling growth.\n * @returns {FillPoly} A new FillPoly with adjusted vertices.\n */\n grow(f = 1) {\n const { v: tr_v, m: tr_m, dir: tr_dir } = this.trim(f);\n const len = tr_v.length;\n\n const outLen = len * 2;\n if (_growInsX.length < len) { _growInsX = new Array(len); _growInsY = new Array(len); }\n if (_growMods.length < outLen) { _growMods = new Array(outLen); _growDirs = new Array(outLen); }\n const insertedX = _growInsX;\n const insertedY = _growInsY;\n const newMods = _growMods;\n const newDirs = _growDirs;\n const bleedDirDeg = State.fill.direction === \"out\" ? -90 : 90;\n\n if (_gaussians[0].length === 0) _fillGaussianPools();\n const gPool = _gaussians[0],\n gPoolLen = gPool.length;\n const g2Pool = _gaussians[1],\n g2PoolLen = g2Pool.length;\n\n let idx = 0;\n let insertedIdx = 0;\n let mod = f === 999 ? rr(0.6, 0.8) : State.fill.bleed_strength;\n\n for (let i = 0; i < len; i++) {\n const cv = tr_v[i];\n const nv = tr_v[i + 1 < len ? i + 1 : 0];\n const mi = tr_m[i];\n const di = tr_dir[i];\n\n if (f < 997) mod = mi;\n\n // If mod is smaller than 0.02, skip growing math and just insert the middle vertex\n if (mod < 0.05) {\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n insertedX[insertedIdx] = (cv.x + nv.x) / 2;\n insertedY[insertedIdx] = (cv.y + nv.y) / 2;\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n insertedIdx++;\n continue;\n }\n\n const rotDeg = (di ? bleedDirDeg : -bleedDirDeg) + rr(-1, 1) * 5;\n const c = cos(rotDeg);\n const s = sin(rotDeg);\n\n const sideX = nv.x - cv.x;\n const sideY = nv.y - cv.y;\n const dirX = c * sideX + s * sideY;\n const dirY = c * sideY - s * sideX;\n\n const d = gPool[~~(rr(0, 1) * gPoolLen)] * rr(0.65, 1.35) * mod;\n const nextMod = mi + g2Pool[~~(rr(0, 1) * g2PoolLen)];\n\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n\n insertedX[insertedIdx] = cv.x + sideX * 0.5 + dirX * d;\n insertedY[insertedIdx] = cv.y + sideY * 0.5 + dirY * d;\n newMods[idx] = nextMod;\n newDirs[idx] = di;\n idx++;\n insertedIdx++;\n }\n\n let fv,\n fm,\n fd;\n \n if (GROW_CAP && idx > GROW_CAP) {\n const step = Math.ceil(idx / GROW_CAP);\n const kept = Math.ceil(idx / step);\n fv = new Array(kept);\n fm = new Array(kept);\n fd = new Array(kept);\n let dst = 0;\n for (let j = 0; j < idx; j += step, dst++) {\n fv[dst] =\n j % 2 === 0\n ? tr_v[j >> 1]\n : { x: insertedX[j >> 1], y: insertedY[j >> 1] };\n fm[dst] = newMods[j];\n fd[dst] = newDirs[j];\n }\n } else {\n fv = new Array(idx);\n for (let j = 0; j < idx; j++) {\n fv[j] =\n j % 2 === 0\n ? tr_v[j >> 1]\n : { x: insertedX[j >> 1], y: insertedY[j >> 1] };\n }\n fm = newMods.slice(0, idx);\n fd = newDirs.slice(0, idx);\n }\n return new FillPoly(fv, fm, this.midP, fd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Fills the polygon with multiple layers to simulate a watercolor effect.\n * @param {Color|string} color - The fill color.\n * @param {number} intensity - Opacity intensity (mapped from 0 to 1).\n * @param {number} tex - Texture factor.\n */\n fill(color, intensity, tex) {\n const numLayers = 20;\n const texture = tex * 3;\n const int = 2 * intensity * (1 + tex / 2);\n\n const switchingToFill = Mix.isBrush !== false;\n Mix.isBrush = false;\n if (switchingToFill) Mix.justChanged = true;\n Mix.blend(color);\n\n const m = getAffineMatrix();\n Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * m.a,\n Density * m.b,\n Density * m.c,\n Density * m.d,\n Density * (m.x + Cwidth / 2),\n Density * (m.y + Cheight / 2),\n );\n\n Mix.ctx.strokeStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${\n 0.005 * State.fill.border_strength\n })`;\n Mix.ctx.lineCap = \"round\";\n\n GROW_CAP = GROW_MAX_VERTS * Math.max(0.1, 2 * State.fill.bleed_strength);\n\n const size = Math.max(this.sizeX, this.sizeY);\n const darker = rr(0.15, 0.7);\n let pol = this.grow();\n const sparse = this.scatter(0.1).grow().scatter(0.75).flipDirs();\n let pols;\n\n for (let i = 0; i < numLayers; i++) {\n if (i % 4 === 0) {\n pol = pol.grow();\n }\n\n if (i % 2 === 0) {\n pols = [\n pol.grow(1 - 0.0125 * i),\n pol.grow(0.7 - 0.0125 * i),\n pol.grow(0.4 - 0.0125 * i),\n ];\n }\n\n for (const p of pols) {\n const grown = p.grow(999).grow(997);\n grown.layer(i, size, int, color);\n }\n const sparseLayer = sparse.grow(999).flipDirs().grow(997);\n sparseLayer.layer(i, size, int * texture, color);\n if (i % 2 === 0) {\n const darkerLayer = pol.grow(darker).grow(999);\n darkerLayer.layer(i, size, int * 2, color);\n }\n\n if (i % 8 === 0 || i === numLayers - 1) {\n if (texture !== 0) {\n pol.erase(texture * 3, intensity);\n }\n Mix.blend(color, true);\n }\n }\n\n Mix.ctx.restore();\n }\n\n /**\n * Draws a layer of the fill polygon with stroke and fill.\n * @param {number} i - The layer index.\n */\n layer(i, size, int, color) {\n Mix.ctx.lineWidth = map(i, 0, 24, size / 25, size / 30, true);\n\n Mix.ctx.fillStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${int}%)`;\n\n drawPolygon(this.v);\n Mix.ctx.fill();\n Mix.ctx.stroke();\n }\n\n /**\n * Erases parts of the polygon to create a natural watercolor texture.\n * @param {number} texture - Texture strength factor.\n * @param {number} intensity - Intensity value for size scaling.\n */\n erase(texture, intensity) {\n Mix.ctx.save();\n\n const numCircles = ~~(rr(80, 110) * map(texture, 0, 1, 2, 3.5));\n const halfSizeX = this.sizeX / 1.3;\n const halfSizeY = this.sizeY / 1.3;\n const minSize =\n Math.min(this.sizeX, this.sizeY) * (1.3);\n const minSizeFactor = 0.03 * minSize;\n const maxSizeFactor = 0.45 * minSize;\n const { x: midX, y: midY } = this.midP;\n\n Mix.ctx.globalCompositeOperation = \"destination-out\";\n\n const alpha =\n ((5 - map(intensity, 80, 100, 0.3, 0.7, true)) * texture) / 255;\n Mix.ctx.fillStyle = `rgb(255 0 0 / ${alpha})`;\n Mix.ctx.lineWidth = 0;\n\n for (let i = 0; i < numCircles; i++) {\n const x = midX + gaussian(0, halfSizeX);\n const y = midY + gaussian(0, halfSizeY);\n const radius = rr(minSizeFactor, maxSizeFactor);\n\n Mix.ctx.beginPath();\n circle(x, y, radius);\n if (i % 5 !== 0) {\n Mix.ctx.fill();\n }\n }\n\n Mix.ctx.globalCompositeOperation = \"source-over\";\n Mix.ctx.restore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Extend Polygon and Plot Prototypes for Fill\n// ---------------------------------------------------------------------------\n\n/**\n * Applies a fill effect to the polygon using the current fill state.\n * @param {Color|string} [_color] - The color for the fill.\n * @param {number} [_opacity] - The opacity value.\n * @param {number} [_bleed] - The bleed intensity.\n * @param {number} [_texture] - The texture strength.\n * @param {number} [_border] - The border strength.\n * @param {string} [_direction] - The bleed direction.\n */\nPolygon.prototype.fill = function (\n _color = false,\n _opacity,\n _bleed,\n _texture,\n _border,\n _direction,\n) {\n let state = FillState();\n if (_color) {\n fill(_color, _opacity);\n fillBleed(_bleed, _direction);\n fillTexture(_texture, _border);\n }\n if (state.isActive) {\n isFieldReady();\n createFill(this);\n }\n FillSetState(state);\n};\n\n/**\n * Fills a plot on the canvas by generating a polygon based on the provided coordinates.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - Scaling factor.\n */\nPlot.prototype.fill = function (x, y, scale) {\n if (FillState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n this.pol = this.genPol(\n x,\n y,\n scale,\n State.fill.bleed_strength < 0.06\n ? 0\n : map(State.fill.bleed_strength, 0, 0.6, 0.2, 0.60, true),\n );\n this.pol.fill();\n }\n};\n","\nexport default function earcut(data, holeIndices, dim = 2) {\n\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n let outerNode = linkedList(data, 0, outerLen, dim, true);\n const triangles = [];\n\n if (!outerNode || outerNode.next === outerNode.prev) return triangles;\n\n let minX, minY, invSize;\n\n if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);\n\n // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox\n if (data.length > 80 * dim) {\n minX = data[0];\n minY = data[1];\n let maxX = minX;\n let maxY = minY;\n\n for (let i = dim; i < outerLen; i += dim) {\n const x = data[i];\n const y = data[i + 1];\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n\n // minX, minY and invSize are later used to transform coords into integers for z-order calculation\n invSize = Math.max(maxX - minX, maxY - minY);\n invSize = invSize !== 0 ? 32767 / invSize : 0;\n }\n\n earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);\n\n return triangles;\n}\n\n// create a circular doubly linked list from polygon points in the specified winding order\nfunction linkedList(data, start, end, dim, clockwise) {\n let last;\n\n if (clockwise === (signedArea(data, start, end, dim) > 0)) {\n for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n } else {\n for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n }\n\n if (last && equals(last, last.next)) {\n removeNode(last);\n last = last.next;\n }\n\n return last;\n}\n\n// eliminate colinear or duplicate points\nfunction filterPoints(start, end) {\n if (!start) return start;\n if (!end) end = start;\n\n let p = start,\n again;\n do {\n again = false;\n\n if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {\n removeNode(p);\n p = end = p.prev;\n if (p === p.next) break;\n again = true;\n\n } else {\n p = p.next;\n }\n } while (again || p !== end);\n\n return end;\n}\n\n// main ear slicing loop which triangulates a polygon (given as a linked list)\nfunction earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {\n if (!ear) return;\n\n // interlink polygon nodes in z-order\n if (!pass && invSize) indexCurve(ear, minX, minY, invSize);\n\n let stop = ear;\n\n // iterate through ears, slicing them one by one\n while (ear.prev !== ear.next) {\n const prev = ear.prev;\n const next = ear.next;\n\n if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {\n triangles.push(prev.i, ear.i, next.i); // cut off the triangle\n\n removeNode(ear);\n\n // skipping the next vertex leads to less sliver triangles\n ear = next.next;\n stop = next.next;\n\n continue;\n }\n\n ear = next;\n\n // if we looped through the whole remaining polygon and can't find any more ears\n if (ear === stop) {\n // try filtering points and slicing again\n if (!pass) {\n earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);\n\n // if this didn't work, try curing all small self-intersections locally\n } else if (pass === 1) {\n ear = cureLocalIntersections(filterPoints(ear), triangles);\n earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);\n\n // as a last resort, try splitting the remaining polygon into two\n } else if (pass === 2) {\n splitEarcut(ear, triangles, dim, minX, minY, invSize);\n }\n\n break;\n }\n }\n}\n\n// check whether a polygon node forms a valid ear with adjacent nodes\nfunction isEar(ear) {\n const a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n // now make sure we don't have other points inside the potential ear\n const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox\n const x0 = Math.min(ax, bx, cx),\n y0 = Math.min(ay, by, cy),\n x1 = Math.max(ax, bx, cx),\n y1 = Math.max(ay, by, cy);\n\n let p = c.next;\n while (p !== a) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&\n area(p.prev, p, p.next) >= 0) return false;\n p = p.next;\n }\n\n return true;\n}\n\nfunction isEarHashed(ear, minX, minY, invSize) {\n const a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox\n const x0 = Math.min(ax, bx, cx),\n y0 = Math.min(ay, by, cy),\n x1 = Math.max(ax, bx, cx),\n y1 = Math.max(ay, by, cy);\n\n // z-order range for the current triangle bbox;\n const minZ = zOrder(x0, y0, minX, minY, invSize),\n maxZ = zOrder(x1, y1, minX, minY, invSize);\n\n let p = ear.prevZ,\n n = ear.nextZ;\n\n // look for points inside the triangle in both directions\n while (p && p.z >= minZ && n && n.z <= maxZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n // look for remaining points in decreasing z-order\n while (p && p.z >= minZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n }\n\n // look for remaining points in increasing z-order\n while (n && n.z <= maxZ) {\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n return true;\n}\n\n// go through all polygon nodes and cure small local self-intersections\nfunction cureLocalIntersections(start, triangles) {\n let p = start;\n do {\n const a = p.prev,\n b = p.next.next;\n\n if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {\n\n triangles.push(a.i, p.i, b.i);\n\n // remove two nodes involved\n removeNode(p);\n removeNode(p.next);\n\n p = start = b;\n }\n p = p.next;\n } while (p !== start);\n\n return filterPoints(p);\n}\n\n// try splitting polygon into two and triangulate them independently\nfunction splitEarcut(start, triangles, dim, minX, minY, invSize) {\n // look for a valid diagonal that divides the polygon into two\n let a = start;\n do {\n let b = a.next.next;\n while (b !== a.prev) {\n if (a.i !== b.i && isValidDiagonal(a, b)) {\n // split the polygon in two by the diagonal\n let c = splitPolygon(a, b);\n\n // filter colinear points around the cuts\n a = filterPoints(a, a.next);\n c = filterPoints(c, c.next);\n\n // run earcut on each half\n earcutLinked(a, triangles, dim, minX, minY, invSize, 0);\n earcutLinked(c, triangles, dim, minX, minY, invSize, 0);\n return;\n }\n b = b.next;\n }\n a = a.next;\n } while (a !== start);\n}\n\n// link every hole into the outer loop, producing a single-ring polygon without holes\nfunction eliminateHoles(data, holeIndices, outerNode, dim) {\n const queue = [];\n\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n const list = linkedList(data, start, end, dim, false);\n if (list === list.next) list.steiner = true;\n queue.push(getLeftmost(list));\n }\n\n queue.sort(compareXYSlope);\n\n // process holes from left to right\n for (let i = 0; i < queue.length; i++) {\n outerNode = eliminateHole(queue[i], outerNode);\n }\n\n return outerNode;\n}\n\nfunction compareXYSlope(a, b) {\n let result = a.x - b.x;\n // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find\n // the bridge to the outer shell is always the point that they meet at.\n if (result === 0) {\n result = a.y - b.y;\n if (result === 0) {\n const aSlope = (a.next.y - a.y) / (a.next.x - a.x);\n const bSlope = (b.next.y - b.y) / (b.next.x - b.x);\n result = aSlope - bSlope;\n }\n }\n return result;\n}\n\n// find a bridge between vertices that connects hole with an outer ring and link it\nfunction eliminateHole(hole, outerNode) {\n const bridge = findHoleBridge(hole, outerNode);\n if (!bridge) {\n return outerNode;\n }\n\n const bridgeReverse = splitPolygon(bridge, hole);\n\n // filter collinear points around the cuts\n filterPoints(bridgeReverse, bridgeReverse.next);\n return filterPoints(bridge, bridge.next);\n}\n\n// David Eberly's algorithm for finding a bridge between hole and outer polygon\nfunction findHoleBridge(hole, outerNode) {\n let p = outerNode;\n const hx = hole.x;\n const hy = hole.y;\n let qx = -Infinity;\n let m;\n\n // find a segment intersected by a ray from the hole's leftmost point to the left;\n // segment's endpoint with lesser x will be potential connection point\n // unless they intersect at a vertex, then choose the vertex\n if (equals(hole, p)) return p;\n do {\n if (equals(hole, p.next)) return p.next;\n else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {\n const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);\n if (x <= hx && x > qx) {\n qx = x;\n m = p.x < p.next.x ? p : p.next;\n if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint\n }\n }\n p = p.next;\n } while (p !== outerNode);\n\n if (!m) return null;\n\n // look for points inside the triangle of hole point, segment intersection and endpoint;\n // if there are no points found, we have a valid connection;\n // otherwise choose the point of the minimum angle with the ray as connection point\n\n const stop = m;\n const mx = m.x;\n const my = m.y;\n let tanMin = Infinity;\n\n p = m;\n\n do {\n if (hx >= p.x && p.x >= mx && hx !== p.x &&\n pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {\n\n const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential\n\n if (locallyInside(p, hole) &&\n (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {\n m = p;\n tanMin = tan;\n }\n }\n\n p = p.next;\n } while (p !== stop);\n\n return m;\n}\n\n// whether sector in vertex m contains sector in vertex p in the same coordinates\nfunction sectorContainsSector(m, p) {\n return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;\n}\n\n// interlink polygon nodes in z-order\nfunction indexCurve(start, minX, minY, invSize) {\n let p = start;\n do {\n if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);\n p.prevZ = p.prev;\n p.nextZ = p.next;\n p = p.next;\n } while (p !== start);\n\n p.prevZ.nextZ = null;\n p.prevZ = null;\n\n sortLinked(p);\n}\n\n// Simon Tatham's linked list merge sort algorithm\n// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html\nfunction sortLinked(list) {\n let numMerges;\n let inSize = 1;\n\n do {\n let p = list;\n let e;\n list = null;\n let tail = null;\n numMerges = 0;\n\n while (p) {\n numMerges++;\n let q = p;\n let pSize = 0;\n for (let i = 0; i < inSize; i++) {\n pSize++;\n q = q.nextZ;\n if (!q) break;\n }\n let qSize = inSize;\n\n while (pSize > 0 || (qSize > 0 && q)) {\n\n if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {\n e = p;\n p = p.nextZ;\n pSize--;\n } else {\n e = q;\n q = q.nextZ;\n qSize--;\n }\n\n if (tail) tail.nextZ = e;\n else list = e;\n\n e.prevZ = tail;\n tail = e;\n }\n\n p = q;\n }\n\n tail.nextZ = null;\n inSize *= 2;\n\n } while (numMerges > 1);\n\n return list;\n}\n\n// z-order of a point given coords and inverse of the longer side of data bbox\nfunction zOrder(x, y, minX, minY, invSize) {\n // coords are transformed into non-negative 15-bit integer range\n x = (x - minX) * invSize | 0;\n y = (y - minY) * invSize | 0;\n\n x = (x | (x << 8)) & 0x00FF00FF;\n x = (x | (x << 4)) & 0x0F0F0F0F;\n x = (x | (x << 2)) & 0x33333333;\n x = (x | (x << 1)) & 0x55555555;\n\n y = (y | (y << 8)) & 0x00FF00FF;\n y = (y | (y << 4)) & 0x0F0F0F0F;\n y = (y | (y << 2)) & 0x33333333;\n y = (y | (y << 1)) & 0x55555555;\n\n return x | (y << 1);\n}\n\n// find the leftmost node of a polygon ring\nfunction getLeftmost(start) {\n let p = start,\n leftmost = start;\n do {\n if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;\n p = p.next;\n } while (p !== start);\n\n return leftmost;\n}\n\n// check if a point lies within a convex triangle\nfunction pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {\n return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&\n (ax - px) * (by - py) >= (bx - px) * (ay - py) &&\n (bx - px) * (cy - py) >= (cx - px) * (by - py);\n}\n\n// check if a point lies within a convex triangle but false if its equal to the first point of the triangle\nfunction pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {\n return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);\n}\n\n// check if a diagonal between two polygon nodes is valid (lies in polygon interior)\nfunction isValidDiagonal(a, b) {\n return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges\n (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible\n (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors\n equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case\n}\n\n// signed area of a triangle\nfunction area(p, q, r) {\n return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);\n}\n\n// check if two points are equal\nfunction equals(p1, p2) {\n return p1.x === p2.x && p1.y === p2.y;\n}\n\n// check if two segments intersect\nfunction intersects(p1, q1, p2, q2) {\n const o1 = sign(area(p1, q1, p2));\n const o2 = sign(area(p1, q1, q2));\n const o3 = sign(area(p2, q2, p1));\n const o4 = sign(area(p2, q2, q1));\n\n if (o1 !== o2 && o3 !== o4) return true; // general case\n\n if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1\n if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1\n if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2\n if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2\n\n return false;\n}\n\n// for collinear points p, q, r, check if point q lies on segment pr\nfunction onSegment(p, q, r) {\n return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);\n}\n\nfunction sign(num) {\n return num > 0 ? 1 : num < 0 ? -1 : 0;\n}\n\n// check if a polygon diagonal intersects any polygon segments\nfunction intersectsPolygon(a, b) {\n let p = a;\n do {\n if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&\n intersects(p, p.next, a, b)) return true;\n p = p.next;\n } while (p !== a);\n\n return false;\n}\n\n// check if a polygon diagonal is locally inside the polygon\nfunction locallyInside(a, b) {\n return area(a.prev, a, a.next) < 0 ?\n area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :\n area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;\n}\n\n// check if the middle point of a polygon diagonal is inside the polygon\nfunction middleInside(a, b) {\n let p = a;\n let inside = false;\n const px = (a.x + b.x) / 2;\n const py = (a.y + b.y) / 2;\n do {\n if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&\n (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))\n inside = !inside;\n p = p.next;\n } while (p !== a);\n\n return inside;\n}\n\n// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;\n// if one belongs to the outer ring and another to a hole, it merges it into a single ring\nfunction splitPolygon(a, b) {\n const a2 = createNode(a.i, a.x, a.y),\n b2 = createNode(b.i, b.x, b.y),\n an = a.next,\n bp = b.prev;\n\n a.next = b;\n b.prev = a;\n\n a2.next = an;\n an.prev = a2;\n\n b2.next = a2;\n a2.prev = b2;\n\n bp.next = b2;\n b2.prev = bp;\n\n return b2;\n}\n\n// create a node and optionally link it with previous one (in a circular doubly linked list)\nfunction insertNode(i, x, y, last) {\n const p = createNode(i, x, y);\n\n if (!last) {\n p.prev = p;\n p.next = p;\n\n } else {\n p.next = last.next;\n p.prev = last;\n last.next.prev = p;\n last.next = p;\n }\n return p;\n}\n\nfunction removeNode(p) {\n p.next.prev = p.prev;\n p.prev.next = p.next;\n\n if (p.prevZ) p.prevZ.nextZ = p.nextZ;\n if (p.nextZ) p.nextZ.prevZ = p.prevZ;\n}\n\nfunction createNode(i, x, y) {\n return {\n i, // vertex index in coordinates array\n x, y, // vertex coordinates\n prev: null, // previous and next vertex nodes in a polygon ring\n next: null,\n z: 0, // z-order curve value\n prevZ: null, // previous and next nodes in z-order\n nextZ: null,\n steiner: false // indicates whether this is a steiner point\n };\n}\n\n// return a percentage difference between the polygon area and its triangulation area;\n// used to verify correctness of triangulation\nexport function deviation(data, holeIndices, dim, triangles) {\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n\n let polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));\n if (hasHoles) {\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n polygonArea -= Math.abs(signedArea(data, start, end, dim));\n }\n }\n\n let trianglesArea = 0;\n for (let i = 0; i < triangles.length; i += 3) {\n const a = triangles[i] * dim;\n const b = triangles[i + 1] * dim;\n const c = triangles[i + 2] * dim;\n trianglesArea += Math.abs(\n (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -\n (data[a] - data[b]) * (data[c + 1] - data[a + 1]));\n }\n\n return polygonArea === 0 && trianglesArea === 0 ? 0 :\n Math.abs((trianglesArea - polygonArea) / polygonArea);\n}\n\nfunction signedArea(data, start, end, dim) {\n let sum = 0;\n for (let i = start, j = end - dim; i < end; i += dim) {\n sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);\n j = i;\n }\n return sum;\n}\n\n// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts\nexport function flatten(data) {\n const vertices = [];\n const holes = [];\n const dimensions = data[0][0].length;\n let holeIndex = 0;\n let prevLen = 0;\n\n for (const ring of data) {\n for (const p of ring) {\n for (let d = 0; d < dimensions; d++) vertices.push(p[d]);\n }\n if (prevLen) {\n holeIndex += prevLen;\n holes.push(holeIndex);\n }\n prevLen = ring.length;\n }\n return {vertices, holes, dimensions};\n}\n","// =============================================================================\n// Module: Wash\n// =============================================================================\n/**\n * Minimal stateful API for the `wash()` fill modifier.\n */\n\nimport earcut from \"earcut\";\nimport { Renderer, Cwidth, Cheight, isCanvasReady } from \"../core/target.js\";\nimport { State, flushActiveComposite } from \"../core/color.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { getAffineMatrix } from \"../core/runtime.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport { createColor } from \"../core/runtime.js\";\nimport { resetDirectShaderTracking } from \"../core/renderer_runtime.js\";\n\nlet gl = null;\nlet washProgram = null;\nlet washVao = null;\nlet washBuffer = null;\nlet washProjection = null;\nlet loadedWidth = 0;\nlet loadedHeight = 0;\nlet washGpuBufferSize = 0;\n\nconst WashAttr = {};\nconst WashUniform = {};\n\nconst washVertSrc = `#version 300 es\nin vec2 a_position;\nuniform mat4 u_matrix;\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n}`;\n\nconst washFragSrc = `#version 300 es\nprecision highp float;\nuniform vec4 u_color;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(u_color.rgb * u_color.a, u_color.a);\n}`;\n\nState.wash = {\n color: null,\n opacity: 150,\n isActive: false,\n};\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Enables wash mode with a color and opacity.\n *\n * @param {number|string|Color} a - Either the red component, a CSS color string, or a Color object.\n * @param {number} [b] - The green component or the opacity if using grayscale.\n * @param {number} [c] - The blue component.\n * @param {number} [d] - The opacity.\n */\nexport function wash(a, b, c, d) {\n isCanvasReady();\n State.wash.opacity = (arguments.length < 4 ? b : d) ?? 150;\n State.wash.color = arguments.length < 3 ? createColor(a) : createColor(a, b, c);\n State.wash.isActive = true;\n}\n\n/**\n * Disables wash mode for subsequent drawing operations.\n */\nexport function noWash() {\n State.wash.isActive = false;\n}\n\n// =============================================================================\n// GL helpers\n// =============================================================================\n\n/**\n * Lazily creates the reusable program/buffer state for solid wash drawing and\n * refreshes the orthographic projection when the active target size changes.\n */\nfunction ensureWashReady() {\n const nextGl = Renderer.drawingContext;\n const sizeChanged = loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (!washProjection || sizeChanged) {\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n washProjection = new Float32Array([\n 2 / loadedWidth,\n 0,\n 0,\n 0,\n 0,\n -2 / loadedHeight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n 1,\n 0,\n 1,\n ]);\n }\n\n if (gl === nextGl && washProgram && washVao && washBuffer) return;\n\n gl = nextGl;\n washProgram = createProgram(gl, washVertSrc, washFragSrc);\n WashAttr.a_position = gl.getAttribLocation(washProgram, \"a_position\");\n WashUniform.u_matrix = gl.getUniformLocation(washProgram, \"u_matrix\");\n WashUniform.u_color = gl.getUniformLocation(washProgram, \"u_color\");\n\n washVao = gl.createVertexArray();\n gl.bindVertexArray(washVao);\n\n washBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, 0, gl.DYNAMIC_DRAW);\n washGpuBufferSize = 0;\n\n gl.enableVertexAttribArray(WashAttr.a_position);\n gl.vertexAttribPointer(WashAttr.a_position, 2, gl.FLOAT, false, 8, 0);\n\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n}\n\n/**\n * Applies the current runtime affine transform and converts the result into\n * the screen-space coordinates used by the direct GL wash pipeline.\n *\n * @param {number} x - The source x-coordinate in brush drawing space.\n * @param {number} y - The source y-coordinate in brush drawing space.\n * @returns {[number, number]} The transformed screen-space position.\n */\nfunction transformVertexToScreen(x, y) {\n const m = getAffineMatrix();\n return [\n m.a * x + m.c * y + m.x + loadedWidth / 2,\n m.b * x + m.d * y + m.y + loadedHeight / 2,\n ];\n}\n\n/**\n * Triangulates a polygon in local space and returns the transformed triangle\n * vertex buffer ready for upload to the GPU.\n *\n * @param {Polygon} polygon - The polygon to triangulate.\n * @returns {{ triangles: Float32Array, vertexCount: number }} Screen-space\n * triangle vertices plus the number of vertices to draw.\n */\nfunction buildTriangleBuffer(polygon) {\n const flat = new Float32Array(polygon.vertices.length * 2);\n for (let i = 0; i < polygon.vertices.length; i++) {\n const vertex = polygon.vertices[i];\n flat[i * 2] = vertex.x;\n flat[i * 2 + 1] = vertex.y;\n }\n\n const indices = earcut(flat);\n const triangles = new Float32Array(indices.length * 2);\n for (let i = 0; i < indices.length; i++) {\n const idx = indices[i];\n const [screenX, screenY] = transformVertexToScreen(flat[idx * 2], flat[idx * 2 + 1]);\n triangles[i * 2] = screenX;\n triangles[i * 2 + 1] = screenY;\n }\n\n return {\n triangles,\n vertexCount: indices.length,\n };\n}\n\n/**\n * Draws a triangulated solid wash directly to the current GL target.\n *\n * @param {Polygon} polygon - The polygon to fill with the current wash state.\n */\nfunction drawWashPolygon(polygon) {\n if (!State.wash?.isActive || !State.wash.color || polygon.vertices.length < 3) return;\n\n flushActiveComposite();\n ensureWashReady();\n const { triangles, vertexCount } = buildTriangleBuffer(polygon);\n const byteCount = triangles.byteLength;\n gl.useProgram(washProgram);\n gl.enable(gl.BLEND);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n gl.bindVertexArray(washVao);\n gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);\n if (byteCount > washGpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, triangles, gl.DYNAMIC_DRAW);\n washGpuBufferSize = byteCount;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, triangles);\n }\n const color = State.wash.color._array;\n gl.uniformMatrix4fv(WashUniform.u_matrix, false, washProjection);\n gl.uniform4f(\n WashUniform.u_color,\n color[0],\n color[1],\n color[2],\n State.wash.opacity / 255,\n );\n\n gl.drawArrays(gl.TRIANGLES, 0, vertexCount);\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n resetDirectShaderTracking(Renderer, gl);\n}\n\n// =============================================================================\n// Prototype methods\n// =============================================================================\n\n/**\n * Applies a direct GL wash fill to the polygon using the current wash state.\n *\n * @param {Color|string|false} [_color] - Optional override color for this call.\n * @param {number} [_opacity] - Optional override opacity for this call.\n */\nPolygon.prototype.wash = function (_color = false, _opacity) {\n const state = { ...State.wash };\n if (_color !== false) wash(_color, _opacity);\n\n if (State.wash.isActive) {\n drawWashPolygon(this);\n }\n\n State.wash = { ...state };\n};\n\n/**\n * Applies wash to a plot by first generating the plot polygon, mirroring the\n * existing fill-path behavior, and then drawing that polygon with wash.\n *\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\nPlot.prototype.wash = function (x, y, scale) {\n if (!State.wash?.isActive) return;\n if (this.origin) {\n x = this.origin[0];\n y = this.origin[1];\n scale = 1;\n }\n this.pol = this.genPol(x, y, scale, 0, -1);\n this.pol.wash();\n};\n","// =============================================================================\n// Adapter: p5 Runtime Target Resolution\n// =============================================================================\n/**\n * Owns the active renderer/instance selection used by p5.brush when running\n * on top of p5's WEBGL renderer.\n */\n\nimport {\n setTargetRuntime,\n setTargetState,\n Instance,\n Renderer,\n} from \"../../core/target.js\";\n\nlet ReadySketch = null;\nlet ActiveInstance = null;\nconst ActiveInstanceStack = [];\nlet _isReady = false;\n\n/**\n * Checks whether the given draw target is a p5.Framebuffer-like object.\n * @param {*} target - Candidate draw target.\n * @returns {boolean} True when the target behaves like a p5.Framebuffer.\n */\nexport const isFramebufferTarget = (target) =>\n !!target &&\n typeof target.begin === \"function\" &&\n typeof target.end === \"function\" &&\n !!target.renderer &&\n !!target.renderer._pInst;\n\nconst isFiniteSize = (value) =>\n typeof value === \"number\" && Number.isFinite(value) && value > 0;\n\nconst safeRead = (getter) => {\n try {\n return getter();\n } catch (_error) {\n return undefined;\n }\n};\n\nconst isReadyWebGLSketch = (candidate) =>\n !!candidate &&\n typeof candidate.pixelDensity === \"function\" &&\n typeof candidate.createFramebuffer === \"function\" &&\n isFiniteSize(safeRead(() => candidate.width)) &&\n isFiniteSize(safeRead(() => candidate.height)) &&\n safeRead(() => candidate.webglVersion) === \"webgl2\";\n\nconst getCurrentP5Instance = () => window.self?.p5?.instance ?? null;\n\nconst rememberReadySketch = (candidate) => {\n if (isReadyWebGLSketch(candidate)) ReadySketch = candidate;\n return ReadySketch;\n};\n\nconst getActiveSketchRenderer = () => {\n if (!ActiveInstance) return null;\n if (!isReadyWebGLSketch(ActiveInstance)) return null;\n return rememberReadySketch(ActiveInstance);\n};\n\n/**\n * Resolves the sketch renderer that owns the current drawing session.\n * Preference order:\n * 1. the sketch currently executing a p5 lifecycle callback\n * 2. the explicitly selected instance from brush.instance(p), if ready\n * 3. the last known-good ready sketch\n * @returns {p5|Window[\"p5\"][\"instance\"]|null} The active sketch renderer.\n */\nexport const getSketchRenderer = () =>\n getActiveSketchRenderer() ||\n rememberReadySketch(getCurrentP5Instance()) ||\n rememberReadySketch(Instance) ||\n ReadySketch;\n\n/**\n * Resolves the renderer and pixel size used by `brush.load()`.\n * @param {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional draw target.\n * @returns {{renderer: object, width: number, height: number}} Active renderer info.\n */\nconst resolveTarget = (buffer = false) => {\n const sketchRenderer = getSketchRenderer();\n\n if (!buffer) {\n if (!sketchRenderer) {\n throw new Error(\n \"p5.brush could not resolve an active WEBGL sketch. Call brush.instance(p) and brush.load() after createCanvas(..., WEBGL).\",\n );\n }\n return {\n renderer: sketchRenderer,\n width: sketchRenderer.width,\n height: sketchRenderer.height,\n };\n }\n\n if (isFramebufferTarget(buffer)) {\n const owner = buffer.renderer._pInst;\n rememberReadySketch(owner);\n\n if (sketchRenderer && owner !== sketchRenderer) {\n throw new Error(\n \"p5.brush only supports p5.Framebuffer targets created from the active sketch\",\n );\n }\n\n return {\n renderer: owner,\n width: buffer.width,\n height: buffer.height,\n };\n }\n\n return {\n renderer: buffer,\n width: buffer.width,\n height: buffer.height,\n };\n};\n\n/**\n * Returns the currently bound sketch framebuffer when drawing into one.\n * @returns {p5.Framebuffer|null} Active framebuffer or null.\n */\nexport const getActiveFramebuffer = () =>\n Renderer?._renderer?.activeFramebuffer?.() ?? null;\n\n/**\n * Loads and initializes a canvas for the drawing system.\n * @param {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional offscreen target.\n * Pass a framebuffer only while drawing inside its begin()/end() or draw() scope.\n * Framebuffers created from p5.Graphics are not supported.\n */\nexport const load = (buffer = false) => {\n const target = resolveTarget(buffer);\n setTargetState({ Renderer: target.renderer });\n rememberReadySketch(!buffer ? Renderer : getSketchRenderer());\n\n if (Renderer.webglVersion !== \"webgl2\") {\n throw new Error(\"p5.brush requires a WEBGL canvas\");\n }\n\n setTargetState({\n Cwidth: target.width,\n Cheight: target.height,\n });\n\n _isReady = true;\n};\n\n/**\n * Refreshes the stored pixel density for the active renderer.\n * @returns {number} Current renderer pixel density.\n */\nexport const syncDensity = () => {\n const density = Renderer.pixelDensity();\n setTargetState({ Density: density });\n return density;\n};\n\n/**\n * Ensures the drawing system is ready before any operation.\n */\nexport const isCanvasReady = () => {\n if (!_isReady) load();\n};\n\nexport const instance = (inst) => {\n setTargetState({ Instance: inst });\n rememberReadySketch(inst);\n};\n\nexport const activateInstance = (inst) => {\n ActiveInstanceStack.push(ActiveInstance);\n ActiveInstance = inst;\n instance(inst);\n};\n\nexport const deactivateInstance = () => {\n ActiveInstance = ActiveInstanceStack.pop() ?? null;\n};\n\nexport function initP5TargetRuntime() {\n setTargetRuntime({\n load,\n syncDensity,\n isCanvasReady,\n instance,\n activateInstance,\n deactivateInstance,\n getActiveFramebuffer,\n isFramebufferTarget,\n });\n}\n","// =============================================================================\n// Adapter: p5 Runtime Hooks\n// =============================================================================\n\nimport { setRuntime } from \"../../core/runtime.js\";\nimport { Renderer } from \"../../core/target.js\";\nimport { getSketchRenderer } from \"./target.js\";\n\nconst getP5RuntimeRenderer = () =>\n Renderer ?? getSketchRenderer?.() ?? window.self?.p5?.instance ?? null;\nconst identityMatrix = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\nconst affineMatrix = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\n\nfunction isRadians() {\n const renderer = getP5RuntimeRenderer();\n return !!renderer &&\n typeof renderer.angleMode === \"function\" &&\n renderer.angleMode() === renderer.RADIANS;\n}\n\nexport function initP5Runtime() {\n setRuntime({\n usesRadians: isRadians,\n\n fromDegrees: (angle) =>\n isRadians() ? (angle * Math.PI) / 180 : angle,\n\n createColor: (...args) => {\n const renderer = getP5RuntimeRenderer();\n if (!renderer?.color) {\n throw new Error(\"p5 runtime color creation requires an active renderer.\");\n }\n return renderer.color(...args);\n },\n\n getAffineMatrix: () => {\n const renderer = getP5RuntimeRenderer();\n const mat4 = renderer?._renderer?.uModelMatrix?.mat4;\n if (!mat4) return identityMatrix;\n\n affineMatrix.a = mat4[0];\n affineMatrix.b = mat4[1];\n affineMatrix.c = mat4[4];\n affineMatrix.d = mat4[5];\n affineMatrix.x = mat4[12];\n affineMatrix.y = mat4[13];\n return affineMatrix;\n },\n });\n}\n","// =============================================================================\n// Adapter: p5 Renderer Hooks\n// =============================================================================\n\nimport { setRendererRuntime } from \"../../core/renderer_runtime.js\";\n\nfunction getFramebufferHandle(target) {\n if (!target) return null;\n if (typeof target._framebufferToBind === \"function\") return target._framebufferToBind();\n return target.framebuffer ?? null;\n}\n\nfunction beginDirectMaskDraw(renderer, gl, target) {\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n if (hadDepthTest) gl.disable(gl.DEPTH_TEST);\n\n const previousTarget = renderer._renderer.activeFramebuffer?.() ?? null;\n if (previousTarget?._beforeEnd) previousTarget._beforeEnd();\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, getFramebufferHandle(target));\n gl.viewport(0, 0, target.width * target.density, target.height * target.density);\n\n return { hadDepthTest, previousTarget };\n}\n\nfunction endDirectMaskDraw(renderer, gl, state) {\n if (state?.hadDepthTest) gl.enable(gl.DEPTH_TEST);\n\n if (state?.previousTarget?._beforeBegin) {\n state.previousTarget._beforeBegin();\n return;\n }\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n renderer._renderer.viewport(\n renderer._renderer._origViewport.width,\n renderer._renderer._origViewport.height,\n );\n renderer._renderer._applyStencilTestIfClipping?.();\n}\n\nfunction resetP5ShaderTracking(renderer, gl) {\n const coreRenderer = renderer?._renderer;\n if (!coreRenderer) return;\n coreRenderer._curShader = null;\n coreRenderer._cachedBlendMode = null;\n coreRenderer._isBlending = null;\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n}\n\nexport function initP5RendererRuntime() {\n setRendererRuntime({\n beginDirectMaskDraw,\n endDirectMaskDraw,\n resetDirectShaderTracking: resetP5ShaderTracking,\n });\n}\n","// =============================================================================\n// Adapter: p5 Compositor Hooks\n// =============================================================================\n\nimport {\n setCompositorRuntime,\n blitDefaultFramebufferSource,\n} from \"../../core/compositor_runtime.js\";\n\nfunction clearTarget(renderer, target, isFramebufferTarget) {\n if (!target) return;\n\n if (isFramebufferTarget(target)) {\n target.draw(() => renderer.clear());\n return;\n }\n\n const ctx = target.drawingContext;\n ctx.save();\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.clearRect(0, 0, target.width, target.height);\n ctx.restore();\n}\n\nfunction ensureBlendShaderProgram(renderer, vertSrc, fragSrc) {\n if (!renderer.loaded) {\n renderer.loaded = true;\n renderer.shaderProgram ??= renderer.createShader(vertSrc, fragSrc);\n }\n return renderer.shaderProgram;\n}\n\nfunction ensureBlendSourceFramebuffer(\n renderer,\n currentFramebuffer,\n width,\n height,\n density,\n) {\n if (currentFramebuffer?.remove) currentFramebuffer.remove();\n const fb = renderer.createFramebuffer({\n width,\n height,\n density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n return fb;\n}\n\nconst createFramebuffer = (renderer, options) =>\n renderer.createFramebuffer(options);\n\nfunction runBlendShaderPass({\n renderer,\n shader,\n source,\n mask,\n color,\n isBrushMask,\n Cwidth,\n Cheight,\n dirtyRect,\n targetIsFramebuffer,\n withScissor,\n}) {\n const gl = renderer.drawingContext;\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n\n gl.disable(gl.DEPTH_TEST);\n\n renderer.push();\n renderer.translate(0, 0);\n renderer.shader(shader);\n\n shader.setUniform(\"u_source\", source);\n shader.setUniform(\"u_targetIsFramebuffer\", targetIsFramebuffer);\n shader.setUniform(\"u_isBrush\", isBrushMask);\n shader.setUniform(\"u_mask\", mask);\n shader.setUniform(\"u_color\", color);\n\n withScissor(\n gl,\n dirtyRect,\n () => {\n renderer.fill(0, 0, 0, 0);\n renderer.noStroke();\n renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);\n },\n !targetIsFramebuffer,\n );\n\n renderer.pop();\n renderer.resetShader();\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n}\n\nfunction blitSourceToFramebuffer(args) {\n if (args.isFramebufferTarget(args.sourceTarget)) {\n (args.sourceTarget.renderer ?? args.renderer)._renderer?.flushDraw?.();\n args.sourceFramebuffer.draw(() => {\n args.withScissor(\n args.renderer.drawingContext,\n args.dirtyRect,\n () => {\n args.renderer.clear();\n args.renderer.push();\n args.renderer.imageMode(args.renderer.CENTER);\n args.renderer.image(\n args.sourceTarget,\n 0,\n 0,\n args.Cwidth,\n args.Cheight,\n );\n args.renderer.pop();\n },\n false,\n );\n });\n return args.sourceFramebuffer;\n }\n\n args.renderer._renderer?.flushDraw?.();\n return blitDefaultFramebufferSource(args);\n}\n\nexport function initP5CompositorRuntime() {\n setCompositorRuntime({\n clearTarget,\n ensureBlendShaderProgram,\n ensureBlendSourceFramebuffer,\n createFramebuffer,\n runBlendShaderPass,\n blitSourceToFramebuffer,\n });\n}\n","// =============================================================================\n// Adapter: p5 Stroke Hooks\n// =============================================================================\n\nimport { Renderer, Instance } from \"../../core/target.js\";\nimport { setStrokeRuntime } from \"../../stroke/runtime.js\";\n\nconst getP5BrushFactory = () => Renderer ?? Instance ?? window.self?.p5?.instance;\n\nfunction createTipSurface(width, height) {\n const factory = getP5BrushFactory();\n if (!factory?.createGraphics) {\n throw new Error(\"p5 stroke tip creation requires an active renderer or instance.\");\n }\n return factory.createGraphics(width, height);\n}\n\nfunction loadImageTip(src, imageToWhite) {\n return new Promise((resolve, reject) => {\n const nativeImg = new window.Image();\n nativeImg.onload = () => {\n const factory = getP5BrushFactory();\n if (!factory?.createImage) {\n reject(new Error(\"p5 image tip loading requires an active renderer or instance.\"));\n return;\n }\n const p5img = factory.createImage(\n nativeImg.naturalWidth,\n nativeImg.naturalHeight,\n );\n p5img.drawingContext.drawImage(nativeImg, 0, 0);\n imageToWhite(p5img);\n resolve(p5img);\n };\n nativeImg.onerror = () =>\n reject(new Error(`Failed to load image tip: ${src}`));\n nativeImg.crossOrigin = \"anonymous\";\n nativeImg.src = src;\n });\n}\n\nexport function initP5StrokeRuntime() {\n setStrokeRuntime({\n createTipSurface,\n loadImageTip,\n });\n}\n","import { State } from \"./color.js\";\nimport { isFieldReady } from \"./flowfield.js\";\n\n// =============================================================================\n// SAVE / RESTORE\n// =============================================================================\n\n/**\n * Stack of saved brush states for push/pop operations.\n * A stack (not a single slot) is required because applyShader() internally\n * calls Renderer.push()/pop(), which fires our hook — a flat object would be\n * overwritten mid-draw and pop() would restore the wrong state.\n */\nconst _stateStack = [];\n\n/**\n * Pushes the current brush state onto the stack.\n */\nexport function push() {\n isFieldReady();\n _stateStack.push({\n fill: { ...State.fill },\n wash: State.wash ? { ...State.wash } : null,\n stroke: { ...State.stroke },\n hatch: { ...State.hatch },\n mass: State.mass ? { ...State.mass } : null,\n field: { ...State.field },\n });\n}\n\n/**\n * Pops the top brush state from the stack and restores it.\n */\nexport function pop() {\n const saved = _stateStack.pop();\n if (!saved) return;\n State.stroke = { ...saved.stroke };\n State.field = { ...saved.field };\n State.hatch = { ...saved.hatch };\n State.fill = { ...saved.fill };\n if (saved.wash) State.wash = { ...saved.wash };\n if (saved.mass) {\n State.mass = { ...saved.mass };\n } else if (State.mass) {\n State.mass = {\n ...State.mass,\n isActive: false,\n brush: null,\n color: null,\n options: {},\n };\n }\n}\n","/**\n * @fileoverview p5 entry point for p5.brush.\n */\n\nexport * from \"./index.shared.js\";\n\nimport { initP5TargetRuntime } from \"./adapters/p5/target.js\";\nimport { initP5Runtime } from \"./adapters/p5/runtime.js\";\nimport { initP5RendererRuntime } from \"./adapters/p5/renderer.js\";\nimport { initP5CompositorRuntime } from \"./adapters/p5/compositor.js\";\nimport { initP5StrokeRuntime } from \"./adapters/p5/stroke.js\";\nimport { registerP5Addon } from \"./adapters/p5/addon.js\";\n\ninitP5TargetRuntime();\ninitP5Runtime();\ninitP5RendererRuntime();\ninitP5CompositorRuntime();\ninitP5StrokeRuntime();\n\nif (typeof p5 !== \"undefined\") p5.registerAddon(registerP5Addon);\n","// =============================================================================\n// Adapter: p5 Addon Registration\n// =============================================================================\n\nimport { flushActiveComposite } from \"../../core/color.js\";\nimport {\n instance as bindInstance,\n activateInstance,\n deactivateInstance,\n} from \"../../core/target.js\";\nimport { push as brushPush, pop as brushPop } from \"../../core/save.js\";\nimport { seed as brushSeed, noiseSeed as brushNoiseSeed } from \"../../core/utils.js\";\n\n/**\n * Registers the p5 addon hooks that keep p5.brush in sync with p5's runtime.\n *\n * This stays in the p5 adapter layer so a future standalone build can provide\n * its own lifecycle integration without importing p5-specific globals.\n *\n * @param {*} _p5\n * @param {Object} fn\n * @param {Object} lifecycles\n */\nexport function registerP5Addon(_p5, fn, lifecycles) {\n lifecycles.presetup = function () {\n activateInstance(this);\n };\n\n lifecycles.predraw = function () {\n activateInstance(this);\n };\n\n lifecycles.postsetup = function () {\n bindInstance(this);\n flushActiveComposite();\n deactivateInstance();\n };\n\n lifecycles.postdraw = function () {\n bindInstance(this);\n flushActiveComposite();\n deactivateInstance();\n };\n\n const _push = fn.push;\n const _pop = fn.pop;\n const _randomSeed = fn.randomSeed;\n const _noiseSeed = fn.noiseSeed;\n\n fn.push = function () {\n _push.call(this);\n brushPush();\n };\n\n fn.pop = function () {\n _pop.call(this);\n brushPop();\n };\n\n fn.randomSeed = function (s) {\n _randomSeed.call(this, s);\n brushSeed(s);\n };\n\n fn.noiseSeed = function (s) {\n _noiseSeed.call(this, s);\n brushNoiseSeed(s);\n };\n}\n"],"names":["identityMatrix","a","b","c","d","x","y","usesRadians","fromDegrees","angle","createColor","Error","getAffineMatrix","SQRT3","Math","sqrt","F2","G2","fastFloor","floor","grad2","Float64Array","createNoise2D","random","perm","p","Uint8Array","i","tableSize","r","aux","buildPermutationTable","permGrad2x","map","v","permGrad2y","n0","n1","n2","s","j","t","x0","y0","i1","j1","x1","y1","x2","y2","ii","jj","t0","gi0","t1","gi1","t2","gi2","prng_alea","seed","opts","xg","AleaGen","prng","next","double","int32","quick","constructor","Date","n","mash","data","String","length","charCodeAt","h","this","s0","s1","s2","copy","f","rng","rng2","_seedCallbacks","_onSeed","cb","push","callback","noise","noise2","noiseSeed","rr","e","rr2","rArray","array","randInt","randInt2","gaussian","mean","stdev","u","log","cos","weightedRand","weights","totalWeight","entries","key","cumulative","rnd","isNaN","parseInt","value","withinBounds","constrain","low","high","max","min","nAngle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","fill","NaN","sLookup","idx","sin","toDegrees","rad","isRad","runtimeUsesRadians","toDegreesSigned","rotate","cx","cy","coseno","seno","dist","hypot","calcAngle","atan2","intersectLines","s1a","s1b","s2a","s2b","includeSegmentExtension","x3","y3","x4","y4","deltaX1","deltaY1","deltaX2","deltaY2","denominator","ua","ub","Cwidth","Cheight","Instance","Renderer","Density","targetRuntime","load","syncDensity","isCanvasReady","instance","inst","activateInstance","deactivateInstance","getActiveFramebuffer","isFramebufferTarget","setTargetState","state","target","expandDirtyRect","rect","padding","minX","minY","maxX","maxY","create2DCanvas","width","height","willReadFrequently","canvas","OffscreenCanvas","element","document","createElement","drawingContext","getContext","undefined","compositorRuntime","clearTarget","ensureBlendShaderProgram","ensureBlendSourceFramebuffer","createFramebuffer","runBlendShaderPass","blitSourceToFramebuffer","args","strokeComposite","fillComposite","clearRenderTarget","getTargetPixelSize","round","normalizeDirtyRect","ceil","clampDirtyRect","getFullDirtyRect","getFullRect","toScissorBox","flipY","normalized","withScissor","gl","draw","box","enable","SCISSOR_TEST","scissor","disable","State","isMixReady","loaded","Mix","isBlending","cachedColor","markDirtyRect","dirtyRect","isDrawn","clearMask","composite","glMask","getCompositeRect","isBrushMask","needsBlendSourceFramebuffer","blendSourceFramebuffer","pixelDensity","ensureResources","fillResources","mask","ctx","blend","_color","_isLast","isBrush","otherMask","nextColor","_array","colorChanged","justChanged","applyShader","shader","shaderProgram","activeFramebuffer","source","renderer","sourceTarget","sourceFramebuffer","targetIsFramebuffer","shaderMask","getShaderMask","color","flushActiveComposite","isLoaded","isFieldReady","resolution","left_x","top_y","num_columns","num_rows","addField","field","bs","ba","fillField","ar","abs","dif","sr","cr","_t","dir","offset","attractors","Array","from","wx","wy","att","dx","dy","w","freq","amp","_r","Position","m","mx","my","update","plotted","colIdx","rowIdx","reset","isIn","isActive","isInCanvas","skipCheck","list","get","current","wiggle","moveTo","_dir","_length","_step_length","movePos","_moveToDegrees","plotTo","_plot","_scale","_dirPlot","_step","scaleFactor","steps","fieldActive","usePlot","getRowIndex","y_offset","getColIndex","x_offset","col","row","Map","FIELD_ANGLE_MODES","Set","normalizeFieldAngleMode","options","angleMode","has","generateField","entry","normalizeFieldAngles","gen","keys","join","name","funct","set","fn","Polygon","pointsArray","useRawVertices","vertices","sides","arr","_intersectionCache","intersect","line","cacheKey","point1","point2","points","start","end","intersection","show","wash","mass","hatch","stroke","Plot","_type","segments","angles","pres","type","calcIndex","pol","addSegment","_a","_pres","_degrees","pop","reduce","sum","len","endPlot","pressure","_d","curving","index","map0","map1","suma","genPol","_x","_y","_side","step","numSteps","pos","pside","prevIdx","scale","arc","radius","startDeg","sweepDeg","segmentCount","segmentSweep","arcLength","startX","startY","_current","_curvature","_strokeArray","_strokeOrigin","SubPath","isClosed","curvature","vert","vertex","_createSpline","beginShape","endShape","close","PI2","pep","tep","pep2","done","p1","p2","p3","d1","d2","a1","a2","curvAdjust","dmax","temp","temp2","point3","point4","intPt","halfDist","asin","origin","strokeRuntime","createTipSurface","loadImageTip","isStrokeCompositeRegistered","createProgram","frag","src","VERTEX_SHADER","FRAGMENT_SHADER","createShader","shaderSource","compileShader","attachShader","linkProgram","rendererRuntime","beginDirectMaskDraw","endDirectMaskDraw","resetDirectShaderTracking","framebufferProjMatrix","vao","buf","program","loadedWidth","loadedHeight","brushMaskTarget","Attr","Frag","_ma","_mb","_mc","_md","_mx","_my","_halfW","_halfH","_density","circleData","INITIAL_CAPACITY","circleCount","bufferCapacity","gpuBufferSize","circleDirtyRect","imgProgram","imgVao","imgCornerBuf","imgInstanceBuf","imgAttr","imgFrag","imgGpuSize","imgData","IMG_INIT_CAP","imgCount","imgCapacity","imgDirtyRect","texCache","QUAD_CORNERS","getProjectionMatrix","beginMaskTarget","endMaskTarget","accumulateDirtyRect","currentRect","circle","diameter","alpha","newData","px","py","screenX","screenY","dScreenX","dScreenY","glDrawImages","p5img","targetState","tex","createTexture","bindTexture","TEXTURE_2D","texImage2D","RGBA","UNSIGNED_BYTE","texParameteri","TEXTURE_MIN_FILTER","LINEAR","TEXTURE_MAG_FILTER","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","useProgram","BLEND","blendFunc","ONE_MINUS_DST_ALPHA","ONE","activeTexture","TEXTURE0","uniform1i","u_tex","uniform4f","u_color","uniformMatrix4fv","u_proj","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","drawArraysInstanced","TRIANGLE_STRIP","flush","needsStrokeMask","remove","density","antialias","depth","stencil","_Renderer","weight","opacity","DEFAULT_CUSTOM_PRESSURE_VARIATION","warp","tilt","BrushState","BrushSetState","add","params","includes","markerTip","vibration","scatter","definition","sharpness","quality","grain","min_max","curve","variation","isArray","mode","rest","range","ns","nm","ne","normalizePressure","tip","deleteTexture","delete","invalidateTexEntry","g","background","noSmooth","translate","noStroke","T","imageToWhite","tips","tipKey","param","colors","buffers","image","getBrushParams","brushName","pick","arguments","strokeWeight","_position","initializeDrawingState","plot","snapshotMatrix","gaussians","angleScale","isPlot","cp","ct","cs","ck","noiseoffset","rendererMask","ensureBrushMaskTarget","nextGl","needsContextRefresh","forEach","getAttribLocation","getUniformLocation","createVertexArray","createBuffer","enableVertexAttribArray","a_position","vertexAttribPointer","FLOAT","a_radius","a_alpha","clear","STATIC_DRAW","a_corner","a_pos","IMG_FLOATS","vertexAttribDivisor","a_size","a_angle","isReady","switchingToBrush","saveState","stepSize","spacing","totalSteps","pressureCount","cachedPressure","lineNoiseCount","cachedLineNoise","u_matrix","drawArrays","POINTS","glDraw","restoreState","calculatePressure","lineNoise","sw","iterations","rX","yRandomFactor","sqrtPart","drawSpray","drawMarker","drawImageTip","plotAngle","plotCos","plotSin","perp","along","drawDefault","simPressure","peakPos","halfWidth","pow","gauss","vibrate","rx","ry","size","overscan","maxPressure","scatterReach","tipReach","getImageTipOverscan","extraPadding","halfSize","extraRadius","base","boundsRadius","stampImage","_vals","_standard_brushes","obj","prototype","_brush","_weight","loadPixels","average","pixels","updatePixels","filter","k","Promise","all","then","HatchState","HatchSetState","rand","continuous","gradient","scanlineHatch","polygon","cosA","sinA","cosB","sinB","verts","rotated","Infinity","edges","eLen","Y","sort","scanY","getHatchLines","polygons","segs","poly","getHatchSegments","getActiveHatchConfig","lines","isConnector","prev","createHatch","drawSegment","save","hBrush","Object","values","drawFn","withHatchStyle","renderHatchSegments","jitterPolygon","jitterX","jitterY","projectAnchorToBisector","anchor","nx","ny","getShortArcAngles","toAngleUnit","endDeg","splitSegment","seg","gap","gx","gy","drawMassArcs","pivotBias","bias","bounds","getPolygonBounds","sx","sy","getPivotAnchor","parts","part","center","startAngle","endAngle","drawMassPass","createMass","shape","pols","isPolygon","brush","basePolygon","maxJitter","jitters","getMassPolygons","hatchState","brushState","fieldState","precision","strength","outline","hatchDist","baseAngle","_dist","_angle","_options","FillMaskUploadCanvas","isFillCompositeRegistered","maskWidth","maskHeight","needsFillMaskCanvas","fillMaskFramebuffer","needsFillMaskFramebuffer","imageSmoothingEnabled","_getActiveFramebuffer","uploadRect","uploadWidth","uploadHeight","uploadContext","clearRect","drawImage","colorTexture","texSubImage2D","GROW_CAP","_growInsX","_growInsY","_growMods","_growDirs","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","_polygon","_gaussians","_fillGaussianPools","_isLeft","FillPoly","isFirst","midP","rayCalc","v1","v2","side","rt","mid","ray","sizeX","sizeY","rc","count","isect","trim","keep","dst","trimStart","trimEnd","edgeStart","edgeEnd","edgeVec","newVertex","insertIdx","splice","ratio","L","indices","sv","sm","sd","crossings","ay","by","flipDirs","grow","tr_v","tr_m","tr_dir","outLen","insertedX","insertedY","newMods","newDirs","bleedDirDeg","gPool","gPoolLen","g2Pool","g2PoolLen","fv","fm","fd","insertedIdx","mod","cv","nv","mi","di","rotDeg","sideX","sideY","dirX","dirY","nextMod","kept","slice","intensity","texture","int","switchingToFill","setTransform","strokeStyle","_getRed","_getGreen","_getBlue","lineCap","darker","sparse","layer","numLayers","erase","restore","lineWidth","fillStyle","matrix","getTransform","beginPath","first","tx","ty","lineTo","closePath","strokePadding","drawPolygon","numCircles","halfSizeX","halfSizeY","minSize","minSizeFactor","maxSizeFactor","midX","midY","globalCompositeOperation","filterPoints","again","steiner","equals","area","removeNode","earcutLinked","ear","triangles","dim","invSize","pass","z","zOrder","prevZ","nextZ","numMerges","inSize","tail","q","pSize","qSize","sortLinked","indexCurve","stop","isEarHashed","isEar","cureLocalIntersections","splitEarcut","ax","bx","pointInTriangleExceptFirst","minZ","maxZ","intersects","locallyInside","isValidDiagonal","splitPolygon","pointInTriangle","intersectsPolygon","inside","middleInside","q1","q2","o1","sign","o2","o3","o4","onSegment","num","createNode","b2","an","bp","insertNode","last","_opacity","_bleed","fluid","modifiers","_","shift","shifted","pts","point","cross","_center","createFill","FillSetState","washProgram","washVao","washBuffer","washProjection","washGpuBufferSize","WashAttr","WashUniform","transformVertexToScreen","ensureWashReady","vertexCount","flat","holeIndices","outerLen","outerNode","signedArea","linkedList","earcut","buildTriangleBuffer","blendEquation","FUNC_ADD","ONE_MINUS_SRC_ALPHA","TRIANGLES","drawWashPolygon","ReadySketch","ActiveInstance","ActiveInstanceStack","_isReady","begin","_pInst","isFiniteSize","Number","isFinite","safeRead","getter","_error","isReadyWebGLSketch","candidate","webglVersion","rememberReadySketch","getSketchRenderer","window","self","p5","buffer","sketchRenderer","owner","resolveTarget","getP5RuntimeRenderer","affineMatrix","isRadians","RADIANS","hadDepthTest","isEnabled","DEPTH_TEST","previousTarget","_renderer","_beforeEnd","bindFramebuffer","FRAMEBUFFER","_framebufferToBind","framebuffer","getFramebufferHandle","viewport","_beforeBegin","_origViewport","_applyStencilTestIfClipping","resetP5ShaderTracking","coreRenderer","_curShader","_cachedBlendMode","_isBlending","vertSrc","fragSrc","currentFramebuffer","setUniform","resetShader","flushDraw","imageMode","CENTER","sourceBox","previousReadFramebuffer","getParameter","READ_FRAMEBUFFER_BINDING","previousDrawFramebuffer","DRAW_FRAMEBUFFER_BINDING","READ_FRAMEBUFFER","DRAW_FRAMEBUFFER","clearColor","COLOR_BUFFER_BIT","blitFramebuffer","NEAREST","blitDefaultFramebufferSource","getP5BrushFactory","factory","createGraphics","resolve","reject","nativeImg","Image","onload","createImage","naturalWidth","naturalHeight","onerror","crossOrigin","_stateStack","hooks","mat4","uModelMatrix","initP5Runtime","initP5RendererRuntime","initP5CompositorRuntime","initP5StrokeRuntime","registerAddon","_p5","lifecycles","presetup","predraw","postsetup","bindInstance","postdraw","_push","_pop","_randomSeed","randomSeed","_noiseSeed","call","saved","brushPop","brushSeed","brushNoiseSeed","angleOffset","randomFactor","randomAngle","offsetX","offsetY","region","loadTarget","currentField","_array_points"],"mappings":"6BAIA,MAAMA,EAAiB,CACrBC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,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BoS,GAC3B,IAAK,MAAMgS,MAAEA,KAAW/S,GAAK8b,SACvB/I,IACFA,EAAMzC,QAAUvP,EAChBgS,EAAM7B,SAAWnQ,EACjBgS,EAAMgD,SAAWhV,EAGvB,6BNSO,SAAgBk0B,EAAetuB,EAAa,IACjD,IAAKsuB,GAAiBA,EAAcrkC,OAAS,EAC3C,MAAM,IAAI/D,MACR,+EAGIsa,GAAc8tB,EAAetuB,GACnCzM,MACJ","x_google_ignoreList":[1,2,23]}
\ No newline at end of file
+{"version":3,"file":"p5.brush.js","sources":["../src/core/runtime.js","../node_modules/simplex-noise/dist/esm/simplex-noise.js","../node_modules/esm-seedrandom/esm/index.mjs","../src/core/utils.js","../src/core/target.js","../src/core/dirty_rect.js","../src/core/compositor_runtime.js","../src/core/color.js","../src/core/flowfield.js","../src/core/polygon.js","../src/core/plot.js","../src/core/primitives.js","../src/stroke/runtime.js","../src/stroke/composite.js","../src/core/gl/utils.js","../src/core/renderer_runtime.js","../src/stroke/gl_draw.js","../src/stroke/stroke.js","../src/hatch/hatch.js","../src/hatch/mass.js","../src/fill/mask.js","../src/fill/composite.js","../src/fill/fill.js","../node_modules/earcut/src/earcut.js","../src/fill/wash.js","../src/adapters/p5/target.js","../src/adapters/p5/runtime.js","../src/adapters/p5/renderer.js","../src/adapters/p5/compositor.js","../src/adapters/p5/stroke.js","../src/core/save.js","../src/index.p5.js","../src/adapters/p5/addon.js"],"sourcesContent":["// =============================================================================\n// Runtime Hooks\n// =============================================================================\n\nconst identityMatrix = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\n\nexport let usesRadians = () => false;\nexport let fromDegrees = (angle) => angle;\nexport let createColor = () => {\n throw new Error(\"No runtime color adapter registered.\");\n};\nexport let getAffineMatrix = () => identityMatrix;\n\n/**\n * Registers or updates host-runtime hooks used by core modules.\n *\n * @param {object} hooks\n */\nexport function setRuntime(hooks) {\n if (hooks.usesRadians) usesRadians = hooks.usesRadians;\n if (hooks.fromDegrees) fromDegrees = hooks.fromDegrees;\n if (hooks.createColor) createColor = hooks.createColor;\n if (hooks.getAffineMatrix) getAffineMatrix = hooks.getAffineMatrix;\n}\n","/*\n * A fast javascript implementation of simplex noise by Jonas Wagner\n\nBased on a speed-improved simplex noise algorithm for 2D, 3D and 4D in Java.\nWhich is based on example code by Stefan Gustavson ([email protected]).\nWith Optimisations by Peter Eastman ([email protected]).\nBetter rank ordering method by Stefan Gustavson in 2012.\n\n Copyright (c) 2024 Jonas Wagner\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n */\n// these __PURE__ comments help uglifyjs with dead code removal\n//\nconst SQRT3 = /*#__PURE__*/ Math.sqrt(3.0);\nconst SQRT5 = /*#__PURE__*/ Math.sqrt(5.0);\nconst F2 = 0.5 * (SQRT3 - 1.0);\nconst G2 = (3.0 - SQRT3) / 6.0;\nconst F3 = 1.0 / 3.0;\nconst G3 = 1.0 / 6.0;\nconst F4 = (SQRT5 - 1.0) / 4.0;\nconst G4 = (5.0 - SQRT5) / 20.0;\n// I'm really not sure why this | 0 (basically a coercion to int)\n// is making this faster but I get ~5 million ops/sec more on the\n// benchmarks across the board or a ~10% speedup.\nconst fastFloor = (x) => Math.floor(x) | 0;\nconst grad2 = /*#__PURE__*/ new Float64Array([1, 1,\n -1, 1,\n 1, -1,\n -1, -1,\n 1, 0,\n -1, 0,\n 1, 0,\n -1, 0,\n 0, 1,\n 0, -1,\n 0, 1,\n 0, -1]);\n// double seems to be faster than single or int's\n// probably because most operations are in double precision\nconst grad3 = /*#__PURE__*/ new Float64Array([1, 1, 0,\n -1, 1, 0,\n 1, -1, 0,\n -1, -1, 0,\n 1, 0, 1,\n -1, 0, 1,\n 1, 0, -1,\n -1, 0, -1,\n 0, 1, 1,\n 0, -1, 1,\n 0, 1, -1,\n 0, -1, -1]);\n// double is a bit quicker here as well\nconst grad4 = /*#__PURE__*/ new Float64Array([0, 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1,\n 0, -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1,\n 1, 0, 1, 1, 1, 0, 1, -1, 1, 0, -1, 1, 1, 0, -1, -1,\n -1, 0, 1, 1, -1, 0, 1, -1, -1, 0, -1, 1, -1, 0, -1, -1,\n 1, 1, 0, 1, 1, 1, 0, -1, 1, -1, 0, 1, 1, -1, 0, -1,\n -1, 1, 0, 1, -1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, -1,\n 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1, 0,\n -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1, 0]);\n/**\n * Creates a 2D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction2D}\n */\nexport function createNoise2D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating this yields a little ~3% performance improvement.\n const permGrad2x = new Float64Array(perm).map(v => grad2[(v % 12) * 2]);\n const permGrad2y = new Float64Array(perm).map(v => grad2[(v % 12) * 2 + 1]);\n return function noise2D(x, y) {\n // if(!isFinite(x) || !isFinite(y)) return 0;\n let n0 = 0; // Noise contributions from the three corners\n let n1 = 0;\n let n2 = 0;\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y) * F2; // Hairy factor for 2D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const t = (i + j) * G2;\n const X0 = i - t; // Unskew the cell origin back to (x,y) space\n const Y0 = j - t;\n const x0 = x - X0; // The x,y distances from the cell origin\n const y0 = y - Y0;\n // For the 2D case, the simplex shape is an equilateral triangle.\n // Determine which simplex we are in.\n let i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords\n if (x0 > y0) {\n i1 = 1;\n j1 = 0;\n } // lower triangle, XY order: (0,0)->(1,0)->(1,1)\n else {\n i1 = 0;\n j1 = 1;\n } // upper triangle, YX order: (0,0)->(0,1)->(1,1)\n // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and\n // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where\n // c = (3-sqrt(3))/6\n const x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords\n const y1 = y0 - j1 + G2;\n const x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords\n const y2 = y0 - 1.0 + 2.0 * G2;\n // Work out the hashed gradient indices of the three simplex corners\n const ii = i & 255;\n const jj = j & 255;\n // Calculate the contribution from the three corners\n let t0 = 0.5 - x0 * x0 - y0 * y0;\n if (t0 >= 0) {\n const gi0 = ii + perm[jj];\n const g0x = permGrad2x[gi0];\n const g0y = permGrad2y[gi0];\n t0 *= t0;\n // n0 = t0 * t0 * (grad2[gi0] * x0 + grad2[gi0 + 1] * y0); // (x,y) of grad3 used for 2D gradient\n n0 = t0 * t0 * (g0x * x0 + g0y * y0);\n }\n let t1 = 0.5 - x1 * x1 - y1 * y1;\n if (t1 >= 0) {\n const gi1 = ii + i1 + perm[jj + j1];\n const g1x = permGrad2x[gi1];\n const g1y = permGrad2y[gi1];\n t1 *= t1;\n // n1 = t1 * t1 * (grad2[gi1] * x1 + grad2[gi1 + 1] * y1);\n n1 = t1 * t1 * (g1x * x1 + g1y * y1);\n }\n let t2 = 0.5 - x2 * x2 - y2 * y2;\n if (t2 >= 0) {\n const gi2 = ii + 1 + perm[jj + 1];\n const g2x = permGrad2x[gi2];\n const g2y = permGrad2y[gi2];\n t2 *= t2;\n // n2 = t2 * t2 * (grad2[gi2] * x2 + grad2[gi2 + 1] * y2);\n n2 = t2 * t2 * (g2x * x2 + g2y * y2);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to return values in the interval [-1,1].\n return 70.0 * (n0 + n1 + n2);\n };\n}\n/**\n * Creates a 3D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction3D}\n */\nexport function createNoise3D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these seems to yield a speedup of over 15%\n const permGrad3x = new Float64Array(perm).map(v => grad3[(v % 12) * 3]);\n const permGrad3y = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 1]);\n const permGrad3z = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 2]);\n return function noise3D(x, y, z) {\n let n0, n1, n2, n3; // Noise contributions from the four corners\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y + z) * F3; // Very nice and simple skew factor for 3D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const t = (i + j + k) * G3;\n const X0 = i - t; // Unskew the cell origin back to (x,y,z) space\n const Y0 = j - t;\n const Z0 = k - t;\n const x0 = x - X0; // The x,y,z distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n // For the 3D case, the simplex shape is a slightly irregular tetrahedron.\n // Determine which simplex we are in.\n let i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords\n let i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords\n if (x0 >= y0) {\n if (y0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // X Y Z order\n else if (x0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // X Z Y order\n else {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // Z X Y order\n }\n else { // x0<y0\n if (y0 < z0) {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Z Y X order\n else if (x0 < z0) {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Y Z X order\n else {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // Y X Z order\n }\n // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),\n // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and\n // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where\n // c = 1/6.\n const x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords\n const y1 = y0 - j1 + G3;\n const z1 = z0 - k1 + G3;\n const x2 = x0 - i2 + 2.0 * G3; // Offsets for third corner in (x,y,z) coords\n const y2 = y0 - j2 + 2.0 * G3;\n const z2 = z0 - k2 + 2.0 * G3;\n const x3 = x0 - 1.0 + 3.0 * G3; // Offsets for last corner in (x,y,z) coords\n const y3 = y0 - 1.0 + 3.0 * G3;\n const z3 = z0 - 1.0 + 3.0 * G3;\n // Work out the hashed gradient indices of the four simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n // Calculate the contribution from the four corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad3x[gi0] * x0 + permGrad3y[gi0] * y0 + permGrad3z[gi0] * z0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad3x[gi1] * x1 + permGrad3y[gi1] * y1 + permGrad3z[gi1] * z1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad3x[gi2] * x2 + permGrad3y[gi2] * y2 + permGrad3z[gi2] * z2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + 1 + perm[jj + 1 + perm[kk + 1]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad3x[gi3] * x3 + permGrad3y[gi3] * y3 + permGrad3z[gi3] * z3);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to stay just inside [-1,1]\n return 32.0 * (n0 + n1 + n2 + n3);\n };\n}\n/**\n * Creates a 4D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction4D}\n */\nexport function createNoise4D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these leads to a ~10% speedup\n const permGrad4x = new Float64Array(perm).map(v => grad4[(v % 32) * 4]);\n const permGrad4y = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 1]);\n const permGrad4z = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 2]);\n const permGrad4w = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 3]);\n return function noise4D(x, y, z, w) {\n let n0, n1, n2, n3, n4; // Noise contributions from the five corners\n // Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in\n const s = (x + y + z + w) * F4; // Factor for 4D skewing\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const l = fastFloor(w + s);\n const t = (i + j + k + l) * G4; // Factor for 4D unskewing\n const X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space\n const Y0 = j - t;\n const Z0 = k - t;\n const W0 = l - t;\n const x0 = x - X0; // The x,y,z,w distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n const w0 = w - W0;\n // For the 4D case, the simplex is a 4D shape I won't even try to describe.\n // To find out which of the 24 possible simplices we're in, we need to\n // determine the magnitude ordering of x0, y0, z0 and w0.\n // Six pair-wise comparisons are performed between each possible pair\n // of the four coordinates, and the results are used to rank the numbers.\n let rankx = 0;\n let ranky = 0;\n let rankz = 0;\n let rankw = 0;\n if (x0 > y0)\n rankx++;\n else\n ranky++;\n if (x0 > z0)\n rankx++;\n else\n rankz++;\n if (x0 > w0)\n rankx++;\n else\n rankw++;\n if (y0 > z0)\n ranky++;\n else\n rankz++;\n if (y0 > w0)\n ranky++;\n else\n rankw++;\n if (z0 > w0)\n rankz++;\n else\n rankw++;\n // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order.\n // Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w and x<w\n // impossible. Only the 24 indices which have non-zero entries make any sense.\n // We use a thresholding to set the coordinates in turn from the largest magnitude.\n // Rank 3 denotes the largest coordinate.\n // Rank 2 denotes the second largest coordinate.\n // Rank 1 denotes the second smallest coordinate.\n // The integer offsets for the second simplex corner\n const i1 = rankx >= 3 ? 1 : 0;\n const j1 = ranky >= 3 ? 1 : 0;\n const k1 = rankz >= 3 ? 1 : 0;\n const l1 = rankw >= 3 ? 1 : 0;\n // The integer offsets for the third simplex corner\n const i2 = rankx >= 2 ? 1 : 0;\n const j2 = ranky >= 2 ? 1 : 0;\n const k2 = rankz >= 2 ? 1 : 0;\n const l2 = rankw >= 2 ? 1 : 0;\n // The integer offsets for the fourth simplex corner\n const i3 = rankx >= 1 ? 1 : 0;\n const j3 = ranky >= 1 ? 1 : 0;\n const k3 = rankz >= 1 ? 1 : 0;\n const l3 = rankw >= 1 ? 1 : 0;\n // The fifth corner has all coordinate offsets = 1, so no need to compute that.\n const x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords\n const y1 = y0 - j1 + G4;\n const z1 = z0 - k1 + G4;\n const w1 = w0 - l1 + G4;\n const x2 = x0 - i2 + 2.0 * G4; // Offsets for third corner in (x,y,z,w) coords\n const y2 = y0 - j2 + 2.0 * G4;\n const z2 = z0 - k2 + 2.0 * G4;\n const w2 = w0 - l2 + 2.0 * G4;\n const x3 = x0 - i3 + 3.0 * G4; // Offsets for fourth corner in (x,y,z,w) coords\n const y3 = y0 - j3 + 3.0 * G4;\n const z3 = z0 - k3 + 3.0 * G4;\n const w3 = w0 - l3 + 3.0 * G4;\n const x4 = x0 - 1.0 + 4.0 * G4; // Offsets for last corner in (x,y,z,w) coords\n const y4 = y0 - 1.0 + 4.0 * G4;\n const z4 = z0 - 1.0 + 4.0 * G4;\n const w4 = w0 - 1.0 + 4.0 * G4;\n // Work out the hashed gradient indices of the five simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n const ll = l & 255;\n // Calculate the contribution from the five corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk + perm[ll]]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad4x[gi0] * x0 + permGrad4y[gi0] * y0 + permGrad4z[gi0] * z0 + permGrad4w[gi0] * w0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad4x[gi1] * x1 + permGrad4y[gi1] * y1 + permGrad4z[gi1] * z1 + permGrad4w[gi1] * w1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad4x[gi2] * x2 + permGrad4y[gi2] * y2 + permGrad4z[gi2] * z2 + permGrad4w[gi2] * w2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad4x[gi3] * x3 + permGrad4y[gi3] * y3 + permGrad4z[gi3] * z3 + permGrad4w[gi3] * w3);\n }\n let t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4;\n if (t4 < 0)\n n4 = 0.0;\n else {\n const gi4 = ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]];\n t4 *= t4;\n n4 = t4 * t4 * (permGrad4x[gi4] * x4 + permGrad4y[gi4] * y4 + permGrad4z[gi4] * z4 + permGrad4w[gi4] * w4);\n }\n // Sum up and scale the result to cover the range [-1,1]\n return 27.0 * (n0 + n1 + n2 + n3 + n4);\n };\n}\n/**\n * Builds a random permutation table.\n * This is exported only for (internal) testing purposes.\n * Do not rely on this export.\n * @private\n */\nexport function buildPermutationTable(random) {\n const tableSize = 512;\n const p = new Uint8Array(tableSize);\n for (let i = 0; i < tableSize / 2; i++) {\n p[i] = i;\n }\n for (let i = 0; i < tableSize / 2 - 1; i++) {\n const r = i + ~~(random() * (256 - i));\n const aux = p[i];\n p[i] = p[r];\n p[r] = aux;\n }\n for (let i = 256; i < tableSize; i++) {\n p[i] = p[i - 256];\n }\n return p;\n}\n//# sourceMappingURL=simplex-noise.js.map","function _prng_restore(prng, xg, opts) {\n let state = opts && opts.state;\n if (state) {\n if (typeof(state) == 'object') xg.copy(state, xg);\n prng.state = () => xg.copy(xg, {});\n }\n}\n\nfunction _prng_xor_core(xg, opts) {\n let prng = () => (xg.next() >>> 0) / 0x100000000;\n\n prng.double = () => {\n let top, bot, result;\n do {\n top = xg.next() >>> 11;\n bot = (xg.next() >>> 0) / 0x100000000;\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n\n prng.int32 = () => xg.next() | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng;\n}\n\n// A port of an algorithm by Johannes Baagøe <[email protected]>, 2010\nfunction prng_alea(seed, opts) {\n let xg = new AleaGen(seed);\n\n let prng = () => xg.next();\n\n prng.double = () =>\n prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53\n\n prng.int32 = () => (xg.next() * 0x100000000) | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\nclass AleaGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let n = 0xefc8249d;\n\n // Apply the seeding algorithm from Baagoe.\n this.c = 1;\n this.s0 = mash(' ');\n this.s1 = mash(' ');\n this.s2 = mash(' ');\n this.s0 -= mash(seed);\n if (this.s0 < 0) { this.s0 += 1; }\n this.s1 -= mash(seed);\n if (this.s1 < 0) { this.s1 += 1; }\n this.s2 -= mash(seed);\n if (this.s2 < 0) { this.s2 += 1; }\n\n function mash(data) {\n data = String(data);\n for (let i = 0; i < data.length; i++) {\n n += data.charCodeAt(i);\n let h = 0.02519603282416938 * n;\n n = h >>> 0;\n h -= n;\n h *= n;\n n = h >>> 0;\n h -= n;\n n += h * 0x100000000; // 2^32\n }\n return (n >>> 0) * 2.3283064365386963e-10; // 2^-32\n }\n }\n\n next() {\n let {c,s0,s1,s2} = this;\n let t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32\n this.s0 = s1;\n this.s1 = s2;\n return this.s2 = t - (this.c = t | 0);\n }\n\n copy(f, t) {\n t.c = f.c;\n t.s0 = f.s0;\n t.s1 = f.s1;\n t.s2 = f.s2;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xor128\" prng algorithm by\nfunction prng_xor128(seed, opts) {\n let xg = new Xor128Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass Xor128Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w} = this;\n let t = x ^ (x << 11);\n this.x = y;\n this.y = z;\n this.z = w;\n return this.w = w ^ ((w >>> 19) ^ t ^ (t >>> 8));\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorwow\" prng algorithm by\nfunction prng_xorwow(seed, opts) {\n let xg = new XorWowGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass XorWowGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n this.v = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n if (k == strseed.length) {\n this.d = this.x << 10 ^ this.x >>> 4;\n }\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w,v,d} = this;\n let t = (x ^ (x >>> 2));\n this.x = y;\n this.y = z;\n this.z = w;\n this.w = v;\n return (this.d = (d + 362437 | 0)) +\n (this.v = (v ^ (v << 4)) ^ (t ^ (t << 1))) | 0;\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n t.v = f.v;\n t.d = f.d;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorshift7\" algorithm by\nfunction prng_xorshift7(seed, opts) {\n let xg = new XorShift7Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass XorShift7Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n var j, w, x = [];\n\n if (seed === (seed | 0)) {\n // Seed state array using a 32-bit integer.\n w = x[0] = seed;\n } else {\n // Seed state using a string.\n seed = '' + seed;\n for (j = 0; j < seed.length; ++j) {\n x[j & 7] = (x[j & 7] << 15) ^\n (seed.charCodeAt(j) + x[(j + 1) & 7] << 13);\n }\n }\n\n // Enforce an array length of 8, not all zeroes.\n while (x.length < 8) x.push(0);\n for (j = 0; j < 8 && x[j] === 0; ++j);\n if (j == 8) w = x[7] = -1; else w = x[j];\n\n this.x = x;\n this.i = 0;\n\n // Discard an initial 256 values.\n for (j = 256; j > 0; --j) {\n this.next();\n }\n }\n\n next() {\n // Update xor generator.\n let t, v, {x,i} = this;\n t = x[i]; t ^= (t >>> 7); v = t ^ (t << 24);\n t = x[(i + 1) & 7]; v ^= t ^ (t >>> 10);\n t = x[(i + 3) & 7]; v ^= t ^ (t >>> 3);\n t = x[(i + 4) & 7]; v ^= t ^ (t << 7);\n t = x[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);\n x[i] = v;\n this.i = (i + 1) & 7;\n return v;\n };\n\n copy(f, t) {\n t.x = [... f.x];\n t.i = f.i;\n return t;\n }\n}\n\n// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.\nfunction prng_xor4096(seed, opts) {\n let xg = new Xor4096Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass Xor4096Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let t, v, i, j, w, X = [], limit = 128;\n if (seed === (seed | 0)) {\n // Numeric seeds initialize v, which is used to generates X.\n v = seed;\n seed = null;\n } else {\n // String seeds are mixed into v and X one character at a time.\n seed = seed + '\\0';\n v = 0;\n limit = Math.max(limit, seed.length);\n }\n // Initialize circular array and weyl value.\n for (i = 0, j = -32; j < limit; ++j) {\n // Put the unicode characters into the array, and shuffle them.\n if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);\n // After 32 shuffles, take v as the starting w value.\n if (j === 0) w = v;\n v ^= v << 10;\n v ^= v >>> 15;\n v ^= v << 4;\n v ^= v >>> 13;\n if (j >= 0) {\n w = (w + 0x61c88647) | 0; // Weyl.\n t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array.\n i = (0 == t) ? i + 1 : 0; // Count zeroes.\n }\n }\n // We have detected all zeroes; make the key nonzero.\n if (i >= 128) {\n X[(seed && seed.length || 0) & 127] = -1;\n }\n // Run the generator 512 times to further mix the state before using it.\n // Factoring this as a function slows the main generator, so it is just\n // unrolled here. The weyl generator is not advanced while warming up.\n i = 127;\n for (j = 4 * 128; j > 0; --j) {\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n X[i] = v ^ t;\n }\n // Storing state as object members is faster than using closure variables.\n this.w = w;\n this.X = X;\n this.i = i;\n }\n\n next() {\n let t, v, {w, X, i} = this;\n // Update Weyl generator.\n this.w = w = (w + 0x61c88647) | 0;\n // Update xor generator.\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n // Update Xor generator array state.\n v = X[i] = v ^ t;\n this.i = i;\n // Result is the combination.\n return (v + (w ^ (w >>> 16))) | 0;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.w = f.w;\n t.X = [... f.X];\n return t;\n }\n}\n\n// A Javascript implementaion of the \"Tyche-i\" prng algorithm by\nfunction prng_tychei(seed, opts) {\n let xg = new TycheiGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass TycheiGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.a = 0;\n this.b = 0;\n this.c = 2654435769 | 0;\n this.d = 1367130551;\n\n if (seed === Math.floor(seed)) {\n // Integer seed.\n this.a = (seed / 0x100000000) | 0;\n this.b = seed | 0;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 20; k++) {\n this.b ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {a,b,c,d} = this;\n b = (b << 25) ^ (b >>> 7) ^ c;\n c = (c - d) | 0;\n d = (d << 24) ^ (d >>> 8) ^ a;\n a = (a - b) | 0;\n this.b = b = (b << 20) ^ (b >>> 12) ^ c;\n this.c = c = (c - d) | 0;\n this.d = (d << 16) ^ (c >>> 16) ^ a;\n return this.a = (a - b) | 0;\n };\n\n copy(f, t) {\n t.a = f.a;\n t.b = f.b;\n t.c = f.c;\n t.d = f.d;\n return t;\n }\n}\n\n\n/* The following is non-inverted tyche, which has better internal\n * bit diffusion, but which is about 25% slower than tyche-i in JS.\n *\n\nclass TycheiGenAlt extends TycheiGen {\n next() {\n let {a,b,c,d} = this\n a = (a + b | 0) >>> 0;\n d = d ^ a; d = d << 16 ^ d >>> 16;\n c = c + d | 0;\n b = b ^ c; b = b << 12 ^ d >>> 20;\n this.a = a = a + b | 0;\n d = d ^ a; this.d = d = d << 8 ^ d >>> 24;\n this.c = c = c + d | 0;\n b = b ^ c;\n return this.b = (b << 7 ^ b >>> 25);\n }\n}\n*/\n\n/*\nCopyright 2019 David Bau.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*/\nfunction prng_arc4(seed, opts) {\n let xg = new ARC4Gen(seed);\n let prng = () => xg.next();\n\n prng.double = prng;\n\n prng.int32 = () => xg.g(4) | 0;\n\n prng.quick = () => xg.g(4) / 0x100000000;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\n\n//\n// ARC4\n//\n// An ARC4 implementation. The constructor takes a key in the form of\n// an array of at most (width) integers that should be 0 <= x < (width).\n//\n// The g(count) method returns a pseudorandom integer that concatenates\n// the next (count) outputs from ARC4. Its return value is a number x\n// that is in the range 0 <= x < (width ^ count).\n//\n\n//\n// The following constants are related to IEEE 754 limits.\n//\n\n// const width = 256 // each RC4 output is 0 <= x < 256\n// const chunks = 6 // at least six RC4 outputs for each double\nconst _arc4_startdenom = 281474976710656; // 256 ** 6 == width ** chunks\nconst _arc4_significance = 4503599627370496; // 2 ** 52 significant digits in a double\nconst _arc4_overflow = 9007199254740992; // 2 ** 53 == significance * 2\n\n\nclass ARC4Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let key = this.mixkey(seed, []);\n let i,j,t, S=[], keylen = key.length;\n this.i = this.j = i = j = 0;\n this.S = S;\n\n // The empty key [] is treated as [0].\n if (!keylen) { key = [keylen++]; }\n\n // Set up S using the standard key scheduling algorithm.\n while (i <= 0xff) {\n S[i] = i++;\n }\n for (i = 0; i <= 0xff; i++) {\n S[i] = S[j = 0xff & (j + key[i % keylen] + (t = S[i]))];\n S[j] = t;\n }\n\n // For robust unpredictability, the function call below automatically\n // discards an initial batch of values. This is called RC4-drop[256].\n // See http://google.com/search?q=rsa+fluhrer+response&btnI\n this.g(256);\n }\n\n next() {\n // This function returns a random double in [0, 1) that contains\n // randomness in every bit of the mantissa of the IEEE 754 value.\n\n let n = this.g(6); // Start with a numerator n < 2 ^ 48\n let d = _arc4_startdenom; // and denominator d = 2 ^ 48.\n let x = 0; // and no 'extra last byte'.\n\n while (n < _arc4_significance) { // Fill up all significant digits (2 ** 52)\n n = (n + x) * 256; // by shifting numerator and\n d *= 256; // denominator and generating a\n x = this.g(1); // new least-significant-byte.\n }\n while (n >= _arc4_overflow) { // To avoid rounding past overflow, before adding\n n /= 2; // last byte, shift everything\n d /= 2; // right using integer math until\n x >>>= 1; // we have exactly the desired bits.\n }\n return (n + x) / d; // Form the number within [0, 1).\n }\n\n g(count) {\n // The \"g\" method returns the next (count) outputs as one number.\n let t, r = 0, {i,j,S} = this;\n while (count--) {\n t = S[i = 0xff & (i + 1)];\n r = r * 256 + S[0xff & ((S[i] = S[j = 0xff & (j + t)]) + (S[j] = t))];\n }\n this.i = i;\n this.j = j;\n return r;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.j = f.j;\n t.S = [... f.S];\n return t;\n }\n\n mixkey(seed, key) {\n seed = seed + '';\n let smear=0, j=0;\n while (j < seed.length) {\n key[0xff & j] =\n 0xff & ((smear ^= key[0xff & j] * 19) + seed.charCodeAt(j++));\n }\n return key\n }\n}\n\nexport { prng_alea, prng_arc4, prng_tychei, prng_xor128, prng_xor4096, prng_xorshift7, prng_xorwow };\n//# sourceMappingURL=index.mjs.map\n","import { usesRadians as runtimeUsesRadians } from \"./runtime.js\";\n\n// =============================================================================\n// Section: Randomness & Noise\n// =============================================================================\n\nimport { createNoise2D } from \"simplex-noise\";\nimport { prng_alea } from \"esm-seedrandom\";\n\n/**\n * A uniform PRNG function. Returns a float in [0,1).\n * @callback RNG\n * @returns {number}\n */\n/** @type {RNG} */\nlet rng = prng_alea(Math.random());\nlet rng2 = prng_alea(Math.random());\n\nconst _seedCallbacks = [];\n\n/**\n * Register a callback to be called whenever seed() is invoked.\n * Used internally by modules that maintain gaussian pools.\n * @param {Function} cb\n */\nexport const _onSeed = (cb) => _seedCallbacks.push(cb);\n\n/**\n * Seed the random number generator.\n * @param {number|string} s – The seed value.\n * @returns {void}\n */\nexport const seed = (s) => {\n rng = prng_alea(s);\n rng2 = prng_alea(`${s}:2`);\n for (const callback of _seedCallbacks) {\n callback();\n }\n};\n\n/**\n * Simplex‐noise 2D function.\n * @type {function(number, number): number}\n */\nexport let noise = createNoise2D(prng_alea(Math.random()));\nexport let noise2 = createNoise2D(prng_alea(Math.random()));\n\n/**\n * Seed the noise generator.\n * @param {number|string} s - The seed value.\n * @returns {void}\n */\nexport const noiseSeed = (s) => {\n noise = createNoise2D(prng_alea(s));\n noise2 = createNoise2D(prng_alea(`${s}:2`));\n};\n\n/**\n * Returns a random float in [min, max).\n * @param {number} [min=0]\n * @param {number} [max=1]\n * @returns {number}\n */\nexport const rr = (e = 0, r = 1) => e + rng() * (r - e);\nexport const rr2 = (e = 0, r = 1) => e + rng2() * (r - e);\n\n/**\n * Selects a random element from an array.\n * @param {T[]} array - Input array.\n * @returns {T}\n */\nexport const rArray = (array) => array[~~(rng() * array.length)];\n\n/**\n * Returns a random integer in [min, max).\n * @param {number} min\n * @param {number} max\n * @returns {number}\n */\nexport const randInt = (e, r) => ~~rr(e, r);\nexport const randInt2 = (e, r) => ~~rr2(e, r);\n\n/**\n * Gaussian (normal) random sample N(mean, stdev²).\n * @param {number} [mean=0]\n * @param {number} [stdev=1]\n * @returns {number}\n */\nexport const gaussian = (mean = 0, stdev = 1) => {\n const u = 1 - rng();\n const v = rng();\n const z = Math.sqrt(-2.0 * Math.log(u)) * cos(360 * v);\n return z * stdev + mean;\n};\n\n/**\n * Picks a key from an object according to weighted probabilities.\n * @param {Object<string|number, number>} weights\n * @returns {string|number}\n */\nexport const weightedRand = (weights) => {\n let totalWeight = 0;\n const entries = [];\n\n // Build cumulative weights array\n for (const key in weights) {\n totalWeight += weights[key];\n entries.push({ key, cumulative: totalWeight });\n }\n\n // Get a random number between 0 and totalWeight\n const rnd = rng() * totalWeight;\n\n // Pick the first entry where rnd is less than the cumulative weight\n for (const { key, cumulative } of entries) {\n if (rnd < cumulative) {\n return isNaN(key) ? key : parseInt(key);\n }\n }\n};\n\n// =============================================================================\n// Section: Numeric Mapping & Constraints\n// =============================================================================\n\n/**\n * Maps a value from range [a,b] to [c,d], optionally clamped.\n * @param {number} value\n * @param {number} a\n * @param {number} b\n * @param {number} c\n * @param {number} d\n * @param {boolean} [withinBounds=false]\n * @returns {number}\n */\nexport const map = (value, a, b, c, d, withinBounds = false) => {\n let r = c + ((value - a) / (b - a)) * (d - c);\n if (!withinBounds) return r;\n if (c < d) return constrain(r, c, d);\n else return constrain(r, d, c);\n};\n\n/**\n * Constrains a number within the provided bounds.\n * @param {number} n - The number.\n * @param {number} low - Lower bound.\n * @param {number} high - Upper bound.\n * @returns {number} The constrained number.\n */\nexport const constrain = (n, low, high) => Math.max(Math.min(n, high), low);\n\n// =============================================================================\n// Section: Trigonometry\n// =============================================================================\n\n/**\n * Normalize an angle in degrees to [0,360).\n * @param {number} angle\n * @returns {number}\n */\nconst nAngle = (angle) => {\n angle = angle % 360;\n return angle < 0 ? angle + 360 : angle;\n};\n\n// number of discrete steps (360° × 4 samples per degree)\nconst totalDegrees = 1440;\nconst radiansPerIndex = (2 * Math.PI) / totalDegrees;\n\n// lazy‐initialized lookup tables\nconst cLookup = new Float32Array(totalDegrees).fill(NaN);\nconst sLookup = new Float32Array(totalDegrees).fill(NaN);\n\n/**\n * Cosine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const cos = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = cLookup[idx];\n if (isNaN(v)) {\n v = Math.cos(idx * radiansPerIndex);\n cLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Sine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const sin = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = sLookup[idx];\n if (isNaN(v)) {\n v = Math.sin(idx * radiansPerIndex);\n sLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Converts radians to degrees, normalized to [0,360).\n * @param {number} rad\n * @returns {number}\n */\nexport const toDegrees = (rad, isRad = false) => {\n if (isRad || runtimeUsesRadians()) {\n let angle = ((rad * 180) / Math.PI) % 360;\n return angle < 0 ? angle + 360 : angle;\n } else {\n return rad;\n }\n};\n\n/**\n * Converts radians to degrees without wrapping the result.\n * Preserves signed angles so downstream scaling keeps its direction.\n * @param {number} angle\n * @param {boolean} [isRad=false]\n * @returns {number}\n */\nexport const toDegreesSigned = (angle, isRad = false) =>\n isRad || runtimeUsesRadians()\n ? (angle * 180) / Math.PI\n : angle;\n\n// =============================================================================\n// Section: Geometry & Transforms\n// =============================================================================\n\n/**\n * Rotates point (x,y) around center (cx,cy) by angle degrees.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x\n * @param {number} y\n * @param {number} angle - Degrees\n * @returns {{x:number,y:number}}\n */\nexport const rotate = (cx, cy, x, y, angle) => {\n let coseno = cos(angle),\n seno = sin(angle),\n nx = coseno * (x - cx) + seno * (y - cy) + cx,\n ny = coseno * (y - cy) - seno * (x - cx) + cy;\n return { x: nx, y: ny };\n};\n\n/**\n * Euclidean distance between two points.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const dist = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1);\n\n/**\n * Angle in degrees between two points, measured clockwise from +X.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const calcAngle = (x1, y1, x2, y2) =>\n toDegrees(Math.atan2(-(y2 - y1), x2 - x1), true);\n\n/**\n * Intersection of two line segments, or false if none.\n * @param {{x:number,y:number}} s1a\n * @param {{x:number,y:number}} s1b\n * @param {{x:number,y:number}} s2a\n * @param {{x:number,y:number}} s2b\n * @param {boolean} [includeSegmentExtension=false]\n * @returns {{x:number,y:number}|false}\n */\nexport const intersectLines = (\n s1a,\n s1b,\n s2a,\n s2b,\n includeSegmentExtension = false\n) => {\n // Extract coordinates from points\n let x1 = s1a.x,\n y1 = s1a.y;\n let x2 = s1b.x,\n y2 = s1b.y;\n let x3 = s2a.x,\n y3 = s2a.y;\n let x4 = s2b.x,\n y4 = s2b.y;\n // Early return if line segments are points or if the lines are parallel\n if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) {\n return false; // Segments are points\n }\n let deltaX1 = x2 - x1,\n deltaY1 = y2 - y1;\n let deltaX2 = x4 - x3,\n deltaY2 = y4 - y3;\n let denominator = deltaY2 * deltaX1 - deltaX2 * deltaY1;\n if (denominator === 0) {\n return false; // Lines are parallel\n }\n // Calculate the intersection point\n let ua = (deltaX2 * (y1 - y3) - deltaY2 * (x1 - x3)) / denominator;\n let ub = (deltaX1 * (y1 - y3) - deltaY1 * (x1 - x3)) / denominator;\n // Check if the intersection is within the bounds of the line segments\n if (!includeSegmentExtension && (ub < 0 || ub > 1)) {\n return false;\n }\n // Calculate the intersection coordinates\n let x = x1 + ua * deltaX1;\n let y = y1 + ua * deltaY1;\n return { x: x, y: y };\n};\n","// =============================================================================\n// Target Runtime Hooks\n// =============================================================================\n\n/**\n * Shared target state exposed to core modules.\n *\n * Host adapters are expected to keep these bindings updated with the currently\n * active drawing target. The exact object type is adapter-defined, but core code\n * assumes the active renderer exposes:\n * - `drawingContext`: the active WebGL context\n * - target dimensions through `Cwidth` / `Cheight`\n * - pixel density through `Density`\n */\n\nexport let Cwidth, Cheight, Instance, Renderer, Density;\n\nlet targetRuntime = {\n load: () => {\n throw new Error(\"No target runtime adapter registered.\");\n },\n syncDensity: () => Density,\n isCanvasReady: () => {\n throw new Error(\"No target runtime adapter registered.\");\n },\n instance: (inst) => {\n Instance = inst;\n },\n activateInstance: (inst) => {\n Instance = inst;\n },\n deactivateInstance: () => {},\n getActiveFramebuffer: () => null,\n isFramebufferTarget: () => false,\n};\n\n/**\n * Updates the shared target state consumed by core modules.\n *\n * @param {object} state\n */\nexport function setTargetState(state) {\n if (\"Cwidth\" in state) Cwidth = state.Cwidth;\n if (\"Cheight\" in state) Cheight = state.Cheight;\n if (\"Instance\" in state) Instance = state.Instance;\n if (\"Renderer\" in state) Renderer = state.Renderer;\n if (\"Density\" in state) Density = state.Density;\n}\n\n/**\n * Registers or updates host target hooks used by core modules.\n *\n * @param {object} hooks\n */\nexport function setTargetRuntime(hooks) {\n targetRuntime = { ...targetRuntime, ...hooks };\n}\n\nexport const load = (buffer = false) => targetRuntime.load(buffer);\nexport const syncDensity = () => targetRuntime.syncDensity();\nexport const isCanvasReady = () => targetRuntime.isCanvasReady();\nexport const instance = (inst) => targetRuntime.instance(inst);\nexport const activateInstance = (inst) => targetRuntime.activateInstance(inst);\nexport const deactivateInstance = () => targetRuntime.deactivateInstance();\nexport const getActiveFramebuffer = () => targetRuntime.getActiveFramebuffer();\nexport const isFramebufferTarget = (target) =>\n targetRuntime.isFramebufferTarget(target);\n","// =============================================================================\n// Module: Dirty Rect Utilities\n// =============================================================================\n/**\n * Expands a dirty rectangle outward by a constant padding value.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Rect to expand.\n * @param {number} [padding=0] - Padding in pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Expanded rect.\n */\nexport const expandDirtyRect = (rect, padding = 0) =>\n rect\n ? {\n minX: rect.minX - padding,\n minY: rect.minY - padding,\n maxX: rect.maxX + padding,\n maxY: rect.maxY + padding,\n }\n : null;\n\n/**\n * Clamps a dirty rectangle to explicit target bounds.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Candidate rect.\n * @param {number} width - Target width in physical pixels.\n * @param {number} height - Target height in physical pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Clamped rect.\n */\nexport const normalizeDirtyRect = (rect, width, height) => {\n if (!rect) return null;\n\n const minX = Math.max(0, Math.floor(Math.min(rect.minX, rect.maxX)));\n const minY = Math.max(0, Math.floor(Math.min(rect.minY, rect.maxY)));\n const maxX = Math.min(width, Math.ceil(Math.max(rect.minX, rect.maxX)));\n const maxY = Math.min(height, Math.ceil(Math.max(rect.minY, rect.maxY)));\n\n if (maxX <= minX || maxY <= minY) return null;\n\n return { minX, minY, maxX, maxY };\n};\n\n/**\n * Returns the union of two dirty rectangles.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} a - First rect.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} b - Second rect.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Union rect.\n */\nexport const unionDirtyRect = (a, b) => {\n if (!a) return b;\n if (!b) return a;\n\n return {\n minX: Math.min(a.minX, b.minX),\n minY: Math.min(a.minY, b.minY),\n maxX: Math.max(a.maxX, b.maxX),\n maxY: Math.max(a.maxY, b.maxY),\n };\n};\n\n/**\n * Returns a dirty rectangle covering the full target bounds.\n *\n * @param {number} width - Target width in physical pixels.\n * @param {number} height - Target height in physical pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}} Full-target rect.\n */\nexport const getFullDirtyRect = (width, height) => ({\n minX: 0,\n minY: 0,\n maxX: width,\n maxY: height,\n});\n","// =============================================================================\n// Compositor Runtime Hooks\n// =============================================================================\n\n/**\n * Shared compositor helpers and host hooks.\n *\n * The shared code in this module assumes framebuffer-like targets expose:\n * - `framebuffer`: native WebGL framebuffer handle\n * - optional lifecycle methods supplied by the host adapter\n *\n * Higher-level core modules also attach their own bookkeeping fields onto the\n * active renderer and mask targets, such as:\n * - `shaderProgram`\n * - `blendSourceFramebuffer`\n * - `glMask`\n * - `fillMaskFramebuffer`\n * - `mask`\n *\n * These are library-level contract fields, not host-specific internals.\n */\n\nexport const create2DCanvas = (width, height, willReadFrequently = false) => {\n const canvas =\n typeof OffscreenCanvas !== \"undefined\"\n ? new OffscreenCanvas(width, height)\n : (() => {\n const element = document.createElement(\"canvas\");\n element.width = width;\n element.height = height;\n return element;\n })();\n canvas.drawingContext = canvas.getContext(\n \"2d\",\n willReadFrequently ? { willReadFrequently: true } : undefined,\n );\n return canvas;\n};\n\nexport const get2DContext = (canvas, willReadFrequently = false) => {\n canvas.drawingContext ??= canvas.getContext(\n \"2d\",\n willReadFrequently ? { willReadFrequently: true } : undefined,\n );\n return canvas.drawingContext;\n};\n\nexport function blitDefaultFramebufferSource({\n renderer,\n sourceFramebuffer,\n dirtyRect,\n getTargetPixelSize,\n toScissorBox,\n}) {\n const gl = renderer.drawingContext;\n const { width, height } = getTargetPixelSize();\n const sourceBox = dirtyRect ? toScissorBox(dirtyRect) : null;\n const previousReadFramebuffer = gl.getParameter(gl.READ_FRAMEBUFFER_BINDING);\n const previousDrawFramebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING);\n\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, sourceFramebuffer.framebuffer);\n gl.blitFramebuffer(\n sourceBox?.x ?? 0,\n sourceBox?.y ?? 0,\n sourceBox ? sourceBox.x + sourceBox.width : width,\n sourceBox ? sourceBox.y + sourceBox.height : height,\n sourceBox?.x ?? 0,\n sourceBox?.y ?? 0,\n sourceBox ? sourceBox.x + sourceBox.width : width,\n sourceBox ? sourceBox.y + sourceBox.height : height,\n gl.COLOR_BUFFER_BIT,\n gl.NEAREST,\n );\n\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, previousReadFramebuffer);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, previousDrawFramebuffer);\n\n return sourceFramebuffer;\n}\n\nlet compositorRuntime = {\n clearTarget: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n ensureBlendShaderProgram: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n ensureBlendSourceFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n createFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n runBlendShaderPass: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n blitSourceToFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n};\n\n/**\n * Registers or updates host compositor hooks used by core compositing code.\n *\n * @param {object} hooks\n */\nexport function setCompositorRuntime(hooks) {\n compositorRuntime = { ...compositorRuntime, ...hooks };\n}\n\nexport const clearTarget = (...args) => compositorRuntime.clearTarget(...args);\nexport const ensureBlendShaderProgram = (...args) =>\n compositorRuntime.ensureBlendShaderProgram(...args);\nexport const ensureBlendSourceFramebuffer = (...args) =>\n compositorRuntime.ensureBlendSourceFramebuffer(...args);\nexport const createFramebuffer = (...args) =>\n compositorRuntime.createFramebuffer(...args);\nexport const runBlendShaderPass = (...args) =>\n compositorRuntime.runBlendShaderPass(...args);\nexport const blitSourceToFramebuffer = (...args) =>\n compositorRuntime.blitSourceToFramebuffer(...args);\n","import {\n Cwidth,\n Cheight,\n Renderer,\n Density,\n load as loadTarget,\n isCanvasReady,\n syncDensity,\n getActiveFramebuffer,\n isFramebufferTarget,\n} from \"./target.js\";\nimport {\n expandDirtyRect,\n normalizeDirtyRect as clampDirtyRect,\n unionDirtyRect,\n getFullDirtyRect as getFullRect,\n} from \"./dirty_rect.js\";\nimport {\n clearTarget as clearRenderTarget,\n ensureBlendShaderProgram,\n ensureBlendSourceFramebuffer,\n runBlendShaderPass,\n blitSourceToFramebuffer,\n} from \"./compositor_runtime.js\";\n\nimport vertSrc from \"./gl/shader.vert\";\nimport fragSrc from \"./gl/shader.frag\";\n\n// =============================================================================\n// Module: Configure and Initiate\n// =============================================================================\n/**\n * This module handles the configuration and initialization of the drawing system.\n * It manages canvas properties, ensures the system is ready for rendering, and\n * provides utilities for saving and restoring states.\n */\n\nlet strokeComposite = null;\nlet fillComposite = null;\n\nexport const registerStrokeComposite = (composite) => {\n strokeComposite = composite;\n};\n\nexport const registerFillComposite = (composite) => {\n fillComposite = composite;\n};\n\nconst clearTarget = (target) => {\n clearRenderTarget(Renderer, target, isFramebufferTarget);\n};\n\n// =============================================================================\n// Section: Dirty Rect Utilities\n// =============================================================================\n/**\n * Returns the current render target size in physical pixels.\n * @returns {{width: number, height: number}} Pixel size of the active target.\n */\nconst getTargetPixelSize = () => ({\n width: Math.max(1, Math.round(Cwidth * Density)),\n height: Math.max(1, Math.round(Cheight * Density)),\n});\n\nconst normalizeDirtyRect = (rect) => {\n if (!rect) return null;\n const { width, height } = getTargetPixelSize();\n return clampDirtyRect(rect, width, height);\n};\n\n/**\n * Returns a dirty rectangle covering the full active target.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}} Full-target rect.\n */\nconst getFullDirtyRect = () => {\n const { width, height } = getTargetPixelSize();\n return getFullRect(width, height);\n};\n\n// =============================================================================\n// Section: Scissor Helpers\n// =============================================================================\n/**\n * Converts a top-left-based dirty rectangle into a WebGL scissor box.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Dirty rect.\n * @returns {{x:number,y:number,width:number,height:number}|null} Scissor box or null.\n */\nconst toScissorBox = (rect, flipY = true) => {\n const normalized = normalizeDirtyRect(rect);\n if (!normalized) return null;\n\n const { height } = getTargetPixelSize();\n return {\n x: normalized.minX,\n y: flipY ? height - normalized.maxY : normalized.minY,\n width: normalized.maxX - normalized.minX,\n height: normalized.maxY - normalized.minY,\n };\n};\n\n/**\n * Runs a draw callback with a temporary scissor region.\n * @param {WebGL2RenderingContext} gl - Active WebGL context.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Dirty rect.\n * @param {Function} draw - Draw callback executed under the scissor box.\n */\nconst withScissor = (gl, rect, draw, flipY = true) => {\n const box = toScissorBox(rect, flipY);\n if (!box) {\n draw();\n return;\n }\n\n // Scissor is never nested in this module, so we can set/clear it directly\n // without saving previous GL state.\n gl.enable(gl.SCISSOR_TEST);\n gl.scissor(box.x, box.y, box.width, box.height);\n\n try {\n draw();\n } finally {\n gl.disable(gl.SCISSOR_TEST);\n }\n};\n\n/**\n * Stores the current state of the drawing system.\n * Can be used to save and restore configurations or canvas states.\n */\nexport const State = {};\n/**\n * Handles color blending using WebGL shaders. Implements advanced blending\n * effects based on Kubelka-Munk theory. Relies on spectral.js for blending logic.\n */\n\n// =============================================================================\n// Section: Color Blending / Rendering\n// =============================================================================\n/**\n * Ensures the Mix object is initialized and ready for blending.\n */\nexport const isMixReady = () => {\n if (!Renderer?.loaded) {\n isCanvasReady();\n Mix.load();\n }\n};\n\n/**\n * Manages blending operations with WebGL shaders.\n * @property {boolean} loaded - Indicates if shaders are loaded.\n * @property {boolean} isBlending - Indicates if blending is active.\n * @property {object} currentColor - Current color in WebGL format.\n * @property {function} load - Initializes blending resources.\n * @property {function} blend - Applies blending effects.\n */\nexport const Mix = {\n isBlending: false,\n cachedColor: null,\n\n /**\n * Merges a new dirty rectangle into the target's accumulated draw bounds.\n * @param {object} target - Mask buffer receiving draw output.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Rect to merge.\n */\n markDirtyRect(target, rect) {\n const normalized = normalizeDirtyRect(rect);\n if (!target || !normalized) return;\n target.dirtyRect = unionDirtyRect(target.dirtyRect, normalized);\n target.isDrawn = true;\n },\n\n /**\n * Clears a mask buffer and resets its dirty-rect tracking.\n * @param {object} target - Mask buffer to reset.\n */\n clearMask(target) {\n if (!target) return;\n const composite = target === this.glMask ? strokeComposite : fillComposite;\n composite?.clearMask?.(target, clearTarget);\n },\n\n /**\n * Resolves the region that should be composited back into the destination.\n * @param {object} target - Mask buffer being sampled.\n * @param {boolean} isBrushMask - True when compositing the GL brush mask.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\n getCompositeRect(target, isBrushMask) {\n const composite = isBrushMask ? strokeComposite : fillComposite;\n return composite?.getCompositeRect?.(\n target,\n getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n );\n },\n\n // =============================================================================\n // Section: Setup and load shaders\n // =============================================================================\n /**\n * Ensures the mask buffers and blend shader exist for the current renderer.\n */\n load() {\n syncDensity();\n const needsBlendSourceFramebuffer =\n !Renderer.blendSourceFramebuffer ||\n Renderer.blendSourceFramebuffer.width !== Cwidth ||\n Renderer.blendSourceFramebuffer.height !== Cheight ||\n (typeof Renderer.blendSourceFramebuffer.pixelDensity === \"function\" &&\n Renderer.blendSourceFramebuffer.pixelDensity() !== Density);\n ensureBlendShaderProgram(Renderer, vertSrc, fragSrc);\n\n this.glMask = strokeComposite?.ensureResources?.(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n );\n const fillResources = fillComposite?.ensureResources?.(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n clearTarget,\n ) ?? {\n mask: null,\n ctx: null,\n };\n\n if (needsBlendSourceFramebuffer) {\n Renderer.blendSourceFramebuffer = ensureBlendSourceFramebuffer(\n Renderer,\n Renderer.blendSourceFramebuffer,\n Cwidth,\n Cheight,\n Density,\n );\n }\n\n this.mask = fillResources.mask;\n this.ctx = fillResources.ctx;\n },\n\n // =============================================================================\n // Section: Compositing\n // =============================================================================\n /**\n * Flushes pending mask work when the blend color changes or a frame ends.\n * @param {Color|false} [_color=false] - New blend color.\n * @param {boolean} [_isLast=false] - True when this is the final blend flush.\n */\n blend(_color = false, _isLast = false) {\n isMixReady();\n // Only one mask is \"active\" for the current drawing mode; the other one\n // may still need flushing if the mode just changed mid-frame.\n const isBrushMask = this.isBrush === true;\n const mask = isBrushMask ? this.glMask : this.mask;\n const otherMask = isBrushMask ? this.mask : this.glMask;\n const nextColor = _color?._array;\n const colorChanged =\n !!nextColor &&\n (this.cachedColor?.[0] !== nextColor[0] ||\n this.cachedColor?.[1] !== nextColor[1] ||\n this.cachedColor?.[2] !== nextColor[2] ||\n this.cachedColor?.[3] !== nextColor[3]);\n if (!this.isBlending && nextColor) {\n this.isBlending = true;\n this.cachedColor = nextColor;\n // Reset the brush mask fully at the start of each blend cycle so stale\n // dirty-rect bookkeeping cannot leak an old stroke into the next color.\n this.clearMask(this.glMask);\n }\n\n if (_isLast || colorChanged) {\n if (this.justChanged) {\n this.applyShader(otherMask, !isBrushMask);\n this.justChanged = false;\n }\n if (this.isBlending) {\n this.applyShader(mask, isBrushMask);\n }\n if (nextColor) this.cachedColor = nextColor;\n if (_isLast) {\n this.isBlending = false;\n this.cachedColor = null;\n \n }\n }\n },\n\n /**\n * Runs the blend shader over a mask and composites the result into the active renderer.\n * @param {object} mask - Mask buffer to composite.\n * @param {boolean} isBrushMask - True when compositing the GL brush mask.\n */\n applyShader(mask, isBrushMask) {\n if (!mask?.isDrawn) return;\n\n const dirtyRect = this.getCompositeRect(mask, isBrushMask);\n if (!dirtyRect) {\n this.clearMask(mask);\n return;\n }\n\n const gl = Renderer.drawingContext;\n const shader = Renderer.shaderProgram;\n const activeFramebuffer = getActiveFramebuffer();\n const source = blitSourceToFramebuffer({\n renderer: Renderer,\n sourceTarget: activeFramebuffer ?? Renderer,\n sourceFramebuffer: Renderer.blendSourceFramebuffer,\n dirtyRect,\n isFramebufferTarget,\n Cwidth,\n Cheight,\n getTargetPixelSize,\n toScissorBox,\n withScissor,\n });\n const targetIsFramebuffer = !!activeFramebuffer;\n const composite = isBrushMask ? strokeComposite : fillComposite;\n const shaderMask = composite.getShaderMask(\n Renderer,\n mask,\n dirtyRect,\n getFullDirtyRect,\n clearTarget,\n );\n\n runBlendShaderPass({\n renderer: Renderer,\n shader,\n source,\n mask: shaderMask,\n color: this.cachedColor,\n isBrushMask,\n Cwidth,\n Cheight,\n dirtyRect,\n targetIsFramebuffer,\n withScissor,\n });\n this.clearMask(mask);\n },\n};\n\n/**\n * Flushes any pending stroke/fill mask work into the current target and resets\n * the shared compositor back to its initial idle state.\n */\nexport const flushActiveComposite = () => {\n isMixReady();\n Mix.blend(false, true);\n Mix.clearMask(Mix.glMask);\n Mix.clearMask(Mix.mask);\n Mix.justChanged = false;\n Mix.isBlending = false;\n Mix.isBrush = null;\n Mix.cachedColor = null;\n};\n\n/**\n * Loads and initializes the drawing target, then refreshes compositing\n * resources if the renderer was already active.\n *\n * @param {object|false} [buffer=false] - Optional offscreen target.\n */\nexport const load = (buffer = false) => {\n loadTarget(buffer);\n if (Renderer.loaded) Mix.load();\n};\n","import { Cwidth, Cheight } from \"./target.js\";\nimport { isMixReady, State } from \"./color.js\";\nimport { randInt2, noise2, rr2, sin, cos, map, toDegreesSigned } from \"./utils.js\";\nimport { getAffineMatrix } from \"./runtime.js\";\n\n// =============================================================================\n// Section: Matrix transformations\n// =============================================================================\n\n// =============================================================================\n// Section: Field Initialization\n// =============================================================================\n\nlet isLoaded = false;\n\n/**\n * Ensures the field system is initialized and ready for use.\n * If the field is not loaded, it initializes the mixing system and creates the field.\n */\nexport function isFieldReady() {\n if (!isLoaded) {\n isMixReady(); // Ensure the mixing system is ready\n createField(); // Initialize the field\n isLoaded = true;\n }\n}\n\n// =============================================================================\n// Section: Position Class\n// =============================================================================\n\n/**\n * The Position class represents a point within a two-dimensional space, which can interact with a vector field.\n * It provides methods to update the position based on the field's flow and to check whether the position is\n * within certain bounds (e.g., within the field or canvas).\n */\nexport class Position {\n /**\n * Constructs a new Position instance.\n * @param {number} x - The initial x-coordinate.\n * @param {number} y - The initial y-coordinate.\n */\n constructor(x, y) {\n isFieldReady();\n const m = getAffineMatrix();\n this.mx = m.x;\n this.my = m.y;\n this.update(x, y);\n this.plotted = 0; // Tracks the total distance plotted\n }\n\n /**\n * Updates the position's coordinates and calculates its offsets and indices within the flow field.\n * @param {number} x - The new x-coordinate.\n * @param {number} y - The new y-coordinate.\n */\n update(x, y) {\n this.x = x;\n this.y = y;\n if (State.field.isActive) {\n this.colIdx = Math.round((x + this.mx - left_x) / resolution);\n this.rowIdx = Math.round((y + this.my - top_y) / resolution);\n }\n }\n\n /**\n * Resets the 'plotted' property to 0.\n */\n reset() {\n this.plotted = 0;\n }\n\n /**\n * Checks if the position is within the active flow field's bounds.\n * @returns {boolean} - True if the position is within the flow field, false otherwise.\n */\n isIn() {\n return State.field.isActive\n ? Position.isIn(this.colIdx, this.rowIdx)\n : this.isInCanvas(this.x, this.y);\n }\n\n /**\n * Checks if the position is within the canvas bounds (with a margin).\n * @returns {boolean} - True if the position is within bounds, false otherwise.\n */\n isInCanvas() {\n const margin = 0.3;\n const w = Cwidth;\n const h = Cheight;\n const x = this.x + this.mx;\n const y = this.y + this.my;\n return (\n x >= -margin * w &&\n x <= (1 + margin) * w &&\n y >= -margin * h &&\n y <= (1 + margin) * h\n );\n }\n\n /**\n * Calculates the angle of the flow field at the position's current coordinates.\n * @returns {number} - The internal flow angle in degrees, or 0 if the position is not in the field or if no field is active.\n */\n angle(skipCheck = false) {\n if (!State.field.isActive) return 0;\n return (skipCheck || this.isIn())\n ? flow_field()[this.colIdx][this.rowIdx] * State.field.wiggle\n : 0;\n }\n\n /**\n * Moves the position along the flow field by a certain length.\n * @param {number} _dir - The direction of movement, interpreted using the current runtime angle units.\n * @param {number} _length - The length to move along the field.\n * @param {number} _step_length - The length of each step.\n */\n moveTo(_dir, _length, _step_length = 1) {\n this.movePos(toDegreesSigned(_dir), _length, _step_length);\n }\n\n /**\n * Internal variant of moveTo() that expects a degree value already normalized to the library's internal representation.\n */\n _moveToDegrees(_dir, _length, _step_length = 1) {\n this.movePos(_dir, _length, _step_length);\n }\n\n /**\n * Plots a point to another position within the flow field, following a Plot object\n * @param {Position} _plot - The Plot path object.\n * @param {number} _length - The length to move towards the target position.\n * @param {number} _step_length - The length of each step.\n * @param {number} _scale - The scaling factor for the plotting path.\n */\n plotTo(_plot, _length, _step_length, _scale = 1, precomputedAngle = undefined) {\n this.movePos(_plot, _length, _step_length, _scale, precomputedAngle);\n }\n\n movePos(_dirPlot, _length, _step, _scale = false, precomputedAngle = undefined) {\n const scaleFactor = _scale || 1;\n if (!this.isIn()) {\n this.plotted += _step / scaleFactor;\n return;\n }\n const steps = _length / _step;\n const fieldActive = State.field.isActive;\n const usePlot = !!_scale;\n for (let i = 0; i < steps; i++) {\n const plotAngle = (usePlot && precomputedAngle !== undefined && i === 0)\n ? precomputedAngle\n : (usePlot ? _dirPlot.angle(this.plotted) : _dirPlot);\n const angle = (fieldActive ? this.angle(true) : 0) - plotAngle;\n // Calculate new position\n this.update(this.x + _step * cos(angle), this.y + _step * sin(angle));\n this.plotted += _step / scaleFactor;\n }\n }\n\n // Static Methods\n\n /**\n * Gets the row index for a given y-coordinate.\n * @param {number} y - The y-coordinate.\n * @returns {number} - The row index.\n */\n static getRowIndex(y, d = 1) {\n const y_offset = y + getAffineMatrix().y - top_y;\n return Math.round(y_offset / resolution / d);\n }\n\n /**\n * Gets the column index for a given x-coordinate.\n * @param {number} x - The x-coordinate.\n * @returns {number} - The column index.\n */\n static getColIndex(x, d = 1) {\n const x_offset = x + getAffineMatrix().x - left_x;\n return Math.round(x_offset / resolution / d);\n }\n\n /**\n * Checks if a column and row index are within the flow field bounds.\n * @param {number} col - The column index.\n * @param {number} row - The row index.\n * @returns {boolean} - True if the indices are within bounds, false otherwise.\n */\n static isIn(col, row) {\n return col >= 0 && row >= 0 && col < num_columns && row < num_rows;\n }\n}\n\n// =============================================================================\n// Section: VectorField\n// =============================================================================\n\n/**\n * Represents the state of the vector field.\n * @property {boolean} isActive - Indicates if the vector field is active.\n * @property {string|null} current - The name of the currently active vector field.\n */\nState.field = {\n isActive: false,\n current: null,\n wiggle: 1,\n};\n\n// Internal variables for field configuration\nlet list = new Map();\nlet resolution, left_x, top_y, num_columns, num_rows;\nconst FIELD_ANGLE_MODES = new Set([\"degrees\", \"radians\"]);\n\n/**\n * Initializes the field grid and sets up the vector field's structure based on the renderer's dimensions.\n */\nfunction createField() {\n resolution = Cwidth * 0.01; // Determine the resolution of the field grid\n left_x = -0.5 * Cwidth; // Left boundary of the field\n top_y = -0.5 * Cheight; // Top boundary of the field\n num_columns = Math.round((2 * Cwidth) / resolution); // Number of columns in the grid\n num_rows = Math.round((2 * Cheight) / resolution); // Number of columns in the grid\n addStandard(); // Add default vector field\n}\n\n/**\n * Retrieves the field values for the current vector field.\n * @returns {Float32Array[]} The current vector field grid.\n */\nfunction flow_field() {\n return list.get(State.field.current).field;\n}\n\nfunction normalizeFieldAngleMode(options = {}) {\n const config =\n typeof options === \"string\" ? { angleMode: options } : options || {};\n const angleMode = config.angleMode ?? \"degrees\";\n\n if (!FIELD_ANGLE_MODES.has(angleMode)) {\n throw new Error(\n `Invalid field angle mode \"${angleMode}\". Use \"degrees\" or \"radians\".`,\n );\n }\n\n return angleMode;\n}\n\nfunction normalizeFieldAngles(field, angleMode) {\n if (angleMode !== \"radians\") return field;\n\n for (let c = 0; c < field.length; c++) {\n for (let r = 0; r < field[c].length; r++) {\n field[c][r] = toDegreesSigned(field[c][r], true);\n }\n }\n\n return field;\n}\n\nfunction generateField(entry, t) {\n return normalizeFieldAngles(entry.gen(t, genField()), entry.angleMode);\n}\n\n/**\n * Regenerates the current vector field using its associated generator function.\n * @param {number} [t=0] - An optional time parameter that can affect field generation.\n */\nexport function refreshField(t = 0) {\n if (!State.field.isActive || !State.field.current) {\n throw new Error(\n \"No field is currently active. Call brush.field('name') to activate one before refreshing.\",\n );\n }\n const currentField = list.get(State.field.current);\n currentField.field = generateField(currentField, t);\n}\n\n/**\n * Generates an empty field array.\n * Reuses existing arrays to reduce memory allocation overhead.\n * @returns {Float32Array[]} Empty vector field grid.\n */\nfunction genField() {\n return new Array(num_columns)\n .fill(null)\n .map(() => new Float32Array(num_rows));\n}\n\n/**\n * Activates a specific vector field by name, ensuring it's ready for use.\n * @param {string} a - The name of the vector field to activate.\n */\nexport function field(a) {\n if (!State.field.wiggle) {\n State.field.wiggle = 1;\n } // Set default wiggle value\n isFieldReady();\n if (!list.has(a)) {\n throw new Error(\n `Field \"${a}\" does not exist. Available fields: ${Array.from(list.keys()).join(\", \")}.`,\n );\n }\n State.field.isActive = true;\n State.field.current = a;\n const entry = list.get(a);\n if (!entry.field) entry.field = generateField(entry, 0);\n}\n\n/**\n * Deactivates the current vector field.\n */\nexport function noField() {\n isFieldReady();\n State.field.isActive = false;\n}\n\n/**\n * Adds a new vector field to the field list with a unique name and a generator function.\n * @param {string} name - The unique name for the new vector field.\n * @param {Function} funct - The function that generates the field values.\n * @param {object} [options] - Optional field configuration.\n * @param {\"degrees\"|\"radians\"} [options.angleMode=\"degrees\"] - How the generator's output angles should be interpreted.\n */\nexport function addField(name, funct, options = {}) {\n list.set(name, {\n gen: funct,\n field: null,\n angleMode: normalizeFieldAngleMode(options),\n });\n}\n\n/**\n * Retrieves a list of all available vector field names.\n * @returns {string[]} An array of all the field names.\n */\nexport function listFields() {\n isFieldReady();\n return Array.from(list.keys());\n}\n\nexport function wiggle(a = 1) {\n field(\"hand\");\n State.field.wiggle = a;\n}\n\n/**\n * Fills every cell of a field grid using a callback (c, r) => angle.\n */\nfunction fillField(field, fn) {\n for (let c = 0; c < num_columns; c++)\n for (let r = 0; r < num_rows; r++) field[c][r] = fn(c, r);\n return field;\n}\n\n/**\n * Adds standard predefined vector fields to the list with unique behaviors.\n */\nfunction addStandard() {\n // Organic noise — basis for brush.wiggle()\n addField(\"hand\", (t, field) => {\n const bs = rr2(0.2, 0.8),\n ba = randInt2(5, 10);\n return fillField(field, (c, r) => {\n const angle = 0.5 * ba * sin(bs * r * c + randInt2(15, 25));\n return 0.2 * angle * cos(t) + noise2(c, r) * ba * 0.7;\n });\n });\n // Smooth large-scale noise curves\n addField(\"curved\", (t, field) => {\n let ar = randInt2(-10, 10);\n if (randInt2(0, 100) % 2 == 0) ar *= -1;\n return fillField(\n field,\n (c, r) =>\n 3 * map(noise2(c * 0.02 + t * 0.03, r * 0.02 + t * 0.03), 0, 1, -ar, ar),\n );\n });\n // Sharp alternating angles per cell — herringbone / wicker look\n addField(\"zigzag\", (t, field) => {\n let ar = randInt2(-30, -15) + Math.abs(44 * sin(t));\n if (randInt2(0, 100) % 2 == 0) ar *= -1;\n let dif = ar,\n angle = 0;\n for (let c = 0; c < num_columns; c++) {\n for (let r = 0; r < num_rows; r++) {\n field[c][r] = angle;\n angle += dif;\n dif *= -1;\n }\n angle += dif;\n dif *= -1;\n }\n return field;\n });\n // Sinusoidal wave bands\n addField(\"waves\", (t, field) => {\n const sr = randInt2(10, 15) + 5 * sin(t),\n cr = randInt2(3, 6) + 3 * cos(t),\n ba = randInt2(20, 35);\n return fillField(\n field,\n (c, r) => sin(sr * c) * ba * cos(r * cr) + randInt2(-3, 3),\n );\n });\n // Dense oscillation from row×col product\n addField(\"seabed\", (t, field) => {\n const bs = rr2(0.4, 0.8),\n ba = randInt2(18, 26);\n return fillField(\n field,\n (c, r) => 1.1 * ba * sin(bs * r * c + randInt2(15, 20)) * cos(t),\n );\n });\n // Radial vortex — angles spiral around the field centre\n addField(\"spiral\", (_t, field) => {\n const n = randInt2(5, 10);\n const dir = randInt2(0, 2) * 2 - 1;\n const offset = randInt2(65, 80); // <90 = inward spiral\n const attractors = Array.from({ length: n }, () => ({\n x: rr2(0.1, 0.9) * num_columns,\n y: rr2(0.1, 0.9) * num_rows,\n }));\n return fillField(field, (c, r) => {\n let wx = 0,\n wy = 0;\n for (const att of attractors) {\n const dx = c - att.x,\n dy = r - att.y;\n const w = 1 / (dx * dx + dy * dy + 1);\n const a = Math.atan2(dy, dx) * (180 / Math.PI);\n const angle = (dir * (a + offset) * Math.PI) / 180;\n wx += w * Math.cos(angle);\n wy += w * Math.sin(angle);\n }\n return Math.atan2(wy, wx) * (180 / Math.PI);\n });\n });\n // Column-banded stripes — parallel rake marks\n addField(\"columns\", (_t, field) => {\n const freq = randInt2(3, 8),\n amp = randInt2(25, 45);\n return fillField(field, (c, _r) => sin(c * freq) * amp);\n });\n}\n","import { State } from \"./color.js\";\nimport { intersectLines } from \"./utils.js\";\n\n// =============================================================================\n// Section: Polygon Class\n// =============================================================================\n\n/**\n * Represents a polygon with a set of vertices and provides methods for\n * intersection, drawing, filling, and hatching.\n */\nexport class Polygon {\n /**\n * Constructs the Polygon object from an array of points.\n * @param {Array} pointsArray - An array of points, where each point is an array of two numbers [x, y].\n * @param {boolean} [useRawVertices=false] - If true, uses the raw array as vertices.\n */\n constructor(pointsArray, useRawVertices = false) {\n this.a = pointsArray;\n this.vertices = useRawVertices\n ? pointsArray\n : pointsArray.map(([x, y]) => ({ x, y }));\n this.sides = this.vertices.map((v, i, arr) => [\n v,\n arr[(i + 1) % arr.length],\n ]);\n this._intersectionCache = {}; // Cache for intersection results\n }\n\n /**\n * Intersects a given line with the polygon, returning all intersection points.\n * @param {Object} line - The line to intersect with the polygon, having two properties 'point1' and 'point2'.\n * @returns {Array} An array of intersection points (each with 'x' and 'y' properties) or an empty array if no intersections.\n */\n intersect(line) {\n // Check if the result has been cached\n const cacheKey = `${line.point1.x},${line.point1.y}-${line.point2.x},${line.point2.y}`;\n if (this._intersectionCache[cacheKey]) {\n return this._intersectionCache[cacheKey];\n }\n const points = [];\n for (const [start, end] of this.sides) {\n const intersection = intersectLines(line.point1, line.point2, start, end);\n if (intersection) points.push(intersection);\n }\n this._intersectionCache[cacheKey] = points; // Cache the result\n return points;\n }\n\n /**\n * Displays the polygon with optional stroke, hatch, and fill effects.\n */\n show() {\n if (State.wash) this.wash();\n if (State.fill) this.fill();\n if (State.mass) this.mass();\n if (State.hatch) this.hatch();\n if (State.stroke) this.draw();\n }\n}","import { Cwidth, Cheight } from \"./target.js\";\nimport { State } from \"./color.js\";\nimport { toDegrees, map, rr2 } from \"./utils.js\";\nimport { Position, isFieldReady } from \"./flowfield.js\";\nimport { Polygon } from \"./polygon.js\";\n\n// =============================================================================\n// Section: Plot Class\n// =============================================================================\n\n/**\n * The Plot class represents a collection of segments that define shapes or paths.\n * It supports operations like adding segments, calculating angles and pressures,\n * and generating polygons based on the plot's structure.\n */\nexport class Plot {\n /**\n * Creates a new Plot.\n * @param {string} _type - The type of plot, \"curve\" or \"segments\".\n */\n constructor(_type) {\n this.segments = [];\n this.angles = [];\n this.pres = [];\n this.type = _type;\n this.dir = 0;\n this.calcIndex(0);\n this.pol = false;\n }\n\n /**\n * Adds a segment to the plot with specified angle, length, and pressure.\n * @param {number} _a - The angle of the segment.\n * @param {number} _length - The length of the segment.\n * @param {number} _pres - The pressure of the segment.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n addSegment(_a = 0, _length = 0, _pres = 1, _degrees = false) {\n if (this.angles.length > 0) this.angles.pop(); // Remove the last angle\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a); // Normalize angle\n this.angles.push(_a, _a); // Push angle twice for continuity\n this.pres.push(_pres);\n this.segments.push(_length);\n this.length = this.segments.reduce((sum, len) => sum + len, 0); // Update total length\n }\n\n /**\n * Finalizes the plot by setting the last angle and pressure.\n * @param {number} _a - The final angle.\n * @param {number} _pres - The final pressure.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n endPlot(_a = 0, _pres = 1, _degrees = false) {\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a);\n this.angles[this.angles.length - 1] = _a; // Update the last angle\n this.pres.push(_pres);\n }\n\n /**\n * Rotates the entire plot by a given angle.\n * @param {number} _a - The angle to rotate the plot.\n */\n rotate(_a) {\n this.dir = toDegrees(_a);\n }\n\n /**\n * Calculates the pressure at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated pressure.\n */\n pressure(_d) {\n // If the distance exceeds the plot length, return the last pressure\n if (_d > this.length) return this.pres[this.pres.length - 1];\n // Otherwise, calculate the pressure using the curving function\n return this.curving(this.pres, _d);\n }\n\n /**\n * Calculates the angle at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The calculated angle.\n */\n angle(_d) {\n // If the distance exceeds the plot length, return the last angle\n if (_d > this.length) return this.angles[this.angles.length - 1];\n // Calculate the index for the given distance\n this.calcIndex(_d);\n // Return the angle, adjusted for the plot type and direction\n return this.type === \"curve\"\n ? this.curving(this.angles, _d) + this.dir\n : this.angles[this.index] + this.dir;\n }\n\n /**\n * Interpolates values between segments for smooth transitions.\n * @param {Array<number>} array - The array to interpolate within.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated value.\n */\n curving(array, _d) {\n let map0 = array[this.index];\n let map1 = array[this.index + 1] ?? map0;\n if (Math.abs(map1 - map0) > 180) {\n if (map1 > map0) map1 = -(360 - map1);\n else map0 = -(360 - map0);\n }\n return map(_d - this.suma, 0, this.segments[this.index], map0, map1, true);\n }\n\n /**\n * Calculates the current index of the plot based on the distance.\n * @param {number} _d - The distance along the plot.\n */\n calcIndex(_d) {\n this.index = -1;\n this.suma = 0;\n let d = 0;\n while (d <= _d) {\n this.suma = d;\n d += this.segments[this.index + 1];\n this.index++;\n }\n return this.index;\n }\n\n /**\n * Generates a polygon based on the plot.\n * @param {number} _x - The x-coordinate for the starting point.\n * @param {number} _y - The y-coordinate for the starting point.\n * @param {number} _scale - The scale factor for the polygon.\n * @param {number} _side - The side factor for the polygon.\n * @returns {Polygon} - The generated polygon.\n */\n genPol(_x, _y, _scale = 1, _side) {\n isFieldReady(); // Ensure that the drawing environment is prepared\n const step = _side < 0 ? 4 : 1;\n const vertices = [];\n const numSteps = Math.round(this.length / step);\n const pos = new Position(_x + Cwidth / 2, _y + Cheight / 2);\n let pside = 0;\n let prevIdx = 0;\n\n for (let i = 0; i < numSteps; i++) {\n pos.plotTo(this, step, step);\n const idx = this.calcIndex(pos.plotted);\n pside += step;\n let maxSize = _side <= 0 ? 8 : Math.max(this.segments[idx] * _side * rr2(0.7, 1.3), 20);\n if ((pside >= maxSize || idx >= prevIdx) && pos.x) {\n vertices.push([pos.x - Cwidth / 2, pos.y - Cheight / 2]);\n pside = 0;\n if (idx >= prevIdx) prevIdx++;\n }\n }\n return new Polygon(vertices);\n }\n\n /**\n * Displays the plot with optional stroke, hatch, and fill effects.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\n show(x, y, scale = 1) {\n if (State.wash) this.wash(x, y, scale);\n if (State.fill) this.fill(x, y, scale);\n if (State.mass) this.mass(x, y, scale);\n if (State.hatch) this.hatch(x, y, scale);\n if (State.stroke) this.draw(x, y, scale);\n }\n}\n","import {\n rr2,\n randInt2,\n sin,\n cos,\n toDegreesSigned,\n constrain,\n dist,\n calcAngle,\n intersectLines,\n} from \"./utils.js\";\nimport { Polygon } from \"./polygon.js\";\nimport { Plot } from \"./plot.js\";\n\n// =============================================================================\n// Section: Primitives and Geommetry\n// =============================================================================\n\n/**\n * Creates a Polygon from an array of points and calls its show() method.\n * Polygons ignore fields and won't be good for fills and masses\n * @param {Array<Array<number>>} pointsArray - Array of points [x, y, pressure]\n */\nexport function polygon(pointsArray) {\n // Create a new Polygon instance\n const polygon = new Polygon(pointsArray);\n polygon.show();\n}\n\n/**\n * Draws a rectangle on the canvas using path functions.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} w - Width.\n * @param {number} h - Height.\n * @param {boolean} [mode=\"corner\"] - \"corner\" (default) or \"center\".\n */\nexport function rect(x, y, w, h, mode = \"corner\") {\n if (mode === \"center\") {\n x -= w / 2;\n y -= h / 2;\n }\n beginShape(0);\n vertex(x, y);\n vertex(x + w, y);\n vertex(x + w, y + h);\n vertex(x, y + h);\n endShape(true);\n}\n\n/**\n * Draws a circle on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Circle radius.\n * @param {boolean} [r=false] - Randomizes segment lengths if true.\n */\nexport function circle(x, y, radius, r = false) {\n const p = new Plot(\"curve\");\n const arcLength = Math.PI * radius;\n const angleOffset = rr2(0, 360);\n const randomFactor = r ? () => 1 + r * 0.2 * rr2() : () => 1;\n\n // Divide circle into 4 segments\n for (let i = 0; i < 4; i++) {\n const angle = -90 * i + angleOffset;\n p.addSegment(\n angle * randomFactor(),\n (arcLength / 2) * randomFactor(),\n 1,\n true,\n );\n }\n\n // Optionally add a random final angle for the last segment\n if (r) {\n const randomAngle = r * randInt2(-5, 5);\n p.addSegment(\n angleOffset,\n Math.abs(randomAngle) * (Math.PI / 180) * radius,\n 1,\n true,\n );\n p.endPlot(randomAngle + angleOffset, 1, true);\n } else {\n p.endPlot(angleOffset, 1, true);\n }\n\n // Draw the circle\n const offsetX = x - radius * sin(angleOffset);\n const offsetY = y - radius * cos(-angleOffset);\n p.show(offsetX, offsetY, 1);\n}\n\n/**\n * Draws an arc on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Radius.\n * @param {number} start - Start angle in the current runtime angle units.\n * @param {number} end - End angle in the current runtime angle units.\n */\nexport function arc(x, y, radius, start, end) {\n const startDeg = toDegreesSigned(start);\n const endDeg = toDegreesSigned(end);\n const sweepDeg = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweepDeg === 0) return;\n\n const p = new Plot(\"curve\");\n const segmentCount = Math.max(1, Math.ceil(sweepDeg / 90));\n const segmentSweep = sweepDeg / segmentCount;\n const arcLength = (Math.PI * radius * segmentSweep) / 180;\n\n for (let i = 0; i < segmentCount; i++) {\n p.addSegment(startDeg + i * segmentSweep + 90, arcLength, 1, true);\n }\n p.endPlot(startDeg + sweepDeg + 90, 1, true);\n\n const startX = x + radius * cos(startDeg);\n const startY = y - radius * sin(startDeg);\n p.draw(startX, startY, 1);\n}\n\n// Variables for managing paths and strokes\nlet _current;\nlet _curvature;\n\nclass SubPath {\n constructor() {\n this.isClosed = false;\n this.curvature = _curvature;\n this.vert = [];\n }\n /**\n * Adds a vertex to this subpath.\n * @param {number} x\n * @param {number} y\n * @param {number} pressure\n */\n vertex(x, y, pressure) {\n this.vert.push([x, y, pressure]);\n }\n /**\n * Renders the subpath by creating a spline from its vertices.\n */\n show() {\n let plot = _createSpline(this.vert, this.curvature, this.isClosed);\n plot.show();\n }\n}\n\n/**\n * Begins a new path with a specified curvature.\n * @param {number} [curvature=0] - Curvature from 0 to 1.\n */\nexport function beginShape(curvature = 0) {\n _curvature = constrain(curvature, 0, 1);\n _current = new SubPath();\n}\n\n/**\n * Adds a line segment from the current point to the given coordinates.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} [pressure=1] - Pressure value.\n */\nexport function vertex(x, y, pressure = 1) {\n if (!_current) {\n throw new Error(\n \"vertex() called outside of beginShape()/endShape(). Call beginShape() first.\",\n );\n }\n _current.vertex(x, y, pressure);\n}\n\n/**\n * Ends the current path and renders all subpaths.\n */\nexport function endShape(close = false) {\n if (!_current) {\n throw new Error(\n \"endShape() called without beginShape(). Call beginShape() first.\",\n );\n }\n if (_current.vert.length < 2) {\n throw new Error(\n \"endShape() requires at least 2 vertices. Add more with vertex().\",\n );\n }\n if (close) {\n _current.vertex(..._current.vert[0]);\n _current.isClosed = true;\n }\n _current.show();\n _current = false;\n}\n\nlet _strokeArray, _strokeOrigin;\n\n/**\n * Begins a new stroke with a given type and starting position.\n * @param {string} type - Stroke type.\n * @param {number} x - Starting x.\n * @param {number} y - Starting y.\n */\nexport function beginStroke(type, x, y) {\n if (type !== \"curve\" && type !== \"segments\") {\n throw new Error(\n `beginStroke() type must be \"curve\" or \"segments\", got \"${type}\".`,\n );\n }\n _strokeOrigin = [x, y];\n _strokeArray = new Plot(type);\n}\n\n/**\n * Adds a segment to the stroke.\n * @param {number} angle - Segment angle.\n * @param {number} length - Segment length.\n * @param {number} pressure - Segment pressure.\n */\nexport function move(angle, length, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"move() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.addSegment(angle, length, pressure);\n}\n\n/**\n * Completes and renders the stroke.\n * @param {number} angle - End angle.\n * @param {number} pressure - End pressure.\n */\nexport function endStroke(angle, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"endStroke() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.endPlot(angle, pressure);\n _strokeArray.draw(_strokeOrigin[0], _strokeOrigin[1], 1);\n _strokeArray = false;\n}\n\n/**\n * Creates and draws a spline curve from an array of points.\n * @param {Array<Array<number>>} array_points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature from 0 to 1.\n */\nexport function spline(_array_points, _curvature = 0.5) {\n if (!_array_points || _array_points.length < 2) {\n throw new Error(\n \"spline() requires at least 2 points. Each point should be [x, y, pressure].\",\n );\n }\n let p = _createSpline(_array_points, _curvature);\n p.draw();\n}\n\n/**\n * Creates a new Plot object representing a spline curve.\n *\n * For curved segments (curvature > 0) with at least 3 points available,\n * the function either treats segments as straight (if their angles match)\n * or calculates control points to compute a circular arc.\n *\n * If no curvature is specified, a simple straight segment is used.\n *\n * @param {Array<Array<number>>} points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature value between 0 and 1.\n * @param {boolean} [close=false] - Whether to close the spline.\n * @returns {Plot} - The generated Plot object.\n */\nfunction _createSpline(points, curvature = 0.5, close = false) {\n const plotType = curvature === 0 ? \"segments\" : \"curve\";\n const p = new Plot(plotType);\n const PI2 = Math.PI * 2;\n\n // If closing the spline, add the second point to the end\n if (close && curvature !== 0) {\n points.push(points[1]);\n }\n\n if (points && points.length > 0) {\n let done = 0; // Tracks excess length from previous segment\n let pep, tep, pep2; // Variables used for initial calibration\n\n for (let i = 0; i < points.length - 1; i++) {\n // For curved segments (if curvature > 0 and there is at least 3 points ahead)\n if (curvature > 0 && i < points.length - 2) {\n const p1 = points[i];\n const p2 = points[i + 1];\n const p3 = points[i + 2];\n\n const d1 = dist(p1[0], p1[1], p2[0], p2[1]);\n const d2 = dist(p2[0], p2[1], p3[0], p3[1]);\n const a1 = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n const a2 = calcAngle(p2[0], p2[1], p3[0], p3[1]);\n\n // Compute the adjustment length based on curvature\n const curvAdjust = curvature * Math.min(d1, d2, 0.5 * Math.min(d1, d2));\n const dmax = Math.max(d1, d2);\n const s1 = d1 - curvAdjust;\n const s2 = d2 - curvAdjust;\n\n if (Math.floor(a1) === Math.floor(a2)) {\n // If angles are nearly the same, treat as a straight segment\n const temp = close ? (i === 0 ? 0 : d1 - done) : d1 - done;\n const temp2 = close ? (i === 0 ? 0 : d2 - pep2) : d2;\n\n p.addSegment(a1, temp, p1[2], true);\n if (i === points.length - 3) {\n p.addSegment(a2, temp2, p2[2], true);\n }\n\n done = 0;\n if (i === 0) {\n pep = d1;\n pep2 = curvAdjust;\n tep = points[1];\n done = 0;\n }\n } else {\n // For a curved segment, compute control points and arc segment details\n const point1 = {\n x: p2[0] - curvAdjust * cos(-a1),\n y: p2[1] - curvAdjust * sin(-a1),\n };\n const point2 = {\n x: point1.x + dmax * cos(-a1 + 90),\n y: point1.y + dmax * sin(-a1 + 90),\n };\n const point3 = {\n x: p2[0] + curvAdjust * cos(-a2),\n y: p2[1] + curvAdjust * sin(-a2),\n };\n const point4 = {\n x: point3.x + dmax * cos(-a2 + 90),\n y: point3.y + dmax * sin(-a2 + 90),\n };\n\n const intPt = intersectLines(point1, point2, point3, point4, true);\n const radius = dist(point1.x, point1.y, intPt.x, intPt.y);\n const halfDist = dist(point1.x, point1.y, point3.x, point3.y) / 2;\n const arcAngle = 2 * Math.asin(halfDist / radius) * (180 / Math.PI);\n const arcLength = (PI2 * radius * arcAngle) / 360;\n\n const temp = close ? (i === 0 ? 0 : s1 - done) : s1 - done;\n const temp2 =\n i === points.length - 3 ? (close ? pep - curvAdjust : s2) : 0;\n\n p.addSegment(a1, temp, p1[2], true);\n p.addSegment(a1, isNaN(arcLength) ? 0 : arcLength, p1[2], true);\n p.addSegment(a2, temp2, p2[2], true);\n\n done = curvAdjust;\n if (i === 0) {\n pep = s1;\n pep2 = curvAdjust;\n tep = [point1.x, point1.y];\n }\n }\n\n if (i === points.length - 3) {\n p.endPlot(a2, p2[2], true);\n }\n } else if (curvature === 0) {\n // If no curvature, add a simple straight segment\n const p1 = points[i];\n const p2 = points[i + 1];\n const d = dist(p1[0], p1[1], p2[0], p2[1]);\n const a = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n\n p.addSegment(a, d, p2[2], true);\n if (i === points.length - 2) {\n p.endPlot(a, 1, true);\n }\n }\n }\n\n p.origin = close && curvature !== 0 ? tep : points[0];\n }\n\n return p;\n}\n","// =============================================================================\n// Stroke Runtime Hooks\n// =============================================================================\n\nlet strokeRuntime = {\n createTipSurface: () => {\n throw new Error(\"No stroke runtime adapter registered.\");\n },\n loadImageTip: () => {\n throw new Error(\"No stroke runtime adapter registered.\");\n },\n};\n\n/**\n * Registers or updates host stroke hooks used by brush-tip loading code.\n *\n * @param {object} hooks\n */\nexport function setStrokeRuntime(hooks) {\n strokeRuntime = { ...strokeRuntime, ...hooks };\n}\n\nexport const createTipSurface = (width, height) =>\n strokeRuntime.createTipSurface(width, height);\nexport const loadImageTip = (src, imageToWhite) =>\n strokeRuntime.loadImageTip(src, imageToWhite);\n","import * as Color from \"../core/color.js\";\nimport { createFramebuffer } from \"../core/compositor_runtime.js\";\n\nlet isStrokeCompositeRegistered = false;\nconst DIRTY_BRUSH_PADDING = 2;\n\n// =============================================================================\n// Section: Helpers\n// =============================================================================\n/**\n * Returns whether the current stroke mask framebuffer must be recreated.\n * This happens when the renderer has no mask yet, or when the canvas size or\n * pixel density changed since the last allocation.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {boolean} True when the stroke mask must be rebuilt.\n */\nfunction needsStrokeMask(Renderer, Cwidth, Cheight, Density) {\n return (\n !Renderer.glMask ||\n Renderer.glMask.width !== Cwidth ||\n Renderer.glMask.height !== Cheight ||\n (typeof Renderer.glMask.pixelDensity === \"function\" &&\n Renderer.glMask.pixelDensity() !== Density)\n );\n}\n\n// =============================================================================\n// Section: Resource Management\n// =============================================================================\n/**\n * Ensures the stroke compositor owns a framebuffer-backed mask with the current\n * canvas dimensions. Stroke stamps are rendered into this mask in WebGL before\n * being blended into the main target.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {object} The framebuffer used as stroke mask.\n */\nexport function ensureStrokeCompositeResources(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n) {\n if (needsStrokeMask(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.glMask?.remove) Renderer.glMask.remove();\n Renderer.glMask = createFramebuffer(Renderer, {\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n }\n\n Renderer.glMask.dirtyRect ??= null;\n Renderer.glMask.isDrawn ??= false;\n return Renderer.glMask;\n}\n\n// =============================================================================\n// Section: Mask Lifecycle\n// =============================================================================\n/**\n * Clears the current stroke mask and resets its bookkeeping flags.\n *\n * @param {object|null} target - Stroke mask framebuffer.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n */\nexport function clearStrokeMask(target, clearTarget) {\n if (!target) return;\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\n}\n\n// =============================================================================\n// Section: Composite Bounds\n// =============================================================================\n/**\n * Returns the rect that should be composited from the stroke mask into the\n * main canvas. Stroke bounds are normally tight dirty rects, but when drawing\n * into an active framebuffer we keep the result conservative and composite the\n * full target.\n *\n * @param {object|null} target - Stroke mask framebuffer.\n * @param {Function} getActiveFramebuffer - Returns the currently bound framebuffer.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} expandDirtyRect - Expands a rect by a constant padding.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @param {number} padding - Extra brush padding in pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\nexport function getStrokeCompositeRect(\n target,\n getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n if (getActiveFramebuffer()) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(target.dirtyRect, DIRTY_BRUSH_PADDING),\n );\n}\n\n/**\n * Returns the resource that should be bound to the blend shader's `u_mask`\n * uniform for stroke compositing.\n *\n * @param {object} _Renderer - Active host renderer.\n * @param {object} mask - Stroke mask framebuffer.\n * @returns {object} Stroke mask framebuffer.\n */\nexport function getStrokeShaderMask(_Renderer, mask) {\n return mask;\n}\n\n// =============================================================================\n// Section: Registration\n// =============================================================================\n/**\n * Registers the stroke compositor with the shared color/composite core.\n * Safe to call multiple times.\n */\nexport function initStrokeComposite() {\n if (isStrokeCompositeRegistered) return;\n Color.registerStrokeComposite?.({\n ensureResources: ensureStrokeCompositeResources,\n clearMask: clearStrokeMask,\n getCompositeRect: getStrokeCompositeRect,\n getShaderMask: getStrokeShaderMask,\n });\n isStrokeCompositeRegistered = true;\n}\n","/**\n * Compiles a shader program from the given vertex and fragment sources.\n * @param {WebGL2RenderingContext} gl - The WebGL2 context.\n * @param {string} vert - Vertex shader source.\n * @param {string} frag - Fragment shader source.\n * @returns {WebGLProgram} The compiled and linked program.\n */\nexport const createProgram = (gl, vert, frag) => {\n const p = gl.createProgram();\n for (let [t, src] of [\n [gl.VERTEX_SHADER, vert],\n [gl.FRAGMENT_SHADER, frag],\n ]) {\n const s = gl.createShader(t);\n gl.shaderSource(s, src);\n gl.compileShader(s);\n gl.attachShader(p, s);\n }\n gl.linkProgram(p);\n return p;\n};\n","// =============================================================================\n// Renderer Runtime Hooks\n// =============================================================================\n\n/**\n * Direct-render hooks used by modules that issue raw WebGL commands.\n *\n * These hooks are intentionally narrow:\n * - begin drawing into an offscreen GL mask target\n * - restore the previous draw target afterward\n * - reset any host-side shader/program bookkeeping after direct GL usage\n */\n\nlet rendererRuntime = {\n beginDirectMaskDraw: () => {\n throw new Error(\"No renderer runtime adapter registered.\");\n },\n endDirectMaskDraw: () => {\n throw new Error(\"No renderer runtime adapter registered.\");\n },\n resetDirectShaderTracking: () => {},\n};\n\n/**\n * Registers or updates host renderer hooks used by direct WebGL drawing paths.\n *\n * @param {object} hooks\n */\nexport function setRendererRuntime(hooks) {\n rendererRuntime = { ...rendererRuntime, ...hooks };\n}\n\nexport const beginDirectMaskDraw = (renderer, gl, target) =>\n rendererRuntime.beginDirectMaskDraw(renderer, gl, target);\nexport const endDirectMaskDraw = (renderer, gl, state) =>\n rendererRuntime.endDirectMaskDraw(renderer, gl, state);\nexport const resetDirectShaderTracking = (renderer, gl) =>\n rendererRuntime.resetDirectShaderTracking(renderer, gl);\n","// =============================================================================\n// Module: GL Draw\n// =============================================================================\n/**\n * The GL Draw module batches brush primitives for WebGL2 rendering. It initializes\n * the shader programs and buffers used by circle-based brushes and image-tip brushes,\n * then flushes those queues into the shared framebuffer-backed brush mask.\n */\n\nimport { Cwidth, Cheight, Density, Renderer } from \"../core/target.js\";\nimport {\n Mix,\n isMixReady,\n State,\n} from \"../core/color.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport {\n beginDirectMaskDraw,\n endDirectMaskDraw,\n resetDirectShaderTracking,\n} from \"../core/renderer_runtime.js\";\nimport { getAffineMatrix } from \"../core/runtime.js\";\nimport vertSrc from \"./shader.vert\";\nimport fragSrc from \"./shader.frag\";\nimport imgVertSrc from \"./image.vert\";\nimport imgFragSrc from \"./image.frag\";\n\n// =============================================================================\n// Section: Initialization and Setup\n// =============================================================================\n\n// Module state\nlet isLoaded = false,\n gl,\n framebufferProjMatrix,\n vao,\n buf,\n program;\nlet loadedWidth = 0,\n loadedHeight = 0;\nlet brushMaskTarget = null;\nconst Attr = {},\n Frag = {};\n\n// Cached matrix values — snapshotted once per stroke in snapshotMatrix()\nlet _ma = 1,\n _mb = 0,\n _mc = 0,\n _md = 1,\n _mx = 0,\n _my = 0,\n _halfW = 0,\n _halfH = 0,\n _scale = 1,\n _density = 1;\n\n/**\n * Snapshots the current runtime affine transform. Call once at the start of each stroke.\n */\nexport function snapshotMatrix() {\n const m = getAffineMatrix();\n _ma = m.a;\n _mb = m.b;\n _mc = m.c;\n _md = m.d;\n _mx = m.x;\n _my = m.y;\n _halfW = Cwidth / 2;\n _halfH = Cheight / 2;\n _scale = Math.sqrt(_ma * _ma + _mb * _mb);\n _density = Density;\n}\n\n// Pre-allocated flat buffer for circle data (x, y, radius, alpha per circle)\nconst INITIAL_CAPACITY = 2048;\nlet circleData = new Float32Array(INITIAL_CAPACITY * 4);\nlet circleCount = 0;\nlet bufferCapacity = INITIAL_CAPACITY;\nlet gpuBufferSize = INITIAL_CAPACITY * 4 * 4; // bytes allocated on GPU\nlet circleDirtyRect = null;\n\n// ---------------------------------------------------------------------------\n// Image instancing state\n// ---------------------------------------------------------------------------\nlet imgProgram = null;\nlet imgVao = null;\nlet imgCornerBuf = null;\nlet imgInstanceBuf = null;\nconst imgAttr = {};\nconst imgFrag = {};\nlet imgGpuSize = 0;\n\nconst IMG_FLOATS = 5; // screenX, screenY, halfSize, angle, alpha — per stamp\nconst IMG_INIT_CAP = 256;\nlet imgData = new Float32Array(IMG_INIT_CAP * IMG_FLOATS);\nlet imgCount = 0;\nlet imgCapacity = IMG_INIT_CAP;\nlet imgDirtyRect = null;\n\n// Texture cache: src string → WebGLTexture (cleared whenever the GL context changes)\nconst texCache = new Map();\n\n// Static unit-quad corners for gl.TRIANGLE_STRIP in quad-local space.\nconst QUAD_CORNERS = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]);\n\nfunction ensureBrushMaskTarget() {\n const rendererMask = Renderer?.glMask;\n if (!rendererMask) return null;\n brushMaskTarget = rendererMask;\n brushMaskTarget.dirtyRect ??= null;\n brushMaskTarget.isDrawn ??= false;\n Mix.glMask = brushMaskTarget;\n return brushMaskTarget;\n}\n\nfunction getProjectionMatrix() {\n return framebufferProjMatrix;\n}\n\nfunction beginMaskTarget() {\n return beginDirectMaskDraw(Renderer, gl, Mix.glMask);\n}\n\nfunction endMaskTarget(state) {\n endDirectMaskDraw(Renderer, gl, state);\n}\n\nfunction accumulateDirtyRect(currentRect, minX, minY, maxX, maxY) {\n if (!currentRect) return { minX, minY, maxX, maxY };\n if (minX < currentRect.minX) currentRect.minX = minX;\n if (minY < currentRect.minY) currentRect.minY = minY;\n if (maxX > currentRect.maxX) currentRect.maxX = maxX;\n if (maxY > currentRect.maxY) currentRect.maxY = maxY;\n return currentRect;\n}\n\n/**\n * Initializes WebGL objects if not done already.\n */\nexport function isReady() {\n isMixReady();\n ensureBrushMaskTarget();\n\n const nextGl = Renderer.drawingContext;\n const needsContextRefresh = !isLoaded || gl !== nextGl;\n const needsProjectionRefresh =\n needsContextRefresh || loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (needsProjectionRefresh) {\n framebufferProjMatrix = new Float32Array([\n 2 / Cwidth,\n 0,\n 0,\n 0,\n 0,\n 2 / Cheight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n -1,\n 0,\n 1,\n ]);\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n }\n\n if (!needsContextRefresh) return;\n\n gl = nextGl;\n\n // Create shader program and initialize\n program = createProgram(gl, vertSrc, fragSrc);\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n // Cache attribute and uniform locations\n [\"a_position\", \"a_radius\", \"a_alpha\"].forEach(\n (n) => (Attr[n] = gl.getAttribLocation(program, n)),\n );\n [\"u_matrix\", \"u_color\"].forEach(\n (n) => (Frag[n] = gl.getUniformLocation(program, n)),\n );\n\n // Create persistent VAO and VBO\n vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n\n buf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n gl.bufferData(gl.ARRAY_BUFFER, circleData.byteLength, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n\n // Set up vertex attributes (only needs to happen once with persistent VAO)\n const stride = 16; // 4 floats × 4 bytes\n gl.enableVertexAttribArray(Attr.a_position);\n gl.vertexAttribPointer(Attr.a_position, 2, gl.FLOAT, false, stride, 0);\n gl.enableVertexAttribArray(Attr.a_radius);\n gl.vertexAttribPointer(Attr.a_radius, 1, gl.FLOAT, false, stride, 8);\n gl.enableVertexAttribArray(Attr.a_alpha);\n gl.vertexAttribPointer(Attr.a_alpha, 1, gl.FLOAT, false, stride, 12);\n\n gl.bindVertexArray(null);\n\n // ------------------------------------------------------------------\n // Image-tip instancing program\n // ------------------------------------------------------------------\n texCache.clear();\n\n imgProgram = createProgram(gl, imgVertSrc, imgFragSrc);\n [\"a_corner\", \"a_pos\", \"a_size\", \"a_angle\", \"a_alpha\"].forEach(\n (n) => (imgAttr[n] = gl.getAttribLocation(imgProgram, n)),\n );\n [\"u_proj\", \"u_color\", \"u_tex\"].forEach(\n (n) => (imgFrag[n] = gl.getUniformLocation(imgProgram, n)),\n );\n\n imgVao = gl.createVertexArray();\n gl.bindVertexArray(imgVao);\n\n // Static corner VBO (per-vertex, no divisor)\n imgCornerBuf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, imgCornerBuf);\n gl.bufferData(gl.ARRAY_BUFFER, QUAD_CORNERS, gl.STATIC_DRAW);\n gl.enableVertexAttribArray(imgAttr.a_corner);\n gl.vertexAttribPointer(imgAttr.a_corner, 2, gl.FLOAT, false, 0, 0);\n\n // Instance data VBO (per-instance)\n imgInstanceBuf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, imgInstanceBuf);\n gl.bufferData(gl.ARRAY_BUFFER, imgData.byteLength, gl.DYNAMIC_DRAW);\n imgGpuSize = imgData.byteLength;\n\n const istride = IMG_FLOATS * 4; // 20 bytes\n gl.enableVertexAttribArray(imgAttr.a_pos);\n gl.vertexAttribPointer(imgAttr.a_pos, 2, gl.FLOAT, false, istride, 0);\n gl.vertexAttribDivisor(imgAttr.a_pos, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_size);\n gl.vertexAttribPointer(imgAttr.a_size, 1, gl.FLOAT, false, istride, 8);\n gl.vertexAttribDivisor(imgAttr.a_size, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_angle);\n gl.vertexAttribPointer(imgAttr.a_angle, 1, gl.FLOAT, false, istride, 12);\n gl.vertexAttribDivisor(imgAttr.a_angle, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_alpha);\n gl.vertexAttribPointer(imgAttr.a_alpha, 1, gl.FLOAT, false, istride, 16);\n gl.vertexAttribDivisor(imgAttr.a_alpha, 1);\n\n gl.bindVertexArray(null);\n\n isLoaded = true;\n}\n\n// =============================================================================\n// Section: Drawing Primitives\n// =============================================================================\n\n/**\n * Queue a circle to be drawn with the specified parameters.\n * Data is written directly into a flat Float32Array to avoid object allocation.\n * Applies the full 2D affine transform (rotation + scale + translation) from\n * the current runtime transform so that brush.rotate() and brush.scale() work correctly.\n */\nexport function circle(x, y, diameter, alpha) {\n // Grow buffer if needed\n if (circleCount >= bufferCapacity) {\n bufferCapacity *= 2;\n const newData = new Float32Array(bufferCapacity * 4);\n newData.set(circleData);\n circleData = newData;\n }\n\n // x/y arrive in \"position space\": user coords + (Cwidth/2, Cheight/2).\n // Subtract the offset to recover user coords, apply the full matrix, then re-add\n // the offset so the result is in screen pixel space [0..Cwidth, 0..Cheight].\n const px = x - _halfW;\n const py = y - _halfH;\n\n const offset = circleCount * 4;\n const screenX = _ma * px + _mc * py + _mx + _halfW;\n const screenY = _mb * px + _md * py + _my + _halfH;\n const radius = (_density * diameter * _scale) / 2;\n\n circleData[offset] = screenX;\n circleData[offset + 1] = screenY;\n // Scale the diameter by the matrix's scale factor (length of the transformed x-axis)\n circleData[offset + 2] = radius;\n circleData[offset + 3] = alpha / 255;\n\n const dScreenX = screenX * _density;\n const dScreenY = screenY * _density;\n circleDirtyRect = accumulateDirtyRect(\n circleDirtyRect,\n dScreenX - radius - 1,\n dScreenY - radius - 1,\n dScreenX + radius + 1,\n dScreenY + radius + 1,\n );\n\n circleCount++;\n}\n\n/**\n * Queue an image stamp to be drawn with instanced rendering.\n * Accepts the same coordinate conventions as circle(): x/y in position space\n * (user coords + Cwidth/2, Cheight/2), size in user-coord units, alpha in [0..255].\n * @param {number} x - X in position space.\n * @param {number} y - Y in position space.\n * @param {number} size - Full stamp diameter in user-coord units.\n * @param {number} angle - Rotation in radians.\n * @param {number} alpha - Opacity [0..255].\n * @param {number} [extraPadding=0] - Conservative extra padding in user units.\n */\nexport function stampImage(x, y, size, angle, alpha, extraPadding = 0) {\n if (imgCount >= imgCapacity) {\n imgCapacity *= 2;\n const next = new Float32Array(imgCapacity * IMG_FLOATS);\n next.set(imgData);\n imgData = next;\n }\n\n const px = x - _halfW;\n const py = y - _halfH;\n const screenX = _ma * px + _mc * py + _mx + _halfW;\n const screenY = _mb * px + _md * py + _my + _halfH;\n const halfSize = (_density * size * _scale) / 2;\n const extraRadius = _density * extraPadding * _scale;\n\n const base = imgCount * IMG_FLOATS;\n imgData[base] = screenX;\n imgData[base + 1] = screenY;\n imgData[base + 2] = halfSize;\n imgData[base + 3] = angle;\n imgData[base + 4] = alpha / 255;\n\n // Bounding box: rotated square worst-case = circle of radius halfSize * √2\n const dScreenX = screenX * _density;\n const dScreenY = screenY * _density;\n const boundsRadius = halfSize * 1.42 + extraRadius;\n imgDirtyRect = accumulateDirtyRect(\n imgDirtyRect,\n dScreenX - boundsRadius - 1,\n dScreenY - boundsRadius - 1,\n dScreenX + boundsRadius + 1,\n dScreenY + boundsRadius + 1,\n );\n\n imgCount++;\n}\n\n/**\n * Flush all queued image stamps in a single instanced draw call.\n * @param {object} p5img - The preprocessed brush-tip image/canvas (from T.tips).\n * @param {string} src - The image src string, used as the texture cache key.\n */\nexport function glDrawImages(p5img, src) {\n if (imgCount === 0) return;\n\n Mix.glMask.isDrawn = true;\n const targetState = beginMaskTarget();\n\n // Lazy-create the WebGL texture from the tip canvas on first use.\n let tex = texCache.get(src);\n if (!tex) {\n tex = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, p5img.canvas);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n texCache.set(src, tex);\n }\n\n gl.useProgram(imgProgram);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.uniform1i(imgFrag.u_tex, 0);\n\n const color = State.stroke.color._array;\n gl.uniform4f(imgFrag.u_color, ...color);\n gl.uniformMatrix4fv(imgFrag.u_proj, false, getProjectionMatrix());\n\n gl.bindVertexArray(imgVao);\n gl.bindBuffer(gl.ARRAY_BUFFER, imgInstanceBuf);\n\n const byteCount = imgCount * IMG_FLOATS * 4;\n const dataView = imgData.subarray(0, imgCount * IMG_FLOATS);\n if (byteCount > imgGpuSize) {\n gl.bufferData(gl.ARRAY_BUFFER, imgData, gl.DYNAMIC_DRAW);\n imgGpuSize = imgData.byteLength;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);\n }\n\n gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, imgCount);\n\n gl.bindVertexArray(null);\n gl.bindTexture(gl.TEXTURE_2D, null);\n endMaskTarget(targetState);\n\n if (imgDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, imgDirtyRect);\n imgDirtyRect = null;\n }\n\n imgCount = 0;\n\n // Let the host adapter know we changed the active program.\n resetDirectShaderTracking(Renderer, gl);\n}\n\n/**\n * Removes a cached GL texture by key, forcing re-upload on next draw.\n * Call this when a custom tip function changes after brush.add().\n */\nexport function invalidateTexEntry(key) {\n const tex = texCache.get(key);\n if (tex && gl) gl.deleteTexture(tex);\n texCache.delete(key);\n}\n\n/**\n * Draw all queued circles using WebGL\n */\nexport function glDraw() {\n if (circleCount === 0) return;\n\n Mix.glMask.isDrawn = true;\n const targetState = beginMaskTarget();\n\n const color = State.stroke.color._array;\n\n // Re-activate our shader in case host drawing switched programs.\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n gl.bindVertexArray(vao);\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n\n // Upload vertex data — reallocate GPU buffer only if needed\n const byteCount = circleCount * 16; // 4 floats × 4 bytes\n const dataView = circleData.subarray(0, circleCount * 4);\n if (byteCount > gpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, circleData, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);\n }\n\n // Set uniforms and draw\n gl.uniform4f(Frag.u_color, ...color);\n gl.uniformMatrix4fv(Frag.u_matrix, false, getProjectionMatrix());\n gl.drawArrays(gl.POINTS, 0, circleCount);\n\n gl.bindVertexArray(null);\n endMaskTarget(targetState);\n\n if (circleDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, circleDirtyRect);\n circleDirtyRect = null;\n }\n\n // Reset queue (no deallocation)\n circleCount = 0;\n\n // We called gl.useProgram() directly, bypassing host shader tracking.\n // Reset it so the host is forced to re-activate its own shader next time\n // it draws — otherwise it may skip gl.useProgram() and set uniforms on the\n // wrong active program, causing \"location is not from the associated program\".\n resetDirectShaderTracking(Renderer, gl);\n}\n","// =============================================================================\n// Module: Brush\n// =============================================================================\n/**\n * The Brush module provides a comprehensive set of functions and classes for\n * simulating various drawing tools ranging from pens, markers, pencils, to\n * custom image-based brushes. This module controls brush properties such as\n * weight, color, vibration, and spacing, and manages the drawing process through\n * stateful methods that enable features like pressure sensitivity, clipping, and\n * blending. By supporting multiple brush types and dynamic parameter adjustments,\n * the Brush module facilitates the creation of realistic and expressive stroke effects.\n */\n\n// Core imports\nimport { Cwidth, Cheight, Renderer, isCanvasReady } from \"../core/target.js\";\nimport {\n Mix,\n State,\n} from \"../core/color.js\";\nimport {\n rr,\n map,\n dist,\n randInt,\n calcAngle,\n toDegrees,\n gaussian,\n rArray,\n noise,\n _onSeed, \n cos,\n sin\n} from \"../core/utils.js\";\nimport { createColor } from \"../core/runtime.js\";\nimport { Position, isFieldReady } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { createTipSurface, loadImageTip } from \"./runtime.js\";\n\n// Internal module imports\nimport { initStrokeComposite } from \"./composite.js\";\nimport {\n isReady,\n glDraw,\n glDrawImages,\n circle,\n stampImage,\n invalidateTexEntry,\n snapshotMatrix,\n} from \"./gl_draw.js\";\n\ninitStrokeComposite(); // Register the stroke composite system for offscreen mask rendering and compositing.\n\n// ---------------------------------------------------------------------------\n// Brush State and Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Global stroke state settings.\n */\nState.stroke = {\n color: null,\n weight: 1,\n type: \"HB\",\n isActive: false,\n opacity: 1,\n};\n\nlet list = new Map();\n\nconst DEFAULT_CUSTOM_PRESSURE_VARIATION = {\n offset: 0.08,\n scale: 0.08,\n warp: 0.06,\n tilt: 0.06,\n};\n\n/**\n * Retrieves a shallow copy of the current stroke state.\n * @returns {object} The stroke state.\n */\nexport function BrushState() {\n return { ...State.stroke };\n}\n\n/**\n * Updates the stroke state.\n * @param {object} state - The new stroke state.\n */\nexport function BrushSetState(state) {\n State.stroke = { ...state };\n}\n\n// =============================================================================\n// Section: Brush Manager\n// =============================================================================\n\n/**\n * Adds a new brush with the specified parameters to the brush list.\n * @param {string} name - The unique name for the new brush.\n * @param {object} params - The parameters defining the brush behavior and appearance.\n */\n/**\n * Normalizes the pressure parameter to the internal { type, min_max, curve } format.\n * Accepts:\n * [start, end] — linear ramp between two pressure values\n * [start, mid, end] — piecewise linear (e.g. [1.5, 0.5, 1.5] for U-curve)\n * (t) => value — custom function, t ∈ [0,1], return value ∈ [0,1]\n * { mode: \"gaussian\", curve, min_max } — advanced built-in pressure profile\n * { curve, min_max } — legacy gaussian format, preserved for compatibility\n */\nexport function normalizePressure(p) {\n if (!p) return p;\n if (typeof p === \"function\")\n return {\n type: \"custom\",\n min_max: [0, 1],\n curve: p,\n variation: { ...DEFAULT_CUSTOM_PRESSURE_VARIATION },\n };\n if (typeof p === \"object\" && !Array.isArray(p)) {\n if (p.type === \"custom\" || p.mode === \"custom\") {\n const { mode, ...rest } = p;\n return {\n ...rest,\n type: \"custom\",\n variation: {\n ...DEFAULT_CUSTOM_PRESSURE_VARIATION,\n ...(rest.variation ?? {}),\n },\n };\n }\n if (\n p.type === \"gaussian\" ||\n p.mode === \"gaussian\" ||\n (Array.isArray(p.curve) && Array.isArray(p.min_max))\n ) {\n return {\n ...p,\n type: \"gaussian\",\n curve: p.curve,\n min_max: p.min_max,\n };\n }\n return p;\n }\n if (Array.isArray(p)) {\n const [s, m, e] = p.length === 2 ? [p[0], (p[0] + p[1]) / 2, p[1]] : p;\n const min = Math.min(s, m, e),\n max = Math.max(s, m, e);\n const range = max - min || 1;\n const [ns, nm, ne] = [\n (s - min) / range,\n (m - min) / range,\n (e - min) / range,\n ];\n return {\n type: \"custom\",\n min_max: [min, max],\n variation: { ...DEFAULT_CUSTOM_PRESSURE_VARIATION },\n curve: (t) =>\n t < 0.5 ? ns + (nm - ns) * t * 2 : nm + (ne - nm) * (t - 0.5) * 2,\n };\n }\n}\n\nexport function add(name, params) {\n const validTypes = [\"marker\", \"custom\", \"image\", \"spray\"];\n params.type = validTypes.includes(params.type) ? params.type : \"default\";\n if (params.markerTip === undefined) params.markerTip = true;\n if (params.noise === undefined) params.noise = 0.3;\n params.noise = Math.max(0, Math.min(1, params.noise));\n // Accept legacy param names for backward compatibility\n if (params.vibration !== undefined && params.scatter === undefined)\n params.scatter = params.vibration;\n if (params.definition !== undefined && params.sharpness === undefined)\n params.sharpness = params.definition;\n if (params.quality !== undefined && params.grain === undefined)\n params.grain = params.quality;\n params.pressure = normalizePressure(params.pressure);\n if (params.type === \"custom\") {\n if (typeof params.tip !== \"function\") {\n throw new Error(`Brush \"${name}\" is type \"custom\" but is missing a tip function.`);\n }\n // Rasterise the tip once into a 500×500 P2D buffer.\n // Users draw in a 100×100 coordinate space (origin at centre);\n // dark fills/strokes → high opacity, light/white → transparent.\n const key = `custom::${name}`;\n invalidateTexEntry(key); // discard stale GPU texture if tip changed\n const g = createTipSurface(500, 500);\n g.pixelDensity(1);\n g.background(255);\n g.noSmooth();\n g.push();\n g.translate(250, 250); // centre origin\n g.scale(5); // 100 user units → 500 px\n g.noStroke();\n params.tip(g);\n g.pop();\n T.imageToWhite(g); // dark → high alpha, RGB → white for tint\n T.tips.set(key, g);\n params.tipKey = key;\n list.set(name, { param: params, colors: [], buffers: [] });\n return;\n }\n if (params.type === \"image\") {\n if (!params.image || !params.image.src) {\n throw new Error(\n `Brush \"${name}\" is type \"image\" but is missing params.image.src. Example: image: { src: \"./tip.jpg\" }`,\n );\n }\n T.add(params.image.src);\n list.set(name, { param: params, colors: [], buffers: [] });\n return T.load(); // returns a Promise; only loads images not yet loaded\n }\n list.set(name, { param: params, colors: [], buffers: [] });\n}\n\n/**\n * Retrieves the list of available brush names.\n * @returns {Array<string>} Array of brush names.\n */\nexport function box() {\n return [...list.keys()];\n}\n\nexport function getBrushParams(brushName) {\n return list.get(brushName)?.param ?? null;\n}\n\n/**\n * Scales standard brush parameters by the provided factor.\n * @param {number} scaleFactor - The scaling factor to apply.\n */\nexport function scaleBrushes(scaleFactor) {\n for (const { param } of list.values()) {\n if (param) {\n param.weight *= scaleFactor;\n param.scatter *= scaleFactor;\n param.spacing *= scaleFactor;\n }\n }\n}\n\n/**\n * Sets the current brush type by name.\n * @param {string} brushName - The name of the brush.\n */\nexport function pick(brushName) {\n if (!list.has(brushName)) {\n throw new Error(\n `Brush \"${brushName}\" not found. Available brushes: ${[...list.keys()].join(\", \")}.`,\n );\n }\n State.stroke.type = brushName;\n}\n\n/**\n * Sets the stroke style (color) for the current brush.\n * @param {number|string|Color} r - Red component, CSS color string, or Color object.\n * @param {number} [g] - Green component.\n * @param {number} [b] - Blue component.\n */\nexport function stroke(r, g, b) {\n isCanvasReady();\n State.stroke.color = createColor(...arguments);\n State.stroke.isActive = true;\n}\n\n/**\n * Sets the brush weight (thickness).\n * @param {number} weight - The weight value.\n */\nexport function strokeWeight(weight) {\n State.stroke.weight = weight;\n}\n\n/**\n * Sets the current brush with name, color, and weight.\n * @param {string} brushName - The brush name.\n * @param {string|Color} color - The brush color.\n * @param {number} [weight=1] - The brush weight.\n */\nexport function set(brushName, color, weight = 1) {\n pick(brushName);\n stroke(color);\n strokeWeight(weight);\n}\n\n/**\n * Disables the stroke effect.\n */\nexport function noStroke() {\n State.stroke.isActive = false;\n}\n\n/**\n * Defines a clipping region for strokes.\n * The region uses the same coordinate space as brush drawing commands,\n * with the current runtime transform captured at call time.\n * @param {number[]} region - Array as [x1, y1, x2, y2] defining the clipping region.\n */\nexport function clip(region) {\n isCanvasReady();\n return region;\n}\n\n/**\n * Disables the clipping region.\n */\nexport function noClip() {\n return;\n}\n\n// ---------------------------------------------------------------------------\n// Drawing Variables and Functions\n// ---------------------------------------------------------------------------\nlet _position, _length, _plot, _dir;\nlet _cachedPlotAngle = 0;\nconst current = {};\n\n/**\n * Initializes the drawing state.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of stroke.\n * @param {Plot|false} [plot=false] - Plot object for path-following strokes.\n */\nfunction initializeDrawingState(x, y, length, plot = false) {\n snapshotMatrix();\n _position = new Position(x + Cwidth / 2, y + Cheight / 2);\n _length = length;\n _plot = plot;\n if (_plot) _plot.calcIndex(0);\n}\n\nconst gaussians = [];\n\n_onSeed(() => {\n gaussians.length = 0;\n});\n\n/**\n * Executes the drawing operation.\n * @param {number} angleScale - Angle (in degrees) or scaling factor.\n * @param {boolean} isPlot - True if plotting a shape.\n */\nfunction draw(angleScale, isPlot) {\n if (!isPlot) _dir = angleScale;\n saveState();\n\n const stepSize = spacing();\n const totalSteps = Math.round(\n (_length * (isPlot ? angleScale : 1)) / stepSize,\n );\n current.pressureCount = 10;\n current.cachedPressure = undefined;\n current.lineNoiseCount = 5;\n current.cachedLineNoise = undefined;\n\n const neededGaussians = totalSteps * 2;\n while (gaussians.length < neededGaussians) {\n gaussians.push(gaussian());\n }\n\n for (let i = 0; i < totalSteps; i++) {\n if (isPlot) _cachedPlotAngle = _plot.angle(_position.plotted);\n tip();\n if (isPlot) {\n _position.plotTo(_plot, stepSize, stepSize, angleScale, _cachedPlotAngle);\n } else {\n _position._moveToDegrees(angleScale, stepSize, stepSize);\n }\n }\n restoreState();\n}\n\n/**\n * Prepares the environment for a brush stroke.\n */\nfunction saveState() {\n current.seed = rr() * 999999;\n const { param } = list.get(State.stroke.type) ?? {};\n if (!param) return;\n current.p = param;\n\n // Set pressure values for the stroke\n const { pressure } = param;\n current.isCustomPressure = pressure.type === \"custom\";\n current.a = !current.isCustomPressure ? rr(-1, 1) : 0;\n current.b = !current.isCustomPressure ? rr(1, 1.5) : 0;\n if (!current.isCustomPressure) {\n current.cp = rr(3, 3.5);\n current.ct = 0;\n current.cs = 1;\n current.ck = 0;\n } else {\n const variation = pressure.variation ?? DEFAULT_CUSTOM_PRESSURE_VARIATION;\n current.cp = rr(-variation.offset, variation.offset);\n current.ct = rr(-variation.warp, variation.warp);\n current.cs = rr(1 - variation.scale, 1 + variation.scale);\n current.ck = rr(-variation.tilt, variation.tilt);\n }\n [current.min, current.max] = pressure.min_max;\n\n current.noiseoffset = 0.05 * current.p.noise;\n\n // Cache stroke direction for direction-aware dispersion (non-plot strokes only)\n if (!_plot) {\n current.cos = cos(_dir);\n current.sin = sin(_dir);\n }\n\n // Ensure GL is ready and blend state\n isReady();\n const switchingToBrush = Mix.isBrush !== true;\n Mix.isBrush = true;\n if (switchingToBrush) Mix.justChanged = true;\n Mix.blend(State.stroke.color);\n\n // Set additional state values\n current.alpha = calculateAlpha();\n current.overscan = getImageTipOverscan();\n current.drawFn =\n current.p.type === \"spray\" ? drawSpray :\n current.p.type === \"marker\" ? drawMarker :\n (current.p.type === \"custom\" || current.p.type === \"image\") ? drawImageTip :\n drawDefault;\n\n markerTip();\n}\n\n/**\n * Restores drawing state after completing a stroke.\n */\nfunction restoreState() {\n markerTip();\n glDraw();\n const type = current.p?.type;\n if (type === \"image\") glDrawImages(T.tips.get(current.p.image.src), current.p.image.src);\n else if (type === \"custom\") glDrawImages(T.tips.get(current.p.tipKey), current.p.tipKey);\n}\n\n/**\n * Renders the brush tip based on current pressure and position.\n */\nfunction tip() {\n const pressure = calculatePressure();\n const lineNoise = calculateLineNoise();\n\n if (lineNoise > rr(1,1.02) && rr(0,1) < 0.7) return;\n current.drawFn(pressure * lineNoise);\n}\n\n/**\n * Calculates the effective brush pressure.\n * @returns {number} The calculated pressure.\n */\nfunction calculatePressure() {\n if (current.pressureCount >= 10 || current.cachedPressure === undefined) {\n current.cachedPressure = _plot\n ? simPressure() * _plot.pressure(_position.plotted)\n : simPressure();\n current.pressureCount = 0;\n }\n current.pressureCount++;\n return current.cachedPressure;\n}\n\nfunction calculateLineNoise() {\n if (current.lineNoiseCount >= 10 || current.cachedLineNoise === undefined) {\n current.cachedLineNoise = map(\n noise(current.seed + _position.plotted * 0.01, 0),\n -1,\n 1,\n 1 - current.noiseoffset,\n 1 + current.noiseoffset,\n );\n current.lineNoiseCount = 0;\n }\n current.lineNoiseCount++;\n return current.cachedLineNoise;\n}\n\n/**\n * Simulates brush pressure based on stroke parameters.\n * @returns {number} Simulated pressure value.\n */\nfunction simPressure() {\n if (!current.isCustomPressure) return gauss();\n const t = _position.plotted / _length;\n return map(\n current.p.pressure.curve(\n Math.max(0, Math.min(1, 0.5 + (t - 0.5 + current.ct) * current.cs)),\n ) +\n current.cp +\n current.ck * (t - 0.5),\n 0,\n 1,\n current.min,\n current.max,\n true,\n );\n}\n\n/**\n * Generates a Gaussian-based pressure value.\n * @param {number} [a] - Center parameter.\n * @param {number} [b] - Width parameter.\n * @param {number} [c] - Shape parameter.\n * @param {number} [min] - Minimum pressure.\n * @param {number} [max] - Maximum pressure.\n * @returns {number} Gaussian pressure value.\n */\nfunction gauss(\n a = 0.5 + current.p.pressure.curve[0] * current.a,\n b = 1 - current.p.pressure.curve[1] * current.b,\n c = current.cp,\n min = current.min,\n max = current.max,\n) {\n const peakPos = a * _length;\n const halfWidth =\n (_position.plotted < peakPos ? b * 1.2 : b * 0.8) * (_length / 2);\n return map(\n 1 /\n (1 +\n Math.pow(Math.abs((_position.plotted - peakPos) / halfWidth), 2 * c)),\n 0,\n 1,\n min,\n max,\n );\n}\n\n/**\n * Calculates the alpha (opacity) level for a brush stroke.\n * @returns {number} The calculated opacity.\n */\nfunction calculateAlpha() {\n return [\"default\", \"spray\"].includes(current.p.type)\n ? current.p.opacity\n : current.p.opacity / Math.min(State.stroke.weight, 1.3);\n}\n\n/**\n * Calculates the step spacing based on the current brush parameters.\n * @returns {number} The spacing value.\n */\nfunction spacing() {\n return current.p?.spacing ?? 1;\n}\n\nfunction getImageTipOverscan() {\n const maxPressure = Math.max(1, current.max ?? 1);\n const scatterReach = State.stroke.weight * current.p.scatter;\n const tipReach = State.stroke.weight * current.p.weight * maxPressure;\n\n // Custom/image tips can extend beyond their nominal square because the tip\n // drawing itself may be large and because high scatter creates sparse large\n // stamps near the edge. Keep culling/dirty tracking conservative.\n return Math.max(8, scatterReach * 1.5 + tipReach * 0.75);\n}\n\n// ---------------------------------------------------------------------------\n// Brush Tip Rendering Methods\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the spray tip effect.\n * @param {number} pressure - Current pressure.\n */\nfunction drawSpray(pressure) {\n const vibration =\n State.stroke.weight * current.p.scatter * pressure +\n (State.stroke.weight * rArray(gaussians) * current.p.scatter) / 3;\n const sw = current.p.weight * rr(0.9, 1.1);\n const iterations = Math.ceil(current.p.grain / pressure);\n for (let j = 0; j < iterations; j++) {\n const r = rr(0.9, 1.1);\n const rX = r * vibration * rr(-1, 1);\n const yRandomFactor = rr(-1, 1);\n const sqrtPart = Math.sqrt((r * vibration) ** 2 - rX ** 2);\n circle(\n _position.x + rX,\n _position.y + yRandomFactor * sqrtPart,\n sw,\n current.alpha,\n );\n }\n}\n\n/**\n * Draws the marker tip effect.\n * @param {number} pressure - Current pressure.\n * @param {boolean} [vibrate=true] - Whether to apply vibration.\n */\nfunction drawMarker(pressure, vibrate = true, alpha = current.alpha) {\n const vibration = vibrate ? State.stroke.weight * current.p.scatter : 0;\n const rx = vibrate ? vibration * rr(-1, 1) : 0;\n const ry = vibrate ? vibration * rr(-1, 1) : 0;\n circle(\n _position.x + rx,\n _position.y + ry,\n State.stroke.weight * current.p.weight * pressure,\n alpha * Math.max(0.8, pressure) * rr(0.9,1.1),\n );\n}\n\n/**\n * Queues a stamp for instanced GL rendering.\n * Handles both \"image\" and \"custom\" tip types.\n * @param {number} pressure - Current pressure.\n * @param {number} alpha - Opacity [0..255].\n */\nfunction drawImageTip(pressure, alpha = current.alpha) {\n const vibration = State.stroke.weight * current.p.scatter;\n const rx = vibration * rr(-1, 1);\n const ry = vibration * rr(-1, 1);\n const size = current.p.weight * State.stroke.weight * pressure;\n const overscan = current.overscan;\n let angle = 0;\n if (current.p.rotate === \"random\") {\n angle = randInt(0, 360) * (Math.PI / 180);\n } else if (current.p.rotate === \"natural\") {\n angle = ((_plot ? -_cachedPlotAngle : -_dir) + _position.angle()) * (Math.PI / 180);\n }\n stampImage(\n _position.x + rx,\n _position.y + ry,\n size,\n angle,\n alpha * Math.max(0.8, pressure) * rr(0.9, 1.1),\n overscan,\n );\n}\n\n/**\n * Draws the default brush tip.\n * @param {number} pressure - Current pressure.\n */\nfunction drawDefault(pressure, wiggle = 1) {\n wiggle = map(wiggle, 0, 1, 0.9, 1.05);\n const vibration =\n wiggle *\n State.stroke.weight *\n current.p.scatter *\n (current.p.sharpness +\n ((1 - current.p.sharpness) * rArray(gaussians)) / pressure);\n const passesGate = rr(0, current.p.grain * pressure) > 0.4;\n if (passesGate) {\n let dx, dy;\n if (_plot) {\n const plotAngle = _cachedPlotAngle;\n const plotCos = cos(plotAngle);\n const plotSin = sin(plotAngle);\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * plotSin + along * plotCos;\n dy = perp * plotCos - along * plotSin;\n } else {\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * current.sin + along * current.cos;\n dy = perp * current.cos - along * current.sin;\n }\n const diameter =\n pressure *\n pressure *\n current.p.weight *\n rr(0.85, 1.15) *\n State.stroke.weight;\n const alpha = Math.max(0.9, pressure) * current.alpha * rr(0.75, 1.1);\n circle(\n _position.x + dx,\n _position.y + dy,\n diameter,\n alpha,\n );\n }\n}\n\n/**\n * Draws the marker tip with a blend effect.\n */\nfunction markerTip() {\n if (current.p.markerTip === false) return;\n let pressure = calculatePressure();\n let alpha = current.alpha;\n if (current.p.type === \"marker\") {\n for (let s = 1; s < 10; s++) {\n drawMarker((pressure * s) / 10, true, alpha * 8);\n }\n } else if (current.p.type === \"custom\" || current.p.type === \"image\") {\n for (let s = 1; s < 5; s++) {\n drawImageTip((pressure * s) / 10, alpha * 2);\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Basic Drawing Operations\n// ---------------------------------------------------------------------------\n\n/**\n * Draws a line using the current brush.\n * @param {number} x1 - Start x-coordinate.\n * @param {number} y1 - Start y-coordinate.\n * @param {number} x2 - End x-coordinate.\n * @param {number} y2 - End y-coordinate.\n */\nexport function line(x1, y1, x2, y2) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n let d = dist(x1, y1, x2, y2);\n if (d == 0) return;\n initializeDrawingState(x1, y1, d);\n let angle = calcAngle(x1, y1, x2, y2);\n draw(angle, false);\n}\n\n/**\n * Draws a stroke from a starting point in a given direction.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of the stroke.\n * @param {number} dir - Direction, interpreted using the current runtime angle units.\n */\nexport function flowLine(x, y, length, dir) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n initializeDrawingState(x, y, length);\n draw(toDegrees(dir), false);\n}\n\n/**\n * Draws a predefined plot.\n * @param {object} p - Shape object representing the plot.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nfunction plot(p, x, y, scale) {\n isFieldReady();\n initializeDrawingState(x, y, p.length, p);\n draw(scale, true);\n}\n\n// ---------------------------------------------------------------------------\n// Standard Brushes Definition and Initialization\n// ---------------------------------------------------------------------------\n\n/**\n * Defines a set of standard brushes with specific characteristics. Each brush is defined\n * with properties such as weight, scatter, sharpness, grain, opacity, spacing, and\n * pressure sensitivity. Some brushes have additional properties like type, tip, and rotate.\n */\nconst _vals = [\n \"weight\",\n \"scatter\",\n \"sharpness\",\n \"grain\",\n \"opacity\",\n \"spacing\",\n \"pressure\",\n \"type\",\n \"tip\",\n \"rotate\",\n \"markerTip\",\n \"noise\",\n];\nconst _standard_brushes = [\n [\n \"pen\",\n [0.3, 0.15, 0.9, 2, 150, 0.1, { curve: [0.15, 0.2], min_max: [1.2, 1] }],\n ],\n [\n \"rotring\",\n [0.15, 0.05, 0.7, 15, 210, 0.1, { curve: [0.35, 0.2], min_max: [1.3, 1] }],\n ],\n [\n \"2B\",\n [0.3, 0.75, 0.45, 15, 180, 0.1, { curve: [0.1, 0.3], min_max: [1.1, 0.9] }],\n ],\n [\n \"HB\",\n [0.3, 0.6, 0.3, 10, 170, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"2H\",\n [0.2, 0.6, 0.3, 4, 120, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"cpencil\",\n [0.3, 0.55, 0.8, 7, 75, 0.1, { curve: [0.15, 0.2], min_max: [0.95, 1.2] }],\n ],\n [\n \"pastel\",\n [\n 2.05 / 3,\n 13.4 / 3,\n 0.91,\n 28,\n 35,\n 0.085 / 3,\n { mode: \"gaussian\", curve: [0.4, 0.05], min_max: [1.09, 0.93] },\n \"default\",\n undefined,\n \"natural\",\n true,\n 1,\n ],\n ],\n [\n \"crayon\",\n [\n 0.9 / 3,\n 5.45 / 3,\n 0.75,\n 250,\n 159,\n 0.23 / 3,\n [1.1, 0.9],\n \"default\",\n undefined,\n \"natural\",\n true,\n 1,\n ],\n ],\n [\n \"charcoal\",\n [\n 0.35,\n 1.5,\n 0.68,\n 500,\n 120,\n 0.03,\n { curve: [0.15, 0.4], min_max: [1.1, 0.95] },\n ],\n ],\n [\n \"spray\",\n [\n 0.2,\n 6,\n 15,\n 40,\n 90,\n 0.5,\n { curve: [0.2, 0.35], min_max: [0.7, 1] },\n \"spray\",\n ],\n ],\n [\n \"marker\",\n [\n 2,\n 0.2,\n null,\n null,\n 1,\n 0.03,\n { curve: [0.35, 0.25], min_max: [1.2, 0.85] },\n \"marker\",\n ],\n ],\n];\n\nfor (let s of _standard_brushes) {\n let obj = {};\n for (let i = 0; i < s[1].length; i++) obj[_vals[i]] = s[1][i];\n add(s[0], obj);\n}\n\n// ---------------------------------------------------------------------------\n// Extensions to Polygon and Plot Prototypes\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the polygon using the current brush.\n * @param {boolean} [_brush=false] - Optional brush name override.\n * @param {string|Color} [_color] - Optional color override.\n * @param {number} [_weight] - Optional weight override.\n */\nPolygon.prototype.draw = function (_brush = false, _color, _weight) {\n let state = BrushState();\n if (_brush) set(_brush, _color, _weight);\n if (state.isActive) {\n for (let s of this.sides) {\n line(s[0].x, s[0].y, s[1].x, s[1].y);\n }\n }\n BrushSetState(state);\n};\n\n/**\n * Draws the plot using the current brush.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nPlot.prototype.draw = function (x, y, scale) {\n if (BrushState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n plot(this, x, y, scale);\n }\n};\n\n// =============================================================================\n// Section: Loading Custom Image Tips\n// =============================================================================\n/**\n * This section defines the functionality for managing the loading and processing of image tips.\n * Images are loaded from specified source URLs, converted to a white tint for visual effects,\n * and then stored for future use. It includes methods to add new images, convert their color\n * scheme, and integrate them into the active host image pipeline.\n */\n\n/**\n * Manages loading and processing of image tips.\n * Images are converted to white with inverted alpha for tinting via shaders.\n */\nconst T = {\n tips: new Map(),\n\n /**\n * Registers an image source for later loading.\n * @param {string} src - The source URL of the image.\n */\n add(src) {\n if (!this.tips.has(src)) this.tips.set(src, false);\n },\n\n /**\n * Converts image to white with inverted alpha for tint-based rendering.\n * @param {object} image - The host image object to convert.\n */\n imageToWhite(image) {\n image.loadPixels();\n for (let i = 0; i < 4 * image.width * image.height; i += 4) {\n let average =\n (image.pixels[i] + image.pixels[i + 1] + image.pixels[i + 2]) / 3;\n image.pixels[i] = image.pixels[i + 1] = image.pixels[i + 2] = 255;\n image.pixels[i + 3] = 255 - average;\n }\n image.updatePixels();\n },\n\n /**\n * Loads all registered image tips. Returns a promise that resolves\n * when all images are loaded and processed.\n * @returns {Promise}\n */\n async load() {\n const entries = [...this.tips.keys()].filter((k) => !this.tips.get(k));\n await Promise.all(\n entries.map(\n (src) =>\n loadImageTip(src, T.imageToWhite).then((p5img) => {\n this.tips.set(src, p5img);\n }),\n ),\n );\n },\n};\n","import { State } from \"../core/color.js\";\nimport { toDegreesSigned, map, rr } from \"../core/utils.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { BrushState, BrushSetState, set, line } from \"../stroke/stroke.js\";\n\n// =============================================================================\n// Module: Classic Hatch\n// =============================================================================\n\n// ---------------------------------------------------------------------------\n// Hatch State\n// ---------------------------------------------------------------------------\n\nState.hatch = {\n isActive: false,\n dist: 5,\n angle: 45,\n options: {},\n hBrush: false,\n};\n\n/**\n * Returns a shallow snapshot of the current hatch modifier state.\n *\n * @returns {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}}\n */\nexport function HatchState() {\n return { ...State.hatch };\n}\n\n/**\n * Restores hatch modifier state from a previously captured snapshot.\n *\n * @param {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}} state\n */\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Activates classic scanline hatching for subsequent shapes.\n *\n * @param {number} [dist=5] Distance between scanlines.\n * @param {number} [angle=45] Hatch angle in the current runtime angle units.\n * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [options]\n */\nexport function hatch(\n dist = 5,\n angle = 45,\n options = { rand: false, continuous: false, gradient: false }\n) {\n let s = State.hatch;\n s.isActive = true;\n s.dist = dist;\n s.angle = toDegreesSigned(angle);\n s.options = options;\n}\n\n/**\n * Overrides the brush, color, and weight used specifically for hatch strokes.\n *\n * @param {string} brush\n * @param {string|object} [color=\"black\"]\n * @param {number} [weight=1]\n */\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\n/**\n * Deactivates hatching and clears any hatch-specific brush override.\n */\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Scanline Generation\n// ---------------------------------------------------------------------------\n\n/**\n * Computes hatch segments for one polygon by rotating it into scanline space,\n * intersecting horizontal scanlines against its edges, and rotating the\n * resulting segments back into canvas space.\n *\n * @param {Polygon} polygon\n * @param {number} angle Hatch angle in degrees.\n * @param {number} dist Base scanline spacing.\n * @param {number} gradient Multiplicative spacing growth per scanline.\n * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}\n */\nfunction scanlineHatch(polygon, angle, dist, gradient) {\n const rad = (angle * Math.PI) / 180;\n const cosA = Math.cos(rad),\n sinA = Math.sin(rad);\n const cosB = Math.cos(-rad),\n sinB = Math.sin(-rad);\n\n const verts = polygon.a,\n n = verts.length;\n\n // Rotate vertices; track Y extent\n const rotated = new Array(n);\n let minY = Infinity,\n maxY = -Infinity;\n for (let i = 0; i < n; i++) {\n const x = verts[i][0],\n y = verts[i][1];\n const r = [x * cosA - y * sinA, x * sinA + y * cosA];\n rotated[i] = r;\n if (r[1] < minY) minY = r[1];\n if (r[1] > maxY) maxY = r[1];\n }\n\n // Build edge list (skip horizontal edges)\n const edges = [];\n for (let i = 0; i < n; i++) {\n const a = rotated[i],\n b = rotated[(i + 1) % n];\n if (a[1] !== b[1]) edges.push(a, b);\n }\n const eLen = edges.length;\n\n // Scan, find crossings, rotate back\n const segments = [];\n const cx = [];\n let Y = minY + dist * 0.5,\n step = dist;\n while (Y < maxY) {\n cx.length = 0;\n for (let i = 0; i < eLen; i += 2) {\n const y1 = edges[i][1],\n y2 = edges[i + 1][1];\n if ((y1 <= Y && Y < y2) || (y2 <= Y && Y < y1))\n cx.push(\n edges[i][0] + ((Y - y1) / (y2 - y1)) * (edges[i + 1][0] - edges[i][0])\n );\n }\n cx.sort((a, b) => a - b);\n for (let i = 0; i < cx.length - 1; i += 2) {\n segments.push({\n scanY: Y,\n x1: cx[i] * cosB - Y * sinB,\n y1: cx[i] * sinB + Y * cosB,\n x2: cx[i + 1] * cosB - Y * sinB,\n y2: cx[i + 1] * sinB + Y * cosB,\n });\n }\n Y += step;\n step *= gradient;\n }\n return segments;\n}\n\n/**\n * Collects and orders hatch segments for one polygon or a polygon list.\n *\n * Segments are sorted in scanline traversal order so downstream rendering can\n * optionally connect them into a continuous serpentine path.\n *\n * @param {Polygon|Polygon[]} polygons\n * @param {number} dist\n * @param {number} angle\n * @param {number} gradient\n * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}\n */\nfunction getHatchSegments(polygons, dist, angle, gradient) {\n if (!Array.isArray(polygons)) polygons = [polygons];\n const segs = [];\n for (const poly of polygons) {\n for (const s of scanlineHatch(poly, angle, dist, gradient)) segs.push(s);\n }\n segs.sort((a, b) => (a.scanY === b.scanY ? a.x1 - b.x1 : a.scanY - b.scanY));\n return segs;\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Configuration\n// ---------------------------------------------------------------------------\n\n/**\n * Runs hatch drawing with the temporary hatch-specific brush style if one is active,\n * then restores the outer stroke state.\n *\n * @param {() => void} drawFn\n */\nfunction withHatchStyle(drawFn) {\n const save = BrushState();\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n drawFn();\n BrushSetState(save);\n}\n\n/**\n * Resolves the active hatch parameters and precomputes the ordered scanline segments.\n *\n * @param {Polygon|Polygon[]} polygons\n * @returns {{dist:number, options:Object, segs:Object[]}}\n */\nfunction getActiveHatchConfig(polygons) {\n const dist = State.hatch.dist;\n const angle = ((State.hatch.angle % 180) + 180) % 180;\n const options = State.hatch.options;\n const gradient = options.gradient ? map(options.gradient, 0, 1, 1, 1.1, true) : 1;\n const segs = getHatchSegments(polygons, dist, angle, gradient);\n return { dist, options, segs };\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Lines\n// ---------------------------------------------------------------------------\n\n/**\n * Expands ordered hatch segments into the actual line list that will be drawn.\n *\n * This includes endpoint jitter when `rand` is active and inserts the serpentine\n * connector lines when `continuous` is enabled.\n *\n * @param {Polygon|Polygon[]} polygons\n * @returns {{x1:number, y1:number, x2:number, y2:number, scanY:number, isConnector:boolean}[]}\n */\nexport function getHatchLines(polygons) {\n const { dist, options, segs } = getActiveHatchConfig(polygons);\n const r = options.rand || 0;\n const lines = [];\n\n for (let j = 0; j < segs.length; j++) {\n const s = segs[j];\n let x1 = s.x1, y1 = s.y1, x2 = s.x2, y2 = s.y2;\n if (r) {\n x1 += 2 * r * dist * rr(-1, 1);\n y1 += 2 * r * dist * rr(-1, 1);\n x2 += 2 * r * dist * rr(-1, 1);\n y2 += 2 * r * dist * rr(-1, 1);\n }\n const reverse = options.continuous && j % 2 === 1;\n const line = reverse\n ? { x1: x2, y1: y2, x2: x1, y2: y1, scanY: s.scanY, isConnector: false }\n : { x1, y1, x2, y2, scanY: s.scanY, isConnector: false };\n lines.push(line);\n if (j > 0 && options.continuous) {\n const prev = lines[lines.length - 2];\n lines.push({\n x1: prev.x2,\n y1: prev.y2,\n x2: line.x1,\n y2: line.y1,\n scanY: s.scanY,\n isConnector: true,\n });\n }\n }\n\n return lines;\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Rendering\n// ---------------------------------------------------------------------------\n\n/**\n * Iterates the generated hatch lines and delegates the actual rendering of each\n * segment to the provided callback.\n *\n * @param {Polygon|Polygon[]} polygons\n * @param {(x1:number, y1:number, x2:number, y2:number, index:number, segs:Object[]) => void} drawSegment\n */\nfunction renderHatchSegments(polygons, drawSegment) {\n const segs = getHatchLines(polygons);\n withHatchStyle(() => {\n for (let j = 0; j < segs.length; j++) {\n const s = segs[j];\n drawSegment(s.x1, s.y1, s.x2, s.y2, j, segs);\n }\n });\n}\n\n/**\n * Draws classic hatch lines over one polygon or an array of polygons.\n *\n * @param {Polygon|Polygon[]} polygons\n */\nexport function createHatch(polygons) {\n renderHatchSegments(polygons, (x1, y1, x2, y2) => {\n line(x1, y1, x2, y2);\n });\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Applies the currently active hatch modifier to a polygon, or temporarily\n * overrides hatch parameters for this call only.\n *\n * @param {number|false} [_dist=false]\n * @param {number} [_angle]\n * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [_options]\n */\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (State.hatch.isActive) createHatch(this);\n HatchSetState(state);\n};\n\n/**\n * Converts the plot to a polygon and applies the currently active hatch modifier.\n *\n * @param {number} x\n * @param {number} y\n * @param {number} scale\n */\nPlot.prototype.hatch = function (x, y, scale) {\n if (HatchState().isActive) {\n if (this.origin) (x = this.origin[0]), (y = this.origin[1]), (scale = 1);\n this.pol = this.genPol(x, y, scale, 0.3);\n this.pol.hatch();\n }\n};\n","// =============================================================================\n// Module: Mass\n// =============================================================================\n\nimport { State } from \"../core/color.js\";\nimport { arc } from \"../core/primitives.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { rr2, dist, calcAngle } from \"../core/utils.js\";\nimport { fromDegrees, usesRadians } from \"../core/runtime.js\";\nimport { HatchState, HatchSetState, hatch, getHatchLines } from \"./hatch.js\";\nimport { BrushState, BrushSetState, getBrushParams, set } from \"../stroke/stroke.js\";\nimport { wiggle } from \"../core/flowfield.js\";\n\n// ---------------------------------------------------------------------------\n// Mass State\n// ---------------------------------------------------------------------------\n\nState.mass = {\n isActive: false,\n brush: null,\n color: null,\n options: {},\n};\n\n/**\n * Returns a shallow copy of the current mass state.\n * @returns {object}\n */\nexport function MassState() {\n return { ...State.mass };\n}\n\n/**\n * Restores a previously saved mass state.\n * @param {object} state\n */\nexport function MassSetState(state) {\n State.mass = { ...state };\n}\n\n/**\n * Enables massing mode with a brush, color, and optional configuration.\n *\n * @param {string} brush - Brush name to use for the mass pass.\n * @param {string|Color} color - Color to use for the mass pass.\n * @param {object} [options={}] - Massing options such as precision, strength, gradient, and outline.\n */\nexport function mass(brush, color, options = {}) {\n State.mass.brush = brush;\n State.mass.color = color;\n State.mass.options = options;\n State.mass.isActive = true;\n}\n\n/**\n * Disables massing mode for subsequent geometry.\n */\nexport function noMass() {\n State.mass.isActive = false;\n State.mass.brush = null;\n State.mass.color = null;\n State.mass.options = {};\n}\n\n// ---------------------------------------------------------------------------\n// Polygon Preparation\n// ---------------------------------------------------------------------------\n\n/**\n * Returns a translated copy of a polygon.\n * Used to build the secondary mass layers from an existing base polygon.\n * @param {Polygon} polygon\n * @param {number} jitterX\n * @param {number} jitterY\n * @returns {Polygon}\n */\nfunction jitterPolygon(polygon, jitterX, jitterY) {\n return new Polygon(\n polygon.vertices.map((vertex) => [vertex.x + jitterX, vertex.y + jitterY]),\n );\n}\n\n/**\n * Builds the three polygons used for a mass pass.\n * Both polygon and plot inputs use one base polygon plus two translated copies,\n * so plot-based massing only needs a single `genPol(...)` call.\n * @param {Polygon|Plot} shape\n * @param {number|false} x\n * @param {number} y\n * @param {number} scale\n * @returns {Polygon[]}\n */\nfunction getMassPolygons(shape, x, y, scale) {\n const isPolygon = x === false;\n const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;\n const basePolygon = isPolygon ? shape : shape.genPol(x, y, scale, 0.15);\n const maxJitter = Math.min(scatter * 2, 5);\n const jitters = [\n [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],\n [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],\n ];\n\n return [\n basePolygon,\n jitterPolygon(basePolygon, jitters[0][0], jitters[0][1]),\n jitterPolygon(basePolygon, jitters[1][0], jitters[1][1]),\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Angle & Bounds Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Converts degree values into the current runtime angle units.\n * @param {number} angle\n * @returns {number}\n */\nfunction getAngleConverter() {\n return usesRadians()\n ? (angle) => (angle * Math.PI) / 180\n : (angle) => angle;\n}\n\n/**\n * Computes an axis-aligned bounding box for a polygon.\n * The diagonal is used as a size reference for pivot distance.\n * @param {Polygon} polygon\n * @returns {{minX:number,minY:number,maxX:number,maxY:number,cx:number,cy:number,size:number}}\n */\nfunction getPolygonBounds(polygon) {\n const points = polygon?.a ?? [];\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n for (const [x, y] of points) {\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n return {\n minX,\n minY,\n maxX,\n maxY,\n cx: (minX + maxX) / 2,\n cy: (minY + maxY) / 2,\n size: Math.hypot(maxX - minX, maxY - minY),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Pivot Geometry\n// ---------------------------------------------------------------------------\n\n/**\n * Chooses the diagonal corner family for a whole mass gesture.\n * Positive-angle hatching uses either bottom-right or top-left; negative-angle\n * hatching uses either bottom-left or top-right.\n * @param {number} angleDeg\n * @returns {[number, number]}\n */\nfunction getPivotBias(angleDeg) {\n const normalizedAngle = ((((angleDeg + 90) % 180) + 180) % 180) - 90;\n if (normalizedAngle >= 0) {\n return rr2() < 0.5 ? [1, 1] : [-1, -1];\n } else {\n return rr2() < 0.5 ? [-1, 1] : [1, -1];\n }\n}\n\n/**\n * Places the global pivot anchor outside the polygon, along the selected bias.\n * Distance varies per layer while the bias stays fixed for the whole mass.\n * @param {Polygon} polygon\n * @param {[number, number]} bias\n * @returns {{x:number,y:number}}\n */\nfunction getPivotAnchor(polygon, bias) {\n const bounds = getPolygonBounds(polygon);\n const offset = bounds.size * rr2(0.6, 1.4);\n const [sx, sy] = bias;\n return {\n x: bounds.cx + sx * offset,\n y: bounds.cy + sy * offset,\n };\n}\n\n/**\n * Projects the global pivot anchor onto the perpendicular bisector of a line.\n * This yields a valid circle center equidistant from both endpoints.\n * @param {{x:number,y:number}} anchor\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {{x:number,y:number}|null}\n */\nfunction projectAnchorToBisector(anchor, x1, y1, x2, y2) {\n const mx = (x1 + x2) / 2;\n const my = (y1 + y2) / 2;\n const dx = x2 - x1;\n const dy = y2 - y1;\n const length = Math.hypot(dx, dy);\n if (!length) return null;\n const nx = -dy / length;\n const ny = dx / length;\n const offset = (anchor.x - mx) * nx + (anchor.y - my) * ny;\n return {\n x: mx + nx * offset,\n y: my + ny * offset,\n };\n}\n\n/**\n * Returns the shortest arc between two endpoints around a given center.\n * The returned angles are already converted into the current runtime angle units.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {[number, number]}\n */\nfunction getShortArcAngles(cx, cy, x1, y1, x2, y2, toAngleUnit) {\n let startDeg = calcAngle(cx, cy, x1, y1);\n let endDeg = calcAngle(cx, cy, x2, y2);\n const sweep = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweep > 180) [startDeg, endDeg] = [endDeg, startDeg];\n return [\n toAngleUnit(startDeg),\n toAngleUnit(endDeg),\n ];\n}\n\n/**\n * Splits a hatch line into two slightly separated segments so some gestures\n * read as interrupted rather than perfectly continuous.\n * @param {{x1:number,y1:number,x2:number,y2:number}} seg\n * @returns {Array<{x1:number,y1:number,x2:number,y2:number}>}\n */\nfunction splitSegment(seg) {\n const t = rr2(0.35, 0.65);\n const mx = seg.x1 + (seg.x2 - seg.x1) * t;\n const my = seg.y1 + (seg.y2 - seg.y1) * t;\n const dx = seg.x2 - seg.x1;\n const dy = seg.y2 - seg.y1;\n const length = Math.hypot(dx, dy) || 1;\n const gap = rr2(0.04, 0.1) * length;\n const gx = (dx / length) * gap * 0.5;\n const gy = (dy / length) * gap * 0.5;\n return [\n { x1: seg.x1, y1: seg.y1, x2: mx - gx, y2: my - gy },\n { x1: mx + gx, y1: my + gy, x2: seg.x2, y2: seg.y2 },\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Mass Rendering\n// ---------------------------------------------------------------------------\n\n/**\n * Draws one polygon of the mass as a family of arcs derived from hatch lines.\n * The same pivot bias is used across layers, while each layer gets its own\n * anchor distance from the shape.\n * @param {Polygon} polygon\n * @param {[number, number]} pivotBias\n */\nfunction drawMassArcs(polygon, pivotBias, toAngleUnit) {\n const anchor = getPivotAnchor(polygon, pivotBias);\n for (const seg of getHatchLines(polygon)) {\n const parts = !seg.isConnector && rr2() < 0.35 ? splitSegment(seg) : [seg];\n for (const part of parts) {\n const center = projectAnchorToBisector(anchor, part.x1, part.y1, part.x2, part.y2);\n if (!center) continue;\n const radius = dist(center.x, center.y, part.x1, part.y1);\n if (!radius) continue;\n const [startAngle, endAngle] = getShortArcAngles(\n center.x,\n center.y,\n part.x1,\n part.y1,\n part.x2,\n part.y2,\n toAngleUnit,\n );\n arc(center.x, center.y, radius, startAngle, endAngle);\n }\n }\n}\n\n/**\n * Configures a hatch pass and immediately reinterprets the generated lines as arcs.\n * @param {Polygon} polygon\n * @param {number} dist\n * @param {number} angle\n * @param {object} options\n * @param {[number, number]} pivotBias\n */\nfunction drawMassPass(polygon, dist, angle, options, pivotBias, toAngleUnit) {\n hatch(dist, angle, options);\n drawMassArcs(polygon, pivotBias, toAngleUnit);\n}\n\n/**\n * Creates the built-in \"massing\" effect for a polygon or plot.\n * A mass is built from up to three jittered polygon layers, each hatched and\n * then redrawn as arc gestures around a shared pivot bias.\n * @param {Polygon|Plot} shape\n * @param {number|false} x\n * @param {number} y\n * @param {number} scale\n */\nexport function createMass(shape, x, y, scale) {\n const pols = getMassPolygons(shape, x, y, scale);\n const hatchState = HatchState();\n const brushState = BrushState();\n const fieldState = { ...State.field };\n const precision = State.mass.options?.precision ?? 0.5;\n const strength = State.mass.options?.strength ?? 1;\n const gradient = State.mass.options?.gradient ?? 0.1;\n const outline = State.mass.options?.outline ?? false;\n const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;\n const hatchDist = 1.6 * rr2(scatter * 0.65, scatter * 0.85) - 0.4 * gradient;\n const baseAngle = rr2(-90, 90);\n const pivotBias = getPivotBias(baseAngle);\n const toAngleUnit = getAngleConverter();\n\n set(State.mass.brush, State.mass.color, 1);\n wiggle(2 - precision);\n if (outline) pols[0].draw();\n\n drawMassPass(\n pols[0],\n hatchDist * 0.9,\n fromDegrees(baseAngle),\n {\n gradient,\n rand: 2 - 2 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n\n if (strength > 0.33) {\n drawMassPass(\n pols[1],\n hatchDist,\n fromDegrees(baseAngle + 20 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n }\n\n if (strength > 0.66) {\n drawMassPass(\n pols[2],\n hatchDist * 0.8,\n fromDegrees(baseAngle + 15 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n }\n\n BrushSetState(brushState);\n HatchSetState(hatchState);\n State.field = { ...fieldState };\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Applies massing to polygon geometry.\n */\nPolygon.prototype.mass = function () {\n if (State.mass?.isActive) {\n createMass(this, false);\n }\n};\n\n/**\n * Applies massing to plots by generating their polygon first.\n * @param {number} x\n * @param {number} y\n * @param {number} scale\n */\nPlot.prototype.mass = function (x, y, scale) {\n if (State.mass?.isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n createMass(this, x, y, scale);\n }\n};\n","import { Mix } from \"../core/color.js\";\n\nfunction strokePadding(ctx, matrix) {\n const lineWidth = ctx.lineWidth || 0;\n if (lineWidth <= 0) return 1;\n\n return (\n 1 +\n (lineWidth * Math.max(Math.hypot(matrix.a, matrix.c), Math.hypot(matrix.b, matrix.d))) /\n 2\n );\n}\n\n// =============================================================================\n// Section: Draw shapes to Mask Buffers\n// =============================================================================\n\n/**\n * Draws a polygon to the mask using the provided vertices.\n * @param {Array<{x: number, y: number}>} vertices - Array of vertex coordinates.\n */\nexport function drawPolygon(vertices, matrix = null) {\n const ctx = Mix.ctx;\n if (!matrix) matrix = ctx.getTransform();\n // Cache the current 2D transform once so the hot loop can stay numeric and\n // avoid repeated property reads while we build bounds.\n const a = matrix.a;\n const b = matrix.b;\n const c = matrix.c;\n const d = matrix.d;\n const e = matrix.e;\n const f = matrix.f;\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n\n ctx.beginPath();\n\n // Seed both the path and the transformed bounds from the first vertex so the\n // loop below only needs to append line segments.\n const first = vertices[0];\n let tx = a * first.x + c * first.y + e;\n let ty = b * first.x + d * first.y + f;\n minX = maxX = tx;\n minY = maxY = ty;\n\n ctx.moveTo(first.x, first.y);\n\n for (let i = 1; i < vertices.length; i++) {\n const v = vertices[i];\n\n // Track the transformed bounds in canvas space while we build the path so\n // dirty-rect bookkeeping does not need a second pass over the vertices.\n tx = a * v.x + c * v.y + e;\n ty = b * v.x + d * v.y + f;\n minX = Math.min(minX, tx);\n minY = Math.min(minY, ty);\n maxX = Math.max(maxX, tx);\n maxY = Math.max(maxY, ty);\n\n ctx.lineTo(v.x, v.y);\n }\n\n ctx.closePath();\n\n // Expand by stroke width so the later composite pass copies enough pixels\n // even when the polygon border extends outside the raw vertex bounds.\n const padding = strokePadding(ctx, matrix);\n Mix.markDirtyRect(Mix.mask, {\n minX: minX - padding,\n minY: minY - padding,\n maxX: maxX + padding,\n maxY: maxY + padding,\n });\n}\n\n/**\n * Draws a circle to the mask.\n * @param {number} x - X-coordinate of the circle's center.\n * @param {number} y - Y-coordinate of the circle's center.\n * @param {number} d - Diameter of the circle.\n */\nexport function circle(x, y, d) {\n const PI2 = Math.PI * 2;\n const ctx = Mix.ctx;\n const radius = d / 2;\n\n ctx.moveTo(x + radius, y);\n ctx.arc(x, y, radius, 0, PI2);\n}\n","import * as Color from \"../core/color.js\";\nimport {\n createFramebuffer,\n create2DCanvas,\n} from \"../core/compositor_runtime.js\";\n\n// Small staging canvas used to upload only the dirty fill sub-rect into the\n// framebuffer-backed mask mirror consumed by the blend shader.\nlet FillMaskUploadCanvas = null;\nlet isFillCompositeRegistered = false;\nconst DIRTY_FILL_PADDING = 4;\n\n// =============================================================================\n// Section: Helpers\n// =============================================================================\n/**\n * Returns whether the CPU-side 2D fill mask must be recreated.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} maskWidth - Mask width in physical pixels.\n * @param {number} maskHeight - Mask height in physical pixels.\n * @returns {boolean} True when the 2D fill mask needs reallocation.\n */\nfunction needsFillMaskCanvas(Renderer, maskWidth, maskHeight) {\n return (\n !Renderer.mask ||\n Renderer.mask.width !== maskWidth ||\n Renderer.mask.height !== maskHeight\n );\n}\n\n/**\n * Returns whether the framebuffer-backed fill mask mirror must be recreated.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {boolean} True when the fill mask framebuffer needs reallocation.\n */\nfunction needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density) {\n return (\n !Renderer.fillMaskFramebuffer ||\n Renderer.fillMaskFramebuffer.width !== Cwidth ||\n Renderer.fillMaskFramebuffer.height !== Cheight ||\n (typeof Renderer.fillMaskFramebuffer.pixelDensity === \"function\" &&\n Renderer.fillMaskFramebuffer.pixelDensity() !== Density)\n );\n}\n\n// =============================================================================\n// Section: Resource Management\n// =============================================================================\n/**\n * Ensures fill compositing resources exist for the active renderer.\n *\n * Fill draws first into a CPU-side 2D mask canvas. That mask is later uploaded,\n * dirty-rect by dirty-rect, into a framebuffer-backed mirror used by the final\n * blend shader pass.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n * @returns {{mask: object, ctx: CanvasRenderingContext2D}} Fill mask resources.\n */\nexport function ensureFillCompositeResources(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n clearTarget,\n) {\n const maskWidth = Math.max(1, Math.round(Cwidth * Density));\n const maskHeight = Math.max(1, Math.round(Cheight * Density));\n\n if (needsFillMaskCanvas(Renderer, maskWidth, maskHeight)) {\n Renderer.mask = create2DCanvas(maskWidth, maskHeight);\n }\n\n if (needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.fillMaskFramebuffer?.remove) {\n Renderer.fillMaskFramebuffer.remove();\n }\n Renderer.fillMaskFramebuffer = createFramebuffer(Renderer, {\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n clearTarget(Renderer.fillMaskFramebuffer);\n }\n\n Renderer.mask.dirtyRect ??= null;\n Renderer.mask.isDrawn ??= false;\n Renderer.mask.drawingContext.imageSmoothingEnabled = false;\n return {\n mask: Renderer.mask,\n ctx: Renderer.mask.drawingContext,\n };\n}\n\n// =============================================================================\n// Section: Mask Lifecycle\n// =============================================================================\n/**\n * Clears the current fill mask and resets its bookkeeping flags.\n *\n * @param {object|null} target - Fill mask canvas or framebuffer mirror.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n */\nexport function clearFillMask(target, clearTarget) {\n if (!target) return;\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\n}\n\n// =============================================================================\n// Section: Composite Bounds\n// =============================================================================\n/**\n * Returns the fill dirty rect to composite into the main target. Fill bounds are\n * taken directly from the accumulated 2D mask dirty area plus a small padding.\n *\n * @param {object|null} target - Fill mask canvas.\n * @param {Function} _getActiveFramebuffer - Unused for fill masks.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} expandDirtyRect - Expands a rect by a constant padding.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\nexport function getFillCompositeRect(\n target,\n _getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(target.dirtyRect, DIRTY_FILL_PADDING),\n );\n}\n\n// =============================================================================\n// Section: Upload\n// =============================================================================\n/**\n * Uploads only the dirty portion of the CPU-side 2D fill mask into the\n * framebuffer-backed fill mask mirror used by the shader compositor.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {object} mask - CPU-side 2D fill mask canvas.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} dirtyRect - Dirty rect to upload.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n * @returns {object} Framebuffer-backed fill mask mirror.\n */\nexport function getFillShaderMask(\n Renderer,\n mask,\n dirtyRect,\n getFullDirtyRect,\n clearTarget,\n) {\n const target = Renderer.fillMaskFramebuffer;\n const gl = Renderer.drawingContext;\n const uploadRect = dirtyRect ?? getFullDirtyRect();\n const uploadWidth = uploadRect.maxX - uploadRect.minX;\n const uploadHeight = uploadRect.maxY - uploadRect.minY;\n\n if (\n !FillMaskUploadCanvas ||\n FillMaskUploadCanvas.width !== uploadWidth ||\n FillMaskUploadCanvas.height !== uploadHeight\n ) {\n FillMaskUploadCanvas = create2DCanvas(uploadWidth, uploadHeight);\n }\n\n const uploadContext = FillMaskUploadCanvas.drawingContext;\n uploadContext.clearRect(0, 0, uploadWidth, uploadHeight);\n uploadContext.drawImage(\n mask,\n uploadRect.minX,\n uploadRect.minY,\n uploadWidth,\n uploadHeight,\n 0,\n 0,\n uploadWidth,\n uploadHeight,\n );\n\n clearTarget(target);\n gl.bindTexture(gl.TEXTURE_2D, target.colorTexture);\n gl.texSubImage2D(\n gl.TEXTURE_2D,\n 0,\n uploadRect.minX,\n uploadRect.minY,\n gl.RGBA,\n gl.UNSIGNED_BYTE,\n FillMaskUploadCanvas,\n );\n return target;\n}\n\n// =============================================================================\n// Section: Registration\n// =============================================================================\n/**\n * Registers the fill compositor with the shared color/composite core.\n * Safe to call multiple times.\n */\nexport function initFillComposite() {\n if (isFillCompositeRegistered) return;\n Color.registerFillComposite?.({\n ensureResources: ensureFillCompositeResources,\n clearMask: clearFillMask,\n getCompositeRect: getFillCompositeRect,\n getShaderMask: getFillShaderMask,\n });\n isFillCompositeRegistered = true;\n}\n","// =============================================================================\n// Module: Fill\n// =============================================================================\n/**\n * The Fill module contains functions and classes dedicated to handling\n * the fill properties of shapes within the drawing context. It supports complex fill\n * operations with effects such as bleeding to simulate watercolor-like textures. The\n * methods provided allow for setting the fill color with opacity, controlling the\n * intensity of the bleed effect, and enabling or disabling the fill operation.\n *\n * The watercolor effect implementation is inspired by Tyler Hobbs'\n * techniques for simulating watercolor paints.\n */\n\n// Core imports\nimport { Renderer, Cwidth, Cheight, Density } from \"../core/target.js\";\nimport {\n Mix,\n State,\n} from \"../core/color.js\";\nimport { drawPolygon, circle } from \"./mask.js\";\nimport {\n constrain,\n rr,\n map,\n randInt,\n gaussian,\n rotate,\n cos,\n sin,\n _onSeed,\n} from \"../core/utils.js\";\nimport { isFieldReady } from \"../core/flowfield.js\";\nimport { createColor, getAffineMatrix } from \"../core/runtime.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\n\n// Internal module imports\nimport { initFillComposite } from \"./composite.js\";\n\ninitFillComposite(); // Register the fill composite with the core color module\n\n// =============================================================================\n// Fill State and helpers\n// =============================================================================\n\n// Vertex cap for grow() — set to 0 or false to disable\nconst GROW_MAX_VERTS = 2024;\nlet GROW_CAP;\n\n// Reusable scratch arrays for grow() — avoids 4 allocations per call (~15× per fill)\nlet _growInsX = [];\nlet _growInsY = [];\nlet _growMods = [];\nlet _growDirs = [];\n\n/**\n * Global fill state settings.\n */\nState.fill = {\n opacity: 150,\n bleed_strength: 0.07,\n texture_strength: 0.8,\n border_strength: 0.5,\n direction: \"out\",\n isActive: false,\n};\n\n// Cache the current state\nconst FillState = () => ({ ...State.fill });\nconst FillSetState = (state) => {\n State.fill = { ...state };\n};\n\n// ---------------------------------------------------------------------------\n// Fill Style Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Sets the fill color and opacity for subsequent drawing operations.\n * @param {number|string|Color} a - Either the red component, a CSS color string, or a Color object.\n * @param {number} [b] - The green component or the opacity if using grayscale.\n * @param {number} [c] - The blue component.\n * @param {number} [d] - The opacity.\n */\nexport function fill(a, b, c, d) {\n State.fill.opacity = (arguments.length < 4 ? b : d) || 150;\n State.fill.color = arguments.length < 3 ? createColor(a) : createColor(a, b, c);\n State.fill.isActive = true;\n}\n\n/**\n * Sets the bleed (watercolor) intensity and direction.\n * @param {number} _i - The bleed intensity (clamped to [0,1]).\n * @param {string} [_direction=\"out\"] - The bleeding direction.\n */\nexport function fillBleed(_i, _direction = \"out\") {\n State.fill.bleed_strength = constrain(_i, 0, 1);\n State.fill.direction = _direction;\n}\n\n/**\n * Sets the texture and border strengths for the fill.\n * @param {number} [_texture=0.4] - The texture strength (clamped to [0,1]).\n * @param {number} [_border=0.4] - The border strength (clamped to [0,1]).\n */\nexport function fillTexture(_texture = 0.4, _border = 0.4) {\n State.fill.texture_strength = constrain(_texture, 0, 1);\n State.fill.border_strength = constrain(_border, 0, 1);\n}\n\n/**\n * Disables fill for subsequent drawing operations.\n */\nexport function noFill() {\n State.fill.isActive = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fill Manager Functions\n// ---------------------------------------------------------------------------\n\nlet _polygon;\nlet _bbMinX, _bbMinY, _bbMaxX, _bbMaxY;\n\n// Pre-compute gaussians for reuse\nconst GAUSSIAN_POOL_SIZE = 512;\nconst _gaussians = [[], []]; // [a, b]\nfunction _fillGaussianPools() {\n for (let i = 0; i < GAUSSIAN_POOL_SIZE; i++) {\n _gaussians[0][i] = gaussian(0.5, 0.2);\n _gaussians[1][i] = gaussian(0, 0.02);\n }\n}\n_onSeed(_fillGaussianPools);\n\n// Helper for direction checking - extracted to reduce duplication\nfunction _isLeft(a, b, c) {\n return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) > 0.01;\n}\n\n/**\n * Calculates the centroid of a polygon from its vertices.\n * @param {Object[]} pts - Array of points with {x, y}.\n * @returns {Object} The center point {x, y}.\n */\nfunction _center(pts) {\n if (pts.length === 0) {\n return { x: 0, y: 0 };\n }\n\n if (pts.length < 8) {\n // Simple average for small polygons\n let sumX = 0, sumY = 0;\n for (const pt of pts) { sumX += pt.x; sumY += pt.y; }\n return { x: sumX / pts.length, y: sumY / pts.length };\n }\n\n // Close polygon if needed\n const v = [...pts];\n if (v[0].x !== v[v.length - 1].x || v[0].y !== v[v.length - 1].y)\n v.push(v[0]);\n\n // Calculate using shoelace formula (more efficient implementation)\n let area = 0,\n cx = 0,\n cy = 0;\n for (let i = 0; i < v.length - 1; i++) {\n const cross = v[i].x * v[i + 1].y - v[i + 1].x * v[i].y;\n area += cross;\n cx += (v[i].x + v[i + 1].x) * cross;\n cy += (v[i].y + v[i + 1].y) * cross;\n }\n\n area *= 0.5;\n return area\n ? { x: cx / (6 * area), y: cy / (6 * area) }\n : { x: v[0].x, y: v[0].y };\n}\n\n/**\n * Fills a given polygon with a watercolor effect.\n * @param {Polygon} polygon - The polygon to fill.\n */\nexport function createFill(polygon) {\n if (!State.fill.isActive || !State.fill.color) {\n throw new Error(\n \"No fill color set. Call brush.fill(color) before drawing shapes.\",\n );\n }\n _polygon = polygon;\n _bbMinX = Infinity; _bbMinY = Infinity; _bbMaxX = -Infinity; _bbMaxY = -Infinity;\n for (const [a] of polygon.sides) {\n if (a.x < _bbMinX) _bbMinX = a.x;\n if (a.x > _bbMaxX) _bbMaxX = a.x;\n if (a.y < _bbMinY) _bbMinY = a.y;\n if (a.y > _bbMaxY) _bbMaxY = a.y;\n }\n const v = [...polygon.vertices];\n const _wr = rr(0, 75);\n const fluid = ~~(v.length * 0.25 * (_wr < 5 ? 1 : _wr < 15 ? 2 : 3));\n const strength = State.fill.bleed_strength;\n const modifiers = v.map(\n (_, i) => (i > fluid ? 1 : 0.3) * rr(0.85, 1.4) * strength,\n );\n const shift = randInt(0, v.length);\n const n = v.length;\n const shifted = new Array(n);\n for (let i = 0; i < n; i++) shifted[i] = v[(i + shift) % n];\n const center = _center(shifted);\n return new FillPoly(shifted, modifiers, center, [], true).fill(\n State.fill.color,\n map(State.fill.opacity, 0, 255, 0, 1, true),\n State.fill.texture_strength,\n );\n}\n\n// ---------------------------------------------------------------------------\n// FillPolygon Class\n// ---------------------------------------------------------------------------\n\n/**\n * The FillPolygon class is used to create and manage the properties of the polygons that produces\n * the watercolor effect. It includes methods to grow (expand) the polygon and apply layers\n * of color with varying intensity and erase parts to simulate a natural watercolor bleed.\n * The implementation follows Tyler Hobbs' guide to simulating watercolor:\n * https://tylerxhobbs.com/essays/2017/a-generative-approach-to-simulating-watercolor-paints\n */\nclass FillPoly {\n /**\n * Constructs a FillPolygon.\n * @param {Object[]} _v - Vertices of the polygon.\n * @param {number[]} _m - Multipliers for the bleed effect at each vertex.\n * @param {Object} _center - The polygon's center {x, y}.\n * @param {boolean[]} dir - Array indicating bleed direction per vertex.\n * @param {boolean} isFirst - True for initial polygon.\n */\n constructor(v, m, center, dir = [], isFirst = false, sx, sy) {\n // Initialize properties\n this.v = v;\n this.m = m;\n this.dir = dir;\n this.midP = center;\n\n // Initialize size and direction for first polygon\n if (isFirst) {\n // Calculate size bounds\n let maxX = 0,\n maxY = 0;\n const rayCalc = [];\n\n for (let i = 0; i < v.length; i++) {\n // Store vertex distances to center for size calculation\n const dx = Math.abs(center.x - v[i].x);\n const dy = Math.abs(center.y - v[i].y);\n maxX = Math.max(maxX, dx);\n maxY = Math.max(maxY, dy);\n\n // Store edge info for ray calculations\n const v1 = v[i],\n v2 = v[(i + 1) % v.length];\n const side = { x: v2.x - v1.x, y: v2.y - v1.y };\n const rt = rotate(0, 0, side.x, side.y, 90);\n const mid = { x: v1.x + side.x / 2, y: v1.y + side.y / 2 };\n\n rayCalc.push({\n v1,\n v2,\n ray: {\n point1: mid,\n point2: { x: mid.x + rt.x, y: mid.y + rt.y },\n },\n });\n }\n\n // Store sizes\n this.sizeX = maxX;\n this.sizeY = maxY;\n\n // Calculate directions — inline ray-polygon intersection to avoid\n // O(n) overhead of Polygon.intersect() (cache-key string building,\n // object allocation, intersectLines wrapper) per edge.\n const polySides = _polygon.sides;\n this.dir = Array(v.length);\n for (let i = 0; i < rayCalc.length; i++) {\n const rc = rayCalc[i];\n const r1x = rc.ray.point1.x, r1y = rc.ray.point1.y;\n const r2x = rc.ray.point2.x, r2y = rc.ray.point2.y;\n const rdx = r2x - r1x, rdy = r2y - r1y;\n let count = 0;\n for (let j = 0; j < polySides.length; j++) {\n const sa = polySides[j][0], sb = polySides[j][1];\n const sdx = sb.x - sa.x, sdy = sb.y - sa.y;\n const denom = sdy * rdx - sdx * rdy;\n if (denom === 0) continue;\n const ub = (rdx * (r1y - sa.y) - rdy * (r1x - sa.x)) / denom;\n if (ub < 0 || ub > 1) continue;\n // Compute intersection point inline\n const ua = (sdx * (r1y - sa.y) - sdy * (r1x - sa.x)) / denom;\n const ix = r1x + ua * rdx;\n const iy = r1y + ua * rdy;\n // _isLeft check inline: (v2-v1) × (isect-v1) > 0.01\n if ((rc.v2.x - rc.v1.x) * (iy - rc.v1.y) - (rc.v2.y - rc.v1.y) * (ix - rc.v1.x) > 0.01) {\n count++;\n }\n }\n this.dir[i] = count % 2 === 0;\n }\n\n // Randomize center (single calculation)\n const rx = rr(-0.6, 0.6) * maxX;\n const ry = rr(-0.6, 0.6) * maxY;\n this.midP = { x: center.x + rx, y: center.y + ry };\n } else {\n this.sizeX = sx;\n this.sizeY = sy;\n }\n }\n\n /**\n * Trims vertices from the polygon based on a factor.\n * @param {number} [factor=1] - Factor determining amount of trimming.\n * @returns {Object} An object containing trimmed vertices, multipliers, and direction.\n */\n trim(f = 1) {\n // Fast path for common case\n if (f >= 1 || f < 0 || this.v.length <= 8) {\n return { v: this.v, m: this.m, dir: this.dir };\n }\n\n // Trim from middle for balance\n const n = ~~((1 - f) * this.v.length);\n const s = ~~(this.v.length / 2 - n / 2);\n\n // Copy only the kept ranges instead of cloning the full arrays and splicing.\n const keep = this.v.length - n;\n const v = new Array(keep);\n const m = new Array(keep);\n const dir = new Array(keep);\n let dst = 0;\n\n for (let i = 0; i < s; i++, dst++) {\n v[dst] = this.v[i];\n m[dst] = this.m[i];\n dir[dst] = this.dir[i];\n }\n\n for (let i = s + n; i < this.v.length; i++, dst++) {\n v[dst] = this.v[i];\n m[dst] = this.m[i];\n dir[dst] = this.dir[i];\n }\n\n\n // We want to add at least two vertices to divide the new edge that appears after trimming, at random distances along its path\n const trimStart = s;\n const trimEnd = s + n;\n const edgeStart = this.v[(trimStart - 1 + this.v.length) % this.v.length];\n const edgeEnd = this.v[trimEnd % this.v.length];\n const edgeVec = { x: edgeEnd.x - edgeStart.x, y: edgeEnd.y - edgeStart.y };\n \n // Insert two new vertices at random positions along the new edge\n const insertCount = 2;\n for (let i = 0; i < insertCount; i++) {\n const t = rr(0.25, 0.75); // Random position between 25% and 75% along the edge\n const newVertex = { x: edgeStart.x + edgeVec.x * t, y: edgeStart.y + edgeVec.y * t };\n const insertIdx = s + i;\n v.splice(insertIdx, 0, newVertex);\n m.splice(insertIdx, 0, rr(0.4, 0.7));\n dir.splice(insertIdx, 0, this.dir[trimStart % this.dir.length]);\n }\n\n return { v, m, dir };\n }\n\n /**\n * Randomly samples a fraction of vertices, keeping their order.\n * Any sampled vertex outside the original polygon is pulled inward.\n * @param {number} [ratio=0.3] - Fraction of vertices to keep.\n * @returns {FillPoly} A new FillPoly with fewer vertices, guaranteed inside the original.\n */\n scatter(ratio = 0.3) {\n const L = this.v.length;\n const keep = Math.max(3, ~~(L * ratio));\n const indices = [];\n const step = L / keep;\n for (let i = 0; i < keep; i++) {\n indices.push(~~(i * step + rr(0, step * 0.8)));\n }\n\n const sv = [],\n sm = [],\n sd = [];\n const mid = this.midP;\n const sides = _polygon.sides;\n\n for (const idx of indices) {\n const j = idx % L;\n let p = this.v[j];\n let outside = false;\n // Bounding box reject — vertex outside AABB is definitely outside polygon\n if (p.x < _bbMinX || p.x > _bbMaxX || p.y < _bbMinY || p.y > _bbMaxY) {\n outside = true;\n } else {\n let crossings = 0;\n for (const [a, b] of sides) {\n const ay = a.y,\n by = b.y;\n if ((ay > p.y) === (by > p.y)) continue;\n const t = (p.y - ay) / (by - ay);\n if (p.x < a.x + t * (b.x - a.x)) crossings++;\n }\n outside = crossings % 2 === 0;\n }\n if (outside) {\n p = {\n x: mid.x + (p.x - mid.x) * rr(0.3, 0.6),\n y: mid.y + (p.y - mid.y) * rr(0.3, 0.6),\n };\n }\n sv.push(p);\n sm.push(this.m[j]);\n sd.push(!this.dir[j]);\n }\n\n return new FillPoly(sv, sm, this.midP, sd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Returns a copy with all bleed directions flipped.\n */\n flipDirs() {\n return new FillPoly(this.v, this.m, this.midP, this.dir.map(d => !d), false, this.sizeX, this.sizeY);\n }\n\n /**\n * Grows (or shrinks) the polygon vertices to simulate watercolor spread.\n * @param {number} [growthFactor=1] - Factor controlling growth.\n * @returns {FillPoly} A new FillPoly with adjusted vertices.\n */\n grow(f = 1) {\n const { v: tr_v, m: tr_m, dir: tr_dir } = this.trim(f);\n const len = tr_v.length;\n\n const outLen = len * 2;\n if (_growInsX.length < len) { _growInsX = new Array(len); _growInsY = new Array(len); }\n if (_growMods.length < outLen) { _growMods = new Array(outLen); _growDirs = new Array(outLen); }\n const insertedX = _growInsX;\n const insertedY = _growInsY;\n const newMods = _growMods;\n const newDirs = _growDirs;\n const bleedDirDeg = State.fill.direction === \"out\" ? -90 : 90;\n\n if (_gaussians[0].length === 0) _fillGaussianPools();\n const gPool = _gaussians[0],\n gPoolLen = gPool.length;\n const g2Pool = _gaussians[1],\n g2PoolLen = g2Pool.length;\n\n let idx = 0;\n let insertedIdx = 0;\n let mod = f === 999 ? rr(0.6, 0.8) : State.fill.bleed_strength;\n\n for (let i = 0; i < len; i++) {\n const cv = tr_v[i];\n const nv = tr_v[i + 1 < len ? i + 1 : 0];\n const mi = tr_m[i];\n const di = tr_dir[i];\n\n if (f < 997) mod = mi;\n\n // If mod is smaller than 0.02, skip growing math and just insert the middle vertex\n if (mod < 0.05) {\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n insertedX[insertedIdx] = (cv.x + nv.x) / 2;\n insertedY[insertedIdx] = (cv.y + nv.y) / 2;\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n insertedIdx++;\n continue;\n }\n\n const rotDeg = (di ? bleedDirDeg : -bleedDirDeg) + rr(-1, 1) * 5;\n const c = cos(rotDeg);\n const s = sin(rotDeg);\n\n const sideX = nv.x - cv.x;\n const sideY = nv.y - cv.y;\n const dirX = c * sideX + s * sideY;\n const dirY = c * sideY - s * sideX;\n\n const d = gPool[~~(rr(0, 1) * gPoolLen)] * rr(0.65, 1.35) * mod;\n const nextMod = mi + g2Pool[~~(rr(0, 1) * g2PoolLen)];\n\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n\n insertedX[insertedIdx] = cv.x + sideX * 0.5 + dirX * d;\n insertedY[insertedIdx] = cv.y + sideY * 0.5 + dirY * d;\n newMods[idx] = nextMod;\n newDirs[idx] = di;\n idx++;\n insertedIdx++;\n }\n\n let fv,\n fm,\n fd;\n \n if (GROW_CAP && idx > GROW_CAP) {\n const step = Math.ceil(idx / GROW_CAP);\n const kept = Math.ceil(idx / step);\n fv = new Array(kept);\n fm = new Array(kept);\n fd = new Array(kept);\n let dst = 0;\n for (let j = 0; j < idx; j += step, dst++) {\n fv[dst] =\n j % 2 === 0\n ? tr_v[j >> 1]\n : { x: insertedX[j >> 1], y: insertedY[j >> 1] };\n fm[dst] = newMods[j];\n fd[dst] = newDirs[j];\n }\n } else {\n fv = new Array(idx);\n for (let j = 0; j < idx; j++) {\n fv[j] =\n j % 2 === 0\n ? tr_v[j >> 1]\n : { x: insertedX[j >> 1], y: insertedY[j >> 1] };\n }\n fm = newMods.slice(0, idx);\n fd = newDirs.slice(0, idx);\n }\n return new FillPoly(fv, fm, this.midP, fd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Fills the polygon with multiple layers to simulate a watercolor effect.\n * @param {Color|string} color - The fill color.\n * @param {number} intensity - Opacity intensity (mapped from 0 to 1).\n * @param {number} tex - Texture factor.\n */\n fill(color, intensity, tex) {\n const numLayers = 20;\n const texture = tex * 3;\n const int = 2 * intensity * (1 + tex / 2);\n\n const switchingToFill = Mix.isBrush !== false;\n Mix.isBrush = false;\n if (switchingToFill) Mix.justChanged = true;\n Mix.blend(color);\n\n const m = getAffineMatrix();\n Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * m.a,\n Density * m.b,\n Density * m.c,\n Density * m.d,\n Density * (m.x + Cwidth / 2),\n Density * (m.y + Cheight / 2),\n );\n\n const fillColorBase = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / `;\n Mix.ctx.strokeStyle = fillColorBase + (0.005 * State.fill.border_strength) + \")\";\n Mix.ctx.lineCap = \"round\";\n\n GROW_CAP = GROW_MAX_VERTS * Math.max(0.1, 2 * State.fill.bleed_strength);\n\n const fillMatrix = Mix.ctx.getTransform();\n const size = Math.max(this.sizeX, this.sizeY);\n const darker = rr(0.15, 0.7);\n let pol = this.grow();\n const sparse = this.scatter(0.1).grow().scatter(0.75).flipDirs();\n let pols;\n\n for (let i = 0; i < numLayers; i++) {\n if (i % 4 === 0) {\n pol = pol.grow();\n }\n\n if (i % 2 === 0) {\n pols = [\n pol.grow(1 - 0.0125 * i),\n pol.grow(0.7 - 0.0125 * i),\n pol.grow(0.4 - 0.0125 * i),\n ];\n }\n\n for (const p of pols) {\n const grown = p.grow(999).grow(997);\n grown.layer(i, size, int, fillColorBase, fillMatrix);\n }\n const sparseLayer = sparse.grow(999).flipDirs().grow(997);\n sparseLayer.layer(i, size, int * texture, fillColorBase, fillMatrix);\n if (i % 2 === 0) {\n const darkerLayer = pol.grow(darker).grow(999);\n darkerLayer.layer(i, size, int * 2, fillColorBase, fillMatrix);\n }\n\n if (i % 8 === 0 || i === numLayers - 1) {\n if (texture !== 0) {\n pol.erase(texture * 3, intensity);\n }\n Mix.blend(color, true);\n }\n }\n\n Mix.ctx.restore();\n }\n\n /**\n * Draws a layer of the fill polygon with stroke and fill.\n * @param {number} i - The layer index.\n */\n layer(i, size, int, colorBase, matrix = null) {\n Mix.ctx.lineWidth = map(i, 0, 24, size / 25, size / 30, true);\n\n Mix.ctx.fillStyle = colorBase + int + \"%)\";\n\n drawPolygon(this.v, matrix);\n Mix.ctx.fill();\n Mix.ctx.stroke();\n }\n\n /**\n * Erases parts of the polygon to create a natural watercolor texture.\n * @param {number} texture - Texture strength factor.\n * @param {number} intensity - Intensity value for size scaling.\n */\n erase(texture, intensity) {\n Mix.ctx.save();\n\n const numCircles = ~~(rr(80, 110) * map(texture, 0, 1, 2, 3.5));\n const halfSizeX = this.sizeX / 1.3;\n const halfSizeY = this.sizeY / 1.3;\n const minSize =\n Math.min(this.sizeX, this.sizeY) * (1.3);\n const minSizeFactor = 0.03 * minSize;\n const maxSizeFactor = 0.45 * minSize;\n const { x: midX, y: midY } = this.midP;\n\n Mix.ctx.globalCompositeOperation = \"destination-out\";\n\n const alpha =\n ((5 - map(intensity, 80, 100, 0.3, 0.7, true)) * texture) / 255;\n Mix.ctx.fillStyle = `rgb(255 0 0 / ${alpha})`;\n Mix.ctx.lineWidth = 0;\n\n for (let i = 0; i < numCircles; i++) {\n const x = midX + gaussian(0, halfSizeX);\n const y = midY + gaussian(0, halfSizeY);\n const radius = rr(minSizeFactor, maxSizeFactor);\n\n Mix.ctx.beginPath();\n circle(x, y, radius);\n if (i % 5 !== 0) {\n Mix.ctx.fill();\n }\n }\n\n Mix.ctx.globalCompositeOperation = \"source-over\";\n Mix.ctx.restore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Extend Polygon and Plot Prototypes for Fill\n// ---------------------------------------------------------------------------\n\n/**\n * Applies a fill effect to the polygon using the current fill state.\n * @param {Color|string} [_color] - The color for the fill.\n * @param {number} [_opacity] - The opacity value.\n * @param {number} [_bleed] - The bleed intensity.\n * @param {number} [_texture] - The texture strength.\n * @param {number} [_border] - The border strength.\n * @param {string} [_direction] - The bleed direction.\n */\nPolygon.prototype.fill = function (\n _color = false,\n _opacity,\n _bleed,\n _texture,\n _border,\n _direction,\n) {\n let state = FillState();\n if (_color) {\n fill(_color, _opacity);\n fillBleed(_bleed, _direction);\n fillTexture(_texture, _border);\n }\n if (state.isActive) {\n isFieldReady();\n createFill(this);\n }\n FillSetState(state);\n};\n\n/**\n * Fills a plot on the canvas by generating a polygon based on the provided coordinates.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - Scaling factor.\n */\nPlot.prototype.fill = function (x, y, scale) {\n if (FillState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n this.pol = this.genPol(\n x,\n y,\n scale,\n State.fill.bleed_strength < 0.06\n ? 0\n : map(State.fill.bleed_strength, 0, 0.6, 0.2, 0.60, true),\n );\n this.pol.fill();\n }\n};\n","\nexport default function earcut(data, holeIndices, dim = 2) {\n\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n let outerNode = linkedList(data, 0, outerLen, dim, true);\n const triangles = [];\n\n if (!outerNode || outerNode.next === outerNode.prev) return triangles;\n\n let minX, minY, invSize;\n\n if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);\n\n // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox\n if (data.length > 80 * dim) {\n minX = data[0];\n minY = data[1];\n let maxX = minX;\n let maxY = minY;\n\n for (let i = dim; i < outerLen; i += dim) {\n const x = data[i];\n const y = data[i + 1];\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n\n // minX, minY and invSize are later used to transform coords into integers for z-order calculation\n invSize = Math.max(maxX - minX, maxY - minY);\n invSize = invSize !== 0 ? 32767 / invSize : 0;\n }\n\n earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);\n\n return triangles;\n}\n\n// create a circular doubly linked list from polygon points in the specified winding order\nfunction linkedList(data, start, end, dim, clockwise) {\n let last;\n\n if (clockwise === (signedArea(data, start, end, dim) > 0)) {\n for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n } else {\n for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n }\n\n if (last && equals(last, last.next)) {\n removeNode(last);\n last = last.next;\n }\n\n return last;\n}\n\n// eliminate colinear or duplicate points\nfunction filterPoints(start, end) {\n if (!start) return start;\n if (!end) end = start;\n\n let p = start,\n again;\n do {\n again = false;\n\n if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {\n removeNode(p);\n p = end = p.prev;\n if (p === p.next) break;\n again = true;\n\n } else {\n p = p.next;\n }\n } while (again || p !== end);\n\n return end;\n}\n\n// main ear slicing loop which triangulates a polygon (given as a linked list)\nfunction earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {\n if (!ear) return;\n\n // interlink polygon nodes in z-order\n if (!pass && invSize) indexCurve(ear, minX, minY, invSize);\n\n let stop = ear;\n\n // iterate through ears, slicing them one by one\n while (ear.prev !== ear.next) {\n const prev = ear.prev;\n const next = ear.next;\n\n if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {\n triangles.push(prev.i, ear.i, next.i); // cut off the triangle\n\n removeNode(ear);\n\n // skipping the next vertex leads to less sliver triangles\n ear = next.next;\n stop = next.next;\n\n continue;\n }\n\n ear = next;\n\n // if we looped through the whole remaining polygon and can't find any more ears\n if (ear === stop) {\n // try filtering points and slicing again\n if (!pass) {\n earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);\n\n // if this didn't work, try curing all small self-intersections locally\n } else if (pass === 1) {\n ear = cureLocalIntersections(filterPoints(ear), triangles);\n earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);\n\n // as a last resort, try splitting the remaining polygon into two\n } else if (pass === 2) {\n splitEarcut(ear, triangles, dim, minX, minY, invSize);\n }\n\n break;\n }\n }\n}\n\n// check whether a polygon node forms a valid ear with adjacent nodes\nfunction isEar(ear) {\n const a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n // now make sure we don't have other points inside the potential ear\n const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox\n const x0 = Math.min(ax, bx, cx),\n y0 = Math.min(ay, by, cy),\n x1 = Math.max(ax, bx, cx),\n y1 = Math.max(ay, by, cy);\n\n let p = c.next;\n while (p !== a) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&\n area(p.prev, p, p.next) >= 0) return false;\n p = p.next;\n }\n\n return true;\n}\n\nfunction isEarHashed(ear, minX, minY, invSize) {\n const a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox\n const x0 = Math.min(ax, bx, cx),\n y0 = Math.min(ay, by, cy),\n x1 = Math.max(ax, bx, cx),\n y1 = Math.max(ay, by, cy);\n\n // z-order range for the current triangle bbox;\n const minZ = zOrder(x0, y0, minX, minY, invSize),\n maxZ = zOrder(x1, y1, minX, minY, invSize);\n\n let p = ear.prevZ,\n n = ear.nextZ;\n\n // look for points inside the triangle in both directions\n while (p && p.z >= minZ && n && n.z <= maxZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n // look for remaining points in decreasing z-order\n while (p && p.z >= minZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n }\n\n // look for remaining points in increasing z-order\n while (n && n.z <= maxZ) {\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n return true;\n}\n\n// go through all polygon nodes and cure small local self-intersections\nfunction cureLocalIntersections(start, triangles) {\n let p = start;\n do {\n const a = p.prev,\n b = p.next.next;\n\n if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {\n\n triangles.push(a.i, p.i, b.i);\n\n // remove two nodes involved\n removeNode(p);\n removeNode(p.next);\n\n p = start = b;\n }\n p = p.next;\n } while (p !== start);\n\n return filterPoints(p);\n}\n\n// try splitting polygon into two and triangulate them independently\nfunction splitEarcut(start, triangles, dim, minX, minY, invSize) {\n // look for a valid diagonal that divides the polygon into two\n let a = start;\n do {\n let b = a.next.next;\n while (b !== a.prev) {\n if (a.i !== b.i && isValidDiagonal(a, b)) {\n // split the polygon in two by the diagonal\n let c = splitPolygon(a, b);\n\n // filter colinear points around the cuts\n a = filterPoints(a, a.next);\n c = filterPoints(c, c.next);\n\n // run earcut on each half\n earcutLinked(a, triangles, dim, minX, minY, invSize, 0);\n earcutLinked(c, triangles, dim, minX, minY, invSize, 0);\n return;\n }\n b = b.next;\n }\n a = a.next;\n } while (a !== start);\n}\n\n// link every hole into the outer loop, producing a single-ring polygon without holes\nfunction eliminateHoles(data, holeIndices, outerNode, dim) {\n const queue = [];\n\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n const list = linkedList(data, start, end, dim, false);\n if (list === list.next) list.steiner = true;\n queue.push(getLeftmost(list));\n }\n\n queue.sort(compareXYSlope);\n\n // process holes from left to right\n for (let i = 0; i < queue.length; i++) {\n outerNode = eliminateHole(queue[i], outerNode);\n }\n\n return outerNode;\n}\n\nfunction compareXYSlope(a, b) {\n let result = a.x - b.x;\n // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find\n // the bridge to the outer shell is always the point that they meet at.\n if (result === 0) {\n result = a.y - b.y;\n if (result === 0) {\n const aSlope = (a.next.y - a.y) / (a.next.x - a.x);\n const bSlope = (b.next.y - b.y) / (b.next.x - b.x);\n result = aSlope - bSlope;\n }\n }\n return result;\n}\n\n// find a bridge between vertices that connects hole with an outer ring and link it\nfunction eliminateHole(hole, outerNode) {\n const bridge = findHoleBridge(hole, outerNode);\n if (!bridge) {\n return outerNode;\n }\n\n const bridgeReverse = splitPolygon(bridge, hole);\n\n // filter collinear points around the cuts\n filterPoints(bridgeReverse, bridgeReverse.next);\n return filterPoints(bridge, bridge.next);\n}\n\n// David Eberly's algorithm for finding a bridge between hole and outer polygon\nfunction findHoleBridge(hole, outerNode) {\n let p = outerNode;\n const hx = hole.x;\n const hy = hole.y;\n let qx = -Infinity;\n let m;\n\n // find a segment intersected by a ray from the hole's leftmost point to the left;\n // segment's endpoint with lesser x will be potential connection point\n // unless they intersect at a vertex, then choose the vertex\n if (equals(hole, p)) return p;\n do {\n if (equals(hole, p.next)) return p.next;\n else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {\n const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);\n if (x <= hx && x > qx) {\n qx = x;\n m = p.x < p.next.x ? p : p.next;\n if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint\n }\n }\n p = p.next;\n } while (p !== outerNode);\n\n if (!m) return null;\n\n // look for points inside the triangle of hole point, segment intersection and endpoint;\n // if there are no points found, we have a valid connection;\n // otherwise choose the point of the minimum angle with the ray as connection point\n\n const stop = m;\n const mx = m.x;\n const my = m.y;\n let tanMin = Infinity;\n\n p = m;\n\n do {\n if (hx >= p.x && p.x >= mx && hx !== p.x &&\n pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {\n\n const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential\n\n if (locallyInside(p, hole) &&\n (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {\n m = p;\n tanMin = tan;\n }\n }\n\n p = p.next;\n } while (p !== stop);\n\n return m;\n}\n\n// whether sector in vertex m contains sector in vertex p in the same coordinates\nfunction sectorContainsSector(m, p) {\n return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;\n}\n\n// interlink polygon nodes in z-order\nfunction indexCurve(start, minX, minY, invSize) {\n let p = start;\n do {\n if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);\n p.prevZ = p.prev;\n p.nextZ = p.next;\n p = p.next;\n } while (p !== start);\n\n p.prevZ.nextZ = null;\n p.prevZ = null;\n\n sortLinked(p);\n}\n\n// Simon Tatham's linked list merge sort algorithm\n// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html\nfunction sortLinked(list) {\n let numMerges;\n let inSize = 1;\n\n do {\n let p = list;\n let e;\n list = null;\n let tail = null;\n numMerges = 0;\n\n while (p) {\n numMerges++;\n let q = p;\n let pSize = 0;\n for (let i = 0; i < inSize; i++) {\n pSize++;\n q = q.nextZ;\n if (!q) break;\n }\n let qSize = inSize;\n\n while (pSize > 0 || (qSize > 0 && q)) {\n\n if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {\n e = p;\n p = p.nextZ;\n pSize--;\n } else {\n e = q;\n q = q.nextZ;\n qSize--;\n }\n\n if (tail) tail.nextZ = e;\n else list = e;\n\n e.prevZ = tail;\n tail = e;\n }\n\n p = q;\n }\n\n tail.nextZ = null;\n inSize *= 2;\n\n } while (numMerges > 1);\n\n return list;\n}\n\n// z-order of a point given coords and inverse of the longer side of data bbox\nfunction zOrder(x, y, minX, minY, invSize) {\n // coords are transformed into non-negative 15-bit integer range\n x = (x - minX) * invSize | 0;\n y = (y - minY) * invSize | 0;\n\n x = (x | (x << 8)) & 0x00FF00FF;\n x = (x | (x << 4)) & 0x0F0F0F0F;\n x = (x | (x << 2)) & 0x33333333;\n x = (x | (x << 1)) & 0x55555555;\n\n y = (y | (y << 8)) & 0x00FF00FF;\n y = (y | (y << 4)) & 0x0F0F0F0F;\n y = (y | (y << 2)) & 0x33333333;\n y = (y | (y << 1)) & 0x55555555;\n\n return x | (y << 1);\n}\n\n// find the leftmost node of a polygon ring\nfunction getLeftmost(start) {\n let p = start,\n leftmost = start;\n do {\n if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;\n p = p.next;\n } while (p !== start);\n\n return leftmost;\n}\n\n// check if a point lies within a convex triangle\nfunction pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {\n return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&\n (ax - px) * (by - py) >= (bx - px) * (ay - py) &&\n (bx - px) * (cy - py) >= (cx - px) * (by - py);\n}\n\n// check if a point lies within a convex triangle but false if its equal to the first point of the triangle\nfunction pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {\n return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);\n}\n\n// check if a diagonal between two polygon nodes is valid (lies in polygon interior)\nfunction isValidDiagonal(a, b) {\n return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges\n (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible\n (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors\n equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case\n}\n\n// signed area of a triangle\nfunction area(p, q, r) {\n return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);\n}\n\n// check if two points are equal\nfunction equals(p1, p2) {\n return p1.x === p2.x && p1.y === p2.y;\n}\n\n// check if two segments intersect\nfunction intersects(p1, q1, p2, q2) {\n const o1 = sign(area(p1, q1, p2));\n const o2 = sign(area(p1, q1, q2));\n const o3 = sign(area(p2, q2, p1));\n const o4 = sign(area(p2, q2, q1));\n\n if (o1 !== o2 && o3 !== o4) return true; // general case\n\n if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1\n if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1\n if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2\n if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2\n\n return false;\n}\n\n// for collinear points p, q, r, check if point q lies on segment pr\nfunction onSegment(p, q, r) {\n return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);\n}\n\nfunction sign(num) {\n return num > 0 ? 1 : num < 0 ? -1 : 0;\n}\n\n// check if a polygon diagonal intersects any polygon segments\nfunction intersectsPolygon(a, b) {\n let p = a;\n do {\n if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&\n intersects(p, p.next, a, b)) return true;\n p = p.next;\n } while (p !== a);\n\n return false;\n}\n\n// check if a polygon diagonal is locally inside the polygon\nfunction locallyInside(a, b) {\n return area(a.prev, a, a.next) < 0 ?\n area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :\n area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;\n}\n\n// check if the middle point of a polygon diagonal is inside the polygon\nfunction middleInside(a, b) {\n let p = a;\n let inside = false;\n const px = (a.x + b.x) / 2;\n const py = (a.y + b.y) / 2;\n do {\n if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&\n (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))\n inside = !inside;\n p = p.next;\n } while (p !== a);\n\n return inside;\n}\n\n// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;\n// if one belongs to the outer ring and another to a hole, it merges it into a single ring\nfunction splitPolygon(a, b) {\n const a2 = createNode(a.i, a.x, a.y),\n b2 = createNode(b.i, b.x, b.y),\n an = a.next,\n bp = b.prev;\n\n a.next = b;\n b.prev = a;\n\n a2.next = an;\n an.prev = a2;\n\n b2.next = a2;\n a2.prev = b2;\n\n bp.next = b2;\n b2.prev = bp;\n\n return b2;\n}\n\n// create a node and optionally link it with previous one (in a circular doubly linked list)\nfunction insertNode(i, x, y, last) {\n const p = createNode(i, x, y);\n\n if (!last) {\n p.prev = p;\n p.next = p;\n\n } else {\n p.next = last.next;\n p.prev = last;\n last.next.prev = p;\n last.next = p;\n }\n return p;\n}\n\nfunction removeNode(p) {\n p.next.prev = p.prev;\n p.prev.next = p.next;\n\n if (p.prevZ) p.prevZ.nextZ = p.nextZ;\n if (p.nextZ) p.nextZ.prevZ = p.prevZ;\n}\n\nfunction createNode(i, x, y) {\n return {\n i, // vertex index in coordinates array\n x, y, // vertex coordinates\n prev: null, // previous and next vertex nodes in a polygon ring\n next: null,\n z: 0, // z-order curve value\n prevZ: null, // previous and next nodes in z-order\n nextZ: null,\n steiner: false // indicates whether this is a steiner point\n };\n}\n\n// return a percentage difference between the polygon area and its triangulation area;\n// used to verify correctness of triangulation\nexport function deviation(data, holeIndices, dim, triangles) {\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n\n let polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));\n if (hasHoles) {\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n polygonArea -= Math.abs(signedArea(data, start, end, dim));\n }\n }\n\n let trianglesArea = 0;\n for (let i = 0; i < triangles.length; i += 3) {\n const a = triangles[i] * dim;\n const b = triangles[i + 1] * dim;\n const c = triangles[i + 2] * dim;\n trianglesArea += Math.abs(\n (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -\n (data[a] - data[b]) * (data[c + 1] - data[a + 1]));\n }\n\n return polygonArea === 0 && trianglesArea === 0 ? 0 :\n Math.abs((trianglesArea - polygonArea) / polygonArea);\n}\n\nfunction signedArea(data, start, end, dim) {\n let sum = 0;\n for (let i = start, j = end - dim; i < end; i += dim) {\n sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);\n j = i;\n }\n return sum;\n}\n\n// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts\nexport function flatten(data) {\n const vertices = [];\n const holes = [];\n const dimensions = data[0][0].length;\n let holeIndex = 0;\n let prevLen = 0;\n\n for (const ring of data) {\n for (const p of ring) {\n for (let d = 0; d < dimensions; d++) vertices.push(p[d]);\n }\n if (prevLen) {\n holeIndex += prevLen;\n holes.push(holeIndex);\n }\n prevLen = ring.length;\n }\n return {vertices, holes, dimensions};\n}\n","// =============================================================================\n// Module: Wash\n// =============================================================================\n/**\n * Minimal stateful API for the `wash()` fill modifier.\n */\n\nimport earcut from \"earcut\";\nimport { Renderer, Cwidth, Cheight, isCanvasReady } from \"../core/target.js\";\nimport { State, flushActiveComposite } from \"../core/color.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { getAffineMatrix } from \"../core/runtime.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport { createColor } from \"../core/runtime.js\";\nimport { resetDirectShaderTracking } from \"../core/renderer_runtime.js\";\n\nlet gl = null;\nlet washProgram = null;\nlet washVao = null;\nlet washBuffer = null;\nlet washProjection = null;\nlet loadedWidth = 0;\nlet loadedHeight = 0;\nlet washGpuBufferSize = 0;\n\nconst WashAttr = {};\nconst WashUniform = {};\n\nconst washVertSrc = `#version 300 es\nin vec2 a_position;\nuniform mat4 u_matrix;\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n}`;\n\nconst washFragSrc = `#version 300 es\nprecision highp float;\nuniform vec4 u_color;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(u_color.rgb * u_color.a, u_color.a);\n}`;\n\nState.wash = {\n color: null,\n opacity: 150,\n isActive: false,\n};\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Enables wash mode with a color and opacity.\n *\n * @param {number|string|Color} a - Either the red component, a CSS color string, or a Color object.\n * @param {number} [b] - The green component or the opacity if using grayscale.\n * @param {number} [c] - The blue component.\n * @param {number} [d] - The opacity.\n */\nexport function wash(a, b, c, d) {\n isCanvasReady();\n State.wash.opacity = (arguments.length < 4 ? b : d) ?? 150;\n State.wash.color = arguments.length < 3 ? createColor(a) : createColor(a, b, c);\n State.wash.isActive = true;\n}\n\n/**\n * Disables wash mode for subsequent drawing operations.\n */\nexport function noWash() {\n State.wash.isActive = false;\n}\n\n// =============================================================================\n// GL helpers\n// =============================================================================\n\n/**\n * Lazily creates the reusable program/buffer state for solid wash drawing and\n * refreshes the orthographic projection when the active target size changes.\n */\nfunction ensureWashReady() {\n const nextGl = Renderer.drawingContext;\n const sizeChanged = loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (!washProjection || sizeChanged) {\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n washProjection = new Float32Array([\n 2 / loadedWidth,\n 0,\n 0,\n 0,\n 0,\n -2 / loadedHeight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n 1,\n 0,\n 1,\n ]);\n }\n\n if (gl === nextGl && washProgram && washVao && washBuffer) return;\n\n gl = nextGl;\n washProgram = createProgram(gl, washVertSrc, washFragSrc);\n WashAttr.a_position = gl.getAttribLocation(washProgram, \"a_position\");\n WashUniform.u_matrix = gl.getUniformLocation(washProgram, \"u_matrix\");\n WashUniform.u_color = gl.getUniformLocation(washProgram, \"u_color\");\n\n washVao = gl.createVertexArray();\n gl.bindVertexArray(washVao);\n\n washBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, 0, gl.DYNAMIC_DRAW);\n washGpuBufferSize = 0;\n\n gl.enableVertexAttribArray(WashAttr.a_position);\n gl.vertexAttribPointer(WashAttr.a_position, 2, gl.FLOAT, false, 8, 0);\n\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n}\n\n/**\n * Applies the current runtime affine transform and converts the result into\n * the screen-space coordinates used by the direct GL wash pipeline.\n *\n * @param {number} x - The source x-coordinate in brush drawing space.\n * @param {number} y - The source y-coordinate in brush drawing space.\n * @returns {[number, number]} The transformed screen-space position.\n */\nfunction transformVertexToScreen(x, y) {\n const m = getAffineMatrix();\n return [\n m.a * x + m.c * y + m.x + loadedWidth / 2,\n m.b * x + m.d * y + m.y + loadedHeight / 2,\n ];\n}\n\n/**\n * Triangulates a polygon in local space and returns the transformed triangle\n * vertex buffer ready for upload to the GPU.\n *\n * @param {Polygon} polygon - The polygon to triangulate.\n * @returns {{ triangles: Float32Array, vertexCount: number }} Screen-space\n * triangle vertices plus the number of vertices to draw.\n */\nfunction buildTriangleBuffer(polygon) {\n const flat = new Float32Array(polygon.vertices.length * 2);\n for (let i = 0; i < polygon.vertices.length; i++) {\n const vertex = polygon.vertices[i];\n flat[i * 2] = vertex.x;\n flat[i * 2 + 1] = vertex.y;\n }\n\n const indices = earcut(flat);\n const triangles = new Float32Array(indices.length * 2);\n for (let i = 0; i < indices.length; i++) {\n const idx = indices[i];\n const [screenX, screenY] = transformVertexToScreen(flat[idx * 2], flat[idx * 2 + 1]);\n triangles[i * 2] = screenX;\n triangles[i * 2 + 1] = screenY;\n }\n\n return {\n triangles,\n vertexCount: indices.length,\n };\n}\n\n/**\n * Draws a triangulated solid wash directly to the current GL target.\n *\n * @param {Polygon} polygon - The polygon to fill with the current wash state.\n */\nfunction drawWashPolygon(polygon) {\n if (!State.wash?.isActive || !State.wash.color || polygon.vertices.length < 3) return;\n\n flushActiveComposite();\n ensureWashReady();\n const { triangles, vertexCount } = buildTriangleBuffer(polygon);\n const byteCount = triangles.byteLength;\n gl.useProgram(washProgram);\n gl.enable(gl.BLEND);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n gl.bindVertexArray(washVao);\n gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);\n if (byteCount > washGpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, triangles, gl.DYNAMIC_DRAW);\n washGpuBufferSize = byteCount;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, triangles);\n }\n const color = State.wash.color._array;\n gl.uniformMatrix4fv(WashUniform.u_matrix, false, washProjection);\n gl.uniform4f(\n WashUniform.u_color,\n color[0],\n color[1],\n color[2],\n State.wash.opacity / 255,\n );\n\n gl.drawArrays(gl.TRIANGLES, 0, vertexCount);\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n resetDirectShaderTracking(Renderer, gl);\n}\n\n// =============================================================================\n// Prototype methods\n// =============================================================================\n\n/**\n * Applies a direct GL wash fill to the polygon using the current wash state.\n *\n * @param {Color|string|false} [_color] - Optional override color for this call.\n * @param {number} [_opacity] - Optional override opacity for this call.\n */\nPolygon.prototype.wash = function (_color = false, _opacity) {\n const state = { ...State.wash };\n if (_color !== false) wash(_color, _opacity);\n\n if (State.wash.isActive) {\n drawWashPolygon(this);\n }\n\n State.wash = { ...state };\n};\n\n/**\n * Applies wash to a plot by first generating the plot polygon, mirroring the\n * existing fill-path behavior, and then drawing that polygon with wash.\n *\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\nPlot.prototype.wash = function (x, y, scale) {\n if (!State.wash?.isActive) return;\n if (this.origin) {\n x = this.origin[0];\n y = this.origin[1];\n scale = 1;\n }\n this.pol = this.genPol(x, y, scale, 0, -1);\n this.pol.wash();\n};\n","// =============================================================================\n// Adapter: p5 Runtime Target Resolution\n// =============================================================================\n/**\n * Owns the active renderer/instance selection used by p5.brush when running\n * on top of p5's WEBGL renderer.\n */\n\nimport {\n setTargetRuntime,\n setTargetState,\n Instance,\n Renderer,\n} from \"../../core/target.js\";\n\nlet ReadySketch = null;\nlet ActiveInstance = null;\nconst ActiveInstanceStack = [];\nlet _isReady = false;\n\n/**\n * Checks whether the given draw target is a p5.Framebuffer-like object.\n * @param {*} target - Candidate draw target.\n * @returns {boolean} True when the target behaves like a p5.Framebuffer.\n */\nexport const isFramebufferTarget = (target) =>\n !!target &&\n typeof target.begin === \"function\" &&\n typeof target.end === \"function\" &&\n !!target.renderer &&\n !!target.renderer._pInst;\n\nconst isFiniteSize = (value) =>\n typeof value === \"number\" && Number.isFinite(value) && value > 0;\n\nconst safeRead = (getter) => {\n try {\n return getter();\n } catch (_error) {\n return undefined;\n }\n};\n\nconst isReadyWebGLSketch = (candidate) =>\n !!candidate &&\n typeof candidate.pixelDensity === \"function\" &&\n typeof candidate.createFramebuffer === \"function\" &&\n isFiniteSize(safeRead(() => candidate.width)) &&\n isFiniteSize(safeRead(() => candidate.height)) &&\n safeRead(() => candidate.webglVersion) === \"webgl2\";\n\nconst getCurrentP5Instance = () => window.self?.p5?.instance ?? null;\n\nconst rememberReadySketch = (candidate) => {\n if (isReadyWebGLSketch(candidate)) ReadySketch = candidate;\n return ReadySketch;\n};\n\nconst getActiveSketchRenderer = () => {\n if (!ActiveInstance) return null;\n if (!isReadyWebGLSketch(ActiveInstance)) return null;\n return rememberReadySketch(ActiveInstance);\n};\n\n/**\n * Resolves the sketch renderer that owns the current drawing session.\n * Preference order:\n * 1. the sketch currently executing a p5 lifecycle callback\n * 2. the explicitly selected instance from brush.instance(p), if ready\n * 3. the last known-good ready sketch\n * @returns {p5|Window[\"p5\"][\"instance\"]|null} The active sketch renderer.\n */\nexport const getSketchRenderer = () =>\n getActiveSketchRenderer() ||\n rememberReadySketch(getCurrentP5Instance()) ||\n rememberReadySketch(Instance) ||\n ReadySketch;\n\n/**\n * Resolves the renderer and pixel size used by `brush.load()`.\n * @param {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional draw target.\n * @returns {{renderer: object, width: number, height: number}} Active renderer info.\n */\nconst resolveTarget = (buffer = false) => {\n const sketchRenderer = getSketchRenderer();\n\n if (!buffer) {\n if (!sketchRenderer) {\n throw new Error(\n \"p5.brush could not resolve an active WEBGL sketch. Call brush.instance(p) and brush.load() after createCanvas(..., WEBGL).\",\n );\n }\n return {\n renderer: sketchRenderer,\n width: sketchRenderer.width,\n height: sketchRenderer.height,\n };\n }\n\n if (isFramebufferTarget(buffer)) {\n const owner = buffer.renderer._pInst;\n rememberReadySketch(owner);\n\n if (sketchRenderer && owner !== sketchRenderer) {\n throw new Error(\n \"p5.brush only supports p5.Framebuffer targets created from the active sketch\",\n );\n }\n\n return {\n renderer: owner,\n width: buffer.width,\n height: buffer.height,\n };\n }\n\n return {\n renderer: buffer,\n width: buffer.width,\n height: buffer.height,\n };\n};\n\n/**\n * Returns the currently bound sketch framebuffer when drawing into one.\n * @returns {p5.Framebuffer|null} Active framebuffer or null.\n */\nexport const getActiveFramebuffer = () =>\n Renderer?._renderer?.activeFramebuffer?.() ?? null;\n\n/**\n * Loads and initializes a canvas for the drawing system.\n * @param {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional offscreen target.\n * Pass a framebuffer only while drawing inside its begin()/end() or draw() scope.\n * Framebuffers created from p5.Graphics are not supported.\n */\nexport const load = (buffer = false) => {\n const target = resolveTarget(buffer);\n setTargetState({ Renderer: target.renderer });\n rememberReadySketch(!buffer ? Renderer : getSketchRenderer());\n\n if (Renderer.webglVersion !== \"webgl2\") {\n throw new Error(\"p5.brush requires a WEBGL canvas\");\n }\n\n setTargetState({\n Cwidth: target.width,\n Cheight: target.height,\n });\n\n _isReady = true;\n};\n\n/**\n * Refreshes the stored pixel density for the active renderer.\n * @returns {number} Current renderer pixel density.\n */\nexport const syncDensity = () => {\n const density = Renderer.pixelDensity();\n setTargetState({ Density: density });\n return density;\n};\n\n/**\n * Ensures the drawing system is ready before any operation.\n */\nexport const isCanvasReady = () => {\n if (!_isReady) load();\n};\n\nexport const instance = (inst) => {\n setTargetState({ Instance: inst });\n rememberReadySketch(inst);\n};\n\nexport const activateInstance = (inst) => {\n ActiveInstanceStack.push(ActiveInstance);\n ActiveInstance = inst;\n instance(inst);\n};\n\nexport const deactivateInstance = () => {\n ActiveInstance = ActiveInstanceStack.pop() ?? null;\n};\n\nexport function initP5TargetRuntime() {\n setTargetRuntime({\n load,\n syncDensity,\n isCanvasReady,\n instance,\n activateInstance,\n deactivateInstance,\n getActiveFramebuffer,\n isFramebufferTarget,\n });\n}\n","// =============================================================================\n// Adapter: p5 Runtime Hooks\n// =============================================================================\n\nimport { setRuntime } from \"../../core/runtime.js\";\nimport { Renderer } from \"../../core/target.js\";\nimport { getSketchRenderer } from \"./target.js\";\n\nconst getP5RuntimeRenderer = () =>\n Renderer ?? getSketchRenderer?.() ?? window.self?.p5?.instance ?? null;\nconst identityMatrix = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\nconst affineMatrix = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\n\nfunction isRadians() {\n const renderer = getP5RuntimeRenderer();\n return !!renderer &&\n typeof renderer.angleMode === \"function\" &&\n renderer.angleMode() === renderer.RADIANS;\n}\n\nexport function initP5Runtime() {\n setRuntime({\n usesRadians: isRadians,\n\n fromDegrees: (angle) =>\n isRadians() ? (angle * Math.PI) / 180 : angle,\n\n createColor: (...args) => {\n const renderer = getP5RuntimeRenderer();\n if (!renderer?.color) {\n throw new Error(\"p5 runtime color creation requires an active renderer.\");\n }\n return renderer.color(...args);\n },\n\n getAffineMatrix: () => {\n const renderer = getP5RuntimeRenderer();\n const mat4 = renderer?._renderer?.uModelMatrix?.mat4;\n if (!mat4) return identityMatrix;\n\n affineMatrix.a = mat4[0];\n affineMatrix.b = mat4[1];\n affineMatrix.c = mat4[4];\n affineMatrix.d = mat4[5];\n affineMatrix.x = mat4[12];\n affineMatrix.y = mat4[13];\n return affineMatrix;\n },\n });\n}\n","// =============================================================================\n// Adapter: p5 Renderer Hooks\n// =============================================================================\n\nimport { setRendererRuntime } from \"../../core/renderer_runtime.js\";\n\nfunction getFramebufferHandle(target) {\n if (!target) return null;\n if (typeof target._framebufferToBind === \"function\") return target._framebufferToBind();\n return target.framebuffer ?? null;\n}\n\nfunction beginDirectMaskDraw(renderer, gl, target) {\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n if (hadDepthTest) gl.disable(gl.DEPTH_TEST);\n\n const previousTarget = renderer._renderer.activeFramebuffer?.() ?? null;\n if (previousTarget?._beforeEnd) previousTarget._beforeEnd();\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, getFramebufferHandle(target));\n gl.viewport(0, 0, target.width * target.density, target.height * target.density);\n\n return { hadDepthTest, previousTarget };\n}\n\nfunction endDirectMaskDraw(renderer, gl, state) {\n if (state?.hadDepthTest) gl.enable(gl.DEPTH_TEST);\n\n if (state?.previousTarget?._beforeBegin) {\n state.previousTarget._beforeBegin();\n return;\n }\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n renderer._renderer.viewport(\n renderer._renderer._origViewport.width,\n renderer._renderer._origViewport.height,\n );\n renderer._renderer._applyStencilTestIfClipping?.();\n}\n\nfunction resetP5ShaderTracking(renderer, gl) {\n const coreRenderer = renderer?._renderer;\n if (!coreRenderer) return;\n coreRenderer._curShader = null;\n coreRenderer._cachedBlendMode = null;\n coreRenderer._isBlending = null;\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n}\n\nexport function initP5RendererRuntime() {\n setRendererRuntime({\n beginDirectMaskDraw,\n endDirectMaskDraw,\n resetDirectShaderTracking: resetP5ShaderTracking,\n });\n}\n","// =============================================================================\n// Adapter: p5 Compositor Hooks\n// =============================================================================\n\nimport {\n setCompositorRuntime,\n blitDefaultFramebufferSource,\n} from \"../../core/compositor_runtime.js\";\n\nfunction clearTarget(renderer, target, isFramebufferTarget) {\n if (!target) return;\n\n if (isFramebufferTarget(target)) {\n target.draw(() => renderer.clear());\n return;\n }\n\n const ctx = target.drawingContext;\n ctx.save();\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.clearRect(0, 0, target.width, target.height);\n ctx.restore();\n}\n\nfunction ensureBlendShaderProgram(renderer, vertSrc, fragSrc) {\n if (!renderer.loaded) {\n renderer.loaded = true;\n renderer.shaderProgram ??= renderer.createShader(vertSrc, fragSrc);\n }\n return renderer.shaderProgram;\n}\n\nfunction ensureBlendSourceFramebuffer(\n renderer,\n currentFramebuffer,\n width,\n height,\n density,\n) {\n if (currentFramebuffer?.remove) currentFramebuffer.remove();\n const fb = renderer.createFramebuffer({\n width,\n height,\n density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n return fb;\n}\n\nconst createFramebuffer = (renderer, options) =>\n renderer.createFramebuffer(options);\n\nfunction runBlendShaderPass({\n renderer,\n shader,\n source,\n mask,\n color,\n isBrushMask,\n Cwidth,\n Cheight,\n dirtyRect,\n targetIsFramebuffer,\n withScissor,\n}) {\n const gl = renderer.drawingContext;\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n\n gl.disable(gl.DEPTH_TEST);\n\n renderer.push();\n renderer.translate(0, 0);\n renderer.shader(shader);\n\n shader.setUniform(\"u_source\", source);\n shader.setUniform(\"u_targetIsFramebuffer\", targetIsFramebuffer);\n shader.setUniform(\"u_isBrush\", isBrushMask);\n shader.setUniform(\"u_mask\", mask);\n shader.setUniform(\"u_color\", color);\n\n withScissor(\n gl,\n dirtyRect,\n () => {\n renderer.fill(0, 0, 0, 0);\n renderer.noStroke();\n renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);\n },\n !targetIsFramebuffer,\n );\n\n renderer.pop();\n renderer.resetShader();\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n}\n\nfunction blitSourceToFramebuffer(args) {\n if (args.isFramebufferTarget(args.sourceTarget)) {\n (args.sourceTarget.renderer ?? args.renderer)._renderer?.flushDraw?.();\n args.sourceFramebuffer.draw(() => {\n args.withScissor(\n args.renderer.drawingContext,\n args.dirtyRect,\n () => {\n args.renderer.clear();\n args.renderer.push();\n args.renderer.imageMode(args.renderer.CENTER);\n args.renderer.image(\n args.sourceTarget,\n 0,\n 0,\n args.Cwidth,\n args.Cheight,\n );\n args.renderer.pop();\n },\n false,\n );\n });\n return args.sourceFramebuffer;\n }\n\n args.renderer._renderer?.flushDraw?.();\n return blitDefaultFramebufferSource(args);\n}\n\nexport function initP5CompositorRuntime() {\n setCompositorRuntime({\n clearTarget,\n ensureBlendShaderProgram,\n ensureBlendSourceFramebuffer,\n createFramebuffer,\n runBlendShaderPass,\n blitSourceToFramebuffer,\n });\n}\n","// =============================================================================\n// Adapter: p5 Stroke Hooks\n// =============================================================================\n\nimport { Renderer, Instance } from \"../../core/target.js\";\nimport { setStrokeRuntime } from \"../../stroke/runtime.js\";\n\nconst getP5BrushFactory = () => Renderer ?? Instance ?? window.self?.p5?.instance;\n\nfunction createTipSurface(width, height) {\n const factory = getP5BrushFactory();\n if (!factory?.createGraphics) {\n throw new Error(\"p5 stroke tip creation requires an active renderer or instance.\");\n }\n return factory.createGraphics(width, height);\n}\n\nfunction loadImageTip(src, imageToWhite) {\n return new Promise((resolve, reject) => {\n const nativeImg = new window.Image();\n nativeImg.onload = () => {\n const factory = getP5BrushFactory();\n if (!factory?.createImage) {\n reject(new Error(\"p5 image tip loading requires an active renderer or instance.\"));\n return;\n }\n const p5img = factory.createImage(\n nativeImg.naturalWidth,\n nativeImg.naturalHeight,\n );\n p5img.drawingContext.drawImage(nativeImg, 0, 0);\n imageToWhite(p5img);\n resolve(p5img);\n };\n nativeImg.onerror = () =>\n reject(new Error(`Failed to load image tip: ${src}`));\n nativeImg.crossOrigin = \"anonymous\";\n nativeImg.src = src;\n });\n}\n\nexport function initP5StrokeRuntime() {\n setStrokeRuntime({\n createTipSurface,\n loadImageTip,\n });\n}\n","import { State } from \"./color.js\";\nimport { isFieldReady } from \"./flowfield.js\";\n\n// =============================================================================\n// SAVE / RESTORE\n// =============================================================================\n\n/**\n * Stack of saved brush states for push/pop operations.\n * A stack (not a single slot) is required because applyShader() internally\n * calls Renderer.push()/pop(), which fires our hook — a flat object would be\n * overwritten mid-draw and pop() would restore the wrong state.\n */\nconst _stateStack = [];\n\n/**\n * Pushes the current brush state onto the stack.\n */\nexport function push() {\n isFieldReady();\n _stateStack.push({\n fill: { ...State.fill },\n wash: State.wash ? { ...State.wash } : null,\n stroke: { ...State.stroke },\n hatch: { ...State.hatch },\n mass: State.mass ? { ...State.mass } : null,\n field: { ...State.field },\n });\n}\n\n/**\n * Pops the top brush state from the stack and restores it.\n */\nexport function pop() {\n const saved = _stateStack.pop();\n if (!saved) return;\n State.stroke = { ...saved.stroke };\n State.field = { ...saved.field };\n State.hatch = { ...saved.hatch };\n State.fill = { ...saved.fill };\n if (saved.wash) State.wash = { ...saved.wash };\n if (saved.mass) {\n State.mass = { ...saved.mass };\n } else if (State.mass) {\n State.mass = {\n ...State.mass,\n isActive: false,\n brush: null,\n color: null,\n options: {},\n };\n }\n}\n","/**\n * @fileoverview p5 entry point for p5.brush.\n */\n\nexport * from \"./index.shared.js\";\n\nimport { initP5TargetRuntime } from \"./adapters/p5/target.js\";\nimport { initP5Runtime } from \"./adapters/p5/runtime.js\";\nimport { initP5RendererRuntime } from \"./adapters/p5/renderer.js\";\nimport { initP5CompositorRuntime } from \"./adapters/p5/compositor.js\";\nimport { initP5StrokeRuntime } from \"./adapters/p5/stroke.js\";\nimport { registerP5Addon } from \"./adapters/p5/addon.js\";\n\ninitP5TargetRuntime();\ninitP5Runtime();\ninitP5RendererRuntime();\ninitP5CompositorRuntime();\ninitP5StrokeRuntime();\n\nif (typeof p5 !== \"undefined\") p5.registerAddon(registerP5Addon);\n","// =============================================================================\n// Adapter: p5 Addon Registration\n// =============================================================================\n\nimport { flushActiveComposite } from \"../../core/color.js\";\nimport {\n instance as bindInstance,\n activateInstance,\n deactivateInstance,\n} from \"../../core/target.js\";\nimport { push as brushPush, pop as brushPop } from \"../../core/save.js\";\nimport { seed as brushSeed, noiseSeed as brushNoiseSeed } from \"../../core/utils.js\";\n\n/**\n * Registers the p5 addon hooks that keep p5.brush in sync with p5's runtime.\n *\n * This stays in the p5 adapter layer so a future standalone build can provide\n * its own lifecycle integration without importing p5-specific globals.\n *\n * @param {*} _p5\n * @param {Object} fn\n * @param {Object} lifecycles\n */\nexport function registerP5Addon(_p5, fn, lifecycles) {\n lifecycles.presetup = function () {\n activateInstance(this);\n };\n\n lifecycles.predraw = function () {\n activateInstance(this);\n };\n\n lifecycles.postsetup = function () {\n bindInstance(this);\n flushActiveComposite();\n deactivateInstance();\n };\n\n lifecycles.postdraw = function () {\n bindInstance(this);\n flushActiveComposite();\n deactivateInstance();\n };\n\n const _push = fn.push;\n const _pop = fn.pop;\n const _randomSeed = fn.randomSeed;\n const _noiseSeed = fn.noiseSeed;\n\n fn.push = function () {\n _push.call(this);\n brushPush();\n };\n\n fn.pop = function () {\n _pop.call(this);\n brushPop();\n };\n\n fn.randomSeed = function (s) {\n _randomSeed.call(this, s);\n brushSeed(s);\n };\n\n fn.noiseSeed = function (s) {\n _noiseSeed.call(this, s);\n brushNoiseSeed(s);\n };\n}\n"],"names":["identityMatrix","a","b","c","d","x","y","usesRadians","fromDegrees","angle","createColor","Error","getAffineMatrix","SQRT3","Math","sqrt","F2","G2","fastFloor","floor","grad2","Float64Array","createNoise2D","random","perm","p","Uint8Array","i","tableSize","r","aux","buildPermutationTable","permGrad2x","map","v","permGrad2y","n0","n1","n2","s","j","t","x0","y0","i1","j1","x1","y1","x2","y2","ii","jj","t0","gi0","t1","gi1","t2","gi2","prng_alea","seed","opts","xg","AleaGen","prng","next","double","int32","quick","constructor","Date","n","mash","data","String","length","charCodeAt","h","this","s0","s1","s2","copy","f","rng","rng2","_seedCallbacks","_onSeed","cb","push","callback","noise","noise2","noiseSeed","rr","e","rr2","rArray","array","randInt","randInt2","gaussian","mean","stdev","u","log","cos","value","withinBounds","constrain","low","high","max","min","nAngle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","fill","NaN","sLookup","idx","isNaN","sin","toDegrees","rad","isRad","runtimeUsesRadians","toDegreesSigned","rotate","cx","cy","coseno","seno","dist","hypot","calcAngle","atan2","intersectLines","s1a","s1b","s2a","s2b","includeSegmentExtension","x3","y3","x4","y4","deltaX1","deltaY1","deltaX2","deltaY2","denominator","ua","ub","Cwidth","Cheight","Instance","Renderer","Density","targetRuntime","load","syncDensity","isCanvasReady","instance","inst","activateInstance","deactivateInstance","getActiveFramebuffer","isFramebufferTarget","setTargetState","state","target","expandDirtyRect","rect","padding","minX","minY","maxX","maxY","create2DCanvas","width","height","willReadFrequently","canvas","OffscreenCanvas","element","document","createElement","drawingContext","getContext","undefined","compositorRuntime","clearTarget","ensureBlendShaderProgram","ensureBlendSourceFramebuffer","createFramebuffer","runBlendShaderPass","blitSourceToFramebuffer","args","strokeComposite","fillComposite","clearRenderTarget","getTargetPixelSize","round","normalizeDirtyRect","ceil","clampDirtyRect","getFullDirtyRect","getFullRect","toScissorBox","flipY","normalized","withScissor","gl","draw","box","enable","SCISSOR_TEST","scissor","disable","State","isMixReady","loaded","Mix","isBlending","cachedColor","markDirtyRect","dirtyRect","isDrawn","clearMask","composite","glMask","getCompositeRect","isBrushMask","needsBlendSourceFramebuffer","blendSourceFramebuffer","pixelDensity","ensureResources","fillResources","mask","ctx","blend","_color","_isLast","isBrush","otherMask","nextColor","_array","colorChanged","justChanged","applyShader","shader","shaderProgram","activeFramebuffer","source","renderer","sourceTarget","sourceFramebuffer","targetIsFramebuffer","shaderMask","getShaderMask","color","flushActiveComposite","isLoaded","isFieldReady","resolution","left_x","top_y","num_columns","num_rows","addField","field","bs","ba","fillField","ar","abs","dif","sr","cr","_t","dir","offset","attractors","Array","from","wx","wy","att","dx","dy","w","freq","amp","_r","Position","m","mx","my","update","plotted","isActive","colIdx","rowIdx","reset","isIn","isInCanvas","skipCheck","list","get","current","wiggle","moveTo","_dir","_length","_step_length","movePos","_moveToDegrees","plotTo","_plot","_scale","precomputedAngle","_dirPlot","_step","scaleFactor","steps","fieldActive","usePlot","plotAngle","getRowIndex","y_offset","getColIndex","x_offset","col","row","Map","FIELD_ANGLE_MODES","Set","normalizeFieldAngleMode","options","angleMode","has","generateField","entry","normalizeFieldAngles","gen","keys","join","name","funct","set","fn","Polygon","pointsArray","useRawVertices","vertices","sides","arr","_intersectionCache","intersect","line","cacheKey","point1","point2","points","start","end","intersection","show","wash","mass","hatch","stroke","Plot","_type","segments","angles","pres","type","calcIndex","pol","addSegment","_a","_pres","_degrees","pop","reduce","sum","len","endPlot","pressure","_d","curving","index","map0","map1","suma","genPol","_x","_y","_side","step","numSteps","pos","pside","prevIdx","scale","arc","radius","startDeg","sweepDeg","segmentCount","segmentSweep","arcLength","startX","startY","_current","_curvature","_strokeArray","_strokeOrigin","SubPath","isClosed","curvature","vert","vertex","_createSpline","beginShape","endShape","close","PI2","pep","tep","pep2","done","p1","p2","p3","d1","d2","a1","a2","curvAdjust","dmax","temp","temp2","point3","point4","intPt","halfDist","asin","origin","strokeRuntime","createTipSurface","loadImageTip","isStrokeCompositeRegistered","createProgram","frag","src","VERTEX_SHADER","FRAGMENT_SHADER","createShader","shaderSource","compileShader","attachShader","linkProgram","rendererRuntime","beginDirectMaskDraw","endDirectMaskDraw","resetDirectShaderTracking","framebufferProjMatrix","vao","buf","program","loadedWidth","loadedHeight","brushMaskTarget","Attr","Frag","_ma","_mb","_mc","_md","_mx","_my","_halfW","_halfH","_density","circleData","INITIAL_CAPACITY","circleCount","bufferCapacity","gpuBufferSize","circleDirtyRect","imgProgram","imgVao","imgCornerBuf","imgInstanceBuf","imgAttr","imgFrag","imgGpuSize","imgData","IMG_INIT_CAP","imgCount","imgCapacity","imgDirtyRect","texCache","QUAD_CORNERS","getProjectionMatrix","beginMaskTarget","endMaskTarget","accumulateDirtyRect","currentRect","circle","diameter","alpha","newData","px","py","screenX","screenY","dScreenX","dScreenY","glDrawImages","p5img","targetState","tex","createTexture","bindTexture","TEXTURE_2D","texImage2D","RGBA","UNSIGNED_BYTE","texParameteri","TEXTURE_MIN_FILTER","LINEAR","TEXTURE_MAG_FILTER","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","useProgram","BLEND","blendFunc","ONE_MINUS_DST_ALPHA","ONE","activeTexture","TEXTURE0","uniform1i","u_tex","uniform4f","u_color","uniformMatrix4fv","u_proj","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","drawArraysInstanced","TRIANGLE_STRIP","needsStrokeMask","remove","density","antialias","depth","stencil","_Renderer","weight","opacity","DEFAULT_CUSTOM_PRESSURE_VARIATION","warp","tilt","BrushState","BrushSetState","add","params","includes","markerTip","vibration","scatter","definition","sharpness","quality","grain","min_max","curve","variation","isArray","mode","rest","range","ns","nm","ne","normalizePressure","tip","key","deleteTexture","delete","invalidateTexEntry","g","background","noSmooth","translate","noStroke","T","imageToWhite","tips","tipKey","param","colors","buffers","image","getBrushParams","brushName","pick","arguments","strokeWeight","_position","_cachedPlotAngle","initializeDrawingState","plot","snapshotMatrix","gaussians","angleScale","isPlot","isCustomPressure","cp","ct","cs","ck","noiseoffset","rendererMask","ensureBrushMaskTarget","nextGl","needsContextRefresh","forEach","getAttribLocation","getUniformLocation","createVertexArray","createBuffer","enableVertexAttribArray","a_position","vertexAttribPointer","FLOAT","a_radius","a_alpha","clear","STATIC_DRAW","a_corner","a_pos","IMG_FLOATS","vertexAttribDivisor","a_size","a_angle","isReady","switchingToBrush","overscan","maxPressure","scatterReach","tipReach","getImageTipOverscan","drawFn","drawSpray","drawMarker","drawImageTip","drawDefault","saveState","stepSize","spacing","totalSteps","pressureCount","cachedPressure","lineNoiseCount","cachedLineNoise","neededGaussians","u_matrix","drawArrays","POINTS","glDraw","restoreState","calculatePressure","lineNoise","simPressure","peakPos","halfWidth","pow","gauss","sw","iterations","rX","yRandomFactor","sqrtPart","vibrate","rx","ry","size","extraPadding","halfSize","extraRadius","base","boundsRadius","stampImage","plotCos","plotSin","perp","along","_vals","_standard_brushes","obj","prototype","_brush","_weight","loadPixels","average","pixels","updatePixels","entries","filter","k","Promise","all","then","HatchState","HatchSetState","rand","continuous","gradient","scanlineHatch","polygon","cosA","sinA","cosB","sinB","verts","rotated","Infinity","edges","eLen","Y","sort","scanY","getHatchLines","polygons","segs","poly","getHatchSegments","getActiveHatchConfig","lines","isConnector","prev","createHatch","drawSegment","save","hBrush","Object","values","withHatchStyle","renderHatchSegments","jitterPolygon","jitterX","jitterY","projectAnchorToBisector","anchor","nx","ny","getShortArcAngles","toAngleUnit","endDeg","splitSegment","seg","gap","gx","gy","drawMassArcs","pivotBias","bias","bounds","getPolygonBounds","sx","sy","getPivotAnchor","parts","part","center","startAngle","endAngle","drawMassPass","createMass","shape","pols","isPolygon","brush","basePolygon","maxJitter","jitters","getMassPolygons","hatchState","brushState","fieldState","precision","strength","outline","hatchDist","baseAngle","_dist","_angle","_options","FillMaskUploadCanvas","isFillCompositeRegistered","maskWidth","maskHeight","needsFillMaskCanvas","fillMaskFramebuffer","needsFillMaskFramebuffer","imageSmoothingEnabled","_getActiveFramebuffer","uploadRect","uploadWidth","uploadHeight","uploadContext","clearRect","drawImage","colorTexture","texSubImage2D","GROW_CAP","_growInsX","_growInsY","_growMods","_growDirs","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","_polygon","_bbMinX","_bbMinY","_bbMaxX","_bbMaxY","_gaussians","_fillGaussianPools","FillPoly","isFirst","midP","rayCalc","v1","v2","side","rt","mid","ray","sizeX","sizeY","polySides","rc","r1x","r1y","rdx","rdy","count","sa","sb","sdx","sdy","denom","ix","iy","trim","keep","dst","trimStart","trimEnd","edgeStart","edgeEnd","edgeVec","newVertex","insertIdx","splice","ratio","L","indices","sv","sm","sd","outside","crossings","ay","by","flipDirs","grow","tr_v","tr_m","tr_dir","outLen","insertedX","insertedY","newMods","newDirs","bleedDirDeg","gPool","gPoolLen","g2Pool","g2PoolLen","fv","fm","fd","insertedIdx","mod","cv","nv","mi","di","rotDeg","sideX","sideY","dirX","dirY","nextMod","kept","slice","intensity","texture","int","switchingToFill","setTransform","fillColorBase","_getRed","_getGreen","_getBlue","strokeStyle","lineCap","fillMatrix","getTransform","darker","sparse","layer","numLayers","erase","restore","colorBase","matrix","lineWidth","fillStyle","beginPath","first","tx","ty","lineTo","closePath","strokePadding","drawPolygon","numCircles","halfSizeX","halfSizeY","minSize","minSizeFactor","maxSizeFactor","midX","midY","globalCompositeOperation","filterPoints","again","steiner","equals","area","removeNode","earcutLinked","ear","triangles","dim","invSize","pass","z","zOrder","prevZ","nextZ","numMerges","inSize","tail","q","pSize","qSize","sortLinked","indexCurve","stop","isEarHashed","isEar","cureLocalIntersections","splitEarcut","ax","bx","pointInTriangleExceptFirst","minZ","maxZ","intersects","locallyInside","isValidDiagonal","splitPolygon","pointInTriangle","intersectsPolygon","inside","middleInside","q1","q2","o1","sign","o2","o3","o4","onSegment","num","createNode","b2","an","bp","insertNode","last","_opacity","_bleed","_wr","fluid","modifiers","_","shift","shifted","pts","sumX","sumY","pt","cross","_center","createFill","FillSetState","washProgram","washVao","washBuffer","washProjection","washGpuBufferSize","WashAttr","WashUniform","transformVertexToScreen","ensureWashReady","vertexCount","flat","holeIndices","outerLen","outerNode","signedArea","linkedList","earcut","buildTriangleBuffer","blendEquation","FUNC_ADD","ONE_MINUS_SRC_ALPHA","TRIANGLES","drawWashPolygon","ReadySketch","ActiveInstance","ActiveInstanceStack","_isReady","begin","_pInst","isFiniteSize","Number","isFinite","safeRead","getter","_error","isReadyWebGLSketch","candidate","webglVersion","rememberReadySketch","getSketchRenderer","window","self","p5","buffer","sketchRenderer","owner","resolveTarget","getP5RuntimeRenderer","affineMatrix","isRadians","RADIANS","hadDepthTest","isEnabled","DEPTH_TEST","previousTarget","_renderer","_beforeEnd","bindFramebuffer","FRAMEBUFFER","_framebufferToBind","framebuffer","getFramebufferHandle","viewport","_beforeBegin","_origViewport","_applyStencilTestIfClipping","resetP5ShaderTracking","coreRenderer","_curShader","_cachedBlendMode","_isBlending","vertSrc","fragSrc","currentFramebuffer","setUniform","resetShader","flushDraw","imageMode","CENTER","sourceBox","previousReadFramebuffer","getParameter","READ_FRAMEBUFFER_BINDING","previousDrawFramebuffer","DRAW_FRAMEBUFFER_BINDING","READ_FRAMEBUFFER","DRAW_FRAMEBUFFER","blitFramebuffer","COLOR_BUFFER_BIT","NEAREST","blitDefaultFramebufferSource","getP5BrushFactory","factory","createGraphics","resolve","reject","nativeImg","Image","onload","createImage","naturalWidth","naturalHeight","onerror","crossOrigin","_stateStack","hooks","mat4","uModelMatrix","initP5Runtime","initP5RendererRuntime","initP5CompositorRuntime","initP5StrokeRuntime","registerAddon","_p5","lifecycles","presetup","predraw","postsetup","bindInstance","postdraw","_push","_pop","_randomSeed","randomSeed","_noiseSeed","call","saved","brushPop","brushSeed","brushNoiseSeed","angleOffset","randomFactor","randomAngle","offsetX","offsetY","region","loadTarget","currentField","_array_points","weights","totalWeight","cumulative","rnd","parseInt"],"mappings":"6BAIA,MAAMA,EAAiB,CACrBC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,GAGE,IAAIC,EAAc,KAAM,EACpBC,EAAeC,GAAUA,EACzBC,EAAc,KACvB,MAAM,IAAIC,MAAM,yCAEPC,EAAkB,IAAMZ,ECYnC,MAAMa,EAAsB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AAe7vB,EAAa,IACjD,IAAK6vB,GAAiBA,EAActlC,OAAS,EAC3C,MAAM,IAAI/D,MACR,+EAGIga,GAAcqvB,EAAe7vB,GACnC3M,MACJ,oDR/J6By8B,IAC3B,IAAIC,EAAc,EAClB,MAAM/c,EAAU,GAGhB,IAAK,MAAMzH,KAAOukB,EAChBC,GAAeD,EAAQvkB,GACvByH,EAAQ3nB,KAAK,CAAEkgB,MAAKykB,WAAYD,IAIlC,MAAME,EAAMjlC,IAAQ+kC,EAGpB,IAAK,MAAMxkB,IAAEA,EAAGykB,WAAEA,KAAgBhd,EAChC,GAAIid,EAAMD,EACR,OAAOxiC,MAAM+d,GAAOA,EAAM2kB,SAAS3kB","x_google_ignoreList":[1,2,23]}
\ No newline at end of file
diff --git a/package-lock.json b/package-lock.json
index d5c9e3a..58208c0 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,16 +1,17 @@
{
"name": "p5.brush",
- "version": "2.0.3-beta",
+ "version": "2.1.1-beta",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "p5.brush",
- "version": "2.0.3-beta",
+ "version": "2.1.1-beta",
"license": "MIT",
"dependencies": {
"earcut": "^3.0.2",
"esm-seedrandom": "^3.0.5",
+ "p5": "^2.2",
"simplex-noise": "^4.0.3"
},
"devDependencies": {
@@ -30,7 +31,6 @@
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.28.6.tgz",
"integrity": "sha512-05WQkdpL9COIMz4LjTxGpPNCdlpyimKppYNoJ5Di5EUObifl8t4tuLuUBBZEpoLYOmfvIWrsp9fCl0HoPRVTdA==",
"license": "MIT",
- "peer": true,
"engines": {
"node": ">=6.9.0"
}
@@ -52,8 +52,7 @@
"version": "0.0.7",
"resolved": "https://registry.npmjs.org/@davepagurek/bezier-path/-/bezier-path-0.0.7.tgz",
"integrity": "sha512-CVlnCOrV1iy4Z12T756i9l4G6kF7r8uhlnb+xqDemAMmWQB+8Q0b+8VEqIiUfywgZDSiDr18Rm7pZlnA69rE8Q==",
- "license": "MIT",
- "peer": true
+ "license": "MIT"
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.21.5",
@@ -450,8 +449,7 @@
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@japont/unicode-range/-/unicode-range-1.0.0.tgz",
"integrity": "sha512-BckHvA2XdjRBVAWe2uceNuRf78lBeI28kyWEbfr/Q2pE17POkwuZ6WWY/UMv8FL9iBxhW4xfDoNLM9UVZaTeUQ==",
- "license": "MIT",
- "peer": true
+ "license": "MIT"
},
"node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13",
@@ -1098,7 +1096,6 @@
"resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.5.tgz",
"integrity": "sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw==",
"license": "MIT",
- "peer": true,
"dependencies": {
"acorn": "^8.11.0"
},
@@ -1176,7 +1173,6 @@
"resolved": "https://registry.npmjs.org/colorjs.io/-/colorjs.io-0.6.1.tgz",
"integrity": "sha512-8lyR2wHzuIykCpqHKgluGsqQi5iDm3/a2IgP2GBZrasn2sBRkE4NOGsglZxWLs/jZQoNkmA/KM/8NV16rLUdBg==",
"license": "MIT",
- "peer": true,
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/color"
@@ -1477,8 +1473,7 @@
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/gifenc/-/gifenc-1.0.3.tgz",
"integrity": "sha512-xdr6AdrfGBcfzncONUOlXMBuc5wJDtOueE3c5rdG0oNgtINLD+f2iFZltrBRZYzACRbKr+mSVU/x98zv2u3jmw==",
- "license": "MIT",
- "peer": true
+ "license": "MIT"
},
"node_modules/glsl-inject-defines": {
"version": "1.0.3",
@@ -1727,7 +1722,6 @@
"resolved": "https://registry.npmjs.org/i18next/-/i18next-19.9.2.tgz",
"integrity": "sha512-0i6cuo6ER6usEOtKajUUDj92zlG+KArFia0857xxiEHAQcUwh/RtOQocui1LPJwunSYT574Pk64aNva1kwtxZg==",
"license": "MIT",
- "peer": true,
"dependencies": {
"@babel/runtime": "^7.12.0"
}
@@ -1737,7 +1731,6 @@
"resolved": "https://registry.npmjs.org/i18next-browser-languagedetector/-/i18next-browser-languagedetector-4.3.1.tgz",
"integrity": "sha512-KIToAzf8zwWvacgnRwJp63ase26o24AuNUlfNVJ5YZAFmdGhsJpmFClxXPuk9rv1FMI4lnc8zLSqgZPEZMrW4g==",
"license": "MIT",
- "peer": true,
"dependencies": {
"@babel/runtime": "^7.5.5"
}
@@ -1798,8 +1791,7 @@
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/libtess/-/libtess-1.2.2.tgz",
"integrity": "sha512-Nps8HPeVVcsmJxUvFLKVJcCgcz+1ajPTXDVAVPs6+giOQP4AHV31uZFFkh+CKow/bkB7GbZWKmwmit7myaqDSw==",
- "license": "SGI-B-2.0",
- "peer": true
+ "license": "SGI-B-2.0"
},
"node_modules/loupe": {
"version": "3.2.1",
@@ -1885,8 +1877,7 @@
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/omggif/-/omggif-1.0.10.tgz",
"integrity": "sha512-LMJTtvgc/nugXj0Vcrrs68Mn2D1r0zf630VNtqtpI1FEO7e+O9FP4gqs9AcnBaSEeoHIPm28u6qgPR0oyEpGSw==",
- "license": "MIT",
- "peer": true
+ "license": "MIT"
},
"node_modules/once": {
"version": "1.4.0",
@@ -1903,7 +1894,6 @@
"resolved": "https://registry.npmjs.org/p5/-/p5-2.2.2.tgz",
"integrity": "sha512-zJ3NJDtvZ8rsrVik8LcMaRurbE70Dqjy4Dku6/7lOz8jMnbkBVVyimknElzRwxG/X+sqHtkQKzZulNcZtRmy0w==",
"license": "LGPL-2.1",
- "peer": true,
"dependencies": {
"@davepagurek/bezier-path": "^0.0.7",
"@japont/unicode-range": "^1.0.0",
@@ -1924,8 +1914,7 @@
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/pako/-/pako-2.1.0.tgz",
"integrity": "sha512-w+eufiZ1WuJYgPXbV/PO3NCMEc3xqylkKHzp8bxp1uW4qaSNQUkwmLLEc3kKsfz8lpV1F8Ht3U1Cm+9Srog2ug==",
- "license": "(MIT AND Zlib)",
- "peer": true
+ "license": "(MIT AND Zlib)"
},
"node_modules/path-parse": {
"version": "1.0.7",
@@ -2624,7 +2613,6 @@
"resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
"license": "MIT",
- "peer": true,
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
diff --git a/src/adapters/standalone/runtime.js b/src/adapters/standalone/runtime.js
index 5594f5f..522d247 100644
--- a/src/adapters/standalone/runtime.js
+++ b/src/adapters/standalone/runtime.js
@@ -11,7 +11,7 @@ export const DEGREES = "degrees";
export const RADIANS = "radians";
let colorContext = null;
-let currentAngleMode = DEGREES;
+let currentAngleMode = RADIANS;
const transformStack = [];
let currentTransform = {
a: 1,
diff --git a/src/core/color.js b/src/core/color.js
index 618e02e..9cfd4e4 100644
--- a/src/core/color.js
+++ b/src/core/color.js
@@ -326,7 +326,6 @@ export const Mix = {
Renderer,
mask,
dirtyRect,
- normalizeDirtyRect,
getFullDirtyRect,
clearTarget,
);
diff --git a/src/core/compositor_runtime.js b/src/core/compositor_runtime.js
index 66590bf..955fa05 100644
--- a/src/core/compositor_runtime.js
+++ b/src/core/compositor_runtime.js
@@ -60,8 +60,6 @@ export function blitDefaultFramebufferSource({
gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, sourceFramebuffer.framebuffer);
- gl.clearColor(0, 0, 0, 0);
- gl.clear(gl.COLOR_BUFFER_BIT);
gl.blitFramebuffer(
sourceBox?.x ?? 0,
sourceBox?.y ?? 0,
diff --git a/src/core/flowfield.js b/src/core/flowfield.js
index 6167975..af18f85 100644
--- a/src/core/flowfield.js
+++ b/src/core/flowfield.js
@@ -57,8 +57,10 @@ export class Position {
update(x, y) {
this.x = x;
this.y = y;
- this.colIdx = Math.round((x + this.mx - left_x) / resolution);
- this.rowIdx = Math.round((y + this.my - top_y) / resolution);
+ if (State.field.isActive) {
+ this.colIdx = Math.round((x + this.mx - left_x) / resolution);
+ this.rowIdx = Math.round((y + this.my - top_y) / resolution);
+ }
}
/**
@@ -131,11 +133,11 @@ export class Position {
* @param {number} _step_length - The length of each step.
* @param {number} _scale - The scaling factor for the plotting path.
*/
- plotTo(_plot, _length, _step_length, _scale = 1) {
- this.movePos(_plot, _length, _step_length, _scale);
+ plotTo(_plot, _length, _step_length, _scale = 1, precomputedAngle = undefined) {
+ this.movePos(_plot, _length, _step_length, _scale, precomputedAngle);
}
- movePos(_dirPlot, _length, _step, _scale = false) {
+ movePos(_dirPlot, _length, _step, _scale = false, precomputedAngle = undefined) {
const scaleFactor = _scale || 1;
if (!this.isIn()) {
this.plotted += _step / scaleFactor;
@@ -145,8 +147,10 @@ export class Position {
const fieldActive = State.field.isActive;
const usePlot = !!_scale;
for (let i = 0; i < steps; i++) {
- const angle =
- (fieldActive ? this.angle(true) : 0) - (usePlot ? _dirPlot.angle(this.plotted) : _dirPlot);
+ const plotAngle = (usePlot && precomputedAngle !== undefined && i === 0)
+ ? precomputedAngle
+ : (usePlot ? _dirPlot.angle(this.plotted) : _dirPlot);
+ const angle = (fieldActive ? this.angle(true) : 0) - plotAngle;
// Calculate new position
this.update(this.x + _step * cos(angle), this.y + _step * sin(angle));
this.plotted += _step / scaleFactor;
diff --git a/src/fill/composite.js b/src/fill/composite.js
index 04de3e9..46083da 100644
--- a/src/fill/composite.js
+++ b/src/fill/composite.js
@@ -166,13 +166,12 @@ export function getFillShaderMask(
Renderer,
mask,
dirtyRect,
- normalizeDirtyRect,
getFullDirtyRect,
clearTarget,
) {
const target = Renderer.fillMaskFramebuffer;
const gl = Renderer.drawingContext;
- const uploadRect = normalizeDirtyRect(dirtyRect) ?? getFullDirtyRect();
+ const uploadRect = dirtyRect ?? getFullDirtyRect();
const uploadWidth = uploadRect.maxX - uploadRect.minX;
const uploadHeight = uploadRect.maxY - uploadRect.minY;
diff --git a/src/fill/fill.js b/src/fill/fill.js
index f794686..3b98371 100644
--- a/src/fill/fill.js
+++ b/src/fill/fill.js
@@ -21,7 +21,6 @@ import {
import { drawPolygon, circle } from "./mask.js";
import {
constrain,
- weightedRand,
rr,
map,
randInt,
@@ -122,6 +121,7 @@ export function noFill() {
// ---------------------------------------------------------------------------
let _polygon;
+let _bbMinX, _bbMinY, _bbMaxX, _bbMaxY;
// Pre-compute gaussians for reuse
const GAUSSIAN_POOL_SIZE = 512;
@@ -151,11 +151,9 @@ function _center(pts) {
if (pts.length < 8) {
// Simple average for small polygons
- const sum = pts.reduce(
- (center, point) => ({ x: center.x + point.x, y: center.y + point.y }),
- { x: 0, y: 0 },
- );
- return { x: sum.x / pts.length, y: sum.y / pts.length };
+ let sumX = 0, sumY = 0;
+ for (const pt of pts) { sumX += pt.x; sumY += pt.y; }
+ return { x: sumX / pts.length, y: sumY / pts.length };
}
// Close polygon if needed
@@ -191,14 +189,24 @@ export function createFill(polygon) {
);
}
_polygon = polygon;
+ _bbMinX = Infinity; _bbMinY = Infinity; _bbMaxX = -Infinity; _bbMaxY = -Infinity;
+ for (const [a] of polygon.sides) {
+ if (a.x < _bbMinX) _bbMinX = a.x;
+ if (a.x > _bbMaxX) _bbMaxX = a.x;
+ if (a.y < _bbMinY) _bbMinY = a.y;
+ if (a.y > _bbMaxY) _bbMaxY = a.y;
+ }
const v = [...polygon.vertices];
- const fluid = ~~(v.length * 0.25 * weightedRand({ 1: 5, 2: 10, 3: 60 }));
+ const _wr = rr(0, 75);
+ const fluid = ~~(v.length * 0.25 * (_wr < 5 ? 1 : _wr < 15 ? 2 : 3));
const strength = State.fill.bleed_strength;
const modifiers = v.map(
(_, i) => (i > fluid ? 1 : 0.3) * rr(0.85, 1.4) * strength,
);
const shift = randInt(0, v.length);
- const shifted = [...v.slice(shift), ...v.slice(0, shift)];
+ const n = v.length;
+ const shifted = new Array(n);
+ for (let i = 0; i < n; i++) shifted[i] = v[(i + shift) % n];
const center = _center(shifted);
return new FillPoly(shifted, modifiers, center, [], true).fill(
State.fill.color,
@@ -269,15 +277,35 @@ class FillPoly {
this.sizeX = maxX;
this.sizeY = maxY;
- // Calculate directions
+ // Calculate directions — inline ray-polygon intersection to avoid
+ // O(n) overhead of Polygon.intersect() (cache-key string building,
+ // object allocation, intersectLines wrapper) per edge.
+ const polySides = _polygon.sides;
this.dir = Array(v.length);
- rayCalc.forEach((rc, i) => {
+ for (let i = 0; i < rayCalc.length; i++) {
+ const rc = rayCalc[i];
+ const r1x = rc.ray.point1.x, r1y = rc.ray.point1.y;
+ const r2x = rc.ray.point2.x, r2y = rc.ray.point2.y;
+ const rdx = r2x - r1x, rdy = r2y - r1y;
let count = 0;
- for (const isect of _polygon.intersect(rc.ray)) {
- if (_isLeft(rc.v1, rc.v2, isect)) count++;
+ for (let j = 0; j < polySides.length; j++) {
+ const sa = polySides[j][0], sb = polySides[j][1];
+ const sdx = sb.x - sa.x, sdy = sb.y - sa.y;
+ const denom = sdy * rdx - sdx * rdy;
+ if (denom === 0) continue;
+ const ub = (rdx * (r1y - sa.y) - rdy * (r1x - sa.x)) / denom;
+ if (ub < 0 || ub > 1) continue;
+ // Compute intersection point inline
+ const ua = (sdx * (r1y - sa.y) - sdy * (r1x - sa.x)) / denom;
+ const ix = r1x + ua * rdx;
+ const iy = r1y + ua * rdy;
+ // _isLeft check inline: (v2-v1) × (isect-v1) > 0.01
+ if ((rc.v2.x - rc.v1.x) * (iy - rc.v1.y) - (rc.v2.y - rc.v1.y) * (ix - rc.v1.x) > 0.01) {
+ count++;
+ }
}
this.dir[i] = count % 2 === 0;
- });
+ }
// Randomize center (single calculation)
const rx = rr(-0.6, 0.6) * maxX;
@@ -369,15 +397,22 @@ class FillPoly {
for (const idx of indices) {
const j = idx % L;
let p = this.v[j];
- let crossings = 0;
- for (const [a, b] of sides) {
- const ay = a.y,
- by = b.y;
- if ((ay > p.y) === (by > p.y)) continue;
- const t = (p.y - ay) / (by - ay);
- if (p.x < a.x + t * (b.x - a.x)) crossings++;
+ let outside = false;
+ // Bounding box reject — vertex outside AABB is definitely outside polygon
+ if (p.x < _bbMinX || p.x > _bbMaxX || p.y < _bbMinY || p.y > _bbMaxY) {
+ outside = true;
+ } else {
+ let crossings = 0;
+ for (const [a, b] of sides) {
+ const ay = a.y,
+ by = b.y;
+ if ((ay > p.y) === (by > p.y)) continue;
+ const t = (p.y - ay) / (by - ay);
+ if (p.x < a.x + t * (b.x - a.x)) crossings++;
+ }
+ outside = crossings % 2 === 0;
}
- if (crossings % 2 === 0) {
+ if (outside) {
p = {
x: mid.x + (p.x - mid.x) * rr(0.3, 0.6),
y: mid.y + (p.y - mid.y) * rr(0.3, 0.6),
@@ -532,13 +567,13 @@ class FillPoly {
Density * (m.y + Cheight / 2),
);
- Mix.ctx.strokeStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${
- 0.005 * State.fill.border_strength
- })`;
+ const fillColorBase = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / `;
+ Mix.ctx.strokeStyle = fillColorBase + (0.005 * State.fill.border_strength) + ")";
Mix.ctx.lineCap = "round";
GROW_CAP = GROW_MAX_VERTS * Math.max(0.1, 2 * State.fill.bleed_strength);
+ const fillMatrix = Mix.ctx.getTransform();
const size = Math.max(this.sizeX, this.sizeY);
const darker = rr(0.15, 0.7);
let pol = this.grow();
@@ -560,13 +595,13 @@ class FillPoly {
for (const p of pols) {
const grown = p.grow(999).grow(997);
- grown.layer(i, size, int, color);
+ grown.layer(i, size, int, fillColorBase, fillMatrix);
}
const sparseLayer = sparse.grow(999).flipDirs().grow(997);
- sparseLayer.layer(i, size, int * texture, color);
+ sparseLayer.layer(i, size, int * texture, fillColorBase, fillMatrix);
if (i % 2 === 0) {
const darkerLayer = pol.grow(darker).grow(999);
- darkerLayer.layer(i, size, int * 2, color);
+ darkerLayer.layer(i, size, int * 2, fillColorBase, fillMatrix);
}
if (i % 8 === 0 || i === numLayers - 1) {
@@ -584,12 +619,12 @@ class FillPoly {
* Draws a layer of the fill polygon with stroke and fill.
* @param {number} i - The layer index.
*/
- layer(i, size, int, color) {
+ layer(i, size, int, colorBase, matrix = null) {
Mix.ctx.lineWidth = map(i, 0, 24, size / 25, size / 30, true);
- Mix.ctx.fillStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${int}%)`;
+ Mix.ctx.fillStyle = colorBase + int + "%)";
- drawPolygon(this.v);
+ drawPolygon(this.v, matrix);
Mix.ctx.fill();
Mix.ctx.stroke();
}
diff --git a/src/fill/mask.js b/src/fill/mask.js
index d3da076..8062608 100644
--- a/src/fill/mask.js
+++ b/src/fill/mask.js
@@ -19,9 +19,9 @@ function strokePadding(ctx, matrix) {
* Draws a polygon to the mask using the provided vertices.
* @param {Array<{x: number, y: number}>} vertices - Array of vertex coordinates.
*/
-export function drawPolygon(vertices) {
+export function drawPolygon(vertices, matrix = null) {
const ctx = Mix.ctx;
- const matrix = ctx.getTransform();
+ if (!matrix) matrix = ctx.getTransform();
// Cache the current 2D transform once so the hot loop can stay numeric and
// avoid repeated property reads while we build bounds.
const a = matrix.a;
diff --git a/src/stroke/gl_draw.js b/src/stroke/gl_draw.js
index 3a38ed9..e8b20ce 100644
--- a/src/stroke/gl_draw.js
+++ b/src/stroke/gl_draw.js
@@ -404,7 +404,6 @@ export function glDrawImages(p5img, src) {
}
gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, imgCount);
- gl.flush();
gl.bindVertexArray(null);
gl.bindTexture(gl.TEXTURE_2D, null);
@@ -464,7 +463,6 @@ export function glDraw() {
gl.uniform4f(Frag.u_color, ...color);
gl.uniformMatrix4fv(Frag.u_matrix, false, getProjectionMatrix());
gl.drawArrays(gl.POINTS, 0, circleCount);
- gl.flush();
gl.bindVertexArray(null);
endMaskTarget(targetState);
diff --git a/src/stroke/stroke.js b/src/stroke/stroke.js
index c578c22..0eadbcf 100644
--- a/src/stroke/stroke.js
+++ b/src/stroke/stroke.js
@@ -316,6 +316,7 @@ export function noClip() {
// Drawing Variables and Functions
// ---------------------------------------------------------------------------
let _position, _length, _plot, _dir;
+let _cachedPlotAngle = 0;
const current = {};
/**
@@ -357,19 +358,16 @@ function draw(angleScale, isPlot) {
current.lineNoiseCount = 5;
current.cachedLineNoise = undefined;
+ const neededGaussians = totalSteps * 2;
+ while (gaussians.length < neededGaussians) {
+ gaussians.push(gaussian());
+ }
+
for (let i = 0; i < totalSteps; i++) {
- if (gaussians.length < totalSteps * 2) {
- gaussians.push(gaussian());
- }
+ if (isPlot) _cachedPlotAngle = _plot.angle(_position.plotted);
tip();
if (isPlot) {
- _position.plotTo(
- _plot,
- stepSize,
- stepSize,
- angleScale,
- i < 10 ? true : false,
- );
+ _position.plotTo(_plot, stepSize, stepSize, angleScale, _cachedPlotAngle);
} else {
_position._moveToDegrees(angleScale, stepSize, stepSize);
}
@@ -388,9 +386,10 @@ function saveState() {
// Set pressure values for the stroke
const { pressure } = param;
- current.a = pressure.type !== "custom" ? rr(-1, 1) : 0;
- current.b = pressure.type !== "custom" ? rr(1, 1.5) : 0;
- if (pressure.type !== "custom") {
+ current.isCustomPressure = pressure.type === "custom";
+ current.a = !current.isCustomPressure ? rr(-1, 1) : 0;
+ current.b = !current.isCustomPressure ? rr(1, 1.5) : 0;
+ if (!current.isCustomPressure) {
current.cp = rr(3, 3.5);
current.ct = 0;
current.cs = 1;
@@ -421,6 +420,12 @@ function saveState() {
// Set additional state values
current.alpha = calculateAlpha();
+ current.overscan = getImageTipOverscan();
+ current.drawFn =
+ current.p.type === "spray" ? drawSpray :
+ current.p.type === "marker" ? drawMarker :
+ (current.p.type === "custom" || current.p.type === "image") ? drawImageTip :
+ drawDefault;
markerTip();
}
@@ -444,21 +449,7 @@ function tip() {
const lineNoise = calculateLineNoise();
if (lineNoise > rr(1,1.02) && rr(0,1) < 0.7) return;
- switch (current.p.type) {
- case "spray":
- drawSpray(pressure * lineNoise);
- break;
- case "marker":
- drawMarker(pressure * lineNoise);
- break;
- case "custom":
- case "image":
- drawImageTip(pressure * lineNoise);
- break;
- default:
- drawDefault(pressure * lineNoise);
- break;
- }
+ current.drawFn(pressure * lineNoise);
}
/**
@@ -496,27 +487,20 @@ function calculateLineNoise() {
* @returns {number} Simulated pressure value.
*/
function simPressure() {
- const value = current.p.pressure.type === "custom"
- ? map(
- current.p.pressure.curve(
- Math.max(
- 0,
- Math.min(
- 1,
- 0.5 + ((_position.plotted / _length) - 0.5 + current.ct) * current.cs,
- ),
- ),
- ) +
- current.cp +
- current.ck * ((_position.plotted / _length) - 0.5),
- 0,
- 1,
- current.min,
- current.max,
- true,
- )
- : gauss();
- return value;
+ if (!current.isCustomPressure) return gauss();
+ const t = _position.plotted / _length;
+ return map(
+ current.p.pressure.curve(
+ Math.max(0, Math.min(1, 0.5 + (t - 0.5 + current.ct) * current.cs)),
+ ) +
+ current.cp +
+ current.ck * (t - 0.5),
+ 0,
+ 1,
+ current.min,
+ current.max,
+ true,
+ );
}
/**
@@ -564,9 +548,7 @@ function calculateAlpha() {
* @returns {number} The spacing value.
*/
function spacing() {
- const { param } = list.get(State.stroke.type) ?? {};
- if (!param) return 1;
- return param.spacing;
+ return current.p?.spacing ?? 1;
}
function getImageTipOverscan() {
@@ -636,12 +618,12 @@ function drawImageTip(pressure, alpha = current.alpha) {
const rx = vibration * rr(-1, 1);
const ry = vibration * rr(-1, 1);
const size = current.p.weight * State.stroke.weight * pressure;
- const overscan = getImageTipOverscan();
+ const overscan = current.overscan;
let angle = 0;
if (current.p.rotate === "random") {
angle = randInt(0, 360) * (Math.PI / 180);
} else if (current.p.rotate === "natural") {
- angle = ((_plot ? -_plot.angle(_position.plotted) : -_dir) + _position.angle()) * (Math.PI / 180);
+ angle = ((_plot ? -_cachedPlotAngle : -_dir) + _position.angle()) * (Math.PI / 180);
}
stampImage(
_position.x + rx,
@@ -669,7 +651,7 @@ function drawDefault(pressure, wiggle = 1) {
if (passesGate) {
let dx, dy;
if (_plot) {
- const plotAngle = _plot.angle(_position.plotted);
+ const plotAngle = _cachedPlotAngle;
const plotCos = cos(plotAngle);
const plotSin = sin(plotAngle);
const perp = vibration * rr(-1, 1);
diff --git a/test/standalone/transform_test.html b/test/standalone/transform_test.html
index 2fc9a0a..9a18de0 100644
--- a/test/standalone/transform_test.html
+++ b/test/standalone/transform_test.html
@@ -78,8 +78,7 @@
</div>
<h1>Transform Alignment <small style="font-size:0.55em;color:#8a9aa8;">standalone</small></h1>
<p>
- Red canvas2D references are drawn at the same coordinates as standalone brush marks using matching transforms,
- so they should align precisely.
+ Red canvas2D references are drawn at the same coordinates as standalone brush marks using matching transforms.
</p>
<p>
Columns cover <b>translate(+80, -40)</b>, <b>rotate(PI/5)</b>, and <b>scale(1.8)</b>. Row 1 checks strokes and row 2 checks fills.