Skip to content

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

Fix loading lib for p5.graphics and p5.framebuffer targets, angleMode, and other things

acamposuribea9a60aacbef2
diff --git a/README.md b/README.md
index ebc4224..c3778b8 100644
--- a/README.md
+++ b/README.md
@@ -131,7 +131,7 @@ p5.brush.js provides a comprehensive API for creating complex drawings and effec
| | brush.stroke() | | | brush.endShape() |
| | brush.noStroke() | | | brush.polygon() |
| | brush.strokeWeight()| | [Configuration](#optional-configuration) | brush.load() |
-| [Fill Operations](#fill-operations) | brush.fill() | | | brush.preload() |
+| [Fill Operations](#fill-operations) | brush.fill() | | | |
| | brush.noFill() | | | brush.scaleBrushes()|
| | brush.fillBleed() | | | brush.instance() |
| | brush.fillTexture() | | | |
@@ -148,6 +148,8 @@ p5.brush.js provides a comprehensive API for creating complex drawings and effec
> **Note for users upgrading from older versions**: `brush.push()`, `brush.pop()`, `brush.translate()`, `brush.rotate()`, and `brush.scale()` are no longer needed. The library now automatically hooks into p5's `push()` and `pop()`, so brush state (stroke, fill, hatch settings) is saved and restored alongside p5's own state. Likewise, p5's `translate()`, `rotate()`, and `scale()` are automatically inherited by all brush strokes and fills.
+> Public brush APIs that accept angles also inherit p5's current `angleMode()`. With no `angleMode()` call, that means radians by default, matching p5 itself. The main exception is `brush.addField(name, fn, { angleMode })`, which lets custom field generators declare how returned angles should be interpreted before they are stored internally in degrees.
+
---
<sub>[back to table](#table-of-functions)</sub>
@@ -230,12 +232,14 @@ Vector Fields allow for dynamic control over brush stroke behavior, enabling the
---
-- `brush.addField(name, generatorFunction)`
+- `brush.addField(name, generatorFunction, options)`
- **Description**: Creates your own custom vector field. A vector field is just a grid of angles — each cell tells the brush "point in this direction". You give the field a name and a function that fills the grid. Once added, activate it with `brush.field(name)` just like any built-in field.
- **Parameters**:
- `name` (String): Any name you want, e.g. `"myField"`.
- - `generatorFunction` (Function): A function `(t, field) => field` that fills every cell of the grid with an angle **in degrees** and returns it. `t` is a time value you can use for animation (pass it via `brush.refreshField(t)`).
- - **How the grid works**: `field` is a 2D array — `field[column][row]`. You loop through every column and row and set each cell to an angle in degrees. Small angles (±10°) make subtle curves; large ones (±90° or more) make dramatic bends.
+ - `generatorFunction` (Function): A function `(t, field) => field` that fills every cell of the grid with an angle and returns it. `t` is a time value you can use for animation (pass it via `brush.refreshField(t)`).
+ - `options` (Object): Optional configuration for custom field angles.
+ - `angleMode`: `"degrees"` (default) or `"radians"`. This controls how the values written into `field[column][row]` are interpreted.
+ - **How the grid works**: `field` is a 2D array — `field[column][row]`. You loop through every column and row and set each cell to an angle. By default those angles are interpreted as degrees. Small angles (±10°) make subtle curves; large ones (±90° or more) make dramatic bends.
- **Simplest example** — a diagonal flow that slowly rotates over time:
```javascript
brush.addField("diagonal", function(t, field) {
@@ -343,7 +347,7 @@ Functions for managing brush behaviors and properties.
---
- `brush.clip(clippingRegion)`
- - **Description**: Sets a rectangular clipping region for all subsequent brush strokes. When this clipping region is active, brush strokes outside this area will not be rendered. This is particularly useful for ensuring that strokes, such as lines and curves, are contained within a specified area. The clipping affects only stroke and hatch operations, not fill operations. The clipping remains in effect for all strokes drawn after the call to `brush.clip()` until `brush.noClip()` is used.
+ - **Description**: Sets a rectangular clipping region for all subsequent brush strokes. When this clipping region is active, brush strokes outside this area will not be rendered. This is particularly useful for ensuring that strokes, such as lines and curves, are contained within a specified area. The clipping affects only stroke and hatch operations, not fill operations. The region is interpreted in the same coordinate space as your brush drawing calls, with the current p5 transform captured when `brush.clip()` is called. The clipping remains in effect for all strokes drawn after the call to `brush.clip()` until `brush.noClip()` is used.
- **Parameters**:
- `clippingRegion` (Array): An array defining the clipping region as `[x1, y1, x2, y2]`, with `(x1, y1)` and `(x2, y2)` being the corners of the clipping rectangle.
- **Usage**:
@@ -523,7 +527,7 @@ The Hatching section focuses on creating and drawing hatching patterns, which in
- **Description**: Activates hatching with specified parameters for subsequent geometries. This function enables the drawing of hatching patterns with controlled line spacing, angle, and additional stylistic options.
- **Parameters**:
- `dist` (Number): The distance between hatching lines, in canvas units.
- - `angle` (Number): The angle at which hatching lines are drawn. The angle mode (degrees or radians) is set by p5's `angleMode()`.
+ - `angle` (Number): The angle at which hatching lines are drawn. It is interpreted using p5's current `angleMode()` when `brush.hatch()` is called.
- `options` (Object): Optional settings to affect the hatching style, including:
- `rand`: Randomness in line placement (0 to 1 or false).
- `continuous`: Whether to connect the end of a line with the start of the next.
@@ -621,7 +625,7 @@ The following functions are only affected by stroke() operations, completely ign
- `x` (Number): The x-coordinate of the starting point.
- `y` (Number): The y-coordinate of the starting point.
- `length` (Number): The length of the line.
- - `dir` (Number): The direction in which to draw the line, measured anticlockwise from the x-axis.
+ - `dir` (Number): The direction in which to draw the line, measured anticlockwise from the x-axis and interpreted using the current p5 `angleMode()`.
- **Usage**:
```javascript
// Set a vector field and draw a flow line
@@ -711,12 +715,12 @@ The following functions are affected by stroke(), fill() and hatch() operations.
---
- `brush.circle(x, y, radius, r)`
- - **Description**: Draw a circle outline using the current brush settings. Circles are affected by vector fields. Note: `circle()` draws only the stroke outline — `fill()` is not applied. To draw a filled circle, use `brush.polygon()` with many vertices approximating a circle.
+ - **Description**: Draw a circle using the current stroke, fill, and hatch settings. Circles are affected by vector fields, so their outlines follow the active field just like other field-aware shapes.
- **Parameters**:
- `x` (Number): The x-coordinate of the circle's center.
- `y` (Number): The y-coordinate of the circle's center.
- `radius` (Number): The radius of the circle.
- - `r` (Boolean): Optional. When true, applies a hand-drawn style to the circle.
+ - `r` (Number|Boolean): Optional. Hand-drawn irregularity amount. Values around `0` to `1` give subtle variation; `true` behaves like a strong irregularity.
- **Usage**:
```javascript
brush.circle(100, 150, 75, true);
@@ -730,8 +734,8 @@ The following functions are affected by stroke(), fill() and hatch() operations.
- `x` (Number): The x-coordinate of the center.
- `y` (Number): The y-coordinate of the center.
- `radius` (Number): The radius of the arc.
- - `start` (Number): Start angle in radians.
- - `end` (Number): End angle in radians.
+ - `start` (Number): Start angle interpreted using the current p5 `angleMode()`.
+ - `end` (Number): End angle interpreted using the current p5 `angleMode()`.
- **Usage**:
```javascript
brush.arc(200, 200, 50, 0, Math.PI);
@@ -806,9 +810,14 @@ This section covers functions for initializing the drawing system, preloading re
> **Seeding**: p5.brush automatically hooks into p5's `randomSeed()` and `noiseSeed()`. Calling either of those functions seeds both p5 and the library simultaneously — no separate `brush.seed()` call is needed.
- `brush.load(buffer)`
- - **Description**: Initialize the library on the current canvas. If a `p5.Graphics` buffer is passed, the library will target that buffer instead. Call `brush.load()` again (with no argument) to switch back to the main canvas.
+ - **Description**: Initialize the library on the current canvas. If a `p5.Graphics` buffer is passed, the library will target that buffer instead. If a `p5.Framebuffer` is passed, it must belong to the active sketch; call `brush.load(framebuffer)` while that framebuffer is active inside `begin()` / `end()` or `draw()`. Framebuffers created from `p5.Graphics` are not supported. Call `brush.load()` again (with no argument) to switch back to the main canvas.
- **Parameters**:
- - `buffer` (p5.Graphics): Optional. A p5.Graphics buffer to draw into.
+ - `buffer` (p5.Graphics | p5.Framebuffer): Optional. An offscreen target to draw into.
+ - **How to use it**:
+ - `p5.Graphics`: create it with `WEBGL`, call `brush.load(pg)`, draw with brush functions, then call `brush.load()` to restore the main canvas before presenting it with `image(pg, ...)`.
+ - `p5.Framebuffer`: create it from the main sketch with `createFramebuffer(...)`, enter its `draw()` or `begin()` / `end()` scope, call `brush.load(fb)` while it is active, draw with brush functions, then call `brush.load()` again after leaving the framebuffer scope.
+ - `brush.load(...)` only changes the target used by p5.brush. If you also use native p5 drawing calls, call them on the same target yourself, for example `pg.background(...)` for `p5.Graphics`.
+ - `pg.createFramebuffer()` is not supported.
- **Example (draw into a buffer)**:
```javascript
function setup() {
@@ -828,32 +837,61 @@ This section covers functions for initializing the drawing system, preloading re
brush.load();
}
```
+ - **Example (draw into a framebuffer)**:
+ ```javascript
+ function setup() {
+ createCanvas(400, 400, WEBGL);
+ brush.load();
----
+ const layer = createFramebuffer({ width: 200, height: 200 });
-- `brush.preload()`
- - **Description**: Kept for backward compatibility. Image brushes no longer require a separate `preload()` call — they auto-load when you use `await brush.add()` with `type: "image"`. You only need this function if you are working with older code that relied on the previous loading approach.
- - **Parameters**: None
- - **Example**:
- ```javascript
- function preload() {
- brush.preload(); // only needed for backward compatibility
+ layer.draw(() => {
+ brush.load(layer);
+ brush.set("HB", "black", 1);
+ brush.circle(100, 100, 80);
+ });
+
+ brush.load();
+ image(layer, 20, 20);
}
```
+ - **Typical workflows**:
+ ```javascript
+ // p5.Graphics
+ const pg = createGraphics(300, 200, WEBGL);
+ pg.background(250);
+ brush.load(pg);
+ brush.set("HB", "black", 1);
+ brush.circle(150, 100, 70);
+ brush.load();
+ image(pg, 20, 20);
+
+ // p5.Framebuffer
+ const fb = createFramebuffer({ width: 300, height: 200 });
+ fb.draw(() => {
+ background(250);
+ brush.load(fb);
+ brush.set("HB", "black", 1);
+ brush.circle(150, 100, 70);
+ });
+ brush.load();
+ image(fb, 20, 240);
+ ```
+
---
- `brush.scaleBrushes(scale)`
- - **Description**: Adjusts the global scale of all standard brush parameters, including weight, vibration, and spacing, based on the given scaling factor. This function is specifically designed to affect default brushes only, allowing for uniform scaling across various brush types.
+ - **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 function only impacts the default brushes. Custom brushes may not be affected by this scaling, since they are defined per case basis.
+ - **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.
- **Usage**:
```javascript
// Scale all standard brushes by a factor of 1.5
brush.scaleBrushes(1.5);
```
- Using `brush.scaleBrushes()`, you can easily adjust the size and spacing characteristics of standard brushes in your project, providing a convenient way to adapt to different canvas sizes or artistic styles.
+ 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.
---
@@ -984,13 +1022,13 @@ Exposed Classes provide foundational elements for creating and manipulating shap
- `y` (Number): The initial y-coordinate.
- **Methods**:
- - `.moveTo(_length, _dir, _step_length, isFlow)`
+ - `.moveTo(_dir, _length, _step_length)`
- Moves the position along the flow field by a specified length.
- Parameters:
- - `_length` (Number): The length to move along the field.
- `_dir` (Number): The direction of movement, with angles measured anticlockwise from the x-axis.
+ It is interpreted using the current p5 `angleMode()`.
+ - `_length` (Number): The length to move along the field.
- `_step_length` (Number): The length of each step.
- - `isFlow` (Boolean): Whether to use the flow field for movement.
- `.plotTo(_plot, _length, _step_length, _scale)`
- Plots a point to another position within the flow field, following a given `Plot` object.
- Parameters:
diff --git a/dist/p5.brush.esm.js b/dist/p5.brush.esm.js
index 395b0d4..a4956e0 100644
--- a/dist/p5.brush.esm.js
+++ b/dist/p5.brush.esm.js
@@ -1,2 +1,2 @@
-let t,e,r,i,n;const o=(n=!1)=>{if(i=a&&!n?r:n||window.self.p5.instance,"webgl2"!==i.webglVersion)throw new Error("p5.brush requires a WEBGL canvas");t=i.width,e=i.height,s=!0,i.loaded&&f.load()};let s=!1,a=!1;const l=()=>{s||o()},c={},h=t=>{a=!0,r=t},u=()=>{i.loaded||(l(),f.load())},f={isBlending:!1,isBlendingGL:!1,isWaterColor:!1,cachedColor:new Object,cachedColorGL:new Object,masks:[],load(){i.loaded||(i.mask=i.createGraphics(t,e,i.P2D),i.glMask=i.createGraphics(t,e,i.WEBGL),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.;gl_Position=vec4(p=v.xy,0,1);}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nuniform bool u_isBrush;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 uv1=vec2(uv.x,1.0-uv.y);vec4 source=texture(u_source,uv1);vec4 maskColor=texture(u_mask,uv1);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 sampleUV=uv1+vec2(float(i),float(j))*texelSize;float neighborAlpha=texture(u_mask,sampleUV).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.0);}"),n=i.pixelDensity(),this.mask=i.mask,this.mask.pixelDensity(n),this.mask.clear(),this.mask.angleMode(i.DEGREES),this.ctx=this.mask.drawingContext,this.glMask=i.glMask,this.glMask.pixelDensity(n),this.glMask.clear(),this.glMask.angleMode(this.glMask.DEGREES),this.glMask.drawingContext.lineWidth=0,this.glMask._renderer.uModelMatrix=i._renderer.uModelMatrix)},blend(t=!1,e=!1){u();const r=this.isBrush?this.glMask:this.mask,i=this.isBrush?this.mask:this.glMask;!this.isBlending&&t&&(this.isBlending=!0,this.cachedColor=t._array,this.glMask.clear()),(e||this.cachedColor[0]!==t._array[0]||this.cachedColor[1]!==t._array[1]||this.cachedColor[2]!==t._array[2]||this.cachedColor[3]!==t._array[3])&&(this.justChanged&&(this.applyShader(i),this.justChanged=!1),this.isBlending&&this.applyShader(r),this.cachedColor=t._array,e&&(this.isBlending=!1))},applyShader(r){let n=i.shaderProgram;const o=i.drawingContext,s=o.getParameter(o.DEPTH_TEST);o.disable(o.DEPTH_TEST),i.push(),i.translate(0,0),i.shader(n),n.setUniform("u_source",i._renderer),n.setUniform("u_isBrush",this.isBrush),n.setUniform("u_mask",r),n.setUniform("u_color",this.cachedColor),i.fill(0,0,0,0),i.noStroke(),i.rect(-t/2,-e/2,t,e),i.pop(),i.resetShader(),s&&o.enable(o.DEPTH_TEST),r.clear(),r.isDrawn=!1}},g=Math.sqrt(3),m=.5*(g-1),d=(3-g)/6,x=t=>0|Math.floor(t),p=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 i=r+~~(t()*(256-r)),n=e[r];e[r]=e[i],e[i]=n}for(let t=256;t<512;t++)e[t]=e[t-256];return e}(t),r=new Float64Array(e).map(t=>p[t%12*2]),i=new Float64Array(e).map(t=>p[t%12*2+1]);return function(t,n){let o=0,s=0,a=0;const l=(t+n)*m,c=x(t+l),h=x(n+l),u=(c+h)*d,f=t-(c-u),g=n-(h-u);let p,y;f>g?(p=1,y=0):(p=0,y=1);const _=f-p+d,v=g-y+d,b=f-1+2*d,w=g-1+2*d,R=255&c,S=255&h;let E=.5-f*f-g*g;if(E>=0){const t=R+e[S];E*=E,o=E*E*(r[t]*f+i[t]*g)}let A=.5-_*_-v*v;if(A>=0){const t=R+p+e[S+y];A*=A,s=A*A*(r[t]*_+i[t]*v)}let P=.5-b*b-w*w;if(P>=0){const t=R+1+e[S+1];P*=P,a=P*P*(r[t]*b+i[t]*w)}return 70*(o+s+a)}}function _(t,e){let r=new v(t),i=()=>r.next();return i.double=()=>i()+11102230246251565e-32*(2097152*i()|0),i.int32=()=>4294967296*r.next()|0,i.quick=i,i}class v{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 i=.02519603282416938*e;e=i>>>0,i-=e,i*=e,e=i>>>0,i-=e,e+=4294967296*i}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:i}=this,n=2091639*e+2.3283064365386963e-10*t;return this.s0=r,this.s1=i,this.s2=n-(this.c=0|n)}copy(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}}let b=_(Math.random()),w=y(_(Math.random()));const R=(t=0,e=1)=>t+b()*(e-t),S=t=>t[~~(b()*t.length)],E=(t,e)=>~~R(t,e),A=(t=0,e=1)=>{const r=1-b(),i=b();return Math.sqrt(-2*Math.log(r))*z(360*i)*e+t},P=t=>{let e=0;const r=[];for(const i in t)e+=t[i],r.push({key:i,cumulative:e});const i=b()*e;for(const{key:t,cumulative:e}of r)if(i<e)return isNaN(t)?t:parseInt(t)},M=(t,e,r,i,n,o=!1)=>{let s=i+(t-e)/(r-e)*(n-i);return o?i<n?L(s,i,n):L(s,n,i):s},L=(t,e,r)=>Math.max(Math.min(t,r),e),k=t=>(t%=360)<0?t+360:t,C=1440,I=2*Math.PI/C,T=new Float32Array(C).fill(NaN),N=new Float32Array(C).fill(NaN),z=t=>{const e=~~(4*k(t));let r=T[e];return isNaN(r)&&(r=Math.cos(e*I),T[e]=r),r},O=t=>{const e=~~(4*k(t));let r=N[e];return isNaN(r)&&(r=Math.sin(e*I),N[e]=r),r},B=(t,e=!1)=>{if(i.angleMode()===i.RADIANS||e){let e=180*t/Math.PI%360;return e<0?e+360:e}return t},D=(t,e,r,i,n)=>{let o=z(n),s=O(n);return{x:o*(r-t)+s*(i-e)+t,y:o*(i-e)-s*(r-t)+e}},Y=(t,e,r,i)=>Math.hypot(r-t,i-e),F=(t,e,r,i)=>B(Math.atan2(-(i-e),r-t),!0),X=(t,e,r,i,n=!1)=>{let o=t.x,s=t.y,a=e.x,l=e.y,c=r.x,h=r.y,u=i.x,f=i.y;if(o===a&&s===l||c===u&&h===f)return!1;let g=a-o,m=l-s,d=u-c,x=f-h,p=x*g-d*m;if(0===p)return!1;let y=(d*(s-h)-x*(o-c))/p,_=(g*(s-h)-m*(o-c))/p;return!(!n&&(_<0||_>1))&&{x:o+y*g,y:s+y*m}},G=()=>i._renderer.uModelMatrix.mat4[12],$=()=>i._renderer.uModelMatrix.mat4[13],W=()=>i._renderer.uModelMatrix.mat4[0],H=()=>i._renderer.uModelMatrix.mat4[1],j=()=>i._renderer.uModelMatrix.mat4[4],U=()=>i._renderer.uModelMatrix.mat4[5];let Z=!1;function V(){Z||(u(),q=.01*t,J=-.5*t,Q=-.5*e,tt=Math.round(2*t/q),et=Math.round(2*e/q),ut("hand",(t,e)=>{const r=R(.2,.8),i=E(5,10);return mt(e,(e,n)=>.5*i*O(r*n*e+E(15,25))*.2*z(t)+w(e,n)*i*.7)}),ut("curved",(t,e)=>{let r=E(-10,10);return E(0,100)%2==0&&(r*=-1),mt(e,(e,i)=>3*M(w(.02*e+.03*t,.02*i+.03*t),0,1,-r,r))}),ut("zigzag",(t,e)=>{let r=E(-30,-15)+Math.abs(44*O(t));E(0,100)%2==0&&(r*=-1);let i=r,n=0;for(let t=0;t<tt;t++){for(let r=0;r<et;r++)e[t][r]=n,n+=i,i*=-1;n+=i,i*=-1}return e}),ut("waves",(t,e)=>{const r=E(10,15)+5*O(t),i=E(3,6)+3*z(t),n=E(20,35);return mt(e,(t,e)=>O(r*t)*n*z(e*i)+E(-3,3))}),ut("seabed",(t,e)=>{const r=R(.4,.8),i=E(18,26);return mt(e,(e,n)=>1.1*i*O(r*n*e+E(15,20))*z(t))}),ut("spiral",(t,e)=>{const r=E(5,10),i=2*E(0,2)-1,n=E(65,80),o=Array.from({length:r},()=>({x:R(.1,.9)*tt,y:R(.1,.9)*et}));return mt(e,(t,e)=>{let r=0,s=0;for(const a of o){const o=t-a.x,l=e-a.y,c=1/(o*o+l*l+1),h=Math.atan2(l,o)*(180/Math.PI),u=i*(h+n)*Math.PI/180;r+=c*Math.cos(u),s+=c*Math.sin(u)}return Math.atan2(s,r)*(180/Math.PI)})}),ut("columns",(t,e)=>{const r=E(3,8),i=E(25,45);return mt(e,(t,e)=>O(t*r)*i)}),Z=!0)}class K{constructor(t,e){V(),this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=K.getColIndex(t),this.rowIdx=K.getRowIndex(e)}reset(){this.plotted=0}isIn(){return c.field.isActive?K.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const r=t,i=e,n=this.x+G(),o=this.y+$();return n>=-.3*r&&n<=1.3*r&&o>=-.3*i&&o<=1.3*i}angle(){return this.isIn()&&c.field.isActive?st.get(c.field.current).field[this.colIdx][this.rowIdx]*c.field.wiggle:0}moveTo(t,e,r=1){this.movePos(t,e,r)}plotTo(t,e,r,i=1){this.movePos(t,e,r,i)}movePos(t,e,r,i=!1){const n=i||1;if(this.isIn())for(let o=0;o<e/r;o++){const e=this.angle()-(i?t.angle(this.plotted):t);this.update(this.x+r*z(e),this.y+r*O(e)),this.plotted+=r/n}else this.plotted+=r/n}static getRowIndex(t,e=1){const r=t+$()-Q;return Math.round(r/q/e)}static getColIndex(t,e=1){const r=t+G()-J;return Math.round(r/q/e)}static isIn(t,e){return t>=0&&e>=0&&t<tt&&e<et}}c.field={isActive:!1,current:null,wiggle:1};let q,J,Q,tt,et,rt,it,nt,ot,st=new Map;function at(t=0){if(!c.field.isActive||!c.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=st.get(c.field.current);e.field=e.gen(t,lt())}function lt(){return new Array(tt).fill(null).map(()=>new Float32Array(et))}function ct(t){if(c.field.wiggle||(c.field.wiggle=1),V(),!st.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(st.keys()).join(", ")}.`);c.field.isActive=!0,c.field.current=t;const e=st.get(t);e.field||(e.field=e.gen(0,lt()))}function ht(){V(),c.field.isActive=!1}function ut(t,e){st.set(t,{gen:e,field:null})}function ft(){return V(),Array.from(st.keys())}function gt(t=1){ct("hand"),c.field.wiggle=t}function mt(t,e){for(let r=0;r<tt;r++)for(let i=0;i<et;i++)t[r][i]=e(r,i);return t}class dt{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,i]of this.sides){const n=X(t.point1,t.point2,e,i);n&&r.push(n)}return this._intersectionCache[e]=r,r}show(){c.stroke&&this.draw(),c.hatch&&this.hatch(),c.fill&&this.fill()}}class xt{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,i=!1){this.angles.length>0&&this.angles.pop(),t=i?(t%360+360)%360:B(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:B(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=B(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],i=t[this.index+1]??r;return Math.abs(i-r)>180&&(i>r?i=-(360-i):r=-(360-r)),M(e-this.suma,0,this.segments[this.index],r,i,!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,i,n=1,o){V();const s=.5,a=[],l=Math.round(this.length/s),c=new K(r+t/2,i+e/2);let h=0,u=0;for(let r=0;r<l;r++){c.plotTo(this,s,s);const r=this.calcIndex(c.plotted);h+=s,(h>=Math.max(this.segments[r]*o*R(.7,1.3),10)||r>=u)&&c.x&&(a.push([c.x-t/2,c.y-e/2]),h=0,r>=u&&u++)}return new dt(a)}show(t,e,r=1){c.stroke&&this.draw(t,e,r),c.hatch&&this.hatch(t,e,r),c.fill&&this.fill(t,e,r)}}function pt(t){new dt(t).show()}function yt(t,e,r,i,n="corner"){"center"===n&&(t-=r/2,e-=i/2),wt(0),Rt(t,e),Rt(t+r,e),Rt(t+r,e+i),Rt(t,e+i),St(!0)}function _t(t,e,r,i=!1){const n=new xt("curve"),o=Math.PI*r,s=R(0,360),a=i?()=>1+.2*i*R():()=>1;for(let t=0;t<4;t++){const e=-90*t+s;n.addSegment(e*a(),o/2*a(),1,!0)}if(i){const t=i*E(-5,5);n.addSegment(s,Math.abs(t)*(Math.PI/180)*r,1,!0),n.endPlot(t+s,1,!0)}else n.endPlot(s,1,!0);const l=t-r*O(s),c=e-r*z(-s);n.show(l,c,1)}function vt(t,e,r,i,n){const o=new xt("curve"),s=270-B(i),a=270-B(n),l=B(n-i),c=Math.PI*r*l/180;o.addSegment(s,c,1,!0),o.endPlot(a,1,!0);const h=t+r*z(-s-90),u=e+r*O(-s-90);o.draw(h,u,1)}class bt{constructor(){this.isClosed=!1,this.curvature=it,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){Lt(this.vert,this.curvature,this.isClosed).show()}}function wt(t=0){it=L(t,0,1),rt=new bt}function Rt(t,e,r=1){if(!rt)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");rt.vertex(t,e,r)}function St(t=!1){if(!rt)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(rt.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(rt.vertex(...rt.vert[0]),rt.isClosed=!0),rt.show(),rt=!1}function Et(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);ot=[e,r],nt=new xt(t)}function At(t,e,r){if(!nt)throw new Error("move() called without beginStroke(). Call beginStroke() first.");nt.addSegment(t,e,r)}function Pt(t,e){if(!nt)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");nt.endPlot(t,e),nt.draw(ot[0],ot[1],1),nt=!1}function Mt(t,e=.5){if(!t||t.length<2)throw new Error("spline() requires at least 2 points. Each point should be [x, y, pressure].");Lt(t,e).draw()}function Lt(t,e=.5,r=!1){const i=new xt(0===e?"segments":"curve"),n=2*Math.PI;if(r&&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 h=t[c],u=t[c+1],f=t[c+2],g=Y(h[0],h[1],u[0],u[1]),m=Y(u[0],u[1],f[0],f[1]),d=F(h[0],h[1],u[0],u[1]),x=F(u[0],u[1],f[0],f[1]),p=e*Math.min(g,m,.5*Math.min(g,m)),y=Math.max(g,m),_=g-p,v=m-p;if(Math.floor(d)===Math.floor(x)){const e=r&&0===c?0:g-l,n=r?0===c?0:m-a:m;i.addSegment(d,e,h[2],!0),c===t.length-3&&i.addSegment(x,n,u[2],!0),l=0,0===c&&(o=g,a=p,s=t[1],l=0)}else{const e={x:u[0]-p*z(-d),y:u[1]-p*O(-d)},f={x:e.x+y*z(90-d),y:e.y+y*O(90-d)},g={x:u[0]+p*z(-x),y:u[1]+p*O(-x)},m={x:g.x+y*z(90-x),y:g.y+y*O(90-x)},b=X(e,f,g,m,!0),w=Y(e.x,e.y,b.x,b.y),R=Y(e.x,e.y,g.x,g.y)/2,S=n*w*(2*Math.asin(R/w)*(180/Math.PI))/360,E=r&&0===c?0:_-l,A=c===t.length-3?r?o-p:v:0;i.addSegment(d,E,h[2],!0),i.addSegment(d,isNaN(S)?0:S,h[2],!0),i.addSegment(x,A,u[2],!0),l=p,0===c&&(o=_,a=p,s=[e.x,e.y])}c===t.length-3&&i.endPlot(x,u[2],!0)}else if(0===e){const e=t[c],r=t[c+1],n=Y(e[0],e[1],r[0],r[1]),o=F(e[0],e[1],r[0],r[1]);i.addSegment(o,n,r[2],!0),c===t.length-2&&i.endPlot(o,1,!0)}i.origin=r&&0!==e?s:t[0]}return i}let kt,Ct,It,Tt,Nt,zt=!1;const Ot={},Bt={};let Dt=1,Yt=0,Ft=0,Xt=1,Gt=0,$t=0,Wt=new Float32Array(8192),Ht=0,jt=2048,Ut=32768;function Zt(r,i,o,s){if(Ht>=jt){jt*=2;const t=new Float32Array(4*jt);t.set(Wt),Wt=t}const a=r-t/2,l=i-e/2,c=4*Ht;Wt[c]=Dt*a+Ft*l+Gt+t/2,Wt[c+1]=Yt*a+Xt*l+$t+e/2,Wt[c+2]=n*o*Math.sqrt(Dt*Dt+Yt*Yt)/2,Wt[c+3]=s/255,Ht++}function Vt(){if(0===Ht)return;f.glMask.isDrawn=!0;const t=c.stroke.color._array;kt.useProgram(Nt),kt.enable(kt.BLEND),kt.blendFunc(kt.ONE_MINUS_DST_ALPHA,kt.ONE),kt.bindVertexArray(It),kt.bindBuffer(kt.ARRAY_BUFFER,Tt);const e=16*Ht,r=Wt.subarray(0,4*Ht);e>Ut?(kt.bufferData(kt.ARRAY_BUFFER,Wt,kt.DYNAMIC_DRAW),Ut=Wt.byteLength):kt.bufferSubData(kt.ARRAY_BUFFER,0,r),kt.uniform4f(Bt.u_color,...t),kt.uniformMatrix4fv(Bt.u_matrix,!1,Ct),kt.drawArrays(kt.POINTS,0,Ht),kt.bindVertexArray(null),Ht=0,f.glMask._renderer._curShader=null}c.stroke={color:null,weight:1,clipWindow:null,type:"HB",isActive:!1,opacity:1};let Kt,qt,Jt,Qt,te=new Map,ee=null;function re(){return{...c.stroke}}function ie(t){c.stroke={...t}}function ne(t,e){if(e.type=["marker","custom","image","spray"].includes(e.type)?e.type:"default",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||"object"==typeof t&&!Array.isArray(t))return t;if("function"==typeof t)return{type:"custom",min_max:[0,1],curve:t};if(Array.isArray(t)){const[e,r,i]=2===t.length?[t[0],(t[0]+t[1])/2,t[1]]:t,n=Math.min(e,r,i),o=Math.max(e,r,i),s=o-n||1,[a,l,c]=[(e-n)/s,(r-n)/s,(i-n)/s];return{type:"custom",min_max:[n,o],curve:t=>t<.5?a+(l-a)*t*2:l+(c-l)*(t-.5)*2}}}(e.pressure),"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 ke.add(e.image.src),e.tip=()=>{ee.image(ke.tips.get(me.p.image.src),-me.p.weight/2,-me.p.weight/2,me.p.weight,me.p.weight)},te.set(t,{param:e,colors:[],buffers:[]}),ke.load()}te.set(t,{param:e,colors:[],buffers:[]})}function oe(){return[...te.keys()]}function se(t){for(const{param:e}of te.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)}function ae(t){if(!te.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...te.keys()].join(", ")}.`);c.stroke.type=t}function le(t,e,r){l(),c.stroke.color=i.color(...arguments),c.stroke.isActive=!0}function ce(t){c.stroke.weight=t}function he(t,e,r=1){ae(t),le(e),ce(r)}function ue(){c.stroke.isActive=!1}function fe(t){c.stroke.clipWindow=t}function ge(){c.stroke.clipWindow=null}const me={};function de(r,i,n,o=!1){Dt=W(),Yt=H(),Ft=j(),Xt=U(),Gt=G(),$t=$(),Kt=new K(r+t/2,i+e/2),qt=n,Jt=o,Jt&&Jt.calcIndex(0)}const xe=[];function pe(r,i){i||(Qt=r),function(){me.seed=999999*R();const{param:r}=te.get(c.stroke.type)??{};if(!r)return;me.p=r,ee=f.glMask;const{pressure:i}=r;if(me.a="custom"!==i.type?R(-1,1):0,me.b="custom"!==i.type?R(1,1.5):0,me.cp="custom"!==i.type?R(3,3.5):R(-.2,.2),[me.min,me.max]=i.min_max,me.noiseoffset=.03,!Jt){const t=Qt*Math.PI/180;me.cos=Math.cos(t),me.sin=Math.sin(t)}(function(){if(!zt){u(),kt=f.glMask.drawingContext,Ct=new Float32Array([2/t,0,0,0,0,-2/e,0,0,0,0,1,0,-1,1,0,1]),Nt=(t=>{const e=t.createProgram();for(let[r,i]of[[t.VERTEX_SHADER,"#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;}"],[t.FRAGMENT_SHADER,"#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);}"]]){const n=t.createShader(r);t.shaderSource(n,i),t.compileShader(n),t.attachShader(e,n)}return t.linkProgram(e),e})(kt),kt.useProgram(Nt),kt.enable(kt.BLEND),kt.blendFunc(kt.ONE_MINUS_DST_ALPHA,kt.ONE),["a_position","a_radius","a_alpha"].forEach(t=>Ot[t]=kt.getAttribLocation(Nt,t)),["u_matrix","u_color"].forEach(t=>Bt[t]=kt.getUniformLocation(Nt,t)),It=kt.createVertexArray(),kt.bindVertexArray(It),Tt=kt.createBuffer(),kt.bindBuffer(kt.ARRAY_BUFFER,Tt),kt.bufferData(kt.ARRAY_BUFFER,Wt.byteLength,kt.DYNAMIC_DRAW);const r=16;kt.enableVertexAttribArray(Ot.a_position),kt.vertexAttribPointer(Ot.a_position,2,kt.FLOAT,!1,r,0),kt.enableVertexAttribArray(Ot.a_radius),kt.vertexAttribPointer(Ot.a_radius,1,kt.FLOAT,!1,r,8),kt.enableVertexAttribArray(Ot.a_alpha),kt.vertexAttribPointer(Ot.a_alpha,1,kt.FLOAT,!1,r,12),kt.bindVertexArray(null),zt=!0}})(),we()&&f.blend(c.stroke.color),!1===f.isBrush&&(f.justChanged=!0),f.isBrush=!0,me.alpha=be(),Ee()}();const n=function(){const{param:t}=te.get(c.stroke.type)??{};return t?t.spacing:1}(),o=Math.round(qt*(i?r:1)/n);for(let t=0;t<o;t++)xe.length<2*o&&xe.push(A()),ye(),i?Kt.plotTo(Jt,n,n,r,t<10):Kt.moveTo(r,n,n);Vt(),Ee()}function ye(t=!1){if(!we())return;let e=t||_e(),r=M(w(me.seed+.002*Kt.plotted,0),0,1,1-me.noiseoffset,1+me.noiseoffset);switch(me.p.type){case"spray":!function(t){const e=c.stroke.weight*me.p.scatter*t+c.stroke.weight*S(xe)*me.p.scatter/3,r=me.p.weight*R(.9,1.1),i=Math.ceil(me.p.grain/t);for(let t=0;t<i;t++){const t=R(.9,1.1),i=t*e*R(-1,1),n=R(-1,1),o=Math.sqrt((t*e)**2-i**2);Zt(Kt.x+i,Kt.y+n*o,r,me.alpha)}}(e*r);break;case"marker":Re(e*r);break;case"custom":case"image":Se(e*r,me.alpha);break;default:!function(t,e=1){const r=(e=M(e,0,1,.9,1.05))*c.stroke.weight*me.p.scatter*(me.p.sharpness+(1-me.p.sharpness)*S(xe)/t);if(R(0,me.p.grain*t)>.4){let e,i;if(Jt)e=.7*r*R(-1,1),i=r*R(-1,1);else{const t=r*R(-1,1),n=.3*r*R(-1,1);e=t*-me.sin+n*me.cos,i=t*me.cos+n*me.sin}Zt(Kt.x+e,Kt.y+i,t*t*me.p.weight*R(.85,1.15)*c.stroke.weight,Math.max(.9,t)*me.alpha*R(.75,1.1))}}(e*r)}}function _e(){return Jt?ve()*Jt.pressure(Kt.plotted):ve()}function ve(){return"custom"===me.p.pressure.type?M(me.p.pressure.curve(Kt.plotted/qt)+me.cp,0,1,me.min,me.max,!0):function(t=.5+me.p.pressure.curve[0]*me.a,e=1-me.p.pressure.curve[1]*me.b,r=me.cp,i=me.min,n=me.max){const o=t*qt,s=(Kt.plotted<o?1.2*e:.8*e)*(qt/2);return M(1/(1+Math.pow(Math.abs((Kt.plotted-o)/s),2*r)),0,1,i,n)}()}function be(){return["default","spray"].includes(me.p.type)?me.p.opacity:me.p.opacity/Math.min(c.stroke.weight,1.3)}function we(){if(c.stroke.clipWindow)return Kt.x>=c.stroke.clipWindow[0]&&Kt.x<=c.stroke.clipWindow[2]&&Kt.y>=c.stroke.clipWindow[1]&&Kt.y<=c.stroke.clipWindow[3];{let r=t,i=e,n=.05*t,o=Kt.x+G(),s=Kt.y+$();return o>=-n&&o<=r+n&&s>=-n&&s<=i+n}}function Re(t,e=!0,r=me.alpha){const i=e?c.stroke.weight*me.p.scatter:0,n=e?i*R(-1,1):0,o=e?i*R(-1,1):0;Zt(Kt.x+n,Kt.y+o,c.stroke.weight*me.p.weight*t,r)}function Se(r,i,n=!0){f.glMask.isDrawn=!0,ee.push(),ee.noStroke(),c.stroke.color.setAlpha(i),ee.fill(c.stroke.color);const o=n?c.stroke.weight*me.p.scatter:0,s=n?o*R(-1,1):0,a=n?o*R(-1,1):0;ee.translate(Kt.x+s-t,Kt.y+a-e),function(t,e){ee.scale(t),"image"===me.p.type&&ee.tint(255,0,0,e/2);let r=0;"random"===me.p.rotate?r=E(0,360):"natural"===me.p.rotate&&(r=(Jt?-Jt.angle(Kt.plotted):-Qt)+Kt.angle()),ee.rotate(r)}(c.stroke.weight*r,i),me.p.tip(ee),ee.pop()}function Ee(){if(we()){let t=_e(),e=be();if("marker"===me.p.type){for(let r=1;r<10;r++)Re(t*r/10,!1,5*e);Vt()}else if("custom"===me.p.type||"image"===me.p.type)for(let r=1;r<5;r++)Se(t*r/5,e,!1)}}function Ae(t,e,r,i){if(!c.stroke.isActive||!c.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");V();let n=Y(t,e,r,i);0!=n&&(de(t,e,n),pe(F(t,e,r,i),!1))}function Pe(t,e,r,i){if(!c.stroke.isActive||!c.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");V(),de(t,e,r),pe(B(i),!1)}const Me=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate"],Le=[["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,.12,null,null,1,.03,{curve:[.35,.25],min_max:[1.2,.85]},"marker"]]];for(let t of Le){let e={};for(let r=0;r<t[1].length;r++)e[Me[r]]=t[1][r];ne(t[0],e)}dt.prototype.draw=function(t=!1,e,r){let i=re();if(t&&he(t,e,r),i.isActive)for(let t of this.sides)Ae(t[0].x,t[0].y,t[1].x,t[1].y);ie(i)},xt.prototype.draw=function(t,e,r){re().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,i){V(),de(e,r,t.length,t),pe(i,!0)}(this,t,e,r))};const ke={tips:new Map,add(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=i.createImage(n.naturalWidth,n.naturalHeight);r.drawingContext.drawImage(n,0,0),ke.imageToWhite(r),this.tips.set(t,r),e()},n.onerror=()=>r(new Error(`Failed to load image tip: ${t}`)),n.src=t})))}};async function Ce(){await ke.load()}function Ie(){return{...c.hatch}}function Te(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let i=c.hatch;i.isActive=!0,i.dist=t,i.angle=e,i.options=r}function Ne(t,e="black",r=1){c.hatch.hBrush={brush:t,color:e,weight:r}}function ze(){c.hatch.isActive=!1,c.hatch.hBrush=!1}function Oe(t){let e=c.hatch.dist,r=B(c.hatch.angle)%180,i=c.hatch.options,n=re();c.hatch.hBrush&&he(...Object.values(c.hatch.hBrush)),Array.isArray(t)||(t=[t]);const o=function(t){let e={minX:Infinity,minY:Infinity,maxX:-Infinity,maxY:-Infinity};for(let r of t){const t=Be(r);e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY)}return e}(t);let s=new dt([[o.minX,o.minY],[o.maxX,o.minY],[o.maxX,o.maxY],[o.minX,o.maxY]]),a=r<=90&&r>=0?o.minY:o.maxY,l=i.gradient?M(i.gradient,0,1,1,1.1,!0):1,h=[],u=0,f=e,g=t=>({point1:{x:o.minX+f*t*z(90-r),y:a+f*t*O(90-r)},point2:{x:o.minX+f*t*z(90-r)+z(-r),y:a+f*t*O(90-r)+O(-r)}});for(;s.intersect(g(u)).length>0;){let e=[];for(let r of t)e.push(r.intersect(g(u)));h[u]=e.flat().sort((t,e)=>t.x===e.x?t.y-e.y:t.x-e.x),f*=l,u++}let m=h.filter(t=>void 0!==t[0]),d=i.rand||0;for(let t=0;t<m.length;t++){let r=m[t],n=t>0&&i.continuous;for(let i=0;i<r.length-1;i+=2)0!==d&&(r[i].x+=d*e*R(-1,1),r[i].y+=d*e*R(-1,1),r[i+1].x+=d*e*R(-1,1),r[i+1].y+=d*e*R(-1,1)),Ae(r[i].x,r[i].y,r[i+1].x,r[i+1].y),n&&Ae(m[t-1][1].x,m[t-1][1].y,r[i].x,r[i].y)}ie(n)}function Be(t){if(t._boundingBox)return t._boundingBox;let e=Infinity,r=Infinity,i=-Infinity,n=-Infinity;for(let o=0;o<t.a.length;o++){const[s,a]=t.a[o];s<e&&(e=s),s>i&&(i=s),a<r&&(r=a),a>n&&(n=a)}return t._boundingBox={minX:e,minY:r,maxX:i,maxY:n},t._boundingBox}function De(t,e,r){const i=2*Math.PI,n=r/2;f.ctx.moveTo(t+n,e),f.ctx.arc(t,e,n,0,i)}c.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},dt.prototype.hatch=function(t=!1,e,r){let i=Ie();t&&Te(t,e,r),i.isActive&&Oe(this),function(t){c.hatch={...t}}(i)},xt.prototype.hatch=function(t,e,r){Ie().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,.25),this.pol.hatch())},c.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const Ye=()=>({...c.fill});function Fe(t,e,r,n){c.fill.opacity=(arguments.length<4?e:n)||150,c.fill.color=arguments.length<3?i.color(t):i.color(t,e,r),c.fill.isActive=!0}function Xe(t,e="out"){c.fill.bleed_strength=L(t,0,1),c.fill.direction=e}function Ge(t=.4,e=.4){c.fill.texture_strength=L(t,0,1),c.fill.border_strength=L(e,0,1)}function $e(){c.fill.isActive=!1}let We;const He=[[],[]];function je(t,e,r){return(e.x-t.x)*(r.y-t.y)-(e.y-t.y)*(r.x-t.x)>.01}class Ue{constructor(t,e,r,i=[],n=!1,o,s){if(this.v=t,this.m=e,this.dir=i,this.midP=r,n){let e=0,i=0;const n=[];for(let o=0;o<t.length;o++){const s=Math.abs(r.x-t[o].x),a=Math.abs(r.y-t[o].y);e=Math.max(e,s),i=Math.max(i,a);const l=t[o],c=t[(o+1)%t.length],h={x:c.x-l.x,y:c.y-l.y},u=D(0,0,h.x,h.y,90),f={x:l.x+h.x/2,y:l.y+h.y/2};n.push({v1:l,v2:c,ray:{point1:f,point2:{x:f.x+u.x,y:f.y+u.y}}})}this.sizeX=e,this.sizeY=i,this.dir=Array(t.length),n.forEach((t,e)=>{let r=0;for(const e of We.intersect(t.ray))je(t.v1,t.v2,e)&&r++;this.dir[e]=r%2==0});const o=R(-.6,.6)*e,s=R(-.6,.6)*i;this.midP={x:r.x+o,y:r.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),r=~~(this.v.length/2-e/2),i=[...this.v],n=[...this.m],o=[...this.dir];return i.splice(r,e),n.splice(r,e),o.splice(r,e),{v:i,m:n,dir:o}}grow(t=1){const{v:e,m:r,dir:i}=this.trim(t),n=e.length,o=[],s=[],a=[],l="out"===c.fill.direction?-90:90;let h=0,u=999===t?R(.6,.8):c.fill.bleed_strength;for(let c=0;c<n;c++){He[0].length<1.5*n&&(He[0].push(A(.5,.2)),He[1].push(A(0,.02)));const f=e[c],g=c+1<n?e[c+1]:e[0];t<997&&(u=r[c]);const m=(i[c]?l:-l)+5*R(-1,1),d=g.x-f.x,x=g.y-f.y,{x:p,y:y}=D(0,0,d,x,m),_=.5,v=S(He[0])*R(.65,1.35)*u;o[h]=f,s[h]=r[c],a[h++]=i[c],o[h]={x:f.x+d*_+p*v,y:f.y+x*_+y*v},s[h]=r[c]+S(He[1]),a[h++]=i[c]}return new Ue(o,s,this.midP,a,!1,this.sizeX,this.sizeY)}fill(r,i,o){const s=3*o,a=2*i*(1+o/2);f.blend(r),f.justChanged=!0,f.isBrush=!1,f.ctx.save(),f.ctx.setTransform(n*W(),n*H(),n*j(),n*U(),n*(G()+t/2),n*($()+e/2)),f.ctx.strokeStyle=`rgb(${r._getRed()} ${r._getGreen()} ${r._getBlue()} / ${.005*c.fill.border_strength})`,f.ctx.lineCap="round";const l=Math.max(this.sizeX,this.sizeY),h=R(.15,.7);let u,g=this.grow();for(let t=0;t<20;t++){t%4==0&&(g=g.grow()),t%2==0&&(u=[g.grow(1-.0125*t),g.grow(.7-.0125*t),g.grow(.4-.0125*t)]);for(const e of u)e.grow(999).grow(997).layer(t,l,a,r);t%2==0&&g.grow(h).grow(999).layer(t,l,2*a,r),t%5!=0&&19!==t||(0!==s&&g.erase(3*s,i),f.blend(r,!0,!1,!0))}f.ctx.restore()}layer(t,e,r,i){var n;f.ctx.lineWidth=M(t,0,24,e/25,e/30,!0),f.ctx.fillStyle=`rgb(${i._getRed()} ${i._getGreen()} ${i._getBlue()} / ${r}%)`,n=this.v,f.ctx.beginPath(),n.forEach((t,e)=>{0===e?f.ctx.moveTo(t.x,t.y):f.ctx.lineTo(t.x,t.y)}),f.ctx.closePath(),f.ctx.fill(),f.ctx.stroke()}erase(t,e){f.ctx.save();const r=~~(R(80,110)*M(t,0,1,2,3.5)),i=this.sizeX/1.3,n=this.sizeY/1.3,o=Math.min(this.sizeX,this.sizeY)*(1.4-c.fill.bleed_strength),s=.05*o,a=.4*o,{x:l,y:h}=this.midP;f.ctx.globalCompositeOperation="destination-out";const u=(5-M(e,80,100,.3,.7,!0))*t/255;f.ctx.fillStyle=`rgb(255 0 0 / ${u})`,f.ctx.lineWidth=0;for(let t=0;t<r;t++){const e=l+A(0,i),r=h+A(0,n),o=R(s,a);f.ctx.beginPath(),De(e,r,o),t%5!=0&&f.ctx.fill()}f.ctx.globalCompositeOperation="source-over",f.ctx.restore()}}dt.prototype.fill=function(t=!1,e,r,i,n,o){let s=Ye();t&&(Fe(t,e),Xe(r,o),Ge(i,n)),s.isActive&&(V(),function(t){if(!c.fill.isActive||!c.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");We=t;const e=[...t.vertices],r=~~(.25*e.length*P({1:5,2:10,3:60})),i=c.fill.bleed_strength,n=e.map((t,e)=>(e>r?1:.3)*R(.85,1.2)*i),o=E(0,e.length),s=[...e.slice(o),...e.slice(0,o)],a=function(t){if(t.length<8)return t.reduce((t,e)=>({x:t.x+e.x,y:t.y+e.y}),{x:0,y:0}).map(e=>e/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,i=0,n=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,i+=(e[t].x+e[t+1].x)*o,n+=(e[t].y+e[t+1].y)*o}return r*=.5,r?{x:i/(6*r),y:n/(6*r)}:{x:e[0].x,y:e[0].y}}(s);new Ue(s,n,a,[],!0).fill(c.fill.color,M(c.fill.opacity,0,255,0,1,!0),c.fill.texture_strength)}(this)),(t=>{c.fill={...t}})(s)},xt.prototype.fill=function(t,e,r){Ye().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,M(c.fill.bleed_strength,0,.6,.3,.45,!0)),this.pol.fill())};const Ze=[];"undefined"!=typeof p5&&p5.registerAddon(function(t,e,r){r.postsetup=()=>f.blend(!1,!0),r.postdraw=()=>f.blend(!1,!0);const i=e.push,n=e.pop,o=e.randomSeed,s=e.noiseSeed;e.push=function(){i.call(this),V(),Ze.push({fill:{...c.fill},stroke:{...c.stroke},hatch:{...c.hatch},field:{...c.field}})},e.pop=function(){n.call(this),function(){const t=Ze.pop();t&&(c.stroke={...t.stroke},c.field={...t.field},c.hatch={...t.hatch},c.fill={...t.fill})}()},e.randomSeed=function(t){o.call(this,t),(t=>{b=_(t)})(t)},e.noiseSeed=function(t){s.call(this,t),(t=>{w=y(_(t))})(t)}});export{xt as Plot,dt as Polygon,K as Position,ne as add,ut as addField,vt as arc,wt as beginShape,Et as beginStroke,oe as box,_t as circle,fe as clip,St as endShape,Pt as endStroke,ct as field,Fe as fill,Xe as fillBleed,Ge as fillTexture,Pe as flowLine,Te as hatch,Oe as hatchArray,Ne as hatchStyle,h as instance,Ae as line,ft as listFields,o as load,At as move,ge as noClip,ht as noField,$e as noFill,ze as noHatch,ue as noStroke,ae as pick,pt as polygon,Ce as preload,yt as rect,at as refreshField,se as scaleBrushes,he as set,Mt as spline,le as stroke,ce as strokeWeight,Rt as vertex,P as wRand,gt as wiggle};
+let t,e,r,i,n;const o=t=>!!t&&"function"==typeof t.begin&&"function"==typeof t.end&&!!t.renderer&&!!t.renderer._pInst,s=()=>u?r:window.self.p5.instance,a=t=>{t&&"function"==typeof t.remove&&t.remove()},l=()=>i&&i._renderer&&"function"==typeof i._renderer.activeFramebuffer?i._renderer.activeFramebuffer():null,c=(n=!1)=>{const a=((t=!1)=>{if(u&&!t)return{renderer:r,width:r.width,height:r.height};if(!t){const t=s();return{renderer:t,width:t.width,height:t.height}}if(o(t)){if(!o(e=t)||e.renderer._pInst!==s())throw new Error("p5.brush only supports p5.Framebuffer targets created from the active sketch. Framebuffers created from p5.Graphics are not supported.");return{renderer:s(),width:t.width,height:t.height}}var e;return{renderer:t,width:t.width,height:t.height}})(n);if(i=a.renderer,"webgl2"!==i.webglVersion)throw new Error("p5.brush requires a WEBGL canvas");t=a.width,e=a.height,h=!0,i.loaded&&p.load()};let h=!1,u=!1;const f=()=>{h||c()},g={},d=t=>{u=!0,r=t},m=()=>{i.loaded||(f(),p.load())},p={isBlending:!1,cachedColor:new Object,captureBlendSource(){const r=l();if(!r)return i._renderer;var o;(!(o=i.blendSourceFramebuffer)||o.width!==t||o.height!==e||"function"==typeof o.pixelDensity&&o.pixelDensity()!==n)&&(a(i.blendSourceFramebuffer),i.blendSourceFramebuffer=i.createFramebuffer({width:t,height:e,density:n,antialias:!1,depth:!1,stencil:!1}));const s=i.blendSourceFramebuffer;return s.draw(()=>{i.clear(),i.push(),"function"==typeof i.imageMode&&i.imageMode(i.CENTER??i._renderer?._pInst?.CENTER),i.image(r,0,0,t,e),i.pop()}),s},load(){n=i.pixelDensity();const r="function"==typeof i.createGraphics?i:i._pInst,o=r.P2D??i.P2D,s=r.WEBGL??i.WEBGL;i.loaded&&i.mask&&i.glMask&&i.mask.width===t&&i.mask.height===e&&i.glMask.width===t&&i.glMask.height===e?(this.mask=i.mask,this.glMask=i.glMask,this.ctx=this.mask.drawingContext):(a(i.mask),a(i.glMask),i.mask=r.createGraphics(t,e,o),i.glMask=r.createGraphics(t,e,s),i.loaded=!0,i.shaderProgram??=i.createShader("#version 300 es\n#define GLSLIFY 1\nuniform bool u_flipOutputY;out vec2 p;void main(){vec3 v=vec3(-1);v[gl_VertexID]=3.;p=v.xy;gl_Position=vec4(v.x,u_flipOutputY ?-v.y : v.y,0,1);}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nuniform bool u_isBrush;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 uv1=vec2(uv.x,1.0-uv.y);vec4 source=texture(u_source,uv1);vec4 maskColor=texture(u_mask,uv1);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=uv1+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.0);}"),this.mask=i.mask,this.mask.pixelDensity(n),this.mask.clear(),this.mask.angleMode(i.DEGREES),this.ctx=this.mask.drawingContext,this.glMask=i.glMask,this.glMask.pixelDensity(n),this.glMask.clear(),this.glMask.angleMode(this.glMask.DEGREES),this.glMask.drawingContext.lineWidth=0),this.glMask._renderer.uModelMatrix=i._renderer.uModelMatrix},blend(t=!1,e=!1){m();const r=this.isBrush?this.glMask:this.mask,i=this.isBrush?this.mask:this.glMask;!this.isBlending&&t&&(this.isBlending=!0,this.cachedColor=t._array,this.glMask.clear()),(e||this.cachedColor[0]!==t._array[0]||this.cachedColor[1]!==t._array[1]||this.cachedColor[2]!==t._array[2]||this.cachedColor[3]!==t._array[3])&&(this.justChanged&&(this.applyShader(i),this.justChanged=!1),this.isBlending&&this.applyShader(r),this.cachedColor=t._array,e&&(this.isBlending=!1))},applyShader(r){let n=i.shaderProgram;const o=i.drawingContext,s=!!l(),a=this.captureBlendSource(),c=o.getParameter(o.DEPTH_TEST);o.disable(o.DEPTH_TEST),i.push(),i.translate(0,0),i.shader(n),n.setUniform("u_source",a),n.setUniform("u_isBrush",this.isBrush),n.setUniform("u_flipOutputY",s),n.setUniform("u_mask",r),n.setUniform("u_color",this.cachedColor),i.fill(0,0,0,0),i.noStroke(),i.rect(-t/2,-e/2,t,e),i.pop(),i.resetShader(),c&&o.enable(o.DEPTH_TEST),r.clear(),r.isDrawn=!1}},x=Math.sqrt(3),y=.5*(x-1),v=(3-x)/6,_=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 w(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 i=r+~~(t()*(256-r)),n=e[r];e[r]=e[i],e[i]=n}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]),i=new Float64Array(e).map(t=>b[t%12*2+1]);return function(t,n){let o=0,s=0,a=0;const l=(t+n)*y,c=_(t+l),h=_(n+l),u=(c+h)*v,f=t-(c-u),g=n-(h-u);let d,m;f>g?(d=1,m=0):(d=0,m=1);const p=f-d+v,x=g-m+v,b=f-1+2*v,w=g-1+2*v,R=255&c,S=255&h;let E=.5-f*f-g*g;if(E>=0){const t=R+e[S];E*=E,o=E*E*(r[t]*f+i[t]*g)}let A=.5-p*p-x*x;if(A>=0){const t=R+d+e[S+m];A*=A,s=A*A*(r[t]*p+i[t]*x)}let M=.5-b*b-w*w;if(M>=0){const t=R+1+e[S+1];M*=M,a=M*M*(r[t]*b+i[t]*w)}return 70*(o+s+a)}}function R(t,e){let r=new S(t),i=()=>r.next();return i.double=()=>i()+11102230246251565e-32*(2097152*i()|0),i.int32=()=>4294967296*r.next()|0,i.quick=i,i}class S{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 i=.02519603282416938*e;e=i>>>0,i-=e,i*=e,e=i>>>0,i-=e,e+=4294967296*i}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:i}=this,n=2091639*e+2.3283064365386963e-10*t;return this.s0=r,this.s1=i,this.s2=n-(this.c=0|n)}copy(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}}let E=R(Math.random());const A=[],M=t=>A.push(t);let P=w(R(Math.random()));const k=(t=0,e=1)=>t+E()*(e-t),I=t=>t[~~(E()*t.length)],L=(t,e)=>~~k(t,e),C=(t=0,e=1)=>{const r=1-E(),i=E();return Math.sqrt(-2*Math.log(r))*X(360*i)*e+t},T=t=>{let e=0;const r=[];for(const i in t)e+=t[i],r.push({key:i,cumulative:e});const i=E()*e;for(const{key:t,cumulative:e}of r)if(i<e)return isNaN(t)?t:parseInt(t)},N=(t,e,r,i,n,o=!1)=>{let s=i+(t-e)/(r-e)*(n-i);return o?i<n?z(s,i,n):z(s,n,i):s},z=(t,e,r)=>Math.max(Math.min(t,r),e),O=t=>(t%=360)<0?t+360:t,B=1440,D=2*Math.PI/B,Y=new Float32Array(B).fill(NaN),F=new Float32Array(B).fill(NaN),X=t=>{const e=~~(4*O(t));let r=Y[e];return isNaN(r)&&(r=Math.cos(e*D),Y[e]=r),r},G=t=>{const e=~~(4*O(t));let r=F[e];return isNaN(r)&&(r=Math.sin(e*D),F[e]=r),r},$=(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},H=(t,e=!1)=>e||i&&"function"==typeof i.angleMode&&i.angleMode()===i.RADIANS?180*t/Math.PI:t,U=(t,e,r,i,n)=>{let o=X(n),s=G(n);return{x:o*(r-t)+s*(i-e)+t,y:o*(i-e)-s*(r-t)+e}},W=(t,e,r,i)=>Math.hypot(r-t,i-e),j=(t,e,r,i)=>$(Math.atan2(-(i-e),r-t),!0),Z=(t,e,r,i,n=!1)=>{let o=t.x,s=t.y,a=e.x,l=e.y,c=r.x,h=r.y,u=i.x,f=i.y;if(o===a&&s===l||c===u&&h===f)return!1;let g=a-o,d=l-s,m=u-c,p=f-h,x=p*g-m*d;if(0===x)return!1;let y=(m*(s-h)-p*(o-c))/x,v=(g*(s-h)-d*(o-c))/x;return!(!n&&(v<0||v>1))&&{x:o+y*g,y:s+y*d}},V=()=>i._renderer.uModelMatrix.mat4[12],K=()=>i._renderer.uModelMatrix.mat4[13],q=()=>i._renderer.uModelMatrix.mat4[0],J=()=>i._renderer.uModelMatrix.mat4[1],Q=()=>i._renderer.uModelMatrix.mat4[4],tt=()=>i._renderer.uModelMatrix.mat4[5];let et=!1;function rt(){et||(m(),nt=.01*t,ot=-.5*t,st=-.5*e,at=Math.round(2*t/nt),lt=Math.round(2*e/nt),pt("hand",(t,e)=>{const r=k(.2,.8),i=L(5,10);return vt(e,(e,n)=>.5*i*G(r*n*e+L(15,25))*.2*X(t)+P(e,n)*i*.7)}),pt("curved",(t,e)=>{let r=L(-10,10);return L(0,100)%2==0&&(r*=-1),vt(e,(e,i)=>3*N(P(.02*e+.03*t,.02*i+.03*t),0,1,-r,r))}),pt("zigzag",(t,e)=>{let r=L(-30,-15)+Math.abs(44*G(t));L(0,100)%2==0&&(r*=-1);let i=r,n=0;for(let t=0;t<at;t++){for(let r=0;r<lt;r++)e[t][r]=n,n+=i,i*=-1;n+=i,i*=-1}return e}),pt("waves",(t,e)=>{const r=L(10,15)+5*G(t),i=L(3,6)+3*X(t),n=L(20,35);return vt(e,(t,e)=>G(r*t)*n*X(e*i)+L(-3,3))}),pt("seabed",(t,e)=>{const r=k(.4,.8),i=L(18,26);return vt(e,(e,n)=>1.1*i*G(r*n*e+L(15,20))*X(t))}),pt("spiral",(t,e)=>{const r=L(5,10),i=2*L(0,2)-1,n=L(65,80),o=Array.from({length:r},()=>({x:k(.1,.9)*at,y:k(.1,.9)*lt}));return vt(e,(t,e)=>{let r=0,s=0;for(const a of o){const o=t-a.x,l=e-a.y,c=1/(o*o+l*l+1),h=Math.atan2(l,o)*(180/Math.PI),u=i*(h+n)*Math.PI/180;r+=c*Math.cos(u),s+=c*Math.sin(u)}return Math.atan2(s,r)*(180/Math.PI)})}),pt("columns",(t,e)=>{const r=L(3,8),i=L(25,45);return vt(e,(t,e)=>G(t*r)*i)}),et=!0)}class it{constructor(t,e){rt(),this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=it.getColIndex(t),this.rowIdx=it.getRowIndex(e)}reset(){this.plotted=0}isIn(){return g.field.isActive?it.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const r=t,i=e,n=this.x+V(),o=this.y+K();return n>=-.3*r&&n<=1.3*r&&o>=-.3*i&&o<=1.3*i}angle(){return this.isIn()&&g.field.isActive?ct.get(g.field.current).field[this.colIdx][this.rowIdx]*g.field.wiggle:0}moveTo(t,e,r=1){this.movePos(H(t),e,r)}_moveToDegrees(t,e,r=1){this.movePos(t,e,r)}plotTo(t,e,r,i=1){this.movePos(t,e,r,i)}movePos(t,e,r,i=!1){const n=i||1;if(this.isIn())for(let o=0;o<e/r;o++){const e=this.angle()-(i?t.angle(this.plotted):t);this.update(this.x+r*X(e),this.y+r*G(e)),this.plotted+=r/n}else this.plotted+=r/n}static getRowIndex(t,e=1){const r=t+K()-st;return Math.round(r/nt/e)}static getColIndex(t,e=1){const r=t+V()-ot;return Math.round(r/nt/e)}static isIn(t,e){return t>=0&&e>=0&&t<at&&e<lt}}g.field={isActive:!1,current:null,wiggle:1};let nt,ot,st,at,lt,ct=new Map;const ht=new Set(["degrees","radians"]);function ut(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!ht.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function ft(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]=H(t[e][r],!0);return t}(t.gen(e,new Array(at).fill(null).map(()=>new Float32Array(lt))),t.angleMode)}function gt(t=0){if(!g.field.isActive||!g.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=ct.get(g.field.current);e.field=ft(e,t)}function dt(t){if(g.field.wiggle||(g.field.wiggle=1),rt(),!ct.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(ct.keys()).join(", ")}.`);g.field.isActive=!0,g.field.current=t;const e=ct.get(t);e.field||(e.field=ft(e,0))}function mt(){rt(),g.field.isActive=!1}function pt(t,e,r={}){ct.set(t,{gen:e,field:null,angleMode:ut(r)})}function xt(){return rt(),Array.from(ct.keys())}function yt(t=1){dt("hand"),g.field.wiggle=t}function vt(t,e){for(let r=0;r<at;r++)for(let i=0;i<lt;i++)t[r][i]=e(r,i);return t}class _t{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,i]of this.sides){const n=Z(t.point1,t.point2,e,i);n&&r.push(n)}return this._intersectionCache[e]=r,r}show(){g.stroke&&this.draw(),g.hatch&&this.hatch(),g.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,i=!1){this.angles.length>0&&this.angles.pop(),t=i?(t%360+360)%360:$(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:$(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=$(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],i=t[this.index+1]??r;return Math.abs(i-r)>180&&(i>r?i=-(360-i):r=-(360-r)),N(e-this.suma,0,this.segments[this.index],r,i,!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,i,n=1,o){rt();const s=.5,a=[],l=Math.round(this.length/s),c=new it(r+t/2,i+e/2);let h=0,u=0;for(let r=0;r<l;r++){c.plotTo(this,s,s);const r=this.calcIndex(c.plotted);h+=s,(h>=Math.max(this.segments[r]*o*k(.7,1.3),10)||r>=u)&&c.x&&(a.push([c.x-t/2,c.y-e/2]),h=0,r>=u&&u++)}return new _t(a)}show(t,e,r=1){g.stroke&&this.draw(t,e,r),g.hatch&&this.hatch(t,e,r),g.fill&&this.fill(t,e,r)}}function wt(t){new _t(t).show()}function Rt(t,e,r,i,n="corner"){"center"===n&&(t-=r/2,e-=i/2),Lt(0),Ct(t,e),Ct(t+r,e),Ct(t+r,e+i),Ct(t,e+i),Tt(!0)}function St(t,e,r,i=!1){const n=new bt("curve"),o=Math.PI*r,s=k(0,360),a=i?()=>1+.2*i*k():()=>1;for(let t=0;t<4;t++){const e=-90*t+s;n.addSegment(e*a(),o/2*a(),1,!0)}if(i){const t=i*L(-5,5);n.addSegment(s,Math.abs(t)*(Math.PI/180)*r,1,!0),n.endPlot(t+s,1,!0)}else n.endPlot(s,1,!0);const l=t-r*G(s),c=e-r*X(-s);n.show(l,c,1)}function Et(t,e,r,i,n){const o=H(i),s=((H(n)-o)%360+360)%360;if(0===s)return;const a=new bt("curve"),l=Math.max(1,Math.ceil(s/90)),c=s/l,h=Math.PI*r*c/180;for(let t=0;t<l;t++)a.addSegment(o+t*c+90,h,1,!0);a.endPlot(o+s+90,1,!0);const u=t+r*X(o),f=e-r*G(o);a.draw(u,f,1)}let At,Mt,Pt,kt;class It{constructor(){this.isClosed=!1,this.curvature=Mt,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){Dt(this.vert,this.curvature,this.isClosed).show()}}function Lt(t=0){Mt=z(t,0,1),At=new It}function Ct(t,e,r=1){if(!At)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");At.vertex(t,e,r)}function Tt(t=!1){if(!At)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(At.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(At.vertex(...At.vert[0]),At.isClosed=!0),At.show(),At=!1}function Nt(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);kt=[e,r],Pt=new bt(t)}function zt(t,e,r){if(!Pt)throw new Error("move() called without beginStroke(). Call beginStroke() first.");Pt.addSegment(t,e,r)}function Ot(t,e){if(!Pt)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");Pt.endPlot(t,e),Pt.draw(kt[0],kt[1],1),Pt=!1}function Bt(t,e=.5){if(!t||t.length<2)throw new Error("spline() requires at least 2 points. Each point should be [x, y, pressure].");Dt(t,e).draw()}function Dt(t,e=.5,r=!1){const i=new bt(0===e?"segments":"curve"),n=2*Math.PI;if(r&&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 h=t[c],u=t[c+1],f=t[c+2],g=W(h[0],h[1],u[0],u[1]),d=W(u[0],u[1],f[0],f[1]),m=j(h[0],h[1],u[0],u[1]),p=j(u[0],u[1],f[0],f[1]),x=e*Math.min(g,d,.5*Math.min(g,d)),y=Math.max(g,d),v=g-x,_=d-x;if(Math.floor(m)===Math.floor(p)){const e=r&&0===c?0:g-l,n=r?0===c?0:d-a:d;i.addSegment(m,e,h[2],!0),c===t.length-3&&i.addSegment(p,n,u[2],!0),l=0,0===c&&(o=g,a=x,s=t[1],l=0)}else{const e={x:u[0]-x*X(-m),y:u[1]-x*G(-m)},f={x:e.x+y*X(90-m),y:e.y+y*G(90-m)},g={x:u[0]+x*X(-p),y:u[1]+x*G(-p)},d={x:g.x+y*X(90-p),y:g.y+y*G(90-p)},b=Z(e,f,g,d,!0),w=W(e.x,e.y,b.x,b.y),R=W(e.x,e.y,g.x,g.y)/2,S=n*w*(2*Math.asin(R/w)*(180/Math.PI))/360,E=r&&0===c?0:v-l,A=c===t.length-3?r?o-x:_:0;i.addSegment(m,E,h[2],!0),i.addSegment(m,isNaN(S)?0:S,h[2],!0),i.addSegment(p,A,u[2],!0),l=x,0===c&&(o=v,a=x,s=[e.x,e.y])}c===t.length-3&&i.endPlot(p,u[2],!0)}else if(0===e){const e=t[c],r=t[c+1],n=W(e[0],e[1],r[0],r[1]),o=j(e[0],e[1],r[0],r[1]);i.addSegment(o,n,r[2],!0),c===t.length-2&&i.endPlot(o,1,!0)}i.origin=r&&0!==e?s:t[0]}return i}let Yt,Ft,Xt,Gt,$t,Ht=!1,Ut=0,Wt=0;const jt={},Zt={};let Vt=1,Kt=0,qt=0,Jt=1,Qt=0,te=0,ee=new Float32Array(8192),re=0,ie=2048,ne=32768;function oe(r,i,o,s){if(re>=ie){ie*=2;const t=new Float32Array(4*ie);t.set(ee),ee=t}const a=r-t/2,l=i-e/2,c=4*re;ee[c]=Vt*a+qt*l+Qt+t/2,ee[c+1]=Kt*a+Jt*l+te+e/2,ee[c+2]=n*o*Math.sqrt(Vt*Vt+Kt*Kt)/2,ee[c+3]=s/255,re++}function se(){if(0===re)return;p.glMask.isDrawn=!0;const t=g.stroke.color._array;Yt.useProgram($t),Yt.enable(Yt.BLEND),Yt.blendFunc(Yt.ONE_MINUS_DST_ALPHA,Yt.ONE),Yt.bindVertexArray(Xt),Yt.bindBuffer(Yt.ARRAY_BUFFER,Gt);const e=16*re,r=ee.subarray(0,4*re);e>ne?(Yt.bufferData(Yt.ARRAY_BUFFER,ee,Yt.DYNAMIC_DRAW),ne=ee.byteLength):Yt.bufferSubData(Yt.ARRAY_BUFFER,0,r),Yt.uniform4f(Zt.u_color,...t),Yt.uniformMatrix4fv(Zt.u_matrix,!1,Ft),Yt.drawArrays(Yt.POINTS,0,re),Yt.bindVertexArray(null),re=0,p.glMask._renderer._curShader=null}g.stroke={color:null,weight:1,clipWindow:null,type:"HB",isActive:!1,opacity:1};let ae,le,ce,he,ue=new Map,fe=null,ge={a:1,b:0,c:0,d:1,tx:0,ty:0};function de(){return{...g.stroke}}function me(t){g.stroke={...t}}function pe(t,e){if(e.type=["marker","custom","image","spray"].includes(e.type)?e.type:"default",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||"object"==typeof t&&!Array.isArray(t))return t;if("function"==typeof t)return{type:"custom",min_max:[0,1],curve:t};if(Array.isArray(t)){const[e,r,i]=2===t.length?[t[0],(t[0]+t[1])/2,t[1]]:t,n=Math.min(e,r,i),o=Math.max(e,r,i),s=o-n||1,[a,l,c]=[(e-n)/s,(r-n)/s,(i-n)/s];return{type:"custom",min_max:[n,o],curve:t=>t<.5?a+(l-a)*t*2:l+(c-l)*(t-.5)*2}}}(e.pressure),"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 Ue.add(e.image.src),e.tip=()=>{fe.image(Ue.tips.get(ke.p.image.src),-ke.p.weight/2,-ke.p.weight/2,ke.p.weight,ke.p.weight)},ue.set(t,{param:e,colors:[],buffers:[]}),Ue.load()}ue.set(t,{param:e,colors:[],buffers:[]})}function xe(){return[...ue.keys()]}function ye(t){for(const{param:e}of ue.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)}function ve(t){if(!ue.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...ue.keys()].join(", ")}.`);g.stroke.type=t}function _e(t,e,r){f(),g.stroke.color=i.color(...arguments),g.stroke.isActive=!0}function be(t){g.stroke.weight=t}function we(t,e,r=1){ve(t),_e(e),be(r)}function Re(){g.stroke.isActive=!1}function Se(){return{a:q(),b:J(),c:Q(),d:tt(),tx:V(),ty:K()}}function Ee(t,e,r){return{x:t.a*e+t.c*r+t.tx,y:t.b*e+t.d*r+t.ty}}function Ae(t){const[e,r,i,n]=t;return{minX:Math.min(e,i),minY:Math.min(r,n),maxX:Math.max(e,i),maxY:Math.max(r,n)}}function Me(t){f();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}}(Se());if(!e)throw new Error("brush.clip() cannot be used with a non-invertible transform.");g.stroke.clipWindow={bounds:Ae(t),inverse:e}}function Pe(){g.stroke.clipWindow=null}const ke={};function Ie(r,i,n,o=!1){Vt=q(),Kt=J(),qt=Q(),Jt=tt(),Qt=V(),te=K(),ge=Se(),ae=new it(r+t/2,i+e/2),le=n,ce=o,ce&&ce.calcIndex(0)}const Le=[];function Ce(r,i){i||(he=r),function(){ke.seed=999999*k();const{param:r}=ue.get(g.stroke.type)??{};if(!r)return;ke.p=r,fe=p.glMask;const{pressure:i}=r;if(ke.a="custom"!==i.type?k(-1,1):0,ke.b="custom"!==i.type?k(1,1.5):0,ke.cp="custom"!==i.type?k(3,3.5):k(-.2,.2),[ke.min,ke.max]=i.min_max,ke.noiseoffset=.03,!ce){const t=he*Math.PI/180;ke.cos=Math.cos(t),ke.sin=Math.sin(t)}(function(){m();const r=p.glMask.drawingContext,i=!Ht||Yt!==r;(i||Ut!==t||Wt!==e)&&(Ft=new Float32Array([2/t,0,0,0,0,-2/e,0,0,0,0,1,0,-1,1,0,1]),Ut=t,Wt=e),i&&(Yt=r,$t=(t=>{const e=t.createProgram();for(let[r,i]of[[t.VERTEX_SHADER,"#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;}"],[t.FRAGMENT_SHADER,"#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);}"]]){const n=t.createShader(r);t.shaderSource(n,i),t.compileShader(n),t.attachShader(e,n)}return t.linkProgram(e),e})(Yt),Yt.useProgram($t),Yt.enable(Yt.BLEND),Yt.blendFunc(Yt.ONE_MINUS_DST_ALPHA,Yt.ONE),["a_position","a_radius","a_alpha"].forEach(t=>jt[t]=Yt.getAttribLocation($t,t)),["u_matrix","u_color"].forEach(t=>Zt[t]=Yt.getUniformLocation($t,t)),Xt=Yt.createVertexArray(),Yt.bindVertexArray(Xt),Gt=Yt.createBuffer(),Yt.bindBuffer(Yt.ARRAY_BUFFER,Gt),Yt.bufferData(Yt.ARRAY_BUFFER,ee.byteLength,Yt.DYNAMIC_DRAW),ne=ee.byteLength,Yt.enableVertexAttribArray(jt.a_position),Yt.vertexAttribPointer(jt.a_position,2,Yt.FLOAT,!1,16,0),Yt.enableVertexAttribArray(jt.a_radius),Yt.vertexAttribPointer(jt.a_radius,1,Yt.FLOAT,!1,16,8),Yt.enableVertexAttribArray(jt.a_alpha),Yt.vertexAttribPointer(jt.a_alpha,1,Yt.FLOAT,!1,16,12),Yt.bindVertexArray(null),Ht=!0)})(),Be()&&p.blend(g.stroke.color),!1===p.isBrush&&(p.justChanged=!0),p.isBrush=!0,ke.alpha=Oe(),Fe()}();const n=function(){const{param:t}=ue.get(g.stroke.type)??{};return t?t.spacing:1}(),o=Math.round(le*(i?r:1)/n);for(let t=0;t<o;t++)Le.length<2*o&&Le.push(C()),Te(),i?ae.plotTo(ce,n,n,r,t<10):ae._moveToDegrees(r,n,n);se(),Fe()}function Te(t=!1){if(!Be())return;let e=t||Ne(),r=N(P(ke.seed+.002*ae.plotted,0),0,1,1-ke.noiseoffset,1+ke.noiseoffset);switch(ke.p.type){case"spray":!function(t){const e=g.stroke.weight*ke.p.scatter*t+g.stroke.weight*I(Le)*ke.p.scatter/3,r=ke.p.weight*k(.9,1.1),i=Math.ceil(ke.p.grain/t);for(let t=0;t<i;t++){const t=k(.9,1.1),i=t*e*k(-1,1),n=k(-1,1),o=Math.sqrt((t*e)**2-i**2);oe(ae.x+i,ae.y+n*o,r,ke.alpha)}}(e*r);break;case"marker":De(e*r);break;case"custom":case"image":Ye(e*r,ke.alpha);break;default:!function(t,e=1){const r=(e=N(e,0,1,.9,1.05))*g.stroke.weight*ke.p.scatter*(ke.p.sharpness+(1-ke.p.sharpness)*I(Le)/t);if(k(0,ke.p.grain*t)>.4){let e,i;if(ce)e=.7*r*k(-1,1),i=r*k(-1,1);else{const t=r*k(-1,1),n=.3*r*k(-1,1);e=t*-ke.sin+n*ke.cos,i=t*ke.cos+n*ke.sin}oe(ae.x+e,ae.y+i,t*t*ke.p.weight*k(.85,1.15)*g.stroke.weight,Math.max(.9,t)*ke.alpha*k(.75,1.1))}}(e*r)}}function Ne(){return ce?ze()*ce.pressure(ae.plotted):ze()}function ze(){return"custom"===ke.p.pressure.type?N(ke.p.pressure.curve(ae.plotted/le)+ke.cp,0,1,ke.min,ke.max,!0):function(t=.5+ke.p.pressure.curve[0]*ke.a,e=1-ke.p.pressure.curve[1]*ke.b,r=ke.cp,i=ke.min,n=ke.max){const o=t*le,s=(ae.plotted<o?1.2*e:.8*e)*(le/2);return N(1/(1+Math.pow(Math.abs((ae.plotted-o)/s),2*r)),0,1,i,n)}()}function Oe(){return["default","spray"].includes(ke.p.type)?ke.p.opacity:ke.p.opacity/Math.min(g.stroke.weight,1.3)}function Be(){const r=Ee(ge,ae.x-t/2,ae.y-e/2);if(g.stroke.clipWindow){const t=Ee(g.stroke.clipWindow.inverse,r.x,r.y),{bounds:e}=g.stroke.clipWindow;return t.x>=e.minX&&t.x<=e.maxX&&t.y>=e.minY&&t.y<=e.maxY}let i=.05*t;return r.x>=-t/2-i&&r.x<=t/2+i&&r.y>=-e/2-i&&r.y<=e/2+i}function De(t,e=!0,r=ke.alpha){const i=e?g.stroke.weight*ke.p.scatter:0,n=e?i*k(-1,1):0,o=e?i*k(-1,1):0;oe(ae.x+n,ae.y+o,g.stroke.weight*ke.p.weight*t,r)}function Ye(r,i,n=!0){p.glMask.isDrawn=!0,fe.push(),fe.noStroke(),g.stroke.color.setAlpha(i),fe.fill(g.stroke.color);const o=n?g.stroke.weight*ke.p.scatter:0,s=n?o*k(-1,1):0,a=n?o*k(-1,1):0;fe.translate(ae.x+s-t,ae.y+a-e),function(t,e){fe.scale(t),"image"===ke.p.type&&fe.tint(255,0,0,e/2);let r=0;"random"===ke.p.rotate?r=L(0,360):"natural"===ke.p.rotate&&(r=(ce?-ce.angle(ae.plotted):-he)+ae.angle()),fe.rotate(r)}(g.stroke.weight*r,i),ke.p.tip(fe),fe.pop()}function Fe(){if(Be()){let t=Ne(),e=Oe();if("marker"===ke.p.type){for(let r=1;r<10;r++)De(t*r/10,!1,5*e);se()}else if("custom"===ke.p.type||"image"===ke.p.type)for(let r=1;r<5;r++)Ye(t*r/5,e,!1)}}function Xe(t,e,r,i){if(!g.stroke.isActive||!g.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");rt();let n=W(t,e,r,i);0!=n&&(Ie(t,e,n),Ce(j(t,e,r,i),!1))}function Ge(t,e,r,i){if(!g.stroke.isActive||!g.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");rt(),Ie(t,e,r),Ce($(i),!1)}M(()=>{Le.length=0});const $e=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate"],He=[["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,.12,null,null,1,.03,{curve:[.35,.25],min_max:[1.2,.85]},"marker"]]];for(let t of He){let e={};for(let r=0;r<t[1].length;r++)e[$e[r]]=t[1][r];pe(t[0],e)}_t.prototype.draw=function(t=!1,e,r){let i=de();if(t&&we(t,e,r),i.isActive)for(let t of this.sides)Xe(t[0].x,t[0].y,t[1].x,t[1].y);me(i)},bt.prototype.draw=function(t,e,r){de().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,i){rt(),Ie(e,r,t.length,t),Ce(i,!0)}(this,t,e,r))};const Ue={tips:new Map,add(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=i.createImage(n.naturalWidth,n.naturalHeight);r.drawingContext.drawImage(n,0,0),Ue.imageToWhite(r),this.tips.set(t,r),e()},n.onerror=()=>r(new Error(`Failed to load image tip: ${t}`)),n.src=t})))}};function We(){return{...g.hatch}}function je(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let i=g.hatch;i.isActive=!0,i.dist=t,i.angle=H(e),i.options=r}function Ze(t,e="black",r=1){g.hatch.hBrush={brush:t,color:e,weight:r}}function Ve(){g.hatch.isActive=!1,g.hatch.hBrush=!1}function Ke(t){let e=g.hatch.dist,r=(g.hatch.angle%180+180)%180,i=g.hatch.options,n=de();g.hatch.hBrush&&we(...Object.values(g.hatch.hBrush)),Array.isArray(t)||(t=[t]);const o=function(t){let e={minX:Infinity,minY:Infinity,maxX:-Infinity,maxY:-Infinity};for(let r of t){const t=qe(r);e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY)}return e}(t);let s=new _t([[o.minX,o.minY],[o.maxX,o.minY],[o.maxX,o.maxY],[o.minX,o.maxY]]),a=r<=90&&r>=0?o.minY:o.maxY,l=i.gradient?N(i.gradient,0,1,1,1.1,!0):1,c=[],h=0,u=e,f=t=>({point1:{x:o.minX+u*t*X(90-r),y:a+u*t*G(90-r)},point2:{x:o.minX+u*t*X(90-r)+X(-r),y:a+u*t*G(90-r)+G(-r)}});for(;s.intersect(f(h)).length>0;){let e=[];for(let r of t)e.push(r.intersect(f(h)));c[h]=e.flat().sort((t,e)=>t.x===e.x?t.y-e.y:t.x-e.x),u*=l,h++}let d=c.filter(t=>void 0!==t[0]),m=i.rand||0;for(let t=0;t<d.length;t++){let r=d[t],n=t>0&&i.continuous;for(let i=0;i<r.length-1;i+=2)0!==m&&(r[i].x+=m*e*k(-1,1),r[i].y+=m*e*k(-1,1),r[i+1].x+=m*e*k(-1,1),r[i+1].y+=m*e*k(-1,1)),Xe(r[i].x,r[i].y,r[i+1].x,r[i+1].y),n&&Xe(d[t-1][1].x,d[t-1][1].y,r[i].x,r[i].y)}me(n)}function qe(t){if(t._boundingBox)return t._boundingBox;let e=Infinity,r=Infinity,i=-Infinity,n=-Infinity;for(let o=0;o<t.a.length;o++){const[s,a]=t.a[o];s<e&&(e=s),s>i&&(i=s),a<r&&(r=a),a>n&&(n=a)}return t._boundingBox={minX:e,minY:r,maxX:i,maxY:n},t._boundingBox}function Je(t,e,r){const i=2*Math.PI,n=r/2;p.ctx.moveTo(t+n,e),p.ctx.arc(t,e,n,0,i)}g.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},_t.prototype.hatch=function(t=!1,e,r){let i=We();t&&je(t,e,r),i.isActive&&Ke(this),function(t){g.hatch={...t}}(i)},bt.prototype.hatch=function(t,e,r){We().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,.25),this.pol.hatch())},g.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const Qe=()=>({...g.fill});function tr(t,e,r,n){g.fill.opacity=(arguments.length<4?e:n)||150,g.fill.color=arguments.length<3?i.color(t):i.color(t,e,r),g.fill.isActive=!0}function er(t,e="out"){g.fill.bleed_strength=z(t,0,1),g.fill.direction=e}function rr(t=.4,e=.4){g.fill.texture_strength=z(t,0,1),g.fill.border_strength=z(e,0,1)}function ir(){g.fill.isActive=!1}let nr;const or=[[],[]];function sr(){for(let t=0;t<512;t++)or[0][t]=C(.5,.2),or[1][t]=C(0,.02)}function ar(t,e,r){return(e.x-t.x)*(r.y-t.y)-(e.y-t.y)*(r.x-t.x)>.01}M(sr);class lr{constructor(t,e,r,i=[],n=!1,o,s){if(this.v=t,this.m=e,this.dir=i,this.midP=r,n){let e=0,i=0;const n=[];for(let o=0;o<t.length;o++){const s=Math.abs(r.x-t[o].x),a=Math.abs(r.y-t[o].y);e=Math.max(e,s),i=Math.max(i,a);const l=t[o],c=t[(o+1)%t.length],h={x:c.x-l.x,y:c.y-l.y},u=U(0,0,h.x,h.y,90),f={x:l.x+h.x/2,y:l.y+h.y/2};n.push({v1:l,v2:c,ray:{point1:f,point2:{x:f.x+u.x,y:f.y+u.y}}})}this.sizeX=e,this.sizeY=i,this.dir=Array(t.length),n.forEach((t,e)=>{let r=0;for(const e of nr.intersect(t.ray))ar(t.v1,t.v2,e)&&r++;this.dir[e]=r%2==0});const o=k(-.6,.6)*e,s=k(-.6,.6)*i;this.midP={x:r.x+o,y:r.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),r=~~(this.v.length/2-e/2),i=[...this.v],n=[...this.m],o=[...this.dir];return i.splice(r,e),n.splice(r,e),o.splice(r,e),{v:i,m:n,dir:o}}scatter(t=.3){const e=this.v.length,r=Math.max(3,~~(e*t)),i=[],n=e/r;for(let t=0;t<r;t++)i.push(~~(t*n+k(0,.8*n)));const o=[],s=[],a=[],l=this.midP,c=nr.sides;for(const t of i){const r=t%e;let i=this.v[r],n=0;for(const[t,e]of c){const r=t.y,o=e.y;if(r>i.y==o>i.y)continue;const s=(i.y-r)/(o-r);i.x<t.x+s*(e.x-t.x)&&n++}n%2==0&&(i={x:l.x+(i.x-l.x)*k(.3,.6),y:l.y+(i.y-l.y)*k(.3,.6)}),o.push(i),s.push(this.m[r]),a.push(!this.dir[r])}return new lr(o,s,this.midP,a,!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:i}=this.trim(t),n=e.length,o=2*n,s=new Array(o),a=new Array(o),l=new Array(o),c="out"===g.fill.direction?-90:90;0===or[0].length&&sr();const h=or[0],u=h.length,f=or[1],d=f.length;let m=0,p=999===t?k(.6,.8):g.fill.bleed_strength;for(let o=0;o<n;o++){const g=e[o],x=e[o+1<n?o+1:0],y=r[o],v=i[o];t<997&&(p=y);const _=(v?c:-c)+5*k(-1,1),b=X(_),w=G(_),R=x.x-g.x,S=x.y-g.y,E=b*R+w*S,A=b*S-w*R,M=h[~~(k(0,1)*u)]*k(.65,1.35)*p;s[m]=g,a[m]=y,l[m]=v,m++,s[m]={x:g.x+.5*R+E*M,y:g.y+.5*S+A*M},a[m]=y+f[~~(k(0,1)*d)],l[m]=v,m++}let x=s,y=a,v=l,_=1024/g.fill.texture_strength;if(_&&m>_){const t=Math.ceil(m/_);x=[],y=[],v=[];for(let e=0;e<m;e+=t)x.push(s[e]),y.push(a[e]),v.push(l[e])}else x.length=m,y.length=m,v.length=m;return new lr(x,y,this.midP,v,!1,this.sizeX,this.sizeY)}fill(r,i,o){const s=3*o,a=2*i*(1+o/2);p.blend(r),p.justChanged=!0,p.isBrush=!1,p.ctx.save(),p.ctx.setTransform(n*q(),n*J(),n*Q(),n*tt(),n*(V()+t/2),n*(K()+e/2)),p.ctx.strokeStyle=`rgb(${r._getRed()} ${r._getGreen()} ${r._getBlue()} / ${.005*g.fill.border_strength})`,p.ctx.lineCap="round";const l=Math.max(this.sizeX,this.sizeY),c=k(.15,.7);let h=this.grow();const u=this.scatter(.1).grow().scatter(.75).flipDirs();let f;for(let t=0;t<20;t++){t%4==0&&(h=h.grow()),t%2==0&&(f=[h.grow(1-.0125*t),h.grow(.7-.0125*t),h.grow(.4-.0125*t)]);for(const e of f)e.grow(999).grow(997).layer(t,l,a,r);u.grow(999).flipDirs().grow(997).layer(t,l,1.5*a*s,r),t%2==0&&h.grow(c).grow(999).layer(t,l,2*a,r),t%5!=0&&19!==t||(0!==s&&h.erase(3*s,i),p.blend(r,!0,!1,!0))}p.ctx.restore()}layer(t,e,r,i){var n;p.ctx.lineWidth=N(t,0,24,e/25,e/30,!0),p.ctx.fillStyle=`rgb(${i._getRed()} ${i._getGreen()} ${i._getBlue()} / ${r}%)`,n=this.v,p.ctx.beginPath(),n.forEach((t,e)=>{0===e?p.ctx.moveTo(t.x,t.y):p.ctx.lineTo(t.x,t.y)}),p.ctx.closePath(),p.ctx.fill(),p.ctx.stroke()}erase(t,e){p.ctx.save();const r=~~(k(80,110)*N(t,0,1,2,3.5)),i=this.sizeX/1.3,n=this.sizeY/1.3,o=Math.min(this.sizeX,this.sizeY)*(1.4-g.fill.bleed_strength),s=.05*o,a=.4*o,{x:l,y:c}=this.midP;p.ctx.globalCompositeOperation="destination-out";const h=(5-N(e,80,100,.3,.7,!0))*t/255;p.ctx.fillStyle=`rgb(255 0 0 / ${h})`,p.ctx.lineWidth=0;for(let t=0;t<r;t++){const e=l+C(0,i),r=c+C(0,n),o=k(s,a);p.ctx.beginPath(),Je(e,r,o),t%5!=0&&p.ctx.fill()}p.ctx.globalCompositeOperation="source-over",p.ctx.restore()}}_t.prototype.fill=function(t=!1,e,r,i,n,o){let s=Qe();t&&(tr(t,e),er(r,o),rr(i,n)),s.isActive&&(rt(),function(t){if(!g.fill.isActive||!g.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");nr=t;const e=[...t.vertices],r=~~(.25*e.length*T({1:5,2:10,3:60})),i=g.fill.bleed_strength,n=e.map((t,e)=>(e>r?1:.3)*k(.85,1.2)*i),o=L(0,e.length),s=[...e.slice(o),...e.slice(0,o)],a=function(t){if(t.length<8)return t.reduce((t,e)=>({x:t.x+e.x,y:t.y+e.y}),{x:0,y:0}).map(e=>e/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,i=0,n=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,i+=(e[t].x+e[t+1].x)*o,n+=(e[t].y+e[t+1].y)*o}return r*=.5,r?{x:i/(6*r),y:n/(6*r)}:{x:e[0].x,y:e[0].y}}(s);new lr(s,n,a,[],!0).fill(g.fill.color,N(g.fill.opacity,0,255,0,1,!0),g.fill.texture_strength)}(this)),(t=>{g.fill={...t}})(s)},bt.prototype.fill=function(t,e,r){Qe().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,N(g.fill.bleed_strength,0,.6,.3,.45,!0)),this.pol.fill())};const cr=[];"undefined"!=typeof p5&&p5.registerAddon(function(t,e,r){r.postsetup=()=>p.blend(!1,!0),r.postdraw=()=>p.blend(!1,!0);const i=e.push,n=e.pop,o=e.randomSeed,s=e.noiseSeed;e.push=function(){i.call(this),rt(),cr.push({fill:{...g.fill},stroke:{...g.stroke},hatch:{...g.hatch},field:{...g.field}})},e.pop=function(){n.call(this),function(){const t=cr.pop();t&&(g.stroke={...t.stroke},g.field={...t.field},g.hatch={...t.hatch},g.fill={...t.fill})}()},e.randomSeed=function(t){o.call(this,t),(t=>{E=R(t);for(const t of A)t()})(t)},e.noiseSeed=function(t){s.call(this,t),(t=>{P=w(R(t))})(t)}});export{bt as Plot,_t as Polygon,it as Position,pe as add,pt as addField,Et as arc,Lt as beginShape,Nt as beginStroke,xe as box,St as circle,Me as clip,Tt as endShape,Ot as endStroke,dt as field,tr as fill,er as fillBleed,rr as fillTexture,Ge as flowLine,je as hatch,Ke as hatchArray,Ze as hatchStyle,d as instance,Xe as line,xt as listFields,c as load,zt as move,Pe as noClip,mt as noField,ir as noFill,Ve as noHatch,Re as noStroke,ve as pick,wt as polygon,Rt as rect,gt as refreshField,ye as scaleBrushes,we as set,Bt as spline,_e as stroke,be as strokeWeight,Ct as vertex,T as wRand,yt as wiggle};
//# sourceMappingURL=p5.brush.esm.js.map
diff --git a/dist/p5.brush.esm.js.map b/dist/p5.brush.esm.js.map
index 79905fd..d9a2dfc 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/primitives.js","../src/core/polygon.js","../src/core/plot.js","../src/stroke/gl_draw.js","../src/stroke/stroke.js","../src/core/gl/utils.js","../src/hatch/hatch.js","../src/core/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// Section: 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\nconst Canvases = {}; // Stores canvas instances by ID\nexport let cID, Cwidth, Cheight, Instance, Renderer, Density; // Global canvas properties\n\n/**\n * Loads and initializes a canvas for the drawing system.\n * @param {string|boolean} [canvasID=false] - Optional ID of the canvas element to use.\n * If false, it uses the current window as the rendering context.\n */\nexport const load = (buffer = false) => {\n // Set renderer to specificed Buffer, Instance,, or Window\n Renderer =\n _isInstanced && !buffer\n ? Instance\n : !buffer\n ? window.self.p5.instance\n : buffer;\n\n // Check if Rendrer is webgl and throw error if it's not\n\n if (Renderer.webglVersion !== \"webgl2\") {\n throw new Error(\"p5.brush requires a WEBGL canvas\");\n }\n\n Cwidth = Renderer.width;\n Cheight = Renderer.height;\n\n _isReady = true;\n if (Renderer.loaded) Mix.load();\n};\n\nlet _isReady = false;\nlet _isInstanced = 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 _isInstanced = true;\n Instance = inst;\n};\n\n\n// =============================================================================\n// Section: Color Blending\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 * 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\nconst disable = false;\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 isBlendingGL: false,\n isWaterColor: false,\n cachedColor: new Object(),\n cachedColorGL: new Object(),\n masks: [],\n\n /**\n * Loads necessary resources and prepares the mask buffer and shader for colour blending.\n */\n load() {\n // Create Renderer masks\n if (!Renderer.loaded) {\n Renderer.mask = Renderer.createGraphics(Cwidth, Cheight, Renderer.P2D);\n Renderer.glMask = Renderer.createGraphics(\n Cwidth,\n Cheight,\n Renderer.WEBGL,\n );\n Renderer.loaded = true;\n Renderer.shaderProgram = Renderer.createShader(vertSrc, fragSrc);\n\n Density = Renderer.pixelDensity();\n\n this.mask = Renderer.mask;\n this.mask.pixelDensity(Density);\n this.mask.clear();\n this.mask.angleMode(Renderer.DEGREES);\n\n this.ctx = this.mask.drawingContext;\n\n this.glMask = Renderer.glMask;\n this.glMask.pixelDensity(Density);\n this.glMask.clear();\n this.glMask.angleMode(this.glMask.DEGREES);\n this.glMask.drawingContext.lineWidth = 0;\n // Link Matrix of GL mask to main Renderer\n this.glMask._renderer.uModelMatrix = Renderer._renderer.uModelMatrix;\n }\n },\n\n /**\n * Applies blending effects using the current color and mask.\n * @param {Color} _color - Color to blend.\n * @param {boolean} _isLast - If this is the final blend operation.\n * @param {boolean} _isImg - If blending an image.\n * @param {boolean} _isFillLayer - If this is a special case.\n */\n blend(_color = false, _isLast = false) {\n isMixReady();\n\n const mask = this.isBrush ? this.glMask : this.mask;\n const no_mask = this.isBrush ? this.mask : this.glMask;\n\n // Perf gains are minimal but let's keep it for now\n if (disable) {\n if (_isLast && mask.isDrawn) {\n Renderer.push();\n Renderer.translate(0, 0);\n Renderer.image(mask, 0, 0, Cwidth, Cheight);\n Renderer.pop();\n mask.isDrawn = false;\n }\n return;\n }\n\n // Initialize blending if not already active\n if (!this.isBlending && _color) {\n this.isBlending = true;\n this.cachedColor = _color._array;\n // Force p5 to bind its internal render target for glMask,\n // so the first glDraw() writes to the correct framebuffer.\n this.glMask.clear();\n }\n\n if (_isLast || this.cachedColor[0] !== _color._array[0] || this.cachedColor[1] !== _color._array[1] || this.cachedColor[2] !== _color._array[2] || this.cachedColor[3] !== _color._array[3]) {\n if (this.justChanged) {\n this.applyShader(no_mask);\n this.justChanged = false;\n }\n if (this.isBlending) {\n this.applyShader(mask);\n }\n this.cachedColor = _color._array;\n if (_isLast) this.isBlending = false;\n }\n },\n\n applyShader(mask) {\n let shader = Renderer.shaderProgram;\n const gl = Renderer.drawingContext;\n\n // Disable depth test for this compositing draw so the fullscreen rect\n // does not write Z=0 into the depth buffer — which would cause any\n // subsequent p5 geometry drawn at the same depth to fail depth testing\n // and become invisible.\n const hadDepthTest = gl.getParameter(gl.DEPTH_TEST);\n gl.disable(gl.DEPTH_TEST);\n\n Renderer.push();\n Renderer.translate(0, 0);\n\n // Use the blend shader for rendering\n Renderer.shader(shader);\n\n // Set shader uniforms\n shader.setUniform(\"u_source\", Renderer._renderer);\n shader.setUniform(\"u_isBrush\", this.isBrush);\n shader.setUniform(\"u_mask\", mask);\n shader.setUniform(\"u_color\", this.cachedColor);\n\n // Draw a rectangle covering the whole canvas to apply the shader\n Renderer.fill(0, 0, 0, 0);\n Renderer.noStroke();\n Renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);\n\n // Finish and clear mask\n Renderer.pop();\n Renderer.resetShader();\n\n // Restore depth test state\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n\n mask.clear();\n mask.isDrawn = false;\n },\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());\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};\n\n/**\n * Simplex‐noise 2D function.\n * @type {function(number, number): number}\n */\nexport let noise = 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};\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);\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 * Generates a random number or picks a random array element.\n * @param {number|Array} [minOrArr=0]\n * @param {number} [max=1]\n * @returns {number}\n */\nexport function random(e = 0, r = 1) {\n if (Array.isArray(e)) return rArray(e);\n if (arguments.length === 1) return rng() * e;\n return rr(e, r);\n}\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);\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 // Only if Renderer.angleMode() is set to radians\n if (Renderer.angleMode() === Renderer.RADIANS || isRad) {\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// 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 { randInt, noise, rr, sin, cos, map } 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 angle in radians, or 0 if the position is not in the flow field or if the flow field is not 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} _length - The length to move along the field.\n * @param {number} _dir - The direction of movement.\n * @param {number} _step_length - The length of each step.\n */\n moveTo(_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;\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\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 = currentField.gen(t, genField());\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 = entry.gen(0, genField());\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 */\nexport function addField(name, funct) {\n list.set(name, { gen: funct, field: null });\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 = rr(0.2, 0.8),\n ba = randInt(5, 10);\n return fillField(field, (c, r) => {\n const angle = 0.5 * ba * sin(bs * r * c + randInt(15, 25));\n return 0.2 * angle * cos(t) + noise(c, r) * ba * 0.7;\n });\n });\n // Smooth large-scale noise curves\n addField(\"curved\", (t, field) => {\n let ar = randInt(-10, 10);\n if (randInt(0, 100) % 2 == 0) ar *= -1;\n return fillField(\n field,\n (c, r) =>\n 3 * map(noise(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 = randInt(-30, -15) + Math.abs(44 * sin(t));\n if (randInt(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 = randInt(10, 15) + 5 * sin(t),\n cr = randInt(3, 6) + 3 * cos(t),\n ba = randInt(20, 35);\n return fillField(\n field,\n (c, r) => sin(sr * c) * ba * cos(r * cr) + randInt(-3, 3),\n );\n });\n // Dense oscillation from row×col product\n addField(\"seabed\", (t, field) => {\n const bs = rr(0.4, 0.8),\n ba = randInt(18, 26);\n return fillField(\n field,\n (c, r) => 1.1 * ba * sin(bs * r * c + randInt(15, 20)) * cos(t),\n );\n });\n // Radial vortex — angles spiral around the field centre\n addField(\"spiral\", (_t, field) => {\n const n = randInt(5, 10);\n const dir = randInt(0, 2) * 2 - 1;\n const offset = randInt(65, 80); // <90 = inward spiral\n const attractors = Array.from({ length: n }, () => ({\n x: rr(0.1, 0.9) * num_columns,\n y: rr(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 = randInt(3, 8),\n amp = randInt(25, 45);\n return fillField(field, (c, _r) => sin(c * freq) * amp);\n });\n}\n","import {\n rr,\n randInt,\n sin,\n cos,\n toDegrees,\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 = rr(0, 360);\n const randomFactor = r ? () => 1 + r * 0.2 * rr() : () => 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 * randInt(-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 - Radian start angle.\n * @param {number} end - Radian end angle.\n */\nexport function arc(x, y, radius, start, end) {\n const p = new Plot(\"curve\");\n const startAngle = 270 - toDegrees(start);\n const endAngle = 270 - toDegrees(end);\n const arcAngle = toDegrees(end - start);\n const arcLength = (Math.PI * radius * arcAngle) / 180;\n\n p.addSegment(startAngle, arcLength, 1, true);\n p.endPlot(endAngle, 1, true);\n\n const startX = x + radius * cos(-startAngle - 90);\n const startY = y + radius * sin(-startAngle - 90);\n p.draw(startX, startY, 1);\n}\n\n// Variables for managing paths and strokes\nlet _current;\nlet _curvature;\n\nclass SubPath {\n constructor() {\n this.isClosed = false;\n this.curvature = _curvature;\n this.vert = [];\n }\n /**\n * Adds a vertex to this subpath.\n * @param {number} x\n * @param {number} y\n * @param {number} pressure\n */\n vertex(x, y, pressure) {\n this.vert.push([x, y, pressure]);\n }\n /**\n * Renders the subpath by creating a spline from its vertices.\n */\n show() {\n let plot = _createSpline(this.vert, this.curvature, this.isClosed);\n plot.show();\n }\n}\n\n/**\n * Begins a new path with a specified curvature.\n * @param {number} [curvature=0] - Curvature from 0 to 1.\n */\nexport function beginShape(curvature = 0) {\n _curvature = constrain(curvature, 0, 1);\n _current = new SubPath();\n}\n\n/**\n * Adds a line segment from the current point to the given coordinates.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} [pressure=1] - Pressure value.\n */\nexport function vertex(x, y, pressure = 1) {\n if (!_current) {\n throw new Error(\n \"vertex() called outside of beginShape()/endShape(). Call beginShape() first.\",\n );\n }\n _current.vertex(x, y, pressure);\n}\n\n/**\n * Ends the current path and renders all subpaths.\n */\nexport function endShape(close = false) {\n if (!_current) {\n throw new Error(\n \"endShape() called without beginShape(). Call beginShape() first.\",\n );\n }\n if (_current.vert.length < 2) {\n throw new Error(\n \"endShape() requires at least 2 vertices. Add more with vertex().\",\n );\n }\n if (close) {\n _current.vertex(..._current.vert[0]);\n _current.isClosed = true;\n }\n _current.show();\n _current = false;\n}\n\nlet _strokeArray, _strokeOrigin;\n\n/**\n * Begins a new stroke with a given type and starting position.\n * @param {string} type - Stroke type.\n * @param {number} x - Starting x.\n * @param {number} y - Starting y.\n */\nexport function beginStroke(type, x, y) {\n if (type !== \"curve\" && type !== \"segments\") {\n throw new Error(\n `beginStroke() type must be \"curve\" or \"segments\", got \"${type}\".`,\n );\n }\n _strokeOrigin = [x, y];\n _strokeArray = new Plot(type);\n}\n\n/**\n * Adds a segment to the stroke.\n * @param {number} angle - Segment angle.\n * @param {number} length - Segment length.\n * @param {number} pressure - Segment pressure.\n */\nexport function move(angle, length, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"move() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.addSegment(angle, length, pressure);\n}\n\n/**\n * Completes and renders the stroke.\n * @param {number} angle - End angle.\n * @param {number} pressure - End pressure.\n */\nexport function endStroke(angle, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"endStroke() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.endPlot(angle, pressure);\n _strokeArray.draw(_strokeOrigin[0], _strokeOrigin[1], 1);\n _strokeArray = false;\n}\n\n/**\n * Creates and draws a spline curve from an array of points.\n * @param {Array<Array<number>>} array_points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature from 0 to 1.\n */\nexport function spline(_array_points, _curvature = 0.5) {\n if (!_array_points || _array_points.length < 2) {\n throw new Error(\n \"spline() requires at least 2 points. Each point should be [x, y, pressure].\",\n );\n }\n let p = _createSpline(_array_points, _curvature);\n p.draw();\n}\n\n/**\n * Creates a new Plot object representing a spline curve.\n *\n * For curved segments (curvature > 0) with at least 3 points available,\n * the function either treats segments as straight (if their angles match)\n * or calculates control points to compute a circular arc.\n *\n * If no curvature is specified, a simple straight segment is used.\n *\n * @param {Array<Array<number>>} points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature value between 0 and 1.\n * @param {boolean} [close=false] - Whether to close the spline.\n * @returns {Plot} - The generated Plot object.\n */\nfunction _createSpline(points, curvature = 0.5, close = false) {\n const plotType = curvature === 0 ? \"segments\" : \"curve\";\n const p = new Plot(plotType);\n const PI2 = Math.PI * 2;\n\n // If closing the spline, add the second point to the end\n if (close && curvature !== 0) {\n points.push(points[1]);\n }\n\n if (points && points.length > 0) {\n let done = 0; // Tracks excess length from previous segment\n let pep, tep, pep2; // Variables used for initial calibration\n\n for (let i = 0; i < points.length - 1; i++) {\n // For curved segments (if curvature > 0 and there is at least 3 points ahead)\n if (curvature > 0 && i < points.length - 2) {\n const p1 = points[i];\n const p2 = points[i + 1];\n const p3 = points[i + 2];\n\n const d1 = dist(p1[0], p1[1], p2[0], p2[1]);\n const d2 = dist(p2[0], p2[1], p3[0], p3[1]);\n const a1 = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n const a2 = calcAngle(p2[0], p2[1], p3[0], p3[1]);\n\n // Compute the adjustment length based on curvature\n const curvAdjust = curvature * Math.min(d1, d2, 0.5 * Math.min(d1, d2));\n const dmax = Math.max(d1, d2);\n const s1 = d1 - curvAdjust;\n const s2 = d2 - curvAdjust;\n\n if (Math.floor(a1) === Math.floor(a2)) {\n // If angles are nearly the same, treat as a straight segment\n const temp = close ? (i === 0 ? 0 : d1 - done) : d1 - done;\n const temp2 = close ? (i === 0 ? 0 : d2 - pep2) : d2;\n\n p.addSegment(a1, temp, p1[2], true);\n if (i === points.length - 3) {\n p.addSegment(a2, temp2, p2[2], true);\n }\n\n done = 0;\n if (i === 0) {\n pep = d1;\n pep2 = curvAdjust;\n tep = points[1];\n done = 0;\n }\n } else {\n // For a curved segment, compute control points and arc segment details\n const point1 = {\n x: p2[0] - curvAdjust * cos(-a1),\n y: p2[1] - curvAdjust * sin(-a1),\n };\n const point2 = {\n x: point1.x + dmax * cos(-a1 + 90),\n y: point1.y + dmax * sin(-a1 + 90),\n };\n const point3 = {\n x: p2[0] + curvAdjust * cos(-a2),\n y: p2[1] + curvAdjust * sin(-a2),\n };\n const point4 = {\n x: point3.x + dmax * cos(-a2 + 90),\n y: point3.y + dmax * sin(-a2 + 90),\n };\n\n const intPt = intersectLines(point1, point2, point3, point4, true);\n const radius = dist(point1.x, point1.y, intPt.x, intPt.y);\n const halfDist = dist(point1.x, point1.y, point3.x, point3.y) / 2;\n const arcAngle = 2 * Math.asin(halfDist / radius) * (180 / Math.PI);\n const arcLength = (PI2 * radius * arcAngle) / 360;\n\n const temp = close ? (i === 0 ? 0 : s1 - done) : s1 - done;\n const temp2 =\n i === points.length - 3 ? (close ? pep - curvAdjust : s2) : 0;\n\n p.addSegment(a1, temp, p1[2], true);\n p.addSegment(a1, isNaN(arcLength) ? 0 : arcLength, p1[2], true);\n p.addSegment(a2, temp2, p2[2], true);\n\n done = curvAdjust;\n if (i === 0) {\n pep = s1;\n pep2 = curvAdjust;\n tep = [point1.x, point1.y];\n }\n }\n\n if (i === points.length - 3) {\n p.endPlot(a2, p2[2], true);\n }\n } else if (curvature === 0) {\n // If no curvature, add a simple straight segment\n const p1 = points[i];\n const p2 = points[i + 1];\n const d = dist(p1[0], p1[1], p2[0], p2[1]);\n const a = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n\n p.addSegment(a, d, p2[2], true);\n if (i === points.length - 2) {\n p.endPlot(a, 1, true);\n }\n }\n }\n\n p.origin = close && curvature !== 0 ? tep : points[0];\n }\n\n return p;\n}\n","import { State } from \"./color.js\";\nimport { intersectLines } from \"./utils.js\";\n\n// =============================================================================\n// Section: Polygon Class\n// =============================================================================\n\n/**\n * Represents a polygon with a set of vertices and provides methods for\n * intersection, drawing, filling, and hatching.\n */\nexport class Polygon {\n /**\n * Constructs the Polygon object from an array of points.\n * @param {Array} pointsArray - An array of points, where each point is an array of two numbers [x, y].\n * @param {boolean} [useRawVertices=false] - If true, uses the raw array as vertices.\n */\n constructor(pointsArray, useRawVertices = false) {\n this.a = pointsArray;\n this.vertices = useRawVertices\n ? pointsArray\n : pointsArray.map(([x, y]) => ({ x, y }));\n this.sides = this.vertices.map((v, i, arr) => [\n v,\n arr[(i + 1) % arr.length],\n ]);\n this._intersectionCache = {}; // Cache for intersection results\n }\n\n /**\n * Intersects a given line with the polygon, returning all intersection points.\n * @param {Object} line - The line to intersect with the polygon, having two properties 'point1' and 'point2'.\n * @returns {Array} An array of intersection points (each with 'x' and 'y' properties) or an empty array if no intersections.\n */\n intersect(line) {\n // Check if the result has been cached\n const cacheKey = `${line.point1.x},${line.point1.y}-${line.point2.x},${line.point2.y}`;\n if (this._intersectionCache[cacheKey]) {\n return this._intersectionCache[cacheKey];\n }\n const points = [];\n for (const [start, end] of this.sides) {\n const intersection = intersectLines(line.point1, line.point2, start, end);\n if (intersection) points.push(intersection);\n }\n this._intersectionCache[cacheKey] = points; // Cache the result\n return points;\n }\n\n /**\n * Displays the polygon with optional stroke, hatch, and fill effects.\n */\n show() {\n if (State.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, rr } 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 = Math.max(this.segments[idx] * _side * rr(0.7, 1.3), 10);\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","// =============================================================================\n// Module: GL Draw\n// =============================================================================\n/**\n * The GL Draw module provides functions for rendering shapes (circles and squares)\n * using WebGL2. It initializes the WebGL context and shader programs, prepares buffers,\n * and implements drawing routines based on queued drawing primitives. The module uses\n * an orthographic projection to map canvas coordinates to clip space and supports adjustable\n * blending for translucent effects.\n */\n\nimport {\n Mix,\n Cwidth,\n Cheight,\n isMixReady,\n Density,\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\";\n\n// =============================================================================\n// Section: Initialization and Setup\n// =============================================================================\n\n// Module state\nlet isLoaded = false,\n gl,\n projMatrix,\n vao,\n buf,\n program;\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\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}\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\n\n/**\n * Initializes WebGL objects if not done already.\n */\nexport function isReady() {\n if (!isLoaded) {\n isMixReady();\n gl = Mix.glMask.drawingContext;\n projMatrix = 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\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\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 isLoaded = true;\n }\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 - Cwidth / 2;\n const py = y - Cheight / 2;\n\n const offset = circleCount * 4;\n circleData[offset] = _ma * px + _mc * py + _mx + Cwidth / 2;\n circleData[offset + 1] = _mb * px + _md * py + _my + Cheight / 2;\n // Scale the diameter by the matrix's scale factor (length of the transformed x-axis)\n circleData[offset + 2] =\n (Density * diameter * Math.sqrt(_ma * _ma + _mb * _mb)) / 2;\n circleData[offset + 3] = alpha / 255;\n circleCount++;\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\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, projMatrix);\n gl.drawArrays(gl.POINTS, 0, circleCount);\n\n gl.bindVertexArray(null);\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 Mix.glMask._renderer._curShader = null;\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 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} 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 { isReady, glDraw, circle, snapshotMatrix } 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();\n\nlet Mask = null;\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 * { type, min_max, curve } — old internal format, passed through unchanged\n */\nfunction normalizePressure(p) {\n if (!p || (typeof p === \"object\" && !Array.isArray(p))) return p;\n if (typeof p === \"function\")\n return { type: \"custom\", min_max: [0, 1], curve: p };\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 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 // 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 === \"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 params.tip = () => {\n Mask.image(\n T.tips.get(current.p.image.src),\n -current.p.weight / 2,\n -current.p.weight / 2,\n current.p.weight,\n current.p.weight,\n );\n };\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\n/**\n * Defines a clipping region for strokes.\n * @param {number[]} region - Array as [x1, y1, x2, y2] defining the clipping region.\n */\nexport function clip(region) {\n State.stroke.clipWindow = region;\n}\n\n/**\n * Disables the clipping region.\n */\nexport function noClip() {\n State.stroke.clipWindow = null;\n}\n\n/**\n * Sets the brush density by scaling standard brushes.\n * @param {number} d - Density factor.\n */\nexport function setDensity(d) {\n scaleBrushes(d);\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 {boolean} flow - Flag for vector-field following.\n * @param {Object|boolean} plot - Plot object or false.\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/**\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.moveTo(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 Mask = Mix.glMask;\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 current.cp = pressure.type !== \"custom\" ? rr(3, 3.5) : rr(-0.2, 0.2);\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 if (isInsideClippingArea()) Mix.blend(State.stroke.color);\n if (Mix.isBrush === false) Mix.justChanged = true;\n Mix.isBrush = true;\n\n // Set additional state values\n current.alpha = calculateAlpha();\n markerTip();\n}\n\n/**\n * Restores drawing state after completing a stroke.\n */\nfunction restoreState() {\n glDraw();\n markerTip();\n}\n\n/**\n * Renders the brush tip based on current pressure and position.\n * @param {number} [customPressure=false] - Optional custom pressure.\n */\nfunction tip(customPressure = false) {\n if (!isInsideClippingArea()) return;\n let pressure = customPressure || calculatePressure();\n\n let 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\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 drawTip(pressure * lineNoise, current.alpha);\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 return current.p.pressure.type === \"custom\"\n ? map(\n current.p.pressure.curve(_position.plotted / _length) + current.cp,\n 0,\n 1,\n current.min,\n current.max,\n true,\n )\n : gauss();\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 * @returns {boolean} True if inside clipping area; false otherwise.\n */\nfunction isInsideClippingArea() {\n if (State.stroke.clipWindow)\n return (\n _position.x >= State.stroke.clipWindow[0] &&\n _position.x <= State.stroke.clipWindow[2] &&\n _position.y >= State.stroke.clipWindow[1] &&\n _position.y <= State.stroke.clipWindow[3]\n );\n else {\n let w = Cwidth,\n h = Cheight,\n o = Cwidth * 0.05;\n let x = _position.x + Matrix.x();\n let y = _position.y + Matrix.y();\n return x >= -o && x <= w + o && y >= -o && y <= h + o;\n }\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\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,\n );\n}\n\n/**\n * Draws a custom or image-based brush tip.\n * @param {number} pressure - Current pressure.\n * @param {number} alpha - Alpha (opacity) for drawing.\n * @param {boolean} [vibrate=true] - Whether to apply vibration.\n */\nfunction drawTip(pressure, alpha, vibrate = true) {\n Mix.glMask.isDrawn = true;\n Mask.push();\n Mask.noStroke();\n let color = State.stroke.color;\n color.setAlpha(alpha);\n Mask.fill(State.stroke.color);\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 Mask.translate(_position.x + rx - Cwidth, _position.y + ry - Cheight);\n adjustSizeAndRotation(State.stroke.weight * pressure, alpha);\n current.p.tip(Mask);\n Mask.pop();\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 if (rr(0, current.p.grain * pressure) > 0.4) {\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 circle(\n _position.x + dx,\n _position.y + dy,\n pressure *\n pressure *\n current.p.weight *\n rr(0.85, 1.15) *\n State.stroke.weight,\n Math.max(0.9, pressure) * current.alpha * rr(0.75, 1.1),\n );\n }\n}\n\n/**\n * Adjusts the size and rotation of the brush tip before rendering.\n * @param {number} pressure - Pressure-based scaling factor.\n * @param {number} alpha - Opacity value.\n */\nfunction adjustSizeAndRotation(pressure, alpha) {\n Mask.scale(pressure);\n if (current.p.type === \"image\") {\n Mask.tint(255, 0, 0, alpha / 2);\n }\n let angle = 0;\n if (current.p.rotate === \"random\") angle = randInt(0, 360);\n else if (current.p.rotate === \"natural\") {\n angle =\n (_plot ? -_plot.angle(_position.plotted) : -_dir) + _position.angle();\n }\n Mask.rotate(angle);\n}\n\n/**\n * Draws the marker tip with a blend effect.\n */\nfunction markerTip() {\n if (isInsideClippingArea()) {\n let pressure = calculatePressure();\n let alpha = calculateAlpha(pressure);\n if (current.p.type === \"marker\") {\n for (let s = 1; s < 10; s++) {\n drawMarker((pressure * s) / 10, false, alpha * 5);\n }\n glDraw();\n } else if (current.p.type === \"custom\" || current.p.type === \"image\") {\n for (let s = 1; s < 5; s++) {\n drawTip((pressure * s) / 5, alpha, false);\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 (in radians, anticlockwise from the x-axis).\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, vibration, definition, quality, 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];\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.12,\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 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 p5img = Renderer.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.src = src;\n }),\n ),\n );\n },\n};\n\n/**\n * Loads all registered image tips. Must be awaited before setup/draw.\n * @returns {Promise}\n *\n * @example\n * // In your sketch:\n * await brush.preload();\n */\nexport async function preload() {\n await T.load();\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// Module: Hatch\n// =============================================================================\n/**\n * The Hatch module contains functions and classes dedicated to applying\n * hatch patterns over shapes and polygons. It enables the simulation of\n * cross-hatching and shading effects by drawing parallel lines or strokes\n * across a geometry. The module supports adjustable spacing, angle, and\n * optional style parameters (such as randomness, continuity, and gradient),\n * giving an artistic representation similar to hand-drawn hatching techniques.\n *\n * The implementation allows for hatching to be applied either to a Polygon\n * directly or via a Plot, extending the drawing capabilities with layered,\n * stylized textures.\n */\n\nimport { State } from \"../core/color.js\";\nimport { toDegrees, map, cos, sin, 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 and Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Global hatch state settings.\n */\nState.hatch = {\n isActive: false,\n dist: 5,\n angle: 45,\n options: {},\n hBrush: false,\n};\n\n/**\n * Returns a shallow copy of the current hatch state.\n * @returns {object} The current hatch state.\n */\nexport function HatchState() {\n return { ...State.hatch };\n}\n\n/**\n * Updates the global hatch state.\n * @param {object} state - The new hatch state.\n */\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Style Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Activates hatching for subsequent geometries.\n *\n * @param {number} dist - The distance between hatching lines.\n * @param {number} angle - The angle (in degrees) at which hatching lines are drawn.\n * @param {object} options - Optional parameters to affect the hatching style:\n * - rand: Number value to introduce randomness.\n * - continuous: Boolean to connect adjacent lines.\n * - gradient: Number to gradually change spacing.\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 = angle;\n s.options = options;\n}\n\n/**\n * Sets the hatch brush style for subsequent hatching.\n *\n * @param {string} brush - The brush name.\n * @param {string|Color} color - The brush color.\n * @param {number} weight - The brush weight (size).\n */\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\n/**\n * Disables hatching.\n */\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fill Manager Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a hatching pattern over the given polygon(s).\n *\n * @param {Polygon|Polygon[]} polygons - A polygon or an array of polygons.\n */\nexport function createHatch(polygons) {\n let dist = State.hatch.dist;\n let angle = toDegrees(State.hatch.angle) % 180; // normalize to [0, 180)\n let options = State.hatch.options;\n\n // Save current stroke state\n let save = BrushState();\n // If a hatch brush is set, override with those parameters.\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n\n // Compute overall bounding box for all polygons.\n if (!Array.isArray(polygons)) polygons = [polygons];\n const overallBB = computeOverallBoundingBox(polygons);\n\n // Build a bounding polygon based on the overall bounding box.\n let ventana = new Polygon([\n [overallBB.minX, overallBB.minY],\n [overallBB.maxX, overallBB.minY],\n [overallBB.maxX, overallBB.maxY],\n [overallBB.minX, overallBB.maxY],\n ]);\n\n // Determine starting y coordinate based on angle.\n let startY = angle <= 90 && angle >= 0 ? overallBB.minY : overallBB.maxY;\n let gradient = options.gradient\n ? map(options.gradient, 0, 1, 1, 1.1, true)\n : 1;\n let dots = [];\n let i = 0;\n let dist1 = dist;\n\n // Function to generate a line for index i.\n let linea = (i) => {\n return {\n point1: {\n x: overallBB.minX + dist1 * i * cos(-angle + 90),\n y: startY + dist1 * i * sin(-angle + 90),\n },\n point2: {\n x: overallBB.minX + dist1 * i * cos(-angle + 90) + cos(-angle),\n y: startY + dist1 * i * sin(-angle + 90) + sin(-angle),\n },\n };\n };\n\n // Generate lines and calculate intersections with polygons\n // Loop through the lines based on the distance and angle to calculate intersections with the polygons\n // The loop continues until a line does not intersect with the bounding window polygon\n // Each iteration accounts for the gradient effect by adjusting the distance between lines\n while (ventana.intersect(linea(i)).length > 0) {\n let tempArray = [];\n for (let p of polygons) {\n tempArray.push(p.intersect(linea(i)));\n }\n dots[i] = tempArray\n .flat()\n .sort((a, b) => (a.x === b.x ? a.y - b.y : a.x - b.x));\n dist1 *= gradient;\n i++;\n }\n\n // Filter out empty intersection sets.\n let gdots = dots.filter((dd) => typeof dd[0] !== \"undefined\");\n\n // Draw the hatching lines using the calculated intersections\n // If the 'rand' option is enabled, add randomness to the start and end points of the lines\n // If the 'continuous' option is set, connect the end of one line to the start of the next\n let r = options.rand || 0;\n for (let j = 0; j < gdots.length; j++) {\n let dd = gdots[j];\n let continuousLine = j > 0 && options.continuous;\n for (let i = 0; i < dd.length - 1; i += 2) {\n if (r !== 0) {\n dd[i].x += r * dist * rr(-1, 1);\n dd[i].y += r * dist * rr(-1, 1);\n dd[i + 1].x += r * dist * rr(-1, 1);\n dd[i + 1].y += r * dist * rr(-1, 1);\n }\n line(dd[i].x, dd[i].y, dd[i + 1].x, dd[i + 1].y);\n if (continuousLine) {\n line(gdots[j - 1][1].x, gdots[j - 1][1].y, dd[i].x, dd[i].y);\n }\n }\n }\n\n // Restore previous brush state.\n BrushSetState(save);\n}\n\n/**\n * Computes the bounding box for a single polygon.\n * @param {Polygon} polygon - The polygon to evaluate.\n * @returns {object} The bounding box as {minX, minY, maxX, maxY}.\n */\nfunction computeBoundingBoxForPolygon(polygon) {\n if (polygon._boundingBox) return polygon._boundingBox;\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n for (let i = 0; i < polygon.a.length; i++) {\n const [x, y] = polygon.a[i];\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n }\n polygon._boundingBox = { minX, minY, maxX, maxY };\n return polygon._boundingBox;\n}\n\n/**\n * Computes an overall bounding box for an array of polygons.\n * @param {Array} polygons - Array of Polygon objects.\n * @returns {object} The overall bounding box {minX, minY, maxX, maxY}.\n */\nfunction computeOverallBoundingBox(polygons) {\n let overall = {\n minX: Infinity,\n minY: Infinity,\n maxX: -Infinity,\n maxY: -Infinity,\n };\n for (let poly of polygons) {\n const bb = computeBoundingBoxForPolygon(poly);\n overall.minX = Math.min(overall.minX, bb.minX);\n overall.minY = Math.min(overall.minY, bb.minY);\n overall.maxX = Math.max(overall.maxX, bb.maxX);\n overall.maxY = Math.max(overall.maxY, bb.maxY);\n }\n return overall;\n}\n\n// ---------------------------------------------------------------------------\n// Extend Polygon and Plot Prototypes\n// ---------------------------------------------------------------------------\n\n/**\n * Adds a hatch effect to the polygon.\n *\n * If a distance is provided, activates hatching with the given parameters.\n * Then, if hatch is active, applies the hatching pattern.\n *\n * @param {number} [_dist] - The distance between hatch lines.\n * @param {number} _angle - The angle (in degrees) for hatching.\n * @param {object} _options - Optional hatch options.\n */\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (state.isActive) {\n createHatch(this);\n }\n HatchSetState(state);\n};\n\n/**\n * Applies hatching to a plot.\n *\n * If hatching is active, generates a polygon from the plot and applies hatch.\n *\n * @param {number} x - The x-coordinate to draw at.\n * @param {number} y - The y-coordinate to draw at.\n * @param {number} scale - Scaling factor.\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 \"./color.js\";\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 Mix.ctx.beginPath();\n vertices.forEach((v, i) => {\n if (i === 0) Mix.ctx.moveTo(v.x, v.y);\n else Mix.ctx.lineTo(v.x, v.y);\n });\n Mix.ctx.closePath();\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 radius = d / 2;\n Mix.ctx.moveTo(x + radius, y);\n Mix.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 { Renderer, Mix, State, Cwidth, Cheight, Density } from \"../core/color.js\";\nimport { drawPolygon, circle } from \"../core/mask.js\";\nimport {\n constrain,\n weightedRand,\n rr,\n map,\n randInt,\n gaussian,\n rArray,\n rotate,\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/**\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 _gaussians = [[], []]; // [a, b]\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 < 8) {\n // Simple average for small polygons\n return pts\n .reduce((c, p) => ({ x: c.x + p.x, y: c.y + p.y }), { x: 0, y: 0 })\n .map((v) => v / 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\n // Map vertices\n const fluid = ~~(v.length * 0.25 * weightedRand({ 1: 5, 2: 10, 3: 60 }));\n const strength = State.fill.bleed_strength;\n\n // Create bleed modifiers\n const modifiers = v.map(\n (_, i) => (i > fluid ? 1 : 0.3) * rr(0.85, 1.2) * strength,\n );\n\n // Randomize starting point\n const shift = randInt(0, v.length);\n const shifted = [...v.slice(shift), ...v.slice(0, shift)];\n\n // Calculate center and create FillPolygon\n const center = _center(shifted);\n 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 // Clone and splice\n const v = [...this.v],\n m = [...this.m],\n dir = [...this.dir];\n v.splice(s, n);\n m.splice(s, n);\n dir.splice(s, n);\n\n return { v, m, dir };\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 // Get trimmed vertices\n const { v: tr_v, m: tr_m, dir: tr_dir } = this.trim(f);\n const len = tr_v.length;\n\n // Pre-allocate arrays for better performance\n const newVerts = [],\n newMods = [],\n newDirs = [];\n\n // Determine bleed direction\n const bleedDirDeg = State.fill.direction === \"out\" ? -90 : 90;\n\n // Process vertices\n let idx = 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 // compute two gaussians if necessary\n if (_gaussians[0].length < len * 1.5) {\n _gaussians[0].push(gaussian(0.5, 0.2));\n _gaussians[1].push(gaussian(0, 0.02));\n }\n\n const cv = tr_v[i];\n const nv = i + 1 < len ? tr_v[i + 1] : tr_v[0];\n\n // Use existing modifier or calculate new one\n if (f < 997) mod = tr_m[i];\n\n // Calculate rotation\n const rotDeg = (tr_dir[i] ? bleedDirDeg : -bleedDirDeg) + rr(-1, 1) * 5;\n const sideX = nv.x - cv.x;\n const sideY = nv.y - cv.y;\n const { x: dirX, y: dirY } = rotate(0, 0, sideX, sideY, rotDeg);\n\n // pick a random point along the edge\n const t = 0.5;\n // compute outward distance\n const d = rArray(_gaussians[0]) * rr(0.65, 1.35) * mod;\n\n // first vertex: stay at cv\n newVerts[idx] = cv;\n newMods[idx] = tr_m[i];\n newDirs[idx++] = tr_dir[i];\n\n // second vertex: offset by lerp + outward push\n newVerts[idx] = {\n x: cv.x + sideX * t + dirX * d,\n y: cv.y + sideY * t + dirY * d,\n };\n newMods[idx] = tr_m[i] + rArray(_gaussians[1]);\n newDirs[idx++] = tr_dir[i];\n }\n return new FillPoly(\n newVerts,\n newMods,\n this.midP,\n newDirs,\n false,\n this.sizeX,\n this.sizeY,\n );\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 // Precalculate stuff\n const numLayers = 20;\n const texture = tex * 3;\n const int = 2 * intensity * (1 + tex / 2);\n\n // Perform initial setup only once\n Mix.blend(color);\n Mix.justChanged = true;\n Mix.isBrush = false;\n\n Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * Matrix.a(), Density * Matrix.b(),\n Density * Matrix.c(), 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\n // Create initial polygon\n let pol = this.grow();\n let pols;\n\n for (let i = 0; i < numLayers; i++) {\n // Grow polygon every 4 layers\n if (i % 4 === 0) pol = pol.grow();\n\n // Create variant polygons\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 // Draw layers\n for (const p of pols) p.grow(999).grow(997).layer(i, size, int, color);\n if (i % 2 === 0)\n pol\n .grow(darker)\n .grow(999)\n .layer(i, size, int * 2, color);\n\n // Apply texture and blend periodically\n if (i % 5 === 0 || i === numLayers - 1) {\n if (texture !== 0) pol.erase(texture * 3, intensity);\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 Mix.ctx.fillStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${int}%)`;\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 // Optimize by pre-calculating values\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.4 - State.fill.bleed_strength);\n const minSizeFactor = 0.05 * minSize;\n const maxSizeFactor = 0.4 * minSize;\n const { x: midX, y: midY } = this.midP;\n\n // Set up erase mode\n Mix.ctx.globalCompositeOperation = \"destination-out\";\n\n // Calculate transparency\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 // Draw erase circles\n for (let i = 0; i < numCircles; i++) {\n const x = midX + gaussian(0, halfSizeX);\n const y = midY + gaussian(0, halfSizeY);\n const size = rr(minSizeFactor, maxSizeFactor);\n\n Mix.ctx.beginPath();\n circle(x, y, size);\n if (i % 5 !== 0) Mix.ctx.fill();\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 map(State.fill.bleed_strength, 0, 0.6, 0.3, 0.45, 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 * @version 2.0.0-alpha\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\n *\n * // Fill textures:\n * brush.noStroke();\n * brush.fill('#FF0000', 90); // Set fill color to red and opacity to 90\n * brush.bleed(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-2024 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 preload,\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 { Mix } 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.postsetup = () => Mix.blend(false, true);\n lifecycles.postdraw = () => Mix.blend(false, true);\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","load","buffer","_isInstanced","window","self","p5","instance","webglVersion","Error","width","height","_isReady","loaded","Mix","isCanvasReady","State","inst","isMixReady","isBlending","isBlendingGL","isWaterColor","cachedColor","Object","cachedColorGL","masks","mask","createGraphics","P2D","glMask","WEBGL","shaderProgram","createShader","pixelDensity","this","clear","angleMode","DEGREES","ctx","drawingContext","lineWidth","_renderer","uModelMatrix","blend","_color","_isLast","isBrush","no_mask","_array","justChanged","applyShader","shader","gl","hadDepthTest","getParameter","DEPTH_TEST","disable","push","translate","setUniform","fill","noStroke","rect","pop","resetShader","enable","isDrawn","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","c","s0","s1","s2","copy","f","rng","noise","rr","e","rArray","array","randInt","gaussian","mean","stdev","u","log","cos","weightedRand","weights","totalWeight","entries","key","cumulative","rnd","isNaN","parseInt","value","a","b","d","withinBounds","constrain","low","high","max","min","nAngle","angle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","NaN","sLookup","idx","sin","toDegrees","rad","isRad","RADIANS","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","mat4","isLoaded","isFieldReady","resolution","left_x","top_y","num_columns","round","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","plotTo","_plot","_scale","_dirPlot","_step","scaleFactor","y_offset","x_offset","col","row","_current","_curvature","_strokeArray","_strokeOrigin","Map","refreshField","currentField","gen","genField","has","keys","join","entry","noField","name","funct","set","listFields","fn","Polygon","pointsArray","useRawVertices","vertices","sides","arr","_intersectionCache","intersect","line","cacheKey","point1","point2","points","start","end","intersection","show","stroke","draw","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","startAngle","endAngle","arcAngle","startX","startY","SubPath","isClosed","curvature","vert","_createSpline","close","beginStroke","move","endStroke","spline","_array_points","PI2","pep","tep","pep2","done","p1","p2","p3","d1","d2","a1","a2","curvAdjust","dmax","temp","temp2","point3","point4","intPt","halfDist","asin","origin","projMatrix","vao","buf","program","Attr","Frag","_ma","_mb","_mc","_md","_mx","_my","circleData","INITIAL_CAPACITY","circleCount","bufferCapacity","gpuBufferSize","diameter","alpha","newData","px","py","glDraw","color","useProgram","BLEND","blendFunc","ONE_MINUS_DST_ALPHA","ONE","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","uniform4f","u_color","uniformMatrix4fv","u_matrix","drawArrays","POINTS","_curShader","weight","clipWindow","opacity","_position","Mask","BrushState","BrushSetState","state","add","params","includes","undefined","vibration","scatter","definition","sharpness","quality","grain","isArray","min_max","curve","m","range","ns","nm","ne","normalizePressure","image","src","T","tip","tips","param","colors","buffers","box","scaleBrushes","values","spacing","pick","brushName","g","arguments","strokeWeight","clip","region","noClip","initializeDrawingState","plot","gaussians","angleScale","isPlot","cp","noiseoffset","dirRad","createProgram","VERTEX_SHADER","FRAGMENT_SHADER","shaderSource","compileShader","attachShader","linkProgram","forEach","getAttribLocation","getUniformLocation","createVertexArray","createBuffer","stride","enableVertexAttribArray","a_position","vertexAttribPointer","FLOAT","a_radius","a_alpha","isReady","isInsideClippingArea","calculateAlpha","markerTip","saveState","stepSize","totalSteps","customPressure","calculatePressure","lineNoise","sw","iterations","ceil","rX","yRandomFactor","sqrtPart","drawSpray","drawMarker","drawTip","perp","along","drawDefault","simPressure","peakPos","halfWidth","pow","gauss","o","vibrate","rx","ry","setAlpha","tint","adjustSizeAndRotation","flowLine","_vals","_standard_brushes","obj","prototype","_brush","_weight","imageToWhite","loadPixels","average","pixels","updatePixels","filter","k","Promise","all","resolve","reject","nativeImg","Image","onload","p5img","createImage","naturalWidth","naturalHeight","drawImage","onerror","async","preload","HatchState","options","rand","continuous","gradient","hatchStyle","brush","hBrush","noHatch","createHatch","polygons","save","overallBB","overall","minX","Infinity","minY","maxX","maxY","poly","bb","computeBoundingBoxForPolygon","computeOverallBoundingBox","ventana","dots","dist1","linea","tempArray","flat","sort","gdots","dd","continuousLine","_boundingBox","_dist","_angle","_options","HatchSetState","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","noFill","_polygon","_gaussians","_isLeft","FillPoly","center","isFirst","sx","sy","midP","rayCalc","v1","v2","side","rt","mid","ray","sizeX","sizeY","rc","count","isect","trim","splice","grow","tr_v","tr_m","tr_dir","newVerts","newMods","newDirs","bleedDirDeg","mod","cv","nv","rotDeg","sideX","sideY","dirX","dirY","intensity","tex","texture","int","setTransform","strokeStyle","_getRed","_getGreen","_getBlue","lineCap","size","darker","pols","layer","numLayers","erase","restore","fillStyle","beginPath","lineTo","closePath","numCircles","halfSizeX","halfSizeY","minSize","minSizeFactor","maxSizeFactor","midX","midY","globalCompositeOperation","_opacity","_bleed","fluid","strength","modifiers","_","shift","shifted","slice","pts","area","cross","_center","createFill","FillSetState","_stateStack","registerAddon","_p5","lifecycles","postsetup","postdraw","_push","_pop","_randomSeed","randomSeed","_noiseSeed","noiseSeed","call","saved","brushPop","brushSeed","brushNoiseSeed"],"mappings":"AAaU,IAAMA,EAAQC,EAASC,EAAUC,EAAUC,EAOzC,MAACC,EAAO,CAACC,GAAS,KAW5B,GATAH,EACEI,IAAiBD,EACbJ,EACCI,GACCE,OAAOC,KAAKC,GAAGC,SAKO,WAA1BR,EAASS,aACX,MAAM,IAAIC,MAAM,oCAGlBb,EAASG,EAASW,MAClBb,EAAUE,EAASY,OAEnBC,GAAW,EACPb,EAASc,QAAQC,EAAIb,QAG3B,IAAIW,GAAW,EACXT,GAAe,EAKZ,MAAMY,EAAgB,KACtBH,GAAUX,KAOJe,EAAQ,CAAA,EAERT,EAAYU,IACvBd,GAAe,EACfL,EAAWmB,GAeAC,EAAa,KACnBnB,EAASc,SACZE,IACAD,EAAIb,SAcKa,EAAM,CACjBK,YAAY,EACZC,cAAc,EACdC,cAAc,EACdC,YAAa,IAAIC,OACjBC,cAAe,IAAID,OACnBE,MAAO,GAKP,IAAAxB,GAEOF,EAASc,SACZd,EAAS2B,KAAO3B,EAAS4B,eAAe/B,EAAQC,EAASE,EAAS6B,KAClE7B,EAAS8B,OAAS9B,EAAS4B,eACzB/B,EACAC,EACAE,EAAS+B,OAEX/B,EAASc,QAAS,EAClBd,EAASgC,cAAgBhC,EAASiC,muaAElChC,EAAUD,EAASkC,eAEnBC,KAAKR,KAAO3B,EAAS2B,KACrBQ,KAAKR,KAAKO,aAAajC,GACvBkC,KAAKR,KAAKS,QACVD,KAAKR,KAAKU,UAAUrC,EAASsC,SAE7BH,KAAKI,IAAMJ,KAAKR,KAAKa,eAErBL,KAAKL,OAAS9B,EAAS8B,OACvBK,KAAKL,OAAOI,aAAajC,GACzBkC,KAAKL,OAAOM,QACZD,KAAKL,OAAOO,UAAUF,KAAKL,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AAM2S,OAClB5F,MAAO,IAAK/M,EAAM+M,QCoHpB,EAEAwE,EAAGxO,IAAM,WACPspB,EAAKK,KAAKxrB,MDhHP,WACL,MAAMyrB,EAAQb,GAAY/oB,MACrB4pB,IACL3sB,EAAMyS,OAAS,IAAKka,EAAMla,QAC1BzS,EAAM+M,MAAQ,IAAK4f,EAAM5f,OACzB/M,EAAM2S,MAAQ,IAAKga,EAAMha,OACzB3S,EAAM4C,KAAO,IAAK+pB,EAAM/pB,MAC1B,CC0GIgqB,EACF,EAEArb,EAAGgb,WAAa,SAAUxnB,GACxBunB,EAAYI,KAAKxrB,KAAM6D,GZ9HP,CAACA,IACnB4C,EAAMzB,EAAUnB,IY8Hd8nB,CAAU9nB,EACZ,EAEAwM,EAAGkb,UAAY,SAAU1nB,GACvBynB,EAAWE,KAAKxrB,KAAM6D,GZpHD,CAACA,IACxB6C,EAAQ/D,EAAcqC,EAAUnB,KYoH9B+nB,CAAe/nB,EACjB,CACF","x_google_ignoreList":[1,2]}
\ No newline at end of file
+{"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/stroke/gl_draw.js","../src/stroke/stroke.js","../src/core/gl/utils.js","../src/hatch/hatch.js","../src/core/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// Section: 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\nconst isFramebufferTarget = (target) =>\n !!target &&\n typeof target.begin === \"function\" &&\n typeof target.end === \"function\" &&\n !!target.renderer &&\n !!target.renderer._pInst;\n\nconst getSketchRenderer = () =>\n _isInstanced ? Instance : window.self.p5.instance;\n\nconst isSupportedFramebufferTarget = (target) =>\n isFramebufferTarget(target) && target.renderer._pInst === getSketchRenderer();\n\nconst resolveTarget = (buffer = false) => {\n if (_isInstanced && !buffer) {\n return {\n renderer: Instance,\n width: Instance.width,\n height: Instance.height,\n };\n }\n\n if (!buffer) {\n const renderer = getSketchRenderer();\n return {\n renderer,\n width: renderer.width,\n height: renderer.height,\n };\n }\n\n if (isFramebufferTarget(buffer)) {\n if (!isSupportedFramebufferTarget(buffer)) {\n throw new Error(\n \"p5.brush only supports p5.Framebuffer targets created from the active sketch. Framebuffers created from p5.Graphics are not supported.\",\n );\n }\n\n return {\n renderer: getSketchRenderer(),\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\nconst removeTargetBuffer = (buffer) => {\n if (buffer && typeof buffer.remove === \"function\") {\n buffer.remove();\n }\n};\n\nconst getGraphicsFactory = () =>\n typeof Renderer.createGraphics === \"function\" ? Renderer : Renderer._pInst;\n\nconst getActiveFramebuffer = () =>\n Renderer &&\n Renderer._renderer &&\n typeof Renderer._renderer.activeFramebuffer === \"function\"\n ? Renderer._renderer.activeFramebuffer()\n : null;\n\nconst needsBlendSourceFramebuffer = (framebuffer) =>\n !framebuffer ||\n framebuffer.width !== Cwidth ||\n framebuffer.height !== Cheight ||\n (typeof framebuffer.pixelDensity === \"function\" &&\n framebuffer.pixelDensity() !== Density);\n\nconst needsMixBuffers = () =>\n !Renderer.mask ||\n !Renderer.glMask ||\n Renderer.mask.width !== Cwidth ||\n Renderer.mask.height !== Cheight ||\n Renderer.glMask.width !== Cwidth ||\n Renderer.glMask.height !== Cheight;\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\n // Check if Rendrer is webgl and throw error if it's not\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;\nlet _isInstanced = 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 _isInstanced = true;\n Instance = inst;\n};\n\n\n// =============================================================================\n// Section: Color Blending\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 * 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\nconst disable = false;\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 captureBlendSource() {\n const activeFramebuffer = getActiveFramebuffer();\n\n if (!activeFramebuffer) return Renderer._renderer;\n\n if (needsBlendSourceFramebuffer(Renderer.blendSourceFramebuffer)) {\n removeTargetBuffer(Renderer.blendSourceFramebuffer);\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 const source = Renderer.blendSourceFramebuffer;\n\n source.draw(() => {\n Renderer.clear();\n Renderer.push();\n if (typeof Renderer.imageMode === \"function\") {\n Renderer.imageMode(Renderer.CENTER ?? Renderer._renderer?._pInst?.CENTER);\n }\n Renderer.image(activeFramebuffer, 0, 0, Cwidth, Cheight);\n Renderer.pop();\n });\n\n return source;\n },\n\n /**\n * Loads necessary resources and prepares the mask buffer and shader for colour blending.\n */\n load() {\n Density = Renderer.pixelDensity();\n const graphicsFactory = getGraphicsFactory();\n const p2dMode = graphicsFactory.P2D ?? Renderer.P2D;\n const webglMode = graphicsFactory.WEBGL ?? Renderer.WEBGL;\n\n if (!Renderer.loaded || needsMixBuffers()) {\n removeTargetBuffer(Renderer.mask);\n removeTargetBuffer(Renderer.glMask);\n\n Renderer.mask = graphicsFactory.createGraphics(Cwidth, Cheight, p2dMode);\n Renderer.glMask = graphicsFactory.createGraphics(\n Cwidth,\n Cheight,\n webglMode,\n );\n Renderer.loaded = true;\n Renderer.shaderProgram ??= Renderer.createShader(vertSrc, fragSrc);\n\n this.mask = Renderer.mask;\n this.mask.pixelDensity(Density);\n this.mask.clear();\n this.mask.angleMode(Renderer.DEGREES);\n\n this.ctx = this.mask.drawingContext;\n\n this.glMask = Renderer.glMask;\n this.glMask.pixelDensity(Density);\n this.glMask.clear();\n this.glMask.angleMode(this.glMask.DEGREES);\n this.glMask.drawingContext.lineWidth = 0;\n } else {\n this.mask = Renderer.mask;\n this.glMask = Renderer.glMask;\n this.ctx = this.mask.drawingContext;\n }\n\n // Link Matrix of GL mask to main Renderer\n this.glMask._renderer.uModelMatrix = Renderer._renderer.uModelMatrix;\n },\n\n /**\n * Applies blending effects using the current color and mask.\n * @param {Color} _color - Color to blend.\n * @param {boolean} _isLast - If this is the final blend operation.\n * @param {boolean} _isImg - If blending an image.\n * @param {boolean} _isFillLayer - If this is a special case.\n */\n blend(_color = false, _isLast = false) {\n isMixReady();\n\n const mask = this.isBrush ? this.glMask : this.mask;\n const no_mask = this.isBrush ? this.mask : this.glMask;\n\n // Perf gains are minimal but let's keep it for now\n if (disable) {\n if (_isLast && mask.isDrawn) {\n Renderer.push();\n Renderer.translate(0, 0);\n Renderer.image(mask, 0, 0, Cwidth, Cheight);\n Renderer.pop();\n mask.isDrawn = false;\n }\n return;\n }\n\n // Initialize blending if not already active\n if (!this.isBlending && _color) {\n this.isBlending = true;\n this.cachedColor = _color._array;\n // Force p5 to bind its internal render target for glMask,\n // so the first glDraw() writes to the correct framebuffer.\n this.glMask.clear();\n }\n\n if (_isLast || this.cachedColor[0] !== _color._array[0] || this.cachedColor[1] !== _color._array[1] || this.cachedColor[2] !== _color._array[2] || this.cachedColor[3] !== _color._array[3]) {\n if (this.justChanged) {\n this.applyShader(no_mask);\n this.justChanged = false;\n }\n if (this.isBlending) {\n this.applyShader(mask);\n }\n this.cachedColor = _color._array;\n if (_isLast) this.isBlending = false;\n }\n },\n\n applyShader(mask) {\n let shader = Renderer.shaderProgram;\n const gl = Renderer.drawingContext;\n const targetIsFramebuffer = !!getActiveFramebuffer();\n const source = this.captureBlendSource();\n\n // Disable depth test for this compositing draw so the fullscreen rect\n // does not write Z=0 into the depth buffer — which would cause any\n // subsequent p5 geometry drawn at the same depth to fail depth testing\n // and become invisible.\n const hadDepthTest = gl.getParameter(gl.DEPTH_TEST);\n gl.disable(gl.DEPTH_TEST);\n\n Renderer.push();\n Renderer.translate(0, 0);\n\n // Use the blend shader for rendering\n Renderer.shader(shader);\n\n // Set shader uniforms\n shader.setUniform(\"u_source\", source);\n shader.setUniform(\"u_isBrush\", this.isBrush);\n shader.setUniform(\"u_flipOutputY\", targetIsFramebuffer);\n shader.setUniform(\"u_mask\", mask);\n shader.setUniform(\"u_color\", this.cachedColor);\n\n // Draw a rectangle covering the whole canvas to apply the shader\n Renderer.fill(0, 0, 0, 0);\n Renderer.noStroke();\n Renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);\n\n // Finish and clear mask\n Renderer.pop();\n Renderer.resetShader();\n\n // Restore depth test state\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n\n mask.clear();\n mask.isDrawn = false;\n },\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());\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 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()));\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};\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);\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);\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 { randInt, noise, rr, 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 = rr(0.2, 0.8),\n ba = randInt(5, 10);\n return fillField(field, (c, r) => {\n const angle = 0.5 * ba * sin(bs * r * c + randInt(15, 25));\n return 0.2 * angle * cos(t) + noise(c, r) * ba * 0.7;\n });\n });\n // Smooth large-scale noise curves\n addField(\"curved\", (t, field) => {\n let ar = randInt(-10, 10);\n if (randInt(0, 100) % 2 == 0) ar *= -1;\n return fillField(\n field,\n (c, r) =>\n 3 * map(noise(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 = randInt(-30, -15) + Math.abs(44 * sin(t));\n if (randInt(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 = randInt(10, 15) + 5 * sin(t),\n cr = randInt(3, 6) + 3 * cos(t),\n ba = randInt(20, 35);\n return fillField(\n field,\n (c, r) => sin(sr * c) * ba * cos(r * cr) + randInt(-3, 3),\n );\n });\n // Dense oscillation from row×col product\n addField(\"seabed\", (t, field) => {\n const bs = rr(0.4, 0.8),\n ba = randInt(18, 26);\n return fillField(\n field,\n (c, r) => 1.1 * ba * sin(bs * r * c + randInt(15, 20)) * cos(t),\n );\n });\n // Radial vortex — angles spiral around the field centre\n addField(\"spiral\", (_t, field) => {\n const n = randInt(5, 10);\n const dir = randInt(0, 2) * 2 - 1;\n const offset = randInt(65, 80); // <90 = inward spiral\n const attractors = Array.from({ length: n }, () => ({\n x: rr(0.1, 0.9) * num_columns,\n y: rr(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 = randInt(3, 8),\n amp = randInt(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, rr } 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 = Math.max(this.segments[idx] * _side * rr(0.7, 1.3), 10);\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 rr,\n randInt,\n sin,\n cos,\n toDegrees,\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 = rr(0, 360);\n const randomFactor = r ? () => 1 + r * 0.2 * rr() : () => 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 * randInt(-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// Module: GL Draw\n// =============================================================================\n/**\n * The GL Draw module provides functions for rendering shapes (circles and squares)\n * using WebGL2. It initializes the WebGL context and shader programs, prepares buffers,\n * and implements drawing routines based on queued drawing primitives. The module uses\n * an orthographic projection to map canvas coordinates to clip space and supports adjustable\n * blending for translucent effects.\n */\n\nimport {\n Mix,\n Cwidth,\n Cheight,\n isMixReady,\n Density,\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\";\n\n// =============================================================================\n// Section: Initialization and Setup\n// =============================================================================\n\n// Module state\nlet isLoaded = false,\n gl,\n projMatrix,\n vao,\n buf,\n program;\nlet loadedWidth = 0,\n loadedHeight = 0;\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\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}\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\n\n/**\n * Initializes WebGL objects if not done already.\n */\nexport function isReady() {\n isMixReady();\n\n const nextGl = Mix.glMask.drawingContext;\n const needsContextRefresh = !isLoaded || gl !== nextGl;\n const needsProjectionRefresh =\n needsContextRefresh || loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (needsProjectionRefresh) {\n projMatrix = 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 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 - Cwidth / 2;\n const py = y - Cheight / 2;\n\n const offset = circleCount * 4;\n circleData[offset] = _ma * px + _mc * py + _mx + Cwidth / 2;\n circleData[offset + 1] = _mb * px + _md * py + _my + Cheight / 2;\n // Scale the diameter by the matrix's scale factor (length of the transformed x-axis)\n circleData[offset + 2] =\n (Density * diameter * Math.sqrt(_ma * _ma + _mb * _mb)) / 2;\n circleData[offset + 3] = alpha / 255;\n circleCount++;\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\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, projMatrix);\n gl.drawArrays(gl.POINTS, 0, circleCount);\n\n gl.bindVertexArray(null);\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 Mix.glMask._renderer._curShader = null;\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 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 { isReady, glDraw, circle, snapshotMatrix } 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();\n\nlet Mask = null;\nlet _strokeTransform = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n tx: 0,\n ty: 0,\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 * { type, min_max, curve } — old internal format, passed through unchanged\n */\nfunction normalizePressure(p) {\n if (!p || (typeof p === \"object\" && !Array.isArray(p))) return p;\n if (typeof p === \"function\")\n return { type: \"custom\", min_max: [0, 1], curve: p };\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 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 // 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 === \"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 params.tip = () => {\n Mask.image(\n T.tips.get(current.p.image.src),\n -current.p.weight / 2,\n -current.p.weight / 2,\n current.p.weight,\n current.p.weight,\n );\n };\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 transformPoint(transform, x, y) {\n return {\n x: transform.a * x + transform.c * y + transform.tx,\n y: transform.b * x + transform.d * y + transform.ty,\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\nfunction currentPointInUserSpace() {\n return transformPoint(\n _strokeTransform,\n _position.x - Cwidth / 2,\n _position.y - Cheight / 2,\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 {boolean} flow - Flag for vector-field following.\n * @param {Object|boolean} plot - Plot object or false.\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 Mask = Mix.glMask;\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 current.cp = pressure.type !== \"custom\" ? rr(3, 3.5) : rr(-0.2, 0.2);\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 if (isInsideClippingArea()) Mix.blend(State.stroke.color);\n if (Mix.isBrush === false) Mix.justChanged = true;\n Mix.isBrush = true;\n\n // Set additional state values\n current.alpha = calculateAlpha();\n markerTip();\n}\n\n/**\n * Restores drawing state after completing a stroke.\n */\nfunction restoreState() {\n glDraw();\n markerTip();\n}\n\n/**\n * Renders the brush tip based on current pressure and position.\n * @param {number} [customPressure=false] - Optional custom pressure.\n */\nfunction tip(customPressure = false) {\n if (!isInsideClippingArea()) return;\n let pressure = customPressure || calculatePressure();\n\n let 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\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 drawTip(pressure * lineNoise, current.alpha);\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 return current.p.pressure.type === \"custom\"\n ? map(\n current.p.pressure.curve(_position.plotted / _length) + current.cp,\n 0,\n 1,\n current.min,\n current.max,\n true,\n )\n : gauss();\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 * @returns {boolean} True if inside clipping area; false otherwise.\n */\nfunction isInsideClippingArea() {\n const point = currentPointInUserSpace();\n\n if (State.stroke.clipWindow) {\n const local = transformPoint(\n State.stroke.clipWindow.inverse,\n point.x,\n point.y,\n );\n const { bounds } = State.stroke.clipWindow;\n return (\n local.x >= bounds.minX &&\n local.x <= bounds.maxX &&\n local.y >= bounds.minY &&\n local.y <= bounds.maxY\n );\n }\n\n let o = Cwidth * 0.05;\n return (\n point.x >= -Cwidth / 2 - o &&\n point.x <= Cwidth / 2 + o &&\n point.y >= -Cheight / 2 - o &&\n point.y <= Cheight / 2 + o\n );\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\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,\n );\n}\n\n/**\n * Draws a custom or image-based brush tip.\n * @param {number} pressure - Current pressure.\n * @param {number} alpha - Alpha (opacity) for drawing.\n * @param {boolean} [vibrate=true] - Whether to apply vibration.\n */\nfunction drawTip(pressure, alpha, vibrate = true) {\n Mix.glMask.isDrawn = true;\n Mask.push();\n Mask.noStroke();\n let color = State.stroke.color;\n color.setAlpha(alpha);\n Mask.fill(State.stroke.color);\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 Mask.translate(_position.x + rx - Cwidth, _position.y + ry - Cheight);\n adjustSizeAndRotation(State.stroke.weight * pressure, alpha);\n current.p.tip(Mask);\n Mask.pop();\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 if (rr(0, current.p.grain * pressure) > 0.4) {\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 circle(\n _position.x + dx,\n _position.y + dy,\n pressure *\n pressure *\n current.p.weight *\n rr(0.85, 1.15) *\n State.stroke.weight,\n Math.max(0.9, pressure) * current.alpha * rr(0.75, 1.1),\n );\n }\n}\n\n/**\n * Adjusts the size and rotation of the brush tip before rendering.\n * @param {number} pressure - Pressure-based scaling factor.\n * @param {number} alpha - Opacity value.\n */\nfunction adjustSizeAndRotation(pressure, alpha) {\n Mask.scale(pressure);\n if (current.p.type === \"image\") {\n Mask.tint(255, 0, 0, alpha / 2);\n }\n let angle = 0;\n if (current.p.rotate === \"random\") angle = randInt(0, 360);\n else if (current.p.rotate === \"natural\") {\n angle =\n (_plot ? -_plot.angle(_position.plotted) : -_dir) + _position.angle();\n }\n Mask.rotate(angle);\n}\n\n/**\n * Draws the marker tip with a blend effect.\n */\nfunction markerTip() {\n if (isInsideClippingArea()) {\n let pressure = calculatePressure();\n let alpha = calculateAlpha(pressure);\n if (current.p.type === \"marker\") {\n for (let s = 1; s < 10; s++) {\n drawMarker((pressure * s) / 10, false, alpha * 5);\n }\n glDraw();\n } else if (current.p.type === \"custom\" || current.p.type === \"image\") {\n for (let s = 1; s < 5; s++) {\n drawTip((pressure * s) / 5, alpha, false);\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, vibration, definition, quality, 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];\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.12,\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 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 p5img = Renderer.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.src = src;\n }),\n ),\n );\n },\n};\n\n/**\n * Loads all registered image tips. Must be awaited before setup/draw.\n * @returns {Promise}\n *\n * @example\n * // In your sketch:\n * await brush.preload();\n */\nexport async function preload() {\n await T.load();\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// Module: Hatch\n// =============================================================================\n/**\n * The Hatch module contains functions and classes dedicated to applying\n * hatch patterns over shapes and polygons. It enables the simulation of\n * cross-hatching and shading effects by drawing parallel lines or strokes\n * across a geometry. The module supports adjustable spacing, angle, and\n * optional style parameters (such as randomness, continuity, and gradient),\n * giving an artistic representation similar to hand-drawn hatching techniques.\n *\n * The implementation allows for hatching to be applied either to a Polygon\n * directly or via a Plot, extending the drawing capabilities with layered,\n * stylized textures.\n */\n\nimport { State } from \"../core/color.js\";\nimport { toDegreesSigned, map, cos, sin, 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 and Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Global hatch state settings.\n */\nState.hatch = {\n isActive: false,\n dist: 5,\n angle: 45,\n options: {},\n hBrush: false,\n};\n\n/**\n * Returns a shallow copy of the current hatch state.\n * @returns {object} The current hatch state.\n */\nexport function HatchState() {\n return { ...State.hatch };\n}\n\n/**\n * Updates the global hatch state.\n * @param {object} state - The new hatch state.\n */\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Style Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Activates hatching for subsequent geometries.\n *\n * @param {number} dist - The distance between hatching lines.\n * @param {number} angle - The hatch angle, interpreted using the current p5 angle mode.\n * @param {object} options - Optional parameters to affect the hatching style:\n * - rand: Number value to introduce randomness.\n * - continuous: Boolean to connect adjacent lines.\n * - gradient: Number to gradually change spacing.\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 * Sets the hatch brush style for subsequent hatching.\n *\n * @param {string} brush - The brush name.\n * @param {string|Color} color - The brush color.\n * @param {number} weight - The brush weight (size).\n */\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\n/**\n * Disables hatching.\n */\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fill Manager Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a hatching pattern over the given polygon(s).\n *\n * @param {Polygon|Polygon[]} polygons - A polygon or an array of polygons.\n */\nexport function createHatch(polygons) {\n let dist = State.hatch.dist;\n let angle = ((State.hatch.angle % 180) + 180) % 180;\n let options = State.hatch.options;\n\n // Save current stroke state\n let save = BrushState();\n // If a hatch brush is set, override with those parameters.\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n\n // Compute overall bounding box for all polygons.\n if (!Array.isArray(polygons)) polygons = [polygons];\n const overallBB = computeOverallBoundingBox(polygons);\n\n // Build a bounding polygon based on the overall bounding box.\n let ventana = new Polygon([\n [overallBB.minX, overallBB.minY],\n [overallBB.maxX, overallBB.minY],\n [overallBB.maxX, overallBB.maxY],\n [overallBB.minX, overallBB.maxY],\n ]);\n\n // Determine starting y coordinate based on angle.\n let startY = angle <= 90 && angle >= 0 ? overallBB.minY : overallBB.maxY;\n let gradient = options.gradient\n ? map(options.gradient, 0, 1, 1, 1.1, true)\n : 1;\n let dots = [];\n let i = 0;\n let dist1 = dist;\n\n // Function to generate a line for index i.\n let linea = (i) => {\n return {\n point1: {\n x: overallBB.minX + dist1 * i * cos(-angle + 90),\n y: startY + dist1 * i * sin(-angle + 90),\n },\n point2: {\n x: overallBB.minX + dist1 * i * cos(-angle + 90) + cos(-angle),\n y: startY + dist1 * i * sin(-angle + 90) + sin(-angle),\n },\n };\n };\n\n // Generate lines and calculate intersections with polygons\n // Loop through the lines based on the distance and angle to calculate intersections with the polygons\n // The loop continues until a line does not intersect with the bounding window polygon\n // Each iteration accounts for the gradient effect by adjusting the distance between lines\n while (ventana.intersect(linea(i)).length > 0) {\n let tempArray = [];\n for (let p of polygons) {\n tempArray.push(p.intersect(linea(i)));\n }\n dots[i] = tempArray\n .flat()\n .sort((a, b) => (a.x === b.x ? a.y - b.y : a.x - b.x));\n dist1 *= gradient;\n i++;\n }\n\n // Filter out empty intersection sets.\n let gdots = dots.filter((dd) => typeof dd[0] !== \"undefined\");\n\n // Draw the hatching lines using the calculated intersections\n // If the 'rand' option is enabled, add randomness to the start and end points of the lines\n // If the 'continuous' option is set, connect the end of one line to the start of the next\n let r = options.rand || 0;\n for (let j = 0; j < gdots.length; j++) {\n let dd = gdots[j];\n let continuousLine = j > 0 && options.continuous;\n for (let i = 0; i < dd.length - 1; i += 2) {\n if (r !== 0) {\n dd[i].x += r * dist * rr(-1, 1);\n dd[i].y += r * dist * rr(-1, 1);\n dd[i + 1].x += r * dist * rr(-1, 1);\n dd[i + 1].y += r * dist * rr(-1, 1);\n }\n line(dd[i].x, dd[i].y, dd[i + 1].x, dd[i + 1].y);\n if (continuousLine) {\n line(gdots[j - 1][1].x, gdots[j - 1][1].y, dd[i].x, dd[i].y);\n }\n }\n }\n\n // Restore previous brush state.\n BrushSetState(save);\n}\n\n/**\n * Computes the bounding box for a single polygon.\n * @param {Polygon} polygon - The polygon to evaluate.\n * @returns {object} The bounding box as {minX, minY, maxX, maxY}.\n */\nfunction computeBoundingBoxForPolygon(polygon) {\n if (polygon._boundingBox) return polygon._boundingBox;\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n for (let i = 0; i < polygon.a.length; i++) {\n const [x, y] = polygon.a[i];\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n }\n polygon._boundingBox = { minX, minY, maxX, maxY };\n return polygon._boundingBox;\n}\n\n/**\n * Computes an overall bounding box for an array of polygons.\n * @param {Array} polygons - Array of Polygon objects.\n * @returns {object} The overall bounding box {minX, minY, maxX, maxY}.\n */\nfunction computeOverallBoundingBox(polygons) {\n let overall = {\n minX: Infinity,\n minY: Infinity,\n maxX: -Infinity,\n maxY: -Infinity,\n };\n for (let poly of polygons) {\n const bb = computeBoundingBoxForPolygon(poly);\n overall.minX = Math.min(overall.minX, bb.minX);\n overall.minY = Math.min(overall.minY, bb.minY);\n overall.maxX = Math.max(overall.maxX, bb.maxX);\n overall.maxY = Math.max(overall.maxY, bb.maxY);\n }\n return overall;\n}\n\n// ---------------------------------------------------------------------------\n// Extend Polygon and Plot Prototypes\n// ---------------------------------------------------------------------------\n\n/**\n * Adds a hatch effect to the polygon.\n *\n * If a distance is provided, activates hatching with the given parameters.\n * Then, if hatch is active, applies the hatching pattern.\n *\n * @param {number} [_dist] - The distance between hatch lines.\n * @param {number} _angle - The hatch angle, interpreted using the current p5 angle mode.\n * @param {object} _options - Optional hatch options.\n */\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (state.isActive) {\n createHatch(this);\n }\n HatchSetState(state);\n};\n\n/**\n * Applies hatching to a plot.\n *\n * If hatching is active, generates a polygon from the plot and applies hatch.\n *\n * @param {number} x - The x-coordinate to draw at.\n * @param {number} y - The y-coordinate to draw at.\n * @param {number} scale - Scaling factor.\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 \"./color.js\";\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 Mix.ctx.beginPath();\n vertices.forEach((v, i) => {\n if (i === 0) Mix.ctx.moveTo(v.x, v.y);\n else Mix.ctx.lineTo(v.x, v.y);\n });\n Mix.ctx.closePath();\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 radius = d / 2;\n Mix.ctx.moveTo(x + radius, y);\n Mix.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 { Renderer, Mix, State, Cwidth, Cheight, Density } from \"../core/color.js\";\nimport { drawPolygon, circle } from \"../core/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 = 1024;\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 < 8) {\n // Simple average for small polygons\n return pts\n .reduce((c, p) => ({ x: c.x + p.x, y: c.y + p.y }), { x: 0, y: 0 })\n .map((v) => v / 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\n // Map vertices\n const fluid = ~~(v.length * 0.25 * weightedRand({ 1: 5, 2: 10, 3: 60 }));\n const strength = State.fill.bleed_strength;\n\n // Create bleed modifiers\n const modifiers = v.map(\n (_, i) => (i > fluid ? 1 : 0.3) * rr(0.85, 1.2) * strength,\n );\n\n // Randomize starting point\n const shift = randInt(0, v.length);\n const shifted = [...v.slice(shift), ...v.slice(0, shift)];\n\n // Calculate center and create FillPolygon\n const center = _center(shifted);\n 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 // Clone and splice\n const v = [...this.v],\n m = [...this.m],\n dir = [...this.dir];\n v.splice(s, n);\n m.splice(s, n);\n dir.splice(s, 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\n // Build sorted random indices\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 = [], sm = [], 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\n // Ray-cast: count intersections from p to far right\n let crossings = 0;\n for (const [a, b] of sides) {\n const ay = a.y, 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 outside (even crossings), pull toward center\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\n sv.push(p);\n sm.push(this.m[j]);\n sd.push(!this.dir[j]); // flip direction → grow inward\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 // Get trimmed vertices\n const { v: tr_v, m: tr_m, dir: tr_dir } = this.trim(f);\n const len = tr_v.length;\n \n // Pre-allocate output arrays\n const outLen = len * 2;\n const newVerts = new Array(outLen);\n const newMods = new Array(outLen);\n const newDirs = new Array(outLen);\n \n // Determine bleed direction\n const bleedDirDeg = State.fill.direction === \"out\" ? -90 : 90;\n \n // Ensure gaussian pool is filled\n if (_gaussians[0].length === 0) _fillGaussianPools();\n const gPool = _gaussians[0], gPoolLen = gPool.length;\n const g2Pool = _gaussians[1], g2PoolLen = g2Pool.length;\n \n let idx = 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 // Inline rotate: rotDeg = ±bleedDirDeg + small jitter\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 // Outward distance: inline rArray + rr\n const d = gPool[~~(rr(0, 1) * gPoolLen)] * rr(0.65, 1.35) * mod;\n \n // First vertex: original\n newVerts[idx] = cv;\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n \n // Second vertex: midpoint + outward push\n newVerts[idx] = {\n x: cv.x + sideX * 0.5 + dirX * d,\n y: cv.y + sideY * 0.5 + dirY * d,\n };\n newMods[idx] = mi + g2Pool[~~(rr(0, 1) * g2PoolLen)];\n newDirs[idx] = di;\n idx++;\n }\n \n // Cap vertex count to prevent exponential blowup.\n let fv = newVerts, fm = newMods, fd = newDirs;\n let growe = GROW_MAX_VERTS / (State.fill.texture_strength);\n if (growe && idx > growe) {\n const step = Math.ceil(idx / growe);\n fv = []; fm = []; fd = [];\n for (let j = 0; j < idx; j += step) {\n fv.push(newVerts[j]);\n fm.push(newMods[j]);\n fd.push(newDirs[j]);\n }\n } else {\n // Trim pre-allocated arrays to actual size\n fv.length = idx;\n fm.length = idx;\n fd.length = idx;\n }\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 // Precalculate stuff\n const numLayers = 20;\n const texture = tex * 3;\n const int = 2 * intensity * (1 + tex / 2);\n\n // Perform initial setup only once\n Mix.blend(color);\n Mix.justChanged = true;\n Mix.isBrush = false;\n\n Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * Matrix.a(), Density * Matrix.b(),\n Density * Matrix.c(), 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\n // Create initial polygon\n let pol = this.grow();\n // Create sparse inner polygon from original (pre-grow) vertices\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 // Grow polygon every 4 layers\n if (i % 4 === 0) pol = pol.grow();\n\n // Create variant polygons\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 // Draw layers\n for (const p of pols) p.grow(999).grow(997).layer(i, size, int, color);\n sparse.grow(999).flipDirs().grow(997).layer(i, size, int * 1.5 * texture, color);\n if (i % 2 === 0)\n pol\n .grow(darker)\n .grow(999)\n .layer(i, size, int * 2, color);\n\n // Apply texture and blend periodically\n if (i % 5 === 0 || i === numLayers - 1) {\n if (texture !== 0) pol.erase(texture * 3, intensity);\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 Mix.ctx.fillStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${int}%)`;\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 // Optimize by pre-calculating values\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.4 - State.fill.bleed_strength);\n const minSizeFactor = 0.05 * minSize;\n const maxSizeFactor = 0.4 * minSize;\n const { x: midX, y: midY } = this.midP;\n\n // Set up erase mode\n Mix.ctx.globalCompositeOperation = \"destination-out\";\n\n // Calculate transparency\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 // Draw erase circles\n for (let i = 0; i < numCircles; i++) {\n const x = midX + gaussian(0, halfSizeX);\n const y = midY + gaussian(0, halfSizeY);\n const size = rr(minSizeFactor, maxSizeFactor);\n\n Mix.ctx.beginPath();\n circle(x, y, size);\n if (i % 5 !== 0) Mix.ctx.fill();\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 map(State.fill.bleed_strength, 0, 0.6, 0.3, 0.45, 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 * @version 2.0.0-alpha\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.bleed(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-2024 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 { Mix } 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.postsetup = () => Mix.blend(false, true);\n lifecycles.postdraw = () => Mix.blend(false, true);\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","isFramebufferTarget","target","begin","end","renderer","_pInst","getSketchRenderer","_isInstanced","window","self","p5","instance","removeTargetBuffer","buffer","remove","getActiveFramebuffer","_renderer","activeFramebuffer","load","width","height","Error","resolveTarget","webglVersion","_isReady","loaded","Mix","isCanvasReady","State","inst","isMixReady","isBlending","cachedColor","Object","captureBlendSource","framebuffer","blendSourceFramebuffer","pixelDensity","createFramebuffer","density","antialias","depth","stencil","source","draw","clear","push","imageMode","CENTER","image","pop","graphicsFactory","createGraphics","p2dMode","P2D","webglMode","WEBGL","mask","glMask","this","ctx","drawingContext","shaderProgram","createShader","angleMode","DEGREES","lineWidth","uModelMatrix","blend","_color","_isLast","isBrush","no_mask","_array","justChanged","applyShader","shader","gl","targetIsFramebuffer","hadDepthTest","getParameter","DEPTH_TEST","disable","translate","setUniform","fill","noStroke","rect","resetShader","enable","isDrawn","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","c","s0","s1","s2","copy","f","rng","_seedCallbacks","_onSeed","cb","noise","rr","e","rArray","array","randInt","gaussian","mean","stdev","u","log","cos","weightedRand","weights","totalWeight","entries","key","cumulative","rnd","isNaN","parseInt","value","a","b","d","withinBounds","constrain","low","high","max","min","nAngle","angle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","NaN","sLookup","idx","sin","toDegrees","rad","isRad","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","mat4","isLoaded","isFieldReady","resolution","left_x","top_y","num_columns","round","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","ceil","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","projMatrix","vao","buf","program","loadedWidth","loadedHeight","Attr","Frag","_ma","_mb","_mc","_md","_mx","_my","circleData","INITIAL_CAPACITY","circleCount","bufferCapacity","gpuBufferSize","diameter","alpha","newData","px","py","glDraw","color","useProgram","BLEND","blendFunc","ONE_MINUS_DST_ALPHA","ONE","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","uniform4f","u_color","uniformMatrix4fv","u_matrix","drawArrays","POINTS","_curShader","weight","clipWindow","opacity","_position","Mask","_strokeTransform","tx","ty","BrushState","BrushSetState","state","add","params","includes","undefined","vibration","scatter","definition","sharpness","quality","grain","isArray","min_max","curve","m","range","ns","nm","ne","normalizePressure","src","T","tip","tips","param","colors","buffers","box","scaleBrushes","values","spacing","pick","brushName","g","arguments","strokeWeight","snapshotTransform","transformPoint","transform","normalizeRegion","region","minX","minY","maxX","maxY","clip","inverse","det","invertTransform","bounds","noClip","initializeDrawingState","plot","gaussians","angleScale","isPlot","cp","noiseoffset","dirRad","nextGl","needsContextRefresh","createProgram","VERTEX_SHADER","FRAGMENT_SHADER","shaderSource","compileShader","attachShader","linkProgram","forEach","getAttribLocation","getUniformLocation","createVertexArray","createBuffer","enableVertexAttribArray","a_position","vertexAttribPointer","FLOAT","a_radius","a_alpha","isReady","isInsideClippingArea","calculateAlpha","markerTip","saveState","stepSize","totalSteps","customPressure","calculatePressure","lineNoise","sw","iterations","rX","yRandomFactor","sqrtPart","drawSpray","drawMarker","drawTip","perp","along","drawDefault","simPressure","peakPos","halfWidth","pow","gauss","point","local","o","vibrate","rx","ry","setAlpha","tint","adjustSizeAndRotation","flowLine","_vals","_standard_brushes","obj","prototype","_brush","_weight","imageToWhite","loadPixels","average","pixels","updatePixels","filter","k","Promise","all","resolve","reject","nativeImg","Image","onload","p5img","createImage","naturalWidth","naturalHeight","drawImage","onerror","HatchState","rand","continuous","gradient","hatchStyle","brush","hBrush","noHatch","createHatch","polygons","save","overallBB","overall","Infinity","poly","bb","computeBoundingBoxForPolygon","computeOverallBoundingBox","ventana","dots","dist1","linea","tempArray","flat","sort","gdots","dd","continuousLine","_boundingBox","_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","splice","ratio","L","keep","indices","sv","sm","sd","crossings","ay","by","flipDirs","grow","tr_v","tr_m","tr_dir","outLen","newVerts","newMods","newDirs","bleedDirDeg","gPool","gPoolLen","g2Pool","g2PoolLen","mod","cv","nv","mi","di","rotDeg","sideX","sideY","dirX","dirY","fv","fm","fd","growe","intensity","tex","texture","int","setTransform","strokeStyle","_getRed","_getGreen","_getBlue","lineCap","size","darker","sparse","pols","layer","numLayers","erase","restore","fillStyle","beginPath","lineTo","closePath","numCircles","halfSizeX","halfSizeY","minSize","minSizeFactor","maxSizeFactor","midX","midY","globalCompositeOperation","_opacity","_bleed","fluid","strength","modifiers","_","shift","shifted","slice","pts","area","cross","_center","createFill","FillSetState","_stateStack","registerAddon","_p5","lifecycles","postsetup","postdraw","_push","_pop","_randomSeed","randomSeed","_noiseSeed","noiseSeed","call","saved","brushPop","callback","brushS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rqB,GACxBoqB,EAAYI,KAAKpuB,KAAM4D,GZpHP,CAACA,IACnB4C,EAAMzB,EAAUnB,GAChB,IAAK,MAAM2qB,KAAY9nB,EACrB8nB,KYkHAC,CAAU5qB,EACZ,EAEA8M,EAAGyd,UAAY,SAAUvqB,GACvBsqB,EAAWE,KAAKpuB,KAAM4D,GZvGD,CAACA,IACxBgD,EAAQlE,EAAcqC,EAAUnB,KYuG9B6qB,CAAe7qB,EACjB,CACF","x_google_ignoreList":[1,2]}
\ No newline at end of file
diff --git a/dist/p5.brush.js b/dist/p5.brush.js
index 0b8424f..c83bd38 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,i,n,o;const s=(t=!1)=>{if(n=l&&!t?i:t||window.self.p5.instance,"webgl2"!==n.webglVersion)throw new Error("p5.brush requires a WEBGL canvas");e=n.width,r=n.height,a=!0,n.loaded&&f.load()};let a=!1,l=!1;const c=()=>{a||s()},h={},u=()=>{n.loaded||(c(),f.load())},f={isBlending:!1,isBlendingGL:!1,isWaterColor:!1,cachedColor:new Object,cachedColorGL:new Object,masks:[],load(){n.loaded||(n.mask=n.createGraphics(e,r,n.P2D),n.glMask=n.createGraphics(e,r,n.WEBGL),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.;gl_Position=vec4(p=v.xy,0,1);}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nuniform bool u_isBrush;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 uv1=vec2(uv.x,1.0-uv.y);vec4 source=texture(u_source,uv1);vec4 maskColor=texture(u_mask,uv1);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 sampleUV=uv1+vec2(float(i),float(j))*texelSize;float neighborAlpha=texture(u_mask,sampleUV).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.0);}"),o=n.pixelDensity(),this.mask=n.mask,this.mask.pixelDensity(o),this.mask.clear(),this.mask.angleMode(n.DEGREES),this.ctx=this.mask.drawingContext,this.glMask=n.glMask,this.glMask.pixelDensity(o),this.glMask.clear(),this.glMask.angleMode(this.glMask.DEGREES),this.glMask.drawingContext.lineWidth=0,this.glMask._renderer.uModelMatrix=n._renderer.uModelMatrix)},blend(t=!1,e=!1){u();const r=this.isBrush?this.glMask:this.mask,i=this.isBrush?this.mask:this.glMask;!this.isBlending&&t&&(this.isBlending=!0,this.cachedColor=t._array,this.glMask.clear()),(e||this.cachedColor[0]!==t._array[0]||this.cachedColor[1]!==t._array[1]||this.cachedColor[2]!==t._array[2]||this.cachedColor[3]!==t._array[3])&&(this.justChanged&&(this.applyShader(i),this.justChanged=!1),this.isBlending&&this.applyShader(r),this.cachedColor=t._array,e&&(this.isBlending=!1))},applyShader(t){let i=n.shaderProgram;const o=n.drawingContext,s=o.getParameter(o.DEPTH_TEST);o.disable(o.DEPTH_TEST),n.push(),n.translate(0,0),n.shader(i),i.setUniform("u_source",n._renderer),i.setUniform("u_isBrush",this.isBrush),i.setUniform("u_mask",t),i.setUniform("u_color",this.cachedColor),n.fill(0,0,0,0),n.noStroke(),n.rect(-e/2,-r/2,e,r),n.pop(),n.resetShader(),s&&o.enable(o.DEPTH_TEST),t.clear(),t.isDrawn=!1}},g=Math.sqrt(3),d=.5*(g-1),m=(3-g)/6,p=t=>0|Math.floor(t),x=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 i=r+~~(t()*(256-r)),n=e[r];e[r]=e[i],e[i]=n}for(let t=256;t<512;t++)e[t]=e[t-256];return e}(t),r=new Float64Array(e).map(t=>x[t%12*2]),i=new Float64Array(e).map(t=>x[t%12*2+1]);return function(t,n){let o=0,s=0,a=0;const l=(t+n)*d,c=p(t+l),h=p(n+l),u=(c+h)*m,f=t-(c-u),g=n-(h-u);let x,y;f>g?(x=1,y=0):(x=0,y=1);const v=f-x+m,_=g-y+m,b=f-1+2*m,w=g-1+2*m,R=255&c,S=255&h;let E=.5-f*f-g*g;if(E>=0){const t=R+e[S];E*=E,o=E*E*(r[t]*f+i[t]*g)}let A=.5-v*v-_*_;if(A>=0){const t=R+x+e[S+y];A*=A,s=A*A*(r[t]*v+i[t]*_)}let P=.5-b*b-w*w;if(P>=0){const t=R+1+e[S+1];P*=P,a=P*P*(r[t]*b+i[t]*w)}return 70*(o+s+a)}}function v(t,e){let r=new _(t),i=()=>r.next();return i.double=()=>i()+11102230246251565e-32*(2097152*i()|0),i.int32=()=>4294967296*r.next()|0,i.quick=i,i}class _{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 i=.02519603282416938*e;e=i>>>0,i-=e,i*=e,e=i>>>0,i-=e,e+=4294967296*i}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:i}=this,n=2091639*e+2.3283064365386963e-10*t;return this.s0=r,this.s1=i,this.s2=n-(this.c=0|n)}copy(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}}let b=v(Math.random()),w=y(v(Math.random()));const R=(t=0,e=1)=>t+b()*(e-t),S=t=>t[~~(b()*t.length)],E=(t,e)=>~~R(t,e),A=(t=0,e=1)=>{const r=1-b(),i=b();return Math.sqrt(-2*Math.log(r))*z(360*i)*e+t},P=t=>{let e=0;const r=[];for(const i in t)e+=t[i],r.push({key:i,cumulative:e});const i=b()*e;for(const{key:t,cumulative:e}of r)if(i<e)return isNaN(t)?t:parseInt(t)},M=(t,e,r,i,n,o=!1)=>{let s=i+(t-e)/(r-e)*(n-i);return o?i<n?k(s,i,n):k(s,n,i):s},k=(t,e,r)=>Math.max(Math.min(t,r),e),L=t=>(t%=360)<0?t+360:t,C=1440,I=2*Math.PI/C,T=new Float32Array(C).fill(NaN),N=new Float32Array(C).fill(NaN),z=t=>{const e=~~(4*L(t));let r=T[e];return isNaN(r)&&(r=Math.cos(e*I),T[e]=r),r},O=t=>{const e=~~(4*L(t));let r=N[e];return isNaN(r)&&(r=Math.sin(e*I),N[e]=r),r},B=(t,e=!1)=>{if(n.angleMode()===n.RADIANS||e){let e=180*t/Math.PI%360;return e<0?e+360:e}return t},D=(t,e,r,i,n)=>{let o=z(n),s=O(n);return{x:o*(r-t)+s*(i-e)+t,y:o*(i-e)-s*(r-t)+e}},Y=(t,e,r,i)=>Math.hypot(r-t,i-e),F=(t,e,r,i)=>B(Math.atan2(-(i-e),r-t),!0),X=(t,e,r,i,n=!1)=>{let o=t.x,s=t.y,a=e.x,l=e.y,c=r.x,h=r.y,u=i.x,f=i.y;if(o===a&&s===l||c===u&&h===f)return!1;let g=a-o,d=l-s,m=u-c,p=f-h,x=p*g-m*d;if(0===x)return!1;let y=(m*(s-h)-p*(o-c))/x,v=(g*(s-h)-d*(o-c))/x;return!(!n&&(v<0||v>1))&&{x:o+y*g,y:s+y*d}},G=()=>n._renderer.uModelMatrix.mat4[12],W=()=>n._renderer.uModelMatrix.mat4[13],$=()=>n._renderer.uModelMatrix.mat4[0],H=()=>n._renderer.uModelMatrix.mat4[1],j=()=>n._renderer.uModelMatrix.mat4[4],U=()=>n._renderer.uModelMatrix.mat4[5];let Z=!1;function V(){Z||(u(),q=.01*e,J=-.5*e,Q=-.5*r,tt=Math.round(2*e/q),et=Math.round(2*r/q),ct("hand",(t,e)=>{const r=R(.2,.8),i=E(5,10);return ht(e,(e,n)=>.5*i*O(r*n*e+E(15,25))*.2*z(t)+w(e,n)*i*.7)}),ct("curved",(t,e)=>{let r=E(-10,10);return E(0,100)%2==0&&(r*=-1),ht(e,(e,i)=>3*M(w(.02*e+.03*t,.02*i+.03*t),0,1,-r,r))}),ct("zigzag",(t,e)=>{let r=E(-30,-15)+Math.abs(44*O(t));E(0,100)%2==0&&(r*=-1);let i=r,n=0;for(let t=0;t<tt;t++){for(let r=0;r<et;r++)e[t][r]=n,n+=i,i*=-1;n+=i,i*=-1}return e}),ct("waves",(t,e)=>{const r=E(10,15)+5*O(t),i=E(3,6)+3*z(t),n=E(20,35);return ht(e,(t,e)=>O(r*t)*n*z(e*i)+E(-3,3))}),ct("seabed",(t,e)=>{const r=R(.4,.8),i=E(18,26);return ht(e,(e,n)=>1.1*i*O(r*n*e+E(15,20))*z(t))}),ct("spiral",(t,e)=>{const r=E(5,10),i=2*E(0,2)-1,n=E(65,80),o=Array.from({length:r},()=>({x:R(.1,.9)*tt,y:R(.1,.9)*et}));return ht(e,(t,e)=>{let r=0,s=0;for(const a of o){const o=t-a.x,l=e-a.y,c=1/(o*o+l*l+1),h=Math.atan2(l,o)*(180/Math.PI),u=i*(h+n)*Math.PI/180;r+=c*Math.cos(u),s+=c*Math.sin(u)}return Math.atan2(s,r)*(180/Math.PI)})}),ct("columns",(t,e)=>{const r=E(3,8),i=E(25,45);return ht(e,(t,e)=>O(t*r)*i)}),Z=!0)}class K{constructor(t,e){V(),this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=K.getColIndex(t),this.rowIdx=K.getRowIndex(e)}reset(){this.plotted=0}isIn(){return h.field.isActive?K.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const t=e,i=r,n=this.x+G(),o=this.y+W();return n>=-.3*t&&n<=1.3*t&&o>=-.3*i&&o<=1.3*i}angle(){return this.isIn()&&h.field.isActive?st.get(h.field.current).field[this.colIdx][this.rowIdx]*h.field.wiggle:0}moveTo(t,e,r=1){this.movePos(t,e,r)}plotTo(t,e,r,i=1){this.movePos(t,e,r,i)}movePos(t,e,r,i=!1){const n=i||1;if(this.isIn())for(let o=0;o<e/r;o++){const e=this.angle()-(i?t.angle(this.plotted):t);this.update(this.x+r*z(e),this.y+r*O(e)),this.plotted+=r/n}else this.plotted+=r/n}static getRowIndex(t,e=1){const r=t+W()-Q;return Math.round(r/q/e)}static getColIndex(t,e=1){const r=t+G()-J;return Math.round(r/q/e)}static isIn(t,e){return t>=0&&e>=0&&t<tt&&e<et}}h.field={isActive:!1,current:null,wiggle:1};let q,J,Q,tt,et,rt,it,nt,ot,st=new Map;function at(){return new Array(tt).fill(null).map(()=>new Float32Array(et))}function lt(t){if(h.field.wiggle||(h.field.wiggle=1),V(),!st.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(st.keys()).join(", ")}.`);h.field.isActive=!0,h.field.current=t;const e=st.get(t);e.field||(e.field=e.gen(0,at()))}function ct(t,e){st.set(t,{gen:e,field:null})}function ht(t,e){for(let r=0;r<tt;r++)for(let i=0;i<et;i++)t[r][i]=e(r,i);return t}class ut{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,i]of this.sides){const n=X(t.point1,t.point2,e,i);n&&r.push(n)}return this._intersectionCache[e]=r,r}show(){h.stroke&&this.draw(),h.hatch&&this.hatch(),h.fill&&this.fill()}}class ft{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,i=!1){this.angles.length>0&&this.angles.pop(),t=i?(t%360+360)%360:B(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:B(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=B(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],i=t[this.index+1]??r;return Math.abs(i-r)>180&&(i>r?i=-(360-i):r=-(360-r)),M(e-this.suma,0,this.segments[this.index],r,i,!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,i,n=1,o){V();const s=.5,a=[],l=Math.round(this.length/s),c=new K(t+e/2,i+r/2);let h=0,u=0;for(let t=0;t<l;t++){c.plotTo(this,s,s);const t=this.calcIndex(c.plotted);h+=s,(h>=Math.max(this.segments[t]*o*R(.7,1.3),10)||t>=u)&&c.x&&(a.push([c.x-e/2,c.y-r/2]),h=0,t>=u&&u++)}return new ut(a)}show(t,e,r=1){h.stroke&&this.draw(t,e,r),h.hatch&&this.hatch(t,e,r),h.fill&&this.fill(t,e,r)}}class gt{constructor(){this.isClosed=!1,this.curvature=it,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){xt(this.vert,this.curvature,this.isClosed).show()}}function dt(t=0){it=k(t,0,1),rt=new gt}function mt(t,e,r=1){if(!rt)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");rt.vertex(t,e,r)}function pt(t=!1){if(!rt)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(rt.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(rt.vertex(...rt.vert[0]),rt.isClosed=!0),rt.show(),rt=!1}function xt(t,e=.5,r=!1){const i=new ft(0===e?"segments":"curve"),n=2*Math.PI;if(r&&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 h=t[c],u=t[c+1],f=t[c+2],g=Y(h[0],h[1],u[0],u[1]),d=Y(u[0],u[1],f[0],f[1]),m=F(h[0],h[1],u[0],u[1]),p=F(u[0],u[1],f[0],f[1]),x=e*Math.min(g,d,.5*Math.min(g,d)),y=Math.max(g,d),v=g-x,_=d-x;if(Math.floor(m)===Math.floor(p)){const e=r&&0===c?0:g-l,n=r?0===c?0:d-a:d;i.addSegment(m,e,h[2],!0),c===t.length-3&&i.addSegment(p,n,u[2],!0),l=0,0===c&&(o=g,a=x,s=t[1],l=0)}else{const e={x:u[0]-x*z(-m),y:u[1]-x*O(-m)},f={x:e.x+y*z(90-m),y:e.y+y*O(90-m)},g={x:u[0]+x*z(-p),y:u[1]+x*O(-p)},d={x:g.x+y*z(90-p),y:g.y+y*O(90-p)},b=X(e,f,g,d,!0),w=Y(e.x,e.y,b.x,b.y),R=Y(e.x,e.y,g.x,g.y)/2,S=n*w*(2*Math.asin(R/w)*(180/Math.PI))/360,E=r&&0===c?0:v-l,A=c===t.length-3?r?o-x:_:0;i.addSegment(m,E,h[2],!0),i.addSegment(m,isNaN(S)?0:S,h[2],!0),i.addSegment(p,A,u[2],!0),l=x,0===c&&(o=v,a=x,s=[e.x,e.y])}c===t.length-3&&i.endPlot(p,u[2],!0)}else if(0===e){const e=t[c],r=t[c+1],n=Y(e[0],e[1],r[0],r[1]),o=F(e[0],e[1],r[0],r[1]);i.addSegment(o,n,r[2],!0),c===t.length-2&&i.endPlot(o,1,!0)}i.origin=r&&0!==e?s:t[0]}return i}let yt,vt,_t,bt,wt,Rt=!1;const St={},Et={};let At=1,Pt=0,Mt=0,kt=1,Lt=0,Ct=0,It=new Float32Array(8192),Tt=0,Nt=2048,zt=32768;function Ot(t,i,n,s){if(Tt>=Nt){Nt*=2;const t=new Float32Array(4*Nt);t.set(It),It=t}const a=t-e/2,l=i-r/2,c=4*Tt;It[c]=At*a+Mt*l+Lt+e/2,It[c+1]=Pt*a+kt*l+Ct+r/2,It[c+2]=o*n*Math.sqrt(At*At+Pt*Pt)/2,It[c+3]=s/255,Tt++}function Bt(){if(0===Tt)return;f.glMask.isDrawn=!0;const t=h.stroke.color._array;yt.useProgram(wt),yt.enable(yt.BLEND),yt.blendFunc(yt.ONE_MINUS_DST_ALPHA,yt.ONE),yt.bindVertexArray(_t),yt.bindBuffer(yt.ARRAY_BUFFER,bt);const e=16*Tt,r=It.subarray(0,4*Tt);e>zt?(yt.bufferData(yt.ARRAY_BUFFER,It,yt.DYNAMIC_DRAW),zt=It.byteLength):yt.bufferSubData(yt.ARRAY_BUFFER,0,r),yt.uniform4f(Et.u_color,...t),yt.uniformMatrix4fv(Et.u_matrix,!1,vt),yt.drawArrays(yt.POINTS,0,Tt),yt.bindVertexArray(null),Tt=0,f.glMask._renderer._curShader=null}h.stroke={color:null,weight:1,clipWindow:null,type:"HB",isActive:!1,opacity:1};let Dt,Yt,Ft,Xt,Gt=new Map,Wt=null;function $t(){return{...h.stroke}}function Ht(t){h.stroke={...t}}function jt(t,e){if(e.type=["marker","custom","image","spray"].includes(e.type)?e.type:"default",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||"object"==typeof t&&!Array.isArray(t))return t;if("function"==typeof t)return{type:"custom",min_max:[0,1],curve:t};if(Array.isArray(t)){const[e,r,i]=2===t.length?[t[0],(t[0]+t[1])/2,t[1]]:t,n=Math.min(e,r,i),o=Math.max(e,r,i),s=o-n||1,[a,l,c]=[(e-n)/s,(r-n)/s,(i-n)/s];return{type:"custom",min_max:[n,o],curve:t=>t<.5?a+(l-a)*t*2:l+(c-l)*(t-.5)*2}}}(e.pressure),"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 fe.add(e.image.src),e.tip=()=>{Wt.image(fe.tips.get(qt.p.image.src),-qt.p.weight/2,-qt.p.weight/2,qt.p.weight,qt.p.weight)},Gt.set(t,{param:e,colors:[],buffers:[]}),fe.load()}Gt.set(t,{param:e,colors:[],buffers:[]})}function Ut(t){if(!Gt.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...Gt.keys()].join(", ")}.`);h.stroke.type=t}function Zt(t,e,r){c(),h.stroke.color=n.color(...arguments),h.stroke.isActive=!0}function Vt(t){h.stroke.weight=t}function Kt(t,e,r=1){Ut(t),Zt(e),Vt(r)}const qt={};function Jt(t,i,n,o=!1){At=$(),Pt=H(),Mt=j(),kt=U(),Lt=G(),Ct=W(),Dt=new K(t+e/2,i+r/2),Yt=n,Ft=o,Ft&&Ft.calcIndex(0)}const Qt=[];function te(t,i){i||(Xt=t),function(){qt.seed=999999*R();const{param:t}=Gt.get(h.stroke.type)??{};if(!t)return;qt.p=t,Wt=f.glMask;const{pressure:i}=t;if(qt.a="custom"!==i.type?R(-1,1):0,qt.b="custom"!==i.type?R(1,1.5):0,qt.cp="custom"!==i.type?R(3,3.5):R(-.2,.2),[qt.min,qt.max]=i.min_max,qt.noiseoffset=.03,!Ft){const t=Xt*Math.PI/180;qt.cos=Math.cos(t),qt.sin=Math.sin(t)}(function(){if(!Rt){u(),yt=f.glMask.drawingContext,vt=new Float32Array([2/e,0,0,0,0,-2/r,0,0,0,0,1,0,-1,1,0,1]),wt=(t=>{const e=t.createProgram();for(let[r,i]of[[t.VERTEX_SHADER,"#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;}"],[t.FRAGMENT_SHADER,"#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);}"]]){const n=t.createShader(r);t.shaderSource(n,i),t.compileShader(n),t.attachShader(e,n)}return t.linkProgram(e),e})(yt),yt.useProgram(wt),yt.enable(yt.BLEND),yt.blendFunc(yt.ONE_MINUS_DST_ALPHA,yt.ONE),["a_position","a_radius","a_alpha"].forEach(t=>St[t]=yt.getAttribLocation(wt,t)),["u_matrix","u_color"].forEach(t=>Et[t]=yt.getUniformLocation(wt,t)),_t=yt.createVertexArray(),yt.bindVertexArray(_t),bt=yt.createBuffer(),yt.bindBuffer(yt.ARRAY_BUFFER,bt),yt.bufferData(yt.ARRAY_BUFFER,It.byteLength,yt.DYNAMIC_DRAW);const t=16;yt.enableVertexAttribArray(St.a_position),yt.vertexAttribPointer(St.a_position,2,yt.FLOAT,!1,t,0),yt.enableVertexAttribArray(St.a_radius),yt.vertexAttribPointer(St.a_radius,1,yt.FLOAT,!1,t,8),yt.enableVertexAttribArray(St.a_alpha),yt.vertexAttribPointer(St.a_alpha,1,yt.FLOAT,!1,t,12),yt.bindVertexArray(null),Rt=!0}})(),oe()&&f.blend(h.stroke.color),!1===f.isBrush&&(f.justChanged=!0),f.isBrush=!0,qt.alpha=ne(),le()}();const n=function(){const{param:t}=Gt.get(h.stroke.type)??{};return t?t.spacing:1}(),o=Math.round(Yt*(i?t:1)/n);for(let e=0;e<o;e++)Qt.length<2*o&&Qt.push(A()),ee(),i?Dt.plotTo(Ft,n,n,t,e<10):Dt.moveTo(t,n,n);Bt(),le()}function ee(t=!1){if(!oe())return;let e=t||re(),r=M(w(qt.seed+.002*Dt.plotted,0),0,1,1-qt.noiseoffset,1+qt.noiseoffset);switch(qt.p.type){case"spray":!function(t){const e=h.stroke.weight*qt.p.scatter*t+h.stroke.weight*S(Qt)*qt.p.scatter/3,r=qt.p.weight*R(.9,1.1),i=Math.ceil(qt.p.grain/t);for(let t=0;t<i;t++){const t=R(.9,1.1),i=t*e*R(-1,1),n=R(-1,1),o=Math.sqrt((t*e)**2-i**2);Ot(Dt.x+i,Dt.y+n*o,r,qt.alpha)}}(e*r);break;case"marker":se(e*r);break;case"custom":case"image":ae(e*r,qt.alpha);break;default:!function(t,e=1){const r=(e=M(e,0,1,.9,1.05))*h.stroke.weight*qt.p.scatter*(qt.p.sharpness+(1-qt.p.sharpness)*S(Qt)/t);if(R(0,qt.p.grain*t)>.4){let e,i;if(Ft)e=.7*r*R(-1,1),i=r*R(-1,1);else{const t=r*R(-1,1),n=.3*r*R(-1,1);e=t*-qt.sin+n*qt.cos,i=t*qt.cos+n*qt.sin}Ot(Dt.x+e,Dt.y+i,t*t*qt.p.weight*R(.85,1.15)*h.stroke.weight,Math.max(.9,t)*qt.alpha*R(.75,1.1))}}(e*r)}}function re(){return Ft?ie()*Ft.pressure(Dt.plotted):ie()}function ie(){return"custom"===qt.p.pressure.type?M(qt.p.pressure.curve(Dt.plotted/Yt)+qt.cp,0,1,qt.min,qt.max,!0):function(t=.5+qt.p.pressure.curve[0]*qt.a,e=1-qt.p.pressure.curve[1]*qt.b,r=qt.cp,i=qt.min,n=qt.max){const o=t*Yt,s=(Dt.plotted<o?1.2*e:.8*e)*(Yt/2);return M(1/(1+Math.pow(Math.abs((Dt.plotted-o)/s),2*r)),0,1,i,n)}()}function ne(){return["default","spray"].includes(qt.p.type)?qt.p.opacity:qt.p.opacity/Math.min(h.stroke.weight,1.3)}function oe(){if(h.stroke.clipWindow)return Dt.x>=h.stroke.clipWindow[0]&&Dt.x<=h.stroke.clipWindow[2]&&Dt.y>=h.stroke.clipWindow[1]&&Dt.y<=h.stroke.clipWindow[3];{let t=e,i=r,n=.05*e,o=Dt.x+G(),s=Dt.y+W();return o>=-n&&o<=t+n&&s>=-n&&s<=i+n}}function se(t,e=!0,r=qt.alpha){const i=e?h.stroke.weight*qt.p.scatter:0,n=e?i*R(-1,1):0,o=e?i*R(-1,1):0;Ot(Dt.x+n,Dt.y+o,h.stroke.weight*qt.p.weight*t,r)}function ae(t,i,n=!0){f.glMask.isDrawn=!0,Wt.push(),Wt.noStroke(),h.stroke.color.setAlpha(i),Wt.fill(h.stroke.color);const o=n?h.stroke.weight*qt.p.scatter:0,s=n?o*R(-1,1):0,a=n?o*R(-1,1):0;Wt.translate(Dt.x+s-e,Dt.y+a-r),function(t,e){Wt.scale(t),"image"===qt.p.type&&Wt.tint(255,0,0,e/2);let r=0;"random"===qt.p.rotate?r=E(0,360):"natural"===qt.p.rotate&&(r=(Ft?-Ft.angle(Dt.plotted):-Xt)+Dt.angle()),Wt.rotate(r)}(h.stroke.weight*t,i),qt.p.tip(Wt),Wt.pop()}function le(){if(oe()){let t=re(),e=ne();if("marker"===qt.p.type){for(let r=1;r<10;r++)se(t*r/10,!1,5*e);Bt()}else if("custom"===qt.p.type||"image"===qt.p.type)for(let r=1;r<5;r++)ae(t*r/5,e,!1)}}function ce(t,e,r,i){if(!h.stroke.isActive||!h.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");V();let n=Y(t,e,r,i);0!=n&&(Jt(t,e,n),te(F(t,e,r,i),!1))}const he=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate"],ue=[["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,.12,null,null,1,.03,{curve:[.35,.25],min_max:[1.2,.85]},"marker"]]];for(let t of ue){let e={};for(let r=0;r<t[1].length;r++)e[he[r]]=t[1][r];jt(t[0],e)}ut.prototype.draw=function(t=!1,e,r){let i=$t();if(t&&Kt(t,e,r),i.isActive)for(let t of this.sides)ce(t[0].x,t[0].y,t[1].x,t[1].y);Ht(i)},ft.prototype.draw=function(t,e,r){$t().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,i){V(),Jt(e,r,t.length,t),te(i,!0)}(this,t,e,r))};const fe={tips:new Map,add(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 i=new window.Image;i.onload=()=>{const r=n.createImage(i.naturalWidth,i.naturalHeight);r.drawingContext.drawImage(i,0,0),fe.imageToWhite(r),this.tips.set(t,r),e()},i.onerror=()=>r(new Error(`Failed to load image tip: ${t}`)),i.src=t})))}};function ge(){return{...h.hatch}}function de(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let i=h.hatch;i.isActive=!0,i.dist=t,i.angle=e,i.options=r}function me(t){let e=h.hatch.dist,r=B(h.hatch.angle)%180,i=h.hatch.options,n=$t();h.hatch.hBrush&&Kt(...Object.values(h.hatch.hBrush)),Array.isArray(t)||(t=[t]);const o=function(t){let e={minX:Infinity,minY:Infinity,maxX:-Infinity,maxY:-Infinity};for(let r of t){const t=pe(r);e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY)}return e}(t);let s=new ut([[o.minX,o.minY],[o.maxX,o.minY],[o.maxX,o.maxY],[o.minX,o.maxY]]),a=r<=90&&r>=0?o.minY:o.maxY,l=i.gradient?M(i.gradient,0,1,1,1.1,!0):1,c=[],u=0,f=e,g=t=>({point1:{x:o.minX+f*t*z(90-r),y:a+f*t*O(90-r)},point2:{x:o.minX+f*t*z(90-r)+z(-r),y:a+f*t*O(90-r)+O(-r)}});for(;s.intersect(g(u)).length>0;){let e=[];for(let r of t)e.push(r.intersect(g(u)));c[u]=e.flat().sort((t,e)=>t.x===e.x?t.y-e.y:t.x-e.x),f*=l,u++}let d=c.filter(t=>void 0!==t[0]),m=i.rand||0;for(let t=0;t<d.length;t++){let r=d[t],n=t>0&&i.continuous;for(let i=0;i<r.length-1;i+=2)0!==m&&(r[i].x+=m*e*R(-1,1),r[i].y+=m*e*R(-1,1),r[i+1].x+=m*e*R(-1,1),r[i+1].y+=m*e*R(-1,1)),ce(r[i].x,r[i].y,r[i+1].x,r[i+1].y),n&&ce(d[t-1][1].x,d[t-1][1].y,r[i].x,r[i].y)}Ht(n)}function pe(t){if(t._boundingBox)return t._boundingBox;let e=Infinity,r=Infinity,i=-Infinity,n=-Infinity;for(let o=0;o<t.a.length;o++){const[s,a]=t.a[o];s<e&&(e=s),s>i&&(i=s),a<r&&(r=a),a>n&&(n=a)}return t._boundingBox={minX:e,minY:r,maxX:i,maxY:n},t._boundingBox}function xe(t,e,r){const i=2*Math.PI,n=r/2;f.ctx.moveTo(t+n,e),f.ctx.arc(t,e,n,0,i)}h.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},ut.prototype.hatch=function(t=!1,e,r){let i=ge();t&&de(t,e,r),i.isActive&&me(this),function(t){h.hatch={...t}}(i)},ft.prototype.hatch=function(t,e,r){ge().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,.25),this.pol.hatch())},h.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const ye=()=>({...h.fill});function ve(t,e,r,i){h.fill.opacity=(arguments.length<4?e:i)||150,h.fill.color=arguments.length<3?n.color(t):n.color(t,e,r),h.fill.isActive=!0}function _e(t,e="out"){h.fill.bleed_strength=k(t,0,1),h.fill.direction=e}function be(t=.4,e=.4){h.fill.texture_strength=k(t,0,1),h.fill.border_strength=k(e,0,1)}let we;const Re=[[],[]];function Se(t,e,r){return(e.x-t.x)*(r.y-t.y)-(e.y-t.y)*(r.x-t.x)>.01}class Ee{constructor(t,e,r,i=[],n=!1,o,s){if(this.v=t,this.m=e,this.dir=i,this.midP=r,n){let e=0,i=0;const n=[];for(let o=0;o<t.length;o++){const s=Math.abs(r.x-t[o].x),a=Math.abs(r.y-t[o].y);e=Math.max(e,s),i=Math.max(i,a);const l=t[o],c=t[(o+1)%t.length],h={x:c.x-l.x,y:c.y-l.y},u=D(0,0,h.x,h.y,90),f={x:l.x+h.x/2,y:l.y+h.y/2};n.push({v1:l,v2:c,ray:{point1:f,point2:{x:f.x+u.x,y:f.y+u.y}}})}this.sizeX=e,this.sizeY=i,this.dir=Array(t.length),n.forEach((t,e)=>{let r=0;for(const e of we.intersect(t.ray))Se(t.v1,t.v2,e)&&r++;this.dir[e]=r%2==0});const o=R(-.6,.6)*e,s=R(-.6,.6)*i;this.midP={x:r.x+o,y:r.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),r=~~(this.v.length/2-e/2),i=[...this.v],n=[...this.m],o=[...this.dir];return i.splice(r,e),n.splice(r,e),o.splice(r,e),{v:i,m:n,dir:o}}grow(t=1){const{v:e,m:r,dir:i}=this.trim(t),n=e.length,o=[],s=[],a=[],l="out"===h.fill.direction?-90:90;let c=0,u=999===t?R(.6,.8):h.fill.bleed_strength;for(let h=0;h<n;h++){Re[0].length<1.5*n&&(Re[0].push(A(.5,.2)),Re[1].push(A(0,.02)));const f=e[h],g=h+1<n?e[h+1]:e[0];t<997&&(u=r[h]);const d=(i[h]?l:-l)+5*R(-1,1),m=g.x-f.x,p=g.y-f.y,{x:x,y:y}=D(0,0,m,p,d),v=.5,_=S(Re[0])*R(.65,1.35)*u;o[c]=f,s[c]=r[h],a[c++]=i[h],o[c]={x:f.x+m*v+x*_,y:f.y+p*v+y*_},s[c]=r[h]+S(Re[1]),a[c++]=i[h]}return new Ee(o,s,this.midP,a,!1,this.sizeX,this.sizeY)}fill(t,i,n){const s=3*n,a=2*i*(1+n/2);f.blend(t),f.justChanged=!0,f.isBrush=!1,f.ctx.save(),f.ctx.setTransform(o*$(),o*H(),o*j(),o*U(),o*(G()+e/2),o*(W()+r/2)),f.ctx.strokeStyle=`rgb(${t._getRed()} ${t._getGreen()} ${t._getBlue()} / ${.005*h.fill.border_strength})`,f.ctx.lineCap="round";const l=Math.max(this.sizeX,this.sizeY),c=R(.15,.7);let u,g=this.grow();for(let e=0;e<20;e++){e%4==0&&(g=g.grow()),e%2==0&&(u=[g.grow(1-.0125*e),g.grow(.7-.0125*e),g.grow(.4-.0125*e)]);for(const r of u)r.grow(999).grow(997).layer(e,l,a,t);e%2==0&&g.grow(c).grow(999).layer(e,l,2*a,t),e%5!=0&&19!==e||(0!==s&&g.erase(3*s,i),f.blend(t,!0,!1,!0))}f.ctx.restore()}layer(t,e,r,i){var n;f.ctx.lineWidth=M(t,0,24,e/25,e/30,!0),f.ctx.fillStyle=`rgb(${i._getRed()} ${i._getGreen()} ${i._getBlue()} / ${r}%)`,n=this.v,f.ctx.beginPath(),n.forEach((t,e)=>{0===e?f.ctx.moveTo(t.x,t.y):f.ctx.lineTo(t.x,t.y)}),f.ctx.closePath(),f.ctx.fill(),f.ctx.stroke()}erase(t,e){f.ctx.save();const r=~~(R(80,110)*M(t,0,1,2,3.5)),i=this.sizeX/1.3,n=this.sizeY/1.3,o=Math.min(this.sizeX,this.sizeY)*(1.4-h.fill.bleed_strength),s=.05*o,a=.4*o,{x:l,y:c}=this.midP;f.ctx.globalCompositeOperation="destination-out";const u=(5-M(e,80,100,.3,.7,!0))*t/255;f.ctx.fillStyle=`rgb(255 0 0 / ${u})`,f.ctx.lineWidth=0;for(let t=0;t<r;t++){const e=l+A(0,i),r=c+A(0,n),o=R(s,a);f.ctx.beginPath(),xe(e,r,o),t%5!=0&&f.ctx.fill()}f.ctx.globalCompositeOperation="source-over",f.ctx.restore()}}ut.prototype.fill=function(t=!1,e,r,i,n,o){let s=ye();t&&(ve(t,e),_e(r,o),be(i,n)),s.isActive&&(V(),function(t){if(!h.fill.isActive||!h.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");we=t;const e=[...t.vertices],r=~~(.25*e.length*P({1:5,2:10,3:60})),i=h.fill.bleed_strength,n=e.map((t,e)=>(e>r?1:.3)*R(.85,1.2)*i),o=E(0,e.length),s=[...e.slice(o),...e.slice(0,o)],a=function(t){if(t.length<8)return t.reduce((t,e)=>({x:t.x+e.x,y:t.y+e.y}),{x:0,y:0}).map(e=>e/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,i=0,n=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,i+=(e[t].x+e[t+1].x)*o,n+=(e[t].y+e[t+1].y)*o}return r*=.5,r?{x:i/(6*r),y:n/(6*r)}:{x:e[0].x,y:e[0].y}}(s);new Ee(s,n,a,[],!0).fill(h.fill.color,M(h.fill.opacity,0,255,0,1,!0),h.fill.texture_strength)}(this)),(t=>{h.fill={...t}})(s)},ft.prototype.fill=function(t,e,r){ye().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,M(h.fill.bleed_strength,0,.6,.3,.45,!0)),this.pol.fill())};const Ae=[];"undefined"!=typeof p5&&p5.registerAddon(function(t,e,r){r.postsetup=()=>f.blend(!1,!0),r.postdraw=()=>f.blend(!1,!0);const i=e.push,n=e.pop,o=e.randomSeed,s=e.noiseSeed;e.push=function(){i.call(this),V(),Ae.push({fill:{...h.fill},stroke:{...h.stroke},hatch:{...h.hatch},field:{...h.field}})},e.pop=function(){n.call(this),function(){const t=Ae.pop();t&&(h.stroke={...t.stroke},h.field={...t.field},h.hatch={...t.hatch},h.fill={...t.fill})}()},e.randomSeed=function(t){o.call(this,t),(t=>{b=v(t)})(t)},e.noiseSeed=function(t){s.call(this,t),(t=>{w=y(v(t))})(t)}}),t.Plot=ft,t.Polygon=ut,t.Position=K,t.add=jt,t.addField=ct,t.arc=function(t,e,r,i,n){const o=new ft("curve"),s=270-B(i),a=270-B(n),l=B(n-i),c=Math.PI*r*l/180;o.addSegment(s,c,1,!0),o.endPlot(a,1,!0);const h=t+r*z(-s-90),u=e+r*O(-s-90);o.draw(h,u,1)},t.beginShape=dt,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],nt=new ft(t)},t.box=function(){return[...Gt.keys()]},t.circle=function(t,e,r,i=!1){const n=new ft("curve"),o=Math.PI*r,s=R(0,360),a=i?()=>1+.2*i*R():()=>1;for(let t=0;t<4;t++){const e=-90*t+s;n.addSegment(e*a(),o/2*a(),1,!0)}if(i){const t=i*E(-5,5);n.addSegment(s,Math.abs(t)*(Math.PI/180)*r,1,!0),n.endPlot(t+s,1,!0)}else n.endPlot(s,1,!0);const l=t-r*O(s),c=e-r*z(-s);n.show(l,c,1)},t.clip=function(t){h.stroke.clipWindow=t},t.endShape=pt,t.endStroke=function(t,e){if(!nt)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");nt.endPlot(t,e),nt.draw(ot[0],ot[1],1),nt=!1},t.field=lt,t.fill=ve,t.fillBleed=_e,t.fillTexture=be,t.flowLine=function(t,e,r,i){if(!h.stroke.isActive||!h.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");V(),Jt(t,e,r),te(B(i),!1)},t.hatch=de,t.hatchArray=me,t.hatchStyle=function(t,e="black",r=1){h.hatch.hBrush={brush:t,color:e,weight:r}},t.instance=t=>{l=!0,i=t},t.line=ce,t.listFields=function(){return V(),Array.from(st.keys())},t.load=s,t.move=function(t,e,r){if(!nt)throw new Error("move() called without beginStroke(). Call beginStroke() first.");nt.addSegment(t,e,r)},t.noClip=function(){h.stroke.clipWindow=null},t.noField=function(){V(),h.field.isActive=!1},t.noFill=function(){h.fill.isActive=!1},t.noHatch=function(){h.hatch.isActive=!1,h.hatch.hBrush=!1},t.noStroke=function(){h.stroke.isActive=!1},t.pick=Ut,t.polygon=function(t){new ut(t).show()},t.preload=async function(){await fe.load()},t.rect=function(t,e,r,i,n="corner"){"center"===n&&(t-=r/2,e-=i/2),dt(0),mt(t,e),mt(t+r,e),mt(t+r,e+i),mt(t,e+i),pt(!0)},t.refreshField=function(t=0){if(!h.field.isActive||!h.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=st.get(h.field.current);e.field=e.gen(t,at())},t.scaleBrushes=function(t){for(const{param:e}of Gt.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)},t.set=Kt,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].");xt(t,e).draw()},t.stroke=Zt,t.strokeWeight=Vt,t.vertex=mt,t.wRand=P,t.wiggle=function(t=1){lt("hand"),h.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,r,i,n,o;const s=t=>!!t&&"function"==typeof t.begin&&"function"==typeof t.end&&!!t.renderer&&!!t.renderer._pInst,a=()=>f?i:window.self.p5.instance,l=t=>{t&&"function"==typeof t.remove&&t.remove()},c=()=>n&&n._renderer&&"function"==typeof n._renderer.activeFramebuffer?n._renderer.activeFramebuffer():null,h=(t=!1)=>{const o=((t=!1)=>{if(f&&!t)return{renderer:i,width:i.width,height:i.height};if(!t){const t=a();return{renderer:t,width:t.width,height:t.height}}if(s(t)){if(!s(e=t)||e.renderer._pInst!==a())throw new Error("p5.brush only supports p5.Framebuffer targets created from the active sketch. Framebuffers created from p5.Graphics are not supported.");return{renderer:a(),width:t.width,height:t.height}}var e;return{renderer:t,width:t.width,height:t.height}})(t);if(n=o.renderer,"webgl2"!==n.webglVersion)throw new Error("p5.brush requires a WEBGL canvas");e=o.width,r=o.height,u=!0,n.loaded&&p.load()};let u=!1,f=!1;const g=()=>{u||h()},d={},m=()=>{n.loaded||(g(),p.load())},p={isBlending:!1,cachedColor:new Object,captureBlendSource(){const t=c();if(!t)return n._renderer;var i;(!(i=n.blendSourceFramebuffer)||i.width!==e||i.height!==r||"function"==typeof i.pixelDensity&&i.pixelDensity()!==o)&&(l(n.blendSourceFramebuffer),n.blendSourceFramebuffer=n.createFramebuffer({width:e,height:r,density:o,antialias:!1,depth:!1,stencil:!1}));const s=n.blendSourceFramebuffer;return s.draw(()=>{n.clear(),n.push(),"function"==typeof n.imageMode&&n.imageMode(n.CENTER??n._renderer?._pInst?.CENTER),n.image(t,0,0,e,r),n.pop()}),s},load(){o=n.pixelDensity();const t="function"==typeof n.createGraphics?n:n._pInst,i=t.P2D??n.P2D,s=t.WEBGL??n.WEBGL;n.loaded&&n.mask&&n.glMask&&n.mask.width===e&&n.mask.height===r&&n.glMask.width===e&&n.glMask.height===r?(this.mask=n.mask,this.glMask=n.glMask,this.ctx=this.mask.drawingContext):(l(n.mask),l(n.glMask),n.mask=t.createGraphics(e,r,i),n.glMask=t.createGraphics(e,r,s),n.loaded=!0,n.shaderProgram??=n.createShader("#version 300 es\n#define GLSLIFY 1\nuniform bool u_flipOutputY;out vec2 p;void main(){vec3 v=vec3(-1);v[gl_VertexID]=3.;p=v.xy;gl_Position=vec4(v.x,u_flipOutputY ?-v.y : v.y,0,1);}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nuniform bool u_isBrush;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 uv1=vec2(uv.x,1.0-uv.y);vec4 source=texture(u_source,uv1);vec4 maskColor=texture(u_mask,uv1);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=uv1+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.0);}"),this.mask=n.mask,this.mask.pixelDensity(o),this.mask.clear(),this.mask.angleMode(n.DEGREES),this.ctx=this.mask.drawingContext,this.glMask=n.glMask,this.glMask.pixelDensity(o),this.glMask.clear(),this.glMask.angleMode(this.glMask.DEGREES),this.glMask.drawingContext.lineWidth=0),this.glMask._renderer.uModelMatrix=n._renderer.uModelMatrix},blend(t=!1,e=!1){m();const r=this.isBrush?this.glMask:this.mask,i=this.isBrush?this.mask:this.glMask;!this.isBlending&&t&&(this.isBlending=!0,this.cachedColor=t._array,this.glMask.clear()),(e||this.cachedColor[0]!==t._array[0]||this.cachedColor[1]!==t._array[1]||this.cachedColor[2]!==t._array[2]||this.cachedColor[3]!==t._array[3])&&(this.justChanged&&(this.applyShader(i),this.justChanged=!1),this.isBlending&&this.applyShader(r),this.cachedColor=t._array,e&&(this.isBlending=!1))},applyShader(t){let i=n.shaderProgram;const o=n.drawingContext,s=!!c(),a=this.captureBlendSource(),l=o.getParameter(o.DEPTH_TEST);o.disable(o.DEPTH_TEST),n.push(),n.translate(0,0),n.shader(i),i.setUniform("u_source",a),i.setUniform("u_isBrush",this.isBrush),i.setUniform("u_flipOutputY",s),i.setUniform("u_mask",t),i.setUniform("u_color",this.cachedColor),n.fill(0,0,0,0),n.noStroke(),n.rect(-e/2,-r/2,e,r),n.pop(),n.resetShader(),l&&o.enable(o.DEPTH_TEST),t.clear(),t.isDrawn=!1}},x=Math.sqrt(3),y=.5*(x-1),v=(3-x)/6,b=t=>0|Math.floor(t),_=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 w(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 i=r+~~(t()*(256-r)),n=e[r];e[r]=e[i],e[i]=n}for(let t=256;t<512;t++)e[t]=e[t-256];return e}(t),r=new Float64Array(e).map(t=>_[t%12*2]),i=new Float64Array(e).map(t=>_[t%12*2+1]);return function(t,n){let o=0,s=0,a=0;const l=(t+n)*y,c=b(t+l),h=b(n+l),u=(c+h)*v,f=t-(c-u),g=n-(h-u);let d,m;f>g?(d=1,m=0):(d=0,m=1);const p=f-d+v,x=g-m+v,_=f-1+2*v,w=g-1+2*v,S=255&c,R=255&h;let E=.5-f*f-g*g;if(E>=0){const t=S+e[R];E*=E,o=E*E*(r[t]*f+i[t]*g)}let A=.5-p*p-x*x;if(A>=0){const t=S+d+e[R+m];A*=A,s=A*A*(r[t]*p+i[t]*x)}let P=.5-_*_-w*w;if(P>=0){const t=S+1+e[R+1];P*=P,a=P*P*(r[t]*_+i[t]*w)}return 70*(o+s+a)}}function S(t,e){let r=new R(t),i=()=>r.next();return i.double=()=>i()+11102230246251565e-32*(2097152*i()|0),i.int32=()=>4294967296*r.next()|0,i.quick=i,i}class R{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 i=.02519603282416938*e;e=i>>>0,i-=e,i*=e,e=i>>>0,i-=e,e+=4294967296*i}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:i}=this,n=2091639*e+2.3283064365386963e-10*t;return this.s0=r,this.s1=i,this.s2=n-(this.c=0|n)}copy(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}}let E=S(Math.random());const A=[],P=t=>A.push(t);let M=w(S(Math.random()));const k=(t=0,e=1)=>t+E()*(e-t),I=t=>t[~~(E()*t.length)],L=(t,e)=>~~k(t,e),C=(t=0,e=1)=>{const r=1-E(),i=E();return Math.sqrt(-2*Math.log(r))*X(360*i)*e+t},T=t=>{let e=0;const r=[];for(const i in t)e+=t[i],r.push({key:i,cumulative:e});const i=E()*e;for(const{key:t,cumulative:e}of r)if(i<e)return isNaN(t)?t:parseInt(t)},N=(t,e,r,i,n,o=!1)=>{let s=i+(t-e)/(r-e)*(n-i);return o?i<n?z(s,i,n):z(s,n,i):s},z=(t,e,r)=>Math.max(Math.min(t,r),e),O=t=>(t%=360)<0?t+360:t,B=1440,D=2*Math.PI/B,Y=new Float32Array(B).fill(NaN),F=new Float32Array(B).fill(NaN),X=t=>{const e=~~(4*O(t));let r=Y[e];return isNaN(r)&&(r=Math.cos(e*D),Y[e]=r),r},G=t=>{const e=~~(4*O(t));let r=F[e];return isNaN(r)&&(r=Math.sin(e*D),F[e]=r),r},$=(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},H=(t,e=!1)=>e||n&&"function"==typeof n.angleMode&&n.angleMode()===n.RADIANS?180*t/Math.PI:t,W=(t,e,r,i,n)=>{let o=X(n),s=G(n);return{x:o*(r-t)+s*(i-e)+t,y:o*(i-e)-s*(r-t)+e}},U=(t,e,r,i)=>Math.hypot(r-t,i-e),j=(t,e,r,i)=>$(Math.atan2(-(i-e),r-t),!0),Z=(t,e,r,i,n=!1)=>{let o=t.x,s=t.y,a=e.x,l=e.y,c=r.x,h=r.y,u=i.x,f=i.y;if(o===a&&s===l||c===u&&h===f)return!1;let g=a-o,d=l-s,m=u-c,p=f-h,x=p*g-m*d;if(0===x)return!1;let y=(m*(s-h)-p*(o-c))/x,v=(g*(s-h)-d*(o-c))/x;return!(!n&&(v<0||v>1))&&{x:o+y*g,y:s+y*d}},V=()=>n._renderer.uModelMatrix.mat4[12],K=()=>n._renderer.uModelMatrix.mat4[13],q=()=>n._renderer.uModelMatrix.mat4[0],J=()=>n._renderer.uModelMatrix.mat4[1],Q=()=>n._renderer.uModelMatrix.mat4[4],tt=()=>n._renderer.uModelMatrix.mat4[5];let et=!1;function rt(){et||(m(),nt=.01*e,ot=-.5*e,st=-.5*r,at=Math.round(2*e/nt),lt=Math.round(2*r/nt),dt("hand",(t,e)=>{const r=k(.2,.8),i=L(5,10);return mt(e,(e,n)=>.5*i*G(r*n*e+L(15,25))*.2*X(t)+M(e,n)*i*.7)}),dt("curved",(t,e)=>{let r=L(-10,10);return L(0,100)%2==0&&(r*=-1),mt(e,(e,i)=>3*N(M(.02*e+.03*t,.02*i+.03*t),0,1,-r,r))}),dt("zigzag",(t,e)=>{let r=L(-30,-15)+Math.abs(44*G(t));L(0,100)%2==0&&(r*=-1);let i=r,n=0;for(let t=0;t<at;t++){for(let r=0;r<lt;r++)e[t][r]=n,n+=i,i*=-1;n+=i,i*=-1}return e}),dt("waves",(t,e)=>{const r=L(10,15)+5*G(t),i=L(3,6)+3*X(t),n=L(20,35);return mt(e,(t,e)=>G(r*t)*n*X(e*i)+L(-3,3))}),dt("seabed",(t,e)=>{const r=k(.4,.8),i=L(18,26);return mt(e,(e,n)=>1.1*i*G(r*n*e+L(15,20))*X(t))}),dt("spiral",(t,e)=>{const r=L(5,10),i=2*L(0,2)-1,n=L(65,80),o=Array.from({length:r},()=>({x:k(.1,.9)*at,y:k(.1,.9)*lt}));return mt(e,(t,e)=>{let r=0,s=0;for(const a of o){const o=t-a.x,l=e-a.y,c=1/(o*o+l*l+1),h=Math.atan2(l,o)*(180/Math.PI),u=i*(h+n)*Math.PI/180;r+=c*Math.cos(u),s+=c*Math.sin(u)}return Math.atan2(s,r)*(180/Math.PI)})}),dt("columns",(t,e)=>{const r=L(3,8),i=L(25,45);return mt(e,(t,e)=>G(t*r)*i)}),et=!0)}class it{constructor(t,e){rt(),this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=it.getColIndex(t),this.rowIdx=it.getRowIndex(e)}reset(){this.plotted=0}isIn(){return d.field.isActive?it.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const t=e,i=r,n=this.x+V(),o=this.y+K();return n>=-.3*t&&n<=1.3*t&&o>=-.3*i&&o<=1.3*i}angle(){return this.isIn()&&d.field.isActive?ct.get(d.field.current).field[this.colIdx][this.rowIdx]*d.field.wiggle:0}moveTo(t,e,r=1){this.movePos(H(t),e,r)}_moveToDegrees(t,e,r=1){this.movePos(t,e,r)}plotTo(t,e,r,i=1){this.movePos(t,e,r,i)}movePos(t,e,r,i=!1){const n=i||1;if(this.isIn())for(let o=0;o<e/r;o++){const e=this.angle()-(i?t.angle(this.plotted):t);this.update(this.x+r*X(e),this.y+r*G(e)),this.plotted+=r/n}else this.plotted+=r/n}static getRowIndex(t,e=1){const r=t+K()-st;return Math.round(r/nt/e)}static getColIndex(t,e=1){const r=t+V()-ot;return Math.round(r/nt/e)}static isIn(t,e){return t>=0&&e>=0&&t<at&&e<lt}}d.field={isActive:!1,current:null,wiggle:1};let nt,ot,st,at,lt,ct=new Map;const ht=new Set(["degrees","radians"]);function ut(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!ht.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function ft(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]=H(t[e][r],!0);return t}(t.gen(e,new Array(at).fill(null).map(()=>new Float32Array(lt))),t.angleMode)}function gt(t){if(d.field.wiggle||(d.field.wiggle=1),rt(),!ct.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(ct.keys()).join(", ")}.`);d.field.isActive=!0,d.field.current=t;const e=ct.get(t);e.field||(e.field=ft(e,0))}function dt(t,e,r={}){ct.set(t,{gen:e,field:null,angleMode:ut(r)})}function mt(t,e){for(let r=0;r<at;r++)for(let i=0;i<lt;i++)t[r][i]=e(r,i);return t}class pt{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,i]of this.sides){const n=Z(t.point1,t.point2,e,i);n&&r.push(n)}return this._intersectionCache[e]=r,r}show(){d.stroke&&this.draw(),d.hatch&&this.hatch(),d.fill&&this.fill()}}class xt{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,i=!1){this.angles.length>0&&this.angles.pop(),t=i?(t%360+360)%360:$(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:$(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=$(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],i=t[this.index+1]??r;return Math.abs(i-r)>180&&(i>r?i=-(360-i):r=-(360-r)),N(e-this.suma,0,this.segments[this.index],r,i,!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,i,n=1,o){rt();const s=.5,a=[],l=Math.round(this.length/s),c=new it(t+e/2,i+r/2);let h=0,u=0;for(let t=0;t<l;t++){c.plotTo(this,s,s);const t=this.calcIndex(c.plotted);h+=s,(h>=Math.max(this.segments[t]*o*k(.7,1.3),10)||t>=u)&&c.x&&(a.push([c.x-e/2,c.y-r/2]),h=0,t>=u&&u++)}return new pt(a)}show(t,e,r=1){d.stroke&&this.draw(t,e,r),d.hatch&&this.hatch(t,e,r),d.fill&&this.fill(t,e,r)}}let yt,vt,bt,_t;class wt{constructor(){this.isClosed=!1,this.curvature=vt,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){At(this.vert,this.curvature,this.isClosed).show()}}function St(t=0){vt=z(t,0,1),yt=new wt}function Rt(t,e,r=1){if(!yt)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");yt.vertex(t,e,r)}function Et(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 At(t,e=.5,r=!1){const i=new xt(0===e?"segments":"curve"),n=2*Math.PI;if(r&&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 h=t[c],u=t[c+1],f=t[c+2],g=U(h[0],h[1],u[0],u[1]),d=U(u[0],u[1],f[0],f[1]),m=j(h[0],h[1],u[0],u[1]),p=j(u[0],u[1],f[0],f[1]),x=e*Math.min(g,d,.5*Math.min(g,d)),y=Math.max(g,d),v=g-x,b=d-x;if(Math.floor(m)===Math.floor(p)){const e=r&&0===c?0:g-l,n=r?0===c?0:d-a:d;i.addSegment(m,e,h[2],!0),c===t.length-3&&i.addSegment(p,n,u[2],!0),l=0,0===c&&(o=g,a=x,s=t[1],l=0)}else{const e={x:u[0]-x*X(-m),y:u[1]-x*G(-m)},f={x:e.x+y*X(90-m),y:e.y+y*G(90-m)},g={x:u[0]+x*X(-p),y:u[1]+x*G(-p)},d={x:g.x+y*X(90-p),y:g.y+y*G(90-p)},_=Z(e,f,g,d,!0),w=U(e.x,e.y,_.x,_.y),S=U(e.x,e.y,g.x,g.y)/2,R=n*w*(2*Math.asin(S/w)*(180/Math.PI))/360,E=r&&0===c?0:v-l,A=c===t.length-3?r?o-x:b:0;i.addSegment(m,E,h[2],!0),i.addSegment(m,isNaN(R)?0:R,h[2],!0),i.addSegment(p,A,u[2],!0),l=x,0===c&&(o=v,a=x,s=[e.x,e.y])}c===t.length-3&&i.endPlot(p,u[2],!0)}else if(0===e){const e=t[c],r=t[c+1],n=U(e[0],e[1],r[0],r[1]),o=j(e[0],e[1],r[0],r[1]);i.addSegment(o,n,r[2],!0),c===t.length-2&&i.endPlot(o,1,!0)}i.origin=r&&0!==e?s:t[0]}return i}let Pt,Mt,kt,It,Lt,Ct=!1,Tt=0,Nt=0;const zt={},Ot={};let Bt=1,Dt=0,Yt=0,Ft=1,Xt=0,Gt=0,$t=new Float32Array(8192),Ht=0,Wt=2048,Ut=32768;function jt(t,i,n,s){if(Ht>=Wt){Wt*=2;const t=new Float32Array(4*Wt);t.set($t),$t=t}const a=t-e/2,l=i-r/2,c=4*Ht;$t[c]=Bt*a+Yt*l+Xt+e/2,$t[c+1]=Dt*a+Ft*l+Gt+r/2,$t[c+2]=o*n*Math.sqrt(Bt*Bt+Dt*Dt)/2,$t[c+3]=s/255,Ht++}function Zt(){if(0===Ht)return;p.glMask.isDrawn=!0;const t=d.stroke.color._array;Pt.useProgram(Lt),Pt.enable(Pt.BLEND),Pt.blendFunc(Pt.ONE_MINUS_DST_ALPHA,Pt.ONE),Pt.bindVertexArray(kt),Pt.bindBuffer(Pt.ARRAY_BUFFER,It);const e=16*Ht,r=$t.subarray(0,4*Ht);e>Ut?(Pt.bufferData(Pt.ARRAY_BUFFER,$t,Pt.DYNAMIC_DRAW),Ut=$t.byteLength):Pt.bufferSubData(Pt.ARRAY_BUFFER,0,r),Pt.uniform4f(Ot.u_color,...t),Pt.uniformMatrix4fv(Ot.u_matrix,!1,Mt),Pt.drawArrays(Pt.POINTS,0,Ht),Pt.bindVertexArray(null),Ht=0,p.glMask._renderer._curShader=null}d.stroke={color:null,weight:1,clipWindow:null,type:"HB",isActive:!1,opacity:1};let Vt,Kt,qt,Jt,Qt=new Map,te=null,ee={a:1,b:0,c:0,d:1,tx:0,ty:0};function re(){return{...d.stroke}}function ie(t){d.stroke={...t}}function ne(t,e){if(e.type=["marker","custom","image","spray"].includes(e.type)?e.type:"default",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||"object"==typeof t&&!Array.isArray(t))return t;if("function"==typeof t)return{type:"custom",min_max:[0,1],curve:t};if(Array.isArray(t)){const[e,r,i]=2===t.length?[t[0],(t[0]+t[1])/2,t[1]]:t,n=Math.min(e,r,i),o=Math.max(e,r,i),s=o-n||1,[a,l,c]=[(e-n)/s,(r-n)/s,(i-n)/s];return{type:"custom",min_max:[n,o],curve:t=>t<.5?a+(l-a)*t*2:l+(c-l)*(t-.5)*2}}}(e.pressure),"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 Pe.add(e.image.src),e.tip=()=>{te.image(Pe.tips.get(fe.p.image.src),-fe.p.weight/2,-fe.p.weight/2,fe.p.weight,fe.p.weight)},Qt.set(t,{param:e,colors:[],buffers:[]}),Pe.load()}Qt.set(t,{param:e,colors:[],buffers:[]})}function oe(t){if(!Qt.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...Qt.keys()].join(", ")}.`);d.stroke.type=t}function se(t,e,r){g(),d.stroke.color=n.color(...arguments),d.stroke.isActive=!0}function ae(t){d.stroke.weight=t}function le(t,e,r=1){oe(t),se(e),ae(r)}function ce(){return{a:q(),b:J(),c:Q(),d:tt(),tx:V(),ty:K()}}function he(t,e,r){return{x:t.a*e+t.c*r+t.tx,y:t.b*e+t.d*r+t.ty}}function ue(t){const[e,r,i,n]=t;return{minX:Math.min(e,i),minY:Math.min(r,n),maxX:Math.max(e,i),maxY:Math.max(r,n)}}const fe={};function ge(t,i,n,o=!1){Bt=q(),Dt=J(),Yt=Q(),Ft=tt(),Xt=V(),Gt=K(),ee=ce(),Vt=new it(t+e/2,i+r/2),Kt=n,qt=o,qt&&qt.calcIndex(0)}const de=[];function me(t,i){i||(Jt=t),function(){fe.seed=999999*k();const{param:t}=Qt.get(d.stroke.type)??{};if(!t)return;fe.p=t,te=p.glMask;const{pressure:i}=t;if(fe.a="custom"!==i.type?k(-1,1):0,fe.b="custom"!==i.type?k(1,1.5):0,fe.cp="custom"!==i.type?k(3,3.5):k(-.2,.2),[fe.min,fe.max]=i.min_max,fe.noiseoffset=.03,!qt){const t=Jt*Math.PI/180;fe.cos=Math.cos(t),fe.sin=Math.sin(t)}(function(){m();const t=p.glMask.drawingContext,i=!Ct||Pt!==t;(i||Tt!==e||Nt!==r)&&(Mt=new Float32Array([2/e,0,0,0,0,-2/r,0,0,0,0,1,0,-1,1,0,1]),Tt=e,Nt=r),i&&(Pt=t,Lt=(t=>{const e=t.createProgram();for(let[r,i]of[[t.VERTEX_SHADER,"#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;}"],[t.FRAGMENT_SHADER,"#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);}"]]){const n=t.createShader(r);t.shaderSource(n,i),t.compileShader(n),t.attachShader(e,n)}return t.linkProgram(e),e})(Pt),Pt.useProgram(Lt),Pt.enable(Pt.BLEND),Pt.blendFunc(Pt.ONE_MINUS_DST_ALPHA,Pt.ONE),["a_position","a_radius","a_alpha"].forEach(t=>zt[t]=Pt.getAttribLocation(Lt,t)),["u_matrix","u_color"].forEach(t=>Ot[t]=Pt.getUniformLocation(Lt,t)),kt=Pt.createVertexArray(),Pt.bindVertexArray(kt),It=Pt.createBuffer(),Pt.bindBuffer(Pt.ARRAY_BUFFER,It),Pt.bufferData(Pt.ARRAY_BUFFER,$t.byteLength,Pt.DYNAMIC_DRAW),Ut=$t.byteLength,Pt.enableVertexAttribArray(zt.a_position),Pt.vertexAttribPointer(zt.a_position,2,Pt.FLOAT,!1,16,0),Pt.enableVertexAttribArray(zt.a_radius),Pt.vertexAttribPointer(zt.a_radius,1,Pt.FLOAT,!1,16,8),Pt.enableVertexAttribArray(zt.a_alpha),Pt.vertexAttribPointer(zt.a_alpha,1,Pt.FLOAT,!1,16,12),Pt.bindVertexArray(null),Ct=!0)})(),be()&&p.blend(d.stroke.color),!1===p.isBrush&&(p.justChanged=!0),p.isBrush=!0,fe.alpha=ve(),Se()}();const n=function(){const{param:t}=Qt.get(d.stroke.type)??{};return t?t.spacing:1}(),o=Math.round(Kt*(i?t:1)/n);for(let e=0;e<o;e++)de.length<2*o&&de.push(C()),pe(),i?Vt.plotTo(qt,n,n,t,e<10):Vt._moveToDegrees(t,n,n);Zt(),Se()}function pe(t=!1){if(!be())return;let e=t||xe(),r=N(M(fe.seed+.002*Vt.plotted,0),0,1,1-fe.noiseoffset,1+fe.noiseoffset);switch(fe.p.type){case"spray":!function(t){const e=d.stroke.weight*fe.p.scatter*t+d.stroke.weight*I(de)*fe.p.scatter/3,r=fe.p.weight*k(.9,1.1),i=Math.ceil(fe.p.grain/t);for(let t=0;t<i;t++){const t=k(.9,1.1),i=t*e*k(-1,1),n=k(-1,1),o=Math.sqrt((t*e)**2-i**2);jt(Vt.x+i,Vt.y+n*o,r,fe.alpha)}}(e*r);break;case"marker":_e(e*r);break;case"custom":case"image":we(e*r,fe.alpha);break;default:!function(t,e=1){const r=(e=N(e,0,1,.9,1.05))*d.stroke.weight*fe.p.scatter*(fe.p.sharpness+(1-fe.p.sharpness)*I(de)/t);if(k(0,fe.p.grain*t)>.4){let e,i;if(qt)e=.7*r*k(-1,1),i=r*k(-1,1);else{const t=r*k(-1,1),n=.3*r*k(-1,1);e=t*-fe.sin+n*fe.cos,i=t*fe.cos+n*fe.sin}jt(Vt.x+e,Vt.y+i,t*t*fe.p.weight*k(.85,1.15)*d.stroke.weight,Math.max(.9,t)*fe.alpha*k(.75,1.1))}}(e*r)}}function xe(){return qt?ye()*qt.pressure(Vt.plotted):ye()}function ye(){return"custom"===fe.p.pressure.type?N(fe.p.pressure.curve(Vt.plotted/Kt)+fe.cp,0,1,fe.min,fe.max,!0):function(t=.5+fe.p.pressure.curve[0]*fe.a,e=1-fe.p.pressure.curve[1]*fe.b,r=fe.cp,i=fe.min,n=fe.max){const o=t*Kt,s=(Vt.plotted<o?1.2*e:.8*e)*(Kt/2);return N(1/(1+Math.pow(Math.abs((Vt.plotted-o)/s),2*r)),0,1,i,n)}()}function ve(){return["default","spray"].includes(fe.p.type)?fe.p.opacity:fe.p.opacity/Math.min(d.stroke.weight,1.3)}function be(){const t=he(ee,Vt.x-e/2,Vt.y-r/2);if(d.stroke.clipWindow){const e=he(d.stroke.clipWindow.inverse,t.x,t.y),{bounds:r}=d.stroke.clipWindow;return e.x>=r.minX&&e.x<=r.maxX&&e.y>=r.minY&&e.y<=r.maxY}let i=.05*e;return t.x>=-e/2-i&&t.x<=e/2+i&&t.y>=-r/2-i&&t.y<=r/2+i}function _e(t,e=!0,r=fe.alpha){const i=e?d.stroke.weight*fe.p.scatter:0,n=e?i*k(-1,1):0,o=e?i*k(-1,1):0;jt(Vt.x+n,Vt.y+o,d.stroke.weight*fe.p.weight*t,r)}function we(t,i,n=!0){p.glMask.isDrawn=!0,te.push(),te.noStroke(),d.stroke.color.setAlpha(i),te.fill(d.stroke.color);const o=n?d.stroke.weight*fe.p.scatter:0,s=n?o*k(-1,1):0,a=n?o*k(-1,1):0;te.translate(Vt.x+s-e,Vt.y+a-r),function(t,e){te.scale(t),"image"===fe.p.type&&te.tint(255,0,0,e/2);let r=0;"random"===fe.p.rotate?r=L(0,360):"natural"===fe.p.rotate&&(r=(qt?-qt.angle(Vt.plotted):-Jt)+Vt.angle()),te.rotate(r)}(d.stroke.weight*t,i),fe.p.tip(te),te.pop()}function Se(){if(be()){let t=xe(),e=ve();if("marker"===fe.p.type){for(let r=1;r<10;r++)_e(t*r/10,!1,5*e);Zt()}else if("custom"===fe.p.type||"image"===fe.p.type)for(let r=1;r<5;r++)we(t*r/5,e,!1)}}function Re(t,e,r,i){if(!d.stroke.isActive||!d.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");rt();let n=U(t,e,r,i);0!=n&&(ge(t,e,n),me(j(t,e,r,i),!1))}P(()=>{de.length=0});const Ee=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate"],Ae=[["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,.12,null,null,1,.03,{curve:[.35,.25],min_max:[1.2,.85]},"marker"]]];for(let t of Ae){let e={};for(let r=0;r<t[1].length;r++)e[Ee[r]]=t[1][r];ne(t[0],e)}pt.prototype.draw=function(t=!1,e,r){let i=re();if(t&&le(t,e,r),i.isActive)for(let t of this.sides)Re(t[0].x,t[0].y,t[1].x,t[1].y);ie(i)},xt.prototype.draw=function(t,e,r){re().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,i){rt(),ge(e,r,t.length,t),me(i,!0)}(this,t,e,r))};const Pe={tips:new Map,add(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 i=new window.Image;i.onload=()=>{const r=n.createImage(i.naturalWidth,i.naturalHeight);r.drawingContext.drawImage(i,0,0),Pe.imageToWhite(r),this.tips.set(t,r),e()},i.onerror=()=>r(new Error(`Failed to load image tip: ${t}`)),i.src=t})))}};function Me(){return{...d.hatch}}function ke(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let i=d.hatch;i.isActive=!0,i.dist=t,i.angle=H(e),i.options=r}function Ie(t){let e=d.hatch.dist,r=(d.hatch.angle%180+180)%180,i=d.hatch.options,n=re();d.hatch.hBrush&&le(...Object.values(d.hatch.hBrush)),Array.isArray(t)||(t=[t]);const o=function(t){let e={minX:Infinity,minY:Infinity,maxX:-Infinity,maxY:-Infinity};for(let r of t){const t=Le(r);e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY)}return e}(t);let s=new pt([[o.minX,o.minY],[o.maxX,o.minY],[o.maxX,o.maxY],[o.minX,o.maxY]]),a=r<=90&&r>=0?o.minY:o.maxY,l=i.gradient?N(i.gradient,0,1,1,1.1,!0):1,c=[],h=0,u=e,f=t=>({point1:{x:o.minX+u*t*X(90-r),y:a+u*t*G(90-r)},point2:{x:o.minX+u*t*X(90-r)+X(-r),y:a+u*t*G(90-r)+G(-r)}});for(;s.intersect(f(h)).length>0;){let e=[];for(let r of t)e.push(r.intersect(f(h)));c[h]=e.flat().sort((t,e)=>t.x===e.x?t.y-e.y:t.x-e.x),u*=l,h++}let g=c.filter(t=>void 0!==t[0]),m=i.rand||0;for(let t=0;t<g.length;t++){let r=g[t],n=t>0&&i.continuous;for(let i=0;i<r.length-1;i+=2)0!==m&&(r[i].x+=m*e*k(-1,1),r[i].y+=m*e*k(-1,1),r[i+1].x+=m*e*k(-1,1),r[i+1].y+=m*e*k(-1,1)),Re(r[i].x,r[i].y,r[i+1].x,r[i+1].y),n&&Re(g[t-1][1].x,g[t-1][1].y,r[i].x,r[i].y)}ie(n)}function Le(t){if(t._boundingBox)return t._boundingBox;let e=Infinity,r=Infinity,i=-Infinity,n=-Infinity;for(let o=0;o<t.a.length;o++){const[s,a]=t.a[o];s<e&&(e=s),s>i&&(i=s),a<r&&(r=a),a>n&&(n=a)}return t._boundingBox={minX:e,minY:r,maxX:i,maxY:n},t._boundingBox}function Ce(t,e,r){const i=2*Math.PI,n=r/2;p.ctx.moveTo(t+n,e),p.ctx.arc(t,e,n,0,i)}d.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},pt.prototype.hatch=function(t=!1,e,r){let i=Me();t&&ke(t,e,r),i.isActive&&Ie(this),function(t){d.hatch={...t}}(i)},xt.prototype.hatch=function(t,e,r){Me().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,.25),this.pol.hatch())},d.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const Te=()=>({...d.fill});function Ne(t,e,r,i){d.fill.opacity=(arguments.length<4?e:i)||150,d.fill.color=arguments.length<3?n.color(t):n.color(t,e,r),d.fill.isActive=!0}function ze(t,e="out"){d.fill.bleed_strength=z(t,0,1),d.fill.direction=e}function Oe(t=.4,e=.4){d.fill.texture_strength=z(t,0,1),d.fill.border_strength=z(e,0,1)}let Be;const De=[[],[]];function Ye(){for(let t=0;t<512;t++)De[0][t]=C(.5,.2),De[1][t]=C(0,.02)}function Fe(t,e,r){return(e.x-t.x)*(r.y-t.y)-(e.y-t.y)*(r.x-t.x)>.01}P(Ye);class Xe{constructor(t,e,r,i=[],n=!1,o,s){if(this.v=t,this.m=e,this.dir=i,this.midP=r,n){let e=0,i=0;const n=[];for(let o=0;o<t.length;o++){const s=Math.abs(r.x-t[o].x),a=Math.abs(r.y-t[o].y);e=Math.max(e,s),i=Math.max(i,a);const l=t[o],c=t[(o+1)%t.length],h={x:c.x-l.x,y:c.y-l.y},u=W(0,0,h.x,h.y,90),f={x:l.x+h.x/2,y:l.y+h.y/2};n.push({v1:l,v2:c,ray:{point1:f,point2:{x:f.x+u.x,y:f.y+u.y}}})}this.sizeX=e,this.sizeY=i,this.dir=Array(t.length),n.forEach((t,e)=>{let r=0;for(const e of Be.intersect(t.ray))Fe(t.v1,t.v2,e)&&r++;this.dir[e]=r%2==0});const o=k(-.6,.6)*e,s=k(-.6,.6)*i;this.midP={x:r.x+o,y:r.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),r=~~(this.v.length/2-e/2),i=[...this.v],n=[...this.m],o=[...this.dir];return i.splice(r,e),n.splice(r,e),o.splice(r,e),{v:i,m:n,dir:o}}scatter(t=.3){const e=this.v.length,r=Math.max(3,~~(e*t)),i=[],n=e/r;for(let t=0;t<r;t++)i.push(~~(t*n+k(0,.8*n)));const o=[],s=[],a=[],l=this.midP,c=Be.sides;for(const t of i){const r=t%e;let i=this.v[r],n=0;for(const[t,e]of c){const r=t.y,o=e.y;if(r>i.y==o>i.y)continue;const s=(i.y-r)/(o-r);i.x<t.x+s*(e.x-t.x)&&n++}n%2==0&&(i={x:l.x+(i.x-l.x)*k(.3,.6),y:l.y+(i.y-l.y)*k(.3,.6)}),o.push(i),s.push(this.m[r]),a.push(!this.dir[r])}return new Xe(o,s,this.midP,a,!1,this.sizeX,this.sizeY)}flipDirs(){return new Xe(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:i}=this.trim(t),n=e.length,o=2*n,s=new Array(o),a=new Array(o),l=new Array(o),c="out"===d.fill.direction?-90:90;0===De[0].length&&Ye();const h=De[0],u=h.length,f=De[1],g=f.length;let m=0,p=999===t?k(.6,.8):d.fill.bleed_strength;for(let o=0;o<n;o++){const d=e[o],x=e[o+1<n?o+1:0],y=r[o],v=i[o];t<997&&(p=y);const b=(v?c:-c)+5*k(-1,1),_=X(b),w=G(b),S=x.x-d.x,R=x.y-d.y,E=_*S+w*R,A=_*R-w*S,P=h[~~(k(0,1)*u)]*k(.65,1.35)*p;s[m]=d,a[m]=y,l[m]=v,m++,s[m]={x:d.x+.5*S+E*P,y:d.y+.5*R+A*P},a[m]=y+f[~~(k(0,1)*g)],l[m]=v,m++}let x=s,y=a,v=l,b=1024/d.fill.texture_strength;if(b&&m>b){const t=Math.ceil(m/b);x=[],y=[],v=[];for(let e=0;e<m;e+=t)x.push(s[e]),y.push(a[e]),v.push(l[e])}else x.length=m,y.length=m,v.length=m;return new Xe(x,y,this.midP,v,!1,this.sizeX,this.sizeY)}fill(t,i,n){const s=3*n,a=2*i*(1+n/2);p.blend(t),p.justChanged=!0,p.isBrush=!1,p.ctx.save(),p.ctx.setTransform(o*q(),o*J(),o*Q(),o*tt(),o*(V()+e/2),o*(K()+r/2)),p.ctx.strokeStyle=`rgb(${t._getRed()} ${t._getGreen()} ${t._getBlue()} / ${.005*d.fill.border_strength})`,p.ctx.lineCap="round";const l=Math.max(this.sizeX,this.sizeY),c=k(.15,.7);let h=this.grow();const u=this.scatter(.1).grow().scatter(.75).flipDirs();let f;for(let e=0;e<20;e++){e%4==0&&(h=h.grow()),e%2==0&&(f=[h.grow(1-.0125*e),h.grow(.7-.0125*e),h.grow(.4-.0125*e)]);for(const r of f)r.grow(999).grow(997).layer(e,l,a,t);u.grow(999).flipDirs().grow(997).layer(e,l,1.5*a*s,t),e%2==0&&h.grow(c).grow(999).layer(e,l,2*a,t),e%5!=0&&19!==e||(0!==s&&h.erase(3*s,i),p.blend(t,!0,!1,!0))}p.ctx.restore()}layer(t,e,r,i){var n;p.ctx.lineWidth=N(t,0,24,e/25,e/30,!0),p.ctx.fillStyle=`rgb(${i._getRed()} ${i._getGreen()} ${i._getBlue()} / ${r}%)`,n=this.v,p.ctx.beginPath(),n.forEach((t,e)=>{0===e?p.ctx.moveTo(t.x,t.y):p.ctx.lineTo(t.x,t.y)}),p.ctx.closePath(),p.ctx.fill(),p.ctx.stroke()}erase(t,e){p.ctx.save();const r=~~(k(80,110)*N(t,0,1,2,3.5)),i=this.sizeX/1.3,n=this.sizeY/1.3,o=Math.min(this.sizeX,this.sizeY)*(1.4-d.fill.bleed_strength),s=.05*o,a=.4*o,{x:l,y:c}=this.midP;p.ctx.globalCompositeOperation="destination-out";const h=(5-N(e,80,100,.3,.7,!0))*t/255;p.ctx.fillStyle=`rgb(255 0 0 / ${h})`,p.ctx.lineWidth=0;for(let t=0;t<r;t++){const e=l+C(0,i),r=c+C(0,n),o=k(s,a);p.ctx.beginPath(),Ce(e,r,o),t%5!=0&&p.ctx.fill()}p.ctx.globalCompositeOperation="source-over",p.ctx.restore()}}pt.prototype.fill=function(t=!1,e,r,i,n,o){let s=Te();t&&(Ne(t,e),ze(r,o),Oe(i,n)),s.isActive&&(rt(),function(t){if(!d.fill.isActive||!d.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");Be=t;const e=[...t.vertices],r=~~(.25*e.length*T({1:5,2:10,3:60})),i=d.fill.bleed_strength,n=e.map((t,e)=>(e>r?1:.3)*k(.85,1.2)*i),o=L(0,e.length),s=[...e.slice(o),...e.slice(0,o)],a=function(t){if(t.length<8)return t.reduce((t,e)=>({x:t.x+e.x,y:t.y+e.y}),{x:0,y:0}).map(e=>e/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,i=0,n=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,i+=(e[t].x+e[t+1].x)*o,n+=(e[t].y+e[t+1].y)*o}return r*=.5,r?{x:i/(6*r),y:n/(6*r)}:{x:e[0].x,y:e[0].y}}(s);new Xe(s,n,a,[],!0).fill(d.fill.color,N(d.fill.opacity,0,255,0,1,!0),d.fill.texture_strength)}(this)),(t=>{d.fill={...t}})(s)},xt.prototype.fill=function(t,e,r){Te().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,N(d.fill.bleed_strength,0,.6,.3,.45,!0)),this.pol.fill())};const Ge=[];"undefined"!=typeof p5&&p5.registerAddon(function(t,e,r){r.postsetup=()=>p.blend(!1,!0),r.postdraw=()=>p.blend(!1,!0);const i=e.push,n=e.pop,o=e.randomSeed,s=e.noiseSeed;e.push=function(){i.call(this),rt(),Ge.push({fill:{...d.fill},stroke:{...d.stroke},hatch:{...d.hatch},field:{...d.field}})},e.pop=function(){n.call(this),function(){const t=Ge.pop();t&&(d.stroke={...t.stroke},d.field={...t.field},d.hatch={...t.hatch},d.fill={...t.fill})}()},e.randomSeed=function(t){o.call(this,t),(t=>{E=S(t);for(const t of A)t()})(t)},e.noiseSeed=function(t){s.call(this,t),(t=>{M=w(S(t))})(t)}}),t.Plot=xt,t.Polygon=pt,t.Position=it,t.add=ne,t.addField=dt,t.arc=function(t,e,r,i,n){const o=H(i),s=((H(n)-o)%360+360)%360;if(0===s)return;const a=new xt("curve"),l=Math.max(1,Math.ceil(s/90)),c=s/l,h=Math.PI*r*c/180;for(let t=0;t<l;t++)a.addSegment(o+t*c+90,h,1,!0);a.endPlot(o+s+90,1,!0);const u=t+r*X(o),f=e-r*G(o);a.draw(u,f,1)},t.beginShape=St,t.beginStroke=function(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);_t=[e,r],bt=new xt(t)},t.box=function(){return[...Qt.keys()]},t.circle=function(t,e,r,i=!1){const n=new xt("curve"),o=Math.PI*r,s=k(0,360),a=i?()=>1+.2*i*k():()=>1;for(let t=0;t<4;t++){const e=-90*t+s;n.addSegment(e*a(),o/2*a(),1,!0)}if(i){const t=i*L(-5,5);n.addSegment(s,Math.abs(t)*(Math.PI/180)*r,1,!0),n.endPlot(t+s,1,!0)}else n.endPlot(s,1,!0);const l=t-r*G(s),c=e-r*X(-s);n.show(l,c,1)},t.clip=function(t){g();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}}(ce());if(!e)throw new Error("brush.clip() cannot be used with a non-invertible transform.");d.stroke.clipWindow={bounds:ue(t),inverse:e}},t.endShape=Et,t.endStroke=function(t,e){if(!bt)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");bt.endPlot(t,e),bt.draw(_t[0],_t[1],1),bt=!1},t.field=gt,t.fill=Ne,t.fillBleed=ze,t.fillTexture=Oe,t.flowLine=function(t,e,r,i){if(!d.stroke.isActive||!d.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");rt(),ge(t,e,r),me($(i),!1)},t.hatch=ke,t.hatchArray=Ie,t.hatchStyle=function(t,e="black",r=1){d.hatch.hBrush={brush:t,color:e,weight:r}},t.instance=t=>{f=!0,i=t},t.line=Re,t.listFields=function(){return rt(),Array.from(ct.keys())},t.load=h,t.move=function(t,e,r){if(!bt)throw new Error("move() called without beginStroke(). Call beginStroke() first.");bt.addSegment(t,e,r)},t.noClip=function(){d.stroke.clipWindow=null},t.noField=function(){rt(),d.field.isActive=!1},t.noFill=function(){d.fill.isActive=!1},t.noHatch=function(){d.hatch.isActive=!1,d.hatch.hBrush=!1},t.noStroke=function(){d.stroke.isActive=!1},t.pick=oe,t.polygon=function(t){new pt(t).show()},t.rect=function(t,e,r,i,n="corner"){"center"===n&&(t-=r/2,e-=i/2),St(0),Rt(t,e),Rt(t+r,e),Rt(t+r,e+i),Rt(t,e+i),Et(!0)},t.refreshField=function(t=0){if(!d.field.isActive||!d.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=ct.get(d.field.current);e.field=ft(e,t)},t.scaleBrushes=function(t){for(const{param:e}of Qt.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)},t.set=le,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].");At(t,e).draw()},t.stroke=se,t.strokeWeight=ae,t.vertex=Rt,t.wRand=T,t.wiggle=function(t=1){gt("hand"),d.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={});
//# sourceMappingURL=p5.brush.js.map
diff --git a/dist/p5.brush.js.map b/dist/p5.brush.js.map
index 5dc3cab..967a88c 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/primitives.js","../src/core/polygon.js","../src/core/plot.js","../src/stroke/gl_draw.js","../src/stroke/stroke.js","../src/core/gl/utils.js","../src/hatch/hatch.js","../src/core/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// Section: 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\nconst Canvases = {}; // Stores canvas instances by ID\nexport let cID, Cwidth, Cheight, Instance, Renderer, Density; // Global canvas properties\n\n/**\n * Loads and initializes a canvas for the drawing system.\n * @param {string|boolean} [canvasID=false] - Optional ID of the canvas element to use.\n * If false, it uses the current window as the rendering context.\n */\nexport const load = (buffer = false) => {\n // Set renderer to specificed Buffer, Instance,, or Window\n Renderer =\n _isInstanced && !buffer\n ? Instance\n : !buffer\n ? window.self.p5.instance\n : buffer;\n\n // Check if Rendrer is webgl and throw error if it's not\n\n if (Renderer.webglVersion !== \"webgl2\") {\n throw new Error(\"p5.brush requires a WEBGL canvas\");\n }\n\n Cwidth = Renderer.width;\n Cheight = Renderer.height;\n\n _isReady = true;\n if (Renderer.loaded) Mix.load();\n};\n\nlet _isReady = false;\nlet _isInstanced = 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 _isInstanced = true;\n Instance = inst;\n};\n\n\n// =============================================================================\n// Section: Color Blending\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 * 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\nconst disable = false;\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 isBlendingGL: false,\n isWaterColor: false,\n cachedColor: new Object(),\n cachedColorGL: new Object(),\n masks: [],\n\n /**\n * Loads necessary resources and prepares the mask buffer and shader for colour blending.\n */\n load() {\n // Create Renderer masks\n if (!Renderer.loaded) {\n Renderer.mask = Renderer.createGraphics(Cwidth, Cheight, Renderer.P2D);\n Renderer.glMask = Renderer.createGraphics(\n Cwidth,\n Cheight,\n Renderer.WEBGL,\n );\n Renderer.loaded = true;\n Renderer.shaderProgram = Renderer.createShader(vertSrc, fragSrc);\n\n Density = Renderer.pixelDensity();\n\n this.mask = Renderer.mask;\n this.mask.pixelDensity(Density);\n this.mask.clear();\n this.mask.angleMode(Renderer.DEGREES);\n\n this.ctx = this.mask.drawingContext;\n\n this.glMask = Renderer.glMask;\n this.glMask.pixelDensity(Density);\n this.glMask.clear();\n this.glMask.angleMode(this.glMask.DEGREES);\n this.glMask.drawingContext.lineWidth = 0;\n // Link Matrix of GL mask to main Renderer\n this.glMask._renderer.uModelMatrix = Renderer._renderer.uModelMatrix;\n }\n },\n\n /**\n * Applies blending effects using the current color and mask.\n * @param {Color} _color - Color to blend.\n * @param {boolean} _isLast - If this is the final blend operation.\n * @param {boolean} _isImg - If blending an image.\n * @param {boolean} _isFillLayer - If this is a special case.\n */\n blend(_color = false, _isLast = false) {\n isMixReady();\n\n const mask = this.isBrush ? this.glMask : this.mask;\n const no_mask = this.isBrush ? this.mask : this.glMask;\n\n // Perf gains are minimal but let's keep it for now\n if (disable) {\n if (_isLast && mask.isDrawn) {\n Renderer.push();\n Renderer.translate(0, 0);\n Renderer.image(mask, 0, 0, Cwidth, Cheight);\n Renderer.pop();\n mask.isDrawn = false;\n }\n return;\n }\n\n // Initialize blending if not already active\n if (!this.isBlending && _color) {\n this.isBlending = true;\n this.cachedColor = _color._array;\n // Force p5 to bind its internal render target for glMask,\n // so the first glDraw() writes to the correct framebuffer.\n this.glMask.clear();\n }\n\n if (_isLast || this.cachedColor[0] !== _color._array[0] || this.cachedColor[1] !== _color._array[1] || this.cachedColor[2] !== _color._array[2] || this.cachedColor[3] !== _color._array[3]) {\n if (this.justChanged) {\n this.applyShader(no_mask);\n this.justChanged = false;\n }\n if (this.isBlending) {\n this.applyShader(mask);\n }\n this.cachedColor = _color._array;\n if (_isLast) this.isBlending = false;\n }\n },\n\n applyShader(mask) {\n let shader = Renderer.shaderProgram;\n const gl = Renderer.drawingContext;\n\n // Disable depth test for this compositing draw so the fullscreen rect\n // does not write Z=0 into the depth buffer — which would cause any\n // subsequent p5 geometry drawn at the same depth to fail depth testing\n // and become invisible.\n const hadDepthTest = gl.getParameter(gl.DEPTH_TEST);\n gl.disable(gl.DEPTH_TEST);\n\n Renderer.push();\n Renderer.translate(0, 0);\n\n // Use the blend shader for rendering\n Renderer.shader(shader);\n\n // Set shader uniforms\n shader.setUniform(\"u_source\", Renderer._renderer);\n shader.setUniform(\"u_isBrush\", this.isBrush);\n shader.setUniform(\"u_mask\", mask);\n shader.setUniform(\"u_color\", this.cachedColor);\n\n // Draw a rectangle covering the whole canvas to apply the shader\n Renderer.fill(0, 0, 0, 0);\n Renderer.noStroke();\n Renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);\n\n // Finish and clear mask\n Renderer.pop();\n Renderer.resetShader();\n\n // Restore depth test state\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n\n mask.clear();\n mask.isDrawn = false;\n },\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());\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};\n\n/**\n * Simplex‐noise 2D function.\n * @type {function(number, number): number}\n */\nexport let noise = 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};\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);\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 * Generates a random number or picks a random array element.\n * @param {number|Array} [minOrArr=0]\n * @param {number} [max=1]\n * @returns {number}\n */\nexport function random(e = 0, r = 1) {\n if (Array.isArray(e)) return rArray(e);\n if (arguments.length === 1) return rng() * e;\n return rr(e, r);\n}\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);\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 // Only if Renderer.angleMode() is set to radians\n if (Renderer.angleMode() === Renderer.RADIANS || isRad) {\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// 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 { randInt, noise, rr, sin, cos, map } 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 angle in radians, or 0 if the position is not in the flow field or if the flow field is not 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} _length - The length to move along the field.\n * @param {number} _dir - The direction of movement.\n * @param {number} _step_length - The length of each step.\n */\n moveTo(_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;\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\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 = currentField.gen(t, genField());\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 = entry.gen(0, genField());\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 */\nexport function addField(name, funct) {\n list.set(name, { gen: funct, field: null });\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 = rr(0.2, 0.8),\n ba = randInt(5, 10);\n return fillField(field, (c, r) => {\n const angle = 0.5 * ba * sin(bs * r * c + randInt(15, 25));\n return 0.2 * angle * cos(t) + noise(c, r) * ba * 0.7;\n });\n });\n // Smooth large-scale noise curves\n addField(\"curved\", (t, field) => {\n let ar = randInt(-10, 10);\n if (randInt(0, 100) % 2 == 0) ar *= -1;\n return fillField(\n field,\n (c, r) =>\n 3 * map(noise(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 = randInt(-30, -15) + Math.abs(44 * sin(t));\n if (randInt(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 = randInt(10, 15) + 5 * sin(t),\n cr = randInt(3, 6) + 3 * cos(t),\n ba = randInt(20, 35);\n return fillField(\n field,\n (c, r) => sin(sr * c) * ba * cos(r * cr) + randInt(-3, 3),\n );\n });\n // Dense oscillation from row×col product\n addField(\"seabed\", (t, field) => {\n const bs = rr(0.4, 0.8),\n ba = randInt(18, 26);\n return fillField(\n field,\n (c, r) => 1.1 * ba * sin(bs * r * c + randInt(15, 20)) * cos(t),\n );\n });\n // Radial vortex — angles spiral around the field centre\n addField(\"spiral\", (_t, field) => {\n const n = randInt(5, 10);\n const dir = randInt(0, 2) * 2 - 1;\n const offset = randInt(65, 80); // <90 = inward spiral\n const attractors = Array.from({ length: n }, () => ({\n x: rr(0.1, 0.9) * num_columns,\n y: rr(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 = randInt(3, 8),\n amp = randInt(25, 45);\n return fillField(field, (c, _r) => sin(c * freq) * amp);\n });\n}\n","import {\n rr,\n randInt,\n sin,\n cos,\n toDegrees,\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 = rr(0, 360);\n const randomFactor = r ? () => 1 + r * 0.2 * rr() : () => 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 * randInt(-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 - Radian start angle.\n * @param {number} end - Radian end angle.\n */\nexport function arc(x, y, radius, start, end) {\n const p = new Plot(\"curve\");\n const startAngle = 270 - toDegrees(start);\n const endAngle = 270 - toDegrees(end);\n const arcAngle = toDegrees(end - start);\n const arcLength = (Math.PI * radius * arcAngle) / 180;\n\n p.addSegment(startAngle, arcLength, 1, true);\n p.endPlot(endAngle, 1, true);\n\n const startX = x + radius * cos(-startAngle - 90);\n const startY = y + radius * sin(-startAngle - 90);\n p.draw(startX, startY, 1);\n}\n\n// Variables for managing paths and strokes\nlet _current;\nlet _curvature;\n\nclass SubPath {\n constructor() {\n this.isClosed = false;\n this.curvature = _curvature;\n this.vert = [];\n }\n /**\n * Adds a vertex to this subpath.\n * @param {number} x\n * @param {number} y\n * @param {number} pressure\n */\n vertex(x, y, pressure) {\n this.vert.push([x, y, pressure]);\n }\n /**\n * Renders the subpath by creating a spline from its vertices.\n */\n show() {\n let plot = _createSpline(this.vert, this.curvature, this.isClosed);\n plot.show();\n }\n}\n\n/**\n * Begins a new path with a specified curvature.\n * @param {number} [curvature=0] - Curvature from 0 to 1.\n */\nexport function beginShape(curvature = 0) {\n _curvature = constrain(curvature, 0, 1);\n _current = new SubPath();\n}\n\n/**\n * Adds a line segment from the current point to the given coordinates.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} [pressure=1] - Pressure value.\n */\nexport function vertex(x, y, pressure = 1) {\n if (!_current) {\n throw new Error(\n \"vertex() called outside of beginShape()/endShape(). Call beginShape() first.\",\n );\n }\n _current.vertex(x, y, pressure);\n}\n\n/**\n * Ends the current path and renders all subpaths.\n */\nexport function endShape(close = false) {\n if (!_current) {\n throw new Error(\n \"endShape() called without beginShape(). Call beginShape() first.\",\n );\n }\n if (_current.vert.length < 2) {\n throw new Error(\n \"endShape() requires at least 2 vertices. Add more with vertex().\",\n );\n }\n if (close) {\n _current.vertex(..._current.vert[0]);\n _current.isClosed = true;\n }\n _current.show();\n _current = false;\n}\n\nlet _strokeArray, _strokeOrigin;\n\n/**\n * Begins a new stroke with a given type and starting position.\n * @param {string} type - Stroke type.\n * @param {number} x - Starting x.\n * @param {number} y - Starting y.\n */\nexport function beginStroke(type, x, y) {\n if (type !== \"curve\" && type !== \"segments\") {\n throw new Error(\n `beginStroke() type must be \"curve\" or \"segments\", got \"${type}\".`,\n );\n }\n _strokeOrigin = [x, y];\n _strokeArray = new Plot(type);\n}\n\n/**\n * Adds a segment to the stroke.\n * @param {number} angle - Segment angle.\n * @param {number} length - Segment length.\n * @param {number} pressure - Segment pressure.\n */\nexport function move(angle, length, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"move() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.addSegment(angle, length, pressure);\n}\n\n/**\n * Completes and renders the stroke.\n * @param {number} angle - End angle.\n * @param {number} pressure - End pressure.\n */\nexport function endStroke(angle, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"endStroke() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.endPlot(angle, pressure);\n _strokeArray.draw(_strokeOrigin[0], _strokeOrigin[1], 1);\n _strokeArray = false;\n}\n\n/**\n * Creates and draws a spline curve from an array of points.\n * @param {Array<Array<number>>} array_points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature from 0 to 1.\n */\nexport function spline(_array_points, _curvature = 0.5) {\n if (!_array_points || _array_points.length < 2) {\n throw new Error(\n \"spline() requires at least 2 points. Each point should be [x, y, pressure].\",\n );\n }\n let p = _createSpline(_array_points, _curvature);\n p.draw();\n}\n\n/**\n * Creates a new Plot object representing a spline curve.\n *\n * For curved segments (curvature > 0) with at least 3 points available,\n * the function either treats segments as straight (if their angles match)\n * or calculates control points to compute a circular arc.\n *\n * If no curvature is specified, a simple straight segment is used.\n *\n * @param {Array<Array<number>>} points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature value between 0 and 1.\n * @param {boolean} [close=false] - Whether to close the spline.\n * @returns {Plot} - The generated Plot object.\n */\nfunction _createSpline(points, curvature = 0.5, close = false) {\n const plotType = curvature === 0 ? \"segments\" : \"curve\";\n const p = new Plot(plotType);\n const PI2 = Math.PI * 2;\n\n // If closing the spline, add the second point to the end\n if (close && curvature !== 0) {\n points.push(points[1]);\n }\n\n if (points && points.length > 0) {\n let done = 0; // Tracks excess length from previous segment\n let pep, tep, pep2; // Variables used for initial calibration\n\n for (let i = 0; i < points.length - 1; i++) {\n // For curved segments (if curvature > 0 and there is at least 3 points ahead)\n if (curvature > 0 && i < points.length - 2) {\n const p1 = points[i];\n const p2 = points[i + 1];\n const p3 = points[i + 2];\n\n const d1 = dist(p1[0], p1[1], p2[0], p2[1]);\n const d2 = dist(p2[0], p2[1], p3[0], p3[1]);\n const a1 = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n const a2 = calcAngle(p2[0], p2[1], p3[0], p3[1]);\n\n // Compute the adjustment length based on curvature\n const curvAdjust = curvature * Math.min(d1, d2, 0.5 * Math.min(d1, d2));\n const dmax = Math.max(d1, d2);\n const s1 = d1 - curvAdjust;\n const s2 = d2 - curvAdjust;\n\n if (Math.floor(a1) === Math.floor(a2)) {\n // If angles are nearly the same, treat as a straight segment\n const temp = close ? (i === 0 ? 0 : d1 - done) : d1 - done;\n const temp2 = close ? (i === 0 ? 0 : d2 - pep2) : d2;\n\n p.addSegment(a1, temp, p1[2], true);\n if (i === points.length - 3) {\n p.addSegment(a2, temp2, p2[2], true);\n }\n\n done = 0;\n if (i === 0) {\n pep = d1;\n pep2 = curvAdjust;\n tep = points[1];\n done = 0;\n }\n } else {\n // For a curved segment, compute control points and arc segment details\n const point1 = {\n x: p2[0] - curvAdjust * cos(-a1),\n y: p2[1] - curvAdjust * sin(-a1),\n };\n const point2 = {\n x: point1.x + dmax * cos(-a1 + 90),\n y: point1.y + dmax * sin(-a1 + 90),\n };\n const point3 = {\n x: p2[0] + curvAdjust * cos(-a2),\n y: p2[1] + curvAdjust * sin(-a2),\n };\n const point4 = {\n x: point3.x + dmax * cos(-a2 + 90),\n y: point3.y + dmax * sin(-a2 + 90),\n };\n\n const intPt = intersectLines(point1, point2, point3, point4, true);\n const radius = dist(point1.x, point1.y, intPt.x, intPt.y);\n const halfDist = dist(point1.x, point1.y, point3.x, point3.y) / 2;\n const arcAngle = 2 * Math.asin(halfDist / radius) * (180 / Math.PI);\n const arcLength = (PI2 * radius * arcAngle) / 360;\n\n const temp = close ? (i === 0 ? 0 : s1 - done) : s1 - done;\n const temp2 =\n i === points.length - 3 ? (close ? pep - curvAdjust : s2) : 0;\n\n p.addSegment(a1, temp, p1[2], true);\n p.addSegment(a1, isNaN(arcLength) ? 0 : arcLength, p1[2], true);\n p.addSegment(a2, temp2, p2[2], true);\n\n done = curvAdjust;\n if (i === 0) {\n pep = s1;\n pep2 = curvAdjust;\n tep = [point1.x, point1.y];\n }\n }\n\n if (i === points.length - 3) {\n p.endPlot(a2, p2[2], true);\n }\n } else if (curvature === 0) {\n // If no curvature, add a simple straight segment\n const p1 = points[i];\n const p2 = points[i + 1];\n const d = dist(p1[0], p1[1], p2[0], p2[1]);\n const a = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n\n p.addSegment(a, d, p2[2], true);\n if (i === points.length - 2) {\n p.endPlot(a, 1, true);\n }\n }\n }\n\n p.origin = close && curvature !== 0 ? tep : points[0];\n }\n\n return p;\n}\n","import { State } from \"./color.js\";\nimport { intersectLines } from \"./utils.js\";\n\n// =============================================================================\n// Section: Polygon Class\n// =============================================================================\n\n/**\n * Represents a polygon with a set of vertices and provides methods for\n * intersection, drawing, filling, and hatching.\n */\nexport class Polygon {\n /**\n * Constructs the Polygon object from an array of points.\n * @param {Array} pointsArray - An array of points, where each point is an array of two numbers [x, y].\n * @param {boolean} [useRawVertices=false] - If true, uses the raw array as vertices.\n */\n constructor(pointsArray, useRawVertices = false) {\n this.a = pointsArray;\n this.vertices = useRawVertices\n ? pointsArray\n : pointsArray.map(([x, y]) => ({ x, y }));\n this.sides = this.vertices.map((v, i, arr) => [\n v,\n arr[(i + 1) % arr.length],\n ]);\n this._intersectionCache = {}; // Cache for intersection results\n }\n\n /**\n * Intersects a given line with the polygon, returning all intersection points.\n * @param {Object} line - The line to intersect with the polygon, having two properties 'point1' and 'point2'.\n * @returns {Array} An array of intersection points (each with 'x' and 'y' properties) or an empty array if no intersections.\n */\n intersect(line) {\n // Check if the result has been cached\n const cacheKey = `${line.point1.x},${line.point1.y}-${line.point2.x},${line.point2.y}`;\n if (this._intersectionCache[cacheKey]) {\n return this._intersectionCache[cacheKey];\n }\n const points = [];\n for (const [start, end] of this.sides) {\n const intersection = intersectLines(line.point1, line.point2, start, end);\n if (intersection) points.push(intersection);\n }\n this._intersectionCache[cacheKey] = points; // Cache the result\n return points;\n }\n\n /**\n * Displays the polygon with optional stroke, hatch, and fill effects.\n */\n show() {\n if (State.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, rr } 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 = Math.max(this.segments[idx] * _side * rr(0.7, 1.3), 10);\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","// =============================================================================\n// Module: GL Draw\n// =============================================================================\n/**\n * The GL Draw module provides functions for rendering shapes (circles and squares)\n * using WebGL2. It initializes the WebGL context and shader programs, prepares buffers,\n * and implements drawing routines based on queued drawing primitives. The module uses\n * an orthographic projection to map canvas coordinates to clip space and supports adjustable\n * blending for translucent effects.\n */\n\nimport {\n Mix,\n Cwidth,\n Cheight,\n isMixReady,\n Density,\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\";\n\n// =============================================================================\n// Section: Initialization and Setup\n// =============================================================================\n\n// Module state\nlet isLoaded = false,\n gl,\n projMatrix,\n vao,\n buf,\n program;\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\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}\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\n\n/**\n * Initializes WebGL objects if not done already.\n */\nexport function isReady() {\n if (!isLoaded) {\n isMixReady();\n gl = Mix.glMask.drawingContext;\n projMatrix = 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\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\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 isLoaded = true;\n }\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 - Cwidth / 2;\n const py = y - Cheight / 2;\n\n const offset = circleCount * 4;\n circleData[offset] = _ma * px + _mc * py + _mx + Cwidth / 2;\n circleData[offset + 1] = _mb * px + _md * py + _my + Cheight / 2;\n // Scale the diameter by the matrix's scale factor (length of the transformed x-axis)\n circleData[offset + 2] =\n (Density * diameter * Math.sqrt(_ma * _ma + _mb * _mb)) / 2;\n circleData[offset + 3] = alpha / 255;\n circleCount++;\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\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, projMatrix);\n gl.drawArrays(gl.POINTS, 0, circleCount);\n\n gl.bindVertexArray(null);\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 Mix.glMask._renderer._curShader = null;\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 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} 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 { isReady, glDraw, circle, snapshotMatrix } 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();\n\nlet Mask = null;\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 * { type, min_max, curve } — old internal format, passed through unchanged\n */\nfunction normalizePressure(p) {\n if (!p || (typeof p === \"object\" && !Array.isArray(p))) return p;\n if (typeof p === \"function\")\n return { type: \"custom\", min_max: [0, 1], curve: p };\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 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 // 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 === \"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 params.tip = () => {\n Mask.image(\n T.tips.get(current.p.image.src),\n -current.p.weight / 2,\n -current.p.weight / 2,\n current.p.weight,\n current.p.weight,\n );\n };\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\n/**\n * Defines a clipping region for strokes.\n * @param {number[]} region - Array as [x1, y1, x2, y2] defining the clipping region.\n */\nexport function clip(region) {\n State.stroke.clipWindow = region;\n}\n\n/**\n * Disables the clipping region.\n */\nexport function noClip() {\n State.stroke.clipWindow = null;\n}\n\n/**\n * Sets the brush density by scaling standard brushes.\n * @param {number} d - Density factor.\n */\nexport function setDensity(d) {\n scaleBrushes(d);\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 {boolean} flow - Flag for vector-field following.\n * @param {Object|boolean} plot - Plot object or false.\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/**\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.moveTo(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 Mask = Mix.glMask;\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 current.cp = pressure.type !== \"custom\" ? rr(3, 3.5) : rr(-0.2, 0.2);\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 if (isInsideClippingArea()) Mix.blend(State.stroke.color);\n if (Mix.isBrush === false) Mix.justChanged = true;\n Mix.isBrush = true;\n\n // Set additional state values\n current.alpha = calculateAlpha();\n markerTip();\n}\n\n/**\n * Restores drawing state after completing a stroke.\n */\nfunction restoreState() {\n glDraw();\n markerTip();\n}\n\n/**\n * Renders the brush tip based on current pressure and position.\n * @param {number} [customPressure=false] - Optional custom pressure.\n */\nfunction tip(customPressure = false) {\n if (!isInsideClippingArea()) return;\n let pressure = customPressure || calculatePressure();\n\n let 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\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 drawTip(pressure * lineNoise, current.alpha);\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 return current.p.pressure.type === \"custom\"\n ? map(\n current.p.pressure.curve(_position.plotted / _length) + current.cp,\n 0,\n 1,\n current.min,\n current.max,\n true,\n )\n : gauss();\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 * @returns {boolean} True if inside clipping area; false otherwise.\n */\nfunction isInsideClippingArea() {\n if (State.stroke.clipWindow)\n return (\n _position.x >= State.stroke.clipWindow[0] &&\n _position.x <= State.stroke.clipWindow[2] &&\n _position.y >= State.stroke.clipWindow[1] &&\n _position.y <= State.stroke.clipWindow[3]\n );\n else {\n let w = Cwidth,\n h = Cheight,\n o = Cwidth * 0.05;\n let x = _position.x + Matrix.x();\n let y = _position.y + Matrix.y();\n return x >= -o && x <= w + o && y >= -o && y <= h + o;\n }\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\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,\n );\n}\n\n/**\n * Draws a custom or image-based brush tip.\n * @param {number} pressure - Current pressure.\n * @param {number} alpha - Alpha (opacity) for drawing.\n * @param {boolean} [vibrate=true] - Whether to apply vibration.\n */\nfunction drawTip(pressure, alpha, vibrate = true) {\n Mix.glMask.isDrawn = true;\n Mask.push();\n Mask.noStroke();\n let color = State.stroke.color;\n color.setAlpha(alpha);\n Mask.fill(State.stroke.color);\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 Mask.translate(_position.x + rx - Cwidth, _position.y + ry - Cheight);\n adjustSizeAndRotation(State.stroke.weight * pressure, alpha);\n current.p.tip(Mask);\n Mask.pop();\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 if (rr(0, current.p.grain * pressure) > 0.4) {\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 circle(\n _position.x + dx,\n _position.y + dy,\n pressure *\n pressure *\n current.p.weight *\n rr(0.85, 1.15) *\n State.stroke.weight,\n Math.max(0.9, pressure) * current.alpha * rr(0.75, 1.1),\n );\n }\n}\n\n/**\n * Adjusts the size and rotation of the brush tip before rendering.\n * @param {number} pressure - Pressure-based scaling factor.\n * @param {number} alpha - Opacity value.\n */\nfunction adjustSizeAndRotation(pressure, alpha) {\n Mask.scale(pressure);\n if (current.p.type === \"image\") {\n Mask.tint(255, 0, 0, alpha / 2);\n }\n let angle = 0;\n if (current.p.rotate === \"random\") angle = randInt(0, 360);\n else if (current.p.rotate === \"natural\") {\n angle =\n (_plot ? -_plot.angle(_position.plotted) : -_dir) + _position.angle();\n }\n Mask.rotate(angle);\n}\n\n/**\n * Draws the marker tip with a blend effect.\n */\nfunction markerTip() {\n if (isInsideClippingArea()) {\n let pressure = calculatePressure();\n let alpha = calculateAlpha(pressure);\n if (current.p.type === \"marker\") {\n for (let s = 1; s < 10; s++) {\n drawMarker((pressure * s) / 10, false, alpha * 5);\n }\n glDraw();\n } else if (current.p.type === \"custom\" || current.p.type === \"image\") {\n for (let s = 1; s < 5; s++) {\n drawTip((pressure * s) / 5, alpha, false);\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 (in radians, anticlockwise from the x-axis).\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, vibration, definition, quality, 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];\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.12,\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 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 p5img = Renderer.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.src = src;\n }),\n ),\n );\n },\n};\n\n/**\n * Loads all registered image tips. Must be awaited before setup/draw.\n * @returns {Promise}\n *\n * @example\n * // In your sketch:\n * await brush.preload();\n */\nexport async function preload() {\n await T.load();\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// Module: Hatch\n// =============================================================================\n/**\n * The Hatch module contains functions and classes dedicated to applying\n * hatch patterns over shapes and polygons. It enables the simulation of\n * cross-hatching and shading effects by drawing parallel lines or strokes\n * across a geometry. The module supports adjustable spacing, angle, and\n * optional style parameters (such as randomness, continuity, and gradient),\n * giving an artistic representation similar to hand-drawn hatching techniques.\n *\n * The implementation allows for hatching to be applied either to a Polygon\n * directly or via a Plot, extending the drawing capabilities with layered,\n * stylized textures.\n */\n\nimport { State } from \"../core/color.js\";\nimport { toDegrees, map, cos, sin, 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 and Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Global hatch state settings.\n */\nState.hatch = {\n isActive: false,\n dist: 5,\n angle: 45,\n options: {},\n hBrush: false,\n};\n\n/**\n * Returns a shallow copy of the current hatch state.\n * @returns {object} The current hatch state.\n */\nexport function HatchState() {\n return { ...State.hatch };\n}\n\n/**\n * Updates the global hatch state.\n * @param {object} state - The new hatch state.\n */\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Style Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Activates hatching for subsequent geometries.\n *\n * @param {number} dist - The distance between hatching lines.\n * @param {number} angle - The angle (in degrees) at which hatching lines are drawn.\n * @param {object} options - Optional parameters to affect the hatching style:\n * - rand: Number value to introduce randomness.\n * - continuous: Boolean to connect adjacent lines.\n * - gradient: Number to gradually change spacing.\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 = angle;\n s.options = options;\n}\n\n/**\n * Sets the hatch brush style for subsequent hatching.\n *\n * @param {string} brush - The brush name.\n * @param {string|Color} color - The brush color.\n * @param {number} weight - The brush weight (size).\n */\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\n/**\n * Disables hatching.\n */\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fill Manager Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a hatching pattern over the given polygon(s).\n *\n * @param {Polygon|Polygon[]} polygons - A polygon or an array of polygons.\n */\nexport function createHatch(polygons) {\n let dist = State.hatch.dist;\n let angle = toDegrees(State.hatch.angle) % 180; // normalize to [0, 180)\n let options = State.hatch.options;\n\n // Save current stroke state\n let save = BrushState();\n // If a hatch brush is set, override with those parameters.\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n\n // Compute overall bounding box for all polygons.\n if (!Array.isArray(polygons)) polygons = [polygons];\n const overallBB = computeOverallBoundingBox(polygons);\n\n // Build a bounding polygon based on the overall bounding box.\n let ventana = new Polygon([\n [overallBB.minX, overallBB.minY],\n [overallBB.maxX, overallBB.minY],\n [overallBB.maxX, overallBB.maxY],\n [overallBB.minX, overallBB.maxY],\n ]);\n\n // Determine starting y coordinate based on angle.\n let startY = angle <= 90 && angle >= 0 ? overallBB.minY : overallBB.maxY;\n let gradient = options.gradient\n ? map(options.gradient, 0, 1, 1, 1.1, true)\n : 1;\n let dots = [];\n let i = 0;\n let dist1 = dist;\n\n // Function to generate a line for index i.\n let linea = (i) => {\n return {\n point1: {\n x: overallBB.minX + dist1 * i * cos(-angle + 90),\n y: startY + dist1 * i * sin(-angle + 90),\n },\n point2: {\n x: overallBB.minX + dist1 * i * cos(-angle + 90) + cos(-angle),\n y: startY + dist1 * i * sin(-angle + 90) + sin(-angle),\n },\n };\n };\n\n // Generate lines and calculate intersections with polygons\n // Loop through the lines based on the distance and angle to calculate intersections with the polygons\n // The loop continues until a line does not intersect with the bounding window polygon\n // Each iteration accounts for the gradient effect by adjusting the distance between lines\n while (ventana.intersect(linea(i)).length > 0) {\n let tempArray = [];\n for (let p of polygons) {\n tempArray.push(p.intersect(linea(i)));\n }\n dots[i] = tempArray\n .flat()\n .sort((a, b) => (a.x === b.x ? a.y - b.y : a.x - b.x));\n dist1 *= gradient;\n i++;\n }\n\n // Filter out empty intersection sets.\n let gdots = dots.filter((dd) => typeof dd[0] !== \"undefined\");\n\n // Draw the hatching lines using the calculated intersections\n // If the 'rand' option is enabled, add randomness to the start and end points of the lines\n // If the 'continuous' option is set, connect the end of one line to the start of the next\n let r = options.rand || 0;\n for (let j = 0; j < gdots.length; j++) {\n let dd = gdots[j];\n let continuousLine = j > 0 && options.continuous;\n for (let i = 0; i < dd.length - 1; i += 2) {\n if (r !== 0) {\n dd[i].x += r * dist * rr(-1, 1);\n dd[i].y += r * dist * rr(-1, 1);\n dd[i + 1].x += r * dist * rr(-1, 1);\n dd[i + 1].y += r * dist * rr(-1, 1);\n }\n line(dd[i].x, dd[i].y, dd[i + 1].x, dd[i + 1].y);\n if (continuousLine) {\n line(gdots[j - 1][1].x, gdots[j - 1][1].y, dd[i].x, dd[i].y);\n }\n }\n }\n\n // Restore previous brush state.\n BrushSetState(save);\n}\n\n/**\n * Computes the bounding box for a single polygon.\n * @param {Polygon} polygon - The polygon to evaluate.\n * @returns {object} The bounding box as {minX, minY, maxX, maxY}.\n */\nfunction computeBoundingBoxForPolygon(polygon) {\n if (polygon._boundingBox) return polygon._boundingBox;\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n for (let i = 0; i < polygon.a.length; i++) {\n const [x, y] = polygon.a[i];\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n }\n polygon._boundingBox = { minX, minY, maxX, maxY };\n return polygon._boundingBox;\n}\n\n/**\n * Computes an overall bounding box for an array of polygons.\n * @param {Array} polygons - Array of Polygon objects.\n * @returns {object} The overall bounding box {minX, minY, maxX, maxY}.\n */\nfunction computeOverallBoundingBox(polygons) {\n let overall = {\n minX: Infinity,\n minY: Infinity,\n maxX: -Infinity,\n maxY: -Infinity,\n };\n for (let poly of polygons) {\n const bb = computeBoundingBoxForPolygon(poly);\n overall.minX = Math.min(overall.minX, bb.minX);\n overall.minY = Math.min(overall.minY, bb.minY);\n overall.maxX = Math.max(overall.maxX, bb.maxX);\n overall.maxY = Math.max(overall.maxY, bb.maxY);\n }\n return overall;\n}\n\n// ---------------------------------------------------------------------------\n// Extend Polygon and Plot Prototypes\n// ---------------------------------------------------------------------------\n\n/**\n * Adds a hatch effect to the polygon.\n *\n * If a distance is provided, activates hatching with the given parameters.\n * Then, if hatch is active, applies the hatching pattern.\n *\n * @param {number} [_dist] - The distance between hatch lines.\n * @param {number} _angle - The angle (in degrees) for hatching.\n * @param {object} _options - Optional hatch options.\n */\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (state.isActive) {\n createHatch(this);\n }\n HatchSetState(state);\n};\n\n/**\n * Applies hatching to a plot.\n *\n * If hatching is active, generates a polygon from the plot and applies hatch.\n *\n * @param {number} x - The x-coordinate to draw at.\n * @param {number} y - The y-coordinate to draw at.\n * @param {number} scale - Scaling factor.\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 \"./color.js\";\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 Mix.ctx.beginPath();\n vertices.forEach((v, i) => {\n if (i === 0) Mix.ctx.moveTo(v.x, v.y);\n else Mix.ctx.lineTo(v.x, v.y);\n });\n Mix.ctx.closePath();\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 radius = d / 2;\n Mix.ctx.moveTo(x + radius, y);\n Mix.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 { Renderer, Mix, State, Cwidth, Cheight, Density } from \"../core/color.js\";\nimport { drawPolygon, circle } from \"../core/mask.js\";\nimport {\n constrain,\n weightedRand,\n rr,\n map,\n randInt,\n gaussian,\n rArray,\n rotate,\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/**\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 _gaussians = [[], []]; // [a, b]\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 < 8) {\n // Simple average for small polygons\n return pts\n .reduce((c, p) => ({ x: c.x + p.x, y: c.y + p.y }), { x: 0, y: 0 })\n .map((v) => v / 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\n // Map vertices\n const fluid = ~~(v.length * 0.25 * weightedRand({ 1: 5, 2: 10, 3: 60 }));\n const strength = State.fill.bleed_strength;\n\n // Create bleed modifiers\n const modifiers = v.map(\n (_, i) => (i > fluid ? 1 : 0.3) * rr(0.85, 1.2) * strength,\n );\n\n // Randomize starting point\n const shift = randInt(0, v.length);\n const shifted = [...v.slice(shift), ...v.slice(0, shift)];\n\n // Calculate center and create FillPolygon\n const center = _center(shifted);\n 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 // Clone and splice\n const v = [...this.v],\n m = [...this.m],\n dir = [...this.dir];\n v.splice(s, n);\n m.splice(s, n);\n dir.splice(s, n);\n\n return { v, m, dir };\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 // Get trimmed vertices\n const { v: tr_v, m: tr_m, dir: tr_dir } = this.trim(f);\n const len = tr_v.length;\n\n // Pre-allocate arrays for better performance\n const newVerts = [],\n newMods = [],\n newDirs = [];\n\n // Determine bleed direction\n const bleedDirDeg = State.fill.direction === \"out\" ? -90 : 90;\n\n // Process vertices\n let idx = 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 // compute two gaussians if necessary\n if (_gaussians[0].length < len * 1.5) {\n _gaussians[0].push(gaussian(0.5, 0.2));\n _gaussians[1].push(gaussian(0, 0.02));\n }\n\n const cv = tr_v[i];\n const nv = i + 1 < len ? tr_v[i + 1] : tr_v[0];\n\n // Use existing modifier or calculate new one\n if (f < 997) mod = tr_m[i];\n\n // Calculate rotation\n const rotDeg = (tr_dir[i] ? bleedDirDeg : -bleedDirDeg) + rr(-1, 1) * 5;\n const sideX = nv.x - cv.x;\n const sideY = nv.y - cv.y;\n const { x: dirX, y: dirY } = rotate(0, 0, sideX, sideY, rotDeg);\n\n // pick a random point along the edge\n const t = 0.5;\n // compute outward distance\n const d = rArray(_gaussians[0]) * rr(0.65, 1.35) * mod;\n\n // first vertex: stay at cv\n newVerts[idx] = cv;\n newMods[idx] = tr_m[i];\n newDirs[idx++] = tr_dir[i];\n\n // second vertex: offset by lerp + outward push\n newVerts[idx] = {\n x: cv.x + sideX * t + dirX * d,\n y: cv.y + sideY * t + dirY * d,\n };\n newMods[idx] = tr_m[i] + rArray(_gaussians[1]);\n newDirs[idx++] = tr_dir[i];\n }\n return new FillPoly(\n newVerts,\n newMods,\n this.midP,\n newDirs,\n false,\n this.sizeX,\n this.sizeY,\n );\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 // Precalculate stuff\n const numLayers = 20;\n const texture = tex * 3;\n const int = 2 * intensity * (1 + tex / 2);\n\n // Perform initial setup only once\n Mix.blend(color);\n Mix.justChanged = true;\n Mix.isBrush = false;\n\n Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * Matrix.a(), Density * Matrix.b(),\n Density * Matrix.c(), 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\n // Create initial polygon\n let pol = this.grow();\n let pols;\n\n for (let i = 0; i < numLayers; i++) {\n // Grow polygon every 4 layers\n if (i % 4 === 0) pol = pol.grow();\n\n // Create variant polygons\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 // Draw layers\n for (const p of pols) p.grow(999).grow(997).layer(i, size, int, color);\n if (i % 2 === 0)\n pol\n .grow(darker)\n .grow(999)\n .layer(i, size, int * 2, color);\n\n // Apply texture and blend periodically\n if (i % 5 === 0 || i === numLayers - 1) {\n if (texture !== 0) pol.erase(texture * 3, intensity);\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 Mix.ctx.fillStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${int}%)`;\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 // Optimize by pre-calculating values\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.4 - State.fill.bleed_strength);\n const minSizeFactor = 0.05 * minSize;\n const maxSizeFactor = 0.4 * minSize;\n const { x: midX, y: midY } = this.midP;\n\n // Set up erase mode\n Mix.ctx.globalCompositeOperation = \"destination-out\";\n\n // Calculate transparency\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 // Draw erase circles\n for (let i = 0; i < numCircles; i++) {\n const x = midX + gaussian(0, halfSizeX);\n const y = midY + gaussian(0, halfSizeY);\n const size = rr(minSizeFactor, maxSizeFactor);\n\n Mix.ctx.beginPath();\n circle(x, y, size);\n if (i % 5 !== 0) Mix.ctx.fill();\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 map(State.fill.bleed_strength, 0, 0.6, 0.3, 0.45, 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 * @version 2.0.0-alpha\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\n *\n * // Fill textures:\n * brush.noStroke();\n * brush.fill('#FF0000', 90); // Set fill color to red and opacity to 90\n * brush.bleed(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-2024 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 preload,\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 { Mix } 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.postsetup = () => Mix.blend(false, true);\n lifecycles.postdraw = () => Mix.blend(false, true);\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","load","buffer","_isInstanced","window","self","p5","instance","webglVersion","Error","width","height","_isReady","loaded","Mix","isCanvasReady","State","isMixReady","isBlending","isBlendingGL","isWaterColor","cachedColor","Object","cachedColorGL","masks","mask","createGraphics","P2D","glMask","WEBGL","shaderProgram","createShader","pixelDensity","this","clear","angleMode","DEGREES","ctx","drawingContext","lineWidth","_renderer","uModelMatrix","blend","_color","_isLast","isBrush","no_mask","_array","justChanged","applyShader","shader","gl","hadDepthTest","getParameter","DEPTH_TEST","disable","push","translate","setUniform","fill","noStroke","rect","pop","resetShader","enable","isDrawn","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","c","s0","s1","s2","copy","f","rng","noise","rr","e","rArray","array","randInt","gaussian","mean","stdev","u","log","cos","weightedRand","weights","totalWeight","entries","key","cumulative","rnd","isNaN","parseInt","value","a","b","d","withinBounds","constrain","low","high","max","min","nAngle","angle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","NaN","sLookup","idx","sin","toDegrees","rad","isRad","RADIANS","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","mat4","isLoaded","isFieldReady","resolution","left_x","top_y","num_columns","round","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","plotTo","_plot","_scale","_dirPlot","_step","scaleFactor","y_offset","x_offset","col","row","_current","_curvature","_strokeArray","_strokeOrigin","Map","genField","has","keys","join","entry","gen","name","funct","set","fn","Polygon","pointsArray","useRawVertices","vertices","sides","arr","_intersectionCache","intersect","line","cacheKey","point1","point2","points","start","end","intersection","show","stroke","draw","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","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","projMatrix","vao","buf","program","Attr","Frag","_ma","_mb","_mc","_md","_mx","_my","circleData","INITIAL_CAPACITY","circleCount","bufferCapacity","gpuBufferSize","circle","diameter","alpha","newData","px","py","glDraw","color","useProgram","BLEND","blendFunc","ONE_MINUS_DST_ALPHA","ONE","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","uniform4f","u_color","uniformMatrix4fv","u_matrix","drawArrays","POINTS","_curShader","weight","clipWindow","opacity","_position","Mask","BrushState","BrushSetState","state","add","params","includes","undefined","vibration","scatter","definition","sharpness","quality","grain","isArray","min_max","curve","m","range","ns","nm","ne","normalizePressure","image","src","T","tip","tips","param","colors","buffers","pick","brushName","g","arguments","strokeWeight","initializeDrawingState","plot","gaussians","angleScale","isPlot","cp","noiseoffset","dirRad","createProgram","VERTEX_SHADER","FRAGMENT_SHADER","shaderSource","compileShader","attachShader","linkProgram","forEach","getAttribLocation","getUniformLocation","createVertexArray","createBuffer","stride","enableVertexAttribArray","a_position","vertexAttribPointer","FLOAT","a_radius","a_alpha","isReady","isInsideClippingArea","calculateAlpha","markerTip","saveState","stepSize","spacing","totalSteps","customPressure","calculatePressure","lineNoise","sw","iterations","ceil","rX","yRandomFactor","sqrtPart","drawSpray","drawMarker","drawTip","perp","along","drawDefault","simPressure","peakPos","halfWidth","pow","gauss","o","vibrate","rx","ry","setAlpha","tint","adjustSizeAndRotation","_vals","_standard_brushes","obj","prototype","_brush","_weight","imageToWhite","loadPixels","average","pixels","updatePixels","filter","k","Promise","all","resolve","reject","nativeImg","Image","onload","p5img","createImage","naturalWidth","naturalHeight","drawImage","onerror","HatchState","options","rand","continuous","gradient","createHatch","polygons","save","hBrush","values","overallBB","overall","minX","Infinity","minY","maxX","maxY","poly","bb","computeBoundingBoxForPolygon","computeOverallBoundingBox","ventana","startY","dots","dist1","linea","tempArray","flat","sort","gdots","dd","continuousLine","polygon","_boundingBox","arc","_dist","_angle","_options","HatchSetState","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","_polygon","_gaussians","_isLeft","FillPoly","center","isFirst","sx","sy","midP","rayCalc","v1","v2","side","rt","mid","ray","sizeX","sizeY","rc","count","isect","trim","splice","grow","tr_v","tr_m","tr_dir","newVerts","newMods","newDirs","bleedDirDeg","mod","cv","nv","rotDeg","sideX","sideY","dirX","dirY","intensity","tex","texture","int","setTransform","strokeStyle","_getRed","_getGreen","_getBlue","lineCap","size","darker","pols","layer","numLayers","erase","restore","fillStyle","beginPath","lineTo","closePath","numCircles","halfSizeX","halfSizeY","minSize","minSizeFactor","maxSizeFactor","midX","midY","globalCompositeOperation","_opacity","_bleed","fluid","strength","modifiers","_","shift","shifted","slice","pts","area","cross","_center","createFill","FillSetState","_stateStack","registerAddon","_p5","lifecycles","postsetup","postdraw","_push","_pop","_randomSeed","randomSeed","_noiseSeed","noiseSeed","call","saved","brushPop","brushSeed","brushNoiseSeed","startAngle","endAngle","arcAngle","startX","angleOffset","randomFactor","randomAngle","offsetX","offsetY","region","brush","inst","async","mode","currentField","_array_points"],"mappings":"6BAaU,IAAMA,EAAQC,EAASC,EAAUC,EAAUC,EAOzC,MAACC,EAAO,CAACC,GAAS,KAW5B,GATAH,EACEI,IAAiBD,EACbJ,EACCI,GACCE,OAAOC,KAAKC,GAAGC,SAKO,WAA1BR,EAASS,aACX,MAAM,IAAIC,MAAM,oCAGlBb,EAASG,EAASW,MAClBb,EAAUE,EAASY,OAEnBC,GAAW,EACPb,EAASc,QAAQC,EAAIb,QAG3B,IAAIW,GAAW,EACXT,GAAe,EAKZ,MAAMY,EAAgB,KACtBH,GAAUX,KAOJe,EAAQ,CAAA,EAmBRC,EAAa,KACnBlB,EAASc,SACZE,IACAD,EAAIb,SAcKa,EAAM,CACjBI,YAAY,EACZC,cAAc,EACdC,cAAc,EACdC,YAAa,IAAIC,OACjBC,cAAe,IAAID,OACnBE,MAAO,GAKP,IAAAvB,GAEOF,EAASc,SACZd,EAAS0B,KAAO1B,EAAS2B,eAAe9B,EAAQC,EAASE,EAAS4B,KAClE5B,EAAS6B,OAAS7B,EAAS2B,eACzB9B,EACAC,EACAE,EAAS8B,OAEX9B,EAASc,QAAS,EAClBd,EAAS+B,cAAgB/B,EAASgC,muaAElC/B,EAAUD,EAASiC,eAEnBC,KAAKR,KAAO1B,EAAS0B,KACrBQ,KAAKR,KAAKO,aAAahC,GACvBiC,KAAKR,KAAKS,QACVD,KAAKR,KAAKU,UAAUpC,EAASqC,SAE7BH,KAAKI,IAAMJ,KAAKR,KAAKa,eAErBL,KAAKL,OAAS7B,EAAS6B,OACvBK,KAAKL,OAAOI,aAAahC,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1P,MACR,6FAGJ,MAAMosB,EAAe5c,GAAKC,IAAIlP,EAAM8M,MAAMqC,SAC1C0c,EAAa/e,MAAQ+e,EAAa/a,IAAI9L,EAAGyL,KAC3C,iBKjFO,SAAsBV,GAC3B,IAAK,MAAMyL,MAAEA,KAAWvM,GAAKgT,SACvBzG,IACFA,EAAMhC,QAAUzJ,EAChByL,EAAMnB,SAAWtK,EACjByL,EAAMyC,SAAWlO,EAGvB,oBJ8EO,SAAgB+b,EAAezb,EAAa,IACjD,IAAKyb,GAAiBA,EAAc7kB,OAAS,EAC3C,MAAM,IAAIxH,MACR,+EAGIoV,GAAciX,EAAezb,GACnCgC,MACJ,+DD8CO,SAAgBpJ,EAAI,GACzB6D,GAAM,QACN9M,EAAM8M,MAAMsC,OAASnG,CACvB","x_google_ignoreList":[1,2]}
\ No newline at end of file
+{"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/stroke/gl_draw.js","../src/stroke/stroke.js","../src/core/gl/utils.js","../src/hatch/hatch.js","../src/core/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// Section: 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\nconst isFramebufferTarget = (target) =>\n !!target &&\n typeof target.begin === \"function\" &&\n typeof target.end === \"function\" &&\n !!target.renderer &&\n !!target.renderer._pInst;\n\nconst getSketchRenderer = () =>\n _isInstanced ? Instance : window.self.p5.instance;\n\nconst isSupportedFramebufferTarget = (target) =>\n isFramebufferTarget(target) && target.renderer._pInst === getSketchRenderer();\n\nconst resolveTarget = (buffer = false) => {\n if (_isInstanced && !buffer) {\n return {\n renderer: Instance,\n width: Instance.width,\n height: Instance.height,\n };\n }\n\n if (!buffer) {\n const renderer = getSketchRenderer();\n return {\n renderer,\n width: renderer.width,\n height: renderer.height,\n };\n }\n\n if (isFramebufferTarget(buffer)) {\n if (!isSupportedFramebufferTarget(buffer)) {\n throw new Error(\n \"p5.brush only supports p5.Framebuffer targets created from the active sketch. Framebuffers created from p5.Graphics are not supported.\",\n );\n }\n\n return {\n renderer: getSketchRenderer(),\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\nconst removeTargetBuffer = (buffer) => {\n if (buffer && typeof buffer.remove === \"function\") {\n buffer.remove();\n }\n};\n\nconst getGraphicsFactory = () =>\n typeof Renderer.createGraphics === \"function\" ? Renderer : Renderer._pInst;\n\nconst getActiveFramebuffer = () =>\n Renderer &&\n Renderer._renderer &&\n typeof Renderer._renderer.activeFramebuffer === \"function\"\n ? Renderer._renderer.activeFramebuffer()\n : null;\n\nconst needsBlendSourceFramebuffer = (framebuffer) =>\n !framebuffer ||\n framebuffer.width !== Cwidth ||\n framebuffer.height !== Cheight ||\n (typeof framebuffer.pixelDensity === \"function\" &&\n framebuffer.pixelDensity() !== Density);\n\nconst needsMixBuffers = () =>\n !Renderer.mask ||\n !Renderer.glMask ||\n Renderer.mask.width !== Cwidth ||\n Renderer.mask.height !== Cheight ||\n Renderer.glMask.width !== Cwidth ||\n Renderer.glMask.height !== Cheight;\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\n // Check if Rendrer is webgl and throw error if it's not\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;\nlet _isInstanced = 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 _isInstanced = true;\n Instance = inst;\n};\n\n\n// =============================================================================\n// Section: Color Blending\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 * 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\nconst disable = false;\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 captureBlendSource() {\n const activeFramebuffer = getActiveFramebuffer();\n\n if (!activeFramebuffer) return Renderer._renderer;\n\n if (needsBlendSourceFramebuffer(Renderer.blendSourceFramebuffer)) {\n removeTargetBuffer(Renderer.blendSourceFramebuffer);\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 const source = Renderer.blendSourceFramebuffer;\n\n source.draw(() => {\n Renderer.clear();\n Renderer.push();\n if (typeof Renderer.imageMode === \"function\") {\n Renderer.imageMode(Renderer.CENTER ?? Renderer._renderer?._pInst?.CENTER);\n }\n Renderer.image(activeFramebuffer, 0, 0, Cwidth, Cheight);\n Renderer.pop();\n });\n\n return source;\n },\n\n /**\n * Loads necessary resources and prepares the mask buffer and shader for colour blending.\n */\n load() {\n Density = Renderer.pixelDensity();\n const graphicsFactory = getGraphicsFactory();\n const p2dMode = graphicsFactory.P2D ?? Renderer.P2D;\n const webglMode = graphicsFactory.WEBGL ?? Renderer.WEBGL;\n\n if (!Renderer.loaded || needsMixBuffers()) {\n removeTargetBuffer(Renderer.mask);\n removeTargetBuffer(Renderer.glMask);\n\n Renderer.mask = graphicsFactory.createGraphics(Cwidth, Cheight, p2dMode);\n Renderer.glMask = graphicsFactory.createGraphics(\n Cwidth,\n Cheight,\n webglMode,\n );\n Renderer.loaded = true;\n Renderer.shaderProgram ??= Renderer.createShader(vertSrc, fragSrc);\n\n this.mask = Renderer.mask;\n this.mask.pixelDensity(Density);\n this.mask.clear();\n this.mask.angleMode(Renderer.DEGREES);\n\n this.ctx = this.mask.drawingContext;\n\n this.glMask = Renderer.glMask;\n this.glMask.pixelDensity(Density);\n this.glMask.clear();\n this.glMask.angleMode(this.glMask.DEGREES);\n this.glMask.drawingContext.lineWidth = 0;\n } else {\n this.mask = Renderer.mask;\n this.glMask = Renderer.glMask;\n this.ctx = this.mask.drawingContext;\n }\n\n // Link Matrix of GL mask to main Renderer\n this.glMask._renderer.uModelMatrix = Renderer._renderer.uModelMatrix;\n },\n\n /**\n * Applies blending effects using the current color and mask.\n * @param {Color} _color - Color to blend.\n * @param {boolean} _isLast - If this is the final blend operation.\n * @param {boolean} _isImg - If blending an image.\n * @param {boolean} _isFillLayer - If this is a special case.\n */\n blend(_color = false, _isLast = false) {\n isMixReady();\n\n const mask = this.isBrush ? this.glMask : this.mask;\n const no_mask = this.isBrush ? this.mask : this.glMask;\n\n // Perf gains are minimal but let's keep it for now\n if (disable) {\n if (_isLast && mask.isDrawn) {\n Renderer.push();\n Renderer.translate(0, 0);\n Renderer.image(mask, 0, 0, Cwidth, Cheight);\n Renderer.pop();\n mask.isDrawn = false;\n }\n return;\n }\n\n // Initialize blending if not already active\n if (!this.isBlending && _color) {\n this.isBlending = true;\n this.cachedColor = _color._array;\n // Force p5 to bind its internal render target for glMask,\n // so the first glDraw() writes to the correct framebuffer.\n this.glMask.clear();\n }\n\n if (_isLast || this.cachedColor[0] !== _color._array[0] || this.cachedColor[1] !== _color._array[1] || this.cachedColor[2] !== _color._array[2] || this.cachedColor[3] !== _color._array[3]) {\n if (this.justChanged) {\n this.applyShader(no_mask);\n this.justChanged = false;\n }\n if (this.isBlending) {\n this.applyShader(mask);\n }\n this.cachedColor = _color._array;\n if (_isLast) this.isBlending = false;\n }\n },\n\n applyShader(mask) {\n let shader = Renderer.shaderProgram;\n const gl = Renderer.drawingContext;\n const targetIsFramebuffer = !!getActiveFramebuffer();\n const source = this.captureBlendSource();\n\n // Disable depth test for this compositing draw so the fullscreen rect\n // does not write Z=0 into the depth buffer — which would cause any\n // subsequent p5 geometry drawn at the same depth to fail depth testing\n // and become invisible.\n const hadDepthTest = gl.getParameter(gl.DEPTH_TEST);\n gl.disable(gl.DEPTH_TEST);\n\n Renderer.push();\n Renderer.translate(0, 0);\n\n // Use the blend shader for rendering\n Renderer.shader(shader);\n\n // Set shader uniforms\n shader.setUniform(\"u_source\", source);\n shader.setUniform(\"u_isBrush\", this.isBrush);\n shader.setUniform(\"u_flipOutputY\", targetIsFramebuffer);\n shader.setUniform(\"u_mask\", mask);\n shader.setUniform(\"u_color\", this.cachedColor);\n\n // Draw a rectangle covering the whole canvas to apply the shader\n Renderer.fill(0, 0, 0, 0);\n Renderer.noStroke();\n Renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);\n\n // Finish and clear mask\n Renderer.pop();\n Renderer.resetShader();\n\n // Restore depth test state\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n\n mask.clear();\n mask.isDrawn = false;\n },\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());\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 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()));\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};\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);\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);\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 { randInt, noise, rr, 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 = rr(0.2, 0.8),\n ba = randInt(5, 10);\n return fillField(field, (c, r) => {\n const angle = 0.5 * ba * sin(bs * r * c + randInt(15, 25));\n return 0.2 * angle * cos(t) + noise(c, r) * ba * 0.7;\n });\n });\n // Smooth large-scale noise curves\n addField(\"curved\", (t, field) => {\n let ar = randInt(-10, 10);\n if (randInt(0, 100) % 2 == 0) ar *= -1;\n return fillField(\n field,\n (c, r) =>\n 3 * map(noise(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 = randInt(-30, -15) + Math.abs(44 * sin(t));\n if (randInt(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 = randInt(10, 15) + 5 * sin(t),\n cr = randInt(3, 6) + 3 * cos(t),\n ba = randInt(20, 35);\n return fillField(\n field,\n (c, r) => sin(sr * c) * ba * cos(r * cr) + randInt(-3, 3),\n );\n });\n // Dense oscillation from row×col product\n addField(\"seabed\", (t, field) => {\n const bs = rr(0.4, 0.8),\n ba = randInt(18, 26);\n return fillField(\n field,\n (c, r) => 1.1 * ba * sin(bs * r * c + randInt(15, 20)) * cos(t),\n );\n });\n // Radial vortex — angles spiral around the field centre\n addField(\"spiral\", (_t, field) => {\n const n = randInt(5, 10);\n const dir = randInt(0, 2) * 2 - 1;\n const offset = randInt(65, 80); // <90 = inward spiral\n const attractors = Array.from({ length: n }, () => ({\n x: rr(0.1, 0.9) * num_columns,\n y: rr(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 = randInt(3, 8),\n amp = randInt(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, rr } 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 = Math.max(this.segments[idx] * _side * rr(0.7, 1.3), 10);\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 rr,\n randInt,\n sin,\n cos,\n toDegrees,\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 = rr(0, 360);\n const randomFactor = r ? () => 1 + r * 0.2 * rr() : () => 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 * randInt(-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// Module: GL Draw\n// =============================================================================\n/**\n * The GL Draw module provides functions for rendering shapes (circles and squares)\n * using WebGL2. It initializes the WebGL context and shader programs, prepares buffers,\n * and implements drawing routines based on queued drawing primitives. The module uses\n * an orthographic projection to map canvas coordinates to clip space and supports adjustable\n * blending for translucent effects.\n */\n\nimport {\n Mix,\n Cwidth,\n Cheight,\n isMixReady,\n Density,\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\";\n\n// =============================================================================\n// Section: Initialization and Setup\n// =============================================================================\n\n// Module state\nlet isLoaded = false,\n gl,\n projMatrix,\n vao,\n buf,\n program;\nlet loadedWidth = 0,\n loadedHeight = 0;\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\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}\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\n\n/**\n * Initializes WebGL objects if not done already.\n */\nexport function isReady() {\n isMixReady();\n\n const nextGl = Mix.glMask.drawingContext;\n const needsContextRefresh = !isLoaded || gl !== nextGl;\n const needsProjectionRefresh =\n needsContextRefresh || loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (needsProjectionRefresh) {\n projMatrix = 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 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 - Cwidth / 2;\n const py = y - Cheight / 2;\n\n const offset = circleCount * 4;\n circleData[offset] = _ma * px + _mc * py + _mx + Cwidth / 2;\n circleData[offset + 1] = _mb * px + _md * py + _my + Cheight / 2;\n // Scale the diameter by the matrix's scale factor (length of the transformed x-axis)\n circleData[offset + 2] =\n (Density * diameter * Math.sqrt(_ma * _ma + _mb * _mb)) / 2;\n circleData[offset + 3] = alpha / 255;\n circleCount++;\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\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, projMatrix);\n gl.drawArrays(gl.POINTS, 0, circleCount);\n\n gl.bindVertexArray(null);\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 Mix.glMask._renderer._curShader = null;\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 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 { isReady, glDraw, circle, snapshotMatrix } 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();\n\nlet Mask = null;\nlet _strokeTransform = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n tx: 0,\n ty: 0,\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 * { type, min_max, curve } — old internal format, passed through unchanged\n */\nfunction normalizePressure(p) {\n if (!p || (typeof p === \"object\" && !Array.isArray(p))) return p;\n if (typeof p === \"function\")\n return { type: \"custom\", min_max: [0, 1], curve: p };\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 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 // 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 === \"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 params.tip = () => {\n Mask.image(\n T.tips.get(current.p.image.src),\n -current.p.weight / 2,\n -current.p.weight / 2,\n current.p.weight,\n current.p.weight,\n );\n };\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 transformPoint(transform, x, y) {\n return {\n x: transform.a * x + transform.c * y + transform.tx,\n y: transform.b * x + transform.d * y + transform.ty,\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\nfunction currentPointInUserSpace() {\n return transformPoint(\n _strokeTransform,\n _position.x - Cwidth / 2,\n _position.y - Cheight / 2,\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 {boolean} flow - Flag for vector-field following.\n * @param {Object|boolean} plot - Plot object or false.\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 Mask = Mix.glMask;\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 current.cp = pressure.type !== \"custom\" ? rr(3, 3.5) : rr(-0.2, 0.2);\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 if (isInsideClippingArea()) Mix.blend(State.stroke.color);\n if (Mix.isBrush === false) Mix.justChanged = true;\n Mix.isBrush = true;\n\n // Set additional state values\n current.alpha = calculateAlpha();\n markerTip();\n}\n\n/**\n * Restores drawing state after completing a stroke.\n */\nfunction restoreState() {\n glDraw();\n markerTip();\n}\n\n/**\n * Renders the brush tip based on current pressure and position.\n * @param {number} [customPressure=false] - Optional custom pressure.\n */\nfunction tip(customPressure = false) {\n if (!isInsideClippingArea()) return;\n let pressure = customPressure || calculatePressure();\n\n let 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\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 drawTip(pressure * lineNoise, current.alpha);\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 return current.p.pressure.type === \"custom\"\n ? map(\n current.p.pressure.curve(_position.plotted / _length) + current.cp,\n 0,\n 1,\n current.min,\n current.max,\n true,\n )\n : gauss();\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 * @returns {boolean} True if inside clipping area; false otherwise.\n */\nfunction isInsideClippingArea() {\n const point = currentPointInUserSpace();\n\n if (State.stroke.clipWindow) {\n const local = transformPoint(\n State.stroke.clipWindow.inverse,\n point.x,\n point.y,\n );\n const { bounds } = State.stroke.clipWindow;\n return (\n local.x >= bounds.minX &&\n local.x <= bounds.maxX &&\n local.y >= bounds.minY &&\n local.y <= bounds.maxY\n );\n }\n\n let o = Cwidth * 0.05;\n return (\n point.x >= -Cwidth / 2 - o &&\n point.x <= Cwidth / 2 + o &&\n point.y >= -Cheight / 2 - o &&\n point.y <= Cheight / 2 + o\n );\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\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,\n );\n}\n\n/**\n * Draws a custom or image-based brush tip.\n * @param {number} pressure - Current pressure.\n * @param {number} alpha - Alpha (opacity) for drawing.\n * @param {boolean} [vibrate=true] - Whether to apply vibration.\n */\nfunction drawTip(pressure, alpha, vibrate = true) {\n Mix.glMask.isDrawn = true;\n Mask.push();\n Mask.noStroke();\n let color = State.stroke.color;\n color.setAlpha(alpha);\n Mask.fill(State.stroke.color);\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 Mask.translate(_position.x + rx - Cwidth, _position.y + ry - Cheight);\n adjustSizeAndRotation(State.stroke.weight * pressure, alpha);\n current.p.tip(Mask);\n Mask.pop();\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 if (rr(0, current.p.grain * pressure) > 0.4) {\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 circle(\n _position.x + dx,\n _position.y + dy,\n pressure *\n pressure *\n current.p.weight *\n rr(0.85, 1.15) *\n State.stroke.weight,\n Math.max(0.9, pressure) * current.alpha * rr(0.75, 1.1),\n );\n }\n}\n\n/**\n * Adjusts the size and rotation of the brush tip before rendering.\n * @param {number} pressure - Pressure-based scaling factor.\n * @param {number} alpha - Opacity value.\n */\nfunction adjustSizeAndRotation(pressure, alpha) {\n Mask.scale(pressure);\n if (current.p.type === \"image\") {\n Mask.tint(255, 0, 0, alpha / 2);\n }\n let angle = 0;\n if (current.p.rotate === \"random\") angle = randInt(0, 360);\n else if (current.p.rotate === \"natural\") {\n angle =\n (_plot ? -_plot.angle(_position.plotted) : -_dir) + _position.angle();\n }\n Mask.rotate(angle);\n}\n\n/**\n * Draws the marker tip with a blend effect.\n */\nfunction markerTip() {\n if (isInsideClippingArea()) {\n let pressure = calculatePressure();\n let alpha = calculateAlpha(pressure);\n if (current.p.type === \"marker\") {\n for (let s = 1; s < 10; s++) {\n drawMarker((pressure * s) / 10, false, alpha * 5);\n }\n glDraw();\n } else if (current.p.type === \"custom\" || current.p.type === \"image\") {\n for (let s = 1; s < 5; s++) {\n drawTip((pressure * s) / 5, alpha, false);\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, vibration, definition, quality, 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];\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.12,\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 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 p5img = Renderer.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.src = src;\n }),\n ),\n );\n },\n};\n\n/**\n * Loads all registered image tips. Must be awaited before setup/draw.\n * @returns {Promise}\n *\n * @example\n * // In your sketch:\n * await brush.preload();\n */\nexport async function preload() {\n await T.load();\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// Module: Hatch\n// =============================================================================\n/**\n * The Hatch module contains functions and classes dedicated to applying\n * hatch patterns over shapes and polygons. It enables the simulation of\n * cross-hatching and shading effects by drawing parallel lines or strokes\n * across a geometry. The module supports adjustable spacing, angle, and\n * optional style parameters (such as randomness, continuity, and gradient),\n * giving an artistic representation similar to hand-drawn hatching techniques.\n *\n * The implementation allows for hatching to be applied either to a Polygon\n * directly or via a Plot, extending the drawing capabilities with layered,\n * stylized textures.\n */\n\nimport { State } from \"../core/color.js\";\nimport { toDegreesSigned, map, cos, sin, 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 and Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Global hatch state settings.\n */\nState.hatch = {\n isActive: false,\n dist: 5,\n angle: 45,\n options: {},\n hBrush: false,\n};\n\n/**\n * Returns a shallow copy of the current hatch state.\n * @returns {object} The current hatch state.\n */\nexport function HatchState() {\n return { ...State.hatch };\n}\n\n/**\n * Updates the global hatch state.\n * @param {object} state - The new hatch state.\n */\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Style Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Activates hatching for subsequent geometries.\n *\n * @param {number} dist - The distance between hatching lines.\n * @param {number} angle - The hatch angle, interpreted using the current p5 angle mode.\n * @param {object} options - Optional parameters to affect the hatching style:\n * - rand: Number value to introduce randomness.\n * - continuous: Boolean to connect adjacent lines.\n * - gradient: Number to gradually change spacing.\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 * Sets the hatch brush style for subsequent hatching.\n *\n * @param {string} brush - The brush name.\n * @param {string|Color} color - The brush color.\n * @param {number} weight - The brush weight (size).\n */\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\n/**\n * Disables hatching.\n */\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fill Manager Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a hatching pattern over the given polygon(s).\n *\n * @param {Polygon|Polygon[]} polygons - A polygon or an array of polygons.\n */\nexport function createHatch(polygons) {\n let dist = State.hatch.dist;\n let angle = ((State.hatch.angle % 180) + 180) % 180;\n let options = State.hatch.options;\n\n // Save current stroke state\n let save = BrushState();\n // If a hatch brush is set, override with those parameters.\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n\n // Compute overall bounding box for all polygons.\n if (!Array.isArray(polygons)) polygons = [polygons];\n const overallBB = computeOverallBoundingBox(polygons);\n\n // Build a bounding polygon based on the overall bounding box.\n let ventana = new Polygon([\n [overallBB.minX, overallBB.minY],\n [overallBB.maxX, overallBB.minY],\n [overallBB.maxX, overallBB.maxY],\n [overallBB.minX, overallBB.maxY],\n ]);\n\n // Determine starting y coordinate based on angle.\n let startY = angle <= 90 && angle >= 0 ? overallBB.minY : overallBB.maxY;\n let gradient = options.gradient\n ? map(options.gradient, 0, 1, 1, 1.1, true)\n : 1;\n let dots = [];\n let i = 0;\n let dist1 = dist;\n\n // Function to generate a line for index i.\n let linea = (i) => {\n return {\n point1: {\n x: overallBB.minX + dist1 * i * cos(-angle + 90),\n y: startY + dist1 * i * sin(-angle + 90),\n },\n point2: {\n x: overallBB.minX + dist1 * i * cos(-angle + 90) + cos(-angle),\n y: startY + dist1 * i * sin(-angle + 90) + sin(-angle),\n },\n };\n };\n\n // Generate lines and calculate intersections with polygons\n // Loop through the lines based on the distance and angle to calculate intersections with the polygons\n // The loop continues until a line does not intersect with the bounding window polygon\n // Each iteration accounts for the gradient effect by adjusting the distance between lines\n while (ventana.intersect(linea(i)).length > 0) {\n let tempArray = [];\n for (let p of polygons) {\n tempArray.push(p.intersect(linea(i)));\n }\n dots[i] = tempArray\n .flat()\n .sort((a, b) => (a.x === b.x ? a.y - b.y : a.x - b.x));\n dist1 *= gradient;\n i++;\n }\n\n // Filter out empty intersection sets.\n let gdots = dots.filter((dd) => typeof dd[0] !== \"undefined\");\n\n // Draw the hatching lines using the calculated intersections\n // If the 'rand' option is enabled, add randomness to the start and end points of the lines\n // If the 'continuous' option is set, connect the end of one line to the start of the next\n let r = options.rand || 0;\n for (let j = 0; j < gdots.length; j++) {\n let dd = gdots[j];\n let continuousLine = j > 0 && options.continuous;\n for (let i = 0; i < dd.length - 1; i += 2) {\n if (r !== 0) {\n dd[i].x += r * dist * rr(-1, 1);\n dd[i].y += r * dist * rr(-1, 1);\n dd[i + 1].x += r * dist * rr(-1, 1);\n dd[i + 1].y += r * dist * rr(-1, 1);\n }\n line(dd[i].x, dd[i].y, dd[i + 1].x, dd[i + 1].y);\n if (continuousLine) {\n line(gdots[j - 1][1].x, gdots[j - 1][1].y, dd[i].x, dd[i].y);\n }\n }\n }\n\n // Restore previous brush state.\n BrushSetState(save);\n}\n\n/**\n * Computes the bounding box for a single polygon.\n * @param {Polygon} polygon - The polygon to evaluate.\n * @returns {object} The bounding box as {minX, minY, maxX, maxY}.\n */\nfunction computeBoundingBoxForPolygon(polygon) {\n if (polygon._boundingBox) return polygon._boundingBox;\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n for (let i = 0; i < polygon.a.length; i++) {\n const [x, y] = polygon.a[i];\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n }\n polygon._boundingBox = { minX, minY, maxX, maxY };\n return polygon._boundingBox;\n}\n\n/**\n * Computes an overall bounding box for an array of polygons.\n * @param {Array} polygons - Array of Polygon objects.\n * @returns {object} The overall bounding box {minX, minY, maxX, maxY}.\n */\nfunction computeOverallBoundingBox(polygons) {\n let overall = {\n minX: Infinity,\n minY: Infinity,\n maxX: -Infinity,\n maxY: -Infinity,\n };\n for (let poly of polygons) {\n const bb = computeBoundingBoxForPolygon(poly);\n overall.minX = Math.min(overall.minX, bb.minX);\n overall.minY = Math.min(overall.minY, bb.minY);\n overall.maxX = Math.max(overall.maxX, bb.maxX);\n overall.maxY = Math.max(overall.maxY, bb.maxY);\n }\n return overall;\n}\n\n// ---------------------------------------------------------------------------\n// Extend Polygon and Plot Prototypes\n// ---------------------------------------------------------------------------\n\n/**\n * Adds a hatch effect to the polygon.\n *\n * If a distance is provided, activates hatching with the given parameters.\n * Then, if hatch is active, applies the hatching pattern.\n *\n * @param {number} [_dist] - The distance between hatch lines.\n * @param {number} _angle - The hatch angle, interpreted using the current p5 angle mode.\n * @param {object} _options - Optional hatch options.\n */\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (state.isActive) {\n createHatch(this);\n }\n HatchSetState(state);\n};\n\n/**\n * Applies hatching to a plot.\n *\n * If hatching is active, generates a polygon from the plot and applies hatch.\n *\n * @param {number} x - The x-coordinate to draw at.\n * @param {number} y - The y-coordinate to draw at.\n * @param {number} scale - Scaling factor.\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 \"./color.js\";\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 Mix.ctx.beginPath();\n vertices.forEach((v, i) => {\n if (i === 0) Mix.ctx.moveTo(v.x, v.y);\n else Mix.ctx.lineTo(v.x, v.y);\n });\n Mix.ctx.closePath();\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 radius = d / 2;\n Mix.ctx.moveTo(x + radius, y);\n Mix.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 { Renderer, Mix, State, Cwidth, Cheight, Density } from \"../core/color.js\";\nimport { drawPolygon, circle } from \"../core/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 = 1024;\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 < 8) {\n // Simple average for small polygons\n return pts\n .reduce((c, p) => ({ x: c.x + p.x, y: c.y + p.y }), { x: 0, y: 0 })\n .map((v) => v / 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\n // Map vertices\n const fluid = ~~(v.length * 0.25 * weightedRand({ 1: 5, 2: 10, 3: 60 }));\n const strength = State.fill.bleed_strength;\n\n // Create bleed modifiers\n const modifiers = v.map(\n (_, i) => (i > fluid ? 1 : 0.3) * rr(0.85, 1.2) * strength,\n );\n\n // Randomize starting point\n const shift = randInt(0, v.length);\n const shifted = [...v.slice(shift), ...v.slice(0, shift)];\n\n // Calculate center and create FillPolygon\n const center = _center(shifted);\n 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 // Clone and splice\n const v = [...this.v],\n m = [...this.m],\n dir = [...this.dir];\n v.splice(s, n);\n m.splice(s, n);\n dir.splice(s, 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\n // Build sorted random indices\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 = [], sm = [], 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\n // Ray-cast: count intersections from p to far right\n let crossings = 0;\n for (const [a, b] of sides) {\n const ay = a.y, 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 outside (even crossings), pull toward center\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\n sv.push(p);\n sm.push(this.m[j]);\n sd.push(!this.dir[j]); // flip direction → grow inward\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 // Get trimmed vertices\n const { v: tr_v, m: tr_m, dir: tr_dir } = this.trim(f);\n const len = tr_v.length;\n \n // Pre-allocate output arrays\n const outLen = len * 2;\n const newVerts = new Array(outLen);\n const newMods = new Array(outLen);\n const newDirs = new Array(outLen);\n \n // Determine bleed direction\n const bleedDirDeg = State.fill.direction === \"out\" ? -90 : 90;\n \n // Ensure gaussian pool is filled\n if (_gaussians[0].length === 0) _fillGaussianPools();\n const gPool = _gaussians[0], gPoolLen = gPool.length;\n const g2Pool = _gaussians[1], g2PoolLen = g2Pool.length;\n \n let idx = 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 // Inline rotate: rotDeg = ±bleedDirDeg + small jitter\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 // Outward distance: inline rArray + rr\n const d = gPool[~~(rr(0, 1) * gPoolLen)] * rr(0.65, 1.35) * mod;\n \n // First vertex: original\n newVerts[idx] = cv;\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n \n // Second vertex: midpoint + outward push\n newVerts[idx] = {\n x: cv.x + sideX * 0.5 + dirX * d,\n y: cv.y + sideY * 0.5 + dirY * d,\n };\n newMods[idx] = mi + g2Pool[~~(rr(0, 1) * g2PoolLen)];\n newDirs[idx] = di;\n idx++;\n }\n \n // Cap vertex count to prevent exponential blowup.\n let fv = newVerts, fm = newMods, fd = newDirs;\n let growe = GROW_MAX_VERTS / (State.fill.texture_strength);\n if (growe && idx > growe) {\n const step = Math.ceil(idx / growe);\n fv = []; fm = []; fd = [];\n for (let j = 0; j < idx; j += step) {\n fv.push(newVerts[j]);\n fm.push(newMods[j]);\n fd.push(newDirs[j]);\n }\n } else {\n // Trim pre-allocated arrays to actual size\n fv.length = idx;\n fm.length = idx;\n fd.length = idx;\n }\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 // Precalculate stuff\n const numLayers = 20;\n const texture = tex * 3;\n const int = 2 * intensity * (1 + tex / 2);\n\n // Perform initial setup only once\n Mix.blend(color);\n Mix.justChanged = true;\n Mix.isBrush = false;\n\n Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * Matrix.a(), Density * Matrix.b(),\n Density * Matrix.c(), 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\n // Create initial polygon\n let pol = this.grow();\n // Create sparse inner polygon from original (pre-grow) vertices\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 // Grow polygon every 4 layers\n if (i % 4 === 0) pol = pol.grow();\n\n // Create variant polygons\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 // Draw layers\n for (const p of pols) p.grow(999).grow(997).layer(i, size, int, color);\n sparse.grow(999).flipDirs().grow(997).layer(i, size, int * 1.5 * texture, color);\n if (i % 2 === 0)\n pol\n .grow(darker)\n .grow(999)\n .layer(i, size, int * 2, color);\n\n // Apply texture and blend periodically\n if (i % 5 === 0 || i === numLayers - 1) {\n if (texture !== 0) pol.erase(texture * 3, intensity);\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 Mix.ctx.fillStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${int}%)`;\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 // Optimize by pre-calculating values\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.4 - State.fill.bleed_strength);\n const minSizeFactor = 0.05 * minSize;\n const maxSizeFactor = 0.4 * minSize;\n const { x: midX, y: midY } = this.midP;\n\n // Set up erase mode\n Mix.ctx.globalCompositeOperation = \"destination-out\";\n\n // Calculate transparency\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 // Draw erase circles\n for (let i = 0; i < numCircles; i++) {\n const x = midX + gaussian(0, halfSizeX);\n const y = midY + gaussian(0, halfSizeY);\n const size = rr(minSizeFactor, maxSizeFactor);\n\n Mix.ctx.beginPath();\n circle(x, y, size);\n if (i % 5 !== 0) Mix.ctx.fill();\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 map(State.fill.bleed_strength, 0, 0.6, 0.3, 0.45, 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 * @version 2.0.0-alpha\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.bleed(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-2024 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 { Mix } 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.postsetup = () => Mix.blend(false, true);\n lifecycles.postdraw = () => Mix.blend(false, true);\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","isFramebufferTarget","target","begin","end","renderer","_pInst","getSketchRenderer","_isInstanced","window","self","p5","instance","removeTargetBuffer","buffer","remove","getActiveFramebuffer","_renderer","activeFramebuffer","load","width","height","Error","resolveTarget","webglVersion","_isReady","loaded","Mix","isCanvasReady","State","isMixReady","isBlending","cachedColor","Object","captureBlendSource","framebuffer","blendSourceFramebuffer","pixelDensity","createFramebuffer","density","antialias","depth","stencil","source","draw","clear","push","imageMode","CENTER","image","pop","graphicsFactory","createGraphics","p2dMode","P2D","webglMode","WEBGL","mask","glMask","this","ctx","drawingContext","shaderProgram","createShader","angleMode","DEGREES","lineWidth","uModelMatrix","blend","_color","_isLast","isBrush","no_mask","_array","justChanged","applyShader","shader","gl","targetIsFramebuffer","hadDepthTest","getParameter","DEPTH_TEST","disable","translate","setUniform","fill","noStroke","rect","resetShader","enable","isDrawn","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","c","s0","s1","s2","copy","f","rng","_seedCallbacks","_onSeed","cb","noise","rr","e","rArray","array","randInt","gaussian","mean","stdev","u","log","cos","weightedRand","weights","totalWeight","entries","key","cumulative","rnd","isNaN","parseInt","value","a","b","d","withinBounds","constrain","low","high","max","min","nAngle","angle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","NaN","sLookup","idx","sin","toDegrees","rad","isRad","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","mat4","isLoaded","isFieldReady","resolution","left_x","top_y","num_columns","round","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","projMatrix","vao","buf","program","loadedWidth","loadedHeight","Attr","Frag","_ma","_mb","_mc","_md","_mx","_my","circleData","INITIAL_CAPACITY","circleCount","bufferCapacity","gpuBufferSize","circle","diameter","alpha","newData","px","py","glDraw","color","useProgram","BLEND","blendFunc","ONE_MINUS_DST_ALPHA","ONE","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","uniform4f","u_color","uniformMatrix4fv","u_matrix","drawArrays","POINTS","_curShader","weight","clipWindow","opacity","_position","Mask","_strokeTransform","tx","ty","BrushState","BrushSetState","state","add","params","includes","undefined","vibration","scatter","definition","sharpness","quality","grain","isArray","min_max","curve","m","range","ns","nm","ne","normalizePressure","src","T","tip","tips","param","colors","buffers","pick","brushName","g","arguments","strokeWeight","snapshotTransform","transformPoint","transform","normalizeRegion","region","minX","minY","maxX","maxY","initializeDrawingState","plot","gaussians","angleScale","isPlot","cp","noiseoffset","dirRad","nextGl","needsContextRefresh","createProgram","VERTEX_SHADER","FRAGMENT_SHADER","shaderSource","compileShader","attachShader","linkProgram","forEach","getAttribLocation","getUniformLocation","createVertexArray","createBuffer","enableVertexAttribArray","a_position","vertexAttribPointer","FLOAT","a_radius","a_alpha","isReady","isInsideClippingArea","calculateAlpha","markerTip","saveState","stepSize","spacing","totalSteps","customPressure","calculatePressure","lineNoise","sw","iterations","ceil","rX","yRandomFactor","sqrtPart","drawSpray","drawMarker","drawTip","perp","along","drawDefault","simPressure","peakPos","halfWidth","pow","gauss","point","local","inverse","bounds","o","vibrate","rx","ry","setAlpha","tint","adjustSizeAndRotation","_vals","_standard_brushes","obj","prototype","_brush","_weight","imageToWhite","loadPixels","average","pixels","updatePixels","filter","k","Promise","all","resolve","reject","nativeImg","Image","onload","p5img","createImage","naturalWidth","naturalHeight","drawImage","onerror","HatchState","rand","continuous","gradient","createHatch","polygons","save","hBrush","values","overallBB","overall","Infinity","poly","bb","computeBoundingBoxForPolygon","computeOverallBoundingBox","ventana","startY","dots","dist1","linea","tempArray","flat","sort","gdots","dd","continuousLine","polygon","_boundingBox","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","splice","ratio","L","keep","indices","sv","sm","sd","crossings","ay","by","flipDirs","grow","tr_v","tr_m","tr_dir","outLen","newVerts","newMods","newDirs","bleedDirDeg","gPool","gPoolLen","g2Pool","g2PoolLen","mod","cv","nv","mi","di","rotDeg","sideX","sideY","dirX","dirY","fv","fm","fd","growe","intensity","tex","texture","int","setTransform","strokeStyle","_getRed","_getGreen","_getBlue","lineCap","size","darker","sparse","pols","layer","numLayers","erase","restore","fillStyle","beginPath","lineTo","closePath","numCircles","halfSizeX","halfSizeY","minSize","minSizeFactor","maxSizeFactor","midX","midY","globalCompositeOperation","_opacity","_bleed","fluid","strength","modifiers","_","shift","shifted","slice","pts","area","cross","_center","createFill","FillSetState","_stateStack","registerAddon","_p5","lifecycles","postsetup","postdraw","_push","_pop","_randomSeed","randomSeed","_noiseSeed","noiseSeed","call","saved","brushPop","callback","brushSeed","brushNoiseSeed","startDeg","sweepDeg","segmentCount","segmentSweep","startX","angleOffset","randomFactor","randomAngle","offsetX","offsetY","det","invertTransform","brush","inst","mode","currentField","_array_points"],"mappings":"6BAYO,IAAIA,EAAQC,EAASC,EAAUC,EAAUC,EAEhD,MAAMC,EAAuBC,KACzBA,GACsB,mBAAjBA,EAAOC,OACQ,mBAAfD,EAAOE,OACZF,EAAOG,YACPH,EAAOG,SAASC,OAEdC,EAAoB,IACxBC,EA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file mode 100644
index a08fcd0..0000000
Binary files a/images/teaser.gif and /dev/null differ
diff --git a/llms.txt b/llms.txt
index 7a59ea3..12688fd 100644
--- a/llms.txt
+++ b/llms.txt
@@ -43,8 +43,10 @@ p5.brush hooks into p5 automatically:
- `translate()`, `rotate()`, `scale()` — all p5 transforms apply to brush strokes
- `randomSeed(n)` — seeds both p5 and the brush library
- `noiseSeed(n)` — seeds both p5 noise and the brush library
+- `angleMode(mode)` — public brush APIs that accept angles follow p5's current angle mode; with no `angleMode()` call, this defaults to radians just like p5
No separate `brush.push()`, `brush.translate()`, or `brush.seed()` calls are needed.
+Exception: `brush.addField(name, fn, { angleMode })` lets custom field generators declare whether returned angles are in degrees or radians before the library stores them internally in degrees.
---
@@ -52,10 +54,10 @@ No separate `brush.push()`, `brush.translate()`, or `brush.seed()` calls are nee
### Configuration
-- `brush.load(buffer?)` — Initialize on the current canvas, or on a `p5.Graphics` buffer. Call again with no args to return to the main canvas.
-- `brush.scaleBrushes(scale)` — Multiply all default brush sizes by `scale`. Call once in setup.
+- `brush.load(buffer?)` — Initialize on the current canvas, on a `p5.Graphics` buffer, or on an active `p5.Framebuffer` from the current sketch. For `p5.Graphics`, create the buffer in `WEBGL`, call `brush.load(pg)`, draw, then call `brush.load()` 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. Call again with no args to return to the main canvas.
+- `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.instance(p)` — Use when p5 is in instance mode. Call before setup/draw.
-- `brush.preload()` — Legacy. Not needed in v2.
+- `brush.preload()` — Compatibility helper for preloading image tips. Usually unnecessary in v2 if you `await brush.add(...)` for image brushes.
---
@@ -73,7 +75,7 @@ No separate `brush.push()`, `brush.translate()`, or `brush.seed()` calls are nee
Fill simulates watercolor — soft edges, bleed, texture layering.
-- `brush.fill(color, opacity)` or `brush.fill(r, g, b, opacity)` — Set fill color. Opacity is 0–255. Enables fill.
+- `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.fillBleed(strength, direction?)` — Edge bleed amount, 0–1. Direction: `"out"` or `"in"`.
- `brush.fillTexture(textureStrength, borderIntensity)` — Texture and border, both 0–1.
@@ -84,7 +86,7 @@ Fill simulates watercolor — soft edges, bleed, texture layering.
Hatching draws parallel lines inside shapes. Activate before drawing a shape, disable after.
-- `brush.hatch(dist, angle, options?)` — Enable hatching. `dist` = spacing in canvas units, `angle` = line angle (respects `angleMode()`). Options: `{rand: 0–1, continuous: bool, gradient: 0–1}`.
+- `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.hatchArray(polygons)` — Apply current hatch style directly to a `brush.Polygon` or array of polygons.
@@ -102,7 +104,7 @@ Built-in fields: `"hand"`, `"curved"`, `"zigzag"`, `"waves"`, `"seabed"`, `"spir
- `brush.wiggle(intensity)` — Shorthand for activating `"hand"` field with a given wobble strength (e.g. 1–10).
- `brush.listFields()` — Returns array of all field names.
- `brush.refreshField(t)` — Update field values using its time-dependent generator. Call in draw loop.
-- `brush.addField(name, fn)` — Create a custom field. `fn(t, field)` fills a 2D angle grid and returns it.
+- `brush.addField(name, fn, options?)` — Create a custom field. `fn(t, field)` fills a 2D angle grid and returns it. By default the grid values are degrees; pass `{ angleMode: "radians" }` if your generator writes radians.
```js
brush.addField("diagonal", (t, field) => {
@@ -121,7 +123,7 @@ brush.field("diagonal")
#### Lines (stroke only, no fill/hatch)
- `brush.line(x1, y1, x2, y2)` — Straight line with current brush.
-- `brush.flowLine(x, y, length, dir)` — Line that follows the active vector field. `dir` is initial angle.
+- `brush.flowLine(x, y, length, dir)` — Line that follows the active vector field. `dir` is the initial angle and follows the current `angleMode()`.
- `brush.spline(points, curvature?)` — Smooth curve through `[[x,y], [x,y,pressure], ...]`. Curvature 0–1.
#### Manual strokes (stroke only)
@@ -136,8 +138,8 @@ brush.endStroke(angle, pressure)
#### Shapes (affected by stroke + fill + hatch)
- `brush.rect(x, y, w, h, mode?)` — Rectangle. `mode`: `"corner"` (default) or `"center"`.
-- `brush.circle(x, y, radius, r?)` — Circle outline. `r` = hand-drawn irregularity (0–1). **Fill is not applied to circles** — use `brush.polygon()` for filled circles.
-- `brush.arc(x, y, radius, start, end)` — Arc in radians. Stroke only.
+- `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.
- `brush.beginShape(curvature?)` / `brush.vertex(x, y, pressure?)` / `brush.endShape(close?)` — Custom shape.
@@ -146,7 +148,7 @@ brush.endStroke(angle, pressure)
### Brush Management
- `brush.box()` — Returns array of all brush names.
-- `brush.clip([x1, y1, x2, y2])` — Clip all strokes to a rectangle.
+- `brush.clip([x1, y1, x2, y2])` — Clip all strokes to a rectangle in the same coordinate space as brush drawing calls. The current p5 transform is captured when you call it.
- `brush.noClip()` — Remove clipping.
- `brush.add(name, params)` — Define a custom brush.
@@ -225,7 +227,7 @@ Point that can move through a vector field.
```js
let pos = new brush.Position(x, y)
-pos.moveTo(length, dir, stepLength, isFlow)
+pos.moveTo(dir, length, stepLength) // direction follows the current angleMode()
pos.plotTo(plot, length, stepLength, scale)
```
@@ -260,6 +262,7 @@ function draw() {
### Vector field + flowLine
```js
+angleMode(DEGREES)
brush.field("waves")
brush.set("charcoal", "white", 1)
for (let i = 0; i < 40; i++)
@@ -294,9 +297,10 @@ pop()
- Canvas **must be WEBGL** — `createCanvas(w, h, WEBGL)`.
- In WEBGL mode the origin is at the center. Use `translate(-width/2, -height/2)` at the start of `draw()` to work in top-left coordinates.
-- `brush.circle()` draws a stroke outline only — fill is not applied. Use `brush.polygon()` with many points for a filled circle.
+- `brush.circle()` can be stroked, hatched, and filled. `brush.arc()` is stroke-only.
- `brush.load()` must be called after `createCanvas()`, not before.
- For image brushes, `setup()` must be `async` and you must `await brush.add(...)`.
- `randomSeed()` and `noiseSeed()` seed the library automatically — no separate brush seed call needed.
+- `brush.flowLine()` direction and `brush.hatch()` angles follow the current `angleMode()`.
- `brush.rect()` mode uses strings: `"corner"` or `"center"` — not p5 constants.
-- Fill opacity is 0–255, not 0–100.
+- Fill opacity follows p5-style alpha values, not 0–100.
diff --git a/package.json b/package.json
index 37eae31..c70947c 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "p5.brush",
- "version": "2.0.0-alpha",
+ "version": "2.0.0-beta",
"description": "Unlock custom brushes, natural fill effects and intuitive hatching in p5.js",
"main": "src/index.js",
"module": "src/index.js",
@@ -10,7 +10,7 @@
"test:watch": "vitest",
"build": "rollup --config -w"
},
- "sideEffects": "false",
+ "sideEffects": false,
"type": "module",
"repository": {
"type": "git",
diff --git a/src/core/color.js b/src/core/color.js
index 65c83c4..7bd6d4e 100644
--- a/src/core/color.js
+++ b/src/core/color.js
@@ -10,22 +10,100 @@ import fragSrc from "./gl/shader.frag";
* provides utilities for saving and restoring states.
*/
-const Canvases = {}; // Stores canvas instances by ID
-export let cID, Cwidth, Cheight, Instance, Renderer, Density; // Global canvas properties
+export let Cwidth, Cheight, Instance, Renderer, Density; // Global canvas properties
+
+const isFramebufferTarget = (target) =>
+ !!target &&
+ typeof target.begin === "function" &&
+ typeof target.end === "function" &&
+ !!target.renderer &&
+ !!target.renderer._pInst;
+
+const getSketchRenderer = () =>
+ _isInstanced ? Instance : window.self.p5.instance;
+
+const isSupportedFramebufferTarget = (target) =>
+ isFramebufferTarget(target) && target.renderer._pInst === getSketchRenderer();
+
+const resolveTarget = (buffer = false) => {
+ if (_isInstanced && !buffer) {
+ return {
+ renderer: Instance,
+ width: Instance.width,
+ height: Instance.height,
+ };
+ }
+
+ if (!buffer) {
+ const renderer = getSketchRenderer();
+ return {
+ renderer,
+ width: renderer.width,
+ height: renderer.height,
+ };
+ }
+
+ if (isFramebufferTarget(buffer)) {
+ if (!isSupportedFramebufferTarget(buffer)) {
+ throw new Error(
+ "p5.brush only supports p5.Framebuffer targets created from the active sketch. Framebuffers created from p5.Graphics are not supported.",
+ );
+ }
+
+ return {
+ renderer: getSketchRenderer(),
+ width: buffer.width,
+ height: buffer.height,
+ };
+ }
+
+ return {
+ renderer: buffer,
+ width: buffer.width,
+ height: buffer.height,
+ };
+};
+
+const removeTargetBuffer = (buffer) => {
+ if (buffer && typeof buffer.remove === "function") {
+ buffer.remove();
+ }
+};
+
+const getGraphicsFactory = () =>
+ typeof Renderer.createGraphics === "function" ? Renderer : Renderer._pInst;
+
+const getActiveFramebuffer = () =>
+ Renderer &&
+ Renderer._renderer &&
+ typeof Renderer._renderer.activeFramebuffer === "function"
+ ? Renderer._renderer.activeFramebuffer()
+ : null;
+
+const needsBlendSourceFramebuffer = (framebuffer) =>
+ !framebuffer ||
+ framebuffer.width !== Cwidth ||
+ framebuffer.height !== Cheight ||
+ (typeof framebuffer.pixelDensity === "function" &&
+ framebuffer.pixelDensity() !== Density);
+
+const needsMixBuffers = () =>
+ !Renderer.mask ||
+ !Renderer.glMask ||
+ Renderer.mask.width !== Cwidth ||
+ Renderer.mask.height !== Cheight ||
+ Renderer.glMask.width !== Cwidth ||
+ Renderer.glMask.height !== Cheight;
/**
* Loads and initializes a canvas for the drawing system.
- * @param {string|boolean} [canvasID=false] - Optional ID of the canvas element to use.
- * If false, it uses the current window as the rendering context.
+ * @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) => {
- // Set renderer to specificed Buffer, Instance,, or Window
- Renderer =
- _isInstanced && !buffer
- ? Instance
- : !buffer
- ? window.self.p5.instance
- : buffer;
+ const target = resolveTarget(buffer);
+ Renderer = target.renderer;
// Check if Rendrer is webgl and throw error if it's not
@@ -33,8 +111,8 @@ export const load = (buffer = false) => {
throw new Error("p5.brush requires a WEBGL canvas");
}
- Cwidth = Renderer.width;
- Cheight = Renderer.height;
+ Cwidth = target.width;
+ Cheight = target.height;
_isReady = true;
if (Renderer.loaded) Mix.load();
@@ -92,28 +170,61 @@ const disable = false;
*/
export const Mix = {
isBlending: false,
- isBlendingGL: false,
- isWaterColor: false,
cachedColor: new Object(),
- cachedColorGL: new Object(),
- masks: [],
+
+ captureBlendSource() {
+ const activeFramebuffer = getActiveFramebuffer();
+
+ if (!activeFramebuffer) return Renderer._renderer;
+
+ if (needsBlendSourceFramebuffer(Renderer.blendSourceFramebuffer)) {
+ removeTargetBuffer(Renderer.blendSourceFramebuffer);
+ Renderer.blendSourceFramebuffer = Renderer.createFramebuffer({
+ width: Cwidth,
+ height: Cheight,
+ density: Density,
+ antialias: false,
+ depth: false,
+ stencil: false,
+ });
+ }
+
+ const source = Renderer.blendSourceFramebuffer;
+
+ source.draw(() => {
+ Renderer.clear();
+ Renderer.push();
+ if (typeof Renderer.imageMode === "function") {
+ Renderer.imageMode(Renderer.CENTER ?? Renderer._renderer?._pInst?.CENTER);
+ }
+ Renderer.image(activeFramebuffer, 0, 0, Cwidth, Cheight);
+ Renderer.pop();
+ });
+
+ return source;
+ },
/**
* Loads necessary resources and prepares the mask buffer and shader for colour blending.
*/
load() {
- // Create Renderer masks
- if (!Renderer.loaded) {
- Renderer.mask = Renderer.createGraphics(Cwidth, Cheight, Renderer.P2D);
- Renderer.glMask = Renderer.createGraphics(
+ Density = Renderer.pixelDensity();
+ const graphicsFactory = getGraphicsFactory();
+ const p2dMode = graphicsFactory.P2D ?? Renderer.P2D;
+ const webglMode = graphicsFactory.WEBGL ?? Renderer.WEBGL;
+
+ if (!Renderer.loaded || needsMixBuffers()) {
+ removeTargetBuffer(Renderer.mask);
+ removeTargetBuffer(Renderer.glMask);
+
+ Renderer.mask = graphicsFactory.createGraphics(Cwidth, Cheight, p2dMode);
+ Renderer.glMask = graphicsFactory.createGraphics(
Cwidth,
Cheight,
- Renderer.WEBGL,
+ webglMode,
);
Renderer.loaded = true;
- Renderer.shaderProgram = Renderer.createShader(vertSrc, fragSrc);
-
- Density = Renderer.pixelDensity();
+ Renderer.shaderProgram ??= Renderer.createShader(vertSrc, fragSrc);
this.mask = Renderer.mask;
this.mask.pixelDensity(Density);
@@ -127,9 +238,14 @@ export const Mix = {
this.glMask.clear();
this.glMask.angleMode(this.glMask.DEGREES);
this.glMask.drawingContext.lineWidth = 0;
- // Link Matrix of GL mask to main Renderer
- this.glMask._renderer.uModelMatrix = Renderer._renderer.uModelMatrix;
+ } else {
+ this.mask = Renderer.mask;
+ this.glMask = Renderer.glMask;
+ this.ctx = this.mask.drawingContext;
}
+
+ // Link Matrix of GL mask to main Renderer
+ this.glMask._renderer.uModelMatrix = Renderer._renderer.uModelMatrix;
},
/**
@@ -182,6 +298,8 @@ export const Mix = {
applyShader(mask) {
let shader = Renderer.shaderProgram;
const gl = Renderer.drawingContext;
+ const targetIsFramebuffer = !!getActiveFramebuffer();
+ const source = this.captureBlendSource();
// Disable depth test for this compositing draw so the fullscreen rect
// does not write Z=0 into the depth buffer — which would cause any
@@ -197,8 +315,9 @@ export const Mix = {
Renderer.shader(shader);
// Set shader uniforms
- shader.setUniform("u_source", Renderer._renderer);
+ shader.setUniform("u_source", source);
shader.setUniform("u_isBrush", this.isBrush);
+ shader.setUniform("u_flipOutputY", targetIsFramebuffer);
shader.setUniform("u_mask", mask);
shader.setUniform("u_color", this.cachedColor);
diff --git a/src/core/flowfield.js b/src/core/flowfield.js
index 45c09c3..c9d7217 100644
--- a/src/core/flowfield.js
+++ b/src/core/flowfield.js
@@ -1,5 +1,5 @@
import { isMixReady, Cwidth, Cheight, State, Renderer } from "./color.js";
-import { randInt, noise, rr, sin, cos, map } from "./utils.js";
+import { randInt, noise, rr, sin, cos, map, toDegreesSigned } from "./utils.js";
// =============================================================================
// Section: Matrix transformations
@@ -109,7 +109,7 @@ export class Position {
/**
* Calculates the angle of the flow field at the position's current coordinates.
- * @returns {number} - The angle in radians, or 0 if the position is not in the flow field or if the flow field is not active.
+ * @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
@@ -119,11 +119,18 @@ export class Position {
/**
* Moves the position along the flow field by a certain length.
+ * @param {number} _dir - The direction of movement, interpreted using the current p5 angle mode.
* @param {number} _length - The length to move along the field.
- * @param {number} _dir - The direction of movement.
* @param {number} _step_length - The length of each step.
*/
moveTo(_dir, _length, _step_length = 1) {
+ this.movePos(toDegreesSigned(_dir), _length, _step_length);
+ }
+
+ /**
+ * Internal variant of moveTo() that expects a degree value already normalized to the library's internal representation.
+ */
+ _moveToDegrees(_dir, _length, _step_length = 1) {
this.movePos(_dir, _length, _step_length);
}
@@ -204,6 +211,7 @@ State.field = {
// Internal variables for field configuration
let list = new Map();
let resolution, left_x, top_y, num_columns, num_rows;
+const FIELD_ANGLE_MODES = new Set(["degrees", "radians"]);
/**
* Initializes the field grid and sets up the vector field's structure based on the renderer's dimensions.
@@ -225,6 +233,36 @@ function flow_field() {
return list.get(State.field.current).field;
}
+function normalizeFieldAngleMode(options = {}) {
+ const config =
+ typeof options === "string" ? { angleMode: options } : options || {};
+ const angleMode = config.angleMode ?? "degrees";
+
+ if (!FIELD_ANGLE_MODES.has(angleMode)) {
+ throw new Error(
+ `Invalid field angle mode "${angleMode}". Use "degrees" or "radians".`,
+ );
+ }
+
+ return angleMode;
+}
+
+function normalizeFieldAngles(field, angleMode) {
+ if (angleMode !== "radians") return field;
+
+ for (let c = 0; c < field.length; c++) {
+ for (let r = 0; r < field[c].length; r++) {
+ field[c][r] = toDegreesSigned(field[c][r], true);
+ }
+ }
+
+ return field;
+}
+
+function generateField(entry, t) {
+ return normalizeFieldAngles(entry.gen(t, genField()), entry.angleMode);
+}
+
/**
* Regenerates the current vector field using its associated generator function.
* @param {number} [t=0] - An optional time parameter that can affect field generation.
@@ -236,7 +274,7 @@ export function refreshField(t = 0) {
);
}
const currentField = list.get(State.field.current);
- currentField.field = currentField.gen(t, genField());
+ currentField.field = generateField(currentField, t);
}
/**
@@ -267,7 +305,7 @@ export function field(a) {
State.field.isActive = true;
State.field.current = a;
const entry = list.get(a);
- if (!entry.field) entry.field = entry.gen(0, genField());
+ if (!entry.field) entry.field = generateField(entry, 0);
}
/**
@@ -282,9 +320,15 @@ export function noField() {
* Adds a new vector field to the field list with a unique name and a generator function.
* @param {string} name - The unique name for the new vector field.
* @param {Function} funct - The function that generates the field values.
+ * @param {object} [options] - Optional field configuration.
+ * @param {"degrees"|"radians"} [options.angleMode="degrees"] - How the generator's output angles should be interpreted.
*/
-export function addField(name, funct) {
- list.set(name, { gen: funct, field: null });
+export function addField(name, funct, options = {}) {
+ list.set(name, {
+ gen: funct,
+ field: null,
+ angleMode: normalizeFieldAngleMode(options),
+ });
}
/**
diff --git a/src/core/gl/shader.frag b/src/core/gl/shader.frag
index eedd28d..7022183 100644
--- a/src/core/gl/shader.frag
+++ b/src/core/gl/shader.frag
@@ -206,8 +206,8 @@ void main(void) {
vec2 uv1 = vec2(uv.x, 1.0 - uv.y);
// Get source and mask colors
- vec4 source = texture(u_source, uv1);
- vec4 maskColor = texture(u_mask, uv1);
+ vec4 source = texture(u_source, uv1);
+ vec4 maskColor = texture(u_mask, uv1);
if (maskColor.a == 0.0) {
outColor = source;
@@ -234,8 +234,8 @@ void main(void) {
float blurEdge = 0.0;
for (int i = -2; i <= 2; i += 2) {
for (int j = -2; j <= 2; j += 2) {
- vec2 sampleUV = uv1 + vec2(float(i), float(j)) * texelSize;
- float neighborAlpha = texture(u_mask, sampleUV).a * 15.0;
+ vec2 neighborUV = uv1 + 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))));
}
diff --git a/src/core/gl/shader.vert b/src/core/gl/shader.vert
index e93aa3c..d8a2e0a 100644
--- a/src/core/gl/shader.vert
+++ b/src/core/gl/shader.vert
@@ -1,7 +1,12 @@
#version 300 es
+
+uniform bool u_flipOutputY;
+
out vec2 p;
+
void main() {
vec3 v = vec3(-1);
v[gl_VertexID] = 3.;
- gl_Position = vec4(p=v.xy, 0, 1);
+ p = v.xy;
+ gl_Position = vec4(v.x, u_flipOutputY ? -v.y : v.y, 0, 1);
}
\ No newline at end of file
diff --git a/src/core/primitives.js b/src/core/primitives.js
index 88c2bd9..5a94cfc 100644
--- a/src/core/primitives.js
+++ b/src/core/primitives.js
@@ -4,6 +4,7 @@ import {
sin,
cos,
toDegrees,
+ toDegreesSigned,
constrain,
dist,
calcAngle,
@@ -96,21 +97,27 @@ export function circle(x, y, radius, r = false) {
* @param {number} x - Center x.
* @param {number} y - Center y.
* @param {number} radius - Radius.
- * @param {number} start - Radian start angle.
- * @param {number} end - Radian end angle.
+ * @param {number} start - Start angle in the current p5 angle mode.
+ * @param {number} end - End angle in the current p5 angle mode.
*/
export function arc(x, y, radius, start, end) {
+ const startDeg = toDegreesSigned(start);
+ const endDeg = toDegreesSigned(end);
+ const sweepDeg = ((endDeg - startDeg) % 360 + 360) % 360;
+ if (sweepDeg === 0) return;
+
const p = new Plot("curve");
- const startAngle = 270 - toDegrees(start);
- const endAngle = 270 - toDegrees(end);
- const arcAngle = toDegrees(end - start);
- const arcLength = (Math.PI * radius * arcAngle) / 180;
+ const segmentCount = Math.max(1, Math.ceil(sweepDeg / 90));
+ const segmentSweep = sweepDeg / segmentCount;
+ const arcLength = (Math.PI * radius * segmentSweep) / 180;
- p.addSegment(startAngle, arcLength, 1, true);
- p.endPlot(endAngle, 1, true);
+ for (let i = 0; i < segmentCount; i++) {
+ p.addSegment(startDeg + i * segmentSweep + 90, arcLength, 1, true);
+ }
+ p.endPlot(startDeg + sweepDeg + 90, 1, true);
- const startX = x + radius * cos(-startAngle - 90);
- const startY = y + radius * sin(-startAngle - 90);
+ const startX = x + radius * cos(startDeg);
+ const startY = y - radius * sin(startDeg);
p.draw(startX, startY, 1);
}
diff --git a/src/core/utils.js b/src/core/utils.js
index c1adced..c8df5bf 100644
--- a/src/core/utils.js
+++ b/src/core/utils.js
@@ -15,6 +15,15 @@ import { prng_alea } from "esm-seedrandom";
/** @type {RNG} */
let rng = prng_alea(Math.random());
+const _seedCallbacks = [];
+
+/**
+ * Register a callback to be called whenever seed() is invoked.
+ * Used internally by modules that maintain gaussian pools.
+ * @param {Function} cb
+ */
+export const _onSeed = (cb) => _seedCallbacks.push(cb);
+
/**
* Seed the random number generator.
* @param {number|string} s – The seed value.
@@ -22,6 +31,9 @@ let rng = prng_alea(Math.random());
*/
export const seed = (s) => {
rng = prng_alea(s);
+ for (const callback of _seedCallbacks) {
+ callback();
+ }
};
/**
@@ -54,18 +66,6 @@ export const rr = (e = 0, r = 1) => e + rng() * (r - e);
*/
export const rArray = (array) => array[~~(rng() * array.length)];
-/**
- * Generates a random number or picks a random array element.
- * @param {number|Array} [minOrArr=0]
- * @param {number} [max=1]
- * @returns {number}
- */
-export function random(e = 0, r = 1) {
- if (Array.isArray(e)) return rArray(e);
- if (arguments.length === 1) return rng() * e;
- return rr(e, r);
-}
-
/**
* Returns a random integer in [min, max).
* @param {number} min
@@ -201,8 +201,13 @@ export const sin = (angle) => {
* @returns {number}
*/
export const toDegrees = (rad, isRad = false) => {
+ const usesRadians =
+ isRad ||
+ (Renderer &&
+ typeof Renderer.angleMode === "function" &&
+ Renderer.angleMode() === Renderer.RADIANS);
// Only if Renderer.angleMode() is set to radians
- if (Renderer.angleMode() === Renderer.RADIANS || isRad) {
+ if (usesRadians) {
let angle = ((rad * 180) / Math.PI) % 360;
return angle < 0 ? angle + 360 : angle;
} else {
@@ -210,6 +215,21 @@ export const toDegrees = (rad, isRad = false) => {
}
};
+/**
+ * Converts radians to degrees without wrapping the result.
+ * Preserves signed angles so downstream scaling keeps its direction.
+ * @param {number} angle
+ * @param {boolean} [isRad=false]
+ * @returns {number}
+ */
+export const toDegreesSigned = (angle, isRad = false) =>
+ isRad ||
+ (Renderer &&
+ typeof Renderer.angleMode === "function" &&
+ Renderer.angleMode() === Renderer.RADIANS)
+ ? (angle * 180) / Math.PI
+ : angle;
+
// =============================================================================
// Section: Geometry & Transforms
// =============================================================================
diff --git a/src/fill/fill.js b/src/fill/fill.js
index 3341485..0af8c04 100644
--- a/src/fill/fill.js
+++ b/src/fill/fill.js
@@ -21,8 +21,10 @@ import {
map,
randInt,
gaussian,
- rArray,
rotate,
+ cos,
+ sin,
+ _onSeed,
} from "../core/utils.js";
import { isFieldReady, Matrix } from "../core/flowfield.js";
import { Polygon } from "../core/polygon.js";
@@ -32,6 +34,9 @@ import { Plot } from "../core/plot.js";
// Fill State and helpers
// =============================================================================
+// Vertex cap for grow() — set to 0 or false to disable
+const GROW_MAX_VERTS = 1024;
+
/**
* Global fill state settings.
*/
@@ -102,7 +107,15 @@ export function noFill() {
let _polygon;
// Pre-compute gaussians for reuse
+const GAUSSIAN_POOL_SIZE = 512;
const _gaussians = [[], []]; // [a, b]
+function _fillGaussianPools() {
+ for (let i = 0; i < GAUSSIAN_POOL_SIZE; i++) {
+ _gaussians[0][i] = gaussian(0.5, 0.2);
+ _gaussians[1][i] = gaussian(0, 0.02);
+ }
+}
+_onSeed(_fillGaussianPools);
// Helper for direction checking - extracted to reduce duplication
function _isLeft(a, b, c) {
@@ -287,6 +300,62 @@ class FillPoly {
return { v, m, dir };
}
+ /**
+ * Randomly samples a fraction of vertices, keeping their order.
+ * Any sampled vertex outside the original polygon is pulled inward.
+ * @param {number} [ratio=0.3] - Fraction of vertices to keep.
+ * @returns {FillPoly} A new FillPoly with fewer vertices, guaranteed inside the original.
+ */
+ scatter(ratio = 0.3) {
+ const L = this.v.length;
+ const keep = Math.max(3, ~~(L * ratio));
+
+ // Build sorted random indices
+ const indices = [];
+ const step = L / keep;
+ for (let i = 0; i < keep; i++) {
+ indices.push(~~(i * step + rr(0, step * 0.8)));
+ }
+
+ const sv = [], sm = [], sd = [];
+ const mid = this.midP;
+ const sides = _polygon.sides;
+
+ for (const idx of indices) {
+ const j = idx % L;
+ let p = this.v[j];
+
+ // Ray-cast: count intersections from p to far right
+ let crossings = 0;
+ for (const [a, b] of sides) {
+ const ay = a.y, by = b.y;
+ if ((ay > p.y) === (by > p.y)) continue;
+ const t = (p.y - ay) / (by - ay);
+ if (p.x < a.x + t * (b.x - a.x)) crossings++;
+ }
+ // If outside (even crossings), pull toward center
+ if (crossings % 2 === 0) {
+ p = {
+ x: mid.x + (p.x - mid.x) * rr(0.3, 0.6),
+ y: mid.y + (p.y - mid.y) * rr(0.3, 0.6),
+ };
+ }
+
+ sv.push(p);
+ sm.push(this.m[j]);
+ sd.push(!this.dir[j]); // flip direction → grow inward
+ }
+
+ return new FillPoly(sv, sm, this.midP, sd, false, this.sizeX, this.sizeY);
+ }
+
+ /**
+ * Returns a copy with all bleed directions flipped.
+ */
+ flipDirs() {
+ return new FillPoly(this.v, this.m, this.midP, this.dir.map(d => !d), false, this.sizeX, this.sizeY);
+ }
+
/**
* Grows (or shrinks) the polygon vertices to simulate watercolor spread.
* @param {number} [growthFactor=1] - Factor controlling growth.
@@ -294,69 +363,84 @@ class FillPoly {
*/
grow(f = 1) {
// Get trimmed vertices
- const { v: tr_v, m: tr_m, dir: tr_dir } = this.trim(f);
- const len = tr_v.length;
-
- // Pre-allocate arrays for better performance
- const newVerts = [],
- newMods = [],
- newDirs = [];
-
- // Determine bleed direction
- const bleedDirDeg = State.fill.direction === "out" ? -90 : 90;
-
- // Process vertices
- let idx = 0;
- let mod = f === 999 ? rr(0.6, 0.8) : State.fill.bleed_strength;
-
- for (let i = 0; i < len; i++) {
- // compute two gaussians if necessary
- if (_gaussians[0].length < len * 1.5) {
- _gaussians[0].push(gaussian(0.5, 0.2));
- _gaussians[1].push(gaussian(0, 0.02));
+ const { v: tr_v, m: tr_m, dir: tr_dir } = this.trim(f);
+ const len = tr_v.length;
+
+ // Pre-allocate output arrays
+ const outLen = len * 2;
+ const newVerts = new Array(outLen);
+ const newMods = new Array(outLen);
+ const newDirs = new Array(outLen);
+
+ // Determine bleed direction
+ const bleedDirDeg = State.fill.direction === "out" ? -90 : 90;
+
+ // Ensure gaussian pool is filled
+ if (_gaussians[0].length === 0) _fillGaussianPools();
+ const gPool = _gaussians[0], gPoolLen = gPool.length;
+ const g2Pool = _gaussians[1], g2PoolLen = g2Pool.length;
+
+ let idx = 0;
+ let mod = f === 999 ? rr(0.6, 0.8) : State.fill.bleed_strength;
+
+ for (let i = 0; i < len; i++) {
+ const cv = tr_v[i];
+ const nv = tr_v[i + 1 < len ? i + 1 : 0];
+ const mi = tr_m[i];
+ const di = tr_dir[i];
+
+ if (f < 997) mod = mi;
+
+ // Inline rotate: rotDeg = ±bleedDirDeg + small jitter
+ const rotDeg = (di ? bleedDirDeg : -bleedDirDeg) + rr(-1, 1) * 5;
+ const c = cos(rotDeg);
+ const s = sin(rotDeg);
+
+ const sideX = nv.x - cv.x;
+ const sideY = nv.y - cv.y;
+ const dirX = c * sideX + s * sideY;
+ const dirY = c * sideY - s * sideX;
+
+ // Outward distance: inline rArray + rr
+ const d = gPool[~~(rr(0, 1) * gPoolLen)] * rr(0.65, 1.35) * mod;
+
+ // First vertex: original
+ newVerts[idx] = cv;
+ newMods[idx] = mi;
+ newDirs[idx] = di;
+ idx++;
+
+ // Second vertex: midpoint + outward push
+ newVerts[idx] = {
+ x: cv.x + sideX * 0.5 + dirX * d,
+ y: cv.y + sideY * 0.5 + dirY * d,
+ };
+ newMods[idx] = mi + g2Pool[~~(rr(0, 1) * g2PoolLen)];
+ newDirs[idx] = di;
+ idx++;
+ }
+
+ // Cap vertex count to prevent exponential blowup.
+ let fv = newVerts, fm = newMods, fd = newDirs;
+ let growe = GROW_MAX_VERTS / (State.fill.texture_strength);
+ if (growe && idx > growe) {
+ const step = Math.ceil(idx / growe);
+ fv = []; fm = []; fd = [];
+ for (let j = 0; j < idx; j += step) {
+ fv.push(newVerts[j]);
+ fm.push(newMods[j]);
+ fd.push(newDirs[j]);
+ }
+ } else {
+ // Trim pre-allocated arrays to actual size
+ fv.length = idx;
+ fm.length = idx;
+ fd.length = idx;
+ }
+
+ return new FillPoly(fv, fm, this.midP, fd, false, this.sizeX, this.sizeY);
}
- const cv = tr_v[i];
- const nv = i + 1 < len ? tr_v[i + 1] : tr_v[0];
-
- // Use existing modifier or calculate new one
- if (f < 997) mod = tr_m[i];
-
- // Calculate rotation
- const rotDeg = (tr_dir[i] ? bleedDirDeg : -bleedDirDeg) + rr(-1, 1) * 5;
- const sideX = nv.x - cv.x;
- const sideY = nv.y - cv.y;
- const { x: dirX, y: dirY } = rotate(0, 0, sideX, sideY, rotDeg);
-
- // pick a random point along the edge
- const t = 0.5;
- // compute outward distance
- const d = rArray(_gaussians[0]) * rr(0.65, 1.35) * mod;
-
- // first vertex: stay at cv
- newVerts[idx] = cv;
- newMods[idx] = tr_m[i];
- newDirs[idx++] = tr_dir[i];
-
- // second vertex: offset by lerp + outward push
- newVerts[idx] = {
- x: cv.x + sideX * t + dirX * d,
- y: cv.y + sideY * t + dirY * d,
- };
- newMods[idx] = tr_m[i] + rArray(_gaussians[1]);
- newDirs[idx++] = tr_dir[i];
- }
- return new FillPoly(
- newVerts,
- newMods,
- this.midP,
- newDirs,
- false,
- this.sizeX,
- this.sizeY,
- );
- }
-
/**
* Fills the polygon with multiple layers to simulate a watercolor effect.
* @param {Color|string} color - The fill color.
@@ -392,6 +476,8 @@ class FillPoly {
// Create initial polygon
let pol = this.grow();
+ // Create sparse inner polygon from original (pre-grow) vertices
+ const sparse = this.scatter(0.1).grow().scatter(0.75).flipDirs();
let pols;
for (let i = 0; i < numLayers; i++) {
@@ -409,6 +495,7 @@ class FillPoly {
// Draw layers
for (const p of pols) p.grow(999).grow(997).layer(i, size, int, color);
+ sparse.grow(999).flipDirs().grow(997).layer(i, size, int * 1.5 * texture, color);
if (i % 2 === 0)
pol
.grow(darker)
diff --git a/src/hatch/hatch.js b/src/hatch/hatch.js
index d4d604e..e839300 100644
--- a/src/hatch/hatch.js
+++ b/src/hatch/hatch.js
@@ -15,7 +15,7 @@
*/
import { State } from "../core/color.js";
-import { toDegrees, map, cos, sin, rr } from "../core/utils.js";
+import { toDegreesSigned, map, cos, sin, 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";
@@ -59,7 +59,7 @@ export function HatchSetState(state) {
* Activates hatching for subsequent geometries.
*
* @param {number} dist - The distance between hatching lines.
- * @param {number} angle - The angle (in degrees) at which hatching lines are drawn.
+ * @param {number} angle - The hatch angle, interpreted using the current p5 angle mode.
* @param {object} options - Optional parameters to affect the hatching style:
* - rand: Number value to introduce randomness.
* - continuous: Boolean to connect adjacent lines.
@@ -73,7 +73,7 @@ export function hatch(
let s = State.hatch;
s.isActive = true;
s.dist = dist;
- s.angle = angle;
+ s.angle = toDegreesSigned(angle);
s.options = options;
}
@@ -107,7 +107,7 @@ export function noHatch() {
*/
export function createHatch(polygons) {
let dist = State.hatch.dist;
- let angle = toDegrees(State.hatch.angle) % 180; // normalize to [0, 180)
+ let angle = ((State.hatch.angle % 180) + 180) % 180;
let options = State.hatch.options;
// Save current stroke state
@@ -249,7 +249,7 @@ function computeOverallBoundingBox(polygons) {
* Then, if hatch is active, applies the hatching pattern.
*
* @param {number} [_dist] - The distance between hatch lines.
- * @param {number} _angle - The angle (in degrees) for hatching.
+ * @param {number} _angle - The hatch angle, interpreted using the current p5 angle mode.
* @param {object} _options - Optional hatch options.
*/
Polygon.prototype.hatch = function (_dist = false, _angle, _options) {
diff --git a/src/index.js b/src/index.js
index 5d5f5f0..9f4feaf 100644
--- a/src/index.js
+++ b/src/index.js
@@ -25,7 +25,7 @@
*
* // Use the custom brush for a vector-field line:
* brush.field('field_name') // Pick a flowfield
- * brush.flowLine(50, 50, 100, PI / 4); // Draw a line within the vector-field
+ * brush.flowLine(50, 50, 100, PI / 4); // Draw a line within the vector-field; angle follows p5 angleMode()
*
* // Fill textures:
* brush.noStroke();
@@ -107,7 +107,6 @@ export {
noClip,
line,
flowLine,
- preload,
} from "./stroke/stroke.js";
// Section: Hatching
diff --git a/src/stroke/gl_draw.js b/src/stroke/gl_draw.js
index 9577ba8..9a143eb 100644
--- a/src/stroke/gl_draw.js
+++ b/src/stroke/gl_draw.js
@@ -33,6 +33,8 @@ let isLoaded = false,
vao,
buf,
program;
+let loadedWidth = 0,
+ loadedHeight = 0;
const Attr = {},
Frag = {};
@@ -67,9 +69,14 @@ let gpuBufferSize = INITIAL_CAPACITY * 4 * 4; // bytes allocated on GPU
* Initializes WebGL objects if not done already.
*/
export function isReady() {
- if (!isLoaded) {
- isMixReady();
- gl = Mix.glMask.drawingContext;
+ isMixReady();
+
+ const nextGl = Mix.glMask.drawingContext;
+ const needsContextRefresh = !isLoaded || gl !== nextGl;
+ const needsProjectionRefresh =
+ needsContextRefresh || loadedWidth !== Cwidth || loadedHeight !== Cheight;
+
+ if (needsProjectionRefresh) {
projMatrix = new Float32Array([
2 / Cwidth,
0,
@@ -88,42 +95,49 @@ export function isReady() {
0,
1,
]);
-
- // Create shader program and initialize
- program = createProgram(gl, vertSrc, fragSrc);
- gl.useProgram(program);
- gl.enable(gl.BLEND);
- gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);
-
- // Cache attribute and uniform locations
- ["a_position", "a_radius", "a_alpha"].forEach(
- (n) => (Attr[n] = gl.getAttribLocation(program, n)),
- );
- ["u_matrix", "u_color"].forEach(
- (n) => (Frag[n] = gl.getUniformLocation(program, n)),
- );
-
- // Create persistent VAO and VBO
- vao = gl.createVertexArray();
- gl.bindVertexArray(vao);
-
- buf = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, buf);
- gl.bufferData(gl.ARRAY_BUFFER, circleData.byteLength, gl.DYNAMIC_DRAW);
-
- // Set up vertex attributes (only needs to happen once with persistent VAO)
- const stride = 16; // 4 floats × 4 bytes
- gl.enableVertexAttribArray(Attr.a_position);
- gl.vertexAttribPointer(Attr.a_position, 2, gl.FLOAT, false, stride, 0);
- gl.enableVertexAttribArray(Attr.a_radius);
- gl.vertexAttribPointer(Attr.a_radius, 1, gl.FLOAT, false, stride, 8);
- gl.enableVertexAttribArray(Attr.a_alpha);
- gl.vertexAttribPointer(Attr.a_alpha, 1, gl.FLOAT, false, stride, 12);
-
- gl.bindVertexArray(null);
-
- isLoaded = true;
+ loadedWidth = Cwidth;
+ loadedHeight = Cheight;
}
+
+ if (!needsContextRefresh) return;
+
+ gl = nextGl;
+
+ // Create shader program and initialize
+ program = createProgram(gl, vertSrc, fragSrc);
+ gl.useProgram(program);
+ gl.enable(gl.BLEND);
+ gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);
+
+ // Cache attribute and uniform locations
+ ["a_position", "a_radius", "a_alpha"].forEach(
+ (n) => (Attr[n] = gl.getAttribLocation(program, n)),
+ );
+ ["u_matrix", "u_color"].forEach(
+ (n) => (Frag[n] = gl.getUniformLocation(program, n)),
+ );
+
+ // Create persistent VAO and VBO
+ vao = gl.createVertexArray();
+ gl.bindVertexArray(vao);
+
+ buf = gl.createBuffer();
+ gl.bindBuffer(gl.ARRAY_BUFFER, buf);
+ gl.bufferData(gl.ARRAY_BUFFER, circleData.byteLength, gl.DYNAMIC_DRAW);
+ gpuBufferSize = circleData.byteLength;
+
+ // Set up vertex attributes (only needs to happen once with persistent VAO)
+ const stride = 16; // 4 floats × 4 bytes
+ gl.enableVertexAttribArray(Attr.a_position);
+ gl.vertexAttribPointer(Attr.a_position, 2, gl.FLOAT, false, stride, 0);
+ gl.enableVertexAttribArray(Attr.a_radius);
+ gl.vertexAttribPointer(Attr.a_radius, 1, gl.FLOAT, false, stride, 8);
+ gl.enableVertexAttribArray(Attr.a_alpha);
+ gl.vertexAttribPointer(Attr.a_alpha, 1, gl.FLOAT, false, stride, 12);
+
+ gl.bindVertexArray(null);
+
+ isLoaded = true;
}
// =============================================================================
diff --git a/src/stroke/stroke.js b/src/stroke/stroke.js
index a2e4d15..1480cb4 100644
--- a/src/stroke/stroke.js
+++ b/src/stroke/stroke.js
@@ -29,6 +29,7 @@ import {
gaussian,
rArray,
noise,
+ _onSeed,
} from "../core/utils.js";
import { Position, Matrix, isFieldReady } from "../core/flowfield.js";
import { Polygon } from "../core/polygon.js";
@@ -54,6 +55,14 @@ State.stroke = {
let list = new Map();
let Mask = null;
+let _strokeTransform = {
+ a: 1,
+ b: 0,
+ c: 0,
+ d: 1,
+ tx: 0,
+ ty: 0,
+};
/**
* Retrieves a shallow copy of the current stroke state.
@@ -218,12 +227,74 @@ 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 transformPoint(transform, x, y) {
+ return {
+ x: transform.a * x + transform.c * y + transform.tx,
+ y: transform.b * x + transform.d * y + transform.ty,
+ };
+}
+
+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),
+ };
+}
+
+function currentPointInUserSpace() {
+ return transformPoint(
+ _strokeTransform,
+ _position.x - Cwidth / 2,
+ _position.y - Cheight / 2,
+ );
+}
+
/**
* Defines a clipping region for strokes.
+ * The region uses the same coordinate space as brush drawing commands,
+ * with the current p5 transform captured at call time.
* @param {number[]} region - Array as [x1, y1, x2, y2] defining the clipping region.
*/
export function clip(region) {
- State.stroke.clipWindow = 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,
+ };
}
/**
@@ -233,14 +304,6 @@ export function noClip() {
State.stroke.clipWindow = null;
}
-/**
- * Sets the brush density by scaling standard brushes.
- * @param {number} d - Density factor.
- */
-export function setDensity(d) {
- scaleBrushes(d);
-}
-
// ---------------------------------------------------------------------------
// Drawing Variables and Functions
// ---------------------------------------------------------------------------
@@ -257,6 +320,7 @@ 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;
@@ -265,6 +329,10 @@ function initializeDrawingState(x, y, length, plot = false) {
const gaussians = [];
+_onSeed(() => {
+ gaussians.length = 0;
+});
+
/**
* Executes the drawing operation.
* @param {number} angleScale - Angle (in degrees) or scaling factor.
@@ -291,7 +359,7 @@ function draw(angleScale, isPlot) {
angleScale,
i < 10 ? true : false,
)
- : _position.moveTo(angleScale, stepSize, stepSize);
+ : _position._moveToDegrees(angleScale, stepSize, stepSize);
}
restoreState();
}
@@ -447,21 +515,30 @@ function calculateAlpha() {
* @returns {boolean} True if inside clipping area; false otherwise.
*/
function isInsideClippingArea() {
- if (State.stroke.clipWindow)
+ const point = currentPointInUserSpace();
+
+ if (State.stroke.clipWindow) {
+ const local = transformPoint(
+ State.stroke.clipWindow.inverse,
+ point.x,
+ point.y,
+ );
+ const { bounds } = State.stroke.clipWindow;
return (
- _position.x >= State.stroke.clipWindow[0] &&
- _position.x <= State.stroke.clipWindow[2] &&
- _position.y >= State.stroke.clipWindow[1] &&
- _position.y <= State.stroke.clipWindow[3]
+ local.x >= bounds.minX &&
+ local.x <= bounds.maxX &&
+ local.y >= bounds.minY &&
+ local.y <= bounds.maxY
);
- else {
- let w = Cwidth,
- h = Cheight,
- o = Cwidth * 0.05;
- let x = _position.x + Matrix.x();
- let y = _position.y + Matrix.y();
- return x >= -o && x <= w + o && y >= -o && y <= h + o;
}
+
+ let o = Cwidth * 0.05;
+ return (
+ point.x >= -Cwidth / 2 - o &&
+ point.x <= Cwidth / 2 + o &&
+ point.y >= -Cheight / 2 - o &&
+ point.y <= Cheight / 2 + o
+ );
}
/**
@@ -646,7 +723,7 @@ export function line(x1, y1, x2, y2) {
* @param {number} x - Starting x-coordinate.
* @param {number} y - Starting y-coordinate.
* @param {number} length - Length of the stroke.
- * @param {number} dir - Direction (in radians, anticlockwise from the x-axis).
+ * @param {number} dir - Direction, interpreted using the current p5 angle mode.
*/
export function flowLine(x, y, length, dir) {
if (!State.stroke.isActive || !State.stroke.color) {
diff --git a/test/angle_mode_test.html b/test/angle_mode_test.html
new file mode 100644
index 0000000..e88fcb1
--- /dev/null
+++ b/test/angle_mode_test.html
@@ -0,0 +1,83 @@
+<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>p5.brush - Angle Mode Test</title>
+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.min.js"></script>
+ <script src="../dist/p5.brush.js"></script>
+ <style>
+ * {
+ box-sizing: border-box;
+ }
+
+ body {
+ margin: 0;
+ background:
+ radial-gradient(circle at top left, rgba(20, 48, 73, 0.08), transparent 24%),
+ linear-gradient(180deg, #f7f2e7 0%, #ece3d3 100%);
+ color: #22313f;
+ font-family: "Iowan Old Style", "Palatino Linotype", "Book Antiqua", Palatino, serif;
+ }
+
+ main {
+ width: min(1400px, calc(100vw - 24px));
+ margin: 0 auto;
+ padding: 20px 0 28px;
+ }
+
+ .nav {
+ margin-bottom: 18px;
+ font: 12px/1.2 Menlo, Monaco, "Courier New", monospace;
+ }
+
+ .nav a {
+ color: #153e5c;
+ text-decoration: none;
+ }
+
+ .nav a:hover {
+ text-decoration: underline;
+ }
+
+ h1 {
+ margin: 0 0 10px;
+ font-size: clamp(28px, 4vw, 46px);
+ letter-spacing: -0.04em;
+ }
+
+ p {
+ max-width: 900px;
+ margin: 0 0 8px;
+ color: #52616e;
+ line-height: 1.55;
+ }
+
+ .legend {
+ font: 12px/1.4 Menlo, Monaco, "Courier New", monospace;
+ color: #405160;
+ }
+
+ canvas {
+ display: block;
+ margin-top: 18px;
+ box-shadow: 0 18px 50px rgba(50, 39, 24, 0.12);
+ }
+ </style>
+ </head>
+ <body>
+ <main>
+ <div class="nav"><a href="./index.html">All tests</a></div>
+ <h1>Angle Mode Test</h1>
+ <p>
+ Each row compares equivalent degree and radian inputs across public APIs.
+ Matching panels should produce the same direction, curvature, and hatch orientation.
+ </p>
+ <p class="legend">
+ Red guides = native reference geometry. Blue / green marks = p5.brush output.
+ The hatch row intentionally changes <b>angleMode()</b> after <b>brush.hatch()</b> and should still match.
+ </p>
+ <script src="./angle_mode_test.js"></script>
+ </main>
+ </body>
+</html>
\ No newline at end of file
diff --git a/test/angle_mode_test.js b/test/angle_mode_test.js
new file mode 100644
index 0000000..abe5eca
--- /dev/null
+++ b/test/angle_mode_test.js
@@ -0,0 +1,582 @@
+const CANVAS_W = 1360;
+const CANVAS_H = 1260;
+const MARGIN = 36;
+const LABEL_W = 190;
+const PANEL_GAP = 18;
+const ROW_H = 170;
+
+const INK = "#183a59";
+const ALT = "#21695f";
+const REF = "#c74a3d";
+const FRAME = "#cdbfae";
+const PANEL_BG = "#fcf7ef";
+const REF_ALPHA = 110;
+const REF_WEIGHT = 0.9;
+const REF_POINT = 3;
+
+let currentY = MARGIN;
+let labelBuf;
+
+function toRadians(deg) {
+ return (deg * Math.PI) / 180;
+}
+
+function projectPoint(x, y, angleDeg, length) {
+ const rad = toRadians(angleDeg);
+ return {
+ x: x + length * Math.cos(rad),
+ y: y - length * Math.sin(rad),
+ };
+}
+
+function buildPolyline(x, y, steps) {
+ const points = [{ x, y }];
+ let cursor = { x, y };
+
+ for (const step of steps) {
+ cursor = projectPoint(cursor.x, cursor.y, step.angle, step.length);
+ points.push(cursor);
+ }
+
+ return points;
+}
+
+function runPositionSequence(startX, startY, steps, moveRunner) {
+ const pos = new brush.Position(startX + width / 2, startY + height / 2);
+ const pts = [{ x: startX, y: startY }];
+
+ moveRunner(pos, steps, pts);
+
+ return pts;
+}
+
+function maxLineLengthInBox(x, y, angleDeg, bounds) {
+ const rad = toRadians(angleDeg);
+ const dx = Math.cos(rad);
+ const dy = -Math.sin(rad);
+ const candidates = [];
+
+ if (dx > 0) candidates.push((bounds.maxX - x) / dx);
+ else if (dx < 0) candidates.push((bounds.minX - x) / dx);
+
+ if (dy > 0) candidates.push((bounds.maxY - y) / dy);
+ else if (dy < 0) candidates.push((bounds.minY - y) / dy);
+
+ const valid = candidates.filter((value) => Number.isFinite(value) && value >= 0);
+ return valid.length ? Math.min(...valid) : 0;
+}
+
+function drawCenteredReferenceLine(bounds, angleDeg, padding = 10) {
+ const cx = (bounds.minX + bounds.maxX) / 2;
+ const cy = (bounds.minY + bounds.maxY) / 2;
+ const forward = Math.max(
+ 0,
+ maxLineLengthInBox(cx, cy, angleDeg, bounds) - padding,
+ );
+ const backward = Math.max(
+ 0,
+ maxLineLengthInBox(cx, cy, angleDeg + 180, bounds) - padding,
+ );
+ const start = projectPoint(cx, cy, angleDeg + 180, backward);
+ const end = projectPoint(cx, cy, angleDeg, forward);
+
+ push();
+ stroke(199, 74, 61, REF_ALPHA);
+ strokeWeight(REF_WEIGHT);
+ line(start.x, start.y, end.x, end.y);
+ noStroke();
+ fill(199, 74, 61, REF_ALPHA);
+ circle(start.x, start.y, REF_POINT);
+ circle(end.x, end.y, REF_POINT);
+ pop();
+}
+
+function section(title, note = "") {
+ labelBuf.noStroke();
+ labelBuf.fill(29);
+ labelBuf.textStyle(BOLD);
+ labelBuf.textSize(13);
+ labelBuf.text(title, MARGIN, currentY + 14);
+
+ if (note) {
+ labelBuf.fill(92);
+ labelBuf.textStyle(NORMAL);
+ labelBuf.textSize(10);
+ labelBuf.text(note, MARGIN, currentY + 30);
+ }
+
+ push();
+ stroke(215, 205, 191);
+ strokeWeight(1);
+ line(MARGIN, currentY + 40, CANVAS_W - MARGIN, currentY + 40);
+ pop();
+
+ currentY += 58;
+}
+
+function drawRow(label, panels) {
+ const available = CANVAS_W - 2 * MARGIN - LABEL_W;
+ const panelW = (available - PANEL_GAP * (panels.length - 1)) / panels.length;
+
+ labelBuf.noStroke();
+ labelBuf.fill(251, 247, 239, 240);
+ labelBuf.rect(MARGIN - 2, currentY + 6, LABEL_W - 10, ROW_H - 18, 10);
+ labelBuf.fill(46);
+ labelBuf.textStyle(BOLD);
+ labelBuf.textSize(11);
+ labelBuf.text(label, MARGIN, currentY + 20, LABEL_W - 18, ROW_H - 30);
+
+ panels.forEach((panel, index) => {
+ const x = MARGIN + LABEL_W + index * (panelW + PANEL_GAP);
+ const y = currentY;
+
+ push();
+ fill(PANEL_BG);
+ stroke(FRAME);
+ strokeWeight(1);
+ rect(x, y, panelW, ROW_H - 8, 14);
+ pop();
+
+ labelBuf.noStroke();
+ labelBuf.fill(255, 255, 255, 220);
+ labelBuf.rect(x + 10, y + 10, panelW - 20, 20, 9);
+ labelBuf.fill(74);
+ labelBuf.textStyle(NORMAL);
+ labelBuf.textSize(10);
+ labelBuf.text(panel.title, x + 16, y + 24);
+
+ panel.render(x + 14, y + 40, panelW - 28, ROW_H - 56);
+ });
+
+ currentY += ROW_H;
+}
+
+function drawReferenceLine(x, y, length, angleDeg) {
+ const end = projectPoint(x, y, angleDeg, length);
+ push();
+ stroke(199, 74, 61, REF_ALPHA);
+ strokeWeight(REF_WEIGHT);
+ line(x, y, end.x, end.y);
+ fill(199, 74, 61);
+ noStroke();
+ circle(x, y, REF_POINT);
+ circle(end.x, end.y, REF_POINT);
+ pop();
+}
+
+function drawReferencePolyline(x, y, steps, options = {}) {
+ const {
+ dashed = false,
+ showPoints = true,
+ alpha = REF_ALPHA,
+ pointSize = REF_POINT,
+ dash = 7,
+ gap = 5,
+ } = options;
+ const points = buildPolyline(x, y, steps);
+
+ push();
+ stroke(199, 74, 61, alpha);
+ strokeWeight(REF_WEIGHT);
+ noFill();
+ if (dashed) {
+ for (let i = 0; i < points.length - 1; i++) {
+ const p0 = points[i];
+ const p1 = points[i + 1];
+ const dx = p1.x - p0.x;
+ const dy = p1.y - p0.y;
+ const len = Math.hypot(dx, dy);
+ if (len === 0) continue;
+ const ux = dx / len;
+ const uy = dy / len;
+ for (let d = 0; d < len; d += dash + gap) {
+ const from = d;
+ const to = Math.min(d + dash, len);
+ line(
+ p0.x + ux * from,
+ p0.y + uy * from,
+ p0.x + ux * to,
+ p0.y + uy * to,
+ );
+ }
+ }
+ } else {
+ beginShape();
+ for (const pt of points) vertex(pt.x, pt.y);
+ endShape();
+ }
+
+ if (showPoints) {
+ noStroke();
+ fill(199, 74, 61, alpha);
+ for (const pt of points) circle(pt.x, pt.y, pointSize);
+ }
+ pop();
+}
+
+function drawReferenceArc(cx, cy, radius, startDeg, endDeg) {
+ const segments = 36;
+
+ push();
+ stroke(199, 74, 61, REF_ALPHA);
+ strokeWeight(REF_WEIGHT);
+ noFill();
+ beginShape();
+ for (let i = 0; i <= segments; i++) {
+ const t = i / segments;
+ const angle = startDeg + (endDeg - startDeg) * t;
+ const pt = projectPoint(cx, cy, angle, radius);
+ vertex(pt.x, pt.y);
+ }
+ endShape();
+ pop();
+}
+
+function renderFlowLinePanel(x, y, w, h, mode, angleValue) {
+ const angleDeg = 28;
+ const startX = x + 16;
+ const startY = y + h - 14;
+ const len = Math.max(
+ 12,
+ maxLineLengthInBox(startX, startY, angleDeg, {
+ minX: x + 8,
+ minY: y + 8,
+ maxX: x + w - 8,
+ maxY: y + h - 8,
+ }) - 4,
+ );
+
+ drawReferenceLine(startX, startY, len, angleDeg);
+
+ angleMode(mode);
+ brush.noField();
+ brush.clip([x, y, x + w, y + h]);
+ brush.set("pen", INK, 1.8);
+ brush.flowLine(startX, startY, len, angleValue);
+ brush.noClip();
+ angleMode(DEGREES);
+}
+
+function renderArcPanel(x, y, w, h, mode, startValue, endValue) {
+ const cx = x + w / 2;
+ const cy = y + h / 2 + 10;
+ const radius = Math.min(w, h) * 0.3;
+
+ drawReferenceArc(cx, cy, radius, 20, 145);
+
+ angleMode(mode);
+ brush.noField();
+ brush.set("pen", ALT, 1.8);
+ brush.arc(cx, cy, radius, startValue, endValue);
+ angleMode(DEGREES);
+}
+
+function renderManualStrokePanel(x, y, w, h, runner) {
+ const startX = x + 20;
+ const startY = y + h - 16;
+ const steps = [
+ { angle: 24, length: 64, pressure: 1 },
+ { angle: 112, length: 52, pressure: 0.9 },
+ { angle: -18, length: 70, pressure: 1.05 },
+ ];
+
+ drawReferencePolyline(startX, startY, steps);
+
+ brush.clip([x, y, x + w, y + h]);
+ brush.set("2B", INK, 1.7);
+ runner(startX, startY, steps);
+ brush.noClip();
+ angleMode(DEGREES);
+}
+
+function renderPositionPanel(x, y, w, h, runner) {
+ const startX = x + 20;
+ const startY = y + h - 16;
+ const steps = [
+ { angle: 18, length: 58 },
+ { angle: 104, length: 50 },
+ { angle: -24, length: 68 },
+ ];
+
+ brush.noField();
+ const pts = runner(startX, startY, steps);
+
+ brush.clip([x, y, x + w, y + h]);
+ brush.set("marker", INK, 1.05);
+ for (let i = 0; i < pts.length - 1; i++) {
+ brush.line(pts[i].x, pts[i].y, pts[i + 1].x, pts[i + 1].y);
+ }
+ brush.noClip();
+
+ drawReferencePolyline(startX, startY, steps, {
+ dashed: true,
+ showPoints: true,
+ pointSize: 2.4,
+ alpha: 105,
+ dash: 4,
+ gap: 9,
+ });
+
+ push();
+ noStroke();
+ fill(24, 58, 89);
+ for (const pt of pts) circle(pt.x, pt.y, 4);
+ pop();
+}
+
+function renderHatchPanel(x, y, w, h, setupHatch, referenceAngleDeg = 45) {
+ const rx = x + 14;
+ const ry = y + 10;
+ const rw = w - 28;
+ const rh = h - 20;
+ const bounds = {
+ minX: rx,
+ minY: ry,
+ maxX: rx + rw,
+ maxY: ry + rh,
+ };
+
+ push();
+ fill(245, 239, 228);
+ stroke(214, 201, 186);
+ strokeWeight(1);
+ rect(rx, ry, rw, rh, 10);
+ pop();
+
+ drawCenteredReferenceLine(bounds, referenceAngleDeg);
+
+ brush.noField();
+ brush.noStroke();
+ brush.noFill();
+ brush.hatchStyle("pen", INK, 1.35);
+ setupHatch();
+ brush.clip([x, y, x + w, y + h]);
+ brush.rect(rx, ry, rw, rh, "corner");
+ brush.noClip();
+ brush.noHatch();
+ angleMode(DEGREES);
+}
+
+function renderFieldPanel(x, y, w, h, mode, fieldName) {
+ const lines = 6;
+ const startX = x + 16;
+ const len = w - 32;
+
+ angleMode(mode);
+ brush.field(fieldName);
+ brush.clip([x, y, x + w, y + h]);
+ brush.set("pen", ALT, 1.45);
+ for (let i = 0; i < lines; i++) {
+ const sy = y + 12 + (i / (lines - 1)) * (h - 24);
+ brush.flowLine(startX, sy, len, 0);
+ }
+ brush.noClip();
+ brush.noField();
+ angleMode(DEGREES);
+}
+
+function setup() {
+ randomSeed(42);
+ noiseSeed(42);
+
+ createCanvas(CANVAS_W, CANVAS_H, WEBGL);
+ brush.load();
+ brush.scaleBrushes(2.4);
+ angleMode(DEGREES);
+ noLoop();
+
+ labelBuf = createGraphics(CANVAS_W, CANVAS_H);
+ labelBuf.pixelDensity(1);
+ labelBuf.textFont("monospace");
+
+ brush.addField("diagDegreesTest", (_t, field) => {
+ for (let col = 0; col < field.length; col++) {
+ for (let row = 0; row < field[col].length; row++) {
+ field[col][row] = 32;
+ }
+ }
+ return field;
+ });
+
+ brush.addField(
+ "diagRadiansTest",
+ (_t, field) => {
+ for (let col = 0; col < field.length; col++) {
+ for (let row = 0; row < field[col].length; row++) {
+ field[col][row] = toRadians(32);
+ }
+ }
+ return field;
+ },
+ { angleMode: "radians" },
+ );
+}
+
+function draw() {
+ background("#f4ede0");
+ translate(-width / 2, -height / 2);
+
+ section(
+ "DIRECT ANGLE ARGUMENTS",
+ "Matching panels here mean the public function interprets degrees and radians equivalently under the current angleMode().",
+ );
+
+ drawRow("flowLine(dir)", [
+ {
+ title: "angleMode(DEGREES) + 28",
+ render: (x, y, w, h) => renderFlowLinePanel(x, y, w, h, DEGREES, 28),
+ },
+ {
+ title: "angleMode(RADIANS) + PI / 180 * 28",
+ render: (x, y, w, h) => renderFlowLinePanel(x, y, w, h, RADIANS, toRadians(28)),
+ },
+ ]);
+
+ drawRow("arc(start, end)", [
+ {
+ title: "DEGREES input",
+ render: (x, y, w, h) => renderArcPanel(x, y, w, h, DEGREES, 20, 145),
+ },
+ {
+ title: "RADIANS input",
+ render: (x, y, w, h) => renderArcPanel(x, y, w, h, RADIANS, toRadians(20), toRadians(145)),
+ },
+ ]);
+
+ drawRow("beginStroke / move / endStroke", [
+ {
+ title: "all degrees",
+ render: (x, y, w, h) =>
+ renderManualStrokePanel(x, y, w, h, (startX, startY, steps) => {
+ angleMode(DEGREES);
+ brush.beginStroke("segments", startX, startY);
+ for (const step of steps) brush.move(step.angle, step.length, step.pressure);
+ brush.endStroke(steps[steps.length - 1].angle, 1);
+ }),
+ },
+ {
+ title: "all radians",
+ render: (x, y, w, h) =>
+ renderManualStrokePanel(x, y, w, h, (startX, startY, steps) => {
+ angleMode(RADIANS);
+ brush.beginStroke("segments", startX, startY);
+ for (const step of steps)
+ brush.move(toRadians(step.angle), step.length, step.pressure);
+ brush.endStroke(toRadians(steps[steps.length - 1].angle), 1);
+ }),
+ },
+ {
+ title: "mixed angleMode() per call",
+ render: (x, y, w, h) =>
+ renderManualStrokePanel(x, y, w, h, (startX, startY, steps) => {
+ brush.beginStroke("segments", startX, startY);
+ angleMode(DEGREES);
+ brush.move(steps[0].angle, steps[0].length, steps[0].pressure);
+ angleMode(RADIANS);
+ brush.move(toRadians(steps[1].angle), steps[1].length, steps[1].pressure);
+ angleMode(DEGREES);
+ brush.move(steps[2].angle, steps[2].length, steps[2].pressure);
+ angleMode(RADIANS);
+ brush.endStroke(toRadians(steps[steps.length - 1].angle), 1);
+ }),
+ },
+ ]);
+
+ drawRow("Position.moveTo(dir, length, step)", [
+ {
+ title: "all degrees",
+ render: (x, y, w, h) =>
+ renderPositionPanel(x, y, w, h, (startX, startY, steps) => {
+ return runPositionSequence(startX, startY, steps, (pos, steps, pts) => {
+ angleMode(DEGREES);
+ for (const step of steps) {
+ pos.moveTo(step.angle, step.length, step.length);
+ pts.push({ x: pos.x - width / 2, y: pos.y - height / 2 });
+ }
+ });
+ }),
+ },
+ {
+ title: "all radians",
+ render: (x, y, w, h) =>
+ renderPositionPanel(x, y, w, h, (startX, startY, steps) => {
+ return runPositionSequence(startX, startY, steps, (pos, steps, pts) => {
+ angleMode(RADIANS);
+ for (const step of steps) {
+ pos.moveTo(toRadians(step.angle), step.length, step.length);
+ pts.push({ x: pos.x - width / 2, y: pos.y - height / 2 });
+ }
+ });
+ }),
+ },
+ {
+ title: "mixed angleMode() per segment",
+ render: (x, y, w, h) =>
+ renderPositionPanel(x, y, w, h, (startX, startY, steps) => {
+ return runPositionSequence(startX, startY, steps, (pos, steps, pts) => {
+ angleMode(DEGREES);
+ pos.moveTo(steps[0].angle, steps[0].length, steps[0].length);
+ pts.push({ x: pos.x - width / 2, y: pos.y - height / 2 });
+
+ angleMode(RADIANS);
+ pos.moveTo(toRadians(steps[1].angle), steps[1].length, steps[1].length);
+ pts.push({ x: pos.x - width / 2, y: pos.y - height / 2 });
+
+ angleMode(DEGREES);
+ pos.moveTo(steps[2].angle, steps[2].length, steps[2].length);
+ pts.push({ x: pos.x - width / 2, y: pos.y - height / 2 });
+ });
+ }),
+ },
+ ]);
+
+ section(
+ "STORED AND CUSTOM ANGLE STATE",
+ "These rows check the places where angles are stored and used later, or where custom generators provide their own angle convention.",
+ );
+
+ drawRow("hatch(angle)", [
+ {
+ title: "set in degrees, draw in degrees",
+ render: (x, y, w, h) =>
+ renderHatchPanel(x, y, w, h, () => {
+ angleMode(DEGREES);
+ brush.hatch(10, 45, { rand: 0 });
+ }, 45),
+ },
+ {
+ title: "set in radians, draw in radians",
+ render: (x, y, w, h) =>
+ renderHatchPanel(x, y, w, h, () => {
+ angleMode(RADIANS);
+ brush.hatch(10, toRadians(45), { rand: 0 });
+ }, 45),
+ },
+ {
+ title: "set in degrees, switch to radians, then draw",
+ render: (x, y, w, h) =>
+ renderHatchPanel(x, y, w, h, () => {
+ angleMode(DEGREES);
+ brush.hatch(10, 45, { rand: 0 });
+ angleMode(RADIANS);
+ }, 45),
+ },
+ ]);
+
+ drawRow("addField(name, fn, { angleMode })", [
+ {
+ title: "generator writes degrees",
+ render: (x, y, w, h) => renderFieldPanel(x, y, w, h, DEGREES, "diagDegreesTest"),
+ },
+ {
+ title: "generator writes radians",
+ render: (x, y, w, h) => renderFieldPanel(x, y, w, h, RADIANS, "diagRadiansTest"),
+ },
+ {
+ title: "degree field while global mode is radians",
+ render: (x, y, w, h) => renderFieldPanel(x, y, w, h, RADIANS, "diagDegreesTest"),
+ },
+ ]);
+
+ image(labelBuf, 0, 0);
+}
\ No newline at end of file
diff --git a/test/index.html b/test/index.html
index 2095fe1..0928c4d 100644
--- a/test/index.html
+++ b/test/index.html
@@ -1,15 +1,258 @@
<!doctype html>
<html>
<head>
- <title>p5.brush Test Suite</title>
- <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.min.js"></script>
- <script src="../dist/p5.brush.js"></script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>p5.brush Test Index</title>
<style>
- body { margin: 0; background: #111; display: flex; justify-content: center; }
- canvas { display: block; }
+ :root {
+ --paper: #f3eee2;
+ --ink: #1e2a35;
+ --muted: #576574;
+ --line: #d4c8b8;
+ --card: rgba(255, 252, 245, 0.84);
+ --accent-a: #153e5c;
+ --accent-b: #8f3a2f;
+ --accent-c: #2d6a5f;
+ }
+
+ * {
+ box-sizing: border-box;
+ }
+
+ body {
+ margin: 0;
+ min-height: 100vh;
+ color: var(--ink);
+ background:
+ radial-gradient(circle at top left, rgba(21, 62, 92, 0.08), transparent 28%),
+ radial-gradient(circle at top right, rgba(143, 58, 47, 0.08), transparent 26%),
+ linear-gradient(180deg, #faf6ee 0%, var(--paper) 100%);
+ font-family: "Iowan Old Style", "Palatino Linotype", "Book Antiqua", Palatino, serif;
+ }
+
+ main {
+ width: min(1120px, calc(100vw - 48px));
+ margin: 0 auto;
+ padding: 40px 0 56px;
+ }
+
+ header {
+ display: grid;
+ gap: 14px;
+ margin-bottom: 28px;
+ }
+
+ .eyebrow {
+ font-family: Menlo, Monaco, "Courier New", monospace;
+ font-size: 12px;
+ letter-spacing: 0.18em;
+ text-transform: uppercase;
+ color: var(--accent-a);
+ }
+
+ h1 {
+ margin: 0;
+ font-size: clamp(34px, 4vw, 56px);
+ line-height: 0.95;
+ letter-spacing: -0.04em;
+ }
+
+ .intro {
+ max-width: 760px;
+ margin: 0;
+ color: var(--muted);
+ font-size: 17px;
+ line-height: 1.55;
+ }
+
+ .bands {
+ display: grid;
+ gap: 18px;
+ }
+
+ .band {
+ border: 1px solid var(--line);
+ background: linear-gradient(180deg, rgba(255, 252, 246, 0.82), rgba(248, 241, 230, 0.82));
+ backdrop-filter: blur(6px);
+ border-radius: 22px;
+ padding: 22px;
+ box-shadow: 0 18px 50px rgba(58, 46, 32, 0.08);
+ }
+
+ .band h2 {
+ margin: 0 0 6px;
+ font-size: 22px;
+ }
+
+ .band p {
+ margin: 0 0 18px;
+ color: var(--muted);
+ line-height: 1.5;
+ }
+
+ .grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
+ gap: 16px;
+ }
+
+ .card {
+ display: grid;
+ gap: 8px;
+ min-height: 170px;
+ padding: 18px;
+ text-decoration: none;
+ color: inherit;
+ border-radius: 18px;
+ border: 1px solid rgba(48, 41, 30, 0.14);
+ background: var(--card);
+ transition: transform 160ms ease, box-shadow 160ms ease, border-color 160ms ease;
+ box-shadow: 0 10px 22px rgba(53, 42, 29, 0.06);
+ }
+
+ .card:hover {
+ transform: translateY(-2px);
+ box-shadow: 0 16px 30px rgba(53, 42, 29, 0.1);
+ border-color: rgba(21, 62, 92, 0.28);
+ }
+
+ .card h3 {
+ margin: 0;
+ font-size: 18px;
+ }
+
+ .card p {
+ margin: 0;
+ color: var(--muted);
+ line-height: 1.45;
+ }
+
+ .path,
+ .tag {
+ font-family: Menlo, Monaco, "Courier New", monospace;
+ font-size: 12px;
+ }
+
+ .path {
+ color: var(--accent-a);
+ }
+
+ .tag {
+ display: inline-flex;
+ width: fit-content;
+ padding: 4px 8px;
+ border-radius: 999px;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ background: rgba(21, 62, 92, 0.08);
+ color: var(--accent-a);
+ }
+
+ .tag.alt {
+ background: rgba(45, 106, 95, 0.1);
+ color: var(--accent-c);
+ }
+
+ .tag.warn {
+ background: rgba(143, 58, 47, 0.1);
+ color: var(--accent-b);
+ }
+
+ @media (max-width: 720px) {
+ main {
+ width: min(1120px, calc(100vw - 24px));
+ padding-top: 28px;
+ }
+
+ .band {
+ padding: 18px;
+ border-radius: 18px;
+ }
+ }
</style>
</head>
<body>
- <script src="./sketch.js"></script>
+ <main>
+ <header>
+ <div class="eyebrow">p5.brush / test</div>
+ <h1>Test Index</h1>
+ <p class="intro">
+ Browser pages for manual verification plus the automated unit suite.
+ Use this page as the entry point when checking rendering behavior,
+ transforms, angle semantics, and regression coverage.
+ </p>
+ </header>
+
+ <div class="bands">
+ <section class="band">
+ <h2>Browser Tests</h2>
+ <p>Open one of these pages to inspect rendering directly in the browser.</p>
+ <div class="grid">
+ <a class="card" href="./visual_suite.html">
+ <span class="tag">Browser</span>
+ <h3>Visual API Suite</h3>
+ <p>Wide coverage page that exercises most public APIs and logs error-message checks to the console.</p>
+ <span class="path">test/visual_suite.html</span>
+ </a>
+
+ <a class="card" href="./angle_mode_test.html">
+ <span class="tag warn">New</span>
+ <h3>Angle Mode Test</h3>
+ <p>Compares degrees, radians, mixed mode changes, stored hatch angles, low-level Position movement, and custom fields.</p>
+ <span class="path">test/angle_mode_test.html</span>
+ </a>
+
+ <a class="card" href="./offscreen_target_test.html">
+ <span class="tag warn">New</span>
+ <h3>Offscreen Targets</h3>
+ <p>Checks brush.load() on p5.Graphics and custom-sized main framebuffers, with pixel-count diagnostics.</p>
+ <span class="path">test/offscreen_target_test.html</span>
+ </a>
+
+ <a class="card" href="./instance_mode_test.html">
+ <span class="tag warn">New</span>
+ <h3>Instance Mode</h3>
+ <p>Checks brush.instance(p) on the instance canvas, an instance p5.Graphics target, and an instance-owned main framebuffer.</p>
+ <span class="path">test/instance_mode_test.html</span>
+ </a>
+
+ <a class="card" href="./transform_test.html">
+ <span class="tag">Browser</span>
+ <h3>Transform Alignment</h3>
+ <p>Checks that brush strokes and fills align with native p5 reference geometry under translate, rotate, and scale.</p>
+ <span class="path">test/transform_test.html</span>
+ </a>
+
+ <a class="card" href="./pushpop_test.html">
+ <span class="tag">Browser</span>
+ <h3>Push / Pop State</h3>
+ <p>Verifies that p5 push/pop restores stroke, brush, fill, and hatch state correctly.</p>
+ <span class="path">test/pushpop_test.html</span>
+ </a>
+
+ <a class="card" href="./field_explorer.html">
+ <span class="tag">Browser</span>
+ <h3>Flow Field Explorer</h3>
+ <p>Interactive field inspector for comparing built-in fields with adjustable density and line length.</p>
+ <span class="path">test/field_explorer.html</span>
+ </a>
+ </div>
+ </section>
+
+ <section class="band">
+ <h2>Automated Tests</h2>
+ <p>The browser pages above are visual checks. The file below contains the scripted regression suite.</p>
+ <div class="grid">
+ <a class="card" href="./unit.test.js">
+ <span class="tag alt">Automated</span>
+ <h3>Unit Test Source</h3>
+ <p>Utility, angle conversion, hatch capture, Position movement, and custom field angle-mode regression tests.</p>
+ <span class="path">test/unit.test.js</span>
+ </a>
+ </div>
+ </section>
+ </div>
+ </main>
</body>
</html>
diff --git a/test/instance_mode_test.html b/test/instance_mode_test.html
new file mode 100644
index 0000000..6d1b575
--- /dev/null
+++ b/test/instance_mode_test.html
@@ -0,0 +1,85 @@
+<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>p5.brush - Instance Mode Test</title>
+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.min.js"></script>
+ <script src="../dist/p5.brush.js"></script>
+ <style>
+ * {
+ box-sizing: border-box;
+ }
+
+ body {
+ margin: 0;
+ background:
+ radial-gradient(circle at top left, rgba(20, 48, 73, 0.08), transparent 24%),
+ linear-gradient(180deg, #f7f2e7 0%, #ece3d3 100%);
+ color: #22313f;
+ font-family: "Iowan Old Style", "Palatino Linotype", "Book Antiqua", Palatino, serif;
+ }
+
+ main {
+ width: min(1400px, calc(100vw - 24px));
+ margin: 0 auto;
+ padding: 20px 0 28px;
+ }
+
+ .nav {
+ margin-bottom: 18px;
+ font: 12px/1.2 Menlo, Monaco, "Courier New", monospace;
+ }
+
+ .nav a {
+ color: #153e5c;
+ text-decoration: none;
+ }
+
+ .nav a:hover {
+ text-decoration: underline;
+ }
+
+ h1 {
+ margin: 0 0 10px;
+ font-size: clamp(28px, 4vw, 46px);
+ letter-spacing: -0.04em;
+ }
+
+ p {
+ max-width: 980px;
+ margin: 0 0 8px;
+ color: #52616e;
+ line-height: 1.55;
+ }
+
+ .legend {
+ font: 12px/1.4 Menlo, Monaco, "Courier New", monospace;
+ color: #405160;
+ }
+
+ canvas {
+ display: block;
+ margin-top: 18px;
+ box-shadow: 0 18px 50px rgba(50, 39, 24, 0.12);
+ }
+ </style>
+ </head>
+ <body>
+ <main>
+ <div class="nav"><a href="./index.html">All tests</a></div>
+ <h1>Instance Mode Test</h1>
+ <p>
+ This page is rendered entirely by a <b>new p5((p) =&gt; {})</b> sketch and checks that
+ <b>brush.instance(p)</b> and <b>brush.load()</b> behave correctly in instance mode.
+ </p>
+ <p class="legend">
+ The three rows cover direct drawing on the instance canvas, drawing into an instance-owned
+ <b>p5.Graphics</b> target, and drawing into an instance-owned main <b>p5.Framebuffer</b>.
+ All three should show the same scene with the same textures.
+ </p>
+ <div id="instance-mode-app"></div>
+ <script src="./instance_mode_test.js"></script>
+ </main>
+ </body>
+</html>
\ No newline at end of file
diff --git a/test/instance_mode_test.js b/test/instance_mode_test.js
new file mode 100644
index 0000000..12b99a7
--- /dev/null
+++ b/test/instance_mode_test.js
@@ -0,0 +1,306 @@
+const sketch = (p) => {
+ const CANVAS_W = 1360
+ const CANVAS_H = 960
+ const MARGIN = 36
+ const INFO_W = 270
+ const PANEL_GAP = 18
+ const ROW_H = 250
+ const ROW_GAP = 28
+ const PANEL_W = CANVAS_W - 2 * MARGIN - INFO_W - PANEL_GAP
+ const TARGET_H = ROW_H - 56
+
+ const PAPER = "#fcf7ef"
+ const FRAME = "#d1c3b1"
+ const INK = "#21313f"
+ const MUTED = "#5d6a74"
+ const TARGET_BG = [247, 241, 231]
+ const BLUE = "#174d71"
+ const GREEN = "#4d8b76"
+ const OCHRE = "#d38f47"
+ const RED = "#8a3d2f"
+ const FAIL_FG = "#8b3328"
+
+ const GEOMETRY_SEEDS = {
+ line: 101,
+ rect: 202,
+ arc: 303,
+ circle: 404,
+ }
+
+ let labelBuf
+ let results = []
+ let targetDensity = 1
+
+ function prepareBrushRandom(seed) {
+ p.randomSeed(seed)
+ p.noiseSeed(seed)
+ }
+
+ function renderBrushSceneLocal(w, h) {
+ brush.noField()
+ brush.noClip()
+ brush.noHatch()
+ brush.noFill()
+
+ brush.set("marker", BLUE, 1.05)
+ prepareBrushRandom(GEOMETRY_SEEDS.line)
+ brush.line(26, 32, w - 28, h * 0.36)
+
+ brush.noStroke()
+ brush.fill(OCHRE, 86)
+ brush.hatch(11, 35, { rand: 0 })
+ brush.hatchStyle("pen", RED, 1.05)
+ prepareBrushRandom(GEOMETRY_SEEDS.rect)
+ brush.rect(38, h * 0.52, w * 0.34, h * 0.22)
+ brush.noHatch()
+
+ brush.set("HB", INK, 0.95)
+ brush.noFill()
+ prepareBrushRandom(GEOMETRY_SEEDS.arc)
+ brush.arc(w * 0.72, h * 0.28, Math.min(w, h) * 0.14, 18, 158)
+
+ brush.noStroke()
+ brush.fill(GREEN, 92)
+ prepareBrushRandom(GEOMETRY_SEEDS.circle)
+ brush.circle(w * 0.74, h * 0.64, Math.min(w, h) * 0.23)
+ }
+
+ function renderSceneOnSurface(surface, x, y, w, h) {
+ surface.push()
+ surface.translate(x, y)
+ renderBrushSceneLocal(w, h)
+ surface.pop()
+ }
+
+ function paintTargetBackground(surface, w, h) {
+ surface.push()
+ surface.noStroke()
+ surface.background(...TARGET_BG)
+ surface.pop()
+ }
+
+ function runGraphicsTest() {
+ const result = {
+ title: "Instance p5.Graphics",
+ subtitle: "const pg = p.createGraphics(..., p.WEBGL)",
+ note: "Tests brush.load(pg) after brush.instance(p), with the offscreen result presented back on the instance canvas.",
+ error: null,
+ displayTarget: null,
+ renderDirect: null,
+ }
+
+ try {
+ const pg = p.createGraphics(PANEL_W, TARGET_H, p.WEBGL)
+ pg.pixelDensity(targetDensity)
+ pg.angleMode(p.DEGREES)
+ paintTargetBackground(pg, PANEL_W, TARGET_H)
+
+ brush.load(pg)
+ renderSceneOnSurface(pg, -PANEL_W / 2, -TARGET_H / 2, PANEL_W, TARGET_H)
+ brush.load()
+
+ result.displayTarget = pg
+ } catch (error) {
+ result.error = error.message
+ try {
+ brush.load()
+ } catch (_error) {}
+ }
+
+ return result
+ }
+
+ function runFramebufferTest() {
+ const result = {
+ title: "Instance Framebuffer",
+ subtitle: "const fb = p.createFramebuffer({ width, height })",
+ note: "Tests brush.load(fb) inside the active framebuffer scope of the instance sketch, then presents it on the instance canvas.",
+ error: null,
+ displayTarget: null,
+ renderDirect: null,
+ }
+
+ try {
+ const fb = p.createFramebuffer({
+ width: PANEL_W,
+ height: TARGET_H,
+ density: targetDensity,
+ })
+
+ fb.draw(() => {
+ p.background(...TARGET_BG)
+ brush.load(fb)
+ renderSceneOnSurface(p, -PANEL_W / 2, -TARGET_H / 2, PANEL_W, TARGET_H)
+ })
+
+ brush.load()
+ result.displayTarget = fb
+ } catch (error) {
+ result.error = error.message
+ try {
+ brush.load()
+ } catch (_error) {}
+ }
+
+ return result
+ }
+
+ function drawCard(result, x, y, w, h) {
+ labelBuf.stroke(FRAME)
+ labelBuf.strokeWeight(1)
+ labelBuf.fill("#fffaf1")
+ labelBuf.rect(x, y, w, h, 22)
+
+ labelBuf.noStroke()
+ labelBuf.fill(INK)
+ labelBuf.textFont("Iowan Old Style")
+ labelBuf.textSize(22)
+ labelBuf.text(result.title, x + 18, y + 30)
+
+ labelBuf.fill(MUTED)
+ labelBuf.textFont("Menlo")
+ labelBuf.textSize(11)
+ labelBuf.text(result.subtitle, x + 18, y + 52, w - 36)
+
+ labelBuf.fill(MUTED)
+ labelBuf.textFont("Iowan Old Style")
+ labelBuf.textSize(13)
+ labelBuf.textLeading(18)
+ labelBuf.text(result.note, x + 18, y + 98, w - 36)
+
+ if (result.error) {
+ labelBuf.fill(FAIL_FG)
+ labelBuf.textFont("Menlo")
+ labelBuf.textSize(12)
+ labelBuf.text(`error: ${result.error}`, x + 18, y + h - 50, w - 36)
+ }
+ }
+
+ function drawPanelFrame(x, y, w, h) {
+ p.stroke(FRAME)
+ p.strokeWeight(1)
+ p.fill(PAPER)
+ p.rect(x, y, w, h, 22)
+
+ p.stroke(230, 223, 211)
+ p.line(x + 14, y + 56, x + w - 14, y + 56)
+ }
+
+ function drawPanelLabel(x, y, title, subtitle) {
+ labelBuf.noStroke()
+ labelBuf.fill(INK)
+ labelBuf.textFont("Iowan Old Style")
+ labelBuf.textSize(18)
+ labelBuf.text(title, x + 16, y + 26)
+
+ labelBuf.fill(MUTED)
+ labelBuf.textFont("Menlo")
+ labelBuf.textSize(11)
+ labelBuf.text(subtitle, x + 16, y + 44)
+ }
+
+ function drawDirectInstanceContent(x, y, w, h) {
+ brush.load()
+
+ p.push()
+ p.translate(x, y)
+ p.noStroke()
+ p.fill(...TARGET_BG)
+ p.rect(0, 0, w, h)
+ p.noFill()
+ p.stroke(222, 214, 201)
+ p.strokeWeight(1)
+ p.rect(10, 10, w - 20, h - 20, 16)
+ renderBrushSceneLocal(w, h)
+ p.pop()
+ }
+
+ function drawTargetPanel(result, x, y, w, h) {
+ drawPanelFrame(x, y, w, h)
+ drawPanelLabel(x, y, "Instance-mode output", result.subtitle)
+
+ if (result.renderDirect) {
+ result.renderDirect(x, y + 56, w, TARGET_H)
+ } else if (result.displayTarget) {
+ p.image(result.displayTarget, x, y + 56, w, TARGET_H)
+ }
+
+ if (result.error) {
+ labelBuf.noStroke()
+ labelBuf.fill(FAIL_FG)
+ labelBuf.textFont("Menlo")
+ labelBuf.textSize(12)
+ labelBuf.text(result.error, x + 16, y + 84, w - 32)
+ }
+ }
+
+ function drawHeader() {
+ labelBuf.noStroke()
+ labelBuf.fill(INK)
+ labelBuf.textFont("Iowan Old Style")
+ labelBuf.textSize(34)
+ labelBuf.text("Instance Mode Coverage", MARGIN, 42)
+
+ labelBuf.fill(MUTED)
+ labelBuf.textSize(16)
+ labelBuf.textLeading(24)
+ labelBuf.text(
+ "This entire page is produced by a new p5((p) => {}) sketch. Matching scenes across the three rows indicate that brush.instance(p) works on the instance canvas, on instance p5.Graphics targets, and on instance-owned main framebuffers.",
+ MARGIN,
+ 72,
+ CANVAS_W - 2 * MARGIN,
+ )
+ }
+
+ p.setup = () => {
+ brush.instance(p)
+
+ const canvas = p.createCanvas(CANVAS_W, CANVAS_H, p.WEBGL)
+ canvas.parent("instance-mode-app")
+ p.imageMode(p.CORNER)
+ p.angleMode(p.DEGREES)
+ targetDensity = p.pixelDensity()
+
+ labelBuf = p.createGraphics(CANVAS_W, CANVAS_H)
+ labelBuf.pixelDensity(targetDensity)
+
+ brush.load()
+ brush.scaleBrushes(4)
+
+ results = [
+ {
+ title: "Instance Canvas",
+ subtitle: "brush.instance(p) + brush.load()",
+ note: "Tests the direct instance-mode path on the sketch canvas itself, with no intermediate target object.",
+ error: null,
+ displayTarget: null,
+ renderDirect: drawDirectInstanceContent,
+ },
+ runGraphicsTest(),
+ runFramebufferTest(),
+ ]
+
+ p.noLoop()
+ }
+
+ p.draw = () => {
+ p.background(244, 238, 226)
+ p.translate(-p.width / 2, -p.height / 2)
+ labelBuf.clear()
+
+ drawHeader()
+
+ const outputX = MARGIN + INFO_W + PANEL_GAP
+ let y = 144
+
+ for (const result of results) {
+ drawCard(result, MARGIN, y, INFO_W, ROW_H)
+ drawTargetPanel(result, outputX, y, PANEL_W, ROW_H)
+ y += ROW_H + ROW_GAP
+ }
+
+ p.image(labelBuf, 0, 0)
+ }
+}
+
+new p5(sketch)
\ No newline at end of file
diff --git a/test/offscreen_target_test.html b/test/offscreen_target_test.html
new file mode 100644
index 0000000..a28dbea
--- /dev/null
+++ b/test/offscreen_target_test.html
@@ -0,0 +1,83 @@
+<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>p5.brush - Offscreen Target Test</title>
+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.min.js"></script>
+ <script src="../dist/p5.brush.js"></script>
+ <style>
+ * {
+ box-sizing: border-box;
+ }
+
+ body {
+ margin: 0;
+ background:
+ radial-gradient(circle at top left, rgba(20, 48, 73, 0.08), transparent 24%),
+ linear-gradient(180deg, #f7f2e7 0%, #ece3d3 100%);
+ color: #22313f;
+ font-family: "Iowan Old Style", "Palatino Linotype", "Book Antiqua", Palatino, serif;
+ }
+
+ main {
+ width: min(1400px, calc(100vw - 24px));
+ margin: 0 auto;
+ padding: 20px 0 28px;
+ }
+
+ .nav {
+ margin-bottom: 18px;
+ font: 12px/1.2 Menlo, Monaco, "Courier New", monospace;
+ }
+
+ .nav a {
+ color: #153e5c;
+ text-decoration: none;
+ }
+
+ .nav a:hover {
+ text-decoration: underline;
+ }
+
+ h1 {
+ margin: 0 0 10px;
+ font-size: clamp(28px, 4vw, 46px);
+ letter-spacing: -0.04em;
+ }
+
+ p {
+ max-width: 980px;
+ margin: 0 0 8px;
+ color: #52616e;
+ line-height: 1.55;
+ }
+
+ .legend {
+ font: 12px/1.4 Menlo, Monaco, "Courier New", monospace;
+ color: #405160;
+ }
+
+ canvas {
+ display: block;
+ margin-top: 18px;
+ box-shadow: 0 18px 50px rgba(50, 39, 24, 0.12);
+ }
+ </style>
+ </head>
+ <body>
+ <main>
+ <div class="nav"><a href="./index.html">All tests</a></div>
+ <h1>Offscreen Target Test</h1>
+ <p>
+ This page checks that p5.brush can target offscreen drawing surfaces and still composite them back correctly.
+ Each row first renders offscreen, then draws a fresh main-canvas reference after switching back with <b>brush.load()</b>.
+ </p>
+ <p class="legend">
+ Pass = the offscreen target produced a visible image and its changed-pixel count cleared the threshold.
+ Rows cover <b>createGraphics(WEBGL)</b> and a custom-sized main <b>createFramebuffer()</b>.
+ </p>
+ <script src="./offscreen_target_test.js"></script>
+ </main>
+ </body>
+</html>
\ No newline at end of file
diff --git a/test/offscreen_target_test.js b/test/offscreen_target_test.js
new file mode 100644
index 0000000..fa88ae4
--- /dev/null
+++ b/test/offscreen_target_test.js
@@ -0,0 +1,379 @@
+const CANVAS_W = 1360
+const CANVAS_H = 780
+const MARGIN = 36
+const INFO_W = 250
+const PANEL_GAP = 18
+const ROW_H = 250
+const ROW_GAP = 28
+const PANEL_W = (CANVAS_W - 2 * MARGIN - INFO_W - PANEL_GAP * 2) / 2
+const TARGET_H = ROW_H - 56
+const PIXEL_THRESHOLD = Math.round(PANEL_W * TARGET_H * 0.004)
+
+const PAPER = "#fcf7ef"
+const FRAME = "#d1c3b1"
+const INK = "#21313f"
+const MUTED = "#5d6a74"
+const TARGET_BG = [247, 241, 231]
+const BLUE = "#174d71"
+const GREEN = "#4d8b76"
+const OCHRE = "#d38f47"
+const RED = "#8a3d2f"
+const PASS_BG = "#dbe8cf"
+const PASS_FG = "#355f27"
+const FAIL_BG = "#f2d3cb"
+const FAIL_FG = "#8b3328"
+
+let results = []
+let labelBuf
+let targetDensity = 1
+
+const GEOMETRY_SEEDS = {
+ line: 101,
+ rect: 202,
+ arc: 303,
+ circle: 404,
+}
+
+function prepareBrushRandom(seed) {
+ randomSeed(seed)
+ noiseSeed(seed)
+}
+
+function renderBrushSceneLocal(w, h) {
+ brush.noField()
+ brush.noClip()
+ brush.noHatch()
+ brush.noFill()
+
+ brush.set("marker", BLUE, 1.05)
+ prepareBrushRandom(GEOMETRY_SEEDS.line)
+ brush.line(26, 32, w - 28, h * 0.36)
+
+ brush.noStroke()
+ brush.fill(OCHRE, 86)
+ brush.hatch(11, 35, { rand: 0 })
+ brush.hatchStyle("pen", RED, 1.05)
+ prepareBrushRandom(GEOMETRY_SEEDS.rect)
+ brush.rect(38, h * 0.52, w * 0.34, h * 0.22)
+ brush.noHatch()
+
+ brush.set("HB", INK, 0.95)
+ brush.noFill()
+ prepareBrushRandom(GEOMETRY_SEEDS.arc)
+ brush.arc(w * 0.72, h * 0.28, Math.min(w, h) * 0.14, 18, 158)
+
+ brush.noStroke()
+ brush.fill(GREEN, 92)
+ prepareBrushRandom(GEOMETRY_SEEDS.circle)
+ brush.circle(w * 0.74, h * 0.64, Math.min(w, h) * 0.23)
+}
+
+function renderSceneOnSurface(surface, x, y, w, h) {
+ surface.push()
+ surface.translate(x, y)
+ renderBrushSceneLocal(w, h)
+ surface.pop()
+}
+
+function paintTargetBackground(surface, w, h) {
+ surface.push()
+ surface.noStroke()
+ surface.background(...TARGET_BG)
+ surface.pop()
+}
+
+function countChangedPixels(target) {
+ target.loadPixels()
+
+ let count = 0
+ for (let i = 0; i < target.pixels.length; i += 4) {
+ const r = target.pixels[i]
+ const g = target.pixels[i + 1]
+ const b = target.pixels[i + 2]
+ const alpha = target.pixels[i + 3]
+
+ if (
+ alpha > 8 &&
+ (Math.abs(r - TARGET_BG[0]) +
+ Math.abs(g - TARGET_BG[1]) +
+ Math.abs(b - TARGET_BG[2]) > 18)
+ ) {
+ count++
+ }
+ }
+
+ return count
+}
+
+function finalizeResult(result) {
+ result.pass = !result.error && result.pixels >= PIXEL_THRESHOLD
+ return result
+}
+
+function runGraphicsTest() {
+ const result = {
+ title: "p5.Graphics",
+ subtitle: "createGraphics(..., WEBGL)",
+ note: "This is the direct offscreen buffer path already documented by brush.load(buffer).",
+ pixels: 0,
+ error: null,
+ target: null,
+ displayTarget: null,
+ }
+
+ try {
+ const pg = createGraphics(PANEL_W, TARGET_H, WEBGL)
+ pg.pixelDensity(targetDensity)
+ pg.angleMode(DEGREES)
+ paintTargetBackground(pg, PANEL_W, TARGET_H)
+
+ brush.load(pg)
+ renderSceneOnSurface(pg, -PANEL_W / 2, -TARGET_H / 2, PANEL_W, TARGET_H)
+ brush.load()
+
+ result.target = pg
+ result.displayTarget = pg
+ result.pixels = countChangedPixels(pg)
+ } catch (error) {
+ result.error = error.message
+ try {
+ brush.load()
+ } catch (_error) {}
+ }
+
+ return finalizeResult(result)
+}
+
+function runMainFramebufferTest() {
+ const result = {
+ title: "Main Framebuffer",
+ subtitle: "createFramebuffer({ width, height })",
+ note: "This row checks the framebuffer adapter on the main canvas, including custom target dimensions.",
+ pixels: 0,
+ error: null,
+ target: null,
+ displayTarget: null,
+ }
+
+ try {
+ const fb = createFramebuffer({
+ width: PANEL_W,
+ height: TARGET_H,
+ density: targetDensity,
+ })
+
+ fb.draw(() => {
+ background(...TARGET_BG)
+
+ brush.load(fb)
+ renderSceneOnSurface(window.self.p5.instance, -PANEL_W / 2, -TARGET_H / 2, PANEL_W, TARGET_H)
+ })
+
+ brush.load()
+
+ result.target = fb
+ result.displayTarget = fb
+ result.pixels = countChangedPixels(fb)
+ } catch (error) {
+ result.error = error.message
+ try {
+ brush.load()
+ } catch (_error) {}
+ }
+
+ return finalizeResult(result)
+}
+
+function drawBadge(label, x, y, pass) {
+ labelBuf.noStroke()
+ labelBuf.fill(pass ? PASS_BG : FAIL_BG)
+ labelBuf.rect(x, y, 70, 24, 999)
+ labelBuf.fill(pass ? PASS_FG : FAIL_FG)
+ labelBuf.textFont("Menlo")
+ labelBuf.textSize(11)
+ labelBuf.textAlign(CENTER, CENTER)
+ labelBuf.text(label, x + 35, y + 12)
+ labelBuf.textAlign(LEFT, BASELINE)
+}
+
+function drawFittedMonoLine(text, x, y, maxWidth, startSize = 12, minSize = 8) {
+ let size = startSize
+ labelBuf.textSize(size)
+
+ while (size > minSize && labelBuf.textWidth(text) > maxWidth) {
+ size -= 0.5
+ labelBuf.textSize(size)
+ }
+
+ labelBuf.text(text, x, y)
+}
+
+function drawCard(result, x, y, w, h) {
+ labelBuf.stroke(FRAME)
+ labelBuf.strokeWeight(1)
+ labelBuf.fill("#fffaf1")
+ labelBuf.rect(x, y, w, h, 22)
+
+ labelBuf.noStroke()
+ labelBuf.fill(INK)
+ labelBuf.textFont("Iowan Old Style")
+ labelBuf.textSize(22)
+ labelBuf.text(result.title, x + 18, y + 30)
+
+ labelBuf.fill(MUTED)
+ labelBuf.textFont("Menlo")
+ drawFittedMonoLine(result.subtitle, x + 18, y + 52, w - 36, 12, 8)
+
+ drawBadge(result.pass ? "PASS" : "FAIL", x + 18, y + 66, result.pass)
+
+ labelBuf.fill(MUTED)
+ labelBuf.textFont("Iowan Old Style")
+ labelBuf.textSize(12)
+ labelBuf.textLeading(17)
+ labelBuf.text(result.note, x + 18, y + 110, w - 36, 54)
+
+ labelBuf.textFont("Menlo")
+ labelBuf.fill(INK)
+ drawFittedMonoLine(`changed pixels: ${result.pixels}`, x + 18, y + h - 54, w - 36, 12, 8.5)
+ drawFittedMonoLine(`pass threshold: ${PIXEL_THRESHOLD}`, x + 18, y + h - 34, w - 36, 12, 8.5)
+
+ if (result.error) {
+ labelBuf.fill(FAIL_FG)
+ labelBuf.text(`error: ${result.error}`, x + 18, y + h - 82, w - 36, 24)
+ return
+ }
+}
+
+function drawPanelFrame(x, y, w, h) {
+ stroke(FRAME)
+ strokeWeight(1)
+ fill(PAPER)
+ rect(x, y, w, h, 22)
+
+ stroke(230, 223, 211)
+ line(x + 14, y + 56, x + w - 14, y + 56)
+}
+
+function drawPanelLabel(x, y, title, subtitle) {
+ labelBuf.noStroke()
+ labelBuf.fill(INK)
+ labelBuf.textFont("Iowan Old Style")
+ labelBuf.textSize(18)
+ labelBuf.text(title, x + 16, y + 26)
+
+ labelBuf.fill(MUTED)
+ labelBuf.textFont("Menlo")
+ labelBuf.textSize(11)
+ labelBuf.text(subtitle, x + 16, y + 44)
+}
+
+function drawReferencePanel(x, y, w, h) {
+ drawPanelFrame(x, y, w, h)
+ drawPanelLabel(
+ x,
+ y,
+ "Main-canvas reference",
+ "Drawn after the offscreen pass with brush.load()",
+ )
+
+ brush.load()
+
+ push()
+ translate(x, y + 56)
+ noStroke()
+ fill(...TARGET_BG)
+ rect(0, 0, w, TARGET_H)
+ noFill()
+ stroke(222, 214, 201)
+ strokeWeight(1)
+ rect(10, 10, w - 20, TARGET_H - 20, 16)
+ renderBrushSceneLocal(w, TARGET_H)
+ pop()
+}
+
+function drawTargetPanel(result, x, y, w, h) {
+ drawPanelFrame(x, y, w, h)
+ drawPanelLabel(x, y, "Offscreen target output", result.subtitle)
+ drawBadge(result.pass ? "PASS" : "FAIL", x + w - 88, y + 16, result.pass)
+
+ if (result.displayTarget || result.target) {
+ image(result.displayTarget || result.target, x, y + 56, w, TARGET_H)
+ }
+
+ if (result.error) {
+ labelBuf.noStroke()
+ labelBuf.fill(FAIL_FG)
+ labelBuf.textFont("Menlo")
+ labelBuf.textSize(12)
+ labelBuf.text(result.error, x + 16, y + 84, w - 32)
+ }
+}
+
+function drawHeader() {
+ labelBuf.noStroke()
+ labelBuf.fill(INK)
+ labelBuf.textFont("Iowan Old Style")
+ labelBuf.textSize(34)
+ labelBuf.text("Offscreen Target Coverage", MARGIN, 42)
+
+ labelBuf.fill(MUTED)
+ labelBuf.textSize(16)
+ labelBuf.textLeading(24)
+ labelBuf.text(
+ "Each row renders the same brush scene offscreen and then composites it back with image(). Matching reference panels and non-zero pixel counts indicate that brush.load() is targeting the correct renderer.",
+ MARGIN,
+ 72,
+ CANVAS_W - 2 * MARGIN,
+ )
+}
+
+function setup() {
+ createCanvas(CANVAS_W, CANVAS_H, WEBGL)
+ imageMode(CORNER)
+ angleMode(DEGREES)
+ targetDensity = pixelDensity()
+
+ labelBuf = createGraphics(CANVAS_W, CANVAS_H)
+ labelBuf.pixelDensity(targetDensity)
+
+ brush.load()
+ brush.scaleBrushes(4)
+
+ results = [
+ runGraphicsTest(),
+ runMainFramebufferTest(),
+ ]
+
+ console.table(
+ results.map((result) => ({
+ target: result.title,
+ pass: result.pass,
+ pixels: result.pixels,
+ error: result.error ?? "",
+ })),
+ )
+
+ noLoop()
+}
+
+function draw() {
+ background(244, 238, 226)
+ translate(-width / 2, -height / 2)
+ labelBuf.clear()
+
+ drawHeader()
+
+ const referenceX = MARGIN + INFO_W + PANEL_GAP
+ const targetX = referenceX + PANEL_W + PANEL_GAP
+
+ let y = 144
+
+ for (const result of results) {
+ drawCard(result, MARGIN, y, INFO_W, ROW_H)
+ drawReferencePanel(referenceX, y, PANEL_W, ROW_H)
+ drawTargetPanel(result, targetX, y, PANEL_W, ROW_H)
+ y += ROW_H + ROW_GAP
+ }
+
+ image(labelBuf, 0, 0)
+}
\ No newline at end of file
diff --git a/test/sketch.js b/test/sketch.js
index 8a66a75..eb8038e 100644
--- a/test/sketch.js
+++ b/test/sketch.js
@@ -4,7 +4,7 @@
// Opens a canvas that exercises every public API function.
// Error-message tests are logged to the browser console.
//
-// Run: open test/index.html (after npm run build)
+// Run: open test/visual_suite.html
// ============================================================
// ---- Layout constants ----
diff --git a/test/unit.test.js b/test/unit.test.js
index 59f2eb8..a2319b9 100644
--- a/test/unit.test.js
+++ b/test/unit.test.js
@@ -5,23 +5,57 @@
// Run: npm test
// ============================================================
-import { describe, it, expect, vi, beforeAll } from "vitest";
+import { describe, it, expect, vi, beforeAll, beforeEach } from "vitest";
+
+const { currentAngleMode, mockState, plotInstances } = vi.hoisted(() => ({
+ currentAngleMode: { value: "radians" },
+ mockState: {},
+ plotInstances: [],
+}));
// Mock color.js (pulls in GLSL shaders and WebGL — not available in Node)
vi.mock("../src/core/color.js", () => ({
Renderer: {
- angleMode: () => "radians",
+ angleMode: () => currentAngleMode.value,
RADIANS: "radians",
DEGREES: "degrees",
+ _renderer: {
+ uModelMatrix: {
+ mat4: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
+ },
+ },
},
Mix: {},
- State: {},
+ State: mockState,
Cwidth: 800,
Cheight: 600,
isCanvasReady: () => {},
isMixReady: () => {},
}));
+vi.mock("../src/stroke/stroke.js", () => ({
+ BrushState: () => ({}),
+ BrushSetState: () => {},
+ set: () => {},
+ line: () => {},
+}));
+
+vi.mock("../src/core/polygon.js", () => ({
+ Polygon: class Polygon {},
+}));
+
+vi.mock("../src/core/plot.js", () => ({
+ Plot: class Plot {
+ constructor(type) {
+ this.type = type;
+ this.addSegment = vi.fn();
+ this.endPlot = vi.fn();
+ this.draw = vi.fn();
+ plotInstances.push(this);
+ }
+ },
+}));
+
import {
map,
constrain,
@@ -34,7 +68,28 @@ import {
randInt,
seed,
weightedRand,
+ toDegreesSigned,
} from "../src/core/utils.js";
+import { arc } from "../src/core/primitives.js";
+import { Position, addField, field as activateField, noField } from "../src/core/flowfield.js";
+import { hatch } from "../src/hatch/hatch.js";
+
+beforeEach(() => {
+ currentAngleMode.value = "radians";
+ plotInstances.length = 0;
+ if (mockState.field) {
+ mockState.field.isActive = false;
+ mockState.field.current = null;
+ mockState.field.wiggle = 1;
+ }
+ if (mockState.hatch) {
+ mockState.hatch.isActive = false;
+ mockState.hatch.dist = 5;
+ mockState.hatch.angle = 45;
+ mockState.hatch.options = {};
+ mockState.hatch.hBrush = false;
+ }
+});
// ---- map() ----
describe("map()", () => {
@@ -122,6 +177,17 @@ describe("cos() and sin()", () => {
});
});
+describe("toDegreesSigned()", () => {
+ it("matches p5's default radians mode when angleMode() has not been changed", () => {
+ expect(toDegreesSigned(Math.PI / 2)).toBeCloseTo(90);
+ });
+
+ it("converts radians without wrapping signed angles", () => {
+ currentAngleMode.value = "radians";
+ expect(toDegreesSigned(-Math.PI / 4)).toBeCloseTo(-45);
+ });
+});
+
// ---- rotate() ----
describe("rotate()", () => {
it("rotating (1,0) by 90° around origin gives ~(0,1)", () => {
@@ -263,3 +329,92 @@ describe("weightedRand()", () => {
expect(counts.common).toBeGreaterThan(480);
});
});
+
+describe("hatch()", () => {
+ it("captures the hatch angle using the current angle mode at call time", () => {
+ currentAngleMode.value = "radians";
+ hatch(8, Math.PI / 2);
+ expect(mockState.hatch.angle).toBeCloseTo(90);
+
+ currentAngleMode.value = "degrees";
+ expect(mockState.hatch.angle).toBeCloseTo(90);
+ });
+});
+
+describe("arc()", () => {
+ it("matches p5-style top-half arc geometry in degrees mode", () => {
+ currentAngleMode.value = "degrees";
+
+ arc(100, 120, 40, 20, 145);
+
+ const plot = plotInstances.at(-1);
+ expect(plot).toBeTruthy();
+ expect(plot.addSegment).toHaveBeenCalledTimes(2);
+ expect(plot.addSegment.mock.calls[0][0]).toBeCloseTo(110);
+ expect(plot.addSegment.mock.calls[1][0]).toBeCloseTo(172.5);
+ expect(plot.endPlot).toHaveBeenCalledWith(235, 1, true);
+ expect(plot.draw.mock.calls[0][0]).toBeCloseTo(100 + 40 * cos(20));
+ expect(plot.draw.mock.calls[0][1]).toBeCloseTo(120 - 40 * sin(20));
+ });
+
+ it("uses equivalent geometry in radians mode", () => {
+ currentAngleMode.value = "radians";
+
+ arc(100, 120, 40, (20 * Math.PI) / 180, (145 * Math.PI) / 180);
+
+ const plot = plotInstances.at(-1);
+ expect(plot).toBeTruthy();
+ expect(plot.addSegment).toHaveBeenCalledTimes(2);
+ expect(plot.addSegment.mock.calls[0][0]).toBeCloseTo(110);
+ expect(plot.endPlot).toHaveBeenCalledWith(235, 1, true);
+ expect(plot.draw.mock.calls[0][0]).toBeCloseTo(100 + 40 * cos(20));
+ expect(plot.draw.mock.calls[0][1]).toBeCloseTo(120 - 40 * sin(20));
+ });
+});
+
+describe("Position.moveTo()", () => {
+ it("interprets its public direction argument using the current angle mode", () => {
+ currentAngleMode.value = "radians";
+ noField();
+
+ const pos = new Position(400, 300);
+ pos.moveTo(Math.PI / 2, 10, 10);
+
+ expect(pos.x).toBeCloseTo(400, 3);
+ expect(pos.y).toBeCloseTo(290, 3);
+ });
+
+ it("keeps the internal degree-based path stable", () => {
+ currentAngleMode.value = "radians";
+ noField();
+
+ const pos = new Position(400, 300);
+ pos._moveToDegrees(90, 10, 10);
+
+ expect(pos.x).toBeCloseTo(400, 3);
+ expect(pos.y).toBeCloseTo(290, 3);
+ });
+});
+
+describe("addField()", () => {
+ it("supports custom fields declared in radians without losing signed direction", () => {
+ addField(
+ "neg-radians-test",
+ (_t, field) => {
+ for (let c = 0; c < field.length; c++) {
+ for (let r = 0; r < field[c].length; r++) {
+ field[c][r] = -Math.PI / 4;
+ }
+ }
+ return field;
+ },
+ { angleMode: "radians" },
+ );
+
+ activateField("neg-radians-test");
+ mockState.field.wiggle = 2;
+
+ const pos = new Position(400, 300);
+ expect(pos.angle()).toBeCloseTo(-90, 3);
+ });
+});
diff --git a/test/visual_suite.html b/test/visual_suite.html
new file mode 100644
index 0000000..4e1f059
--- /dev/null
+++ b/test/visual_suite.html
@@ -0,0 +1,47 @@
+<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8" />
+ <title>p5.brush Visual Suite</title>
+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.min.js"></script>
+ <script src="../dist/p5.brush.js"></script>
+ <style>
+ * {
+ box-sizing: border-box;
+ }
+
+ body {
+ margin: 0;
+ background: #111;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ }
+
+ .nav {
+ width: 100%;
+ padding: 12px 18px;
+ font: 12px/1.2 Menlo, Monaco, "Courier New", monospace;
+ background: rgba(12, 12, 12, 0.92);
+ border-bottom: 1px solid rgba(255, 255, 255, 0.08);
+ }
+
+ .nav a {
+ color: #f0dca8;
+ text-decoration: none;
+ }
+
+ .nav a:hover {
+ text-decoration: underline;
+ }
+
+ canvas {
+ display: block;
+ }
+ </style>
+ </head>
+ <body>
+ <div class="nav"><a href="./index.html">All tests</a></div>
+ <script src="./sketch.js"></script>
+ </body>
+</html>
\ No newline at end of file