Something went wrong. Try again.
A puzzle game of bent arrows sent off a board of dots, written in Zig.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Frames presented through a swapchain on a surface, where the platform//! has one to give: Android's window.//!//! The renderer draws straight into the swapchain's images. One frame is in//! flight at a time — `Renderer.draw` waits for the last frame's fence//! before it acquires — so one semaphore is enough for acquiring, while//! each image has its own to present with, since an image may still be//! waiting to be shown when the next frame's submit is made.//!//! The swapchain keeps the identity transform even when the display is//! rotated, and lets the compositor turn the frame: Android then reports//! every present as suboptimal, which is taken as nothing worth acting on.
const std = @import("std");const vk = @import("vk");
const Device = @import("Device.zig");const Renderer = @import("Renderer.zig");
const Swapchain = @This();
const log = std.log.scoped(.swapchain);
device: *Device,surface: vk.SurfaceKHR,format: vk.Format,handle: vk.SwapchainKHR = .null_handle,extent: vk.Extent2D = .{ .width = 0, .height = 0 },images: []Image = &.{},/// The render pass the framebuffers were made with.render_pass: vk.RenderPass = .null_handle,acquired_semaphore: vk.Semaphore,/// The image the frame being drawn is going into.current: u32 = 0,/// Made again before the next frame: the surface changed under it.stale: bool = false,
const Image = struct { image: vk.Image, view: vk.ImageView, framebuffer: vk.Framebuffer = .null_handle, /// Signaled when the frame drawn into this image is done, for the /// present to wait on. drawn: vk.Semaphore,};
/// A swapchain on `surface`, which it takes and will destroy, presenting/// images of `format`. Nothing is made until the first frame says how big/// it is.pub fn init(device: *Device, surface: vk.SurfaceKHR, format: vk.Format) !Swapchain { errdefer device.instance.destroySurfaceKHR(surface, null); const formats = try device.instance.getPhysicalDeviceSurfaceFormatsAllocKHR(device.physical, surface, device.gpa); defer device.gpa.free(formats); for (formats) |f| { if (f.format == format) break; } else { log.err("the surface cannot show {t}", .{format}); return error.UnsupportedFormat; } if (try device.instance.getPhysicalDeviceSurfaceSupportKHR(device.physical, device.queue_family, surface) != .true) return error.CannotPresent; return .{ .device = device, .surface = surface, .format = format, .acquired_semaphore = try device.device.createSemaphore(&.{}, null), };}
pub fn deinit(s: *Swapchain) void { const d = s.device.device; d.deviceWaitIdle() catch {}; s.destroyImages(); if (s.handle != .null_handle) d.destroySwapchainKHR(s.handle, null); d.destroySemaphore(s.acquired_semaphore, null); s.device.instance.destroySurfaceKHR(s.surface, null); s.* = undefined;}
fn destroyImages(s: *Swapchain) void { const d = s.device.device; for (s.images) |img| { if (img.framebuffer != .null_handle) d.destroyFramebuffer(img.framebuffer, null); d.destroyImageView(img.view, null); d.destroySemaphore(img.drawn, null); } s.device.gpa.free(s.images); s.images = &.{};}
/// Makes the swapchain `width` by `height`, replacing the one there was.fn create(s: *Swapchain, width: u32, height: u32) !void { const dev = s.device; const d = dev.device; const caps = try dev.instance.getPhysicalDeviceSurfaceCapabilitiesKHR(dev.physical, s.surface); const extent: vk.Extent2D = .{ .width = std.math.clamp(width, caps.min_image_extent.width, caps.max_image_extent.width), .height = std.math.clamp(height, caps.min_image_extent.height, caps.max_image_extent.height), }; var count = @max(caps.min_image_count + 1, 2); if (caps.max_image_count > 0) count = @min(count, caps.max_image_count); const alpha: vk.CompositeAlphaFlagsKHR = for ([_]vk.CompositeAlphaFlagsKHR{ .{ .opaque_khr = true }, .{ .inherit_khr = true }, .{ .pre_multiplied_khr = true }, .{ .post_multiplied_khr = true }, }) |a| { if (caps.supported_composite_alpha.contains(a)) break a; } else return error.NoCompositeAlpha;
try d.deviceWaitIdle(); const old = s.handle; s.handle = try d.createSwapchainKHR(&.{ .surface = s.surface, .min_image_count = count, .image_format = s.format, .image_color_space = .srgb_nonlinear_khr, .image_extent = extent, .image_array_layers = 1, .image_usage = .{ .color_attachment = true }, .image_sharing_mode = .exclusive, .pre_transform = .{ .identity_khr = true }, .composite_alpha = alpha, // Always there, and paced by the display, which is all a game // drawing only when something moves wants. .present_mode = .fifo_khr, .clipped = .true, .old_swapchain = old, }, null); s.destroyImages(); if (old != .null_handle) d.destroySwapchainKHR(old, null); s.extent = extent; s.stale = false;
const handles = try d.getSwapchainImagesAllocKHR(s.handle, dev.gpa); defer dev.gpa.free(handles); const images = try dev.gpa.alloc(Image, handles.len); var made: usize = 0; errdefer { for (images[0..made]) |img| { d.destroyImageView(img.view, null); d.destroySemaphore(img.drawn, null); } dev.gpa.free(images); } for (handles, images) |h, *img| { const view = try d.createImageView(&.{ .image = h, .view_type = .@"2d", .format = s.format, .components = .{ .r = .identity, .g = .identity, .b = .identity, .a = .identity }, .subresource_range = Device.color_range, }, null); errdefer d.destroyImageView(view, null); img.* = .{ .image = h, .view = view, .drawn = try d.createSemaphore(&.{}, null) }; made += 1; } s.images = images; s.render_pass = .null_handle; log.info("{d} images of {d}x{d}", .{ images.len, extent.width, extent.height });}
pub fn target(s: *Swapchain) Renderer.Target { return .{ .context = s, .acquire = acquire, .record = record, .finish = finish };}
fn acquire(context: *anyopaque, width: u32, height: u32, render_pass: vk.RenderPass) anyerror!Renderer.Acquired { const s: *Swapchain = @ptrCast(@alignCast(context)); const d = s.device.device; if (s.handle == .null_handle or s.stale or s.extent.width != width or s.extent.height != height) try s.create(width, height);
const index = for (0..2) |_| { const result = d.acquireNextImageKHR(s.handle, std.math.maxInt(u64), s.acquired_semaphore, .null_handle) catch |err| switch (err) { error.OutOfDateKHR => { try s.create(width, height); continue; }, else => return err, }; break result.image_index; } else return error.OutOfDateKHR; s.current = index;
const img = &s.images[index]; if (s.render_pass != render_pass) { for (s.images) |*i| if (i.framebuffer != .null_handle) { d.destroyFramebuffer(i.framebuffer, null); i.framebuffer = .null_handle; }; s.render_pass = render_pass; } if (img.framebuffer == .null_handle) img.framebuffer = try d.createFramebuffer(&.{ .render_pass = render_pass, .attachment_count = 1, .p_attachments = &.{img.view}, .width = s.extent.width, .height = s.extent.height, .layers = 1, }, null); return .{ .direct = .{ .image = img.image, .framebuffer = img.framebuffer, .owner = .swapchain }, .sync = .{ .wait = s.acquired_semaphore, .signal = img.drawn }, };}
fn record(_: *anyopaque, _: vk.CommandBuffer, _: vk.Image, _: u32, _: u32) anyerror!void { // Every frame is drawn straight into a swapchain image. unreachable;}
fn finish(context: *anyopaque, _: vk.Fence) anyerror!void { const s: *Swapchain = @ptrCast(@alignCast(context)); const result = s.device.device.queuePresentKHR(s.device.queue, &.{ .wait_semaphore_count = 1, .p_wait_semaphores = &.{s.images[s.current].drawn}, .swapchain_count = 1, .p_swapchains = &.{s.handle}, .p_image_indices = &.{s.current}, }) catch |err| switch (err) { error.OutOfDateKHR => { s.stale = true; return; }, else => return err, }; _ = result;}
/// The surface has changed size or otherwise gone stale: the next frame/// makes the swapchain again.pub fn invalidate(s: *Swapchain) void { s.stale = true;}