// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT // From harrier's src/renderer/vulkan/Device.zig, without Windows. //! The Vulkan instance and device the game draws with. //! //! On Linux the loader is opened at run time rather than linked, so that a //! machine without Vulkan gets a message rather than a binary that will not //! start, and no surface extensions are asked for, since there is no surface //! to make (see `wayland/Shm.zig` and `wayland/Dmabuf.zig`). Every Android //! device has the loader, so there it is linked, and frames go to a //! swapchain on the window's surface (see `Swapchain.zig`). const std = @import("std"); const builtin = @import("builtin"); const Allocator = std.mem.Allocator; const vk = @import("vk"); const dmabuf = @import("../wayland/dmabuf.zig"); const Device = @This(); const log = std.log.scoped(.vulkan); pub const api_version = vk.API_VERSION_1_2; const android = builtin.abi.isAndroid(); /// Whether frames are presented through a swapchain, which only Android's /// device has the extension for. pub const has_swapchain = android; const loader_name = "libvulkan.so.1"; /// What the instance needs: on Linux nothing, since there is no surface. const instance_extensions: []const [*:0]const u8 = if (android) &.{ vk.extensions.khr_surface.name, vk.extensions.khr_android_surface.name, } else &.{}; /// What a device needs, whatever else it can do. const device_extensions: []const [*:0]const u8 = if (android) &.{ vk.extensions.khr_swapchain.name, } else &.{}; gpa: Allocator, /// The loader, where it is opened rather than linked. lib: if (android) void else std.DynLib, base: vk.BaseWrapper, instance_wrapper: *vk.InstanceWrapper, instance: vk.InstanceProxy, physical: vk.PhysicalDevice, properties: vk.PhysicalDeviceProperties, memory_properties: vk.PhysicalDeviceMemoryProperties, device_wrapper: *vk.DeviceWrapper, device: vk.DeviceProxy, queue: vk.Queue, queue_family: u32, /// What the device can do with dma-bufs, when it can share them at all. dmabuf_support: ?dmabuf.Support, var get_instance_proc_addr: vk.PfnGetInstanceProcAddr = undefined; extern "vulkan" fn vkGetInstanceProcAddr(instance: vk.Instance, name: [*:0]const u8) callconv(vk.vulkan_call_conv) vk.PfnVoidFunction; fn getInstanceProcAddr(instance: vk.Instance, name: [*:0]const u8) callconv(vk.vulkan_call_conv) vk.PfnVoidFunction { return get_instance_proc_addr(instance, name); } pub const Options = struct { /// The `dev_t` of the device the compositor composites with, which is /// the one whose memory it can read without a copy. main_device: ?u64 = null, /// Turn on the validation layer, where it is installed. validation: bool = false, /// Use the device whose name contains this, rather than choosing. name: ?[]const u8 = null, }; pub fn init(gpa: Allocator, options: Options) !*Device { const d = try gpa.create(Device); errdefer gpa.destroy(d); var lib = if (android) {} else std.DynLib.open(loader_name) catch |err| { log.err("no Vulkan loader ({s}): {t}", .{ loader_name, err }); return error.NoVulkan; }; errdefer if (!android) lib.close(); get_instance_proc_addr = if (android) &vkGetInstanceProcAddr else lib.lookup(vk.PfnGetInstanceProcAddr, "vkGetInstanceProcAddr") orelse return error.NoVulkan; const base = vk.BaseWrapper.load(getInstanceProcAddr); var layers_buf: [1][*:0]const u8 = undefined; var layers: []const [*:0]const u8 = &.{}; if (options.validation) { const available = try base.enumerateInstanceLayerPropertiesAlloc(gpa); defer gpa.free(available); for (available) |l| if (std.mem.eql(u8, std.mem.sliceTo(&l.layer_name, 0), "VK_LAYER_KHRONOS_validation")) { layers_buf[0] = "VK_LAYER_KHRONOS_validation"; layers = &layers_buf; }; if (layers.len == 0) log.warn("validation asked for, but VK_LAYER_KHRONOS_validation is not installed", .{}); } const instance_handle = try base.createInstance(&.{ .p_application_info = &.{ .p_application_name = "pfeilstorch", .application_version = 0, .p_engine_name = "pfeilstorch", .engine_version = 0, .api_version = api_version.toU32(), }, .enabled_layer_count = @intCast(layers.len), .pp_enabled_layer_names = layers.ptr, .enabled_extension_count = @intCast(instance_extensions.len), .pp_enabled_extension_names = instance_extensions.ptr, }, null); const instance_wrapper = try gpa.create(vk.InstanceWrapper); errdefer gpa.destroy(instance_wrapper); instance_wrapper.* = .load(instance_handle, getInstanceProcAddr); const instance = vk.InstanceProxy.init(instance_handle, instance_wrapper); errdefer instance.destroyInstance(null); const chosen = try choose(gpa, instance, options.main_device, options.name); log.info("drawing with {s}{s}", .{ std.mem.sliceTo(&chosen.properties.device_name, 0), if (chosen.support != null) ", sharing dma-bufs" else "", }); var ext_buf: [dmabuf.max_extensions + device_extensions.len][*:0]const u8 = undefined; @memcpy(ext_buf[0..device_extensions.len], device_extensions); const n_dmabuf = if (chosen.support) |s| s.extensions(ext_buf[device_extensions.len..][0..dmabuf.max_extensions]).len else 0; const extensions = ext_buf[0 .. device_extensions.len + n_dmabuf]; var timeline_features: vk.PhysicalDeviceTimelineSemaphoreFeatures = .{ .timeline_semaphore = .true }; const want_timelines = chosen.support != null and chosen.support.?.timelines; const priority: [1]f32 = .{1}; const device_handle = try instance.createDevice(chosen.physical, &.{ .p_next = if (want_timelines) &timeline_features else null, .queue_create_info_count = 1, .p_queue_create_infos = &.{.{ .queue_family_index = chosen.queue_family, .queue_count = 1, .p_queue_priorities = &priority, }}, .enabled_extension_count = @intCast(extensions.len), .pp_enabled_extension_names = extensions.ptr, }, null); const device_wrapper = try gpa.create(vk.DeviceWrapper); errdefer gpa.destroy(device_wrapper); device_wrapper.* = .load(device_handle, instance_wrapper.dispatch.vkGetDeviceProcAddr.?); const device = vk.DeviceProxy.init(device_handle, device_wrapper); d.* = .{ .gpa = gpa, .lib = lib, .base = base, .instance_wrapper = instance_wrapper, .instance = instance, .physical = chosen.physical, .properties = chosen.properties, .memory_properties = instance.getPhysicalDeviceMemoryProperties(chosen.physical), .device_wrapper = device_wrapper, .device = device, .queue = device.getDeviceQueue(chosen.queue_family, 0), .queue_family = chosen.queue_family, .dmabuf_support = chosen.support, }; return d; } pub fn deinit(d: *Device) void { d.device.deviceWaitIdle() catch {}; d.device.destroyDevice(null); d.instance.destroyInstance(null); d.gpa.destroy(d.device_wrapper); d.gpa.destroy(d.instance_wrapper); if (!android) d.lib.close(); d.gpa.destroy(d); } const Chosen = struct { physical: vk.PhysicalDevice, properties: vk.PhysicalDeviceProperties, queue_family: u32, support: ?dmabuf.Support, }; /// The compositor's own device if it named one we can draw with; otherwise /// a discrete GPU before an integrated one before anything else. fn choose(gpa: Allocator, instance: vk.InstanceProxy, main_device: ?u64, name: ?[]const u8) !Chosen { const devices = try instance.enumeratePhysicalDevicesAlloc(gpa); defer gpa.free(devices); var best: ?Chosen = null; var best_score: i32 = -1; for (devices) |pd| { const props = instance.getPhysicalDeviceProperties(pd); if (props.api_version < api_version.toU32()) continue; const family = graphicsFamily(gpa, instance, pd) orelse continue; const extensions = try instance.enumerateDeviceExtensionPropertiesAlloc(pd, null, gpa); defer gpa.free(extensions); if (!hasAll(extensions, device_extensions)) continue; const support = if (android) null else dmabuf.probe(instance, pd, extensions); var score: i32 = switch (props.device_type) { .discrete_gpu => 30, .integrated_gpu => 20, .virtual_gpu => 10, else => 0, }; if (support != null) score += 5; if (main_device) |dev| if (support) |s| if (s.isDevice(dev)) { score += 100; }; if (name) |want| { if (std.ascii.findIgnoreCase(std.mem.sliceTo(&props.device_name, 0), want) != null) score += 1000 else continue; } if (score > best_score) { best_score = score; best = .{ .physical = pd, .properties = props, .queue_family = family, .support = support }; } } if (best == null) if (name) |want| log.err("no Vulkan device's name contains \"{s}\"", .{want}); return best orelse error.NoUsableDevice; } /// A queue family that draws. fn graphicsFamily(gpa: Allocator, instance: vk.InstanceProxy, pd: vk.PhysicalDevice) ?u32 { const families = instance.getPhysicalDeviceQueueFamilyPropertiesAlloc(pd, gpa) catch return null; defer gpa.free(families); for (families, 0..) |f, i| { if (!f.queue_flags.graphics) continue; return @intCast(i); } return null; } fn hasAll(available: []const vk.ExtensionProperties, wanted: []const [*:0]const u8) bool { for (wanted) |w| { const name = std.mem.span(w); for (available) |a| { if (std.mem.eql(u8, std.mem.sliceTo(&a.extension_name, 0), name)) break; } else return false; } return true; } /// A memory type among `type_bits` with all of `required`. pub fn memoryType(d: *const Device, type_bits: u32, required: vk.MemoryPropertyFlags) ?u32 { const props = d.memory_properties; for (props.memory_types[0..props.memory_type_count], 0..) |t, i| { if (type_bits & (@as(u32, 1) << @intCast(i)) != 0 and t.property_flags.contains(required)) return @intCast(i); } return null; } /// A buffer with its own memory. pub const Buffer = struct { buffer: vk.Buffer = .null_handle, memory: vk.DeviceMemory = .null_handle, size: vk.DeviceSize = 0, /// Mapped for the buffer's life, when it is host-visible. mapped: ?[*]u8 = null, pub fn destroy(b: *Buffer, d: *const Device) void { if (b.mapped != null) d.device.unmapMemory(b.memory); if (b.buffer != .null_handle) d.device.destroyBuffer(b.buffer, null); if (b.memory != .null_handle) d.device.freeMemory(b.memory, null); b.* = .{}; } }; /// A host-visible, coherent buffer, mapped. pub fn hostBuffer(d: *const Device, size: vk.DeviceSize, usage: vk.BufferUsageFlags) !Buffer { const buffer = try d.device.createBuffer(&.{ .size = size, .usage = usage, .sharing_mode = .exclusive }, null); errdefer d.device.destroyBuffer(buffer, null); const req = d.device.getBufferMemoryRequirements(buffer); const mt = d.memoryType(req.memory_type_bits, .{ .host_visible = true, .host_coherent = true }) orelse return error.NoHostMemory; const memory = try d.device.allocateMemory(&.{ .allocation_size = req.size, .memory_type_index = mt }, null); errdefer d.device.freeMemory(memory, null); try d.device.bindBufferMemory(buffer, memory, 0); const mapped = try d.device.mapMemory(memory, 0, vk.WHOLE_SIZE, .{}); return .{ .buffer = buffer, .memory = memory, .size = size, .mapped = @ptrCast(mapped.?) }; } /// An image in device memory. pub const Image = struct { image: vk.Image = .null_handle, memory: vk.DeviceMemory = .null_handle, view: vk.ImageView = .null_handle, width: u32 = 0, height: u32 = 0, pub fn destroy(i: *Image, d: *const Device) void { if (i.view != .null_handle) d.device.destroyImageView(i.view, null); if (i.image != .null_handle) d.device.destroyImage(i.image, null); if (i.memory != .null_handle) d.device.freeMemory(i.memory, null); i.* = .{}; } }; pub fn image(d: *const Device, width: u32, height: u32, format: vk.Format, usage: vk.ImageUsageFlags) !Image { const img = try d.device.createImage(&.{ .image_type = .@"2d", .format = format, .extent = .{ .width = width, .height = height, .depth = 1 }, .mip_levels = 1, .array_layers = 1, .samples = .{ .@"1" = true }, .tiling = .optimal, .usage = usage, .sharing_mode = .exclusive, .initial_layout = .undefined, }, null); errdefer d.device.destroyImage(img, null); const req = d.device.getImageMemoryRequirements(img); const mt = d.memoryType(req.memory_type_bits, .{ .device_local = true }) orelse d.memoryType(req.memory_type_bits, .{}) orelse return error.NoDeviceMemory; const memory = try d.device.allocateMemory(&.{ .allocation_size = req.size, .memory_type_index = mt }, null); errdefer d.device.freeMemory(memory, null); try d.device.bindImageMemory(img, memory, 0); const view = try d.device.createImageView(&.{ .image = img, .view_type = .@"2d", .format = format, .components = .{ .r = .identity, .g = .identity, .b = .identity, .a = .identity }, .subresource_range = color_range, }, null); return .{ .image = img, .memory = memory, .view = view, .width = width, .height = height }; } pub const color_range: vk.ImageSubresourceRange = .{ .aspect_mask = .{ .color = true }, .base_mip_level = 0, .level_count = 1, .base_array_layer = 0, .layer_count = 1, };