mod functions; use functions::{create_instance, create_logical_device, pick_physical_device}; use crate::VALIDATION_ENABLED; use ::anyhow::{anyhow, Result}; use ::log::*; use ::thiserror::Error; use ::vulkanalia::loader::{LibloadingLoader, LIBRARY}; use ::vulkanalia::prelude::v1_0::*; use ::vulkanalia::vk::ExtDebugUtilsExtension; use ::vulkanalia::vk::KhrSurfaceExtension; use ::vulkanalia::window as vk_window; use ::winit::window::Window; /// Our Vulkan app. #[derive(Clone, Debug)] pub struct App { entry: Entry, instance: Instance, data: AppData, device: Device, } impl App { /// Creates our Vulkan app. pub unsafe fn create(window: &Window) -> Result { let loader = LibloadingLoader::new(LIBRARY)?; let entry = Entry::new(loader).map_err(|b| anyhow!("{}", b))?; let mut data = AppData::default(); let instance = create_instance(window, &entry, &mut data)?; data.surface = vk_window::create_surface(&instance, window)?; pick_physical_device(&instance, &mut data)?; let device = create_logical_device(&instance, &mut data)?; Ok(Self { entry, instance, data, device, }) } /// Renders a frame for our Vulkan app. pub unsafe fn render(&mut self, window: &Window) -> Result<()> { Ok(()) } /// Destroys our Vulkan app. pub unsafe fn destroy(&mut self) { self.device.destroy_device(None); if VALIDATION_ENABLED { self.instance .destroy_debug_utils_messenger_ext(self.data.messenger, None); } self.instance.destroy_surface_khr(self.data.surface, None); self.instance.destroy_instance(None); } } /// The Vulkan handles and associated properties used by our Vulkan app. #[derive(Clone, Debug, Default)] pub struct AppData { surface: vk::SurfaceKHR, // Debug messenger: vk::DebugUtilsMessengerEXT, // Physical Device / Logical Device physical_device: vk::PhysicalDevice, graphics_queue: vk::Queue, present_queue: vk::Queue, } #[derive(Debug, Error)] #[error("Missing {0}.")] pub struct SuitabilityError(pub &'static str); #[derive(Copy, Clone, Debug)] pub(crate) struct QueueFamilyIndicies { graphics: u32, present: u32, } impl QueueFamilyIndicies { unsafe fn get( instance: &Instance, data: &AppData, physical_device: vk::PhysicalDevice, ) -> Result { let properties = instance.get_physical_device_queue_family_properties(physical_device); let graphics = properties .iter() .position(|p| p.queue_flags.contains(vk::QueueFlags::GRAPHICS)) .map(|i| i as u32); let mut present = None; for (index, properties) in properties.iter().enumerate() { if instance.get_physical_device_surface_support_khr( physical_device, index as u32, data.surface, )? { present = Some(index as u32); break; } } if let (Some(graphics), Some(present)) = (graphics, present) { Ok(Self { graphics, present }) } else { Err(anyhow!(SuitabilityError( "Missing required queue families." ))) } } }