arthur/frontend/src/arthur/domain/raster.cljs
Olive Vaughn 943dc93d7d A lens draws what is under it finer, not bigger
Magnifying the pixels under a lens showed each one as a block, so a fine
line went to two pixels wide and a curve to steps. What is under a lens is
the ops drawn before it in its buffer, so it now draws them again, as many
times finer as it magnifies, over the box it reads from, and reads that:
the picture bending the shapes would give, through the same rasteriser,
so knockouts, stencils and remaps under it are what they were. A raster
has a :scale for it beside its :origin. The redraw is at most four times
finer and four stages' worth of pixels; a warp that magnifies nothing
reads the buffer as it is.

A fill also skips a shape wholly to one side of its raster rather than
walking every row to find that out, which is most of what a redraw over a
small box would otherwise cost.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 11:47:13 -05:00

500 lines
24 KiB
Clojure

(ns arthur.domain.raster
"Indexed flat-fill rasteriser.
Canvas2D antialiases path fills, and antialiasing is exactly what the target
idiom does not have: Animator Pro fills polygons into a 256-colour indexed
raster with hard edges (csd_render_poly). A preview that antialiases would
misrepresent the look it exists to judge, so this writes palette indices into
a byte buffer with an even-odd scanline fill and expands to RGBA only at the
very end.
A raster is {:w :h :buf} where :buf is a Uint8Array, and the fill functions
MUTATE it and return it. That is deliberate and it is the one place in domain/
that mutates: a persistent 64000-entry vector rebuilt per draw op per frame is
not a rasteriser. The mutation is confined — a raster is created, filled and
blitted inside one frame, and never stored in app-db.
No DOM here. `->rgba` returns plain bytes; wrapping them in an ImageData is
ui/canvas's job, which is also what lets every assertion below run in node.
A raster may have an `:origin`, the stage point its first pixel is, and ops
stay in stage pixels either way: the editor rasterises whatever part of the
work area is on screen, which need not be the stage. It may have a `:scale`
too, a whole number of its pixels to a stage pixel, which is how a lens sees
what is under it more finely than the stage does; see `warp!`."
(:require [arthur.domain.warp :as warp]))
(defn make [w h]
{:w w :h h :buf (js/Uint8Array. (* w h))})
(defn clear!
"`r` filled with `index`, which it remembers as what is under everything
drawn on it."
[{:keys [buf cov] :as r} index]
(.fill buf index)
(when cov (.fill cov 0))
(assoc r :bg index))
;; ---------------------------------------------------------------------------
;; layers and knockouts
;;
;; A symbol holding a KNOCKOUT shape is drawn into a layer of its own first —
;; Flash's Erase blend inside a symbol set to Layer. A layer is a raster with a
;; `:cov` byte per pixel saying whether anything is there; a knockout clears
;; coverage, of every colour or of one, and the layer lands on the one under it
;; only where it is covered. The main raster has no `:cov` and is always
;; covered.
;;
;; THE INK is how a shape marks the pixels it covers, and there are four, as
;; Deluxe Paint and Animator Pro had inks:
;;
;; nil an ordinary fill: write the shape's index
;; a number a knockout: clear coverage — of every colour at -1, or of
;; that index only
;; a Uint8Array a REMAP, index -> index: what is already there is drawn
;; in another slot. A flashlight is a circle of this.
;; an Int32Array a WARP: what is already there is drawn from somewhere
;; else. The fill only collects the pixels it covers here,
;; counted in its first entry; `warp!` draws them, once it
;; has read every one.
(defn- plot! [^js buf cov o index ink]
(cond
(nil? ink) (do (aset buf o index)
(when cov (aset cov o 1)))
(number? ink) (when (and cov (or (neg? ink) (== (aget buf o) ink)))
(aset cov o 0))
(instance? js/Int32Array ink) (let [n (inc (aget ink 0))]
(aset ink n o)
(aset ink 0 n))
:else (aset buf o (aget ink (aget buf o)))))
(defn- shows?
"Does pixel `o` hold `over`? A stencil only matches what is really there, so
an uncovered pixel of a layer holds nothing."
[^js buf cov o over]
(or (nil? over)
(and (or (nil? cov) (== 1 (aget cov o))) (== (aget buf o) over))))
(defn layer [w h]
{:w w :h h :buf (js/Uint8Array. (* w h)) :cov (js/Uint8Array. (* w h))})
(defn composite!
"Land layer `l` on raster `r` wherever `l` is covered."
[{:keys [buf cov] :as r} l]
(let [^js lb (:buf l) ^js lc (:cov l)]
(dotimes [o (.-length lb)]
(when (== 1 (aget lc o))
(aset buf o (aget lb o))
(when cov (aset cov o 1)))))
r)
(defn fill-poly-buf!
"Even-odd scanline fill of a polygon held FLAT in `pts` as [x0 y0 x1 y1 …],
using the first `n` points. Samples at pixel centres (y + 0.5), so a polygon
edge landing exactly on a pixel boundary resolves consistently.
Flat and preallocated because this is the per-frame path: fixed topology means
a node's vertex count is known at freeze time, so symbol/resolver hands the same
buffer back every frame and a frame allocates nothing. At 30fps per-frame
allocation is the only thing that will make this stutter.
`pts` may be a CLJS vector or any typed array; scanline crossings are collected
into a plain JS array and sorted in place. `ink` is as `plot!`'s."
([r pts n index] (fill-poly-buf! r pts n index nil))
([{:keys [w h buf cov origin scale] :as r} pts n index ink]
(when (>= n 3)
(let [[ox oy] (or origin [0 0])
sc (or scale 1)
px (fn [i] (* sc (- (if (vector? pts) (-nth pts (* 2 i)) (aget pts (* 2 i))) ox)))
py (fn [i] (* sc (- (if (vector? pts) (-nth pts (inc (* 2 i))) (aget pts (inc (* 2 i)))) oy)))
xs (array)
ys (map py (range n))
y0 (max 0 (js/Math.ceil (- (reduce min ys) 0.5)))
y1 (min (dec h) (inc (js/Math.floor (- (reduce max ys) 0.5))))
;; A shape wholly to one side of the raster has no span on any row
;; of it, and need not be walked row by row to find that out: a lens
;; redraws everything before it over a small box.
y1 (let [qs (map px (range n))]
(if (or (< (reduce max qs) 0) (> (reduce min qs) w)) -1 y1))]
;; `dotimes` over the span rather than a hand-rolled index: bounded
;; iteration with no accumulator is what it is for, and it compiles to the
;; same JS for-loop the recur did.
(dotimes [dy (inc (- y1 y0))]
(let [y (+ y0 dy)
sy (+ y 0.5)]
(set! (.-length xs) 0)
(dotimes [i n]
(let [j (mod (inc i) n)
ay (py i) by (py j)]
;; A horizontal edge contributes no crossing, and dividing by its
;; zero height would emit Infinity.
(when (not= ay by)
(let [lo (min ay by) hi (max ay by)]
;; Half-open in y: >= lo and < hi. A vertex shared by two edges
;; is counted exactly once, so the parity cannot flip at a
;; corner and leak a whole scanline.
(when (and (>= sy lo) (< sy hi))
(.push xs (+ (px i) (* (/ (- sy ay) (- by ay))
(- (px j) (px i))))))))))
(when (>= (.-length xs) 2)
(.sort xs (fn [a b] (- a b)))
;; Crossings pair up left to right: inside a span, outside the next.
;; Iterated as PAIRS rather than as a stepped index, but over the
;; array directly — `partition 2` over an `array-seq` says the same
;; thing and allocates two seqs per scanline, which is some five
;; thousand throwaway objects a frame in the hottest loop here.
(dotimes [k (quot (.-length xs) 2)]
(let [xa (aget xs (* 2 k))
xb (aget xs (inc (* 2 k)))
x-from (max 0 (js/Math.ceil (- xa 0.5)))
x-to (min (dec w) (js/Math.floor (- xb 0.5)))
row (* y w)]
(dotimes [dx (inc (- x-to x-from))]
(plot! buf cov (+ row x-from dx) index ink)))))))))
r))
(defn fill-poly!
"`fill-poly-buf!` over a seq of {:x :y} points.
The map form is what the analysis stages and the paint tool speak, and what the
JS oracle is diffed against; the flat form is what evaluation produces. ONE
scanline implementation serves both, because two would drift and the drift
would read as a rendering bug rather than as two functions disagreeing."
[r pts index]
(fill-poly-buf! r (into-array (mapcat (juxt :x :y) pts)) (count pts) index))
(defn fill-disc!
"`over` is an optional stencil: when given, only pixels that currently hold
that index are written. The indexed buffer is its own clip mask, which is
how Animator Pro would do it - and it is what keeps the iris inside the
eye. A disc clipped by the sclera cannot spill past the lid at any gaze or
any radius, including mid-blink when the opening is a two-pixel sliver, so
the lid crops the iris for free instead of the gaze range needing a
clamp that would flatten the performance at the extremes."
([r cx cy rad index] (fill-disc! r cx cy rad index nil nil))
([r cx cy rad index over] (fill-disc! r cx cy rad index over nil))
([{:keys [w h buf cov origin scale] :as r} cx cy rad index over ink]
(let [[ox oy] (or origin [0 0])
sc (or scale 1)
cx (* sc (- cx ox)) cy (* sc (- cy oy))
rad (* sc rad)
rr (* rad rad)
y0 (max 0 (js/Math.floor (- cy rad)))
y1 (min (dec h) (js/Math.ceil (+ cy rad)))
x0 (max 0 (js/Math.floor (- cx rad)))
x1 (min (dec w) (js/Math.ceil (+ cx rad)))]
(dotimes [iy (inc (- y1 y0))]
(dotimes [ix (inc (- x1 x0))]
(let [x (+ x0 ix)
y (+ y0 iy)
dx (- (+ x 0.5) cx)
dy (- (+ y 0.5) cy)]
(when (<= (+ (* dx dx) (* dy dy)) rr)
(let [o (+ (* y w) x)]
(when (shows? buf cov o over)
(plot! buf cov o index ink)))))))
r)))
(defn fill-rect!
"An exactly size x size block of pixels, snapped to the pixel grid, with the
same optional stencil as fill-disc!.
The pupil is a SQUARE because at 320x200 it is three pixels across, and a
circle of radius 1.5 is not a circle - it is a plus sign with the corners
gnawed off, and it changes shape as it moves. A square that size is a
deliberate mark that stays the same mark wherever it lands, which is the
whole argument for flat shapes at this resolution.
The top-left is rounded rather than the centre, so the block is size x size
on every frame. Round the extents instead and a fractional centre gives you
three pixels on one frame and four on the next, which reads as the pupil
breathing.
On a finer raster it is snapped to the STAGE's grid and then scaled, so a
lens shows the same block bigger, not a block of another size."
([r cx cy size index] (fill-rect! r cx cy size index nil nil))
([r cx cy size index over] (fill-rect! r cx cy size index over nil))
([{:keys [w h buf cov origin scale] :as r} cx cy size index over ink]
(let [[ox oy] (or origin [0 0])
sc (or scale 1)
cx (- cx ox) cy (- cy oy)
size (js/Math.round size)]
(when (>= size 1)
(let [x0 (* sc (js/Math.round (- cx (/ size 2))))
y0 (* sc (js/Math.round (- cy (/ size 2))))
size (* sc size)
ya (max 0 y0) yb (min h (+ y0 size))
xa (max 0 x0) xb (min w (+ x0 size))]
(dotimes [iy (- yb ya)]
(dotimes [ix (- xb xa)]
(let [o (+ (* (+ ya iy) w) xa ix)]
(when (shows? buf cov o over)
(plot! buf cov o index ink))))))))
r))
(def ^:private little-endian?
(let [b (js/ArrayBuffer. 4)]
(aset (js/Uint32Array. b) 0 1)
(= 1 (aget (js/Uint8Array. b) 0))))
;; The palette arrives as a CLJS vector of [r g b] vectors, which is the right
;; shape to author and the wrong shape to read 64,000 times a frame: a `nth` into
;; a vector of vectors is four protocol dispatches per pixel, and that measured at
;; 3.16ms per frame against 0.11ms for the same work off typed arrays. So it is
;; flattened once and cached by IDENTITY of the source vector — palettes are
;; values and a swap replaces the whole thing, so identity is exactly the right
;; test and there is no invalidation to get wrong.
(defonce ^:private flat-cache (atom nil))
(defn- flatten-palette [palette-rgb]
(let [cached @flat-cache]
(if (and cached (identical? palette-rgb (:src cached)))
cached
(let [p8 (js/Uint8Array. (* 256 3))
p32 (js/Uint32Array. 256)]
(dotimes [i 256]
;; An index with no palette entry comes out MAGENTA rather than
;; transparent or black: writing an index the palette does not have is
;; a bug, and it should be impossible to miss.
(let [c (or (nth palette-rgb i nil) [255 0 255])
r (nth c 0) g (nth c 1) b (nth c 2)]
(aset p8 (* i 3) r)
(aset p8 (+ 1 (* i 3)) g)
(aset p8 (+ 2 (* i 3)) b)
(aset p32 i (if little-endian?
(bit-or (bit-shift-left 255 24) (bit-shift-left b 16)
(bit-shift-left g 8) r)
(bit-or (bit-shift-left r 24) (bit-shift-left g 16)
(bit-shift-left b 8) 255)))))
(reset! flat-cache {:src palette-rgb :p8 p8 :p32 p32})))))
(defn ->rgba
"Expand indices through the palette at integer zoom. Nearest-neighbour by
construction, so no filtering softens the result.
Returns {:width :height :data} with :data a Uint8ClampedArray, ready to hand to
an ImageData.
`dest` is an optional Uint8ClampedArray to write into instead of allocating
one. At 320x200 the buffer is 256KB, and allocating and discarding that thirty
times a second is exactly the per-frame allocation the model is arranged to
avoid; ui/canvas passes the live ImageData's own array.
At zoom 1 on a little-endian machine this writes ONE 32-bit word per pixel
through a Uint32Array view of the same buffer, which is the whole of the inner
loop. Every other case walks bytes. Both paths read the same flattened palette
and raster-test asserts they agree with a naive reference pixel for pixel,
because a fast path that is subtly wrong about colour would look like a palette
bug rather than like an optimisation."
([r palette-rgb] (->rgba r palette-rgb 1 nil))
([r palette-rgb zoom] (->rgba r palette-rgb zoom nil))
([{:keys [w h buf]} palette-rgb zoom dest]
(let [W (* w zoom)
H (* h zoom)
d (or dest (js/Uint8ClampedArray. (* W H 4)))
{:keys [p8 p32]} (flatten-palette palette-rgb)]
(if (and (= 1 zoom) little-endian? (zero? (mod (.-byteOffset d) 4)))
(let [v (js/Uint32Array. (.-buffer d) (.-byteOffset d) (* w h))]
(dotimes [i (* w h)]
(aset v i (aget p32 (aget buf i)))))
(dotimes [y H]
(let [srow (* (js/Math.floor (/ y zoom)) w)]
(dotimes [x W]
(let [p (* 3 (aget buf (+ srow (js/Math.floor (/ x zoom)))))
o (* (+ (* y W) x) 4)]
(aset d o (aget p8 p))
(aset d (+ o 1) (aget p8 (+ p 1)))
(aset d (+ o 2) (aget p8 (+ p 2)))
(aset d (+ o 3) 255))))))
{:width W :height H :data d})))
(defn- fill-mask!
"Every pixel set in `mask`, a byte per stage pixel: a brush stroke as it is
being painted, before it is a polygon."
[{:keys [buf cov] :as r} ^js mask index ink]
(dotimes [o (.-length mask)]
(when (== 1 (aget mask o))
(plot! buf cov o index ink)))
r)
;; One layer per depth of nesting, reused from frame to frame, as the resolver
;; reuses its point buffers — and one set per LEVEL, a lens's finer redraw of
;; what is under it being level 1, so the redraw never draws into a layer the
;; frame it is part of is still using.
(defonce ^:private layers (atom {}))
(defn- layer-at [level depth {:keys [w h origin scale]}]
(let [l (get @layers [level depth])]
(if (and l (= w (:w l)) (= h (:h l)))
(assoc l :origin origin :scale scale)
(let [l (layer w h)]
(swap! layers assoc [level depth] l)
(assoc l :origin origin :scale scale)))))
;; What a warp works with, per level, reused from op to op as the layers are
;; and grown only for a bigger raster: the pixels it covers, where each reads
;; from, and what each will show. A warp costs what it covers and allocates
;; nothing for that.
(defonce ^:private scratch (atom {}))
(defn- scratch-at [level {:keys [w h]}]
(let [n (* w h)
sc (get @scratch level)]
(if (and sc (<= n (.-length (:shown sc))))
sc
(let [sc {:covered (js/Int32Array. (inc n)) :src (js/Float64Array. (* 2 n))
:shown (js/Int32Array. n) :at (js/Float64Array. 2)}]
(swap! scratch assoc level sc)
sc))))
(defn- covered-for
"The scratch a warp over raster `r` at `level` records its pixels into,
emptied."
[level r]
(doto (:covered (scratch-at level r)) (aset 0 0)))
;; How much finer a lens may see, and how many pixels its redraw may come to:
;; four stage rasters' worth, which a full-stage lens at 2x is exactly.
(def ^:private finest 4)
(def ^:private fine-budget (* 4 320 200))
;; The buffers a finer redraw draws into, grown and never shrunk.
(defonce ^:private fine-bufs (volatile! {:buf (js/Uint8Array. 0) :cov (js/Uint8Array. 0)}))
(defn- fine-raster
"A raster `k` times finer than the stage over stage box `[x0 y0 x1 y1]`, for
a redraw of what is under a lens: a layer when `layer?`, otherwise filled
with `bg`, as the raster the lens is on was."
[k [x0 y0 x1 y1] layer? bg]
(let [ox (js/Math.floor x0) oy (js/Math.floor y0)
w (* k (inc (- (js/Math.ceil x1) ox)))
h (* k (inc (- (js/Math.ceil y1) oy)))
n (* w h)]
(when (< (.-length (:buf @fine-bufs)) n)
(vreset! fine-bufs {:buf (js/Uint8Array. n) :cov (js/Uint8Array. n)}))
(let [buf (.subarray (:buf @fine-bufs) 0 n)
cov (when layer? (.subarray (:cov @fine-bufs) 0 n))]
(.fill buf (or bg 0))
(when cov (.fill cov 0))
{:w w :h h :buf buf :cov cov :origin [ox oy] :scale k})))
(declare draw!)
(defn- warp!
"Draw each pixel the fill before this covered as what `field` says it shows,
read from where it shows it.
EVERY PIXEL IS READ BEFORE ANY IS WRITTEN. A pixel a lens moves is one some
other pixel of the lens reads, so writing as it goes would magnify what it
had already magnified. Nothing outside what is covered is written.
WHAT IT MAGNIFIES IS DRAWN AGAIN, FINER, not blown up. Magnifying the pixels
would show each one as a block and lose what the drawing has between them;
but what is under a lens is `under`, the ops drawn before it in this buffer,
and drawing them again `k` times finer over the box it reads from shows what
the shapes are at that size — the same picture as bending the shapes before
rasterising, at a fraction of the work. `k` is how much the field magnifies
where it magnifies most: one over the smallest step between what two
neighbouring pixels read. It is a whole number, at most `finest`, and small
enough that the redraw keeps to `fine-budget`; a warp that magnifies nothing
reads the buffer as it is. A redraw is level 1, and a lens in it reads its
own buffer rather than redrawing again.
A point off the raster reads its nearest edge. In a layer what is shown
includes whether anything is there: a warp moves a hole as it moves a mark."
[{:keys [w h ^js buf ^js cov origin scale bg] :as r} field level under]
(let [[ox oy] (or origin [0 0])
sc (or scale 1)
{:keys [^js covered ^js src ^js shown ^js at]} (scratch-at level r)
n (aget covered 0)
layer? (some? cov)
box #js [js/Infinity js/Infinity (- js/Infinity) (- js/Infinity)]
step (volatile! js/Infinity)]
;; `js-mod` and a division rather than `rem` and `quot`, which are calls:
;; this is once per covered pixel.
(dotimes [i n]
(let [o (aget covered (inc i))
ix (js-mod o w)]
(field at (+ ox (/ (+ ix 0.5) sc)) (+ oy (/ (+ (/ (- o ix) w) 0.5) sc)))
(let [x (aget at 0) y (aget at 1)]
(aset src (* 2 i) x)
(aset src (inc (* 2 i)) y)
(aset box 0 (min (aget box 0) x)) (aset box 1 (min (aget box 1) y))
(aset box 2 (max (aget box 2) x)) (aset box 3 (max (aget box 3) y))
(when (and (pos? i) (== o (inc (aget covered i))))
(let [d (js/Math.hypot (- x (aget src (* 2 (dec i)))) (- y (aget src (dec (* 2 i)))))]
(when (< 1e-6 d @step) (vreset! step d)))))))
(let [area (* (- (aget box 2) (aget box 0) -2) (- (aget box 3) (aget box 1) -2))
k (if (and under (pos? n) (< @step (/ 1 sc)))
(loop [k (min finest (js/Math.ceil (- (/ 1 @step) 1e-6)))]
(if (and (< 1 k) (< fine-budget (* area k k))) (recur (dec k)) k))
1)
;; Where the lens reads from: the stage drawn again, finer, or the
;; buffer as it is.
{fw :w fh :h ^js fbuf :buf ^js fcov :cov [fx fy] :origin fs :scale}
(if (< 1 k)
(draw! (fine-raster k (vec box) layer? bg) under 1)
{:w w :h h :buf buf :cov cov :origin [ox oy] :scale sc})]
(dotimes [i n]
(let [x (max 0 (min (dec fw) (js/Math.floor (* fs (- (aget src (* 2 i)) fx)))))
y (max 0 (min (dec fh) (js/Math.floor (* fs (- (aget src (inc (* 2 i))) fy)))))
s (+ (* y fw) x)]
(aset shown i (if layer? (+ (aget fbuf s) (* 256 (aget fcov s))) (aget fbuf s))))))
(dotimes [i n]
(let [o (aget covered (inc i))
v (aget shown i)]
(aset buf o (bit-and v 255))
(when layer? (aset cov o (bit-shift-right v 8)))))
r))
(defn draw-ops!
"Paint a list of draw ops, in the order given, into the raster. Stage 7.
This is the boundary the whole model is arranged around: an op carries raster
space points and a PALETTE INDEX, and the rasteriser knows nothing about nodes,
channels, time maps or provenance. Everything above here can be rearranged
without touching a scanline, and a painted cel and a rotoscoped mouth arrive
here indistinguishable from each other, which is the point.
`:begin` and `:end` bracket the ops of a symbol drawn into a layer of its own;
`:knock` on an op makes it a knockout, `:lut` a remap and `:warp` a warp. See
`plot!`. A warp with no field — a kind there is none of — is drawn MAGENTA,
as a colour the palette lacks is: loud, and not fatal."
[r ops]
(draw! r ops 0))
(defn- draw!
"`draw-ops!` at `level`, which a lens's finer redraw of what is under it is
1 of. Each buffer on the stack remembers where in `ops` it began, so a lens
knows which ops are under it: the ones before it in its own buffer."
[r ops level]
(let [ops (vec ops)]
(reduce
(fn [stack i]
(let [{:keys [kind pts n color stencil cx cy size] :as op} (nth ops i)
top (:r (peek stack))
field (when (:warp op) (warp/field op))
color (if (and (:warp op) (nil? field)) 255 color)
ink (if field (covered-for level top) (or (:knock op) (:lut op)))]
(case kind
:begin (let [l (layer-at level (count stack) r)]
(.fill (:cov l) 0)
(conj stack {:r l :from (inc i)}))
:end (if (< 1 (count stack))
(let [s (pop stack)] (composite! (:r (peek s)) top) s)
stack)
(do (case kind
:poly (fill-poly-buf! top pts n color ink)
:disc (fill-disc! top cx cy (:r op) color stencil ink)
:rect (fill-rect! top cx cy size color stencil ink)
;; A brush stroke's mask is a byte per stage pixel, and has
;; nothing finer to show.
:mask (when (= 1 (or (:scale top) 1)) (fill-mask! top (:mask op) color ink))
(throw (ex-info "draw op kind is not rasterisable" {:op (dissoc op :pts)})))
(when field
(warp! top field level
(when (zero? level) (subvec ops (:from (peek stack)) i))))
stack))))
[{:r r :from 0}] (range (count ops))))
r)