summaryrefslogtreecommitdiff
path: root/src/host/gfx.zig
blob: 95c3ecc768a50633524d03a5f8b6c38b70af77d5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
//! Images and drawing. Textures have host lifetime; sketches hold handles.
const std = @import("std");
const c = @import("c");
const abi = @import("abi");

pub const Images = struct {
    gpa: std.mem.Allocator,
    renderer: *c.SDL_Renderer,
    /// Handle `n` is `entries[n - 1]`.
    entries: std.ArrayList(Entry) = .empty,
    paths: std.StringHashMapUnmanaged(abi.Image) = .empty,

    const Entry = struct {
        texture: ?*c.SDL_Texture = null,
        w: u32 = 0,
        h: u32 = 0,
        /// Holds premultiplied colour: a target drawn into, a GPU pass's
        /// output, or premultiplied `pixels`.
        premultiplied: bool = false,
        /// Made by `new`: a render target for `Command.target`.
        target: bool = false,
        /// Scales smoothly (GPU pass output), not nearest.
        smooth: bool = false,
        /// A target's supersampled self (`factor` times the size), which
        /// 2D commands draw into; `texture` is its average, brought up to
        /// date (`stale`) before the image is drawn.
        big: ?*c.SDL_Texture = null,
        factor: u32 = 1,
        stale: bool = false,

        fn release(entry: *Entry) void {
            if (entry.texture) |t| c.SDL_DestroyTexture(t);
            if (entry.big) |t| c.SDL_DestroyTexture(t);
            entry.* = .{};
        }
    };

    pub fn deinit(self: *Images) void {
        for (self.entries.items) |*entry| entry.release();
        self.entries.deinit(self.gpa);
        var keys = self.paths.keyIterator();
        while (keys.next()) |key| self.gpa.free(key.*);
        self.paths.deinit(self.gpa);
    }

    pub fn load(self: *Images, path: []const u8) abi.Image {
        if (self.paths.get(path)) |image| return image;
        var buf: [std.fs.max_path_bytes]u8 = undefined;
        const z = std.mem.printSentinel(&buf, "{s}", .{path}, 0) catch return .none;
        const surface = c.SDL_LoadPNG(z.ptr);
        if (surface == null) std.log.warn("image {s}: {s}", .{ path, c.SDL_GetError() });
        const image = self.add(surface);
        const key = self.gpa.dupe(u8, path) catch return image;
        self.paths.put(self.gpa, key, image) catch self.gpa.free(key);
        return image;
    }

    pub fn decode(self: *Images, png: []const u8) abi.Image {
        const io = c.SDL_IOFromConstMem(png.ptr, png.len) orelse return .none;
        return self.add(c.SDL_LoadPNG_IO(io, true));
    }

    /// A blank (transparent) image, which `Command.pixels` fills and
    /// `Command.target` draws into: a render target, cleared now, since a
    /// new SDL texture's contents are undefined (a canvas starts clear).
    pub fn new(self: *Images, w: u32, h: u32) abi.Image {
        const texture = c.SDL_CreateTexture(self.renderer, c.SDL_PIXELFORMAT_RGBA32, c.SDL_TEXTUREACCESS_TARGET, @intCast(w), @intCast(h));
        if (texture) |t| {
            setup(t);
            const previous = c.SDL_GetRenderTarget(self.renderer);
            _ = c.SDL_SetRenderTarget(self.renderer, t);
            _ = c.SDL_SetRenderDrawColor(self.renderer, 0, 0, 0, 0);
            _ = c.SDL_RenderClear(self.renderer);
            _ = c.SDL_SetRenderTarget(self.renderer, previous);
        }
        return self.append(.{ .texture = texture, .w = w, .h = h, .premultiplied = true, .target = texture != null });
    }

    /// Makes `image` show a GPU render target (GPU renderer only).
    pub fn wrap(self: *Images, image: abi.Image, gpu_texture: *anyopaque, w: u32, h: u32) !void {
        const entry = self.get(image) orelse return error.UnknownImage;
        const props = c.SDL_CreateProperties();
        defer c.SDL_DestroyProperties(props);
        _ = c.SDL_SetPointerProperty(props, c.SDL_PROP_TEXTURE_CREATE_GPU_TEXTURE_POINTER, gpu_texture);
        _ = c.SDL_SetNumberProperty(props, c.SDL_PROP_TEXTURE_CREATE_FORMAT_NUMBER, c.SDL_PIXELFORMAT_ABGR8888);
        _ = c.SDL_SetNumberProperty(props, c.SDL_PROP_TEXTURE_CREATE_WIDTH_NUMBER, w);
        _ = c.SDL_SetNumberProperty(props, c.SDL_PROP_TEXTURE_CREATE_HEIGHT_NUMBER, h);
        const texture = c.SDL_CreateTextureWithProperties(self.renderer, props) orelse return error.WrapTexture;
        // Rendered output: smooth scaling, and already premultiplied.
        _ = c.SDL_SetTextureScaleMode(texture, c.SDL_SCALEMODE_LINEAR);
        entry.release();
        entry.* = .{ .texture = texture, .w = w, .h = h, .premultiplied = true, .smooth = true };
    }

    /// Stops showing a wrapped render target, before the target goes away.
    pub fn unwrap(self: *Images, image: abi.Image) void {
        const entry = self.get(image) orelse return;
        if (entry.texture) |t| c.SDL_DestroyTexture(t);
        entry.texture = null;
    }

    pub fn free(self: *Images, image: abi.Image) void {
        const entry = self.get(image) orelse return;
        entry.release();
    }

    pub fn size(self: *Images, image: abi.Image) [2]u32 {
        const entry = self.get(image) orelse return .{ 0, 0 };
        return .{ entry.w, entry.h };
    }

    pub fn get(self: *Images, image: abi.Image) ?*Entry {
        const index = @backingInt(image);
        if (index == 0 or index > self.entries.items.len) return null;
        return &self.entries.items[index - 1];
    }

    /// Takes ownership of `surface`, which may be null (a missing image).
    fn add(self: *Images, surface: ?*c.SDL_Surface) abi.Image {
        const s = surface orelse return self.append(.{});
        defer c.SDL_DestroySurface(s);
        const texture = c.SDL_CreateTextureFromSurface(self.renderer, s);
        if (texture) |t| setup(t);
        return self.append(.{ .texture = texture, .w = @intCast(s.*.w), .h = @intCast(s.*.h) });
    }

    fn append(self: *Images, entry: Entry) abi.Image {
        self.entries.append(self.gpa, entry) catch return .none;
        return @fromBackingInt(@intCast(self.entries.items.len));
    }

    fn setup(texture: *c.SDL_Texture) void {
        _ = c.SDL_SetTextureScaleMode(texture, c.SDL_SCALEMODE_NEAREST);
    }
};

