Skip to content

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

Updated autoresearch.md with final summary. Current best: total 55.7ms. All key optimizations documented.

acamposuribee5b468cb01a4
diff --git a/autoresearch.ideas.md b/autoresearch.ideas.md
new file mode 100644
index 0000000..7703738
--- /dev/null
+++ b/autoresearch.ideas.md
@@ -0,0 +1,26 @@
+# Autoresearch Ideas
+
+## Unexplored / Deferred
+
+- **Amortized O(1) calcIndex for genPol()**: In Plot.genPol(), `this.calcIndex(pos.plotted)` is called after `pos.plotTo(this, step, step)`. The plotTo already sets this.index for the pre-step position. A post-step check (`if (this._cumLen[this.index+1] > pos.plotted)`) would save binary search for ~95% of genPol steps. BUT: previous attempt caused JIT interference when added inside calcIndex. Could work if inlined in genPol() directly. **Risk: medium (modifying plot.js).**
+
+- **AEL (Active Edge List) for scanlineHatch**: Sort edges by min(y1,y2) and use an active edge list to skip checking edges that don't span the current Y. For convex polygons (common case), would save ~0% (all edges are potentially active). For non-convex shapes: could save up to 50% of edge checks. **Risk: medium complexity, low benefit for convex polygons.**
+
+- **XOR pre-check in Polygon.intersect() for horizontal lines**: Add a fast Y-range check before calling intersectLines for horizontal lines. Saves ~50% of intersectLines calls. But Polygon.intersect() is not in rendering hot path, and modifying polygon.js risks JIT interference with fill.js. **Risk: medium JIT, low benefit.**
+
+- **Box-Muller cached value**: Store the second gaussian value (z1 = sqrt(-2ln(u)) * sin(360*v)) and use it on next call. Would halve Math.sqrt/Math.log calls. BUT: changes the RNG sequence = changes visual output. **Off-limits without explicit visual-change permission.**
+
+- **GROW_CAP skip computation**: For grows that will hit GROW_CAP (idx > GROW_CAP, step=2), the inserted vertices are discarded. Computing them wastes CPU but the RNG calls are needed for sequence preservation. Only the NON-RNG computation (cossin, multiplications) can be skipped for discarded vertices. Saves ~10ns × 150 vertices × 200 GROW_CAP grows = 300µs per fill. **Worth trying: low risk to utils.js, high complexity in fill.js.**
+
+- **Double-buffered scratch arrays for grow()**: Use two alternating sets of newMods/newDirs to avoid slice() allocation. Complex to implement correctly given multiple live FillPoly objects. **Risk: high complexity.**
+
+- **Interleaved Float64Array for FillPoly vertices**: Store [x0, y0, x1, y1, ...] as a single Float64Array. Better cache locality than parallel arrays. Avoids {x,y} object allocations in grow(). BUT: previous typed-array refactors caused JIT interference. Float64 vs Float32 matters (avoid type conversion overhead). **Risk: high JIT interference.**
+
+## Known Dead Ends
+
+- Sequential fast path in calcIndex (inside the function): Causes JIT deoptimization of unrelated code
+- movePos fast path for constant-direction strokes: JIT interference
+- Float32Array for FillPoly vertices: net negative (2 writes per vertex instead of 1 alloc)
+- Float32Array for gaussian pools: JIT interference
+- for-of → indexed loop in fill inner loop: JIT interference from fill.js changes
+- Any code additions to hatch.js that change control flow: JIT interference on fill_ms
diff --git a/autoresearch.jsonl b/autoresearch.jsonl
index 710464f..8df1d13 100644
--- a/autoresearch.jsonl
+++ b/autoresearch.jsonl
@@ -19,3 +19,5 @@
{"run":18,"commit":"2e1a931","metric":58.092,"metrics":{"trig_ms":4.447,"gauss_ms":2.899,"plot_ms":5.31,"hatch_ms":2.769,"intersect_ms":3.369,"intersect_lines_ms":1.861,"movepos_ms":5.003,"fill_ms":32.434},"status":"discard","description":"getHatchLines fast path + isConnector in segments: JIT interference (fill_ms +3%), hatch_ms unchanged. Object shape change causes slowdown. Revert.","timestamp":1774086673700,"segment":0,"confidence":1.037945205479452}
{"run":19,"commit":"2e1a931","metric":58.819,"metrics":{"trig_ms":5.258,"gauss_ms":3.003,"plot_ms":5.277,"hatch_ms":2.92,"intersect_ms":3.77,"intersect_lines_ms":1.78,"movepos_ms":5.07,"fill_ms":31.741},"status":"discard","description":"for-of → indexed loop in fill inner: JIT interference again (trig +27%), total +2ms. V8 JIT can't be controlled at this granularity in fill.js. Revert.","timestamp":1774086912968,"segment":0,"confidence":1}
{"run":20,"commit":"2e1a931","metric":60.252,"metrics":{"trig_ms":5.333,"gauss_ms":3.041,"plot_ms":5.554,"hatch_ms":2.746,"intersect_ms":3.527,"intersect_lines_ms":1.93,"movepos_ms":5.291,"fill_ms":32.831},"status":"discard","description":"Single-polygon fast path in getHatchSegments (skip sort): hatch_ms -0.03ms but fill_ms +1.4ms (JIT). Sort of 50 elements is negligible. Revert.","timestamp":1774087090305,"segment":0,"confidence":0.5007434821399067}
+{"run":21,"commit":"7700170","metric":55.471,"metrics":{"trig_ms":3.851,"gauss_ms":2.926,"plot_ms":3.798,"hatch_ms":2.893,"intersect_ms":3.579,"intersect_lines_ms":1.755,"movepos_ms":4.812,"fill_ms":31.858},"status":"keep","description":"calcIndex: amortized O(1) forward scan + binary search fallback. plot_ms: 5.5→3.8ms (-31%), movepos_ms: 5.1→4.8ms (-6%). total: 57→55.5ms (-3%)","timestamp":1774087282529,"segment":0,"confidence":1.2762337881084709}
+{"run":22,"commit":"7700170","metric":56.427,"metrics":{"trig_ms":5.176,"gauss_ms":2.894,"plot_ms":3.905,"hatch_ms":2.829,"intersect_ms":3.311,"intersect_lines_ms":1.841,"movepos_ms":4.855,"fill_ms":31.615},"status":"discard","description":"intersectLines 1/denom: intersect_ms -8% but trig_ms +35% (JIT from utils.js change). intersect_lines_ms unchanged. Net total +0.9ms. Revert.","timestamp":1774087655988,"segment":0,"confidence":1.5523458307723812}
diff --git a/autoresearch.md b/autoresearch.md
index bfb0156..b22907a 100644
--- a/autoresearch.md
+++ b/autoresearch.md
@@ -7,7 +7,7 @@ pure math and data structure operations that run thousands of times per frame.
## Metrics
- **Primary**: `total_ms` (ms, lower is better) — sum of all hot-path timings
-- **Secondary**: `trig_ms`, `gauss_ms`, `plot_ms`, `hatch_ms`, `intersect_ms`, `intersect_lines_ms`
+- **Secondary**: `trig_ms`, `gauss_ms`, `plot_ms`, `hatch_ms`, `fill_ms`, `movepos_ms`, `intersect_ms`, `intersect_lines_ms`
## How to Run
```
@@ -16,16 +16,17 @@ pure math and data structure operations that run thousands of times per frame.
Outputs `METRIC name=value` lines. Tests must pass. Benchmark imports from actual source files.
## Files in Scope
-- `src/core/utils.js` — Math utilities: cos/sin lookup tables, random number generators, gaussian, intersectLines, map, constrain, rotate, dist
-- `src/core/plot.js` — Plot class: calcIndex (O(n) linear scan), angle(), pressure(), curving() interpolation
+- `src/core/utils.js` — Math utilities: cos/sin lookup tables, random, gaussian, intersectLines
+- `src/core/plot.js` — Plot class: calcIndex (now amortized O(1) sequential scan), angle(), pressure()
- `src/core/polygon.js` — Polygon class: intersect() with cache
- `src/hatch/hatch.js` — scanlineHatch(): edge-list intersection, scanline generation
- `src/fill/fill.js` — FillPoly: grow(), trim(), scatter() — watercolor simulation hot path
+- `src/core/flowfield.js` — Position.movePos() — core stroke rendering loop
- `benchmark/bench.mjs` — Benchmark script (imports from source)
- `benchmark/loader.mjs` — ESM loader stub for .vert/.frag files
## Off Limits
-- `src/stroke/gl_draw.js` — WebGL rendering, not benchmarked
+- `src/stroke/gl_draw.js` — WebGL rendering
- `src/core/color.js` — Compositor/color management
- `test/` — Tests must keep passing unchanged
- No new dependencies
@@ -35,34 +36,56 @@ Outputs `METRIC name=value` lines. Tests must pass. Benchmark imports from actua
- Visual output must be identical (same RNG sequence, same math results within float precision)
- No algorithmic changes that alter output values
+## Results Summary
+
+**Total improvement: ~18-22% on the hot path computations**
+
+| Metric | Before | After | Change |
+|--------|--------|-------|--------|
+| plot_ms | 5.5ms | ~3.9ms | -29% |
+| hatch_ms | 4.7ms | ~2.9ms | -38% |
+| trig_ms | 6.3ms | ~4.5ms | -28% |
+| fill_ms | ~34ms (est.) | ~32ms | -6% |
+| movepos_ms | ~5.5ms | ~4.9ms | -11% |
+| intersect_lines_ms | 2.2ms | 1.8ms | -18% |
+
+## Key Optimizations Applied
+
+1. **Plot.calcIndex: binary search** (was O(n) linear scan): First replaced O(n) with O(log n). Pre-compute cumulative lengths `_cumLen[]` in `addSegment()`. Also incremental `this.length` update. -47% plot_ms.
+
+2. **Plot.calcIndex: amortized O(1) sequential scan**: For the common case of monotonically increasing access (stroke rendering), forward scan from cached index is O(1) per step. Fallback to binary search for backward access. -31% additional plot_ms.
+
+3. **scanlineHatch: flat typed array buffers**: Replaced 200 small `[x,y]` array allocations with pre-allocated Float64Arrays. -27% hatch_ms.
+
+4. **scanlineHatch: XOR crossing check + 2-element fast swap**: `(y1<=Y) !== (y2<=Y)` instead of 4 comparisons. Fast swap for 2-element cx array (convex polygon common case). -16% hatch_ms.
+
+5. **angleToIdx: avoid % for common ranges**: Fast paths for [-360,0), [0,360), [360,720) avoid floating-point modulo. -17% trig_ms.
+
+6. **Pre-warmed trig table**: Fill cos/sin lookup tables at module load instead of lazy. Removes isNaN check + lazy store overhead.
+
+7. **cossin()**: Computes cos+sin with a SINGLE angleToIdx call. Used in rotate(), movePos(), fill grow(). -4% fill_ms.
+
+8. **Simplified intersectLines**: Removed redundant "segment is a point" check (denom=0 catches it). -11% intersect_lines_ms.
+
+9. **Inlined Plot.angle()/pressure()**: Removed curving() function call overhead, skipped wrap-around for pressure.
+
## What's Been Tried
-### Key Finding: JIT Sensitivity
-Adding branches (if/else fast paths) to hot functions like `calcIndex()` and `movePos()` causes V8 to deoptimize the function OR unrelated code in the same module. This happened twice — sequential fast path in calcIndex, constant-direction fast path in movePos. **Do NOT add branches to these functions.**
-
-### Key Finding: Fill Performance
-The `createFill()` watercolor fill function is dominated by RNG calls (prng_alea ~6ns/call × ~87,000 calls/fill ≈ 522µs). A typed-array refactor of FillPoly vertices made it SLOWER because V8 handles short-lived `{x,y}` objects efficiently in young-gen GC. Real optimization opportunity: avoid calling `angleToIdx()` twice for the same angle (cos + sin).
-
-### Baseline
-- Established benchmark: total_ms ≈ 36-37ms
-- trig_ms ≈ 7ms (lookup table already in place)
-- gauss_ms ≈ 3ms (Box-Muller with trig lookup)
-- plot_ms ≈ 13ms (Plot.calcIndex is O(n) linear scan)
-- hatch_ms ≈ 6ms (scanlineHatch with edge intersections)
-- intersect_ms ≈ 5ms (Polygon.intersect with cache)
-- intersect_lines_ms ≈ 2ms
-
-### Key Observations
-1. **plot_ms dominates** at ~35% of total. Plot.calcIndex() does a linear scan through segments on every angle/pressure query. This is called thousands of times per stroke.
-2. **trig lookup tables** are already implemented (good optimization already in place)
-3. **Polygon.intersect cache** already uses string key caching
-4. **gaussian()** uses Box-Muller with cos() lookup — could pool pre-computed values
-5. **intersectLines()** uses early exit checks — pretty lean already
-
-### Ideas to Try
-- [ ] Plot.calcIndex(): Use binary search instead of linear scan (O(log n) vs O(n))
-- [ ] Plot: Cache cumulative segment lengths for faster binary search
-- [ ] Polygon.intersect: Replace string key with numeric hash for cache lookup
-- [ ] scanlineHatch: Avoid repeated rotation math per scanline
-- [ ] intersectLines: Simplify with direct computations
-- [ ] gaussian pool: Pre-compute pool at seed time, use cycling index
+### Key Findings
+
+**JIT Sensitivity**: Adding branches to hot functions in hatch.js/fill.js (even simple ones) causes fill_ms to increase 1-5ms due to V8 JIT cross-module interference. Safest changes are to utils.js and plot.js (foundational modules). AVOID adding new control flow to hatch.js, fill.js.
+
+**Sequential scan vs binary search**: Clean two-phase pattern (forward scan then binary search fallback) works for calcIndex. Previous failed attempt had complex bounds checking inside the fast path. Key: no complex conditions in the hot path.
+
+**Fill Performance**: Dominated by RNG calls (~219 grow() × 150 verts × 4 rr() calls = ~131k rr() calls per fill × 6ns = 786µs). Cannot skip any rng() calls without changing visual output. Typed array refactors of FillPoly vertices made things SLOWER (2 writes vs 1 alloc; V8 handles short-lived objects efficiently).
+
+### Dead Ends
+- Sequential fast path in calcIndex (with complex conditions): JIT deoptimization of other code
+- movePos constant-direction fast path: JIT interference
+- Float32Array for FillPoly vertices: net negative (2 writes per vertex vs 1 alloc)
+- Float32Array for gaussian pools: JIT interference
+- Any code additions to hatch.js changing control flow: JIT on fill_ms
+- intersectLines 1/denom optimization: JIT interference
+- for-of → indexed loop in fill inner loop: JIT interference
+- genPol fast index check: JIT interference from plot.js changes
+- FillPoly typed array refactor: net negative for fill