Unlock custom brushes, natural fill effects and intuitive hatching in p5.js
new 2.0.0-alpha release for p5 2.x compatibility, modularity, ∫∫new features, and bug fixes. See CHANGELOG.md for details.
Alejandro52f0ad9c8932
diff --git a/.gitignore b/.gitignoreindex 8aedf59..403c22f 100644--- a/.gitignore+++ b/.gitignore@@ -1,3 +1,4 @@node_modules/package-lock.json-src/index_noP5.js\ No newline at end of file+src/index_noP5.js+.claude/\ No newline at end of filediff --git a/README.md b/README.mdindex 4874e5d..d79d76a 100644--- a/README.md+++ b/README.md@@ -2,13 +2,7 @@# p5.brush.js-p5.brush.js is a versatile library for the p5.js ecosystem, tailored for artists, designers, and hobbyists who wish to explore natural textures in generative art. This library extends the drawing capabilities of p5.js by introducing a rich set of tools that allow for the creation of dynamic and customizable brushes, vector-fields, and fill modes.--With p5.brush.js, you can easily configure and manage intricate drawing systems, inject life into your sketches with organic movements, and apply complex vector fields to control the flow and form of strokes. The library is designed with texture quality in mind, and may only be suitable for high-resolution artworks, not real-time interactive pieces.--Whether you're looking to simulate natural media, create patterned backgrounds, or design intricate particle systems, p5.brush.js offers the functionalities to turn your vision into reality. The API is straightforward and modular, providing both high-level functions for quick setup and in-depth customization options for advanced users.--Embrace the full potential of your creative coding projects with p5.brush.js, where every stroke is a brush with possibility.+p5.brush.js adds natural drawing tools to p5.js — pencils, charcoal, markers, watercolor fills, hatch patterns, and vector fields that bend strokes organically. It's built for generative art and high-resolution printing.[Visit the library website here! (more examples soon)](https://p5-brush.cargo.site/)@@ -23,7 +17,7 @@ Embrace the full potential of your creative coding projects with p5.brush.js, wh## Installation-Important note: p5.brush requires p5.js 1.11 or higher.+Important note: p5.brush requires p5.js 2.x or higher.### Local Installation@@ -65,38 +59,31 @@ If you are using p5 and p5.brush as modules, you will need to use instance mode.### Note for p5 instance mode-By default, all p5.js functions are in the global namespace (i.e. bound to the window object), meaning you can call them simply ellipse(), fill(), etc. However, this might be inconvenient if you are mixing with other JS libraries (synchronously or asynchronously) or writing long programs of your own. p5.js currently supports a way around this problem called "instance mode". In instance mode, all p5 functions are bound up in a single variable instead of polluting your global namespace.--If you plan to use p5 instance mode, you need to load p5.brush in a specific way:--- Use `brush.instance()` before the setup and draw functions, pointing to your sketch id and the p5 function argument-- Example:+In instance mode, p5 functions are scoped to a variable instead of the global namespace — useful when mixing with other libraries or using p5 as an ES module.- ```javascript- let sketch = function(p) {- let x = 100;- let y = 100;+Call `brush.instance(p)` inside your sketch function before `setup` and `draw`. After that, all `brush.*` calls work normally without any `p.` prefix.- // Register instance method here, sending your function arg p- brush.instance(p)+```javascript+const sketch = (p) => {+ // Tell p5.brush which p5 instance to use+ brush.instance(p);- p.setup = function() {- // Important to create the canvas in WEBGL mode- p.createCanvas(700, 410, p.WEBGL);- // Don't forget to load the library after canvas is created- brush.load()- };+ p.setup = () => {+ // Canvas must be in WEBGL mode+ p.createCanvas(700, 410, p.WEBGL);+ // Initialize p5.brush after canvas is created+ brush.load();+ };- p.draw = function() {- p.background(0);- brush.fill("red", 75);- brush.rect(x, y, 50, 50);- };+ p.draw = () => {+ p.background(240);+ brush.set("HB", "#333", 1);+ brush.line(100, 100, 400, 300);};+};- let myp5 = new p5(sketch);- ```+new p5(sketch);+```---@@ -127,30 +114,29 @@ p5.brush.js provides a comprehensive API for creating complex drawings and effec| Section | Functions | | Section | Functions ||--------------------------------------------|---------------------|---|--------------------------------------------|---------------------|-| [Utility](#utility-functions) | brush.push() | | [Hatch Operations](#hatch-operations) | brush.hatch() |-| | brush.pop() | | | brush.noHatch() |-| | brush.rotate() | | | brush.setHatch() |-| | brush.scale() | | [Geometry](#geometry) | brush.line() |-| | brush.reDraw() | | | brush.flowLine() |-| | brush.reBlend() | | | brush.beginStroke() |-| [Vector-Fields](#vector-fields) | brush.field() | | | brush.segment() |-| | brush.noField() | | | brush.endStroke() |-| | brush.refreshField()| | | brush.spline() |-| | brush.listFields() | | | brush.plot() |-| | brush.addField() | | | brush.rect() |-| [Brush Management](#brush-management) | brush.box() | | | brush.circle() |-| | brush.add() | | | brush.beginShape() |-| | brush.clip() | | | brush.vertex() |-| | brush.noClip() | | | brush.endShape() |-| [Stroke Operations](#stroke-operations) | brush.set() | | | brush.polygon() |-| | brush.pick() | | [Configuration](#optional-configuration) | brush.seed() |-| | brush.stroke() | | | brush.load() |-| | brush.noStroke() | | | brush.preload() |-| | brush.strokeWeight()| | | brush.colorCache() |-| [Fill Operations](#fill-operations) | brush.fill() | | | brush.scaleBrushes()|-| | brush.noFill() | | | brush.remove() |-| | brush.bleed() | | | brush.instance() |-| | brush.fillTexture() | | [Classes](#exposed-classes) | brush.Polygon() |+| [Utility](#utility-functions) | | | [Hatch Operations](#hatch-operations) | brush.hatch() |+| | | | | brush.noHatch() |+| [Vector-Fields](#vector-fields) | brush.field() | | | brush.hatchStyle() |+| | brush.noField() | | [Geometry](#geometry) | brush.line() |+| | brush.refreshField()| | | brush.flowLine() |+| | brush.listFields() | | | brush.beginStroke() |+| | brush.addField() | | | brush.move() |+| | brush.wiggle() | | | brush.endStroke() |+| [Brush Management](#brush-management) | brush.box() | | | brush.spline() |+| | brush.add() | | | brush.rect() |+| | brush.clip() | | | brush.circle() |+| | brush.noClip() | | | brush.arc() |+| [Stroke Operations](#stroke-operations) | brush.set() | | | brush.beginShape() |+| | brush.pick() | | | brush.vertex() |+| | brush.stroke() | | | brush.endShape() |+| | brush.noStroke() | | | brush.polygon() |+| | brush.strokeWeight()| | [Configuration](#optional-configuration) | brush.seed() |+| [Fill Operations](#fill-operations) | brush.fill() | | | brush.noiseSeed() |+| | brush.noFill() | | | brush.load() |+| | brush.fillBleed() | | | brush.preload() |+| | brush.fillTexture() | | | brush.scaleBrushes()|+| | | | | brush.instance() |+| | | | [Classes](#exposed-classes) | brush.Polygon() || | | | | brush.Plot() || | | | | brush.Position() |@@ -161,30 +147,7 @@ p5.brush.js provides a comprehensive API for creating complex drawings and effec----- `brush.push()`- - **Description**: The push() function saves the current brush, hatch, and fill settings and transformations, while pop() restores these settings. Note that these functions are always used together.--- `brush.pop()`- - **Description**: The push() function saves the current brush, hatch, and fill settings and transformations, while pop() restores these settings. Note that these functions are always used together.-------- `brush.rotate(angle)`- - **Description**: Rotates following shapes by the amount specified by the angle parameter. This function accounts for angleMode(), so angles can be entered in either RADIANS or DEGREES. Objects are always rotated around their relative position to the origin and positive numbers rotate objects in an anti-clockwise direction. Transformations apply to everything that happens after and subsequent calls to the function accumulate the effect. This function can be further controlled by brush.push() and brush.pop().-------- `brush.scale(scale)`- - **Description**: Increases or decreases the size of shapes and strokes by expanding or contracting vertices. Objects always scale from their relative origin to the coordinate system. Scale values are specified as decimal percentages. For example, the function call scale(2.0) increases the dimension of a shape by 200%. Transformations apply to everything that happens after and subsequent calls to the function multiply the effect. For example, calling scale(2.0) and then scale(1.5) is the same as scale(3.0).-------- `brush.reDraw()`- - **Description**: p5.brush uses several buffers and caches to make the drawing operations more performant. Use the reDraw() function if you want to force noBlend brushes to be drawn into the canvas. This function is designed to help maintain the correct draw order for the different strokes and shapes.--- `brush.reBlend()`- - **Description**: p5.brush uses several buffers and caches to make the drawing operations more performant. Use the reDraw() function if you want to force Blend brushes to be drawn into the canvas. This function is designed to help maintain the correct draw order for the different strokes and shapes.-+> **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.---@@ -202,7 +165,7 @@ Vector Fields allow for dynamic control over brush stroke behavior, enabling the- **Description**: Activates a named vector field. When a vector field is active, it influences the flow and direction of the brush strokes for shapes drawn thereafter. It is important to note that certain shapes may be exempt from this influence; such exceptions will be clearly documented in the API for each specific geometry.- **Parameters**:- `name` (String): The identifier for the vector field to be activated. This can be a name of one of the predefined fields or a custom field created with `brush.addField()`.- - **Default Fields**: The library comes with a set of built-in vector fields: `curved`, `truncated`, `zigzag`, `seabed`, and `waves`. These, as well as any custom fields added, can be activated using this function.+ - **Default Fields**: The library comes with a set of built-in vector fields: `hand`, `curved`, `zigzag`, `waves`, `seabed`, `spiral`, and `columns`. These, as well as any custom fields added, can be activated using this function.- **Usage**:```javascript// To activate the "waves" vector field@@ -216,13 +179,22 @@ Vector Fields allow for dynamic control over brush stroke behavior, enabling the---- `brush.noField()`- - **Description**: Deactivates the currently active vector field, returning the drawing behavior to its default state where shapes are not influenced by any vector field. Any shapes drawn after this function call will not be affected by the previously active vector field.+ - **Description**: Deactivate the currently active vector field, returning the drawing behavior to its default state where shapes are not influenced by any vector field.- **Usage**:```javascript- // Deactivate the current vector fieldbrush.noField();```- Use this function when you want to draw shapes that are unaffected by the directional flow of any vector field, effectively resetting the drawing behavior to its original state.++---++- `brush.wiggle(wiggle)`+ - **Description**: Activate the built-in `"hand"` vector field with a given wiggle intensity. A shorthand for adding a subtle hand-drawn wobble to strokes without calling `brush.field("hand")` directly.+ - **Parameters**:+ - `wiggle` (Number): Intensity of the wobble, e.g. 1–10.+ - **Usage**:+ ```javascript+ brush.wiggle(3);+ ```---@@ -243,18 +215,15 @@ Vector Fields allow for dynamic control over brush stroke behavior, enabling the---- `brush.listFields()`- - **Description**: Retrieves an iterator containing the names of all the available vector fields within the system. This includes both the default fields provided by the library and any custom fields that have been added using `brush.addField()`.- - **Returns**: `Iterator<string>` - An iterator that yields the names of the vector fields.+ - **Description**: Retrieve an array containing the names of all available vector fields, including built-in fields and any custom fields added with `brush.addField()`.+ - **Returns**: `Array<string>` - An array of vector field names.- **Usage**:```javascript- // Get an iterator of all vector field nameslet fieldNames = brush.listFields();- // Loop through the names using the iteratorfor (let name of fieldNames) {console.log(name);}```- Use `brush.listFields()` to access the names of all existing vector fields, which can then be used to activate or modify fields as needed.---@@ -263,41 +232,26 @@ Vector Fields allow for dynamic control over brush stroke behavior, enabling the---- `brush.addField(name, generatorFunction)`- - **Description**: Adds a custom vector field to the list of available fields. This advanced function requires a unique name for the field and a generator function that defines the behavior of the vector field over time.+ - **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): A unique identifier for the vector field.- - `generatorFunction` (Function): A function that generates the field values. It takes a time parameter `t`, loops through the vector field cells, assigns angular values based on custom logic, and returns the modified `field` array.- - **Default Fields**: The library includes several pre-defined vector fields. Users can add their own to extend the functionality.- - **Usage**: To add a vector field that creates wave-like motions:- ```javascript- brush.addField("waves", function(t, field) {- let sinrange = random(10,15) + 5 * sin(t);- let cosrange = random(3,6) + 3 * cos(t);- let baseAngle = random(20,35);- for (let column = 0; column < field.length; column++) {- for (let row = 0; row < field[0].length; row++) {- let angle = sin(sinrange * column) * (baseAngle * cos(row * cosrange)) + random(-3,3);- field[column][row] = angle;- }- }- return field;- });- ```- - **Note**: It's important that your loops create a grid of `field.length` x `field[0].length`. It's necessary to fill all the `field` cells with a numeric value. Return this array when you've filled the values. **The angles MUST BE in Degrees**.+ - `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.+ - **Simplest example** — a diagonal flow that slowly rotates over time:```javascript- brush.addField("name_field", function(t, field) {- let field = FF.genField()- // Related functions for angle calculation- for (let i = 0; i < field.length; i++) {- for (let j = 0; j < field[0].length; j++) {- // Related functions for angle calculation here- field[i][j] = CalculatedAngle;+ brush.addField("diagonal", function(t, field) {+ for (let col = 0; col < field.length; col++) {+ for (let row = 0; row < field[0].length; row++) {+ field[col][row] = 45 + t * 10; // 45° angle, changes with time}}- return field;+ return field; // always return field at the end!});++ brush.field("diagonal"); // activate it```-+ - **Tip**: You don't have to use `t` at all if you don't need animation. Just fill the grid and return it.+---@@ -323,72 +277,69 @@ Functions for managing brush behaviors and properties.---- `brush.add(name, params)`- - **Description**: Adds a new brush to the brush list with specified parameters, defining the brush's behavior and appearance. This function allows for extensive customization, enabling the creation of unique brush types suited to various artistic needs.+ - **Description**: Creates a new brush with your own settings. Once added, you use it just like any built-in brush with `brush.set("myBrush", color, size)`.- **Parameters**:- - `name` (String): A unique identifier for the brush.- - `params` (BrushParameters): An object containing the parameters for the brush. The parameters include:- - `type`: (`standard` | `spray` | `marker` | `custom` | `image`) The tip type.- - `weight`: Base size of the brush tip, in canvas units.- - `vibration`: Vibration of the lines, affecting spread, in canvas units.- - `definition`: (Number from 0-1) Between 0 and 1, defining clarity. Unnecessary for custom, marker, and image type brushes.- - `quality`: Higher values lead to a more continuous line. Unnecessary for custom, marker, and image type brushes.- - `opacity`: (Number from 0-255) Base opacity of the brush (affected by pressure).- - `spacing`: Spacing between points in the brush stroke, in canvas units.- - `blend`: (Boolean) Enables or disables realistic color mixing (default true for marker, custom, and image brushes).- - `pressure`: An object or function defining the pressure sensitivity.- - `type` : 'standard" or 'custom". Use standard for simple gauss bell curves. Use 'custom' for custom pressure curves.- - `min_max`: (Array [min, max]) Define min and max pressure (reverse for inverted presure).- - `curve`: function or array.- - Standard pressure: [a, b] - If 'standard' pressure curve, pick a and b values for the gauss curve. a is max horizontal mvt of the bell, b changes the slope.- - Custom pressure: (x) => function - If 'custom' pressure curve, define the curve function with a curve equation receiving values from 0 to 1, returning values from 0 to 1. Use https://mycurvefit.com/- - `tip`: (For custom types) A function defining the geometry of the brush tip. Remove if unnecessary.- - `image`: (For image types) The url path to your image, which MUST be in the same baseURL. Remove if unnecessary.- - `rotate`: (`none` | `natural` | `random`) Defines the tip angle rotation.+ - `name` (String): A name for your brush — pick anything you like.+ - `params` (Object): An object with the brush settings:+ - `type`: The kind of brush tip. Choose one: `"default"` (pencil-like), `"spray"` (scattered dots), `"marker"` (flat solid), `"custom"` (you draw the tip shape), `"image"` (use a photo as the tip).+ - `weight`: How thick the brush is, in canvas units.+ - `scatter`: How much the stroke wobbles sideways. Higher = more spread. (in canvas units)+ - `sharpness`: A number from 0 to 1. Lower = softer/fuzzier edge. Only matters for `"default"` type.+ - `grain`: Controls how dense the texture is. Higher = smoother, more continuous line. Only matters for `"default"` type.+ - `opacity`: How opaque each mark is, from 0 to 255. Pressure also affects this.+ - `spacing`: Gap between brush tip stamps along the stroke. `1` means no overlap, lower values create denser strokes.+ - `blend`: `true` or `false`. Enables realistic paint mixing. On by default for `"marker"`, `"custom"`, and `"image"` types.+ - `pressure`: Controls how the brush size changes from start to end of a stroke. Use a simple array — the easiest way:+ - `[start, end]` — e.g. `[2, 0.5]` starts thick and gets thin.+ - `[start, middle, end]` — e.g. `[0.5, 2, 0.5]` starts thin, swells in the middle, ends thin.+ - Or a function `(t) => value` where `t` goes from 0 (start) to 1 (end), for full control.+ - `tip`: Only for `"custom"` type. A function where you draw the tip shape using p5.js commands inside a small graphics buffer `_m`.+ - `image`: Only for `"image"` type. An object with a `src` property pointing to your image file: `{ src: "./tip.jpg" }`.+ - `rotate`: How the tip rotates as it moves. `"none"` keeps it fixed, `"natural"` follows the stroke direction, `"random"` spins randomly.- **Usage**:```javascript- // You create an image brush like this:- brush.add("watercolor", {- type: "image",- weight: 10,- vibration: 2,- opacity: 30,- spacing: 1.5,- blend: true,- pressure: {- type: "custom",- min_max: [0.5,1.2],- // This formula implies that the pressure changes in a linear distribution through the whole length of the line.- // Minimum pressure at the start, maximum pressure at the end.- curve: (x) => 1-x- },- image: {- src: "./brush_tips/brush.jpg",- },- rotate: "random",- })-- // You create a custom tip brush like this:- brush.add("watercolor", {+ // Image brush — use a photo as the brush tip.+ // IMPORTANT: use "await" so the image loads before drawing,+ // and make sure your setup() function is declared "async"!+ async function setup() {+ createCanvas(800, 800, WEBGL);+ brush.load();++ await brush.add("watercolor", {+ type: "image",+ weight: 10,+ scatter: 2,+ opacity: 30,+ spacing: 1.5,+ blend: true,+ pressure: [1, 0.5], // starts thick, ends thin+ image: { src: "./brush_tips/brush.jpg" },+ rotate: "random",+ });++ // Now you can draw with it!+ brush.set("watercolor", "blue", 1);+ brush.line(100, 100, 400, 100);+ }++ // Custom tip brush — no await needed, just call brush.add() normally+ brush.add("diamond", {type: "custom",weight: 5,- vibration: 0.08,+ scatter: 0.08,opacity: 23,spacing: 0.6,blend: true,- pressure: {- type: "standard",- min_max: [1.35,1],- curve: [0.35,0.25] // Values for the bell curve- },+ pressure: [0.5, 1.5, 0.5], // thin → thick → thintip: (_m) => {- // in this example, the tip is composed of two squares, rotated 45 degrees- // Always execute drawing functions within the _m buffer!- _m.rotate(45), _m.rect(-1.5,-1.5,3,3), _m.rect(1,1,1,1);+ // Draw inside _m using normal p5.js drawing commands+ _m.rotate(45);+ _m.rect(-1.5, -1.5, 3, 3);},rotate: "natural",- })+ });```- By using `brush.add()`, you can expand your brush collection with custom brushes tailored to specific artistic effects and styles.+ **Image brushes only**: `brush.add()` returns a Promise when `type` is `"image"` — you must `await` it so the image finishes loading before you start drawing. For this to work, your `setup()` function must be declared `async`. For all other brush types, no `await` is needed.---@@ -504,8 +455,6 @@ Stroke Operations encompass methods for manipulating and applying brushes to strThe Fill Management section focuses on managing fill properties for shapes, enabling complex fill operations with effects like bleeding to simulate watercolor-like textures. These methods set fill colors with opacity, control bleed intensity, and manage fill operations. The watercolor fill effect is inspired by Tyler Hobbs' generative art techniques.-** IMPORTANT: ** At the moment, fill operations expect an array of vertices in the clockwise direction. Otherwise, the fill will "bleed" to the inside, destroying the effect. I'll try to fix this on a forthcoming update.----- `brush.fill(a, b, c, d)` or `brush.fill(color, opacity)`@@ -536,16 +485,15 @@ The Fill Management section focuses on managing fill properties for shapes, enab----- `brush.bleed(strength, direction)`- - **Description**: Adjusts the bleed and texture levels for the fill operation, mimicking the behavior of watercolor paints. This function adds a natural and organic feel to digital artwork.+- `brush.fillBleed(strength, direction)`+ - **Description**: Adjust the bleed intensity for the fill operation, mimicking the edge diffusion of watercolor paints.- **Parameters**:- - `strength` (Number): The intensity of the bleed effect, capped at 0.5.- - `direction` (String): Optional. "out" or "in". Defines the direction of the bleed effect+ - `strength` (Number): The intensity of the bleed effect, ranging from 0 to 1.+ - `direction` (String): Optional. `"out"` or `"in"`. Defines the direction of the bleed effect.- `_borderIntensity` (Number): The intensity of the border watercolor effect, ranging from 0 to 1.- **Usage**:```javascript- // Set the bleed intensity and direction for a watercolor effect- brush.bleed(0.3, "out");+ brush.fillBleed(0.3, "out");```---@@ -563,17 +511,6 @@ The Fill Management section focuses on managing fill properties for shapes, enab----- `brush.fillAnimatedMode(mode)`- - **Description**: Toggles certain operations on or off to ensure a consistent bleed effect for animations, especially useful at varying bleed levels.- - **Parameters**:- - `mode` (Boolean): Set to `true` to enable animated mode, `false` to disable.- - **Usage**:- ```javascript- // Enable animated mode for consistent bleed effects in animations- brush.fillAnimatedMode(true);- ```- `brush.fillAnimatedMode()` is valuable for animators and artists working on dynamic projects, where maintaining consistent fill effects across frames is crucial.----<sub>[back to table](#table-of-functions)</sub>@@ -611,16 +548,15 @@ The Hatching section focuses on creating and drawing hatching patterns, which in----- `brush.setHatch(brushName, color, weight)`- - **Description**: Sets the brush type, color, and weight specifically for hatching. If not called, hatching will use the parameters defined by the current stroke settings.+- `brush.hatchStyle(brushName, color, weight)`+ - **Description**: Set the brush type, color, and weight specifically for hatching. If not called, hatching will use the parameters defined by the current stroke settings.- **Parameters**:- `brushName` (String): The name of the brush to use for hatching.- `color` (String|p5.Color): The color for the brush, either as a CSS string or a p5.Color object.- `weight` (Number): The weight or size of the brush for hatching.- **Usage**:```javascript- // Set the hatching brush to "rotring" with green color and specific weight- brush.setHatch("rotring", "green", 1.3);+ brush.hatchStyle("rotring", "green", 1.3);```---@@ -696,7 +632,7 @@ The following functions are only affected by stroke() operations, completely ign----These three functions provide advanced control over the creation of strokes/paths, allowing for custom pressure and direction at different points along the path. This is a strange way of defining strokes, but intuitive when you think of them as bodily movements performed with the hands. You can create two types of strokes: "curve" or "segments". For curved strokes, the curvature at any point of the stroke is lerped between the nearest control points.+These three functions provide advanced control over the creation of strokes/paths, allowing for custom pressure and direction at different points along the path. Think of them as bodily movements performed with the hands. You can create two types of strokes: `"curve"` or `"segments"`. For curved strokes, the curvature at any point is interpolated between the nearest control points.These functions allow for the creation of strokes with varied pressures and directions, mimicking the organic nature of hand-drawn strokes. For an application of these principles, see: [Enfantines II](https://art.arqtistic.com/Enfantines-2)@@ -712,17 +648,16 @@ These functions allow for the creation of strokes with varied pressures and direbrush.beginStroke("curve", 15, 30);```-- `brush.segment(angle, length, pressure)`- - **Description**: Adds a segment to the stroke, defining its path by specifying the angle, length, and pressure. This function is used after `brush.beginStroke()` and before `brush.endStroke()` to outline the stroke's trajectory and characteristics.+- `brush.move(angle, length, pressure)`+ - **Description**: Add a segment to the stroke, defining its path by specifying the angle, length, and pressure. Use between `brush.beginStroke()` and `brush.endStroke()` to outline the stroke's trajectory and characteristics.- **Parameters**:- `angle` (Number): The initial angle of the segment, relative to the canvas, measured anticlockwise from the x-axis.- `length` (Number): The length of the segment.- `pressure` (Number): The pressure at the start of the segment, influencing properties like width.- **Usage**:```javascript- // Add two segments to the stroke- brush.segment(30, 150, 0.6);- brush.segment(75, 40, 1.1);+ brush.move(30, 150, 0.6);+ brush.move(75, 40, 1.1);```- `brush.endStroke(angle, pressure)`@@ -739,40 +674,19 @@ These functions allow for the creation of strokes with varied pressures and dire---- `brush.spline(array_points, curvature)`- - **Description**: Generates and draws a spline curve, a smooth curve defined by a series of control points. The curve connects the start and end points directly, using the other points in the array as control points to define the curve's path. The curvature parameter allows for adjusting the smoothness of the curve. Spline is maybe not the appropriate description, since these splines are basically segmented paths with rounded corners.+ - **Description**: Draw a spline curve through a series of control points. The curve connects the start and end points directly, using intermediate points to shape the path. These splines are segmented paths with rounded corners.- **Parameters**:- - `array_points` (Array<Array<number>>): An array of points, where each point is an array of two numbers `[x, y]`.- - `curvature` (Number): Optional. The curvature of the spline curve, ranging from 0 to 1. A curvature of 0 results in a series of straight segments.+ - `array_points` (Array<Array<number>>): An array of points, where each point is `[x, y]` or `[x, y, pressure]`. The optional pressure value at each point influences brush width along the curve.+ - `curvature` (Number): Optional. The curvature of the spline, ranging from 0 to 1. A value of 0 produces straight segments.- **Note**: This is a simplified alternative to beginShape() - endShape() operations, useful for certain stroke() applications.- **Usage**:```javascript- // Define points for the spline curve- let points = [[30, 70], [85, 20], [130, 100], [180, 50]];- // Create a spline curve with a specified curvature+ let points = [[30, 70], [85, 20, 1.5], [130, 100], [180, 50]];brush.spline(points, 0.5);```----- `brush.plot(p, x, y, scale)`- - **Description**: Renders a predefined shape or plot with a flowing brush stroke, following the currently active vector field. The shape is drawn at a specified starting position and scale. The plot object should be defined following the instructions in the Exposed Classes section.- - **Parameters**:- - `p` (Plot Object): A plot object representing the shape.- - `x` (Number): The x-coordinate of the starting position.- - `y` (Number): The y-coordinate of the starting position.- - `scale` (Number): The scale at which to draw the shape.- - **Note**: This is an alternative to beginStroke() - endStroke() operations. It is useful for drawing the same Plot at different starting points and scales.- - **Usage**:- ```javascript- // Define a plot (heart shape)- let heart = new brush.Plot();- // ... Define the heart plot here ...- // Draw the heart shape with a flowing stroke- brush.flowShape(heart, 200, 200, 1.3);- ```------#### Shapes and PolygonsThe following functions are affected by stroke(), fill() and hatch() operations.@@ -780,25 +694,25 @@ The following functions are affected by stroke(), fill() and hatch() operations.---- `brush.rect(x, y, w, h, mode)`- - **Description**: Draws a rectangle on the canvas. This shape adheres to the current stroke, fill, and hatch attributes. Rectangles are influenced by active vector fields.+ - **Description**: Draw a rectangle on the canvas using the current stroke, fill, and hatch settings. Rectangles are influenced by active vector fields.- **Parameters**:- `x` (Number): The x-coordinate of the rectangle.- `y` (Number): The y-coordinate of the rectangle.- `w` (Number): The width of the rectangle.- `h` (Number): The height of the rectangle.- - `mode` (Boolean): Optional. If `CENTER`, the rectangle is drawn centered at `(x, y)`.+ - `mode` (String): Optional. `"corner"` (default) positions `(x, y)` at the top-left corner. `"center"` draws the rectangle centered at `(x, y)`.- **Usage**:```javascriptbrush.noStroke();brush.noHatch();brush.fill("#002185", 75);- brush.rect(150, 100, 50, 35, CENTER);+ brush.rect(150, 100, 50, 35, "center");```---- `brush.circle(x, y, radius, r)`- - **Description**: Draws a circle on the canvas, using the current brush settings. If `r` is true, the circle is rendered with a hand-drawn style. Circles are affected by vector fields.+ - **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.- **Parameters**:- `x` (Number): The x-coordinate of the circle's center.- `y` (Number): The y-coordinate of the circle's center.@@ -811,6 +725,21 @@ The following functions are affected by stroke(), fill() and hatch() operations.---+- `brush.arc(x, y, radius, start, end)`+ - **Description**: Draw an arc (partial circle) using the current brush settings. The arc is drawn as a stroke only — `fill()` is not applied.+ - **Parameters**:+ - `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.+ - **Usage**:+ ```javascript+ brush.arc(200, 200, 50, 0, Math.PI);+ ```++---+These three functions perform similarly to the p5.js beginShape(), vertex(), and endShape() functions, althouh curvature calculation is very different. These allow you to draw custom shapes, with fine control over brush pressure at the different points of the perimeter.- `brush.beginShape(curvature)`@@ -840,14 +769,16 @@ These three functions perform similarly to the p5.js beginShape(), vertex(), and```- `brush.endShape(a)`- - **Description**: Completes the custom shape, finalizing the recording of vertices. The shape can be either closed or left open based on the optional argument. The function also triggers the rendering of the shape with the current stroke, fill, and hatch settings.+ - **Description**: Complete the custom shape, finalizing the recording of vertices, and render it with the current stroke, fill, and hatch settings.- **Parameters**:- - `a` (String): Optional. If set to `CLOSE`, the shape is closed.+ - `a` (Boolean): Optional. Pass `true` to close the shape (connect the last vertex back to the first). Pass `false` or omit to leave the shape open.- **Returns**: None.- **Usage**:```javascript- // Finish the custom shape and close it with a straight line- brush.endShape(CLOSE);+ // Finish the custom shape and close it+ brush.endShape(true);+ // Or leave it open+ brush.endShape(false);```---@@ -874,90 +805,65 @@ These three functions perform similarly to the p5.js beginShape(), vertex(), andThis section covers functions for initializing the drawing system, preloading required assets, and configuring system behavior. By default, the library works without executing these functions, but you might want to configure them to your liking.- `brush.seed(seed)`- - **Description**: Sets a custom seed for deterministic drawing results.- - **Parameters**:- - `seed` (String | Number): A seed.- - **Example**:+ - **Description**: Set a custom seed for deterministic drawing results.+ - **Parameters**:+ - `seed` (String | Number): A seed value.+ - **Example**:```javascriptbrush.seed('hello');```- Replace `hello` with the actual seed.----- `brush.load(canvasID)`- - **Description**: Initializes the drawing system and sets up the environment. If `canvasID` is not provided, the current window is used as the rendering context. If you want to load the library on a custom p5.Graphics element, you can do it by executing this function.- - **Parameters**:- - `canvasID` (string): Optional ID of the buffer/canvas element. If false, uses the window's rendering context.- - **Example (load p5.brush on buffer)**:+- `brush.noiseSeed(seed)`+ - **Description**: Set the seed for the Perlin noise used internally by the library. Useful for getting reproducible organic texture in brush strokes.+ - **Parameters**:+ - `seed` (Number): Any integer.+ - **Example**:```javascript- function setup() {- createCanvas(400, 400, WEBGL)- // Draw stuff to global canvas- brush.set("HB","black",1)- brush.rect(40,40,150,100)- // Force draw stuff to canvas- brush.reDraw()-- // Create buffer- let buffer = createGraphics(200, 300, WEBGL)- brush.load(buffer)- brush.set("HB","black",1)- brush.rect(40,40,150,100)- // Force draw stuff to buffer- brush.reDraw()-- image(buffer,20,40)-- // Load p5.brush again on global canvas- brush.load()- }- ```- - **Note for Instance Mode**: If you want to use the p5 instance mode, you need to pass the proper variable as canvasID.- ```javascript- let sketch = function(p) {- let x = 100;- let y = 100;-- // Register instance method here, sending your function arg p- brush.instance(p)-- p.setup = function() {- p.createCanvas(700, 410);- };+ brush.noiseSeed(99);+ ```- p.draw = function() {- p.background(0);- brush.fill("red", 75);- brush.rect(x, y, 50, 50);- };- };+---- let myp5 = new p5(sketch);- ```+- `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.+ - **Parameters**:+ - `buffer` (p5.Graphics): Optional. A p5.Graphics buffer to draw into.+ - **Example (draw into a buffer)**:+ ```javascript+ function setup() {+ createCanvas(400, 400, WEBGL);+ brush.load();+ brush.set("HB", "black", 1);+ brush.rect(40, 40, 150, 100);++ // Switch to a buffer+ let buffer = createGraphics(200, 300, WEBGL);+ brush.load(buffer);+ brush.set("HB", "black", 1);+ brush.rect(40, 40, 150, 100);+ image(buffer, 20, 40);++ // Switch back to main canvas+ brush.load();+ }+ ```---- `brush.preload()`- - **Description**: Preloads necessary assets or configurations for brushes. If you are using custom image tip brushes, you need to include this question within the preload() function of your p5 sketch.+ - **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**: To use a deterministic random number generator, such as one from a generative art platform like fx(hash), you might configure your system as follows:+ - **Example**:```javascript- // Your p5 preload function- function preload () {- brush.preload() // Add this if you want to use custom img brushes+ function preload() {+ brush.preload(); // only needed for backward compatibility}```----- `brush.colorCache(bool = true)`- - **Description**: Enables or disables color caching for WebGL shaders. Color caching can increase performance but may produce less accurate textures when the same color is used repeatedly. It's set to _true_ by default- - **Parameters**:- - `bool` (boolean): Set to true to enable caching, or false to disable it.------- `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.- **Parameters**:@@ -972,38 +878,30 @@ This section covers functions for initializing the drawing system, preloading re---------- `brush.remove()`- - **Description**: Removes brush library brushes and unloads the library. This can be useful if you only used the library to draw into a buffer, and you want to perform only normal p5 operations after that.------- `brush.instance(p)`- - **Description**: Execute before the setup() and draw() functions if you need to use p5 in instance mode- - **Parameters**:- - `p` (variable): Variable used as the function argument. See below+ - **Description**: Call this inside your sketch function before `setup` and `draw` when using p5 in instance mode. Tells p5.brush which p5 instance to render into. After calling this, all `brush.*` functions work normally — no need to prefix them with `p.`.+ - **Parameters**:+ - `p` (p5): The p5 instance passed as the argument to your sketch function.- **Example**:```javascript- let sketch = function(p) {- let x = 100;- let y = 100;-- // Register instance method here, sending your function arg p- brush.instance(p)-- p.setup = function() {- p.createCanvas(700, 410);+ const sketch = (p) => {+ // Must be called before setup/draw+ brush.instance(p);++ p.setup = () => {+ // Canvas must be WEBGL+ p.createCanvas(700, 410, p.WEBGL);+ brush.load();};- p.draw = function() {- p.background(0);- brush.fill("red", 75);- brush.rect(x, y, 50, 50);+ p.draw = () => {+ p.background(240);+ brush.set("HB", "#333", 1);+ brush.line(100, 100, 400, 300);};};- let myp5 = new p5(sketch);+ new p5(sketch);```---diff --git a/dist/p5.brush.esm.js b/dist/p5.brush.esm.jsnew file mode 100644index 0000000..86103e5--- /dev/null+++ b/dist/p5.brush.esm.js@@ -0,0 +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),x=(3-g)/6,p=t=>0|Math.floor(t),d=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=>d[t%12*2])),i=new Float64Array(e).map((t=>d[t%12*2+1]));return function(t,n){let o=0,s=0,a=0;const l=(t+n)*m,c=p(t+l),h=p(n+l),u=(c+h)*x,f=t-(c-u),g=n-(h-u);let d,y;f>g?(d=1,y=0):(d=0,y=1);const v=f-d+x,_=g-y+x,b=f-1+2*x,w=g-1+2*x,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+d+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());const w=t=>{b=v(t)};let R=y(v(Math.random()));const S=t=>{R=y(v(t))},E=(t=0,e=1)=>t+b()*(e-t),A=t=>t[~~(b()*t.length)],P=(t,e)=>~~E(t,e),M=(t=0,e=1)=>{const r=1-b(),i=b();return Math.sqrt(-2*Math.log(r))*B(360*i)*e+t},L=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)},k=(t,e,r,i,n,o=!1)=>{let s=i+(t-e)/(r-e)*(n-i);return o?i<n?C(s,i,n):C(s,n,i):s},C=(t,e,r)=>Math.max(Math.min(t,r),e),I=t=>(t%=360)<0?t+360:t,T=1440,N=2*Math.PI/T,z=new Float32Array(T).fill(NaN),O=new Float32Array(T).fill(NaN),B=t=>{const e=~~(4*I(t));let r=z[e];return isNaN(r)&&(r=Math.cos(e*N),z[e]=r),r},D=t=>{const e=~~(4*I(t));let r=O[e];return isNaN(r)&&(r=Math.sin(e*N),O[e]=r),r},Y=(t,e=!1)=>{if(i.angleMode()===i.RADIANS||e){let e=180*t/Math.PI%360;return e<0?e+360:e}return t},F=(t,e,r,i,n)=>{let o=B(n),s=D(n);return{x:o*(r-t)+s*(i-e)+t,y:o*(i-e)-s*(r-t)+e}},X=(t,e,r,i)=>Math.hypot(r-t,i-e),G=(t,e,r,i)=>Y(Math.atan2(-(i-e),r-t),!0),$=(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,x=u-c,p=f-h,d=p*g-x*m;if(0===d)return!1;let y=(x*(s-h)-p*(o-c))/d,v=(g*(s-h)-m*(o-c))/d;return!(!n&&(v<0||v>1))&&{x:o+y*g,y:s+y*m}},W={x:()=>i._renderer.uModelMatrix.mat4[12],y:()=>i._renderer.uModelMatrix.mat4[13],a:()=>i._renderer.uModelMatrix.mat4[0],b:()=>i._renderer.uModelMatrix.mat4[1],c:()=>i._renderer.uModelMatrix.mat4[4],d:()=>i._renderer.uModelMatrix.mat4[5]};let H=!1;function j(){H||(u(),Z=.01*t,V=-.5*t,K=-.5*e,q=Math.round(2*t/Z),J=Math.round(2*e/Z),lt("hand",((t,e)=>{const r=E(.2,.8),i=P(5,10);return ut(e,((e,n)=>.5*i*D(r*n*e+P(15,25))*.2*B(t)+R(e,n)*i*.7))})),lt("curved",((t,e)=>{let r=P(-10,10);return P(0,100)%2==0&&(r*=-1),ut(e,((e,i)=>3*k(R(.02*e+.03*t,.02*i+.03*t),0,1,-r,r)))})),lt("zigzag",((t,e)=>{let r=P(-30,-15)+Math.abs(44*D(t));P(0,100)%2==0&&(r*=-1);let i=r,n=0;for(let t=0;t<q;t++){for(let r=0;r<J;r++)e[t][r]=n,n+=i,i*=-1;n+=i,i*=-1}return e})),lt("waves",((t,e)=>{const r=P(10,15)+5*D(t),i=P(3,6)+3*B(t),n=P(20,35);return ut(e,((t,e)=>D(r*t)*n*B(e*i)+P(-3,3)))})),lt("seabed",((t,e)=>{const r=E(.4,.8),i=P(18,26);return ut(e,((e,n)=>1.1*i*D(r*n*e+P(15,20))*B(t)))})),lt("spiral",((t,e)=>{const r=P(5,10),i=2*P(0,2)-1,n=P(65,80),o=Array.from({length:r},(()=>({x:E(.1,.9)*q,y:E(.1,.9)*J})));return ut(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)}))})),lt("columns",((t,e)=>{const r=P(3,8),i=P(25,45);return ut(e,((t,e)=>D(t*r)*i))})),H=!0)}class U{constructor(t,e){j(),this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=U.getColIndex(t),this.rowIdx=U.getRowIndex(e)}reset(){this.plotted=0}isIn(){return c.field.isActive?U.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const r=t,i=e,n=this.x+W.x(),o=this.y+W.y();return n>=-.3*r&&n<=1.3*r&&o>=-.3*i&&o<=1.3*i}angle(){return this.isIn()&&c.field.isActive?it.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*B(e),this.y+r*D(e)),this.plotted+=r/n}else this.plotted+=r/n}static getRowIndex(t,e=1){const r=t+W.y()-K;return Math.round(r/Z/e)}static getColIndex(t,e=1){const r=t+W.x()-V;return Math.round(r/Z/e)}static isIn(t,e){return t>=0&&e>=0&&t<q&&e<J}}c.field={isActive:!1,current:null,wiggle:1};let Z,V,K,q,J,Q,tt,et,rt,it=new Map;function nt(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=it.get(c.field.current);e.field=e.gen(t,ot())}function ot(){return new Array(q).fill(null).map((()=>new Float32Array(J)))}function st(t){if(c.field.wiggle||(c.field.wiggle=1),j(),!it.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(it.keys()).join(", ")}.`);c.field.isActive=!0,c.field.current=t;const e=it.get(t);e.field||(e.field=e.gen(0,ot()))}function at(){j(),c.field.isActive=!1}function lt(t,e){it.set(t,{gen:e,field:null})}function ct(){return j(),Array.from(it.keys())}function ht(t=1){st("hand"),c.field.wiggle=t}function ut(t,e){for(let r=0;r<q;r++)for(let i=0;i<J;i++)t[r][i]=e(r,i);return t}class ft{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=$(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 gt{constructor(t){this.segments=[],this.angles=[],this.pres=[],this.type=t,this.dir=0,this.calcIndex(0),this.pol=!1}addSegment(t=0,e=0,r=1,i=!1){this.angles.length>0&&this.angles.pop(),t=i?(t%360+360)%360:Y(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:Y(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=Y(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)),k(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){j();const s=.5,a=[],l=Math.round(this.length/s),c=new U(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*E(.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 ft(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 mt(t){new ft(t).show()}function xt(t,e,r,i,n="corner"){"center"===n&&(t-=r/2,e-=i/2),vt(0),_t(t,e),_t(t+r,e),_t(t+r,e+i),_t(t,e+i),bt(!0)}function pt(t,e,r,i=!1){const n=new gt("curve"),o=Math.PI*r,s=E(0,360),a=i?()=>1+.2*E():()=>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=P(-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*D(s),c=e-r*B(-s);n.show(l,c,1)}function dt(t,e,r,i,n){const o=new gt("curve"),s=270-Y(i),a=270-Y(n),l=Y(n-i),c=Math.PI*r*l/180;o.addSegment(s,c,1,!0),o.endPlot(a,1,!0);const h=t+r*B(-s-90),u=e+r*D(-s-90);o.draw(h,u,1)}class yt{constructor(){this.isClosed=!1,this.curvature=tt,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){At(this.vert,this.curvature,this.isClosed).show()}}function vt(t=0){tt=C(t,0,1),Q=new yt}function _t(t,e,r=1){if(!Q)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");Q.vertex(t,e,r)}function bt(t=!1){if(!Q)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(Q.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(Q.vertex(...Q.vert[0]),Q.isClosed=!0),Q.show(),Q=!1}function wt(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);rt=[e,r],et=new gt(t)}function Rt(t,e,r){if(!et)throw new Error("move() called without beginStroke(). Call beginStroke() first.");et.addSegment(t,e,r)}function St(t,e){if(!et)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");et.endPlot(t,e),et.draw(rt[0],rt[1],1),et=!1}function Et(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()}function At(t,e=.5,r=!1){const i=new gt(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=X(h[0],h[1],u[0],u[1]),m=X(u[0],u[1],f[0],f[1]),x=G(h[0],h[1],u[0],u[1]),p=G(u[0],u[1],f[0],f[1]),d=e*Math.min(g,m,.5*Math.min(g,m)),y=Math.max(g,m),v=g-d,_=m-d;if(Math.floor(x)===Math.floor(p)){const e=r&&0===c?0:g-l,n=r?0===c?0:m-a:m;i.addSegment(x,e,h[2],!0),c===t.length-3&&i.addSegment(p,n,u[2],!0),l=0,0===c&&(o=g,a=d,s=t[1],l=0)}else{const e={x:u[0]-d*B(-x),y:u[1]-d*D(-x)},f={x:e.x+y*B(90-x),y:e.y+y*D(90-x)},g={x:u[0]+d*B(-p),y:u[1]+d*D(-p)},m={x:g.x+y*B(90-p),y:g.y+y*D(90-p)},b=$(e,f,g,m,!0),w=X(e.x,e.y,b.x,b.y),R=X(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-d:_:0;i.addSegment(x,E,h[2],!0),i.addSegment(x,isNaN(S)?0:S,h[2],!0),i.addSegment(p,A,u[2],!0),l=d,0===c&&(o=v,a=d,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=X(e[0],e[1],r[0],r[1]),o=G(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}const Pt=(t,e,r)=>{const i=t.createProgram();for(let[n,o]of[[t.VERTEX_SHADER,e],[t.FRAGMENT_SHADER,r]]){const e=t.createShader(n);t.shaderSource(e,o),t.compileShader(e),t.attachShader(i,e)}return t.linkProgram(i),i};var Mt="#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;}",Lt="#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);}";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}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 xe(r,i,n,o=!1){Dt=W.a(),Yt=W.b(),Ft=W.c(),Xt=W.d(),Gt=W.x(),$t=W.y(),Kt=new U(r+t/2,i+e/2),qt=n,Jt=o,Jt&&Jt.calcIndex(0)}const pe=[];function de(r,i){i||(Qt=r),function(){me.seed=999999*E();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?E(-1,1):0,me.b="custom"!==i.type?E(1,1.5):0,me.cp="custom"!==i.type?E(3,3.5):E(-.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=Pt(kt,Mt,Lt),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++)pe.length<2*o&&pe.push(M()),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||ve(),r=k(R(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*A(pe)*me.p.scatter/3,r=me.p.weight*E(.9,1.1),i=Math.ceil(me.p.grain/t);for(let t=0;t<i;t++){const t=E(.9,1.1),i=t*e*E(-1,1),n=E(-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=k(e,0,1,.9,1.05))*c.stroke.weight*me.p.scatter*(me.p.sharpness+(1-me.p.sharpness)*A(pe)/t);if(E(0,me.p.grain*t)>.4){let e,i;if(Jt)e=.7*r*E(-1,1),i=r*E(-1,1);else{const t=r*E(-1,1),n=.3*r*E(-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*E(.85,1.15)*c.stroke.weight,Math.max(.9,t)*me.alpha*E(.75,1.1))}}(e*r)}}function ve(){return Jt?_e()*Jt.pressure(Kt.plotted):_e()}function _e(){return"custom"===me.p.pressure.type?k(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 k(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+W.x(),s=Kt.y+W.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*E(-1,1):0,o=e?i*E(-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*E(-1,1):0,a=n?o*E(-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=P(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=ve(),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.");j();let n=X(t,e,r,i);0!=n&&(xe(t,e,n),de(G(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.");j(),xe(t,e,r),de(Y(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)}ft.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)},gt.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){j(),xe(e,r,t.length,t),de(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=Y(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 ft([[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?k(i.gradient,0,1,1,1.1,!0):1,h=[],u=0,f=e,g=t=>({point1:{x:o.minX+f*t*B(90-r),y:a+f*t*D(90-r)},point2:{x:o.minX+f*t*B(90-r)+B(-r),y:a+f*t*D(90-r)+D(-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])),x=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!==x&&(r[i].x+=x*e*E(-10,10),r[i].y+=x*e*E(-10,10),r[i+1].x+=x*e*E(-10,10),r[i+1].y+=x*e*E(-10,10)),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},ft.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)},gt.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:60,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)||60,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=C(t,0,1),c.fill.direction=e}function Ge(t=.4,e=.4){c.fill.texture_strength=C(t,0,1),c.fill.border_strength=C(e,0,1)}function $e(){c.fill.isActive=!1}let We;const He=[[],[]];class je{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=F(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))i=t.v1,o=e,((n=t.v2).x-i.x)*(o.y-i.y)-(n.y-i.y)*(o.x-i.x)>.01&&r++;var i,n,o;this.dir[e]=r%2==0}));const o=E(-.6,.6)*e,s=E(-.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?E(.6,.8):c.fill.bleed_strength;for(let c=0;c<n;c++){He[0].length<1.5*n&&(He[0].push(M(.5,.2)),He[1].push(M(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*E(-1,1),x=g.x-f.x,p=g.y-f.y,{x:d,y:y}=F(0,0,x,p,m),v=.5,_=A(He[0])*E(.65,1.35)*u;o[h]=f,s[h]=r[c],a[h++]=i[c],o[h]={x:f.x+x*v+d*_,y:f.y+p*v+y*_},s[h]=r[c]+A(He[1]),a[h++]=i[c]}return new je(o,s,this.midP,a,!1,this.sizeX,this.sizeY)}fill(r,i,n){const o=3*n,s=2*i*(1+n/2);f.blend(r),f.justChanged=!0,f.isBrush=!1,f.ctx.save(),f.ctx.setTransform(W.a(),W.b(),W.c(),W.d(),W.x()+t/2,W.y()+e/2),f.ctx.strokeStyle=`rgb(${r._getRed()} ${r._getGreen()} ${r._getBlue()} / ${.005*c.fill.border_strength})`,f.ctx.lineCap="round";const a=Math.max(this.sizeX,this.sizeY),l=E(.15,.7);let h,u=this.grow();for(let t=0;t<20;t++){t%4==0&&(u=u.grow()),t%2==0&&(h=[u.grow(1-.0125*t),u.grow(.7-.0125*t),u.grow(.4-.0125*t)]);for(const e of h)e.grow(999).grow(997).layer(t,a,s,r);t%2==0&&u.grow(l).grow(999).layer(t,a,2*s,r),t%5!=0&&19!==t||(0!==o&&u.erase(3*o,i),f.blend(r,!0,!1,!0))}f.ctx.restore()}layer(t,e,r,i){var n;f.ctx.lineWidth=k(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=~~(E(80,110)*k(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-k(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+M(0,i),r=h+M(0,n),o=E(s,a);f.ctx.beginPath(),De(e,r,o),t%5!=0&&f.ctx.fill()}f.ctx.globalCompositeOperation="source-over",f.ctx.restore()}}ft.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&&(j(),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*L({1:5,2:10,3:60})),i=c.fill.bleed_strength,n=e.map(((t,e)=>(e>r?1:.3)*E(.85,1.2)*i)),o=P(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 je(s,n,a,[],!0).fill(c.fill.color,k(c.fill.opacity,0,100,0,1,!0),c.fill.texture_strength)}(this)),(t=>{c.fill={...t}})(s)},gt.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,k(c.fill.bleed_strength,0,.6,.3,.45,!0)),this.pol.fill())};const Ue=[];"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;e.push=function(){i.call(this),j(),Ue.push({fill:{...c.fill},stroke:{...c.stroke},hatch:{...c.hatch},field:{...c.field}})},e.pop=function(){n.call(this),function(){const t=Ue.pop();t&&(c.stroke={...t.stroke},c.field={...t.field},c.hatch={...t.hatch},c.fill={...t.fill})}()}}));export{gt as Plot,ft as Polygon,U as Position,ne as add,lt as addField,dt as arc,vt as beginShape,wt as beginStroke,oe as box,pt as circle,fe as clip,bt as endShape,St as endStroke,st 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,ct as listFields,o as load,Rt as move,ge as noClip,at as noField,$e as noFill,ze as noHatch,ue as noStroke,S as noiseSeed,ae as pick,mt as polygon,Ce as preload,xt as rect,nt as refreshField,se as scaleBrushes,w as seed,he as set,Et as spline,le as stroke,ce as strokeWeight,_t as vertex,L as wRand,ht as wiggle};+//# sourceMappingURL=p5.brush.esm.js.mapdiff --git a/dist/p5.brush.esm.js.map b/dist/p5.brush.esm.js.mapnew file mode 100644index 0000000..0878d69--- /dev/null+++ b/dist/p5.brush.esm.js.map@@ -0,0 +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/core/gl/utils.js","../src/stroke/gl_draw.js","../src/stroke/stroke.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 + 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 = 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 * 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: 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","// =============================================================================\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// 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(-10, 10);\n dd[i].y += r * dist * rr(-10, 10);\n dd[i + 1].x += r * dist * rr(-10, 10);\n dd[i + 1].y += r * dist * rr(-10, 10);\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 } 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: 60,\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) || 60;\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, 100, 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 Matrix.a(), Matrix.b(),\n Matrix.c(), Matrix.d(),\n Matrix.x() + Cwidth / 2,\n 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, seed, noiseSeed } 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\";\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\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\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","noiseSeed","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","createProgram","frag","src","VERTEX_SHADER","FRAGMENT_SHADER","shaderSource","compileShader","attachShader","linkProgram","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","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","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","vertSrc","fragSrc","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","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","call","saved","brushPop"],"mappings":"AAaU,IAAMA,E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,EAAQ9a,EAAG/O,KACX8pB,EAAO/a,EAAGzO,IAEhByO,EAAG/O,KAAO,WACR6pB,EAAME,KAAKtrB,MDpHbsL,IACAwf,GAAYvpB,KAAK,CACfG,KAAM,IAAK5C,EAAM4C,MACjB8P,OAAQ,IAAK1S,EAAM0S,QACnBE,MAAO,IAAK5S,EAAM4S,OAClB5F,MAAO,IAAKhN,EAAMgN,QCiHpB,EAEAwE,EAAGzO,IAAM,WACPwpB,EAAKC,KAAKtrB,MD7GP,WACL,MAAMurB,EAAQT,GAAYjpB,MACrB0pB,IACLzsB,EAAM0S,OAAS,IAAK+Z,EAAM/Z,QAC1B1S,EAAMgN,MAAQ,IAAKyf,EAAMzf,OACzBhN,EAAM4S,MAAQ,IAAK6Z,EAAM7Z,OACzB5S,EAAM4C,KAAO,IAAK6pB,EAAM7pB,MAC1B,CCuGI8pB,EACF,CACF","x_google_ignoreList":[1,2]}\ No newline at end of filediff --git a/dist/p5.brush.js b/dist/p5.brush.jsindex 333aec4..c808e71 100644--- a/dist/p5.brush.js+++ b/dist/p5.brush.js@@ -1 +1,2 @@-!function(t,e){"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={})}(this,(function(t){"use strict";function e(t,e){let s=new i(t),n=()=>s.next();return n.double=()=>n()+11102230246251565e-32*(2097152*n()|0),n.int32=()=>4294967296*s.next()|0,n.quick=n,function(t,e,i){let s=i&&i.state;s&&("object"==typeof s&&e.copy(s,e),t.state=()=>e.copy(e,{}))}(n,s,e),n}class i{constructor(t){null==t&&(t=+new Date);let e=4022871197;function i(t){t=String(t);for(let i=0;i<t.length;i++){e+=t.charCodeAt(i);let s=.02519603282416938*e;e=s>>>0,s-=e,s*=e,e=s>>>0,s-=e,e+=4294967296*s}return 2.3283064365386963e-10*(e>>>0)}this.c=1,this.s0=i(" "),this.s1=i(" "),this.s2=i(" "),this.s0-=i(t),this.s0<0&&(this.s0+=1),this.s1-=i(t),this.s1<0&&(this.s1+=1),this.s2-=i(t),this.s2<0&&(this.s2+=1)}next(){let{c:t,s0:e,s1:i,s2:s}=this,n=2091639*e+2.3283064365386963e-10*t;return this.s0=i,this.s1=s,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 s,n=!1,o=!1,r=!1,a=!1;function h(t=!1){let e=!(!r||!t)&&a;n&&l(!1),!t&&r&&(t=a),s=t||window.self,y.load(e),o=!0}function l(t=!0){n&&(y.masks[0].remove(),y.masks[0]=null,y.masks[1].remove(),y.masks[1]=null,y.masks[2].remove(),y.masks[2]=null,t&&brush.load())}function c(){n||(o||h(),z.create(),A(s.width/250),n=!0)}let m=new e(Math.random());const d={random:(t=0,e=1)=>t+m()*(e-t),randInt(t,e){return Math.floor(this.random(t,e))},gaussian(t=0,e=1){const i=1-m(),s=m();return Math.sqrt(-2*Math.log(i))*Math.cos(2*Math.PI*s)*e+t},weightedRand(t){let e,i,s=[];for(e in t)for(i=0;i<10*t[e];i++)s.push(e);return s[Math.floor(m()*s.length)]},map(t,e,i,s,n,o=!1){let r=s+(t-e)/(i-e)*(n-s);return o?s<n?this.constrain(r,s,n):this.constrain(r,n,s):r},constrain:(t,e,i)=>Math.max(Math.min(t,i),e),cos(t){return this.c[Math.floor((t%360+360)%360*4)]},sin(t){return this.s[Math.floor((t%360+360)%360*4)]},isPrecalculationDone:!1,preCalculation(){if(this.isPrecalculationDone)return;const t=1440,e=2*Math.PI/t;this.c=new Float64Array(t),this.s=new Float64Array(t);for(let i=0;i<t;i++){const t=i*e;d.c[i]=Math.cos(t),d.s[i]=Math.sin(t)}this.isPrecalculationDone=!0},isNumber:t=>!isNaN(t),toDegrees:t=>(("radians"===s.angleMode()?180*t/Math.PI:t)%360+360)%360,dist:(t,e,i,s)=>Math.hypot(i-t,s-e)};function u(t,e,i,s,n=!1){let o=t.x,r=t.y,a=e.x,h=e.y,l=i.x,c=i.y,m=s.x,d=s.y;if(o===a&&r===h||l===m&&c===d)return!1;let u=a-o,p=h-r,f=m-l,v=d-c,g=v*u-f*p;if(0===g)return!1;let x=(f*(r-c)-v*(o-l))/g,y=(u*(r-c)-p*(o-l))/g;return!(!n&&(y<0||y>1))&&{x:o+x*u,y:r+x*p}}function p(t,e,i,s){return(Math.atan2(-(s-e),i-t)*(180/Math.PI)%360+360)%360}d.preCalculation();const f={field:{},stroke:{},hatch:{},fill:{},others:{}};const v={translation:[0,0],rotation:0,trans(){return this.translation=[s._renderer.uModelMatrix.mat4[12],s._renderer.uModelMatrix.mat4[13]],this.translation}};let g=1;function x(t){g*=t}const y={loaded:!1,isBlending:!1,isCaching:!0,currentColor:new Float32Array(3),load(t){this.type=r&&!t?0:t?2:1,this.masks=[];for(let e=0;e<3;e++)switch(this.type){case 0:this.masks[e]=s.createGraphics(s.width,s.height,1==e?s.WEBGL:s.P2D);break;case 1:this.masks[e]=createGraphics(s.width,s.height,1==e?WEBGL:P2D);break;case 2:this.masks[e]=t.createGraphics(t.width,t.height,1==e?t.WEBGL:t.P2D)}for(let t of this.masks)t.pixelDensity(s.pixelDensity()),t.clear(),t.angleMode(s.DEGREES),t.noSmooth();this.shader=s.createShader(this.vert,this.frag),y.loaded=!0},getPigment(t){let e=t.levels,i=new Float32Array(3);return i[0]=e[0]/255,i[1]=e[1]/255,i[2]=e[2]/255,i},color1:new Float32Array(3),color2:new Float32Array(3),blending1:!1,blending2:!1,blend(t=!1,e=!1,i=!1){if(c(),this.isBlending=i?this.blending1:this.blending2,this.currentColor=i?this.color1:this.color2,!this.isBlending)if(t)this.currentColor=this.getPigment(t),i?(this.blending1=!0,this.color1=this.currentColor):(this.blending2=!0,this.color2=this.currentColor);else if(e)return void(i||w());if((t?this.getPigment(t):this.currentColor).toString()!==this.currentColor.toString()||e||!this.isCaching){if(w(),this.isBlending){s.push(),s.translate(-v.trans()[0],-v.trans()[1]),s.shader(this.shader),this.shader.setUniform("addColor",this.currentColor),this.shader.setUniform("source",s._renderer),this.shader.setUniform("active",y.watercolor),this.shader.setUniform("random",[d.random(),d.random(),d.random()]);let t=i?this.masks[1]:this.masks[0];this.shader.setUniform("mask",t),s.fill(0,0,0,0),s.noStroke(),s.rect(-s.width/2,-s.height/2,s.width,s.height),s.pop(),t.clear()}e||(this.currentColor=this.getPigment(t),i?this.color1=this.currentColor:this.color2=this.currentColor)}e&&(this.isBlending=!1,i?this.blending1=this.isBlending:this.blending2=this.isBlending)},vert:"precision highp float;attribute vec3 aPosition;attribute vec2 aTexCoord;uniform mat4 uModelViewMatrix,uProjectionMatrix;varying vec2 vVertTexCoord;void main(){gl_Position=uProjectionMatrix*uModelViewMatrix*vec4(aPosition,1);vVertTexCoord=aTexCoord;}",frag:"precision highp float;varying vec2 vVertTexCoord;uniform sampler2D source,mask;uniform vec4 addColor;uniform vec3 random;uniform bool active;\n #ifndef SPECTRAL\n #define SPECTRAL\n float x(float v){return v<.04045?v/12.92:pow((v+.055)/1.055,2.4);}float v(float v){return v<.0031308?v*12.92:1.055*pow(v,1./2.4)-.055;}vec3 m(vec3 v){return vec3(x(v[0]),x(v[1]),x(v[2]));}vec3 f(vec3 f){return clamp(vec3(v(f[0]),v(f[1]),v(f[2])),0.,1.);}void f(vec3 v,out float m,out float f,out float x,out float y,out float z,out float i,out float r){m=min(v.x,min(v.y,v.z));v-=m;f=min(v.y,v.z);x=min(v.x,v.z);y=min(v.x,v.y);z=min(max(0.,v.x-v.z),max(0.,v.x-v.y));i=min(max(0.,v.y-v.z),max(0.,v.y-v.x));r=min(max(0.,v.z-v.y),max(0.,v.z-v.x));}void f(vec3 v,inout float i[38]){float x,y,d,z,o,m,e;f(v,x,y,d,z,o,m,e);i[0]=max(1e-4,x+y*.96853629+d*.51567122+z*.02055257+o*.03147571+m*.49108579+e*.97901834);i[1]=max(1e-4,x+y*.96855103+d*.5401552+z*.02059936+o*.03146636+m*.46944057+e*.97901649);i[2]=max(1e-4,x+y*.96859338+d*.62645502+z*.02062723+o*.03140624+m*.4016578+e*.97901118);i[3]=max(1e-4,x+y*.96877345+d*.75595012+z*.02073387+o*.03119611+m*.2449042+e*.97892146);i[4]=max(1e-4,x+y*.96942204+d*.92826996+z*.02114202+o*.03053888+m*.0682688+e*.97858555);i[5]=max(1e-4,x+y*.97143709+d*.97223624+z*.02233154+o*.02856855+m*.02732883+e*.97743705);i[6]=max(1e-4,x+y*.97541862+d*.98616174+z*.02556857+o*.02459485+m*.013606+e*.97428075);i[7]=max(1e-4,x+y*.98074186+d*.98955255+z*.03330189+o*.0192952+m*.01000187+e*.96663223);i[8]=max(1e-4,x+y*.98580992+d*.98676237+z*.05185294+o*.01423112+m*.01284127+e*.94822893);i[9]=max(1e-4,x+y*.98971194+d*.97312575+z*.10087639+o*.01033111+m*.02636635+e*.89937713);i[10]=max(1e-4,x+y*.99238027+d*.91944277+z*.24000413+o*.00765876+m*.07058713+e*.76070164);i[11]=max(1e-4,x+y*.99409844+d*.32564851+z*.53589066+o*.00593693+m*.70421692+e*.4642044);i[12]=max(1e-4,x+y*.995172+d*.13820628+z*.79874659+o*.00485616+m*.85473994+e*.20123039);i[13]=max(1e-4,x+y*.99576545+d*.05015143+z*.91186529+o*.00426186+m*.95081565+e*.08808402);i[14]=max(1e-4,x+y*.99593552+d*.02912336+z*.95399623+o*.00409039+m*.9717037+e*.04592894);i[15]=max(1e-4,x+y*.99564041+d*.02421691+z*.97137099+o*.00438375+m*.97651888+e*.02860373);i[16]=max(1e-4,x+y*.99464769+d*.02660696+z*.97939505+o*.00537525+m*.97429245+e*.02060067);i[17]=max(1e-4,x+y*.99229579+d*.03407586+z*.98345207+o*.00772962+m*.97012917+e*.01656701);i[18]=max(1e-4,x+y*.98638762+d*.04835936+z*.98553736+o*.0136612+m*.9425863+e*.01451549);i[19]=max(1e-4,x+y*.96829712+d*.0001172+z*.98648905+o*.03181352+m*.99989207+e*.01357964);i[20]=max(1e-4,x+y*.89228016+d*8.554e-5+z*.98674535+o*.10791525+m*.99989891+e*.01331243);i[21]=max(1e-4,x+y*.53740239+d*.85267882+z*.98657555+o*.46249516+m*.13823139+e*.01347661);i[22]=max(1e-4,x+y*.15360445+d*.93188793+z*.98611877+o*.84604333+m*.06968113+e*.01387181);i[23]=max(1e-4,x+y*.05705719+d*.94810268+z*.98559942+o*.94275572+m*.05628787+e*.01435472);i[24]=max(1e-4,x+y*.03126539+d*.94200977+z*.98507063+o*.96860996+m*.06111561+e*.01479836);i[25]=max(1e-4,x+y*.02205445+d*.91478045+z*.98460039+o*.97783966+m*.08987709+e*.0151525);i[26]=max(1e-4,x+y*.01802271+d*.87065445+z*.98425301+o*.98187757+m*.13656016+e*.01540513);i[27]=max(1e-4,x+y*.0161346+d*.78827548+z*.98403909+o*.98377315+m*.22169624+e*.01557233);i[28]=max(1e-4,x+y*.01520947+d*.65738359+z*.98388535+o*.98470202+m*.32176956+e*.0156571);i[29]=max(1e-4,x+y*.01475977+d*.59909403+z*.98376116+o*.98515481+m*.36157329+e*.01571025);i[30]=max(1e-4,x+y*.01454263+d*.56817268+z*.98368246+o*.98537114+m*.4836192+e*.01571916);i[31]=max(1e-4,x+y*.01444459+d*.54031997+z*.98365023+o*.98546685+m*.46488579+e*.01572133);i[32]=max(1e-4,x+y*.01439897+d*.52110241+z*.98361309+o*.98550011+m*.47440306+e*.01572502);i[33]=max(1e-4,x+y*.0143762+d*.51041094+z*.98357259+o*.98551031+m*.4857699+e*.01571717);i[34]=max(1e-4,x+y*.01436343+d*.50526577+z*.98353856+o*.98550741+m*.49267971+e*.01571905);i[35]=max(1e-4,x+y*.01435687+d*.5025508+z*.98351247+o*.98551323+m*.49625685+e*.01571059);i[36]=max(1e-4,x+y*.0143537+d*.50126452+z*.98350101+o*.98551563+m*.49807754+e*.01569728);i[37]=max(1e-4,x+y*.01435408+d*.50083021+z*.98350852+o*.98551547+m*.49889859+e*.0157002);}vec3 t(vec3 x){mat3 i;i[0]=vec3(3.24306333,-1.53837619,-.49893282);i[1]=vec3(-.96896309,1.87542451,.04154303);i[2]=vec3(.05568392,-.20417438,1.05799454);float v=dot(i[0],x),y=dot(i[1],x),o=dot(i[2],x);return f(vec3(v,y,o));}vec3 d(float m[38]){vec3 i=vec3(0);i+=m[0]*vec3(6.469e-5,1.84e-6,.00030502);i+=m[1]*vec3(.00021941,6.21e-6,.00103681);i+=m[2]*vec3(.00112057,3.101e-5,.00531314);i+=m[3]*vec3(.00376661,.00010475,.01795439);i+=m[4]*vec3(.01188055,.00035364,.05707758);i+=m[5]*vec3(.02328644,.00095147,.11365162);i+=m[6]*vec3(.03455942,.00228226,.17335873);i+=m[7]*vec3(.03722379,.00420733,.19620658);i+=m[8]*vec3(.03241838,.0066888,.18608237);i+=m[9]*vec3(.02123321,.0098884,.13995048);i+=m[10]*vec3(.01049099,.01524945,.08917453);i+=m[11]*vec3(.00329584,.02141831,.04789621);i+=m[12]*vec3(.00050704,.03342293,.02814563);i+=m[13]*vec3(.00094867,.05131001,.01613766);i+=m[14]*vec3(.00627372,.07040208,.0077591);i+=m[15]*vec3(.01686462,.08783871,.00429615);i+=m[16]*vec3(.02868965,.09424905,.00200551);i+=m[17]*vec3(.04267481,.09795667,.00086147);i+=m[18]*vec3(.05625475,.09415219,.00036904);i+=m[19]*vec3(.0694704,.08678102,.00019143);i+=m[20]*vec3(.08305315,.07885653,.00014956);i+=m[21]*vec3(.0861261,.0635267,9.231e-5);i+=m[22]*vec3(.09046614,.05374142,6.813e-5);i+=m[23]*vec3(.08500387,.04264606,2.883e-5);i+=m[24]*vec3(.07090667,.03161735,1.577e-5);i+=m[25]*vec3(.05062889,.02088521,3.94e-6);i+=m[26]*vec3(.03547396,.01386011,1.58e-6);i+=m[27]*vec3(.02146821,.00810264,0);i+=m[28]*vec3(.01251646,.0046301,0);i+=m[29]*vec3(.00680458,.00249138,0);i+=m[30]*vec3(.00346457,.0012593,0);i+=m[31]*vec3(.00149761,.00054165,0);i+=m[32]*vec3(.0007697,.00027795,0);i+=m[33]*vec3(.00040737,.00014711,0);i+=m[34]*vec3(.00016901,6.103e-5,0);i+=m[35]*vec3(9.522e-5,3.439e-5,0);i+=m[36]*vec3(4.903e-5,1.771e-5,0);i+=m[37]*vec3(2e-5,7.22e-6,0);return i;}float d(float y,float m,float v){float z=m*pow(v,2.);return z/(y*pow(1.-v,2.)+z);}vec3 f(vec3 v,vec3 y,float z){vec3 x=m(v),o=m(y);float i[38],a[38];f(x,i);f(o,a);float r=d(i)[1],e=d(a)[1];z=d(r,e,z);float s[38];for(int u=0;u<38;u++){float p=(1.-z)*(pow(1.-i[u],2.)/(2.*i[u]))+z*(pow(1.-a[u],2.)/(2.*a[u]));s[u]=1.+p-sqrt(pow(p,2.)+2.*p);}return t(d(s));}vec4 f(vec4 v,vec4 x,float y){return vec4(f(v.xyz,x.xyz,y),mix(v.w,x.w,y));}\n #endif\n float d(vec2 m,vec2 v,float y,out vec2 i){vec2 f=vec2(m.x+m.y*.5,m.y),x=floor(f),o=fract(f);float z=step(o.y,o.x);vec2 d=vec2(z,1.-z),r=x+d,e=x+1.,a=vec2(x.x-x.y*.5,x.y),p=vec2(a.x+d.x-d.y*.5,a.y+d.y),s=vec2(a.x+.5,a.y+1.),w=m-a,g=m-p,k=m-s;vec3 u,c,t,A;if(any(greaterThan(v,vec2(0)))){t=vec3(a.x,p.x,s);A=vec3(a.y,p.y,s.y);if(v.x>0.)t=mod(vec3(a.x,p.x,s),v.x);if(v.y>0.)A=mod(vec3(a.y,p.y,s.y),v.y);u=floor(t+.5*A+.5);c=floor(A+.5);}else u=vec3(x.x,r.x,e),c=vec3(x.y,r.y,e.y);vec3 S=mod(u,289.);S=mod((S*51.+2.)*S+c,289.);S=mod((S*34.+10.)*S,289.);vec3 b=S*.07482+y,C=cos(b),D=sin(b);vec2 h=vec2(C.x,D),B=vec2(C.y,D.y),E=vec2(C.z,D.z);vec3 F=.8-vec3(dot(w,w),dot(g,g),dot(k,k));F=max(F,0.);vec3 G=F*F,H=G*G,I=vec3(dot(h,w),dot(B,g),dot(E,k)),J=G*F,K=-8.*J*I;i=10.9*(H.x*h+K.x*w+(H.y*B+K.y*g)+(H.z*E+K.z*k));return 10.9*dot(H,I);}vec4 d(vec3 v,float x){return vec4(mix(v,vec3(dot(vec3(.299,.587,.114),v)),x),1);}float f(vec2 v,float x,float y,float f){return fract(sin(dot(v,vec2(x,y)))*f);}void main(){vec4 v=texture2D(mask,vVertTexCoord);if(v.x>0.){vec2 x=vec2(12.9898,78.233),o=vec2(7.9898,58.233),m=vec2(17.9898,3.233);float y=f(vVertTexCoord,x.x,x.y,43358.5453)*2.-1.,z=f(vVertTexCoord,o.x,o.y,43213.5453)*2.-1.,e=f(vVertTexCoord,m.x,m.y,33358.5453)*2.-1.;const vec2 i=vec2(0);vec2 s;vec4 r;if(active){float a=d(vVertTexCoord*5.,i,10.*random.x,s),p=d(vVertTexCoord*5.,i,10.*random.y,s),g=d(vVertTexCoord*5.,i,10.*random.z,s),k=.25+.25*d(vVertTexCoord*4.,i,3.*random.x,s);r=vec4(d(addColor.xyz,k).xyz+vec3(a,p,g)*.03*abs(addColor.x-addColor.y-addColor.z),1);}else r=vec4(addColor.xyz,1);if(v.w>.7){float a=.5*(v.w-.7);r=r*(1.-a)-vec4(.5)*a;}vec3 a=f(texture2D(source,vVertTexCoord).xyz,r.xyz,.9*v.w);gl_FragColor=vec4(a+.01*vec3(y,z,e),1);}}"};function w(){s.push(),s.translate(-v.trans()[0],-v.trans()[1]),s.image(y.masks[2],-s.width/2,-s.height/2),y.masks[2].clear(),s.pop()}function k(t){t.registerMethod("afterSetup",(()=>y.blend(!1,!0))),t.registerMethod("afterSetup",(()=>y.blend(!1,!0,!0))),t.registerMethod("post",(()=>y.blend(!1,!0))),t.registerMethod("post",(()=>y.blend(!1,!0,!0)))}function _(t,e){z.list.set(t,{gen:e}),z.current=t,z.refresh()}"undefined"!=typeof p5&&k(p5.prototype);const z={isActive:!1,list:new Map,current:"",step_length:()=>Math.min(s.width,s.height)/1e3,create(){this.R=.01*s.width,this.left_x=-1*s.width,this.top_y=-1*s.height,this.num_columns=Math.round(2*s.width/this.R),this.num_rows=Math.round(2*s.height/this.R),this.addStandard()},flow_field(){return this.list.get(this.current).field},refresh(t=0){this.list.get(this.current).field=this.list.get(this.current).gen(t,this.genField())},genField(){let t=new Array(this.num_columns);for(let e=0;e<this.num_columns;e++)t[e]=new Float64Array(this.num_rows);return t},addStandard(){_("curved",(function(t,e){let i=d.randInt(-25,-15);d.randInt(0,100)%2==0&&(i*=-1);for(let n=0;n<z.num_columns;n++)for(let o=0;o<z.num_rows;o++){let r=s.noise(.02*n+.03*t,.02*o+.03*t),a=d.map(r,0,1,-i,i);e[n][o]=3*a}return e})),_("truncated",(function(t,e){let i=d.randInt(-25,-15)+5*d.sin(t);d.randInt(0,100)%2==0&&(i*=-1);let n=d.randInt(5,10);for(let t=0;t<z.num_columns;t++)for(let o=0;o<z.num_rows;o++){let r=s.noise(.02*t,.02*o),a=Math.round(d.map(r,0,1,-i,i)/n)*n;e[t][o]=4*a}return e})),_("zigzag",(function(t,e){let i=d.randInt(-30,-15)+Math.abs(44*d.sin(t));d.randInt(0,100)%2==0&&(i*=-1);let s=i,n=0;for(let t=0;t<z.num_columns;t++){for(let i=0;i<z.num_rows;i++)e[t][i]=n,n+=s,s*=-1;n+=s,s*=-1}return e})),_("waves",(function(t,e){let i=d.randInt(10,15)+5*d.sin(t),s=d.randInt(3,6)+3*d.cos(t),n=d.randInt(20,35);for(let t=0;t<z.num_columns;t++)for(let o=0;o<z.num_rows;o++){let r=d.sin(i*t)*(n*d.cos(o*s))+d.randInt(-3,3);e[t][o]=r}return e})),_("seabed",(function(t,e){let i=d.random(.4,.8),s=d.randInt(18,26);for(let n=0;n<z.num_columns;n++)for(let o=0;o<z.num_rows;o++){let r=d.randInt(15,20),a=s*d.sin(i*o*n+r);e[n][o]=1.1*a*d.cos(t)}return e}))}};class b{constructor(t,e){this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,z.isActive&&(this.x_offset=this.x-z.left_x+v.trans()[0],this.y_offset=this.y-z.top_y+v.trans()[1],this.column_index=Math.round(this.x_offset/z.R),this.row_index=Math.round(this.y_offset/z.R))}reset(){this.plotted=0}isIn(){return z.isActive?this.column_index>=0&&this.row_index>=0&&this.column_index<z.num_columns&&this.row_index<z.num_rows:this.isInCanvas()}isInCanvas(){let t=s.width,e=s.height;return this.x>=-t-v.trans()[0]&&this.x<=t-v.trans()[0]&&this.y>=-e-v.trans()[1]&&this.y<=e-v.trans()[1]}angle(){return this.isIn()&&z.isActive?z.flow_field()[this.column_index][this.row_index]:0}moveTo(t,e,i=C.spacing(),s=!0){if(this.isIn()){let n,o;s||(n=d.cos(-e),o=d.sin(-e));for(let r=0;r<t/i;r++){if(s){let t=this.angle();n=d.cos(t-e),o=d.sin(t-e)}let t=i*n,r=i*o;this.plotted+=i,this.update(this.x+t,this.y+r)}}else this.plotted+=i}plotTo(t,e,i,s){if(this.isIn()){const n=1/s;for(let s=0;s<e/i;s++){let e=this.angle(),s=t.angle(this.plotted),o=i*d.cos(e-s),r=i*d.sin(e-s);this.plotted+=i*n,this.update(this.x+o,this.y+r)}}else this.plotted+=i/x}}function A(t){for(let e of Z){let i=C.list.get(e[0]).param;i.weight*=t,i.vibration*=t,i.spacing*=t}M=t}let M=1;const C={isActive:!0,list:new Map,c:"#000000",w:1,cr:null,name:"HB",spacing(){return this.p=this.list.get(this.name).param,"default"===this.p.type||"spray"===this.p.type?this.p.spacing/this.w:this.p.spacing},initializeDrawingState(t,e,i,s,n){this.position=new b(t,e),this.length=i,this.flow=s,this.plot=n,n&&n.calcIndex(0)},draw(t,e){e||(this.dir=t),this.pushState();const i=this.spacing(),s=e?Math.round(this.length*t/i):Math.round(this.length/i);for(let n=0;n<s;n++)this.tip(),e?this.position.plotTo(this.plot,i,i,t):this.position.moveTo(i,t,i,this.flow);this.popState()},drawTip(t){this.pushState(!0),this.tip(t),this.popState(!0)},pushState(t=!1){if(this.p=this.list.get(this.name).param,!t){this.a="custom"!==this.p.pressure.type?d.random(-1,1):0,this.b="custom"!==this.p.pressure.type?d.random(1,1.5):0,this.cp="custom"!==this.p.pressure.type?d.random(3,3.5):d.random(-.2,.2);const[t,e]=this.p.pressure.min_max;this.min=t,this.max=e}this.c=s.color(this.c),this.mask=this.p.blend?"image"===this.p.type?y.masks[1]:y.masks[0]:y.masks[2],v.trans(),this.mask.push(),this.mask.noStroke(),"image"===this.p.type?this.mask.translate(v.translation[0],v.translation[1]):this.mask.translate(v.translation[0]+s.width/2,v.translation[1]+s.height/2),this.mask.rotate(-v.rotation),this.mask.scale(g),this.p.blend&&(y.watercolor=!1,"image"!==this.p.type?y.blend(this.c):y.blend(this.c,!1,!0),t||this.markerTip()),this.alpha=this.calculateAlpha(),this.applyColor(this.alpha)},popState(t=!1){this.p.blend&&!t&&this.markerTip(),this.mask.pop()},tip(t=!1){let e=t||this.calculatePressure();if(this.isInsideClippingArea())switch(this.p.type){case"spray":this.drawSpray(e);break;case"marker":this.drawMarker(e);break;case"custom":case"image":this.drawCustomOrImage(e,this.alpha);break;default:this.drawDefault(e)}},calculatePressure(){return this.plot?this.simPressure()*this.plot.pressure(this.position.plotted):this.simPressure()},simPressure(){return"custom"===this.p.pressure.type?d.map(this.p.pressure.curve(this.position.plotted/this.length)+this.cp,0,1,this.min,this.max,!0):this.gauss()},gauss(t=.5+C.p.pressure.curve[0]*C.a,e=1-C.p.pressure.curve[1]*C.b,i=C.cp,s=C.min,n=C.max){return d.map(1/(1+Math.pow(Math.abs((this.position.plotted-t*this.length)/(e*this.length/2)),2*i)),0,1,s,n)},calculateAlpha(){return"default"!==this.p.type&&"spray"!==this.p.type?this.p.opacity/this.w:this.p.opacity},applyColor(t){this.p.blend?this.mask.fill(255,0,0,t/2):(this.c.setAlpha(t),this.mask.fill(this.c))},isInsideClippingArea(){if(C.cr)return this.position.x>=C.cr[0]&&this.position.x<=C.cr[2]&&this.position.y>=C.cr[1]&&this.position.y<=C.cr[3];{let t=.55*s.width,e=.55*s.height;return this.position.x>=-t-v.trans()[0]&&this.position.x<=t-v.trans()[0]&&this.position.y>=-e-v.trans()[1]&&this.position.y<=e-v.trans()[1]}},drawSpray(t){let e=this.w*this.p.vibration*t+this.w*d.gaussian()*this.p.vibration/3,i=this.p.weight*d.random(.9,1.1);const s=this.p.quality/t;for(let t=0;t<s;t++){let t=d.random(.9,1.1),s=t*e*d.random(-1,1),n=d.random(-1,1),o=Math.pow(t*e,2),r=Math.sqrt(o-Math.pow(s,2));this.mask.circle(this.position.x+s,this.position.y+n*r,i)}},drawMarker(t,e=!0){let i=e?this.w*this.p.vibration:0,s=e?i*d.random(-1,1):0,n=e?i*d.random(-1,1):0;this.mask.circle(this.position.x+s,this.position.y+n,this.w*this.p.weight*t)},drawCustomOrImage(t,e,i=!0){this.mask.push();let s=i?this.w*this.p.vibration:0,n=i?s*d.random(-1,1):0,o=i?s*d.random(-1,1):0;this.mask.translate(this.position.x+n,this.position.y+o),this.adjustSizeAndRotation(this.w*t,e),this.p.tip(this.mask),this.mask.pop()},drawDefault(t){let e=this.w*this.p.vibration*(this.p.definition+(1-this.p.definition)*d.gaussian()*this.gauss(.5,.9,5,.2,1.2)/t);d.random(0,this.p.quality*t)>.4&&this.mask.circle(this.position.x+.7*e*d.random(-1,1),this.position.y+e*d.random(-1,1),t*this.p.weight*d.random(.85,1.15))},adjustSizeAndRotation(t,e){if(this.mask.scale(t),"image"===this.p.type&&(this.p.blend?this.mask.tint(255,0,0,e/2):this.mask.tint(this.mask.red(this.c),this.mask.green(this.c),this.mask.blue(this.c),e)),"random"===this.p.rotate)this.mask.rotate(d.randInt(0,360));else if("natural"===this.p.rotate){let t=(this.plot?-this.plot.angle(this.position.plotted):-this.dir)+(this.flow?this.position.angle():0);this.mask.rotate(t)}},markerTip(){if(this.isInsideClippingArea()){let t=this.calculatePressure(),e=this.calculateAlpha(t);if(this.mask.fill(255,0,0,e/1.5),"marker"===C.p.type)for(let e=1;e<5;e++)this.drawMarker(t*e/5,!1);else if("custom"===C.p.type||"image"===C.p.type)for(let i=1;i<5;i++)this.drawCustomOrImage(t*i/5,e,!1)}}};function S(t,e){const i="marker"===e.type||"custom"===e.type||"image"===e.type;i||"spray"===e.type||(e.type="default"),"image"===e.type&&(B.add(e.image.src),e.tip=()=>C.mask.image(B.tips.get(C.p.image.src),-C.p.weight/2,-C.p.weight/2,C.p.weight,C.p.weight)),e.blend=!!(i&&!1!==e.blend||e.blend),C.list.set(t,{param:e,colors:[],buffers:[]})}function P(t,e,i=1){I(t),C.c=e,C.w=i,C.isActive=!0}function I(t){C.name=t}function D(t,e,i,s){c();let n=d.dist(t,e,i,s);if(0==n)return;C.initializeDrawingState(t,e,n,!1,!1);let o=p(t,e,i,s);C.draw(o,!1)}function T(t,e,i,s){c(),C.initializeDrawingState(e,i,t.length,!0,t),C.draw(s,!0)}const B={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 i=(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-i}t.updatePixels()},load(){for(let t of this.tips.keys()){let e=(r?a:window.self).loadImage(t,(()=>B.imageToWhite(e)));this.tips.set(t,e)}}};function E(t=5,e=45,i={rand:!1,continuous:!1,gradient:!1}){F.isActive=!0,F.hatchingParams=[t,e,i]}const F={isActive:!1,hatchingParams:[5,45,{}],hatchingBrush:!1,hatch(t){let e=F.hatchingParams[0],i=F.hatchingParams[1],s=F.hatchingParams[2],n=C.c,o=C.name,r=C.w,a=C.isActive;F.hatchingBrush&&P(F.hatchingBrush[0],F.hatchingBrush[1],F.hatchingBrush[2]),i=d.toDegrees(i)%180;let h=1/0,l=-1/0,c=1/0,m=-1/0,u=t=>{for(let e of t.a)h=e[0]<h?e[0]:h,l=e[0]>l?e[0]:l,c=e[1]<c?e[1]:c,m=e[1]>m?e[1]:m};Array.isArray(t)||(t=[t]);for(let e of t)u(e);let p=new V([[h,c],[l,c],[l,m],[h,m]]),f=i<=90&&i>=0?c:m,v=s.gradient?d.map(s.gradient,0,1,1,1.1,!0):1,g=[],x=0,y=e,w=t=>({point1:{x:h+y*t*d.cos(90-i),y:f+y*t*d.sin(90-i)},point2:{x:h+y*t*d.cos(90-i)+d.cos(-i),y:f+y*t*d.sin(90-i)+d.sin(-i)}});for(;p.intersect(w(x)).length>0;){let e=[];for(let i of t)e.push(i.intersect(w(x)));g[x]=e.flat().sort(((t,e)=>t.x===e.x?t.y-e.y:t.x-e.x)),y*=v,x++}let k=[];for(let t of g)void 0!==t[0]&&k.push(t);let _=s.rand?s.rand:0;for(let t=0;t<k.length;t++){let i=k[t],n=t>0&&s.continuous;for(let s=0;s<i.length-1;s+=2)0!==_&&(i[s].x+=_*e*d.random(-10,10),i[s].y+=_*e*d.random(-10,10),i[s+1].x+=_*e*d.random(-10,10),i[s+1].y+=_*e*d.random(-10,10)),D(i[s].x,i[s].y,i[s+1].x,i[s+1].y),n&&D(k[t-1][1].x,k[t-1][1].y,i[s].x,i[s].y)}P(o,n,r),C.isActive=a}},R=F.hatch;class V{constructor(t,e=!1){this.a=t,this.vertices=t.map((t=>({x:t[0],y:t[1]}))),e&&(this.vertices=t),this.sides=this.vertices.map(((t,e,i)=>[t,i[(e+1)%i.length]]))}intersect(t){let e=`${t.point1.x},${t.point1.y}-${t.point2.x},${t.point2.y}`;if(this._intersectionCache&&this._intersectionCache[e])return this._intersectionCache[e];let i=[];for(let e of this.sides){let s=u(t.point1,t.point2,e[0],e[1]);!1!==s&&i.push(s)}return this._intersectionCache||(this._intersectionCache={}),this._intersectionCache[e]=i,i}draw(t=!1,e,i){let s=C.isActive;if(t&&P(t,e,i),C.isActive){c();for(let t of this.sides)D(t[0].x,t[0].y,t[1].x,t[1].y)}C.isActive=s}fill(t=!1,e,i,s,n,o){let r=J.isActive;t&&(U(t,e),K(i,o),$(s,n)),J.isActive&&(c(),J.fill(this)),J.isActive=r}hatch(t=!1,e,i){let s=F.isActive;t&&E(t,e,i),F.isActive&&(c(),F.hatch(this)),F.isActive=s}erase(t=!1,e=j.a){if(j.isActive||t){y.masks[2].push(),y.masks[2].noStroke();let i=s.color(t||j.c);i.setAlpha(e),y.masks[2].fill(i),y.masks[2].beginShape();for(let t of this.vertices)y.masks[2].vertex(t.x,t.y);y.masks[2].endShape(s.CLOSE),y.masks[2].pop()}}show(){this.fill(),this.hatch(),this.draw(),this.erase()}}class G{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,i=1,s=!1){this.angles.length>0&&this.angles.splice(-1),t=s?(t%360+360)%360:d.toDegrees(t),this.angles.push(t),this.pres.push(i),this.segments.push(e),this.length=this.segments.reduce(((t,e)=>t+e),0),this.angles.push(t)}endPlot(t=0,e=1,i=!1){t=i?(t%360+360)%360:d.toDegrees(t),this.angles.splice(-1),this.angles.push(t),this.pres.push(e)}rotate(t){this.dir=d.toDegrees(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 i=t[this.index],s=t[this.index+1];return void 0===s&&(s=i),Math.abs(s-i)>180&&(s>i?s=-(360-s):i=-(360-i)),d.map(e-this.suma,0,this.segments[this.index],i,s,!0)}calcIndex(t){this.index=-1,this.suma=0;let e=0;for(;e<=t;)this.suma=e,e+=this.segments[this.index+1],this.index++;return this.index}genPol(t,e,i=1,s=!1){c();const n=.5,o=[],r=Math.round(this.length/n),a=new b(t,e);let h=s?.15:3*J.bleed_strength,l=0,m=0;for(let t=0;t<r;t++){a.plotTo(this,n,n,1);let t=this.calcIndex(a.plotted);l+=n,(l>=this.segments[t]*h*d.random(.7,1.3)||t>=m)&&a.x&&(o.push([a.x,a.y]),l=0,t>=m&&m++)}return new V(o)}draw(t,e,i){C.isActive&&(c(),this.origin&&(t=this.origin[0],e=this.origin[1],i=1),T(this,t,e,i))}fill(t,e,i){J.isActive&&(c(),this.origin&&(t=this.origin[0],e=this.origin[1],i=1),this.pol=this.genPol(t,e,i),this.pol.fill())}hatch(t,e,i){F.isActive&&(c(),this.origin&&(t=this.origin[0],e=this.origin[1],i=1),this.pol=this.genPol(t,e,i,!0),this.pol.hatch())}erase(t,e,i){if(j.isActive){this.origin&&(t=this.origin[0],e=this.origin[1],i=1),this.pol=this.genPol(t,e,i,!0),y.masks[2].push(),y.masks[2].noStroke();let n=s.color(j.c);n.setAlpha(j.a),y.masks[2].fill(n),y.masks[2].beginShape();for(let t of this.pol.vertices)y.masks[2].vertex(t.x,t.y);y.masks[2].endShape(s.CLOSE),y.masks[2].pop()}}show(t,e,i=1){this.draw(t,e,i),this.fill(t,e,i),this.hatch(t,e,i),this.erase(t,e,i)}}let L,H=!1;function O(t=0){L=d.constrain(t,0,1),H=[]}function q(t,e,i){H.push([t,e,i])}function N(t){c(),t===s.CLOSE&&(H.push(H[0]),H.push(H[1])),(0!=L||z.isActive?W(H,L,t===s.CLOSE):new V(H)).show(),H=!1}function W(t,e=.5,i=!1){let s=new G(0===e?"segments":"curve");if(t&&t.length>0){let n,o,r,a=0;for(let h=0;h<t.length-1;h++)if(e>0&&h<t.length-2){let l=t[h],c=t[h+1],m=t[h+2],f=d.dist(l[0],l[1],c[0],c[1]),v=d.dist(c[0],c[1],m[0],m[1]),g=p(l[0],l[1],c[0],c[1]),x=p(c[0],c[1],m[0],m[1]),y=e*Math.min(Math.min(f,v),.5*Math.min(f,v)),w=Math.max(f,v),k=f-y,_=v-y;if(Math.floor(g)===Math.floor(x)){let e=i&&0===h?0:f-a,m=i?0===h?0:v-r:v;s.addSegment(g,e,l[2],!0),h===t.length-3&&s.addSegment(x,m,c[2],!0),a=0,0===h&&(n=f,r=y,o=t[1],a=0)}else{let e={x:c[0]-y*d.cos(-g),y:c[1]-y*d.sin(-g)},m={x:e.x+w*d.cos(90-g),y:e.y+w*d.sin(90-g)},p={x:c[0]+y*d.cos(-x),y:c[1]+y*d.sin(-x)},f=u(e,m,p,{x:p.x+w*d.cos(90-x),y:p.y+w*d.sin(90-x)},!0),v=d.dist(e.x,e.y,f.x,f.y),z=d.dist(e.x,e.y,p.x,p.y)/2,b=2*Math.asin(z/v)*(180/Math.PI),A=2*Math.PI*v*b/360,M=i&&0===h?0:k-a,C=h===t.length-3?i?n-y:_:0;s.addSegment(g,M,l[2],!0),s.addSegment(g,isNaN(A)?0:A,l[2],!0),s.addSegment(x,C,c[2],!0),a=y,0===h&&(n=k,r=y,o=[e.x,e.y])}h==t.length-3&&s.endPlot(x,c[2],!0)}else if(0===e){0===h&&i&&t.pop();let e=t[h],n=t[h+1],o=d.dist(e[0],e[1],n[0],n[1]),r=p(e[0],e[1],n[0],n[1]);s.addSegment(r,o,1,!0),h==t.length-2&&s.endPlot(r,1,!0)}s.origin=i&&0!==e?o:t[0]}return s}const j={};function U(t,e,i,n){c(),J.opacity=arguments.length<4?arguments.length<3?e:1:n,J.color=arguments.length<3?s.color(t):s.color(t,e,i),J.isActive=!0}function K(t,e="out"){c(),J.bleed_strength=d.constrain(t,0,.6),J.direction=e}function $(t=.4,e=.4){c(),J.texture_strength=d.constrain(t,0,1),J.border_strength=d.constrain(e,0,1)}const J={isActive:!1,isAnimated:!1,color:"#002185",opacity:80,bleed_strength:.07,texture_strength:.4,border_strength:.4,fill(t){this.polygon=t,this.v=[...t.vertices];const e=this.v.length*d.random(.4);J.m=this.v.map(((t,i)=>{let s=d.random(.8,1.2)*this.bleed_strength;return i<e?d.constrain(2*s,0,.9):s}));let i=d.randInt(0,this.v.length);if(J.light_source)for(let t=0;t<this.v.length;t++)d.dist(this.v[t].x,this.v[t].y,J.light_source.x,J.light_source.y)<d.dist(this.v[i].x,this.v[i].y,J.light_source.x,J.light_source.y)&&(i=t);this.v=[...this.v.slice(i),...this.v.slice(0,i)],new X(this.v,this.m,this.calcCenter(),[],!0).fill(this.color,Math.floor(d.map(this.opacity,0,155,0,20,!0)),this.texture_strength)},calcCenter(){let t=0,e=0;for(let i=0;i<this.v.length;++i)t+=this.v[i].x,e+=this.v[i].y;return t/=this.v.length,e/=this.v.length,{x:t,y:e}}};function Q(t,e,i,s,n){let o=d.cos(n),r=d.sin(n);return{x:o*(i-t)+r*(s-e)+t,y:o*(s-e)-r*(i-t)+e}}class X{constructor(t,e,i,s,n=!1){this.pol=new V(t,!0),this.v=t,this.dir=s,this.m=e,this.midP=i,this.size=-1/0;for(let t of this.v){let e=d.dist(this.midP.x,this.midP.y,t.x,t.y);e>this.size&&(this.size=e)}if(n)for(let t=0;t<this.v.length;t++){const e=this.v[t],i=this.v[(t+1)%this.v.length],s={x:i.x-e.x,y:i.y-e.y},n=Q(0,0,s.x,s.y,90);let o={point1:{x:e.x+s.x/2,y:e.y+s.y/2},point2:{x:e.x+s.x/2+n.x,y:e.y+s.y/2+n.y}};const r=(t,e,i)=>(e.x-t.x)*(i.y-t.y)-(e.y-t.y)*(i.x-t.x)>.01;let a=0;for(let t of J.polygon.intersect(o))r(e,i,t)&&a++;this.dir[t]=a%2==0}}trim(t){let e=[...this.v],i=[...this.m],s=[...this.dir];if(this.v.length>10&&t>=.2){let n=~~((1-t)*this.v.length),o=~~this.v.length/2-~~n/2;e.splice(o,n),i.splice(o,n),s.splice(o,n)}return{v:e,m:i,dir:s}}grow(t,e=!1){const i=[],s=[],n=[];let o=this.trim(t);const r=e?-.5:1,a=t=>t+.1*(d.gaussian(.5,.1)-.5);for(let e=0;e<o.v.length;e++){const h=o.v[e],l=o.v[(e+1)%o.v.length];let c=.1===t?J.bleed_strength<=.1?.25:.75:o.m[e];c*=r,i.push(h),s.push(a(c));let m={x:l.x-h.x,y:l.y-h.y},u=o.dir[e],p="out"==J.direction?-90:90,f=(u?p:-p)+45*d.gaussian(0,.4),v=d.constrain(d.gaussian(.5,.2),.1,.9),g={x:h.x+m.x*v,y:h.y+m.y*v},x=d.gaussian(.5,.2)*d.random(.6,1.4)*c,y=Q(0,0,m.x,m.y,f);g.x+=y.x*x,g.y+=y.y*x,i.push(g),s.push(a(c)),n.push(u,u)}return new X(i,s,this.midP,n)}fill(t,e,i){let n=d.map(J.bleed_strength,0,.15,.6,1,!0);const o=24*n,r=e/5+i*e/6,a=e/4+i*e/3,h=e/7+i*e/3,l=e/5,c=3*i;y.watercolor=!0,v.trans(),y.blend(t,!1,!1,!0),y.masks[0].push(),y.masks[0].noStroke(),y.masks[0].translate(v.translation[0]+s.width/2,v.translation[1]+s.height/2),y.masks[0].rotate(v.rotation),y.masks[0].scale(g);let m=this.grow(),u=m.grow().grow(.9),p=u.grow(.75),f=this.grow(.6);for(let t=0;t<o;t++)t!==Math.floor(o/4)&&t!==Math.floor(o/2)&&t!==Math.floor(3*o/4)||(m=m.grow(),1!==n&&t!==Math.floor(o/2)||(u=u.grow(.75),p=p.grow(.75),f=f.grow(.1,!0))),m.grow().layer(t,l),f.grow(.1,!0).grow(.1).layer(t,h,!1),u.grow(.1).grow(.1).layer(t,a,!1),p.grow(.8).grow(.1).layer(t,r,!1),0!==c&&m.erase(c,e);y.masks[0].pop()}layer(t,e,i=!0){y.masks[0].fill(255,0,0,e),i?(y.masks[0].stroke(255,0,0,.5+1.5*J.border_strength),y.masks[0].strokeWeight(d.map(t,0,24,6,.5))):y.masks[0].noStroke(),y.masks[0].beginShape();for(let t of this.v)y.masks[0].vertex(t.x,t.y);y.masks[0].endShape(s.CLOSE)}erase(t,e){const i=d.random(130,200),s=this.size/2,n=.025*this.size,o=.19*this.size;y.masks[0].erase(3.5*t-d.map(e,80,120,.3,1,!0),0);for(let t=0;t<i;t++){const t=this.midP.x+d.gaussian(0,s),e=this.midP.y+d.gaussian(0,s),i=d.random(n,o);y.masks[0].circle(t,e,i)}y.masks[0].noErase()}}const Y=["weight","vibration","definition","quality","opacity","spacing","pressure","type","tip","rotate"],Z=[["pen",[.35,.12,.5,8,200,.3,{curve:[.15,.2],min_max:[1.4,.9]}]],["rotring",[.2,.05,1,3,250,.15,{curve:[.05,.2],min_max:[1.7,.8]}]],["2B",[.35,.5,.1,8,180,.2,{curve:[.15,.2],min_max:[1.3,1]}]],["HB",[.3,.5,.4,4,180,.25,{curve:[.15,.2],min_max:[1.2,.9]}]],["2H",[.2,.4,.3,2,150,.2,{curve:[.15,.2],min_max:[1.2,.9]}]],["cpencil",[.4,.6,.8,7,120,.15,{curve:[.15,.2],min_max:[.95,1.2]}]],["charcoal",[.5,2,.8,300,110,.06,{curve:[.15,.2],min_max:[1.3,.8]}]],["hatch_brush",[.2,.4,.3,2,150,.15,{curve:[.5,.7],min_max:[1,1.5]}]],["spray",[.3,12,15,40,80,.65,{curve:[0,.1],min_max:[.15,1.2]},"spray"]],["marker",[2.5,.12,null,null,25,.4,{curve:[.35,.25],min_max:[1.5,1]},"marker"]],["marker2",[2.5,.12,null,null,25,.35,{curve:[.35,.25],min_max:[1.3,.95]},"custom",function(t){let e=M;t.rect(-1.5*e,-1.5*e,3*e,3*e),t.rect(1*e,1*e,1*e,1*e)},"natural"]]];for(let t of Z){let e={};for(let i=0;i<t[1].length;i++)e[Y[i]]=t[1][i];S(t[0],e)}t.Plot=G,t.Polygon=V,t.Position=b,t.add=S,t.addField=_,t.arc=function(t,e,i,s,n){c();let o=new G("curve"),r=270-d.toDegrees(s),a=270-d.toDegrees(n),h=d.toDegrees(n-s),l=Math.PI*i*h/180;o.addSegment(r,l,1,!0),o.endPlot(a,1,!0),o.draw(t+i*d.cos(-r-90),e+i*d.sin(-r-90),1)},t.beginShape=O,t.beginStroke=function(t,e,i){L=[e,i],H=new G(t)},t.bleed=K,t.box=function(){return Array.from(C.list.keys())},t.circle=function(t,e,i,s=!1){c();let n=new G("curve"),o=Math.PI*i/2,r=d.random(0,360),a=()=>s?d.random(-1,1):0;n.addSegment(0+r+a(),o+a(),1,!0),n.addSegment(-90+r+a(),o+a(),1,!0),n.addSegment(-180+r+a(),o+a(),1,!0),n.addSegment(-270+r+a(),o+a(),1,!0);let h=s?d.randInt(-5,5):0;s&&n.addSegment(0+r,h*(Math.PI/180)*i,!0),n.endPlot(h+r,1,!0);let l=[t-i*d.sin(r),e-i*d.cos(-r)];n.show(l[0],l[1],1)},t.clip=function(t){C.cr=t},t.colorCache=function(t=!0){y.isCaching=t},t.endShape=N,t.endStroke=function(t,e){H.endPlot(t,e),H.draw(L[0],L[1],1),H=!1},t.erase=function(t="white",e=255){j.isActive=!0,j.c=t,j.a=e},t.field=function(t){c(),z.isActive=!0,z.current=t},t.fill=U,t.fillAnimatedMode=function(t){J.isAnimated=t},t.fillTexture=$,t.flowLine=function(t,e,i,s){c(),C.initializeDrawingState(t,e,i,!0,!1),C.draw(d.toDegrees(s),!1)},t.gravity=function(t,e){c(),J.light_source={x:t,y:e}},t.hatch=E,t.hatchArray=R,t.instance=function(t){r=!0,a=t,s=t,k(t)},t.line=D,t.listFields=function(){return Array.from(z.list.keys())},t.load=h,t.noClip=function(){C.cr=null},t.noErase=function(){j.isActive=!1},t.noField=function(){c(),z.isActive=!1},t.noFill=function(){J.isActive=!1},t.noGravity=function(){J.light_source=!1},t.noHatch=function(){F.isActive=!1,F.hatchingBrush=!1},t.noStroke=function(){C.isActive=!1},t.pick=I,t.plot=T,t.polygon=function(t){new V(t).show()},t.pop=function(){z.isActive=f.field.isActive,z.current=f.field.current,C.isActive=f.stroke.isActive,C.name=f.stroke.name,C.c=f.stroke.color,C.w=f.stroke.weight,C.cr=f.stroke.clip,F.isActive=f.hatch.isActive,F.hatchingParams=f.hatch.hatchingParams,F.hatchingBrush=f.hatch.hatchingBrush,J.isActive=f.fill.isActive,J.color=f.fill.color,J.opacity=f.fill.opacity,J.bleed_strength=f.fill.bleed_strength,J.texture_strength=f.fill.texture_strength,J.border_strength=f.fill.border_strength,v.rotation=f.others.rotate},t.preload=function(){B.load()},t.push=function(){f.field.isActive=z.isActive,f.field.current=z.current,f.stroke.isActive=C.isActive,f.stroke.name=C.name,f.stroke.color=C.c,f.stroke.weight=C.w,f.stroke.clip=C.cr,f.hatch.isActive=F.isActive,f.hatch.hatchingParams=F.hatchingParams,f.hatch.hatchingBrush=F.hatchingBrush,f.fill.isActive=J.isActive,f.fill.color=J.color,f.fill.opacity=J.opacity,f.fill.bleed_strength=J.bleed_strength,f.fill.texture_strength=J.texture_strength,f.fill.border_strength=J.border_strength,f.others.rotate=v.rotation},t.reBlend=function(){y.blend(!1,!0),y.blend(!1,!0,!0)},t.reDraw=w,t.rect=function(t,e,i,n,o=s.CORNER){if(o==s.CENTER&&(t-=i/2,e-=n/2),z.isActive)O(0),q(t,e),q(t+i,e),q(t+i,e+n),q(t,e+n),N(s.CLOSE);else{new V([[t,e],[t+i,e],[t+i,e+n],[t,e+n]]).show()}},t.refreshField=function(t){z.refresh(t)},t.remove=l,t.rotate=function(t=0){v.rotation=d.toDegrees(t)},t.scale=x,t.scaleBrushes=A,t.seed=function(t){m=new e(t)},t.segment=function(t,e,i){H.addSegment(t,e,i)},t.set=P,t.setHatch=function(t,e="black",i=1){F.hatchingBrush=[t,e,i]},t.spline=function(t,e=.5){W(t,e).draw()},t.stroke=function(t,e,i){arguments.length>0&&(C.c=arguments.length<2?t:[t,e,i]),C.isActive=!0},t.strokeWeight=function(t){C.w=t},t.vertex=q}));+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={x:()=>n._renderer.uModelMatrix.mat4[12],y:()=>n._renderer.uModelMatrix.mat4[13],a:()=>n._renderer.uModelMatrix.mat4[0],b:()=>n._renderer.uModelMatrix.mat4[1],c:()=>n._renderer.uModelMatrix.mat4[4],d:()=>n._renderer.uModelMatrix.mat4[5]};let W=!1;function $(){W||(u(),j=.01*e,U=-.5*e,Z=-.5*r,V=Math.round(2*e/j),K=Math.round(2*r/j),nt("hand",((t,e)=>{const r=R(.2,.8),i=E(5,10);return ot(e,((e,n)=>.5*i*O(r*n*e+E(15,25))*.2*z(t)+w(e,n)*i*.7))})),nt("curved",((t,e)=>{let r=E(-10,10);return E(0,100)%2==0&&(r*=-1),ot(e,((e,i)=>3*M(w(.02*e+.03*t,.02*i+.03*t),0,1,-r,r)))})),nt("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<V;t++){for(let r=0;r<K;r++)e[t][r]=n,n+=i,i*=-1;n+=i,i*=-1}return e})),nt("waves",((t,e)=>{const r=E(10,15)+5*O(t),i=E(3,6)+3*z(t),n=E(20,35);return ot(e,((t,e)=>O(r*t)*n*z(e*i)+E(-3,3)))})),nt("seabed",((t,e)=>{const r=R(.4,.8),i=E(18,26);return ot(e,((e,n)=>1.1*i*O(r*n*e+E(15,20))*z(t)))})),nt("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)*V,y:R(.1,.9)*K})));return ot(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)}))})),nt("columns",((t,e)=>{const r=E(3,8),i=E(25,45);return ot(e,((t,e)=>O(t*r)*i))})),W=!0)}class H{constructor(t,e){$(),this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=H.getColIndex(t),this.rowIdx=H.getRowIndex(e)}reset(){this.plotted=0}isIn(){return h.field.isActive?H.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const t=e,i=r,n=this.x+G.x(),o=this.y+G.y();return n>=-.3*t&&n<=1.3*t&&o>=-.3*i&&o<=1.3*i}angle(){return this.isIn()&&h.field.isActive?et.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+G.y()-Z;return Math.round(r/j/e)}static getColIndex(t,e=1){const r=t+G.x()-U;return Math.round(r/j/e)}static isIn(t,e){return t>=0&&e>=0&&t<V&&e<K}}h.field={isActive:!1,current:null,wiggle:1};let j,U,Z,V,K,q,J,Q,tt,et=new Map;function rt(){return new Array(V).fill(null).map((()=>new Float32Array(K)))}function it(t){if(h.field.wiggle||(h.field.wiggle=1),$(),!et.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(et.keys()).join(", ")}.`);h.field.isActive=!0,h.field.current=t;const e=et.get(t);e.field||(e.field=e.gen(0,rt()))}function nt(t,e){et.set(t,{gen:e,field:null})}function ot(t,e){for(let r=0;r<V;r++)for(let i=0;i<K;i++)t[r][i]=e(r,i);return t}class st{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 at{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){$();const s=.5,a=[],l=Math.round(this.length/s),c=new H(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 st(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 lt{constructor(){this.isClosed=!1,this.curvature=J,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){ft(this.vert,this.curvature,this.isClosed).show()}}function ct(t=0){J=k(t,0,1),q=new lt}function ht(t,e,r=1){if(!q)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");q.vertex(t,e,r)}function ut(t=!1){if(!q)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(q.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(q.vertex(...q.vert[0]),q.isClosed=!0),q.show(),q=!1}function ft(t,e=.5,r=!1){const i=new at(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}const gt=(t,e,r)=>{const i=t.createProgram();for(let[n,o]of[[t.VERTEX_SHADER,e],[t.FRAGMENT_SHADER,r]]){const e=t.createShader(n);t.shaderSource(e,o),t.compileShader(e),t.attachShader(i,e)}return t.linkProgram(i),i};var dt="#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;}",mt="#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);}";let pt,xt,yt,vt,_t,bt=!1;const wt={},Rt={};let St=1,Et=0,At=0,Pt=1,Mt=0,kt=0,Lt=new Float32Array(8192),Ct=0,It=2048,Tt=32768;function Nt(t,i,n,s){if(Ct>=It){It*=2;const t=new Float32Array(4*It);t.set(Lt),Lt=t}const a=t-e/2,l=i-r/2,c=4*Ct;Lt[c]=St*a+At*l+Mt+e/2,Lt[c+1]=Et*a+Pt*l+kt+r/2,Lt[c+2]=o*n*Math.sqrt(St*St+Et*Et)/2,Lt[c+3]=s/255,Ct++}function zt(){if(0===Ct)return;f.glMask.isDrawn=!0;const t=h.stroke.color._array;pt.useProgram(_t),pt.enable(pt.BLEND),pt.blendFunc(pt.ONE_MINUS_DST_ALPHA,pt.ONE),pt.bindVertexArray(yt),pt.bindBuffer(pt.ARRAY_BUFFER,vt);const e=16*Ct,r=Lt.subarray(0,4*Ct);e>Tt?(pt.bufferData(pt.ARRAY_BUFFER,Lt,pt.DYNAMIC_DRAW),Tt=Lt.byteLength):pt.bufferSubData(pt.ARRAY_BUFFER,0,r),pt.uniform4f(Rt.u_color,...t),pt.uniformMatrix4fv(Rt.u_matrix,!1,xt),pt.drawArrays(pt.POINTS,0,Ct),pt.bindVertexArray(null),Ct=0}h.stroke={color:null,weight:1,clipWindow:null,type:"HB",isActive:!1,opacity:1};let Ot,Bt,Dt,Yt,Ft=new Map,Xt=null;function Gt(){return{...h.stroke}}function Wt(t){h.stroke={...t}}function $t(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 he.add(e.image.src),e.tip=()=>{Xt.image(he.tips.get(Vt.p.image.src),-Vt.p.weight/2,-Vt.p.weight/2,Vt.p.weight,Vt.p.weight)},Ft.set(t,{param:e,colors:[],buffers:[]}),he.load()}Ft.set(t,{param:e,colors:[],buffers:[]})}function Ht(t){if(!Ft.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...Ft.keys()].join(", ")}.`);h.stroke.type=t}function jt(t,e,r){c(),h.stroke.color=n.color(...arguments),h.stroke.isActive=!0}function Ut(t){h.stroke.weight=t}function Zt(t,e,r=1){Ht(t),jt(e),Ut(r)}const Vt={};function Kt(t,i,n,o=!1){St=G.a(),Et=G.b(),At=G.c(),Pt=G.d(),Mt=G.x(),kt=G.y(),Ot=new H(t+e/2,i+r/2),Bt=n,Dt=o,Dt&&Dt.calcIndex(0)}const qt=[];function Jt(t,i){i||(Yt=t),function(){Vt.seed=999999*R();const{param:t}=Ft.get(h.stroke.type)??{};if(!t)return;Vt.p=t,Xt=f.glMask;const{pressure:i}=t;if(Vt.a="custom"!==i.type?R(-1,1):0,Vt.b="custom"!==i.type?R(1,1.5):0,Vt.cp="custom"!==i.type?R(3,3.5):R(-.2,.2),[Vt.min,Vt.max]=i.min_max,Vt.noiseoffset=.03,!Dt){const t=Yt*Math.PI/180;Vt.cos=Math.cos(t),Vt.sin=Math.sin(t)}(function(){if(!bt){u(),pt=f.glMask.drawingContext,xt=new Float32Array([2/e,0,0,0,0,-2/r,0,0,0,0,1,0,-1,1,0,1]),_t=gt(pt,dt,mt),pt.useProgram(_t),pt.enable(pt.BLEND),pt.blendFunc(pt.ONE_MINUS_DST_ALPHA,pt.ONE),["a_position","a_radius","a_alpha"].forEach((t=>wt[t]=pt.getAttribLocation(_t,t))),["u_matrix","u_color"].forEach((t=>Rt[t]=pt.getUniformLocation(_t,t))),yt=pt.createVertexArray(),pt.bindVertexArray(yt),vt=pt.createBuffer(),pt.bindBuffer(pt.ARRAY_BUFFER,vt),pt.bufferData(pt.ARRAY_BUFFER,Lt.byteLength,pt.DYNAMIC_DRAW);const t=16;pt.enableVertexAttribArray(wt.a_position),pt.vertexAttribPointer(wt.a_position,2,pt.FLOAT,!1,t,0),pt.enableVertexAttribArray(wt.a_radius),pt.vertexAttribPointer(wt.a_radius,1,pt.FLOAT,!1,t,8),pt.enableVertexAttribArray(wt.a_alpha),pt.vertexAttribPointer(wt.a_alpha,1,pt.FLOAT,!1,t,12),pt.bindVertexArray(null),bt=!0}})(),ie()&&f.blend(h.stroke.color),!1===f.isBrush&&(f.justChanged=!0),f.isBrush=!0,Vt.alpha=re(),se()}();const n=function(){const{param:t}=Ft.get(h.stroke.type)??{};return t?t.spacing:1}(),o=Math.round(Bt*(i?t:1)/n);for(let e=0;e<o;e++)qt.length<2*o&&qt.push(A()),Qt(),i?Ot.plotTo(Dt,n,n,t,e<10):Ot.moveTo(t,n,n);zt(),se()}function Qt(t=!1){if(!ie())return;let e=t||te(),r=M(w(Vt.seed+.002*Ot.plotted,0),0,1,1-Vt.noiseoffset,1+Vt.noiseoffset);switch(Vt.p.type){case"spray":!function(t){const e=h.stroke.weight*Vt.p.scatter*t+h.stroke.weight*S(qt)*Vt.p.scatter/3,r=Vt.p.weight*R(.9,1.1),i=Math.ceil(Vt.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);Nt(Ot.x+i,Ot.y+n*o,r,Vt.alpha)}}(e*r);break;case"marker":ne(e*r);break;case"custom":case"image":oe(e*r,Vt.alpha);break;default:!function(t,e=1){const r=(e=M(e,0,1,.9,1.05))*h.stroke.weight*Vt.p.scatter*(Vt.p.sharpness+(1-Vt.p.sharpness)*S(qt)/t);if(R(0,Vt.p.grain*t)>.4){let e,i;if(Dt)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*-Vt.sin+n*Vt.cos,i=t*Vt.cos+n*Vt.sin}Nt(Ot.x+e,Ot.y+i,t*t*Vt.p.weight*R(.85,1.15)*h.stroke.weight,Math.max(.9,t)*Vt.alpha*R(.75,1.1))}}(e*r)}}function te(){return Dt?ee()*Dt.pressure(Ot.plotted):ee()}function ee(){return"custom"===Vt.p.pressure.type?M(Vt.p.pressure.curve(Ot.plotted/Bt)+Vt.cp,0,1,Vt.min,Vt.max,!0):function(t=.5+Vt.p.pressure.curve[0]*Vt.a,e=1-Vt.p.pressure.curve[1]*Vt.b,r=Vt.cp,i=Vt.min,n=Vt.max){const o=t*Bt,s=(Ot.plotted<o?1.2*e:.8*e)*(Bt/2);return M(1/(1+Math.pow(Math.abs((Ot.plotted-o)/s),2*r)),0,1,i,n)}()}function re(){return["default","spray"].includes(Vt.p.type)?Vt.p.opacity:Vt.p.opacity/Math.min(h.stroke.weight,1.3)}function ie(){if(h.stroke.clipWindow)return Ot.x>=h.stroke.clipWindow[0]&&Ot.x<=h.stroke.clipWindow[2]&&Ot.y>=h.stroke.clipWindow[1]&&Ot.y<=h.stroke.clipWindow[3];{let t=e,i=r,n=.05*e,o=Ot.x+G.x(),s=Ot.y+G.y();return o>=-n&&o<=t+n&&s>=-n&&s<=i+n}}function ne(t,e=!0,r=Vt.alpha){const i=e?h.stroke.weight*Vt.p.scatter:0,n=e?i*R(-1,1):0,o=e?i*R(-1,1):0;Nt(Ot.x+n,Ot.y+o,h.stroke.weight*Vt.p.weight*t,r)}function oe(t,i,n=!0){f.glMask.isDrawn=!0,Xt.push(),Xt.noStroke(),h.stroke.color.setAlpha(i),Xt.fill(h.stroke.color);const o=n?h.stroke.weight*Vt.p.scatter:0,s=n?o*R(-1,1):0,a=n?o*R(-1,1):0;Xt.translate(Ot.x+s-e,Ot.y+a-r),function(t,e){Xt.scale(t),"image"===Vt.p.type&&Xt.tint(255,0,0,e/2);let r=0;"random"===Vt.p.rotate?r=E(0,360):"natural"===Vt.p.rotate&&(r=(Dt?-Dt.angle(Ot.plotted):-Yt)+Ot.angle()),Xt.rotate(r)}(h.stroke.weight*t,i),Vt.p.tip(Xt),Xt.pop()}function se(){if(ie()){let t=te(),e=re();if("marker"===Vt.p.type){for(let r=1;r<10;r++)ne(t*r/10,!1,5*e);zt()}else if("custom"===Vt.p.type||"image"===Vt.p.type)for(let r=1;r<5;r++)oe(t*r/5,e,!1)}}function ae(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.");$();let n=Y(t,e,r,i);0!=n&&(Kt(t,e,n),Jt(F(t,e,r,i),!1))}const le=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate"],ce=[["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 ce){let e={};for(let r=0;r<t[1].length;r++)e[le[r]]=t[1][r];$t(t[0],e)}st.prototype.draw=function(t=!1,e,r){let i=Gt();if(t&&Zt(t,e,r),i.isActive)for(let t of this.sides)ae(t[0].x,t[0].y,t[1].x,t[1].y);Wt(i)},at.prototype.draw=function(t,e,r){Gt().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,i){$(),Kt(e,r,t.length,t),Jt(i,!0)}(this,t,e,r))};const he={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),he.imageToWhite(r),this.tips.set(t,r),e()},i.onerror=()=>r(new Error(`Failed to load image tip: ${t}`)),i.src=t})))))}};function ue(){return{...h.hatch}}function fe(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 ge(t){let e=h.hatch.dist,r=B(h.hatch.angle)%180,i=h.hatch.options,n=Gt();h.hatch.hBrush&&Zt(...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=de(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 st([[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(-10,10),r[i].y+=m*e*R(-10,10),r[i+1].x+=m*e*R(-10,10),r[i+1].y+=m*e*R(-10,10)),ae(r[i].x,r[i].y,r[i+1].x,r[i+1].y),n&&ae(d[t-1][1].x,d[t-1][1].y,r[i].x,r[i].y)}Wt(n)}function de(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 me(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},st.prototype.hatch=function(t=!1,e,r){let i=ue();t&&fe(t,e,r),i.isActive&&ge(this),function(t){h.hatch={...t}}(i)},at.prototype.hatch=function(t,e,r){ue().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:60,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const pe=()=>({...h.fill});function xe(t,e,r,i){h.fill.opacity=(arguments.length<4?e:i)||60,h.fill.color=arguments.length<3?n.color(t):n.color(t,e,r),h.fill.isActive=!0}function ye(t,e="out"){h.fill.bleed_strength=k(t,0,1),h.fill.direction=e}function ve(t=.4,e=.4){h.fill.texture_strength=k(t,0,1),h.fill.border_strength=k(e,0,1)}let _e;const be=[[],[]];class we{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 _e.intersect(t.ray))i=t.v1,o=e,((n=t.v2).x-i.x)*(o.y-i.y)-(n.y-i.y)*(o.x-i.x)>.01&&r++;var i,n,o;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++){be[0].length<1.5*n&&(be[0].push(A(.5,.2)),be[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(be[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(be[1]),a[c++]=i[h]}return new we(o,s,this.midP,a,!1,this.sizeX,this.sizeY)}fill(t,i,n){const o=3*n,s=2*i*(1+n/2);f.blend(t),f.justChanged=!0,f.isBrush=!1,f.ctx.save(),f.ctx.setTransform(G.a(),G.b(),G.c(),G.d(),G.x()+e/2,G.y()+r/2),f.ctx.strokeStyle=`rgb(${t._getRed()} ${t._getGreen()} ${t._getBlue()} / ${.005*h.fill.border_strength})`,f.ctx.lineCap="round";const a=Math.max(this.sizeX,this.sizeY),l=R(.15,.7);let c,u=this.grow();for(let e=0;e<20;e++){e%4==0&&(u=u.grow()),e%2==0&&(c=[u.grow(1-.0125*e),u.grow(.7-.0125*e),u.grow(.4-.0125*e)]);for(const r of c)r.grow(999).grow(997).layer(e,a,s,t);e%2==0&&u.grow(l).grow(999).layer(e,a,2*s,t),e%5!=0&&19!==e||(0!==o&&u.erase(3*o,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(),me(e,r,o),t%5!=0&&f.ctx.fill()}f.ctx.globalCompositeOperation="source-over",f.ctx.restore()}}st.prototype.fill=function(t=!1,e,r,i,n,o){let s=pe();t&&(xe(t,e),ye(r,o),ve(i,n)),s.isActive&&($(),function(t){if(!h.fill.isActive||!h.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");_e=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 we(s,n,a,[],!0).fill(h.fill.color,M(h.fill.opacity,0,100,0,1,!0),h.fill.texture_strength)}(this)),(t=>{h.fill={...t}})(s)},at.prototype.fill=function(t,e,r){pe().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 Re=[];"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;e.push=function(){i.call(this),$(),Re.push({fill:{...h.fill},stroke:{...h.stroke},hatch:{...h.hatch},field:{...h.field}})},e.pop=function(){n.call(this),function(){const t=Re.pop();t&&(h.stroke={...t.stroke},h.field={...t.field},h.hatch={...t.hatch},h.fill={...t.fill})}()}})),t.Plot=at,t.Polygon=st,t.Position=H,t.add=$t,t.addField=nt,t.arc=function(t,e,r,i,n){const o=new at("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=ct,t.beginStroke=function(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);tt=[e,r],Q=new at(t)},t.box=function(){return[...Ft.keys()]},t.circle=function(t,e,r,i=!1){const n=new at("curve"),o=Math.PI*r,s=R(0,360),a=i?()=>1+.2*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=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=ut,t.endStroke=function(t,e){if(!Q)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");Q.endPlot(t,e),Q.draw(tt[0],tt[1],1),Q=!1},t.field=it,t.fill=xe,t.fillBleed=ye,t.fillTexture=ve,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.");$(),Kt(t,e,r),Jt(B(i),!1)},t.hatch=fe,t.hatchArray=ge,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=ae,t.listFields=function(){return $(),Array.from(et.keys())},t.load=s,t.move=function(t,e,r){if(!Q)throw new Error("move() called without beginStroke(). Call beginStroke() first.");Q.addSegment(t,e,r)},t.noClip=function(){h.stroke.clipWindow=null},t.noField=function(){$(),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.noiseSeed=t=>{w=y(v(t))},t.pick=Ht,t.polygon=function(t){new st(t).show()},t.preload=async function(){await he.load()},t.rect=function(t,e,r,i,n="corner"){"center"===n&&(t-=r/2,e-=i/2),ct(0),ht(t,e),ht(t+r,e),ht(t+r,e+i),ht(t,e+i),ut(!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=et.get(h.field.current);e.field=e.gen(t,rt())},t.scaleBrushes=function(t){for(const{param:e}of Ft.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)},t.seed=t=>{b=v(t)},t.set=Zt,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].");ft(t,e).draw()},t.stroke=jt,t.strokeWeight=Ut,t.vertex=ht,t.wRand=P,t.wiggle=function(t=1){it("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={});+//# sourceMappingURL=p5.brush.js.mapdiff --git a/dist/p5.brush.js.map b/dist/p5.brush.js.mapnew file mode 100644index 0000000..b52c61e--- /dev/null+++ b/dist/p5.brush.js.map@@ -0,0 +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/core/gl/utils.js","../src/stroke/gl_draw.js","../src/stroke/stroke.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 + 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 = 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 * 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: 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","// =============================================================================\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// 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(-10, 10);\n dd[i].y += r * dist * rr(-10, 10);\n dd[i + 1].x += r * dist * rr(-10, 10);\n dd[i + 1].y += r * dist * rr(-10, 10);\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 } 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: 60,\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) || 60;\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, 100, 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 Matrix.a(), Matrix.b(),\n Matrix.c(), Matrix.d(),\n Matrix.x() + Cwidth / 2,\n 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, seed, noiseSeed } 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\";\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\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\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","createProgram","frag","src","VERTEX_SHADER","FRAGMENT_SHADER","shaderSource","compileShader","attachShader","linkProgram","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","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","T","tip","tips","param","colors","buffers","pick","brushName","g","arguments","strokeWeight","initializeDrawingState","plot","gaussians","angleScale","isPlot","cp","noiseoffset","dirRad","vertSrc","fragSrc","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","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","call","saved","brushPop","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,MAAM,EAGjC,IAAIW,GAAW,EACXT,GAAe,EAKZ,MAAMY,EAAgB,KACtBH,GAAUX,GAAM,EAOVe,EAAQ,CAAA,EAmBRC,EAAa,KACnBlB,EAASc,SACZE,IACAD,EAAIb,OACN,EAaWa,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,GACzBiC,KAAKL,OAAOM,QACZD,KAAKL,OAAOO,UAAUF,KAAKL,OAAOQ,SAClCH,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KC,IAAIlP,EAAM8M,MAAMqC,SAC1Cqc,EAAa1e,MAAQ0e,EAAa1a,IAAI9L,EAAGyL,KAC3C,iBMjFO,SAAsBV,GAC3B,IAAK,MAAMgM,MAAEA,KAAW9M,GAAKkT,SACvBpG,IACFA,EAAM/B,QAAUjK,EAChBgM,EAAMlB,SAAW9K,EACjBgM,EAAMoC,SAAWpO,EAGvB,SPhJqBjL,IACnB4C,EAAMzB,EAAUnB,EAAE,oBE6Nb,SAAgB2mB,EAAepb,EAAa,IACjD,IAAKob,GAAiBA,EAAcxkB,OAAS,EAC3C,MAAM,IAAIxH,MACR,+EAGIoV,GAAc4W,EAAepb,GACnCgC,MACJ,+DD8CO,SAAgBpJ,EAAI,GACzB6D,GAAM,QACN9M,EAAM8M,MAAMsC,OAASnG,CACvB","x_google_ignoreList":[1,2]}\ No newline at end of filediff --git a/example/index.html b/example/index.htmlindex 20cb0b3..d735ecd 100644--- a/example/index.html+++ b/example/index.html@@ -1,9 +1,9 @@-<!DOCTYPE html>+<!doctype html><html><head><title>p5.brush.js Example</title>- <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.min.js"></script>- <script src="https://cdn.jsdelivr.net/npm/p5.brush"></script>+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.min.js"></script>+ <script src="../dist/p5.brush.js"></script><link rel="stylesheet" href="./style.css" /></head><body>diff --git a/example/sketch.js b/example/sketch.jsindex 84e11e5..b67192b 100644--- a/example/sketch.js+++ b/example/sketch.js@@ -1,155 +1,80 @@//////////////////////////////////////////////////-// CANVAS SIZE-// Good function to create canvas and resize functions-const C = {- loaded: false,- prop() {return this.height/this.width},- isLandscape() {return window.innerHeight <= window.innerWidth * this.prop()},- resize () {- if (this.isLandscape()) {- document.getElementById(this.css).style.height = "100%";- document.getElementById(this.css).style.removeProperty('width');- } else {- document.getElementById(this.css).style.removeProperty('height');- document.getElementById(this.css).style.width = "100%";- }- },- setSize(w,h,p,css) {- this.width = w, this.height = h, this.pD = p, this.css = css;- },- createCanvas() {- this.main = createCanvas(this.width,this.height,WEBGL), pixelDensity(this.pD), this.main.id(this.css), this.resize();- }-};-// SET CANVAS SIZE: width, height, pixelDensity, html_id for the canvas-// Here I'm working with mm units, so I want a big pixelDensity for high-res.-C.setSize(250,250,8,'mainCanvas')--function windowResized () {- C.resize();+function adjustCanvas(id) {+ let canvas = document.getElementById(id);+ canvas.style.maxWidth = "100vw";+ canvas.style.maxHeight = "100vh";+ canvas.style.width = "auto";+ canvas.style.height = "auto";+ canvas.style.objectFit = "contain";}-// YOU CAN CREATE YOU OWN BRUSHES-brush.add("watercolor", {- type: "image", // this is the TIP TYPE: choose standard / spray / marker / custom / image- weight: 10, // Base weight of the brush tip- vibration: 2, // Vibration of the lines, spread- definition: 0.5, // Between 0 and 1- quality: 8, // + quality = more continuous line- opacity: 20, // Base opacity of the brush (this will be affected by pressure)- spacing: 1.5, // Spacing between the points that compose the brush stroke- blend: true, // Activate / Disable realistic color mixing. By default, this is active for marker-custom-image brushes- pressure: {- type: "custom", // "standard" or "custom". Use "custom"" for custom pressure curves. Use standard for simple gauss bell curve- //curve: [0.15,0.2], // If "standard", pick a and b values for the gauss curve. a is max horizontal mvt of the bell, b changes the slope- curve: function (x) {return 1-x}, // If "custom", define the curve function with a curve equation from x = 0 to x = 1, returning values from 0 to 1- min_max: [0.5,1.2] // For both cases, define min and max pressure (reverse for inverted presure)- },- // if you select the a custom type brush, define the tip geometry here. Use 0,0 as center of tip. If not, you can remove these lines.- tip: function () {- brush.mask.rotate(45),brush.mask.rect(-1.5,-1.5,3,3),brush.mask.rect(1.5,1.5,1,1); // in this example, the tip would be two squares, rotated 45 degrees- },- // if you select the image type brush, link your image below. If not, you can remove these lines.- image: {- src: "./brush_tips/brush.jpg",- },- // For "custom" and "image" types, you can define the tip angle rotation here.- rotate: "natural", // "none" disables rotation | "natural" follows the direction of the stroke | "random"-})-//////////////////////////////////////////////////// P5 FUNCTIONS-function preload() {- // If you are going to use custom image brush tips, include this in preload!- brush.preload();-}--let palette = ["#002185", "#fcd300", "#ff2702", "#6b9404"]--let x_values = []-let y_values = []--function setup () {-- randomSeed(12323)- brush.seed(121233)- C.createCanvas()- background("#e2e7dc")- angleMode(RADIANS)-- translate(-width/2,-height/2)-- for (let i = 0; i < 6; i++) {- x_values[i] = random(width)- y_values[i] = random(width)- }--- /*- brush.field("seabed")- // STANDARD PALETTE TEST- let i = 0- for (let b of brush.box()) {- brush.set(b,random(palette),1)- brush.flowLine(30,60+i*10,195,0)- i++- }- */--- brush.noStroke()-- brush.gravity(0,height)-- brush.fill("black", 60)-- brush.bleed(0.3)- brush.beginShape(0.5)- brush.vertex(50,50)- brush.vertex(150,50)- brush.vertex(150,150)- brush.vertex(50,150)- brush.endShape(CLOSE)-- brush.reBlend()-- brush.fill("blue", 60)- brush.beginShape(0.5)- brush.vertex(100,50)- brush.vertex(200,50)- brush.vertex(200,150)- brush.vertex(100,150)- brush.endShape(CLOSE)- brush.noFill()---}--function draw() {-- /*- //background("#e2e7dc")- translate(-width/2,-height/2)- strokeWeight(2)- brush.set("HB", "black", 1)- brush.bleed(0.4)- brush.beginShape(1)- for (let i = 0; i < 6; i++) {- stroke(random(palette))- point(x_values[i],y_values[i])- brush.vertex(x_values[i],y_values[i])- }- randomSeed(12133)- brush.endShape(CLOSE)-- noLoop()+let palette = ["#002185", "#fcd300", "#ff2702", "#6b9404"];++async function setup() {+ randomSeed(1232343);+ brush.seed(1212233);+ brush.noiseSeed(121233123);+ brush.scaleBrushes(7);+ let c = createCanvas(1500, 1500, WEBGL);+ c.id("main");+ adjustCanvas("main");+ clear();++ //background("#ffffff");+ angleMode(DEGREES);++ brush.load();++ brush.wiggle(5);++ // ---- Custom tip brush definition ----+ brush.add("diamondTip", {+ type: "custom",+ weight: 0.5,+ scatter: 0.3,+ sharpness: 0.5,+ grain: 8,+ opacity: 6,+ spacing: 1,+ pressure: [1.35, 1],+ rotate: "natural",+ tip: function (_m) {+ (_m.rotate(45), _m.rect(-5, -5, 10, 10), _m.rect(0, 0, 3, 3));+ },+ });++ // ---- Image tip brush definition ----+ await brush.add("imageTip", {+ type: "image",+ weight: 50,+ scatter: 0.2,+ sharpness: 1,+ grain: 1,+ opacity: 14,+ spacing: 1.5,+ pressure: [0.95, 5, 1.35],+ rotate: "natural",+ image: { src: "brush_tips/brush.jpg" },+ });++ translate(-width / 2, -height / 2);++ // ---- Standard brushes test ----+ let i = 0;++ brush.set("imageTip", random(palette), 1);+ brush.flowLine(150, 150 + i * 50, 700, 0);++ /*+ for (let b of brush.box()) {+ brush.set(b, random(palette), 1);+ brush.flowLine(150, 150 + i * 50, 700, 0);+ i++;+ }*/}-function mouseDragged() {- loop()- frameRate(10)- x_values[0] = mouseX- y_values[0] = mouseY-}\ No newline at end of file+function draw() {}diff --git a/example/style.css b/example/style.cssindex e633f2e..ed9891c 100644--- a/example/style.css+++ b/example/style.css@@ -1,27 +1,8 @@html, body {- height: 100%;-}--body {- overflow: hidden;- padding: 0;margin: 0;+ height: 100%;display: flex;justify-content: center;align-items: center;-}--#mainCanvas {- position: absolute;- z-index: 0;- margin: auto;- top: 0;- left: 0;- bottom: 0;- right: 0;- background-color: transparent;-}--#p5_loading {- display:none;+ overflow: hidden;}\ No newline at end of filediff --git a/package copy.json b/package copy.jsonnew file mode 100644index 0000000..1213efc--- /dev/null+++ b/package copy.json@@ -0,0 +1,45 @@+{+ "name": "p5.brush",+ "version": "1.1.4",+ "description": "Unlock custom brushes, natural fill effects and intuitive hatching in p5.js",+ "main": "src/index.js",+ "module": "src/index.js",+ "browser": "dist/p5.brush.js",+ "scripts": {+ "test": "echo \"Error: no test specified\" && exit 1",+ "build": "rollup --config -w"+ },+ "type": "module",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/acamposuribe/p5.brush.git"+ },+ "keywords": [+ "brush",+ "p5",+ "p5js",+ "brushes",+ "watercolor",+ "flowfield",+ "p5-library"+ ],+ "author": "Alejandro Campos Uribe",+ "license": "MIT",+ "bugs": {+ "url": "https://github.com/acamposuribe/p5.brush/issues"+ },+ "homepage": "https://p5-brush.cargo.site/",+ "devDependencies": {+ "@rollup/plugin-node-resolve": "^15.2.3",+ "@rollup/plugin-terser": "^0.4.4",+ "rollup": "^4.9.4",+ "rollup-plugin-cleanup": "^3.2.1",+ "rollup-plugin-glslify": "^1.3.1"+ },+ "peerDependencies": {+ "p5": "^1.11.0"+ },+ "dependencies": {+ "esm-seedrandom": "^3.0.5"+ }+}diff --git a/package.json b/package.jsonindex c0ca050..37eae31 100644--- a/package.json+++ b/package.json@@ -1,14 +1,16 @@{"name": "p5.brush",- "version": "1.1.4",+ "version": "2.0.0-alpha","description": "Unlock custom brushes, natural fill effects and intuitive hatching in p5.js","main": "src/index.js","module": "src/index.js","browser": "dist/p5.brush.js","scripts": {- "test": "echo \"Error: no test specified\" && exit 1",+ "test": "vitest run",+ "test:watch": "vitest","build": "rollup --config -w"},+ "sideEffects": "false","type": "module","repository": {"type": "git",@@ -31,14 +33,17 @@"homepage": "https://p5-brush.cargo.site/","devDependencies": {"@rollup/plugin-node-resolve": "^15.2.3",- "@rollup/plugin-terser": "^0.4.4",+ "@rollup/plugin-terser": "^1.0.0","rollup": "^4.9.4",- "rollup-plugin-cleanup": "^3.2.1"+ "rollup-plugin-cleanup": "^3.2.1",+ "rollup-plugin-glslify": "^1.3.1",+ "vitest": "^2.0.0"},"peerDependencies": {- "p5": "^1.11.0"+ "p5": "^2.1.1"},"dependencies": {- "esm-seedrandom": "^3.0.5"+ "esm-seedrandom": "^3.0.5",+ "simplex-noise": "^4.0.3"}}diff --git a/rollup.config.js b/rollup.config.jsindex 47f4b03..9219860 100644--- a/rollup.config.js+++ b/rollup.config.js@@ -1,25 +1,47 @@// rollup.config.js-import terser from '@rollup/plugin-terser';-import cleanup from 'rollup-plugin-cleanup';-import resolve from '@rollup/plugin-node-resolve';+import terser from "@rollup/plugin-terser";+import cleanup from "rollup-plugin-cleanup";+import resolve from "@rollup/plugin-node-resolve";+import glslify from "rollup-plugin-glslify";const config = {- input: 'src/index.js',- output: {- file: 'dist/p5.brush.js',- format: 'umd',- name: 'brush',+ input: "src/index.js",+ output: [+ {+ file: "dist/p5.brush.js",+ format: "umd",+ name: "brush",+ sourcemap: true,},- plugins: [- resolve({- browser: true- }),- terser(),- cleanup({- comments: "none",- })- ],- };-- export default config;\ No newline at end of file+ {+ file: "dist/p5.brush.esm.js",+ format: "esm",+ sourcemap: true,+ },+ ],+ plugins: [+ resolve({+ browser: true,+ }),+ glslify({+ include: ["**/*.frag", "**/*.vert"],+ compress: true,+ sourceMap: false,+ }),+ terser({+ module: true,+ compress: {+ keep_infinity: true,+ module: true,+ passes: 3,+ toplevel: true,+ },+ }),+ cleanup({+ comments: "none",+ }),+ ],+};++export default config;diff --git a/src/core/color.js b/src/core/color.jsnew file mode 100644index 0000000..65c83c4--- /dev/null+++ b/src/core/color.js@@ -0,0 +1,220 @@+import vertSrc from "./gl/shader.vert";+import fragSrc from "./gl/shader.frag";++// =============================================================================+// Section: Configure and Initiate+// =============================================================================+/**+ * This module handles the configuration and initialization of the drawing system.+ * It manages canvas properties, ensures the system is ready for rendering, and+ * 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++/**+ * 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.+ */+export const load = (buffer = false) => {+ // Set renderer to specificed Buffer, Instance,, or Window+ Renderer =+ _isInstanced && !buffer+ ? Instance+ : !buffer+ ? window.self.p5.instance+ : buffer;++ // Check if Rendrer is webgl and throw error if it's not++ if (Renderer.webglVersion !== "webgl2") {+ throw new Error("p5.brush requires a WEBGL canvas");+ }++ Cwidth = Renderer.width;+ Cheight = Renderer.height;++ _isReady = true;+ if (Renderer.loaded) Mix.load();+};++let _isReady = false;+let _isInstanced = false;++/**+ * Ensures the drawing system is ready before any operation.+ */+export const isCanvasReady = () => {+ if (!_isReady) load();+};++/**+ * Stores the current state of the drawing system.+ * Can be used to save and restore configurations or canvas states.+ */+export const State = {};++export const instance = (inst) => {+ _isInstanced = true;+ Instance = inst;+};+++// =============================================================================+// Section: Color Blending+// =============================================================================+/**+ * Handles color blending using WebGL shaders. Implements advanced blending+ * effects based on Kubelka-Munk theory. Relies on spectral.js for blending logic.+ */++/**+ * Ensures the Mix object is initialized and ready for blending.+ */+export const isMixReady = () => {+ if (!Renderer.loaded) {+ isCanvasReady();+ Mix.load();+ }+};++const disable = false;++/**+ * Manages blending operations with WebGL shaders.+ * @property {boolean} loaded - Indicates if shaders are loaded.+ * @property {boolean} isBlending - Indicates if blending is active.+ * @property {object} currentColor - Current color in WebGL format.+ * @property {function} load - Initializes blending resources.+ * @property {function} blend - Applies blending effects.+ */+export const Mix = {+ isBlending: false,+ isBlendingGL: false,+ isWaterColor: false,+ cachedColor: new Object(),+ cachedColorGL: new Object(),+ masks: [],++ /**+ * 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(+ Cwidth,+ Cheight,+ Renderer.WEBGL,+ );+ Renderer.loaded = true;+ Renderer.shaderProgram = Renderer.createShader(vertSrc, fragSrc);++ Density = Renderer.pixelDensity();++ this.mask = Renderer.mask;+ this.mask.pixelDensity(Density);+ this.mask.clear();+ this.mask.angleMode(Renderer.DEGREES);++ this.ctx = this.mask.drawingContext;++ this.glMask = Renderer.glMask;+ this.glMask.pixelDensity(Density);+ 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;+ }+ },++ /**+ * Applies blending effects using the current color and mask.+ * @param {Color} _color - Color to blend.+ * @param {boolean} _isLast - If this is the final blend operation.+ * @param {boolean} _isImg - If blending an image.+ * @param {boolean} _isFillLayer - If this is a special case.+ */+ blend(_color = false, _isLast = false) {+ isMixReady();++ const mask = this.isBrush ? this.glMask : this.mask;+ const no_mask = this.isBrush ? this.mask : this.glMask;++ // Perf gains are minimal but let's keep it for now+ if (disable) {+ if (_isLast && mask.isDrawn) {+ Renderer.push();+ Renderer.translate(0, 0);+ Renderer.image(mask, 0, 0, Cwidth, Cheight);+ Renderer.pop();+ mask.isDrawn = false;+ }+ return;+ }++ // Initialize blending if not already active+ if (!this.isBlending && _color) {+ this.isBlending = true;+ this.cachedColor = _color._array;+ // Force p5 to bind its internal render target for glMask,+ // so the first glDraw() writes to the correct framebuffer.+ this.glMask.clear();+ }++ 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]) {+ if (this.justChanged) {+ this.applyShader(no_mask);+ this.justChanged = false;+ }+ if (this.isBlending) {+ this.applyShader(mask);+ }+ this.cachedColor = _color._array;+ if (_isLast) this.isBlending = false;+ }+ },++ applyShader(mask) {+ let shader = Renderer.shaderProgram;+ const gl = Renderer.drawingContext;++ // Disable depth test for this compositing draw so the fullscreen rect+ // does not write Z=0 into the depth buffer — which would cause any+ // subsequent p5 geometry drawn at the same depth to fail depth testing+ // and become invisible.+ const hadDepthTest = gl.getParameter(gl.DEPTH_TEST);+ gl.disable(gl.DEPTH_TEST);++ Renderer.push();+ Renderer.translate(0, 0);++ // Use the blend shader for rendering+ Renderer.shader(shader);++ // Set shader uniforms+ shader.setUniform("u_source", Renderer._renderer);+ shader.setUniform("u_isBrush", this.isBrush);+ shader.setUniform("u_mask", mask);+ shader.setUniform("u_color", this.cachedColor);++ // Draw a rectangle covering the whole canvas to apply the shader+ Renderer.fill(0, 0, 0, 0);+ Renderer.noStroke();+ Renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);++ // Finish and clear mask+ Renderer.pop();+ Renderer.resetShader();++ // Restore depth test state+ if (hadDepthTest) gl.enable(gl.DEPTH_TEST);++ mask.clear();+ mask.isDrawn = false;+ },+};diff --git a/src/core/flowfield.js b/src/core/flowfield.jsnew file mode 100644index 0000000..45c09c3--- /dev/null+++ b/src/core/flowfield.js@@ -0,0 +1,402 @@+import { isMixReady, Cwidth, Cheight, State, Renderer } from "./color.js";+import { randInt, noise, rr, sin, cos, map } from "./utils.js";++// =============================================================================+// Section: Matrix transformations+// =============================================================================++/**+ * The `Matrix` object exposes the current 2D affine transform from p5's model matrix.+ * mat4 layout (column-major 4x4):+ * [0]=a [1]=b [4]=c [5]=d [12]=tx [13]=ty+ * where the 2D transform of a point (x,y) is: (a*x + c*y + tx, b*x + d*y + ty)+ */+export const Matrix = {+ x: () => Renderer._renderer.uModelMatrix.mat4[12],+ y: () => Renderer._renderer.uModelMatrix.mat4[13],+ a: () => Renderer._renderer.uModelMatrix.mat4[0],+ b: () => Renderer._renderer.uModelMatrix.mat4[1],+ c: () => Renderer._renderer.uModelMatrix.mat4[4],+ d: () => Renderer._renderer.uModelMatrix.mat4[5],+};+++// =============================================================================+// Section: Field Initialization+// =============================================================================++let isLoaded = false;++/**+ * Ensures the field system is initialized and ready for use.+ * If the field is not loaded, it initializes the mixing system and creates the field.+ */+export function isFieldReady() {+ if (!isLoaded) {+ isMixReady(); // Ensure the mixing system is ready+ createField(); // Initialize the field+ isLoaded = true;+ }+}++// =============================================================================+// Section: Position Class+// =============================================================================++/**+ * The Position class represents a point within a two-dimensional space, which can interact with a vector field.+ * It provides methods to update the position based on the field's flow and to check whether the position is+ * within certain bounds (e.g., within the field or canvas).+ */+export class Position {+ /**+ * Constructs a new Position instance.+ * @param {number} x - The initial x-coordinate.+ * @param {number} y - The initial y-coordinate.+ */+ constructor(x, y) {+ isFieldReady();+ this.update(x, y);+ this.plotted = 0; // Tracks the total distance plotted+ }++ /**+ * Updates the position's coordinates and calculates its offsets and indices within the flow field.+ * @param {number} x - The new x-coordinate.+ * @param {number} y - The new y-coordinate.+ */+ update(x, y) {+ this.x = x;+ this.y = y;+ this.colIdx = Position.getColIndex(x);+ this.rowIdx = Position.getRowIndex(y);+ }++ /**+ * Resets the 'plotted' property to 0.+ */+ reset() {+ this.plotted = 0;+ }++ /**+ * Checks if the position is within the active flow field's bounds.+ * @returns {boolean} - True if the position is within the flow field, false otherwise.+ */+ isIn() {+ return State.field.isActive+ ? Position.isIn(this.colIdx, this.rowIdx)+ : this.isInCanvas(this.x, this.y);+ }++ /**+ * Checks if the position is within the canvas bounds (with a margin).+ * @returns {boolean} - True if the position is within bounds, false otherwise.+ */+ isInCanvas() {+ const margin = 0.3;+ const w = Cwidth;+ const h = Cheight;+ const x = this.x + Matrix.x();+ const y = this.y + Matrix.y();+ return (+ x >= -margin * w &&+ x <= (1 + margin) * w &&+ y >= -margin * h &&+ y <= (1 + margin) * h+ );+ }++ /**+ * 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.+ */+ angle() {+ return this.isIn() && State.field.isActive+ ? flow_field()[this.colIdx][this.rowIdx] * State.field.wiggle+ : 0;+ }++ /**+ * Moves the position along the flow field by a certain length.+ * @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(_dir, _length, _step_length);+ }++ /**+ * Plots a point to another position within the flow field, following a Plot object+ * @param {Position} _plot - The Plot path object.+ * @param {number} _length - The length to move towards the target position.+ * @param {number} _step_length - The length of each step.+ * @param {number} _scale - The scaling factor for the plotting path.+ */+ plotTo(_plot, _length, _step_length, _scale = 1) {+ this.movePos(_plot, _length, _step_length, _scale);+ }++ movePos(_dirPlot, _length, _step, _scale = false) {+ const scaleFactor = _scale || 1;+ if (!this.isIn()) {+ this.plotted += _step / scaleFactor;+ return;+ }+ for (let i = 0; i < _length / _step; i++) {+ const angle =+ this.angle() - (_scale ? _dirPlot.angle(this.plotted) : _dirPlot);+ // Calculate new position+ this.update(this.x + _step * cos(angle), this.y + _step * sin(angle));+ this.plotted += _step / scaleFactor;+ }+ }++ // Static Methods++ /**+ * Gets the row index for a given y-coordinate.+ * @param {number} y - The y-coordinate.+ * @returns {number} - The row index.+ */+ static getRowIndex(y, d = 1) {+ const y_offset = y + Matrix.y() - top_y;+ return Math.round(y_offset / resolution / d);+ }++ /**+ * Gets the column index for a given x-coordinate.+ * @param {number} x - The x-coordinate.+ * @returns {number} - The column index.+ */+ static getColIndex(x, d = 1) {+ const x_offset = x + Matrix.x() - left_x;+ return Math.round(x_offset / resolution / d);+ }++ /**+ * Checks if a column and row index are within the flow field bounds.+ * @param {number} col - The column index.+ * @param {number} row - The row index.+ * @returns {boolean} - True if the indices are within bounds, false otherwise.+ */+ static isIn(col, row) {+ return col >= 0 && row >= 0 && col < num_columns && row < num_rows;+ }+}++// =============================================================================+// Section: VectorField+// =============================================================================++/**+ * Represents the state of the vector field.+ * @property {boolean} isActive - Indicates if the vector field is active.+ * @property {string|null} current - The name of the currently active vector field.+ */+State.field = {+ isActive: false,+ current: null,+ wiggle: 1,+};++// Internal variables for field configuration+let list = new Map();+let resolution, left_x, top_y, num_columns, num_rows;++/**+ * Initializes the field grid and sets up the vector field's structure based on the renderer's dimensions.+ */+function createField() {+ resolution = Cwidth * 0.01; // Determine the resolution of the field grid+ left_x = -0.5 * Cwidth; // Left boundary of the field+ top_y = -0.5 * Cheight; // Top boundary of the field+ num_columns = Math.round((2 * Cwidth) / resolution); // Number of columns in the grid+ num_rows = Math.round((2 * Cheight) / resolution); // Number of columns in the grid+ addStandard(); // Add default vector field+}++/**+ * Retrieves the field values for the current vector field.+ * @returns {Float32Array[]} The current vector field grid.+ */+function flow_field() {+ return list.get(State.field.current).field;+}++/**+ * Regenerates the current vector field using its associated generator function.+ * @param {number} [t=0] - An optional time parameter that can affect field generation.+ */+export function refreshField(t = 0) {+ if (!State.field.isActive || !State.field.current) {+ throw new Error(+ "No field is currently active. Call brush.field('name') to activate one before refreshing.",+ );+ }+ const currentField = list.get(State.field.current);+ currentField.field = currentField.gen(t, genField());+}++/**+ * Generates an empty field array.+ * Reuses existing arrays to reduce memory allocation overhead.+ * @returns {Float32Array[]} Empty vector field grid.+ */+function genField() {+ return new Array(num_columns)+ .fill(null)+ .map(() => new Float32Array(num_rows));+}++/**+ * Activates a specific vector field by name, ensuring it's ready for use.+ * @param {string} a - The name of the vector field to activate.+ */+export function field(a) {+ if (!State.field.wiggle) {+ State.field.wiggle = 1;+ } // Set default wiggle value+ isFieldReady();+ if (!list.has(a)) {+ throw new Error(+ `Field "${a}" does not exist. Available fields: ${Array.from(list.keys()).join(", ")}.`,+ );+ }+ State.field.isActive = true;+ State.field.current = a;+ const entry = list.get(a);+ if (!entry.field) entry.field = entry.gen(0, genField());+}++/**+ * Deactivates the current vector field.+ */+export function noField() {+ isFieldReady();+ State.field.isActive = false;+}++/**+ * 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.+ */+export function addField(name, funct) {+ list.set(name, { gen: funct, field: null });+}++/**+ * Retrieves a list of all available vector field names.+ * @returns {string[]} An array of all the field names.+ */+export function listFields() {+ isFieldReady();+ return Array.from(list.keys());+}++export function wiggle(a = 1) {+ field("hand");+ State.field.wiggle = a;+}++/**+ * Fills every cell of a field grid using a callback (c, r) => angle.+ */+function fillField(field, fn) {+ for (let c = 0; c < num_columns; c++)+ for (let r = 0; r < num_rows; r++) field[c][r] = fn(c, r);+ return field;+}++/**+ * Adds standard predefined vector fields to the list with unique behaviors.+ */+function addStandard() {+ // Organic noise — basis for brush.wiggle()+ addField("hand", (t, field) => {+ const bs = rr(0.2, 0.8),+ ba = randInt(5, 10);+ return fillField(field, (c, r) => {+ const angle = 0.5 * ba * sin(bs * r * c + randInt(15, 25));+ return 0.2 * angle * cos(t) + noise(c, r) * ba * 0.7;+ });+ });+ // Smooth large-scale noise curves+ addField("curved", (t, field) => {+ let ar = randInt(-10, 10);+ if (randInt(0, 100) % 2 == 0) ar *= -1;+ return fillField(+ field,+ (c, r) =>+ 3 * map(noise(c * 0.02 + t * 0.03, r * 0.02 + t * 0.03), 0, 1, -ar, ar),+ );+ });+ // Sharp alternating angles per cell — herringbone / wicker look+ addField("zigzag", (t, field) => {+ let ar = randInt(-30, -15) + Math.abs(44 * sin(t));+ if (randInt(0, 100) % 2 == 0) ar *= -1;+ let dif = ar,+ angle = 0;+ for (let c = 0; c < num_columns; c++) {+ for (let r = 0; r < num_rows; r++) {+ field[c][r] = angle;+ angle += dif;+ dif *= -1;+ }+ angle += dif;+ dif *= -1;+ }+ return field;+ });+ // Sinusoidal wave bands+ addField("waves", (t, field) => {+ const sr = randInt(10, 15) + 5 * sin(t),+ cr = randInt(3, 6) + 3 * cos(t),+ ba = randInt(20, 35);+ return fillField(+ field,+ (c, r) => sin(sr * c) * ba * cos(r * cr) + randInt(-3, 3),+ );+ });+ // Dense oscillation from row×col product+ addField("seabed", (t, field) => {+ const bs = rr(0.4, 0.8),+ ba = randInt(18, 26);+ return fillField(+ field,+ (c, r) => 1.1 * ba * sin(bs * r * c + randInt(15, 20)) * cos(t),+ );+ });+ // Radial vortex — angles spiral around the field centre+ addField("spiral", (_t, field) => {+ const n = randInt(5, 10);+ const dir = randInt(0, 2) * 2 - 1;+ const offset = randInt(65, 80); // <90 = inward spiral+ const attractors = Array.from({ length: n }, () => ({+ x: rr(0.1, 0.9) * num_columns,+ y: rr(0.1, 0.9) * num_rows,+ }));+ return fillField(field, (c, r) => {+ let wx = 0,+ wy = 0;+ for (const att of attractors) {+ const dx = c - att.x,+ dy = r - att.y;+ const w = 1 / (dx * dx + dy * dy + 1);+ const a = Math.atan2(dy, dx) * (180 / Math.PI);+ const angle = (dir * (a + offset) * Math.PI) / 180;+ wx += w * Math.cos(angle);+ wy += w * Math.sin(angle);+ }+ return Math.atan2(wy, wx) * (180 / Math.PI);+ });+ });+ // Column-banded stripes — parallel rake marks+ addField("columns", (_t, field) => {+ const freq = randInt(3, 8),+ amp = randInt(25, 45);+ return fillField(field, (c, _r) => sin(c * freq) * amp);+ });+}diff --git a/src/core/gl/shader.frag b/src/core/gl/shader.fragnew file mode 100644index 0000000..eedd28d--- /dev/null+++ b/src/core/gl/shader.frag@@ -0,0 +1,252 @@+#version 300 es++precision highp float;++uniform bool u_isBrush;+uniform sampler2D u_source;+uniform sampler2D u_mask;+uniform vec3 u_color;++in vec2 p;++out vec4 outColor;++// SPECTRAL STARTS HERE++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);+}++// SPECTRAL ENDS HERE++// Define constants in more compact form+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) {+ // Calculate UV coordinates+ vec2 uv = 0.5 * p + 0.5;+ 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);++ if (maskColor.a == 0.0) {+ outColor = source;+ return;+ }++ // Set up pigment color+ 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));+ }++ // Determine blend intensity — clamp to [0,1] to prevent NaN in spectral math+ float mixIntensity = min(maskColor.a, 1.0);++ // Apply edge detection for better blending+ if (!u_isBrush) {+ vec2 texelSize = 1.0 / vec2(textureSize(u_mask, 0));+ float scaledAlpha = maskColor.a * 15.0;++ // Calculate edge factor from 9 samples+ 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);+ }++ // Transparent background pixels are treated as white paper+ vec3 bgColor = mix(vec3(1.0), source.rgb, source.a);++ // Perform the spectral color mixing+ outColor = vec4(spectral_mix(bgColor, pigment.rgb, mixIntensity), 1.0);+}\ No newline at end of filediff --git a/src/core/gl/shader.vert b/src/core/gl/shader.vertnew file mode 100644index 0000000..e93aa3c--- /dev/null+++ b/src/core/gl/shader.vert@@ -0,0 +1,7 @@+#version 300 es+out vec2 p;+void main() {+ vec3 v = vec3(-1);+ v[gl_VertexID] = 3.;+ gl_Position = vec4(p=v.xy, 0, 1);+}\ No newline at end of filediff --git a/src/core/gl/utils.js b/src/core/gl/utils.jsnew file mode 100644index 0000000..530b3de--- /dev/null+++ b/src/core/gl/utils.js@@ -0,0 +1,21 @@+/**+ * Compiles a shader program from the given vertex and fragment sources.+ * @param {WebGL2RenderingContext} gl - The WebGL2 context.+ * @param {string} vert - Vertex shader source.+ * @param {string} frag - Fragment shader source.+ * @returns {WebGLProgram} The compiled and linked program.+ */+export const createProgram = (gl, vert, frag) => {+ const p = gl.createProgram();+ for (let [t, src] of [+ [gl.VERTEX_SHADER, vert],+ [gl.FRAGMENT_SHADER, frag],+ ]) {+ const s = gl.createShader(t);+ gl.shaderSource(s, src);+ gl.compileShader(s);+ gl.attachShader(p, s);+ }+ gl.linkProgram(p);+ return p;+};\ No newline at end of filediff --git a/src/core/mask.js b/src/core/mask.jsnew file mode 100644index 0000000..8ed0cdc--- /dev/null+++ b/src/core/mask.js@@ -0,0 +1,31 @@+import { Mix } from "./color.js";++// =============================================================================+// Section: Draw shapes to Mask Buffers+// =============================================================================++/**+ * Draws a polygon to the mask using the provided vertices.+ * @param {Array<{x: number, y: number}>} vertices - Array of vertex coordinates.+ */+export function drawPolygon(vertices) {+ Mix.ctx.beginPath();+ vertices.forEach((v, i) => {+ if (i === 0) Mix.ctx.moveTo(v.x, v.y);+ else Mix.ctx.lineTo(v.x, v.y);+ });+ Mix.ctx.closePath();+}++/**+ * Draws a circle to the mask.+ * @param {number} x - X-coordinate of the circle's center.+ * @param {number} y - Y-coordinate of the circle's center.+ * @param {number} d - Diameter of the circle.+ */+export function circle(x, y, d) {+ const PI2 = Math.PI * 2;+ const radius = d / 2;+ Mix.ctx.moveTo(x + radius, y);+ Mix.ctx.arc(x, y, radius, 0, PI2);+}diff --git a/src/core/plot.js b/src/core/plot.jsnew file mode 100644index 0000000..62934e8--- /dev/null+++ b/src/core/plot.js@@ -0,0 +1,168 @@+import { State, Cwidth, Cheight } from "./color.js";+import { toDegrees, map, rr } from "./utils.js";+import { Position, isFieldReady } from "./flowfield.js";+import { Polygon } from "./polygon.js";++// =============================================================================+// Section: Plot Class+// =============================================================================++/**+ * The Plot class represents a collection of segments that define shapes or paths.+ * It supports operations like adding segments, calculating angles and pressures,+ * and generating polygons based on the plot's structure.+ */+export class Plot {+ /**+ * Creates a new Plot.+ * @param {string} _type - The type of plot, "curve" or "segments".+ */+ constructor(_type) {+ this.segments = [];+ this.angles = [];+ this.pres = [];+ this.type = _type;+ this.dir = 0;+ this.calcIndex(0);+ this.pol = false;+ }++ /**+ * Adds a segment to the plot with specified angle, length, and pressure.+ * @param {number} _a - The angle of the segment.+ * @param {number} _length - The length of the segment.+ * @param {number} _pres - The pressure of the segment.+ * @param {boolean} _degrees - Whether the angle is in degrees.+ */+ addSegment(_a = 0, _length = 0, _pres = 1, _degrees = false) {+ if (this.angles.length > 0) this.angles.pop(); // Remove the last angle+ _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a); // Normalize angle+ this.angles.push(_a, _a); // Push angle twice for continuity+ this.pres.push(_pres);+ this.segments.push(_length);+ this.length = this.segments.reduce((sum, len) => sum + len, 0); // Update total length+ }++ /**+ * Finalizes the plot by setting the last angle and pressure.+ * @param {number} _a - The final angle.+ * @param {number} _pres - The final pressure.+ * @param {boolean} _degrees - Whether the angle is in degrees.+ */+ endPlot(_a = 0, _pres = 1, _degrees = false) {+ _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a);+ this.angles[this.angles.length - 1] = _a; // Update the last angle+ this.pres.push(_pres);+ }++ /**+ * Rotates the entire plot by a given angle.+ * @param {number} _a - The angle to rotate the plot.+ */+ rotate(_a) {+ this.dir = toDegrees(_a);+ }++ /**+ * Calculates the pressure at a given distance along the plot.+ * @param {number} _d - The distance along the plot.+ * @returns {number} - The interpolated pressure.+ */+ pressure(_d) {+ // If the distance exceeds the plot length, return the last pressure+ if (_d > this.length) return this.pres[this.pres.length - 1];+ // Otherwise, calculate the pressure using the curving function+ return this.curving(this.pres, _d);+ }++ /**+ * Calculates the angle at a given distance along the plot.+ * @param {number} _d - The distance along the plot.+ * @returns {number} - The calculated angle.+ */+ angle(_d) {+ // If the distance exceeds the plot length, return the last angle+ if (_d > this.length) return this.angles[this.angles.length - 1];+ // Calculate the index for the given distance+ this.calcIndex(_d);+ // Return the angle, adjusted for the plot type and direction+ return this.type === "curve"+ ? this.curving(this.angles, _d) + this.dir+ : this.angles[this.index] + this.dir;+ }++ /**+ * Interpolates values between segments for smooth transitions.+ * @param {Array<number>} array - The array to interpolate within.+ * @param {number} _d - The distance along the plot.+ * @returns {number} - The interpolated value.+ */+ curving(array, _d) {+ let map0 = array[this.index];+ let map1 = array[this.index + 1] ?? map0;+ if (Math.abs(map1 - map0) > 180) {+ if (map1 > map0) map1 = -(360 - map1);+ else map0 = -(360 - map0);+ }+ return map(_d - this.suma, 0, this.segments[this.index], map0, map1, true);+ }++ /**+ * Calculates the current index of the plot based on the distance.+ * @param {number} _d - The distance along the plot.+ */+ calcIndex(_d) {+ this.index = -1;+ this.suma = 0;+ let d = 0;+ while (d <= _d) {+ this.suma = d;+ d += this.segments[this.index + 1];+ this.index++;+ }+ return this.index;+ }++ /**+ * Generates a polygon based on the plot.+ * @param {number} _x - The x-coordinate for the starting point.+ * @param {number} _y - The y-coordinate for the starting point.+ * @param {number} _scale - The scale factor for the polygon.+ * @param {number} _side - The side factor for the polygon.+ * @returns {Polygon} - The generated polygon.+ */+ genPol(_x, _y, _scale = 1, _side) {+ isFieldReady(); // Ensure that the drawing environment is prepared+ const step = 0.5;+ const vertices = [];+ const numSteps = Math.round(this.length / step);+ const pos = new Position(_x + Cwidth / 2, _y + Cheight / 2);+ let pside = 0;+ let prevIdx = 0;++ for (let i = 0; i < numSteps; i++) {+ pos.plotTo(this, step, step);+ const idx = this.calcIndex(pos.plotted);+ pside += step;+ const maxSize = Math.max(this.segments[idx] * _side * rr(0.7, 1.3), 10);+ if ((pside >= maxSize || idx >= prevIdx) && pos.x) {+ vertices.push([pos.x - Cwidth / 2, pos.y - Cheight / 2]);+ pside = 0;+ if (idx >= prevIdx) prevIdx++;+ }+ }+ return new Polygon(vertices);+ }++ /**+ * Displays the plot with optional stroke, hatch, and fill effects.+ * @param {number} x - The x-coordinate.+ * @param {number} y - The y-coordinate.+ * @param {number} scale - The scale factor.+ */+ show(x, y, scale = 1) {+ if (State.stroke) this.draw(x, y, scale);+ if (State.hatch) this.hatch(x, y, scale);+ if (State.fill) this.fill(x, y, scale);+ }+}diff --git a/src/core/polygon.js b/src/core/polygon.jsnew file mode 100644index 0000000..d138608--- /dev/null+++ b/src/core/polygon.js@@ -0,0 +1,58 @@+import { State } from "./color.js";+import { intersectLines } from "./utils.js";++// =============================================================================+// Section: Polygon Class+// =============================================================================++/**+ * Represents a polygon with a set of vertices and provides methods for+ * intersection, drawing, filling, and hatching.+ */+export class Polygon {+ /**+ * Constructs the Polygon object from an array of points.+ * @param {Array} pointsArray - An array of points, where each point is an array of two numbers [x, y].+ * @param {boolean} [useRawVertices=false] - If true, uses the raw array as vertices.+ */+ constructor(pointsArray, useRawVertices = false) {+ this.a = pointsArray;+ this.vertices = useRawVertices+ ? pointsArray+ : pointsArray.map(([x, y]) => ({ x, y }));+ this.sides = this.vertices.map((v, i, arr) => [+ v,+ arr[(i + 1) % arr.length],+ ]);+ this._intersectionCache = {}; // Cache for intersection results+ }++ /**+ * Intersects a given line with the polygon, returning all intersection points.+ * @param {Object} line - The line to intersect with the polygon, having two properties 'point1' and 'point2'.+ * @returns {Array} An array of intersection points (each with 'x' and 'y' properties) or an empty array if no intersections.+ */+ intersect(line) {+ // Check if the result has been cached+ const cacheKey = `${line.point1.x},${line.point1.y}-${line.point2.x},${line.point2.y}`;+ if (this._intersectionCache[cacheKey]) {+ return this._intersectionCache[cacheKey];+ }+ const points = [];+ for (const [start, end] of this.sides) {+ const intersection = intersectLines(line.point1, line.point2, start, end);+ if (intersection) points.push(intersection);+ }+ this._intersectionCache[cacheKey] = points; // Cache the result+ return points;+ }++ /**+ * Displays the polygon with optional stroke, hatch, and fill effects.+ */+ show() {+ if (State.stroke) this.draw();+ if (State.hatch) this.hatch();+ if (State.fill) this.fill();+ }+}diff --git a/src/core/primitives.js b/src/core/primitives.jsnew file mode 100644index 0000000..6a0e625--- /dev/null+++ b/src/core/primitives.js@@ -0,0 +1,380 @@+import {+ rr,+ randInt,+ sin,+ cos,+ toDegrees,+ constrain,+ dist,+ calcAngle,+ intersectLines,+} from "./utils.js";+import { Polygon } from "./polygon.js";+import { Plot } from "./plot.js";++// =============================================================================+// Section: Primitives and Geommetry+// =============================================================================++/**+ * Creates a Polygon from an array of points and calls its show() method.+ * @param {Array<Array<number>>} pointsArray - Array of points [x, y, pressure]+ */+export function polygon(pointsArray) {+ // Create a new Polygon instance+ const polygon = new Polygon(pointsArray);+ polygon.show();+}++/**+ * Draws a rectangle on the canvas using path functions.+ * @param {number} x - X-coordinate.+ * @param {number} y - Y-coordinate.+ * @param {number} w - Width.+ * @param {number} h - Height.+ * @param {boolean} [mode="corner"] - "corner" (default) or "center".+ */+export function rect(x, y, w, h, mode = "corner") {+ if (mode === "center") {+ x -= w / 2;+ y -= h / 2;+ }+ beginShape(0);+ vertex(x, y);+ vertex(x + w, y);+ vertex(x + w, y + h);+ vertex(x, y + h);+ endShape(true);+}++/**+ * Draws a circle on the canvas.+ * @param {number} x - Center x.+ * @param {number} y - Center y.+ * @param {number} radius - Circle radius.+ * @param {boolean} [r=false] - Randomizes segment lengths if true.+ */+export function circle(x, y, radius, r = false) {+ const p = new Plot("curve");+ const arcLength = Math.PI * radius;+ const angleOffset = rr(0, 360);+ const randomFactor = r ? () => 1 + 0.2 * rr() : () => 1;++ // Divide circle into 4 segments+ for (let i = 0; i < 4; i++) {+ const angle = -90 * i + angleOffset;+ p.addSegment(+ angle * randomFactor(),+ (arcLength / 2) * randomFactor(),+ 1,+ true,+ );+ }++ // Optionally add a random final angle for the last segment+ if (r) {+ const randomAngle = randInt(-5, 5);+ p.addSegment(+ angleOffset,+ Math.abs(randomAngle) * (Math.PI / 180) * radius,+ 1,+ true,+ );+ p.endPlot(randomAngle + angleOffset, 1, true);+ } else {+ p.endPlot(angleOffset, 1, true);+ }++ // Draw the circle+ const offsetX = x - radius * sin(angleOffset);+ const offsetY = y - radius * cos(-angleOffset);+ p.show(offsetX, offsetY, 1);+}++/**+ * Draws an arc on the canvas.+ * @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.+ */+export function arc(x, y, radius, start, end) {+ 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;++ p.addSegment(startAngle, arcLength, 1, true);+ p.endPlot(endAngle, 1, true);++ const startX = x + radius * cos(-startAngle - 90);+ const startY = y + radius * sin(-startAngle - 90);+ p.draw(startX, startY, 1);+}++// Variables for managing paths and strokes+let _current;+let _curvature;++class SubPath {+ constructor() {+ this.isClosed = false;+ this.curvature = _curvature;+ this.vert = [];+ }+ /**+ * Adds a vertex to this subpath.+ * @param {number} x+ * @param {number} y+ * @param {number} pressure+ */+ vertex(x, y, pressure) {+ this.vert.push([x, y, pressure]);+ }+ /**+ * Renders the subpath by creating a spline from its vertices.+ */+ show() {+ let plot = _createSpline(this.vert, this.curvature, this.isClosed);+ plot.show();+ }+}++/**+ * Begins a new path with a specified curvature.+ * @param {number} [curvature=0] - Curvature from 0 to 1.+ */+export function beginShape(curvature = 0) {+ _curvature = constrain(curvature, 0, 1);+ _current = new SubPath();+}++/**+ * Adds a line segment from the current point to the given coordinates.+ * @param {number} x - X-coordinate.+ * @param {number} y - Y-coordinate.+ * @param {number} [pressure=1] - Pressure value.+ */+export function vertex(x, y, pressure = 1) {+ if (!_current) {+ throw new Error(+ "vertex() called outside of beginShape()/endShape(). Call beginShape() first.",+ );+ }+ _current.vertex(x, y, pressure);+}++/**+ * Ends the current path and renders all subpaths.+ */+export function endShape(close = false) {+ if (!_current) {+ throw new Error(+ "endShape() called without beginShape(). Call beginShape() first.",+ );+ }+ if (_current.vert.length < 2) {+ throw new Error(+ "endShape() requires at least 2 vertices. Add more with vertex().",+ );+ }+ if (close) {+ _current.vertex(..._current.vert[0]);+ _current.isClosed = true;+ }+ _current.show();+ _current = false;+}++let _strokeArray, _strokeOrigin;++/**+ * Begins a new stroke with a given type and starting position.+ * @param {string} type - Stroke type.+ * @param {number} x - Starting x.+ * @param {number} y - Starting y.+ */+export function beginStroke(type, x, y) {+ if (type !== "curve" && type !== "segments") {+ throw new Error(+ `beginStroke() type must be "curve" or "segments", got "${type}".`,+ );+ }+ _strokeOrigin = [x, y];+ _strokeArray = new Plot(type);+}++/**+ * Adds a segment to the stroke.+ * @param {number} angle - Segment angle.+ * @param {number} length - Segment length.+ * @param {number} pressure - Segment pressure.+ */+export function move(angle, length, pressure) {+ if (!_strokeArray) {+ throw new Error(+ "move() called without beginStroke(). Call beginStroke() first.",+ );+ }+ _strokeArray.addSegment(angle, length, pressure);+}++/**+ * Completes and renders the stroke.+ * @param {number} angle - End angle.+ * @param {number} pressure - End pressure.+ */+export function endStroke(angle, pressure) {+ if (!_strokeArray) {+ throw new Error(+ "endStroke() called without beginStroke(). Call beginStroke() first.",+ );+ }+ _strokeArray.endPlot(angle, pressure);+ _strokeArray.draw(_strokeOrigin[0], _strokeOrigin[1], 1);+ _strokeArray = false;+}++/**+ * Creates and draws a spline curve from an array of points.+ * @param {Array<Array<number>>} array_points - Array of points [x, y, pressure].+ * @param {number} [curvature=0.5] - Curvature from 0 to 1.+ */+export function spline(_array_points, _curvature = 0.5) {+ if (!_array_points || _array_points.length < 2) {+ throw new Error(+ "spline() requires at least 2 points. Each point should be [x, y, pressure].",+ );+ }+ let p = _createSpline(_array_points, _curvature);+ p.draw();+}++/**+ * Creates a new Plot object representing a spline curve.+ *+ * For curved segments (curvature > 0) with at least 3 points available,+ * the function either treats segments as straight (if their angles match)+ * or calculates control points to compute a circular arc.+ *+ * If no curvature is specified, a simple straight segment is used.+ *+ * @param {Array<Array<number>>} points - Array of points [x, y, pressure].+ * @param {number} [curvature=0.5] - Curvature value between 0 and 1.+ * @param {boolean} [close=false] - Whether to close the spline.+ * @returns {Plot} - The generated Plot object.+ */+function _createSpline(points, curvature = 0.5, close = false) {+ const plotType = curvature === 0 ? "segments" : "curve";+ const p = new Plot(plotType);+ const PI2 = Math.PI * 2;++ // If closing the spline, add the second point to the end+ if (close && curvature !== 0) {+ points.push(points[1]);+ }++ if (points && points.length > 0) {+ let done = 0; // Tracks excess length from previous segment+ let pep, tep, pep2; // Variables used for initial calibration++ for (let i = 0; i < points.length - 1; i++) {+ // For curved segments (if curvature > 0 and there is at least 3 points ahead)+ if (curvature > 0 && i < points.length - 2) {+ const p1 = points[i];+ const p2 = points[i + 1];+ const p3 = points[i + 2];++ const d1 = dist(p1[0], p1[1], p2[0], p2[1]);+ const d2 = dist(p2[0], p2[1], p3[0], p3[1]);+ const a1 = calcAngle(p1[0], p1[1], p2[0], p2[1]);+ const a2 = calcAngle(p2[0], p2[1], p3[0], p3[1]);++ // Compute the adjustment length based on curvature+ const curvAdjust = curvature * Math.min(d1, d2, 0.5 * Math.min(d1, d2));+ const dmax = Math.max(d1, d2);+ const s1 = d1 - curvAdjust;+ const s2 = d2 - curvAdjust;++ if (Math.floor(a1) === Math.floor(a2)) {+ // If angles are nearly the same, treat as a straight segment+ const temp = close ? (i === 0 ? 0 : d1 - done) : d1 - done;+ const temp2 = close ? (i === 0 ? 0 : d2 - pep2) : d2;++ p.addSegment(a1, temp, p1[2], true);+ if (i === points.length - 3) {+ p.addSegment(a2, temp2, p2[2], true);+ }++ done = 0;+ if (i === 0) {+ pep = d1;+ pep2 = curvAdjust;+ tep = points[1];+ done = 0;+ }+ } else {+ // For a curved segment, compute control points and arc segment details+ const point1 = {+ x: p2[0] - curvAdjust * cos(-a1),+ y: p2[1] - curvAdjust * sin(-a1),+ };+ const point2 = {+ x: point1.x + dmax * cos(-a1 + 90),+ y: point1.y + dmax * sin(-a1 + 90),+ };+ const point3 = {+ x: p2[0] + curvAdjust * cos(-a2),+ y: p2[1] + curvAdjust * sin(-a2),+ };+ const point4 = {+ x: point3.x + dmax * cos(-a2 + 90),+ y: point3.y + dmax * sin(-a2 + 90),+ };++ const intPt = intersectLines(point1, point2, point3, point4, true);+ const radius = dist(point1.x, point1.y, intPt.x, intPt.y);+ const halfDist = dist(point1.x, point1.y, point3.x, point3.y) / 2;+ const arcAngle = 2 * Math.asin(halfDist / radius) * (180 / Math.PI);+ const arcLength = (PI2 * radius * arcAngle) / 360;++ const temp = close ? (i === 0 ? 0 : s1 - done) : s1 - done;+ const temp2 =+ i === points.length - 3 ? (close ? pep - curvAdjust : s2) : 0;++ p.addSegment(a1, temp, p1[2], true);+ p.addSegment(a1, isNaN(arcLength) ? 0 : arcLength, p1[2], true);+ p.addSegment(a2, temp2, p2[2], true);++ done = curvAdjust;+ if (i === 0) {+ pep = s1;+ pep2 = curvAdjust;+ tep = [point1.x, point1.y];+ }+ }++ if (i === points.length - 3) {+ p.endPlot(a2, p2[2], true);+ }+ } else if (curvature === 0) {+ // If no curvature, add a simple straight segment+ const p1 = points[i];+ const p2 = points[i + 1];+ const d = dist(p1[0], p1[1], p2[0], p2[1]);+ const a = calcAngle(p1[0], p1[1], p2[0], p2[1]);++ p.addSegment(a, d, p2[2], true);+ if (i === points.length - 2) {+ p.endPlot(a, 1, true);+ }+ }+ }++ p.origin = close && curvature !== 0 ? tep : points[0];+ }++ return p;+}diff --git a/src/core/save.js b/src/core/save.jsnew file mode 100644index 0000000..8c80ac5--- /dev/null+++ b/src/core/save.js@@ -0,0 +1,39 @@+import { State } from "./color.js";+import { isFieldReady } from "./flowfield.js";++// =============================================================================+// SAVE / RESTORE+// =============================================================================++/**+ * Stack of saved brush states for push/pop operations.+ * A stack (not a single slot) is required because applyShader() internally+ * calls Renderer.push()/pop(), which fires our hook — a flat object would be+ * overwritten mid-draw and pop() would restore the wrong state.+ */+const _stateStack = [];++/**+ * Pushes the current brush state onto the stack.+ */+export function push() {+ isFieldReady();+ _stateStack.push({+ fill: { ...State.fill },+ stroke: { ...State.stroke },+ hatch: { ...State.hatch },+ field: { ...State.field },+ });+}++/**+ * Pops the top brush state from the stack and restores it.+ */+export function pop() {+ const saved = _stateStack.pop();+ if (!saved) return;+ State.stroke = { ...saved.stroke };+ State.field = { ...saved.field };+ State.hatch = { ...saved.hatch };+ State.fill = { ...saved.fill };+}diff --git a/src/core/utils.js b/src/core/utils.jsnew file mode 100644index 0000000..c1adced--- /dev/null+++ b/src/core/utils.js@@ -0,0 +1,303 @@+import { Renderer } from "./color.js";++// =============================================================================+// Section: Randomness & Noise+// =============================================================================++import { createNoise2D } from "simplex-noise";+import { prng_alea } from "esm-seedrandom";++/**+ * A uniform PRNG function. Returns a float in [0,1).+ * @callback RNG+ * @returns {number}+ */+/** @type {RNG} */+let rng = prng_alea(Math.random());++/**+ * Seed the random number generator.+ * @param {number|string} s – The seed value.+ * @returns {void}+ */+export const seed = (s) => {+ rng = prng_alea(s);+};++/**+ * Simplex‐noise 2D function.+ * @type {function(number, number): number}+ */+export let noise = createNoise2D(prng_alea(Math.random()));++/**+ * Seed the noise generator.+ * @param {number|string} s - The seed value.+ * @returns {void}+ */+export const noiseSeed = (s) => {+ noise = createNoise2D(prng_alea(s));+};++/**+ * Returns a random float in [min, max).+ * @param {number} [min=0]+ * @param {number} [max=1]+ * @returns {number}+ */+export const rr = (e = 0, r = 1) => e + rng() * (r - e);++/**+ * Selects a random element from an array.+ * @param {T[]} array - Input array.+ * @returns {T}+ */+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+ * @param {number} max+ * @returns {number}+ */+export const randInt = (e, r) => ~~rr(e, r);++/**+ * Gaussian (normal) random sample N(mean, stdev²).+ * @param {number} [mean=0]+ * @param {number} [stdev=1]+ * @returns {number}+ */+export const gaussian = (mean = 0, stdev = 1) => {+ const u = 1 - rng();+ const v = rng();+ const z = Math.sqrt(-2.0 * Math.log(u)) * cos(360 * v);+ return z * stdev + mean;+};++/**+ * Picks a key from an object according to weighted probabilities.+ * @param {Object<string|number, number>} weights+ * @returns {string|number}+ */+export const weightedRand = (weights) => {+ let totalWeight = 0;+ const entries = [];++ // Build cumulative weights array+ for (const key in weights) {+ totalWeight += weights[key];+ entries.push({ key, cumulative: totalWeight });+ }++ // Get a random number between 0 and totalWeight+ const rnd = rng() * totalWeight;++ // Pick the first entry where rnd is less than the cumulative weight+ for (const { key, cumulative } of entries) {+ if (rnd < cumulative) {+ return isNaN(key) ? key : parseInt(key);+ }+ }+};++// =============================================================================+// Section: Numeric Mapping & Constraints+// =============================================================================++/**+ * Maps a value from range [a,b] to [c,d], optionally clamped.+ * @param {number} value+ * @param {number} a+ * @param {number} b+ * @param {number} c+ * @param {number} d+ * @param {boolean} [withinBounds=false]+ * @returns {number}+ */+export const map = (value, a, b, c, d, withinBounds = false) => {+ let r = c + ((value - a) / (b - a)) * (d - c);+ if (!withinBounds) return r;+ if (c < d) return constrain(r, c, d);+ else return constrain(r, d, c);+};++/**+ * Constrains a number within the provided bounds.+ * @param {number} n - The number.+ * @param {number} low - Lower bound.+ * @param {number} high - Upper bound.+ * @returns {number} The constrained number.+ */+export const constrain = (n, low, high) => Math.max(Math.min(n, high), low);++// =============================================================================+// Section: Trigonometry+// =============================================================================++/**+ * Normalize an angle in degrees to [0,360).+ * @param {number} angle+ * @returns {number}+ */+const nAngle = (angle) => {+ angle = angle % 360;+ return angle < 0 ? angle + 360 : angle;+};++// number of discrete steps (360° × 4 samples per degree)+const totalDegrees = 1440;+const radiansPerIndex = (2 * Math.PI) / totalDegrees;++// lazy‐initialized lookup tables+const cLookup = new Float32Array(totalDegrees).fill(NaN);+const sLookup = new Float32Array(totalDegrees).fill(NaN);++/**+ * Cosine of an angle (degrees), via a lazy lookup table.+ * @param {number} angle+ * @returns {number}+ */+export const cos = (angle) => {+ const idx = ~~(4 * nAngle(angle));+ let v = cLookup[idx];+ if (isNaN(v)) {+ v = Math.cos(idx * radiansPerIndex);+ cLookup[idx] = v;+ }+ return v;+};++/**+ * Sine of an angle (degrees), via a lazy lookup table.+ * @param {number} angle+ * @returns {number}+ */+export const sin = (angle) => {+ const idx = ~~(4 * nAngle(angle));+ let v = sLookup[idx];+ if (isNaN(v)) {+ v = Math.sin(idx * radiansPerIndex);+ sLookup[idx] = v;+ }+ return v;+};++/**+ * Converts radians to degrees, normalized to [0,360).+ * @param {number} rad+ * @returns {number}+ */+export const toDegrees = (rad, isRad = false) => {+ // Only if Renderer.angleMode() is set to radians+ if (Renderer.angleMode() === Renderer.RADIANS || isRad) {+ let angle = ((rad * 180) / Math.PI) % 360;+ return angle < 0 ? angle + 360 : angle;+ } else {+ return rad;+ }+};++// =============================================================================+// Section: Geometry & Transforms+// =============================================================================++/**+ * Rotates point (x,y) around center (cx,cy) by angle degrees.+ * @param {number} cx+ * @param {number} cy+ * @param {number} x+ * @param {number} y+ * @param {number} angle - Degrees+ * @returns {{x:number,y:number}}+ */+export const rotate = (cx, cy, x, y, angle) => {+ let coseno = cos(angle),+ seno = sin(angle),+ nx = coseno * (x - cx) + seno * (y - cy) + cx,+ ny = coseno * (y - cy) - seno * (x - cx) + cy;+ return { x: nx, y: ny };+};++/**+ * Euclidean distance between two points.+ * @param {number} x1+ * @param {number} y1+ * @param {number} x2+ * @param {number} y2+ * @returns {number}+ */+export const dist = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1);++/**+ * Angle in degrees between two points, measured clockwise from +X.+ * @param {number} x1+ * @param {number} y1+ * @param {number} x2+ * @param {number} y2+ * @returns {number}+ */+export const calcAngle = (x1, y1, x2, y2) =>+ toDegrees(Math.atan2(-(y2 - y1), x2 - x1), true);++/**+ * Intersection of two line segments, or false if none.+ * @param {{x:number,y:number}} s1a+ * @param {{x:number,y:number}} s1b+ * @param {{x:number,y:number}} s2a+ * @param {{x:number,y:number}} s2b+ * @param {boolean} [includeSegmentExtension=false]+ * @returns {{x:number,y:number}|false}+ */+export const intersectLines = (+ s1a,+ s1b,+ s2a,+ s2b,+ includeSegmentExtension = false+) => {+ // Extract coordinates from points+ let x1 = s1a.x,+ y1 = s1a.y;+ let x2 = s1b.x,+ y2 = s1b.y;+ let x3 = s2a.x,+ y3 = s2a.y;+ let x4 = s2b.x,+ y4 = s2b.y;+ // Early return if line segments are points or if the lines are parallel+ if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) {+ return false; // Segments are points+ }+ let deltaX1 = x2 - x1,+ deltaY1 = y2 - y1;+ let deltaX2 = x4 - x3,+ deltaY2 = y4 - y3;+ let denominator = deltaY2 * deltaX1 - deltaX2 * deltaY1;+ if (denominator === 0) {+ return false; // Lines are parallel+ }+ // Calculate the intersection point+ let ua = (deltaX2 * (y1 - y3) - deltaY2 * (x1 - x3)) / denominator;+ let ub = (deltaX1 * (y1 - y3) - deltaY1 * (x1 - x3)) / denominator;+ // Check if the intersection is within the bounds of the line segments+ if (!includeSegmentExtension && (ub < 0 || ub > 1)) {+ return false;+ }+ // Calculate the intersection coordinates+ let x = x1 + ua * deltaX1;+ let y = y1 + ua * deltaY1;+ return { x: x, y: y };+};diff --git a/src/fill/fill.js b/src/fill/fill.jsnew file mode 100644index 0000000..a8e3f01--- /dev/null+++ b/src/fill/fill.js@@ -0,0 +1,534 @@+// =============================================================================+// Module: Fill+// =============================================================================+/**+ * The Fill module contains functions and classes dedicated to handling+ * the fill properties of shapes within the drawing context. It supports complex fill+ * operations with effects such as bleeding to simulate watercolor-like textures. The+ * methods provided allow for setting the fill color with opacity, controlling the+ * intensity of the bleed effect, and enabling or disabling the fill operation.+ *+ * The watercolor effect implementation is inspired by Tyler Hobbs'+ * techniques for simulating watercolor paints.+ */++import { Renderer, Mix, State, Cwidth, Cheight } from "../core/color.js";+import { drawPolygon, circle } from "../core/mask.js";+import {+ constrain,+ weightedRand,+ rr,+ map,+ randInt,+ gaussian,+ rArray,+ rotate,+} from "../core/utils.js";+import { isFieldReady, Matrix } from "../core/flowfield.js";+import { Polygon } from "../core/polygon.js";+import { Plot } from "../core/plot.js";++// =============================================================================+// Fill State and helpers+// =============================================================================++/**+ * Global fill state settings.+ */+State.fill = {+ opacity: 60,+ bleed_strength: 0.07,+ texture_strength: 0.8,+ border_strength: 0.5,+ direction: "out",+ isActive: false,+};++// Cache the current state+const FillState = () => ({ ...State.fill });+const FillSetState = (state) => {+ State.fill = { ...state };+};++// ---------------------------------------------------------------------------+// Fill Style Functions+// ---------------------------------------------------------------------------++/**+ * Sets the fill color and opacity for subsequent drawing operations.+ * @param {number|string|Color} a - Either the red component, a CSS color string, or a Color object.+ * @param {number} [b] - The green component or the opacity if using grayscale.+ * @param {number} [c] - The blue component.+ * @param {number} [d] - The opacity.+ */+export function fill(a, b, c, d) {+ State.fill.opacity = (arguments.length < 4 ? b : d) || 60;+ State.fill.color =+ arguments.length < 3 ? Renderer.color(a) : Renderer.color(a, b, c);+ State.fill.isActive = true;+}++/**+ * Sets the bleed (watercolor) intensity and direction.+ * @param {number} _i - The bleed intensity (clamped to [0,1]).+ * @param {string} [_direction="out"] - The bleeding direction.+ */+export function fillBleed(_i, _direction = "out") {+ State.fill.bleed_strength = constrain(_i, 0, 1);+ State.fill.direction = _direction;+}++/**+ * Sets the texture and border strengths for the fill.+ * @param {number} [_texture=0.4] - The texture strength (clamped to [0,1]).+ * @param {number} [_border=0.4] - The border strength (clamped to [0,1]).+ */+export function fillTexture(_texture = 0.4, _border = 0.4) {+ State.fill.texture_strength = constrain(_texture, 0, 1);+ State.fill.border_strength = constrain(_border, 0, 1);+}++/**+ * Disables fill for subsequent drawing operations.+ */+export function noFill() {+ State.fill.isActive = false;+}++// ---------------------------------------------------------------------------+// Fill Manager Functions+// ---------------------------------------------------------------------------++let _polygon;++// Pre-compute gaussians for reuse+const _gaussians = [[], []]; // [a, b]++// Helper for direction checking - extracted to reduce duplication+function _isLeft(a, b, c) {+ return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) > 0.01;+}++/**+ * Calculates the centroid of a polygon from its vertices.+ * @param {Object[]} pts - Array of points with {x, y}.+ * @returns {Object} The center point {x, y}.+ */+function _center(pts) {+ if (pts.length < 8) {+ // Simple average for small polygons+ return pts+ .reduce((c, p) => ({ x: c.x + p.x, y: c.y + p.y }), { x: 0, y: 0 })+ .map((v) => v / pts.length);+ }++ // Close polygon if needed+ const v = [...pts];+ if (v[0].x !== v[v.length - 1].x || v[0].y !== v[v.length - 1].y)+ v.push(v[0]);++ // Calculate using shoelace formula (more efficient implementation)+ let area = 0,+ cx = 0,+ cy = 0;+ for (let i = 0; i < v.length - 1; i++) {+ const cross = v[i].x * v[i + 1].y - v[i + 1].x * v[i].y;+ area += cross;+ cx += (v[i].x + v[i + 1].x) * cross;+ cy += (v[i].y + v[i + 1].y) * cross;+ }++ area *= 0.5;+ return area+ ? { x: cx / (6 * area), y: cy / (6 * area) }+ : { x: v[0].x, y: v[0].y };+}++/**+ * Fills a given polygon with a watercolor effect.+ * @param {Polygon} polygon - The polygon to fill.+ */+export function createFill(polygon) {+ if (!State.fill.isActive || !State.fill.color) {+ throw new Error(+ "No fill color set. Call brush.fill(color) before drawing shapes.",+ );+ }+ _polygon = polygon;+ const v = [...polygon.vertices];++ // Map vertices+ const fluid = ~~(v.length * 0.25 * weightedRand({ 1: 5, 2: 10, 3: 60 }));+ const strength = State.fill.bleed_strength;++ // Create bleed modifiers+ const modifiers = v.map(+ (_, i) => (i > fluid ? 1 : 0.3) * rr(0.85, 1.2) * strength,+ );++ // Randomize starting point+ const shift = randInt(0, v.length);+ const shifted = [...v.slice(shift), ...v.slice(0, shift)];++ // Calculate center and create FillPolygon+ const center = _center(shifted);+ new FillPoly(shifted, modifiers, center, [], true).fill(+ State.fill.color,+ map(State.fill.opacity, 0, 100, 0, 1, true),+ State.fill.texture_strength,+ );+}++// ---------------------------------------------------------------------------+// FillPolygon Class+// ---------------------------------------------------------------------------++/**+ * The FillPolygon class is used to create and manage the properties of the polygons that produces+ * the watercolor effect. It includes methods to grow (expand) the polygon and apply layers+ * of color with varying intensity and erase parts to simulate a natural watercolor bleed.+ * The implementation follows Tyler Hobbs' guide to simulating watercolor:+ * https://tylerxhobbs.com/essays/2017/a-generative-approach-to-simulating-watercolor-paints+ */+class FillPoly {+ /**+ * Constructs a FillPolygon.+ * @param {Object[]} _v - Vertices of the polygon.+ * @param {number[]} _m - Multipliers for the bleed effect at each vertex.+ * @param {Object} _center - The polygon's center {x, y}.+ * @param {boolean[]} dir - Array indicating bleed direction per vertex.+ * @param {boolean} isFirst - True for initial polygon.+ */+ constructor(v, m, center, dir = [], isFirst = false, sx, sy) {+ // Initialize properties+ this.v = v;+ this.m = m;+ this.dir = dir;+ this.midP = center;++ // Initialize size and direction for first polygon+ if (isFirst) {+ // Calculate size bounds+ let maxX = 0,+ maxY = 0;+ const rayCalc = [];++ for (let i = 0; i < v.length; i++) {+ // Store vertex distances to center for size calculation+ const dx = Math.abs(center.x - v[i].x);+ const dy = Math.abs(center.y - v[i].y);+ maxX = Math.max(maxX, dx);+ maxY = Math.max(maxY, dy);++ // Store edge info for ray calculations+ const v1 = v[i],+ v2 = v[(i + 1) % v.length];+ const side = { x: v2.x - v1.x, y: v2.y - v1.y };+ const rt = rotate(0, 0, side.x, side.y, 90);+ const mid = { x: v1.x + side.x / 2, y: v1.y + side.y / 2 };++ rayCalc.push({+ v1,+ v2,+ ray: {+ point1: mid,+ point2: { x: mid.x + rt.x, y: mid.y + rt.y },+ },+ });+ }++ // Store sizes+ this.sizeX = maxX;+ this.sizeY = maxY;++ // Calculate directions+ this.dir = Array(v.length);+ rayCalc.forEach((rc, i) => {+ let count = 0;+ for (const isect of _polygon.intersect(rc.ray)) {+ if (_isLeft(rc.v1, rc.v2, isect)) count++;+ }+ this.dir[i] = count % 2 === 0;+ });++ // Randomize center (single calculation)+ const rx = rr(-0.6, 0.6) * maxX;+ const ry = rr(-0.6, 0.6) * maxY;+ this.midP = { x: center.x + rx, y: center.y + ry };+ } else {+ this.sizeX = sx;+ this.sizeY = sy;+ }+ }++ /**+ * Trims vertices from the polygon based on a factor.+ * @param {number} [factor=1] - Factor determining amount of trimming.+ * @returns {Object} An object containing trimmed vertices, multipliers, and direction.+ */+ trim(f = 1) {+ // Fast path for common case+ if (f >= 1 || f < 0 || this.v.length <= 8) {+ return { v: [...this.v], m: [...this.m], dir: [...this.dir] };+ }++ // Trim from middle for balance+ const n = ~~((1 - f) * this.v.length);+ const s = ~~(this.v.length / 2 - n / 2);++ // Clone and splice+ const v = [...this.v],+ m = [...this.m],+ dir = [...this.dir];+ v.splice(s, n);+ m.splice(s, n);+ dir.splice(s, n);++ return { v, m, dir };+ }++ /**+ * Grows (or shrinks) the polygon vertices to simulate watercolor spread.+ * @param {number} [growthFactor=1] - Factor controlling growth.+ * @returns {FillPoly} A new FillPoly with adjusted vertices.+ */+ 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 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.+ * @param {number} intensity - Opacity intensity (mapped from 0 to 1).+ * @param {number} tex - Texture factor.+ */+ fill(color, intensity, tex) {+ // Precalculate stuff+ const numLayers = 20;+ const texture = tex * 3;+ const int = 2 * intensity * (1 + tex / 2);++ // Perform initial setup only once+ Mix.blend(color);+ Mix.justChanged = true;+ Mix.isBrush = false;++ Mix.ctx.save();+ Mix.ctx.setTransform(+ Matrix.a(), Matrix.b(),+ Matrix.c(), Matrix.d(),+ Matrix.x() + Cwidth / 2,+ Matrix.y() + Cheight / 2,+ );++ Mix.ctx.strokeStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${+ 0.005 * State.fill.border_strength+ })`;+ Mix.ctx.lineCap = "round";++ const size = Math.max(this.sizeX, this.sizeY);+ const darker = rr(0.15, 0.7);++ // Create initial polygon+ let pol = this.grow();+ let pols;++ for (let i = 0; i < numLayers; i++) {+ // Grow polygon every 4 layers+ if (i % 4 === 0) pol = pol.grow();++ // Create variant polygons+ if (i % 2 === 0) {+ pols = [+ pol.grow(1 - 0.0125 * i),+ pol.grow(0.7 - 0.0125 * i),+ pol.grow(0.4 - 0.0125 * i),+ ];+ }++ // Draw layers+ for (const p of pols) p.grow(999).grow(997).layer(i, size, int, color);+ if (i % 2 === 0)+ pol+ .grow(darker)+ .grow(999)+ .layer(i, size, int * 2, color);++ // Apply texture and blend periodically+ if (i % 5 === 0 || i === numLayers - 1) {+ if (texture !== 0) pol.erase(texture * 3, intensity);+ Mix.blend(color, true, false, true);+ }+ }++ Mix.ctx.restore();+ }++ /**+ * Draws a layer of the fill polygon with stroke and fill.+ * @param {number} i - The layer index.+ */+ layer(i, size, int, color) {+ Mix.ctx.lineWidth = map(i, 0, 24, size / 25, size / 30, true);+ Mix.ctx.fillStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${int}%)`;+ drawPolygon(this.v);+ Mix.ctx.fill();+ Mix.ctx.stroke();+ }++ /**+ * Erases parts of the polygon to create a natural watercolor texture.+ * @param {number} texture - Texture strength factor.+ * @param {number} intensity - Intensity value for size scaling.+ */+ erase(texture, intensity) {+ Mix.ctx.save();++ // Optimize by pre-calculating values+ const numCircles = ~~(rr(80, 110) * map(texture, 0, 1, 2, 3.5));+ const halfSizeX = this.sizeX / 1.3;+ const halfSizeY = this.sizeY / 1.3;+ const minSize =+ Math.min(this.sizeX, this.sizeY) * (1.4 - State.fill.bleed_strength);+ const minSizeFactor = 0.05 * minSize;+ const maxSizeFactor = 0.4 * minSize;+ const { x: midX, y: midY } = this.midP;++ // Set up erase mode+ Mix.ctx.globalCompositeOperation = "destination-out";++ // Calculate transparency+ const alpha =+ ((5 - map(intensity, 80, 100, 0.3, 0.7, true)) * texture) / 255;+ Mix.ctx.fillStyle = `rgb(255 0 0 / ${alpha})`;+ Mix.ctx.lineWidth = 0;++ // Draw erase circles+ for (let i = 0; i < numCircles; i++) {+ const x = midX + gaussian(0, halfSizeX);+ const y = midY + gaussian(0, halfSizeY);+ const size = rr(minSizeFactor, maxSizeFactor);++ Mix.ctx.beginPath();+ circle(x, y, size);+ if (i % 5 !== 0) Mix.ctx.fill();+ }++ Mix.ctx.globalCompositeOperation = "source-over";+ Mix.ctx.restore();+ }+}++// ---------------------------------------------------------------------------+// Extend Polygon and Plot Prototypes for Fill+// ---------------------------------------------------------------------------++/**+ * Applies a fill effect to the polygon using the current fill state.+ * @param {Color|string} [_color] - The color for the fill.+ * @param {number} [_opacity] - The opacity value.+ * @param {number} [_bleed] - The bleed intensity.+ * @param {number} [_texture] - The texture strength.+ * @param {number} [_border] - The border strength.+ * @param {string} [_direction] - The bleed direction.+ */+Polygon.prototype.fill = function (+ _color = false,+ _opacity,+ _bleed,+ _texture,+ _border,+ _direction,+) {+ let state = FillState();+ if (_color) {+ fill(_color, _opacity);+ fillBleed(_bleed, _direction);+ fillTexture(_texture, _border);+ }+ if (state.isActive) {+ isFieldReady();+ createFill(this);+ }+ FillSetState(state);+};++/**+ * Fills a plot on the canvas by generating a polygon based on the provided coordinates.+ * @param {number} x - The x-coordinate.+ * @param {number} y - The y-coordinate.+ * @param {number} scale - Scaling factor.+ */+Plot.prototype.fill = function (x, y, scale) {+ if (FillState().isActive) {+ if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));+ this.pol = this.genPol(+ x,+ y,+ scale,+ map(State.fill.bleed_strength, 0, 0.6, 0.3, 0.45, true),+ );+ this.pol.fill();+ }+};diff --git a/src/hatch/hatch.js b/src/hatch/hatch.jsnew file mode 100644index 0000000..579bfd8--- /dev/null+++ b/src/hatch/hatch.js@@ -0,0 +1,279 @@+// =============================================================================+// Module: Hatch+// =============================================================================+/**+ * The Hatch module contains functions and classes dedicated to applying+ * hatch patterns over shapes and polygons. It enables the simulation of+ * cross-hatching and shading effects by drawing parallel lines or strokes+ * across a geometry. The module supports adjustable spacing, angle, and+ * optional style parameters (such as randomness, continuity, and gradient),+ * giving an artistic representation similar to hand-drawn hatching techniques.+ *+ * The implementation allows for hatching to be applied either to a Polygon+ * directly or via a Plot, extending the drawing capabilities with layered,+ * stylized textures.+ */++import { State } from "../core/color.js";+import { toDegrees, 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";++// ---------------------------------------------------------------------------+// Hatch State and Helpers+// ---------------------------------------------------------------------------++/**+ * Global hatch state settings.+ */+State.hatch = {+ isActive: false,+ dist: 5,+ angle: 45,+ options: {},+ hBrush: false,+};++/**+ * Returns a shallow copy of the current hatch state.+ * @returns {object} The current hatch state.+ */+export function HatchState() {+ return { ...State.hatch };+}++/**+ * Updates the global hatch state.+ * @param {object} state - The new hatch state.+ */+export function HatchSetState(state) {+ State.hatch = { ...state };+}++// ---------------------------------------------------------------------------+// Hatch Style Functions+// ---------------------------------------------------------------------------++/**+ * 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 {object} options - Optional parameters to affect the hatching style:+ * - rand: Number value to introduce randomness.+ * - continuous: Boolean to connect adjacent lines.+ * - gradient: Number to gradually change spacing.+ */+export function hatch(+ dist = 5,+ angle = 45,+ options = { rand: false, continuous: false, gradient: false }+) {+ let s = State.hatch;+ s.isActive = true;+ s.dist = dist;+ s.angle = angle;+ s.options = options;+}++/**+ * Sets the hatch brush style for subsequent hatching.+ *+ * @param {string} brush - The brush name.+ * @param {string|Color} color - The brush color.+ * @param {number} weight - The brush weight (size).+ */+export function hatchStyle(brush, color = "black", weight = 1) {+ State.hatch.hBrush = { brush, color, weight };+}++/**+ * Disables hatching.+ */+export function noHatch() {+ State.hatch.isActive = false;+ State.hatch.hBrush = false;+}++// ---------------------------------------------------------------------------+// Fill Manager Functions+// ---------------------------------------------------------------------------++/**+ * Creates a hatching pattern over the given polygon(s).+ *+ * @param {Polygon|Polygon[]} polygons - A polygon or an array of polygons.+ */+export function createHatch(polygons) {+ let dist = State.hatch.dist;+ let angle = toDegrees(State.hatch.angle) % 180; // normalize to [0, 180)+ let options = State.hatch.options;++ // Save current stroke state+ let save = BrushState();+ // If a hatch brush is set, override with those parameters.+ if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));++ // Compute overall bounding box for all polygons.+ if (!Array.isArray(polygons)) polygons = [polygons];+ const overallBB = computeOverallBoundingBox(polygons);++ // Build a bounding polygon based on the overall bounding box.+ let ventana = new Polygon([+ [overallBB.minX, overallBB.minY],+ [overallBB.maxX, overallBB.minY],+ [overallBB.maxX, overallBB.maxY],+ [overallBB.minX, overallBB.maxY],+ ]);++ // Determine starting y coordinate based on angle.+ let startY = angle <= 90 && angle >= 0 ? overallBB.minY : overallBB.maxY;+ let gradient = options.gradient+ ? map(options.gradient, 0, 1, 1, 1.1, true)+ : 1;+ let dots = [];+ let i = 0;+ let dist1 = dist;++ // Function to generate a line for index i.+ let linea = (i) => {+ return {+ point1: {+ x: overallBB.minX + dist1 * i * cos(-angle + 90),+ y: startY + dist1 * i * sin(-angle + 90),+ },+ point2: {+ x: overallBB.minX + dist1 * i * cos(-angle + 90) + cos(-angle),+ y: startY + dist1 * i * sin(-angle + 90) + sin(-angle),+ },+ };+ };++ // Generate lines and calculate intersections with polygons+ // Loop through the lines based on the distance and angle to calculate intersections with the polygons+ // The loop continues until a line does not intersect with the bounding window polygon+ // Each iteration accounts for the gradient effect by adjusting the distance between lines+ while (ventana.intersect(linea(i)).length > 0) {+ let tempArray = [];+ for (let p of polygons) {+ tempArray.push(p.intersect(linea(i)));+ }+ dots[i] = tempArray+ .flat()+ .sort((a, b) => (a.x === b.x ? a.y - b.y : a.x - b.x));+ dist1 *= gradient;+ i++;+ }++ // Filter out empty intersection sets.+ let gdots = dots.filter((dd) => typeof dd[0] !== "undefined");++ // Draw the hatching lines using the calculated intersections+ // If the 'rand' option is enabled, add randomness to the start and end points of the lines+ // If the 'continuous' option is set, connect the end of one line to the start of the next+ let r = options.rand || 0;+ for (let j = 0; j < gdots.length; j++) {+ let dd = gdots[j];+ let continuousLine = j > 0 && options.continuous;+ for (let i = 0; i < dd.length - 1; i += 2) {+ if (r !== 0) {+ dd[i].x += r * dist * rr(-10, 10);+ dd[i].y += r * dist * rr(-10, 10);+ dd[i + 1].x += r * dist * rr(-10, 10);+ dd[i + 1].y += r * dist * rr(-10, 10);+ }+ line(dd[i].x, dd[i].y, dd[i + 1].x, dd[i + 1].y);+ if (continuousLine) {+ line(gdots[j - 1][1].x, gdots[j - 1][1].y, dd[i].x, dd[i].y);+ }+ }+ }++ // Restore previous brush state.+ BrushSetState(save);+}++/**+ * Computes the bounding box for a single polygon.+ * @param {Polygon} polygon - The polygon to evaluate.+ * @returns {object} The bounding box as {minX, minY, maxX, maxY}.+ */+function computeBoundingBoxForPolygon(polygon) {+ if (polygon._boundingBox) return polygon._boundingBox;+ let minX = Infinity,+ minY = Infinity,+ maxX = -Infinity,+ maxY = -Infinity;+ for (let i = 0; i < polygon.a.length; i++) {+ const [x, y] = polygon.a[i];+ if (x < minX) minX = x;+ if (x > maxX) maxX = x;+ if (y < minY) minY = y;+ if (y > maxY) maxY = y;+ }+ polygon._boundingBox = { minX, minY, maxX, maxY };+ return polygon._boundingBox;+}++/**+ * Computes an overall bounding box for an array of polygons.+ * @param {Array} polygons - Array of Polygon objects.+ * @returns {object} The overall bounding box {minX, minY, maxX, maxY}.+ */+function computeOverallBoundingBox(polygons) {+ let overall = {+ minX: Infinity,+ minY: Infinity,+ maxX: -Infinity,+ maxY: -Infinity,+ };+ for (let poly of polygons) {+ const bb = computeBoundingBoxForPolygon(poly);+ overall.minX = Math.min(overall.minX, bb.minX);+ overall.minY = Math.min(overall.minY, bb.minY);+ overall.maxX = Math.max(overall.maxX, bb.maxX);+ overall.maxY = Math.max(overall.maxY, bb.maxY);+ }+ return overall;+}++// ---------------------------------------------------------------------------+// Extend Polygon and Plot Prototypes+// ---------------------------------------------------------------------------++/**+ * Adds a hatch effect to the polygon.+ *+ * If a distance is provided, activates hatching with the given parameters.+ * 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 {object} _options - Optional hatch options.+ */+Polygon.prototype.hatch = function (_dist = false, _angle, _options) {+ let state = HatchState();+ if (_dist) hatch(_dist, _angle, _options);+ if (state.isActive) {+ createHatch(this);+ }+ HatchSetState(state);+};++/**+ * Applies hatching to a plot.+ *+ * If hatching is active, generates a polygon from the plot and applies hatch.+ *+ * @param {number} x - The x-coordinate to draw at.+ * @param {number} y - The y-coordinate to draw at.+ * @param {number} scale - Scaling factor.+ */+Plot.prototype.hatch = function (x, y, scale) {+ if (HatchState().isActive) {+ if (this.origin) (x = this.origin[0]), (y = this.origin[1]), (scale = 1);+ this.pol = this.genPol(x, y, scale, 0.25);+ this.pol.hatch();+ }+};diff --git a/src/index.js b/src/index.jsindex a5e0a8d..efe85d4 100644--- a/src/index.js+++ b/src/index.js@@ -1,9 +1,9 @@/*** @fileoverview p5.brush - A comprehensive toolset for brush management in p5.js.- * @version 1.1.4+ * @version 2.0.0-alpha* @license MIT* @author Alejandro Campos Uribe- *n+ ** @description* p5.brush is a p5.js library dedicated to the creation and management of custom brushes.* It extends the drawing capabilities of p5.js by allowing users to simulate a wide range@@ -57,2992 +57,90 @@* DEALINGS IN THE SOFTWARE.*/-// =============================================================================-// Section: Configure and Initiate-// =============================================================================-/**- * This section contains functions for setting up the drawing system. It allows- * for configuration with custom options, initialization of the system, preloading- * necessary assets, and a check to ensure the system is ready before any drawing- * operation is performed.- */--/**- * Reference to the renderer or canvas object.- * @type {Object}- */-let _r;--/**- * Flag to indicate if the system is ready for rendering.- * @type {boolean}- */-let _isReady = false;-let _isLoaded = false;--/**- * Flag to indicate if p5 is instanced or global mode.- * @type {boolean}- */-let _isInstanced = false;-let _inst = false;--/**- * Initializes the drawing system and sets up the environment.- * @param {string|boolean} [canvasID=false] - Optional ID of the canvas element to use.- * If false, it uses the current window as the rendering context.- */-export function load(canvasID = false) {- let inst = _isInstanced && canvasID ? _inst : false;- if (_isReady) remove(false);- // Set the renderer to the specified canvas or to the window if no ID is given- if (!canvasID && _isInstanced) canvasID = _inst;- _r = !canvasID ? window.self : canvasID;-- // Load color blending- Mix.load(inst);- _isLoaded = true;-}--/**- * Removes brush buffers- */-export function remove(a = true) {- if (_isReady) {- Mix.masks[0].remove();- Mix.masks[0] = null;- Mix.masks[1].remove();- Mix.masks[1] = null;- Mix.masks[2].remove();- Mix.masks[2] = null;- if (a) brush.load();- }-}--/**- * Preloads necessary assets or configurations.- * This function should be called before setup to ensure all assets are loaded.- */-export function preload() {- // Load custom image tips- T.load();-}--/**- * Ensures that the drawing system is ready before any drawing operation.- * Loads the system if it hasn't been loaded already.- */-function _ensureReady() {- if (!_isReady) {- if (!_isLoaded) load();- FF.create(); // Load flowfield system- scaleBrushes(_r.width / 250); // Adjust standard brushes to match canvas- _isReady = true;- }-}--// =============================================================================-// Section: Randomness and other auxiliary functions-// =============================================================================-/**- * This section includes utility functions for randomness, mapping values,- * constraining numbers within a range, and precalculated trigonometric values- * to optimize performance. Additionally, it provides auxiliary functions for- * geometric calculations such as translation extraction, line intersection,- * and angle calculation.- */--import { prng_alea } from "esm-seedrandom";--/**- * The basic source of randomness, can be seeded for determinism.- * @returns {number} A random number between 0 and 1.- */-let rng = new prng_alea(Math.random());-export function seed(s) {- rng = new prng_alea(s);-}--/**- * Object for random number generation and related utility functions.- * @property {function} source - Function that returns a random number from the base random generator.- * @property {function} random - Function to generate a random number within a specified range.- * @property {function} randInt - Function to generate a random integer within a specified range.- * @property {function} weightedRand - Function to generate a random value based on weighted probabilities.- * @property {function} map - Function to remap a number from one range to another.- * @property {function} constrain - Function to constrain a number within a range.- * @property {function} cos - Function to get the cosine of an angle from precalculated values.- * @property {function} sin - Function to get the sine of an angle from precalculated values.- * @property {boolean} isPrecalculationDone - Flag to check if precalculation of trigonometric values is complete.- * @property {function} preCalculation - Function to precalculate trigonometric values.- */-const R = {- /**- * Generates a random number within a specified range.- * @param {number} [min=0] - The lower bound of the range.- * @param {number} [max=1] - The upper bound of the range.- * @returns {number} A random number within the specified range.- */- random(e = 0, r = 1) {- return e + rng() * (r - e);- },-- /**- * Generates a random integer within a specified range.- * @param {number} min - The lower bound of the range.- * @param {number} max - The upper bound of the range.- * @returns {number} A random integer within the specified range.- */- randInt(e, r) {- return Math.floor(this.random(e, r));- },-- /**- * Generates a random gaussian.- * @param {number} mean - Mean.- * @param {number} stdev - Standard deviation.- * @returns {number} A random number following a normal distribution.- */- gaussian(mean = 0, stdev = 1) {- const u = 1 - rng();- const v = rng();- const z = Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);- return z * stdev + mean;- },-- /**- * Generates a random value based on weighted probabilities.- * @param {Object} weights - An object containing values as keys and their probabilities as values.- * @returns {string} A key randomly chosen based on its weight.- */- weightedRand(e) {- let r,- a,- n = [];- for (r in e) for (a = 0; a < 10 * e[r]; a++) n.push(r);- return n[Math.floor(rng() * n.length)];- },-- /**- * Remaps a number from one range to another.- * @param {number} value - The number to remap.- * @param {number} a - The lower bound of the value's current range.- * @param {number} b- The upper bound of the value's current range.- * @param {number} c - The lower bound of the value's target range.- * @param {number} d - The upper bound of the value's target range.- * @param {boolean} [withinBounds=false] - Whether to constrain the value to the target range.- * @returns {number} The remapped number.- */- map(value, a, b, c, d, withinBounds = false) {- let r = c + ((value - a) / (b - a)) * (d - c);- if (!withinBounds) return r;- if (c < d) {- return this.constrain(r, c, d);- } else {- return this.constrain(r, d, c);- }- },-- /**- * Constrains a number to be within a range.- * @param {number} n - The number to constrain.- * @param {number} low - The lower bound of the range.- * @param {number} high - The upper bound of the range.- * @returns {number} The constrained number.- */- constrain(n, low, high) {- return Math.max(Math.min(n, high), low);- },-- /**- * Calculates the cosine for a given angle using precalculated values.- * @param {number} angle - The angle in degrees.- * @returns {number} The cosine of the angle.- */- cos(angle) {- return this.c[Math.floor(4 * (((angle % 360) + 360) % 360))];- },-- /**- * Calculates the sine for a given angle using precalculated values.- * @param {number} angle - The angle in degrees.- * @returns {number} The sine of the angle.- */- sin(angle) {- return this.s[Math.floor(4 * (((angle % 360) + 360) % 360))];- },- // Flag to indicate if the trigonometric tables have been precalculated- isPrecalculationDone: false,-- /**- * Precalculates trigonometric values for improved performance.- * This function should be called before any trigonometric calculations are performed.- */- preCalculation() {- if (this.isPrecalculationDone) return;- const totalDegrees = 1440;- const radiansPerIndex = (2 * Math.PI) / totalDegrees;- this.c = new Float64Array(totalDegrees);- this.s = new Float64Array(totalDegrees);- for (let i = 0; i < totalDegrees; i++) {- const radians = i * radiansPerIndex;- R.c[i] = Math.cos(radians);- R.s[i] = Math.sin(radians);- }- this.isPrecalculationDone = true;- },-- /**- * Checks if value is numeric- */- isNumber: (a) => !isNaN(a),-- /**- * Changes angles to degrees and between 0-360- */- toDegrees: (a) =>- (((_r.angleMode() === "radians" ? (a * 180) / Math.PI : a) % 360) + 360) %- 360,-- /**- * Calculates distance between two 2D points- */- dist: (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1),-};-// Perform the precalculation of trigonometric values for the R object-R.preCalculation();--/**- * Calculates the intersection point between two line segments if it exists.- *- * @param {Object} seg1Start - The start point of the first line segment.- * @param {Object} seg1End - The end point of the first line segment.- * @param {Object} seg2Start - The start point of the second line segment.- * @param {Object} seg2End - The end point of the second line segment.- * @param {boolean} [includeSegmentExtension=false] - Whether to include points of intersection not lying on the segments.- * @returns {Object|boolean} The intersection point as an object with 'x' and 'y' properties, or 'false' if there is no intersection.- */-function _intersectLines(- seg1Start,- seg1End,- seg2Start,- seg2End,- includeSegmentExtension = false-) {- // Extract coordinates from points- let x1 = seg1Start.x,- y1 = seg1Start.y;- let x2 = seg1End.x,- y2 = seg1End.y;- let x3 = seg2Start.x,- y3 = seg2Start.y;- let x4 = seg2End.x,- y4 = seg2End.y;- // Early return if line segments are points or if the lines are parallel- if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) {- return false; // Segments are points- }- let deltaX1 = x2 - x1,- deltaY1 = y2 - y1;- let deltaX2 = x4 - x3,- deltaY2 = y4 - y3;- let denominator = deltaY2 * deltaX1 - deltaX2 * deltaY1;- if (denominator === 0) {- return false; // Lines are parallel- }- // Calculate the intersection point- let ua = (deltaX2 * (y1 - y3) - deltaY2 * (x1 - x3)) / denominator;- let ub = (deltaX1 * (y1 - y3) - deltaY1 * (x1 - x3)) / denominator;- // Check if the intersection is within the bounds of the line segments- if (!includeSegmentExtension && (ub < 0 || ub > 1)) {- return false;- }- // Calculate the intersection coordinates- let x = x1 + ua * deltaX1;- let y = y1 + ua * deltaY1;- return { x: x, y: y };-}--/**- * Calculates the angle in degrees between two points in 2D space.- * The angle is measured in a clockwise direction from the positive X-axis.- *- * @param {number} x1 - The x-coordinate of the first point.- * @param {number} y1 - The y-coordinate of the first point.- * @param {number} x2 - The x-coordinate of the second point.- * @param {number} y2 - The y-coordinate of the second point.- * @returns {number} The angle in degrees between the two points.- */-function _calculateAngle(x1, y1, x2, y2) {- // Calculate the angle based on the quadrant in which the second point lies- let angleRadians = Math.atan2(-(y2 - y1), x2 - x1);- // Convert radians to degrees and normalize the angle between 0 and 360- let angleDegrees = angleRadians * (180 / Math.PI);- return ((angleDegrees % 360) + 360) % 360;-}--/**- * Object that saves the current p5.brush state for push and pop operations- */-const _saveState = {- field: {},- stroke: {},- hatch: {},- fill: {},- others: {},-};--/**- * Saves current state to object- */-export function push() {- // Field- _saveState.field.isActive = FF.isActive;- _saveState.field.current = FF.current;-- // Stroke- _saveState.stroke.isActive = B.isActive;- _saveState.stroke.name = B.name;- _saveState.stroke.color = B.c;- _saveState.stroke.weight = B.w;- _saveState.stroke.clip = B.cr;-- // Hatch- _saveState.hatch.isActive = H.isActive;- _saveState.hatch.hatchingParams = H.hatchingParams;- _saveState.hatch.hatchingBrush = H.hatchingBrush;-- // Fill- _saveState.fill.isActive = F.isActive;- _saveState.fill.color = F.color;- _saveState.fill.opacity = F.opacity;- _saveState.fill.bleed_strength = F.bleed_strength;- _saveState.fill.texture_strength = F.texture_strength;- _saveState.fill.border_strength = F.border_strength;-- // Rotate- _saveState.others.rotate = Matrix.rotation;-}--/**- * Restores previous state from object- */-export function pop() {- // Field- FF.isActive = _saveState.field.isActive;- FF.current = _saveState.field.current;-- // Stroke- B.isActive = _saveState.stroke.isActive;- B.name = _saveState.stroke.name;- B.c = _saveState.stroke.color;- B.w = _saveState.stroke.weight;- B.cr = _saveState.stroke.clip;-- // Hatch- H.isActive = _saveState.hatch.isActive;- H.hatchingParams = _saveState.hatch.hatchingParams;- H.hatchingBrush = _saveState.hatch.hatchingBrush;-- // Fill- F.isActive = _saveState.fill.isActive;- F.color = _saveState.fill.color;- F.opacity = _saveState.fill.opacity;- F.bleed_strength = _saveState.fill.bleed_strength;- F.texture_strength = _saveState.fill.texture_strength;- F.border_strength = _saveState.fill.border_strength;-- // Rotate- Matrix.rotation = _saveState.others.rotate;-}--/**- * Object to perform matrix translation and rotation operations- */-const Matrix = {- translation: [0, 0],- rotation: 0,- /**- * Captures the current translation values from the renderer's transformation matrix.- *- * Assumes that the renderer's transformation matrix (`uModelMatrix`) is a 4x4 matrix- * where the translation components are in the 13th (index 12) and 14th (index 13) positions.- *- * @returns {number[]} An array containing the x (horizontal) and y (vertical) translation values.- */- trans() {- // Access the renderer's current model-view matrix and extract the translation components- this.translation = [- _r._renderer.uModelMatrix.mat4[12],- _r._renderer.uModelMatrix.mat4[13],- ];- // Return the translation components as a two-element array- return this.translation;- },-};--/**- * Captures the desired rotation.- */-export function rotate(a = 0) {- Matrix.rotation = R.toDegrees(a);-}--/**- * Object to perform scale operations- */-let _curScale = 1;-export function scale(a) {- _curScale *= a;-}--// =============================================================================-// Section: Color Blending - Uses spectral.js as a module-// =============================================================================-/**- * The Mix object is responsible for handling color blending operations within- * the rendering context. It utilizes WebGL shaders to apply advanced blending- * effects based on Kubelka-Munk theory. It depends on spectral.js for the- * blending logic incorporated into its fragment shader.- */--/**- * Enables/Disables color caching for WebGL Shaders.- * Color caching increases performance but might produce worse textures- * when using the same colour repeteadly.- * @param {bool} bool- *- */-export function colorCache(bool = true) {- Mix.isCaching = bool;-}--/**- * Object handling blending operations with WebGL shaders.- * @property {boolean} loaded - Flag indicating if the blend shaders have been loaded.- * @property {boolean} isBlending - Flag indicating if the blending has been initiated.- * @property {boolean} isCaching - Flag indicating if the color caching is active.- * @property {Float32Array} currentColor - Typed array to hold color values for shaders.- * @property {function} load - Loads resources and initializes blend operations.- * @property {function} blend - Applies blending effects using the initialized shader.- * @property {string} vert - Vertex shader source code.- * @property {string} frag - Fragment shader source code with blending logic.- */-const Mix = {- loaded: false,- isBlending: false,- isCaching: true,- currentColor: new Float32Array(3),-- /**- * Loads necessary resources and prepares the mask buffer and shader for colour blending.- */- load(inst) {- this.type = _isInstanced && !inst ? 0 : !inst ? 1 : 2;- this.masks = [];- // Create a buffer to be used as a mask for blending- // WEBGL buffer for img brushes (image() is much quicker like this)- // Create a buffer for noBlend brushes- for (let i = 0; i < 3; i++) {- switch (this.type) {- case 0:- this.masks[i] = _r.createGraphics(- _r.width,- _r.height,- i == 1 ? _r.WEBGL : _r.P2D- );- break;- case 1:- this.masks[i] = createGraphics(- _r.width,- _r.height,- i == 1 ? WEBGL : P2D- );- break;- case 2:- this.masks[i] = inst.createGraphics(- inst.width,- inst.height,- i == 1 ? inst.WEBGL : inst.P2D- );- break;- }- }-- for (let mask of this.masks) {- mask.pixelDensity(_r.pixelDensity());- mask.clear();- mask.angleMode(_r.DEGREES);- mask.noSmooth();- }-- // Create the shader program from the vertex and fragment shaders- this.shader = _r.createShader(this.vert, this.frag);- Mix.loaded = true;- },-- /**- * Converts a color object with RGB levels to a Float32Array representation.- * The RGB levels are normalized to a range of 0.0 to 1.0.- * @param {object} _color - A p5 color object representing a color, containing an 'levels' property.- * @returns {Float32Array} A Float32Array with three elements, each representing the normalized levels of red, green, and blue.- */- getPigment(_color) {- let currentLevels = _color.levels;- let colorArray = new Float32Array(3);- colorArray[0] = currentLevels[0] / 255.0;- colorArray[1] = currentLevels[1] / 255.0;- colorArray[2] = currentLevels[2] / 255.0;- return colorArray;- },-- /**- * There are two parallel blender instances: one uses the 2D mask, the other the WEBGL mask- * 2D Canvas API mask: for basi geometry (circles, polygons, etc), which is much faster with the 2D API- * WEBGL mask: for image-type brushes. p5 image() is much faster in WEBGL mode- */- color1: new Float32Array(3),- color2: new Float32Array(3),- blending1: false,- blending2: false,-- /**- * Applies the blend shader to the current rendering context.- * @param {string} _c - The color used for blending, as a p5.Color object.- * @param {boolean} _isLast - Indicates if this is the last blend after setup and draw.- * @param {boolean} _isLast - Indicates if this is the last blend after setup and draw.- */- blend(_color = false, _isLast = false, webgl_mask = false) {- _ensureReady();-- // Select between the two options:- this.isBlending = webgl_mask ? this.blending1 : this.blending2;- this.currentColor = webgl_mask ? this.color1 : this.color2;-- // Check if blending is initialised- if (!this.isBlending) {- // If color has been provided, we initialise blending- if (_color) {- this.currentColor = this.getPigment(_color);- if (webgl_mask)- (this.blending1 = true), (this.color1 = this.currentColor);- else (this.blending2 = true), (this.color2 = this.currentColor);- } else if (_isLast) {- if (!webgl_mask) reDraw();- return;- }- }-- // Checks if newColor is the same than the cadhedColor- // If it is the same, we wait before applying the shader for color mixing- // If it's NOT the same, we apply the shader and cache the new color- let newColor = !_color ? this.currentColor : this.getPigment(_color);-- if (- newColor.toString() !== this.currentColor.toString() ||- _isLast ||- !this.isCaching- ) {- // Paste info from noBlend buffer- reDraw();-- if (this.isBlending) {- _r.push();- _r.translate(-Matrix.trans()[0], -Matrix.trans()[1]);- // Use the blend shader for rendering- _r.shader(this.shader);- // Set shader uniforms- // Color to blend- this.shader.setUniform("addColor", this.currentColor);- // Source canvas- this.shader.setUniform("source", _r._renderer);- // Bool to active watercolor blender vs marker blenderd- this.shader.setUniform("active", Mix.watercolor);- // Random values for watercolor blender- this.shader.setUniform("random", [R.random(), R.random(), R.random()]);- // We select and apply the correct mask here- let mask = webgl_mask ? this.masks[1] : this.masks[0];- this.shader.setUniform("mask", mask);- // Draw a rectangle covering the whole canvas to apply the shader- _r.fill(0, 0, 0, 0);- _r.noStroke();- _r.rect(-_r.width / 2, -_r.height / 2, _r.width, _r.height);- _r.pop();- // Clear the mask after drawing- mask.clear();- }- // We cache the new color here- if (!_isLast) {- this.currentColor = this.getPigment(_color);- if (webgl_mask) this.color1 = this.currentColor;- else this.color2 = this.currentColor;- }- }-- if (_isLast) {- this.isBlending = false;- if (webgl_mask) this.blending1 = this.isBlending;- else this.blending2 = this.isBlending;- }- },-- // Vertex shader source code- vert: `precision highp float;attribute vec3 aPosition;attribute vec2 aTexCoord;uniform mat4 uModelViewMatrix,uProjectionMatrix;varying vec2 vVertTexCoord;void main(){gl_Position=uProjectionMatrix*uModelViewMatrix*vec4(aPosition,1);vVertTexCoord=aTexCoord;}`,-- // Fragment shader source code with blending operations- // For unminified shader see shader_unminified.frag- frag: `precision highp float;varying vec2 vVertTexCoord;uniform sampler2D source,mask;uniform vec4 addColor;uniform vec3 random;uniform bool active;- #ifndef SPECTRAL- #define SPECTRAL- float x(float v){return v<.04045?v/12.92:pow((v+.055)/1.055,2.4);}float v(float v){return v<.0031308?v*12.92:1.055*pow(v,1./2.4)-.055;}vec3 m(vec3 v){return vec3(x(v[0]),x(v[1]),x(v[2]));}vec3 f(vec3 f){return clamp(vec3(v(f[0]),v(f[1]),v(f[2])),0.,1.);}void f(vec3 v,out float m,out float f,out float x,out float y,out float z,out float i,out float r){m=min(v.x,min(v.y,v.z));v-=m;f=min(v.y,v.z);x=min(v.x,v.z);y=min(v.x,v.y);z=min(max(0.,v.x-v.z),max(0.,v.x-v.y));i=min(max(0.,v.y-v.z),max(0.,v.y-v.x));r=min(max(0.,v.z-v.y),max(0.,v.z-v.x));}void f(vec3 v,inout float i[38]){float x,y,d,z,o,m,e;f(v,x,y,d,z,o,m,e);i[0]=max(1e-4,x+y*.96853629+d*.51567122+z*.02055257+o*.03147571+m*.49108579+e*.97901834);i[1]=max(1e-4,x+y*.96855103+d*.5401552+z*.02059936+o*.03146636+m*.46944057+e*.97901649);i[2]=max(1e-4,x+y*.96859338+d*.62645502+z*.02062723+o*.03140624+m*.4016578+e*.97901118);i[3]=max(1e-4,x+y*.96877345+d*.75595012+z*.02073387+o*.03119611+m*.2449042+e*.97892146);i[4]=max(1e-4,x+y*.96942204+d*.92826996+z*.02114202+o*.03053888+m*.0682688+e*.97858555);i[5]=max(1e-4,x+y*.97143709+d*.97223624+z*.02233154+o*.02856855+m*.02732883+e*.97743705);i[6]=max(1e-4,x+y*.97541862+d*.98616174+z*.02556857+o*.02459485+m*.013606+e*.97428075);i[7]=max(1e-4,x+y*.98074186+d*.98955255+z*.03330189+o*.0192952+m*.01000187+e*.96663223);i[8]=max(1e-4,x+y*.98580992+d*.98676237+z*.05185294+o*.01423112+m*.01284127+e*.94822893);i[9]=max(1e-4,x+y*.98971194+d*.97312575+z*.10087639+o*.01033111+m*.02636635+e*.89937713);i[10]=max(1e-4,x+y*.99238027+d*.91944277+z*.24000413+o*.00765876+m*.07058713+e*.76070164);i[11]=max(1e-4,x+y*.99409844+d*.32564851+z*.53589066+o*.00593693+m*.70421692+e*.4642044);i[12]=max(1e-4,x+y*.995172+d*.13820628+z*.79874659+o*.00485616+m*.85473994+e*.20123039);i[13]=max(1e-4,x+y*.99576545+d*.05015143+z*.91186529+o*.00426186+m*.95081565+e*.08808402);i[14]=max(1e-4,x+y*.99593552+d*.02912336+z*.95399623+o*.00409039+m*.9717037+e*.04592894);i[15]=max(1e-4,x+y*.99564041+d*.02421691+z*.97137099+o*.00438375+m*.97651888+e*.02860373);i[16]=max(1e-4,x+y*.99464769+d*.02660696+z*.97939505+o*.00537525+m*.97429245+e*.02060067);i[17]=max(1e-4,x+y*.99229579+d*.03407586+z*.98345207+o*.00772962+m*.97012917+e*.01656701);i[18]=max(1e-4,x+y*.98638762+d*.04835936+z*.98553736+o*.0136612+m*.9425863+e*.01451549);i[19]=max(1e-4,x+y*.96829712+d*.0001172+z*.98648905+o*.03181352+m*.99989207+e*.01357964);i[20]=max(1e-4,x+y*.89228016+d*8.554e-5+z*.98674535+o*.10791525+m*.99989891+e*.01331243);i[21]=max(1e-4,x+y*.53740239+d*.85267882+z*.98657555+o*.46249516+m*.13823139+e*.01347661);i[22]=max(1e-4,x+y*.15360445+d*.93188793+z*.98611877+o*.84604333+m*.06968113+e*.01387181);i[23]=max(1e-4,x+y*.05705719+d*.94810268+z*.98559942+o*.94275572+m*.05628787+e*.01435472);i[24]=max(1e-4,x+y*.03126539+d*.94200977+z*.98507063+o*.96860996+m*.06111561+e*.01479836);i[25]=max(1e-4,x+y*.02205445+d*.91478045+z*.98460039+o*.97783966+m*.08987709+e*.0151525);i[26]=max(1e-4,x+y*.01802271+d*.87065445+z*.98425301+o*.98187757+m*.13656016+e*.01540513);i[27]=max(1e-4,x+y*.0161346+d*.78827548+z*.98403909+o*.98377315+m*.22169624+e*.01557233);i[28]=max(1e-4,x+y*.01520947+d*.65738359+z*.98388535+o*.98470202+m*.32176956+e*.0156571);i[29]=max(1e-4,x+y*.01475977+d*.59909403+z*.98376116+o*.98515481+m*.36157329+e*.01571025);i[30]=max(1e-4,x+y*.01454263+d*.56817268+z*.98368246+o*.98537114+m*.4836192+e*.01571916);i[31]=max(1e-4,x+y*.01444459+d*.54031997+z*.98365023+o*.98546685+m*.46488579+e*.01572133);i[32]=max(1e-4,x+y*.01439897+d*.52110241+z*.98361309+o*.98550011+m*.47440306+e*.01572502);i[33]=max(1e-4,x+y*.0143762+d*.51041094+z*.98357259+o*.98551031+m*.4857699+e*.01571717);i[34]=max(1e-4,x+y*.01436343+d*.50526577+z*.98353856+o*.98550741+m*.49267971+e*.01571905);i[35]=max(1e-4,x+y*.01435687+d*.5025508+z*.98351247+o*.98551323+m*.49625685+e*.01571059);i[36]=max(1e-4,x+y*.0143537+d*.50126452+z*.98350101+o*.98551563+m*.49807754+e*.01569728);i[37]=max(1e-4,x+y*.01435408+d*.50083021+z*.98350852+o*.98551547+m*.49889859+e*.0157002);}vec3 t(vec3 x){mat3 i;i[0]=vec3(3.24306333,-1.53837619,-.49893282);i[1]=vec3(-.96896309,1.87542451,.04154303);i[2]=vec3(.05568392,-.20417438,1.05799454);float v=dot(i[0],x),y=dot(i[1],x),o=dot(i[2],x);return f(vec3(v,y,o));}vec3 d(float m[38]){vec3 i=vec3(0);i+=m[0]*vec3(6.469e-5,1.84e-6,.00030502);i+=m[1]*vec3(.00021941,6.21e-6,.00103681);i+=m[2]*vec3(.00112057,3.101e-5,.00531314);i+=m[3]*vec3(.00376661,.00010475,.01795439);i+=m[4]*vec3(.01188055,.00035364,.05707758);i+=m[5]*vec3(.02328644,.00095147,.11365162);i+=m[6]*vec3(.03455942,.00228226,.17335873);i+=m[7]*vec3(.03722379,.00420733,.19620658);i+=m[8]*vec3(.03241838,.0066888,.18608237);i+=m[9]*vec3(.02123321,.0098884,.13995048);i+=m[10]*vec3(.01049099,.01524945,.08917453);i+=m[11]*vec3(.00329584,.02141831,.04789621);i+=m[12]*vec3(.00050704,.03342293,.02814563);i+=m[13]*vec3(.00094867,.05131001,.01613766);i+=m[14]*vec3(.00627372,.07040208,.0077591);i+=m[15]*vec3(.01686462,.08783871,.00429615);i+=m[16]*vec3(.02868965,.09424905,.00200551);i+=m[17]*vec3(.04267481,.09795667,.00086147);i+=m[18]*vec3(.05625475,.09415219,.00036904);i+=m[19]*vec3(.0694704,.08678102,.00019143);i+=m[20]*vec3(.08305315,.07885653,.00014956);i+=m[21]*vec3(.0861261,.0635267,9.231e-5);i+=m[22]*vec3(.09046614,.05374142,6.813e-5);i+=m[23]*vec3(.08500387,.04264606,2.883e-5);i+=m[24]*vec3(.07090667,.03161735,1.577e-5);i+=m[25]*vec3(.05062889,.02088521,3.94e-6);i+=m[26]*vec3(.03547396,.01386011,1.58e-6);i+=m[27]*vec3(.02146821,.00810264,0);i+=m[28]*vec3(.01251646,.0046301,0);i+=m[29]*vec3(.00680458,.00249138,0);i+=m[30]*vec3(.00346457,.0012593,0);i+=m[31]*vec3(.00149761,.00054165,0);i+=m[32]*vec3(.0007697,.00027795,0);i+=m[33]*vec3(.00040737,.00014711,0);i+=m[34]*vec3(.00016901,6.103e-5,0);i+=m[35]*vec3(9.522e-5,3.439e-5,0);i+=m[36]*vec3(4.903e-5,1.771e-5,0);i+=m[37]*vec3(2e-5,7.22e-6,0);return i;}float d(float y,float m,float v){float z=m*pow(v,2.);return z/(y*pow(1.-v,2.)+z);}vec3 f(vec3 v,vec3 y,float z){vec3 x=m(v),o=m(y);float i[38],a[38];f(x,i);f(o,a);float r=d(i)[1],e=d(a)[1];z=d(r,e,z);float s[38];for(int u=0;u<38;u++){float p=(1.-z)*(pow(1.-i[u],2.)/(2.*i[u]))+z*(pow(1.-a[u],2.)/(2.*a[u]));s[u]=1.+p-sqrt(pow(p,2.)+2.*p);}return t(d(s));}vec4 f(vec4 v,vec4 x,float y){return vec4(f(v.xyz,x.xyz,y),mix(v.w,x.w,y));}- #endif- float d(vec2 m,vec2 v,float y,out vec2 i){vec2 f=vec2(m.x+m.y*.5,m.y),x=floor(f),o=fract(f);float z=step(o.y,o.x);vec2 d=vec2(z,1.-z),r=x+d,e=x+1.,a=vec2(x.x-x.y*.5,x.y),p=vec2(a.x+d.x-d.y*.5,a.y+d.y),s=vec2(a.x+.5,a.y+1.),w=m-a,g=m-p,k=m-s;vec3 u,c,t,A;if(any(greaterThan(v,vec2(0)))){t=vec3(a.x,p.x,s);A=vec3(a.y,p.y,s.y);if(v.x>0.)t=mod(vec3(a.x,p.x,s),v.x);if(v.y>0.)A=mod(vec3(a.y,p.y,s.y),v.y);u=floor(t+.5*A+.5);c=floor(A+.5);}else u=vec3(x.x,r.x,e),c=vec3(x.y,r.y,e.y);vec3 S=mod(u,289.);S=mod((S*51.+2.)*S+c,289.);S=mod((S*34.+10.)*S,289.);vec3 b=S*.07482+y,C=cos(b),D=sin(b);vec2 h=vec2(C.x,D),B=vec2(C.y,D.y),E=vec2(C.z,D.z);vec3 F=.8-vec3(dot(w,w),dot(g,g),dot(k,k));F=max(F,0.);vec3 G=F*F,H=G*G,I=vec3(dot(h,w),dot(B,g),dot(E,k)),J=G*F,K=-8.*J*I;i=10.9*(H.x*h+K.x*w+(H.y*B+K.y*g)+(H.z*E+K.z*k));return 10.9*dot(H,I);}vec4 d(vec3 v,float x){return vec4(mix(v,vec3(dot(vec3(.299,.587,.114),v)),x),1);}float f(vec2 v,float x,float y,float f){return fract(sin(dot(v,vec2(x,y)))*f);}void main(){vec4 v=texture2D(mask,vVertTexCoord);if(v.x>0.){vec2 x=vec2(12.9898,78.233),o=vec2(7.9898,58.233),m=vec2(17.9898,3.233);float y=f(vVertTexCoord,x.x,x.y,43358.5453)*2.-1.,z=f(vVertTexCoord,o.x,o.y,43213.5453)*2.-1.,e=f(vVertTexCoord,m.x,m.y,33358.5453)*2.-1.;const vec2 i=vec2(0);vec2 s;vec4 r;if(active){float a=d(vVertTexCoord*5.,i,10.*random.x,s),p=d(vVertTexCoord*5.,i,10.*random.y,s),g=d(vVertTexCoord*5.,i,10.*random.z,s),k=.25+.25*d(vVertTexCoord*4.,i,3.*random.x,s);r=vec4(d(addColor.xyz,k).xyz+vec3(a,p,g)*.03*abs(addColor.x-addColor.y-addColor.z),1);}else r=vec4(addColor.xyz,1);if(v.w>.7){float a=.5*(v.w-.7);r=r*(1.-a)-vec4(.5)*a;}vec3 a=f(texture2D(source,vVertTexCoord).xyz,r.xyz,.9*v.w);gl_FragColor=vec4(a+.01*vec3(y,z,e),1);}}`,-};--/**- * This function forces standard-brushes to be updated into the canvas- */-export function reDraw() {- _r.push();- _r.translate(-Matrix.trans()[0], -Matrix.trans()[1]);- _r.image(Mix.masks[2], -_r.width / 2, -_r.height / 2);- Mix.masks[2].clear();- _r.pop();-}--/**- * This function forces marker-brushes and fills to be updated into the canvas- */-export function reBlend() {- Mix.blend(false, true);- Mix.blend(false, true, true);-}--/**- * Register methods after setup() and post draw() for belding last buffered color- */-function _registerMethods(p5p) {- p5p.registerMethod("afterSetup", () => Mix.blend(false, true));- p5p.registerMethod("afterSetup", () => Mix.blend(false, true, true));- p5p.registerMethod("post", () => Mix.blend(false, true));- p5p.registerMethod("post", () => Mix.blend(false, true, true));-}-if (typeof p5 !== "undefined") _registerMethods(p5.prototype);--export function instance(inst) {- _isInstanced = true;- _inst = inst;- _r = inst;- _registerMethods(inst);-}--// =============================================================================-// Section: FlowField-// =============================================================================-/**- * The FlowField (FF) section includes functions and objects for creating and managing vector fields.- * These fields can guide the motion of particles or brush strokes in a canvas, creating complex and- * dynamic visual patterns.- */--/**- * Activates a specific vector field by name, ensuring it's ready for use.- * @param {string} a - The name of the vector field to activate.- */-export function field(a) {- _ensureReady();- // Check if field exists- FF.isActive = true; // Mark the field framework as active- FF.current = a; // Update the current field-}--/**- * Deactivates the current vector field.- */-export function noField() {- _ensureReady();- FF.isActive = false;-}--/**- * 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.- */-export function addField(name, funct) {- FF.list.set(name, { gen: funct }); // Map the field name to its generator function- FF.current = name; // Set the newly added field as the current one to be used- FF.refresh(); // Refresh the field values using the generator function-}--/**- * Refreshes the current vector field based on the generator function, which can be time-dependent.- * @param {number} [t=0] - An optional time parameter that can affect field generation.- */-export function refreshField(t) {- FF.refresh(t);-}--/**- * Retrieves a list of all available vector field names.- * @returns {Iterator<string>} An iterator that provides the names of all the fields.- */-export function listFields() {- return Array.from(FF.list.keys());-}--/**- * Represents a framework for managing vector fields used in dynamic simulations or visualizations.- * @property {boolean} isActive - Indicates whether any vector field is currently active.- * @property {Map} list - A map associating field names to their respective generator functions and current states.- * @property {Array} field - An array representing the current vector field grid with values.- */-const FF = {- isActive: false,- list: new Map(),- current: "",-- /**- * Calculates a relative step length based on the renderer's dimensions, used in field grid calculations.- * @returns {number} The relative step length value.- */- step_length() {- return Math.min(_r.width, _r.height) / 1000;- },-- /**- * Initializes the field grid and sets up the vector field's structure based on the renderer's dimensions.- */- create() {- this.R = _r.width * 0.01; // Determine the resolution of the field grid- this.left_x = -1 * _r.width; // Left boundary of the field- this.top_y = -1 * _r.height; // Top boundary of the field- this.num_columns = Math.round((2 * _r.width) / this.R); // Number of columns in the grid- this.num_rows = Math.round((2 * _r.height) / this.R); // Number of columns in the grid- this.addStandard(); // Add default vector fields- },-- /**- * Retrieves the field values for the current vector field.- * @returns {Float64Array[]} The current vector field grid.- */- flow_field() {- return this.list.get(this.current).field;- },-- /**- * Regenerates the current vector field using its associated generator function.- * @param {number} [t=0] - An optional time parameter that can affect field generation.- */- refresh(t = 0) {- this.list.get(this.current).field = this.list- .get(this.current)- .gen(t, this.genField());- },-- /**- * Generates empty field array using its associated generator function.- * @returns {Float64Array[]} Empty vector field grid.- */- genField() {- let grid = new Array(this.num_columns); // Initialize the field array- for (let i = 0; i < this.num_columns; i++) {- grid[i] = new Float64Array(this.num_rows);- }- return grid;- },-- /**- * Adds standard predefined vector fields to the list with unique behaviors.- */- addStandard() {- addField("curved", function (t, field) {- let angleRange = R.randInt(-25, -15);- if (R.randInt(0, 100) % 2 == 0) {- angleRange = angleRange * -1;- }- for (let column = 0; column < FF.num_columns; column++) {- for (let row = 0; row < FF.num_rows; row++) {- let noise_val = _r.noise(- column * 0.02 + t * 0.03,- row * 0.02 + t * 0.03- );- let angle = R.map(noise_val, 0.0, 1.0, -angleRange, angleRange);- field[column][row] = 3 * angle;- }- }- return field;- });- addField("truncated", function (t, field) {- let angleRange = R.randInt(-25, -15) + 5 * R.sin(t);- if (R.randInt(0, 100) % 2 == 0) {- angleRange = angleRange * -1;- }- let truncate = R.randInt(5, 10);- for (let column = 0; column < FF.num_columns; column++) {- for (let row = 0; row < FF.num_rows; row++) {- let noise_val = _r.noise(column * 0.02, row * 0.02);- let angle =- Math.round(- R.map(noise_val, 0.0, 1.0, -angleRange, angleRange) / truncate- ) * truncate;- field[column][row] = 4 * angle;- }- }- return field;- });- addField("zigzag", function (t, field) {- let angleRange = R.randInt(-30, -15) + Math.abs(44 * R.sin(t));- if (R.randInt(0, 100) % 2 == 0) {- angleRange = angleRange * -1;- }- let dif = angleRange;- let angle = 0;- for (let column = 0; column < FF.num_columns; column++) {- for (let row = 0; row < FF.num_rows; row++) {- field[column][row] = angle;- angle = angle + dif;- dif = -1 * dif;- }- angle = angle + dif;- dif = -1 * dif;- }- return field;- });- addField("waves", function (t, field) {- let sinrange = R.randInt(10, 15) + 5 * R.sin(t);- let cosrange = R.randInt(3, 6) + 3 * R.cos(t);- let baseAngle = R.randInt(20, 35);- for (let column = 0; column < FF.num_columns; column++) {- for (let row = 0; row < FF.num_rows; row++) {- let angle =- R.sin(sinrange * column) * (baseAngle * R.cos(row * cosrange)) +- R.randInt(-3, 3);- field[column][row] = angle;- }- }- return field;- });- addField("seabed", function (t, field) {- let baseSize = R.random(0.4, 0.8);- let baseAngle = R.randInt(18, 26);- for (let column = 0; column < FF.num_columns; column++) {- for (let row = 0; row < FF.num_rows; row++) {- let addition = R.randInt(15, 20);- let angle = baseAngle * R.sin(baseSize * row * column + addition);- field[column][row] = 1.1 * angle * R.cos(t);- }- }- return field;- });- },-};--/**- * The Position class represents a point within a two-dimensional space, which can interact with a vector field.- * It provides methods to update the position based on the field's flow and to check whether the position is- * within certain bounds (e.g., within the field or canvas).- */-export class Position {- /**- * Constructs a new Position instance.- * @param {number} x - The initial x-coordinate.- * @param {number} y - The initial y-coordinate.- */- constructor(x, y) {- this.update(x, y);- this.plotted = 0;- }-- /**- * Updates the position's coordinates and calculates its offsets and indices within the flow field if active.- * @param {number} x - The new x-coordinate.- * @param {number} y - The new y-coordinate.- */- update(x, y) {- (this.x = x), (this.y = y);- if (FF.isActive) {- this.x_offset = this.x - FF.left_x + Matrix.trans()[0];- this.y_offset = this.y - FF.top_y + Matrix.trans()[1];- this.column_index = Math.round(this.x_offset / FF.R);- this.row_index = Math.round(this.y_offset / FF.R);- }- }-- /**- * Resets the 'plotted' property to 0.- */- reset() {- this.plotted = 0;- }-- /**- * Checks if the position is within the active flow field's bounds.- * @returns {boolean} - True if the position is within the flow field, false otherwise.- */- isIn() {- return FF.isActive- ? this.column_index >= 0 &&- this.row_index >= 0 &&- this.column_index < FF.num_columns &&- this.row_index < FF.num_rows- : this.isInCanvas();- }-- /**- * Checks if the position is within reasonable bounds (+ half canvas on each side).- * @returns {boolean} - True if the position is within bounds, false otherwise.- */- isInCanvas() {- let w = _r.width,- h = _r.height;- return (- this.x >= -w - Matrix.trans()[0] &&- this.x <= w - Matrix.trans()[0] &&- this.y >= -h - Matrix.trans()[1] &&- this.y <= h - Matrix.trans()[1]- );- }-- /**- * 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.- */- angle() {- return this.isIn() && FF.isActive- ? FF.flow_field()[this.column_index][this.row_index]- : 0;- }-- /**- * Moves the position along the flow field by a certain length.- * @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.- * @param {boolean} isFlow - Whether to use the flow field for movement.- */- moveTo(_length, _dir, _step_length = B.spacing(), isFlow = true) {- if (this.isIn()) {- let a, b;- if (!isFlow) {- a = R.cos(-_dir);- b = R.sin(-_dir);- }- for (let i = 0; i < _length / _step_length; i++) {- if (isFlow) {- let angle = this.angle();- a = R.cos(angle - _dir);- b = R.sin(angle - _dir);- }- let x_step = _step_length * a,- y_step = _step_length * b;- this.plotted += _step_length;- this.update(this.x + x_step, this.y + y_step);- }- } else {- this.plotted += _step_length;- }- }-- /**- * Plots a point to another position within the flow field, following a Plot object- * @param {Position} _plot - The Plot path object.- * @param {number} _length - The length to move towards the target position.- * @param {number} _step_length - The length of each step.- * @param {number} _scale - The scaling factor for the plotting path.- */- plotTo(_plot, _length, _step_length, _scale) {- if (this.isIn()) {- const inverse_scale = 1 / _scale;- for (let i = 0; i < _length / _step_length; i++) {- let current_angle = this.angle();- let plot_angle = _plot.angle(this.plotted);- let x_step = _step_length * R.cos(current_angle - plot_angle);- let y_step = _step_length * R.sin(current_angle - plot_angle);- this.plotted += _step_length * inverse_scale;- this.update(this.x + x_step, this.y + y_step);- }- } else {- this.plotted += _step_length / scale;- }- }-}--// =============================================================================-// Section: Brushes-// =============================================================================-/**- * The Brushes section provides tools for drawing with various brush types. Each brush- * can simulate different materials and techniques, such as spray, marker, or custom- * image stamps. The 'B' object is central to this section, storing brush properties- * and methods for applying brush strokes to the canvas.- *- * The 'B' object contains methods to control the brush, including setting the brush- * type, color, weight, and blending mode. It also handles the application of the brush- * to draw lines, flow lines, and shapes with specific behaviors defined by the brush type.- * Additionally, it provides a mechanism to clip the drawing area, ensuring brush strokes- * only appear within the defined region.- *- * Brush tips can vary from basic circles to complex patterns, with support for custom- * pressure curves, opacity control, and dynamic size adjustments to simulate natural- * drawing tools. The brush engine can create effects like variable line weight, texture,- * and color blending, emulating real-world drawing experiences.- *- * The brush system is highly customizable, allowing users to define their own brushes- * with specific behaviors and appearances. By extending the brush types and parameters,- * one can achieve a wide range of artistic styles and techniques.- */--/**- * Adjusts the global scale of brush parameters based on the provided scale factor.- * This affects the weight, vibration, and spacing of each standard brush.- *- * @param {number} _scale - The scaling factor to apply to the brush parameters.- */-export function scaleBrushes(_scale) {- for (let s of _standard_brushes) {- let params = B.list.get(s[0]).param;- (params.weight *= _scale),- (params.vibration *= _scale),- (params.spacing *= _scale);- }- _gScale = _scale;-}-let _gScale = 1;--/**- * Disables the stroke for subsequent drawing operations.- * This function sets the brush's `isActive` property to false, indicating that no stroke- * should be applied to the shapes drawn after this method is called.- */-export function noStroke() {- B.isActive = false;-}--/**- * Retrieves a list of all available brush names from the brush manager.- * @returns {Array<string>} An array containing the names of all brushes.- */-export function box() {- return Array.from(B.list.keys());-}--/**- * The B object, representing a brush, contains properties and methods to manipulate- * the brush's appearance and behavior when drawing on the canvas.- * @type {Object}- */-const B = {- isActive: true, // Indicates if the brush is active.- list: new Map(), // Stores brush definitions by name.- c: "#000000", // Current color of the brush.- w: 1, // Current weight (size) of the brush.- cr: null, // Clipping region for brush strokes.- name: "HB", // Name of the current brush.-- /**- * Calculates the tip spacing based on the current brush parameters.- * @returns {number} The calculated spacing value.- */- spacing() {- this.p = this.list.get(this.name).param;- if (this.p.type === "default" || this.p.type === "spray")- return this.p.spacing / this.w;- return this.p.spacing;- },-- /**- * Initializes the drawing state with the given parameters.- * @param {number} x - The x-coordinate of the starting point.- * @param {number} y - The y-coordinate of the starting point.- * @param {number} length - The length of the line to draw.- * @param {boolean} flow - Flag indicating if the line should follow the vector-field.- * @param {Object|boolean} plot - The shape object to be used for plotting, or false if not plotting a shape.- */- initializeDrawingState(x, y, length, flow, plot) {- this.position = new Position(x, y);- this.length = length;- this.flow = flow;- this.plot = plot;- if (plot) plot.calcIndex(0);- },-- /**- * Executes the drawing operation for lines or shapes.- * @param {number} angle_scale - The angle or scale to apply during drawing.- * @param {boolean} isPlot - Flag indicating if the operation is plotting a shape.- */- draw(angle_scale, isPlot) {- if (!isPlot) this.dir = angle_scale;- this.pushState();- const st = this.spacing();- const total_steps = isPlot- ? Math.round((this.length * angle_scale) / st)- : Math.round(this.length / st);- for (let steps = 0; steps < total_steps; steps++) {- this.tip();- if (isPlot) {- this.position.plotTo(this.plot, st, st, angle_scale);- } else {- this.position.moveTo(st, angle_scale, st, this.flow);- }- }- this.popState();- },-- /**- * Executes the drawing operation for a single tip.- * @param {number} pressure - The desired pressure value.- */- drawTip(pressure) {- this.pushState(true);- this.tip(pressure);- this.popState(true);- },-- /**- * Sets up the environment for a brush stroke.- */- pushState(isTip = false) {- this.p = this.list.get(this.name).param;- // Pressure values for the stroke- if (!isTip) {- this.a = this.p.pressure.type !== "custom" ? R.random(-1, 1) : 0;- this.b = this.p.pressure.type !== "custom" ? R.random(1, 1.5) : 0;- this.cp =- this.p.pressure.type !== "custom"- ? R.random(3, 3.5)- : R.random(-0.2, 0.2);- const [min, max] = this.p.pressure.min_max;- this.min = min;- this.max = max;- }- // Blend Mode- this.c = _r.color(this.c);- // Select mask buffer for blend mode- this.mask = this.p.blend- ? this.p.type === "image"- ? Mix.masks[1]- : Mix.masks[0]- : Mix.masks[2];- Matrix.trans();- // Set the blender- this.mask.push();- this.mask.noStroke();- this.p.type === "image"- ? this.mask.translate(Matrix.translation[0], Matrix.translation[1])- : this.mask.translate(- Matrix.translation[0] + _r.width / 2,- Matrix.translation[1] + _r.height / 2- );- this.mask.rotate(-Matrix.rotation);- this.mask.scale(_curScale);- if (this.p.blend) {- Mix.watercolor = false;- if (this.p.type !== "image") Mix.blend(this.c);- else Mix.blend(this.c, false, true);- if (!isTip) this.markerTip();- }- this.alpha = this.calculateAlpha(); // Calcula Alpha- this.applyColor(this.alpha); // Apply Color- },-- /**- * Restores the drawing state after a brush stroke is completed.- */- popState(isTip = false) {- if (this.p.blend && !isTip) this.markerTip();- this.mask.pop();- },-- /**- * Draws the tip of the brush based on the current pressure and position.- * @param {number} pressure - The desired pressure value.- */- tip(custom_pressure = false) {- let pressure = custom_pressure ? custom_pressure : this.calculatePressure(); // Calculate Pressure- if (this.isInsideClippingArea()) {- // Check if it's inside clipping area- switch (- this.p.type // Draw different tip types- ) {- case "spray":- this.drawSpray(pressure);- break;- case "marker":- this.drawMarker(pressure);- break;- case "custom":- case "image":- this.drawCustomOrImage(pressure, this.alpha);- break;- default:- this.drawDefault(pressure);- break;- }- }- },-- /**- * Calculates the pressure for the current position in the stroke.- * @returns {number} The calculated pressure value.- */- calculatePressure() {- return this.plot- ? this.simPressure() * this.plot.pressure(this.position.plotted)- : this.simPressure();- },-- /**- * Simulates brush pressure based on the current position and brush parameters.- * @returns {number} The simulated pressure value.- */- simPressure() {- if (this.p.pressure.type === "custom") {- return R.map(- this.p.pressure.curve(this.position.plotted / this.length) + this.cp,- 0,- 1,- this.min,- this.max,- true- );- }- return this.gauss();- },-- /**- * Generates a Gaussian distribution value for the pressure calculation.- * @param {number} a - Center of the Gaussian bell curve.- * @param {number} b - Width of the Gaussian bell curve.- * @param {number} c - Shape of the Gaussian bell curve.- * @param {number} min - Minimum pressure value.- * @param {number} max - Maximum pressure value.- * @returns {number} The calculated Gaussian value.- */- gauss(- a = 0.5 + B.p.pressure.curve[0] * B.a,- b = 1 - B.p.pressure.curve[1] * B.b,- c = B.cp,- min = B.min,- max = B.max- ) {- return R.map(- 1 /- (1 +- Math.pow(- Math.abs(- (this.position.plotted - a * this.length) /- ((b * this.length) / 2)- ),- 2 * c- )),- 0,- 1,- min,- max- );- },-- /**- * Calculates the alpha (opacity) level for the brush stroke based on pressure.- * @param {number} pressure - The current pressure value.- * @returns {number} The calculated alpha value.- */- calculateAlpha() {- let opacity =- this.p.type !== "default" && this.p.type !== "spray"- ? this.p.opacity / this.w- : this.p.opacity;- return opacity;- },-- /**- * Applies the current color and alpha to the renderer.- * @param {number} alpha - The alpha (opacity) level to apply.- */- applyColor(alpha) {- if (this.p.blend) {- this.mask.fill(255, 0, 0, alpha / 2);- } else {- this.c.setAlpha(alpha);- this.mask.fill(this.c);- }- },-- /**- * Checks if the current brush position is inside the defined clipping area.- * @returns {boolean} True if the position is inside the clipping area, false otherwise.- */- isInsideClippingArea() {- if (B.cr)- return (- this.position.x >= B.cr[0] &&- this.position.x <= B.cr[2] &&- this.position.y >= B.cr[1] &&- this.position.y <= B.cr[3]- );- else {- let w = 0.55 * _r.width,- h = 0.55 * _r.height;- return (- this.position.x >= -w - Matrix.trans()[0] &&- this.position.x <= w - Matrix.trans()[0] &&- this.position.y >= -h - Matrix.trans()[1] &&- this.position.y <= h - Matrix.trans()[1]- );- }- },-- /**- * Draws the spray tip of the brush.- * @param {number} pressure - The current pressure value.- */- drawSpray(pressure) {- let vibration =- this.w * this.p.vibration * pressure +- (this.w * R.gaussian() * this.p.vibration) / 3;- let sw = this.p.weight * R.random(0.9, 1.1);- const iterations = this.p.quality / pressure;- for (let j = 0; j < iterations; j++) {- let r = R.random(0.9, 1.1);- let rX = r * vibration * R.random(-1, 1);- let yRandomFactor = R.random(-1, 1);- let rVibrationSquared = Math.pow(r * vibration, 2);- let sqrtPart = Math.sqrt(rVibrationSquared - Math.pow(rX, 2));- this.mask.circle(- this.position.x + rX,- this.position.y + yRandomFactor * sqrtPart,- sw- );- }- },-- /**- * Draws the marker tip of the brush.- * @param {number} pressure - The current pressure value.- * @param {boolean} [vibrate=true] - Whether to apply vibration effect.- */- drawMarker(pressure, vibrate = true) {- let vibration = vibrate ? this.w * this.p.vibration : 0;- let rx = vibrate ? vibration * R.random(-1, 1) : 0;- let ry = vibrate ? vibration * R.random(-1, 1) : 0;- this.mask.circle(- this.position.x + rx,- this.position.y + ry,- this.w * this.p.weight * pressure- );- },-- /**- * Draws the custom or image tip of the brush.- * @param {number} pressure - The current pressure value.- * @param {number} alpha - The alpha (opacity) level to apply.- * @param {boolean} [vibrate=true] - Whether to apply vibration effect.- */- drawCustomOrImage(pressure, alpha, vibrate = true) {- this.mask.push();- let vibration = vibrate ? this.w * this.p.vibration : 0;- let rx = vibrate ? vibration * R.random(-1, 1) : 0;- let ry = vibrate ? vibration * R.random(-1, 1) : 0;- this.mask.translate(this.position.x + rx, this.position.y + ry);- this.adjustSizeAndRotation(this.w * pressure, alpha);- this.p.tip(this.mask);- this.mask.pop();- },-- /**- * Draws the default tip of the brush.- * @param {number} pressure - The current pressure value.- */- drawDefault(pressure) {- let vibration =- this.w *- this.p.vibration *- (this.p.definition +- ((1 - this.p.definition) *- R.gaussian() *- this.gauss(0.5, 0.9, 5, 0.2, 1.2)) /- pressure);- if (R.random(0, this.p.quality * pressure) > 0.4) {- this.mask.circle(- this.position.x + 0.7 * vibration * R.random(-1, 1),- this.position.y + vibration * R.random(-1, 1),- pressure * this.p.weight * R.random(0.85, 1.15)- );- }- },+// Randomness and other auxiliary functions+export { weightedRand as wRand, seed, noiseSeed } from "./core/utils.js";++// Color Blending+export { load, instance } from "./core/color.js";++// Matrix transformations, FlowField and Position Class+export {+ field,+ noField,+ addField,+ refreshField,+ listFields,+ Position,+ wiggle,+} from "./core/flowfield.js";++// Polygon and Plot classes+export { Polygon } from "./core/polygon.js";+export { Plot } from "./core/plot.js";++// Primitives+export {+ rect,+ circle,+ arc,+ beginShape,+ vertex,+ endShape,+ beginStroke,+ move,+ endStroke,+ spline,+ polygon,+} from "./core/primitives.js";++// Brushes+export {+ add,+ box,+ scaleBrushes,+ pick,+ stroke,+ strokeWeight,+ set,+ noStroke,+ clip,+ noClip,+ line,+ flowLine,+ preload,+} from "./stroke/stroke.js";- /**- * Adjusts the size and rotation of the brush tip before drawing.- * @param {number} pressure - The current pressure value.- * @param {number} alpha - The alpha (opacity) level to apply.- */- adjustSizeAndRotation(pressure, alpha) {- this.mask.scale(pressure);- if (this.p.type === "image")- this.p.blend- ? this.mask.tint(255, 0, 0, alpha / 2)- : this.mask.tint(- this.mask.red(this.c),- this.mask.green(this.c),- this.mask.blue(this.c),- alpha- );- if (this.p.rotate === "random") this.mask.rotate(R.randInt(0, 360));- else if (this.p.rotate === "natural") {- let angle =- (this.plot ? -this.plot.angle(this.position.plotted) : -this.dir) +- (this.flow ? this.position.angle() : 0);- this.mask.rotate(angle);- }- },-- /**- * Draws the marker tip with a blend effect.- */- markerTip() {- if (this.isInsideClippingArea()) {- let pressure = this.calculatePressure();- let alpha = this.calculateAlpha(pressure);- this.mask.fill(255, 0, 0, alpha / 1.5);- if (B.p.type === "marker") {- for (let s = 1; s < 5; s++) {- this.drawMarker((pressure * s) / 5, false);- }- } else if (B.p.type === "custom" || B.p.type === "image") {- for (let s = 1; s < 5; s++) {- this.drawCustomOrImage((pressure * s) / 5, alpha, false);- }- }- }- },-};--/**- * Adds a new brush with the specified parameters to the brush list.- * @param {string} name - The unique name for the new brush.- * @param {BrushParameters} params - The parameters defining the brush behavior and appearance.- */-export function add(a, b) {- const isBlendableType =- b.type === "marker" || b.type === "custom" || b.type === "image";- if (!isBlendableType && b.type !== "spray") b.type = "default";- if (b.type === "image") {- T.add(b.image.src);- b.tip = () =>- B.mask.image(- T.tips.get(B.p.image.src),- -B.p.weight / 2,- -B.p.weight / 2,- B.p.weight,- B.p.weight- );- }- b.blend = (isBlendableType && b.blend !== false) || b.blend ? true : false;- B.list.set(a, { param: b, colors: [], buffers: [] });-}--/**- * Sets the current brush with the specified name, color, and weight.- * @param {string} brushName - The name of the brush to set as current.- * @param {string|p5.Color} color - The color to set for the brush.- * @param {number} weight - The weight (size) to set for the brush.- */-export function set(brushName, color, weight = 1) {- pick(brushName);- B.c = color;- B.w = weight;- B.isActive = true;-}--/**- * Sets only the current brush type based on the given name.- * @param {string} brushName - The name of the brush to set as current.- */-export function pick(brushName) {- B.name = brushName;-}--/**- * Sets the color of the current brush.- * @param {number|string|p5.Color} r - The red component of the color, a CSS color string, or a p5.Color object.- * @param {number} [g] - The green component of the color.- * @param {number} [b] - The blue component of the color.- */-export function stroke(r, g, b) {- if (arguments.length > 0) B.c = arguments.length < 2 ? r : [r, g, b];- B.isActive = true;-}--/**- * Sets the weight (size) of the current brush.- * @param {number} weight - The weight to set for the brush.- */-export function strokeWeight(weight) {- B.w = weight;-}--/**- * Defines a clipping region for the brush strokes.- * @param {number[]} clippingRegion - An array defining the clipping region as [x1, y1, x2, y2].- */-export function clip(clippingRegion) {- B.cr = clippingRegion;-}--/**- * Disables clipping region.- */-export function noClip() {- B.cr = null;-}--/**- * Draws a line using the current brush from (x1, y1) to (x2, y2).- * @param {number} x1 - The x-coordinate of the start point.- * @param {number} y1 - The y-coordinate of the start point.- * @param {number} x2 - The x-coordinate of the end point.- * @param {number} y2 - The y-coordinate of the end point.- */-export function line(x1, y1, x2, y2) {- _ensureReady();- let d = R.dist(x1, y1, x2, y2);- if (d == 0) return;- B.initializeDrawingState(x1, y1, d, false, false);- let angle = _calculateAngle(x1, y1, x2, y2);- B.draw(angle, false);-}--/**- * Draws a flow line with the current brush from a starting point in a specified direction.- * @param {number} x - The x-coordinate of the starting point.- * @param {number} y - The y-coordinate of the starting point.- * @param {number} length - The length of the line to draw.- * @param {number} dir - The direction in which to draw the line. Angles measured anticlockwise from the x-axis- */-export function flowLine(x, y, length, dir) {- _ensureReady();- B.initializeDrawingState(x, y, length, true, false);- B.draw(R.toDegrees(dir), false);-}--/**- * Draws a predefined shape/plot with a flowing brush stroke.- * @param {Object} p - An object representing the shape to draw.- * @param {number} x - The x-coordinate of the starting position to draw the shape.- * @param {number} y - The y-coordinate of the starting position to draw the shape.- * @param {number} scale - The scale at which to draw the shape.- */-export function plot(p, x, y, scale) {- _ensureReady();- B.initializeDrawingState(x, y, p.length, true, p);- B.draw(scale, true);-}--// =============================================================================-// Section: Loading Custom Image Tips-// =============================================================================-/**- * This section defines the functionality for managing the loading and processing of image tips.- * Images are loaded from specified source URLs, converted to a white tint for visual effects,- * and then stored for future use. It includes methods to add new images, convert their color- * scheme, and integrate them into the p5.js graphics library.- */--/**- * A utility object for loading images, converting them to a red tint, and managing their states.- */-const T = {- tips: new Map(),-- /**- * Adds an image to the tips Map and sets up loading and processing.- *- * @param {string} src - The source URL of the image to be added and processed.- */- add(src) {- // Initially set the source as not processed- this.tips.set(src, false);- },-- /**- * Converts the given image to a white tint by setting all color channels to white and adjusting the alpha channel.- *- * @param {Image} image - The image to be converted.- */- imageToWhite(image) {- image.loadPixels();- // Modify the image data to create a white tint effect- for (let i = 0; i < 4 * image.width * image.height; i += 4) {- // Calculate the average for the grayscale value- let average =- (image.pixels[i] + image.pixels[i + 1] + image.pixels[i + 2]) / 3;- // Set all color channels to white- image.pixels[i] = image.pixels[i + 1] = image.pixels[i + 2] = 255;- // Adjust the alpha channel to the inverse of the average, creating the white tint effect- image.pixels[i + 3] = 255 - average;- }- image.updatePixels();- },- /**- * Loads all processed images into the p5.js environment.- * If no images are in the tips Map, logs a warning message.- */- load() {- for (let key of this.tips.keys()) {- let _r = _isInstanced ? _inst : window.self;- let image = _r.loadImage(key, () => T.imageToWhite(image));- this.tips.set(key, image);- }- },-};--// =============================================================================// Section: Hatching-// =============================================================================-/**- * The Hatching section of the code is responsible for creating and drawing hatching patterns.- * Hatching involves drawing closely spaced parallel lines.- */--/**- * Activates hatching for subsequent geometries, with the given params.- * @param {number} dist - The distance between hatching lines.- * @param {number} angle - The angle at which hatching lines are drawn.- * @param {Object} options - An object containing optional parameters to affect the hatching style:- * - rand: Introduces randomness to the line placement.- * - continuous: Connects the end of a line with the start of the next.- * - gradient: Changes the distance between lines to create a gradient effect.- * Defaults to {rand: false, continuous: false, gradient: false}.- */-export function hatch(- dist = 5,- angle = 45,- options = { rand: false, continuous: false, gradient: false }-) {- H.isActive = true;- H.hatchingParams = [dist, angle, options];-}--/**- * Sets the brush type, color, and weight for subsequent hatches.- * If this function is not called, hatches will use the parameters from stroke operations.- * @param {string} brushName - The name of the brush to set as current.- * @param {string|p5.Color} color - The color to set for the brush.- * @param {number} weight - The weight (size) to set for the brush.- */-export function setHatch(brush, color = "black", weight = 1) {- H.hatchingBrush = [brush, color, weight];-}--/**- * Disables hatching for subsequent shapes- */-export function noHatch() {- H.isActive = false;- H.hatchingBrush = false;-}--/**- * Object to hold the current hatch state and to perform hatch calculation- */-const H = {- isActive: false,- hatchingParams: [5, 45, {}],- hatchingBrush: false,+export {+ hatch,+ hatchStyle,+ noHatch,+ createHatch as hatchArray,+} from "./hatch/hatch.js";- /**- * Creates a hatching pattern across the given polygons.- *- * @param {Array|Object} polygons - A single polygon or an array of polygons to apply the hatching.- */- hatch(polygons) {- let dist = H.hatchingParams[0];- let angle = H.hatchingParams[1];- let options = H.hatchingParams[2];+// Fill+export { fill, noFill, fillTexture, fillBleed } from "./fill/fill.js";- // Save current stroke state- let strokeColor = B.c,- strokeBrush = B.name,- strokeWeight = B.w,- strokeActive = B.isActive;- // Change state if hatch has been set to different params than stroke- if (H.hatchingBrush)- set(H.hatchingBrush[0], H.hatchingBrush[1], H.hatchingBrush[2]);+// p5 addon registration+import { Mix } from "./core/color.js";+import { push as brushPush, pop as brushPop } from "./core/save.js";- // Transform to degrees and between 0-180- angle = R.toDegrees(angle) % 180;+function registerAddon(_p5, fn, lifecycles) {+ lifecycles.postsetup = () => Mix.blend(false, true);+ lifecycles.postdraw = () => Mix.blend(false, true);- // Calculate the bounding area of the provided polygons- let minX = Infinity,- maxX = -Infinity,- minY = Infinity,- maxY = -Infinity;- let processPolygonPoints = (p) => {- for (let a of p.a) {- // (process points of a single polygon to find bounding area)- minX = a[0] < minX ? a[0] : minX;- maxX = a[0] > maxX ? a[0] : maxX;- minY = a[1] < minY ? a[1] : minY;- maxY = a[1] > maxY ? a[1] : maxY;- }- };+ const _push = fn.push;+ const _pop = fn.pop;- // Ensure polygons is an array and find overall bounding area- if (!Array.isArray(polygons)) {- polygons = [polygons];- }- for (let p of polygons) {- processPolygonPoints(p);- }-- // Create a bounding polygon- let ventana = new Polygon([- [minX, minY],- [maxX, minY],- [maxX, maxY],- [minX, maxY],- ]);-- // Set initial values for line generation- let startY = angle <= 90 && angle >= 0 ? minY : maxY;- let gradient = options.gradient- ? R.map(options.gradient, 0, 1, 1, 1.1, true)- : 1;- let dots = [];- let i = 0;- let dist1 = dist;- let linea = (i) => {- return {- point1: {- x: minX + dist1 * i * R.cos(-angle + 90),- y: startY + dist1 * i * R.sin(-angle + 90),- },- point2: {- x: minX + dist1 * i * R.cos(-angle + 90) + R.cos(-angle),- y: startY + dist1 * i * R.sin(-angle + 90) + R.sin(-angle),- },- };- };-- // Generate lines and calculate intersections with polygons- // Loop through the lines based on the distance and angle to calculate intersections with the polygons- // The loop continues until a line does not intersect with the bounding window polygon- // Each iteration accounts for the gradient effect by adjusting the distance between lines- while (ventana.intersect(linea(i)).length > 0) {- let tempArray = [];- for (let p of polygons) {- tempArray.push(p.intersect(linea(i)));- }- dots[i] = tempArray- .flat()- .sort((a, b) => (a.x === b.x ? a.y - b.y : a.x - b.x));- dist1 *= gradient;- i++;- }-- // Filter out empty arrays to avoid drawing unnecessary lines- let gdots = [];- for (let dd of dots) {- if (typeof dd[0] !== "undefined") {- gdots.push(dd);- }- }-- // Draw the hatching lines using the calculated intersections- // If the 'rand' option is enabled, add randomness to the start and end points of the lines- // If the 'continuous' option is set, connect the end of one line to the start of the next- let r = options.rand ? options.rand : 0;- for (let j = 0; j < gdots.length; j++) {- let dd = gdots[j];- let shouldDrawContinuousLine = j > 0 && options.continuous;- for (let i = 0; i < dd.length - 1; i += 2) {- if (r !== 0) {- dd[i].x += r * dist * R.random(-10, 10);- dd[i].y += r * dist * R.random(-10, 10);- dd[i + 1].x += r * dist * R.random(-10, 10);- dd[i + 1].y += r * dist * R.random(-10, 10);- }- line(dd[i].x, dd[i].y, dd[i + 1].x, dd[i + 1].y);- if (shouldDrawContinuousLine) {- line(gdots[j - 1][1].x, gdots[j - 1][1].y, dd[i].x, dd[i].y);- }- }- }-- // Change state back to previous- set(strokeBrush, strokeColor, strokeWeight);- B.isActive = strokeActive;- },-};--export const hatchArray = H.hatch;--// =============================================================================-// Section: Polygon management. Basic geometries-// =============================================================================-/**- * This section includes the Polygon class for managing polygons and functions for drawing basic geometries- * like rectangles and circles. It provides methods for creating, intersecting, drawing, and filling polygons,- * as well as hatching them with a given distance and angle. Additional functions leverage the Polygon class- * to draw rectangles with options for randomness and different drawing modes.- */--/**- * Represents a polygon with a set of vertices.- */-export class Polygon {- /**- * Constructs the Polygon object from an array of points.- *- * @param {Array} pointsArray - An array of points, where each point is an array of two numbers [x, y].- */- constructor(array, bool = false) {- this.a = array;- this.vertices = array.map((a) => ({ x: a[0], y: a[1] }));- if (bool) this.vertices = array;- this.sides = this.vertices.map((v, i, arr) => [- v,- arr[(i + 1) % arr.length],- ]);- }- /**- * Intersects a given line with the polygon, returning all intersection points.- *- * @param {Object} line - The line to intersect with the polygon, having two properties 'point1' and 'point2'.- * @returns {Array} An array of intersection points (each with 'x' and 'y' properties) or an empty array if no intersections.- */- intersect(line) {- // Check if the result has been cached- let cacheKey = `${line.point1.x},${line.point1.y}-${line.point2.x},${line.point2.y}`;- if (this._intersectionCache && this._intersectionCache[cacheKey]) {- return this._intersectionCache[cacheKey];- }- let points = [];- for (let s of this.sides) {- let intersection = _intersectLines(line.point1, line.point2, s[0], s[1]);- if (intersection !== false) {- points.push(intersection);- }- }- // Cache the result- if (!this._intersectionCache) this._intersectionCache = {};- this._intersectionCache[cacheKey] = points;+ fn.push = function () {+ _push.call(this);+ brushPush();+ };- return points;- }- /**- * Draws the polygon by iterating over its sides and drawing lines between the vertices.- */- draw(_brush = false, _color, _weight) {- let curState = B.isActive;- if (_brush) set(_brush, _color, _weight);- if (B.isActive) {- _ensureReady();- for (let s of this.sides) {- line(s[0].x, s[0].y, s[1].x, s[1].y);- }- }- B.isActive = curState;- }- /**- * Fills the polygon using the current fill state.- */- fill(_color = false, _opacity, _bleed, _texture, _border, _direction) {- let curState = F.isActive;- if (_color) {- fill(_color, _opacity);- bleed(_bleed, _direction);- fillTexture(_texture, _border);- }- if (F.isActive) {- _ensureReady();- F.fill(this);- }- F.isActive = curState;- }- /**- * Creates hatch lines across the polygon based on a given distance and angle.- */- hatch(_dist = false, _angle, _options) {- let curState = H.isActive;- if (_dist) hatch(_dist, _angle, _options);- if (H.isActive) {- _ensureReady();- H.hatch(this);- }- H.isActive = curState;- }-- erase(c = false, a = E.a) {- if (E.isActive || c) {- Mix.masks[2].push();- Mix.masks[2].noStroke();- let ccc = _r.color(c ? c : E.c);- ccc.setAlpha(a);- Mix.masks[2].fill(ccc);- Mix.masks[2].beginShape();- for (let p of this.vertices) {- Mix.masks[2].vertex(p.x, p.y);- }- Mix.masks[2].endShape(_r.CLOSE);- Mix.masks[2].pop();- }- }-- show() {- this.fill();- this.hatch();- this.draw();- this.erase();- }-}--/**- * Creates a Polygon from a given array of points and performs drawing and filling- * operations based on active states.- *- * @param {Array} pointsArray - An array of points where each point is an array of two numbers [x, y].- */-export function polygon(pointsArray) {- // Create a new Polygon instance- let polygon = new Polygon(pointsArray);- polygon.show();+ fn.pop = function () {+ _pop.call(this);+ brushPop();+ };}-/**- * Draws a rectangle on the canvas and fills it with the current fill color.- *- * @param {number} x - The x-coordinate of the rectangle.- * @param {number} y - The y-coordinate of the rectangle.- * @param {number} w - The width of the rectangle.- * @param {number} h - The height of the rectangle.- * @param {boolean} [mode=CORNER] - If CENTER, the rectangle is drawn centered at (x, y).- */-export function rect(x, y, w, h, mode = _r.CORNER) {- if (mode == _r.CENTER) (x = x - w / 2), (y = y - h / 2);- if (FF.isActive) {- beginShape(0);- vertex(x, y);- vertex(x + w, y);- vertex(x + w, y + h);- vertex(x, y + h);- endShape(_r.CLOSE);- } else {- let p = new Polygon([- [x, y],- [x + w, y],- [x + w, y + h],- [x, y + h],- ]);- p.show();- }-}--// =============================================================================-// Section: Shape, Stroke, and Spline. Plot System-// =============================================================================-/**- * This section defines the functionality for creating and managing plots, which are used to draw complex shapes,- * strokes, and splines on a canvas. It includes classes and functions to create plots of type "curve" or "segments",- * manipulate them with operations like adding segments and applying rotations, and render them as visual elements- * like polygons or strokes. The spline functionality allows for smooth curve creation using control points with- * specified curvature, which can be rendered directly or used as part of more complex drawings.- */--/**- * The Plot class is central to the plot system, serving as a blueprint for creating and manipulating a variety- * of shapes and paths. It manages a collection of segments, each defined by an angle, length, and pressure,- * allowing for intricate designs such as curves and custom strokes. Plot instances can be transformed by rotation,- * and their visual representation can be controlled through pressure and angle calculations along their length.- */-export class Plot {- /**- * Creates a new Plot.- * @param {string} _type - The type of plot, "curve" or "segments"- */- constructor(_type) {- (this.segments = []), (this.angles = []), (this.pres = []);- this.type = _type;- this.dir = 0;- this.calcIndex(0);- this.pol = false;- }-- /**- * Adds a segment to the plot with specified angle, length, and pressure.- * @param {number} _a - The angle of the segment.- * @param {number} _length - The length of the segment.- * @param {number} _pres - The pressure of the segment.- * @param {boolean} _degrees - Whether the angle is in degrees.- */- addSegment(_a = 0, _length = 0, _pres = 1, _degrees = false) {- // Remove the last angle if the angles array is not empty- if (this.angles.length > 0) {- this.angles.splice(-1);- }- // Convert to degrees and normalize between 0 and 360 degrees- _a = _degrees ? ((_a % 360) + 360) % 360 : R.toDegrees(_a);- // Store the angle, pressure, and segment length- this.angles.push(_a);- this.pres.push(_pres);- this.segments.push(_length);- // Calculate the total length of the plot- this.length = this.segments.reduce((partialSum, a) => partialSum + a, 0);- // Push the angle again to prepare for the next segment- this.angles.push(_a);- }-- /**- * Finalizes the plot by setting the last angle and pressure.- * @param {number} _a - The final angle of the plot.- * @param {number} _pres - The final pressure of the plot.- * @param {boolean} _degrees - Whether the angle is in degrees.- */- endPlot(_a = 0, _pres = 1, _degrees = false) {- // Convert angle to degrees if necessary- _a = _degrees ? ((_a % 360) + 360) % 360 : R.toDegrees(_a);- // Replace the last angle with the final angle- this.angles.splice(-1);- this.angles.push(_a);- // Store the final pressure- this.pres.push(_pres);- }-- /**- * Rotates the entire plot by a given angle.- * @param {number} _a - The angle to rotate the plot.- */- rotate(_a) {- this.dir = R.toDegrees(_a);- }-- /**- * Calculates the pressure at a given distance along the plot.- * @param {number} _d - The distance along the plot.- * @returns {number} - The calculated pressure.- */- pressure(_d) {- // If the distance exceeds the plot length, return the last pressure- if (_d > this.length) return this.pres[this.pres.length - 1];- // Otherwise, calculate the pressure using the curving function- return this.curving(this.pres, _d);- }-- /**- * Calculates the angle at a given distance along the plot.- * @param {number} _d - The distance along the plot.- * @returns {number} - The calculated angle.- */- angle(_d) {- // If the distance exceeds the plot length, return the last angle- if (_d > this.length) return this.angles[this.angles.length - 1];- // Calculate the index for the given distance- this.calcIndex(_d);- // Return the angle, adjusted for the plot type and direction- return this.type === "curve"- ? this.curving(this.angles, _d) + this.dir- : this.angles[this.index] + this.dir;- }-- /**- * Interpolates values between segments for smooth transitions.- * @param {Array<number>} array - The array to interpolate within.- * @param {number} _d - The distance along the plot.- * @returns {number} - The interpolated value.- */- curving(array, _d) {- let map0 = array[this.index];- let map1 = array[this.index + 1];- if (typeof map1 == "undefined") {- map1 = map0;- }- if (Math.abs(map1 - map0) > 180) {- if (map1 > map0) {- map1 = -(360 - map1);- } else {- map0 = -(360 - map0);- }- }- return R.map(- _d - this.suma,- 0,- this.segments[this.index],- map0,- map1,- true- );- }-- /**- * Calculates the current index of the plot based on the distance.- * @param {number} _d - The distance along the plot.- */- calcIndex(_d) {- (this.index = -1), (this.suma = 0);- let d = 0;- while (d <= _d) {- this.suma = d;- d += this.segments[this.index + 1];- this.index++;- }- return this.index;- }-- /**- * Generates a polygon based on the plot.- * @param {number} _x - The x-coordinate for the starting point of the polygon.- * @param {number} _y - The y-coordinate for the starting point of the polygon.- * @returns {Polygon} - The generated polygon.- */- genPol(_x, _y, _scale = 1, isHatch = false) {- _ensureReady(); // Ensure that the drawing environment is prepared- const step = 0.5;- const vertices = [];- const numSteps = Math.round(this.length / step);- const pos = new Position(_x, _y);- let side = isHatch ? 0.15 : F.bleed_strength * 3;- let pside = 0;- let prevIdx = 0;- for (let i = 0; i < numSteps; i++) {- pos.plotTo(this, step, step, 1);- let idx = this.calcIndex(pos.plotted);- pside += step;- if (- (pside >= this.segments[idx] * side * R.random(0.7, 1.3) ||- idx >= prevIdx) &&- pos.x- ) {- vertices.push([pos.x, pos.y]);- pside = 0;- if (idx >= prevIdx) prevIdx++;- }- }- return new Polygon(vertices);- }-- /**- * Draws the plot on the canvas.- * @param {number} x - The x-coordinate to draw at.- * @param {number} y - The y-coordinate to draw at.- * @param {number} scale - The scale to draw with.- */- draw(x, y, scale) {- if (B.isActive) {- _ensureReady(); // Ensure that the drawing environment is prepared- if (this.origin) (x = this.origin[0]), (y = this.origin[1]), (scale = 1);- plot(this, x, y, scale);- }- }-- /**- * Fill the plot on the canvas.- * @param {number} x - The x-coordinate to draw at.- * @param {number} y - The y-coordinate to draw at.- */- fill(x, y, scale) {- if (F.isActive) {- _ensureReady(); // Ensure that the drawing environment is prepared- if (this.origin) (x = this.origin[0]), (y = this.origin[1]), (scale = 1);- this.pol = this.genPol(x, y, scale);- this.pol.fill();- }- }-- /**- * Hatch the plot on the canvas.- * @param {number} x - The x-coordinate to draw at.- * @param {number} y - The y-coordinate to draw at.- */- hatch(x, y, scale) {- if (H.isActive) {- _ensureReady(); // Ensure that the drawing environment is prepared- if (this.origin) (x = this.origin[0]), (y = this.origin[1]), (scale = 1);- this.pol = this.genPol(x, y, scale, true);- this.pol.hatch();- }- }-- erase(x, y, scale) {- if (E.isActive) {- if (this.origin) (x = this.origin[0]), (y = this.origin[1]), (scale = 1);- this.pol = this.genPol(x, y, scale, true);- Mix.masks[2].push();- Mix.masks[2].noStroke();- let ccc = _r.color(E.c);- ccc.setAlpha(E.a);- Mix.masks[2].fill(ccc);- Mix.masks[2].beginShape();- for (let p of this.pol.vertices) {- Mix.masks[2].vertex(p.x, p.y);- }- Mix.masks[2].endShape(_r.CLOSE);- Mix.masks[2].pop();- }- }-- show(x, y, scale = 1) {- this.draw(x, y, scale);- this.fill(x, y, scale);- this.hatch(x, y, scale);- this.erase(x, y, scale);- }-}--/**- * Draws a circle on the canvas and fills it with the current fill color.- *- * @param {number} x - The x-coordinate of the center of the circle.- * @param {number} y - The y-coordinate of the center of the circle.- * @param {number} radius - The radius of the circle.- * @param {boolean} [r=false] - If true, applies a random factor to the radius for each segment.- */-export function circle(x, y, radius, r = false) {- _ensureReady();- // Create a new Plot instance for a curve shape- let p = new Plot("curve");- // Calculate the length of the arc for each quarter of the circle- let l = (Math.PI * radius) / 2;- // Initialize the angle for the drawing segments- let angle = R.random(0, 360);- // Define a function to optionally add randomness to the segment length- let rr = () => (r ? R.random(-1, 1) : 0);- // Add segments for each quarter of the circle with optional randomness- p.addSegment(0 + angle + rr(), l + rr(), 1, true);- p.addSegment(-90 + angle + rr(), l + rr(), 1, true);- p.addSegment(-180 + angle + rr(), l + rr(), 1, true);- p.addSegment(-270 + angle + rr(), l + rr(), 1, true);- // Optionally add a random final angle for the last segment- let angle2 = r ? R.randInt(-5, 5) : 0;- if (r) p.addSegment(0 + angle, angle2 * (Math.PI / 180) * radius, true);- // Finalize the plot- p.endPlot(angle2 + angle, 1, true);- // Fill / hatch / draw- let o = [x - radius * R.sin(angle), y - radius * R.cos(-angle)];- p.show(o[0], o[1], 1);-}--export function arc(x, y, radius, start, end) {- _ensureReady();- // Create a new Plot instance for a curve shape- let p = new Plot("curve");- // Calculate start angle and end angle- let a1 = 270 - R.toDegrees(start),- a2 = 270 - R.toDegrees(end);- // Calculate length arc- let arcAngle = R.toDegrees(end - start);- let l = (Math.PI * radius * arcAngle) / 180;- // Add segments to plot- p.addSegment(a1, l, 1, true);- p.endPlot(a2, 1, true);- // Draw from starting point- p.draw(x + radius * R.cos(-a1 - 90), y + radius * R.sin(-a1 - 90), 1);-}--// Holds the array of vertices for the custom shape being defined. Each vertex includes position and optional pressure.-let _strokeArray = false;-// Holds options for the stroke, such as curvature, that can influence the shape's rendering.-let _strokeOption;--/**- * Starts recording vertices for a custom shape. Optionally, a curvature can be defined.- * @param {number} [curvature] - From 0 to 1. Defines the curvature for the vertices being recorded (optional).- */-export function beginShape(curvature = 0) {- _strokeOption = R.constrain(curvature, 0, 1); // Set the curvature option for the shape- _strokeArray = []; // Initialize the array to store vertices-}--/**- * Records a vertex in the custom shape being defined between beginShape and endShape.- * @param {number} x - The x-coordinate of the vertex.- * @param {number} y - The y-coordinate of the vertex.- * @param {number} [pressure] - The pressure at the vertex (optional).- */-export function vertex(x, y, pressure) {- _strokeArray.push([x, y, pressure]); // Add the vertex to the array-}--/**- * Finishes recording vertices for a custom shape and either closes it or leaves it open.- * It also triggers the drawing of the shape with the active stroke(), fill() and hatch() states.- * @param {string} [a] - An optional argument to close the shape if set to _r.CLOSE.- */-export function endShape(a) {- _ensureReady();- if (a === _r.CLOSE) {- _strokeArray.push(_strokeArray[0]); // Close the shape by connecting the last vertex to the first- _strokeArray.push(_strokeArray[1]);- }- // Create a new Plot with the recorded vertices and curvature option- let plot =- _strokeOption == 0 && !FF.isActive- ? new Polygon(_strokeArray)- : _createSpline(- _strokeArray,- _strokeOption,- a === _r.CLOSE ? true : false- );- plot.show();- _strokeArray = false; // Clear the array after the shape has been drawn-}--/**- * Begins a new stroke with a given type and starting position. This initializes- * a new Plot to record the stroke's path.- * @param {string} type - The type of the stroke, which defines the kind of Plot to create.- * @param {number} x - The x-coordinate of the starting point of the stroke.- * @param {number} y - The y-coordinate of the starting point of the stroke.- */-export function beginStroke(type, x, y) {- _strokeOption = [x, y]; // Store the starting position for later use- _strokeArray = new Plot(type); // Initialize a new Plot with the specified type-}--/**- * Adds a segment to the stroke with a given angle, length, and pressure. This function- * is called between beginStroke and endStroke to define the stroke's path.- * @param {number} angle - The initial angle of the segment, relative to the canvas.- * @param {number} length - The length of the segment.- * @param {number} pressure - The pressure at the start of the segment, affecting properties like width.- */-export function segment(angle, length, pressure) {- _strokeArray.addSegment(angle, length, pressure); // Add the new segment to the Plot-}--/**- * Completes the stroke path and triggers the rendering of the stroke.- * @param {number} angle - The angle of the curve at the last point of the stroke path.- * @param {number} pressure - The pressure at the end of the stroke.- */-export function endStroke(angle, pressure) {- _strokeArray.endPlot(angle, pressure); // Finalize the Plot with the end angle and pressure- _strokeArray.draw(_strokeOption[0], _strokeOption[1], 1); // Draw the stroke using the stored starting position- _strokeArray = false; // Clear the _strokeArray to indicate the end of this stroke-}--/**- * Creates a new Plot object.- * @param {Array<Array<number>>} array_points - An array of points defining the spline curve.- * @param {number} [curvature=0.5] - The curvature of the spline curve, beterrn 0 and 1. A curvature of 0 will create a series of straight segments.- */-function _createSpline(array_points, curvature = 0.5, _close = false) {- // Initialize the plot type based on curvature- let plotType = curvature === 0 ? "segments" : "curve";- let p = new Plot(plotType);-- // Proceed only if there are points provided- if (array_points && array_points.length > 0) {- // Add each segment to the plot- let done = 0;- let pep, tep, pep2;- for (let i = 0; i < array_points.length - 1; i++) {- if (curvature > 0 && i < array_points.length - 2) {- // Get the current and next points- let p1 = array_points[i],- p2 = array_points[i + 1],- p3 = array_points[i + 2];- // Calculate distances and angles between points- let d1 = R.dist(p1[0], p1[1], p2[0], p2[1]),- d2 = R.dist(p2[0], p2[1], p3[0], p3[1]);- let a1 = _calculateAngle(p1[0], p1[1], p2[0], p2[1]),- a2 = _calculateAngle(p2[0], p2[1], p3[0], p3[1]);- // Calculate curvature based on the minimum distance- let dd = curvature * Math.min(Math.min(d1, d2), 0.5 * Math.min(d1, d2)),- dmax = Math.max(d1, d2);- let s1 = d1 - dd,- s2 = d2 - dd;- // If the angles are approximately the same, create a straight segment- if (Math.floor(a1) === Math.floor(a2)) {- let temp = _close ? (i === 0 ? 0 : d1 - done) : d1 - done;- let temp2 = _close ? (i === 0 ? 0 : d2 - pep2) : d2;- p.addSegment(a1, temp, p1[2], true);- if (i === array_points.length - 3)- p.addSegment(a2, temp2, p2[2], true);- done = 0;- if (i === 0)- (pep = d1), (pep2 = dd), (tep = array_points[1]), (done = 0);- } else {- // If the angles are not the same, create curves, etc (this is a too complex...)- let point1 = {- x: p2[0] - dd * R.cos(-a1),- y: p2[1] - dd * R.sin(-a1),- };- let point2 = {- x: point1.x + dmax * R.cos(-a1 + 90),- y: point1.y + dmax * R.sin(-a1 + 90),- };- let point3 = {- x: p2[0] + dd * R.cos(-a2),- y: p2[1] + dd * R.sin(-a2),- };- let point4 = {- x: point3.x + dmax * R.cos(-a2 + 90),- y: point3.y + dmax * R.sin(-a2 + 90),- };- let int = _intersectLines(point1, point2, point3, point4, true);- let radius = R.dist(point1.x, point1.y, int.x, int.y);- let disti = R.dist(point1.x, point1.y, point3.x, point3.y) / 2;- let a3 = 2 * Math.asin(disti / radius) * (180 / Math.PI);- let s3 = (2 * Math.PI * radius * a3) / 360;- let temp = _close ? (i === 0 ? 0 : s1 - done) : s1 - done;- let temp2 =- i === array_points.length - 3 ? (_close ? pep - dd : s2) : 0;- p.addSegment(a1, temp, p1[2], true);- p.addSegment(a1, isNaN(s3) ? 0 : s3, p1[2], true);- p.addSegment(a2, temp2, p2[2], true);- done = dd;- if (i === 0) (pep = s1), (pep2 = dd), (tep = [point1.x, point1.y]);- }- if (i == array_points.length - 3) {- p.endPlot(a2, p2[2], true);- }- } else if (curvature === 0) {- // If curvature is 0, simply create segments- if (i === 0 && _close) array_points.pop();- let p1 = array_points[i],- p2 = array_points[i + 1];- let d = R.dist(p1[0], p1[1], p2[0], p2[1]);- let a = _calculateAngle(p1[0], p1[1], p2[0], p2[1]);- p.addSegment(a, d, 1, true);- if (i == array_points.length - 2) {- p.endPlot(a, 1, true);- }- }- }- // Set the origin point from the first point in the array- p.origin = _close && curvature !== 0 ? tep : array_points[0];- }- return p;-}--/**- * Creates and draws a spline curve with the given points and curvature.- * @param {Array<Array<number>>} array_points - An array of points defining the spline curve.- * @param {number} [curvature=0.5] - The curvature of the spline curve, between 0 and 1. A curvature of 0 will create a series of straight segments.- */-export function spline(array_points, curvature = 0.5) {- let p = _createSpline(array_points, curvature); // Create a new Plot-spline instance- p.draw(); // Draw the Plot-}--// =============================================================================-// Section: Fill Management-// =============================================================================-/**- * The Fill Management section contains functions and classes dedicated to handling- * the fill properties of shapes within the drawing context. It supports complex fill- * operations with effects such as bleeding to simulate watercolor-like textures. The- * methods provided allow for setting the fill color with opacity, controlling the- * intensity of the bleed effect, and enabling or disabling the fill operation.- *- * The watercolor effect implementation is inspired by Tyler Hobbs' generative art- * techniques for simulating watercolor paints.- */--// No docs for now-const E = {};-export function erase(color = "white", alpha = 255) {- E.isActive = true;- E.c = color;- E.a = alpha;-}-export function noErase() {- E.isActive = false;-}--/**- * Sets the fill color and opacity for subsequent drawing operations.- * @param {number|p5.Color} a - The red component of the color or grayscale value, a CSS color string, or a p5.Color object.- * @param {number} [b] - The green component of the color or the grayscale opacity if two arguments.- * @param {number} [c] - The blue component of the color.- * @param {number} [d] - The opacity of the color.- */-export function fill(a, b, c, d) {- _ensureReady();- F.opacity = arguments.length < 4 ? (arguments.length < 3 ? b : 1) : d;- F.color = arguments.length < 3 ? _r.color(a) : _r.color(a, b, c);- F.isActive = true;-}--/**- * Sets the bleed and texture levels for the fill operation, simulating a watercolor effect.- * @param {number} _i - The intensity of the bleed effect, capped at 0.5.- * @param {number} _texture - The texture of the watercolor effect, from 0 to 1.- */-export function bleed(_i, _direction = "out") {- _ensureReady();- F.bleed_strength = R.constrain(_i, 0, 0.6);- F.direction = _direction;-}--export function fillTexture(_texture = 0.4, _border = 0.4) {- _ensureReady();- F.texture_strength = R.constrain(_texture, 0, 1);- F.border_strength = R.constrain(_border, 0, 1);-}--export function gravity(x, y) {- _ensureReady();- F.light_source = { x: x, y: y };-}-export function noGravity() {- F.light_source = false;-}--/**- * Disables the fill for subsequent drawing operations.- */-export function noFill() {- F.isActive = false;-}--/**- * Disables some operations in order to guarantee a consistent bleed efect for animations (at different bleed levels)- */-export function fillAnimatedMode(bool) {- F.isAnimated = bool;-}--/**- * Object representing the fill state and operations for drawing.- * @property {boolean} isActive - Indicates if the fill operation is active.- * @property {boolean} isAnimated - Enable or disable animation-mode- * @property {Array} v - Array of p5.Vector representing vertices of the polygon to fill.- * @property {Array} m - Array of multipliers for the bleed effect on each vertex.- * @property {p5.Color} color - Current fill color.- * @property {p5.Color} opacity - Current fill opacity.- * @property {number} bleed_strength - Base value for bleed effect.- * @property {number} texture_strength - Base value for texture strength.- * @property {number} border_strength - Base value for border strength.- * @property {function} fill - Method to fill a polygon with a watercolor effect.- * @property {function} calcCenter - Method to calculate the centroid of the polygon.- */-const F = {- isActive: false,- isAnimated: false,- color: "#002185",- opacity: 80,- bleed_strength: 0.07,- texture_strength: 0.4,- border_strength: 0.4,-- /**- * Fills the given polygon with a watercolor effect.- * @param {Object} polygon - The polygon to fill.- */- fill(polygon) {- // Store polygon- this.polygon = polygon;- // Map polygon vertices to p5.Vector objects- this.v = [...polygon.vertices];- // Calculate fluidity once, outside the loop- const fluid = this.v.length * R.random(0.4);- // Map vertices to bleed multipliers with more intense effect on 'fluid' vertices- F.m = this.v.map((_, i) => {- let multiplier = R.random(0.8, 1.2) * this.bleed_strength;- return i < fluid ? R.constrain(multiplier * 2, 0, 0.9) : multiplier;- });- // Shift vertices randomly to create a more natural watercolor edge- let shift = R.randInt(0, this.v.length);- // If light source, look for closest- if (F.light_source) {- for (let i = 0; i < this.v.length; i++) {- if (- R.dist(this.v[i].x, this.v[i].y, F.light_source.x, F.light_source.y) <- R.dist(- this.v[shift].x,- this.v[shift].y,- F.light_source.x,- F.light_source.y- )- )- shift = i;- }- }- this.v = [...this.v.slice(shift), ...this.v.slice(0, shift)];- // Create and fill the polygon with the calculated bleed effect- let pol = new FillPolygon(this.v, this.m, this.calcCenter(), [], true);- pol.fill(- this.color,- Math.floor(R.map(this.opacity, 0, 155, 0, 20, true)),- this.texture_strength- );- },-- /**- * Calculates the center point of the polygon based on the vertices.- * @returns {p5.Vector} A vector representing the centroid of the polygon.- */- calcCenter() {- let midx = 0,- midy = 0;- for (let i = 0; i < this.v.length; ++i) {- midx += this.v[i].x;- midy += this.v[i].y;- }- (midx /= this.v.length), (midy /= this.v.length);- return { x: midx, y: midy };- },-};--function _rotate(cx, cy, x, y, angle) {- let cos = R.cos(angle),- sin = R.sin(angle),- nx = cos * (x - cx) + sin * (y - cy) + cx,- ny = cos * (y - cy) - sin * (x - cx) + cy;- return { x: nx, y: ny };-}--/**- * The FillPolygon class is used to create and manage the properties of the polygons that produces- * the watercolor effect. It includes methods to grow (expand) the polygon and apply layers- * of color with varying intensity and erase parts to simulate a natural watercolor bleed.- * The implementation follows Tyler Hobbs' guide to simulating watercolor:- * https://tylerxhobbs.com/essays/2017/a-generative-approach-to-simulating-watercolor-paints- */-class FillPolygon {- /**- * The constructor initializes the polygon with a set of vertices, multipliers for the bleed effect, and a center point.- * @param {p5.Vector[]} _v - An array of p5.Vector objects representing the vertices of the polygon.- * @param {number[]} _m - An array of numbers representing the multipliers for the bleed effect at each vertex.- * @param {p5.Vector} _center - A p5.Vector representing the calculated center point of the polygon.- * @param {boolean[]} dir - An array of booleans representing the bleed direction.- * @param {boolean} isFirst - Boolean = true for initial fill polygon- */- constructor(_v, _m, _center, dir, isFirst = false) {- this.pol = new Polygon(_v, true);- this.v = _v;- this.dir = dir;- this.m = _m;- this.midP = _center;- this.size = -Infinity;- for (let v of this.v) {- let temp_size = R.dist(this.midP.x, this.midP.y, v.x, v.y);- if (temp_size > this.size) this.size = temp_size;- }- // This calculates the bleed direction for the initial shape, for each of the vertices.- if (isFirst) {- for (let i = 0; i < this.v.length; i++) {- const v1 = this.v[i];- const v2 = this.v[(i + 1) % this.v.length];- const side = { x: v2.x - v1.x, y: v2.y - v1.y };- const rt = _rotate(0, 0, side.x, side.y, 90);- let linea = {- point1: { x: v1.x + side.x / 2, y: v1.y + side.y / 2 },- point2: { x: v1.x + side.x / 2 + rt.x, y: v1.y + side.y / 2 + rt.y },- };- const isLeft = (a, b, c) => {- return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) > 0.01;- };- let d1 = 0;- for (let int of F.polygon.intersect(linea)) {- if (isLeft(v1, v2, int)) d1++;- }- this.dir[i] = d1 % 2 === 0 ? true : false;- }- }- }-- trim(factor) {- let v = [...this.v],- m = [...this.m],- dir = [...this.dir];- if (this.v.length > 10 && factor >= 0.2) {- let numTrim = ~~((1 - factor) * this.v.length);- let sp = ~~this.v.length / 2 - ~~numTrim / 2;- v.splice(sp, numTrim);- m.splice(sp, numTrim);- dir.splice(sp, numTrim);- }- return { v: v, m: m, dir: dir };- }-- /**- * Grows the polygon's vertices outwards to simulate the spread of watercolor.- * Optionally, can also shrink (degrow) the polygon's vertices inward.- * @param {number} _a - The growth factor.- * @param {boolean} [degrow=false] - If true, vertices will move inwards.- * @returns {FillPolygon} A new `FillPolygon` object with adjusted vertices.- */- grow(growthFactor, degrow = false) {- const newVerts = [];- const newMods = [];- const newDirs = [];- // Determine the length of vertices to process based on growth factor- let tr = this.trim(growthFactor);- // Pre-compute values that do not change within the loop- const modAdjustment = degrow ? -0.5 : 1;- // Inline changeModifier to reduce function calls- const changeModifier = (modifier) => {- const gaussianVariation = R.gaussian(0.5, 0.1);- return modifier + (gaussianVariation - 0.5) * 0.1;- };- // Loop through each vertex to calculate the new position based on growth- for (let i = 0; i < tr.v.length; i++) {- const currentVertex = tr.v[i];- const nextVertex = tr.v[(i + 1) % tr.v.length];- // Determine the growth modifier- let mod =- growthFactor === 0.1- ? F.bleed_strength <= 0.1- ? 0.25- : 0.75- : tr.m[i];- mod *= modAdjustment;- // Add the current vertex and its modified value- newVerts.push(currentVertex);- newMods.push(changeModifier(mod));-- // Calculate side- let side = {- x: nextVertex.x - currentVertex.x,- y: nextVertex.y - currentVertex.y,- };-- // Make sure that we always bleed in the selected direction- let dir = tr.dir[i];- let bleed = F.direction == "out" ? -90 : 90;- let rotationDegrees = (dir ? bleed : -bleed) + R.gaussian(0, 0.4) * 45;-- // Calculate the middle vertex position- let lerp = R.constrain(R.gaussian(0.5, 0.2), 0.1, 0.9);- let newVertex = {- x: currentVertex.x + side.x * lerp,- y: currentVertex.y + side.y * lerp,- };-- // Calculate the new vertex position- let mult = R.gaussian(0.5, 0.2) * R.random(0.6, 1.4) * mod;- let direction = _rotate(0, 0, side.x, side.y, rotationDegrees);- newVertex.x += direction.x * mult;- newVertex.y += direction.y * mult;-- // Add the new vertex and its modifier- newVerts.push(newVertex);- newMods.push(changeModifier(mod));- newDirs.push(dir, dir);- }- return new FillPolygon(newVerts, newMods, this.midP, newDirs);- }-- /**- * Fills the polygon with the specified color and intensity.- * It uses layered growth to simulate watercolor paper absorption and drying patterns.- * @param {p5.Color|string} color - The fill color.- * @param {number} intensity - The opacity of the color layers.- */- fill(color, intensity, tex) {- let bleed = R.map(F.bleed_strength, 0, 0.15, 0.6, 1, true);- // Precalculate stuff- const numLayers = 24 * bleed;- const intensityThird = intensity / 5 + (tex * intensity) / 6;- const intensityQuarter = intensity / 4 + (tex * intensity) / 3;- const intensityFifth = intensity / 7 + (tex * intensity) / 3;- const intensityHalf = intensity / 5;- const texture = tex * 3;-- // Perform initial setup only once- Mix.watercolor = true;- Matrix.trans();- Mix.blend(color, false, false, true);- Mix.masks[0].push();- Mix.masks[0].noStroke();- Mix.masks[0].translate(- Matrix.translation[0] + _r.width / 2,- Matrix.translation[1] + _r.height / 2- );- Mix.masks[0].rotate(Matrix.rotation);- Mix.masks[0].scale(_curScale);-- // Set the different polygons for texture- let pol = this.grow();- let pol2 = pol.grow().grow(0.9);- let pol3 = pol2.grow(0.75);- let pol4 = this.grow(0.6);-- for (let i = 0; i < numLayers; i++) {- if (- i === Math.floor(numLayers / 4) ||- i === Math.floor(numLayers / 2) ||- i === Math.floor((3 * numLayers) / 4)- ) {- // Grow the polygon objects once per fourth of the process- pol = pol.grow();- // Grow the texture polygons if conditions are met- if (bleed === 1 || i === Math.floor(numLayers / 2)) {- pol2 = pol2.grow(0.75);- pol3 = pol3.grow(0.75);- pol4 = pol4.grow(0.1, true);- }- }- // Draw layers- pol.grow().layer(i, intensityHalf);- pol4.grow(0.1, true).grow(0.1).layer(i, intensityFifth, false);- pol2.grow(0.1).grow(0.1).layer(i, intensityQuarter, false);- pol3.grow(0.8).grow(0.1).layer(i, intensityThird, false);- // Erase after each set of layers is drawn- if (texture !== 0) pol.erase(texture, intensity);- }- Mix.masks[0].pop();- }-- /**- * Adds a layer of color to the polygon with specified opacity.- * It also sets a stroke to outline the layer edges.- * @param {number} _nr - The layer number, affecting the stroke and opacity mapping.- * @param {number} _alpha - The opacity of the layer.- * @param {boolean} [bool=true] - If true, adds a stroke to the layer.- */- layer(_nr, _alpha, bool = true) {- // Set fill and stroke properties once- Mix.masks[0].fill(255, 0, 0, _alpha);- if (bool) {- Mix.masks[0].stroke(255, 0, 0, 0.5 + 1.5 * F.border_strength);- Mix.masks[0].strokeWeight(R.map(_nr, 0, 24, 6, 0.5));- } else {- Mix.masks[0].noStroke();- }- Mix.masks[0].beginShape();- for (let v of this.v) {- Mix.masks[0].vertex(v.x, v.y);- }- Mix.masks[0].endShape(_r.CLOSE);- }-- /**- * Erases parts of the polygon to create a more natural, uneven watercolor texture.- * Uses random placement and sizing of circles to simulate texture.- */- erase(texture, intensity) {- const numCircles = R.random(130, 200);- const halfSize = this.size / 2;- const minSizeFactor = 0.025 * this.size;- const maxSizeFactor = 0.19 * this.size;- Mix.masks[0].erase(- 3.5 * texture - R.map(intensity, 80, 120, 0.3, 1, true),- 0- );- for (let i = 0; i < numCircles; i++) {- const x = this.midP.x + R.gaussian(0, halfSize);- const y = this.midP.y + R.gaussian(0, halfSize);- const size = R.random(minSizeFactor, maxSizeFactor);- Mix.masks[0].circle(x, y, size);- }- Mix.masks[0].noErase();- }-}--// =============================================================================-// Section: Standard Brushes-// =============================================================================--/**- * Defines a set of standard brushes with specific characteristics. Each brush is defined- * with properties such as weight, vibration, definition, quality, opacity, spacing, and- * pressure sensitivity. Some brushes have additional properties like type, tip, and rotate.- */-const _vals = [- "weight",- "vibration",- "definition",- "quality",- "opacity",- "spacing",- "pressure",- "type",- "tip",- "rotate",-];-const _standard_brushes = [- // Define each brush with a name and a set of parameters- // For example, the "pen" brush has a weight of 0.35, a vibration of 0.12, etc.- // The "marker2" brush has a custom tip defined by a function that draws rectangles.- [- "pen",- [0.35, 0.12, 0.5, 8, 200, 0.3, { curve: [0.15, 0.2], min_max: [1.4, 0.9] }],- ],- [- "rotring",- [0.2, 0.05, 1, 3, 250, 0.15, { curve: [0.05, 0.2], min_max: [1.7, 0.8] }],- ],- [- "2B",- [0.35, 0.5, 0.1, 8, 180, 0.2, { curve: [0.15, 0.2], min_max: [1.3, 1] }],- ],- [- "HB",- [0.3, 0.5, 0.4, 4, 180, 0.25, { curve: [0.15, 0.2], min_max: [1.2, 0.9] }],- ],- [- "2H",- [0.2, 0.4, 0.3, 2, 150, 0.2, { curve: [0.15, 0.2], min_max: [1.2, 0.9] }],- ],- [- "cpencil",- [0.4, 0.6, 0.8, 7, 120, 0.15, { curve: [0.15, 0.2], min_max: [0.95, 1.2] }],- ],- [- "charcoal",- [0.5, 2, 0.8, 300, 110, 0.06, { curve: [0.15, 0.2], min_max: [1.3, 0.8] }],- ],- [- "hatch_brush",- [0.2, 0.4, 0.3, 2, 150, 0.15, { curve: [0.5, 0.7], min_max: [1, 1.5] }],- ],- [- "spray",- [- 0.3,- 12,- 15,- 40,- 80,- 0.65,- { curve: [0, 0.1], min_max: [0.15, 1.2] },- "spray",- ],- ],- [- "marker",- [- 2.5,- 0.12,- null,- null,- 25,- 0.4,- { curve: [0.35, 0.25], min_max: [1.5, 1] },- "marker",- ],- ],- [- "marker2",- [- 2.5,- 0.12,- null,- null,- 25,- 0.35,- { curve: [0.35, 0.25], min_max: [1.3, 0.95] },- "custom",- function (t) {- let scale = _gScale;- t.rect(-1.5 * scale, -1.5 * scale, 3 * scale, 3 * scale);- t.rect(1 * scale, 1 * scale, 1 * scale, 1 * scale);- },- "natural",- ],- ],-];-/**- * Iterates through the list of standard brushes and adds each one to the brush manager.- * The brush manager is assumed to be a global object `B` that has an `add` method.- */-for (let s of _standard_brushes) {- let obj = {};- for (let i = 0; i < s[1].length; i++) obj[_vals[i]] = s[1][i];- add(s[0], obj);-}+if (typeof p5 !== "undefined") p5.registerAddon(registerAddon);diff --git a/src/shader_unminified.frag b/src/shader_unminified.fragdeleted file mode 100644index e83889b..0000000--- a/src/shader_unminified.frag+++ /dev/null@@ -1,276 +0,0 @@-precision highp float;varying vec2 vVertTexCoord;-uniform sampler2D source;-uniform sampler2D mask;-uniform vec4 addColor;-uniform vec3 random;-uniform bool active;-- #ifndef SPECTRAL- #define SPECTRAL-- const int SPECTRAL_SIZE = 38;- const float SPECTRAL_GAMMA = 2.4;- const float SPECTRAL_EPSILON = 0.0001;-- 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.0, 1.0);- }-- void spectral_upsampling(vec3 lrgb, out float w, out float c, out float m, out float y, out float r, out float g, out float b) {- w = min(lrgb.r, min(lrgb.g, lrgb.b));-- lrgb -= w;-- c = min(lrgb.g, lrgb.b);- m = min(lrgb.r, lrgb.b);- y = min(lrgb.r, lrgb.g);- r = min(max(0., lrgb.r - lrgb.b), max(0., lrgb.r - lrgb.g));- g = min(max(0., lrgb.g - lrgb.b), max(0., lrgb.g - lrgb.r));- b = min(max(0., lrgb.b - lrgb.g), max(0., lrgb.b - lrgb.r));- }-- void spectral_linear_to_reflectance(vec3 lrgb, inout float R[SPECTRAL_SIZE]) {- float w, c, m, y, r, g, b;-- spectral_upsampling(lrgb, w, c, m, y, r, g, b);-- R[0] = max(SPECTRAL_EPSILON, w + c * 0.96853629 + m * 0.51567122 + y * 0.02055257 + r * 0.03147571 + g * 0.49108579 + b * 0.97901834);- R[1] = max(SPECTRAL_EPSILON, w + c * 0.96855103 + m * 0.54015520 + y * 0.02059936 + r * 0.03146636 + g * 0.46944057 + b * 0.97901649);- R[2] = max(SPECTRAL_EPSILON, w + c * 0.96859338 + m * 0.62645502 + y * 0.02062723 + r * 0.03140624 + g * 0.40165780 + b * 0.97901118);- R[3] = max(SPECTRAL_EPSILON, w + c * 0.96877345 + m * 0.75595012 + y * 0.02073387 + r * 0.03119611 + g * 0.24490420 + b * 0.97892146);- R[4] = max(SPECTRAL_EPSILON, w + c * 0.96942204 + m * 0.92826996 + y * 0.02114202 + r * 0.03053888 + g * 0.06826880 + b * 0.97858555);- R[5] = max(SPECTRAL_EPSILON, w + c * 0.97143709 + m * 0.97223624 + y * 0.02233154 + r * 0.02856855 + g * 0.02732883 + b * 0.97743705);- R[6] = max(SPECTRAL_EPSILON, w + c * 0.97541862 + m * 0.98616174 + y * 0.02556857 + r * 0.02459485 + g * 0.01360600 + b * 0.97428075);- R[7] = max(SPECTRAL_EPSILON, w + c * 0.98074186 + m * 0.98955255 + y * 0.03330189 + r * 0.01929520 + g * 0.01000187 + b * 0.96663223);- R[8] = max(SPECTRAL_EPSILON, w + c * 0.98580992 + m * 0.98676237 + y * 0.05185294 + r * 0.01423112 + g * 0.01284127 + b * 0.94822893);- R[9] = max(SPECTRAL_EPSILON, w + c * 0.98971194 + m * 0.97312575 + y * 0.10087639 + r * 0.01033111 + g * 0.02636635 + b * 0.89937713);- R[10] = max(SPECTRAL_EPSILON, w + c * 0.99238027 + m * 0.91944277 + y * 0.24000413 + r * 0.00765876 + g * 0.07058713 + b * 0.76070164);- R[11] = max(SPECTRAL_EPSILON, w + c * 0.99409844 + m * 0.32564851 + y * 0.53589066 + r * 0.00593693 + g * 0.70421692 + b * 0.46420440);- R[12] = max(SPECTRAL_EPSILON, w + c * 0.99517200 + m * 0.13820628 + y * 0.79874659 + r * 0.00485616 + g * 0.85473994 + b * 0.20123039);- R[13] = max(SPECTRAL_EPSILON, w + c * 0.99576545 + m * 0.05015143 + y * 0.91186529 + r * 0.00426186 + g * 0.95081565 + b * 0.08808402);- R[14] = max(SPECTRAL_EPSILON, w + c * 0.99593552 + m * 0.02912336 + y * 0.95399623 + r * 0.00409039 + g * 0.97170370 + b * 0.04592894);- R[15] = max(SPECTRAL_EPSILON, w + c * 0.99564041 + m * 0.02421691 + y * 0.97137099 + r * 0.00438375 + g * 0.97651888 + b * 0.02860373);- R[16] = max(SPECTRAL_EPSILON, w + c * 0.99464769 + m * 0.02660696 + y * 0.97939505 + r * 0.00537525 + g * 0.97429245 + b * 0.02060067);- R[17] = max(SPECTRAL_EPSILON, w + c * 0.99229579 + m * 0.03407586 + y * 0.98345207 + r * 0.00772962 + g * 0.97012917 + b * 0.01656701);- R[18] = max(SPECTRAL_EPSILON, w + c * 0.98638762 + m * 0.04835936 + y * 0.98553736 + r * 0.01366120 + g * 0.94258630 + b * 0.01451549);- R[19] = max(SPECTRAL_EPSILON, w + c * 0.96829712 + m * 0.00011720 + y * 0.98648905 + r * 0.03181352 + g * 0.99989207 + b * 0.01357964);- R[20] = max(SPECTRAL_EPSILON, w + c * 0.89228016 + m * 0.00008554 + y * 0.98674535 + r * 0.10791525 + g * 0.99989891 + b * 0.01331243);- R[21] = max(SPECTRAL_EPSILON, w + c * 0.53740239 + m * 0.85267882 + y * 0.98657555 + r * 0.46249516 + g * 0.13823139 + b * 0.01347661);- R[22] = max(SPECTRAL_EPSILON, w + c * 0.15360445 + m * 0.93188793 + y * 0.98611877 + r * 0.84604333 + g * 0.06968113 + b * 0.01387181);- R[23] = max(SPECTRAL_EPSILON, w + c * 0.05705719 + m * 0.94810268 + y * 0.98559942 + r * 0.94275572 + g * 0.05628787 + b * 0.01435472);- R[24] = max(SPECTRAL_EPSILON, w + c * 0.03126539 + m * 0.94200977 + y * 0.98507063 + r * 0.96860996 + g * 0.06111561 + b * 0.01479836);- R[25] = max(SPECTRAL_EPSILON, w + c * 0.02205445 + m * 0.91478045 + y * 0.98460039 + r * 0.97783966 + g * 0.08987709 + b * 0.01515250);- R[26] = max(SPECTRAL_EPSILON, w + c * 0.01802271 + m * 0.87065445 + y * 0.98425301 + r * 0.98187757 + g * 0.13656016 + b * 0.01540513);- R[27] = max(SPECTRAL_EPSILON, w + c * 0.01613460 + m * 0.78827548 + y * 0.98403909 + r * 0.98377315 + g * 0.22169624 + b * 0.01557233);- R[28] = max(SPECTRAL_EPSILON, w + c * 0.01520947 + m * 0.65738359 + y * 0.98388535 + r * 0.98470202 + g * 0.32176956 + b * 0.01565710);- R[29] = max(SPECTRAL_EPSILON, w + c * 0.01475977 + m * 0.59909403 + y * 0.98376116 + r * 0.98515481 + g * 0.36157329 + b * 0.01571025);- R[30] = max(SPECTRAL_EPSILON, w + c * 0.01454263 + m * 0.56817268 + y * 0.98368246 + r * 0.98537114 + g * 0.48361920 + b * 0.01571916);- R[31] = max(SPECTRAL_EPSILON, w + c * 0.01444459 + m * 0.54031997 + y * 0.98365023 + r * 0.98546685 + g * 0.46488579 + b * 0.01572133);- R[32] = max(SPECTRAL_EPSILON, w + c * 0.01439897 + m * 0.52110241 + y * 0.98361309 + r * 0.98550011 + g * 0.47440306 + b * 0.01572502);- R[33] = max(SPECTRAL_EPSILON, w + c * 0.01437620 + m * 0.51041094 + y * 0.98357259 + r * 0.98551031 + g * 0.48576990 + b * 0.01571717);- R[34] = max(SPECTRAL_EPSILON, w + c * 0.01436343 + m * 0.50526577 + y * 0.98353856 + r * 0.98550741 + g * 0.49267971 + b * 0.01571905);- R[35] = max(SPECTRAL_EPSILON, w + c * 0.01435687 + m * 0.50255080 + y * 0.98351247 + r * 0.98551323 + g * 0.49625685 + b * 0.01571059);- R[36] = max(SPECTRAL_EPSILON, w + c * 0.01435370 + m * 0.50126452 + y * 0.98350101 + r * 0.98551563 + g * 0.49807754 + b * 0.01569728);- R[37] = max(SPECTRAL_EPSILON, w + c * 0.01435408 + m * 0.50083021 + y * 0.98350852 + r * 0.98551547 + g * 0.49889859 + b * 0.01570020);- }-- vec3 spectral_xyz_to_srgb(vec3 xyz) {- mat3 XYZ_RGB;-- XYZ_RGB[0] = vec3( 3.24306333, -1.53837619, -0.49893282);- XYZ_RGB[1] = vec3(-0.96896309, 1.87542451, 0.04154303);- XYZ_RGB[2] = vec3( 0.05568392, -0.20417438, 1.05799454);-- 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.0);-- xyz += R[0] * vec3(0.00006469, 0.00000184, 0.00030502);- xyz += R[1] * vec3(0.00021941, 0.00000621, 0.00103681);- xyz += R[2] * vec3(0.00112057, 0.00003101, 0.00531314);- xyz += R[3] * vec3(0.00376661, 0.00010475, 0.01795439);- xyz += R[4] * vec3(0.01188055, 0.00035364, 0.05707758);- xyz += R[5] * vec3(0.02328644, 0.00095147, 0.11365162);- xyz += R[6] * vec3(0.03455942, 0.00228226, 0.17335873);- xyz += R[7] * vec3(0.03722379, 0.00420733, 0.19620658);- xyz += R[8] * vec3(0.03241838, 0.00668880, 0.18608237);- xyz += R[9] * vec3(0.02123321, 0.00988840, 0.13995048);- xyz += R[10] * vec3(0.01049099, 0.01524945, 0.08917453);- xyz += R[11] * vec3(0.00329584, 0.02141831, 0.04789621);- xyz += R[12] * vec3(0.00050704, 0.03342293, 0.02814563);- xyz += R[13] * vec3(0.00094867, 0.05131001, 0.01613766);- xyz += R[14] * vec3(0.00627372, 0.07040208, 0.00775910);- xyz += R[15] * vec3(0.01686462, 0.08783871, 0.00429615);- xyz += R[16] * vec3(0.02868965, 0.09424905, 0.00200551);- xyz += R[17] * vec3(0.04267481, 0.09795667, 0.00086147);- xyz += R[18] * vec3(0.05625475, 0.09415219, 0.00036904);- xyz += R[19] * vec3(0.06947040, 0.08678102, 0.00019143);- xyz += R[20] * vec3(0.08305315, 0.07885653, 0.00014956);- xyz += R[21] * vec3(0.08612610, 0.06352670, 0.00009231);- xyz += R[22] * vec3(0.09046614, 0.05374142, 0.00006813);- xyz += R[23] * vec3(0.08500387, 0.04264606, 0.00002883);- xyz += R[24] * vec3(0.07090667, 0.03161735, 0.00001577);- xyz += R[25] * vec3(0.05062889, 0.02088521, 0.00000394);- xyz += R[26] * vec3(0.03547396, 0.01386011, 0.00000158);- xyz += R[27] * vec3(0.02146821, 0.00810264, 0.00000000);- xyz += R[28] * vec3(0.01251646, 0.00463010, 0.00000000);- xyz += R[29] * vec3(0.00680458, 0.00249138, 0.00000000);- xyz += R[30] * vec3(0.00346457, 0.00125930, 0.00000000);- xyz += R[31] * vec3(0.00149761, 0.00054165, 0.00000000);- xyz += R[32] * vec3(0.00076970, 0.00027795, 0.00000000);- xyz += R[33] * vec3(0.00040737, 0.00014711, 0.00000000);- xyz += R[34] * vec3(0.00016901, 0.00006103, 0.00000000);- xyz += R[35] * vec3(0.00009522, 0.00003439, 0.00000000);- xyz += R[36] * vec3(0.00004903, 0.00001771, 0.00000000);- xyz += R[37] * vec3(0.00002000, 0.00000722, 0.00000000);-- return xyz;- }-- float spectral_linear_to_concentration(float l1, float l2, float t) {- float t1 = l1 * pow(1.0 - t, 2.0);- float t2 = l2 * pow(t, 2.0);-- return t2 / (t1 + t2);- }-- vec3 spectral_mix(vec3 color1, vec3 color2, float t) {- 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 l1 = spectral_reflectance_to_xyz(R1)[1];- float l2 = spectral_reflectance_to_xyz(R2)[1];-- t = spectral_linear_to_concentration(l1, l2, t);-- float R[SPECTRAL_SIZE];-- for (int i = 0; i < SPECTRAL_SIZE; i++) {- float KS = (1.0 - t) * (pow(1.0 - R1[i], 2.0) / (2.0 * R1[i])) + t * (pow(1.0 - R2[i], 2.0) / (2.0 * R2[i]));- float KM = 1.0 + KS - sqrt(pow(KS, 2.0) + 2.0 * KS);-- //Saunderson correction- // let S = ((1.0 - K1) * (1.0 - K2) * KM) / (1.0 - K2 * KM);-- R[i] = KM;- }-- return spectral_xyz_to_srgb(spectral_reflectance_to_xyz(R));- }-- vec4 spectral_mix(vec4 color1, vec4 color2, float t) {- return vec4(spectral_mix(color1.rgb, color2.rgb, t), mix(color1.a, color2.a, t));- }-- #endif--// psrdnoise (c) Stefan Gustavson and Ian McEwan,-float psrdnoise(vec2 x, vec2 period, float alpha, out vec2 gradient) {- vec2 uv = vec2(x.x+x.y*0.5, x.y);- vec2 i0 = floor(uv), f0 = fract(uv);- float cmp = step(f0.y, f0.x);- vec2 o1 = vec2(cmp, 1.0-cmp);- vec2 i1 = i0 + o1, i2 = i0 + 1.0;- vec2 v0 = vec2(i0.x - i0.y*0.5, i0.y);- vec2 v1 = vec2(v0.x + o1.x - o1.y*0.5, v0.y + o1.y);- vec2 v2 = vec2(v0.x + 0.5, v0.y + 1.0);- vec2 x0 = x - v0, x1 = x - v1, x2 = x - v2;- vec3 iu, iv, xw, yw;- if(any(greaterThan(period, vec2(0.0)))) {- xw = vec3(v0.x, v1.x, v2.x);- yw = vec3(v0.y, v1.y, v2.y);- if(period.x > 0.0)- xw = mod(vec3(v0.x, v1.x, v2.x), period.x);- if(period.y > 0.0)- yw = mod(vec3(v0.y, v1.y, v2.y), period.y);- iu = floor(xw + 0.5*yw + 0.5); iv = floor(yw + 0.5);- } else {- iu = vec3(i0.x, i1.x, i2.x); iv = vec3(i0.y, i1.y, i2.y);- }- vec3 hash = mod(iu, 289.0);- hash = mod((hash*51.0 + 2.0)*hash + iv, 289.0);- hash = mod((hash*34.0 + 10.0)*hash, 289.0);- vec3 psi = hash*0.07482 + alpha;- vec3 gx = cos(psi); vec3 gy = sin(psi);- vec2 g0 = vec2(gx.x, gy.x);- vec2 g1 = vec2(gx.y, gy.y);- vec2 g2 = vec2(gx.z, gy.z);- vec3 w = 0.8 - vec3(dot(x0, x0), dot(x1, x1), dot(x2, x2));- w = max(w, 0.0); vec3 w2 = w*w; vec3 w4 = w2*w2;- vec3 gdotx = vec3(dot(g0, x0), dot(g1, x1), dot(g2, x2));- float n = dot(w4, gdotx);- vec3 w3 = w2*w; vec3 dw = -8.0*w3*gdotx;- vec2 dn0 = w4.x*g0 + dw.x*x0;- vec2 dn1 = w4.y*g1 + dw.y*x1;- vec2 dn2 = w4.z*g2 + dw.z*x2;- gradient = 10.9*(dn0 + dn1 + dn2);- return 10.9*n;-}--vec4 generic_desaturate(vec3 color, float factor) {- vec3 lum = vec3(0.299, 0.587, 0.114);- vec3 gray = vec3(dot(lum, color));- return vec4(mix(color, gray, factor), 1.0);-}--float rand(vec2 co, float a, float b, float c) {- return fract(sin(dot(co, vec2(a, b))) * c);-}--void main() {- vec4 maskColor = texture2D(mask, vVertTexCoord);- if (maskColor.r > 0.0) {- vec2 r=vec2(12.9898,78.233), a=vec2(7.9898,58.233), l=vec2(17.9898,3.233);- float d=rand(vVertTexCoord,r.x,r.y,43358.5453)*2.-1., x=rand(vVertTexCoord,a.x,a.y,43213.5453)*2.-1., s=rand(vVertTexCoord,l.x,l.y,33358.5453)*2.-1.;-- const vec2 p = vec2(0.0);- vec2 g;-- vec4 pigment;-- if (active) {- float n = psrdnoise(vVertTexCoord * 5., p, 10.0 * random.x, g);- float n2 = psrdnoise(vVertTexCoord * 5., p, 10.0 * random.y, g);- float n3 = psrdnoise(vVertTexCoord * 5., p, 10.0 * random.z, g);- float tt = abs(addColor.x - addColor.y - addColor.z);- float n4 = 0.25 + 0.25 * psrdnoise(vVertTexCoord * 4., p, 3.0 * random.x, g);- pigment = vec4(generic_desaturate(addColor.xyz,n4).xyz + vec3(n,n2,n3) * 0.03 * tt, 1.0);- }- else {- pigment = vec4(addColor.xyz,1.0);- }-- float darken_above = 0.7;- if (maskColor.a > darken_above) {- float blacken = 0.5 * (maskColor.a - darken_above);- pigment = pigment * (1. - blacken) - vec4(0.5) * blacken;- }-- vec3 mixedColor = spectral_mix(texture2D(source,vVertTexCoord).xyz, pigment.xyz, 0.9 * maskColor.a);- gl_FragColor = vec4(mixedColor + 0.01*vec3(d,x,s),1.);- }-}\ No newline at end of filediff --git a/src/stroke/gl_draw.js b/src/stroke/gl_draw.jsnew file mode 100644index 0000000..1ed5c8a--- /dev/null+++ b/src/stroke/gl_draw.js@@ -0,0 +1,201 @@+// =============================================================================+// Module: GL Draw+// =============================================================================+/**+ * The GL Draw module provides functions for rendering shapes (circles and squares)+ * using WebGL2. It initializes the WebGL context and shader programs, prepares buffers,+ * and implements drawing routines based on queued drawing primitives. The module uses+ * an orthographic projection to map canvas coordinates to clip space and supports adjustable+ * blending for translucent effects.+ */++import {+ Mix,+ Cwidth,+ Cheight,+ isMixReady,+ Density,+ State,+} from "../core/color.js";+import { Matrix } from "../core/flowfield.js";+import { createProgram } from "../core/gl/utils.js";+import vertSrc from "./shader.vert";+import fragSrc from "./shader.frag";++// =============================================================================+// Section: Initialization and Setup+// =============================================================================++// Module state+let isLoaded = false,+ gl,+ projMatrix,+ vao,+ buf,+ program;+const Attr = {},+ Frag = {};++// Cached matrix values — snapshotted once per stroke in snapshotMatrix()+let _ma = 1,+ _mb = 0,+ _mc = 0,+ _md = 1,+ _mx = 0,+ _my = 0;++/**+ * Snapshots the current p5 model matrix. Call once at the start of each stroke.+ */+export function snapshotMatrix() {+ _ma = Matrix.a();+ _mb = Matrix.b();+ _mc = Matrix.c();+ _md = Matrix.d();+ _mx = Matrix.x();+ _my = Matrix.y();+}++// Pre-allocated flat buffer for circle data (x, y, radius, alpha per circle)+const INITIAL_CAPACITY = 2048;+let circleData = new Float32Array(INITIAL_CAPACITY * 4);+let circleCount = 0;+let bufferCapacity = INITIAL_CAPACITY;+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;+ projMatrix = new Float32Array([+ 2 / Cwidth,+ 0,+ 0,+ 0,+ 0,+ -2 / Cheight,+ 0,+ 0,+ 0,+ 0,+ 1,+ 0,+ -1,+ 1,+ 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;+ }+}++// =============================================================================+// Section: Drawing Primitives+// =============================================================================++/**+ * Queue a circle to be drawn with the specified parameters.+ * Data is written directly into a flat Float32Array to avoid object allocation.+ * Applies the full 2D affine transform (rotation + scale + translation) from+ * p5's current model matrix so that brush.rotate() and brush.scale() work correctly.+ */+export function circle(x, y, diameter, alpha) {+ // Grow buffer if needed+ if (circleCount >= bufferCapacity) {+ bufferCapacity *= 2;+ const newData = new Float32Array(bufferCapacity * 4);+ newData.set(circleData);+ circleData = newData;+ }++ // x/y arrive in "position space": user coords + (Cwidth/2, Cheight/2).+ // Subtract the offset to recover user coords, apply the full matrix, then re-add+ // the offset so the result is in screen pixel space [0..Cwidth, 0..Cheight].+ const px = x - Cwidth / 2;+ const py = y - Cheight / 2;++ const offset = circleCount * 4;+ circleData[offset] = _ma * px + _mc * py + _mx + Cwidth / 2;+ circleData[offset + 1] = _mb * px + _md * py + _my + Cheight / 2;+ // Scale the diameter by the matrix's scale factor (length of the transformed x-axis)+ circleData[offset + 2] =+ (Density * diameter * Math.sqrt(_ma * _ma + _mb * _mb)) / 2;+ circleData[offset + 3] = alpha / 255;+ circleCount++;+}++/**+ * Draw all queued circles using WebGL+ */+export function glDraw() {+ if (circleCount === 0) return;++ Mix.glMask.isDrawn = true;++ const color = State.stroke.color._array;++ // Re-activate our shader (p5 drawing may have switched programs)+ gl.useProgram(program);+ gl.enable(gl.BLEND);+ gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);++ gl.bindVertexArray(vao);+ gl.bindBuffer(gl.ARRAY_BUFFER, buf);++ // Upload vertex data — reallocate GPU buffer only if needed+ const byteCount = circleCount * 16; // 4 floats × 4 bytes+ const dataView = circleData.subarray(0, circleCount * 4);+ if (byteCount > gpuBufferSize) {+ gl.bufferData(gl.ARRAY_BUFFER, circleData, gl.DYNAMIC_DRAW);+ gpuBufferSize = circleData.byteLength;+ } else {+ gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);+ }++ // Set uniforms and draw+ gl.uniform4f(Frag.u_color, ...color);+ gl.uniformMatrix4fv(Frag.u_matrix, false, projMatrix);+ gl.drawArrays(gl.POINTS, 0, circleCount);++ gl.bindVertexArray(null);++ // Reset queue (no deallocation)+ circleCount = 0;+}diff --git a/src/stroke/shader.frag b/src/stroke/shader.fragnew file mode 100644index 0000000..5a9447b--- /dev/null+++ b/src/stroke/shader.frag@@ -0,0 +1,29 @@+#version 300 es+precision highp float;++in float v_alpha;+out vec4 outColor;++uniform vec4 u_color;++void main() {+ // Point coordinate centered around (0.0, 0.0)+ vec2 v = gl_PointCoord - vec2(0.5);++ // Distance from center+ float f = length(v);++ // Antialiasing factor+ float a = fwidth(f);++ // Soft circular mask (1.0 at center, 0.0 outside radius ~0.5)+ f = 1.0 - smoothstep(0.5 - a, 0.5 + a, f);++ // Discard nearly transparent fragments+ if (f < 0.01) {+ discard;+ }++ // Red color tinted by v_alpha, with smooth edge by f+ outColor = vec4(u_color.xyz, v_alpha * f);+}\ No newline at end of filediff --git a/src/stroke/shader.vert b/src/stroke/shader.vertnew file mode 100644index 0000000..4f0f69e--- /dev/null+++ b/src/stroke/shader.vert@@ -0,0 +1,20 @@+#version 300 es++in vec2 a_position;+in float a_radius;+in float a_alpha;++uniform mat4 u_matrix;++out float v_alpha;++void main() {+ // Transform 2D position into clip space using the matrix+ gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);++ // Pass alpha to the fragment shader+ v_alpha = a_alpha;++ // Set point size (diameter = 2 * radius)+ gl_PointSize = a_radius * 2.0;+}\ No newline at end of filediff --git a/src/stroke/stroke.js b/src/stroke/stroke.jsnew file mode 100644index 0000000..a2e4d15--- /dev/null+++ b/src/stroke/stroke.js@@ -0,0 +1,882 @@+// =============================================================================+// Module: Brush+// =============================================================================+/**+ * The Brush module provides a comprehensive set of functions and classes for+ * simulating various drawing tools ranging from pens, markers, pencils, to+ * custom image-based brushes. This module controls brush properties such as+ * weight, color, vibration, and spacing, and manages the drawing process through+ * stateful methods that enable features like pressure sensitivity, clipping, and+ * blending. By supporting multiple brush types and dynamic parameter adjustments,+ * the Brush module facilitates the creation of realistic and expressive stroke effects.+ */++import {+ Mix,+ Cwidth,+ Cheight,+ State,+ Renderer,+ isCanvasReady,+} from "../core/color.js";+import {+ rr,+ map,+ dist,+ randInt,+ calcAngle,+ toDegrees,+ gaussian,+ rArray,+ noise,+} from "../core/utils.js";+import { Position, Matrix, isFieldReady } from "../core/flowfield.js";+import { Polygon } from "../core/polygon.js";+import { Plot } from "../core/plot.js";+import { isReady, glDraw, circle, snapshotMatrix } from "./gl_draw.js";++// ---------------------------------------------------------------------------+// Brush State and Helpers+// ---------------------------------------------------------------------------++/**+ * Global stroke state settings.+ */+State.stroke = {+ color: null,+ weight: 1,+ clipWindow: null,+ type: "HB",+ isActive: false,+ opacity: 1,+};++let list = new Map();++let Mask = null;++/**+ * Retrieves a shallow copy of the current stroke state.+ * @returns {object} The stroke state.+ */+export function BrushState() {+ return { ...State.stroke };+}++/**+ * Updates the stroke state.+ * @param {object} state - The new stroke state.+ */+export function BrushSetState(state) {+ State.stroke = { ...state };+}++// =============================================================================+// Section: Brush Manager+// =============================================================================++/**+ * Adds a new brush with the specified parameters to the brush list.+ * @param {string} name - The unique name for the new brush.+ * @param {object} params - The parameters defining the brush behavior and appearance.+ */+/**+ * Normalizes the pressure parameter to the internal { type, min_max, curve } format.+ * Accepts:+ * [start, end] — linear ramp between two pressure values+ * [start, mid, end] — piecewise linear (e.g. [1.5, 0.5, 1.5] for U-curve)+ * (t) => value — custom function, t ∈ [0,1], return value ∈ [0,1]+ * { type, min_max, curve } — old internal format, passed through unchanged+ */+function normalizePressure(p) {+ if (!p || (typeof p === "object" && !Array.isArray(p))) return p;+ if (typeof p === "function")+ return { type: "custom", min_max: [0, 1], curve: p };+ if (Array.isArray(p)) {+ const [s, m, e] = p.length === 2 ? [p[0], (p[0] + p[1]) / 2, p[1]] : p;+ const min = Math.min(s, m, e),+ max = Math.max(s, m, e);+ const range = max - min || 1;+ const [ns, nm, ne] = [+ (s - min) / range,+ (m - min) / range,+ (e - min) / range,+ ];+ return {+ type: "custom",+ min_max: [min, max],+ curve: (t) =>+ t < 0.5 ? ns + (nm - ns) * t * 2 : nm + (ne - nm) * (t - 0.5) * 2,+ };+ }+}++export function add(name, params) {+ const validTypes = ["marker", "custom", "image", "spray"];+ params.type = validTypes.includes(params.type) ? params.type : "default";+ // Accept legacy param names for backward compatibility+ if (params.vibration !== undefined && params.scatter === undefined)+ params.scatter = params.vibration;+ if (params.definition !== undefined && params.sharpness === undefined)+ params.sharpness = params.definition;+ if (params.quality !== undefined && params.grain === undefined)+ params.grain = params.quality;+ params.pressure = normalizePressure(params.pressure);+ if (params.type === "image") {+ if (!params.image || !params.image.src) {+ throw new Error(+ `Brush "${name}" is type "image" but is missing params.image.src. Example: image: { src: "./tip.jpg" }`,+ );+ }+ T.add(params.image.src);+ params.tip = () => {+ Mask.image(+ T.tips.get(current.p.image.src),+ -current.p.weight / 2,+ -current.p.weight / 2,+ current.p.weight,+ current.p.weight,+ );+ };+ list.set(name, { param: params, colors: [], buffers: [] });+ return T.load(); // returns a Promise; only loads images not yet loaded+ }+ list.set(name, { param: params, colors: [], buffers: [] });+}++/**+ * Retrieves the list of available brush names.+ * @returns {Array<string>} Array of brush names.+ */+export function box() {+ return [...list.keys()];+}++/**+ * Scales standard brush parameters by the provided factor.+ * @param {number} scaleFactor - The scaling factor to apply.+ */+export function scaleBrushes(scaleFactor) {+ for (const { param } of list.values()) {+ if (param) {+ param.weight *= scaleFactor;+ param.scatter *= scaleFactor;+ param.spacing *= scaleFactor;+ }+ }+}++/**+ * Sets the current brush type by name.+ * @param {string} brushName - The name of the brush.+ */+export function pick(brushName) {+ if (!list.has(brushName)) {+ throw new Error(+ `Brush "${brushName}" not found. Available brushes: ${[...list.keys()].join(", ")}.`,+ );+ }+ State.stroke.type = brushName;+}++/**+ * Sets the stroke style (color) for the current brush.+ * @param {number|string|Color} r - Red component, CSS color string, or Color object.+ * @param {number} [g] - Green component.+ * @param {number} [b] - Blue component.+ */+export function stroke(r, g, b) {+ isCanvasReady();+ State.stroke.color = Renderer.color(...arguments);+ State.stroke.isActive = true;+}++/**+ * Sets the brush weight (thickness).+ * @param {number} weight - The weight value.+ */+export function strokeWeight(weight) {+ State.stroke.weight = weight;+}++/**+ * Sets the current brush with name, color, and weight.+ * @param {string} brushName - The brush name.+ * @param {string|Color} color - The brush color.+ * @param {number} [weight=1] - The brush weight.+ */+export function set(brushName, color, weight = 1) {+ pick(brushName);+ stroke(color);+ strokeWeight(weight);+}++/**+ * Disables the stroke effect.+ */+export function noStroke() {+ State.stroke.isActive = false;+}++/**+ * Defines a clipping region for strokes.+ * @param {number[]} region - Array as [x1, y1, x2, y2] defining the clipping region.+ */+export function clip(region) {+ State.stroke.clipWindow = region;+}++/**+ * Disables the clipping region.+ */+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+// ---------------------------------------------------------------------------+let _position, _length, _plot, _dir;+const current = {};++/**+ * Initializes the drawing state.+ * @param {number} x - Starting x-coordinate.+ * @param {number} y - Starting y-coordinate.+ * @param {number} length - Length of stroke.+ * @param {boolean} flow - Flag for vector-field following.+ * @param {Object|boolean} plot - Plot object or false.+ */+function initializeDrawingState(x, y, length, plot = false) {+ snapshotMatrix();+ _position = new Position(x + Cwidth / 2, y + Cheight / 2);+ _length = length;+ _plot = plot;+ if (_plot) _plot.calcIndex(0);+}++const gaussians = [];++/**+ * Executes the drawing operation.+ * @param {number} angleScale - Angle (in degrees) or scaling factor.+ * @param {boolean} isPlot - True if plotting a shape.+ */+function draw(angleScale, isPlot) {+ if (!isPlot) _dir = angleScale;+ saveState();++ const stepSize = spacing();+ const totalSteps = Math.round(+ (_length * (isPlot ? angleScale : 1)) / stepSize,+ );+ for (let i = 0; i < totalSteps; i++) {+ if (gaussians.length < totalSteps * 2) {+ gaussians.push(gaussian());+ }+ tip();+ isPlot+ ? _position.plotTo(+ _plot,+ stepSize,+ stepSize,+ angleScale,+ i < 10 ? true : false,+ )+ : _position.moveTo(angleScale, stepSize, stepSize);+ }+ restoreState();+}++/**+ * Prepares the environment for a brush stroke.+ */+function saveState() {+ current.seed = rr() * 999999;+ const { param } = list.get(State.stroke.type) ?? {};+ if (!param) return;+ current.p = param;++ Mask = Mix.glMask;++ // Set pressure values for the stroke+ const { pressure } = param;+ current.a = pressure.type !== "custom" ? rr(-1, 1) : 0;+ current.b = pressure.type !== "custom" ? rr(1, 1.5) : 0;+ current.cp = pressure.type !== "custom" ? rr(3, 3.5) : rr(-0.2, 0.2);+ [current.min, current.max] = pressure.min_max;++ current.noiseoffset = 0.03;++ // Cache stroke direction for direction-aware dispersion (non-plot strokes only)+ if (!_plot) {+ const dirRad = (_dir * Math.PI) / 180;+ current.cos = Math.cos(dirRad);+ current.sin = Math.sin(dirRad);+ }++ // Ensure GL is ready and blend state+ isReady();+ if (isInsideClippingArea()) Mix.blend(State.stroke.color);+ if (Mix.isBrush === false) Mix.justChanged = true;+ Mix.isBrush = true;++ // Set additional state values+ current.alpha = calculateAlpha();+ markerTip();+}++/**+ * Restores drawing state after completing a stroke.+ */+function restoreState() {+ glDraw();+ markerTip();+}++/**+ * Renders the brush tip based on current pressure and position.+ * @param {number} [customPressure=false] - Optional custom pressure.+ */+function tip(customPressure = false) {+ if (!isInsideClippingArea()) return;+ let pressure = customPressure || calculatePressure();++ let lineNoise = map(+ noise(current.seed + _position.plotted * 0.002, 0),+ 0,+ 1,+ 1 - current.noiseoffset,+ 1 + current.noiseoffset,+ );++ switch (current.p.type) {+ case "spray":+ drawSpray(pressure * lineNoise);+ break;+ case "marker":+ drawMarker(pressure * lineNoise);+ break;+ case "custom":+ case "image":+ drawTip(pressure * lineNoise, current.alpha);+ break;+ default:+ drawDefault(pressure * lineNoise);+ break;+ }+}++/**+ * Calculates the effective brush pressure.+ * @returns {number} The calculated pressure.+ */+function calculatePressure() {+ return _plot+ ? simPressure() * _plot.pressure(_position.plotted)+ : simPressure();+}++/**+ * Simulates brush pressure based on stroke parameters.+ * @returns {number} Simulated pressure value.+ */+function simPressure() {+ return current.p.pressure.type === "custom"+ ? map(+ current.p.pressure.curve(_position.plotted / _length) + current.cp,+ 0,+ 1,+ current.min,+ current.max,+ true,+ )+ : gauss();+}++/**+ * Generates a Gaussian-based pressure value.+ * @param {number} [a] - Center parameter.+ * @param {number} [b] - Width parameter.+ * @param {number} [c] - Shape parameter.+ * @param {number} [min] - Minimum pressure.+ * @param {number} [max] - Maximum pressure.+ * @returns {number} Gaussian pressure value.+ */+function gauss(+ a = 0.5 + current.p.pressure.curve[0] * current.a,+ b = 1 - current.p.pressure.curve[1] * current.b,+ c = current.cp,+ min = current.min,+ max = current.max,+) {+ const peakPos = a * _length;+ const halfWidth =+ (_position.plotted < peakPos ? b * 1.2 : b * 0.8) * (_length / 2);+ return map(+ 1 /+ (1 ++ Math.pow(Math.abs((_position.plotted - peakPos) / halfWidth), 2 * c)),+ 0,+ 1,+ min,+ max,+ );+}++/**+ * Calculates the alpha (opacity) level for a brush stroke.+ * @returns {number} The calculated opacity.+ */+function calculateAlpha() {+ return ["default", "spray"].includes(current.p.type)+ ? current.p.opacity+ : current.p.opacity / Math.min(State.stroke.weight, 1.3);+}++/**+ * Checks if the current drawing position is within the clipping region.+ * @returns {boolean} True if inside clipping area; false otherwise.+ */+function isInsideClippingArea() {+ if (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]+ );+ 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;+ }+}++/**+ * Calculates the step spacing based on the current brush parameters.+ * @returns {number} The spacing value.+ */+function spacing() {+ const { param } = list.get(State.stroke.type) ?? {};+ if (!param) return 1;+ return param.spacing;+}++// ---------------------------------------------------------------------------+// Brush Tip Rendering Methods+// ---------------------------------------------------------------------------++/**+ * Draws the spray tip effect.+ * @param {number} pressure - Current pressure.+ */+function drawSpray(pressure) {+ const vibration =+ State.stroke.weight * current.p.scatter * pressure ++ (State.stroke.weight * rArray(gaussians) * current.p.scatter) / 3;+ const sw = current.p.weight * rr(0.9, 1.1);+ const iterations = Math.ceil(current.p.grain / pressure);+ for (let j = 0; j < iterations; j++) {+ const r = rr(0.9, 1.1);+ const rX = r * vibration * rr(-1, 1);+ const yRandomFactor = rr(-1, 1);+ const sqrtPart = Math.sqrt((r * vibration) ** 2 - rX ** 2);+ circle(+ _position.x + rX,+ _position.y + yRandomFactor * sqrtPart,+ sw,+ current.alpha,+ );+ }+}++/**+ * Draws the marker tip effect.+ * @param {number} pressure - Current pressure.+ * @param {boolean} [vibrate=true] - Whether to apply vibration.+ */+function drawMarker(pressure, vibrate = true, alpha = current.alpha) {+ const vibration = vibrate ? State.stroke.weight * current.p.scatter : 0;+ const rx = vibrate ? vibration * rr(-1, 1) : 0;+ const ry = vibrate ? vibration * rr(-1, 1) : 0;+ circle(+ _position.x + rx,+ _position.y + ry,+ State.stroke.weight * current.p.weight * pressure,+ alpha,+ );+}++/**+ * Draws a custom or image-based brush tip.+ * @param {number} pressure - Current pressure.+ * @param {number} alpha - Alpha (opacity) for drawing.+ * @param {boolean} [vibrate=true] - Whether to apply vibration.+ */+function drawTip(pressure, alpha, vibrate = true) {+ Mix.glMask.isDrawn = true;+ Mask.push();+ Mask.noStroke();+ let color = State.stroke.color;+ color.setAlpha(alpha);+ Mask.fill(State.stroke.color);+ const vibration = vibrate ? State.stroke.weight * current.p.scatter : 0;+ const rx = vibrate ? vibration * rr(-1, 1) : 0;+ const ry = vibrate ? vibration * rr(-1, 1) : 0;+ Mask.translate(_position.x + rx - Cwidth, _position.y + ry - Cheight);+ adjustSizeAndRotation(State.stroke.weight * pressure, alpha);+ current.p.tip(Mask);+ Mask.pop();+}++/**+ * Draws the default brush tip.+ * @param {number} pressure - Current pressure.+ */+function drawDefault(pressure, wiggle = 1) {+ wiggle = map(wiggle, 0, 1, 0.9, 1.05);+ const vibration =+ wiggle *+ State.stroke.weight *+ current.p.scatter *+ (current.p.sharpness ++ ((1 - current.p.sharpness) * rArray(gaussians)) / pressure);+ if (rr(0, current.p.grain * pressure) > 0.4) {+ let dx, dy;+ if (_plot) {+ dx = 0.7 * vibration * rr(-1, 1);+ dy = vibration * rr(-1, 1);+ } else {+ const perp = vibration * rr(-1, 1);+ const along = 0.3 * vibration * rr(-1, 1);+ dx = perp * -current.sin + along * current.cos;+ dy = perp * current.cos + along * current.sin;+ }+ circle(+ _position.x + dx,+ _position.y + dy,+ pressure *+ pressure *+ current.p.weight *+ rr(0.85, 1.15) *+ State.stroke.weight,+ Math.max(0.9, pressure) * current.alpha * rr(0.75, 1.1),+ );+ }+}++/**+ * Adjusts the size and rotation of the brush tip before rendering.+ * @param {number} pressure - Pressure-based scaling factor.+ * @param {number} alpha - Opacity value.+ */+function adjustSizeAndRotation(pressure, alpha) {+ Mask.scale(pressure);+ if (current.p.type === "image") {+ Mask.tint(255, 0, 0, alpha / 2);+ }+ let angle = 0;+ if (current.p.rotate === "random") angle = randInt(0, 360);+ else if (current.p.rotate === "natural") {+ angle =+ (_plot ? -_plot.angle(_position.plotted) : -_dir) + _position.angle();+ }+ Mask.rotate(angle);+}++/**+ * Draws the marker tip with a blend effect.+ */+function markerTip() {+ if (isInsideClippingArea()) {+ let pressure = calculatePressure();+ let alpha = calculateAlpha(pressure);+ if (current.p.type === "marker") {+ for (let s = 1; s < 10; s++) {+ drawMarker((pressure * s) / 10, false, alpha * 5);+ }+ glDraw();+ } else if (current.p.type === "custom" || current.p.type === "image") {+ for (let s = 1; s < 5; s++) {+ drawTip((pressure * s) / 5, alpha, false);+ }+ }+ }+}++// ---------------------------------------------------------------------------+// Basic Drawing Operations+// ---------------------------------------------------------------------------++/**+ * Draws a line using the current brush.+ * @param {number} x1 - Start x-coordinate.+ * @param {number} y1 - Start y-coordinate.+ * @param {number} x2 - End x-coordinate.+ * @param {number} y2 - End y-coordinate.+ */+export function line(x1, y1, x2, y2) {+ if (!State.stroke.isActive || !State.stroke.color) {+ throw new Error(+ "No brush or color set. Call brush.set('brushName', color) before drawing.",+ );+ }+ isFieldReady();+ let d = dist(x1, y1, x2, y2);+ if (d == 0) return;+ initializeDrawingState(x1, y1, d);+ let angle = calcAngle(x1, y1, x2, y2);+ draw(angle, false);+}++/**+ * Draws a stroke from a starting point in a given direction.+ * @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).+ */+export function flowLine(x, y, length, dir) {+ if (!State.stroke.isActive || !State.stroke.color) {+ throw new Error(+ "No brush or color set. Call brush.set('brushName', color) before drawing.",+ );+ }+ isFieldReady();+ initializeDrawingState(x, y, length);+ draw(toDegrees(dir), false);+}++/**+ * Draws a predefined plot.+ * @param {object} p - Shape object representing the plot.+ * @param {number} x - Starting x-coordinate.+ * @param {number} y - Starting y-coordinate.+ * @param {number} scale - Scale factor.+ */+function plot(p, x, y, scale) {+ isFieldReady();+ initializeDrawingState(x, y, p.length, p);+ draw(scale, true);+}++// ---------------------------------------------------------------------------+// Standard Brushes Definition and Initialization+// ---------------------------------------------------------------------------++/**+ * Defines a set of standard brushes with specific characteristics. Each brush is defined+ * with properties such as weight, vibration, definition, quality, opacity, spacing, and+ * pressure sensitivity. Some brushes have additional properties like type, tip, and rotate.+ */+const _vals = [+ "weight",+ "scatter",+ "sharpness",+ "grain",+ "opacity",+ "spacing",+ "pressure",+ "type",+ "tip",+ "rotate",+];+const _standard_brushes = [+ [+ "pen",+ [0.3, 0.15, 0.9, 2, 150, 0.1, { curve: [0.15, 0.2], min_max: [1.2, 1] }],+ ],+ [+ "rotring",+ [0.15, 0.05, 0.7, 15, 210, 0.1, { curve: [0.35, 0.2], min_max: [1.3, 1] }],+ ],+ [+ "2B",+ [0.3, 0.75, 0.45, 15, 180, 0.1, { curve: [0.1, 0.3], min_max: [1.1, 0.9] }],+ ],+ [+ "HB",+ [0.3, 0.6, 0.3, 10, 170, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],+ ],+ [+ "2H",+ [0.2, 0.6, 0.3, 4, 120, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],+ ],+ [+ "cpencil",+ [0.3, 0.55, 0.8, 7, 75, 0.1, { curve: [0.15, 0.2], min_max: [0.95, 1.2] }],+ ],+ [+ "charcoal",+ [+ 0.35,+ 1.5,+ 0.68,+ 500,+ 120,+ 0.03,+ { curve: [0.15, 0.4], min_max: [1.1, 0.95] },+ ],+ ],+ [+ "spray",+ [+ 0.2,+ 6,+ 15,+ 40,+ 90,+ 0.5,+ { curve: [0.2, 0.35], min_max: [0.7, 1] },+ "spray",+ ],+ ],+ [+ "marker",+ [+ 2,+ 0.12,+ null,+ null,+ 1,+ 0.03,+ { curve: [0.35, 0.25], min_max: [1.2, 0.85] },+ "marker",+ ],+ ],+];++for (let s of _standard_brushes) {+ let obj = {};+ for (let i = 0; i < s[1].length; i++) obj[_vals[i]] = s[1][i];+ add(s[0], obj);+}++// ---------------------------------------------------------------------------+// Extensions to Polygon and Plot Prototypes+// ---------------------------------------------------------------------------++/**+ * Draws the polygon using the current brush.+ * @param {boolean} [_brush=false] - Optional brush name override.+ * @param {string|Color} [_color] - Optional color override.+ * @param {number} [_weight] - Optional weight override.+ */+Polygon.prototype.draw = function (_brush = false, _color, _weight) {+ let state = BrushState();+ if (_brush) set(_brush, _color, _weight);+ if (state.isActive) {+ for (let s of this.sides) {+ line(s[0].x, s[0].y, s[1].x, s[1].y);+ }+ }+ BrushSetState(state);+};++/**+ * Draws the plot using the current brush.+ * @param {number} x - Starting x-coordinate.+ * @param {number} y - Starting y-coordinate.+ * @param {number} scale - Scale factor.+ */+Plot.prototype.draw = function (x, y, scale) {+ if (BrushState().isActive) {+ if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));+ plot(this, x, y, scale);+ }+};++// =============================================================================+// Section: Loading Custom Image Tips+// =============================================================================+/**+ * This section defines the functionality for managing the loading and processing of image tips.+ * Images are loaded from specified source URLs, converted to a white tint for visual effects,+ * and then stored for future use. It includes methods to add new images, convert their color+ * scheme, and integrate them into the p5.js graphics library.+ */++/**+ * Manages loading and processing of image tips.+ * Images are converted to white with inverted alpha for tinting via shaders.+ */+const T = {+ tips: new Map(),++ /**+ * Registers an image source for later loading.+ * @param {string} src - The source URL of the image.+ */+ add(src) {+ this.tips.set(src, false);+ },++ /**+ * Converts image to white with inverted alpha for tint-based rendering.+ * @param {object} image - The p5.Image to convert.+ */+ imageToWhite(image) {+ image.loadPixels();+ for (let i = 0; i < 4 * image.width * image.height; i += 4) {+ let average =+ (image.pixels[i] + image.pixels[i + 1] + image.pixels[i + 2]) / 3;+ image.pixels[i] = image.pixels[i + 1] = image.pixels[i + 2] = 255;+ image.pixels[i + 3] = 255 - average;+ }+ image.updatePixels();+ },++ /**+ * Loads all registered image tips. Returns a promise that resolves+ * when all images are loaded and processed.+ * @returns {Promise}+ */+ async load() {+ const entries = [...this.tips.keys()].filter((k) => !this.tips.get(k));+ await Promise.all(+ entries.map(+ (src) =>+ new Promise((resolve, reject) => {+ const nativeImg = new window.Image();+ nativeImg.onload = () => {+ const p5img = Renderer.createImage(+ nativeImg.naturalWidth,+ nativeImg.naturalHeight,+ );+ p5img.drawingContext.drawImage(nativeImg, 0, 0);+ T.imageToWhite(p5img);+ this.tips.set(src, p5img);+ resolve();+ };+ nativeImg.onerror = () =>+ reject(new Error(`Failed to load image tip: ${src}`));+ nativeImg.src = src;+ }),+ ),+ );+ },+};++/**+ * Loads all registered image tips. Must be awaited before setup/draw.+ * @returns {Promise}+ *+ * @example+ * // In your sketch:+ * await brush.preload();+ */+export async function preload() {+ await T.load();+}diff --git a/test/field_explorer.html b/test/field_explorer.htmlnew file mode 100644index 0000000..4fc9ab4--- /dev/null+++ b/test/field_explorer.html@@ -0,0 +1,122 @@+<!doctype html>+<html>+ <head>+ <title>Flow Field Explorer</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; margin: 0; padding: 0; }+ body { background: #e8e8e8; font-family: monospace; }+ #controls {+ padding: 10px 24px;+ background: #fff;+ border-bottom: 1px solid #ccc;+ display: flex;+ align-items: center;+ gap: 24px;+ font-size: 13px;+ }+ label { display: flex; align-items: center; gap: 6px; }+ select { font-family: monospace; font-size: 13px; padding: 3px 8px; }+ input[type=range] { width: 100px; }+ span.val { width: 28px; display: inline-block; }+ canvas { display: block; margin: 24px auto; box-shadow: 0 2px 12px rgba(0,0,0,0.15); }+ </style>+ </head>+ <body>+ <div id="controls">+ <label>+ Field:+ <select id="fieldSel"></select>+ </label>+ <label>+ Density:+ <input type="range" id="density" min="6" max="30" value="18">+ <span class="val" id="densityVal">18</span>+ </label>+ <label>+ Line length:+ <input type="range" id="lineLen" min="20" max="150" value="55">+ <span class="val" id="lineLenVal">55</span>+ </label>+ </div>++ <script>+ const FIELDS = ["curved", "zigzag", "waves", "seabed", "spiral", "columns", "hand"];++ // Read current params+ const params = new URLSearchParams(location.search);+ const currentField = params.get("field") || "curved";+ const currentDensity = parseInt(params.get("density") || "18");+ const currentLen = parseInt(params.get("len") || "55");++ // Populate select+ const sel = document.getElementById("fieldSel");+ FIELDS.forEach((f) => {+ const opt = document.createElement("option");+ opt.value = f;+ opt.textContent = f;+ if (f === currentField) opt.selected = true;+ sel.appendChild(opt);+ });++ // Sync slider displays+ const densityEl = document.getElementById("density");+ const densityVal = document.getElementById("densityVal");+ const lineLenEl = document.getElementById("lineLen");+ const lineLenVal = document.getElementById("lineLenVal");++ densityEl.value = currentDensity;+ densityVal.textContent = currentDensity;+ lineLenEl.value = currentLen;+ lineLenVal.textContent = currentLen;++ densityEl.addEventListener("input", () => { densityVal.textContent = densityEl.value; });+ lineLenEl.addEventListener("input", () => { lineLenVal.textContent = lineLenEl.value; });++ function navigate() {+ const f = sel.value;+ const d = densityEl.value;+ const l = lineLenEl.value;+ location.search = `?field=${f}&density=${d}&len=${l}`;+ }++ sel.addEventListener("change", navigate);+ densityEl.addEventListener("change", navigate);+ lineLenEl.addEventListener("change", navigate);++ // ---- p5 sketch ----+ function setup() {+ createCanvas(800, 800, WEBGL);+ brush.load();+ brush.scaleBrushes(3);+ background(245);+ translate(-width / 2, -height / 2);++ if (currentField === "hand") {+ brush.wiggle(5);+ } else {+ brush.field(currentField);+ }+ brush.set("HB", "#1a2a5a", 1);++ const n = currentDensity;+ for (let r = 0; r < n; r++) {+ for (let c = 0; c < n; c++) {+ const x = 40 + (c / (n - 1)) * 720;+ const y = 40 + (r / (n - 1)) * 720;+ brush.flowLine(x, y, currentLen, 0);+ }+ }++ brush.noField();+ noLoop();+ }++ function draw() {+ translate(-width / 2, -height / 2);+ noLoop();+ }+ </script>+ </body>+</html>diff --git a/test/index.html b/test/index.htmlnew file mode 100644index 0000000..2095fe1--- /dev/null+++ b/test/index.html@@ -0,0 +1,15 @@+<!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>+ <style>+ body { margin: 0; background: #111; display: flex; justify-content: center; }+ canvas { display: block; }+ </style>+ </head>+ <body>+ <script src="./sketch.js"></script>+ </body>+</html>diff --git a/test/pushpop_test.html b/test/pushpop_test.htmlnew file mode 100644index 0000000..bf8d4e1--- /dev/null+++ b/test/pushpop_test.html@@ -0,0 +1,182 @@+<!doctype html>+<html>+ <head>+ <meta charset="utf-8" />+ <title>p5.brush - Push/Pop 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;+ margin: 0;+ padding: 0;+ }+ body {+ background: #ccc;+ font-family: monospace;+ display: flex;+ flex-direction: column;+ align-items: center;+ padding: 20px;+ gap: 10px;+ }+ h1 {+ font-size: 13px;+ color: #333;+ letter-spacing: 0.05em;+ }+ p {+ font-size: 11px;+ color: #555;+ max-width: 760px;+ text-align: center;+ }+ canvas {+ display: block;+ box-shadow: 0 2px 16px rgba(0, 0, 0, 0.25);+ }+ </style>+ </head>+ <body>+ <h1>PUSH / POP TEST - p5.brush</h1>+ <p>+ Each column proves that p5's <b>push()</b> / <b>pop()</b> automatically+ saves & restores brush state. Inside the push block a different state+ is set; after pop the original state must be fully restored.<br />+ Col 1: <b>stroke color</b> | Col 2:+ <b>stroke weight + brush type</b> | Col 3:+ <b>fill color + opacity</b><br />+ Each column shows:+ <span style="color: #1a3a6a">■ before (blue)</span> — + <i>inside push (red, should differ)</i> — + <span style="color: #1a3a6a">■ after pop (must match before)</span>+ </p>++ <script>+ const CW = 760,+ CH = 500;+ const COLS = 3;+ const CellW = CW / COLS;+ const cx = (c) => c * CellW + CellW / 2;++ // Row y positions+ const Y_BEFORE = 100,+ Y_INSIDE = 250,+ Y_AFTER = 400;++ function setup() {+ createCanvas(CW, CH, WEBGL);+ brush.load();+ brush.scaleBrushes(1.5);+ noLoop();+ }++ function draw() {+ translate(-CW / 2, -CH / 2);+ background(248, 246, 238);++ // Grid dividers+ stroke(190);+ strokeWeight(1);+ noFill();+ for (let c = 1; c < COLS; c++) line(c * CellW, 0, c * CellW, CH);++ // Row labels (native p5 lines as separators)+ stroke(200);+ strokeWeight(0.5);+ line(0, Y_BEFORE - 50, CW, Y_BEFORE - 50);+ line(0, Y_INSIDE - 50, CW, Y_INSIDE - 50);+ line(0, Y_AFTER - 50, CW, Y_AFTER - 50);++ // ================================================================+ // COL 0 — stroke COLOR saved/restored+ // ================================================================+ // Set outer state: blue marker+ brush.pick("marker");+ brush.stroke("#1a3a6a");+ brush.strokeWeight(3);++ // BEFORE+ push();+ translate(cx(0), Y_BEFORE);+ brush.line(-60, 0, 60, 0);+ brush.line(0, -30, 0, 30);+ pop();++ // INSIDE push — change to red+ push();+ translate(cx(0), Y_INSIDE);+ brush.stroke("#c0392b");+ brush.line(-60, 0, 60, 0);+ brush.line(0, -30, 0, 30);+ pop();++ // AFTER pop — must be blue again+ push();+ translate(cx(0), Y_AFTER);+ brush.line(-60, 0, 60, 0);+ brush.line(0, -30, 0, 30);+ pop();++ // ================================================================+ // COL 1 — stroke WEIGHT + brush TYPE saved/restored+ // ================================================================+ brush.pick("HB");+ brush.stroke("#1a3a6a");+ brush.strokeWeight(1);+ brush.noFill();++ // BEFORE+ push();+ translate(cx(1), Y_BEFORE);+ brush.line(-60, 0, 60, 0);+ brush.line(0, -30, 0, 30);+ pop();++ // INSIDE push — heavy weight, different brush+ push();+ translate(cx(1), Y_INSIDE);+ brush.pick("charcoal");+ brush.stroke("#c0392b");+ brush.strokeWeight(6);+ brush.line(-60, 0, 60, 0);+ brush.line(0, -30, 0, 30);+ pop();++ // AFTER pop — must be HB thin blue again+ push();+ translate(cx(1), Y_AFTER);+ brush.line(-60, 0, 60, 0);+ brush.line(0, -30, 0, 30);+ pop();++ // ================================================================+ // COL 2 — FILL color + opacity saved/restored+ // ================================================================+ brush.noStroke();+ brush.fill("#1a3a6a", 70);+ brush.fillBleed(0.2);+ brush.fillTexture(0.4, 0.3);++ // BEFORE+ push();+ translate(cx(2), Y_BEFORE);+ brush.rect(-55, -35, 110, 70, "corner");+ pop();++ // INSIDE push — red fill, high opacity+ push();+ translate(cx(2), Y_INSIDE);+ brush.fill("#c0392b", 120);+ brush.rect(-55, -35, 110, 70, "corner");+ pop();++ // AFTER pop — must be blue 70 again+ push();+ translate(cx(2), Y_AFTER);+ brush.rect(-55, -35, 110, 70, "corner");+ pop();+ }+ </script>+ </body>+</html>diff --git a/test/sketch.js b/test/sketch.jsnew file mode 100644index 0000000..9452e1b--- /dev/null+++ b/test/sketch.js@@ -0,0 +1,578 @@+// ============================================================+// p5.brush Visual Test Suite+//+// 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)+// ============================================================++// ---- Layout constants ----+const CANVAS_W = 1400;+const CANVAS_H = 5200;+const MARGIN = 50;+const LABEL_W = 175; // width reserved for row labels+const ROW_H = 52; // height of one test row+const CONTENT_X = MARGIN + LABEL_W;+const CONTENT_W = CANVAS_W - MARGIN - LABEL_W - 40;++let currentY = MARGIN;+let labelBuf; // P2D overlay for labels (composited at the end)++const palette = ["#002185", "#c0392b", "#27ae60", "#8e44ad", "#e67e22"];+function col(i) {+ return palette[i % palette.length];+}++// ---- Label helpers (all draw to labelBuf so they don't interfere with brush) ----++function header(title) {+ labelBuf.noStroke();+ labelBuf.fill(15);+ labelBuf.textSize(12);+ labelBuf.textStyle(BOLD);+ labelBuf.text(title, MARGIN, currentY + 15);+ labelBuf.stroke(180);+ labelBuf.strokeWeight(0.7);+ labelBuf.line(MARGIN, currentY + 20, CANVAS_W - MARGIN, currentY + 20);+ currentY += 30;+}++function rowLabel(text) {+ labelBuf.noStroke();+ // White bg so label is readable over any brush strokes that bleed left+ labelBuf.fill(245);+ labelBuf.rect(MARGIN - 2, currentY + 2, LABEL_W - 3, ROW_H - 4);+ labelBuf.fill(70);+ labelBuf.textSize(10);+ labelBuf.textStyle(NORMAL);+ // Constrain text to label column so it never overlaps brush strokes+ labelBuf.text(text, MARGIN, currentY + ROW_H / 2 - 4, LABEL_W - 8, ROW_H);+}++function nextRow() {+ currentY += ROW_H;+}++function gap(px = 12) {+ currentY += px;+}++// ---- Error tests (runs before drawing, logged to console) ----++function runErrorTests() {+ // Each test: [description, function that SHOULD throw]+ const tests = [+ ["pick() with unknown brush name", () => brush.pick("__DOES_NOT_EXIST__")],+ [+ "line() without brush/color set",+ () => {+ brush.noStroke();+ brush.line(0, 0, 10, 10);+ },+ ],+ [+ "flowLine() without brush/color set",+ () => {+ brush.noStroke();+ brush.flowLine(0, 0, 100, 0);+ },+ ],+ ["vertex() called before beginShape()", () => brush.vertex(0, 0)],+ ["endShape() called before beginShape()", () => brush.endShape()],+ ["move() called before beginStroke()", () => brush.move(0, 100, 1)],+ ["endStroke() called before beginStroke()", () => brush.endStroke(0, 1)],+ [+ 'beginStroke() with invalid type (not "curve"/"segments")',+ () => brush.beginStroke("INVALID_TYPE", 0, 0),+ ],+ ["spline() with fewer than 2 points", () => brush.spline([[0, 0, 1]])],+ [+ "field() with unknown field name",+ () => brush.field("__DOES_NOT_EXIST__"),+ ],+ [+ "refreshField() when no field is active",+ () => {+ brush.noField();+ brush.refreshField();+ },+ ],+ ];++ let passed = 0;+ console.group(+ "%cp5.brush - Error Message Tests",+ "font-weight:bold;font-size:14px",+ );++ for (const [desc, fn] of tests) {+ try {+ fn();+ console.error(`[FAIL] ${desc}\n (no error was thrown)`);+ } catch (e) {+ console.log(+ `%c[PASS]%c ${desc}\n > "${e.message}"`,+ "color:green;font-weight:bold",+ "color:inherit",+ );+ passed++;+ }+ }++ const all = passed === tests.length;+ console.log(+ `\n%c${passed} / ${tests.length} passed`,+ all+ ? "color:green;font-weight:bold;font-size:13px"+ : "color:red;font-weight:bold;font-size:13px",+ );+ console.groupEnd();++ return { passed, total: tests.length };+}++// ================================================================+// MAIN SETUP+// ================================================================++async function setup() {+ randomSeed(42);+ brush.seed(42);+ brush.noiseSeed(42);++ createCanvas(CANVAS_W, CANVAS_H, WEBGL);+ brush.load();+ brush.scaleBrushes(5);+ angleMode(DEGREES);++ // P2D buffer for labels — transparent background so brush strokes show through+ labelBuf = createGraphics(CANVAS_W, CANVAS_H);+ labelBuf.textFont("monospace");+ labelBuf.textLeading(14);++ // Gray canvas background (visible where no brush strokes land)+ background(245);++ // Shift origin to top-left corner (WEBGL default is center)+ translate(-width / 2, -height / 2);++ // ---- Add image brush (must be awaited) ----+ await brush.add("imageTip", {+ type: "image",+ weight: 40,+ scatter: 0.15,+ opacity: 10,+ spacing: 1.5,+ pressure: [0.8, 1.2],+ rotate: "random",+ image: { src: "../example/brush_tips/brush.jpg" },+ });++ // ---- Add custom tip brush ----+ brush.add("diamondTip", {+ type: "custom",+ weight: 0.6,+ scatter: 0.15,+ sharpness: 0.5,+ grain: 8,+ opacity: 30,+ spacing: 0.8,+ pressure: [1, 1],+ rotate: "natural",+ tip: (_m) => {+ _m.rotate(45);+ _m.rect(-4, -4, 8, 8);+ },+ });++ // ---- Run error tests first (before modifying drawing state) ----+ brush.set("HB", "#000000", 1); // ensure canvas is ready for canvas-dependent checks+ const { passed, total } = runErrorTests();+ brush.set("HB", "#000000", 1); // restore clean state++ // ---- Title banner ----+ labelBuf.noStroke();+ labelBuf.fill(10);+ labelBuf.textSize(20);+ labelBuf.textStyle(BOLD);+ labelBuf.text("p5.brush Test Suite", MARGIN, currentY + 22);+ currentY += 34;++ const ok = passed === total;+ labelBuf.fill(ok ? "#1a7a1a" : "#b03030");+ labelBuf.textSize(11);+ labelBuf.textStyle(NORMAL);+ labelBuf.text(+ `Error tests: ${passed}/${total} ${ok ? "all passed" : "some FAILED"} - see browser console`,+ MARGIN,+ currentY + 14,+ );+ currentY += 28;+ gap();++ // ================================================================+ // SECTION 1 — STANDARD BRUSHES+ // ================================================================+ header("STANDARD BRUSHES");++ const customNames = new Set(["imageTip", "diamondTip", "_pt"]);+ for (const b of brush.box().filter((n) => !customNames.has(n))) {+ brush.set(b, col(brush.box().indexOf(b)), 1);+ rowLabel(b);+ brush.flowLine(CONTENT_X, currentY + ROW_H / 2, CONTENT_W, 0);+ nextRow();+ }+ gap();++ // ================================================================+ // SECTION 2 — PRESSURE CURVES+ // ================================================================+ header("PRESSURE CURVES (type: default, brush: pen weight)");++ const pressureCases = [+ { label: "[2, 0.3] heavy -> thin", p: [2, 0.3] },+ { label: "[0.3, 2] thin -> heavy", p: [0.3, 2] },+ { label: "[1.5, 0.3, 1.5] U-curve", p: [1.5, 0.3, 1.5] },+ { label: "[0.3, 1.5, 0.3] hill", p: [0.3, 1.5, 0.3] },+ { label: "[1, 1] flat", p: [1, 1] },+ ];++ for (const { label, p } of pressureCases) {+ brush.add("_pt", {+ type: "default",+ weight: 0.3,+ scatter: 3,+ sharpness: 0.3,+ grain: 8,+ opacity: 140,+ spacing: 0.1,+ pressure: p,+ });+ brush.set("_pt", "#1a1a1a", 1);+ rowLabel(label);+ brush.flowLine(CONTENT_X, currentY + ROW_H / 2, CONTENT_W, 0);+ nextRow();+ }+ gap();++ // ================================================================+ // SECTION 3 — BRUSH TYPES+ // ================================================================+ header("BRUSH TYPES");++ const typeTests = [+ { label: "custom tip (diamondTip)", name: "diamondTip", color: col(0) },+ { label: "image tip (imageTip)", name: "imageTip", color: col(0) },+ { label: "marker", name: "marker", color: col(1) },+ { label: "spray", name: "spray", color: col(2) },+ ];+ for (const t of typeTests) {+ brush.set(t.name, t.color, 1);+ rowLabel(t.label);+ brush.flowLine(CONTENT_X, currentY + ROW_H / 2, CONTENT_W, 0);+ nextRow();+ }+ gap();++ // ================================================================+ // SECTION 4 — FLOW FIELDS+ // ================================================================+ header("FLOW FIELDS (hatching reveals distortion per field)");++ const FIELD_GAP = 20;+ const FIELD_CELL_W = Math.floor((CONTENT_W - FIELD_GAP) / 2);+ const FIELD_CELL_H = 140;+ const FIELD_LINES = 9;++ // All fields except "hand"; add "hand" at end as wiggle demo+ const allFields = [...brush.listFields().filter((f) => f !== "hand"), "hand"];++ for (let fi = 0; fi < allFields.length; fi += 2) {+ for (let side = 0; side < 2 && fi + side < allFields.length; side++) {+ const name = allFields[fi + side];+ const cellX = CONTENT_X + side * (FIELD_CELL_W + FIELD_GAP);+ const cellY = currentY;+ const lineColor = col(fi + side);++ if (name === "hand") {+ brush.wiggle(5);+ } else {+ brush.field(name);+ }+ brush.set("HB", lineColor, 1);++ for (let li = 0; li < FIELD_LINES; li++) {+ const ly =+ cellY + 22 + (li / (FIELD_LINES - 1)) * (FIELD_CELL_H - 32);+ brush.flowLine(cellX, ly, FIELD_CELL_W, 0);+ }++ // Label above the hatch lines+ labelBuf.noStroke();+ labelBuf.fill(245);+ labelBuf.rect(cellX, cellY, 130, 18);+ labelBuf.fill(30);+ labelBuf.textSize(10);+ labelBuf.textStyle(BOLD);+ labelBuf.text(+ name === "hand" ? "hand [wiggle(5)]" : name,+ cellX + 4,+ cellY + 13,+ );+ }+ currentY += FIELD_CELL_H + 8;+ }++ brush.noField();+ gap();++ // ================================================================+ // SECTION 5 — PRIMITIVES+ // ================================================================+ header("PRIMITIVES");++ // line()+ brush.set("pen", col(0), 1);+ rowLabel("line()");+ brush.line(+ CONTENT_X,+ currentY + ROW_H / 2,+ CONTENT_X + 500,+ currentY + ROW_H / 2,+ );+ nextRow();++ // flowLine()+ brush.set("HB", col(1), 1);+ rowLabel("flowLine()");+ brush.flowLine(CONTENT_X, currentY + ROW_H / 2, 500, 0);+ nextRow();++ // circle()+ brush.set("pen", col(2), 1);+ rowLabel("circle()");+ brush.circle(CONTENT_X + 80, currentY + ROW_H / 2, 22, true);+ nextRow();++ // arc()+ brush.set("HB", col(3), 1);+ rowLabel("arc()");+ brush.arc(CONTENT_X + 80, currentY + ROW_H / 2 + 5, 22, 0, Math.PI * 1.5);+ nextRow();++ // rect()+ brush.set("cpencil", col(4), 1);+ rowLabel("rect()");+ brush.rect(CONTENT_X, currentY + 6, 260, ROW_H - 14);+ nextRow();++ // spline()+ brush.set("2B", col(0), 1);+ rowLabel("spline()");+ brush.spline(+ [+ [CONTENT_X, currentY + ROW_H - 10, 1],+ [CONTENT_X + 110, currentY + 10, 1],+ [CONTENT_X + 220, currentY + ROW_H - 10, 1],+ [CONTENT_X + 330, currentY + 10, 1],+ [CONTENT_X + 440, currentY + ROW_H - 10, 1],+ ],+ 0.5,+ );+ nextRow();++ // polygon()+ brush.set("pen", col(2), 1);+ rowLabel("polygon()");+ const px = CONTENT_X + 70,+ py = currentY + ROW_H / 2,+ pr = 22;+ brush.polygon([+ [px + pr * cos(0), py + pr * sin(0), 1],+ [px + pr * cos(72), py + pr * sin(72), 1],+ [px + pr * cos(144), py + pr * sin(144), 1],+ [px + pr * cos(216), py + pr * sin(216), 1],+ [px + pr * cos(288), py + pr * sin(288), 1],+ ]);+ nextRow();+ gap();++ // ================================================================+ // SECTION 6 — beginShape / vertex / endShape+ // ================================================================+ header("beginShape / vertex / endShape");++ // open shape+ brush.set("2B", col(0), 1);+ rowLabel("open shape (curvature 0.5)");+ brush.beginShape(0.5);+ for (let i = 0; i < 7; i++) {+ brush.vertex(+ CONTENT_X + i * 70,+ currentY + (i % 2 === 0 ? 10 : ROW_H - 10),+ );+ }+ brush.endShape(false);+ nextRow();++ // closed shape+ brush.set("HB", col(1), 1);+ rowLabel("closed shape (curvature 0.3)");+ brush.beginShape(0.3);+ brush.vertex(CONTENT_X + 40, currentY + ROW_H - 8);+ brush.vertex(CONTENT_X + 90, currentY + 8);+ brush.vertex(CONTENT_X + 140, currentY + ROW_H - 8);+ brush.vertex(CONTENT_X + 190, currentY + 8);+ brush.vertex(CONTENT_X + 240, currentY + ROW_H - 8);+ brush.endShape(true);+ nextRow();+ gap();++ // ================================================================+ // SECTION 7 — beginStroke / move / endStroke+ // ================================================================+ header("beginStroke / move / endStroke");++ brush.set("cpencil", col(0), 1);+ rowLabel('type: "curve"');+ brush.beginStroke("curve", CONTENT_X, currentY + ROW_H / 2);+ brush.move(15, 90, 1.0);+ brush.move(25, 90, 1.5);+ brush.move(-25, 90, 0.5);+ brush.move(-15, 90, 1.0);+ brush.move(0, 90, 1.2);+ brush.endStroke(0, 1);+ nextRow();++ brush.set("pen", col(3), 1);+ rowLabel('type: "segments"');+ brush.beginStroke("segments", CONTENT_X, currentY + ROW_H / 2);+ brush.move(20, 90, 1.0);+ brush.move(-20, 90, 1.5);+ brush.move(35, 90, 0.7);+ brush.move(-35, 90, 1.2);+ brush.move(0, 90, 1.0);+ brush.endStroke(0, 1);+ nextRow();+ gap();++ // ================================================================+ // SECTION 8 — HATCH+ // ================================================================+ header("HATCH");++ const hatchTests = [+ { label: "45deg basic", angle: 45, dist: 9, opts: {} },+ { label: "0deg horizontal", angle: 0, dist: 9, opts: {} },+ {+ label: "rand + continuous",+ angle: 30,+ dist: 8,+ opts: { rand: 0.2, continuous: true },+ },+ { label: "gradient (0.6)", angle: 60, dist: 6, opts: { gradient: 0.6 } },+ ];++ for (let hi = 0; hi < hatchTests.length; hi++) {+ const h = hatchTests[hi];+ brush.hatch(h.dist, h.angle, h.opts);+ brush.hatchStyle("HB", col(hi), 1);+ rowLabel(h.label);+ const hp = new brush.Polygon([+ [CONTENT_X, currentY + 5],+ [CONTENT_X + 260, currentY + 5],+ [CONTENT_X + 260, currentY + ROW_H - 6],+ [CONTENT_X, currentY + ROW_H - 6],+ ]);+ hp.hatch();+ brush.noHatch();+ nextRow();+ }+ gap();++ // ================================================================+ // SECTION 9 — FILL (watercolor)+ // ================================================================+ header("FILL (watercolor) rect + polygon per row");++ const FILL_ROW_H = 115;+ const FRECT_W = 230, FRECT_H = 90;+ const FCIRC_R = 45;+ const FCIRC_X = CONTENT_X + FRECT_W + 70 + FCIRC_R; // circle center x++ // Helper — draws one test row with rect + polygon-circle+ function fillRow(label, color, opacity, bleed, dir, texture, border) {+ brush.noStroke();+ brush.fill(color, opacity);+ brush.fillBleed(bleed, dir);+ brush.fillTexture(texture, border);+ rowLabel(label);+ const ry = currentY + (FILL_ROW_H - FRECT_H) / 2;+ brush.rect(CONTENT_X, ry, FRECT_W, FRECT_H);+ // Polygon approximating a circle (~24 verts)+ const cx = FCIRC_X, cy = currentY + FILL_ROW_H / 2;+ const n = 24;+ const pts = Array.from({ length: n }, (_, i) => {+ const a = (i / n) * Math.PI * 2;+ return [cx + FCIRC_R * Math.cos(a), cy + FCIRC_R * Math.sin(a)];+ });+ brush.polygon(pts);+ brush.noFill();+ currentY += FILL_ROW_H;+ }++ // Sub-section label helper+ function fillSubHeader(text) {+ labelBuf.noStroke();+ labelBuf.fill(120);+ labelBuf.textSize(9);+ labelBuf.textStyle(ITALIC);+ labelBuf.text(text, MARGIN, currentY + 12);+ currentY += 18;+ }++ // -- Bleed strength (direction: out) --+ fillSubHeader("bleed strength (texture 0.4, border 0.4, opacity 60)");+ fillRow("bleed 0.03 out", col(0), 60, 0.03, "out", 0.4, 0.4);+ fillRow("bleed 0.1 out", col(0), 60, 0.1, "out", 0.4, 0.4);+ fillRow("bleed 0.25 out", col(0), 60, 0.25, "out", 0.4, 0.4);+ fillRow("bleed 0.5 out", col(0), 60, 0.5, "out", 0.4, 0.4);++ // -- Bleed direction --+ fillSubHeader("bleed direction (bleed 0.2, texture 0.4, border 0.4, opacity 60)");+ fillRow("direction: out", col(1), 60, 0.2, "out", 0.4, 0.4);+ fillRow("direction: in", col(1), 60, 0.2, "in", 0.4, 0.4);++ // -- Texture strength --+ fillSubHeader("texture strength (bleed 0.1, border 0.4, opacity 60)");+ fillRow("texture 0.05", col(2), 60, 0.1, "out", 0.05, 0.4);+ fillRow("texture 0.3", col(2), 60, 0.1, "out", 0.3, 0.4);+ fillRow("texture 0.7", col(2), 60, 0.1, "out", 0.7, 0.4);+ fillRow("texture 1.0", col(2), 60, 0.1, "out", 1.0, 0.4);++ // -- Border strength --+ fillSubHeader("border strength (bleed 0.1, texture 0.4, opacity 60)");+ fillRow("border 0.05", col(3), 60, 0.1, "out", 0.4, 0.05);+ fillRow("border 0.3", col(3), 60, 0.1, "out", 0.4, 0.3);+ fillRow("border 0.7", col(3), 60, 0.1, "out", 0.4, 0.7);+ fillRow("border 1.0", col(3), 60, 0.1, "out", 0.4, 1.0);++ // -- Opacity --+ fillSubHeader("opacity (bleed 0.1, texture 0.4, border 0.4)");+ fillRow("opacity 20", col(4), 20, 0.1, "out", 0.4, 0.4);+ fillRow("opacity 50", col(4), 50, 0.1, "out", 0.4, 0.4);+ fillRow("opacity 90", col(4), 90, 0.1, "out", 0.4, 0.4);+ fillRow("opacity 140", col(4), 140, 0.1, "out", 0.4, 0.4);++ // ---- Composite label overlay on top of brush rendering ----+ // (draw() runs after postsetup which composites the final brush pass)+}++// draw() runs after postsetup — ideal moment to overlay labels+function draw() {+ // WEBGL resets transforms each frame; re-translate to top-left+ translate(-width / 2, -height / 2);+ image(labelBuf, 0, 0, width, height);+ noLoop(); // static sketch — draw only once+}diff --git a/test/transform_test.html b/test/transform_test.htmlnew file mode 100644index 0000000..d73ee95--- /dev/null+++ b/test/transform_test.html@@ -0,0 +1,228 @@+<!doctype html>+<html>+ <head>+ <meta charset="utf-8" />+ <title>p5.brush - Transform 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;+ margin: 0;+ padding: 0;+ }+ body {+ background: #ccc;+ font-family: monospace;+ display: flex;+ flex-direction: column;+ align-items: center;+ padding: 20px;+ gap: 10px;+ }+ h1 {+ font-size: 13px;+ color: #333;+ letter-spacing: 0.05em;+ }+ p {+ font-size: 11px;+ color: #555;+ max-width: 760px;+ text-align: center;+ }+ canvas {+ display: block;+ box-shadow: 0 2px 16px rgba(0, 0, 0, 0.25);+ }+ </style>+ </head>+ <body>+ <h1>TRANSFORM TEST - p5.brush</h1>+ <p>+ Red = native p5 lines/rect at the exact same coordinates as brush marks —+ they must align perfectly.<br />+ Col 1: <b>translate(+80, -40)</b> | Col 2:+ <b>rotate(PI/5)</b> | Col 3: <b>scale(1.8)</b><br />+ Row 1: strokes | Row 2: fills+ </p>++ <script>+ // Canvas / grid layout+ const CW = 760,+ CH = 600;+ const COLS = 3,+ ROWS = 2;+ const CellW = CW / COLS; // 253+ const CellH = CH / ROWS; // 300+ const cx = (c) => c * CellW + CellW / 2;+ const cy = (r) => r * CellH + CellH / 2;++ // Colours+ const BLUE = "#1a3a6a";+ const RED = "#c0392b";+ const OLIVE = "#4a6a1a";++ // ----------------------------------------------------------------+ // p5 sketch+ // ----------------------------------------------------------------+ function setup() {+ createCanvas(CW, CH, WEBGL);+ brush.load();+ brush.scaleBrushes(2);+ noLoop();+ }++ function draw() {+ // Shift origin to top-left (standard for p5.brush in WEBGL mode)+ translate(-CW / 2, -CH / 2);+ background(248, 246, 238);++ // ---- grid lines & column headers ----+ stroke(190);+ strokeWeight(1);+ noFill();+ for (let c = 1; c < COLS; c++) line(c * CellW, 0, c * CellW, CH);+ line(0, CellH, CW, CellH);++ // ================================================================+ // HELPER: native p5 lines at the exact same coords as brushLines()+ // ================================================================+ function refLines() {+ stroke(220, 30, 30);+ strokeWeight(0.5);+ noFill();+ line(-60, 0, 60, 0);+ line(0, -40, 0, 40);+ line(-50, -20, 50, 20);+ noStroke();+ }++ // ================================================================+ // HELPER: native p5 rect + fill at the exact same coords as brushFill()+ // ================================================================+ function refRect(hex) {+ // translucent fill matching brush opacity (~80/255 ≈ 31%)+ const c = color(hex);+ fill(red(c), green(c), blue(c), 80);+ stroke(220, 30, 30);+ strokeWeight(2);+ rect(-55, -40, 110, 80);+ noFill();+ noStroke();+ }++ // ================================================================+ // HELPER: draw the same brush stroke pattern at local (0,0)+ // ================================================================+ function brushLines(color) {+ brush.set("HB", color, 1.2);+ brush.line(-60, 0, 60, 0); // horizontal line through origin+ brush.line(0, -40, 0, 40); // vertical line through origin+ brush.set("2B", color, 0.8);+ brush.line(-50, -20, 50, 20); // diagonal+ }++ // ================================================================+ // HELPER: draw a brush fill rect centred at (0,0)+ // ================================================================+ function brushFill(color) {+ brush.noStroke();+ brush.fill(color, 200);+ brush.fillBleed(0.3);+ brush.fillTexture(0.5, 0.4);+ brush.rect(-55, -40, 110, 80, "corner");+ brush.noFill();+ }++ const r0 = 0;+ const dashLen = 3,+ gapLen = 4,+ unit = dashLen + gapLen;++ // Col 0 — translate+ push();+ translate(cx(0), cy(r0));+ stroke(180);+ strokeWeight(0.5);+ for (let d = -70; d < 70; d += unit)+ line(d, 0, Math.min(d + dashLen, 70), 0);+ for (let d = -60; d < 60; d += unit)+ line(0, d, 0, Math.min(d + dashLen, 60));+ push();+ translate(80, -40);+ refLines();+ brushLines(BLUE);+ pop();+ pop();++ // Col 1 — rotate+ push();+ translate(cx(1), cy(r0));+ stroke(180);+ strokeWeight(0.5);+ for (let d = -70; d < 70; d += unit)+ line(d, 0, Math.min(d + dashLen, 70), 0);+ for (let d = -60; d < 60; d += unit)+ line(0, d, 0, Math.min(d + dashLen, 60));+ push();+ rotate(Math.PI / 5);+ refLines();+ brushLines(RED);+ pop();+ pop();++ // Col 2 — scale+ push();+ translate(cx(2), cy(r0));+ stroke(180);+ strokeWeight(0.5);+ for (let d = -70; d < 70; d += unit)+ line(d, 0, Math.min(d + dashLen, 70), 0);+ for (let d = -60; d < 60; d += unit)+ line(0, d, 0, Math.min(d + dashLen, 60));+ push();+ scale(1.8);+ refLines();+ brushLines(OLIVE);+ pop();+ pop();++ // ================================================================+ // ROW 1 — FILL TESTS+ // ================================================================+ const r1 = 1;++ // Col 0 — translate+ push();+ translate(cx(0), cy(r1));+ push();+ translate(80, -40);+ refRect(BLUE);+ brushFill(BLUE);+ pop();+ pop();++ // Col 1 — rotate+ push();+ translate(cx(1), cy(r1));+ push();+ rotate(Math.PI / 5);+ refRect(RED);+ brushFill(RED);+ pop();+ pop();++ // Col 2 — scale+ push();+ translate(cx(2), cy(r1));+ push();+ scale(1.8);+ refRect(OLIVE);+ brushFill(OLIVE);+ pop();+ pop();+ }+ </script>+ </body>+</html>diff --git a/test/unit.test.js b/test/unit.test.jsnew file mode 100644index 0000000..199d55b--- /dev/null+++ b/test/unit.test.js@@ -0,0 +1,262 @@+// ============================================================+// p5.brush Unit Tests (Vitest)+//+// Tests pure utility functions that have no browser dependency.+// Run: npm test+// ============================================================++import { describe, it, expect, vi, beforeAll } from "vitest";++// Mock color.js (pulls in GLSL shaders and WebGL — not available in Node)+vi.mock("../src2/core/color.js", () => ({+ Renderer: {+ angleMode: () => "radians",+ RADIANS: "radians",+ DEGREES: "degrees",+ },+ Mix: {},+ State: {},+ Cwidth: 800,+ Cheight: 600,+ isCanvasReady: () => {},+ isMixReady: () => {},+}));++import {+ map,+ constrain,+ dist,+ cos,+ sin,+ rotate,+ intersectLines,+ rr,+ randInt,+ seed,+ weightedRand,+} from "../src2/core/utils.js";++// ---- map() ----+describe("map()", () => {+ it("maps midpoint correctly", () => {+ expect(map(5, 0, 10, 0, 100)).toBeCloseTo(50);+ });++ it("maps minimum", () => {+ expect(map(0, 0, 10, 0, 100)).toBeCloseTo(0);+ });++ it("maps maximum", () => {+ expect(map(10, 0, 10, 0, 100)).toBeCloseTo(100);+ });++ it("maps to inverted range", () => {+ expect(map(0, 0, 10, 100, 0)).toBeCloseTo(100);+ expect(map(10, 0, 10, 100, 0)).toBeCloseTo(0);+ });++ it("clamps when withinBounds=true", () => {+ expect(map(20, 0, 10, 0, 100, true)).toBeCloseTo(100);+ expect(map(-5, 0, 10, 0, 100, true)).toBeCloseTo(0);+ });++ it("does NOT clamp by default", () => {+ expect(map(20, 0, 10, 0, 100)).toBeCloseTo(200);+ });+});++// ---- constrain() ----+describe("constrain()", () => {+ it("returns value when within bounds", () => {+ expect(constrain(5, 0, 10)).toBe(5);+ });++ it("clamps to lower bound", () => {+ expect(constrain(-3, 0, 10)).toBe(0);+ });++ it("clamps to upper bound", () => {+ expect(constrain(15, 0, 10)).toBe(10);+ });++ it("handles equal bounds", () => {+ expect(constrain(7, 5, 5)).toBe(5);+ });+});++// ---- dist() ----+describe("dist()", () => {+ it("returns 0 for same point", () => {+ expect(dist(3, 4, 3, 4)).toBe(0);+ });++ it("returns correct Euclidean distance", () => {+ expect(dist(0, 0, 3, 4)).toBeCloseTo(5);+ });++ it("is symmetric", () => {+ expect(dist(1, 2, 5, 6)).toBeCloseTo(dist(5, 6, 1, 2));+ });+});++// ---- cos() / sin() — degree-based lookup table ----+describe("cos() and sin()", () => {+ it("cos(0) === 1", () => expect(cos(0)).toBeCloseTo(1));+ it("cos(90) === 0", () => expect(cos(90)).toBeCloseTo(0, 3));+ it("cos(180) === -1", () => expect(cos(180)).toBeCloseTo(-1));+ it("sin(0) === 0", () => expect(sin(0)).toBeCloseTo(0, 3));+ it("sin(90) === 1", () => expect(sin(90)).toBeCloseTo(1));+ it("sin(180) === 0", () => expect(sin(180)).toBeCloseTo(0, 3));++ it("cos² + sin² === 1 for arbitrary angle", () => {+ const a = 37;+ expect(cos(a) ** 2 + sin(a) ** 2).toBeCloseTo(1);+ });++ it("handles negative angles", () => {+ expect(cos(-90)).toBeCloseTo(cos(270));+ });++ it("handles angles > 360", () => {+ expect(cos(450)).toBeCloseTo(cos(90));+ });+});++// ---- rotate() ----+describe("rotate()", () => {+ it("rotating (1,0) by 90° around origin gives ~(0,1)", () => {+ const r = rotate(0, 0, 1, 0, 90);+ expect(r.x).toBeCloseTo(0, 3);+ expect(r.y).toBeCloseTo(-1, 3); // y-down coordinate system+ });++ it("rotating by 0° returns same point", () => {+ const r = rotate(0, 0, 5, 3, 0);+ expect(r.x).toBeCloseTo(5);+ expect(r.y).toBeCloseTo(3);+ });++ it("rotating by 360° returns same point", () => {+ const r = rotate(2, 2, 7, 5, 360);+ expect(r.x).toBeCloseTo(7);+ expect(r.y).toBeCloseTo(5);+ });+});++// ---- intersectLines() ----+describe("intersectLines()", () => {+ const mkPt = (x, y) => ({ x, y });++ it("finds intersection of two crossing lines", () => {+ const pt = intersectLines(+ mkPt(0, 0), mkPt(10, 10),+ mkPt(0, 10), mkPt(10, 0),+ true,+ );+ expect(pt).not.toBe(false);+ expect(pt.x).toBeCloseTo(5);+ expect(pt.y).toBeCloseTo(5);+ });++ it("returns false for parallel lines", () => {+ const pt = intersectLines(+ mkPt(0, 0), mkPt(10, 0),+ mkPt(0, 5), mkPt(10, 5),+ true,+ );+ expect(pt).toBe(false);+ });++ it("returns false when intersection is outside second segment bounds (default)", () => {+ // Segment 1: long horizontal at y=-5+ // Segment 2: short vertical from y=0 to y=3 — intersection at y=-5 is outside it+ const pt = intersectLines(+ mkPt(0, -5), mkPt(10, -5),+ mkPt(5, 0), mkPt(5, 3),+ );+ expect(pt).toBe(false);+ });++ it("returns false for point-like segments", () => {+ const pt = intersectLines(+ mkPt(0, 0), mkPt(0, 0),+ mkPt(1, 0), mkPt(2, 0),+ );+ expect(pt).toBe(false);+ });+});++// ---- rr() and randInt() — seeded RNG ----+describe("rr() — seeded random", () => {+ beforeAll(() => seed(42));++ it("returns a number in [min, max)", () => {+ for (let i = 0; i < 50; i++) {+ const v = rr(5, 10);+ expect(v).toBeGreaterThanOrEqual(5);+ expect(v).toBeLessThan(10);+ }+ });++ it("default range is [0, 1)", () => {+ for (let i = 0; i < 50; i++) {+ const v = rr();+ expect(v).toBeGreaterThanOrEqual(0);+ expect(v).toBeLessThan(1);+ }+ });++ it("produces consistent values with same seed", () => {+ seed(1234);+ const a = rr(0, 100);+ seed(1234);+ const b = rr(0, 100);+ expect(a).toBeCloseTo(b);+ });+});++describe("randInt()", () => {+ beforeAll(() => seed(42));++ it("returns integers in range", () => {+ for (let i = 0; i < 100; i++) {+ const v = randInt(0, 10);+ expect(Number.isInteger(v)).toBe(true);+ expect(v).toBeGreaterThanOrEqual(0);+ expect(v).toBeLessThan(10);+ }+ });+});++// ---- weightedRand() ----+describe("weightedRand()", () => {+ beforeAll(() => seed(99));++ it("always returns a key from the weights object", () => {+ const weights = { a: 1, b: 2, c: 7 };+ for (let i = 0; i < 100; i++) {+ const v = weightedRand(weights);+ expect(["a", "b", "c"]).toContain(String(v));+ }+ });++ it("returns numeric keys as numbers", () => {+ const weights = { 1: 1, 2: 2, 3: 7 };+ for (let i = 0; i < 100; i++) {+ const v = weightedRand(weights);+ expect(typeof v).toBe("number");+ }+ });++ it("strongly favours the high-weight key", () => {+ const weights = { rare: 1, common: 999 };+ seed(0);+ const counts = { rare: 0, common: 0 };+ for (let i = 0; i < 500; i++) {+ const v = String(weightedRand(weights));+ counts[v]++;+ }+ // common should win more than 98% of the time+ expect(counts.common).toBeGreaterThan(480);+ });+});diff --git a/vitest.config.js b/vitest.config.jsnew file mode 100644index 0000000..c16046f--- /dev/null+++ b/vitest.config.js@@ -0,0 +1,8 @@+import { defineConfig } from "vitest/config";++export default defineConfig({+ test: {+ environment: "node",+ include: ["test/**/*.test.js"],+ },+});