diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index e305ea13c..4229a45de 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -1487,8 +1487,8 @@ or does not check is rebuilt from the generations' names, with young counted ful ### Known gaps of render pipeline states -- Refused at creation by `Gap::RenderPipeline`, naming its `RenderPipelineKind`: a depth - attachment, more than one sample, vertex amplification, a post-tessellation vertex function, +- Refused at creation by `Gap::RenderPipeline`, naming its `RenderPipelineKind`: more than one + sample, vertex amplification, a post-tessellation vertex function, stages the translator synthesizes beside the functions', framebuffer fetch, an imageblock, a fragment function's stencil output, alpha to one, constant data the binder supplies, a specialization other than the sample and amplification counts, dynamic state beyond Vulkan @@ -1524,6 +1524,14 @@ or does not check is rebuilt from the generations' names, with young counted ful even); an integer channel's is truncated toward zero and saturated to the channel's width, NaN 0, as Metal's. A rotated format's clear color, and `A8Unorm`'s held in `R8_UNORM`, go through the format's rotation. A clear stencil keeps its low 8 bits. +- A depth attachment is loaded, cleared and stored as a color attachment is, its clear depth a + `float`. A draw neither tests nor writes it yet (`DrawKind::DepthTest`, below). Where a pass + has both a depth and a stencil attachment they are one texture's same level and slice, a + format of depth and stencil, rendered through one view: Vulkan's rendering takes one view for + both (`VUID-VkRenderingInfo-pDepthAttachment-06085`). A pipeline state's depth and stencil + formats are the pass's, as its color formats are; the format query decides which depth and + stencil formats a device renders, a texture of `RenderTarget` usage in one it does not is not + made, and a pipeline state of one is the translator's refusal. - The render area is the smallest attachment's level, cut to `renderTargetWidth` and `renderTargetHeight` where they are set. - A pass orders itself as a blit's copy does, with two barriers. The first runs it after every @@ -1541,8 +1549,9 @@ or does not check is rebuilt from the generations' names, with young counted ful copies nothing. - Refused, as Metal's validation stops them: an attachment's texture made without `RenderTarget` usage (`Refusal::AttachmentUsage`), a level or slice past its texture's - (`Refusal::AttachmentPlace`), a color attachment of a depth or stencil format or a stencil - attachment of a format without stencil (`Refusal::AttachmentFormat`). A refused descriptor + (`Refusal::AttachmentPlace`), a color attachment of a depth or stencil format, a depth + attachment of a format without depth or a stencil attachment of a format without stencil + (`Refusal::AttachmentFormat`). A refused descriptor leaves the command buffer open for another encoder. A pass may use all eight color attachments: the floor's `maxColorAttachments` is 8. - An encoder holds Metal's render state: a pipeline state, the vertex and fragment functions' @@ -1623,7 +1632,8 @@ or does not check is rebuilt from the generations' names, with young counted ful ### Known gaps of render encoders - Refused by `Gap::Draw`, naming its `DrawKind`: a draw of points, a depth-stencil state that - tests or writes depth (no pass has a depth attachment yet), a viewport Vulkan's is not (a + tests or writes depth (a pass's depth attachment is loaded, cleared and stored, and no draw + tests or writes it yet), a viewport Vulkan's is not (a negative width, a depth range past `[0, 1]`, bounds past the device's viewport limits), a pipeline state whose formats are not the pass's attachments', a draw that binds a texture whose image the pass renders, where neither the feedback loop nor a copy reads it: on a device @@ -1651,15 +1661,21 @@ or does not check is rebuilt from the generations' names, with young counted ful `useHeap:stages:` (`command-replay shapes` counts a stream's calls of each selector), it is built in the compute encoder's form, `use_heap`: the command buffer keeps the block and declares no access. -- Refused by `Gap::RenderPass`, naming its `RenderPassKind`: a depth attachment, an attachment of - more than one sample, a resolve, a 1D or 3D texture's attachment, the `Unknown` and +- Refused by `Gap::RenderPass`, naming its `RenderPassKind`: a depth and a stencil attachment + that are not one texture's same level and slice (`DepthStencilViews`: Vulkan's rendering takes + one view for both), a `Clear` load of a depth attachment whose clear depth is outside `[0, 1]` + or NaN (`ClearDepth`: Vulkan clears no such depth without `VK_EXT_depth_range_unrestricted`, + `VUID-VkClearDepthStencilValue-depth-00022`, which the floor does not require), an attachment + of more than one sample, a resolve, a 1D or 3D texture's attachment, the `Unknown` and `CustomSampleDepthStore` store actions, a clear of a format only a shader clears (extended range, bfloat, YCbCr), and a pass with no attachment. The descriptor has no field for a visibility result buffer, a rasterization rate map, tile sizes, imageblock and threadgroup memory, sample buffer attachments, layered rendering or store action options. The replay - streams' passes render into one or two color attachments and a stencil attachment, each a level - of a 2D texture of one sample, with `Load`, `Clear` and `DontCare` loads and `Store` and - `DontCare` stores. + streams' passes render into one or two color attachments and a stencil attachment or a + `Depth32Float` depth attachment, each a level of a 2D texture of one sample, with `Load`, + `Clear` and `DontCare` loads and `Store` and `DontCare` stores. Their depth attachments (478 + passes of one stream, none beside a stencil attachment) clear to 1 or load, and store, under + Metal's default depth-stencil state. - An attachment whose home layout is shader-read-only (a texture of shader-read and render-target usage) is moved to the attachment layout and back by every pass that renders into it. A pass that reads it through a texture moves the whole image to the feedback layout at its first diff --git a/crates/metal2vulkan-rt/src/error.rs b/crates/metal2vulkan-rt/src/error.rs index d539c7202..50a03ebb5 100644 --- a/crates/metal2vulkan-rt/src/error.rs +++ b/crates/metal2vulkan-rt/src/error.rs @@ -637,11 +637,12 @@ pub enum Refusal { /// The slice asked for. slice: u32, }, - /// A render pass color attachment of a depth or stencil pixel format, or a stencil attachment - /// of a format without stencil. + /// A render pass color attachment of a depth or stencil pixel format, a depth attachment of a + /// format without depth, or a stencil attachment of a format without stencil. /// - /// Basis: metal-documented (a color attachment takes a color-renderable format and a stencil - /// attachment a format with stencil; Metal's validation stops the descriptor). + /// Basis: metal-documented (a color attachment takes a color-renderable format, a depth + /// attachment a format with depth and a stencil attachment a format with stencil; Metal's + /// validation stops the descriptor). AttachmentFormat { /// The texture's pixel format. pixel_format: PixelFormat, @@ -883,9 +884,9 @@ pub enum Gap { }, /// A render pipeline state of something the runtime does not build yet: what `kind` names. /// - /// Basis: ours (the replay streams' render pipelines draw into colour and stencil attachments - /// of one sample, with no depth attachment, no tessellation and no framebuffer fetch; each - /// other kind is built when a replay stream makes one). + /// Basis: ours (the replay streams' render pipelines draw into colour, depth and stencil + /// attachments of one sample, with no tessellation and no framebuffer fetch; each other kind + /// is built when a replay stream makes one). RenderPipeline { /// What the pipeline asks for. kind: RenderPipelineKind, @@ -911,9 +912,10 @@ pub enum Gap { /// what `kind` names. /// /// Basis: ours (the replay streams' passes render into one to two color attachments and a - /// stencil attachment, each a level of a 2D texture of one sample, with no depth attachment, - /// no resolve and no store action left unknown; each other kind is built when a replay stream - /// makes one). + /// stencil or a `Depth32Float` depth attachment, each a level of a 2D texture of one sample, + /// with no resolve, no store action left unknown and a clear depth of 1; each other kind is + /// built when a replay stream makes one; `DepthStencilViews` and `ClearDepth` are what Vulkan's + /// rendering under the floor takes no form of). RenderPass { /// What the pass asks for. kind: RenderPassKind, @@ -936,8 +938,6 @@ pub enum Gap { #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum RenderPipelineKind { - /// A depth attachment (`depthAttachmentPixelFormat`). - DepthAttachment, /// More than one sample (`rasterSampleCount`). Multisample, /// Vertex amplification (`maxVertexAmplificationCount` above 1). @@ -976,7 +976,8 @@ pub enum RenderPipelineKind { pub enum DrawKind { /// A draw of points (`MTLPrimitiveTypePoint`). Points, - /// A depth-stencil state that tests or writes depth: no pass has a depth attachment yet. + /// A depth-stencil state that tests or writes depth: a pass's depth attachment is loaded, + /// cleared and stored, and no draw tests or writes it yet. DepthTest, /// A viewport Vulkan's is not: a negative width (Metal mirrors the draw), a depth range past /// `[0, 1]`, or bounds past the device's viewport limits. @@ -1003,8 +1004,14 @@ pub enum DrawKind { #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum RenderPassKind { - /// A depth attachment (`depthAttachment.texture`). - DepthAttachment, + /// A depth attachment and a stencil attachment that are not one texture's same level and + /// slice: Vulkan's rendering takes one image view for both + /// (VUID-VkRenderingInfo-pDepthAttachment-06085). + DepthStencilViews, + /// A `Clear` load of a depth attachment whose `clearDepth` lies outside `[0, 1]`, or is NaN: + /// Vulkan clears no such depth without `VK_EXT_depth_range_unrestricted` + /// (VUID-VkClearDepthStencilValue-depth-00022), which the floor does not require. + ClearDepth, /// An attachment of more than one sample. Multisample, /// A resolve texture, or a store action that resolves. diff --git a/crates/metal2vulkan-rt/src/pass.rs b/crates/metal2vulkan-rt/src/pass.rs index a1903292b..c4875d8f9 100644 --- a/crates/metal2vulkan-rt/src/pass.rs +++ b/crates/metal2vulkan-rt/src/pass.rs @@ -123,11 +123,20 @@ pub struct RenderPassColorAttachmentDescriptor { pub clear_color: ClearColor, } -/// `MTLRenderPassDepthAttachmentDescriptor`: a pass with a depth texture is refused, -/// [`Gap::RenderPass`] of [`RenderPassKind::DepthAttachment`]. +/// `MTLRenderPassDepthAttachmentDescriptor`. +/// +/// Loaded, cleared and stored as a color attachment is; a draw neither tests nor writes it yet +/// ([`DrawKind::DepthTest`](crate::DrawKind::DepthTest)). With a stencil attachment beside it, +/// both are one texture's same level and slice, a format of depth and stencil, as Vulkan's +/// rendering takes them; two others are refused, [`Gap::RenderPass`] of +/// [`RenderPassKind::DepthStencilViews`]. A `Clear` load's depth lies in `[0, 1]`; another is +/// refused, [`RenderPassKind::ClearDepth`]. +/// +/// Not built: a resolve and a 3D texture's `depthPlane`, as a color attachment's. #[derive(Clone)] pub struct RenderPassDepthAttachmentDescriptor { - /// `texture`: the depth texture rendered into; `None` for no depth attachment. + /// `texture`: the texture whose depth is rendered into; `None` for no depth attachment. It + /// needs `RenderTarget` usage, a format with depth and one sample. pub texture: Option, /// `level`: the mipmap level rendered into. pub level: u32, @@ -306,14 +315,21 @@ pub(crate) fn layout_barrier( pub(crate) struct Pass { /// Up to the last color attachment with a texture. pub(crate) colors: Vec>, + /// The depth attachment and the stencil attachment: one view of one image where both are set + /// (`Pass::check`), each with its own load, store and clear. + pub(crate) depth: Option, pub(crate) stencil: Option, pub(crate) area: [u32; 2], } impl Pass { - /// Every attachment, colors first. + /// Every attachment's image once, colors first: the stencil attachment's only where there is + /// no depth attachment, whose image it otherwise is. pub(crate) fn targets(&self) -> impl Iterator { - (self.colors.iter().flatten()).chain(&self.stencil) + let stencil = self.stencil.as_ref().filter(|_| self.depth.is_none()); + (self.colors.iter().flatten()) + .chain(&self.depth) + .chain(stencil) } /// Records `vkCmdBeginRendering` of the pass into `command`; `resumed`, again after the @@ -335,6 +351,7 @@ impl Pass { .map_or_else(Default::default, |t| t.info(resumed)) }) .collect(); + let depth = self.depth.as_ref().map(|t| t.info(resumed)); let stencil = self.stencil.as_ref().map(|t| t.info(resumed)); let [width, height] = self.area; let mut info = vk::RenderingInfo::default() @@ -344,11 +361,15 @@ impl Pass { }) .layer_count(1) .color_attachments(&colors); + if let Some(depth) = &depth { + info = info.depth_attachment(depth); + } if let Some(stencil) = &stencil { info = info.stencil_attachment(stencil); } - // SAFETY: as the caller states; the render area lies inside every attachment, and each - // is a view of one level and layer of its image. + // SAFETY: as the caller states; the render area lies inside every attachment, each is a + // view of one level and layer of its image, and a depth and a stencil attachment both set + // are one view. unsafe { device.cmd_begin_rendering(command, &info) }; } @@ -392,10 +413,41 @@ impl Pass { clear, )?); } - if let Some(texture) = &d.depth_attachment.texture { - mine(texture)?; - return Err(gap(RenderPassKind::DepthAttachment)); - } + let z = &d.depth_attachment; + let depth = match &z.texture { + Some(texture) => { + mine(texture)?; + let pf = texture.descriptor().pixel_format; + let depth = metal2vulkan::vk::ImageAspectFlags::DEPTH; + if !formats::aspects(pf).is_some_and(|aspects| aspects.contains(depth)) { + return Err(Error::Refused(Refusal::AttachmentFormat { + pixel_format: pf, + })); + } + let attachment = texture.attachment(z.level, z.slice)?; + let clear = match z.load_action { + LoadAction::Clear if !(0.0..=1.0).contains(&z.clear_depth) => { + return Err(gap(RenderPassKind::ClearDepth)) + } + LoadAction::Clear => z.clear_depth as f32, + LoadAction::Load | LoadAction::DontCare => 0.0, + }; + let clear = vk::ClearValue { + depth_stencil: vk::ClearDepthStencilValue { + depth: clear, + stencil: 0, + }, + }; + Some(target( + texture, + attachment, + z.load_action, + z.store_action, + clear, + )?) + } + None => None, + }; let s = &d.stencil_attachment; let stencil = match &s.texture { Some(texture) => { @@ -424,8 +476,14 @@ impl Pass { } None => None, }; + if let (Some(depth), Some(stencil)) = (&depth, &stencil) { + if depth.attachment.view != stencil.attachment.view { + return Err(gap(RenderPassKind::DepthStencilViews)); + } + } let mut pass = Pass { colors, + depth, stencil, area: [u32::MAX; 2], }; diff --git a/crates/metal2vulkan-rt/src/render.rs b/crates/metal2vulkan-rt/src/render.rs index 149b50f5e..8193f38d6 100644 --- a/crates/metal2vulkan-rt/src/render.rs +++ b/crates/metal2vulkan-rt/src/render.rs @@ -179,6 +179,8 @@ struct Fixed { blends: Vec, /// Each colour attachment's format by Metal index, `UNDEFINED` for an absent one. colors: Vec, + /// The depth and the stencil attachment's formats, `UNDEFINED` for none. + depth: vk::Format, stencil: vk::Format, } @@ -201,7 +203,9 @@ impl crate::Device { /// [`DeviceOptions::pipeline_cache_dir`]: crate::DeviceOptions::pipeline_cache_dir /// /// Built: one vertex and at most one fragment function, colour attachments of any format the - /// translator maps for the device, a stencil attachment, one sample, and every blend state, + /// translator maps for the device, a depth and a stencil attachment of a format the device + /// renders depth or stencil in (its format query, through the translator's mapping; another + /// is the translator's refusal), one sample, and every blend state, /// write mask and vertex descriptor of static strides Vulkan's fixed-function state takes with /// what device creation enables; what else the translator states is refused at the creation, /// by kind. @@ -440,8 +444,6 @@ fn draws( fn refuse(d: &RenderPipelineDescriptor) -> Result<(), Error> { let kind = if d.support_indirect_command_buffers { return Err(Error::Unsupported(Gap::IndirectCommandBuffers)); - } else if d.depth_format.is_some() { - RenderPipelineKind::DepthAttachment } else if d.raster_sample_count != 1 { RenderPipelineKind::Multisample } else if d.max_vertex_amplification_count != 1 { @@ -561,6 +563,11 @@ impl Fixed { }) }) .collect(); + let format = |format: Option| { + format.map_or(vk::Format::UNDEFINED, |format| { + vk::Format::from_raw(format.as_raw()) + }) + }; Fixed { bindings, divisors, @@ -570,9 +577,8 @@ impl Fixed { alpha_to_coverage: g.alpha_to_coverage, blends, colors, - stencil: g.stencil_format.map_or(vk::Format::UNDEFINED, |format| { - vk::Format::from_raw(format.as_raw()) - }), + depth: format(g.depth_format), + stencil: format(g.stencil_format), } } } @@ -717,7 +723,7 @@ impl RenderCompiled { /// Whether the content's `VkPipeline`s render into `pass`'s attachments: its colour formats are /// the pass's colour attachments', by index, an absent one where the pass has none, and its - /// stencil format the pass's stencil attachment's, or none without one. + /// depth and stencil formats the pass's depth and stencil attachments', or none without one. pub(crate) fn renders_into(&self, pass: &Pass) -> bool { let fixed = &self.fixed; let format = |t: Option<&crate::pass::Target>| { @@ -725,6 +731,7 @@ impl RenderCompiled { }; fixed.colors.len() == pass.colors.len() && (fixed.colors.iter().zip(&pass.colors)).all(|(&f, t)| f == format(t.as_ref())) + && fixed.depth == format(pass.depth.as_ref()) && fixed.stencil == format(pass.stencil.as_ref()) } @@ -783,6 +790,7 @@ impl RenderCompiled { let dynamic_states = vk::PipelineDynamicStateCreateInfo::default().dynamic_states(&states); let mut rendering = vk::PipelineRenderingCreateInfo::default() .color_attachment_formats(&fixed.colors) + .depth_attachment_format(fixed.depth) .stencil_attachment_format(fixed.stencil); let mut info = vk::GraphicsPipelineCreateInfo::default() .push_next(&mut rendering) diff --git a/crates/metal2vulkan-rt/src/render_encoder.rs b/crates/metal2vulkan-rt/src/render_encoder.rs index 762750b4a..75f7d3748 100644 --- a/crates/metal2vulkan-rt/src/render_encoder.rs +++ b/crates/metal2vulkan-rt/src/render_encoder.rs @@ -363,7 +363,8 @@ enum Call<'a> { /// /// Built: a render pipeline state, the vertex and fragment functions' buffers, bytes, textures /// and sampler states, one viewport and scissor rectangle, the cull mode, the front-facing -/// winding, a depth-stencil state that tests the stencil, the stencil references, the blend color, +/// winding, a depth-stencil state that tests the stencil and neither tests nor writes depth (a +/// pass's depth attachment is loaded, cleared and stored), the stencil references, the blend color, /// memory barriers, fences, and direct draws of lines and triangles, indexed or not. Not built, /// and so not methods: indirect draws, several viewports or scissor rectangles, the triangle fill /// mode, the depth clip mode, depth bias, visibility results, `useResource:`, the store action @@ -1688,8 +1689,8 @@ impl RenderCommandEncoder { device.cmd_set_front_face(command, face); } if dirty & TESTS != 0 { - // No pass has a depth attachment: a state that tests depth draws nothing - // (`DrawKind::DepthTest`). + // A pass's depth attachment is neither tested nor written: a state that tests or + // writes depth draws nothing (`DrawKind::DepthTest`). device.cmd_set_depth_test_enable(command, false); device.cmd_set_depth_write_enable(command, false); device.cmd_set_depth_compare_op(command, vk::CompareOp::ALWAYS); diff --git a/crates/metal2vulkan-rt/src/tests/draw.rs b/crates/metal2vulkan-rt/src/tests/draw.rs index f8b39f086..7e9a718ae 100644 --- a/crates/metal2vulkan-rt/src/tests/draw.rs +++ b/crates/metal2vulkan-rt/src/tests/draw.rs @@ -20,6 +20,10 @@ //! its row. //! - a stencil state that replaces the stencil marks what a draw covers, and one that tests it //! keeps a later draw to those pixels. +//! - a pass clears, loads and stores a shader-read `Depth32Float` depth attachment that its +//! draws, under Metal's default depth-stencil state, neither test nor write: one submission, +//! three barriers and one pass each; a state without the pass's depth format, or with one in +//! a pass without a depth attachment, is the formats' gap, and a depth test is its own. //! - a fragment function samples a texture through its constexpr sampler at the index the //! consumer gave it: each pixel reads its own texel. //! - a vertex function that reads `[[base_instance]]` (the owned fixture @@ -662,6 +666,130 @@ mod on_device { }); } + /// A pass with a depth attachment (a shader-read `Depth32Float` texture, as a replay stream's) + /// clears, loads and stores it while its draws, under Metal's default depth-stencil state, + /// neither test nor write it: a pass is one submission, three barriers (the attachment moves + /// from its shader-read home and back) and one pass. A pipeline state's depth format is the + /// pass's: a state without one, or one drawn in a pass without a depth attachment, is the + /// formats' gap, and a state that tests depth is the depth test's. + #[test] + fn every_device_clears_loads_and_stores_a_depth_attachment_its_draws_do_not_test() { + let Some(library) = examples() else { + return; + }; + let plain = descriptor(&library, "colored_fragment", PixelFormat::RGBA8Unorm); + let mut d = plain.clone(); + d.depth_format = Some(PixelFormat::Depth32Float); + each_device("draw_depth", |name, _, device| { + device + .grant_indices(IndexClass::Texture, 4096, 4) + .expect("a grant"); + let depth_state = state(name, &device, &d); + let mut buffers = Buffers::new(&device); + let (positions, colors) = vertices(&device, &mut buffers); + let color = target( + &device, + PixelFormat::RGBA8Unorm, + TextureUsage::RENDER_TARGET, + ); + let mut zd = + TextureDescriptor::new(TextureType::Type2D, PixelFormat::Depth32Float, SIDE, SIDE); + zd.usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET; + zd.storage_mode = StorageMode::Shared; + let depth = (device.new_texture(&zd, Some(4096))) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let with_depth = |load| { + let mut d = pass(&color, None); + let z = &mut d.depth_attachment; + z.texture = Some(depth.clone()); + z.load_action = load; + z.store_action = crate::StoreAction::Store; + z.clear_depth = 0.25; + d + }; + let queue = device.new_command_queue(4).expect("a queue"); + let draw = |result: Result<(), Error>| result.unwrap_or_else(|e| panic!("{name}: {e}")); + let counters = device.counters(); + for (load, first, color_of) in [ + (crate::LoadAction::Clear, 3, BLUE), + (crate::LoadAction::Load, 6, WHITE), + ] { + settled(&device); + let before = counters.metrics(); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = (command_buffer.render_command_encoder(&with_depth(load))) + .unwrap_or_else(|error| panic!("{name}: {error}")); + draw(encoder.set_render_pipeline_state(&depth_state)); + draw(encoder.set_vertex_buffer(Some(&positions), 0, 0)); + draw(encoder.set_vertex_buffer(Some(&colors), 0, 1)); + draw(encoder.draw_primitives(PrimitiveType::Triangle, first, 3, 1, 0)); + encoder.end_encoding(); + run(name, &command_buffer); + let after = counters.metrics(); + assert_eq!( + ( + after.submissions - before.submissions, + after.barriers - before.barriers, + after.passes - before.passes, + after.bytes_copied - before.bytes_copied, + ), + (1, 3, 1, 0), + "{name}: {load:?}: submissions, barriers, passes, bytes copied" + ); + assert_eq!(read(&color, 4), texels(|_, _| color_of), "{name}: {load:?}"); + if depth.unit().is_some() { + let want = floats(&[0.25; (SIDE * SIDE) as usize]); + assert_eq!(read(&depth, 4), want, "{name}: {load:?}: the depth kept"); + } else { + println!("{name}: the depth's bytes are not copied on this device"); + } + } + + // The pipeline state's depth format is the pass's, and a depth test is a gap. + let plain = state(name, &device, &plain); + let mut less = DepthStencilDescriptor::default(); + less.depth_compare_function = CompareFunction::Less; + let less = device.new_depth_stencil_state(&less); + let gap = |kind| Err::<(), _>(Error::Unsupported(Gap::Draw { kind })); + let same = |got: Result<(), Error>, want: Result<(), Error>, case: &str| { + assert_eq!(format!("{got:?}"), format!("{want:?}"), "{name}: {case}"); + }; + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = (command_buffer + .render_command_encoder(&with_depth(crate::LoadAction::Load))) + .unwrap_or_else(|error| panic!("{name}: {error}")); + draw(encoder.set_vertex_buffer(Some(&positions), 0, 0)); + draw(encoder.set_vertex_buffer(Some(&colors), 0, 1)); + draw(encoder.set_render_pipeline_state(&plain)); + same( + encoder.draw_primitives(PrimitiveType::Triangle, 3, 3, 1, 0), + gap(DrawKind::AttachmentFormats), + "a state without the pass's depth format", + ); + draw(encoder.set_render_pipeline_state(&depth_state)); + draw(encoder.set_depth_stencil_state(Some(&less))); + same( + encoder.draw_primitives(PrimitiveType::Triangle, 3, 3, 1, 0), + gap(DrawKind::DepthTest), + "a depth test", + ); + encoder.end_encoding(); + let mut encoder = (command_buffer.render_command_encoder(&pass(&color, None))) + .unwrap_or_else(|error| panic!("{name}: {error}")); + draw(encoder.set_vertex_buffer(Some(&positions), 0, 0)); + draw(encoder.set_vertex_buffer(Some(&colors), 0, 1)); + draw(encoder.set_render_pipeline_state(&depth_state)); + same( + encoder.draw_primitives(PrimitiveType::Triangle, 3, 3, 1, 0), + gap(DrawKind::AttachmentFormats), + "a depth format in a pass without a depth attachment", + ); + encoder.end_encoding(); + run(name, &command_buffer); + println!("{name}: the depth attachment cleared, loaded and stored, untested"); + }); + } + /// Each pixel samples its own texel through the constexpr sampler at the consumer's index. #[test] fn every_device_samples_a_texture_through_a_constexpr_sampler_in_a_draw() { diff --git a/crates/metal2vulkan-rt/src/tests/pass.rs b/crates/metal2vulkan-rt/src/tests/pass.rs index fea6e2681..a02d5a1dc 100644 --- a/crates/metal2vulkan-rt/src/tests/pass.rs +++ b/crates/metal2vulkan-rt/src/tests/pass.rs @@ -14,8 +14,10 @@ //! area; a pass clears one slice of a 2D array, the other slices kept. A pass alone is one //! submission, three barriers (its two and the segment's end) and one pass, and copies no byte //! of the runtime's own. Each attachment's view is made once and kept with its texture, then -//! freed with it. What Metal refuses is refused, what a pass does not build is a gap, and either -//! leaves the command buffer open for another encoder. +//! freed with it. What Metal refuses is refused (a depth attachment of a colour format among +//! it), what a pass does not build is a gap (a depth and a stencil attachment of two textures, +//! and a clear depth past `[0, 1]` or NaN, among them), and either leaves the command buffer +//! open for another encoder. use crate::error::{Error, Gap, RenderPassKind}; use crate::pass::{clear_color, ops}; @@ -520,8 +522,16 @@ mod on_device { }; let mut store = color(&colors, 0); store.color_attachments[0].store_action = StoreAction::Unknown; - let mut with_depth = color(&colors, 0); - with_depth.depth_attachment.texture = Some(depth.clone()); + let mut depth_of_color = color(&colors, 0); + depth_of_color.depth_attachment.texture = Some(colors.clone()); + let mut two_views = color(&colors, 0); + two_views.depth_attachment.texture = Some(depth.clone()); + two_views.stencil_attachment.texture = Some(stencil.clone()); + let mut far_clear = color(&colors, 0); + far_clear.depth_attachment.texture = Some(depth.clone()); + far_clear.depth_attachment.clear_depth = 2.0; + let mut nan_clear = far_clear.clone(); + nan_clear.depth_attachment.clear_depth = f64::NAN; let mut stencil_of_color = color(&colors, 0); stencil_of_color.stencil_attachment.texture = Some(colors.clone()); let cases = [ @@ -548,9 +558,27 @@ mod on_device { }), ), ( - with_depth, + depth_of_color, + Error::Refused(Refusal::AttachmentFormat { + pixel_format: PixelFormat::RGBA8Unorm, + }), + ), + ( + two_views, Error::Unsupported(Gap::RenderPass { - kind: RenderPassKind::DepthAttachment, + kind: RenderPassKind::DepthStencilViews, + }), + ), + ( + far_clear, + Error::Unsupported(Gap::RenderPass { + kind: RenderPassKind::ClearDepth, + }), + ), + ( + nan_clear, + Error::Unsupported(Gap::RenderPass { + kind: RenderPassKind::ClearDepth, }), ), ( diff --git a/crates/metal2vulkan-rt/src/tests/render.rs b/crates/metal2vulkan-rt/src/tests/render.rs index bf01c971c..eebc0890e 100644 --- a/crates/metal2vulkan-rt/src/tests/render.rs +++ b/crates/metal2vulkan-rt/src/tests/render.rs @@ -9,7 +9,7 @@ //! - Filled past a cap of 2, the map holds 2 render contents and forgets the least recently used, //! which lives while a state holds it and goes once that state does; a forgotten content //! compiles again, and one the map holds does not. -//! - A depth attachment or more than one sample is refused by kind, making no `VkPipeline`. +//! - More than one sample is refused by kind, making no `VkPipeline`. //! - A device on a cache directory a device before it used lowers nothing at creation: both //! lowerings are read from the directory, and the triangle class's `VkPipeline` is made from //! its file; the first device writes one pipeline file for each `VkPipeline` it made, and the @@ -219,18 +219,9 @@ mod on_device { return; }; let plain = descriptor(&library, "colored_fragment", PixelFormat::BGRA8Unorm); - let mut depth = plain.clone(); - depth.depth_format = Some(PixelFormat::Depth32Float); let mut samples = plain.clone(); samples.raster_sample_count = 4; - let cases = [ - ( - "a depth attachment", - depth, - RenderPipelineKind::DepthAttachment, - ), - ("four samples", samples, RenderPipelineKind::Multisample), - ]; + let cases = [("four samples", samples, RenderPipelineKind::Multisample)]; each_device("render_refused", |name, _, device| { let counters = device.counters(); for (case, d, kind) in &cases { diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 1b850ca8f..bafc6edae 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -13790,8 +13790,9 @@ variant metal2vulkan-rt::Refusal::ViewportNotFinite ViewportNotFinite variant metal2vulkan-rt::Refusal::WaitOnOwnThread WaitOnOwnThread variant metal2vulkan-rt::Refusal::ZeroRangePastBlock ZeroRangePastBlock { offset: u64, length: u64, block_len: u64 } variant metal2vulkan-rt::Refusal::ZeroRangeShared ZeroRangeShared { block: BlockId } +variant metal2vulkan-rt::RenderPassKind::ClearDepth ClearDepth variant metal2vulkan-rt::RenderPassKind::ClearFormat ClearFormat -variant metal2vulkan-rt::RenderPassKind::DepthAttachment DepthAttachment +variant metal2vulkan-rt::RenderPassKind::DepthStencilViews DepthStencilViews variant metal2vulkan-rt::RenderPassKind::Multisample Multisample variant metal2vulkan-rt::RenderPassKind::NoAttachment NoAttachment variant metal2vulkan-rt::RenderPassKind::Resolve Resolve @@ -13799,7 +13800,6 @@ variant metal2vulkan-rt::RenderPassKind::StoreAction StoreAction variant metal2vulkan-rt::RenderPassKind::TextureType TextureType variant metal2vulkan-rt::RenderPipelineKind::AlphaToOne AlphaToOne variant metal2vulkan-rt::RenderPipelineKind::ConstantData ConstantData -variant metal2vulkan-rt::RenderPipelineKind::DepthAttachment DepthAttachment variant metal2vulkan-rt::RenderPipelineKind::DeviceFeature DeviceFeature variant metal2vulkan-rt::RenderPipelineKind::DrawInput DrawInput variant metal2vulkan-rt::RenderPipelineKind::DynamicState DynamicState diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 80d0cb4dd..0b9380fa1 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -668,7 +668,7 @@ Columns: | `BufferCopyOverlap` | A copy between buffers whose source and destination share bytes | every device (a public call's own check of its arguments) | `ours`: Metal states no result for such a copy, and `vkCmdCopyBuffer` reads no byte it also writes, `VUID-vkCmdCopyBuffer-pRegions-00117`; the runtime does not emulate one | 1: `crates/metal2vulkan-rt/src/blit.rs (buffer_to_buffer)` | `-` | | `AttachmentUsage` | A render pass attachment (`CommandBuffer::render_command_encoder`) whose texture was made without `RenderTarget` usage | every device (a public call's own check of its arguments) | `metal-documented`: a texture a render pass renders into needs `MTLTextureUsageRenderTarget`; Metal's validation stops the descriptor | 1: `crates/metal2vulkan-rt/src/texture.rs (attachment)` | `-` | | `AttachmentPlace` | A render pass attachment of a level or slice past its texture's | every device (a public call's own check of its arguments) | `ours`: no texel of the texture is there to render into | 1: `crates/metal2vulkan-rt/src/texture.rs (attachment)` | `-` | -| `AttachmentFormat` | A render pass color attachment of a depth or stencil pixel format, or a stencil attachment of a format without stencil | every device (a public call's own check of its arguments) | `metal-documented`: a color attachment takes a color-renderable format and a stencil attachment a format with stencil; Metal's validation stops the descriptor | 2: `crates/metal2vulkan-rt/src/pass.rs (check, 2 sites)` | `-` | +| `AttachmentFormat` | A render pass color attachment of a depth or stencil pixel format, a depth attachment of a format without depth, or a stencil attachment of a... | every device (a public call's own check of its arguments) | `metal-documented`: a color attachment takes a color-renderable format, a depth attachment a format with depth and a stencil attachment a format with stencil; Metal's validation stops the descriptor | 3: `crates/metal2vulkan-rt/src/pass.rs (check, 3 sites)` | `-` | | `VertexBufferOffset` | A draw whose vertex descriptor reads a vertex buffer at an offset at or past the buffer's length | every device (a public call's own check of its arguments) | `metal-documented`: a buffer's offset lies inside it; Metal's validation stops the bind | 1: `crates/metal2vulkan-rt/src/render_encoder.rs (find)` | `-` | | `IndexBufferOffset` | An indexed draw whose index buffer offset is not a multiple of the index size, or whose indices leave the buffer | every device (a public call's own check of its arguments) | `metal-documented`: the offset is a multiple of the index size and the indices lie in the buffer; Metal's validation stops the draw | 1: `crates/metal2vulkan-rt/src/render_encoder.rs (draw)` | `-` | | `ArgumentPlace` | An indirect dispatch's arguments, or an indexed draw's indices, at a byte of the block the buffer lies in (its device copy's, for a Managed buffer... | every device (a public call's own check of its arguments) | `ours`: `vkCmdDispatchIndirect` reads its arguments at a multiple of 4 in the `VkBuffer`, and `vkCmdBindIndexBuffer` takes indices at a multiple of their size in the memory; a Metal buffer starts at an aligned address, so Metal's offset rule alone keeps both aligned there | 2: `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)`, `crates/metal2vulkan-rt/src/render_encoder.rs (draw)` | `-` | @@ -709,10 +709,10 @@ Columns: | `HeapTexture` | A heap texture the runtime does not place (`Device::new_heap_texture` and `Device::heap_texture_size_and_align`) | every device (a public call's own check of its arguments) | `ours`: heap textures are built for Private heaps of placeable images | 2: `crates/metal2vulkan-rt/src/texture.rs (heap_fit)`, `crates/metal2vulkan-rt/src/texture.rs (new_heap_texture)` | `-` | | `BufferCopyAlignment` | `BlitCommandEncoder::copy_from_buffer` or `BlitCommandEncoder::copy_from_texture_to_buffer` whose bytes no copy command in the floor addresses,... | every device (a public call's own check of its arguments) | `ours`: Vulkan 1.3 places a copy's rows in a buffer by a count of texels from an aligned offset; each is built when a replay stream makes one | 1: `crates/metal2vulkan-rt/src/blit.rs (buffer_copy)` | `-` | | `FillAlignment` | `BlitCommandEncoder::fill_buffer` of a range that does not start and end on whole 4-byte words of the bytes shaders reach, which Metal fills byte... | every device (a public call's own check of its arguments) | `ours`: `vkCmdFillBuffer` writes whole words; a byte fill is built when a replay stream makes one | 1: `crates/metal2vulkan-rt/src/blit.rs (fill_range)` | `-` | -| `RenderPipeline` | A render pipeline state of something the runtime does not build yet | every device (a public call's own check of its arguments) | `ours`: the replay streams' render pipelines draw into colour and stencil attachments of one sample, with no depth attachment, no tessellation and no framebuffer fetch; each other kind is built when a replay stream makes one | 5: `crates/metal2vulkan-rt/src/render.rs (draw_input)`, `crates/metal2vulkan-rt/src/render.rs (of, 3 sites)` (+1) | `-` | +| `RenderPipeline` | A render pipeline state of something the runtime does not build yet | every device (a public call's own check of its arguments) | `ours`: the replay streams' render pipelines draw into colour, depth and stencil attachments of one sample, with no tessellation and no framebuffer fetch; each other kind is built when a replay stream makes one | 5: `crates/metal2vulkan-rt/src/render.rs (draw_input)`, `crates/metal2vulkan-rt/src/render.rs (of, 3 sites)` (+1) | `-` | | `FenceOtherQueue` | A `Fence` updated or waited on by an encoder of a queue other than the first that used it | every device (a public call's own check of its arguments) | `ours`: a fence is built for one queue; the replay streams use each on one queue | 1: `crates/metal2vulkan-rt/src/fence.rs (used_on)` | `-` | | `TextureView` | `Texture::new_texture_view` of a kind Metal makes and the runtime does not build | every device (a public call's own check of its arguments) | `ours`: the replay streams' views that compute binds are same-format views of every slice, 2D views of one slice of a 2D array, and level subranges; each other kind is built when a replay stream binds one | 1: `crates/metal2vulkan-rt/src/texture.rs (new_texture_view)` | `-` | -| `RenderPass` | A render pass of something the runtime does not build yet (`CommandBuffer::render_command_encoder`) | every device (a public call's own check of its arguments) | `ours`: the replay streams' passes render into one to two color attachments and a stencil attachment, each a level of a 2D texture of one sample, with no depth attachment, no resolve and no store action left unknown; each other kind is built when a replay stream makes one | 3: `crates/metal2vulkan-rt/src/pass.rs (check)`, `crates/metal2vulkan-rt/src/pass.rs (ops)` (+1) | `-` | +| `RenderPass` | A render pass of something the runtime does not build yet (`CommandBuffer::render_command_encoder`) | every device (a public call's own check of its arguments) | `ours`: the replay streams' passes render into one to two color attachments and a stencil or a `Depth32Float` depth attachment, each a level of a 2D texture of one sample, with no resolve, no store action left unknown and a clear depth of 1; each other kind is built when a replay stream makes one; `DepthStencilViews` and `ClearDepth` are what Vulkan's rendering under the floor takes no form of | 3: `crates/metal2vulkan-rt/src/pass.rs (check)`, `crates/metal2vulkan-rt/src/pass.rs (ops)` (+1) | `-` | | `Draw` | A draw or render encoder state the runtime does not build yet (`RenderCommandEncoder`) | every device (a public call's own check of its arguments) | `ours`: the replay streams draw lines and triangles under depth-stencil states that test no depth, through viewports Vulkan's are, with pipeline states of their pass's formats; each other kind is built when a replay stream draws one), and device for [`DrawKind::DividedBaseInstance`] (a device that does not report `supportsNonZeroFirstInstance` | 4: `crates/metal2vulkan-rt/src/render_encoder.rs (attachment_reads)`, `crates/metal2vulkan-rt/src/render_encoder.rs (draw)` (+2) | `-` | ## Appendix: every site @@ -1257,7 +1257,7 @@ Each refusal's sites, with the function that builds it. - `rt:Refusal::BufferCopyOverlap`: `crates/metal2vulkan-rt/src/blit.rs (buffer_to_buffer)` - `rt:Refusal::AttachmentUsage`: `crates/metal2vulkan-rt/src/texture.rs (attachment)` - `rt:Refusal::AttachmentPlace`: `crates/metal2vulkan-rt/src/texture.rs (attachment)` -- `rt:Refusal::AttachmentFormat`: `crates/metal2vulkan-rt/src/pass.rs (check, 2 sites)` +- `rt:Refusal::AttachmentFormat`: `crates/metal2vulkan-rt/src/pass.rs (check, 3 sites)` - `rt:Refusal::VertexBufferOffset`: `crates/metal2vulkan-rt/src/render_encoder.rs (find)` - `rt:Refusal::IndexBufferOffset`: `crates/metal2vulkan-rt/src/render_encoder.rs (draw)` - `rt:Refusal::ArgumentPlace`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)`; `crates/metal2vulkan-rt/src/render_encoder.rs (draw)`