summaryrefslogtreecommitdiff
path: root/src/gpu
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-17 04:36:56 -0300
committerGabriel Schneider <[email protected]>2026-11-17 12:15:01 -0300
commitada7e4137d66aa7c7c463bb8521c0db4e7fac18a (patch)
tree8ac9367dbb1a0a6c97c88f0acbfb938702aa46f7 /src/gpu
parentdf1d47d4fddd4165bdf511f4056d8075562a663e (diff)
downloadsketchbook-ada7e4137d66aa7c7c463bb8521c0db4e7fac18a.tar.gz
sketchbook-ada7e4137d66aa7c7c463bb8521c0db4e7fac18a.zip
Add pardes's cell resources, pictures, overlay and atlas upload
Moved from pardes's src/gui/gui.zig (step S4a of moving its renderer here): Cells is now a struct over the embedder's device and swapchain format holding the four pipelines (and the addon one, made on first use), the glyph atlas's texture, nearest sampler and upload buffer, the pictures' linear sampler, the cells', pictures' and overlay's buffers, and the pictures' textures by key. init and deinit make and release them; image uploads a picture's RGBA, or only its dirty rows into the texture of the picture it replaces; mapImages, uploadImages and drawImages carry the frame's picture instances and draws, an ImageDraw's texture either one of Cells' own or the caller's, borrowed (an addon's premultiplied output); uploadAtlas sends the Atlas's dirty rows; uploadOverlay, pushLayerOpacity and drawOverlay the overlay's triangles. The SPIR-V is the embedder's `<name>.spv` imports; Cells.zig imports the Atlas as `font_atlas`.
Diffstat (limited to 'src/gpu')
-rw-r--r--src/gpu/Cells.zig343
1 files changed, 338 insertions, 5 deletions
diff --git a/src/gpu/Cells.zig b/src/gpu/Cells.zig
index 78d7f22..5055d31 100644
--- a/src/gpu/Cells.zig
+++ b/src/gpu/Cells.zig
@@ -1,10 +1,343 @@
-//! pardes's cell renderer on SDL_GPU, part 1: the shaders' instance ABI
-//! (src/gpu/shaders/*.glsl), the pipelines over it and the resource helpers,
-//! moved from pardes's gui.zig as they were. `c` is the embedder's own SDL
-//! translation (pardes's: SDL3 and font.h), so the embedder's SDL is the one
-//! linked.
+//! pardes's cell renderer on SDL_GPU: the shaders' instance ABI
+//! (src/gpu/shaders/*.glsl), the pipelines over it, the glyph atlas's
+//! texture and its upload, the pictures' textures and their draws, the
+//! overlay's triangles, and the resource helpers, moved from pardes's
+//! gui.zig as they were. `c` is the embedder's own SDL translation (pardes's:
+//! SDL3 and font.h), so the embedder's SDL is the one linked; the SPIR-V is
+//! the build's (`<name>.spv` imports, from src/gpu/shaders/).
const std = @import("std");
const c = @import("c");
+const Atlas = @import("font_atlas");
+
+const Cells = @This();
+
+/// The embedder's device (Present's), which everything here is made on.
+device: *c.SDL_GPUDevice,
+/// What every pipeline draws into: the swapchain's format.
+format: c.SDL_GPUTextureFormat,
+pipeline: *c.SDL_GPUGraphicsPipeline,
+decor_pipeline: *c.SDL_GPUGraphicsPipeline,
+overlay_pipeline: *c.SDL_GPUGraphicsPipeline,
+image_pipeline: *c.SDL_GPUGraphicsPipeline,
+/// Premultiplied pictures' (an addon's), made on first use
+/// (makeAddonPipeline).
+addon_pipeline: ?*c.SDL_GPUGraphicsPipeline = null,
+atlas_tex: *c.SDL_GPUTexture,
+atlas_sampler: *c.SDL_GPUSampler,
+linear_sampler: *c.SDL_GPUSampler,
+atlas_xfer: *c.SDL_GPUTransferBuffer,
+vbuf: ?*c.SDL_GPUBuffer = null,
+vxfer: ?*c.SDL_GPUTransferBuffer = null,
+vbuf_cells: u32 = 0,
+overlay_vbuf: *c.SDL_GPUBuffer,
+overlay_vxfer: *c.SDL_GPUTransferBuffer,
+image_vbuf: ?*c.SDL_GPUBuffer = null,
+image_vxfer: ?*c.SDL_GPUTransferBuffer = null,
+image_capacity: u32 = 0,
+/// The textures of the pictures shown, by key (image).
+native_images: std.AutoHashMapUnmanaged(u64, *c.SDL_GPUTexture) = .empty,
+/// The frame's pictures, instance by instance (mapImages, drawImages).
+images: std.ArrayListUnmanaged(ImageDraw) = .empty,
+
+const vert_spv = @embedFile("ui.vert.spv");
+const frag_spv = @embedFile("ui.frag.spv");
+const decor_frag_spv = @embedFile("decor.frag.spv");
+const overlay_vert_spv = @embedFile("overlay.vert.spv");
+const overlay_frag_spv = @embedFile("overlay.frag.spv");
+const image_vert_spv = @embedFile("image.vert.spv");
+const image_frag_spv = @embedFile("image.frag.spv");
+
+/// The atlas's texture, sampler and upload buffer, the pictures' sampler,
+/// the four pipelines drawing into `swapchain_format`, and the overlay's
+/// buffers, `max_overlay_vertices` long, made on `device`.
+pub fn init(device: *c.SDL_GPUDevice, swapchain_format: c.SDL_GPUTextureFormat, max_overlay_vertices: usize) !Cells {
+ const atlas_tex = texture2d(device, c.SDL_GPU_TEXTUREFORMAT_R8_UNORM, c.SDL_GPU_TEXTUREUSAGE_SAMPLER, Atlas.atlas_w, Atlas.atlas_h) orelse return error.GpuCreate;
+
+ var samp_info = std.mem.zeroes(c.SDL_GPUSamplerCreateInfo);
+ samp_info.min_filter = c.SDL_GPU_FILTER_NEAREST;
+ samp_info.mag_filter = c.SDL_GPU_FILTER_NEAREST;
+ samp_info.mipmap_mode = c.SDL_GPU_FILTER_NEAREST;
+ samp_info.address_mode_u = c.SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
+ samp_info.address_mode_v = c.SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
+ samp_info.address_mode_w = c.SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
+ const atlas_sampler = c.SDL_CreateGPUSampler(device, &samp_info) orelse return error.GpuCreate;
+ samp_info.min_filter = c.SDL_GPU_FILTER_LINEAR;
+ samp_info.mag_filter = c.SDL_GPU_FILTER_LINEAR;
+ samp_info.mipmap_mode = c.SDL_GPU_FILTER_LINEAR;
+ const linear_sampler = c.SDL_CreateGPUSampler(device, &samp_info) orelse return error.GpuCreate;
+
+ var ax_info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = Atlas.atlas_w * Atlas.atlas_h, .props = 0 };
+ const atlas_xfer = c.SDL_CreateGPUTransferBuffer(device, &ax_info) orelse return error.GpuCreate;
+
+ const pipeline = try makePipeline(device, swapchain_format, vert_spv, frag_spv, 1, 1, cell_input, std.mem.zeroes(c.SDL_GPUColorTargetBlendState));
+ const decor_pipeline = try makePipeline(device, swapchain_format, vert_spv, decor_frag_spv, 0, 1, cell_input, backgroundLayerBlend());
+ const overlay_pipeline = try makePipeline(device, swapchain_format, overlay_vert_spv, overlay_frag_spv, 0, 1, overlay_input, backgroundLayerBlend());
+ const image_pipeline = try makePipeline(device, swapchain_format, image_vert_spv, image_frag_spv, 1, 1, image_input, backgroundLayerBlend());
+
+ const overlay_buffer_size: u32 = @intCast(max_overlay_vertices * @sizeOf(OverlayVertex));
+ var ovb_info = c.SDL_GPUBufferCreateInfo{ .usage = c.SDL_GPU_BUFFERUSAGE_VERTEX, .size = overlay_buffer_size, .props = 0 };
+ const overlay_vbuf = c.SDL_CreateGPUBuffer(device, &ovb_info) orelse return error.GpuCreate;
+ var ovx_info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = overlay_buffer_size, .props = 0 };
+ const overlay_vxfer = c.SDL_CreateGPUTransferBuffer(device, &ovx_info) orelse return error.GpuCreate;
+
+ return .{
+ .device = device,
+ .format = swapchain_format,
+ .pipeline = pipeline,
+ .decor_pipeline = decor_pipeline,
+ .overlay_pipeline = overlay_pipeline,
+ .image_pipeline = image_pipeline,
+ .atlas_tex = atlas_tex,
+ .atlas_sampler = atlas_sampler,
+ .linear_sampler = linear_sampler,
+ .atlas_xfer = atlas_xfer,
+ .overlay_vbuf = overlay_vbuf,
+ .overlay_vxfer = overlay_vxfer,
+ };
+}
+
+/// The pipelines, textures and buffers, whatever they were regrown to, and
+/// the pictures' textures let go (the device stays: Present's).
+pub fn deinit(cells: *Cells, gpa: std.mem.Allocator) void {
+ const device = cells.device;
+ c.SDL_ReleaseGPUGraphicsPipeline(device, cells.image_pipeline);
+ if (cells.addon_pipeline) |pipeline_| c.SDL_ReleaseGPUGraphicsPipeline(device, pipeline_);
+ cells.clearImages();
+ cells.native_images.deinit(gpa);
+ cells.images.deinit(gpa);
+ c.SDL_ReleaseGPUGraphicsPipeline(device, cells.pipeline);
+ c.SDL_ReleaseGPUGraphicsPipeline(device, cells.decor_pipeline);
+ c.SDL_ReleaseGPUGraphicsPipeline(device, cells.overlay_pipeline);
+ c.SDL_ReleaseGPUTexture(device, cells.atlas_tex);
+ c.SDL_ReleaseGPUSampler(device, cells.atlas_sampler);
+ c.SDL_ReleaseGPUSampler(device, cells.linear_sampler);
+ c.SDL_ReleaseGPUTransferBuffer(device, cells.atlas_xfer);
+ c.SDL_ReleaseGPUBuffer(device, cells.overlay_vbuf);
+ c.SDL_ReleaseGPUTransferBuffer(device, cells.overlay_vxfer);
+ if (cells.vbuf) |buffer| c.SDL_ReleaseGPUBuffer(device, buffer);
+ if (cells.vxfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(device, transfer);
+ if (cells.image_vbuf) |buffer| c.SDL_ReleaseGPUBuffer(device, buffer);
+ if (cells.image_vxfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(device, transfer);
+}
+
+/// The pipeline of premultiplied pictures (an addon's GPU scene), made the
+/// first time one is drawn.
+pub fn makeAddonPipeline(cells: *Cells) !void {
+ if (cells.addon_pipeline != null) return;
+ var blend = backgroundLayerBlend();
+ blend.src_color_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE;
+ cells.addon_pipeline = try makePipeline(cells.device, cells.format, image_vert_spv, image_frag_spv, 1, 1, image_input, blend);
+}
+
+/// Uploads only the atlas rows drawn into since the last upload. Glyphs fill
+/// the atlas pen-style, a band of rows at a time, so new glyphs are a band a
+/// cell or two tall, not the whole 4 MB texture. The band sits at the same
+/// offset in the transfer buffer as in the stage, and the texture keeps the
+/// rows outside it.
+pub fn uploadAtlas(cells: *Cells, cmd: *c.SDL_GPUCommandBuffer, atlas: *Atlas) void {
+ const atlas_w = Atlas.atlas_w;
+ const top = atlas.atlas_dirty_top;
+ const rows = atlas.atlas_dirty_bottom - top;
+ const ptr = c.SDL_MapGPUTransferBuffer(cells.device, cells.atlas_xfer, false) orelse return;
+ const dst: [*]u8 = @ptrCast(ptr);
+ @memcpy(dst[top * atlas_w ..][0 .. rows * atlas_w], atlas.atlas_stage[top * atlas_w ..][0 .. rows * atlas_w]);
+ c.SDL_UnmapGPUTransferBuffer(cells.device, cells.atlas_xfer);
+
+ const copy = c.SDL_BeginGPUCopyPass(cmd);
+ const src = c.SDL_GPUTextureTransferInfo{ .transfer_buffer = cells.atlas_xfer, .offset = top * atlas_w, .pixels_per_row = atlas_w, .rows_per_layer = rows };
+ const dstregion = c.SDL_GPUTextureRegion{ .texture = cells.atlas_tex, .mip_level = 0, .layer = 0, .x = 0, .y = top, .z = 0, .w = atlas_w, .h = rows, .d = 1 };
+ c.SDL_UploadToGPUTexture(copy, &src, &dstregion, false);
+ c.SDL_EndGPUCopyPass(copy);
+ atlas.atlas_dirty_top = Atlas.atlas_h;
+ atlas.atlas_dirty_bottom = 0;
+}
+
+/// A picture of the frame: its texture (one of `native_images`, or the
+/// caller's, borrowed: an addon's, premultiplied) and the target rectangle
+/// it is clipped to.
+pub const ImageDraw = struct {
+ premultiplied: bool = false,
+ texture: *c.SDL_GPUTexture,
+ clip: c.SDL_Rect,
+};
+
+/// Rows of a picture that alone differ from the picture under the key
+/// `from` (image).
+pub const Dirty = struct { from: u64, y: u32, h: u32 };
+
+pub fn releaseImage(cells: *Cells, key: u64) void {
+ if (cells.native_images.fetchRemove(key)) |removed|
+ c.SDL_ReleaseGPUTexture(cells.device, removed.value);
+}
+
+pub fn clearImages(cells: *Cells) void {
+ var iterator = cells.native_images.valueIterator();
+ while (iterator.next()) |texture| c.SDL_ReleaseGPUTexture(cells.device, texture.*);
+ cells.native_images.clearRetainingCapacity();
+}
+
+/// The texture of the picture `key`, `w` by `h` RGBA pixels in `rgba`, a
+/// row `stride` bytes: uploaded unless it is held already, or, where
+/// `dirty_rows` names a picture held, only those rows written into that
+/// picture's texture, which takes the new key.
+pub fn image(
+ cells: *Cells,
+ gpa: std.mem.Allocator,
+ cmd: *c.SDL_GPUCommandBuffer,
+ key: u64,
+ rgba: []const u8,
+ w: u32,
+ h: u32,
+ stride: u32,
+ dirty_rows: ?Dirty,
+) !void {
+ if (cells.native_images.contains(key)) return;
+ const row = stride;
+ if (dirty_rows) |dirty| dirty: {
+ // The core changed only these rows since a picture we still hold:
+ // write them into that texture rather than sending the whole page.
+ if (dirty.y + dirty.h > h) break :dirty;
+ const texture = cells.native_images.get(dirty.from) orelse break :dirty;
+ try uploadTextureRows(cells, cmd, texture, rgba[dirty.y * row ..][0 .. dirty.h * row], w, dirty.y, dirty.h);
+ try cells.native_images.put(gpa, key, texture);
+ _ = cells.native_images.remove(dirty.from);
+ return;
+ }
+
+ const texture = texture2d(cells.device, c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, c.SDL_GPU_TEXTUREUSAGE_SAMPLER, w, h) orelse return error.GpuCreate;
+ errdefer c.SDL_ReleaseGPUTexture(cells.device, texture);
+ try uploadTextureRows(cells, cmd, texture, rgba, w, 0, h);
+ try cells.native_images.put(gpa, key, texture);
+}
+
+/// Copy `rows` rows of RGBA, `width` pixels each, into `texture` at row `y`.
+fn uploadTextureRows(
+ cells: *Cells,
+ cmd: *c.SDL_GPUCommandBuffer,
+ texture: *c.SDL_GPUTexture,
+ rgba: []const u8,
+ width: usize,
+ y: usize,
+ rows: usize,
+) !void {
+ var xf_info = c.SDL_GPUTransferBufferCreateInfo{
+ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD,
+ .size = @intCast(rgba.len),
+ .props = 0,
+ };
+ const transfer = c.SDL_CreateGPUTransferBuffer(cells.device, &xf_info) orelse return error.GpuCreate;
+ defer c.SDL_ReleaseGPUTransferBuffer(cells.device, transfer);
+ const mapped: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(cells.device, transfer, false) orelse return error.GpuMap);
+ @memcpy(mapped[0..rgba.len], rgba);
+ c.SDL_UnmapGPUTransferBuffer(cells.device, transfer);
+
+ const copy = c.SDL_BeginGPUCopyPass(cmd);
+ const src = c.SDL_GPUTextureTransferInfo{
+ .transfer_buffer = transfer,
+ .offset = 0,
+ .pixels_per_row = @intCast(width),
+ .rows_per_layer = @intCast(rows),
+ };
+ const dst = c.SDL_GPUTextureRegion{
+ .texture = texture,
+ .mip_level = 0,
+ .layer = 0,
+ .x = 0,
+ .y = @intCast(y),
+ .z = 0,
+ .w = @intCast(width),
+ .h = @intCast(rows),
+ .d = 1,
+ };
+ c.SDL_UploadToGPUTexture(copy, &src, &dst, false);
+ c.SDL_EndGPUCopyPass(copy);
+}
+
+/// The frame's `n` picture instances, mapped for the caller to write, and
+/// `images` emptied with room for as many draws; uploadImages sends them.
+/// Null when the buffers will not grow or map.
+pub fn mapImages(cells: *Cells, gpa: std.mem.Allocator, n: u32) ?[*]ImageInstance {
+ growInstances(cells.device, &cells.image_vbuf, &cells.image_vxfer, &cells.image_capacity, n, @sizeOf(ImageInstance)) catch return null;
+ cells.images.clearRetainingCapacity();
+ cells.images.ensureTotalCapacity(gpa, n) catch return null;
+ const ptr: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(cells.device, cells.image_vxfer.?, false) orelse return null);
+ return @ptrCast(@alignCast(ptr));
+}
+
+/// The first `n` instances mapImages gave, sent.
+pub fn uploadImages(cells: *Cells, cmd: *c.SDL_GPUCommandBuffer, n: u32) void {
+ c.SDL_UnmapGPUTransferBuffer(cells.device, cells.image_vxfer.?);
+
+ const copy = c.SDL_BeginGPUCopyPass(cmd);
+ const src = c.SDL_GPUTransferBufferLocation{ .transfer_buffer = cells.image_vxfer.?, .offset = 0 };
+ const dst = c.SDL_GPUBufferRegion{ .buffer = cells.image_vbuf.?, .offset = 0, .size = n * @sizeOf(ImageInstance) };
+ c.SDL_UploadToGPUBuffer(copy, &src, &dst, false);
+ c.SDL_EndGPUCopyPass(copy);
+}
+
+/// Draws `count` of the frame's pictures from `start`, each clipped to its
+/// rectangle; the scissor is the whole target, `whole`, after.
+pub fn drawImages(cells: *Cells, rp: ?*c.SDL_GPURenderPass, start: u32, count: u32, whole: c.SDL_Rect) void {
+ const pass = rp orelse return;
+ c.SDL_BindGPUGraphicsPipeline(pass, cells.image_pipeline);
+ var idx = start;
+ const end = start + count;
+ for (cells.images.items[start..end]) |prepared| {
+ c.SDL_BindGPUGraphicsPipeline(pass, if (prepared.premultiplied) cells.addon_pipeline.? else cells.image_pipeline);
+ const clip = prepared.clip;
+ if (clip.w > 0 and clip.h > 0) {
+ c.SDL_SetGPUScissor(pass, &clip);
+ const sampler = c.SDL_GPUTextureSamplerBinding{ .texture = prepared.texture, .sampler = cells.linear_sampler };
+ c.SDL_BindGPUFragmentSamplers(pass, 0, &sampler, 1);
+ const binding = c.SDL_GPUBufferBinding{ .buffer = cells.image_vbuf.?, .offset = idx * @sizeOf(ImageInstance) };
+ c.SDL_BindGPUVertexBuffers(pass, 0, &binding, 1);
+ c.SDL_DrawGPUPrimitives(pass, 6, 1, 0, 0);
+ }
+ idx += 1;
+ }
+ std.debug.assert(idx == start + count);
+ // Back to the whole target: what draws after a picture may run on past
+ // the grid, as a rule and a band do.
+ c.SDL_SetGPUScissor(pass, &whole);
+}
+
+/// The overlay's triangles, `vertices`, sent.
+pub fn uploadOverlay(cells: *Cells, cmd: *c.SDL_GPUCommandBuffer, vertices: []const OverlayVertex) bool {
+ const vertex_count: u32 = @intCast(vertices.len);
+ const byte_len: u32 = vertex_count * @sizeOf(OverlayVertex);
+ const ptr = c.SDL_MapGPUTransferBuffer(cells.device, cells.overlay_vxfer, false) orelse return false;
+ const dst: [*]u8 = @ptrCast(ptr);
+ const src: [*]const u8 = @ptrCast(vertices.ptr);
+ @memcpy(dst[0..byte_len], src[0..byte_len]);
+ c.SDL_UnmapGPUTransferBuffer(cells.device, cells.overlay_vxfer);
+ const copy = c.SDL_BeginGPUCopyPass(cmd);
+ const src_loc = c.SDL_GPUTransferBufferLocation{ .transfer_buffer = cells.overlay_vxfer, .offset = 0 };
+ const dst_region = c.SDL_GPUBufferRegion{ .buffer = cells.overlay_vbuf, .offset = 0, .size = byte_len };
+ c.SDL_UploadToGPUBuffer(copy, &src_loc, &dst_region, false);
+ c.SDL_EndGPUCopyPass(copy);
+ return true;
+}
+
+pub fn pushLayerOpacity(cmd: *c.SDL_GPUCommandBuffer, pass: ?*c.SDL_GPURenderPass, opacity: f32) void {
+ const uniforms = [4]f32{ opacity, 0, 0, 0 };
+ c.SDL_PushGPUFragmentUniformData(cmd, 0, &uniforms, @sizeOf(@TypeOf(uniforms)));
+ // The source alpha is geometric/image coverage, not window opacity. Its
+ // alpha contribution is multiplied by this constant separately, so a
+ // rail repainted over a gutter still has alpha p, not p + p*(1-p).
+ c.SDL_SetGPUBlendConstants(pass, .{ .r = opacity, .g = opacity, .b = opacity, .a = opacity });
+}
+
+/// The overlay's first `vertex_count` vertices (uploadOverlay), drawn at
+/// the layer opacity `opacity`.
+pub fn drawOverlay(cells: *Cells, cmd: *c.SDL_GPUCommandBuffer, rp: ?*c.SDL_GPURenderPass, vertex_count: u32, opacity: f32) void {
+ if (vertex_count == 0) return;
+ const pass = rp orelse return;
+ c.SDL_BindGPUGraphicsPipeline(pass, cells.overlay_pipeline);
+ const binding = c.SDL_GPUBufferBinding{ .buffer = cells.overlay_vbuf, .offset = 0 };
+ c.SDL_BindGPUVertexBuffers(pass, 0, &binding, 1);
+ pushLayerOpacity(cmd, pass, opacity);
+ c.SDL_DrawGPUPrimitives(pass, vertex_count, 1, 0, 0);
+}
pub const CellInstance = extern struct {
x0: f32,