//! Surfaces and swapchains, done by the driver (Venus leaves a window //! system to the guest, as Mesa's driver does its own): a surface is a //! window of Pinnacle's display server, as winit's port hands it over (its //! [`Window`] behind the window handle); a swapchain's images are the host //! GPU's, and presenting one copies it into memory the host shares, then //! into the window's pixels, the display server told what changed. use crate::commands::*; use crate::{GENERATE_REPLY, call, driver, new_id, vkCreateBuffer, vkDestroyBuffer, vkGetBufferMemoryRequirements, zeroed}; use pinnacle_venus::encode::*; use pinnacle_venus::vk::*; use std::collections::HashMap; use std::ffi::c_void; use std::ptr::{null, null_mut}; use std::sync::Mutex; pub type VkSurfaceKHR = u64; pub type VkSwapchainKHR = u64; pub type VkPresentModeKHR = i32; pub type VkColorSpaceKHR = i32; pub type VkSurfaceTransformFlagsKHR = u32; pub type VkCompositeAlphaFlagsKHR = u32; const VK_PRESENT_MODE_FIFO_KHR: VkPresentModeKHR = 2; const VK_COLOR_SPACE_SRGB_NONLINEAR_KHR: VkColorSpaceKHR = 0; const VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR: u32 = 1; const VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR: u32 = 1; const VK_SUBOPTIMAL_KHR: VkResult = 1000001003; /// A winit window on Pinnacle, as its port lays it out (`Surface` in /// `ports/winit-*/src/platform_impl/pinnacle/window.rs`, by agreement). #[repr(C)] pub struct Window { pub context: *const c_void, pub size: unsafe extern "C" fn(*const c_void, *mut u32, *mut u32), pub present: unsafe extern "C" fn(*const c_void, *const u32, u32, u32), } #[repr(C)] #[derive(Clone, Copy)] pub struct VkSurfaceCapabilitiesKHR { pub minImageCount: u32, pub maxImageCount: u32, pub currentExtent: VkExtent2D, pub minImageExtent: VkExtent2D, pub maxImageExtent: VkExtent2D, pub maxImageArrayLayers: u32, pub supportedTransforms: VkSurfaceTransformFlagsKHR, pub currentTransform: u32, pub supportedCompositeAlpha: VkCompositeAlphaFlagsKHR, pub supportedUsageFlags: VkImageUsageFlags, } #[repr(C)] #[derive(Clone, Copy)] pub struct VkSurfaceFormatKHR { pub format: VkFormat, pub colorSpace: VkColorSpaceKHR, } #[repr(C)] pub struct VkSwapchainCreateInfoKHR { pub sType: VkStructureType, pub pNext: *const c_void, pub flags: u32, pub surface: VkSurfaceKHR, pub minImageCount: u32, pub imageFormat: VkFormat, pub imageColorSpace: VkColorSpaceKHR, pub imageExtent: VkExtent2D, pub imageArrayLayers: u32, pub imageUsage: VkImageUsageFlags, pub imageSharingMode: VkSharingMode, pub queueFamilyIndexCount: u32, pub pQueueFamilyIndices: *const u32, pub preTransform: u32, pub compositeAlpha: u32, pub presentMode: VkPresentModeKHR, pub clipped: VkBool32, pub oldSwapchain: VkSwapchainKHR, } #[repr(C)] pub struct VkPresentInfoKHR { pub sType: VkStructureType, pub pNext: *const c_void, pub waitSemaphoreCount: u32, pub pWaitSemaphores: *const VkSemaphore, pub swapchainCount: u32, pub pSwapchains: *const VkSwapchainKHR, pub pImageIndices: *const u32, pub pResults: *mut VkResult, } /// A swapchain: its images (the host's), what presenting copies them /// through, and the window they go to. struct Swapchain { device: VkDevice, window: usize, family: u32, extent: VkExtent2D, images: Vec<(VkImage, VkDeviceMemory)>, /// Memory the host shares, mapped: what an image is copied into. buffer: VkBuffer, buffer_memory: VkDeviceMemory, mapped: *const u32, pool: VkCommandPool, command_buffer: VkCommandBuffer, fence: VkFence, next: u32, } // SAFETY: the mapping is the driver's, used under SWAPCHAINS' lock. unsafe impl Send for Swapchain {} static SURFACES: Mutex> = Mutex::new(Vec::new()); static SWAPCHAINS: Mutex>> = Mutex::new(None); /// A surface on a winit window (`window`: its window handle, the address /// of its port's `Surface`). What wgpu-hal's port calls. pub fn create_surface(window: *const c_void) -> VkSurfaceKHR { let surface = new_id(); SURFACES.lock().unwrap().push((surface, window as usize)); surface } fn window_of(surface: VkSurfaceKHR) -> Option<&'static Window> { let surfaces = SURFACES.lock().unwrap(); let &(_, window) = surfaces.iter().find(|(s, _)| *s == surface)?; // SAFETY: winit's window, which outlives its surface (wgpu's rule). Some(unsafe { &*(window as *const Window) }) } fn window_size(window: &Window) -> VkExtent2D { let (mut width, mut height) = (0, 0); // SAFETY: the window's own function on its own context. unsafe { (window.size)(window.context, &mut width, &mut height) }; VkExtent2D { width, height } } pub unsafe extern "system" fn vkDestroySurfaceKHR( _instance: VkInstance, surface: VkSurfaceKHR, _pAllocator: *const VkAllocationCallbacks, ) { SURFACES.lock().unwrap().retain(|(s, _)| *s != surface); } pub unsafe extern "system" fn vkGetPhysicalDeviceSurfaceSupportKHR( _physicalDevice: VkPhysicalDevice, _queueFamilyIndex: u32, _surface: VkSurfaceKHR, pSupported: *mut VkBool32, ) -> VkResult { unsafe { *pSupported = 1 }; VK_SUCCESS } pub unsafe extern "system" fn vkGetPhysicalDeviceSurfaceCapabilitiesKHR( _physicalDevice: VkPhysicalDevice, surface: VkSurfaceKHR, pSurfaceCapabilities: *mut VkSurfaceCapabilitiesKHR, ) -> VkResult { let Some(window) = window_of(surface) else { return VK_ERROR_SURFACE_LOST_KHR; }; let extent = window_size(window); unsafe { *pSurfaceCapabilities = VkSurfaceCapabilitiesKHR { minImageCount: 2, maxImageCount: 3, currentExtent: extent, minImageExtent: VkExtent2D { width: 1, height: 1 }, maxImageExtent: extent, maxImageArrayLayers: 1, supportedTransforms: VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, currentTransform: VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, supportedCompositeAlpha: VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, supportedUsageFlags: (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT) as u32, } }; VK_SUCCESS } /// BGRA, as the window's pixels are (0xAARRGGBB in memory order). pub unsafe extern "system" fn vkGetPhysicalDeviceSurfaceFormatsKHR( _physicalDevice: VkPhysicalDevice, _surface: VkSurfaceKHR, pSurfaceFormatCount: *mut u32, pSurfaceFormats: *mut VkSurfaceFormatKHR, ) -> VkResult { let formats = [VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_B8G8R8A8_SRGB].map(|format| VkSurfaceFormatKHR { format, colorSpace: VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, }); // SAFETY: as the caller promised. unsafe { crate::enumerate(&formats, pSurfaceFormatCount, pSurfaceFormats) } } pub unsafe extern "system" fn vkGetPhysicalDeviceSurfacePresentModesKHR( _physicalDevice: VkPhysicalDevice, _surface: VkSurfaceKHR, pPresentModeCount: *mut u32, pPresentModes: *mut VkPresentModeKHR, ) -> VkResult { // SAFETY: as the caller promised. unsafe { crate::enumerate(&[VK_PRESENT_MODE_FIFO_KHR], pPresentModeCount, pPresentModes) } } /// The first memory type allowed by `bits` that has `flags`. fn memory_type(device: VkDevice, bits: u32, flags: u32) -> Option { let physical = driver().as_ref()?.physical.as_ref()?.first().copied()?; let _ = device; let mut properties: VkPhysicalDeviceMemoryProperties = zeroed(); // SAFETY: a live local. unsafe { vkGetPhysicalDeviceMemoryProperties(physical, &mut properties) }; (0..properties.memoryTypeCount.min(32)) .find(|&i| bits & 1 << i != 0 && properties.memoryTypes[i as usize].propertyFlags & flags == flags) } /// Memory for an object with these requirements, bound by `bind`. unsafe fn allocate( device: VkDevice, requirements: &VkMemoryRequirements, flags: u32, ) -> Option { let kind = memory_type(device, requirements.memoryTypeBits, flags)?; let mut info: VkMemoryAllocateInfo = zeroed(); info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; info.allocationSize = requirements.size; info.memoryTypeIndex = kind; let mut memory = 0; // SAFETY: live locals. (unsafe { crate::vkAllocateMemory(device, &info, null(), &mut memory) } == VK_SUCCESS).then_some(memory) } pub unsafe extern "system" fn vkCreateSwapchainKHR( device: VkDevice, pCreateInfo: *const VkSwapchainCreateInfoKHR, _pAllocator: *const VkAllocationCallbacks, pSwapchain: *mut VkSwapchainKHR, ) -> VkResult { // SAFETY: as the caller promised. let info = unsafe { &*pCreateInfo }; let Some(window) = SURFACES .lock() .unwrap() .iter() .find(|(s, _)| *s == info.surface) .map(|&(_, w)| w) else { return VK_ERROR_SURFACE_LOST_KHR; }; let family = driver() .as_ref() .and_then(|d| { d.devices .get(&device) .and_then(|f| f.first().map(|&(family, _)| family)) }) .unwrap_or(0); let extent = info.imageExtent; // SAFETY (below): every pointer a live local; the handles just made. unsafe { let mut images = Vec::new(); for _ in 0..info.minImageCount.clamp(2, 3) { let mut image_info: VkImageCreateInfo = zeroed(); image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; image_info.imageType = VK_IMAGE_TYPE_2D; image_info.format = info.imageFormat; image_info.extent = VkExtent3D { width: extent.width, height: extent.height, depth: 1, }; image_info.mipLevels = 1; image_info.arrayLayers = 1; image_info.samples = VK_SAMPLE_COUNT_1_BIT; image_info.tiling = VK_IMAGE_TILING_OPTIMAL; image_info.usage = info.imageUsage | VK_IMAGE_USAGE_TRANSFER_SRC_BIT as u32; image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; let mut image = 0; let result = vkCreateImage(device, &image_info, null(), &mut image); if result != VK_SUCCESS { return result; } let mut requirements: VkMemoryRequirements = zeroed(); vkGetImageMemoryRequirements(device, image, &mut requirements); let Some(memory) = allocate(device, &requirements, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT as u32) .or_else(|| allocate(device, &requirements, 0)) else { return VK_ERROR_OUT_OF_DEVICE_MEMORY; }; vkBindImageMemory(device, image, memory, 0); images.push((image, memory)); } // What an image is copied into: memory the host shares, mapped. let size = extent.width as u64 * extent.height as u64 * 4; let mut buffer_info: VkBufferCreateInfo = zeroed(); buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; buffer_info.size = size; buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT as u32; buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; let mut buffer = 0; let result = vkCreateBuffer(device, &buffer_info, null(), &mut buffer); if result != VK_SUCCESS { return result; } let mut requirements: VkMemoryRequirements = zeroed(); vkGetBufferMemoryRequirements(device, buffer, &mut requirements); let visible = (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) as u32; let Some(buffer_memory) = allocate(device, &requirements, visible) else { return VK_ERROR_OUT_OF_DEVICE_MEMORY; }; vkBindBufferMemory(device, buffer, buffer_memory, 0); let mut mapped = null_mut(); let result = crate::vkMapMemory(device, buffer_memory, 0, size, 0, &mut mapped); if result != VK_SUCCESS { return result; } // The command buffer that copies, and its fence. let mut pool_info: VkCommandPoolCreateInfo = zeroed(); pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT as u32; pool_info.queueFamilyIndex = family; let mut pool = 0; vkCreateCommandPool(device, &pool_info, null(), &mut pool); let mut allocate_info: VkCommandBufferAllocateInfo = zeroed(); allocate_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocate_info.commandPool = pool; allocate_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocate_info.commandBufferCount = 1; let mut command_buffer = 0; vkAllocateCommandBuffers(device, &allocate_info, &mut command_buffer); let mut fence_info: VkFenceCreateInfo = zeroed(); fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; let mut fence = 0; vkCreateFence(device, &fence_info, null(), &mut fence); let swapchain = new_id(); *pSwapchain = swapchain; let old = info.oldSwapchain; SWAPCHAINS .lock() .unwrap() .get_or_insert_with(HashMap::new) .insert( swapchain, Swapchain { device, window, family, extent, images, buffer, buffer_memory, mapped: mapped as *const u32, pool, command_buffer, fence, next: 0, }, ); let _ = old; } VK_SUCCESS } pub unsafe extern "system" fn vkDestroySwapchainKHR( device: VkDevice, swapchain: VkSwapchainKHR, _pAllocator: *const VkAllocationCallbacks, ) { let Some(chain) = SWAPCHAINS .lock() .unwrap() .as_mut() .and_then(|s| s.remove(&swapchain)) else { return; }; // SAFETY: the swapchain's own handles, done with (the caller's rule). unsafe { vkDestroyFence(device, chain.fence, null()); vkDestroyCommandPool(device, chain.pool, null()); vkDestroyBuffer(device, chain.buffer, null()); crate::vkFreeMemory(device, chain.buffer_memory, null()); for (image, memory) in chain.images { vkDestroyImage(device, image, null()); crate::vkFreeMemory(device, memory, null()); } } } pub unsafe extern "system" fn vkGetSwapchainImagesKHR( _device: VkDevice, swapchain: VkSwapchainKHR, pSwapchainImageCount: *mut u32, pSwapchainImages: *mut VkImage, ) -> VkResult { let images: Vec = match SWAPCHAINS .lock() .unwrap() .as_ref() .and_then(|s| s.get(&swapchain)) { Some(chain) => chain.images.iter().map(|&(image, _)| image).collect(), None => return VK_ERROR_SURFACE_LOST_KHR, }; // SAFETY: as the caller promised. unsafe { crate::enumerate(&images, pSwapchainImageCount, pSwapchainImages) } } /// The next image, in turn; the semaphore and fence signalled at once by an /// empty submit (the image is free: presenting waited for its copy). pub unsafe extern "system" fn vkAcquireNextImageKHR( device: VkDevice, swapchain: VkSwapchainKHR, _timeout: u64, semaphore: VkSemaphore, fence: VkFence, pImageIndex: *mut u32, ) -> VkResult { let (index, family, extent, window) = { let mut chains = SWAPCHAINS.lock().unwrap(); let Some(chain) = chains.as_mut().and_then(|s| s.get_mut(&swapchain)) else { return VK_ERROR_SURFACE_LOST_KHR; }; let index = chain.next; chain.next = (chain.next + 1) % chain.images.len() as u32; (index, chain.family, chain.extent, chain.window) }; unsafe { *pImageIndex = index }; if semaphore != 0 || fence != 0 { let queue = crate::queue(device, 0, family, 0); let mut submit: VkSubmitInfo = zeroed(); submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submit.signalSemaphoreCount = u32::from(semaphore != 0); submit.pSignalSemaphores = &semaphore; let submit = &raw const submit; let result = call( COMMAND_VK_QUEUE_SUBMIT, // SAFETY: a live local. |e| unsafe { encode_vkQueueSubmit(e, GENERATE_REPLY, queue, 1, submit, fence) }, |d| unsafe { decode_vkQueueSubmit_reply(d, queue, 1, submit, fence) }, ); if result != VK_SUCCESS { return result; } } // A window that changed size wants a new swapchain. // SAFETY: winit's window, which outlives its swapchain. let now = window_size(unsafe { &*(window as *const Window) }); if now.width != extent.width || now.height != extent.height { return VK_SUBOPTIMAL_KHR; } VK_SUCCESS } /// Each image copied, once what it waits for has run, into memory the host /// shares, then into its window. pub unsafe extern "system" fn vkQueuePresentKHR( queue: VkQueue, pPresentInfo: *const VkPresentInfoKHR, ) -> VkResult { // SAFETY: as the caller promised. let info = unsafe { &*pPresentInfo }; let mut overall = VK_SUCCESS; for i in 0..info.swapchainCount as usize { // SAFETY: `swapchainCount` of each, the caller's. let (swapchain, index) = unsafe { (*info.pSwapchains.add(i), *info.pImageIndices.add(i)) }; let start = std::time::Instant::now(); let result = unsafe { present(queue, swapchain, index, (i == 0).then_some(info)) }; if let Some(driver) = crate::driver().as_mut() { driver.stats.presented(start.elapsed()); } if !info.pResults.is_null() { unsafe { *info.pResults.add(i) = result }; } if result != VK_SUCCESS { overall = result; } } overall } /// One image presented: the first present of a call waits for the call's /// semaphores. unsafe fn present( queue: VkQueue, swapchain: VkSwapchainKHR, index: u32, waits: Option<&VkPresentInfoKHR>, ) -> VkResult { let chains = SWAPCHAINS.lock().unwrap(); let Some(chain) = chains.as_ref().and_then(|s| s.get(&swapchain)) else { return VK_ERROR_SURFACE_LOST_KHR; }; let Some(&(image, _)) = chain.images.get(index as usize) else { return VK_ERROR_OUT_OF_DATE_KHR; }; let (device, command_buffer, fence) = (chain.device, chain.command_buffer, chain.fence); // SAFETY (below): live locals and the swapchain's handles. unsafe { let mut begin: VkCommandBufferBeginInfo = zeroed(); begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT as u32; vkResetCommandBuffer(command_buffer, 0); vkBeginCommandBuffer(command_buffer, &begin); let mut range: VkImageSubresourceRange = zeroed(); range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT as u32; range.levelCount = 1; range.layerCount = 1; let mut barrier: VkImageMemoryBarrier = zeroed(); barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barrier.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT as u32; barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT as u32; barrier.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED as u32; barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED as u32; barrier.image = image; barrier.subresourceRange = range; let all = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT as u32; vkCmdPipelineBarrier( command_buffer, all, VK_PIPELINE_STAGE_TRANSFER_BIT as u32, 0, 0, null(), 0, null(), 1, &barrier, ); let mut region: VkBufferImageCopy = zeroed(); region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT as u32; region.imageSubresource.layerCount = 1; region.imageExtent = VkExtent3D { width: chain.extent.width, height: chain.extent.height, depth: 1, }; vkCmdCopyImageToBuffer( command_buffer, image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, chain.buffer, 1, ®ion, ); vkEndCommandBuffer(command_buffer); let (count, semaphores) = waits.map_or((0, null()), |w| (w.waitSemaphoreCount, w.pWaitSemaphores)); let stages: Vec = vec![all; count as usize]; let mut submit: VkSubmitInfo = zeroed(); submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submit.waitSemaphoreCount = count; submit.pWaitSemaphores = semaphores; submit.pWaitDstStageMask = stages.as_ptr(); submit.commandBufferCount = 1; submit.pCommandBuffers = &command_buffer; let result = vkQueueSubmit(queue, 1, &submit, fence); if result != VK_SUCCESS { return result; } let result = crate::vkWaitForFences(device, 1, &fence, 1, 5_000_000_000); if result != VK_SUCCESS { return result; } vkResetFences(device, 1, &fence); let window = &*(chain.window as *const Window); (window.present)( window.context, chain.mapped, chain.extent.width, chain.extent.height, ); } VK_SUCCESS }