From d806c0a792f8861bbf22178e5bd6912838bb65cd Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Tue, 3 Nov 2026 07:53:36 -0800 Subject: [PATCH] Write Boolean visibility results as the device's nonzero query result, without the resolve Metal's Boolean visibility result is nonzero where any sample passed and 0 otherwise. The Apple M3 Max writes 1; Metal on the AMD Radeon Pro 5300M and the Intel UHD Graphics 630 (macOS 26.7.1, the reims-vgpu team's probes) writes the samples that passed. The runtime had a crate-owned dispatch (bind::visibility_resolve_module) after every pass with a Boolean offset whose only job was to rewrite that word to exactly 1. Under AGENTS.md rule 1 the device's native answer is the only form: a Boolean result is now the imprecise occlusion query's own result, which Vulkan states as "When any samples are passed, boolean queries will return a non-zero result value, otherwise a result value of zero is returned" (occlusionQueryPrecise). Across a split pass's render pass instances the combine still ORs the continuations, so zero stays zero exactly where no instance passed a sample. Counting queries stay precise. - Runtime: the resolve's plan, uploads, sets and dispatch are gone from visibility.rs, and OwnedModule::VisibilityResolve from owned_kernel.rs. A pass with no continuation now records only vkCmdCopyQueryPoolResults. The combine's in-place words are declared as shader reads and writes for every combined offset (they were declared only for Boolean ones). A new precision degradation, DeviceBooleanVisibility (device-boolean-visibility), is announced where a pass's Boolean results record; its catalogue entry is in docs/API.md section 9 and a device-gaps row in docs/FAST-PATHS.md, as for the other native-answer kinds. - Translator: bind/visibility_resolve.rs and its tests are deleted (VisibilityResolve, VisibilityResolveModule, visibility_resolve_module leave the public surface). Its shared helpers (windows, words_buffer, u32_value) move into visibility_combine.rs; the combine's plan tests take the two refusal cases only the resolve's tests held. No translation output changes. - Conformance: a new Loosening::Nonzero, and an allowance may name one element of a byte region as /. The visibility family loosens each Boolean result's word, and only that word, by Nonzero, justified by device-boolean-visibility, which its Boolean cases also declare at the notices site. Every other word still compares exactly. No recording changes. README and docs/CONFORMANCE-COVERAGE.md (regenerated) say so. - Validation lane: every Boolean expectation reads the word by its contract (visibility::by_contract: nonzero and not the buffer's starting word reads as 1), in visibility, framebuffer_fetch, host_bytes, depth_never and amplified_draws; the notice is a new lane site (visibility::BOOLEANS) taken by boolean_results_announce_the_device_s_value and expected where other tests' notice sets are exact. boolean_results_are_copied_with_no_dispatch counts one query result copy and no vkCmdDispatch for a pass of two Boolean offsets. Verified: cargo clippy --workspace --all-targets --all-features -D warnings with --cfg m2v_gpu; the runtime's degradation catalogue and site tests, the translator's combine, owned-division, resolve-helper users', api_surface and api_signatures tests; the conformance suite's 1024 device-free tests. The device lane tests run on the M3 with the next step. (cherry picked from commit a4976cdc3734c21c1b9ed4cf603bbf6bab2523f0) (cherry picked from commit 34e44e3a12a46e6ff4b651cc4689002690d680fc) --- crates/metal2vulkan-conformance/README.md | 6 + .../metal2vulkan-conformance/src/allowance.rs | 18 + .../src/cases/visibility.rs | 81 ++++- .../metal2vulkan-conformance/src/compare.rs | 23 +- crates/metal2vulkan-conformance/src/tests.rs | 35 ++ .../metal2vulkan-runtime/src/degradation.rs | 15 +- .../metal2vulkan-runtime/src/owned_kernel.rs | 15 +- crates/metal2vulkan-runtime/src/visibility.rs | 136 ++++---- .../src/runtime_lane/amplified_draws.rs | 25 +- .../src/runtime_lane/degrade_notices.rs | 6 +- .../src/runtime_lane/depth_never.rs | 22 +- .../src/runtime_lane/framebuffer_fetch.rs | 22 +- .../src/runtime_lane/host_bytes.rs | 11 +- .../src/runtime_lane/visibility.rs | 139 +++++++- .../src/bind/color_resolve/extended_tests.rs | 2 +- .../src/bind/color_resolve/tests.rs | 4 +- .../src/bind/color_resolve/word_tests.rs | 2 +- .../src/bind/depth_stencil_resolve/tests.rs | 2 +- crates/metal2vulkan/src/bind/mod.rs | 14 +- .../src/bind/replay/predication.rs | 2 +- .../src/bind/visibility_combine.rs | 101 +++++- .../src/bind/visibility_combine/tests.rs | 10 + .../src/bind/visibility_resolve.rs | 312 ------------------ .../src/bind/visibility_resolve/tests.rs | 178 ---------- .../metal2vulkan/src/tests/owned_divisions.rs | 1 - crates/metal2vulkan/tests/api_signatures.tsv | 21 +- crates/metal2vulkan/tests/api_surface.rs | 3 - docs/API.md | 13 +- docs/CONFORMANCE-COVERAGE.md | 12 +- docs/FAST-PATHS.md | 3 +- 30 files changed, 545 insertions(+), 689 deletions(-) delete mode 100644 crates/metal2vulkan/src/bind/visibility_resolve.rs delete mode 100644 crates/metal2vulkan/src/bind/visibility_resolve/tests.rs diff --git a/crates/metal2vulkan-conformance/README.md b/crates/metal2vulkan-conformance/README.md index 325adb9ff..f1ba30513 100644 --- a/crates/metal2vulkan-conformance/README.md +++ b/crates/metal2vulkan-conformance/README.md @@ -45,6 +45,12 @@ venue whose device answers so, that says what differs, whose answer it is, and w recorded bound covers it. A tolerance justified by a note is for a note whose documentation gives a bound validation may hold, and is never wider than that bound. +A tolerance may name one element of a byte region rather than the whole site: the element's path is +the site's and its byte offset in the region, `case/pass-0/words/24`. The visibility family loosens +each `Boolean` result's word that way, and only by `Loosening::Nonzero` (zero exactly where Metal's +word is zero), the bound `device-boolean-visibility` documents; every other word of the buffer +still compares exactly. + A site where plain Metal answered a call and we returned a typed error is a **refusal**, and no allowance can make it anything else: it counts in its own verdict and is never compliant. diff --git a/crates/metal2vulkan-conformance/src/allowance.rs b/crates/metal2vulkan-conformance/src/allowance.rs index 419e68006..b4e0ef59d 100644 --- a/crates/metal2vulkan-conformance/src/allowance.rs +++ b/crates/metal2vulkan-conformance/src/allowance.rs @@ -206,6 +206,11 @@ pub enum Loosening { Absolute(f64), /// The value may be any of these. AnyOf(Vec), + /// An integer zero exactly where the recorded one is: any nonzero value stands for any other. + /// For a value whose contract states only whether it is zero, such as a `Boolean` visibility + /// result, which is the device's own nonzero value where Metal's M3 Max writes 1 + /// (`device-boolean-visibility`). + Nonzero, /// The value is not compared. The justification still has to hold, and the report says the /// field went unchecked. Unchecked, @@ -233,6 +238,11 @@ impl Allowance { } /// Whether the allowance covers the site at `path` (node names from the root, `/`-separated). + /// + /// An element of a byte region is addressed as its site's path and its byte offset in the + /// region, `/` in decimal (`case/pass-0/words/24`, the eight bytes from offset 24 + /// of a `U64` region): an allowance there covers that element alone, where one at the site + /// covers every element. pub fn covers(&self, path: &str) -> bool { match self.path.strip_suffix("/*") { Some(prefix) => path == prefix || path.starts_with(&format!("{prefix}/")), @@ -245,6 +255,14 @@ impl Allowance { match &self.loosening { Loosening::Unchecked => true, Loosening::AnyOf(values) => values.contains(actual), + Loosening::Nonzero => { + let zero = |value: &Value| match *value { + Value::Uint(word) => Some(word == 0), + Value::Int(word) => Some(word == 0), + _ => None, + }; + matches!((zero(expected), zero(actual)), (Some(a), Some(b)) if a == b) + } Loosening::Ulps(ulps) => within_ulps(expected, actual, *ulps), Loosening::Absolute(bound) => within_absolute(expected, actual, *bound), } diff --git a/crates/metal2vulkan-conformance/src/cases/visibility.rs b/crates/metal2vulkan-conformance/src/cases/visibility.rs index 9bf25f1bf..0bedd13ea 100644 --- a/crates/metal2vulkan-conformance/src/cases/visibility.rs +++ b/crates/metal2vulkan-conformance/src/cases/visibility.rs @@ -12,6 +12,13 @@ //! the recordings against the lane's words, which is the evidence the port owes the lane. A fresh //! answer that disagrees with the lane is a finding about one of the two chips, not a nuisance. //! +//! Every word compares exactly but a `Boolean` result's: the M3 Max writes 1 where a sample +//! passed, and the runtime the device's own nonzero value, which it announces +//! (`device-boolean-visibility`), whose documentation states the bound the comparison holds: zero +//! exactly where Metal's word is zero ([`Loosening::Nonzero`] at that word alone, `boolean_words`). +//! Not a native note of the suite's set: the note's bound is exact, so a case names it at the +//! words it loosens. +//! //! The shapes, each its own case so a device that lacks precise occlusion queries loses only the //! counted rows: //! @@ -64,6 +71,7 @@ use crate::transcript::{ByteLayout, Digest, Element, Node, Observed, Sites, Valu use metal2vulkan::metal::state::DepthStencilDescriptor; use metal2vulkan::metal::{CompareFunction, PixelFormat, PrimitiveType}; use metal2vulkan_runtime::{Degradation, StoreAction, VisibilityResultMode}; +use std::collections::BTreeSet; /// The owned fixture the lane draws with: `rt6_full` takes a depth and a slope as one `float2` at /// vertex buffer 0, and `rt6_white` returns white. @@ -351,6 +359,28 @@ const PASS_NOTICES: &[Degradation] = &[ Degradation::DontCareStore, ]; +/// Each pass's `Boolean` results, as (the pass's index, the result's offset): the offsets whose +/// last mode set, in that pass or one before it, is `Boolean`, which the pass's `words` site holds. +fn boolean_words(shape: &Shape) -> Vec<(usize, u64)> { + let mut held: BTreeSet = BTreeSet::new(); + let mut out = Vec::new(); + for (index, acts) in shape.passes.iter().enumerate() { + for act in *acts { + match act { + Act::Mode(BOOL, offset) => { + held.insert(*offset); + } + Act::Mode(COUNT, offset) => { + held.remove(offset); + } + Act::Mode(..) | Act::Draw { .. } | Act::DrawIndirect => {} + } + } + out.extend(held.iter().map(|&offset| (index, offset))); + } + out +} + /// The bytes a buffer of `words` 64-bit words starts as. fn start(words: usize) -> Vec { vec![UNWRITTEN; 8 * words] @@ -594,9 +624,10 @@ impl Case for Visibility { } fn allowances(&self) -> Vec { - // The notices site alone: a visibility result is a number Metal wrote, and a number that - // differs is a bug, not a near-equivalent. Nothing else here is loosened. - PASS_NOTICES + // The notices site, and each `Boolean` result's word by its contract (the module docs): a + // visibility result is a number Metal wrote, and any other number that differs is a bug, + // not a near-equivalent. Nothing else here is loosened. + let mut all: Vec = PASS_NOTICES .iter() .map(|kind| { Allowance::new( @@ -605,7 +636,21 @@ impl Case for Visibility { Justification::notice(*kind), ) }) - .collect() + .collect(); + let booleans = boolean_words(self.shape); + if !booleans.is_empty() { + all.push(crate::replay::notice_allowance( + Degradation::DeviceBooleanVisibility.code(), + )); + } + for (index, offset) in booleans { + all.push(Allowance::new( + format!("case/pass-{index}/words/{offset}"), + Loosening::Nonzero, + Justification::notice(Degradation::DeviceBooleanVisibility), + )); + } + all } fn shaders(&self) -> Result, String> { @@ -930,12 +975,13 @@ mod tests { } /// Every case of the family is in the table, states its inputs, and loosens **only** its - /// notices site. + /// notices site and its `Boolean` results' words, each by its contract alone. /// /// A visibility result is a number Metal wrote; a number that differs is a bug, never a - /// near-equivalent. A case that ever loosened its words would fail here. + /// near-equivalent, but that a `Boolean` result's nonzero value is the device's. A case that + /// ever loosened another word, or a `Boolean` one by more than its contract, would fail here. #[test] - fn every_case_is_tabled_and_loosens_its_notices_alone() { + fn every_case_is_tabled_and_loosens_its_notices_and_boolean_words_alone() { for case in all() { assert!( TABLE.iter().any(|(name, _)| *name == case.name()), @@ -950,16 +996,33 @@ mod tests { ); assert_eq!(case.metal_source(), MetalSource::Run); case.shaders().unwrap(); + let words: Vec = boolean_words(case.shape) + .iter() + .map(|(index, offset)| format!("case/pass-{index}/words/{offset}")) + .collect(); for allowance in case.allowances() { + if words.contains(&allowance.path) { + assert_eq!(allowance.loosening, Loosening::Nonzero, "{}", case.name()); + assert_eq!( + allowance.justified_by, + Justification::notice(Degradation::DeviceBooleanVisibility), + "{}", + case.name() + ); + continue; + } assert_eq!( allowance.path, format!("case/{NOTICES_SITE}/*"), - "{}: an allowance outside the notices site", + "{}: an allowance outside the notices site and the Boolean words", case.name() ); match &allowance.justified_by { Justification::Degradation(code) => assert!( - PASS_NOTICES.iter().any(|kind| kind.code() == code), + PASS_NOTICES + .iter() + .chain([&Degradation::DeviceBooleanVisibility]) + .any(|kind| kind.code() == code), "{}: {code} is not a visibility-pass notice", case.name() ), diff --git a/crates/metal2vulkan-conformance/src/compare.rs b/crates/metal2vulkan-conformance/src/compare.rs index 6654faa23..4e32f571d 100644 --- a/crates/metal2vulkan-conformance/src/compare.rs +++ b/crates/metal2vulkan-conformance/src/compare.rs @@ -581,7 +581,10 @@ impl Walk<'_> { else { continue; }; - if self.allowed(path, &expected, &actual) { + // An allowance of the site covers the element, and so does one of the element + // itself, `/` (`Allowance::covers`). + let element = format!("{path}/{at}"); + if self.allowed_at(path, Some(&element), &expected, &actual) { continue; } count += 1; @@ -905,11 +908,27 @@ impl Walk<'_> { /// where none does, and then by the first of them, so the report names a justification the /// case actually claimed. fn allowed(&mut self, path: &str, metal: &Value, ours: &Value) -> bool { + self.allowed_at(path, None, metal, ours) + } + + /// [`allowed`](Self::allowed) of an element of the byte region at `path`, which an allowance + /// covers at the site or at `element`, the element's own path (`Allowance::covers`). What it + /// records is the site's. + fn allowed_at( + &mut self, + path: &str, + element: Option<&str>, + metal: &Value, + ours: &Value, + ) -> bool { let mut covering = self .allowances .iter() .enumerate() - .filter(|(_, allowance)| allowance.covers(path) && allowance.within(metal, ours)) + .filter(|(_, allowance)| { + (allowance.covers(path) || element.is_some_and(|at| allowance.covers(at))) + && allowance.within(metal, ours) + }) .peekable(); if covering.peek().is_none() { return false; diff --git a/crates/metal2vulkan-conformance/src/tests.rs b/crates/metal2vulkan-conformance/src/tests.rs index 540b07ff3..e86e5dcfb 100644 --- a/crates/metal2vulkan-conformance/src/tests.rs +++ b/crates/metal2vulkan-conformance/src/tests.rs @@ -1543,6 +1543,41 @@ fn an_accepted_difference_in_the_document_justifies_a_loosened_field() { ); } +/// A `Nonzero` allowance at one element of a byte region (`/`) takes any nonzero +/// value for the recorded nonzero one there, and nothing else: a zero there, or a moved element +/// beside it, still diverges. +#[test] +fn a_nonzero_allowance_at_an_element_loosens_that_element_alone() { + let kind = Degradation::DeviceBooleanVisibility; + let case = WordsCase { + allowances: vec![ + crate::replay::notice_allowance(kind.code()), + Allowance::new( + "case/output/4", + Loosening::Nonzero, + Justification::notice(kind), + ), + ], + ..WordsCase::new("words", 2) + }; + let recording = recording_of(&case, case.transcript(words(&[1, 1]), "Completed", &[]), 3); + let verdict = |answer: &[u32]| { + let mut side = StubSide::new(words(answer)).announcing(&[kind]); + replay_against(&case, &mut side, &recording) + .unwrap() + .verdict + }; + let loosened = verdict(&[1, 16]); + assert!(matches!(loosened, Verdict::Announced { .. }), "{loosened}"); + for (answer, why) in [ + ([1, 0], "a zero for a nonzero"), + ([16, 1], "the element beside it"), + ] { + let held = verdict(&answer); + assert!(matches!(held, Verdict::Divergent { .. }), "{why}: {held}"); + } +} + #[test] fn the_accepted_differences_are_read_from_the_document() { let entries = accepted_differences(); diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 6397412d8..a4a9b9b0f 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -2187,7 +2187,20 @@ degradations! { /// command; the payload names the draw and its colors. VisibilityCountPerColor = "visibility-count-per-color", Precision, "the result is Metal's count multiplied by the colors the draw writes; a `Boolean` \ - result is Metal's"; + result keeps its contract"; + /// A pass writes a `Boolean` visibility result (`visibility.rs`): where a sample passed, + /// its word is the device's occlusion query result without + /// `VK_QUERY_CONTROL_PRECISE_BIT`, which Vulkan states only as nonzero ("When any samples + /// are passed, boolean queries will return a non-zero result value, otherwise a result + /// value of zero is returned", `occlusionQueryPrecise`), ORed over the pass's render pass + /// instances; where none passed, 0. That is Metal's `Boolean` contract, and Metal's own + /// nonzero value is not one value either: an Apple M3 Max (macOS 27.0.1) writes 1, Metal + /// on the AMD Radeon Pro 5300M and the Intel UHD Graphics 630 (macOS 26.7.1) the samples + /// that passed. The device's value is the only form; no dispatch rewrites it. Announced + /// where the pass's results record; the payload names the pass's first `Boolean` offset. + DeviceBooleanVisibility = "device-boolean-visibility", Precision, + "a `Boolean` visibility result where a sample passed is the device's nonzero value, \ + which can be other than the 1 an Apple M3 Max writes; where none passed it is 0"; /// A device whose float functions are not Metal's own (not MoltenVK, /// `DriverDeviation::MetalFloatFunctions`): Metal flushes a `float` product, fused /// multiply-add or `ldexp` whose exact value lies below `2^-126` to the zero of its sign, diff --git a/crates/metal2vulkan-runtime/src/owned_kernel.rs b/crates/metal2vulkan-runtime/src/owned_kernel.rs index 656fbd275..de1806240 100644 --- a/crates/metal2vulkan-runtime/src/owned_kernel.rs +++ b/crates/metal2vulkan-runtime/src/owned_kernel.rs @@ -45,11 +45,8 @@ use std::collections::HashMap; /// A crate-owned module the runtime dispatches. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum OwnedModule { - /// `bind::visibility_resolve_module`: a pass's `Boolean` visibility results, made Metal's 1 - /// or 0 in place. - VisibilityResolve, - /// `bind::visibility_combine_module`: a split pass's continuation queries, ORed into their - /// results. + /// `bind::visibility_combine_module`: a split pass's continuation queries, summed or ORed + /// into their results. VisibilityCombine, /// `bind::index_bounds_plan_module`: an indexed indirect draw's index bounds plan /// (`index_bounds.rs`). @@ -240,11 +237,6 @@ impl OwnedModule { /// [`images`](Self::images)), and its push bytes. fn build(self, device: &Device) -> Result<(Vec, u32, u32), Error> { match self { - OwnedModule::VisibilityResolve => { - let module = metal2vulkan::bind::visibility_resolve_module(device.compile_device()) - .map_err(Error::Compile)?; - Ok((module.spirv.to_vec(), 2, 0)) - } OwnedModule::VisibilityCombine => { let module = metal2vulkan::bind::visibility_combine_module(device.compile_device()) .map_err(Error::Compile)?; @@ -537,7 +529,6 @@ impl OwnedKernel { /// Every kernel one device has made. #[derive(Default)] pub(super) struct OwnedKernels { - visibility_resolve: Option, visibility_combine: Option, index_bounds_plan: Option, index_bounds_fill: Option, @@ -591,7 +582,6 @@ impl OwnedKernels { /// Destroy every kernel; the device is idle, and is destroyed next. pub(super) fn destroy(&self, raw: &ash::Device) { for kernel in [ - self.visibility_resolve, self.visibility_combine, self.index_bounds_plan, self.index_bounds_fill, @@ -751,7 +741,6 @@ impl OwnedKernels { /// per key). fn slot(&mut self, which: OwnedModule) -> Option<&mut Option> { Some(match which { - OwnedModule::VisibilityResolve => &mut self.visibility_resolve, OwnedModule::VisibilityCombine => &mut self.visibility_combine, OwnedModule::IndexBoundsPlan => &mut self.index_bounds_plan, OwnedModule::IndexBoundsFill => &mut self.index_bounds_fill, diff --git a/crates/metal2vulkan-runtime/src/visibility.rs b/crates/metal2vulkan-runtime/src/visibility.rs index 7e384df10..63663bd2f 100644 --- a/crates/metal2vulkan-runtime/src/visibility.rs +++ b/crates/metal2vulkan-runtime/src/visibility.rs @@ -1,16 +1,22 @@ //! Visibility results (`setVisibilityResultMode:offset:`). //! //! Metal writes, at the end of a pass, one 64-bit result at each offset the encoder set a mode at: -//! in `Boolean` mode 1 when any sample of the draws while it was set passed and 0 otherwise, in -//! `Counting` mode the samples that passed; an offset set with no draw after it gets 0, an offset -//! the encoder never set keeps its bytes, and a later pass rewrites only its own offsets (measured -//! on an M4 with macOS 27.0.1). +//! in `Boolean` mode a nonzero value when any sample of the draws while it was set passed and 0 +//! otherwise, in `Counting` mode the samples that passed; an offset set with no draw after it gets +//! 0, an offset the encoder never set keeps its bytes, and a later pass rewrites only its own +//! offsets (measured on an M4 with macOS 27.0.1). The nonzero `Boolean` value is the device's: an +//! Apple M3 Max writes 1, Metal on the AMD Radeon Pro 5300M and the Intel UHD Graphics 630 +//! (macOS 26.7.1) the samples that passed, and the runtime the device's occlusion query's result +//! (`Degradation::DeviceBooleanVisibility`). //! //! - **Queries.** Each mode set is an occlusion query of the encoder's own pools, begun in the //! draws' secondary command buffer when the mode is set and ended when the next one is set, at //! `Disabled`, or at `end_encoding`: one query spans every draw of its offset. A `Counting` //! query is precise (`VK_QUERY_CONTROL_PRECISE_BIT`): its result is the samples that passed, -//! Metal's count. A `Boolean` query is imprecise: its count is only ever zero or not. +//! Metal's count. A `Boolean` query is imprecise: Vulkan states its result only as zero or not +//! ("When any samples are passed, boolean queries will return a non-zero result value, +//! otherwise a result value of zero is returned", `occlusionQueryPrecise`), which is Metal's +//! `Boolean` contract, so its result is the offset's word as the device writes it. //! `end_encoding` resets the pools before the pass (query commands run in submission order, so //! the queries begun later see the reset). //! - **Continuations.** A query begins and ends in one subpass, so where the pass splits into @@ -26,13 +32,12 @@ //! (`vkCmdCopyQueryPoolResults` waiting for each), consecutive ones in one copy, and every //! continuation's to a word of an upload region, whose words one dispatch of the crate-owned //! `bind::visibility_combine_module` combines into their offsets' -//! (`bind::VisibilityCombine::plan`): summed for a `Counting` offset, ORed for a `Boolean` one, -//! since an imprecise query's count is any nonzero value. A `Counting` result is then as -//! copied; the `Boolean` offsets are made Metal's 1 or 0 in place by one dispatch of the -//! crate-owned `bind::visibility_resolve_module` (more only where the offsets span more than -//! one storage binding reaches, `bind::VisibilityResolve::plan`), whose targets are uploaded. -//! Where a no-copy buffer's bytes start at no multiple of 8 of its `VkBuffer`, the results land -//! in an upload region first and are copied on (`Landing`). +//! (`bind::VisibilityCombine::plan`; more only where the offsets span more than one storage +//! binding reaches): summed for a `Counting` offset, ORed for a `Boolean` one, since an +//! imprecise query's count is any nonzero value and a sum of such counts could wrap to zero. A +//! pass with no continuation records no dispatch. Where a no-copy buffer's bytes start at no +//! multiple of 8 of its `VkBuffer`, the results land in an upload region first and are copied on +//! (`Landing`). //! - **Refusals** (`Invalid`, measured): a pass without a visibility result buffer, an offset //! whose 8 bytes run past the buffer, and an offset the encoder took before in the other mode. //! `Counting` needs a precise query: `Unsupported`, naming `occlusionQueryPrecise`, where the @@ -41,7 +46,8 @@ //! ANV): its precise query counts each sample once for every color output the fragment shader //! writes. A draw counted by a `Counting` query whose fragment variant writes more than one //! color attachment runs, and the device announces `Degradation::VisibilityCountPerColor`: its -//! result is the samples times those colors, not divided back. `Boolean` results are exact. +//! result is the samples times those colors, not divided back. `Boolean` results keep their +//! contract: zero where no sample passed. //! - **An offset taken again in its mode** stops Metal's validation ("using the same offset ... //! twice in the same command encoder is not allowed"); plain Metal adds the draws since to its //! result: `Counting` sums them (16 and 16 write 32), `Boolean` writes 1 when either passed a @@ -65,13 +71,12 @@ use super::exit_guard; use super::owned_kernel::{OwnedModule, OwnedSets}; use super::release; use super::tracker::{Access, Barrier, Use, UseRange}; -use super::upload::Upload; use super::{Buffer, Device}; use ash::vk; -use metal2vulkan::bind::{ContinuedResult, VisibilityCombine, VisibilityResolve}; +use metal2vulkan::bind::{ContinuedResult, VisibilityCombine}; use metal2vulkan::device::VkFeature; use metal2vulkan::error::{Capability, Feature, Unsupported}; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; /// `MTLVisibilityResultMode`. #[non_exhaustive] @@ -80,7 +85,9 @@ pub enum VisibilityResultMode { /// `MTLVisibilityResultModeDisabled`: the draws write no result. #[default] Disabled, - /// `MTLVisibilityResultModeBoolean`: 1 when any sample passed, else 0. + /// `MTLVisibilityResultModeBoolean`: nonzero when any sample passed, else 0. The nonzero value + /// is the device's occlusion query's, where an Apple M3 Max writes 1 + /// (`Degradation::DeviceBooleanVisibility`). Boolean, /// `MTLVisibilityResultModeCounting`: the samples that passed. Counting, @@ -647,7 +654,7 @@ impl Visibility { Ok((self.pools.len() - 1, 0)) } - /// The results' copies and resolves, planned before anything of the pass records: `None` + /// The results' copies and combine, planned before anything of the pass records: `None` /// when the encoder took no offset. The draws' command buffer must have ended its query /// ([`Visibility::end`]). pub(super) fn plan(self, core: &mut EncoderCore) -> Result, Error> { @@ -667,10 +674,9 @@ impl Visibility { let Some(buffer) = buffer.filter(|_| !taken.is_empty()) else { return Ok(None); }; - let device = core.device().clone(); let landing = Landing::new(core, &buffer, &taken)?; - // Consecutive queries of one pool at consecutive offsets copy at once. The copies and - // resolves address the landing region; the uses, the Metal buffer. + // Consecutive queries of one pool at consecutive offsets copy at once. The copies and the + // combine address the landing region; the uses, the Metal buffer. let mut copies: Vec = Vec::new(); for t in &taken { push_copy( @@ -682,53 +688,10 @@ impl Visibility { ); } let combine = combine(core, &pools, &taken, &continued, &landing, &mut copies)?; - let booleans: Vec = taken - .iter() - .filter(|t| t.boolean) - .map(|t| landing.at(t.offset)) - .collect(); - let limits = &device.properties().description.limits; - let resolves = VisibilityResolve::plan( - &booleans, - limits.min_storage_buffer_offset_alignment, - limits.max_storage_buffer_range, - limits.max_compute_work_group_count[0], - ) - .ok_or_else(|| internal("visibility offsets the resolve cannot bind"))?; - let resolve = if resolves.is_empty() { - None - } else { - let kernel = device.owned_kernel(OwnedModule::VisibilityResolve)?; - let mut uploads: Vec = Vec::with_capacity(resolves.len()); - { - let mut state = core.command_buffer().state(); - for r in &resolves { - let bytes = r.target_bytes(); - uploads.push(state.uploads.upload(&device, &bytes, bytes.len() as u64)?); - } - } - let target = landing.raw; - let ranges: Vec> = resolves - .iter() - .zip(&uploads) - .map(|(r, upload)| { - vec![ - (upload.raw(), upload.offset(), 4 * r.targets.len() as u64), - (target, r.dest_range.offset, r.dest_range.range), - ] - }) - .collect(); - let sets = OwnedSets::write(&device, &kernel, &ranges)?; - let groups = resolves.iter().map(|r| r.group_count).collect(); - Some(Dispatches { - pipeline: kernel.pipeline, - layout: kernel.layout, - sets, - groups, - }) - }; + // The offsets whose words the combine reads and writes in place. + let combined: BTreeSet = continued.iter().map(|c| c.taken).collect(); let mut uses = Vec::with_capacity(taken.len()); - for t in &taken { + for (index, t) in taken.iter().enumerate() { let (identity, range) = buffer.tracked(t.offset..t.offset + RESULT_BYTES); let range = UseRange::Bytes(range); let copy = Access::new( @@ -741,7 +704,7 @@ impl Visibility { range.clone(), copy, )); - if t.boolean { + if combined.contains(&index) && landing.onward.is_empty() { let shader = Access::new( vk::PipelineStageFlags2::COMPUTE_SHADER, vk::AccessFlags2::SHADER_STORAGE_READ | vk::AccessFlags2::SHADER_STORAGE_WRITE, @@ -755,13 +718,14 @@ impl Visibility { }); } } + let boolean = taken.iter().find(|t| t.boolean).map(|t| t.offset); Ok(Some(Results { pools: QueryPools(pools), buffer, landing, copies, combine, - resolve, + boolean, uses, })) } @@ -770,7 +734,7 @@ impl Visibility { /// Where a pass's results land, at multiples of 8 as Vulkan copies them: in the buffer's /// `VkBuffer`, or, where a no-copy buffer's bytes start past such a multiple (`Buffer::base`), in /// an upload region laid out as the buffer from the first offset taken, whence one more copy, which -/// takes any offset, moves each result into the buffer after the resolve. +/// takes any offset, moves each result into the buffer after the combine. struct Landing { /// The `VkBuffer` the results land in. raw: vk::Buffer, @@ -959,7 +923,7 @@ fn combine( })) } -/// The dispatches of one crate-owned kernel after a pass: the combine's or the resolve's. +/// The dispatches of the crate-owned combine after a pass. struct Dispatches { pipeline: vk::Pipeline, layout: vk::PipelineLayout, @@ -974,7 +938,9 @@ pub(super) struct Results { landing: Landing, copies: Vec, combine: Option, - resolve: Option, + /// The first offset taken in `Boolean` mode, whose word is the device's own nonzero value + /// where a sample passed (`Degradation::DeviceBooleanVisibility`). + boolean: Option, uses: Vec>, } @@ -991,8 +957,9 @@ impl Results { } } - /// Record the copies and resolves in `core`'s command buffer after the pass, between barriers - /// from everything before and to everything after, and hold their objects until it completes. + /// Record the copies and the combine in `core`'s command buffer after the pass, between + /// barriers from everything before and to everything after, and hold their objects until it + /// completes. pub(super) fn record(self, core: &mut EncoderCore) { let Results { pools, @@ -1000,11 +967,22 @@ impl Results { landing, copies, combine, - resolve, + boolean, uses, } = self; + if let Some(offset) = boolean { + core.device() + .degrade(Degradation::DeviceBooleanVisibility, || { + let object = format!("the Boolean visibility result at offset {offset}"); + let reason = "a Boolean result is the device's occlusion query result, which \ + Vulkan states only as zero or not without \ + VK_QUERY_CONTROL_PRECISE_BIT" + .to_owned(); + (object, reason) + }); + } let mut stages = vk::PipelineStageFlags2::TRANSFER; - if combine.is_some() || resolve.is_some() { + if combine.is_some() { stages |= vk::PipelineStageFlags2::COMPUTE_SHADER; } core.device().shared().counts.pool_compiled( @@ -1032,8 +1010,8 @@ impl Results { vk::QueryResultFlags::TYPE_64 | vk::QueryResultFlags::WAIT, ); } - // The continuations ORed into their results, then the `Boolean` ones resolved. - for dispatches in [&combine, &resolve].into_iter().flatten() { + // The continuations combined into their results. + if let Some(dispatches) = &combine { Barrier::everything().record(raw, command_buffer); raw.cmd_bind_pipeline( command_buffer, @@ -1060,7 +1038,7 @@ impl Results { }); core.barrier(Barrier::everything()); core.retain(pools); - for dispatches in [combine, resolve].into_iter().flatten() { + if let Some(dispatches) = combine { core.retain(dispatches.sets); } core.retain(buffer); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/amplified_draws.rs b/crates/metal2vulkan-validation/src/runtime_lane/amplified_draws.rs index fbce80b6f..d7305111b 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/amplified_draws.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/amplified_draws.rs @@ -320,6 +320,14 @@ impl Lane { Degradation::SharedInSystemMemory, shared_in_system_memory(&self.device), ), + ( + Degradation::DeviceBooleanVisibility, + matches!( + case.visibility, + Visibility::Before(VisibilityResultMode::Boolean) + | Visibility::After(VisibilityResultMode::Boolean) + ), + ), ]); kinds.extend(self.made(case)); kinds @@ -570,12 +578,18 @@ impl Lane { drop(executed); let visibility = match case.visibility { Visibility::Off => None, - Visibility::Before(_) => Some(0), - Visibility::After(_) => Some(8), + Visibility::Before(mode) => Some((0, mode)), + Visibility::After(mode) => Some((8, mode)), } - .map(|offset| { + .map(|(offset, mode)| { let bytes = read_buffer(&results, offset, 8).unwrap(); - u64::from_le_bytes(bytes.try_into().unwrap()) + let word = u64::from_le_bytes(bytes.try_into().unwrap()); + // A `Boolean` word by its contract: the device's nonzero value where a sample passed. + let booleans: &[usize] = match mode { + VisibilityResultMode::Boolean => &[0], + _ => &[], + }; + super::visibility::by_contract(vec![word], booleans, 0xdead)[0] }); drop(layers); Ok(Stored { @@ -1197,7 +1211,8 @@ fn what_multiview_does_not_express_draws_one_amplification_at_a_time() { /// A visibility result over amplified draws counts the samples of every amplification, as one query /// over draws of one amplification each does (a Metal probe on the M3 Max and an M4: 16 for one /// amplification of the 16-pixel target, 32 for two into two layers or into one, and with a depth -/// test; 1 for `Boolean`). A mode set after a draw amplified as views leaves its texels as Metal's. +/// test; 1 for `Boolean`, the device's nonzero value read by its contract). A mode set after a draw +/// amplified as views leaves its texels as Metal's. #[test] fn a_visibility_result_counts_every_amplification() { use VisibilityResultMode::{Boolean, Counting}; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs index a8de7adae..65c5822b2 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs @@ -43,7 +43,8 @@ //! states whose stages an archive holds from two adds in `binary_archives` ([`ARCHIVES`]), //! texture views of another component layout shadowed in `view_reinterpretation` //! ([`VIEW_SHADOWS`]), executions of an indirect command buffer from one command -//! with two lengths in `visibility` ([`REPEATED_STARTS`]), resources made with Metal's private +//! with two lengths in `visibility` ([`REPEATED_STARTS`]), passes writing a `Boolean` visibility +//! result there ([`BOOLEANS`]), resources made with Metal's private //! option bit here ([`PRIVATE_OPTION`]), indexed indirect draws of bytes a draw wrote with no //! barrier in `indirect_draws` ([`UNORDERED_DRAWS`]), pipeline states whose functions read an //! argument their function constants removed in `absent_reads` ([`ABSENT_READS`]), a slot's @@ -215,7 +216,7 @@ use super::two_plane_copies::TWO_PLANE_COPIES; use super::unorm_depth_bias::{UNORM_DEPTH_BIAS, UNORM_DEPTH_ROUNDING}; use super::view_reinterpretation::VIEW_SHADOWS; use super::viewport_ranges::{NAN_DEPTH, UNCLAMPED_BIAS, VERTEX_CLAMPS}; -use super::visibility::REPEATED_STARTS; +use super::visibility::{BOOLEANS, REPEATED_STARTS}; use super::wide_points::POINT_GUARD_BAND; use super::word_samples_msaa::WORD_RESOLVE; use super::ycbcr_passes::YCBCR_PASSES; @@ -504,6 +505,7 @@ fn every_kind_has_a_site_a_lane_test_takes() { &ARCHIVES, &VIEW_SHADOWS, &REPEATED_STARTS, + &BOOLEANS, &PRIVATE_OPTION, &IN_PLACE_VERTEX_READS, &FRAGMENTS_BEFORE_GEOMETRY, diff --git a/crates/metal2vulkan-validation/src/runtime_lane/depth_never.rs b/crates/metal2vulkan-validation/src/runtime_lane/depth_never.rs index 655774c08..a0cd32cae 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/depth_never.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/depth_never.rs @@ -260,6 +260,18 @@ fn each(color: [u8; 4]) -> Vec { color.repeat(16) } +/// The result `left` holds as `mode`'s contract reads it (`visibility::by_contract`): a `Boolean` +/// word nonzero where a sample passed, the device's own value, against Metal's 1. +fn by_contract(left: &Left, mode: VisibilityResultMode) -> Option { + let booleans: &[usize] = match mode { + VisibilityResultMode::Boolean => &[0], + _ => &[], + }; + let unwritten = u64::from_le_bytes([0xab; 8]); + left.visibility + .map(|word| super::visibility::by_contract(vec![word], booleans, unwritten)[0]) +} + /// Whether the device refused `Counting` results for want of precise occlusion queries /// (`visibility.rs`' lane), printed. fn counting_refused(left: &Result, device: &str) -> bool { @@ -345,7 +357,7 @@ fn a_never_depth_test_without_an_attachment_counts_no_sample() { if counting_refused(&left, &device) { continue; } - assert_eq!(left.unwrap().visibility, Some(result), "{name}"); + assert_eq!(by_contract(&left.unwrap(), mode), Some(result), "{name}"); } // One offset over drawn and undrawn samples: the `Never` draw's query pauses around it. for (mode, result) in [(boolean, 1), (counting, 32)] { @@ -360,7 +372,11 @@ fn a_never_depth_test_without_an_attachment_counts_no_sample() { continue; } let left = left.unwrap(); - assert_eq!(left.visibility, Some(result), "{mode:?} around never"); + assert_eq!( + by_contract(&left, mode), + Some(result), + "{mode:?} around never" + ); assert_eq!(left.fragments, 48, "{mode:?} around never"); assert_eq!(left.color, each(RED), "{mode:?} around never"); } @@ -597,7 +613,7 @@ fn executed_never_draws_count_no_sample() { continue; } let left = left.unwrap(); - assert_eq!(left.visibility, Some(result), "{name} on {device}"); + assert_eq!(by_contract(&left, mode), Some(result), "{name} on {device}"); assert_eq!(left.fragments, fragments, "{name} on {device}"); assert_eq!(left.color, each(color), "{name} on {device}"); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/framebuffer_fetch.rs b/crates/metal2vulkan-validation/src/runtime_lane/framebuffer_fetch.rs index c078704fc..163aa1cb5 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/framebuffer_fetch.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/framebuffer_fetch.rs @@ -1106,11 +1106,23 @@ fn visibility_results_span_split_passes() { want.extend(&pattern[24..]); eprintln!("refused: Counting across a split on {device}: no occlusionQueryPrecise"); } - assert_eq!( - read_buffer(&results, 0, 32).unwrap(), - want, - "the results on {device}" - ); + // The three `Boolean` words by their contract (`visibility::by_contract`): nonzero where a + // sample passed, the device's own value. + let read = read_buffer(&results, 0, 32).unwrap(); + let words: Vec = read + .as_chunks::<8>() + .0 + .iter() + .map(|w| u64::from_le_bytes(*w)) + .collect(); + let unwritten = u64::from_le_bytes(pattern[..8].try_into().unwrap()); + let mut read: Vec = + super::visibility::by_contract(words[..3].to_vec(), &[0, 1, 2], unwritten) + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + read.extend(words[3].to_le_bytes()); + assert_eq!(read, want, "the results on {device}"); let ran = Ok(lane.read(&target, (0, 0), 4, BlitOption::None)); let texel = if precise { 0.5f32 } else { 0.25 }; expect( diff --git a/crates/metal2vulkan-validation/src/runtime_lane/host_bytes.rs b/crates/metal2vulkan-validation/src/runtime_lane/host_bytes.rs index 695aeba94..f99344a98 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/host_bytes.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/host_bytes.rs @@ -496,8 +496,8 @@ fn draws_read_indices_and_arguments_where_their_bytes_lie() { /// Visibility results in buffers 4 bytes past a page (Vulkan copies results only to multiples of /// 8, so they land in an upload region and are copied on) and 8 past it (in place): probe 1's -/// `Boolean` words, 1 for a covering draw, 0 for one covering nothing, and an offset never set -/// keeps its bytes. +/// `Boolean` words, 1 for a covering draw (the device's nonzero value, read by its contract), 0 for +/// one covering nothing, and an offset never set keeps its bytes. #[test] fn visibility_results_land_where_their_bytes_lie() { use VisibilityResultMode::Boolean; @@ -526,6 +526,7 @@ fn visibility_results_land_where_their_bytes_lie() { .map(|c| u64::from_le_bytes(*c)) .collect(); let u = 0xaaaa_aaaa_aaaa_aaaa; + let words = super::visibility::by_contract(words, &[1, 3], u); assert_eq!(words, [u, 1, u, 0], "results {at} bytes past a page"); vis.check_around("the visibility buffer"); } @@ -537,8 +538,9 @@ fn visibility_results_land_where_their_bytes_lie() { /// texture buffers 2 past one (staged on every venue), two indexed draws over indices 2 past one /// (copied before the pass), and two passes' visibility results 4 past one (landed in an upload /// region). The notices fail nothing; `degrade_notices` checks each one's form. Beside them the -/// device announces what the steps force: the white pipeline's making's kinds and the cases' -/// `Shared` buffers' system memory. +/// device announces what the steps force: the white pipeline's making's kinds, the cases' +/// `Shared` buffers' system memory, and the passes' `Boolean` results +/// (`visibility::BOOLEANS`). #[test] fn host_byte_degradations_are_announced_once_per_device_and_kind() { use VisibilityResultMode::Boolean; @@ -586,6 +588,7 @@ fn host_byte_degradations_are_announced_once_per_device_and_kind() { shared_in_system_memory(device), )]); first.extend(probe.made(WHITE)); + first.extend(super::visibility::BOOLEANS); assert_made_once(&messages, &HOST_BYTES, &first); quiet(probe, &messages); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/visibility.rs b/crates/metal2vulkan-validation/src/runtime_lane/visibility.rs index 300f4783d..df6492acf 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/visibility.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/visibility.rs @@ -5,7 +5,8 @@ //! Metal's API validation), drawn with the owned fixture `rt6_render_state` into a 4² target: the //! fullscreen triangle covers every pixel, and the same draw from vertex 3 covers none. Each //! visibility buffer starts as 0xaa bytes, and its words after the command buffer are compared with -//! the ones Metal wrote: `Boolean` writes 1 or 0 at each offset the encoder set, `Counting` the +//! the ones Metal wrote: `Boolean` writes 1 or 0 at each offset the encoder set (the runtime the +//! device's nonzero value for 1, compared by [`by_contract`]), `Counting` the //! samples that passed (16 for the fullscreen triangle, 48 for three instances of it, 64 at 4x), an //! offset set with no draw after it gets 0, an offset never set keeps its bytes, a later pass //! rewrites only its own offsets, and an offset taken again in its mode, which Metal's validation @@ -17,7 +18,7 @@ use std::collections::BTreeSet; use super::degrade_notices::{ - assert_made_once, assert_once, made_render_kinds, shared_in_system_memory, + assert_made_once, assert_once, made_once, made_render_kinds, shared_in_system_memory, }; use super::read_buffer; use super::render_state::{quiet, texture, validated, Pipe, Probe, PASS, WHITE}; @@ -79,6 +80,25 @@ fn set(encoder: &mut RenderCommandEncoder, mode: VisibilityResultMode, offset: u encoder.set_visibility_result_mode(mode, offset).unwrap(); } +/// `words` as their modes' contracts read them, to compare with the words an Apple M3 Max wrote: +/// each word at an index of `booleans`, a `Boolean` result, 1 where it is nonzero (the device's own +/// value where a sample passed, `Degradation::DeviceBooleanVisibility`) and not `unwritten`, the +/// buffer's starting word, so a result never written still differs; every other word as it is. +pub(super) fn by_contract(mut words: Vec, booleans: &[usize], unwritten: u64) -> Vec { + for &index in booleans { + let word = &mut words[index]; + if *word != 0 && *word != unwritten { + *word = 1; + } + } + words +} + +/// [`by_contract`] of a buffer that started as [`UNWRITTEN`]. +fn read(buffer: &Buffer, booleans: &[usize]) -> Vec { + by_contract(words(buffer), booleans, UNWRITTEN) +} + /// The words Metal wrote in each pass (the module docs). #[test] fn boolean_results_store_metals_words() { @@ -102,7 +122,7 @@ fn boolean_results_store_metals_words() { }) .unwrap(); let u = UNWRITTEN; - assert_eq!(words(&vis), [1, u, u, 0, u, 0, u, 1]); + assert_eq!(read(&vis, &[0, 3, 5, 7]), [1, u, u, 0, u, 0, u, 1]); // A second pass over the buffer rewrites only its own offset. probe .try_run_with(PASS, Some(&vis), |p, e, h| { @@ -110,7 +130,7 @@ fn boolean_results_store_metals_words() { draw(p, e, h, WHITE, 0.5, true); }) .unwrap(); - assert_eq!(words(&vis), [1, 1, u, 0, u, 0, u, 1]); + assert_eq!(read(&vis, &[0, 1, 3, 5, 7]), [1, 1, u, 0, u, 0, u, 1]); // Probe 5's vis_revisit_boolean_then_none and vis_revisit_none_then_boolean: offset 0 taken // again after offset 8 writes 1 where either of its draws passed a sample. @@ -129,7 +149,7 @@ fn boolean_results_store_metals_words() { draw(p, e, h, WHITE, 0.5, again); }) .unwrap(); - assert_eq!(words(&vis), metal, "{name}"); + assert_eq!(read(&vis, &[0, 1]), metal, "{name}"); } // Probe 1's visibility_occluded: a draw behind the cleared depth (0.5 against 0.25 under @@ -146,7 +166,7 @@ fn boolean_results_store_metals_words() { draw(p, e, h, WHITE.depth(depth), 0.125, true); }) .unwrap(); - assert_eq!(words(&vis), [1, 0]); + assert_eq!(read(&vis, &[0, 1]), [1, 0]); // Probe 5's vis_indirect_no_instances, as Boolean: an indirect draw of no instances. let vis = visibility_buffer(&probe, 1); @@ -162,7 +182,95 @@ fn boolean_results_store_metals_words() { h.push(depth); }) .unwrap(); - assert_eq!(words(&vis), [0]); + assert_eq!(read(&vis, &[0]), [0]); + quiet(probe, &messages); +} + +/// The kind a pass writing a `Boolean` result takes ([`boolean_results_announce_the_device_s_value`]). +pub(super) const BOOLEANS: [Degradation; 1] = [Degradation::DeviceBooleanVisibility]; + +/// A pass writing a `Boolean` result announces [`BOOLEANS`] once on a device, however many passes +/// write one, naming the pass's first `Boolean` offset; a pass of `Counting` results alone does not. +/// Beside it the device announces what the steps force: the white pipeline's making's kinds and +/// the visibility buffer's system memory. +#[test] +fn boolean_results_announce_the_device_s_value() { + use VisibilityResultMode::{Boolean, Counting}; + let (messages, _cache, probe) = validated(); + let precise = probe + .device + .properties() + .description + .has(metal2vulkan::device::VkFeature::OcclusionQueryPrecise); + let vis = visibility_buffer(&probe, 2); + if precise { + probe + .try_run_with(PASS, Some(&vis), |p, e, h| { + set(e, Counting, 0); + draw(p, e, h, WHITE, 0.5, true); + }) + .unwrap(); + assert!( + !messages.take_notices().iter().any(|m| m + .degradation + .as_ref() + .is_some_and(|n| n.degradation == BOOLEANS[0])), + "a pass of Counting results alone" + ); + } + for offset in [8, 0] { + probe + .try_run_with(PASS, Some(&vis), |p, e, h| { + set(e, Boolean, offset); + draw(p, e, h, WHITE, 0.5, true); + }) + .unwrap(); + } + let mut first = probe.made(WHITE); + if shared_in_system_memory(&probe.device) { + first.insert(Degradation::SharedInSystemMemory); + } + let notices = made_once(&messages, &BOOLEANS, &first); + let notice = notices + .iter() + .find_map(|m| { + m.degradation + .as_ref() + .filter(|n| n.degradation == BOOLEANS[0]) + }) + .unwrap(); + assert_eq!(notice.object, "the Boolean visibility result at offset 8"); + quiet(probe, &messages); +} + +/// A pass's `Boolean` results are its queries' own words: one `vkCmdCopyQueryPoolResults` of +/// both offsets' queries and no dispatch after it, the word of the draw that passed a sample +/// nonzero and the other's 0. +#[test] +fn boolean_results_are_copied_with_no_dispatch() { + use VisibilityResultMode::Boolean; + let (messages, _cache, probe) = validated(); + let vis = visibility_buffer(&probe, 2); + let before = probe.device.work_counts().commands_recorded; + probe + .try_run_with(PASS, Some(&vis), |p, e, h| { + set(e, Boolean, 0); + draw(p, e, h, WHITE, 0.5, true); + set(e, Boolean, 8); + draw(p, e, h, WHITE, 0.5, false); + }) + .unwrap(); + let after = probe.device.work_counts().commands_recorded; + assert_eq!( + ( + after.cmd_copy_query_pool_results - before.cmd_copy_query_pool_results, + after.cmd_dispatch - before.cmd_dispatch, + ), + (1, 0), + "query result copies and dispatches" + ); + let words = words(&vis); + assert!(words[0] != 0 && words[1] == 0, "{words:?}"); quiet(probe, &messages); } @@ -220,7 +328,7 @@ fn counting_results_store_metals_counts() { return; } let u = UNWRITTEN; - assert_eq!(words(&vis), [16, 0, 32, 48, 0, 1, u, u], "on {device}"); + assert_eq!(read(&vis, &[5]), [16, 0, 32, 48, 0, 1, u, u], "on {device}"); // Probe 1's visibility_occluded, counted: a draw behind the cleared depth passes no sample. let vis = visibility_buffer(&probe, 2); @@ -344,7 +452,7 @@ fn command_buffers_released_at_completion_leave_nothing_read_later() { }) .unwrap(); let expected = if first { [1, 0] } else { [0, 1] }; - assert_eq!(words(&vis), expected, "round {round}"); + assert_eq!(read(&vis, &[0, 1]), expected, "round {round}"); } quiet(probe, &messages); } @@ -388,8 +496,8 @@ fn results_are_ordered_with_the_command_buffers_later_commands() { .unwrap(); assert_eq!(command_buffer.error(), None); drop(held); - assert_eq!(words(&vis), [1, 1]); - assert_eq!(words(©), [1, 1]); + assert_eq!(read(&vis, &[0, 1]), [1, 1]); + assert_eq!(read(©, &[0, 1]), [1, 1]); quiet(probe, &messages); } @@ -455,7 +563,7 @@ fn visibility_modes_are_refused_as_metal_refuses_them() { }) .unwrap(); let u = UNWRITTEN; - assert_eq!(words(&vis), [1, u, 1, u, u, u, u, 0]); + assert_eq!(read(&vis, &[0, 2, 7]), [1, u, 1, u, u, u, u, 0]); quiet(probe, &messages); } @@ -545,7 +653,7 @@ fn a_pass_that_executes_commands_keeps_its_visibility_results() { draw(p, e, h, WHITE, 0.5, false); }) .unwrap(); - assert_eq!(words(&vis), [1, 0, UNWRITTEN]); + assert_eq!(read(&vis, &[0, 1]), [1, 0, UNWRITTEN]); assert_eq!( stored.color, alone.color, "the command draws after the white" @@ -619,7 +727,7 @@ fn executions_count_in_the_mode_set_at_them() { e.execute_commands_in_buffer(&icb, 0..1).unwrap(); }) .unwrap(); - assert_eq!(words(&vis), [1], "bool_icb on {device}"); + assert_eq!(read(&vis, &[0]), [1], "bool_icb on {device}"); // bool_none: `Boolean`, then `Disabled`, then the command. let vis = visibility_buffer(&probe, 1); probe @@ -630,7 +738,7 @@ fn executions_count_in_the_mode_set_at_them() { e.execute_commands_in_buffer(&icb, 0..1).unwrap(); }) .unwrap(); - assert_eq!(words(&vis), [0], "bool_none on {device}"); + assert_eq!(read(&vis, &[0]), [0], "bool_none on {device}"); // The counted cases, where the device counts: whether it did. let counted = |cases: &[CountedCase<'_>]| { for (name, length, encode, want) in cases { @@ -726,6 +834,7 @@ fn executions_count_in_the_mode_set_at_them() { if ran { let mut kinds: Vec = execution_kinds(&probe, true).into_iter().collect(); kinds.extend(REPEATED_STARTS); + kinds.extend(BOOLEANS); assert_once(¬ices, &kinds); let notice = notices .iter() diff --git a/crates/metal2vulkan/src/bind/color_resolve/extended_tests.rs b/crates/metal2vulkan/src/bind/color_resolve/extended_tests.rs index 65f2c9e0c..cab97d05d 100644 --- a/crates/metal2vulkan/src/bind/color_resolve/extended_tests.rs +++ b/crates/metal2vulkan/src/bind/color_resolve/extended_tests.rs @@ -115,7 +115,7 @@ const RESOLVED_OUT: ResourceSlot = ResourceSlot { fn kernel(form: ExtendedRange, samples: u32) -> TypedModule { let mut b = ModuleBuilder::new(); let t = Types::new(&mut b).expect("types"); - let words = super::super::visibility_resolve::words_buffer; + let words = super::super::visibility_combine::words_buffer; let input = words(&mut b, SAMPLES_IN, t.u32_).expect("in"); let output = words(&mut b, RESOLVED_OUT, t.u32_).expect("out"); let uvec3 = b diff --git a/crates/metal2vulkan/src/bind/color_resolve/tests.rs b/crates/metal2vulkan/src/bind/color_resolve/tests.rs index 892ddf9a6..e84c238e2 100644 --- a/crates/metal2vulkan/src/bind/color_resolve/tests.rs +++ b/crates/metal2vulkan/src/bind/color_resolve/tests.rs @@ -243,7 +243,7 @@ fn arithmetic_module( .then(|| SrgbTables::declare(&mut b, t, format, source)) .transpose() .expect("tables"); - let words = super::super::visibility_resolve::words_buffer; + let words = super::super::visibility_combine::words_buffer; let input = words(&mut b, SAMPLES_IN, t.u32_).expect("in"); let output = words(&mut b, RESOLVED_OUT, t.u32_).expect("out"); let uvec3 = b @@ -830,7 +830,7 @@ fn word_kernel( let srgb = ColorResolveFormat::of(Format::R8G8B8A8_SRGB).expect("closed"); let tables = SrgbTables::declare(&mut b, t, srgb, ResolveSource::InputAttachment).expect("tables"); - let buffer = super::super::visibility_resolve::words_buffer; + let buffer = super::super::visibility_combine::words_buffer; let input = buffer(&mut b, SAMPLES_IN, t.u32_).expect("in"); let output = buffer(&mut b, RESOLVED_OUT, t.u32_).expect("out"); let uvec3 = b diff --git a/crates/metal2vulkan/src/bind/color_resolve/word_tests.rs b/crates/metal2vulkan/src/bind/color_resolve/word_tests.rs index 660afd737..0a4d9fcee 100644 --- a/crates/metal2vulkan/src/bind/color_resolve/word_tests.rs +++ b/crates/metal2vulkan/src/bind/color_resolve/word_tests.rs @@ -94,7 +94,7 @@ const RESOLVED_OUT: ResourceSlot = ResourceSlot { fn kernel(word: WordAttachment, samples: u32) -> TypedModule { let mut b = ModuleBuilder::new(); let t = Types::new(&mut b).expect("types"); - let buffer = super::super::visibility_resolve::words_buffer; + let buffer = super::super::visibility_combine::words_buffer; let input = buffer(&mut b, SAMPLES_IN, t.u32_).expect("in"); let output = buffer(&mut b, RESOLVED_OUT, t.u32_).expect("out"); let uvec3 = b diff --git a/crates/metal2vulkan/src/bind/depth_stencil_resolve/tests.rs b/crates/metal2vulkan/src/bind/depth_stencil_resolve/tests.rs index 8eea8d062..4d361c663 100644 --- a/crates/metal2vulkan/src/bind/depth_stencil_resolve/tests.rs +++ b/crates/metal2vulkan/src/bind/depth_stencil_resolve/tests.rs @@ -125,7 +125,7 @@ fn pick_module(pick: DepthPick, samples: u32) -> TypedModule { let mut b = ModuleBuilder::new(); let u32_ = super::super::depth_stencil_copy::u32_ty(&mut b).expect("u32"); let f32_ = b.ty(Type::Float { width: 32 }).expect("f32"); - let words = super::super::visibility_resolve::words_buffer; + let words = super::super::visibility_combine::words_buffer; let input = words(&mut b, DEPTHS_IN, u32_).expect("in"); let output = words(&mut b, PICKED_OUT, u32_).expect("out"); let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 }).expect("uvec3"); diff --git a/crates/metal2vulkan/src/bind/mod.rs b/crates/metal2vulkan/src/bind/mod.rs index 662a9af2e..03c4fc012 100644 --- a/crates/metal2vulkan/src/bind/mod.rs +++ b/crates/metal2vulkan/src/bind/mod.rs @@ -54,11 +54,11 @@ //! one index buffer; indirect draws over one arguments buffer, [`IndirectGatherDraw`]) can take //! one [`IndexGather`] dispatch of [`index_gather_module`] for all of them instead (an indirect //! run's after one [`index_gather_plan_module`] dispatch, [`IndexGatherPlanModule`]), and one -//! indexed draw each. A pass's `Boolean` visibility results are query -//! counts copied to their offsets and made Metal's 1 or 0 in place by a [`VisibilityResolve`] -//! dispatch of [`visibility_resolve_module`]; where a split pass continues a result's query in a -//! later render pass instance, a [`VisibilityCombine`] dispatch of [`visibility_combine_module`] -//! first ORs the continuations' counts into it. A pass whose fetching draws read a multisampled +//! indexed draw each. A pass's visibility results are its queries' results copied to their +//! offsets, a `Boolean` one the device's own nonzero value where a sample passed; where a split +//! pass continues a result's query in a later render pass instance, a [`VisibilityCombine`] +//! dispatch of [`visibility_combine_module`] sums the continuations' counts into a `Counting` +//! result and ORs them into a `Boolean` one. A pass whose fetching draws read a multisampled //! attachment's sample planes (`StorageAttachmentView::SamplePlanes`) splits the attachment into //! them with [`planes_split_module`] and merges them back with [`planes_merge_modules`], through //! the [`PlanesCopy`] view of its texel size. A multisampled depth or stencil aspect moves @@ -174,7 +174,6 @@ pub(crate) mod tile_map; pub(crate) mod tiled_texels; pub(crate) mod two_plane_texels; pub(crate) mod visibility_combine; -pub(crate) mod visibility_resolve; pub(crate) mod ycbcr_convert; pub(crate) mod ycbcr_in_place; pub(crate) mod ycbcr_refresh; @@ -330,9 +329,6 @@ pub use two_plane_texels::{two_plane_texels_module, PlaneLayout, TwoPlaneTexelsM pub use visibility_combine::{ visibility_combine_module, ContinuedResult, VisibilityCombine, VisibilityCombineModule, }; -pub use visibility_resolve::{ - visibility_resolve_module, VisibilityResolve, VisibilityResolveModule, -}; pub use ycbcr_convert::{ ycbcr_convert_floats_module, ycbcr_convert_module, ycbcr_read, ycbcr_texel, YCbCrCodes, YCbCrConversion, YCbCrConvertModule, YCbCrMatrix, YCbCrOutput, YCbCrPlanes, YCbCrRange, diff --git a/crates/metal2vulkan/src/bind/replay/predication.rs b/crates/metal2vulkan/src/bind/replay/predication.rs index 4a7b96985..046838369 100644 --- a/crates/metal2vulkan/src/bind/replay/predication.rs +++ b/crates/metal2vulkan/src/bind/replay/predication.rs @@ -83,7 +83,7 @@ use std::sync::Arc; use super::{ at, count_loop, count_words, k32, k64, load32, load64, no_binding, store32, wide, Types, }; -use crate::bind::visibility_resolve::words_buffer; +use crate::bind::visibility_combine::words_buffer; use crate::budget::{Budget, Meter}; use crate::device::profile::BufferAccess; use crate::device::requirements::Requirements; diff --git a/crates/metal2vulkan/src/bind/visibility_combine.rs b/crates/metal2vulkan/src/bind/visibility_combine.rs index 9cccfe388..011784cc1 100644 --- a/crates/metal2vulkan/src/bind/visibility_combine.rs +++ b/crates/metal2vulkan/src/bind/visibility_combine.rs @@ -5,10 +5,10 @@ //! queries: the first, copied to the result's offset as every query is, and its continuations, //! one per later instance, each copied to a word of a scratch buffer of the consumer's //! (`vkCmdCopyQueryPoolResults`). One dispatch of [`visibility_combine_module`] then combines each -//! result's continuation words into its word. A `Boolean` result ORs them, before its -//! [`VisibilityResolve`] makes it Metal's 1 or 0: an imprecise query's count is any nonzero value -//! when a sample passed, and a sum of such counts could wrap to zero. A `Counting` result, of -//! precise queries, sums them: the samples that passed in every instance. +//! result's continuation words into its word. A `Boolean` result ORs them: an imprecise query's +//! count is any nonzero value when a sample passed, and a sum of such counts could wrap to zero, so +//! the OR is zero exactly where no instance passed a sample. A `Counting` result, of precise +//! queries, sums them: the samples that passed in every instance. //! //! **The module** (one per device). One `GLCompute` entry `main` with local size //! ([`VisibilityCombineModule::LOCAL_SIZE`], 1, 1), no push constants, and three storage buffers in @@ -30,12 +30,11 @@ //! //! **Synchronization** (consumer): the result and continuation copies' `TRANSFER_WRITE` → //! `SHADER_STORAGE_READ` and `SHADER_STORAGE_WRITE` in `COMPUTE_SHADER` before the combine, and -//! the upload's host write before the submission; then the combine's writes → -//! `SHADER_STORAGE_READ` and `SHADER_STORAGE_WRITE` before the resolve. +//! the upload's host write before the submission; the combine's writes are then ordered before the +//! buffer's later uses as any compute write is. use std::sync::Arc; -use super::visibility_resolve::{u32_value, windows, words_buffer, VisibilityResolve}; use crate::bind::instantiate::BufferRange; use crate::budget::{Budget, Meter}; use crate::device::requirements::Requirements; @@ -45,8 +44,14 @@ use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage, Symbol}; use crate::spirv::builder::constructs::{ArmEnd, ArmFn, LoopFn, LoopSpec}; use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; use crate::spirv::error::BResult; -use crate::spirv::ids::Value; -use crate::spirv::ir::{BinOp, ExecMode, ExecModel, IoDir, MemAccess, Type, TypedModule}; +use crate::spirv::ids::{GlobalId, TypeId, Value}; +use crate::spirv::ir::{ + natural_layout, BinOp, ExecMode, ExecModel, IoDir, LayoutRule, MemAccess, StorageClass, Type, + TypedModule, +}; + +/// Bytes of one result in the visibility buffer, and of one continuation word. +const RESULT_BYTES: u64 = 8; /// One dispatch of [`visibility_combine_module`]: it combines, in place, the continuation words /// of the results whose words lie in `dest_range` of the visibility buffer. @@ -103,10 +108,13 @@ impl VisibilityCombine { /// The dispatches that combine `results` (distinct offsets, any order), each binding the /// visibility buffer at an offset aligned to `alignment` (`minStorageBufferOffsetAlignment`) /// over at most `max_range` bytes (`maxStorageBufferRange`) and dispatching at most - /// `max_groups` workgroups (`maxComputeWorkGroupCount[0]`), as [`VisibilityResolve::plan`] - /// does. No dispatch when `results` is empty. `None` where [`VisibilityResolve::plan`] is, - /// when two results share an offset, or when a result's continuation words run past - /// `max_range` bytes of sources, which the consumer binds from their first word. + /// `max_groups` workgroups (`maxComputeWorkGroupCount[0]`). Results too far apart for one + /// binding, or too many for one dispatch, take more dispatches. No dispatch when `results` is + /// empty. `None` when an offset is not a multiple of 8 (Metal requires it of a visibility + /// offset), its word overflows, or one word does not fit `max_range` past its aligned offset, + /// or `max_groups` is 0; when two results share an offset; or when a result's continuation + /// words run past `max_range` bytes of sources, which the consumer binds from their first + /// word. pub fn plan( results: &[ContinuedResult], alignment: u64, @@ -118,7 +126,7 @@ impl VisibilityCombine { if sorted.windows(2).any(|w| w[0].offset == w[1].offset) { return None; } - let source_words = u64::from(max_range) / VisibilityResolve::RESULT_BYTES; + let source_words = u64::from(max_range) / RESULT_BYTES; if sorted .iter() .any(|r| u64::from(r.first) + u64::from(r.count) > source_words) @@ -154,6 +162,71 @@ impl VisibilityCombine { } } +/// The windows of the visibility buffer that bind `items`, each at Metal's offset of its result +/// (ascending, each once): each window binds from an offset aligned down to `alignment` (at +/// least 8) over at most `max_range` bytes, and takes at most `max_items` items, each with the +/// index of its 64-bit word inside the window. A dispatch per window. `None` when an offset is not +/// a multiple of 8, its word overflows, or one word does not fit `max_range` past its aligned +/// offset, or `max_items` is 0 (with an item). +fn windows( + items: impl IntoIterator, + alignment: u64, + max_range: u32, + max_items: u64, +) -> Option)>> { + let a = alignment.max(RESULT_BYTES); + let mut out: Vec<(BufferRange, Vec<(u32, T)>)> = Vec::new(); + for (offset, item) in items { + if !offset.is_multiple_of(RESULT_BYTES) { + return None; + } + let end = offset.checked_add(RESULT_BYTES)?; + let joins = out.last().is_some_and(|(range, taken)| { + end - range.offset <= u64::from(max_range) && (taken.len() as u64) < max_items + }); + if !joins { + let start = offset - offset % a; + if end - start > u64::from(max_range) || max_items == 0 { + return None; + } + let range = BufferRange { + offset: start, + range: 0, + }; + out.push((range, Vec::new())); + } + let (range, taken) = out.last_mut()?; + // Inside `max_range` (a `u32`) of the range's start: the index fits. + let index = u32::try_from((offset - range.offset) / RESULT_BYTES).ok()?; + taken.push((index, item)); + range.range = end - range.offset; + } + Some(out) +} + +/// A `Block { u32 words[]; }` storage buffer bound at `sym`. +pub(super) fn words_buffer( + b: &mut ModuleBuilder, + sym: ResourceSlot, + u32_: TypeId, +) -> BResult { + let rta = b.ty(Type::RuntimeArray { + elem: u32_, + stride: Some(4), + })?; + let layout = natural_layout(b.types(), LayoutRule::Std430, true, &[rta])?; + let block = b.ty(Type::Struct { + members: [rta].into(), + layout: Some(layout), + })?; + b.resource(sym, StorageClass::StorageBuffer, block) +} + +fn u32_value(f: &mut FunctionBuilder<'_>, v: u32) -> BResult { + let c = f.u32_const(v)?; + f.module().const_value(c) +} + /// The crate-owned continuation combine module of one device, validated like any output. #[non_exhaustive] #[derive(Clone, Debug, PartialEq, Eq)] diff --git a/crates/metal2vulkan/src/bind/visibility_combine/tests.rs b/crates/metal2vulkan/src/bind/visibility_combine/tests.rs index ac8ac5284..96b90eaee 100644 --- a/crates/metal2vulkan/src/bind/visibility_combine/tests.rs +++ b/crates/metal2vulkan/src/bind/visibility_combine/tests.rs @@ -225,6 +225,16 @@ fn the_plan_refuses_what_it_cannot_bind() { None, "no groups" ); + assert_eq!( + VisibilityCombine::plan(&[at(u64::MAX - 7, 0, 1, false)], 8, 64, 1), + None, + "an overflow" + ); + assert_eq!( + VisibilityCombine::plan(&[at(56, 0, 1, false)], 64, 32, 1), + None, + "a word past the range from its aligned offset" + ); } #[test] diff --git a/crates/metal2vulkan/src/bind/visibility_resolve.rs b/crates/metal2vulkan/src/bind/visibility_resolve.rs deleted file mode 100644 index c5d09049e..000000000 --- a/crates/metal2vulkan/src/bind/visibility_resolve.rs +++ /dev/null @@ -1,312 +0,0 @@ -//! The boolean resolve of a pass's visibility results (step 6's third part). -//! -//! Metal's visibility results are occlusion queries. In `Counting` mode Metal writes the samples -//! that passed, which a precise query's result is. In `Boolean` mode Metal writes exactly 1 when -//! any sample passed and 0 otherwise (measured on an M4 with macOS 27.0.1); a Vulkan query's result -//! is a count (any nonzero value without the precise flag), so a copy alone cannot give it. The -//! consumer copies every query's 64-bit result to its Metal offset in the visibility buffer -//! (`vkCmdCopyQueryPoolResults`), then records [`VisibilityResolve`] for the pass's `Boolean` -//! offsets: one dispatch of the crate-owned module [`visibility_resolve_module`] rewrites each of -//! their words in place as Metal's 1 or 0. `Counting` words are left as copied. -//! -//! **The module** (one per device). One `GLCompute` entry `main` with local size -//! ([`VisibilityResolveModule::LOCAL_SIZE`], 1, 1), no loops, no push constants, and two storage -//! buffers in set 0: -//! -//! | Binding | Buffer | Range | -//! |---|---|---| -//! | [`VisibilityResolveModule::TARGETS_BINDING`] | the consumer's upload of [`VisibilityResolve::targets`] | exactly its bytes | -//! | [`VisibilityResolveModule::DEST_BINDING`] | the visibility buffer | [`VisibilityResolve::dest_range`] | -//! -//! Invocation `i` below the targets' count rewrites the 64-bit word `targets[i]` of the bound -//! visibility range: 1 when either half is nonzero, else 0, with a high half of 0. The targets' -//! count is the bound table's length, so a range bound whole is the whole contract; a word past -//! the bound visibility range is skipped, so a wrongly bound range can never make the resolve -//! fault. Distinct targets touch distinct words, and the rewrite is idempotent. -//! -//! **Synchronization** (consumer): the result copies' `TRANSFER_WRITE` → `SHADER_STORAGE_READ` -//! and `SHADER_STORAGE_WRITE` in `COMPUTE_SHADER` before the resolve, and the upload's host write -//! before the submission; the resolve's writes are then ordered before the buffer's later uses as -//! any compute write is. - -use std::sync::Arc; - -use crate::bind::instantiate::BufferRange; -use crate::budget::{Budget, Meter}; -use crate::device::requirements::Requirements; -use crate::device::Device; -use crate::error::{Error, InternalError, InternalKind}; -use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage, Symbol}; -use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; -use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; -use crate::spirv::error::BResult; -use crate::spirv::ids::{GlobalId, TypeId, Value}; -use crate::spirv::ir::{ - natural_layout, BinOp, ExecMode, ExecModel, IoDir, LayoutRule, MemAccess, StorageClass, Type, - TypedModule, -}; - -/// One dispatch of [`visibility_resolve_module`]: it rewrites, in place, the `Boolean` results -/// of a pass whose words lie in `dest_range` of the visibility buffer. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct VisibilityResolve { - /// The range of the visibility buffer to bind at [`VisibilityResolveModule::DEST_BINDING`]: - /// from the first word's offset aligned down to `minStorageBufferOffsetAlignment` through - /// the last word's end. - pub dest_range: BufferRange, - /// The table to upload (little-endian `u32`s) and bind, exactly, at - /// [`VisibilityResolveModule::TARGETS_BINDING`]: the index of each result's 64-bit word - /// inside `dest_range`, ascending. - pub targets: Vec, - /// Workgroups to dispatch along x, each of [`VisibilityResolveModule::LOCAL_SIZE`] - /// invocations. - pub group_count: u32, -} - -impl VisibilityResolve { - /// Bytes of one result in the visibility buffer. - pub const RESULT_BYTES: u64 = 8; - - /// The dispatches that resolve the `Boolean` results at Metal's `offsets` (any order; - /// repeats resolve once), each binding the visibility buffer at an offset aligned to - /// `alignment` (`minStorageBufferOffsetAlignment`) over at most `max_range` bytes - /// (`maxStorageBufferRange`) and dispatching at most `max_groups` workgroups - /// (`maxComputeWorkGroupCount[0]`). Results too far apart for one binding, or too many for - /// one dispatch, take more dispatches. No dispatch when `offsets` is empty. `None` when an - /// offset is not a multiple of 8 (Metal requires it of a visibility offset), its word - /// overflows, or one word does not fit `max_range` past its aligned offset, or `max_groups` - /// is 0. - pub fn plan( - offsets: &[u64], - alignment: u64, - max_range: u32, - max_groups: u32, - ) -> Option> { - let mut sorted = offsets.to_vec(); - sorted.sort_unstable(); - sorted.dedup(); - let max_targets = - u64::from(max_groups).checked_mul(u64::from(VisibilityResolveModule::LOCAL_SIZE))?; - let items = sorted.into_iter().map(|offset| (offset, ())); - windows(items, alignment, max_range, max_targets)? - .into_iter() - .map(|(dest_range, items)| { - let targets: Vec = items.into_iter().map(|(index, ())| index).collect(); - let groups = - (targets.len() as u64).div_ceil(u64::from(VisibilityResolveModule::LOCAL_SIZE)); - Some(VisibilityResolve { - dest_range, - targets, - group_count: u32::try_from(groups).ok()?, - }) - }) - .collect() - } - - /// The targets as the bytes to upload. - pub fn target_bytes(&self) -> Vec { - self.targets.iter().flat_map(|t| t.to_le_bytes()).collect() - } -} - -/// The windows of the visibility buffer that bind `items`, each at Metal's offset of its result -/// (ascending, each once): each window binds from an offset aligned down to `alignment` (at -/// least 8) over at most `max_range` bytes, and takes at most `max_items` items, each with the -/// index of its 64-bit word inside the window. A dispatch per window: [`VisibilityResolve`]'s -/// and the continuation combine's (`visibility_combine.rs`). `None` when an offset is not a -/// multiple of 8, its word overflows, or one word does not fit `max_range` past its aligned -/// offset, or `max_items` is 0 (with an item). -pub(super) fn windows( - items: impl IntoIterator, - alignment: u64, - max_range: u32, - max_items: u64, -) -> Option)>> { - let a = alignment.max(VisibilityResolve::RESULT_BYTES); - let mut out: Vec<(BufferRange, Vec<(u32, T)>)> = Vec::new(); - for (offset, item) in items { - if !offset.is_multiple_of(VisibilityResolve::RESULT_BYTES) { - return None; - } - let end = offset.checked_add(VisibilityResolve::RESULT_BYTES)?; - let joins = out.last().is_some_and(|(range, taken)| { - end - range.offset <= u64::from(max_range) && (taken.len() as u64) < max_items - }); - if !joins { - let start = offset - offset % a; - if end - start > u64::from(max_range) || max_items == 0 { - return None; - } - let range = BufferRange { - offset: start, - range: 0, - }; - out.push((range, Vec::new())); - } - let (range, taken) = out.last_mut()?; - // Inside `max_range` (a `u32`) of the range's start: the index fits. - let index = - u32::try_from((offset - range.offset) / VisibilityResolve::RESULT_BYTES).ok()?; - taken.push((index, item)); - range.range = end - range.offset; - } - Some(out) -} - -/// The crate-owned visibility resolve module of one device, validated like any output. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct VisibilityResolveModule { - /// SPIR-V 1.5 words, entry point `main`, bindings numbered as below in set 0. - pub spirv: Arc<[u32]>, - /// What the module needs from the device (within every Vulkan 1.2 device). - pub requirements: Requirements, -} - -impl VisibilityResolveModule { - /// Descriptor set of every binding. - pub const SET: u32 = 0; - /// The table of targets, a storage buffer. - pub const TARGETS_BINDING: u32 = 0; - /// The visibility buffer, a storage buffer. - pub const DEST_BINDING: u32 = 1; - /// Invocations of one workgroup, along x. - pub const LOCAL_SIZE: u32 = 64; -} - -/// The binding symbol of the targets in the typed module -/// ([`VisibilityResolveModule::TARGETS_BINDING`]). -pub const TARGETS: ResourceSlot = ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: 0, -}; -/// The binding symbol of the visibility buffer in the typed module -/// ([`VisibilityResolveModule::DEST_BINDING`]). -pub const DEST: ResourceSlot = ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: 1, -}; - -/// A `Block { u32 words[]; }` storage buffer bound at `sym`. -pub(super) fn words_buffer( - b: &mut ModuleBuilder, - sym: ResourceSlot, - u32_: TypeId, -) -> BResult { - let rta = b.ty(Type::RuntimeArray { - elem: u32_, - stride: Some(4), - })?; - let layout = natural_layout(b.types(), LayoutRule::Std430, true, &[rta])?; - let block = b.ty(Type::Struct { - members: [rta].into(), - layout: Some(layout), - })?; - b.resource(sym, StorageClass::StorageBuffer, block) -} - -pub(super) fn u32_value(f: &mut FunctionBuilder<'_>, v: u32) -> BResult { - let c = f.u32_const(v)?; - f.module().const_value(c) -} - -/// The resolve module as a typed module, before serialization: the module -/// [`visibility_resolve_module`] serializes, which the CPU interpreter runs. Its bindings are the -/// symbols [`TARGETS`] and [`DEST`]. -pub fn typed_module() -> BResult { - let mut b = ModuleBuilder::new(); - let u32_ = b.ty(Type::Int { - width: 32, - signed: false, - })?; - let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?; - let targets = words_buffer(&mut b, TARGETS, u32_)?; - let dest = words_buffer(&mut b, DEST, u32_)?; - let invocation = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?; - let void = b.ty(Type::Void)?; - let mut f = b.function(void)?; - let zero = u32_value(&mut f, 0)?; - let one = u32_value(&mut f, 1)?; - let invocation = f.module().global_value(invocation)?; - let invocation = f.load(invocation, MemAccess::default())?; - let i = f.composite_extract(invocation, &[0])?; - let targets = f.module().global_value(targets)?; - let count = f.array_length(targets, 0)?; - let dest = f.module().global_value(dest)?; - let dest_len = f.array_length(dest, 0)?; - let listed = f.binary(BinOp::ULessThan, i, count)?; - // Invocation `i` rewrites the word `targets[i]` names, when its two halves lie in the range. - let resolve: ArmFn<'_, ()> = Box::new(move |f, _| { - let p = f.access_chain(targets, &[zero, i])?; - let target = f.load(p, MemAccess::default())?; - let low_index = f.binary(BinOp::ShiftLeftLogical, target, one)?; - let high_index = f.binary(BinOp::IAdd, low_index, one)?; - let inside = f.binary(BinOp::ULessThan, high_index, dest_len)?; - let rewrite: ArmFn<'_, ()> = Box::new(move |f, _| { - let low_ptr = f.access_chain(dest, &[zero, low_index])?; - let high_ptr = f.access_chain(dest, &[zero, high_index])?; - let low = f.load(low_ptr, MemAccess::default())?; - let high = f.load(high_ptr, MemAccess::default())?; - let any = f.binary(BinOp::BitwiseOr, low, high)?; - let passed = f.binary(BinOp::INotEqual, any, zero)?; - let word = f.select(passed, one, zero)?; - f.store(low_ptr, word, MemAccess::default())?; - f.store(high_ptr, zero, MemAccess::default())?; - Ok(ArmEnd::FallThrough(Vec::new())) - }); - f.if_(&mut (), inside, rewrite, None)?; - Ok(ArmEnd::FallThrough(Vec::new())) - }); - f.if_(&mut (), listed, resolve, None)?; - f.ret(None)?; - let id = f.finish()?; - b.entry( - ExecModel::GLCompute, - id, - vec![ExecMode::LocalSize { - x: VisibilityResolveModule::LOCAL_SIZE, - y: 1, - z: 1, - }], - )?; - b.finalize() -} - -/// The fixed binding numbers of the module's symbols. -fn binding_of(sym: &Symbol) -> Option { - match sym { - Symbol::DescriptorSet(_) => Some(VisibilityResolveModule::SET), - Symbol::Binding(s) if *s == TARGETS => Some(VisibilityResolveModule::TARGETS_BINDING), - Symbol::Binding(s) if *s == DEST => Some(VisibilityResolveModule::DEST_BINDING), - _ => None, - } -} - -/// The visibility resolve module of `device`: built with the typed builder, checked by the owned -/// verifier against the device's profile (requirements included), serialized, and numbered with -/// the fixed bindings of [`VisibilityResolveModule`]. -pub fn visibility_resolve_module(device: &Device) -> Result { - let profile = device.profile(); - let m = typed_module()?; - let mut meter = Meter::new(&Budget::default()); - crate::spirv::verify::verify(&m, profile, &mut meter)?; - let r = crate::spirv::serialize::serialize(m)?; - profile.check(&r.requirements).map_err(|c| { - Error::Internal(InternalError::new( - InternalKind::RequirementsExceedProfile, - format!("the visibility resolve needs {c:?}"), - )) - })?; - let words = crate::spirv::serialize::relocate(&r, &binding_of)?; - Ok(VisibilityResolveModule { - spirv: words.into(), - requirements: r.requirements, - }) -} - -#[cfg(test)] -mod tests; diff --git a/crates/metal2vulkan/src/bind/visibility_resolve/tests.rs b/crates/metal2vulkan/src/bind/visibility_resolve/tests.rs deleted file mode 100644 index d47971042..000000000 --- a/crates/metal2vulkan/src/bind/visibility_resolve/tests.rs +++ /dev/null @@ -1,178 +0,0 @@ -//! The visibility resolve module: valid on every committed profile (L3, `G-val`), and exact on -//! the CPU interpreter (Metal's 1 or 0 for any count), in place, for the listed words only, -//! across workgroups and short ranges; and its plan's windows. - -use super::*; -use crate::spirv::interp::{run, Buffer, Config, Order, Resources}; -use crate::spirv::testing::{assert_valid, committed_profiles}; - -fn words(bytes: &[u8]) -> Vec { - bytes - .as_chunks::<4>() - .0 - .iter() - .map(|c| u32::from_le_bytes(*c)) - .collect() -} - -fn bytes(words: &[u32]) -> Vec { - words.iter().flat_map(|w| w.to_le_bytes()).collect() -} - -/// Run the resolve of `targets` over `dest` (each bound whole) in `groups` workgroups, in both -/// invocation orders; the destination's words after it. -fn resolve(targets: &[u32], dest: &[u32], groups: u32) -> Vec { - let m = typed_module().expect("module"); - let mut out = Vec::new(); - for order in [Order::Forward, Order::Reverse] { - let res = Resources { - buffers: vec![ - Buffer { - slot: Some(TARGETS), - address: None, - bytes: bytes(targets), - }, - Buffer { - slot: Some(DEST), - address: None, - bytes: bytes(dest), - }, - ], - push: Vec::new(), - spec: Default::default(), - }; - let cfg = Config { - order, - workgroups: [groups, 1, 1], - ..Config::default() - }; - out.push(run(&m, &cfg, res).expect("run").buffers); - } - assert_eq!(out[0], out[1], "order independent"); - words(&out[0][1]) -} - -#[test] -fn the_resolve_module_is_valid_on_every_committed_profile() { - for (_, p) in committed_profiles().expect("profiles") { - assert_valid(typed_module().expect("module"), &p); - } -} - -/// Any nonzero count, in either half of the 64-bit word, becomes Metal's 1, and zero stays 0; -/// the high half becomes 0. Words not listed keep their bytes. -#[test] -fn a_count_becomes_metals_one_or_zero_in_place() { - for (count, want) in [ - ([0, 0], 0), - ([1, 0], 1), - ([16, 0], 1), - ([u32::MAX, u32::MAX], 1), - ([0, 1], 1), - ] { - let dest = [0xAAAA_AAAA, 0xAAAA_AAAA, count[0], count[1], 7, 9]; - let out = resolve(&[1], &dest, 1); - assert_eq!(out, [0xAAAA_AAAA, 0xAAAA_AAAA, want, 0, 7, 9], "{count:?}"); - } -} - -/// Every listed word is rewritten, across workgroups, and a counting word between them is -/// left as copied; an invocation past the table does nothing. -#[test] -fn every_listed_word_resolves_across_workgroups() { - let n = VisibilityResolveModule::LOCAL_SIZE + 3; - // Word 2k holds the count k (0 for k = 0); the odd words are counting results, untouched. - let mut dest = Vec::new(); - for k in 0..2 * n { - dest.extend([k, 0]); - } - let targets: Vec = (0..n).map(|k| 2 * k).collect(); - let out = resolve(&targets, &dest, 2); - for k in 0..2 * n { - let want = if k % 2 == 1 { - [k, 0] - } else { - [u32::from(k != 0), 0] - }; - assert_eq!(out[2 * k as usize..2 * k as usize + 2], want, "word {k}"); - } -} - -/// A word whose high half lies past the bound range is skipped, and so is a target past it; -/// nothing faults. -#[test] -fn words_past_the_bound_range_are_skipped() { - assert_eq!(resolve(&[0, 1, 9], &[5, 0, 6], 1), [1, 0, 6]); - assert_eq!(resolve(&[0], &[5], 1), [5]); -} - -#[test] -fn the_plan_binds_aligned_windows() { - let plan = VisibilityResolve::plan(&[72, 24, 72], 64, 1 << 16, 65_535).expect("plan"); - assert_eq!(plan.len(), 1); - assert_eq!( - (plan[0].dest_range.offset, plan[0].dest_range.range), - (0, 80) - ); - assert_eq!(plan[0].targets, [3, 9], "sorted, each once"); - assert_eq!(plan[0].group_count, 1); - assert_eq!(plan[0].target_bytes(), [3, 0, 0, 0, 9, 0, 0, 0]); - // Results farther apart than one binding reaches take a dispatch each, from an aligned - // offset. - let plan = VisibilityResolve::plan(&[8, 200], 16, 64, 65_535).expect("plan"); - let ranges: Vec<_> = plan - .iter() - .map(|r| (r.dest_range.offset, r.dest_range.range, r.targets.clone())) - .collect(); - assert_eq!(ranges, [(0, 16, vec![1]), (192, 16, vec![1])]); - // Too many for one dispatch. - let offsets: Vec = (0..65).map(|k| 8 * k).collect(); - let plan = VisibilityResolve::plan(&offsets, 8, 1 << 16, 1).expect("plan"); - assert_eq!(plan.len(), 2); - assert_eq!(plan[0].targets.len(), 64); - assert_eq!(plan[1].targets, [0]); - assert_eq!(plan[1].dest_range.offset, 512); - assert_eq!(VisibilityResolve::plan(&[], 64, 64, 1), Some(Vec::new())); -} - -#[test] -fn the_plan_refuses_what_it_cannot_bind() { - assert_eq!(VisibilityResolve::plan(&[12], 8, 64, 1), None, "misaligned"); - assert_eq!( - VisibilityResolve::plan(&[u64::MAX - 7], 8, 64, 1), - None, - "an overflow" - ); - assert_eq!( - VisibilityResolve::plan(&[56], 64, 32, 1), - None, - "a word past the range from its aligned offset" - ); - assert_eq!(VisibilityResolve::plan(&[0], 8, 64, 0), None, "no groups"); -} - -#[test] -fn the_device_module_is_numbered_with_the_fixed_bindings() { - let (_, p) = committed_profiles() - .expect("profiles") - .into_iter() - .find(|(s, _)| s == "vk12-floor") - .expect("vk12-floor"); - let r = crate::spirv::serialize::serialize(typed_module().expect("module")).expect("serialize"); - let words = crate::spirv::serialize::relocate(&r, &binding_of).expect("relocate"); - crate::spirv::testing::check_words_valid(&words, &r.requirements, &p).expect("L3"); - let mut bindings: Vec = r - .relocs - .iter() - .filter(|(s, _)| matches!(s, Symbol::Binding(_))) - .map(|(_, at)| words[*at as usize]) - .collect(); - bindings.sort_unstable(); - assert_eq!( - bindings, - [ - VisibilityResolveModule::TARGETS_BINDING, - VisibilityResolveModule::DEST_BINDING - ] - ); -} diff --git a/crates/metal2vulkan/src/tests/owned_divisions.rs b/crates/metal2vulkan/src/tests/owned_divisions.rs index fa2f92d83..b47149fb9 100644 --- a/crates/metal2vulkan/src/tests/owned_divisions.rs +++ b/crates/metal2vulkan/src/tests/owned_divisions.rs @@ -75,7 +75,6 @@ fn modules() -> Vec { tiled_texels_module, two_plane_texels_module, visibility_combine_module, - visibility_resolve_module, ycbcr_refresh_module, ycbcr_write_module, ); diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 9560f7a99..bdf7f50b3 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -365,11 +365,6 @@ assoc-const metal2vulkan::bind::VisibilityCombineModule::LOCAL_SIZE pub const LO assoc-const metal2vulkan::bind::VisibilityCombineModule::SET pub const SET: u32 assoc-const metal2vulkan::bind::VisibilityCombineModule::SOURCES_BINDING pub const SOURCES_BINDING: u32 assoc-const metal2vulkan::bind::VisibilityCombineModule::TABLE_BINDING pub const TABLE_BINDING: u32 -assoc-const metal2vulkan::bind::VisibilityResolve::RESULT_BYTES pub const RESULT_BYTES: u64 -assoc-const metal2vulkan::bind::VisibilityResolveModule::DEST_BINDING pub const DEST_BINDING: u32 -assoc-const metal2vulkan::bind::VisibilityResolveModule::LOCAL_SIZE pub const LOCAL_SIZE: u32 -assoc-const metal2vulkan::bind::VisibilityResolveModule::SET pub const SET: u32 -assoc-const metal2vulkan::bind::VisibilityResolveModule::TARGETS_BINDING pub const TARGETS_BINDING: u32 assoc-const metal2vulkan::bind::YCbCrConvertModule::BYTES_BINDING pub const BYTES_BINDING: u32 assoc-const metal2vulkan::bind::YCbCrConvertModule::IMAGE_BINDING pub const IMAGE_BINDING: u32 assoc-const metal2vulkan::bind::YCbCrConvertModule::LOCAL_SIZE pub const LOCAL_SIZE: u32 @@ -836,11 +831,6 @@ assoc-const-value metal2vulkan::bind::VisibilityCombineModule::LOCAL_SIZE 64 assoc-const-value metal2vulkan::bind::VisibilityCombineModule::SET 0 assoc-const-value metal2vulkan::bind::VisibilityCombineModule::SOURCES_BINDING 2 assoc-const-value metal2vulkan::bind::VisibilityCombineModule::TABLE_BINDING 0 -assoc-const-value metal2vulkan::bind::VisibilityResolve::RESULT_BYTES 8 -assoc-const-value metal2vulkan::bind::VisibilityResolveModule::DEST_BINDING 1 -assoc-const-value metal2vulkan::bind::VisibilityResolveModule::LOCAL_SIZE 64 -assoc-const-value metal2vulkan::bind::VisibilityResolveModule::SET 0 -assoc-const-value metal2vulkan::bind::VisibilityResolveModule::TARGETS_BINDING 0 assoc-const-value metal2vulkan::bind::YCbCrConvertModule::BYTES_BINDING 2 assoc-const-value metal2vulkan::bind::YCbCrConvertModule::IMAGE_BINDING 0 assoc-const-value metal2vulkan::bind::YCbCrConvertModule::LOCAL_SIZE 8 @@ -3630,11 +3620,6 @@ field metal2vulkan::bind::VisibilityCombine.group_count pub group_count: u32 field metal2vulkan::bind::VisibilityCombine.table pub table: Vec field metal2vulkan::bind::VisibilityCombineModule.requirements pub requirements: Requirements field metal2vulkan::bind::VisibilityCombineModule.spirv pub spirv: Arc<[u32]> -field metal2vulkan::bind::VisibilityResolve.dest_range pub dest_range: BufferRange -field metal2vulkan::bind::VisibilityResolve.group_count pub group_count: u32 -field metal2vulkan::bind::VisibilityResolve.targets pub targets: Vec -field metal2vulkan::bind::VisibilityResolveModule.requirements pub requirements: Requirements -field metal2vulkan::bind::VisibilityResolveModule.spirv pub spirv: Arc<[u32]> field metal2vulkan::bind::YCbCrCodes.bits pub bits: u32 field metal2vulkan::bind::YCbCrCodes.bytes pub bytes: u32 field metal2vulkan::bind::YCbCrCodes.output pub output: YCbCrOutput @@ -4708,7 +4693,6 @@ fn metal2vulkan::bind::tessellation_scan_module pub fn tessellation_scan_module( fn metal2vulkan::bind::tiled_texels_module pub fn tiled_texels_module(device: &Device) -> Result fn metal2vulkan::bind::two_plane_texels_module pub fn two_plane_texels_module(device: &Device) -> Result fn metal2vulkan::bind::visibility_combine_module pub fn visibility_combine_module(device: &Device) -> Result -fn metal2vulkan::bind::visibility_resolve_module pub fn visibility_resolve_module(device: &Device) -> Result fn metal2vulkan::bind::ycbcr_convert_floats_module pub fn ycbcr_convert_floats_module(device: &Device, conversion: YCbCrConversion) -> Result fn metal2vulkan::bind::ycbcr_convert_module pub fn ycbcr_convert_module(device: &Device, conversion: YCbCrConversion) -> Result fn metal2vulkan::bind::ycbcr_read pub fn ycbcr_read(codes: YCbCrCodes, (range, matrix): (YCbCrRange, YCbCrMatrix), [y, cb, cr]: [u16; 3]) -> [u16; 3] @@ -5040,6 +5024,7 @@ macro-member metal2vulkan-runtime::Degradation::DetachedStorageKeepsWrites Detac macro-member metal2vulkan-runtime::Degradation::DeviceAlphaCoverage DeviceAlphaCoverage = "device-alpha-coverage"; macro-member metal2vulkan-runtime::Degradation::DeviceAnisotropicFilter DeviceAnisotropicFilter = "device-anisotropic-filter"; macro-member metal2vulkan-runtime::Degradation::DeviceArithmetic DeviceArithmetic = "device-arithmetic"; +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::DeviceFilteredMipmaps DeviceFilteredMipmaps = "device-filtered-mipmaps", Precision, @@ -8745,8 +8730,6 @@ method metal2vulkan::bind::VertexAmplification::new pub fn new(count: u32, view_ method metal2vulkan::bind::ViewMapping::new pub fn new(viewport_array_index_offset: u32, render_target_array_index_offset: u32) -> Self method metal2vulkan::bind::VisibilityCombine::plan pub fn plan(results: &[ContinuedResult], alignment: u64, max_range: u32, max_groups: u32) -> Option> method metal2vulkan::bind::VisibilityCombine::table_bytes pub fn table_bytes(&self) -> Vec -method metal2vulkan::bind::VisibilityResolve::plan pub fn plan(offsets: &[u64], alignment: u64, max_range: u32, max_groups: u32) -> Option> -method metal2vulkan::bind::VisibilityResolve::target_bytes pub fn target_bytes(&self) -> Vec method metal2vulkan::bind::YCbCrCodes::of pub fn of(format: crate::metal::format::YCbCrFormat) -> Option method metal2vulkan::bind::YCbCrCodes::units pub fn units(&self, n: u64) -> u64 method metal2vulkan::bind::YCbCrConversion::of pub fn of(codes: YCbCrCodes, (range, matrix): (YCbCrRange, YCbCrMatrix)) -> YCbCrConversion @@ -9699,8 +9682,6 @@ struct metal2vulkan::bind::ViewMapping #[cfg_attr(feature = "serde", derive(serd struct metal2vulkan::bind::ViewSetup #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ViewSetup struct metal2vulkan::bind::VisibilityCombine #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct VisibilityCombine struct metal2vulkan::bind::VisibilityCombineModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct VisibilityCombineModule -struct metal2vulkan::bind::VisibilityResolve #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct VisibilityResolve -struct metal2vulkan::bind::VisibilityResolveModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct VisibilityResolveModule struct metal2vulkan::bind::YCbCrCodes #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct YCbCrCodes struct metal2vulkan::bind::YCbCrConversion #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct YCbCrConversion struct metal2vulkan::bind::YCbCrConvertModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct YCbCrConvertModule diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index a2dba0b9b..7ae51dbe0 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -634,9 +634,6 @@ surface! { struct ContinuedResult N; struct VisibilityCombine N; struct VisibilityCombineModule N; - fn visibility_resolve_module; - struct VisibilityResolve N; - struct VisibilityResolveModule N; fn shadow_copy_back_module; struct ShadowCopyBackModule N; enum ShadowTexelView E; diff --git a/docs/API.md b/docs/API.md index 628a3dbf6..8de35d5ce 100644 --- a/docs/API.md +++ b/docs/API.md @@ -2912,7 +2912,18 @@ bound. - `metal2vulkan-degrade-visibility-count-per-color` (precision). `VisibilityCountPerColor`: A draw counted by a `Counting` visibility result whose fragment function writes more than one color attachment, on ANV (`RuntimeDriverDefect::OcclusionCountPerColorOutput`). Cost: the result is - Metal's count multiplied by the colors the draw writes; a `Boolean` result is Metal's. + Metal's count multiplied by the colors the draw writes; a `Boolean` result keeps its contract. +- `metal2vulkan-degrade-device-boolean-visibility` (precision). `DeviceBooleanVisibility`: A pass + writes a `Boolean` visibility result. Where a sample passed, its word is the device's occlusion + query result without `VK_QUERY_CONTROL_PRECISE_BIT`, which Vulkan states only as nonzero ("When + any samples are passed, boolean queries will return a non-zero result value, otherwise a result + value of zero is returned"), ORed over the pass's render pass instances; where none passed, 0. + That is Metal's `Boolean` contract, and Metal's own nonzero value is not one value either: an + Apple M3 Max (macOS 27.0.1) writes 1, Metal on the AMD Radeon Pro 5300M and the Intel UHD + Graphics 630 (macOS 26.7.1) the samples that passed. No dispatch rewrites the device's value. + Announced where the pass's results record. Cost: a `Boolean` visibility result where a sample + passed is the device's nonzero value, which can be other than the 1 an Apple M3 Max writes; + where none passed it is 0. - `metal2vulkan-degrade-float-tininess-after-rounding` (precision). `FloatTininessAfterRounding`: A device whose float functions are not Metal's own (not MoltenVK): Metal flushes a `float` product, fused multiply-add or `ldexp` whose exact value lies below `2^-126` to the zero of its sign, diff --git a/docs/CONFORMANCE-COVERAGE.md b/docs/CONFORMANCE-COVERAGE.md index 1daec27f3..6eb49a885 100644 --- a/docs/CONFORMANCE-COVERAGE.md +++ b/docs/CONFORMANCE-COVERAGE.md @@ -38,8 +38,8 @@ Its limits, measured rather than asserted: | of the reachable, exercised by the suite's Metal leg | 793 | | of the reachable, not exercised | 163 | | share of the reachable exercised | 83% | -| of those exercised, no case reaching it loosens anything | 594 | -| of those exercised, a case reaching it loosens some site | 199 | +| of those exercised, no case reaching it loosens anything | 578 | +| of those exercised, a case reaching it loosens some site | 215 | | case modules | 152 | | committed recordings | 1123 | | distinct SDK items the Metal leg reaches, of any status | 800 | @@ -532,10 +532,10 @@ An implemented container no case's Metal leg touches. These are the families of | cases whose Metal answer is `metal_run` | 1039 | | cases whose Metal answer is `carried` | 80 | | cases whose Metal answer is `never_returned` | 4 | -| modules that loosen a measured value | 8 | -| tolerances in all | 8 | +| modules that loosen a measured value | 9 | +| tolerances in all | 9 | | modules declaring a notice (loosening no value) | 120 | -| loosenings used | `Unchecked`, `Absolute` | +| loosenings used | `Unchecked`, `Absolute`, `Nonzero` | | justifications named | `Degradation`, `AcceptedDifference` | | modules forbidding a re-record | 8 | | `Side` methods (the suite's whole device vocabulary) | 126 | @@ -699,7 +699,7 @@ Each case module: the cases it holds, the `Side` methods it calls, and how many | `two_plane_heap_blits` | 1 | 1 | every field | 51 | | `two_plane_samples` | 16 | 16 | every field | 50 | | `vertex_formats` | 4 | 4 | every field | 108 | -| `visibility` | 10 | 10 | every field | 135 | +| `visibility` | 10 | 10 | 1 tolerance(s): `Degradation` | 135 | | `visible_tables` | 18 | 18 | every field | 55 | | `wide_int_attributes` | 2 | 2 | every field | 108 | | `wide_points` | 1 | 1 | every field | 123 | diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index cbd650ec3..10cb1fcf8 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -89,7 +89,8 @@ known. The rest of the differences are docs/API.md section 9's precision notes. | On NVIDIA's driver (615.71.09 on an RTX 5080 Laptop GPU) one `vkQueueSubmit` in every 1024 that signal on a `VkQueue` takes 2 to 4 ms in the driver (1.97 to 4.06 ms measured), which holds the command buffer whose batch it falls on, and the ones committed behind it, from the GPU that long. | The cost is the driver's, and every batch signals its completion. The scheduler's thread takes the stall while idle, by empty submissions, once one was seen (`DriverFact::SignallingSubmitsStallEvery1024`, `device/submit_stalls.rs`; a call of 1 ms or more, and once one came where the count put it, only there): it falls on work only before then, after a use of the queue the runtime cannot count, or on a queue that never idles 1 ms. Whether the driver's stall also holds other threads' semaphore calls is unsettled: a probe polling the timeline from a second thread during 10 stalls saw 5 of its 9 slow calls (up to 7.1 ms) overlap one in one run, and none of its 3 in another; in `host_ab present` the completion handlers of command buffers that completed during a stall taken idle ran 126 us (p50, 341 at most) after their GPU end, as elsewhere. | None (timing only; `WorkCounts::submit_stalls_on_work`, `WorkCounts::submit_stalls_idle`) | | Command buffers that share no resource run one after another, where Metal overlaps them while the GPU has room. | The runtime orders nothing between them and runs at each driver's floor for one completion signal per command buffer; a signal shared by several would hold an earlier one's completion for the later ones' work. | None (timing only) | | On MoltenVK a light queue's command buffer waits for the latest one another queue committed, where Metal waits for none: MoltenVK fences every encoder of every queue device-wide when argument buffers and a residency set are on. | The runtime needs argument buffers, and MoltenVK has no setting for its residency set; `runtime_lane::queue_storms` judges the runtime against Metal under those fences. | None (timing only) | -| A `Counting` visibility result of a draw writing more than one color attachment, on ANV (Mesa 26.2.4): Metal's count multiplied by the colors written, not divided back. `Boolean` results stay exact. | The driver counts each sample once per color output (`RuntimeDriverDefect::OcclusionCountPerColorOutput`), no documented Vulkan form counts it once, and a refusal would withhold the Mac2 and Metal3 families. | `VisibilityCountPerColor` (`visibility-count-per-color`) | +| A `Boolean` visibility result where a sample passed is the device's occlusion query result without `VK_QUERY_CONTROL_PRECISE_BIT` (ORed over a split pass's render pass instances), which Vulkan states only as nonzero; where none passed it is 0. An Apple M3 Max writes 1, Metal on the AMD Radeon Pro 5300M and the Intel UHD Graphics 630 (macOS 26.7.1) the samples that passed. | Metal's contract is nonzero, and the device's query answers it natively: no dispatch rewrites the word to 1. | `DeviceBooleanVisibility` (`device-boolean-visibility`) | +| A `Counting` visibility result of a draw writing more than one color attachment, on ANV (Mesa 26.2.4): Metal's count multiplied by the colors written, not divided back. `Boolean` results keep their contract (zero where no sample passed). | The driver counts each sample once per color output (`RuntimeDriverDefect::OcclusionCountPerColorOutput`), no documented Vulkan form counts it once, and a refusal would withhold the Mac2 and Metal3 families. | `VisibilityCountPerColor` (`visibility-count-per-color`) | | On MoltenVK a no-copy buffer or heap released with no keep-alive while batches are in flight runs its deallocator once the batches submitted before its release completed, and the program's own submissions through `CommandQueue::with_vk_queue` before it, where Metal runs it at the release. | MoltenVK 1.4.1 fails pending work that reads device addresses where memory a device-address buffer lay in is freed (`RuntimeDriverDefect::FreedAddressMemoryFailsPendingWork`), so freed memory waits for the batches in flight (`WorkCounts::freed_memory_parked`). | `HostDeallocatorDelayed` (`host-deallocator-delayed`) | | On MoltenVK a `Shared` or `Managed` texture whose format packs more than one texel into a block (every block-compressed family) keeps its image out of host-transfer memory, so its CPU copies take submissions where another driver's take none. The stored texels are Metal's either way; what changes is the work, in `WorkCounts::command_buffers_begun_batch_work` and the `command_buffers_begun` and `command_buffers_submitted` that carry it (`bc1-rgba`, four 16 x 16 `BC1_RGBA` levels: `command_buffers_begun` 8 on the bind-time path and 15 off it; `fresh-texture-bc1-rgba-managed`: 3 and 5). A `replaceRegion` of such a texture stages its bytes for the device's next submission and waits for none (`texture/first_move.rs`). Its CPU **reads** come out of a host shadow of the image's texels, made at the first read of the texture by the submission that read waits for either way and read from by every read after it: exact (it holds the image's own bytes, and a CPU write writes both), bounded (`host_shadow::SHADOW_BYTES`, past which a read takes the submission path), and lazy, so a texture nobody reads back holds nothing. It is dropped wherever anything but a CPU write may have written the texels: every commit of the program's, its own Vulkan submissions, another `VkImage`, a detach, or the program taking the image's handle (`texture/host_shadow.rs`; `WorkCounts::texel_shadows_made`, `texel_shadow_reads`, `texel_shadows_dropped`). Measured on an M3 Max: `compressed-moves-bc1-rgba` reads `internal_submissions` 5 where it read 56 and `command_buffers_begun` 30 where it read 81, for 1,168 bytes of shadow over its five textures and 56 reads out of them. | MoltenVK 1.4.2 binds such an image through a `flushToDevice` that `replaceRegion:`s every subresource at one block's bytes a row instead of the row of blocks, tripping AGX's `bytes_per_row >= used_bytes_per_row` assertion (`RuntimeDriverDefect::HostTransferImagesCopiedAtBind`). The copy is the driver's own and no call of the program's asks for it, so the only way not to provoke it is not to ask for the image; every other driver keeps the host-transfer path, as does a device without `VK_EXT_host_image_copy`. A write cannot leave the GPU's copy of the texels unwritten, so only reads come off the host shadow. | None (cost only, and exact) | | On a driver that does not take a set-0 buffer binding whose entry point uses it through several variables as a **dynamic** descriptor, a draw or dispatch of such a variant that binds it at another offset than its predecessor did allocates and writes a descriptor set of its own, where a dynamic binding would let it bind its predecessor's set again at its own offset. That saving needs the binding's range to stay as its offset moves (`bind::instantiate::descriptor_range`): a slot read to its buffer's end has a range that moves with its offset, so its commands write a set each in either form. Such a binding is a slot reached through its word view and a narrow or `uvec4` unit view (`memory::views`), as `record_stride_not_a_multiple_of_four`'s `recs` is. The stored values are the same either way; what changes is the set a command allocates and writes (`WorkCounts::set_zero_sets_reused` counts none of them). The device answers for itself, by creating one pipeline of exactly that shape and destroying it (`pipeline::objects::takes_multi_variable_dynamic`, `bind::DynamicViewsModule`, asked once and only where a layout has such a binding), so a driver without the defect pays nothing. A binding the device takes still turns dynamic only while the layout's dynamic-buffer budget lasts (`maxDescriptorSetUniformBuffersDynamic`, `maxDescriptorSetStorageBuffersDynamic`), spent in binding order: on a Radeon 780M (RADV, Mesa 26.2.4, eight dynamic storage buffers) a layout's storage bindings past the eighth get none, so commands that bind them at moving offsets keep a set each wherever set 0 is not pushed. A device whose set 0 is pushed (`VK_KHR_push_descriptor` with an eligible layout) never reaches the choice. | Nothing in Vulkan bounds the variables at a binding, dynamic or not, so there is no exact form to switch to: the driver either compiles the shape or does not. MoltenVK's SPIRV-Cross declares one variable's local alone -- read in 1.4.1's source and measured on 1.4.2 (`driverVersion` 10402) on an Apple M3 Max, where `vkCreateComputePipelines` answers `VK_ERROR_INITIALIZATION_FAILED` for a kernel of three and of four variables at one dynamic binding. The check proves the driver compiles the shape, not that it applies the dynamic offset to every variable at it; no device is measured to get that wrong, and RADV (Mesa 26.2.4, Radeon 780M, at offset 0) and lavapipe (Mesa, arm64, at moving offsets) are measured to get it right, `record_stride_not_a_multiple_of_four` answering Metal's `sizeof` and both its narrow stores with its three-variable binding dynamic. | None (cost only, and exact) |