Unlock custom brushes, natural fill effects and intuitive hatching in p5.js
Remove tests
acamposuribe6ca8015e639b
diff --git a/benchmark/bench.mjs b/benchmark/bench.mjsdeleted file mode 100644index f22a7c2..0000000--- a/benchmark/bench.mjs+++ /dev/null@@ -1,213 +0,0 @@-/**- * p5.brush Performance Benchmark- * ================================- * Imports directly from source files to ensure benchmark always reflects- * the actual implementation. Uses a custom ESM loader to stub GLSL shaders.- *- * Run via: node --experimental-loader ./benchmark/loader.mjs benchmark/bench.mjs- * Outputs METRIC lines for autoresearch.- */--import { performance } from "perf_hooks";-import { setTargetState, setTargetRuntime } from "../src/core/target.js";-import { setRuntime } from "../src/core/runtime.js";-import {- cos, sin, gaussian, map, rr, randInt, constrain, dist, rotate, intersectLines, seed,-} from "../src/core/utils.js";-import { Plot } from "../src/core/plot.js";-import { Polygon } from "../src/core/polygon.js";-import { hatch, getHatchLines } from "../src/hatch/hatch.js";-import { isFieldReady, Position, noField } from "../src/core/flowfield.js";-import { Mix } from "../src/core/color.js";-import { fill, fillBleed, fillTexture, createFill } from "../src/fill/fill.js";--// Mock canvas context for fill benchmarking-const mockCtx = {- save: () => {}, restore: () => {}, beginPath: () => {}, fill: () => {}, stroke: () => {},- closePath: () => {}, moveTo: () => {}, lineTo: () => {}, arc: () => {},- setTransform: () => {}, strokeStyle: '', lineCap: '', lineWidth: 0, fillStyle: '',- globalCompositeOperation: 'source-over',- getTransform: () => ({ a: 1, b: 0, c: 0, d: 1, e: 400, f: 300 }),-};--// Setup minimal environment-setTargetState({ Cwidth: 800, Cheight: 600, Density: 1, Renderer: { loaded: true } });-setTargetRuntime({ isCanvasReady: () => {}, syncDensity: () => 1 });-setRuntime({ createColor: (r, g, b) => ({ r, g, b }), getAffineMatrix: () => ({ a: 1, b: 0, c: 0, d: 1, x: 0, y: 0 }), usesRadians: () => false });-Mix.ctx = mockCtx;-Mix.isBrush = false; Mix.justChanged = false; Mix.blend = () => {}; Mix.mask = null; Mix.markDirtyRect = () => {};--seed(42);-isFieldReady();-noField();--fill(255, 0, 0, 150); fillBleed(0.07); fillTexture(0.8, 0.5);--// ============================================================-// BENCHMARK RUNNER-// ============================================================--function bench(fn, iterations) {- // Warmup- for (let i = 0; i < Math.min(Math.ceil(iterations / 10), 100); i++) fn();- // Timed run- const t0 = performance.now();- for (let i = 0; i < iterations; i++) fn();- return performance.now() - t0;-}--function medianOf(arr) {- const sorted = [...arr].sort((a, b) => a - b);- const mid = Math.floor(sorted.length / 2);- return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;-}--const RUNS = 7;--// ============================================================-// 1. TRIG LOOKUP (cos/sin from utils.js)-// ============================================================-function benchTrig() {- let sum = 0;- for (let i = 0; i < 10000; i++) {- sum += cos(i * 0.1) + sin(i * 0.1 + 45.3);- }- return sum;-}-const trigMs = medianOf(Array.from({ length: RUNS }, () => bench(benchTrig, 100)));--// ============================================================-// 2. GAUSSIAN RANDOM (Box-Muller from utils.js)-// ============================================================-function benchGaussian() {- let sum = 0;- for (let i = 0; i < 1000; i++) sum += gaussian(0, 1);- return sum;-}-const gaussMs = medianOf(Array.from({ length: RUNS }, () => bench(benchGaussian, 200)));--// ============================================================-// 3. PLOT: calcIndex + angle + pressure-// ============================================================-const testPlot = new Plot("curve");-for (let i = 0; i < 20; i++) testPlot.addSegment(i * 18, 50, 0.8);-testPlot.endPlot(0, 1.0);--function benchPlot() {- let sum = 0;- for (let d = 0; d < testPlot.length; d += 2) {- sum += testPlot.angle(d) + testPlot.pressure(d);- }- return sum;-}-const plotMs = medianOf(Array.from({ length: RUNS }, () => bench(benchPlot, 2000)));--// ============================================================-// 4. HATCH: scanlineHatch (via getHatchLines)-// ============================================================-const hatchPolyPts = [];-for (let i = 0; i < 200; i++) {- const a = (i / 200) * 2 * Math.PI;- hatchPolyPts.push([Math.cos(a) * 200, Math.sin(a) * 200]);-}-const hatchPolygon = new Polygon(hatchPolyPts);-hatch(8, 45);--function benchHatch() {- return getHatchLines([hatchPolygon]);-}-const hatchMs = medianOf(Array.from({ length: RUNS }, () => bench(benchHatch, 200)));--// ============================================================-// 5. POLYGON: intersect (via cached intersection)-// ============================================================-const bigPolygon = (() => {- const pts = [];- for (let i = 0; i < 60; i++) {- const a = (i / 60) * 2 * Math.PI;- pts.push([Math.cos(a) * 150, Math.sin(a) * 150]);- }- return new Polygon(pts);-})();--function benchIntersect() {- // Clear cache to force fresh computation- bigPolygon._intersectionCache = {};- let count = 0;- for (let y = -120; y < 120; y += 10) {- const line = { point1: { x: -200, y }, point2: { x: 200, y } };- count += bigPolygon.intersect(line).length;- }- return count;-}-const intersectMs = medianOf(Array.from({ length: RUNS }, () => bench(benchIntersect, 500)));--// ============================================================-// 6. POSITION.movePos() — core stroke rendering loop-// ============================================================-const movePlot = new Plot("curve");-for (let i = 0; i < 10; i++) movePlot.addSegment(i * 36, 100, 0.8);-movePlot.endPlot(0, 1.0);--function benchMovePos() {- // Simulate a brush stroke: moveTo (direction-based) + plotTo (plot-based)- let total = 0;- for (let i = 0; i < 5; i++) {- const pos = new Position(400, 300);- pos.moveTo(45 + i * 30, 200, 1);- total += pos.x;- }- for (let i = 0; i < 5; i++) {- const pos = new Position(400, 300);- pos.plotTo(movePlot, 500, 1, 1);- total += pos.x;- }- return total;-}-const movePosMs = medianOf(Array.from({ length: RUNS }, () => bench(benchMovePos, 200)));--// ============================================================-// 7. INTERSECT LINES: raw intersectLines() from utils.js-// ============================================================-function benchIntersectLines() {- let count = 0;- const p1 = { x: -200, y: 0 }, p2 = { x: 200, y: 0 };- for (let i = 0; i < 1000; i++) {- const a = { x: i * 0.5 - 100, y: -50 };- const b = { x: i * 0.3 + 50, y: 50 };- if (intersectLines(p1, p2, a, b)) count++;- }- return count;-}-const intersectLinesMs = medianOf(Array.from({ length: RUNS }, () => bench(benchIntersectLines, 500)));--// ============================================================-// 8. FILL: createFill() watercolor hot path-// ============================================================-const fillPolyPts = [];-for (let i = 0; i < 30; i++) {- const a = (i / 30) * 2 * Math.PI;- fillPolyPts.push([Math.cos(a) * 100, Math.sin(a) * 100]);-}-const fillPolygon = new Polygon(fillPolyPts);--function benchFill() {- seed(42);- createFill(fillPolygon);-}-const fillMs = medianOf(Array.from({ length: RUNS }, () => bench(benchFill, 30)));--// ============================================================-// TOTAL (primary metric)-// ============================================================-const total_ms = trigMs + gaussMs + plotMs + hatchMs + intersectMs + intersectLinesMs + movePosMs + fillMs;--console.log(`METRIC total_ms=${total_ms.toFixed(3)}`);-console.log(`METRIC trig_ms=${trigMs.toFixed(3)}`);-console.log(`METRIC gauss_ms=${gaussMs.toFixed(3)}`);-console.log(`METRIC plot_ms=${plotMs.toFixed(3)}`);-console.log(`METRIC hatch_ms=${hatchMs.toFixed(3)}`);-console.log(`METRIC intersect_ms=${intersectMs.toFixed(3)}`);-console.log(`METRIC intersect_lines_ms=${intersectLinesMs.toFixed(3)}`);-console.log(`METRIC movepos_ms=${movePosMs.toFixed(3)}`);-console.log(`METRIC fill_ms=${fillMs.toFixed(3)}`);diff --git a/benchmark/bench_mass_profile.html b/benchmark/bench_mass_profile.htmldeleted file mode 100644index 9a5c976..0000000--- a/benchmark/bench_mass_profile.html+++ /dev/null@@ -1,111 +0,0 @@-<!DOCTYPE html>-<html>-<head><meta charset="utf-8"/><title>mass.js pipeline profiler</title></head>-<body style="margin:0;background:#000">-<div id="host" style="position:fixed;left:-9999px;top:-9999px;visibility:hidden"></div>-<script type="module">- import * as brush from '../dist/brush.esm.js';- // Profiling accumulators are exposed on globalThis by the instrumented bundle- const _prof = () => window.__massProf;- const _arcProf = () => window.__arcProf;- const _sProf = () => window.__strokeProf;- function resetAll() {- window.__massProfReset?.();- window.__arcProfReset?.();- window.__strokeProfReset?.();- }-- const CW = 400, CH = 400;- brush.createCanvas(CW, CH, { parent: '#host', pixelDensity: 1 });- brush.scaleBrushes(1);-- const syncCanvas = document.createElement('canvas');- syncCanvas.width = 1; syncCanvas.height = 1;- const syncCtx = syncCanvas.getContext('2d', { willReadFrequently: true });- const mainCanvas = document.querySelector('#host canvas');- function gpuSync() {- syncCtx.drawImage(mainCanvas, 0, 0, 1, 1, 0, 0, 1, 1);- syncCtx.getImageData(0, 0, 1, 1);- }-- const WARMUP = 5, RUNS = 15;---- // warmup- for (let i = 0; i < WARMUP; i++) {- brush.seed(42 + i); brush.clear('#fffceb'); brush.wiggle();- brush.mass('HB', '#335588', { precision: 0.3, strength: 0.6, gradient: 0.1 });- brush.set('HB', '#000', 0.5);- brush.circle(CW / 2, CH / 2, 90);- brush.noMass();- brush.render(); gpuSync();- }-- resetAll();-- const t_total0 = performance.now();- for (let i = 0; i < RUNS; i++) {- brush.seed(42 + i); brush.clear('#fffceb'); brush.wiggle();- brush.mass('HB', '#335588', { precision: 0.3, strength: 0.6, gradient: 0.1 });- brush.set('HB', '#000', 0.5);- brush.circle(CW / 2, CH / 2, 90);- brush.noMass();- brush.render(); gpuSync();- }- const t_total = (performance.now() - t_total0) / RUNS;-- const p = _prof(), a = _arcProf(), s = _sProf();- const perRun = v => (v / RUNS).toFixed(2);-- const breakdown = {- total_per_run_ms: t_total.toFixed(2),- // mass.js phases- getMassPolygons_ms: perRun(p.getMassPolygons_ms),- getHatchLines_ms: perRun(p.getHatchLines_ms),- geometry_per_arc_ms: perRun(p.geometry_ms),- arc_call_total_ms: perRun(p.arc_ms), // = plotConstruct + plotDraw- // arc() breakdown (primitives.js)- plotConstruct_ms: perRun(a.plotConstruct_ms),- plotDraw_ms: perRun(a.plotDraw_ms), // = saveState + gaussians + loop + restoreState- // stroke draw() breakdown- saveState_ms: perRun(s.saveState_ms),- gaussians_ms: perRun(s.gaussians_ms),- angleCalc_ms: perRun(s.angleCalc_ms), // _plot.angle() per step- tip_ms: perRun(s.tip_ms),- move_ms: perRun(s.move_ms), // plotTo / moveTo per step- restoreState_glDraw_ms: perRun(s.restoreState_ms),- // counts- nArcs_per_run: (p.nArcs / RUNS).toFixed(1),- nLines_per_run: (p.nLines / RUNS).toFixed(1),- nSteps_per_run: (s.nSteps / RUNS).toFixed(0),- nStrokes_per_run: (s.nStrokes / RUNS).toFixed(1),- };-- console.log('\n=== mass.js deep profile ===\n');- console.log(`Total per run : ${breakdown.total_per_run_ms} ms`);- console.log(`\n-- mass.js phases --`);- console.log(` getMassPolygons : ${breakdown.getMassPolygons_ms} ms`);- console.log(` getHatchLines (total) : ${breakdown.getHatchLines_ms} ms`);- console.log(` geometry / arc math : ${breakdown.geometry_per_arc_ms} ms`);- console.log(` arc() calls (total) : ${breakdown.arc_call_total_ms} ms`);- console.log(`\n-- arc() breakdown (primitives.js) --`);- console.log(` Plot construction : ${breakdown.plotConstruct_ms} ms`);- console.log(` p.draw() / stroke : ${breakdown.plotDraw_ms} ms`);- console.log(`\n-- stroke draw() loop --`);- console.log(` saveState() : ${breakdown.saveState_ms} ms`);- console.log(` gaussian pool fill : ${breakdown.gaussians_ms} ms`);- console.log(` _plot.angle() total : ${breakdown.angleCalc_ms} ms`);- console.log(` tip() total : ${breakdown.tip_ms} ms`);- console.log(` plotTo/moveTo total : ${breakdown.move_ms} ms`);- console.log(` restoreState+glDraw : ${breakdown.restoreState_glDraw_ms} ms`);- console.log(`\n-- counts per run --`);- console.log(` hatch lines : ${breakdown.nLines_per_run}`);- console.log(` arcs rendered : ${breakdown.nArcs_per_run}`);- console.log(` stroke steps : ${breakdown.nSteps_per_run}`);- console.log(` strokes : ${breakdown.nStrokes_per_run}`);-- window.__profileDone = breakdown;-</script>-</body>-</html>diff --git a/benchmark/bench_mass_profile.mjs b/benchmark/bench_mass_profile.mjsdeleted file mode 100644index 922b4b8..0000000--- a/benchmark/bench_mass_profile.mjs+++ /dev/null@@ -1,43 +0,0 @@-import { chromium } from 'playwright-chromium';-import { fileURLToPath } from 'url';-import path from 'path';-import http from 'http';-import fs from 'fs';--const __dirname = path.dirname(fileURLToPath(import.meta.url));-const rootDir = path.resolve(__dirname, '..');--function startServer() {- const mimeTypes = { '.html':'text/html', '.js':'application/javascript', '.mjs':'application/javascript', '.map':'application/json', '.json':'application/json' };- const server = http.createServer((req, res) => {- const filePath = path.join(rootDir, req.url.split('?')[0]);- fs.readFile(filePath, (err, data) => {- if (err) { res.writeHead(404); res.end('Not found'); return; }- res.writeHead(200, { 'Content-Type': mimeTypes[path.extname(filePath)] ?? 'application/octet-stream' });- res.end(data);- });- });- return new Promise(resolve => server.listen(0, '127.0.0.1', () => resolve({ server, port: server.address().port })));-}--const { server, port } = await startServer();-const browser = await chromium.launch({ headless: true, args: ['--enable-webgl','--use-gl=angle','--disable-gpu-sandbox','--no-sandbox'] });-const page = await browser.newPage();--page.on('console', msg => {- const text = msg.text();- if (msg.type() === 'error') process.stderr.write(`[profile] ${text}\n`);- else if (!text.startsWith('METRIC')) process.stdout.write(text + '\n');-});--await page.goto(`http://127.0.0.1:${port}/benchmark/bench_mass_profile.html`, { waitUntil: 'domcontentloaded' });--try {- await page.waitForFunction(() => window.__profileDone !== undefined, { timeout: 120_000 });-} catch {- process.stderr.write('timed out\n');- await browser.close(); server.close(); process.exit(1);-}--await browser.close();-server.close();diff --git a/benchmark/bench_rng.mjs b/benchmark/bench_rng.mjsdeleted file mode 100644index bdfedee..0000000--- a/benchmark/bench_rng.mjs+++ /dev/null@@ -1,91 +0,0 @@-/**- * RNG benchmark: compare prng_alea vs alternatives- * Tests raw speed and quality sufficient for visual simulation- */-import { performance } from "perf_hooks";-import { prng_alea } from "esm-seedrandom";--const ITERS = 5_000_000;-const RUNS = 5;--function medianOf(arr) {- const s = [...arr].sort((a, b) => a - b);- return s[Math.floor(s.length / 2)];-}--function bench(fn) {- const times = [];- for (let r = 0; r < RUNS; r++) {- const t0 = performance.now();- fn();- times.push(performance.now() - t0);- }- return medianOf(times);-}--// ---- 1. Current: prng_alea -----const aleaMs = bench(() => {- const rng = prng_alea(42);- let s = 0;- for (let i = 0; i < ITERS; i++) s += rng();- return s;-});--// ---- 2. xorshift32 -----const xorMs = bench(() => {- let s = 42;- let sum = 0;- for (let i = 0; i < ITERS; i++) {- s ^= s << 13; s ^= s >> 17; s ^= s << 5;- sum += (s >>> 0) * 2.3283064365386963e-10;- }- return sum;-});--// ---- 3. mulberry32 (fast high-quality 32-bit PRNG) -----const mulberryMs = bench(() => {- let s = 42;- let sum = 0;- for (let i = 0; i < ITERS; i++) {- s |= 0; s = s + 0x6D2B79F5 | 0;- let t = Math.imul(s ^ s >>> 15, s | 1);- t ^= t + Math.imul(t ^ t >>> 7, t | 61);- sum += ((t ^ t >>> 14) >>> 0) * 2.3283064365386963e-10;- }- return sum;-});--// ---- 4. SFC32 -----const sfcMs = bench(() => {- let a = 42, b = 0, c = 0, d = 1;- let sum = 0;- for (let i = 0; i < ITERS; i++) {- const t = (a + b | 0) + d | 0;- d = d + 1 | 0;- a = b ^ b >>> 9;- b = c + (c << 3) | 0;- c = (c << 21 | c >>> 11) + t | 0;- sum += (t >>> 0) * 2.3283064365386963e-10;- }- return sum;-});--// ---- 5. Lehmer LCG (simplest, fastest) -----const lehmerMs = bench(() => {- let s = 42;- let sum = 0;- for (let i = 0; i < ITERS; i++) {- s = Math.imul(s, 2654435761) >>> 0;- sum += s * 2.3283064365386963e-10;- }- return sum;-});--const nsPerCall = (ms) => ((ms / ITERS) * 1e6).toFixed(2);--console.log(`\nRNG Benchmark (${ITERS.toLocaleString()} calls each):`);-console.log(`prng_alea (current): ${aleaMs.toFixed(1)}ms = ${nsPerCall(aleaMs)}ns/call`);-console.log(`xorshift32: ${xorMs.toFixed(1)}ms = ${nsPerCall(xorMs)}ns/call`);-console.log(`mulberry32: ${mulberryMs.toFixed(1)}ms = ${nsPerCall(mulberryMs)}ns/call`);-console.log(`SFC32: ${sfcMs.toFixed(1)}ms = ${nsPerCall(sfcMs)}ns/call`);-console.log(`Lehmer LCG: ${lehmerMs.toFixed(1)}ms = ${nsPerCall(lehmerMs)}ns/call`);diff --git a/benchmark/bench_visual.html b/benchmark/bench_visual.htmldeleted file mode 100644index f1b852d..0000000--- a/benchmark/bench_visual.html+++ /dev/null@@ -1,152 +0,0 @@-<!DOCTYPE html>-<html>-<head>- <meta charset="utf-8" />- <title>p5.brush visual benchmark</title>-</head>-<body style="margin:0;padding:0;background:#000">- <div id="host" style="position:fixed;left:-9999px;top:-9999px;visibility:hidden"></div>- <script type="module">- import * as brush from '../dist/brush.esm.js';-- const CW = 400, CH = 400;- brush.createCanvas(CW, CH, { parent: '#host', pixelDensity: 1 });- brush.scaleBrushes(1);-- // GPU sync: blit one pixel of the main canvas to a 2D canvas then readback.- // This forces the browser to flush all pending GPU commands before returning.- const syncCanvas = document.createElement('canvas');- syncCanvas.width = 1; syncCanvas.height = 1;- const syncCtx = syncCanvas.getContext('2d');- const mainCanvas = document.querySelector('#host canvas');-- function gpuSync() {- syncCtx.drawImage(mainCanvas, 0, 0, 1, 1, 0, 0, 1, 1);- syncCtx.getImageData(0, 0, 1, 1); // forces CPU-GPU sync- }-- // Build a circular test polygon (24 points)- function circlePts(cx, cy, r, n = 24) {- const pts = [];- for (let i = 0; i < n; i++) {- const a = (i / n) * Math.PI * 2;- pts.push([cx + Math.cos(a) * r, cy + Math.sin(a) * r]);- }- return pts;- }-- const POLY = circlePts(CW / 2, CH / 2, 90);-- // wiggle() is always active — representative of real sketch usage.- // It is re-activated each run because brush.seed() may reset field state.- function setupFrame(seed) {- brush.seed(seed);- brush.clear('#fffceb');- brush.wiggle(); // always on- }-- // Time RUNS iterations of fn(), returning the median ms/run.- function benchOp(runs, fn) {- const times = [];- for (let i = 0; i < runs; i++) {- setupFrame(42 + i);- const t0 = performance.now();- fn();- brush.render();- gpuSync();- times.push(performance.now() - t0);- }- times.sort((a, b) => a - b);- return times[Math.floor(times.length / 2)];- }-- async function run() {- // Ensure module is fully initialised before timing- setupFrame(1); brush.render(); gpuSync();-- const WARMUP = 5;- const RUNS = 15;-- // ── stroke ──────────────────────────────────────────────────────────────- // 8 circles with HB brush, wiggle active- for (let i = 0; i < WARMUP; i++) {- setupFrame(42 + i);- brush.set('HB', '#222222', 1);- for (let j = 0; j < 8; j++) brush.circle(CW / 2, CH / 2, 40 + j * 8);- brush.render(); gpuSync();- }- const stroke_ms = benchOp(RUNS, () => {- brush.set('HB', '#222222', 1);- for (let j = 0; j < 8; j++) brush.circle(CW / 2, CH / 2, 40 + j * 8);- });-- // ── fill ─────────────────────────────────────────────────────────────────- // Watercolor fill on a 90-px circle polygon, wiggle active- for (let i = 0; i < WARMUP; i++) {- setupFrame(42 + i);- brush.fill(100, 50, 200, 180); brush.fillTexture(0.8, 0.5);- brush.polygon(POLY); brush.noFill();- brush.render(); gpuSync();- }- const fill_ms = benchOp(RUNS, () => {- brush.fill(100, 50, 200, 180); brush.fillTexture(0.8, 0.5);- brush.polygon(POLY); brush.noFill();- });-- // ── hatch ────────────────────────────────────────────────────────────────- // HB hatch at 45° on the same polygon, wiggle active- for (let i = 0; i < WARMUP; i++) {- setupFrame(42 + i);- brush.set('HB', '#333333', 0.5);- brush.hatch(5, 45, { rand: 0.5, continuous: false });- brush.polygon(POLY); brush.noHatch();- brush.render(); gpuSync();- }- const hatch_ms = benchOp(RUNS, () => {- brush.set('HB', '#333333', 0.5);- brush.hatch(5, 45, { rand: 0.5, continuous: false });- brush.polygon(POLY); brush.noHatch();- });-- // ── mass ─────────────────────────────────────────────────────────────────- // Mass pass using HB brush (same as hatch) so we isolate the mass- // overhead (arc conversion, 3 polygon layers, Plot creation) cleanly.- for (let i = 0; i < WARMUP; i++) {- setupFrame(42 + i);- brush.mass('HB', '#335588', { precision: 0.3, strength: 0.6, gradient: 0.1 });- brush.set('HB', '#000000', 0.5);- brush.circle(CW / 2, CH / 2, 90);- brush.noMass();- brush.render(); gpuSync();- }- const mass_ms = benchOp(RUNS, () => {- brush.mass('HB', '#335588', { precision: 0.3, strength: 0.6, gradient: 0.1 });- brush.set('HB', '#000000', 0.5);- brush.circle(CW / 2, CH / 2, 90);- brush.noMass();- });-- // ── results ──────────────────────────────────────────────────────────────- const total_visual_ms = stroke_ms + fill_ms + hatch_ms + mass_ms;- const results = {- total_visual_ms,- v_stroke_ms: stroke_ms,- v_fill_ms: fill_ms,- v_hatch_ms: hatch_ms,- v_mass_ms: mass_ms,- };-- for (const [k, v] of Object.entries(results)) {- console.log(`METRIC ${k}=${v.toFixed(3)}`);- }-- window.__benchDone = results;- }-- run().catch(e => {- console.error('BENCH_ERROR:', e.message, e.stack);- window.__benchError = e.message;- });- </script>-</body>-</html>diff --git a/benchmark/bench_visual.mjs b/benchmark/bench_visual.mjsdeleted file mode 100644index 79544a7..0000000--- a/benchmark/bench_visual.mjs+++ /dev/null@@ -1,96 +0,0 @@-#!/usr/bin/env node-// Playwright-based visual benchmark for p5.brush-// Runs bench_visual.html in headless Chromium with real WebGL, captures METRIC lines.--import { chromium } from 'playwright-chromium';-import { fileURLToPath } from 'url';-import path from 'path';-import http from 'http';-import fs from 'fs';--const __dirname = path.dirname(fileURLToPath(import.meta.url));-const rootDir = path.resolve(__dirname, '..');--// Minimal static file server — serves the project root so relative imports work-function startServer() {- const mimeTypes = {- '.html': 'text/html',- '.js': 'application/javascript',- '.mjs': 'application/javascript',- '.map': 'application/json',- '.json': 'application/json',- };- const server = http.createServer((req, res) => {- const filePath = path.join(rootDir, req.url.split('?')[0]);- fs.readFile(filePath, (err, data) => {- if (err) { res.writeHead(404); res.end('Not found'); return; }- const ext = path.extname(filePath);- const mime = mimeTypes[ext] ?? 'application/octet-stream';- res.writeHead(200, { 'Content-Type': mime });- res.end(data);- });- });- return new Promise(resolve => {- server.listen(0, '127.0.0.1', () => {- resolve({ server, port: server.address().port });- });- });-}--const { server, port } = await startServer();-const benchUrl = `http://127.0.0.1:${port}/benchmark/bench_visual.html`;--const browser = await chromium.launch({- headless: true,- args: [- '--enable-webgl',- '--use-gl=angle',- '--disable-gpu-sandbox',- '--no-sandbox',- ],-});--const page = await browser.newPage();--// Relay console output → stdout so autoresearch.sh can grep METRIC lines-page.on('console', msg => {- const text = msg.text();- if (msg.type() === 'error') {- process.stderr.write(`[bench_visual] ${text}\n`);- } else {- // Pass METRIC lines straight through; suppress noise from the brush lib- if (text.startsWith('METRIC ')) {- process.stdout.write(text + '\n');- }- }-});--page.on('pageerror', err => {- process.stderr.write(`[bench_visual] page error: ${err.message}\n`);-});--await page.goto(benchUrl, { waitUntil: 'domcontentloaded' });--// Wait up to 120s for the benchmark to finish (mass pass is slow per iteration)-try {- await page.waitForFunction(- () => window.__benchDone !== undefined || window.__benchError !== undefined,- { timeout: 120_000 },- );-} catch {- process.stderr.write('[bench_visual] timed out waiting for benchmark\n');- await browser.close();- server.close();- process.exit(1);-}--const error = await page.evaluate(() => window.__benchError);-if (error) {- process.stderr.write(`[bench_visual] benchmark failed: ${error}\n`);- await browser.close();- server.close();- process.exit(1);-}--await browser.close();-server.close();diff --git a/benchmark/loader.mjs b/benchmark/loader.mjsdeleted file mode 100644index 1bdf201..0000000--- a/benchmark/loader.mjs+++ /dev/null@@ -1,36 +0,0 @@-/**- * Custom ESM loader that stubs GLSL shader files and browser-only modules- * so that source modules can be imported in Node.js without a browser/WebGL context.- */-export async function load(url, context, nextLoad) {- // Stub GLSL shader files- if (url.endsWith('.vert') || url.endsWith('.frag')) {- return { format: 'module', source: 'export default "";', shortCircuit: true };- }- // Stub compositor_runtime — provides GL compositor hooks not needed for pure computation- if (url.includes('compositor_runtime') || url.includes('renderer_runtime')) {- return {- format: 'module',- source: `- export const setCompositorRuntime = () => {};- export const setRendererRuntime = () => {};- export const clearTarget = () => {};- export const ensureBlendShaderProgram = () => {};- export const ensureBlendSourceFramebuffer = () => {};- export const createFramebuffer = () => null;- export const runBlendShaderPass = () => {};- export const blitSourceToFramebuffer = () => {};- export const blendToTarget = () => {};- export const composite = () => {};- export const create2DCanvas = () => null;- export const get2DContext = () => null;- export const blitDefaultFramebufferSource = () => {};- export const beginDirectMaskDraw = () => null;- export const endDirectMaskDraw = () => {};- export const resetDirectShaderTracking = () => {};- `,- shortCircuit: true,- };- }- return nextLoad(url, context);-}diff --git a/benchmark/test_fill.mjs b/benchmark/test_fill.mjsdeleted file mode 100644index 18a743f..0000000--- a/benchmark/test_fill.mjs+++ /dev/null@@ -1,13 +0,0 @@-import { setTargetState, setTargetRuntime } from "../src/core/target.js";-import { seed } from "../src/core/utils.js";-import { isFieldReady, noField } from "../src/core/flowfield.js";--setTargetState({ Cwidth: 800, Cheight: 600, Density: 1, Renderer: { loaded: true } });-setTargetRuntime({ isCanvasReady: () => {}, syncDensity: () => 1 });-seed(42);-isFieldReady();-noField();--// Test importing fill.js indirectly through what we can-import { createFill, fill, noFill } from "../src/fill/fill.js";-console.log("fill.js imported OK");diff --git a/benchmark/test_flowfield.mjs b/benchmark/test_flowfield.mjsdeleted file mode 100644index 6483db6..0000000--- a/benchmark/test_flowfield.mjs+++ /dev/null@@ -1,23 +0,0 @@-import { setTargetState, setTargetRuntime } from "../src/core/target.js";-import { seed } from "../src/core/utils.js";-import { isFieldReady, Position, noField } from "../src/core/flowfield.js";-import { Plot } from "../src/core/plot.js";--// Provide mock Renderer with loaded=true to skip Mix.load()-setTargetState({ Cwidth: 800, Cheight: 600, Density: 1, Renderer: { loaded: true } });-setTargetRuntime({ isCanvasReady: () => {}, syncDensity: () => 1 });-seed(42);-isFieldReady();-noField();--const plot = new Plot("curve");-for (let i = 0; i < 10; i++) plot.addSegment(i * 36, 100, 0.8);-plot.endPlot(0, 1);--const pos = new Position(400, 300);-pos.moveTo(45, 200, 1);-console.log("pos after moveTo:", pos.x.toFixed(2), pos.y.toFixed(2));--const pos2 = new Position(400, 300);-pos2.plotTo(plot, 500, 1, 1);-console.log("pos2 after plotTo:", pos2.x.toFixed(2), pos2.y.toFixed(2));