lactea-host 0.3.2

Host-side helpers for embedding lactea: directory texture provider, image decoding, headless GPU setup, non-blocking frame read-back, rendering on the host's own Vulkan or Metal device, WAV reading.
Documentation
//! Vulkan interop: run lactea on the host's own `VkDevice` and render into host `VkImage`s.
//!
//! wgpu cannot adopt a foreign image on a device of its own, so the engine has to *be* on the host's
//! device. The host keeps creating the `VkInstance` and `VkDevice`; lactea only wraps the handles
//! through `wgpu::hal::vulkan` and never destroys them. Only raw Vulkan handles cross this API, so the
//! host may use any Vulkan binding, or a wgpu of another major version (its `as_hal::<Vulkan>()`
//! gives the handles).
//!
//! The contract, in order:
//!
//! 1. Create the `VkInstance` with `apiVersion` >= 1.1 *and* >= the version the physical device
//!    reports (`vkEnumerateInstanceVersion` is always safe: wgpu assumes the device exposes every
//!    core version it reports, and a lower instance version hides those functions; [`open_device`]
//!    checks this and refuses), plus the extension `VK_KHR_get_physical_device_properties2` (wgpu
//!    assumes it is on whenever it exists).
//! 2. [`requirements`] lists the device extensions wgpu needs and a `VkPhysicalDeviceFeatures` +
//!    `pNext` feature chain. Create the `VkDevice` with them (add your own extensions and features;
//!    chain your own structs in front of the `pNext` chain). A device created by wgpu itself already
//!    has them unless that wgpu needs fewer extensions than this one: [`open_device`] names the
//!    first one missing.
//! 3. [`open_device`] wraps the device as a `wgpu::Device` + `wgpu::Queue` for `lactea::Engine`.
//! 4. Every frame, [`wrap_image`] turns the host's `VkImage` into a `wgpu::Texture` to render into.
//!
//! Layout and synchronisation: lactea submits to the host's queue (`queue_family_index` /
//! `queue_index`, externally synchronised like any queue: do not submit to it from another thread at
//! the same time). The image may be in any layout and its contents are discarded; after the
//! submission it is in `VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL` with the colour writes finished
//! once the work has executed. On the same queue a pipeline barrier (`COLOR_ATTACHMENT_OUTPUT` ->
//! whatever comes next) is enough. Drop the engine and the wrapped device before the `VkDevice`, and
//! keep each image alive until the work rendering into it has executed.
//!
//! Present where wgpu has a Vulkan backend: Windows and non-Apple Unix.

use std::ffi::{CStr, c_void};

use ash::vk::{self, Handle};
use wgpu::hal::api::Vulkan;
use wgpu::hal::vulkan as hal;

/// `VK_FORMAT_R8G8B8A8_UNORM`.
pub const VK_FORMAT_R8G8B8A8_UNORM: u32 = 37;
/// `VK_FORMAT_B8G8R8A8_UNORM`.
pub const VK_FORMAT_B8G8R8A8_UNORM: u32 = 44;

/// The image formats lactea renders into, by `VkFormat`; `None` for any other.
pub fn format_from_vk(vk_format: u32) -> Option<wgpu::TextureFormat> {
    match vk_format {
        VK_FORMAT_R8G8B8A8_UNORM => Some(wgpu::TextureFormat::Rgba8Unorm),
        VK_FORMAT_B8G8R8A8_UNORM => Some(wgpu::TextureFormat::Bgra8Unorm),
        _ => None,
    }
}

/// The host's Vulkan objects. Dispatchable handles are pointers, extension names exactly as given
/// to `vkCreateInstance` / `vkCreateDevice`.
#[derive(Clone, Copy, Debug)]
pub struct VulkanHost<'a> {
    /// `vkGetInstanceProcAddr` of the loader the host uses, cast to a data pointer.
    pub get_instance_proc_addr: *const c_void,
    /// `VkInstance`.
    pub instance: *mut c_void,
    /// `VkPhysicalDevice` the device was (or will be) created on.
    pub physical_device: *mut c_void,
    /// `VkDevice`. Not read by [`requirements`].
    pub device: *mut c_void,
    /// Queue family and index lactea submits to (a family with graphics support, requested in
    /// `vkCreateDevice`). Not read by [`requirements`].
    pub queue_family_index: u32,
    pub queue_index: u32,
    /// `VkApplicationInfo::apiVersion` the instance was created with (0 = 1.0).
    pub api_version: u32,
    /// Instance extensions enabled by the host.
    pub instance_extensions: &'a [&'a CStr],
    /// Device extensions enabled by the host. Not read by [`requirements`].
    pub device_extensions: &'a [&'a CStr],
}

