SEMANTICS 2098 / RUNTIME 2244: a rate-mapped pass's region-by-region draws copy each region in the vertex function, scissored, so Equal depth matches the fanned-out route

Under RateMapRegionPolicy::FanOut a draw was drawn two ways: fanned out (a geometry stage's copy
of each triangle per region, window position a*x + b*w through one viewport), or region by region
(each region through its own Vulkan viewport). The two rounded a vertex's window position
differently, so a pass testing depth Equal against depth the other route stored failed along whole
surfaces: the consumer's black blotches on lit surfaces in Apple's Modern Rendering sample on the
RTX 3090. The depth-Equal repro left 44,666 of 89,483 pixels red on lavapipe whenever the prepass
and the Equal pass took different routes; 0 under Exact or on one route.

Now on a fanning device the region-by-region draws take a region-copy variant
(RegionFanOut::RegionCopies), with no geometry stage. Its vertex function computes region
RegionFirst + DrawIndex of the table, stores its position through the region's line and four clip
distances by the one emitter the fan-out stage's copies use (pipeline::link::fan_out::region_copy:
NoContraction arithmetic, Position and ClipDistance Invariant), and its draw index as
ViewportIndex. Each recording sets as many viewports as one multi-draw takes, every one the
fan-out's over the render area, with each region's scissor at its index (bind::fan_out::scissors),
so off-region triangles are scissored, not clipped. The settle keys the pipeline with the same
viewport count (fan_out::copy_viewports). The variant replaces the regions variant, so no pipeline
is added per state. A device without multiViewport, shaderOutputViewportIndex and
shaderDrawParameters keeps the per-region-viewport route (FAST-PATHS known gap). Exact is
untouched. New: bind::fan_out::scissors, WorkCounts::rate_map_region_copy_draws and
rate_map_region_copy_recordings, PushField::RegionFirst; cache codec variants (artifact format).

Verified (blotch, steelbrain/blotch 1fd68a45c0..16d5c2404f):
- lavapipe at 16d5c2404f: rate_mapped_depth_equal + rate_mapped_fan_out 4/4, 0 red in all 10
  depth-Equal lines (mixed pairs included), 0 pipelines made at the host step; clippy CPUICD,
  GPU and plain 0; rustdoc 0. Translator suite at 8ad673ffba 3562/3563, the one failure
  golden_hashes (re-blessed on development).
- 780M and XTX at 8ad673ffba (differs from the tip by the settle fix only): 0 red in all 10
  lines. E->E GPU cold/warm: 780M 4.99/4.97 ms against Exact 1.68/1.65; XTX 1.14 ms/650 us
  against 569/265 us. Creation (shader cache off): 780M 1.32 ms/state (Exact 0.92), XTX 1.30
  (Exact 0.68).
- Owed: the same numbers at development's tip without this change (the GS fan-out), the
  clip-distance probe, and the 780M/XTX runs at 16d5c2404f.

SEMANTICS_VERSION 2097 -> 2098, ARTIFACT_FORMAT_VERSION 518 -> 519, RUNTIME_VERSION 2243 -> 2244.
This commit is contained in:
Anees Iqbal committed 2026-11-13 14:52:26 -08:00
1 parent 522a8245e2
commit b741f93b9e
39 files changed
+1508 -218

No files matched your search

