use std::ffi::c_void;
use objc2::rc::Retained;
use objc2::runtime::ProtocolObject;
use objc2_metal::{MTLCommandQueue, MTLDevice, MTLTexture, MTLTextureType};
use wgpu::hal::api::Metal;
use wgpu::hal::metal as hal;
pub const MTL_PIXEL_FORMAT_RGBA8_UNORM: u64 = 70;
pub const MTL_PIXEL_FORMAT_BGRA8_UNORM: u64 = 80;
pub fn format_from_mtl(pixel_format: u64) -> Option<wgpu::TextureFormat> {
match pixel_format {
MTL_PIXEL_FORMAT_RGBA8_UNORM => Some(wgpu::TextureFormat::Rgba8Unorm),
MTL_PIXEL_FORMAT_BGRA8_UNORM => Some(wgpu::TextureFormat::Bgra8Unorm),
_ => None,
}
}
#[derive(Clone, Copy, Debug)]
pub struct MetalHost {
pub device: *mut c_void,
pub command_queue: *mut c_void,
}
unsafe fn retain<P: ?Sized>(ptr: *mut c_void) -> Option<Retained<ProtocolObject<P>>> {
unsafe { Retained::retain(ptr.cast::<ProtocolObject<P>>()) }
}
pub unsafe fn open_device(host: &MetalHost) -> Result<(wgpu::Device, wgpu::Queue), String> {
let device = unsafe { retain::<dyn MTLDevice>(host.device) }.ok_or("device is nil")?;
let queue = unsafe { retain::<dyn MTLCommandQueue>(host.command_queue) }
.ok_or("command_queue is nil")?;
let registry_id = device.registryID();
if queue.device().registryID() != registry_id {
return Err("command_queue belongs to another MTLDevice".into());
}
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends: wgpu::Backends::METAL,
..wgpu::InstanceDescriptor::new_without_display_handle()
});
let adapter = pollster::block_on(instance.enumerate_adapters(wgpu::Backends::METAL))
.into_iter()
.find(|a| {
unsafe { a.as_hal::<Metal>() }
.is_some_and(|h| h.raw_device().registryID() == registry_id)
})
.ok_or("wgpu does not list this MTLDevice")?;
let open = wgpu::hal::OpenDevice {
device: unsafe {
hal::Device::device_from_raw(device, wgpu::Features::empty(), &wgpu::Limits::default())
},
queue: unsafe { hal::Queue::queue_from_raw(queue, 1.0) },
};
unsafe { adapter.create_device_from_hal::<Metal>(open, &wgpu::DeviceDescriptor::default()) }
.map_err(|e| format!("create_device_from_hal: {e}"))
}
pub unsafe fn wrap_texture(
device: &wgpu::Device,
texture: *mut c_void,
width: u32,
height: u32,
format: wgpu::TextureFormat,
) -> Result<wgpu::Texture, String> {
let raw = unsafe { retain::<dyn MTLTexture>(texture) }.ok_or("texture is nil")?;
let (w, h) = (raw.width(), raw.height());
if (w, h) != (width as usize, height as usize) {
return Err(format!(
"the texture is {w}x{h}, the engine renders {width}x{height}"
));
}
if raw.textureType() != MTLTextureType::Type2D {
return Err("the texture must be MTLTextureType2D".into());
}
let size = wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
};
let hal_texture = unsafe {
hal::Device::texture_from_raw(
raw,
format,
MTLTextureType::Type2D,
1,
1,
wgpu::hal::CopyExtent {
width,
height,
depth: 1,
},
None,
)
};
Ok(unsafe {
device.create_texture_from_hal::<Metal>(
hal_texture,
&wgpu::TextureDescriptor {
label: Some("lactea host texture"),
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,
)
})
}