/// What `vkCreateDevice` needs for lactea; the pointers stay valid as long as this value.
pub struct VulkanRequirements {
    device_extensions: Vec<&'static CStr>,
    enabled_features: *const c_void,
    device_pnext: *const c_void,
    /// Owns the structs both pointers point into (boxed: their address must not move).
    _features: Box<hal::PhysicalDeviceFeatures>,
}

impl VulkanRequirements {
    /// Device extension names to enable (drop the ones already on your list: Vulkan forbids
    /// listing one twice).
    pub fn device_extensions(&self) -> &[&'static CStr] {
        &self.device_extensions
    }

    /// `const VkPhysicalDeviceFeatures *` for `VkDeviceCreateInfo::pEnabledFeatures`.
    pub fn enabled_features(&self) -> *const c_void {
        self.enabled_features
    }

    /// `const void *` feature-struct chain for `VkDeviceCreateInfo::pNext`; null when empty. Do not
    /// combine [`Self::enabled_features`] with a `VkPhysicalDeviceFeatures2` of your own.
    pub fn device_pnext(&self) -> *const c_void {
        self.device_pnext
    }
}

/// The host's instance as a wgpu-hal instance (never destroyed by lactea) and its adapter.
unsafe fn open_instance(
    host: &VulkanHost<'_>,
) -> Result<(hal::Instance, wgpu::hal::ExposedAdapter<Vulkan>), String> {
    if host.get_instance_proc_addr.is_null()
        || host.instance.is_null()
        || host.physical_device.is_null()
    {
        return Err("get_instance_proc_addr, instance and physical_device must be set".into());
    }
    // SAFETY: the host promises `get_instance_proc_addr` is a valid `PFN_vkGetInstanceProcAddr`;
    // data and function pointers have the same size on every platform with a Vulkan loader.
    let get_instance_proc_addr = unsafe {
        std::mem::transmute::<*const c_void, vk::PFN_vkGetInstanceProcAddr>(
            host.get_instance_proc_addr,
        )
    };
    let static_fn = || ash::StaticFn {
        get_instance_proc_addr,
    };
    let entry = unsafe { ash::Entry::from_static_fn(static_fn()) };
    let raw_instance = unsafe {
        ash::Instance::load(
            &static_fn(),
            vk::Instance::from_raw(host.instance as usize as u64),
        )
    };
    let api_version = if host.api_version == 0 {
        vk::API_VERSION_1_0
    } else {
        host.api_version
    };
    // wgpu-hal wants `&'static CStr` names and only ever looks for the ones it knows: hand it its own
    // list of what it would enable, restricted to what the host enabled.
    let flags = wgpu::InstanceFlags::empty();
    let mut extensions = hal::Instance::desired_extensions(&entry, api_version, flags)
        .map_err(|e| format!("enumerating instance extensions: {e}"))?;
    extensions.retain(|e| host.instance_extensions.contains(e));
    let instance = unsafe {
        hal::Instance::from_raw(
            entry,
            raw_instance,
            api_version,
            0,
            None,
            extensions,
            flags,
            wgpu::MemoryBudgetThresholds::default(),
            false,
            // The engine renders off-screen and never creates a swapchain.
            wgpu::VulkanSwapchainKind::Native,
            None,
            // The host owns the VkInstance.
            Some(Box::new(|| {})),
        )
    }
    .map_err(|e| format!("wrapping the VkInstance: {e}"))?;
    let phd = vk::PhysicalDevice::from_raw(host.physical_device as usize as u64);
    // wgpu-hal assumes the device exposes every version the physical device reports; a lower
    // instance apiVersion hides the newer core functions (the loader returns NULL for them).
    let device_version = unsafe {
        instance
            .shared_instance()
            .raw_instance()
            .get_physical_device_properties(phd)
    }
    .api_version;
    let have = (
        vk::api_version_major(api_version),
        vk::api_version_minor(api_version),
    );
    let need = (
        vk::api_version_major(device_version),
        vk::api_version_minor(device_version),
    );
    if have < need {
        return Err(format!(
            "the VkInstance was created with apiVersion {}.{} but the physical device is {}.{}: create it with \
             apiVersion >= {}.{} (e.g. the value of vkEnumerateInstanceVersion)",
            have.0, have.1, need.0, need.1, need.0, need.1
        ));
    }
    let adapter = instance
        .expose_adapter(phd)
        .ok_or("wgpu cannot use this VkPhysicalDevice (below its minimum requirements)")?;
    Ok((instance, adapter))
}