@@ -62,8 +62,10 @@
//! function that reads `[[viewport_array_index]]` reads 0 under it, as it does drawn region by
//! region. Neither the route nor `k` follows the map: a draw of the pass routes so over any
//! map, the identity and a map of no layers among them, so a reset (below) never changes the
//! pipeline its pass's encoding again draws with. Every other draw, and every draw on another
//! device, records region by region.
//! pipeline its pass's encoding again draws with. A draw the fan-out's variant takes on a
//! device that fans out and draws region copies (**Fan-out**) is drawn through its region-copy
//! variant instead; every other draw, and every draw on another device, records region by
//! region.
//! - **Layers**. Metal rasterizes each primitive by the map's layer of the slice it renders (probes
//! on the M3 Max and an M4, alike with and without API validation: over a 2-slice target and a
//! map whose layer 0 is at quality 0.5 and layer 1 the identity, a vertex function's slice,
@@ -227,12 +229,34 @@
//! `VkPipeline`s on the device's pool beside the draws' own, so the step takes them made, or
//! waits for them (`WorkCounts::rate_map_fan_out_pipelines_ready`,
//! `rate_map_fan_out_pipelines_waited`), and makes none itself for the states the settle foresaw,
//! the regions variant a flagged draw takes included. The probe and the fanned-out draws each
//! the region-copy variant a flagged draw takes included. The probe and the fanned-out draws each
//! upload the region table to the command buffer as they first bind it
//! (`WorkCounts::rate_map_fan_tables_uploaded`); the settle, which records nothing, uploads none.
//! A copy's window coordinates are computed in the geometry stage, so a pixel centre within a
//! rounding error of a triangle's edge may be covered by one route and not by the other. The
//! encoder's own draws, and the commands `commit` records, are drawn region by region
//!
//! On such a device that also enables `multiViewport`, `shaderOutputViewportIndex` and
//! `shaderDrawParameters`, every other draw of the pass that the variant takes (the same draws: of
//! triangles filled, of one amplification and so on, over a plan the table holds, whose vertex
//! function writes no memory) is drawn region by region through its region-copy variant rather
//! than through each region's viewport: the encoder's own draws, the commands `commit` records,
//! the commands the probe does not probe and those of a pass the step does not probe, a flagged
//! draw's runs and a flagged draw drawn whole (`render/fan_out.rs`, **Region-copy variant**;
//! `WorkCounts::rate_map_region_copy_draws`). The variant has no geometry stage: its vertex
//! function puts each vertex in its region by the instructions that put a fanned-out copy's,
//! decorated `NoContraction`, its `Position` and `ClipDistance` `Invariant`, a recording per
//! region or per as many regions as a direct draw's multi-draw takes
//! (`rate_map_region_copy_recordings`), each pushing its first region. It stores its draw's
//! index as `ViewportIndex`, every viewport the recording sets is the fan-out's over the render
//! area, and the scissor at a draw's index is its region's, so the four clip distances keep each
//! copy to its region and the scissor rejects the rest of the triangle. So a vertex in a region
//! is rasterized at one window position whichever of the pass's routes draws it, where both
//! pipelines compute its position alike, and a later pass that tests `Equal` the depth one
//! route stored meets it where another draws the same vertices (`tests::rate_mapped_depth_equal`:
//! through each region's viewport beside the fan-out, 44,666 of a ground plane's 89,483 pixels
//! failed that test on lavapipe). Its work is its region draws ([`draw_work`]). The window
//! position differs from the one a region's own viewport gives by rounding, so a pixel centre
//! within a rounding error of a triangle's edge may be covered under one policy and not the
//! other; and a draw the variant does not take, and every draw it would take on a device without
//! those three features, is drawn region by region through each region's viewport
//! (`docs/FAST-PATHS.md`, known gaps).
//! - **What the plan refuses** is `NotImplemented(RuntimeGap::RateMapRegions)`, naming the
//! compile layer's reason ([`RegionRefusal`]): a viewport of no extent or a flipped one, a
@@ -614,11 +638,10 @@ pub(super) fn piece_work() -> u64 {
PIECE_WORK
}
/// The work of `draw` recorded through `scissors`, a recording's (the module docs, **Pieces**):
/// one region draw for each scissor that holds a pixel (at least one), each of the draw's
/// vertices or indices times its instances, an indirect or mesh draw's counted as none.
pub(super) fn draw_work(scissors: &[vk::Rect2D], draw: &DrawCommand) -> u64 {
let regions = region_draws(scissors);
/// The work of a recording of `draw` that makes `regions` region draws ([`region_draws`], or a
/// region-copy variant's; the module docs, **Pieces**): each of the draw's vertices or indices
/// times its instances, an indirect or mesh draw's counted as none.
pub(super) fn draw_work(regions: u64, draw: &DrawCommand) -> u64 {
regions.saturating_mul(vertices(draw).saturating_add(REGION_DRAW_WORK))
}
+130 -28
View File
@@ -985,8 +985,25 @@ struct DrawState {
blend_color: [f32; 4],
/// The draws one command records, each through the viewport and scissor at its index: 1 for
/// a plain draw, and the regions of a rate-mapped pass a multi-draw records several at a
/// time (`rate_mapped_pass.rs`, `MultiDraws`), at most its viewports.
/// time (`rate_mapped_pass.rs`, `MultiDraws`), at most its viewports; or, through a
/// region-copy variant, as many regions from `region_first`, each through the viewport over
/// the render area at its index and its region's scissor there.
draws: u32,
/// The first of a rate-mapped pass's regions, in its region table's order, it draws through
/// its region-copy variant, which its recording pushes, drawing `draws` regions from it
/// (`render/fan_out.rs`, **Region-copy variant**); `None` for any other.
region_first: Option<u32>,
}
impl DrawState {
/// The region draws its recording makes (`rate_mapped_pass::region_draws`): its `draws`
/// where it draws through its region-copy variant.
fn region_draws(&self) -> u64 {
match self.region_first {
Some(_) => u64::from(self.draws),
None => rate_mapped_pass::region_draws(&self.scissors),
}
}
}
impl PartialEq for DrawState {
@@ -1002,6 +1019,7 @@ impl PartialEq for DrawState {
&& self.depth_bias == other.depth_bias
&& self.blend_color == other.blend_color
&& self.draws == other.draws
&& self.region_first == other.region_first
}
}
@@ -1782,9 +1800,10 @@ pub(crate) struct RenderLowering {
/// The last draw ran its fan-out variant, and whether its pipeline writes memory: what
/// `fan_run` hears of it.
fanned: (bool, bool),
/// The region table a fan-out draw binds, by the viewport and scissor it was made for, and
/// `None` where their regions make none (`fan_out::table`).
fan_table: Option<(FanTableKey, Option<FanTable>)>,
/// The region table a fan-out draw binds and its regions' scissors in its order, by the
/// viewport and scissor it was made for, and `None` where their regions make none
/// (`fan_out::table`).
fan_table: Option<(FanTableKey, Option<(FanTable, Vec<vk::Rect2D>)>)>,
/// The encoder records an execution's commands and the command it draws holds a barrier,
/// which orders its draw after every draw before it (`render/executions.rs`).
command_barrier: bool,
@@ -8724,10 +8743,12 @@ impl RenderLowering {
// A fan-out variant's draw, or its probe (`render/fan_out.rs`). The probe's run records
// its probes alone: a draw whose variant does not fan out, or whose vertex function
// writes memory (the probe and the draw would each run it), records nothing there, and the
// routes' run draws it region by region.
// routes' run draws it region by region. A draw through its region-copy variant draws
// region by region (`render/fan_out.rs`, **Region-copy variant**).
let writes = graphics.vertex_writes_memory || graphics.fragment_writes_memory;
let fans = (variant.key().region_fan_out).filter(|_| !graphics.vertex_writes_memory);
self.fanned = (fans.is_some(), writes);
let region_copies = fans == Some(RegionFanOut::RegionCopies);
self.fanned = (fans.is_some() && !region_copies, writes);
if fans.is_none()
&& self
.fan_run
@@ -8745,10 +8766,15 @@ impl RenderLowering {
None => None,
};
// A fan-out draw's work is its vertices, its triangles' geometry stage and the copies the
// probe counted (`rate_mapped_pass::fan_out_work`).
// probe counted (`rate_mapped_pass::fan_out_work`); a draw through its region-copy
// variant's, its region draws (`DrawState::region_draws`), each recording pushing its first
// region.
let region_offset = (graphics.region_fan_out)
.filter(|fan| fan.mode == RegionFanOut::RegionCopies)
.map(|fan| fan.push_offset);
let fan_copies = match fans {
Some(RegionFanOut::Draw | RegionFanOut::DrawFew) => self.fan_out.map(|fan| fan.copies),
Some(RegionFanOut::Probe) | None => None,
Some(RegionFanOut::Probe | RegionFanOut::RegionCopies) | None => None,
};
// A fragment function that runs the draw's depth test itself computes and clamps its
// depth by the draw's own Vulkan depth range, read as push data.
@@ -9944,6 +9970,14 @@ impl RenderLowering {
// Where its plan's variant draws them so, the draw records those regions several at a
// time (`region_batch`).
let batch = region_batch(&variant, &device)?;
// A draw through its region-copy variant sets as many viewports as a multi-draw takes
// (one without the multi-draw commands), and draws as many regions a recording where it
// is direct, else one (`render/fan_out.rs`, **Region-copy variant**).
let copy_viewports = fan_out::copy_viewports(&device);
let copy_batch = match draw {
DrawCall::Primitives { .. } | DrawCall::Indexed { .. } => copy_viewports,
_ => 1,
};
// A rate-mapped pass records the draw once per region of the map's layer of the slice
// it renders (`rate_mapped_pass.rs`): each amplification drawn one at a time its own
// slice's, else the draw's one slice, or none known where its primitives choose.
@@ -9951,6 +9985,44 @@ impl RenderLowering {
// the whole draw.
let mut draw_states = match (&self.rate_map, fans) {
(None, _) => DrawStates::Whole([draw_state]),
// A draw through its region-copy variant records the table's regions in its order, each
// recording pushing its first region and drawing as many from it as a direct draw's
// multi-draw takes, else one; it sets `copy_viewports` viewports, every one over the
// render area of the draw's depth range, and each draw's scissor its region's, past
// its regions an empty one (`render/fan_out.rs`, **Region-copy variant**).
(Some(_), Some(_)) if region_copies => {
let depth = (draw_state.viewports.iter().next())
.map_or([0.0, 1.0], |v| [v.min_depth, v.max_depth]);
let (viewport, _) = fan_out::target(render_area, depth);
let Some((_, Some((_, scissors)))) = &self.fan_table else {
return Err(internal(
"a draw through its region-copy variant without its region table",
));
};
let (each, per) = (copy_viewports as usize, copy_batch as usize);
let recordings: Vec<DrawState> = ((0u32..).step_by(per))
.zip(scissors.chunks(per))
.map(|(first, chunk)| DrawState {
viewports: std::iter::repeat_n(viewport, each).collect(),
scissors: (chunk.iter().copied())
.chain(std::iter::repeat(vk::Rect2D::default()))
.take(each)
.collect(),
fixed: FixedState {
viewports: copy_viewports,
..draw_state.fixed
},
draws: chunk.len() as u32,
region_first: Some(first),
..draw_state.clone()
})
.collect();
device
.shared()
.counts
.rate_map_region_copy_draw(recordings.len() as u64);
DrawStates::Regions(vec![recordings])
}
// A fan-out draw, or its probe, records once, through one viewport over the render
// area of the draw's depth range (`render/fan_out.rs`).
(Some(_), Some(_)) => {
@@ -9996,6 +10068,9 @@ impl RenderLowering {
if let Some(batch) = batch {
fixed.viewports = batch as u32;
}
if region_copies {
fixed.viewports = copy_viewports;
}
// A draw that reaches no fragment runs its vertex function alone, through empty scissors,
// and so do unsized points.
if failing == Some(FailingDraw::Untouched) || unsized_points {
@@ -10403,7 +10478,8 @@ impl RenderLowering {
)),
};
let vk_draws = &vk_draws[..count];
// Regions drawn several at a time are direct draws' alone (`draws_region_batches`).
// Regions drawn several at a time are direct draws' alone (`draws_region_batches`, and a
// region-copy variant's `copy_batch`).
let direct = |&(_, _, draw): &(_, _, metal2vulkan::vk::DrawCommand)| {
matches!(
draw,
@@ -10411,7 +10487,7 @@ impl RenderLowering {
| metal2vulkan::vk::DrawCommand::DrawIndexed { .. }
)
};
if batch.is_some() && !vk_draws.iter().all(direct) {
if (batch.is_some() || (region_copies && copy_batch > 1)) && !vk_draws.iter().all(direct) {
return Err(internal(
"regions drawn several at a time by a draw of another command",
));
@@ -11184,16 +11260,27 @@ impl RenderLowering {
for a in 0..entries {
let (push, vk_draws) = entry(a);
for state in draw_states.of(a) {
// A recording through the region-copy variant pushes its first region
// (`render/fan_out.rs`, **Region-copy variant**).
let region_push;
let push = match (state.region_first, region_offset) {
(Some(first), Some(offset)) => {
region_push = fan_out::region_push(push, offset, first)?;
&region_push[..]
}
_ => push,
};
for &(index, indirect, draw) in vk_draws {
draws_recorded += 1;
if counts_work {
let mut work = rate_mapped_pass::draw_work(&state.scissors, &draw);
let regions = state.region_draws();
let mut work = rate_mapped_pass::draw_work(regions, &draw);
if let Some(copies) = fan_copies {
let fanned = rate_mapped_pass::fan_out_work(&draw, copies);
work = work.saturating_add(fanned);
}
piece_work = piece_work.saturating_add(work);
piece_regions += rate_mapped_pass::region_draws(&state.scissors);
piece_regions += regions;
}
if indirect.is_some()
&& phase != Some(snapshot::Phase::Snapshot)
@@ -11795,21 +11882,36 @@ impl RenderLowering {
})
}
/// The fan-out a draw of `pipeline` under `settings` as `assembly` asks for
/// (`BindState::region_fan_out`, `render/fan_out.rs`): the next command's, where the encoder
/// records an execution's commands at a host step that fans the pass's triangles out, for a
/// draw of triangles filled, of one amplification, without a compensation or a band, of a
/// pipeline whose vertex function chooses no slice, over a map whose layers are alike, whose
/// regions make a region table ([`fan_table`](Self::fan_table)); `None` for any other.
/// The fan-out a draw of `pipeline` under `settings` as `assembly` asks for, and the word it
/// binds (`BindState::region_fan_out`, `render/fan_out.rs`): the next command's, where the
/// encoder records an execution's commands at a host step that fans the pass's triangles out,
/// a probe's at its index and a draw's 0; else, in a rate-mapped pass on a device that fans out
/// (`fan_out::fans_out`), outside a probe's run, for a pipeline whose vertex function writes no
/// memory, its region-copy variant, 0 until each recording pushes its first region
/// (`render/fan_out.rs`, **Region-copy variant**). Either for a draw of triangles filled, of
/// one amplification, without a compensation or a band, of a pipeline whose vertex function
/// chooses no slice, over a map whose layers are alike, whose regions make a region table
/// ([`fan_table`](Self::fan_table)); `None` for any other.
fn fan_out_asked(
&mut self,
pipeline: &DrawingState,
settings: &DrawSettings,
assembly: Assembly,
) -> Result<Option<(RegionFanOut, u32)>, Error> {
let Some(fan) = self.fan_out else {
return Ok(None);
let fan = match self.fan_out {
Some(fan) => Some(fan),
// The probe's run records its probes alone.
None if (self.fan_run.as_ref()).is_some_and(fan_out::FanOutRun::probes) => {
return Ok(None)
}
None => None,
};
let regions = self.rate_map.is_some()
&& fan_out::copies_regions(self.core.device())
&& !pipeline.base().graphics.vertex_writes_memory;
if fan.is_none() && !regions {
return Ok(None);
}
let triangles = matches!(
assembly,
Assembly::Primitives(PrimitiveType::Triangle | PrimitiveType::TriangleStrip)
@@ -11827,12 +11929,11 @@ impl RenderLowering {
if !asks || !self.fan_table(pipeline)? {
return Ok(None);
}
// A draw binds no index: only a probe writes its words.
let index = match fan.mode {
RegionFanOut::Probe => fan.index,
RegionFanOut::Draw | RegionFanOut::DrawFew => 0,
};
Ok(Some((fan.mode, index)))
Ok(Some(match fan {
Some(fan) if fan.mode == RegionFanOut::Probe => (fan.mode, fan.index),
Some(fan) => (fan.mode, 0),
None => (RegionFanOut::RegionCopies, 0),
}))
}
/// Whether the encoder's first viewport and scissor plan regions that make a fan-out draw of
@@ -11863,7 +11964,8 @@ impl RenderLowering {
&device.shared().region_limits,
extent,
)?;
let table = fan_out::table(&regions, extent).map(FanTable::Bytes);
let table = (fan_out::table(&regions, extent))
.map(|(bytes, scissors)| (FanTable::Bytes(bytes), scissors));
let made = table.is_some();
self.fan_table = Some((key, table));
Ok(made)
@@ -11872,7 +11974,7 @@ impl RenderLowering {
/// The region table the next fan-out draw binds ([`fan_table`](Self::fan_table)), uploaded to
/// the command buffer by the encoder's first draw that binds it.
fn fan_table_bound(&mut self) -> Result<vk::DescriptorBufferInfo, Error> {
let Some((_, Some(table))) = &mut self.fan_table else {
let Some((_, Some((table, _)))) = &mut self.fan_table else {
return Err(internal("a fan-out draw without its region table"));
};
let bytes = match table {
@@ -640,6 +640,7 @@ impl ShapeInputs<'_> {
depth_bias,
blend_color: self.state.blend_color(),
draws: 1,
region_first: None,
};
Ok(ShapedState {
state,
@@ -1986,7 +1986,8 @@ impl RenderLowering {
/// A tessellation or mesh pipeline's draws, and a state the pass refuses, are left to the
/// step, which meets them as they are then. Announces nothing: it draws nothing. The draws
/// settle with the bind state `live`. Under the encoder's fan-out (`render/fan_out.rs`), the
/// probe's or the fanned-out draw's variant of each draw it takes, none of another.
/// probe's or the fanned-out draw's variant of each draw it takes, none of another; outside
/// it, a draw's region-copy variant where the device fans out.
fn settle_draws(
&mut self,
live: &mut LiveBind,
@@ -2060,8 +2061,11 @@ impl RenderLowering {
// (`render/vertex_reach.rs`), are the step's: none here. A command's draw is direct, and
// draws a rate-mapped pass's regions as the encoder's direct draw would.
let region_viewports = self.draws_region_batches(state, &settings, true);
// Outside the encoder's fan-out, the region-copy variant the step records where the device
// fans out (`render/fan_out.rs`, **Region-copy variant**), else its region by region
// variant.
let region_fan_out = match self.fan_out {
None => None,
None => self.fan_out_asked(state, &settings, assembly)?,
Some(_) => match self.fan_out_asked(state, &settings, assembly)? {
Some(fan) => Some(fan),
None => return Ok(None),
@@ -2136,6 +2140,13 @@ impl RenderLowering {
if let Some(batch) = super::region_batch(&variant, self.core.device())? {
fixed.viewports = batch as u32;
}
// And as many as its draw through its region-copy variant sets (`render/fan_out.rs`,
// **Region-copy variant**).
if variant.key().region_fan_out == Some(RegionFanOut::RegionCopies)
&& !graphics.vertex_writes_memory
{
fixed.viewports = fan_out::copy_viewports(self.core.device());
}
// The class's list topology where the pipeline makes the topology dynamic.
let (topology, primitive_restart) = crate::pipeline::keyed_assembly(
settings.topology,
@@ -14,8 +14,25 @@
//! indices, so each triangle keeps its vertices, its `vertex_id`s and its place among the draw's:
//! a pixel takes the draw's fragments in the draw's order. A flagged draw of any other kind is
//! drawn region by region whole.
//!
//! **Region-copy variant.** On a device that fans the pass's triangles out and enabled what the
//! variant takes ([`copies_regions`]), a draw of the pass that is not fanned out (the encoder's
//! own, a command the probe did not probe or whose host step does not probe, a flagged draw's
//! runs and a flagged draw drawn whole) is drawn region by region through its region-copy variant
//! (`RegionFanOut::RegionCopies`), whose vertex function puts each vertex in its region as a
//! fan-out stage puts a copy's. The regions go in the table's order, each recording pushing its
//! first region ([`region_push`]) and drawing as many regions from it as a direct draw's
//! multi-draw takes (`DrawIndex` the region past the first, which the vertex function stores as
//! `ViewportIndex`), else one. Each recording sets as many viewports as a multi-draw takes, every
//! one the target's over the render area ([`target`]), and each draw's scissor its region's
//! ([`table`]), so the rasterizer rejects a triangle outside the region by its scissor
//! (`bind::fan_out`, **One route per pass**). Every route of the pass hands the rasterizer the
//! same position for a vertex in a region, so a draw that tests `Equal` the depth another stored
//! meets it whichever route each took.
use super::executions::Command;
use crate::binding::PushWrite;
use crate::error::{internal, Error};
use crate::rate_mapped_pass::RUN_GAP;
use crate::render_values::{ScissorRect, Viewport};
use crate::Device;
@@ -349,8 +366,13 @@ fn target_rect([width, height]: [u32; 2]) -> [f32; 4] {
/// The region table of a fan-out draw over `regions`, each a region's viewport and scissor as the
/// device draws it (`RateMappedPass::draws`), through one viewport over the render area `extent`
/// (`bind::fan_out::table`): `None` where they are not a grid of segments or hold no pixel.
pub(super) fn table(regions: &[(vk::Viewport, vk::Rect2D)], extent: [u32; 2]) -> Option<Vec<u8>> {
/// (`bind::fan_out::table`), and its regions' scissors in its order (`bind::fan_out::scissors`),
/// which a draw through the region-copy variant draws through (the module docs, **Region-copy
/// variant**): `None` where they are not a grid of segments or hold no pixel.
pub(super) fn table(
regions: &[(vk::Viewport, vk::Rect2D)],
extent: [u32; 2],
) -> Option<(Vec<u8>, Vec<vk::Rect2D>)> {
if !(regions.iter()).any(|(_, s)| s.extent.width > 0 && s.extent.height > 0) {
return None;
}
@@ -365,7 +387,69 @@ pub(super) fn table(regions: &[(vk::Viewport, vk::Rect2D)], extent: [u32; 2]) ->
Some(([v.x, v.y, v.width, v.height], scissor))
})
.collect::<Option<_>>()?;
metal2vulkan::bind::fan_out::table(target_rect(extent), &regions)
let table = metal2vulkan::bind::fan_out::table(target_rect(extent), &regions)?;
let scissors = (metal2vulkan::bind::fan_out::scissors(&regions)?.into_iter())
.map(|[x, y, width, height]| {
Some(vk::Rect2D {
offset: vk::Offset2D {
x: i32::try_from(x).ok()?,
y: i32::try_from(y).ok()?,
},
extent: vk::Extent2D { width, height },
})
})
.collect::<Option<_>>()?;
Some((table, scissors))
}
/// The viewports a recording of a draw through its region-copy variant sets, every one the
/// target's: as many as one multi-draw command takes, one without the multi-draw commands (the
/// module docs, **Region-copy variant**). Its `VkPipeline` takes as many
/// (`FixedState::viewports`).
pub(super) fn copy_viewports(device: &Device) -> u32 {
(device.shared().multi_draws)
.as_ref()
.map_or(1, |multi| multi.batch().max(1))
}
/// Whether `device` draws a fanning pass's region-by-region draws through their region-copy
/// variant (the module docs, **Region-copy variant**): it fans out ([`fans_out`]), and it enabled
/// what the variant's vertex function takes to store its draw's index as `ViewportIndex` and its
/// several viewports (`LoweringInputs::region_copies`).
pub(super) fn copies_regions(device: &Device) -> bool {
let compile = device.compile_device();
let features = &compile.profile().enabled().features;
fans_out(device)
&& [
VkFeature::MultiViewport,
VkFeature::ShaderOutputViewportIndex,
VkFeature::ShaderDrawParameters,
]
.iter()
.all(|feature| features.contains(feature))
}
/// The push writes of a recording of a draw through its region-copy variant from region `first`
/// (the module docs, **Region-copy variant**): the draw's, `push`, with the vertex stage's word at
/// `offset` (`PushField::RegionFirst`) holding `first`.
pub(super) fn region_push(
push: &[PushWrite],
offset: u32,
first: u32,
) -> Result<Vec<PushWrite>, Error> {
let mut pushed = push.to_vec();
let write = (pushed.iter_mut())
.find(|(stages, at, bytes)| {
stages.contains(vk::ShaderStageFlags::VERTEX)
&& *at <= offset
&& offset + 4 <= *at + bytes.len() as u32
})
.ok_or_else(|| {
internal("a draw through its region-copy variant without its region's push")
})?;
let from = (offset - write.1) as usize;
write.2[from..from + 4].copy_from_slice(&first.to_le_bytes());
Ok(pushed)
}
/// The viewport and scissor a fan-out draw records through: one over the whole render area
@@ -539,6 +539,8 @@ mod queue_switch_gate;
mod range;
mod rate_map;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod rate_mapped_depth_equal;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod rate_mapped_fan_out;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod rate_mapped_pieces;
@@ -0,0 +1,398 @@
//! A rate-mapped pass's depth, drawn by one route, tested `Equal` by a later pass drawing the same
//! triangles by another (`rate_mapped_pass.rs`, **Fan-out**): the encoder's draws are drawn region
//! by region, and an execution's commands a host step records are fanned out, each copy's window
//! coordinates computed in the geometry stage, the triangles the probe flags region by region.
//! Under `RateMapRegionPolicy::FanOut` on a device that fans out, a draw drawn region by region
//! takes its region-copy variant, whose vertex function puts each vertex in its region as the
//! fan-out's stage puts a copy's (`render/fan_out.rs`, **Region-copy variant**); under `Exact` each
//! region through its own viewport. A
//! depth prepass and an `Equal` pass over the same vertices are Metal's way to shade each pixel
//! once; Metal rasterizes both passes alike, so the second shades every pixel the first covered.
//!
//! The first pass clears the colour to black and the depth to 1 and draws a ground plane in
//! perspective (64 by 64 quads, every `w` positive) red, `Less`, writing depth; the second loads
//! both and draws the same vertices white, `Equal`, writing none. A pixel left red is one the first
//! pass covered and the second's depth test failed at: a hole of black in Metal's terms, where the
//! second pass is the lit surface. Each leg draws the first pass by one route and the second by
//! another, under `RateMapRegionPolicy::FanOut` and under `Exact`.
//!
//! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`,
//! `m2v_cpu_icd`), on the kind of device the cfg selects. The functions are `cfb_depth_vertex` and
//! `cfb_depth_white` of the owned fixture `validation/fixtures/public/engine/cfb_sample_depth.ll`,
//! which draws each vertex where its buffer holds it, and `tob_solid` of `engine/tob_renders.ll`.
use super::blit_holds::{options, Scratch, WAIT};
use super::encoder_holds::library;
use crate::write_routes::GpuWriter;
use crate::{
Buffer, ClearColor, CommandBufferStatus, CommandQueue, DepthStencilState, Device,
IndirectCommandBuffer, IndirectCommandBufferDescriptor, Library, LoadAction, PipelineOptions,
RasterizationRateMap, Region, RenderPassDescriptor, RenderPipelineState, ResourceOptions,
StoreAction, TextureDescriptor, WorkCounts,
};
use metal2vulkan::bind::{RateMapDescriptor, RateMapLayerDescriptor};
use metal2vulkan::device::{RateMapRegionPolicy, VkFeature};
use metal2vulkan::metal::state::DepthStencilDescriptor;
use metal2vulkan::metal::{
CompareFunction, IndexType, IndirectCommandType, PixelFormat, PrimitiveType, TextureUsage,
};
use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource};
use std::path::Path;
/// The ground's quads on a side.
const QUADS: u32 = 64;
const INDICES: u32 = QUADS * QUADS * 6;
/// The map's screen side, and its quality samples on both axes.
const SCREEN: u32 = 512;
const QUALITY: [f32; 5] = [0.3, 0.6, 1.0, 0.6, 0.3];
/// The indirect command buffer's commands: the first pass's, then the second's.
const FIRST: u64 = 0;
const SECOND: u64 = 1;
/// How a pass draws the ground.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Route {
/// On the encoder: region by region.
Encoder,
/// Executed from the indirect command buffer at the host step: fanned out under `FanOut`.
Executed,
}
struct Ground {
device: Device,
queue: CommandQueue,
red: RenderPipelineState,
white: RenderPipelineState,
less: DepthStencilState,
equal: DepthStencilState,
positions: Buffer,
indices: Buffer,
color: Buffer,
icb: IndirectCommandBuffer,
map: RasterizationRateMap,
}
/// The ground plane's corners in clip space, four floats each: a camera 1.7 above it looking 12
/// degrees down, a 60-degree field of view, depth from 0.1 to 200 in Metal's `[0, 1]`.
fn ground_corners() -> Vec<[f32; 4]> {
let pitch = 12f64.to_radians();
let (sin, cos) = pitch.sin_cos();
let f = 1.0 / 30f64.to_radians().tan();
let (near, far) = (0.1f64, 200.0f64);
let mut corners = Vec::new();
for j in 0..=QUADS {
for i in 0..=QUADS {
let x = -30.0 + 60.0 * f64::from(i) / f64::from(QUADS);
let z = 2.0 + 78.0 * f64::from(j) / f64::from(QUADS);
let (dx, dy, dz) = (x, -1.7, z);
let vx = dx;
let vy = dy * cos + dz * sin;
let vz = -dy * sin + dz * cos;
let clip_z = vz * far / (far - near) - near * far / (far - near);
corners.push([f * vx, f * vy, clip_z, vz].map(|v| v as f32));
}
}
corners
}
impl Ground {
fn new(device: Device) -> Ground {
let (depth, solid) = (
library(&device, "engine/cfb_sample_depth.ll"),
library(&device, "engine/tob_renders.ll"),
);
let function = |library: &Library, name| {
StageSource::Function(
library
.new_function_with_name(name)
.unwrap()
.function_descriptor(),
)
};
let pipeline = |fragment: StageSource| {
let mut descriptor =
RenderPipelineDescriptor::new(function(&depth, "cfb_depth_vertex"));
descriptor.fragment = Some(fragment);
descriptor.color_attachments[0] =
Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm));
descriptor.depth_format = Some(PixelFormat::Depth32Float);
descriptor.support_indirect_command_buffers = true;
device
.new_render_pipeline_state(&descriptor, &PipelineOptions::default())
.unwrap()
};
let red = pipeline(function(&solid, "tob_solid"));
let white = pipeline(function(&depth, "cfb_depth_white"));
let state = |compare: CompareFunction, write: bool| {
let mut descriptor = DepthStencilDescriptor::default();
descriptor.depth_compare_function = compare;
descriptor.depth_write_enabled = write;
device.new_depth_stencil_state(&descriptor).unwrap()
};
let (less, equal) = (
state(CompareFunction::Less, true),
state(CompareFunction::Equal, false),
);
let positions: Vec<u8> = ground_corners()
.into_iter()
.flatten()
.flat_map(f32::to_le_bytes)
.collect();
let corner = |x: u32, y: u32| y * (QUADS + 1) + x;
let indices: Vec<u8> = (0..QUADS * QUADS)
.flat_map(|quad| {
let (x, y) = (quad % QUADS, quad / QUADS);
let [a, b, c, d] = [
corner(x, y),
corner(x + 1, y),
corner(x, y + 1),
corner(x + 1, y + 1),
];
[a, b, c, b, d, c]
})
.flat_map(u32::to_le_bytes)
.collect();
let color: Vec<u8> = [1.0f32, 0.0, 0.0, 1.0]
.into_iter()
.flat_map(f32::to_le_bytes)
.collect();
let buffer = |bytes: &[u8]| {
(device.new_buffer_with_bytes(bytes, ResourceOptions::shared())).unwrap()
};
let mut icb = IndirectCommandBufferDescriptor::new();
icb.command_types = IndirectCommandType::DRAW_INDEXED;
icb.inherit_buffers = false;
icb.max_vertex_buffer_bind_count = 1;
icb.max_fragment_buffer_bind_count = 1;
let icb = device
.new_indirect_command_buffer(&icb, 2, ResourceOptions::shared())
.unwrap();
let mut map = RateMapDescriptor::new([SCREEN, SCREEN]);
map.layers = vec![RateMapLayerDescriptor::new(
QUALITY.to_vec(),
QUALITY.to_vec(),
)];
let map = device.new_rasterization_rate_map(&map).unwrap();
let ground = Ground {
queue: device.new_command_queue().unwrap(),
red,
white,
less,
equal,
positions: buffer(&positions),
indices: buffer(&indices),
color: buffer(&color),
icb,
map,
device,
};
for (k, pipeline) in [(FIRST, &ground.red), (SECOND, &ground.white)] {
let command = ground.icb.indirect_render_command_at(k).unwrap();
command.set_render_pipeline_state(pipeline).unwrap();
command
.set_vertex_buffer(Some(&ground.positions), 0, 0)
.unwrap();
command
.set_fragment_buffer(Some(&ground.color), 0, 0)
.unwrap();
command
.draw_indexed_primitives(
PrimitiveType::Triangle,
u64::from(INDICES),
IndexType::UInt32,
&ground.indices,
0,
1,
0,
0,
)
.unwrap();
}
// The GPU may write the records: the host step records the passes.
ground.icb.written_by_gpu(GpuWriter::Reset);
drop(ground.icb.gpu_write());
ground
}
/// The two passes, the first drawn by `first` and the second by `second`, in one command
/// buffer: the target's red, white and black pixels, the command buffer's GPU time in
/// nanoseconds (0 where the device times none), and the device's counts before and after.
fn frame(&self, first: Route, second: Route) -> ([usize; 3], u64, WorkCounts, WorkCounts) {
let size = self.map.physical_size_for_layer(0);
let texture = |format, options| {
let mut d = TextureDescriptor::texture_2d(format, size.width, size.height, false);
d.usage = TextureUsage::RENDER_TARGET;
d.resource_options = options;
self.device.new_texture(&d).unwrap()
};
let target = texture(PixelFormat::RGBA8Unorm, ResourceOptions::shared());
let depth = texture(PixelFormat::Depth32Float, ResourceOptions::private());
let before = self.device.work_counts();
let command_buffer = self.queue.command_buffer().unwrap();
for (pass, route) in [(FIRST, first), (SECOND, second)] {
let mut descriptor = RenderPassDescriptor::new();
let color = &mut descriptor.color_attachments[0];
color.texture = Some(target.clone());
color.load_action = match pass {
FIRST => LoadAction::Clear,
_ => LoadAction::Load,
};
color.clear_color = ClearColor::new(0.0, 0.0, 0.0, 1.0);
color.store_action = StoreAction::Store;
descriptor.depth_attachment.texture = Some(depth.clone());
descriptor.depth_attachment.load_action = color.load_action;
descriptor.depth_attachment.clear_depth = 1.0;
descriptor.depth_attachment.store_action = StoreAction::Store;
descriptor.rasterization_rate_map = Some(self.map.clone());
let mut encoder = command_buffer.render_command_encoder(&descriptor).unwrap();
let (pipeline, state) = match pass {
FIRST => (&self.red, &self.less),
_ => (&self.white, &self.equal),
};
encoder.set_depth_stencil_state(state).unwrap();
encoder.set_render_pipeline_state(pipeline).unwrap();
match route {
Route::Executed => encoder
.execute_commands_in_buffer(&self.icb, pass..pass + 1)
.unwrap(),
Route::Encoder => {
encoder
.set_vertex_buffer(Some(&self.positions), 0, 0)
.unwrap();
encoder
.set_fragment_buffer(Some(&self.color), 0, 0)
.unwrap();
encoder
.draw_indexed_primitives(
PrimitiveType::Triangle,
INDICES,
IndexType::UInt32,
&self.indices,
0,
1,
0,
0,
)
.unwrap();
}
}
encoder.end_encoding().unwrap();
}
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
let gpu = match (
command_buffer.gpu_start_time(),
command_buffer.gpu_end_time(),
) {
(Ok(start), Ok(end)) => ((end - start) * 1e9) as u64,
_ => 0,
};
drop(command_buffer);
let after = self.device.work_counts();
let (width, height) = (size.width, size.height);
let mut bytes = vec![0u8; (width * height * 4) as usize];
target
.get_bytes(
&mut bytes,
width * 4,
0,
Region::new_2d(0, 0, width, height),
0,
0,
)
.unwrap();
let mut counts = [0usize; 3];
for texel in bytes.chunks(4) {
match texel[..3] {
[255, 0, 0] => counts[0] += 1,
[255, 255, 255] => counts[1] += 1,
_ => counts[2] += 1,
}
}
(counts, gpu, before, after)
}
}
/// The device the cfg selects under `policy`, its shader cache in `cache`.
fn device_under(cache: &Path, policy: RateMapRegionPolicy) -> Device {
let mut options = options(cache);
options.policy.rate_map_regions = policy;
Device::system_default_with(&options).unwrap()
}
/// Whether `device` enables the features the fan-out and its probe take.
fn fans_out(device: &Device) -> bool {
let profile = device.compile_device().profile();
let features = &profile.enabled().features;
[
VkFeature::GeometryShader,
VkFeature::ShaderClipDistance,
VkFeature::VertexPipelineStoresAndAtomics,
]
.iter()
.all(|feature| features.contains(feature))
}
/// The fanned-out draws, the flagged ones, the ones in parts, and the draws through the regions
/// variant and their recordings between two counts.
fn fanned(before: &WorkCounts, after: &WorkCounts) -> [u64; 5] {
[
after.rate_map_fanned_draws - before.rate_map_fanned_draws,
after.rate_map_flagged_draws - before.rate_map_flagged_draws,
after.rate_map_parted_draws - before.rate_map_parted_draws,
after.rate_map_region_copy_draws - before.rate_map_region_copy_draws,
after.rate_map_region_copy_recordings - before.rate_map_region_copy_recordings,
]
}
/// Each pairing of routes, under each policy, and the encoder's again once its pipelines are
/// made: the second pass shades every pixel the first covered, so no pixel is left red. Under
/// `FanOut` on a device that fans out, the encoder's draws are drawn through their regions
/// variant; under `Exact` none is.
#[test]
fn an_equal_depth_pass_shades_every_pixel_its_prepass_covered_whatever_the_routes() {
// The last pairing again, its pipelines made: the warm frame of the encoder's routes.
let routes = [
(Route::Encoder, Route::Encoder),
(Route::Encoder, Route::Executed),
(Route::Executed, Route::Encoder),
(Route::Executed, Route::Executed),
(Route::Encoder, Route::Encoder),
];
let mut holes = Vec::new();
for policy in [RateMapRegionPolicy::Exact, RateMapRegionPolicy::FanOut] {
let scratch = Scratch::new("rate-mapped-depth-equal");
let ground = Ground::new(device_under(&scratch.0, policy));
for (first, second) in routes {
let ([red, white, black], gpu, before, after) = ground.frame(first, second);
let counts = fanned(&before, &after);
let made = after.variant_pipelines_made - before.variant_pipelines_made;
let create = after.render_pipeline_create_nanos - before.render_pipeline_create_nanos;
eprintln!(
"RATE-MAP-DEPTH-EQUAL {policy:?} {first:?} then {second:?}: {red} red, {white} \
white, {black} black; fanned, flagged, parted, region copy draws, recordings \
{counts:?}; {made} pipelines made in {create} ns; GPU {gpu} ns"
);
assert!(white > 0, "the second pass shaded nothing");
let encoded = [first, second]
.iter()
.filter(|&&r| r == Route::Encoder)
.count();
match policy == RateMapRegionPolicy::FanOut && fans_out(&ground.device) {
true => assert!(
counts[3] >= encoded as u64,
"the encoder's draws through the region-copy variant"
),
false => assert_eq!(counts[3], 0, "draws through the region-copy variant"),
}
if red != 0 {
holes.push((policy, first, second, red));
}
}
}
assert!(
holes.is_empty(),
"pixels the first pass covered and the equal pass did not: {holes:?}"
);
}
@@ -11,15 +11,14 @@
//! (`render/fan_out.rs`, **Parts**), each in its place: each grid with the wide triangles in five,
//! the blocks of `bind::fan_out::BLOCK_TRIANGLES` that hold them region by region, from each wide
//! triangle to its block's end and from its block's start, and the triangles before, between and
//! after them fanned out; and each single triangle region by region; under `Exact` no probe runs
//! and every command is drawn region by region. Either way the target's bytes are those of the
//! same commands drawn on the encoder, region by region as `Exact` draws them: a command or a
//! triangle lost, drawn twice or out of order, or a copy drawn into another region or left out of
//! its own, changes the pixels.
//! The
//! probe's and the fanned-out draws' pipelines are begun at commit (`RenderExecution::settle`):
//! the host step takes them made or waits for them, and makes no more pipelines itself than it
//! makes for the same frame under `Exact`.
//! after them fanned out; and each single triangle region by region, through its region-copy
//! variant (`render/fan_out.rs`, **Region-copy variant**), as the encoder draws every command;
//! under `Exact` no probe runs and every command is drawn region by region, each region through its
//! own viewport. Either way the target's bytes are those of the same commands drawn on the encoder:
//! a command or a triangle lost, drawn twice or out of order, or a copy drawn into another region
//! or left out of its own, changes the pixels. The probe's and the fanned-out draws' pipelines are
//! begun at commit (`RenderExecution::settle`): the host step takes them made or waits for them,
//! and makes no more pipelines itself than it makes for the same frame under `Exact`.
//!
//! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`,
//! `m2v_cpu_icd`), on the kind of device the cfg selects. The functions are `tob_triangle` and
@@ -28,6 +27,7 @@
//! each vertex where its buffer holds it (`llvm-as`).
use super::blit_holds::{options, Scratch, WAIT};
use super::encoder_holds::library;
use crate::write_routes::GpuWriter;
use crate::{
Buffer, ClearColor, CommandBufferStatus, CommandQueue, Device, IndirectCommandBuffer,
@@ -106,14 +106,10 @@ fn draw_of(
impl Workload {
fn new(device: Device) -> Workload {
let ll = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../metal2vulkan-validation/fixtures/public/engine/tob_renders.ll");
let bitcode = metal2vulkan_devtools::llvm_assemble(&ll).unwrap();
let library = metal2vulkan::library::Library::from_air(&bitcode).unwrap();
let library = device.new_library_with_compile_library(library);
let renders = library(&device, "engine/tob_renders.ll");
let function = |name| {
StageSource::Function(
library
renders
.new_function_with_name(name)
.unwrap()
.function_descriptor(),
@@ -133,11 +129,7 @@ impl Workload {
.new_render_pipeline_state(&descriptor, &PipelineOptions::default())
.unwrap();
// The command across `w = 0`: the same colour stage, each vertex where its buffer holds it.
let ll = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../metal2vulkan-validation/fixtures/public/engine/cfb_sample_depth.ll");
let bitcode = metal2vulkan_devtools::llvm_assemble(&ll).unwrap();
let depth = metal2vulkan::library::Library::from_air(&bitcode).unwrap();
let depth = device.new_library_with_compile_library(depth);
let depth = library(&device, "engine/cfb_sample_depth.ll");
let vertex = depth.new_function_with_name("cfb_depth_vertex").unwrap();
descriptor.vertex = StageSource::Function(vertex.function_descriptor());
let behind_pipeline = device
@@ -384,6 +376,15 @@ fn fan_counts(before: &WorkCounts, after: &WorkCounts) -> [u64; 4] {
]
}
/// The draws through the region-copy variant and their recordings between two counts
/// (`render/fan_out.rs`, **Region-copy variant**).
fn copy_counts(before: &WorkCounts, after: &WorkCounts) -> [u64; 2] {
[
after.rate_map_region_copy_draws - before.rate_map_region_copy_draws,
after.rate_map_region_copy_recordings - before.rate_map_region_copy_recordings,
]
}
/// The texels of `a` and `b` that differ: how many, and the first's index and its bytes in each.
fn differing<'a>(a: &'a [u8], b: &'a [u8]) -> (usize, Option<(usize, &'a [u8], &'a [u8])>) {
let mut differ = (a.chunks(4).zip(b.chunks(4)).enumerate()).filter(|(_, (a, b))| a != b);
@@ -394,18 +395,21 @@ fn differing<'a>(a: &'a [u8], b: &'a [u8]) -> (usize, Option<(usize, &'a [u8], &
/// Under `FanOut` the host step probes once, fans the grid commands out and draws the four it
/// flagged in parts between them, each grid's two wide triangles in runs of their own blocks
/// region by region and the triangles between them fanned out, with the pipelines `commit` began:
/// the fan-out's and the regions variant's, so the step makes none. The grid commands are drawn
/// through the variant of few copies and the medium one through the most copies'. Its probe and
/// its fanned-out draws each upload the region table once, the commit's settle none. The pixels
/// are the encoder's region-by-region draws', `Exact`'s.
/// the fan-out's, its runs region by region through the region-copy variant, so the step makes
/// none. The grid commands are drawn through the variant of few copies and the medium one
/// through the most copies'. Its probe and its fanned-out draws each upload the region table
/// once, the commit's settle none. The encoder draws every command through the region-copy
/// variant. The pixels are the encoder's.
#[test]
fn a_host_step_fans_out_the_commands_the_probe_does_not_flag() {
let scratch = Scratch::new("rate-mapped-fan-out");
let workload = Workload::new(device_under(&scratch.0, RateMapRegionPolicy::FanOut));
let (drawn, before, after) = workload.frame(false);
assert_eq!(fan_counts(&before, &after), [0; 4], "the encoder's draws");
let encoder_copies = copy_counts(&before, &after);
let (fanned, before, after) = workload.frame(true);
let counts = fan_counts(&before, &after);
let copies = copy_counts(&before, &after);
let probe_nanos = after.rate_map_probe_gpu_nanos - before.rate_map_probe_gpu_nanos;
let made = after.host_step_pipelines_made - before.host_step_pipelines_made;
let ready = after.rate_map_fan_out_pipelines_ready - before.rate_map_fan_out_pipelines_ready;
@@ -422,11 +426,25 @@ fn a_host_step_fans_out_the_commands_the_probe_does_not_flag() {
{flagged} flagged triangles; \
fan-out pipelines {ready} ready, {waited} waited for; {made} made at the step; {tables} \
region tables uploaded; {few} drawn of few copies; {by_regions} triangles of draws in \
parts region by region, in {runs} runs"
parts region by region, in {runs} runs; draws through the region-copy variant and \
their recordings: the encoder's {encoder_copies:?}, the execution's {copies:?}"
);
assert_eq!(made, 0, "pipelines the host step made");
match fans_out(&workload.device) {
true => {
assert_eq!(
encoder_copies[0],
u64::from(COMMANDS),
"the encoder's draws"
);
assert!(
encoder_copies[1] >= encoder_copies[0],
"the encoder's recordings"
);
assert_eq!(
copies[0], runs,
"the runs drawn through the region-copy variant"
);
assert_eq!(counts, [1, 4, u64::from(COMMANDS - 4), 4]);
assert_eq!(tables, 2, "region tables uploaded");
assert!(
@@ -449,7 +467,14 @@ fn a_host_step_fans_out_the_commands_the_probe_does_not_flag() {
assert_eq!(flagged, 6, "the triangles the probe flagged");
assert!(wait > 0, "the host's wait for the probe");
}
false => assert_eq!(counts, [0; 4]),
false => {
assert_eq!(counts, [0; 4]);
assert_eq!(
[encoder_copies, copies],
[[0; 2]; 2],
"draws through the region-copy variant"
);
}
}
// Every pixel took the commands' blends: none is the clear's black.
assert!(
@@ -489,16 +514,22 @@ fn the_encoder_trail_fans_out_the_same_pixels() {
);
}
/// Under `Exact` no probe runs and every command is drawn region by region, with the regions
/// variant's pipelines `commit` began: the host step makes none. The pixels are the encoder's
/// draws'.
/// Under `Exact` no probe runs and every command is drawn region by region, each region through
/// its own viewport, none through the region-copy variant, with the regions variant's pipelines
/// `commit` began: the host step makes none. The pixels are the encoder's draws'.
#[test]
fn exact_regions_draw_every_command_region_by_region() {
let scratch = Scratch::new("rate-mapped-fan-out-exact");
let workload = Workload::new(device_under(&scratch.0, RateMapRegionPolicy::Exact));
let (drawn, _, _) = workload.frame(false);
let (drawn, before, after) = workload.frame(false);
assert_eq!(copy_counts(&before, &after), [0; 2], "the encoder's draws");
let (exact, before, after) = workload.frame(true);
assert_eq!(fan_counts(&before, &after), [0; 4]);
assert_eq!(
copy_counts(&before, &after),
[0; 2],
"the execution's draws"
);
let made = after.host_step_pipelines_made - before.host_step_pipelines_made;
eprintln!("RATE-MAP-EXACT {made} made at the step");
assert_eq!(made, 0, "pipelines the host step made");
@@ -248,6 +248,8 @@ pub(crate) struct Counters {
rate_map_fan_out_pipelines_ready: AtomicU64,
rate_map_fan_out_pipelines_waited: AtomicU64,
rate_map_fan_tables_uploaded: AtomicU64,
rate_map_region_copy_draws: AtomicU64,
rate_map_region_copy_recordings: AtomicU64,
encoder_primaries_begun_ahead: AtomicU64,
primaries_begun_ahead: AtomicU64,
barrier_buffers_kept: AtomicU64,
@@ -3009,6 +3011,13 @@ impl Counters {
(self.rate_map_fan_tables_uploaded).fetch_add(1, Ordering::Relaxed);
}
/// A draw of a rate-mapped pass recorded region by region through its region-copy variant, in
/// `recordings` recordings (`render/fan_out.rs`, **Region-copy variant**).
pub(crate) fn rate_map_region_copy_draw(&self, recordings: u64) {
(self.rate_map_region_copy_draws).fetch_add(1, Ordering::Relaxed);
(self.rate_map_region_copy_recordings).fetch_add(recordings, Ordering::Relaxed);
}
/// A host step's probe ran for `nanos` of GPU time, read from its timestamps once it completed
/// (`rate_mapped_pass.rs`, **Fan-out**).
pub(crate) fn rate_map_probe_time(&self, nanos: u64) {
@@ -7438,6 +7447,17 @@ pub struct WorkCounts {
/// that binds it: one for a host step's probe and one for its fanned-out draws, none for
/// `commit`'s settle, which records nothing (`rate_mapped_pass.rs`, **Fan-out**).
pub rate_map_fan_tables_uploaded: u64,
/// Draws in rate-mapped passes drawn region by region through their region-copy variant, on a
/// device that fans the pass's triangles out: its vertex function puts each vertex in its
/// region as a fanned-out draw's geometry stage puts a copy's, each region through a viewport
/// over the render area and its own scissor (`rate_mapped_pass.rs`, **Fan-out**): the
/// encoder's own draws, executed
/// commands the probe did not probe or whose host step does not probe, and a flagged draw's
/// runs or the whole of one drawn so.
pub rate_map_region_copy_draws: u64,
/// The recordings they made: one per region, or per as many regions as one multi-draw
/// command draws where the draw is direct and the device has the multi-draw commands.
pub rate_map_region_copy_recordings: u64,
/// Render passes whose first instance did not record inline, its draws in a secondary command
/// buffer, by the first check that ruled it out (`render/inline_first.rs`), counted as the pass
/// opens or at its first draw that records: here, the encoder encodes an ended encoder's calls
@@ -10685,6 +10705,10 @@ impl Device {
.load(Ordering::Relaxed),
rate_map_fan_tables_uploaded: (counters.rate_map_fan_tables_uploaded)
.load(Ordering::Relaxed),
rate_map_region_copy_draws: (counters.rate_map_region_copy_draws)
.load(Ordering::Relaxed),
rate_map_region_copy_recordings: (counters.rate_map_region_copy_recordings)
.load(Ordering::Relaxed),
passes_not_inline_encoders: not_inline(NotInline::Encoders),
passes_not_inline_layouts: not_inline(NotInline::Layouts),
passes_not_inline_memoryless: not_inline(NotInline::Memoryless),
+57 -9
View File
@@ -18,10 +18,34 @@
//! 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
//! A copy's fragments are its region viewport'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).
//! a triangle's edge may be covered by the copy and not through the region's own viewport (a
//! near-equivalent, rule 1's fast default; `RateMapRegionPolicy::Exact`, which draws every region
//! through its own viewport, is the exact one).
//!
//! **One route per pass.** Where a pass fans its triangles out, the draws it records region by
//! region take their region-copy variant (`RegionFanOut::RegionCopies`): region `k` of a
//! recording the first it pushes (`PushField::RegionFirst`) plus its draw's `DrawIndex` among a
//! multi-draw's (0 for a draw that is no multi-draw's), the segments `(k mod nx, k / nx)`, and
//! the vertex function putting each vertex in region `k` by the emitter of the fan-out stage's
//! copies (`pipeline::link::fan_out::region_copy`). It stores `DrawIndex` as `ViewportIndex`, and
//! every viewport the recording sets is the target's, each scissor its region's ([`scissors`]):
//! the rasterizer rejects a triangle outside the region by its scissor, as it does through a
//! region's own viewport, and the viewport transform is the fan-out's whatever the index,
//! Vulkan's being "determined by the selected viewport's width and height in pixels, px and py,
//! respectively, and its center (ox, oy) (also in pixels), as well as its depth range"
//! (*Controlling the Viewport*). Every route then hands the rasterizer the same position and clip
//! distances for a vertex in a region, through the same viewport transform: a later pass that
//! tests `Equal` the depth one draw stored meets it where the other route drew it. The copy's
//! arithmetic is decorated `NoContraction`, each operation correctly rounded on its own (Vulkan's
//! *Precision and Operation of SPIR-V Instructions*), and its `Position` and `ClipDistance`
//! outputs are `Invariant`. The routes run the copy in different pipelines and different stages
//! (the region-copy variant's vertex function, the fan-out variant's geometry stage), each on the
//! position its own vertex function computes: the identity rests on those correctly rounded
//! operations and on the guest's position computation compiling alike in both pipelines, which
//! Vulkan's invariance appendix does not promise across pipelines (its Rule 4), and which is
//! checked by running it (`docs/FAST-PATHS.md`, known gaps).
//!
//! 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
@@ -148,12 +172,9 @@ impl Segment {
}
}
/// 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<Vec<u8>> {
/// The segments of each axis of `regions` ([`table`]'s), in the order of their normalized device
/// coordinates, or `None` where they make no table.
fn segments(regions: &[([f32; 4], [u32; 4])]) -> Option<[Vec<Segment>; 2]> {
let axis = |a: usize| {
let mut segments: Vec<Segment> = Vec::new();
for &(viewport, scissor) in regions {
@@ -174,6 +195,16 @@ pub fn table(target: [f32; 4], regions: &[([f32; 4], [u32; 4])]) -> Option<Vec<u
if !fits(&xs) || !fits(&ys) || xs.len() * ys.len() != regions.len() {
return None;
}
Some([xs, ys])
}
/// 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<Vec<u8>> {
let [xs, ys] = segments(regions)?;
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
@@ -202,5 +233,22 @@ pub fn table(target: [f32; 4], regions: &[([f32; 4], [u32; 4])]) -> Option<Vec<u
)
}
/// The scissors `[x, y, width, height]` of the regions of [`table`]'s table over `regions`, in
/// the table's order: region `k` of segments `(k mod nx, k / nx)` (the module docs, **One route
/// per pass**), the scissor a region-copy variant's draw of region `k` takes. `None` where
/// [`table`] makes none.
pub fn scissors(regions: &[([f32; 4], [u32; 4])]) -> Option<Vec<[u32; 4]>> {
let [xs, ys] = segments(regions)?;
let scissor = |x: &Segment, y: &Segment| {
let ([x0, x1], [y0, y1]) = (x.pixels, y.pixels);
[x0, y0, x1 - x0, y1 - y0]
};
Some(
(ys.iter())
.flat_map(|y| xs.iter().map(|x| scissor(x, y)))
.collect(),
)
}
#[cfg(test)]
mod tests;
@@ -130,6 +130,41 @@ fn each_copy_lands_where_its_region_draws_and_clips_to_its_pixels() {
}
}
/// The scissors of the table's regions, in its order, are those its lines and clips draw: region
/// `k`'s the pixels of x segment `k mod nx` and y segment `k / nx`; and they are the plan's
/// regions' scissors, each once.
#[test]
fn each_region_s_scissor_is_its_segments_pixels_in_the_table_s_order() {
let (regions, target) = falling([3648, 1734]);
let table = table(target, &regions).expect("table");
let scissors = scissors(&regions).expect("scissors");
let [nx, ny] = counts(&table);
assert_eq!(scissors.len(), (nx * ny) as usize);
// The pixels of segment `k` of axis `a`: those of the region whose viewport the line maps.
let pixels = |a: u32, k: u32| {
let au = a as usize;
let [_, _, sa, sb] = entry(&table, line_entry(a, k));
(regions.iter())
.find(|&&(v, _)| {
let (x, ex) = (f64::from(v[au]), f64::from(v[au + 2]));
let (t0, tw) = (f64::from(target[au]), f64::from(target[au + 2]));
(ex / tw - f64::from(sa)).abs() < 1e-6
&& ((2.0 * x + ex - 2.0 * t0) / tw - 1.0 - f64::from(sb)).abs() < 1e-5
})
.map(|&(_, s)| [s[au], s[au] + s[au + 2]])
.expect("the segment's region")
};
for (k, scissor) in (0u32..).zip(&scissors) {
let ([x0, x1], [y0, y1]) = (pixels(0, k % nx), pixels(1, k / nx));
assert_eq!(*scissor, [x0, y0, x1 - x0, y1 - y0], "region {k}");
}
let mut theirs: Vec<[u32; 4]> = regions.iter().map(|&(_, s)| s).collect();
let mut ours = scissors;
theirs.sort_unstable();
ours.sort_unstable();
assert_eq!(ours, theirs);
}
/// The segments the bisection finds for an interval of normalized device coordinates hold every
/// segment with a pixel centre inside it.
#[test]
@@ -176,4 +211,5 @@ fn regions_off_the_grid_take_no_table() {
let (regions, target) = falling([1024, 1024]);
assert!(table(target, &regions[1..]).is_none());
assert!(table(target, &[]).is_none());
assert!(scissors(&regions[1..]).is_none());
}
+22 -3
View File
@@ -196,9 +196,12 @@
//! drawn without a viewport compensation, whose stages synthesize no geometry stage of their own
//! (`RuntimeFact::SynthesizedGeometry`), draw no band and choose no slice or viewport; it binds
//! the region table (`WriteSource::RateMapRegions`) and, for a probe, the flags
//! (`WriteSource::RateMapFlags`), and a probe pushes its flag's index to the geometry stage.
//! Elsewhere the plan keeps the plain variant, and the consumer draws the regions one at a time.
//! A fanned-out draw draws no regions several at a time.
//! (`WriteSource::RateMapFlags`), and a probe pushes its flag's index to the geometry stage. A
//! region-copy variant (`RegionFanOut::RegionCopies`) draws no geometry stage: its vertex
//! function draws its region's copy, binding the region table, and its draw pushes its first
//! region (`PushField::RegionFirst`) in the vertex stage's range. Elsewhere the plan keeps the
//! plain variant, and the consumer draws the regions one at a time. A fanned-out draw draws no
//! regions several at a time.
//! - **Index buffer bounds**. A direct indexed draw whose indices run past where Metal's fetch
//! stops reading its index buffer (`IndexBufferRef::fetch_end`: the length rounded up to 4 bytes;
//! Metal's API validation rejects the draw, and Apple's GPUs read index 0 past there) is drawn
@@ -1845,6 +1848,14 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
| PushField::PatchIndexBound
| PushField::ControlPointIndexOffset
if stage == Stage::Vertex && emulated_tessellation.is_some() => {}
// A region-copy variant's first region of a recording, which instantiation writes
// from the state and the consumer pushes before each recording, in the window as
// the amplification fields are.
PushField::RegionFirst
if stage == Stage::Vertex
&& (p.graphics.region_fan_out)
.is_some_and(|f| f.mode == RegionFanOut::RegionCopies)
&& matches!(field.loc, PushLoc::Push { .. }) => {}
PushField::VertexBufferStride(layout) if stage == Stage::Vertex => {
match pulled_stride(layout) {
Some(VertexStride::Static(_)) => {}
@@ -4736,6 +4747,14 @@ fn instantiate(
FieldBytes::of(&word.to_le_bytes())
}
PushField::VertexBufferStride(layout) => pulled_stride(t, state, layout)?,
// A region-copy variant's first region, which the consumer pushes before each
// recording of its regions.
PushField::RegionFirst => {
let (_, first) = state.region_fan_out.ok_or_else(|| {
internal("a region-copy variant's draw without its region")
})?;
FieldBytes::of(&first.to_le_bytes())
}
field => slot_field(field, &bound.residuals, &t.resources, state)
.ok_or_else(|| internal(format!("a render push field {field:?}")))?,
};
+7 -3
View File
@@ -157,7 +157,11 @@ pub struct BindState {
/// touches (`VariantKey::region_fan_out`, `GraphicsState::region_fan_out`), or probing which
/// of the draw's triangles it cannot ([`RegionFanOut::Probe`](crate::pipeline::RegionFanOut)),
/// and the index of the pair of words a probe writes (`PushField::RegionProbe`,
/// `WriteSource::RateMapFlags`; 0 for a draw). The
/// `WriteSource::RateMapFlags`; 0 for a draw); or records them region by region through that
/// viewport, its vertex function putting each vertex in its region as the triangle stage
/// puts a copy's ([`RegionFanOut::RegionCopies`](crate::pipeline::RegionFanOut)), and the first
/// region, in the region table's order, of the draw's recording (`PushField::RegionFirst`),
/// which the consumer pushes again for each of its recordings. The
/// consumer sets it only for a draw of triangles. The plan's variant fans out only a vertex
/// pipeline without tessellation drawn in one pass of no views, whose stages synthesize no
/// geometry stage of their own and draw no band (`bind::graphics`'s module docs). Its variant
@@ -1873,8 +1877,8 @@ pub struct BindShape {
#[cfg_attr(feature = "serde", serde(default))]
pub region_viewports: bool,
/// `BindState.region_fan_out`'s variant: a draw of a rate-mapped pass's triangles once, its
/// variant's triangle stage fanning them out to their regions, or probing which it cannot
/// (`VariantKey::region_fan_out`).
/// variant's triangle stage fanning them out to their regions, or probing which it cannot, or
/// region by region through its vertex function's copies (`VariantKey::region_fan_out`).
#[cfg_attr(feature = "serde", serde(default))]
pub region_fan_out: Option<crate::pipeline::RegionFanOut>,
}
+2 -1
View File
@@ -918,6 +918,7 @@ codec_enum! {
YCbCrInPlace(f0),
LineBand,
RegionProbe,
RegionFirst,
}
Symbol { Binding(f0), DescriptorSet(f0), Location(f0), Component(f0), SpecId(f0) }
}
@@ -1447,7 +1448,7 @@ codec_enum! {
StorageAttachmentView { Attachment, SamplePlanes { layers } }
StandInView { Image, SamplePlanes { layers } }
BandPrimitive { Lines, Triangles }
RegionFanOut { Draw, Probe, DrawFew }
RegionFanOut { Draw, Probe, DrawFew, RegionCopies }
PrecisionNote {
F16FmaDoubleRounding, F16IntConvDoubleRounding, GradFromBias,
DeviceTranscendentals, ReductionOrder, DeviceDenormals,
+6 -3
View File
@@ -61,7 +61,7 @@ mod tests;
/// unchanged version, and its bless records the version. Independent of the crate's version and of
/// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no
/// history.
pub const SEMANTICS_VERSION: u32 = 2097;
pub const SEMANTICS_VERSION: u32 = 2098;
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
@@ -71,7 +71,7 @@ pub const SEMANTICS_VERSION: u32 = 2097;
/// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag
/// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that
/// bumps it says what changed; this comment keeps no history.
pub const ARTIFACT_FORMAT_VERSION: u32 = 518;
pub const ARTIFACT_FORMAT_VERSION: u32 = 519;
/// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding
/// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle
@@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 518;
/// changes no behaviour, and then updates that hash alone with the commit saying why, or changes
/// behaviour and also bumps this version. The commit that bumps it says what changed; this comment
/// keeps no history.
pub const RUNTIME_VERSION: u32 = 2243;
pub const RUNTIME_VERSION: u32 = 2244;
/// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex,
/// of the manifest, the build script, and exactly the files the crate roots' module tree compiles
@@ -676,6 +676,9 @@ impl VariantKey {
.filter(|_| stage == crate::pipeline::sym::Stage::Vertex);
out.region_viewports =
self.region_viewports && stage == crate::pipeline::sym::Stage::Vertex;
out.region_copies = self.region_fan_out
== Some(crate::pipeline::RegionFanOut::RegionCopies)
&& stage == crate::pipeline::sym::Stage::Vertex;
out.storage_view_slots = self
.storage_view_slots
.iter()
+10 -5
View File
@@ -752,10 +752,10 @@ pub enum VertexReachPolicy {
/// by region, a draw runs its vertex function once per region (a plan may hold thousands); fanned
/// out, once, a geometry stage emitting a copy of each triangle for each region it touches, through
/// one viewport over the whole target, clip distances keeping each copy to its region's pixels.
/// A copy's window coordinates are the region viewport's computed in the geometry stage, so a
/// pixel centre within a rounding error of a triangle's edge may be covered by one route and not
/// the other. The runtime's choice alone: no emitted code of a pipeline changes, the fan-out and
/// its probe being variants of their own (`VariantKey::region_fan_out`).
/// A copy's window coordinates are the region viewport's computed in the shader, so a pixel
/// centre within a rounding error of a triangle's edge may be covered under one value and not
/// the other. The runtime's choice alone: no emitted code of a pipeline changes, the fan-out, its
/// probe and the region-copy variant being variants of their own (`VariantKey::region_fan_out`).
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
@@ -765,7 +765,12 @@ pub enum RateMapRegionPolicy {
/// submitted and waited for first, flags each draw a triangle of which crosses `w = 0` or
/// touches more regions than the fan-out's copies, and counts the copies of the others; a
/// flagged draw is drawn region by region, the others once each, fanned out. Every other draw
/// is drawn region by region.
/// is drawn region by region: on such a device that also enables `multiViewport`,
/// `shaderOutputViewportIndex` and `shaderDrawParameters`, one the fan-out's variant takes
/// through its region-copy variant, whose vertex function puts each vertex in its region as a
/// fanned-out draw's copy is put, each region through a viewport over the render area and its
/// own scissor, so every route of the pass rasterizes a vertex at one position; any other
/// through each region's viewport and scissor.
#[default]
FanOut,
/// Every draw region by region, each region's through its own viewport and scissor.
+2
View File
@@ -139,6 +139,8 @@ pub const fn shape(f: PushField) -> FieldShape {
| PushField::ControlPointIndexOffset => FieldShape::U32,
// An emulated tessellation draw's chunk.
PushField::TessellationChunk => FieldShape::U32,
// The first region a recording of a rate-mapped pass's regions draws.
PushField::RegionFirst => 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.
@@ -116,6 +116,12 @@
//! through more than one variant of its pipeline (each color group's) rasterizes the same
//! positions in each.
//!
//! A vertex function compiled under `LoweringInputs::region_copies` stores its region's copy at
//! every return ([`RegionCopy`]): region `PushField::RegionFirst + DrawIndex` of the region table,
//! its position through the region's line and four clip distances after its own, by the emitter
//! a fan-out stage's copies share (`pipeline::link::fan_out::region_copy`), and `DrawIndex` as
//! `ViewportIndex`; those clip distances are `Invariant` too.
//!
//! A fragment function compiled for a render pipeline that rasterizes more than one sample
//! (`LoweringInputs::multisampled`) reads what Metal reads at the pixel center in every invocation
//! there ([`Source::PixelCenter`]): `[[position]]`'s x and y as `floor(FragCoord.xy) + 0.5`, and,
@@ -372,6 +378,18 @@ pub struct RegionViewport {
pub viewport: usize,
}
/// The region's copy a vertex function compiled under `LoweringInputs::region_copies` stores
/// (`plan::region_copy`): interface objects `position`, its `Position` output, `draw_index`, the
/// `DrawIndex` input, `viewport`, the `ViewportIndex` output it stores `DrawIndex` to, and
/// `clip`, its `ClipDistance` object and the first of the four elements it writes after its own.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct RegionCopy {
pub position: usize,
pub draw_index: usize,
pub viewport: usize,
pub clip: (usize, u32),
}
/// The private alpha test a fragment function compiled under `LoweringInputs::alpha_test` runs
/// at each return ([`alpha_test`]): the returned field of its color 0, four `float` lanes (a
/// `half` output held widened), and the comparison.
@@ -401,6 +419,10 @@ pub struct StageIoPlan {
/// A vertex function compiled under `LoweringInputs::region_viewports` that returns outputs:
/// its `DrawIndex` input, which it stores to its `ViewportIndex` output at every return.
pub region_viewport: Option<RegionViewport>,
/// A vertex function compiled under `LoweringInputs::region_copies` that returns outputs: the
/// region's copy it stores at every return, its position through the region's line and four
/// clip distances keeping the region's pixels.
pub region_copy: Option<RegionCopy>,
/// The color outputs a fragment function compiled under `LoweringInputs::zeroed_colors`
/// stores zero to at every return, one per such color.
pub zeroed: Vec<Link>,
@@ -698,6 +720,9 @@ pub struct Declared {
/// covered samples is read into at every sample before the loop, where the driver's
/// interpolation needs the whole quad ([`read_at_every_sample`]).
pub at_samples: BTreeMap<usize, GlobalId>,
/// The region table a vertex function that stores its region's copy reads
/// ([`StageIoPlan::region_copy`]).
pub region_table: Option<GlobalId>,
}
/// Plan the entry's stage interface: its outputs and execution modes. A kernel has none (and a
@@ -1832,6 +1857,7 @@ pub fn emit_return(
let (outputs, returned, point) = (plan.outputs.clone(), plan.returned, plan.point_size_default);
let seconds = plan.rotated_seconds.clone();
let compensation = plan.compensation;
let region_copy = plan.region_copy;
let depth_clamp = plan.depth_clamp;
let window_depth = plan.window_depth;
let primitive_id = plan.primitive_id;
@@ -1870,6 +1896,10 @@ pub fn emit_return(
Some(c) => compensate(cx, fb, c, part, selected)?,
None => part,
};
let part = match region_copy.filter(|r| r.position == o.link.object) {
Some(r) => store_region_copy(cx, fb, r, part)?,
None => part,
};
let part = match depth_clamp.filter(|d| d.object == o.link.object) {
Some(d) => {
let kill = nan_drop(cx)?;
@@ -2601,6 +2631,55 @@ fn compensate(
fb.composite_construct(vec4, &[sxx, y_out, depth, w])
}
/// `position`, a vertex function's `float4` position, as its region's copy (`r`,
/// `LoweringInputs::region_copies`): region `PushField::RegionFirst + DrawIndex` of the region
/// table, in the table's order, its position through the region's line and its four clip
/// distances stored after the function's own, by the emitter a fan-out stage's copies share
/// (`pipeline::link::fan_out::region_copy`), and `DrawIndex` stored as `ViewportIndex`.
fn store_region_copy(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
r: RegionCopy,
position: SValue,
) -> BResult<SValue> {
use crate::pipeline::link::fan_out;
let Some(table) = cx.decl.families.stage_io.region_table else {
return Err(cx.fail("a region's copy without its region table"));
};
let first = cx.push_field(fb, PushField::RegionFirst)?;
let draw = fetch::load_builtin(cx, fb, r.draw_index)?;
let k = fb.binary(BinOp::IAdd, first, draw)?;
// The draw's index among a multi-draw's selects its viewport, each the same target viewport,
// and so its region's scissor.
let link = Link {
object: r.viewport,
place: Place::Whole,
form: Form {
held: Held::Int {
bits: 32,
container: 32,
},
lanes: 1,
},
};
store(cx, fb, &link, draw)?;
let segments = fan_out::region_segments(fb, table, k)?;
let f32_ = fb.module().ty(SType::Float { width: 32 })?;
let vec4 = fb.module().ty(SType::Vector { elem: f32_, len: 4 })?;
let terms = fan_out::region_terms(fb, (table, f32_), segments)?;
let (moved, distances) = fan_out::region_copy(fb, &terms, position, vec4)?;
let (object, first) = r.clip;
let g = global(cx, object)?;
let base = fb.module().global_value(g)?;
for (k, d) in (first..).zip(distances) {
let kc = fb.u32_const(k)?;
let kc = fb.module().const_value(kc)?;
let p = fb.access_chain(base, &[kc])?;
fb.store(p, d, MemAccess::default())?;
}
Ok(moved)
}
/// How a return drops a positive NaN depth, which fails Metal's depth test (`clamp_depth`).
#[derive(Clone, Copy, Debug)]
enum NanDrop {
@@ -2989,6 +3068,14 @@ pub fn declare(
if let Some(g) = sp.invariant.and_then(|i| d.globals.get(i)) {
mb.invariant(*g)?;
}
// A region's copy: its clip distances computed alike in every pipeline that draws the
// function's region copies, as a fan-out stage's are, and the table it reads.
if let Some(r) = sp.region_copy {
if let Some(g) = d.globals.get(r.clip.0) {
mb.invariant(*g)?;
}
d.region_table = Some(crate::pipeline::link::fan_out::declare_table(mb)?);
}
if sp.invariant_fragment_outputs {
use crate::spv::BuiltIn as B;
for (o, g) in sp.objects.iter().zip(&d.globals) {
+159 -49
View File
@@ -2717,6 +2717,9 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> {
if cx.inputs.region_viewports && cx.stage == Stage::Vertex {
region_viewport(cx, &outputs, returned)?;
}
if cx.inputs.region_copies && cx.stage == Stage::Vertex {
region_copy(cx, &outputs, returned)?;
}
// A viewport Vulkan's cannot be: the position compensated for it.
if let Some(c) = cx
.inputs
@@ -3045,55 +3048,7 @@ fn compensate(cx: &mut SelectCx<'_>, c: ViewportCompensation) -> Result<(), Erro
let added = 2 * u32::from(c.depth) + 4 * u32::from(c.point_guard);
let clips = match added {
0 => None,
_ => {
if !cx.profile.fields().fragment.clip_distance {
return Err(needs(Feature::ClipDistance, VkFeature::ShaderClipDistance));
}
let limits = cx.profile.fields().limits;
let sp = &mut cx.families.stage_io;
let own = sp.objects.iter().position(|o| is(o, B::ClipDistance));
let first = match own.and_then(|i| sp.objects.get(i)) {
Some(IoObject::Builtin {
shape: Shape::F32Array(n),
..
}) => *n,
Some(_) => return Err(not_lowered()),
None => 0,
};
let count = first + added;
for (lim, max) in [
(VkLimit::MaxClipDistances, limits.max_clip_distances),
(
VkLimit::MaxCombinedClipAndCullDistances,
limits.max_combined_clip_and_cull_distances,
),
] {
if count > max {
return Err(limit(Feature::ClipDistance, lim, u64::from(count), max));
}
}
let object = match own {
// The function's own clip distances, two elements longer.
Some(i) => {
if let Some(IoObject::Builtin { shape, .. }) = sp.objects.get_mut(i) {
*shape = Shape::F32Array(count);
}
let builtins = &mut sp.interface.builtins;
builtins.retain(|b| !matches!(b, StageBuiltin::ClipDistance { .. }));
builtins.push(StageBuiltin::ClipDistance { count });
builtins.sort();
i
}
None => builtin(
sp,
B::ClipDistance,
IoDir::Output,
Shape::F32Array(count),
StageBuiltin::ClipDistance { count },
),
};
Some((object, first))
}
_ => Some(added_clip_distances(cx, added, Feature::ClipDistance)?),
};
let clip = clips.filter(|_| c.depth);
let guard = clips
@@ -3109,6 +3064,161 @@ fn compensate(cx: &mut SelectCx<'_>, c: ViewportCompensation) -> Result<(), Erro
Ok(())
}
/// Add `added` clip distances past a vertex function's own, for `feature`: its `ClipDistance`
/// object, `added` elements longer, or a new one, and the first of the added elements. Refused as
/// `feature` where the device writes no clip distances or the count passes its limits.
fn added_clip_distances(
cx: &mut SelectCx<'_>,
added: u32,
feature: Feature,
) -> Result<(usize, u32), Error> {
if !cx.profile.fields().fragment.clip_distance {
return Err(needs(feature, VkFeature::ShaderClipDistance));
}
let is = |o: &IoObject| {
matches!(
o,
IoObject::Builtin {
builtin: B::ClipDistance,
dir: IoDir::Output,
..
}
)
};
let limits = cx.profile.fields().limits;
let sp = &mut cx.families.stage_io;
let own = sp.objects.iter().position(is);
let first = match own.and_then(|i| sp.objects.get(i)) {
Some(IoObject::Builtin {
shape: Shape::F32Array(n),
..
}) => *n,
Some(_) => return Err(not_lowered()),
None => 0,
};
let count = first + added;
for (lim, max) in [
(VkLimit::MaxClipDistances, limits.max_clip_distances),
(
VkLimit::MaxCombinedClipAndCullDistances,
limits.max_combined_clip_and_cull_distances,
),
] {
if count > max {
return Err(limit(feature, lim, u64::from(count), max));
}
}
let object = match own {
// The function's own clip distances, `added` elements longer.
Some(i) => {
if let Some(IoObject::Builtin { shape, .. }) = sp.objects.get_mut(i) {
*shape = Shape::F32Array(count);
}
let builtins = &mut sp.interface.builtins;
builtins.retain(|b| !matches!(b, StageBuiltin::ClipDistance { .. }));
builtins.push(StageBuiltin::ClipDistance { count });
builtins.sort();
i
}
None => builtin(
sp,
B::ClipDistance,
IoDir::Output,
Shape::F32Array(count),
StageBuiltin::ClipDistance { count },
),
};
Ok((object, first))
}
/// Plan the region's copy a vertex function with outputs `outputs`, returning `returned`,
/// compiled under `LoweringInputs::region_copies`, stores at every return: region `first +
/// DrawIndex` of the region table (`PushField::RegionFirst`, the specification's `DrawIndex`,
/// 0 for a draw that is no multi-draw's), its position moved by the region's line and four clip
/// distances past its own keeping the region's pixels ([`super::RegionCopy`],
/// `pipeline::link::fan_out::region_copy`), and `DrawIndex` as `ViewportIndex`, which selects
/// the region's scissor among a multi-draw's. A function that writes its own viewport or slice
/// index, one under another field that moves its indices or position (`amplification_draws`,
/// `viewport_compensation`), reads its draw from a replay (`replay_bindings`, `merged_draws`),
/// runs behind the tessellator or returns no outputs is `NotImplemented(RasterizationRateMap)`:
/// the runtime draws those through each region's viewport. A device that cannot store
/// `ViewportIndex` from a vertex function, read `DrawIndex`, take several viewports or write four
/// more clip distances refuses it.
fn region_copy(
cx: &mut SelectCx<'_>,
outputs: &[OutputBinding],
returned: Returned,
) -> Result<(), Error> {
let i = &cx.inputs;
let indexed = outputs.iter().any(|o| {
matches!(
o.role,
OutputRole::ViewportArrayIndex | OutputRole::RenderTargetArrayIndex
)
});
let tessellated = matches!(cx.entry.ep.stage, AirStage::Vertex { patch: Some(_) });
let sp = &cx.families.stage_io;
let position = sp.objects.iter().position(|o| {
matches!(
o,
IoObject::Builtin {
builtin: B::Position,
dir: IoDir::Output,
..
}
)
});
let position = match position {
Some(p) if returned != Returned::Void => p,
_ => return Err(Unsupported::not_implemented(Feature::RasterizationRateMap).into()),
};
if indexed
|| tessellated
|| i.amplification_draws.is_some()
|| i.viewport_compensation.is_some()
|| i.region_viewports
|| i.replay_bindings
|| i.merged_draws
{
return Err(Unsupported::not_implemented(Feature::RasterizationRateMap).into());
}
let f = cx.profile.fields();
let multi_viewport = f.enabled.features.contains(&VkFeature::MultiViewport);
if !(f.fragment.output_viewport_index && f.draw_parameters && multi_viewport) {
return Err(Unsupported::needs_any_of(
Feature::RasterizationRateMap,
vec![vec![
Capability::Feature(VkFeature::ShaderOutputViewportIndex),
Capability::Feature(VkFeature::ShaderDrawParameters),
Capability::Feature(VkFeature::MultiViewport),
]],
)
.into());
}
let clip = added_clip_distances(cx, 4, Feature::RasterizationRateMap)?;
cx.push.insert(PushField::RegionFirst);
// The region table, one more storage buffer of the stage.
let d = &mut cx.descriptors;
d.storage_buffers = d.storage_buffers.saturating_add(1);
let sp = &mut cx.families.stage_io;
let draw_index = builtin(
sp,
B::DrawIndex,
IoDir::Input,
Shape::U32,
StageBuiltin::DrawIndex,
);
// Not the contract's `ViewportIndex`, as a region viewport's is not (`region_viewport`).
let viewport = builtin_object(sp, B::ViewportIndex, IoDir::Output, Shape::U32);
sp.region_copy = Some(super::RegionCopy {
position,
draw_index,
viewport,
clip,
});
Ok(())
}
/// Plan one output of AIR type `ty`.
fn output(cx: &mut SelectCx<'_>, o: &OutputBinding, ty: AirTypeId) -> Result<Link, Error> {
// A shared output (`air.shared`) has the same value for every amplification; each view
@@ -489,6 +489,7 @@ mod serde_round_trips {
}),
object_payload: Some(64),
region_viewports: true,
region_copies: true,
});
}
@@ -1754,6 +1754,9 @@ fn variant_fields(v: &VariantKey) -> String {
Some(crate::pipeline::RegionFanOut::Draw) => fields.push_str(" region_fan_out"),
Some(crate::pipeline::RegionFanOut::Probe) => fields.push_str(" region_fan_out probe"),
Some(crate::pipeline::RegionFanOut::DrawFew) => fields.push_str(" region_fan_out few"),
Some(crate::pipeline::RegionFanOut::RegionCopies) => {
fields.push_str(" region_fan_out copies")
}
}
fields
}
@@ -531,6 +531,10 @@ pub fn function_key(
if inputs.region_viewports {
h.bytes(b"region-viewports");
}
// Appended only when set.
if inputs.region_copies {
h.bytes(b"region-copies");
}
// Appended only when present, so a stage that links nothing keeps its key: the tag's length
// prefix keeps the encoding unambiguous.
if !linked.is_empty() {
@@ -745,7 +745,8 @@ fn the_inputs_encoding_is_the_earlier_derived_debug() {
.replace(", color_group: None", "")
.replace(", object_payload: None", "")
.replace(", tessellation: None", "")
.replace(", region_viewports: false", ""),
.replace(", region_viewports: false", "")
.replace(", region_copies: false", ""),
"{derived}"
);
}
+20 -3
View File
@@ -420,6 +420,12 @@ pub enum RegionFanOut {
/// [`Draw`](Self::Draw) through a stage of at most `bind::fan_out::FEW_COPIES` copies, for a
/// draw the probe found none of whose triangles reaches more pairs of segments.
DrawFew,
/// Draw the plan's regions region by region, each region's copy of each vertex computed by
/// the vertex function as a fanned-out copy's is, the draw's index stored as `ViewportIndex`
/// (`LoweringInputs::region_copies`): no geometry stage. A draw of a pass whose triangles a
/// draw fans out that is not fanned out itself, so that every route of the pass puts a vertex
/// in a region at the same position (`bind::fan_out`, **One route per pass**).
RegionCopies,
}
/// What a consumer and the binder need of a render pipeline variant that draws a rate-mapped
@@ -429,7 +435,15 @@ pub enum RegionFanOut {
///
/// 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. Of
/// viewport over the plan's regions bound. A draw of [`RegionFanOut::RegionCopies`] records the
/// plan's regions in the table's order, `k` of them a recording (one draw of a
/// `vkCmdDrawMultiEXT` or `vkCmdDrawMultiIndexedEXT` each, or a draw alone), each recording
/// pushing the index of its first region to its vertex function's `PushField::RegionFirst`, at
/// [`push_offset`](Self::push_offset) of its stage `VERTEX`: the vertex function draws region
/// `first + DrawIndex` and stores `DrawIndex` as `ViewportIndex`. Such a recording sets every
/// viewport its pipeline takes to the one over the whole target, and at each draw's index its
/// region's scissor (`bind::fan_out::scissors`, in the table's order). A probe
/// ([`RegionFanOut::Probe`]) draws nothing. Of
/// the flags buffer's (`SyntheticBinding::RateMapFlags`) `bind::fan_out::PROBE_DRAW_WORDS`
/// `u32`s from `PROBE_DRAW_WORDS·i`, `i` its pushed index (`PushField::RegionProbe`, at
/// [`push_offset`](Self::push_offset) for stage `GEOMETRY`), it writes 1 into the first where a
@@ -451,10 +465,13 @@ pub enum RegionFanOut {
pub struct FanOutState {
/// What the variant does.
pub mode: RegionFanOut,
/// The most copies of a triangle its stage emits.
/// The most copies of a triangle its stage emits; 0 for [`RegionFanOut::RegionCopies`], which
/// emits each vertex once.
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.
/// `GEOMETRY`, [`PUSH_BYTES`](Self::PUSH_BYTES)); of the vertex function's
/// `PushField::RegionFirst` in its push window for [`RegionFanOut::RegionCopies`]; 0 for a
/// draw.
pub push_offset: u32,
}
+25
View File
@@ -553,6 +553,15 @@ pub fn link(
push_offset: fan.push_offset,
});
}
// A region-copy variant draws no geometry stage: its vertex function draws its region's
// copy, the first region of a recording pushed at its `RegionFirst` field.
if r.region_fan_out == Some(crate::pipeline::RegionFanOut::RegionCopies) {
gs.region_fan_out = Some(crate::pipeline::graphics::FanOutState {
mode: crate::pipeline::RegionFanOut::RegionCopies,
copies: 0,
push_offset: region_first(vs)?,
});
}
(vi, Some(gs))
}
// The mesh stage stands in the vertex stage's place; the fragment stage follows it.
@@ -611,6 +620,22 @@ pub fn link(
/// The graphics state of a render or mesh render pipeline whose geometry stage (its vertex or
/// mesh stage) is `geometry`, with its fragment stage's.
/// The byte offset of the push-constant block a region-copy variant's vertex function `vs` reads
/// its recording's first region at (`PushField::RegionFirst`): each recording pushes its own, so
/// a function that holds it in its `ArgumentTable`, or reads none, is
/// `NotImplemented(RasterizationRateMap)`.
fn region_first(vs: &StageInterface) -> Result<u32, Error> {
let at = vs
.push
.fields
.iter()
.find(|f| f.field == crate::pipeline::sym::PushField::RegionFirst);
match at.map(|f| f.loc) {
Some(crate::pipeline::interface::PushLoc::Push { offset }) => Ok(offset),
_ => Err(Unsupported::not_implemented(Feature::RasterizationRateMap).into()),
}
}
fn render_state(
r: &RenderLinkInputs,
geometry: &StageInterface,
+107 -40
View File
@@ -14,7 +14,10 @@
//! - **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. The copies are a loop the driver is asked not to unroll (`DontUnroll`): its
//! the probe found. Each copy's vertices are [`region_copy`]'s, the emitter a vertex function
//! that draws its region's copy shares (`LoweringInputs::region_copies`), and the stage's
//! `Position` and `ClipDistance` outputs are `Invariant`. The copies are a loop the driver is
//! asked not to unroll (`DontUnroll`): its
//! body compiled once, the pipeline is made in about a third of the time 16 unrolled copies
//! took (on an RTX 3090 45.2 against 81.3 ms for the probe's and the draw's, Iris Xe 20.0
//! against 66.9 ms, Radeon 780M 14.4 against 44.5 ms), with the same GPU time. A draw of few
@@ -184,37 +187,99 @@ fn extreme(fb: &mut FunctionBuilder<'_>, op: GlslOp, v: [Value; 3]) -> BResult<V
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);
/// Declare the region table (`SyntheticBinding::RateMapRegions`, [`REGIONS_SLOT`]) in `mb`: a
/// `Block { uint[] }` storage buffer, which a fan-out stage reads and a vertex function that
/// draws its region's copy (`LoweringInputs::region_copies`) reads alike.
pub(crate) fn declare_table(mb: &mut ModuleBuilder) -> BResult<GlobalId> {
let u32_ = mb.ty(Type::Int {
width: 32,
signed: false,
})?;
let words = mb.ty(Type::RuntimeArray {
elem: u32_,
stride: Some(4),
})?;
let layout = natural_layout(mb.types(), LayoutRule::Std430, true, &[words])?;
let block = mb.ty(Type::Struct {
members: [words].into(),
layout: Some(layout),
})?;
mb.resource(REGIONS_SLOT, StorageClass::StorageBuffer, block)
}
/// The segments of region `k` (a `uint`) of the table `table`, in its order (`bind::fan_out`,
/// **One route per pass**): `(k mod nx, k / nx)`, `nx` its segments of axis x.
pub(crate) fn region_segments(
fb: &mut FunctionBuilder<'_>,
table: GlobalId,
k: Value,
) -> BResult<(Value, Value)> {
let header = ku(fb, 0)?;
let nx = word(fb, table, header)?;
let sx = fb.binary(BinOp::UMod, k, nx)?;
let sy = fb.binary(BinOp::UDiv, k, nx)?;
Ok((sx, sy))
}
/// The terms of the copy for segments `sx` and `sy` (`uint`s) of the table `table` (its global
/// and `float` type), of axis x then y: `[a, b, W/2, X + W/2 − p₀, p₁ − X − W/2]`, its line's
/// `a` and `b` and its clip (the layout of `bind::fan_out`).
pub(crate) fn region_terms(
fb: &mut FunctionBuilder<'_>,
table: (GlobalId, TypeId),
(sx, sy): (Value, Value),
) -> BResult<[[Value; 5]; 2]> {
let mut axes = [[sx; 5]; 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));
let terms = &mut axes[axis as usize];
terms[0] = component(fb, table, line_entry(axis, 0), Some(s), 2)?;
terms[1] = component(fb, table, line_entry(axis, 0), Some(s), 3)?;
for (t, c) in [(2, 0), (3, 1), (4, 2)] {
terms[t] = component(fb, table, clip_entry(axis, 0), Some(s), c)?;
}
}
Ok(axes)
}
/// The copy of the clip-space position `p` (a `vec4` of type `vec4`) through `terms`
/// ([`region_terms`]): `(a·x + b·w, a·y + b·w, z, w)`, each axis's own `a` and `b`, and the clip
/// distances `W/2·v + lo·w` and `hi·w − W/2·v` of x then y. The one emitter of a region's copy:
/// a fan-out stage's of each vertex it emits, and a vertex function's that draws its region's
/// copy (`LoweringInputs::region_copies`). Each operation is decorated `NoContraction`, so each
/// is correctly rounded on its own (Vulkan's *Precision and Operation of SPIR-V Instructions*)
/// and both put a vertex in a region at the same bits (`bind::fan_out`, **One route per pass**).
pub(crate) fn region_copy(
fb: &mut FunctionBuilder<'_>,
terms: &[[Value; 5]; 2],
p: Value,
vec4: TypeId,
) -> BResult<(Value, [Value; 4])> {
let w = fb.composite_extract(p, &[3])?;
let z = fb.composite_extract(p, &[2])?;
let mut moved = [w; 2];
let mut distances = [w; 4];
for (axis, &[a, b, half, lo, hi]) in terms.iter().enumerate() {
let v = fb.composite_extract(p, &[axis as u32])?;
let av = fb.binary_no_contraction(BinOp::FMul, a, v)?;
let bw = fb.binary_no_contraction(BinOp::FMul, b, w)?;
moved[axis] = fb.binary_no_contraction(BinOp::FAdd, av, bw)?;
let hv = fb.binary_no_contraction(BinOp::FMul, half, v)?;
let low = fb.binary_no_contraction(BinOp::FMul, lo, w)?;
distances[2 * axis] = fb.binary_no_contraction(BinOp::FAdd, hv, low)?;
let high = fb.binary_no_contraction(BinOp::FMul, hi, w)?;
distances[2 * axis + 1] = fb.binary_no_contraction(BinOp::FSub, high, hv)?;
}
let position = fb.composite_construct(vec4, &[moved[0], moved[1], z, w])?;
Ok((position, distances))
}
/// 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 ([`region_copy`]).
fn emit_copy(fb: &mut FunctionBuilder<'_>, c: &Copies, (sx, sy): (Value, Value)) -> BResult<()> {
let terms = region_terms(fb, (c.table, c.f32_), (sx, sy))?;
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 (position, distances) = region_copy(fb, &terms, p, c.vec4)?;
let to = fb.module().global_value(c.position)?;
fb.store(to, position, MemAccess::default())?;
let clips = fb.module().global_value(c.clips)?;
@@ -261,6 +326,7 @@ pub(super) fn module(stages: &GeometryStages, fan: FanOutStage) -> BResult<Typed
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)?;
mb.invariant(position)?;
let own = stages.clip_distances;
let own_clips = match own {
0 => None,
@@ -272,6 +338,7 @@ pub(super) fn module(stages: &GeometryStages, fan: FanOutStage) -> BResult<Typed
};
let ty = array(&mut mb, f32_, own + 4)?;
let clips = mb.builtin(B::ClipDistance, IoDir::Output, ty)?;
mb.invariant(clips)?;
let packed = IoDecor {
packed: true,
..IoDecor::default()
@@ -296,18 +363,18 @@ pub(super) fn module(stages: &GeometryStages, fan: FanOutStage) -> BResult<Typed
)),
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 table = declare_table(&mut mb)?;
let probe = match fan.mode {
RegionFanOut::Probe => {
let words = mb.ty(Type::RuntimeArray {
elem: u32_,
stride: Some(4),
})?;
let layout = natural_layout(mb.types(), LayoutRule::Std430, true, &[words])?;
let block = mb.ty(Type::Struct {
members: [words].into(),
layout: Some(layout),
})?;
let flags = mb.resource(FLAGS_SLOT, StorageClass::StorageBuffer, block)?;
let member = (mb.push_member(PushField::RegionProbe, u32_, fan.push_offset)?).index;
// The probe picks a triangle's count by its `PrimitiveId`.
@@ -317,7 +384,7 @@ pub(super) fn module(stages: &GeometryStages, fan: FanOutStage) -> BResult<Typed
};
Some((flags, member, mb.push_global()?, id))
}
RegionFanOut::Draw | RegionFanOut::DrawFew => None,
RegionFanOut::Draw | RegionFanOut::DrawFew | RegionFanOut::RegionCopies => None,
};
let mut fb = mb.function(void)?;
let mut loaded = Vec::with_capacity(3);
@@ -532,7 +599,7 @@ pub(super) fn module(stages: &GeometryStages, fan: FanOutStage) -> BResult<Typed
fb.ret(None)?;
let f = fb.finish()?;
let vertices = match fan.mode {
RegionFanOut::Draw | RegionFanOut::DrawFew => 3 * copies,
RegionFanOut::Draw | RegionFanOut::DrawFew | RegionFanOut::RegionCopies => 3 * copies,
RegionFanOut::Probe => 3,
};
let modes = vec![
@@ -224,7 +224,9 @@ pub fn plan(
layer: selects(IoRole::SelectedLayer),
viewport: selects(IoRole::SelectedViewport),
};
if let Some(mode) = fan_out {
// A variant that draws its regions' copies from its vertex function synthesizes no stage
// for them (`LoweringInputs::region_copies`).
if let Some(mode) = fan_out.filter(|&mode| mode != RegionFanOut::RegionCopies) {
return fan_plan(ifaces, (why, mode), (amplification, mesh), p).map(Some);
}
if !why.weights && !why.layer && !why.viewport {
@@ -449,7 +451,9 @@ impl GeometryStages {
}
let most = match fan.mode {
RegionFanOut::DrawFew => crate::bind::fan_out::FEW_COPIES,
RegionFanOut::Draw | RegionFanOut::Probe => fan_out::MOST_COPIES,
RegionFanOut::Draw | RegionFanOut::Probe | RegionFanOut::RegionCopies => {
fan_out::MOST_COPIES
}
};
fan.copies = room.min(u64::from(most)) as u32;
}
@@ -56,8 +56,9 @@ fn count_ops(words: &[u32], op: u32) -> usize {
}
/// A draw's triangle stage emits three vertices a copy, in a loop of as many copies as its state
/// says, its output vertices three a copy, 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.
/// says, its output vertices three a copy, its copies' arithmetic `NoContraction`, and a probe's
/// none and pushes its flag's index in the geometry stage's own range; its `Position` and
/// `ClipDistance` are `Invariant`; 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"] {
@@ -74,7 +75,7 @@ fn a_fan_out_variant_s_triangle_stage_emits_its_copies() {
let fan = g.fan_out.expect("the fan-out stage");
let most = match mode {
RegionFanOut::DrawFew => crate::bind::fan_out::FEW_COPIES,
RegionFanOut::Draw | RegionFanOut::Probe => 16,
_ => 16,
};
assert!((1..=most).contains(&fan.copies), "{stem}: {}", fan.copies);
let state = linked
@@ -92,10 +93,8 @@ fn a_fan_out_variant_s_triangle_stage_emits_its_copies() {
.map(|r| (r.offset, r.size))
.collect::<Vec<_>>();
match mode {
RegionFanOut::Draw | RegionFanOut::DrawFew => {
assert!(pushes.is_empty(), "{stem}")
}
RegionFanOut::Probe => assert_eq!(pushes, [(fan.push_offset, 4)], "{stem}"),
_ => assert!(pushes.is_empty(), "{stem} {mode:?}"),
}
let made = g
.stages(&linked, &p, &mut crate::pipeline::testing::meter())
@@ -107,8 +106,8 @@ fn a_fan_out_variant_s_triangle_stage_emits_its_copies() {
let (expected, outputs) = match (class, mode) {
(Class::Point, _) => (1, 1),
(Class::Line, _) => (2, 2),
(_, RegionFanOut::Draw | RegionFanOut::DrawFew) => (3, 3 * fan.copies),
(_, RegionFanOut::Probe) => (0, 3),
(_, _) => (3, 3 * fan.copies),
};
assert_eq!(emits, expected, "{stem} {mode:?} {class:?}");
let loops = count_ops(&module.spirv, crate::spv::Op::LoopMerge as u32);
@@ -122,6 +121,24 @@ fn a_fan_out_variant_s_triangle_stage_emits_its_copies() {
.map(|m| m[2])
.collect::<Vec<u32>>();
assert_eq!(declared, [outputs], "{stem} {mode:?} {class:?}");
if class != Class::Triangle {
continue;
}
let decorated = |decoration: crate::spv::Decoration| {
(instructions(&module.spirv, crate::spv::Op::Decorate).into_iter())
.filter(|d| d.get(1) == Some(&(decoration as u32)))
.count()
};
// Of each of a copy's three vertices, each axis's coordinate and its two clip
// distances: five products and three sums.
let contracted = match mode {
RegionFanOut::Probe => 0,
_ => 3 * 2 * 8,
};
let no_contraction = decorated(crate::spv::Decoration::NoContraction);
assert_eq!(no_contraction, contracted, "{stem} {mode:?}");
let invariant = decorated(crate::spv::Decoration::Invariant);
assert_eq!(invariant, 2, "{stem} {mode:?}");
}
}
}
@@ -275,3 +292,34 @@ fn what_the_fan_out_cannot_carry_is_refused() {
other => panic!("{other:?}"),
}
}
/// A region-copy variant draws no geometry stage: its vertex function draws its region's copy, at
/// the first region it reads pushed (`PushField::RegionFirst`), which its graphics state names; a
/// vertex function that reads none is refused.
#[test]
fn a_regions_variant_draws_its_vertex_function_s_copies() {
let p = profile("lavapipe");
let (mut v, f) = pipeline();
let regions = fanned(RegionFanOut::RegionCopies);
not_implemented(link(&[&v, &f], &regions, &p).unwrap_err());
let fields = BTreeSet::from([PushField::RegionFirst]);
v.interface.push = crate::lower::push::place(Stage::Vertex, &fields);
let offset = match v.interface.push.fields.as_slice() {
[placed] => match placed.loc {
crate::pipeline::interface::PushLoc::Push { offset } => offset,
other => panic!("{other:?}"),
},
other => panic!("{other:?}"),
};
let linked = link(&[&v, &f], &regions, &p).unwrap_or_else(|e| panic!("{e}"));
assert!(linked.geometry.is_none());
let fan = linked.graphics.and_then(|g| g.region_fan_out);
assert_eq!(
fan,
Some(crate::pipeline::graphics::FanOutState {
mode: RegionFanOut::RegionCopies,
copies: 0,
push_offset: offset,
})
);
}
@@ -878,6 +878,28 @@ pub struct LoweringInputs {
/// function that writes none. Any other stage compiles as without it.
#[cfg_attr(feature = "serde", serde(default))]
pub region_viewports: bool,
/// The function's render pipeline draws a rasterization-rate-mapped pass's regions through
/// the target's viewport, each region's copy of each vertex computed in the vertex function
/// (`VariantKey::region_fan_out`, `RegionFanOut::RegionCopies`), as a fanned-out copy's is:
/// region `first + DrawIndex` of the region table (`SyntheticBinding::RateMapRegions`,
/// `bind::fan_out`), `first` its recording's `PushField::RegionFirst` and `DrawIndex` its
/// draw's among a `vkCmdDrawMultiEXT`'s (0 for any other draw). The vertex function stores the
/// position the region's line moves (`pipeline::link::fan_out::region_copy`, the emitter the
/// fan-out stage shares, its operations `NoContraction`), four clip distances past its own
/// that keep the region's pixels, and `DrawIndex` as `ViewportIndex`: every viewport the
/// runtime sets is the target's and each scissor its region's. It needs the device to store
/// `ViewportIndex` from a vertex function (`shaderOutputViewportIndex`), read `DrawIndex`
/// (`shaderDrawParameters`) and take several viewports (`multiViewport`), and to write clip
/// distances (`shaderClipDistance`), four more within `maxClipDistances` and
/// `maxCombinedClipAndCullDistances`: `Unsupported(RasterizationRateMap)` names them otherwise.
/// A function that writes its own `[[viewport_array_index]]` or
/// `[[render_target_array_index]]`, one compiled under `amplification_draws`,
/// `viewport_compensation`, `replay_bindings` or `merged_draws`, a post-tessellation vertex
/// function and one that returns no outputs are `NotImplemented(RasterizationRateMap)` under
/// it: the runtime draws those region by region through each region's viewport. Any other stage
/// compiles as without it.
#[cfg_attr(feature = "serde", serde(default))]
pub region_copies: bool,
}
/// One group of a render pipeline's color attachments (`LoweringInputs::color_group`,
+5
View File
@@ -1015,6 +1015,11 @@ pub enum PushField {
/// window holds it (at most 44 bytes before it there: `SnapshotPhase` is a fragment
/// function's): the draw of each chunk writes it alone, between its draws.
TessellationChunk,
/// The first region a recording of a rate-mapped pass's regions draws, in the region table's
/// order (`u32`; `RegionFanOut::RegionCopies`, `LoweringInputs::region_copies`): its vertex
/// function draws region `first + DrawIndex`. Placed with the amplification fields, so the
/// vertex window holds it, as a recording writes it before its draws.
RegionFirst,
/// Region base and grid of a multi-region dispatch.
DispatchRegion,
/// Device address (`u64`) of the region record a device-replay variant's dispatch reads its
@@ -896,14 +896,16 @@ impl ModuleBuilder {
/// Decorate builtin output `g` `Invariant`: SPIR-V's "expressions computing its value be
/// computed invariantly with respect to other shaders computing the same expressions". Only
/// the `Position` output (Metal's `[[invariant]]` position) and a fragment's per-fragment
/// outputs, `FragDepth`, `SampleMask` and `FragStencilRefEXT` (the variants of one render
/// pipeline's color groups, `LoweringInputs::color_group`), can be invariant.
/// the `Position` output (Metal's `[[invariant]]` position), the `ClipDistance` output (a
/// rate-mapped pass's copies of its triangles, `pipeline::link::fan_out`) and a fragment's
/// per-fragment outputs, `FragDepth`, `SampleMask` and `FragStencilRefEXT` (the variants of
/// one render pipeline's color groups, `LoweringInputs::color_group`), can be invariant.
pub fn invariant(&mut self, g: GlobalId) -> BResult<()> {
use crate::spv::BuiltIn as B;
match self.global(g)?.kind {
GlobalKind::BuiltIn {
builtin: B::Position | B::FragDepth | B::SampleMask | B::FragStencilRefEXT,
builtin:
B::Position | B::ClipDistance | B::FragDepth | B::SampleMask | B::FragStencilRefEXT,
dir: IoDir::Output,
} => {
self.invariant.insert(g);
@@ -1028,16 +1028,21 @@ fn a_push_block_that_is_not_std430_uses_scalar_layout() {
assert_eq!(m.push_members().len(), 2);
}
/// Only the `Position` output (Metal `[[invariant]]`) and a fragment's per-fragment outputs (the
/// variants of a render pipeline's color groups) can be decorated `Invariant`.
/// Only the `Position` output (Metal `[[invariant]]`), the `ClipDistance` output (a rate-mapped
/// pass's copies) and a fragment's per-fragment outputs (the variants of a render pipeline's
/// color groups) can be decorated `Invariant`.
#[test]
fn only_the_position_and_per_fragment_outputs_are_invariant() {
fn only_the_position_clip_distances_and_per_fragment_outputs_are_invariant() {
let mut t = T::new();
let f = t.f32();
let v4 = t.vec(f, 4);
let pos =
t.b.builtin(BuiltIn::Position, IoDir::Output, v4)
.expect("position");
let clips = t.array(f, 4, None);
let clips =
t.b.builtin(BuiltIn::ClipDistance, IoDir::Output, clips)
.expect("clip distances");
let depth =
t.b.builtin(BuiltIn::FragDepth, IoDir::Output, f)
.expect("depth");
@@ -1048,6 +1053,7 @@ fn only_the_position_and_per_fragment_outputs_are_invariant() {
t.b.io(key("color"), IoDir::Output, v4, IoDecor::default())
.expect("varying");
assert_eq!(t.b.invariant(pos), Ok(()));
assert_eq!(t.b.invariant(clips), Ok(()));
assert_eq!(t.b.invariant(depth), Ok(()));
for g in [size, color] {
assert_eq!(
+2 -2
View File
@@ -206,8 +206,8 @@ pub enum GlobalRule {
/// implicitly laid-out variables (`SPV_KHR_workgroup_memory_explicit_layout` allows all or
/// none).
MixedWorkgroupLayout,
/// `Invariant` on a variable other than the `Position`, `FragDepth`, `SampleMask` and
/// `FragStencilRefEXT` outputs.
/// `Invariant` on a variable other than the `Position`, `ClipDistance`, `FragDepth`,
/// `SampleMask` and `FragStencilRefEXT` outputs.
InvariantTarget,
/// `PerPrimitiveEXT` on a variable other than a user varying.
PerPrimitiveTarget,
@@ -6,7 +6,10 @@
//! variant, which the base pipeline does not draw (`BindError::NeedsVariant`); compiled, its
//! modules pass L3, its graphics state states the fan-out, it states no synthesized-geometry
//! fact, and its plan settles on itself. A draw binds the region table; a probe binds its flags
//! too and pushes its flag's index to the geometry stage.
//! too and pushes its flag's index to the geometry stage. A region-copy variant draws no geometry
//! stage: its vertex function draws its region's copy, sixteen more `NoContraction`
//! operations than the plain one's and its clip distances `Invariant` too, binds the region
//! table and pushes its first region to the vertex stage.
//! - Drawn amplified, the plan keeps the plain variant, and draws the regions one at a time.
//!
//! `llvm-as` assembles the fixtures; a missing tool skips visibly. No GPU is used.
@@ -85,10 +88,15 @@ fn a_fanned_out_draw_runs_its_variant() {
let base = dev
.compile_render_pipeline(&d, &budget)
.unwrap_or_else(|e| panic!("{stem}: {e}"));
let plain = (base.stages.iter())
.find(|m| m.stage == vk::ShaderStage::VERTEX)
.map(|m| decorated(&m.spirv))
.expect("a vertex module");
for mode in [
RegionFanOut::Draw,
RegionFanOut::Probe,
RegionFanOut::DrawFew,
RegionFanOut::RegionCopies,
] {
let state = BindState {
region_fan_out: Some((mode, 5)),
@@ -119,7 +127,11 @@ fn a_fanned_out_draw_runs_its_variant() {
let geometry = (p.stages.iter())
.filter(|m| m.stage == vk::ShaderStage::GEOMETRY)
.count();
assert_eq!(geometry, 3, "{stem} {mode:?}");
let stages = match mode {
RegionFanOut::RegionCopies => 0,
_ => 3,
};
assert_eq!(geometry, stages, "{stem} {mode:?}");
let fan = p.graphics.region_fan_out.expect("the fan-out state");
assert_eq!(fan.mode, mode, "{stem}");
assert!(
@@ -146,15 +158,63 @@ fn a_fanned_out_draw_runs_its_variant() {
.map(|w| (w.offset, w.bytes.clone()))
.collect();
match mode {
RegionFanOut::Draw | RegionFanOut::DrawFew => assert!(pushed.is_empty(), "{stem}"),
RegionFanOut::Probe => {
assert_eq!(pushed, [(fan.push_offset, 5u32.to_le_bytes().to_vec())])
}
_ => assert!(pushed.is_empty(), "{stem}"),
}
if mode != RegionFanOut::RegionCopies {
continue;
}
// Its first region, in the vertex stage's push range.
let at = fan.push_offset;
let first = (commands.push_constants.iter())
.filter(|w| w.stages.contains(vk::ShaderStageFlags::VERTEX))
.find(|w| w.offset <= at && at + 4 <= w.offset + w.bytes.len() as u32)
.map(|w| w.bytes[(at - w.offset) as usize..][..4].to_vec());
assert_eq!(first, Some(5u32.to_le_bytes().to_vec()), "{stem}");
let vertex = (p.stages.iter())
.find(|m| m.stage == vk::ShaderStage::VERTEX)
.map(|m| decorated(&m.spirv))
.expect("a vertex module");
// Of each axis's coordinate and its two clip distances, five products and three sums.
assert_eq!(vertex[0], plain[0] + 2 * 8, "{stem}");
assert_eq!(vertex[1], plain[1] + 1, "{stem}");
// It stores its draw's index as the viewport's, its region's scissor's.
assert_eq!(vertex[2], plain[2] + 1, "{stem}");
}
}
}
/// How many `NoContraction`, `Invariant` and `BuiltIn ViewportIndex` decorations module `words`
/// holds.
fn decorated(words: &[u32]) -> [usize; 3] {
use crate::spv::{BuiltIn, Decoration};
let mut n = [0; 3];
let mut i = 5;
while let Some(&w) = words.get(i) {
let len = (w >> 16) as usize;
if w & 0xFFFF == crate::spv::Op::Decorate as u32 {
match words.get(i + 2).copied() {
Some(d) if d == Decoration::NoContraction as u32 => n[0] += 1,
Some(d) if d == Decoration::Invariant as u32 => n[1] += 1,
Some(d)
if d == Decoration::BuiltIn as u32
&& words.get(i + 3).copied() == Some(BuiltIn::ViewportIndex as u32) =>
{
n[2] += 1
}
_ => {}
}
}
if len == 0 {
break;
}
i += len;
}
n
}
/// Drawn amplified, a plan whose shape fans triangles out keeps the plain variant.
#[test]
fn an_amplified_draw_keeps_the_plain_variant() {
@@ -3315,6 +3315,8 @@ field metal2vulkan-runtime::WorkCounts.rate_map_pieces_timed pub rate_map_pieces
field metal2vulkan-runtime::WorkCounts.rate_map_probe_gpu_nanos pub rate_map_probe_gpu_nanos: u64
field metal2vulkan-runtime::WorkCounts.rate_map_probe_wait_nanos pub rate_map_probe_wait_nanos: u64
field metal2vulkan-runtime::WorkCounts.rate_map_probes pub rate_map_probes: u64
field metal2vulkan-runtime::WorkCounts.rate_map_region_copy_draws pub rate_map_region_copy_draws: u64
field metal2vulkan-runtime::WorkCounts.rate_map_region_copy_recordings pub rate_map_region_copy_recordings: u64
field metal2vulkan-runtime::WorkCounts.rate_map_region_runs pub rate_map_region_runs: u64
field metal2vulkan-runtime::WorkCounts.reading_draws_by_coverage pub reading_draws_by_coverage: u64
field metal2vulkan-runtime::WorkCounts.reading_draws_in_place pub reading_draws_in_place: u64
@@ -4939,6 +4941,7 @@ field metal2vulkan::pipeline::LoweringInputs.private_list pub private_list: bool
field metal2vulkan::pipeline::LoweringInputs.psb_slots pub psb_slots: BTreeSet<SlotRef>
field metal2vulkan::pipeline::LoweringInputs.quad_primitive_ids pub quad_primitive_ids: bool
field metal2vulkan::pipeline::LoweringInputs.read_only_tests pub read_only_tests: bool
field metal2vulkan::pipeline::LoweringInputs.region_copies pub region_copies: bool
field metal2vulkan::pipeline::LoweringInputs.region_viewports pub region_viewports: bool
field metal2vulkan::pipeline::LoweringInputs.render_target_array_index_varying pub render_target_array_index_varying: bool
field metal2vulkan::pipeline::LoweringInputs.replay_bindings pub replay_bindings: bool
@@ -5349,6 +5352,7 @@ fn metal2vulkan::bind::extended_range_canonical pub fn extended_range_canonical(
fn metal2vulkan::bind::extended_shadow_module pub fn extended_shadow_module(device: &Device, form: ExtendedRange) -> Result<ExtendedShadowModule, Error>
fn metal2vulkan::bind::fan_out::clip_entry pub const fn clip_entry(axis: u32, k: u32) -> u32
fn metal2vulkan::bind::fan_out::line_entry pub const fn line_entry(axis: u32, k: u32) -> u32
fn metal2vulkan::bind::fan_out::scissors pub fn scissors(regions: &[([f32; 4], [u32; 4])]) -> Option<Vec<[u32; 4]>>
fn metal2vulkan::bind::fan_out::table pub fn table(target: [f32; 4], regions: &[([f32; 4], [u32; 4])]) -> Option<Vec<u8>>
fn metal2vulkan::bind::flat_dispatch_module pub fn flat_dispatch_module(device: &Device) -> Result<FlatDispatchModule, Error>
fn metal2vulkan::bind::fold_object_grid pub fn fold_object_grid(groups: [u32; 3], threads: [u32; 3], task: MeshGridLimits, direct: bool) -> Option<ObjectFold>
@@ -14848,6 +14852,7 @@ variant metal2vulkan::pipeline::PushField::MergedDrawAddress MergedDrawAddress
variant metal2vulkan::pipeline::PushField::PatchIndexBound PatchIndexBound
variant metal2vulkan::pipeline::PushField::PatchIndexOffset PatchIndexOffset
variant metal2vulkan::pipeline::PushField::PointGuard PointGuard
variant metal2vulkan::pipeline::PushField::RegionFirst RegionFirst
variant metal2vulkan::pipeline::PushField::RegionProbe RegionProbe
variant metal2vulkan::pipeline::PushField::RenderTargetArrayLength RenderTargetArrayLength
variant metal2vulkan::pipeline::PushField::ReplayRegionAddress ReplayRegionAddress
@@ -14889,6 +14894,7 @@ variant metal2vulkan::pipeline::RecordValue::ViewportIndex ViewportIndex
variant metal2vulkan::pipeline::RegionFanOut::Draw Draw
variant metal2vulkan::pipeline::RegionFanOut::DrawFew DrawFew
variant metal2vulkan::pipeline::RegionFanOut::Probe Probe
variant metal2vulkan::pipeline::RegionFanOut::RegionCopies RegionCopies
variant metal2vulkan::pipeline::ResourceKind::AccelerationStructure AccelerationStructure(AccelerationStructureLevel)
variant metal2vulkan::pipeline::ResourceKind::Buffer Buffer
variant metal2vulkan::pipeline::ResourceKind::CombinedTextureSampler CombinedTextureSampler(CombinedSampler)
Can't render this file because it is too large.
+1
View File
@@ -838,6 +838,7 @@ surface! {
const WIDEN_PIXELS;
fn clip_entry;
fn line_entry;
fn scissors;
fn table;
}
"bind::indirect_commands" => metal2vulkan::bind::indirect_commands {
+11 -1
View File
@@ -5878,7 +5878,17 @@ each item named states the rule in full.
and after them fanned out (`WorkCounts::rate_map_parted_draws`, the runs
`rate_map_region_runs`, their triangles `rate_map_parted_region_triangles` and of those the
ones the probe flagged `rate_map_flagged_triangles`); another flagged draw is drawn region by
region. The
region. On such a device every draw of the pass the fan-out's variant takes and does not fan
out (the encoder's own, those the probe flags or does not probe) is drawn region by region
through its region-copy variant where the device also enables `multiViewport`,
`shaderOutputViewportIndex` and `shaderDrawParameters`, whose vertex function puts each vertex
in its region by the instructions that put a fanned-out copy's, a region a recording or as many
as a direct draw's multi-draw takes, each through a viewport over the render area and its own
scissor (`WorkCounts::rate_map_region_copy_draws`, the recordings
`rate_map_region_copy_recordings`), so the pass's routes rasterize a vertex at one
position and a depth `Equal` test across them holds where both pipelines compute the position
alike; a draw the variant does not take is drawn through each region's viewport
(`docs/FAST-PATHS.md`, known gaps). The
probe costs the host step a submission it waits for before the pass, which runs each probed
draw's vertex function and geometry stage once and shades nothing (`WorkCounts::rate_map_probes`,
`rate_map_probe_gpu_nanos`, the host's wait `rate_map_probe_wait_nanos`); a fanned-out draw
+20 -3
View File
@@ -47,7 +47,7 @@ three consumer pipelines: A2X (`a2x-s4`, `a2x-s96`), Xgc14 (`xgc14-bgra8`) and X
| An attachment (not memoryless) that a pass loads `DontCare` and does not store, in a pass whose draws reach a tile, is cleared over the render area (`clear_reach.rs`) on a driver measured to run that clear no slower than its `DONT_CARE` load (`DriverFact::UnstoredClearNoSlower`: MoltenVK on the M3 Max, RADV on the Radeon 780M), and left `DONT_CARE` on every other driver; an aspect of separate depth and stencil textures likewise, each aspect apart, in the scratch image of the combined format the pass renders them through (`depth_stencil_scratch.rs`). Metal's draws read zero (a colour) or the pass's clear value (depth, stencil) of such an attachment wherever they read it, never its earlier texels (an M3 Max under macOS 27.0.1: an `RG16Float` second colour a framebuffer fetch reads and a `Stencil8` a stencil test reads, in passes split and whole; a separate `Depth32Float` and `Stencil8` read by a depth and a stencil test, each aspect so loaded alone or both; `runtime_lane::dont_care_unstored`); Vulkan's `DONT_CARE` load leaves the contents undefined. | `unstored_dont_care_loads = UnstoredDontCarePolicy::Driver` | `unstored_dont_care_loads = UnstoredDontCarePolicy::Cleared`: cleared on every device, by the pass's first render pass instance's load operation, or before the pass where that instance leaves the attachment out (separate depth and stencil textures: by the scratch image's load operation of the aspect); Metal's answer wherever a draw reads it | On a driver without the fact, the draws read what its `DONT_CARE` load leaves (lavapipe: the attachment's earlier texels). An image the runtime makes to stand for an attachment (the scratch image of separate depth and stencil textures, a stand-in, a backing: `Device::new_planned_texture`) starts at zero on such a driver, never as its memory lies, which may hold a released texture's texels: a clear as it is made. `DontCareUnstoredLoad` (`dont-care-unstored-load`), once per device; `runtime_lane::dont_care_unstored` (both values: Metal's answer under `Cleared` and on a driver with the fact, lavapipe's earlier texels under `Driver`; separate depth and stencil textures alike, but what lavapipe's `DONT_CARE` leaves in the scratch image is printed, not checked) | Measured, `CLEAR` against `DONT_CARE`, the GPU's span per pass, medians of 15 frames in each of two rounds, eight 3648x2038 passes a frame (a `BGRA8Unorm` colour loaded and stored, an `RG16Float` colour and a `Depth32Float_Stencil8` loaded by the form and stored `DontCare`, one draw over the whole target writing all three; a probe whose runtime still left such a load `DONT_CARE`, without the validation layer): lavapipe (Mesa 26.2.6, llvmpipe on LLVM 23.1.4) 10480 and 10744 µs against 7280 and 7259, 3.2 to 3.5 ms more, its clear a write of every texel; ANV (Mesa 26.2.6) on the Iris Xe (RPL-P) 1936 and 1936 µs against 1907 and 1151, slower in both rounds; RADV (Mesa 26.2.6) on the Radeon 780M 861 and 865 µs against 1147 and 988, faster; MoltenVK 1.4.2 on the M3 Max 218 and 218 µs against 224 and 217, apart by less than one form's two rounds; NVIDIA's 615.71.09 on the RTX 5080 Laptop GPU 74.4 and 74.6 µs against 71.2 and 71.4, 3.2 µs more. Memory: none |
| A linear sample of a two-plane YCbCr texture whose planes a function reads in place (`YCBCR8_420_2P`, `YCBCR10_420_2P` through a uniform texel buffer over their codes, on an integrated GPU or a CPU device; `lower::sampler::in_place`), through a sampler that addresses no border on either plane axis, with no texel offset placed by a parent's size, is Vulkan's Y′CbCr model of the codes, as the device's own conversion with a linear chroma filter computes it: the four luma codes around the point and the four chroma pairs around the same point of the chroma plane (Metal's midpoint siting) blended bilinearly, then the surface's range and matrix (Metal's coefficients) in `float`, each channel clamped into `[0, 1]`: eight fetches. A runtime sampler's word decides as the function runs. A nearest sample, a border mode, a parent-placed offset and a gather are Metal's under either value. | `ycbcr_in_place_reads = YCbCrInPlacePolicy::Model` | `ycbcr_in_place_reads = YCbCrInPlacePolicy::Exact`: every tap Metal's texel (its chroma weighted 9/3/3/1 and rounded to a code, the fixed-point conversion), and the sample Metal's sum of the four taps' steps on the grid `2048`: twenty fetches and four conversions | The model reconstructs each channel at the point where Metal converts four taps and sums them: within the `float` arithmetic's rounding of the model (checked against an `f64` model on the CPU interpreter, `engine_ycbcr_in_place`), it differs from Metal's by the chroma the taps reconstruct, by Metal's roundings to a code and to `1/2048`, and where a tap's channel leaves `[0, 1]`, which Metal clamps before it sums. `HalfSampleFilter` / `FloatSampleFilter` under the bound converted 4:2:0 format, announced `ycbcr-filter-not-exact` | Radeon 780M (RADV): a 3840 x 2160 `YCBCR10_420_2P` frame sampled linearly into a 3840 x 2160 `BGRA8Unorm` target, GPU time per frame (median of 60): 6.4-6.9 ms under the exact form (`runtime_lane::video_frames`) |
| A vertex buffer layout a draw fetches in fixed function, on a driver whose fixed-function vertex input takes an element's displacement modulo `2^32` (`RuntimeDriverDefect::VertexFetchWrapsPast4GiB`: lavapipe), where the draw's indices (`uint` indices, a per-vertex layout) or its indirect arguments (any layout but a constant one) state how far it fetches: the layout keeps the fixed-function fetch, so an element `2^32` bytes or more past the buffer's bind offset reads the bytes at its displacement's low 32 bits, where Metal reads zero past a buffer that ends before them (`render/vertex_reach.rs`). A layout whose reach the draw's own values bound (its last vertex without indices, `65535` plus its base vertex with `ushort` indices, its base instance plus its last instance over the step rate) is pulled where that reach passes `2^32`, under either value, and reads zero. Other drivers read zero (RADV on the 780M, MoltenVK 1.4.2: `runtime_lane::far_vertex_fetches`). | `vertex_reach = VertexReachPolicy::Bounded` | `vertex_reach = VertexReachPolicy::Exact`: such a layout is pulled too, wherever its stride and furthest attribute could reach past `2^32` from the largest index or argument (on lavapipe, every `uint`-indexed draw's per-vertex layout of a stride above 0, and every indirect draw's layout but a constant one), the plan's pulled-vertex-buffer variant (`WorkCounts::far_vertex_fetch_pulled_draws`) | Under `Bounded`, on lavapipe, an element of such a draw at or past `2^32` reads the wrapped bytes: the conformance case `vertex-fetch-past-4gib-small-buffer` replayed under the default policy differs in 8 elements (its two far `uint`-indexed draws at stride 4), and passes under `Exact`. `VertexFetchMayWrap` (`vertex-fetch-may-wrap`), once per device, for a draw left so; `runtime_lane::far_vertex_fetches` (both values) | Measured on lavapipe (Mesa 26.2.4, LLVM 23.1.1) on a Core Ultra 9 275HX shared with other jobs (`runtime_lane::far_vertex_fetches::far_reach_costs`): a state drawn without indices and then with `uint` indices makes one pipeline under `Bounded` and two under `Exact`, the pulled variant made at the first `uint`-indexed draw; a pass of one draw of 65,536 `uint`-indexed points, from the encoder's making to the wait's return, takes 2.3 to 2.8 times as long pulled (medians of 20 passes: 0.94 against 2.41 ms beside two builds, 3.5 to 4.8 against 9.7 to 12.0 ms at a load average of 59 on 24 threads). On every other driver neither value changes a draw |
| A draw of triangles in a rasterization-rate-mapped pass that a host step records (an execution whose records the GPU writes or whose range a buffer holds), filled, of one amplification, without a compensation or a band, whose pipeline chooses no slice or viewport and writes no memory from its vertex function, over a map whose layers are alike and whose plan is a grid of at most 128 columns and rows, on a device that enables `geometryShader`, `shaderClipDistance` and `vertexPipelineStoresAndAtomics`, is drawn once and fanned out to the regions its triangles touch (`rate_mapped_pass.rs`, **Fan-out**): its variant's geometry stage emits a copy of each triangle for each region it touches, at most the copies the device's `maxGeometryTotalOutputComponents` allows up to 16, through one viewport over the render area, four clip distances keeping each copy to its region's pixels, where Metal shades each region through its own viewport. A probe recorded before the pass, submitted and waited for, flags a draw a triangle of which crosses `w = 0` or touches more regions than the copies, with the first and the last such triangle: a flagged list of triangles of one instance whose pipeline reads no `[[primitive_id]]` and writes no memory is drawn in parts in its place, its runs of blocks of 64 triangles that hold a flagged one region by region (the probe sets each flagged triangle's block's bit, `bind::fan_out::BLOCK_TRIANGLES`), cut to the first and the last flagged triangle, runs fewer than 170 triangles apart joined (`rate_mapped_pass::RUN_GAP`, what a region draw costs beyond its vertices) and at most four a draw, the nearest joined first, and the triangles before, between and after them fanned out (`render/fan_out.rs`, **Parts**), and another flagged draw region by region; and marks a draw a triangle of which it does not flag touches more than four (`bind::fan_out::FEW_COPIES`): a draw it marks none of, and a flagged draw's parts fanned out, is drawn through the variant of four copies, whose geometry stage declares the output of fewer vertices, the three variants (the probe's, four copies and the most) begun at `commit`; it stops at a command's barrier and after a draw that writes memory. A copy's window coordinates are the region viewport's computed in the geometry stage, so a pixel centre within a rounding error of a triangle's edge may be covered by one route and not by the other | `rate_map_regions = RateMapRegionPolicy::FanOut` | `rate_map_regions = RateMapRegionPolicy::Exact`: every draw recorded once per region of the map's plan, each through its own viewport and scissor, its vertex function run once per region | No note of its own: the map's creation announces the pass as a near-equivalent (`rasterization-rate-map`). `WorkCounts::rate_map_probes`, `rate_map_flagged_draws` and `rate_map_fanned_draws` count the probes, the draws they flagged and the draws fanned out whole, `rate_map_fanned_few_draws` the fanned-out draws of four copies, `rate_map_parted_draws` the flagged draws drawn in parts, `rate_map_region_runs` their runs drawn region by region and `rate_map_parted_region_triangles` those runs' triangles; `WorkCounts::rate_map_probe_gpu_nanos` the probes' GPU time and `rate_map_probe_wait_nanos` the host's wait for them | Measured at the host step, 64 executed commands of 918,108 indices over a 3648 by 1734 screen's 2074 regions (`runtime_lane::rate_mapped_pieces`), each frame cold (its pipelines begun at `commit`) then warm, the command buffer's GPU time under `FanOut` against `Exact`: an Iris Xe's (Mesa 26.2.6) 48 ms cold and 40 ms warm against 510 ms and 498 ms; a Radeon 780M's (Mesa 26.2.6) 40 ms and 30 ms against 299 ms and 233 ms (`Exact`'s from an earlier run); an RTX 3090's (NVIDIA 620.70.06) 29 ms and 6.1 ms against 64 ms and 58 ms, its cold frame's step waiting for the fan-out's pipelines. Every draw of the lane's is of four copies; on the Radeon 780M, in one run, two frames of them took 29.7 ms and 30.8 ms warm, where the same draws through the most copies took 36.8 ms and 34.5 ms (40.2 ms and 43.9 ms cold against 61.9 ms and 62.7 ms). The probe's GPU time 1.3 ms, 0.5 ms and 1.5 ms. With one triangle of every 8192 over 48 tiles a side (`rate_mapped_pieces_host_step_wide`: 23 of the 64 draws flagged, 36 of their triangles flagged, 8983 triangles drawn region by region in 35 runs, where the flagged draws' spans from the first flagged triangle to the last hold 106,519), warm, in two runs each: an RTX 2080's (NVIDIA 620.70.06) 16.6 ms and 18.7 ms against 60.1 ms under `Exact`, where drawing the spans region by region whole took 28.7 ms and 27.9 ms; a Radeon 780M's (Mesa 26.2.6) 61.2 ms and 57.7 ms against 257 ms, where the spans took 115 ms and 90.5 ms. Unmeasured on the RTX 5080. Under `Exact` a draw's vertex work is its vertices times the regions its viewport reaches (`rate_mapped_pass::draw_work`), under `FanOut` its vertices once, its triangles' geometry stage, three vertices per copy (`rate_maLine truncated
| A draw of triangles in a rasterization-rate-mapped pass that a host step records (an execution whose records the GPU writes or whose range a buffer holds), filled, of one amplification, without a compensation or a band, whose pipeline chooses no slice or viewport and writes no memory from its vertex function, over a map whose layers are alike and whose plan is a grid of at most 128 columns and rows, on a device that enables `geometryShader`, `shaderClipDistance` and `vertexPipelineStoresAndAtomics`, is drawn once and fanned out to the regions its triangles touch (`rate_mapped_pass.rs`, **Fan-out**): its variant's geometry stage emits a copy of each triangle for each region it touches, at most the copies the device's `maxGeometryTotalOutputComponents` allows up to 16, through one viewport over the render area, four clip distances keeping each copy to its region's pixels, where Metal shades each region through its own viewport. A probe recorded before the pass, submitted and waited for, flags a draw a triangle of which crosses `w = 0` or touches more regions than the copies, with the first and the last such triangle: a flagged list of triangles of one instance whose pipeline reads no `[[primitive_id]]` and writes no memory is drawn in parts in its place, its runs of blocks of 64 triangles that hold a flagged one region by region (the probe sets each flagged triangle's block's bit, `bind::fan_out::BLOCK_TRIANGLES`), cut to the first and the last flagged triangle, runs fewer than 170 triangles apart joined (`rate_mapped_pass::RUN_GAP`, what a region draw costs beyond its vertices) and at most four a draw, the nearest joined first, and the triangles before, between and after them fanned out (`render/fan_out.rs`, **Parts**), and another flagged draw region by region; and marks a draw a triangle of which it does not flag touches more than four (`bind::fan_out::FEW_COPIES`): a draw it marks none of, and a flagged draw's parts fanned out, is drawn through the variant of four copies, whose geometry stage declares the output of fewer vertices, the three variants (the probe's, four copies and the most) begun at `commit`; it stops at a command's barrier and after a draw that writes memory. On such a device that also enables `multiViewport`, `shaderOutputViewportIndex` and `shaderDrawParameters`, every other draw of the pass the variant takes (the encoder's own, the commands `commit` records, those the probe does not probe or whose step does not probe, a flagged draw's runs and a flagged draw drawn whole) is drawn region by region through its region-copy variant (`render/fan_out.rs`, **Region-copy variant**): no geometry stage, its vertex function putting each vertex in its region by the instructions that put a fanned-out copy's (`pipeline::link::fan_out::region_copy`), decorated `NoContraction`, its `Position` and `ClipDistance` `Invariant` (no rounding mode is forced), a recording per region or per as many regions as a direct draw's multi-draw takes, each pushing its first region, the vertex function storing its draw's index as `ViewportIndex`, every viewport the recording sets the fan-out's over the render area and the scissor at a draw's index its region's (`bind::fan_out::scissors`; Vulkan's viewport transform is determined by the selected viewport's extent, centre and depth range, *Controlling the Viewport*), so every route of the pass puts a vertex in a region at one window position and a later pass's `Equal` depth test meets the depth another route stored. A copy's window coordinates are the region viewport's computed in the geometry stage, so a pixel centre within a rounding error of a triangle's edge may be covered under one policy and not the other | `rate_map_regions = RateMapRegionPolicy::FanOut` | `rate_map_regions = RateMapRegionPolicy::Exact`: every draw recorded once per region of the map's plan, each through its own viewport and scissor, its vertex function run once per region | No note of its own: the map's creation announces the pass as a near-equivalent (`rasterization-rate-map`). `WorkCounts::rate_map_probes`, `rate_map_flagged_draws` and `rate_map_fanned_draws` count the probes, the draws they flagged and the draws fanned out whole, `rate_map_fanned_few_draws` the fanned-out draws of four copies, `rate_map_parted_draws` the flagged draws drawn in parts, `rate_map_region_runs` their runs drawn region by region and `rate_map_parted_region_triangles` those runs' triangles; `rate_map_region_copy_draws` the draws drawn region by region through the region-copy variant and `rate_map_region_copy_recordings` their recordings; `WorkCounts::rate_map_probe_gpu_nanos` the probes' GPU time and `rate_map_probe_wait_nanos` the host's wait for them; `tests::rate_mapped_depth_equal` (an `Equal` pass over a prepass's depth, each by either route: 44,666 of 89,483 pixels failed it on lavapipe through the regions' own viewports beside the fan-out, none under `Exact` or through the region-copy variant) | Measured at tLine truncated
| A `Managed` buffer's range that `did_modify_range` names, on a device without unified memory (two copies: the runtime's own host copy, or the caller's pages through their import, `managed.rs`, `managed_copy.rs`), is copied into the GPU's copy by the GPU as the submission of the next command buffer committed that uses the buffer runs, from the host copy as it holds the range then: no copy on the CPU and no staging (pages no import of their own maps are staged by the CPU at the commit under either value, but those a guest RAM's chunk imports hold all of, which the GPU copies from those imports: `WorkCounts::managed_bytes_copied_in_from_ram`, `managed_bytes_staged_in`). Macs differ on a CPU write of the range after the commit, before the GPU runs the command buffer: an AMD Radeon Pro 5300M (two copies, macOS 26.7.1) read the bytes at the commit, an Intel UHD Graphics 630 (one copy) read the later write (steps A,B,B,A,B against A,B,B,B,B; `runtime_lane::device_copies`), so the cheaper answer is the default. | `managed_copy_in = ManagedCopyInPolicy::AtSubmission` | `managed_copy_in = ManagedCopyInPolicy::AtCommit`: the commit takes the range as the host copy holds it then, by a CPU copy into staging buffers of host-cached system memory, freed once the submission that copies them in completed (at most 256 MiB staged ahead); a write after the commit reaches no command buffer committed before it, the 5300M's answer | A CPU write after the commit, before the GPU runs the command buffer, may be read. No notice: both answers are a Mac's. `tests::managed_copy_device`'s `ranges_named_*` (the default: each round reads its own bytes or those written after its commit, never an earlier round's; `AtCommit`: its own alone) and `runtime_lane::device_copies`'s `a_did_modify_range_reaches_the_bytes_the_next_commit_finds` (step 4 reads either answer) and `exact_answers_take_a_did_modify_range_at_the_commit` (step 4 reads the bytes at the commit) | A CPU copy of each range at the commit into system memory, which the commit waits for. `tests::managed_copy_device::managed_copy_in_bench` (`MANAGED-COPY-IN`, medians of 40 commits of 32 MiB each, two rounds, over the runtime's own buffer and the caller's pages): RTX 3090 (an eGPU, NVIDIA 620.70.06) `AtSubmission` commit 0.034 to 0.045 ms and 17.3 to 17.7 ms to the completion, `AtCommit` 1.8 to 2.9 ms and 19.2 to 20.2 ms; RX 7900 XTX (RADV, Mesa 26.2.6) `AtSubmission` 0.012 to 0.036 ms and 5.1 to 5.5 ms, `AtCommit` 1.9 to 2.2 ms and 7.1 to 7.5 ms. Memory: the staged ranges until their submission completed, in buffers the device parks and takes again |
All at once: `DevicePolicy::exact_answers()` sets every switch above; each row states its own cost.
@@ -646,8 +646,25 @@ driver's. Each is open work.
- **Only the draws a host step records are fanned out to a rate-mapped pass's regions**
(`rate_mapped_pass.rs`, **Fan-out**). The encoder's own draws in such a pass, the executed
commands `commit` records from the CPU's records, a probe's flagged draws, and every draw after
a command's barrier or after a draw that writes memory are drawn once per region of the map: an
executed command's draws stay bounded by the pieces above, the encoder's own draws by nothing.
a command's barrier or after a draw that writes memory are drawn once per region of the map,
through their region-copy variant where the fan-out's variant takes the draw; an executed
command's draws stay bounded by the pieces above, the encoder's own draws by nothing.
- **A rate-mapped pass's draw the fan-out's variant does not take is rasterized through each
region's own viewport** (`rate_mapped_pass.rs`, **Fan-out**): points, lines, triangles in a
`Lines` fill mode, an amplified, compensated or banded draw, a pipeline that chooses its slice
or viewport or whose vertex function writes memory, a map whose layers differ, a plan of more
than 128 columns or rows, every draw where the device lacks `geometryShader`, `shaderClipDistance` or
`vertexPipelineStoresAndAtomics`, and every draw it does not fan out where it lacks
`multiViewport`, `shaderOutputViewportIndex` or `shaderDrawParameters`. Under `RateMapRegionPolicy::FanOut` such a draw's window
positions differ by rounding from those the pass's fanned-out draws and region-copy variants give
the same vertices, so a later pass that tests `Equal` the depth one stored can fail along a
triangle's edges where it draws the same vertices the other way. Between the fan-out's routes
the one position rests on the same `NoContraction` instructions run in different pipelines and
different stages (the region-copy variant's vertex function, the fan-out variant's geometry
stage): on those operations being correctly rounded (Vulkan's precision table) and on the
guest's position computation compiling alike in both pipelines, which Vulkan promises only
within one pipeline (its invariance appendix, rule 4).
- **A heap texture Metal keeps uncompressed lies in its driver's layout, not Metal's tiles, where
its image fits the heap's answer in the heap's memory** (`texture/heap.rs`,
+2 -2
View File
@@ -131,7 +131,7 @@ Columns:
| `Imageblocks` | An imageblock outside the forms implemented | devices without VkFeature::SampleRateShading; devices without a capability the site computes (`missing`); drivers with a defect; every device (not implemented) | `ours` | 10: `crates/metal2vulkan/src/lower/access/imageblock.rs (imageblocks)`, `crates/metal2vulkan/src/lower/access/mod.rs (select_param)` (+7) | `rare`: imageblocks (Apple GPU families) |
| `RayTracing` | | devices without a capability the site computes (`missing`); every device (no Vulkan mechanism); every device (not implemented) | `ours` | 12: `crates/metal2vulkan/src/bind/acceleration.rs (instance_record, 2 sites)`, `crates/metal2vulkan/src/lower/raytracing/mod.rs (instance_count)` (+5) | `rare`: ray tracing (out of scope by ruling) |
| `Tensors` | | every device (not implemented) | `ours` | 2: `crates/metal2vulkan-air/src/canon/matmul2d/synth.rs (refuse)`, `crates/metal2vulkan/src/lower/select.rs (route_air)` | `rare`: shader tensors |
| `RasterizationRateMap` | | devices without VkFeature::MultiViewport; devices without VkFeature::ShaderDrawParameters; devices without VkFeature::ShaderOutputViewportIndex; devices without VkLimit::MaxGeometryTotalOutputComponents; devices without a capability the site computes; devices without a capability the site computes (`vec![Capability::Feature(lacks)]`); every device (not implemented) | `ours` | 6: `crates/metal2vulkan/src/lower/stage_io/plan.rs (region_viewport, 2 sites)`, `crates/metal2vulkan/src/pipeline/link/geometry.rs (check_limits)` (+1) | `rare`: rasterization rate maps |
| `RasterizationRateMap` | | devices without VkFeature::MultiViewport; devices without VkFeature::ShaderDrawParameters; devices without VkFeature::ShaderOutputViewportIndex; devices without VkLimit::MaxGeometryTotalOutputComponents; devices without a capability the site computes; devices without a capability the site computes (`vec![Capability::Feature(lacks)]`); every device (not implemented) | `ours` | 10: `crates/metal2vulkan/src/lower/stage_io/plan.rs (region_copy, 3 sites)`, `crates/metal2vulkan/src/lower/stage_io/plan.rs (region_viewport, 2 sites)` (+3) | `rare`: rasterization rate maps |
| `GpuEncodedIndirectCommands` | | devices short of a Vulkan feature the site names; devices without buffer device addresses (`addressed_needs`); every device (no Vulkan mechanism); every device (not implemented) | `ours` | 20: `crates/metal2vulkan/src/bind/replay.rs (preprocess)`, `crates/metal2vulkan/src/bind/replay.rs (replay_preprocess_module)` (+13) | `rare`: indirect command buffers encoded by a kernel |
| `VulkanVersion` | The device's Vulkan version is below the 1.2 floor | devices without ApiVersion::V1_2 | `device` | 2: `crates/metal2vulkan/src/ash_interop/query.rs (query)`, `crates/metal2vulkan/src/device/derive.rs (with_deviations)` | `none`: a device below Vulkan 1.2 |
| `Constant` | A constants-block record LLVM defines that the typed model has no form for (a block address, a `select` and the other constant expressions of... | - | `-` | via a helper: 3: `crates/metal2vulkan-air/src/bitcode/constants.rs (record, 2 sites)`, `crates/metal2vulkan/src/error/mod.rs (from)` | `none`: LLVM constant forms AIR does not emit |
@@ -657,7 +657,7 @@ Each refusal's sites, with the function that builds it.
- `feature::Imageblocks`: `crates/metal2vulkan/src/lower/access/imageblock.rs (imageblocks)`; `crates/metal2vulkan/src/lower/access/mod.rs (select_param)`; `crates/metal2vulkan/src/lower/fragment/imageblock.rs (not_implemented)`; `crates/metal2vulkan/src/lower/fragment/imageblock.rs (plan_tests, 2 sites)`; `crates/metal2vulkan/src/lower/fragment/imageblock.rs (reach)`; `crates/metal2vulkan/src/lower/fragment/imageblock.rs (require)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select)`; `crates/metal2vulkan/src/lower/texture/slice.rs (imageblocks)`; `crates/metal2vulkan/src/pipeline/link/imageblock.rs (fragment_imageblock)`
- `feature::RayTracing`: `crates/metal2vulkan/src/bind/acceleration.rs (instance_record, 2 sites)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (instance_count)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (intersect, 5 sites)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (primitive_data_read)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (select_param)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (slot_of)`; `crates/metal2vulkan/src/lower/select.rs (route_air)`
- `feature::Tensors`: `crates/metal2vulkan-air/src/canon/matmul2d/synth.rs (refuse)`; `crates/metal2vulkan/src/lower/select.rs (route_air)`
- `feature::RasterizationRateMap`: `crates/metal2vulkan/src/lower/stage_io/plan.rs (region_viewport, 2 sites)`; `crates/metal2vulkan/src/pipeline/link/geometry.rs (check_limits)`; `crates/metal2vulkan/src/pipeline/link/geometry.rs (fan_plan, 3 sites)`
- `feature::RasterizationRateMap`: `crates/metal2vulkan/src/lower/stage_io/plan.rs (region_copy, 3 sites)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (region_viewport, 2 sites)`; `crates/metal2vulkan/src/pipeline/link.rs (region_first)`; `crates/metal2vulkan/src/pipeline/link/geometry.rs (check_limits)`; `crates/metal2vulkan/src/pipeline/link/geometry.rs (fan_plan, 3 sites)`
- `feature::GpuEncodedIndirectCommands`: `crates/metal2vulkan/src/bind/replay.rs (preprocess)`; `crates/metal2vulkan/src/bind/replay.rs (replay_preprocess_module)`; `crates/metal2vulkan/src/bind/replay/draws.rs (draw_replay_module)`; `crates/metal2vulkan/src/bind/replay/draws.rs (draw_replay_preprocess)`; `crates/metal2vulkan/src/bind/replay/flat.rs (flat_dispatch_module)`; `crates/metal2vulkan/src/bind/replay/merged.rs (draw_merge_module)`; `crates/metal2vulkan/src/lower/access/encode.rs (needs, 2 sites)`; `crates/metal2vulkan/src/lower/access/encode.rs (select_command)`; `crates/metal2vulkan/src/lower/access/mod.rs (plan_replay, 3 sites)`; `crates/metal2vulkan/src/lower/mesh/mod.rs (plan_partial_groups)`; `crates/metal2vulkan/src/lower/select.rs (finish, 2 sites)`; `crates/metal2vulkan/src/lower/simd/divergent.rs (barriers)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (merged)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (param)`; `crates/metal2vulkan/src/pipeline/compile.rs (analyze_one, 2 sites)`
- `feature::VulkanVersion`: `crates/metal2vulkan/src/ash_interop/query.rs (query)`; `crates/metal2vulkan/src/device/derive.rs (with_deviations)`
- `feature::Constant`: `crates/metal2vulkan-air/src/bitcode/constants.rs (record, 2 sites)`; `crates/metal2vulkan/src/error/mod.rs (from)`