// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Draws a frame's shapes and hands it to a `Target` to put on screen. //! //! Every shape is one instance of one pipeline, whose vertex shader makes a //! quad around the shape and whose fragment shader covers it by its signed //! distance (see `shaders/shapes.zig`): a frame is one draw call. It is //! drawn straight into the target's own image when the target has one that //! can be drawn into, and otherwise into an image of the renderer's own, //! which the target copies out. //! //! The way frames reach a target, and the `Target` interface itself, follow //! harrier's `src/renderer/vulkan/Renderer.zig`. One frame is in flight at //! a time: a frame is drawn only when something moved, and paced by the //! compositor. const std = @import("std"); const vk = @import("vk"); const shaders = @import("shaders"); const view = @import("view"); const Device = @import("Device.zig"); const Renderer = @This(); /// What Wayland's buffers are, and the snapshot's. pub const default_format: vk.Format = .b8g8r8a8_unorm; device: *Device, format: vk.Format, render_pass: vk.RenderPass, /// The same, for drawing straight into a target's own image: left in /// GENERAL, for a consumer outside this device. render_pass_direct: vk.RenderPass, /// The same, for drawing into a swapchain's image: left ready to present. /// Only where the device has swapchains. render_pass_present: vk.RenderPass, pipeline_layout: vk.PipelineLayout, pipeline: vk.Pipeline, command_pool: vk.CommandPool, command_buffer: vk.CommandBuffer, fence: vk.Fence, target: Device.Image = .{}, framebuffer: vk.Framebuffer = .null_handle, instances: Device.Buffer = .{}, /// The frame's instances, built from its draw list. scratch: std.ArrayList(Instance) = .empty, /// One shape. Matches the vertex inputs of `shaders/shapes.zig`. pub const Instance = extern struct { a: [2]f32, b: [2]f32 = .{ 0, 0 }, c: [2]f32 = .{ 0, 0 }, radius: f32 = 0, kind: Kind, /// Straight RGBA. color: [4]u8, pub const Kind = enum(u32) { circle = 0, segment = 1, triangle = 2 }; pub fn of(item: view.draw.Item) Instance { return switch (item.shape) { .circle => |c| .{ .a = c.center, .radius = c.radius, .kind = .circle, .color = item.color }, .segment => |s| .{ .a = s.a, .b = s.b, .radius = s.radius, .kind = .segment, .color = item.color }, .triangle => |t| .{ .a = t.a, .b = t.b, .c = t.c, .kind = .triangle, .color = item.color }, }; } }; comptime { std.debug.assert(@sizeOf(Instance) == 36); } /// Puts a finished frame somewhere. /// /// `acquire` comes first, and says where the frame goes: straight into the /// target's own image, through a framebuffer it makes with the render pass /// it is given; or, when it returns none, into the renderer's offscreen /// image, which `record` then copies out. `finish` follows the submit. pub const Target = struct { context: *anyopaque, acquire: *const fn (context: *anyopaque, width: u32, height: u32, render_pass: vk.RenderPass) anyerror!Acquired, /// Called only when there was no framebuffer: with the render pass /// ended and the offscreen image in TRANSFER_SRC_OPTIMAL. record: *const fn (context: *anyopaque, cmd: vk.CommandBuffer, image: vk.Image, width: u32, height: u32) anyerror!void, /// Called after the submit, with the fence that signals its end. finish: *const fn (context: *anyopaque, fence: vk.Fence) anyerror!void, }; pub const Acquired = struct { direct: ?Direct = null, sync: Sync = .{}, }; /// A target's own image, to draw into, through a framebuffer made with the /// render pass `acquire` was given or any compatible with it. pub const Direct = struct { image: vk.Image, framebuffer: vk.Framebuffer, owner: Owner = .foreign, pub const Owner = enum { /// A consumer outside this device — a compositor — between frames, /// so the renderer takes the image from the foreign queue family /// before drawing and gives it back after. foreign, /// A swapchain of this device's, so the image is left ready to /// present, and the target presents it. swapchain, }; }; /// What a frame's submit waits for before it writes the target, and /// signals when it is done, for a target whose consumer is outside this /// device. pub const Sync = struct { /// A binary semaphore to wait on before writing the target. wait: ?vk.Semaphore = null, /// A semaphore to signal, and for a timeline the value to signal it to. signal: ?vk.Semaphore = null, signal_value: ?u64 = null, }; /// The dependencies every render pass has. Identical in each, because /// pipelines are compatible only with render passes whose dependencies /// match, and one pipeline draws in all of them. /// /// The first holds the clear, and the layout transition before it, until /// the stage the submit waits on its semaphore at: a swapchain image may /// still be being read for the frame before when it is acquired. const before_drawing: vk.SubpassDependency = .{ .src_subpass = vk.SUBPASS_EXTERNAL, .dst_subpass = 0, .src_stage_mask = .{ .color_attachment_output = true }, .dst_stage_mask = .{ .color_attachment_output = true }, .src_access_mask = .{}, .dst_access_mask = .{ .color_attachment_write = true }, }; const after_drawing: vk.SubpassDependency = .{ .src_subpass = 0, .dst_subpass = vk.SUBPASS_EXTERNAL, .src_stage_mask = .{ .color_attachment_output = true }, .dst_stage_mask = .{ .transfer = true, .bottom_of_pipe = true }, .src_access_mask = .{ .color_attachment_write = true }, .dst_access_mask = .{ .transfer_read = true }, }; fn createRenderPass(d: vk.DeviceProxy, format: vk.Format, final_layout: vk.ImageLayout) !vk.RenderPass { return d.createRenderPass(&.{ .attachment_count = 1, .p_attachments = &.{.{ .format = format, .samples = .{ .@"1" = true }, .load_op = .clear, .store_op = .store, .stencil_load_op = .dont_care, .stencil_store_op = .dont_care, .initial_layout = .undefined, .final_layout = final_layout, }}, .subpass_count = 1, .p_subpasses = &.{.{ .pipeline_bind_point = .graphics, .color_attachment_count = 1, .p_color_attachments = &.{.{ .attachment = 0, .layout = .color_attachment_optimal }}, }}, .dependency_count = 2, .p_dependencies = &.{ before_drawing, after_drawing }, }, null); } /// A renderer drawing in `format`, which is what its targets' images /// must be. pub fn init(device: *Device, format: vk.Format) !Renderer { const d = device.device; const render_pass = try createRenderPass(d, format, .transfer_src_optimal); errdefer d.destroyRenderPass(render_pass, null); const render_pass_direct = try createRenderPass(d, format, .general); errdefer d.destroyRenderPass(render_pass_direct, null); const render_pass_present: vk.RenderPass = if (Device.has_swapchain) try createRenderPass(d, format, .present_src_khr) else .null_handle; errdefer if (render_pass_present != .null_handle) d.destroyRenderPass(render_pass_present, null); const pipeline_layout = try d.createPipelineLayout(&.{ .push_constant_range_count = 1, .p_push_constant_ranges = &.{.{ .stage_flags = .{ .vertex = true }, .offset = 0, .size = 8 }}, }, null); errdefer d.destroyPipelineLayout(pipeline_layout, null); const pipeline = try createPipeline(d, render_pass, pipeline_layout); errdefer d.destroyPipeline(pipeline, null); const command_pool = try d.createCommandPool(&.{ .flags = .{ .reset_command_buffer = true }, .queue_family_index = device.queue_family, }, null); errdefer d.destroyCommandPool(command_pool, null); var command_buffer: vk.CommandBuffer = undefined; try d.allocateCommandBuffers(&.{ .command_pool = command_pool, .level = .primary, .command_buffer_count = 1, }, @ptrCast(&command_buffer)); const fence = try d.createFence(&.{ .flags = .{ .signaled = true } }, null); return .{ .device = device, .format = format, .render_pass = render_pass, .render_pass_direct = render_pass_direct, .render_pass_present = render_pass_present, .pipeline_layout = pipeline_layout, .pipeline = pipeline, .command_pool = command_pool, .command_buffer = command_buffer, .fence = fence, }; } pub fn deinit(r: *Renderer) void { const dev = r.device; const d = dev.device; _ = d.waitForFences(&.{r.fence}, .true, std.math.maxInt(u64)) catch {}; r.scratch.deinit(dev.gpa); r.instances.destroy(dev); if (r.framebuffer != .null_handle) d.destroyFramebuffer(r.framebuffer, null); r.target.destroy(dev); d.destroyFence(r.fence, null); d.destroyCommandPool(r.command_pool, null); d.destroyPipeline(r.pipeline, null); d.destroyPipelineLayout(r.pipeline_layout, null); d.destroyRenderPass(r.render_pass, null); d.destroyRenderPass(r.render_pass_direct, null); if (r.render_pass_present != .null_handle) d.destroyRenderPass(r.render_pass_present, null); r.* = undefined; } fn createPipeline(d: vk.DeviceProxy, render_pass: vk.RenderPass, layout: vk.PipelineLayout) !vk.Pipeline { const module = try d.createShaderModule(&.{ .code_size = shaders.shapes.len, .p_code = @ptrCast(&shaders.shapes), }, null); defer d.destroyShaderModule(module, null); const stages = [_]vk.PipelineShaderStageCreateInfo{ .{ .stage = .{ .vertex = true }, .module = module, .p_name = "vertex" }, .{ .stage = .{ .fragment = true }, .module = module, .p_name = "fragment" }, }; const attributes = [_]vk.VertexInputAttributeDescription{ .{ .location = 0, .binding = 0, .format = .r32g32_sfloat, .offset = @offsetOf(Instance, "a") }, .{ .location = 1, .binding = 0, .format = .r32g32_sfloat, .offset = @offsetOf(Instance, "b") }, .{ .location = 2, .binding = 0, .format = .r32g32_sfloat, .offset = @offsetOf(Instance, "c") }, .{ .location = 3, .binding = 0, .format = .r32_sfloat, .offset = @offsetOf(Instance, "radius") }, .{ .location = 4, .binding = 0, .format = .r32_uint, .offset = @offsetOf(Instance, "kind") }, .{ .location = 5, .binding = 0, .format = .r8g8b8a8_unorm, .offset = @offsetOf(Instance, "color") }, }; const dynamic = [_]vk.DynamicState{ .viewport, .scissor }; var pipeline: vk.Pipeline = undefined; _ = try d.createGraphicsPipelines(.null_handle, &.{.{ .stage_count = stages.len, .p_stages = &stages, .p_vertex_input_state = &.{ .vertex_binding_description_count = 1, .p_vertex_binding_descriptions = &.{.{ .binding = 0, .stride = @sizeOf(Instance), .input_rate = .instance }}, .vertex_attribute_description_count = attributes.len, .p_vertex_attribute_descriptions = &attributes, }, .p_input_assembly_state = &.{ .topology = .triangle_list, .primitive_restart_enable = .false }, .p_viewport_state = &.{ .viewport_count = 1, .scissor_count = 1 }, .p_rasterization_state = &.{ .depth_clamp_enable = .false, .rasterizer_discard_enable = .false, .polygon_mode = .fill, .cull_mode = .{}, .front_face = .clockwise, .depth_bias_enable = .false, .depth_bias_constant_factor = 0, .depth_bias_clamp = 0, .depth_bias_slope_factor = 0, .line_width = 1, }, .p_multisample_state = &.{ .rasterization_samples = .{ .@"1" = true }, .sample_shading_enable = .false, .min_sample_shading = 1, .alpha_to_coverage_enable = .false, .alpha_to_one_enable = .false, }, .p_color_blend_state = &.{ .logic_op_enable = .false, .logic_op = .copy, .attachment_count = 1, .p_attachments = &.{.{ .blend_enable = .true, .src_color_blend_factor = .one, .dst_color_blend_factor = .one_minus_src_alpha, .color_blend_op = .add, .src_alpha_blend_factor = .one, .dst_alpha_blend_factor = .one_minus_src_alpha, .alpha_blend_op = .add, .color_write_mask = .{ .r = true, .g = true, .b = true, .a = true }, }}, .blend_constants = .{ 0, 0, 0, 0 }, }, .p_dynamic_state = &.{ .dynamic_state_count = dynamic.len, .p_dynamic_states = &dynamic }, .layout = layout, .render_pass = render_pass, .subpass = 0, .base_pipeline_index = -1, }}, null, @ptrCast(&pipeline)); return pipeline; } /// Makes the offscreen image `width` by `height`, if it is not already. fn ensureTarget(r: *Renderer, width: u32, height: u32) !void { if (r.target.image != .null_handle and r.target.width == width and r.target.height == height) return; const dev = r.device; if (r.framebuffer != .null_handle) dev.device.destroyFramebuffer(r.framebuffer, null); r.framebuffer = .null_handle; r.target.destroy(dev); r.target = try dev.image(width, height, r.format, .{ .color_attachment = true, .transfer_src = true }); r.framebuffer = try dev.device.createFramebuffer(&.{ .render_pass = r.render_pass, .attachment_count = 1, .p_attachments = &.{r.target.view}, .width = width, .height = height, .layers = 1, }, null); } /// Draws `items` over `background` into a `width` by `height` image and /// hands it to `target`. pub fn draw( r: *Renderer, width: u32, height: u32, background: view.draw.Color, items: []const view.draw.Item, target: Target, ) !void { const dev = r.device; const d = dev.device; _ = try d.waitForFences(&.{r.fence}, .true, std.math.maxInt(u64)); r.scratch.clearRetainingCapacity(); try r.scratch.ensureTotalCapacity(dev.gpa, items.len); for (items) |item| r.scratch.appendAssumeCapacity(.of(item)); const bytes = std.mem.sliceAsBytes(r.scratch.items); if (r.instances.size < @max(bytes.len, 1)) { r.instances.destroy(dev); r.instances = try dev.hostBuffer(@max(bytes.len * 2, 64 * 1024), .{ .vertex_buffer = true }); } @memcpy(r.instances.mapped.?[0..bytes.len], bytes); const acquired = try target.acquire(target.context, width, height, r.render_pass_direct); if (acquired.direct == null) try r.ensureTarget(width, height); try d.resetFences(&.{r.fence}); const cmd = r.command_buffer; try d.resetCommandBuffer(cmd, .{}); try d.beginCommandBuffer(cmd, &.{ .flags = .{ .one_time_submit = true } }); const ours = dev.queue_family; if (acquired.direct) |direct| if (direct.owner == .foreign) { // Taken from the compositor; its old contents are not wanted. const take = vk.ImageMemoryBarrier{ .src_access_mask = .{}, .dst_access_mask = .{ .color_attachment_write = true }, .old_layout = .undefined, .new_layout = .color_attachment_optimal, .src_queue_family_index = vk.QUEUE_FAMILY_FOREIGN_EXT, .dst_queue_family_index = ours, .image = direct.image, .subresource_range = Device.color_range, }; d.cmdPipelineBarrier(cmd, .{ .top_of_pipe = true }, .{ .color_attachment_output = true }, .{}, null, null, &.{take}); }; const bg = [4]f32{ @as(f32, @floatFromInt(background[0])) / 255, @as(f32, @floatFromInt(background[1])) / 255, @as(f32, @floatFromInt(background[2])) / 255, @as(f32, @floatFromInt(background[3])) / 255, }; d.cmdBeginRenderPass(cmd, &.{ .render_pass = if (acquired.direct) |direct| switch (direct.owner) { .foreign => r.render_pass_direct, .swapchain => r.render_pass_present, } else r.render_pass, .framebuffer = if (acquired.direct) |direct| direct.framebuffer else r.framebuffer, .render_area = .{ .offset = .{ .x = 0, .y = 0 }, .extent = .{ .width = width, .height = height } }, .clear_value_count = 1, .p_clear_values = &.{.{ .color = .{ .float_32 = bg } }}, }, .@"inline"); d.cmdBindPipeline(cmd, .graphics, r.pipeline); d.cmdSetViewport(cmd, 0, &.{.{ .x = 0, .y = 0, .width = @floatFromInt(width), .height = @floatFromInt(height), .min_depth = 0, .max_depth = 1 }}); d.cmdSetScissor(cmd, 0, &.{.{ .offset = .{ .x = 0, .y = 0 }, .extent = .{ .width = width, .height = height } }}); const viewport = [2]f32{ @floatFromInt(width), @floatFromInt(height) }; d.cmdPushConstants(cmd, r.pipeline_layout, .{ .vertex = true }, 0, @sizeOf(@TypeOf(viewport)), &viewport); d.cmdBindVertexBuffers(cmd, 0, &.{r.instances.buffer}, &.{0}); if (items.len > 0) d.cmdDraw(cmd, 6, @intCast(items.len), 0, 0); d.cmdEndRenderPass(cmd); if (acquired.direct) |direct| { // Given back, unless it is ours to present. if (direct.owner == .foreign) { const give = vk.ImageMemoryBarrier{ .src_access_mask = .{ .color_attachment_write = true }, .dst_access_mask = .{}, .old_layout = .general, .new_layout = .general, .src_queue_family_index = ours, .dst_queue_family_index = vk.QUEUE_FAMILY_FOREIGN_EXT, .image = direct.image, .subresource_range = Device.color_range, }; d.cmdPipelineBarrier(cmd, .{ .color_attachment_output = true }, .{ .bottom_of_pipe = true }, .{}, null, null, &.{give}); } } else try target.record(target.context, cmd, r.target.image, width, height); try d.endCommandBuffer(cmd); const sync = acquired.sync; const wait_stage: vk.PipelineStageFlags = .{ .transfer = true, .color_attachment_output = true }; const signal_values = [1]u64{sync.signal_value orelse 0}; const timeline: vk.TimelineSemaphoreSubmitInfo = .{ .signal_semaphore_value_count = 1, .p_signal_semaphore_values = &signal_values, }; try d.queueSubmit(dev.queue, &.{.{ .p_next = if (sync.signal_value != null) &timeline else null, .wait_semaphore_count = @intFromBool(sync.wait != null), .p_wait_semaphores = if (sync.wait) |*w| @ptrCast(w) else null, .p_wait_dst_stage_mask = @ptrCast(&wait_stage), .command_buffer_count = 1, .p_command_buffers = &.{cmd}, .signal_semaphore_count = @intFromBool(sync.signal != null), .p_signal_semaphores = if (sync.signal) |*sg| @ptrCast(sg) else null, }}, r.fence); try target.finish(target.context, r.fence); }