/// Plays 2D commands into the renderer, keeping what they leave behind
/// (target, blend) and the antialiasing textures. One per host; `begin`
/// and `end` bracket a frame.
///
/// Antialiasing (with a GPU renderer) is supersampling, 4x4 samples a
/// pixel, averaged by halving twice (bilinear sampling at the centre of a
/// 2x2 block is their exact mean), so coverage resolves per sample:
/// - On the canvas, consecutive shapes are drawn into `layer` and
///   composited together, premultiplied, when another command comes.
/// - A target is supersampled whole (`Entry.big`): everything drawn into
///   it is, and it is averaged when drawn. Its picture is therefore the
///   same however its commands were split into frames, so a trail
///   repainted at once after a seek equals the one painted step by step.
pub const Painter = struct {
    renderer: *c.SDL_Renderer,
    images: *Images,
    /// The canvas's render target: null for the window, or the headless
    /// host's offscreen texture.
    canvas: ?*c.SDL_Texture = null,
    canvas_size: [2]u32 = .{ 0, 0 },
    /// Antialias (a GPU renderer); false draws everything aliased.
    smooth: bool = false,
    /// Per-vertex colours, for one frame.
    arena: std.mem.Allocator = undefined,
    target: abi.Image = .none,
    blend: abi.BlendMode = .alpha,
    layer: Layer = .{},
    /// Half-way through averaging (2x), shared; `half_size` in its pixels.
    half: ?*c.SDL_Texture = null,
    half_size: [2]u32 = .{ 0, 0 },

    const Layer = struct {
        big: ?*c.SDL_Texture = null,
        /// Room in `big`, in its pixels.
        w: u32 = 0,
        h: u32 = 0,
        /// Open: shapes went into it since the last composite.
        open: bool = false,
        blend: abi.BlendMode = .alpha,
        factor: u32 = 4,
        /// What the open layer's shapes cover, in canvas pixels (x0, y0,
        /// x1, y1); after a composite, what still holds them, cleared
        /// when the next layer opens.
        dirty: [4]u32 = .{ 0, 0, 0, 0 },
    };

    /// 16 samples a pixel, unless that takes more than a 3840x2160 canvas
    /// does at 4 (what 1920x1080 takes at 16: a 127 MiB layer); 4, then;
    /// else none.
    const max_samples = 3840 * 2160 * 4;

    fn factorFor(size: [2]u32) u32 {
        const pixels = @as(u64, size[0]) * size[1];
        return if (pixels * 16 <= max_samples) 4 else if (pixels * 4 <= max_samples) 2 else 1;
    }

    pub fn deinit(p: *Painter) void {
        if (p.layer.big) |t| c.SDL_DestroyTexture(t);
        if (p.half) |t| c.SDL_DestroyTexture(t);
        p.layer = .{};
        p.half = null;
        p.half_size = .{ 0, 0 };
    }

    pub fn begin(p: *Painter, canvas: ?*c.SDL_Texture, size: [2]u32, arena: std.mem.Allocator) void {
        p.canvas = canvas;
        p.canvas_size = size;
        p.arena = arena;
        p.target = .none;
        p.blend = .alpha;
    }

    /// Back to the canvas, blending alpha, unclipped: where overlays draw
    /// and screenshots read.
    pub fn end(p: *Painter) void {
        p.flush();
        if (p.target != .none) {
            p.target = .none;
            _ = c.SDL_SetRenderTarget(p.renderer, p.canvas);
        }
        p.blend = .alpha;
        _ = c.SDL_SetRenderClipRect(p.renderer, null);
    }

    /// Draws one graphics command. Other commands are not graphics: ignored.
    pub fn draw(p: *Painter, command: abi.Command) void {
        if (command != .shape) p.flush();
        const renderer = p.renderer;
        switch (command) {
            .clear => |color| {
                if (@import("builtin").os.tag == .linux and p.target == .none) c.sk_text_begin_frame(renderer);
                // A target holds premultiplied colour, as a canvas cleared
                // to a translucent colour does.
                setColor(renderer, if (p.target == .none) color else premultiply(color));
                _ = c.SDL_RenderClear(renderer);
            },
            .rect => |r| {
                setColor(renderer, r.color);
                _ = c.SDL_SetRenderDrawBlendMode(renderer, drawBlend(p.blend));
                _ = c.SDL_RenderFillRect(renderer, &frect(r.dst));
            },
            .shape => |s| p.shape(s.color, s.points, s.ends, s.indices, s.colors),
            .image => |img| p.drawImage(img.image, img.dst, img.src, img.tint, img.corners),
            .text => |text| {
                _ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_BLEND);
                drawText(renderer, text.x, text.y, text.scale, text.bytes, text.color, text.face, if (text.raster > 0) text.raster else text.scale);
            },
            .clip => |clip| {
                if (clip) |r| {
                    const rect: c.SDL_Rect = .{ .x = @intFromFloat(r.x), .y = @intFromFloat(r.y), .w = @intFromFloat(r.w), .h = @intFromFloat(r.h) };
                    _ = c.SDL_SetRenderClipRect(renderer, &rect);
                } else _ = c.SDL_SetRenderClipRect(renderer, null);
            },
            .pixels => |px| {
                const entry = p.images.get(px.image) orelse return;
                const texture = entry.texture orelse return;
                if (px.w != entry.w or px.h != entry.h or px.rgba.len < @as(usize, px.w) * px.h * 4) return;
                entry.premultiplied = px.premultiplied;
                _ = c.SDL_UpdateTexture(texture, null, px.rgba.ptr, @intCast(px.w * 4));
                if (entry.big != null) p.spread(entry);
            },
            .target => |img| p.setTarget(img),
            .blend => |mode| p.blend = mode,
            else => {},
        }
    }

    fn setTarget(p: *Painter, handle: abi.Image) void {
        const texture = if (handle == .none) p.canvas else blk: {
            const entry = p.images.get(handle) orelse return;
            if (!entry.target or entry.texture == null) return;
            if (entry.big == null and p.smooth) p.supersample(entry);
            entry.stale = entry.big != null;
            break :blk entry.big orelse entry.texture;
        };
        p.target = handle;
        _ = c.SDL_SetRenderTarget(p.renderer, texture);
        _ = c.SDL_SetRenderClipRect(p.renderer, null);
    }

    /// Gives a target its supersampled self, holding what it shows now.
    fn supersample(p: *Painter, entry: *Images.Entry) void {
        const factor = factorFor(.{ entry.w, entry.h });
        if (factor == 1) return;
        const big = c.SDL_CreateTexture(p.renderer, c.SDL_PIXELFORMAT_RGBA32, c.SDL_TEXTUREACCESS_TARGET, @intCast(entry.w * factor), @intCast(entry.h * factor)) orelse return;
        _ = c.SDL_SetTextureScaleMode(big, c.SDL_SCALEMODE_LINEAR);
        entry.big = big;
        entry.factor = factor;
        const f: f32 = @floatFromInt(factor);
        const previous = c.SDL_GetRenderTarget(p.renderer);
        _ = c.SDL_SetRenderTarget(p.renderer, big);
        _ = c.SDL_SetRenderScale(p.renderer, f, f);
        _ = c.SDL_SetRenderTarget(p.renderer, previous);
        p.spread(entry);
    }

    /// Copies a target's `texture` into its supersampled self (after
    /// `pixels` replaced it), each pixel into its samples.
    fn spread(p: *Painter, entry: *Images.Entry) void {
        const previous = c.SDL_GetRenderTarget(p.renderer);
        _ = c.SDL_SetRenderTarget(p.renderer, entry.big);
        const t = entry.texture.?;
        _ = c.SDL_SetTextureBlendMode(t, c.SDL_BLENDMODE_NONE);
        _ = c.SDL_SetTextureColorMod(t, 255, 255, 255);
        _ = c.SDL_SetTextureAlphaMod(t, 255);
        _ = c.SDL_RenderTexture(p.renderer, t, null, &.{ .x = 0, .y = 0, .w = @floatFromInt(entry.w), .h = @floatFromInt(entry.h) });
        _ = c.SDL_SetRenderTarget(p.renderer, previous);
        entry.stale = false;
    }

    /// Brings a target's `texture` up to date: its samples averaged.
    fn resolve(p: *Painter, entry: *Images.Entry) void {
        entry.stale = false;
        const previous = c.SDL_GetRenderTarget(p.renderer);
        p.average(entry.big.?, entry.factor, .{ 0, 0, entry.w, entry.h }, entry.texture.?, c.SDL_BLENDMODE_NONE);
        _ = c.SDL_SetRenderTarget(p.renderer, previous);
    }

    /// Draws `box` (destination pixels) of `from`, `factor` times larger,
    /// averaged into `to` with `blend`. Leaves `to` the render target.
    fn average(p: *Painter, from: *c.SDL_Texture, factor: u32, box: [4]u32, to: ?*c.SDL_Texture, blend: c.SDL_BlendMode) void {
        var source = from;
        var k: f32 = @floatFromInt(factor);
        if (factor == 4) half: {
            const need: [2]u32 = .{ box[2] * 2, box[3] * 2 };
            if (p.half == null or p.half_size[0] < need[0] or p.half_size[1] < need[1]) {
                if (p.half) |t| c.SDL_DestroyTexture(t);
                const size: [2]u32 = .{ @max(need[0], p.half_size[0]), @max(need[1], p.half_size[1]) };
                p.half = c.SDL_CreateTexture(p.renderer, c.SDL_PIXELFORMAT_RGBA32, c.SDL_TEXTUREACCESS_TARGET, @intCast(size[0]), @intCast(size[1]));
                p.half_size = if (p.half != null) size else .{ 0, 0 };
                if (p.half) |t| _ = c.SDL_SetTextureScaleMode(t, c.SDL_SCALEMODE_LINEAR) else break :half;
            }
            _ = c.SDL_SetRenderTarget(p.renderer, p.half);
            plain(from, c.SDL_BLENDMODE_NONE);
            _ = c.SDL_RenderTexture(p.renderer, from, &frect(scaledBox(box, 4)), &frect(scaledBox(box, 2)));
            source = p.half.?;
            k = 2;
        }
        _ = c.SDL_SetRenderTarget(p.renderer, to);
        plain(source, blend);
        _ = c.SDL_RenderTexture(p.renderer, source, &frect(scaledBox(box, k)), &frect(scaledBox(box, 1)));
    }

    /// The current destination's size in its own pixels.
    fn destinationSize(p: *Painter) [2]u32 {
        if (p.target == .none) return p.canvas_size;
        const entry = p.images.get(p.target) orelse return p.canvas_size;
        return .{ entry.w, entry.h };
    }

    fn drawImage(p: *Painter, handle: abi.Image, dst: abi.Rect, src_rect: abi.Rect, tint: abi.Color, corners: ?abi.Corners) void {
        const renderer = p.renderer;
        const entry = p.images.get(handle);
        const texture = if (entry) |e| e.texture else null;
        const t = texture orelse return missing(renderer, dst);
        const e = entry.?;
        if (handle == p.target) return; // Drawing into itself: nothing.
        if (e.stale) p.resolve(e);
        // A premultiplied texture needs its colour scaled by the tint's
        // alpha too, which SDL's alpha mod does not do.
        const scale: u32 = if (e.premultiplied) tint.a else 255;
        _ = c.SDL_SetTextureColorMod(t, @intCast(@as(u32, tint.r) * scale / 255), @intCast(@as(u32, tint.g) * scale / 255), @intCast(@as(u32, tint.b) * scale / 255));
        _ = c.SDL_SetTextureAlphaMod(t, tint.a);
        _ = c.SDL_SetTextureBlendMode(t, textureBlend(p.blend, e.premultiplied));
        const src = frect(src_rect);
        const srcp = if (src_rect.w > 0) &src else null;
        if (corners) |q| {
            const origin: c.SDL_FPoint = .{ .x = q.top_left[0], .y = q.top_left[1] };
            const right: c.SDL_FPoint = .{ .x = q.top_right[0], .y = q.top_right[1] };
            const down: c.SDL_FPoint = .{ .x = q.bottom_left[0], .y = q.bottom_left[1] };
            _ = c.SDL_RenderTextureAffine(renderer, t, srcp, &origin, &right, &down);
        } else _ = c.SDL_RenderTexture(renderer, t, srcp, &frect(dst));
    }

    /// `Command.shape`: its triangles in one geometry call, one colour for
    /// every vertex (stride 0, nothing copied) or each subpath's. The
    /// subpaths are for the web; native needs only the triangles.
    fn shape(p: *Painter, color: abi.Color, points: []const [2]f32, ends: []const u32, indices: []const u32, colors: []const abi.Color) void {
        const count = indices.len - indices.len % 3;
        if (count == 0 or points.len == 0 or points.len > std.math.maxInt(c_int) or count > std.math.maxInt(c_int)) return;
        for (indices[0..count]) |i| if (i >= points.len) return;
        var one = fcolor(color);
        var vertex_colors: []const c.SDL_FColor = (&one)[0..1];
        var stride: c_int = 0;
        if (colors.len > 0) {
            const each = p.arena.alloc(c.SDL_FColor, points.len) catch return;
            @memset(each, one);
            var start: usize = 0;
            for (ends, 0..) |subpath_end, i| {
                if (i >= colors.len) break;
                const stop = @min(subpath_end, points.len);
                if (stop > start) @memset(each[start..stop], fcolor(colors[i]));
                start = @max(start, stop);
            }
            vertex_colors = each;
            stride = @sizeOf(c.SDL_FColor);
        }
        // A supersampled target takes shapes as they are; the canvas
        // through the layer.
        if (p.target == .none and p.smooth) {
            const box = bounds(points, indices[0..count], p.canvas_size) orelse return;
            if (!p.openLayer(box)) return;
        }
        _ = c.SDL_SetRenderDrawBlendMode(p.renderer, drawBlend(p.blend));
        _ = c.SDL_RenderGeometryRaw(p.renderer, null, @ptrCast(points.ptr), @sizeOf([2]f32), vertex_colors.ptr, stride, null, 0, @intCast(points.len), indices.ptr, @intCast(count), @sizeOf(u32));
    }

    /// Makes the layer the render target for a shape covering `box`
    /// (canvas pixels): the open one, if for this blend, else a new one.
    /// False if there is no room for one (the shape is then drawn on the
    /// canvas, aliased).
    fn openLayer(p: *Painter, box: [4]u32) bool {
        const l = &p.layer;
        if (l.open and l.blend == p.blend) {
            l.dirty = .{ @min(l.dirty[0], box[0]), @min(l.dirty[1], box[1]), @max(l.dirty[2], box[2]), @max(l.dirty[3], box[3]) };
            return true;
        }
        p.flush();
        const size = p.canvas_size;
        const factor = factorFor(size);
        if (factor == 1) return true;
        const w = size[0] * factor;
        const h = size[1] * factor;
        if (l.big == null or l.w < w or l.h < h) {
            if (l.big) |t| c.SDL_DestroyTexture(t);
            l.* = .{ .w = w, .h = h };
            l.big = c.SDL_CreateTexture(p.renderer, c.SDL_PIXELFORMAT_RGBA32, c.SDL_TEXTUREACCESS_TARGET, @intCast(w), @intCast(h));
            const big = l.big orelse {
                std.log.warn("no antialiasing layer: {s}", .{c.SDL_GetError()});
                p.smooth = false;
                return true;
            };
            _ = c.SDL_SetTextureScaleMode(big, c.SDL_SCALEMODE_LINEAR);
            // Cleared whole once; afterwards only what a composite left.
            _ = c.SDL_SetRenderTarget(p.renderer, big);
            _ = c.SDL_SetRenderDrawColor(p.renderer, 0, 0, 0, 0);
            _ = c.SDL_RenderClear(p.renderer);
        }
        _ = c.SDL_SetRenderTarget(p.renderer, l.big);
        const f: f32 = @floatFromInt(factor);
        _ = c.SDL_SetRenderScale(p.renderer, f, f);
        if (l.dirty[2] > l.dirty[0]) {
            // The last layer's shapes, gone: at the scale it drew them.
            const old: f32 = @floatFromInt(l.factor);
            _ = c.SDL_SetRenderDrawBlendMode(p.renderer, c.SDL_BLENDMODE_NONE);
            _ = c.SDL_SetRenderDrawColor(p.renderer, 0, 0, 0, 0);
            _ = c.SDL_RenderFillRect(p.renderer, &frect(scaledBox(l.dirty, old / f)));
        }
        l.factor = factor;
        l.blend = p.blend;
        l.open = true;
        l.dirty = box;
        return true;
    }

    /// Composites an open layer onto the canvas: the rect its shapes
    /// cover, nothing else.
    fn flush(p: *Painter) void {
        const l = &p.layer;
        if (!l.open) return;
        l.open = false;
        p.average(l.big.?, l.factor, l.dirty, p.canvas, textureBlend(l.blend, true));
    }
};

