summaryrefslogtreecommitdiff
path: root/src/host/gfx.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/host/gfx.zig')
-rw-r--r--src/host/gfx.zig475
1 files changed, 429 insertions, 46 deletions
diff --git a/src/host/gfx.zig b/src/host/gfx.zig
index 16148a6..20b4dcc 100644
--- a/src/host/gfx.zig
+++ b/src/host/gfx.zig
@@ -14,10 +14,29 @@ pub const Images = 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| if (entry.texture) |t| c.SDL_DestroyTexture(t);
+ 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.*);
@@ -41,10 +60,20 @@ pub const Images = struct {
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_STREAMING, @intCast(w), @intCast(h));
- if (texture) |t| setup(t);
- return self.append(.{ .texture = texture, .w = w, .h = h });
+ 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).
@@ -59,9 +88,8 @@ pub const Images = struct {
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);
- _ = c.SDL_SetTextureBlendMode(texture, c.SDL_BLENDMODE_BLEND_PREMULTIPLIED);
- if (entry.texture) |old| c.SDL_DestroyTexture(old);
- entry.* = .{ .texture = texture, .w = w, .h = h };
+ entry.release();
+ entry.* = .{ .texture = texture, .w = w, .h = h, .premultiplied = true, .smooth = true };
}
/// Stops showing a wrapped render target, before the target goes away.
@@ -73,8 +101,7 @@ pub const Images = struct {
pub fn free(self: *Images, image: abi.Image) void {
const entry = self.get(image) orelse return;
- if (entry.texture) |t| c.SDL_DestroyTexture(t);
- entry.* = .{};
+ entry.release();
}
pub fn size(self: *Images, image: abi.Image) [2]u32 {
@@ -104,47 +131,397 @@ pub const Images = struct {
fn setup(texture: *c.SDL_Texture) void {
_ = c.SDL_SetTextureScaleMode(texture, c.SDL_SCALEMODE_NEAREST);
- _ = c.SDL_SetTextureBlendMode(texture, c.SDL_BLENDMODE_BLEND);
}
};
-/// Draws one graphics command. Other commands are not graphics: ignored.
-pub fn draw(renderer: *c.SDL_Renderer, images: *Images, command: abi.Command) void {
- switch (command) {
- .clear => |color| {
- if (@import("builtin").os.tag == .linux) c.sk_text_begin_frame(renderer);
- setColor(renderer, color);
- _ = c.SDL_RenderClear(renderer);
- },
- .rect => |r| {
- setColor(renderer, r.color);
- _ = c.SDL_RenderFillRect(renderer, &frect(r.dst));
- },
- .image => |img| {
- const entry = images.get(img.image);
- const texture = if (entry) |e| e.texture else null;
- const t = texture orelse return missing(renderer, img.dst);
- _ = c.SDL_SetTextureColorMod(t, img.tint.r, img.tint.g, img.tint.b);
- _ = c.SDL_SetTextureAlphaMod(t, img.tint.a);
- const src = frect(img.src);
- _ = c.SDL_RenderTexture(renderer, t, if (img.src.w > 0) &src else null, &frect(img.dst));
- },
- .text => |text| drawText(renderer, text.x, text.y, text.scale, text.bytes, text.color),
- .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 => |p| {
- const entry = images.get(p.image) orelse return;
- const texture = entry.texture orelse return;
- if (p.w != entry.w or p.h != entry.h or p.rgba.len < @as(usize, p.w) * p.h * 4) return;
- _ = c.SDL_SetTextureBlendMode(texture, if (p.premultiplied) c.SDL_BLENDMODE_BLEND_PREMULTIPLIED else c.SDL_BLENDMODE_BLEND);
- _ = c.SDL_UpdateTexture(texture, null, p.rgba.ptr, @intCast(p.w * 4));
- },
- else => {},
+/// 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 16 Mi of them; 4,
+ /// then; else none.
+ const max_samples = 16 << 20;
+
+ 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);
+ },
+ .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.
@@ -178,7 +555,13 @@ pub fn drawText(renderer: *c.SDL_Renderer, x: f32, y: f32, scale: f32, bytes: []
if (clipped and s != 1) _ = c.SDL_SetRenderClipRect(renderer, &clip);
}
+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 });