use std::ffi::c_void;
use super::device::{MetalDevice, MetalError};
use super::enums::*;
use super::objc::{msg0, msg9, sel, AutoreleasePool, Id, Owned, NIL};
use super::renderer::PassAttachments;
use super::resources::{new_texture_2d, new_texture_array};
const ROW_ALIGNMENT: usize = 256;
pub struct MetalRenderTarget {
draw_color: Owned,
color: Owned,
depth: Owned,
width: u32,
height: u32,
color_format: NSUInteger,
sample_count: u32,
slices: u32,
}
impl MetalRenderTarget {
pub fn new(
device: &MetalDevice,
width: u32,
height: u32,
color_format: NSUInteger,
sample_count: u32,
) -> Result<Self, MetalError> {
let (width, height) = (width.max(1), height.max(1));
let samples = sample_count.max(1);
if samples > 1 && !device.supports_sample_count(samples) {
return Err(MetalError::Unsupported(format!(
"{samples}x MSAA — this device does not support that sample count"
)));
}
let color = new_texture_2d(
device,
width,
height,
color_format,
texture_usage::RENDER_TARGET | texture_usage::SHADER_READ,
storage_mode::PRIVATE,
1,
1,
)?;
let draw_color = if samples > 1 {
new_texture_2d(
device,
width,
height,
color_format,
texture_usage::RENDER_TARGET,
storage_mode::PRIVATE,
samples,
1,
)?
} else {
color.clone()
};
let depth = new_texture_2d(
device,
width,
height,
pixel_format::DEPTH32_FLOAT,
texture_usage::RENDER_TARGET,
storage_mode::PRIVATE,
samples,
1,
)?;
Ok(Self {
draw_color,
color,
depth,
width,
height,
color_format,
sample_count: samples,
slices: 1,
})
}
pub fn attachments(&self) -> PassAttachments {
let resolve = if self.sample_count > 1 {
self.color.id()
} else {
NIL
};
unsafe {
PassAttachments::from_raw(
self.draw_color.id(),
resolve,
self.depth.id(),
NIL,
self.width,
self.height,
self.color_format,
pixel_format::DEPTH32_FLOAT,
self.sample_count,
)
}
}
pub fn size(&self) -> (u32, u32) {
(self.width, self.height)
}
pub fn sample_count(&self) -> u32 {
self.sample_count
}
pub fn color_texture(&self) -> Id {
self.color.id()
}
pub fn depth_texture(&self) -> Id {
self.depth.id()
}
pub fn layered(
device: &MetalDevice,
width: u32,
height: u32,
color_format: NSUInteger,
slices: u32,
) -> Result<Self, MetalError> {
let (width, height) = (width.max(1), height.max(1));
let slices = slices.clamp(1, 16);
let color = new_texture_array(
device,
width,
height,
color_format,
texture_usage::RENDER_TARGET | texture_usage::SHADER_READ,
slices,
)?;
let depth = new_texture_array(
device,
width,
height,
pixel_format::DEPTH32_FLOAT,
texture_usage::RENDER_TARGET,
slices,
)?;
Ok(Self {
draw_color: color.clone(),
color,
depth,
width,
height,
color_format,
sample_count: 1,
slices,
})
}
pub fn slices(&self) -> u32 {
self.slices
}
pub fn read_rgba(&self, device: &MetalDevice) -> Result<Vec<u8>, MetalError> {
self.read_rgba_slice(device, 0)
}
pub fn read_rgba_slice(&self, device: &MetalDevice, slice: u32) -> Result<Vec<u8>, MetalError> {
let bpp = pixel_format::bytes_per_pixel(self.color_format).ok_or_else(|| {
MetalError::Unsupported(format!(
"readback of pixel format {} is not implemented",
self.color_format
))
})?;
if bpp != 4 {
return Err(MetalError::Unsupported(format!(
"readback expects an 8-bit 4-channel format, got {} bytes per pixel",
bpp
)));
}
let width = self.width as usize;
let height = self.height as usize;
let padded = padded_row_bytes(width, bpp);
let staging = device.new_buffer(&vec![0u8; padded * height])?;
let _pool = AutoreleasePool::new();
unsafe {
let cmd = device.command_buffer();
if cmd.is_null() {
return Err(MetalError::NoCommandQueue);
}
let blit: Id = msg0(cmd, sel!("blitCommandEncoder"));
if blit.is_null() {
return Err(MetalError::NoCommandQueue);
}
let _: () = msg9(
blit,
sel!(
"copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:toBuffer:destinationOffset:destinationBytesPerRow:destinationBytesPerImage:"
),
self.color.id(),
slice.min(self.slices.saturating_sub(1)) as NSUInteger,
0usize,
MTLOrigin::default(),
MTLSize {
width: self.width as NSUInteger,
height: self.height as NSUInteger,
depth: 1,
},
staging.id(),
0usize,
padded as NSUInteger,
(padded * height) as NSUInteger,
);
let _: () = msg0(blit, sel!("endEncoding"));
let _: () = msg0(cmd, sel!("commit"));
let _: () = msg0(cmd, sel!("waitUntilCompleted"));
let contents: *const u8 = msg0::<*mut c_void>(staging.id(), sel!("contents")).cast();
if contents.is_null() {
return Err(MetalError::Allocation("readback buffer contents".into()));
}
let mut out = vec![0u8; width * height * bpp];
for y in 0..height {
let src = std::slice::from_raw_parts(contents.add(y * padded), width * bpp);
out[y * width * bpp..(y + 1) * width * bpp].copy_from_slice(src);
}
if pixel_format::is_bgra(self.color_format) {
for px in out.chunks_exact_mut(4) {
px.swap(0, 2);
}
}
Ok(out)
}
}
}
impl std::fmt::Debug for MetalRenderTarget {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MetalRenderTarget")
.field("width", &self.width)
.field("height", &self.height)
.field("color_format", &self.color_format)
.field("sample_count", &self.sample_count)
.finish()
}
}
fn padded_row_bytes(width: usize, bytes_per_pixel: usize) -> usize {
(width * bytes_per_pixel).div_ceil(ROW_ALIGNMENT) * ROW_ALIGNMENT
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rows_pad_up_to_the_alignment() {
assert_eq!(padded_row_bytes(64, 4), 256);
assert_eq!(padded_row_bytes(65, 4), 512);
assert_eq!(padded_row_bytes(256, 4), 1024);
for w in [1usize, 3, 17, 100, 1920] {
assert!(padded_row_bytes(w, 4) >= w * 4);
assert_eq!(padded_row_bytes(w, 4) % ROW_ALIGNMENT, 0);
}
}
}