//! 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, gpu_texture: ?*anyopaque = 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; if (entry.gpu_texture == gpu_texture) return; 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, .gpu_texture = gpu_texture }; } /// 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; entry.gpu_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 }, backdrop_texture: ?*c.SDL_Texture = null, backdrop_size: [2]u32 = .{ 0, 0 }, backdrop_state: ?*c.SDL_GPURenderState = null, backdrop_shader: ?*c.SDL_GPUShader = null, backdrop_hash: u64 = 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.backdrop_texture) |t| c.SDL_DestroyTexture(t); if (p.backdrop_state) |state| c.SDL_DestroyGPURenderState(state); if (p.backdrop_shader) |shader| if (c.SDL_GetGPURendererDevice(p.renderer)) |device| c.SDL_ReleaseGPUShader(device, shader); 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), .backdrop => |b| p.backdrop(b.dst, b.fragment, b.uniforms), .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 backdrop(p: *Painter, dst: abi.Rect, fragment: []const u8, uniforms: []const u8) void { if (p.target != .none or p.canvas == null or dst.w <= 0 or dst.h <= 0) return; const device = c.SDL_GetGPURendererDevice(p.renderer) orelse return; const hash = std.hash.Wyhash.hash(0, fragment); if (p.backdrop_hash != hash) { if (p.backdrop_state) |state| c.SDL_DestroyGPURenderState(state); if (p.backdrop_shader) |shader| c.SDL_ReleaseGPUShader(device, shader); p.backdrop_state = null; p.backdrop_hash = hash; var info: c.SDL_GPUShaderCreateInfo = std.mem.zeroes(c.SDL_GPUShaderCreateInfo); info.code = fragment.ptr; info.code_size = fragment.len; info.entrypoint = "main"; info.format = c.SDL_GPU_SHADERFORMAT_SPIRV; info.stage = c.SDL_GPU_SHADERSTAGE_FRAGMENT; info.num_samplers = 1; info.num_uniform_buffers = 1; p.backdrop_shader = c.SDL_CreateGPUShader(device, &info); if (p.backdrop_shader) |shader| { var state_info: c.SDL_GPURenderStateCreateInfo = std.mem.zeroes(c.SDL_GPURenderStateCreateInfo); state_info.fragment_shader = shader; p.backdrop_state = c.SDL_CreateGPURenderState(p.renderer, &state_info); } if (p.backdrop_state == null) std.log.warn("backdrop shader: {s}", .{c.SDL_GetError()}); } const state = p.backdrop_state orelse return; // One snapshot, bounded by the canvas and reused by every backdrop. const size: [2]u32 = .{ @intFromFloat(@ceil(@min(dst.w, @as(f32, @floatFromInt(p.canvas_size[0]))))), @intFromFloat(@ceil(@min(dst.h, @as(f32, @floatFromInt(p.canvas_size[1]))))) }; if (size[0] == 0 or size[1] == 0) return; if (!std.meta.eql(size, p.backdrop_size)) { if (p.backdrop_texture) |t| c.SDL_DestroyTexture(t); p.backdrop_texture = c.SDL_CreateTexture(p.renderer, c.SDL_PIXELFORMAT_RGBA32, c.SDL_TEXTUREACCESS_TARGET, @intCast(size[0]), @intCast(size[1])); p.backdrop_size = size; } const snapshot = p.backdrop_texture orelse return; var clip: c.SDL_Rect = undefined; const clipped = c.SDL_RenderClipEnabled(p.renderer); _ = c.SDL_GetRenderClipRect(p.renderer, &clip); _ = c.SDL_SetRenderTarget(p.renderer, snapshot); _ = c.SDL_SetRenderClipRect(p.renderer, null); _ = c.SDL_SetRenderDrawColor(p.renderer, 0, 0, 0, 255); _ = c.SDL_RenderClear(p.renderer); _ = c.SDL_SetTextureBlendMode(p.canvas, c.SDL_BLENDMODE_NONE); _ = c.SDL_RenderTexture(p.renderer, p.canvas, &frect(dst), null); _ = c.SDL_SetRenderTarget(p.renderer, p.canvas); _ = c.SDL_SetRenderClipRect(p.renderer, if (clipped) &clip else null); _ = c.SDL_SetTextureScaleMode(snapshot, c.SDL_SCALEMODE_LINEAR); _ = c.SDL_SetTextureBlendMode(snapshot, c.SDL_BLENDMODE_BLEND); if (!c.SDL_SetGPURenderStateFragmentUniforms(state, 0, uniforms.ptr, @intCast(uniforms.len))) return; _ = c.SDL_SetGPURenderState(p.renderer, state); _ = c.SDL_RenderTexture(p.renderer, snapshot, null, &frect(dst)); _ = c.SDL_SetGPURenderState(p.renderer, null); } 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)); } /// One atlas batch; vertex colors are premultiplied when the image is. pub fn texturedTriangles(p: *Painter, image: abi.Image, vertices: []const c.SDL_Vertex, indices: []const u16) void { if (vertices.len == 0 or indices.len == 0 or vertices.len > std.math.maxInt(c_int) or indices.len > std.math.maxInt(c_int)) return; const entry = p.images.get(image) orelse return; const texture = entry.texture orelse return; if (image == p.target) return; p.flush(); if (entry.stale) p.resolve(entry); _ = c.SDL_SetTextureBlendMode(texture, textureBlend(p.blend, entry.premultiplied)); const stride = @sizeOf(c.SDL_Vertex); _ = c.SDL_RenderGeometryRaw(p.renderer, texture, @ptrCast(&vertices[0].position), stride, &vertices[0].color, stride, @ptrCast(&vertices[0].tex_coord), stride, @intCast(vertices.len), indices.ptr, @intCast(indices.len), @sizeOf(u16)); } /// `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, @backingInt(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, @backingInt(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 }; }