diff --git a/crates/metal2vulkan/src/bind/mod.rs b/crates/metal2vulkan/src/bind/mod.rs index 24f76e70e..ad5da1be4 100644 --- a/crates/metal2vulkan/src/bind/mod.rs +++ b/crates/metal2vulkan/src/bind/mod.rs @@ -265,6 +265,7 @@ pub use plan::{ GraphicsTemplate, ImageSource, ImageViewDesc, PlanDiagnostic, PushFieldPlacement, PushTemplate, ResourceUse, SamplerSource, UseTarget, VertexBufferBind, ViewSetup, WriteSource, }; +pub use rate_map::fan_out; pub use rate_map::{ RasterizationRateMap, RateMapAxis, RateMapDescriptor, RateMapError, RateMapLayerDescriptor, RateMapRegion, RateMapRegions, RegionError, RegionLimits, UnpinnedCompile, MAX_SCREEN_EXTENT, diff --git a/crates/metal2vulkan/src/bind/rate_map.rs b/crates/metal2vulkan/src/bind/rate_map.rs index 0fc1108a6..b763a7a9e 100644 --- a/crates/metal2vulkan/src/bind/rate_map.rs +++ b/crates/metal2vulkan/src/bind/rate_map.rs @@ -793,6 +793,7 @@ fn encode(words: &mut [u32], axis: &RateMapAxis, to_screen: u32, to_physical: u3 } } +pub mod fan_out; mod regions; pub use regions::{RateMapRegion, RateMapRegions, RegionError, RegionLimits}; diff --git a/crates/metal2vulkan/src/bind/rate_map/fan_out.rs b/crates/metal2vulkan/src/bind/rate_map/fan_out.rs new file mode 100644 index 000000000..308dfd409 --- /dev/null +++ b/crates/metal2vulkan/src/bind/rate_map/fan_out.rs @@ -0,0 +1,158 @@ +//! The region table of a rate-mapped pass drawn by fan-out: each primitive once, its vertices +//! shaded once, and a geometry stage that emits a copy of each triangle per region it touches +//! (`pipeline::link::geometry`, the fan-out stage), where the regions route +//! ([`RateMapRegions`](super::RateMapRegions)) records each draw once per region. +//! +//! A region of the plan is a viewport and a scissor: its line maps the guest's normalized device +//! coordinates to physical pixels, and its scissor keeps its own pixels. The fan-out draw has one +//! viewport over the whole target, so a copy of a triangle for a region carries both in clip +//! space, per axis: +//! +//! - its position, `x' = a·x + b·w`, where the target's viewport `(X₀, W₀)` maps `x'` to the +//! same window coordinate as the region's viewport `(X, W)` maps `x`: `a = W / W₀` and +//! `b = (2X + W − 2X₀) / W₀ − 1` (Vulkan's viewport transform, `window = X + (ndc + 1)·W / 2`, +//! whatever the sign of `W`); +//! - two clip distances that hold the window coordinate within the scissor's pixels `[p₀, p₁)`: +//! `(W/2)·x + (X + W/2 − p₀)·w` and `−(W/2)·x + (p₁ − X − W/2)·w`, the window coordinate times +//! `w` less `p₀`, and `p₁` less it. Clipping keeps a fragment whose pixel centre lies inside, and +//! a pixel centre lies half a pixel from every scissor edge, so each pixel the triangle covers is +//! shaded by the one copy of its region. +//! +//! A copy's fragments are the region route's up to rounding: its window coordinates are the +//! region viewport's computed another way, so a pixel centre that lies within a rounding error of +//! a triangle's edge may be covered by one route and not the other (a near-equivalent, rule 1's +//! fast default; the regions route is the exact one). +//! +//! The table holds, for each axis, the segments of the plan's regions that hold a pixel, in the +//! order of their normalized device coordinates: a region is a segment of each axis. The stage +//! reads a triangle's bounds in normalized device coordinates (`x / w`, every `w` positive), +//! finds the segments of each axis they reach by bisection, and emits a copy for each pair, at +//! most its copies; a triangle with more, or with a `w` not positive and another positive, is +//! the probe's to find, whose bounds are widened by [`WIDEN_PIXELS`] of a pixel so that a draw +//! the probe passed reaches no more. +//! +//! The layout (`std430`, 16-byte entries): a header of the counts `uvec4(nx, ny, 0, 0)` and the +//! widenings `vec4(ex, ey, 0, 0)`, then [`MAX_SEGMENTS`] lines and as many clips per axis, x's +//! then y's: a line `vec4(ndc_lo, ndc_hi, a, b)`, a clip `vec4(W/2, X + W/2 − p₀, p₁ − X − W/2, +//! 0)`. + +/// The most segments an axis holds: [`RateMapRegions::MAX_REGIONS`](super::RateMapRegions) is +/// this many per axis squared. +pub const MAX_SEGMENTS: u32 = 128; + +/// The entries before the lines: the counts and the widenings. +pub const HEADER_ENTRIES: u32 = 2; + +/// The table's bytes. +pub const TABLE_BYTES: u64 = (HEADER_ENTRIES as u64 + 4 * MAX_SEGMENTS as u64) * 16; + +/// How far, in physical pixels, the probe widens a triangle's bounds before it counts the +/// segments they reach: past the difference rounding makes between the probe's and the draw's +/// vertex positions, each its own pipeline's. +pub const WIDEN_PIXELS: f64 = 0.125; + +/// The entry of axis `axis`'s line `k`. +pub const fn line_entry(axis: u32, k: u32) -> u32 { + HEADER_ENTRIES + axis * MAX_SEGMENTS + k +} + +/// The entry of axis `axis`'s clip `k`. +pub const fn clip_entry(axis: u32, k: u32) -> u32 { + HEADER_ENTRIES + 2 * MAX_SEGMENTS + axis * MAX_SEGMENTS + k +} + +/// One segment of an axis: the region viewport's `(X, W)` on it, Vulkan's (`W` negative where +/// the consumer flips the axis), and its scissor's pixels `[p₀, p₁)`. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Segment { + origin: f64, + extent: f64, + pixels: [u32; 2], +} + +impl Segment { + /// Its normalized device coordinates, least first: those of its pixels' edges. + fn ndc(&self) -> [f64; 2] { + let at = |p: u32| 2.0 * (f64::from(p) - self.origin) / self.extent - 1.0; + let [a, b] = [at(self.pixels[0]), at(self.pixels[1])]; + [a.min(b), a.max(b)] + } + + /// Its line `vec4(ndc_lo, ndc_hi, a, b)` for the target's viewport `(X₀, W₀)` on its axis. + fn line(&self, (x0, w0): (f64, f64)) -> [f32; 4] { + let [lo, hi] = self.ndc(); + let a = self.extent / w0; + let b = (2.0 * self.origin + self.extent - 2.0 * x0) / w0 - 1.0; + [lo, hi, a, b].map(|v| v as f32) + } + + /// Its clip `vec4(W/2, X + W/2 − p₀, p₁ − X − W/2, 0)`. + fn clip(&self) -> [f32; 4] { + let half = self.extent / 2.0; + let centre = self.origin + half; + [ + half, + centre - f64::from(self.pixels[0]), + f64::from(self.pixels[1]) - centre, + 0.0, + ] + .map(|v| v as f32) + } +} + +/// The region table of a fan-out draw through the Vulkan viewport `target` (`[x, y, width, +/// height]`, its height negative where the consumer flips y) over the regions `regions`, each its +/// Vulkan viewport and its scissor `[x, y, width, height]`, those that hold a pixel (the module +/// docs). `None` where the regions are not one segment of each axis per pair (a plan's are), or an +/// axis has more than [`MAX_SEGMENTS`] or none. +pub fn table(target: [f32; 4], regions: &[([f32; 4], [u32; 4])]) -> Option> { + let axis = |a: usize| { + let mut segments: Vec = Vec::new(); + for &(viewport, scissor) in regions { + let segment = Segment { + origin: f64::from(viewport[a]), + extent: f64::from(viewport[a + 2]), + pixels: [scissor[a], scissor[a] + scissor[a + 2]], + }; + if !segments.contains(&segment) { + segments.push(segment); + } + } + segments.sort_by(|s, t| s.ndc()[0].total_cmp(&t.ndc()[0])); + segments + }; + let [xs, ys] = [axis(0), axis(1)]; + let fits = |s: &[Segment]| !s.is_empty() && s.len() <= MAX_SEGMENTS as usize; + if !fits(&xs) || !fits(&ys) || xs.len() * ys.len() != regions.len() { + return None; + } + let mut entries = vec![[0u32; 4]; (TABLE_BYTES / 16) as usize]; + entries[0] = [xs.len() as u32, ys.len() as u32, 0, 0]; + // A physical pixel is `2 / |W|` of normalized device coordinates; the widening is the least + // segment's. + let widen = |s: &[Segment]| { + (s.iter()) + .map(|s| WIDEN_PIXELS * 2.0 / s.extent.abs()) + .fold(0.0f64, f64::max) as f32 + }; + entries[1] = [widen(&xs), widen(&ys), 0.0, 0.0].map(f32::to_bits); + for (a, segments) in [&xs, &ys].into_iter().enumerate() { + let a32 = a as u32; + let target = (f64::from(target[a]), f64::from(target[a + 2])); + for (k, segment) in segments.iter().enumerate() { + let k = k as u32; + entries[line_entry(a32, k) as usize] = segment.line(target).map(f32::to_bits); + entries[clip_entry(a32, k) as usize] = segment.clip().map(f32::to_bits); + } + } + Some( + entries + .iter() + .flatten() + .flat_map(|w| w.to_le_bytes()) + .collect(), + ) +} + +#[cfg(test)] +mod tests; diff --git a/crates/metal2vulkan/src/bind/rate_map/fan_out/tests.rs b/crates/metal2vulkan/src/bind/rate_map/fan_out/tests.rs new file mode 100644 index 000000000..0572186e2 --- /dev/null +++ b/crates/metal2vulkan/src/bind/rate_map/fan_out/tests.rs @@ -0,0 +1,179 @@ +use super::*; +use crate::bind::rate_map::{ + RasterizationRateMap, RateMapDescriptor, RateMapLayerDescriptor, RegionLimits, +}; + +/// A map over `screen` whose quality falls from 1 at the centre to 0.3 at the edges on both +/// axes, planned for a viewport over the whole screen: each region's Vulkan viewport, y flipped +/// as the runtime draws it (`y + height`, `-height`), and its scissor; and the target's viewport. +fn falling(screen: [u32; 2]) -> (Vec<([f32; 4], [u32; 4])>, [f32; 4]) { + let quality = vec![0.3, 0.6, 1.0, 0.6, 0.3]; + let mut desc = RateMapDescriptor::new(screen); + desc.layers + .push(RateMapLayerDescriptor::new(quality.clone(), quality)); + let map = RasterizationRateMap::new(&desc).expect("map"); + let limits = RegionLimits::new([16384, 16384], [-32768.0, 32767.0]); + let whole = [0.0, 0.0, f64::from(screen[0]), f64::from(screen[1])]; + let plan = map.regions(0, whole, None, &limits).expect("plan"); + let regions = (plan.regions().iter()) + .map(|r| { + let [x, y, w, h] = r.viewport(); + let [sx, sy] = r.scissor_offset(); + let [sw, sh] = r.scissor_extent(); + ([x, y + h, w, -h], [sx, sy, sw, sh]) + }) + .filter(|(_, s)| s[2] > 0 && s[3] > 0) + .collect(); + let [pw, ph] = plan.physical_size().map(|v| v as f32); + (regions, [0.0, ph, pw, -ph]) +} + +/// The table's entry `e`, as floats. +fn entry(table: &[u8], e: u32) -> [f32; 4] { + let at = e as usize * 16; + [0, 1, 2, 3].map(|i| { + let word = &table[at + 4 * i..at + 4 * i + 4]; + f32::from_le_bytes(word.try_into().unwrap()) + }) +} + +/// The segment counts of the table. +fn counts(table: &[u8]) -> [u32; 2] { + let word = |i: usize| u32::from_le_bytes(table[4 * i..4 * i + 4].try_into().unwrap()); + [word(0), word(1)] +} + +/// The last segment of axis `a` whose least coordinate is at most `v`, or the first: the stage's +/// bisection. +fn find(table: &[u8], a: u32, v: f32) -> u32 { + let (mut lo, mut hi) = (0, counts(table)[a as usize] - 1); + while lo < hi { + let mid = (lo + hi).div_ceil(2); + match entry(table, line_entry(a, mid))[0] <= v { + true => lo = mid, + false => hi = mid - 1, + } + } + lo +} + +/// A small deterministic generator of floats in `[0, 1)`. +struct Lcg(u64); + +impl Lcg { + fn next(&mut self) -> f64 { + self.0 = self + .0 + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + (self.0 >> 11) as f64 / (1u64 << 53) as f64 + } +} + +/// Through each region's line in the table, a clip-space point lands at the window coordinate +/// the region's own viewport maps it to, and its clip distances hold it within the region's +/// scissor exactly where that coordinate lies inside. +#[test] +fn each_copy_lands_where_its_region_draws_and_clips_to_its_pixels() { + let (regions, target) = falling([3648, 1734]); + let table = table(target, ®ions).expect("table"); + assert_eq!(table.len() as u64, TABLE_BYTES); + let [nx, ny] = counts(&table); + assert_eq!(nx as usize * ny as usize, regions.len()); + let mut random = Lcg(7); + for _ in 0..2000 { + let w = 0.1 + 4.0 * random.next(); + let point = [0, 1].map(|_| (2.4 * random.next() - 1.2) * w); + for a in 0..2u32 { + let au = a as usize; + for k in 0..counts(&table)[au] { + let [_, _, sa, sb] = entry(&table, line_entry(a, k)); + let [half, lo, hi, _] = entry(&table, clip_entry(a, k)); + // The segment's region: its viewport on the axis from its line. + let (origin, extent, pixels) = (regions.iter()) + .map(|&(v, s)| (v[au], v[au + 2], [s[au], s[au] + s[au + 2]])) + .find(|&(x, ex, _)| { + let a_of = f64::from(ex) / f64::from(target[au + 2]); + (a_of - f64::from(sa)).abs() < 1e-6 + && ((2.0 * f64::from(x) + f64::from(ex) - 2.0 * f64::from(target[au])) + / f64::from(target[au + 2]) + - 1.0 + - f64::from(sb)) + .abs() + < 1e-5 + }) + .expect("the segment's region"); + let x = point[au]; + let window = f64::from(origin) + (x / w + 1.0) * f64::from(extent) / 2.0; + let moved = f64::from(sa) * x + f64::from(sb) * w; + let through = + f64::from(target[au]) + (moved / w + 1.0) * f64::from(target[au + 2]) / 2.0; + assert!( + (window - through).abs() < 2e-3, + "axis {a} segment {k}: {window} through its viewport, {through} through the table" + ); + let d_lo = f64::from(half) * x + f64::from(lo) * w; + let d_hi = -f64::from(half) * x + f64::from(hi) * w; + let inside = window >= f64::from(pixels[0]) && window <= f64::from(pixels[1]); + let margin = (window - f64::from(pixels[0])) + .abs() + .min((window - f64::from(pixels[1])).abs()); + if margin > 1e-2 { + assert_eq!( + d_lo >= 0.0 && d_hi >= 0.0, + inside, + "axis {a} segment {k}: window {window} in {pixels:?}" + ); + } + } + } + } +} + +/// The segments the bisection finds for an interval of normalized device coordinates hold every +/// segment with a pixel centre inside it. +#[test] +fn the_bisection_reaches_every_segment_with_a_pixel_centre_inside_the_bounds() { + for screen in [[3648, 1734], [1024, 1024], [100, 70]] { + let (regions, target) = falling(screen); + let table = table(target, ®ions).expect("table"); + let mut random = Lcg(11); + for _ in 0..500 { + for a in 0..2u32 { + let au = a as usize; + let (p, q) = (2.2 * random.next() - 1.1, 2.2 * random.next() - 1.1); + let span = 0.2 * random.next(); + let (lo, hi) = (p.min(q), p.min(q) + span.min((p - q).abs())); + let (i0, i1) = (find(&table, a, lo as f32), find(&table, a, hi as f32)); + for &(viewport, scissor) in ®ions { + let (origin, extent) = (f64::from(viewport[au]), f64::from(viewport[au + 2])); + let centres = (scissor[au]..scissor[au] + scissor[au + 2]) + .map(|p| 2.0 * (f64::from(p) + 0.5 - origin) / extent - 1.0); + if !centres.clone().any(|n| n >= lo && n <= hi) { + continue; + } + let ndc_lo = centres.fold(f64::INFINITY, f64::min); + let k = (0..counts(&table)[au]) + .find(|&k| { + let [l, h, _, _] = entry(&table, line_entry(a, k)); + f64::from(l) <= ndc_lo && ndc_lo <= f64::from(h) + }) + .expect("the region's segment"); + assert!( + (i0..=i1).contains(&k), + "{screen:?} axis {a}: [{lo}, {hi}] reaches segment {k}, the bisection \ + [{i0}, {i1}]" + ); + } + } + } + } +} + +/// Regions that are not one segment of each axis per pair, or none, take no table. +#[test] +fn regions_off_the_grid_take_no_table() { + let (regions, target) = falling([1024, 1024]); + assert!(table(target, ®ions[1..]).is_none()); + assert!(table(target, &[]).is_none()); +} diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 367ded3c1..764c571b6 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -483,6 +483,12 @@ pub struct VariantKey { /// (`RuntimeFact::RegionViewports`). #[cfg_attr(feature = "serde", serde(default))] pub region_viewports: bool, + /// The render pipeline draws a rasterization-rate-mapped pass's triangles once, its + /// triangle class's synthesized geometry stage emitting a copy of each per region it touches, + /// or probing which draws it cannot (`BindShape::region_fan_out`, `pipeline::link::fan_out`). + /// Its graphics state states it (`GraphicsState::region_fan_out`). + #[cfg_attr(feature = "serde", serde(default))] + pub region_fan_out: Option, } impl VariantKey { @@ -594,6 +600,7 @@ impl VariantKey { && self.anisotropic_samplers.is_empty() && self.color_group == 0 && !self.region_viewports + && self.region_fan_out.is_none() } /// The lowering inputs of the function of `stage` under this key: its storage-image choices, diff --git a/crates/metal2vulkan/src/lower/push.rs b/crates/metal2vulkan/src/lower/push.rs index b78f550db..f68616b6a 100644 --- a/crates/metal2vulkan/src/lower/push.rs +++ b/crates/metal2vulkan/src/lower/push.rs @@ -141,6 +141,8 @@ pub const fn shape(f: PushField) -> FieldShape { PushField::TessellationChunk => FieldShape::U32, // A band's viewport half extent and half width, four `f32`s. PushField::LineBand => FieldShape::UVec4Array(1), + // A fan-out probe's flag index. + PushField::RegionProbe => FieldShape::U32, // The whole indices from the bound index offset to the buffer's end, unsaturated: // `firstIndex + indexCount` reaches `2^33`. PushField::IndexCapacity => FieldShape::U64, diff --git a/crates/metal2vulkan/src/pipeline/compile/api.rs b/crates/metal2vulkan/src/pipeline/compile/api.rs index f9d685a72..32049ed03 100644 --- a/crates/metal2vulkan/src/pipeline/compile/api.rs +++ b/crates/metal2vulkan/src/pipeline/compile/api.rs @@ -1742,6 +1742,12 @@ fn variant_fields(v: &VariantKey) -> String { Some(crate::pipeline::BandPrimitive::Lines) => fields.push_str(" line_band"), Some(crate::pipeline::BandPrimitive::Triangles) => fields.push_str(" line_band triangles"), } + // The fan-out's synthesized geometry stages, in no stage's key. + match v.region_fan_out { + None => {} + Some(crate::pipeline::RegionFanOut::Draw) => fields.push_str(" region_fan_out"), + Some(crate::pipeline::RegionFanOut::Probe) => fields.push_str(" region_fan_out probe"), + } fields } @@ -1754,7 +1760,9 @@ fn render_fields(d: &RenderPipelineDescriptor) -> String { RenderLinkInputs::from(d), d.support_indirect_command_buffers ) - ); + ) + // A descriptor's inputs never fan out (`variant_fields` keys a variant that does). + .replace(", region_fan_out: None", ""); // Appended only past Metal's defaults, so a default descriptor keeps its key. let fields = match ( d.max_vertex_call_stack_depth, diff --git a/crates/metal2vulkan/src/pipeline/graphics.rs b/crates/metal2vulkan/src/pipeline/graphics.rs index ffee5bf65..9b84e263d 100644 --- a/crates/metal2vulkan/src/pipeline/graphics.rs +++ b/crates/metal2vulkan/src/pipeline/graphics.rs @@ -180,6 +180,11 @@ pub struct GraphicsState { /// evaluation stages, then the fragment stage. `None` for every other pipeline. #[cfg_attr(feature = "serde", serde(default))] pub line_band: Option, + /// A render pipeline variant that draws a rate-mapped pass's triangles once, fanned out to + /// their regions by its triangle class's geometry stage (`VariantKey::region_fan_out`, + /// `pipeline::link::fan_out`). `None` for every other pipeline. + #[cfg_attr(feature = "serde", serde(default))] + pub region_fan_out: Option, /// The vertex function writes `[[point_size]]` (as its compiled function's /// `writes_point_size` answers; a post-tessellation vertex function's is dropped and /// answers `false`). Metal sizes a point @@ -403,6 +408,47 @@ impl BandPrimitive { } } +/// What a fan-out variant of a render pipeline does with a rate-mapped pass's triangles +/// (`VariantKey::region_fan_out`, `GraphicsState::region_fan_out`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum RegionFanOut { + /// Draw each triangle once per region it touches, at most the stage's copies. + Draw, + /// Draw nothing, and flag the draw whose triangles the draw cannot fan out. + Probe, +} + +/// What a consumer and the binder need of a render pipeline variant that draws a rate-mapped +/// pass's triangles once, its triangle class's geometry stage fanning each out to the regions it +/// touches (`GraphicsState::region_fan_out`, `pipeline::link::fan_out`, `bind::fan_out` for the +/// table). +/// +/// Draw triangles alone, through one Vulkan viewport over the whole target and a scissor over it, +/// with the region table (`bind::fan_out::table`, `SyntheticBinding::RateMapRegions`) of that +/// viewport over the plan's regions bound. A probe ([`RegionFanOut::Probe`]) draws nothing: it +/// writes 1 at its pushed index (`u32`, `PushField::RegionProbe`, at +/// [`push_offset`](Self::push_offset) for stage `GEOMETRY`) of the flags buffer +/// (`SyntheticBinding::RateMapFlags`) where a triangle of the draw touches more regions than +/// [`copies`](Self::copies), or crosses `w = 0`; the consumer draws such a draw region by region. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct FanOutState { + /// What the variant does. + pub mode: RegionFanOut, + /// The most copies of a triangle its stage emits. + pub copies: u32, + /// Byte offset of the probe's push range (`PipelineLayout::push_constants`, stage + /// `GEOMETRY`, [`PUSH_BYTES`](Self::PUSH_BYTES)); 0 for a draw. + pub push_offset: u32, +} + +impl FanOutState { + /// The probe's push range's bytes: one `u32`. + pub const PUSH_BYTES: u32 = crate::pipeline::link::fan_out::PUSH_BYTES; +} + /// What a consumer and the binder need of a render pipeline variant that draws its lines, or its /// triangles' edges, as bands (`GraphicsState::line_band`): Apple's `setLineWidth:` at a width the /// device's own lines do not draw. @@ -516,6 +562,7 @@ impl GraphicsState { mesh_corners: None, emulated_tessellation: None, line_band: None, + region_fan_out: None, writes_point_size: false, flat_fragment_inputs: false, clip_distances: 0, diff --git a/crates/metal2vulkan/src/pipeline/link.rs b/crates/metal2vulkan/src/pipeline/link.rs index aba48ad67..f454037ee 100644 --- a/crates/metal2vulkan/src/pipeline/link.rs +++ b/crates/metal2vulkan/src/pipeline/link.rs @@ -49,6 +49,7 @@ pub mod band; pub mod contract; +pub mod fan_out; pub mod fetch; pub mod geometry; pub mod graphics; @@ -161,6 +162,7 @@ impl LinkInputs { r.pull_every = variant.primitive_id_indices.is_some() || variant.private_list; r.color_group = group; r.line_band = variant.line_band; + r.region_fan_out = variant.region_fan_out; LinkInputs::Render(Box::new(r)) } @@ -206,6 +208,10 @@ pub struct RenderLinkInputs { /// tessellation stages (`VariantKey::line_band`, [`band`]), each patch one primitive of this /// kind; `None` for every other variant. pub line_band: Option, + /// The variant draws a rate-mapped pass's triangles once, its triangle class's geometry stage + /// fanning each out to its regions (`VariantKey::region_fan_out`, [`fan_out`]); `None` for + /// every other variant. + pub region_fan_out: Option, } impl RenderLinkInputs { @@ -228,6 +234,7 @@ impl RenderLinkInputs { texture_write_rounding_mode: metal::TextureWriteRoundingMode::TowardZero, color_group: None, line_band: None, + region_fan_out: None, } } } @@ -257,6 +264,7 @@ impl From<&RenderPipelineDescriptor> for RenderLinkInputs { texture_write_rounding_mode: d.texture_write_rounding_mode, color_group: None, line_band: None, + region_fan_out: None, } } } @@ -370,6 +378,7 @@ pub fn link( r.input_primitive_topology, r.max_vertex_amplification_count, false, + r.region_fan_out, p, )?, LinkInputs::Mesh(r) => geometry::plan( @@ -377,6 +386,7 @@ pub fn link( r.input_primitive_topology, r.max_vertex_amplification_count, true, + r.region_fan_out, p, )?, LinkInputs::Standalone | LinkInputs::Compute => None, @@ -417,6 +427,14 @@ pub fn link( synthesized.push((mesh::RECORDS_SLOT, vk::ShaderStageFlags::VERTEX)); synthesized.push((mesh::WORK_SLOT, vk::ShaderStageFlags::VERTEX)); } + // A fan-out variant's triangle stage reads the region table, and a probe's writes its flags. + if let Some(fan) = geometry.as_ref().and_then(|g| g.fan_out) { + let stage = vk::ShaderStageFlags::GEOMETRY; + synthesized.push((fan_out::REGIONS_SLOT, stage)); + if fan.mode == crate::pipeline::RegionFanOut::Probe { + synthesized.push((fan_out::FLAGS_SLOT, stage)); + } + } let mut layout = layout(&ifaces, &synthesized, &mut table, p)?; count_variables(&mut layout, stages, &table); let control = match plan { @@ -453,9 +471,27 @@ pub fn link( } None => None, }; + // A fan-out probe's stage pushes the index of its flag. + let mut geometry = geometry; + if let Some(fan) = geometry.as_mut().and_then(|g| g.fan_out.as_mut()) { + if fan.mode == crate::pipeline::RegionFanOut::Probe { + let offset = tessellation::push_offset( + &layout.push_constants, + (fan_out::PUSH_BYTES, 4), + Feature::RasterizationRateMap, + p, + )?; + layout.push_constants.push(PushConstantRange { + stages: vk::ShaderStageFlags::GEOMETRY, + offset, + size: fan_out::PUSH_BYTES, + }); + fan.push_offset = offset; + } + } let specialization = specialize(&ifaces, &mut table)?; table.locations = varyings::assign(stages, p)?; - if let Some(g) = &geometry { + if let Some(g) = &mut geometry { g.check_limits(&table.locations, p)?; } let interface = pipeline_interface(&ifaces); @@ -510,6 +546,13 @@ pub fn link( primitive: b.primitive, }); } + if let Some(fan) = geometry.as_ref().and_then(|g| g.fan_out) { + gs.region_fan_out = Some(crate::pipeline::graphics::FanOutState { + mode: fan.mode, + copies: fan.copies, + push_offset: fan.push_offset, + }); + } (vi, Some(gs)) } // The mesh stage stands in the vertex stage's place; the fragment stage follows it. diff --git a/crates/metal2vulkan/src/pipeline/link/fan_out.rs b/crates/metal2vulkan/src/pipeline/link/fan_out.rs new file mode 100644 index 000000000..28c6c4a40 --- /dev/null +++ b/crates/metal2vulkan/src/pipeline/link/fan_out.rs @@ -0,0 +1,424 @@ +//! The fan-out geometry stage of a render pipeline variant that draws a rate-mapped pass's +//! triangles once (`VariantKey::region_fan_out`): the vertex function runs once per vertex, and +//! the triangle class's geometry stage emits a copy of each triangle for each region it touches, +//! through the region table's lines and clip distances (`bind::fan_out`, its layout and math), +//! where the regions route records each draw once per region. +//! +//! The stage passes through what [`GeometryStages`] passes through (the vertex outputs the +//! fragment stage reads, the vertex function's clip distances, `PrimitiveId`), emits each copy's +//! vertices in the order it receives them, so a copy keeps the triangle's winding and provoking +//! vertex, and writes four clip distances past the vertex function's, which keep the copy's +//! region's pixels. Its point and line classes' stages are the plain ones: the variant draws +//! triangles alone. +//! +//! - **Draw** ([`RegionFanOut::Draw`]): a triangle every `w` of which is positive emits one copy +//! per pair of segments its bounds reach, at most [`FanOutStage::copies`]; one with no positive +//! `w`, or one past the segments, emits none, and so does one with some `w` not positive, which +//! the probe found. +//! - **Probe** ([`RegionFanOut::Probe`]): emits nothing, and writes 1 into the flags buffer at +//! the index the draw pushes (`PushField::RegionProbe`) for a triangle the draw cannot fan out: +//! one with some `w` not positive and another positive, or whose bounds, widened by the table's +//! widening, reach more pairs than the copies. Its writes need `vertexPipelineStoresAndAtomics`. + +use super::geometry::{array, kf, ku, scalar, GeometryStages}; +use crate::bind::fan_out::{clip_entry, line_entry, MAX_SEGMENTS}; +use crate::pipeline::graphics::RegionFanOut; +use crate::pipeline::stage_io::IoNumeric; +use crate::pipeline::sym::{PushField, ResourceKind, ResourceSlot, Stage, SyntheticBinding}; +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, ConvOp, ExecMode, ExecModel, GlslOp, IoDecor, IoDir, LayoutRule, + MemAccess, Scope, Semantics, StorageClass, Type, TypedModule, UnOp, +}; +use crate::spv::BuiltIn as B; + +/// The most copies of a triangle a draw's stage emits: past it, a device's geometry stage +/// reserves output for vertices most triangles never emit. +pub const MOST_COPIES: u32 = 16; + +/// The bytes of the probe's push range: the index of the flag it writes. +pub const PUSH_BYTES: u32 = 4; + +/// The binding symbol of the region table (`SyntheticBinding::RateMapRegions`), declared with +/// the vertex stage's symbols. +pub const REGIONS_SLOT: ResourceSlot = ResourceSlot { + stage: Stage::Vertex, + kind: ResourceKind::Synthetic(SyntheticBinding::RateMapRegions), + index: 0, +}; + +/// The binding symbol of the probe's flags (`SyntheticBinding::RateMapFlags`), declared with the +/// vertex stage's symbols. +pub const FLAGS_SLOT: ResourceSlot = ResourceSlot { + stage: Stage::Vertex, + kind: ResourceKind::Synthetic(SyntheticBinding::RateMapFlags), + index: 0, +}; + +/// A fan-out variant's triangle stage (the module docs). +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FanOutStage { + /// What it does. + pub mode: RegionFanOut, + /// The most copies of a triangle it emits, what the device's geometry limits leave for its + /// vertices' outputs, at most [`MOST_COPIES`]: set once link placed the varyings. + pub copies: u32, + /// The byte offset of the probe's push range ([`PUSH_BYTES`]); 0 for a draw. + pub push_offset: u32, +} + +impl FanOutStage { + /// The stage of `mode`, its copies and push offset not yet placed. + pub fn new(mode: RegionFanOut) -> FanOutStage { + FanOutStage { + mode, + copies: 0, + push_offset: 0, + } + } +} + +/// The values the copies are made from. +struct Copies { + table: GlobalId, + positions: [Value; 3], + own_clips: Option, + own: u32, + clips: GlobalId, + position: GlobalId, + carried: Vec<(GlobalId, GlobalId)>, + primitive: Option<(GlobalId, GlobalId)>, + vec4: TypeId, + f32_: TypeId, +} + +/// The table's word `word` (a `uint` value). +fn word(fb: &mut FunctionBuilder<'_>, table: GlobalId, word: Value) -> BResult { + let base = fb.module().global_value(table)?; + let member = ku(fb, 0)?; + let ptr = fb.access_chain(base, &[member, word])?; + fb.load(ptr, MemAccess::default()) +} + +/// Component `c` of entry `entry` plus `k` of the table, as a float: `k` a `uint` value, or none. +fn component( + fb: &mut FunctionBuilder<'_>, + (table, f32_): (GlobalId, TypeId), + entry: u32, + k: Option, + c: u32, +) -> BResult { + let at = ku(fb, entry * 4 + c)?; + let at = match k { + Some(k) => { + let four = ku(fb, 4)?; + let k4 = fb.binary(BinOp::IMul, k, four)?; + fb.binary(BinOp::IAdd, at, k4)? + } + None => at, + }; + let bits = word(fb, table, at)?; + fb.convert(ConvOp::Bitcast, bits, f32_) +} + +/// The last segment of axis `axis` (of `n`) whose least coordinate is at most `v`, or the first: +/// a bisection of `log2(MAX_SEGMENTS)` steps over the table's lines. +fn find( + fb: &mut FunctionBuilder<'_>, + table: (GlobalId, TypeId), + axis: u32, + n: Value, + v: Value, +) -> BResult { + let zero = ku(fb, 0)?; + let one = ku(fb, 1)?; + let empty = fb.binary(BinOp::IEqual, n, zero)?; + let last = fb.binary(BinOp::ISub, n, one)?; + let mut lo = zero; + let mut hi = fb.select(empty, zero, last)?; + for _ in 0..MAX_SEGMENTS.ilog2() { + let open = fb.binary(BinOp::ULessThan, lo, hi)?; + let sum = fb.binary(BinOp::IAdd, lo, hi)?; + let sum = fb.binary(BinOp::IAdd, sum, one)?; + let mid = fb.binary(BinOp::ShiftRightLogical, sum, one)?; + let at = component(fb, table, line_entry(axis, 0), Some(mid), 0)?; + let below = fb.binary(BinOp::FOrdLessThanEqual, at, v)?; + let above = fb.unary(UnOp::LogicalNot, below)?; + let up = fb.binary(BinOp::LogicalAnd, open, below)?; + let down = fb.binary(BinOp::LogicalAnd, open, above)?; + let before = fb.binary(BinOp::ISub, mid, one)?; + lo = fb.select(up, mid, lo)?; + hi = fb.select(down, before, hi)?; + } + Ok(lo) +} + +/// The least or the greatest of three floats. +fn extreme(fb: &mut FunctionBuilder<'_>, op: GlslOp, v: [Value; 3]) -> BResult { + let two = fb.glsl(op, &[v[0], v[1]])?; + fb.glsl(op, &[two, v[2]]) +} + +/// Emit the copy of the triangle for segments `sx` and `sy`: each vertex through their lines, +/// with their clip distances past the vertex function's. +fn emit_copy(fb: &mut FunctionBuilder<'_>, c: &Copies, (sx, sy): (Value, Value)) -> BResult<()> { + let table = (c.table, c.f32_); + let mut axes = Vec::with_capacity(2); + for (axis, s) in [(0, sx), (1, sy)] { + let a = component(fb, table, line_entry(axis, 0), Some(s), 2)?; + let b = component(fb, table, line_entry(axis, 0), Some(s), 3)?; + let half = component(fb, table, clip_entry(axis, 0), Some(s), 0)?; + let lo = component(fb, table, clip_entry(axis, 0), Some(s), 1)?; + let hi = component(fb, table, clip_entry(axis, 0), Some(s), 2)?; + axes.push((a, b, half, lo, hi)); + } + for (k, &p) in c.positions.iter().enumerate() { + let at = ku(fb, k as u32)?; + let w = fb.composite_extract(p, &[3])?; + let z = fb.composite_extract(p, &[2])?; + let mut moved = Vec::with_capacity(2); + let mut distances = Vec::with_capacity(4); + for (axis, &(a, b, half, lo, hi)) in axes.iter().enumerate() { + let v = fb.composite_extract(p, &[axis as u32])?; + let av = fb.binary(BinOp::FMul, a, v)?; + let bw = fb.binary(BinOp::FMul, b, w)?; + moved.push(fb.binary(BinOp::FAdd, av, bw)?); + let hv = fb.binary(BinOp::FMul, half, v)?; + let low = fb.binary(BinOp::FMul, lo, w)?; + distances.push(fb.binary(BinOp::FAdd, hv, low)?); + let high = fb.binary(BinOp::FMul, hi, w)?; + distances.push(fb.binary(BinOp::FSub, high, hv)?); + } + let position = fb.composite_construct(c.vec4, &[moved[0], moved[1], z, w])?; + let to = fb.module().global_value(c.position)?; + fb.store(to, position, MemAccess::default())?; + let clips = fb.module().global_value(c.clips)?; + if let Some(own) = c.own_clips { + let from = fb.module().global_value(own)?; + for e in 0..c.own { + let element = ku(fb, e)?; + let ptr = fb.access_chain(from, &[at, element])?; + let value = fb.load(ptr, MemAccess::default())?; + let to = fb.access_chain(clips, &[element])?; + fb.store(to, value, MemAccess::default())?; + } + } + for (e, &d) in distances.iter().enumerate() { + let element = ku(fb, c.own + e as u32)?; + let to = fb.access_chain(clips, &[element])?; + fb.store(to, d, MemAccess::default())?; + } + for &(input, output) in &c.carried { + let base = fb.module().global_value(input)?; + let from = fb.access_chain(base, &[at])?; + let value = fb.load(from, MemAccess::default())?; + let to = fb.module().global_value(output)?; + fb.store(to, value, MemAccess::default())?; + } + if let Some((input, output)) = c.primitive { + let from = fb.module().global_value(input)?; + let value = fb.load(from, MemAccess::default())?; + let to = fb.module().global_value(output)?; + fb.store(to, value, MemAccess::default())?; + } + fb.emit_vertex()?; + } + fb.end_primitive() +} + +/// The fan-out variant's triangle stage of `stages` (the module docs). +pub(super) fn module(stages: &GeometryStages, fan: FanOutStage) -> BResult { + let mut mb = ModuleBuilder::new(); + let u32_ = scalar(&mut mb, IoNumeric::Uint)?; + let f32_ = scalar(&mut mb, IoNumeric::Float)?; + let vec4 = mb.ty(Type::Vector { elem: f32_, len: 4 })?; + let void = mb.ty(Type::Void)?; + let ty = array(&mut mb, vec4, 3)?; + let positions = mb.builtin(B::Position, IoDir::Input, ty)?; + let position = mb.builtin(B::Position, IoDir::Output, vec4)?; + let own = stages.clip_distances; + let own_clips = match own { + 0 => None, + n => { + let clip = array(&mut mb, f32_, n)?; + let ty = array(&mut mb, clip, 3)?; + Some(mb.builtin(B::ClipDistance, IoDir::Input, ty)?) + } + }; + let ty = array(&mut mb, f32_, own + 4)?; + let clips = mb.builtin(B::ClipDistance, IoDir::Output, ty)?; + let packed = IoDecor { + packed: true, + ..IoDecor::default() + }; + let mut carried = Vec::with_capacity(stages.varyings.len()); + for (key, io) in &stages.varyings { + let elem = scalar(&mut mb, io.numeric)?; + let ty = match io.components { + 1 => elem, + c => mb.ty(Type::Vector { elem, len: c })?, + }; + let input_ty = array(&mut mb, ty, 3)?; + carried.push(( + mb.io(key.clone(), IoDir::Input, input_ty, packed)?, + mb.io(key.clone(), IoDir::Output, ty, packed)?, + )); + } + let primitive = match stages.primitive_id { + true => Some(( + mb.builtin(B::PrimitiveId, IoDir::Input, u32_)?, + mb.builtin(B::PrimitiveId, IoDir::Output, u32_)?, + )), + false => None, + }; + let words = mb.ty(Type::RuntimeArray { + elem: u32_, + stride: Some(4), + })?; + let block_layout = natural_layout(mb.types(), LayoutRule::Std430, true, &[words])?; + let block = mb.ty(Type::Struct { + members: [words].into(), + layout: Some(block_layout), + })?; + let table = mb.resource(REGIONS_SLOT, StorageClass::StorageBuffer, block)?; + let probe = match fan.mode { + RegionFanOut::Probe => { + let flags = mb.resource(FLAGS_SLOT, StorageClass::StorageBuffer, block)?; + let member = (mb.push_member(PushField::RegionProbe, u32_, fan.push_offset)?).index; + Some((flags, member, mb.push_global()?)) + } + RegionFanOut::Draw => None, + }; + let mut fb = mb.function(void)?; + let mut loaded = Vec::with_capacity(3); + for k in 0..3 { + let at = ku(&mut fb, k)?; + let base = fb.module().global_value(positions)?; + let from = fb.access_chain(base, &[at])?; + loaded.push(fb.load(from, MemAccess::default())?); + } + let positions = [loaded[0], loaded[1], loaded[2]]; + let zero = kf(&mut fb, 0.0)?; + let mut positive = Vec::with_capacity(3); + for &p in &positions { + let w = fb.composite_extract(p, &[3])?; + positive.push(fb.binary(BinOp::FOrdGreaterThan, w, zero)?); + } + let two = fb.binary(BinOp::LogicalAnd, positive[0], positive[1])?; + let every = fb.binary(BinOp::LogicalAnd, two, positive[2])?; + let two = fb.binary(BinOp::LogicalOr, positive[0], positive[1])?; + let some = fb.binary(BinOp::LogicalOr, two, positive[2])?; + let table_f = (table, f32_); + let header = ku(&mut fb, 0)?; + let nx = word(&mut fb, table, header)?; + let header = ku(&mut fb, 1)?; + let ny = word(&mut fb, table, header)?; + let one = ku(&mut fb, 1)?; + // Per axis: the first segment its bounds reach, how many, and whether they reach any. + let mut reach = Vec::with_capacity(2); + for (axis, n) in [(0u32, nx), (1, ny)] { + let mut ndc = Vec::with_capacity(3); + for &p in &positions { + let v = fb.composite_extract(p, &[axis])?; + let w = fb.composite_extract(p, &[3])?; + ndc.push(fb.binary(BinOp::FDiv, v, w)?); + } + let ndc = [ndc[0], ndc[1], ndc[2]]; + let mut lo = extreme(&mut fb, GlslOp::FMin, ndc)?; + let mut hi = extreme(&mut fb, GlslOp::FMax, ndc)?; + if probe.is_some() { + let widen = component(&mut fb, table_f, 1, None, axis)?; + lo = fb.binary(BinOp::FSub, lo, widen)?; + hi = fb.binary(BinOp::FAdd, hi, widen)?; + } + let first = component(&mut fb, table_f, line_entry(axis, 0), None, 0)?; + let last = fb.binary(BinOp::ISub, n, one)?; + let end = component(&mut fb, table_f, line_entry(axis, 0), Some(last), 1)?; + let after = fb.binary(BinOp::FOrdGreaterThanEqual, hi, first)?; + let before = fb.binary(BinOp::FOrdLessThanEqual, lo, end)?; + let inside = fb.binary(BinOp::LogicalAnd, after, before)?; + let i0 = find(&mut fb, table_f, axis, n, lo)?; + let i1 = find(&mut fb, table_f, axis, n, hi)?; + let span = fb.binary(BinOp::ISub, i1, i0)?; + let span = fb.binary(BinOp::IAdd, span, one)?; + reach.push((i0, span, inside)); + } + let (x0, xs, x_in) = reach[0]; + let (y0, ys, y_in) = reach[1]; + let both = fb.binary(BinOp::LogicalAnd, x_in, y_in)?; + let fans = fb.binary(BinOp::LogicalAnd, every, both)?; + let pairs = fb.binary(BinOp::IMul, xs, ys)?; + let none = ku(&mut fb, 0)?; + let count = fb.select(fans, pairs, none)?; + let copies = fan.copies.max(1); + let mut ctx = (); + match probe { + Some((flags, member, push)) => { + // Some `w` not positive beside a positive one, or more pairs than the copies. + let straddles = fb.unary(UnOp::LogicalNot, every)?; + let straddles = fb.binary(BinOp::LogicalAnd, some, straddles)?; + let most = ku(&mut fb, copies)?; + let over = fb.binary(BinOp::UGreaterThan, count, most)?; + let flagged = fb.binary(BinOp::LogicalOr, straddles, over)?; + let arm: ArmFn<'_, ()> = Box::new(move |fb, _| { + let base = fb.module().global_value(push)?; + let index = ku(fb, member)?; + let ptr = fb.access_chain(base, &[index])?; + let at = fb.load(ptr, MemAccess::default())?; + let base = fb.module().global_value(flags)?; + let zero = ku(fb, 0)?; + let ptr = fb.access_chain(base, &[zero, at])?; + let one = ku(fb, 1)?; + fb.atomic_store(ptr, Scope::Device, Semantics::RELAXED, one)?; + Ok(ArmEnd::FallThrough(Vec::new())) + }); + fb.if_(&mut ctx, flagged, arm, None)?; + } + None => { + let c = Copies { + table, + positions, + own_clips, + own, + clips, + position, + carried, + primitive, + vec4, + f32_, + }; + for i in 0..copies { + let at = ku(&mut fb, i)?; + let due = fb.binary(BinOp::ULessThan, at, count)?; + let c = &c; + let arm: ArmFn<'_, ()> = Box::new(move |fb, _| { + let across = fb.binary(BinOp::UMod, at, xs)?; + let down = fb.binary(BinOp::UDiv, at, xs)?; + let sx = fb.binary(BinOp::IAdd, x0, across)?; + let sy = fb.binary(BinOp::IAdd, y0, down)?; + emit_copy(fb, c, (sx, sy))?; + Ok(ArmEnd::FallThrough(Vec::new())) + }); + fb.if_(&mut ctx, due, arm, None)?; + } + } + } + fb.ret(None)?; + let f = fb.finish()?; + let vertices = match fan.mode { + RegionFanOut::Draw => 3 * copies, + RegionFanOut::Probe => 3, + }; + let modes = vec![ + ExecMode::Triangles, + ExecMode::OutputTriangleStrip, + ExecMode::OutputVertices { n: vertices }, + ExecMode::Invocations { n: 1 }, + ]; + mb.entry(ExecModel::Geometry, f, modes)?; + mb.finalize() +} diff --git a/crates/metal2vulkan/src/pipeline/link/geometry.rs b/crates/metal2vulkan/src/pipeline/link/geometry.rs index 8108d4383..40544657e 100644 --- a/crates/metal2vulkan/src/pipeline/link/geometry.rs +++ b/crates/metal2vulkan/src/pipeline/link/geometry.rs @@ -76,13 +76,26 @@ //! Each needs `fragmentShaderBarycentric` instead, or `shaderOutputLayer` and //! `shaderOutputViewportIndex` for the indices the stage selects. A device without //! `geometryShader` either is refused at the function (`lower::stage_io`). +//! +//! A variant that draws a rate-mapped pass's triangles once (`VariantKey::region_fan_out`) +//! carries the stages too, its triangle class's the fan-out stage ([`fan_out`](super::fan_out)), +//! which needs `geometryShader` and `shaderClipDistance`, four clip distances past the vertex +//! function's within `maxClipDistances` and `maxCombinedClipAndCullDistances`, and room in +//! `maxGeometryTotalOutputComponents` for one copy's vertices; and, for the probe, +//! `vertexPipelineStoresAndAtomics`. Refused as `NotImplemented(RasterizationRateMap)` beside +//! another reason for the stages, for a mesh or post-tessellation vertex function, and a pipeline +//! that amplifies its vertices; as `Unsupported{RasterizationRateMap}` needing what the device +//! lacks otherwise. The consumer draws +//! such a pipeline region by region instead. +use super::fan_out::{self, FanOutStage}; use crate::budget::Meter; use crate::device::requirements::{Requirements, VkFeature, VkLimit}; use crate::device::DeviceProfile; use crate::error::{Capability, Error, Feature, Unsupported}; use crate::metal::PrimitiveTopologyClass; use crate::pipeline::artifact::{Reconvergence, SpecializationLayout, StageModule, StrategyCensus}; +use crate::pipeline::graphics::RegionFanOut; use crate::pipeline::interface::StageInterface; use crate::pipeline::link::varyings::Locations; use crate::pipeline::stage_io::{IoNumeric, IoRole, IoType, StageBuiltin}; @@ -130,6 +143,8 @@ pub struct GeometryStages { pub primitive_id: bool, /// The pipeline is drawn as multiview. pub multiview: bool, + /// The triangle class's stage is the fan-out stage ([`fan_out`](super::fan_out)). + pub fan_out: Option, } /// Why the stages are made: the fragment stage reads the weights, or else the vertex function @@ -177,14 +192,16 @@ impl Reason { /// The geometry stages of the render pipeline of stages `ifaces` (vertex, then fragment when it /// has one), drawn as `class` with vertex amplification up to `amplification`, where its fragment -/// stage reads the weights as varyings or its vertex function selects an index through them; -/// `None` where neither. Refused as the module docs state. A mesh pipeline (`mesh`) whose fragment -/// stage reads the weights is not implemented. +/// stage reads the weights as varyings or its vertex function selects an index through them, or +/// its variant fans a rate-mapped pass's triangles out (`fan_out`); `None` where none. Refused as +/// the module docs state. A mesh pipeline (`mesh`) whose fragment stage reads the weights is not +/// implemented. pub fn plan( ifaces: &[&StageInterface], class: PrimitiveTopologyClass, amplification: u32, mesh: bool, + fan_out: Option, p: &DeviceProfile, ) -> Result, Error> { let fragment = ifaces.iter().find(|i| i.stage == Stage::Fragment); @@ -206,6 +223,9 @@ pub fn plan( layer: selects(IoRole::SelectedLayer), viewport: selects(IoRole::SelectedViewport), }; + if let Some(mode) = fan_out { + return fan_plan(ifaces, (why, mode), (amplification, mesh), p).map(Some); + } if !why.weights && !why.layer && !why.viewport { return Ok(None); } @@ -276,9 +296,93 @@ pub fn plan( writes_point_size, primitive_id: fragment.is_some_and(|f| f.io.builtins.contains(&StageBuiltin::PrimitiveId)), multiview, + fan_out: None, })) } +/// The stages of a fan-out variant (the module docs): refused beside another reason for them +/// (`why`), and where the pipeline or the device cannot carry the stage, `mode`'s. +fn fan_plan( + ifaces: &[&StageInterface], + (why, mode): (Reason, RegionFanOut), + (amplification, mesh): (u32, bool), + p: &DeviceProfile, +) -> Result { + let not_implemented = || Unsupported::not_implemented(Feature::RasterizationRateMap).into(); + let fragment = ifaces.iter().find(|i| i.stage == Stage::Fragment); + let vertex = match ifaces.iter().find(|i| i.stage == Stage::Vertex) { + Some(v) if !mesh && v.tessellation.is_none() => v, + _ => return Err(not_implemented()), + }; + let builtins = &vertex.io.builtins; + if why.weights || why.layer || why.viewport || amplification > 1 { + return Err(not_implemented()); + } + let f = p.fields(); + let enabled = &f.enabled.features; + let mut needs = vec![VkFeature::GeometryShader, VkFeature::ShaderClipDistance]; + if mode == RegionFanOut::Probe { + needs.push(VkFeature::VertexPipelineStoresAndAtomics); + } + if let Some(&lacks) = needs.iter().find(|n| !enabled.contains(n)) { + return Err(Unsupported::needs_any_of( + Feature::RasterizationRateMap, + vec![vec![Capability::Feature(lacks)]], + ) + .into()); + } + let clip_distances = builtins + .iter() + .find_map(|b| match b { + StageBuiltin::ClipDistance { count } => Some(*count), + _ => None, + }) + .unwrap_or(0); + let l = &f.limits; + for (limit, available) in [ + (VkLimit::MaxClipDistances, l.max_clip_distances), + ( + VkLimit::MaxCombinedClipAndCullDistances, + l.max_combined_clip_and_cull_distances, + ), + ] { + let required = u64::from(clip_distances) + 4; + if required > u64::from(available) { + return Err(Unsupported::needs_any_of( + Feature::RasterizationRateMap, + vec![vec![Capability::Limit { + limit, + required, + available: u64::from(available), + }]], + ) + .into()); + } + } + let varyings = vertex + .io + .outputs + .iter() + .filter(|o| fragment.is_some_and(|f| f.io.inputs.iter().any(|i| i.key == o.key))) + .map(|o| (o.key.clone(), o.ty)) + .collect(); + let point_size = builtins + .iter() + .any(|b| matches!(b, StageBuiltin::PointSize { .. })); + Ok(GeometryStages { + varyings, + forms: Vec::new(), + layer: false, + viewport: false, + clip_distances, + point_size, + writes_point_size: enabled.contains(&VkFeature::ShaderTessellationAndGeometryPointSize), + primitive_id: fragment.is_some_and(|f| f.io.builtins.contains(&StageBuiltin::PrimitiveId)), + multiview: false, + fan_out: Some(FanOutStage::new(mode)), + }) +} + impl GeometryStages { /// Why the stages are made ([`Reason`]). fn reason(&self) -> Reason { @@ -299,8 +403,8 @@ impl GeometryStages { } /// Refuses stages whose inputs or outputs at `locations` pass the device's geometry limits - /// (the module docs). - pub fn check_limits(&self, locations: &Locations, p: &DeviceProfile) -> Result<(), Error> { + /// (the module docs); for a fan-out variant, sets the copies its triangle stage emits. + pub fn check_limits(&mut self, locations: &Locations, p: &DeviceProfile) -> Result<(), Error> { let l = &p.fields().limits; let end = |keys: &mut dyn Iterator| -> Result { let mut end = 0u64; @@ -323,6 +427,24 @@ impl GeometryStages { let selected: Vec = self.selected().map(|(k, _)| k).collect(); let inputs = end(&mut self.varyings.iter().map(|(k, _)| k).chain(&selected))?; let outputs = end(&mut self.varyings.iter().map(|(k, _)| k).chain(&weights))?; + // A copy's vertex: its varyings' locations, its position, its clip distances and its + // primitive ID, in components. + if let Some(fan) = &mut self.fan_out { + let vertex = outputs * 4 + 4 + u64::from(self.clip_distances) + 4 + 1; + let room = u64::from(l.max_geometry_total_output_components) / (3 * vertex); + if room == 0 { + return Err(Unsupported::needs_any_of( + Feature::RasterizationRateMap, + vec![vec![Capability::Limit { + limit: VkLimit::MaxGeometryTotalOutputComponents, + required: 3 * vertex, + available: u64::from(l.max_geometry_total_output_components), + }]], + ) + .into()); + } + fan.copies = room.min(u64::from(fan_out::MOST_COPIES)) as u32; + } let vertices = 3u64; for (limit, required, available) in [ ( @@ -402,6 +524,9 @@ impl GeometryStages { /// The geometry stage of `class` (the module docs). pub fn module(&self, class: PrimitiveTopologyClass) -> BResult { + if let (PrimitiveTopologyClass::Triangle, Some(fan)) = (class, self.fan_out) { + return fan_out::module(self, fan); + } let (n, input, output) = match class { PrimitiveTopologyClass::Point => (1, ExecMode::InputPoints, ExecMode::OutputPoints), PrimitiveTopologyClass::Line => (2, ExecMode::InputLines, ExecMode::OutputLineStrip), diff --git a/crates/metal2vulkan/src/pipeline/link/tests.rs b/crates/metal2vulkan/src/pipeline/link/tests.rs index 5c01a2376..b80522ad0 100644 --- a/crates/metal2vulkan/src/pipeline/link/tests.rs +++ b/crates/metal2vulkan/src/pipeline/link/tests.rs @@ -2,6 +2,7 @@ //! limits (the sweep over every committed profile), stage-interface locations and packing, vertex //! input, graphics state, and the property over random pipelines. +mod fan_out; mod geometry; mod property; mod render; diff --git a/crates/metal2vulkan/src/pipeline/link/tests/fan_out.rs b/crates/metal2vulkan/src/pipeline/link/tests/fan_out.rs new file mode 100644 index 000000000..b4e2b932a --- /dev/null +++ b/crates/metal2vulkan/src/pipeline/link/tests/fan_out.rs @@ -0,0 +1,180 @@ +//! The fan-out variant's geometry stages (`link::fan_out`): its triangle class's stage emits as +//! many copies as the device's limits leave room for, a probe's none, each module valid on the +//! device; a probe pushes its flag's index; and the refusals. + +use super::*; +use crate::error::Needs; +use crate::metal::PrimitiveTopologyClass as Class; +use crate::pipeline::link::geometry::{plan, GeometryStages, CLASSES}; +use crate::pipeline::stage_io::StageBuiltin; +use crate::pipeline::RegionFanOut; + +fn stage(stage: Stage, io: StageIo) -> FunctionArtifact { + let mut i = iface(stage, vec![], vec![]); + i.io = io; + artifact(i, None) +} + +/// A vertex function writing `a` (`float4`), its position and two clip distances, and a +/// fragment function reading `a` and the primitive ID. +fn pipeline() -> (FunctionArtifact, FunctionArtifact) { + let f4 = io_ty(IoNumeric::Float, 4); + let mut vio = stage_io(vec![], vec![varying("a", f4, None)]); + vio.builtins = vec![ + StageBuiltin::Position { invariant: false }, + StageBuiltin::ClipDistance { count: 2 }, + ]; + let mut fio = stage_io(vec![varying("a", f4, SMOOTH)], vec![color(0, 0, f4)]); + fio.builtins = vec![StageBuiltin::PrimitiveId]; + (stage(Stage::Vertex, vio), stage(Stage::Fragment, fio)) +} + +fn fanned(mode: RegionFanOut) -> LinkInputs { + let mut r = RenderLinkInputs::new(); + r.color_attachments[0] = Some(crate::pipeline::descriptor::ColorAttachmentDescriptor::new( + crate::metal::PixelFormat::RGBA32Float, + )); + r.input_primitive_topology = Class::Triangle; + r.region_fan_out = Some(mode); + LinkInputs::Render(Box::new(r)) +} + +/// How many instructions of `words` have opcode `op`. +fn count_ops(words: &[u32], op: u32) -> usize { + let mut i = 5; + let mut n = 0; + while let Some(&w) = words.get(i) { + let len = (w >> 16) as usize; + n += usize::from(w & 0xFFFF == op); + if len == 0 { + break; + } + i += len; + } + n +} + +/// A draw's triangle stage emits three vertices a copy, as many copies as its state says, and a +/// probe's none and pushes its flag's index in the geometry stage's own range; every class's +/// module is valid on the device. +#[test] +fn a_fan_out_variant_s_triangle_stage_emits_its_copies() { + for stem in ["lavapipe", "intel-irisxe-rplp-anv", "nvidia-pascal-linux"] { + let p = profile(stem); + let (v, f) = pipeline(); + for mode in [RegionFanOut::Draw, RegionFanOut::Probe] { + let linked = + link(&[&v, &f], &fanned(mode), &p).unwrap_or_else(|e| panic!("{stem}: {e}")); + let g = linked.geometry.as_ref().expect("geometry stages"); + let fan = g.fan_out.expect("the fan-out stage"); + assert!((1..=16).contains(&fan.copies), "{stem}: {}", fan.copies); + let state = linked + .graphics + .as_ref() + .and_then(|g| g.region_fan_out) + .expect("the fan-out state"); + assert_eq!( + (state.mode, state.copies, state.push_offset), + (mode, fan.copies, fan.push_offset), + "{stem}" + ); + let pushes = (linked.layout.push_constants.iter()) + .filter(|r| r.stages == vk::ShaderStageFlags::GEOMETRY) + .map(|r| (r.offset, r.size)) + .collect::>(); + match mode { + RegionFanOut::Draw => assert!(pushes.is_empty(), "{stem}"), + RegionFanOut::Probe => assert_eq!(pushes, [(fan.push_offset, 4)], "{stem}"), + } + let made = g + .stages(&linked, &p, &mut crate::pipeline::testing::meter()) + .unwrap_or_else(|e| panic!("{stem} {mode:?}: {e}")); + for ((module, requirements), class) in made.iter().zip(CLASSES) { + crate::spirv::testing::check_words_valid(&module.spirv, requirements, &p) + .unwrap_or_else(|e| panic!("{stem} {mode:?} {class:?}: {e}")); + let emits = count_ops(&module.spirv, crate::spv::Op::EmitVertex as u32); + let expected = match (class, mode) { + (Class::Point, _) => 1, + (Class::Line, _) => 2, + (_, RegionFanOut::Draw) => 3 * fan.copies as usize, + (_, RegionFanOut::Probe) => 0, + }; + assert_eq!(emits, expected, "{stem} {mode:?} {class:?}"); + } + } + } +} + +fn not_implemented(e: Error) { + match e { + Error::Unsupported(u) => { + assert_eq!(u.feature, Feature::RasterizationRateMap); + assert_eq!(u.needs, Needs::NotImplemented); + } + other => panic!("{other:?}"), + } +} + +/// A fan-out beside another reason for the stages (a fragment function reading the weights where +/// the device reads none), of a mesh or post-tessellation vertex function, or of a pipeline that +/// amplifies its vertices is not implemented; a probe on a device without +/// `vertexPipelineStoresAndAtomics` needs it, where a draw takes the stages. +#[test] +fn what_the_fan_out_cannot_carry_is_refused() { + let mut p = profile("lavapipe"); + p.edit(|x| { + x.enabled + .features + .remove(&VkFeature::FragmentShaderBarycentric); + }); + let (v, f) = pipeline(); + let run = |v: &FunctionArtifact, + f: &FunctionArtifact, + amplification, + mesh, + mode, + p: &DeviceProfile| { + let i = [v.interface.clone(), f.interface.clone()]; + let refs: Vec<&StageInterface> = i.iter().collect(); + plan(&refs, Class::Triangle, amplification, mesh, Some(mode), p) + }; + for mode in [RegionFanOut::Draw, RegionFanOut::Probe] { + let g: GeometryStages = run(&v, &f, 1, false, mode, &p).unwrap().unwrap(); + assert_eq!(g.fan_out.map(|s| s.mode), Some(mode)); + assert_eq!(g.clip_distances, 2); + let mut weights = f.clone(); + weights.interface.io.inputs.push(IoVariable { + key: VaryingKey::barycentric(true), + role: IoRole::Barycentric { perspective: true }, + ty: io_ty(IoNumeric::Float, 2), + }); + not_implemented(run(&v, &weights, 1, false, mode, &p).unwrap_err()); + not_implemented(run(&v, &f, 2, false, mode, &p).unwrap_err()); + not_implemented(run(&v, &f, 1, true, mode, &p).unwrap_err()); + let mut tess = v.clone(); + tess.interface.tessellation = Some(crate::pipeline::interface::TessellationStage::new( + crate::pipeline::interface::PatchDomain::Triangle, + 3, + )); + not_implemented(run(&tess, &f, 1, false, mode, &p).unwrap_err()); + } + let mut no_stores = p.clone(); + no_stores.edit(|x| { + x.enabled + .features + .remove(&VkFeature::VertexPipelineStoresAndAtomics); + }); + assert!(run(&v, &f, 1, false, RegionFanOut::Draw, &no_stores).is_ok()); + match run(&v, &f, 1, false, RegionFanOut::Probe, &no_stores).unwrap_err() { + Error::Unsupported(u) => { + assert_eq!(u.feature, Feature::RasterizationRateMap); + assert_eq!( + u.needs, + Needs::AnyOf(vec![vec![Capability::Feature( + VkFeature::VertexPipelineStoresAndAtomics + )]]) + ); + } + other => panic!("{other:?}"), + } +} diff --git a/crates/metal2vulkan/src/pipeline/link/tests/geometry.rs b/crates/metal2vulkan/src/pipeline/link/tests/geometry.rs index e1ee627d8..57db37de4 100644 --- a/crates/metal2vulkan/src/pipeline/link/tests/geometry.rs +++ b/crates/metal2vulkan/src/pipeline/link/tests/geometry.rs @@ -160,7 +160,7 @@ fn what_a_geometry_stage_cannot_carry_is_refused() { p: &DeviceProfile| { let i = ifaces(v, f); let refs: Vec<&StageInterface> = i.iter().collect(); - plan(&refs, class, amplification, mesh, p) + plan(&refs, class, amplification, mesh, None, p) }; assert!(run(&v, &f, Class::Triangle, 1, false, &p) .unwrap() @@ -273,6 +273,7 @@ fn planned( Class::Triangle, amplification, mesh, + None, p, ) } diff --git a/crates/metal2vulkan/src/pipeline/mod.rs b/crates/metal2vulkan/src/pipeline/mod.rs index b7ef8095a..bcda30520 100644 --- a/crates/metal2vulkan/src/pipeline/mod.rs +++ b/crates/metal2vulkan/src/pipeline/mod.rs @@ -117,10 +117,10 @@ pub use descriptor::{ VertexAttributeDescriptor, VertexBufferLayoutDescriptor, VertexDescriptor, }; pub use graphics::{ - BandPrimitive, BlendState, ColorAttachmentState, EmulatedTessellation, FragmentImageblock, - GraphicsState, ImageblockMechanism, InputAttachmentUse, LineBandState, ShaderTestsUse, - ShadowStencilUse, StandInUse, StandInView, StorageAttachmentUse, StorageAttachmentView, - TessellationState, + BandPrimitive, BlendState, ColorAttachmentState, EmulatedTessellation, FanOutState, + FragmentImageblock, GraphicsState, ImageblockMechanism, InputAttachmentUse, LineBandState, + RegionFanOut, ShaderTestsUse, ShadowStencilUse, StandInUse, StandInView, StorageAttachmentUse, + StorageAttachmentView, TessellationState, }; pub use interface::{ AccessSet, AttributeFetch, BufferForm, BufferKind, BufferSlot, CommandWrites, DescriptorView, diff --git a/crates/metal2vulkan/src/pipeline/sym.rs b/crates/metal2vulkan/src/pipeline/sym.rs index c2234b6ee..b64a38203 100644 --- a/crates/metal2vulkan/src/pipeline/sym.rs +++ b/crates/metal2vulkan/src/pipeline/sym.rs @@ -285,6 +285,14 @@ pub enum SyntheticBinding { HandleTable, /// The pipeline constant blob, a read-only storage buffer. ConstantBlob, + /// A rate-mapped pass's region table (`bind::fan_out`), a read-only storage buffer of a + /// fan-out variant's geometry stage (`GraphicsState::region_fan_out`), declared with the + /// vertex stage's symbols. + RateMapRegions, + /// A fan-out probe's flags (`GraphicsState::region_fan_out`), a storage buffer of `u32`s its + /// geometry stage writes 1 into at the pushed index (`PushField::RegionProbe`), declared with + /// the vertex stage's symbols. + RateMapFlags, /// The render encoder's tessellation factor buffer (`setTessellationFactorBuffer:offset: /// instanceStride:`), a read-only storage buffer of a tessellation pipeline's synthesized /// control stage, declared with the vertex stage's symbols. @@ -1087,6 +1095,9 @@ pub enum PushField { /// height negative, as the runtime's viewports are) and half the band's width in pixels /// (`BindState::line_band`). LineBand, + /// The index a fan-out probe writes its flag at (`u32`; `GraphicsState::region_fan_out`, + /// `link::fan_out`): one field of the synthesized geometry stage's own push range. + RegionProbe, /// The stride (`u32`) the compute encoder binds the kernel buffer at this Metal index with /// (`setBuffer:offset:attributeStride:atIndex:` and its forms, its low 32 bits, /// `MTLAttributeStrideStatic`'s `2^32 - 1` included), 0 where it binds none, which a