/// A texture drawn as it is: no tint, `blend`.
fn plain(t: *c.SDL_Texture, blend: c.SDL_BlendMode) void {
    _ = c.SDL_SetTextureBlendMode(t, blend);
    _ = c.SDL_SetTextureColorMod(t, 255, 255, 255);
    _ = c.SDL_SetTextureAlphaMod(t, 255);
}

/// The pixels a shape's triangles may touch, one pixel around, clamped to
/// the destination: null if none.
fn bounds(points: []const [2]f32, indices: []const u32, size: [2]u32) ?[4]u32 {
    var lo: [2]f32 = .{ std.math.inf(f32), std.math.inf(f32) };
    var hi: [2]f32 = .{ -std.math.inf(f32), -std.math.inf(f32) };
    for (indices) |i| for (0..2) |axis| {
        lo[axis] = @min(lo[axis], points[i][axis]);
        hi[axis] = @max(hi[axis], points[i][axis]);
    };
    var box: [4]u32 = undefined;
    for (0..2) |axis| {
        const limit: f32 = @floatFromInt(size[axis]);
        const a = std.math.clamp(@floor(lo[axis]) - 1, 0, limit);
        const b = std.math.clamp(@ceil(hi[axis]) + 1, 0, limit);
        if (!(b > a)) return null; // off the destination, or NaN
        box[axis] = @intFromFloat(a);
        box[axis + 2] = @intFromFloat(b);
    }
    return box;
}

