use std::ffi::{CStr, c_void};
use ash::vk::{self, Handle};
use wgpu::hal::api::Vulkan;
use wgpu::hal::vulkan as hal;
pub const VK_FORMAT_R8G8B8A8_UNORM: u32 = 37;
pub const VK_FORMAT_B8G8R8A8_UNORM: u32 = 44;
const UNUSED_BY_ENGINE: &[&CStr] = &[
ash::khr::swapchain::NAME,
ash::khr::swapchain_mutable_format::NAME,
ash::khr::incremental_present::NAME,
ash::google::display_timing::NAME,
ash::khr::external_memory_fd::NAME,
ash::ext::external_memory_dma_buf::NAME,
ash::ext::image_drm_format_modifier::NAME,
ash::khr::external_memory_win32::NAME,
ash::khr::external_semaphore_win32::NAME,
];
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,
}
}
#[derive(Clone, Copy, Debug)]
pub struct VulkanHost<'a> {
pub get_instance_proc_addr: *const c_void,
pub instance: *mut c_void,
pub physical_device: *mut c_void,
pub device: *mut c_void,
pub queue_family_index: u32,
pub queue_index: u32,
pub api_version: u32,
pub instance_extensions: &'a [&'a CStr],
pub device_extensions: &'a [&'a CStr],
}
pub struct VulkanRequirements {
device_extensions: Vec<&'static CStr>,
enabled_features: *const c_void,
device_pnext: *const c_void,
_features: Box<hal::PhysicalDeviceFeatures>,
}
impl VulkanRequirements {
pub fn device_extensions(&self) -> &[&'static CStr] {
&self.device_extensions
}
pub fn enabled_features(&self) -> *const c_void {
self.enabled_features
}
pub fn device_pnext(&self) -> *const c_void {
self.device_pnext
}
}
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());
}
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
};
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,
wgpu::VulkanSwapchainKind::Native,
None,
Some(Box::new(|| {})),
)
}
.map_err(|e| format!("wrapping the VkInstance: {e}"))?;
let phd = vk::PhysicalDevice::from_raw(host.physical_device as usize as u64);
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))
}
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,
})
}
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();
let mut enabled = exposed.adapter.required_device_extensions(features);
enabled.retain(|e| !UNUSED_BY_ENGINE.contains(e) || host.device_extensions.contains(e));
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,
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}"))
}
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,
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,
true,
)
})
}