/// Which device extensions and features wgpu needs on `host`'s physical device. Reads only
/// `get_instance_proc_addr`, `instance`, `physical_device`, `api_version` and the instance
/// extensions.
///
/// # Safety
/// The handles in `host` are valid Vulkan objects.
pub unsafe fn requirements(host: &VulkanHost<'_>) -> Result<VulkanRequirements, String> {
    let (_instance, adapter) = unsafe { open_instance(host) }?;
    let features = wgpu::Features::empty();
    let device_extensions = adapter.adapter.required_device_extensions(features);
    let mut phd_features = Box::new(
        adapter
            .adapter
            .physical_device_features(&device_extensions, features),
    );
    let (enabled_features, device_pnext) = {
        let info = phd_features.add_to_device_create(vk::DeviceCreateInfo::default());
        (info.p_enabled_features.cast::<c_void>(), info.p_next)
    };
    Ok(VulkanRequirements {
        device_extensions,
        enabled_features,
        device_pnext,
        _features: phd_features,
    })
}

/// Wrap the host's `VkDevice` as the device and queue to build a `lactea::Engine` on. Uses wgpu's
/// default limits and no optional features.
///
/// # Safety
/// All handles in `host` are valid Vulkan objects; the device was created with at least the
/// extensions and features of [`requirements`], and outlives the returned device, its queue and
/// everything created from them.
pub unsafe fn open_device(host: &VulkanHost<'_>) -> Result<(wgpu::Device, wgpu::Queue), String> {
    if host.device.is_null() {
        return Err("device is NULL".into());
    }
    let (instance, exposed) = unsafe { open_instance(host) }?;
    let features = wgpu::Features::empty();
    // Exactly what wgpu itself enables on a device it opens for these features.
    let enabled = exposed.adapter.required_device_extensions(features);
    if let Some(missing) = enabled.iter().find(|e| !host.device_extensions.contains(e)) {
        return Err(format!(
            "the VkDevice must enable {} (see the Vulkan interop requirements)",
            missing.to_string_lossy()
        ));
    }
    let raw_device = unsafe {
        ash::Device::load(
            instance.shared_instance().raw_instance().fp_v1_0(),
            vk::Device::from_raw(host.device as usize as u64),
        )
    };
    let open = unsafe {
        exposed.adapter.device_from_raw(
            raw_device,
            // The host owns the VkDevice.
            Some(Box::new(|| {})),
            &enabled,
            features,
            &wgpu::Limits::default(),
            &wgpu::MemoryHints::default(),
            host.queue_family_index,
            host.queue_index,
        )
    }
    .map_err(|e| format!("wrapping the VkDevice: {e}"))?;
    let wgpu_instance = unsafe { wgpu::Instance::from_hal::<Vulkan>(instance) };
    let adapter = unsafe { wgpu_instance.create_adapter_from_hal::<Vulkan>(exposed) };
    unsafe { adapter.create_device_from_hal::<Vulkan>(open, &wgpu::DeviceDescriptor::default()) }
        .map_err(|e| format!("create_device_from_hal: {e}"))
}

/// The host's `VkImage` (a non-dispatchable handle, as `u64`) as a render attachment of `device`.
/// `format` is one [`format_from_vk`] accepts and the image's own; the image was created with
/// `VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT` at `width` x `height`.
///
/// Wrap the image again for every frame and drop the texture after submitting: a fresh wrapper makes
/// wgpu assume an undefined layout and discard the old contents, so it never relies on a layout the
/// host moved the image to in between.
///
/// # Safety
/// `device` comes from [`open_device`]; `image` is a valid image of that `VkDevice` matching the
/// description above, alive until the work rendering into it has executed.
pub unsafe fn wrap_image(
    device: &wgpu::Device,
    image: u64,
    width: u32,
    height: u32,
    format: wgpu::TextureFormat,
) -> Result<wgpu::Texture, String> {
    if image == 0 {
        return Err("image is VK_NULL_HANDLE".into());
    }
    let size = wgpu::Extent3d {
        width,
        height,
        depth_or_array_layers: 1,
    };
    let hal_desc = wgpu::hal::TextureDescriptor {
        label: Some("lactea host image"),
        size,
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format,
        usage: wgpu::TextureUses::COLOR_TARGET,
        memory_flags: wgpu::hal::MemoryFlags::empty(),
        view_formats: Vec::new(),
        texture_binding_view_dimension: None,
    };
    let hal_texture = {
        let Some(hal_device) = (unsafe { device.as_hal::<Vulkan>() }) else {
            return Err("the device is not a Vulkan device".into());
        };
        unsafe {
            hal_device.texture_from_raw(
                vk::Image::from_raw(image),
                &hal_desc,
                // The host owns the VkImage.
                Some(Box::new(|| {})),
                hal::TextureMemory::External,
            )
        }
    };
    Ok(unsafe {
        device.create_texture_from_hal::<Vulkan>(
            hal_texture,
            &wgpu::TextureDescriptor {
                label: Some("lactea host image"),
                size,
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format,
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
                view_formats: &[],
                texture_binding_view_dimension: None,
            },
            wgpu::TextureUses::UNINITIALIZED,
            // The host's image holds defined contents: no lazy clear (wgpu 30 behaviour).
            true,
        )
    })
}