/// `box` (x0, y0, x1, y1) times `k`, as a rect.
fn scaledBox(box: [4]u32, k: f32) abi.Rect {
    const x: f32 = @floatFromInt(box[0]);
    const y: f32 = @floatFromInt(box[1]);
    return .{ .x = x * k, .y = y * k, .w = @as(f32, @floatFromInt(box[2] - box[0])) * k, .h = @as(f32, @floatFromInt(box[3] - box[1])) * k };
}

/// Adds colour times alpha, and alpha, as canvas `lighter` does (SDL's
/// `ADD` keeps the destination's alpha).
fn addBlend(premultiplied: bool) c.SDL_BlendMode {
    const src: c.SDL_BlendFactor = if (premultiplied) c.SDL_BLENDFACTOR_ONE else c.SDL_BLENDFACTOR_SRC_ALPHA;
    return c.SDL_ComposeCustomBlendMode(src, c.SDL_BLENDFACTOR_ONE, c.SDL_BLENDOPERATION_ADD, c.SDL_BLENDFACTOR_ONE, c.SDL_BLENDFACTOR_ONE, c.SDL_BLENDOPERATION_ADD);
}

/// Solid colours (straight alpha) onto the destination.
fn drawBlend(blend: abi.BlendMode) c.SDL_BlendMode {
    return switch (blend) {
        .alpha => c.SDL_BLENDMODE_BLEND,
        .add => addBlend(false),
    };
}

