Unlock custom brushes, natural fill effects and intuitive hatching in p5.js
Implement modular color refactor, wash and mass
acamposuribe75062528d0e4
diff --git a/README.md b/README.mdindex 9ce3357..d3a0063 100644--- a/README.md+++ b/README.md@@ -139,10 +139,12 @@ p5.brush.js provides a comprehensive API for creating complex drawings and effec| | brush.strokeWeight()| | [Configuration](#optional-configuration) | brush.load() || [Fill Operations](#fill-operations) | brush.fill() | | | || | brush.noFill() | | | brush.scaleBrushes()|-| | brush.fillBleed() | | | brush.instance() |+| | brush.wash() | | | brush.instance() |+| | brush.noWash() | | | |+| | brush.fillBleed() | | | || | brush.fillTexture() | | | |-| | | | [Classes](#exposed-classes) | brush.Polygon() |-| | | | | brush.Plot() |+| [Hatch Operations](#hatch-operations) | brush.mass() | | [Classes](#exposed-classes) | brush.Polygon() |+| | brush.noMass() | | | brush.Plot() || | | | | brush.Position() |---@@ -309,6 +311,7 @@ Functions for managing brush behaviors and properties.- `image`: Only for `"image"` type. An object with a `src` property pointing to your image file: `{ src: "./tip.jpg" }`.- `rotate`: How the tip rotates as it moves. `"none"` keeps it fixed, `"natural"` follows the stroke direction, `"random"` spins randomly.- `markerTip`: Only for `"marker"`, `"custom"`, and `"image"` types. Set to `false` to disable the extra soft tip buildup those brushes add at the start and end of each stroke. Defaults to `true`.+ - `noise`: Multiplies the subtle line-noise variation used along the stroke. `1` keeps the default behavior, `0` disables it, and higher values make the line wobble more.- **Usage**:```javascript// Image brush — use a photo as the brush tip.@@ -515,6 +518,29 @@ The Fill Management section focuses on managing fill properties for shapes, enab---+- `brush.wash(color, opacity)`+ - **Description**: Enables a fast solid fill pass for subsequent shapes. Unlike `fill()`, `wash()` does not simulate watercolor bleed or texture; it draws a direct flat color with the given opacity.+ - **Parameters**:+ - `color` (String|p5.Color): The wash color.+ - `opacity` (Number): Opacity from 0 to 255.+ - **Usage**:+ ```javascript+ brush.wash("#f7e4a0", 255);+ brush.circle(width / 2, height / 2, 180);+ brush.noWash();+ ```++---++- `brush.noWash()`+ - **Description**: Disables wash mode for subsequent geometry.+ - **Usage**:+ ```javascript+ brush.noWash();+ ```++---+- `brush.fillBleed(strength, direction)`- **Description**: Adjust the bleed intensity for the fill operation, mimicking the edge diffusion of watercolor paints.- **Parameters**:@@ -589,6 +615,38 @@ The Hatching section focuses on creating and drawing hatching patterns, which inbrush.hatchStyle("rotring", "green", 1.3);```+---++- `brush.mass(brushName, color, options)`+ - **Description**: Enables massing for subsequent shapes. Massing builds layered hand-filled value using internally generated hatch geometry and curved gestures rather than explicit watercolor fills.+ - **Parameters**:+ - `brushName` (String): Brush used for the mass strokes.+ - `color` (String|p5.Color): Color of the mass.+ - `options` (Object): Optional settings:+ - `precision`: `0` to `1`. Higher values reduce jitter and randomness.+ - `strength`: `0` to `1`. Controls how many of the three internal layers are drawn.+ - `gradient`: `0` to `1`. Passed through to hatch generation for spacing variation.+ - `outline`: `true` or `false`. If true, the first polygon is also outlined.+ - **Usage**:+ ```javascript+ brush.mass("pastel", "#4b6cb7", {+ precision: 0.55,+ strength: 0.9,+ gradient: 0.35,+ outline: true,+ });+ brush.circle(width / 2, height / 2, 180);+ ```++---++- `brush.noMass()`+ - **Description**: Disables massing for subsequent geometry.+ - **Usage**:+ ```javascript+ brush.noMass();+ ```+---In essence, the hatching system activates hatches for subsequent shapes, similarly to stroke and fill operations. However, you can also directly hatch multiple objects at once (and their intersections), if you proceed as described below.@@ -912,11 +970,11 @@ This section covers functions for initializing the drawing system and configurin- **Description**: Adjusts the global scale of all currently registered brush parameters, including weight, scatter, and spacing, based on the given scaling factor.- **Parameters**:- `scale` (Number): The scaling factor to be applied to the brush parameters.- - **Note**: This affects the brushes that already exist when you call it. If you only want the built-in brushes scaled, call it before adding custom brushes. If you add custom brushes later, call `brush.scaleBrushes()` again to scale them too.+ - **Note**: In practice, using `brush.scaleBrushes()` is usually necessary to adapt the built-in brushes to your canvas size. For a `600x600` canvas, `brush.scaleBrushes(3)` is a good starting point, but the final value should still be confirmed visually. This affects the brushes that already exist when you call it. If you only want the built-in brushes scaled, call it before adding custom brushes. If you add custom brushes later, call `brush.scaleBrushes()` again to scale them too.- **Usage**:```javascript- // Scale all standard brushes by a factor of 1.5- brush.scaleBrushes(1.5);+ // Good starting point for a 600x600 canvas+ brush.scaleBrushes(3);```Using `brush.scaleBrushes()`, you can easily adjust the size and spacing characteristics of brushes in your project, providing a convenient way to adapt to different canvas sizes or artistic styles.@@ -975,8 +1033,12 @@ Exposed Classes provide foundational elements for creating and manipulating shap- Draws the polygon on the canvas, following the current stroke state or the provided params.- `.fill(color, opacity, bleed, texture)`- Fills the polygon on the canvas, adhering to the current fill state or to the provided params.+ - `.wash(color, opacity)`+ - Washes the polygon on the canvas with the current wash() state or the provided params.- `.hatch(distance, angle, options)`- Applies hatching to the polygon on the canvas, based on the current hatch state or the provided params.+ - `.mass()`+ - Applies the current mass() state to the polygon.- **Attributes**:- `.vertices`: An array of the polygon's vertices, each vertex being an object with `x` and `y` properties.@@ -1024,11 +1086,21 @@ Exposed Classes provide foundational elements for creating and manipulating shap- Parameters:- `x` (Number): The x-coordinate to fill at.- `y` (Number): The y-coordinate to fill at.+ - `.wash(x, y)`+ - Washes the plot on the canvas with current wash() state.+ - Parameters:+ - `x` (Number): The x-coordinate to wash at.+ - `y` (Number): The y-coordinate to wash at.- `.hatch(x, y)`- Hatches the plot on the canvas with current hatch() state.- Parameters:- `x` (Number): The x-coordinate to hatch at.- `y` (Number): The y-coordinate to hatch at.+ - `.mass(x, y)`+ - Applies the current mass() state to the plot.+ - Parameters:+ - `x` (Number): The x-coordinate to mass at.+ - `y` (Number): The y-coordinate to mass at.- **Attributes**:- `.segments`: An array containing the lengths of all segments.diff --git a/dist/p5.brush.esm.js b/dist/p5.brush.esm.jsindex 62d2734..9814bad 100644--- a/dist/p5.brush.esm.js+++ b/dist/p5.brush.esm.js@@ -1,2 +1,2 @@-let t,e,r,n,i,a=null,o=null,s=null;const l=[],c=t=>!!t&&"function"==typeof t.begin&&"function"==typeof t.end&&!!t.renderer&&!!t.renderer._pInst,h=t=>"number"==typeof t&&Number.isFinite(t)&&t>0,u=t=>{try{return t()}catch(t){return}},f=t=>!!t&&"function"==typeof t.pixelDensity&&"function"==typeof t.createFramebuffer&&h(u(()=>t.width))&&h(u(()=>t.height))&&"webgl2"===u(()=>t.webglVersion),m=t=>(f(t)&&(o=t),o),d=()=>(s&&f(s)?m(s):null)||m(window.self?.p5?.instance??null)||m(r)||o,g=()=>n?._renderer?.activeFramebuffer?.()??null,p=t=>{if(!t)return;if(c(t))return void t.draw(()=>n.clear());const e=t.drawingContext;e.save(),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,t.width,t.height),e.restore()},x=()=>({width:Math.max(1,Math.round(t*i)),height:Math.max(1,Math.round(e*i))}),y=t=>{if(!t)return null;const{width:e,height:r}=x(),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}},_=()=>{const{width:t,height:e}=x();return{minX:0,minY:0,maxX:t,maxY:e}},b=(t,e=!0)=>{const r=y(t);if(!r)return null;const{height:n}=x();return{x:r.minX,y:e?n-r.maxY:r.minY,width:r.maxX-r.minX,height:r.maxY-r.minY}},v=(t,e,r,n=!0)=>{const i=b(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()},w=(r=!1)=>{const i=((t=!1)=>{const e=d();if(!t){if(!e)throw new Error("p5.brush could not resolve an active WEBGL sketch. Call brush.instance(p) and brush.load() after createCanvas(..., WEBGL).");return{renderer:e,width:e.width,height:e.height}}if(c(t)){const r=t.renderer._pInst;if(m(r),e&&r!==e)throw new Error("p5.brush only supports p5.Framebuffer targets created from the active sketch");return{renderer:r,width:t.width,height:t.height}}return{renderer:t,width:t.width,height:t.height}})(r);if(n=i.renderer,m(r?d():n),"webgl2"!==n.webglVersion)throw new Error("p5.brush requires a WEBGL canvas");t=i.width,e=i.height,R=!0,n.loaded&&k.load()};let R=!1;const A=()=>{R||w()},E={},M=t=>{r=t,m(t)},S=t=>{l.push(s),s=t,M(t)},T=()=>{s=l.pop()??null},P=()=>{n?.loaded||(A(),k.load())},k={isBlending:!1,cachedColor:new Object,markDirtyRect(t,e){const r=y(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){t&&(p(t),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:(t,e)=>t?t.dirtyRect?e&&g()?_():y(((t,e=0)=>t?{minX:t.minX-e,minY:t.minY-e,maxX:t.maxX+e,maxY:t.maxY+e}:null)(t.dirtyRect,e?2:4)):_():null,load(){i=n.pixelDensity();const r=Math.max(1,Math.round(t*i)),a=Math.max(1,Math.round(e*i)),o=!n.mask||!n.glMask||n.mask.width!==r||n.mask.height!==a||n.glMask.width!==t||n.glMask.height!==e,s=!n.blendSourceFramebuffer||n.blendSourceFramebuffer.width!==t||n.blendSourceFramebuffer.height!==e||"function"==typeof n.blendSourceFramebuffer.pixelDensity&&n.blendSourceFramebuffer.pixelDensity()!==i,l=!n.fillMaskFramebuffer||n.fillMaskFramebuffer.width!==t||n.fillMaskFramebuffer.height!==e||"function"==typeof n.fillMaskFramebuffer.pixelDensity&&n.fillMaskFramebuffer.pixelDensity()!==i;n.loaded&&!o||(n.glMask?.remove&&n.glMask.remove(),n.mask=new OffscreenCanvas(r,a),n.mask.drawingContext=n.mask.getContext("2d"),n.glMask=n.createFramebuffer({width:t,height:e,density:i,antialias:!1,depth:!1,stencil:!1}),n.loaded=!0,n.shaderProgram??=n.createShader("#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.);}")),s&&(n.blendSourceFramebuffer?.remove&&n.blendSourceFramebuffer.remove(),n.blendSourceFramebuffer=n.createFramebuffer({width:t,height:e,density:i,antialias:!1,depth:!1,stencil:!1})),l&&(n.fillMaskFramebuffer?.remove&&n.fillMaskFramebuffer.remove(),n.fillMaskFramebuffer=n.createFramebuffer({width:t,height:e,density:i,antialias:!1,depth:!1,stencil:!1}),p(n.fillMaskFramebuffer)),this.mask=n.mask,this.glMask=n.glMask,this.ctx=this.mask.drawingContext,this.mask.dirtyRect??=null,this.mask.isDrawn??=!1,this.ctx.imageSmoothingEnabled=!1,this.glMask.dirtyRect??=null,this.glMask.isDrawn??=!1},blend(t=!1,e=!1){P();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,p(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))},applyShader(r,i){if(!r?.isDrawn)return;const o=this.getCompositeRect(r,i);if(!o)return void this.clearMask(r);const s=n.drawingContext,l=n.shaderProgram,c=g(),h=I(c??n,o),u=!!c,f=s.getParameter(s.DEPTH_TEST);s.disable(s.DEPTH_TEST),n.push(),n.translate(0,0),n.shader(l),l.setUniform("u_source",h),l.setUniform("u_targetIsFramebuffer",u),l.setUniform("u_isBrush",i),i?l.setUniform("u_mask",r):l.setUniform("u_mask",((t,e=null)=>{const r=n.fillMaskFramebuffer,i=n.drawingContext,o=y(e)??_(),s=o.maxX-o.minX,l=o.maxY-o.minY;a&&a.width===s&&a.height===l||(a=new OffscreenCanvas(s,l),a.drawingContext=a.getContext("2d"));const c=a.drawingContext;return c.clearRect(0,0,s,l),c.drawImage(t,o.minX,o.minY,s,l,0,0,s,l),p(r),i.bindTexture(i.TEXTURE_2D,r.colorTexture),i.texSubImage2D(i.TEXTURE_2D,0,o.minX,o.minY,i.RGBA,i.UNSIGNED_BYTE,a),r})(r,o)),l.setUniform("u_color",this.cachedColor),v(s,o,()=>{n.fill(0,0,0,0),n.noStroke(),n.rect(-t/2,-e/2,t,e)},!u),n.pop(),n.resetShader(),f&&s.enable(s.DEPTH_TEST),this.clearMask(r)}},I=(r,i=null)=>{const a=n.blendSourceFramebuffer,o=n.drawingContext,s=c(r),{width:l,height:h}=x(),u=i?b(i):null,f=o.getParameter(o.READ_FRAMEBUFFER_BINDING),m=o.getParameter(o.DRAW_FRAMEBUFFER_BINDING);return(s?r.renderer:n._renderer)?.flushDraw?.(),s?(a.draw(()=>{v(n.drawingContext,i,()=>{n.clear(),n.push(),n.imageMode(n.CENTER),n.image(r,0,0,t,e),n.pop()},!1)}),a):(o.bindFramebuffer(o.READ_FRAMEBUFFER,null),o.bindFramebuffer(o.DRAW_FRAMEBUFFER,a.framebuffer),o.clearColor(0,0,0,0),o.clear(o.COLOR_BUFFER_BIT),o.blitFramebuffer(u?.x??0,u?.y??0,u?u.x+u.width:l,u?u.y+u.height:h,u?.x??0,u?.y??0,u?u.x+u.width:l,u?u.y+u.height:h,o.COLOR_BUFFER_BIT,o.NEAREST),o.bindFramebuffer(o.READ_FRAMEBUFFER,f),o.bindFramebuffer(o.DRAW_FRAMEBUFFER,m),a)},C=Math.sqrt(3),L=.5*(C-1),F=(3-C)/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 l=(t+i)*L,c=D(t+l),h=D(i+l),u=(c+h)*F,f=t-(c-u),m=i-(h-u);let d,g;f>m?(d=1,g=0):(d=0,g=1);const p=f-d+F,x=m-g+F,y=f-1+2*F,_=m-1+2*F,b=255&c,v=255&h;let w=.5-f*f-m*m;if(w>=0){const t=b+e[v];w*=w,a=w*w*(r[t]*f+n[t]*m)}let R=.5-p*p-x*x;if(R>=0){const t=b+d+e[v+g];R*=R,o=R*R*(r[t]*p+n[t]*x)}let A=.5-y*y-_*_;if(A>=0){const t=b+1+e[v+1];A*=A,s=A*A*(r[t]*y+n[t]*_)}return 70*(a+o+s)}}function Y(t,e){let r=new X(t),n=()=>r.next();return n.double=()=>n()+11102230246251565e-32*(2097152*n()|0),n.int32=()=>4294967296*r.next()|0,n.quick=n,n}class X{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=Y(Math.random()),O=Y(Math.random());const U=[],G=t=>U.push(t);let V=B(Y(Math.random())),W=B(Y(Math.random()));const $=(t=0,e=1)=>t+z()*(e-t),H=(t=0,e=1)=>t+O()*(e-t),j=t=>t[~~(z()*t.length)],K=(t,e)=>~~$(t,e),Z=(t,e)=>~~H(t,e),q=(t=0,e=1)=>{const r=1-z(),n=z();return Math.sqrt(-2*Math.log(r))*ot(360*n)*e+t},J=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)},Q=(t,e,r,n,i,a=!1)=>{let o=n+(t-e)/(r-e)*(i-n);return a?n<i?tt(o,n,i):tt(o,i,n):o},tt=(t,e,r)=>Math.max(Math.min(t,r),e),et=t=>(t%=360)<0?t+360:t,rt=1440,nt=2*Math.PI/rt,it=new Float32Array(rt).fill(NaN),at=new Float32Array(rt).fill(NaN),ot=t=>{const e=~~(4*et(t));let r=it[e];return isNaN(r)&&(r=Math.cos(e*nt),it[e]=r),r},st=t=>{const e=~~(4*et(t));let r=at[e];return isNaN(r)&&(r=Math.sin(e*nt),at[e]=r),r},lt=(t,e=!1)=>{if(e||n&&"function"==typeof n.angleMode&&n.angleMode()===n.RADIANS){let e=180*t/Math.PI%360;return e<0?e+360:e}return t},ct=(t,e=!1)=>e||n&&"function"==typeof n.angleMode&&n.angleMode()===n.RADIANS?180*t/Math.PI:t,ht=(t,e,r,n,i)=>{let a=ot(i),o=st(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),ft=(t,e,r,n)=>lt(Math.atan2(-(n-e),r-t),!0),mt=(t,e,r,n,i=!1)=>{let a=t.x,o=t.y,s=e.x,l=e.y,c=r.x,h=r.y,u=n.x,f=n.y;if(a===s&&o===l||c===u&&h===f)return!1;let m=s-a,d=l-o,g=u-c,p=f-h,x=p*m-g*d;if(0===x)return!1;let y=(g*(o-h)-p*(a-c))/x,_=(m*(o-h)-d*(a-c))/x;return!(!i&&(_<0||_>1))&&{x:a+y*m,y:o+y*d}},dt=()=>n._renderer.uModelMatrix.mat4[12],gt=()=>n._renderer.uModelMatrix.mat4[13],pt=()=>n._renderer.uModelMatrix.mat4[0],xt=()=>n._renderer.uModelMatrix.mat4[1],yt=()=>n._renderer.uModelMatrix.mat4[4],_t=()=>n._renderer.uModelMatrix.mat4[5];let bt=!1;function vt(){bt||(P(),Rt=.01*t,At=-.5*t,Et=-.5*e,Mt=Math.round(2*t/Rt),St=Math.round(2*e/Rt),Dt("hand",(t,e)=>{const r=H(.2,.8),n=Z(5,10);return Yt(e,(e,i)=>.5*n*st(r*i*e+Z(15,25))*.2*ot(t)+W(e,i)*n*.7)}),Dt("curved",(t,e)=>{let r=Z(-10,10);return Z(0,100)%2==0&&(r*=-1),Yt(e,(e,n)=>3*Q(W(.02*e+.03*t,.02*n+.03*t),0,1,-r,r))}),Dt("zigzag",(t,e)=>{let r=Z(-30,-15)+Math.abs(44*st(t));Z(0,100)%2==0&&(r*=-1);let n=r,i=0;for(let t=0;t<Mt;t++){for(let r=0;r<St;r++)e[t][r]=i,i+=n,n*=-1;i+=n,n*=-1}return e}),Dt("waves",(t,e)=>{const r=Z(10,15)+5*st(t),n=Z(3,6)+3*ot(t),i=Z(20,35);return Yt(e,(t,e)=>st(r*t)*i*ot(e*n)+Z(-3,3))}),Dt("seabed",(t,e)=>{const r=H(.4,.8),n=Z(18,26);return Yt(e,(e,i)=>1.1*n*st(r*i*e+Z(15,20))*ot(t))}),Dt("spiral",(t,e)=>{const r=Z(5,10),n=2*Z(0,2)-1,i=Z(65,80),a=Array.from({length:r},()=>({x:H(.1,.9)*Mt,y:H(.1,.9)*St}));return Yt(e,(t,e)=>{let r=0,o=0;for(const s of a){const a=t-s.x,l=e-s.y,c=1/(a*a+l*l+1),h=Math.atan2(l,a)*(180/Math.PI),u=n*(h+i)*Math.PI/180;r+=c*Math.cos(u),o+=c*Math.sin(u)}return Math.atan2(o,r)*(180/Math.PI)})}),Dt("columns",(t,e)=>{const r=Z(3,8),n=Z(25,45);return Yt(e,(t,e)=>st(t*r)*n)}),bt=!0)}class wt{constructor(t,e){vt(),this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=wt.getColIndex(t),this.rowIdx=wt.getRowIndex(e)}reset(){this.plotted=0}isIn(){return E.field.isActive?wt.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const r=t,n=e,i=this.x+dt(),a=this.y+gt();return i>=-.3*r&&i<=1.3*r&&a>=-.3*n&&a<=1.3*n}angle(){return this.isIn()&&E.field.isActive?Tt.get(E.field.current).field[this.colIdx][this.rowIdx]*E.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())for(let a=0;a<e/r;a++){const e=this.angle()-(n?t.angle(this.plotted):t);this.update(this.x+r*ot(e),this.y+r*st(e)),this.plotted+=r/i}else this.plotted+=r/i}static getRowIndex(t,e=1){const r=t+gt()-Et;return Math.round(r/Rt/e)}static getColIndex(t,e=1){const r=t+dt()-At;return Math.round(r/Rt/e)}static isIn(t,e){return t>=0&&e>=0&&t<Mt&&e<St}}E.field={isActive:!1,current:null,wiggle:1};let Rt,At,Et,Mt,St,Tt=new Map;const Pt=new Set(["degrees","radians"]);function kt(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!Pt.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function It(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(Mt).fill(null).map(()=>new Float32Array(St))),t.angleMode)}function Ct(t=0){if(!E.field.isActive||!E.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=Tt.get(E.field.current);e.field=It(e,t)}function Lt(t){if(E.field.wiggle||(E.field.wiggle=1),vt(),!Tt.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(Tt.keys()).join(", ")}.`);E.field.isActive=!0,E.field.current=t;const e=Tt.get(t);e.field||(e.field=It(e,0))}function Ft(){vt(),E.field.isActive=!1}function Dt(t,e,r={}){Tt.set(t,{gen:e,field:null,angleMode:kt(r)})}function Nt(){return vt(),Array.from(Tt.keys())}function Bt(t=1){Lt("hand"),E.field.wiggle=t}function Yt(t,e){for(let r=0;r<Mt;r++)for(let n=0;n<St;n++)t[r][n]=e(r,n);return t}class Xt{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=mt(t.point1,t.point2,e,n);i&&r.push(i)}return this._intersectionCache[e]=r,r}show(){E.stroke&&this.draw(),E.hatch&&this.hatch(),E.fill&&this.fill()}}class zt{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:lt(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:lt(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=lt(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)),Q(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(r,n,i=1,a){vt();const o=.5,s=[],l=Math.round(this.length/o),c=new wt(r+t/2,n+e/2);let h=0,u=0;for(let r=0;r<l;r++){c.plotTo(this,o,o);const r=this.calcIndex(c.plotted);h+=o,(h>=(0===a?5:Math.max(this.segments[r]*a*H(.7,1.3),20))||r>=u)&&c.x&&(s.push([c.x-t/2,c.y-e/2]),h=0,r>=u&&u++)}return new Xt(s)}show(t,e,r=1){E.stroke&&this.draw(t,e,r),E.hatch&&this.hatch(t,e,r),E.fill&&this.fill(t,e,r)}}function Ot(t){new Xt(t).show()}function Ut(t,e,r,n,i="corner"){"center"===i&&(t-=r/2,e-=n/2),Zt(0),qt(t,e),qt(t+r,e),qt(t+r,e+n),qt(t,e+n),Jt(!0)}function Gt(t,e,r,n=!1){const i=new zt("curve"),a=Math.PI*r,o=H(0,360),s=n?()=>1+.2*n*H():()=>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*Z(-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 l=t-r*st(o),c=e-r*ot(-o);i.show(l,c,1)}function Vt(t,e,r,n,i){const a=ct(n),o=((ct(i)-a)%360+360)%360;if(0===o)return;const s=new zt("curve"),l=Math.max(1,Math.ceil(o/90)),c=o/l,h=Math.PI*r*c/180;for(let t=0;t<l;t++)s.addSegment(a+t*c+90,h,1,!0);s.endPlot(a+o+90,1,!0);const u=t+r*ot(a),f=e-r*st(a);s.draw(u,f,1)}let Wt,$t,Ht,jt;class Kt{constructor(){this.isClosed=!1,this.curvature=$t,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){ne(this.vert,this.curvature,this.isClosed).show()}}function Zt(t=0){$t=tt(t,0,1),Wt=new Kt}function qt(t,e,r=1){if(!Wt)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");Wt.vertex(t,e,r)}function Jt(t=!1){if(!Wt)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(Wt.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(Wt.vertex(...Wt.vert[0]),Wt.isClosed=!0),Wt.show(),Wt=!1}function Qt(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);jt=[e,r],Ht=new zt(t)}function te(t,e,r){if(!Ht)throw new Error("move() called without beginStroke(). Call beginStroke() first.");Ht.addSegment(t,e,r)}function ee(t,e){if(!Ht)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");Ht.endPlot(t,e),Ht.draw(jt[0],jt[1],1),Ht=!1}function re(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()}function ne(t,e=.5,r=!1){const n=new zt(0===e?"segments":"curve"),i=2*Math.PI;if(r&&0!==e&&t.push(t[1]),t&&t.length>0){let a,o,s,l=0;for(let c=0;c<t.length-1;c++)if(e>0&&c<t.length-2){const h=t[c],u=t[c+1],f=t[c+2],m=ut(h[0],h[1],u[0],u[1]),d=ut(u[0],u[1],f[0],f[1]),g=ft(h[0],h[1],u[0],u[1]),p=ft(u[0],u[1],f[0],f[1]),x=e*Math.min(m,d,.5*Math.min(m,d)),y=Math.max(m,d),_=m-x,b=d-x;if(Math.floor(g)===Math.floor(p)){const e=r&&0===c?0:m-l,i=r?0===c?0:d-s:d;n.addSegment(g,e,h[2],!0),c===t.length-3&&n.addSegment(p,i,u[2],!0),l=0,0===c&&(a=m,s=x,o=t[1],l=0)}else{const e={x:u[0]-x*ot(-g),y:u[1]-x*st(-g)},f={x:e.x+y*ot(90-g),y:e.y+y*st(90-g)},m={x:u[0]+x*ot(-p),y:u[1]+x*st(-p)},d={x:m.x+y*ot(90-p),y:m.y+y*st(90-p)},v=mt(e,f,m,d,!0),w=ut(e.x,e.y,v.x,v.y),R=ut(e.x,e.y,m.x,m.y)/2,A=i*w*(2*Math.asin(R/w)*(180/Math.PI))/360,E=r&&0===c?0:_-l,M=c===t.length-3?r?a-x:b:0;n.addSegment(g,E,h[2],!0),n.addSegment(g,isNaN(A)?0:A,h[2],!0),n.addSegment(p,M,u[2],!0),l=x,0===c&&(a=_,s=x,o=[e.x,e.y])}c===t.length-3&&n.endPlot(p,u[2],!0)}else if(0===e){const e=t[c],r=t[c+1],i=ut(e[0],e[1],r[0],r[1]),a=ft(e[0],e[1],r[0],r[1]);n.addSegment(a,i,r[2],!0),c===t.length-2&&n.endPlot(a,1,!0)}n.origin=r&&0!==e?o:t[0]}return n}const ie=(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 ae,oe,se,le,ce,he=!1,ue=0,fe=0,me=null,de=null;const ge={},pe={};let xe=1,ye=0,_e=0,be=1,ve=0,we=0,Re=0,Ae=0,Ee=1,Me=1,Se=new Float32Array(8192),Te=0,Pe=2048,ke=32768,Ie=null,Ce=null,Le=null,Fe=null,De=null;const Ne={},Be={};let Ye=0,Xe=new Float32Array(1280),ze=0,Oe=256,Ue=null;const Ge=new Map,Ve=new Float32Array([-1,-1,1,-1,-1,1,1,1]);function We(){const t=k.glMask?.renderer;t&&(t._curShader=null,t._cachedBlendMode=null,t._isBlending=null,ae.activeTexture(ae.TEXTURE0),ae.bindTexture(ae.TEXTURE_2D,null),ae.blendEquation(ae.FUNC_ADD),ae.blendFunc(ae.ONE,ae.ONE_MINUS_SRC_ALPHA))}function $e(){return oe}function He(){const t=ae.isEnabled(ae.DEPTH_TEST);var e;He._hadDepthTest=t,t&&ae.disable(ae.DEPTH_TEST),de=n._renderer.activeFramebuffer?.()??null,de?._beforeEnd&&de._beforeEnd(),ae.bindFramebuffer(ae.FRAMEBUFFER,(e=k.glMask)?"function"==typeof e._framebufferToBind?e._framebufferToBind():e.framebuffer??null:null),ae.viewport(0,0,k.glMask.width*k.glMask.density,k.glMask.height*k.glMask.density)}function je(){He._hadDepthTest&&ae.enable(ae.DEPTH_TEST),He._hadDepthTest=!1,de?._beforeBegin?de._beforeBegin():(ae.bindFramebuffer(ae.FRAMEBUFFER,null),n._renderer.viewport(n._renderer._origViewport.width,n._renderer._origViewport.height),n._renderer._applyStencilTestIfClipping?.()),de=null}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 Ze(t,e,r,n){if(Te>=Pe){Pe*=2;const t=new Float32Array(4*Pe);t.set(Se),Se=t}const i=t-Re,a=e-Ae,o=4*Te,s=xe*i+_e*a+ve+Re,l=ye*i+be*a+we+Ae,c=Me*r*Ee/2;Se[o]=s,Se[o+1]=l,Se[o+2]=c,Se[o+3]=n/255;const h=s*Me,u=l*Me;Ie=Ke(Ie,h-c-1,u-c-1,h+c+1,u+c+1),Te++}function qe(t,e){if(0===ze)return;k.glMask.isDrawn=!0,He();let r=Ge.get(e);r||(r=ae.createTexture(),ae.bindTexture(ae.TEXTURE_2D,r),ae.texImage2D(ae.TEXTURE_2D,0,ae.RGBA,ae.RGBA,ae.UNSIGNED_BYTE,t.canvas),ae.texParameteri(ae.TEXTURE_2D,ae.TEXTURE_MIN_FILTER,ae.LINEAR),ae.texParameteri(ae.TEXTURE_2D,ae.TEXTURE_MAG_FILTER,ae.LINEAR),ae.texParameteri(ae.TEXTURE_2D,ae.TEXTURE_WRAP_S,ae.CLAMP_TO_EDGE),ae.texParameteri(ae.TEXTURE_2D,ae.TEXTURE_WRAP_T,ae.CLAMP_TO_EDGE),Ge.set(e,r)),ae.useProgram(Ce),ae.enable(ae.BLEND),ae.blendFunc(ae.ONE_MINUS_DST_ALPHA,ae.ONE),ae.activeTexture(ae.TEXTURE0),ae.bindTexture(ae.TEXTURE_2D,r),ae.uniform1i(Be.u_tex,0);const n=E.stroke.color._array;ae.uniform4f(Be.u_color,...n),ae.uniformMatrix4fv(Be.u_proj,!1,$e()),ae.bindVertexArray(Le),ae.bindBuffer(ae.ARRAY_BUFFER,De);const i=5*ze*4,a=Xe.subarray(0,5*ze);i>Ye?(ae.bufferData(ae.ARRAY_BUFFER,Xe,ae.DYNAMIC_DRAW),Ye=Xe.byteLength):ae.bufferSubData(ae.ARRAY_BUFFER,0,a),ae.drawArraysInstanced(ae.TRIANGLE_STRIP,0,4,ze),ae.flush(),ae.bindVertexArray(null),ae.bindTexture(ae.TEXTURE_2D,null),je(),Ue&&(k.markDirtyRect(k.glMask,Ue),Ue=null),ze=0,We()}E.stroke={color:null,weight:1,clipWindow:null,type:"HB",isActive:!1,opacity:1};let Je=new Map,Qe={a:1,b:0,c:0,d:1,tx:0,ty:0};function tr(){return n??r??window.self.p5.instance}const er={offset:.08,scale:.08,warp:.06,tilt:.06};function rr(){return{...E.stroke}}function nr(t){E.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.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,l,c]=[(e-i)/o,(r-i)/o,(n-i)/o];return{type:"custom",min_max:[i,a],variation:{...er},curve:t=>t<.5?s+(l-s)*t*2:l+(c-l)*(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=Ge.get(t);e&&ae&&ae.deleteTexture(e),Ge.delete(t)}(r);const n=tr().createGraphics(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(),Nr.imageToWhite(n),Nr.tips.set(r,n),e.tipKey=r,void Je.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 Nr.add(e.image.src),Je.set(t,{param:e,colors:[],buffers:[]}),Nr.load()}Je.set(t,{param:e,colors:[],buffers:[]})}function ar(){return[...Je.keys()]}function or(t){for(const{param:e}of Je.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)}function sr(t){if(!Je.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...Je.keys()].join(", ")}.`);E.stroke.type=t}function lr(t,e,r){A(),E.stroke.color=n.color(...arguments),E.stroke.isActive=!0}function cr(t){E.stroke.weight=t}function hr(t,e,r=1){sr(t),lr(e),cr(r)}function ur(){E.stroke.isActive=!1}function fr(){return{a:pt(),b:xt(),c:yt(),d:_t(),tx:dt(),ty:gt()}}function mr(t){const[e,r,n,i]=t;return{minX:Math.min(e,n),minY:Math.min(r,i),maxX:Math.max(e,n),maxY:Math.max(r,i)}}function dr(t){A();const e=function(t){const e=t.a*t.d-t.b*t.c;return Math.abs(e)<1e-12?null:{a:t.d/e,b:-t.b/e,c:-t.c/e,d:t.a/e,tx:(t.c*t.ty-t.d*t.tx)/e,ty:(t.b*t.tx-t.a*t.ty)/e}}(fr());if(!e)throw new Error("brush.clip() cannot be used with a non-invertible transform.");E.stroke.clipWindow={bounds:mr(t),inverse:e}}function gr(){E.stroke.clipWindow=null}let pr,xr,yr,_r;const br={};function vr(r,n,a,o=!1){xe=pt(),ye=xt(),_e=yt(),be=_t(),ve=dt(),we=gt(),Re=t/2,Ae=e/2,Ee=Math.sqrt(xe*xe+ye*ye),Me=i,Qe=fr(),pr=new wt(r+t/2,n+e/2),xr=a,yr=o,yr&&yr.calcIndex(0)}const wr=[];function Rr(r,i){i||(_r=r),function(){br.seed=999999*$();const{param:r}=Je.get(E.stroke.type)??{};if(!r)return;br.p=r;const{pressure:i}=r;if(br.a="custom"!==i.type?$(-1,1):0,br.b="custom"!==i.type?$(1,1.5):0,"custom"!==i.type)br.cp=$(3,3.5),br.ct=0,br.cs=1,br.ck=0;else{const t=i.variation??er;br.cp=$(-t.offset,t.offset),br.ct=$(-t.warp,t.warp),br.cs=$(1-t.scale,1+t.scale),br.ck=$(-t.tilt,t.tilt)}if([br.min,br.max]=i.min_max,br.noiseoffset=.03,!yr){const t=_r*Math.PI/180;br.cos=Math.cos(t),br.sin=Math.sin(t)}!function(){P(),function(){const t=n?.glMask;t&&(me=t,me.dirtyRect??=null,me.isDrawn??=!1,k.glMask=me)}();const r=n.drawingContext,i=!he||ae!==r;(i||ue!==t||fe!==e)&&(oe=new Float32Array([2/t,0,0,0,0,2/e,0,0,0,0,1,0,-1,-1,0,1]),ue=t,fe=e),i&&(ae=r,ce=ie(ae,"#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);}"),ae.useProgram(ce),ae.enable(ae.BLEND),ae.blendFunc(ae.ONE_MINUS_DST_ALPHA,ae.ONE),["a_position","a_radius","a_alpha"].forEach(t=>ge[t]=ae.getAttribLocation(ce,t)),["u_matrix","u_color"].forEach(t=>pe[t]=ae.getUniformLocation(ce,t)),se=ae.createVertexArray(),ae.bindVertexArray(se),le=ae.createBuffer(),ae.bindBuffer(ae.ARRAY_BUFFER,le),ae.bufferData(ae.ARRAY_BUFFER,Se.byteLength,ae.DYNAMIC_DRAW),ke=Se.byteLength,ae.enableVertexAttribArray(ge.a_position),ae.vertexAttribPointer(ge.a_position,2,ae.FLOAT,!1,16,0),ae.enableVertexAttribArray(ge.a_radius),ae.vertexAttribPointer(ge.a_radius,1,ae.FLOAT,!1,16,8),ae.enableVertexAttribArray(ge.a_alpha),ae.vertexAttribPointer(ge.a_alpha,1,ae.FLOAT,!1,16,12),ae.bindVertexArray(null),Ge.clear(),Ce=ie(ae,"#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=>Ne[t]=ae.getAttribLocation(Ce,t)),["u_proj","u_color","u_tex"].forEach(t=>Be[t]=ae.getUniformLocation(Ce,t)),Le=ae.createVertexArray(),ae.bindVertexArray(Le),Fe=ae.createBuffer(),ae.bindBuffer(ae.ARRAY_BUFFER,Fe),ae.bufferData(ae.ARRAY_BUFFER,Ve,ae.STATIC_DRAW),ae.enableVertexAttribArray(Ne.a_corner),ae.vertexAttribPointer(Ne.a_corner,2,ae.FLOAT,!1,0,0),De=ae.createBuffer(),ae.bindBuffer(ae.ARRAY_BUFFER,De),ae.bufferData(ae.ARRAY_BUFFER,Xe.byteLength,ae.DYNAMIC_DRAW),Ye=Xe.byteLength,ae.enableVertexAttribArray(Ne.a_pos),ae.vertexAttribPointer(Ne.a_pos,2,ae.FLOAT,!1,20,0),ae.vertexAttribDivisor(Ne.a_pos,1),ae.enableVertexAttribArray(Ne.a_size),ae.vertexAttribPointer(Ne.a_size,1,ae.FLOAT,!1,20,8),ae.vertexAttribDivisor(Ne.a_size,1),ae.enableVertexAttribArray(Ne.a_angle),ae.vertexAttribPointer(Ne.a_angle,1,ae.FLOAT,!1,20,12),ae.vertexAttribDivisor(Ne.a_angle,1),ae.enableVertexAttribArray(Ne.a_alpha),ae.vertexAttribPointer(Ne.a_alpha,1,ae.FLOAT,!1,20,16),ae.vertexAttribDivisor(Ne.a_alpha,1),ae.bindVertexArray(null),he=!0)}();const a=!0!==k.isBrush;k.isBrush=!0,a&&(k.justChanged=!0),k.blend(E.stroke.color),br.alpha=["default","spray"].includes(br.p.type)?br.p.opacity:br.p.opacity/Math.min(E.stroke.weight,1.3);{const r=t/2,n=e/2,i=Qe;if(E.stroke.clipWindow){const{inverse:t,bounds:e}=E.stroke.clipWindow,a=t.a*i.a+t.c*i.b,o=t.a*i.c+t.c*i.d,s=t.b*i.a+t.d*i.b,l=t.b*i.c+t.d*i.d;br.clipA=a,br.clipB=s,br.clipC=o,br.clipD=l,br.clipTX=t.a*i.tx+t.c*i.ty+t.tx-a*r-o*n,br.clipTY=t.b*i.tx+t.d*i.ty+t.ty-s*r-l*n,br.clipMinX=e.minX,br.clipMaxX=e.maxX,br.clipMinY=e.minY,br.clipMaxY=e.maxY}else{const e="custom"===br.p.type||"image"===br.p.type?Math.max(.05*t,Tr()):.05*t;br.clipA=i.a,br.clipB=i.b,br.clipC=i.c,br.clipD=i.d,br.clipTX=i.tx-i.a*r-i.c*n,br.clipTY=i.ty-i.b*r-i.d*n,br.clipMinX=-r-e,br.clipMaxX=r+e,br.clipMinY=-n-e,br.clipMaxY=n+e}}Ir()}();const a=function(){const{param:t}=Je.get(E.stroke.type)??{};return t?t.spacing:1}(),o=Math.round(xr*(i?r:1)/a);for(let t=0;t<o;t++)wr.length<2*o&&wr.push(q()),Ar(),i?pr.plotTo(yr,a,a,r,t<10):pr._moveToDegrees(r,a,a);!function(){Ir(),function(){if(0===Te)return;k.glMask.isDrawn=!0,He();const t=E.stroke.color._array;ae.useProgram(ce),ae.enable(ae.BLEND),ae.blendFunc(ae.ONE_MINUS_DST_ALPHA,ae.ONE),ae.bindVertexArray(se),ae.bindBuffer(ae.ARRAY_BUFFER,le);const e=16*Te,r=Se.subarray(0,4*Te);e>ke?(ae.bufferData(ae.ARRAY_BUFFER,Se,ae.DYNAMIC_DRAW),ke=Se.byteLength):ae.bufferSubData(ae.ARRAY_BUFFER,0,r),ae.uniform4f(pe.u_color,...t),ae.uniformMatrix4fv(pe.u_matrix,!1,$e()),ae.drawArrays(ae.POINTS,0,Te),ae.flush(),ae.bindVertexArray(null),je(),Ie&&(k.markDirtyRect(k.glMask,Ie),Ie=null),Te=0,We()}();const t=br.p?.type;"image"===t?qe(Nr.tips.get(br.p.image.src),br.p.image.src):"custom"===t&&qe(Nr.tips.get(br.p.tipKey),br.p.tipKey)}()}function Ar(){if(!Sr())return;const t=Er(),e=Q(V(br.seed+.002*pr.plotted,0),0,1,1-br.noiseoffset,1+br.noiseoffset);switch(br.p.type){case"spray":!function(t){const e=E.stroke.weight*br.p.scatter*t+E.stroke.weight*j(wr)*br.p.scatter/3,r=br.p.weight*$(.9,1.1),n=Math.ceil(br.p.grain/t);for(let t=0;t<n;t++){const t=$(.9,1.1),n=t*e*$(-1,1),i=$(-1,1),a=Math.sqrt((t*e)**2-n**2);Ze(pr.x+n,pr.y+i*a,r,br.alpha)}}(t*e);break;case"marker":Pr(t*e);break;case"custom":case"image":kr(t*e);break;default:!function(t,e=1){const r=(e=Q(e,0,1,.9,1.05))*E.stroke.weight*br.p.scatter*(br.p.sharpness+(1-br.p.sharpness)*j(wr)/t);if($(0,br.p.grain*t)>.4){let e,n;if(yr)e=.7*r*$(-1,1),n=r*$(-1,1);else{const t=r*$(-1,1),i=.3*r*$(-1,1);e=t*-br.sin+i*br.cos,n=t*br.cos+i*br.sin}const i=t*t*br.p.weight*$(.85,1.15)*E.stroke.weight,a=Math.max(.9,t)*br.alpha*$(.75,1.1);Ze(pr.x+e,pr.y+n,i,a)}}(t*e)}}function Er(){return yr?Mr()*yr.pressure(pr.plotted):Mr()}function Mr(){return"custom"===br.p.pressure.type?Q(br.p.pressure.curve(Math.max(0,Math.min(1,.5+(pr.plotted/xr-.5+br.ct)*br.cs)))+br.cp+br.ck*(pr.plotted/xr-.5),0,1,br.min,br.max,!0):function(t=.5+br.p.pressure.curve[0]*br.a,e=1-br.p.pressure.curve[1]*br.b,r=br.cp,n=br.min,i=br.max){const a=t*xr,o=(pr.plotted<a?1.2*e:.8*e)*(xr/2);return Q(1/(1+Math.pow(Math.abs((pr.plotted-a)/o),2*r)),0,1,n,i)}()}function Sr(){const t=br.clipA*pr.x+br.clipC*pr.y+br.clipTX;if(t<br.clipMinX||t>br.clipMaxX)return!1;const e=br.clipB*pr.x+br.clipD*pr.y+br.clipTY;return e>=br.clipMinY&&e<=br.clipMaxY}function Tr(){const t=Math.max(1,br.max??1),e=E.stroke.weight*br.p.scatter,r=E.stroke.weight*br.p.weight*t;return Math.max(8,1.5*e+.75*r)}function Pr(t,e=!0,r=br.alpha){const n=e?E.stroke.weight*br.p.scatter:0,i=e?n*$(-1,1):0,a=e?n*$(-1,1):0;Ze(pr.x+i,pr.y+a,E.stroke.weight*br.p.weight*t,r*Math.max(.8,t)*$(.9,1.1))}function kr(t,e=br.alpha){const r=E.stroke.weight*br.p.scatter,n=r*$(-1,1),i=r*$(-1,1),a=br.p.weight*E.stroke.weight*t,o=Tr();let s=0;"random"===br.p.rotate?s=K(0,360)*(Math.PI/180):"natural"===br.p.rotate&&(s=((yr?-yr.angle(pr.plotted):-_r)+pr.angle())*(Math.PI/180)),function(t,e,r,n,i,a=0){if(ze>=Oe){Oe*=2;const t=new Float32Array(5*Oe);t.set(Xe),Xe=t}const o=t-Re,s=e-Ae,l=xe*o+_e*s+ve+Re,c=ye*o+be*s+we+Ae,h=Me*r*Ee/2,u=Me*a*Ee,f=5*ze;Xe[f]=l,Xe[f+1]=c,Xe[f+2]=h,Xe[f+3]=n,Xe[f+4]=i/255;const m=l*Me,d=c*Me,g=1.42*h+u;Ue=Ke(Ue,m-g-1,d-g-1,m+g+1,d+g+1),ze++}(pr.x+n,pr.y+i,a,s,e*Math.max(.8,t)*$(.9,1.1),o)}function Ir(){if(!1!==br.p.markerTip&&Sr()){let t=Er(),e=br.alpha;if("marker"===br.p.type)for(let r=1;r<10;r++)Pr(t*r/10,!0,8*e);else if("custom"===br.p.type||"image"===br.p.type)for(let r=1;r<5;r++)kr(t*r/10,2*e)}}function Cr(t,e,r,n){if(!E.stroke.isActive||!E.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");vt();let i=ut(t,e,r,n);0!=i&&(vr(t,e,i),Rr(ft(t,e,r,n),!1))}function Lr(t,e,r,n){if(!E.stroke.isActive||!E.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");vt(),vr(t,e,r),Rr(lt(n),!1)}G(()=>{wr.length=0});const Fr=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate","markerTip"],Dr=[["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]}]],["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 Dr){let e={};for(let r=0;r<t[1].length;r++)e[Fr[r]]=t[1][r];ir(t[0],e)}Xt.prototype.draw=function(t=!1,e,r){let n=rr();if(t&&hr(t,e,r),n.isActive)for(let t of this.sides)Cr(t[0].x,t[0].y,t[1].x,t[1].y);nr(n)},zt.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){vt(),vr(e,r,t.length,t),Rr(n,!0)}(this,t,e,r))};const Nr={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=>new Promise((e,r)=>{const n=new window.Image;n.onload=()=>{const r=tr().createImage(n.naturalWidth,n.naturalHeight);r.drawingContext.drawImage(n,0,0),Nr.imageToWhite(r),this.tips.set(t,r),e()},n.onerror=()=>r(new Error(`Failed to load image tip: ${t}`)),n.crossOrigin="anonymous",n.src=t})))}};function Br(){return{...E.hatch}}function Yr(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let n=E.hatch;n.isActive=!0,n.dist=t,n.angle=ct(e),n.options=r}function Xr(t,e="black",r=1){E.hatch.hBrush={brush:t,color:e,weight:r}}function zr(){E.hatch.isActive=!1,E.hatch.hBrush=!1}function Or(t,e,r,n){const i=e*Math.PI/180,a=Math.cos(i),o=Math.sin(i),s=Math.cos(-i),l=Math.sin(-i),c=t.a,h=c.length,u=new Array(h);let f=Infinity,m=-Infinity;for(let t=0;t<h;t++){const e=c[t][0],r=c[t][1],n=[e*a-r*o,e*o+r*a];u[t]=n,n[1]<f&&(f=n[1]),n[1]>m&&(m=n[1])}const d=[];for(let t=0;t<h;t++){const e=u[t],r=u[(t+1)%h];e[1]!==r[1]&&d.push(e,r)}const g=d.length,p=[];let x=f+.5*r,y=r;for(;x<m;){const t=[];for(let e=0;e<g;e+=2){const r=d[e][1],n=d[e+1][1];(r<=x&&x<n||n<=x&&x<r)&&t.push(d[e][0]+(x-r)/(n-r)*(d[e+1][0]-d[e][0]))}t.sort((t,e)=>t-e);for(let e=0;e<t.length-1;e+=2)p.push({x1:t[e]*s-x*l,y1:t[e]*l+x*s,x2:t[e+1]*s-x*l,y2:t[e+1]*l+x*s});x+=y,y*=n}return p}function Ur(t){const e=E.hatch.dist,r=(E.hatch.angle%180+180)%180,n=E.hatch.options,i=rr();E.hatch.hBrush&&hr(...Object.values(E.hatch.hBrush)),Array.isArray(t)||(t=[t]);const a=n.gradient?Q(n.gradient,0,1,1,1.1,!0):1,o=[];for(const n of t)for(const t of Or(n,r,e,a))o.push(t);o.sort((t,e)=>t.x1===e.x1?t.y1-e.y1:t.x1-e.x1);const s=n.rand||0;for(let t=0;t<o.length;t++){const r=o[t];let i=r.x1,a=r.y1,l=r.x2,c=r.y2;s&&(i+=s*e*$(-1,1),a+=s*e*$(-1,1),l+=s*e*$(-1,1),c+=s*e*$(-1,1)),Cr(i,a,l,c),t>0&&n.continuous&&Cr(o[t-1].x2,o[t-1].y2,i,a)}nr(i)}function Gr(t,e,r){const n=2*Math.PI,i=k.ctx,a=r/2;i.moveTo(t+a,e),i.arc(t,e,a,0,n)}E.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},Xt.prototype.hatch=function(t=!1,e,r){let n=Br();t&&Yr(t,e,r),n.isActive&&Ur(this),function(t){E.hatch={...t}}(n)},zt.prototype.hatch=function(t,e,r){Br().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,.25),this.pol.hatch())},E.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const Vr=()=>({...E.fill});function Wr(t,e,r,i){E.fill.opacity=(arguments.length<4?e:i)||150,E.fill.color=arguments.length<3?n.color(t):n.color(t,e,r),E.fill.isActive=!0}function $r(t,e="out"){E.fill.bleed_strength=tt(t,0,1),E.fill.direction=e}function Hr(t=.4,e=.4){E.fill.texture_strength=tt(t,0,1),E.fill.border_strength=tt(e,0,1)}function jr(){E.fill.isActive=!1}let Kr;const Zr=[[],[]];function qr(){for(let t=0;t<512;t++)Zr[0][t]=q(.5,.2),Zr[1][t]=q(0,.02)}function Jr(t,e,r){return(e.x-t.x)*(r.y-t.y)-(e.y-t.y)*(r.x-t.x)>.01}G(qr);class Qr{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 l=t[a],c=t[(a+1)%t.length],h={x:c.x-l.x,y:c.y-l.y},u=ht(0,0,h.x,h.y,90),f={x:l.x+h.x/2,y:l.y+h.y/2};i.push({v1:l,v2:c,ray:{point1:f,point2:{x:f.x+u.x,y:f.y+u.y}}})}this.sizeX=e,this.sizeY=n,this.dir=Array(t.length),i.forEach((t,e)=>{let r=0;for(const e of Kr.intersect(t.ray))Jr(t.v1,t.v2,e)&&r++;this.dir[e]=r%2==0});const a=$(-.6,.6)*e,o=$(-.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 l=r,c=r+e,h=this.v[(l-1+this.v.length)%this.v.length],u=this.v[c%this.v.length],f=u.x-h.x,m=u.y-h.y;for(let t=0;t<2;t++){const e=$(.25,.75),n={x:h.x+f*e,y:h.y+m*e},s=r+t;i.splice(s,0,n),a.splice(s,0,$(.4,.7)),o.splice(s,0,this.dir[l%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+$(0,.8*i)));const a=[],o=[],s=[],l=this.midP,c=Kr.sides;for(const t of n){const r=t%e;let n=this.v[r],i=0;for(const[t,e]of c){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:l.x+(n.x-l.x)*$(.3,.6),y:l.y+(n.y-l.y)*$(.3,.6)}),a.push(n),o.push(this.m[r]),s.push(!this.dir[r])}return new Qr(a,o,this.midP,s,!1,this.sizeX,this.sizeY)}flipDirs(){return new Qr(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,o=new Array(i),s=new Array(i),l=new Array(a),c=new Array(a),h="out"===E.fill.direction?-90:90;0===Zr[0].length&&qr();const u=Zr[0],f=u.length,m=Zr[1],d=m.length;let g,p,x,y=0,_=0,b=999===t?$(.6,.8):E.fill.bleed_strength;for(let a=0;a<i;a++){const g=e[a],p=e[a+1<i?a+1:0],x=r[a],v=n[a];if(t<997&&(b=x),b<.05){l[y]=x,c[y]=v,y++,o[_]=(g.x+p.x)/2,s[_]=(g.y+p.y)/2,l[y]=x,c[y]=v,y++,_++;continue}const w=(v?h:-h)+5*$(-1,1),R=ot(w),A=st(w),E=p.x-g.x,M=p.y-g.y,S=R*E+A*M,T=R*M-A*E,P=u[~~($(0,1)*f)]*$(.65,1.35)*b,k=x+m[~~($(0,1)*d)];l[y]=x,c[y]=v,y++,o[_]=g.x+.5*E+S*P,s[_]=g.y+.5*M+T*P,l[y]=k,c[y]=v,y++,_++}const v=2024*Math.max(.1,2*E.fill.bleed_strength);if(v&&y>v){const t=Math.ceil(y/v),r=Math.ceil(y/t);g=new Array(r),p=new Array(r),x=new Array(r);let n=0;for(let r=0;r<y;r+=t,n++)g[n]=r%2==0?e[r>>1]:{x:o[r>>1],y:s[r>>1]},p[n]=l[r],x[n]=c[r]}else{g=new Array(y);for(let t=0;t<y;t++)g[t]=t%2==0?e[t>>1]:{x:o[t>>1],y:s[t>>1]};l.length=y,c.length=y,p=l,x=c}return new Qr(g,p,this.midP,x,!1,this.sizeX,this.sizeY)}fill(r,n,a){const o=3*a,s=2*n*(1+a/2),l=!1!==k.isBrush;k.isBrush=!1,l&&(k.justChanged=!0),k.blend(r),k.ctx.save(),k.ctx.setTransform(i*pt(),i*xt(),i*yt(),i*_t(),i*(dt()+t/2),i*(gt()+e/2)),k.ctx.strokeStyle=`rgb(${r._getRed()} ${r._getGreen()} ${r._getBlue()} / ${.005*E.fill.border_strength})`,k.ctx.lineCap="round";const c=Math.max(this.sizeX,this.sizeY),h=$(.15,.7);let u=this.grow();const f=this.scatter(.1).grow().scatter(.75).flipDirs();let m;for(let t=0;t<20;t++){t%4==0&&(u=u.grow()),t%2==0&&(m=[u.grow(1-.0125*t),u.grow(.7-.0125*t),u.grow(.4-.0125*t)]);for(const e of m)e.grow(999).grow(997).layer(t,c,s,r);f.grow(999).flipDirs().grow(997).layer(t,c,s*o,r),t%2==0&&u.grow(h).grow(999).layer(t,c,2*s,r),t%8!=0&&19!==t||(0!==o&&u.erase(3*o,n),k.blend(r,!0,!1,!0))}k.ctx.restore()}layer(t,e,r,n){k.ctx.lineWidth=Q(t,0,24,e/25,e/30,!0),k.ctx.fillStyle=`rgb(${n._getRed()} ${n._getGreen()} ${n._getBlue()} / ${r}%)`,function(t){const e=k.ctx,r=e.getTransform(),n=r.a,i=r.b,a=r.c,o=r.d,s=r.e,l=r.f;let c=Infinity,h=Infinity,u=-Infinity,f=-Infinity;e.beginPath();const m=t[0];let d=n*m.x+a*m.y+s,g=i*m.x+o*m.y+l;c=u=d,h=f=g,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,g=i*m.x+o*m.y+l,c=Math.min(c,d),h=Math.min(h,g),u=Math.max(u,d),f=Math.max(f,g),e.lineTo(m.x,m.y)}e.closePath();const p=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);k.markDirtyRect(k.mask,{minX:c-p,minY:h-p,maxX:u+p,maxY:f+p})}(this.v),k.ctx.fill(),k.ctx.stroke()}erase(t,e){k.ctx.save();const r=~~($(80,110)*Q(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:l,y:c}=this.midP;k.ctx.globalCompositeOperation="destination-out";const h=(5-Q(e,80,100,.3,.7,!0))*t/255;k.ctx.fillStyle=`rgb(255 0 0 / ${h})`,k.ctx.lineWidth=0;for(let t=0;t<r;t++){const e=l+q(0,n),r=c+q(0,i),a=$(o,s);k.ctx.beginPath(),Gr(e,r,a),t%5!=0&&k.ctx.fill()}k.ctx.globalCompositeOperation="source-over",k.ctx.restore()}}Xt.prototype.fill=function(t=!1,e,r,n,i,a){let o=Vr();t&&(Wr(t,e),$r(r,a),Hr(n,i)),o.isActive&&(vt(),function(t){if(!E.fill.isActive||!E.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");Kr=t;const e=[...t.vertices],r=~~(.25*e.length*J({1:5,2:10,3:60})),n=E.fill.bleed_strength,i=e.map((t,e)=>(e>r?1:.3)*$(.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 Qr(o,i,s,[],!0).fill(E.fill.color,Q(E.fill.opacity,0,255,0,1,!0),E.fill.texture_strength)}(this)),(t=>{E.fill={...t}})(o)},zt.prototype.fill=function(t,e,r){Vr().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,E.fill.bleed_strength<.06?0:Q(E.fill.bleed_strength,0,.6,.2,.6,!0)),this.pol.fill())};const tn=[];"undefined"!=typeof p5&&p5.registerAddon(function(t,e,r){r.presetup=function(){S(this)},r.predraw=function(){S(this)},r.postsetup=function(){M(this),k.blend(!1,!0),T()},r.postdraw=function(){M(this),k.blend(!1,!0),T()};const n=e.push,i=e.pop,a=e.randomSeed,o=e.noiseSeed;e.push=function(){n.call(this),vt(),tn.push({fill:{...E.fill},stroke:{...E.stroke},hatch:{...E.hatch},field:{...E.field}})},e.pop=function(){i.call(this),function(){const t=tn.pop();t&&(E.stroke={...t.stroke},E.field={...t.field},E.hatch={...t.hatch},E.fill={...t.fill})}()},e.randomSeed=function(t){a.call(this,t),(t=>{z=Y(t),O=Y(`${t}:2`);for(const t of U)t()})(t)},e.noiseSeed=function(t){o.call(this,t),(t=>{V=B(Y(t)),W=B(Y(`${t}:2`))})(t)}});export{zt as Plot,Xt as Polygon,wt as Position,ir as add,Dt as addField,Vt as arc,Zt as beginShape,Qt as beginStroke,ar as box,Gt as circle,dr as clip,Jt as endShape,ee as endStroke,Lt as field,Wr as fill,$r as fillBleed,Hr as fillTexture,Lr as flowLine,Yr as hatch,Ur as hatchArray,Xr as hatchStyle,M as instance,Cr as line,Nt as listFields,w as load,te as move,gr as noClip,Ft as noField,jr as noFill,zr as noHatch,ur as noStroke,sr as pick,Ot as polygon,Ut as rect,Ct as refreshField,or as scaleBrushes,hr as set,re as spline,lr as stroke,cr as strokeWeight,qt as vertex,J as wRand,Bt as wiggle};+let t,e,n,r,i,o=null,s=null;const a=[];let l=!1;const c=t=>!!t&&"function"==typeof t.begin&&"function"==typeof t.end&&!!t.renderer&&!!t.renderer._pInst,u=t=>"number"==typeof t&&Number.isFinite(t)&&t>0,h=t=>{try{return t()}catch(t){return}},f=t=>!!t&&"function"==typeof t.pixelDensity&&"function"==typeof t.createFramebuffer&&u(h(()=>t.width))&&u(h(()=>t.height))&&"webgl2"===h(()=>t.webglVersion),x=t=>(f(t)&&(o=t),o),m=()=>(s&&f(s)?x(s):null)||x(window.self?.p5?.instance??null)||x(n)||o,g=()=>r?._renderer?.activeFramebuffer?.()??null,d=(n=!1)=>{const i=((t=!1)=>{const e=m();if(!t){if(!e)throw new Error("p5.brush could not resolve an active WEBGL sketch. Call brush.instance(p) and brush.load() after createCanvas(..., WEBGL).");return{renderer:e,width:e.width,height:e.height}}if(c(t)){const n=t.renderer._pInst;if(x(n),e&&n!==e)throw new Error("p5.brush only supports p5.Framebuffer targets created from the active sketch");return{renderer:n,width:t.width,height:t.height}}return{renderer:t,width:t.width,height:t.height}})(n);if(r=i.renderer,x(n?m():r),"webgl2"!==r.webglVersion)throw new Error("p5.brush requires a WEBGL canvas");t=i.width,e=i.height,l=!0},p=()=>{l||d()},y=t=>{n=t,x(t)},v=t=>{a.push(s),s=t,y(t)},_=()=>{s=a.pop()??null},b=Math.sqrt(3),w=.5*(b-1),R=(3-b)/6,A=t=>0|Math.floor(t),E=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 M(t=Math.random){const e=function(t){const e=new Uint8Array(512);for(let t=0;t<256;t++)e[t]=t;for(let n=0;n<255;n++){const r=n+~~(t()*(256-n)),i=e[n];e[n]=e[r],e[r]=i}for(let t=256;t<512;t++)e[t]=e[t-256];return e}(t),n=new Float64Array(e).map(t=>E[t%12*2]),r=new Float64Array(e).map(t=>E[t%12*2+1]);return function(t,i){let o=0,s=0,a=0;const l=(t+i)*w,c=A(t+l),u=A(i+l),h=(c+u)*R,f=t-(c-h),x=i-(u-h);let m,g;f>x?(m=1,g=0):(m=0,g=1);const d=f-m+R,p=x-g+R,y=f-1+2*R,v=x-1+2*R,_=255&c,b=255&u;let E=.5-f*f-x*x;if(E>=0){const t=_+e[b];E*=E,o=E*E*(n[t]*f+r[t]*x)}let M=.5-d*d-p*p;if(M>=0){const t=_+m+e[b+g];M*=M,s=M*M*(n[t]*d+r[t]*p)}let S=.5-y*y-v*v;if(S>=0){const t=_+1+e[b+1];S*=S,a=S*S*(n[t]*y+r[t]*v)}return 70*(o+s+a)}}function S(t,e){let n=new P(t),r=()=>n.next();return r.double=()=>r()+11102230246251565e-32*(2097152*r()|0),r.int32=()=>4294967296*n.next()|0,r.quick=r,r}class P{constructor(t){null==t&&(t=+new Date);let e=4022871197;function n(t){t=String(t);for(let n=0;n<t.length;n++){e+=t.charCodeAt(n);let r=.02519603282416938*e;e=r>>>0,r-=e,r*=e,e=r>>>0,r-=e,e+=4294967296*r}return 2.3283064365386963e-10*(e>>>0)}this.c=1,this.s0=n(" "),this.s1=n(" "),this.s2=n(" "),this.s0-=n(t),this.s0<0&&(this.s0+=1),this.s1-=n(t),this.s1<0&&(this.s1+=1),this.s2-=n(t),this.s2<0&&(this.s2+=1)}next(){let{c:t,s0:e,s1:n,s2:r}=this,i=2091639*e+2.3283064365386963e-10*t;return this.s0=n,this.s1=r,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 T=S(Math.random()),k=S(Math.random());const C=[],I=t=>C.push(t);let L=M(S(Math.random())),F=M(S(Math.random()));const D=(t=0,e=1)=>t+T()*(e-t),N=(t=0,e=1)=>t+k()*(e-t),B=t=>t[~~(T()*t.length)],Y=(t,e)=>~~D(t,e),z=(t,e)=>~~N(t,e),O=(t=0,e=1)=>{const n=1-T(),r=T();return Math.sqrt(-2*Math.log(n))*j(360*r)*e+t},U=t=>{let e=0;const n=[];for(const r in t)e+=t[r],n.push({key:r,cumulative:e});const r=T()*e;for(const{key:t,cumulative:e}of n)if(r<e)return isNaN(t)?t:parseInt(t)},X=(t,e,n,r,i,o=!1)=>{let s=r+(t-e)/(n-e)*(i-r);return o?r<i?Z(s,r,i):Z(s,i,r):s},Z=(t,e,n)=>Math.max(Math.min(t,n),e),G=t=>(t%=360)<0?t+360:t,V=1440,$=2*Math.PI/V,H=new Float32Array(V).fill(NaN),W=new Float32Array(V).fill(NaN),j=t=>{const e=~~(4*G(t));let n=H[e];return isNaN(n)&&(n=Math.cos(e*$),H[e]=n),n},K=t=>{const e=~~(4*G(t));let n=W[e];return isNaN(n)&&(n=Math.sin(e*$),W[e]=n),n},q=(t,e=!1)=>{if(e||r&&"function"==typeof r.angleMode&&r.angleMode()===r.RADIANS){let e=180*t/Math.PI%360;return e<0?e+360:e}return t},J=(t,e=!1)=>e||r&&"function"==typeof r.angleMode&&r.angleMode()===r.RADIANS?180*t/Math.PI:t,Q=(t,e,n,r,i)=>{let o=j(i),s=K(i);return{x:o*(n-t)+s*(r-e)+t,y:o*(r-e)-s*(n-t)+e}},tt=(t,e,n,r)=>Math.hypot(n-t,r-e),et=(t,e,n,r)=>q(Math.atan2(-(r-e),n-t),!0),nt=(t,e,n,r,i=!1)=>{let o=t.x,s=t.y,a=e.x,l=e.y,c=n.x,u=n.y,h=r.x,f=r.y;if(o===a&&s===l||c===h&&u===f)return!1;let x=a-o,m=l-s,g=h-c,d=f-u,p=d*x-g*m;if(0===p)return!1;let y=(g*(s-u)-d*(o-c))/p,v=(x*(s-u)-m*(o-c))/p;return!(!i&&(v<0||v>1))&&{x:o+y*x,y:s+y*m}},rt=(t,e=0)=>t?{minX:t.minX-e,minY:t.minY-e,maxX:t.maxX+e,maxY:t.maxY+e}:null;let it=null,ot=null;const st=t=>{if(!t)return;if(c(t))return void t.draw(()=>r.clear());const e=t.drawingContext;e.save(),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,t.width,t.height),e.restore()},at=()=>({width:Math.max(1,Math.round(t*i)),height:Math.max(1,Math.round(e*i))}),lt=t=>{if(!t)return null;const{width:e,height:n}=at();return((t,e,n)=>{if(!t)return null;const r=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))),s=Math.min(n,Math.ceil(Math.max(t.minY,t.maxY)));return o<=r||s<=i?null:{minX:r,minY:i,maxX:o,maxY:s}})(t,e,n)},ct=()=>{const{width:t,height:e}=at();return((t,e)=>({minX:0,minY:0,maxX:t,maxY:e}))(t,e)},ut=(t,e=!0)=>{const n=lt(t);if(!n)return null;const{height:r}=at();return{x:n.minX,y:e?r-n.maxY:n.minY,width:n.maxX-n.minX,height:n.maxY-n.minY}},ht=(t,e,n,r=!0)=>{const i=ut(e,r);if(i){t.enable(t.SCISSOR_TEST),t.scissor(i.x,i.y,i.width,i.height);try{n()}finally{t.disable(t.SCISSOR_TEST)}}else n()},ft={},xt=()=>{r?.loaded||(p(),mt.load())},mt={isBlending:!1,cachedColor:null,markDirtyRect(t,e){const n=lt(e);var r,i;t&&n&&(t.dirtyRect=(i=n,(r=t.dirtyRect)?i?{minX:Math.min(r.minX,i.minX),minY:Math.min(r.minY,i.minY),maxX:Math.max(r.maxX,i.maxX),maxY:Math.max(r.maxY,i.maxY)}:r:i),t.isDrawn=!0)},clearMask(t){if(!t)return;const e=t===this.glMask?it:ot;e?.clearMask?.(t,st)},getCompositeRect(t,e){const n=e?it:ot;return n?.getCompositeRect?.(t,g,ct,rt,lt)},load(){i=r.pixelDensity();const n=!r.blendSourceFramebuffer||r.blendSourceFramebuffer.width!==t||r.blendSourceFramebuffer.height!==e||"function"==typeof r.blendSourceFramebuffer.pixelDensity&&r.blendSourceFramebuffer.pixelDensity()!==i;r.loaded||(r.loaded=!0,r.shaderProgram??=r.createShader("#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=it?.ensureResources?.(r,t,e,i);const o=ot?.ensureResources?.(r,t,e,i,st)??{mask:null,ctx:null};n&&(r.blendSourceFramebuffer?.remove&&r.blendSourceFramebuffer.remove(),r.blendSourceFramebuffer=r.createFramebuffer({width:t,height:e,density:i,antialias:!1,depth:!1,stencil:!1})),this.mask=o.mask,this.ctx=o.ctx},blend(t=!1,e=!1){xt();const n=!0===this.isBrush,r=n?this.glMask:this.mask,i=n?this.mask:this.glMask,o=t?._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)),(e||s)&&(this.justChanged&&(this.applyShader(i,!n),this.justChanged=!1),this.isBlending&&this.applyShader(r,n),o&&(this.cachedColor=o),e&&(this.isBlending=!1,this.cachedColor=null))},applyShader(n,i){if(!n?.isDrawn)return;const o=this.getCompositeRect(n,i);if(!o)return void this.clearMask(n);const s=r.drawingContext,a=r.shaderProgram,l=g(),c=pt(l??r,o),u=!!l,h=s.getParameter(s.DEPTH_TEST);s.disable(s.DEPTH_TEST),r.push(),r.translate(0,0),r.shader(a),a.setUniform("u_source",c),a.setUniform("u_targetIsFramebuffer",u),a.setUniform("u_isBrush",i);const f=i?it:ot;a.setUniform("u_mask",f.getShaderMask(r,n,o,lt,ct,st)),a.setUniform("u_color",this.cachedColor),ht(s,o,()=>{r.fill(0,0,0,0),r.noStroke(),r.rect(-t/2,-e/2,t,e)},!u),r.pop(),r.resetShader(),h&&s.enable(s.DEPTH_TEST),this.clearMask(n)}},gt=()=>{xt(),mt.blend(!1,!0),mt.clearMask(mt.glMask),mt.clearMask(mt.mask),mt.justChanged=!1,mt.isBlending=!1,mt.isBrush=null,mt.cachedColor=null},dt=(t=!1)=>{d(t),r.loaded&&mt.load()},pt=(n,i=null)=>{const o=r.blendSourceFramebuffer,s=r.drawingContext,a=c(n),{width:l,height:u}=at(),h=i?ut(i):null,f=s.getParameter(s.READ_FRAMEBUFFER_BINDING),x=s.getParameter(s.DRAW_FRAMEBUFFER_BINDING);return(a?n.renderer:r._renderer)?.flushDraw?.(),a?(o.draw(()=>{ht(r.drawingContext,i,()=>{r.clear(),r.push(),r.imageMode(r.CENTER),r.image(n,0,0,t,e),r.pop()},!1)}),o):(s.bindFramebuffer(s.READ_FRAMEBUFFER,null),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,o.framebuffer),s.clearColor(0,0,0,0),s.clear(s.COLOR_BUFFER_BIT),s.blitFramebuffer(h?.x??0,h?.y??0,h?h.x+h.width:l,h?h.y+h.height:u,h?.x??0,h?.y??0,h?h.x+h.width:l,h?h.y+h.height:u,s.COLOR_BUFFER_BIT,s.NEAREST),s.bindFramebuffer(s.READ_FRAMEBUFFER,f),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,x),o)},yt=()=>r._renderer.uModelMatrix.mat4[12],vt=()=>r._renderer.uModelMatrix.mat4[13],_t=()=>r._renderer.uModelMatrix.mat4[0],bt=()=>r._renderer.uModelMatrix.mat4[1],wt=()=>r._renderer.uModelMatrix.mat4[4],Rt=()=>r._renderer.uModelMatrix.mat4[5];let At=!1;function Et(){At||(xt(),St=.01*t,Pt=-.5*t,Tt=-.5*e,kt=Math.round(2*t/St),Ct=Math.round(2*e/St),zt("hand",(t,e)=>{const n=N(.2,.8),r=z(5,10);return Xt(e,(e,i)=>.5*r*K(n*i*e+z(15,25))*.2*j(t)+F(e,i)*r*.7)}),zt("curved",(t,e)=>{let n=z(-10,10);return z(0,100)%2==0&&(n*=-1),Xt(e,(e,r)=>3*X(F(.02*e+.03*t,.02*r+.03*t),0,1,-n,n))}),zt("zigzag",(t,e)=>{let n=z(-30,-15)+Math.abs(44*K(t));z(0,100)%2==0&&(n*=-1);let r=n,i=0;for(let t=0;t<kt;t++){for(let n=0;n<Ct;n++)e[t][n]=i,i+=r,r*=-1;i+=r,r*=-1}return e}),zt("waves",(t,e)=>{const n=z(10,15)+5*K(t),r=z(3,6)+3*j(t),i=z(20,35);return Xt(e,(t,e)=>K(n*t)*i*j(e*r)+z(-3,3))}),zt("seabed",(t,e)=>{const n=N(.4,.8),r=z(18,26);return Xt(e,(e,i)=>1.1*r*K(n*i*e+z(15,20))*j(t))}),zt("spiral",(t,e)=>{const n=z(5,10),r=2*z(0,2)-1,i=z(65,80),o=Array.from({length:n},()=>({x:N(.1,.9)*kt,y:N(.1,.9)*Ct}));return Xt(e,(t,e)=>{let n=0,s=0;for(const a of o){const o=t-a.x,l=e-a.y,c=1/(o*o+l*l+1),u=Math.atan2(l,o)*(180/Math.PI),h=r*(u+i)*Math.PI/180;n+=c*Math.cos(h),s+=c*Math.sin(h)}return Math.atan2(s,n)*(180/Math.PI)})}),zt("columns",(t,e)=>{const n=z(3,8),r=z(25,45);return Xt(e,(t,e)=>K(t*n)*r)}),At=!0)}class Mt{constructor(t,e){Et(),this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=Mt.getColIndex(t),this.rowIdx=Mt.getRowIndex(e)}reset(){this.plotted=0}isIn(){return ft.field.isActive?Mt.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const n=t,r=e,i=this.x+yt(),o=this.y+vt();return i>=-.3*n&&i<=1.3*n&&o>=-.3*r&&o<=1.3*r}angle(t=!1){return ft.field.isActive&&(t||this.isIn())?It.get(ft.field.current).field[this.colIdx][this.rowIdx]*ft.field.wiggle:0}moveTo(t,e,n=1){this.movePos(J(t),e,n)}_moveToDegrees(t,e,n=1){this.movePos(t,e,n)}plotTo(t,e,n,r=1){this.movePos(t,e,n,r)}movePos(t,e,n,r=!1){const i=r||1;if(!this.isIn())return void(this.plotted+=n/i);const o=e/n,s=ft.field.isActive,a=!!r;for(let e=0;e<o;e++){const e=(s?this.angle(!0):0)-(a?t.angle(this.plotted):t);this.update(this.x+n*j(e),this.y+n*K(e)),this.plotted+=n/i}}static getRowIndex(t,e=1){const n=t+vt()-Tt;return Math.round(n/St/e)}static getColIndex(t,e=1){const n=t+yt()-Pt;return Math.round(n/St/e)}static isIn(t,e){return t>=0&&e>=0&&t<kt&&e<Ct}}ft.field={isActive:!1,current:null,wiggle:1};let St,Pt,Tt,kt,Ct,It=new Map;const Lt=new Set(["degrees","radians"]);function Ft(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!Lt.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function Dt(t,e){return function(t,e){if("radians"!==e)return t;for(let e=0;e<t.length;e++)for(let n=0;n<t[e].length;n++)t[e][n]=J(t[e][n],!0);return t}(t.gen(e,new Array(kt).fill(null).map(()=>new Float32Array(Ct))),t.angleMode)}function Nt(t=0){if(!ft.field.isActive||!ft.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=It.get(ft.field.current);e.field=Dt(e,t)}function Bt(t){if(ft.field.wiggle||(ft.field.wiggle=1),Et(),!It.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(It.keys()).join(", ")}.`);ft.field.isActive=!0,ft.field.current=t;const e=It.get(t);e.field||(e.field=Dt(e,0))}function Yt(){Et(),ft.field.isActive=!1}function zt(t,e,n={}){It.set(t,{gen:e,field:null,angleMode:Ft(n)})}function Ot(){return Et(),Array.from(It.keys())}function Ut(t=1){Bt("hand"),ft.field.wiggle=t}function Xt(t,e){for(let n=0;n<kt;n++)for(let r=0;r<Ct;r++)t[n][r]=e(n,r);return t}class Zt{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,n)=>[t,n[(e+1)%n.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 n=[];for(const[e,r]of this.sides){const i=nt(t.point1,t.point2,e,r);i&&n.push(i)}return this._intersectionCache[e]=n,n}show(){ft.wash&&this.wash(),ft.fill&&this.fill(),ft.mass&&this.mass(),ft.hatch&&this.hatch(),ft.stroke&&this.draw()}}class Gt{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,n=1,r=!1){this.angles.length>0&&this.angles.pop(),t=r?(t%360+360)%360:q(t),this.angles.push(t,t),this.pres.push(n),this.segments.push(e),this.length=this.segments.reduce((t,e)=>t+e,0)}endPlot(t=0,e=1,n=!1){t=n?(t%360+360)%360:q(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=q(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 n=t[this.index],r=t[this.index+1]??n;return Math.abs(r-n)>180&&(r>n?r=-(360-r):n=-(360-n)),X(e-this.suma,0,this.segments[this.index],n,r,!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(n,r,i=1,o){Et();const s=o<0?4:1,a=[],l=Math.round(this.length/s),c=new Mt(n+t/2,r+e/2);let u=0,h=0;for(let n=0;n<l;n++){c.plotTo(this,s,s);const n=this.calcIndex(c.plotted);u+=s,(u>=(o<=0?8:Math.max(this.segments[n]*o*N(.7,1.3),20))||n>=h)&&c.x&&(a.push([c.x-t/2,c.y-e/2]),u=0,n>=h&&h++)}return new Zt(a)}show(t,e,n=1){ft.wash&&this.wash(t,e,n),ft.fill&&this.fill(t,e,n),ft.mass&&this.mass(t,e,n),ft.hatch&&this.hatch(t,e,n),ft.stroke&&this.draw(t,e,n)}}function Vt(t){new Zt(t).show()}function $t(t,e,n,r,i="corner"){"center"===i&&(t-=n/2,e-=r/2),te(0),ee(t,e),ee(t+n,e),ee(t+n,e+r),ee(t,e+r),ne(!0)}function Ht(t,e,n,r=!1){const i=new Gt("curve"),o=Math.PI*n,s=N(0,360),a=r?()=>1+.2*r*N():()=>1;for(let t=0;t<4;t++){const e=-90*t+s;i.addSegment(e*a(),o/2*a(),1,!0)}if(r){const t=r*z(-5,5);i.addSegment(s,Math.abs(t)*(Math.PI/180)*n,1,!0),i.endPlot(t+s,1,!0)}else i.endPlot(s,1,!0);const l=t-n*K(s),c=e-n*j(-s);i.show(l,c,1)}function Wt(t,e,n,r,i){const o=J(r),s=((J(i)-o)%360+360)%360;if(0===s)return;const a=new Gt("curve"),l=Math.max(1,Math.ceil(s/90)),c=s/l,u=Math.PI*n*c/180;for(let t=0;t<l;t++)a.addSegment(o+t*c+90,u,1,!0);a.endPlot(o+s+90,1,!0);const h=t+n*j(o),f=e-n*K(o);a.draw(h,f,1)}let jt,Kt,qt,Jt;class Qt{constructor(){this.isClosed=!1,this.curvature=Kt,this.vert=[]}vertex(t,e,n){this.vert.push([t,e,n])}show(){ae(this.vert,this.curvature,this.isClosed).show()}}function te(t=0){Kt=Z(t,0,1),jt=new Qt}function ee(t,e,n=1){if(!jt)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");jt.vertex(t,e,n)}function ne(t=!1){if(!jt)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(jt.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(jt.vertex(...jt.vert[0]),jt.isClosed=!0),jt.show(),jt=!1}function re(t,e,n){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);Jt=[e,n],qt=new Gt(t)}function ie(t,e,n){if(!qt)throw new Error("move() called without beginStroke(). Call beginStroke() first.");qt.addSegment(t,e,n)}function oe(t,e){if(!qt)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");qt.endPlot(t,e),qt.draw(Jt[0],Jt[1],1),qt=!1}function se(t,e=.5){if(!t||t.length<2)throw new Error("spline() requires at least 2 points. Each point should be [x, y, pressure].");ae(t,e).draw()}function ae(t,e=.5,n=!1){const r=new Gt(0===e?"segments":"curve"),i=2*Math.PI;if(n&&0!==e&&t.push(t[1]),t&&t.length>0){let o,s,a,l=0;for(let c=0;c<t.length-1;c++)if(e>0&&c<t.length-2){const u=t[c],h=t[c+1],f=t[c+2],x=tt(u[0],u[1],h[0],h[1]),m=tt(h[0],h[1],f[0],f[1]),g=et(u[0],u[1],h[0],h[1]),d=et(h[0],h[1],f[0],f[1]),p=e*Math.min(x,m,.5*Math.min(x,m)),y=Math.max(x,m),v=x-p,_=m-p;if(Math.floor(g)===Math.floor(d)){const e=n&&0===c?0:x-l,i=n?0===c?0:m-a:m;r.addSegment(g,e,u[2],!0),c===t.length-3&&r.addSegment(d,i,h[2],!0),l=0,0===c&&(o=x,a=p,s=t[1],l=0)}else{const e={x:h[0]-p*j(-g),y:h[1]-p*K(-g)},f={x:e.x+y*j(90-g),y:e.y+y*K(90-g)},x={x:h[0]+p*j(-d),y:h[1]+p*K(-d)},m={x:x.x+y*j(90-d),y:x.y+y*K(90-d)},b=nt(e,f,x,m,!0),w=tt(e.x,e.y,b.x,b.y),R=tt(e.x,e.y,x.x,x.y)/2,A=i*w*(2*Math.asin(R/w)*(180/Math.PI))/360,E=n&&0===c?0:v-l,M=c===t.length-3?n?o-p:_:0;r.addSegment(g,E,u[2],!0),r.addSegment(g,isNaN(A)?0:A,u[2],!0),r.addSegment(d,M,h[2],!0),l=p,0===c&&(o=v,a=p,s=[e.x,e.y])}c===t.length-3&&r.endPlot(d,h[2],!0)}else if(0===e){const e=t[c],n=t[c+1],i=tt(e[0],e[1],n[0],n[1]),o=et(e[0],e[1],n[0],n[1]);r.addSegment(o,i,n[2],!0),c===t.length-2&&r.endPlot(o,1,!0)}r.origin=n&&0!==e?s:t[0]}return r}let le=!1;const ce=(t,e,n)=>{const r=t.createProgram();for(let[i,o]of[[t.VERTEX_SHADER,e],[t.FRAGMENT_SHADER,n]]){const e=t.createShader(i);t.shaderSource(e,o),t.compileShader(e),t.attachShader(r,e)}return t.linkProgram(r),r};let ue,he,fe,xe,me,ge=!1,de=0,pe=0,ye=null,ve=null;const _e={},be={};let we=1,Re=0,Ae=0,Ee=1,Me=0,Se=0,Pe=0,Te=0,ke=1,Ce=1,Ie=new Float32Array(8192),Le=0,Fe=2048,De=32768,Ne=null,Be=null,Ye=null,ze=null,Oe=null;const Ue={},Xe={};let Ze=0,Ge=new Float32Array(1280),Ve=0,$e=256,He=null;const We=new Map,je=new Float32Array([-1,-1,1,-1,-1,1,1,1]);function Ke(){const t=mt.glMask?.renderer;t&&(t._curShader=null,t._cachedBlendMode=null,t._isBlending=null,ue.activeTexture(ue.TEXTURE0),ue.bindTexture(ue.TEXTURE_2D,null),ue.blendEquation(ue.FUNC_ADD),ue.blendFunc(ue.ONE,ue.ONE_MINUS_SRC_ALPHA))}function qe(){return he}function Je(){const t=ue.isEnabled(ue.DEPTH_TEST);var e;Je._hadDepthTest=t,t&&ue.disable(ue.DEPTH_TEST),ve=r._renderer.activeFramebuffer?.()??null,ve?._beforeEnd&&ve._beforeEnd(),ue.bindFramebuffer(ue.FRAMEBUFFER,(e=mt.glMask)?"function"==typeof e._framebufferToBind?e._framebufferToBind():e.framebuffer??null:null),ue.viewport(0,0,mt.glMask.width*mt.glMask.density,mt.glMask.height*mt.glMask.density)}function Qe(){Je._hadDepthTest&&ue.enable(ue.DEPTH_TEST),Je._hadDepthTest=!1,ve?._beforeBegin?ve._beforeBegin():(ue.bindFramebuffer(ue.FRAMEBUFFER,null),r._renderer.viewport(r._renderer._origViewport.width,r._renderer._origViewport.height),r._renderer._applyStencilTestIfClipping?.()),ve=null}function tn(t,e,n,r,i){return t?(e<t.minX&&(t.minX=e),n<t.minY&&(t.minY=n),r>t.maxX&&(t.maxX=r),i>t.maxY&&(t.maxY=i),t):{minX:e,minY:n,maxX:r,maxY:i}}function en(t,e,n,r){if(Le>=Fe){Fe*=2;const t=new Float32Array(4*Fe);t.set(Ie),Ie=t}const i=t-Pe,o=e-Te,s=4*Le,a=we*i+Ae*o+Me+Pe,l=Re*i+Ee*o+Se+Te,c=Ce*n*ke/2;Ie[s]=a,Ie[s+1]=l,Ie[s+2]=c,Ie[s+3]=r/255;const u=a*Ce,h=l*Ce;Ne=tn(Ne,u-c-1,h-c-1,u+c+1,h+c+1),Le++}function nn(t,e){if(0===Ve)return;mt.glMask.isDrawn=!0,Je();let n=We.get(e);n||(n=ue.createTexture(),ue.bindTexture(ue.TEXTURE_2D,n),ue.texImage2D(ue.TEXTURE_2D,0,ue.RGBA,ue.RGBA,ue.UNSIGNED_BYTE,t.canvas),ue.texParameteri(ue.TEXTURE_2D,ue.TEXTURE_MIN_FILTER,ue.LINEAR),ue.texParameteri(ue.TEXTURE_2D,ue.TEXTURE_MAG_FILTER,ue.LINEAR),ue.texParameteri(ue.TEXTURE_2D,ue.TEXTURE_WRAP_S,ue.CLAMP_TO_EDGE),ue.texParameteri(ue.TEXTURE_2D,ue.TEXTURE_WRAP_T,ue.CLAMP_TO_EDGE),We.set(e,n)),ue.useProgram(Be),ue.enable(ue.BLEND),ue.blendFunc(ue.ONE_MINUS_DST_ALPHA,ue.ONE),ue.activeTexture(ue.TEXTURE0),ue.bindTexture(ue.TEXTURE_2D,n),ue.uniform1i(Xe.u_tex,0);const r=ft.stroke.color._array;ue.uniform4f(Xe.u_color,...r),ue.uniformMatrix4fv(Xe.u_proj,!1,qe()),ue.bindVertexArray(Ye),ue.bindBuffer(ue.ARRAY_BUFFER,Oe);const i=5*Ve*4,o=Ge.subarray(0,5*Ve);i>Ze?(ue.bufferData(ue.ARRAY_BUFFER,Ge,ue.DYNAMIC_DRAW),Ze=Ge.byteLength):ue.bufferSubData(ue.ARRAY_BUFFER,0,o),ue.drawArraysInstanced(ue.TRIANGLE_STRIP,0,4,Ve),ue.flush(),ue.bindVertexArray(null),ue.bindTexture(ue.TEXTURE_2D,null),Qe(),He&&(mt.markDirtyRect(mt.glMask,He),He=null),Ve=0,Ke()}le||(it={ensureResources:function(t,e,n,r){return function(t,e,n,r){return!t.glMask||t.glMask.width!==e||t.glMask.height!==n||"function"==typeof t.glMask.pixelDensity&&t.glMask.pixelDensity()!==r}(t,e,n,r)&&(t.glMask?.remove&&t.glMask.remove(),t.glMask=t.createFramebuffer({width:e,height:n,density:r,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,n,r,i){return t?t.dirtyRect?e()?n():i(r(t.dirtyRect,2)):n():null},getShaderMask:function(t,e){return e}},le=!0),ft.stroke={color:null,weight:1,type:"HB",isActive:!1,opacity:1};let rn=new Map;function on(){return r??n??window.self.p5.instance}const sn={offset:.08,scale:.08,warp:.06,tilt:.06};function an(){return{...ft.stroke}}function ln(t){ft.stroke={...t}}function cn(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:{...sn}};if("object"==typeof t&&!Array.isArray(t)){if("custom"===t.type||"custom"===t.mode){const{mode:e,...n}=t;return{...n,type:"custom",variation:{...sn,...n.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,n,r]=2===t.length?[t[0],(t[0]+t[1])/2,t[1]]:t,i=Math.min(e,n,r),o=Math.max(e,n,r),s=o-i||1,[a,l,c]=[(e-i)/s,(n-i)/s,(r-i)/s];return{type:"custom",min_max:[i,o],variation:{...sn},curve:t=>t<.5?a+(l-a)*t*2:l+(c-l)*(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 n=`custom::${t}`;!function(t){const e=We.get(t);e&&ue&&ue.deleteTexture(e),We.delete(t)}(n);const r=on().createGraphics(500,500);return r.pixelDensity(1),r.background(255),r.noSmooth(),r.push(),r.translate(250,250),r.scale(5),r.noStroke(),e.tip(r),r.pop(),Yn.imageToWhite(r),Yn.tips.set(n,r),e.tipKey=n,void rn.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 Yn.add(e.image.src),rn.set(t,{param:e,colors:[],buffers:[]}),Yn.load()}rn.set(t,{param:e,colors:[],buffers:[]})}function un(){return[...rn.keys()]}function hn(t){return rn.get(t)?.param??null}function fn(t){for(const{param:e}of rn.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)}function xn(t){if(!rn.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...rn.keys()].join(", ")}.`);ft.stroke.type=t}function mn(t,e,n){p(),ft.stroke.color=r.color(...arguments),ft.stroke.isActive=!0}function gn(t){ft.stroke.weight=t}function dn(t,e,n=1){xn(t),mn(e),gn(n)}function pn(){ft.stroke.isActive=!1}function yn(t){return p(),t}function vn(){}let _n,bn,wn,Rn;const An={};function En(n,r,o,s=!1){we=_t(),Re=bt(),Ae=wt(),Ee=Rt(),Me=yt(),Se=vt(),Pe=t/2,Te=e/2,ke=Math.sqrt(we*we+Re*Re),Ce=i,_n=new Mt(n+t/2,r+e/2),bn=o,wn=s,wn&&wn.calcIndex(0)}const Mn=[];function Sn(n,i){i||(Rn=n),function(){An.seed=999999*D();const{param:n}=rn.get(ft.stroke.type)??{};if(!n)return;An.p=n;const{pressure:i}=n;if(An.a="custom"!==i.type?D(-1,1):0,An.b="custom"!==i.type?D(1,1.5):0,"custom"!==i.type)An.cp=D(3,3.5),An.ct=0,An.cs=1,An.ck=0;else{const t=i.variation??sn;An.cp=D(-t.offset,t.offset),An.ct=D(-t.warp,t.warp),An.cs=D(1-t.scale,1+t.scale),An.ck=D(-t.tilt,t.tilt)}[An.min,An.max]=i.min_max,An.noiseoffset=.05*An.p.noise,wn||(An.cos=j(Rn),An.sin=K(Rn)),function(){xt(),function(){const t=r?.glMask;t&&(ye=t,ye.dirtyRect??=null,ye.isDrawn??=!1,mt.glMask=ye)}();const n=r.drawingContext,i=!ge||ue!==n;(i||de!==t||pe!==e)&&(he=new Float32Array([2/t,0,0,0,0,2/e,0,0,0,0,1,0,-1,-1,0,1]),de=t,pe=e),i&&(ue=n,me=ce(ue,"#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);}"),ue.useProgram(me),ue.enable(ue.BLEND),ue.blendFunc(ue.ONE_MINUS_DST_ALPHA,ue.ONE),["a_position","a_radius","a_alpha"].forEach(t=>_e[t]=ue.getAttribLocation(me,t)),["u_matrix","u_color"].forEach(t=>be[t]=ue.getUniformLocation(me,t)),fe=ue.createVertexArray(),ue.bindVertexArray(fe),xe=ue.createBuffer(),ue.bindBuffer(ue.ARRAY_BUFFER,xe),ue.bufferData(ue.ARRAY_BUFFER,Ie.byteLength,ue.DYNAMIC_DRAW),De=Ie.byteLength,ue.enableVertexAttribArray(_e.a_position),ue.vertexAttribPointer(_e.a_position,2,ue.FLOAT,!1,16,0),ue.enableVertexAttribArray(_e.a_radius),ue.vertexAttribPointer(_e.a_radius,1,ue.FLOAT,!1,16,8),ue.enableVertexAttribArray(_e.a_alpha),ue.vertexAttribPointer(_e.a_alpha,1,ue.FLOAT,!1,16,12),ue.bindVertexArray(null),We.clear(),Be=ce(ue,"#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]=ue.getAttribLocation(Be,t)),["u_proj","u_color","u_tex"].forEach(t=>Xe[t]=ue.getUniformLocation(Be,t)),Ye=ue.createVertexArray(),ue.bindVertexArray(Ye),ze=ue.createBuffer(),ue.bindBuffer(ue.ARRAY_BUFFER,ze),ue.bufferData(ue.ARRAY_BUFFER,je,ue.STATIC_DRAW),ue.enableVertexAttribArray(Ue.a_corner),ue.vertexAttribPointer(Ue.a_corner,2,ue.FLOAT,!1,0,0),Oe=ue.createBuffer(),ue.bindBuffer(ue.ARRAY_BUFFER,Oe),ue.bufferData(ue.ARRAY_BUFFER,Ge.byteLength,ue.DYNAMIC_DRAW),Ze=Ge.byteLength,ue.enableVertexAttribArray(Ue.a_pos),ue.vertexAttribPointer(Ue.a_pos,2,ue.FLOAT,!1,20,0),ue.vertexAttribDivisor(Ue.a_pos,1),ue.enableVertexAttribArray(Ue.a_size),ue.vertexAttribPointer(Ue.a_size,1,ue.FLOAT,!1,20,8),ue.vertexAttribDivisor(Ue.a_size,1),ue.enableVertexAttribArray(Ue.a_angle),ue.vertexAttribPointer(Ue.a_angle,1,ue.FLOAT,!1,20,12),ue.vertexAttribDivisor(Ue.a_angle,1),ue.enableVertexAttribArray(Ue.a_alpha),ue.vertexAttribPointer(Ue.a_alpha,1,ue.FLOAT,!1,20,16),ue.vertexAttribDivisor(Ue.a_alpha,1),ue.bindVertexArray(null),ge=!0)}();const o=!0!==mt.isBrush;mt.isBrush=!0,o&&(mt.justChanged=!0),mt.blend(ft.stroke.color),An.alpha=["default","spray"].includes(An.p.type)?An.p.opacity:An.p.opacity/Math.min(ft.stroke.weight,1.3),Ln()}();const o=function(){const{param:t}=rn.get(ft.stroke.type)??{};return t?t.spacing:1}(),s=Math.round(bn*(i?n:1)/o);An.pressureCount=10,An.cachedPressure=void 0,An.lineNoiseCount=5,An.cachedLineNoise=void 0;for(let t=0;t<s;t++)Mn.length<2*s&&Mn.push(O()),Pn(),i?_n.plotTo(wn,o,o,n,t<10):_n._moveToDegrees(n,o,o);!function(){Ln(),function(){if(0===Le)return;mt.glMask.isDrawn=!0,Je();const t=ft.stroke.color._array;ue.useProgram(me),ue.enable(ue.BLEND),ue.blendFunc(ue.ONE_MINUS_DST_ALPHA,ue.ONE),ue.bindVertexArray(fe),ue.bindBuffer(ue.ARRAY_BUFFER,xe);const e=16*Le,n=Ie.subarray(0,4*Le);e>De?(ue.bufferData(ue.ARRAY_BUFFER,Ie,ue.DYNAMIC_DRAW),De=Ie.byteLength):ue.bufferSubData(ue.ARRAY_BUFFER,0,n),ue.uniform4f(be.u_color,...t),ue.uniformMatrix4fv(be.u_matrix,!1,qe()),ue.drawArrays(ue.POINTS,0,Le),ue.flush(),ue.bindVertexArray(null),Qe(),Ne&&(mt.markDirtyRect(mt.glMask,Ne),Ne=null),Le=0,Ke()}();const t=An.p?.type;"image"===t?nn(Yn.tips.get(An.p.image.src),An.p.image.src):"custom"===t&&nn(Yn.tips.get(An.p.tipKey),An.p.tipKey)}()}function Pn(){const t=Tn(),e=((An.lineNoiseCount>=10||void 0===An.cachedLineNoise)&&(An.cachedLineNoise=X(L(An.seed+.01*_n.plotted,0),-1,1,1-An.noiseoffset,1+An.noiseoffset),An.lineNoiseCount=0),An.lineNoiseCount++,An.cachedLineNoise);if(!(e>D(1,1.02)&&D(0,1)<.7))switch(An.p.type){case"spray":!function(t){const e=ft.stroke.weight*An.p.scatter*t+ft.stroke.weight*B(Mn)*An.p.scatter/3,n=An.p.weight*D(.9,1.1),r=Math.ceil(An.p.grain/t);for(let t=0;t<r;t++){const t=D(.9,1.1),r=t*e*D(-1,1),i=D(-1,1),o=Math.sqrt((t*e)**2-r**2);en(_n.x+r,_n.y+i*o,n,An.alpha)}}(t*e);break;case"marker":Cn(t*e);break;case"custom":case"image":In(t*e);break;default:!function(t,e=1){const n=(e=X(e,0,1,.9,1.05))*ft.stroke.weight*An.p.scatter*(An.p.sharpness+(1-An.p.sharpness)*B(Mn)/t);if(D(0,An.p.grain*t)>.4){let e,r;if(wn){const t=wn.angle(_n.plotted),i=j(t),o=K(t),s=n*D(-1,1),a=.3*n*D(-1,1);e=s*o+a*i,r=s*i-a*o}else{const t=n*D(-1,1),i=.3*n*D(-1,1);e=t*An.sin+i*An.cos,r=t*An.cos-i*An.sin}const i=t*t*An.p.weight*D(.85,1.15)*ft.stroke.weight,o=Math.max(.9,t)*An.alpha*D(.75,1.1);en(_n.x+e,_n.y+r,i,o)}}(t*e)}}function Tn(){return(An.pressureCount>=10||void 0===An.cachedPressure)&&(An.cachedPressure=wn?kn()*wn.pressure(_n.plotted):kn(),An.pressureCount=0),An.pressureCount++,An.cachedPressure}function kn(){return"custom"===An.p.pressure.type?X(An.p.pressure.curve(Math.max(0,Math.min(1,.5+(_n.plotted/bn-.5+An.ct)*An.cs)))+An.cp+An.ck*(_n.plotted/bn-.5),0,1,An.min,An.max,!0):function(t=.5+An.p.pressure.curve[0]*An.a,e=1-An.p.pressure.curve[1]*An.b,n=An.cp,r=An.min,i=An.max){const o=t*bn,s=(_n.plotted<o?1.2*e:.8*e)*(bn/2);return X(1/(1+Math.pow(Math.abs((_n.plotted-o)/s),2*n)),0,1,r,i)}()}function Cn(t,e=!0,n=An.alpha){const r=e?ft.stroke.weight*An.p.scatter:0,i=e?r*D(-1,1):0,o=e?r*D(-1,1):0;en(_n.x+i,_n.y+o,ft.stroke.weight*An.p.weight*t,n*Math.max(.8,t)*D(.9,1.1))}function In(t,e=An.alpha){const n=ft.stroke.weight*An.p.scatter,r=n*D(-1,1),i=n*D(-1,1),o=An.p.weight*ft.stroke.weight*t,s=function(){const t=Math.max(1,An.max??1),e=ft.stroke.weight*An.p.scatter,n=ft.stroke.weight*An.p.weight*t;return Math.max(8,1.5*e+.75*n)}();let a=0;"random"===An.p.rotate?a=Y(0,360)*(Math.PI/180):"natural"===An.p.rotate&&(a=((wn?-wn.angle(_n.plotted):-Rn)+_n.angle())*(Math.PI/180)),function(t,e,n,r,i,o=0){if(Ve>=$e){$e*=2;const t=new Float32Array(5*$e);t.set(Ge),Ge=t}const s=t-Pe,a=e-Te,l=we*s+Ae*a+Me+Pe,c=Re*s+Ee*a+Se+Te,u=Ce*n*ke/2,h=Ce*o*ke,f=5*Ve;Ge[f]=l,Ge[f+1]=c,Ge[f+2]=u,Ge[f+3]=r,Ge[f+4]=i/255;const x=l*Ce,m=c*Ce,g=1.42*u+h;He=tn(He,x-g-1,m-g-1,x+g+1,m+g+1),Ve++}(_n.x+r,_n.y+i,o,a,e*Math.max(.8,t)*D(.9,1.1),s)}function Ln(){if(!1===An.p.markerTip)return;let t=Tn(),e=An.alpha;if("marker"===An.p.type)for(let n=1;n<10;n++)Cn(t*n/10,!0,8*e);else if("custom"===An.p.type||"image"===An.p.type)for(let n=1;n<5;n++)In(t*n/10,2*e)}function Fn(t,e,n,r){if(!ft.stroke.isActive||!ft.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");Et();let i=tt(t,e,n,r);0!=i&&(En(t,e,i),Sn(et(t,e,n,r),!1))}function Dn(t,e,n,r){if(!ft.stroke.isActive||!ft.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");Et(),En(t,e,n),Sn(q(r),!1)}I(()=>{Mn.length=0});const Nn=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate","markerTip","noise"],Bn=[["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 Bn){let e={};for(let n=0;n<t[1].length;n++)e[Nn[n]]=t[1][n];cn(t[0],e)}Zt.prototype.draw=function(t=!1,e,n){let r=an();if(t&&dn(t,e,n),r.isActive)for(let t of this.sides)Fn(t[0].x,t[0].y,t[1].x,t[1].y);ln(r)},Gt.prototype.draw=function(t,e,n){an().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],n=1),function(t,e,n,r){Et(),En(e,n,t.length,t),Sn(r,!0)}(this,t,e,n))};const Yn={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 n=(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-n}t.updatePixels()},async load(){const t=[...this.tips.keys()].filter(t=>!this.tips.get(t));await Promise.all(t.map(t=>new Promise((e,n)=>{const r=new window.Image;r.onload=()=>{const n=on().createImage(r.naturalWidth,r.naturalHeight);n.drawingContext.drawImage(r,0,0),Yn.imageToWhite(n),this.tips.set(t,n),e()},r.onerror=()=>n(new Error(`Failed to load image tip: ${t}`)),r.crossOrigin="anonymous",r.src=t})))}};function zn(){return{...ft.hatch}}function On(t){ft.hatch={...t}}function Un(t=5,e=45,n={rand:!1,continuous:!1,gradient:!1}){let r=ft.hatch;r.isActive=!0,r.dist=t,r.angle=J(e),r.options=n}function Xn(t,e="black",n=1){ft.hatch.hBrush={brush:t,color:e,weight:n}}function Zn(){ft.hatch.isActive=!1,ft.hatch.hBrush=!1}function Gn(t,e,n,r){const i=e*Math.PI/180,o=Math.cos(i),s=Math.sin(i),a=Math.cos(-i),l=Math.sin(-i),c=t.a,u=c.length,h=new Array(u);let f=Infinity,x=-Infinity;for(let t=0;t<u;t++){const e=c[t][0],n=c[t][1],r=[e*o-n*s,e*s+n*o];h[t]=r,r[1]<f&&(f=r[1]),r[1]>x&&(x=r[1])}const m=[];for(let t=0;t<u;t++){const e=h[t],n=h[(t+1)%u];e[1]!==n[1]&&m.push(e,n)}const g=m.length,d=[];let p=f+.5*n,y=n;for(;p<x;){const t=[];for(let e=0;e<g;e+=2){const n=m[e][1],r=m[e+1][1];(n<=p&&p<r||r<=p&&p<n)&&t.push(m[e][0]+(p-n)/(r-n)*(m[e+1][0]-m[e][0]))}t.sort((t,e)=>t-e);for(let e=0;e<t.length-1;e+=2)d.push({scanY:p,x1:t[e]*a-p*l,y1:t[e]*l+p*a,x2:t[e+1]*a-p*l,y2:t[e+1]*l+p*a});p+=y,y*=r}return d}function Vn(t){const{dist:e,options:n,segs:r}=function(t){const e=ft.hatch.dist,n=(ft.hatch.angle%180+180)%180,r=ft.hatch.options,i=function(t,e,n,r){Array.isArray(t)||(t=[t]);const i=[];for(const o of t)for(const t of Gn(o,n,e,r))i.push(t);return i.sort((t,e)=>t.scanY===e.scanY?t.x1-e.x1:t.scanY-e.scanY),i}(t,e,n,r.gradient?X(r.gradient,0,1,1,1.1,!0):1);return{dist:e,options:r,segs:i}}(t),i=n.rand||0,o=[];for(let t=0;t<r.length;t++){const s=r[t];let a=s.x1,l=s.y1,c=s.x2,u=s.y2;i&&(a+=2*i*e*D(-1,1),l+=2*i*e*D(-1,1),c+=2*i*e*D(-1,1),u+=2*i*e*D(-1,1));const h=n.continuous&&t%2==1?{x1:c,y1:u,x2:a,y2:l,scanY:s.scanY,isConnector:!1}:{x1:a,y1:l,x2:c,y2:u,scanY:s.scanY,isConnector:!1};if(o.push(h),t>0&&n.continuous){const t=o[o.length-2];o.push({x1:t.x2,y1:t.y2,x2:h.x1,y2:h.y1,scanY:s.scanY,isConnector:!0})}}return o}function $n(t){!function(t,e){const n=Vn(t);!function(){const t=an();ft.hatch.hBrush&&dn(...Object.values(ft.hatch.hBrush)),(()=>{for(let t=0;t<n.length;t++){const r=n[t];e(r.x1,r.y1,r.x2,r.y2,t,n)}})(),ln(t)}()}(t,(t,e,n,r)=>{Fn(t,e,n,r)})}function Hn(t,e,n={}){ft.mass.brush=t,ft.mass.color=e,ft.mass.options=n,ft.mass.isActive=!0}function Wn(){ft.mass.isActive=!1,ft.mass.brush=null,ft.mass.color=null,ft.mass.options={}}function jn(t,e,n){return new Zt(t.vertices.map(t=>[t.x+e,t.y+n]))}function Kn(t){return r&&"function"==typeof r.angleMode&&r.angleMode()===r.RADIANS?t*Math.PI/180:t}function qn(t,e,n,r,i){const o=(e+r)/2,s=(n+i)/2,a=r-e,l=i-n,c=Math.hypot(a,l);if(!c)return null;const u=-l/c,h=a/c,f=(t.x-o)*u+(t.y-s)*h;return{x:o+u*f,y:s+h*f}}function Jn(t,e,n,r,i,o){let s=et(t,e,n,r),a=et(t,e,i,o);return((a-s)%360+360)%360>180&&([s,a]=[a,s]),[Kn(s),Kn(a)]}function Qn(t){const e=N(.35,.65),n=t.x1+(t.x2-t.x1)*e,r=t.y1+(t.y2-t.y1)*e,i=t.x2-t.x1,o=t.y2-t.y1,s=Math.hypot(i,o)||1,a=N(.04,.1)*s,l=i/s*a*.5,c=o/s*a*.5;return[{x1:t.x1,y1:t.y1,x2:n-l,y2:r-c},{x1:n+l,y1:r+c,x2:t.x2,y2:t.y2}]}function tr(t,e){const n=function(t,e){const n=function(t){const e=t?.a??[];let n=Infinity,r=Infinity,i=-Infinity,o=-Infinity;for(const[t,s]of e)t<n&&(n=t),s<r&&(r=s),t>i&&(i=t),s>o&&(o=s);return{minX:n,minY:r,maxX:i,maxY:o,cx:(n+i)/2,cy:(r+o)/2,size:Math.hypot(i-n,o-r)}}(t),r=n.size*N(.6,1.4),[i,o]=e;return{x:n.cx+i*r,y:n.cy+o*r}}(t,e);for(const e of Vn(t)){const t=!e.isConnector&&N()<.35?Qn(e):[e];for(const e of t){const t=qn(n,e.x1,e.y1,e.x2,e.y2);if(!t)continue;const r=tt(t.x,t.y,e.x1,e.y1);if(!r)continue;const[i,o]=Jn(t.x,t.y,e.x1,e.y1,e.x2,e.y2);Wt(t.x,t.y,r,i,o)}}}function er(t,e,n,r,i){Un(e,n,r),tr(t,i)}function nr(t,e,n,r){const i=function(t,e,n,r){const i=!1===e,o=hn(ft.mass.brush)?.scatter??0,s=i?t:t.genPol(e,n,r,.15),a=Math.min(2*o,5),l=[[N(-a,a),N(-a,a)],[N(-a,a),N(-a,a)]];return[s,jn(s,l[0][0],l[0][1]),jn(s,l[1][0],l[1][1])]}(t,e,n,r),o=zn(),s=an(),a={...ft.field},l=ft.mass.options?.precision??.5,c=ft.mass.options?.strength??1,u=ft.mass.options?.gradient??.1,h=ft.mass.options?.outline??!1,f=hn(ft.mass.brush)?.scatter??0,x=1.6*N(.65*f,.85*f)-.4*u,m=N(-90,90),g=((m+90)%180+180)%180-90>=0?N()<.5?[1,1]:[-1,-1]:N()<.5?[-1,1]:[1,-1];dn(ft.mass.brush,ft.mass.color,1),Ut(2-l),h&&i[0].draw(),er(i[0],.9*x,Kn(m),{gradient:u,rand:2-2*l,continuous:!0},g),c>.33&&er(i[1],x,Kn(m+20*N(-1,1)),{gradient:u,rand:.6-.6*l,continuous:!0},g),c>.66&&er(i[2],.8*x,Kn(m+15*N(-1,1)),{gradient:u,rand:.6-.6*l,continuous:!0},g),ln(s),On(o),ft.field={...a}}function rr(t,e,n){const r=2*Math.PI,i=mt.ctx,o=n/2;i.moveTo(t+o,e),i.arc(t,e,o,0,r)}ft.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},Zt.prototype.hatch=function(t=!1,e,n){let r=zn();t&&Un(t,e,n),ft.hatch.isActive&&$n(this),On(r)},Gt.prototype.hatch=function(t,e,n){zn().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],n=1),this.pol=this.genPol(t,e,n,.3),this.pol.hatch())},ft.mass={isActive:!1,brush:null,color:null,options:{}},Zt.prototype.mass=function(){ft.mass?.isActive&&nr(this,!1)},Gt.prototype.mass=function(t,e,n){ft.mass?.isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],n=1),nr(this,t,e,n))};let ir=null,or=!1;or||(ot={ensureResources:function(t,e,n,r,i){const o=Math.max(1,Math.round(e*r)),s=Math.max(1,Math.round(n*r));return function(t,e,n){return!t.mask||t.mask.width!==e||t.mask.height!==n}(t,o,s)&&(t.mask=new OffscreenCanvas(o,s),t.mask.drawingContext=t.mask.getContext("2d")),function(t,e,n,r){return!t.fillMaskFramebuffer||t.fillMaskFramebuffer.width!==e||t.fillMaskFramebuffer.height!==n||"function"==typeof t.fillMaskFramebuffer.pixelDensity&&t.fillMaskFramebuffer.pixelDensity()!==r}(t,e,n,r)&&(t.fillMaskFramebuffer?.remove&&t.fillMaskFramebuffer.remove(),t.fillMaskFramebuffer=t.createFramebuffer({width:e,height:n,density:r,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,n,r,i){return t?t.dirtyRect?i(r(t.dirtyRect,4)):n():null},getShaderMask:function(t,e,n,r,i,o){const s=t.fillMaskFramebuffer,a=t.drawingContext,l=r(n)??i(),c=l.maxX-l.minX,u=l.maxY-l.minY;ir&&ir.width===c&&ir.height===u||(ir=new OffscreenCanvas(c,u),ir.drawingContext=ir.getContext("2d"));const h=ir.drawingContext;return h.clearRect(0,0,c,u),h.drawImage(e,l.minX,l.minY,c,u,0,0,c,u),o(s),a.bindTexture(a.TEXTURE_2D,s.colorTexture),a.texSubImage2D(a.TEXTURE_2D,0,l.minX,l.minY,a.RGBA,a.UNSIGNED_BYTE,ir),s}},or=!0),ft.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const sr=()=>({...ft.fill});function ar(t,e,n,i){ft.fill.opacity=(arguments.length<4?e:i)||150,ft.fill.color=arguments.length<3?r.color(t):r.color(t,e,n),ft.fill.isActive=!0}function lr(t,e="out"){ft.fill.bleed_strength=Z(t,0,1),ft.fill.direction=e}function cr(t=.4,e=.4){ft.fill.texture_strength=Z(t,0,1),ft.fill.border_strength=Z(e,0,1)}function ur(){ft.fill.isActive=!1}let hr;const fr=[[],[]];function xr(){for(let t=0;t<512;t++)fr[0][t]=O(.5,.2),fr[1][t]=O(0,.02)}function mr(t,e,n){return(e.x-t.x)*(n.y-t.y)-(e.y-t.y)*(n.x-t.x)>.01}I(xr);class gr{constructor(t,e,n,r=[],i=!1,o,s){if(this.v=t,this.m=e,this.dir=r,this.midP=n,i){let e=0,r=0;const i=[];for(let o=0;o<t.length;o++){const s=Math.abs(n.x-t[o].x),a=Math.abs(n.y-t[o].y);e=Math.max(e,s),r=Math.max(r,a);const l=t[o],c=t[(o+1)%t.length],u={x:c.x-l.x,y:c.y-l.y},h=Q(0,0,u.x,u.y,90),f={x:l.x+u.x/2,y:l.y+u.y/2};i.push({v1:l,v2:c,ray:{point1:f,point2:{x:f.x+h.x,y:f.y+h.y}}})}this.sizeX=e,this.sizeY=r,this.dir=Array(t.length),i.forEach((t,e)=>{let n=0;for(const e of hr.intersect(t.ray))mr(t.v1,t.v2,e)&&n++;this.dir[e]=n%2==0});const o=D(-.6,.6)*e,s=D(-.6,.6)*r;this.midP={x:n.x+o,y:n.y+s}}else this.sizeX=o,this.sizeY=s}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),n=~~(this.v.length/2-e/2),r=this.v.length-e,i=new Array(r),o=new Array(r),s=new Array(r);let a=0;for(let t=0;t<n;t++,a++)i[a]=this.v[t],o[a]=this.m[t],s[a]=this.dir[t];for(let t=n+e;t<this.v.length;t++,a++)i[a]=this.v[t],o[a]=this.m[t],s[a]=this.dir[t];const l=n,c=n+e,u=this.v[(l-1+this.v.length)%this.v.length],h=this.v[c%this.v.length],f=h.x-u.x,x=h.y-u.y;for(let t=0;t<2;t++){const e=D(.25,.75),r={x:u.x+f*e,y:u.y+x*e},a=n+t;i.splice(a,0,r),o.splice(a,0,D(.4,.7)),s.splice(a,0,this.dir[l%this.dir.length])}return{v:i,m:o,dir:s}}scatter(t=.3){const e=this.v.length,n=Math.max(3,~~(e*t)),r=[],i=e/n;for(let t=0;t<n;t++)r.push(~~(t*i+D(0,.8*i)));const o=[],s=[],a=[],l=this.midP,c=hr.sides;for(const t of r){const n=t%e;let r=this.v[n],i=0;for(const[t,e]of c){const n=t.y,o=e.y;if(n>r.y==o>r.y)continue;const s=(r.y-n)/(o-n);r.x<t.x+s*(e.x-t.x)&&i++}i%2==0&&(r={x:l.x+(r.x-l.x)*D(.3,.6),y:l.y+(r.y-l.y)*D(.3,.6)}),o.push(r),s.push(this.m[n]),a.push(!this.dir[n])}return new gr(o,s,this.midP,a,!1,this.sizeX,this.sizeY)}flipDirs(){return new gr(this.v,this.m,this.midP,this.dir.map(t=>!t),!1,this.sizeX,this.sizeY)}grow(t=1){const{v:e,m:n,dir:r}=this.trim(t),i=e.length,o=2*i,s=new Array(i),a=new Array(i),l=new Array(o),c=new Array(o),u="out"===ft.fill.direction?-90:90;0===fr[0].length&&xr();const h=fr[0],f=h.length,x=fr[1],m=x.length;let g,d,p,y=0,v=0,_=999===t?D(.6,.8):ft.fill.bleed_strength;for(let o=0;o<i;o++){const g=e[o],d=e[o+1<i?o+1:0],p=n[o],b=r[o];if(t<997&&(_=p),_<.05){l[y]=p,c[y]=b,y++,s[v]=(g.x+d.x)/2,a[v]=(g.y+d.y)/2,l[y]=p,c[y]=b,y++,v++;continue}const w=(b?u:-u)+5*D(-1,1),R=j(w),A=K(w),E=d.x-g.x,M=d.y-g.y,S=R*E+A*M,P=R*M-A*E,T=h[~~(D(0,1)*f)]*D(.65,1.35)*_,k=p+x[~~(D(0,1)*m)];l[y]=p,c[y]=b,y++,s[v]=g.x+.5*E+S*T,a[v]=g.y+.5*M+P*T,l[y]=k,c[y]=b,y++,v++}const b=2024*Math.max(.1,2*ft.fill.bleed_strength);if(b&&y>b){const t=Math.ceil(y/b),n=Math.ceil(y/t);g=new Array(n),d=new Array(n),p=new Array(n);let r=0;for(let n=0;n<y;n+=t,r++)g[r]=n%2==0?e[n>>1]:{x:s[n>>1],y:a[n>>1]},d[r]=l[n],p[r]=c[n]}else{g=new Array(y);for(let t=0;t<y;t++)g[t]=t%2==0?e[t>>1]:{x:s[t>>1],y:a[t>>1]};l.length=y,c.length=y,d=l,p=c}return new gr(g,d,this.midP,p,!1,this.sizeX,this.sizeY)}fill(n,r,o){const s=3*o,a=2*r*(1+o/2),l=!1!==mt.isBrush;mt.isBrush=!1,l&&(mt.justChanged=!0),mt.blend(n),mt.ctx.save(),mt.ctx.setTransform(i*_t(),i*bt(),i*wt(),i*Rt(),i*(yt()+t/2),i*(vt()+e/2)),mt.ctx.strokeStyle=`rgb(${n._getRed()} ${n._getGreen()} ${n._getBlue()} / ${.005*ft.fill.border_strength})`,mt.ctx.lineCap="round";const c=Math.max(this.sizeX,this.sizeY),u=D(.15,.7);let h=this.grow();const f=this.scatter(.1).grow().scatter(.75).flipDirs();let x;for(let t=0;t<20;t++){t%4==0&&(h=h.grow()),t%2==0&&(x=[h.grow(1-.0125*t),h.grow(.7-.0125*t),h.grow(.4-.0125*t)]);for(const e of x)e.grow(999).grow(997).layer(t,c,a,n);f.grow(999).flipDirs().grow(997).layer(t,c,a*s,n),t%2==0&&h.grow(u).grow(999).layer(t,c,2*a,n),t%8!=0&&19!==t||(0!==s&&h.erase(3*s,r),mt.blend(n,!0))}mt.ctx.restore()}layer(t,e,n,r){mt.ctx.lineWidth=X(t,0,24,e/25,e/30,!0),mt.ctx.fillStyle=`rgb(${r._getRed()} ${r._getGreen()} ${r._getBlue()} / ${n}%)`,function(t){const e=mt.ctx,n=e.getTransform(),r=n.a,i=n.b,o=n.c,s=n.d,a=n.e,l=n.f;let c=Infinity,u=Infinity,h=-Infinity,f=-Infinity;e.beginPath();const x=t[0];let m=r*x.x+o*x.y+a,g=i*x.x+s*x.y+l;c=h=m,u=f=g,e.moveTo(x.x,x.y);for(let n=1;n<t.length;n++){const x=t[n];m=r*x.x+o*x.y+a,g=i*x.x+s*x.y+l,c=Math.min(c,m),u=Math.min(u,g),h=Math.max(h,m),f=Math.max(f,g),e.lineTo(x.x,x.y)}e.closePath();const d=function(t,e){const n=t.lineWidth||0;return n<=0?1:1+n*Math.max(Math.hypot(e.a,e.c),Math.hypot(e.b,e.d))/2}(e,n);mt.markDirtyRect(mt.mask,{minX:c-d,minY:u-d,maxX:h+d,maxY:f+d})}(this.v),mt.ctx.fill(),mt.ctx.stroke()}erase(t,e){mt.ctx.save();const n=~~(D(80,110)*X(t,0,1,2,3.5)),r=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:l,y:c}=this.midP;mt.ctx.globalCompositeOperation="destination-out";const u=(5-X(e,80,100,.3,.7,!0))*t/255;mt.ctx.fillStyle=`rgb(255 0 0 / ${u})`,mt.ctx.lineWidth=0;for(let t=0;t<n;t++){const e=l+O(0,r),n=c+O(0,i),o=D(s,a);mt.ctx.beginPath(),rr(e,n,o),t%5!=0&&mt.ctx.fill()}mt.ctx.globalCompositeOperation="source-over",mt.ctx.restore()}}function dr(t,e){if(!t)return t;e||(e=t);let n,r=t;do{if(n=!1,r.steiner||!Mr(r,r.next)&&0!==Er(r.prev,r,r.next))r=r.next;else{if(Lr(r),r=e=r.prev,r===r.next)break;n=!0}}while(n||r!==e);return e}function pr(t,e,n,r,i,o,s){if(!t)return;!s&&o&&function(t,e,n,r){let i=t;do{0===i.z&&(i.z=wr(i.x,i.y,e,n,r)),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,n=1;do{let r,i=t;t=null;let o=null;for(e=0;i;){e++;let s=i,a=0;for(let t=0;t<n&&(a++,s=s.nextZ,s);t++);let l=n;for(;a>0||l>0&&s;)0!==a&&(0===l||!s||i.z<=s.z)?(r=i,i=i.nextZ,a--):(r=s,s=s.nextZ,l--),o?o.nextZ=r:t=r,r.prevZ=o,o=r;i=s}o.nextZ=null,n*=2}while(e>1)}(i)}(t,r,i,o);let a=t;for(;t.prev!==t.next;){const l=t.prev,c=t.next;if(o?vr(t,r,i,o):yr(t))e.push(l.i,t.i,c.i),Lr(t),t=c.next,a=c.next;else if((t=c)===a){s?1===s?pr(t=_r(dr(t),e),e,n,r,i,o,2):2===s&&br(t,e,n,r,i,o):pr(dr(t),e,n,r,i,o,1);break}}}function yr(t){const e=t.prev,n=t,r=t.next;if(Er(e,n,r)>=0)return!1;const i=e.x,o=n.x,s=r.x,a=e.y,l=n.y,c=r.y,u=Math.min(i,o,s),h=Math.min(a,l,c),f=Math.max(i,o,s),x=Math.max(a,l,c);let m=r.next;for(;m!==e;){if(m.x>=u&&m.x<=f&&m.y>=h&&m.y<=x&&Rr(i,a,o,l,s,c,m.x,m.y)&&Er(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function vr(t,e,n,r){const i=t.prev,o=t,s=t.next;if(Er(i,o,s)>=0)return!1;const a=i.x,l=o.x,c=s.x,u=i.y,h=o.y,f=s.y,x=Math.min(a,l,c),m=Math.min(u,h,f),g=Math.max(a,l,c),d=Math.max(u,h,f),p=wr(x,m,e,n,r),y=wr(g,d,e,n,r);let v=t.prevZ,_=t.nextZ;for(;v&&v.z>=p&&_&&_.z<=y;){if(v.x>=x&&v.x<=g&&v.y>=m&&v.y<=d&&v!==i&&v!==s&&Rr(a,u,l,h,c,f,v.x,v.y)&&Er(v.prev,v,v.next)>=0)return!1;if(v=v.prevZ,_.x>=x&&_.x<=g&&_.y>=m&&_.y<=d&&_!==i&&_!==s&&Rr(a,u,l,h,c,f,_.x,_.y)&&Er(_.prev,_,_.next)>=0)return!1;_=_.nextZ}for(;v&&v.z>=p;){if(v.x>=x&&v.x<=g&&v.y>=m&&v.y<=d&&v!==i&&v!==s&&Rr(a,u,l,h,c,f,v.x,v.y)&&Er(v.prev,v,v.next)>=0)return!1;v=v.prevZ}for(;_&&_.z<=y;){if(_.x>=x&&_.x<=g&&_.y>=m&&_.y<=d&&_!==i&&_!==s&&Rr(a,u,l,h,c,f,_.x,_.y)&&Er(_.prev,_,_.next)>=0)return!1;_=_.nextZ}return!0}function _r(t,e){let n=t;do{const r=n.prev,i=n.next.next;!Mr(r,i)&&Sr(r,n,n.next,i)&&kr(r,i)&&kr(i,r)&&(e.push(r.i,n.i,i.i),Lr(n),Lr(n.next),n=t=i),n=n.next}while(n!==t);return dr(n)}function br(t,e,n,r,i,o){let s=t;do{let t=s.next.next;for(;t!==s.prev;){if(s.i!==t.i&&Ar(s,t)){let a=Cr(s,t);return s=dr(s,s.next),a=dr(a,a.next),pr(s,e,n,r,i,o,0),void pr(a,e,n,r,i,o,0)}t=t.next}s=s.next}while(s!==t)}function wr(t,e,n,r,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-n)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-r)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function Rr(t,e,n,r,i,o,s,a){return!(t===s&&e===a)&&function(t,e,n,r,i,o,s,a){return(i-s)*(e-a)>=(t-s)*(o-a)&&(t-s)*(r-a)>=(n-s)*(e-a)&&(n-s)*(o-a)>=(i-s)*(r-a)}(t,e,n,r,i,o,s,a)}function Ar(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let n=t;do{if(n.i!==t.i&&n.next.i!==t.i&&n.i!==e.i&&n.next.i!==e.i&&Sr(n,n.next,t,e))return!0;n=n.next}while(n!==t);return!1}(t,e)&&(kr(t,e)&&kr(e,t)&&function(t,e){let n=t,r=!1;const i=(t.x+e.x)/2,o=(t.y+e.y)/2;do{n.y>o!=n.next.y>o&&n.next.y!==n.y&&i<(n.next.x-n.x)*(o-n.y)/(n.next.y-n.y)+n.x&&(r=!r),n=n.next}while(n!==t);return r}(t,e)&&(Er(t.prev,t,e.prev)||Er(t,e.prev,e))||Mr(t,e)&&Er(t.prev,t,t.next)>0&&Er(e.prev,e,e.next)>0)}function Er(t,e,n){return(e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y)}function Mr(t,e){return t.x===e.x&&t.y===e.y}function Sr(t,e,n,r){const i=Tr(Er(t,e,n)),o=Tr(Er(t,e,r)),s=Tr(Er(n,r,t)),a=Tr(Er(n,r,e));return i!==o&&s!==a||!(0!==i||!Pr(t,n,e))||!(0!==o||!Pr(t,r,e))||!(0!==s||!Pr(n,t,r))||!(0!==a||!Pr(n,e,r))}function Pr(t,e,n){return e.x<=Math.max(t.x,n.x)&&e.x>=Math.min(t.x,n.x)&&e.y<=Math.max(t.y,n.y)&&e.y>=Math.min(t.y,n.y)}function Tr(t){return t>0?1:t<0?-1:0}function kr(t,e){return Er(t.prev,t,t.next)<0?Er(t,e,t.next)>=0&&Er(t,t.prev,e)>=0:Er(t,e,t.prev)<0||Er(t,t.next,e)<0}function Cr(t,e){const n=Fr(t.i,t.x,t.y),r=Fr(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,n.next=i,i.prev=n,r.next=n,n.prev=r,o.next=r,r.prev=o,r}function Ir(t,e,n,r){const i=Fr(t,e,n);return r?(i.next=r.next,i.prev=r,r.next.prev=i,r.next=i):(i.prev=i,i.next=i),i}function Lr(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 Fr(t,e,n){return{i:t,x:e,y:n,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}Zt.prototype.fill=function(t=!1,e,n,r,i,o){let s=sr();t&&(ar(t,e),lr(n,o),cr(r,i)),s.isActive&&(Et(),function(t){if(!ft.fill.isActive||!ft.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");hr=t;const e=[...t.vertices],n=~~(.25*e.length*U({1:5,2:10,3:60})),r=ft.fill.bleed_strength,i=e.map((t,e)=>(e>n?1:.3)*D(.85,1.4)*r),o=Y(0,e.length),s=[...e.slice(o),...e.slice(0,o)],a=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 n=0,r=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;n+=o,r+=(e[t].x+e[t+1].x)*o,i+=(e[t].y+e[t+1].y)*o}return n*=.5,n?{x:r/(6*n),y:i/(6*n)}:{x:e[0].x,y:e[0].y}}(s);new gr(s,i,a,[],!0).fill(ft.fill.color,X(ft.fill.opacity,0,255,0,1,!0),ft.fill.texture_strength)}(this)),(t=>{ft.fill={...t}})(s)},Gt.prototype.fill=function(t,e,n){sr().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],n=1),this.pol=this.genPol(t,e,n,ft.fill.bleed_strength<.06?0:X(ft.fill.bleed_strength,0,.6,.2,.6,!0)),this.pol.fill())};let Dr=null,Nr=null,Br=null,Yr=null,zr=null,Or=0,Ur=0,Xr=0;const Zr={},Gr={};function Vr(t,e,n,i){p(),ft.wash.opacity=(arguments.length<4?e:i)??150,ft.wash.color=arguments.length<3?r.color(t):r.color(t,e,n),ft.wash.isActive=!0}function $r(){ft.wash.isActive=!1}function Hr(t,e){return[_t()*t+wt()*e+yt()+Or/2,bt()*t+Rt()*e+vt()+Ur/2]}ft.wash={color:null,opacity:150,isActive:!1},Zt.prototype.wash=function(n=!1,i){const o={...ft.wash};!1!==n&&Vr(n,i),ft.wash.isActive&&function(n){if(!ft.wash?.isActive||!ft.wash.color||n.vertices.length<3)return;gt(),function(){const n=r.drawingContext;zr&&!(Or!==t||Ur!==e)||(Or=t,Ur=e,zr=new Float32Array([2/Or,0,0,0,0,-2/Ur,0,0,0,0,1,0,-1,1,0,1])),Dr===n&&Nr&&Br&&Yr||(Dr=n,Nr=ce(Dr,"#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}"),Zr.a_position=Dr.getAttribLocation(Nr,"a_position"),Gr.u_matrix=Dr.getUniformLocation(Nr,"u_matrix"),Gr.u_color=Dr.getUniformLocation(Nr,"u_color"),Br=Dr.createVertexArray(),Dr.bindVertexArray(Br),Yr=Dr.createBuffer(),Dr.bindBuffer(Dr.ARRAY_BUFFER,Yr),Dr.bufferData(Dr.ARRAY_BUFFER,0,Dr.DYNAMIC_DRAW),Xr=0,Dr.enableVertexAttribArray(Zr.a_position),Dr.vertexAttribPointer(Zr.a_position,2,Dr.FLOAT,!1,8,0),Dr.bindVertexArray(null),Dr.bindBuffer(Dr.ARRAY_BUFFER,null))}();const{triangles:i,vertexCount:o}=function(t){const e=new Float32Array(2*t.vertices.length);for(let n=0;n<t.vertices.length;n++){const r=t.vertices[n];e[2*n]=r.x,e[2*n+1]=r.y}const n=function(t,e,n=2){const r=t.length;let i=function(t,e,n,r){let i;if(1==function(t,e,n,r){let i=0;for(let e=0,o=n-r;e<n;e+=r)i+=(t[o]-t[e])*(t[e+1]+t[o+1]),o=e;return i}(t,0,n,r)>0)for(let e=0;e<n;e+=r)i=Ir(e/r|0,t[e],t[e+1],i);else for(let e=n-r;e>=0;e-=r)i=Ir(e/r|0,t[e],t[e+1],i);return i&&Mr(i,i.next)&&(Lr(i),i=i.next),i}(t,0,r,n);const o=[];if(!i||i.next===i.prev)return o;let s,a,l;if(t.length>80*n){s=t[0],a=t[1];let e=s,i=a;for(let o=n;o<r;o+=n){const n=t[o],r=t[o+1];n<s&&(s=n),r<a&&(a=r),n>e&&(e=n),r>i&&(i=r)}l=Math.max(e-s,i-a),l=0!==l?32767/l:0}return pr(i,o,n,s,a,l,0),o}(e),r=new Float32Array(2*n.length);for(let t=0;t<n.length;t++){const i=n[t],[o,s]=Hr(e[2*i],e[2*i+1]);r[2*t]=o,r[2*t+1]=s}return{triangles:r,vertexCount:n.length}}(n),s=i.byteLength;Dr.useProgram(Nr),Dr.enable(Dr.BLEND),Dr.blendEquation(Dr.FUNC_ADD),Dr.blendFunc(Dr.ONE,Dr.ONE_MINUS_SRC_ALPHA),Dr.bindVertexArray(Br),Dr.bindBuffer(Dr.ARRAY_BUFFER,Yr),s>Xr?(Dr.bufferData(Dr.ARRAY_BUFFER,i,Dr.DYNAMIC_DRAW),Xr=s):Dr.bufferSubData(Dr.ARRAY_BUFFER,0,i);const a=ft.wash.color._array;Dr.uniformMatrix4fv(Gr.u_matrix,!1,zr),Dr.uniform4f(Gr.u_color,a[0],a[1],a[2],ft.wash.opacity/255),Dr.drawArrays(Dr.TRIANGLES,0,o),Dr.bindVertexArray(null),Dr.bindBuffer(Dr.ARRAY_BUFFER,null),function(){const t=r?._renderer;t&&(t._curShader=null,t._cachedBlendMode=null,t._isBlending=null)}()}(this),ft.wash={...o}},Gt.prototype.wash=function(t,e,n){ft.wash?.isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],n=1),this.pol=this.genPol(t,e,n,0,-1),this.pol.wash())};const Wr=[];"undefined"!=typeof p5&&p5.registerAddon(function(t,e,n){n.presetup=function(){v(this)},n.predraw=function(){v(this)},n.postsetup=function(){y(this),gt(),_()},n.postdraw=function(){y(this),gt(),_()};const r=e.push,i=e.pop,o=e.randomSeed,s=e.noiseSeed;e.push=function(){r.call(this),Et(),Wr.push({fill:{...ft.fill},wash:ft.wash?{...ft.wash}:null,stroke:{...ft.stroke},hatch:{...ft.hatch},mass:ft.mass?{...ft.mass}:null,field:{...ft.field}})},e.pop=function(){i.call(this),function(){const t=Wr.pop();t&&(ft.stroke={...t.stroke},ft.field={...t.field},ft.hatch={...t.hatch},ft.fill={...t.fill},t.wash&&(ft.wash={...t.wash}),t.mass?ft.mass={...t.mass}:ft.mass&&(ft.mass={...ft.mass,isActive:!1,brush:null,color:null,options:{}}))}()},e.randomSeed=function(t){o.call(this,t),(t=>{T=S(t),k=S(`${t}:2`);for(const t of C)t()})(t)},e.noiseSeed=function(t){s.call(this,t),(t=>{L=M(S(t)),F=M(S(`${t}:2`))})(t)}});export{Gt as Plot,Zt as Polygon,Mt as Position,cn as add,zt as addField,Wt as arc,te as beginShape,re as beginStroke,un as box,Ht as circle,yn as clip,ne as endShape,oe as endStroke,Bt as field,ar as fill,lr as fillBleed,cr as fillTexture,Dn as flowLine,Un as hatch,$n as hatchArray,Xn as hatchStyle,y as instance,Fn as line,Ot as listFields,dt as load,Hn as mass,ie as move,vn as noClip,Yt as noField,ur as noFill,Zn as noHatch,Wn as noMass,pn as noStroke,$r as noWash,xn as pick,Vt as polygon,$t as rect,Nt as refreshField,fn as scaleBrushes,dn as set,se as spline,mn as stroke,gn as strokeWeight,ee as vertex,U as wRand,Vr as wash,Ut as wiggle};//# sourceMappingURL=p5.brush.esm.js.mapdiff --git a/dist/p5.brush.esm.js.map b/dist/p5.brush.esm.js.mapindex c2008a4..30d3c28 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/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/polygon.js","../src/core/plot.js","../src/core/primitives.js","../src/core/gl/utils.js","../src/stroke/gl_draw.js","../src/stroke/stroke.js","../src/hatch/hatch.js","../src/fill/mask.js","../src/fill/fill.js","../src/core/save.js","../src/index.js"],"sourcesContent":["import 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\nexport let Cwidth, Cheight, Instance, Renderer, Density; // Global canvas properties\n\nlet FillMaskUploadCanvas = null;\nlet ReadySketch = null;\nlet ActiveInstance = null;\nconst ActiveInstanceStack = [];\n\n// =============================================================================\n// Section: Target Resolution\n// =============================================================================\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 */\nconst 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 */\nconst 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 // brush.load() can target the main sketch renderer, a p5.Graphics surface,\n // or an active framebuffer owned by the current sketch.\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 */\nconst getActiveFramebuffer = () => Renderer?._renderer?.activeFramebuffer?.() ?? null;\n\nconst clearTarget = (target) => {\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\nconst uploadFillMaskToMirror = (mask, dirtyRect = null) => {\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 = new OffscreenCanvas(uploadWidth, uploadHeight);\n FillMaskUploadCanvas.drawingContext = FillMaskUploadCanvas.getContext(\"2d\");\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\n return target;\n};\n\n// =============================================================================\n// Section: Dirty Rect Utilities\n// =============================================================================\nconst DIRTY_BRUSH_PADDING = 2;\nconst DIRTY_FILL_PADDING = 4;\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\n/**\n * Expands a dirty rectangle outward by a constant padding value.\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 */\nconst 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 the current target bounds.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Candidate rect.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Clamped rect.\n */\nconst normalizeDirtyRect = (rect) => {\n if (!rect) return null;\n\n const { width, height } = getTargetPixelSize();\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 * @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 */\nconst 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 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 { minX: 0, minY: 0, maxX: width, maxY: 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// Section: Load and State\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 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 Cwidth = target.width;\n Cheight = target.height;\n\n _isReady = true;\n if (Renderer.loaded) Mix.load();\n};\n\nlet _isReady = false;\n\n/**\n * Ensures the drawing system is ready before any operation.\n */\nexport const isCanvasReady = () => {\n if (!_isReady) load();\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\nexport const instance = (inst) => {\n 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/**\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: new Object(),\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\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\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 WEBGL brush mask.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\n getCompositeRect(target, isBrushMask) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n\n // Brush-mask dirty rects are still less predictable when the destination\n // is itself a framebuffer, so keep that path conservative.\n if (isBrushMask && getActiveFramebuffer()) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(\n target.dirtyRect,\n isBrushMask ? DIRTY_BRUSH_PADDING : DIRTY_FILL_PADDING,\n ),\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 Density = Renderer.pixelDensity();\n const maskWidth = Math.max(1, Math.round(Cwidth * Density));\n const maskHeight = Math.max(1, Math.round(Cheight * Density));\n const needsBuffers =\n !Renderer.mask ||\n !Renderer.glMask ||\n Renderer.mask.width !== maskWidth ||\n Renderer.mask.height !== maskHeight ||\n Renderer.glMask.width !== Cwidth ||\n Renderer.glMask.height !== Cheight;\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 const needsFillMaskFramebuffer =\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 if (!Renderer.loaded || needsBuffers) {\n if (Renderer.glMask?.remove) Renderer.glMask.remove();\n // Keep one 2D mask for fill/hatch work and one framebuffer-backed mask\n // for brush stamps so the brush path stays in the main renderer context.\n Renderer.mask = new OffscreenCanvas(maskWidth, maskHeight);\n Renderer.mask.drawingContext = Renderer.mask.getContext(\"2d\");\n Renderer.glMask = Renderer.createFramebuffer({\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n Renderer.loaded = true;\n\n Renderer.shaderProgram ??= Renderer.createShader(vertSrc, fragSrc);\n }\n\n if (needsBlendSourceFramebuffer) {\n if (Renderer.blendSourceFramebuffer?.remove) {\n Renderer.blendSourceFramebuffer.remove();\n }\n Renderer.blendSourceFramebuffer = Renderer.createFramebuffer({\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n }\n\n if (needsFillMaskFramebuffer) {\n if (Renderer.fillMaskFramebuffer?.remove) {\n Renderer.fillMaskFramebuffer.remove();\n }\n Renderer.fillMaskFramebuffer = Renderer.createFramebuffer({\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 this.mask = Renderer.mask;\n this.glMask = Renderer.glMask;\n this.ctx = this.mask.drawingContext;\n this.mask.dirtyRect ??= null;\n this.mask.isDrawn ??= false;\n this.ctx.imageSmoothingEnabled = false;\n\n this.glMask.dirtyRect ??= null;\n this.glMask.isDrawn ??= false;\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\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 at the start of each blend cycle.\n clearTarget(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) this.isBlending = false;\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 WEBGL 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 = blitToBlendSourceFramebuffer(activeFramebuffer ?? Renderer, dirtyRect);\n const targetIsFramebuffer = !!activeFramebuffer;\n const hadDepthTest = gl.getParameter(gl.DEPTH_TEST);\n\n // This pass is a fullscreen compositing rect, not scene geometry, so it\n // should not participate in the sketch's depth buffer.\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 if (isBrushMask) {\n shader.setUniform(\"u_mask\", mask);\n } else {\n shader.setUniform(\"u_mask\", uploadFillMaskToMirror(mask, dirtyRect));\n }\n shader.setUniform(\"u_color\", this.cachedColor);\n\n withScissor(gl, dirtyRect, () => {\n Renderer.fill(0, 0, 0, 0);\n Renderer.noStroke();\n Renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);\n }, !targetIsFramebuffer);\n\n Renderer.pop();\n Renderer.resetShader();\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n this.clearMask(mask);\n },\n};\n\n/**\n * Copies the current pixels of a renderer or framebuffer into the reusable\n * blend source framebuffer.\n * @param {p5|p5.Graphics|p5.Framebuffer} sourceTarget - Source to copy from.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} [dirtyRect=null] - Optional copy region.\n * @returns {p5.Framebuffer} Blend source framebuffer after the blit.\n */\nconst blitToBlendSourceFramebuffer = (sourceTarget, dirtyRect = null) => {\n const sourceFramebuffer = Renderer.blendSourceFramebuffer;\n const gl = Renderer.drawingContext;\n const sourceIsFramebuffer = isFramebufferTarget(sourceTarget);\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 (sourceIsFramebuffer ? sourceTarget.renderer : Renderer._renderer)?.flushDraw?.();\n\n if (sourceIsFramebuffer) {\n sourceFramebuffer.draw(() => {\n withScissor(Renderer.drawingContext, dirtyRect, () => {\n Renderer.clear();\n Renderer.push();\n Renderer.imageMode(Renderer.CENTER);\n Renderer.image(sourceTarget, 0, 0, Cwidth, Cheight);\n Renderer.pop();\n }, false);\n });\n return sourceFramebuffer;\n }\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","/*\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 { Renderer } from \"./color.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 const usesRadians =\n isRad ||\n (Renderer &&\n typeof Renderer.angleMode === \"function\" &&\n Renderer.angleMode() === Renderer.RADIANS);\n // Only if Renderer.angleMode() is set to radians\n if (usesRadians) {\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 ||\n (Renderer &&\n typeof Renderer.angleMode === \"function\" &&\n Renderer.angleMode() === Renderer.RADIANS)\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 { isMixReady, Cwidth, Cheight, State, Renderer } from \"./color.js\";\nimport { randInt2, noise2, rr2, sin, cos, map, toDegreesSigned } from \"./utils.js\";\n\n// =============================================================================\n// Section: Matrix transformations\n// =============================================================================\n\n/**\n * The `Matrix` object exposes the current 2D affine transform from p5's model matrix.\n * mat4 layout (column-major 4x4):\n * [0]=a [1]=b [4]=c [5]=d [12]=tx [13]=ty\n * where the 2D transform of a point (x,y) is: (a*x + c*y + tx, b*x + d*y + ty)\n */\nexport const Matrix = {\n x: () => Renderer._renderer.uModelMatrix.mat4[12],\n y: () => Renderer._renderer.uModelMatrix.mat4[13],\n a: () => Renderer._renderer.uModelMatrix.mat4[0],\n b: () => Renderer._renderer.uModelMatrix.mat4[1],\n c: () => Renderer._renderer.uModelMatrix.mat4[4],\n d: () => Renderer._renderer.uModelMatrix.mat4[5],\n};\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 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 = Position.getColIndex(x);\n this.rowIdx = Position.getRowIndex(y);\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 + Matrix.x();\n const y = this.y + Matrix.y();\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() {\n return this.isIn() && State.field.isActive\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 p5 angle mode.\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 for (let i = 0; i < _length / _step; i++) {\n const angle =\n this.angle() - (_scale ? _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 + Matrix.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 + Matrix.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.stroke) this.draw();\n if (State.hatch) this.hatch();\n if (State.fill) this.fill();\n }\n}\n","import { State, Cwidth, Cheight } 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 = 0.5;\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 const maxSize = _side === 0 ? 5 : 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.stroke) this.draw(x, y, scale);\n if (State.hatch) this.hatch(x, y, scale);\n if (State.fill) this.fill(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 * @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 p5 angle mode.\n * @param {number} end - End angle in the current p5 angle mode.\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 * 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// 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 {\n Mix,\n Cwidth,\n Cheight,\n isMixReady,\n Density,\n State,\n Renderer,\n} from \"../core/color.js\";\nimport { Matrix } from \"../core/flowfield.js\";\nimport { createProgram } from \"../core/gl/utils.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;\nlet prevMaskTarget = 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 p5 model matrix. Call once at the start of each stroke.\n */\nexport function snapshotMatrix() {\n _ma = Matrix.a();\n _mb = Matrix.b();\n _mc = Matrix.c();\n _md = Matrix.d();\n _mx = Matrix.x();\n _my = Matrix.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 resetMaskShaderTracking() {\n const renderer = Mix.glMask?.renderer;\n if (!renderer) return;\n renderer._curShader = null;\n renderer._cachedBlendMode = null;\n renderer._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\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 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 const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n beginMaskTarget._hadDepthTest = hadDepthTest;\n if (hadDepthTest) gl.disable(gl.DEPTH_TEST);\n prevMaskTarget = Renderer._renderer.activeFramebuffer?.() ?? null;\n if (prevMaskTarget?._beforeEnd) prevMaskTarget._beforeEnd();\n gl.bindFramebuffer(gl.FRAMEBUFFER, getFramebufferHandle(Mix.glMask));\n gl.viewport(\n 0,\n 0,\n Mix.glMask.width * Mix.glMask.density,\n Mix.glMask.height * Mix.glMask.density,\n );\n}\n\nfunction endMaskTarget() {\n if (beginMaskTarget._hadDepthTest) gl.enable(gl.DEPTH_TEST);\n beginMaskTarget._hadDepthTest = false;\n if (prevMaskTarget?._beforeBegin) {\n prevMaskTarget._beforeBegin();\n } else {\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 prevMaskTarget = null;\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 * p5's current model matrix 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 {p5.Image} p5img - The preprocessed brush-tip image (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 beginMaskTarget();\n\n // Lazy-create the WebGL texture from the p5.Image 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();\n\n if (imgDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, imgDirtyRect);\n imgDirtyRect = null;\n }\n\n imgCount = 0;\n\n // Let p5 know we changed the active program\n resetMaskShaderTracking();\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 beginMaskTarget();\n\n const color = State.stroke.color._array;\n\n // Re-activate our shader (p5 drawing may have 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();\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 p5's _curShader tracking.\n // Reset it to null so p5 is forced to re-activate its own shader next time\n // it draws — otherwise p5 skips gl.useProgram() and sets uniforms on the\n // wrong active program, causing \"location is not from the associated program\".\n resetMaskShaderTracking();\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\nimport {\n Mix,\n Cwidth,\n Cheight,\n State,\n Renderer,\n Instance,\n isCanvasReady,\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} from \"../core/utils.js\";\nimport { Position, Matrix, isFieldReady } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport {\n isReady,\n glDraw,\n glDrawImages,\n circle,\n stampImage,\n invalidateTexEntry,\n snapshotMatrix,\n} from \"./gl_draw.js\";\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 clipWindow: null,\n type: \"HB\",\n isActive: false,\n opacity: 1,\n};\n\nlet list = new Map();\nlet _strokeTransform = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n tx: 0,\n ty: 0,\n};\n\nfunction getBrushFactory() {\n return Renderer ?? Instance ?? window.self.p5.instance;\n}\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 // 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 factory = getBrushFactory();\n const g = factory.createGraphics(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\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 = Renderer.color(...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\nfunction snapshotTransform() {\n return {\n a: Matrix.a(),\n b: Matrix.b(),\n c: Matrix.c(),\n d: Matrix.d(),\n tx: Matrix.x(),\n ty: Matrix.y(),\n };\n}\n\nfunction invertTransform(transform) {\n const det = transform.a * transform.d - transform.b * transform.c;\n if (Math.abs(det) < 1e-12) return null;\n\n return {\n a: transform.d / det,\n b: -transform.b / det,\n c: -transform.c / det,\n d: transform.a / det,\n tx: (transform.c * transform.ty - transform.d * transform.tx) / det,\n ty: (transform.b * transform.tx - transform.a * transform.ty) / det,\n };\n}\n\nfunction normalizeRegion(region) {\n const [x1, y1, x2, y2] = region;\n return {\n minX: Math.min(x1, x2),\n minY: Math.min(y1, y2),\n maxX: Math.max(x1, x2),\n maxY: Math.max(y1, y2),\n };\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 p5 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 const inverse = invertTransform(snapshotTransform());\n if (!inverse) {\n throw new Error(\n \"brush.clip() cannot be used with a non-invertible transform.\",\n );\n }\n State.stroke.clipWindow = {\n bounds: normalizeRegion(region),\n inverse,\n };\n}\n\n/**\n * Disables the clipping region.\n */\nexport function noClip() {\n State.stroke.clipWindow = null;\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 _strokeTransform = snapshotTransform();\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 for (let i = 0; i < totalSteps; i++) {\n if (gaussians.length < totalSteps * 2) {\n gaussians.push(gaussian());\n }\n tip();\n isPlot\n ? _position.plotTo(\n _plot,\n stepSize,\n stepSize,\n angleScale,\n i < 10 ? true : false,\n )\n : _position._moveToDegrees(angleScale, stepSize, stepSize);\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.03;\n\n // Cache stroke direction for direction-aware dispersion (non-plot strokes only)\n if (!_plot) {\n const dirRad = (_dir * Math.PI) / 180;\n current.cos = Math.cos(dirRad);\n current.sin = Math.sin(dirRad);\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 // Pre-compute clip-check coefficients so isInsideClippingArea() needs no\n // temporary objects and only one matrix×vector multiply per step instead of two.\n {\n const cw2 = Cwidth / 2, ch2 = Cheight / 2;\n const T = _strokeTransform;\n if (State.stroke.clipWindow) {\n const { inverse: I, bounds: B } = State.stroke.clipWindow;\n // Compose (I ∘ T) and fold the -cw2/-ch2 position offset into the translation\n const ca = I.a * T.a + I.c * T.b, cc = I.a * T.c + I.c * T.d;\n const cb = I.b * T.a + I.d * T.b, cd = I.b * T.c + I.d * T.d;\n current.clipA = ca; current.clipB = cb;\n current.clipC = cc; current.clipD = cd;\n current.clipTX = I.a * T.tx + I.c * T.ty + I.tx - ca * cw2 - cc * ch2;\n current.clipTY = I.b * T.tx + I.d * T.ty + I.ty - cb * cw2 - cd * ch2;\n current.clipMinX = B.minX; current.clipMaxX = B.maxX;\n current.clipMinY = B.minY; current.clipMaxY = B.maxY;\n } else {\n const o =\n current.p.type === \"custom\" || current.p.type === \"image\"\n ? Math.max(Cwidth * 0.05, getImageTipOverscan())\n : Cwidth * 0.05;\n current.clipA = T.a; current.clipB = T.b;\n current.clipC = T.c; current.clipD = T.d;\n current.clipTX = T.tx - T.a * cw2 - T.c * ch2;\n current.clipTY = T.ty - T.b * cw2 - T.d * ch2;\n current.clipMinX = -cw2 - o; current.clipMaxX = cw2 + o;\n current.clipMinY = -ch2 - o; current.clipMaxY = ch2 + o;\n }\n }\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 insideClip = isInsideClippingArea();\n if (!insideClip) return;\n const pressure = calculatePressure();\n const lineNoise = map(\n noise(current.seed + _position.plotted * 0.002, 0),\n 0,\n 1,\n 1 - current.noiseoffset,\n 1 + current.noiseoffset,\n );\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 return _plot\n ? simPressure() * _plot.pressure(_position.plotted)\n : simPressure();\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 * Checks if the current drawing position is within the clipping region.\n * Uses coefficients pre-computed in saveState() — no object allocations,\n * one fused matrix×vector multiply (both transforms composed at setup time).\n * @returns {boolean} True if inside clipping area; false otherwise.\n */\nfunction isInsideClippingArea() {\n const lx = current.clipA * _position.x + current.clipC * _position.y + current.clipTX;\n if (lx < current.clipMinX || lx > current.clipMaxX) return false;\n const ly = current.clipB * _position.x + current.clipD * _position.y + current.clipTY;\n return ly >= current.clipMinY && ly <= current.clipMaxY;\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 dx = 0.7 * vibration * rr(-1, 1);\n dy = vibration * rr(-1, 1);\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 if (isInsideClippingArea()) {\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// ---------------------------------------------------------------------------\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 p5 angle mode.\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];\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 \"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 p5.js graphics library.\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 p5.Image 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 new Promise((resolve, reject) => {\n const nativeImg = new window.Image();\n nativeImg.onload = () => {\n const factory = getBrushFactory();\n const p5img = factory.createImage(\n nativeImg.naturalWidth,\n nativeImg.naturalHeight,\n );\n p5img.drawingContext.drawImage(nativeImg, 0, 0);\n T.imageToWhite(p5img);\n this.tips.set(src, p5img);\n resolve();\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 );\n },\n};\n","// =============================================================================\n// Module: Classic Hatch\n// =============================================================================\n\nimport { 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// Hatch State\n// ---------------------------------------------------------------------------\n\nState.hatch = {\n isActive: false,\n dist: 5,\n angle: 45,\n options: {},\n hBrush: false,\n};\n\nexport function HatchState() {\n return { ...State.hatch };\n}\n\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\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\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Scanline Hatching\n// ---------------------------------------------------------------------------\n\n/**\n * Computes hatch segments for a polygon via scanline intersection.\n * Rotates vertices so hatch lines become horizontal, scans for edge\n * crossings, then rotates intersections back to original space.\n */\nfunction scanlineHatch(polygon, angle, dist, gradient) {\n const rad = (angle * Math.PI) / 180;\n const cosA = Math.cos(rad), sinA = Math.sin(rad);\n const cosB = Math.cos(-rad), sinB = Math.sin(-rad);\n\n const verts = polygon.a, n = verts.length;\n\n // Rotate vertices; track Y extent\n const rotated = new Array(n);\n let minY = Infinity, maxY = -Infinity;\n for (let i = 0; i < n; i++) {\n const x = verts[i][0], 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], 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 let Y = minY + dist * 0.5, step = dist;\n while (Y < maxY) {\n const cx = [];\n for (let i = 0; i < eLen; i += 2) {\n const y1 = edges[i][1], y2 = edges[i + 1][1];\n if ((y1 <= Y && Y < y2) || (y2 <= Y && Y < y1))\n cx.push(edges[i][0] + ((Y - y1) / (y2 - y1)) * (edges[i + 1][0] - edges[i][0]));\n }\n cx.sort((a, b) => a - b);\n for (let i = 0; i < cx.length - 1; i += 2) {\n segments.push({\n x1: cx[i] * cosB - Y * sinB, y1: cx[i] * sinB + Y * cosB,\n x2: cx[i + 1] * cosB - Y * sinB, y2: cx[i + 1] * sinB + Y * cosB,\n });\n }\n Y += step;\n step *= gradient;\n }\n return segments;\n}\n\n// ---------------------------------------------------------------------------\n// Create Hatch\n// ---------------------------------------------------------------------------\n\nexport function createHatch(polygons) {\n const dist = State.hatch.dist;\n const angle = ((State.hatch.angle % 180) + 180) % 180;\n const options = State.hatch.options;\n\n const save = BrushState();\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n if (!Array.isArray(polygons)) polygons = [polygons];\n\n const gradient = options.gradient ? map(options.gradient, 0, 1, 1, 1.1, true) : 1;\n\n const segs = [];\n for (const poly of polygons)\n for (const s of scanlineHatch(poly, angle, dist, gradient)) segs.push(s);\n segs.sort((a, b) => a.x1 === b.x1 ? a.y1 - b.y1 : a.x1 - b.x1);\n\n const r = options.rand || 0;\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 += r * dist * rr(-1, 1);\n y1 += r * dist * rr(-1, 1);\n x2 += r * dist * rr(-1, 1);\n y2 += r * dist * rr(-1, 1);\n }\n line(x1, y1, x2, y2);\n if (j > 0 && options.continuous) line(segs[j - 1].x2, segs[j - 1].y2, x1, y1);\n }\n\n BrushSetState(save);\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (state.isActive) createHatch(this);\n HatchSetState(state);\n};\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.25);\n this.pol.hatch();\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","// =============================================================================\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\nimport {\n Renderer,\n Mix,\n State,\n Cwidth,\n Cheight,\n Density,\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, Matrix } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\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;\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 =\n arguments.length < 3 ? Renderer.color(a) : Renderer.color(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 const insertedX = new Array(len);\n const insertedY = new Array(len);\n const newMods = new Array(outLen);\n const newDirs = new Array(outLen);\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 const growCap = GROW_MAX_VERTS * Math.max(0.1, 2 * State.fill.bleed_strength);\n if (growCap && idx > growCap) {\n const step = Math.ceil(idx / growCap);\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 newMods.length = idx;\n newDirs.length = idx;\n fm = newMods;\n fd = newDirs;\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 Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * Matrix.a(),\n Density * Matrix.b(),\n Density * Matrix.c(),\n Density * Matrix.d(),\n Density * (Matrix.x() + Cwidth / 2),\n Density * (Matrix.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 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, false, 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","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 stroke: { ...State.stroke },\n hatch: { ...State.hatch },\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}\n","/**\n * @fileoverview p5.brush - A comprehensive toolset for brush management in p5.js.\n * @license MIT\n * @author Alejandro Campos Uribe\n *\n * @description\n * p5.brush is a p5.js library dedicated to the creation and management of custom brushes.\n * It extends the drawing capabilities of p5.js by allowing users to simulate a wide range\n * of brush strokes, vector fields, hatching patterns, and fill textures. These features\n * are essential for emulating the nuanced effects found in traditional sketching and painting.\n * Whether for digital art applications or procedural generation of graphics, p5.brush provides\n * a robust framework for artists and developers to create rich, dynamic, and textured visuals.\n *\n * @example\n * // Basic usage:\n * brush.pick('marker'); // Select brush type\n * brush.stroke(255, 0, 0); // Set brush color\n * brush.strokeWeight(10); // Set brush size\n * brush.line(25, 25, 75, 75); // Draw a line\n *\n * // Add a new brush type:\n * brush.add('customBrush', { /* parameters for the brush *\\/ });\n * brush.pick('customBrush');\n *\n * // Use the custom brush for a vector-field line:\n * brush.field('field_name') // Pick a flowfield\n * brush.flowLine(50, 50, 100, PI / 4); // Draw a line within the vector-field; angle follows p5 angleMode()\n *\n * // Fill textures:\n * brush.noStroke();\n * brush.fill('#FF0000', 90); // Set fill color to red and opacity to 90\n * brush.fillBleed(0.3); // Set bleed effect for a watercolor-like appearance\n * brush.rect(100, 100, 50, 50); // Fill a rectangle with the bleed effect\n *\n * @license\n * MIT License\n *\n * Copyright (c) 2023-2026 Alejandro Campos Uribe\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\n * all 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\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n// Randomness and other auxiliary functions\nexport { weightedRand as wRand } from \"./core/utils.js\";\n\n// Color Blending\nexport { load, instance } from \"./core/color.js\";\n\n// Matrix transformations, FlowField and Position Class\nexport {\n field,\n noField,\n addField,\n refreshField,\n listFields,\n Position,\n wiggle,\n} from \"./core/flowfield.js\";\n\n// Polygon and Plot classes\nexport { Polygon } from \"./core/polygon.js\";\nexport { Plot } from \"./core/plot.js\";\n\n// Primitives\nexport {\n rect,\n circle,\n arc,\n beginShape,\n vertex,\n endShape,\n beginStroke,\n move,\n endStroke,\n spline,\n polygon,\n} from \"./core/primitives.js\";\n\n// Brushes\nexport {\n add,\n box,\n scaleBrushes,\n pick,\n stroke,\n strokeWeight,\n set,\n noStroke,\n clip,\n noClip,\n line,\n flowLine,\n} from \"./stroke/stroke.js\";\n\n// Section: Hatching\nexport {\n hatch,\n hatchStyle,\n noHatch,\n createHatch as hatchArray,\n} from \"./hatch/hatch.js\";\n\n// Fill\nexport { fill, noFill, fillTexture, fillBleed } from \"./fill/fill.js\";\n\n// p5 addon registration\nimport {\n Mix,\n instance as bindInstance,\n activateInstance,\n deactivateInstance,\n} from \"./core/color.js\";\nimport { push as brushPush, pop as brushPop } from \"./core/save.js\";\nimport { seed as brushSeed, noiseSeed as brushNoiseSeed } from \"./core/utils.js\";\n\nfunction registerAddon(_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 Mix.blend(false, true);\n deactivateInstance();\n };\n\n lifecycles.postdraw = function () {\n bindInstance(this);\n Mix.blend(false, true);\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\nif (typeof p5 !== \"undefined\") p5.registerAddon(registerAddon);\n"],"names":["Cwidth","Cheight","Instance","Renderer","Density","FillMaskUploadCanvas","ReadySketch","ActiveInstance","ActiveInstanceStack","isFramebufferTarget","target","begin","end","renderer","_pInst","isFiniteSize","value","Number","isFinite","safeRead","getter","_error","isReadyWebGLSketch","candidate","pixelDensity","createFramebuffer","width","height","webglVersion","rememberReadySketch","getSketchRenderer","window","self","p5","instance","getActiveFramebuffer","_renderer","activeFramebuffer","clearTarget","draw","clear","ctx","drawingContext","save","setTransform","clearRect","restore","getTargetPixelSize","Math","max","round","normalizeDirtyRect","rect","minX","floor","min","maxX","minY","maxY","ceil","getFullDirtyRect","toScissorBox","flipY","normalized","x","y","withScissor","gl","box","enable","SCISSOR_TEST","scissor","disable","load","buffer","sketchRenderer","Error","owner","resolveTarget","_isReady","loaded","Mix","isCanvasReady","State","inst","activateInstance","push","deactivateInstance","pop","isMixReady","isBlending","cachedColor","Object","markDirtyRect","a","b","dirtyRect","isDrawn","clearMask","getCompositeRect","isBrushMask","padding","expandDirtyRect","maskWidth","maskHeight","needsBuffers","mask","glMask","needsBlendSourceFramebuffer","blendSourceFramebuffer","needsFillMaskFramebuffer","fillMaskFramebuffer","remove","OffscreenCanvas","getContext","density","antialias","depth","stencil","shaderProgram","createShader","this","imageSmoothingEnabled","blend","_color","_isLast","isBrush","otherMask","nextColor","_array","colorChanged","justChanged","applyShader","shader","source","blitToBlendSourceFramebuffer","targetIsFramebuffer","hadDepthTest","getParameter","DEPTH_TEST","translate","setUniform","uploadRect","uploadWidth","uploadHeight","uploadContext","drawImage","bindTexture","TEXTURE_2D","colorTexture","texSubImage2D","RGBA","UNSIGNED_BYTE","uploadFillMaskToMirror","fill","noStroke","resetShader","sourceTarget","sourceFramebuffer","sourceIsFramebuffer","sourceBox","previousReadFramebuffer","READ_FRAMEBUFFER_BINDING","previousDrawFramebuffer","DRAW_FRAMEBUFFER_BINDING","flushDraw","imageMode","CENTER","image","bindFramebuffer","READ_FRAMEBUFFER","DRAW_FRAMEBUFFER","framebuffer","clearColor","COLOR_BUFFER_BIT","blitFramebuffer","NEAREST","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","c","s0","s1","s2","copy","f","rng","rng2","_seedCallbacks","_onSeed","cb","noise","noise2","rr","e","rr2","rArray","array","randInt","randInt2","gaussian","mean","stdev","u","log","cos","weightedRand","weights","totalWeight","entries","key","cumulative","rnd","isNaN","parseInt","d","withinBounds","constrain","low","high","nAngle","angle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","NaN","sLookup","idx","sin","toDegrees","rad","isRad","angleMode","RADIANS","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","Matrix","uModelMatrix","mat4","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","update","plotted","colIdx","getColIndex","rowIdx","getRowIndex","reset","isIn","isActive","isInCanvas","list","get","current","wiggle","moveTo","_dir","_length","_step_length","movePos","_moveToDegrees","plotTo","_plot","_scale","_dirPlot","_step","scaleFactor","y_offset","x_offset","col","row","Map","FIELD_ANGLE_MODES","Set","normalizeFieldAngleMode","options","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","intersection","show","stroke","hatch","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","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","createProgram","frag","src","VERTEX_SHADER","FRAGMENT_SHADER","shaderSource","compileShader","attachShader","linkProgram","framebufferProjMatrix","vao","buf","program","loadedWidth","loadedHeight","brushMaskTarget","prevMaskTarget","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","resetMaskShaderTracking","_curShader","_cachedBlendMode","_isBlending","activeTexture","TEXTURE0","blendEquation","FUNC_ADD","blendFunc","ONE","ONE_MINUS_SRC_ALPHA","getProjectionMatrix","beginMaskTarget","isEnabled","_hadDepthTest","_beforeEnd","FRAMEBUFFER","_framebufferToBind","viewport","endMaskTarget","_beforeBegin","_origViewport","_applyStencilTestIfClipping","accumulateDirtyRect","currentRect","diameter","alpha","newData","px","py","screenX","screenY","dScreenX","dScreenY","glDrawImages","p5img","tex","createTexture","texImage2D","canvas","texParameteri","TEXTURE_MIN_FILTER","LINEAR","TEXTURE_MAG_FILTER","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","useProgram","BLEND","ONE_MINUS_DST_ALPHA","uniform1i","u_tex","color","uniform4f","u_color","uniformMatrix4fv","u_proj","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","drawArraysInstanced","TRIANGLE_STRIP","flush","weight","clipWindow","opacity","_strokeTransform","tx","ty","getBrushFactory","DEFAULT_CUSTOM_PRESSURE_VARIATION","warp","tilt","BrushState","BrushSetState","state","add","params","includes","undefined","markerTip","vibration","scatter","definition","sharpness","quality","grain","min_max","curve","variation","isArray","rest","m","range","ns","nm","ne","normalizePressure","tip","deleteTexture","delete","invalidateTexEntry","g","createGraphics","background","noSmooth","T","imageToWhite","tips","tipKey","param","colors","buffers","scaleBrushes","values","spacing","pick","brushName","arguments","strokeWeight","snapshotTransform","normalizeRegion","region","clip","inverse","transform","det","invertTransform","bounds","noClip","_position","initializeDrawingState","plot","gaussians","angleScale","isPlot","cp","ct","cs","ck","noiseoffset","dirRad","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","cw2","ch2","I","B","ca","cc","cd","clipA","clipB","clipC","clipD","clipTX","clipTY","clipMinX","clipMaxX","clipMinY","clipMaxY","o","getImageTipOverscan","saveState","stepSize","totalSteps","u_matrix","drawArrays","POINTS","glDraw","restoreState","isInsideClippingArea","calculatePressure","lineNoise","sw","iterations","rX","yRandomFactor","sqrtPart","drawSpray","drawMarker","drawImageTip","perp","along","drawDefault","simPressure","peakPos","halfWidth","pow","gauss","lx","ly","maxPressure","scatterReach","tipReach","vibrate","rx","ry","size","overscan","extraPadding","halfSize","extraRadius","base","boundsRadius","stampImage","flowLine","_vals","_standard_brushes","obj","prototype","_brush","_weight","loadPixels","average","pixels","updatePixels","filter","k","Promise","all","resolve","reject","nativeImg","Image","onload","createImage","naturalWidth","naturalHeight","onerror","crossOrigin","HatchState","rand","continuous","gradient","hatchStyle","brush","hBrush","noHatch","scanlineHatch","cosA","sinA","cosB","sinB","verts","rotated","Infinity","edges","eLen","Y","sort","createHatch","polygons","segs","poly","_dist","_angle","_options","HatchSetState","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","noFill","_polygon","_gaussians","_fillGaussianPools","_isLeft","FillPoly","center","isFirst","sx","sy","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","growCap","kept","intensity","texture","int","switchingToFill","strokeStyle","_getRed","_getGreen","_getBlue","lineCap","darker","sparse","pols","layer","numLayers","erase","lineWidth","fillStyle","matrix","getTransform","beginPath","first","lineTo","closePath","strokePadding","drawPolygon","numCircles","halfSizeX","halfSizeY","minSize","minSizeFactor","maxSizeFactor","midX","midY","globalCompositeOperation","_opacity","_bleed","fluid","strength","modifiers","_","shift","shifted","slice","pts","point","area","cross","_center","createFill","FillSetState","_stateStack","registerAddon","_p5","lifecycles","presetup","predraw","postsetup","bindInstance","postdraw","_push","_pop","_randomSeed","randomSeed","_noiseSeed","noiseSeed","call","saved","brushPop","callback","brushSeed","brushNoiseSeed"],"mappings":"AAYO,IAAIA,EAAQC,EAASC,EAAUC,EAAUC,EAE5CC,EAAuB,KACvBC,EAAc,KACdC,EAAiB,KACrB,MAAMC,EAAsB,GAWtBC,EAAuBC,KACzBA,GACsB,mBAAjBA,EAAOC,OACQ,mBAAfD,EAAOE,OACZF,EAAOG,YACPH,EAAOG,SAASC,OAEdC,EAAgBC,GACH,iBAAVA,GAAsBC,OAAOC,SAASF,IAAUA,EAAQ,EAE3DG,EAAYC,IAChB,IACE,OAAOA,GACT,CAAE,MAAOC,GACP,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F,EAEA,MAAM84B,EAAQ9kB,EAAGjU,KACXg5B,EAAO/kB,EAAG/T,IACV+4B,EAAchlB,EAAGilB,WACjBC,EAAallB,EAAGmlB,UAEtBnlB,EAAGjU,KAAO,WACR+4B,EAAMM,KAAKl3B,MD3Ib6M,KACAspB,GAAYt4B,KAAK,CACfoE,KAAM,IAAKvE,EAAMuE,MACjB8Q,OAAQ,IAAKrV,EAAMqV,QACnBC,MAAO,IAAKtV,EAAMsV,OAClB5F,MAAO,IAAK1P,EAAM0P,QCwIpB,EAEA0E,EAAG/T,IAAM,WACP84B,EAAKK,KAAKl3B,MDpIP,WACL,MAAMm3B,EAAQhB,GAAYp4B,MACrBo5B,IACLz5B,EAAMqV,OAAS,IAAKokB,EAAMpkB,QAC1BrV,EAAM0P,MAAQ,IAAK+pB,EAAM/pB,OACzB1P,EAAMsV,MAAQ,IAAKmkB,EAAMnkB,OACzBtV,EAAMuE,KAAO,IAAKk1B,EAAMl1B,MAC1B,CC8HIm1B,EACF,EAEAtlB,EAAGilB,WAAa,SAAU/xB,GACxB8xB,EAAYI,KAAKl3B,KAAMgF,GZxIP,CAACA,IACnB4C,EAAMzB,EAAUnB,GAChB6C,EAAO1B,EAAU,GAAGnB,OACpB,IAAK,MAAMqyB,KAAYvvB,EACrBuvB,KYqIAC,CAAUtyB,EACZ,EAEA8M,EAAGmlB,UAAY,SAAUjyB,GACvBgyB,EAAWE,KAAKl3B,KAAMgF,GZzHD,CAACA,IACxBiD,EAAQlE,EAAcoC,EAAUnB,IAChCkD,EAASnE,EAAcoC,EAAU,GAAGnB,SYwHlCuyB,CAAevyB,EACjB,CACF","x_google_ignoreList":[1,2]}\ No newline at end of file+{"version":3,"file":"p5.brush.esm.js","sources":["../src/core/target.js","../node_modules/simplex-noise/dist/esm/simplex-noise.js","../node_modules/esm-seedrandom/esm/index.mjs","../src/core/utils.js","../src/core/dirty_rect.js","../src/core/color.js","../src/core/flowfield.js","../src/core/polygon.js","../src/core/plot.js","../src/core/primitives.js","../src/stroke/composite.js","../src/core/gl/utils.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/core/save.js","../src/index.js"],"sourcesContent":["// =============================================================================\n// Module: Target Resolution and Runtime Context\n// =============================================================================\n/**\n * Owns the active renderer/instance selection used by p5.brush.\n */\n\nexport let Cwidth, Cheight, Instance, Renderer, Density;\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 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 Cwidth = target.width;\n Cheight = target.height;\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 Density = Renderer.pixelDensity();\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 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","/*\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 { Renderer } from \"./target.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 const usesRadians =\n isRad ||\n (Renderer &&\n typeof Renderer.angleMode === \"function\" &&\n Renderer.angleMode() === Renderer.RADIANS);\n // Only if Renderer.angleMode() is set to radians\n if (usesRadians) {\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 ||\n (Renderer &&\n typeof Renderer.angleMode === \"function\" &&\n Renderer.angleMode() === Renderer.RADIANS)\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// 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","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\";\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 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\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 WEBGL 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 if (!Renderer.loaded) {\n Renderer.loaded = true;\n Renderer.shaderProgram ??= Renderer.createShader(vertSrc, fragSrc);\n }\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 if (Renderer.blendSourceFramebuffer?.remove) {\n Renderer.blendSourceFramebuffer.remove();\n }\n Renderer.blendSourceFramebuffer = Renderer.createFramebuffer({\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\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 WEBGL 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 = blitToBlendSourceFramebuffer(activeFramebuffer ?? Renderer, dirtyRect);\n const targetIsFramebuffer = !!activeFramebuffer;\n const hadDepthTest = gl.getParameter(gl.DEPTH_TEST);\n\n // This pass is a fullscreen compositing rect, not scene geometry, so it\n // should not participate in the sketch's depth buffer.\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 const composite = isBrushMask ? strokeComposite : fillComposite;\n shader.setUniform(\n \"u_mask\",\n composite.getShaderMask(\n Renderer,\n mask,\n dirtyRect,\n normalizeDirtyRect,\n getFullDirtyRect,\n clearTarget,\n ),\n );\n shader.setUniform(\"u_color\", this.cachedColor);\n\n withScissor(gl, dirtyRect, () => {\n Renderer.fill(0, 0, 0, 0);\n Renderer.noStroke();\n Renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);\n }, !targetIsFramebuffer);\n\n Renderer.pop();\n Renderer.resetShader();\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\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 {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional offscreen target.\n */\nexport const load = (buffer = false) => {\n loadTarget(buffer);\n if (Renderer.loaded) Mix.load();\n};\n\n/**\n * Copies the current pixels of a renderer or framebuffer into the reusable\n * blend source framebuffer.\n * @param {p5|p5.Graphics|p5.Framebuffer} sourceTarget - Source to copy from.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} [dirtyRect=null] - Optional copy region.\n * @returns {p5.Framebuffer} Blend source framebuffer after the blit.\n */\nconst blitToBlendSourceFramebuffer = (sourceTarget, dirtyRect = null) => {\n const sourceFramebuffer = Renderer.blendSourceFramebuffer;\n const gl = Renderer.drawingContext;\n const sourceIsFramebuffer = isFramebufferTarget(sourceTarget);\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 (sourceIsFramebuffer ? sourceTarget.renderer : Renderer._renderer)?.flushDraw?.();\n\n if (sourceIsFramebuffer) {\n sourceFramebuffer.draw(() => {\n withScissor(Renderer.drawingContext, dirtyRect, () => {\n Renderer.clear();\n Renderer.push();\n Renderer.imageMode(Renderer.CENTER);\n Renderer.image(sourceTarget, 0, 0, Cwidth, Cheight);\n Renderer.pop();\n }, false);\n });\n return sourceFramebuffer;\n }\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","import { Cwidth, Cheight, Renderer } from \"./target.js\";\nimport { isMixReady, State } from \"./color.js\";\nimport { randInt2, noise2, rr2, sin, cos, map, toDegreesSigned } from \"./utils.js\";\n\n// =============================================================================\n// Section: Matrix transformations\n// =============================================================================\n\n/**\n * The `Matrix` object exposes the current 2D affine transform from p5's model matrix.\n * mat4 layout (column-major 4x4):\n * [0]=a [1]=b [4]=c [5]=d [12]=tx [13]=ty\n * where the 2D transform of a point (x,y) is: (a*x + c*y + tx, b*x + d*y + ty)\n */\nexport const Matrix = {\n x: () => Renderer._renderer.uModelMatrix.mat4[12],\n y: () => Renderer._renderer.uModelMatrix.mat4[13],\n a: () => Renderer._renderer.uModelMatrix.mat4[0],\n b: () => Renderer._renderer.uModelMatrix.mat4[1],\n c: () => Renderer._renderer.uModelMatrix.mat4[4],\n d: () => Renderer._renderer.uModelMatrix.mat4[5],\n};\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 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 = Position.getColIndex(x);\n this.rowIdx = Position.getRowIndex(y);\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 + Matrix.x();\n const y = this.y + Matrix.y();\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 p5 angle mode.\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 + Matrix.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 + Matrix.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 p5 angle mode.\n * @param {number} end - End angle in the current p5 angle mode.\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 * as Color from \"../core/color.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 p5 renderer/sketch.\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 p5 renderer/sketch.\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 = Renderer.createFramebuffer({\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 p5 renderer/sketch.\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// 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 { Matrix } from \"../core/flowfield.js\";\nimport { createProgram } from \"../core/gl/utils.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;\nlet prevMaskTarget = 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 p5 model matrix. Call once at the start of each stroke.\n */\nexport function snapshotMatrix() {\n _ma = Matrix.a();\n _mb = Matrix.b();\n _mc = Matrix.c();\n _md = Matrix.d();\n _mx = Matrix.x();\n _my = Matrix.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 resetMaskShaderTracking() {\n const renderer = Mix.glMask?.renderer;\n if (!renderer) return;\n renderer._curShader = null;\n renderer._cachedBlendMode = null;\n renderer._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\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 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 const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n beginMaskTarget._hadDepthTest = hadDepthTest;\n if (hadDepthTest) gl.disable(gl.DEPTH_TEST);\n prevMaskTarget = Renderer._renderer.activeFramebuffer?.() ?? null;\n if (prevMaskTarget?._beforeEnd) prevMaskTarget._beforeEnd();\n gl.bindFramebuffer(gl.FRAMEBUFFER, getFramebufferHandle(Mix.glMask));\n gl.viewport(\n 0,\n 0,\n Mix.glMask.width * Mix.glMask.density,\n Mix.glMask.height * Mix.glMask.density,\n );\n}\n\nfunction endMaskTarget() {\n if (beginMaskTarget._hadDepthTest) gl.enable(gl.DEPTH_TEST);\n beginMaskTarget._hadDepthTest = false;\n if (prevMaskTarget?._beforeBegin) {\n prevMaskTarget._beforeBegin();\n } else {\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 prevMaskTarget = null;\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 * p5's current model matrix 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 {p5.Image} p5img - The preprocessed brush-tip image (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 beginMaskTarget();\n\n // Lazy-create the WebGL texture from the p5.Image 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();\n\n if (imgDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, imgDirtyRect);\n imgDirtyRect = null;\n }\n\n imgCount = 0;\n\n // Let p5 know we changed the active program\n resetMaskShaderTracking();\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 beginMaskTarget();\n\n const color = State.stroke.color._array;\n\n // Re-activate our shader (p5 drawing may have 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();\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 p5's _curShader tracking.\n // Reset it to null so p5 is forced to re-activate its own shader next time\n // it draws — otherwise p5 skips gl.useProgram() and sets uniforms on the\n // wrong active program, causing \"location is not from the associated program\".\n resetMaskShaderTracking();\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, Instance, 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 { Position, isFieldReady } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.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; ensures p5's WebGL mode is patched to support offscreen stroke 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\nfunction getBrushFactory() {\n return Renderer ?? Instance ?? window.self.p5.instance;\n}\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 factory = getBrushFactory();\n const g = factory.createGraphics(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 = Renderer.color(...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 p5 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 p5 angle mode.\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 p5.js graphics library.\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 p5.Image 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 new Promise((resolve, reject) => {\n const nativeImg = new window.Image();\n nativeImg.onload = () => {\n const factory = getBrushFactory();\n const p5img = factory.createImage(\n nativeImg.naturalWidth,\n nativeImg.naturalHeight,\n );\n p5img.drawingContext.drawImage(nativeImg, 0, 0);\n T.imageToWhite(p5img);\n this.tips.set(src, p5img);\n resolve();\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 );\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 p5 angle mode.\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|p5.Color} [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 let Y = minY + dist * 0.5,\n step = dist;\n while (Y < maxY) {\n const cx = [];\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 { Renderer } from \"../core/target.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 { 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 p5 angle mode units.\n * @param {number} angle\n * @returns {number}\n */\nfunction degreesToCurrentAngleMode(angle) {\n return Renderer &&\n typeof Renderer.angleMode === \"function\" &&\n Renderer.angleMode() === Renderer.RADIANS\n ? (angle * Math.PI) / 180\n : 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 p5 angle mode.\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) {\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 degreesToCurrentAngleMode(startDeg),\n degreesToCurrentAngleMode(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) {\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 );\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) {\n hatch(dist, angle, options);\n drawMassArcs(polygon, pivotBias);\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\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 degreesToCurrentAngleMode(baseAngle),\n {\n gradient,\n rand: 2 - 2 * precision,\n continuous: true,\n },\n pivotBias,\n );\n\n if (strength > 0.33) {\n drawMassPass(\n pols[1],\n hatchDist,\n degreesToCurrentAngleMode(baseAngle + 20 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n );\n }\n\n if (strength > 0.66) {\n drawMassPass(\n pols[2],\n hatchDist * 0.8,\n degreesToCurrentAngleMode(baseAngle + 15 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\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\";\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 p5 renderer/sketch.\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 p5 renderer/sketch.\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 p5 renderer/sketch.\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 = new OffscreenCanvas(maskWidth, maskHeight);\n Renderer.mask.drawingContext = Renderer.mask.getContext(\"2d\");\n }\n\n if (needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.fillMaskFramebuffer?.remove) {\n Renderer.fillMaskFramebuffer.remove();\n }\n Renderer.fillMaskFramebuffer = Renderer.createFramebuffer({\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\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 p5 renderer/sketch.\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 = new OffscreenCanvas(uploadWidth, uploadHeight);\n FillMaskUploadCanvas.drawingContext = FillMaskUploadCanvas.getContext(\"2d\");\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\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, Matrix } from \"../core/flowfield.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;\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 =\n arguments.length < 3 ? Renderer.color(a) : Renderer.color(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 const insertedX = new Array(len);\n const insertedY = new Array(len);\n const newMods = new Array(outLen);\n const newDirs = new Array(outLen);\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 const growCap = GROW_MAX_VERTS * Math.max(0.1, 2 * State.fill.bleed_strength);\n if (growCap && idx > growCap) {\n const step = Math.ceil(idx / growCap);\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 newMods.length = idx;\n newDirs.length = idx;\n fm = newMods;\n fd = newDirs;\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 Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * Matrix.a(),\n Density * Matrix.b(),\n Density * Matrix.c(),\n Density * Matrix.d(),\n Density * (Matrix.x() + Cwidth / 2),\n Density * (Matrix.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 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 { Matrix } from \"../core/flowfield.js\";\nimport { createProgram } from \"../core/gl/utils.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 =\n arguments.length < 3 ? Renderer.color(a) : Renderer.color(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 * Resets p5's cached shader/blend bookkeeping after direct WebGL calls.\n */\nfunction resetWashShaderTracking() {\n const renderer = Renderer?._renderer;\n if (!renderer) return;\n renderer._curShader = null;\n renderer._cachedBlendMode = null;\n renderer._isBlending = null;\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 p5.brush transform matrix 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 p5.brush space.\n * @param {number} y - The source y-coordinate in p5.brush space.\n * @returns {[number, number]} The transformed screen-space position.\n */\nfunction transformVertexToScreen(x, y) {\n return [\n Matrix.a() * x + Matrix.c() * y + Matrix.x() + loadedWidth / 2,\n Matrix.b() * x + Matrix.d() * y + Matrix.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 WEBGL 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 resetWashShaderTracking();\n}\n\n// =============================================================================\n// Prototype methods\n// =============================================================================\n\n/**\n * Applies a direct WEBGL 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","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.brush - A comprehensive toolset for brush management in p5.js.\n * @license MIT\n * @author Alejandro Campos Uribe\n *\n * @description\n * p5.brush is a p5.js library dedicated to the creation and management of custom brushes.\n * It extends the drawing capabilities of p5.js by allowing users to simulate a wide range\n * of brush strokes, vector fields, hatching patterns, and fill textures. These features\n * are essential for emulating the nuanced effects found in traditional sketching and painting.\n * Whether for digital art applications or procedural generation of graphics, p5.brush provides\n * a robust framework for artists and developers to create rich, dynamic, and textured visuals.\n *\n * @example\n * // Basic usage:\n * brush.pick('marker'); // Select brush type\n * brush.stroke(255, 0, 0); // Set brush color\n * brush.strokeWeight(10); // Set brush size\n * brush.line(25, 25, 75, 75); // Draw a line\n *\n * // Add a new brush type:\n * brush.add('customBrush', { /* parameters for the brush *\\/ });\n * brush.pick('customBrush');\n *\n * // Use the custom brush for a vector-field line:\n * brush.field('field_name') // Pick a flowfield\n * brush.flowLine(50, 50, 100, PI / 4); // Draw a line within the vector-field; angle follows p5 angleMode()\n *\n * // Fill textures:\n * brush.noStroke();\n * brush.fill('#FF0000', 90); // Set fill color to red and opacity to 90\n * brush.fillBleed(0.3); // Set bleed effect for a watercolor-like appearance\n * brush.rect(100, 100, 50, 50); // Fill a rectangle with the bleed effect\n *\n * @license\n * MIT License\n *\n * Copyright (c) 2023-2026 Alejandro Campos Uribe\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\n * all 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\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n// Randomness and other auxiliary functions\nexport { weightedRand as wRand } from \"./core/utils.js\";\n\n// Color Blending\nexport { load } from \"./core/color.js\";\nexport { instance } from \"./core/target.js\";\n\n// Matrix transformations, FlowField and Position Class\nexport {\n field,\n noField,\n addField,\n refreshField,\n listFields,\n Position,\n wiggle,\n} from \"./core/flowfield.js\";\n\n// Polygon and Plot classes\nexport { Polygon } from \"./core/polygon.js\";\nexport { Plot } from \"./core/plot.js\";\n\n// Primitives\nexport {\n rect,\n circle,\n arc,\n beginShape,\n vertex,\n endShape,\n beginStroke,\n move,\n endStroke,\n spline,\n polygon,\n} from \"./core/primitives.js\";\n\n// Brushes\nexport {\n add,\n box,\n scaleBrushes,\n pick,\n stroke,\n strokeWeight,\n set,\n noStroke,\n clip,\n noClip,\n line,\n flowLine,\n} from \"./stroke/stroke.js\";\n\n// Section: Hatching\nexport {\n hatch,\n hatchStyle,\n noHatch,\n createHatch as hatchArray,\n} from \"./hatch/hatch.js\";\nexport { \n mass, \n noMass \n} from \"./hatch/mass.js\";\n\n// Fill\nexport { fill, noFill, fillTexture, fillBleed } from \"./fill/fill.js\";\nexport { wash, noWash } from \"./fill/wash.js\";\n\n// p5 addon registration\nimport {\n Mix, \n flushActiveComposite,\n} 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\nfunction registerAddon(_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\nif (typeof p5 !== \"undefined\") p5.registerAddon(registerAddon);\n"],"names":["Cwidth","Cheight","Instance","Renderer","Density","ReadySketch","ActiveInstance","ActiveInstanceStack","_isReady","isFramebufferTarget","target","begin","end","renderer","_pInst","isFiniteSize","value","Number","isFinite","safeRead","getter","_error","isReadyWebGLSketch","candidate","pixelDensity","createFramebuffer","width","height","webglVersion","rememberReadySketch","getSketchRenderer","window","self","p5","instance","getActiveFramebuffer","_renderer","activeFramebuffer","load","buffer","sketchRenderer","Error","owner","resolveTarget","isCanvasReady","inst","activateInstance","push","deactivateInstance","pop","SQRT3","Math","sqrt","F2","G2","fastFloor","x","floor","grad2","Float64Array","createNoise2D","random","perm","p","Uint8Array","i","tableSize","r","aux","buildPermutationTable","permGrad2x","map","v","permGrad2y","y","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","c","s0","s1","s2","copy","f","rng","rng2","_seedCallbacks","_onSeed","cb","noise","noise2","rr","e","rr2","rArray","array","randInt","randInt2","gaussian","mean","stdev","u","log","cos","weightedRand","weights","totalWeight","entries","key","cumulative","rnd","isNaN","parseInt","a","b","d","withinBounds","constrain","low","high","max","min","nAngle","angle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","fill","NaN","sLookup","idx","sin","toDegrees","rad","isRad","angleMode","RADIANS","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","expandDirtyRect","rect","padding","minX","minY","maxX","maxY","strokeComposite","fillComposite","clearTarget","draw","clear","ctx","drawingContext","save","setTransform","clearRect","restore","getTargetPixelSize","round","normalizeDirtyRect","ceil","clampDirtyRect","getFullDirtyRect","getFullRect","toScissorBox","flipY","normalized","withScissor","gl","box","enable","SCISSOR_TEST","scissor","disable","State","isMixReady","loaded","Mix","isBlending","cachedColor","markDirtyRect","dirtyRect","isDrawn","clearMask","composite","glMask","getCompositeRect","isBrushMask","needsBlendSourceFramebuffer","blendSourceFramebuffer","shaderProgram","createShader","ensureResources","fillResources","mask","remove","density","antialias","depth","stencil","blend","_color","_isLast","isBrush","otherMask","nextColor","_array","colorChanged","justChanged","applyShader","shader","source","blitToBlendSourceFramebuffer","targetIsFramebuffer","hadDepthTest","getParameter","DEPTH_TEST","translate","setUniform","getShaderMask","noStroke","resetShader","flushActiveComposite","loadTarget","sourceTarget","sourceFramebuffer","sourceIsFramebuffer","sourceBox","previousReadFramebuffer","READ_FRAMEBUFFER_BINDING","previousDrawFramebuffer","DRAW_FRAMEBUFFER_BINDING","flushDraw","imageMode","CENTER","image","bindFramebuffer","READ_FRAMEBUFFER","DRAW_FRAMEBUFFER","framebuffer","clearColor","COLOR_BUFFER_BIT","blitFramebuffer","NEAREST","Matrix","uModelMatrix","mat4","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","update","plotted","colIdx","getColIndex","rowIdx","getRowIndex","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","y_offset","x_offset","col","row","Map","FIELD_ANGLE_MODES","Set","normalizeFieldAngleMode","options","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","intersection","show","wash","mass","hatch","stroke","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","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","isStrokeCompositeRegistered","createProgram","frag","src","VERTEX_SHADER","FRAGMENT_SHADER","shaderSource","compileShader","attachShader","linkProgram","framebufferProjMatrix","vao","buf","program","loadedWidth","loadedHeight","brushMaskTarget","prevMaskTarget","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","resetMaskShaderTracking","_curShader","_cachedBlendMode","_isBlending","activeTexture","TEXTURE0","bindTexture","TEXTURE_2D","blendEquation","FUNC_ADD","blendFunc","ONE","ONE_MINUS_SRC_ALPHA","getProjectionMatrix","beginMaskTarget","isEnabled","_hadDepthTest","_beforeEnd","FRAMEBUFFER","_framebufferToBind","viewport","endMaskTarget","_beforeBegin","_origViewport","_applyStencilTestIfClipping","accumulateDirtyRect","currentRect","diameter","alpha","newData","px","py","screenX","screenY","dScreenX","dScreenY","glDrawImages","p5img","tex","createTexture","texImage2D","RGBA","UNSIGNED_BYTE","canvas","texParameteri","TEXTURE_MIN_FILTER","LINEAR","TEXTURE_MAG_FILTER","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","useProgram","BLEND","ONE_MINUS_DST_ALPHA","uniform1i","u_tex","color","uniform4f","u_color","uniformMatrix4fv","u_proj","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","drawArraysInstanced","TRIANGLE_STRIP","flush","needsStrokeMask","_Renderer","weight","opacity","getBrushFactory","DEFAULT_CUSTOM_PRESSURE_VARIATION","warp","tilt","BrushState","BrushSetState","state","add","params","includes","undefined","markerTip","vibration","scatter","definition","sharpness","quality","grain","min_max","curve","variation","isArray","rest","m","range","ns","nm","ne","normalizePressure","tip","deleteTexture","delete","invalidateTexEntry","g","createGraphics","background","noSmooth","T","imageToWhite","tips","tipKey","param","colors","buffers","getBrushParams","brushName","scaleBrushes","values","spacing","pick","arguments","strokeWeight","clip","region","noClip","_position","initializeDrawingState","plot","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","resolve","reject","nativeImg","Image","onload","createImage","naturalWidth","naturalHeight","drawImage","onerror","crossOrigin","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","Object","drawFn","withHatchStyle","renderHatchSegments","noMass","jitterPolygon","jitterX","jitterY","degreesToCurrentAngleMode","projectAnchorToBisector","anchor","mx","my","nx","ny","getShortArcAngles","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","OffscreenCanvas","getContext","fillMaskFramebuffer","needsFillMaskFramebuffer","imageSmoothingEnabled","_getActiveFramebuffer","uploadRect","uploadWidth","uploadHeight","uploadContext","colorTexture","texSubImage2D","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","growCap","kept","intensity","texture","int","switchingToFill","strokeStyle","_getRed","_getGreen","_getBlue","lineCap","darker","sparse","layer","numLayers","erase","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","slice","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","TRIANGLES","resetWashShaderTracking","drawWashPolygon","_stateStack","registerAddon","_p5","lifecycles","presetup","predraw","postsetup","bindInstance","postdraw","_push","_pop","_randomSeed","randomSeed","_noiseSeed","noiseSeed","call","saved","brushPop","callback","brushSeed","brushNoiseSeed"],"mappings":"AAOO,IAAIA,EAAQC,EAASC,EAAUC,EAAUC,EAE5CC,EAAc,KACdC,EAAiB,KACrB,MAAMC,EAA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AS,IAAK0sB,EAAM1sB,QAC1BnL,GAAMiF,MAAQ,IAAK4yB,EAAM5yB,OACzBjF,GAAMkL,MAAQ,IAAK2sB,EAAM3sB,OACzBlL,GAAMxE,KAAO,IAAKq8B,EAAMr8B,MACpBq8B,EAAM7sB,OAAMhL,GAAMgL,KAAO,IAAK6sB,EAAM7sB,OACpC6sB,EAAM5sB,KACRjL,GAAMiL,KAAO,IAAK4sB,EAAM5sB,MACfjL,GAAMiL,OACfjL,GAAMiL,KAAO,IACRjL,GAAMiL,KACT/D,UAAU,EACVqc,MAAO,KACPhM,MAAO,KACPvO,QAAS,CAAA,IAGf,CCyHI8uB,EACF,EAEA/tB,EAAG0tB,WAAa,SAAU3hC,GACxB0hC,EAAYI,KAAKx/B,KAAMtC,GnBjJP,CAACA,IACnB6C,EAAM1B,EAAUnB,GAChB8C,EAAO3B,EAAU,GAAGnB,OACpB,IAAK,MAAMiiC,KAAYl/B,EACrBk/B,KmB8IAC,CAAUliC,EACZ,EAEAiU,EAAG4tB,UAAY,SAAU7hC,GACvB4hC,EAAWE,KAAKx/B,KAAMtC,GnBlID,CAACA,IACxBkD,EAAQpE,EAAcqC,EAAUnB,IAChCmD,EAASrE,EAAcqC,EAAU,GAAGnB,SmBiIlCmiC,CAAeniC,EACjB,CACF","x_google_ignoreList":[1,2,19]}\ No newline at end of filediff --git a/dist/p5.brush.js b/dist/p5.brush.jsindex 7a0a404..6492a88 100644--- a/dist/p5.brush.js+++ b/dist/p5.brush.js@@ -1,2 +1,2 @@-var t,e;t=this,e=function(t){let e,r,n,i,o,a=null,s=null,l=null;const c=[],h=t=>!!t&&"function"==typeof t.begin&&"function"==typeof t.end&&!!t.renderer&&!!t.renderer._pInst,u=t=>"number"==typeof t&&Number.isFinite(t)&&t>0,f=t=>{try{return t()}catch(t){return}},m=t=>!!t&&"function"==typeof t.pixelDensity&&"function"==typeof t.createFramebuffer&&u(f(()=>t.width))&&u(f(()=>t.height))&&"webgl2"===f(()=>t.webglVersion),d=t=>(m(t)&&(s=t),s),g=()=>(l&&m(l)?d(l):null)||d(window.self?.p5?.instance??null)||d(n)||s,p=()=>i?._renderer?.activeFramebuffer?.()??null,x=t=>{if(!t)return;if(h(t))return void t.draw(()=>i.clear());const e=t.drawingContext;e.save(),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,t.width,t.height),e.restore()},y=()=>({width:Math.max(1,Math.round(e*o)),height:Math.max(1,Math.round(r*o))}),_=t=>{if(!t)return null;const{width:e,height:r}=y(),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}},b=()=>{const{width:t,height:e}=y();return{minX:0,minY:0,maxX:t,maxY:e}},v=(t,e=!0)=>{const r=_(t);if(!r)return null;const{height:n}=y();return{x:r.minX,y:e?n-r.maxY:r.minY,width:r.maxX-r.minX,height:r.maxY-r.minY}},w=(t,e,r,n=!0)=>{const i=v(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()},R=(t=!1)=>{const n=((t=!1)=>{const e=g();if(!t){if(!e)throw new Error("p5.brush could not resolve an active WEBGL sketch. Call brush.instance(p) and brush.load() after createCanvas(..., WEBGL).");return{renderer:e,width:e.width,height:e.height}}if(h(t)){const r=t.renderer._pInst;if(d(r),e&&r!==e)throw new Error("p5.brush only supports p5.Framebuffer targets created from the active sketch");return{renderer:r,width:t.width,height:t.height}}return{renderer:t,width:t.width,height:t.height}})(t);if(i=n.renderer,d(t?g():i),"webgl2"!==i.webglVersion)throw new Error("p5.brush requires a WEBGL canvas");e=n.width,r=n.height,A=!0,i.loaded&&I.load()};let A=!1;const E=()=>{A||R()},M={},S=t=>{n=t,d(t)},T=t=>{c.push(l),l=t,S(t)},P=()=>{l=c.pop()??null},k=()=>{i?.loaded||(E(),I.load())},I={isBlending:!1,cachedColor:new Object,markDirtyRect(t,e){const r=_(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){t&&(x(t),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:(t,e)=>t?t.dirtyRect?e&&p()?b():_(((t,e=0)=>t?{minX:t.minX-e,minY:t.minY-e,maxX:t.maxX+e,maxY:t.maxY+e}:null)(t.dirtyRect,e?2:4)):b():null,load(){o=i.pixelDensity();const t=Math.max(1,Math.round(e*o)),n=Math.max(1,Math.round(r*o)),a=!i.mask||!i.glMask||i.mask.width!==t||i.mask.height!==n||i.glMask.width!==e||i.glMask.height!==r,s=!i.blendSourceFramebuffer||i.blendSourceFramebuffer.width!==e||i.blendSourceFramebuffer.height!==r||"function"==typeof i.blendSourceFramebuffer.pixelDensity&&i.blendSourceFramebuffer.pixelDensity()!==o,l=!i.fillMaskFramebuffer||i.fillMaskFramebuffer.width!==e||i.fillMaskFramebuffer.height!==r||"function"==typeof i.fillMaskFramebuffer.pixelDensity&&i.fillMaskFramebuffer.pixelDensity()!==o;i.loaded&&!a||(i.glMask?.remove&&i.glMask.remove(),i.mask=new OffscreenCanvas(t,n),i.mask.drawingContext=i.mask.getContext("2d"),i.glMask=i.createFramebuffer({width:e,height:r,density:o,antialias:!1,depth:!1,stencil:!1}),i.loaded=!0,i.shaderProgram??=i.createShader("#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.);}")),s&&(i.blendSourceFramebuffer?.remove&&i.blendSourceFramebuffer.remove(),i.blendSourceFramebuffer=i.createFramebuffer({width:e,height:r,density:o,antialias:!1,depth:!1,stencil:!1})),l&&(i.fillMaskFramebuffer?.remove&&i.fillMaskFramebuffer.remove(),i.fillMaskFramebuffer=i.createFramebuffer({width:e,height:r,density:o,antialias:!1,depth:!1,stencil:!1}),x(i.fillMaskFramebuffer)),this.mask=i.mask,this.glMask=i.glMask,this.ctx=this.mask.drawingContext,this.mask.dirtyRect??=null,this.mask.isDrawn??=!1,this.ctx.imageSmoothingEnabled=!1,this.glMask.dirtyRect??=null,this.glMask.isDrawn??=!1},blend(t=!1,e=!1){k();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,x(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))},applyShader(t,n){if(!t?.isDrawn)return;const o=this.getCompositeRect(t,n);if(!o)return void this.clearMask(t);const s=i.drawingContext,l=i.shaderProgram,c=p(),h=C(c??i,o),u=!!c,f=s.getParameter(s.DEPTH_TEST);s.disable(s.DEPTH_TEST),i.push(),i.translate(0,0),i.shader(l),l.setUniform("u_source",h),l.setUniform("u_targetIsFramebuffer",u),l.setUniform("u_isBrush",n),n?l.setUniform("u_mask",t):l.setUniform("u_mask",((t,e=null)=>{const r=i.fillMaskFramebuffer,n=i.drawingContext,o=_(e)??b(),s=o.maxX-o.minX,l=o.maxY-o.minY;a&&a.width===s&&a.height===l||(a=new OffscreenCanvas(s,l),a.drawingContext=a.getContext("2d"));const c=a.drawingContext;return c.clearRect(0,0,s,l),c.drawImage(t,o.minX,o.minY,s,l,0,0,s,l),x(r),n.bindTexture(n.TEXTURE_2D,r.colorTexture),n.texSubImage2D(n.TEXTURE_2D,0,o.minX,o.minY,n.RGBA,n.UNSIGNED_BYTE,a),r})(t,o)),l.setUniform("u_color",this.cachedColor),w(s,o,()=>{i.fill(0,0,0,0),i.noStroke(),i.rect(-e/2,-r/2,e,r)},!u),i.pop(),i.resetShader(),f&&s.enable(s.DEPTH_TEST),this.clearMask(t)}},C=(t,n=null)=>{const o=i.blendSourceFramebuffer,a=i.drawingContext,s=h(t),{width:l,height:c}=y(),u=n?v(n):null,f=a.getParameter(a.READ_FRAMEBUFFER_BINDING),m=a.getParameter(a.DRAW_FRAMEBUFFER_BINDING);return(s?t.renderer:i._renderer)?.flushDraw?.(),s?(o.draw(()=>{w(i.drawingContext,n,()=>{i.clear(),i.push(),i.imageMode(i.CENTER),i.image(t,0,0,e,r),i.pop()},!1)}),o):(a.bindFramebuffer(a.READ_FRAMEBUFFER,null),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,o.framebuffer),a.clearColor(0,0,0,0),a.clear(a.COLOR_BUFFER_BIT),a.blitFramebuffer(u?.x??0,u?.y??0,u?u.x+u.width:l,u?u.y+u.height:c,u?.x??0,u?.y??0,u?u.x+u.width:l,u?u.y+u.height:c,a.COLOR_BUFFER_BIT,a.NEAREST),a.bindFramebuffer(a.READ_FRAMEBUFFER,f),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,m),o)},L=Math.sqrt(3),F=.5*(L-1),D=(3-L)/6,N=t=>0|Math.floor(t),B=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 Y(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=>B[t%12*2]),n=new Float64Array(e).map(t=>B[t%12*2+1]);return function(t,i){let o=0,a=0,s=0;const l=(t+i)*F,c=N(t+l),h=N(i+l),u=(c+h)*D,f=t-(c-u),m=i-(h-u);let d,g;f>m?(d=1,g=0):(d=0,g=1);const p=f-d+D,x=m-g+D,y=f-1+2*D,_=m-1+2*D,b=255&c,v=255&h;let w=.5-f*f-m*m;if(w>=0){const t=b+e[v];w*=w,o=w*w*(r[t]*f+n[t]*m)}let R=.5-p*p-x*x;if(R>=0){const t=b+d+e[v+g];R*=R,a=R*R*(r[t]*p+n[t]*x)}let A=.5-y*y-_*_;if(A>=0){const t=b+1+e[v+1];A*=A,s=A*A*(r[t]*y+n[t]*_)}return 70*(o+a+s)}}function X(t,e){let r=new z(t),n=()=>r.next();return n.double=()=>n()+11102230246251565e-32*(2097152*n()|0),n.int32=()=>4294967296*r.next()|0,n.quick=n,n}class z{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=X(Math.random()),U=X(Math.random());const G=[],V=t=>G.push(t);let W=Y(X(Math.random())),$=Y(X(Math.random()));const H=(t=0,e=1)=>t+O()*(e-t),j=(t=0,e=1)=>t+U()*(e-t),K=t=>t[~~(O()*t.length)],Z=(t,e)=>~~H(t,e),q=(t,e)=>~~j(t,e),J=(t=0,e=1)=>{const r=1-O(),n=O();return Math.sqrt(-2*Math.log(r))*st(360*n)*e+t},Q=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)},tt=(t,e,r,n,i,o=!1)=>{let a=n+(t-e)/(r-e)*(i-n);return o?n<i?et(a,n,i):et(a,i,n):a},et=(t,e,r)=>Math.max(Math.min(t,r),e),rt=t=>(t%=360)<0?t+360:t,nt=1440,it=2*Math.PI/nt,ot=new Float32Array(nt).fill(NaN),at=new Float32Array(nt).fill(NaN),st=t=>{const e=~~(4*rt(t));let r=ot[e];return isNaN(r)&&(r=Math.cos(e*it),ot[e]=r),r},lt=t=>{const e=~~(4*rt(t));let r=at[e];return isNaN(r)&&(r=Math.sin(e*it),at[e]=r),r},ct=(t,e=!1)=>{if(e||i&&"function"==typeof i.angleMode&&i.angleMode()===i.RADIANS){let e=180*t/Math.PI%360;return e<0?e+360:e}return t},ht=(t,e=!1)=>e||i&&"function"==typeof i.angleMode&&i.angleMode()===i.RADIANS?180*t/Math.PI:t,ut=(t,e,r,n,i)=>{let o=st(i),a=lt(i);return{x:o*(r-t)+a*(n-e)+t,y:o*(n-e)-a*(r-t)+e}},ft=(t,e,r,n)=>Math.hypot(r-t,n-e),mt=(t,e,r,n)=>ct(Math.atan2(-(n-e),r-t),!0),dt=(t,e,r,n,i=!1)=>{let o=t.x,a=t.y,s=e.x,l=e.y,c=r.x,h=r.y,u=n.x,f=n.y;if(o===s&&a===l||c===u&&h===f)return!1;let m=s-o,d=l-a,g=u-c,p=f-h,x=p*m-g*d;if(0===x)return!1;let y=(g*(a-h)-p*(o-c))/x,_=(m*(a-h)-d*(o-c))/x;return!(!i&&(_<0||_>1))&&{x:o+y*m,y:a+y*d}},gt=()=>i._renderer.uModelMatrix.mat4[12],pt=()=>i._renderer.uModelMatrix.mat4[13],xt=()=>i._renderer.uModelMatrix.mat4[0],yt=()=>i._renderer.uModelMatrix.mat4[1],_t=()=>i._renderer.uModelMatrix.mat4[4],bt=()=>i._renderer.uModelMatrix.mat4[5];let vt=!1;function wt(){vt||(k(),At=.01*e,Et=-.5*e,Mt=-.5*r,St=Math.round(2*e/At),Tt=Math.round(2*r/At),Ft("hand",(t,e)=>{const r=j(.2,.8),n=q(5,10);return Dt(e,(e,i)=>.5*n*lt(r*i*e+q(15,25))*.2*st(t)+$(e,i)*n*.7)}),Ft("curved",(t,e)=>{let r=q(-10,10);return q(0,100)%2==0&&(r*=-1),Dt(e,(e,n)=>3*tt($(.02*e+.03*t,.02*n+.03*t),0,1,-r,r))}),Ft("zigzag",(t,e)=>{let r=q(-30,-15)+Math.abs(44*lt(t));q(0,100)%2==0&&(r*=-1);let n=r,i=0;for(let t=0;t<St;t++){for(let r=0;r<Tt;r++)e[t][r]=i,i+=n,n*=-1;i+=n,n*=-1}return e}),Ft("waves",(t,e)=>{const r=q(10,15)+5*lt(t),n=q(3,6)+3*st(t),i=q(20,35);return Dt(e,(t,e)=>lt(r*t)*i*st(e*n)+q(-3,3))}),Ft("seabed",(t,e)=>{const r=j(.4,.8),n=q(18,26);return Dt(e,(e,i)=>1.1*n*lt(r*i*e+q(15,20))*st(t))}),Ft("spiral",(t,e)=>{const r=q(5,10),n=2*q(0,2)-1,i=q(65,80),o=Array.from({length:r},()=>({x:j(.1,.9)*St,y:j(.1,.9)*Tt}));return Dt(e,(t,e)=>{let r=0,a=0;for(const s of o){const o=t-s.x,l=e-s.y,c=1/(o*o+l*l+1),h=Math.atan2(l,o)*(180/Math.PI),u=n*(h+i)*Math.PI/180;r+=c*Math.cos(u),a+=c*Math.sin(u)}return Math.atan2(a,r)*(180/Math.PI)})}),Ft("columns",(t,e)=>{const r=q(3,8),n=q(25,45);return Dt(e,(t,e)=>lt(t*r)*n)}),vt=!0)}class Rt{constructor(t,e){wt(),this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=Rt.getColIndex(t),this.rowIdx=Rt.getRowIndex(e)}reset(){this.plotted=0}isIn(){return M.field.isActive?Rt.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const t=e,n=r,i=this.x+gt(),o=this.y+pt();return i>=-.3*t&&i<=1.3*t&&o>=-.3*n&&o<=1.3*n}angle(){return this.isIn()&&M.field.isActive?Pt.get(M.field.current).field[this.colIdx][this.rowIdx]*M.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())for(let o=0;o<e/r;o++){const e=this.angle()-(n?t.angle(this.plotted):t);this.update(this.x+r*st(e),this.y+r*lt(e)),this.plotted+=r/i}else this.plotted+=r/i}static getRowIndex(t,e=1){const r=t+pt()-Mt;return Math.round(r/At/e)}static getColIndex(t,e=1){const r=t+gt()-Et;return Math.round(r/At/e)}static isIn(t,e){return t>=0&&e>=0&&t<St&&e<Tt}}M.field={isActive:!1,current:null,wiggle:1};let At,Et,Mt,St,Tt,Pt=new Map;const kt=new Set(["degrees","radians"]);function It(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!kt.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function Ct(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(St).fill(null).map(()=>new Float32Array(Tt))),t.angleMode)}function Lt(t){if(M.field.wiggle||(M.field.wiggle=1),wt(),!Pt.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(Pt.keys()).join(", ")}.`);M.field.isActive=!0,M.field.current=t;const e=Pt.get(t);e.field||(e.field=Ct(e,0))}function Ft(t,e,r={}){Pt.set(t,{gen:e,field:null,angleMode:It(r)})}function Dt(t,e){for(let r=0;r<St;r++)for(let n=0;n<Tt;n++)t[r][n]=e(r,n);return t}class Nt{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=dt(t.point1,t.point2,e,n);i&&r.push(i)}return this._intersectionCache[e]=r,r}show(){M.stroke&&this.draw(),M.hatch&&this.hatch(),M.fill&&this.fill()}}class Bt{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:ct(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:ct(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=ct(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)),tt(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,o){wt();const a=.5,s=[],l=Math.round(this.length/a),c=new Rt(t+e/2,n+r/2);let h=0,u=0;for(let t=0;t<l;t++){c.plotTo(this,a,a);const t=this.calcIndex(c.plotted);h+=a,(h>=(0===o?5:Math.max(this.segments[t]*o*j(.7,1.3),20))||t>=u)&&c.x&&(s.push([c.x-e/2,c.y-r/2]),h=0,t>=u&&u++)}return new Nt(s)}show(t,e,r=1){M.stroke&&this.draw(t,e,r),M.hatch&&this.hatch(t,e,r),M.fill&&this.fill(t,e,r)}}let Yt,Xt,zt,Ot;class Ut{constructor(){this.isClosed=!1,this.curvature=Xt,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){$t(this.vert,this.curvature,this.isClosed).show()}}function Gt(t=0){Xt=et(t,0,1),Yt=new Ut}function Vt(t,e,r=1){if(!Yt)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");Yt.vertex(t,e,r)}function Wt(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 $t(t,e=.5,r=!1){const n=new Bt(0===e?"segments":"curve"),i=2*Math.PI;if(r&&0!==e&&t.push(t[1]),t&&t.length>0){let o,a,s,l=0;for(let c=0;c<t.length-1;c++)if(e>0&&c<t.length-2){const h=t[c],u=t[c+1],f=t[c+2],m=ft(h[0],h[1],u[0],u[1]),d=ft(u[0],u[1],f[0],f[1]),g=mt(h[0],h[1],u[0],u[1]),p=mt(u[0],u[1],f[0],f[1]),x=e*Math.min(m,d,.5*Math.min(m,d)),y=Math.max(m,d),_=m-x,b=d-x;if(Math.floor(g)===Math.floor(p)){const e=r&&0===c?0:m-l,i=r?0===c?0:d-s:d;n.addSegment(g,e,h[2],!0),c===t.length-3&&n.addSegment(p,i,u[2],!0),l=0,0===c&&(o=m,s=x,a=t[1],l=0)}else{const e={x:u[0]-x*st(-g),y:u[1]-x*lt(-g)},f={x:e.x+y*st(90-g),y:e.y+y*lt(90-g)},m={x:u[0]+x*st(-p),y:u[1]+x*lt(-p)},d={x:m.x+y*st(90-p),y:m.y+y*lt(90-p)},v=dt(e,f,m,d,!0),w=ft(e.x,e.y,v.x,v.y),R=ft(e.x,e.y,m.x,m.y)/2,A=i*w*(2*Math.asin(R/w)*(180/Math.PI))/360,E=r&&0===c?0:_-l,M=c===t.length-3?r?o-x:b:0;n.addSegment(g,E,h[2],!0),n.addSegment(g,isNaN(A)?0:A,h[2],!0),n.addSegment(p,M,u[2],!0),l=x,0===c&&(o=_,s=x,a=[e.x,e.y])}c===t.length-3&&n.endPlot(p,u[2],!0)}else if(0===e){const e=t[c],r=t[c+1],i=ft(e[0],e[1],r[0],r[1]),o=mt(e[0],e[1],r[0],r[1]);n.addSegment(o,i,r[2],!0),c===t.length-2&&n.endPlot(o,1,!0)}n.origin=r&&0!==e?a:t[0]}return n}const Ht=(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 jt,Kt,Zt,qt,Jt,Qt=!1,te=0,ee=0,re=null,ne=null;const ie={},oe={};let ae=1,se=0,le=0,ce=1,he=0,ue=0,fe=0,me=0,de=1,ge=1,pe=new Float32Array(8192),xe=0,ye=2048,_e=32768,be=null,ve=null,we=null,Re=null,Ae=null;const Ee={},Me={};let Se=0,Te=new Float32Array(1280),Pe=0,ke=256,Ie=null;const Ce=new Map,Le=new Float32Array([-1,-1,1,-1,-1,1,1,1]);function Fe(){const t=I.glMask?.renderer;t&&(t._curShader=null,t._cachedBlendMode=null,t._isBlending=null,jt.activeTexture(jt.TEXTURE0),jt.bindTexture(jt.TEXTURE_2D,null),jt.blendEquation(jt.FUNC_ADD),jt.blendFunc(jt.ONE,jt.ONE_MINUS_SRC_ALPHA))}function De(){return Kt}function Ne(){const t=jt.isEnabled(jt.DEPTH_TEST);var e;Ne._hadDepthTest=t,t&&jt.disable(jt.DEPTH_TEST),ne=i._renderer.activeFramebuffer?.()??null,ne?._beforeEnd&&ne._beforeEnd(),jt.bindFramebuffer(jt.FRAMEBUFFER,(e=I.glMask)?"function"==typeof e._framebufferToBind?e._framebufferToBind():e.framebuffer??null:null),jt.viewport(0,0,I.glMask.width*I.glMask.density,I.glMask.height*I.glMask.density)}function Be(){Ne._hadDepthTest&&jt.enable(jt.DEPTH_TEST),Ne._hadDepthTest=!1,ne?._beforeBegin?ne._beforeBegin():(jt.bindFramebuffer(jt.FRAMEBUFFER,null),i._renderer.viewport(i._renderer._origViewport.width,i._renderer._origViewport.height),i._renderer._applyStencilTestIfClipping?.()),ne=null}function Ye(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 Xe(t,e,r,n){if(xe>=ye){ye*=2;const t=new Float32Array(4*ye);t.set(pe),pe=t}const i=t-fe,o=e-me,a=4*xe,s=ae*i+le*o+he+fe,l=se*i+ce*o+ue+me,c=ge*r*de/2;pe[a]=s,pe[a+1]=l,pe[a+2]=c,pe[a+3]=n/255;const h=s*ge,u=l*ge;be=Ye(be,h-c-1,u-c-1,h+c+1,u+c+1),xe++}function ze(t,e){if(0===Pe)return;I.glMask.isDrawn=!0,Ne();let r=Ce.get(e);r||(r=jt.createTexture(),jt.bindTexture(jt.TEXTURE_2D,r),jt.texImage2D(jt.TEXTURE_2D,0,jt.RGBA,jt.RGBA,jt.UNSIGNED_BYTE,t.canvas),jt.texParameteri(jt.TEXTURE_2D,jt.TEXTURE_MIN_FILTER,jt.LINEAR),jt.texParameteri(jt.TEXTURE_2D,jt.TEXTURE_MAG_FILTER,jt.LINEAR),jt.texParameteri(jt.TEXTURE_2D,jt.TEXTURE_WRAP_S,jt.CLAMP_TO_EDGE),jt.texParameteri(jt.TEXTURE_2D,jt.TEXTURE_WRAP_T,jt.CLAMP_TO_EDGE),Ce.set(e,r)),jt.useProgram(ve),jt.enable(jt.BLEND),jt.blendFunc(jt.ONE_MINUS_DST_ALPHA,jt.ONE),jt.activeTexture(jt.TEXTURE0),jt.bindTexture(jt.TEXTURE_2D,r),jt.uniform1i(Me.u_tex,0);const n=M.stroke.color._array;jt.uniform4f(Me.u_color,...n),jt.uniformMatrix4fv(Me.u_proj,!1,De()),jt.bindVertexArray(we),jt.bindBuffer(jt.ARRAY_BUFFER,Ae);const i=5*Pe*4,o=Te.subarray(0,5*Pe);i>Se?(jt.bufferData(jt.ARRAY_BUFFER,Te,jt.DYNAMIC_DRAW),Se=Te.byteLength):jt.bufferSubData(jt.ARRAY_BUFFER,0,o),jt.drawArraysInstanced(jt.TRIANGLE_STRIP,0,4,Pe),jt.flush(),jt.bindVertexArray(null),jt.bindTexture(jt.TEXTURE_2D,null),Be(),Ie&&(I.markDirtyRect(I.glMask,Ie),Ie=null),Pe=0,Fe()}M.stroke={color:null,weight:1,clipWindow:null,type:"HB",isActive:!1,opacity:1};let Oe=new Map,Ue={a:1,b:0,c:0,d:1,tx:0,ty:0};function Ge(){return i??n??window.self.p5.instance}const Ve={offset:.08,scale:.08,warp:.06,tilt:.06};function We(){return{...M.stroke}}function $e(t){M.stroke={...t}}function He(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.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:{...Ve}};if("object"==typeof t&&!Array.isArray(t)){if("custom"===t.type||"custom"===t.mode){const{mode:e,...r}=t;return{...r,type:"custom",variation:{...Ve,...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,l,c]=[(e-i)/a,(r-i)/a,(n-i)/a];return{type:"custom",min_max:[i,o],variation:{...Ve},curve:t=>t<.5?s+(l-s)*t*2:l+(c-l)*(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=Ce.get(t);e&&jt&&jt.deleteTexture(e),Ce.delete(t)}(r);const n=Ge().createGraphics(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(),_r.imageToWhite(n),_r.tips.set(r,n),e.tipKey=r,void Oe.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 _r.add(e.image.src),Oe.set(t,{param:e,colors:[],buffers:[]}),_r.load()}Oe.set(t,{param:e,colors:[],buffers:[]})}function je(t){if(!Oe.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...Oe.keys()].join(", ")}.`);M.stroke.type=t}function Ke(t,e,r){E(),M.stroke.color=i.color(...arguments),M.stroke.isActive=!0}function Ze(t){M.stroke.weight=t}function qe(t,e,r=1){je(t),Ke(e),Ze(r)}function Je(){return{a:xt(),b:yt(),c:_t(),d:bt(),tx:gt(),ty:pt()}}function Qe(t){const[e,r,n,i]=t;return{minX:Math.min(e,n),minY:Math.min(r,i),maxX:Math.max(e,n),maxY:Math.max(r,i)}}let tr,er,rr,nr;const ir={};function or(t,n,i,a=!1){ae=xt(),se=yt(),le=_t(),ce=bt(),he=gt(),ue=pt(),fe=e/2,me=r/2,de=Math.sqrt(ae*ae+se*se),ge=o,Ue=Je(),tr=new Rt(t+e/2,n+r/2),er=i,rr=a,rr&&rr.calcIndex(0)}const ar=[];function sr(t,n){n||(nr=t),function(){ir.seed=999999*H();const{param:t}=Oe.get(M.stroke.type)??{};if(!t)return;ir.p=t;const{pressure:n}=t;if(ir.a="custom"!==n.type?H(-1,1):0,ir.b="custom"!==n.type?H(1,1.5):0,"custom"!==n.type)ir.cp=H(3,3.5),ir.ct=0,ir.cs=1,ir.ck=0;else{const t=n.variation??Ve;ir.cp=H(-t.offset,t.offset),ir.ct=H(-t.warp,t.warp),ir.cs=H(1-t.scale,1+t.scale),ir.ck=H(-t.tilt,t.tilt)}if([ir.min,ir.max]=n.min_max,ir.noiseoffset=.03,!rr){const t=nr*Math.PI/180;ir.cos=Math.cos(t),ir.sin=Math.sin(t)}!function(){k(),function(){const t=i?.glMask;t&&(re=t,re.dirtyRect??=null,re.isDrawn??=!1,I.glMask=re)}();const t=i.drawingContext,n=!Qt||jt!==t;(n||te!==e||ee!==r)&&(Kt=new Float32Array([2/e,0,0,0,0,2/r,0,0,0,0,1,0,-1,-1,0,1]),te=e,ee=r),n&&(jt=t,Jt=Ht(jt,"#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);}"),jt.useProgram(Jt),jt.enable(jt.BLEND),jt.blendFunc(jt.ONE_MINUS_DST_ALPHA,jt.ONE),["a_position","a_radius","a_alpha"].forEach(t=>ie[t]=jt.getAttribLocation(Jt,t)),["u_matrix","u_color"].forEach(t=>oe[t]=jt.getUniformLocation(Jt,t)),Zt=jt.createVertexArray(),jt.bindVertexArray(Zt),qt=jt.createBuffer(),jt.bindBuffer(jt.ARRAY_BUFFER,qt),jt.bufferData(jt.ARRAY_BUFFER,pe.byteLength,jt.DYNAMIC_DRAW),_e=pe.byteLength,jt.enableVertexAttribArray(ie.a_position),jt.vertexAttribPointer(ie.a_position,2,jt.FLOAT,!1,16,0),jt.enableVertexAttribArray(ie.a_radius),jt.vertexAttribPointer(ie.a_radius,1,jt.FLOAT,!1,16,8),jt.enableVertexAttribArray(ie.a_alpha),jt.vertexAttribPointer(ie.a_alpha,1,jt.FLOAT,!1,16,12),jt.bindVertexArray(null),Ce.clear(),ve=Ht(jt,"#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=>Ee[t]=jt.getAttribLocation(ve,t)),["u_proj","u_color","u_tex"].forEach(t=>Me[t]=jt.getUniformLocation(ve,t)),we=jt.createVertexArray(),jt.bindVertexArray(we),Re=jt.createBuffer(),jt.bindBuffer(jt.ARRAY_BUFFER,Re),jt.bufferData(jt.ARRAY_BUFFER,Le,jt.STATIC_DRAW),jt.enableVertexAttribArray(Ee.a_corner),jt.vertexAttribPointer(Ee.a_corner,2,jt.FLOAT,!1,0,0),Ae=jt.createBuffer(),jt.bindBuffer(jt.ARRAY_BUFFER,Ae),jt.bufferData(jt.ARRAY_BUFFER,Te.byteLength,jt.DYNAMIC_DRAW),Se=Te.byteLength,jt.enableVertexAttribArray(Ee.a_pos),jt.vertexAttribPointer(Ee.a_pos,2,jt.FLOAT,!1,20,0),jt.vertexAttribDivisor(Ee.a_pos,1),jt.enableVertexAttribArray(Ee.a_size),jt.vertexAttribPointer(Ee.a_size,1,jt.FLOAT,!1,20,8),jt.vertexAttribDivisor(Ee.a_size,1),jt.enableVertexAttribArray(Ee.a_angle),jt.vertexAttribPointer(Ee.a_angle,1,jt.FLOAT,!1,20,12),jt.vertexAttribDivisor(Ee.a_angle,1),jt.enableVertexAttribArray(Ee.a_alpha),jt.vertexAttribPointer(Ee.a_alpha,1,jt.FLOAT,!1,20,16),jt.vertexAttribDivisor(Ee.a_alpha,1),jt.bindVertexArray(null),Qt=!0)}();const o=!0!==I.isBrush;I.isBrush=!0,o&&(I.justChanged=!0),I.blend(M.stroke.color),ir.alpha=["default","spray"].includes(ir.p.type)?ir.p.opacity:ir.p.opacity/Math.min(M.stroke.weight,1.3);{const t=e/2,n=r/2,i=Ue;if(M.stroke.clipWindow){const{inverse:e,bounds:r}=M.stroke.clipWindow,o=e.a*i.a+e.c*i.b,a=e.a*i.c+e.c*i.d,s=e.b*i.a+e.d*i.b,l=e.b*i.c+e.d*i.d;ir.clipA=o,ir.clipB=s,ir.clipC=a,ir.clipD=l,ir.clipTX=e.a*i.tx+e.c*i.ty+e.tx-o*t-a*n,ir.clipTY=e.b*i.tx+e.d*i.ty+e.ty-s*t-l*n,ir.clipMinX=r.minX,ir.clipMaxX=r.maxX,ir.clipMinY=r.minY,ir.clipMaxY=r.maxY}else{const r="custom"===ir.p.type||"image"===ir.p.type?Math.max(.05*e,fr()):.05*e;ir.clipA=i.a,ir.clipB=i.b,ir.clipC=i.c,ir.clipD=i.d,ir.clipTX=i.tx-i.a*t-i.c*n,ir.clipTY=i.ty-i.b*t-i.d*n,ir.clipMinX=-t-r,ir.clipMaxX=t+r,ir.clipMinY=-n-r,ir.clipMaxY=n+r}}gr()}();const o=function(){const{param:t}=Oe.get(M.stroke.type)??{};return t?t.spacing:1}(),a=Math.round(er*(n?t:1)/o);for(let e=0;e<a;e++)ar.length<2*a&&ar.push(J()),lr(),n?tr.plotTo(rr,o,o,t,e<10):tr._moveToDegrees(t,o,o);!function(){gr(),function(){if(0===xe)return;I.glMask.isDrawn=!0,Ne();const t=M.stroke.color._array;jt.useProgram(Jt),jt.enable(jt.BLEND),jt.blendFunc(jt.ONE_MINUS_DST_ALPHA,jt.ONE),jt.bindVertexArray(Zt),jt.bindBuffer(jt.ARRAY_BUFFER,qt);const e=16*xe,r=pe.subarray(0,4*xe);e>_e?(jt.bufferData(jt.ARRAY_BUFFER,pe,jt.DYNAMIC_DRAW),_e=pe.byteLength):jt.bufferSubData(jt.ARRAY_BUFFER,0,r),jt.uniform4f(oe.u_color,...t),jt.uniformMatrix4fv(oe.u_matrix,!1,De()),jt.drawArrays(jt.POINTS,0,xe),jt.flush(),jt.bindVertexArray(null),Be(),be&&(I.markDirtyRect(I.glMask,be),be=null),xe=0,Fe()}();const t=ir.p?.type;"image"===t?ze(_r.tips.get(ir.p.image.src),ir.p.image.src):"custom"===t&&ze(_r.tips.get(ir.p.tipKey),ir.p.tipKey)}()}function lr(){if(!ur())return;const t=cr(),e=tt(W(ir.seed+.002*tr.plotted,0),0,1,1-ir.noiseoffset,1+ir.noiseoffset);switch(ir.p.type){case"spray":!function(t){const e=M.stroke.weight*ir.p.scatter*t+M.stroke.weight*K(ar)*ir.p.scatter/3,r=ir.p.weight*H(.9,1.1),n=Math.ceil(ir.p.grain/t);for(let t=0;t<n;t++){const t=H(.9,1.1),n=t*e*H(-1,1),i=H(-1,1),o=Math.sqrt((t*e)**2-n**2);Xe(tr.x+n,tr.y+i*o,r,ir.alpha)}}(t*e);break;case"marker":mr(t*e);break;case"custom":case"image":dr(t*e);break;default:!function(t,e=1){const r=(e=tt(e,0,1,.9,1.05))*M.stroke.weight*ir.p.scatter*(ir.p.sharpness+(1-ir.p.sharpness)*K(ar)/t);if(H(0,ir.p.grain*t)>.4){let e,n;if(rr)e=.7*r*H(-1,1),n=r*H(-1,1);else{const t=r*H(-1,1),i=.3*r*H(-1,1);e=t*-ir.sin+i*ir.cos,n=t*ir.cos+i*ir.sin}const i=t*t*ir.p.weight*H(.85,1.15)*M.stroke.weight,o=Math.max(.9,t)*ir.alpha*H(.75,1.1);Xe(tr.x+e,tr.y+n,i,o)}}(t*e)}}function cr(){return rr?hr()*rr.pressure(tr.plotted):hr()}function hr(){return"custom"===ir.p.pressure.type?tt(ir.p.pressure.curve(Math.max(0,Math.min(1,.5+(tr.plotted/er-.5+ir.ct)*ir.cs)))+ir.cp+ir.ck*(tr.plotted/er-.5),0,1,ir.min,ir.max,!0):function(t=.5+ir.p.pressure.curve[0]*ir.a,e=1-ir.p.pressure.curve[1]*ir.b,r=ir.cp,n=ir.min,i=ir.max){const o=t*er,a=(tr.plotted<o?1.2*e:.8*e)*(er/2);return tt(1/(1+Math.pow(Math.abs((tr.plotted-o)/a),2*r)),0,1,n,i)}()}function ur(){const t=ir.clipA*tr.x+ir.clipC*tr.y+ir.clipTX;if(t<ir.clipMinX||t>ir.clipMaxX)return!1;const e=ir.clipB*tr.x+ir.clipD*tr.y+ir.clipTY;return e>=ir.clipMinY&&e<=ir.clipMaxY}function fr(){const t=Math.max(1,ir.max??1),e=M.stroke.weight*ir.p.scatter,r=M.stroke.weight*ir.p.weight*t;return Math.max(8,1.5*e+.75*r)}function mr(t,e=!0,r=ir.alpha){const n=e?M.stroke.weight*ir.p.scatter:0,i=e?n*H(-1,1):0,o=e?n*H(-1,1):0;Xe(tr.x+i,tr.y+o,M.stroke.weight*ir.p.weight*t,r*Math.max(.8,t)*H(.9,1.1))}function dr(t,e=ir.alpha){const r=M.stroke.weight*ir.p.scatter,n=r*H(-1,1),i=r*H(-1,1),o=ir.p.weight*M.stroke.weight*t,a=fr();let s=0;"random"===ir.p.rotate?s=Z(0,360)*(Math.PI/180):"natural"===ir.p.rotate&&(s=((rr?-rr.angle(tr.plotted):-nr)+tr.angle())*(Math.PI/180)),function(t,e,r,n,i,o=0){if(Pe>=ke){ke*=2;const t=new Float32Array(5*ke);t.set(Te),Te=t}const a=t-fe,s=e-me,l=ae*a+le*s+he+fe,c=se*a+ce*s+ue+me,h=ge*r*de/2,u=ge*o*de,f=5*Pe;Te[f]=l,Te[f+1]=c,Te[f+2]=h,Te[f+3]=n,Te[f+4]=i/255;const m=l*ge,d=c*ge,g=1.42*h+u;Ie=Ye(Ie,m-g-1,d-g-1,m+g+1,d+g+1),Pe++}(tr.x+n,tr.y+i,o,s,e*Math.max(.8,t)*H(.9,1.1),a)}function gr(){if(!1!==ir.p.markerTip&&ur()){let t=cr(),e=ir.alpha;if("marker"===ir.p.type)for(let r=1;r<10;r++)mr(t*r/10,!0,8*e);else if("custom"===ir.p.type||"image"===ir.p.type)for(let r=1;r<5;r++)dr(t*r/10,2*e)}}function pr(t,e,r,n){if(!M.stroke.isActive||!M.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");wt();let i=ft(t,e,r,n);0!=i&&(or(t,e,i),sr(mt(t,e,r,n),!1))}V(()=>{ar.length=0});const xr=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate","markerTip"],yr=[["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]}]],["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 yr){let e={};for(let r=0;r<t[1].length;r++)e[xr[r]]=t[1][r];He(t[0],e)}Nt.prototype.draw=function(t=!1,e,r){let n=We();if(t&&qe(t,e,r),n.isActive)for(let t of this.sides)pr(t[0].x,t[0].y,t[1].x,t[1].y);$e(n)},Bt.prototype.draw=function(t,e,r){We().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,n){wt(),or(e,r,t.length,t),sr(n,!0)}(this,t,e,r))};const _r={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=>new Promise((e,r)=>{const n=new window.Image;n.onload=()=>{const r=Ge().createImage(n.naturalWidth,n.naturalHeight);r.drawingContext.drawImage(n,0,0),_r.imageToWhite(r),this.tips.set(t,r),e()},n.onerror=()=>r(new Error(`Failed to load image tip: ${t}`)),n.crossOrigin="anonymous",n.src=t})))}};function br(){return{...M.hatch}}function vr(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let n=M.hatch;n.isActive=!0,n.dist=t,n.angle=ht(e),n.options=r}function wr(t,e,r,n){const i=e*Math.PI/180,o=Math.cos(i),a=Math.sin(i),s=Math.cos(-i),l=Math.sin(-i),c=t.a,h=c.length,u=new Array(h);let f=Infinity,m=-Infinity;for(let t=0;t<h;t++){const e=c[t][0],r=c[t][1],n=[e*o-r*a,e*a+r*o];u[t]=n,n[1]<f&&(f=n[1]),n[1]>m&&(m=n[1])}const d=[];for(let t=0;t<h;t++){const e=u[t],r=u[(t+1)%h];e[1]!==r[1]&&d.push(e,r)}const g=d.length,p=[];let x=f+.5*r,y=r;for(;x<m;){const t=[];for(let e=0;e<g;e+=2){const r=d[e][1],n=d[e+1][1];(r<=x&&x<n||n<=x&&x<r)&&t.push(d[e][0]+(x-r)/(n-r)*(d[e+1][0]-d[e][0]))}t.sort((t,e)=>t-e);for(let e=0;e<t.length-1;e+=2)p.push({x1:t[e]*s-x*l,y1:t[e]*l+x*s,x2:t[e+1]*s-x*l,y2:t[e+1]*l+x*s});x+=y,y*=n}return p}function Rr(t){const e=M.hatch.dist,r=(M.hatch.angle%180+180)%180,n=M.hatch.options,i=We();M.hatch.hBrush&&qe(...Object.values(M.hatch.hBrush)),Array.isArray(t)||(t=[t]);const o=n.gradient?tt(n.gradient,0,1,1,1.1,!0):1,a=[];for(const n of t)for(const t of wr(n,r,e,o))a.push(t);a.sort((t,e)=>t.x1===e.x1?t.y1-e.y1:t.x1-e.x1);const s=n.rand||0;for(let t=0;t<a.length;t++){const r=a[t];let i=r.x1,o=r.y1,l=r.x2,c=r.y2;s&&(i+=s*e*H(-1,1),o+=s*e*H(-1,1),l+=s*e*H(-1,1),c+=s*e*H(-1,1)),pr(i,o,l,c),t>0&&n.continuous&&pr(a[t-1].x2,a[t-1].y2,i,o)}$e(i)}function Ar(t,e,r){const n=2*Math.PI,i=I.ctx,o=r/2;i.moveTo(t+o,e),i.arc(t,e,o,0,n)}M.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},Nt.prototype.hatch=function(t=!1,e,r){let n=br();t&&vr(t,e,r),n.isActive&&Rr(this),function(t){M.hatch={...t}}(n)},Bt.prototype.hatch=function(t,e,r){br().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,.25),this.pol.hatch())},M.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const Er=()=>({...M.fill});function Mr(t,e,r,n){M.fill.opacity=(arguments.length<4?e:n)||150,M.fill.color=arguments.length<3?i.color(t):i.color(t,e,r),M.fill.isActive=!0}function Sr(t,e="out"){M.fill.bleed_strength=et(t,0,1),M.fill.direction=e}function Tr(t=.4,e=.4){M.fill.texture_strength=et(t,0,1),M.fill.border_strength=et(e,0,1)}let Pr;const kr=[[],[]];function Ir(){for(let t=0;t<512;t++)kr[0][t]=J(.5,.2),kr[1][t]=J(0,.02)}function Cr(t,e,r){return(e.x-t.x)*(r.y-t.y)-(e.y-t.y)*(r.x-t.x)>.01}V(Ir);class Lr{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 l=t[o],c=t[(o+1)%t.length],h={x:c.x-l.x,y:c.y-l.y},u=ut(0,0,h.x,h.y,90),f={x:l.x+h.x/2,y:l.y+h.y/2};i.push({v1:l,v2:c,ray:{point1:f,point2:{x:f.x+u.x,y:f.y+u.y}}})}this.sizeX=e,this.sizeY=n,this.dir=Array(t.length),i.forEach((t,e)=>{let r=0;for(const e of Pr.intersect(t.ray))Cr(t.v1,t.v2,e)&&r++;this.dir[e]=r%2==0});const o=H(-.6,.6)*e,a=H(-.6,.6)*n;this.midP={x:r.x+o,y:r.y+a}}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 l=r,c=r+e,h=this.v[(l-1+this.v.length)%this.v.length],u=this.v[c%this.v.length],f=u.x-h.x,m=u.y-h.y;for(let t=0;t<2;t++){const e=H(.25,.75),n={x:h.x+f*e,y:h.y+m*e},s=r+t;i.splice(s,0,n),o.splice(s,0,H(.4,.7)),a.splice(s,0,this.dir[l%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+H(0,.8*i)));const o=[],a=[],s=[],l=this.midP,c=Pr.sides;for(const t of n){const r=t%e;let n=this.v[r],i=0;for(const[t,e]of c){const r=t.y,o=e.y;if(r>n.y==o>n.y)continue;const a=(n.y-r)/(o-r);n.x<t.x+a*(e.x-t.x)&&i++}i%2==0&&(n={x:l.x+(n.x-l.x)*H(.3,.6),y:l.y+(n.y-l.y)*H(.3,.6)}),o.push(n),a.push(this.m[r]),s.push(!this.dir[r])}return new Lr(o,a,this.midP,s,!1,this.sizeX,this.sizeY)}flipDirs(){return new Lr(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,a=new Array(i),s=new Array(i),l=new Array(o),c=new Array(o),h="out"===M.fill.direction?-90:90;0===kr[0].length&&Ir();const u=kr[0],f=u.length,m=kr[1],d=m.length;let g,p,x,y=0,_=0,b=999===t?H(.6,.8):M.fill.bleed_strength;for(let o=0;o<i;o++){const g=e[o],p=e[o+1<i?o+1:0],x=r[o],v=n[o];if(t<997&&(b=x),b<.05){l[y]=x,c[y]=v,y++,a[_]=(g.x+p.x)/2,s[_]=(g.y+p.y)/2,l[y]=x,c[y]=v,y++,_++;continue}const w=(v?h:-h)+5*H(-1,1),R=st(w),A=lt(w),E=p.x-g.x,M=p.y-g.y,S=R*E+A*M,T=R*M-A*E,P=u[~~(H(0,1)*f)]*H(.65,1.35)*b,k=x+m[~~(H(0,1)*d)];l[y]=x,c[y]=v,y++,a[_]=g.x+.5*E+S*P,s[_]=g.y+.5*M+T*P,l[y]=k,c[y]=v,y++,_++}const v=2024*Math.max(.1,2*M.fill.bleed_strength);if(v&&y>v){const t=Math.ceil(y/v),r=Math.ceil(y/t);g=new Array(r),p=new Array(r),x=new Array(r);let n=0;for(let r=0;r<y;r+=t,n++)g[n]=r%2==0?e[r>>1]:{x:a[r>>1],y:s[r>>1]},p[n]=l[r],x[n]=c[r]}else{g=new Array(y);for(let t=0;t<y;t++)g[t]=t%2==0?e[t>>1]:{x:a[t>>1],y:s[t>>1]};l.length=y,c.length=y,p=l,x=c}return new Lr(g,p,this.midP,x,!1,this.sizeX,this.sizeY)}fill(t,n,i){const a=3*i,s=2*n*(1+i/2),l=!1!==I.isBrush;I.isBrush=!1,l&&(I.justChanged=!0),I.blend(t),I.ctx.save(),I.ctx.setTransform(o*xt(),o*yt(),o*_t(),o*bt(),o*(gt()+e/2),o*(pt()+r/2)),I.ctx.strokeStyle=`rgb(${t._getRed()} ${t._getGreen()} ${t._getBlue()} / ${.005*M.fill.border_strength})`,I.ctx.lineCap="round";const c=Math.max(this.sizeX,this.sizeY),h=H(.15,.7);let u=this.grow();const f=this.scatter(.1).grow().scatter(.75).flipDirs();let m;for(let e=0;e<20;e++){e%4==0&&(u=u.grow()),e%2==0&&(m=[u.grow(1-.0125*e),u.grow(.7-.0125*e),u.grow(.4-.0125*e)]);for(const r of m)r.grow(999).grow(997).layer(e,c,s,t);f.grow(999).flipDirs().grow(997).layer(e,c,s*a,t),e%2==0&&u.grow(h).grow(999).layer(e,c,2*s,t),e%8!=0&&19!==e||(0!==a&&u.erase(3*a,n),I.blend(t,!0,!1,!0))}I.ctx.restore()}layer(t,e,r,n){I.ctx.lineWidth=tt(t,0,24,e/25,e/30,!0),I.ctx.fillStyle=`rgb(${n._getRed()} ${n._getGreen()} ${n._getBlue()} / ${r}%)`,function(t){const e=I.ctx,r=e.getTransform(),n=r.a,i=r.b,o=r.c,a=r.d,s=r.e,l=r.f;let c=Infinity,h=Infinity,u=-Infinity,f=-Infinity;e.beginPath();const m=t[0];let d=n*m.x+o*m.y+s,g=i*m.x+a*m.y+l;c=u=d,h=f=g,e.moveTo(m.x,m.y);for(let r=1;r<t.length;r++){const m=t[r];d=n*m.x+o*m.y+s,g=i*m.x+a*m.y+l,c=Math.min(c,d),h=Math.min(h,g),u=Math.max(u,d),f=Math.max(f,g),e.lineTo(m.x,m.y)}e.closePath();const p=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);I.markDirtyRect(I.mask,{minX:c-p,minY:h-p,maxX:u+p,maxY:f+p})}(this.v),I.ctx.fill(),I.ctx.stroke()}erase(t,e){I.ctx.save();const r=~~(H(80,110)*tt(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:l,y:c}=this.midP;I.ctx.globalCompositeOperation="destination-out";const h=(5-tt(e,80,100,.3,.7,!0))*t/255;I.ctx.fillStyle=`rgb(255 0 0 / ${h})`,I.ctx.lineWidth=0;for(let t=0;t<r;t++){const e=l+J(0,n),r=c+J(0,i),o=H(a,s);I.ctx.beginPath(),Ar(e,r,o),t%5!=0&&I.ctx.fill()}I.ctx.globalCompositeOperation="source-over",I.ctx.restore()}}Nt.prototype.fill=function(t=!1,e,r,n,i,o){let a=Er();t&&(Mr(t,e),Sr(r,o),Tr(n,i)),a.isActive&&(wt(),function(t){if(!M.fill.isActive||!M.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");Pr=t;const e=[...t.vertices],r=~~(.25*e.length*Q({1:5,2:10,3:60})),n=M.fill.bleed_strength,i=e.map((t,e)=>(e>r?1:.3)*H(.85,1.4)*n),o=Z(0,e.length),a=[...e.slice(o),...e.slice(0,o)],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 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}}(a);new Lr(a,i,s,[],!0).fill(M.fill.color,tt(M.fill.opacity,0,255,0,1,!0),M.fill.texture_strength)}(this)),(t=>{M.fill={...t}})(a)},Bt.prototype.fill=function(t,e,r){Er().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,M.fill.bleed_strength<.06?0:tt(M.fill.bleed_strength,0,.6,.2,.6,!0)),this.pol.fill())};const Fr=[];"undefined"!=typeof p5&&p5.registerAddon(function(t,e,r){r.presetup=function(){T(this)},r.predraw=function(){T(this)},r.postsetup=function(){S(this),I.blend(!1,!0),P()},r.postdraw=function(){S(this),I.blend(!1,!0),P()};const n=e.push,i=e.pop,o=e.randomSeed,a=e.noiseSeed;e.push=function(){n.call(this),wt(),Fr.push({fill:{...M.fill},stroke:{...M.stroke},hatch:{...M.hatch},field:{...M.field}})},e.pop=function(){i.call(this),function(){const t=Fr.pop();t&&(M.stroke={...t.stroke},M.field={...t.field},M.hatch={...t.hatch},M.fill={...t.fill})}()},e.randomSeed=function(t){o.call(this,t),(t=>{O=X(t),U=X(`${t}:2`);for(const t of G)t()})(t)},e.noiseSeed=function(t){a.call(this,t),(t=>{W=Y(X(t)),$=Y(X(`${t}:2`))})(t)}}),t.Plot=Bt,t.Polygon=Nt,t.Position=Rt,t.add=He,t.addField=Ft,t.arc=function(t,e,r,n,i){const o=ht(n),a=((ht(i)-o)%360+360)%360;if(0===a)return;const s=new Bt("curve"),l=Math.max(1,Math.ceil(a/90)),c=a/l,h=Math.PI*r*c/180;for(let t=0;t<l;t++)s.addSegment(o+t*c+90,h,1,!0);s.endPlot(o+a+90,1,!0);const u=t+r*st(o),f=e-r*lt(o);s.draw(u,f,1)},t.beginShape=Gt,t.beginStroke=function(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);Ot=[e,r],zt=new Bt(t)},t.box=function(){return[...Oe.keys()]},t.circle=function(t,e,r,n=!1){const i=new Bt("curve"),o=Math.PI*r,a=j(0,360),s=n?()=>1+.2*n*j():()=>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 l=t-r*lt(a),c=e-r*st(-a);i.show(l,c,1)},t.clip=function(t){E();const e=function(t){const e=t.a*t.d-t.b*t.c;return Math.abs(e)<1e-12?null:{a:t.d/e,b:-t.b/e,c:-t.c/e,d:t.a/e,tx:(t.c*t.ty-t.d*t.tx)/e,ty:(t.b*t.tx-t.a*t.ty)/e}}(Je());if(!e)throw new Error("brush.clip() cannot be used with a non-invertible transform.");M.stroke.clipWindow={bounds:Qe(t),inverse:e}},t.endShape=Wt,t.endStroke=function(t,e){if(!zt)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");zt.endPlot(t,e),zt.draw(Ot[0],Ot[1],1),zt=!1},t.field=Lt,t.fill=Mr,t.fillBleed=Sr,t.fillTexture=Tr,t.flowLine=function(t,e,r,n){if(!M.stroke.isActive||!M.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");wt(),or(t,e,r),sr(ct(n),!1)},t.hatch=vr,t.hatchArray=Rr,t.hatchStyle=function(t,e="black",r=1){M.hatch.hBrush={brush:t,color:e,weight:r}},t.instance=S,t.line=pr,t.listFields=function(){return wt(),Array.from(Pt.keys())},t.load=R,t.move=function(t,e,r){if(!zt)throw new Error("move() called without beginStroke(). Call beginStroke() first.");zt.addSegment(t,e,r)},t.noClip=function(){M.stroke.clipWindow=null},t.noField=function(){wt(),M.field.isActive=!1},t.noFill=function(){M.fill.isActive=!1},t.noHatch=function(){M.hatch.isActive=!1,M.hatch.hBrush=!1},t.noStroke=function(){M.stroke.isActive=!1},t.pick=je,t.polygon=function(t){new Nt(t).show()},t.rect=function(t,e,r,n,i="corner"){"center"===i&&(t-=r/2,e-=n/2),Gt(0),Vt(t,e),Vt(t+r,e),Vt(t+r,e+n),Vt(t,e+n),Wt(!0)},t.refreshField=function(t=0){if(!M.field.isActive||!M.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=Pt.get(M.field.current);e.field=Ct(e,t)},t.scaleBrushes=function(t){for(const{param:e}of Oe.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)},t.set=qe,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].");$t(t,e).draw()},t.stroke=Ke,t.strokeWeight=Ze,t.vertex=Vt,t.wRand=Q,t.wiggle=function(t=1){Lt("hand"),M.field.wiggle=t}},"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){let e,n,r,i,o,s=null,a=null;const l=[];let c=!1;const u=t=>!!t&&"function"==typeof t.begin&&"function"==typeof t.end&&!!t.renderer&&!!t.renderer._pInst,h=t=>"number"==typeof t&&Number.isFinite(t)&&t>0,f=t=>{try{return t()}catch(t){return}},x=t=>!!t&&"function"==typeof t.pixelDensity&&"function"==typeof t.createFramebuffer&&h(f(()=>t.width))&&h(f(()=>t.height))&&"webgl2"===f(()=>t.webglVersion),m=t=>(x(t)&&(s=t),s),d=()=>(a&&x(a)?m(a):null)||m(window.self?.p5?.instance??null)||m(r)||s,g=()=>i?._renderer?.activeFramebuffer?.()??null,p=(t=!1)=>{const r=((t=!1)=>{const e=d();if(!t){if(!e)throw new Error("p5.brush could not resolve an active WEBGL sketch. Call brush.instance(p) and brush.load() after createCanvas(..., WEBGL).");return{renderer:e,width:e.width,height:e.height}}if(u(t)){const n=t.renderer._pInst;if(m(n),e&&n!==e)throw new Error("p5.brush only supports p5.Framebuffer targets created from the active sketch");return{renderer:n,width:t.width,height:t.height}}return{renderer:t,width:t.width,height:t.height}})(t);if(i=r.renderer,m(t?d():i),"webgl2"!==i.webglVersion)throw new Error("p5.brush requires a WEBGL canvas");e=r.width,n=r.height,c=!0},y=()=>{c||p()},v=t=>{r=t,m(t)},_=t=>{l.push(a),a=t,v(t)},b=()=>{a=l.pop()??null},w=Math.sqrt(3),R=.5*(w-1),A=(3-w)/6,E=t=>0|Math.floor(t),M=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 S(t=Math.random){const e=function(t){const e=new Uint8Array(512);for(let t=0;t<256;t++)e[t]=t;for(let n=0;n<255;n++){const r=n+~~(t()*(256-n)),i=e[n];e[n]=e[r],e[r]=i}for(let t=256;t<512;t++)e[t]=e[t-256];return e}(t),n=new Float64Array(e).map(t=>M[t%12*2]),r=new Float64Array(e).map(t=>M[t%12*2+1]);return function(t,i){let o=0,s=0,a=0;const l=(t+i)*R,c=E(t+l),u=E(i+l),h=(c+u)*A,f=t-(c-h),x=i-(u-h);let m,d;f>x?(m=1,d=0):(m=0,d=1);const g=f-m+A,p=x-d+A,y=f-1+2*A,v=x-1+2*A,_=255&c,b=255&u;let w=.5-f*f-x*x;if(w>=0){const t=_+e[b];w*=w,o=w*w*(n[t]*f+r[t]*x)}let M=.5-g*g-p*p;if(M>=0){const t=_+m+e[b+d];M*=M,s=M*M*(n[t]*g+r[t]*p)}let S=.5-y*y-v*v;if(S>=0){const t=_+1+e[b+1];S*=S,a=S*S*(n[t]*y+r[t]*v)}return 70*(o+s+a)}}function P(t,e){let n=new k(t),r=()=>n.next();return r.double=()=>r()+11102230246251565e-32*(2097152*r()|0),r.int32=()=>4294967296*n.next()|0,r.quick=r,r}class k{constructor(t){null==t&&(t=+new Date);let e=4022871197;function n(t){t=String(t);for(let n=0;n<t.length;n++){e+=t.charCodeAt(n);let r=.02519603282416938*e;e=r>>>0,r-=e,r*=e,e=r>>>0,r-=e,e+=4294967296*r}return 2.3283064365386963e-10*(e>>>0)}this.c=1,this.s0=n(" "),this.s1=n(" "),this.s2=n(" "),this.s0-=n(t),this.s0<0&&(this.s0+=1),this.s1-=n(t),this.s1<0&&(this.s1+=1),this.s2-=n(t),this.s2<0&&(this.s2+=1)}next(){let{c:t,s0:e,s1:n,s2:r}=this,i=2091639*e+2.3283064365386963e-10*t;return this.s0=n,this.s1=r,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 T=P(Math.random()),C=P(Math.random());const I=[],L=t=>I.push(t);let F=S(P(Math.random())),D=S(P(Math.random()));const N=(t=0,e=1)=>t+T()*(e-t),B=(t=0,e=1)=>t+C()*(e-t),Y=t=>t[~~(T()*t.length)],z=(t,e)=>~~N(t,e),O=(t,e)=>~~B(t,e),U=(t=0,e=1)=>{const n=1-T(),r=T();return Math.sqrt(-2*Math.log(n))*K(360*r)*e+t},X=t=>{let e=0;const n=[];for(const r in t)e+=t[r],n.push({key:r,cumulative:e});const r=T()*e;for(const{key:t,cumulative:e}of n)if(r<e)return isNaN(t)?t:parseInt(t)},Z=(t,e,n,r,i,o=!1)=>{let s=r+(t-e)/(n-e)*(i-r);return o?r<i?G(s,r,i):G(s,i,r):s},G=(t,e,n)=>Math.max(Math.min(t,n),e),V=t=>(t%=360)<0?t+360:t,$=1440,H=2*Math.PI/$,W=new Float32Array($).fill(NaN),j=new Float32Array($).fill(NaN),K=t=>{const e=~~(4*V(t));let n=W[e];return isNaN(n)&&(n=Math.cos(e*H),W[e]=n),n},q=t=>{const e=~~(4*V(t));let n=j[e];return isNaN(n)&&(n=Math.sin(e*H),j[e]=n),n},J=(t,e=!1)=>{if(e||i&&"function"==typeof i.angleMode&&i.angleMode()===i.RADIANS){let e=180*t/Math.PI%360;return e<0?e+360:e}return t},Q=(t,e=!1)=>e||i&&"function"==typeof i.angleMode&&i.angleMode()===i.RADIANS?180*t/Math.PI:t,tt=(t,e,n,r,i)=>{let o=K(i),s=q(i);return{x:o*(n-t)+s*(r-e)+t,y:o*(r-e)-s*(n-t)+e}},et=(t,e,n,r)=>Math.hypot(n-t,r-e),nt=(t,e,n,r)=>J(Math.atan2(-(r-e),n-t),!0),rt=(t,e,n,r,i=!1)=>{let o=t.x,s=t.y,a=e.x,l=e.y,c=n.x,u=n.y,h=r.x,f=r.y;if(o===a&&s===l||c===h&&u===f)return!1;let x=a-o,m=l-s,d=h-c,g=f-u,p=g*x-d*m;if(0===p)return!1;let y=(d*(s-u)-g*(o-c))/p,v=(x*(s-u)-m*(o-c))/p;return!(!i&&(v<0||v>1))&&{x:o+y*x,y:s+y*m}},it=(t,e=0)=>t?{minX:t.minX-e,minY:t.minY-e,maxX:t.maxX+e,maxY:t.maxY+e}:null;let ot=null,st=null;const at=t=>{if(!t)return;if(u(t))return void t.draw(()=>i.clear());const e=t.drawingContext;e.save(),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,t.width,t.height),e.restore()},lt=()=>({width:Math.max(1,Math.round(e*o)),height:Math.max(1,Math.round(n*o))}),ct=t=>{if(!t)return null;const{width:e,height:n}=lt();return((t,e,n)=>{if(!t)return null;const r=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))),s=Math.min(n,Math.ceil(Math.max(t.minY,t.maxY)));return o<=r||s<=i?null:{minX:r,minY:i,maxX:o,maxY:s}})(t,e,n)},ut=()=>{const{width:t,height:e}=lt();return((t,e)=>({minX:0,minY:0,maxX:t,maxY:e}))(t,e)},ht=(t,e=!0)=>{const n=ct(t);if(!n)return null;const{height:r}=lt();return{x:n.minX,y:e?r-n.maxY:n.minY,width:n.maxX-n.minX,height:n.maxY-n.minY}},ft=(t,e,n,r=!0)=>{const i=ht(e,r);if(i){t.enable(t.SCISSOR_TEST),t.scissor(i.x,i.y,i.width,i.height);try{n()}finally{t.disable(t.SCISSOR_TEST)}}else n()},xt={},mt=()=>{i?.loaded||(y(),dt.load())},dt={isBlending:!1,cachedColor:null,markDirtyRect(t,e){const n=ct(e);var r,i;t&&n&&(t.dirtyRect=(i=n,(r=t.dirtyRect)?i?{minX:Math.min(r.minX,i.minX),minY:Math.min(r.minY,i.minY),maxX:Math.max(r.maxX,i.maxX),maxY:Math.max(r.maxY,i.maxY)}:r:i),t.isDrawn=!0)},clearMask(t){if(!t)return;const e=t===this.glMask?ot:st;e?.clearMask?.(t,at)},getCompositeRect(t,e){const n=e?ot:st;return n?.getCompositeRect?.(t,g,ut,it,ct)},load(){o=i.pixelDensity();const t=!i.blendSourceFramebuffer||i.blendSourceFramebuffer.width!==e||i.blendSourceFramebuffer.height!==n||"function"==typeof i.blendSourceFramebuffer.pixelDensity&&i.blendSourceFramebuffer.pixelDensity()!==o;i.loaded||(i.loaded=!0,i.shaderProgram??=i.createShader("#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=ot?.ensureResources?.(i,e,n,o);const r=st?.ensureResources?.(i,e,n,o,at)??{mask:null,ctx:null};t&&(i.blendSourceFramebuffer?.remove&&i.blendSourceFramebuffer.remove(),i.blendSourceFramebuffer=i.createFramebuffer({width:e,height:n,density:o,antialias:!1,depth:!1,stencil:!1})),this.mask=r.mask,this.ctx=r.ctx},blend(t=!1,e=!1){mt();const n=!0===this.isBrush,r=n?this.glMask:this.mask,i=n?this.mask:this.glMask,o=t?._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)),(e||s)&&(this.justChanged&&(this.applyShader(i,!n),this.justChanged=!1),this.isBlending&&this.applyShader(r,n),o&&(this.cachedColor=o),e&&(this.isBlending=!1,this.cachedColor=null))},applyShader(t,r){if(!t?.isDrawn)return;const o=this.getCompositeRect(t,r);if(!o)return void this.clearMask(t);const s=i.drawingContext,a=i.shaderProgram,l=g(),c=pt(l??i,o),u=!!l,h=s.getParameter(s.DEPTH_TEST);s.disable(s.DEPTH_TEST),i.push(),i.translate(0,0),i.shader(a),a.setUniform("u_source",c),a.setUniform("u_targetIsFramebuffer",u),a.setUniform("u_isBrush",r);const f=r?ot:st;a.setUniform("u_mask",f.getShaderMask(i,t,o,ct,ut,at)),a.setUniform("u_color",this.cachedColor),ft(s,o,()=>{i.fill(0,0,0,0),i.noStroke(),i.rect(-e/2,-n/2,e,n)},!u),i.pop(),i.resetShader(),h&&s.enable(s.DEPTH_TEST),this.clearMask(t)}},gt=()=>{mt(),dt.blend(!1,!0),dt.clearMask(dt.glMask),dt.clearMask(dt.mask),dt.justChanged=!1,dt.isBlending=!1,dt.isBrush=null,dt.cachedColor=null},pt=(t,r=null)=>{const o=i.blendSourceFramebuffer,s=i.drawingContext,a=u(t),{width:l,height:c}=lt(),h=r?ht(r):null,f=s.getParameter(s.READ_FRAMEBUFFER_BINDING),x=s.getParameter(s.DRAW_FRAMEBUFFER_BINDING);return(a?t.renderer:i._renderer)?.flushDraw?.(),a?(o.draw(()=>{ft(i.drawingContext,r,()=>{i.clear(),i.push(),i.imageMode(i.CENTER),i.image(t,0,0,e,n),i.pop()},!1)}),o):(s.bindFramebuffer(s.READ_FRAMEBUFFER,null),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,o.framebuffer),s.clearColor(0,0,0,0),s.clear(s.COLOR_BUFFER_BIT),s.blitFramebuffer(h?.x??0,h?.y??0,h?h.x+h.width:l,h?h.y+h.height:c,h?.x??0,h?.y??0,h?h.x+h.width:l,h?h.y+h.height:c,s.COLOR_BUFFER_BIT,s.NEAREST),s.bindFramebuffer(s.READ_FRAMEBUFFER,f),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,x),o)},yt=()=>i._renderer.uModelMatrix.mat4[12],vt=()=>i._renderer.uModelMatrix.mat4[13],_t=()=>i._renderer.uModelMatrix.mat4[0],bt=()=>i._renderer.uModelMatrix.mat4[1],wt=()=>i._renderer.uModelMatrix.mat4[4],Rt=()=>i._renderer.uModelMatrix.mat4[5];let At=!1;function Et(){At||(mt(),St=.01*e,Pt=-.5*e,kt=-.5*n,Tt=Math.round(2*e/St),Ct=Math.round(2*n/St),Bt("hand",(t,e)=>{const n=B(.2,.8),r=O(5,10);return zt(e,(e,i)=>.5*r*q(n*i*e+O(15,25))*.2*K(t)+D(e,i)*r*.7)}),Bt("curved",(t,e)=>{let n=O(-10,10);return O(0,100)%2==0&&(n*=-1),zt(e,(e,r)=>3*Z(D(.02*e+.03*t,.02*r+.03*t),0,1,-n,n))}),Bt("zigzag",(t,e)=>{let n=O(-30,-15)+Math.abs(44*q(t));O(0,100)%2==0&&(n*=-1);let r=n,i=0;for(let t=0;t<Tt;t++){for(let n=0;n<Ct;n++)e[t][n]=i,i+=r,r*=-1;i+=r,r*=-1}return e}),Bt("waves",(t,e)=>{const n=O(10,15)+5*q(t),r=O(3,6)+3*K(t),i=O(20,35);return zt(e,(t,e)=>q(n*t)*i*K(e*r)+O(-3,3))}),Bt("seabed",(t,e)=>{const n=B(.4,.8),r=O(18,26);return zt(e,(e,i)=>1.1*r*q(n*i*e+O(15,20))*K(t))}),Bt("spiral",(t,e)=>{const n=O(5,10),r=2*O(0,2)-1,i=O(65,80),o=Array.from({length:n},()=>({x:B(.1,.9)*Tt,y:B(.1,.9)*Ct}));return zt(e,(t,e)=>{let n=0,s=0;for(const a of o){const o=t-a.x,l=e-a.y,c=1/(o*o+l*l+1),u=Math.atan2(l,o)*(180/Math.PI),h=r*(u+i)*Math.PI/180;n+=c*Math.cos(h),s+=c*Math.sin(h)}return Math.atan2(s,n)*(180/Math.PI)})}),Bt("columns",(t,e)=>{const n=O(3,8),r=O(25,45);return zt(e,(t,e)=>q(t*n)*r)}),At=!0)}class Mt{constructor(t,e){Et(),this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=Mt.getColIndex(t),this.rowIdx=Mt.getRowIndex(e)}reset(){this.plotted=0}isIn(){return xt.field.isActive?Mt.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const t=e,r=n,i=this.x+yt(),o=this.y+vt();return i>=-.3*t&&i<=1.3*t&&o>=-.3*r&&o<=1.3*r}angle(t=!1){return xt.field.isActive&&(t||this.isIn())?It.get(xt.field.current).field[this.colIdx][this.rowIdx]*xt.field.wiggle:0}moveTo(t,e,n=1){this.movePos(Q(t),e,n)}_moveToDegrees(t,e,n=1){this.movePos(t,e,n)}plotTo(t,e,n,r=1){this.movePos(t,e,n,r)}movePos(t,e,n,r=!1){const i=r||1;if(!this.isIn())return void(this.plotted+=n/i);const o=e/n,s=xt.field.isActive,a=!!r;for(let e=0;e<o;e++){const e=(s?this.angle(!0):0)-(a?t.angle(this.plotted):t);this.update(this.x+n*K(e),this.y+n*q(e)),this.plotted+=n/i}}static getRowIndex(t,e=1){const n=t+vt()-kt;return Math.round(n/St/e)}static getColIndex(t,e=1){const n=t+yt()-Pt;return Math.round(n/St/e)}static isIn(t,e){return t>=0&&e>=0&&t<Tt&&e<Ct}}xt.field={isActive:!1,current:null,wiggle:1};let St,Pt,kt,Tt,Ct,It=new Map;const Lt=new Set(["degrees","radians"]);function Ft(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!Lt.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function Dt(t,e){return function(t,e){if("radians"!==e)return t;for(let e=0;e<t.length;e++)for(let n=0;n<t[e].length;n++)t[e][n]=Q(t[e][n],!0);return t}(t.gen(e,new Array(Tt).fill(null).map(()=>new Float32Array(Ct))),t.angleMode)}function Nt(t){if(xt.field.wiggle||(xt.field.wiggle=1),Et(),!It.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(It.keys()).join(", ")}.`);xt.field.isActive=!0,xt.field.current=t;const e=It.get(t);e.field||(e.field=Dt(e,0))}function Bt(t,e,n={}){It.set(t,{gen:e,field:null,angleMode:Ft(n)})}function Yt(t=1){Nt("hand"),xt.field.wiggle=t}function zt(t,e){for(let n=0;n<Tt;n++)for(let r=0;r<Ct;r++)t[n][r]=e(n,r);return t}class Ot{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,n)=>[t,n[(e+1)%n.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 n=[];for(const[e,r]of this.sides){const i=rt(t.point1,t.point2,e,r);i&&n.push(i)}return this._intersectionCache[e]=n,n}show(){xt.wash&&this.wash(),xt.fill&&this.fill(),xt.mass&&this.mass(),xt.hatch&&this.hatch(),xt.stroke&&this.draw()}}class Ut{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,n=1,r=!1){this.angles.length>0&&this.angles.pop(),t=r?(t%360+360)%360:J(t),this.angles.push(t,t),this.pres.push(n),this.segments.push(e),this.length=this.segments.reduce((t,e)=>t+e,0)}endPlot(t=0,e=1,n=!1){t=n?(t%360+360)%360:J(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=J(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 n=t[this.index],r=t[this.index+1]??n;return Math.abs(r-n)>180&&(r>n?r=-(360-r):n=-(360-n)),Z(e-this.suma,0,this.segments[this.index],n,r,!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,r,i=1,o){Et();const s=o<0?4:1,a=[],l=Math.round(this.length/s),c=new Mt(t+e/2,r+n/2);let u=0,h=0;for(let t=0;t<l;t++){c.plotTo(this,s,s);const t=this.calcIndex(c.plotted);u+=s,(u>=(o<=0?8:Math.max(this.segments[t]*o*B(.7,1.3),20))||t>=h)&&c.x&&(a.push([c.x-e/2,c.y-n/2]),u=0,t>=h&&h++)}return new Ot(a)}show(t,e,n=1){xt.wash&&this.wash(t,e,n),xt.fill&&this.fill(t,e,n),xt.mass&&this.mass(t,e,n),xt.hatch&&this.hatch(t,e,n),xt.stroke&&this.draw(t,e,n)}}function Xt(t,e,n,r,i){const o=Q(r),s=((Q(i)-o)%360+360)%360;if(0===s)return;const a=new Ut("curve"),l=Math.max(1,Math.ceil(s/90)),c=s/l,u=Math.PI*n*c/180;for(let t=0;t<l;t++)a.addSegment(o+t*c+90,u,1,!0);a.endPlot(o+s+90,1,!0);const h=t+n*K(o),f=e-n*q(o);a.draw(h,f,1)}let Zt,Gt,Vt,$t;class Ht{constructor(){this.isClosed=!1,this.curvature=Gt,this.vert=[]}vertex(t,e,n){this.vert.push([t,e,n])}show(){qt(this.vert,this.curvature,this.isClosed).show()}}function Wt(t=0){Gt=G(t,0,1),Zt=new Ht}function jt(t,e,n=1){if(!Zt)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");Zt.vertex(t,e,n)}function Kt(t=!1){if(!Zt)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(Zt.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(Zt.vertex(...Zt.vert[0]),Zt.isClosed=!0),Zt.show(),Zt=!1}function qt(t,e=.5,n=!1){const r=new Ut(0===e?"segments":"curve"),i=2*Math.PI;if(n&&0!==e&&t.push(t[1]),t&&t.length>0){let o,s,a,l=0;for(let c=0;c<t.length-1;c++)if(e>0&&c<t.length-2){const u=t[c],h=t[c+1],f=t[c+2],x=et(u[0],u[1],h[0],h[1]),m=et(h[0],h[1],f[0],f[1]),d=nt(u[0],u[1],h[0],h[1]),g=nt(h[0],h[1],f[0],f[1]),p=e*Math.min(x,m,.5*Math.min(x,m)),y=Math.max(x,m),v=x-p,_=m-p;if(Math.floor(d)===Math.floor(g)){const e=n&&0===c?0:x-l,i=n?0===c?0:m-a:m;r.addSegment(d,e,u[2],!0),c===t.length-3&&r.addSegment(g,i,h[2],!0),l=0,0===c&&(o=x,a=p,s=t[1],l=0)}else{const e={x:h[0]-p*K(-d),y:h[1]-p*q(-d)},f={x:e.x+y*K(90-d),y:e.y+y*q(90-d)},x={x:h[0]+p*K(-g),y:h[1]+p*q(-g)},m={x:x.x+y*K(90-g),y:x.y+y*q(90-g)},b=rt(e,f,x,m,!0),w=et(e.x,e.y,b.x,b.y),R=et(e.x,e.y,x.x,x.y)/2,A=i*w*(2*Math.asin(R/w)*(180/Math.PI))/360,E=n&&0===c?0:v-l,M=c===t.length-3?n?o-p:_:0;r.addSegment(d,E,u[2],!0),r.addSegment(d,isNaN(A)?0:A,u[2],!0),r.addSegment(g,M,h[2],!0),l=p,0===c&&(o=v,a=p,s=[e.x,e.y])}c===t.length-3&&r.endPlot(g,h[2],!0)}else if(0===e){const e=t[c],n=t[c+1],i=et(e[0],e[1],n[0],n[1]),o=nt(e[0],e[1],n[0],n[1]);r.addSegment(o,i,n[2],!0),c===t.length-2&&r.endPlot(o,1,!0)}r.origin=n&&0!==e?s:t[0]}return r}let Jt=!1;const Qt=(t,e,n)=>{const r=t.createProgram();for(let[i,o]of[[t.VERTEX_SHADER,e],[t.FRAGMENT_SHADER,n]]){const e=t.createShader(i);t.shaderSource(e,o),t.compileShader(e),t.attachShader(r,e)}return t.linkProgram(r),r};let te,ee,ne,re,ie,oe=!1,se=0,ae=0,le=null,ce=null;const ue={},he={};let fe=1,xe=0,me=0,de=1,ge=0,pe=0,ye=0,ve=0,_e=1,be=1,we=new Float32Array(8192),Re=0,Ae=2048,Ee=32768,Me=null,Se=null,Pe=null,ke=null,Te=null;const Ce={},Ie={};let Le=0,Fe=new Float32Array(1280),De=0,Ne=256,Be=null;const Ye=new Map,ze=new Float32Array([-1,-1,1,-1,-1,1,1,1]);function Oe(){const t=dt.glMask?.renderer;t&&(t._curShader=null,t._cachedBlendMode=null,t._isBlending=null,te.activeTexture(te.TEXTURE0),te.bindTexture(te.TEXTURE_2D,null),te.blendEquation(te.FUNC_ADD),te.blendFunc(te.ONE,te.ONE_MINUS_SRC_ALPHA))}function Ue(){return ee}function Xe(){const t=te.isEnabled(te.DEPTH_TEST);var e;Xe._hadDepthTest=t,t&&te.disable(te.DEPTH_TEST),ce=i._renderer.activeFramebuffer?.()??null,ce?._beforeEnd&&ce._beforeEnd(),te.bindFramebuffer(te.FRAMEBUFFER,(e=dt.glMask)?"function"==typeof e._framebufferToBind?e._framebufferToBind():e.framebuffer??null:null),te.viewport(0,0,dt.glMask.width*dt.glMask.density,dt.glMask.height*dt.glMask.density)}function Ze(){Xe._hadDepthTest&&te.enable(te.DEPTH_TEST),Xe._hadDepthTest=!1,ce?._beforeBegin?ce._beforeBegin():(te.bindFramebuffer(te.FRAMEBUFFER,null),i._renderer.viewport(i._renderer._origViewport.width,i._renderer._origViewport.height),i._renderer._applyStencilTestIfClipping?.()),ce=null}function Ge(t,e,n,r,i){return t?(e<t.minX&&(t.minX=e),n<t.minY&&(t.minY=n),r>t.maxX&&(t.maxX=r),i>t.maxY&&(t.maxY=i),t):{minX:e,minY:n,maxX:r,maxY:i}}function Ve(t,e,n,r){if(Re>=Ae){Ae*=2;const t=new Float32Array(4*Ae);t.set(we),we=t}const i=t-ye,o=e-ve,s=4*Re,a=fe*i+me*o+ge+ye,l=xe*i+de*o+pe+ve,c=be*n*_e/2;we[s]=a,we[s+1]=l,we[s+2]=c,we[s+3]=r/255;const u=a*be,h=l*be;Me=Ge(Me,u-c-1,h-c-1,u+c+1,h+c+1),Re++}function $e(t,e){if(0===De)return;dt.glMask.isDrawn=!0,Xe();let n=Ye.get(e);n||(n=te.createTexture(),te.bindTexture(te.TEXTURE_2D,n),te.texImage2D(te.TEXTURE_2D,0,te.RGBA,te.RGBA,te.UNSIGNED_BYTE,t.canvas),te.texParameteri(te.TEXTURE_2D,te.TEXTURE_MIN_FILTER,te.LINEAR),te.texParameteri(te.TEXTURE_2D,te.TEXTURE_MAG_FILTER,te.LINEAR),te.texParameteri(te.TEXTURE_2D,te.TEXTURE_WRAP_S,te.CLAMP_TO_EDGE),te.texParameteri(te.TEXTURE_2D,te.TEXTURE_WRAP_T,te.CLAMP_TO_EDGE),Ye.set(e,n)),te.useProgram(Se),te.enable(te.BLEND),te.blendFunc(te.ONE_MINUS_DST_ALPHA,te.ONE),te.activeTexture(te.TEXTURE0),te.bindTexture(te.TEXTURE_2D,n),te.uniform1i(Ie.u_tex,0);const r=xt.stroke.color._array;te.uniform4f(Ie.u_color,...r),te.uniformMatrix4fv(Ie.u_proj,!1,Ue()),te.bindVertexArray(Pe),te.bindBuffer(te.ARRAY_BUFFER,Te);const i=5*De*4,o=Fe.subarray(0,5*De);i>Le?(te.bufferData(te.ARRAY_BUFFER,Fe,te.DYNAMIC_DRAW),Le=Fe.byteLength):te.bufferSubData(te.ARRAY_BUFFER,0,o),te.drawArraysInstanced(te.TRIANGLE_STRIP,0,4,De),te.flush(),te.bindVertexArray(null),te.bindTexture(te.TEXTURE_2D,null),Ze(),Be&&(dt.markDirtyRect(dt.glMask,Be),Be=null),De=0,Oe()}Jt||(ot={ensureResources:function(t,e,n,r){return function(t,e,n,r){return!t.glMask||t.glMask.width!==e||t.glMask.height!==n||"function"==typeof t.glMask.pixelDensity&&t.glMask.pixelDensity()!==r}(t,e,n,r)&&(t.glMask?.remove&&t.glMask.remove(),t.glMask=t.createFramebuffer({width:e,height:n,density:r,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,n,r,i){return t?t.dirtyRect?e()?n():i(r(t.dirtyRect,2)):n():null},getShaderMask:function(t,e){return e}},Jt=!0),xt.stroke={color:null,weight:1,type:"HB",isActive:!1,opacity:1};let He=new Map;function We(){return i??r??window.self.p5.instance}const je={offset:.08,scale:.08,warp:.06,tilt:.06};function Ke(){return{...xt.stroke}}function qe(t){xt.stroke={...t}}function Je(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:{...je}};if("object"==typeof t&&!Array.isArray(t)){if("custom"===t.type||"custom"===t.mode){const{mode:e,...n}=t;return{...n,type:"custom",variation:{...je,...n.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,n,r]=2===t.length?[t[0],(t[0]+t[1])/2,t[1]]:t,i=Math.min(e,n,r),o=Math.max(e,n,r),s=o-i||1,[a,l,c]=[(e-i)/s,(n-i)/s,(r-i)/s];return{type:"custom",min_max:[i,o],variation:{...je},curve:t=>t<.5?a+(l-a)*t*2:l+(c-l)*(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 n=`custom::${t}`;!function(t){const e=Ye.get(t);e&&te&&te.deleteTexture(e),Ye.delete(t)}(n);const r=We().createGraphics(500,500);return r.pixelDensity(1),r.background(255),r.noSmooth(),r.push(),r.translate(250,250),r.scale(5),r.noStroke(),e.tip(r),r.pop(),wn.imageToWhite(r),wn.tips.set(n,r),e.tipKey=n,void He.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 wn.add(e.image.src),He.set(t,{param:e,colors:[],buffers:[]}),wn.load()}He.set(t,{param:e,colors:[],buffers:[]})}function Qe(t){return He.get(t)?.param??null}function tn(t){if(!He.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...He.keys()].join(", ")}.`);xt.stroke.type=t}function en(t,e,n){y(),xt.stroke.color=i.color(...arguments),xt.stroke.isActive=!0}function nn(t){xt.stroke.weight=t}function rn(t,e,n=1){tn(t),en(e),nn(n)}let on,sn,an,ln;const cn={};function un(t,r,i,s=!1){fe=_t(),xe=bt(),me=wt(),de=Rt(),ge=yt(),pe=vt(),ye=e/2,ve=n/2,_e=Math.sqrt(fe*fe+xe*xe),be=o,on=new Mt(t+e/2,r+n/2),sn=i,an=s,an&&an.calcIndex(0)}const hn=[];function fn(t,r){r||(ln=t),function(){cn.seed=999999*N();const{param:t}=He.get(xt.stroke.type)??{};if(!t)return;cn.p=t;const{pressure:r}=t;if(cn.a="custom"!==r.type?N(-1,1):0,cn.b="custom"!==r.type?N(1,1.5):0,"custom"!==r.type)cn.cp=N(3,3.5),cn.ct=0,cn.cs=1,cn.ck=0;else{const t=r.variation??je;cn.cp=N(-t.offset,t.offset),cn.ct=N(-t.warp,t.warp),cn.cs=N(1-t.scale,1+t.scale),cn.ck=N(-t.tilt,t.tilt)}[cn.min,cn.max]=r.min_max,cn.noiseoffset=.05*cn.p.noise,an||(cn.cos=K(ln),cn.sin=q(ln)),function(){mt(),function(){const t=i?.glMask;t&&(le=t,le.dirtyRect??=null,le.isDrawn??=!1,dt.glMask=le)}();const t=i.drawingContext,r=!oe||te!==t;(r||se!==e||ae!==n)&&(ee=new Float32Array([2/e,0,0,0,0,2/n,0,0,0,0,1,0,-1,-1,0,1]),se=e,ae=n),r&&(te=t,ie=Qt(te,"#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);}"),te.useProgram(ie),te.enable(te.BLEND),te.blendFunc(te.ONE_MINUS_DST_ALPHA,te.ONE),["a_position","a_radius","a_alpha"].forEach(t=>ue[t]=te.getAttribLocation(ie,t)),["u_matrix","u_color"].forEach(t=>he[t]=te.getUniformLocation(ie,t)),ne=te.createVertexArray(),te.bindVertexArray(ne),re=te.createBuffer(),te.bindBuffer(te.ARRAY_BUFFER,re),te.bufferData(te.ARRAY_BUFFER,we.byteLength,te.DYNAMIC_DRAW),Ee=we.byteLength,te.enableVertexAttribArray(ue.a_position),te.vertexAttribPointer(ue.a_position,2,te.FLOAT,!1,16,0),te.enableVertexAttribArray(ue.a_radius),te.vertexAttribPointer(ue.a_radius,1,te.FLOAT,!1,16,8),te.enableVertexAttribArray(ue.a_alpha),te.vertexAttribPointer(ue.a_alpha,1,te.FLOAT,!1,16,12),te.bindVertexArray(null),Ye.clear(),Se=Qt(te,"#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=>Ce[t]=te.getAttribLocation(Se,t)),["u_proj","u_color","u_tex"].forEach(t=>Ie[t]=te.getUniformLocation(Se,t)),Pe=te.createVertexArray(),te.bindVertexArray(Pe),ke=te.createBuffer(),te.bindBuffer(te.ARRAY_BUFFER,ke),te.bufferData(te.ARRAY_BUFFER,ze,te.STATIC_DRAW),te.enableVertexAttribArray(Ce.a_corner),te.vertexAttribPointer(Ce.a_corner,2,te.FLOAT,!1,0,0),Te=te.createBuffer(),te.bindBuffer(te.ARRAY_BUFFER,Te),te.bufferData(te.ARRAY_BUFFER,Fe.byteLength,te.DYNAMIC_DRAW),Le=Fe.byteLength,te.enableVertexAttribArray(Ce.a_pos),te.vertexAttribPointer(Ce.a_pos,2,te.FLOAT,!1,20,0),te.vertexAttribDivisor(Ce.a_pos,1),te.enableVertexAttribArray(Ce.a_size),te.vertexAttribPointer(Ce.a_size,1,te.FLOAT,!1,20,8),te.vertexAttribDivisor(Ce.a_size,1),te.enableVertexAttribArray(Ce.a_angle),te.vertexAttribPointer(Ce.a_angle,1,te.FLOAT,!1,20,12),te.vertexAttribDivisor(Ce.a_angle,1),te.enableVertexAttribArray(Ce.a_alpha),te.vertexAttribPointer(Ce.a_alpha,1,te.FLOAT,!1,20,16),te.vertexAttribDivisor(Ce.a_alpha,1),te.bindVertexArray(null),oe=!0)}();const o=!0!==dt.isBrush;dt.isBrush=!0,o&&(dt.justChanged=!0),dt.blend(xt.stroke.color),cn.alpha=["default","spray"].includes(cn.p.type)?cn.p.opacity:cn.p.opacity/Math.min(xt.stroke.weight,1.3),yn()}();const o=function(){const{param:t}=He.get(xt.stroke.type)??{};return t?t.spacing:1}(),s=Math.round(sn*(r?t:1)/o);cn.pressureCount=10,cn.cachedPressure=void 0,cn.lineNoiseCount=5,cn.cachedLineNoise=void 0;for(let e=0;e<s;e++)hn.length<2*s&&hn.push(U()),xn(),r?on.plotTo(an,o,o,t,e<10):on._moveToDegrees(t,o,o);!function(){yn(),function(){if(0===Re)return;dt.glMask.isDrawn=!0,Xe();const t=xt.stroke.color._array;te.useProgram(ie),te.enable(te.BLEND),te.blendFunc(te.ONE_MINUS_DST_ALPHA,te.ONE),te.bindVertexArray(ne),te.bindBuffer(te.ARRAY_BUFFER,re);const e=16*Re,n=we.subarray(0,4*Re);e>Ee?(te.bufferData(te.ARRAY_BUFFER,we,te.DYNAMIC_DRAW),Ee=we.byteLength):te.bufferSubData(te.ARRAY_BUFFER,0,n),te.uniform4f(he.u_color,...t),te.uniformMatrix4fv(he.u_matrix,!1,Ue()),te.drawArrays(te.POINTS,0,Re),te.flush(),te.bindVertexArray(null),Ze(),Me&&(dt.markDirtyRect(dt.glMask,Me),Me=null),Re=0,Oe()}();const t=cn.p?.type;"image"===t?$e(wn.tips.get(cn.p.image.src),cn.p.image.src):"custom"===t&&$e(wn.tips.get(cn.p.tipKey),cn.p.tipKey)}()}function xn(){const t=mn(),e=((cn.lineNoiseCount>=10||void 0===cn.cachedLineNoise)&&(cn.cachedLineNoise=Z(F(cn.seed+.01*on.plotted,0),-1,1,1-cn.noiseoffset,1+cn.noiseoffset),cn.lineNoiseCount=0),cn.lineNoiseCount++,cn.cachedLineNoise);if(!(e>N(1,1.02)&&N(0,1)<.7))switch(cn.p.type){case"spray":!function(t){const e=xt.stroke.weight*cn.p.scatter*t+xt.stroke.weight*Y(hn)*cn.p.scatter/3,n=cn.p.weight*N(.9,1.1),r=Math.ceil(cn.p.grain/t);for(let t=0;t<r;t++){const t=N(.9,1.1),r=t*e*N(-1,1),i=N(-1,1),o=Math.sqrt((t*e)**2-r**2);Ve(on.x+r,on.y+i*o,n,cn.alpha)}}(t*e);break;case"marker":gn(t*e);break;case"custom":case"image":pn(t*e);break;default:!function(t,e=1){const n=(e=Z(e,0,1,.9,1.05))*xt.stroke.weight*cn.p.scatter*(cn.p.sharpness+(1-cn.p.sharpness)*Y(hn)/t);if(N(0,cn.p.grain*t)>.4){let e,r;if(an){const t=an.angle(on.plotted),i=K(t),o=q(t),s=n*N(-1,1),a=.3*n*N(-1,1);e=s*o+a*i,r=s*i-a*o}else{const t=n*N(-1,1),i=.3*n*N(-1,1);e=t*cn.sin+i*cn.cos,r=t*cn.cos-i*cn.sin}const i=t*t*cn.p.weight*N(.85,1.15)*xt.stroke.weight,o=Math.max(.9,t)*cn.alpha*N(.75,1.1);Ve(on.x+e,on.y+r,i,o)}}(t*e)}}function mn(){return(cn.pressureCount>=10||void 0===cn.cachedPressure)&&(cn.cachedPressure=an?dn()*an.pressure(on.plotted):dn(),cn.pressureCount=0),cn.pressureCount++,cn.cachedPressure}function dn(){return"custom"===cn.p.pressure.type?Z(cn.p.pressure.curve(Math.max(0,Math.min(1,.5+(on.plotted/sn-.5+cn.ct)*cn.cs)))+cn.cp+cn.ck*(on.plotted/sn-.5),0,1,cn.min,cn.max,!0):function(t=.5+cn.p.pressure.curve[0]*cn.a,e=1-cn.p.pressure.curve[1]*cn.b,n=cn.cp,r=cn.min,i=cn.max){const o=t*sn,s=(on.plotted<o?1.2*e:.8*e)*(sn/2);return Z(1/(1+Math.pow(Math.abs((on.plotted-o)/s),2*n)),0,1,r,i)}()}function gn(t,e=!0,n=cn.alpha){const r=e?xt.stroke.weight*cn.p.scatter:0,i=e?r*N(-1,1):0,o=e?r*N(-1,1):0;Ve(on.x+i,on.y+o,xt.stroke.weight*cn.p.weight*t,n*Math.max(.8,t)*N(.9,1.1))}function pn(t,e=cn.alpha){const n=xt.stroke.weight*cn.p.scatter,r=n*N(-1,1),i=n*N(-1,1),o=cn.p.weight*xt.stroke.weight*t,s=function(){const t=Math.max(1,cn.max??1),e=xt.stroke.weight*cn.p.scatter,n=xt.stroke.weight*cn.p.weight*t;return Math.max(8,1.5*e+.75*n)}();let a=0;"random"===cn.p.rotate?a=z(0,360)*(Math.PI/180):"natural"===cn.p.rotate&&(a=((an?-an.angle(on.plotted):-ln)+on.angle())*(Math.PI/180)),function(t,e,n,r,i,o=0){if(De>=Ne){Ne*=2;const t=new Float32Array(5*Ne);t.set(Fe),Fe=t}const s=t-ye,a=e-ve,l=fe*s+me*a+ge+ye,c=xe*s+de*a+pe+ve,u=be*n*_e/2,h=be*o*_e,f=5*De;Fe[f]=l,Fe[f+1]=c,Fe[f+2]=u,Fe[f+3]=r,Fe[f+4]=i/255;const x=l*be,m=c*be,d=1.42*u+h;Be=Ge(Be,x-d-1,m-d-1,x+d+1,m+d+1),De++}(on.x+r,on.y+i,o,a,e*Math.max(.8,t)*N(.9,1.1),s)}function yn(){if(!1===cn.p.markerTip)return;let t=mn(),e=cn.alpha;if("marker"===cn.p.type)for(let n=1;n<10;n++)gn(t*n/10,!0,8*e);else if("custom"===cn.p.type||"image"===cn.p.type)for(let n=1;n<5;n++)pn(t*n/10,2*e)}function vn(t,e,n,r){if(!xt.stroke.isActive||!xt.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");Et();let i=et(t,e,n,r);0!=i&&(un(t,e,i),fn(nt(t,e,n,r),!1))}L(()=>{hn.length=0});const _n=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate","markerTip","noise"],bn=[["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 bn){let e={};for(let n=0;n<t[1].length;n++)e[_n[n]]=t[1][n];Je(t[0],e)}Ot.prototype.draw=function(t=!1,e,n){let r=Ke();if(t&&rn(t,e,n),r.isActive)for(let t of this.sides)vn(t[0].x,t[0].y,t[1].x,t[1].y);qe(r)},Ut.prototype.draw=function(t,e,n){Ke().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],n=1),function(t,e,n,r){Et(),un(e,n,t.length,t),fn(r,!0)}(this,t,e,n))};const wn={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 n=(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-n}t.updatePixels()},async load(){const t=[...this.tips.keys()].filter(t=>!this.tips.get(t));await Promise.all(t.map(t=>new Promise((e,n)=>{const r=new window.Image;r.onload=()=>{const n=We().createImage(r.naturalWidth,r.naturalHeight);n.drawingContext.drawImage(r,0,0),wn.imageToWhite(n),this.tips.set(t,n),e()},r.onerror=()=>n(new Error(`Failed to load image tip: ${t}`)),r.crossOrigin="anonymous",r.src=t})))}};function Rn(){return{...xt.hatch}}function An(t){xt.hatch={...t}}function En(t=5,e=45,n={rand:!1,continuous:!1,gradient:!1}){let r=xt.hatch;r.isActive=!0,r.dist=t,r.angle=Q(e),r.options=n}function Mn(t,e,n,r){const i=e*Math.PI/180,o=Math.cos(i),s=Math.sin(i),a=Math.cos(-i),l=Math.sin(-i),c=t.a,u=c.length,h=new Array(u);let f=Infinity,x=-Infinity;for(let t=0;t<u;t++){const e=c[t][0],n=c[t][1],r=[e*o-n*s,e*s+n*o];h[t]=r,r[1]<f&&(f=r[1]),r[1]>x&&(x=r[1])}const m=[];for(let t=0;t<u;t++){const e=h[t],n=h[(t+1)%u];e[1]!==n[1]&&m.push(e,n)}const d=m.length,g=[];let p=f+.5*n,y=n;for(;p<x;){const t=[];for(let e=0;e<d;e+=2){const n=m[e][1],r=m[e+1][1];(n<=p&&p<r||r<=p&&p<n)&&t.push(m[e][0]+(p-n)/(r-n)*(m[e+1][0]-m[e][0]))}t.sort((t,e)=>t-e);for(let e=0;e<t.length-1;e+=2)g.push({scanY:p,x1:t[e]*a-p*l,y1:t[e]*l+p*a,x2:t[e+1]*a-p*l,y2:t[e+1]*l+p*a});p+=y,y*=r}return g}function Sn(t){const{dist:e,options:n,segs:r}=function(t){const e=xt.hatch.dist,n=(xt.hatch.angle%180+180)%180,r=xt.hatch.options,i=function(t,e,n,r){Array.isArray(t)||(t=[t]);const i=[];for(const o of t)for(const t of Mn(o,n,e,r))i.push(t);return i.sort((t,e)=>t.scanY===e.scanY?t.x1-e.x1:t.scanY-e.scanY),i}(t,e,n,r.gradient?Z(r.gradient,0,1,1,1.1,!0):1);return{dist:e,options:r,segs:i}}(t),i=n.rand||0,o=[];for(let t=0;t<r.length;t++){const s=r[t];let a=s.x1,l=s.y1,c=s.x2,u=s.y2;i&&(a+=2*i*e*N(-1,1),l+=2*i*e*N(-1,1),c+=2*i*e*N(-1,1),u+=2*i*e*N(-1,1));const h=n.continuous&&t%2==1?{x1:c,y1:u,x2:a,y2:l,scanY:s.scanY,isConnector:!1}:{x1:a,y1:l,x2:c,y2:u,scanY:s.scanY,isConnector:!1};if(o.push(h),t>0&&n.continuous){const t=o[o.length-2];o.push({x1:t.x2,y1:t.y2,x2:h.x1,y2:h.y1,scanY:s.scanY,isConnector:!0})}}return o}function Pn(t){!function(t,e){const n=Sn(t);!function(){const t=Ke();xt.hatch.hBrush&&rn(...Object.values(xt.hatch.hBrush)),(()=>{for(let t=0;t<n.length;t++){const r=n[t];e(r.x1,r.y1,r.x2,r.y2,t,n)}})(),qe(t)}()}(t,(t,e,n,r)=>{vn(t,e,n,r)})}function kn(t,e,n){return new Ot(t.vertices.map(t=>[t.x+e,t.y+n]))}function Tn(t){return i&&"function"==typeof i.angleMode&&i.angleMode()===i.RADIANS?t*Math.PI/180:t}function Cn(t,e,n,r,i){const o=(e+r)/2,s=(n+i)/2,a=r-e,l=i-n,c=Math.hypot(a,l);if(!c)return null;const u=-l/c,h=a/c,f=(t.x-o)*u+(t.y-s)*h;return{x:o+u*f,y:s+h*f}}function In(t,e,n,r,i,o){let s=nt(t,e,n,r),a=nt(t,e,i,o);return((a-s)%360+360)%360>180&&([s,a]=[a,s]),[Tn(s),Tn(a)]}function Ln(t){const e=B(.35,.65),n=t.x1+(t.x2-t.x1)*e,r=t.y1+(t.y2-t.y1)*e,i=t.x2-t.x1,o=t.y2-t.y1,s=Math.hypot(i,o)||1,a=B(.04,.1)*s,l=i/s*a*.5,c=o/s*a*.5;return[{x1:t.x1,y1:t.y1,x2:n-l,y2:r-c},{x1:n+l,y1:r+c,x2:t.x2,y2:t.y2}]}function Fn(t,e){const n=function(t,e){const n=function(t){const e=t?.a??[];let n=Infinity,r=Infinity,i=-Infinity,o=-Infinity;for(const[t,s]of e)t<n&&(n=t),s<r&&(r=s),t>i&&(i=t),s>o&&(o=s);return{minX:n,minY:r,maxX:i,maxY:o,cx:(n+i)/2,cy:(r+o)/2,size:Math.hypot(i-n,o-r)}}(t),r=n.size*B(.6,1.4),[i,o]=e;return{x:n.cx+i*r,y:n.cy+o*r}}(t,e);for(const e of Sn(t)){const t=!e.isConnector&&B()<.35?Ln(e):[e];for(const e of t){const t=Cn(n,e.x1,e.y1,e.x2,e.y2);if(!t)continue;const r=et(t.x,t.y,e.x1,e.y1);if(!r)continue;const[i,o]=In(t.x,t.y,e.x1,e.y1,e.x2,e.y2);Xt(t.x,t.y,r,i,o)}}}function Dn(t,e,n,r,i){En(e,n,r),Fn(t,i)}function Nn(t,e,n,r){const i=function(t,e,n,r){const i=!1===e,o=Qe(xt.mass.brush)?.scatter??0,s=i?t:t.genPol(e,n,r,.15),a=Math.min(2*o,5),l=[[B(-a,a),B(-a,a)],[B(-a,a),B(-a,a)]];return[s,kn(s,l[0][0],l[0][1]),kn(s,l[1][0],l[1][1])]}(t,e,n,r),o=Rn(),s=Ke(),a={...xt.field},l=xt.mass.options?.precision??.5,c=xt.mass.options?.strength??1,u=xt.mass.options?.gradient??.1,h=xt.mass.options?.outline??!1,f=Qe(xt.mass.brush)?.scatter??0,x=1.6*B(.65*f,.85*f)-.4*u,m=B(-90,90),d=((m+90)%180+180)%180-90>=0?B()<.5?[1,1]:[-1,-1]:B()<.5?[-1,1]:[1,-1];rn(xt.mass.brush,xt.mass.color,1),Yt(2-l),h&&i[0].draw(),Dn(i[0],.9*x,Tn(m),{gradient:u,rand:2-2*l,continuous:!0},d),c>.33&&Dn(i[1],x,Tn(m+20*B(-1,1)),{gradient:u,rand:.6-.6*l,continuous:!0},d),c>.66&&Dn(i[2],.8*x,Tn(m+15*B(-1,1)),{gradient:u,rand:.6-.6*l,continuous:!0},d),qe(s),An(o),xt.field={...a}}function Bn(t,e,n){const r=2*Math.PI,i=dt.ctx,o=n/2;i.moveTo(t+o,e),i.arc(t,e,o,0,r)}xt.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},Ot.prototype.hatch=function(t=!1,e,n){let r=Rn();t&&En(t,e,n),xt.hatch.isActive&&Pn(this),An(r)},Ut.prototype.hatch=function(t,e,n){Rn().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],n=1),this.pol=this.genPol(t,e,n,.3),this.pol.hatch())},xt.mass={isActive:!1,brush:null,color:null,options:{}},Ot.prototype.mass=function(){xt.mass?.isActive&&Nn(this,!1)},Ut.prototype.mass=function(t,e,n){xt.mass?.isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],n=1),Nn(this,t,e,n))};let Yn=null,zn=!1;zn||(st={ensureResources:function(t,e,n,r,i){const o=Math.max(1,Math.round(e*r)),s=Math.max(1,Math.round(n*r));return function(t,e,n){return!t.mask||t.mask.width!==e||t.mask.height!==n}(t,o,s)&&(t.mask=new OffscreenCanvas(o,s),t.mask.drawingContext=t.mask.getContext("2d")),function(t,e,n,r){return!t.fillMaskFramebuffer||t.fillMaskFramebuffer.width!==e||t.fillMaskFramebuffer.height!==n||"function"==typeof t.fillMaskFramebuffer.pixelDensity&&t.fillMaskFramebuffer.pixelDensity()!==r}(t,e,n,r)&&(t.fillMaskFramebuffer?.remove&&t.fillMaskFramebuffer.remove(),t.fillMaskFramebuffer=t.createFramebuffer({width:e,height:n,density:r,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,n,r,i){return t?t.dirtyRect?i(r(t.dirtyRect,4)):n():null},getShaderMask:function(t,e,n,r,i,o){const s=t.fillMaskFramebuffer,a=t.drawingContext,l=r(n)??i(),c=l.maxX-l.minX,u=l.maxY-l.minY;Yn&&Yn.width===c&&Yn.height===u||(Yn=new OffscreenCanvas(c,u),Yn.drawingContext=Yn.getContext("2d"));const h=Yn.drawingContext;return h.clearRect(0,0,c,u),h.drawImage(e,l.minX,l.minY,c,u,0,0,c,u),o(s),a.bindTexture(a.TEXTURE_2D,s.colorTexture),a.texSubImage2D(a.TEXTURE_2D,0,l.minX,l.minY,a.RGBA,a.UNSIGNED_BYTE,Yn),s}},zn=!0),xt.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const On=()=>({...xt.fill});function Un(t,e,n,r){xt.fill.opacity=(arguments.length<4?e:r)||150,xt.fill.color=arguments.length<3?i.color(t):i.color(t,e,n),xt.fill.isActive=!0}function Xn(t,e="out"){xt.fill.bleed_strength=G(t,0,1),xt.fill.direction=e}function Zn(t=.4,e=.4){xt.fill.texture_strength=G(t,0,1),xt.fill.border_strength=G(e,0,1)}let Gn;const Vn=[[],[]];function $n(){for(let t=0;t<512;t++)Vn[0][t]=U(.5,.2),Vn[1][t]=U(0,.02)}function Hn(t,e,n){return(e.x-t.x)*(n.y-t.y)-(e.y-t.y)*(n.x-t.x)>.01}L($n);class Wn{constructor(t,e,n,r=[],i=!1,o,s){if(this.v=t,this.m=e,this.dir=r,this.midP=n,i){let e=0,r=0;const i=[];for(let o=0;o<t.length;o++){const s=Math.abs(n.x-t[o].x),a=Math.abs(n.y-t[o].y);e=Math.max(e,s),r=Math.max(r,a);const l=t[o],c=t[(o+1)%t.length],u={x:c.x-l.x,y:c.y-l.y},h=tt(0,0,u.x,u.y,90),f={x:l.x+u.x/2,y:l.y+u.y/2};i.push({v1:l,v2:c,ray:{point1:f,point2:{x:f.x+h.x,y:f.y+h.y}}})}this.sizeX=e,this.sizeY=r,this.dir=Array(t.length),i.forEach((t,e)=>{let n=0;for(const e of Gn.intersect(t.ray))Hn(t.v1,t.v2,e)&&n++;this.dir[e]=n%2==0});const o=N(-.6,.6)*e,s=N(-.6,.6)*r;this.midP={x:n.x+o,y:n.y+s}}else this.sizeX=o,this.sizeY=s}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),n=~~(this.v.length/2-e/2),r=this.v.length-e,i=new Array(r),o=new Array(r),s=new Array(r);let a=0;for(let t=0;t<n;t++,a++)i[a]=this.v[t],o[a]=this.m[t],s[a]=this.dir[t];for(let t=n+e;t<this.v.length;t++,a++)i[a]=this.v[t],o[a]=this.m[t],s[a]=this.dir[t];const l=n,c=n+e,u=this.v[(l-1+this.v.length)%this.v.length],h=this.v[c%this.v.length],f=h.x-u.x,x=h.y-u.y;for(let t=0;t<2;t++){const e=N(.25,.75),r={x:u.x+f*e,y:u.y+x*e},a=n+t;i.splice(a,0,r),o.splice(a,0,N(.4,.7)),s.splice(a,0,this.dir[l%this.dir.length])}return{v:i,m:o,dir:s}}scatter(t=.3){const e=this.v.length,n=Math.max(3,~~(e*t)),r=[],i=e/n;for(let t=0;t<n;t++)r.push(~~(t*i+N(0,.8*i)));const o=[],s=[],a=[],l=this.midP,c=Gn.sides;for(const t of r){const n=t%e;let r=this.v[n],i=0;for(const[t,e]of c){const n=t.y,o=e.y;if(n>r.y==o>r.y)continue;const s=(r.y-n)/(o-n);r.x<t.x+s*(e.x-t.x)&&i++}i%2==0&&(r={x:l.x+(r.x-l.x)*N(.3,.6),y:l.y+(r.y-l.y)*N(.3,.6)}),o.push(r),s.push(this.m[n]),a.push(!this.dir[n])}return new Wn(o,s,this.midP,a,!1,this.sizeX,this.sizeY)}flipDirs(){return new Wn(this.v,this.m,this.midP,this.dir.map(t=>!t),!1,this.sizeX,this.sizeY)}grow(t=1){const{v:e,m:n,dir:r}=this.trim(t),i=e.length,o=2*i,s=new Array(i),a=new Array(i),l=new Array(o),c=new Array(o),u="out"===xt.fill.direction?-90:90;0===Vn[0].length&&$n();const h=Vn[0],f=h.length,x=Vn[1],m=x.length;let d,g,p,y=0,v=0,_=999===t?N(.6,.8):xt.fill.bleed_strength;for(let o=0;o<i;o++){const d=e[o],g=e[o+1<i?o+1:0],p=n[o],b=r[o];if(t<997&&(_=p),_<.05){l[y]=p,c[y]=b,y++,s[v]=(d.x+g.x)/2,a[v]=(d.y+g.y)/2,l[y]=p,c[y]=b,y++,v++;continue}const w=(b?u:-u)+5*N(-1,1),R=K(w),A=q(w),E=g.x-d.x,M=g.y-d.y,S=R*E+A*M,P=R*M-A*E,k=h[~~(N(0,1)*f)]*N(.65,1.35)*_,T=p+x[~~(N(0,1)*m)];l[y]=p,c[y]=b,y++,s[v]=d.x+.5*E+S*k,a[v]=d.y+.5*M+P*k,l[y]=T,c[y]=b,y++,v++}const b=2024*Math.max(.1,2*xt.fill.bleed_strength);if(b&&y>b){const t=Math.ceil(y/b),n=Math.ceil(y/t);d=new Array(n),g=new Array(n),p=new Array(n);let r=0;for(let n=0;n<y;n+=t,r++)d[r]=n%2==0?e[n>>1]:{x:s[n>>1],y:a[n>>1]},g[r]=l[n],p[r]=c[n]}else{d=new Array(y);for(let t=0;t<y;t++)d[t]=t%2==0?e[t>>1]:{x:s[t>>1],y:a[t>>1]};l.length=y,c.length=y,g=l,p=c}return new Wn(d,g,this.midP,p,!1,this.sizeX,this.sizeY)}fill(t,r,i){const s=3*i,a=2*r*(1+i/2),l=!1!==dt.isBrush;dt.isBrush=!1,l&&(dt.justChanged=!0),dt.blend(t),dt.ctx.save(),dt.ctx.setTransform(o*_t(),o*bt(),o*wt(),o*Rt(),o*(yt()+e/2),o*(vt()+n/2)),dt.ctx.strokeStyle=`rgb(${t._getRed()} ${t._getGreen()} ${t._getBlue()} / ${.005*xt.fill.border_strength})`,dt.ctx.lineCap="round";const c=Math.max(this.sizeX,this.sizeY),u=N(.15,.7);let h=this.grow();const f=this.scatter(.1).grow().scatter(.75).flipDirs();let x;for(let e=0;e<20;e++){e%4==0&&(h=h.grow()),e%2==0&&(x=[h.grow(1-.0125*e),h.grow(.7-.0125*e),h.grow(.4-.0125*e)]);for(const n of x)n.grow(999).grow(997).layer(e,c,a,t);f.grow(999).flipDirs().grow(997).layer(e,c,a*s,t),e%2==0&&h.grow(u).grow(999).layer(e,c,2*a,t),e%8!=0&&19!==e||(0!==s&&h.erase(3*s,r),dt.blend(t,!0))}dt.ctx.restore()}layer(t,e,n,r){dt.ctx.lineWidth=Z(t,0,24,e/25,e/30,!0),dt.ctx.fillStyle=`rgb(${r._getRed()} ${r._getGreen()} ${r._getBlue()} / ${n}%)`,function(t){const e=dt.ctx,n=e.getTransform(),r=n.a,i=n.b,o=n.c,s=n.d,a=n.e,l=n.f;let c=Infinity,u=Infinity,h=-Infinity,f=-Infinity;e.beginPath();const x=t[0];let m=r*x.x+o*x.y+a,d=i*x.x+s*x.y+l;c=h=m,u=f=d,e.moveTo(x.x,x.y);for(let n=1;n<t.length;n++){const x=t[n];m=r*x.x+o*x.y+a,d=i*x.x+s*x.y+l,c=Math.min(c,m),u=Math.min(u,d),h=Math.max(h,m),f=Math.max(f,d),e.lineTo(x.x,x.y)}e.closePath();const g=function(t,e){const n=t.lineWidth||0;return n<=0?1:1+n*Math.max(Math.hypot(e.a,e.c),Math.hypot(e.b,e.d))/2}(e,n);dt.markDirtyRect(dt.mask,{minX:c-g,minY:u-g,maxX:h+g,maxY:f+g})}(this.v),dt.ctx.fill(),dt.ctx.stroke()}erase(t,e){dt.ctx.save();const n=~~(N(80,110)*Z(t,0,1,2,3.5)),r=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:l,y:c}=this.midP;dt.ctx.globalCompositeOperation="destination-out";const u=(5-Z(e,80,100,.3,.7,!0))*t/255;dt.ctx.fillStyle=`rgb(255 0 0 / ${u})`,dt.ctx.lineWidth=0;for(let t=0;t<n;t++){const e=l+U(0,r),n=c+U(0,i),o=N(s,a);dt.ctx.beginPath(),Bn(e,n,o),t%5!=0&&dt.ctx.fill()}dt.ctx.globalCompositeOperation="source-over",dt.ctx.restore()}}function jn(t,e){if(!t)return t;e||(e=t);let n,r=t;do{if(n=!1,r.steiner||!or(r,r.next)&&0!==ir(r.prev,r,r.next))r=r.next;else{if(fr(r),r=e=r.prev,r===r.next)break;n=!0}}while(n||r!==e);return e}function Kn(t,e,n,r,i,o,s){if(!t)return;!s&&o&&function(t,e,n,r){let i=t;do{0===i.z&&(i.z=er(i.x,i.y,e,n,r)),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,n=1;do{let r,i=t;t=null;let o=null;for(e=0;i;){e++;let s=i,a=0;for(let t=0;t<n&&(a++,s=s.nextZ,s);t++);let l=n;for(;a>0||l>0&&s;)0!==a&&(0===l||!s||i.z<=s.z)?(r=i,i=i.nextZ,a--):(r=s,s=s.nextZ,l--),o?o.nextZ=r:t=r,r.prevZ=o,o=r;i=s}o.nextZ=null,n*=2}while(e>1)}(i)}(t,r,i,o);let a=t;for(;t.prev!==t.next;){const l=t.prev,c=t.next;if(o?Jn(t,r,i,o):qn(t))e.push(l.i,t.i,c.i),fr(t),t=c.next,a=c.next;else if((t=c)===a){s?1===s?Kn(t=Qn(jn(t),e),e,n,r,i,o,2):2===s&&tr(t,e,n,r,i,o):Kn(jn(t),e,n,r,i,o,1);break}}}function qn(t){const e=t.prev,n=t,r=t.next;if(ir(e,n,r)>=0)return!1;const i=e.x,o=n.x,s=r.x,a=e.y,l=n.y,c=r.y,u=Math.min(i,o,s),h=Math.min(a,l,c),f=Math.max(i,o,s),x=Math.max(a,l,c);let m=r.next;for(;m!==e;){if(m.x>=u&&m.x<=f&&m.y>=h&&m.y<=x&&nr(i,a,o,l,s,c,m.x,m.y)&&ir(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function Jn(t,e,n,r){const i=t.prev,o=t,s=t.next;if(ir(i,o,s)>=0)return!1;const a=i.x,l=o.x,c=s.x,u=i.y,h=o.y,f=s.y,x=Math.min(a,l,c),m=Math.min(u,h,f),d=Math.max(a,l,c),g=Math.max(u,h,f),p=er(x,m,e,n,r),y=er(d,g,e,n,r);let v=t.prevZ,_=t.nextZ;for(;v&&v.z>=p&&_&&_.z<=y;){if(v.x>=x&&v.x<=d&&v.y>=m&&v.y<=g&&v!==i&&v!==s&&nr(a,u,l,h,c,f,v.x,v.y)&&ir(v.prev,v,v.next)>=0)return!1;if(v=v.prevZ,_.x>=x&&_.x<=d&&_.y>=m&&_.y<=g&&_!==i&&_!==s&&nr(a,u,l,h,c,f,_.x,_.y)&&ir(_.prev,_,_.next)>=0)return!1;_=_.nextZ}for(;v&&v.z>=p;){if(v.x>=x&&v.x<=d&&v.y>=m&&v.y<=g&&v!==i&&v!==s&&nr(a,u,l,h,c,f,v.x,v.y)&&ir(v.prev,v,v.next)>=0)return!1;v=v.prevZ}for(;_&&_.z<=y;){if(_.x>=x&&_.x<=d&&_.y>=m&&_.y<=g&&_!==i&&_!==s&&nr(a,u,l,h,c,f,_.x,_.y)&&ir(_.prev,_,_.next)>=0)return!1;_=_.nextZ}return!0}function Qn(t,e){let n=t;do{const r=n.prev,i=n.next.next;!or(r,i)&&sr(r,n,n.next,i)&&cr(r,i)&&cr(i,r)&&(e.push(r.i,n.i,i.i),fr(n),fr(n.next),n=t=i),n=n.next}while(n!==t);return jn(n)}function tr(t,e,n,r,i,o){let s=t;do{let t=s.next.next;for(;t!==s.prev;){if(s.i!==t.i&&rr(s,t)){let a=ur(s,t);return s=jn(s,s.next),a=jn(a,a.next),Kn(s,e,n,r,i,o,0),void Kn(a,e,n,r,i,o,0)}t=t.next}s=s.next}while(s!==t)}function er(t,e,n,r,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-n)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-r)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function nr(t,e,n,r,i,o,s,a){return!(t===s&&e===a)&&function(t,e,n,r,i,o,s,a){return(i-s)*(e-a)>=(t-s)*(o-a)&&(t-s)*(r-a)>=(n-s)*(e-a)&&(n-s)*(o-a)>=(i-s)*(r-a)}(t,e,n,r,i,o,s,a)}function rr(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let n=t;do{if(n.i!==t.i&&n.next.i!==t.i&&n.i!==e.i&&n.next.i!==e.i&&sr(n,n.next,t,e))return!0;n=n.next}while(n!==t);return!1}(t,e)&&(cr(t,e)&&cr(e,t)&&function(t,e){let n=t,r=!1;const i=(t.x+e.x)/2,o=(t.y+e.y)/2;do{n.y>o!=n.next.y>o&&n.next.y!==n.y&&i<(n.next.x-n.x)*(o-n.y)/(n.next.y-n.y)+n.x&&(r=!r),n=n.next}while(n!==t);return r}(t,e)&&(ir(t.prev,t,e.prev)||ir(t,e.prev,e))||or(t,e)&&ir(t.prev,t,t.next)>0&&ir(e.prev,e,e.next)>0)}function ir(t,e,n){return(e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y)}function or(t,e){return t.x===e.x&&t.y===e.y}function sr(t,e,n,r){const i=lr(ir(t,e,n)),o=lr(ir(t,e,r)),s=lr(ir(n,r,t)),a=lr(ir(n,r,e));return i!==o&&s!==a||!(0!==i||!ar(t,n,e))||!(0!==o||!ar(t,r,e))||!(0!==s||!ar(n,t,r))||!(0!==a||!ar(n,e,r))}function ar(t,e,n){return e.x<=Math.max(t.x,n.x)&&e.x>=Math.min(t.x,n.x)&&e.y<=Math.max(t.y,n.y)&&e.y>=Math.min(t.y,n.y)}function lr(t){return t>0?1:t<0?-1:0}function cr(t,e){return ir(t.prev,t,t.next)<0?ir(t,e,t.next)>=0&&ir(t,t.prev,e)>=0:ir(t,e,t.prev)<0||ir(t,t.next,e)<0}function ur(t,e){const n=xr(t.i,t.x,t.y),r=xr(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,n.next=i,i.prev=n,r.next=n,n.prev=r,o.next=r,r.prev=o,r}function hr(t,e,n,r){const i=xr(t,e,n);return r?(i.next=r.next,i.prev=r,r.next.prev=i,r.next=i):(i.prev=i,i.next=i),i}function fr(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 xr(t,e,n){return{i:t,x:e,y:n,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}Ot.prototype.fill=function(t=!1,e,n,r,i,o){let s=On();t&&(Un(t,e),Xn(n,o),Zn(r,i)),s.isActive&&(Et(),function(t){if(!xt.fill.isActive||!xt.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");Gn=t;const e=[...t.vertices],n=~~(.25*e.length*X({1:5,2:10,3:60})),r=xt.fill.bleed_strength,i=e.map((t,e)=>(e>n?1:.3)*N(.85,1.4)*r),o=z(0,e.length),s=[...e.slice(o),...e.slice(0,o)],a=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 n=0,r=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;n+=o,r+=(e[t].x+e[t+1].x)*o,i+=(e[t].y+e[t+1].y)*o}return n*=.5,n?{x:r/(6*n),y:i/(6*n)}:{x:e[0].x,y:e[0].y}}(s);new Wn(s,i,a,[],!0).fill(xt.fill.color,Z(xt.fill.opacity,0,255,0,1,!0),xt.fill.texture_strength)}(this)),(t=>{xt.fill={...t}})(s)},Ut.prototype.fill=function(t,e,n){On().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],n=1),this.pol=this.genPol(t,e,n,xt.fill.bleed_strength<.06?0:Z(xt.fill.bleed_strength,0,.6,.2,.6,!0)),this.pol.fill())};let mr=null,dr=null,gr=null,pr=null,yr=null,vr=0,_r=0,br=0;const wr={},Rr={};function Ar(t,e,n,r){y(),xt.wash.opacity=(arguments.length<4?e:r)??150,xt.wash.color=arguments.length<3?i.color(t):i.color(t,e,n),xt.wash.isActive=!0}function Er(t,e){return[_t()*t+wt()*e+yt()+vr/2,bt()*t+Rt()*e+vt()+_r/2]}xt.wash={color:null,opacity:150,isActive:!1},Ot.prototype.wash=function(t=!1,r){const o={...xt.wash};!1!==t&&Ar(t,r),xt.wash.isActive&&function(t){if(!xt.wash?.isActive||!xt.wash.color||t.vertices.length<3)return;gt(),function(){const t=i.drawingContext;yr&&!(vr!==e||_r!==n)||(vr=e,_r=n,yr=new Float32Array([2/vr,0,0,0,0,-2/_r,0,0,0,0,1,0,-1,1,0,1])),mr===t&&dr&&gr&&pr||(mr=t,dr=Qt(mr,"#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}"),wr.a_position=mr.getAttribLocation(dr,"a_position"),Rr.u_matrix=mr.getUniformLocation(dr,"u_matrix"),Rr.u_color=mr.getUniformLocation(dr,"u_color"),gr=mr.createVertexArray(),mr.bindVertexArray(gr),pr=mr.createBuffer(),mr.bindBuffer(mr.ARRAY_BUFFER,pr),mr.bufferData(mr.ARRAY_BUFFER,0,mr.DYNAMIC_DRAW),br=0,mr.enableVertexAttribArray(wr.a_position),mr.vertexAttribPointer(wr.a_position,2,mr.FLOAT,!1,8,0),mr.bindVertexArray(null),mr.bindBuffer(mr.ARRAY_BUFFER,null))}();const{triangles:r,vertexCount:o}=function(t){const e=new Float32Array(2*t.vertices.length);for(let n=0;n<t.vertices.length;n++){const r=t.vertices[n];e[2*n]=r.x,e[2*n+1]=r.y}const n=function(t,e,n=2){const r=t.length;let i=function(t,e,n,r){let i;if(1==function(t,e,n,r){let i=0;for(let e=0,o=n-r;e<n;e+=r)i+=(t[o]-t[e])*(t[e+1]+t[o+1]),o=e;return i}(t,0,n,r)>0)for(let e=0;e<n;e+=r)i=hr(e/r|0,t[e],t[e+1],i);else for(let e=n-r;e>=0;e-=r)i=hr(e/r|0,t[e],t[e+1],i);return i&&or(i,i.next)&&(fr(i),i=i.next),i}(t,0,r,n);const o=[];if(!i||i.next===i.prev)return o;let s,a,l;if(t.length>80*n){s=t[0],a=t[1];let e=s,i=a;for(let o=n;o<r;o+=n){const n=t[o],r=t[o+1];n<s&&(s=n),r<a&&(a=r),n>e&&(e=n),r>i&&(i=r)}l=Math.max(e-s,i-a),l=0!==l?32767/l:0}return Kn(i,o,n,s,a,l,0),o}(e),r=new Float32Array(2*n.length);for(let t=0;t<n.length;t++){const i=n[t],[o,s]=Er(e[2*i],e[2*i+1]);r[2*t]=o,r[2*t+1]=s}return{triangles:r,vertexCount:n.length}}(t),s=r.byteLength;mr.useProgram(dr),mr.enable(mr.BLEND),mr.blendEquation(mr.FUNC_ADD),mr.blendFunc(mr.ONE,mr.ONE_MINUS_SRC_ALPHA),mr.bindVertexArray(gr),mr.bindBuffer(mr.ARRAY_BUFFER,pr),s>br?(mr.bufferData(mr.ARRAY_BUFFER,r,mr.DYNAMIC_DRAW),br=s):mr.bufferSubData(mr.ARRAY_BUFFER,0,r);const a=xt.wash.color._array;mr.uniformMatrix4fv(Rr.u_matrix,!1,yr),mr.uniform4f(Rr.u_color,a[0],a[1],a[2],xt.wash.opacity/255),mr.drawArrays(mr.TRIANGLES,0,o),mr.bindVertexArray(null),mr.bindBuffer(mr.ARRAY_BUFFER,null),function(){const t=i?._renderer;t&&(t._curShader=null,t._cachedBlendMode=null,t._isBlending=null)}()}(this),xt.wash={...o}},Ut.prototype.wash=function(t,e,n){xt.wash?.isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],n=1),this.pol=this.genPol(t,e,n,0,-1),this.pol.wash())};const Mr=[];"undefined"!=typeof p5&&p5.registerAddon(function(t,e,n){n.presetup=function(){_(this)},n.predraw=function(){_(this)},n.postsetup=function(){v(this),gt(),b()},n.postdraw=function(){v(this),gt(),b()};const r=e.push,i=e.pop,o=e.randomSeed,s=e.noiseSeed;e.push=function(){r.call(this),Et(),Mr.push({fill:{...xt.fill},wash:xt.wash?{...xt.wash}:null,stroke:{...xt.stroke},hatch:{...xt.hatch},mass:xt.mass?{...xt.mass}:null,field:{...xt.field}})},e.pop=function(){i.call(this),function(){const t=Mr.pop();t&&(xt.stroke={...t.stroke},xt.field={...t.field},xt.hatch={...t.hatch},xt.fill={...t.fill},t.wash&&(xt.wash={...t.wash}),t.mass?xt.mass={...t.mass}:xt.mass&&(xt.mass={...xt.mass,isActive:!1,brush:null,color:null,options:{}}))}()},e.randomSeed=function(t){o.call(this,t),(t=>{T=P(t),C=P(`${t}:2`);for(const t of I)t()})(t)},e.noiseSeed=function(t){s.call(this,t),(t=>{F=S(P(t)),D=S(P(`${t}:2`))})(t)}}),t.Plot=Ut,t.Polygon=Ot,t.Position=Mt,t.add=Je,t.addField=Bt,t.arc=Xt,t.beginShape=Wt,t.beginStroke=function(t,e,n){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);$t=[e,n],Vt=new Ut(t)},t.box=function(){return[...He.keys()]},t.circle=function(t,e,n,r=!1){const i=new Ut("curve"),o=Math.PI*n,s=B(0,360),a=r?()=>1+.2*r*B():()=>1;for(let t=0;t<4;t++){const e=-90*t+s;i.addSegment(e*a(),o/2*a(),1,!0)}if(r){const t=r*O(-5,5);i.addSegment(s,Math.abs(t)*(Math.PI/180)*n,1,!0),i.endPlot(t+s,1,!0)}else i.endPlot(s,1,!0);const l=t-n*q(s),c=e-n*K(-s);i.show(l,c,1)},t.clip=function(t){return y(),t},t.endShape=Kt,t.endStroke=function(t,e){if(!Vt)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");Vt.endPlot(t,e),Vt.draw($t[0],$t[1],1),Vt=!1},t.field=Nt,t.fill=Un,t.fillBleed=Xn,t.fillTexture=Zn,t.flowLine=function(t,e,n,r){if(!xt.stroke.isActive||!xt.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");Et(),un(t,e,n),fn(J(r),!1)},t.hatch=En,t.hatchArray=Pn,t.hatchStyle=function(t,e="black",n=1){xt.hatch.hBrush={brush:t,color:e,weight:n}},t.instance=v,t.line=vn,t.listFields=function(){return Et(),Array.from(It.keys())},t.load=(t=!1)=>{p(t),i.loaded&&dt.load()},t.mass=function(t,e,n={}){xt.mass.brush=t,xt.mass.color=e,xt.mass.options=n,xt.mass.isActive=!0},t.move=function(t,e,n){if(!Vt)throw new Error("move() called without beginStroke(). Call beginStroke() first.");Vt.addSegment(t,e,n)},t.noClip=function(){},t.noField=function(){Et(),xt.field.isActive=!1},t.noFill=function(){xt.fill.isActive=!1},t.noHatch=function(){xt.hatch.isActive=!1,xt.hatch.hBrush=!1},t.noMass=function(){xt.mass.isActive=!1,xt.mass.brush=null,xt.mass.color=null,xt.mass.options={}},t.noStroke=function(){xt.stroke.isActive=!1},t.noWash=function(){xt.wash.isActive=!1},t.pick=tn,t.polygon=function(t){new Ot(t).show()},t.rect=function(t,e,n,r,i="corner"){"center"===i&&(t-=n/2,e-=r/2),Wt(0),jt(t,e),jt(t+n,e),jt(t+n,e+r),jt(t,e+r),Kt(!0)},t.refreshField=function(t=0){if(!xt.field.isActive||!xt.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=It.get(xt.field.current);e.field=Dt(e,t)},t.scaleBrushes=function(t){for(const{param:e}of He.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)},t.set=rn,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].");qt(t,e).draw()},t.stroke=en,t.strokeWeight=nn,t.vertex=jt,t.wRand=X,t.wash=Ar,t.wiggle=Yt},"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=p5.brush.js.mapdiff --git a/dist/p5.brush.js.map b/dist/p5.brush.js.mapindex 22f9b04..40fbbe7 100644--- a/dist/p5.brush.js.map+++ b/dist/p5.brush.js.map@@ -1 +1 @@-{"version":3,"file":"p5.brush.js","sources":["../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/polygon.js","../src/core/plot.js","../src/core/primitives.js","../src/core/gl/utils.js","../src/stroke/gl_draw.js","../src/stroke/stroke.js","../src/hatch/hatch.js","../src/fill/mask.js","../src/fill/fill.js","../src/core/save.js","../src/index.js"],"sourcesContent":["import 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\nexport let Cwidth, Cheight, Instance, Renderer, Density; // Global canvas properties\n\nlet FillMaskUploadCanvas = null;\nlet ReadySketch = null;\nlet ActiveInstance = null;\nconst ActiveInstanceStack = [];\n\n// =============================================================================\n// Section: Target Resolution\n// =============================================================================\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 */\nconst 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 */\nconst 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 // brush.load() can target the main sketch renderer, a p5.Graphics surface,\n // or an active framebuffer owned by the current sketch.\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 */\nconst getActiveFramebuffer = () => Renderer?._renderer?.activeFramebuffer?.() ?? null;\n\nconst clearTarget = (target) => {\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\nconst uploadFillMaskToMirror = (mask, dirtyRect = null) => {\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 = new OffscreenCanvas(uploadWidth, uploadHeight);\n FillMaskUploadCanvas.drawingContext = FillMaskUploadCanvas.getContext(\"2d\");\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\n return target;\n};\n\n// =============================================================================\n// Section: Dirty Rect Utilities\n// =============================================================================\nconst DIRTY_BRUSH_PADDING = 2;\nconst DIRTY_FILL_PADDING = 4;\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\n/**\n * Expands a dirty rectangle outward by a constant padding value.\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 */\nconst 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 the current target bounds.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Candidate rect.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Clamped rect.\n */\nconst normalizeDirtyRect = (rect) => {\n if (!rect) return null;\n\n const { width, height } = getTargetPixelSize();\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 * @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 */\nconst 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 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 { minX: 0, minY: 0, maxX: width, maxY: 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// Section: Load and State\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 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 Cwidth = target.width;\n Cheight = target.height;\n\n _isReady = true;\n if (Renderer.loaded) Mix.load();\n};\n\nlet _isReady = false;\n\n/**\n * Ensures the drawing system is ready before any operation.\n */\nexport const isCanvasReady = () => {\n if (!_isReady) load();\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\nexport const instance = (inst) => {\n 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/**\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: new Object(),\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\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\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 WEBGL brush mask.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\n getCompositeRect(target, isBrushMask) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n\n // Brush-mask dirty rects are still less predictable when the destination\n // is itself a framebuffer, so keep that path conservative.\n if (isBrushMask && getActiveFramebuffer()) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(\n target.dirtyRect,\n isBrushMask ? DIRTY_BRUSH_PADDING : DIRTY_FILL_PADDING,\n ),\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 Density = Renderer.pixelDensity();\n const maskWidth = Math.max(1, Math.round(Cwidth * Density));\n const maskHeight = Math.max(1, Math.round(Cheight * Density));\n const needsBuffers =\n !Renderer.mask ||\n !Renderer.glMask ||\n Renderer.mask.width !== maskWidth ||\n Renderer.mask.height !== maskHeight ||\n Renderer.glMask.width !== Cwidth ||\n Renderer.glMask.height !== Cheight;\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 const needsFillMaskFramebuffer =\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 if (!Renderer.loaded || needsBuffers) {\n if (Renderer.glMask?.remove) Renderer.glMask.remove();\n // Keep one 2D mask for fill/hatch work and one framebuffer-backed mask\n // for brush stamps so the brush path stays in the main renderer context.\n Renderer.mask = new OffscreenCanvas(maskWidth, maskHeight);\n Renderer.mask.drawingContext = Renderer.mask.getContext(\"2d\");\n Renderer.glMask = Renderer.createFramebuffer({\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n Renderer.loaded = true;\n\n Renderer.shaderProgram ??= Renderer.createShader(vertSrc, fragSrc);\n }\n\n if (needsBlendSourceFramebuffer) {\n if (Renderer.blendSourceFramebuffer?.remove) {\n Renderer.blendSourceFramebuffer.remove();\n }\n Renderer.blendSourceFramebuffer = Renderer.createFramebuffer({\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n }\n\n if (needsFillMaskFramebuffer) {\n if (Renderer.fillMaskFramebuffer?.remove) {\n Renderer.fillMaskFramebuffer.remove();\n }\n Renderer.fillMaskFramebuffer = Renderer.createFramebuffer({\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 this.mask = Renderer.mask;\n this.glMask = Renderer.glMask;\n this.ctx = this.mask.drawingContext;\n this.mask.dirtyRect ??= null;\n this.mask.isDrawn ??= false;\n this.ctx.imageSmoothingEnabled = false;\n\n this.glMask.dirtyRect ??= null;\n this.glMask.isDrawn ??= false;\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\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 at the start of each blend cycle.\n clearTarget(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) this.isBlending = false;\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 WEBGL 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 = blitToBlendSourceFramebuffer(activeFramebuffer ?? Renderer, dirtyRect);\n const targetIsFramebuffer = !!activeFramebuffer;\n const hadDepthTest = gl.getParameter(gl.DEPTH_TEST);\n\n // This pass is a fullscreen compositing rect, not scene geometry, so it\n // should not participate in the sketch's depth buffer.\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 if (isBrushMask) {\n shader.setUniform(\"u_mask\", mask);\n } else {\n shader.setUniform(\"u_mask\", uploadFillMaskToMirror(mask, dirtyRect));\n }\n shader.setUniform(\"u_color\", this.cachedColor);\n\n withScissor(gl, dirtyRect, () => {\n Renderer.fill(0, 0, 0, 0);\n Renderer.noStroke();\n Renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);\n }, !targetIsFramebuffer);\n\n Renderer.pop();\n Renderer.resetShader();\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n this.clearMask(mask);\n },\n};\n\n/**\n * Copies the current pixels of a renderer or framebuffer into the reusable\n * blend source framebuffer.\n * @param {p5|p5.Graphics|p5.Framebuffer} sourceTarget - Source to copy from.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} [dirtyRect=null] - Optional copy region.\n * @returns {p5.Framebuffer} Blend source framebuffer after the blit.\n */\nconst blitToBlendSourceFramebuffer = (sourceTarget, dirtyRect = null) => {\n const sourceFramebuffer = Renderer.blendSourceFramebuffer;\n const gl = Renderer.drawingContext;\n const sourceIsFramebuffer = isFramebufferTarget(sourceTarget);\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 (sourceIsFramebuffer ? sourceTarget.renderer : Renderer._renderer)?.flushDraw?.();\n\n if (sourceIsFramebuffer) {\n sourceFramebuffer.draw(() => {\n withScissor(Renderer.drawingContext, dirtyRect, () => {\n Renderer.clear();\n Renderer.push();\n Renderer.imageMode(Renderer.CENTER);\n Renderer.image(sourceTarget, 0, 0, Cwidth, Cheight);\n Renderer.pop();\n }, false);\n });\n return sourceFramebuffer;\n }\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","/*\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 { Renderer } from \"./color.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 const usesRadians =\n isRad ||\n (Renderer &&\n typeof Renderer.angleMode === \"function\" &&\n Renderer.angleMode() === Renderer.RADIANS);\n // Only if Renderer.angleMode() is set to radians\n if (usesRadians) {\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 ||\n (Renderer &&\n typeof Renderer.angleMode === \"function\" &&\n Renderer.angleMode() === Renderer.RADIANS)\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 { isMixReady, Cwidth, Cheight, State, Renderer } from \"./color.js\";\nimport { randInt2, noise2, rr2, sin, cos, map, toDegreesSigned } from \"./utils.js\";\n\n// =============================================================================\n// Section: Matrix transformations\n// =============================================================================\n\n/**\n * The `Matrix` object exposes the current 2D affine transform from p5's model matrix.\n * mat4 layout (column-major 4x4):\n * [0]=a [1]=b [4]=c [5]=d [12]=tx [13]=ty\n * where the 2D transform of a point (x,y) is: (a*x + c*y + tx, b*x + d*y + ty)\n */\nexport const Matrix = {\n x: () => Renderer._renderer.uModelMatrix.mat4[12],\n y: () => Renderer._renderer.uModelMatrix.mat4[13],\n a: () => Renderer._renderer.uModelMatrix.mat4[0],\n b: () => Renderer._renderer.uModelMatrix.mat4[1],\n c: () => Renderer._renderer.uModelMatrix.mat4[4],\n d: () => Renderer._renderer.uModelMatrix.mat4[5],\n};\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 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 = Position.getColIndex(x);\n this.rowIdx = Position.getRowIndex(y);\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 + Matrix.x();\n const y = this.y + Matrix.y();\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() {\n return this.isIn() && State.field.isActive\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 p5 angle mode.\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 for (let i = 0; i < _length / _step; i++) {\n const angle =\n this.angle() - (_scale ? _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 + Matrix.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 + Matrix.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.stroke) this.draw();\n if (State.hatch) this.hatch();\n if (State.fill) this.fill();\n }\n}\n","import { State, Cwidth, Cheight } 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 = 0.5;\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 const maxSize = _side === 0 ? 5 : 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.stroke) this.draw(x, y, scale);\n if (State.hatch) this.hatch(x, y, scale);\n if (State.fill) this.fill(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 * @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 p5 angle mode.\n * @param {number} end - End angle in the current p5 angle mode.\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 * 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// 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 {\n Mix,\n Cwidth,\n Cheight,\n isMixReady,\n Density,\n State,\n Renderer,\n} from \"../core/color.js\";\nimport { Matrix } from \"../core/flowfield.js\";\nimport { createProgram } from \"../core/gl/utils.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;\nlet prevMaskTarget = 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 p5 model matrix. Call once at the start of each stroke.\n */\nexport function snapshotMatrix() {\n _ma = Matrix.a();\n _mb = Matrix.b();\n _mc = Matrix.c();\n _md = Matrix.d();\n _mx = Matrix.x();\n _my = Matrix.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 resetMaskShaderTracking() {\n const renderer = Mix.glMask?.renderer;\n if (!renderer) return;\n renderer._curShader = null;\n renderer._cachedBlendMode = null;\n renderer._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\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 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 const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n beginMaskTarget._hadDepthTest = hadDepthTest;\n if (hadDepthTest) gl.disable(gl.DEPTH_TEST);\n prevMaskTarget = Renderer._renderer.activeFramebuffer?.() ?? null;\n if (prevMaskTarget?._beforeEnd) prevMaskTarget._beforeEnd();\n gl.bindFramebuffer(gl.FRAMEBUFFER, getFramebufferHandle(Mix.glMask));\n gl.viewport(\n 0,\n 0,\n Mix.glMask.width * Mix.glMask.density,\n Mix.glMask.height * Mix.glMask.density,\n );\n}\n\nfunction endMaskTarget() {\n if (beginMaskTarget._hadDepthTest) gl.enable(gl.DEPTH_TEST);\n beginMaskTarget._hadDepthTest = false;\n if (prevMaskTarget?._beforeBegin) {\n prevMaskTarget._beforeBegin();\n } else {\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 prevMaskTarget = null;\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 * p5's current model matrix 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 {p5.Image} p5img - The preprocessed brush-tip image (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 beginMaskTarget();\n\n // Lazy-create the WebGL texture from the p5.Image 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();\n\n if (imgDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, imgDirtyRect);\n imgDirtyRect = null;\n }\n\n imgCount = 0;\n\n // Let p5 know we changed the active program\n resetMaskShaderTracking();\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 beginMaskTarget();\n\n const color = State.stroke.color._array;\n\n // Re-activate our shader (p5 drawing may have 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();\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 p5's _curShader tracking.\n // Reset it to null so p5 is forced to re-activate its own shader next time\n // it draws — otherwise p5 skips gl.useProgram() and sets uniforms on the\n // wrong active program, causing \"location is not from the associated program\".\n resetMaskShaderTracking();\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\nimport {\n Mix,\n Cwidth,\n Cheight,\n State,\n Renderer,\n Instance,\n isCanvasReady,\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} from \"../core/utils.js\";\nimport { Position, Matrix, isFieldReady } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport {\n isReady,\n glDraw,\n glDrawImages,\n circle,\n stampImage,\n invalidateTexEntry,\n snapshotMatrix,\n} from \"./gl_draw.js\";\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 clipWindow: null,\n type: \"HB\",\n isActive: false,\n opacity: 1,\n};\n\nlet list = new Map();\nlet _strokeTransform = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n tx: 0,\n ty: 0,\n};\n\nfunction getBrushFactory() {\n return Renderer ?? Instance ?? window.self.p5.instance;\n}\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 // 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 factory = getBrushFactory();\n const g = factory.createGraphics(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\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 = Renderer.color(...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\nfunction snapshotTransform() {\n return {\n a: Matrix.a(),\n b: Matrix.b(),\n c: Matrix.c(),\n d: Matrix.d(),\n tx: Matrix.x(),\n ty: Matrix.y(),\n };\n}\n\nfunction invertTransform(transform) {\n const det = transform.a * transform.d - transform.b * transform.c;\n if (Math.abs(det) < 1e-12) return null;\n\n return {\n a: transform.d / det,\n b: -transform.b / det,\n c: -transform.c / det,\n d: transform.a / det,\n tx: (transform.c * transform.ty - transform.d * transform.tx) / det,\n ty: (transform.b * transform.tx - transform.a * transform.ty) / det,\n };\n}\n\nfunction normalizeRegion(region) {\n const [x1, y1, x2, y2] = region;\n return {\n minX: Math.min(x1, x2),\n minY: Math.min(y1, y2),\n maxX: Math.max(x1, x2),\n maxY: Math.max(y1, y2),\n };\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 p5 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 const inverse = invertTransform(snapshotTransform());\n if (!inverse) {\n throw new Error(\n \"brush.clip() cannot be used with a non-invertible transform.\",\n );\n }\n State.stroke.clipWindow = {\n bounds: normalizeRegion(region),\n inverse,\n };\n}\n\n/**\n * Disables the clipping region.\n */\nexport function noClip() {\n State.stroke.clipWindow = null;\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 _strokeTransform = snapshotTransform();\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 for (let i = 0; i < totalSteps; i++) {\n if (gaussians.length < totalSteps * 2) {\n gaussians.push(gaussian());\n }\n tip();\n isPlot\n ? _position.plotTo(\n _plot,\n stepSize,\n stepSize,\n angleScale,\n i < 10 ? true : false,\n )\n : _position._moveToDegrees(angleScale, stepSize, stepSize);\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.03;\n\n // Cache stroke direction for direction-aware dispersion (non-plot strokes only)\n if (!_plot) {\n const dirRad = (_dir * Math.PI) / 180;\n current.cos = Math.cos(dirRad);\n current.sin = Math.sin(dirRad);\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 // Pre-compute clip-check coefficients so isInsideClippingArea() needs no\n // temporary objects and only one matrix×vector multiply per step instead of two.\n {\n const cw2 = Cwidth / 2, ch2 = Cheight / 2;\n const T = _strokeTransform;\n if (State.stroke.clipWindow) {\n const { inverse: I, bounds: B } = State.stroke.clipWindow;\n // Compose (I ∘ T) and fold the -cw2/-ch2 position offset into the translation\n const ca = I.a * T.a + I.c * T.b, cc = I.a * T.c + I.c * T.d;\n const cb = I.b * T.a + I.d * T.b, cd = I.b * T.c + I.d * T.d;\n current.clipA = ca; current.clipB = cb;\n current.clipC = cc; current.clipD = cd;\n current.clipTX = I.a * T.tx + I.c * T.ty + I.tx - ca * cw2 - cc * ch2;\n current.clipTY = I.b * T.tx + I.d * T.ty + I.ty - cb * cw2 - cd * ch2;\n current.clipMinX = B.minX; current.clipMaxX = B.maxX;\n current.clipMinY = B.minY; current.clipMaxY = B.maxY;\n } else {\n const o =\n current.p.type === \"custom\" || current.p.type === \"image\"\n ? Math.max(Cwidth * 0.05, getImageTipOverscan())\n : Cwidth * 0.05;\n current.clipA = T.a; current.clipB = T.b;\n current.clipC = T.c; current.clipD = T.d;\n current.clipTX = T.tx - T.a * cw2 - T.c * ch2;\n current.clipTY = T.ty - T.b * cw2 - T.d * ch2;\n current.clipMinX = -cw2 - o; current.clipMaxX = cw2 + o;\n current.clipMinY = -ch2 - o; current.clipMaxY = ch2 + o;\n }\n }\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 insideClip = isInsideClippingArea();\n if (!insideClip) return;\n const pressure = calculatePressure();\n const lineNoise = map(\n noise(current.seed + _position.plotted * 0.002, 0),\n 0,\n 1,\n 1 - current.noiseoffset,\n 1 + current.noiseoffset,\n );\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 return _plot\n ? simPressure() * _plot.pressure(_position.plotted)\n : simPressure();\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 * Checks if the current drawing position is within the clipping region.\n * Uses coefficients pre-computed in saveState() — no object allocations,\n * one fused matrix×vector multiply (both transforms composed at setup time).\n * @returns {boolean} True if inside clipping area; false otherwise.\n */\nfunction isInsideClippingArea() {\n const lx = current.clipA * _position.x + current.clipC * _position.y + current.clipTX;\n if (lx < current.clipMinX || lx > current.clipMaxX) return false;\n const ly = current.clipB * _position.x + current.clipD * _position.y + current.clipTY;\n return ly >= current.clipMinY && ly <= current.clipMaxY;\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 dx = 0.7 * vibration * rr(-1, 1);\n dy = vibration * rr(-1, 1);\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 if (isInsideClippingArea()) {\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// ---------------------------------------------------------------------------\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 p5 angle mode.\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];\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 \"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 p5.js graphics library.\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 p5.Image 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 new Promise((resolve, reject) => {\n const nativeImg = new window.Image();\n nativeImg.onload = () => {\n const factory = getBrushFactory();\n const p5img = factory.createImage(\n nativeImg.naturalWidth,\n nativeImg.naturalHeight,\n );\n p5img.drawingContext.drawImage(nativeImg, 0, 0);\n T.imageToWhite(p5img);\n this.tips.set(src, p5img);\n resolve();\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 );\n },\n};\n","// =============================================================================\n// Module: Classic Hatch\n// =============================================================================\n\nimport { 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// Hatch State\n// ---------------------------------------------------------------------------\n\nState.hatch = {\n isActive: false,\n dist: 5,\n angle: 45,\n options: {},\n hBrush: false,\n};\n\nexport function HatchState() {\n return { ...State.hatch };\n}\n\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\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\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Scanline Hatching\n// ---------------------------------------------------------------------------\n\n/**\n * Computes hatch segments for a polygon via scanline intersection.\n * Rotates vertices so hatch lines become horizontal, scans for edge\n * crossings, then rotates intersections back to original space.\n */\nfunction scanlineHatch(polygon, angle, dist, gradient) {\n const rad = (angle * Math.PI) / 180;\n const cosA = Math.cos(rad), sinA = Math.sin(rad);\n const cosB = Math.cos(-rad), sinB = Math.sin(-rad);\n\n const verts = polygon.a, n = verts.length;\n\n // Rotate vertices; track Y extent\n const rotated = new Array(n);\n let minY = Infinity, maxY = -Infinity;\n for (let i = 0; i < n; i++) {\n const x = verts[i][0], 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], 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 let Y = minY + dist * 0.5, step = dist;\n while (Y < maxY) {\n const cx = [];\n for (let i = 0; i < eLen; i += 2) {\n const y1 = edges[i][1], y2 = edges[i + 1][1];\n if ((y1 <= Y && Y < y2) || (y2 <= Y && Y < y1))\n cx.push(edges[i][0] + ((Y - y1) / (y2 - y1)) * (edges[i + 1][0] - edges[i][0]));\n }\n cx.sort((a, b) => a - b);\n for (let i = 0; i < cx.length - 1; i += 2) {\n segments.push({\n x1: cx[i] * cosB - Y * sinB, y1: cx[i] * sinB + Y * cosB,\n x2: cx[i + 1] * cosB - Y * sinB, y2: cx[i + 1] * sinB + Y * cosB,\n });\n }\n Y += step;\n step *= gradient;\n }\n return segments;\n}\n\n// ---------------------------------------------------------------------------\n// Create Hatch\n// ---------------------------------------------------------------------------\n\nexport function createHatch(polygons) {\n const dist = State.hatch.dist;\n const angle = ((State.hatch.angle % 180) + 180) % 180;\n const options = State.hatch.options;\n\n const save = BrushState();\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n if (!Array.isArray(polygons)) polygons = [polygons];\n\n const gradient = options.gradient ? map(options.gradient, 0, 1, 1, 1.1, true) : 1;\n\n const segs = [];\n for (const poly of polygons)\n for (const s of scanlineHatch(poly, angle, dist, gradient)) segs.push(s);\n segs.sort((a, b) => a.x1 === b.x1 ? a.y1 - b.y1 : a.x1 - b.x1);\n\n const r = options.rand || 0;\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 += r * dist * rr(-1, 1);\n y1 += r * dist * rr(-1, 1);\n x2 += r * dist * rr(-1, 1);\n y2 += r * dist * rr(-1, 1);\n }\n line(x1, y1, x2, y2);\n if (j > 0 && options.continuous) line(segs[j - 1].x2, segs[j - 1].y2, x1, y1);\n }\n\n BrushSetState(save);\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (state.isActive) createHatch(this);\n HatchSetState(state);\n};\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.25);\n this.pol.hatch();\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","// =============================================================================\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\nimport {\n Renderer,\n Mix,\n State,\n Cwidth,\n Cheight,\n Density,\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, Matrix } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\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;\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 =\n arguments.length < 3 ? Renderer.color(a) : Renderer.color(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 const insertedX = new Array(len);\n const insertedY = new Array(len);\n const newMods = new Array(outLen);\n const newDirs = new Array(outLen);\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 const growCap = GROW_MAX_VERTS * Math.max(0.1, 2 * State.fill.bleed_strength);\n if (growCap && idx > growCap) {\n const step = Math.ceil(idx / growCap);\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 newMods.length = idx;\n newDirs.length = idx;\n fm = newMods;\n fd = newDirs;\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 Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * Matrix.a(),\n Density * Matrix.b(),\n Density * Matrix.c(),\n Density * Matrix.d(),\n Density * (Matrix.x() + Cwidth / 2),\n Density * (Matrix.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 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, false, 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","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 stroke: { ...State.stroke },\n hatch: { ...State.hatch },\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}\n","/**\n * @fileoverview p5.brush - A comprehensive toolset for brush management in p5.js.\n * @license MIT\n * @author Alejandro Campos Uribe\n *\n * @description\n * p5.brush is a p5.js library dedicated to the creation and management of custom brushes.\n * It extends the drawing capabilities of p5.js by allowing users to simulate a wide range\n * of brush strokes, vector fields, hatching patterns, and fill textures. These features\n * are essential for emulating the nuanced effects found in traditional sketching and painting.\n * Whether for digital art applications or procedural generation of graphics, p5.brush provides\n * a robust framework for artists and developers to create rich, dynamic, and textured visuals.\n *\n * @example\n * // Basic usage:\n * brush.pick('marker'); // Select brush type\n * brush.stroke(255, 0, 0); // Set brush color\n * brush.strokeWeight(10); // Set brush size\n * brush.line(25, 25, 75, 75); // Draw a line\n *\n * // Add a new brush type:\n * brush.add('customBrush', { /* parameters for the brush *\\/ });\n * brush.pick('customBrush');\n *\n * // Use the custom brush for a vector-field line:\n * brush.field('field_name') // Pick a flowfield\n * brush.flowLine(50, 50, 100, PI / 4); // Draw a line within the vector-field; angle follows p5 angleMode()\n *\n * // Fill textures:\n * brush.noStroke();\n * brush.fill('#FF0000', 90); // Set fill color to red and opacity to 90\n * brush.fillBleed(0.3); // Set bleed effect for a watercolor-like appearance\n * brush.rect(100, 100, 50, 50); // Fill a rectangle with the bleed effect\n *\n * @license\n * MIT License\n *\n * Copyright (c) 2023-2026 Alejandro Campos Uribe\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\n * all 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\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n// Randomness and other auxiliary functions\nexport { weightedRand as wRand } from \"./core/utils.js\";\n\n// Color Blending\nexport { load, instance } from \"./core/color.js\";\n\n// Matrix transformations, FlowField and Position Class\nexport {\n field,\n noField,\n addField,\n refreshField,\n listFields,\n Position,\n wiggle,\n} from \"./core/flowfield.js\";\n\n// Polygon and Plot classes\nexport { Polygon } from \"./core/polygon.js\";\nexport { Plot } from \"./core/plot.js\";\n\n// Primitives\nexport {\n rect,\n circle,\n arc,\n beginShape,\n vertex,\n endShape,\n beginStroke,\n move,\n endStroke,\n spline,\n polygon,\n} from \"./core/primitives.js\";\n\n// Brushes\nexport {\n add,\n box,\n scaleBrushes,\n pick,\n stroke,\n strokeWeight,\n set,\n noStroke,\n clip,\n noClip,\n line,\n flowLine,\n} from \"./stroke/stroke.js\";\n\n// Section: Hatching\nexport {\n hatch,\n hatchStyle,\n noHatch,\n createHatch as hatchArray,\n} from \"./hatch/hatch.js\";\n\n// Fill\nexport { fill, noFill, fillTexture, fillBleed } from \"./fill/fill.js\";\n\n// p5 addon registration\nimport {\n Mix,\n instance as bindInstance,\n activateInstance,\n deactivateInstance,\n} from \"./core/color.js\";\nimport { push as brushPush, pop as brushPop } from \"./core/save.js\";\nimport { seed as brushSeed, noiseSeed as brushNoiseSeed } from \"./core/utils.js\";\n\nfunction registerAddon(_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 Mix.blend(false, true);\n deactivateInstance();\n };\n\n lifecycles.postdraw = function () {\n bindInstance(this);\n Mix.blend(false, true);\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\nif (typeof p5 !== \"undefined\") p5.registerAddon(registerAddon);\n"],"names":["Cwidth","Cheight","Instance","Renderer","Density","FillMaskUploadCanvas","ReadySketch","ActiveInstance","ActiveInstanceStack","isFramebufferTarget","target","begin","end","renderer","_pInst","isFiniteSize","value","Number","isFinite","safeRead","getter","_error","isReadyWebGLSketch","candidate","pixelDensity","createFramebuffer","width","height","webglVersion","rememberReadySketch","getSketchRenderer","window","self","p5","instance","getActiveFramebuffer","_renderer","activeFramebuffer","clearTarget","draw","clear","ctx","drawingContext","save","setTransform","clearRect","restore","getTargetPixelSize","Math","max","round","normalizeDirtyRect","rect","minX","floor","min","maxX","minY","maxY","ceil","getFullDirtyRect","toScissorBox","flipY","normalized","x","y","withScissor","gl","box","enable","SCISSOR_TEST","scissor","disable","load","buffer","sketchRenderer","Error","owner","resolveTarget","_isReady","loaded","Mix","isCanvasReady","State","inst","activateInstance","push","deactivateInstance","pop","isMixReady","isBlending","cachedColor","Object","markDirtyRect","a","b","dirtyRect","isDrawn","clearMask","getCompositeRect","isBrushMask","padding","expandDirtyRect","maskWidth","maskHeight","needsBuffers","mask","glMask","needsBlendSourceFramebuffer","blendSourceFramebuffer","needsFillMaskFramebuffer","fillMaskFramebuffer","remove","OffscreenCanvas","getContext","density","antialias","depth","stencil","shaderProgram","createShader","this","imageSmoothingEnabled","blend","_color","_isLast","isBrush","otherMask","nextColor","_array","colorChanged","justChanged","applyShader","shader","source","blitToBlendSourceFramebuffer","targetIsFramebuffer","hadDepthTest","getParameter","DEPTH_TEST","translate","setUniform","uploadRect","uploadWidth","uploadHeight","uploadContext","drawImage","bindTexture","TEXTURE_2D","colorTexture","texSubImage2D","RGBA","UNSIGNED_BYTE","uploadFillMaskToMirror","fill","noStroke","resetShader","sourceTarget","sourceFramebuffer","sourceIsFramebuffer","sourceBox","previousReadFramebuffer","READ_FRAMEBUFFER_BINDING","previousDrawFramebuffer","DRAW_FRAMEBUFFER_BINDING","flushDraw","imageMode","CENTER","image","bindFramebuffer","READ_FRAMEBUFFER","DRAW_FRAMEBUFFER","framebuffer","clearColor","COLOR_BUFFER_BIT","blitFramebuffer","NEAREST","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","c","s0","s1","s2","copy","f","rng","rng2","_seedCallbacks","_onSeed","cb","noise","noise2","rr","e","rr2","rArray","array","randInt","randInt2","gaussian","mean","stdev","u","log","cos","weightedRand","weights","totalWeight","entries","key","cumulative","rnd","isNaN","parseInt","d","withinBounds","constrain","low","high","nAngle","angle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","NaN","sLookup","idx","sin","toDegrees","rad","isRad","angleMode","RADIANS","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","Matrix","uModelMatrix","mat4","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","update","plotted","colIdx","getColIndex","rowIdx","getRowIndex","reset","isIn","isActive","isInCanvas","list","get","current","wiggle","moveTo","_dir","_length","_step_length","movePos","_moveToDegrees","plotTo","_plot","_scale","_dirPlot","_step","scaleFactor","y_offset","x_offset","col","row","Map","FIELD_ANGLE_MODES","Set","normalizeFieldAngleMode","options","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","intersection","show","stroke","hatch","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","scale","_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","radius","halfDist","arcLength","asin","origin","createProgram","frag","src","VERTEX_SHADER","FRAGMENT_SHADER","shaderSource","compileShader","attachShader","linkProgram","framebufferProjMatrix","vao","buf","program","loadedWidth","loadedHeight","brushMaskTarget","prevMaskTarget","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","resetMaskShaderTracking","_curShader","_cachedBlendMode","_isBlending","activeTexture","TEXTURE0","blendEquation","FUNC_ADD","blendFunc","ONE","ONE_MINUS_SRC_ALPHA","getProjectionMatrix","beginMaskTarget","isEnabled","_hadDepthTest","_beforeEnd","FRAMEBUFFER","_framebufferToBind","viewport","endMaskTarget","_beforeBegin","_origViewport","_applyStencilTestIfClipping","accumulateDirtyRect","currentRect","circle","diameter","alpha","newData","px","py","screenX","screenY","dScreenX","dScreenY","glDrawImages","p5img","tex","createTexture","texImage2D","canvas","texParameteri","TEXTURE_MIN_FILTER","LINEAR","TEXTURE_MAG_FILTER","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","useProgram","BLEND","ONE_MINUS_DST_ALPHA","uniform1i","u_tex","color","uniform4f","u_color","uniformMatrix4fv","u_proj","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","drawArraysInstanced","TRIANGLE_STRIP","flush","weight","clipWindow","opacity","_strokeTransform","tx","ty","getBrushFactory","DEFAULT_CUSTOM_PRESSURE_VARIATION","warp","tilt","BrushState","BrushSetState","state","add","params","includes","undefined","markerTip","vibration","scatter","definition","sharpness","quality","grain","min_max","curve","variation","isArray","mode","rest","m","range","ns","nm","ne","normalizePressure","tip","deleteTexture","delete","invalidateTexEntry","g","createGraphics","background","noSmooth","T","imageToWhite","tips","tipKey","param","colors","buffers","pick","brushName","arguments","strokeWeight","snapshotTransform","normalizeRegion","region","_position","initializeDrawingState","plot","gaussians","angleScale","isPlot","cp","ct","cs","ck","noiseoffset","dirRad","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","cw2","ch2","inverse","I","bounds","B","ca","cc","cd","clipA","clipB","clipC","clipD","clipTX","clipTY","clipMinX","clipMaxX","clipMinY","clipMaxY","o","getImageTipOverscan","saveState","stepSize","spacing","totalSteps","u_matrix","drawArrays","POINTS","glDraw","restoreState","isInsideClippingArea","calculatePressure","lineNoise","sw","iterations","rX","yRandomFactor","sqrtPart","drawSpray","drawMarker","drawImageTip","perp","along","drawDefault","simPressure","peakPos","halfWidth","pow","gauss","lx","ly","maxPressure","scatterReach","tipReach","vibrate","rx","ry","size","overscan","extraPadding","halfSize","extraRadius","base","boundsRadius","stampImage","_vals","_standard_brushes","obj","prototype","_brush","_weight","loadPixels","average","pixels","updatePixels","filter","k","Promise","all","resolve","reject","nativeImg","Image","onload","createImage","naturalWidth","naturalHeight","onerror","crossOrigin","HatchState","rand","continuous","gradient","scanlineHatch","polygon","cosA","sinA","cosB","sinB","verts","rotated","Infinity","edges","eLen","Y","sort","createHatch","polygons","hBrush","values","segs","poly","arc","_dist","_angle","_options","HatchSetState","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","_polygon","_gaussians","_fillGaussianPools","_isLeft","FillPoly","center","isFirst","sx","sy","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","growCap","kept","intensity","texture","int","switchingToFill","strokeStyle","_getRed","_getGreen","_getBlue","lineCap","darker","sparse","pols","layer","numLayers","erase","lineWidth","fillStyle","matrix","getTransform","beginPath","first","lineTo","closePath","strokePadding","drawPolygon","numCircles","halfSizeX","halfSizeY","minSize","minSizeFactor","maxSizeFactor","midX","midY","globalCompositeOperation","_opacity","_bleed","fluid","strength","modifiers","_","shift","shifted","slice","pts","point","area","cross","_center","createFill","FillSetState","_stateStack","registerAddon","_p5","lifecycles","presetup","predraw","postsetup","bindInstance","postdraw","_push","_pop","_randomSeed","randomSeed","_noiseSeed","noiseSeed","call","saved","brushPop","callback","brushSeed","brushNoiseSeed","startDeg","sweepDeg","segmentCount","segmentSweep","startX","startY","angleOffset","randomFactor","randomAngle","offsetX","offsetY","transform","det","invertTransform","brush","currentField","_array_points"],"mappings":"6BAYO,IAAIA,EAAQC,EAASC,EAAUC,EAAUC,EAE5CC,EAAuB,KACvBC,EAAc,KACdC,EAAiB,KACrB,MAAMC,EAAsB,GAWtBC,EAAuBC,KACzBA,GACsB,mBAAjBA,EAAOC,OACQ,mBAAfD,EAAOE,OACZF,EAAOG,YACPH,EAAOG,SAASC,OAEdC,EAAgBC,GACH,iBAAVA,GAAsBC,OAAOC,SAASF,IAAUA,EAAQ,EAE3DG,EAAYC,IAChB,IACE,OAAOA,GACT,CAAE,MAAOC,GACP,MACF,GAGIC,EAAsBC,KACxBA,GACgC,mBAA3BA,EAAUC,cACsB,mBAAhCD,EAAUE,mBACjBV,EAAaI,EAAS,IAAMI,EAAUG,SACtCX,EAAaI,EAAS,IAAMI,EAAUI,UACK,WAA3CR,EAAS,IAAMI,EAAUK,cAIrBC,EAAuBN,IACvBD,EAAmBC,KAAYjB,EAAciB,GAC1CjB,GAiBHwB,EAAoB,KAbnBvB,GACAe,EAAmBf,GACjBsB,EAAoBtB,GAFC,OAe5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AAejnB,GAAKC,IAAI9R,EAAM0P,MAAMqC,SAC1C+mB,EAAappB,MAAQ6D,GAAculB,EAActxB,EACnD,iBMzCO,SAAsBoL,GAC3B,IAAK,MAAMoR,MAAEA,KAAWnS,GAAK8b,SACvB3J,IACFA,EAAMhD,QAAUpO,EAChBoR,EAAM7B,SAAWvP,EACjBoR,EAAMqE,SAAWzV,EAGvB,oBHMO,SAAgBmmB,EAAe1hB,EAAa,IACjD,IAAK0hB,GAAiBA,EAActvB,OAAS,EAC3C,MAAM,IAAIhK,MACR,+EAGIoY,GAAckhB,EAAe1hB,GACnCja,MACJ,+DHoFO,SAAgBuD,EAAI,GACzB+O,GAAM,QACN1P,EAAM0P,MAAMsC,OAASrR,CACvB","x_google_ignoreList":[1,2]}\ No newline at end of file+{"version":3,"file":"p5.brush.js","sources":["../src/core/target.js","../node_modules/simplex-noise/dist/esm/simplex-noise.js","../node_modules/esm-seedrandom/esm/index.mjs","../src/core/utils.js","../src/core/dirty_rect.js","../src/core/color.js","../src/core/flowfield.js","../src/core/polygon.js","../src/core/plot.js","../src/core/primitives.js","../src/stroke/composite.js","../src/core/gl/utils.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/core/save.js","../src/index.js"],"sourcesContent":["// =============================================================================\n// Module: Target Resolution and Runtime Context\n// =============================================================================\n/**\n * Owns the active renderer/instance selection used by p5.brush.\n */\n\nexport let Cwidth, Cheight, Instance, Renderer, Density;\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 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 Cwidth = target.width;\n Cheight = target.height;\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 Density = Renderer.pixelDensity();\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 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","/*\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 { Renderer } from \"./target.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 const usesRadians =\n isRad ||\n (Renderer &&\n typeof Renderer.angleMode === \"function\" &&\n Renderer.angleMode() === Renderer.RADIANS);\n // Only if Renderer.angleMode() is set to radians\n if (usesRadians) {\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 ||\n (Renderer &&\n typeof Renderer.angleMode === \"function\" &&\n Renderer.angleMode() === Renderer.RADIANS)\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// 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","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\";\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 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\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 WEBGL 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 if (!Renderer.loaded) {\n Renderer.loaded = true;\n Renderer.shaderProgram ??= Renderer.createShader(vertSrc, fragSrc);\n }\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 if (Renderer.blendSourceFramebuffer?.remove) {\n Renderer.blendSourceFramebuffer.remove();\n }\n Renderer.blendSourceFramebuffer = Renderer.createFramebuffer({\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\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 WEBGL 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 = blitToBlendSourceFramebuffer(activeFramebuffer ?? Renderer, dirtyRect);\n const targetIsFramebuffer = !!activeFramebuffer;\n const hadDepthTest = gl.getParameter(gl.DEPTH_TEST);\n\n // This pass is a fullscreen compositing rect, not scene geometry, so it\n // should not participate in the sketch's depth buffer.\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 const composite = isBrushMask ? strokeComposite : fillComposite;\n shader.setUniform(\n \"u_mask\",\n composite.getShaderMask(\n Renderer,\n mask,\n dirtyRect,\n normalizeDirtyRect,\n getFullDirtyRect,\n clearTarget,\n ),\n );\n shader.setUniform(\"u_color\", this.cachedColor);\n\n withScissor(gl, dirtyRect, () => {\n Renderer.fill(0, 0, 0, 0);\n Renderer.noStroke();\n Renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);\n }, !targetIsFramebuffer);\n\n Renderer.pop();\n Renderer.resetShader();\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\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 {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional offscreen target.\n */\nexport const load = (buffer = false) => {\n loadTarget(buffer);\n if (Renderer.loaded) Mix.load();\n};\n\n/**\n * Copies the current pixels of a renderer or framebuffer into the reusable\n * blend source framebuffer.\n * @param {p5|p5.Graphics|p5.Framebuffer} sourceTarget - Source to copy from.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} [dirtyRect=null] - Optional copy region.\n * @returns {p5.Framebuffer} Blend source framebuffer after the blit.\n */\nconst blitToBlendSourceFramebuffer = (sourceTarget, dirtyRect = null) => {\n const sourceFramebuffer = Renderer.blendSourceFramebuffer;\n const gl = Renderer.drawingContext;\n const sourceIsFramebuffer = isFramebufferTarget(sourceTarget);\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 (sourceIsFramebuffer ? sourceTarget.renderer : Renderer._renderer)?.flushDraw?.();\n\n if (sourceIsFramebuffer) {\n sourceFramebuffer.draw(() => {\n withScissor(Renderer.drawingContext, dirtyRect, () => {\n Renderer.clear();\n Renderer.push();\n Renderer.imageMode(Renderer.CENTER);\n Renderer.image(sourceTarget, 0, 0, Cwidth, Cheight);\n Renderer.pop();\n }, false);\n });\n return sourceFramebuffer;\n }\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","import { Cwidth, Cheight, Renderer } from \"./target.js\";\nimport { isMixReady, State } from \"./color.js\";\nimport { randInt2, noise2, rr2, sin, cos, map, toDegreesSigned } from \"./utils.js\";\n\n// =============================================================================\n// Section: Matrix transformations\n// =============================================================================\n\n/**\n * The `Matrix` object exposes the current 2D affine transform from p5's model matrix.\n * mat4 layout (column-major 4x4):\n * [0]=a [1]=b [4]=c [5]=d [12]=tx [13]=ty\n * where the 2D transform of a point (x,y) is: (a*x + c*y + tx, b*x + d*y + ty)\n */\nexport const Matrix = {\n x: () => Renderer._renderer.uModelMatrix.mat4[12],\n y: () => Renderer._renderer.uModelMatrix.mat4[13],\n a: () => Renderer._renderer.uModelMatrix.mat4[0],\n b: () => Renderer._renderer.uModelMatrix.mat4[1],\n c: () => Renderer._renderer.uModelMatrix.mat4[4],\n d: () => Renderer._renderer.uModelMatrix.mat4[5],\n};\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 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 = Position.getColIndex(x);\n this.rowIdx = Position.getRowIndex(y);\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 + Matrix.x();\n const y = this.y + Matrix.y();\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 p5 angle mode.\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 + Matrix.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 + Matrix.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 p5 angle mode.\n * @param {number} end - End angle in the current p5 angle mode.\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 * as Color from \"../core/color.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 p5 renderer/sketch.\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 p5 renderer/sketch.\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 = Renderer.createFramebuffer({\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 p5 renderer/sketch.\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// 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 { Matrix } from \"../core/flowfield.js\";\nimport { createProgram } from \"../core/gl/utils.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;\nlet prevMaskTarget = 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 p5 model matrix. Call once at the start of each stroke.\n */\nexport function snapshotMatrix() {\n _ma = Matrix.a();\n _mb = Matrix.b();\n _mc = Matrix.c();\n _md = Matrix.d();\n _mx = Matrix.x();\n _my = Matrix.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 resetMaskShaderTracking() {\n const renderer = Mix.glMask?.renderer;\n if (!renderer) return;\n renderer._curShader = null;\n renderer._cachedBlendMode = null;\n renderer._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\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 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 const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n beginMaskTarget._hadDepthTest = hadDepthTest;\n if (hadDepthTest) gl.disable(gl.DEPTH_TEST);\n prevMaskTarget = Renderer._renderer.activeFramebuffer?.() ?? null;\n if (prevMaskTarget?._beforeEnd) prevMaskTarget._beforeEnd();\n gl.bindFramebuffer(gl.FRAMEBUFFER, getFramebufferHandle(Mix.glMask));\n gl.viewport(\n 0,\n 0,\n Mix.glMask.width * Mix.glMask.density,\n Mix.glMask.height * Mix.glMask.density,\n );\n}\n\nfunction endMaskTarget() {\n if (beginMaskTarget._hadDepthTest) gl.enable(gl.DEPTH_TEST);\n beginMaskTarget._hadDepthTest = false;\n if (prevMaskTarget?._beforeBegin) {\n prevMaskTarget._beforeBegin();\n } else {\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 prevMaskTarget = null;\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 * p5's current model matrix 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 {p5.Image} p5img - The preprocessed brush-tip image (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 beginMaskTarget();\n\n // Lazy-create the WebGL texture from the p5.Image 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();\n\n if (imgDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, imgDirtyRect);\n imgDirtyRect = null;\n }\n\n imgCount = 0;\n\n // Let p5 know we changed the active program\n resetMaskShaderTracking();\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 beginMaskTarget();\n\n const color = State.stroke.color._array;\n\n // Re-activate our shader (p5 drawing may have 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();\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 p5's _curShader tracking.\n // Reset it to null so p5 is forced to re-activate its own shader next time\n // it draws — otherwise p5 skips gl.useProgram() and sets uniforms on the\n // wrong active program, causing \"location is not from the associated program\".\n resetMaskShaderTracking();\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, Instance, 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 { Position, isFieldReady } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.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; ensures p5's WebGL mode is patched to support offscreen stroke 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\nfunction getBrushFactory() {\n return Renderer ?? Instance ?? window.self.p5.instance;\n}\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 factory = getBrushFactory();\n const g = factory.createGraphics(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 = Renderer.color(...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 p5 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 p5 angle mode.\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 p5.js graphics library.\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 p5.Image 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 new Promise((resolve, reject) => {\n const nativeImg = new window.Image();\n nativeImg.onload = () => {\n const factory = getBrushFactory();\n const p5img = factory.createImage(\n nativeImg.naturalWidth,\n nativeImg.naturalHeight,\n );\n p5img.drawingContext.drawImage(nativeImg, 0, 0);\n T.imageToWhite(p5img);\n this.tips.set(src, p5img);\n resolve();\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 );\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 p5 angle mode.\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|p5.Color} [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 let Y = minY + dist * 0.5,\n step = dist;\n while (Y < maxY) {\n const cx = [];\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 { Renderer } from \"../core/target.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 { 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 p5 angle mode units.\n * @param {number} angle\n * @returns {number}\n */\nfunction degreesToCurrentAngleMode(angle) {\n return Renderer &&\n typeof Renderer.angleMode === \"function\" &&\n Renderer.angleMode() === Renderer.RADIANS\n ? (angle * Math.PI) / 180\n : 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 p5 angle mode.\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) {\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 degreesToCurrentAngleMode(startDeg),\n degreesToCurrentAngleMode(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) {\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 );\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) {\n hatch(dist, angle, options);\n drawMassArcs(polygon, pivotBias);\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\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 degreesToCurrentAngleMode(baseAngle),\n {\n gradient,\n rand: 2 - 2 * precision,\n continuous: true,\n },\n pivotBias,\n );\n\n if (strength > 0.33) {\n drawMassPass(\n pols[1],\n hatchDist,\n degreesToCurrentAngleMode(baseAngle + 20 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n );\n }\n\n if (strength > 0.66) {\n drawMassPass(\n pols[2],\n hatchDist * 0.8,\n degreesToCurrentAngleMode(baseAngle + 15 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\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\";\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 p5 renderer/sketch.\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 p5 renderer/sketch.\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 p5 renderer/sketch.\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 = new OffscreenCanvas(maskWidth, maskHeight);\n Renderer.mask.drawingContext = Renderer.mask.getContext(\"2d\");\n }\n\n if (needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.fillMaskFramebuffer?.remove) {\n Renderer.fillMaskFramebuffer.remove();\n }\n Renderer.fillMaskFramebuffer = Renderer.createFramebuffer({\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\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 p5 renderer/sketch.\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 = new OffscreenCanvas(uploadWidth, uploadHeight);\n FillMaskUploadCanvas.drawingContext = FillMaskUploadCanvas.getContext(\"2d\");\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\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, Matrix } from \"../core/flowfield.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;\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 =\n arguments.length < 3 ? Renderer.color(a) : Renderer.color(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 const insertedX = new Array(len);\n const insertedY = new Array(len);\n const newMods = new Array(outLen);\n const newDirs = new Array(outLen);\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 const growCap = GROW_MAX_VERTS * Math.max(0.1, 2 * State.fill.bleed_strength);\n if (growCap && idx > growCap) {\n const step = Math.ceil(idx / growCap);\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 newMods.length = idx;\n newDirs.length = idx;\n fm = newMods;\n fd = newDirs;\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 Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * Matrix.a(),\n Density * Matrix.b(),\n Density * Matrix.c(),\n Density * Matrix.d(),\n Density * (Matrix.x() + Cwidth / 2),\n Density * (Matrix.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 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 { Matrix } from \"../core/flowfield.js\";\nimport { createProgram } from \"../core/gl/utils.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 =\n arguments.length < 3 ? Renderer.color(a) : Renderer.color(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 * Resets p5's cached shader/blend bookkeeping after direct WebGL calls.\n */\nfunction resetWashShaderTracking() {\n const renderer = Renderer?._renderer;\n if (!renderer) return;\n renderer._curShader = null;\n renderer._cachedBlendMode = null;\n renderer._isBlending = null;\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 p5.brush transform matrix 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 p5.brush space.\n * @param {number} y - The source y-coordinate in p5.brush space.\n * @returns {[number, number]} The transformed screen-space position.\n */\nfunction transformVertexToScreen(x, y) {\n return [\n Matrix.a() * x + Matrix.c() * y + Matrix.x() + loadedWidth / 2,\n Matrix.b() * x + Matrix.d() * y + Matrix.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 WEBGL 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 resetWashShaderTracking();\n}\n\n// =============================================================================\n// Prototype methods\n// =============================================================================\n\n/**\n * Applies a direct WEBGL 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","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.brush - A comprehensive toolset for brush management in p5.js.\n * @license MIT\n * @author Alejandro Campos Uribe\n *\n * @description\n * p5.brush is a p5.js library dedicated to the creation and management of custom brushes.\n * It extends the drawing capabilities of p5.js by allowing users to simulate a wide range\n * of brush strokes, vector fields, hatching patterns, and fill textures. These features\n * are essential for emulating the nuanced effects found in traditional sketching and painting.\n * Whether for digital art applications or procedural generation of graphics, p5.brush provides\n * a robust framework for artists and developers to create rich, dynamic, and textured visuals.\n *\n * @example\n * // Basic usage:\n * brush.pick('marker'); // Select brush type\n * brush.stroke(255, 0, 0); // Set brush color\n * brush.strokeWeight(10); // Set brush size\n * brush.line(25, 25, 75, 75); // Draw a line\n *\n * // Add a new brush type:\n * brush.add('customBrush', { /* parameters for the brush *\\/ });\n * brush.pick('customBrush');\n *\n * // Use the custom brush for a vector-field line:\n * brush.field('field_name') // Pick a flowfield\n * brush.flowLine(50, 50, 100, PI / 4); // Draw a line within the vector-field; angle follows p5 angleMode()\n *\n * // Fill textures:\n * brush.noStroke();\n * brush.fill('#FF0000', 90); // Set fill color to red and opacity to 90\n * brush.fillBleed(0.3); // Set bleed effect for a watercolor-like appearance\n * brush.rect(100, 100, 50, 50); // Fill a rectangle with the bleed effect\n *\n * @license\n * MIT License\n *\n * Copyright (c) 2023-2026 Alejandro Campos Uribe\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\n * all 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\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n// Randomness and other auxiliary functions\nexport { weightedRand as wRand } from \"./core/utils.js\";\n\n// Color Blending\nexport { load } from \"./core/color.js\";\nexport { instance } from \"./core/target.js\";\n\n// Matrix transformations, FlowField and Position Class\nexport {\n field,\n noField,\n addField,\n refreshField,\n listFields,\n Position,\n wiggle,\n} from \"./core/flowfield.js\";\n\n// Polygon and Plot classes\nexport { Polygon } from \"./core/polygon.js\";\nexport { Plot } from \"./core/plot.js\";\n\n// Primitives\nexport {\n rect,\n circle,\n arc,\n beginShape,\n vertex,\n endShape,\n beginStroke,\n move,\n endStroke,\n spline,\n polygon,\n} from \"./core/primitives.js\";\n\n// Brushes\nexport {\n add,\n box,\n scaleBrushes,\n pick,\n stroke,\n strokeWeight,\n set,\n noStroke,\n clip,\n noClip,\n line,\n flowLine,\n} from \"./stroke/stroke.js\";\n\n// Section: Hatching\nexport {\n hatch,\n hatchStyle,\n noHatch,\n createHatch as hatchArray,\n} from \"./hatch/hatch.js\";\nexport { \n mass, \n noMass \n} from \"./hatch/mass.js\";\n\n// Fill\nexport { fill, noFill, fillTexture, fillBleed } from \"./fill/fill.js\";\nexport { wash, noWash } from \"./fill/wash.js\";\n\n// p5 addon registration\nimport {\n Mix, \n flushActiveComposite,\n} 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\nfunction registerAddon(_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\nif (typeof p5 !== \"undefined\") p5.registerAddon(registerAddon);\n"],"names":["Cwidth","Cheight","Instance","Renderer","Density","ReadySketch","ActiveInstance","ActiveInstanceStack","_isReady","isFramebufferTarget","target","begin","end","renderer","_pInst","isFiniteSize","value","Number","isFinite","safeRead","getter","_error","isReadyWebGLSketch","candidate","pixelDensity","createFramebuffer","width","height","webglVersion","rememberReadySketch","getSketchRenderer","window","self","p5","instance","getActiveFramebuffer","_renderer","activeFramebuffer","load","buffer","sketchRenderer","Error","owner","resolveTarget","isCanvasReady","inst","activateInstance","push","deactivateInstance","pop","SQRT3","Math","sqrt","F2","G2","fastFloor","x","floor","grad2","Float64Array","createNoise2D","random","perm","p","Uint8Array","i","tableSize","r","aux","buildPermutationTable","permGrad2x","map","v","permGrad2y","y","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","c","s0","s1","s2","copy","f","rng","rng2","_seedCallbacks","_onSeed","cb","noise","noise2","rr","e","rr2","rArray","array","randInt","randInt2","gaussian","mean","stdev","u","log","cos","weightedRand","weights","totalWeight","entries","key","cumulative","rnd","isNaN","parseInt","a","b","d","withinBounds","constrain","low","high","max","min","nAngle","angle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","fill","NaN","sLookup","idx","sin","toDegrees","rad","isRad","angleMode","RADIANS","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","expandDirtyRect","rect","padding","minX","minY","maxX","maxY","strokeComposite","fillComposite","clearTarget","draw","clear","ctx","drawingContext","save","setTransform","clearRect","restore","getTargetPixelSize","round","normalizeDirtyRect","ceil","clampDirtyRect","getFullDirtyRect","getFullRect","toScissorBox","flipY","normalized","withScissor","gl","box","enable","SCISSOR_TEST","scissor","disable","State","isMixReady","loaded","Mix","isBlending","cachedColor","markDirtyRect","dirtyRect","isDrawn","clearMask","composite","glMask","getCompositeRect","isBrushMask","needsBlendSourceFramebuffer","blendSourceFramebuffer","shaderProgram","createShader","ensureResources","fillResources","mask","remove","density","antialias","depth","stencil","blend","_color","_isLast","isBrush","otherMask","nextColor","_array","colorChanged","justChanged","applyShader","shader","source","blitToBlendSourceFramebuffer","targetIsFramebuffer","hadDepthTest","getParameter","DEPTH_TEST","translate","setUniform","getShaderMask","noStroke","resetShader","flushActiveComposite","sourceTarget","sourceFramebuffer","sourceIsFramebuffer","sourceBox","previousReadFramebuffer","READ_FRAMEBUFFER_BINDING","previousDrawFramebuffer","DRAW_FRAMEBUFFER_BINDING","flushDraw","imageMode","CENTER","image","bindFramebuffer","READ_FRAMEBUFFER","DRAW_FRAMEBUFFER","framebuffer","clearColor","COLOR_BUFFER_BIT","blitFramebuffer","NEAREST","Matrix","uModelMatrix","mat4","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","update","plotted","colIdx","getColIndex","rowIdx","getRowIndex","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","y_offset","x_offset","col","row","Map","FIELD_ANGLE_MODES","Set","normalizeFieldAngleMode","options","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","intersection","show","wash","mass","hatch","stroke","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","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","isStrokeCompositeRegistered","createProgram","frag","src","VERTEX_SHADER","FRAGMENT_SHADER","shaderSource","compileShader","attachShader","linkProgram","framebufferProjMatrix","vao","buf","program","loadedWidth","loadedHeight","brushMaskTarget","prevMaskTarget","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","resetMaskShaderTracking","_curShader","_cachedBlendMode","_isBlending","activeTexture","TEXTURE0","bindTexture","TEXTURE_2D","blendEquation","FUNC_ADD","blendFunc","ONE","ONE_MINUS_SRC_ALPHA","getProjectionMatrix","beginMaskTarget","isEnabled","_hadDepthTest","_beforeEnd","FRAMEBUFFER","_framebufferToBind","viewport","endMaskTarget","_beforeBegin","_origViewport","_applyStencilTestIfClipping","accumulateDirtyRect","currentRect","circle","diameter","alpha","newData","px","py","screenX","screenY","dScreenX","dScreenY","glDrawImages","p5img","tex","createTexture","texImage2D","RGBA","UNSIGNED_BYTE","canvas","texParameteri","TEXTURE_MIN_FILTER","LINEAR","TEXTURE_MAG_FILTER","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","useProgram","BLEND","ONE_MINUS_DST_ALPHA","uniform1i","u_tex","color","uniform4f","u_color","uniformMatrix4fv","u_proj","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","drawArraysInstanced","TRIANGLE_STRIP","flush","needsStrokeMask","_Renderer","weight","opacity","getBrushFactory","DEFAULT_CUSTOM_PRESSURE_VARIATION","warp","tilt","BrushState","BrushSetState","state","add","params","includes","undefined","markerTip","vibration","scatter","definition","sharpness","quality","grain","min_max","curve","variation","isArray","mode","rest","m","range","ns","nm","ne","normalizePressure","tip","deleteTexture","delete","invalidateTexEntry","g","createGraphics","background","noSmooth","T","imageToWhite","tips","tipKey","param","colors","buffers","getBrushParams","brushName","pick","arguments","strokeWeight","_position","initializeDrawingState","plot","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","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","resolve","reject","nativeImg","Image","onload","createImage","naturalWidth","naturalHeight","drawImage","onerror","crossOrigin","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","hBrush","Object","values","drawFn","withHatchStyle","renderHatchSegments","jitterPolygon","jitterX","jitterY","degreesToCurrentAngleMode","projectAnchorToBisector","anchor","mx","my","nx","ny","getShortArcAngles","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","OffscreenCanvas","getContext","fillMaskFramebuffer","needsFillMaskFramebuffer","imageSmoothingEnabled","_getActiveFramebuffer","uploadRect","uploadWidth","uploadHeight","uploadContext","colorTexture","texSubImage2D","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","growCap","kept","intensity","texture","int","switchingToFill","strokeStyle","_getRed","_getGreen","_getBlue","lineCap","darker","sparse","layer","numLayers","erase","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","slice","pts","point","cross","_center","createFill","FillSetState","washProgram","washVao","washBuffer","washProjection","washGpuBufferSize","WashAttr","WashUniform","transformVertexToScreen","ensureWashReady","vertexCount","flat","holeIndices","outerLen","outerNode","signedArea","linkedList","earcut","buildTriangleBuffer","TRIANGLES","resetWashShaderTracking","drawWashPolygon","_stateStack","registerAddon","_p5","lifecycles","presetup","predraw","postsetup","bindInstance","postdraw","_push","_pop","_randomSeed","randomSeed","_noiseSeed","noiseSeed","call","saved","brushPop","callback","brushSeed","brushNoiseSeed","angleOffset","randomFactor","randomAngle","offsetX","offsetY","region","loadTarget","currentField","_array_points"],"mappings":"6BAOO,IAAIA,EAAQC,EAASC,EAAUC,EAAUC,EAE5CC,EAAc,KACdC,EAAiB,KACrB,MAAMC,EAAsB,GAC5B,IAAIC,GAAW,EAOR,MAAMC,EAAuBC,KAChCA,GACsB,mBAAjBA,EAAOC,OACQ,mBAAfD,EAAOE,OACZF,EAAOG,YACPH,EAAOG,SAASC,OAEdC,EAAgBC,GACH,iBAAVA,GAAsBC,OAAOC,SAASF,IAAUA,EAAQ,EAE3DG,EAAYC,IAChB,IACE,OAAOA,GACT,CAAE,MAAOC,GACP,MACF,GAGIC,EAAsBC,KACxBA,GACgC,mBAA3BA,EAAUC,cACsB,mBAAhCD,EAAUE,mBACjBV,EAAaI,EAAS,IAAMI,EAAUG,SACtCX,EAAaI,EAAS,IAAMI,EAAUI,UACK,WAA3CR,EAAS,IAAMI,EAAUK,cAIrBC,EAAuBN,IACvBD,EAAmBC,KAAYlB,EAAckB,GAC1ClB,GAiBIyB,EAAoB,KAb1BxB,GACAgB,EAAmBhB,GACjBuB,EAAoBvB,GAFC,OAe5BuB,EAvBiCE,OAAOC,MAAMC,IAAIC,UAAY,OAwB9DL,EAAoB3B,IACpBG,EAmDW8B,EAAu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nCnP,MACJ","x_google_ignoreList":[1,2,19]}\ No newline at end of filediff --git a/llms.txt b/llms.txtindex 53b33eb..7416b8c 100644--- a/llms.txt+++ b/llms.txt@@ -22,7 +22,7 @@ The canvas **must use WEBGL mode**. The library initializes automatically when `async function setup() {createCanvas(600, 600, WEBGL)angleMode(DEGREES) // optional, but all angle-taking brush APIs follow p5's angleMode- brush.scaleBrushes(1.5) // optional: scale all default brushes+ brush.scaleBrushes(3) // usually necessary: good starting point for a 600x600 canvas, then confirm visually}```@@ -55,7 +55,7 @@ Exception: `brush.addField(name, fn, { angleMode })` lets custom field generator### Configuration- `brush.load(buffer?)` — Use this when targeting a **secondary** canvas. Pass a `p5.Graphics` buffer or an active `p5.Framebuffer` to redirect brush drawing there. Call `brush.load()` with no args to return to the main canvas. For `p5.Graphics`, create the buffer in `WEBGL`, call `brush.load(pg)`, draw, then call `brush.load()` again before presenting it with `image(pg, ...)`. For framebuffers, call `brush.load(framebuffer)` only while that framebuffer is active inside `begin()` / `end()` or `draw()`, then call `brush.load()` again after leaving that scope. `brush.load(...)` only changes p5.brush's target; native p5 drawing calls still need to be directed at the same target explicitly. Framebuffers created from `p5.Graphics` are not supported.-- `brush.scaleBrushes(scale)` — Scale all currently registered brushes by `scale`. Call once in setup; if you only want the built-ins scaled, call it before adding custom brushes.+- `brush.scaleBrushes(scale)` — Scale all currently registered brushes by `scale`. In practice this is usually necessary to adapt brushes to the canvas size, not just optional polish. For a `600x600` canvas, `brush.scaleBrushes(3)` is a good starting point, but it should still be confirmed visually. Call once in setup; if you only want the built-ins scaled, call it before adding custom brushes.- `brush.instance(p)` — Use when p5 is in instance mode. Call before setup/draw.- `brush.preload()` — Compatibility helper for preloading image tips. Usually unnecessary in v2 if you `await brush.add(...)` for image brushes.@@ -77,8 +77,11 @@ Fill simulates watercolor — soft edges, bleed, texture layering.- `brush.fill(color, opacity)` or `brush.fill(r, g, b, opacity)` — Set fill color. Opacity uses p5-style alpha values (typically 0–255). Enables fill.- `brush.noFill()` — Disable fill.+- `brush.wash(color, opacity)` — Fast solid fill pass for subsequent shapes. No watercolor bleed or texture simulation.+- `brush.noWash()` — Disable wash.- `brush.fillBleed(strength, direction?)` — Edge bleed amount, 0–1. Direction: `"out"` or `"in"`.- `brush.fillTexture(textureStrength, borderIntensity)` — Texture and border, both 0–1.+- For better fill performance, prefer drawing fills in color batches when possible. Group shapes by fill color/opacities so the library can reuse its internal color-specific caching more effectively.---@@ -89,6 +92,8 @@ Hatching draws parallel lines inside shapes. Activate before drawing a shape, di- `brush.hatch(dist, angle, options?)` — Enable hatching. `dist` = spacing in canvas units, `angle` is interpreted using the current `angleMode()` when `brush.hatch()` is called. Options: `{rand: 0–1, continuous: bool, gradient: 0–1}`.- `brush.noHatch()` — Disable hatching.- `brush.hatchStyle(name, color, weight)` — Set brush used for hatching (independent of stroke brush).+- `brush.mass(brush, color, options?)` — Enable massing: layered hand-filled value built from internal hatch geometry and curved gestures. Options: `{precision: 0–1, strength: 0–1, gradient: 0–1, outline: bool}`.+- `brush.noMass()` — Disable massing.- `brush.hatchArray(polygons)` — Apply current hatch style directly to a `brush.Polygon` or array of polygons.---@@ -141,6 +146,7 @@ brush.endStroke(angle, pressure)- `brush.circle(x, y, radius, r?)` — Circle. `r` = hand-drawn irregularity (0–1). Circles can be stroked, hatched, and filled.- `brush.arc(x, y, radius, start, end)` — Arc. `start` and `end` follow the current `angleMode()`. Stroke only.- `brush.polygon(pointsArray)` — Polygon from `[[x,y], ...]`. Not affected by vector fields.+- Prefer avoiding `brush.polygon(...)` in generated examples when field-following behavior or robust fill behavior matters. It bypasses the field-aware primitive generation used by `rect()`, `circle()`, `beginShape()`, etc., and it can be a poor choice when fills are involved.- `brush.beginShape(curvature?)` / `brush.vertex(x, y, pressure?)` / `brush.endShape(close?)` — Custom shape.---@@ -173,6 +179,7 @@ If an LLM is helping a user design a brush, prefer pointing them to the interact| `image` | `"image"` type: `{ src: "./tip.jpg" }` || `rotate` | `"none"`, `"natural"`, `"random"` || `markerTip` | `"marker"`, `"custom"`, `"image"` only. Boolean. Defaults to `true`. Set `false` to disable the extra soft tip buildup at the start/end of strokes. |+| `noise` | Multiplies subtle line-noise variation along the stroke. Use `0–1`; `0` disables it and `1` keeps the standard amount. |Important `brush.add()` guidance for LLMs:@@ -213,7 +220,9 @@ await brush.add("photo", {let p = new brush.Polygon([[x1,y1],[x2,y2],[x3,y3]])p.draw(brushName, color, weight)p.fill(color, opacity, bleed, texture)+p.wash(color, opacity)p.hatch(distance, angle, options)+p.mass()p.intersect(line) // returns [{x,y}, ...]// Attributes: p.vertices, p.sides```@@ -228,7 +237,9 @@ plot.addSegment(angle, length, pressure)plot.endPlot(angle, pressure)plot.draw(x, y) // draws with current stroke stateplot.fill(x, y) // fills with current fill state+plot.wash(x, y) // washes with current wash stateplot.hatch(x, y) // hatches with current hatch state+plot.mass(x, y) // masses with current mass stateplot.rotate(angle)plot.genPol(x, y) // returns a Polygon```@@ -252,7 +263,7 @@ pos.plotTo(plot, length, stepLength, scale)```jsasync function setup() {createCanvas(600, 600, WEBGL)- brush.scaleBrushes(2)+ brush.scaleBrushes(3)angleMode(DEGREES)background("#fffceb")}diff --git a/package-lock.json b/package-lock.jsonindex fd7837d..d5c9e3a 100644--- a/package-lock.json+++ b/package-lock.json@@ -9,6 +9,7 @@"version": "2.0.3-beta","license": "MIT","dependencies": {+ "earcut": "^3.0.2","esm-seedrandom": "^3.0.5","simplex-noise": "^4.0.3"},@@ -1262,6 +1263,12 @@"stream-shift": "^1.0.0"}},+ "node_modules/earcut": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/earcut/-/earcut-3.0.2.tgz",+ "integrity": "sha512-X7hshQbLyMJ/3RPhyObLARM2sNxxmRALLKx1+NVFFnQ9gKzmCrxm9+uLIAdBcvc8FNLpctqlQ2V6AE92Ol9UDQ==",+ "license": "ISC"+ },"node_modules/end-of-stream": {"version": "1.4.5","resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",diff --git a/package.json b/package.jsonindex 330509e..89e716b 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "p5.brush",- "version": "2.0.3-beta",+ "version": "2.1.0-beta","description": "Unlock custom brushes, natural fill effects and intuitive hatching in p5.js","main": "src/index.js","module": "src/index.js",@@ -43,6 +43,7 @@"p5": "^2.2"},"dependencies": {+ "earcut": "^3.0.2","esm-seedrandom": "^3.0.5","simplex-noise": "^4.0.3"}diff --git a/src/core/color.js b/src/core/color.jsindex f2a4f5b..c2da0de 100644--- a/src/core/color.js+++ b/src/core/color.js@@ -1,3 +1,21 @@+import {+ Cwidth,+ Cheight,+ Renderer,+ Density,+ load as loadTarget,+ isCanvasReady,+ syncDensity,+ getActiveFramebuffer,+ isFramebufferTarget,+} from "./target.js";+import {+ expandDirtyRect,+ normalizeDirtyRect as clampDirtyRect,+ unionDirtyRect,+ getFullDirtyRect as getFullRect,+} from "./dirty_rect.js";+import vertSrc from "./gl/shader.vert";import fragSrc from "./gl/shader.frag";@@ -10,128 +28,17 @@ import fragSrc from "./gl/shader.frag";* provides utilities for saving and restoring states.*/-export let Cwidth, Cheight, Instance, Renderer, Density; // Global canvas properties--let FillMaskUploadCanvas = null;-let ReadySketch = null;-let ActiveInstance = null;-const ActiveInstanceStack = [];--// =============================================================================-// Section: Target Resolution-// =============================================================================--/**- * Checks whether the given draw target is a p5.Framebuffer-like object.- * @param {*} target - Candidate draw target.- * @returns {boolean} True when the target behaves like a p5.Framebuffer.- */-const isFramebufferTarget = (target) =>- !!target &&- typeof target.begin === "function" &&- typeof target.end === "function" &&- !!target.renderer &&- !!target.renderer._pInst;--const isFiniteSize = (value) =>- typeof value === "number" && Number.isFinite(value) && value > 0;--const safeRead = (getter) => {- try {- return getter();- } catch (_error) {- return undefined;- }-};--const isReadyWebGLSketch = (candidate) =>- !!candidate &&- typeof candidate.pixelDensity === "function" &&- typeof candidate.createFramebuffer === "function" &&- isFiniteSize(safeRead(() => candidate.width)) &&- isFiniteSize(safeRead(() => candidate.height)) &&- safeRead(() => candidate.webglVersion) === "webgl2";--const getCurrentP5Instance = () => window.self?.p5?.instance ?? null;--const rememberReadySketch = (candidate) => {- if (isReadyWebGLSketch(candidate)) ReadySketch = candidate;- return ReadySketch;-};+let strokeComposite = null;+let fillComposite = null;-const getActiveSketchRenderer = () => {- if (!ActiveInstance) return null;- if (!isReadyWebGLSketch(ActiveInstance)) return null;- return rememberReadySketch(ActiveInstance);+export const registerStrokeComposite = (composite) => {+ strokeComposite = composite;};-/**- * Resolves the sketch renderer that owns the current drawing session.- * Preference order:- * 1. the sketch currently executing a p5 lifecycle callback- * 2. the explicitly selected instance from brush.instance(p), if ready- * 3. the last known-good ready sketch- * @returns {p5|Window["p5"]["instance"]|null} The active sketch renderer.- */-const getSketchRenderer = () =>- getActiveSketchRenderer() ||- rememberReadySketch(getCurrentP5Instance()) ||- rememberReadySketch(Instance) ||- ReadySketch;--/**- * Resolves the renderer and pixel size used by `brush.load()`.- * @param {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional draw target.- * @returns {{renderer: object, width: number, height: number}} Active renderer info.- */-const resolveTarget = (buffer = false) => {- const sketchRenderer = getSketchRenderer();-- // brush.load() can target the main sketch renderer, a p5.Graphics surface,- // or an active framebuffer owned by the current sketch.- if (!buffer) {- if (!sketchRenderer) {- throw new Error(- "p5.brush could not resolve an active WEBGL sketch. Call brush.instance(p) and brush.load() after createCanvas(..., WEBGL).",- );- }- return {- renderer: sketchRenderer,- width: sketchRenderer.width,- height: sketchRenderer.height,- };- }-- if (isFramebufferTarget(buffer)) {- const owner = buffer.renderer._pInst;- rememberReadySketch(owner);-- if (sketchRenderer && owner !== sketchRenderer) {- throw new Error(- "p5.brush only supports p5.Framebuffer targets created from the active sketch",- );- }-- return {- renderer: owner,- width: buffer.width,- height: buffer.height,- };- }-- return {- renderer: buffer,- width: buffer.width,- height: buffer.height,- };+export const registerFillComposite = (composite) => {+ fillComposite = composite;};-/**- * Returns the currently bound sketch framebuffer when drawing into one.- * @returns {p5.Framebuffer|null} Active framebuffer or null.- */-const getActiveFramebuffer = () => Renderer?._renderer?.activeFramebuffer?.() ?? null;-const clearTarget = (target) => {if (!target) return;@@ -147,57 +54,9 @@ const clearTarget = (target) => {ctx.restore();};-const uploadFillMaskToMirror = (mask, dirtyRect = null) => {- const target = Renderer.fillMaskFramebuffer;- const gl = Renderer.drawingContext;- const uploadRect = normalizeDirtyRect(dirtyRect) ?? getFullDirtyRect();- const uploadWidth = uploadRect.maxX - uploadRect.minX;- const uploadHeight = uploadRect.maxY - uploadRect.minY;-- if (- !FillMaskUploadCanvas ||- FillMaskUploadCanvas.width !== uploadWidth ||- FillMaskUploadCanvas.height !== uploadHeight- ) {- FillMaskUploadCanvas = new OffscreenCanvas(uploadWidth, uploadHeight);- FillMaskUploadCanvas.drawingContext = FillMaskUploadCanvas.getContext("2d");- }-- const uploadContext = FillMaskUploadCanvas.drawingContext;- uploadContext.clearRect(0, 0, uploadWidth, uploadHeight);- uploadContext.drawImage(- mask,- uploadRect.minX,- uploadRect.minY,- uploadWidth,- uploadHeight,- 0,- 0,- uploadWidth,- uploadHeight,- );-- clearTarget(target);- gl.bindTexture(gl.TEXTURE_2D, target.colorTexture);- gl.texSubImage2D(- gl.TEXTURE_2D,- 0,- uploadRect.minX,- uploadRect.minY,- gl.RGBA,- gl.UNSIGNED_BYTE,- FillMaskUploadCanvas,- );-- return target;-};-// =============================================================================// Section: Dirty Rect Utilities// =============================================================================-const DIRTY_BRUSH_PADDING = 2;-const DIRTY_FILL_PADDING = 4;-/*** Returns the current render target size in physical pixels.* @returns {{width: number, height: number}} Pixel size of the active target.@@ -207,57 +66,10 @@ const getTargetPixelSize = () => ({height: Math.max(1, Math.round(Cheight * Density)),});-/**- * Expands a dirty rectangle outward by a constant padding value.- * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Rect to expand.- * @param {number} [padding=0] - Padding in pixels.- * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Expanded rect.- */-const expandDirtyRect = (rect, padding = 0) =>- rect- ? {- minX: rect.minX - padding,- minY: rect.minY - padding,- maxX: rect.maxX + padding,- maxY: rect.maxY + padding,- }- : null;--/**- * Clamps a dirty rectangle to the current target bounds.- * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Candidate rect.- * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Clamped rect.- */const normalizeDirtyRect = (rect) => {if (!rect) return null;-const { width, height } = getTargetPixelSize();- const minX = Math.max(0, Math.floor(Math.min(rect.minX, rect.maxX)));- const minY = Math.max(0, Math.floor(Math.min(rect.minY, rect.maxY)));- const maxX = Math.min(width, Math.ceil(Math.max(rect.minX, rect.maxX)));- const maxY = Math.min(height, Math.ceil(Math.max(rect.minY, rect.maxY)));-- if (maxX <= minX || maxY <= minY) return null;-- return { minX, minY, maxX, maxY };-};--/**- * Returns the union of two dirty rectangles.- * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} a - First rect.- * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} b - Second rect.- * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Union rect.- */-const unionDirtyRect = (a, b) => {- if (!a) return b;- if (!b) return a;-- return {- minX: Math.min(a.minX, b.minX),- minY: Math.min(a.minY, b.minY),- maxX: Math.max(a.maxX, b.maxX),- maxY: Math.max(a.maxY, b.maxY),- };+ return clampDirtyRect(rect, width, height);};/**@@ -266,7 +78,7 @@ const unionDirtyRect = (a, b) => {*/const getFullDirtyRect = () => {const { width, height } = getTargetPixelSize();- return { minX: 0, minY: 0, maxX: width, maxY: height };+ return getFullRect(width, height);};// =============================================================================@@ -315,60 +127,11 @@ const withScissor = (gl, rect, draw, flipY = true) => {}};-// =============================================================================-// Section: Load and State-// =============================================================================-/**- * Loads and initializes a canvas for the drawing system.- * @param {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional offscreen target.- * Pass a framebuffer only while drawing inside its begin()/end() or draw() scope.- * Framebuffers created from p5.Graphics are not supported.- */-export const load = (buffer = false) => {- const target = resolveTarget(buffer);- Renderer = target.renderer;- rememberReadySketch(!buffer ? Renderer : getSketchRenderer());-- if (Renderer.webglVersion !== "webgl2") {- throw new Error("p5.brush requires a WEBGL canvas");- }-- Cwidth = target.width;- Cheight = target.height;-- _isReady = true;- if (Renderer.loaded) Mix.load();-};--let _isReady = false;--/**- * Ensures the drawing system is ready before any operation.- */-export const isCanvasReady = () => {- if (!_isReady) load();-};-/*** Stores the current state of the drawing system.* Can be used to save and restore configurations or canvas states.*/export const State = {};--export const instance = (inst) => {- Instance = inst;- rememberReadySketch(inst);-};--export const activateInstance = (inst) => {- ActiveInstanceStack.push(ActiveInstance);- ActiveInstance = inst;- instance(inst);-};--export const deactivateInstance = () => {- ActiveInstance = ActiveInstanceStack.pop() ?? null;-};/*** Handles color blending using WebGL shaders. Implements advanced blending* effects based on Kubelka-Munk theory. Relies on spectral.js for blending logic.@@ -397,7 +160,7 @@ export const isMixReady = () => {*/export const Mix = {isBlending: false,- cachedColor: new Object(),+ cachedColor: null,/*** Merges a new dirty rectangle into the target's accumulated draw bounds.@@ -417,10 +180,8 @@ export const Mix = {*/clearMask(target) {if (!target) return;-- clearTarget(target);- target.isDrawn = false;- target.dirtyRect = null;+ const composite = target === this.glMask ? strokeComposite : fillComposite;+ composite?.clearMask?.(target, clearTarget);},/**@@ -430,17 +191,13 @@ export const Mix = {* @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.*/getCompositeRect(target, isBrushMask) {- if (!target) return null;- if (!target.dirtyRect) return getFullDirtyRect();-- // Brush-mask dirty rects are still less predictable when the destination- // is itself a framebuffer, so keep that path conservative.- if (isBrushMask && getActiveFramebuffer()) return getFullDirtyRect();- return normalizeDirtyRect(- expandDirtyRect(- target.dirtyRect,- isBrushMask ? DIRTY_BRUSH_PADDING : DIRTY_FILL_PADDING,- ),+ const composite = isBrushMask ? strokeComposite : fillComposite;+ return composite?.getCompositeRect?.(+ target,+ getActiveFramebuffer,+ getFullDirtyRect,+ expandDirtyRect,+ normalizeDirtyRect,);},@@ -451,47 +208,35 @@ export const Mix = {* Ensures the mask buffers and blend shader exist for the current renderer.*/load() {- Density = Renderer.pixelDensity();- const maskWidth = Math.max(1, Math.round(Cwidth * Density));- const maskHeight = Math.max(1, Math.round(Cheight * Density));- const needsBuffers =- !Renderer.mask ||- !Renderer.glMask ||- Renderer.mask.width !== maskWidth ||- Renderer.mask.height !== maskHeight ||- Renderer.glMask.width !== Cwidth ||- Renderer.glMask.height !== Cheight;+ syncDensity();const needsBlendSourceFramebuffer =!Renderer.blendSourceFramebuffer ||Renderer.blendSourceFramebuffer.width !== Cwidth ||Renderer.blendSourceFramebuffer.height !== Cheight ||(typeof Renderer.blendSourceFramebuffer.pixelDensity === "function" &&Renderer.blendSourceFramebuffer.pixelDensity() !== Density);- const needsFillMaskFramebuffer =- !Renderer.fillMaskFramebuffer ||- Renderer.fillMaskFramebuffer.width !== Cwidth ||- Renderer.fillMaskFramebuffer.height !== Cheight ||- (typeof Renderer.fillMaskFramebuffer.pixelDensity === "function" &&- Renderer.fillMaskFramebuffer.pixelDensity() !== Density);- if (!Renderer.loaded || needsBuffers) {- if (Renderer.glMask?.remove) Renderer.glMask.remove();- // Keep one 2D mask for fill/hatch work and one framebuffer-backed mask- // for brush stamps so the brush path stays in the main renderer context.- Renderer.mask = new OffscreenCanvas(maskWidth, maskHeight);- Renderer.mask.drawingContext = Renderer.mask.getContext("2d");- Renderer.glMask = Renderer.createFramebuffer({- width: Cwidth,- height: Cheight,- density: Density,- antialias: false,- depth: false,- stencil: false,- });+ if (!Renderer.loaded) {Renderer.loaded = true;-Renderer.shaderProgram ??= Renderer.createShader(vertSrc, fragSrc);}+ this.glMask = strokeComposite?.ensureResources?.(+ Renderer,+ Cwidth,+ Cheight,+ Density,+ );+ const fillResources = fillComposite?.ensureResources?.(+ Renderer,+ Cwidth,+ Cheight,+ Density,+ clearTarget,+ ) ?? {+ mask: null,+ ctx: null,+ };+if (needsBlendSourceFramebuffer) {if (Renderer.blendSourceFramebuffer?.remove) {Renderer.blendSourceFramebuffer.remove();@@ -506,30 +251,8 @@ export const Mix = {});}- if (needsFillMaskFramebuffer) {- if (Renderer.fillMaskFramebuffer?.remove) {- Renderer.fillMaskFramebuffer.remove();- }- Renderer.fillMaskFramebuffer = Renderer.createFramebuffer({- width: Cwidth,- height: Cheight,- density: Density,- antialias: false,- depth: false,- stencil: false,- });- clearTarget(Renderer.fillMaskFramebuffer);- }-- this.mask = Renderer.mask;- this.glMask = Renderer.glMask;- this.ctx = this.mask.drawingContext;- this.mask.dirtyRect ??= null;- this.mask.isDrawn ??= false;- this.ctx.imageSmoothingEnabled = false;-- this.glMask.dirtyRect ??= null;- this.glMask.isDrawn ??= false;+ this.mask = fillResources.mask;+ this.ctx = fillResources.ctx;},// =============================================================================@@ -542,7 +265,6 @@ export const Mix = {*/blend(_color = false, _isLast = false) {isMixReady();-// Only one mask is "active" for the current drawing mode; the other one// may still need flushing if the mode just changed mid-frame.const isBrushMask = this.isBrush === true;@@ -551,15 +273,16 @@ export const Mix = {const nextColor = _color?._array;const colorChanged =!!nextColor &&- (this.cachedColor[0] !== nextColor[0] ||- this.cachedColor[1] !== nextColor[1] ||- this.cachedColor[2] !== nextColor[2] ||- this.cachedColor[3] !== nextColor[3]);+ (this.cachedColor?.[0] !== nextColor[0] ||+ this.cachedColor?.[1] !== nextColor[1] ||+ this.cachedColor?.[2] !== nextColor[2] ||+ this.cachedColor?.[3] !== nextColor[3]);if (!this.isBlending && nextColor) {this.isBlending = true;this.cachedColor = nextColor;- // Reset the brush mask at the start of each blend cycle.- clearTarget(this.glMask);+ // Reset the brush mask fully at the start of each blend cycle so stale+ // dirty-rect bookkeeping cannot leak an old stroke into the next color.+ this.clearMask(this.glMask);}if (_isLast || colorChanged) {@@ -571,7 +294,11 @@ export const Mix = {this.applyShader(mask, isBrushMask);}if (nextColor) this.cachedColor = nextColor;- if (_isLast) this.isBlending = false;+ if (_isLast) {+ this.isBlending = false;+ this.cachedColor = null;++ }}},@@ -607,11 +334,18 @@ export const Mix = {shader.setUniform("u_source", source);shader.setUniform("u_targetIsFramebuffer", targetIsFramebuffer);shader.setUniform("u_isBrush", isBrushMask);- if (isBrushMask) {- shader.setUniform("u_mask", mask);- } else {- shader.setUniform("u_mask", uploadFillMaskToMirror(mask, dirtyRect));- }+ const composite = isBrushMask ? strokeComposite : fillComposite;+ shader.setUniform(+ "u_mask",+ composite.getShaderMask(+ Renderer,+ mask,+ dirtyRect,+ normalizeDirtyRect,+ getFullDirtyRect,+ clearTarget,+ ),+ );shader.setUniform("u_color", this.cachedColor);withScissor(gl, dirtyRect, () => {@@ -627,6 +361,32 @@ export const Mix = {},};+/**+ * Flushes any pending stroke/fill mask work into the current target and resets+ * the shared compositor back to its initial idle state.+ */+export const flushActiveComposite = () => {+ isMixReady();+ Mix.blend(false, true);+ Mix.clearMask(Mix.glMask);+ Mix.clearMask(Mix.mask);+ Mix.justChanged = false;+ Mix.isBlending = false;+ Mix.isBrush = null;+ Mix.cachedColor = null;+};++/**+ * Loads and initializes the drawing target, then refreshes compositing+ * resources if the renderer was already active.+ *+ * @param {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional offscreen target.+ */+export const load = (buffer = false) => {+ loadTarget(buffer);+ if (Renderer.loaded) Mix.load();+};+/*** Copies the current pixels of a renderer or framebuffer into the reusable* blend source framebuffer.diff --git a/src/core/dirty_rect.js b/src/core/dirty_rect.jsnew file mode 100644index 0000000..3a25b1c--- /dev/null+++ b/src/core/dirty_rect.js@@ -0,0 +1,73 @@+// =============================================================================+// Module: Dirty Rect Utilities+// =============================================================================+/**+ * Expands a dirty rectangle outward by a constant padding value.+ *+ * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Rect to expand.+ * @param {number} [padding=0] - Padding in pixels.+ * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Expanded rect.+ */+export const expandDirtyRect = (rect, padding = 0) =>+ rect+ ? {+ minX: rect.minX - padding,+ minY: rect.minY - padding,+ maxX: rect.maxX + padding,+ maxY: rect.maxY + padding,+ }+ : null;++/**+ * Clamps a dirty rectangle to explicit target bounds.+ *+ * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Candidate rect.+ * @param {number} width - Target width in physical pixels.+ * @param {number} height - Target height in physical pixels.+ * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Clamped rect.+ */+export const normalizeDirtyRect = (rect, width, height) => {+ if (!rect) return null;++ const minX = Math.max(0, Math.floor(Math.min(rect.minX, rect.maxX)));+ const minY = Math.max(0, Math.floor(Math.min(rect.minY, rect.maxY)));+ const maxX = Math.min(width, Math.ceil(Math.max(rect.minX, rect.maxX)));+ const maxY = Math.min(height, Math.ceil(Math.max(rect.minY, rect.maxY)));++ if (maxX <= minX || maxY <= minY) return null;++ return { minX, minY, maxX, maxY };+};++/**+ * Returns the union of two dirty rectangles.+ *+ * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} a - First rect.+ * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} b - Second rect.+ * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Union rect.+ */+export const unionDirtyRect = (a, b) => {+ if (!a) return b;+ if (!b) return a;++ return {+ minX: Math.min(a.minX, b.minX),+ minY: Math.min(a.minY, b.minY),+ maxX: Math.max(a.maxX, b.maxX),+ maxY: Math.max(a.maxY, b.maxY),+ };+};++/**+ * Returns a dirty rectangle covering the full target bounds.+ *+ * @param {number} width - Target width in physical pixels.+ * @param {number} height - Target height in physical pixels.+ * @returns {{minX:number,minY:number,maxX:number,maxY:number}} Full-target rect.+ */+export const getFullDirtyRect = (width, height) => ({+ minX: 0,+ minY: 0,+ maxX: width,+ maxY: height,+});diff --git a/src/core/flowfield.js b/src/core/flowfield.jsindex 6a5eb1d..9865dc5 100644--- a/src/core/flowfield.js+++ b/src/core/flowfield.js@@ -1,4 +1,5 @@-import { isMixReady, Cwidth, Cheight, State, Renderer } from "./color.js";+import { Cwidth, Cheight, Renderer } from "./target.js";+import { isMixReady, State } from "./color.js";import { randInt2, noise2, rr2, sin, cos, map, toDegreesSigned } from "./utils.js";// =============================================================================@@ -111,8 +112,9 @@ export class Position {* Calculates the angle of the flow field at the position's current coordinates.* @returns {number} - The internal flow angle in degrees, or 0 if the position is not in the field or if no field is active.*/- angle() {- return this.isIn() && State.field.isActive+ angle(skipCheck = false) {+ if (!State.field.isActive) return 0;+ return (skipCheck || this.isIn())? flow_field()[this.colIdx][this.rowIdx] * State.field.wiggle: 0;}@@ -151,9 +153,12 @@ export class Position {this.plotted += _step / scaleFactor;return;}- for (let i = 0; i < _length / _step; i++) {+ const steps = _length / _step;+ const fieldActive = State.field.isActive;+ const usePlot = !!_scale;+ for (let i = 0; i < steps; i++) {const angle =- this.angle() - (_scale ? _dirPlot.angle(this.plotted) : _dirPlot);+ (fieldActive ? this.angle(true) : 0) - (usePlot ? _dirPlot.angle(this.plotted) : _dirPlot);// Calculate new positionthis.update(this.x + _step * cos(angle), this.y + _step * sin(angle));this.plotted += _step / scaleFactor;diff --git a/src/core/plot.js b/src/core/plot.jsindex 18285f4..7f96867 100644--- a/src/core/plot.js+++ b/src/core/plot.js@@ -1,4 +1,5 @@-import { State, Cwidth, Cheight } from "./color.js";+import { Cwidth, Cheight } from "./target.js";+import { State } from "./color.js";import { toDegrees, map, rr2 } from "./utils.js";import { Position, isFieldReady } from "./flowfield.js";import { Polygon } from "./polygon.js";@@ -133,7 +134,7 @@ export class Plot {*/genPol(_x, _y, _scale = 1, _side) {isFieldReady(); // Ensure that the drawing environment is prepared- const step = 0.5;+ const step = _side < 0 ? 4 : 1;const vertices = [];const numSteps = Math.round(this.length / step);const pos = new Position(_x + Cwidth / 2, _y + Cheight / 2);@@ -144,7 +145,7 @@ export class Plot {pos.plotTo(this, step, step);const idx = this.calcIndex(pos.plotted);pside += step;- const maxSize = _side === 0 ? 5 : Math.max(this.segments[idx] * _side * rr2(0.7, 1.3), 20);+ let maxSize = _side <= 0 ? 8 : Math.max(this.segments[idx] * _side * rr2(0.7, 1.3), 20);if ((pside >= maxSize || idx >= prevIdx) && pos.x) {vertices.push([pos.x - Cwidth / 2, pos.y - Cheight / 2]);pside = 0;@@ -161,8 +162,10 @@ export class Plot {* @param {number} scale - The scale factor.*/show(x, y, scale = 1) {- if (State.stroke) this.draw(x, y, scale);- if (State.hatch) this.hatch(x, y, scale);+ if (State.wash) this.wash(x, y, scale);if (State.fill) this.fill(x, y, scale);+ if (State.mass) this.mass(x, y, scale);+ if (State.hatch) this.hatch(x, y, scale);+ if (State.stroke) this.draw(x, y, scale);}}diff --git a/src/core/polygon.js b/src/core/polygon.jsindex d138608..41df5fc 100644--- a/src/core/polygon.js+++ b/src/core/polygon.js@@ -51,8 +51,10 @@ export class Polygon {* Displays the polygon with optional stroke, hatch, and fill effects.*/show() {- if (State.stroke) this.draw();- if (State.hatch) this.hatch();+ if (State.wash) this.wash();if (State.fill) this.fill();+ if (State.mass) this.mass();+ if (State.hatch) this.hatch();+ if (State.stroke) this.draw();}-}+}\ No newline at end of filediff --git a/src/core/primitives.js b/src/core/primitives.jsindex 12efb59..4fae39e 100644--- a/src/core/primitives.js+++ b/src/core/primitives.js@@ -18,6 +18,7 @@ import { Plot } from "./plot.js";/*** Creates a Polygon from an array of points and calls its show() method.+ * Polygons ignore fields and won't be good for fills and masses* @param {Array<Array<number>>} pointsArray - Array of points [x, y, pressure]*/export function polygon(pointsArray) {diff --git a/src/core/save.js b/src/core/save.jsindex 8c80ac5..e25f66c 100644--- a/src/core/save.js+++ b/src/core/save.js@@ -20,8 +20,10 @@ export function push() {isFieldReady();_stateStack.push({fill: { ...State.fill },+ wash: State.wash ? { ...State.wash } : null,stroke: { ...State.stroke },hatch: { ...State.hatch },+ mass: State.mass ? { ...State.mass } : null,field: { ...State.field },});}@@ -36,4 +38,16 @@ export function pop() {State.field = { ...saved.field };State.hatch = { ...saved.hatch };State.fill = { ...saved.fill };+ if (saved.wash) State.wash = { ...saved.wash };+ if (saved.mass) {+ State.mass = { ...saved.mass };+ } else if (State.mass) {+ State.mass = {+ ...State.mass,+ isActive: false,+ brush: null,+ color: null,+ options: {},+ };+ }}diff --git a/src/core/target.js b/src/core/target.jsnew file mode 100644index 0000000..f91fef2--- /dev/null+++ b/src/core/target.js@@ -0,0 +1,175 @@+// =============================================================================+// Module: Target Resolution and Runtime Context+// =============================================================================+/**+ * Owns the active renderer/instance selection used by p5.brush.+ */++export let Cwidth, Cheight, Instance, Renderer, Density;++let ReadySketch = null;+let ActiveInstance = null;+const ActiveInstanceStack = [];+let _isReady = false;++/**+ * Checks whether the given draw target is a p5.Framebuffer-like object.+ * @param {*} target - Candidate draw target.+ * @returns {boolean} True when the target behaves like a p5.Framebuffer.+ */+export const isFramebufferTarget = (target) =>+ !!target &&+ typeof target.begin === "function" &&+ typeof target.end === "function" &&+ !!target.renderer &&+ !!target.renderer._pInst;++const isFiniteSize = (value) =>+ typeof value === "number" && Number.isFinite(value) && value > 0;++const safeRead = (getter) => {+ try {+ return getter();+ } catch (_error) {+ return undefined;+ }+};++const isReadyWebGLSketch = (candidate) =>+ !!candidate &&+ typeof candidate.pixelDensity === "function" &&+ typeof candidate.createFramebuffer === "function" &&+ isFiniteSize(safeRead(() => candidate.width)) &&+ isFiniteSize(safeRead(() => candidate.height)) &&+ safeRead(() => candidate.webglVersion) === "webgl2";++const getCurrentP5Instance = () => window.self?.p5?.instance ?? null;++const rememberReadySketch = (candidate) => {+ if (isReadyWebGLSketch(candidate)) ReadySketch = candidate;+ return ReadySketch;+};++const getActiveSketchRenderer = () => {+ if (!ActiveInstance) return null;+ if (!isReadyWebGLSketch(ActiveInstance)) return null;+ return rememberReadySketch(ActiveInstance);+};++/**+ * Resolves the sketch renderer that owns the current drawing session.+ * Preference order:+ * 1. the sketch currently executing a p5 lifecycle callback+ * 2. the explicitly selected instance from brush.instance(p), if ready+ * 3. the last known-good ready sketch+ * @returns {p5|Window["p5"]["instance"]|null} The active sketch renderer.+ */+export const getSketchRenderer = () =>+ getActiveSketchRenderer() ||+ rememberReadySketch(getCurrentP5Instance()) ||+ rememberReadySketch(Instance) ||+ ReadySketch;++/**+ * Resolves the renderer and pixel size used by `brush.load()`.+ * @param {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional draw target.+ * @returns {{renderer: object, width: number, height: number}} Active renderer info.+ */+const resolveTarget = (buffer = false) => {+ const sketchRenderer = getSketchRenderer();++ if (!buffer) {+ if (!sketchRenderer) {+ throw new Error(+ "p5.brush could not resolve an active WEBGL sketch. Call brush.instance(p) and brush.load() after createCanvas(..., WEBGL).",+ );+ }+ return {+ renderer: sketchRenderer,+ width: sketchRenderer.width,+ height: sketchRenderer.height,+ };+ }++ if (isFramebufferTarget(buffer)) {+ const owner = buffer.renderer._pInst;+ rememberReadySketch(owner);++ if (sketchRenderer && owner !== sketchRenderer) {+ throw new Error(+ "p5.brush only supports p5.Framebuffer targets created from the active sketch",+ );+ }++ return {+ renderer: owner,+ width: buffer.width,+ height: buffer.height,+ };+ }++ return {+ renderer: buffer,+ width: buffer.width,+ height: buffer.height,+ };+};++/**+ * Returns the currently bound sketch framebuffer when drawing into one.+ * @returns {p5.Framebuffer|null} Active framebuffer or null.+ */+export const getActiveFramebuffer = () =>+ Renderer?._renderer?.activeFramebuffer?.() ?? null;++/**+ * Loads and initializes a canvas for the drawing system.+ * @param {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional offscreen target.+ * Pass a framebuffer only while drawing inside its begin()/end() or draw() scope.+ * Framebuffers created from p5.Graphics are not supported.+ */+export const load = (buffer = false) => {+ const target = resolveTarget(buffer);+ Renderer = target.renderer;+ rememberReadySketch(!buffer ? Renderer : getSketchRenderer());++ if (Renderer.webglVersion !== "webgl2") {+ throw new Error("p5.brush requires a WEBGL canvas");+ }++ Cwidth = target.width;+ Cheight = target.height;++ _isReady = true;+};++/**+ * Refreshes the stored pixel density for the active renderer.+ * @returns {number} Current renderer pixel density.+ */+export const syncDensity = () => {+ Density = Renderer.pixelDensity();+ return Density;+};++/**+ * Ensures the drawing system is ready before any operation.+ */+export const isCanvasReady = () => {+ if (!_isReady) load();+};++export const instance = (inst) => {+ Instance = inst;+ rememberReadySketch(inst);+};++export const activateInstance = (inst) => {+ ActiveInstanceStack.push(ActiveInstance);+ ActiveInstance = inst;+ instance(inst);+};++export const deactivateInstance = () => {+ ActiveInstance = ActiveInstanceStack.pop() ?? null;+};diff --git a/src/core/utils.js b/src/core/utils.jsindex bc1d57f..7540a95 100644--- a/src/core/utils.js+++ b/src/core/utils.js@@ -1,4 +1,4 @@-import { Renderer } from "./color.js";+import { Renderer } from "./target.js";// =============================================================================// Section: Randomness & Noisediff --git a/src/fill/composite.js b/src/fill/composite.jsnew file mode 100644index 0000000..813e95a--- /dev/null+++ b/src/fill/composite.js@@ -0,0 +1,231 @@+import * as Color from "../core/color.js";++// Small staging canvas used to upload only the dirty fill sub-rect into the+// framebuffer-backed mask mirror consumed by the blend shader.+let FillMaskUploadCanvas = null;+let isFillCompositeRegistered = false;+const DIRTY_FILL_PADDING = 4;++// =============================================================================+// Section: Helpers+// =============================================================================+/**+ * Returns whether the CPU-side 2D fill mask must be recreated.+ *+ * @param {object} Renderer - Active p5 renderer/sketch.+ * @param {number} maskWidth - Mask width in physical pixels.+ * @param {number} maskHeight - Mask height in physical pixels.+ * @returns {boolean} True when the 2D fill mask needs reallocation.+ */+function needsFillMaskCanvas(Renderer, maskWidth, maskHeight) {+ return (+ !Renderer.mask ||+ Renderer.mask.width !== maskWidth ||+ Renderer.mask.height !== maskHeight+ );+}++/**+ * Returns whether the framebuffer-backed fill mask mirror must be recreated.+ *+ * @param {object} Renderer - Active p5 renderer/sketch.+ * @param {number} Cwidth - Target width in sketch units.+ * @param {number} Cheight - Target height in sketch units.+ * @param {number} Density - Active pixel density.+ * @returns {boolean} True when the fill mask framebuffer needs reallocation.+ */+function needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density) {+ return (+ !Renderer.fillMaskFramebuffer ||+ Renderer.fillMaskFramebuffer.width !== Cwidth ||+ Renderer.fillMaskFramebuffer.height !== Cheight ||+ (typeof Renderer.fillMaskFramebuffer.pixelDensity === "function" &&+ Renderer.fillMaskFramebuffer.pixelDensity() !== Density)+ );+}++// =============================================================================+// Section: Resource Management+// =============================================================================+/**+ * Ensures fill compositing resources exist for the active renderer.+ *+ * Fill draws first into a CPU-side 2D mask canvas. That mask is later uploaded,+ * dirty-rect by dirty-rect, into a framebuffer-backed mirror used by the final+ * blend shader pass.+ *+ * @param {object} Renderer - Active p5 renderer/sketch.+ * @param {number} Cwidth - Target width in sketch units.+ * @param {number} Cheight - Target height in sketch units.+ * @param {number} Density - Active pixel density.+ * @param {Function} clearTarget - Shared low-level clear helper from core.+ * @returns {{mask: object, ctx: CanvasRenderingContext2D}} Fill mask resources.+ */+export function ensureFillCompositeResources(+ Renderer,+ Cwidth,+ Cheight,+ Density,+ clearTarget,+) {+ const maskWidth = Math.max(1, Math.round(Cwidth * Density));+ const maskHeight = Math.max(1, Math.round(Cheight * Density));++ if (needsFillMaskCanvas(Renderer, maskWidth, maskHeight)) {+ Renderer.mask = new OffscreenCanvas(maskWidth, maskHeight);+ Renderer.mask.drawingContext = Renderer.mask.getContext("2d");+ }++ if (needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density)) {+ if (Renderer.fillMaskFramebuffer?.remove) {+ Renderer.fillMaskFramebuffer.remove();+ }+ Renderer.fillMaskFramebuffer = Renderer.createFramebuffer({+ width: Cwidth,+ height: Cheight,+ density: Density,+ antialias: false,+ depth: false,+ stencil: false,+ });+ clearTarget(Renderer.fillMaskFramebuffer);+ }++ Renderer.mask.dirtyRect ??= null;+ Renderer.mask.isDrawn ??= false;+ Renderer.mask.drawingContext.imageSmoothingEnabled = false;++ return {+ mask: Renderer.mask,+ ctx: Renderer.mask.drawingContext,+ };+}++// =============================================================================+// Section: Mask Lifecycle+// =============================================================================+/**+ * Clears the current fill mask and resets its bookkeeping flags.+ *+ * @param {object|null} target - Fill mask canvas or framebuffer mirror.+ * @param {Function} clearTarget - Shared low-level clear helper from core.+ */+export function clearFillMask(target, clearTarget) {+ if (!target) return;+ clearTarget(target);+ target.isDrawn = false;+ target.dirtyRect = null;+}++// =============================================================================+// Section: Composite Bounds+// =============================================================================+/**+ * Returns the fill dirty rect to composite into the main target. Fill bounds are+ * taken directly from the accumulated 2D mask dirty area plus a small padding.+ *+ * @param {object|null} target - Fill mask canvas.+ * @param {Function} _getActiveFramebuffer - Unused for fill masks.+ * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.+ * @param {Function} expandDirtyRect - Expands a rect by a constant padding.+ * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.+ * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.+ */+export function getFillCompositeRect(+ target,+ _getActiveFramebuffer,+ getFullDirtyRect,+ expandDirtyRect,+ normalizeDirtyRect,+) {+ if (!target) return null;+ if (!target.dirtyRect) return getFullDirtyRect();+ return normalizeDirtyRect(+ expandDirtyRect(target.dirtyRect, DIRTY_FILL_PADDING),+ );+}++// =============================================================================+// Section: Upload+// =============================================================================+/**+ * Uploads only the dirty portion of the CPU-side 2D fill mask into the+ * framebuffer-backed fill mask mirror used by the shader compositor.+ *+ * @param {object} Renderer - Active p5 renderer/sketch.+ * @param {object} mask - CPU-side 2D fill mask canvas.+ * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} dirtyRect - Dirty rect to upload.+ * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.+ * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.+ * @param {Function} clearTarget - Shared low-level clear helper from core.+ * @returns {object} Framebuffer-backed fill mask mirror.+ */+export function getFillShaderMask(+ Renderer,+ mask,+ dirtyRect,+ normalizeDirtyRect,+ getFullDirtyRect,+ clearTarget,+) {+ const target = Renderer.fillMaskFramebuffer;+ const gl = Renderer.drawingContext;+ const uploadRect = normalizeDirtyRect(dirtyRect) ?? getFullDirtyRect();+ const uploadWidth = uploadRect.maxX - uploadRect.minX;+ const uploadHeight = uploadRect.maxY - uploadRect.minY;++ if (+ !FillMaskUploadCanvas ||+ FillMaskUploadCanvas.width !== uploadWidth ||+ FillMaskUploadCanvas.height !== uploadHeight+ ) {+ FillMaskUploadCanvas = new OffscreenCanvas(uploadWidth, uploadHeight);+ FillMaskUploadCanvas.drawingContext = FillMaskUploadCanvas.getContext("2d");+ }++ const uploadContext = FillMaskUploadCanvas.drawingContext;+ uploadContext.clearRect(0, 0, uploadWidth, uploadHeight);+ uploadContext.drawImage(+ mask,+ uploadRect.minX,+ uploadRect.minY,+ uploadWidth,+ uploadHeight,+ 0,+ 0,+ uploadWidth,+ uploadHeight,+ );++ clearTarget(target);+ gl.bindTexture(gl.TEXTURE_2D, target.colorTexture);+ gl.texSubImage2D(+ gl.TEXTURE_2D,+ 0,+ uploadRect.minX,+ uploadRect.minY,+ gl.RGBA,+ gl.UNSIGNED_BYTE,+ FillMaskUploadCanvas,+ );++ return target;+}++// =============================================================================+// Section: Registration+// =============================================================================+/**+ * Registers the fill compositor with the shared color/composite core.+ * Safe to call multiple times.+ */+export function initFillComposite() {+ if (isFillCompositeRegistered) return;+ Color.registerFillComposite?.({+ ensureResources: ensureFillCompositeResources,+ clearMask: clearFillMask,+ getCompositeRect: getFillCompositeRect,+ getShaderMask: getFillShaderMask,+ });+ isFillCompositeRegistered = true;+}diff --git a/src/fill/fill.js b/src/fill/fill.jsindex c7e15be..5f7eeb9 100644--- a/src/fill/fill.js+++ b/src/fill/fill.js@@ -12,13 +12,11 @@* techniques for simulating watercolor paints.*/+// Core imports+import { Renderer, Cwidth, Cheight, Density } from "../core/target.js";import {- Renderer,Mix,State,- Cwidth,- Cheight,- Density,} from "../core/color.js";import { drawPolygon, circle } from "./mask.js";import {@@ -37,6 +35,11 @@ import { isFieldReady, Matrix } from "../core/flowfield.js";import { Polygon } from "../core/polygon.js";import { Plot } from "../core/plot.js";+// Internal module imports+import { initFillComposite } from "./composite.js";++initFillComposite(); // Register the fill composite with the core color module+// =============================================================================// Fill State and helpers// =============================================================================@@ -560,7 +563,7 @@ class FillPoly {if (texture !== 0) {pol.erase(texture * 3, intensity);}- Mix.blend(color, true, false, true);+ Mix.blend(color, true);}}diff --git a/src/fill/wash.js b/src/fill/wash.jsnew file mode 100644index 0000000..bf34553--- /dev/null+++ b/src/fill/wash.js@@ -0,0 +1,269 @@+// =============================================================================+// Module: Wash+// =============================================================================+/**+ * Minimal stateful API for the `wash()` fill modifier.+ */++import earcut from "earcut";+import { Renderer, Cwidth, Cheight, isCanvasReady } from "../core/target.js";+import { State, flushActiveComposite } from "../core/color.js";+import { Polygon } from "../core/polygon.js";+import { Plot } from "../core/plot.js";+import { Matrix } from "../core/flowfield.js";+import { createProgram } from "../core/gl/utils.js";++let gl = null;+let washProgram = null;+let washVao = null;+let washBuffer = null;+let washProjection = null;+let loadedWidth = 0;+let loadedHeight = 0;+let washGpuBufferSize = 0;++const WashAttr = {};+const WashUniform = {};++const washVertSrc = `#version 300 es+in vec2 a_position;+uniform mat4 u_matrix;+void main() {+ gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);+}`;++const washFragSrc = `#version 300 es+precision highp float;+uniform vec4 u_color;+out vec4 outColor;+void main() {+ outColor = vec4(u_color.rgb * u_color.a, u_color.a);+}`;++State.wash = {+ color: null,+ opacity: 150,+ isActive: false,+};++// =============================================================================+// Public API+// =============================================================================++/**+ * Enables wash mode with a color and opacity.+ *+ * @param {number|string|Color} a - Either the red component, a CSS color string, or a Color object.+ * @param {number} [b] - The green component or the opacity if using grayscale.+ * @param {number} [c] - The blue component.+ * @param {number} [d] - The opacity.+ */+export function wash(a, b, c, d) {+ isCanvasReady();+ State.wash.opacity = (arguments.length < 4 ? b : d) ?? 150;+ State.wash.color =+ arguments.length < 3 ? Renderer.color(a) : Renderer.color(a, b, c);+ State.wash.isActive = true;+}++/**+ * Disables wash mode for subsequent drawing operations.+ */+export function noWash() {+ State.wash.isActive = false;+}++// =============================================================================+// GL helpers+// =============================================================================++/**+ * Resets p5's cached shader/blend bookkeeping after direct WebGL calls.+ */+function resetWashShaderTracking() {+ const renderer = Renderer?._renderer;+ if (!renderer) return;+ renderer._curShader = null;+ renderer._cachedBlendMode = null;+ renderer._isBlending = null;+}++/**+ * Lazily creates the reusable program/buffer state for solid wash drawing and+ * refreshes the orthographic projection when the active target size changes.+ */+function ensureWashReady() {+ const nextGl = Renderer.drawingContext;+ const sizeChanged = loadedWidth !== Cwidth || loadedHeight !== Cheight;++ if (!washProjection || sizeChanged) {+ loadedWidth = Cwidth;+ loadedHeight = Cheight;+ washProjection = new Float32Array([+ 2 / loadedWidth,+ 0,+ 0,+ 0,+ 0,+ -2 / loadedHeight,+ 0,+ 0,+ 0,+ 0,+ 1,+ 0,+ -1,+ 1,+ 0,+ 1,+ ]);+ }++ if (gl === nextGl && washProgram && washVao && washBuffer) return;++ gl = nextGl;+ washProgram = createProgram(gl, washVertSrc, washFragSrc);+ WashAttr.a_position = gl.getAttribLocation(washProgram, "a_position");+ WashUniform.u_matrix = gl.getUniformLocation(washProgram, "u_matrix");+ WashUniform.u_color = gl.getUniformLocation(washProgram, "u_color");++ washVao = gl.createVertexArray();+ gl.bindVertexArray(washVao);++ washBuffer = gl.createBuffer();+ gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);+ gl.bufferData(gl.ARRAY_BUFFER, 0, gl.DYNAMIC_DRAW);+ washGpuBufferSize = 0;++ gl.enableVertexAttribArray(WashAttr.a_position);+ gl.vertexAttribPointer(WashAttr.a_position, 2, gl.FLOAT, false, 8, 0);++ gl.bindVertexArray(null);+ gl.bindBuffer(gl.ARRAY_BUFFER, null);+}++/**+ * Applies the current p5.brush transform matrix and converts the result into+ * the screen-space coordinates used by the direct GL wash pipeline.+ *+ * @param {number} x - The source x-coordinate in p5.brush space.+ * @param {number} y - The source y-coordinate in p5.brush space.+ * @returns {[number, number]} The transformed screen-space position.+ */+function transformVertexToScreen(x, y) {+ return [+ Matrix.a() * x + Matrix.c() * y + Matrix.x() + loadedWidth / 2,+ Matrix.b() * x + Matrix.d() * y + Matrix.y() + loadedHeight / 2,+ ];+}++/**+ * Triangulates a polygon in local space and returns the transformed triangle+ * vertex buffer ready for upload to the GPU.+ *+ * @param {Polygon} polygon - The polygon to triangulate.+ * @returns {{ triangles: Float32Array, vertexCount: number }} Screen-space+ * triangle vertices plus the number of vertices to draw.+ */+function buildTriangleBuffer(polygon) {+ const flat = new Float32Array(polygon.vertices.length * 2);+ for (let i = 0; i < polygon.vertices.length; i++) {+ const vertex = polygon.vertices[i];+ flat[i * 2] = vertex.x;+ flat[i * 2 + 1] = vertex.y;+ }++ const indices = earcut(flat);+ const triangles = new Float32Array(indices.length * 2);+ for (let i = 0; i < indices.length; i++) {+ const idx = indices[i];+ const [screenX, screenY] = transformVertexToScreen(flat[idx * 2], flat[idx * 2 + 1]);+ triangles[i * 2] = screenX;+ triangles[i * 2 + 1] = screenY;+ }++ return {+ triangles,+ vertexCount: indices.length,+ };+}++/**+ * Draws a triangulated solid wash directly to the current WEBGL target.+ *+ * @param {Polygon} polygon - The polygon to fill with the current wash state.+ */+function drawWashPolygon(polygon) {+ if (!State.wash?.isActive || !State.wash.color || polygon.vertices.length < 3) return;++ flushActiveComposite();+ ensureWashReady();+ const { triangles, vertexCount } = buildTriangleBuffer(polygon);+ const byteCount = triangles.byteLength;+ gl.useProgram(washProgram);+ gl.enable(gl.BLEND);+ gl.blendEquation(gl.FUNC_ADD);+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);+ gl.bindVertexArray(washVao);+ gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);+ if (byteCount > washGpuBufferSize) {+ gl.bufferData(gl.ARRAY_BUFFER, triangles, gl.DYNAMIC_DRAW);+ washGpuBufferSize = byteCount;+ } else {+ gl.bufferSubData(gl.ARRAY_BUFFER, 0, triangles);+ }+ const color = State.wash.color._array;+ gl.uniformMatrix4fv(WashUniform.u_matrix, false, washProjection);+ gl.uniform4f(+ WashUniform.u_color,+ color[0],+ color[1],+ color[2],+ State.wash.opacity / 255,+ );++ gl.drawArrays(gl.TRIANGLES, 0, vertexCount);+ gl.bindVertexArray(null);+ gl.bindBuffer(gl.ARRAY_BUFFER, null);+ resetWashShaderTracking();+}++// =============================================================================+// Prototype methods+// =============================================================================++/**+ * Applies a direct WEBGL wash fill to the polygon using the current wash state.+ *+ * @param {Color|string|false} [_color] - Optional override color for this call.+ * @param {number} [_opacity] - Optional override opacity for this call.+ */+Polygon.prototype.wash = function (_color = false, _opacity) {+ const state = { ...State.wash };+ if (_color !== false) wash(_color, _opacity);++ if (State.wash.isActive) {+ drawWashPolygon(this);+ }++ State.wash = { ...state };+};++/**+ * Applies wash to a plot by first generating the plot polygon, mirroring the+ * existing fill-path behavior, and then drawing that polygon with wash.+ *+ * @param {number} x - The x-coordinate.+ * @param {number} y - The y-coordinate.+ * @param {number} scale - The scale factor.+ */+Plot.prototype.wash = function (x, y, scale) {+ if (!State.wash?.isActive) return;+ if (this.origin) {+ x = this.origin[0];+ y = this.origin[1];+ scale = 1;+ }+ this.pol = this.genPol(x, y, scale, 0, -1);+ this.pol.wash();+};diff --git a/src/hatch/hatch.js b/src/hatch/hatch.jsindex ac265dd..dc67f1e 100644--- a/src/hatch/hatch.js+++ b/src/hatch/hatch.js@@ -1,13 +1,13 @@-// =============================================================================-// Module: Classic Hatch-// =============================================================================-import { State } from "../core/color.js";import { toDegreesSigned, map, rr } from "../core/utils.js";import { Polygon } from "../core/polygon.js";import { Plot } from "../core/plot.js";import { BrushState, BrushSetState, set, line } from "../stroke/stroke.js";+// =============================================================================+// Module: Classic Hatch+// =============================================================================+// ---------------------------------------------------------------------------// Hatch State// ---------------------------------------------------------------------------@@ -20,10 +20,20 @@ State.hatch = {hBrush: false,};+/**+ * Returns a shallow snapshot of the current hatch modifier state.+ *+ * @returns {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}}+ */export function HatchState() {return { ...State.hatch };}+/**+ * Restores hatch modifier state from a previously captured snapshot.+ *+ * @param {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}} state+ */export function HatchSetState(state) {State.hatch = { ...state };}@@ -32,6 +42,13 @@ export function HatchSetState(state) {// Public API// ---------------------------------------------------------------------------+/**+ * Activates classic scanline hatching for subsequent shapes.+ *+ * @param {number} [dist=5] Distance between scanlines.+ * @param {number} [angle=45] Hatch angle in the current p5 angle mode.+ * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [options]+ */export function hatch(dist = 5,angle = 45,@@ -44,36 +61,57 @@ export function hatch(s.options = options;}+/**+ * Overrides the brush, color, and weight used specifically for hatch strokes.+ *+ * @param {string} brush+ * @param {string|p5.Color} [color="black"]+ * @param {number} [weight=1]+ */export function hatchStyle(brush, color = "black", weight = 1) {State.hatch.hBrush = { brush, color, weight };}+/**+ * Deactivates hatching and clears any hatch-specific brush override.+ */export function noHatch() {State.hatch.isActive = false;State.hatch.hBrush = false;}// ----------------------------------------------------------------------------// Scanline Hatching+// Scanline Generation// ---------------------------------------------------------------------------/**- * Computes hatch segments for a polygon via scanline intersection.- * Rotates vertices so hatch lines become horizontal, scans for edge- * crossings, then rotates intersections back to original space.+ * Computes hatch segments for one polygon by rotating it into scanline space,+ * intersecting horizontal scanlines against its edges, and rotating the+ * resulting segments back into canvas space.+ *+ * @param {Polygon} polygon+ * @param {number} angle Hatch angle in degrees.+ * @param {number} dist Base scanline spacing.+ * @param {number} gradient Multiplicative spacing growth per scanline.+ * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}*/function scanlineHatch(polygon, angle, dist, gradient) {const rad = (angle * Math.PI) / 180;- const cosA = Math.cos(rad), sinA = Math.sin(rad);- const cosB = Math.cos(-rad), sinB = Math.sin(-rad);+ const cosA = Math.cos(rad),+ sinA = Math.sin(rad);+ const cosB = Math.cos(-rad),+ sinB = Math.sin(-rad);- const verts = polygon.a, n = verts.length;+ const verts = polygon.a,+ n = verts.length;// Rotate vertices; track Y extentconst rotated = new Array(n);- let minY = Infinity, maxY = -Infinity;+ let minY = Infinity,+ maxY = -Infinity;for (let i = 0; i < n; i++) {- const x = verts[i][0], y = verts[i][1];+ const x = verts[i][0],+ y = verts[i][1];const r = [x * cosA - y * sinA, x * sinA + y * cosA];rotated[i] = r;if (r[1] < minY) minY = r[1];@@ -83,26 +121,34 @@ function scanlineHatch(polygon, angle, dist, gradient) {// Build edge list (skip horizontal edges)const edges = [];for (let i = 0; i < n; i++) {- const a = rotated[i], b = rotated[(i + 1) % n];+ const a = rotated[i],+ b = rotated[(i + 1) % n];if (a[1] !== b[1]) edges.push(a, b);}const eLen = edges.length;// Scan, find crossings, rotate backconst segments = [];- let Y = minY + dist * 0.5, step = dist;+ let Y = minY + dist * 0.5,+ step = dist;while (Y < maxY) {const cx = [];for (let i = 0; i < eLen; i += 2) {- const y1 = edges[i][1], y2 = edges[i + 1][1];+ const y1 = edges[i][1],+ y2 = edges[i + 1][1];if ((y1 <= Y && Y < y2) || (y2 <= Y && Y < y1))- cx.push(edges[i][0] + ((Y - y1) / (y2 - y1)) * (edges[i + 1][0] - edges[i][0]));+ cx.push(+ edges[i][0] + ((Y - y1) / (y2 - y1)) * (edges[i + 1][0] - edges[i][0])+ );}cx.sort((a, b) => a - b);for (let i = 0; i < cx.length - 1; i += 2) {segments.push({- x1: cx[i] * cosB - Y * sinB, y1: cx[i] * sinB + Y * cosB,- x2: cx[i + 1] * cosB - Y * sinB, y2: cx[i + 1] * sinB + Y * cosB,+ scanY: Y,+ x1: cx[i] * cosB - Y * sinB,+ y1: cx[i] * sinB + Y * cosB,+ x2: cx[i + 1] * cosB - Y * sinB,+ y2: cx[i + 1] * sinB + Y * cosB,});}Y += step;@@ -111,58 +157,170 @@ function scanlineHatch(polygon, angle, dist, gradient) {return segments;}+/**+ * Collects and orders hatch segments for one polygon or a polygon list.+ *+ * Segments are sorted in scanline traversal order so downstream rendering can+ * optionally connect them into a continuous serpentine path.+ *+ * @param {Polygon|Polygon[]} polygons+ * @param {number} dist+ * @param {number} angle+ * @param {number} gradient+ * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}+ */+function getHatchSegments(polygons, dist, angle, gradient) {+ if (!Array.isArray(polygons)) polygons = [polygons];+ const segs = [];+ for (const poly of polygons) {+ for (const s of scanlineHatch(poly, angle, dist, gradient)) segs.push(s);+ }+ segs.sort((a, b) => (a.scanY === b.scanY ? a.x1 - b.x1 : a.scanY - b.scanY));+ return segs;+}+// ----------------------------------------------------------------------------// Create Hatch+// Hatch Configuration// ----------------------------------------------------------------------------export function createHatch(polygons) {- const dist = State.hatch.dist;- const angle = ((State.hatch.angle % 180) + 180) % 180;- const options = State.hatch.options;-+/**+ * Runs hatch drawing with the temporary hatch-specific brush style if one is active,+ * then restores the outer stroke state.+ *+ * @param {() => void} drawFn+ */+function withHatchStyle(drawFn) {const save = BrushState();if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));- if (!Array.isArray(polygons)) polygons = [polygons];+ drawFn();+ BrushSetState(save);+}+/**+ * Resolves the active hatch parameters and precomputes the ordered scanline segments.+ *+ * @param {Polygon|Polygon[]} polygons+ * @returns {{dist:number, options:Object, segs:Object[]}}+ */+function getActiveHatchConfig(polygons) {+ const dist = State.hatch.dist;+ const angle = ((State.hatch.angle % 180) + 180) % 180;+ const options = State.hatch.options;const gradient = options.gradient ? map(options.gradient, 0, 1, 1, 1.1, true) : 1;+ const segs = getHatchSegments(polygons, dist, angle, gradient);+ return { dist, options, segs };+}- const segs = [];- for (const poly of polygons)- for (const s of scanlineHatch(poly, angle, dist, gradient)) segs.push(s);- segs.sort((a, b) => a.x1 === b.x1 ? a.y1 - b.y1 : a.x1 - b.x1);+// ---------------------------------------------------------------------------+// Hatch Lines+// ---------------------------------------------------------------------------+/**+ * Expands ordered hatch segments into the actual line list that will be drawn.+ *+ * This includes endpoint jitter when `rand` is active and inserts the serpentine+ * connector lines when `continuous` is enabled.+ *+ * @param {Polygon|Polygon[]} polygons+ * @returns {{x1:number, y1:number, x2:number, y2:number, scanY:number, isConnector:boolean}[]}+ */+export function getHatchLines(polygons) {+ const { dist, options, segs } = getActiveHatchConfig(polygons);const r = options.rand || 0;+ const lines = [];+for (let j = 0; j < segs.length; j++) {const s = segs[j];let x1 = s.x1, y1 = s.y1, x2 = s.x2, y2 = s.y2;if (r) {- x1 += r * dist * rr(-1, 1);- y1 += r * dist * rr(-1, 1);- x2 += r * dist * rr(-1, 1);- y2 += r * dist * rr(-1, 1);+ x1 += 2 * r * dist * rr(-1, 1);+ y1 += 2 * r * dist * rr(-1, 1);+ x2 += 2 * r * dist * rr(-1, 1);+ y2 += 2 * r * dist * rr(-1, 1);+ }+ const reverse = options.continuous && j % 2 === 1;+ const line = reverse+ ? { x1: x2, y1: y2, x2: x1, y2: y1, scanY: s.scanY, isConnector: false }+ : { x1, y1, x2, y2, scanY: s.scanY, isConnector: false };+ lines.push(line);+ if (j > 0 && options.continuous) {+ const prev = lines[lines.length - 2];+ lines.push({+ x1: prev.x2,+ y1: prev.y2,+ x2: line.x1,+ y2: line.y1,+ scanY: s.scanY,+ isConnector: true,+ });}- line(x1, y1, x2, y2);- if (j > 0 && options.continuous) line(segs[j - 1].x2, segs[j - 1].y2, x1, y1);}- BrushSetState(save);+ return lines;+}++// ---------------------------------------------------------------------------+// Hatch Rendering+// ---------------------------------------------------------------------------++/**+ * Iterates the generated hatch lines and delegates the actual rendering of each+ * segment to the provided callback.+ *+ * @param {Polygon|Polygon[]} polygons+ * @param {(x1:number, y1:number, x2:number, y2:number, index:number, segs:Object[]) => void} drawSegment+ */+function renderHatchSegments(polygons, drawSegment) {+ const segs = getHatchLines(polygons);+ withHatchStyle(() => {+ for (let j = 0; j < segs.length; j++) {+ const s = segs[j];+ drawSegment(s.x1, s.y1, s.x2, s.y2, j, segs);+ }+ });+}++/**+ * Draws classic hatch lines over one polygon or an array of polygons.+ *+ * @param {Polygon|Polygon[]} polygons+ */+export function createHatch(polygons) {+ renderHatchSegments(polygons, (x1, y1, x2, y2) => {+ line(x1, y1, x2, y2);+ });}// ---------------------------------------------------------------------------// Prototype Extensions// ---------------------------------------------------------------------------+/**+ * Applies the currently active hatch modifier to a polygon, or temporarily+ * overrides hatch parameters for this call only.+ *+ * @param {number|false} [_dist=false]+ * @param {number} [_angle]+ * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [_options]+ */Polygon.prototype.hatch = function (_dist = false, _angle, _options) {let state = HatchState();if (_dist) hatch(_dist, _angle, _options);- if (state.isActive) createHatch(this);+ if (State.hatch.isActive) createHatch(this);HatchSetState(state);};+/**+ * Converts the plot to a polygon and applies the currently active hatch modifier.+ *+ * @param {number} x+ * @param {number} y+ * @param {number} scale+ */Plot.prototype.hatch = function (x, y, scale) {if (HatchState().isActive) {if (this.origin) (x = this.origin[0]), (y = this.origin[1]), (scale = 1);- this.pol = this.genPol(x, y, scale, 0.25);+ this.pol = this.genPol(x, y, scale, 0.3);this.pol.hatch();}};diff --git a/src/hatch/mass.js b/src/hatch/mass.jsnew file mode 100644index 0000000..6179db1--- /dev/null+++ b/src/hatch/mass.js@@ -0,0 +1,403 @@+// =============================================================================+// Module: Mass+// =============================================================================++import { State } from "../core/color.js";+import { Renderer } from "../core/target.js";+import { arc } from "../core/primitives.js";+import { Polygon } from "../core/polygon.js";+import { Plot } from "../core/plot.js";+import { rr2, dist, calcAngle } from "../core/utils.js";+import { HatchState, HatchSetState, hatch, getHatchLines } from "./hatch.js";+import { BrushState, BrushSetState, getBrushParams, set } from "../stroke/stroke.js";+import { wiggle } from "../core/flowfield.js";++// ---------------------------------------------------------------------------+// Mass State+// ---------------------------------------------------------------------------++State.mass = {+ isActive: false,+ brush: null,+ color: null,+ options: {},+};++/**+ * Returns a shallow copy of the current mass state.+ * @returns {object}+ */+export function MassState() {+ return { ...State.mass };+}++/**+ * Restores a previously saved mass state.+ * @param {object} state+ */+export function MassSetState(state) {+ State.mass = { ...state };+}++/**+ * Enables massing mode with a brush, color, and optional configuration.+ *+ * @param {string} brush - Brush name to use for the mass pass.+ * @param {string|Color} color - Color to use for the mass pass.+ * @param {object} [options={}] - Massing options such as precision, strength, gradient, and outline.+ */+export function mass(brush, color, options = {}) {+ State.mass.brush = brush;+ State.mass.color = color;+ State.mass.options = options;+ State.mass.isActive = true;+}++/**+ * Disables massing mode for subsequent geometry.+ */+export function noMass() {+ State.mass.isActive = false;+ State.mass.brush = null;+ State.mass.color = null;+ State.mass.options = {};+}++// ---------------------------------------------------------------------------+// Polygon Preparation+// ---------------------------------------------------------------------------++/**+ * Returns a translated copy of a polygon.+ * Used to build the secondary mass layers from an existing base polygon.+ * @param {Polygon} polygon+ * @param {number} jitterX+ * @param {number} jitterY+ * @returns {Polygon}+ */+function jitterPolygon(polygon, jitterX, jitterY) {+ return new Polygon(+ polygon.vertices.map((vertex) => [vertex.x + jitterX, vertex.y + jitterY]),+ );+}++/**+ * Builds the three polygons used for a mass pass.+ * Both polygon and plot inputs use one base polygon plus two translated copies,+ * so plot-based massing only needs a single `genPol(...)` call.+ * @param {Polygon|Plot} shape+ * @param {number|false} x+ * @param {number} y+ * @param {number} scale+ * @returns {Polygon[]}+ */+function getMassPolygons(shape, x, y, scale) {+ const isPolygon = x === false;+ const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;+ const basePolygon = isPolygon ? shape : shape.genPol(x, y, scale, 0.15);+ const maxJitter = Math.min(scatter * 2, 5);+ const jitters = [+ [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],+ [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],+ ];++ return [+ basePolygon,+ jitterPolygon(basePolygon, jitters[0][0], jitters[0][1]),+ jitterPolygon(basePolygon, jitters[1][0], jitters[1][1]),+ ];+}++// ---------------------------------------------------------------------------+// Angle & Bounds Helpers+// ---------------------------------------------------------------------------++/**+ * Converts degree values into the current p5 angle mode units.+ * @param {number} angle+ * @returns {number}+ */+function degreesToCurrentAngleMode(angle) {+ return Renderer &&+ typeof Renderer.angleMode === "function" &&+ Renderer.angleMode() === Renderer.RADIANS+ ? (angle * Math.PI) / 180+ : angle;+}++/**+ * Computes an axis-aligned bounding box for a polygon.+ * The diagonal is used as a size reference for pivot distance.+ * @param {Polygon} polygon+ * @returns {{minX:number,minY:number,maxX:number,maxY:number,cx:number,cy:number,size:number}}+ */+function getPolygonBounds(polygon) {+ const points = polygon?.a ?? [];+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;+ for (const [x, y] of points) {+ if (x < minX) minX = x;+ if (y < minY) minY = y;+ if (x > maxX) maxX = x;+ if (y > maxY) maxY = y;+ }+ return {+ minX,+ minY,+ maxX,+ maxY,+ cx: (minX + maxX) / 2,+ cy: (minY + maxY) / 2,+ size: Math.hypot(maxX - minX, maxY - minY),+ };+}++// ---------------------------------------------------------------------------+// Pivot Geometry+// ---------------------------------------------------------------------------++/**+ * Chooses the diagonal corner family for a whole mass gesture.+ * Positive-angle hatching uses either bottom-right or top-left; negative-angle+ * hatching uses either bottom-left or top-right.+ * @param {number} angleDeg+ * @returns {[number, number]}+ */+function getPivotBias(angleDeg) {+ const normalizedAngle = ((((angleDeg + 90) % 180) + 180) % 180) - 90;+ if (normalizedAngle >= 0) {+ return rr2() < 0.5 ? [1, 1] : [-1, -1];+ } else {+ return rr2() < 0.5 ? [-1, 1] : [1, -1];+ }+}++/**+ * Places the global pivot anchor outside the polygon, along the selected bias.+ * Distance varies per layer while the bias stays fixed for the whole mass.+ * @param {Polygon} polygon+ * @param {[number, number]} bias+ * @returns {{x:number,y:number}}+ */+function getPivotAnchor(polygon, bias) {+ const bounds = getPolygonBounds(polygon);+ const offset = bounds.size * rr2(0.6, 1.4);+ const [sx, sy] = bias;+ return {+ x: bounds.cx + sx * offset,+ y: bounds.cy + sy * offset,+ };+}++/**+ * Projects the global pivot anchor onto the perpendicular bisector of a line.+ * This yields a valid circle center equidistant from both endpoints.+ * @param {{x:number,y:number}} anchor+ * @param {number} x1+ * @param {number} y1+ * @param {number} x2+ * @param {number} y2+ * @returns {{x:number,y:number}|null}+ */+function projectAnchorToBisector(anchor, x1, y1, x2, y2) {+ const mx = (x1 + x2) / 2;+ const my = (y1 + y2) / 2;+ const dx = x2 - x1;+ const dy = y2 - y1;+ const length = Math.hypot(dx, dy);+ if (!length) return null;+ const nx = -dy / length;+ const ny = dx / length;+ const offset = (anchor.x - mx) * nx + (anchor.y - my) * ny;+ return {+ x: mx + nx * offset,+ y: my + ny * offset,+ };+}++/**+ * Returns the shortest arc between two endpoints around a given center.+ * The returned angles are already converted into the current p5 angle mode.+ * @param {number} cx+ * @param {number} cy+ * @param {number} x1+ * @param {number} y1+ * @param {number} x2+ * @param {number} y2+ * @returns {[number, number]}+ */+function getShortArcAngles(cx, cy, x1, y1, x2, y2) {+ let startDeg = calcAngle(cx, cy, x1, y1);+ let endDeg = calcAngle(cx, cy, x2, y2);+ const sweep = ((endDeg - startDeg) % 360 + 360) % 360;+ if (sweep > 180) [startDeg, endDeg] = [endDeg, startDeg];+ return [+ degreesToCurrentAngleMode(startDeg),+ degreesToCurrentAngleMode(endDeg),+ ];+}++/**+ * Splits a hatch line into two slightly separated segments so some gestures+ * read as interrupted rather than perfectly continuous.+ * @param {{x1:number,y1:number,x2:number,y2:number}} seg+ * @returns {Array<{x1:number,y1:number,x2:number,y2:number}>}+ */+function splitSegment(seg) {+ const t = rr2(0.35, 0.65);+ const mx = seg.x1 + (seg.x2 - seg.x1) * t;+ const my = seg.y1 + (seg.y2 - seg.y1) * t;+ const dx = seg.x2 - seg.x1;+ const dy = seg.y2 - seg.y1;+ const length = Math.hypot(dx, dy) || 1;+ const gap = rr2(0.04, 0.1) * length;+ const gx = (dx / length) * gap * 0.5;+ const gy = (dy / length) * gap * 0.5;+ return [+ { x1: seg.x1, y1: seg.y1, x2: mx - gx, y2: my - gy },+ { x1: mx + gx, y1: my + gy, x2: seg.x2, y2: seg.y2 },+ ];+}++// ---------------------------------------------------------------------------+// Mass Rendering+// ---------------------------------------------------------------------------++/**+ * Draws one polygon of the mass as a family of arcs derived from hatch lines.+ * The same pivot bias is used across layers, while each layer gets its own+ * anchor distance from the shape.+ * @param {Polygon} polygon+ * @param {[number, number]} pivotBias+ */+function drawMassArcs(polygon, pivotBias) {+ const anchor = getPivotAnchor(polygon, pivotBias);+ for (const seg of getHatchLines(polygon)) {+ const parts = !seg.isConnector && rr2() < 0.35 ? splitSegment(seg) : [seg];+ for (const part of parts) {+ const center = projectAnchorToBisector(anchor, part.x1, part.y1, part.x2, part.y2);+ if (!center) continue;+ const radius = dist(center.x, center.y, part.x1, part.y1);+ if (!radius) continue;+ const [startAngle, endAngle] = getShortArcAngles(+ center.x,+ center.y,+ part.x1,+ part.y1,+ part.x2,+ part.y2,+ );+ arc(center.x, center.y, radius, startAngle, endAngle);+ }+ }+}++/**+ * Configures a hatch pass and immediately reinterprets the generated lines as arcs.+ * @param {Polygon} polygon+ * @param {number} dist+ * @param {number} angle+ * @param {object} options+ * @param {[number, number]} pivotBias+ */+function drawMassPass(polygon, dist, angle, options, pivotBias) {+ hatch(dist, angle, options);+ drawMassArcs(polygon, pivotBias);+}++/**+ * Creates the built-in "massing" effect for a polygon or plot.+ * A mass is built from up to three jittered polygon layers, each hatched and+ * then redrawn as arc gestures around a shared pivot bias.+ * @param {Polygon|Plot} shape+ * @param {number|false} x+ * @param {number} y+ * @param {number} scale+ */+export function createMass(shape, x, y, scale) {+ const pols = getMassPolygons(shape, x, y, scale);+ const hatchState = HatchState();+ const brushState = BrushState();+ const fieldState = { ...State.field };+ const precision = State.mass.options?.precision ?? 0.5;+ const strength = State.mass.options?.strength ?? 1;+ const gradient = State.mass.options?.gradient ?? 0.1;+ const outline = State.mass.options?.outline ?? false;+ const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;+ const hatchDist = 1.6 * rr2(scatter * 0.65, scatter * 0.85) - 0.4 * gradient;+ const baseAngle = rr2(-90, 90);+ const pivotBias = getPivotBias(baseAngle);++ set(State.mass.brush, State.mass.color, 1);+ wiggle(2 - precision);+ if (outline) pols[0].draw();++ drawMassPass(+ pols[0],+ hatchDist * 0.9,+ degreesToCurrentAngleMode(baseAngle),+ {+ gradient,+ rand: 2 - 2 * precision,+ continuous: true,+ },+ pivotBias,+ );++ if (strength > 0.33) {+ drawMassPass(+ pols[1],+ hatchDist,+ degreesToCurrentAngleMode(baseAngle + 20 * rr2(-1, 1)),+ {+ gradient,+ rand: 0.6 - 0.6 * precision,+ continuous: true,+ },+ pivotBias,+ );+ }++ if (strength > 0.66) {+ drawMassPass(+ pols[2],+ hatchDist * 0.8,+ degreesToCurrentAngleMode(baseAngle + 15 * rr2(-1, 1)),+ {+ gradient,+ rand: 0.6 - 0.6 * precision,+ continuous: true,+ },+ pivotBias,+ );+ }++ BrushSetState(brushState);+ HatchSetState(hatchState);+ State.field = { ...fieldState };+}++// ---------------------------------------------------------------------------+// Prototype Extensions+// ---------------------------------------------------------------------------++/**+ * Applies massing to polygon geometry.+ */+Polygon.prototype.mass = function () {+ if (State.mass?.isActive) {+ createMass(this, false);+ }+};++/**+ * Applies massing to plots by generating their polygon first.+ * @param {number} x+ * @param {number} y+ * @param {number} scale+ */+Plot.prototype.mass = function (x, y, scale) {+ if (State.mass?.isActive) {+ if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));+ createMass(this, x, y, scale);+ }+};diff --git a/src/index.js b/src/index.jsindex ad3acb9..7e38488 100644--- a/src/index.js+++ b/src/index.js@@ -60,7 +60,8 @@export { weightedRand as wRand } from "./core/utils.js";// Color Blending-export { load, instance } from "./core/color.js";+export { load } from "./core/color.js";+export { instance } from "./core/target.js";// Matrix transformations, FlowField and Position Classexport {@@ -115,17 +116,25 @@ export {noHatch,createHatch as hatchArray,} from "./hatch/hatch.js";+export {+ mass,+ noMass+} from "./hatch/mass.js";// Fillexport { fill, noFill, fillTexture, fillBleed } from "./fill/fill.js";+export { wash, noWash } from "./fill/wash.js";// p5 addon registrationimport {- Mix,+ Mix,+ flushActiveComposite,+} from "./core/color.js";+import {instance as bindInstance,activateInstance,deactivateInstance,-} from "./core/color.js";+} from "./core/target.js";import { push as brushPush, pop as brushPop } from "./core/save.js";import { seed as brushSeed, noiseSeed as brushNoiseSeed } from "./core/utils.js";@@ -140,13 +149,13 @@ function registerAddon(_p5, fn, lifecycles) {lifecycles.postsetup = function () {bindInstance(this);- Mix.blend(false, true);+ flushActiveComposite();deactivateInstance();};lifecycles.postdraw = function () {bindInstance(this);- Mix.blend(false, true);+ flushActiveComposite();deactivateInstance();};diff --git a/src/stroke/composite.js b/src/stroke/composite.jsnew file mode 100644index 0000000..01ba3c6--- /dev/null+++ b/src/stroke/composite.js@@ -0,0 +1,143 @@+import * as Color from "../core/color.js";++let isStrokeCompositeRegistered = false;+const DIRTY_BRUSH_PADDING = 2;++// =============================================================================+// Section: Helpers+// =============================================================================+/**+ * Returns whether the current stroke mask framebuffer must be recreated.+ * This happens when the renderer has no mask yet, or when the canvas size or+ * pixel density changed since the last allocation.+ *+ * @param {object} Renderer - Active p5 renderer/sketch.+ * @param {number} Cwidth - Target width in sketch units.+ * @param {number} Cheight - Target height in sketch units.+ * @param {number} Density - Active pixel density.+ * @returns {boolean} True when the stroke mask must be rebuilt.+ */+function needsStrokeMask(Renderer, Cwidth, Cheight, Density) {+ return (+ !Renderer.glMask ||+ Renderer.glMask.width !== Cwidth ||+ Renderer.glMask.height !== Cheight ||+ (typeof Renderer.glMask.pixelDensity === "function" &&+ Renderer.glMask.pixelDensity() !== Density)+ );+}++// =============================================================================+// Section: Resource Management+// =============================================================================+/**+ * Ensures the stroke compositor owns a framebuffer-backed mask with the current+ * canvas dimensions. Stroke stamps are rendered into this mask in WebGL before+ * being blended into the main target.+ *+ * @param {object} Renderer - Active p5 renderer/sketch.+ * @param {number} Cwidth - Target width in sketch units.+ * @param {number} Cheight - Target height in sketch units.+ * @param {number} Density - Active pixel density.+ * @returns {object} The framebuffer used as stroke mask.+ */+export function ensureStrokeCompositeResources(+ Renderer,+ Cwidth,+ Cheight,+ Density,+) {+ if (needsStrokeMask(Renderer, Cwidth, Cheight, Density)) {+ if (Renderer.glMask?.remove) Renderer.glMask.remove();+ Renderer.glMask = Renderer.createFramebuffer({+ width: Cwidth,+ height: Cheight,+ density: Density,+ antialias: false,+ depth: false,+ stencil: false,+ });+ }++ Renderer.glMask.dirtyRect ??= null;+ Renderer.glMask.isDrawn ??= false;+ return Renderer.glMask;+}++// =============================================================================+// Section: Mask Lifecycle+// =============================================================================+/**+ * Clears the current stroke mask and resets its bookkeeping flags.+ *+ * @param {object|null} target - Stroke mask framebuffer.+ * @param {Function} clearTarget - Shared low-level clear helper from core.+ */+export function clearStrokeMask(target, clearTarget) {+ if (!target) return;+ clearTarget(target);+ target.isDrawn = false;+ target.dirtyRect = null;+}++// =============================================================================+// Section: Composite Bounds+// =============================================================================+/**+ * Returns the rect that should be composited from the stroke mask into the+ * main canvas. Stroke bounds are normally tight dirty rects, but when drawing+ * into an active framebuffer we keep the result conservative and composite the+ * full target.+ *+ * @param {object|null} target - Stroke mask framebuffer.+ * @param {Function} getActiveFramebuffer - Returns the currently bound framebuffer.+ * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.+ * @param {Function} expandDirtyRect - Expands a rect by a constant padding.+ * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.+ * @param {number} padding - Extra brush padding in pixels.+ * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.+ */+export function getStrokeCompositeRect(+ target,+ getActiveFramebuffer,+ getFullDirtyRect,+ expandDirtyRect,+ normalizeDirtyRect,+) {+ if (!target) return null;+ if (!target.dirtyRect) return getFullDirtyRect();+ if (getActiveFramebuffer()) return getFullDirtyRect();+ return normalizeDirtyRect(+ expandDirtyRect(target.dirtyRect, DIRTY_BRUSH_PADDING),+ );+}++/**+ * Returns the resource that should be bound to the blend shader's `u_mask`+ * uniform for stroke compositing.+ *+ * @param {object} _Renderer - Active p5 renderer/sketch.+ * @param {object} mask - Stroke mask framebuffer.+ * @returns {object} Stroke mask framebuffer.+ */+export function getStrokeShaderMask(_Renderer, mask) {+ return mask;+}++// =============================================================================+// Section: Registration+// =============================================================================+/**+ * Registers the stroke compositor with the shared color/composite core.+ * Safe to call multiple times.+ */+export function initStrokeComposite() {+ if (isStrokeCompositeRegistered) return;+ Color.registerStrokeComposite?.({+ ensureResources: ensureStrokeCompositeResources,+ clearMask: clearStrokeMask,+ getCompositeRect: getStrokeCompositeRect,+ getShaderMask: getStrokeShaderMask,+ });+ isStrokeCompositeRegistered = true;+}diff --git a/src/stroke/gl_draw.js b/src/stroke/gl_draw.jsindex 575ace5..02343be 100644--- a/src/stroke/gl_draw.js+++ b/src/stroke/gl_draw.js@@ -7,14 +7,11 @@* then flushes those queues into the shared framebuffer-backed brush mask.*/+import { Cwidth, Cheight, Density, Renderer } from "../core/target.js";import {Mix,- Cwidth,- Cheight,isMixReady,- Density,State,- Renderer,} from "../core/color.js";import { Matrix } from "../core/flowfield.js";import { createProgram } from "../core/gl/utils.js";diff --git a/src/stroke/stroke.js b/src/stroke/stroke.jsindex 89a6377..d07458d 100644--- a/src/stroke/stroke.js+++ b/src/stroke/stroke.js@@ -11,14 +11,11 @@* the Brush module facilitates the creation of realistic and expressive stroke effects.*/+// Core imports+import { Cwidth, Cheight, Renderer, Instance, isCanvasReady } from "../core/target.js";import {Mix,- Cwidth,- Cheight,State,- Renderer,- Instance,- isCanvasReady,} from "../core/color.js";import {rr,@@ -30,11 +27,16 @@ import {gaussian,rArray,noise,- _onSeed,+ _onSeed,+ cos,+ sin} from "../core/utils.js";-import { Position, Matrix, isFieldReady } from "../core/flowfield.js";+import { Position, isFieldReady } from "../core/flowfield.js";import { Polygon } from "../core/polygon.js";import { Plot } from "../core/plot.js";++// Internal module imports+import { initStrokeComposite } from "./composite.js";import {isReady,glDraw,@@ -45,6 +47,8 @@ import {snapshotMatrix,} from "./gl_draw.js";+initStrokeComposite(); // Register the stroke composite system; ensures p5's WebGL mode is patched to support offscreen stroke rendering and compositing+// ---------------------------------------------------------------------------// Brush State and Helpers// ---------------------------------------------------------------------------@@ -55,21 +59,12 @@ import {State.stroke = {color: null,weight: 1,- clipWindow: null,type: "HB",isActive: false,opacity: 1,};let list = new Map();-let _strokeTransform = {- a: 1,- b: 0,- c: 0,- d: 1,- tx: 0,- ty: 0,-};function getBrushFactory() {return Renderer ?? Instance ?? window.self.p5.instance;@@ -175,6 +170,8 @@ export function add(name, params) {const validTypes = ["marker", "custom", "image", "spray"];params.type = validTypes.includes(params.type) ? params.type : "default";if (params.markerTip === undefined) params.markerTip = true;+ if (params.noise === undefined) params.noise = 0.3;+ params.noise = Math.max(0, Math.min(1, params.noise));// Accept legacy param names for backward compatibilityif (params.vibration !== undefined && params.scatter === undefined)params.scatter = params.vibration;@@ -230,6 +227,10 @@ export function box() {return [...list.keys()];}+export function getBrushParams(brushName) {+ return list.get(brushName)?.param ?? null;+}+/*** Scales standard brush parameters by the provided factor.* @param {number} scaleFactor - The scaling factor to apply.@@ -296,41 +297,6 @@ export function noStroke() {State.stroke.isActive = false;}-function snapshotTransform() {- return {- a: Matrix.a(),- b: Matrix.b(),- c: Matrix.c(),- d: Matrix.d(),- tx: Matrix.x(),- ty: Matrix.y(),- };-}--function invertTransform(transform) {- const det = transform.a * transform.d - transform.b * transform.c;- if (Math.abs(det) < 1e-12) return null;-- return {- a: transform.d / det,- b: -transform.b / det,- c: -transform.c / det,- d: transform.a / det,- tx: (transform.c * transform.ty - transform.d * transform.tx) / det,- ty: (transform.b * transform.tx - transform.a * transform.ty) / det,- };-}--function normalizeRegion(region) {- const [x1, y1, x2, y2] = region;- return {- minX: Math.min(x1, x2),- minY: Math.min(y1, y2),- maxX: Math.max(x1, x2),- maxY: Math.max(y1, y2),- };-}-/*** Defines a clipping region for strokes.* The region uses the same coordinate space as brush drawing commands,@@ -339,23 +305,14 @@ function normalizeRegion(region) {*/export function clip(region) {isCanvasReady();- const inverse = invertTransform(snapshotTransform());- if (!inverse) {- throw new Error(- "brush.clip() cannot be used with a non-invertible transform.",- );- }- State.stroke.clipWindow = {- bounds: normalizeRegion(region),- inverse,- };+ return region;}/*** Disables the clipping region.*/export function noClip() {- State.stroke.clipWindow = null;+ return;}// ---------------------------------------------------------------------------@@ -373,7 +330,6 @@ const current = {};*/function initializeDrawingState(x, y, length, plot = false) {snapshotMatrix();- _strokeTransform = snapshotTransform();_position = new Position(x + Cwidth / 2, y + Cheight / 2);_length = length;_plot = plot;@@ -399,20 +355,27 @@ function draw(angleScale, isPlot) {const totalSteps = Math.round((_length * (isPlot ? angleScale : 1)) / stepSize,);+ current.pressureCount = 10;+ current.cachedPressure = undefined;+ current.lineNoiseCount = 5;+ current.cachedLineNoise = undefined;+for (let i = 0; i < totalSteps; i++) {if (gaussians.length < totalSteps * 2) {gaussians.push(gaussian());}tip();- isPlot- ? _position.plotTo(- _plot,- stepSize,- stepSize,- angleScale,- i < 10 ? true : false,- )- : _position._moveToDegrees(angleScale, stepSize, stepSize);+ if (isPlot) {+ _position.plotTo(+ _plot,+ stepSize,+ stepSize,+ angleScale,+ i < 10 ? true : false,+ );+ } else {+ _position._moveToDegrees(angleScale, stepSize, stepSize);+ }}restoreState();}@@ -444,13 +407,12 @@ function saveState() {}[current.min, current.max] = pressure.min_max;- current.noiseoffset = 0.03;+ current.noiseoffset = 0.05 * current.p.noise;// Cache stroke direction for direction-aware dispersion (non-plot strokes only)if (!_plot) {- const dirRad = (_dir * Math.PI) / 180;- current.cos = Math.cos(dirRad);- current.sin = Math.sin(dirRad);+ current.cos = cos(_dir);+ current.sin = sin(_dir);}// Ensure GL is ready and blend state@@ -463,36 +425,6 @@ function saveState() {// Set additional state valuescurrent.alpha = calculateAlpha();- // Pre-compute clip-check coefficients so isInsideClippingArea() needs no- // temporary objects and only one matrix×vector multiply per step instead of two.- {- const cw2 = Cwidth / 2, ch2 = Cheight / 2;- const T = _strokeTransform;- if (State.stroke.clipWindow) {- const { inverse: I, bounds: B } = State.stroke.clipWindow;- // Compose (I ∘ T) and fold the -cw2/-ch2 position offset into the translation- const ca = I.a * T.a + I.c * T.b, cc = I.a * T.c + I.c * T.d;- const cb = I.b * T.a + I.d * T.b, cd = I.b * T.c + I.d * T.d;- current.clipA = ca; current.clipB = cb;- current.clipC = cc; current.clipD = cd;- current.clipTX = I.a * T.tx + I.c * T.ty + I.tx - ca * cw2 - cc * ch2;- current.clipTY = I.b * T.tx + I.d * T.ty + I.ty - cb * cw2 - cd * ch2;- current.clipMinX = B.minX; current.clipMaxX = B.maxX;- current.clipMinY = B.minY; current.clipMaxY = B.maxY;- } else {- const o =- current.p.type === "custom" || current.p.type === "image"- ? Math.max(Cwidth * 0.05, getImageTipOverscan())- : Cwidth * 0.05;- current.clipA = T.a; current.clipB = T.b;- current.clipC = T.c; current.clipD = T.d;- current.clipTX = T.tx - T.a * cw2 - T.c * ch2;- current.clipTY = T.ty - T.b * cw2 - T.d * ch2;- current.clipMinX = -cw2 - o; current.clipMaxX = cw2 + o;- current.clipMinY = -ch2 - o; current.clipMaxY = ch2 + o;- }- }-markerTip();}@@ -511,16 +443,10 @@ function restoreState() {* Renders the brush tip based on current pressure and position.*/function tip() {- const insideClip = isInsideClippingArea();- if (!insideClip) return;const pressure = calculatePressure();- const lineNoise = map(- noise(current.seed + _position.plotted * 0.002, 0),- 0,- 1,- 1 - current.noiseoffset,- 1 + current.noiseoffset,- );+ const lineNoise = calculateLineNoise();++ if (lineNoise > rr(1,1.02) && rr(0,1) < 0.7) return;switch (current.p.type) {case "spray":drawSpray(pressure * lineNoise);@@ -543,9 +469,29 @@ function tip() {* @returns {number} The calculated pressure.*/function calculatePressure() {- return _plot- ? simPressure() * _plot.pressure(_position.plotted)- : simPressure();+ if (current.pressureCount >= 10 || current.cachedPressure === undefined) {+ current.cachedPressure = _plot+ ? simPressure() * _plot.pressure(_position.plotted)+ : simPressure();+ current.pressureCount = 0;+ }+ current.pressureCount++;+ return current.cachedPressure;+}++function calculateLineNoise() {+ if (current.lineNoiseCount >= 10 || current.cachedLineNoise === undefined) {+ current.cachedLineNoise = map(+ noise(current.seed + _position.plotted * 0.01, 0),+ -1,+ 1,+ 1 - current.noiseoffset,+ 1 + current.noiseoffset,+ );+ current.lineNoiseCount = 0;+ }+ current.lineNoiseCount++;+ return current.cachedLineNoise;}/**@@ -616,19 +562,6 @@ function calculateAlpha() {: current.p.opacity / Math.min(State.stroke.weight, 1.3);}-/**- * Checks if the current drawing position is within the clipping region.- * Uses coefficients pre-computed in saveState() — no object allocations,- * one fused matrix×vector multiply (both transforms composed at setup time).- * @returns {boolean} True if inside clipping area; false otherwise.- */-function isInsideClippingArea() {- const lx = current.clipA * _position.x + current.clipC * _position.y + current.clipTX;- if (lx < current.clipMinX || lx > current.clipMaxX) return false;- const ly = current.clipB * _position.x + current.clipD * _position.y + current.clipTY;- return ly >= current.clipMinY && ly <= current.clipMaxY;-}-/*** Calculates the step spacing based on the current brush parameters.* @returns {number} The spacing value.@@ -739,13 +672,18 @@ function drawDefault(pressure, wiggle = 1) {if (passesGate) {let dx, dy;if (_plot) {- dx = 0.7 * vibration * rr(-1, 1);- dy = vibration * rr(-1, 1);+ const plotAngle = _plot.angle(_position.plotted);+ const plotCos = cos(plotAngle);+ const plotSin = sin(plotAngle);+ const perp = vibration * rr(-1, 1);+ const along = 0.3 * vibration * rr(-1, 1);+ dx = perp * plotSin + along * plotCos;+ dy = perp * plotCos - along * plotSin;} else {const perp = vibration * rr(-1, 1);const along = 0.3 * vibration * rr(-1, 1);- dx = perp * -current.sin + along * current.cos;- dy = perp * current.cos + along * current.sin;+ dx = perp * current.sin + along * current.cos;+ dy = perp * current.cos - along * current.sin;}const diameter =pressure *@@ -768,17 +706,15 @@ function drawDefault(pressure, wiggle = 1) {*/function markerTip() {if (current.p.markerTip === false) return;- if (isInsideClippingArea()) {- let pressure = calculatePressure();- let alpha = current.alpha;- if (current.p.type === "marker") {- for (let s = 1; s < 10; s++) {- drawMarker((pressure * s) / 10, true, alpha * 8);- }- } else if (current.p.type === "custom" || current.p.type === "image") {- for (let s = 1; s < 5; s++) {- drawImageTip((pressure * s) / 10, alpha * 2);- }+ let pressure = calculatePressure();+ let alpha = current.alpha;+ if (current.p.type === "marker") {+ for (let s = 1; s < 10; s++) {+ drawMarker((pressure * s) / 10, true, alpha * 8);+ }+ } else if (current.p.type === "custom" || current.p.type === "image") {+ for (let s = 1; s < 5; s++) {+ drawImageTip((pressure * s) / 10, alpha * 2);}}}@@ -860,6 +796,7 @@ const _vals = ["tip","rotate","markerTip",+ "noise",];const _standard_brushes = [[@@ -886,6 +823,40 @@ const _standard_brushes = ["cpencil",[0.3, 0.55, 0.8, 7, 75, 0.1, { curve: [0.15, 0.2], min_max: [0.95, 1.2] }],],+ [+ "pastel",+ [+ 2.05 / 3,+ 13.4 / 3,+ 0.91,+ 28,+ 35,+ 0.085 / 3,+ { mode: "gaussian", curve: [0.4, 0.05], min_max: [1.09, 0.93] },+ "default",+ undefined,+ "natural",+ true,+ 1,+ ],+ ],+ [+ "crayon",+ [+ 0.9 / 3,+ 5.45 / 3,+ 0.75,+ 250,+ 159,+ 0.23 / 3,+ [1.1, 0.9],+ "default",+ undefined,+ "natural",+ true,+ 1,+ ],+ ],["charcoal",[diff --git a/test/fill.test.js b/test/fill.test.jsindex a1df10d..d3243d4 100644--- a/test/fill.test.js+++ b/test/fill.test.js@@ -19,13 +19,6 @@ const { blend, mockCtx, mockState } = vi.hoisted(() => ({}));vi.mock("../src/core/color.js", () => ({- Renderer: {- color: () => ({- _getBlue: () => 64,- _getGreen: () => 128,- _getRed: () => 255,- }),- },Mix: {blend,ctx: mockCtx,@@ -33,6 +26,17 @@ vi.mock("../src/core/color.js", () => ({justChanged: false,},State: mockState,+ registerFillComposite: () => {},+}));++vi.mock("../src/core/target.js", () => ({+ Renderer: {+ color: () => ({+ _getBlue: () => 64,+ _getGreen: () => 128,+ _getRed: () => 255,+ }),+ },Cwidth: 800,Cheight: 600,Density: 1,diff --git a/test/index.html b/test/index.htmlindex ee763ae..9a4297f 100644--- a/test/index.html+++ b/test/index.html@@ -184,13 +184,6 @@<span class="path">test/visual_suite.html</span></a>- <a class="card" href="./fill_issue_43.html">- <h3>Fill Issue 43</h3>- <p>Replays the reported 30+ fill repro with repeated rect and circle watercolor fills on a WEBGL canvas.</p>- <span class="meta">Regression</span>- <span class="path">test/fill_issue_43.html</span>- </a>-<a class="card" href="./fill_circle_explorer.html"><h3>Fill Circle Explorer</h3><p>Seeded single-shape page for inspecting watercolor fill bleed, opacity, texture, border, and palette color on a centered circle.</p>@@ -198,6 +191,20 @@<span class="path">test/fill_circle_explorer.html</span></a>+ <a class="card" href="./wash_test.html">+ <h3>Wash Test</h3>+ <p>Direct WEBGL wash page that draws five random rect and circle polygons with palette colors at full opacity.</p>+ <span class="meta">Coverage</span>+ <span class="path">test/wash_test.html</span>+ </a>++ <a class="card" href="./pastel_hatching_test.html">+ <h3>Pastel Hatching Test</h3>+ <p>Minimal global-mode sketch with a custom crayon brush and a single centered rectangle for pastel hatching experiments.</p>+ <span class="meta">Experiment</span>+ <span class="path">test/pastel_hatching_test.html</span>+ </a>+<a class="card" href="./angle_mode_test.html"><h3>Angle Mode Test</h3><p>Compares degrees, radians, mixed mode changes, stored hatch angles, low-level Position movement, and custom fields.</p>diff --git a/test/pastel_hatching_test.html b/test/pastel_hatching_test.htmlnew file mode 100644index 0000000..5683a0e--- /dev/null+++ b/test/pastel_hatching_test.html@@ -0,0 +1,253 @@+<!doctype html>+<html>+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>Pastel Hatching Test</title>+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.min.js"></script>+ <script src="../dist/p5.brush.js"></script>+ <style>+ :root {+ --paper: #f3eee2;+ --ink: #22313f;+ --muted: #52616e;+ --line: #d4c8b8;+ --panel: rgba(255, 252, 245, 0.86);+ --accent: #153e5c;+ }++ * { box-sizing: border-box; }++ body {+ margin: 0;+ color: var(--ink);+ background:+ radial-gradient(circle at top left, rgba(21, 62, 92, 0.08), transparent 24%),+ linear-gradient(180deg, #f7f2e7 0%, #ece3d3 100%);+ font-family: "Iowan Old Style", "Palatino Linotype", "Book Antiqua", Palatino, serif;+ }++ main {+ width: min(920px, calc(100vw - 24px));+ margin: 0 auto;+ padding: 18px 0 24px;+ display: grid;+ justify-items: center;+ }++ main > * { width: 100%; }++ .nav {+ margin-bottom: 14px;+ font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;+ }++ .nav a {+ color: var(--accent);+ text-decoration: none;+ }++ .nav a:hover { text-decoration: underline; }++ h1 {+ margin: 0 0 8px;+ font-size: clamp(24px, 3.6vw, 34px);+ letter-spacing: -0.04em;+ }++ p {+ margin: 0 0 8px;+ max-width: 760px;+ color: var(--muted);+ line-height: 1.45;+ font-size: 13px;+ }++ .workspace {+ margin-top: 18px;+ display: grid;+ grid-template-columns: 260px minmax(0, 1fr);+ gap: 18px;+ align-items: start;+ }++ button {+ border: 1px solid var(--line);+ border-radius: 999px;+ padding: 7px 12px;+ background: rgba(255, 252, 245, 0.95);+ color: var(--accent);+ font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;+ cursor: pointer;+ }++ button:hover {+ background: #fff;+ }++ .panel {+ border: 1px solid var(--line);+ border-radius: 8px;+ background: var(--panel);+ }++ #controls {+ padding: 14px 16px;+ display: grid;+ gap: 12px;+ align-self: start;+ }++ .top-row {+ display: flex;+ align-items: center;+ gap: 12px;+ flex-wrap: wrap;+ justify-content: space-between;+ font: 11px/1.4 Menlo, Monaco, "Courier New", monospace;+ }++ .seed {+ display: flex;+ align-items: center;+ gap: 8px;+ }++ .seed strong {+ color: var(--accent);+ font-weight: 600;+ }++ .control-grid {+ display: grid;+ grid-template-columns: 1fr;+ gap: 10px;+ align-items: center;+ font: 11px/1.4 Menlo, Monaco, "Courier New", monospace;+ }++ label {+ display: grid;+ gap: 6px;+ }++ .slider-row {+ display: flex;+ align-items: center;+ gap: 8px;+ }++ input[type="range"] {+ flex: 1;+ min-width: 0;+ }++ .val {+ min-width: 34px;+ color: var(--accent);+ text-align: right;+ }++ select {+ border: 1px solid var(--line);+ border-radius: 6px;+ background: #fbf8f0;+ color: var(--ink);+ font: inherit;+ padding: 6px 8px;+ }++ .checkbox-row {+ display: flex;+ align-items: center;+ gap: 8px;+ }++ #canvas-host {+ padding: 10px;+ display: grid;+ justify-content: center;+ width: 100%;+ overflow: hidden;+ }++ canvas {+ display: block;+ border-radius: 6px;+ max-width: 100%;+ max-height: min(78vh, 760px);+ height: auto !important;+ }++ @media (max-width: 820px) {+ .workspace {+ grid-template-columns: 1fr;+ }+ }+ </style>+ </head>+ <body>+ <main>+ <div class="nav"><a href="./index.html">All tests</a></div>+ <h1>Pastel Hatching Test</h1>+ <p>+ Minimal global-mode sketch with a custom crayon brush, scaled built-in brushes, and a single centered rectangle for trying pastel hatching ideas.+ </p>+ <div class="workspace">+ <div id="controls" class="panel">+ <div class="top-row">+ <div class="seed">+ <span>Seed</span>+ <strong id="seedVal">000000</strong>+ </div>+ <button id="refresh-seed" type="button">Refresh Seed</button>+ </div>++ <div class="control-grid">+ <label>+ Brush+ <select id="brushType">+ <option value="pastel">pastel</option>+ <option value="crayon">crayon</option>+ <option value="HB">HB</option>+ <option value="pen">pen</option>+ </select>+ </label>++ <label>+ Precision+ <div class="slider-row">+ <input type="range" id="precision" min="0" max="1" step="0.01" value="0.3" />+ <span class="val" id="precisionVal">0.3</span>+ </div>+ </label>++ <label>+ Strength+ <div class="slider-row">+ <input type="range" id="strength" min="0" max="1" step="0.01" value="0.6" />+ <span class="val" id="strengthVal">0.6</span>+ </div>+ </label>++ <label>+ Gradient+ <div class="slider-row">+ <input type="range" id="gradient" min="0" max="1" step="0.01" value="0.1" />+ <span class="val" id="gradientVal">0.1</span>+ </div>+ </label>++ <label class="checkbox-row">+ <input type="checkbox" id="outline" />+ Outline+ </label>+ </div>+ </div>++ <div id="canvas-host" class="panel"></div>+ </div>+ </main>+ <script src="./pastel_hatching_test.js"></script>+ </body>+</html>diff --git a/test/pastel_hatching_test.js b/test/pastel_hatching_test.jsnew file mode 100644index 0000000..228c02e--- /dev/null+++ b/test/pastel_hatching_test.js@@ -0,0 +1,116 @@+const PAPER = "#fffceb";+const PALETTE = ["#002185", "#003c32", "#fcd300", "#ff2702", "#6b9404"];+const CANVAS_W = 600;+const CANVAS_H = 600;+let currentSeed = Math.floor(Math.random() * 900000) + 100000;+const state = {+ brushType: "pastel",+ precision: 0.3,+ strength: 0.6,+ gradient: 0.1,+ outline: false,+};++const controls = {+ seedVal: document.getElementById("seedVal"),+ refreshSeed: document.getElementById("refresh-seed"),+ brushType: document.getElementById("brushType"),+ precision: document.getElementById("precision"),+ precisionVal: document.getElementById("precisionVal"),+ strength: document.getElementById("strength"),+ strengthVal: document.getElementById("strengthVal"),+ gradient: document.getElementById("gradient"),+ gradientVal: document.getElementById("gradientVal"),+ outline: document.getElementById("outline"),+};++function formatValue(value) {+ return Number.isInteger(value)+ ? String(value)+ : value.toFixed(2).replace(/0$/, "").replace(/\.$/, "");+}++function syncReadouts() {+ controls.seedVal.textContent = String(currentSeed).padStart(6, "0");+ controls.precisionVal.textContent = formatValue(state.precision);+ controls.strengthVal.textContent = formatValue(state.strength);+ controls.gradientVal.textContent = formatValue(state.gradient);+}++function queueRender() {+ redraw();+}++function setup() {+ const canvas = createCanvas(CANVAS_W, CANVAS_H, WEBGL);+ canvas.parent("canvas-host");+ brush.load();++ brush.scaleBrushes(3)++ noLoop();++ syncReadouts();++ if (controls.refreshSeed) {+ controls.refreshSeed.addEventListener("click", () => {+ currentSeed = Math.floor(Math.random() * 900000) + 100000;+ syncReadouts();+ queueRender();+ });+ }++ controls.brushType?.addEventListener("input", () => {+ state.brushType = controls.brushType.value;+ queueRender();+ });++ controls.precision?.addEventListener("input", () => {+ state.precision = Number(controls.precision.value);+ syncReadouts();+ queueRender();+ });++ controls.strength?.addEventListener("input", () => {+ state.strength = Number(controls.strength.value);+ syncReadouts();+ queueRender();+ });++ controls.gradient?.addEventListener("input", () => {+ state.gradient = Number(controls.gradient.value);+ syncReadouts();+ queueRender();+ });++ controls.outline?.addEventListener("input", () => {+ state.outline = controls.outline.checked;+ queueRender();+ });+}++function draw() {+ randomSeed(currentSeed);+ noiseSeed(currentSeed);+ syncReadouts();+ background(PAPER);+ translate(-width / 2, -height / 2);+ brush.wiggle();++ for (let i = 0; i < 3; i++) {+ brush.mass(state.brushType, random(PALETTE), {+ precision: state.precision,+ strength: state.strength,+ gradient: state.gradient,+ outline: state.outline,+ });+ brush.set("pen", "black", 1)+ brush.circle(+ random(CANVAS_W),+ random(CANVAS_H),+ CANVAS_W * random(0.2, 0.4),+ );+ brush.noMass();+ }+ noLoop();+}diff --git a/test/stroke_pressure.test.js b/test/stroke_pressure.test.jsindex 36c8ecc..15bd377 100644--- a/test/stroke_pressure.test.js+++ b/test/stroke_pressure.test.js@@ -2,11 +2,16 @@ import { describe, it, expect, vi } from "vitest";vi.mock("../src/core/color.js", () => ({Mix: {},+ State: {},+ isCanvasReady: () => {},+ registerStrokeComposite: () => {},+}));++vi.mock("../src/core/target.js", () => ({Cwidth: 800,Cheight: 600,- State: {},Renderer: {},- isCanvasReady: () => {},+ Instance: null,}));vi.mock("../src/core/utils.js", () => ({diff --git a/test/unit.test.js b/test/unit.test.jsindex a2319b9..1dce827 100644--- a/test/unit.test.js+++ b/test/unit.test.js@@ -15,6 +15,13 @@ const { currentAngleMode, mockState, plotInstances } = vi.hoisted(() => ({// Mock color.js (pulls in GLSL shaders and WebGL — not available in Node)vi.mock("../src/core/color.js", () => ({+ Mix: {},+ State: mockState,+ isCanvasReady: () => {},+ isMixReady: () => {},+}));++vi.mock("../src/core/target.js", () => ({Renderer: {angleMode: () => currentAngleMode.value,RADIANS: "radians",@@ -25,12 +32,8 @@ vi.mock("../src/core/color.js", () => ({},},},- Mix: {},- State: mockState,Cwidth: 800,Cheight: 600,- isCanvasReady: () => {},- isMixReady: () => {},}));vi.mock("../src/stroke/stroke.js", () => ({diff --git a/test/wash_test.html b/test/wash_test.htmlnew file mode 100644index 0000000..71e521a--- /dev/null+++ b/test/wash_test.html@@ -0,0 +1,147 @@+<!doctype html>+<html>+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>Wash Test</title>+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.min.js"></script>+ <script src="../dist/p5.brush.js"></script>+ <style>+ :root {+ --paper: #f3eee2;+ --ink: #22313f;+ --muted: #52616e;+ --line: #d4c8b8;+ --panel: rgba(255, 252, 245, 0.86);+ --accent: #153e5c;+ }++ * { box-sizing: border-box; }++ body {+ margin: 0;+ color: var(--ink);+ background:+ radial-gradient(circle at top left, rgba(21, 62, 92, 0.08), transparent 24%),+ linear-gradient(180deg, #f7f2e7 0%, #ece3d3 100%);+ font-family: "Iowan Old Style", "Palatino Linotype", "Book Antiqua", Palatino, serif;+ }++ main {+ width: min(920px, calc(100vw - 24px));+ margin: 0 auto;+ padding: 18px 0 24px;+ display: grid;+ justify-items: center;+ }++ main > * { width: 100%; }++ .nav {+ margin-bottom: 14px;+ font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;+ }++ .nav a {+ color: var(--accent);+ text-decoration: none;+ }++ .nav a:hover { text-decoration: underline; }++ h1 {+ margin: 0 0 8px;+ font-size: clamp(24px, 3.6vw, 34px);+ letter-spacing: -0.04em;+ }++ p {+ margin: 0 0 8px;+ max-width: 760px;+ color: var(--muted);+ line-height: 1.45;+ font-size: 13px;+ }++ .panel {+ border: 1px solid var(--line);+ border-radius: 8px;+ background: var(--panel);+ }++ .toolbar {+ margin-top: 18px;+ padding: 12px 14px;+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ flex-wrap: wrap;+ font: 11px/1.4 Menlo, Monaco, "Courier New", monospace;+ }++ .seed {+ display: flex;+ align-items: center;+ gap: 8px;+ }++ .seed strong {+ color: var(--accent);+ font-weight: 600;+ }++ button {+ border: 1px solid var(--line);+ background: #fbf8f0;+ color: var(--accent);+ font: inherit;+ padding: 6px 10px;+ border-radius: 6px;+ cursor: pointer;+ }++ button:hover { background: #f4eee2; }++ #canvas-host {+ margin-top: 16px;+ padding: 10px;+ display: grid;+ justify-content: center;+ width: 100%;+ overflow: hidden;+ }++ canvas {+ display: block;+ border-radius: 6px;+ max-width: 100%;+ max-height: min(78vh, 760px);+ height: auto !important;+ }+ </style>+ </head>+ <body>+ <main>+ <div class="nav"><a href="./index.html">All tests</a></div>+ <h1>Wash Test</h1>+ <p>+ Direct WEBGL wash test that draws five random rect and circle polygons with palette colors at full opacity.+ </p>+ <p>+ Refresh the seed to regenerate the shape mix and placement while keeping the wash path isolated from fill and stroke.+ </p>++ <div class="toolbar panel">+ <div class="seed">+ <span>Seed</span>+ <strong id="seedVal">000000</strong>+ </div>+ <button id="refreshSeed" type="button">Refresh seed</button>+ </div>++ <div id="canvas-host" class="panel"></div>+ </main>+ <script src="./wash_test.js"></script>+ </body>+</html>diff --git a/test/wash_test.js b/test/wash_test.jsnew file mode 100644index 0000000..ad4ae4c--- /dev/null+++ b/test/wash_test.js@@ -0,0 +1,63 @@+const PALETTE = ["#002185", "#003c32", "#fcd300", "#ff2702", "#6b9404"];+const PAPER = "#fffceb";++const seedLabel = document.getElementById("seedVal");+const refreshSeedButton = document.getElementById("refreshSeed");++let currentSeed = 100000 + Math.floor(Math.random() * 900000);++function updateSeedLabel() {+ seedLabel.textContent = String(currentSeed).padStart(6, "0");+}++function drawRandomWashSet() {+ randomSeed(currentSeed);+ noiseSeed(currentSeed);+ updateSeedLabel();++ background(PAPER);+ translate(-width / 2, -height / 2);++ brush.wiggle(3)++ for (let i = 0; i < 50; i++) {++ const color = PALETTE[i % PALETTE.length];+ brush.wash(color, 255);++ const isCircle = random() < 0.5;++ if (isCircle) {+ const radius = random(100, 200);+ const cx = random(radius + 24, width - radius - 24);+ const cy = random(radius + 24, height - radius - 24);+ brush.circle(cx, cy, radius);+ } else {+ const rw = random(190, 250);+ const rh = random(190, 250);+ const rx = random(24, width - rw - 24);+ const ry = random(24, height - rh - 24);+ brush.rect(rx, ry, rw, rh);+ }+ }++ brush.noWash();+}++function setup() {+ const canvas = createCanvas(840, 720, WEBGL);+ canvas.parent("canvas-host");+ brush.load();+ brush.scaleBrushes(3)+ noLoop();+ updateSeedLabel();+}++function draw() {+ drawRandomWashSet();+}++refreshSeedButton.addEventListener("click", () => {+ currentSeed = 100000 + Math.floor(Math.random() * 900000);+ redraw();+});diff --git a/tools/brush-maker.html b/tools/brush-maker.htmlindex c632459..f80be4a 100644--- a/tools/brush-maker.html+++ b/tools/brush-maker.html@@ -599,7 +599,7 @@<div class="control-row"><label>scatter</label>- <input type="range" id="scatter" min="0" max="15" step="0.05" value="1.8" />+ <input type="range" id="scatter" min="0" max="25" step="0.05" value="1.8" /><span class="val" id="scatter-val">1.8</span></div>@@ -631,6 +631,12 @@<span class="val" id="spacing-val">0.3</span></div>+ <div class="control-row" id="noise-row" style="display:none">+ <label>noise</label>+ <input type="range" id="noise" min="0" max="4" step="0.05" value="1" />+ <span class="val" id="noise-val">0.5</span>+ </div>+<div class="control-row" id="rotate-row" style="display:none"><label>rotate</label><select id="rotate">@@ -799,6 +805,7 @@ const params = {grain: 10,opacity: 170,spacing: 0.3,+ noise: 0.5,rotate: 'natural',markerTip: true,pressureMode: 'simple',@@ -917,12 +924,13 @@ function generateCode() {const markerTipField = (p.type === 'marker' || p.type === 'custom' || p.type === 'image')? ` markerTip: ${p.markerTip},\n`: '';+ const noiseField = ` noise: ${p.noise},\n`;const prefix = p.type === 'image'? '// Image brushes must be awaited inside async setup()\nawait ': '';- return `${prefix}brush.add("${p.name}", {\n type: "${p.type}",\n weight: ${p.weight},\n scatter: ${p.scatter},\n${typeSpecific} opacity: ${p.opacity},\n spacing: ${p.spacing},\n pressure: ${pressure},\n rotate: "${p.rotate}",\n${markerTipField}${imageField}${tipField}});`;+ return `${prefix}brush.add("${p.name}", {\n type: "${p.type}",\n weight: ${p.weight},\n scatter: ${p.scatter},\n${typeSpecific} opacity: ${p.opacity},\n spacing: ${p.spacing},\n${noiseField} pressure: ${pressure},\n rotate: "${p.rotate}",\n${markerTipField}${imageField}${tipField}});`;}function updateCode() {@@ -983,6 +991,7 @@ wire('scatter', 'scatter', v => Math.round(parseFloat(v) * 100) / 100);wire('sharpness', 'sharpness', v => Math.round(parseFloat(v) * 100) / 100);wire('opacity', 'opacity', v => Math.round(parseFloat(v) * 100) / 100);wire('spacing', 'spacing', v => Math.max(0.001, Math.round(parseFloat(v) * 1000) / 1000));+wire('noise', 'noise', v => Math.round(parseFloat(v) * 100) / 100);wire('press-start','pressStart', v => Math.round(parseFloat(v) * 100) / 100);wire('press-mid', 'pressMid', v => Math.round(parseFloat(v) * 100) / 100);wire('press-end', 'pressEnd', v => Math.round(parseFloat(v) * 100) / 100);@@ -1028,27 +1037,31 @@ wire('gauss-max', 'gaussMax', v => Math.round(parseFloat(v) * 100) / 100);const SLIDER_RANGES = {default: {weight: { min: 0, max: 3, step: 0.01 },- scatter: { min: 0, max: 15, step: 0.05 },+ scatter: { min: 0, max: 25, step: 0.05 },opacity: { min: 1, max: 255, step: 1 },spacing: { min: 0.01, max: 2, step: 0.01 },+ noise: { min: 0, max: 1, step: 0.05 },},spray: {weight: { min: 0, max: 3, step: 0.01 },scatter: { min: 10, max: 50, step: 1 },opacity: { min: 1, max: 255, step: 1 },spacing: { min: 2, max: 50, step: 1 },+ noise: { min: 0, max: 1, step: 0.05 },},marker: {weight: { min: 0, max: 50, step: 1 },scatter: { min: 0, max: 15, step: 0.05 },opacity: { min: 0, max: 5, step: 0.01 },spacing: { min: 0.002, max: 0.5, step: 0.002 },+ noise: { min: 0, max: 1, step: 0.05 },},custom: {weight: { min: 1, max: 60, step: 1 },scatter: { min: 0, max: 10, step: 0.05 },opacity: { min: 1, max: 50, step: 1 },spacing: { min: 0.1, max: 15, step: 0.1 },+ noise: { min: 0, max: 1, step: 0.05 },},image: {weight: { min: 1, max: 60, step: 1 },@@ -1064,31 +1077,31 @@ const TYPE_PRESETS = {weight: 0.9, scatter: 1.8, sharpness: 0.3, grain: 10,opacity: 170, spacing: 0.3, pressStart: 1.1, pressEnd: 0.9,gaussCurveA: 0.15, gaussCurveB: 0.2, gaussMin: 1.1, gaussMax: 0.9,- rotate: 'natural', referenceBrush: 'HB',+ rotate: 'natural', noise: 1, referenceBrush: 'HB',},spray: {weight: 0.6, scatter: 18, sharpness: null, grain: 40,opacity: 90, spacing: 5, pressStart: 0.7, pressEnd: 1,gaussCurveA: 0.2, gaussCurveB: 0.35, gaussMin: 0.7, gaussMax: 1,- rotate: 'random', referenceBrush: 'spray',+ rotate: 'random', noise: 1, referenceBrush: 'spray',},marker: {weight: 6, scatter: 0.36, sharpness: null, grain: null,opacity: 1, spacing: 0.09, pressStart: 1.2, pressEnd: 0.85,gaussCurveA: 0.35, gaussCurveB: 0.25, gaussMin: 1.2, gaussMax: 0.85,- rotate: 'none', markerTip: true, referenceBrush: 'marker',+ rotate: 'none', markerTip: true, noise: 1, referenceBrush: 'marker',},custom: {weight: 29, scatter: 0.45, sharpness: null, grain: null,opacity: 6, spacing: 0.4, pressStart: 0.8, pressEnd: 1.2,gaussCurveA: 0.15, gaussCurveB: 0.2, gaussMin: 1.1, gaussMax: 0.9,- rotate: 'none', markerTip: true, referenceBrush: 'HB',+ rotate: 'none', markerTip: true, noise: 1, referenceBrush: 'HB',},image: {weight: 17, scatter: 0.15, sharpness: null, grain: null,opacity: 47, spacing: 9.5, pressStart: 0.8, pressEnd: 1.2,gaussCurveA: 0.15, gaussCurveB: 0.2, gaussMin: 1.1, gaussMax: 0.9,- rotate: 'random', markerTip: true, referenceBrush: 'HB',+ rotate: 'random', markerTip: true, noise: 1, referenceBrush: 'HB',},};@@ -1111,6 +1124,7 @@ function updateTypeUI() {document.getElementById('weight-row').style.display = '';document.getElementById('rotate-row').style.display = (isCustom || isImage) ? '' : 'none';document.getElementById('marker-tip-row').style.display = showMarkerTip ? 'flex' : 'none';+ document.getElementById('noise-row').style.display = 'flex';document.getElementById('sharpness-row').style.display = showSharpness ? '' : 'none';document.getElementById('grain-row').style.display = showGrain ? '' : 'none';document.getElementById('tip-section').style.display = isCustom ? '' : 'none';@@ -1120,6 +1134,7 @@ function updateTypeUI() {applySliderRange('opacity', ranges.opacity);applySliderRange('spacing', ranges.spacing);if (ranges.scatter) applySliderRange('scatter', ranges.scatter);+ if (ranges.noise) applySliderRange('noise', ranges.noise);}function applySliderRange(id, cfg) {@@ -1142,6 +1157,7 @@ function applyTypePreset(type) {params.scatter = preset.scatter; applySliderValue('scatter', preset.scatter);params.opacity = preset.opacity; applySliderValue('opacity', preset.opacity);params.spacing = preset.spacing; applySliderValue('spacing', preset.spacing);+ params.noise = preset.noise ?? 1; applySliderValue('noise', params.noise);params.pressStart = preset.pressStart; applySliderValue('press-start', preset.pressStart);params.pressEnd = preset.pressEnd; applySliderValue('press-end', preset.pressEnd);params.gaussCurveA = preset.gaussCurveA; applySliderValue('gauss-curve-a', preset.gaussCurveA);@@ -1171,6 +1187,7 @@ function syncControlsFromParams() {applySliderValue('scatter', params.scatter);applySliderValue('opacity', params.opacity);applySliderValue('spacing', params.spacing);+ applySliderValue('noise', params.noise);applySliderValue('press-start', params.pressStart);applySliderValue('press-mid', params.pressMid);applySliderValue('press-end', params.pressEnd);@@ -1228,6 +1245,7 @@ function applyGeneratedCode(source, reformat = false) {if (cfg.scatter !== undefined) applySliderValue('scatter', cfg.scatter);if (cfg.opacity !== undefined) applySliderValue('opacity', cfg.opacity);if (cfg.spacing !== undefined) applySliderValue('spacing', cfg.spacing);+ if (cfg.noise !== undefined) applySliderValue('noise', cfg.noise);if (cfg.sharpness !== undefined) applySliderValue('sharpness', cfg.sharpness);if (cfg.grain !== undefined) applySliderValue('grain', cfg.grain);@@ -1492,6 +1510,8 @@ const sketch = (p) => {cfg.grain = params.grain;}+ cfg.noise = params.noise;+if (params.type === 'custom') {const tipLines = params.tipBody.split('\n').map(l => l.trim()).filter(Boolean).map(l => `_m.${l}`).join('\n');try { cfg.tip = new Function('_m', tipLines); } catch(e) { cfg.tip = (_m) => {}; }