From 99e5d42debca56a042540c763fcad7e4e208af46 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Fri, 20 Nov 2026 23:00:28 -0800 Subject: [PATCH] rt: several viewports and scissor rectangles, and the viewport index, through the with-count dynamic states setViewports:count: and setScissorRects:count: refused any count but 1 (DrawKind::Viewports). They now take 1 to 16 each, and every draw records them with their count (vkCmdSetViewportWithCount, vkCmdSetScissorWithCount, core in Vulkan 1.3). VIEWPORT_WITH_COUNT and SCISSOR_WITH_COUNT replace VIEWPORT and SCISSOR in every pipeline's dynamic states, whose viewport state counts become 0, so no pipeline is made for a count. Vulkan takes as many scissors as viewports. Each viewport's scissor follows the deleted runtime's rule (render_state.rs's vk_scissors at 5d725aeec7^): the rectangle of its index, the one rectangle where one is set, and none past the rectangles set where several are, each cut to the pixels its viewport covers. A draw's attachment-read area is the union of what it covers through the viewports it reaches: every viewport set for a vertex function that writes [[viewport_array_index]] (GraphicsState::writes_viewport_index, now Draws:: selects_viewport), and viewport 0 for any other. A vertex function's [[viewport_array_index]] is the translator's one form at the floor: its ViewportIndex output, written 0 at or past the encoder's count (RuntimeFact::ViewportCount), which the draw now pushes (PushField::ViewportCount -> FieldValue::ViewportCount, refilled when the count changes). Its fragment function reads the index as written. An index that is not one value across a primitive stays the translator's refusal at creation, needing geometryShader, which device creation does not enable. Out of range: none or more than 16 is DrawKind::Viewports. Floor: multiViewport and shaderOutputViewportIndex join REQUIRED, and the translator is told. The venue dumps report both true on every venue: m3-max-48727, 48728, 48729, 48730, 48731, 48736, 48737 and 61508. shaderOutputViewportIndex is also true in the probes 61359 to 61362 and 61366. tests/floor.rs, the README floor table, RUNTIME_FLOOR and profiles/runtime-floor.json add them. The translator's tests that read runtime-floor as a device without the viewport index now take it below the floor: engine_selected_indices (the raw index alone without multiViewport; the zero indices without shaderOutputLayer and shaderOutputViewportIndex) and engine_stage_io_tail (the floor declares Layer and ViewportIndex; the zero index below it). runtime-floor joins the stems whose fragment ViewportIndex needs MultiViewport. Also, missed in a5fac6fa9b: the README's pipeline bullet names the depth clip and triangle fill modes among what a VkPipeline bakes. Conformance: render-state-boxes leaves known-gaps-rt.tsv; CONFORMANCE-COVERAGE.md regenerated. Docs: README (encoder bullets, floor table, refusal list), REFUSALS.md (Viewports' doc), the encoder's built list. Tests: tests/viewports.rs. rt6_select draws through the viewport of its instance, two viewports (the halves) and two scissors (the whole target and its top half). Instance 0 fills the left half, instance 1 the right half's top, and instance 2, past the count, draws through viewport 0, its fragment reading 2. No pipeline is made, and none or 17 viewports or rectangles are Viewports. draw.rs drops its two-viewport refusal. floor.rs adds the two missing cases, and the translator sees shaderOutputViewportIndex. --- .../known-gaps-rt.tsv | 1 - crates/metal2vulkan-runtime/README.md | 23 +- crates/metal2vulkan-runtime/src/encoder.rs | 3 +- crates/metal2vulkan-runtime/src/error.rs | 4 +- crates/metal2vulkan-runtime/src/floor.rs | 5 + crates/metal2vulkan-runtime/src/pipeline.rs | 4 + crates/metal2vulkan-runtime/src/render.rs | 24 +- .../src/render_encoder.rs | 222 ++++++++++++------ crates/metal2vulkan-runtime/src/tests/draw.rs | 9 +- .../metal2vulkan-runtime/src/tests/floor.rs | 17 +- crates/metal2vulkan-runtime/src/tests/mod.rs | 1 + .../src/tests/viewports.rs | 118 ++++++++++ .../profiles/runtime-floor.json | 6 +- .../src/tests/engine_stage_io_tail.rs | 15 +- docs/REFUSALS.md | 8 +- .../regen_device_profiles.py | 5 +- 16 files changed, 355 insertions(+), 110 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/tests/viewports.rs diff --git a/crates/metal2vulkan-conformance/known-gaps-rt.tsv b/crates/metal2vulkan-conformance/known-gaps-rt.tsv index 303821ef6..34101d9e7 100644 --- a/crates/metal2vulkan-conformance/known-gaps-rt.tsv +++ b/crates/metal2vulkan-conformance/known-gaps-rt.tsv @@ -1526,7 +1526,6 @@ read-write-tier-round-trip-float Iris(R) Xe refused case/MTLPixelFormatRG11B10Fl read-write-tier-round-trip-float llvmpipe divergent case/MTLPixelFormatRG8Unorm/beyond/texels 219 elements differ (U32), the largest difference 1 The device's own answer (rule 1): the device converts an 8-bit code by the reciprocal product, so a code's value is one `f32` ulp off Metal's. Note `device-texel-conversion`. Open: nothing. read-write-tier-round-trip-float llvmpipe divergent case/MTLPixelFormatRGBA8Unorm/tier2/texels 438 elements differ (U32), the largest difference 1 The device's own answer (rule 1): the device converts an 8-bit code by the reciprocal product, so a code's value is one `f32` ulp off Metal's. Note `device-texel-conversion`. Open: nothing. read-write-tier-round-trip-float RX 550 refused case/MTLPixelFormatRGBA8Unorm_sRGB/beyond/read-write Err(Error::Unsupported("texture slot 0, which a function writes or reads as storage, bound to a RGBA8UnormSRGB texture with no storage element on this device, or one it cannot read without a format, is not built")) The device's own answer (rule 2): this device's format queries offer no storage image of MTLPixelFormatRGBA8Unorm_sRGB, so rt binds no such texture to a read_write or write slot. -render-state-boxes * refused case/pieces/pass Err(Error::Unsupported("a draw with Viewports is not built")) Known gap (rt README, Known gaps of render pipeline states): a count of viewports other than 1 is Gap::Draw (Viewports), refused where it is set. render-then-sample-magnified-linear NVIDIA divergent case/sampled/texels 30 elements differ (U8), the largest difference 1 The device's own answer (rule 1): a linear magnified sample of a rendered 8-bit target, codes a step apart (Metal 0xda, ours 0xd9 at the first differing element): the sample is the device's filter and the target's codes its conversion. Notes `device-sampling` and `device-color-conversion`. Open: `device-sampling`'s bound on this device. resolve-stencil-under-depth-filters * refused case/render-pipeline Err(Error::Unsupported("a render pipeline state with DepthStencilFormats is not built")) refused: no stream uses it yet (states-only play 11-19, m3-max-56371-56373, 56375, player 44668b439f: 32 streams, every render and compute pipeline state made). rt builds no render pipeline state with DepthStencilFormats (Gap::RenderPipeline; rt README, Known gaps of render pipeline states). resource-own-getters * refused case/placement-heap-buffer-0-at-1024-shared/fresh Err(Error::Refused("Metal makes no buffer of length 0")) refused: no stream uses it yet (full selector census 11-19, m3-max-53207-53208, 53213, 53217-53221: 26 streams, no buffer of length 0: every newBufferWithLength:options:, newBufferWithLength:options:offset: and buffer in a block is 4 bytes or more). A buffer of length 0 in a placement heap: MTLHeap.h and Apple's makeBuffer(length:options:offset:) page state no least length, and The M3 Max (macOS 27.0.1) made one with its API validation off; its validation layer stops it: "Buffer Validation Cannot create buffer of zero length." diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 3df9ccf40..41182ef79 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -2777,9 +2777,9 @@ or does not check is rebuilt from the generations' names, with young counted ful value changed since the encoder's last draw), and `ring_writes` counts it. The values only a checked access reads (a checked slot's bounds and the zero range's address) come last, so they are the first to move to the block. -- A `VkPipeline` bakes what Vulkan 1.3 cannot leave dynamic: the content and the topology class - (line or triangle) of the draws it serves. It takes as dynamic state the viewport, scissor, cull - mode, front face, primitive topology within its class, primitive restart, depth test, write and +- A `VkPipeline` bakes what Vulkan 1.3 cannot leave dynamic: the content, the topology class + (point, line or triangle) of the draws it serves, and the depth clip and triangle fill modes. It + takes as dynamic state the viewports and scissors with their count, cull mode, front face, primitive topology within its class, primitive restart, depth test, write and compare, stencil test, operations, masks and reference, depth bias and blend constants, and a state without rasterization its discard, which keeps its attachment formats and that state in the pipeline. Vertex buffer strides are the descriptor's, so the content's, and baked. It @@ -3110,7 +3110,7 @@ or does not check is rebuilt from the generations' names, with young counted ful the floor's `maxColorAttachments` is 8. - An encoder holds Metal's render state: a pipeline state, the vertex and fragment functions' 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 + textures and sampler states, up to 16 viewports and scissor rectangles, the cull mode, the front-facing winding, a depth-stencil state (`Device::new_depth_stencil_state`), the stencil 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 @@ -3178,6 +3178,17 @@ or does not check is rebuilt from the generations' names, with young counted ful covers, so the scissor is Metal's rectangle cut to them; a rectangle past Metal's render area, which Metal's validation stops, is cut to it, as plain Metal cuts it. A stencil reference saturates at 255, as Metal stores it. +- `set_viewports` and `set_scissor_rects` are `setViewports:count:` and + `setScissorRects:count:`, 1 to 16 each, recorded with their count (`vkCmdSetViewportWithCount`, + `vkCmdSetScissorWithCount`, so no pipeline is made for a count). A vertex function's + `[[viewport_array_index]]` selects a viewport per primitive: the translator stores it to + `ViewportIndex` (Floor: `multiViewport`, `shaderOutputViewportIndex`), 0 for an index at or past + the encoder's count, which a draw pushes, as Metal draws it through viewport 0. A draw of any + other function draws through viewport 0. Vulkan takes as many scissors as viewports: each + viewport's is the rectangle of its index, the one rectangle where one is set, and none past + the rectangles set where several are, each cut to the pixels its viewport covers. An index + that is not one value across a primitive is the translator's refusal at creation, as a layer + index is: its form is a geometry stage, which device creation does not enable. - A draw may read an attachment of its own pass through a texture, as Metal reads a render target, where the device reads attachments (Floor, Attachment reads): through the attachment feedback loop where the device has it, else through a copy. The texture reaches the @@ -3261,7 +3272,7 @@ or does not check is rebuilt from the generations' names, with young counted ful - Refused by `Gap::Draw`, naming its `DrawKind`: the triangle fill mode `Lines` on a device without `fillModeNonSolid` (KosmicKrisp on the M3 Max, of the venues dumped, m3-max-48737) and the fill mode of raw value 2, which no SDK header declares (`FillMode`, - `set_triangle_fill_mode`), a count of viewports or scissor rectangles other than 1 (`Viewports`, + `set_triangle_fill_mode`), no viewport or scissor rectangle, or more than 16 (`Viewports`, `set_viewports`, `set_scissor_rects`), a visibility result mode but `Disabled` (`VisibilityResults`, `set_visibility_result_mode`), each refused where it is set, the encoder's state unchanged; the replay streams set Metal's defaults alone, which those setters @@ -3655,6 +3666,8 @@ Presenting runs on the runtime's own device; nothing is exported or imported. | `tessellationShader` | `VkPhysicalDeviceFeatures` | a post-tessellation vertex function's patches, drawn through the device's tessellator | | `shaderTessellationAndGeometryPointSize` | `VkPhysicalDeviceFeatures` | a post-tessellation vertex function's `[[point_size]]`; without it the device draws every such point at size 1 | | `shaderOutputLayer` | `VkPhysicalDeviceVulkan12Features` | a vertex function's `[[render_target_array_index]]`, stored to `Layer` in every pass; every venue's driver reports it (RADV on the 780M, the RX 550 and the RX 7900 XTX, NVIDIA's on the RTX 3090 and RTX 2080, lavapipe, KosmicKrisp on the M3 Max, and the UHD 630's Windows driver, a Vulkan 1.3 device; jobs m3-max-61359 to 61362 and 61366) | +| `multiViewport` | `VkPhysicalDeviceFeatures` | several viewports and scissor rectangles (`set_viewports`, `set_scissor_rects`); every venue's driver reports it (jobs m3-max-48727 to 48731, 48736, 48737 and 61508) | +| `shaderOutputViewportIndex` | `VkPhysicalDeviceVulkan12Features` | a vertex function's `[[viewport_array_index]]`, stored to `ViewportIndex`; every venue's driver reports it (jobs m3-max-48727 to 48731, 48736, 48737 and 61508, and the probes 61359 to 61362 and 61366) | | `largePoints` | `VkPhysicalDeviceFeatures` | a draw of points at the `[[point_size]]` its vertex function writes, up to the device's `pointSizeRange`; without it a device draws only points of size 1.0; Vulkan 1.4 and Roadmap 2022 require it | | `dualSrcBlend` | `VkPhysicalDeviceFeatures` | a fragment function's second output for colour attachment 0 (`[[color(0), index(1)]]`) as the blend's second source (`Source1Color`, `Source1Alpha` and their complements) | | `sampleRateShading` | `VkPhysicalDeviceFeatures` | a fragment function that reads its `[[sample_id]]`, or an interpolant at a sample, run once per covered sample as Metal runs it; Vulkan 1.4 requires it | diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 280839b6b..3a8be3ee6 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -1499,7 +1499,8 @@ impl Parameters { | FieldValue::TessellationFactors | FieldValue::AlphaTestReference | FieldValue::FetchedColor(_) - | FieldValue::RenderTargetArrayLength => {} + | FieldValue::RenderTargetArrayLength + | FieldValue::ViewportCount => {} } } self.block_address = (interface.block_len > 0).then_some(interface.block_address); diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index 9d1b98159..d51467a06 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -1478,8 +1478,8 @@ pub enum DrawKind { /// lines at width 1 alone, as Vulkan's wider lines are a device feature (`wideLines`) the /// floor does not require. LineWidth, - /// More than one viewport or scissor rectangle, or none (`setViewports:count:`, - /// `setScissorRects:count:`), which no replay stream sets. + /// No viewport or scissor rectangle, or more than Metal's 16 (`setViewports:count:`, + /// `setScissorRects:count:`), which Metal's validation stops. 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. diff --git a/crates/metal2vulkan-runtime/src/floor.rs b/crates/metal2vulkan-runtime/src/floor.rs index 9b8ed897e..ae183cab3 100644 --- a/crates/metal2vulkan-runtime/src/floor.rs +++ b/crates/metal2vulkan-runtime/src/floor.rs @@ -474,6 +474,11 @@ pub(crate) const REQUIRED: &[Feature] = &[ // output (written 0 for an index at or past the pass's length), in every pass. Every venue's // driver reports it. feature!(vulkan12.shader_output_layer => ShaderOutputLayer), + // Several viewports and scissors (`setViewports:count:`), and a vertex function's + // `[[viewport_array_index]]`: one form, its `ViewportIndex` output (written 0 for an index at + // or past the encoder's viewport count). Every venue's driver reports both. + feature!(core.multi_viewport => MultiViewport), + feature!(vulkan12.shader_output_viewport_index => ShaderOutputViewportIndex), // A point drawn at the size its vertex function writes, up to the device's `pointSizeRange`: // without it a device draws only points of size 1.0. Vulkan 1.4 and Roadmap 2022 require it // of every device. diff --git a/crates/metal2vulkan-runtime/src/pipeline.rs b/crates/metal2vulkan-runtime/src/pipeline.rs index 5f5956e25..d519e3ef7 100644 --- a/crates/metal2vulkan-runtime/src/pipeline.rs +++ b/crates/metal2vulkan-runtime/src/pipeline.rs @@ -747,6 +747,10 @@ pub(crate) enum FieldValue { /// invocation's at its index in the dispatch times the slot's bytes /// (`PushField::PrivateArenaAddress`). PrivateArena, + /// A `u32`: the viewports the render encoder set (`setViewports:count:`, at least 1), at or + /// past which a vertex function's `[[viewport_array_index]]` stores `ViewportIndex` 0 + /// (`PushField::ViewportCount`). + ViewportCount, } /// A `VkPipeline`'s specialization: the threadgroup size, the threadgroup memory lengths in the diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 9381d2fa4..f82afcd60 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -18,7 +18,8 @@ //! What a `VkPipeline` bakes is what Vulkan 1.3 cannot leave dynamic: the content, the topology //! class (point, line or triangle) of the draws it serves, and the encoder's depth clip mode and //! triangle fill mode ([`Raster`]). Everything Metal sets on the -//! encoder that Vulkan 1.3 makes dynamic without a feature is dynamic state: viewport, scissor, +//! encoder that Vulkan 1.3 makes dynamic without a feature is dynamic state: the viewports and +//! scissors with their count, //! cull mode, front face, the primitive topology within its class and primitive restart, the //! depth test, write and compare, the stencil test, operations, masks and reference, depth bias //! and blend constants. Vertex buffer strides are the descriptor's, so the content's: they are @@ -173,12 +174,16 @@ pub(crate) struct Draws { /// Whether the vertex function is post-tessellation: the content draws patches alone, through /// its patch-class `VkPipeline`, and reads the encoder's tessellation factor buffer. pub(crate) patches: bool, + /// Whether the vertex function writes `[[viewport_array_index]]` + /// (`GraphicsState::writes_viewport_index`): its primitives reach every viewport the encoder + /// set, where any other function's reach viewport 0. + pub(crate) selects_viewport: bool, } /// The state Vulkan 1.3 lets a draw set, which every render `VkPipeline` takes as dynamic. const DYNAMIC: [vk::DynamicState; 17] = [ - vk::DynamicState::VIEWPORT, - vk::DynamicState::SCISSOR, + vk::DynamicState::VIEWPORT_WITH_COUNT, + vk::DynamicState::SCISSOR_WITH_COUNT, vk::DynamicState::CULL_MODE, vk::DynamicState::FRONT_FACE, vk::DynamicState::PRIMITIVE_TOPOLOGY, @@ -536,6 +541,10 @@ fn draws( RuntimeFact::RenderTargetArrayLength { layer_dropped: false, } => {} + // A vertex function's `[[viewport_array_index]]`, which stores `ViewportIndex` 0 at or + // past the encoder's viewport count, read from its push field + // (`FieldValue::ViewportCount`). + RuntimeFact::ViewportCount => {} // `RuntimeFact` is non-exhaustive: a fact this match does not name is one a draw does // not supply. _ => return Err(draw_input()), @@ -684,6 +693,9 @@ fn draws( PushField::RenderTargetArrayLength if at == VERTEX => { FieldValue::RenderTargetArrayLength } + // The encoder's viewport count, below which the vertex function's index selects + // its viewport. + PushField::ViewportCount if at == VERTEX => FieldValue::ViewportCount, _ => return Err(draw_input()), }; fields.push((offset, at, value)); @@ -731,6 +743,7 @@ fn draws( blocks, first_instance_zero: divided && !nonzero_first_instance, patches: pipeline.graphics.tessellation.is_some(), + selects_viewport: pipeline.graphics.writes_viewport_index, }; Ok((draws, (numbered, constexprs))) } @@ -1201,9 +1214,8 @@ impl RenderCompiled { let input_assembly = vk::PipelineInputAssemblyStateCreateInfo::default().topology(topology); let tessellation = vk::PipelineTessellationStateCreateInfo::default() .patch_control_points(fixed.patch_control_points); - let viewport = vk::PipelineViewportStateCreateInfo::default() - .viewport_count(1) - .scissor_count(1); + // The draw sets its viewports and scissors with their count (`VIEWPORT_WITH_COUNT`). + let viewport = vk::PipelineViewportStateCreateInfo::default(); // `Clamp` keeps what lies past the near and far planes and clamps its depth to the // viewport's range, as Vulkan's depth clamp does (`depthClamp`, Floor); `Lines` draws each // triangle's edges as lines 1 pixel wide (`fillModeNonSolid`, which the encoder asks of diff --git a/crates/metal2vulkan-runtime/src/render_encoder.rs b/crates/metal2vulkan-runtime/src/render_encoder.rs index 6cf61df38..04878eee3 100644 --- a/crates/metal2vulkan-runtime/src/render_encoder.rs +++ b/crates/metal2vulkan-runtime/src/render_encoder.rs @@ -164,6 +164,10 @@ pub struct IndexBuffer<'a> { pub index_type: IndexType, } +/// Metal's most viewports and scissor rectangles (`setViewports:count:`), which Vulkan's +/// `maxViewports` holds on every device with `multiViewport` (Floor). +const MAX_VIEWPORTS: usize = 16; + /// The dynamic state a draw records before it: the viewport and scissor, the cull mode, the /// front face, the depth test, the stencil references, the blend constants, the depth bias, the /// feedback loop's enable where the device reads attachments, and the stencil test. A setter @@ -548,7 +552,7 @@ struct Declarations { /// [`memory_barrier`](Self::memory_barrier). /// /// 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 +/// and sampler states, up to 16 viewports and scissor rectangles, the cull mode, the front-facing /// winding, the depth clip mode, the triangle fill modes `Fill` and `Lines`, a depth-stencil /// state's depth and stencil tests, the depth bias and its clamp, the stencil references, the /// blend color, the line width (lines drawn at 1 alone: a draw of lines at another width is @@ -556,8 +560,8 @@ struct Declarations { /// them unknown, memory barriers, fences, draws of points, lines and triangles, indexed or not, /// draws of patches with a tessellation factor buffer, each direct or indirect, and the `Disabled` /// visibility result mode (`Boolean` and `Counting` are [`DrawKind::VisibilityResults`]). Not -/// built, and so not methods: several viewports or scissor rectangles, the store action options -/// setters, tile functions, the `setVertexBuffer:offset:attributeStride:atIndex:` family, +/// built, and so not methods: the store action options setters, tile functions, the +/// `setVertexBuffer:offset:attributeStride:atIndex:` family, /// `setTessellationFactorScale:` (read by a pipeline that enables the scale, which is refused), /// and indexed patch draws (`drawIndexedPatches:`, read by a pipeline of a control-point index /// type, which is refused). A draw of what the runtime does not build is [`Gap::Draw`], naming @@ -588,10 +592,13 @@ pub struct RenderCommandEncoder { tests: Tests, /// The tests the encoder last recorded, none before its first draw. recorded: Option, - viewport: Viewport, - /// Metal's scissor rectangle cut to Metal's render area (`Pass::area`), per axis - /// `[first, end)`. - scissor: [[u32; 2]; 2], + /// The viewports, the first `viewport_count` of them set (`setViewports:count:`). + viewports: [Viewport; MAX_VIEWPORTS], + viewport_count: usize, + /// Metal's scissor rectangles cut to Metal's render area (`Pass::area`), per axis + /// `[first, end)`, the first `scissor_count` of them set. + scissors: [[[u32; 2]; 2]; MAX_VIEWPORTS], + scissor_count: usize, cull_mode: CullMode, winding: Winding, /// The front and back stencil references, saturated to 8 bits. @@ -683,15 +690,17 @@ impl CommandBuffer { factors: None, renders_into: false, tests: Tests::of(&DepthStencilDescriptor::default()), - viewport: Viewport { + viewports: [Viewport { origin_x: 0.0, origin_y: 0.0, width: f64::from(width), height: f64::from(height), znear: 0.0, zfar: 1.0, - }, - scissor: [[0, width], [0, height]], + }; MAX_VIEWPORTS], + viewport_count: 1, + scissors: [[[0, width], [0, height]]; MAX_VIEWPORTS], + scissor_count: 1, cull_mode: CullMode::None, winding: Winding::Clockwise, stencil_reference: [0; 2], @@ -1136,6 +1145,14 @@ impl RenderCommandEncoder { /// [`DrawKind::Viewport`] for a negative width, a depth range past `[0, 1]`, or bounds past /// the device's `maxViewportDimensions` and `viewportBoundsRange`. pub fn set_viewport(&mut self, viewport: Viewport) -> Result<(), Error> { + let v = self.checked(viewport)?; + self.viewports[0] = v; + self.viewports_set(1); + Ok(()) + } + + /// `viewport` as a draw takes it, checked as [`set_viewport`](Self::set_viewport) says. + fn checked(&self, viewport: Viewport) -> Result { let v = match viewport.origin_x.is_nan() { true => Viewport { origin_x: 0.0, @@ -1166,24 +1183,38 @@ impl RenderCommandEncoder { kind: DrawKind::Viewport, })); } - self.viewport = v; + Ok(v) + } + + /// The first `count` viewports are set: each later draw records them, and one whose vertex + /// function writes `[[viewport_array_index]]` pushes the count. + fn viewports_set(&mut self, count: usize) { + if count != self.viewport_count { + self.viewport_count = count; + self.push_filled = false; + } self.dirty |= VIEWPORT; - Ok(()) + } + + /// Metal's scissor rectangle `rect` cut to Metal's render area. + fn cut(&self, rect: ScissorRect) -> [[u32; 2]; 2] { + let [width, height] = self.pass.area; + let cut = |origin: u64, size: u64, limit: u32| { + let limit = u64::from(limit); + [origin.min(limit), origin.saturating_add(size).min(limit)].map(|at| at as u32) + }; + [ + cut(rect.x, rect.width, width), + cut(rect.y, rect.height, height), + ] } /// `setScissorRect:`. Metal's default is Metal's render area. A rectangle past that area, /// which Metal's validation stops, is cut to it, as plain Metal cuts it; the pass's load and /// store reach past it to 32-pixel rounding (`RenderPassDescriptor::render_target_width`). pub fn set_scissor_rect(&mut self, rect: ScissorRect) { - let [width, height] = self.pass.area; - let cut = |origin: u64, size: u64, limit: u32| { - let limit = u64::from(limit); - [origin.min(limit), origin.saturating_add(size).min(limit)].map(|at| at as u32) - }; - self.scissor = [ - cut(rect.x, rect.width, width), - cut(rect.y, rect.height, height), - ]; + self.scissors[0] = self.cut(rect); + self.scissor_count = 1; self.dirty |= VIEWPORT; } @@ -1348,34 +1379,49 @@ impl RenderCommandEncoder { Ok(()) } - /// `setViewports:count:`: one viewport is [`set_viewport`](Self::set_viewport)'s; several are - /// not built. + /// `setViewports:count:`: 1 to 16 viewports, each as [`set_viewport`](Self::set_viewport) + /// takes it. A vertex function's `[[viewport_array_index]]` selects one per primitive (the + /// floor's `multiViewport` and `shaderOutputViewportIndex`), viewport 0 for an index at or past + /// the count, as Metal draws it; a draw of any other function takes viewport 0. Each viewport's + /// scissor is the rectangle of its index, the one rectangle where one is set, and none past the + /// rectangles set where several are, each cut to the pixels its viewport covers. An index that + /// is not one value across a primitive is the translator's refusal at the state's creation (a + /// geometry stage, which device creation does not enable). /// - /// Err: as [`set_viewport`](Self::set_viewport); [`Gap::Draw`] of [`DrawKind::Viewports`] for - /// a count other than 1. + /// Err: as [`set_viewport`](Self::set_viewport) for any of them, the encoder's viewports + /// unchanged; [`Gap::Draw`] of [`DrawKind::Viewports`] for none or more than 16. pub fn set_viewports(&mut self, viewports: &[Viewport]) -> Result<(), Error> { - match viewports { - [viewport] => self.set_viewport(*viewport), - _ => Err(Error::Unsupported(Gap::Draw { + if viewports.is_empty() || viewports.len() > MAX_VIEWPORTS { + return Err(Error::Unsupported(Gap::Draw { kind: DrawKind::Viewports, - })), + })); } + let mut checked = self.viewports; + for (at, viewport) in checked.iter_mut().zip(viewports) { + *at = self.checked(*viewport)?; + } + self.viewports = checked; + self.viewports_set(viewports.len()); + Ok(()) } - /// `setScissorRects:count:`: one rectangle is [`set_scissor_rect`](Self::set_scissor_rect)'s; - /// several are not built. + /// `setScissorRects:count:`: 1 to 16 rectangles, each cut as + /// [`set_scissor_rect`](Self::set_scissor_rect) cuts it, the scissors of the viewports of + /// their indices ([`set_viewports`](Self::set_viewports)). /// - /// Err: [`Gap::Draw`] of [`DrawKind::Viewports`] for a count other than 1. + /// Err: [`Gap::Draw`] of [`DrawKind::Viewports`] for none or more than 16. 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 { + if rects.is_empty() || rects.len() > MAX_VIEWPORTS { + return Err(Error::Unsupported(Gap::Draw { kind: DrawKind::Viewports, - })), + })); } + for (at, rect) in rects.iter().enumerate() { + self.scissors[at] = self.cut(*rect); + } + self.scissor_count = rects.len(); + self.dirty |= VIEWPORT; + Ok(()) } /// `setColorStoreAction:atIndex:`: the store action of the colour attachment at `index`, which @@ -2198,7 +2244,8 @@ impl RenderCommandEncoder { }); fill_push( (&mut self.push, &mut self.blocks), - (&self.tables, self.facts.nil, factors, self.alpha_test), + (&self.tables, self.facts.nil, factors), + [self.alpha_test, self.viewport_count as u32], (&self.moved, &self.shadow_slots, &self.pass), state, ); @@ -2349,7 +2396,7 @@ impl RenderCommandEncoder { /// through its texture. fn attachment_reads(&self, draws: &Draws) -> Result { let core = &*self.core; - let drawn = self.drawn(); + let drawn = self.drawn(draws); let tables = &self.tables; let mut found = AttachmentReads { reads: false, @@ -2628,15 +2675,23 @@ impl RenderCommandEncoder { let both = [vk::StencilFaceFlags::FRONT, vk::StencilFaceFlags::BACK]; // SAFETY: the command buffer records; each state is dynamic in every render pipeline. unsafe { + // As many scissors as viewports, as Vulkan's with-count states require. + let count = self.viewport_count; if dirty & VIEWPORT != 0 { - device.cmd_set_viewport(command, 0, &[vk_viewport(&self.viewport)]); + let mut viewports = [vk::Viewport::default(); MAX_VIEWPORTS]; + for (at, viewport) in viewports.iter_mut().zip(&self.viewports[..count]) { + *at = vk_viewport(viewport); + } + device.cmd_set_viewport_with_count(command, &viewports[..count]); } if dirty & VIEWPORT != 0 || hidden != self.hidden { - let scissor = match hidden { - true => vk::Rect2D::default(), - false => self.vk_scissor(), - }; - device.cmd_set_scissor(command, 0, &[scissor]); + let mut scissors = [vk::Rect2D::default(); MAX_VIEWPORTS]; + if !hidden { + for (at, scissor) in scissors[..count].iter_mut().enumerate() { + *scissor = rect(self.drawn_through(at)); + } + } + device.cmd_set_scissor_with_count(command, &scissors[..count]); self.hidden = hidden; } if dirty & CULL != 0 { @@ -2736,31 +2791,41 @@ impl RenderCommandEncoder { } } - /// The pixels a draw covers, per axis `[first, end)`: Metal's scissor rectangle cut to the - /// pixels its viewport covers. - fn drawn(&self) -> [[u32; 2]; 2] { - let pixels = viewport_pixels(&self.viewport, self.pass.area); + /// The pixels a draw covers through viewport `at`, per axis `[first, end)`: its scissor + /// rectangle (the one rectangle where one is set, and none past those set where several are) + /// cut to the pixels the viewport covers. + fn drawn_through(&self, at: usize) -> [[u32; 2]; 2] { + let pixels = viewport_pixels(&self.viewports[at], self.pass.area); + let scissor = match (self.scissor_count, self.scissors.get(at)) { + (1, _) => self.scissors[0], + (count, Some(scissor)) if at < count => *scissor, + _ => [[0, 0], [0, 0]], + }; [0, 1].map(|axis| { - let first = self.scissor[axis][0].max(pixels[axis][0]); - let end = self.scissor[axis][1].min(pixels[axis][1]); + let first = scissor[axis][0].max(pixels[axis][0]); + let end = scissor[axis][1].min(pixels[axis][1]); [first, end.max(first)] }) } - /// The draw's scissor: the pixels it covers ([`drawn`](Self::drawn)). - fn vk_scissor(&self) -> vk::Rect2D { - let [x, y] = self.drawn(); - // Each bound lies in Metal's render area, which fits an `i32`. - vk::Rect2D { - offset: vk::Offset2D { - x: x[0] as i32, - y: y[0] as i32, - }, - extent: vk::Extent2D { - width: x[1] - x[0], - height: y[1] - y[0], - }, - } + /// The pixels a draw of `draws` covers, per axis `[first, end)`: those through viewport 0, or + /// through every viewport set where its vertex function selects one, their bounds. + fn drawn(&self, draws: &Draws) -> [[u32; 2]; 2] { + let used = match draws.selects_viewport { + true => self.viewport_count, + false => 1, + }; + let mut through = (0..used).map(|at| self.drawn_through(at)); + let first = through.next().unwrap_or([[0, 0], [0, 0]]); + through + .filter(|[x, y]| x[0] < x[1] && y[0] < y[1]) + .fold(first, |[x, y], [nx, ny]| match x[0] < x[1] && y[0] < y[1] { + true => [ + [x[0].min(nx[0]), x[1].max(nx[1])], + [y[0].min(ny[0]), y[1].max(ny[1])], + ], + false => [nx, ny], + }) } /// Ends the pass's rendering, has `record` record into the command buffer, and begins the @@ -2874,10 +2939,11 @@ fn primitives(primitive_type: PrimitiveType) -> (vk::PrimitiveTopology, bool) { /// image the pass `moved` to the feedback layout reads through its second element in that layout, /// and one in `shadow_slots`, which reads a shadow, through its second element, the shadow's; a /// colour attachment of `pass` the fragment function reads is read through its texture's second -/// element. +/// element; the alpha test's code and the encoder's viewport count are the encoder's. fn fill_push( (push, blocks): (&mut Vec, &mut [Vec; 2]), - (tables, (nil, zero), factors, alpha_test): (&[Tables; 2], (u64, u64), u64, u32), + (tables, (nil, zero), factors): (&[Tables; 2], (u64, u64), u64), + [alpha_test, viewports]: [u32; 2], (moved, shadow_slots, pass): (&[Moved], &[(usize, u32)], &Pass), state: &RenderPipelineState, ) { @@ -2957,6 +3023,9 @@ fn fill_push( FieldValue::RenderTargetArrayLength => { bytes[at..at + 4].copy_from_slice(&pass.layers.to_le_bytes()); } + FieldValue::ViewportCount => { + bytes[at..at + 4].copy_from_slice(&viewports.to_le_bytes()); + } // A render content has no dispatch or stage-in region (`render::draws`). FieldValue::DispatchRegion | FieldValue::StageInRegion | FieldValue::PrivateArena => {} } @@ -3075,6 +3144,21 @@ pub(crate) fn vk_viewport(v: &Viewport) -> vk::Viewport { } } +/// The Vulkan rectangle of the pixels `[x, y]`, per axis `[first, end)`, which lie in Metal's +/// render area and so fit an `i32`. +fn rect([x, y]: [[u32; 2]; 2]) -> vk::Rect2D { + vk::Rect2D { + offset: vk::Offset2D { + x: x[0] as i32, + y: y[0] as i32, + }, + extent: vk::Extent2D { + width: x[1] - x[0], + height: y[1] - y[0], + }, + } +} + /// The pixels `v` covers in a render area of `extent`, per axis `[first, end)`: none for a /// viewport of no width or height. pub(crate) fn viewport_pixels(v: &Viewport, extent: [u32; 2]) -> [[u32; 2]; 2] { diff --git a/crates/metal2vulkan-runtime/src/tests/draw.rs b/crates/metal2vulkan-runtime/src/tests/draw.rs index 384644db7..ed637171c 100644 --- a/crates/metal2vulkan-runtime/src/tests/draw.rs +++ b/crates/metal2vulkan-runtime/src/tests/draw.rs @@ -1291,8 +1291,8 @@ pub(crate) mod on_device { /// 0.0625, passes and writes 0.3125 on every device; one at 0.375 with no bias then fails; one /// at 0.25 under `Greater`, without writes, passes only by its unclamped bias of 2^23. Setting /// the depth clip mode `Clamp` and the triangle fill mode `Lines` (refused without - /// `fillModeNonSolid`) makes no pipeline when no draw follows; the viewport and scissor setters - /// refuse a count but 1. + /// `fillModeNonSolid`) makes no pipeline when no draw follows; the scissor setter refuses no + /// rectangle. #[test] fn every_device_tests_writes_and_biases_a_depth_attachment() { let Some(library) = examples() else { @@ -1393,11 +1393,6 @@ pub(crate) mod on_device { draw(encoder.set_depth_clip_mode(crate::DepthClipMode::Clamp)); draw(encoder.set_depth_clip_mode(crate::DepthClipMode::Clip)); 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), diff --git a/crates/metal2vulkan-runtime/src/tests/floor.rs b/crates/metal2vulkan-runtime/src/tests/floor.rs index 1e4d4adc1..0d3ddc1bd 100644 --- a/crates/metal2vulkan-runtime/src/tests/floor.rs +++ b/crates/metal2vulkan-runtime/src/tests/floor.rs @@ -72,6 +72,8 @@ fn at_the_floor() -> Queried { features.core.shader_tessellation_and_geometry_point_size = vk::TRUE; features.core.large_points = vk::TRUE; features.vulkan12.shader_output_layer = vk::TRUE; + features.core.multi_viewport = vk::TRUE; + features.vulkan12.shader_output_viewport_index = vk::TRUE; features.core.shader_int16 = vk::TRUE; features.vulkan12.shader_int8 = vk::TRUE; features.vulkan11.storage_buffer16_bit_access = vk::TRUE; @@ -251,7 +253,6 @@ fn the_translator_sees_only_what_device_creation_enables() { use metal2vulkan::device::{VkExtension, VkFeature}; let mut device = at_the_floor(); device.features.core.geometry_shader = vk::TRUE; - device.features.vulkan12.shader_output_viewport_index = vk::TRUE; device.features.vulkan13.robust_image_access = vk::TRUE; device.features.robustness2.robust_buffer_access2 = vk::TRUE; let capabilities = decide(&device).unwrap_or_else(|below| panic!("{below}")); @@ -291,7 +292,6 @@ fn the_translator_sees_only_what_device_creation_enables() { assert!(enables.features.contains(&VkFeature::NullDescriptor)); for reported in [ VkFeature::GeometryShader, - VkFeature::ShaderOutputViewportIndex, VkFeature::RobustBufferAccess2, VkFeature::RobustBufferAccess, ] { @@ -307,7 +307,6 @@ fn a_device_at_the_floor_is_above_it() { // Features beyond the floor are not enabled. device.features.core.geometry_shader = vk::TRUE; device.features.vulkan11.storage_input_output16 = vk::TRUE; - device.features.vulkan12.shader_output_viewport_index = vk::TRUE; let capabilities = decide(&device).unwrap_or_else(|below| panic!("{below}")); assert!(!capabilities.float16); assert!(!capabilities.storage_read_without_format); @@ -345,7 +344,7 @@ fn a_device_at_the_floor_is_above_it() { } assert_eq!(enabled.core.geometry_shader, vk::FALSE); assert_eq!(enabled.vulkan11.storage_input_output16, vk::FALSE); - assert_eq!(enabled.vulkan12.shader_output_viewport_index, vk::FALSE); + assert_eq!(enabled.vulkan12.shader_output_viewport_index, vk::TRUE); assert_eq!(enabled.vulkan12.shader_output_layer, vk::TRUE); assert_eq!(enabled.vulkan13.robust_image_access, vk::TRUE); assert_eq!(enabled.core.independent_blend, vk::TRUE); @@ -375,7 +374,7 @@ fn each_missing_feature_is_named() { const CORE: &str = "VkPhysicalDeviceFeatures"; const ROBUSTNESS2: &str = "VkPhysicalDeviceRobustness2FeaturesEXT"; type Clear = fn(&mut Features); - let cases: [(Clear, Missing); 57] = [ + let cases: [(Clear, Missing); 59] = [ ( |f| f.vulkan12.buffer_device_address = vk::FALSE, feature(V12, "bufferDeviceAddress"), @@ -599,6 +598,14 @@ fn each_missing_feature_is_named() { |f| f.vulkan12.shader_output_layer = vk::FALSE, feature(V12, "shaderOutputLayer"), ), + ( + |f| f.core.multi_viewport = vk::FALSE, + feature(CORE, "multiViewport"), + ), + ( + |f| f.vulkan12.shader_output_viewport_index = vk::FALSE, + feature(V12, "shaderOutputViewportIndex"), + ), ( |f| f.core.large_points = vk::FALSE, feature(CORE, "largePoints"), diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 5e48379b5..c405c573d 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -104,6 +104,7 @@ mod upload; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod validation; mod view; +mod viewports; /// This crate's directory: the test process's `CARGO_MANIFEST_DIR` where it holds the crate's /// sources (cargo and nextest set it for each test, and an archive run elsewhere remaps it to the diff --git a/crates/metal2vulkan-runtime/src/tests/viewports.rs b/crates/metal2vulkan-runtime/src/tests/viewports.rs new file mode 100644 index 000000000..966de7dad --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/viewports.rs @@ -0,0 +1,118 @@ +//! Several viewports and scissor rectangles (`setViewports:count:`, `setScissorRects:count:`), and +//! a vertex function's `[[viewport_array_index]]`, under a device cfg on every device of the cfg's +//! kind. `rt6_select` (engine `rt6_viewports`) draws Metal's fullscreen triangle through the +//! viewport of its instance, and `rt6_viewport_read` colours red the index it reads, green 1. +//! +//! Two viewports, the target's left and right halves, and two scissors, the whole target and its +//! top half: instance 0 fills the left half, instance 1 the right half's top, cut by its scissor, +//! and instance 2, past the count, draws through viewport 0 as Metal does, its fragment function +//! reading the 2 its vertex function wrote. No pipeline is made for the count, and none or 17 +//! viewports or rectangles are `DrawKind::Viewports`. + +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod on_device { + use crate::tests::blit::on_device::settled; + use crate::tests::command::on_device::each_device; + use crate::tests::draw::on_device::{floats, library, pass, read, run, state, target, SIDE}; + use crate::{ + ColorAttachmentDescriptor, DrawKind, Error, FunctionDescriptor, Gap, PixelFormat, + PrimitiveType, RenderPipelineDescriptor, ScissorRect, StageSource, TextureUsage, Viewport, + }; + use metal2vulkan_devtools::engine_dir; + + /// The viewport over columns `[x, x + width)` of the target, every row, depth `[0, 1]`. + fn columns(x: u32, width: u32) -> Viewport { + Viewport { + origin_x: f64::from(x), + origin_y: 0.0, + width: f64::from(width), + height: f64::from(SIDE), + znear: 0.0, + zfar: 1.0, + } + } + + #[test] + fn every_device_selects_a_viewport_and_its_scissor_per_primitive() { + let Some(library) = library(&engine_dir().join("rt6_viewports.ll")) else { + return; + }; + let function = |name| { + StageSource::Function(FunctionDescriptor::new( + library.function(name).expect("the function"), + )) + }; + let mut d = RenderPipelineDescriptor::new(function("rt6_select")); + d.fragment = Some(function("rt6_viewport_read")); + d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); + each_device("viewports", |name, _, device| { + let state = state(name, &device, &d); + let color = target( + &device, + PixelFormat::RGBA8Unorm, + TextureUsage::RENDER_TARGET, + ); + let queue = device.new_command_queue(4).expect("a queue"); + // The upload that moves the new target to its home layout, in a submission apart. + let first = queue.command_buffer().expect("a command buffer"); + (first.record_for_test(&[], |_, _| {})).expect("a command buffer's commands"); + run(name, &first); + let counters = device.counters(); + settled(&device); + let before = counters.metrics(); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = (command_buffer.render_command_encoder(&pass(&color, None))) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let draw = |result: Result<(), Error>| result.unwrap_or_else(|e| panic!("{name}: {e}")); + let refused = |result: Result<(), Error>, what: &str| match result { + Err(Error::Unsupported(Gap::Draw { + kind: DrawKind::Viewports, + })) => {} + other => panic!("{name}: {what}: {other:?}"), + }; + let half = SIDE / 2; + refused(encoder.set_viewports(&[]), "no viewport"); + refused( + encoder.set_viewports(&[columns(0, half); 17]), + "17 viewports", + ); + refused(encoder.set_scissor_rects(&[]), "no scissor rectangle"); + draw(encoder.set_render_pipeline_state(&state)); + draw(encoder.set_vertex_bytes(&floats(&[0.5, 0.0]), 0)); + draw(encoder.set_viewports(&[columns(0, half), columns(half, half)])); + let whole = ScissorRect { + x: 0, + y: 0, + width: u64::from(SIDE), + height: u64::from(SIDE), + }; + let top = ScissorRect { + height: u64::from(half), + ..whole + }; + draw(encoder.set_scissor_rects(&[whole, top])); + draw(encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 3, 0)); + encoder.end_encoding(); + run(name, &command_buffer); + let after = counters.metrics(); + assert_eq!( + after.pipelines_created - before.pipelines_created, + 0, + "{name}: pipelines made" + ); + let want: Vec = (0..SIDE) + .flat_map(|y| (0..SIDE).map(move |x| (x, y))) + .flat_map(|(x, y)| match (x < half, y < half) { + (true, _) => [2, 255, 0, 255], + (false, true) => [1, 255, 0, 255], + (false, false) => [0, 0, 0, 255], + }) + .collect(); + assert_eq!(read(&color, 4), want, "{name}: the texels"); + println!( + "{name}: instance 0 and 2 through viewport 0, instance 1 through viewport 1 cut by \ + its scissor; no pipeline made" + ); + }); + } +} diff --git a/crates/metal2vulkan-validation/profiles/runtime-floor.json b/crates/metal2vulkan-validation/profiles/runtime-floor.json index 79f4e4da0..b80fb84e3 100644 --- a/crates/metal2vulkan-validation/profiles/runtime-floor.json +++ b/crates/metal2vulkan-validation/profiles/runtime-floor.json @@ -1149,7 +1149,8 @@ "largePoints": true, "dualSrcBlend": true, "sampleRateShading": true, - "vertexPipelineStoresAndAtomics": true + "vertexPipelineStoresAndAtomics": true, + "multiViewport": true }, "VkPhysicalDeviceVulkan11Features": { "storageBuffer16BitAccess": true, @@ -1175,7 +1176,8 @@ "shaderSubgroupExtendedTypes": true, "timelineSemaphore": true, "hostQueryReset": true, - "shaderOutputLayer": true + "shaderOutputLayer": true, + "shaderOutputViewportIndex": true }, "VkPhysicalDeviceVulkan13Features": { "subgroupSizeControl": true, diff --git a/crates/metal2vulkan/src/tests/engine_stage_io_tail.rs b/crates/metal2vulkan/src/tests/engine_stage_io_tail.rs index 7625959ec..dfe618165 100644 --- a/crates/metal2vulkan/src/tests/engine_stage_io_tail.rs +++ b/crates/metal2vulkan/src/tests/engine_stage_io_tail.rs @@ -217,16 +217,17 @@ fn a_fragment_primitive_id_takes_the_enabled_alternative() { } /// Fragment `Layer` and `ViewportIndex` inputs take their enabled alternatives. The floor declares -/// `Layer` through `shaderOutputLayer` and cannot declare `ViewportIndex`, so no stage can have -/// written the viewport index and the function reads it as 0, Metal's value with no vertex write -/// (`StageIo::zero_indices`). Below the floor, without `shaderOutputLayer`, it reads both as 0 and -/// declares neither. +/// both, through `shaderOutputLayer`, `shaderOutputViewportIndex` and `multiViewport`. Below it, +/// without the viewport index's two, no stage can have written the viewport index and the function +/// reads it as 0, Metal's value with no vertex write (`StageIo::zero_indices`); without +/// `shaderOutputLayer` too, it reads both as 0 and declares neither. #[test] fn fragment_layer_and_viewport_inputs_take_the_enabled_alternatives() { let Some(bc) = fixture() else { return }; for (stem, caps) in [ ("moltenvk-m3", [Cap::ShaderLayer, Cap::MultiViewport]), ("lavapipe", [Cap::Geometry, Cap::MultiViewport]), + ("runtime-floor", [Cap::ShaderLayer, Cap::MultiViewport]), ] { let p = prof(stem); let a = compile(&bc, "tail_fragment_layer", &p).unwrap_or_else(|e| panic!("{stem}: {e}")); @@ -239,7 +240,9 @@ fn fragment_layer_and_viewport_inputs_take_the_enabled_alternatives() { } validate(&a, &p); } - let floor = prof("runtime-floor"); + let viewport = [F::ShaderOutputViewportIndex, F::MultiViewport]; + let floor = profile_without("runtime-floor", &viewport, DevicePolicy::default()) + .expect("below the runtime's floor"); let a = compile(&bc, "tail_fragment_layer", &floor).expect("floor"); let io = &a.interface.io; assert_eq!(io.zero_indices, [StageBuiltin::ViewportIndex]); @@ -256,7 +259,7 @@ fn fragment_layer_and_viewport_inputs_take_the_enabled_alternatives() { validate(&a, &floor); let below = profile_without( "runtime-floor", - &[F::ShaderOutputLayer], + &[viewport.as_slice(), &[F::ShaderOutputLayer]].concat(), DevicePolicy::default(), ) .expect("below the runtime's floor"); diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index fda99ed71..faddbdd12 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -331,7 +331,7 @@ Columns: | `IndexBufferOffset` | An indexed draw whose index buffer offset is not a multiple of the index size, or whose indices leave the buffer | every device (a public call's own check of its arguments) | `metal-documented`: the offset is a multiple of the index size and the indices lie in the buffer; Metal's validation stops the draw | 1: `crates/metal2vulkan-runtime/src/render_encoder.rs (draw)` | `-` | | `TessellationFactorOffset` | A tessellation factor buffer whose factors, at its address plus the offset, start at an odd byte | every device (a public call's own check of its arguments) | `metal-documented`: `setTessellationFactorBuffer:offset:instanceStride:`'s offset is a multiple of 4; Metal's validation stops a patch draw with any other | 1: `crates/metal2vulkan-runtime/src/render_encoder.rs (set_tessellation_factor_buffer)` | `-` | | `ArgumentPlace` | An indirect dispatch's arguments, or an indexed draw's indices, at a byte of the allocation the buffer's block lies in (its device copy's, for a... | every device (a public call's own check of its arguments) | `ours`: `vkCmdDispatchIndirect` reads its arguments at a multiple of 4 in the `VkBuffer`, and `vkCmdBindIndexBuffer` takes indices at a multiple of their size in the memory; a Metal buffer starts at an aligned address, so Metal's offset rule alone keeps both aligned there | 3: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)`, `crates/metal2vulkan-runtime/src/render_encoder.rs (draw)` (+1) | `-` | -| `ViewportNotFinite` | A viewport with a field that is NaN or infinite (but its origin's x, which draws nothing) | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M4, macOS 27.0.1: Metal's validation stops a NaN or infinite origin; the other fields are taken by the same rule | 1: `crates/metal2vulkan-runtime/src/render_encoder.rs (set_viewport)` | `-` | +| `ViewportNotFinite` | A viewport with a field that is NaN or infinite (but its origin's x, which draws nothing) | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M4, macOS 27.0.1: Metal's validation stops a NaN or infinite origin; the other fields are taken by the same rule | 1: `crates/metal2vulkan-runtime/src/render_encoder.rs (checked)` | `-` | | `StencilAttachment` | A draw under a depth-stencil state that tests the stencil, in a pass without a stencil attachment | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M4, macOS 27.0.1: Metal's validation stops the draw; plain Metal tests it against a hidden stencil of 0 that the runtime does not keep | 1: `crates/metal2vulkan-runtime/src/render_encoder.rs (draw)` | `-` | ## 8. The runtime's `Limit` (`Error::Limit(Limit)`) @@ -388,7 +388,7 @@ Columns: | `BicubicTexels` | A dispatch or a draw whose function samples texture slot `slot` through a constexpr sampler with Metal's bicubic filter (`filter::bicubic`), where... | every device (a public call's own check of its arguments) | `ours`: each refused format's treatment is built when a guest binds one | 2: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch)`, `crates/metal2vulkan-runtime/src/render_encoder.rs (find)` | `-` | | `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, swizzled or not; each other kind is built when a replay stream binds one | 1: `crates/metal2vulkan-runtime/src/texture.rs (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 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 | 6: `crates/metal2vulkan-runtime/src/pass.rs (check)`, `crates/metal2vulkan-runtime/src/pass.rs (ops)` (+4) | `-` | -| `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, 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` | 12: `crates/metal2vulkan-runtime/src/render_encoder.rs (attachment_reads, 3 sites)`, `crates/metal2vulkan-runtime/src/render_encoder.rs (draw)` (+8) | `-` | +| `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, 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` | 12: `crates/metal2vulkan-runtime/src/render_encoder.rs (attachment_reads, 3 sites)`, `crates/metal2vulkan-runtime/src/render_encoder.rs (checked)` (+8) | `-` | | `LinearPlanePass` | A render pass over a surface plane that renders as a linear colour attachment alone, in a shape the device does not render... | at the device's limit | `device`: VK_NV_linear_color_attachment renders such a format as a colour attachment only "as long as all the color attachments in the render pass instance have VK_IMAGE_TILING_LINEAR tiling"; the RTX 3090's driver lost the device rendering a linear colour attachment beside a depth or stencil attachment | 1: `crates/metal2vulkan-runtime/src/pass.rs (check)` | `-` | ## Appendix: every site @@ -627,7 +627,7 @@ Each refusal's sites, with the function that builds it. - `rt:Refusal::IndexBufferOffset`: `crates/metal2vulkan-runtime/src/render_encoder.rs (draw)` - `rt:Refusal::TessellationFactorOffset`: `crates/metal2vulkan-runtime/src/render_encoder.rs (set_tessellation_factor_buffer)` - `rt:Refusal::ArgumentPlace`: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (draw)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (indirect)` -- `rt:Refusal::ViewportNotFinite`: `crates/metal2vulkan-runtime/src/render_encoder.rs (set_viewport)` +- `rt:Refusal::ViewportNotFinite`: `crates/metal2vulkan-runtime/src/render_encoder.rs (checked)` - `rt:Refusal::StencilAttachment`: `crates/metal2vulkan-runtime/src/render_encoder.rs (draw)` - `rt:Limit::BlockLen`: `crates/metal2vulkan-runtime/src/import.rs (check_len)`; `crates/metal2vulkan-runtime/src/memory.rs (round)`; `crates/metal2vulkan-runtime/src/surface.rs (copy_form)`; `crates/metal2vulkan-runtime/src/surface.rs (dma_buf_in_place)` - `rt:Limit::BlockIds`: `crates/metal2vulkan-runtime/src/memory.rs (allocation_number)`; `crates/metal2vulkan-runtime/src/memory.rs (number)` @@ -674,6 +674,6 @@ Each refusal's sites, with the function that builds it. - `rt:Gap::BicubicTexels`: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (find)` - `rt:Gap::TextureView`: `crates/metal2vulkan-runtime/src/texture.rs (view)` - `rt:Gap::RenderPass`: `crates/metal2vulkan-runtime/src/pass.rs (check)`; `crates/metal2vulkan-runtime/src/pass.rs (ops)`; `crates/metal2vulkan-runtime/src/pass.rs (resolve)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (later_store)`; `crates/metal2vulkan-runtime/src/texture.rs (attachment_view)`; `crates/metal2vulkan-runtime/src/texture.rs (resolve_attachment)` -- `rt:Gap::Draw`: `crates/metal2vulkan-runtime/src/render_encoder.rs (attachment_reads, 3 sites)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (draw)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (draw_patches)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (draw_patches_indirect)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (set_scissor_rects)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (set_triangle_fill_mode)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (set_viewport)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (set_viewports)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (set_visibility_result_mode)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (shadow_copies)` +- `rt:Gap::Draw`: `crates/metal2vulkan-runtime/src/render_encoder.rs (attachment_reads, 3 sites)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (checked)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (draw)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (draw_patches)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (draw_patches_indirect)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (set_scissor_rects)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (set_triangle_fill_mode)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (set_viewports)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (set_visibility_result_mode)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (shadow_copies)` - `rt:Gap::LinearPlanePass`: `crates/metal2vulkan-runtime/src/pass.rs (check)` diff --git a/scripts/regen-device-profiles/regen_device_profiles.py b/scripts/regen-device-profiles/regen_device_profiles.py index 1e78cbd86..eead074dd 100755 --- a/scripts/regen-device-profiles/regen_device_profiles.py +++ b/scripts/regen-device-profiles/regen_device_profiles.py @@ -117,7 +117,8 @@ RUNTIME_FLOOR = { "fragmentStoresAndAtomics", "alphaToOne", "logicOp", "fullDrawIndexUint32", "imageCubeArray", "depthBiasClamp", "drawIndirectFirstInstance", "depthClamp", "shaderClipDistance", "tessellationShader", "shaderTessellationAndGeometryPointSize", - "largePoints", "dualSrcBlend", "sampleRateShading", "vertexPipelineStoresAndAtomics")}, + "largePoints", "dualSrcBlend", "sampleRateShading", "vertexPipelineStoresAndAtomics", + "multiViewport")}, "VkPhysicalDeviceVulkan11Features": {member: True for member in ( "storageBuffer16BitAccess", "multiview", "shaderDrawParameters")}, "VkPhysicalDeviceVulkan12Features": {member: True for member in ( @@ -130,7 +131,7 @@ RUNTIME_FLOOR = { "shaderInt8", "storageBuffer8BitAccess", "scalarBlockLayout", "uniformBufferStandardLayout", "vulkanMemoryModel", "vulkanMemoryModelDeviceScope", "shaderSubgroupExtendedTypes", "timelineSemaphore", "hostQueryReset", - "shaderOutputLayer")}, + "shaderOutputLayer", "shaderOutputViewportIndex")}, "VkPhysicalDeviceVulkan13Features": {member: True for member in ( "subgroupSizeControl", "computeFullSubgroups", "robustImageAccess", "shaderDemoteToHelperInvocation", "shaderTerminateInvocation",