fn textureBlend(blend: abi.BlendMode, premultiplied: bool) c.SDL_BlendMode {
    return switch (blend) {
        .alpha => if (premultiplied) c.SDL_BLENDMODE_BLEND_PREMULTIPLIED else c.SDL_BLENDMODE_BLEND,
        .add => addBlend(premultiplied),
    };
}

fn fcolor(color: abi.Color) c.SDL_FColor {
    return .{
        .r = @as(f32, @floatFromInt(color.r)) / 255,
        .g = @as(f32, @floatFromInt(color.g)) / 255,
        .b = @as(f32, @floatFromInt(color.b)) / 255,
        .a = @as(f32, @floatFromInt(color.a)) / 255,
    };
}

/// Native shaped text on Linux, using a 13px monospace face at scale 1.
/// Other targets retain SDL's built-in 8x8 fallback. Coordinates are line-box tops.
pub fn drawText(renderer: *c.SDL_Renderer, x: f32, y: f32, scale: f32, bytes: []const u8, color: abi.Color, face: abi.Face, raster: f32) void {
    if (@import("builtin").os.tag == .linux and c.sk_text_draw_scaled(renderer, @intFromEnum(face), x, y, scale, raster, bytes.ptr, bytes.len, color.r, color.g, color.b, color.a)) return;
    var buf: [1024]u8 = undefined;
    const len = @min(std.mem.indexOfScalar(u8, bytes, 0) orelse bytes.len, buf.len - 1);
    @memcpy(buf[0..len], bytes[0..len]);
    buf[len] = 0;
    setColor(renderer, color);
    var sx: f32 = 1;
    var sy: f32 = 1;
    _ = c.SDL_GetRenderScale(renderer, &sx, &sy);
    const s = @max(scale, 1);
    // The clip rect scales with the renderer: shrink it to match, to the
    // whole pixels around it (so it may let up to `s - 1` pixels more through).
    var clip: c.SDL_Rect = undefined;
    const clipped = c.SDL_RenderClipEnabled(renderer) and c.SDL_GetRenderClipRect(renderer, &clip);
    _ = c.SDL_SetRenderScale(renderer, sx * s, sy * s);
    if (clipped and s != 1) {
        const x0 = @floor(@as(f32, @floatFromInt(clip.x)) / s);
        const y0 = @floor(@as(f32, @floatFromInt(clip.y)) / s);
        const x1 = @ceil(@as(f32, @floatFromInt(clip.x + clip.w)) / s);
        const y1 = @ceil(@as(f32, @floatFromInt(clip.y + clip.h)) / s);
        const scaled: c.SDL_Rect = .{ .x = @intFromFloat(x0), .y = @intFromFloat(y0), .w = @intFromFloat(x1 - x0), .h = @intFromFloat(y1 - y0) };
        _ = c.SDL_SetRenderClipRect(renderer, &scaled);
    }
    _ = c.SDL_RenderDebugText(renderer, x / s, y / s, &buf);
    _ = c.SDL_SetRenderScale(renderer, sx, sy);
    if (clipped and s != 1) _ = c.SDL_SetRenderClipRect(renderer, &clip);
}

