ui_app

source of pkg::alloy::draw

1// A retained 2D renderer over pkg::alloy::gpu (PLAN.md, stage2// F3): a canvas holds a tree of nodes, each with a transform, a clip for3// its children and a paint, the primitives it draws in its own4// coordinates. A frame redraws only what changed since the last one,5// into a texture the canvas keeps, then copies that to the frame.6// Coordinates are physical pixels, y down; colors are sRGB with straight7// alpha, blended as browsers blend them.8//9// ```text10// var canvas = Canvas::create(&var device, surface.format);11// const card = canvas.add(canvas.root());12// canvas.set_transform(card, Transform::translate(40.0, 40.0));13// var paint = Paint::empty();14// paint.rounded_rect(Rect::sized(300.0, 200.0), Radii::all(12.0), Fill::Color(Color::white()));15// canvas.paint(card, move paint);16//17// // on Redraw18// if (canvas.damaged()) {19//     if (device.acquire(surface, window.size()) is ::Some |frame|) {20//         var encoder = Encoder::empty();21//         canvas.render(&var device, &var encoder, frame);22//         device.submit(move encoder);23//         device.present(surface, &var window);24//     }25// }26// ```27//28// ## How it was built29//30// Notes kept from each stage as it was finished, the sizes and numbers31// of their day; what changed since is in REVIEW.md and the history.32//33// **F3 as built** (2026-10-12):34// - `draw`: `draw.alloy` the API (geometry, `Paint`, `Canvas`),35//   `encoding.alloy` primitives as `draw.wgsl`'s instances, `damage.alloy`,36//   `atlas.alloy`, `frame.alloy` the resources and a frame. The API is the37//   design's, with: fills as `Fill::Color(c)`, `Fill::linear`,38//   `Fill::radial` (and `_stops` forms, at most 8 stops); a node's clip39//   applies to its children, not its own paint, so a card's shadow stays40//   outside the clip that rounds its contents; shadows take one radius,41//   the top left one, and a blur of 0 is a plain rounded rectangle;42//   `Picture` is a texture's region: `canvas.picture` and `canvas.mask`43//   pack RGBA images and coverage masks of up to 256 pixels a side into44//   1024x1024 shelf-packed pages (a border of one pixel, an image's edge45//   repeated), larger ones getting a texture, and `Picture::whole` takes a46//   texture of the program's; `paint.image(area, picture, Filter)`;47//   `canvas.damage_all()` after a resize or anything outside the canvas;48//   `canvas.stats()` what the last frame drew, for tests and benchmarks;49//   `canvas.release(&var device)`.50// - Each node keeps its encoded instances, 48 floats each, its texture51//   groups and device boxes, encoded again when its paint changes or, with52//   its descendants, its transform or clip; a node changed marks its53//   ancestors so a frame visits only changed subtrees. Its old and new54//   bounds are damaged, kept as at most 16 rectangles as they come, then55//   snapped to pixels and merged until none overlap and at most 4 remain;56//   past 60% of the frame, the whole frame is drawn. Each rectangle gets a57//   clearing instance (a second pipeline, replacing) and the instances58//   touching it in painter's order, in runs of one texture; untextured59//   ones join any run. The kept texture is copied to the frame, which60//   copies must be able to write.61// - `gpu` gained `TextureFormat::R8Unorm`, `Encoder::copy_texture`,62//   `write_texture_region` and `Color::rgba`, `white`, `transparent`; std63//   `Vector::append` (a push a byte took a third of the encoding) and64//   `read_file` reading past a size of 0 (`/proc`); the compiler no longer65//   lets a free function specialize a method of the same name.66// - Tests: `alloyc test draw/tests.alloy` (geometry, damage, batching, on67//   the CPU device), and `tests/canvas.alloy`'s seven golden scenes68//   (`tests/golden/draw/`), the last drawn in two frames and compared with69//   the same scene drawn whole: the same on the CPU device, lavapipe and70//   WebGPU through Dawn here, on biscuit's GTX 1660 and on the Windows71//   desktop's RTX 4070 Ti. `samples/cards.alloy` floats three of twelve72//   cards by their transforms (run under a headless weston here; not yet73//   seen by a person; `cards.exe` is in `.alloy\window-tests` on the74//   Windows desktop).75// - Benchmarks (`bench/`, `scripts/bench.sh`, run by `scripts/test.sh`76//   against `bench/budgets.txt`), the best of five, in milliseconds:77//78//   | | lavapipe | GTX 1660 | RTX 4070 Ti |79//   |---|---|---|---|80//   | encoding 10,000 primitives on 1000 nodes | 3.8 | 3.2 | 2.1 |81//   | encoding one node changed among them | 0.07 | 0.06 | 0.03 |82//   | a whole 1920x1080 frame of them, to its fence | 38.5 | 3.0 | 1.3 |83//   | a frame redrawing one node | 1.7 | 0.35 | 0.14 |84//85//   (Encoding is CPU time, on each machine's CPU.) The startup program (12 cards in a window) presents its first86//   frame 64 ms after `main` under headless weston on lavapipe, which87//   compiling its pipelines dominates, peaking at 85 MB resident88//   (lavapipe's LLVM); it is 0.77 MB natively and 0.55 MB of wasm. The89//   plan's 50 ms and 20 MB targets are for a hello world on a GPU driver,90//   to measure with F5.91// - Left for later: atlas pages are never reclaimed (F4's glyph cache will92//   need eviction), nor are the bind groups of program textures released;93//   images are not snapped to pixels.94//95// **F10d as built** (2026-10-15; decisions/F10.md, "Color96// emoji"):97// - `glyphs.alloy` asks `text` for `glyph_image` and packs a color glyph98//   into RGBA atlas pages beside the coverage pages (each kind with its99//   own pages and its own eviction, a page's borders clear rather than an100//   edge repeated); a cached glyph says which it is. A color glyph is101//   rasterized once per size, at the quarter-pixel position 0, the other102//   three positions naming its entry, and drawn on whole pixels; one103//   showing the text's color (COLR's 0xFFFF) is kept per color, tints of104//   one glyph listed under its key.105// - `encoding.alloy`: `Kind::Colored`, an instance `draw.wgsl` draws as106//   its texel times its alpha (`COLORED`), in white, so that the text's107//   color tints only what the glyph says, as browsers draw emoji; MSL's108//   golden `draw.metal` follows.109// - Tests: `tests/canvas.alloy`'s `emoji` scene, Noto Color Emoji (COLR110//   version 1), Twemoji Mozilla (version 0) and Twemoji (CBDT) subsets of111//   `tests/fonts` beside text, the same on the CPU device,112//   lavapipe and WebGPU through Dawn.113// - Benchmarks (`bench/canvas.alloy`): a 1920x1080 page of 1914 emoji of114//   100 kinds at 26 pixels, 23.7 ms its first frame on lavapipe, which115//   rasterizing and packing them dominates, 13.2 ms drawn again.116//117// **F11c as built** (2026-10-15; decisions/F11.md, "What118// `window` and `draw` gain"): `canvas.set_hidden(node, hidden)` and119// `is_hidden`: a hidden node covers nothing (its reach empty, so frames120// gather nothing under it) and is skipped with its descendants, which121// keep their paint; hiding damages where the subtree drew, showing marks122// it moved, so it is measured and drawn again. `ui` hides the views a123// `switch` or a navigator keeps.124//125// **F11e as built** (2026-10-15; decisions/F11.md, question126// 12A): `canvas.set_opacity(node, opacity)` and `opacity`: the alpha of127// every primitive under the node multiplied by the opacities above it as128// a frame encodes it (gradient stops' too, as they go into the frame's),129// so overlapping parts show through while fading; a node at 0 is skipped130// with all under it; a change damages where the subtree reaches.131// `Color::mix(a, b, t)`.132//133// **Rounded clips nested** (2026-10-17; decisions/showcase.md,134// question 3A, `ui`'s `clip_radii`): a rectangle clipping inside a135// rounded clip, both upright, no longer drops the rounded one for the136// scissor: when their intersection is one rounded rectangle (each corner137// the rounded clip's own or clear of its curve, as a picture across a138// card's top) that is tested per pixel, else the rounded clip is and the139// rectangle cuts by the scissor (`child_state` in `encoding.alloy`).140// A rounded clip inside another still keeps only the inner one's corners.141// Golden `clips.png` gained a band across a rounded card's top.142//143// **F14c as built** (2026-10-20; decisions/F14.md, "Glyph144// memory", questions 9B and 10A):145// - `glyphs.alloy`: a glyph page is cut into 4 by 4 plots, each packed146//   in shelves (`Shelves` in `atlas.alloy`, the pictures' pages' too),147//   stamped with the frame it last gave a glyph and listing the keys of148//   the glyphs (and tints) placed in it; a cached glyph names its page149//   and plot. A glyph goes into the most recently used plot of the150//   budget's pages with room, else an empty one, else a new page while151//   the budget has room (large glyphs the frame has not drawn cleared152//   for it), else the least recently used plot the frame has not drawn153//   from, cleared; only when the frame drew from every plot of the154//   budget does it get a page past it. Clearing forgets just that plot's155//   keys, and never damages.156// - `canvas.set_glyph_budget(&var device, GlyphBudget)`: `coverage` 4157//   and `color` 2 pages, and `page`, the side, 1024 (smaller in tests; a158//   change of it empties the cache). `canvas.glyph_stats()`: pages, those159//   past the budget, plots holding glyphs, the textures' bytes, entries,160//   and the last frame's glyphs rasterized and plots cleared.161// - At a frame's start (`evict`): a page past the budget is kept where162//   the budget has room again; else its plots are cleared once a frame163//   has not drawn from them, or while the budget's pages have plots the164//   last frame did not use, which its glyphs then move into as they are165//   drawn; a page past the budget holding nothing, and a large glyph's166//   texture cleared, are released with their bind groups167//   (`Resources::forget`). Within the budget pages are kept, so a steady168//   app makes no textures.169// - A glyph larger than a plot (over 254 pixels a side at 1024) has a170//   texture of its own as a page of one plot, counted in the budget as171//   the plots it covers, past it when no room is made; larger than a172//   page, it is not drawn, as before.173// - Entries of glyphs with no pixels, and tinted ones whose tints went,174//   are forgotten together once 8,192 more were made (`MAX_MARKS`).175// - Pictures: a page emptied by `release_picture` is released at the176//   next frame, but a format's last; `release_picture` of a177//   `Picture::whole` releases the bind groups made for the program's178//   texture.179// - Tests: `draw/tests.alloy` (least recently used plots first, a frame's180//   overflow released two frames on with its bind group, glyphs moving181//   back into the budget, a lowered budget, large glyphs, empty glyphs182//   forgotten, picture pages and bind groups released);183//   `tests/canvas.alloy`'s `budget` scene, six lines drawn a frame each184//   under one page of 64 pixels each format, clearing 5 to 9 plots a185//   frame, then the band behind the first line redrawn, compared with the186//   scene drawn at once under the default budget (within one level,187//   question 12); `tests/glyph_memory.alloy`, the long run.188// - Every glyph moved, so glyphs sampled at a texel's center round189//   differently at a few pixels: 26 goldens were written again (`tests/golden/draw/text.png`, 13 of190//   `tests/golden/ui`, 12 of `tests/golden/tickets`), each191//   differing by one level in one channel at 1 to 7 pixels (question 12).192// - The long run (`tests/glyph_memory.alloy`, 2,000 frames of 640x480193//   on the CPU device, run by `scripts/test.sh` natively and for 220194//   frames for ARM64 under qemu): at most 5 pages (4 of coverage, one of195//   color, 8 MiB), none past the budget, at most 9,571 entries; 48.6 MB196//   resident after its first cycle and 48.2 MB at its end, against 77.8197//   and 77.1 MB before F14c, of which the fallback faces read whole were198//   about 25 MB (text's "F14c as built").199// - Benchmarks (`bench/canvas.alloy` on lavapipe): `glyph_churn`, the200//   1920x1080 page at a size not cached over a full cache, 20.6 ms201//   (`text_frame` 20.9); `glyph_bookkeeping`, a frame drawing nothing over202//   that cache, 0.003 ms of CPU; `glyph_resident_kb`, the long run's203//   growth, 0. The counter grew by 14 KB natively and 13 KB of wasm, hello204//   world by 10 KB and 9 KB.205206import std::string;207import std::vector;208import std::option;209import std::math;210import std::macros;211import pkg::alloy::gpu;212import pkg::alloy::window;213import pkg::alloy::text;214215import encoding;216import glyphs;217import damage;218import atlas;219import frame;220221const DRAW = #shader(#read_file("shaders/draw.wgsl"));222223/* --- Geometry --- */224225// A rectangle from its top left corner.226exp type Rect = struct {227    exp x: f32,228    exp y: f32,229    exp width: f32,230    exp height: f32,231};232233exp fn Rect::at(x: f32, y: f32, width: f32, height: f32) -> Rect {234    return Rect { .x = x, .y = y, .width = width, .height = height };235}236237// A rectangle at the origin.238exp fn Rect::sized(width: f32, height: f32) -> Rect {239    return Rect { .x = 0.0, .y = 0.0, .width = width, .height = height };240}241242exp fn Rect::empty() -> Rect {243    return Rect { .x = 0.0, .y = 0.0, .width = 0.0, .height = 0.0 };244}245246exp fn right(self r: &Rect) -> f32 {247    return r.x + r.width;248}249250exp fn bottom(self r: &Rect) -> f32 {251    return r.y + r.height;252}253254exp fn is_empty(self r: &Rect) -> bool {255    return r.width <= 0.0 || r.height <= 0.0;256}257258// What both cover, empty when they do not meet.259exp fn intersection(self r: &Rect, other: &Rect) -> Rect {260    const x = max(r.x, other.x);261    const y = max(r.y, other.y);262    const width = min(r.right(), other.right()) - x;263    const height = min(r.bottom(), other.bottom()) - y;264    if (width <= 0.0 || height <= 0.0) {265        return Rect::empty();266    }267    return Rect { .x = x, .y = y, .width = width, .height = height };268}269270// The smallest rectangle holding both, an empty one counting for nothing.271exp fn union(self r: &Rect, other: &Rect) -> Rect {272    if (r.is_empty()) {273        return copy other;274    }275    if (other.is_empty()) {276        return copy r;277    }278    const x = min(r.x, other.x);279    const y = min(r.y, other.y);280    return Rect {281        .x = x,282        .y = y,283        .width = max(r.right(), other.right()) - x,284        .height = max(r.bottom(), other.bottom()) - y285    };286}287288exp fn intersects(self r: &Rect, other: &Rect) -> bool {289    return !r.intersection(&other).is_empty();290}291292// The rectangle grown by `by` on every side.293exp fn inflated(self r: &Rect, by: f32) -> Rect {294    return Rect {295        .x = r.x - by,296        .y = r.y - by,297        .width = r.width + by * 2.0,298        .height = r.height + by * 2.0299    };300}301302exp fn area(self r: &Rect) -> f32 {303    return if (r.is_empty()) 0.0 else r.width * r.height;304}305306// A rounded rectangle's corner radii.307exp type Radii = struct {308    exp top_left: f32,309    exp top_right: f32,310    exp bottom_right: f32,311    exp bottom_left: f32,312};313314exp fn Radii::all(radius: f32) -> Radii {315    return Radii {316        .top_left = radius,317        .top_right = radius,318        .bottom_right = radius,319        .bottom_left = radius320    };321}322323exp fn Radii::none() -> Radii {324    return Radii::all(0.0);325}326327// A 2D affine transform: the point (x, y) goes to328// (a x + c y + tx, b x + d y + ty).329exp type Transform = struct {330    exp a: f32,331    exp b: f32,332    exp c: f32,333    exp d: f32,334    exp tx: f32,335    exp ty: f32,336};337338exp fn Transform::identity() -> Transform {339    return Transform { .a = 1.0, .b = 0.0, .c = 0.0, .d = 1.0, .tx = 0.0, .ty = 0.0 };340}341342exp fn Transform::translate(x: f32, y: f32) -> Transform {343    return Transform { .a = 1.0, .b = 0.0, .c = 0.0, .d = 1.0, .tx = x, .ty = y };344}345346exp fn Transform::scale(x: f32, y: f32) -> Transform {347    return Transform { .a = x, .b = 0.0, .c = 0.0, .d = y, .tx = 0.0, .ty = 0.0 };348}349350// Turns by the angle, clockwise on the screen, about the origin.351exp fn Transform::rotate(radians: f32) -> Transform {352    const s = sin(radians);353    const c = cos(radians);354    return Transform { .a = c, .b = s, .c = -s, .d = c, .tx = 0.0, .ty = 0.0 };355}356357// This transform, then the next.358exp fn then(self t: &Transform, next: &Transform) -> Transform {359    return Transform {360        .a = next.a * t.a + next.c * t.b,361        .b = next.b * t.a + next.d * t.b,362        .c = next.a * t.c + next.c * t.d,363        .d = next.b * t.c + next.d * t.d,364        .tx = next.a * t.tx + next.c * t.ty + next.tx,365        .ty = next.b * t.tx + next.d * t.ty + next.ty366    };367}368369exp fn apply(self t: &Transform, p: Point) -> Point {370    return Point { .x = t.a * p.x + t.c * p.y + t.tx, .y = t.b * p.x + t.d * p.y + t.ty };371}372373// The transform undoing this one; a flat one has none, and gives the374// identity.375exp fn inverse(self t: &Transform) -> Transform {376    const det = t.a * t.d - t.b * t.c;377    if (det == 0.0) {378        return Transform::identity();379    }380    const a = t.d / det;381    const b = -t.b / det;382    const c = -t.c / det;383    const d = t.a / det;384    return Transform {385        .a = a,386        .b = b,387        .c = c,388        .d = d,389        .tx = -(a * t.tx + c * t.ty),390        .ty = -(b * t.tx + d * t.ty)391    };392}393394// The bounds of the rectangle once transformed.395exp fn map_rect(self t: &Transform, r: &Rect) -> Rect {396    const p0 = t.apply(Point { .x = r.x, .y = r.y });397    const p1 = t.apply(Point { .x = r.right(), .y = r.y });398    const p2 = t.apply(Point { .x = r.x, .y = r.bottom() });399    const p3 = t.apply(Point { .x = r.right(), .y = r.bottom() });400    const x0 = min(min(p0.x, p1.x), min(p2.x, p3.x));401    const y0 = min(min(p0.y, p1.y), min(p2.y, p3.y));402    const x1 = max(max(p0.x, p1.x), max(p2.x, p3.x));403    const y1 = max(max(p0.y, p1.y), max(p2.y, p3.y));404    return Rect { .x = x0, .y = y0, .width = x1 - x0, .height = y1 - y0 };405}406407/* --- Paint --- */408409// A gradient's color at an offset from 0 to 1 along it.410exp type Stop = struct {411    exp offset: f32,412    exp color: Color,413};414415// Two points: a linear gradient's start and end, or a radial one's416// center and a point on its circle.417exp type Gradient = struct {418    exp start: Point,419    exp end: Point,420    exp stops: Vector<Stop>,421};422423exp type Fill = enum {424    Color: Color,425    Linear: Gradient,426    Radial: Gradient,427};428429// At most this many stops a gradient.430exp const MAX_STOPS: u64 = 8;431432// A linear gradient through the colors, evenly spaced.433exp fn Fill::linear(start: Point, end: Point, colors: &[Color]) -> Fill {434    return Fill::Linear(Gradient { .start = start, .end = end, .stops = spaced(&colors) });435}436437exp fn Fill::linear_stops(start: Point, end: Point, stops: &[Stop]) -> Fill {438    return Fill::Linear(Gradient {439        .start = start,440        .end = end,441        .stops = Vector<Stop>::from(&stops)442    });443}444445// A radial gradient through the colors, evenly spaced, from the center446// out to the radius.447exp fn Fill::radial(center: Point, radius: f32, colors: &[Color]) -> Fill {448    return Fill::Radial(Gradient {449        .start = center,450        .end = Point { .x = center.x + radius, .y = center.y },451        .stops = spaced(&colors)452    });453}454455exp fn Fill::radial_stops(center: Point, radius: f32, stops: &[Stop]) -> Fill {456    return Fill::Radial(Gradient {457        .start = center,458        .end = Point { .x = center.x + radius, .y = center.y },459        .stops = Vector<Stop>::from(&stops)460    });461}462463fn spaced(colors: &[Color]) -> Vector<Stop> {464    var stops = Vector<Stop>::empty();465    for ([..colors.length()]) |k| {466        const offset = if (colors.length() < 2) 0.0 else k to f32 / (colors.length() - 1) to f32;467        stops.push(Stop { .offset = offset, .color = colors[k] });468    }469    return move stops;470}471472// The color a fraction `t` of the way from `a` to `b`, each component473// and the alpha mixed straight: 0 gives `a`, 1 gives `b`.474exp fn Color::mix(a: Color, b: Color, t: f32) -> Color => Color {475    .r = a.r + (b.r - a.r) * t,476    .g = a.g + (b.g - a.g) * t,477    .b = a.b + (b.b - a.b) * t,478    .a = a.a + (b.a - a.a) * t479};480481// A box shadow, as CSS's: the shape moved by the offset, grown by the482// spread and blurred over the blur radius (twice the Gaussian's sigma).483exp type Shadow = struct {484    exp offset: Point,485    exp blur: f32,486    exp spread: f32,487    exp color: Color,488};489490exp fn Shadow::soft(x: f32, y: f32, blur: f32, color: Color) -> Shadow {491    return Shadow {492        .offset = Point { .x = x, .y = y },493        .blur = blur,494        .spread = 0.0,495        .color = color496    };497}498499// How an image is sampled between its pixels.500exp type Filter = enum {501    Linear,502    Nearest,503};504505// A region of a texture to draw images or masks from: one the canvas506// packed (`Canvas::picture`, `Canvas::mask`) or one of the program's.507exp type Picture = struct {508    exp texture: Texture,509    exp region: Rect, // in the texture's pixels510};511512// A whole texture of the program's, which it keeps alive while drawn.513exp fn Picture::whole(texture: Texture) -> Picture {514    return Picture {515        .texture = texture,516        .region = Rect::sized(texture.width to f32, texture.height to f32)517    };518}519520// What a node draws: primitives in order, in its own coordinates.521exp type Paint = struct {522    pub items: Vector<Primitive>,523    pub stops: Vector<f32>, // gradients' stops: a color, then an offset, each 4 floats524    pub glyphs: Vector<TextGlyph>, // text's, in the node's coordinates525};526527exp fn Paint::empty() -> Paint {528    return Paint {529        .items = Vector<Primitive>::empty(),530        .stops = Vector<f32>::empty(),531        .glyphs = Vector<TextGlyph>::empty()532    };533}534535// The layout's text with its pen at `origin`, its top left, in the536// color, but where a span gives its own; underlines and strikethroughs537// under it. The layout's fonts are the canvas's (`canvas.fonts()`).538exp fn text(self paint: &var Paint, layout: &Layout, origin: Point, color: Color) {539    for (layout.decorations.view()) |&d| {540        paint.rect(541            Rect::at(origin.x + d.box.x, origin.y + d.box.y, d.box.width, d.box.height),542            Fill::Color(color_of(d.color, color))543        );544    }545    const first = paint.glyphs.length() to u32;546    for (layout.glyphs.view()) |&g| {547        paint.glyphs.push(TextGlyph {548            .face = g.face,549            .glyph = g.glyph,550            .size = g.size,551            .x = origin.x + g.x,552            .y = origin.y + g.y,553            .color = color_of(g.color, color)554        });555    }556    paint.items.push(Primitive::of(557        Kind::Text(GlyphRun { .first = first, .count = layout.glyphs.length() to u32 }),558        Rect::at(origin.x, origin.y, layout.width, layout.height),559        Radii::none()560    ));561}562563fn color_of(c: Option<TextColor>, otherwise: Color) -> Color {564    if (c is ::Some |t|) {565        return Color::rgba(t.r, t.g, t.b, t.a);566    }567    return otherwise;568}569570// Gives back the room past what the paint holds, for a paint kept.571exp fn shrink(self paint: &var Paint) {572    paint.items.shrink();573    paint.stops.shrink();574    paint.glyphs.shrink();575}576577// How many primitives it holds.578exp fn length(self paint: &Paint) -> u64 {579    return paint.items.length();580}581582exp fn rect(self paint: &var Paint, area: Rect, fill: Fill) {583    paint.rounded_rect(area, Radii::none(), move fill);584}585586exp fn rounded_rect(self paint: &var Paint, area: Rect, radii: Radii, fill: Fill) {587    var p = Primitive::of(Kind::Solid, area, radii);588    match (fill) {589        ::Color |c| {590            p.color = c;591        }592        ::Linear |&g| {593            p.kind = Kind::Linear;594            paint.gradient(&var p, &g);595        }596        ::Radial |&g| {597            p.kind = Kind::Radial;598            paint.gradient(&var p, &g);599            const dx = g.end.x - g.start.x;600            const dy = g.end.y - g.start.y;601            p.extra[2] = sqrt(dx * dx + dy * dy);602            p.extra[3] = 0.0;603        }604    }605    paint.items.push(p);606}607608fn gradient(self paint: &var Paint, p: &var Primitive, g: &Gradient) {609    if (g.stops.length() == 0 || g.stops.length() > MAX_STOPS) {610        panic "pkg::alloy::draw: a gradient takes from 1 to 8 stops";611    }612    p.params[0] = (paint.stops.length() / 4) to f32;613    p.params[1] = g.stops.length() to f32;614    p.extra = [g.start.x, g.start.y, g.end.x, g.end.y];615    p.color = Color::white();616    for (g.stops.view()) |&s| {617        paint.stops.append(&[s.color.r, s.color.g, s.color.b, s.color.a, s.offset, 0.0, 0.0, 0.0]);618    }619}620621// A border of the width inside the rounded rectangle's edge.622exp fn border(self paint: &var Paint, area: Rect, radii: Radii, width: f32, color: Color) {623    var p = Primitive::of(Kind::Border, area, radii);624    p.color = color;625    p.params[0] = width;626    paint.items.push(p);627}628629// The rounded rectangle's shadow, drawn under what follows. One radius630// shapes it, the top left one.631exp fn shadow(self paint: &var Paint, area: Rect, radii: Radii, shadow: Shadow) {632    const shape = Rect::at(633        area.x + shadow.offset.x,634        area.y + shadow.offset.y,635        area.width,636        area.height637    ).inflated(shadow.spread);638    const radius = max(radii.top_left + shadow.spread, 0.0);639    if (shadow.blur <= 0.0) {640        paint.rounded_rect(shape, Radii::all(radius), Fill::Color(shadow.color));641        return;642    }643    var p = Primitive::of(Kind::Shadow, shape, Radii::all(radius));644    p.color = shadow.color;645    p.params[0] = shadow.blur * 0.5;646    paint.items.push(p);647}648649// The picture stretched over the area, filtered linearly.650exp fn image(self paint: &var Paint, area: Rect, picture: Picture) {651    paint.image(area, picture, Filter::Linear);652}653654exp fn image(self paint: &var Paint, area: Rect, picture: Picture, filter: Filter) {655    var p = Primitive::of(656        Kind::Image(Sampled { .texture = picture.texture, .linear = filter is ::Linear }),657        area,658        Radii::none()659    );660    p.color = Color::white();661    p.extra = picture.texture_bounds();662    paint.items.push(p);663}664665// The color where the picture, a coverage mask, covers the area.666exp fn mask(self paint: &var Paint, area: Rect, picture: Picture, color: Color) {667    var p = Primitive::of(668        Kind::Mask(Sampled { .texture = picture.texture, .linear = true }),669        area,670        Radii::none()671    );672    p.color = color;673    p.extra = picture.texture_bounds();674    paint.items.push(p);675}676677/* --- The canvas --- */678679// A node of a canvas, valid until it is removed.680exp type NodeId = struct {681    pub index: u32,682    pub generation: u32,683};684685// A clip: its children draw only inside the rounded rectangle, in the686// node's coordinates.687exp type Clip = struct {688    exp area: Rect,689    exp radii: Radii,690};691692exp fn Clip::rect(area: Rect) -> Clip {693    return Clip { .area = area, .radii = Radii::none() };694}695696exp fn Clip::rounded(area: Rect, radius: f32) -> Clip {697    return Clip { .area = area, .radii = Radii::all(radius) };698}699700// What the last frame drew, for tests and benchmarks.701exp type FrameStats = struct {702    exp rects: Vector<Rect>, // the damaged rectangles redrawn, whole pixels703    exp full: bool, // the whole frame redrawn704    exp instances: u32, // the primitives drawn, a clear for each rectangle included705    exp draws: u32,706};707708exp type Canvas = struct {709    pub format: TextureFormat,710    pub background: Color,711    pub nodes: Vector<Node>,712    pub free: Vector<u32>,713    pub damage: Vector<Rect>, // device rectangles changed since the last frame714    pub everything: bool, // the next frame redraws everything715    pub pending: bool,716    pub size: Size, // the kept texture's717    pub gpu: Resources,718    pub stats: FrameStats,719    pub fonts: Option<Fonts>, // made when first asked for, so programs drawing no text leave the bundled faces out720};721722// A canvas drawing into textures of the format: a surface's, or one the723// program reads back.724exp fn Canvas::create(device: &var Device, format: TextureFormat) -> Canvas {725    var nodes = Vector<Node>::empty();726    nodes.push(Node::create(::None, 0));727    return Canvas {728        .format = format,729        .background = Color::white(),730        .nodes = move nodes,731        .free = Vector<u32>::empty(),732        .damage = Vector<Rect>::empty(),733        .everything = true,734        .pending = true,735        .size = Size { .width = 0, .height = 0 },736        .gpu = Resources::create(&var device, &DRAW, format),737        .stats = FrameStats {738            .rects = Vector<Rect>::empty(),739            .full = false,740            .instances = 0,741            .draws = 0742        },743        .fonts = ::None744    };745}746747// The fonts the canvas draws text in, the bundled family first, for the748// layouts it draws.749exp fn fonts(self canvas: &var Canvas) -> &var Fonts {750    if (canvas.fonts is ::None) {751        canvas.fonts = ::Some(Fonts::create());752    }753    if (canvas.fonts is ::Some |&var fonts|) {754        return &var fonts;755    }756    panic "pkg::alloy::draw: no fonts";757}758759// A TrueType face as a family of its own (pkg::alloy::text's760// `Fonts::add`).761exp fn add_font(self canvas: &var Canvas, bytes: Vector<u8>) -> Option<Family> {762    return canvas.fonts().add(move bytes);763}764765exp fn add_font_to(self canvas: &var Canvas, family: Family, bytes: Vector<u8>) -> bool {766    return canvas.fonts().add_to(family, move bytes);767}768769// Releases what the canvas made on the device: its pictures' textures770// among them.771exp fn release(self canvas: &var Canvas, device: &var Device) {772    canvas.gpu.release(&var device);773}774775// The node every other descends from, which the canvas never removes.776exp fn root(self canvas: &Canvas) -> NodeId {777    return NodeId { .index = 0, .generation = canvas.nodes.get(0).generation };778}779780// A new node, the parent's last child: it draws after the parent's781// other children, over them.782exp fn add(self canvas: &var Canvas, parent: NodeId) -> NodeId {783    canvas.check(parent);784    var index = canvas.nodes.length() to u32;785    if (canvas.free.pop() is ::Some |k|) {786        index = k;787        const generation = canvas.nodes.get(k to u64).generation;788        canvas.nodes.set(k to u64, Node::create(::Some(parent.index), generation));789    } else {790        canvas.nodes.push(Node::create(::Some(parent.index), 0));791    }792    canvas.nodes.get_var(parent.index to u64).children.push(index);793    canvas.mark(index, Change::Moved);794    return NodeId { .index = index, .generation = canvas.nodes.get(index to u64).generation };795}796797// Removes the node and its descendants; what they drew is damaged.798exp fn remove(self canvas: &var Canvas, node: NodeId) {799    canvas.check(node);800    if (node.index == 0) {801        panic "pkg::alloy::draw: the root node is never removed";802    }803    if (canvas.nodes.get(node.index to u64).parent is ::Some |parent|) {804        var siblings = &var canvas.nodes.get_var(parent to u64).children;805        for ([..siblings.length()]) |k| {806            if (siblings.get(k) == node.index) {807                siblings.remove(k);808                break;809            }810        }811    }812    canvas.retire(node.index);813    canvas.pending = true;814}815816fn retire(self canvas: &var Canvas, index: u32) {817    const count = canvas.nodes.get(index to u64).children.length();818    for ([..count]) |k| {819        canvas.retire(canvas.nodes.get(index to u64).children.get(k));820    }821    canvas.add_damage(canvas.nodes.get(index to u64).bounds);822    var n = &var canvas.nodes.get_var(index to u64);823    n.alive = false;824    n.generation += 1;825    n.children.clear();826    n.paint = Paint::empty();827    canvas.free.push(index);828}829830// Whether the node is still there: neither it nor an ancestor removed.831exp fn contains(self canvas: &Canvas, node: NodeId) -> bool {832    return node.index to u64 < canvas.nodes.length()833        && canvas.nodes.get(node.index to u64).alive834        && canvas.nodes.get(node.index to u64).generation == node.generation;835}836837// Moves the node and its descendants: the transform takes its838// coordinates into its parent's.839exp fn set_transform(self canvas: &var Canvas, node: NodeId, transform: Transform) {840    canvas.check(node);841    canvas.nodes.get_var(node.index to u64).transform = transform;842    canvas.mark(node.index, Change::Moved);843}844845exp fn transform(self canvas: &Canvas, node: NodeId) -> Transform {846    canvas.check(node);847    return canvas.nodes.get(node.index to u64).transform;848}849850// Clips the node's children, not its own paint, to the rounded851// rectangle; None draws them whole.852exp fn set_clip(self canvas: &var Canvas, node: NodeId, clip: Option<Clip>) {853    canvas.check(node);854    canvas.nodes.get_var(node.index to u64).clip = clip;855    canvas.mark(node.index, Change::Moved);856}857858// Hides the node and its descendants, which keep what they draw, or859// shows them again; where they are is damaged.860exp fn set_hidden(self canvas: &var Canvas, node: NodeId, hidden: bool) {861    canvas.check(node);862    const n = &var canvas.nodes.get_var(node.index to u64);863    if (n.hidden == hidden) {864        return;865    }866    n.hidden = hidden;867    const reach = n.reach;868    canvas.add_damage(reach);869    canvas.mark(node.index, Change::Moved);870}871872// Fades the node and its descendants: the alpha of all they draw873// multiplied by the opacity, from 0 (nothing drawn) to 1, as each874// primitive is drawn, so where they overlap the lower shows through the875// upper. Where they draw is damaged.876exp fn set_opacity(self canvas: &var Canvas, node: NodeId, opacity: f32) {877    canvas.check(node);878    const n = &var canvas.nodes.get_var(node.index to u64);879    const o = clamp(opacity, 0.0, 1.0);880    if (n.opacity == o) {881        return;882    }883    n.opacity = o;884    const reach = n.reach;885    canvas.add_damage(reach);886    canvas.pending = true;887}888889exp fn opacity(self canvas: &Canvas, node: NodeId) -> f32 {890    canvas.check(node);891    return canvas.nodes.get(node.index to u64).opacity;892}893894// Whether the node is hidden.895exp fn is_hidden(self canvas: &Canvas, node: NodeId) -> bool {896    canvas.check(node);897    return canvas.nodes.get(node.index to u64).hidden;898}899900// Replaces what the node draws.901exp fn paint(self canvas: &var Canvas, node: NodeId, paint: Paint) {902    canvas.check(node);903    var kept = move paint;904    kept.shrink();905    canvas.nodes.get_var(node.index to u64).paint = move kept;906    canvas.mark(node.index, Change::Painted);907}908909// The color under everything, white at first.910exp fn set_background(self canvas: &var Canvas, color: Color) {911    canvas.background = color;912    canvas.damage_all();913}914915// Whether a frame would change anything: false, the last one stands.916exp fn damaged(self canvas: &Canvas) -> bool {917    return canvas.pending;918}919920// Redraws the whole next frame, as after the window's size changed.921exp fn damage_all(self canvas: &var Canvas) {922    canvas.everything = true;923    canvas.pending = true;924}925926// Records the frame's drawing into the encoder: what changed since the927// last frame redrawn into the texture the canvas keeps, which is then928// copied to the frame, a texture of the canvas's format that copies929// may write. A frame of another size than the last redraws everything.930exp fn render(931    self canvas: &var Canvas,932    device: &var Device,933    encoder: &var Encoder,934    frame: Texture935) {936    canvas.draw_frame(&var device, &var encoder, frame, false);937}938939// The same, but blending the kept texture over what the frame holds940// instead of copying it, its premultiplied alpha letting the frame show941// where the canvas draws nothing: a canvas whose background is942// transparent over another's drawing, as an engine's (pkg::alloy::ui's943// `Hud`). Every frame blends, whether anything changed or not.944exp fn render_over(945    self canvas: &var Canvas,946    device: &var Device,947    encoder: &var Encoder,948    frame: Texture949) {950    canvas.draw_frame(&var device, &var encoder, frame, true);951}952953// The texture the canvas keeps its drawing in, of the last frame's size,954// for a program placing it itself; None before the first frame.955exp fn texture(self canvas: &Canvas) -> Option<Texture> => canvas.gpu.kept;956957// What the last frame drew.958exp fn stats(self canvas: &Canvas) -> &FrameStats {959    return &canvas.stats;960}961962// How many pages of glyphs the canvas keeps of each format, each cut963// into 4 by 4 plots, which it clears the least recently used of when it964// needs room. A frame needing more than these gets pages past them,965// given back in the frames after it.966exp type GlyphBudget = struct {967    exp coverage: u32 = 4, // pages of one-byte pixels: 4 MiB968    exp color: u32 = 2, // pages of RGBA: 8 MiB969    exp page: u32 = 1024, // a page's width and height in pixels, a multiple of 4970};971972// What the glyph cache holds, and what its last frame did.973exp type GlyphStats = struct {974    exp pages: u32, // the glyphs' textures, a large glyph's own among them975    exp past: u32, // of them past the budget976    exp plots: u32, // holding glyphs977    exp bytes: u64, // the textures'978    exp entries: u64, // the glyphs the cache knows979    exp rasterized: u32, // by the last frame980    exp cleared: u32, // plots, by the last frame981};982983// Sets the glyph cache's budget, which pages past it follow from the984// next frame on; a change of the page's size empties the cache.985exp fn set_glyph_budget(self canvas: &var Canvas, device: &var Device, budget: GlyphBudget) {986    const released = canvas.gpu.glyph_cache.set_budget(&var device, budget);987    for (released.view()) |t| {988        canvas.gpu.forget(&var device, t);989    }990}991992exp fn glyph_stats(self canvas: &Canvas) -> GlyphStats => canvas.gpu.glyph_cache.stats();993994// Packs the image, RGBA rows with straight alpha, into a texture the995// canvas keeps: small ones share pages of an atlas.996exp fn picture(997    self canvas: &var Canvas,998    device: &var Device,999    width: u32,1000    height: u32,1001    pixels: &[u8]1002) -> Picture {1003    return canvas.gpu.pack(&var device, width, height, &pixels, TextureFormat::Rgba8Unorm);1004}10051006// Gives back what a picture `picture` packed holds, for the next one;1007// nothing may draw it afterwards.1008exp fn release_picture(self canvas: &var Canvas, device: &var Device, picture: Picture) {1009    canvas.gpu.unpack(&var device, picture);1010}10111012// Packs a coverage mask, a byte a pixel, as glyphs are.1013exp fn mask(1014    self canvas: &var Canvas,1015    device: &var Device,1016    width: u32,1017    height: u32,1018    coverage: &[u8]1019) -> Picture {1020    return canvas.gpu.pack(&var device, width, height, &coverage, TextureFormat::R8Unorm);1021}10221023fn check(self canvas: &Canvas, node: NodeId) {1024    const n = &canvas.nodes.get(node.index to u64);1025    if (!n.alive || n.generation != node.generation) {1026        panic "pkg::alloy::draw: a node used after its removal";1027    }1028}10291030// What changed of a node.1031pub type Change = enum {1032    Painted, // its paint1033    Moved, // its transform or clip, so its descendants' places too1034};10351036// Marks the node to measure again, and its ancestors to visit it.1037pub fn mark(self canvas: &var Canvas, index: u32, change: Change) {1038    canvas.pending = true;1039    var n = &var canvas.nodes.get_var(index to u64);1040    match (change) {1041        ::Painted {1042            n.dirty = true;1043        }1044        ::Moved {1045            n.moved = true;1046        }1047    }1048    var k = n.parent;1049    while (k is ::Some |i|) {1050        var p = &var canvas.nodes.get_var(i to u64);1051        if (p.below) {1052            return;1053        }1054        p.below = true;1055        k = p.parent;1056    }1057}