From 9c40b3cd833f64108eb94b4acd2e1bd5aac3d8a1 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 18 Nov 2026 16:58:05 -0800 Subject: [PATCH] rt: depth tests, writes and bias as dynamic state, under static notes; an unknown store action stores The render-state lane's depth step (the planner's step 1). - A depth-stencil state's depth test, write and compare operation are dynamic state, recorded where they changed; DrawKind::DepthTest is gone. A pipeline bakes the depth format alone, so a change of depth-stencil state or bias makes no pipeline. In a pass without a depth attachment Vulkan skips the test, where Metal's documentation states no answer. - set_depth_bias (setDepthBias:slopeScale:clamp:): the bias and slope scale as given, enabled for a draw of triangles where either is not zero and never for lines (Metal biases triangles alone). A clamp other than 0 is Gap::Draw of DepthBiasClamp (no stream sets one). - Static notes, carried by the operation: PrecisionNote::DeviceDepthBias (RenderCommandEncoder::DEPTH_BIAS_NOTE: the slope measure, and a fixed-point attachment's unit, are the device's; Apple states neither; read from Vulkan's Depth Bias section and Apple's setDepthBias page), and PrecisionNote::DepthDenormals (DepthStencilState::precision_note, a state that tests or writes depth: every driver measured but MoltenVK on an M4 compares a denormal depth otherwise than Metal; RADV and ANV store one as zero). The old runtime maps DepthDenormals to its own depth-denormals kind and takes device-depth-bias as a note kind; codec, fast_paths, validation's allowance (Unbounded), API.md and ARTIFACT_FORMAT_VERSION 539 follow. No signed-depth note: no clear, viewport or upload gives rt a negative or NaN depth, and Vulkan leaves a depth past the viewport's range undefined. - MTLStoreActionUnknown stores (Vulkan fixes the store as the rendering begins); the encoder's set_color_store_action, set_depth_store_action and set_stencil_store_action change nothing the device does and refuse a resolving action (Resolve). On a tile-based device this stores a target Metal would have discarded (README). - set_triangle_fill_mode, set_depth_clip_mode, set_viewports and set_scissor_rects take Metal's defaults (Fill, Clip, one viewport or rectangle) as nothing and refuse the rest, typed (FillMode, DepthClamp, Viewports): replay found every stream at the defaults. - The conformance rt side plays the depth bias, fill, clip and viewport-count steps and announces the encoder's notes; the replay player maps setDepthBias:slopeScale:clamp:, the three store action setters, setTriangleFillMode: and setDepthClipMode:. - Tests: a depth attachment cleared to 0.5 with its store action unknown, tested under Less with writes, failing at 0.375, passing Greater by its bias alone, every mode setter's refusal, and no pipeline made by the state changes; the instructions a depth-tested draw retires beside a plain one, printed. REFUSALS.md regenerated, the API table blessed. --- .../metal2vulkan-conformance/src/rt_side.rs | 9 +- .../src/rt_side/render.rs | 68 +++-- crates/metal2vulkan-rt/README.md | 53 ++-- crates/metal2vulkan-rt/src/depth_stencil.rs | 29 +- crates/metal2vulkan-rt/src/error.rs | 31 +- crates/metal2vulkan-rt/src/lib.rs | 7 +- crates/metal2vulkan-rt/src/pass.rs | 39 ++- crates/metal2vulkan-rt/src/render_encoder.rs | 196 +++++++++++-- crates/metal2vulkan-rt/src/tests/draw.rs | 264 ++++++++++++++++-- crates/metal2vulkan-rt/src/tests/pass.rs | 8 +- .../metal2vulkan-runtime/src/degradation.rs | 9 +- .../src/observation_contract/comparison.rs | 4 +- .../observation_contract/comparison/tests.rs | 2 + .../src/replay/new_runtime/render.rs | 29 ++ crates/metal2vulkan/src/cache/codec.rs | 2 + crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/src/pipeline/artifact.rs | 26 ++ crates/metal2vulkan/src/tests/fast_paths.rs | 2 + crates/metal2vulkan/tests/api_signatures.tsv | 34 ++- docs/API.md | 12 + docs/REFUSALS.md | 6 +- 21 files changed, 707 insertions(+), 125 deletions(-) diff --git a/crates/metal2vulkan-conformance/src/rt_side.rs b/crates/metal2vulkan-conformance/src/rt_side.rs index 0f2ce3a2f..765c94972 100644 --- a/crates/metal2vulkan-conformance/src/rt_side.rs +++ b/crates/metal2vulkan-conformance/src/rt_side.rs @@ -357,6 +357,10 @@ pub struct RtSide<'a> { /// The render pipeline states a pass the case encoded set, whose precision notes /// [`Side::announced`] answers too. drawn: BTreeSet, + /// The static notes of what a pass the case encoded set beside its pipeline states: a depth + /// bias other than 0 (`RenderCommandEncoder::DEPTH_BIAS_NOTE`) and each depth-stencil state's + /// (`DepthStencilState::precision_note`), which [`Side::announced`] answers too. + encoder_notes: BTreeSet, } impl<'a> RtSide<'a> { @@ -376,6 +380,7 @@ impl<'a> RtSide<'a> { heaps: Vec::new(), dispatched: BTreeSet::new(), drawn: BTreeSet::new(), + encoder_notes: BTreeSet::new(), } } @@ -921,11 +926,13 @@ impl Side for RtSide<'_> { let drawn = (self.drawn.iter()) .filter_map(|&at| self.render_pipelines.get(at)) .flat_map(rt::RenderPipelineState::precision_notes); - let codes: BTreeSet<&'static str> = (dispatched.chain(drawn)) + let encoder = self.encoder_notes.iter().copied(); + let codes: BTreeSet<&'static str> = (dispatched.chain(drawn).chain(encoder)) .map(|note| metal2vulkan_runtime::Degradation::from_precision_note(note).code()) .collect(); self.dispatched.clear(); self.drawn.clear(); + self.encoder_notes.clear(); codes.into_iter().map(str::to_owned).collect() } diff --git a/crates/metal2vulkan-conformance/src/rt_side/render.rs b/crates/metal2vulkan-conformance/src/rt_side/render.rs index ea57cd5cb..12c093f91 100644 --- a/crates/metal2vulkan-conformance/src/rt_side/render.rs +++ b/crates/metal2vulkan-conformance/src/rt_side/render.rs @@ -9,8 +9,8 @@ use super::{keep, waited_for, RtSide, WAIT}; use crate::case::{Answer, Failure, Handle, PassOutcome}; use crate::render::{ - AttachmentPlace, RenderPass, RenderPipelineSpec, RenderStep, RenderWork, StageFunction, - TargetSpec, + AttachmentPlace, RenderPass, RenderPipelineSpec, RenderStep, RenderWork, ScissorBox, + StageFunction, TargetSpec, ViewportRect, }; use crate::transcript::{Negative, Value}; use crate::work::Plane; @@ -70,6 +70,28 @@ fn plain( Ok(()) } +/// The runtime's viewport of the case's. +fn viewport(rect: &ViewportRect) -> rt::Viewport { + rt::Viewport { + origin_x: rect.origin[0], + origin_y: rect.origin[1], + width: rect.size[0], + height: rect.size[1], + znear: rect.depth[0], + zfar: rect.depth[1], + } +} + +/// The runtime's scissor rectangle of the case's. +fn scissor(rect: &ScissorBox) -> rt::ScissorRect { + rt::ScissorRect { + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + } +} + /// The step's variant, which names the Metal call a refusal is of. fn step_name(step: &RenderStep) -> String { let debug = format!("{step:?}"); @@ -286,6 +308,17 @@ impl RtSide<'_> { RenderStep::Pipeline(state) => Some(state.0 as usize), _ => None, })); + let notes = pass.steps.iter().filter_map(|step| match step { + RenderStep::DepthBias(v) if v.bias != 0.0 || v.slope_scale != 0.0 => { + Some(rt::RenderCommandEncoder::DEPTH_BIAS_NOTE) + } + RenderStep::DepthStencilState(state) => (self.depth_stencils) + .get(state.0 as usize) + .and_then(rt::DepthStencilState::precision_note), + _ => None, + }); + let notes: Vec = notes.collect(); + self.encoder_notes.extend(notes); } _ => {} } @@ -392,6 +425,11 @@ impl RtSide<'_> { encoder.set_stencil_reference_value(*value); Ok(()) } + RenderStep::DepthBias(v) => { + (encoder.set_depth_bias(v.bias, v.slope_scale, v.clamp)).map_err(of_rt) + } + RenderStep::FillMode(mode) => encoder.set_triangle_fill_mode(*mode).map_err(of_rt), + RenderStep::DepthClip(mode) => encoder.set_depth_clip_mode(*mode).map_err(of_rt), RenderStep::StencilReferences { front, back } => { encoder.set_stencil_front_back_reference_value(*front, *back); Ok(()) @@ -462,25 +500,19 @@ impl RtSide<'_> { (encoder.set_fragment_sampler_state(Some(sampler(*held)?), index)) .map_err(of_rt) }), - RenderStep::Viewport(rect) => encoder - .set_viewport(rt::Viewport { - origin_x: rect.origin[0], - origin_y: rect.origin[1], - width: rect.size[0], - height: rect.size[1], - znear: rect.depth[0], - zfar: rect.depth[1], - }) - .map_err(of_rt), + RenderStep::Viewport(rect) => encoder.set_viewport(viewport(rect)).map_err(of_rt), + RenderStep::Viewports(rects) => { + let viewports: Vec = rects.iter().map(viewport).collect(); + encoder.set_viewports(&viewports).map_err(of_rt) + } RenderStep::Scissor(rect) => { - encoder.set_scissor_rect(rt::ScissorRect { - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - }); + encoder.set_scissor_rect(scissor(rect)); Ok(()) } + RenderStep::Scissors(rects) => { + let rects: Vec = rects.iter().map(scissor).collect(); + encoder.set_scissor_rects(&rects).map_err(of_rt) + } RenderStep::Cull(mode) => { encoder.set_cull_mode(*mode); Ok(()) diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index 8fcb437f9..5c02900e4 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -1524,16 +1524,34 @@ or does not check is rebuilt from the generations' names, with young counted ful image view of that level and layer with the identity swizzle, made at the first pass that renders into it and freed with the texture (`Gauges::attachment_views`). - Load actions are one to one: `Load`, `Clear` and `DontCare` are Vulkan's load operations of - those names. Both store actions store: a pass may end its rendering before the encoder ends and - begin it again, loading what it stored (below), so a `DontCare` store keeps the texels, one of - the outcomes Metal allows. A clear color is a `float` in a + those names. `Store`, `DontCare` and `Unknown` store: a pass may end its rendering before the + encoder ends and begin it again, loading what it stored (below), so a `DontCare` store keeps the + texels, one of the outcomes Metal allows. Vulkan fixes the store as the rendering begins, so an + `Unknown` store action stores, and the encoder's `set_color_store_action`, + `set_depth_store_action` and `set_stencil_store_action` change nothing the device does: on a + tile-based device this stores a target Metal would have discarded. A resolving action set there + is refused (`Gap::RenderPass` of `Resolve`). A clear color is a `float` in a float, normalized or sRGB channel, which the device converts to the format by its own rules (Vulkan clamps a normalized value and asks for rounding to nearest; Metal rounds to nearest 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 + `float`: an optimal image in its real layout, of the Vulkan format the translator's format table + chooses by the device's format query (`Depth32Float` is `D32_SFLOAT`, `Depth32Float_Stencil8` + `D32_SFLOAT_S8_UINT`). Draws test and write it as their depth-stencil state says, through + dynamic state: a pipeline bakes the depth format alone, so a change of depth-stencil state or + depth bias makes no pipeline. A state that tests or writes depth carries the static note + `PrecisionNote::DepthDenormals` (`DepthStencilState::precision_note`): every driver measured but + MoltenVK on an Apple M4 compares a denormal depth otherwise than Metal, and RADV and ANV store + one a GPU write gives as a zero. A negative or NaN depth, which Metal's test compares by its + magnitude, takes none: no clear, viewport or upload gives one, and Vulkan leaves a depth past + the viewport's range undefined. In a pass without a depth attachment Vulkan skips the depth + test, where Metal's documentation states no answer. `set_depth_bias` takes the bias and slope + scale as given; a draw of triangles is biased where either is not zero and a draw of lines + never, as Metal biases triangles alone, under the static note `PrecisionNote::DeviceDepthBias` + (`RenderCommandEncoder::DEPTH_BIAS_NOTE`): the slope measure, and a fixed-point attachment's + unit, are the device's; Apple states neither. 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 @@ -1566,7 +1584,7 @@ or does not check is rebuilt from the generations' names, with young counted ful buffers (`set_vertex_buffer`, `set_vertex_bytes` and their offsets, the fragment's alike), textures and sampler states, one viewport and scissor rectangle, the cull mode, the front-facing winding, a depth-stencil state (`Device::new_depth_stencil_state`), the stencil - references and the blend color, Metal's defaults where it set none. A vertex buffer slot serves + references, the depth bias and the blend color, Metal's defaults where it set none. A vertex buffer slot serves the vertex function's buffer argument of its index and the vertex descriptor's layout of its index alike, a `set_vertex_bytes` copy too, read through the parameter ring's buffer. - `draw_primitives` and `draw_indexed_primitives` are one `vkCmdDraw` or `vkCmdDrawIndexed` each. @@ -1639,9 +1657,13 @@ 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 (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 +- Refused by `Gap::Draw`, naming its `DrawKind`: a draw of points, a depth bias clamp other + than 0 (`DepthBiasClamp`, set by `set_depth_bias`), a triangle fill mode but `Fill` + (`FillMode`, `set_triangle_fill_mode`), the depth clip mode `Clamp` (`DepthClamp`, + `set_depth_clip_mode`), a count of viewports or scissor rectangles other than 1 (`Viewports`, + `set_viewports`, `set_scissor_rects`), each refused where it is set, the encoder's state + unchanged; the replay streams set Metal's defaults alone, which those setters take as nothing; 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 @@ -1653,7 +1675,7 @@ or does not check is rebuilt from the generations' names, with young counted ful (`DividedBaseInstance`: Vulkan's divisor takes `firstInstance` 0 alone there, VUID-vkCmdDraw-pNext-09461); the same draw from base instance 0 runs. An indirect draw, whose base instance the CPU does not see, is not built. The replay streams draw lines and triangles - under depth-stencil states that test no depth; every attachment they read through a texture is + under depth biases with no clamp; every attachment they read through a texture is a shader-read colour render target of `Private` storage, read from the fragment function; and their stepped draws (a WebGL stream's, at rates 2 and 3) are all at base instance 0. - A draw that reaches an attachment of its own pass through an argument buffer's texture is not @@ -1662,9 +1684,8 @@ or does not check is rebuilt from the generations' names, with young counted ful the level and layer it reads. - A vertex fetch outside its buffer returns what the device gives: the floor enables no buffer robustness, so there is no bounds guarantee beyond the device's. -- 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:`, - `useHeap:stages:`, the store action setters, tile functions and +- Not built, and so not methods: indirect draws, visibility results, `useResource:`, + `useHeap:stages:`, the store action options setters, tile functions and `setVertexBuffer:offset:attributeStride:atIndex:`. Where a replay stream calls `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 @@ -1674,16 +1695,14 @@ or does not check is rebuilt from the generations' names, with young counted ful 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 + of more than one sample, a resolve, a 1D or 3D texture's attachment, the + `CustomSampleDepthStore` store action, 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 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. + `Clear` and `DontCare` loads and `Store`, `DontCare` and `Unknown` stores. - 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/depth_stencil.rs b/crates/metal2vulkan-rt/src/depth_stencil.rs index a9b544922..f36c51c0c 100644 --- a/crates/metal2vulkan-rt/src/depth_stencil.rs +++ b/crates/metal2vulkan-rt/src/depth_stencil.rs @@ -4,6 +4,7 @@ use crate::device::{Core, Device}; use ash::vk; use metal2vulkan::metal::state::{depth_stencil_state, DepthStencilDescriptor, StencilOpState}; +use metal2vulkan::pipeline::PrecisionNote; use std::sync::Arc; /// `MTLDepthStencilState`. @@ -24,8 +25,13 @@ struct Inner { /// A depth/stencil descriptor's tests as Vulkan's dynamic state takes them. #[derive(Clone, Copy)] pub(crate) struct Tests { - /// Whether the depth test compares or writes (`depth_stencil_state`). - pub(crate) depth: bool, + /// Whether the depth test runs: it compares by other than `Always` or writes + /// (`depth_stencil_state`). + pub(crate) depth_test: bool, + /// Whether a fragment that passes writes its depth. + pub(crate) depth_write: bool, + /// The depth compare operation. + pub(crate) depth_compare: vk::CompareOp, /// Whether the stencil test can fail or change the stencil. pub(crate) stencil: bool, /// The front face's and the back face's stencil operations, compare operation and masks. @@ -56,7 +62,9 @@ impl Tests { write_mask: s.write_mask, }; Tests { - depth: state.depth_test_enable || state.depth_write_enable, + depth_test: state.depth_test_enable, + depth_write: state.depth_write_enable, + depth_compare: vk::CompareOp::from_raw(state.depth_compare_op.as_raw()), stencil: state.stencil_test_enable, faces: [face(&state.front), face(&state.back)], } @@ -85,6 +93,21 @@ impl DepthStencilState { &self.inner.descriptor } + /// No Metal counterpart: the static note of a draw under this state, where it tests or writes + /// depth ([`PrecisionNote::DepthDenormals`]: a denormal depth is the device's); `None` where it + /// does neither. + /// + /// A negative or NaN depth, which Metal's test compares by its magnitude, takes no note: the + /// runtime enables no `VK_EXT_depth_range_unrestricted` and refuses a clear depth outside + /// `[0, 1]` (`RenderPassKind::ClearDepth`), a viewport's depth range past it + /// (`DrawKind::Viewport`) and a 32-bit float depth upload (`Gap::FloatDepthUpload`), so a depth + /// attachment holds such a value only where Vulkan leaves a depth past the viewport's range + /// undefined. + pub fn precision_note(&self) -> Option { + let tests = self.inner.tests; + (tests.depth_test || tests.depth_write).then_some(PrecisionNote::DepthDenormals) + } + /// Its tests. pub(crate) fn tests(&self) -> Tests { self.inner.tests diff --git a/crates/metal2vulkan-rt/src/error.rs b/crates/metal2vulkan-rt/src/error.rs index 50a03ebb5..ff00514c3 100644 --- a/crates/metal2vulkan-rt/src/error.rs +++ b/crates/metal2vulkan-rt/src/error.rs @@ -912,10 +912,10 @@ pub enum Gap { /// what `kind` names. /// /// Basis: 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). + /// stencil or a depth attachment, each a level of a 2D texture of one sample, with no resolve + /// and a clear depth of 1, none naming two textures for its depth and stencil; 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, @@ -923,9 +923,9 @@ pub enum Gap { /// A draw or render encoder state the runtime does not build yet /// ([`RenderCommandEncoder`](crate::RenderCommandEncoder)): what `kind` names. /// - /// Basis: 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 + /// Basis: ours (the replay streams draw lines and triangles through one viewport Vulkan's is, + /// with pipeline states of their pass's formats, under depth biases with no clamp, filled and + /// clipped; each other kind is built when a replay stream draws one), and device for /// [`DrawKind::DividedBaseInstance`] (a device that does not report /// `supportsNonZeroFirstInstance`). Draw { @@ -976,9 +976,16 @@ pub enum RenderPipelineKind { pub enum DrawKind { /// A draw of points (`MTLPrimitiveTypePoint`). Points, - /// 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 depth bias clamp other than 0 (`setDepthBias:slopeScale:clamp:`'s `clamp`), which no + /// replay stream sets. + DepthBiasClamp, + /// A triangle fill mode but `Fill` (`setTriangleFillMode:`), which no replay stream sets. + FillMode, + /// The depth clip mode `Clamp` (`setDepthClipMode:`), which no replay stream sets. + DepthClamp, + /// More than one viewport or scissor rectangle, or none (`setViewports:count:`, + /// `setScissorRects:count:`), which no replay stream sets. + Viewports, /// 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. Viewport, @@ -1019,8 +1026,8 @@ pub enum RenderPassKind { /// An attachment of a texture type but a 2D texture, a 2D array, a cube or a cube array: a 1D /// texture's, or a 3D texture's depth plane. TextureType, - /// `MTLStoreActionUnknown`, which the encoder's `setColorStoreAction:atIndex:` family decides - /// later, or `MTLStoreActionCustomSampleDepthStore`. + /// `MTLStoreActionCustomSampleDepthStore`, set on the pass or by the encoder's + /// `setColorStoreAction:atIndex:` family. StoreAction, /// A `Clear` load action on an attachment whose format the runtime clears only through a /// shader: an extended-range, bfloat or YCbCr format. diff --git a/crates/metal2vulkan-rt/src/lib.rs b/crates/metal2vulkan-rt/src/lib.rs index a87e818d6..d22b41d2b 100644 --- a/crates/metal2vulkan-rt/src/lib.rs +++ b/crates/metal2vulkan-rt/src/lib.rs @@ -80,9 +80,12 @@ pub use metal2vulkan::metal::{ CompareFunction, SamplerAddressMode, SamplerBorderColor, SamplerMinMagFilter, SamplerMipFilter, SamplerReductionMode, }; -/// `MTLPrimitiveType`, `MTLIndexType`, `MTLCullMode`, `MTLWinding` and `MTLStencilOperation`: +/// `MTLPrimitiveType`, `MTLIndexType`, `MTLCullMode`, `MTLWinding`, `MTLStencilOperation`, +/// `MTLTriangleFillMode` and `MTLDepthClipMode`: /// the translator's. -pub use metal2vulkan::metal::{CullMode, IndexType, PrimitiveType, StencilOperation, Winding}; +pub use metal2vulkan::metal::{ + CullMode, DepthClipMode, IndexType, PrimitiveType, StencilOperation, TriangleFillMode, Winding, +}; /// `MTLPixelFormat`, `MTLTextureType`, `MTLTextureUsage` and `MTLTextureSwizzleChannels` with its /// `MTLTextureSwizzle`: the translator's. pub use metal2vulkan::metal::{ diff --git a/crates/metal2vulkan-rt/src/pass.rs b/crates/metal2vulkan-rt/src/pass.rs index c4875d8f9..5cfeab0a3 100644 --- a/crates/metal2vulkan-rt/src/pass.rs +++ b/crates/metal2vulkan-rt/src/pass.rs @@ -4,11 +4,14 @@ //! //! Each attachment is one level and slice of its texture, viewed through an image view of that //! level and layer with the identity swizzle, which the texture keeps. Its load actions are -//! Vulkan's of the same name: `Load`, `Clear` and `DontCare`. Both store actions store: a pass may -//! end its rendering before the encoder ends and begin it again, loading what it stored (a memory -//! barrier after a draw that wrote memory, or a copy a draw needs first), so a `DontCare` store -//! keeps the texels too, one of the outcomes Metal allows. The render area is the smallest -//! attachment's level, cut to `renderTargetWidth` and `renderTargetHeight` where they are set. +//! Vulkan's of the same name: `Load`, `Clear` and `DontCare`. Every store action the runtime builds +//! stores: a pass may end its rendering before the encoder ends and begin it again, loading what it +//! stored (a memory barrier after a draw that wrote memory, or a copy a draw needs first), so a +//! `DontCare` store keeps the texels too, one of the outcomes Metal allows. An `Unknown` one, which +//! the encoder sets later, stores too, as Vulkan fixes the store as the rendering begins: on a +//! tile-based device that stores a target Metal would have discarded. The render area is the +//! smallest attachment's level, cut to `renderTargetWidth` and `renderTargetHeight` where they are +//! set. use crate::device::Core; use crate::error::{Error, Gap, Refusal, RenderPassKind}; @@ -51,10 +54,14 @@ pub enum StoreAction { MultisampleResolve, /// `MTLStoreActionStoreAndMultisampleResolve`: refused, as `MultisampleResolve`. StoreAndMultisampleResolve, - /// `MTLStoreActionUnknown`, left to the encoder to decide before it ends: refused, - /// [`Gap::RenderPass`] of [`RenderPassKind::StoreAction`]. + /// `MTLStoreActionUnknown`, left to the encoder to decide before it ends + /// ([`RenderCommandEncoder::set_color_store_action`](crate::RenderCommandEncoder::set_color_store_action) + /// and its depth and stencil siblings): `VK_ATTACHMENT_STORE_OP_STORE`, as Vulkan fixes the + /// store as the rendering begins. A `DontCare` set later keeps the texels, as `DontCare` does; + /// on a tile-based device this stores a target Metal would have discarded. Unknown, - /// `MTLStoreActionCustomSampleDepthStore`: refused, as `Unknown`. + /// `MTLStoreActionCustomSampleDepthStore`: refused, [`Gap::RenderPass`] of + /// [`RenderPassKind::StoreAction`]. CustomSampleDepthStore, } @@ -125,8 +132,9 @@ pub struct RenderPassColorAttachmentDescriptor { /// `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, +/// Loaded, cleared and stored as a color attachment is, an optimal image in its real layout, of +/// the Vulkan format the translator's format table chooses by the device's format query; draws +/// test and write it as their depth-stencil state says. 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 @@ -507,7 +515,8 @@ impl Pass { } /// The Vulkan load and store operations of Metal's `load` and `store` actions: the load one to -/// one, and `STORE` for both store actions ([`StoreAction::DontCare`]). +/// one, and `STORE` for `Store`, `DontCare` ([`StoreAction::DontCare`]) and `Unknown` +/// ([`StoreAction::Unknown`]). /// /// Err: [`Gap::RenderPass`] of [`RenderPassKind::Resolve`] or [`RenderPassKind::StoreAction`]. pub(crate) fn ops( @@ -521,13 +530,13 @@ pub(crate) fn ops( }; let gap = |kind| Err(Error::Unsupported(Gap::RenderPass { kind })); let store = match store { - StoreAction::DontCare | StoreAction::Store => vk::AttachmentStoreOp::STORE, + StoreAction::DontCare | StoreAction::Store | StoreAction::Unknown => { + vk::AttachmentStoreOp::STORE + } StoreAction::MultisampleResolve | StoreAction::StoreAndMultisampleResolve => { return gap(RenderPassKind::Resolve) } - StoreAction::Unknown | StoreAction::CustomSampleDepthStore => { - return gap(RenderPassKind::StoreAction) - } + StoreAction::CustomSampleDepthStore => return gap(RenderPassKind::StoreAction), }; Ok((load, store)) } diff --git a/crates/metal2vulkan-rt/src/render_encoder.rs b/crates/metal2vulkan-rt/src/render_encoder.rs index 75f7d3748..4a5dedd03 100644 --- a/crates/metal2vulkan-rt/src/render_encoder.rs +++ b/crates/metal2vulkan-rt/src/render_encoder.rs @@ -61,6 +61,15 @@ //! derivatives follow Metal's clip space, whose y points up; Metal's front-facing winding is then //! Vulkan's front face of the same name. Metal clips a draw to the pixels its viewport covers, so //! the scissor is Metal's rectangle cut to those pixels. +//! +//! The depth-stencil state's depth test, write and compare operation and the depth bias are +//! dynamic state too, so a change of either makes no pipeline: a pipeline bakes the depth +//! attachment's format alone. In a pass without a depth attachment Vulkan skips the depth test and +//! writes nothing, where Metal's documentation states no answer. Metal biases triangles alone, so +//! a draw of lines records the bias disabled; a draw of triangles records it enabled where the +//! bias or the slope scale is not zero. The slope measure, and a fixed-point attachment's unit, +//! are the device's ([`PrecisionNote::DeviceDepthBias`]); a state that tests or writes depth +//! carries [`PrecisionNote::DepthDenormals`]. use crate::buffer::Buffer; use crate::command::{Building, CommandBuffer}; @@ -73,7 +82,7 @@ use crate::fence::Fence; use crate::hazard::Access; use crate::kept::{Handle, Lent, Uncounted}; use crate::over; -use crate::pass::{layout_barrier, Pass, RenderPassDescriptor}; +use crate::pass::{layout_barrier, ops, LoadAction, Pass, RenderPassDescriptor, StoreAction}; use crate::pipeline::{FieldValue, PUSH_STAGES}; use crate::record::{memory_barrier, Reach}; use crate::render::{Draws, RenderPipelineState, FRAGMENT, VERTEX}; @@ -84,7 +93,10 @@ use crate::texture::Texture; use ash::vk; use metal2vulkan::metal::format::integer_channels_word; use metal2vulkan::metal::state::{input_assembly, DepthStencilDescriptor}; -use metal2vulkan::metal::{CullMode, IndexType, PrimitiveType, Winding}; +use metal2vulkan::metal::{ + CullMode, DepthClipMode, IndexType, PrimitiveType, TriangleFillMode, Winding, +}; +use metal2vulkan::pipeline::PrecisionNote; use std::sync::Arc; /// `MTLViewport`: an origin and size in pixels, and a depth range. @@ -132,8 +144,7 @@ pub struct IndexBuffer<'a> { /// The dynamic state a draw records before it: the viewport and scissor, the cull mode, the /// front face, the depth and stencil tests, the stencil references, the blend constants, the -/// depth bias the encoder does not set, and the feedback loop's enable where the device reads -/// attachments. +/// depth bias, and the feedback loop's enable where the device reads attachments. const VIEWPORT: u32 = 1; const CULL: u32 = 2; const FRONT: u32 = 4; @@ -363,13 +374,14 @@ 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 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 -/// setters, tile functions and the `setVertexBuffer:offset:attributeStride:atIndex:` family. A -/// draw of what the runtime does not build is [`Gap::Draw`], naming its [`DrawKind`]. +/// winding, a depth-stencil state's depth and stencil tests, the depth bias without a clamp, the +/// stencil references, the blend color, the store actions an encoder sets for an attachment whose +/// pass left them unknown, 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, visibility results, `useResource:`, +/// the store action options setters, tile functions and the +/// `setVertexBuffer:offset:attributeStride:atIndex:` family. A draw of what the runtime does not +/// build is [`Gap::Draw`], naming its [`DrawKind`]. /// /// Owned: one thread encodes at a time. Dropping it ends it, as /// [`end_encoding`](Self::end_encoding) does. @@ -400,6 +412,10 @@ pub struct RenderCommandEncoder { /// The front and back stencil references, saturated to 8 bits. stencil_reference: [u32; 2], blend_color: [f32; 4], + /// The depth bias's constant and slope scale, Metal's `depthBias` and `slopeScale`. + depth_bias: [f32; 2], + /// Whether the last draw recorded the depth bias enabled. + biased: bool, /// The dynamic state to record before the next draw. dirty: u32, /// The topology and primitive restart the last draw set. @@ -477,6 +493,8 @@ impl CommandBuffer { winding: Winding::Clockwise, stencil_reference: [0; 2], blend_color: [0.0; 4], + depth_bias: [0.0; 2], + biased: false, dirty: ALL, topology: None, wrote: false, @@ -933,6 +951,125 @@ impl RenderCommandEncoder { self.dirty |= BLEND; } + /// The static precision note of a draw of triangles under a depth bias + /// ([`set_depth_bias`](Self::set_depth_bias)). + pub const DEPTH_BIAS_NOTE: PrecisionNote = PrecisionNote::DeviceDepthBias; + + /// `setDepthBias:slopeScale:clamp:`: the constant bias and the slope scale, as given. A draw of + /// triangles is biased where either is not zero, and a draw of lines never, as Metal biases + /// triangles alone. Metal's default is no bias. The slope measure, and a fixed-point + /// attachment's unit, are the device's; Apple states neither + /// ([`DEPTH_BIAS_NOTE`](Self::DEPTH_BIAS_NOTE)). A biased depth past the viewport's depth + /// range is undefined in Vulkan. + /// + /// Err: [`Gap::Draw`] of [`DrawKind::DepthBiasClamp`] for a clamp other than 0; the encoder's + /// bias is unchanged. + pub fn set_depth_bias( + &mut self, + depth_bias: f32, + slope_scale: f32, + clamp: f32, + ) -> Result<(), Error> { + if clamp != 0.0 { + return Err(Error::Unsupported(Gap::Draw { + kind: DrawKind::DepthBiasClamp, + })); + } + self.depth_bias = [depth_bias, slope_scale]; + self.dirty |= BIAS; + Ok(()) + } + + /// `setTriangleFillMode:`: `Fill`, Metal's default, is every draw's; another mode is not + /// built. + /// + /// Err: [`Gap::Draw`] of [`DrawKind::FillMode`] for another mode. + pub fn set_triangle_fill_mode(&mut self, mode: TriangleFillMode) -> Result<(), Error> { + match mode { + TriangleFillMode::Fill => Ok(()), + _ => Err(Error::Unsupported(Gap::Draw { + kind: DrawKind::FillMode, + })), + } + } + + /// `setDepthClipMode:`: `Clip`, Metal's default, is every draw's; `Clamp` is not built. + /// + /// Err: [`Gap::Draw`] of [`DrawKind::DepthClamp`] for `Clamp`. + pub fn set_depth_clip_mode(&mut self, mode: DepthClipMode) -> Result<(), Error> { + match mode { + DepthClipMode::Clip => Ok(()), + _ => Err(Error::Unsupported(Gap::Draw { + kind: DrawKind::DepthClamp, + })), + } + } + + /// `setViewports:count:`: one viewport is [`set_viewport`](Self::set_viewport)'s; several are + /// not built. + /// + /// Err: as [`set_viewport`](Self::set_viewport); [`Gap::Draw`] of [`DrawKind::Viewports`] for + /// a count other than 1. + pub fn set_viewports(&mut self, viewports: &[Viewport]) -> Result<(), Error> { + match viewports { + [viewport] => self.set_viewport(*viewport), + _ => Err(Error::Unsupported(Gap::Draw { + kind: DrawKind::Viewports, + })), + } + } + + /// `setScissorRects:count:`: one rectangle is [`set_scissor_rect`](Self::set_scissor_rect)'s; + /// several are not built. + /// + /// Err: [`Gap::Draw`] of [`DrawKind::Viewports`] for a count other than 1. + pub fn set_scissor_rects(&mut self, rects: &[ScissorRect]) -> Result<(), Error> { + match rects { + [rect] => { + self.set_scissor_rect(*rect); + Ok(()) + } + _ => Err(Error::Unsupported(Gap::Draw { + kind: DrawKind::Viewports, + })), + } + } + + /// `setColorStoreAction:atIndex:`: the store action of the colour attachment at `index`, which + /// its pass left `Unknown`. The pass stores every attachment + /// ([`StoreAction::Unknown`]), so a `Store` or a `DontCare` changes nothing the device does: + /// the texels are kept, one of the outcomes Metal allows a `DontCare`. An index with no + /// attachment is nothing to store. + /// + /// Err: [`Gap::RenderPass`] of [`RenderPassKind::Resolve`](crate::RenderPassKind::Resolve) + /// for an action that resolves, of + /// [`RenderPassKind::StoreAction`](crate::RenderPassKind::StoreAction) for + /// `CustomSampleDepthStore`. + pub fn set_color_store_action( + &mut self, + action: StoreAction, + index: usize, + ) -> Result<(), Error> { + let attached = self.pass.colors.get(index).is_some_and(Option::is_some); + later_store(action, attached) + } + + /// `setDepthStoreAction:`: the store action of the depth attachment, as + /// [`set_color_store_action`](Self::set_color_store_action)'s. + /// + /// Err: as [`set_color_store_action`](Self::set_color_store_action). + pub fn set_depth_store_action(&mut self, action: StoreAction) -> Result<(), Error> { + later_store(action, self.pass.depth.is_some()) + } + + /// `setStencilStoreAction:`: the store action of the stencil attachment, as + /// [`set_color_store_action`](Self::set_color_store_action)'s. + /// + /// Err: as [`set_color_store_action`](Self::set_color_store_action). + pub fn set_stencil_store_action(&mut self, action: StoreAction) -> Result<(), Error> { + later_store(action, self.pass.stencil.is_some()) + } + /// `memoryBarrierWithScope:afterStages:beforeStages:` and /// `memoryBarrierWithResources:count:afterStages:beforeStages:`: after a draw of the encoder /// that wrote memory, the rendering ends, one global memory barrier is recorded, and the @@ -1261,9 +1398,6 @@ impl RenderCommandEncoder { if topology == vk::PrimitiveTopology::POINT_LIST { return gap(DrawKind::Points); } - if self.tests.depth { - return gap(DrawKind::DepthTest); - } if self.tests.stencil && self.pass.stencil.is_none() { return Err(Error::Refused(Refusal::StencilAttachment)); } @@ -1689,11 +1823,9 @@ impl RenderCommandEncoder { device.cmd_set_front_face(command, face); } if dirty & TESTS != 0 { - // 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); + device.cmd_set_depth_test_enable(command, self.tests.depth_test); + device.cmd_set_depth_write_enable(command, self.tests.depth_write); + device.cmd_set_depth_compare_op(command, self.tests.depth_compare); device.cmd_set_stencil_test_enable(command, self.tests.stencil); for (face, f) in both.iter().zip(&self.tests.faces) { device.cmd_set_stencil_op( @@ -1716,9 +1848,19 @@ impl RenderCommandEncoder { if dirty & BLEND != 0 { device.cmd_set_blend_constants(command, &self.blend_color); } + // Metal biases triangles alone, where the bias or the slope scale is not zero. + let [constant, slope] = self.depth_bias; + let lines = matches!( + topology, + vk::PrimitiveTopology::LINE_LIST | vk::PrimitiveTopology::LINE_STRIP + ); + let biased = !lines && (constant != 0.0 || slope != 0.0); if dirty & BIAS != 0 { - device.cmd_set_depth_bias(command, 0.0, 0.0, 0.0); - device.cmd_set_depth_bias_enable(command, false); + device.cmd_set_depth_bias(command, constant, 0.0, slope); + } + if dirty & BIAS != 0 || biased != self.biased { + device.cmd_set_depth_bias_enable(command, biased); + self.biased = biased; } // Every pipeline takes the enable as dynamic state where the device reads attachments. if let (true, Some(feedback)) = (dirty & LOOP != 0, feedback) { @@ -1956,6 +2098,18 @@ fn around( .collect() } +/// A store action an encoder sets for an attachment its pass left unknown, `attached` where the +/// pass has that attachment: the pass stores it whatever the action, so only an action the +/// rendering could not have begun with is refused. +/// +/// Err: as [`ops`]. +fn later_store(action: StoreAction, attached: bool) -> Result<(), Error> { + match attached { + true => ops(LoadAction::Load, action).map(drop), + false => Ok(()), + } +} + /// The slot of buffer index `index`. /// /// Err: [`Refusal::BufferIndex`] for an index of 31 or more. diff --git a/crates/metal2vulkan-rt/src/tests/draw.rs b/crates/metal2vulkan-rt/src/tests/draw.rs index d1cee1a01..3bda1cf45 100644 --- a/crates/metal2vulkan-rt/src/tests/draw.rs +++ b/crates/metal2vulkan-rt/src/tests/draw.rs @@ -671,7 +671,7 @@ mod on_device { /// 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. + /// formats' gap. #[test] fn every_device_clears_loads_and_stores_a_depth_attachment_its_draws_do_not_test() { let Some(library) = examples() else { @@ -748,11 +748,8 @@ mod on_device { } } - // The pipeline state's depth format is the pass's, and a depth test is a gap. + // The pipeline state's depth format is the pass's. 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}"); @@ -769,13 +766,6 @@ mod on_device { 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}")); @@ -793,6 +783,244 @@ mod on_device { }); } + /// A depth attachment its draws test, write and bias, through dynamic state alone: no + /// pipeline is made by a change of depth-stencil state or bias, and the pass is one + /// submission, the barriers of a shader-read depth texture's pass, and one pass. Cleared to + /// 0.5 with its store action left unknown and set by the encoder: a draw at depth 0.25 under + /// `Less` with writes passes and writes 0.25; one at 0.375 then fails; one at 0.25 under + /// `Greater`, without writes, passes only by its bias (a constant of 2^23, which Vulkan's unit + /// for a `float` depth of exponent -2 makes 0.25, or 0.125 where the device counts 24 mantissa + /// bits). The setters that take Metal's defaults as nothing refuse every other value. + #[test] + fn every_device_tests_writes_and_biases_a_depth_attachment() { + let Some(library) = examples() else { + return; + }; + let mut d = descriptor(&library, "colored_fragment", PixelFormat::RGBA8Unorm); + d.depth_format = Some(PixelFormat::Depth32Float); + each_device("draw_depth_tests", |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 tests = |compare, write| { + let mut t = DepthStencilDescriptor::default(); + t.depth_compare_function = compare; + t.depth_write_enabled = write; + device.new_depth_stencil_state(&t) + }; + let less = tests(CompareFunction::Less, true); + let greater = tests(CompareFunction::Greater, false); + let depth_denormals = Some(crate::PrecisionNote::DepthDenormals); + assert_eq!(less.precision_note(), depth_denormals, "{name}: Less"); + assert_eq!(greater.precision_note(), depth_denormals, "{name}: Greater"); + let none = device.new_depth_stencil_state(&DepthStencilDescriptor::default()); + assert_eq!(none.precision_note(), None, "{name}: Metal's default"); + // The fixture's depth is 0, so a draw's depth is the range's near end, and a bias + // keeps it inside the range, where Vulkan defines it. + let at = |z: f64| Viewport { + origin_x: 0.0, + origin_y: 0.0, + width: f64::from(SIDE), + height: f64::from(SIDE), + znear: z, + zfar: 1.0, + }; + let queue = device.new_command_queue(4).expect("a queue"); + let draw = |result: Result<(), Error>| result.unwrap_or_else(|e| panic!("{name}: {e}")); + let same = |got: Result<(), Error>, want: Result<(), Error>, case: &str| { + assert_eq!(format!("{got:?}"), format!("{want:?}"), "{name}: {case}"); + }; + let gap = |kind| Err::<(), _>(Error::Unsupported(Gap::Draw { kind })); + let counters = device.counters(); + settled(&device); + let before = counters.metrics(); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut p = pass(&color, None); + let z = &mut p.depth_attachment; + z.texture = Some(depth.clone()); + z.load_action = crate::LoadAction::Clear; + z.store_action = crate::StoreAction::Unknown; + z.clear_depth = 0.5; + let mut encoder = (command_buffer.render_command_encoder(&p)) + .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)); + // Blue at 0.25 passes `Less` against 0.5 and writes 0.25. + draw(encoder.set_depth_stencil_state(Some(&less))); + draw(encoder.set_viewport(at(0.25))); + draw(encoder.draw_primitives(PrimitiveType::Triangle, 3, 3, 1, 0)); + // White at 0.375 fails `Less` against 0.25. + draw(encoder.set_viewport(at(0.375))); + draw(encoder.draw_primitives(PrimitiveType::Triangle, 6, 3, 1, 0)); + // White at 0.25 passes `Greater` against 0.25 by its bias alone. + draw(encoder.set_depth_stencil_state(Some(&greater))); + draw(encoder.set_viewport(at(0.25))); + draw(encoder.set_depth_bias(8_388_608.0, 0.0, 0.0)); + draw(encoder.draw_primitives(PrimitiveType::Triangle, 6, 3, 1, 0)); + same( + encoder.set_depth_bias(1.0, 0.0, 0.5), + gap(DrawKind::DepthBiasClamp), + "a depth bias clamp", + ); + draw(encoder.set_triangle_fill_mode(crate::TriangleFillMode::Fill)); + same( + encoder.set_triangle_fill_mode(crate::TriangleFillMode::Lines), + gap(DrawKind::FillMode), + "a fill mode of lines", + ); + draw(encoder.set_depth_clip_mode(crate::DepthClipMode::Clip)); + same( + encoder.set_depth_clip_mode(crate::DepthClipMode::Clamp), + gap(DrawKind::DepthClamp), + "the depth clip mode Clamp", + ); + draw(encoder.set_viewports(&[at(0.25)])); + same( + encoder.set_viewports(&[at(0.25), at(0.5)]), + gap(DrawKind::Viewports), + "two viewports", + ); + same( + encoder.set_scissor_rects(&[]), + gap(DrawKind::Viewports), + "no scissor rectangle", + ); + same( + encoder.set_depth_store_action(crate::StoreAction::MultisampleResolve), + Err(Error::Unsupported(Gap::RenderPass { + kind: crate::RenderPassKind::Resolve, + })), + "a resolving store action set later", + ); + draw(encoder.set_depth_store_action(crate::StoreAction::Store)); + encoder.end_encoding(); + run(name, &command_buffer); + let after = counters.metrics(); + assert_eq!( + ( + after.submissions - before.submissions, + after.passes - before.passes, + after.pipelines_created - before.pipelines_created, + after.bytes_copied - before.bytes_copied, + ), + (1, 1, 0, 0), + "{name}: submissions, passes, pipelines made, bytes copied" + ); + println!( + "{name}: {} barriers, {} pipelines made by three depth-stencil states and a bias", + after.barriers - before.barriers, + after.pipelines_created - before.pipelines_created + ); + assert_eq!(read(&color, 4), texels(|_, _| WHITE), "{name}: the colour"); + if depth.unit().is_some() { + let want = floats(&[0.25; (SIDE * SIDE) as usize]); + assert_eq!(read(&depth, 4), want, "{name}: the depth written"); + } else { + println!("{name}: the depth's bytes are not copied on this device"); + } + println!("{name}: the depth tested, written and biased"); + }); + } + + /// The user-space instructions a draw retires on the encoding thread, under a depth test whose + /// state and bias change every draw beside the plain draw path (no depth attachment, Metal's + /// default depth-stencil state), printed per draw where the kernel offers the counter (Linux). + #[test] + fn every_device_counts_a_depth_tested_draw_s_instructions() { + use metal2vulkan_devtools::instructions::InstructionCounter; + const DRAWS: u32 = 512; + 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_instructions", |name, _, device| { + let Ok(mut counter) = InstructionCounter::new() else { + println!("{name}: no instruction counter here"); + return; + }; + let plain_state = state(name, &device, &plain); + 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 depth = target( + &device, + PixelFormat::Depth32Float, + TextureUsage::RENDER_TARGET, + ); + let tests = |compare, write| { + let mut t = DepthStencilDescriptor::default(); + t.depth_compare_function = compare; + t.depth_write_enabled = write; + device.new_depth_stencil_state(&t) + }; + let states = [ + tests(CompareFunction::LessEqual, true), + tests(CompareFunction::Greater, false), + ]; + let queue = device.new_command_queue(4).expect("a queue"); + let draw = |result: Result<(), Error>| result.unwrap_or_else(|e| panic!("{name}: {e}")); + let mut per_draw = Vec::new(); + for tested in [false, true] { + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut p = pass(&color, None); + if tested { + p.depth_attachment.texture = Some(depth.clone()); + } + let mut encoder = (command_buffer.render_command_encoder(&p)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + draw(encoder.set_render_pipeline_state(match tested { + false => &plain_state, + true => &depth_state, + })); + draw(encoder.set_vertex_buffer(Some(&positions), 0, 0)); + draw(encoder.set_vertex_buffer(Some(&colors), 0, 1)); + // One draw first, so the counted ones record what changed alone. + draw(encoder.draw_primitives(PrimitiveType::Triangle, 3, 3, 1, 0)); + let ((), counted) = (counter.measure(|| { + for at in 0..DRAWS { + if tested { + let state = &states[at as usize % 2]; + draw(encoder.set_depth_stencil_state(Some(state))); + draw(encoder.set_depth_bias(at as f32, 0.0, 0.0)); + } + draw(encoder.draw_primitives(PrimitiveType::Triangle, 3, 3, 1, 0)); + } + })) + .expect("a count"); + encoder.end_encoding(); + run(name, &command_buffer); + per_draw.push(counted / u64::from(DRAWS)); + } + println!( + "{name}: user-space instructions a draw: {} plain, {} under a depth test whose \ + state and bias change every draw", + per_draw[0], per_draw[1] + ); + }); + } + /// 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() { @@ -1845,9 +2073,6 @@ define internal void @_GLOBAL__sub_I_() section "air.static_init" { PixelFormat::RGBA8Unorm, TextureUsage::RENDER_TARGET, ); - let mut depth = DepthStencilDescriptor::default(); - depth.depth_compare_function = CompareFunction::Less; - let depth = device.new_depth_stencil_state(&depth); let queue = device.new_command_queue(4).expect("a queue"); let command_buffer = queue.command_buffer().expect("a command buffer"); let mut encoder = (command_buffer.render_command_encoder(&pass(&color, None))) @@ -1874,15 +2099,6 @@ define internal void @_GLOBAL__sub_I_() section "air.static_init" { gap(DrawKind::Points), "points", ); - encoder - .set_depth_stencil_state(Some(&depth)) - .expect("a state"); - same( - encoder.draw_primitives(triangle, 0, 3, 1, 0), - gap(DrawKind::DepthTest), - "a depth test", - ); - encoder.set_depth_stencil_state(None).expect("no state"); let viewport = Viewport { origin_x: 0.0, origin_y: 0.0, diff --git a/crates/metal2vulkan-rt/src/tests/pass.rs b/crates/metal2vulkan-rt/src/tests/pass.rs index a02d5a1dc..d2c9542bd 100644 --- a/crates/metal2vulkan-rt/src/tests/pass.rs +++ b/crates/metal2vulkan-rt/src/tests/pass.rs @@ -25,8 +25,8 @@ use crate::{ClearColor, LoadAction, PixelFormat, StoreAction}; use ash::vk; use metal2vulkan::metal::format::FormatEmulation; -/// Each load action is Vulkan's of the same name, and the two plain store actions store; the -/// others are gaps. +/// Each load action is Vulkan's of the same name, and the plain and unknown store actions store; +/// the others are gaps. #[test] fn load_actions_are_one_to_one_and_plain_store_actions_store() { let pairs = [ @@ -38,6 +38,7 @@ fn load_actions_are_one_to_one_and_plain_store_actions_store() { for (store, store_op) in [ (StoreAction::DontCare, vk::AttachmentStoreOp::STORE), (StoreAction::Store, vk::AttachmentStoreOp::STORE), + (StoreAction::Unknown, vk::AttachmentStoreOp::STORE), ] { assert!( ops(load, store).ok() == Some((op, store_op)), @@ -51,7 +52,6 @@ fn load_actions_are_one_to_one_and_plain_store_actions_store() { StoreAction::StoreAndMultisampleResolve, RenderPassKind::Resolve, ), - (StoreAction::Unknown, RenderPassKind::StoreAction), ( StoreAction::CustomSampleDepthStore, RenderPassKind::StoreAction, @@ -521,7 +521,7 @@ mod on_device { d }; let mut store = color(&colors, 0); - store.color_attachments[0].store_action = StoreAction::Unknown; + store.color_attachments[0].store_action = StoreAction::CustomSampleDepthStore; let mut depth_of_color = color(&colors, 0); depth_of_color.depth_attachment.texture = Some(colors.clone()); let mut two_views = color(&colors, 0); diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 740e2d184..bef085dfc 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -243,12 +243,15 @@ macro_rules! degradations { /// The kind announcing `note`. [`PrecisionNote::SnormMinimumKept`], which only a /// profile of `Device::from_queries` records, announces this runtime's kind for the - /// same codes, [`Degradation::SnormMinimumKept`]. + /// same codes, [`Degradation::SnormMinimumKept`]; [`PrecisionNote::DepthDenormals`], + /// which `metal2vulkan-rt`'s depth-stencil state carries, announces + /// [`Degradation::DepthDenormals`]. pub const fn from_precision_note(note: PrecisionNote) -> Degradation { match note { $(PrecisionNote::$note => Degradation::$note,)* PrecisionNote::CappedLodBias => Degradation::CappedLodBias, PrecisionNote::SnormMinimumKept => Degradation::SnormMinimumKept, + PrecisionNote::DepthDenormals => Degradation::DepthDenormals, PrecisionNote::DeviceReconvergence => { Degradation::ImplementationDefinedReconvergence } @@ -2945,6 +2948,10 @@ degradations! { /// device's, where Metal reads `0x7FC00000`. Not bounded: a NaN in a sum makes the sum a /// NaN. NativeFloat8 = "native-float8"; + /// A draw of triangles under a depth bias on `metal2vulkan-rt`, whose render encoder + /// carries the note: the biased depth is the device's. This runtime announces its own + /// depth bias kinds instead. + DeviceDepthBias = "device-depth-bias"; } } diff --git a/crates/metal2vulkan-validation/src/observation_contract/comparison.rs b/crates/metal2vulkan-validation/src/observation_contract/comparison.rs index 106179a0c..e8ebdffaf 100644 --- a/crates/metal2vulkan-validation/src/observation_contract/comparison.rs +++ b/crates/metal2vulkan-validation/src/observation_contract/comparison.rs @@ -343,7 +343,9 @@ pub fn allowance(note: PrecisionNote) -> Allowance { | N::NativeFloat8 | N::CappedLodBias | N::DeviceReconvergence - | N::SnormMinimumKept => Allowance::Unbounded, + | N::SnormMinimumKept + | N::DeviceDepthBias + | N::DepthDenormals => Allowance::Unbounded, } } diff --git a/crates/metal2vulkan-validation/src/observation_contract/comparison/tests.rs b/crates/metal2vulkan-validation/src/observation_contract/comparison/tests.rs index 16e56be02..77df18f61 100644 --- a/crates/metal2vulkan-validation/src/observation_contract/comparison/tests.rs +++ b/crates/metal2vulkan-validation/src/observation_contract/comparison/tests.rs @@ -82,6 +82,8 @@ fn every_precision_note_has_its_table_row() { (N::CappedLodBias, Allowance::Unbounded), (N::DeviceReconvergence, Allowance::Unbounded), (N::SnormMinimumKept, Allowance::Unbounded), + (N::DeviceDepthBias, Allowance::Unbounded), + (N::DepthDenormals, Allowance::Unbounded), ]; for (note, expected) in rows { assert_eq!(allowance(note), expected, "{note:?}"); diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/render.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/render.rs index 77c4c47e6..9adc57c5a 100644 --- a/crates/metal2vulkan-validation/src/replay/new_runtime/render.rs +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/render.rs @@ -603,6 +603,35 @@ impl NewRuntime { "memoryBarrierWithScope:afterStages:beforeStages:" => { self.render(id).encoder.memory_barrier() } + "setDepthBias:slopeScale:clamp:" => { + let float = |at: usize| match arg(call, at)?.as_f64() { + Some(value) => Ok(value as f32), + None => Err(refuse(call, format!("argument {at} is no float"))), + }; + let [bias, slope, clamp] = [float(0)?, float(1)?, float(2)?]; + self.render(id).encoder.set_depth_bias(bias, slope, clamp) + } + "setColorStoreAction:atIndex:" => { + let (action, at) = (store_action(call, uint(call, 0)?)?, uint(call, 1)?); + let at = usize::try_from(at).map_err(|_| refuse(call, "an index past usize"))?; + self.render(id).encoder.set_color_store_action(action, at) + } + "setDepthStoreAction:" => { + let action = store_action(call, uint(call, 0)?)?; + self.render(id).encoder.set_depth_store_action(action) + } + "setStencilStoreAction:" => { + let action = store_action(call, uint(call, 0)?)?; + self.render(id).encoder.set_stencil_store_action(action) + } + "setTriangleFillMode:" => { + let mode = metal(call, uint(call, 0)?)?; + self.render(id).encoder.set_triangle_fill_mode(mode) + } + "setDepthClipMode:" => { + let mode = metal(call, uint(call, 0)?)?; + self.render(id).encoder.set_depth_clip_mode(mode) + } _ => return Err(refuse(call, "not played on a render encoder")), }; match result { diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 37d5129e7..5331224a2 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -1534,6 +1534,8 @@ codec_enum! { CappedLodBias, DeviceReconvergence, SnormMinimumKept, + DeviceDepthBias, + DepthDenormals, } BindingSource { Buffer(f0), Texture(f0), Sampler(f0), CombinedTextureSampler { texture, sampler }, diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 97988fa5f..18b4f06d9 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -72,7 +72,7 @@ pub const SEMANTICS_VERSION: u32 = 2183; /// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag /// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that /// bumps it says what changed; this comment keeps no history. -pub const ARTIFACT_FORMAT_VERSION: u32 = 538; +pub const ARTIFACT_FORMAT_VERSION: u32 = 539; /// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding /// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 44a015f44..21aa7fc3e 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -2430,6 +2430,32 @@ pub enum PrecisionNote { /// Validation derives no tolerance from it: a difference stays a mismatch, which the note /// explains. SnormMinimumKept, + /// A draw of triangles under a depth bias (`setDepthBias:slopeScale:clamp:` with a bias or a + /// slope scale other than 0): the slope measure, and a fixed-point attachment's unit, are the + /// device's; Apple states neither. Vulkan biases by `m × slopeScale + r × depthBias` ("Depth + /// Bias"), where the maximum depth slope `m` is the device's (exact, or the larger of the two + /// derivatives' magnitudes), and the unit `r` is `2^(e - n)` of the primitive's largest depth + /// exponent for a float depth attachment and the device's for a fixed-point one (at most + /// `2 × 2^-n`); a biased depth past the viewport's depth range is undefined there ("Depth + /// Clamping and Range Adjustment"). Static per operation: no pipeline stage records it; + /// `metal2vulkan-rt`'s render encoder carries it (`RenderCommandEncoder::DEPTH_BIAS_NOTE`). + /// + /// Validation derives no tolerance from it: a difference stays a mismatch, which the note + /// explains. + DeviceDepthBias, + /// A depth test or depth write of a 32-bit float depth (a depth-stencil state that compares by + /// other than `Always` or writes): a denormal depth is the device's. Every driver measured but + /// MoltenVK on an Apple M4 compares a denormal depth otherwise than Metal, as zero (a positive + /// one) or below zero (a negative one), where Metal compares a positive one above zero and a + /// negative one not below it; and RADV and ANV store a denormal a GPU write gives a depth image + /// as a zero, where Metal keeps it. Static per operation: no pipeline stage records it; + /// `metal2vulkan-rt`'s depth-stencil state carries it + /// (`DepthStencilState::precision_note`). `metal2vulkan-runtime` announces the same + /// difference as its `depth-denormals` kind, which this note announces too. + /// + /// Validation derives no tolerance from it: a difference stays a mismatch, which the note + /// explains. + DepthDenormals, } /// The math mode of an entry's module, which decides, on a device whose `float` functions are diff --git a/crates/metal2vulkan/src/tests/fast_paths.rs b/crates/metal2vulkan/src/tests/fast_paths.rs index 8ea81f6c5..0c4c3b193 100644 --- a/crates/metal2vulkan/src/tests/fast_paths.rs +++ b/crates/metal2vulkan/src/tests/fast_paths.rs @@ -231,6 +231,8 @@ fn notes() -> Vec<(&'static str, Ledger)> { UnorderedFetchWithinDraw, CappedLodBias, SnormMinimumKept, + DeviceDepthBias, + DepthDenormals, ], } } diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index bafc6edae..14531d632 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -43,6 +43,7 @@ assoc-const metal2vulkan-air::ir::BinOp::ALL pub const ALL: [BinOp; 18] assoc-const metal2vulkan-air::ir::FloatPredicate::ALL pub const ALL: [FloatPredicate; 16] assoc-const metal2vulkan-air::ir::IntPredicate::ALL pub const ALL: [IntPredicate; 10] assoc-const metal2vulkan-air::metal::DataType::ALL pub const ALL: [DataType; 17] +assoc-const metal2vulkan-rt::RenderCommandEncoder::DEPTH_BIAS_NOTE pub const DEPTH_BIAS_NOTE: PrecisionNote assoc-const metal2vulkan-rt::ResourceUsage::READ pub const READ: ResourceUsage assoc-const metal2vulkan-rt::ResourceUsage::SAMPLE pub const SAMPLE: ResourceUsage assoc-const metal2vulkan-rt::ResourceUsage::WRITE pub const WRITE: ResourceUsage @@ -571,6 +572,7 @@ assoc-const-value metal2vulkan-air::ir::BinOp::ALL [BinOp::Add, BinOp::Sub, BinO assoc-const-value metal2vulkan-air::ir::FloatPredicate::ALL [FloatPredicate::False, FloatPredicate::Oeq, FloatPredicate::Ogt, FloatPredicate::Oge, FloatPredicate::Olt, FloatPredicate::Ole, FloatPredicate::One, FloatPredicate::Ord, FloatPredicate::Uno, FloatPredicate::Ueq, FloatPredicate::Ugt, FloatPredicate::Uge, FloatPredicate::Ult, FloatPredicate::Ule, FloatPredicate::Une, FloatPredicate::True] assoc-const-value metal2vulkan-air::ir::IntPredicate::ALL [IntPredicate::Eq, IntPredicate::Ne, IntPredicate::Ugt, IntPredicate::Uge, IntPredicate::Ult, IntPredicate::Ule, IntPredicate::Sgt, IntPredicate::Sge, IntPredicate::Slt, IntPredicate::Sle] assoc-const-value metal2vulkan-air::metal::DataType::ALL [DataType::Float32, DataType::Float16, DataType::BFloat16, DataType::Int2, DataType::Int4, DataType::Int8, DataType::Int16, DataType::Int32, DataType::UInt2, DataType::UInt4, DataType::UInt8, DataType::UInt16, DataType::UInt32, DataType::Fp4E2M1, DataType::Fp8E4M3, DataType::Fp8E5M2, DataType::Fp8UE8M0] +assoc-const-value metal2vulkan-rt::RenderCommandEncoder::DEPTH_BIAS_NOTE PrecisionNote::DeviceDepthBias assoc-const-value metal2vulkan-rt::ResourceUsage::READ ResourceUsage(1) assoc-const-value metal2vulkan-rt::ResourceUsage::SAMPLE ResourceUsage(4) assoc-const-value metal2vulkan-rt::ResourceUsage::WRITE ResourceUsage(2) @@ -6224,6 +6226,7 @@ macro-decl metal2vulkan-air::ir::TypeId ir_id! TypeId macro-decl metal2vulkan-air::metal::DataType metal_enum! DataType macro-decl metal2vulkan-rt::CompareFunction metal_enum! CompareFunction macro-decl metal2vulkan-rt::CullMode metal_enum! CullMode +macro-decl metal2vulkan-rt::DepthClipMode metal_enum! DepthClipMode macro-decl metal2vulkan-rt::IndexType metal_enum! IndexType macro-decl metal2vulkan-rt::IndexType vk_enum! IndexType macro-decl metal2vulkan-rt::PixelFormat metal_enum! PixelFormat @@ -6239,6 +6242,7 @@ macro-decl metal2vulkan-rt::StencilOperation metal_enum! StencilOperation macro-decl metal2vulkan-rt::TextureSwizzle metal_enum! TextureSwizzle macro-decl metal2vulkan-rt::TextureType metal_enum! TextureType macro-decl metal2vulkan-rt::TextureUsage metal_flags! TextureUsage +macro-decl metal2vulkan-rt::TriangleFillMode metal_enum! TriangleFillMode macro-decl metal2vulkan-rt::Winding metal_enum! Winding macro-decl metal2vulkan-runtime::Degradation degradations! Degradation macro-decl metal2vulkan::metal::ArgumentBuffersTier metal_enum! ArgumentBuffersTier @@ -6473,6 +6477,10 @@ macro-member metal2vulkan-rt::CullMode::CullMode CullMode = "MTLCullMode" macro-member metal2vulkan-rt::CullMode::Front Front = 1, "MTLCullModeFront"; macro-member metal2vulkan-rt::CullMode::None None = 0, "MTLCullModeNone"; macro-member metal2vulkan-rt::CullMode::aliases aliases +macro-member metal2vulkan-rt::DepthClipMode::Clamp Clamp = 1, "MTLDepthClipModeClamp"; +macro-member metal2vulkan-rt::DepthClipMode::Clip Clip = 0, "MTLDepthClipModeClip"; +macro-member metal2vulkan-rt::DepthClipMode::DepthClipMode DepthClipMode = "MTLDepthClipMode" +macro-member metal2vulkan-rt::DepthClipMode::aliases aliases macro-member metal2vulkan-rt::IndexType::IndexType IndexType = "MTLIndexType" macro-member metal2vulkan-rt::IndexType::IndexType IndexType(i32) = "VkIndexType" macro-member metal2vulkan-rt::IndexType::NONE_KHR NONE_KHR = 1000165000, "VK_INDEX_TYPE_NONE_KHR"; @@ -6873,6 +6881,11 @@ macro-member metal2vulkan-rt::TextureUsage::UNKNOWN UNKNOWN = 0x0, "MTLTextureUs macro-member metal2vulkan-rt::TextureUsage::VIDEO VIDEO = 0x8000, "MTLTextureUsageVideo"; macro-member metal2vulkan-rt::TextureUsage::aliases aliases macro-member metal2vulkan-rt::TextureUsage::dropped dropped +macro-member metal2vulkan-rt::TriangleFillMode::Fill Fill = 0, "MTLTriangleFillModeFill"; +macro-member metal2vulkan-rt::TriangleFillMode::Lines Lines = 1, "MTLTriangleFillModeLines"; +macro-member metal2vulkan-rt::TriangleFillMode::Points Points = 2, "MTLTriangleFillModePoints"; +macro-member metal2vulkan-rt::TriangleFillMode::TriangleFillMode TriangleFillMode = "MTLTriangleFillMode" +macro-member metal2vulkan-rt::TriangleFillMode::aliases aliases macro-member metal2vulkan-rt::Winding::Clockwise Clockwise = 0, "MTLWindingClockwise"; macro-member metal2vulkan-rt::Winding::CounterClockwise CounterClockwise = 1, "MTLWindingCounterClockwise"; macro-member metal2vulkan-rt::Winding::Winding Winding = "MTLWinding" @@ -6912,6 +6925,7 @@ macro-member metal2vulkan-runtime::Degradation::DeviceArithmetic DeviceArithmeti macro-member metal2vulkan-runtime::Degradation::DeviceBooleanVisibility DeviceBooleanVisibility = "device-boolean-visibility", Precision, macro-member metal2vulkan-runtime::Degradation::DeviceColorConversion DeviceColorConversion = "device-color-conversion"; macro-member metal2vulkan-runtime::Degradation::DeviceDenormals DeviceDenormals = "device-denormals"; +macro-member metal2vulkan-runtime::Degradation::DeviceDepthBias DeviceDepthBias = "device-depth-bias"; macro-member metal2vulkan-runtime::Degradation::DeviceFilteredMipmaps DeviceFilteredMipmaps = "device-filtered-mipmaps", Precision, macro-member metal2vulkan-runtime::Degradation::DeviceInterpolation DeviceInterpolation = "device-interpolation"; macro-member metal2vulkan-runtime::Degradation::DeviceInterpolationOffset DeviceInterpolationOffset = "device-interpolation-offset"; @@ -9059,7 +9073,7 @@ macro-template metal2vulkan-rt::vk_bit! ( $(#[$meta:meta])* $name:ident($raw:ty) macro-template metal2vulkan-rt::vk_enum! ( $(#[$meta:meta])* $name:ident($raw:ty) = $vk:literal { $($konst:ident = $value:literal, $vkname:literal;)* } aliases { $($alias:literal => $target:ident;)* } ) => { $(#[$meta])* #[repr(transparent)] #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", serde(transparent))] pub struct $name($raw); impl $name { $( #[doc = concat!("`", $vkname, "`.")] pub const $konst: $name = $name($value); )* pub const VK_NAME: &'static str = $vk; pub const KNOWN: &'static [$name] = &[$($name::$konst),*]; const NAMES: &'static [($name, &'static str)] = &[$(($name::$konst, $vkname)),*]; const ALIASES: &'static [(&'static str, $name)] = &[$(($alias, $name::$target)),*]; pub const fn from_raw(raw: $raw) -> $name { $name(raw) } pub const fn as_raw(self) -> $raw { self.0 } pub fn name(self) -> Option<&'static str> { Self::NAMES.iter().find(|(v, _)| *v == self).map(|(_, n)| *n) } pub fn is_known(self) -> bool { self.name().is_some() } pub fn from_name(name: &str) -> Option<$name> { Self::NAMES .iter() .find(|(_, n)| *n == name) .map(|(v, _)| *v) .or_else(|| Self::ALIASES.iter().find(|(n, _)| *n == name).map(|(_, v)| *v)) } } impl ::std::fmt::Debug for $name { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match self.name() { Some(name) => f.write_str(name), None => write!(f, "{}({})", $vk, self.0), } } } }; macro-template metal2vulkan-rt::vk_flags! ( $(#[$meta:meta])* $name:ident($raw:ty) = $vk:literal { $($konst:ident = $value:literal, $vkname:literal;)* } aliases { $($alias:literal => $target:ident;)* } ) => { $(#[$meta])* #[repr(transparent)] #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", serde(transparent))] pub struct $name($raw); impl $name { $( #[doc = concat!("`", $vkname, "`.")] pub const $konst: $name = $name($value); )* pub const VK_NAME: &'static str = $vk; pub const KNOWN: &'static [($name, &'static str)] = &[$(($name::$konst, $vkname)),*]; const ALIASES: &'static [(&'static str, $name)] = &[$(($alias, $name::$target)),*]; pub const fn empty() -> $name { $name(0) } pub const fn from_raw(raw: $raw) -> $name { $name(raw) } pub const fn as_raw(self) -> $raw { self.0 } pub const fn is_empty(self) -> bool { self.0 == 0 } pub const fn contains(self, other: $name) -> bool { self.0 & other.0 == other.0 } pub const fn intersects(self, other: $name) -> bool { self.0 & other.0 != 0 } pub const fn union(self, other: $name) -> $name { $name(self.0 | other.0) } pub const fn intersection(self, other: $name) -> $name { $name(self.0 & other.0) } pub const fn difference(self, other: $name) -> $name { $name(self.0 & !other.0) } pub const fn known_bits() -> $name { let mut bits: $raw = 0; let mut i = 0; while i < Self::KNOWN.len() { let v = Self::KNOWN[i].0 .0; if v.count_ones() == 1 { bits |= v; } i += 1; } $name(bits) } pub fn name(self) -> Option<&'static str> { Self::KNOWN.iter().find(|(v, _)| *v == self).map(|(_, n)| *n) } pub fn from_name(name: &str) -> Option<$name> { Self::KNOWN .iter() .find(|(_, n)| *n == name) .map(|(v, _)| *v) .or_else(|| Self::ALIASES.iter().find(|(n, _)| *n == name).map(|(_, v)| *v)) } } impl ::std::ops::BitOr for $name { type Output = $name; fn bitor(self, rhs: $name) -> $name { self.union(rhs) } } impl ::std::ops::BitOrAssign for $name { fn bitor_assign(&mut self, rhs: $name) { *self = self.union(rhs); } } impl ::std::ops::BitAnd for $name { type Output = $name; fn bitand(self, rhs: $name) -> $name { self.intersection(rhs) } } impl ::std::ops::BitAndAssign for $name { fn bitand_assign(&mut self, rhs: $name) { *self = self.intersection(rhs); } } impl ::std::fmt::Debug for $name { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { if let Some(name) = self.name() { return f.write_str(name); } let mut rest = self.0; let mut first = true; for (v, n) in Self::KNOWN { if v.0.count_ones() == 1 && rest & v.0 != 0 { if !first { f.write_str(" | ")?; } f.write_str(n)?; rest &= !v.0; first = false; } } if rest != 0 || first { if !first { f.write_str(" | ")?; } write!(f, "{:#x}", rest)?; } Ok(()) } } }; macro-template metal2vulkan-runtime::commands! ( v1_0 { $($v0:ident $f0:ident $n0:literal ($($a0:ident: $t0:ty),*) $(-> $r0:ty)?;)* } v1_3 { $($v3:ident $f3:ident $n3:literal ($($a3:ident: $t3:ty),*) $(-> $r3:ty)?;)* } extension { $($ve:ident $fe:ident $ne:literal ($($ae:ident: $te:ty),*) $(-> $re:ty)?;)* } ) => { #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(crate) enum Command { $($v0,)* $($v3,)* $($ve,)* } impl Command { pub(crate) const ALL: &'static [Command] = &[ $(Command::$v0,)* $(Command::$v3,)* $(Command::$ve,)* ]; pub(crate) const COUNT: usize = Command::ALL.len(); pub(crate) fn name(self) -> &'static CStr { match self { $(Command::$v0 => $n0,)* $(Command::$v3 => $n3,)* $(Command::$ve => $ne,)* } } } #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct CommandsRecorded { $( #[doc = concat!("The calls of `", stringify!($v0), "`.")] pub $f0: u64, )* $( #[doc = concat!("The calls of `", stringify!($v3), "`.")] pub $f3: u64, )* $( #[doc = concat!("The calls of `", stringify!($ve), "`.")] pub $fe: u64, )* } impl CommandsRecorded { fn read(shards: &[Shard; SHARDS + 1]) -> CommandsRecorded { let sum = |command: Command| { let counts = shards.iter().map(|shard| &shard.0[command as usize]); counts.map(|count| count.load(Ordering::Relaxed)).sum() }; CommandsRecorded { $($f0: sum(Command::$v0),)* $($f3: sum(Command::$v3),)* $($fe: sum(Command::$ve),)* } } } struct Real { $($f0: [AtomicPtr; SLOTS],)* $($f3: [AtomicPtr; SLOTS],)* $($fe: [AtomicPtr; SLOTS],)* } static REAL: Real = Real { $($f0: [const { AtomicPtr::new(std::ptr::null_mut()) }; SLOTS],)* $($f3: [const { AtomicPtr::new(std::ptr::null_mut()) }; SLOTS],)* $($fe: [const { AtomicPtr::new(std::ptr::null_mut()) }; SLOTS],)* }; commands!(@thunks $($v0 $f0 $n0 ($($a0: $t0),*) $(-> $r0)?;)*); commands!(@thunks $($v3 $f3 $n3 ($($a3: $t3),*) $(-> $r3)?;)*); commands!(@thunks $($ve $fe $ne ($($ae: $te),*) $(-> $re)?;)*); pub(super) fn thunk(command: Command) -> *const c_void { match command { $(Command::$v0 => $f0:: as *const c_void,)* $(Command::$v3 => $f3:: as *const c_void,)* $(Command::$ve => $fe:: as *const c_void,)* } } pub(super) fn store(index: usize, command: Command, real: *const c_void) { let real = real.cast_mut(); match command { $(Command::$v0 => REAL.$f0[index].store(real, Ordering::Release),)* $(Command::$v3 => REAL.$f3[index].store(real, Ordering::Release),)* $(Command::$ve => REAL.$fe[index].store(real, Ordering::Release),)* } } pub(super) fn real(index: usize, command: Command) -> *const c_void { let real = match command { $(Command::$v0 => REAL.$f0[index].load(Ordering::Acquire),)* $(Command::$v3 => REAL.$f3[index].load(Ordering::Acquire),)* $(Command::$ve => REAL.$fe[index].load(Ordering::Acquire),)* }; real.cast_const() } pub(super) fn clear(index: usize) { $(REAL.$f0[index].store(std::ptr::null_mut(), Ordering::Release);)* $(REAL.$f3[index].store(std::ptr::null_mut(), Ordering::Release);)* $(REAL.$fe[index].store(std::ptr::null_mut(), Ordering::Release);)* } pub(super) fn route_tables( v1_0: &mut ash::DeviceFnV1_0, v1_3: &mut ash::DeviceFnV1_3, ) { $( store(S, Command::$v0, v1_0.$f0 as *const c_void); v1_0.$f0 = $f0::; )* $( store(S, Command::$v3, v1_3.$f3 as *const c_void); v1_3.$f3 = $f3::; )* } }; (@thunks $($v:ident $f:ident $n:literal ($($a:ident: $t:ty),*) $(-> $r:ty)?;)*) => { $( unsafe extern "system" fn $f( command_buffer: vk::CommandBuffer, $($a: $t,)* ) $(-> $r)? { let at = held(); crate::shards::add(at, &COUNTS[S][at].0[Command::$v as usize], 1); let real = REAL.$f[S].load(Ordering::Acquire); if real.is_null() { missing($n); } unsafe { let real = std::mem::transmute::< *mut c_void, unsafe extern "system" fn(vk::CommandBuffer, $($t,)*) $(-> $r)?, >(real); real(command_buffer, $($a,)*) } } )* }; -macro-template metal2vulkan-runtime::degradations! ( runtime { $( $(#[doc = $doc:literal])* $kind:ident = $code:literal, $category:ident, $cost:literal; )* } notes { $( $(#[doc = $note_doc:literal])* $note:ident = $note_code:literal; )* } ) => { #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Degradation { $($(#[doc = $doc])* $kind,)* $( #[doc = concat!( "A pipeline stage records [`PrecisionNote::", stringify!($note), "`]." )] $(#[doc = $note_doc])* $note, )* } impl Degradation { pub const ALL: &'static [Degradation] = &[$(Degradation::$kind,)* $(Degradation::$note,)*]; pub const fn code(self) -> &'static str { match self { $(Degradation::$kind => concat!("metal2vulkan-degrade-", $code),)* $(Degradation::$note => concat!("metal2vulkan-degrade-", $note_code),)* } } pub const fn category(self) -> DegradationCategory { match self { $(Degradation::$kind => DegradationCategory::$category,)* $(Degradation::$note => DegradationCategory::Precision,)* } } pub const fn cost(self) -> &'static str { match self { $(Degradation::$kind => $cost,)* $(Degradation::$note => NOTE_COST,)* } } pub const fn precision_note(self) -> Option { match self { $(Degradation::$kind => None,)* $(Degradation::$note => Some(PrecisionNote::$note),)* } } pub const fn from_precision_note(note: PrecisionNote) -> Degradation { match note { $(PrecisionNote::$note => Degradation::$note,)* PrecisionNote::CappedLodBias => Degradation::CappedLodBias, PrecisionNote::SnormMinimumKept => Degradation::SnormMinimumKept, PrecisionNote::DeviceReconvergence => { Degradation::ImplementationDefinedReconvergence } } } } }; +macro-template metal2vulkan-runtime::degradations! ( runtime { $( $(#[doc = $doc:literal])* $kind:ident = $code:literal, $category:ident, $cost:literal; )* } notes { $( $(#[doc = $note_doc:literal])* $note:ident = $note_code:literal; )* } ) => { #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Degradation { $($(#[doc = $doc])* $kind,)* $( #[doc = concat!( "A pipeline stage records [`PrecisionNote::", stringify!($note), "`]." )] $(#[doc = $note_doc])* $note, )* } impl Degradation { pub const ALL: &'static [Degradation] = &[$(Degradation::$kind,)* $(Degradation::$note,)*]; pub const fn code(self) -> &'static str { match self { $(Degradation::$kind => concat!("metal2vulkan-degrade-", $code),)* $(Degradation::$note => concat!("metal2vulkan-degrade-", $note_code),)* } } pub const fn category(self) -> DegradationCategory { match self { $(Degradation::$kind => DegradationCategory::$category,)* $(Degradation::$note => DegradationCategory::Precision,)* } } pub const fn cost(self) -> &'static str { match self { $(Degradation::$kind => $cost,)* $(Degradation::$note => NOTE_COST,)* } } pub const fn precision_note(self) -> Option { match self { $(Degradation::$kind => None,)* $(Degradation::$note => Some(PrecisionNote::$note),)* } } pub const fn from_precision_note(note: PrecisionNote) -> Degradation { match note { $(PrecisionNote::$note => Degradation::$note,)* PrecisionNote::CappedLodBias => Degradation::CappedLodBias, PrecisionNote::SnormMinimumKept => Degradation::SnormMinimumKept, PrecisionNote::DepthDenormals => Degradation::DepthDenormals, PrecisionNote::DeviceReconvergence => { Degradation::ImplementationDefinedReconvergence } } } } }; macro-template metal2vulkan-runtime::exposures! ($($exposure:expr => [$($feature:ident),* $(,)?];)*) => { impl VkFeature { pub const ALL: &'static [VkFeature] = &[$($(VkFeature::$feature),*),*]; pub fn exposure(self) -> Exposure { match self { $($(VkFeature::$feature)|* => $exposure,)* } } } }; macro-template metal2vulkan-runtime::flag_set! ( $(#[$doc:meta])* $name:ident { $($(#[$fdoc:meta])* $flag:ident = $bit:expr),* $(,)? } $(#[$all:meta])* ALL ) => { $(#[$doc])* #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct $name(u8); impl $name { pub const NONE: $name = $name(0); $($(#[$fdoc])* pub const $flag: $name = $name($bit);)* $(#[$all])* pub const ALL: &'static [($name, &'static str)] = &[$(($name::$flag, stringify!($flag))),*]; pub const fn union(self, other: $name) -> $name { $name(self.0 | other.0) } pub const fn contains(self, other: $name) -> bool { self.0 & other.0 == other.0 } #[cfg(test)] pub const fn bits(self) -> u8 { self.0 } } }; macro-template metal2vulkan-runtime::id_type! ($(#[$doc:meta])* $name:ident) => { $(#[$doc])* #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct $name(pub u32); impl $name { pub const fn new(index: u32) -> $name { $name(index) } pub const fn index(self) -> usize { self.0 as usize } } }; @@ -9512,6 +9526,7 @@ method metal2vulkan-rt::ComputePipelineState::precision_notes pub fn precision_n method metal2vulkan-rt::Counters::gauges pub fn gauges(&self) -> Gauges method metal2vulkan-rt::Counters::metrics pub fn metrics(&self) -> Metrics method metal2vulkan-rt::DepthStencilState::descriptor pub fn descriptor(&self) -> &DepthStencilDescriptor +method metal2vulkan-rt::DepthStencilState::precision_note pub fn precision_note(&self) -> Option method metal2vulkan-rt::Device::counters pub fn counters(&self) -> Counters method metal2vulkan-rt::Device::extensions pub fn extensions(&self) -> &[CString] method metal2vulkan-rt::Device::features pub fn features(&self) -> &[ConsumerFeature] @@ -9578,8 +9593,12 @@ method metal2vulkan-rt::RenderCommandEncoder::draw_primitives pub fn draw_primit method metal2vulkan-rt::RenderCommandEncoder::end_encoding pub fn end_encoding(mut self) method metal2vulkan-rt::RenderCommandEncoder::memory_barrier pub fn memory_barrier(&mut self) -> Result<(), Error> method metal2vulkan-rt::RenderCommandEncoder::set_blend_color pub fn set_blend_color(&mut self, red: f32, green: f32, blue: f32, alpha: f32) +method metal2vulkan-rt::RenderCommandEncoder::set_color_store_action pub fn set_color_store_action(&mut self, action: StoreAction, index: usize) -> Result<(), Error> method metal2vulkan-rt::RenderCommandEncoder::set_cull_mode pub fn set_cull_mode(&mut self, mode: CullMode) +method metal2vulkan-rt::RenderCommandEncoder::set_depth_bias pub fn set_depth_bias(&mut self, depth_bias: f32, slope_scale: f32, clamp: f32) -> Result<(), Error> +method metal2vulkan-rt::RenderCommandEncoder::set_depth_clip_mode pub fn set_depth_clip_mode(&mut self, mode: DepthClipMode) -> Result<(), Error> method metal2vulkan-rt::RenderCommandEncoder::set_depth_stencil_state pub fn set_depth_stencil_state(&mut self, state: Option<&DepthStencilState>) -> Result<(), Error> +method metal2vulkan-rt::RenderCommandEncoder::set_depth_store_action pub fn set_depth_store_action(&mut self, action: StoreAction) -> Result<(), Error> method metal2vulkan-rt::RenderCommandEncoder::set_fragment_buffer pub fn set_fragment_buffer(&mut self, buffer: Option<&Buffer>, offset: u64, index: u32) -> Result<(), Error> method metal2vulkan-rt::RenderCommandEncoder::set_fragment_buffer_offset pub fn set_fragment_buffer_offset(&mut self, offset: u64, index: u32) -> Result<(), Error> method metal2vulkan-rt::RenderCommandEncoder::set_fragment_bytes pub fn set_fragment_bytes(&mut self, bytes: &[u8], index: u32) -> Result<(), Error> @@ -9588,14 +9607,18 @@ method metal2vulkan-rt::RenderCommandEncoder::set_fragment_texture pub fn set_fr method metal2vulkan-rt::RenderCommandEncoder::set_front_facing_winding pub fn set_front_facing_winding(&mut self, winding: Winding) method metal2vulkan-rt::RenderCommandEncoder::set_render_pipeline_state pub fn set_render_pipeline_state(&mut self, state: &RenderPipelineState) -> Result<(), Error> method metal2vulkan-rt::RenderCommandEncoder::set_scissor_rect pub fn set_scissor_rect(&mut self, rect: ScissorRect) +method metal2vulkan-rt::RenderCommandEncoder::set_scissor_rects pub fn set_scissor_rects(&mut self, rects: &[ScissorRect]) -> Result<(), Error> method metal2vulkan-rt::RenderCommandEncoder::set_stencil_front_back_reference_value pub fn set_stencil_front_back_reference_value(&mut self, front: u32, back: u32) method metal2vulkan-rt::RenderCommandEncoder::set_stencil_reference_value pub fn set_stencil_reference_value(&mut self, value: u32) +method metal2vulkan-rt::RenderCommandEncoder::set_stencil_store_action pub fn set_stencil_store_action(&mut self, action: StoreAction) -> Result<(), Error> +method metal2vulkan-rt::RenderCommandEncoder::set_triangle_fill_mode pub fn set_triangle_fill_mode(&mut self, mode: TriangleFillMode) -> Result<(), Error> method metal2vulkan-rt::RenderCommandEncoder::set_vertex_buffer pub fn set_vertex_buffer(&mut self, buffer: Option<&Buffer>, offset: u64, index: u32) -> Result<(), Error> method metal2vulkan-rt::RenderCommandEncoder::set_vertex_buffer_offset pub fn set_vertex_buffer_offset(&mut self, offset: u64, index: u32) -> Result<(), Error> method metal2vulkan-rt::RenderCommandEncoder::set_vertex_bytes pub fn set_vertex_bytes(&mut self, bytes: &[u8], index: u32) -> Result<(), Error> method metal2vulkan-rt::RenderCommandEncoder::set_vertex_sampler_state pub fn set_vertex_sampler_state(&mut self, sampler: Option<&SamplerState>, index: u32) -> Result<(), Error> method metal2vulkan-rt::RenderCommandEncoder::set_vertex_texture pub fn set_vertex_texture(&mut self, texture: Option<&Texture>, index: u32) -> Result<(), Error> method metal2vulkan-rt::RenderCommandEncoder::set_viewport pub fn set_viewport(&mut self, viewport: Viewport) -> Result<(), Error> +method metal2vulkan-rt::RenderCommandEncoder::set_viewports pub fn set_viewports(&mut self, viewports: &[Viewport]) -> Result<(), Error> method metal2vulkan-rt::RenderCommandEncoder::update_fence pub fn update_fence(&mut self, fence: &Fence) -> Result<(), Error> method metal2vulkan-rt::RenderCommandEncoder::wait_for_fence pub fn wait_for_fence(&mut self, fence: &Fence) -> Result<(), Error> method metal2vulkan-rt::RenderPipelineDescriptor::fragment_writes_depth_unattached pub fn fragment_writes_depth_unattached(&self, budget: &crate::Budget, entries: &StageEntries) -> Result @@ -13597,10 +13620,13 @@ variant metal2vulkan-rt::DispatchType::Concurrent Concurrent variant metal2vulkan-rt::DispatchType::Serial Serial variant metal2vulkan-rt::DrawKind::AttachmentFormats AttachmentFormats variant metal2vulkan-rt::DrawKind::AttachmentRead AttachmentRead -variant metal2vulkan-rt::DrawKind::DepthTest DepthTest +variant metal2vulkan-rt::DrawKind::DepthBiasClamp DepthBiasClamp +variant metal2vulkan-rt::DrawKind::DepthClamp DepthClamp variant metal2vulkan-rt::DrawKind::DividedBaseInstance DividedBaseInstance +variant metal2vulkan-rt::DrawKind::FillMode FillMode variant metal2vulkan-rt::DrawKind::Points Points variant metal2vulkan-rt::DrawKind::Viewport Viewport +variant metal2vulkan-rt::DrawKind::Viewports Viewports variant metal2vulkan-rt::Error::BelowFloor BelowFloor(BelowFloor) variant metal2vulkan-rt::Error::Limit Limit(Limit) variant metal2vulkan-rt::Error::Loader Loader(ash::LoadingError) @@ -13662,11 +13688,13 @@ variant metal2vulkan-rt::PrecisionNote::ColorAttachmentGroups ColorAttachmentGro variant metal2vulkan-rt::PrecisionNote::ComputedSampleDepth ComputedSampleDepth variant metal2vulkan-rt::PrecisionNote::CoverageReadsRoundedAlpha CoverageReadsRoundedAlpha variant metal2vulkan-rt::PrecisionNote::CubeGradientFootprint CubeGradientFootprint +variant metal2vulkan-rt::PrecisionNote::DepthDenormals DepthDenormals variant metal2vulkan-rt::PrecisionNote::DeviceAlphaCoverage DeviceAlphaCoverage variant metal2vulkan-rt::PrecisionNote::DeviceAnisotropicFilter DeviceAnisotropicFilter variant metal2vulkan-rt::PrecisionNote::DeviceArithmetic DeviceArithmetic variant metal2vulkan-rt::PrecisionNote::DeviceColorConversion DeviceColorConversion variant metal2vulkan-rt::PrecisionNote::DeviceDenormals DeviceDenormals +variant metal2vulkan-rt::PrecisionNote::DeviceDepthBias DeviceDepthBias variant metal2vulkan-rt::PrecisionNote::DeviceInterpolation DeviceInterpolation variant metal2vulkan-rt::PrecisionNote::DeviceInterpolationOffset DeviceInterpolationOffset variant metal2vulkan-rt::PrecisionNote::DeviceNanEncoding DeviceNanEncoding @@ -16597,11 +16625,13 @@ variant metal2vulkan::pipeline::PrecisionNote::ColorAttachmentGroups ColorAttach variant metal2vulkan::pipeline::PrecisionNote::ComputedSampleDepth ComputedSampleDepth variant metal2vulkan::pipeline::PrecisionNote::CoverageReadsRoundedAlpha CoverageReadsRoundedAlpha variant metal2vulkan::pipeline::PrecisionNote::CubeGradientFootprint CubeGradientFootprint +variant metal2vulkan::pipeline::PrecisionNote::DepthDenormals DepthDenormals variant metal2vulkan::pipeline::PrecisionNote::DeviceAlphaCoverage DeviceAlphaCoverage variant metal2vulkan::pipeline::PrecisionNote::DeviceAnisotropicFilter DeviceAnisotropicFilter variant metal2vulkan::pipeline::PrecisionNote::DeviceArithmetic DeviceArithmetic variant metal2vulkan::pipeline::PrecisionNote::DeviceColorConversion DeviceColorConversion variant metal2vulkan::pipeline::PrecisionNote::DeviceDenormals DeviceDenormals +variant metal2vulkan::pipeline::PrecisionNote::DeviceDepthBias DeviceDepthBias variant metal2vulkan::pipeline::PrecisionNote::DeviceInterpolation DeviceInterpolation variant metal2vulkan::pipeline::PrecisionNote::DeviceInterpolationOffset DeviceInterpolationOffset variant metal2vulkan::pipeline::PrecisionNote::DeviceNanEncoding DeviceNanEncoding diff --git a/docs/API.md b/docs/API.md index 508778d78..49454d463 100644 --- a/docs/API.md +++ b/docs/API.md @@ -4335,6 +4335,9 @@ bound. measured but MoltenVK on an Apple M4). Cost: a denormal depth may read, sample and copy out as a zero, or the depth test may compare it as zero (a positive one) or below zero (a negative one), where Metal keeps it and compares a positive one above zero and a negative one not below it. + On `metal2vulkan-rt` it is the static note `PrecisionNote::DepthDenormals` of every + depth-stencil state that tests or writes depth (`DepthStencilState::precision_note`), on every + device, with no driver fact. - `metal2vulkan-degrade-signed-depth-test` (precision). `SignedDepthTest`: A depth test that may compare a negative value or a NaN stored in the 32-bit float depth of a render target as it is, or a pass with depth writes that may store such a value with its sign, where Metal's test compares @@ -5476,6 +5479,15 @@ bound. reads them, and records none. An `air.convert` from `f8e4m3fn` or `f8e5m2` and a simdgroup-matrix cell of those formats widen through the same type there and record none: their formats are OCP's own, and Metal on Apple M3 does not compile them. +- `metal2vulkan-degrade-device-depth-bias` (precision). `PrecisionNote::DeviceDepthBias`: A draw + of triangles under a depth bias (`setDepthBias:slopeScale:clamp:` with a bias or a slope scale + other than 0) on `metal2vulkan-rt`, whose render encoder carries it as a static note + (`RenderCommandEncoder::DEPTH_BIAS_NOTE`): the biased depth is the device's. Vulkan biases by + `m × slopeScale + r × depthBias`, where the maximum depth slope `m` is the device's (exact, or + the larger of the two derivatives' magnitudes) and the unit `r` is `2^(e - n)` of the primitive's + largest depth exponent for a float depth attachment and the device's for a fixed-point one (at + most `2 × 2^-n`). Apple's documentation states neither the slope measure nor the unit. A draw of + lines is not biased, as Metal biases triangles alone. - `metal2vulkan-degrade-device-pack-conversion` (precision). `PrecisionNote::DevicePackConversion`: Native device maths (a conversion): `air.pack` or `air.unpack` of a normalized format is the device's: `GLSL.std.450`'s `Pack`/`Unpack` `Unorm4x8`, `Snorm4x8`, `Unorm2x16` and `Snorm2x16`, diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index c68834ee7..acb10715a 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -712,8 +712,8 @@ Columns: | `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 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) | `-` | +| `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 depth attachment, each a level of a 2D texture of one sample, with no resolve and a clear depth of 1, none naming two textures for its depth and stencil; 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 through one viewport Vulkan's is, with pipeline states of their pass's formats, under depth biases with no clamp, filled and clipped; each other kind is built when a replay stream draws one), and device for [`DrawKind::DividedBaseInstance`] (a device that does not report `supportsNonZeroFirstInstance` | 9: `crates/metal2vulkan-rt/src/render_encoder.rs (attachment_reads)`, `crates/metal2vulkan-rt/src/render_encoder.rs (draw)` (+7) | `-` | ## Appendix: every site @@ -1292,5 +1292,5 @@ Each refusal's sites, with the function that builds it. - `rt:Gap::FenceOtherQueue`: `crates/metal2vulkan-rt/src/fence.rs (used_on)` - `rt:Gap::TextureView`: `crates/metal2vulkan-rt/src/texture.rs (new_texture_view)` - `rt:Gap::RenderPass`: `crates/metal2vulkan-rt/src/pass.rs (check)`; `crates/metal2vulkan-rt/src/pass.rs (ops)`; `crates/metal2vulkan-rt/src/texture.rs (attachment)` -- `rt:Gap::Draw`: `crates/metal2vulkan-rt/src/render_encoder.rs (attachment_reads)`; `crates/metal2vulkan-rt/src/render_encoder.rs (draw)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_viewport)`; `crates/metal2vulkan-rt/src/render_encoder.rs (shadow_copies)` +- `rt:Gap::Draw`: `crates/metal2vulkan-rt/src/render_encoder.rs (attachment_reads)`; `crates/metal2vulkan-rt/src/render_encoder.rs (draw)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_depth_bias)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_depth_clip_mode)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_scissor_rects)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_triangle_fill_mode)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_viewport)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_viewports)`; `crates/metal2vulkan-rt/src/render_encoder.rs (shadow_copies)`