/// What `drawText` gives `bytes` at `scale`: its width and the height of
/// its line, in canvas units (`Host.textSize`).
pub fn textSize(renderer: *c.SDL_Renderer, scale: f32, bytes: []const u8, face: abi.Face) [2]f32 {
    var size: [2]f32 = .{ 0, 0 };
    if (@import("builtin").os.tag == .linux and c.sk_text_measure_face(renderer, @intFromEnum(face), scale, bytes.ptr, bytes.len, &size[0], &size[1])) return size;
    // The debug font's 8 px cells.
    const s = @max(scale, 1);
    return .{ @as(f32, @floatFromInt(bytes.len)) * 8 * s, 8 * s };
}

fn premultiply(color: abi.Color) abi.Color {
    const a: u32 = color.a;
    return .{ .r = @intCast((color.r * a + 127) / 255), .g = @intCast((color.g * a + 127) / 255), .b = @intCast((color.b * a + 127) / 255), .a = color.a };
}

fn missing(renderer: *c.SDL_Renderer, dst: abi.Rect) void {
    _ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_BLEND);
    setColor(renderer, .{ .r = 110, .g = 30, .b = 70 });
    _ = c.SDL_RenderFillRect(renderer, &frect(dst));
    drawText(renderer, dst.x + 4, dst.y + 4, 1, "missing image", .{ .r = 255, .g = 210, .b = 240 }, .mono, 1);
}

fn setColor(renderer: *c.SDL_Renderer, color: abi.Color) void {
    _ = c.SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a);
}

fn frect(r: abi.Rect) c.SDL_FRect {
    return .{ .x = r.x, .y = r.y, .w = r.w, .h = r.h };
}