Drop the normalized vertex attribute's exact division (vertex_normalized)

One work packet, landed as 9 commits (9c0bdbe0d2..41066d87d0 on archive/development-linear-2026-10-28), in order:

* Drop the normalized vertex attribute's exact division (vertex_normalized)

The owner's ruling of 2026-10-27: the GPU's native arithmetic is the contract, no exact
emulation. A normalized vertex attribute is now always the device's fixed-function UNORM or
SNORM conversion; the policy-forced pull that divided its codes in the shader goes with
DevicePolicy::vertex_normalized, VertexNormalizedPolicy, its profile field, its ledger row and
its tests. A format pulled for any other reason (a format the device cannot fetch, alignment,
limits, containment, the capture form) still decodes in the shader as before.

Verified: cargo clippy --workspace --all-targets --all-features -D warnings clean; nextest of
engine_vertex_variants, device::tests::profile, fast_paths, catalogue, degradation and
api_surface: 71 passed. api_signatures is re-blessed at the end of the lane.

* Keep the compact decoded twin only (decoded_texels)

The owner's ruling of 2026-10-27: no exact emulation. A carried ASTC LDR texture's decoded
twin now always holds 8-bit codes, and an EAC 11-bit texture's 16-bit normalized codes (its
values in floats only where the device does not take those codes' format, a capability
fallback). DevicePolicy::decoded_texels and DecodedTexelsPolicy go, with their ledger row,
their mentions in the degrade catalogue and the runtime's docs, the policy-keyed fingerprint
test, and the validation lanes' exact twins. decoded-texel-precision is announced as before.
bind::AstcTexels::Float stays: the conformance suite's cross-check decodes Metal's values with
it. RUNTIME_VERSION 1654.

Verified: clippy --workspace --all-targets --all-features -D warnings clean, plain and with
--cfg m2v_gpu; nextest of fast_paths, device profile, degradation and catalogue, image_plan's
decode bands, the conformance ASTC and ETC cases, api_surface: 112 passed.

* Take the device's texel conversion only (texel_conversion)

The owner's ruling of 2026-10-27: no exact emulation. A read, sample or gather with a float
or half result off Apple's GPUs is now always the device's conversion of the texel's codes,
recorded as DeviceTexelConversion or HalfTexelConversion. DevicePolicy::texel_conversion and
TexelConversionPolicy go, with Metal's conversion by the bound format's class:
lower::texture::float_texel (its routine, census entry and tests), the float_texel plan flags of
reads and samples, the slots' float_format and the heap's float class, and the field of
RuntimeFact::ExactFormsOverCompilerLimit that named it (encoded, so ARTIFACT_FORMAT_VERSION
456; SEMANTICS_VERSION 1873). The ledger row goes; DeviceTexelConversion is now documented in
docs/API.md section 9 alone (fast_paths classes it Elsewhere), and the conformance cases cite
the note's bound in place of the row. The half routine on Apple's GPUs is untouched.

Verified: clippy --workspace --all-targets --all-features -D warnings clean, plain and with
--cfg m2v_gpu; nextest of fast_paths, device profile, catalogue, degradation, the fit, mechanism,
codec, the snapshot variant, engine_handles, the extended-range heap tests, the texel-conversion
test (rewritten for the device's form alone), the conformance ETC, BC and border cases and the
runtime's fitted-variant notice: passed (one exact-conversion test deleted).

* Take the device's filter of a two-plane YCbCr texture only (ycbcr_filter)

The owner's ruling: promise the GPU's native arithmetic, no exact emulation.
YCbCrFilterPolicy and its Exact form go: no slot takes a YCbCr variant
(RuntimeFact::YCbCrTexture, VariantKey and LoweringInputs::ycbcr_textures,
ProfileFields::ycbcr_variant, Linear::exact_only and the binder's
ycbcr_variant are gone). A natively sampling device filters such a texture's
texels (device-sampling); on MoltenVK Metal's own sampler filters them,
noted where the bound format is two-plane YCbCr (ycbcr-filter-not-exact).
The planes read in place on a device whose memory is the host's are kept:
that is a capability path, Metal's filter exactly.

The FAST-PATHS row goes; HalfTexelConversion, which only that row named, is
classed Elsewhere (API.md's catalogue states it). The YCbCr tests keep the
default's selection and drop the variant's; the uniform-branch test runs at
the default policy; the validation lane's Exact draw test goes.

Verified: cargo clippy --workspace --all-targets --all-features -D warnings,
plain and with --cfg m2v_gpu, clean. nextest over fast_paths, device::tests,
bind::plan, compile::fit, compile::tests, engine_linear_half, catalogue,
degradation, api_surface, codec, cache: 372 passed, 5 failed. The five are
engine_linear_half tests of the emulated sampler on lavapipe and MoltenVK
under EXACT_SAMPLING (the_emulation_reaches_what_metal_measured,
the_linear_sums_run_one_by_a_branch_and_stay_calls,
swizzled_packed_texels_are_the_unswizzled_swizzled,
a_pipelines_texture_notes_follow_its_bound_format_and_sampler,
a_depth_comparison_through_a_filter_is_a_filtered_float_sample); they go with
the emulated sampler in the next step. api_signatures is re-blessed at the
end of the lane.

* Take the device's sampler only (sampling, unorm8_linear_filter)

The owner's ruling of 2026-10-27: promise the GPU's native arithmetic, no
exact emulation. Metal's sampler emulated by fetches (SamplingPolicy::Exact,
a pipeline per bound sampler state) and the device's 8-bit unorm filter at
Metal's footprint step (Unorm8LinearFilterPolicy) are gone with their
switches: every sample, gather and comparison goes to the device's sampler,
Metal's own on MoltenVK (VkProperty::MetalSampler) and the device's
elsewhere (VkProperty::DeviceSampling, PrecisionNote::DeviceSampling).

Deleted: lower/sampler/compared.rs, native.rs, linear/compare.rs,
linear/cube.rs, the nearest and level snaps, the cube face position and
fold (face::snapped, FaceWrap), the span and cube bicubic routines, the heap
depth class (FLAG_DEPTH_*, HANDLE_DEPTH_*, Lookup::Flagged's depth), the
normalized gather snap and the runtime sampler's anisotropic bias route.
Notes nothing records any more are deleted with their catalogue and codec
entries and the runtime's Degradation kinds: DeviceGatherFootprint,
CubeFaceReciprocal, DeviceDepthComparison, DeviceTexelDenormals,
DeviceUnorm8LinearFilter. The fit drops the sampling field of
ExactFormsOverCompilerLimit and makes every module-growing form native in
one reduction.

Kept as capability: bicubic, extended range, heap raw reads, YCbCr planes
read in place (its tests move to engine_ycbcr_in_place), constexpr pixel
samplers' snaps and fetches, the runtime pixel word's gather and footprint
cell, Metal's cube face at a tie, the anisotropic emulation without
samplerAnisotropy and for an unmeasured cube-gradient route, the
VkSampler level clamp on Metal's grid.

Validation and conformance follow: the lanes judge the device's filter
within two codes where it samples natively, the anisotropic lane runs with
samplerAnisotropy withheld, and the conformance cases drop their
device-texel-denormals declarations. docs/API.md, FAST-PATHS.md,
ARCHITECTURE.md, CONTRIBUTING.md and VALIDATION.md updated.

Verified so far: cargo check of the workspace, all targets and features,
plain and --cfg m2v_gpu; 1000 of 3664 translator lib tests passed before
the run was stopped for the rebase.

* Join the device-sampler deletions with development's half and write removals

The rebase onto development left two joins only a build shows:

- `packed_scales` and `PackedField::small` lost their last readers (the
  float texel conversion this branch deleted and the normalized write
  development deleted): both go.
- `engine_srgb_raw` takes `DevicePolicy::default()` where development's
  side named `EXACT_SAMPLING`, so it imports `DevicePolicy` again.

Also formats the conflict resolutions (`cargo fmt --all`).

Verified: `cargo check --workspace --all-targets --all-features` passes.

* Drop the sampler word's snap and level-rule fields with their last readers

With every sample the device's own, no function reads a runtime sampler's
nearest snap (`SamplerWord::NEAREST_BASE`, `NEAREST_SNAP`, `NEAREST_LEVEL`,
`LEVELED_SNAP`) or its level rule (`LEVEL_RULE`); only tests named them.
The constants go, with the word test of the base-level mask; the
`VkSampler` clamp on Metal's level grid (`clamps_on_grid`) stays, and its
docs no longer say the shader reads the rule.

The runtime-sampler tests of `engine_sampler` asked, off MoltenVK, for the
emulation's linear state, leveled snap and level rule: they now state the
device's sample on every committed profile (the pixel fields alone, gated;
`MetalSampler` on MoltenVK, `DeviceSampling` elsewhere; no level field).

Also matches `SnapKind::WordGather` as the unit variant it is (clippy).

Verified: clippy (all targets, all features, -D warnings) passes.

* Test the anisotropic, bias and position paths as the device's sampler runs them

The tests of these paths compiled under the exact sampling policy, which
is gone; under the default each now states what the translation does:

- Metal's anisotropic filter is emulated only without `samplerAnisotropy`
  (and on MoltenVK's unmeasured cube-gradient route), so the emulation's
  shape tests compile on committed profiles with the feature withheld,
  and their MoltenVK arms on the profile as described. An isotropic cube
  keeps the device's gradient sample except on the unmeasured route.
- A bias through a sampler without its own is the `Bias` operand on every
  profile (one test over MoltenVK, RADV, lavapipe and the floor); the
  compile-time and anisotropic axis-gradient tests take a constexpr
  sampler with its own bias, the only one that reaches them. The runtime
  slot's word-chosen axis gradients have no reader left: its test goes,
  with the helpers only it used.
- The position kernel writes three words a lane: its record stride is 12
  bytes, not 16, and the by-word gather test's lane floor matches its
  single pass.

Verified: `cargo check -p metal2vulkan --tests --all-features` clean; the
tests run after the rebase onto development.

* Rewrite the sampling tests and notes for the device's sampler

The sampling, texel-conversion and YCbCr-filter emulations are gone, so
the tests that pinned them now pin the device's answer, and the note
docs that described them describe what the module records today.

Tests: the sampler-unk, anisotropic cube, depth-range, bicubic,
dynamic-offset, heap half-texel, shared-switch, sRGB raw view,
swizzled packed and texture-interpreter families. Deleted the tests of
the emulated linear filter over raw sRGB codes (constexpr and runtime),
the runtime sampler's one-texel raw sample and its switch, the shader's
linear depth comparison, the bicubic small-level comparison against the
linear emulation and the depth read's class conversion; the shared
switch keeps the bicubic emulation alone. A NaN texel's half read only
needs to read a NaN under the default policy.

Docs: HalfSampleFilter, FloatSampleFilter, SrgbTexelDecode,
AnisotropicFilter, DeviceAnisotropicFilter, ViewBaseTexelOffset and
HalfTexelConversion in artifact.rs, RuntimeFact::TexelFormat, the heap
class flag, texel_format_spec and a few comments that still named the
emulated linear filter, snapped gathers or the shader's comparisons.

Verified: plain clippy over the workspace with all targets and
features; the touched families under nextest (see the next commits for
the full runs).
This commit is contained in:
Anees Iqbal committed 2026-10-28 17:24:20 +02:00
1 parent 79166a74b1
commit 78ed264c90
142 files changed
+2894 -27096

No files matched your search

+1 -3
View File
@@ -107,9 +107,7 @@ Set `CARGO_INCREMENTAL=0` for a build that won't be edited and rebuilt.
`src/tests/golden_hashes.rs` pins a hash of the final SPIR-V (or the refusal class) of every public
fixture entry point on every committed profile, in `crates/metal2vulkan/tests/golden_hashes.tsv`,
and of every fixture that samples, gathers or computes a level of detail under every exact form
(Metal's sampler emulated and `DevicePolicy::exact_answers`), in
`crates/metal2vulkan/tests/golden_hashes_exact.tsv`: the default policy samples natively, so only
that table holds the sampler's emulation.
(`DevicePolicy::exact_answers`), in `crates/metal2vulkan/tests/golden_hashes_exact.tsv`.
`cache::SEMANTICS_VERSION` is part of every cache key, so a change that moves a cell while its
fixture and profile are unchanged must bump `SEMANTICS_VERSION`
(`crates/metal2vulkan/src/cache/mod.rs`) in the same change. New, removed or edited fixtures and
@@ -228,7 +228,6 @@ impl Drop for Span {
fn options(notices: &Notices, directory: &str, memo: bool) -> DeviceOptions {
let mut options = DeviceOptions::default();
options.policy = options.policy.exact_answers();
options.policy.sampling = metal2vulkan::device::SamplingPolicy::Exact;
options.announce_each = Degradation::ALL.iter().copied().collect();
options.shader_cache = ShaderCacheOptions::in_directory(std::path::Path::new(directory));
if !memo {
@@ -204,7 +204,6 @@ impl Drop for Span {
fn options(notices: &Notices, directory: &str) -> DeviceOptions {
let mut options = DeviceOptions::default();
options.policy = options.policy.exact_answers();
options.policy.sampling = metal2vulkan::device::SamplingPolicy::Exact;
options.announce_each = Degradation::ALL.iter().copied().collect();
options.shader_cache = ShaderCacheOptions::in_directory(std::path::Path::new(directory));
options.messages = Some(notices.sink());
@@ -320,7 +320,6 @@ impl Drop for Span {
fn options(notices: &Notices, directory: &str, memo: bool) -> DeviceOptions {
let mut options = DeviceOptions::default();
options.policy = options.policy.exact_answers();
options.policy.sampling = metal2vulkan::device::SamplingPolicy::Exact;
options.announce_each = Degradation::ALL.iter().copied().collect();
options.shader_cache = ShaderCacheOptions::in_directory(std::path::Path::new(directory));
if !memo {
@@ -159,7 +159,6 @@ fn options(notices: &Notices, directory: &str, exact: bool) -> DeviceOptions {
let mut options = DeviceOptions::default();
if exact {
options.policy = options.policy.exact_answers();
options.policy.sampling = metal2vulkan::device::SamplingPolicy::Exact;
}
options.shader_cache = ShaderCacheOptions::in_directory(std::path::Path::new(directory));
options.messages = Some(notices.sink());
@@ -535,8 +535,8 @@ impl Case for ArgumentEncoderCase {
/// sampled component is exactly 0.0 or 1.0 wherever the sampling happens, and a filter, a
/// denormal or a decode a device does its own way cannot move a word of that.
///
/// The three codes were measured, not guessed: Apple Metal announces none of them for this
/// work and llvmpipe announces all three, so a run on either venue alone would have left the
/// The two codes were measured, not guessed: Apple Metal announces neither for this work and
/// llvmpipe announces both, so a run on either venue alone would have left the
/// other's set undeclared. Only the two cases that dispatch declare them; the three that
/// encode and read back never sample, so a declaration there would never fire.
fn allowances(&self) -> Vec<Allowance> {
@@ -554,13 +554,9 @@ impl Case for ArgumentEncoderCase {
let mut named = vec![crate::replay::shared_memory_notice()];
if self.dispatches {
named.extend(
[
Degradation::DeviceTexelDenormals,
Degradation::FloatSampleFilter,
Degradation::SrgbTexelDecode,
]
.into_iter()
.map(|notice| crate::replay::notice_allowance(notice.code())),
[Degradation::FloatSampleFilter, Degradation::SrgbTexelDecode]
.into_iter()
.map(|notice| crate::replay::notice_allowance(notice.code())),
);
}
named
@@ -81,14 +81,12 @@
//! second-twin view and the refusals are facts about our own objects and our own typed errors
//! rather than about Metal's texels.
//!
//! **Tolerances.** Only a linear (`_LDR`) format has one. Under the default
//! `DecodedTexelsPolicy::Compact` its twin holds each channel as the 8-bit code nearest Metal's
//! 12-bit value, which `docs/FAST-PATHS.md` bounds at **1/510**, and the runtime announces
//! `decoded-texel-precision` where such a texture is made. That is the ledger's own number, not a
//! round one. The fourteen sRGB forms hold Metal's own 8-bit codes, which their slots decode through
//! Metal's table, so they are exact under either value and name **no tolerance at all**; and neither
//! does any format under `DecodedTexelsPolicy::Exact`, where the twin holds Metal's values as
//! `float`s. An `_HDR` format names none under any policy, having no twin.
//! **Tolerances.** Only a linear (`_LDR`) format has one. Its twin holds each channel as the 8-bit
//! code nearest Metal's 12-bit value, which the runtime announces as `decoded-texel-precision`
//! where such a texture is made, and whose catalogue entry (docs/API.md) bounds it at **1/510**.
//! That is the notice's own number, not a round one. The fourteen sRGB forms hold Metal's own 8-bit
//! codes, which their slots decode through Metal's table, so they are exact and name **no tolerance
//! at all**. An `_HDR` format names none, having no twin.
//!
//! Nothing here can fault a GPU: one compute pass a read, one read-only texture, one buffer, one
//! thread a texel inside the texture, no loop and no sampling.
@@ -124,10 +122,10 @@ const TEXEL_BYTES: usize = 16;
/// texture of its own, so a diff names which blocks moved.
const ROUNDS: [&str; 2] = ["zero-blocks", "seeded-blocks"];
/// The most a compact linear channel may be off Metal's value, as `docs/FAST-PATHS.md` states it
/// for `decoded_texels = DecodedTexelsPolicy::Compact`: the 8-bit code nearest Metal's 12-bit
/// value is at most half an 8-bit step away, which is 1/510. It is the ledger's number, so a run
/// that exceeds it fails rather than being re-fitted to whatever a device answers.
/// The most a compact linear channel may be off Metal's value, as the `decoded-texel-precision`
/// notice states it (docs/API.md): the 8-bit code nearest Metal's 12-bit value is at most half an
/// 8-bit step away, which is 1/510. It is the notice's number, so a run that exceeds it fails
/// rather than being re-fitted to whatever a device answers.
const LEDGERS_COMPACT_BOUND: f64 = 1.0 / 510.0;
/// An LDR void-extent block of red, green, blue and alpha `0x4000`, `0x8000`, `0xc000` and
@@ -519,13 +517,11 @@ impl Case for AstcTextures {
false => Vec::new(),
};
// An sRGB form's twin holds Metal's own 8-bit codes, which its slots decode through Metal's
// table, so its texels compare exactly under either policy and it names nothing further. A
// linear format's compact twin holds the 8-bit code nearest Metal's 12-bit value, which the
// runtime announces as `decoded-texel-precision` and `docs/FAST-PATHS.md` bounds at 1/510.
// The bound here is the ledger's number, so a run that exceeds it is the ledger's claim
// failing. Under `DecodedTexelsPolicy::Exact` the twin holds Metal's values as `float`s,
// the notice does not fire, the justification does not hold, and every texel is compared
// exactly.
// table, so its texels compare exactly and it names nothing further. A linear format's
// compact twin holds the 8-bit code nearest Metal's 12-bit value, which the runtime
// announces as `decoded-texel-precision`, whose catalogue entry bounds it at 1/510. The
// bound here is the notice's number, so a run that exceeds it is the notice's claim
// failing.
if let Some(bound) = self.compact_bound() {
all.push(crate::replay::notice_allowance(
Degradation::DecodedTexelPrecision.code(),
@@ -769,12 +765,12 @@ mod tests {
}
}
/// Only the linear formats name a tolerance, and each names the bound `docs/FAST-PATHS.md`
/// states.
/// Only the linear formats name a tolerance, and each names the bound the
/// `decoded-texel-precision` notice states.
///
/// This is the ruling that a notice declaration is not a tolerance, held as a test: the
/// `carried-decoded-twin` declaration is on every case and loosens no value, while the one
/// allowance that loosens a texel is named only where the ledger says a texel moves.
/// allowance that loosens a texel is named only where the notice says a texel moves.
#[test]
fn only_the_linear_formats_loosen_a_texel() {
let mut loosened = 0;
@@ -52,8 +52,8 @@ use metal2vulkan_runtime::Degradation;
/// The fixture the case runs, whose entry point is its own name.
const FIXTURE: &str = "a2_clamp_to_zero";
/// The bound `docs/FAST-PATHS.md` states for `texel_conversion = TexelConversionPolicy::Device`,
/// one `f32` ulp for 8- and 16-bit codes, as these sites hold it: a word of the float's bits, where
/// The bound `PrecisionNote::DeviceTexelConversion` states (`device-texel-conversion`), one `f32`
/// ulp for 8- and 16-bit codes, as these sites hold it: a word of the float's bits, where
/// one ulp of a positive finite float is a difference of one in the word.
const LEDGERS_TEXEL_CONVERSION_ULPS_AS_WORDS: f64 = 1.0;
@@ -305,14 +305,15 @@ impl Case for BorderSwizzles {
// notices differs, and the two notice allowances cover that site.
//
// The sampled words themselves may differ too. These samplers filter nearest, so the
// ledger's linear-filter row is not what bounds them: the bound is the one
// `docs/FAST-PATHS.md` states for `texel_conversion = TexelConversionPolicy::Device`, one
// `f32` ulp for 8- and 16-bit codes, which is what every format here holds. The words are
// recorded as the `u32` bit patterns of those floats, so one ulp is a difference of one in
// the word -- `every_recorded_word_is_a_positive_finite_float` pins the range that makes
// the two the same thing. The bound is the ledger's number: a run that exceeds it is the
// ledger's claim failing, which is what this allowance exists to catch. Under the exact
// policy neither notice fires, no justification holds, and every word is compared exactly.
// linear filter's bound is not what bounds them: the bound is the one
// `device-texel-conversion` states, one `f32` ulp for 8- and 16-bit codes, which is what
// every format here holds. The words are recorded as the `u32` bit patterns of those
// floats, so one ulp is a difference of one in the word --
// `every_recorded_word_is_a_positive_finite_float` pins the range that makes the two the
// same thing. The bound is the note's number: a run that exceeds it is the note's claim
// failing, which is what this allowance exists to catch. On a device whose sampler is
// Metal's neither notice fires, no justification holds, and every word is compared
// exactly.
// Every row reads its answer back through a `Shared` buffer, so on a device without
// unified memory the runtime announces `shared-in-system-memory`
// (`crate::replay::shared_memory_notice` holds the whole reason). It declares the
@@ -677,8 +678,8 @@ mod tests {
///
/// That range is what makes this case's bounded allowance mean what it says. The words are
/// recorded as `u32`, so the allowance bounds `|a - b|` on the words, and over this range a
/// difference of one in the word is exactly one `f32` ulp -- the bound `docs/FAST-PATHS.md`
/// states for the device's texel conversion. Outside it (a negative value, an infinity, a NaN)
/// difference of one in the word is exactly one `f32` ulp -- the bound
/// `device-texel-conversion` states for the device's texel conversion. Outside it (a negative value, an infinity, a NaN)
/// the two would stop being the same thing, so this test fails rather than letting the
/// allowance quietly mean something else.
///
@@ -65,9 +65,9 @@ const TEXEL_BYTES: usize = 16;
/// The textures read per format, as the lane reads them.
const ROUNDS: u64 = 4;
/// The bound `docs/FAST-PATHS.md` states for `texel_conversion = TexelConversionPolicy::Device`:
/// one `f32` ulp for 8- and 16-bit codes. It is the ledger's number, copied here so a run that
/// exceeds it fails rather than being re-fitted to whatever a device answers.
/// The bound `PrecisionNote::DeviceTexelConversion` states (`device-texel-conversion`): one `f32`
/// ulp for 8- and 16-bit codes. It is the note's number, copied here so a run that exceeds it
/// fails rather than being re-fitted to whatever a device answers.
const LEDGERS_TEXEL_CONVERSION_ULPS: u32 = 1;
/// How Metal decodes a format's block.
@@ -283,14 +283,13 @@ impl Case for CompressedDecode {
// and the allowance fails the case if the notice did not fire. `compressed-texel-decode`
// is deliberately absent — the lane asserts no BC1 to BC5 texture announces it, so a run
// that does is a divergence to report rather than one to excuse.
// Under the default policy a texel's `float` value is the device's conversion of the
// twin's 8-bit codes, not Metal's exact one, which the runtime announces as
// `device-texel-conversion`. `docs/FAST-PATHS.md`'s row for
// `texel_conversion = TexelConversionPolicy::Device` bounds that at one `f32` ulp for 8-
// and 16-bit codes, so the bound here is the ledger's number and not a measurement of
// this chip: a run that exceeds one ulp is the ledger's claim failing, which is what this
// allowance exists to catch. Under `TexelConversionPolicy::Exact` the notice does not
// fire, the justification does not hold, and every texel is compared exactly.
// A texel's `float` value is the device's conversion of the twin's 8-bit codes, not
// Metal's exact one, which the runtime announces as `device-texel-conversion`, whose
// note bounds it at one `f32` ulp for 8- and 16-bit codes, so the bound here is the
// note's number and not a measurement of this chip: a run that exceeds one ulp is the
// note's claim failing, which is what this allowance exists to catch. On a device whose
// sampler is Metal's the notice does not fire, the justification does not hold, and every
// texel is compared exactly.
// A CPU copy that fills such a texture (`replaceRegion`) is decoded on the CPU into that
// twin and copied in, announced as `cpu-block-decode`: the host-copy arm of the very
// mechanism the line above names, measured on lavapipe for every format of this family. It
@@ -36,27 +36,22 @@
//! here is the part Metal can answer. The lane's three further seeded draws (`seed + 1` to
//! `seed + 3`) are left for the same reason.
//!
//! **Tolerances.** Two, each the ledger's own number for a fast default, and each one that fails
//! where the notice it names did not fire.
//! **Tolerances.** Two, each the own number of the notice it names, and each one that fails where
//! that notice did not fire.
//!
//! Under the default `DecodedTexelsPolicy::Compact` an 11-bit channel is read from a 16-bit
//! normalized twin, which `docs/FAST-PATHS.md` bounds at half a 16-bit step — **1/131070
//! unsigned, 1/65534 signed** — and the runtime announces `decoded-texel-precision` where such a
//! texture is made. Those are the ledger's own numbers, named per format, not a round number.
//! An 11-bit channel is read from a 16-bit normalized twin, which the runtime announces as
//! `decoded-texel-precision` where such a texture is made, and whose catalogue entry (docs/API.md)
//! bounds it at half a 16-bit step — **1/131070 unsigned, 1/65534 signed**. Those are the notice's
//! own numbers, named per format, not a round number.
//!
//! Under the default `TexelConversionPolicy::Device` the `float` a function reads of a twin's
//! 8-bit code is the **device's** conversion of that code, not Metal's `c / 255` correctly
//! rounded, which `docs/FAST-PATHS.md` bounds at **one `f32` ulp** for 8- and 16-bit codes and the
//! runtime announces as `device-texel-conversion`. It reaches the three **linear** 8-bit formats
//! The `float` a function reads of a twin's 8-bit code is the **device's** conversion of that
//! code, not Metal's `c / 255` correctly rounded, which the runtime announces as
//! `device-texel-conversion`, whose note bounds it at **one `f32` ulp** for 8- and 16-bit codes. It reaches the three **linear** 8-bit formats
//! (`ETC2_RGB8`, `ETC2_RGB8A1`, `EAC_RGBA8`): their twin holds Metal's codes exactly and the
//! device converts them. It does not reach their sRGB forms, whose colour the function decodes
//! from the raw code through Metal's twelve-bit table itself and whose alpha it converts by the
//! format's class, so no device arithmetic stands between the twin's codes and the answer.
//!
//! No format names either tolerance under `DecodedTexelsPolicy::Exact` with
//! `TexelConversionPolicy::Exact`, where the twin holds Metal's values as `float`s and the
//! function converts a code by the bound format's class: neither notice fires, neither
//! justification holds, and every texel is compared exactly.
//!
//! Nothing here can fault a GPU: one compute pass a read, one read-only texture, one buffer, one
//! thread a texel inside the texture, no loop and no sampling.
@@ -96,18 +91,17 @@ const BLOCKS: u32 = SIDE / 4;
/// texture of its own, so a diff names which blocks moved.
const ROUNDS: [&str; 2] = ["zero-blocks", "seeded-blocks"];
/// The most a compact unsigned 11-bit texel may be off Metal's value: half a 16-bit step, as
/// `docs/FAST-PATHS.md` states it for `decoded_texels = DecodedTexelsPolicy::Compact`. It is the
/// ledger's number, so a run that exceeds it fails rather than being re-fitted to whatever a
/// device answers.
/// The most a compact unsigned 11-bit texel may be off Metal's value: half a 16-bit step, as the
/// `decoded-texel-precision` notice states it (docs/API.md). It is the notice's number, so a run
/// that exceeds it fails rather than being re-fitted to whatever a device answers.
const LEDGERS_UNSIGNED_BOUND: f64 = 1.0 / 131_070.0;
/// The same for a signed 11-bit texel, whose twin holds a 16-bit **signed** normalized code, so
/// half a step is twice as wide ([`LEDGERS_UNSIGNED_BOUND`]).
const LEDGERS_SIGNED_BOUND: f64 = 1.0 / 65_534.0;
/// The bound `docs/FAST-PATHS.md` states for `texel_conversion = TexelConversionPolicy::Device`:
/// one `f32` ulp for 8- and 16-bit codes. It is the ledger's number, copied here so a run that
/// The bound `PrecisionNote::DeviceTexelConversion` states (`device-texel-conversion`): one `f32`
/// ulp for 8- and 16-bit codes. It is the note's number, copied here so a run that
/// exceeds it fails rather than being re-fitted to whatever a device answers, and it is the same
/// number [`crate::cases::compressed_decode`] names for the same read path over a BC twin's codes.
const LEDGERS_TEXEL_CONVERSION_ULPS: u32 = 1;
@@ -284,8 +278,8 @@ impl EtcTextures {
}
/// Whether a device's own arithmetic stands between this format's twin and the `float` the
/// function answers, so that under `TexelConversionPolicy::Device` the texel is the device's
/// conversion of an 8-bit code rather than Metal's `c / 255` correctly rounded.
/// function answers, so that the texel is the device's conversion of an 8-bit code rather than
/// Metal's `c / 255` correctly rounded.
///
/// Decided from the format's own shape, never from the device or the case's name: the twin
/// holds 8-bit codes ([`EtcDecode::eleven_bit`] is false — an 11-bit format's compact twin
@@ -360,18 +354,14 @@ impl Case for EtcTextures {
crate::replay::notice_allowance(Degradation::CarriedDecodedTwin.code()),
crate::replay::notice_allowance(Degradation::CpuBlockDecode.code()),
];
// An 8-bit format's twin holds Metal's own codes, but under the default
// `TexelConversionPolicy::Device` the `float` the function answers is the **device's**
// conversion of a code, not Metal's `c / 255` correctly rounded: lavapipe multiplies by
// the reciprocal. The runtime announces that as `device-texel-conversion`, and
// `docs/FAST-PATHS.md`'s row for the policy bounds it at one `f32` ulp for 8- and 16-bit
// codes, so the bound here is the ledger's number and not a measurement of one driver: a
// run that exceeds one ulp is the ledger's claim failing, which is what this allowance
// exists to catch. It is the same allowance `cases::compressed_decode` names for the same
// read path over a BC twin's codes. Under `TexelConversionPolicy::Exact` the function
// recovers the code from the device's value by the bound format's class
// (`PackedTexels::Argb8`) and converts it itself, the notice does not fire, the
// justification does not hold, and every texel is compared exactly.
// An 8-bit format's twin holds Metal's own codes, but the `float` the function answers is
// the **device's** conversion of a code, not Metal's `c / 255` correctly rounded:
// lavapipe multiplies by the reciprocal. The runtime announces that as
// `device-texel-conversion`, whose note bounds it at one `f32` ulp for 8- and 16-bit
// codes, so the bound here is the note's number and not a measurement of one driver: a run
// that exceeds one ulp is the note's claim failing, which is what this allowance exists to
// catch. It is the same allowance `cases::compressed_decode` names for the same read path
// over a BC twin's codes.
if self.device_converts_codes() {
for round in ROUNDS {
all.push(Allowance::new(
@@ -382,13 +372,11 @@ impl Case for EtcTextures {
}
}
// An EAC 11-bit format's compact twin holds the 16-bit normalized code nearest Metal's
// value, which the runtime announces as `decoded-texel-precision` and
// `docs/FAST-PATHS.md` bounds at half a 16-bit step. The bound here is the ledger's
// number for this format's signedness, so a run that exceeds it is the ledger's claim
// failing. It is wider than the conversion ulp above and covers it, which is why an
// 11-bit format names this one alone. Under `DecodedTexelsPolicy::Exact` the twin holds
// Metal's values as `float`s, the notice does not fire, the justification does not hold,
// and every texel is compared exactly.
// value, which the runtime announces as `decoded-texel-precision`, whose catalogue entry
// bounds it at half a 16-bit step. The bound here is the notice's number for this
// format's signedness, so a run that exceeds it is the notice's claim failing. It is wider
// than the conversion ulp above and covers it, which is why an 11-bit format names this
// one alone.
if let Some(bound) = self.compact_bound() {
all.push(crate::replay::notice_allowance(
Degradation::DecodedTexelPrecision.code(),
@@ -575,20 +563,20 @@ mod tests {
}
}
/// Each format loosens the texel its own `docs/FAST-PATHS.md` row names, and nothing else.
/// Each format loosens the texel its own notice's bound names, and nothing else.
///
/// This is the ruling that a notice declaration is not a tolerance, held as a test: the
/// `carried-decoded-twin` declaration is on every case and loosens no value, while an
/// allowance that loosens a texel is named only where a fast default puts a device's own
/// arithmetic between the twin's codes and the answer. Three groups, each format named in its
/// allowance that loosens a texel is named only where a device's own arithmetic stands between
/// the twin's codes and the answer. Three groups, each format named in its
/// own, so a format moving between them fails here:
///
/// - the three **linear** 8-bit formats, whose codes the device converts under
/// `TexelConversionPolicy::Device`: one `f32` ulp, both rounds;
/// - the three **linear** 8-bit formats, whose codes the device converts: one `f32` ulp, both
/// rounds;
/// - their **sRGB** forms, whose colour the function decodes from the raw code through Metal's
/// twelve-bit table itself: **nothing at all**;
/// - the four EAC **11-bit** formats, read from a compact 16-bit twin under
/// `DecodedTexelsPolicy::Compact`: half a 16-bit step by the format's signedness.
/// - the four EAC **11-bit** formats, read from a compact 16-bit twin: half a 16-bit step by
/// the format's signedness.
#[test]
fn each_format_loosens_the_texel_its_ledger_row_names() {
let mut loosened = Vec::new();
@@ -608,7 +596,7 @@ mod tests {
true => {
// The literal 1 is deliberate, not `LEDGERS_TEXEL_CONVERSION_ULPS`:
// asserting against the constant the allowance is built from makes the
// number unfalsifiable here, and widening it would pass. The ledger's
// number unfalsifiable here, and widening it would pass. The note's
// figure is written out, so moving the constant fails this test as well
// as `the_texel_allowance_holds_one_ulp_only_where_the_notice_fired`.
assert_eq!(
@@ -709,7 +697,7 @@ mod tests {
/// 2. with **nothing** announced the same difference reads **divergent** and the allowance is
/// reported bad as `NoticeNotAnnounced` — so the day the read path stops announcing, this
/// allowance stops excusing anything;
/// 3. **two** ulps apart fails even with the notice announced, so the ledger's bound binds and
/// 3. **two** ulps apart fails even with the notice announced, so the note's bound binds and
/// the notice is no licence;
/// 4. an 8-bit **sRGB** format, which names no texel allowance, is divergent at one ulp
/// whatever was announced, so the partition above is load-bearing.
@@ -418,16 +418,14 @@ impl Case for PixelDownscales {
// These are the two kinds a run of this round provoked (see `pixel_samplers`); a venue
// that announces another reads as divergent there until someone names it with a run.
//
// Two more are named from the run that shows them, which is what the paragraph above asks
// for: on lavapipe the device's texel decode keeps a denormal where Metal flushes it
// (`device-texel-denormals`) and decodes an sRGB code its own way (`srgb-texel-decode`).
// One more is named from the run that shows it, which is what the paragraph above asks
// for: on lavapipe the device decodes an sRGB code its own way (`srgb-texel-decode`).
//
// **Every one of these is a declaration and loosens nothing.** Each sits at the notices
// site alone, so a texel that differs still fails the case wherever it differs.
[
Degradation::ArgumentPixelSamplerScaling,
Degradation::FloatSampleFilter,
Degradation::DeviceTexelDenormals,
Degradation::SrgbTexelDecode,
]
.iter()
@@ -469,16 +469,14 @@ impl Case for PixelSamplers {
// neither venue here provoked — reads as divergent at that site until whoever adds the
// venue names it with a run behind it.
//
// Two more are named from the run that shows them, which is what the paragraph above asks
// for: on lavapipe the device's texel decode keeps a denormal where Metal flushes it
// (`device-texel-denormals`) and decodes an sRGB code its own way (`srgb-texel-decode`).
// One more is named from the run that shows it, which is what the paragraph above asks
// for: on lavapipe the device decodes an sRGB code its own way (`srgb-texel-decode`).
//
// **Every one of these is a declaration and loosens nothing.** Each sits at the notices
// site alone, so a texel that differs still fails the case wherever it differs.
[
Degradation::ArgumentPixelSamplerScaling,
Degradation::FloatSampleFilter,
Degradation::DeviceTexelDenormals,
Degradation::SrgbTexelDecode,
]
.iter()
@@ -961,20 +961,13 @@ impl Case for SamplerCrossings {
// - the `Shared` buffer each row writes its samples into, for all eight rows (the RTX
// 5080);
// - `float-sample-filter`, where the device filters a float texture its own way, for the
// address-mode triples and the three mip-filter rows (llvmpipe and the 5080);
// - `device-texel-denormals`, where the device's texel decode keeps a denormal Metal
// flushes, for the three mip-filter rows alone (llvmpipe and the 5080).
// address-mode triples and the three mip-filter rows (llvmpipe and the 5080).
let mut named = vec![crate::replay::shared_memory_notice()];
if matches!(self.family, Family::Axes | Family::MipFilters(_)) {
named.push(crate::replay::notice_allowance(
Degradation::FloatSampleFilter.code(),
));
}
if matches!(self.family, Family::MipFilters(_)) {
named.push(crate::replay::notice_allowance(
Degradation::DeviceTexelDenormals.code(),
));
}
named
}
@@ -863,16 +863,13 @@ impl Case for SamplerFiltering {
// notices site is the whole of the difference. The other families provoke no notice and
// declare none, so a notice any of them starts announcing reads as divergent at once.
//
// Three more are declared, and the sets differ row by row because which rows announce
// Two more are declared, and the sets differ row by row because which rows announce
// what is a measurement rather than a rule:
//
// - the `Shared` buffer every row writes its samples into
// ([`crate::replay::shared_memory_notice`]), for all fifteen rows (the RTX 5080);
// - `float-sample-filter`, where the device filters a float texture its own way, for
// `sampler-mip-linear` and `sampler-r-address-modes` (llvmpipe and the 5080);
// - `device-texel-denormals`, where the device's texel decode keeps a denormal Metal
// flushes, for `sampler-mip-linear` and `sampler-reduction-modes` (llvmpipe and the
// 5080).
// `sampler-mip-linear` and `sampler-r-address-modes` (llvmpipe and the 5080).
let mut named = vec![crate::replay::shared_memory_notice()];
if matches!(self.family, Family::Cubic) {
named.push(notice_allowance(
@@ -882,9 +879,6 @@ impl Case for SamplerFiltering {
if matches!(self.name, "sampler-mip-linear" | "sampler-r-address-modes") {
named.push(notice_allowance(Degradation::FloatSampleFilter.code()));
}
if matches!(self.name, "sampler-mip-linear" | "sampler-reduction-modes") {
named.push(notice_allowance(Degradation::DeviceTexelDenormals.code()));
}
named
}
@@ -256,7 +256,7 @@ fn loader() -> Option<PathBuf> {
/// and asks for tests of both settings, so the command can select either.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Policy {
/// `DevicePolicy::exact_answers()`, with exact sampling: the accurate form of every choice.
/// `DevicePolicy::exact_answers()`: the accurate form of every choice.
Exact,
/// The runtime's own defaults: the fast form of every choice, which is what a consumer runs.
Default,
@@ -276,7 +276,6 @@ pub fn options_under(policy: Policy, notices: &Notices, cache: &ScratchCache) ->
let mut options = DeviceOptions::default();
if policy == Policy::Exact {
options.policy = options.policy.exact_answers();
options.policy.sampling = metal2vulkan::device::SamplingPolicy::Exact;
}
options.announce_each = Degradation::ALL.iter().copied().collect();
options.shader_cache = ShaderCacheOptions::in_directory(cache.path());
+3 -3
View File
@@ -18,9 +18,9 @@
//! - **What it serves.** Copies between buffers and the texture and between textures (fills
//! included), and the CPU's copies, move its blocks through the carrier, so `getBytes` and a
//! blit out of it hand back the blocks written. Its sampled views present its decoded twin
//! (`texture/decoded_twin.rs`), Metal's decode of the blocks in the texels
//! `DevicePolicy::decoded_texels` names (an sRGB form's 8-bit codes under either, which its
//! slots read raw and decode through Metal's table, exactly), decoded after each write as a BC
//! (`texture/decoded_twin.rs`), Metal's decode of the blocks as 8-bit codes (an LDR form's the
//! code nearest Metal's 12-bit value, announced `decoded-texel-precision`; an sRGB form's its own
//! codes, which its slots read raw and decode through Metal's table, exactly), decoded after each write as a BC
//! texture's twin is: on the GPU (`bind::astc_decode_module`), or a host write's on the CPU.
//! A view in the texture's other colour space (its `_sRGB` or LDR form) presents a second twin
//! of that form's decode, made at the first such view. Refused: a heap's or a sparse heap's
+21 -39
View File
@@ -450,8 +450,7 @@ degradations! {
/// ([`metal2vulkan::pipeline::RuntimeFact::ExactFormsOverCompilerLimit`];
/// [`metal2vulkan::device::DriverWorkaround::RegisterAllocatorOverflowsLargeModules`],
/// ANV's register allocator faults compiling a module past it), so the translation dropped
/// the consumer's exact forms until it fit: native sampling first, then every
/// module-growing exact answer native. Announced where the runtime makes a variant whose
/// the consumer's exact forms: every module-growing exact answer native. Announced where the runtime makes a variant whose
/// pipeline the fit reduced, the base variant or another (`pipeline/render.rs` for a
/// render or mesh render state, `pipeline/mod.rs` for a compute or tile render state, from
/// the pipeline's dependencies), naming the state's kind and the forms dropped; the
@@ -1354,14 +1353,13 @@ degradations! {
/// `PrecisionNote::HalfSampleFilter` or `FloatSampleFilter` under the slot's bound format
/// (a format whose filter is not measured, a swizzle that moves its channels, a linear
/// mip filter, or a sample the emulation does not reach), or, on a device that samples
/// through Metal's own sampler under `YCbCrFilterPolicy::Device` (no slot variant), under
/// any two-plane YCbCr format bound there, whose converted texels Metal's sampler filters
/// through Metal's own sampler, under any two-plane YCbCr format bound there, whose converted texels Metal's sampler filters
/// as an `RGBA16Float` or `RGBA32Float` texture's: within one step of the format's grid of
/// Metal's filter of the format, a `half` result within one `half` unit in the last place
/// (plain Metal on an Apple M3 Max under macOS 27.0.1, `YCBCR8_420_2P` and its `_sRGB`
/// twin against such a texture of the same texels). Announced, in place of those notes'
/// own notices for the slot, where the specialized pipeline is made, or, without the
/// variant, at a draw or dispatch that binds such a texture there (through a runtime
/// own notices for the slot, where the specialized pipeline is made, or at a draw or
/// dispatch that binds such a texture there (through a runtime
/// sampler, whatever its word states), naming the slot and the format.
YCbCrFilterNotExact = "ycbcr-filter-not-exact", Precision,
"the texels hold Metal's reads exactly, but the sample filters them as the device \
@@ -1705,10 +1703,10 @@ degradations! {
/// (`textureCompressionETC2`): its blocks lie in an image of a carrier format whose blocks
/// are also 16 (ASTC, `EAC_RGBA8`, `RG11`) or 8 (PVRTC, the other ETC2 and EAC formats)
/// bytes, which copies and `get_bytes` move unchanged, and its samples read a decoded
/// twin, Metal's decode of the blocks (an ASTC error block's magenta included) in the
/// texels [`metal2vulkan::device::DecodedTexelsPolicy`] names (a PVRTC texture's, an ASTC
/// sRGB one's and an 8-bit ETC2 or EAC one's, 8-bit codes, exact, under either), decoded
/// after each write into it as a BC texture's twin is (`decoded-block-twin`; a PVRTC
/// twin, Metal's decode of the blocks (an ASTC error block's magenta included) in codes:
/// an ASTC LDR texture's and an EAC 11-bit one's each nearest Metal's value
/// (`decoded-texel-precision`), a PVRTC texture's, an ASTC sRGB one's and an 8-bit ETC2 or
/// EAC one's 8-bit codes, exact, decoded after each write into it as a BC texture's twin is (`decoded-block-twin`; a PVRTC
/// texture's whole levels). An ASTC texture's first view in its other colour space gives
/// it a second twin of that form's decode. Also a texture of a 4:2:2 format (`GBGR422`,
/// `BGRG422`) on every device, whose Vulkan formats reconstruct chroma by the
@@ -1716,23 +1714,20 @@ degradations! {
/// holds Metal's texels as 8-bit codes, exact, decoded in whole rows.
CarriedDecodedTwin = "carried-decoded-twin", Performance,
"a carrier image of its blocks, at most about 1 byte a texel (a 4:2:2 texture's 2), \
and a decoded twin of 4 bytes a texel (R8G8B8A8, \
`DecodedTexelsPolicy::Compact`; an EAC 11-bit texture's \
16-bit codes, 2 bytes a channel) or 16 (R32G32B32A32_SFLOAT, \
`DecodedTexelsPolicy::Exact`; an EAC 11-bit texture's floats, 4 bytes a channel), \
two for an ASTC texture viewed in both colour spaces, and a decode after each write \
into it: a pass on the GPU for a blit, a copy from a texture or a CPU copy through a \
and a decoded twin of 4 bytes a texel (R8G8B8A8; an EAC 11-bit texture's \
16-bit codes, 2 bytes a channel, or its floats, 4 bytes a channel, where the device \
does not take those codes), two for an ASTC texture viewed in both colour \
spaces, and a decode after each write into it: a pass on the GPU for a blit, a copy from a texture or a CPU copy through a \
submission; on the CPU, on the device's decode thread, where its CPU copies go on \
the host or the staging queue";
/// A texture with an ASTC LDR decoded twin (`carried-decoded-twin`) of 8-bit codes, or an
/// EAC 11-bit one of 16-bit codes, under
/// [`metal2vulkan::device::DecodedTexelsPolicy::Compact`]: Metal decodes an ASTC LDR channel
/// EAC 11-bit one of 16-bit codes: Metal decodes an ASTC LDR channel
/// to a 12-bit value (`C >> 4` over 4095 of the 16-bit interpolated channel `C`), which the
/// twin's R8G8B8A8 texels hold as the nearest 8-bit code (at most 1/510 off Metal's value).
/// It reads an EAC 11-bit channel as `c / 2047` (signed `c / 1023`), which the twin holds
/// as the nearest 16-bit normalized code (at most half a 16-bit step off).
/// `DecodedTexelsPolicy::Exact` holds Metal's values instead. (An ASTC sRGB texture's twin
/// holds Metal's own 8-bit codes, which its slots decode through Metal's table: exact.)
/// as the nearest 16-bit normalized code (at most half a 16-bit step off). (An ASTC sRGB
/// texture's twin holds Metal's own 8-bit codes, which its slots decode through Metal's
/// table: exact.)
DecodedTexelPrecision = "decoded-texel-precision", Precision,
"a read, sample or gather of its texels answers the nearest 8-bit code to Metal's \
12-bit value, at most 1/510 off it; an EAC 11-bit texture's, the nearest 16-bit \
@@ -2063,12 +2058,8 @@ degradations! {
HalfSampleFilter = "half-sample-filter";
SrgbTexelDecode = "srgb-texel-decode";
FloatSampleFilter = "float-sample-filter";
DeviceGatherFootprint = "device-gather-footprint";
CubeFaceReciprocal = "cube-face-reciprocal";
FunctionStorageAssumed = "function-storage-assumed";
QuadsCountedBeforeDiscard = "quads-counted-before-discard";
DeviceDepthComparison = "device-depth-comparison";
DeviceTexelDenormals = "device-texel-denormals";
ViewBaseTexelOffset = "view-base-texel-offset";
DeviceColorConversion = "device-color-conversion";
DeviceInterpolation = "device-interpolation";
@@ -2090,14 +2081,11 @@ degradations! {
DevicePointSize = "device-point-size";
ClippedCoverageSplit = "clipped-coverage-split";
LoopedSampleOutputs = "looped-sample-outputs";
DeviceUnorm8LinearFilter = "device-unorm8-linear-filter";
HalfOutputFastMathBlend = "half-output-fast-math-blend";
/// Class: native device sampling. The device's own sampler answers the pipeline's
/// samples, gathers and comparisons where Metal's would be emulated
/// (`SamplingPolicy::NativeDevice`, the default on a device whose sampler is not Metal's;
/// `SamplingPolicy::Exact` keeps Metal's). Recorded bound, measured against an Apple M4
/// on 2D textures of one level in seven formats under four address modes: a linear
/// filter within 0.919 of a code (1/255) of Metal's on NVIDIA's 615.71.09, 0.548 on RADV,
/// samples, gathers and comparisons on a device whose sampler is not Metal's. Recorded
/// bound, measured against an Apple M4 on 2D textures of one level in seven formats
/// under four address modes: a linear filter within 0.919 of a code (1/255) of Metal's on NVIDIA's 615.71.09, 0.548 on RADV,
/// 0.918 on ANV and 1.0 on lavapipe (Mesa 26.2.4); an sRGB texture's within 1.832, 0.764,
/// 0.912 and 0.781; a nearest sample's texel the neighbour of Metal's at 0.1% of the
/// probe's coordinates on NVIDIA and ANV, 0.02% on RADV and none on lavapipe. Level
@@ -2125,10 +2113,8 @@ degradations! {
/// the last place of the result.
NativeFma = "native-fma";
/// Class: native device sampling. The device's own conversion of a texel's codes answers
/// the pipeline's reads, samples and gathers with a `float` result where Metal's would be
/// emulated (`TexelConversionPolicy::Device`, the default, on a device whose sampler is not
/// Metal's; `Exact` keeps Metal's for a read, and for a sample or gather under
/// `SamplingPolicy::Exact`). Recorded bound, of a texel whose access reads one texel of one
/// the pipeline's reads, samples and gathers with a `float` result, on a device whose
/// sampler is not Metal's. Recorded bound, of a texel whose access reads one texel of one
/// level: an 8- or 16-bit normalized code within one `f32` ulp of Metal's `c / (2^b - 1)`
/// where measured (lavapipe's reciprocal product); a 5- or 6-bit channel the device widens
/// by replicating its bits within 0.18 of a code (ANV, NVIDIA; a 4-bit channel's exact); a
@@ -2606,12 +2592,8 @@ pub(crate) fn dropped_exact_forms(
) -> Option<Vec<&'static str>> {
dependencies.iter().find_map(|d| match d.fact {
metal2vulkan::pipeline::RuntimeFact::ExactFormsOverCompilerLimit {
sampling,
texel_conversion,
} => Some(
[
(sampling, "exact sampling"),
(texel_conversion, "exact texel conversion"),
]
.into_iter()
.filter_map(|(dropped, name)| dropped.then_some(name))
+4 -3
View File
@@ -19,9 +19,10 @@
//! of the blocks, decoded after each write as a BC texture's twin is, on the GPU
//! (`bind::etc_decode_module`), or a host write's on the CPU. An 8-bit format's twin holds its
//! codes, exact (an sRGB form's slots read them raw and decode them through Metal's table,
//! `metal::texel_format::srgb_raw`); an 11-bit format's holds the texels
//! `DevicePolicy::decoded_texels` names (`bind::EtcTexels`: 16-bit normalized codes, announced
//! `decoded-texel-precision`, or Metal's values exactly). Announced `carried-decoded-twin`.
//! `metal::texel_format::srgb_raw`); an 11-bit format's holds 16-bit normalized codes
//! (`bind::EtcTexels::Compact`, announced `decoded-texel-precision`), or Metal's values exactly
//! where the device does not take those codes' format (`EtcTexels::Float`). Announced
//! `carried-decoded-twin`.
//! Refused: a view of another decode (an `R11` or `RG11` format's other signedness;
//! `Feature::TextureView`) and a sparse heap's texture (`RuntimeGap::DecodedHeapTexture`). A
//! texture without a twin (a heap's over the caller's host pages or laid out apart from the
@@ -71,12 +71,11 @@ fn library(name: &str) -> Library {
Library::from_air(&bitcode).unwrap()
}
/// Add to `dependencies` the fit's record of dropping exact sampling and exact texel conversion.
/// Add to `dependencies` the fit's record of dropping exact NaN and minimum and maximum.
fn fit_into(dependencies: &mut Vec<RuntimeDependency>) {
dependencies.push(RuntimeDependency::new(
RuntimeFact::ExactFormsOverCompilerLimit {
sampling: true,
texel_conversion: true,
},
Mechanism::None,
));
@@ -192,8 +191,7 @@ fn a_variant_fitted_while_its_base_was_not_still_announces() {
let (object, reason) = &said[0];
assert_eq!(object, "a render pipeline state");
assert!(
reason.contains("exact sampling, exact texel conversion")
&& !reason.contains("exact NaN and minimum and maximum"),
reason.contains("exact NaN and minimum and maximum"),
"{reason}"
);
// Once per device: a later fitted variant adds no second notice.
@@ -239,7 +237,7 @@ fn every_kind_of_fitted_pipeline_announces_its_state_kind() {
assert_eq!(said.len(), 1, "{said:?}");
assert_eq!(said[0].0, "a compute pipeline state");
assert!(
said[0].1.contains("exact sampling, exact texel conversion"),
said[0].1.contains("exact NaN and minimum and maximum"),
"{said:?}"
);
@@ -1969,7 +1969,7 @@ fn decoded_twins_are_planned_in_their_texels_format() {
/// texels take at most the budget together, so a pass in the device's decode scratch
/// (`PassScratch::Device`, of the budget and an alignment) holds any band; only a single block
/// row of one image past the budget is a band alone. Regions of BC decodes, of ASTC ones
/// (blocks of 12 x 10 and 4 x 4, texels of 16 and 4 bytes), PVRTC ones, ETC2 and EAC ones
/// (blocks of 12 x 10 and 4 x 4, texels of 4 bytes), PVRTC ones, ETC2 and EAC ones
/// (texels of 2, 8 and 4 bytes) and 4:2:2 ones (pairs of 2 x 1), square and narrow, of sides off a
/// multiple of the block, of layers and of depth slices, under the band budget and two small ones
/// that make them band.
@@ -1993,7 +1993,7 @@ fn decode_bands_cover_each_texel_once_within_the_budget() {
TwinDecode::Block(BlockDecode::Bc1),
TwinDecode::Block(BlockDecode::Bc3),
TwinDecode::Block(BlockDecode::Bc5Unorm),
TwinDecode::Astc(astc(PixelFormat::ASTC12x10LDR), AstcTexels::Float),
TwinDecode::Astc(astc(PixelFormat::ASTC12x10LDR), AstcTexels::Unorm8),
TwinDecode::Astc(astc(PixelFormat::ASTC4x4SRGB), AstcTexels::Unorm8),
TwinDecode::Pvrtc(PvrtcDecode::of(PixelFormat::PVRTCRGBA2BPP).expect("a PVRTC decode")),
TwinDecode::Pvrtc(PvrtcDecode::of(PixelFormat::PVRTCRGB4BPP).expect("a PVRTC decode")),
@@ -44,9 +44,9 @@
//! those texels would.
//!
//! **ASTC** (`astc.rs`): on a device without a texture's ASTC LDR format its blocks lie in a
//! carrier image and its twin holds Metal's decode in the texels `DevicePolicy::decoded_texels` names
//! (`TwinDecode::Astc`; an sRGB form's 8-bit codes under either, which its slots read raw and
//! decode through Metal's table), kept in step as a BC image's twin is (`bind::astc_decode_module`
//! carrier image and its twin holds Metal's decode as 8-bit codes (`TwinDecode::Astc`; an LDR
//! form's the code nearest Metal's 12-bit value, an sRGB form's its own codes, which its slots read
//! raw and decode through Metal's table), kept in step as a BC image's twin is (`bind::astc_decode_module`
//! on the GPU, `AstcDecode::decode_into` on the CPU): a pass's bands are of the texture's texels,
//! each band's blocks copied out of the carrier's texels over them. A new one's zero blocks read
//! magenta (an error block).
@@ -57,7 +57,7 @@
//! bit for bit, footprints 4x4, 6x5 and 12x12). The two forms widen the endpoints apart
//! (`bind::AstcDecode`), so neither's texels follow from the other's: the first view of the
//! texture in its other colour space makes the carrier a second twin ([`Image::make_second_twin`]),
//! of that form's decode in the texels the policy names, in memory of its own, which the CPU
//! of that form's decode in 8-bit codes, in memory of its own, which the CPU
//! never writes. Its decodes are the GPU's, each recorded by a batch's submission
//! ([`SecondDecode`]): its whole decode as it is made, and a host write's, queued for the
//! device's next batch with work, which records them before its work, their uses joined to its
@@ -81,8 +81,9 @@
//! **ETC2 and EAC** (`etc.rs`): on a device without the formats their blocks lie in a carrier of
//! the texture's shape, and the twin holds Metal's decode (`TwinDecode::Etc`): an 8-bit format's
//! codes (`R8G8B8A8_UNORM`; an sRGB form's slots read them raw and decode them through Metal's
//! table), which serve the views of its linear and sRGB forms alike, and an 11-bit format's texels
//! `DevicePolicy::decoded_texels` names (`bind::EtcTexels`). Each is kept in step as a BC image's
//! table), which serve the views of its linear and sRGB forms alike, and an 11-bit format's 16-bit
//! normalized codes, or its values where the device does not take those (`bind::EtcTexels`). Each
//! is kept in step as a BC image's
//! twin is (`bind::etc_decode_module` on the GPU, `EtcDecode::decode_into` on the CPU). A new
//! one's zero blocks read grey of codes 2 (`ETC2_RGB8`, and `EAC_RGBA8`'s colour, its alpha 0),
//! opaque black (`RGB8A1`), or an 11-bit value of 1 (signed -3), not zeros: the twin starts
@@ -137,7 +138,6 @@ use metal2vulkan::bind::{
AstcDecode, AstcTexels, BlockDecode, BlockDecodeModule, ChromaDecode, EtcDecode, EtcTexels,
ImageViewDesc, PvrtcDecode,
};
use metal2vulkan::device::DecodedTexelsPolicy;
use metal2vulkan::device::FormatUsage;
use metal2vulkan::error::{Capability, Feature, Unsupported};
use metal2vulkan::metal::format::FormatMapping;
@@ -158,11 +158,10 @@ const TWIN_FEATURES: FormatFeatureFlags2 = FormatFeatureFlags2::SAMPLED_IMAGE
pub(crate) const BAND_BYTES: u64 = 32 << 20;
/// How a decoded twin's blocks decode: a BC1 to BC5 format's (`BlockDecode`), an ASTC LDR
/// format's held in a carrier (`astc.rs`) into the texels the device's policy names, a PVRTC
/// format's held in a carrier (`pvrtc.rs`) into its codes (its linear form's decode, which its
/// sRGB form's is too), an ETC2 or EAC format's held in a carrier (`etc.rs`) into its codes or
/// an 11-bit format's texels the policy names (its unorm form's decode, which its sRGB form's is
/// too), or a 4:2:2 format's pairs held in a carrier (`chroma_pairs.rs`) into its codes.
/// format's held in a carrier (`astc.rs`) into 8-bit codes, a PVRTC format's held in a carrier
/// (`pvrtc.rs`) into its codes (its linear form's decode, which its sRGB form's is too), an ETC2
/// or EAC format's held in a carrier (`etc.rs`) into its codes or an 11-bit format's texels
/// (`Device::etc_texels`; its unorm form's decode, which its sRGB form's is too), or a 4:2:2 format's pairs held in a carrier (`chroma_pairs.rs`) into its codes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) enum TwinDecode {
Block(BlockDecode),
@@ -471,45 +470,36 @@ impl Device {
(!measured && layout.samples == 1).then_some(decode)
}
/// The texels of the decoded twin of an ASTC texture of `decode` on this device: an sRGB
/// form's 8-bit codes either way, which its slots read raw and decode through Metal's table,
/// exactly (`metal::texel_format::srgb_raw_on`); an LDR form's Metal's exact values where
/// `DevicePolicy::decoded_texels` asks for them and the device samples, filters and copies
/// into their format, else 8-bit codes. Refused where the device does not even take the
/// codes' format so (no conformant device).
/// The texels of the decoded twin of an ASTC texture of `decode` on this device: 8-bit codes,
/// an LDR form's each the code nearest Metal's 12-bit value (`decoded-texel-precision`), an
/// sRGB form's its own, which its slots read raw and decode through Metal's table, exactly
/// (`metal::texel_format::srgb_raw_on`). Refused where the device does not take the codes'
/// format so (no conformant device).
fn astc_texels(&self, decode: AstcDecode) -> Result<AstcTexels, Error> {
let facts = self
.shared()
.textures
.facts(self.compile_device().profile());
let takes = |texels: AstcTexels| {
facts
.optimal(decode.texel_format(texels))
.contains(TWIN_FEATURES)
};
let wanted = match self.compile_device().policy().decoded_texels {
DecodedTexelsPolicy::Exact if !decode.srgb => AstcTexels::Float,
_ => AstcTexels::Unorm8,
};
[wanted, AstcTexels::Unorm8]
.into_iter()
.find(|&texels| takes(texels))
.ok_or_else(|| {
Error::Unsupported(Unsupported::needs(
Feature::Format,
Capability::Format {
format: decode.texel_format(AstcTexels::Unorm8),
usage: FormatUsage::SampledImageFilterLinear,
},
))
})
let texels = AstcTexels::Unorm8;
if facts
.optimal(decode.texel_format(texels))
.contains(TWIN_FEATURES)
{
return Ok(texels);
}
Err(Error::Unsupported(Unsupported::needs(
Feature::Format,
Capability::Format {
format: decode.texel_format(texels),
usage: FormatUsage::SampledImageFilterLinear,
},
)))
}
/// The texels of the decoded twin of an ETC2 or EAC texture of `decode` on this device: an
/// 8-bit format's codes either way; an 11-bit format's values exactly where
/// `DevicePolicy::decoded_texels` asks for them, else 16-bit normalized codes, each where the
/// device samples, filters and copies into their format, else the other. Refused where the
/// device takes neither so.
/// 8-bit format's codes; an 11-bit format's 16-bit normalized codes where the device samples,
/// filters and copies into their format, else its values exactly. Refused where the device
/// takes neither so.
fn etc_texels(&self, decode: EtcDecode) -> Result<EtcTexels, Error> {
if !decode.eleven_bit() {
return Ok(EtcTexels::Compact);
@@ -523,10 +513,7 @@ impl Device {
.optimal(decode.texel_format(texels))
.contains(TWIN_FEATURES)
};
let order = match self.compile_device().policy().decoded_texels {
DecodedTexelsPolicy::Exact => [EtcTexels::Float, EtcTexels::Compact],
_ => [EtcTexels::Compact, EtcTexels::Float],
};
let order = [EtcTexels::Compact, EtcTexels::Float];
order
.into_iter()
.find(|&texels| takes(texels))
@@ -109,9 +109,8 @@
//!
//! `--policy NAMES` (`run` and `time`) opens the device with those `DevicePolicy` switches at their
//! accurate forms, where it opens at the default policy otherwise: a comma-separated list of
//! `exact-answers` (`DevicePolicy::exact_answers`) and field names (`sampling`, `ycbcr_filter`,
//! `texel_conversion`), each set to its `Exact` form, so a making under an application's exact
//! forms is timed as it makes them.
//! `exact-answers` (`DevicePolicy::exact_answers`), so a making under an application's exact forms
//! is timed as it makes them.
//!
//! `--device-type` names the device the draw runs on, as validation's other device commands do
//! (`cpu` matches only a CPU implementation such as lavapipe); the device opens through
@@ -148,7 +147,7 @@
use metal2vulkan::bind::SamplerDescriptor;
use metal2vulkan::device::{
DevicePolicy, SamplingPolicy, TexelConversionPolicy, YCbCrFilterPolicy,
DevicePolicy,
};
use metal2vulkan::metal::state::DepthStencilDescriptor;
use metal2vulkan::metal::CompareFunction;
@@ -313,12 +312,9 @@ fn policy(options: &BTreeMap<String, String>) -> Result<DevicePolicy, String> {
for name in names.split(',').filter(|name| !name.is_empty()) {
match name {
"exact-answers" => policy = policy.exact_answers(),
"sampling" => policy.sampling = SamplingPolicy::Exact,
"ycbcr_filter" => policy.ycbcr_filter = YCbCrFilterPolicy::Exact,
"texel_conversion" => policy.texel_conversion = TexelConversionPolicy::Exact,
_ => {
return Err(format!(
"--policy {name:?}: exact-answers, sampling, ycbcr_filter or texel_conversion"
"--policy {name:?}: exact-answers"
))
}
}
+1 -23
View File
@@ -718,18 +718,11 @@ pub struct SlotRow {
/// Euclidean length of the gradient's two counted components where Apple combines them by its own
/// rule, so near a level or filter boundary a sample selects another level or filter than
/// Metal's, and the sampled value is ordinary data later words use.
/// - A nearest cube sample's texel (`CubeFaceReciprocal`): the product computes Metal's position
/// with the correctly rounded reciprocal of the major magnitude where Apple's texture unit uses
/// an approximate one, so near a texel edge a sample reads the next texel, and the sampled value
/// is ordinary data later words use.
/// - A non-quad simdgroup operation before a discard (`QuadsCountedBeforeDiscard`), in a shape
/// whose placement by Metal's compiler is not known: its lanes include the quads the discard
/// drops, which Metal's may leave out, and the count, ballot, or reduction is ordinary data later
/// words use. Where Metal's placement was measured, the module makes it (a sum moved past the
/// discard, or counted ahead of it) and records no note.
/// - A depth comparison the device makes (`DeviceDepthComparison`): a tap passes or fails where
/// Metal's does not, and the comparison's value is ordinary data later words use. Open until the
/// shader makes those comparisons on texels it fetches.
/// - A bicubic sample's unpinned arithmetic (`BicubicFilterArithmetic`): a 2D normalized sum near a
/// rounding tie lands one grid step from Metal's, whose 2D rounding no model fitted, and the
/// sampled value is ordinary data later words use.
@@ -769,13 +762,11 @@ pub struct SlotRow {
/// denormal, a `half` rounding) belongs in a per-word judgement of a reading's differing words,
/// beside the check of each against Apple's bound, never in this list: a row-level match would
/// reopen every signed-off reading whose row merely records the note.
pub const DEFERRED_NEAR_EQUIVALENTS: [PrecisionNote; 13] = [
pub const DEFERRED_NEAR_EQUIVALENTS: [PrecisionNote; 11] = [
PrecisionNote::RasterizationRateMap,
PrecisionNote::SparseResidency,
PrecisionNote::CubeGradientFootprint,
PrecisionNote::CubeFaceReciprocal,
PrecisionNote::QuadsCountedBeforeDiscard,
PrecisionNote::DeviceDepthComparison,
PrecisionNote::BicubicFilterArithmetic,
PrecisionNote::VertexSimdgroupGrouping,
PrecisionNote::FragmentSimdgroupGrouping,
@@ -842,19 +833,6 @@ fn near_equivalent_bound(note: PrecisionNote) -> &'static str {
1 + 3/2048: a sample near a level or filter boundary can take another level or \
filter"
}
PrecisionNote::CubeFaceReciprocal => {
"a nearest cube texel from Metal's position floor(RN(RN(1 + sc * r) / 2 * n)) with r \
the correctly rounded reciprocal of the major magnitude, where Apple M3 Max's and \
M4's texture unit's is one or two ulps off on 208 of 2,001 majors measured (204 up, 4 \
down, each within about 0.2 ulp of a rounding midpoint): on such a major a position \
within about n * 2^-23 of a texel edge reads the next texel; no exact form of Apple's \
reciprocal is known"
}
PrecisionNote::DeviceDepthComparison => {
"a depth comparison the device makes differs from Apple M4's on up to 584 of 9,024 \
Depth16Unorm comparisons (ANV; RADV 71, the RTX 3090 474, lavapipe 1,203); every \
comparison the shader makes is Metal's, on texels it fetches or the device reads"
}
PrecisionNote::QuadsCountedBeforeDiscard => {
"a non-quad simdgroup operation before a discard, in a shape whose placement by \
Metal's compiler is not known (another operation than a sum, a use of its result \
@@ -1369,16 +1369,6 @@ fn a_cube_gradient_footprint_row_is_deferred_and_never_a_reviewed_reading() {
);
}
/// A nearest cube sample's texel from a correctly rounded reciprocal (`CubeFaceReciprocal`) is
/// deferred the same way, with its measured bound.
#[test]
fn a_cube_face_reciprocal_row_is_deferred_and_never_a_reviewed_reading() {
deferred_and_never_reviewed(
PrecisionNote::CubeFaceReciprocal,
"CubeFaceReciprocal:a nearest cube texel",
);
}
/// A bicubic sample's unpinned arithmetic (`BicubicFilterArithmetic`) is deferred the same way,
/// with its measured bound: no model of Apple's 2D rounding fitted.
#[test]
@@ -127,14 +127,11 @@ pub fn requested_generated_commands() -> bool {
}
/// The policy an engine `Device` of this process is created under: the default policy with
/// Metal's sampler emulated exactly (`SamplingPolicy::Exact`), and Metal's answer wherever the policy offers the
/// device's instead (`DevicePolicy::exact_answers`, Metal's texel conversions; its maths; its
/// `half` rounding; its NaN and minimum and maximum and its rounding order), as Metal's answers are
/// what the candidate is compared with.
/// Metal's answer wherever the policy offers the device's instead (`DevicePolicy::exact_answers`,
/// Metal's maths; its `half` rounding; its NaN and minimum and maximum and its rounding order), as
/// Metal's answers are what the candidate is compared with.
pub fn requested_policy() -> DevicePolicy {
let mut policy = DevicePolicy::default().exact_answers();
policy.sampling = metal2vulkan::device::SamplingPolicy::Exact;
policy
DevicePolicy::default().exact_answers()
}
/// Write every validation-layer message that fails a row to stderr as the layer reports it, for
@@ -628,12 +628,11 @@ pub fn executor_layer_settings() -> Vec<LayerSetting> {
}
/// The options of a device validation makes through the runtime: the validation layer reporting
/// to `messages`, its shader cache in `cache`, and the loader [`loader`] finds. Its policy emulates
/// Metal's sampler exactly (`SamplingPolicy::Exact`) and takes Metal's answer wherever the policy
/// offers the device's instead (`DevicePolicy::exact_answers`): it converts texels as Metal does,
/// computes Metal's maths exactly, rounds `half` results as Metal does, and answers Metal's NaN,
/// minimum and maximum and rounding order. Validation compares Metal's answers, which native device
/// sampling and the device's forms answer only within their recorded bounds
/// to `messages`, its shader cache in `cache`, and the loader [`loader`] finds. Its policy takes
/// Metal's answer wherever the policy offers the device's instead (`DevicePolicy::exact_answers`):
/// it computes Metal's maths exactly, rounds `half` results as Metal does, and answers Metal's NaN,
/// minimum and maximum and rounding order. Validation compares Metal's answers, which the device's
/// sampler and the device's forms answer only within their recorded bounds
/// (`PrecisionNote::DeviceSampling`, `DeviceTexelConversion`; `NativeTranscendentals`,
/// `NativeDivision`, `NativeFma`; `NativeHalfConversion`, `NativeHalfQuantize`;
/// `NativeNanEncoding`, `NativeMinMax`; `NativeDot`, `NativeMix`). The lane of the device's forms
@@ -642,7 +641,6 @@ pub fn executor_layer_settings() -> Vec<LayerSetting> {
pub fn validated_options(messages: &Messages, cache: &Path) -> DeviceOptions {
let mut options = DeviceOptions::default();
options.policy = options.policy.exact_answers();
options.policy.sampling = metal2vulkan::device::SamplingPolicy::Exact;
options.shader_cache = ShaderCacheOptions::in_directory(cache);
options.loader = loader();
options.layers.push(VALIDATION_LAYER.to_owned());
@@ -203,18 +203,9 @@ impl UlpTable {
/// - `FloatSampleFilter`: unbounded: a filtered `float` sample the emulation does not reach is the
/// device's filter, whose footprint, weights, and sum Vulkan bounds only by its precision rules,
/// so a lane can differ from Metal's by any amount.
/// - `DeviceGatherFootprint`: unbounded: a gather the module leaves to the device (a cube's, a
/// runtime or argument-buffer sampler's, a pixel-coordinate sampler's) can read the next 2x2
/// block, which changes whole texels, not lanes.
/// - `CubeFaceReciprocal`: unbounded: a nearest cube sample handed the texel of Metal's position
/// with the correctly rounded reciprocal reads the next texel where Apple's texture unit's
/// reciprocal is the other neighbour and the position lies near a texel edge, which changes whole
/// texels, not lanes.
/// - `QuadsCountedBeforeDiscard`: unbounded: a non-quad simdgroup operation before a discard, in a
/// shape whose placement by Metal's compiler is not known, takes, among its lanes, the quads the
/// discard drops, which moves a count, a ballot, or a reduction by whole lanes.
/// - `DeviceDepthComparison`: unbounded: a depth comparison the device makes passes or fails a
/// whole tap where Metal's does not.
/// - `DeviceInterpolation`: unbounded: the device's interpolation of a varying is measured up to
/// about `3e-4` off Metal's on the probes (more where the varying's range is wider), and the
/// interpolated value is ordinary data later words use, so no word's difference is bounded by
@@ -241,9 +232,6 @@ impl UlpTable {
/// performs is exposed to both; a `half` texel's NaN is the device's decode where Metal hands
/// back the texel's own: a difference they cause stays a mismatch for review, never accepted or
/// explained by the class. C3 tells which differing values they cause ([`value_difference`]).
/// - `DeviceTexelDenormals`: [`Allowance::Recorded`]. A device's sample or gather may read a
/// denormal 32-bit float texel as zero where Metal's keeps it, and every `float` sample or gather
/// whose texels the device reads is exposed to it: a difference stays a mismatch for review.
/// - `FunctionStorageAssumed`: [`Allowance::Recorded`]. A vertex or fragment function's private
/// memory passes the floor of a device not measured, resting on no measurement; a difference is
/// a mismatch for review, never accepted or explained by the note.
@@ -274,7 +262,6 @@ pub fn allowance(note: PrecisionNote) -> Allowance {
N::DeviceDenormals
| N::DeviceNanEncoding
| N::FunctionStorageAssumed
| N::DeviceTexelDenormals
| N::ViewBaseTexelOffset => Allowance::Recorded,
N::DeviceColorConversion => Allowance::Recorded,
N::LinkedSamplerNumbering | N::ColorAttachmentGroups => Allowance::Recorded,
@@ -306,10 +293,7 @@ pub fn allowance(note: PrecisionNote) -> Allowance {
| N::HalfSampleFilter
| N::SrgbTexelDecode
| N::FloatSampleFilter
| N::DeviceGatherFootprint
| N::CubeFaceReciprocal
| N::QuadsCountedBeforeDiscard
| N::DeviceDepthComparison
| N::DeviceInterpolation
| N::ComputedSampleDepth
| N::QuadsSplitByClipping
@@ -326,7 +310,6 @@ pub fn allowance(note: PrecisionNote) -> Allowance {
| N::DevicePointSize
| N::ClippedCoverageSplit
| N::LoopedSampleOutputs
| N::DeviceUnorm8LinearFilter
| N::HalfOutputFastMathBlend
| N::DeviceSampling
| N::NativeTranscendentals
@@ -63,10 +63,7 @@ fn every_precision_note_has_its_table_row() {
(N::HalfSampleFilter, Allowance::Unbounded),
(N::SrgbTexelDecode, Allowance::Unbounded),
(N::FloatSampleFilter, Allowance::Unbounded),
(N::DeviceGatherFootprint, Allowance::Unbounded),
(N::CubeFaceReciprocal, Allowance::Unbounded),
(N::FunctionStorageAssumed, Allowance::Recorded),
(N::DeviceTexelDenormals, Allowance::Recorded),
(N::ViewBaseTexelOffset, Allowance::Recorded),
(N::DeviceColorConversion, Allowance::Recorded),
(N::DeviceInterpolation, Allowance::Unbounded),
@@ -113,7 +110,6 @@ fn only_the_environment_notes_are_told_value_by_value() {
N::RasterizationRateMap,
N::BicubicFilterArithmetic,
N::SparseResidency,
N::DeviceTexelDenormals,
N::ViewBaseTexelOffset,
N::DeviceColorConversion,
] {
@@ -13,17 +13,16 @@
//! bit), each channel stored as `round(v · 255 · 256)`, within `0.002` of a 256th of a code of the
//! `float` Metal wrote.
//!
//! On a device without Metal's own sampler each sample takes the product's emulation of Metal's
//! filter (the module `lower::sampler::anisotropic`), and the device announces
//! `anisotropic-filter`; a device with Metal's sampler (MoltenVK) filters with it and announces
//! nothing. The samplers run again with `samplerAnisotropy` withheld, under the lane's exact
//! sampling and under native device sampling (the default policy's): every Vulkan sampler is then
//! isotropic and every sample takes the emulation, MoltenVK's too, within the same bounds. Each
//! sampler's answers stay within its bound in codes ([`Bound`]): for linear filters the
//! emulation's residue, the device's own bilinear filter (under clamp to edge, lavapipe's 8-bit
//! path) and Metal's level at `1/256` of a level; for nearest ones a tap a texel off Metal's where
//! it sits within the spacing's residue of a texel edge. The test prints each sampler's largest
//! and mean difference in codes and the share of channels a code or more off.
//! The samplers run with `samplerAnisotropy` withheld: every Vulkan sampler is then isotropic and
//! every sample takes the product's emulation of Metal's filter (the module
//! `lower::sampler::anisotropic`) on every device, MoltenVK's too, and the device announces
//! `anisotropic-filter`. Each sampler's answers stay within its bound in codes ([`Bound`]): for
//! linear filters the emulation's residue, the device's own bilinear filter (under clamp to edge,
//! lavapipe's 8-bit path) and Metal's level at `1/256` of a level; for nearest ones a tap a texel
//! off Metal's where it sits within the spacing's residue of a texel edge. The test prints each
//! sampler's largest and mean difference in codes and the share of channels a code or more off.
//! (With `samplerAnisotropy`, the device's own anisotropic filter answers, which no bound here
//! measures.)
use super::degrade_notices::counts;
use super::{
@@ -33,7 +32,6 @@ use super::{
use crate::air_library::AirLibrary;
use crate::gpu::TEST_DEVICE;
use metal2vulkan::bind::SamplerDescriptor;
use metal2vulkan::device::VkProperty;
use metal2vulkan::metal::{PixelFormat, SamplerAddressMode, SamplerMinMagFilter, SamplerMipFilter};
use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource};
use metal2vulkan_devtools::llvm_assemble_text;
@@ -444,57 +442,28 @@ fn the_inputs_are_the_probes() {
assert_eq!(sha(METAL), METAL_SHA);
}
/// Every sampler's answers stay within its bound of the M4's (the module docs), and a device
/// without Metal's own sampler announces `anisotropic-filter`: the emulation ran. Prints each
/// sampler's differences.
#[test]
fn anisotropic_samples_answer_within_their_bounds_of_metals() {
within_bounds("", |_| {}, false);
}
/// [`anisotropic_samples_answer_within_their_bounds_of_metals`] with `samplerAnisotropy` withheld,
/// under the lane's exact sampling and under native device sampling (the default policy's): every
/// sampler state is made, its Vulkan sampler isotropic, every sample takes the emulation on every
/// device (`anisotropic-filter` announced, through Metal's own sampler too), and each sampler's
/// answers stay within its bound of the M4's.
/// With `samplerAnisotropy` withheld every sampler state is made, its Vulkan sampler isotropic,
/// every sample takes the emulation on every device (`anisotropic-filter` announced, through
/// Metal's own sampler too), and each sampler's answers stay within its bound of the M4's.
#[test]
fn without_sampler_anisotropy_the_emulation_answers_within_its_bounds() {
use metal2vulkan::device::{SamplingPolicy, VkFeature};
for sampling in [SamplingPolicy::Exact, SamplingPolicy::NativeDevice] {
let what = format!("samplerAnisotropy withheld, {sampling:?} sampling");
within_bounds(
&what,
|options| {
options.policy.sampling = sampling;
options
.withheld_features
.insert(VkFeature::SamplerAnisotropy);
},
true,
);
}
use metal2vulkan::device::VkFeature;
within_bounds("samplerAnisotropy withheld", |options| {
options
.withheld_features
.insert(VkFeature::SamplerAnisotropy);
});
}
/// Every sampler's answers on the test device made with `adjust` beside the lane's options stay
/// within its bound of the M4's, and the device announces `anisotropic-filter` where it lacks
/// Metal's own sampler or `withheld` (`samplerAnisotropy` withheld): the emulation ran; never
/// `device-anisotropic-filter`. Prints each sampler's differences under `setting`.
fn within_bounds(
setting: &str,
adjust: impl FnOnce(&mut metal2vulkan_runtime::DeviceOptions),
withheld: bool,
) {
/// within its bound of the M4's, and the device announces `anisotropic-filter`: the emulation ran;
/// never `device-anisotropic-filter`. Prints each sampler's differences under `setting`.
fn within_bounds(setting: &str, adjust: impl FnOnce(&mut metal2vulkan_runtime::DeviceOptions)) {
let cache = ScratchCache::new().unwrap();
let messages = Messages::default();
let (name, metal_sampler, outcomes) = {
let (name, outcomes) = {
let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), adjust).unwrap();
let name = format!("{} {setting}", device.name());
let metal_sampler = device
.compile_device()
.profile()
.enabled()
.properties
.contains(&VkProperty::MetalSampler);
let texture = texture(&device, &texture_bytes());
let state = pipeline(&device);
let outcomes: Vec<(&str, Bound, Differences)> = SAMPLERS
@@ -506,7 +475,7 @@ fn within_bounds(
(what, bound, differences(&got, &metal_codes(n)))
})
.collect();
(name, metal_sampler, outcomes)
(name, outcomes)
};
layer_reported_nothing_at_all(&messages);
let announced: BTreeSet<Degradation> = counts(&messages.take_notices()).into_keys().collect();
@@ -532,11 +501,9 @@ fn within_bounds(
wrong.push(format!("{what}: past {bound:?}"));
}
}
assert_eq!(
assert!(
announced.contains(&Degradation::AnisotropicFilter),
!metal_sampler || withheld,
"{name}: anisotropic-filter announced where the device lacks Metal's sampler or the \
feature"
"{name}: anisotropic-filter announced"
);
assert!(
!announced.contains(&Degradation::DeviceAnisotropicFilter),
@@ -5,29 +5,21 @@
//! or the runtime sampler of the same state.
//!
//! Metal filters a heap texture as a slot's, and through an argument buffer's sampler as through
//! a constexpr or a runtime sampler of the same state (Apple M4), and the slot's
//! emulated filter is Metal's on the measured formats (the authored cases on every venue). Outside
//! MoltenVK the heap texture's filter is emulated by the class its handle-table entry carries, else
//! the device's; a device whose filter is not Metal's (an 8-bit format's weights, a half-float
//! format's rounding) answers the two apart where the class is not carried. On MoltenVK both are
//! Metal's own sampler. On a device measured to filter an 8-bit unsigned normalized class within
//! one code of Metal (the owner's accepted difference), a slot's 2D sample of such a class through
//! normalized coordinates is the device's filter at Metal's footprint step, the heap texture's
//! Metal's emulated: the two answer within one code there ([`device_filters`]).
//! a constexpr or a runtime sampler of the same state (Apple M4). Both samples are the device's
//! own sampler's: on MoltenVK, Metal's own; on a device whose sampler is not Metal's, the device's
//! filter, which the lane judges within [`DEVICE_FILTER`] ([`device_filters`]).
//!
//! The textures are 8x8 (2D) and 4x4x4 (3D) of five formats of measured classes (8- and 16-bit
//! normalized, half-float, 32-bit float, and a packed small float), their texels deterministic
//! noise; each is sampled at coordinates across and past its edges, with `float` and `half`
//! results, through linear samplers of every address mode, a border colour, and (2D) pixel
//! coordinates; but a 3D texture's mirror-clamped axes, which the emulation does not reach (no
//! probe measured them), so that both samples are the device's, a slot's `half` result converted
//! by its class and a heap texture's not.
//! coordinates; but a 3D texture's mirror-clamped axes, which no probe measured.
use super::depth_compares::{pipeline_of, run_held, Held, Through};
use super::{layer_reported_nothing_at_all, validated_device, Messages, ScratchCache};
use crate::gpu::TEST_DEVICE;
use metal2vulkan::bind::SamplerDescriptor;
use metal2vulkan::error::DriverDeviation;
use metal2vulkan::device::VkProperty;
use metal2vulkan::metal::{
PixelFormat, SamplerAddressMode, SamplerBorderColor, SamplerMinMagFilter, TextureType,
};
@@ -38,7 +30,7 @@ use metal2vulkan_runtime::{
use std::collections::BTreeMap;
/// A constexpr sampler's words: linear filters, no mip filter, normalized coordinates clamped to
/// the edge (`engine_linear_half`'s `linear(1, false, 0)`).
/// the edge.
pub(super) const LINEAR_EDGE: u64 = 0x007b_ff00_0008_0a49;
/// The formats sampled: one of each measured class's family.
@@ -90,42 +82,28 @@ const STATES: [(SamplerAddressMode, SamplerBorderColor, bool); 7] = [
),
];
/// Whether a texture slot's linear sample of a 2D texture (not `three`) of `format`, through a
/// sampler of normalized coordinates and no `MirrorClampToEdge` axis (`plain`), is the device's
/// own filter at Metal's footprint step (`lower::sampler::native`): the device's profile takes
/// `DriverDeviation::Unorm8LinearFilter` (only under a policy of
/// `Unorm8LinearFilterPolicy::DeviceWithinOneCode`; the lanes' devices take the default, `Exact`)
/// and `format` is of an 8-bit unsigned normalized class it covers. There each channel is within
/// [`ONE_CODE`] of Metal's, where a heap texture's sample keeps Metal's filter, emulated; elsewhere
/// both are bit for bit alike.
pub(super) fn device_filters(
device: &Device,
format: PixelFormat,
three: bool,
plain: bool,
) -> bool {
!three
&& plain
&& matches!(
format,
PixelFormat::R8Unorm
| PixelFormat::RG8Unorm
| PixelFormat::RGBA8Unorm
| PixelFormat::BGRA8Unorm
)
&& device
.compile_device()
.profile()
.takes_driver_deviation(DriverDeviation::Unorm8LinearFilter)
/// Whether the device's own sampler answers a filtered sample where Metal's would differ
/// (`VkProperty::DeviceSampling`: a device whose sampler is not Metal's). Its answers are then
/// Metal's only within the bound `PrecisionNote::DeviceSampling` records, and a lane that compares
/// them judges each channel within [`DEVICE_FILTER`]; on a device that samples through Metal's own
/// sampler, bit for bit.
pub(super) fn device_filters(device: &Device) -> bool {
device
.compile_device()
.profile()
.enabled()
.properties
.contains(&VkProperty::DeviceSampling)
}
/// One code of an 8-bit unsigned normalized channel (1/255): the bound of a sample
/// [`device_filters`] holds of, the owner's accepted difference.
pub(super) const ONE_CODE: f32 = 1.0 / 255.0;
/// The bound a lane judges the device's filter by: two codes of an 8-bit channel (2/255), above
/// the largest linear filter's difference `PrecisionNote::DeviceSampling` records (1.832 codes,
/// an sRGB texture's on NVIDIA).
pub(super) const DEVICE_FILTER: f32 = 2.0 / 255.0;
/// Whether `got` answers as `want` does: bit for bit, or within [`ONE_CODE`] where `within`.
/// Whether `got` answers as `want` does: bit for bit, or within [`DEVICE_FILTER`] where `within`.
pub(super) fn alike(got: f32, want: f32, within: bool) -> bool {
got.to_bits() == want.to_bits() || (within && (got - want).abs() <= ONE_CODE)
got.to_bits() == want.to_bits() || (within && (got - want).abs() <= DEVICE_FILTER)
}
/// A texture's side: 8 in 2D, 4 in 3D.
@@ -387,8 +365,8 @@ impl Kernels {
/// Every linear sample of a heap texture (2D and 3D, `float` and `half` results; through a
/// constexpr sampler, a runtime sampler slot, and its argument buffer's sampler) answers each lane
/// bit for bit as the slot texture's sample through the same state (module docs), but within one
/// code where the slot's sample is the device's filter (`device_filters`).
/// bit for bit as the slot texture's sample through the same state (module docs), but within
/// [`DEVICE_FILTER`] where the device's own sampler filters (`device_filters`).
#[test]
fn heap_linear_samples_answer_as_slot_samples() {
let cache = ScratchCache::new().unwrap();
@@ -396,6 +374,7 @@ fn heap_linear_samples_answer_as_slot_samples() {
{
let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap();
let name = device.name().to_owned();
let within = device_filters(&device);
let mut noise = Noise(0x5eed_d499);
let mut compared = 0usize;
// The differing lanes by group (format, shape, result, sampler), with the first few.
@@ -445,17 +424,14 @@ fn heap_linear_samples_answer_as_slot_samples() {
);
judge(
format!("{result} constexpr sampler"),
device_filters(&device, format, three, true),
within,
&normalized,
&slot,
&heap,
);
for state in STATES {
// Metal reads pixel coordinates of 1D and 2D textures alone. The emulation
// does not reach a 3D texture's mirror-clamped axis, which no probe
// measured (`linear::reaches_word`): both samples are the device's there,
// and a slot's `half` result converts the device's value by its class
// where a heap texture's does not.
// Metal reads pixel coordinates of 1D and 2D textures alone; no probe
// measured a 3D texture's mirror-clamped axis.
if three && (!state.2 || state.0 == SamplerAddressMode::MirrorClampToEdge) {
continue;
}
@@ -484,10 +460,9 @@ fn heap_linear_samples_answer_as_slot_samples() {
] {
let heap =
run_held(&device, (&texture, held, runtime), state_of, &jobs, 1);
let plain = state.2 && state.0 != SamplerAddressMode::MirrorClampToEdge;
judge(
format!("{result} {what} {state:?}"),
device_filters(&device, format, three, plain),
within,
&jobs,
&slot,
&heap,
@@ -3,12 +3,11 @@
//! own tests).
//!
//! On a device without a format's ASTC block ([`decodes_astc`]) the texture holds its blocks in a
//! carrier and its reads go through a decoded twin, announced `carried-decoded-twin` once and, under
//! `DecodedTexelsPolicy::Compact`, `decoded-texel-precision` once ([`ASTC_TWINS`]). Every format's
//! texels read as Metal's after every kind of write ([`astc_texels_read_as_metal_s`], and
//! [`astc_texels_read_exactly_as_metal_s_under_exact`]): exactly under `DecodedTexelsPolicy::Exact`,
//! within 1/510 under the default, an sRGB form's exactly under either (its twin's 8-bit codes read
//! raw and decoded through Metal's table); a new texture's zero blocks as magenta; then blocks a CPU copy
//! carrier and its reads go through a decoded twin, announced `carried-decoded-twin` once and
//! `decoded-texel-precision` once ([`ASTC_TWINS`]). Every format's texels read as Metal's after
//! every kind of write ([`astc_texels_read_as_metal_s`]): an LDR form's within 1/510, an sRGB
//! form's exactly (its twin's 8-bit codes read raw and decoded through Metal's table); a new
//! texture's zero blocks as magenta; then blocks a CPU copy
//! wrote, a blit from a buffer, a fill of one block, and a copy from another ASTC texture, each
//! read by a command buffer after the write's, each decoded into the twin by a GPU decode pass (a
//! blit's always; a CPU copy's where it goes through a submission, else on the CPU, counted in
@@ -27,23 +26,23 @@
//! another decode are refused, and creation with `ShaderWrite` and `RenderTarget` usage is not
//! ([`astc_textures_the_runtime_does_not_hold_are_refused`]).
use super::degrade_notices::{counts, on_device, on_device_with};
use super::degrade_notices::{counts, on_device};
use super::{buffer_with, read_buffer, WAIT};
use crate::air_library::AirLibrary;
use metal2vulkan::bind::{AstcDecode, AstcTexels};
use metal2vulkan::device::{DecodedTexelsPolicy, FormatUsage};
use metal2vulkan::device::FormatUsage;
use metal2vulkan::metal::format::{vk_format, FormatEmulation};
use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage};
use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource};
use metal2vulkan_devtools::{engine_dir, llvm_assemble};
use metal2vulkan_runtime::{
BlitCommandEncoder, BlitOption, Buffer, CommandBufferStatus, ComputePipelineState, Degradation,
Device, DeviceOptions, Error, HeapDescriptor, HeapType, Origin, PipelineOptions, Region,
ResourceOptions, RuntimeGap, Size, Texture, TextureDescriptor,
Device, Error, HeapDescriptor, HeapType, Origin, PipelineOptions, Region, ResourceOptions,
RuntimeGap, Size, Texture, TextureDescriptor,
};
/// The kinds an ASTC texture announces on a device without its ASTC block: the decoded twin, and
/// an LDR form's 8-bit codes under `DecodedTexelsPolicy::Compact`.
/// an LDR form's 8-bit codes.
pub(super) const ASTC_TWINS: [Degradation; 2] = [
Degradation::CarriedDecodedTwin,
Degradation::DecodedTexelPrecision,
@@ -281,12 +280,12 @@ pub(super) fn download(
read_buffer(&out, 0, length).unwrap()
}
/// Every ASTC LDR format's texels read as Metal's on a device without its block, under `policy`
/// (the module docs): a new texture's, then after a CPU copy, a blit from a buffer, a fill and a
/// copy from another texture, the blocks of each coming back unchanged.
fn astc_texels_under(policy: DecodedTexelsPolicy) {
let adjust = |options: &mut DeviceOptions| options.policy.decoded_texels = policy;
on_device_with(adjust, |device, messages| {
/// Every ASTC LDR format's texels read as Metal's on a device without its block (the module
/// docs): a new texture's, then after a CPU copy, a blit from a buffer, a fill and a copy from
/// another texture, the blocks of each coming back unchanged.
#[test]
fn astc_texels_read_as_metal_s() {
on_device(|device, messages| {
let name = device.name().to_owned();
let state = reader(device);
let mut wrong = Vec::new();
@@ -326,7 +325,7 @@ fn astc_texels_under(policy: DecodedTexelsPolicy) {
for c in 0..4 {
let off = (got[c] - want[c]).abs();
most = most.max(off);
let fits = reads_as(policy, decode, got[c], want[c]);
let fits = reads_as(decode, got[c], want[c]);
if !fits && wrong.len() < 24 {
wrong.push(format!(
"{pf:?} {what} texel {t} channel {c}: {} against Metal's {}",
@@ -335,7 +334,7 @@ fn astc_texels_under(policy: DecodedTexelsPolicy) {
}
}
}
eprintln!("ASTCREAD {name} {policy:?} {pf:?} {what}: at most {most} off Metal's");
eprintln!("ASTCREAD {name} {pf:?} {what}: at most {most} off Metal's");
};
let texture = texture(device, pf, TextureUsage::SHADER_READ);
// A new texture's zero blocks are error blocks: magenta.
@@ -390,38 +389,24 @@ fn astc_texels_under(policy: DecodedTexelsPolicy) {
assert!(undecoded.is_empty(), "on {name}:\n{}", undecoded.join("\n"));
let counts = counts(&messages.take_notices());
let announced = |kind| counts.get(&kind).copied().unwrap_or(0);
let precision = twinned && policy == DecodedTexelsPolicy::Compact;
assert_eq!(
(announced(ASTC_TWINS[0]), announced(ASTC_TWINS[1])),
(usize::from(twinned), usize::from(precision)),
(usize::from(twinned), usize::from(twinned)),
"on {name}"
);
});
}
/// Whether `got` reads as Metal's `want` for a channel of a texel of `decode` under `policy` (the
/// module docs): bit for bit under `DecodedTexelsPolicy::Exact`, and an sRGB form's under either
/// (its twin's codes, decoded through Metal's table); an LDR form's within 1/510 under the
/// default.
fn reads_as(policy: DecodedTexelsPolicy, decode: AstcDecode, got: f32, want: f32) -> bool {
match (policy, decode.srgb) {
(DecodedTexelsPolicy::Exact, _) | (_, true) => got.to_bits() == want.to_bits(),
_ => (got - want).abs() <= UNORM8_BOUND,
/// Whether `got` reads as Metal's `want` for a channel of a texel of `decode` (the module docs):
/// an sRGB form's bit for bit (its twin's codes, decoded through Metal's table); an LDR form's
/// within 1/510.
fn reads_as(decode: AstcDecode, got: f32, want: f32) -> bool {
match decode.srgb {
true => got.to_bits() == want.to_bits(),
false => (got - want).abs() <= UNORM8_BOUND,
}
}
/// [`astc_texels_under`] the default, `DecodedTexelsPolicy::Compact`.
#[test]
fn astc_texels_read_as_metal_s() {
astc_texels_under(DecodedTexelsPolicy::Compact);
}
/// [`astc_texels_under`] `DecodedTexelsPolicy::Exact`, which `DevicePolicy::exact_answers` selects.
#[test]
fn astc_texels_read_exactly_as_metal_s_under_exact() {
astc_texels_under(DecodedTexelsPolicy::Exact);
}
/// The other colour space's form of an ASTC LDR format: its sRGB form's LDR one, and the other
/// way.
fn other_space(pf: PixelFormat) -> PixelFormat {
@@ -447,7 +432,6 @@ fn astc_views_in_the_other_colour_space_read_as_metal_s() {
on_device(|device, _messages| {
let name = device.name().to_owned();
let state = reader(device);
let policy = DecodedTexelsPolicy::Compact;
let mut wrong = Vec::new();
let formats = [
PixelFormat::ASTC4x4SRGB,
@@ -474,7 +458,7 @@ fn astc_views_in_the_other_colour_space_read_as_metal_s() {
let want = metal_texels(decode, blocks);
for (t, (got, want)) in got.iter().zip(&want).enumerate() {
for c in 0..4 {
let fits = reads_as(policy, decode, got[c], want[c]);
let fits = reads_as(decode, got[c], want[c]);
if !fits && wrong.len() < 24 {
wrong.push(format!(
"{pf:?} as {:?} {what} texel {t} channel {c}: {} against Metal's {}",
@@ -580,8 +580,9 @@ fn argument_dispatch(
/// While a cubic sampler state is live, a kernel that samples a texture through the sampler its
/// argument buffer holds runs. Through a linear sampler it answers every lane as the same texture
/// at a slot through that sampler (within one code where the slot's sample is the device's filter,
/// `argument_linear_samples::device_filters`), and its command buffer completes; through the cubic
/// at a slot through that sampler (within `argument_linear_samples::DEVICE_FILTER` where the
/// device's own sampler filters, `argument_linear_samples::device_filters`), and its command buffer
/// completes; through the cubic
/// state, whose bicubic filter the runtime does not emulate through an argument buffer, its command
/// buffer fails `CubicArgumentSampler`, the reach decided where the function ran.
#[test]
@@ -629,7 +630,7 @@ fn an_argument_buffer_reaches_a_cubic_sampler_only_where_it_names_one() {
&jobs,
1,
);
let within = device_filters(device, PixelFormat::RGBA8Unorm, false, true);
let within = device_filters(device);
let differ = (0..got.len())
.filter(|&i| !alike(got[i], want[i], within))
.count();
@@ -232,7 +232,6 @@ use crate::candidate::engine::variants::compile_compute_for_shape;
use crate::gpu::TEST_DEVICE;
use metal2vulkan::bind::{AstcDecode, SamplerDescriptor};
use metal2vulkan::cache::VariantKey;
use metal2vulkan::device::DecodedTexelsPolicy;
use metal2vulkan::device::VkExtension;
use metal2vulkan::device::{DriverFact, DriverWorkaround, OpBits, VkFeature, VkProperty};
use metal2vulkan::device::{SimdClass, Tier};
@@ -345,7 +344,7 @@ const RAGGED: &str = "a-ragged-thread-grid-observes-each-threadgroups-size-and-p
/// Shuffles in threadgroups of 8 threads: partial simdgroups.
const PARTIAL_SIMDGROUPS: &str = "dsm2-shuffle-past-the-thread-count-eight";
/// Kernels of float functions and arithmetic, and one of a nearest cube sample, whose stages
/// record precision notes (the cube's `CubeFaceReciprocal` on a device without
/// record precision notes (the cube's `DeviceSampling` on a device without
/// `VkProperty::MetalSampler`).
const NOTED: [&str; 3] = [
"anchor-three-transcendentals-where-rounding-cannot-reach",
@@ -2150,8 +2149,8 @@ pub(super) fn draws_depth_copies(device: &Device) -> bool {
/// (`carried-decoded-twin`), and whether the twin's codes announce `decoded-texel-precision`: an
/// ASTC format the device has no block for (`astc_textures::decodes_astc`), a PVRTC, ETC2 or
/// EAC format it has no format for, or a 4:2:2 format (every device); the notice for an ASTC LDR
/// format's 8-bit codes and an EAC 11-bit format's 16-bit ones under
/// `DecodedTexelsPolicy::Compact`, and for no other twin, whose codes are exact (an ASTC sRGB
/// format's 8-bit codes and an EAC 11-bit format's 16-bit ones, and for no other twin, whose codes
/// are exact (an ASTC sRGB
/// format's, a PVRTC format's, an 8-bit ETC2 or EAC format's, a 4:2:2 format's).
pub(super) fn twins_carried(device: &Device, pf: PixelFormat) -> [bool; 2] {
let astc = AstcDecode::of(pf).filter(|_| !decodes_astc(device, pf));
@@ -2163,11 +2162,10 @@ pub(super) fn twins_carried(device: &Device, pf: PixelFormat) -> [bool; 2] {
let etc = metal2vulkan::bind::EtcDecode::of(pf).filter(|_| decoded);
let chroma = metal2vulkan::bind::ChromaDecode::of(pf).is_some() && decoded;
let eleven = etc.is_some_and(metal2vulkan::bind::EtcDecode::eleven_bit);
let compact = device.compile_device().policy().decoded_texels == DecodedTexelsPolicy::Compact;
let ldr = astc.is_some_and(|decode| !decode.srgb);
[
astc.is_some() || pvrtc || etc.is_some() || chroma,
(ldr || eleven) && compact,
ldr || eleven,
]
}
@@ -826,8 +826,8 @@ fn passed(color: &[u8]) -> usize {
/// the value was stored as given (a blit's denormal is a zero on a driver without
/// `DriverFact::DepthImageKeepsDenormals`, and `get_bytes` reads it so; a host copy's is read as a
/// zero by such a driver's GPU copies and reads, announced as `depth-denormals`, and a sample or
/// comparison whose making records `device-texel-denormals` or `device-depth-comparison` may read
/// it so), and each depth test too where the device's test is Metal's own
/// comparison whose making records `device-sampling`, the device's sampler's answer, may read it
/// so), and each depth test too where the device's test is Metal's own
/// (`DriverFact::DepthTestComparesMagnitudes`). There, a pass with depth writes over a texture
/// holding such values stores its draw's depth where it passed and every other texel without its
/// sign, as Metal's (probe `depthstore`), and one that sets a state with depth writes but draws
@@ -888,12 +888,9 @@ fn a_stored_depth_reads_samples_and_compares_as_metal_s() {
};
let denormals = facts.contains(&DriverFact::DepthImageKeepsDenormals);
let sampled_denormals =
denormals && !kinds("sd_sample").contains(&Degradation::DeviceTexelDenormals);
let compared_denormals = denormals
&& kinds("sd_compare").is_disjoint(&BTreeSet::from([
Degradation::DeviceTexelDenormals,
Degradation::DeviceDepthComparison,
]));
denormals && !kinds("sd_sample").contains(&Degradation::DeviceSampling);
let compared_denormals =
denormals && !kinds("sd_compare").contains(&Degradation::DeviceSampling);
let readers = Readers::new(&device, &library);
let lane = Lane::new(device);
first.extend(made_render_kinds(
@@ -4,12 +4,10 @@
//!
//! On a device without the formats ([`holds_etc`] false: desktop GPUs and lavapipe) the texture
//! holds its blocks in a carrier and its reads go through a decoded twin, announced
//! `carried-decoded-twin` once and, for an 11-bit format under `DecodedTexelsPolicy::Compact`,
//! `decoded-texel-precision` once. Every format's texels read as Metal's after every kind of
//! write ([`etc_texels_read_as_metal_s`], [`etc_texels_read_exactly_as_metal_s_under_exact`]): an
//! 8-bit format's exactly under either policy (an sRGB form's colour through Metal's table, read
//! from the twin's codes), an 11-bit format's exactly under `DecodedTexelsPolicy::Exact` and within
//! half a 16-bit step under the default; a new texture's zero blocks, then blocks a CPU copy wrote,
//! `carried-decoded-twin` once and, for an 11-bit format, `decoded-texel-precision` once. Every
//! format's texels read as Metal's after every kind of write ([`etc_texels_read_as_metal_s`]): an
//! 8-bit format's exactly (an sRGB form's colour through Metal's table, read from the twin's
//! codes), an 11-bit format's within half a 16-bit step; a new texture's zero blocks, then blocks a CPU copy wrote,
//! a blit from a buffer, a fill of one block and a copy from another texture, each read by a
//! command buffer after the write's, each decoded into the twin (a blit's by a GPU decode pass, a
//! CPU copy's by one or on the CPU, counted in `WorkCounts`), and an 8-bit format's view as its
@@ -19,14 +17,12 @@
//! through its own decode (not compared), announcing neither kind.
use super::astc_textures::{blit, download, read_whole, reader, texture, upload};
use super::degrade_notices::{counts, on_device_with};
use super::degrade_notices::{counts, on_device};
use metal2vulkan::bind::{EtcDecode, EtcTexels, PvrtcDecode};
use metal2vulkan::device::{DecodedTexelsPolicy, FormatUsage};
use metal2vulkan::device::FormatUsage;
use metal2vulkan::metal::format::{srgb_raw_twin, vk_format, FormatEmulation};
use metal2vulkan::metal::{PixelFormat, TextureUsage};
use metal2vulkan_runtime::{
Degradation, Device, DeviceOptions, Error, Origin, Region, Size, Texture,
};
use metal2vulkan_runtime::{Degradation, Device, Error, Origin, Region, Size, Texture};
/// The ten ETC2 and EAC formats.
const FORMATS: [PixelFormat; 10] = [
@@ -122,12 +118,12 @@ fn other_form(pf: PixelFormat) -> PixelFormat {
}
}
/// Every ETC2 and EAC format's texels read as Metal's on a device without the formats, under
/// `policy` (the module docs): a new texture's, then after a CPU copy, a blit from a buffer, a
/// fill and a copy from another texture, the blocks of each coming back unchanged.
fn etc_texels_under(policy: DecodedTexelsPolicy) {
let adjust = |options: &mut DeviceOptions| options.policy.decoded_texels = policy;
on_device_with(adjust, |device, messages| {
/// Every ETC2 and EAC format's texels read as Metal's on a device without the formats (the module
/// docs): a new texture's, then after a CPU copy, a blit from a buffer, a fill and a copy from
/// another texture, the blocks of each coming back unchanged.
#[test]
fn etc_texels_read_as_metal_s() {
on_device(|device, messages| {
let name = device.name().to_owned();
let state = reader(device);
let mut wrong = Vec::new();
@@ -169,7 +165,7 @@ fn etc_texels_under(policy: DecodedTexelsPolicy) {
}
let got = read_whole(device, &state, texture);
let want = metal_texels(read_as, blocks);
let exact = !decode.eleven_bit() || policy == DecodedTexelsPolicy::Exact;
let exact = !decode.eleven_bit();
for (t, (got, want)) in got.iter().zip(&want).enumerate() {
for c in 0..4 {
let fits = match exact {
@@ -247,26 +243,13 @@ fn etc_texels_under(policy: DecodedTexelsPolicy) {
assert!(undecoded.is_empty(), "on {name}:\n{}", undecoded.join("\n"));
let counts = counts(&messages.take_notices());
let announced = |kind| counts.get(&kind).copied().unwrap_or(0);
let precision = eleven && policy == DecodedTexelsPolicy::Compact;
assert_eq!(
(
announced(Degradation::CarriedDecodedTwin),
announced(Degradation::DecodedTexelPrecision)
),
(usize::from(twinned), usize::from(precision)),
(usize::from(twinned), usize::from(eleven)),
"on {name}"
);
});
}
/// [`etc_texels_under`] the default, `DecodedTexelsPolicy::Compact`.
#[test]
fn etc_texels_read_as_metal_s() {
etc_texels_under(DecodedTexelsPolicy::Compact);
}
/// [`etc_texels_under`] `DecodedTexelsPolicy::Exact`, which `DevicePolicy::exact_answers` selects.
#[test]
fn etc_texels_read_exactly_as_metal_s_under_exact() {
etc_texels_under(DecodedTexelsPolicy::Exact);
}
@@ -304,48 +304,36 @@ const BELOW_ZERO: [(usize, u32); 3] = [(289, 0x8000_0001), (291, 0x8000_0002), (
const METAL_BELOW_ZERO: [f32; 2] = [80.0, 40.0];
/// Both constexpr clamp-to-zero samplers read Metal's value one, two and three units in the last
/// place below `+0.0`, under native device sampling (the default) and under the exact emulation
/// alike: the module flushes a subnormal coordinate on a border axis as Metal's texture unit
/// reads it (`lower::sampler::position::subnormal_flush`), so the device's own border test is
/// handed Metal's coordinate.
/// place below `+0.0`: the module flushes a subnormal coordinate on a border axis as Metal's
/// texture unit reads it (`lower::sampler::position::subnormal_flush`), so the device's own border
/// test is handed Metal's coordinate.
#[test]
fn clamp_to_zero_samples_just_below_zero_read_metal_s_texels() {
use metal2vulkan::device::SamplingPolicy;
let us = lanes();
for &(lane, bits) in &BELOW_ZERO {
assert_eq!(us[lane].to_bits(), bits, "lane {lane}");
}
for sampling in [SamplingPolicy::NativeDevice, SamplingPolicy::Exact] {
super::degrade_notices::on_device_with(
|options| options.policy.sampling = sampling,
|device, _| {
let float = texture(device, PixelFormat::R32Float, (WIDTH, HEIGHT), |x, y| {
((x + 16 * y) as f32).to_le_bytes()
});
let read = reds(device, &float, SamplerAddressMode::Repeat, &us);
let mut wrong = Vec::new();
for &(lane, bits) in &BELOW_ZERO {
for (column, metal) in METAL_BELOW_ZERO.into_iter().enumerate() {
let got = read[lane][column];
println!(
"BELOW-ZERO {} {sampling:?} lane {lane} ({bits:08x}) column \
{column}: read {got}, Metal {metal}",
device.name()
);
if got.to_bits() != metal.to_bits() {
wrong.push(format!(
"lane {lane} ({bits:08x}) column {column}: read {got}, Metal \
{metal}"
));
}
}
}
assert!(
wrong.is_empty(),
"{} under {sampling:?} sampling: {wrong:#?}",
super::degrade_notices::on_device(|device, _| {
let float = texture(device, PixelFormat::R32Float, (WIDTH, HEIGHT), |x, y| {
((x + 16 * y) as f32).to_le_bytes()
});
let read = reds(device, &float, SamplerAddressMode::Repeat, &us);
let mut wrong = Vec::new();
for &(lane, bits) in &BELOW_ZERO {
for (column, metal) in METAL_BELOW_ZERO.into_iter().enumerate() {
let got = read[lane][column];
println!(
"BELOW-ZERO {} lane {lane} ({bits:08x}) column {column}: read {got}, Metal \
{metal}",
device.name()
);
},
);
}
if got.to_bits() != metal.to_bits() {
wrong.push(format!(
"lane {lane} ({bits:08x}) column {column}: read {got}, Metal {metal}"
));
}
}
}
assert!(wrong.is_empty(), "{}: {wrong:#?}", device.name());
});
}
@@ -7,8 +7,8 @@
//! msf_runtime_samplers.metal`) samples its slot texture through a constexpr sampler into its
//! even outputs and through the runtime sampler at slot 0 into its odd ones. Its committed cases
//! bind four formats with a runtime sampler filtering linearly, clamped to the edge: each runs on
//! the one pipeline state, and each output is Metal's, within one code where the bound format is
//! an 8-bit unsigned normalized class the device filters itself
//! the one pipeline state, and each output is Metal's, within
//! `argument_linear_samples::DEVICE_FILTER` where the device's own sampler filters
//! (`argument_linear_samples::device_filters`). The kernel `msf_slot2d_nearest_repeat` is the same
//! macro under another constexpr sampler; its cases bind a runtime sampler filtering to the nearest
//! texel, repeating, and their odd outputs are Metal's runtime-sampler answers for those inputs.
@@ -23,7 +23,6 @@ use super::{
layer_reported_nothing_at_all, pipeline_state, public_cases, run_with, validated_device,
Messages, ScratchCache,
};
use crate::candidate::engine::resources::pixel_format;
use crate::gpu::TEST_DEVICE;
use metal2vulkan_runtime::ExecutedPipeline;
use std::collections::BTreeSet;
@@ -91,13 +90,9 @@ fn one_pipeline_per_sampler_answers_every_bound_format_as_metal() {
};
let mut variants = BTreeSet::new();
for case in &edge {
// Where both samplers' samples of the bound format are the device's filter at Metal's
// footprint step (`argument_linear_samples::device_filters`), each lane within one code.
let within = case
.compute
.textures
.values()
.all(|texture| device_filters(&device, pixel_format(texture.format), false, true));
// Where the device's own sampler filters (`argument_linear_samples::device_filters`),
// each lane within `argument_linear_samples::DEVICE_FILTER`.
let within = device_filters(&device);
let got = ran(case, &mut variants);
let lanes = |bytes: &[u8]| -> Vec<f32> {
bytes
@@ -114,7 +109,8 @@ fn one_pipeline_per_sampler_answers_every_bound_format_as_metal() {
.iter()
.zip(&metal_lanes)
.all(|(&g, &m)| alike(g, m, within)),
"{} (within one code: {within}): {got_lanes:?}, Metal's {metal_lanes:?}",
"{} (within the device's filter's bound: {within}): {got_lanes:?}, Metal's \
{metal_lanes:?}",
case.case.name
);
}
@@ -9,11 +9,9 @@
//! both matrices, and for one surface Metal's own reads of it texel by texel
//! ([`METAL_READS`]). A nearest sample at each texel's centre reads the same texel,
//! unannounced; a linear one there too, and between the texels it is Metal's filter of them,
//! unannounced (the lane's devices sample as Metal does). Under native sampling it is Metal's
//! filter under `YCbCrFilterPolicy::Exact`, through one pipeline more at the draw, and under
//! the default the device's filter of the same texels (on MoltenVK Metal's own sampler's,
//! announced), within [`DEVICE_FILTER_BOUND`] of Metal's, through the pipeline the state's
//! creation made. A function that samples handles and reaches the texture is refused, typed.
//! unannounced (the lane's devices sample as Metal does). Under native sampling it is the
//! device's filter of the same texels (on MoltenVK Metal's own sampler's, announced), within
//! [`DEVICE_FILTER_BOUND`] of Metal's, through the pipeline the state's creation made. A function that samples handles and reaches the texture is refused, typed.
//! - The texture follows writes of its planes' bytes through other textures over them, as a
//! decoder writes the planes as `R8Unorm` and `RG8Unorm` textures: in an earlier command
//! buffer, an earlier encoder of the same one, an earlier dispatch of the same encoder, and a
@@ -31,7 +29,7 @@
use super::argument_linear_samples::{self, LINEAR_EDGE};
use super::blits::SYSTEM_MEMORY;
use super::degrade_notices::{assert_once, counts, on_device, on_device_with};
use super::degrade_notices::{assert_once, counts, on_device};
use super::depth_compares::{pipeline_of, run_held, Held, Through};
use super::host_memory::{self, host_page, Mapping};
use super::{buffer_with, read_buffer};
@@ -40,7 +38,7 @@ use metal2vulkan::bind::{
ycbcr_read, ycbcr_texel, ycbcr_write, SamplerDescriptor, YCbCrCodes, YCbCrMatrix, YCbCrOutput,
YCbCrRange,
};
use metal2vulkan::device::{SamplingPolicy, VkProperty, YCbCrFilterPolicy};
use metal2vulkan::device::VkProperty;
use metal2vulkan::error::{BindError, Feature, RuntimeDriverDefect};
use metal2vulkan::metal::format::{ycbcr_format, ChromaSubsampling, YCbCrReads};
use metal2vulkan::metal::{
@@ -54,10 +52,10 @@ use metal2vulkan::pipeline::{
use metal2vulkan_devtools::llvm_assemble_text;
use metal2vulkan_runtime::{
BlitOption, Buffer, ClearColor, CommandBuffer, CommandQueue, ComputePipelineState, Deallocator,
Degradation, Device, DeviceOptions, Error, Invalid, IoSurfacePlane, IoSurfaceYCbCr, Library,
LoadAction, MappedSampling, Nil, Origin, PipelineOptions, Problem, Region,
RenderPassDescriptor, RenderPipelineState, ResourceOptions, RuntimeGap, SamplerState, Size,
StoreAction, SurfaceYCbCrMatrix, Texture, TextureDescriptor, TextureProblem,
Degradation, Device, Error, Invalid, IoSurfacePlane, IoSurfaceYCbCr, Library, LoadAction,
MappedSampling, Nil, Origin, PipelineOptions, Problem, Region, RenderPassDescriptor,
RenderPipelineState, ResourceOptions, RuntimeGap, SamplerState, Size, StoreAction,
SurfaceYCbCrMatrix, Texture, TextureDescriptor, TextureProblem,
};
use sha2::{Digest, Sha256};
use std::time::Duration;
@@ -885,8 +883,8 @@ fn half_of_step(k: u16) -> u16 {
}
/// A linear sample is Metal's filter of the exact texels, unannounced: at each texel's centre it
/// is the texel, and between texels Metal's step, on every device (the emulation of Metal's filter;
/// under MoltenVK, the slot's YCbCr variant).
/// is the texel, and between texels Metal's step, on every device (the planes read in place on a
/// device whose memory is the host's, the emulation of Metal's filter elsewhere).
#[test]
fn a_linear_sample_of_a_ycbcr_texture_is_metals() {
on_device(|device, messages| {
@@ -1251,39 +1249,18 @@ fn a_fragments_linear_sample_is_metals_through_each_sampler_and_result() {
/// `1/2048`, 0.125 (`ycbcr-filter-not-exact`).
const DEVICE_FILTER_BOUND: f32 = 0.5;
/// Under native sampling (`SamplingPolicy::NativeDevice`) and the default
/// (`YCbCrFilterPolicy::Device`), a fragment function's linear sample of a `YCBCR8_420_2P` texture
/// through a runtime sampler, with a `float` and a `half` result, takes the pipeline a draw binding
/// any other texture takes: the draw binding it makes no pipeline after the one that bound an
/// A fragment function's linear sample of a `YCBCR8_420_2P` texture through a runtime sampler,
/// with a `float` and a `half` result, takes the pipeline a draw binding any other texture takes: the draw binding it makes no pipeline after the one that bound an
/// `RGBA16Float` texture of the same texels, and its samples are that texture's bit for bit (the
/// device's filter of them), within [`DEVICE_FILTER_BOUND`] of Metal's step. On a device that
/// samples natively the module's `device-sampling` is announced and no filter notice; on one that
/// samples through Metal's own sampler `ycbcr-filter-not-exact`, once, naming the slot and the
/// format, and no `device-sampling`. A device whose memory is the host's reads the planes in place
/// instead (`ycbcr_in_place.rs`): one pipeline more, its samples Metal's step exactly, announced by
/// no filter notice, as under the exact switch.
/// no filter notice.
#[test]
fn a_ycbcr_slot_takes_the_devices_filter_in_the_pipeline_its_creation_made() {
ycbcr_draws_under(YCbCrFilterPolicy::Device);
}
/// [`a_ycbcr_slot_takes_the_devices_filter_in_the_pipeline_its_creation_made`] under Metal's
/// filter of the format (`YCbCrFilterPolicy::Exact`): on every device the draw binding the
/// texture takes the slot's YCbCr variant, one pipeline more, and its samples are Metal's step
/// exactly, announced by no filter notice.
#[test]
fn a_ycbcr_slot_takes_metals_filter_under_the_exact_switch() {
ycbcr_draws_under(YCbCrFilterPolicy::Exact);
}
/// The draws of [`a_ycbcr_slot_takes_the_devices_filter_in_the_pipeline_its_creation_made`] on a
/// device that samples natively, under `filter`.
fn ycbcr_draws_under(filter: YCbCrFilterPolicy) {
let native = |options: &mut DeviceOptions| {
options.policy.sampling = SamplingPolicy::NativeDevice;
options.policy.ycbcr_filter = filter;
};
on_device_with(native, |device, messages| {
on_device(|device, messages| {
let kernels = Kernels::new(device);
let surface = buffer_with(device, &surface_bytes(9)).unwrap();
let texture = ycbcr_texture(
@@ -1309,9 +1286,8 @@ fn ycbcr_draws_under(filter: YCbCrFilterPolicy) {
.properties
.contains(&VkProperty::MetalSampler);
// A device whose memory is the host's reads the planes in place, Metal's filter exactly,
// in the slot's in-place variant under either policy.
let in_place = super::ycbcr_in_place::reads_in_place(device);
let exact = filter == YCbCrFilterPolicy::Exact || in_place;
// in the slot's in-place variant.
let exact = super::ycbcr_in_place::reads_in_place(device);
let linear = sampler(device, SamplerMinMagFilter::Linear);
let library = device
.new_library_with_air(&llvm_assemble_text(&fragments()).unwrap())
@@ -1392,8 +1368,7 @@ pub(super) const YCBCR_FILTERS: [Degradation; 1] = [Degradation::YCbCrFilterNotE
/// A)`. On a device that samples through Metal's own sampler (`VkProperty::MetalSampler`) the
/// view composes the swizzle and the class drops the field the emulation of Metal's filter reads
/// (`TexelFormat::swizzled`): the sample takes the device's filter, Metal's own of the converted
/// texels, the class measured by no family keeping the device's sample under the slot's YCbCr
/// variant, bit for bit an `RGBA16Float` texture's of the same texels under the same swizzle, and
/// texels, the class measured by no family keeping the device's sample, bit for bit an `RGBA16Float` texture's of the same texels under the same swizzle, and
/// announces [`YCBCR_FILTERS`] once, naming the slot and the format, in place of the generic filter
/// notes, which it does not announce. Elsewhere the class is a swizzled packed one
/// (`TexelFormat::packed_exact`): the slot's view takes no swizzle, the emulation filters the
+1 -2
View File
@@ -322,7 +322,7 @@ use crate::bind::plan::slots::{
address_map_variant, anisotropic_variant, bindings, bound_value, buffer_use, check_slots,
check_sparse_textures, cross_variant, cubic_variant, large_view_candidates, mark_disjoint,
plan_buffer, psb_variant, range_variant, record_specialized, snapshot_forms, srgb_twin_variant,
srgb_variant, storage_view_variant, used_uses, ycbcr_in_place_variant, ycbcr_variant,
srgb_variant, storage_view_variant, used_uses, ycbcr_in_place_variant,
};
use crate::bind::plan::{
AccessClass, BindingPlan, BoundKind, ByteRange, DescriptorWrite, FactorSite, FactorTemplate,
@@ -2483,7 +2483,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
variant.srgb_textures = srgb_variant(profile, &p.dependencies, shape, &variant.cross_class);
variant.srgb_twins = srgb_twin_variant(profile, &variant.srgb_textures, shape);
variant.ycbcr_in_place = ycbcr_in_place_variant(&p.dependencies, shape);
variant.ycbcr_textures = ycbcr_variant(&p.dependencies, shape, &variant.ycbcr_in_place);
variant.address_maps = address_map_variant(&p.dependencies, shape);
variant.cubic_samplers = cubic_variant(&p.dependencies, shape)?;
variant.anisotropic_samplers = anisotropic_variant(&p.dependencies, shape);
+8 -28
View File
@@ -61,11 +61,8 @@
//! entry is the null entry, and every id resolves as [`lookup_host`] says. A texture no member
//! names misses. A member's flags are [`FLAG_OUT_OF_BOUNDS_ALPHA_ONE`] where its pixel format
//! has no alpha (`metal::format::out_of_bounds_alpha_one`): a module whose shader-checked heap
//! read observes the alpha takes Metal's out-of-bounds alpha from it; and its depth class
//! ([`depth_flags`]), [`FLAG_DEPTH_CODES`] for `Depth16Unorm` and [`FLAG_DEPTH_VALUES`] for
//! `Depth32Float` and `Depth32Float_Stencil8`: a module whose heap depth comparison the shader
//! makes compares as Metal does where one is set, and leaves the comparison to the device
//! elsewhere. Every other bit is 0.
//! read observes the alpha takes Metal's out-of-bounds alpha from it; and its texel class in
//! [`FLAG_TEXEL_CLASS`]. Every other bit is 0.
//! - **Heap samplers**. A heap image is sampled through a separate sampler binding
//! (`BindingSource::HeapSampler`) in set 0: a constexpr sampler is the layout's immutable sampler
//! and takes no write; a runtime `[[sampler(n)]]` is written with the sampler bound at slot `n`
@@ -140,9 +137,9 @@ use crate::device::requirements::FormatUsage;
use crate::device::DeviceProfile;
use crate::error::{BindError, Feature, Unsupported};
use crate::memory::handles::{
lookup_host, ENTRY_ELEMENT, ENTRY_FLAGS, ENTRY_ID_HI, ENTRY_ID_LO, FLAG_DEPTH_CODES,
FLAG_DEPTH_VALUES, FLAG_OUT_OF_BOUNDS_ALPHA_ONE, FLAG_TEXEL_CLASS, NEUTRAL_ELEMENT,
TABLE_CAPACITY, TABLE_ENTRY_BYTES,
lookup_host, ENTRY_ELEMENT, ENTRY_FLAGS, ENTRY_ID_HI, ENTRY_ID_LO,
FLAG_OUT_OF_BOUNDS_ALPHA_ONE, FLAG_TEXEL_CLASS, NEUTRAL_ELEMENT, TABLE_CAPACITY,
TABLE_ENTRY_BYTES,
};
use crate::metal::format::{
is_depth_stencil, sampled_type, storage_choice, vk_format, without_format_gaps, StorageUse,
@@ -537,9 +534,7 @@ pub fn heap_element(
/// The flags word of the handle-table entry of a texture of `facts`, for [`handle_entry`]: bit 1
/// where its pixel format has no alpha, so a shader-checked read past the texture takes Metal's
/// out-of-bounds alpha of 1; bit 2 for `Depth16Unorm`, whose depth comparison the shader makes on
/// codes, and bit 3 for `Depth32Float` and `Depth32Float_Stencil8`, whose comparison it makes on
/// values; bits 16 to 28 the index of the texture's texel class
/// out-of-bounds alpha of 1; bits 16 to 28 the index of the texture's texel class
/// (`metal::texel_format::heap_class_index` of its pixel format and swizzle), by which the shader
/// emulates Metal's linear filter of the texture's texels, 0 for a swizzled texture; every other
/// bit 0. A writable half-float texture whose image takes no view in another format
@@ -575,7 +570,7 @@ fn entry_flags(shape: &TextureShape) -> u32 {
let index = own_view
.unwrap_or_else(|| crate::metal::texel_format::heap_class_index(pixel_format, swizzle));
let class = index << FLAG_TEXEL_CLASS.trailing_zeros();
alpha | depth_flags(pixel_format) | (class & FLAG_TEXEL_CLASS)
alpha | (class & FLAG_TEXEL_CLASS)
}
/// The bytes of one handle-table entry (the module docs' **Tables**): resource ID `id` at heap
@@ -1785,7 +1780,7 @@ fn handle_table_bytes(
ids.push(member_id(m, &used, state)?);
}
// A member's flags: Metal's out-of-bounds read of a pixel format without alpha returns
// alpha 1, its depth class, and its texel class.
// alpha 1, and its texel class.
let flags: Vec<u32> = members.iter().map(|m| entry_flags(&m.shape)).collect();
let mut out = Vec::with_capacity(tables.len());
for t in tables {
@@ -1803,21 +1798,6 @@ fn handle_table_bytes(
Ok(out)
}
/// The depth class of a texture of pixel format `pf` in its table entry's flags: how Metal compares
/// its texels against a depth comparison's reference, as measured. `Depth16Unorm` compares codes,
/// the texel's against the reference's ([`FLAG_DEPTH_CODES`]); `Depth32Float` compares values, and
/// `Depth32Float_Stencil8` as `Depth32Float` ([`FLAG_DEPTH_VALUES`]). Every other
/// format has no measured class, 0: the device compares a heap comparison of it, which the module
/// records (`DeviceDepthComparison`).
fn depth_flags(pf: metal::PixelFormat) -> u32 {
use metal::PixelFormat as P;
match pf {
P::Depth16Unorm => FLAG_DEPTH_CODES,
P::Depth32Float | P::Depth32FloatStencil8 => FLAG_DEPTH_VALUES,
_ => 0,
}
}
/// The bytes of the sampler tables `tables`, planned for the argument samplers' `shape`, for
/// `state`: listed sampler `i` is element `i + 1`, its flags its [`SamplerWord`]. A state of
/// another shape is the plan's misuse; a list longer than the planned entries (a class past the
+1 -2
View File
@@ -63,7 +63,7 @@ use super::slots::{
address_map_variant, anisotropic_variant, bindings, bound_value, buffer_use, check_slots,
check_sparse_textures, cross_variant, cubic_variant, mark_disjoint, plan_buffer, psb_variant,
record_specialized, srgb_twin_variant, srgb_variant, storage_view_variant, used_uses,
ycbcr_in_place_variant, ycbcr_variant,
ycbcr_in_place_variant,
};
use super::{
BindingPlan, BoundKind, ComputeTemplate, DescriptorWrite, FieldLocation, LocalRules,
@@ -825,7 +825,6 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result<Bindi
);
variant.srgb_twins = srgb_twin_variant(device.profile(), &variant.srgb_textures, shape);
variant.ycbcr_in_place = ycbcr_in_place_variant(&p.dependencies, shape);
variant.ycbcr_textures = ycbcr_variant(&p.dependencies, shape, &variant.ycbcr_in_place);
variant.address_maps = address_map_variant(&p.dependencies, shape);
variant.cubic_samplers = cubic_variant(&p.dependencies, shape)?;
variant.anisotropic_samplers = anisotropic_variant(&p.dependencies, shape);
@@ -426,32 +426,6 @@ pub(crate) fn cross_variant(
.collect()
}
/// The texture slots whose linear samples the function emulates where the slot is bound in a
/// YCbCr format, on a profile that takes the variant (`RuntimeFact::YCbCrTexture`,
/// `ProfileFields::ycbcr_variant`), at which `shape` binds a texture of a two-plane YCbCr format
/// (`metal::format::ycbcr_format`), whose view Metal's sampler filters as the view's format, not as
/// Metal's filter of the YCbCr format: the plan's `VariantKey::ycbcr_textures`. A slot whose
/// planes the function reads in place (`in_place`, [`ycbcr_in_place_variant`]) reads no image
/// there, and its in-place variant's compile states no such fact, so it is not one. The variant's
/// compile states the same facts, so its plan for the same shape states the same key.
pub(crate) fn ycbcr_variant(
dependencies: &[RuntimeDependency],
shape: &BindShape,
in_place: &std::collections::BTreeSet<SlotRef>,
) -> std::collections::BTreeSet<SlotRef> {
dependencies
.iter()
.filter_map(|d| match d.fact {
RuntimeFact::YCbCrTexture { slot } if !in_place.contains(&slot) => Some(slot),
_ => None,
})
.filter(|slot| {
matches!(bound_texture(shape, *slot), Some(TextureShape::Texture { pixel_format, .. })
if metal::format::ycbcr_format(*pixel_format).is_some())
})
.collect()
}
/// The texture slots whose function reads a two-plane YCbCr texture only as its in-place form
/// reads it (`RuntimeFact::YCbCrInPlace`) at which `shape` binds a texture whose planes are read
/// in place (`TextureShape::Texture::ycbcr_in_place`), and each runtime sampler the function
@@ -741,7 +741,6 @@ fn only_a_map_that_moves_a_constexpr_mode_enters_the_variant() {
/// A slot that states the in-place form enters `VariantKey::ycbcr_in_place` only where the bound
/// texture's planes are read in place and each runtime sampler the slot samples through states a
/// filter the form reads: one filter, no anisotropy, cubic filter, comparison or other reduction.
/// Such a slot leaves `VariantKey::ycbcr_textures`, whose image it no longer reads.
#[test]
fn the_in_place_variant_takes_a_slot_its_texture_and_samplers_read() {
use crate::bind::state::{BoundSampler, SamplerDescriptor, TextureFacts};
@@ -783,17 +782,11 @@ fn the_in_place_variant_takes_a_slot_its_texture_and_samplers_read() {
fact: RuntimeFact::YCbCrInPlace { slot, samplers },
mechanism: Mechanism::Variant,
};
let image = |slot| RuntimeDependency {
fact: RuntimeFact::YCbCrTexture { slot },
mechanism: Mechanism::Variant,
};
// Slot 0 samples through constexpr samplers alone, slot 1 also through `[[sampler(3)]]`.
let deps = [
fact(texture(0), 0),
fact(texture(1), 1 << 3),
fact(texture(2), 0),
image(texture(0)),
image(texture(2)),
];
let linear = SamplerDescriptor {
min_filter: F::Linear,
@@ -804,10 +797,6 @@ fn the_in_place_variant_takes_a_slot_its_texture_and_samplers_read() {
let s = shape(linear);
let in_place = ycbcr_in_place_variant(&deps, &s);
assert_eq!(in_place, both);
assert_eq!(
ycbcr_variant(&deps, &s, &in_place),
std::collections::BTreeSet::from([texture(2)])
);
assert_eq!(
ycbcr_in_place_variant(&deps, &shape(SamplerDescriptor::new())),
both
@@ -843,8 +832,8 @@ fn the_in_place_variant_takes_a_slot_its_texture_and_samplers_read() {
"{sampler:?}"
);
}
// A slot that states no form takes none, whatever its texture.
assert!(ycbcr_in_place_variant(&[image(texture(0))], &s).is_empty());
// A stage that states no form takes none, whatever its textures.
assert!(ycbcr_in_place_variant(&[], &s).is_empty());
}
/// A stage's dropped-store word reaches the shape over the slots it binds a buffer at, and is
+1 -10
View File
@@ -1247,7 +1247,6 @@ codec_enum! {
ConstantLanes { slot },
FunctionTableRange { addressed },
TestedStorageWrites { early_tests, early_variant },
YCbCrTexture { slot },
TileThreadgroup { tile_sized },
ConstexprSampled { slot, modes },
CubicSampler { slot },
@@ -1268,10 +1267,7 @@ codec_enum! {
MovableStorageWrites { early_variant },
SynthesizedGeometry { weights, layer, viewport },
ObjectThreadgroupArena { static_bytes, payload },
ExactFormsOverCompilerLimit {
sampling,
texel_conversion
},
ExactFormsOverCompilerLimit {},
MergedDraws,
QuadPrimitiveIds,
PrivateList,
@@ -1411,12 +1407,8 @@ codec_enum! {
HalfSampleFilter,
SrgbTexelDecode,
FloatSampleFilter,
DeviceGatherFootprint,
CubeFaceReciprocal,
FunctionStorageAssumed,
QuadsCountedBeforeDiscard,
DeviceDepthComparison,
DeviceTexelDenormals,
ViewBaseTexelOffset,
DeviceColorConversion,
DeviceInterpolation,
@@ -1438,7 +1430,6 @@ codec_enum! {
DevicePointSize,
ClippedCoverageSplit,
LoopedSampleOutputs,
DeviceUnorm8LinearFilter,
HalfOutputFastMathBlend,
DeviceSampling,
NativeTranscendentals,
+3 -16
View File
@@ -60,7 +60,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 = 1879;
pub const SEMANTICS_VERSION: u32 = 1880;
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
@@ -70,7 +70,7 @@ pub const SEMANTICS_VERSION: u32 = 1879;
/// 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 = 462;
pub const ARTIFACT_FORMAT_VERSION: u32 = 463;
/// 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
@@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 462;
/// 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 = 1661;
pub const RUNTIME_VERSION: u32 = 1662;
/// 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
@@ -209,12 +209,6 @@ pub struct VariantKey {
serde(default, with = "crate::pipeline::serde_pairs")
)]
pub snapshot_textures: BTreeMap<SlotRef, SnapshotForm>,
/// Texture slots bound in a YCbCr format whose linear samples the function emulates on a
/// device that samples through Metal's own sampler: every slot of a
/// `RuntimeFact::YCbCrTexture` the shape binds in a two-plane YCbCr format
/// (`metal::format::ycbcr_format`). The plan of a pipeline compiled under it states it.
#[cfg_attr(feature = "serde", serde(default))]
pub ycbcr_textures: BTreeSet<SlotRef>,
/// Texture slots whose function reads the two-plane YCbCr texture the shape binds there in
/// place: every slot of a `RuntimeFact::YCbCrInPlace` the shape binds a texture whose planes
/// are read so (`TextureShape::Texture::ycbcr_in_place`). Each such slot binds the planes'
@@ -536,7 +530,6 @@ impl VariantKey {
&& self.srgb_textures.is_empty()
&& self.srgb_twins.is_empty()
&& self.snapshot_textures.is_empty()
&& self.ycbcr_textures.is_empty()
&& self.ycbcr_in_place.is_empty()
&& self.address_maps.is_empty()
&& !self.flat_grid
@@ -650,12 +643,6 @@ impl VariantKey {
.filter(|(s, _)| s.stage == stage)
.map(|(s, form)| (*s, *form))
.collect();
out.ycbcr_textures = self
.ycbcr_textures
.iter()
.filter(|s| s.stage == stage)
.copied()
.collect();
out.ycbcr_in_place = self
.ycbcr_in_place
.iter()
+1 -32
View File
@@ -454,12 +454,10 @@ fn the_ulong_atomic_view_fact_round_trips() {
}
/// The members format version 178 appends encode and decode, and each decodes as itself:
/// `VkFeature::Maintenance5`, the three framebuffer `VkLimit`s, and
/// `PrecisionNote::DeviceGatherFootprint`.
/// `VkFeature::Maintenance5` and the three framebuffer `VkLimit`s.
#[test]
fn the_version_178_members_round_trip() {
use crate::device::requirements::{VkFeature, VkLimit};
use crate::pipeline::artifact::PrecisionNote;
let feature = VkFeature::Maintenance5;
assert_eq!(decode::<VkFeature>(&encode(&feature)), Ok(feature));
for limit in [
@@ -469,8 +467,6 @@ fn the_version_178_members_round_trip() {
] {
assert_eq!(decode::<VkLimit>(&encode(&limit)), Ok(limit));
}
let note = PrecisionNote::DeviceGatherFootprint;
assert_eq!(decode::<PrecisionNote>(&encode(&note)), Ok(note));
}
/// The members format version 179 appends encode and decode, and each decodes as itself:
@@ -494,15 +490,6 @@ fn the_version_179_members_round_trip() {
assert_eq!(decode::<VkExtension>(&encode(&extension)), Ok(extension));
}
/// The member format version 182 appends encodes and decodes as itself:
/// `PrecisionNote::CubeFaceReciprocal`.
#[test]
fn the_version_182_members_round_trip() {
use crate::pipeline::artifact::PrecisionNote;
let note = PrecisionNote::CubeFaceReciprocal;
assert_eq!(decode::<PrecisionNote>(&encode(&note)), Ok(note));
}
/// The member format version 197 appends encodes and decodes as itself:
/// `PrecisionNote::FunctionStorageAssumed`.
#[test]
@@ -521,24 +508,6 @@ fn the_version_209_members_round_trip() {
assert_eq!(decode::<PrecisionNote>(&encode(&note)), Ok(note));
}
/// The member format version 210 appends encodes and decodes as itself:
/// `PrecisionNote::DeviceDepthComparison`.
#[test]
fn the_version_210_members_round_trip() {
use crate::pipeline::artifact::PrecisionNote;
let note = PrecisionNote::DeviceDepthComparison;
assert_eq!(decode::<PrecisionNote>(&encode(&note)), Ok(note));
}
/// The member format version 212 appends encodes and decodes as itself:
/// `PrecisionNote::DeviceTexelDenormals`.
#[test]
fn the_version_212_members_round_trip() {
use crate::pipeline::artifact::PrecisionNote;
let note = PrecisionNote::DeviceTexelDenormals;
assert_eq!(decode::<PrecisionNote>(&encode(&note)), Ok(note));
}
/// The member format version 219 appends encodes and decodes as itself:
/// `PrecisionNote::ViewBaseTexelOffset`.
#[test]
+5 -39
View File
@@ -13,7 +13,7 @@ use crate::device::description::{
use crate::device::function_storage;
use crate::device::metal::MetalDeviceProperties;
use crate::device::policy::{
ContainmentPolicy, DevicePolicy, SamplingPolicy, Unorm8LinearFilterPolicy, YCbCrFilterPolicy,
ContainmentPolicy, DevicePolicy,
};
use crate::device::profile::{
BufferAccess, Containment, CubeGradientRoute, CubeGradients, DescriptorCaps, DeviceProfile,
@@ -114,7 +114,6 @@ impl Device {
},
));
}
let deviations = accepted(deviations, &policy);
let fields = derive_fields(&desc, &policy, &deviations);
let profile = DeviceProfile::of(fields);
let metal = MetalDeviceProperties::derive(&profile, &desc.allocation);
@@ -179,19 +178,6 @@ impl Device {
}
}
/// The measured `deviations` the profile takes under `policy`: each, but the 8-bit linear
/// filter's where the policy keeps Metal's filter exact (`Unorm8LinearFilterPolicy::Exact`, the
/// default), so the translation emulates it as on an unmeasured device.
fn accepted(
mut deviations: BTreeSet<DriverDeviation>,
policy: &DevicePolicy,
) -> BTreeSet<DriverDeviation> {
if policy.unorm8_linear_filter == Unorm8LinearFilterPolicy::Exact {
deviations.remove(&DriverDeviation::Unorm8LinearFilter);
}
deviations
}
fn derive_fields(
desc: &DeviceDescription,
policy: &DevicePolicy,
@@ -337,8 +323,6 @@ fn derive_fields(
handle_domain: policy.handle_domain,
containment,
isolation: policy.isolation,
texel_conversion: policy.texel_conversion,
vertex_normalized: policy.vertex_normalized,
leaf,
subgroup: subgroup_model(desc, deviates(DriverDeviation::MetalVertexSimdgroups)),
images,
@@ -356,7 +340,7 @@ fn derive_fields(
// The feature, which both description readers list from 1.3 (core without a member),
// so the extended dynamic states a pipeline makes are exactly what it requires.
dynamic_vertex_stride: has(VkFeature::ExtendedDynamicState),
enabled: enabled_caps(desc, deviations, policy),
enabled: enabled_caps(desc, deviations),
// The measured deviation; unmeasured, the device's own functions.
float_functions: if deviates(DriverDeviation::MetalFloatFunctions) {
FloatFunctions::Metal
@@ -369,20 +353,6 @@ fn derive_fields(
} else {
NanEncoding::Native
},
// Metal's filter of a two-plane YCbCr texture through the slot's variant where the policy
// asks for it: on a device that samples through Metal's own sampler, under the YCbCr
// filter's switch or Metal's sampling; on one that samples natively, under the switch. A
// device that emulates Metal's sampler answers it in every module.
ycbcr_variant: match deviates(DriverDeviation::MetalSampler) {
true => {
policy.ycbcr_filter == YCbCrFilterPolicy::Exact
|| policy.sampling == SamplingPolicy::Exact
}
false => {
policy.sampling == SamplingPolicy::NativeDevice
&& policy.ycbcr_filter == YCbCrFilterPolicy::Exact
}
},
// The planes of a two-plane YCbCr texture read in place where the GPU reads host memory
// with no bus between: an integrated GPU's, a CPU device's.
ycbcr_in_place: matches!(
@@ -707,11 +677,7 @@ pub(crate) fn usage_class(usage: FormatUsage) -> UsageClass {
}
}
fn enabled_caps(
desc: &DeviceDescription,
deviations: &BTreeSet<DriverDeviation>,
policy: &DevicePolicy,
) -> EnabledCaps {
fn enabled_caps(desc: &DeviceDescription, deviations: &BTreeSet<DriverDeviation>) -> EnabledCaps {
let sg = &desc.subgroup;
let mut properties = BTreeSet::new();
for (stage, bit) in STAGE_BITS {
@@ -790,8 +756,8 @@ fn enabled_caps(
}
if deviations.contains(&DriverDeviation::MetalSampler) {
properties.insert(VkProperty::MetalSampler);
} else if policy.sampling == SamplingPolicy::NativeDevice {
// Native device sampling, the policy's default, where the device's sampler is not Metal's.
} else {
// Native device sampling, where the device's sampler is not Metal's.
properties.insert(VkProperty::DeviceSampling);
}
if deviations.contains(&DriverDeviation::MetalColorWrites) {
@@ -37,9 +37,6 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism {
| RuntimeFact::StorageTextureNumericType { .. } => Mechanism::Variant,
// Keyed by the slots bound in an sRGB format whose raw code the function reads.
RuntimeFact::SrgbTexture { .. } => Mechanism::Variant,
// Keyed by the slots bound in a YCbCr format whose filter the function emulates on a
// profile that takes the variant (`ProfileFields::ycbcr_variant`).
RuntimeFact::YCbCrTexture { .. } => Mechanism::Variant,
RuntimeFact::SamplerCoordinates { .. } => Mechanism::Specialization,
RuntimeFact::SamplerReduction { .. } => Mechanism::PlanTimeCheck,
RuntimeFact::ImageViewShape { .. } => Mechanism::BinderView,
+2 -3
View File
@@ -66,9 +66,8 @@ pub use enables::{EnableSet, Exposure};
pub(crate) use mechanism::mechanism;
pub use metal::{MetalDeviceProperties, SimdSupport, StageSimd};
pub use policy::{
BatchOrderPolicy, CompletionPolicy, ContainmentPolicy, DecodedTexelsPolicy, DevicePolicy,
HeapCompressionPolicy, HostPageTexturePolicy, RenderLoweringPolicy, SamplingPolicy,
TexelConversionPolicy, Unorm8LinearFilterPolicy, VertexNormalizedPolicy, YCbCrFilterPolicy,
BatchOrderPolicy, CompletionPolicy, ContainmentPolicy, DevicePolicy, HeapCompressionPolicy,
HostPageTexturePolicy, RenderLoweringPolicy,
};
pub(crate) use profile::whole_point_size;
pub use profile::{DeviceProfile, SpirvValidation};
+15 -221
View File
@@ -3,13 +3,13 @@
use crate::device::profile::{GuestIsolation, HandleDomain, PointerDomain};
/// Policy inputs of `Device::new`. Every field but `decoded_texels`, `heap_compression`,
/// `completion`, `batch_order`, `render_lowering` and `host_page_textures` can change emitted
/// code, so the profile carries it (containment as the encoding it selects) and its fingerprint
/// covers it; those six are the runtime's alone (the texels of a carried texture's decoded twin, a
/// heap's compressed texture's image, when the host sees a command buffer complete, how a batch
/// begins after the earlier ones of its queue, where a render encoder's calls are lowered, and
/// what holds a sampled texture over host pages), and no profile carries them.
/// Policy inputs of `Device::new`. Every field but `heap_compression`, `completion`,
/// `batch_order`, `render_lowering` and `host_page_textures` can change emitted code, so the
/// profile carries it (containment as the encoding it selects) and its fingerprint covers it; those
/// five are the runtime's alone (a heap's compressed texture's image, when the host sees a command
/// buffer complete, how a batch begins after the earlier ones of its queue, where a render
/// encoder's calls are lowered, and what holds a sampled texture over host pages), and no profile
/// carries them.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
@@ -22,29 +22,7 @@ pub struct DevicePolicy {
pub containment: ContainmentPolicy,
/// Whether guest shaders are isolated from each other's resources.
pub isolation: GuestIsolation,
/// Whether an 8-bit unsigned normalized texture's linear sample may be the device's own
/// filter on a device measured within one code of Metal; by default it is Metal's filter,
/// emulated exactly.
pub unorm8_linear_filter: Unorm8LinearFilterPolicy,
/// Whether a device that does not sample through Metal's own sampler samples natively (the
/// default) or emulates Metal's sampler exactly.
pub sampling: SamplingPolicy,
/// Whether, under native device sampling, a linear sample of a texture slot bound to a
/// two-plane YCbCr texture is the device's own filter of its texels (the default) or Metal's
/// filter of the format, emulated in a variant of the pipeline the draw binding it makes.
pub ycbcr_filter: YCbCrFilterPolicy,
/// Whether a texel's `float` or `half` value is the device's conversion of its codes (native
/// device sampling, the default off Apple's GPUs) or Metal's, converted exactly in the
/// shader.
pub texel_conversion: TexelConversionPolicy,
/// Whether a normalized vertex attribute's value is the device's fixed-function conversion of
/// its codes (the default) or Metal's, divided exactly in the shader.
pub vertex_normalized: VertexNormalizedPolicy,
/// Whether a texture whose format the device lacks, held in a carrier (an ASTC LDR texture,
/// or an EAC 11-bit one), samples a decoded twin of compact codes (the default) or of Metal's
/// values exactly. The runtime's choice alone: no emitted code changes.
pub decoded_texels: DecodedTexelsPolicy,
/// Whether a heap's colour texture that Metal keeps losslessly compressed, on a driver whose
/// compressed images hide writes through an alias, is the driver's compressed image (the
/// default) or one the driver keeps uncompressed in the heap's bytes. The runtime's choice
@@ -74,24 +52,16 @@ pub struct DevicePolicy {
}
impl DevicePolicy {
/// The untrusted-guest production policy: containment and isolation on, Metal's 8-bit linear
/// filter emulated exactly where the emulation runs, native device sampling (a two-plane YCbCr texture's samples among them),
/// the device's own texel conversions, compact codes in a carried texture's decoded twin, the
/// driver's compressed image of a heap's texture Metal keeps compressed, command buffers ready
/// together in one kernel submission, batches of one queue ordered by their ends where the
/// driver runs them one after another, and a sampled
/// The untrusted-guest production policy: containment and isolation on, the driver's
/// compressed image of a heap's texture Metal keeps compressed, command buffers ready together
/// in one kernel submission, batches of one queue ordered by their ends where the driver runs
/// them one after another, and a sampled
/// texture over host pages in place where the device's check passed.
pub const UNTRUSTED: DevicePolicy = DevicePolicy {
pointer_domain: PointerDomain::ResidentTable,
handle_domain: HandleDomain::Table,
containment: ContainmentPolicy::Contained,
isolation: GuestIsolation::On,
unorm8_linear_filter: Unorm8LinearFilterPolicy::Exact,
sampling: SamplingPolicy::NativeDevice,
ycbcr_filter: YCbCrFilterPolicy::Device,
texel_conversion: TexelConversionPolicy::Device,
vertex_normalized: VertexNormalizedPolicy::Device,
decoded_texels: DecodedTexelsPolicy::Compact,
heap_compression: HeapCompressionPolicy::Compressed,
completion: CompletionPolicy::Grouped,
batch_order: BatchOrderPolicy::Ends,
@@ -99,26 +69,18 @@ impl DevicePolicy {
host_page_textures: HostPageTexturePolicy::InPlace,
};
/// This policy with Metal's answer wherever the choices offer it: its texel conversions
/// ([`TexelConversionPolicy::Exact`]), its normalized vertex attributes
/// ([`VertexNormalizedPolicy::Exact`]), its filter of a
/// two-plane YCbCr texture
/// ([`YCbCrFilterPolicy::Exact`]), its decode of a carried texture's texels
/// ([`DecodedTexelsPolicy::Exact`]), a heap's texture whose bytes alias the heap's
/// This policy with Metal's answer wherever the choices offer it: a heap's texture whose bytes
/// alias the heap's
/// as written ([`HeapCompressionPolicy::Uncompressed`]), each command buffer seen complete
/// at its own end ([`CompletionPolicy::Exact`]), each batch ordered after the earlier ones of
/// its queue by
/// the accesses it depends on alone ([`BatchOrderPolicy::Exact`]), each render encoder
/// call lowered inside the call, which returns every refusal
/// ([`RenderLoweringPolicy::AtCall`]), and every texture over host pages a shadow, whose
/// copies touch its texels alone ([`HostPageTexturePolicy::Shadow`]). Sampling and every
/// other field are kept.
/// copies touch its texels alone ([`HostPageTexturePolicy::Shadow`]). Every other field is
/// kept.
pub const fn exact_answers(self) -> DevicePolicy {
DevicePolicy {
ycbcr_filter: YCbCrFilterPolicy::Exact,
texel_conversion: TexelConversionPolicy::Exact,
vertex_normalized: VertexNormalizedPolicy::Exact,
decoded_texels: DecodedTexelsPolicy::Exact,
heap_compression: HeapCompressionPolicy::Uncompressed,
completion: CompletionPolicy::Exact,
batch_order: BatchOrderPolicy::Exact,
@@ -148,174 +110,6 @@ pub enum ContainmentPolicy {
UnsafeOff,
}
/// How an 8-bit unsigned normalized texture's linear sample is filtered: a 2D texture's or 2D
/// array's sample of a slot bound in `R8Unorm`, `RG8Unorm`, `RGBA8Unorm` or `BGRA8Unorm`, through a
/// constexpr sampler with normalized coordinates or a runtime sampler slot, without comparison or
/// offset.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Unorm8LinearFilterPolicy {
/// Metal's filter, emulated exactly: the default (the owner's ruling of 2026-10-11; on the
/// consumer's fragments the device's filter bought no GPU time and cost module size and
/// making time).
#[default]
Exact,
/// The device's own filter at the centre of Metal's 1/256 footprint step, on a device
/// measured to filter the class within one code (1/255) of Metal
/// ([`DriverDeviation::Unorm8LinearFilter`](crate::error::DriverDeviation::Unorm8LinearFilter)):
/// such a sample records
/// [`PrecisionNote::DeviceUnorm8LinearFilter`](crate::pipeline::PrecisionNote::DeviceUnorm8LinearFilter)
/// and requires `VkProperty::Unorm8LinearFilter`. An unmeasured device keeps Metal's filter.
DeviceWithinOneCode,
}
/// How a device that does not sample through Metal's own sampler (MoltenVK on Apple's GPU,
/// `DriverDeviation::MetalSampler`) answers a module's samples, gathers and comparisons: natively,
/// its own sampler's answer (the default: the owner's ruling of 2026-10-11, making time before
/// exactness), or Metal's sampler, emulated exactly. A device that samples through Metal's own
/// sampler answers as Metal under either.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SamplingPolicy {
/// Native device sampling: each sample, gather and comparison goes to the device's sampler
/// as on a device whose sampler is Metal's, with no emulation of Metal's filters, footprint,
/// level selection, anisotropy or comparisons in the module. Such a module records
/// [`PrecisionNote::DeviceSampling`](crate::pipeline::PrecisionNote::DeviceSampling), whose
/// docs state the bound measured against Metal, and requires `VkProperty::DeviceSampling`.
#[default]
NativeDevice,
/// Metal's sampler, emulated exactly where the device's differs: the module's size and the
/// driver's making time grow with each sample.
Exact,
}
/// How a linear sample of a texture slot bound to a two-plane YCbCr texture
/// (`metal::format::ycbcr_format`) is filtered where the module leaves the slot's samples to the
/// device's sampler: on a device that samples natively ([`SamplingPolicy::NativeDevice`], the
/// module requiring `VkProperty::DeviceSampling`), and on one that samples through Metal's own
/// sampler (MoltenVK on Apple's GPU) under native sampling. The texture's image holds Metal's reads
/// of the planes exactly, steps of `1/2048` or `1/8192`; Metal's filter sums those steps on their
/// grid, each term truncated, at its own weights, so the device's filter of the same texels lands
/// off Metal's answer: natively within the bound `PrecisionNote::DeviceSampling` states, through
/// Metal's own sampler within one step of the grid (`ycbcr-filter-not-exact`). Under
/// [`SamplingPolicy::Exact`] every sample is Metal's, through the slot's variant on MoltenVK.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum YCbCrFilterPolicy {
/// The device's filter of the texture's texels, as for every other format (the default: the
/// owner's ruling, making time before exactness, recorded and announced): the pipeline a draw
/// binding such a texture takes is the one a draw binding any other texture takes, so the draw
/// makes none. A natively sampling module records
/// [`PrecisionNote::DeviceSampling`](crate::pipeline::PrecisionNote::DeviceSampling), whose
/// docs state the bound measured against Metal; through Metal's own sampler the module records
/// its filter note under the bound format, which the runtime announces as
/// `ycbcr-filter-not-exact` where a draw binds such a texture, and a `half` sample's one texel
/// on the grid `8192` through a runtime sampler rounds to nearest even
/// ([`PrecisionNote::HalfTexelConversion`](crate::pipeline::PrecisionNote::HalfTexelConversion)).
#[default]
Device,
/// Metal's filter of the format, emulated: a draw that binds such a texture at a slot the
/// function samples linearly takes the slot's YCbCr variant (`RuntimeFact::YCbCrTexture`), a
/// pipeline of its own, made at that draw.
Exact,
}
/// How a texel's value reaches a read, sample or gather with a `float` or `half` result on a
/// device that does not sample through Metal's own texture unit (`VkProperty::MetalSampler`). On
/// such a device Metal's conversion of a texel is emulated by a routine that tells the bound
/// format's class apart at every access, and the class is data, so no driver folds it: on the
/// consumer's fragments those routines were most of the driver's making time (296 calls
/// in `Xgc`, 311 in `A2Xghfc`).
///
/// The choice is made per access. A read's texel is this policy's. A sample's or gather's is too
/// where Metal's sampler is emulated ([`SamplingPolicy::Exact`]); under native device sampling
/// ([`SamplingPolicy::NativeDevice`], the module requiring `VkProperty::DeviceSampling`) it is the
/// device's under either policy: the device's sampler decodes its samples and gathers, and an exact
/// conversion of a sample's texel reads the runtime sampler's filter to tell one texel from a
/// filtered sum, which splits the pipeline by the bound sampler state. Measured on the RTX 5080
/// Laptop GPU, `Exact`'s reads cost the consumer's `Xgc` 3 to 5% of its making and 4 to 18% of its
/// GPU time per draw.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TexelConversionPolicy {
/// Native device sampling, the default (the owner's ruling of 2026-10-11: making time before
/// exactness off Apple's GPUs, with the bound recorded and announced): the device's `float`
/// value of each texel, and its `half` rounded to nearest even. Such an access records
/// [`PrecisionNote::DeviceTexelConversion`](crate::pipeline::PrecisionNote::DeviceTexelConversion)
/// (`float`) or
/// [`PrecisionNote::HalfTexelConversion`](crate::pipeline::PrecisionNote::HalfTexelConversion)
/// (`half`), whose docs state the bound.
#[default]
Device,
/// Metal's conversion, emulated exactly by the bound format's class, of every read, and of
/// every sample and gather where Metal's sampler is emulated: what validation compares against
/// Metal's answers.
Exact,
}
/// Who converts a **normalized** vertex attribute: the Metal vertex and attribute formats whose
/// fetch asks for a code divided by its own maximum (`UCharNormalized` through
/// `Short4Normalized`, `UChar4Normalized_BGRA`, `Int1010102Normalized`, `UInt1010102Normalized`).
///
/// Metal's conversion is `c / (2^b - 1)` unsigned and `max(c / (2^(b-1) - 1), -1)` signed, each
/// correctly rounded, which is what Vulkan's `UNORM` and `SNORM` fixed-function vertex input
/// states as well. A driver whose conversion multiplies by the reciprocal instead is one `f32`
/// ulp off at some codes, and nothing in the attribute's own Vulkan format says to correct it
/// after the load, so the exact form moves the fetch into the shader, where
/// `lower::stage_io::fetch`'s `div_exact` computes the quotient in integer arithmetic.
///
/// The choice is per attribute, and it is a variant count as much as a cost: every format the
/// device fetches in fixed function shares one module, while a pulled attribute's decode is its
/// own program. Over `cases::vertex_formats`' 45-format sweep on an Apple M3 Max
/// (`moltenvk-m3`, `tests::engine_vertex_variants`) the `float4` entry compiles 2 modules under
/// [`VertexNormalizedPolicy::Device`] and 21 under [`VertexNormalizedPolicy::Exact`], and the
/// `half4` entry 1 against 20. The runtime's own counter reads the same over the whole case on an
/// Apple M3 Max: `shader_modules_made` 2 of 45 creations against 21, and 1 against 20.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum VertexNormalizedPolicy {
/// The device's, by fixed-function vertex input of the attribute's own `UNORM` or `SNORM`
/// format (the default): one module for every format the device fetches, and the conversion
/// the driver implements.
#[default]
Device,
/// Metal's, computed exactly in the shader: the attribute is pulled from its vertex buffer
/// and its codes divided by `lower::stage_io::fetch`'s integer sequence, as a format the
/// fixed-function path cannot fetch at all already is. One module per format.
Exact,
}
/// What texels the runtime holds in the decoded twin of a texture whose blocks it holds in a
/// carrier on a device without the format (the runtime's `texture/decoded_twin.rs`), which the
/// texture's samples, reads and gathers read: an ASTC LDR texture's (`bind::AstcDecode`), and an
/// EAC 11-bit texture's (`bind::EtcDecode`). Metal reads an ASTC LDR channel as a 12-bit value,
/// `(C >> 4) / 4095` of the decode's 16-bit result, which no 8- or 16-bit texel holds; it reads
/// an EAC 11-bit channel as `c / 2047` (signed `c / 1023`), which no 16-bit normalized code
/// holds. (An ASTC sRGB texture's twin holds the 8-bit codes `C >> 8` under either, which its
/// slots read raw and decode through Metal's table, exact; so does a PVRTC texture's twin, and an
/// 8-bit ETC2 or EAC texture's.) The runtime's choice alone: no emitted code changes.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum DecodedTexelsPolicy {
/// Compact texels (the default): an ASTC LDR texture's `R8G8B8A8_UNORM` codes, 4 bytes a
/// texel, each channel the code nearest Metal's value, at most `1/510` off it. An EAC 11-bit
/// texture's 16-bit normalized codes (`R16_UNORM`, `R16_SNORM` and their two-channel forms),
/// 2 bytes a channel, each nearest Metal's value, at most half a 16-bit step off it.
/// Announced `decoded-texel-precision` where such a texture is made.
#[default]
Compact,
/// Metal's values exactly, an ASTC LDR texture's in `R32G32B32A32_SFLOAT`, 16 bytes a texel
/// (an EAC 11-bit texture's in `R32_SFLOAT` or `R32G32_SFLOAT`, 4 bytes a channel), where the
/// device samples, filters and copies into the format (else the compact texels, announced).
Exact,
}
/// The image of a heap's colour texture that Metal keeps losslessly compressed (with
/// `allowGPUOptimizedContents`, no `ShaderWrite`, `PixelFormatView` or `ShaderAtomic` usage, and a
/// level 0 of 16 texels or more a side), on a driver whose compressed images may keep their texels
+3 -31
View File
@@ -235,22 +235,6 @@ impl DeviceProfile {
.then_some(REGISTER_ALLOCATOR_MODULE_WORD_BOUND)
}
/// Whether the profile's device answers samples, gathers and comparisons with its own
/// sampler, with no emulation of Metal's in the module: a device that samples through Metal's
/// own sampler (`VkProperty::MetalSampler`, MoltenVK on Apple's GPU), whose answers are
/// Metal's, or one that samples natively (`VkProperty::DeviceSampling`,
/// `SamplingPolicy::NativeDevice`, the default), whose answers are the device's
/// ([`PrecisionNote::DeviceSampling`]). The translation's sampler sites and the runtime's
/// sampler objects (`metal::sampler`) ask it alike.
///
/// [`PrecisionNote::DeviceSampling`]: crate::pipeline::PrecisionNote::DeviceSampling
pub(crate) fn device_samples(&self) -> bool {
use crate::device::requirements::VkProperty;
let properties = &self.fields.enabled.properties;
properties.contains(&VkProperty::MetalSampler)
|| properties.contains(&VkProperty::DeviceSampling)
}
/// Whether the profile takes the driver deviation `deviation` (`device::driver_facts`): its
/// driver is measured with it on the device's GPU, so the translation relies on it. A
/// profile that does not take it compiles the conservative route the deviation's
@@ -500,11 +484,6 @@ pub struct ProfileFields {
pub handle_domain: HandleDomain,
pub containment: Containment,
pub isolation: GuestIsolation,
/// Whether a texel's value is the device's conversion or Metal's (the policy's).
pub texel_conversion: crate::device::policy::TexelConversionPolicy,
/// Whether a normalized vertex attribute is converted by fixed-function vertex input or
/// pulled and divided exactly in the shader (the policy's).
pub vertex_normalized: crate::device::policy::VertexNormalizedPolicy,
pub leaf: LeafCaps,
pub subgroup: SubgroupModel,
pub images: ImageCaps,
@@ -540,13 +519,6 @@ pub struct ProfileFields {
/// or the device's own, which the module records where Metal answers a NaN. Either way the
/// translation leaves every NaN's bits to the device.
pub nan_encoding: NanEncoding,
/// Whether a linear sample the device's sampler answers (`DeviceProfile::device_samples`)
/// takes Metal's filter of a two-plane YCbCr texture bound at its slot, through the slot's
/// YCbCr variant (`RuntimeFact::YCbCrTexture`): under the policy's `YCbCrFilterPolicy::Exact`,
/// and on a device that samples through Metal's own sampler also under `SamplingPolicy::Exact`.
/// Elsewhere the device filters such a texture as any other. Derived, so a profile that answers
/// alike under both policies keys the same.
pub ycbcr_variant: bool,
/// Whether a two-plane YCbCr texture's planes may be read in place
/// (`bind::YCbCrInPlace`): on a device whose GPU reads the planes' memory with no bus between
/// (`VkPhysicalDeviceType` integrated or CPU), a texture slot whose function reads such a
@@ -1453,7 +1425,7 @@ pub enum DriverWorkaround {
TessellatorNotMetals,
/// The driver's shader compiler faults creating a pipeline from a stage module past a word
/// bound, so a module the consumer's exact forms grow beyond it is retranslated with those
/// forms dropped until its largest stage fits ([`DeviceProfile::module_word_bound`]): the one
/// forms made native ([`DeviceProfile::module_word_bound`]): the one
/// workaround that changes no leaf encoding and refuses nothing, but bounds a module's size by
/// trading exactness for the fast form, device by device.
///
@@ -1466,8 +1438,8 @@ pub enum DriverWorkaround {
/// and faulted `W` = 60,000, 65,000 and 92,000 (900,107 words and up); and with the consumer's
/// fragments, where a module carrying exact sampling alone (455,402 words) compiled but one
/// carrying every exact answer faulted. The bound is 400,000 words, below the smallest module
/// observed to combine enough exact forms to fault, with margin: a module carrying exact
/// sampling alone above it is reduced too, since the fault point for a module's register
/// observed to combine enough exact forms to fault, with margin: a module above it is reduced,
/// since the fault point for a module's register
/// pressure is not known exactly and the fault is unrecoverable, where the reduction is a
/// logged precision note. Keyed on the driver whatever its GPU, whatever its release, in
/// `device::derive`; a release that fixes the overflow keeps it until a measurement raises or
@@ -782,9 +782,8 @@ pub enum VkProperty {
Unorm8LinearFilter,
/// Native device sampling: the module hands its samples, gathers and comparisons to the
/// device's own sampler as a device that samples through Metal's
/// ([`VkProperty::MetalSampler`]) would, on a device that does not, under
/// [`SamplingPolicy::NativeDevice`](crate::device::SamplingPolicy::NativeDevice), the
/// default. No Vulkan query reports it: the profile takes it from the policy. A module that
/// ([`VkProperty::MetalSampler`]) would, on a device that does not. No Vulkan query reports
/// it: the profile takes it wherever it lacks `VkProperty::MetalSampler`. A module that
/// leaves a sample to the device's sampler there requires it and records
/// [`PrecisionNote::DeviceSampling`](crate::pipeline::PrecisionNote::DeviceSampling).
DeviceSampling,
@@ -189,15 +189,14 @@ fn taken(p: &crate::device::DeviceProfile) -> Vec<crate::error::DriverDeviation>
/// and first-vertex indices; lavapipe's `float` color NaNs and half-float storage writes; RADV's on
/// the Radeon 780M, ANV's on the Iris Xe of RPL-P and the UHD 770 of RPL-S, and NVIDIA's on the
/// RTX 3090 and the RTX 5080 Laptop GPU, as measured there; the 8-bit linear filter's bound where
/// measured, under a policy that accepts it (`Unorm8LinearFilterPolicy::DeviceWithinOneCode`; the
/// default takes it nowhere). Every other committed profile takes none. MoltenVK on another
/// measured. Every other committed profile takes none. MoltenVK on another
/// vendor's GPU takes none, its cube routes unmeasured; another driver on Apple's vendor takes its
/// own driver's rows, with Vulkan's cube rule. `InterpolateAtOffsetCentered` follows the driver alone.
#[test]
fn the_profile_takes_the_deviations_its_driver_is_measured_with() {
use crate::device::profile::{CubeGradientRoute, CubeGradients};
use crate::device::requirements::VkProperty;
use crate::device::{Device, DevicePolicy, Unorm8LinearFilterPolicy};
use crate::device::{Device, DevicePolicy};
use crate::error::DriverDeviation as D;
use crate::spirv::testing::is_moltenvk_capture;
// The nineteen of every Apple GPU measured, and the M3 Max's graphics cube route.
@@ -261,14 +260,12 @@ fn the_profile_takes_the_deviations_its_driver_is_measured_with() {
crate::device::driver_facts::APPLE_M4 => m4_measured.clone(),
_ => apple_all.clone(),
};
// Under a policy that accepts the 8-bit linear filter's bound, so its rows are taken where
// measured; the default policy takes it nowhere (checked with the committed profiles).
let accepting = DevicePolicy {
unorm8_linear_filter: Unorm8LinearFilterPolicy::DeviceWithinOneCode,
..DevicePolicy::default()
let profile_of = |d: DeviceDescription| {
Device::new(d, DevicePolicy::default())
.expect("device")
.profile()
.clone()
};
let profile_of =
|d: DeviceDescription| Device::new(d, accepting).expect("device").profile().clone();
let centered = |p: &crate::device::DeviceProfile| {
p.fields()
.enabled
@@ -327,16 +324,6 @@ fn the_profile_takes_the_deviations_its_driver_is_measured_with() {
};
assert_eq!(taken(&p), want, "{stem}");
assert_eq!(centered(&p), !moltenvk, "{stem}");
// The default policy keeps Metal's 8-bit linear filter exact on every device.
let exact = Device::new(super::profile(stem), DevicePolicy::default())
.expect("device")
.profile()
.clone();
let want: Vec<D> = want
.into_iter()
.filter(|&d| d != D::Unorm8LinearFilter)
.collect();
assert_eq!(taken(&exact), want, "{stem} under the default policy");
}
let m3 = super::profile("moltenvk-m3");
assert_eq!(
@@ -174,7 +174,6 @@ fn every_fact() -> Vec<RuntimeFact> {
early_tests: false,
early_variant: true,
},
RuntimeFact::YCbCrTexture { slot },
RuntimeFact::TileThreadgroup { tile_sized: true },
RuntimeFact::ConstexprSampled {
slot,
@@ -265,8 +264,6 @@ fn every_fact() -> Vec<RuntimeFact> {
payload: None,
},
RuntimeFact::ExactFormsOverCompilerLimit {
sampling: true,
texel_conversion: false,
},
]
}
@@ -340,7 +337,6 @@ fn variant(f: &RuntimeFact) -> usize {
RuntimeFact::ConstantLanes { .. } => 62,
RuntimeFact::FunctionTableRange { .. } => 63,
RuntimeFact::TestedStorageWrites { .. } => 64,
RuntimeFact::YCbCrTexture { .. } => 65,
RuntimeFact::TileThreadgroup { .. } => 66,
RuntimeFact::ConstexprSampled { .. } => 67,
RuntimeFact::CubicSampler { .. } => 68,
@@ -367,8 +363,8 @@ fn variant(f: &RuntimeFact) -> usize {
RuntimeFact::QuadPrimitiveIds => 90,
RuntimeFact::RotatedWeights => 91,
RuntimeFact::PrivateList => 92,
RuntimeFact::MeshLastFirst => 93,
RuntimeFact::YCbCrInPlace { .. } => 71,
RuntimeFact::MeshLastFirst => 71,
RuntimeFact::YCbCrInPlace { .. } => 65,
}
}
@@ -376,7 +372,7 @@ fn variant(f: &RuntimeFact) -> usize {
fn mechanism_is_total_over_every_fact_and_profile() {
let facts = every_fact();
let covered: std::collections::BTreeSet<usize> = facts.iter().map(variant).collect();
assert_eq!(covered, (0..94).collect(), "every_fact misses a variant");
assert_eq!(covered, (0..93).collect(), "every_fact misses a variant");
for (stem, _) in super::committed_profiles() {
let dev = device(&stem);
let p = dev.profile();
@@ -458,7 +454,6 @@ fn mechanism_is_total_over_every_fact_and_profile() {
| RuntimeFact::MeshLastFirst
| RuntimeFact::TestedStorageWrites { .. }
| RuntimeFact::MovableStorageWrites { .. }
| RuntimeFact::YCbCrTexture { .. }
| RuntimeFact::ConstexprSampled { .. }
| RuntimeFact::CubicSampler { .. }
| RuntimeFact::AnisotropicSampler { .. }
@@ -306,57 +306,6 @@ fn below_1_2_and_contradictory_policies_are_refused() {
assert_eq!(dev.profile().fields().containment, Containment::UnsafeOff);
}
/// Each of the policy's choices between the device's answer and Metal's, with a function that
/// flips it alone: the texel conversions, a normalized vertex attribute's conversion, and the filter
/// of a two-plane YCbCr texture.
fn exactness_flips() -> [(&'static str, fn(DevicePolicy) -> DevicePolicy); 3] {
use crate::device::{
TexelConversionPolicy as T, VertexNormalizedPolicy as V, YCbCrFilterPolicy as Y,
};
[
("texel_conversion", |p| DevicePolicy {
texel_conversion: match p.texel_conversion {
T::Device => T::Exact,
T::Exact => T::Device,
},
..p
}),
("vertex_normalized", |p| DevicePolicy {
vertex_normalized: match p.vertex_normalized {
V::Device => V::Exact,
V::Exact => V::Device,
},
..p
}),
("ycbcr_filter", |p| DevicePolicy {
ycbcr_filter: match p.ycbcr_filter {
Y::Device => Y::Exact,
Y::Exact => Y::Device,
},
..p
}),
]
}
/// On MoltenVK on the M3, each choice still moves the key: the texel conversions' is the policy's
/// own field there, and the YCbCr filter's moves whether a two-plane YCbCr slot takes its variant
/// (`ProfileFields::ycbcr_variant`), Metal's sampler filtering such a texture's converted texels
/// otherwise.
#[test]
fn each_choice_keys_apart_on_moltenvk() {
let desc = profile("moltenvk-m3");
let fp = |p: DevicePolicy| {
Device::new(desc.clone(), p)
.unwrap()
.profile()
.fingerprint()
};
let base = DevicePolicy::default();
for (name, flip) in exactness_flips() {
assert_ne!(fp(flip(base)), fp(base), "{name}");
}
}
#[test]
fn fingerprint_covers_every_policy_field() {
let desc = profile("lavapipe");
@@ -374,53 +323,12 @@ fn fingerprint_covers_every_policy_field() {
variants.push(("isolation", p));
p.containment = ContainmentPolicy::UnsafeOff;
variants.push(("containment", p));
// Metal's sampler emulated exactly in place of native device sampling.
let mut p = base;
p.sampling = crate::device::SamplingPolicy::Exact;
variants.push(("sampling", p));
// Each choice between the device's answer and Metal's flipped alone, whichever the default
// takes (lavapipe measures none of Metal's forms).
for (name, flip) in exactness_flips() {
variants.push((name, flip(base)));
}
let mut seen = vec![reference];
for (name, p) in variants {
let h = fp(p);
assert!(!seen.contains(&h), "{name} did not change the fingerprint");
seen.push(h);
}
// The 8-bit linear filter's policy changes the profile, and so the fingerprint, on a device
// measured within its bound (lavapipe's capture, the RTX 5080 Laptop GPU's), through the
// property it decides; on a GPU not measured (the RTX 50 desktop GPU's capture) it changes
// nothing.
let accepting = DevicePolicy {
unorm8_linear_filter: crate::device::Unorm8LinearFilterPolicy::DeviceWithinOneCode,
..base
};
assert_ne!(fp(accepting), reference);
let unmeasured = profile("nvidia-rtx50-linux");
assert_eq!(
Device::new(unmeasured.clone(), base)
.unwrap()
.profile()
.fingerprint(),
Device::new(unmeasured, accepting)
.unwrap()
.profile()
.fingerprint(),
);
let measured = profile("nvidia-rtx5080-laptop");
assert_ne!(
Device::new(measured.clone(), base)
.unwrap()
.profile()
.fingerprint(),
Device::new(measured, accepting)
.unwrap()
.profile()
.fingerprint(),
"unorm8_linear_filter did not change the fingerprint"
);
// Description-derived fields are covered too.
let mut fewer = desc.clone();
fewer.features.remove(&VkFeature::ShaderInt8);
+2 -9
View File
@@ -782,13 +782,7 @@ pub struct AccessPlan {
/// the ids as this states, and the heap's function-table array, or, on a device without the
/// array's features, the stage's function-table snapshot, one more again.
pub function_tables: Option<function_table::TableReads>,
/// A heap depth comparison the shader makes reads its texture's depth class
/// (`lower::sampler::compared`): the handle-table search carries the depth flags
/// (`memory::handles::Lookup::Flagged`), so every heap handle carries its entry's depth flags
/// beside its element.
pub heap_depth: bool,
/// A heap texture's linear sample the function emulates reads its texel class
/// (`lower::sampler::linear`): the handle-table search carries the class's index
/// A heap texture's access reads its texel class: the handle-table search carries the class's index
/// (`memory::handles::Lookup::Flagged`), so every heap handle carries it beside its element.
pub heap_class: bool,
/// A heap texture's float write the function makes tests its texel class's index
@@ -820,10 +814,9 @@ impl AccessPlan {
/// What the function's handle-table search yields.
pub fn lookup(&self) -> crate::memory::handles::Lookup {
if self.heap_alpha || self.heap_depth || self.carries_class() {
if self.heap_alpha || self.carries_class() {
crate::memory::handles::Lookup::Flagged {
alpha: self.heap_alpha,
depth: self.heap_depth,
class: self.carries_class(),
}
} else {
@@ -3760,7 +3760,6 @@ mod blend_packed;
mod color_write;
mod divide;
mod fast;
mod float_texel;
mod fused;
mod half_texel;
mod libm;
@@ -485,86 +485,6 @@ fn the_exact_quad_answers_metals_pinned_lanes() {
);
}
/// The corner routine of a linear cube sample is Metal's made-up texel for every exact format and
/// an 8-bit sRGB format's raw steps: per lane `⌊(6 X + 5 Y + 5 Z + 8) / 16⌋` of the three texels'
/// codes (a signed format's least code read as the next one, an sRGB color lane's steps), as its
/// value on the grid, on random codes and the ranges' ends. A float format's corner is its `x`
/// face's texel, whatever the others.
#[test]
fn the_cube_corner_is_metals_made_up_texel() {
let ins = vec![v4(), v4(), v4(), u()];
let body = |fb: &mut FunctionBuilder<'_>, x: &[Value]| -> BResult<Value> {
let c = routines::define_cube(fb.module())?;
Ok(fb.call(c.corner, x)?.expect("corner"))
};
let mut rng = Rng(0x00c0_be5e_ed02_2001);
let mut formats: Vec<[Exact; 4]> = EXACT_FORMATS.iter().map(|f| [*f; 4]).collect();
formats.push(srgb_lanes());
for lanes in formats {
let mut cases = Vec::new();
for _ in 0..600 {
let cs: [[i64; 3]; 4] = std::array::from_fn(|l| {
let c = codes(lanes[l], &mut rng, 3);
[c[0], c[1], c[2]]
});
let mut case: Case = (0..3)
.map(|t| (0..4).map(|l| lanes[l].value(cs[l][t])).collect())
.collect();
case.push(vec![u64::from(lanes[0].flags)]);
cases.push((case, cs));
}
let reference = |c: &Case| {
let (_, cs) = cases.iter().find(|(k, _)| k == c)?;
let lanes = (0..4).map(|l| {
let f = lanes[l];
let [x, y, z] = cs[l].map(|c| c.max(-f.scale));
let made = (6 * x + 5 * y + 5 * z + 8).div_euclid(16);
f.result(made * (f.d / f.scale), false)
});
Some(lanes.collect())
};
let only: Vec<Case> = cases.iter().map(|(c, _)| c.clone()).collect();
check(
&format!("corner {:?}", lanes[0]),
&ins,
v4(),
&body,
&only,
&reference,
false,
);
}
// A float format's corner is the `x` face's texel, bit for bit (a NaN, an infinity, and a
// `-0` included).
let mut floats = Vec::new();
for flags in [T::LINEAR, T::HALF] {
for n in 0..64u64 {
let mut texel = |k: u64| -> Vec<u64> {
(0..4)
.map(|l| match (n + k + l) % 9 {
0 => u64::from(f32::NAN.to_bits()),
1 => u64::from(f32::NEG_INFINITY.to_bits()),
2 => u64::from((-0.0f32).to_bits()),
_ => rng.next() & 0xffff_ffff,
})
.collect()
};
let mut case: Case = vec![texel(0), texel(3), texel(5)];
case.push(vec![u64::from(flags)]);
floats.push(case);
}
}
check(
"corner float",
&ins,
v4(),
&body,
&floats,
&|c: &Case| Some(c[0].clone()),
false,
);
}
/// A float texel: finite in `[-4, 4]`, or, one tap in `special` lanes, a NaN or an infinity.
fn float_texel(rng: &mut Rng, half: bool) -> f32 {
let x = (rng.next() % 8001) as f32 / 1000.0 - 4.0;
@@ -1238,62 +1158,6 @@ fn the_float_quad_is_metals_accumulator() {
}
}
/// The accumulated linear 1D routine is Metal's accumulator ([`metal_linear`]) on random straining
/// taps, with Metal's non-finite rule on the taps of nonzero weight and the `half` result's
/// conversion.
#[test]
fn the_float_span_is_metals_accumulator() {
let ins = [v4(), v4(), u(), u()];
let mut rng = Rng(0x00b1_c0b1_c5ee_d007);
for flags in [T::LINEAR, T::HALF] {
let half_format = flags & T::HALF != 0;
let mut cases = Vec::new();
for (n, taps) in accumulated_cases(&mut rng, half_format, 2, 2000)
.into_iter()
.enumerate()
{
let k = match n % 4 {
0 => [64, 128, 192][(rng.next() % 3) as usize],
_ => fraction(&mut rng),
};
let mut c: Case = taps
.iter()
.map(|t| t.iter().map(|x| u64::from(x.to_bits())).collect())
.collect();
c.extend([vec![k], vec![u64::from(flags)]]);
cases.push((c, taps));
}
for half in [false, true] {
let body = |fb: &mut FunctionBuilder<'_>, x: &[Value]| -> BResult<Value> {
let s = routines::define_span(fb.module())?;
let h = ops::splat(fb, boolean(), u64::from(half))?;
Ok(fb
.call(s.float, &[x[0], x[1], x[2], x[3], h])?
.expect("float"))
};
let reference = |c: &Case| {
let (_, taps) = cases.iter().find(|(k, _)| k == c)?;
let w = span_weights(arg(c, 2) as u32);
let lanes = (0..4).map(|l| {
let t = [(taps[0][l], w[0]), (taps[1][l], w[1])];
u64::from(metal_linear(&t, flags, half).to_bits())
});
Some(lanes.collect())
};
let only: Vec<Case> = cases.iter().map(|(c, _)| c.clone()).collect();
check(
&format!("float span flags={flags:#x} half={half}"),
&ins,
v4(),
&body,
&only,
&reference,
false,
);
}
}
}
/// Metal's weights of a linear 3D footprint's eight taps (the `s` axis's fastest, then the `t`
/// axis's, then the `r` axis's), in units of `2^-16`: `wx · wy · wz / 256` rounded to nearest, a
/// tie up on the `t` axis's first tap in Metal's frame (its second when `flip`) and down on the
@@ -2126,15 +1990,6 @@ fn the_accumulator_answers_metals_pinned_lanes() {
Some((c, p))
})
.collect();
let spans: Vec<(Case, &Pinned)> = lanes
.iter()
.filter(|p| p.ky.is_none())
.map(|p| {
let mut c: Case = p.taps[..2].iter().map(|x| splat4(*x)).collect();
c.extend([vec![u64::from(p.kx)], vec![u64::from(p.flags)]]);
(c, p)
})
.collect();
let want = |set: &[(Case, &Pinned)], c: &Case| {
let (_, p) = set.iter().find(|(k, _)| k == c)?;
Some(vec![u64::from(p.want.to_bits()); 4])
@@ -2158,24 +2013,6 @@ fn the_accumulator_answers_metals_pinned_lanes() {
&|c| want(&quads, c),
false,
);
let span = |fb: &mut FunctionBuilder<'_>, x: &[Value]| -> BResult<Value> {
let s = routines::define_span(fb.module())?;
let h = ops::splat(fb, boolean(), 0)?;
Ok(fb
.call(s.float, &[x[0], x[1], x[2], x[3], h])?
.expect("float"))
};
let only: Vec<Case> = spans.iter().map(|(c, _)| c.clone()).collect();
let ins = [v4(), v4(), u(), u()];
check(
"pinned span lanes",
&ins,
v4(),
&span,
&only,
&|c| want(&spans, c),
false,
);
}
/// [`Routine::words`] bounds each routine set's emission.
@@ -2199,21 +2036,13 @@ fn bicubic_routines_words_bound_their_emission() {
routines::define_quad(fb.module())?;
Ok(x[0])
}) - without;
let span = size(&|fb, x| {
routines::define_span(fb.module())?;
Ok(x[0])
}) - without;
let block = size(&|fb, x| {
routines::define_block(fb.module())?;
Ok(x[0])
}) - without;
let cube = size(&|fb, x| {
routines::define_cube(fb.module())?;
Ok(x[0])
}) - without;
eprintln!(
"bicubic routines: plane {plane} words, line {line} words, quad {quad} words, span {span} \
words, block {block} words, cube {cube} words"
"bicubic routines: plane {plane} words, line {line} words, quad {quad} words, block \
{block} words"
);
assert!(
plane <= Routine::Plane.words() as usize,
@@ -2230,21 +2059,11 @@ fn bicubic_routines_words_bound_their_emission() {
"the linear 2D routines are {quad} words, bound {}",
Routine::Quad.words()
);
assert!(
span <= Routine::Span.words() as usize,
"the linear 1D routines are {span} words, bound {}",
Routine::Span.words()
);
assert!(
block <= Routine::Block.words() as usize,
"the linear 3D routines are {block} words, bound {}",
Routine::Block.words()
);
assert!(
cube <= Routine::Cube.words() as usize,
"the linear cube routines are {cube} words, bound {}",
Routine::Cube.words()
);
}
/// The scalar values a value of type `ty` holds (a vector's lanes, a struct's members' sum; a
@@ -1,384 +0,0 @@
//! Interpreter differential tests of the `float` value of one texel by the bound format's class
//! (`lower::texture::float_texel`). References are plain Rust: Metal's measured answer, a code's
//! value `c / (2^b - 1)` correctly rounded to `f32`, from each value a device reads the code as
//! (exactly, by the reciprocal, or a short channel's bits replicated to 8).
use super::*;
use crate::lower::texture::float_texel;
use crate::lower::texture::half::TexelLanes;
use crate::metal::texel_format::{texel_format, PackedTexels, TexelFormat as C};
use crate::metal::PixelFormat as P;
fn v4() -> Form {
vec(float(32), 4)
}
/// The routine at class `class` (an input) and lanes `lanes`.
fn body(lanes: TexelLanes) -> impl Fn(&mut FunctionBuilder<'_>, &[Value]) -> BResult<Value> {
move |fb, x| {
let r = float_texel::define(fb.module())?;
let lanes = lanes.value(fb)?;
float_texel::convert(fb, r, x[0], x[1], lanes)
}
}
/// Run the routine over `texels` (four lanes each, `f32` bits) at `class` and `lanes`, against
/// `reference` of each lane's index and value, bit for bit (a NaN's payload included).
fn run(
what: &str,
class: u32,
lanes: TexelLanes,
texels: &[[u64; 4]],
reference: &dyn Fn(usize, u64) -> u64,
) {
let cases: Vec<Case> = texels
.iter()
.map(|t| vec![t.to_vec(), vec![u64::from(class)]])
.collect();
check_accept(
&format!("{what} {lanes:?}"),
&[v4(), int(32)],
v4(),
&body(lanes),
&cases,
&|c| {
Some(
c[0].iter()
.enumerate()
.map(|(i, x)| reference(i, *x))
.collect(),
)
},
&|g, w| g == w,
);
}
/// `x` in groups of four lanes, the last padded with its last value.
fn quads(x: &[u64]) -> Vec<[u64; 4]> {
x.chunks(4)
.map(|c| std::array::from_fn(|i| c[i.min(c.len() - 1)]))
.collect()
}
/// `f32` bits of `c / s` correctly rounded (`f64`'s correctly rounded quotient, whose second
/// rounding cannot meet an `f32` tie: `s` is odd, so `c / s` is dyadic only where it is an
/// integer), `+0` for zero.
fn ratio_bits(c: i64, s: i64) -> u64 {
u64::from(((c as f64 / s as f64) as f32).to_bits())
}
/// The values a device reads code `c` of code scale `s` (signed where `signed`) as: its exact
/// value, the product by the reciprocal (lavapipe's), and for a 4-, 5- or 6-bit code its bits
/// replicated to 8 (ANV's and NVIDIA's `r / 255`); the least signed code reads `-1`.
fn device_values(c: i64, s: i64, signed: bool) -> Vec<u64> {
let c = if signed { c.max(-s) } else { c };
let exact = ratio_bits(c, s);
let product = u64::from((c as f32 * (1.0f32 / s as f32)).to_bits());
let mut out = vec![exact, product];
let bits = 64 - s.leading_zeros() as i64;
if !signed && (4..=6).contains(&bits) {
let r = (c << (8 - bits)) | (c >> (2 * bits - 8));
out.push(u64::from((r as f32 / 255.0).to_bits()));
}
out
}
/// A normalized family's one texel, a read's or a gather's, is its code's value correctly
/// rounded to `f32` from the value the device reads (lavapipe's reciprocal one ulp off included),
/// `-1` for the least signed code; a value that may be filtered is the device's.
#[test]
fn a_normalized_texel_is_its_codes_value() {
for (pf, s, signed) in [
(P::RGBA8Unorm, 255i64, false),
(P::RGBA8Snorm, 127, true),
(P::RGBA16Unorm, 65535, false),
(P::RGBA16Snorm, 32767, true),
] {
let class = texel_format(pf).0;
let (lo, hi) = if signed { (-s - 1, s) } else { (0, s) };
let step = if hi > 255 { 13 } else { 1 };
let codes: Vec<i64> = (lo..=hi)
.step_by(step)
.chain([lo, lo + 1, -1, 0, 1, hi - 1, hi])
.filter(|c| (lo..=hi).contains(c))
.collect();
let pairs: Vec<(u64, i64)> = codes
.iter()
.flat_map(|&c| {
device_values(c, s, signed)
.into_iter()
.map(move |v| (v, c.max(-s)))
})
.collect();
let code: std::collections::BTreeMap<u64, i64> = pairs.iter().copied().collect();
let texels = quads(&pairs.iter().map(|p| p.0).collect::<Vec<_>>());
let want = |_: usize, x: u64| ratio_bits(code[&x], s);
run(&format!("{pf:?}"), class, TexelLanes::Texel, &texels, &want);
run(
&format!("{pf:?}"),
class,
TexelLanes::Gathered(2),
&texels,
&want,
);
run(
&format!("{pf:?}"),
class,
TexelLanes::Filtered,
&texels,
&|_, x| x,
);
}
}
/// A packed format's one texel is each channel's code value `c / (2^b - 1)` correctly rounded to
/// `f32`, from whatever value the device reads it as; a gather's lanes each the gathered
/// channel's; a value that may be filtered, and a swizzled texture's class (no packed field), the
/// device's.
#[test]
fn a_packed_texel_is_its_codes_value() {
for p in PackedTexels::ALL {
let Some(scales) = p.scales() else {
continue;
};
let class = p.class().0;
let most = scales.iter().copied().max().unwrap_or(1);
let mut texels = Vec::new();
let mut codes = Vec::new();
for k in 0..=most {
let code = scales.map(|s| k % (s + 1));
let values: Vec<Vec<u64>> = (0..4)
.map(|i| device_values(i64::from(code[i]), i64::from(scales[i]), false))
.collect();
let n = values.iter().map(Vec::len).max().unwrap_or(1);
for v in 0..n {
texels.push(std::array::from_fn::<u64, 4, _>(|i| {
values[i][v.min(values[i].len() - 1)]
}));
codes.push(code);
}
}
// Each lane's value names its code on that lane's scale.
let lane_code: Vec<std::collections::BTreeMap<u64, u32>> = (0..4)
.map(|i| {
texels
.iter()
.zip(&codes)
.map(|(t, c)| (t[i], c[i]))
.collect()
})
.collect();
run(
&format!("{p:?}"),
class,
TexelLanes::Texel,
&texels,
&|i, x| ratio_bits(i64::from(lane_code[i][&x]), i64::from(scales[i])),
);
for (ch, s) in (0u32..).zip(scales) {
let pairs: Vec<(u64, u32)> = (0..=s)
.flat_map(|c| {
device_values(i64::from(c), i64::from(s), false)
.into_iter()
.map(move |v| (v, c))
})
.collect();
let code: std::collections::BTreeMap<u64, u32> = pairs.iter().copied().collect();
run(
&format!("{p:?} channel {ch}"),
class,
TexelLanes::Gathered(ch),
&quads(&pairs.iter().map(|p| p.0).collect::<Vec<_>>()),
&|_, x| ratio_bits(i64::from(code[&x]), i64::from(s)),
);
}
run(
&format!("{p:?}"),
class,
TexelLanes::Filtered,
&texels,
&|_, x| x,
);
run(
&format!("{p:?} swizzled"),
class & !C::PACKED_MASK,
TexelLanes::Texel,
&texels,
&|_, x| x,
);
// A packed normalized format's own class (its `EXACT` family beside the field) reads
// alike: its one texel the code's value, a filtered value the device's.
let full = match p {
PackedTexels::Rgb565 => P::B5G6R5Unorm,
PackedTexels::Rgb5A1 => P::BGR5A1Unorm,
PackedTexels::Rgba4 => P::ABGR4Unorm,
PackedTexels::Rgb10A2 => P::BGR10A2Unorm,
PackedTexels::SmallFloat
| PackedTexels::Argb8
| PackedTexels::YCbCr2048
| PackedTexels::YCbCr8192
| PackedTexels::YCbCrExtended8192
| PackedTexels::Rgb10A2Srgb => continue,
};
let full = texel_format(full);
assert!(full.packed_exact(), "{p:?}");
run(
&format!("{p:?} class"),
full.0,
TexelLanes::Texel,
&texels,
&|i, x| ratio_bits(i64::from(lane_code[i][&x]), i64::from(scales[i])),
);
run(
&format!("{p:?} class"),
full.0,
TexelLanes::Filtered,
&texels,
&|_, x| x,
);
}
}
/// A small or half float's one texel is the device's value, a NaN Metal's `0x7fc00000`
/// (`RG11B10Float`'s rows; a half-float texel's, whatever the device's widening
/// kept of its sign and payload); a value that may be filtered keeps its payload. Any class of
/// neither a normalized family, a packed field nor the half-float family (32-bit floats, sRGB, a
/// corner alone, `OTHER`) is the device's value, bit for bit.
#[test]
fn a_small_or_half_float_reads_metals_nan_and_other_classes_the_devices_value() {
let mut rng = Rng(0x00f1_0a7e_7e1e_0001);
let mut values: Vec<u64> = (0..4000).map(|_| rng.next() & 0xFFFF_FFFF).collect();
values.extend([
0x7fa8_0000u64,
0x7fd6_0000,
0xffc0_0001,
0x7f80_0001,
0x7f80_0000,
0xff80_0000,
0x0000_0001,
0x8000_0000,
0x3f80_0000,
]);
let texels = quads(&values);
let small = PackedTexels::SmallFloat.class().0;
let nan = |x: u64| f32::from_bits(x as u32).is_nan();
run("small float", small, TexelLanes::Texel, &texels, &|_, x| {
if nan(x) {
0x7fc0_0000
} else {
x
}
});
run(
"small float",
small,
TexelLanes::Gathered(0),
&texels,
&|_, x| if nan(x) { 0x7fc0_0000 } else { x },
);
run(
"small float",
small,
TexelLanes::Filtered,
&texels,
&|_, x| x,
);
// The half floats, and a swizzled small float (its class keeps the family alone).
let swizzled = texel_format(P::RG11B10Float).swizzled();
assert_eq!(swizzled.0 & C::PACKED_MASK, 0);
let halves = [P::R16Float, P::RG16Float, P::RGBA16Float, P::RGBX16Float]
.map(|pf| (format!("{pf:?}"), texel_format(pf).0))
.into_iter()
.chain([("swizzled RG11B10Float".to_owned(), swizzled.0)]);
for (what, class) in halves {
for lanes in [
TexelLanes::Texel,
TexelLanes::Gathered(0),
TexelLanes::Gathered(3),
] {
run(&what, class, lanes, &texels, &|_, x| {
if nan(x) {
0x7fc0_0000
} else {
x
}
});
}
run(&what, class, TexelLanes::Filtered, &texels, &|_, x| x);
}
for pf in [
P::RGBA32Float,
P::R32Float,
P::RGBA8UnormSRGB,
P::BC7RGBAUnorm,
P::RGBA8Uint,
] {
let class = texel_format(pf).0;
run(
&format!("{pf:?}"),
class,
TexelLanes::Texel,
&texels,
&|_, x| x,
);
}
}
/// A YCbCr format's one texel is the device's value, bit for bit: its view holds Metal's read
/// `k / D` exactly, and its class's `EXACT` family sums on its field's grid, never on a normalized
/// family's (whose `1/4080` step would read `k = 1` of `1/2048` as `2/4080`): each step of the grid
/// `2048`, of `8192`, and of the signed `8192` within `[-2, 2]`.
#[test]
fn a_ycbcr_texel_is_the_devices_value() {
for (pf, d, lo, hi) in [
(P::YCBCR84202P, 2048, 0, 2048),
(P::YCBCR124202P, 8192, 0, 8192),
(P::YCBCR104202PXR, 8192, -16384, 16384),
] {
let class = texel_format(pf);
assert!(
PackedTexels::of(pf).is_some_and(PackedTexels::ycbcr),
"{pf:?}"
);
let values: Vec<u64> = (lo..=hi)
.map(|k: i32| u64::from((k as f32 / d as f32).to_bits()))
.collect();
let texels = quads(&values);
for lanes in [
TexelLanes::Texel,
TexelLanes::Gathered(1),
TexelLanes::Filtered,
] {
run(&format!("{pf:?}"), class.0, lanes, &texels, &|_, x| x);
}
}
}
/// [`float_texel::ROUTINE_WORDS`] bounds the routine's emission, and
/// [`float_texel::CALL_WORDS`] a call's.
#[test]
fn the_float_texel_routine_words_bound_its_emission() {
use crate::spirv::serialize::serialize;
let ins = [v4(), int(32)];
let size = |body: Body<'_>| -> usize {
let m = kernel(&ins, v4(), body).expect("build");
serialize(m).expect("serialize").words.len()
};
let without = size(&|_, x| Ok(x[0]));
let defined = size(&|fb, x| {
float_texel::define(fb.module())?;
Ok(x[0])
}) - without;
let called = size(&body(TexelLanes::Texel)) - without - defined;
assert!(
defined as u64 <= float_texel::ROUTINE_WORDS,
"the routine is {defined} words, bound {}",
float_texel::ROUTINE_WORDS
);
assert!(
called <= float_texel::CALL_WORDS as usize,
"a call is {called} words, bound {}",
float_texel::CALL_WORDS
);
eprintln!("float texel routine: {defined} words, a call {called}");
}
@@ -67,8 +67,8 @@
//! next face, as the device projects it). Through an isotropic constexpr sampler the module takes
//! Metal's level alone, its major axis's (an isotropic cube's measured so: a footprint past
//! `1 + 3/2048` minifies, `unk_cube_grad_table`'s turning points), and one tap, where no exact
//! path of the sample's own answers it (Metal's linear filter emulated, a snapped or centred
//! coordinate): its levels are Metal's, each the device's filter.
//! path of the sample's own answers it (a snapped, fetched or centred coordinate): its levels are
//! Metal's, each the device's filter.
//!
//! **The loop**. Tap 0 is written out, and taps 1 to `n - 1` are one loop's body, which asks the
//! driver not to unroll it (`LoopControl` `DontUnroll`): each tap's arithmetic and the sum's order
@@ -102,14 +102,13 @@
//! `half` texels, at the fragment's implicit level (with a bias, through Metal's biased minor
//! axis) or with explicit gradients, or of a cube or cube array with explicit gradients, through a
//! constexpr sampler whose `maxAnisotropy` is above 1 (a cube's isotropic one too) or a runtime
//! sampler slot whose word states anisotropy, on a device that does not sample natively
//! (`DeviceProfile::device_samples`). A cube's also on one that samples through Metal's own
//! sampler where its stage's cube-gradient route is not measured
//! (`CubeGradientRoute::Unmeasured`): its explicit levels are Metal's own, which no route alters,
//! so the emulation goes where the refusal of an anisotropic sampler was. An anisotropic
//! sampler's also on a device without `samplerAnisotropy`, whatever its sampling: every Vulkan
//! sampler is isotropic there (`metal::sampler::device_anisotropy`), so the emulation goes where
//! that feature's refusal was, the device's own sampling unchanged where the feature is. A runtime
//! sampler slot whose word states anisotropy, on a device without `samplerAnisotropy`: every
//! Vulkan sampler is isotropic there (`metal::sampler::device_anisotropy`), so the emulation goes
//! where that feature's refusal was, the device's own sampling unchanged where the feature is. A
//! cube's also on a device that samples through Metal's own sampler where its stage's
//! cube-gradient route is not measured (`CubeGradientRoute::Unmeasured`): its explicit levels are
//! Metal's own, which no route alters, so the emulation goes where the refusal of an anisotropic
//! sampler was. A runtime
//! slot's degree is its `SpecKey::SamplerAnisotropy` specialization; where its word states no
//! anisotropy, the sample is the plain one. Elsewhere (a cube's implicit level, a 3D texture, a
//! comparison, an observed residency, an argument buffer's sampler) the device filters, recorded
@@ -316,7 +315,6 @@ pub(super) fn select(
use_: SamplerUse,
m: &mut Meter,
) -> Result<Option<Anisotropic>, Error> {
let device_samples = cx.profile.device_samples();
// Without `samplerAnisotropy` every Vulkan sampler is isotropic
// (`metal::sampler::device_anisotropy`): the emulation goes where it reaches an anisotropic
// sampler's sample there on every device, and the device's isotropic filter is recorded
@@ -338,7 +336,7 @@ pub(super) fn select(
let cube = matches!(lod, Lod::CubeGrad(..));
let unmeasured =
cube && cx.profile.fields().cube_gradients.route(cx.stage) == CubeGradientRoute::Unmeasured;
let native = device_samples && !unmeasured;
let native = !unmeasured;
if native && anisotropy {
cx.families.sampler.device_sampling = true;
if let Some(SamplerRef::Constexpr(words)) = sampler {
@@ -393,7 +391,7 @@ pub(super) fn select(
&& matches!(image, ImageRef::Slot(_));
// Out of reach on Metal's own sampler, the device's filter is Metal's, at the footprint the
// cube's form hands it (`PrecisionNote::CubeGradientFootprint`).
if device_samples && anisotropy && !reached {
if anisotropy && !reached {
return Ok(None);
}
let note = match reached {
@@ -11,7 +11,7 @@ use std::sync::atomic::{AtomicU64, Ordering};
use crate::air::abi::{Filter, MipFilter};
use crate::device::profile::DeviceProfile;
use crate::device::requirements::VkFeature;
use crate::device::{Device, DevicePolicy, SamplingPolicy};
use crate::device::{Device, DevicePolicy};
use crate::library::FunctionArtifact;
use crate::metal::sampler::SamplerWord;
use crate::pipeline::artifact::PrecisionNote;
@@ -20,7 +20,7 @@ use crate::pipeline::lower_inputs::LoweringInputs;
use crate::pipeline::sym::SpecKey;
use crate::pipeline::sym::{SlotClass, SlotRef, Stage};
use crate::pipeline::testing::{
compile, compile_with, link_and_validate, llvm_assemble, profile, AssembleError, EXACT_SAMPLING,
compile, compile_with, link_and_validate, llvm_assemble, profile, AssembleError,
};
const HEADER: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n";
@@ -122,8 +122,22 @@ declare { <4 x float>, i8 } @air.sample_texture_2d_grad.v4f32(ptr addrspace(1),
!6 = !{i32 3, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint2", !"air.arg_name", !"gid"}
"#;
/// Committed profile `stem` without `samplerAnisotropy`: every Vulkan sampler is isotropic there,
/// so Metal's anisotropic filter is emulated (the emulation's home besides a cube's unmeasured
/// gradient route), the profile the emulation's shape tests compile under.
fn p(stem: &str) -> DeviceProfile {
profile(stem, EXACT_SAMPLING).expect(stem)
let mut desc = crate::pipeline::testing::description(stem).expect(stem);
desc.features.remove(&VkFeature::SamplerAnisotropy);
Device::new(desc, DevicePolicy::default())
.expect(stem)
.profile()
.clone()
}
/// Committed profile `stem` as described, `samplerAnisotropy` included: the device's own
/// anisotropic filter.
fn full(stem: &str) -> DeviceProfile {
profile(stem, DevicePolicy::default()).expect(stem)
}
fn ok(bc: &[u8], entry: &str, p: &DeviceProfile) -> std::sync::Arc<FunctionArtifact> {
@@ -189,9 +203,9 @@ fn dont_unroll_loops(a: &FunctionArtifact) -> usize {
}
/// A fragment's implicit-level sample through a constexpr sampler of `maxAnisotropy` 3, 8 and 16
/// under a linear mip filter, on devices without Metal's own sampler, is Metal's filter emulated:
/// under a linear mip filter, on devices without `samplerAnisotropy`, is Metal's filter emulated:
/// no implicit-level sample, two explicit-level samples a tap, the level count queried, and
/// `AnisotropicFilter` recorded. Through Metal's own sampler (MoltenVK) the device's sample stays,
/// `AnisotropicFilter` recorded. With the feature (MoltenVK's here) the device's sample stays,
/// unrecorded. Whatever the degree Metal rounds the anisotropy to (4, 8, 16), the code holds tap 0
/// and one loop of the others that asks the driver not to unroll it.
#[test]
@@ -222,7 +236,7 @@ fn a_constexpr_anisotropic_sample_takes_metals_filter() {
"{what}"
);
}
let a = ok(&bc, "k", &p("moltenvk-m3"));
let a = ok(&bc, "k", &full("moltenvk-m3"));
assert_eq!(
count(&a, OP_IMAGE_SAMPLE_IMPLICIT_LOD),
1,
@@ -250,8 +264,9 @@ fn a_constexpr_anisotropic_sample_takes_metals_filter() {
/// alone: no `SamplerAnisotropy` specialization, no taps, no note. Under the variant naming the
/// slot it reads the slot's `SamplerAnisotropy` specialization and its word's anisotropy and mip
/// filter: the emulation (its taps' explicit-level samples) where the word states anisotropy, the
/// plain sample elsewhere, and `AnisotropicFilter` recorded under that word alone. On Metal's own
/// sampler nothing of it is compiled, and no fact is stated.
/// plain sample elsewhere, and `AnisotropicFilter` recorded under that word alone; each on a
/// device without `samplerAnisotropy`. With the feature (MoltenVK's here) nothing of it is
/// compiled, and no fact is stated.
#[test]
fn a_runtime_slot_takes_metals_filter_where_its_word_states_anisotropy() {
let Some(bc) = assemble("runtime", RUNTIME_KERNEL) else {
@@ -300,7 +315,7 @@ fn a_runtime_slot_takes_metals_filter_where_its_word_states_anisotropy() {
assert!(a.module.words.len() > base.module.words.len(), "{stem}");
assert!(noted(&a), "{stem}");
}
let a = ok(&bc, "k", &p("moltenvk-m3"));
let a = ok(&bc, "k", &full("moltenvk-m3"));
assert!(!degree(&a));
assert!(!a.facts.contains(&fact));
}
@@ -308,7 +323,8 @@ fn a_runtime_slot_takes_metals_filter_where_its_word_states_anisotropy() {
/// The binder names a slot of the `AnisotropicSampler` fact in the plan's variant where the shape
/// binds a sampler whose word states anisotropy (`maxAnisotropy` above 1), whatever its filters,
/// and nowhere else; the variant's own plan for that shape states the same key, so a draw or
/// dispatch settles on it. Its compiled pipeline round trips as the cached form.
/// dispatch settles on it. Its compiled pipeline round trips as the cached form. On lavapipe
/// without `samplerAnisotropy`, where the emulation runs.
#[test]
fn a_bound_anisotropic_sampler_asks_for_the_variant() {
use crate::bind::{
@@ -327,8 +343,9 @@ fn a_bound_anisotropic_sampler_asks_for_the_variant() {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../metal2vulkan-validation/profiles/lavapipe.json");
let text = std::fs::read_to_string(&path).expect("profile");
let desc = DeviceDescription::from_khronos_json(&text, None).expect("description");
let dev = Device::new(desc, EXACT_SAMPLING).expect("device");
let mut desc = DeviceDescription::from_khronos_json(&text, None).expect("description");
assert!(desc.features.remove(&VkFeature::SamplerAnisotropy));
let dev = Device::new(desc, DevicePolicy::default()).expect("device");
let pipeline = |inputs: &LoweringInputs| {
let function = Library::from_air(&bc)
.and_then(|lib| lib.function("k"))
@@ -459,9 +476,9 @@ const CUBE_DECL: &str = "{ <4 x float>, i8 } @air.sample_texture_cube.v4f32(ptr
/// An implicit-level sample out of the emulation's reach (a cube, a 3D texture, a depth texture, a
/// comparison) through a constexpr sampler of `maxAnisotropy` 8 is the device's own filter, and
/// records `DeviceAnisotropicFilter` (never `AnisotropicFilter`) on every device without Metal's
/// own sampler: the sample stays at its implicit level, with no tap. Through Metal's own sampler
/// (MoltenVK) neither note is recorded. The same samples through an isotropic sampler record
/// records `DeviceAnisotropicFilter` (never `AnisotropicFilter`) on every device without
/// `samplerAnisotropy`: the sample stays at its implicit level, with no tap. With the feature
/// (MoltenVK's here) neither note is recorded. The same samples through an isotropic sampler record
/// neither.
#[test]
fn an_anisotropic_sample_out_of_reach_records_the_device_filter() {
@@ -530,7 +547,7 @@ fn an_anisotropic_sample_out_of_reach_records_the_device_filter() {
assert_eq!(count(&a, OP_IMAGE_SAMPLE_EXPLICIT_LOD), 0, "{what}");
assert_eq!(dont_unroll_loops(&a), 0, "{what}");
}
let a = ok(&bc, "k", &p("moltenvk-m3"));
let a = ok(&bc, "k", &full("moltenvk-m3"));
assert!(
!a.precision
.contains(&PrecisionNote::DeviceAnisotropicFilter),
@@ -562,16 +579,15 @@ fn anisotropy_of(stem: &str, policy: DevicePolicy, withheld: bool) -> DeviceProf
}
/// Without `samplerAnisotropy` every Vulkan sampler is isotropic, so Metal's anisotropic filter is
/// emulated where its reach takes the sample under either sampling policy, the default native
/// sampling included, and the device's isotropic filter is recorded elsewhere. On lavapipe with the
/// feature withheld, a fragment's implicit-level sample through a constexpr sampler of
/// emulated where its reach takes the sample, and the device's isotropic filter is recorded
/// elsewhere. On lavapipe with the feature withheld, a fragment's implicit-level sample through a constexpr sampler of
/// `maxAnisotropy` 8 takes the taps (`AnisotropicFilter`), a runtime slot's sample states its
/// `AnisotropicSampler` fact and takes the taps under the variant (`AnisotropicFilter` under its
/// word), and a cube's implicit-level sample records `DeviceAnisotropicFilter`. With the feature,
/// native sampling compiles none of it, as before: the device's own sample, no fact, no note. An
/// isotropic sampler's sample is the device's under every setting.
/// word), and a cube's implicit-level sample records `DeviceAnisotropicFilter`. With the feature
/// the module compiles none of it: the device's own sample, no fact, no note. An isotropic
/// sampler's sample is the device's either way.
#[test]
fn without_sampler_anisotropy_metals_filter_is_emulated_under_every_sampling() {
fn without_sampler_anisotropy_metals_filter_is_emulated() {
let Some(constexpr) = assemble(
"constexpr",
&constexpr_fragment(words(MipFilter::Linear, 8)),
@@ -597,52 +613,48 @@ fn without_sampler_anisotropy_metals_filter_is_emulated_under_every_sampling() {
return;
};
let fact = RuntimeFact::AnisotropicSampler { slot: SLOT };
let native = DevicePolicy::UNTRUSTED;
assert_eq!(native.sampling, SamplingPolicy::NativeDevice);
for (policy, sampling) in [(native, "native"), (EXACT_SAMPLING, "exact")] {
for withheld in [false, true] {
let what = format!("{sampling} sampling, samplerAnisotropy withheld {withheld}");
let p = anisotropy_of("lavapipe", policy, withheld);
let device = policy.sampling == SamplingPolicy::NativeDevice && !withheld;
let a = ok(&constexpr, "k", &p);
assert_eq!(
count(&a, OP_IMAGE_SAMPLE_IMPLICIT_LOD),
usize::from(device),
"{what}"
);
assert_eq!(dont_unroll_loops(&a), usize::from(!device), "{what}");
assert_eq!(
a.precision.contains(&PrecisionNote::AnisotropicFilter),
!device,
"{what}: {:?}",
a.precision
);
let i = ok(&isotropic, "k", &p);
assert_eq!(count(&i, OP_IMAGE_SAMPLE_IMPLICIT_LOD), 1, "{what}");
for withheld in [false, true] {
let what = format!("samplerAnisotropy withheld {withheld}");
let p = anisotropy_of("lavapipe", DevicePolicy::default(), withheld);
let device = !withheld;
let a = ok(&constexpr, "k", &p);
assert_eq!(
count(&a, OP_IMAGE_SAMPLE_IMPLICIT_LOD),
usize::from(device),
"{what}"
);
assert_eq!(dont_unroll_loops(&a), usize::from(!device), "{what}");
assert_eq!(
a.precision.contains(&PrecisionNote::AnisotropicFilter),
!device,
"{what}: {:?}",
a.precision
);
let i = ok(&isotropic, "k", &p);
assert_eq!(count(&i, OP_IMAGE_SAMPLE_IMPLICIT_LOD), 1, "{what}");
assert!(
!i.precision.contains(&PrecisionNote::AnisotropicFilter),
"{what}"
);
let base = ok(&runtime, "k", &p);
assert_eq!(base.facts.contains(&fact), !device, "{what}");
if !device {
let v = ok_with(&runtime, &variant(), &p);
assert_eq!(dont_unroll_loops(&v), 1, "{what}");
assert!(
!i.precision.contains(&PrecisionNote::AnisotropicFilter),
(v.specialized.iter()).any(|n| n.note == PrecisionNote::AnisotropicFilter),
"{what}"
);
let base = ok(&runtime, "k", &p);
assert_eq!(base.facts.contains(&fact), !device, "{what}");
if !device {
let v = ok_with(&runtime, &variant(), &p);
assert_eq!(dont_unroll_loops(&v), 1, "{what}");
assert!(
(v.specialized.iter()).any(|n| n.note == PrecisionNote::AnisotropicFilter),
"{what}"
);
}
let c = ok(&cube, "k", &p);
assert_eq!(
c.precision
.contains(&PrecisionNote::DeviceAnisotropicFilter),
!device,
"{what}: {:?}",
c.precision
);
assert_eq!(dont_unroll_loops(&c), 0, "{what}");
}
let c = ok(&cube, "k", &p);
assert_eq!(
c.precision
.contains(&PrecisionNote::DeviceAnisotropicFilter),
!device,
"{what}: {:?}",
c.precision
);
assert_eq!(dont_unroll_loops(&c), 0, "{what}");
}
}
@@ -683,20 +695,26 @@ declare {{ <4 x float>, i8 }} @air.sample_texture_cube_grad.v4f32(ptr addrspace(
fn unmeasured_moltenvk() -> DeviceProfile {
let desc = crate::pipeline::testing::description("moltenvk-m3").expect("moltenvk-m3");
let route = crate::error::DriverDeviation::CubeGradientRoute;
crate::device::Device::with_deviation(desc, EXACT_SAMPLING, route, false)
.expect("device")
.profile()
.clone()
crate::device::Device::with_deviation(
desc,
crate::device::DevicePolicy::default(),
route,
false,
)
.expect("device")
.profile()
.clone()
}
/// A cube's explicit gradients through a constexpr sampler under a linear mip filter take Metal's
/// footprint in the shader on every device without Metal's own sampler: through `maxAnisotropy` 8,
/// Metal's level and taps (no gradient sample, the level count queried, tap 0 and the loop's tap
/// of two explicit levels each, `AnisotropicFilter` recorded and `CubeGradientFootprint` not);
/// through an isotropic sampler, Metal's level and its one tap (two explicit levels, no loop,
/// neither note). Through Metal's own sampler on a measured route (`moltenvk-m3`, whose kernels
/// hand Metal's own gradients) the device's gradient sample stays, unrecorded; on a route the
/// description does not state, the shader takes the footprint as off it, where the refusal was.
/// A cube's explicit gradients through a constexpr sampler of `maxAnisotropy` 8 under a linear
/// mip filter take Metal's footprint in the shader on every device without `samplerAnisotropy`,
/// and on MoltenVK where its kernel cube-gradient route is not measured: Metal's level and taps
/// (no gradient sample, the level count queried, tap 0 and the loop's tap of two explicit levels
/// each, `AnisotropicFilter` recorded and `CubeGradientFootprint` not). Through an isotropic
/// sampler the unmeasured route alone takes Metal's level and its one tap (two explicit levels, no
/// loop, neither note), where the refusal was; a device without the feature keeps its own gradient
/// sample there, at the footprint the cube's form hands it. On a measured route (`moltenvk-m3`, whose kernels hand Metal's own gradients) the
/// device's gradient sample stays, unrecorded.
#[test]
fn a_cubes_explicit_gradients_take_metals_level_and_taps() {
const GRAD: u32 = 0x4;
@@ -709,12 +727,14 @@ fn a_cubes_explicit_gradients_take_metals_level_and_taps() {
return;
};
let explicit = 2 * if taps { WRITTEN_TAPS as usize } else { 1 };
let shader = [
("lavapipe", p("lavapipe")),
("amd-rdna3-radv", p("amd-rdna3-radv")),
("intel-irisxe-anv", p("intel-irisxe-anv")),
("unmeasured MoltenVK", unmeasured_moltenvk()),
];
let mut shader = vec![("unmeasured MoltenVK", unmeasured_moltenvk())];
let mut device = vec![("moltenvk-m3", full("moltenvk-m3"))];
for stem in ["lavapipe", "amd-rdna3-radv", "intel-irisxe-anv"] {
match taps {
true => shader.push((stem, p(stem))),
false => device.push((stem, p(stem))),
}
}
for (stem, profile) in shader {
let what = format!("{what}, {stem}");
let a = ok(&bc, "k", &profile);
@@ -734,23 +754,25 @@ fn a_cubes_explicit_gradients_take_metals_level_and_taps() {
assert!(!a.precision.contains(&note), "{what}: {:?}", a.precision);
}
}
let a = ok(&bc, "k", &p("moltenvk-m3"));
assert_eq!(
count(&a, OP_IMAGE_SAMPLE_EXPLICIT_LOD),
1,
"{what}, MoltenVK"
);
assert_eq!(count(&a, OP_IMAGE_QUERY_LEVELS), 0, "{what}, MoltenVK");
assert_eq!(gradient_masks(&a), vec![GRAD], "{what}, MoltenVK");
for note in [
PrecisionNote::AnisotropicFilter,
PrecisionNote::CubeGradientFootprint,
] {
for (stem, profile) in device {
let what = format!("{what}, {stem}");
let a = ok(&bc, "k", &profile);
assert_eq!(count(&a, OP_IMAGE_SAMPLE_EXPLICIT_LOD), 1, "{what}");
assert_eq!(count(&a, OP_IMAGE_QUERY_LEVELS), 0, "{what}");
assert_eq!(gradient_masks(&a), vec![GRAD], "{what}");
assert!(
!a.precision.contains(&note),
"{what}, MoltenVK: {:?}",
!a.precision.contains(&PrecisionNote::AnisotropicFilter),
"{what}: {:?}",
a.precision
);
// Metal's own sampler on a measured route takes Metal's own gradients.
if stem == "moltenvk-m3" {
assert!(
!a.precision.contains(&PrecisionNote::CubeGradientFootprint),
"{what}: {:?}",
a.precision
);
}
}
}
}
@@ -169,8 +169,7 @@ impl Bicubic {
/// ([`PINNED_WORDS`]), and Metal's offset rule on each axis a constant offset moves
/// (`position::OFFSET_RULE_WORDS`). The estimate bounds every public bicubic fixture
/// (`the_estimate_bounds_the_bicubic_fixtures`), every raw form
/// (`the_raw_estimate_bounds_its_emission`), and the mirrored and small-level forms
/// (`mirrored_axes_and_small_levels`).
/// (`the_raw_estimate_bounds_its_emission`), and the mirrored forms (`mirrored_axes`).
pub(super) fn words(&self) -> u32 {
let (base, taps) = if self.linear_only() {
(448, 2)
@@ -1085,23 +1084,6 @@ impl At {
}
}
/// The footprint of sample `s` of sampled image `si` (image facts `image`) over `taps`, the
/// border color seen through the channels of the bound format's treatment `bits` (a
/// [`BicubicTexels`] specialization or a `TexelFormat` one, whose bits are the same, or a heap
/// element's class's bits), and the image its taps are fetched from.
pub(super) fn footprint(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
t: &Tys,
s: &Sampling,
(si, image): (SValue, CombinedImage),
bits: Bits,
taps: &Taps<'_>,
) -> BResult<(Footprint, SValue)> {
let at = At::of(cx, fb, s)?;
footprint_from(fb, t, &at, (si, image), bits, taps)
}
/// [`footprint`] of a sample whose plain data is `at`.
pub(super) fn footprint_from(
fb: &mut FunctionBuilder<'_>,
@@ -33,9 +33,6 @@
//! taps through Metal's linear accumulator (`accumulate`), and any other format's in `f32`
//! operations. Its non-finite results follow IEEE on the taps of nonzero weight: read for a
//! 32-bit float format, inferred for a half one.
//! - [`Span`] (a linear 1D sample's emulation, bilinear over taps `i` and `i + 1`). `exact` is
//! [`Line::exact`]. `float` is a 32-bit float or half format's sum through Metal's linear
//! accumulator (`accumulate`), and Metal's non-finite results on the taps of nonzero weight.
//! - [`Quad`] (a linear 2D sample's emulation, bilinear over the footprint's taps `(i, j)`, `(i +
//! 1, j)`, `(i, j + 1)`, and `(i + 1, j + 1)`). `exact` weighs each tap `wx · wy` in units of
//! `2^-16`, the integer weights `256 - k` and `k` per axis (a merged axis's fraction arrives as
@@ -49,9 +46,6 @@
//! non-finite results on the taps of nonzero weight. [`define_quad_steps`] is `exact` over taps
//! given as the integers `exact` recovers from their values, an extended-range sample's grid
//! steps from its codes ([`Routine::QuadSteps`]).
//! - [`Cube`] (a linear cube sample's emulation, beside [`Quad`]'s sums): `fold` is the texel a tap
//! reads across the faces' edges, and `corner` the tap past both edges of its face, Metal's
//! made-up texel of an exact format's codes.
//! - [`Block`] (a linear 3D sample's emulation, over the footprint's eight corners). Both routines
//! weigh each tap `wx · wy · wz / 256` rounded to nearest in units of `2^-16`, a tie up on the
//! `t` axis's first tap in Metal's frame (`block_weights`). `exact` truncates each code's term
@@ -103,7 +97,7 @@ use crate::lower::arith::ops::splat;
use crate::lower::arith::texel_round::{self, HalfRounding};
use crate::lower::arith::wide::{self, Pair};
use crate::metal::bicubic::BicubicTexels;
use crate::metal::texel_format::{CubeCorner, PackedTexels, TexelFormat};
use crate::metal::texel_format::{PackedTexels, TexelFormat};
use crate::spirv::builder::constructs::{ArmEnd, ArmFn, LoopFn, LoopSpec};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::BResult;
@@ -119,13 +113,8 @@ pub enum Routine {
Line,
/// A linear 2D (or 2D array) sample's emulation: [`Quad`].
Quad,
/// A linear 1D (or 1D array) sample's emulation: [`Span`].
Span,
/// A linear 3D sample's emulation: [`Block`].
Block,
/// A linear cube sample's taps across the faces' edges: [`Cube`], beside [`Routine::Quad`]'s
/// sums.
Cube,
/// A linear mip filter's blend of an extended-range sample's two levels: [`define_levels`].
Levels,
/// A linear 2D (or 2D array) extended-range sample's exact sum of its taps' grid steps:
@@ -136,16 +125,14 @@ pub enum Routine {
impl Routine {
/// An upper estimate of the routines' SPIR-V words, counted once per module. Measured 9062
/// words for [`Routine::Plane`] and 3663 for [`Routine::Line`] since the extended-range grids,
/// and 5218 for [`Routine::Quad`], 4014 for [`Routine::Span`], and 8103 for [`Routine::Block`]
/// and 5218 for [`Routine::Quad`] and 8103 for [`Routine::Block`]
/// since `RGB10A2Unorm_sRGB`'s field (`bicubic_routines_words_bound_their_emission`).
pub fn words(self) -> u32 {
match self {
Routine::Plane => 9216,
Routine::Line => 3712,
Routine::Quad => 5440,
Routine::Span => 4224,
Routine::Block => BLOCK_WORDS,
Routine::Cube => CUBE_WORDS,
Routine::Levels => LEVELS_WORDS,
Routine::QuadSteps => 5440,
}
@@ -157,9 +144,7 @@ impl Routine {
Routine::Plane => "sampler.bicubic.plane",
Routine::Line => "sampler.bicubic.line",
Routine::Quad => "sampler.linear.quad",
Routine::Span => "sampler.linear.span",
Routine::Block => "sampler.linear.block",
Routine::Cube => "sampler.linear.cube",
Routine::Levels => "sampler.linear.levels",
Routine::QuadSteps => "sampler.linear.quad_steps",
}
@@ -442,23 +427,6 @@ pub fn define_line(mb: &mut ModuleBuilder) -> BResult<Line> {
})
}
/// A linear 1D sample's routines (module docs).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Span {
/// `fn(t0: vec4, t1: vec4, k: u32, flags: u32, half: bool) -> vec4`: the exact sum.
pub exact: FuncId,
/// `fn(t0: vec4, t1: vec4, k: u32, flags: u32, half: bool) -> vec4`: Metal's accumulated sum.
pub float: FuncId,
}
/// Define a linear 1D sample's routines in `mb`.
pub fn define_span(mb: &mut ModuleBuilder) -> BResult<Span> {
Ok(Span {
exact: define_exact_line(mb, Packed::Field, Calls::Kept)?,
float: define_float_span(mb)?,
})
}
/// A linear 2D sample's routines (module docs). The taps are the footprint's row `j`, then row `j +
/// 1`, each from column `i`; `kx` and `ky` are the fractions' 1/256 steps.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -506,28 +474,6 @@ pub fn define_block(mb: &mut ModuleBuilder) -> BResult<Block> {
/// [`Routine::words`] of [`Routine::Block`].
const BLOCK_WORDS: u32 = 8320;
/// A linear cube sample's routines, beside [`Quad`]'s sums of the four taps.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Cube {
/// `fn(face: u32, ti: i32, tj: i32, n: i32, pick: u32, base: u32) -> uvec3`: the 2D-array
/// coordinate of the texel a tap reads, across the faces' edges (`face::define_fold`).
pub fold: FuncId,
/// `fn(x: vec4, y: vec4, z: vec4, flags: u32) -> vec4`: the tap past both edges of a face,
/// from the texels of the three faces at the cube's corner (`define_corner`).
pub corner: FuncId,
}
/// Define a linear cube sample's routines in `mb`.
pub fn define_cube(mb: &mut ModuleBuilder) -> BResult<Cube> {
Ok(Cube {
fold: super::super::face::define_fold(mb)?,
corner: define_corner(mb)?,
})
}
/// [`Routine::words`] of [`Routine::Cube`] (1,523 measured since the extended-range grids).
const CUBE_WORDS: u32 = 1536;
// ---- Types and constants ----
/// The four lanes of a texel.
@@ -717,7 +663,6 @@ fn define_weights(mb: &mut ModuleBuilder) -> BResult<FuncId> {
/// (`PackedTexels::filter_truncation`), which [`Truncation::of`] takes there. A field whose steps
/// reach `±2D` (`PackedTexels::filter_extended`) bounds its codes by `±2S` and divides by `2D`.
struct Grid {
d: Value,
scale: Value,
per: Option<Value>,
cap: Value,
@@ -731,8 +676,7 @@ struct Grid {
}
/// Whether a routine's treatment may name a packed normalized format's grids: a `TexelFormat`
/// class's routine (the linear filter's), not a `BicubicTexels` one's nor the cube corner's,
/// whose `CubeCorner` grids a packed class's corner takes.
/// class's routine (the linear filter's), not a `BicubicTexels` one's.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Packed {
Field,
@@ -777,7 +721,6 @@ fn grid(fb: &mut FunctionBuilder<'_>, t: Tys, flags: Value, packed: Packed) -> B
let Some(p) = packed_grids(fb, t, flags, packed)? else {
let cap = fb.convert(ConvOp::ConvertUToF, divisor, t.vf)?;
return Ok(Grid {
d,
scale: fb.convert(ConvOp::ConvertUToF, d, t.vf)?,
per: None,
cap,
@@ -806,7 +749,6 @@ fn grid(fb: &mut FunctionBuilder<'_>, t: Tys, flags: Value, packed: Packed) -> B
let neg_cap = fb.unary(UnOp::FNegate, cap)?;
let ones = u4(fb, 1)?;
let per = Some(fb.select(packed, p.per, ones)?);
let d = fb.select(packed, p.d, d)?;
let field_divisor = bin(fb, BinOp::IMul, p.d, span)?;
let divisor = fb.select(packed, field_divisor, divisor)?;
let span = fb.convert(ConvOp::ConvertUToF, span, t.vf)?;
@@ -814,7 +756,6 @@ fn grid(fb: &mut FunctionBuilder<'_>, t: Tys, flags: Value, packed: Packed) -> B
let rounds_away = bin(fb, BinOp::LogicalAnd, packed, p.away)?;
let away = fb.select(rounds_away, color_lanes, away)?;
Ok(Grid {
d,
scale,
per,
cap,
@@ -1261,90 +1202,6 @@ impl Truncation {
}
}
/// `fn(x, y, z, flags) -> vec4` ([`Cube::corner`]): the tap a linear cube sample reads past both
/// edges of its face, from `x`, `y`, and `z`, the texels at the cube's corner of the faces of the
/// `x`, `y`, and `z` axes. An `EXACT` format's tap is a texel Metal makes up: on each lane `⌊(6 X +
/// 5 Y + 5 Z + 8) / 16⌋` of the three texels' codes (an sRGB color lane's table steps, a signed
/// format's least code read as the next one, as [`code`] reads it), handed on as its value on the
/// format's grid, which the sums recover exactly. In grid units an 8-bit lane's code is `16 ·
/// code`, so its sum is shifted by 4 more and back. A format of a `CubeCorner` with grids (its
/// `TexelFormat::CORNER` field) makes up the same texel of its codes on each lane's grid. Any other
/// format's is `x`.
fn define_corner(mb: &mut ModuleBuilder) -> BResult<FuncId> {
let t = types(mb)?;
let mut fb = mb.routine(t.vf)?;
let x = fb.param(t.vf)?;
let y = fb.param(t.vf)?;
let z = fb.param(t.vf)?;
let flags = fb.param(t.u)?;
let fb_ = &mut fb;
let g = grid(fb_, t, flags, Packed::No)?;
let wide16 = flag(fb_, flags, BicubicTexels::WIDE16)?;
let srgb = flag(fb_, flags, BicubicTexels::SRGB)?;
// A cube corner outside the families: its codes on each lane's grid `D` of the field's
// `CubeCorner` (`RoundEven(v · D)`, clamped into `[-D, D]`), whose made-up code is the texel.
let (coded, corner_d) = corner_grids(fb_, &t, flags)?;
let d = fb_.select(coded, corner_d, g.d)?;
let df = fb_.convert(ConvOp::ConvertUToF, d, t.vf)?;
let neg_df = fb_.unary(UnOp::FNegate, df)?;
// Per lane, the constant of a 16-bit lane or an sRGB color lane (`fine`), of an 8-bit lane
// (`coarse`), or of a cube corner's lane (`corner`).
let lanes = |fb: &mut FunctionBuilder<'_>, fine: u32, coarse: u32, corner: u32| {
let (f, c) = (u1(fb, fine)?, u1(fb, coarse)?);
let plain = fb.select(wide16, f, c)?;
let plain = broadcast(fb, t.vu, plain)?;
let steps = fb.composite_construct(t.vu, &[f, f, f, c])?;
let family = fb.select(srgb, steps, plain)?;
let corner = u4(fb, corner)?;
fb.select(coded, corner, family)
};
let mut sum = lanes(fb_, 1 << 3, 1 << 7, 1 << 3)?;
for (v, w) in [(x, 6), (y, 5), (z, 5)] {
let c = texel_round::grid_step(fb_, fform(LANES), v, df, neg_df)?;
let w = u4(fb_, w)?;
let term = bin(fb_, BinOp::IMul, c, w)?;
sum = bin(fb_, BinOp::IAdd, sum, term)?;
}
let shift = lanes(fb_, 4, 8, 4)?;
let back = lanes(fb_, 0, 4, 0)?;
let n = bin(fb_, BinOp::ShiftRightArithmetic, sum, shift)?;
let n = bin(fb_, BinOp::ShiftLeftLogical, n, back)?;
let made = texel_round::grid_value(fb_, uform(LANES), n, d, |fb, m, d| {
texel_round::ratio_to_f32(fb, uform(LANES), m, d)
})?;
let exact = flag(fb_, flags, BicubicTexels::EXACT)?;
let made_up = bin(fb_, BinOp::LogicalOr, exact, coded)?;
let r = fb_.select(made_up, made, x)?;
finish(fb, r)
}
/// Whether treatment `flags` states a `CubeCorner` with grids in its `TexelFormat::CORNER` field
/// (every corner after `CubeCorner::XFace`), and that corner's grid `D` per lane (`uvec4`; each
/// lane 1 for any other field).
fn corner_grids(fb: &mut FunctionBuilder<'_>, t: &Tys, flags: Value) -> BResult<(Value, Value)> {
let shift = u1(fb, TexelFormat::CORNER)?;
let field = bin(fb, BinOp::ShiftRightLogical, flags, shift)?;
let four_bits = u1(fb, 0xF)?;
let field = bin(fb, BinOp::BitwiseAnd, field, four_bits)?;
let x_face = u1(fb, CubeCorner::XFace as u32)?;
let coded = bin(fb, BinOp::UGreaterThan, field, x_face)?;
let mut d = u4(fb, 1)?;
for corner in CubeCorner::ALL {
let Some(grids) = corner.grids() else {
continue;
};
let k = u1(fb, corner as u32)?;
let is = bin(fb, BinOp::IEqual, field, k)?;
let mut lanes = Vec::with_capacity(4);
for g in grids {
lanes.push(u1(fb, g)?);
}
let g = fb.composite_construct(t.vu, &lanes)?;
d = fb.select(is, g, d)?;
}
Ok((coded, d))
}
/// A packed field's grids ([`packed_grids`]), each `uvec4` lanes.
struct PackedGrids {
/// Whether the treatment names the field's grids.
@@ -2556,28 +2413,3 @@ fn define_float_block(mb: &mut ModuleBuilder) -> BResult<FuncId> {
let r = accumulated_result(fb_, t, kind, (r, specials), p.half)?;
finish(fb, r)
}
/// `fn(t0, t1, k, flags, half) -> vec4` (module docs, [`Span::float`]): Metal's accumulator
/// ([`accumulate`]) over the two taps under the weights `(256 - k) · 256` and `k · 256`; Metal's
/// non-finite results on the taps of nonzero weight; and the `half` result's conversion.
fn define_float_span(mb: &mut ModuleBuilder) -> BResult<FuncId> {
let t = types(mb)?;
let mut fb = mb.texel_routine(t.vf)?;
let t0 = fb.param(t.vf)?;
let t1 = fb.param(t.vf)?;
let k = fb.param(t.u)?;
let flags = fb.param(t.u)?;
let half = fb.param(t.b)?;
let fb_ = &mut fb;
let (k256, k8) = (u1(fb_, 256)?, u1(fb_, 8)?);
let rest = bin(fb_, BinOp::ISub, k256, k)?;
let w0 = bin(fb_, BinOp::ShiftLeftLogical, rest, k8)?;
let w1 = bin(fb_, BinOp::ShiftLeftLogical, k, k8)?;
let kind = Kind::of(fb_, flags)?;
let r = accumulate(fb_, t, &[(t0, w0), (t1, w1)], kind.half)?;
let z = u1(fb_, 0)?;
let zero = bin(fb_, BinOp::IEqual, k, z)?;
let specials = weighed_specials(fb_, t, &[(t0, None), (t1, Some(zero))])?;
let r = accumulated_result(fb_, t, kind, (r, specials), half)?;
finish(fb, r)
}
@@ -1,878 +0,0 @@
//! Depth comparisons of one texel per tap that the shader makes itself: a 2D depth texture's or
//! array's `gather_compare`, and its `sample_compare` through a sampler that reads one texel
//! (nearest filters, no mip filter or the nearest level's, no anisotropy), through a constexpr
//! sampler or a runtime sampler slot.
//!
//! **Why.** A device compares a `Depth16Unorm` texel against a reference by its own rule, and
//! Vulkan pins only the reference's clamp into `[0, 1]`: on 9,024 comparisons each, RADV differs
//! from Metal on 71 (a NaN reference compares as 0), ANV on 584 (its rounding threshold lies below
//! the half-way point and moves with the code; a NaN as 0), the RTX 3090 on 474 (its threshold lies
//! up to 0.51 of a step above the half-way point; a NaN as 0), and x86 lavapipe on 1,203 (it
//! compares the clamped reference with the texel as floats; a NaN as 1); MoltenVK on Apple's GPU
//! matches. Metal compares codes: the reference's is its exact product with 65535 rounded to
//! nearest (`linear::compare`'s `reference`), and a NaN fails every ordered test. A `Depth32Float`
//! texel compares as given, denormals included, which x86 lavapipe's float comparison misses (it
//! flushes them; `linear::compare`'s keys do not), and `depth32Float_stencil8` compares as
//! `depth32Float`. `Depth24Unorm_Stencil8` is not an Apple-family format: its comparison, made here
//! as a float format's, is not measured.
//!
//! **How.** The texels are read without comparison through a binding whose sampler does not
//! compare (`BindingKey::compare` false, so a `Depth32Float` texture held with a twin reads its
//! `R32_SFLOAT` image): a gather's four depths, the taps Metal's footprint names, or a nearest
//! sample's one depth. The shader then compares each with the reference through
//! `linear::compare::TapCompare`, the entry point every comparison the shader makes takes. A tap
//! outside a border axis reads the border's depth, which Metal compares as a texel's.
//!
//! **By fetches**. A device's sample or gather may read a denormal `R32_SFLOAT` texel as zero, and
//! its fetch keeps it, so where Metal's footprint and level are known the shader fetches the depths
//! itself through [`super::fetched`]: a gather's four taps and a nearest sample's texel, behind the
//! slot's `TexelFormat` specialization. A format whose border texel is measured (`Depth32Float`'s
//! and `Depth16Unorm`'s classes) takes the fetches, another the device's read. Elsewhere (an
//! implicit level or gradients in a fragment function, a `min_lod_clamp`, a dynamic offset, an
//! observed residency, axes clamping to zero and to a colored border) the device reads the texels,
//! snapped as a plain gather or nearest sample is (`position::plan`), at Metal's level.
//!
//! **A runtime sampler**. Its compare function is its word's `COMPARE` field, the raw
//! `MTLCompareFunction` (`TapCompare::of_word`), read from the slot's `SamplerState`
//! specialization. A comparison gather fetches its four depths as a constexpr sampler's does, its
//! taps addressed by the word (`fetched::FetchAddress::Word`). A `sample_compare` keeps its
//! reference, since whether the bound sampler reads one texel is known only at run time: a branch
//! on the word's filter (`runtime_sample`) compares in the shader where the sampler reads one texel
//! (nearest filters, no linear mip filter, no anisotropy), and elsewhere takes the filtered
//! comparison: `linear`'s emulation, which compares each tap by the same word, where it reaches the
//! sample, else the device's. Where it reads one texel, the shader fetches the texel, addressed by
//! the word, of the level the word reads at the sample's level or a kernel's bias (or level 0
//! without either): level 0 without a mip filter, and under a nearest one the level Metal's rule
//! reads, clamped into the levels the word's clamp leaves (`fetched::FetchLevel::Word`). Metal
//! reads a comparison's level through a runtime or argument buffer's sampler as a sample's, its
//! clamp held as `f32`s. At an implicit level or gradients in a fragment function it fetches level
//! 0's texel where the word states no mip filter, and under a nearest one samples without
//! comparison through the slot's binding without comparison ([`Compared::plain`]), as it does not
//! know the level Metal reads. A dynamic offset or a `min_lod_clamp` leaves the reads to the
//! device. Metal is taken to compare through a runtime sampler as through a constexpr sampler of
//! the same state, as it filters; the runtime lane's `depth_compares` runs both kinds of sampler on
//! each device, Metal's own through MoltenVK. The module records `DeviceDepthComparison` only where
//! the word reaches the device's comparison or level ([`Compared::device_when`]).
//!
//! **A heap texture**. The function does not know the format of an argument buffer's texture, so
//! the binder states its depth class in the texture's handle-table entry (`Depth16Unorm`'s codes,
//! `Depth32Float`'s and `Depth32Float_Stencil8`'s values, none for any other format), which the
//! handle carries (`memory::handles::Lookup::Flagged`). A heap comparison through a constexpr
//! sampler that reads one texel, a runtime sampler slot, or an argument buffer's sampler keeps its
//! reference, and the shader makes both reads (`heap`): the device's comparison, and the depths
//! read through the use's sampler without comparison (a second heap sampler, or the sampler array
//! of that use), which it compares as a slot's, by the class. It takes its own where the handle
//! states a class and, for a runtime or argument buffer's sampler's sample, the sampler's word
//! states one that reads one texel; elsewhere the device's, which the module records
//! (`DeviceDepthComparison`). Every read runs, so no branch puts an access in divergent flow. Where
//! Metal's footprint and level are known, as for a slot, the shader fetches the depths from that
//! element (an argument buffer's sampler's taps addressed by its table entry's word,
//! `fetched::FetchAddress::Entry`), its border texel read as a slot bound in the class's format
//! reads it; a runtime or argument buffer's sampler's sample takes the texel of the level its word
//! reads at its level or a kernel's bias, as a slot's does, and at an implicit level or gradients
//! level 0's where its word states no mip filter, and under a nearest one samples it, as the
//! function does not know the level Metal reads. Elsewhere the device reads the texels, so a
//! `Depth32Float` denormal it may read as zero is recorded (`DeviceTexelDenormals`). A texture
//! bound in a format without a class keeps the device's comparison.
//!
//! **Not reached**, the device comparing: a sample whose dynamic bias may pass the device's limit
//! through a runtime, argument buffer's, or (of a heap texture) constexpr sampler (its second
//! sample), an access whose residency the function observes, a cube, a sample that filters through
//! a constexpr sampler (a linear comparison of a slot is `linear`'s emulation), and a device with
//! `VkProperty::MetalSampler`, whose comparison is Metal's own, which the module then requires.
use crate::air::abi::{CompareFunction, Coordinates, Filter, MipFilter};
use crate::air::intrinsics::{ImageDim, ImageShape};
use crate::air::ir::ValueId;
use crate::error::Error;
use crate::lower::arith::legal::{Form, Held};
use crate::lower::emit::EmitCx;
use crate::lower::select::SelectCx;
use crate::lower::texture::ImageRef;
use crate::memory::handles::{ENTRY_FIELD_WORDS, HANDLE_DEPTH_CODES, HANDLE_DEPTH_VALUES};
use crate::metal::bicubic::BicubicTexels;
use crate::metal::sampler::SamplerWord;
use crate::metal::texel_format::texel_format;
use crate::metal::PixelFormat;
use crate::metal::SamplerMipFilter;
use crate::pipeline::sym::SamplerRef;
use crate::spirv::builder::constructs::{ArmEnd, ArmFn, Merged};
use crate::spirv::builder::FunctionBuilder;
use crate::spirv::error::BResult;
use crate::spirv::ids::Value as SValue;
use crate::spirv::ir::{BinOp, ConstBits, Constant, ConvOp, GlslOp, ImageQuery, Type as SType};
use super::bicubic::{scalar, value, Bits, Tys};
use super::fetched::{Fetch, FetchAddress};
use super::linear::compare::TapCompare;
use super::linear::Comparison;
use super::{BiasReach, CombinedImage, Lod, Pixel, SampleOp, Sampling, Source};
/// The census name of the masks a heap handle's depth flags cost every heap operation of a module
/// whose search carries no out-of-bounds alpha (`lower::texture::routine_words`): the heap
/// comparisons the shader makes ask for them.
pub const DEPTH_CLASS_CENSUS: &str = "sampler.heap.depth_class";
/// What says how a comparison's texels compare (module docs).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FormatBits {
/// The texture slot's `TexelFormat` specialization: `BicubicTexels::EXACT` for the codes of
/// `Depth16Unorm`.
Slot(u32),
/// The depth flags heap handle `handle` carries (`memory::handles::HANDLE_DEPTH_CODES` and
/// `HANDLE_DEPTH_VALUES`).
Heap(ValueId),
}
/// A comparison the shader makes of the texels read without comparison (module docs): the
/// sampler's compare function (a constexpr sampler's, or a runtime or argument buffer's sampler's
/// word's), the reference, what says how the texels compare, and how the shader fetches them,
/// where it does.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Compared {
pub function: Comparison,
pub dref: ValueId,
pub format: FormatBits,
pub fetch: Option<Fetch>,
/// The read without comparison of a comparison that keeps its reference
/// ([`Compared::keeps_reference`], set by `sampler::select`): a runtime sampler's
/// `sample_compare`'s slot binding without comparison, through which it samples where the
/// bound sampler reads one texel, and a heap comparison's element through its use's sampler
/// without comparison.
pub plain: Option<Source>,
}
/// The estimated words of a runtime sampler's `sample_compare` beyond its comparison
/// ([`runtime_sample`]): the word's filter test, the branch, the sample without comparison and its
/// sampled image, the depth's extraction, and the device's sampled image in its own arm.
const RUNTIME_WORDS: u32 = 160;
/// The estimated words a runtime sampler's `sample_compare` adds where it fetches its texel
/// ([`runtime_sample`]): the word's mip filter test, its branch, and the second sample without
/// comparison, in the arm the format's test leaves to the device.
const RUNTIME_FETCH_WORDS: u32 = 96;
/// The estimated words a heap comparison adds beyond its comparison ([`heap`]): the handle's two
/// depth flags' tests and the format bits' select, the read without comparison (its sampler's load,
/// or an argument buffer's sampler's element, access chain and load; the sampled image, the access,
/// and its depths' extraction and assembly), an argument buffer's sampler's word, a runtime or
/// argument buffer's sampler's sample's test of the word's filter, and the final select, with their
/// constants.
const HEAP_WORDS: u32 = 256 + 2 * ENTRY_FIELD_WORDS;
/// The format classes whose depths the shader fetches (module docs): those whose border texel is
/// measured, `Depth32Float`'s and `Depth16Unorm`'s among them.
const MEASURED: u32 = BicubicTexels::EXACT | BicubicTexels::LINEAR | BicubicTexels::HALF;
impl Compared {
/// The estimated words: the reference's code and each tap's test, the fetches where the shader
/// fetches the texels (a snapped level's own words are its snap's, `level::LEVEL_WORDS`), and a
/// comparison's that keeps its reference.
pub fn words(&self, op: &SampleOp) -> u32 {
let taps = match op {
SampleOp::Gather { .. } => 4,
_ if self.blends() => 2,
_ => 1,
};
let fetch = self.fetch.as_ref().map_or(0, |f| f.words(op));
let kept = match (self.format, self.plain, &self.fetch) {
(_, None, _) => 0,
(FormatBits::Heap(_), Some(_), _) => HEAP_WORDS,
(FormatBits::Slot(_), Some(_), Some(_)) => RUNTIME_WORDS + RUNTIME_FETCH_WORDS,
(FormatBits::Slot(_), Some(_), None) => RUNTIME_WORDS,
};
self.function.words(taps) + fetch + kept
}
/// Whether op `op` keeps its reference for the device's comparison beside the shader's
/// (module docs): a runtime sampler's `sample_compare` of a slot, whose filter only the
/// sampler's word states (`runtime_sample`), a blend of two levels' comparisons, whose
/// device arm compares a format whose class is not measured ([`blended`]), and every heap
/// comparison, whose class only the handle states (`heap`).
pub fn keeps_reference(&self, op: &SampleOp) -> bool {
match self.format {
FormatBits::Heap(_) => true,
FormatBits::Slot(_) => {
(self.function == Comparison::Word && matches!(op, SampleOp::Sample { .. }))
|| self.blends()
}
}
}
/// Whether the comparison blends two levels' comparisons under a linear mip filter
/// ([`blended`], `fetched::FetchLevel::Blend`).
pub fn blends(&self) -> bool {
self.fetch
.as_ref()
.is_some_and(|f| matches!(f.level, super::fetched::FetchLevel::Blend(..)))
}
/// Where the device compares a blend's sample ([`blended`]): where the slot's `TexelFormat`
/// names no measured class.
pub(super) fn blend_device_when(&self) -> Vec<crate::lower::select::NoteClause> {
use crate::lower::select::{NoteClause, NoteOn, NoteTest};
match self.slot() {
Some(texture) => vec![[NoteTest::equal(NoteOn::Texel(texture), MEASURED, 0)].into()],
None => vec![NoteClause::new()],
}
}
/// Where the device compares a runtime sampler slot `n`'s `sample_compare` of a slot, whose
/// filtered comparison is emulation `linear`'s where it is planned ([`runtime_sample`]): where
/// the word filters and the emulation does not reach it (`linear::device_when`; without an
/// emulation, wherever the word filters); and where the word reads one texel under a nearest
/// mip filter but the shader does not fetch it from the level the word reads (an implicit level
/// or gradients, a dynamic offset, or a `min_lod_clamp`), whose level the device chooses.
pub(super) fn device_when(
&self,
n: u32,
linear: Option<&super::linear::Linear>,
) -> Vec<crate::lower::select::NoteClause> {
use crate::lower::select::{NoteOn, NoteTest};
let mut when = match linear {
Some(l) => super::linear::device_when(l),
None => super::linear::word_filters(n),
};
let leveled = self
.fetch
.as_ref()
.is_some_and(|f| matches!(f.level, super::fetched::FetchLevel::Word(_)));
if !leveled {
let one = SamplerWord::MIN_LINEAR
| SamplerWord::MAG_LINEAR
| SamplerWord::ANISOTROPIC
| SamplerWord::MIP_FILTER;
let nearest = SamplerMipFilter::Nearest.as_raw() << SamplerWord::MIP_FILTER_SHIFT;
when.push([NoteTest::equal(NoteOn::Sampler(n), one, nearest)].into());
}
when
}
/// Whether the comparison is a heap texture's (`heap`).
pub fn on_heap(&self) -> bool {
matches!(self.format, FormatBits::Heap(_))
}
/// Whether the shader's comparison of op `op` reads only texels it fetches (module docs): a
/// fetched one, but a runtime sampler slot's `sample_compare` and a heap texture's through a
/// runtime or argument buffer's sampler at an implicit level or gradients, whose texel the
/// device samples where the word states a nearest mip filter. (Where the word filters, the
/// device's own comparison reads the texels, `DeviceDepthComparison`.)
pub fn fetches_every_texel(&self, op: &SampleOp) -> bool {
let sample = matches!(op, SampleOp::Sample { .. });
let leveled = self
.fetch
.as_ref()
.is_some_and(|f| matches!(f.level, super::fetched::FetchLevel::Word(_)));
self.fetch.is_some()
&& (leveled
|| self.blends()
|| match self.format {
FormatBits::Slot(_) => !self.keeps_reference(op),
FormatBits::Heap(_) => !(sample && self.function == Comparison::Word),
})
}
/// The texture slot whose `TexelFormat` specialization says how the texels compare, where it
/// is one.
fn slot(&self) -> Option<u32> {
match self.format {
FormatBits::Slot(n) => Some(n),
FormatBits::Heap(_) => None,
}
}
}
/// `op` with its comparison taken out where the shader makes it alone (module docs), and that
/// comparison; else `op` as it is. `stat` is the static sampler (none for an argument buffer's),
/// `image` and `shape` the texture's, and `level` the call's level or bias operand. A runtime
/// sampler's sample of a slot and every comparison of a heap texture keep their reference
/// ([`Compared::keeps_reference`]).
pub(super) fn select(
cx: &mut SelectCx<'_>,
op: SampleOp,
stat: Option<(SamplerRef, Coordinates)>,
(image, shape): (ImageRef, ImageShape),
level: Option<crate::air::ir::Value>,
) -> Result<(SampleOp, Option<Compared>), Error> {
let dref = match &op {
SampleOp::Sample { dref: Some(r), .. } | SampleOp::Gather { dref: Some(r), .. } => *r,
_ => return Ok((op, None)),
};
if shape.dim != ImageDim::D2 || !shape.depth || shape.ms {
return Ok((op, None));
}
let format = match image {
ImageRef::Slot(texture) => FormatBits::Slot(texture),
ImageRef::Heap { handle, .. } => FormatBits::Heap(handle),
};
// A static sampler, or an argument buffer's (a heap texture's alone), by its word.
let sampler = match (stat, format) {
(Some((sampler, _)), _) => Some(sampler),
(None, FormatBits::Heap(_)) => None,
(None, FormatBits::Slot(_)) => return Ok((op, None)),
};
let heap = matches!(format, FormatBits::Heap(_));
let sample = matches!(op, SampleOp::Sample { .. });
let state = match sampler {
Some(SamplerRef::Constexpr(words)) => Some(super::state_of(words)?),
Some(SamplerRef::Slot(_)) | None => None,
};
// A dynamic bias's second sample stays the device's comparison where the op keeps its
// reference.
let biased = matches!(
&op,
SampleOp::Sample {
lod: Lod::Implicit {
reach: BiasReach::Either { .. },
..
},
..
}
);
// A slot's sample through nearest filters under a linear mip filter blends two levels'
// comparisons, where Metal's level is known (`fetched::FetchLevel::Blend`).
let blend = |s: &crate::air::abi::SamplerState| {
!heap
&& sample
&& s.min_filter == Filter::Nearest
&& s.mag_filter == Filter::Nearest
&& s.mip_filter == MipFilter::Linear
&& s.max_anisotropy <= 1
};
let function = match &state {
// The frontend writes an unspecified compare function as `never`, and no `None`.
Some(s) => match s.compare {
CompareFunction::None => return Ok((op, None)),
_ if sample && !super::linear::unfiltered(s) && !blend(s) => return Ok((op, None)),
_ if heap && biased => return Ok((op, None)),
f => Comparison::Function(f),
},
None if biased => return Ok((op, None)),
None => Comparison::Word,
};
if cx.profile.device_samples() {
cx.families.sampler.metal_sampler = true;
return Ok((op, None));
}
let blends = state.as_ref().is_some_and(blend);
let op = match op {
// A heap texture's class is known at run time, as is a runtime sampler's filter, and a
// blend's device arm compares a format whose class is not measured: the op keeps its
// reference for the device's comparison.
_ if heap || blends => op,
SampleOp::Sample { .. } if state.is_none() => op,
SampleOp::Sample {
lod,
min_lod,
offset,
..
} => SampleOp::Sample {
lod,
dref: None,
min_lod,
offset,
},
SampleOp::Gather {
component, offset, ..
} => SampleOp::Gather {
component,
dref: None,
offset,
},
other => other,
};
// A heap texture's depths are fetched by the class its handle carries (`heap`), an argument
// buffer's sampler's addressed by its table entry's word.
let fetch = match (&state, sampler) {
(Some(s), _) => super::fetched::plan(cx, &op, s, &[s.address_s, s.address_t], level)?,
(None, Some(SamplerRef::Slot(n))) => super::fetched::plan_word(
&op,
FetchAddress::Word {
sampler: n,
axes: 2,
},
),
(None, None) if heap => super::fetched::plan_word(&op, FetchAddress::Entry { axes: 2 }),
(None, _) => None,
};
// A blend whose level the shader does not know (an implicit level or gradients, a
// `min_lod_clamp`, a dynamic offset, a level clamp the snap does not reach) is the device's.
let blended = fetch
.as_ref()
.is_some_and(|f| matches!(f.level, super::fetched::FetchLevel::Blend(..)));
if blends && !blended {
return Ok((op, None));
}
let compared = Compared {
function,
dref,
format,
fetch,
plain: None,
};
Ok((op, Some(compared)))
}
/// The passes of `c` over the depths of `s` (a gather's four, a `vec4`, or a sample's one) that
/// the shader fetches (`c.fetch`, module docs, [`super::fetched::branch`]) where the slot's
/// `TexelFormat` specialization states a measured format, else that `device`'s access of the
/// combined binding's sampled image reads (a `vec4` of the view's sampled type; a sample's first
/// component is its depth).
pub(super) fn fetched(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
s: &Sampling,
(c, f): (&Compared, &Fetch),
image: CombinedImage,
device: &dyn Fn(&mut FunctionBuilder<'_>, SValue) -> BResult<SValue>,
) -> BResult<SValue> {
let gather = matches!(s.op, SampleOp::Gather { .. });
let (Source::Combined(key), Some(texture)) = (s.source, c.slot()) else {
return Err(cx.fail("fetched texels of a heap element"));
};
let read = |fb: &mut FunctionBuilder<'_>, si: SValue| {
let x = device(fb, si)?;
match gather {
true => Ok(x),
false => fb.composite_extract(x, &[0]),
}
};
let texel = super::fetched::branch(
cx,
fb,
(s, key),
(texture, f, MEASURED, false),
image,
&depths,
&read,
)?;
emit(cx, fb, s, c, texel)
}
/// The depths of `texels`, each a `vec4` whose first component is its depth: a sample's one, or a
/// gather's four as a `vec4`.
fn depths(fb: &mut FunctionBuilder<'_>, texels: &[SValue]) -> BResult<SValue> {
let vec4 = Tys::new(fb)?.vec4;
let mut depths = Vec::with_capacity(texels.len());
for &texel in texels {
depths.push(fb.composite_extract(texel, &[0])?);
}
match depths[..] {
[d] => Ok(d),
_ => fb.composite_construct(vec4, &depths),
}
}
/// The held value of runtime sampler sample `s` of combined image `image`, which compares as `c`
/// says ([`Compared::keeps_reference`], module docs): a branch on whether the slot's word states a
/// sampler that reads one texel (nearest minification and magnification, no linear mip filter,
/// not anisotropic). There the depth, compared in the shader: where `c.fetch` is planned, the
/// texel the shader fetches through the slot's binding without comparison (`c.plain`) where the
/// slot's format is measured ([`super::fetched::branch`]), of the level the word reads at the
/// sample's level (`fetched::FetchLevel::Word`), or, at an implicit level or gradients, of level
/// 0 where the word states no mip filter; else the first component of `plain`'s sample of that
/// binding's sampled image; elsewhere `filtered`, the filtered comparison's held value. Each arm
/// makes the sampled images it reads.
pub(super) fn runtime_sample<'a, 'e>(
cx: &mut EmitCx<'e>,
fb: &mut FunctionBuilder<'_>,
(s, c, image): (&'a Sampling, &'a Compared, CombinedImage),
plain: &'a dyn Fn(&mut FunctionBuilder<'_>, SValue) -> BResult<SValue>,
filtered: ArmFn<'a, EmitCx<'e>>,
) -> BResult<SValue> {
let (Some(Source::Combined(key)), Some(texture), Some(form)) = (c.plain, c.slot(), s.texel)
else {
return Err(cx.fail("a runtime sampler's comparison without its plain binding"));
};
let Some(&(binding, _)) = cx.decl.families.sampler.combined.get(&key) else {
return Err(cx.fail(format!("combined binding {key:?} is not declared")));
};
let SamplerRef::Slot(n) = key.sampler else {
return Err(cx.fail("a branched comparison through a constexpr sampler"));
};
let word = super::emit::sampler_word(cx, fb, Pixel::Spec(n))?;
let t = Tys::new(fb)?;
let (one, mip) = one_texel(fb, &t, word)?;
// The one texel of the level the word reads, which the shader fetches; at an implicit level
// or gradients, only under `MTLSamplerMipFilterNotMipmapped`, level 0's.
let unmipped = match &c.fetch {
Some(f) if matches!(f.level, super::fetched::FetchLevel::Word(_)) => Some((f, None)),
Some(f) => {
let zero = scalar(fb, t.u32_, 0)?;
let zero = value(fb, zero)?;
Some((f, Some(fb.binary(BinOp::IEqual, mip, zero)?)))
}
None => None,
};
let texel = image.texel;
let compared: ArmFn<'a, EmitCx<'e>> = Box::new(move |fb, cx| {
let sampled = |fb: &mut FunctionBuilder<'_>, si: SValue| -> BResult<SValue> {
let x = plain(fb, si)?;
fb.composite_extract(x, &[0])
};
let depth = match unmipped {
Some((f, None)) => super::fetched::branch(
cx,
fb,
(s, key),
(texture, f, MEASURED, false),
image,
&depths,
&sampled,
)?,
Some((f, Some(level0))) => {
let fetch: ArmFn<'_, EmitCx<'e>> = Box::new(|fb, cx| {
let d = super::fetched::branch(
cx,
fb,
(s, key),
(texture, f, MEASURED, false),
image,
&depths,
&sampled,
)?;
Ok(ArmEnd::FallThrough(vec![d]))
});
let read: ArmFn<'_, EmitCx<'e>> = Box::new(|fb, _| {
let si = binding.sampled_image(fb)?;
Ok(ArmEnd::FallThrough(vec![sampled(fb, si)?]))
});
let Merged(merged) = fb.if_(cx, level0, fetch, Some(read))?;
match merged[..] {
[d] => d,
_ => return Err(cx.fail("a fetched comparison's depth without its value")),
}
}
None => {
let si = binding.sampled_image(fb)?;
sampled(fb, si)?
}
};
let pass = emit(cx, fb, s, c, depth)?;
let pass = crate::lower::texture::held_texel(fb, texel, form, pass)?;
Ok(ArmEnd::FallThrough(vec![pass]))
});
let Merged(merged) = fb.if_(cx, one, compared, Some(filtered))?;
match merged[..] {
[x] => Ok(x),
_ => Err(cx.fail("a runtime sampler's comparison without its value")),
}
}
/// The held value of sample `s` of combined image `image` through a constexpr sampler of nearest
/// filters under a linear mip filter, which compares as `c` says ([`Compared::blends`], module
/// docs): where the slot's `TexelFormat` states a measured class, Metal's blend of two levels'
/// comparisons. With `L + q` the level the sampler's snap hands the device (`level::LevelSnap::of`)
/// clamped into the texture's levels, the shader fetches the texel of level `L` and of level `L +
/// 1` (clamped into the levels) through the slot's binding without comparison (`c.plain`), compares
/// each, and blends the passes by `1 - q` and `q` as Metal does ([`blend_passes`]). Elsewhere
/// `device`'s comparison of the binding's sampled image. Each arm makes the sampled images it
/// reads.
pub(super) fn blended(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
(s, c, image): (&Sampling, &Compared, CombinedImage),
device: &dyn Fn(&mut FunctionBuilder<'_>, SValue) -> BResult<SValue>,
) -> BResult<SValue> {
use super::fetched::FetchLevel;
let (Some(Source::Combined(key)), Some(texture), Some(f), Some(form)) =
(c.plain, c.slot(), c.fetch.as_ref(), s.texel)
else {
return Err(cx.fail("a blended comparison without its plain binding or its fetch"));
};
let FetchLevel::Blend(snap, operand) = f.level else {
return Err(cx.fail("a blended comparison without its levels"));
};
let Some(spec) = crate::lower::texture::texel_format_const(cx, texture) else {
return Err(cx.fail(format!(
"texture slot {texture} has no `TexelFormat` specialization"
)));
};
let Some(&(binding, _)) = cx.decl.families.sampler.combined.get(&key) else {
return Err(cx.fail(format!("combined binding {key:?} is not declared")));
};
let Source::Combined(own) = s.source else {
return Err(cx.fail("a blended comparison of a heap element"));
};
let Some(&(compares, _)) = cx.decl.families.sampler.combined.get(&own) else {
return Err(cx.fail(format!("combined binding {own:?} is not declared")));
};
let t = Tys::new(fb)?;
let measured = super::bicubic::flag(fb, &t, spec, MEASURED)?;
let texel = image.texel;
let t = &t;
let fetch: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| {
let si = binding.sampled_image(fb)?;
let x = match operand {
Some(v) => cx.operand(fb, v)?,
None => float(fb, 0.0)?,
};
// `L + q`, clamped into the texture's levels: a whole last level leaves `q` 0.
let lambda = snap.emit(fb, x)?;
let img = fb.image(si)?;
let levels = fb.query(ImageQuery::Levels, img)?;
let one = scalar(fb, t.u32_, 1)?;
let one = value(fb, one)?;
let last = fb.binary(BinOp::ISub, levels, one)?;
let f32_ = fb.module().ty(SType::Float { width: 32 })?;
let last_f = fb.convert(ConvOp::ConvertUToF, last, f32_)?;
let lambda = fb.glsl(GlslOp::FMin, &[lambda, last_f])?;
let whole = fb.glsl(GlslOp::Floor, &[lambda])?;
let q = fb.binary_no_contraction(BinOp::FSub, lambda, whole)?;
let l0 = fb.convert(ConvOp::ConvertFToU, whole, t.u32_)?;
let l1 = fb.binary(BinOp::IAdd, l0, one)?;
let l1 = fb.glsl(GlslOp::UMin, &[l1, last])?;
let dref = super::emit::reference(cx, fb, s, c.dref)?;
let test = TapCompare::of(cx, fb, t, (c.function, None), (dref, Bits::Spec(spec)))?;
let mut passes = [q; 2];
for (pass, level) in passes.iter_mut().zip([l0, l1]) {
let Some(taps) = f.taps(s, Some(level), None) else {
return Err(cx.fail("a blended comparison's taps"));
};
let x = super::fetched::texels(cx, fb, t, s, (si, image), Bits::Spec(spec), &taps)?;
let depth = depths(fb, &x)?;
*pass = test.pass(fb, depth)?;
}
let blend = blend_passes(fb, t, passes, q)?;
let held = crate::lower::texture::held_texel(fb, texel, form, blend)?;
Ok(ArmEnd::FallThrough(vec![held]))
});
let read: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, _| {
let si = compares.sampled_image(fb)?;
let x = device(fb, si)?;
let held = crate::lower::texture::held_texel(fb, texel, form, x)?;
Ok(ArmEnd::FallThrough(vec![held]))
});
let Merged(merged) = fb.if_(cx, measured, fetch, Some(read))?;
match merged[..] {
[x] => Ok(x),
_ => Err(cx.fail("a blended comparison without its value")),
}
}
/// Metal's blend of two levels' passes `[p0, p1]` (each `0.0` or `1.0`) by `1 - q` and `q` (`q`
/// on sixty-fourths, `m / 64`), as `blended` takes it: an `r8Unorm` texture's blend of the passes
/// as codes 0 and 255, as a linear comparison sums its taps' (`linear::compare`), its sum `255 (p0
/// (64 - m) + p1 m) / 64` rounded once onto sixteenths of a code, ties up, `n = (255 s + 2) /
/// 4` of `s = p0 (64 - m) + p1 m`, and `n / 4080` correctly rounded to `f32`.
fn blend_passes(
fb: &mut FunctionBuilder<'_>,
t: &Tys,
[p0, p1]: [SValue; 2],
q: SValue,
) -> BResult<SValue> {
let sixty_four = float(fb, 64.0)?;
let m = fb.binary_no_contraction(BinOp::FMul, q, sixty_four)?;
let rest = fb.binary_no_contraction(BinOp::FSub, sixty_four, m)?;
let a = fb.binary_no_contraction(BinOp::FMul, p0, rest)?;
let b = fb.binary_no_contraction(BinOp::FMul, p1, m)?;
let sum = fb.binary_no_contraction(BinOp::FAdd, a, b)?;
let sum = fb.convert(ConvOp::ConvertFToU, sum, t.u32_)?;
let u = |fb: &mut FunctionBuilder<'_>, v: u64| -> BResult<SValue> {
let c = scalar(fb, t.u32_, v)?;
value(fb, c)
};
let (code, two, grid) = (u(fb, 255)?, u(fb, 2)?, u(fb, 4080)?);
let n = fb.binary(BinOp::IMul, sum, code)?;
let n = fb.binary(BinOp::IAdd, n, two)?;
let n = fb.binary(BinOp::ShiftRightLogical, n, two)?;
let form = Form {
held: Held::Int {
bits: 32,
container: 32,
},
lanes: 1,
};
crate::lower::arith::texel_round::ratio_to_f32(fb, form, n, grid)
}
/// Whether sampler word `word` (a `u32`) states a sampler that reads one texel (nearest
/// minification and magnification, no linear mip filter, not anisotropic), and the word's mip
/// filter field.
pub(super) fn one_texel(
fb: &mut FunctionBuilder<'_>,
t: &Tys,
word: SValue,
) -> BResult<(SValue, SValue)> {
let filters = scalar(
fb,
t.u32_,
u64::from(SamplerWord::MIN_LINEAR | SamplerWord::MAG_LINEAR | SamplerWord::ANISOTROPIC),
)?;
let filters = value(fb, filters)?;
let zero = scalar(fb, t.u32_, 0)?;
let zero = value(fb, zero)?;
let filters = fb.binary(BinOp::BitwiseAnd, word, filters)?;
let nearest = fb.binary(BinOp::IEqual, filters, zero)?;
let mip = super::bicubic::word_field(
fb,
t,
word,
SamplerWord::MIP_FILTER_SHIFT,
SamplerWord::MIP_FILTER >> SamplerWord::MIP_FILTER_SHIFT,
)?;
// `MTLSamplerMipFilterLinear`.
let linear = scalar(fb, t.u32_, 2)?;
let linear = value(fb, linear)?;
let one_level = fb.binary(BinOp::INotEqual, mip, linear)?;
Ok((fb.binary(BinOp::LogicalAnd, nearest, one_level)?, mip))
}
/// The held value of heap comparison `s` (module docs, [`Compared::keeps_reference`]): `device`,
/// the device's comparison of the element (read through `s.source`'s sampler with comparison),
/// where the shader does not compare; else the passes of `c` over the element's depths (a
/// gather's four as a `vec4`, a sample's one), compared by the class the handle carries. The
/// depths are the ones the shader fetches from the sampled image of `c.plain` (the same element
/// through its use's sampler without comparison) where `c.fetch` is planned, as a slot of the
/// class's format would ([`super::fetched::texels`]); else, and for a runtime or argument
/// buffer's sampler's sample whose word states a nearest mip filter, the ones `plain` reads of
/// it. The shader compares where the handle states a class and, for such a sample, the word
/// states a sampler that reads one texel. Every read runs, so no branch puts one in divergent
/// flow.
pub(super) fn heap(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
(s, c): (&Sampling, &Compared),
device: SValue,
plain: &dyn Fn(&mut FunctionBuilder<'_>, SValue) -> BResult<SValue>,
) -> BResult<SValue> {
let (FormatBits::Heap(handle), Some(source)) = (c.format, c.plain) else {
return Err(cx.fail("a heap comparison without its handle or its plain read"));
};
let (si, image, _) = super::emit::sampled_image(cx, fb, source)?;
let t = Tys::new(fb)?;
let h = cx.operand(fb, handle)?;
let zero = scalar(fb, t.u32_, 0)?;
let zero = value(fb, zero)?;
let mut flags = [zero; 2];
for (flag, bit) in flags
.iter_mut()
.zip([HANDLE_DEPTH_CODES, HANDLE_DEPTH_VALUES])
{
let bit = scalar(fb, t.u32_, u64::from(bit))?;
let bit = value(fb, bit)?;
let carried = fb.binary(BinOp::BitwiseAnd, h, bit)?;
*flag = fb.binary(BinOp::INotEqual, carried, zero)?;
}
let [codes, values] = flags;
// The class's texels compare, and a border tap reads, as a slot bound in its format would:
// `Depth16Unorm`'s `TexelFormat` (codes) or `Depth32Float`'s (values).
let mut bits = zero;
for (class, format) in [
(values, PixelFormat::Depth32Float),
(codes, PixelFormat::Depth16Unorm),
] {
let b = scalar(fb, t.u32_, u64::from(texel_format(format).0))?;
let b = value(fb, b)?;
bits = fb.select(class, b, bits)?;
}
let word = match c.function {
Comparison::Function(_) => None,
Comparison::Word => Some(word_of(cx, fb, s)?),
};
let one = match (word, &s.op) {
(Some(w), SampleOp::Sample { .. }) => Some(one_texel(fb, &t, w)?),
_ => None,
};
let texel = match &c.fetch {
None => plain(fb, si)?,
Some(f) => {
let level = super::fetched::level(cx, fb, &t, s, (f.level, word), si)?;
let Some(taps) = f.taps(s, level, word) else {
return Err(cx.fail("a word-addressed heap fetch without its word"));
};
let x = super::fetched::texels(cx, fb, &t, s, (si, image), Bits::Value(bits), &taps)?;
let fetched = depths(fb, &x)?;
match one {
// The level the word reads (`fetched::FetchLevel::Word`).
Some(_) if matches!(f.level, super::fetched::FetchLevel::Word(_)) => fetched,
// At an implicit level or gradients, level 0's texel where the word states no mip
// filter; under a nearest one, whose level the function does not know, the
// sample's.
Some((_, mip)) => {
let read = plain(fb, si)?;
let none = fb.binary(BinOp::IEqual, mip, zero)?;
fb.select(none, fetched, read)?
}
None => fetched,
}
}
};
let passes = passes(cx, fb, (s, c), (texel, word), Bits::Value(bits))?;
let class = fb.binary(BinOp::LogicalOr, codes, values)?;
let take = match one {
Some((one, _)) => fb.binary(BinOp::LogicalAnd, class, one)?,
None => class,
};
fb.select(take, passes, device)
}
/// The passes of `c` over `texel`, the depths the device read for `s`: a gather's four (a
/// `vec4`), or a sample's one. The slot's `TexelFormat` specialization says how they compare.
pub(super) fn emit(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
s: &Sampling,
c: &Compared,
texel: SValue,
) -> BResult<SValue> {
let Some(texture) = c.slot() else {
return Err(cx.fail("a heap comparison past its own path"));
};
let Some(spec) = crate::lower::texture::texel_format_const(cx, texture) else {
return Err(cx.fail(format!(
"texture slot {texture} has no `TexelFormat` specialization"
)));
};
let word = match c.function {
Comparison::Function(_) => None,
Comparison::Word => Some(word_of(cx, fb, s)?),
};
passes(cx, fb, (s, c), (texel, word), Bits::Spec(spec))
}
/// The word of the runtime or argument buffer's sampler of `s` (a `u32`): its slot's
/// `SamplerState` specialization, or its table entry's flags.
fn word_of(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, s: &Sampling) -> BResult<SValue> {
match super::emit::word_pixel(s) {
Some(pixel) => super::emit::sampler_word(cx, fb, pixel),
None => Err(cx.fail("a runtime sampler's comparison without its word")),
}
}
/// The passes of `c` over `texel` (a gather's four depths, a `vec4`, or a sample's one) of a
/// texture bound in the format whose treatment is `bits`, under a runtime or argument buffer's
/// sampler's word `word` where `c` compares by it.
fn passes(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
(s, c): (&Sampling, &Compared),
(texel, word): (SValue, Option<SValue>),
bits: Bits,
) -> BResult<SValue> {
let t = Tys::new(fb)?;
let dref = super::emit::reference(cx, fb, s, c.dref)?;
let test = TapCompare::of(cx, fb, &t, (c.function, word), (dref, bits))?;
match s.op {
SampleOp::Gather { .. } => {
let mut passes = [texel; 4];
for (k, pass) in passes.iter_mut().enumerate() {
let depth = fb.composite_extract(texel, &[k as u32])?;
*pass = test.pass(fb, depth)?;
}
fb.composite_construct(t.vec4, &passes)
}
_ => test.pass(fb, texel),
}
}
/// The `f32` constant `v`.
fn float(fb: &mut FunctionBuilder<'_>, v: f32) -> BResult<SValue> {
let ty = fb.module().ty(SType::Float { width: 32 })?;
let c = fb.module().constant(Constant::Scalar {
ty,
bits: ConstBits(u64::from(v.to_bits())),
})?;
fb.module().const_value(c)
}
+30 -414
View File
@@ -3,8 +3,8 @@
use crate::lower::emit::EmitCx;
use crate::lower::texture::half::{HalfForm, TexelOrigin};
use crate::lower::texture::{
float_class, half_class, heap_element, held_texel, live_or_zero, resident_access, sparse_spec,
tile_map, tiled_word, with_word, ImageRef,
half_class, heap_element, held_texel, live_or_zero, resident_access, sparse_spec, tile_map,
tiled_word, with_word, ImageRef,
};
use crate::spirv::builder::constructs::{ArmEnd, ArmFn, Merged};
use crate::spirv::builder::ops::image::ArmedOffset;
@@ -19,7 +19,6 @@ use crate::spirv::ir::{
use crate::air::ir::ValueId;
use crate::lower::texture::TexelClass;
use crate::memory::handles::{entry_field, EntryField};
use crate::metal::bicubic::BicubicTexels;
use crate::metal::sampler::SamplerWord;
use super::{
@@ -1070,49 +1069,20 @@ pub(super) fn sampled_value(
// bias past the device's limit scales, and from which Metal's footprint of an observed access
// follows.
let plane = coord;
// A runtime sampler's level by its word: the level handed to the device, and the one its
// nearest snap reads.
let (lambda, nearest) = word_level(cx, fb, s)?;
// The device reads a coordinate snapped onto the texels Metal reads; a runtime sampler's
// nearest one behind its word.
// The device reads a coordinate snapped onto the texels Metal reads.
if let Some(snap) = &s.snap {
coord = match snap.kind {
super::position::SnapKind::Word { leveled, .. } => {
let word = sampler_word(cx, fb, s.pixel)?;
// A runtime sampler's sample scales pixel coordinates, so its base level's size
// is queried; a leveled snap queries the size of the level it reads.
// Metal's offset rule reads the level's size and the base level's.
let (size, base) = match (leveled, nearest, level0) {
(true, Some(nearest), Some((img, base))) => {
(word_level_size(fb, word, nearest, img)?, Some(base))
}
(false, _, Some((_, size))) => (size, None),
_ => return Err(cx.fail("a word snap without its level's size")),
};
let offsets = snap_offsets(cx, fb, op_offset(&s.op), s.lanes)?;
let parent = offset_base(cx, s)?;
super::position::snapped_by_word(
fb,
(word, leveled),
(coord, &offsets, parent),
s.lanes,
(size, base, size_lanes),
)?
}
// A runtime or argument buffer's sampler's gather, and on a device with Metal's own
// sampler its linear pixel sample, on the base level's size the pixel coordinates
// queried, from the coordinate as given.
super::position::SnapKind::WordGather { metal } => {
// A runtime or argument buffer's sampler's gather, and its linear pixel sample, on the
// base level's size the pixel coordinates queried, from the coordinate as given.
super::position::SnapKind::WordGather => {
let word = sampler_word(cx, fb, s.pixel)?;
let Some((_, size)) = level0 else {
return Err(cx.fail("a word gather without its base level's size"));
};
let offsets = snap_offsets(cx, fb, op_offset(&s.op), s.lanes)?;
let parent = offset_base(cx, s)?;
super::position::gathered_by_word(
fb,
(word, metal),
(given, coord, &offsets, parent),
word,
(given, coord),
s.lanes,
(size, size_lanes),
)?
@@ -1131,9 +1101,8 @@ pub(super) fn sampled_value(
)?
}
_ => {
let from = if snap.pixel { given } else { coord };
let offsets = snap_offsets(cx, fb, op_offset(&s.op), s.lanes)?;
let at = (from, offsets.as_slice(), offset_base(cx, s)?);
let at = (given, offsets.as_slice(), offset_base(cx, s)?);
super::position::snapped(cx, fb, snap, at, s.lanes, (si, image))?
}
};
@@ -1175,138 +1144,9 @@ pub(super) fn sampled_value(
cx,
fb,
s,
(plane, grad, lambda, true),
(plane, grad, true),
(lod, *min_lod, offset, *dref),
)?;
// A heap texture's comparison: the device's, and the shader's of the depths read
// without comparison where the handle states the texture's class. Its sampler is not
// one a dynamic bias may take past the device's limit, and it observes no residency, so
// the word is 0. A depth sample reads the first component.
if let Some(c) = s.compared.as_ref().filter(|c| c.on_heap()) {
if beyond.is_some() {
return Err(cx.fail("a heap comparison biased past the device's limit"));
}
let device = sample_access(coord, dref, ops)(fb, si, false)?;
let plain = sample_access(coord, None, ops);
let x = super::compared::heap(cx, fb, (s, c), device, &|fb, si| {
let x = plain(fb, si, false)?;
fb.composite_extract(x, &[0])
})?;
let x = live_or_zero(fb, live, x)?;
return texel_value(cx, fb, s, image, (x, TexelOrigin::Computed), None);
}
// A constexpr sampler's blend of two levels' comparisons under a linear mip filter,
// made in the shader where the slot's format is measured, else the device's. Its level
// is explicit, so no bias passes the device's limit, and it observes no residency, so
// the word is 0.
if let Some(c) = s.compared.as_ref().filter(|c| c.blends()) {
if beyond.is_some() {
return Err(cx.fail("a blended comparison biased past the device's limit"));
}
let access = sample_access(coord, dref, ops);
let x = super::compared::blended(cx, fb, (s, c, image), &|fb, si| {
access(fb, si, false)
})?;
return with_word(cx, fb, &s.result, x, None);
}
// A runtime sampler's comparison, made in the shader where the bound sampler reads
// one texel, else filtered as below. Its sampler is not one a dynamic bias may take
// past the device's limit, and it observes no residency, so the word is 0.
if let Some(c) = s.compared.as_ref().filter(|c| c.keeps_reference(&s.op)) {
let (Some(form), None) = (s.texel, beyond) else {
return Err(cx.fail("a branched comparison without its form, or biased past"));
};
let access = sample_access(coord, dref, ops);
let plain = sample_access(coord, None, ops);
let filtered: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| {
let x = match &s.linear {
Some(l) => super::linear::emit(
cx,
fb,
s,
(plane, image, dref),
l,
&|fb, si| access(fb, si, false),
None,
)?,
None => {
let (si, _, _) = sampled_image(cx, fb, s.source)?;
let x = access(fb, si, false)?;
held_texel(fb, image.texel, form, x)?
}
};
Ok(ArmEnd::FallThrough(vec![x]))
});
let x = super::compared::runtime_sample(
cx,
fb,
(s, c, image),
&|fb, si| plain(fb, si, false),
filtered,
)?;
return with_word(cx, fb, &s.result, x, None);
}
// Metal's linear filter emulated where the slot's bound format is measured, else the
// device's sample, branched on the slot's `TexelFormat` specialization. It observes no
// residency, so the word is 0. The emulation's sampler has no mip filter and filters
// alike on both sides of level 0, so no bias moves its texel; the device's sample takes
// a bias decided per invocation as the plain one does ([`device_access`]). A depth
// comparison's value is a scalar; a depth sample without comparison reads the first
// component.
if let Some(l) = s.linear.as_ref().filter(|l| l.image.slot().is_some()) {
// A native class's device sample reads Metal's footprint step (`native`).
let (coord, native) = match super::native::slot_facts(cx, fb, s, l)? {
Some(facts) => {
match super::native::coordinate(cx, fb, s, l, (plane, coord), facts)? {
Some((at, native)) => (at, Some(native)),
None => (coord, None),
}
}
None => (coord, None),
};
let device = device_access(coord, dref, ops, beyond);
let x = super::linear::emit(cx, fb, s, (plane, image, dref), l, &device, native)?;
let x = if s.depth && dref.is_none() {
fb.composite_extract(x, &[0])?
} else {
held_constants(cx, fb, s, x)?
};
return with_word(cx, fb, &s.result, x, None);
}
// A comparison whose texel the shader fetches, where the bound format is measured; it
// observes no residency, so the word is 0.
if let Some(c) = &s.compared {
if let Some(f) = &c.fetch {
let device = device_access(coord, dref, ops, beyond);
let x = super::compared::fetched(cx, fb, s, (c, f), image, &device)?;
return texel_value(cx, fb, s, image, (x, TexelOrigin::Computed), None);
}
}
// A plain nearest sample whose texel the shader fetches, where the bound format is a
// 32-bit float one and a runtime sampler's word states one texel, else the device's
// sample, which takes a bias decided per invocation as the plain one does
// ([`device_access`]); it observes no residency, so the word is 0. A depth sample reads
// the first component.
if let (Some((p, texture)), Source::Combined(key)) = (
s.fetched.as_ref().and_then(|p| Some((p, p.image.slot()?))),
s.source,
) {
let device = device_access(coord, dref, ops, beyond);
let x = super::fetched::branch(
cx,
fb,
(s, key),
(texture, &p.fetch, BicubicTexels::LINEAR, true),
image,
&super::fetched::one,
&device,
)?;
let x = match s.depth {
true => fb.composite_extract(x, &[0])?,
false => x,
};
return texel_value(cx, fb, s, image, (x, TexelOrigin::Computed), None);
}
let (x, word) = observe(cx, fb, si, &sample_access(coord, dref, ops))?;
// Past the device's limit the sample with the scaled derivatives replaces the
// implicit one; the implicit sample stays where it was, unconditional.
@@ -1367,57 +1207,12 @@ pub(super) fn sampled_value(
dref,
offset,
} => {
// Metal's cube footprint emulated by fetches, where the slot's bound format's corner
// rule is measured, else the device's gather. It observes no residency, so the word is
// 0; a raw gather's value is already its held texel.
if let Some(g) = &s.cube_gather {
let component = *component;
let dref = match dref {
Some(r) => Some(reference(cx, fb, s, *r)?),
None => None,
};
let device = |fb: &mut FunctionBuilder<'_>, si: SValue| match dref {
Some(r) => fb.dref_gather(si, coord, r, &ImageOperands::default()),
None => fb.gather(si, coord, component, &ImageOperands::default()),
};
let at = (plane, component, dref);
let x = super::linear::gather(cx, fb, s, at, g, &device)?;
return match g.raw {
true => {
let x = held_constants(cx, fb, s, x)?;
with_word(cx, fb, &s.result, x, None)
}
false => texel_value(cx, fb, s, image, (x, TexelOrigin::Computed), None),
};
}
let mut ops = ImageOperands::default();
offset_operands(cx, fb, offset, s.lanes, &mut ops)?;
let component = *component;
// A heap texture's comparison gather: the device's, and the shader's of the depths
// gathered without comparison where the handle states the texture's class; it observes
// no residency, so the word is 0.
if let (Some(c), Some(r)) = (s.compared.as_ref().filter(|c| c.on_heap()), dref) {
let r = cx.operand(fb, *r)?;
let device = fb.dref_gather(si, coord, r, &ops)?;
let x = super::compared::heap(cx, fb, (s, c), device, &|fb, si| {
fb.gather(si, coord, 0, &ops)
})?;
let x = live_or_zero(fb, live, x)?;
return texel_value(cx, fb, s, image, (x, TexelOrigin::Computed), None);
}
// A comparison gather whose taps the shader fetches, where the bound format is
// measured; it observes no residency, so the word is 0.
if let Some(c) = &s.compared {
if let Some(f) = &c.fetch {
let x = super::compared::fetched(cx, fb, s, (c, f), image, &|fb, si| {
fb.gather(si, coord, component, &ops)
})?;
return texel_value(cx, fb, s, image, (x, TexelOrigin::Computed), None);
}
}
// A plain gather whose taps the shader fetches, where the bound format is a 32-bit
// float one: component `component` of each tap's texel, else the device's gather. It
// observes no residency, so the word is 0.
// A `half` gather whose taps the shader fetches, where the bound format is a
// half-float one: component `component` of each tap's texel, else the device's gather.
// It observes no residency, so the word is 0.
if let (Some((p, texture)), Source::Combined(key)) = (
s.fetched.as_ref().and_then(|p| Some((p, p.image.slot()?))),
s.source,
@@ -1426,9 +1221,8 @@ pub(super) fn sampled_value(
cx,
fb,
(s, key),
(texture, &p.fetch, super::fetched::CLASSES, true),
(texture, &p.fetch),
image,
&|fb, texels| super::fetched::plain_value(fb, s, texels),
&|fb, si| fb.gather(si, coord, component, &ops),
)?;
return texel_value(cx, fb, s, image, (x, TexelOrigin::Computed), None);
@@ -1485,25 +1279,13 @@ pub(super) fn sampled_value(
};
// Metal's value of texels in a sparse image's block that holds no mapped tile.
let texel = unmapped_value(cx, fb, s, texel, named)?;
// A comparison the shader makes of the depths the device read.
let texel = match &s.compared {
Some(c) => super::compared::emit(cx, fb, s, c, texel)?,
None => texel,
};
// A heap texture's plain gather or nearest sample: the texels the shader fetches where the
// class its handle carries is the 32-bit float one, else the device's.
// A heap texture's `half` gather: the texels the shader fetches where the class its handle
// carries is the half-float one, else the device's.
let texel = match s.fetched.as_ref().filter(|p| p.image.slot().is_none()) {
Some(p) => super::fetched::heap(cx, fb, s, image, p, texel)?,
None => texel,
};
let texel = live_or_zero(fb, live, texel)?;
// A heap texture's linear sample: Metal's filter emulated where the class its handle carries
// is measured, else the device's sample just made. It observes no residency.
if let Some(l) = s.linear.as_ref().filter(|l| l.image.slot().is_none()) {
let held = held_value(cx, fb, s, image, (texel, TexelOrigin::Computed))?;
let x = super::linear::emit_heap(cx, fb, s, image, l, held)?;
return with_word(cx, fb, &s.result, x, word);
}
texel_value(cx, fb, s, image, (texel, TexelOrigin::Image), word)
}
@@ -1646,9 +1428,7 @@ fn word_states(fb: &mut FunctionBuilder<'_>, word: SValue, mask: u32) -> BResult
/// `u size` of the scaled coordinate can round onto the next integer, so the texel's centre, half a
/// texel from either edge, names it on every device. A coordinate outside the texture keeps its
/// centre outside it, where clamping to the edge, to zero, or to a border, or mirroring once and
/// clamping, reads what Metal reads; where Metal drops a texel offset the device adds
/// ([`Sampling::centre_offset`]), the centre moves back by it (`position::pixel_centre_by_word`).
/// `None` for any other sampling: a gather or a comparison keeps the scaled coordinate, whose
/// clamping, reads what Metal reads. `None` for any other sampling: a gather or a comparison keeps the scaled coordinate, whose
/// texels are the device's.
fn pixel_centre(
cx: &mut EmitCx<'_>,
@@ -1660,13 +1440,13 @@ fn pixel_centre(
if !s.centred {
return Ok(None);
}
let (nearest, word) = match s.pixel {
let nearest = match s.pixel {
Pixel::None => return Ok(None),
Pixel::Always => (None, None),
Pixel::Always => None,
// A runtime sampler: its word's nearest pixel sampler.
Pixel::Spec(_) | Pixel::Heap(_) => {
let word = sampler_word(cx, fb, s.pixel)?;
(Some(word_states(fb, word, s.centre_word)?), Some(word))
Some(word_states(fb, word, s.centre_word)?)
}
};
let floor = fb.glsl(GlslOp::Floor, &[coord])?;
@@ -1687,21 +1467,6 @@ fn pixel_centre(
};
let half = fb.module().const_value(half)?;
let centre = fb.binary(BinOp::FAdd, floor, half)?;
// A texel offset Metal drops on a mirror-clamped axis, which the device adds.
let centre = match (s.centre_offset, word) {
(true, Some(word)) => {
let offsets = snap_offsets(cx, fb, op_offset(&s.op), s.lanes)?;
let parent = offset_base(cx, s)?;
super::position::pixel_centre_by_word(
fb,
word,
(centre, &offsets, parent),
s.lanes,
(size, size_lanes),
)?
}
_ => centre,
};
let centre = scale(fb, centre, size, s.lanes, size_lanes)?;
Ok(Some((nearest, centre)))
}
@@ -1906,8 +1671,7 @@ pub(super) type Beyond = Option<(SValue, (SValue, SValue))>;
/// The operands of sample `s` (level `lod`, `min_lod` clamp, `offset`, comparison `dref`) at
/// plane coordinate `plane` with gradients `grad`: its image operands, its comparison reference,
/// and for a bias decided per invocation the test and the gradients that replace the `Bias`
/// operand where it holds, both in the implicit sample's own position. A runtime sampler's level by
/// its word ([`word_level`]'s `lambda`) is handed in place of the sample's own. An `unshared`
/// operand where it holds, both in the implicit sample's own position. An `unshared`
/// sample's axis gradients read its texture's level-0 size and its sampler's word; a shared one (a
/// switch-at-use's emulation, whose arms' samplers differ) takes the derivatives scaled by `2^B`
/// through every sampler, the isotropic route.
@@ -1915,7 +1679,7 @@ pub(super) fn sample_operands(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
s: &Sampling,
(plane, grad, lambda, unshared): (SValue, Option<(SValue, SValue)>, Option<SValue>, bool),
(plane, grad, unshared): (SValue, Option<(SValue, SValue)>, bool),
(lod, min_lod, offset, dref): (&Lod, Option<ValueId>, &Option<Offset>, Option<ValueId>),
) -> BResult<(ImageOperands, Option<SValue>, Beyond)> {
let mut ops = ImageOperands::default();
@@ -1924,14 +1688,14 @@ pub(super) fn sample_operands(
Lod::Implicit { bias, reach } => {
if let Some(b) = bias {
let b = cx.operand(fb, *b)?;
// Metal's reading of the bias, but where Metal's own sampler reads it.
// Metal's reading of the bias, but where the device's sampler reads it.
let b = match reach {
BiasReach::Metal => b,
_ => metal_bias(fb, b)?,
};
// The level-0 size the axis gradients read, where they are taken.
let axes = match reach {
BiasReach::Axes | BiasReach::Either { word: true, .. } if unshared => {
BiasReach::Axes if unshared => {
// A sampled image is consumed in the block that makes it.
let (si, image, _) = sampled_image(cx, fb, s.source)?;
let img = fb.image(si)?;
@@ -1956,26 +1720,13 @@ pub(super) fn sample_operands(
BiasReach::Either {
max_bias_bits,
sampler_bias_bits,
word,
} => {
// The derivatives in the implicit sample's own position, before any
// branch: both need the fragment's uniform control flow.
let scaled = plane_bias_gradients(fb, plane, b, s.lanes)?;
let past = past_limit(fb, b, max_bias_bits, sampler_bias_bits)?;
// Where the sampler's word states its anisotropy, the axis gradients
// replace the `Bias` operand within the limit too.
let (test, grads) = match (word, axes, word_pixel(s)) {
(true, Some(size), Some(pixel)) => {
let axis = plane_axis_gradients(fb, plane, b, size)?;
let w = sampler_word(cx, fb, pixel)?;
let anisotropic = word_states_any(fb, w, SamplerWord::ANISOTROPIC)?;
let grads = by_anisotropy(fb, w, axis, scaled)?;
(fb.binary(BinOp::LogicalOr, past, anisotropic)?, grads)
}
_ => (past, scaled),
};
ops.bias = Some(b);
beyond = Some((test, grads));
beyond = Some((past, scaled));
}
}
}
@@ -1985,15 +1736,6 @@ pub(super) fn sample_operands(
Lod::Base { bias, min } => ops.lod = Some(base_level(cx, fb, *bias, *min)?),
Lod::Grad(..) | Lod::CubeGrad(..) | Lod::Hoisted => ops.grad = grad,
}
// The level on Metal's grid, a runtime sampler's by its word.
match (&s.level, ops.lod, lambda) {
(Some(super::level::LevelRule::Stated(snap)), Some(l), None) => {
ops.lod = Some(snap.emit(fb, l)?);
}
(Some(super::level::LevelRule::Word), Some(_), Some(l)) => ops.lod = Some(l),
(None, _, None) => {}
_ => return Err(cx.fail("a sample's level rule without its level")),
}
if let Some(m) = min_lod {
ops.min_lod = Some(cx.operand(fb, m)?);
}
@@ -2054,32 +1796,6 @@ pub(super) fn reference(
fb.glsl(GlslOp::NClamp, &[r, zero, one])
}
/// The device's sample at `coord` with comparison `dref` and operands `ops`, from the sampled
/// image it is handed, in an arm of a wrapper that reads the texel otherwise elsewhere (a linear
/// sample's emulation, a plain or a comparison's fetch, a switch-at-use's candidates). Where a
/// bias is decided per invocation (`beyond`), the sample with its gradients from the same sampled
/// image, selected where the test holds: the arm's block consumes the one sampled image it is
/// handed, and the gradients were taken before the wrapper's branch, in the implicit sample's own
/// position.
pub(super) fn device_access(
coord: SValue,
dref: Option<SValue>,
ops: ImageOperands,
beyond: Beyond,
) -> impl Fn(&mut FunctionBuilder<'_>, SValue) -> BResult<SValue> {
move |fb, si| {
let x = fb.sample(si, coord, dref, false, &ops)?;
let Some((test, grads)) = beyond else {
return Ok(x);
};
let mut grad_ops = ops;
grad_ops.bias = None;
grad_ops.grad = Some(grads);
let past = fb.sample(si, coord, dref, false, &grad_ops)?;
fb.select(test, past, x)
}
}
/// The access of a sample at `coord` with comparison `dref` and operands `ops`, from the sampled
/// image it is handed, in its sparse form where asked.
pub(super) fn sample_access(
@@ -2249,56 +1965,6 @@ fn base_level(
Ok(level)
}
/// A runtime or argument buffer's sampler's level of sample `s` by its word (`level::by_word`): the
/// level handed to the device where `s.level` is the word's rule, and the level before the
/// sampler's clamp that a nearest mip filter reads (an `f32`) where its snap is leveled. A sample
/// at level 0 hands its own (on every rule's grid) and reads 0 there.
pub(super) fn word_level(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
s: &Sampling,
) -> BResult<(Option<SValue>, Option<SValue>)> {
let rule = matches!(s.level, Some(super::level::LevelRule::Word));
let leveled = matches!(
s.snap,
Some(super::position::Snap {
kind: super::position::SnapKind::Word { leveled: true, .. },
..
})
);
if !rule && !leveled {
return Ok((None, None));
}
let SampleOp::Sample { lod, .. } = &s.op else {
return Err(cx.fail("a word level without its sample"));
};
let x = match lod {
Lod::Level(Some(l)) => Some(cx.operand(fb, *l)?),
Lod::Base {
bias: Some(b),
min: None,
} => Some(cx.operand(fb, *b)?),
Lod::Level(None)
| Lod::Base {
bias: None,
min: None,
} => None,
_ => return Err(cx.fail("a word level without a level the function knows")),
};
let Some(x) = x else {
if rule {
return Err(cx.fail("a word level rule of level 0"));
}
return Ok((None, Some(f32_const(fb, 0)?)));
};
let Some(pixel) = word_pixel(s) else {
return Err(cx.fail("a word level without its sampler's word"));
};
let word = sampler_word(cx, fb, pixel)?;
let (lambda, nearest) = super::level::by_word(fb, word, x)?;
Ok((rule.then_some(lambda), leveled.then_some(nearest)))
}
/// Where the word of sample `s`'s runtime or argument buffer's sampler is read: its pixel
/// handling's, else (a cube's) its source's sampler slot or sampler table entry.
pub(super) fn word_pixel(s: &Sampling) -> Option<Pixel> {
@@ -2324,23 +1990,6 @@ pub(super) fn word_pixel(s: &Sampling) -> Option<Pixel> {
}
}
/// The size of the level a runtime sampler's leveled nearest snap reads of image `img`
/// (`level::snap_level` of its word `word` and level `nearest`, clamped into the image's levels).
pub(super) fn word_level_size(
fb: &mut FunctionBuilder<'_>,
word: SValue,
nearest: SValue,
img: SValue,
) -> BResult<SValue> {
let level = super::level::snap_level(fb, word, nearest)?;
let levels = fb.query(ImageQuery::Levels, img)?;
let one = fb.u32_const(1)?;
let one = fb.module().const_value(one)?;
let last = fb.binary(BinOp::ISub, levels, one)?;
let level = fb.glsl(GlslOp::UMin, &[level, last])?;
fb.query(ImageQuery::SizeLod(level), img)
}
/// The texel a nearest, clamp-to-edge pixel sampler returns, exactly: `OpImageFetch` of the base
/// level at `clamp(floor(coord) + offset, 0, size - 1)`, the layer clamped into the array as
/// sampling clamps it. A depth texel is its first component. Under a sparse arm the fetch's status
@@ -2614,9 +2263,8 @@ pub(super) fn held_value(
return crate::lower::texture::srgb_raw_texel(cx, fb, form, texel, color);
}
// A `half` texel of a slot converts by the bound format's class: a gather's texel as a read's,
// a sample's (nearest, linear, or fetched) filtered value as a sample's; a `float` texel that
// may be one texel's likewise. Each takes the access's lanes. Not where the sample's texel is
// the device's (`Sampling::half_texel`): it is held.
// a sample's (nearest, linear, or fetched) filtered value as a sample's, each with the access's
// lanes. Not where the sample's texel is the device's (`Sampling::half_texel`): it is held.
let half = match s.source {
Source::Combined(key) if !s.depth && s.half_texel => {
half_class(cx, &ImageRef::Slot(key.texture), form)
@@ -2628,24 +2276,8 @@ pub(super) fn held_value(
}
_ => None,
};
let float = match s.source {
Source::Combined(key) if s.float_texel => {
match float_class(cx, &ImageRef::Slot(key.texture), form) {
Some(f) => Some(f),
None => return Err(cx.fail("a `float` sample without its conversion routine")),
}
}
// A heap texture's by the class its handle carries; a depth texture's too.
Source::Heap { handle, .. } | Source::HeapSampler { handle, .. } if s.float_texel => {
match crate::lower::texture::heap_float_class(cx, fb, handle, form)? {
Some(f) => Some(f),
None => return Err(cx.fail("a `float` sample without its conversion routine")),
}
}
_ => None,
};
Ok(match (half, float) {
(Some(h), _) => {
Ok(match half {
Some(h) => {
let access = match s.op {
SampleOp::Gather { .. } => HalfForm::Read,
_ => HalfForm::Sample,
@@ -2653,23 +2285,7 @@ pub(super) fn held_value(
let lanes = sample_lanes(cx, fb, s)?;
h.convert(fb, texel, (access, lanes), origin)?
}
(None, Some(f)) => {
let lanes = sample_lanes(cx, fb, s)?;
// A depth sample's value is its texel's first lane (a scalar): converted as that lane
// of the texel, every lane of which it fills.
let ty = fb.value_ty(texel)?;
let lane = !matches!(fb.module().types().get(ty)?, SType::Vector { .. });
let x = if lane {
let four = fb.module().ty(SType::Vector { elem: ty, len: 4 })?;
let texel = fb.composite_construct(four, &[texel; 4])?;
let x = f.convert(fb, texel, lanes)?;
fb.composite_extract(x, &[0])?
} else {
f.convert(fb, texel, lanes)?
};
held_texel(fb, image.texel, form, x)?
}
(None, None) => held_texel(fb, image.texel, form, texel)?,
None => held_texel(fb, image.texel, form, texel)?,
})
}
+4 -566
View File
@@ -36,8 +36,8 @@
//! size below `2^23`, and the footprint it reads through a gather or a linear filter on every size
//! below `2^15` (the position quantizes to 1/256 of a texel), above Metal's largest cube face,
//! 16,384. Every other component passes unchanged. A gather or linear sample at a zero direction,
//! like one aimed at any corner, reads a corner texel Vulkan leaves to the device
//! (`PrecisionNote::DeviceGatherFootprint`, `PrecisionNote::FloatSampleFilter`).
//! like one aimed at any corner, reads a corner texel Vulkan leaves to the device (its answer,
//! `PrecisionNote::DeviceSampling` where its sampler is not Metal's).
//!
//! **A huge major magnitude.** Devices misread a direction whose major magnitude is near the top
//! of the range (the probe lanes, `wrg_cube_ties` at 8x8 and 5x5): RADV (AMD Radeon 780M)
@@ -50,56 +50,6 @@
//! at most `2^125`, and no quotient moves, since every component scaled by `1/2` that Metal reads
//! (at least `2^-125`) stays normal.
//!
//! **The texel on the face** (`snapped`). Along `(1, 1 + 2^-23, 0.25)` (a tie's control) the
//! quotient `0.25 / (1 + 2^-23)` is `1/4 - 2^-25` and the face coordinate `(q + 1) / 2` just below
//! `0.625`. Metal reads texel 5 of an 8x8 face there, `0.625 * 8`, as RADV and lavapipe do; ANV and
//! NVIDIA read texel 4, as keeping the bits below would, on all 24 such lanes. Metal's position on
//! a face axis of size `n` (the four cube rounding probes, Apple M4 on macOS 27.0.1 and Apple M3
//! Max on macOS 26.7, byte-identical, each run with and without Metal's validation layer): with `r`
//! its texture unit's reciprocal of the major magnitude `|m_a|` and `s_c` the minor component as
//! the face orients it, `F = RN(1 + s_c * r)`, fused and rounded once with ties to even, and `X =
//! RN(F / 2 * n)`; a nearest sample reads `floor(X)`, at most `n - 1`, and a gather or linear
//! filter quantizes `X` as in 2D, `floor(256 X + 1/2)` (860 of 868 interior lanes; the other 8 are
//! not explained). Twelve other orders fit worse (the quotient first, an unfused sum, a fused
//! scale, an exact quotient, among others), and rounding the sum's ties away from zero misses 2,112
//! of 6,336 tie coordinates, toward zero 1,812 of 5,436, all of which ties to even reads. The
//! texture unit's `r` is not correctly rounded: it equals `RN(1 / |m_a|)` on 1,793 of 2,001 random
//! majors, and lies above it on 204 and below on 4, by one ulp or two (the lanes tell those apart
//! from `RN(1 / |m_a|)`, not from each other), each a major whose reciprocal lies within about 0.2
//! ulp of a rounding midpoint; the shader's own `1.0f / m_a` and `precise::divide` are `RN(1 /
//! |m_a|)` on all of them. It is Metal's fast reciprocal; no exact form of it is known.
//!
//! **A repeating face axis** ([`FaceWrap`]). Metal reads every other address mode of a cube's
//! sampler as clamping, but `repeat` on a face axis whose size is not a power of two wraps that
//! axis's face coordinate `F / 2` of exactly 1 (a minor component equal to the major magnitude,
//! after the reciprocal) to 0, so `X = 0`: the face's other edge. The sampler's `s` address governs
//! the face's `s` axis and its `t` address the `t` axis; its `r` address governs neither, and a
//! size that is a power of two never wraps (our cube probes, Apple M4 on macOS 27.0.1: gathers,
//! linear samples, and nearest samples of identity cubes of 3, 5, and 6 texels wrap on every such
//! lane under `repeat` on both axes, on the `s` axis alone under `s_address::repeat`, and on the
//! `t` axis alone under `t_address::repeat`, and of 4 and 8 texels on none; `mirrored_repeat`,
//! `clamp_to_zero`, and a border read as clamping everywhere). A tied
//! minor component, which `metal_ties` shrinks by an ulp, still sums to `F = 2` (`1 + (1 - 2^-24)`
//! rounds to 2 with ties to even), so it wraps as Metal's tie does.
//!
//! So a nearest sample through a constexpr normalized sampler that reads the base level, on a
//! device without `VkProperty::MetalSampler`, hands the device the direction whose major component
//! is `±1` and whose minor components are the centres of the texels Metal's position names with
//! `r` the device's `1 / |m_a|` (Metal's own where the device's functions are Metal's in a
//! fast-math entry, else `PrecisionNote::NativeDivision`) and the fused multiply-add, wrapped on a
//! repeating face axis ([`FaceWrap`]): each `(2i + 1) / n - 1`, oriented as Vulkan's face table
//! orients it, which every device reads at the face coordinate `(i + 1/2) / n`, half a texel from
//! either edge. Where that reciprocal misses Apple's and `X` lies within about `n * 2^-23` of a
//! texel edge, Metal reads the next texel, which the module records
//! (`PrecisionNote::CubeFaceReciprocal`). A linear sample that Metal's filter answers takes the
//! same position (`position`) and reads its taps by fetches, across a face's edges through
//! `define_fold` (`linear::cube`), under the same note, and so does a cube gather (a depth cube's
//! comparison included), which reads the same four taps in gather order, through a constexpr
//! sampler or a runtime sampler slot, whose word's address modes wrap the face axes
//! (`Wraps::Word`). A nearest sample's comparison, a runtime or argument buffer's sampler, and
//! another level keep the device's position; on `VkProperty::MetalSampler` the sample is Metal's
//! own.
//!
//! A direction with an infinite or NaN component passes unchanged, and the device's answer
//! stands: no infinity becomes finite and no NaN moves. Metal's is measured and not reproduced:
//! it reads a face coordinate of `±inf / inf` at texel 0 and `(inf, 0, 0)` at the centre of `+x`;
@@ -108,19 +58,11 @@
//! direction's derivatives sees each broken tie as a face coordinate moved by at most `2^-24`
//! (`PrecisionNote::CubeGradientFootprint`).
use crate::error::Error;
use crate::lower::arith::fma::{self, Fma};
use crate::lower::arith::legal::{FloatFmt, Form, Held};
use crate::lower::select::SelectCx;
use crate::metal::sampler::SamplerWord;
use crate::pipeline::artifact::PrecisionNote;
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::builder::FunctionBuilder;
use crate::spirv::error::BResult;
use crate::spirv::ids::{FuncId, Value as SValue};
use crate::spirv::ids::Value as SValue;
use crate::spirv::ir::{BinOp, ConstBits, Constant, ConvOp, GlslOp, Type as SType, UnOp};
use super::bicubic::TapAddress;
/// The estimated words of `metal_ties`: its 89 instructions and 11 constants, at most 6 words each.
pub const TIE_WORDS: u32 = 600;
@@ -279,509 +221,5 @@ pub(super) fn metal_ties(fb: &mut FunctionBuilder<'_>, p: SValue) -> BResult<SVa
fb.composite_construct(triple, &[x, y, z])
}
/// The estimated words of `snapped` beside its reciprocal's use and its two fused multiply-adds'
/// (`Snap::words` adds those): its 70 instructions and 6 constants, at most 6 words each.
pub const SNAP_WORDS: u32 = 480;
/// What `snapped` computes Metal's face position with: the device's reciprocal `1 / y`, and the
/// fused multiply-add `fma`.
#[derive(Clone, Copy, Debug)]
pub struct SnapRoutines {
pub fma: Fma,
}
/// The `float` scalar form the routines take.
pub(super) const SCALAR: Form = Form {
held: Held::Float(FloatFmt::F32),
lanes: 1,
};
/// What Metal's face position takes on a profile ([`SnapRoutines`] as emission takes it): the
/// fused multiply-add `fma`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FaceRoutines {
pub fma: Fma,
}
impl FaceRoutines {
/// The census words a position adds beside its own: the reciprocal's division and the two
/// fused multiply-adds'.
pub(super) fn use_words(self) -> u32 {
16 + 2 * self.fma.words()
}
/// The routines as emission takes them.
pub(super) fn declared(self) -> SnapRoutines {
SnapRoutines { fma: self.fma }
}
}
/// Which face axes of a sample's cube wrap a face coordinate of exactly 1 to 0 where the face size
/// is not a power of two (module docs): those its constexpr sampler addresses by `repeat`, the
/// face's `s` axis by the sampler's `s` address and its `t` axis by its `t` address.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct FaceWrap {
pub s: bool,
pub t: bool,
}
impl FaceWrap {
/// The wrap of a sampler whose `s` and `t` axes address their taps by `s` and `t` (`None`: an
/// axis the sample does not address, which never wraps).
pub(super) fn of(s: Option<TapAddress>, t: Option<TapAddress>) -> FaceWrap {
FaceWrap {
s: s == Some(TapAddress::Repeat),
t: t == Some(TapAddress::Repeat),
}
}
/// The census words the wrap adds to a position: the size's power-of-two test, and per wrapping
/// axis its comparison, condition, subtraction, and select, with their constants.
pub(super) fn words(self) -> u32 {
match (self.s, self.t) {
(false, false) => 0,
(true, true) => WRAP_WORDS + 2 * WRAP_AXIS_WORDS,
_ => WRAP_WORDS + WRAP_AXIS_WORDS,
}
}
}
/// The face axes a cube sample's sampler repeats: a constexpr sampler's ([`FaceWrap`]), or a
/// runtime sampler's, whose word's `s` and `t` address modes the function reads.
#[derive(Clone, Copy)]
pub(super) enum Wraps {
Axes(FaceWrap),
Word(SValue),
}
/// The census words [`Wraps::Word`] adds: both axes' wraps ([`FaceWrap::words`]) and each axis's
/// mode, extracted from the word and tested, with their constants.
pub(super) const WORD_WRAP_WORDS: u32 = WRAP_WORDS + 2 * WRAP_AXIS_WORDS + 64;
/// [`FaceWrap::words`]' power-of-two test of the face size: three instructions and two constants.
const WRAP_WORDS: u32 = 32;
/// [`FaceWrap::words`] per wrapping axis: four instructions and a constant.
const WRAP_AXIS_WORDS: u32 = 32;
/// Per face axis whether it wraps a face coordinate of 1 here: the axes `wrap` names (a runtime
/// sampler's, those whose word's mode is `Repeat`), where the face size `n` (a `u32`) is not a
/// power of two.
fn wrapping(
fb: &mut FunctionBuilder<'_>,
n: SValue,
wrap: Wraps,
) -> BResult<(Option<SValue>, Option<SValue>)> {
if let Wraps::Axes(FaceWrap { s: false, t: false }) = wrap {
return Ok((None, None));
}
let u = |fb: &mut FunctionBuilder<'_>, v: u32| -> BResult<SValue> {
let c = fb.u32_const(v)?;
fb.module().const_value(c)
};
let (zero, one) = (u(fb, 0)?, u(fb, 1)?);
let less = fb.binary(BinOp::ISub, n, one)?;
let low = fb.binary(BinOp::BitwiseAnd, n, less)?;
let odd = fb.binary(BinOp::INotEqual, low, zero)?;
match wrap {
Wraps::Axes(w) => Ok((w.s.then_some(odd), w.t.then_some(odd))),
Wraps::Word(word) => {
let modes = u(fb, 0b111)?;
let repeat = u(fb, crate::metal::SamplerAddressMode::Repeat.as_raw())?;
let mut axes = [odd; 2];
for (axis, shift) in axes.iter_mut().zip(SamplerWord::ADDRESS_SHIFT) {
let sh = u(fb, shift)?;
let mode = fb.binary(BinOp::ShiftRightLogical, word, sh)?;
let mode = fb.binary(BinOp::BitwiseAnd, mode, modes)?;
let repeats = fb.binary(BinOp::IEqual, mode, repeat)?;
*axis = fb.binary(BinOp::LogicalAnd, odd, repeats)?;
}
let [s, t] = axes;
Ok((Some(s), Some(t)))
}
}
}
/// What a sample that takes Metal's face position takes ([`snapped`], [`position`]): the
/// device's reciprocal and the profile's fused multiply-add. The device's reciprocal is Apple's
/// texture unit's on most majors at best, not all (module docs), which the module records
/// (`PrecisionNote::CubeFaceReciprocal`), and the device's division within Vulkan's bound, but
/// where the device's functions are Metal's in an entry Metal compiles with fast math
/// (`PrecisionNote::NativeDivision`).
pub(super) fn plan(cx: &mut SelectCx<'_>) -> Result<FaceRoutines, Error> {
// The sum `1 + sc * r` ([`texel_x`]) is computed between the sample's image and its use, which
// stay in one block, so it takes no branch.
let Some(fma) = Fma::on(cx.profile, SCALAR) else {
return Err(cx.invariant("a cube position without a float fused multiply-add"));
};
cx.families.arith.take_fma(fma);
cx.precision.insert(PrecisionNote::CubeFaceReciprocal);
if cx.profile.fields().float_functions == crate::device::profile::FloatFunctions::Metal {
cx.families
.arith
.unless_metal_fast
.insert(PrecisionNote::NativeDivision);
} else {
cx.precision.insert(PrecisionNote::NativeDivision);
}
Ok(FaceRoutines { fma })
}
/// The reciprocal of the major magnitude `ma` (a `float`): the device's `1 / ma` (`one` is
/// `1.0`).
fn reciprocal(fb: &mut FunctionBuilder<'_>, one: SValue, ma: SValue) -> BResult<SValue> {
fb.binary(BinOp::FDiv, one, ma)
}
/// A cube direction `p` (three floats, `metal_ties`'s) handed to the device so that a nearest
/// sample reads the texel Metal reads on a face of size `n` (a `u32`, the base level's), on every
/// device (module docs): the major component is `±1`, and each minor component the centre of
/// Metal's texel on its face axis, `(2i + 1) / n - 1`, oriented as Vulkan's face table orients
/// it, so that the device's face coordinate is `(i + 1/2) / n`. Metal's texel `i` on an axis is
/// `floor(X)`, at most `n - 1`, of its position `X` ([`texel_x`]), wrapped on the face axes `wrap`
/// names. A direction with an infinite or NaN component passes unchanged.
pub(super) fn snapped(
fb: &mut FunctionBuilder<'_>,
p: SValue,
n: SValue,
(routines, wrap): (SnapRoutines, FaceWrap),
) -> BResult<SValue> {
let f32_ = fb.module().ty(SType::Float { width: 32 })?;
let triple = fb.module().ty(SType::Vector { elem: f32_, len: 3 })?;
let zero = f32_value(fb, 0.0)?;
let one = f32_value(fb, 1.0)?;
let nf = fb.convert(ConvOp::ConvertUToF, n, f32_)?;
let last = fb.binary(BinOp::FSub, nf, one)?;
let fr = frame(fb, p)?;
let (wrap_s, wrap_t) = wrapping(fb, n, Wraps::Axes(wrap))?;
// Metal's reciprocal of `|ma|`, its texture unit's on most majors (module docs).
let r = reciprocal(fb, one, fr.ma)?;
// The centre of Metal's texel on one face axis, as the minor component handed on.
let centre = |fb: &mut FunctionBuilder<'_>,
(flip, c): (SValue, SValue),
wrap: Option<SValue>|
-> BResult<SValue> {
let sc = oriented(fb, flip, c)?;
let x = texel_x(fb, sc, (r, nf), (routines, wrap))?;
let i = fb.glsl(GlslOp::Floor, &[x])?;
let i = fb.glsl(GlslOp::FClamp, &[i, zero, last])?;
let twice = fb.binary(BinOp::FAdd, i, i)?;
let odd = fb.binary(BinOp::FAdd, twice, one)?;
let from = fb.binary(BinOp::FSub, odd, nf)?;
let at = fb.binary(BinOp::FDiv, from, nf)?;
oriented(fb, flip, at)
};
let s = centre(fb, (fr.flip_s, fr.c_s), wrap_s)?;
let t = centre(fb, (fr.flip_t, fr.c_t), wrap_t)?;
let minus = f32_value(fb, -1.0)?;
let unit = fb.select(fr.negative, minus, one)?;
// `x` is `sc` beside a major `y` or `z`; `y` is `tc` beside a major `x` or `z`; `z` is `sc`
// beside a major `x` and `tc` beside a major `y`.
let x = fb.select(fr.major_x, unit, s)?;
let y = fb.select(fr.major_y, unit, t)?;
let st = fb.select(fr.major_x, s, t)?;
let z = fb.select(fr.major_z, unit, st)?;
let x = fb.select(fr.regular, x, fr.cx)?;
let y = fb.select(fr.regular, y, fr.cy)?;
let z = fb.select(fr.regular, z, fr.cz)?;
fb.composite_construct(triple, &[x, y, z])
}
/// Metal's face of a cube direction and its position on each face axis ([`position`]).
pub(super) struct FacePosition {
/// The face, `2 a + m` for the major axis `a` (`x`, `y`, `z`) and `m` 1 where the major
/// component is negative: Vulkan's face order (`+x`, `-x`, `+y`, `-y`, `+z`, `-z`), a `u32`.
pub face: SValue,
/// The position `X` on the face's `s` axis, then on its `t` axis, `f32`s in `[0, n]`.
pub s: SValue,
pub t: SValue,
}
/// Metal's face of cube direction `p` (three floats, `metal_ties`'s) and its position `X` on each
/// axis of a face of size `n` (a `u32`, the base level's): the face of the major axis and its
/// sign, and on each face axis `X = RN(RN(1 + sc * r) / 2 * n)` ([`texel_x`]), wrapped on the
/// face axes `wrap` names, which a linear filter and a gather quantize as in 2D
/// (`floor(256 X + 1/2)`). A direction with an infinite or NaN component gives an unspecified face
/// and position.
pub(super) fn position(
fb: &mut FunctionBuilder<'_>,
p: SValue,
n: SValue,
(routines, wrap): (SnapRoutines, Wraps),
) -> BResult<FacePosition> {
let f32_ = fb.module().ty(SType::Float { width: 32 })?;
let one = f32_value(fb, 1.0)?;
let nf = fb.convert(ConvOp::ConvertUToF, n, f32_)?;
let fr = frame(fb, p)?;
let (wrap_s, wrap_t) = wrapping(fb, n, wrap)?;
let r = reciprocal(fb, one, fr.ma)?;
let sc = oriented(fb, fr.flip_s, fr.c_s)?;
let s = texel_x(fb, sc, (r, nf), (routines, wrap_s))?;
let tc = oriented(fb, fr.flip_t, fr.c_t)?;
let t = texel_x(fb, tc, (r, nf), (routines, wrap_t))?;
let u = |fb: &mut FunctionBuilder<'_>, v: u32| -> BResult<SValue> {
let c = fb.u32_const(v)?;
fb.module().const_value(c)
};
let (zero, one, two, four) = (u(fb, 0)?, u(fb, 1)?, u(fb, 2)?, u(fb, 4)?);
let yz = fb.select(fr.major_y, two, four)?;
let axis = fb.select(fr.major_x, zero, yz)?;
let sign = fb.select(fr.negative, one, zero)?;
let face = fb.binary(BinOp::IAdd, axis, sign)?;
Ok(FacePosition { face, s, t })
}
/// The frame of a cube direction's face (module docs): its components, which of them is the
/// major one and its sign and magnitude, the components that are the face's `s` and `t`
/// coordinates and whether Vulkan's face table negates each, and whether every component is
/// finite.
struct Frame {
cx: SValue,
cy: SValue,
cz: SValue,
major_x: SValue,
major_y: SValue,
major_z: SValue,
negative: SValue,
ma: SValue,
c_s: SValue,
c_t: SValue,
flip_s: SValue,
flip_t: SValue,
regular: SValue,
}
/// The [`Frame`] of direction `p` (three floats, `metal_ties`'s, which leaves no tie among the
/// largest magnitudes).
fn frame(fb: &mut FunctionBuilder<'_>, p: SValue) -> BResult<Frame> {
let most = f32_value(fb, f32::MAX)?;
let zero = f32_value(fb, 0.0)?;
let a = fb.glsl(GlslOp::FAbs, &[p])?;
let cx = fb.composite_extract(p, &[0])?;
let cy = fb.composite_extract(p, &[1])?;
let cz = fb.composite_extract(p, &[2])?;
let ax = fb.composite_extract(a, &[0])?;
let ay = fb.composite_extract(a, &[1])?;
let az = fb.composite_extract(a, &[2])?;
let finite_x = fb.binary(BinOp::FOrdLessThanEqual, ax, most)?;
let finite_y = fb.binary(BinOp::FOrdLessThanEqual, ay, most)?;
let finite_z = fb.binary(BinOp::FOrdLessThanEqual, az, most)?;
let finite_xy = fb.binary(BinOp::LogicalAnd, finite_x, finite_y)?;
let regular = fb.binary(BinOp::LogicalAnd, finite_xy, finite_z)?;
let x_y = fb.binary(BinOp::FOrdGreaterThanEqual, ax, ay)?;
let x_z = fb.binary(BinOp::FOrdGreaterThanEqual, ax, az)?;
let major_x = fb.binary(BinOp::LogicalAnd, x_y, x_z)?;
let y_z = fb.binary(BinOp::FOrdGreaterThanEqual, ay, az)?;
let not_x = fb.unary(UnOp::LogicalNot, major_x)?;
let major_y = fb.binary(BinOp::LogicalAnd, not_x, y_z)?;
let z_y = fb.binary(BinOp::FOrdGreaterThan, az, ay)?;
let major_z = fb.binary(BinOp::LogicalAnd, not_x, z_y)?;
let yz = fb.select(major_y, cy, cz)?;
let m = fb.select(major_x, cx, yz)?;
let ma = fb.glsl(GlslOp::FAbs, &[m])?;
let negative = fb.binary(BinOp::FOrdLessThan, m, zero)?;
let positive = fb.unary(UnOp::LogicalNot, negative)?;
// Vulkan's face table: `sc` is `-z` (`+x`), `z` (`-x`), `x` (`±y`, `+z`), or `-x` (`-z`);
// `tc` is `z` (`+y`), `-z` (`-y`), or `-y` (`±x`, `±z`). A flip is the component negated.
let c_s = fb.select(major_x, cz, cx)?;
let c_t = fb.select(major_y, cz, cy)?;
let flip_x = fb.binary(BinOp::LogicalAnd, major_x, positive)?;
let flip_z = fb.binary(BinOp::LogicalAnd, major_z, negative)?;
let flip_s = fb.binary(BinOp::LogicalOr, flip_x, flip_z)?;
let not_y = fb.unary(UnOp::LogicalNot, major_y)?;
let flip_t = fb.binary(BinOp::LogicalOr, not_y, negative)?;
Ok(Frame {
cx,
cy,
cz,
major_x,
major_y,
major_z,
negative,
ma,
c_s,
c_t,
flip_s,
flip_t,
regular,
})
}
/// `v`, negated where `flip`.
fn oriented(fb: &mut FunctionBuilder<'_>, flip: SValue, v: SValue) -> BResult<SValue> {
let negated = fb.unary(UnOp::FNegate, v)?;
fb.select(flip, negated, v)
}
/// Metal's position on a face axis of size `nf` (an `f32`) of the oriented minor component `sc`,
/// with `r` the reciprocal of the major magnitude: `X = RN(RN(1 + sc * r) / 2 * n)`, the sum
/// fused and each step rounded on its own (module docs). Where `wrap` holds (a repeating axis of a
/// size that is not a power of two), a face coordinate `F / 2` of 1 or more is first less 1,
/// exactly (it lies in `[1, 2)`).
fn texel_x(
fb: &mut FunctionBuilder<'_>,
sc: SValue,
(r, nf): (SValue, SValue),
(routines, wrap): (SnapRoutines, Option<SValue>),
) -> BResult<SValue> {
let one = f32_value(fb, 1.0)?;
let half = f32_value(fb, 0.5)?;
let sum = fma::emit(fb, routines.fma, &[sc, r, one])?;
let s = fb.binary_no_contraction(BinOp::FMul, sum, half)?;
let s = match wrap {
Some(w) => {
let past = fb.binary(BinOp::FOrdGreaterThanEqual, s, one)?;
let past = fb.binary(BinOp::LogicalAnd, w, past)?;
let less = fb.binary_no_contraction(BinOp::FSub, s, one)?;
fb.select(past, less, s)?
}
None => s,
};
fb.binary_no_contraction(BinOp::FMul, s, nf)
}
/// Define the fold of a linear cube filter's tap: `fn(face: u32, ti: i32, tj: i32, n: i32, pick:
/// u32, base: u32) -> uvec3`, the 2D-array coordinate `(i, j, base + g)` of the texel that tap
/// `(ti, tj)` of face `face` (Vulkan's face order) reads on a cube of faces `n` texels wide whose
/// first layer is `base`. In the doubled integer frame where a face spans `[-n, n]`, the tap's
/// centre is the direction `D` of Vulkan's face table at `sc = 2 ti + 1 - n` and `tc = 2 tj + 1 -
/// n` with the major component `±n`. A tap inside the face reads its own texel. A tap past one edge
/// has one component past `±n` and reads the adjacent face's texel along the edge: `D` clamped into
/// `±(n - 1)` with that component set to its sign times `n`, whose major axis is the new face. A
/// tap past both edges, at the cube's corner, has two such components, and reads the texel at the
/// corner of the face of axis `pick` (0, 1, 2: `x`, `y`, `z`) the corner touches: `D` clamped with
/// that axis's component set to its sign times `n`. The texel `(i, j)` of a face-frame direction is
/// `((sc + n - 1) / 2, (tc + n - 1) / 2)` of its `sc` and `tc` (the inverse of the face table).
/// Every result lies on the cube.
pub(super) fn define_fold(mb: &mut ModuleBuilder) -> BResult<FuncId> {
let u = mb.ty(SType::Int {
width: 32,
signed: false,
})?;
let i = mb.ty(SType::Int {
width: 32,
signed: true,
})?;
let uv3 = mb.ty(SType::Vector { elem: u, len: 3 })?;
let mut fb = mb.routine(uv3)?;
let face = fb.param(u)?;
let ti = fb.param(i)?;
let tj = fb.param(i)?;
let n = fb.param(i)?;
let pick = fb.param(u)?;
let base = fb.param(u)?;
let fb_ = &mut fb;
let uc = |fb: &mut FunctionBuilder<'_>, v: u32| -> BResult<SValue> {
let c = fb.u32_const(v)?;
fb.module().const_value(c)
};
let ic = |fb: &mut FunctionBuilder<'_>, v: i32| -> BResult<SValue> {
let c = fb.module().constant(Constant::Scalar {
ty: i,
bits: ConstBits(u64::from(v as u32)),
})?;
fb.module().const_value(c)
};
let (u0, u1, u2) = (uc(fb_, 0)?, uc(fb_, 1)?, uc(fb_, 2)?);
let (i0, i1, minus) = (ic(fb_, 0)?, ic(fb_, 1)?, ic(fb_, -1)?);
// The face's major axis and sign.
let m = fb_.binary(BinOp::ShiftRightLogical, face, u1)?;
let low = fb_.binary(BinOp::BitwiseAnd, face, u1)?;
let negative = fb_.binary(BinOp::INotEqual, low, u0)?;
let sign = fb_.select(negative, minus, i1)?;
let is_x = fb_.binary(BinOp::IEqual, m, u0)?;
let is_y = fb_.binary(BinOp::IEqual, m, u1)?;
let is_z = fb_.binary(BinOp::IEqual, m, u2)?;
// The tap's direction `D`: Vulkan's face table at `sc` and `tc`, the major component `±n`.
let doubled = |fb: &mut FunctionBuilder<'_>, t: SValue| -> BResult<SValue> {
let twice = fb.binary(BinOp::IAdd, t, t)?;
let odd = fb.binary(BinOp::IAdd, twice, i1)?;
fb.binary(BinOp::ISub, odd, n)
};
let sc = doubled(fb_, ti)?;
let tc = doubled(fb_, tj)?;
let major = fb_.binary(BinOp::IMul, sign, n)?;
let signed_sc = fb_.binary(BinOp::IMul, sign, sc)?;
let signed_tc = fb_.binary(BinOp::IMul, sign, tc)?;
let minus_tc = fb_.unary(UnOp::SNegate, tc)?;
let minus_signed_sc = fb_.unary(UnOp::SNegate, signed_sc)?;
// `x`: `±n`, `sc` (`±y`), `sign · sc` (`±z`); `y`: `±n`, else `-tc`; `z`: `±n`,
// `-sign · sc` (`±x`), `sign · tc` (`±y`).
let x = fb_.select(is_y, sc, signed_sc)?;
let x = fb_.select(is_x, major, x)?;
let y = fb_.select(is_y, major, minus_tc)?;
let z = fb_.select(is_x, minus_signed_sc, signed_tc)?;
let z = fb_.select(is_z, major, z)?;
// Per axis whether `D` lies past the face's edge there, `D` clamped into `±(n - 1)`, and the
// component's sign times `n`.
let last = fb_.binary(BinOp::ISub, n, i1)?;
let minus_last = fb_.unary(UnOp::SNegate, last)?;
let minus_n = fb_.unary(UnOp::SNegate, n)?;
let axis = |fb_: &mut FunctionBuilder<'_>, d: SValue| -> BResult<[SValue; 3]> {
let a = fb_.glsl(GlslOp::SAbs, &[d])?;
let over = fb_.binary(BinOp::SGreaterThan, a, n)?;
let inner = fb_.glsl(GlslOp::SClamp, &[d, minus_last, last])?;
let below = fb_.binary(BinOp::SLessThan, d, i0)?;
Ok([over, inner, fb_.select(below, minus_n, n)?])
};
let [over_x, inner_x, outer_x] = axis(fb_, x)?;
let [over_y, inner_y, outer_y] = axis(fb_, y)?;
let [over_z, inner_z, outer_z] = axis(fb_, z)?;
// The axis set to `±n`: the one past an edge, the major one where none is, `pick` where two
// are (the cube's corner).
let a = fb_.select(over_z, u2, m)?;
let a = fb_.select(over_y, u1, a)?;
let a = fb_.select(over_x, u0, a)?;
let xy = fb_.binary(BinOp::LogicalAnd, over_x, over_y)?;
let xz = fb_.binary(BinOp::LogicalAnd, over_x, over_z)?;
let yz = fb_.binary(BinOp::LogicalAnd, over_y, over_z)?;
let corner = fb_.binary(BinOp::LogicalOr, xy, xz)?;
let corner = fb_.binary(BinOp::LogicalOr, corner, yz)?;
let a = fb_.select(corner, pick, a)?;
let on_x = fb_.binary(BinOp::IEqual, a, u0)?;
let on_y = fb_.binary(BinOp::IEqual, a, u1)?;
let on_z = fb_.binary(BinOp::IEqual, a, u2)?;
let cx = fb_.select(on_x, outer_x, inner_x)?;
let cy = fb_.select(on_y, outer_y, inner_y)?;
let cz = fb_.select(on_z, outer_z, inner_z)?;
// The texel's face, `2 a` plus 1 where that component is negative, and its `sc` and `tc`:
// `-sign · z` (`±x`), `x` (`±y`), `sign · x` (`±z`); `sign · z` (`±y`), else `-y`.
let yz_ = fb_.select(on_y, y, z)?;
let da = fb_.select(on_x, x, yz_)?;
let below = fb_.binary(BinOp::SLessThan, da, i0)?;
let twice = fb_.binary(BinOp::ShiftLeftLogical, a, u1)?;
let low = fb_.select(below, u1, u0)?;
let g = fb_.binary(BinOp::IAdd, twice, low)?;
let sign = fb_.select(below, minus, i1)?;
let signed_x = fb_.binary(BinOp::IMul, sign, cx)?;
let signed_z = fb_.binary(BinOp::IMul, sign, cz)?;
let minus_signed_z = fb_.unary(UnOp::SNegate, signed_z)?;
let minus_y = fb_.unary(UnOp::SNegate, cy)?;
let s = fb_.select(on_y, cx, signed_x)?;
let s = fb_.select(on_x, minus_signed_z, s)?;
let t = fb_.select(on_y, signed_z, minus_y)?;
let index = |fb: &mut FunctionBuilder<'_>, c: SValue| -> BResult<SValue> {
let shifted = fb.binary(BinOp::IAdd, c, last)?;
let half = fb.binary(BinOp::ShiftRightArithmetic, shifted, i1)?;
fb.convert(ConvOp::Bitcast, half, u)
};
let ii = index(fb_, s)?;
let jj = index(fb_, t)?;
let layer = fb_.binary(BinOp::IAdd, base, g)?;
let at = fb_.composite_construct(uv3, &[ii, jj, layer])?;
fb.ret(Some(at))?;
fb.finish()
}
/// The `f32` constant `x`.
fn f32_value(fb: &mut FunctionBuilder<'_>, x: f32) -> BResult<SValue> {
let f32_ = fb.module().ty(SType::Float { width: 32 })?;
let c = fb.module().constant(Constant::Scalar {
ty: f32_,
bits: ConstBits(u64::from(x.to_bits())),
})?;
fb.module().const_value(c)
}
#[cfg(test)]
mod tests;
@@ -1,7 +1,7 @@
//! `metal_ties` on the interpreter against Metal's rule. Each kernel invocation reads a direction's
//! bits and writes the bits of the direction the device is handed. `snap` checks `snapped`, and
//! `fold` a linear cube filter's taps across the faces' edges. `anisotropic` checks
//! `emit::cube_footprint`'s gradients through a constexpr anisotropic sampler.
//! bits and writes the bits of the direction the device is handed. `anisotropic` checks
//! `emit::cube_footprint`'s gradients through a constexpr anisotropic sampler, and `routines` the
//! sampling routines' function controls.
use super::metal_ties;
use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage};
@@ -599,6 +599,4 @@ fn the_estimate_bounds_the_emitted_words() {
}
mod anisotropic;
mod fold;
mod routines;
mod snap;
@@ -1,151 +0,0 @@
//! `define_fold` on the interpreter against the cube's geometry. Each invocation reads a tap (its
//! face, its indices on the face's axes, the face size, and the corner face it picks) and writes
//! the 2D-array coordinate the fold names; the reference finds the texel whose centre on the cube
//! is nearest the tap's, and at the cube's corner, where the tap lies past both edges of its face,
//! the corner texel of each of the three faces there.
use super::super::define_fold;
use super::{kernel_on, run_records};
use crate::spirv::builder::ModuleBuilder;
use crate::spirv::ir::{ConvOp, Type};
/// The direction of tap `(i, j)` of face `face` (Vulkan's order) in the doubled frame where a
/// face spans `[-n, n]`: Vulkan's face table at `sc = 2 i + 1 - n` and `tc = 2 j + 1 - n`, the
/// major component `±n`.
fn direction(face: usize, i: i64, j: i64, n: i64) -> [i64; 3] {
let (s, t) = (2 * i + 1 - n, 2 * j + 1 - n);
match face {
0 => [n, -t, -s],
1 => [-n, -t, s],
2 => [s, n, t],
3 => [s, -n, -t],
4 => [s, -t, n],
_ => [-s, -t, -n],
}
}
/// Every texel of a cube of `n`-texel faces: its face, its indices, and its centre.
fn centres(n: i64) -> Vec<(usize, i64, i64, [i64; 3])> {
let mut out = Vec::new();
for face in 0..6 {
for j in 0..n {
for i in 0..n {
out.push((face, i, j, direction(face, i, j, n)));
}
}
}
out
}
/// The texel tap `(i, j)` of face `face` reads (picking face axis `pick` at the cube's corner):
/// within the face its own; past one edge the texel whose centre is nearest the tap's (one
/// texel, across the edge); past both, the texel at the cube's corner of the face of axis `pick`,
/// whose centre lies one step in from the corner on the two other axes.
fn reference(face: usize, (i, j): (i64, i64), n: i64, pick: usize) -> (usize, i64, i64) {
let d = direction(face, i, j, n);
let all = centres(n);
let past_i = !(0..n).contains(&i);
let past_j = !(0..n).contains(&j);
if past_i && past_j {
let mut c = d.map(|v| v.signum() * (n - 1));
c[pick] = d[pick].signum() * n;
let found: Vec<_> = all.iter().filter(|t| t.3 == c).collect();
assert_eq!(found.len(), 1, "the corner texel of {c:?}");
return (found[0].0, found[0].1, found[0].2);
}
let distance = |c: &[i64; 3]| -> i64 { (0..3).map(|k| (c[k] - d[k]).pow(2)).sum() };
let least = all.iter().map(|t| distance(&t.3)).min().expect("texels");
let found: Vec<_> = all.iter().filter(|t| distance(&t.3) == least).collect();
assert_eq!(found.len(), 1, "the nearest texel to {d:?}");
(found[0].0, found[0].1, found[0].2)
}
/// The fold names the reference's texel, as the 2D-array coordinate `(i, j, base + face)`, for
/// every tap from one texel before each face's edges to one past, every face, faces of 1, 2, 3,
/// 4, 5, and 8 texels, and every corner pick; and every coordinate lies on the cube.
#[test]
fn the_fold_reads_the_texel_across_the_edge() {
let mut b = ModuleBuilder::new();
let fold = define_fold(&mut b).expect("fold");
// A record: the face, `i`, and `j` as the direction's bits, and the size, the pick, and the
// first layer packed after them.
let m = kernel_on(b, 4, &|f, p, extra| {
let u = f.module().ty(Type::Int {
width: 32,
signed: false,
})?;
let i = f.module().ty(Type::Int {
width: 32,
signed: true,
})?;
let fl = f.module().ty(Type::Float { width: 32 })?;
let vec3 = f.module().ty(Type::Vector { elem: fl, len: 3 })?;
let face = f.composite_extract(p, &[0])?;
let face = f.convert(ConvOp::Bitcast, face, u)?;
let ti = f.composite_extract(p, &[1])?;
let ti = f.convert(ConvOp::Bitcast, ti, i)?;
let tj = f.composite_extract(p, &[2])?;
let tj = f.convert(ConvOp::Bitcast, tj, i)?;
let field = |f: &mut crate::spirv::builder::FunctionBuilder<'_>, shift: u32| {
let s = f.u32_const(shift)?;
let s = f.module().const_value(s)?;
let m = f.u32_const(0xff)?;
let m = f.module().const_value(m)?;
let v = f.binary(crate::spirv::ir::BinOp::ShiftRightLogical, extra, s)?;
f.binary(crate::spirv::ir::BinOp::BitwiseAnd, v, m)
};
let n = field(f, 0)?;
let n = f.convert(ConvOp::Bitcast, n, i)?;
let pick = field(f, 8)?;
let base = field(f, 16)?;
let at = f.call(fold, &[face, ti, tj, n, pick, base])?.expect("fold");
f.convert(ConvOp::Bitcast, at, vec3)
})
.expect("kernel");
let mut records = Vec::new();
let mut want = Vec::new();
for n in [1i64, 2, 3, 4, 5, 8] {
for face in 0..6usize {
for i in -1..=n {
for j in -1..=n {
for pick in 0..3usize {
let base = 6 * (n as u32 % 3);
records.extend([
face as u32,
i as u32,
j as u32,
n as u32 | (pick as u32) << 8 | base << 16,
]);
let (g, ri, rj) = reference(face, (i, j), n, pick);
want.push([ri as u32, rj as u32, base + g as u32]);
}
}
}
}
}
let got = run_records(&m, &records, want.len());
let mut corners = 0;
for (k, (g, w)) in got.iter().zip(&want).enumerate() {
let g = g.map(f32::to_bits);
let r = &records[4 * k..4 * k + 4];
assert_eq!(
g,
*w,
"face {} tap ({}, {}) size {} pick {}",
r[0],
r[1] as i32,
r[2] as i32,
r[3] & 0xff,
(r[3] >> 8) & 0xff
);
let n = r[3] & 0xff;
assert!(g[0] < n && g[1] < n, "{g:?} off a face of {n}");
corners +=
usize::from((r[1] as i32 == -1 || r[1] == n) && (r[2] as i32 == -1 || r[2] == n));
}
assert_eq!(
corners,
6 * 3 * 4 * 6,
"every face's four corners at each size and pick"
);
}
@@ -3,12 +3,10 @@
//! states `DontInline`; for any other profile none states a control, and the entry states none
//! anywhere.
use super::super::define_fold;
use super::kernel_on;
use crate::device::profile::DriverWorkaround;
use crate::device::DevicePolicy;
use crate::lower::sampler::bicubic::routines;
use crate::lower::texture::float_texel;
use crate::lower::texture::half::{self, HalfFamilies};
use crate::pipeline::testing::profile;
use crate::spirv::builder::ModuleBuilder;
@@ -29,22 +27,18 @@ fn controls(words: &[u32]) -> Vec<u32> {
out
}
/// The texel conversions, the emulated linear filters' and the bicubic filter's sums, and the
/// cube's face fold, beside a kernel entry: on moltenvk-m3 each routine states `DontInline`
/// (0x2) and the entry `None`; on amd-rdna3-radv the six texel routines state `DontInline` (the
/// linear span's, quad's and block's two sums each) and every other function `None`.
/// The texel conversion and the linear and bicubic filters' sums beside a kernel entry: on
/// moltenvk-m3 each routine states `DontInline` (0x2) and the entry `None`; on amd-rdna3-radv the
/// four texel routines state `DontInline` (the linear quad's and block's two sums each) and every
/// other function `None`.
#[test]
fn the_sampling_routines_are_declared_dont_inline_where_every_call_is_inlined() {
let mut b = ModuleBuilder::new();
half::define(&mut b, HalfFamilies::Every).expect("half texel");
float_texel::define(&mut b).expect("float texel");
define_fold(&mut b).expect("fold");
routines::define_plane(&mut b).expect("plane");
routines::define_line(&mut b).expect("line");
routines::define_span(&mut b).expect("span");
routines::define_quad(&mut b).expect("quad");
routines::define_block(&mut b).expect("block");
routines::define_cube(&mut b).expect("cube");
let m = kernel_on(b, 3, &|_, p, _| Ok(p)).expect("kernel");
for (stem, inlines_every_call) in [("moltenvk-m3", true), ("amd-rdna3-radv", false)] {
let p = profile(stem, DevicePolicy::default()).expect("profile");
@@ -58,11 +52,11 @@ fn the_sampling_routines_are_declared_dont_inline_where_every_call_is_inlined()
let words = serialize_for(m.clone(), &p).expect("serialized").words;
let mut got = controls(&words);
got.sort_unstable();
// 19 routines (the plane's six, two each for the line, span, quad, block and cube, the
// fold, and the two texel conversions; the cube's fold is a second fold) and the entry.
assert!(got.len() >= 20, "{stem}: {} functions", got.len());
// 13 routines (the plane's six, two each for the line, quad and block, and the texel
// conversion) and the entry.
assert!(got.len() >= 14, "{stem}: {} functions", got.len());
// The texel routines state it on every profile.
let kept = if inlines_every_call { got.len() - 1 } else { 6 };
let kept = if inlines_every_call { got.len() - 1 } else { 4 };
let mut want = vec![0x2; kept];
want.splice(0..0, vec![0; got.len() - kept]);
assert_eq!(
@@ -1,341 +0,0 @@
//! `snapped` on the interpreter against Metal's position (the cube rounding probes, Apple M3 Max
//! and M4), and its wrap of a repeating face axis (the cube probes, Apple M4). Each kernel
//! invocation reads a direction's bits and a face size, hands the direction through `metal_ties`
//! and then `snapped`, and writes the handed direction's bits; a device reading it in exact
//! arithmetic, or rounding each operation to `f32`, must read the texel Metal's position names with
//! the device's reciprocal (here the interpreter's correctly rounded one).
use super::super::{snapped, FaceRoutines, FaceWrap, SnapRoutines, SCALAR, SNAP_WORDS};
use super::{
kernel_on, lanes, metal_axis, metal_ties, read_as_zero, run_records, selecting, SIZES,
};
use crate::lower::arith::fma::{self, Fma, Route};
use crate::spirv::builder::ModuleBuilder;
use crate::spirv::error::BResult;
use crate::spirv::ir::TypedModule;
/// The device's reciprocal of a major magnitude `top`, as the interpreter divides: `RN(1 / top)`.
fn device_recip(top: f32) -> f32 {
1.0 / top
}
/// A kernel whose invocation reads a direction and a face size and writes the direction that
/// `metal_ties` and then (`snap`) `snapped` hand the device, by `fma`'s route, wrapping the face
/// axes `wrap` names.
fn kernel(fma: Fma, snap: bool, wrap: FaceWrap) -> BResult<TypedModule> {
let b = ModuleBuilder::new();
let r = SnapRoutines { fma };
kernel_on(b, 4, &|f, p, n| {
let p = metal_ties(f, p)?;
match snap {
true => snapped(f, p, n, (r, wrap)),
false => Ok(p),
}
})
}
/// The `float` fused multiply-add by `route`.
fn by(route: Route) -> Fma {
let routes = fma::Routes {
float: route,
half: Route::Native,
};
Fma::by(routes, SCALAR).expect("float")
}
/// The handed direction of each lane, a direction and a face size, by `fma`'s route, wrapping
/// the face axes `wrap` names.
fn run(fma: Fma, lanes: &[([f32; 3], u32)], wrap: FaceWrap) -> Vec<[f32; 3]> {
let records: Vec<u32> = lanes
.iter()
.flat_map(|(d, n)| [d[0].to_bits(), d[1].to_bits(), d[2].to_bits(), *n])
.collect();
run_records(
&kernel(fma, true, wrap).expect("kernel"),
&records,
lanes.len(),
)
}
/// Vulkan's face coordinates `(s_c, t_c)` of direction `d` on the face of major axis `major`
/// (`positive`: its sign), by its "Cube Map Face Selection" table.
fn face_minors(d: [f32; 3], major: usize, positive: bool) -> [f32; 2] {
match (major, positive) {
(0, true) => [-d[2], -d[1]],
(0, false) => [d[2], -d[1]],
(1, true) => [d[0], d[2]],
(1, false) => [d[0], -d[2]],
(2, true) => [d[0], -d[1]],
_ => [-d[0], -d[1]],
}
}
/// A face (its major axis and sign) and the texel on each of its axes.
type Texel = (usize, bool, [u32; 2]);
/// The texel `floor(x)`, clamped into a face of size `n`.
fn clamped(x: f64, n: u32) -> u32 {
x.floor().clamp(0.0, f64::from(n - 1)) as u32
}
/// Metal's position `X` on a face axis of size `n` of face coordinate `c` beside a major
/// magnitude whose reciprocal is `r`: `RN(RN(1 + c * r) / 2 * n)`, the sum fused and rounded once,
/// ties to even; on a repeating axis (`wraps`) of a size that is not a power of two, a face
/// coordinate `RN(1 + c * r) / 2` of 1 or more less 1 first.
fn metal_x(c: f32, r: f32, n: u32, wraps: bool) -> f32 {
let u = c.mul_add(r, 1.0) * 0.5;
let u = match wraps && !n.is_power_of_two() && u >= 1.0 {
true => u - 1.0,
false => u,
};
u * n as f32
}
/// Metal's nearest texel along a finite direction `d` on faces of size `n`, its reciprocal of the
/// major magnitude the device's ([`device_recip`]): the face `metal_reading` reads, and on each
/// face axis `floor(X)` of [`metal_x`] (wrapped on the axes `wrap` names), at most `n - 1`, with
/// each component Metal reads as zero `0`; a direction left zero at face `+x`'s texel `(0, 0)`.
fn metal_texel(d: [f32; 3], n: u32, wrap: FaceWrap) -> Texel {
let m = selecting(d);
let major = metal_axis(m);
let top = m[major];
if top == 0.0 {
return (0, true, [0, 0]);
}
let read = std::array::from_fn(|k| match k != major && read_as_zero(d[k], top) {
true => 0.0,
false => d[k],
});
let positive = d[major] > 0.0;
let r = device_recip(top);
let [s, t] = face_minors(read, major, positive);
let texels = [(s, wrap.s), (t, wrap.t)].map(|(c, w)| clamped(metal_x(c, r, n, w).into(), n));
(major, positive, texels)
}
/// What a device reads along the handed direction `q`, whose major magnitude is `1` and alone the
/// largest: its face, and on each face axis the texel of `(s_c / |m_a| + 1) / 2 * n`, in exact
/// arithmetic (`exact`) or with each operation rounded to `f32`.
fn device_texel(q: [f32; 3], n: u32, exact: bool) -> Texel {
let a = q.map(f32::abs);
let major = metal_axis(a);
for k in (0..3).filter(|&k| k != major) {
assert!(a[k] < a[major], "{q:?}: axis {k} ties {major}");
}
assert_eq!(a[major], 1.0, "{q:?}: the major magnitude");
let positive = q[major] > 0.0;
let texels = face_minors(q, major, positive).map(|c| {
let x = match exact {
true => (f64::from(c) + 1.0) / 2.0 * f64::from(n),
false => f64::from((c / a[major] + 1.0) / 2.0 * n as f32),
};
clamped(x, n)
});
(major, positive, texels)
}
/// A deterministic stream of `u32`s (a 64-bit linear congruential generator's high half).
fn stream(mut seed: u64) -> impl FnMut() -> u32 {
move || {
seed = seed
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
(seed >> 32) as u32
}
}
/// Directions whose face coordinate lies at a texel step of Metal's position or a few ulps either
/// side, on several majors and sizes: `s_c = (2k / n - 1) * |m_a|` per step `k`, moved by up to
/// three ulps, on face `+x` (`s_c = -z`) with `t_c` the same on `-y`.
fn steps() -> Vec<([f32; 3], u32)> {
let mut next = stream(1017);
let mut majors = vec![
1.0f32,
f32::from_bits(0x3f80_0001),
3.0,
0.885,
1.0e-30,
1.0e30,
f32::from_bits(0x7e00_0000),
];
majors.extend((0..24).map(|_| f32::from_bits(0x3f80_0000 | (next() >> 9))));
let mut out = Vec::new();
for n in [5u32, 7, 8, 13, 255, 1024, 16_384] {
let ks: Vec<u32> = (1..n).step_by((n as usize / 6).max(1)).collect();
for &ma in &majors {
for &k in &ks {
let c = (2.0 * f64::from(k) / f64::from(n) - 1.0) * f64::from(ma);
let c = c as f32;
for d in -3i32..=3 {
let moved = f32::from_bits(c.to_bits().wrapping_add_signed(d));
if moved.abs() < ma {
out.push(([ma, moved, -moved], n));
}
}
}
}
}
out
}
/// The lane: along `(1, 1 + 2^-23, 0.25)` Metal reads texel `(7, 5)` of face `+y` of an 8x8 cube,
/// where ANV and NVIDIA read `(7, 4)`.
const TODO_1_14: ([f32; 3], u32) = ([1.0, f32::from_bits(0x3f80_0001), 0.25], 8);
/// Each finite lane `(d, n)` and the direction `q` handed for it: one major magnitude `1`, alone
/// the largest, and Metal's face and texel read along `q` both in exact arithmetic and in `f32`.
fn check(lanes: &[([f32; 3], u32)], got: &[[f32; 3]], wrap: FaceWrap, what: &str) {
for ((d, n), q) in lanes.iter().zip(got) {
if d.iter().any(|x| !x.is_finite()) {
assert_eq!(q.map(f32::to_bits), d.map(f32::to_bits), "{what}: {d:?}");
continue;
}
let want = metal_texel(*d, *n, wrap);
for exact in [true, false] {
assert_eq!(
device_texel(*q, *n, exact),
want,
"{what}: direction {d:?} on {n} handed {q:?} (exact: {exact})"
);
}
}
}
/// On every lane of `metal_ties`'s tests, at every size, through `OpFmaKHR`, and on the texel-step
/// lanes through the device's `Fma` too, the device reads the face and texel Metal's position
/// names with the device's reciprocal along the handed direction; a direction with an infinite or
/// NaN component passes unchanged.
#[test]
fn the_device_reads_metals_nearest_texel() {
let mut all: Vec<([f32; 3], u32)> = lanes()
.into_iter()
.enumerate()
.map(|(i, d)| (d, SIZES[i % SIZES.len()]))
.collect();
let steps = steps();
all.extend(steps.iter().copied());
all.push(TODO_1_14);
let none = FaceWrap::default();
assert_eq!(metal_texel(TODO_1_14.0, 8, none), (1, true, [7, 5]));
check(&all, &run(by(Route::Khr), &all, none), none, "Khr");
let mut few: Vec<([f32; 3], u32)> = steps.iter().step_by(5).copied().collect();
few.push(TODO_1_14);
check(&few, &run(by(Route::Native), &few, none), none, "Native");
}
/// The step lanes reach the hazards Metal's position decides: on many of them the texel differs
/// from an unfused sum's (`RN(RN(c * r) + 1)`), from a quotient's (`RN(c / |m_a|)`), and from one
/// ulp of the reciprocal either way (Apple's texture unit's residue,
/// `PrecisionNote::CubeFaceReciprocal`).
#[test]
fn the_step_lanes_reach_the_rounding_hazards() {
let steps = steps();
let (mut unfused, mut quotient, mut residue) = (0, 0, 0);
for ([ma, c, _], n) in &steps {
let r = device_recip(*ma);
let texel = |x: f32| clamped(x.into(), *n);
let want = texel(metal_x(*c, r, *n, false));
unfused += usize::from(texel((c * r + 1.0) * 0.5 * *n as f32) != want);
quotient += usize::from(texel((c / ma + 1.0) * 0.5 * *n as f32) != want);
let off = |d: i32| {
texel(metal_x(
*c,
f32::from_bits(r.to_bits().wrapping_add_signed(d)),
*n,
false,
))
};
residue += usize::from(off(1) != want || off(-1) != want);
}
assert!(unfused > 100, "{unfused} of {} lanes", steps.len());
assert!(quotient > 100, "{quotient} of {} lanes", steps.len());
assert!(residue > 1000, "{residue} of {} lanes", steps.len());
}
/// `SNAP_WORDS`, the reciprocal's division, two fused multiply-adds', and the wrap's bound the
/// words `snapped` adds beside its routines, in a module valid on every committed profile, without
/// a wrap and wrapping either face axis or both.
#[test]
fn the_estimate_bounds_the_emitted_words() {
let profiles = crate::spirv::testing::committed_profiles().expect("profiles");
let wraps = [(false, false), (true, false), (false, true), (true, true)]
.map(|(s, t)| FaceWrap { s, t });
for (stem, profile) in &profiles {
let fma = Fma::on(profile, SCALAR).expect("float");
let without = crate::spirv::testing::assert_valid(
kernel(fma, false, FaceWrap::default()).expect("kernel"),
profile,
);
for wrap in wraps {
let with = crate::spirv::testing::assert_valid(
kernel(fma, true, wrap).expect("kernel"),
profile,
);
let added = with.len() - without.len();
let estimate = SNAP_WORDS + FaceRoutines { fma }.use_words() + wrap.words();
assert!(
added <= estimate as usize,
"{stem} {wrap:?}: snapped adds {added} words, estimated {estimate}"
);
}
}
}
/// Directions whose face coordinate on either axis of every face is exactly 1 or -1, or an ulp or
/// two inside, beside a major magnitude of 1, 3, or 0.75 (a tie among them), on faces of sizes
/// that are and are not powers of two.
fn edges() -> Vec<([f32; 3], u32)> {
let below = |k: u32| f32::from_bits(1.0f32.to_bits() - k);
let minors = [-1.0, -below(1), -below(2), 0.5, below(2), below(1), 1.0];
let mut out = Vec::new();
for n in [3u32, 5, 6, 7, 4, 8, 16] {
for m in [1.0f32, 3.0, 0.75] {
for face in 0..6 {
for s in minors {
for t in minors {
let d = match face {
0 => [1.0, -t, -s],
1 => [-1.0, -t, s],
2 => [s, 1.0, t],
3 => [s, -1.0, -t],
4 => [s, -t, 1.0],
_ => [-s, -t, -1.0],
};
out.push((d.map(|c| c * m), n));
}
}
}
}
}
out
}
/// Under `repeat` on a face axis whose size is not a power of two, a face coordinate of exactly 1
/// (a tie with the major magnitude included) reads texel 0 of that axis, the face's other edge, on
/// each axis the wrap names and on no other; at a size that is a power of two it reads the last
/// texel, as a clamping axis does. Every lane of [`edges`] is Metal's texel through `OpFmaKHR`, and
/// the wrap moves the texel on some lanes at each size that is not a power of two and on none at a
/// power of two.
#[test]
fn a_repeating_face_axis_wraps_a_coordinate_of_one() {
let lanes = edges();
let none = FaceWrap::default();
for wrap in [(true, false), (false, true), (true, true)].map(|(s, t)| FaceWrap { s, t }) {
check(
&lanes,
&run(by(Route::Khr), &lanes, wrap),
wrap,
&format!("{wrap:?}"),
);
for n in [3u32, 5, 6, 7, 4, 8, 16] {
let moved = lanes
.iter()
.filter(|(d, m)| *m == n && metal_texel(*d, n, wrap) != metal_texel(*d, n, none))
.count();
match n.is_power_of_two() {
true => assert_eq!(moved, 0, "{wrap:?} n={n}"),
false => assert!(moved > 0, "{wrap:?} n={n}: no lane wraps"),
}
}
}
}
File diff suppressed because it is too large. Load diff
+12 -389
View File
@@ -1,6 +1,6 @@
//! Metal's level of a sample with an explicit level (`level(x)`), or a kernel's bias (`bias(x)`,
//! the explicit level `x` outside a fragment function), and the level that makes a device's sample
//! read it.
//! the explicit level `x` outside a fragment function), computed in the function where the module
//! reads the texels itself (an extended-range texture's sample, `extended`).
//!
//! **The rule** (Apple M4, macOS 27.0.1; for comparisons of a mipmapped `depth32Float` texture, for
//! colour samples). Metal rounds the level `x` to `half`, to nearest even (a NaN reads 0), clamps
@@ -32,188 +32,44 @@
//! filters under nearest, linear and no mip filters and eleven clamps, a runtime or argument
//! buffer's sampler's as `f32`s); a linear mip filter blends the two levels' comparisons as an
//! `r8Unorm` texture's codes 0 and 255, rounded once onto sixteenths of a code, ties up
//! (`Depth32Float` and `Depth16Unorm`, one level, both, or neither passing). The shader makes those
//! comparisons itself (`compared`); a filtered comparison left to the device keeps the device's
//! level.
//! (`Depth32Float` and `Depth16Unorm`, one level, both, or neither passing). A comparison the
//! device makes takes the device's level.
//!
//! **The device** chooses its level from `λ` (Vulkan's explicit `Lod`), clamped into the
//! sampler's `[minLod, maxLod]` (the same level clamp), at its own precision: a nearest mip filter
//! reads `ceil(λ + 1/2) - 1` (rounding `L + 1/2` either way is the implementation's), a linear one
//! blends `floor(λ)` and the next level by `λ`'s fraction to `mipmapPrecisionBits` (at least 6 on
//! the measured venues), and `λ <= 0` magnifies. So the translation hands it `λ` on Metal's grid
//! ([`LevelSnap::of`]): `L + q` for a linear mip filter (exact on a 1/64 grid) and for a sampler
//! without one (whose `maxLod` keeps level 0, and whose sign alone chooses the filter), and `L`,
//! `L + 1/4`, or `L + 1` for a nearest mip filter (no half-way point to round). It clamps `x` as
//! Metal does, and caps it at 64 (past every texture's levels; Metal's largest have 15) so that an
//! infinity's fraction is 0; the device's clamp into the texture's levels is then Metal's. The
//! device's `minLod` raises a `λ` below it: where the sampler's `lod_min_clamp` is on the 1/64 grid
//! that never happens under a linear mip filter, and under a nearest one it never moves `λ` onto or
//! past a half-way point unless the clamp's fraction lies in `[1/2, 33/64)`; a sampler clamping
//! otherwise keeps the device's level ([`LevelSnap::plan`]).
//!
//! **Reached:** a sample with a level or a kernel's bias (no `min_lod_clamp`) of a texture of
//! floating-point texels through a constexpr sampler with normalized coordinates, no anisotropy,
//! no level bias of its own, and a level clamp as above, on a device without
//! `VkProperty::MetalSampler`; on one with it, the device's sample is Metal's own, so the module
//! leaves the level to it and requires the property. A level known when the function compiles takes
//! no snap where it is on Metal's grid already, as `level(0)` is.
//! the measured venues), and `λ <= 0` magnifies. A sample the device makes takes the device's
//! level (`PrecisionNote::DeviceSampling` on a device whose sampler is not Metal's).
//!
//! **A runtime or argument buffer's sampler** holds its clamp as `f32`s, not `half`s (Apple M4 on
//! macOS 27.0.1: all 37,080 lanes of `level(x)` and a kernel's `bias(x)` through eighteen clamps,
//! nearest and linear filters and mip filters). The function does not know the clamp; the
//! `VkSampler` holds it on Metal's grid instead where the sampler takes one filter both ways and no
//! anisotropy (`metal::sampler::clamps_on_grid`): the level a nearest mip filter reads at each
//! bound, or the bound truncated onto sixty-fourths under a linear one. Metal's rule is monotone in
//! the level, so its level clamped by the bounds is the level clamped by those values; the function
//! hands the device the unclamped level on the grid (`by_word`: `L` or `L + 1` under a nearest mip
//! filter, `L + q` under a linear one), and the device's clamp moves it exactly as Metal's moves
//! the level. The sampler's word says whether it takes its clamp so ([`SamplerWord::LEVEL_RULE`]);
//! elsewhere the device keeps the level it is handed. With one filter both ways the level's sign
//! chooses nothing, so a level handed to the device needs no fraction to stay minified.
//!
//! **A level from derivatives or gradients** (a fragment function's implicit level, explicit
//! gradients, an LOD query) is the device's level arithmetic: Vulkan's level of detail, whose
//! scale factor may be approximated, and the rounding above. Metal's level of detail there is not
//! measured, so nothing hands the device Metal's. Nor does anything hand it Metal's level where
//! the rule is not reached: an integer texture's level, and a constexpr sampler's that
//! [`LevelSnap::plan`] leaves (a level bias of its own, a clamp it does not take). Where the level
//! chooses what a sample reads and no other note records the sample, the module records
//! `PrecisionNote::DeviceSampleLevel` ([`device_when`]).
//! bound, or the bound truncated onto sixty-fourths under a linear one. The function reads a
//! nearest mip filter's level within the levels the word's clamp leaves ([`word_level`]).
use crate::air::abi::{Coordinates, MipFilter, SamplerState};
use crate::air::ir::{Const, Value};
use crate::error::Error;
use crate::float16::{f16_bits_to_f32, f32_to_f16_bits};
use crate::lower::arith::legal::{FloatFmt, Form, Held};
use crate::lower::arith::texel_round::{self, HalfRounding};
use crate::lower::select::{any_of, NoteClause, NoteOn, NoteTest, SelectCx};
use crate::metal::sampler::SamplerWord;
use crate::metal::SamplerMipFilter;
use crate::pipeline::sym::SamplerRef;
use crate::spirv::builder::FunctionBuilder;
use crate::spirv::error::BResult;
use crate::spirv::ids::Value as SValue;
use crate::spirv::ir::{BinOp, ConstBits, Constant, GlslOp, Type as SType, UnOp};
use super::{BiasReach, Lod, SampleOp};
#[cfg(test)]
mod tests;
/// The estimated words of `LevelSnap::emit`: the rounding to `half` (about 40 instructions of 4 to
/// 6 words), the NaN's select, the clamps, the floor, the fraction's grid, the mip filter's level,
/// and their constants.
/// The estimated words of a level on Metal's grid ([`clamped_on_grid`] and the mip filter's
/// level): the rounding to `half` (about 40 instructions of 4 to 6 words), the NaN's select, the
/// clamps, the floor, the fraction's grid, the mip filter's level, and their constants.
pub const LEVEL_WORDS: u32 = 400;
/// The cap on a level before its floor: past every texture's levels, and an `f32` whose fraction
/// is 0.
const CAP: f32 = 64.0;
/// How a sample's level is handed to the device (module docs).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LevelRule {
/// A constexpr sampler's, by its state.
Stated(LevelSnap),
/// A runtime or argument buffer's sampler's, by its word (`by_word`).
Word,
}
/// How a sample's level is handed to the device (module docs): the sampler's mip filter and its
/// level clamp, as `f32` bits.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct LevelSnap {
pub mip: MipFilter,
/// The sampler's `lod_min_clamp`, a `half`'s value.
pub min: u32,
/// The sampler's `lod_max_clamp`, a `half`'s value.
pub max: u32,
}
impl LevelSnap {
/// The snap of a sample with a level through constexpr sampler `s`, or `None` where the rule
/// is not measured or the device's clamp would move the level the snap hands it (module
/// docs): a pixel sampler (which has no mip filter), an anisotropic one, one with a level bias
/// of its own, one whose level clamp is empty, and one whose `lod_min_clamp` the device's
/// `minLod` would raise a snapped level to (off the 1/64 grid under a linear mip filter, of a
/// fraction in `[1/2, 33/64)` under a nearest one).
pub fn plan(s: &SamplerState) -> Option<LevelSnap> {
let (min, max) = (s.lod_min_clamp.to_f32(), s.lod_max_clamp.to_f32());
if s.coordinates != Coordinates::Normalized
|| s.max_anisotropy > 1
|| s.lod_bias.to_f32() != 0.0
|| min.is_nan()
|| max.is_nan()
|| min > max
{
return None;
}
let fraction = min - min.floor();
let raised = min > 0.0
&& match s.mip_filter {
MipFilter::Linear => (fraction * 64.0).fract() != 0.0,
MipFilter::Nearest => (0.5..33.0 / 64.0).contains(&fraction),
MipFilter::None => false,
};
if raised {
return None;
}
Some(LevelSnap {
mip: s.mip_filter,
min: min.to_bits(),
max: max.to_bits(),
})
}
/// The level `λ` handed to the device for Metal's level `x` (module docs).
pub fn of(&self, x: f32) -> f32 {
let (min, max) = (f32::from_bits(self.min), f32::from_bits(self.max));
let x = if x.is_nan() {
0.0
} else {
f16_bits_to_f32(f32_to_f16_bits(x))
};
let x = x.max(min).min(max).clamp(0.0, CAP);
let l = x.floor();
let q = ((x - l) * 64.0).floor() / 64.0;
match self.mip {
MipFilter::Nearest if q > 0.5 => l + 1.0,
MipFilter::Nearest if q > 0.0 => l + 0.25,
MipFilter::Nearest => l,
MipFilter::Linear | MipFilter::None => l + q,
}
}
/// [`Self::of`] of level `x` (an `f32`) in the function.
pub(super) fn emit(&self, fb: &mut FunctionBuilder<'_>, x: SValue) -> BResult<SValue> {
let h = half_level(fb, x)?;
let zero = float(fb, 0.0)?;
let min = float(fb, f32::from_bits(self.min))?;
let max = float(fb, f32::from_bits(self.max))?;
let cap = float(fb, CAP)?;
let h = fb.glsl(GlslOp::FMax, &[h, min])?;
let h = fb.glsl(GlslOp::FMin, &[h, max])?;
let h = fb.glsl(GlslOp::FMax, &[h, zero])?;
let h = fb.glsl(GlslOp::FMin, &[h, cap])?;
let l = fb.glsl(GlslOp::Floor, &[h])?;
let f = fb.binary_no_contraction(BinOp::FSub, h, l)?;
let (sixty_four, step) = (float(fb, 64.0)?, float(fb, 1.0 / 64.0)?);
let f = fb.binary_no_contraction(BinOp::FMul, f, sixty_four)?;
let f = fb.glsl(GlslOp::Floor, &[f])?;
let q = fb.binary_no_contraction(BinOp::FMul, f, step)?;
let up = match self.mip {
MipFilter::Linear | MipFilter::None => q,
MipFilter::Nearest => {
let (half, one, quarter) = (float(fb, 0.5)?, float(fb, 1.0)?, float(fb, 0.25)?);
let next = fb.binary(BinOp::FOrdGreaterThan, q, half)?;
let within = fb.binary(BinOp::FOrdGreaterThan, q, zero)?;
let up = fb.select(within, quarter, zero)?;
fb.select(next, one, up)?
}
};
fb.binary_no_contraction(BinOp::FAdd, l, up)
}
}
/// Level `x` (an `f32`) rounded to `half` to nearest even, a NaN read as 0 (module docs).
fn half_level(fb: &mut FunctionBuilder<'_>, x: SValue) -> BResult<SValue> {
let form = Form {
@@ -281,46 +137,9 @@ pub(super) fn nearest_on_grid(
fb.binary_no_contraction(BinOp::FAdd, l, up)
}
/// Whether `word`'s [`SamplerWord::LEVEL_RULE`] fields state the mip filter `mip` and a sampler
/// that takes its clamp on Metal's grid (a `bool`): normalized coordinates, no anisotropy, and
/// both filters nearest or both linear (`metal::sampler::clamps_on_grid`).
fn word_takes(
fb: &mut FunctionBuilder<'_>,
word: SValue,
mip: SamplerMipFilter,
) -> BResult<SValue> {
let rule = word_const(fb, SamplerWord::LEVEL_RULE)?;
let have = fb.binary(BinOp::BitwiseAnd, word, rule)?;
let nearest = mip.as_raw() << SamplerWord::MIP_FILTER_SHIFT;
let linear = nearest | SamplerWord::MIN_LINEAR | SamplerWord::MAG_LINEAR;
let (nearest, linear) = (word_const(fb, nearest)?, word_const(fb, linear)?);
let a = fb.binary(BinOp::IEqual, have, nearest)?;
let b = fb.binary(BinOp::IEqual, have, linear)?;
fb.binary(BinOp::LogicalOr, a, b)
}
/// A runtime or argument buffer's sampler's level of a sample at level `x` (an `f32`), by its
/// word `word` (module docs): the level handed to the device, `L` or `L + 1` where the word states
/// a sampler that takes its clamp on Metal's grid with a nearest mip filter, `L + q` where it
/// states one with a linear mip filter, `x` elsewhere; and the level before the sampler's clamp
/// that a nearest mip filter reads, which a nearest sample's snap reads.
pub(super) fn by_word(
fb: &mut FunctionBuilder<'_>,
word: SValue,
x: SValue,
) -> BResult<(SValue, SValue)> {
let (l, q) = on_grid(fb, x)?;
let nearest = nearest_on_grid(fb, (l, q))?;
let linear = fb.binary_no_contraction(BinOp::FAdd, l, q)?;
let takes_linear = word_takes(fb, word, SamplerMipFilter::Linear)?;
let lambda = fb.select(takes_linear, linear, x)?;
let takes_nearest = word_takes(fb, word, SamplerMipFilter::Nearest)?;
Ok((fb.select(takes_nearest, nearest, lambda)?, nearest))
}
/// The level a runtime sampler's nearest sample reads (a `u32`) before the texture's levels clamp
/// it, by its word `word`, where the sample's level before the sampler's clamp reads `nearest`
/// (an `f32`, [`by_word`]'s, or 0 at level 0) under a nearest mip filter: that level clamped into
/// (an `f32`, [`nearest_on_grid`]'s, or 0 at level 0) under a nearest mip filter: that level clamped into
/// the levels the word's clamp leaves ([`SamplerWord::LEVEL_MIN`], [`SamplerWord::LEVEL_MAX`])
/// under a nearest mip filter, else 0 (a snapped sample's sampler has no mip filter there).
pub(super) fn snap_level(
@@ -372,202 +191,6 @@ pub(super) fn word_level(
snap_level(fb, word, nearest)
}
/// The snap of sample `op`'s level `value` (the call's level or bias operand) through static
/// sampler `stat` of a texture of `integer` texels, where the module docs reach it: a constexpr
/// sampler's by its state, a runtime or argument buffer's (`stat` a slot, or `None`) by its word.
/// On a device with `VkProperty::MetalSampler` the device's level is Metal's, and the module
/// requires the property instead.
pub(super) fn select(
cx: &mut SelectCx<'_>,
op: &SampleOp,
stat: Option<(SamplerRef, Coordinates)>,
(value, integer): (Option<Value>, bool),
) -> Result<Option<LevelRule>, Error> {
let measured = matches!(
op,
SampleOp::Sample {
lod: Lod::Level(Some(_))
| Lod::Base {
bias: Some(_),
min: None,
},
min_lod: None,
..
}
);
if !measured || integer {
return Ok(None);
}
let constant = match value.and_then(|v| super::select::konst(cx, v)) {
Some(Const::Null) => Some(0.0),
Some(Const::Float(bits)) => Some(f32::from_bits(*bits as u32)),
_ => None,
};
let rule = match stat {
Some((SamplerRef::Constexpr(words), _)) => {
let Some(snap) = LevelSnap::plan(&super::state_of(words)?) else {
return Ok(None);
};
if constant.is_some_and(|x| snap.of(x).to_bits() == x.to_bits()) {
return Ok(None);
}
LevelRule::Stated(snap)
}
// A level on the grid of every rule is a whole level within `[0, 64]`. A comparison
// through a runtime sampler that reads one texel fetches it from the level its word reads
// (`fetched::FetchLevel::Word`); a filtered one keeps the device's level.
Some((SamplerRef::Slot(_), _)) | None => {
let on_grid = constant.is_some_and(|x| x.fract() == 0.0 && (0.0..=CAP).contains(&x));
if on_grid || !matches!(op, SampleOp::Sample { dref: None, .. }) {
return Ok(None);
}
LevelRule::Word
}
};
if cx.profile.device_samples() {
cx.families.sampler.metal_sampler = true;
return Ok(None);
}
Ok(Some(rule))
}
/// Where the level of `op` through `sampler` (`None`: an argument buffer's) is the device's level
/// arithmetic and no other note records it (`PrecisionNote::DeviceSampleLevel`, the module docs),
/// `filtered` whether the sample's filter note records it where its sampler filters
/// (`linear::filter_note`), `snapped` whether [`select`] hands the device Metal's level, `value`
/// the sample's level or bias, and `integer` whether the texture's texels are integers.
///
/// - Never on a device that samples through Metal's own sampler or natively
/// (`DeviceSampling`), nor for a cube, whose level `CubeGradientFootprint` records, nor for a
/// comparison, whose level `DeviceDepthComparison` records where the device compares.
/// - Always for an LOD query, which answers the level.
/// - For a sample at an implicit level whose bias is within the device's limit (a bias past it
/// and hoisted derivatives record `GradFromBias`), with explicit gradients, or at an explicit
/// level that [`select`] does not snap and the device may not read as Metal does
/// ([`reads_metal_level`]): where its sampler chooses a
/// level or a filter by the level (a mip filter, or minification and magnification filters
/// that differ) and the filter note does not hold. A filtered sample's note holds wherever its
/// sampler filters, so through a constexpr sampler that is nearest filters and a nearest mip
/// filter, through a runtime sampler where its word states those, and through an argument
/// buffer's sampler never; a sample no filter note records (an integer texture's) wherever its
/// sampler chooses, an argument buffer's always.
pub(super) fn device_when(
cx: &SelectCx<'_>,
op: &SampleOp,
sampler: Option<SamplerRef>,
(cube, filtered): (bool, bool),
(snapped, value, integer): (bool, Option<Value>, bool),
) -> Result<Vec<NoteClause>, Error> {
let always = || vec![NoteClause::new()];
if cx.profile.device_samples() || cube {
return Ok(Vec::new());
}
let state = match sampler {
Some(SamplerRef::Constexpr(words)) => Some(super::state_of(words)?),
_ => None,
};
match op {
SampleOp::Lod { .. } => return Ok(always()),
SampleOp::Sample { dref: Some(_), .. } => return Ok(Vec::new()),
SampleOp::Sample {
lod:
Lod::Implicit {
reach: BiasReach::Within,
..
}
| Lod::Grad(..),
..
} => {}
SampleOp::Sample {
lod: Lod::Level(_) | Lod::Base { .. },
..
} if !snapped => {
let level = constant_level(cx, op, value);
if level.is_some_and(|x| reads_metal_level(x, state.as_ref(), integer)) {
return Ok(Vec::new());
}
}
_ => return Ok(Vec::new()),
}
Ok(match (sampler, state) {
(Some(SamplerRef::Constexpr(_)), Some(s)) => {
let chooses = s.mip_filter != MipFilter::None || s.min_filter != s.mag_filter;
match chooses && !filtered {
true => always(),
false => Vec::new(),
}
}
(Some(SamplerRef::Slot(n)), _) => {
let on = NoteOn::Sampler(n);
let nearest_mip = 1 << SamplerWord::MIP_FILTER_SHIFT;
match filtered {
true => any_of([NoteTest::equal(on, SamplerWord::LINEAR_FILTER, nearest_mip)]),
false => any_of([
NoteTest::differ(on, SamplerWord::MIP_FILTER, 0),
NoteTest::equal(on, SamplerWord::LINEAR, SamplerWord::MIN_LINEAR),
NoteTest::equal(on, SamplerWord::LINEAR, SamplerWord::MAG_LINEAR),
]),
}
}
_ => match filtered {
true => Vec::new(),
false => always(),
},
})
}
/// The level sample `op` reads at an explicit level where the function states it: its level
/// `value` (`None`: level 0), or a kernel's sample without a level, at its bias `value` (`None`:
/// level 0); `None` where a clamp of the call's own enters or the value is not a constant.
fn constant_level(cx: &SelectCx<'_>, op: &SampleOp, value: Option<Value>) -> Option<f32> {
let SampleOp::Sample {
lod, min_lod: None, ..
} = op
else {
return None;
};
match lod {
Lod::Level(None)
| Lod::Base {
bias: None,
min: None,
} => Some(0.0),
Lod::Level(Some(_)) | Lod::Base { min: None, .. } => {
match value.and_then(|v| super::select::konst(cx, v)) {
Some(Const::Null) => Some(0.0),
Some(Const::Float(bits)) => Some(f32::from_bits(*bits as u32)),
_ => None,
}
}
_ => None,
}
}
/// Whether the device reads Metal's level at the constant explicit level `x` that [`select`] does
/// not snap, through constexpr sampler `state` (`None`: a runtime or argument buffer's), of a
/// texture of `integer` texels:
/// - through a constexpr sampler, where `x` is a whole level that its clamp leaves whole within
/// `[0, 64]`, without a level bias of its own; or, of a texture of float texels, where its snap
/// hands the device `x` itself ([`LevelSnap::of`]);
/// - through a runtime or argument buffer's sampler, of a texture of float texels, where `x` is a
/// whole level within `[0, 64]`: its clamp is on Metal's grid there (`metal::sampler::vk_sampler`).
/// An integer texture's sampler keeps the descriptor's clamp, which may move such a level off it.
fn reads_metal_level(x: f32, state: Option<&SamplerState>, integer: bool) -> bool {
let whole = |x: f32| x.fract() == 0.0 && (0.0..=CAP).contains(&x);
match state {
Some(s) => {
let (min, max) = (s.lod_min_clamp.to_f32(), s.lod_max_clamp.to_f32());
let clamps = !min.is_nan() && !max.is_nan() && min <= max;
let kept =
s.lod_bias.to_f32() == 0.0 && clamps && whole(x) && whole(x.max(min).min(max));
let snaps = !integer
&& LevelSnap::plan(s).is_some_and(|snap| snap.of(x).to_bits() == x.to_bits());
kept || snaps
}
None => !integer && whole(x),
}
}
/// The `u32` constant `v`.
fn word_const(fb: &mut FunctionBuilder<'_>, v: u32) -> BResult<SValue> {
let c = fb.u32_const(v)?;
@@ -1,11 +1,6 @@
//! Metal's level rule against the probes' answers, and [`LevelSnap::emit`] on the interpreter
//! against [`LevelSnap::of`].
//! Metal's level rule: the level a nearest mip filter reads, against the probe's answers, and
//! `word_level` on the interpreter against the host's rule.
use super::LevelSnap;
use crate::air::abi::{
AddressMode, BorderColor, CompareFunction, Coordinates, Filter, Half, MipFilter, Reduction,
SamplerState,
};
use crate::float16::{f16_bits_to_f32, f32_to_f16_bits};
use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
@@ -17,24 +12,6 @@ use crate::spirv::ir::{
Type, TypedModule,
};
/// A sampler's snap with its level clamp `[min, max]`.
fn snap(mip: MipFilter, (min, max): (f32, f32)) -> LevelSnap {
LevelSnap {
mip,
min: min.to_bits(),
max: max.to_bits(),
}
}
/// No level clamp.
const OPEN: (f32, f32) = (0.0, f32::INFINITY);
/// The level a device's nearest mip filter reads at `λ` (Vulkan: `ceil(λ + 1/2) - 1`), in a
/// texture of `levels` levels.
fn nearest_level(lambda: f32, levels: f32) -> f32 {
((lambda + 0.5).ceil() - 1.0).clamp(0.0, levels - 1.0)
}
/// Our probe's `r32Float` 2D texture of five levels, level `L` holding `L`: rows of (level
/// `x`'s bits; the nearest-mip and linear-mip samples; and those of samplers clamping the level
/// into `[0.75, 2.5]`, linear then nearest), Apple M4 on macOS 27.0.1. A linear mip filter's
@@ -65,92 +42,30 @@ const MEASURED: [(u32, f32, f32, f32, f32); 23] = [
(0x0000_0001, 0.0, 0.0, 0.75, 1.0),
];
/// Each measured level, handed to a device as [`LevelSnap::of`] makes it, reads Metal's level
/// under a nearest mip filter and blends Metal's weight under a linear one, without a level
/// clamp and within `[0.75, 2.5]`.
/// The level a nearest mip filter reads at level `x` before the sampler's clamp, by Metal's rule:
/// `x` rounded to `half` (a NaN reads 0), clamped into `[0, 64]`, and `L + 1` where its fraction
/// truncated onto sixty-fourths is above one half, else `L`.
fn nearest_rule(x: f32) -> f32 {
let h = if x.is_nan() {
0.0
} else {
f16_bits_to_f32(f32_to_f16_bits(x))
};
let h = h.clamp(0.0, 64.0);
let l = h.floor();
let q = ((h - l) * 64.0).floor() / 64.0;
l + if q > 0.5 { 1.0 } else { 0.0 }
}
/// The rule reads the probe's nearest-mip levels of a texture of five levels.
#[test]
fn the_snapped_level_reads_metals_measured_levels() {
let levels = 5.0;
let clamp = (0.75, 2.5);
for (bits, nearest, linear, linear_clamped, nearest_clamped) in MEASURED {
fn the_rule_reads_the_measured_nearest_levels() {
for &(bits, nearest, ..) in &MEASURED {
let x = f32::from_bits(bits);
let n = snap(MipFilter::Nearest, OPEN).of(x);
assert_eq!(
nearest_level(n, levels),
nearest,
"nearest at {x:e} (λ {n:e})"
);
let l = snap(MipFilter::Linear, OPEN).of(x);
assert_eq!(l.min(levels - 1.0), linear, "linear at {x:e}");
let l = snap(MipFilter::Linear, clamp).of(x);
assert_eq!(
l.min(levels - 1.0),
linear_clamped,
"clamped linear at {x:e}"
);
let n = snap(MipFilter::Nearest, clamp).of(x);
assert_eq!(
nearest_level(n, levels),
nearest_clamped,
"clamped nearest at {x:e}"
);
assert_eq!(nearest_rule(x).min(4.0), nearest, "{x:e} ({bits:#010x})");
}
}
/// A constexpr sampler of mip filter `mip` clamping the level into `[min, max]`.
fn state(mip: MipFilter, (min, max): (f32, f32)) -> SamplerState {
SamplerState {
address_s: AddressMode::ClampToEdge,
address_t: AddressMode::ClampToEdge,
address_r: AddressMode::ClampToEdge,
mag_filter: Filter::Linear,
min_filter: Filter::Linear,
mip_filter: mip,
coordinates: Coordinates::Normalized,
compare: CompareFunction::None,
max_anisotropy: 1,
lod_min_clamp: Half(f32_to_f16_bits(min)),
lod_max_clamp: Half(f32_to_f16_bits(max)),
border_color: BorderColor::TransparentBlack,
reduction: Reduction::WeightedAverage,
lod_bias: Half(0),
}
}
/// The snap reaches a level clamp only where the device's `minLod` never moves the level it hands
/// over: on the 1/64 grid under a linear mip filter, off `[1/2, 33/64)` under a nearest one, and
/// any without a mip filter; and no pixel, anisotropic, or biasing sampler.
#[test]
fn the_snap_reaches_clamps_the_device_keeps() {
use MipFilter::{Linear, Nearest, None as Unmipped};
let reached = |mip, clamp| LevelSnap::plan(&state(mip, clamp)).is_some();
for (mip, min, want) in [
(Linear, 0.0, true),
(Linear, 0.75, true),
(Linear, 2.0 + 5.0 / 64.0, true),
(Linear, 0.3, false),
(Linear, 1.0 + 1.0 / 128.0, false),
(Nearest, 0.3, true),
(Nearest, 0.75, true),
(Nearest, 1.0 + 33.0 / 64.0, true),
(Nearest, 0.5, false),
(Nearest, 2.51, false),
(Unmipped, 0.3, true),
] {
assert_eq!(reached(mip, (min, 1000.0)), want, "{mip:?} from {min}");
}
assert!(!reached(Linear, (2.0, 1.0)), "an empty clamp");
let mut s = state(Linear, OPEN);
s.coordinates = Coordinates::Pixel;
assert!(LevelSnap::plan(&s).is_none(), "a pixel sampler");
let mut s = state(Linear, OPEN);
s.max_anisotropy = 4;
assert!(LevelSnap::plan(&s).is_none(), "an anisotropic sampler");
let mut s = state(Linear, OPEN);
s.lod_bias = Half(f32_to_f16_bits(0.5));
assert!(LevelSnap::plan(&s).is_none(), "a biasing sampler");
}
fn slot(index: u32) -> ResourceSlot {
ResourceSlot {
stage: Stage::Kernel,
@@ -186,9 +101,9 @@ fn word(f: &mut FunctionBuilder<'_>, buf: GlobalId, i: Value, per: u32, k: u32)
f.access_chain(base, &[zero, at])
}
/// A kernel whose invocation `i` reads a level's bits from buffer 0 and writes the bits of each
/// of `snaps`' level to buffer 1.
fn kernel(snaps: &[LevelSnap]) -> BResult<TypedModule> {
/// A kernel whose invocation `i` reads `(bits(x), word)` from buffer 0 and writes `word_level`'s
/// level of it to buffer 1.
fn word_kernel() -> BResult<TypedModule> {
let mut b = ModuleBuilder::new();
let f32_ = b.ty(Type::Float { width: 32 })?;
let u32_ = b.ty(Type::Int {
@@ -204,16 +119,14 @@ fn kernel(snaps: &[LevelSnap]) -> BResult<TypedModule> {
let gid = f.module().global_value(id)?;
let gid = f.load(gid, MemAccess::default())?;
let i = f.composite_extract(gid, &[0])?;
let at = word(&mut f, input, i, 1, 0)?;
let at = word(&mut f, input, i, 2, 0)?;
let xb = f.load(at, MemAccess::default())?;
let x = f.convert(ConvOp::Bitcast, xb, f32_)?;
let per = u32::try_from(snaps.len()).expect("snaps");
for (k, s) in snaps.iter().enumerate() {
let v = s.emit(&mut f, x)?;
let bits = f.convert(ConvOp::Bitcast, v, u32_)?;
let at = word(&mut f, output, i, per, k as u32)?;
f.store(at, bits, MemAccess::default())?;
}
let at = word(&mut f, input, i, 2, 1)?;
let w = f.load(at, MemAccess::default())?;
let level = super::word_level(&mut f, w, Some(x))?;
let at = word(&mut f, output, i, 1, 0)?;
f.store(at, level, MemAccess::default())?;
f.ret(None)?;
let main = f.finish()?;
b.entry(
@@ -224,7 +137,7 @@ fn kernel(snaps: &[LevelSnap]) -> BResult<TypedModule> {
b.finalize()
}
/// The levels the snap is checked at: the measured ones, every `1/256` from -2 to 18, each `half`
/// The levels the rule is checked at: the measured ones, every `1/256` from -2 to 18, each `half`
/// of `[1/4, 6)` with its tie to the next and the tie's `f32` neighbours, and the edges.
fn levels() -> Vec<u32> {
let mut out: Vec<u32> = MEASURED.iter().map(|m| m.0).collect();
@@ -247,91 +160,7 @@ fn levels() -> Vec<u32> {
out
}
/// [`LevelSnap::emit`] is [`LevelSnap::of`], bit for bit, under every mip filter, without and with
/// a level clamp, at every level of [`levels`].
#[test]
fn the_snap_computes_metals_level_in_the_function() {
let snaps = [
snap(MipFilter::Nearest, OPEN),
snap(MipFilter::Linear, OPEN),
snap(MipFilter::None, OPEN),
snap(MipFilter::Nearest, (0.300_048_83, 2.699_218_8)),
snap(MipFilter::Linear, (0.75, 2.5)),
];
let m = kernel(&snaps).expect("kernel");
let lanes = levels();
let per = snaps.len();
let bytes: Vec<u8> = lanes.iter().flat_map(|b| b.to_le_bytes()).collect();
let res = Resources {
buffers: vec![
Buffer {
slot: Some(slot(0)),
address: None,
bytes,
},
Buffer {
slot: Some(slot(1)),
address: None,
bytes: vec![0xAB; lanes.len() * per * 4],
},
],
..Resources::default()
};
let cfg = Config {
workgroups: [u32::try_from(lanes.len()).expect("lanes"), 1, 1],
..Config::default()
};
let (out, _) = interp::run_with_images(&m, &cfg, res, Vec::new()).expect("run");
let mut wrong = Vec::new();
for (i, &b) in lanes.iter().enumerate() {
let x = f32::from_bits(b);
for (k, s) in snaps.iter().enumerate() {
let at = 4 * (i * per + k);
let got = u32::from_le_bytes(out.buffers[1][at..at + 4].try_into().expect("word"));
let want = s.of(x).to_bits();
if got != want {
wrong.push(format!(
"{s:?} at {x:e} ({b:#010x}): {got:#010x}, want {want:#010x}"
));
}
}
}
assert!(
wrong.is_empty(),
"{} differ:\n{}",
wrong.len(),
wrong.join("\n")
);
}
/// The word rule's level handed to the device, and the level before the sampler's clamp a
/// nearest mip filter reads, at level `x` through a runtime sampler of word `word`, as the host
/// computes them (`by_word`).
fn word_rule(word: u32, x: f32) -> (f32, f32) {
use crate::metal::sampler::SamplerWord as W;
let h = if x.is_nan() {
0.0
} else {
f16_bits_to_f32(f32_to_f16_bits(x))
};
let h = h.clamp(0.0, 64.0);
let l = h.floor();
let q = ((h - l) * 64.0).floor() / 64.0;
let nearest = l + if q > 0.5 { 1.0 } else { 0.0 };
let rule = word & W::LEVEL_RULE;
let both = W::MIN_LINEAR | W::MAG_LINEAR;
let (n, li) = (1 << W::MIP_FILTER_SHIFT, 2 << W::MIP_FILTER_SHIFT);
let lambda = if rule == n || rule == n | both {
nearest
} else if rule == li || rule == li | both {
l + q
} else {
x
};
(lambda, nearest)
}
/// The level a runtime sampler's leveled nearest snap reads before the texture's levels clamp it
/// The level a runtime sampler's nearest mip filter reads before the texture's levels clamp it
/// (`snap_level`), as the host computes it.
fn snap_level_of(word: u32, nearest: f32) -> u32 {
use crate::metal::sampler::{SamplerWord as W, LAST_WORD_LEVEL};
@@ -343,167 +172,10 @@ fn snap_level_of(word: u32, nearest: f32) -> u32 {
(nearest as u32).max(min).min(max)
}
/// Metal's level and weight at level `x` through a runtime sampler clamping it into `[lo, hi]`
/// (`f32`s) in a texture of `levels` levels: the rule with the clamp held as `f32`s, which our
/// probe reads on all 37,080 of its lanes (Apple M4, macOS 27.0.1). The nearest mip
/// filter's level, and the linear one's `L + q`.
fn metal_runtime(x: f32, (lo, hi): (f32, f32), levels: f32) -> (f32, f32) {
let h = if x.is_nan() {
0.0
} else {
f16_bits_to_f32(f32_to_f16_bits(x))
};
let v = h.max(lo).min(hi).max(0.0).min(levels - 1.0);
let l = v.floor();
let q = ((v - l) * 64.0).floor() / 64.0;
(l + if q > 0.5 { 1.0 } else { 0.0 }, l + q)
}
/// Rows our probe measured through runtime samplers (Apple M4, macOS 27.0.1, an
/// `r32Float` texture of five levels, level `L` holding `L`): the clamp `[lo, hi]`'s bits, level
/// `x`'s bits, and the nearest and linear mip filters' samples (nearest filters). Bounds just
/// below `33/64` and `21/64` read as `f32`s, where `half`s would round them onto the step.
const MEASURED_RUNTIME: [(u32, u32, u32, f32, f32); 9] = [
// `[0.515_624_94, 9]` (just below 33/64) at -1: level 0, weight 32/64.
(0x3f03_ffff, 0x4110_0000, 0xbf80_0000, 0.0, 0.5),
// `[33/64, 9]` at -1: level 1, weight 33/64.
(0x3f04_0000, 0x4110_0000, 0xbf80_0000, 1.0, 0.515_625),
// `[0.328_124_97, 9]` (just below 21/64) at 0: weight 20/64.
(0x3ea7_ffff, 0x4110_0000, 0x0000_0000, 0.0, 0.3125),
// `[0.75, 2.5]` at 3: level 2 and `2.5`.
(0x3f40_0000, 0x4020_0000, 0x4040_0000, 2.0, 2.5),
// `[0.3, 2.7]` at -1 and at 4.
(0x3e99_999a, 0x402c_cccd, 0xbf80_0000, 0.0, 0.296_875),
(0x3e99_999a, 0x402c_cccd, 0x4080_0000, 3.0, 2.687_5),
// `[0, 2.4999]` at 3: level 2, weight 31/64.
(0x0000_0000, 0x401f_fe5d, 0x4040_0000, 2.0, 2.484_375),
// `[0, 1 + 33/64]` at 4.
(0x0000_0000, 0x3fc2_0000, 0x4080_0000, 2.0, 1.515_625),
// No clamp, at a NaN.
(0x0000_0000, 0x7f7f_ffff, 0x7fc0_0000, 0.0, 0.0),
];
/// A runtime sampler's level handed to a device as the word rule makes it, through the `VkSampler`
/// the runtime makes of it (its clamp on Metal's grid, `metal::sampler::vk_sampler`), reads Metal's
/// level under a nearest mip filter and Metal's `L + q` under a linear one, at every level of
/// [`levels`] and through every clamp our probe measured; and Metal's rule with `f32`
/// clamps answers the probe's measured rows.
/// `word_level` in the function is the host's rule, bit for bit, for words of every mip filter,
/// filters alike and not, coordinates, anisotropy and clamp levels, at every level of [`levels`].
#[test]
fn a_runtime_samplers_word_level_reads_metals_level_through_its_grid_clamp() {
use crate::metal::sampler::{level_on_grid, nearest_level, SamplerWord as W};
for &(lo, hi, x, nearest, linear) in &MEASURED_RUNTIME {
let (lo, hi, x) = (f32::from_bits(lo), f32::from_bits(hi), f32::from_bits(x));
assert_eq!(
metal_runtime(x, (lo, hi), 5.0),
(nearest, linear),
"[{lo:e}, {hi:e}] at {x:e}"
);
}
let below = |x: f32| x.next_down();
let clamps = [
(0.0, f32::MAX),
(0.75, 2.5),
(0.3, 2.7),
(0.5, 9.0),
(below(33.0 / 64.0), 9.0),
(33.0 / 64.0, 9.0),
(0.507_812_5, 9.0),
(below(21.0 / 64.0), 9.0),
(1.5, 9.0),
(1.0 + below(33.0 / 64.0), 9.0),
(0.0, 1.5),
(0.0, 1.0 + below(33.0 / 64.0)),
(0.0, 1.0 + 33.0 / 64.0),
(0.0, 2.4999),
(0.0, 1.0 + below(21.0 / 64.0)),
(2.2, 2.2),
(6.0, 9.0),
(0.0001, 9.0),
];
let count = 5.0;
let lanes = levels();
let mut checked = 0;
for (lo, hi) in clamps {
for filters in [0, W::MIN_LINEAR | W::MAG_LINEAR] {
for (mip, nearest_mip) in [(1u32, true), (2, false)] {
let word = filters | (mip << W::MIP_FILTER_SHIFT);
let (min_lod, max_lod) = if nearest_mip {
(nearest_level(lo) as f32, nearest_level(hi) as f32)
} else {
(level_on_grid(lo), level_on_grid(hi))
};
for &b in &lanes {
let x = f32::from_bits(b);
let (lambda, _) = word_rule(word, x);
let handed = lambda.max(min_lod).min(max_lod);
let (metal_nearest, metal_linear) = metal_runtime(x, (lo, hi), count);
if nearest_mip {
assert_eq!(
nearest_level(handed.min(count - 1.0)) as f32,
metal_nearest,
"[{lo:e}, {hi:e}] word {word:#x} at {x:e}: handed {handed:e}"
);
assert_eq!(handed.fract(), 0.0, "a whole level: {handed:e}");
} else {
assert_eq!(
handed.min(count - 1.0),
metal_linear,
"[{lo:e}, {hi:e}] word {word:#x} at {x:e}"
);
}
checked += 1;
}
}
}
}
assert!(checked > 100_000, "{checked}");
}
/// A kernel whose invocation `i` reads `(bits(x), word)` from buffer 0 and writes the bits of the
/// word rule's level and `snap_level`'s level of it to buffer 1.
fn word_kernel() -> BResult<TypedModule> {
let mut b = ModuleBuilder::new();
let f32_ = b.ty(Type::Float { width: 32 })?;
let u32_ = b.ty(Type::Int {
width: 32,
signed: false,
})?;
let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?;
let input = storage_buffer(&mut b, 0, u32_)?;
let output = storage_buffer(&mut b, 1, u32_)?;
let id = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?;
let void = b.ty(Type::Void)?;
let mut f = b.function(void)?;
let gid = f.module().global_value(id)?;
let gid = f.load(gid, MemAccess::default())?;
let i = f.composite_extract(gid, &[0])?;
let at = word(&mut f, input, i, 2, 0)?;
let xb = f.load(at, MemAccess::default())?;
let x = f.convert(ConvOp::Bitcast, xb, f32_)?;
let at = word(&mut f, input, i, 2, 1)?;
let w = f.load(at, MemAccess::default())?;
let (lambda, nearest) = super::by_word(&mut f, w, x)?;
let level = super::snap_level(&mut f, w, nearest)?;
let bits = f.convert(ConvOp::Bitcast, lambda, u32_)?;
let at = word(&mut f, output, i, 2, 0)?;
f.store(at, bits, MemAccess::default())?;
let at = word(&mut f, output, i, 2, 1)?;
f.store(at, level, MemAccess::default())?;
f.ret(None)?;
let main = f.finish()?;
b.entry(
ExecModel::GLCompute,
main,
vec![ExecMode::LocalSize { x: 1, y: 1, z: 1 }],
)?;
b.finalize()
}
/// `by_word` and `snap_level` in the function are the host's word rule, bit for bit, for words of
/// every mip filter, filters alike and not, coordinates, anisotropy and clamp levels, at every
/// level of [`levels`].
#[test]
fn the_word_rule_computes_metals_level_in_the_function() {
fn the_word_level_computes_metals_level_in_the_function() {
use crate::metal::sampler::SamplerWord as W;
let clamp = |min: u32, max: u32| {
(min << W::LEVEL_MIN_SHIFT)
@@ -547,7 +219,7 @@ fn the_word_rule_computes_metals_level_in_the_function() {
Buffer {
slot: Some(slot(1)),
address: None,
bytes: vec![0xAB; lanes.len() * 8],
bytes: vec![0xAB; lanes.len() * 4],
},
],
..Resources::default()
@@ -560,23 +232,12 @@ fn the_word_rule_computes_metals_level_in_the_function() {
let mut wrong = Vec::new();
for (i, &(b, w)) in lanes.iter().enumerate() {
let x = f32::from_bits(b);
let at = 8 * i;
let got = |k: usize| {
u32::from_le_bytes(
out.buffers[1][at + 4 * k..at + 4 * k + 4]
.try_into()
.expect("word"),
)
};
let (lambda, nearest) = word_rule(w, x);
let want = (lambda.to_bits(), snap_level_of(w, nearest));
if (got(0), got(1)) != want {
let at = 4 * i;
let got = u32::from_le_bytes(out.buffers[1][at..at + 4].try_into().expect("word"));
let want = snap_level_of(w, nearest_rule(x));
if got != want {
wrong.push(format!(
"word {w:#x} at {x:e} ({b:#010x}): ({:#010x}, {}), want ({:#010x}, {})",
got(0),
got(1),
want.0,
want.1
"word {w:#x} at {x:e} ({b:#010x}): {got}, want {want}"
));
}
}
File diff suppressed because it is too large. Load diff
@@ -1,344 +0,0 @@
//! A depth comparison's per-tap test, the one entry point every comparison the shader makes
//! itself takes: a cube's comparison gather (`cube::gather`) and a linear comparison
//! (`linear::sum`).
//!
//! **What Metal compares** (Apple M4, macOS 27.0.1; the probes for cube gathers, for 2D linear and
//! nearest comparisons and comparison gathers, each run with and without Metal's validation layer;
//! the Apple M3 Max, macOS 26.7, answers every lane of the four alike). Each tap is compared on its
//! own, the reference `r` against the tap's depth `x` as `r OP x` in `f32`, `1` where it passes and
//! `0` elsewhere; a NaN fails every ordered comparison and passes `not_equal`. A float format's
//! reference and texel are compared as given (NaN, denormals and values outside `[0, 1]` included);
//! a `Depth16Unorm` texture's as codes, the texel's its code and the reference's the code of its
//! exact product with 65535 ([`reference()`]). The shader compares the values' integer keys
//! ([`key`]), not the floats: a device's float comparison may flush a denormal to zero, as x86
//! lavapipe's does (`runtime_lane::depth_compares` with float comparisons: 82 of 3,392
//! `Depth32Float` comparisons differed from Metal's, such as the least denormal reference passing
//! `less_equal` against a zero texel; with the keys, none), and Metal's does not. A tap outside a
//! border axis compares the border's depth as it would a texel's (zero, opaque black and opaque
//! white borders under `less` and `greater`, every lane of 2,048).
//!
//! **A linear comparison** (2,560 lanes clamping to the edge, 2,048 to zero, and 2,032 through a
//! runtime pixel sampler; `Depth16Unorm` alike) is an `r8Unorm` texture's linear sample of the
//! passes as codes 0 and 255 (`linear::sum` with [`PASS_FORMAT`]): the exact weighted sum of the
//! passes rounded once onto `1/4080`, ties up.
//!
//! `TapCompare::new` takes the sampler's compare function; a constexpr sampler's is known when
//! the function compiles. A runtime sampler's is its word's `COMPARE` field, the raw
//! `MTLCompareFunction`, whose bits 0, 1 and 2 say whether a reference below, equal to, and above
//! the texel passes (`never` 0, `less` 1, `equal` 2, `less_equal` 3, `greater` 4, `not_equal` 5,
//! `greater_equal` 6, `always` 7): `TapCompare::of_word` tests the three orders and takes the bits,
//! and where either value is a NaN passes exactly where bits 0 and 2 are both set (`not_equal` and
//! `always`), as the named functions do.
use crate::air::abi::CompareFunction;
use crate::lower::emit::EmitCx;
use crate::metal::bicubic::BicubicTexels;
use crate::metal::sampler::SamplerWord;
use crate::metal::PixelFormat;
use crate::spirv::builder::FunctionBuilder;
use crate::spirv::error::BResult;
use crate::spirv::ids::Value as SValue;
use crate::spirv::ir::{BinOp, ConvOp, GlslOp, Type as SType, UnOp};
use super::super::bicubic::{scalar, value, Bits, Tys};
/// The format whose linear sum of codes 0 and 255 a linear comparison's passes are summed as
/// (module docs).
pub(in crate::lower::sampler) const PASS_FORMAT: PixelFormat = PixelFormat::R8Unorm;
/// The census words of a comparison's setup: its reference's code ([`reference()`]) and key
/// ([`key`]), the format's test, and their constants.
pub(in crate::lower::sampler) const REFERENCE_WORDS: u32 = 240;
/// The census words of one tap's comparison: the depth's extraction, its code and key, the test and
/// the NaNs', the pass's select, and the tap's assembly.
pub(in crate::lower::sampler) const TAP_WORDS: u32 = 112;
/// The census words a runtime sampler's comparison adds to its setup: the word's three function
/// bits and the NaN's pass, with their constants.
pub(in crate::lower::sampler) const WORD_REFERENCE_WORDS: u32 = 64;
/// The census words a runtime sampler's comparison adds to each tap: the three orders' tests and
/// their selection by the function's bits.
pub(in crate::lower::sampler) const WORD_TAP_WORDS: u32 = 48;
/// A comparison's function (module docs): a constexpr sampler's, or a runtime sampler's word's
/// `COMPARE` field.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Comparison {
Function(CompareFunction),
Word,
}
impl Comparison {
/// The census words of the comparison's setup and of `taps` taps' tests.
pub(in crate::lower::sampler) fn words(self, taps: u32) -> u32 {
let base = REFERENCE_WORDS + taps * TAP_WORDS;
match self {
Comparison::Function(_) => base,
Comparison::Word => base + WORD_REFERENCE_WORDS + taps * WORD_TAP_WORDS,
}
}
}
/// The code steps of a normalized depth format, `Depth16Unorm`'s (the only one whose
/// `TexelFormat` is `BicubicTexels::EXACT`, `metal::texel_format`).
const DEPTH_CODES: f32 = 65535.0;
/// How a comparison tests each tap (module docs): its reference as compared and whether the
/// bound format compares codes.
pub(in crate::lower::sampler) struct TapCompare {
test: Test,
/// The key of the reference as compared ([`reference()`], [`key`]).
reference: SValue,
/// The reference is not a NaN (a `bool`).
ordered: SValue,
/// The bound format is normalized (`Depth16Unorm`, a `bool`): its codes are compared.
normalized: SValue,
}
/// A compare function's test of reference `r` against texel `x`.
#[derive(Clone, Copy)]
enum Test {
/// `r OP x` on their keys ([`key`]), passing where either is a NaN iff `unordered`.
Op {
op: BinOp,
unordered: bool,
},
Always,
Never,
/// A runtime sampler's function (module docs): `r < x`, `r == x` and `r > x` on their keys,
/// each passing where its bit (`below`, `equal`, `above`, `bool`s) is set, and where either
/// is a NaN `unordered` (a `bool`).
Word {
below: SValue,
equal: SValue,
above: SValue,
unordered: SValue,
},
}
impl TapCompare {
/// The comparison of reference `dref` under `comparison`, a runtime sampler's by `word` (its
/// `SamplerState` specialization's word, a `u32`), on a texture bound in the format whose
/// treatment is `bits` ([`TapCompare::new`], [`TapCompare::of_word`]).
pub(in crate::lower::sampler) fn of(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
t: &Tys,
(comparison, word): (Comparison, Option<SValue>),
(dref, bits): (SValue, Bits),
) -> BResult<TapCompare> {
match (comparison, word) {
(Comparison::Function(f), _) => TapCompare::new(cx, fb, t, f, (dref, bits)),
(Comparison::Word, Some(w)) => TapCompare::of_word(fb, t, w, (dref, bits)),
(Comparison::Word, None) => {
Err(cx.fail("a runtime sampler's comparison without its word"))
}
}
}
/// The comparison of reference `dref` under the function runtime sampler word `word` (a
/// `u32`) states in its `COMPARE` field (module docs), on a texture bound in the format whose
/// treatment is `bits`.
pub(in crate::lower::sampler) fn of_word(
fb: &mut FunctionBuilder<'_>,
t: &Tys,
word: SValue,
(dref, bits): (SValue, Bits),
) -> BResult<TapCompare> {
let field = super::super::bicubic::word_field(
fb,
t,
word,
SamplerWord::COMPARE_SHIFT,
SamplerWord::COMPARE >> SamplerWord::COMPARE_SHIFT,
)?;
let zero = scalar(fb, t.u32_, 0)?;
let zero = value(fb, zero)?;
let mut set = [field; 3];
for (k, b) in set.iter_mut().enumerate() {
let bit = scalar(fb, t.u32_, 1 << k)?;
let bit = value(fb, bit)?;
let and = fb.binary(BinOp::BitwiseAnd, field, bit)?;
*b = fb.binary(BinOp::INotEqual, and, zero)?;
}
let [below, equal, above] = set;
let unordered = fb.binary(BinOp::LogicalAnd, below, above)?;
let normalized = bits.test(fb, t, BicubicTexels::EXACT)?;
let reference = reference(fb, dref, normalized)?;
let (reference, ordered) = key(fb, reference)?;
Ok(TapCompare {
test: Test::Word {
below,
equal,
above,
unordered,
},
reference,
ordered,
normalized,
})
}
/// The comparison of reference `dref` (an `f32`) under `function`, on a texture bound in the
/// format whose treatment is `bits` (a slot's `TexelFormat` bits; `EXACT` is the normalized
/// `Depth16Unorm`'s).
pub(in crate::lower::sampler) fn new(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
t: &Tys,
function: CompareFunction,
(dref, bits): (SValue, Bits),
) -> BResult<TapCompare> {
let ordered = |op| Test::Op {
op,
unordered: false,
};
let test = match function {
CompareFunction::Less => ordered(BinOp::SLessThan),
CompareFunction::LessEqual => ordered(BinOp::SLessThanEqual),
CompareFunction::Greater => ordered(BinOp::SGreaterThan),
CompareFunction::GreaterEqual => ordered(BinOp::SGreaterThanEqual),
CompareFunction::Equal => ordered(BinOp::IEqual),
CompareFunction::NotEqual => Test::Op {
op: BinOp::INotEqual,
unordered: true,
},
CompareFunction::Always => Test::Always,
CompareFunction::Never => Test::Never,
CompareFunction::None => return Err(cx.fail("a comparison without its function")),
};
let normalized = bits.test(fb, t, BicubicTexels::EXACT)?;
let reference = reference(fb, dref, normalized)?;
let (reference, ordered) = key(fb, reference)?;
Ok(TapCompare {
test,
reference,
ordered,
normalized,
})
}
/// `1.0` where the reference passes against depth `x` (an `f32`: a fetched tap's, the
/// border's, or a cube's made-up corner's), else `0.0`.
pub(in crate::lower::sampler) fn pass(
&self,
fb: &mut FunctionBuilder<'_>,
x: SValue,
) -> BResult<SValue> {
let (one, zero) = (float(fb, 1.0)?, float(fb, 0.0)?);
let (op, unordered) = match self.test {
Test::Op { op, unordered } => (op, unordered),
Test::Always => return Ok(one),
Test::Never => return Ok(zero),
Test::Word {
below,
equal,
above,
unordered,
} => {
let x = compared_texel(fb, x, self.normalized)?;
let (x, ordered) = key(fb, x)?;
let mut passes = [x; 3];
for (p, (op, bit)) in passes.iter_mut().zip([
(BinOp::SLessThan, below),
(BinOp::IEqual, equal),
(BinOp::SGreaterThan, above),
]) {
let order = fb.binary(op, self.reference, x)?;
*p = fb.binary(BinOp::LogicalAnd, order, bit)?;
}
let [lt, eq, gt] = passes;
let pass = fb.binary(BinOp::LogicalOr, lt, eq)?;
let pass = fb.binary(BinOp::LogicalOr, pass, gt)?;
let ordered = fb.binary(BinOp::LogicalAnd, self.ordered, ordered)?;
let pass = fb.select(ordered, pass, unordered)?;
return fb.select(pass, one, zero);
}
};
let x = compared_texel(fb, x, self.normalized)?;
let (x, ordered) = key(fb, x)?;
let pass = fb.binary(op, self.reference, x)?;
let ordered = fb.binary(BinOp::LogicalAnd, self.ordered, ordered)?;
let pass = if unordered {
let nan = fb.unary(UnOp::LogicalNot, ordered)?;
fb.binary(BinOp::LogicalOr, pass, nan)?
} else {
fb.binary(BinOp::LogicalAnd, pass, ordered)?
};
fb.select(pass, one, zero)
}
}
/// The `f32` constant `v`.
fn float(fb: &mut FunctionBuilder<'_>, v: f32) -> BResult<SValue> {
let f32_ = fb.module().ty(SType::Float { width: 32 })?;
let c = scalar(fb, f32_, u64::from(v.to_bits()))?;
value(fb, c)
}
/// The value a comparison compares reference `r` as (the probes, Apple M4 on macOS 27.0.1): a float
/// format's as given, NaN and values outside `[0, 1]` included; where `normalized`
/// (`Depth16Unorm`), its code: `r` clamped into `[0, 1]` (`m`) and the exact product `m · 65535`
/// rounded to the nearest integer (at the one half-way reference, 0.5, up to 32768), a NaN kept.
/// The product is rounded once in `f32` to `k` and corrected: with `h = m · 65536` (exact), the
/// exact product lies above `k + 1/2` exactly where `h - (k + 1/2) > m`, and below `k -
/// 1/2` where `h - (k - 1/2) < m`, each difference exact where it decides (its operands within a
/// factor of two). Metal rounds the exact product: our probe's 96 references whose
/// `f32` product rounds to a half-way point between the other code and the exact product's code
/// each read the exact product's.
fn reference(fb: &mut FunctionBuilder<'_>, r: SValue, normalized: SValue) -> BResult<SValue> {
let (zero, one, half) = (float(fb, 0.0)?, float(fb, 1.0)?, float(fb, 0.5)?);
let (codes, wide) = (float(fb, DEPTH_CODES)?, float(fb, DEPTH_CODES + 1.0)?);
let m = fb.glsl(GlslOp::FClamp, &[r, zero, one])?;
let p = fb.binary_no_contraction(BinOp::FMul, m, codes)?;
let k = fb.glsl(GlslOp::RoundEven, &[p])?;
let h = fb.binary_no_contraction(BinOp::FMul, m, wide)?;
let above = fb.binary_no_contraction(BinOp::FAdd, k, half)?;
let above = fb.binary_no_contraction(BinOp::FSub, h, above)?;
let up = fb.binary(BinOp::FOrdGreaterThan, above, m)?;
let below = fb.binary_no_contraction(BinOp::FSub, k, half)?;
let below = fb.binary_no_contraction(BinOp::FSub, h, below)?;
let down = fb.binary(BinOp::FOrdLessThan, below, m)?;
let next = fb.binary_no_contraction(BinOp::FAdd, k, one)?;
let previous = fb.binary_no_contraction(BinOp::FSub, k, one)?;
let k = fb.select(up, next, k)?;
let k = fb.select(down, previous, k)?;
let nan = fb.unary(UnOp::IsNan, r)?;
let code = fb.select(nan, r, k)?;
fb.select(normalized, code, r)
}
/// The key comparison orders `f32` value `v` by (an `i32`), and whether `v` is not a NaN (a
/// `bool`): `v`'s bits as a signed integer where its sign is clear, else its magnitude's bits
/// negated, so that `-0` and `+0` share a key and the keys of the other values order as the values
/// do, denormals included. No float operation reads `v` (module docs).
fn key(fb: &mut FunctionBuilder<'_>, v: SValue) -> BResult<(SValue, SValue)> {
let i32_ = fb.module().ty(SType::Int {
width: 32,
signed: true,
})?;
let int = |fb: &mut FunctionBuilder<'_>, x: u32| -> BResult<SValue> {
let c = scalar(fb, i32_, u64::from(x))?;
value(fb, c)
};
let (zero, magnitudes, infinity) = (int(fb, 0)?, int(fb, 0x7fff_ffff)?, int(fb, 0x7f80_0000)?);
let bits = fb.convert(ConvOp::Bitcast, v, i32_)?;
let magnitude = fb.binary(BinOp::BitwiseAnd, bits, magnitudes)?;
let negative = fb.binary(BinOp::SLessThan, bits, zero)?;
let negated = fb.unary(UnOp::SNegate, magnitude)?;
let key = fb.select(negative, negated, bits)?;
let ordered = fb.binary(BinOp::SLessThanEqual, magnitude, infinity)?;
Ok((key, ordered))
}
/// The value a comparison compares texel `x` (a fetched tap, the border's, or the made-up
/// corner) as: a float format's as fetched; where `normalized`, its code, `x · 65535` rounded to
/// nearest (exact: the fetch is the code over 65535 within far less than half a step).
fn compared_texel(fb: &mut FunctionBuilder<'_>, x: SValue, normalized: SValue) -> BResult<SValue> {
let codes = float(fb, DEPTH_CODES)?;
let c = fb.binary_no_contraction(BinOp::FMul, x, codes)?;
let c = fb.glsl(GlslOp::RoundEven, &[c])?;
fb.select(normalized, c, x)
}
@@ -1,714 +0,0 @@
//! Metal's linear filter of a cube texture, emulated by fetches.
//!
//! **The filter Metal applies** (Apple M4, macOS 27.0.1, and Apple M3 Max, macOS 26.7,
//! byte-identical, each run with and without Metal's validation layer; with their M3 twins). A
//! sample through a sampler with linear minification and magnification and no mip filter reads the
//! face of its direction's major axis (`face::metal_ties`'s ties) at Metal's position on each face
//! axis, `X = RN(RN(1 + sc * r) / 2 * n)` (`face::position`), quantized as in 2D: `q = floor(256
//! X + 1/2) - 128`, the base texel `i = q >> 8` and the fraction's 1/256 steps `k = q & 255`. The
//! four taps `(i, j)`, `(i + 1, j)`, `(i, j + 1)`, and `(i + 1, j + 1)` weigh `(256 - k)` and `k`
//! per axis, each tap `wx · wy` in units of `2^-16`; an axis's two taps are always two texels, so
//! no axis merges. A tap past one edge of the face reads the adjacent face's texel along that edge
//! (`face::define_fold`). A tap past both edges, at the cube's corner, reads a texel that depends
//! on the format: a 32-bit float or half-float format's is the texel at the corner of the face of
//! the `x` axis; an 8- or 16-bit normalized or 8-bit sRGB format's is made up from the corner
//! texels of the three faces there, `⌊(6 X + 5 Y + 5 Z + 8) / 16⌋` of their codes per channel (an
//! sRGB color channel's table steps, a signed format's least code read as the next one;
//! `bicubic::routines::Cube::corner`). The sum is the 2D sum's: a normalized format's terms
//! truncated onto its grid, a float format's Metal's linear accumulator. Metal reads the sampler's
//! address modes and border color as clamping (the probe's `cm` runs: every lane of 4x4 cubes reads
//! this rule under clamp-to-edge, repeat, mirrored repeat, zero, and a white border), but for
//! `repeat` on a face axis of a size that is not a power of two, which wraps a face coordinate of
//! exactly 1 to 0 (`face::FaceWrap`; our probe's linear samples of 3x3, 5x5, and 6x6
//! cubes), reads level 0 whatever a `level` or `bias` names (the probe's `clv`
//! run, a two-level cube), and clamps a cube array's index into the array as an unsigned integer,
//! so a negative index reads the last cube (its `cla` run).
//!
//! **The emulation** reads the slot's `TexelFormat` specialization as the 2D emulation does
//! (`linear`), and fetches the taps from the slot's 2D-array view of the cube's faces (its raw
//! view under its `SrgbTexture` variant), layer `6 c + face` of cube `c`: per tap the fold's
//! texel, and at the corner candidate the `y` and `z` faces' texels too, six fetches. The corner
//! routine replaces the tap past both edges where there is one, and the 2D routines sum the four
//! taps under the unmerged fractions.
//!
//! **Where it is exact.** Every `float` and `half` sample channel of every lane whose major
//! magnitude is 1: our probe's 21 runs (seven formats, an identity texture among them, on faces of
//! 2, 5, and 8 texels, 4,096 lanes each), our probe's 27 `cl` runs (nine formats on faces of 1, 3,
//! and 16 texels, 2,048 such lanes each) and its `clv` and `cla` runs, and our probe's `cm` runs.
//! Elsewhere Metal's texture unit takes an approximate reciprocal `r` of the major magnitude, which
//! the emulation takes correctly rounded (`PrecisionNote::CubeFaceReciprocal`): of the `cl` runs'
//! 6,144 lanes of `rgba32Float` with a scaled major, 5,957 are the emulation's, and each of the
//! other 187 is its rule under an `r` one or two ulps from `RN(1 / |m_a|)`, a position within about
//! `n * 2^-23` of a quantization step reading the next step. A direction with an infinite or NaN
//! component gives an unspecified footprint, whose fetches stay on the cube.
//!
//! **Gathers** (the probes, Apple M4 on macOS 27.0.1, each run with and without Metal's validation
//! layer). A gather reads these four taps at the same position, in gather order `x` `(i, j + 1)`,
//! `y` `(i + 1, j + 1)`, `z` `(i + 1, j)` and `w` `(i, j)`, whatever the sampler's filters, mip
//! filter and anisotropy, from level 0, and wraps as a sample does. The tap past both edges is the
//! format's: the `x` face's corner texel for a 32-bit float, half-float or integer format, the
//! made-up texel for a normalized one (an sRGB color channel's a step `k`, gathered as
//! `RN(k / 4095)`). A `half` gather is the `float` texel rounded to nearest even. A depth cube's
//! taps are its depth texels, `depth32Float`'s corner the `x` face's and `depth16Unorm`'s made up;
//! a comparison compares each tap with the reference (`compare`). Outside those families the corner
//! is measured for the formats of a `metal::texel_format::CubeCorner` (the probe): the `x` face's
//! texel for `depth32Float_stencil8`'s depth (compared as `depth32Float`'s), the small floats,
//! BC6H, and ASTC HDR, and for the packed normalized and compressed formats the made-up texel of
//! each channel's codes on its decoded grid. [`CubeGather`] answers a cube gather through a
//! constexpr normalized sampler with the same fetches (`fetch_taps`): an integer result's taps as
//! fetched, a `float` or `half` result's corner by the corner routine under the slot's
//! `TexelFormat` specialization, an sRGB variant's from the raw view, each step decoded exactly
//! (`texture::srgb_raw_gather`), and a comparison's taps compared in the shader. Every lane of both
//! probes fits but one scaled lane per run, the reciprocal's residue above. A gather through a
//! runtime sampler slot is answered alike: its face axes wrap by the bound sampler's word's address
//! modes, and a comparison takes the word's compare function; an argument buffer's texture keeps
//! the device's gather.
use crate::air::abi::{CompareFunction, Coordinates, SamplerState};
use crate::air::intrinsics::{ImageDim, ImageShape};
use crate::error::Error;
use crate::lower::emit::EmitCx;
use crate::lower::select::{NoteClause, NoteOn, NoteTest, SelectCx};
use crate::lower::texture::{ImageRef, TexelConv, TexelForm};
use crate::metal::bicubic::BicubicTexels;
use crate::metal::texel_format::texel_format;
use crate::pipeline::sym::SamplerRef;
use crate::spirv::builder::constructs::{ArmEnd, ArmFn, Merged};
use crate::spirv::builder::FunctionBuilder;
use crate::spirv::error::BResult;
use crate::spirv::ids::{ConstId, Value as SValue};
use crate::spirv::ir::{
BinOp, ConvOp, GlslOp, ImageOperands, ImageQuery, MemAccess, Type as SType, UnOp,
};
use super::super::bicubic::routines::Routine;
use super::super::bicubic::{self, quantize, scalar, value, Bits, Tys};
use super::super::face::{self, FaceRoutines, FaceWrap, Wraps};
use super::super::{SampleOp, Sampling};
use super::compare::{TapCompare, WORD_REFERENCE_WORDS, WORD_TAP_WORDS};
use super::Comparison;
use super::{bool_value, Linear, LinearImage, LinearState};
/// The census words of a cube's emulation beside its face position's routines
/// ([`FaceRoutines::use_words`]) and a raw sample's tap conversions: the view's load and size
/// query, the cube's first layer, `face::position`, the two quantizations, the six folds and
/// fetches, the corner's test, candidate, and call, the four taps' selects, and the two sums'
/// calls and their select (`the_cube_estimate_bounds_its_emission`).
pub(super) const WORDS: u32 = 1024;
/// The texels a cube's emulation fetches: the four taps, and the corner's `y` and `z` faces'.
pub(super) const TAPS: u32 = 6;
/// The plan of a linear cube sample through sampler `s` of texture slot `texture` (module docs):
/// its face position's routines (`face::plan`, which records `PrecisionNote::CubeFaceReciprocal`),
/// the addressing of its face's `s` and `t` axes, which wraps a repeating one (`face::FaceWrap`),
/// and the 2D sums' and the cube's routines. Metal reads a cube's coordinate as a direction through
/// a pixel sampler too, as through a normalized one. A depth cube's comparison compares each tap
/// under `compare`.
pub(super) fn select(
cx: &mut SelectCx<'_>,
texture: u32,
s: &SamplerState,
compare: Option<Comparison>,
) -> Result<Option<Linear>, Error> {
let face_address = super::super::position::address;
let l = Linear {
image: LinearImage::Slot(texture),
state: LinearState::Constant {
address: vec![face_address(s.address_s), face_address(s.address_t)],
border: s.border_color,
pixel: false,
},
offset: None,
raw: false,
cube: Some(face::plan(cx)?),
compare,
fetch: None,
exact_only: false,
native: false,
};
cx.families
.sampler
.bicubic_routines
.extend(l.routines().iter().copied());
Ok(Some(l))
}
/// The emulation's texel (module docs) of the cube sample `s` by `l` (a runtime sampler's
/// through its `word`), along direction `p` (with Metal's ties broken), its face position's
/// routines `routines`, under the bound format's bits `bits` (the slot's `TexelFormat` value, which
/// a function reads as data), a `half` result when `half`. A depth cube's comparison (`l.compare`,
/// against reference `dref`) compares each tap's depth, the corner's by the format's rule
/// (`Depth32Float`'s the `x` face's texel, `Depth16Unorm`'s the made-up code), and sums the passes
/// as `r8Unorm` codes 0 and 255 through the exact routine: its value is the sum's first channel, a
/// scalar (3,072 directions, `less` and `greater_equal`, cubes and a cube array,
/// every lane).
pub(super) fn emulate(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
t: &Tys,
layer: Option<SValue>,
(l, word): (&Linear, Option<SValue>),
(routines, p): (FaceRoutines, SValue),
(bits, half, dref): (Bits, bool, Option<SValue>),
) -> BResult<SValue> {
let (Some(cube), Some(quad)) = (
cx.decl.families.sampler.linear_cube,
cx.decl.families.sampler.linear_quad,
) else {
return Err(cx.fail("a linear cube sample without its routines"));
};
let post = |cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, v: SValue| match l.raw {
true => crate::lower::texture::srgb_raw_tap(cx, fb, v),
false => Ok(v),
};
let wrap = match (&l.state, word) {
(LinearState::Constant { address, .. }, _) => Wraps::Axes(FaceWrap::of(
address.first().copied(),
address.get(1).copied(),
)),
(LinearState::Slot { .. } | LinearState::Argument { .. }, Some(word)) => Wraps::Word(word),
(LinearState::Slot { .. } | LinearState::Argument { .. }, None) => {
return Err(cx.fail("a runtime sampler's cube sample without its word"))
}
};
let Some(texture) = l.image.slot() else {
return Err(cx.fail("a heap texture's cube sample"));
};
let site = Site {
texture,
raw: l.raw,
routines,
wrap,
p,
};
let taps = fetch_taps(cx, fb, t, layer, &site, (true, &post))?;
let [x, y, z] = taps.corner_texels(cx)?;
let flags = bits.value(fb)?;
let flags = match l.raw {
true => {
let exact = scalar(fb, t.u32_, u64::from(BicubicTexels::EXACT))?;
let exact = value(fb, exact)?;
fb.binary(BinOp::BitwiseOr, flags, exact)?
}
false => flags,
};
let made = fb
.call(cube.corner, &[x, y, z, flags])?
.ok_or_else(bicubic::missing_routine)?;
let mut args = Vec::with_capacity(8);
for (tap, here) in taps.texels.into_iter().zip(taps.corner) {
args.push(fb.select(here, made, tap)?);
}
let h = bool_value(fb, t, half)?;
let compare = match (l.compare, dref) {
(Some(Comparison::Function(f)), Some(r)) => Some(TapCompare::new(cx, fb, t, f, (r, bits))?),
(None, None) => None,
(Some(Comparison::Word), _) => {
return Err(cx.fail("a linear cube comparison through a runtime sampler"))
}
_ => return Err(cx.fail("a linear cube comparison without its reference")),
};
if let Some(c) = compare {
for tap in args.iter_mut() {
let depth = fb.composite_extract(*tap, &[0])?;
let pass = c.pass(fb, depth)?;
*tap = fb.composite_construct(t.vec4, &[pass; 4])?;
}
let pass = texel_format(super::compare::PASS_FORMAT).0;
let pass = scalar(fb, t.u32_, u64::from(pass))?;
args.extend([taps.kx, taps.ky, value(fb, pass)?, h]);
let e = fb
.call(quad.exact, &args)?
.ok_or_else(bicubic::missing_routine)?;
return fb.composite_extract(e, &[0]);
}
args.extend([taps.kx, taps.ky, flags, h]);
if l.raw {
return fb
.call(quad.exact, &args)?
.ok_or_else(bicubic::missing_routine);
}
// One sum runs, by a branch on the class, where both ran and a select took one (the linear
// sum's rule, `linear::sum`).
let is_exact = bits.test(fb, t, BicubicTexels::EXACT)?;
let float_args = args.clone();
let exact_arm: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, _| {
let e = fb
.call(quad.exact, &args)?
.ok_or_else(bicubic::missing_routine)?;
Ok(ArmEnd::FallThrough(vec![e]))
});
let float_arm: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, _| {
let f = fb
.call(quad.float, &float_args)?
.ok_or_else(bicubic::missing_routine)?;
Ok(ArmEnd::FallThrough(vec![f]))
});
let Merged(merged) = fb.if_(cx, is_exact, exact_arm, Some(float_arm))?;
match merged[..] {
[x] => Ok(x),
_ => Err(cx.fail("a linear cube sum's branch without its texel")),
}
}
/// Where a cube footprint's taps are fetched: texture slot `texture`'s view of its faces (its raw
/// view where `raw`), at Metal's position along direction `p` (its ties broken) by the face
/// position's routines `routines`, wrapped on the face axes `wrap` names.
struct Site {
texture: u32,
raw: bool,
routines: FaceRoutines,
wrap: Wraps,
p: SValue,
}
/// A cube footprint's fetched texels (module docs).
struct Taps {
/// The taps `(i, j)`, `(i + 1, j)`, `(i, j + 1)`, and `(i + 1, j + 1)`, each its fold's
/// texel: past both edges, the `x` face's corner texel.
texels: [SValue; 4],
/// Per tap whether it is the one past both edges (a `bool`).
corner: [SValue; 4],
/// The `y` and `z` faces' texels at the cube's corner the tap past both edges would read,
/// where fetched.
yz: Option<[SValue; 2]>,
/// The candidate's own tap, the `x` face's corner texel.
x: SValue,
/// The fractions' 1/256 steps on the face's `s` and `t` axes.
kx: SValue,
ky: SValue,
}
impl Taps {
/// The three faces' texels at the cube's corner: `x`, `y`, and `z`.
fn corner_texels(&self, cx: &mut EmitCx<'_>) -> BResult<[SValue; 3]> {
match self.yz {
Some([y, z]) => Ok([self.x, y, z]),
None => Err(cx.fail("a cube corner's texels not fetched")),
}
}
}
/// The four taps of the cube footprint of a sampling of cube array layer `layer` (`None`: a cube)
/// at `site` (module docs), each fetched texel passed through `post`, and where `faces` the `y`
/// and `z` faces' corner texels beside them.
fn fetch_taps(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
t: &Tys,
layer: Option<SValue>,
site: &Site,
(faces, post): (bool, &Post<'_>),
) -> BResult<Taps> {
let view = match site.raw {
true => cx.decl.families.texture.raw.get(&site.texture).copied(),
false => cx
.decl
.families
.texture
.images
.get(&site.texture)
.map(|(g, _)| *g),
};
let Some(view) = view else {
return Err(cx.fail(format!(
"texture slot {} has no view of its cube's faces",
site.texture
)));
};
let Some(cube) = cx.decl.families.sampler.linear_cube else {
return Err(cx.fail("a cube footprint without its fold"));
};
let routines = site.routines.declared();
let i32_ = fb.module().ty(SType::Int {
width: 32,
signed: true,
})?;
let u = |fb: &mut FunctionBuilder<'_>, v: u32| -> BResult<SValue> {
let c = scalar(fb, t.u32_, u64::from(v))?;
value(fb, c)
};
let zero = u(fb, 0)?;
let ptr = fb.module().global_value(view)?;
let img = fb.load(ptr, MemAccess::default())?;
let size = fb.query(ImageQuery::SizeLod(zero), img)?;
let n = fb.composite_extract(size, &[0])?;
// The cube's first layer: its index clamped into the array, as Metal clamps it, times 6.
let six = u(fb, 6)?;
let base = match layer {
Some(index) => {
let layers = fb.composite_extract(size, &[2])?;
let cubes = fb.binary(BinOp::UDiv, layers, six)?;
let one = u(fb, 1)?;
let last = fb.binary(BinOp::ISub, cubes, one)?;
let c = fb.glsl(GlslOp::UMin, &[index, last])?;
fb.binary(BinOp::IMul, c, six)?
}
None => zero,
};
let at = face::position(fb, site.p, n, (routines, site.wrap))?;
let (i, kx) = quantize(fb, t, at.s, None)?;
let (j, ky) = quantize(fb, t, at.t, None)?;
let ni = fb.convert(ConvOp::Bitcast, n, i32_)?;
let one = {
let c = scalar(fb, i32_, 1)?;
value(fb, c)?
};
let i1 = fb.binary(BinOp::IAdd, i, one)?;
let j1 = fb.binary(BinOp::IAdd, j, one)?;
let lod = ImageOperands {
lod: Some(zero),
..ImageOperands::default()
};
let fetch = |cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
(ti, tj): (SValue, SValue),
pick: u32|
-> BResult<SValue> {
let pick = u(fb, pick)?;
let site = fb
.call(cube.fold, &[at.face, ti, tj, ni, pick, base])?
.ok_or_else(bicubic::missing_routine)?;
let texel = fb.fetch(img, site, &lod)?;
post(cx, fb, texel)
};
let t00 = fetch(cx, fb, (i, j), 0)?;
let t10 = fetch(cx, fb, (i1, j), 0)?;
let t01 = fetch(cx, fb, (i, j1), 0)?;
let t11 = fetch(cx, fb, (i1, j1), 0)?;
// The tap that may lie past both edges: per axis the tap past its edge, `i` where it is
// negative and `i + 1` otherwise (the base tap lies in `[-1, n - 1]`).
let zero_i = {
let c = scalar(fb, i32_, 0)?;
value(fb, c)?
};
let low_i = fb.binary(BinOp::SLessThan, i, zero_i)?;
let low_j = fb.binary(BinOp::SLessThan, j, zero_i)?;
let past = |fb: &mut FunctionBuilder<'_>, low: SValue, next: SValue| -> BResult<SValue> {
let high = fb.binary(BinOp::SGreaterThanEqual, next, ni)?;
fb.binary(BinOp::LogicalOr, low, high)
};
let past_i = past(fb, low_i, i1)?;
let past_j = past(fb, low_j, j1)?;
let corner = fb.binary(BinOp::LogicalAnd, past_i, past_j)?;
let yz = match faces {
true => {
let ci = fb.select(low_i, i, i1)?;
let cj = fb.select(low_j, j, j1)?;
Some([fetch(cx, fb, (ci, cj), 1)?, fetch(cx, fb, (ci, cj), 2)?])
}
false => None,
};
// The candidate's own tap is its `x` face's texel.
let row_j = fb.select(low_i, t00, t10)?;
let row_j1 = fb.select(low_i, t01, t11)?;
let x = fb.select(low_j, row_j, row_j1)?;
let high_i = fb.unary(UnOp::LogicalNot, low_i)?;
let high_j = fb.unary(UnOp::LogicalNot, low_j)?;
let mut here = Vec::with_capacity(4);
for (on_i, on_j) in [
(low_i, low_j),
(high_i, low_j),
(low_i, high_j),
(high_i, high_j),
] {
let tap = fb.binary(BinOp::LogicalAnd, on_i, on_j)?;
here.push(fb.binary(BinOp::LogicalAnd, corner, tap)?);
}
let [c00, c10, c01, c11] = here[..] else {
return Err(cx.fail("a cube footprint without its four taps"));
};
Ok(Taps {
texels: [t00, t10, t01, t11],
corner: [c00, c10, c01, c11],
yz,
x,
kx,
ky,
})
}
/// How a fetched texel becomes a tap: a raw sample's sRGB conversion, or the texel as fetched.
type Post<'a> = dyn Fn(&mut EmitCx<'_>, &mut FunctionBuilder<'_>, SValue) -> BResult<SValue> + 'a;
// ---- Gathers ----------------------------------------------------------------------------------
/// A gather of a cube or cube array that Metal's footprint, emulated by fetches, answers (module
/// docs): the four taps of the linear filter at Metal's position, in gather order, fetched from the
/// slot's view of its faces.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct CubeGather {
/// The texture slot gathered, whose faces are fetched and whose `TexelFormat` specialization
/// states a `float` or `half` result's corner rule.
pub texture: u32,
/// The gather reads an 8-bit sRGB texture's raw codes, its slot in the `SrgbTexture` variant:
/// each tap Metal's table step, the corner a made-up step.
pub raw: bool,
/// The face position's routines.
pub face: FaceRoutines,
/// The face axes the sampler repeats: a constexpr sampler's, or a runtime sampler's by its
/// word.
pub wrap: GatherWrap,
/// An integer result: every tap a texel, the corner's the `x` face's, whatever the format.
pub integer: bool,
/// A comparison gather of a depth texture: its sampler's compare function (a runtime
/// sampler's by its word), under which each tap's texel (the corner's by the format's rule)
/// is compared with the reference, `1` where it passes and `0` elsewhere.
pub compare: Option<Comparison>,
}
/// The face axes a cube gather's sampler repeats (`face::FaceWrap`): a constexpr sampler's, or a
/// runtime sampler's, whose word's `s` and `t` address modes the function reads.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum GatherWrap {
Axes(FaceWrap),
Word,
}
impl CubeGather {
/// Where the gather leaves its footprint to the device
/// (`PrecisionNote::DeviceGatherFootprint`): a `float` or `half` result's on a slot bound in a
/// format whose class states neither a measured family nor a corner rule (`linear::gather`'s
/// device arm). An integer result and a raw gather fetch every tap, with no device arm.
pub(crate) fn footprint_when(&self) -> Vec<NoteClause> {
if self.integer || self.raw {
return Vec::new();
}
vec![[NoteTest::equal(
NoteOn::Texel(self.texture),
BicubicTexels::EXACT
| BicubicTexels::LINEAR
| BicubicTexels::HALF
| crate::metal::texel_format::TexelFormat::CORNER_MASK,
0,
)]
.into()]
}
/// The census words beyond the device's gather: the footprint ([`GATHER_WORDS`]), its face
/// position's routine uses and wrap, a raw gather's corner conversions and decode, and a
/// comparison's ([`COMPARE_WORDS`]).
pub(in crate::lower::sampler) fn words(&self) -> u32 {
let raw = match self.raw {
true => 3 * crate::lower::texture::SRGB_TAP_WORDS + RAW_CORNER_WORDS,
false => 0,
};
let compare = match self.compare {
Some(Comparison::Function(_)) => COMPARE_WORDS,
Some(Comparison::Word) => COMPARE_WORDS + WORD_REFERENCE_WORDS + 4 * WORD_TAP_WORDS,
None => 0,
};
let wrap = match self.wrap {
GatherWrap::Axes(w) => w.words(),
GatherWrap::Word => face::WORD_WRAP_WORDS,
};
GATHER_WORDS + self.face.use_words() + wrap + raw + compare
}
}
/// The census words of a cube gather's footprint beside its face position's routines: the view's
/// load and size query, the cube's first layer, `face::position`, the two quantizations, the six
/// folds and fetches, the corner's test, candidate, and call, the four channels' extractions and
/// selects, the result's assembly, and the format's branch
/// (`the_cube_gather_estimate_bounds_its_emission`).
const GATHER_WORDS: u32 = 1024;
/// A raw gather's words for its corner's step: its extraction, scaling, rounding, conversion,
/// splat, and the four lanes' selects.
const RAW_CORNER_WORDS: u32 = 96;
/// A comparison gather's words: its reference's operand, the constants, the reference's code, and
/// per tap the texel's code, the comparison, and its select (`compare`).
const COMPARE_WORDS: u32 = 256;
/// The plan of gather `op` of `image` (shape `shape`) through the static sampler `stat`, with
/// texel form `form` (`observed`: the function observes its residency), where the emulation reaches
/// it (module docs): a gather of a cube or cube array slot through a constexpr sampler (with
/// normalized or pixel coordinates, which a cube reads alike) or a runtime sampler slot
/// (whose word's address modes wrap the face axes and whose compare function a comparison takes),
/// whose residency is not observed, on a device without `VkProperty::MetalSampler` (where Metal's
/// own sampler gathers): a color one with a `float`, `half`, or integer result, a depth one, and a
/// depth one's comparison under its sampler's compare function. It records
/// `PrecisionNote::CubeFaceReciprocal` (`face::plan`); a `float` or `half` result's
/// `PrecisionNote::DeviceGatherFootprint`, where its format's corner rule is not measured (its
/// gather keeps the device's footprint), is the caller's once it knows whether the gather reads raw
/// codes (`CubeGather::footprint_when`). Any other gather (an argument buffer's texture's among
/// them) is `None`.
pub(in crate::lower::sampler) fn select_gather(
cx: &mut SelectCx<'_>,
op: &SampleOp,
form: Option<TexelForm>,
(stat, image, shape): (Option<(SamplerRef, Coordinates)>, ImageRef, ImageShape),
observed: bool,
) -> Result<Option<CubeGather>, Error> {
let SampleOp::Gather { dref, .. } = op else {
return Ok(None);
};
// Metal compares a depth texture's texels only.
if shape.dim != ImageDim::Cube || shape.ms || observed || (dref.is_some() && !shape.depth) {
return Ok(None);
}
// A pixel sampler's cube coordinate is a direction too.
let (Some((sampler, _)), ImageRef::Slot(texture)) = (stat, image) else {
return Ok(None);
};
let integer = match form.map(|f| f.conv) {
Some(TexelConv::F32 | TexelConv::F16) => false,
Some(TexelConv::I32 | TexelConv::I16 { .. }) => true,
_ => return Ok(None),
};
if cx.profile.device_samples() {
cx.families.sampler.device_sampling = true;
return Ok(None);
}
let (wrap, compare) = match sampler {
SamplerRef::Constexpr(words) => {
let s = super::super::state_of(words)?;
// The frontend encodes an unspecified comparison as `never` and writes no `None`.
let compare = match (dref, s.compare) {
(None, _) => None,
(Some(_), CompareFunction::None) => return Ok(None),
(Some(_), f) => Some(Comparison::Function(f)),
};
let face_address = super::super::position::address;
let wrap = FaceWrap::of(
Some(face_address(s.address_s)),
Some(face_address(s.address_t)),
);
(GatherWrap::Axes(wrap), compare)
}
// The function reads the word's `s` and `t` address modes, and a comparison its compare
// function.
SamplerRef::Slot(n) => {
let Some(slot) = cx.families.sampler.slots.get_mut(&n) else {
return Err(cx.invariant("an unplanned sampler slot"));
};
slot.faces = true;
slot.compared |= dref.is_some();
(GatherWrap::Word, dref.map(|_| Comparison::Word))
}
};
let g = CubeGather {
texture,
raw: false,
face: face::plan(cx)?,
wrap,
integer,
compare,
};
cx.families.sampler.bicubic_routines.insert(Routine::Cube);
Ok(Some(g))
}
/// The gathered texel of cube gather `s` by `g` of channel `component` (module docs), along
/// direction `p` (its ties broken), its face position's routines `routines`: the four taps'
/// channel in gather order, `x` `(i, j + 1)`, `y` `(i + 1, j + 1)`, `z` `(i + 1, j)`, and `w`
/// `(i, j)`. An integer result's taps are the fetched texels (past both edges the `x` face's).
/// A `float` or `half` result's tap past both edges is the corner routine's under the slot's
/// `TexelFormat` specialization `spec`: a normalized format's made-up texel, a float format's `x`
/// face's, a `CubeCorner`'s by its field. The value is the view's texel as a device gather returns
/// it (a `vec4` of its sampled type), but for a raw gather, whose value is the held texel of
/// `form`: each tap's Metal decode (`texture::srgb_raw_texel`'s), and the corner's made-up step
/// over 4095 (alpha's code over 255); and for a comparison, whose value is per tap `1` where
/// reference `dref` passes `g.compare` against the tap's texel and `0` elsewhere (`TapCompare`).
pub(super) fn gather(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
t: &Tys,
s: &Sampling,
g: &CubeGather,
(p, component, dref): (SValue, u32, Option<SValue>),
spec: Option<ConstId>,
) -> BResult<SValue> {
// A runtime sampler's word (its slot's `SamplerState` specialization), where its address modes
// wrap the face axes or its compare function compares.
let word = match (g.wrap, g.compare) {
(GatherWrap::Word, _) | (_, Some(Comparison::Word)) => {
match super::super::emit::word_pixel(s) {
Some(pixel) => Some(super::super::emit::sampler_word(cx, fb, pixel)?),
None => return Err(cx.fail("a runtime sampler's cube gather without its word")),
}
}
_ => None,
};
let wrap = match (g.wrap, word) {
(GatherWrap::Axes(w), _) => Wraps::Axes(w),
(GatherWrap::Word, Some(w)) => Wraps::Word(w),
(GatherWrap::Word, None) => {
return Err(cx.fail("a runtime sampler's cube gather without its word"))
}
};
let site = Site {
texture: g.texture,
raw: g.raw,
routines: g.face,
wrap,
p,
};
let layer = match s.layer {
Some(l) => Some(cx.operand(fb, l)?),
None => None,
};
let taps = fetch_taps(cx, fb, t, layer, &site, (spec.is_some(), &|_, _, v| Ok(v)))?;
// The taps in gather order.
let order = [
taps.texels[2],
taps.texels[3],
taps.texels[1],
taps.texels[0],
];
let corner = [
taps.corner[2],
taps.corner[3],
taps.corner[1],
taps.corner[0],
];
let mut lanes = Vec::with_capacity(4);
for tap in order {
lanes.push(fb.composite_extract(tap, &[component])?);
}
let fetched = fb.value_ty(order[0])?;
let Some(spec) = spec else {
return fb.composite_construct(fetched, &lanes);
};
let Some(cube) = cx.decl.families.sampler.linear_cube else {
return Err(cx.fail("a cube gather without its corner routine"));
};
let [x, y, z] = taps.corner_texels(cx)?;
let flags = Bits::Spec(spec).value(fb)?;
let (x, y, z, flags) = match g.raw {
true => {
let tap = crate::lower::texture::srgb_raw_tap;
let exact = scalar(fb, t.u32_, u64::from(BicubicTexels::EXACT))?;
let exact = value(fb, exact)?;
let flags = fb.binary(BinOp::BitwiseOr, flags, exact)?;
(tap(cx, fb, x)?, tap(cx, fb, y)?, tap(cx, fb, z)?, flags)
}
false => (x, y, z, flags),
};
let made = fb
.call(cube.corner, &[x, y, z, flags])?
.ok_or_else(bicubic::missing_routine)?;
let made = fb.composite_extract(made, &[component])?;
if !g.raw {
for (lane, here) in lanes.iter_mut().zip(corner) {
*lane = fb.select(here, made, *lane)?;
}
if let Some(c) = g.compare {
let Some(r) = dref else {
return Err(cx.fail("a comparison cube gather without its reference"));
};
let compare = TapCompare::of(cx, fb, t, (c, word), (r, Bits::Spec(spec)))?;
for lane in lanes.iter_mut() {
*lane = compare.pass(fb, *lane)?;
}
}
return fb.composite_construct(fetched, &lanes);
}
let Some(form) = s.texel else {
return Err(cx.fail("a raw cube gather without its texel form"));
};
let codes = fb.composite_construct(fetched, &lanes)?;
crate::lower::texture::srgb_raw_gather(cx, fb, form, (codes, component), (made, corner))
}
+92 -354
View File
@@ -67,15 +67,16 @@
//! **Level of detail**. In a fragment function an implicit-LOD sample (with its bias) and
//! `calculate_*_lod` use the fragment's implicit derivatives and are tangled. Metal reads a bias as
//! `B = clamp(floor(half_rne(bias) * 64) / 64, -32, 31.984375)` and applies it whole, where Vulkan
//! clamps a `Bias` operand to `maxSamplerLodBias`. Through Metal's own sampler (MoltenVK) the
//! `Bias` operand is the bias as given, which Metal reads so. Elsewhere the shader forms `B`
//! (`emit::metal_bias`): the `Bias` operand within the limit, and a bias that may reach past it
//! also samples with the derivatives scaled by `2^B` ([`BiasReach`], `bias_gradients`). Through an
//! clamps a `Bias` operand to `maxSamplerLodBias`. Through a sampler without a bias of its own the
//! `Bias` operand is the bias as given, which Metal's own sampler (MoltenVK) reads as Metal does and
//! another device's sampler reads its own way. Through a constexpr sampler with a bias of its own
//! the shader forms `B` (`emit::metal_bias`): the `Bias` operand within the limit, and a bias that
//! may reach past it also samples with the derivatives scaled by `2^B` ([`BiasReach`],
//! `bias_gradients`). Through an
//! anisotropic sampler of a 2D texture Metal's `B` shifts the footprint's minor axis alone, which
//! the axis gradients give (`emit::axis_gradients`): a constexpr sampler's always, a runtime or
//! argument buffer's sampler's where its word states anisotropy, chosen per invocation. A sample
//! under a linear emulation's or a fetch's branch takes the same route in its device arm
//! (`emit::device_access`). Outside one, Metal's sample without a level or gradients reads the
//! argument buffer's sampler's where its word states anisotropy, chosen per invocation. Outside a
//! fragment function, Metal's sample without a level or gradients reads the
//! default level 0, shifted by its bias and bounded below by its `min_lod_clamp`: an explicit level
//! ([`Lod::Base`]), and `calculate_*_lod` is undefined in Metal (`NotRepresentable`). Gradients,
//! explicit levels, and gathers (which read the base level) are not tangled.
@@ -117,43 +118,24 @@
//! ([`bicubic`]), whose treatment of the bound format is the texture slot's `BicubicTexels`
//! specialization; a gather through one is an ordinary gather.
//!
//! **Linear filtering**. On a device that does not sample through Metal's own sampler, a linear
//! sample with a `half` or `float` result also takes Metal's filter emulated by fetches
//! ([`linear`]) beside the device's sample, selected on the slot's `TexelFormat` specialization; a
//! cube's reads its taps from the slot's 2D-array view of its faces at Metal's face position, and
//! records `PrecisionNote::CubeFaceReciprocal`. Where the emulation does not reach a sample, the
//! device filters. Every filtered sample there records `PrecisionNote::HalfSampleFilter` or
//! `PrecisionNote::FloatSampleFilter` by its result type. On a device that does
//! (`VkProperty::MetalSampler`), the device filters every sample, and a module with a filtered
//! sample of either result type requires the property.
//!
//! **Positions and snapped coordinates**. Every footprint Metal's rule decides (the emulated
//! filters, an observed footprint) reads Metal's position ([`position`]): the coordinate wrapped
//! into one period first on a repeating or mirrored axis, then scaled with ties away from zero. On
//! a device without `VkProperty::MetalSampler`, a gather through a constexpr normalized sampler of
//! a 2D texture or array, and a nearest sample through one with a repeating or mirrored axis that
//! reads the base level, hand the device a coordinate snapped onto the texels Metal reads, and a
//! cube gather through such a sampler or a runtime sampler slot (a depth cube's comparison gather
//! included) fetches Metal's four taps ([`linear::CubeGather`]). A gather of a 2D texture or array
//! through a runtime or argument buffer's sampler snaps behind the sampler's word
//! (`position::SnapKind::WordGather`): onto Metal's block at Metal's position by each axis's mode
//! the word states (a `MirrorClampToEdge` axis's a clamping axis's position, whose taps the device
//! mirrors once and clamps as Metal does). Every other gather, and such a runtime gather, records
//! `PrecisionNote::DeviceGatherFootprint`. Such a nearest sample of a cube hands the device a
//! direction onto the centre of the texel Metal's position names with
//! Metal's reciprocal, whose model misses Apple's texture unit's on a few majors
//! (`face::snapped`, `PrecisionNote::CubeFaceReciprocal`). On a device with the property, a module
//! with any of them requires it.
//! **The device's sampler**. Every other sample, gather and comparison of a format the device
//! samples is the device's: Metal's own on a device that samples through Metal's own sampler
//! (`VkProperty::MetalSampler`, MoltenVK), and the device's own elsewhere
//! (`VkProperty::DeviceSampling`, recorded as `PrecisionNote::DeviceSampling`); the module
//! requires the property. A cube's direction takes Metal's face at a tie (`face::metal_ties`).
//! Every footprint Metal's rule decides in the shader (the emulated filters the device has no form
//! for, a pixel sampler's snapped coordinate) reads Metal's position ([`position`]): the coordinate
//! wrapped into one period first on a repeating or mirrored axis, then scaled with ties away from
//! zero.
//!
//! **Pixel coordinates**. Through a pixel sampler Metal's position is the coordinate as given,
//! which the device's sampler, reading the coordinate over the level's size, does not reproduce. On
//! every device, the property's included, a constexpr pixel sampler's nearest sample reads its
//! texel's centre, its gather of a 2D texture or array snaps from the coordinate as given, and its
//! linear sample is emulated from the coordinate as given or, on a device with the property,
//! snapped onto the centre of its footprint cell, so Metal's own filter reads Metal's footprint. A
//! runtime or argument buffer's sampler's gather of a 2D texture or array snaps from the coordinate
//! as given where its word states pixel coordinates, on every device, and on a device with the
//! property its sample snaps onto its footprint cell where its word states a linear pixel sampler
//! every device a constexpr pixel sampler's nearest sample reads its texel's centre, its gather of
//! a 2D texture or array snaps from the coordinate as given, and its linear sample snaps onto the
//! centre of its footprint cell, so the device's filter reads Metal's footprint. A runtime or
//! argument buffer's sampler's gather of a 2D texture or array snaps from the coordinate as given
//! where its word states pixel coordinates (`position::SnapKind::WordGather`), and its sample snaps
//! onto its footprint cell where its word states a linear pixel sampler
//! (`position::SnapKind::WordCell`). Metal reads a cube's coordinate as a direction through a pixel
//! sampler too, so a cube's pixel sampler is a normalized one here.
//!
@@ -163,7 +145,6 @@
pub mod anisotropic;
pub mod bicubic;
pub mod compared;
mod constexpr;
mod emit;
pub mod extended;
@@ -174,7 +155,6 @@ pub mod heap_raw;
pub mod in_place;
pub mod level;
pub mod linear;
mod native;
pub mod position;
pub mod routine;
mod select;
@@ -319,12 +299,12 @@ pub enum Source {
/// axis: Metal's level is `max(log2 minor + B, log2 major - log2 maxAnisotropy)`, which neither the
/// `Bias` operand nor `2^B` derivatives give, but the axis gradients do (`emit::axis_gradients`).
/// Every route but `Metal`'s takes `B` from the module and the device's level arithmetic,
/// `PrecisionNote::GradFromBias` where gradients carry it and `PrecisionNote::DeviceSampleLevel`
/// where the `Bias` operand does (`level::device_when`).
/// `PrecisionNote::GradFromBias` where gradients carry it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BiasReach {
/// The device samples through Metal's own sampler (`VkProperty::MetalSampler`, MoltenVK),
/// which reads the `Bias` operand as Metal reads a bias: the operand as given.
/// A sampler without a bias of its own: the `Bias` operand as given, which Metal's own sampler
/// (`VkProperty::MetalSampler`, MoltenVK) reads as Metal reads a bias, and another device's
/// sampler its own way.
Metal,
/// No bias, or a constant whose `B`, with the sampler's bias, is within the limit, through an
/// isotropic constexpr sampler: the `Bias` operand `B` alone.
@@ -334,20 +314,15 @@ pub enum BiasReach {
Beyond,
/// Through an anisotropic constexpr sampler of a 2D plane: the axis gradients alone.
Axes,
/// Decided per invocation: the `Bias` operand `B` where `|B + sampler| <= maxSamplerLodBias`
/// and the sampler is isotropic, the derivatives scaled by `2^B` past the limit, and where
/// `word`, the axis gradients through a sampler whose word states `SamplerWord::ANISOTROPIC`
/// (all from the sample's own position, so the implicit sample and the derivatives stay in
/// the fragment's uniform control flow). A dynamic bias, or a runtime or argument buffer's
/// sampler of a 2D plane.
/// Decided per invocation: the `Bias` operand `B` where `|B + sampler| <= maxSamplerLodBias`,
/// and the derivatives scaled by `2^B` past the limit (both from the sample's own position, so
/// the implicit sample and the derivatives stay in the fragment's uniform control flow). A
/// dynamic bias through a constexpr sampler with a bias of its own.
Either {
/// The profile's `maxSamplerLodBias` (`f32` bits).
max_bias_bits: u32,
/// The sampler's own bias (`f32` bits): a constexpr sampler's `mipLodBias`, else 0.
/// The sampler's own bias (`f32` bits): the constexpr sampler's `mipLodBias`.
sampler_bias_bits: u32,
/// The sampler's word decides its anisotropy: a runtime or argument buffer's sampler of a
/// 2D plane.
word: bool,
},
}
@@ -623,9 +598,6 @@ pub struct Sampling {
/// Metal's footprint of an observed sample or gather where the rule decides it: its word is the
/// residency of exactly those texels, through the slot's sparse arm or tile map.
pub footprint: Option<footprint::Footprint>,
/// A linear sample that Metal's filter, emulated by fetches, answers where the slot is bound
/// in a measured format ([`linear`]); the device's sample answers otherwise.
pub linear: Option<linear::Linear>,
/// A gather or nearest sample whose plane coordinate is snapped onto the texels Metal reads
/// ([`position`]).
pub snap: Option<position::Snap>,
@@ -633,23 +605,10 @@ pub struct Sampling {
/// before anything reads it, as Metal's texture unit reads it, a bit per axis
/// ([`position::subnormal_flush`]).
pub flush_subnormals: u8,
/// A sample's level or kernel's bias handed to the device on Metal's grid, which makes the
/// device read Metal's levels with Metal's weights ([`level`]): by a constexpr sampler's state,
/// or by a runtime or argument buffer's sampler's word.
pub level: Option<level::LevelRule>,
/// A 2D depth comparison of one texel per tap that the shader makes of the texels the device
/// reads without comparison ([`compared`]).
pub compared: Option<compared::Compared>,
/// A plain gather or nearest sample whose texels the shader fetches where the slot is bound in
/// (or a heap texture's handle carries the class of) a 32-bit float format, whose denormal
/// texels a device's sample or gather may read as zero ([`fetched`]); the device's access
/// answers otherwise.
/// A `half` gather whose texels the shader fetches where the slot is bound in (or a heap
/// texture's handle carries the class of) a half-float format ([`fetched`]); the device's
/// gather answers otherwise.
pub fetched: Option<fetched::Plain>,
/// A cube gather, a depth cube's comparison gather included, that Metal's footprint,
/// emulated by fetches, answers ([`linear::CubeGather`]): always for an integer result or a raw
/// one, else where the slot is bound in a format whose corner rule is measured; the device's
/// gather otherwise.
pub cube_gather: Option<linear::CubeGather>,
/// It reads a cube by a direction, whose ties between major axes the device is handed broken
/// as Metal breaks them ([`face`]).
pub cube: bool,
@@ -665,24 +624,13 @@ pub struct Sampling {
/// [`SamplerWord::PIXEL_COORDINATES`] alone.
pub centre_word: u32,
/// Whether the access reads one texel of one level: its `half` texel's lanes for the class's
/// conversion, and whether a `float` one converts.
/// conversion.
pub one_texel: crate::lower::texture::OneTexel,
/// A `half` texel of the slot, or of the heap color texture, converts by the bound format's
/// class (`texture::half`): not a raw, bicubic or depth one's, nor where the sample's texel is
/// the device's (`texture::device_texels`: native device sampling, or
/// `TexelConversionPolicy::Device`), rounded exactly. The emission follows it, so a module
/// whose reads convert by the class (`TexelConversionPolicy::Exact`) leaves a natively
/// sampled texel the device's.
/// the device's (`texture::device_texels`: a device that does not sample through Metal's own
/// sampler), rounded exactly. The emission follows it.
pub half_texel: bool,
/// A `float` texel of the slot converts by the bound format's class (`float_texel`), where
/// [`one_texel`](Self::one_texel) holds.
pub float_texel: bool,
/// A [`centred`](Self::centred) sample through a runtime or argument buffer's sampler with a
/// texel offset, on a device without `VkProperty::MetalSampler`, which adds the offset to the
/// texel it reads before addressing it: the texel's centre moves back by the offset on an
/// axis whose word states `MirrorClampToEdge` and whose base level's size drops it, as Metal
/// drops it (`position::pixel_centre_by_word`).
pub centre_offset: bool,
/// Metal's value of the texels the access reads in a block of a sparse image that holds no
/// mapped tile.
pub unmapped: Unmapped,
@@ -700,8 +648,7 @@ pub struct Sampling {
/// swizzle names, and sets the lanes Metal reads as constants after it ([`sampling_value`]).
pub swizzle: bool,
/// A slot's access that places a texel offset by Metal's rule on an axis that may repeat or
/// mirror (a snapped gather or nearest sample, fetched texels, an emulated linear or bicubic
/// filter, a pixel sampler's centre): the rule reads the slot's `OffsetBaseAxes`
/// mirror (a bicubic filter's footprint): the rule reads the slot's `OffsetBaseAxes`
/// specialization's tests (`texture::OffsetBase`), which state where a view's parent's
/// base-level size, which Metal reads, is not a power of two where the bound view's is
/// (`position::offset_dropped`).
@@ -797,24 +744,20 @@ impl Sampling {
/// The shape the arms of a switch-at-use share where it emulates once (SEMANTICS 1012,
/// `sampler::shared_value`): this sampling with its texture slot and sampler taken out, where
/// it is an emulation on a combined binding whose residency the function does not observe: a
/// bicubic sample, a linear sample Metal's filter answers but a cube's, which fetches from its
/// own slot's faces, or a snapped gather or nearest sample, a runtime sampler's word snap only
/// beside its linear emulation. Arms of one shape differ only in the binding they read: each
/// emulation states its sampler's addressing in its own fields, and the device's access stays
/// in each arm.
/// bicubic sample, fetched texels, or a snapped gather or sample but a runtime sampler's word
/// snap. Arms of one shape differ only in the binding they read: each emulation states its
/// sampler's addressing in its own fields, and the device's access stays in each arm.
pub(crate) fn shared_shape(&self) -> Option<Sampling> {
let Source::Combined(key) = self.source else {
return None;
};
// A comparison the shader makes compares in each arm's own access. A plain fetch of the
// base level fetches its taps on the named candidate's facts once; one of another level
// A plain fetch of the base level fetches its taps on the named candidate's facts once; one of another level
// reads in each arm's own branch, its level clamped into the arm's own levels. A texture of
// another class's words are handed back as declared in each arm's own access. A swizzled
// slot's sampling swizzles under its own slot's swizzle; an offset placed by a slot's
// `OffsetBaseAxes` is placed by its own slot's.
if self.residency
|| self.footprint.is_some()
|| self.compared.is_some()
|| self.declared.is_some()
|| self.swizzle
|| self.offset_base
@@ -828,62 +771,40 @@ impl Sampling {
..key
});
if let Some(p) = &mut k.fetched {
if p.fetch.level != fetched::FetchLevel::Fixed(0) {
return None;
}
p.image = linear::LinearImage::Slot(0);
return Some(k);
}
match (&mut k.op, &mut k.linear, &k.snap) {
(SampleOp::Bicubic(b), None, None) => b.texture = 0,
// A cube's emulation reads its own slot's faces, so each arm keeps it. A runtime
// sampler's word snap of the device's sample rides along: the emulation's shape names
// the sampler slot whose word it reads.
(SampleOp::Sample { .. }, Some(l), snap)
if l.cube.is_none() && snap.as_ref().is_none_or(position::Snap::by_word) =>
{
l.image = linear::LinearImage::Slot(0);
l.fetch = l.fetch.map(|f| BindingKey {
texture: 0,
sampler: SamplerRef::Slot(0),
..f
});
}
match (&mut k.op, &k.snap) {
(SampleOp::Bicubic(b), None) => b.texture = 0,
// A runtime sampler's word snap alone is no emulation to share.
(SampleOp::Sample { .. } | SampleOp::Gather { .. }, None, Some(p)) if !p.by_word() => {}
(SampleOp::Sample { .. } | SampleOp::Gather { .. }, Some(p)) if !p.by_word() => {}
_ => return None,
}
Some(k)
}
/// The sampled images each arm of a switch-at-use that emulates once makes (SEMANTICS 1012):
/// one for the device's access, a linear sample's (none where it is raw through a constexpr
/// sampler, which the emulation alone answers) or a snapped access's, with a second where a
/// dynamic bias may pass the device's limit; none for a bicubic sample. The facts and the taps
/// read the image alone.
/// one for the device's access, a snapped access's, with a second where a dynamic bias may pass
/// the device's limit; none for a bicubic sample. The facts and the taps read the image alone.
pub(crate) fn shared_sampled_images(&self) -> u32 {
match (&self.op, &self.linear) {
(SampleOp::Bicubic(_), _) => 0,
(_, Some(l)) => u32::from(!l.raw || l.word_state()),
(
SampleOp::Sample {
lod:
Lod::Implicit {
reach: BiasReach::Either { .. },
..
},
..
},
None,
) => 2,
match &self.op {
SampleOp::Bicubic(_) => 0,
SampleOp::Sample {
lod:
Lod::Implicit {
reach: BiasReach::Either { .. },
..
},
..
} => 2,
_ => 1,
}
}
/// The estimated words each arm of a switch-at-use that emulates once adds (SEMANTICS 1012):
/// per dispatch its case, label, branch, and merge operands, and its binding's load, and in it
/// the reads of the candidate's own image: the facts' size query, an emulation's tap fetches, a
/// linear sample's device sample, and a snapped access with its texel's conversion.
/// the reads of the candidate's own image: the facts' size query, an emulation's tap fetches,
/// and a snapped access with its texel's conversion.
/// [`Sampling::words`] counts the emulation once.
pub(crate) fn shared_arm_words(&self) -> u32 {
// A dispatch's arm: its case, label, branch, and merge operands, the binding's loads,
@@ -892,11 +813,8 @@ impl Sampling {
// A read in an arm: the fetch or access with its operands, and its merge operands.
const READ: u32 = 16;
// The facts' merge operands of the lanes Metal reads as constants, eight lane tests, where
// a linear sample or a plain fetch takes them.
let lanes = match (
self.unmapped,
self.fetched.is_some() || self.linear.is_some(),
) {
// a plain fetch takes them.
let lanes = match (self.unmapped, self.fetched.is_some()) {
(Unmapped::Constants | Unmapped::Named, true) => 8 * 2,
_ => 0,
};
@@ -916,18 +834,14 @@ impl Sampling {
};
return facts + (ARM + taps * READ) + ARM + READ + half;
}
match (&self.op, &self.linear, &self.snap) {
(SampleOp::Bicubic(b), ..) => {
match (&self.op, &self.snap) {
(SampleOp::Bicubic(b), _) => {
// A 1D texture's one row of two taps, else each row of four and the half sum's
// row its loop reads.
let (rows, taps) = if b.address.len() == 1 { (2, 2) } else { (5, 4) };
facts + rows * (ARM + taps * READ)
}
(_, Some(l), _) => {
let taps = 1 << l.plane_axes();
facts + (ARM + taps * READ) + (ARM + READ)
}
(SampleOp::Sample { lod, .. }, None, Some(_)) => {
(SampleOp::Sample { lod, .. }, Some(_)) => {
let beyond = match lod {
Lod::Implicit {
reach: BiasReach::Either { .. },
@@ -942,30 +856,11 @@ impl Sampling {
}
/// The census name; a heap element's names its operation, one through an argument buffer's
/// sampler its operation too, its linear sample's emulation included, a slot's linear sample
/// that Metal's filter emulated by fetches answers is `sampler.linear`, a cube gather Metal's
/// footprint emulated by fetches answers `sampler.gather.cube` or, with comparison,
/// `sampler.gather_compare.cube`, and a texture slot's snapped gather or nearest sample is
/// `sampler.gather.snapped`, `sampler.gather_compare.snapped`, `sampler.nearest.snapped`, or a
/// cube's `sampler.cube.snapped`, and a pixel sampler's linear sample snapped onto its
/// footprint cell `sampler.linear.snapped`. A gather whose comparison the shader
/// makes is named as a comparison gather.
/// sampler its operation too, and a texture slot's snapped gather is `sampler.gather.snapped`
/// or `sampler.gather_compare.snapped`, and a pixel sampler's linear sample snapped onto its
/// footprint cell `sampler.linear.snapped`.
pub fn name(&self) -> &'static str {
let compares =
self.compared.is_some() || matches!(self.op, SampleOp::Gather { dref: Some(_), .. });
if self
.linear
.as_ref()
.is_some_and(|l| l.image.slot().is_some())
{
return "sampler.linear";
}
if let Some(g) = &self.cube_gather {
return match g.compare {
Some(_) => "sampler.gather_compare.cube",
None => "sampler.gather.cube",
};
}
let compares = matches!(self.op, SampleOp::Gather { dref: Some(_), .. });
if let Source::HeapSampler { .. } = self.source {
return match &self.op {
SampleOp::Sample { .. } => "sampler.argument_sampler.sample",
@@ -996,19 +891,10 @@ impl Sampling {
(position::SnapKind::Axes(position::AxisSnap::Gather), _) => {
Some("sampler.gather.snapped")
}
(position::SnapKind::Axes(position::AxisSnap::Nearest), _) => {
Some("sampler.nearest.snapped")
}
(position::SnapKind::Axes(position::AxisSnap::Cell), _) => {
Some("sampler.linear.snapped")
}
(position::SnapKind::Cube { .. }, _) => Some("sampler.cube.snapped"),
(
position::SnapKind::Word { .. }
| position::SnapKind::WordGather { .. }
| position::SnapKind::WordCell { .. },
_,
) => None,
(position::SnapKind::WordGather | position::SnapKind::WordCell { .. }, _) => None,
};
if let Some(name) = snapped {
return name;
@@ -1097,12 +983,7 @@ impl Sampling {
BiasReach::Within => 64 + METAL_BIAS_WORDS,
BiasReach::Beyond => 64 + METAL_BIAS_WORDS + BIAS_GRADIENT_WORDS,
BiasReach::Axes => 64 + METAL_BIAS_WORDS + AXIS_GRADIENT_WORDS,
BiasReach::Either { word: false, .. } => {
64 + METAL_BIAS_WORDS + BIAS_GRADIENT_WORDS + 96
}
BiasReach::Either { word: true, .. } => {
64 + METAL_BIAS_WORDS + BIAS_GRADIENT_WORDS + AXIS_GRADIENT_WORDS + 128
}
BiasReach::Either { .. } => 64 + METAL_BIAS_WORDS + BIAS_GRADIENT_WORDS + 96,
},
offset.as_ref(),
),
@@ -1152,15 +1033,6 @@ impl Sampling {
// raw decode; the bicubic routines round their `half` result themselves.
let half = match (&self.op, self.texel) {
(SampleOp::Bicubic(_), _) | (_, None) => 0,
// A raw linear sample's taps are in its emulation's words; a runtime sampler's device
// arm converts its texel as another linear sample's does.
_ if self
.linear
.as_ref()
.is_some_and(|l| l.raw && !l.word_state()) =>
{
0
}
_ if self.raw() => crate::lower::texture::SRGB_RAW_WORDS,
_ if self.srgb_codes => crate::lower::texture::SRGB_FILTERED_WORDS,
// A heap color texture's call reads the class its handle carries first.
@@ -1173,18 +1045,6 @@ impl Sampling {
};
crate::lower::texture::half::CALL_WORDS.max(f.read_words()) + class
}
// A heap color texture's `float` texel likewise, and its call.
(_, Some(f))
if self.float_texel
&& matches!(
self.source,
Source::Heap { .. } | Source::HeapSampler { .. }
) =>
{
crate::lower::texture::HEAP_CLASS_WORDS
+ crate::lower::texture::float_texel::CALL_WORDS
+ f.read_words()
}
(_, Some(f)) => f.read_words(),
};
// An argument buffer's sampler also fetches the texel the rule names: the size query, the
@@ -1202,25 +1062,6 @@ impl Sampling {
}
_ => 0,
};
// The emulation beside the device's sample, or gather, and a native class's snapped
// coordinate; a runtime sampler's raw emulation's device arm where its word reads one
// texel: the word's test and branch, the raw view's sampled image and sample, and the
// table's decode (`linear::emit`).
let one_texel = match &self.linear {
Some(l) if l.raw && l.word_state() && l.cube.is_none() && !self.srgb_codes => {
RAW_TEXEL_ARM_WORDS + crate::lower::texture::SRGB_RAW_WORDS
}
_ => 0,
};
let linear = one_texel
+ self
.linear
.as_ref()
.map_or(0, |l| l.words() + l.native_words())
+ self
.cube_gather
.as_ref()
.map_or(0, linear::CubeGather::words);
// The snapped coordinate, and the position of each axis of Metal's footprint of an observed
// sample or gather.
let snap = self.snap.as_ref().map_or(0, position::Snap::words)
@@ -1229,9 +1070,7 @@ impl Sampling {
.as_ref()
.filter(|_| offset.is_some())
.map_or(0, position::Snap::offset_words)
+ self.level.map_or(0, |_| level::LEVEL_WORDS)
+ self.compared.as_ref().map_or(0, |c| c.words(&self.op))
+ self.fetched.as_ref().map_or(0, |p| p.words(&self.op))
+ self.fetched.as_ref().map_or(0, |p| p.words())
+ match self.flush_subnormals {
0 => 0,
_ => position::FLUSH_WORDS,
@@ -1239,24 +1078,10 @@ impl Sampling {
let footprint = self
.footprint
.map_or(0, |fp| u32::from(fp.axes) * position::POSITION_WORDS);
// The slot's parent tests in Metal's offset rule, on each plane axis of each snap,
// footprint (a blended level's two) and pixel centre that places the offset.
let fetches = |f: &fetched::Fetch| match f.level {
fetched::FetchLevel::Blend(..) => 2,
_ => 1,
};
let places = u32::from(self.snap.is_some())
+ u32::from(self.linear.is_some())
+ self.fetched.as_ref().map_or(0, |p| fetches(&p.fetch))
+ self
.compared
.as_ref()
.and_then(|c| c.fetch.as_ref())
.map_or(0, fetches)
+ u32::from(matches!(self.op, SampleOp::Bicubic(_)))
+ u32::from(self.centre_offset);
// The slot's parent tests in Metal's offset rule, on each plane axis of the bicubic
// footprint that places the offset.
let parent = match self.offset_base {
true => places * u32::from(self.lanes) * position::PARENT_RULE_WORDS,
true => u32::from(self.lanes) * position::PARENT_RULE_WORDS,
false => 0,
};
// Metal's unmapped value: the lanes Metal reads as constants, and a named texel's
@@ -1266,14 +1091,12 @@ impl Sampling {
Unmapped::Constants => CONSTANT_LANES_WORDS,
Unmapped::Named => CONSTANT_LANES_WORDS + 64,
};
(base
+ wrap
base + wrap
+ heap
+ residency
+ half
+ fetch
+ word
+ linear
+ snap
+ footprint
+ parent
@@ -1281,22 +1104,7 @@ impl Sampling {
+ if self.cube { face::TIE_WORDS } else { 0 }
+ if self.pixel == Pixel::None { 0 } else { 48 }
+ if self.centred { PIXEL_CENTRE_WORDS } else { 0 }
+ if self.centre_offset {
u32::from(self.lanes) * position::PIXEL_OFFSET_WORDS
} else {
0
}
+ self.heap_raw.as_ref().map_or(0, heap_raw::HeapRaw::words))
// The code a sampling routine holds is the routine's, counted once in the module.
.saturating_sub(self.routed_words())
}
/// The census words of [`plain_words`](Self::plain_words) that the sampling routines this
/// sampling calls hold, less their calls (`routine::routed_words`): the module counts each
/// routine once (`sampler::routine_words`). A switch-at-use that emulates once adds them back
/// for its inline emulation.
pub(crate) fn routed_words(&self) -> u32 {
routine::routed_words(self)
+ self.heap_raw.as_ref().map_or(0, heap_raw::HeapRaw::words)
}
}
@@ -1304,12 +1112,6 @@ impl Sampling {
/// selects of each lane's source (`extended`'s).
const SWIZZLE_WORDS: u32 = extended::SWIZZLE_WORDS;
/// The estimated words of a runtime sampler's raw emulation's device arm where its word reads one
/// texel, but the table's decode: the word's filter test and mip field, the branch and its merge,
/// and the raw view's sampled image and sample (`linear::emit`,
/// `the_raw_estimate_bounds_its_emission`).
const RAW_TEXEL_ARM_WORDS: u32 = 64 + 64;
/// The estimated words of setting an access's lanes to the constants Metal reads
/// (`texture::constant_lanes`): per lane its extraction and two selections (the slot's tests are
/// specialization constants), the construction, and their constants, at most 8 words each.
@@ -1333,43 +1135,26 @@ pub struct RuntimeSlot {
/// ([`Sampling::centred`]): the function reads whether its word states a nearest pixel
/// sampler.
pub nearest: bool,
/// A linear sample's emulation reads it (`linear::LinearState::Slot`): the function reads its
/// An extended-range or heap raw texture's emulated filter reads it: the function reads its
/// word's filter, coordinates, address modes, and border color.
pub linear: bool,
/// A nearest sample snaps behind its word (`position::SnapKind::Word`): the function reads
/// whether its word reads the base level and its address modes.
pub snap: bool,
/// A nearest sample at a level the function knows snaps behind its word on the level it
/// reads (`position::SnapKind::Word`'s `leveled`): the function reads whether its word reads
/// one level and the levels its clamp leaves.
pub levels: bool,
/// A sample's level reads it (`level::LevelRule::Word`): the function reads whether its word
/// takes its clamp on Metal's grid, and its mip filter.
pub level: bool,
/// A comparison the shader makes reads it (`compared`): the function reads its word's compare
/// function.
pub compared: bool,
/// A `sample_compare` the shader makes where it reads one texel reads it
/// (`compared::runtime_sample`): the function reads its word's filter.
/// A sample whose texel the shader fetches where its word reads one texel reads it
/// (`fetched::word_reach`): the function reads its word's filter.
pub filters: bool,
/// A comparison whose texels the shader fetches by its word reads it
/// (`fetched::FetchAddress::Word`): the function reads its word's coordinates, its plane axes'
/// address modes, and its border color.
/// Texels the shader fetches by its word (`fetched::FetchAddress::Word`): the function reads
/// its word's coordinates, its plane axes' address modes, and its border color.
pub fetched: bool,
/// A 3D texture's texel the shader fetches by its word (`fetched::FetchAddress::Word`): the
/// function reads its word's `r` address mode too.
pub fetched_depth: bool,
/// A comparison the shader makes fetches its texel from the level its word reads
/// (`fetched::FetchLevel::Word`), or an extended-range sample reads its levels by its word
/// A fetched texel is read from the level its word reads (`fetched::FetchLevel::Word`), or an
/// extended-range sample reads its levels by its word
/// (`extended::Level::Word`): the function reads its word's mip filter and the levels its
/// clamp leaves.
pub fetch_levels: bool,
/// A cube's explicit gradients take their footprint by its word (`CubeFootprint::Word`): the
/// function reads whether its word is anisotropic.
pub anisotropy: bool,
/// A cube gather Metal's footprint answers by fetches wraps its face axes by its word
/// (`linear::CubeGather`): the function reads its word's `s` and `t` address modes.
pub faces: bool,
/// A 2D gather snaps behind its word (`position::SnapKind::WordGather`): the function reads its
/// word's coordinates and its `s` and `t` address modes.
pub gathers: bool,
@@ -1416,33 +1201,23 @@ impl RuntimeSlot {
cells: _,
min_level: _,
linear,
snap,
levels,
level,
compared,
filters,
fetched,
fetched_depth,
fetch_levels,
anisotropy,
faces,
gathers,
texels,
emulated,
} = *self;
![
linear,
snap,
levels,
level,
compared,
filters,
fetched,
fetched_depth,
fetch_levels,
anisotropy,
emulated,
faces,
gathers,
texels,
]
@@ -1461,18 +1236,6 @@ impl RuntimeSlot {
if self.linear {
fields |= SamplerWord::LINEAR_STATE;
}
if self.snap {
fields |= SamplerWord::NEAREST_SNAP;
}
if self.levels {
fields |= SamplerWord::LEVELED_SNAP;
}
if self.level {
fields |= SamplerWord::LEVEL_RULE;
}
if self.compared {
fields |= SamplerWord::COMPARE;
}
if self.filters {
fields |= SamplerWord::LINEAR_FILTER;
}
@@ -1494,9 +1257,6 @@ impl RuntimeSlot {
if self.emulated {
fields |= SamplerWord::ANISOTROPIC | SamplerWord::MIP_FILTER;
}
if self.faces {
fields |= SamplerWord::ADDRESS[0] | SamplerWord::ADDRESS[1];
}
if self.gathers {
fields |=
SamplerWord::PIXEL_COORDINATES | SamplerWord::ADDRESS[0] | SamplerWord::ADDRESS[1];
@@ -1557,29 +1317,22 @@ pub struct SamplerPlan {
pub heap_sampler_decls: BTreeMap<HeapSamplerKey, SamplerUse>,
/// The texture slots a bicubic sample reads, each with its `BicubicTexels` specialization.
pub bicubic: BTreeSet<u32>,
/// The bicubic routines the samples call, by dimension, a linear sample's emulation among them.
/// The bicubic routines the samples call, by dimension, an extended-range sample's among them.
pub bicubic_routines: BTreeSet<bicubic::routines::Routine>,
/// A filtered sample with a `half` result relies on the device's filter being Metal's: the
/// module requires `VkProperty::MetalSampler` ([`linear`]); on a device that samples natively
/// ([`DeviceProfile::device_samples`](crate::device::DeviceProfile::device_samples)),
/// `VkProperty::DeviceSampling` instead.
/// A sample relies on the device's sampler: the module requires `VkProperty::MetalSampler`
/// on a device that samples through Metal's own sampler, and `VkProperty::DeviceSampling` on
/// one that samples natively.
pub metal_sampler: bool,
/// A sample, gather or comparison goes to the device's own sampler where an emulation of
/// Metal's would run on a device whose sampler is not Metal's ([`DeviceProfile::device_samples`](crate::device::DeviceProfile::device_samples)): on a
/// device that samples natively the module requires `VkProperty::DeviceSampling` and records
/// `PrecisionNote::DeviceSampling`. A device that samples through Metal's own reads nothing of
/// it.
/// A sample, gather or comparison goes to the device's sampler: on a device that samples
/// natively the module requires `VkProperty::DeviceSampling` and records
/// `PrecisionNote::DeviceSampling`; on one that samples through Metal's own it requires
/// `VkProperty::MetalSampler`.
pub device_sampling: bool,
/// Every operation through an argument buffer's sampler tests its table entry's word for a
/// cubic filter (`SamplerWord::CUBIC`) and marks the command buffer's `ExecutionStatus` where
/// it holds one (`RuntimeFact::CubicArgumentSampler`): set where the stage can write the
/// buffer.
pub cubic_reach: bool,
/// A linear sample hands an 8-bit unsigned normalized class to the device's filter at
/// Metal's footprint step, because the device is measured within one code of Metal's
/// (`native`, `DriverDeviation::Unorm8LinearFilter`): the module requires
/// `VkProperty::Unorm8LinearFilter`.
pub native_filter: bool,
/// The sampling routines the samples call, each shape once (`routine::note`): the census counts
/// each one's words once.
pub routines: Vec<routine::Shape>,
@@ -1639,12 +1392,8 @@ pub struct Declared {
pub bicubic_line: Option<bicubic::routines::Line>,
/// The emulated linear 2D samples' routines, when the module has one.
pub linear_quad: Option<bicubic::routines::Quad>,
/// The emulated linear 1D samples' routines, when the module has one.
pub linear_span: Option<bicubic::routines::Span>,
/// The emulated linear 3D samples' routines, when the module has one.
pub linear_block: Option<bicubic::routines::Block>,
/// The emulated linear cube samples' fold and corner routines, when the module has one.
pub linear_cube: Option<bicubic::routines::Cube>,
/// The blend of an extended-range sample's two levels under a linear mip filter
/// (`bicubic::routines::define_levels`), when the module has one.
pub level_blend: Option<FuncId>,
@@ -1975,15 +1724,9 @@ pub fn declare(
bicubic::routines::Routine::Quad => {
d.linear_quad = Some(bicubic::routines::define_quad(mb)?);
}
bicubic::routines::Routine::Span => {
d.linear_span = Some(bicubic::routines::define_span(mb)?);
}
bicubic::routines::Routine::Block => {
d.linear_block = Some(bicubic::routines::define_block(mb)?);
}
bicubic::routines::Routine::Cube => {
d.linear_cube = Some(bicubic::routines::define_cube(mb)?);
}
bicubic::routines::Routine::Levels => {
d.level_blend = Some(bicubic::routines::define_levels(mb)?);
}
@@ -2031,16 +1774,11 @@ pub fn select_param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<(), Error
coordinates: false,
nearest: false,
linear: false,
snap: false,
levels: false,
level: false,
compared: false,
filters: false,
fetched: false,
fetched_depth: false,
fetch_levels: false,
anisotropy: false,
faces: false,
gathers: false,
cells: false,
texels: false,
@@ -1,343 +0,0 @@
//! The device's own linear filter of an 8-bit unsigned normalized texture, at Metal's footprint
//! step.
//!
//! **What it replaces.** Metal's linear filter is emulated by fetches wherever the bound
//! format's sum is measured (`linear`): exact, at about 574 instructions per sample site, the bulk
//! of a large fragment function's size and of a driver's time to compile it (the breakdown). On a
//! device whose own filter of an 8-bit unsigned normalized texture lands within one code of Metal's
//! once it reads Metal's footprint step, the module hands that class to the device instead, a
//! degrade the owner accepted on 2026-10-10 ("I accept the one color step deviation"), recorded in
//! each artifact and announced with its bound (`PrecisionNote::DeviceUnorm8LinearFilter`).
//!
//! **Metal's footprint step** (`position`'s module docs). Metal reads the texel-space position `X`
//! of a coordinate (wrapped into one period first on a repeating or mirrored axis, then scaled,
//! `position::position`) as `q = floor(256 (X - 1/2) + 1/2)`: the taps `q >> 8` and the one after
//! it, weighed by the step `q & 255` in 256ths. A device reads the position its own way (Vulkan
//! bounds it only by `subTexelPrecisionBits`), so its weights may differ from Metal's by a step.
//! The module hands the device the coordinate of the centre of Metal's step, `X' = q / 256 + 1/2`
//! (`position::AxisSnap::Cell`'s), on each plane axis: a device with eight subtexel bits then reads
//! Metal's taps and weights, and only its blend of them is its own. The position is the cheap one
//! ([`cell`]): the coordinate wrapped into its period by `floor` (a repeating axis's `floor(u)`, a
//! mirrored one's `2 floor(u / 2)`, a constexpr sampler's by its address modes, a runtime sampler
//! slot's by the modes its word states) and scaled, rounded to nearest. Metal rounds the wrap of
//! `-1 < u < 0` up and the product's ties away from zero (`position::position`); where that moves
//! `X` across a step's edge (a coordinate within an `f32` unit of it) the device reads the
//! neighbouring step, a weight 1/256 off. The bound below is measured with this position (the
//! probe's `cell` variant).
//!
//! **The class** ([`CLASSES`]): the slot's `TexelFormat` specialization masked by [`CLASS_MASK`] is
//! `EXACT | UNORM` with the channels of `R8Unorm`, `RG8Unorm`, or `RGBA8Unorm` and `BGRA8Unorm`,
//! the formats the deviation was measured on. Every other class keeps its path: the 16-bit, signed,
//! sRGB, packed, two-plane, float and half-float classes, and `A8Unorm` and `RGBX8Unorm`, which
//! share the family but were not measured.
//!
//! **The reach** ([`planned`]): a sample with a `float` or `half` result of a 2D texture or 2D
//! array slot, without comparison, offset, or pixel coordinates, through a constexpr sampler the
//! emulation reaches (linear filters, no mip filter, no anisotropy) or a runtime sampler slot
//! whose word states such a filter with normalized coordinates and no `MirrorClampToEdge` axis,
//! on a profile that takes `DriverDeviation::Unorm8LinearFilter` (`device::driver_facts`): a
//! device measured within one code, under a policy of `Unorm8LinearFilterPolicy::
//! DeviceWithinOneCode`. An unmeasured device, and every device under the default policy, keep
//! the emulation, exact (on the consumer's fragments this module's arm bought no GPU time and cost
//! module size and making time). A 1D or 3D texture, a cube, a heap element, a comparison and every
//! other sample keep theirs.
//!
//! **The branch** (`linear::emit`, `linear::emit_shared`): the emulation (its routine's call) runs
//! where the class is measured and the native condition ([`coordinate`]'s) does not hold, the
//! device's sample at the selected coordinate elsewhere. The class is data the function reads from
//! its push field, so both arms stay in the module and the branch runs: the native class's gain is
//! GPU time per sample, not words, and a runtime sampler's word tests are specializations as
//! before.
//!
//! **The bound** (the deviation probe, `probes/shb-dev` at the scratch commit `aa944573d` with its
//! `cell` variant, this module's coordinate; our probes compared: 19x13 textures of
//! the four formats, 4,096 coordinates, a third of them near the 1/256 grid, under clamp to edge,
//! repeat, mirrored repeat and clamp to zero, against an Apple M4 on macOS 27.0.1): the largest
//! difference of any channel of a `float` result, in codes (1/255), was 0.849 on NVIDIA's 615.71.09
//! (RTX 3090 and RTX 5080 Laptop GPU alike, its blend's own rounding), 0.031 on RADV and ANV (Mesa
//! 26.2.4 on the Radeon 780M, the Iris Xe of RPL-P and the UHD 770 of RPL-S), and just under 1 on
//! lavapipe (Mesa 26.2.4, LLVM 23.1.1, whose filter answers whole codes); none reached one code. A
//! `half` result is the device's `float` rounded as the class's conversion rounds it: 0.809, 0.125
//! and 0.996 codes on the same lanes. At the coordinate as given the same devices missed by up to
//! 0.919 (NVIDIA), 0.427 (RADV), 0.918 (ANV) and 1.000 (lavapipe).
use crate::air::intrinsics::{ImageDim, ImageShape};
use crate::error::DriverDeviation;
use crate::lower::emit::EmitCx;
use crate::lower::select::{both, NoteClause, NoteOn, NoteTest, SelectCx};
use crate::metal::bicubic::BicubicTexels as B;
use crate::metal::sampler::SamplerWord;
use crate::metal::texel_format::TexelFormat;
use crate::metal::SamplerAddressMode;
use crate::spirv::builder::FunctionBuilder;
use crate::spirv::error::BResult;
use crate::spirv::ids::Value as SValue;
use crate::spirv::ir::{BinOp, ConvOp, GlslOp, ImageQuery, Type as SType};
use super::bicubic::{scalar, value, word_field, Bits, TapAddress, Tys};
use super::linear::{Linear, LinearImage, LinearState};
use super::Sampling;
/// The class bits the native class test reads of a slot's `TexelFormat` specialization: the
/// family's bits, the channels present, and the packed field.
pub(crate) const CLASS_MASK: u32 = B::LINEAR
| B::UNORM
| B::SNORM
| B::HALF
| 0xF << B::PRESENT
| B::EXACT
| B::WIDE16
| B::SRGB
| B::EXTENDED
| TexelFormat::PACKED_MASK;
/// The native classes, masked by [`CLASS_MASK`]: `R8Unorm`'s, `RG8Unorm`'s, and `RGBA8Unorm`'s
/// and `BGRA8Unorm`'s (module docs).
pub(crate) const CLASSES: [u32; 3] = [
B::EXACT | B::UNORM | 0b0001 << B::PRESENT,
B::EXACT | B::UNORM | 0b0011 << B::PRESENT,
B::EXACT | B::UNORM | 0b1111 << B::PRESENT,
];
/// The census words [`coordinate`] adds to a linear sample: the class test, a runtime sampler's
/// word tests, the size query, per plane axis its extractions, its period's start under each mode
/// and their selection, and its cell, and the composite, the layer and the select, with their
/// constants.
pub(super) const WORDS: u32 = 2 * 256 + 512;
/// Whether the sample emulation `l` plans (of an image of shape `shape`) takes the device's
/// filter on the native classes (module docs): the profile takes
/// `DriverDeviation::Unorm8LinearFilter`, and the sample is a 2D texture or 2D array slot's,
/// without comparison, texel offset, or pixel coordinates, through a constexpr sampler or a
/// runtime sampler slot. The module then requires `VkProperty::Unorm8LinearFilter`.
pub(super) fn planned(cx: &mut SelectCx<'_>, l: &Linear, shape: ImageShape) -> bool {
let reach = shape.dim == ImageDim::D2
&& !shape.ms
&& !shape.depth
&& l.cube.is_none()
&& l.compare.is_none()
&& !l.raw
&& !l.exact_only
&& matches!(l.image, LinearImage::Slot(_))
&& match &l.state {
LinearState::Constant { pixel, .. } => !pixel,
LinearState::Slot { .. } => true,
LinearState::Argument { .. } => false,
}
&& l.offset
.as_deref()
.is_none_or(|o| o.iter().all(|k| *k == 0));
let native = reach
&& cx
.profile
.takes_driver_deviation(DriverDeviation::Unorm8LinearFilter);
if native {
cx.families.sampler.native_filter = true;
}
native
}
/// Where the native arm of emulation `l` runs: the slot's class is a native one ([`CLASSES`]) and,
/// through a runtime sampler slot, its word states the linear filter Metal's rule answers
/// (`SamplerWord::LINEAR_FILTER`), normalized coordinates, and no `MirrorClampToEdge` on either
/// plane axis. Empty where `l` takes no native arm.
pub(super) fn when(l: &Linear) -> Vec<NoteClause> {
let LinearImage::Slot(texture) = l.image else {
return Vec::new();
};
if !l.native || l.raw {
return Vec::new();
}
let class: Vec<NoteClause> = CLASSES
.iter()
.map(|&c| [NoteTest::equal(NoteOn::Texel(texture), CLASS_MASK, c)].into())
.collect();
match &l.state {
LinearState::Constant { .. } => class,
LinearState::Slot { sampler, .. } => {
let on = NoteOn::Sampler(*sampler);
let clamp = SamplerAddressMode::MirrorClampToEdge.as_raw();
let [s, t, _] = SamplerWord::ADDRESS_SHIFT;
let word: NoteClause = [
NoteTest::equal(on, SamplerWord::LINEAR_FILTER, SamplerWord::LINEAR),
NoteTest::equal(on, SamplerWord::PIXEL_COORDINATES, 0),
NoteTest::differ(on, 0b111 << s, clamp << s),
NoteTest::differ(on, 0b111 << t, clamp << t),
]
.into();
both(&class, &[word])
}
LinearState::Argument { .. } => Vec::new(),
}
}
/// The base level's size of sample `s`'s combined binding (a `u32` vector, its plane axes first),
/// from a sampled image of its own in the open block, and the slot's `TexelFormat`
/// specialization: what [`coordinate`] reads of a slot's own sample.
pub(super) fn slot_facts(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
s: &Sampling,
l: &Linear,
) -> BResult<Option<(SValue, Bits)>> {
let (true, false, LinearImage::Slot(texture)) = (l.native, l.raw, l.image) else {
return Ok(None);
};
let Some(spec) = crate::lower::texture::texel_format_const(cx, texture) else {
return Err(cx.fail(format!(
"texture slot {texture} has no `TexelFormat` specialization"
)));
};
let (si, _, _) = super::emit::sampled_image(cx, fb, s.source)?;
let img = fb.image(si)?;
let zero = fb.u32_const(0)?;
let zero = fb.module().const_value(zero)?;
let size = fb.query(ImageQuery::SizeLod(zero), img)?;
Ok(Some((size, Bits::Spec(spec))))
}
/// The coordinate the device's arm of emulation `l` samples at, and the native condition (a
/// `bool`): where the class `bits` is native ([`CLASSES`]) and, through a runtime sampler slot,
/// its word states a native sampler ([`when`]), the plane coordinate `plane` (normalized, two
/// lanes) snapped onto the centre of Metal's footprint step on the base level's size `size`
/// (module docs), with `s`'s layer; elsewhere `coord`, the coordinate the device reads otherwise.
/// `None` where `l` takes no native arm.
pub(super) fn coordinate(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
s: &Sampling,
l: &Linear,
(plane, coord): (SValue, SValue),
(size, bits): (SValue, Bits),
) -> BResult<Option<(SValue, SValue)>> {
if !l.native || l.raw {
return Ok(None);
}
let t = Tys::new(fb)?;
let u32_value = |fb: &mut FunctionBuilder<'_>, x: u32| -> BResult<SValue> {
let c = scalar(fb, t.u32_, u64::from(x))?;
value(fb, c)
};
let class = bits.value(fb)?;
let mask = u32_value(fb, CLASS_MASK)?;
let class = fb.binary(BinOp::BitwiseAnd, class, mask)?;
let mut native = None;
for c in CLASSES {
let c = u32_value(fb, c)?;
let is = fb.binary(BinOp::IEqual, class, c)?;
native = Some(match native {
Some(n) => fb.binary(BinOp::LogicalOr, n, is)?,
None => is,
});
}
let Some(mut native) = native else {
return Err(cx.fail("a native linear sample without its classes"));
};
let word = match &l.state {
LinearState::Constant { .. } => None,
LinearState::Slot { sampler, .. } => {
let word = super::emit::sampler_word(cx, fb, super::Pixel::Spec(*sampler))?;
let filter = u32_value(fb, SamplerWord::LINEAR_FILTER)?;
let filter = fb.binary(BinOp::BitwiseAnd, word, filter)?;
let linear = u32_value(fb, SamplerWord::LINEAR)?;
let linear = fb.binary(BinOp::IEqual, filter, linear)?;
native = fb.binary(BinOp::LogicalAnd, native, linear)?;
let pixel = u32_value(fb, SamplerWord::PIXEL_COORDINATES)?;
let pixel = fb.binary(BinOp::BitwiseAnd, word, pixel)?;
let zero = u32_value(fb, 0)?;
let normalized = fb.binary(BinOp::IEqual, pixel, zero)?;
native = fb.binary(BinOp::LogicalAnd, native, normalized)?;
let clamp = u32_value(fb, SamplerAddressMode::MirrorClampToEdge.as_raw())?;
for shift in SamplerWord::ADDRESS_SHIFT.into_iter().take(2) {
let mode = word_field(fb, &t, word, shift, 0b111)?;
let other = fb.binary(BinOp::INotEqual, mode, clamp)?;
native = fb.binary(BinOp::LogicalAnd, native, other)?;
}
Some(word)
}
LinearState::Argument { .. } => return Ok(None),
};
let mut parts = Vec::with_capacity(2);
for (a, shift) in (0..2u32).zip(SamplerWord::ADDRESS_SHIFT) {
let u = fb.composite_extract(plane, &[a])?;
let n = fb.composite_extract(size, &[a])?;
let start = match (&l.state, word) {
(LinearState::Constant { address, .. }, _) => match address.get(a as usize) {
Some(TapAddress::Repeat) => Some(fb.glsl(GlslOp::Floor, &[u])?),
Some(TapAddress::Mirror) => Some(mirror_start(fb, &t, u)?),
Some(TapAddress::Edge | TapAddress::Border) => None,
None => return Err(cx.fail("a native linear sample without its axis's address")),
},
(_, Some(word)) => {
let mode = word_field(fb, &t, word, shift, 0b111)?;
let floor = fb.glsl(GlslOp::Floor, &[u])?;
let twice = mirror_start(fb, &t, u)?;
let none = f32_value(fb, &t, 0.0)?;
let repeat = u32_value(fb, SamplerAddressMode::Repeat.as_raw())?;
let mirror = u32_value(fb, SamplerAddressMode::MirrorRepeat.as_raw())?;
let repeats = fb.binary(BinOp::IEqual, mode, repeat)?;
let mirrors = fb.binary(BinOp::IEqual, mode, mirror)?;
let k = fb.select(mirrors, twice, none)?;
Some(fb.select(repeats, floor, k)?)
}
_ => return Err(cx.fail("a native linear sample without its sampler's word")),
};
parts.push(cell(fb, &t, u, n, start)?);
}
let f = fb.module().ty(SType::Float { width: 32 })?;
let ty = fb.module().ty(SType::Vector { elem: f, len: 2 })?;
let snapped = fb.composite_construct(ty, &parts)?;
let (snapped, _) = super::emit::layered(cx, fb, s, snapped)?;
let at = fb.select(native, snapped, coord)?;
Ok(Some((at, native)))
}
/// The start of the mirrored period of `u` (an `f32`): `2 floor(u / 2)`.
fn mirror_start(fb: &mut FunctionBuilder<'_>, t: &Tys, u: SValue) -> BResult<SValue> {
let half = f32_value(fb, t, 0.5)?;
let two = f32_value(fb, t, 2.0)?;
let h = fb.binary(BinOp::FMul, u, half)?;
let h = fb.glsl(GlslOp::Floor, &[h])?;
fb.binary(BinOp::FMul, h, two)
}
/// The normalized coordinate of the centre of the 1/256 footprint step Metal reads coordinate
/// `u` (an `f32`) at, on an axis of size `n` (a `u32`) whose period starts at `start` (an `f32`;
/// `None` on a clamping axis): the position `X = (u - start) N`, `c = floor(256 X) + [frac(256 X)
/// >= 1/2]` (`q + 128` for Metal's step `q`, as `position::AxisSnap::Cell` reads it), and
/// `c / 256 / N`.
fn cell(
fb: &mut FunctionBuilder<'_>,
t: &Tys,
u: SValue,
n: SValue,
start: Option<SValue>,
) -> BResult<SValue> {
let w = match start {
Some(k) => fb.binary(BinOp::FSub, u, k)?,
None => u,
};
let f = fb.module().ty(SType::Float { width: 32 })?;
let nf = fb.convert(ConvOp::ConvertUToF, n, f)?;
let x = fb.binary(BinOp::FMul, w, nf)?;
let k256 = f32_value(fb, t, 256.0)?;
let y = fb.binary(BinOp::FMul, x, k256)?;
let fl = fb.glsl(GlslOp::Floor, &[y])?;
let r = fb.binary(BinOp::FSub, y, fl)?;
let half = f32_value(fb, t, 0.5)?;
let up = fb.binary(BinOp::FOrdGreaterThanEqual, r, half)?;
let one = f32_value(fb, t, 1.0)?;
let zero = f32_value(fb, t, 0.0)?;
let up = fb.select(up, one, zero)?;
let c = fb.binary(BinOp::FAdd, fl, up)?;
let step = f32_value(fb, t, 1.0 / 256.0)?;
let at = fb.binary(BinOp::FMul, c, step)?;
fb.binary(BinOp::FDiv, at, nf)
}
/// The `f32` constant `x` as a value.
fn f32_value(fb: &mut FunctionBuilder<'_>, _: &Tys, x: f32) -> BResult<SValue> {
let f = fb.module().ty(SType::Float { width: 32 })?;
let c = scalar(fb, f, u64::from(x.to_bits()))?;
value(fb, c)
}
+139 -543
View File
@@ -1,5 +1,5 @@
//! Metal's texel-space position of a normalized coordinate, and the coordinate that makes a
//! device's gather or nearest sample read the texels Metal reads.
//! device's gather or linear sample of a pixel sampler read the texels Metal reads.
//!
//! **The position** (Apple M3 Max, macOS 26.7, and Apple M4, macOS 27.0.1, byte-identical; the
//! tie, gather, and bicubic probes). Per axis of size `N` and normalized coordinate `u`, Apple's
@@ -30,8 +30,7 @@
//! Rounded up, it reads one `1/256` step, sometimes a texel, high where `-1 < u < 0` lands just
//! below a step.
//!
//! Multiplying first and wrapping the taps after (as a Vulkan device does, and as the emulation
//! once did) reads another footprint wherever `u` lies outside `[0, 1)` on a size that is not a
//! Multiplying first and wrapping the taps after (as a Vulkan device does) reads another footprint wherever `u` lies outside `[0, 1)` on a size that is not a
//! power of two and `u N` lands near a step: the product rounds at the magnitude of `u N`, not of
//! `u' N`. At a power-of-two size `u N` is exact, and multiplying first reads Metal's footprints.
//!
@@ -90,55 +89,47 @@
//! reads it (`emit::plane_coord`), so the emulations and the device's own sampler alike are handed
//! Metal's coordinate; every other address mode reads the same texel either way.
//!
//! **The snapped coordinate** ([`snapped`]). A device gather or nearest sample at a coordinate
//! near a texel edge reads whichever texel its own arithmetic gives (ANV's gathers read the block
//! one texel low at odd sizes). Where Metal's texel is known, a snapped axis instead hands the
//! device a coordinate half a texel from every edge of it: a gather's `(i0 + 1) / N`, the centre of
//! its 2x2 block, and a nearest sample's `(i + 1/2) / N`, the centre of its texel, with `i0` and
//! `i` from Metal's position. Any device's rounding then reads Metal's block or texel, and the
//! device keeps everything else: the texel conversion, the border, the comparison, the offset
//! (added to the snapped index, then wrapped or clamped, as Metal adds it), and the layer. A
//! gather's `i0` is computed in `f32`, `floor(floor(256 X + 1/2) / 256 - 1/2)`, exact for `|X| <
//! 2^15` (every position of a Metal texture's repeating or mirrored axis, at most `2N`, included).
//! On a clamping axis `i0` is first clamped into `[-10, N + 8]`: past either end, with any offset
//! in Metal's gather range `[-8, 7]`, both texels lie outside the level on the same side, so they
//! read the same edge texels or border as the exact `i0` would, and the coordinate stays small. On
//! a repeating or mirrored axis whose size drops the offset ([`offset_dropped`]), the snapped index
//! is first moved back by the offset, which the device then adds: the device reads the texel or
//! block Metal reads there, the one without the offset. A nearest sample snaps only its repeating
//! and mirrored axes (`i` lies in `[0, N]` or `[0, 2N]` there), and only where it reads the base
//! level: a constexpr sampler's by its state, a runtime sampler's by its word in the function
//! ([`snapped_by_word`]). A nearest cube sample that reads the base level snaps its direction
//! instead, onto the centre of the texel Metal reads on its face (`face::snapped`): there Metal's
//! position comes from its texture unit's reciprocal of the major magnitude, which the module
//! computes correctly rounded where Apple's approximates it (`PrecisionNote::CubeFaceReciprocal`).
//! **The snapped coordinate** ([`snapped`]). A pixel sampler's coordinate, scaled for the
//! device, reads whichever texels the device's own arithmetic gives near a texel edge. Where
//! Metal's texels follow from the coordinate as given, a snapped axis instead hands the device a
//! coordinate half a step from every edge of them: a gather's `(i0 + 1) / N`, the centre of its
//! 2x2 block ([`AxisSnap::Gather`]), and a linear sample's footprint cell ([`AxisSnap::Cell`]),
//! with `i0` and the cell from Metal's position. Any device's rounding then reads Metal's block or
//! step, and the device keeps everything else: the texel conversion, the filter's weights, the
//! border, the comparison, the offset (added to the snapped index, then wrapped or clamped, as
//! Metal adds it), and the layer. A gather's `i0` is computed in `f32`, `floor(floor(256 X + 1/2)
//! / 256 - 1/2)`, exact for `|X| < 2^15` (every position of a Metal texture's repeating or mirrored
//! axis, at most `2N`, included). On a clamping axis `i0` is first clamped into `[-10, N + 8]`:
//! past either end, with any offset in Metal's gather range `[-8, 7]`, both texels lie outside the
//! level on the same side, so they read the same edge texels or border as the exact `i0` would,
//! and the coordinate stays small. On a repeating or mirrored axis whose size drops the offset
//! ([`offset_dropped`]), the snapped index is first moved back by the offset, which the device then
//! adds: the device reads the texel or block Metal reads there, the one without the offset.
//!
//! **A runtime or argument buffer's sampler** names its state in its word, read in the function:
//! its gather of a 2D texture or array snaps behind it ([`gathered_by_word`]), each axis at the
//! position its mode gives ([`position_by_mode`]) or, where the word states pixel coordinates, at
//! the coordinate as given, with `i0` clamped into the wider `[-2N - 10, 2N + 8]`, which holds
//! every position of a repeating or mirrored axis and reads a clamping axis's same edge texels or
//! border. On a `MirrorClampToEdge` axis (which no constexpr sampler states) Metal's position is a
//! clamping axis's, `u N` unwrapped, its taps mirrored once and clamped as Vulkan's
//! `MIRROR_CLAMP_TO_EDGE` mirrors and clamps them, and a texel offset is dropped by the sizes that
//! drop it on a repeating axis (every gather of 13x11, 7x5 and 16x8 textures through a slot's and
//! an argument buffer's runtime sampler, with offsets of 2 and -3, on an Apple M3 Max and an Apple
//! M4 alike), a pixel coordinate's as a normalized one's, and a nearest sample's, a linear one's
//! and a comparison's as a gather's: a nearest sample snaps such an axis as a repeating one
//! ([`snapped_by_word`]), and a pixel word's texel centre moves back by a
//! dropped offset (`emit::pixel_centre`). On a device with Metal's own sampler, only a pixel word's
//! gather is snapped, and a linear pixel word's sample snaps onto its footprint cell
//! ([`celled_by_word`]), as a constexpr pixel sampler's does there (that sample reads Metal's rule
//! at the coordinate as given: our probe's 10,250 lanes of a runtime pixel sampler on both chips).
//! where the word states pixel coordinates, its gather of a 2D texture or array snaps behind it
//! ([`gathered_by_word`]), each axis at the coordinate as given, with `i0` clamped into the wider
//! `[-2N - 10, 2N + 8]`, which holds every position of a repeating or mirrored axis and reads a
//! clamping axis's same edge texels or border; and where it also states linear min and mag
//! filters, its sample snaps onto its footprint cell ([`celled_by_word`]), as a constexpr pixel
//! sampler's does (that sample reads Metal's rule at the coordinate as given: our probe's 10,250
//! lanes of a runtime pixel sampler on both chips). A normalized word's gather and every other
//! word's sample keep the device's coordinate. On a `MirrorClampToEdge` axis (which no constexpr
//! sampler states) Metal's position is a clamping axis's, `u N` unwrapped, its taps mirrored once
//! and clamped as Vulkan's `MIRROR_CLAMP_TO_EDGE` mirrors and clamps them ([`position_by_mode`]),
//! and a texel offset is dropped by the sizes that drop it on a repeating axis (every gather of
//! 13x11, 7x5 and 16x8 textures through a slot's and an argument buffer's runtime sampler, with
//! offsets of 2 and -3, on an Apple M3 Max and an Apple M4 alike), a pixel coordinate's as a
//! normalized one's, and a pixel word's texel centre moves back by a dropped offset
//! (`emit::pixel_centre`).
use crate::air::abi::{AddressMode, Coordinates, Filter, MipFilter, SamplerState};
use crate::air::abi::{AddressMode, Coordinates, Filter};
use crate::air::intrinsics::{ImageDim, ImageShape};
use crate::error::Error;
use crate::lower::emit::EmitCx;
use crate::lower::select::SelectCx;
use crate::lower::texture::OffsetBase;
use crate::metal::SamplerAddressMode;
use crate::pipeline::artifact::PrecisionNote;
use crate::pipeline::sym::SamplerRef;
use crate::spirv::builder::FunctionBuilder;
use crate::spirv::error::BResult;
@@ -146,8 +137,7 @@ use crate::spirv::ids::Value as SValue;
use crate::spirv::ir::{BinOp, ConstBits, Constant, ConvOp, GlslOp, ImageQuery, Type as SType};
use super::bicubic::TapAddress;
use super::face::{FaceRoutines, FaceWrap};
use super::{CombinedImage, Lod, SampleOp};
use super::{CombinedImage, SampleOp};
/// The census words of one axis's [`position`]: the conversion of the size, the wrap (a mirrored
/// axis's four instructions, and the rounding's thirteen, which choose up or down by the size), the
@@ -160,8 +150,6 @@ pub const POSITION_WORDS: u32 = 200;
pub enum AxisSnap {
/// A gather's 2x2 block: the coordinate `(i0 + 1) / N`.
Gather,
/// A nearest sample's texel: the coordinate `(floor(X) + 1/2) / N`.
Nearest,
/// A linear sample's footprint cell: the coordinate `(floor(256 X - 127.5) + 128) / 256 / N`,
/// the centre of the `1/256` step `q` Metal's filter reads `X` as, half a step from either edge
/// of it.
@@ -173,30 +161,14 @@ pub enum AxisSnap {
pub enum SnapKind {
/// The plane coordinate with [`Snap::axes`]' axes snapped.
Axes(AxisSnap),
/// A nearest cube sample's direction, onto the centre of the texel Metal reads on its face
/// (`face::snapped`), Metal's position computed with Metal's reciprocal (`libm::Fun::Recip`)
/// and the fused multiply-add `fma`, and wrapped on the face axes [`Snap::axes`] repeats
/// (`face::FaceWrap`).
Cube(FaceRoutines),
/// A runtime or argument buffer's sampler's nearest sample of a texture of `axes` plane axes:
/// where the sampler's word states that it reads one texel of the base level
/// (`SamplerWord::NEAREST_BASE`), or, for a sample at a level the function knows (`leveled`),
/// one texel of one level (`SamplerWord::NEAREST_LEVEL`: no mip filter or a nearest one), each
/// plane axis the word repeats or mirrors is snapped as [`AxisSnap::Nearest`] snaps it, at the
/// position its word's mode gives ([`position_by_mode`]) on the size of the level it reads
/// (`level::snap_level`); elsewhere the coordinate is the device's ([`snapped_by_word`]).
/// [`Snap::axes`] is empty: the word names the modes.
Word { axes: u8, leveled: bool },
/// A runtime or argument buffer's sampler's gather of a 2D texture or 2D array: behind the
/// sampler's word, each plane axis takes [`AxisSnap::Gather`]'s coordinate, the centre of the
/// 2x2 block Metal reads at its position: the coordinate as given where the word states pixel
/// coordinates, else [`position_by_mode`] by the axis's mode ([`gathered_by_word`]). On a
/// device that samples through Metal's own sampler (`metal`) only a pixel coordinate is
/// snapped: Metal's own gather of a normalized coordinate is Metal's block. [`Snap::axes`] is
/// empty: the word names the modes.
WordGather { metal: bool },
/// On a device that samples through Metal's own sampler, a runtime or argument buffer's
/// sampler's sample of a texture of `axes` plane axes: where the word states pixel coordinates
/// sampler's word, where it states pixel coordinates, each plane axis takes
/// [`AxisSnap::Gather`]'s coordinate, the centre of the 2x2 block Metal reads at the coordinate
/// as given ([`gathered_by_word`]); a normalized coordinate is the device's gather's.
/// [`Snap::axes`] is empty: the word names the modes.
WordGather,
/// A runtime or argument buffer's sampler's sample of a texture of `axes` plane axes: where
/// the word states pixel coordinates
/// and linear min and mag filters, each plane axis takes [`AxisSnap::Cell`]'s coordinate, the
/// centre of the footprint step Metal reads the coordinate as given at, as a constexpr linear
/// pixel sampler's sample does there ([`celled_by_word`]); every other word keeps the scaled
@@ -204,115 +176,68 @@ pub enum SnapKind {
WordCell { axes: u8 },
}
/// A gather or nearest sample whose coordinate is snapped onto Metal's texels (module docs).
/// A gather or linear sample whose coordinate is snapped onto Metal's texels (module docs).
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Snap {
pub kind: SnapKind,
/// Per plane axis (`s`, then `t`, then `r`), its addressing where the axis is snapped, or
/// `None` where the device reads the coordinate as given; for a cube its face's `s` and `t`
/// axes, addressed by the sampler's `s` and `t` addresses.
/// `None` where the device reads the coordinate as given.
pub axes: Vec<Option<TapAddress>>,
/// The coordinate is in texels (a pixel sampler's): Metal's position `X` is the coordinate as
/// given, so the snap takes no [`position`].
pub pixel: bool,
}
impl Snap {
/// A runtime or argument buffer's sampler's snap behind its word ([`SnapKind::Word`],
/// [`SnapKind::WordGather`], [`SnapKind::WordCell`]).
/// A runtime or argument buffer's sampler's snap behind its word ([`SnapKind::WordGather`],
/// [`SnapKind::WordCell`]).
pub fn by_word(&self) -> bool {
matches!(
self.kind,
SnapKind::Word { .. } | SnapKind::WordGather { .. } | SnapKind::WordCell { .. }
)
matches!(self.kind, SnapKind::WordGather | SnapKind::WordCell { .. })
}
/// The census words: the image and its size query; per snapped plane axis the extractions, the
/// [`position`], the index and its clamp, and the coordinate, and the composite; or a cube's
/// `face::snapped` with its reciprocal and two fused multiply-adds, and its wrap.
/// [`position`], the index and its clamp, and the coordinate, and the composite.
pub fn words(&self) -> u32 {
let position = if self.pixel { 8 } else { POSITION_WORDS };
let per_axis = position
+ match self.kind {
SnapKind::Axes(AxisSnap::Gather) => GATHER_AXIS_WORDS,
SnapKind::Axes(AxisSnap::Nearest) => NEAREST_AXIS_WORDS,
SnapKind::Axes(AxisSnap::Cell) => CELL_AXIS_WORDS,
SnapKind::Cube(routines) => {
return 32
+ super::face::SNAP_WORDS
+ routines.use_words()
+ self.face_wrap().words();
}
SnapKind::Word { axes, leveled } => {
return 32
+ WORD_REACH_WORDS
+ if leveled { WORD_LEVEL_WORDS } else { 0 }
+ u32::from(axes)
* (POSITION_WORDS
+ MODE_POSITION_WORDS
+ NEAREST_AXIS_WORDS
+ WORD_AXIS_WORDS);
}
SnapKind::WordGather { .. } => {
return 32
+ WORD_REACH_WORDS
+ 2 * (POSITION_WORDS
+ MODE_POSITION_WORDS
+ GATHER_AXIS_WORDS
+ WORD_AXIS_WORDS);
}
SnapKind::WordCell { axes } => {
return 32
+ WORD_REACH_WORDS
+ u32::from(axes) * (8 + CELL_AXIS_WORDS + WORD_AXIS_WORDS);
}
};
// The coordinate is in texels: Metal's position `X` is the coordinate as given.
let per_axis = 8 + match self.kind {
SnapKind::Axes(AxisSnap::Gather) => GATHER_AXIS_WORDS,
SnapKind::Axes(AxisSnap::Cell) => CELL_AXIS_WORDS,
SnapKind::WordGather => {
return 32 + WORD_REACH_WORDS + 2 * (8 + GATHER_AXIS_WORDS + WORD_AXIS_WORDS);
}
SnapKind::WordCell { axes } => {
return 32
+ WORD_REACH_WORDS
+ u32::from(axes) * (8 + CELL_AXIS_WORDS + WORD_AXIS_WORDS);
}
};
let snapped = self.axes.iter().filter(|a| a.is_some()).count() as u32;
32 + snapped * per_axis + self.axes.len() as u32 * 8
}
/// The census words of the offset rule ([`offset_dropped`]) on each axis this snap may move
/// back, for an access with a texel offset: each snapped plane axis's, and each axis of a word
/// snap; a cube's access takes no offset.
/// gather.
pub fn offset_words(&self) -> u32 {
let axes = match self.kind {
// A cube's access takes no offset; Metal's own sampler places a pixel cell's.
SnapKind::Cube(_) | SnapKind::WordCell { .. } => 0,
SnapKind::Word { axes, .. } => u32::from(axes),
SnapKind::WordGather { .. } => 2,
// The device's sampler places a pixel cell's.
SnapKind::WordCell { .. } => 0,
SnapKind::WordGather => 2,
SnapKind::Axes(_) => self.axes.iter().filter(|a| a.is_some()).count() as u32,
};
axes * OFFSET_RULE_WORDS
}
/// The face axes a cube's snap wraps (`face::FaceWrap`): those its sampler repeats.
fn face_wrap(&self) -> FaceWrap {
let axis = |k: usize| self.axes.get(k).copied().flatten();
FaceWrap::of(axis(0), axis(1))
}
}
/// A gather axis's words past its position: the two extractions, `i0` (six instructions and their
/// constants), its clamp, and the coordinate.
const GATHER_AXIS_WORDS: u32 = 96;
/// A nearest axis's words past its position: the two extractions, the floor, and the coordinate.
const NEAREST_AXIS_WORDS: u32 = 40;
/// A footprint cell's words past its position: the two extractions, the step (seven instructions
/// and their constants), and the coordinate.
const CELL_AXIS_WORDS: u32 = 96;
/// A word snap's test of the base level (`SamplerWord::NEAREST_BASE`): the mask, the comparison,
/// and their constants.
/// A word snap's test of its word (`SamplerWord::PIXEL_COORDINATES`, and a cell's linear filters):
/// the mask, the comparison, and their constants.
const WORD_REACH_WORDS: u32 = 24;
/// A word snap's axis words past its position and nearest coordinate: the mode's shift and mask,
/// the three mode tests (`Repeat`, `MirrorRepeat` and `MirrorClampToEdge`), their disjunction and
/// conjunction with the reach, and the select.
/// A word snap's axis words past its snapped coordinate: the extractions of the coordinate as
/// given and the device's, the size's conversion, a gather's widened clamp, and the select.
const WORD_AXIS_WORDS: u32 = 64;
/// A leveled word snap's level (`level::snap_level`: the clamp's two fields, the conversion, the
/// clamps, and the mip filter's test and select), the texture's levels and their clamp, and the
/// size query of that level; a dynamic level's grid is the level rule's (`level::by_word`) or
/// its own, at most `level::LEVEL_WORDS`.
const WORD_LEVEL_WORDS: u32 = 160 + super::level::LEVEL_WORDS;
/// The tap addressing of address mode `m`.
pub(super) fn address(m: AddressMode) -> TapAddress {
match m {
@@ -442,47 +367,30 @@ pub(super) fn emit_flush(
}
/// The snap of `op` on a texture of `shape` through the static sampler `stat` (`None`: an
/// argument buffer's), where the module docs snap it, on a device without
/// `VkProperty::MetalSampler`:
/// argument buffer's), where the module docs snap it. A pixel sampler's coordinate is Metal's
/// position as given, which the device's sampler, reading the coordinate over the size, does not
/// reproduce, its own or Metal's alike. So on every device:
///
/// - every gather (with or without a comparison or an offset) of a 2D texture or 2D array through
/// a constexpr sampler with normalized coordinates, on both plane axes;
/// - a nearest sample without a comparison through a constexpr sampler with normalized
/// coordinates ([`super::linear::unfiltered`]) of a 1D, 2D, or 3D texture or array that reads
/// the base level (the sampler has no mip filter, or the sample reads level 0 and the sampler
/// neither biases nor clamps it) and has a repeating or mirrored plane axis, on those axes;
/// - such a nearest sample of a cube or cube array that reads the base level, its direction
/// (`face::snapped`, which records `PrecisionNote::CubeFaceReciprocal`);
/// - a sample without a comparison through a runtime or argument buffer's sampler of a 1D, 2D, or
/// 3D texture or array, behind the sampler's word ([`SnapKind::Word`]): the axes the word repeats
/// or mirrors where the word reads one texel of the base level, or, for a sample at a level the
/// function knows (an explicit level, or a kernel's bias, without a `min_lod_clamp`) of a texture
/// of floating-point texels, of the level a nearest mip filter reads there.
/// - a constexpr pixel sampler's gather of a 2D texture or 2D array snaps both plane axes from the
/// coordinate as given;
/// - a runtime or argument buffer's sampler's gather of a 2D texture or 2D array snaps behind the
/// sampler's word, where it states pixel coordinates ([`SnapKind::WordGather`]);
/// - a constexpr pixel sampler's linear sample of a 1D, 2D, or 3D texture or array with a
/// floating-point texel (an `integer` one's reads one texel) snaps every plane axis onto the
/// centre of its footprint cell, unless the sampler is anisotropic;
/// - a runtime or argument buffer's sampler's sample of such a texture, a comparison's included,
/// snaps onto its footprint cell where its word states a linear pixel sampler
/// ([`SnapKind::WordCell`]).
///
/// Every other gather keeps the device's footprint and records
/// `PrecisionNote::DeviceGatherFootprint` (a cube, a runtime or argument buffer's sampler). On a
/// device with the property, each gather and each such nearest sample is the device's, Metal's own
/// sampler, and the module requires the property.
///
/// A constexpr pixel sampler's coordinate is Metal's position as given, which the device's sampler,
/// reading the coordinate over the size, does not reproduce, its own or Metal's alike. So on every
/// device, the property's included:
///
/// - its gather of a 2D texture or 2D array snaps both plane axes from the coordinate as given;
/// - its linear sample of a 1D, 2D, or 3D texture or array with a floating-point texel (an
/// `integer` one's reads one texel), where nothing emulates it (on a device with the property;
/// elsewhere the emulation reads the coordinate as given, `linear`), snaps every plane axis onto
/// the centre of its footprint cell, unless the sampler is anisotropic.
///
/// A cube's coordinate is a direction through a pixel sampler too, so a cube's snap
/// reads a pixel sampler as a normalized one.
/// Every other gather and sample is the device's, and the module requires the device's sampler
/// (`SamplerFamily::metal_sampler`). A cube's coordinate is a direction through a pixel sampler
/// too, so a cube takes no snap.
pub(super) fn plan(
cx: &mut SelectCx<'_>,
op: &SampleOp,
stat: Option<(SamplerRef, Coordinates)>,
(shape, integer): (ImageShape, bool),
) -> Result<Option<Snap>, Error> {
let metal_sampler = cx.profile.device_samples();
// A constexpr sampler's state, and whether its coordinate is in texels (not a cube's).
let state = match stat {
Some((SamplerRef::Constexpr(words), c)) => Some((
@@ -500,45 +408,30 @@ pub(super) fn plan(
};
match op {
SampleOp::Gather { .. } => match state {
Some((s, pixel))
if shape.dim == ImageDim::D2 && !shape.ms && (pixel || !metal_sampler) =>
{
Ok(Some(Snap {
kind: SnapKind::Axes(AxisSnap::Gather),
axes: vec![Some(address(s.address_s)), Some(address(s.address_t))],
pixel,
}))
}
// A runtime or argument buffer's sampler's gather, behind its word. Metal's own gather
// of a normalized coordinate is Metal's block: on a device with the property the word
// snaps a pixel coordinate alone, and the module requires it.
Some((s, true)) if shape.dim == ImageDim::D2 && !shape.ms => Ok(Some(Snap {
kind: SnapKind::Axes(AxisSnap::Gather),
axes: vec![Some(address(s.address_s)), Some(address(s.address_t))],
})),
// A runtime or argument buffer's sampler's gather, behind its word. The device's own
// gather of a normalized coordinate is its block: the word snaps a pixel coordinate
// alone, and the module requires the device's sampler.
None if shape.dim == ImageDim::D2 && !shape.ms => {
if metal_sampler {
cx.families.sampler.metal_sampler = true;
}
cx.families.sampler.metal_sampler = true;
Ok(Some(Snap {
kind: SnapKind::WordGather {
metal: metal_sampler,
},
kind: SnapKind::WordGather,
axes: Vec::new(),
pixel: false,
}))
}
_ if metal_sampler => {
_ => {
cx.families.sampler.metal_sampler = true;
Ok(None)
}
_ => {
cx.precision.insert(PrecisionNote::DeviceGatherFootprint);
Ok(None)
}
},
// A linear pixel sample's footprint cell, where Metal's own sampler filters it.
// A linear pixel sample's footprint cell.
SampleOp::Sample { dref: None, .. }
if state.as_ref().is_some_and(|(s, pixel)| {
*pixel
&& plane > 0
&& metal_sampler
&& !integer
&& s.min_filter == Filter::Linear
&& s.mag_filter == Filter::Linear
@@ -557,134 +450,29 @@ pub(super) fn plan(
.take(plane)
.map(|m| Some(address(m)))
.collect(),
pixel: true,
}))
}
// On a device with the property, a runtime or argument buffer's sampler's sample, a
// comparison's included, onto its footprint cell where its word states a linear pixel
// sampler, as a constexpr one's. An integer texture's sample reads one texel whatever the
// filters say, its pixel sampler's texel centre.
// A runtime or argument buffer's sampler's sample, a comparison's included, onto its
// footprint cell where its word states a linear pixel sampler, as a constexpr one's. An
// integer texture's sample reads one texel whatever the filters say, its pixel sampler's
// texel centre.
SampleOp::Sample { .. }
if plane > 0
&& metal_sampler
&& !integer
&& !matches!(stat, Some((SamplerRef::Constexpr(_), _))) =>
if plane > 0 && !integer && !matches!(stat, Some((SamplerRef::Constexpr(_), _))) =>
{
cx.families.sampler.metal_sampler = true;
Ok(Some(Snap {
kind: SnapKind::WordCell { axes: plane as u8 },
axes: Vec::new(),
pixel: false,
}))
}
// A runtime or argument buffer's sampler's nearest sample, behind its word: at a level the
// function knows, on the level a nearest mip filter reads there, where Metal's level rule
// is measured (`level`: not an integer texture's, nor beside a `min_lod_clamp`).
SampleOp::Sample {
dref: None,
lod,
min_lod,
..
} if plane > 0 && !matches!(stat, Some((SamplerRef::Constexpr(_), _))) => {
if metal_sampler {
cx.families.sampler.metal_sampler = true;
return Ok(None);
}
let leveled = !integer
&& min_lod.is_none()
&& matches!(lod, Lod::Level(_) | Lod::Base { min: None, .. });
Ok(Some(Snap {
kind: SnapKind::Word {
axes: plane as u8,
leveled,
},
axes: Vec::new(),
pixel: false,
}))
}
SampleOp::Sample {
lod,
dref: None,
min_lod,
..
} => {
// A pixel sampler's nearest sample takes its texel's centre instead (`emit`).
let Some((s, false)) = state else {
return Ok(None);
};
let axes = match (shape.dim, shape.ms) {
(ImageDim::D1, false) => 1,
(ImageDim::D2, false) => 2,
(ImageDim::D3, false) => 3,
(ImageDim::Cube, false) => {
if !super::linear::unfiltered(&s) || !base_level(&s, lod, min_lod.is_some()) {
return Ok(None);
}
if metal_sampler {
cx.families.sampler.metal_sampler = true;
return Ok(None);
}
return cube(cx, &s).map(Some);
}
_ => return Ok(None),
};
let modes = [s.address_s, s.address_t, s.address_r];
let wraps =
|m: &AddressMode| matches!(m, AddressMode::Repeat | AddressMode::MirroredRepeat);
if !super::linear::unfiltered(&s)
|| !base_level(&s, lod, min_lod.is_some())
|| !modes.iter().take(axes).any(wraps)
{
return Ok(None);
}
if metal_sampler {
cx.families.sampler.metal_sampler = true;
return Ok(None);
}
Ok(Some(Snap {
kind: SnapKind::Axes(AxisSnap::Nearest),
axes: modes
.iter()
.take(axes)
.map(|m| wraps(m).then(|| address(*m)))
.collect(),
pixel: false,
}))
SampleOp::Sample { dref: None, .. } => {
cx.families.sampler.metal_sampler = true;
Ok(None)
}
_ => Ok(None),
}
}
/// The snap of a nearest cube sample through sampler `s` (`face::snapped`), with its face
/// position's routines (`face::plan`, which records `PrecisionNote::CubeFaceReciprocal`) and the
/// addressing of its face's `s` and `t` axes, which wraps a repeating one (`face::FaceWrap`).
fn cube(cx: &mut SelectCx<'_>, s: &SamplerState) -> Result<Snap, Error> {
Ok(Snap {
kind: SnapKind::Cube(super::face::plan(cx)?),
axes: vec![Some(address(s.address_s)), Some(address(s.address_t))],
pixel: false,
})
}
/// Whether a sample through sampler `s` with level `lod` (`clamped`: a `min_lod_clamp`) reads the
/// base level: the sampler has no mip filter, or the sample reads level 0 and the sampler neither
/// biases nor clamps it (`footprint::of`'s rule).
fn base_level(s: &SamplerState, lod: &Lod, clamped: bool) -> bool {
if s.mip_filter == MipFilter::None {
return true;
}
matches!(
lod,
Lod::Level(None)
| Lod::Base {
bias: None,
min: None,
}
) && !clamped
&& s.lod_min_clamp.to_f32() == 0.0
&& s.lod_bias.to_f32() == 0.0
}
fn f32_const(fb: &mut FunctionBuilder<'_>, x: f32) -> BResult<SValue> {
let ty = fb.module().ty(SType::Float { width: 32 })?;
let c = fb.module().constant(Constant::Scalar {
@@ -914,25 +702,21 @@ fn lane(fb: &mut FunctionBuilder<'_>, v: SValue, lanes: u8, i: u32) -> BResult<S
}
}
/// The snapped axis coordinate (an `f32`) of coordinate `u` (normalized, or in texels where
/// `pixel`, Metal's position as given) on an axis of size `n` (a `u32`) addressed by `address`,
/// The snapped axis coordinate (an `f32`) of coordinate `u` (in texels, Metal's position as
/// given) on an axis of size `n` (a `u32`) addressed by `address`,
/// for `kind` (module docs), whose access the device moves by the constant texel offset `offset`
/// (an `f32` holding the axis's offset; `None`: none): on a repeating or mirrored axis whose size
/// drops it ([`offset_dropped`], whose `parent` is the axis's `texture::OffsetBase` test), the
/// index is moved back by it first.
pub fn snapped_axis(
fb: &mut FunctionBuilder<'_>,
(kind, pixel): (AxisSnap, bool),
u: SValue,
kind: AxisSnap,
x: SValue,
n: SValue,
(address, offset, parent): (TapAddress, Option<SValue>, Option<SValue>),
) -> BResult<SValue> {
let (x, nf) = if pixel {
let f = fb.module().ty(SType::Float { width: 32 })?;
(u, fb.convert(ConvOp::ConvertUToF, n, f)?)
} else {
position(fb, u, n, address)?
};
let f = fb.module().ty(SType::Float { width: 32 })?;
let nf = fb.convert(ConvOp::ConvertUToF, n, f)?;
let at = match kind {
AxisSnap::Gather => {
let i0 = gather_base(fb, x)?;
@@ -948,11 +732,6 @@ pub fn snapped_axis(
let one = f32_const(fb, 1.0)?;
fb.binary(BinOp::FAdd, i0, one)?
}
AxisSnap::Nearest => {
let i = fb.glsl(GlslOp::Floor, &[x])?;
let half = f32_const(fb, 0.5)?;
fb.binary(BinOp::FAdd, i, half)?
}
// `q + 128 = floor(256 X) + [frac(256 X) >= 1/2]`, as `bicubic::quantize` reads `q`:
// `256 X`, its floor, and its fraction are exact, where `256 X - 127.5` can round (a
// negative `X` whose sum carries into the next binade). The centre `(q + 128) / 256` is
@@ -984,8 +763,7 @@ pub fn snapped_axis(
fb.binary(BinOp::FDiv, at, nf)
}
/// The coordinate `coord` (`lanes` floats; in texels where `snap.pixel`, else normalized) of a
/// sample or gather of sampled image `si` (image facts `image`) snapped by `snap` (module docs) on
/// The coordinate `coord` (`lanes` floats, in texels) of a sample or gather of sampled image `si` (image facts `image`) snapped by `snap` (module docs) on
/// the base level's size: a normalized coordinate. `offsets` holds, per plane axis, the constant
/// texel offset the device adds to the access (an `f32`, or `None`; [`snapped_axis`]), and
/// `parent` the slot's `SpecKey::OffsetBaseAxes` tests (`texture::OffsetBase`).
@@ -1004,9 +782,8 @@ pub fn snapped(
}
/// The coordinate `coord` (`lanes` floats) snapped by `snap` (module docs) on the base level's
/// size `size` of an image with facts `image`: a plane coordinate's axes, or a cube's direction
/// on its face's size, the size's first component. `offsets` holds each plane axis's constant
/// texel offset the device adds ([`snapped_axis`]; a cube has none), and `parent` the slot's
/// size `size` of an image with facts `image`: a plane coordinate's axes. `offsets` holds each
/// plane axis's constant texel offset the device adds ([`snapped_axis`]), and `parent` the slot's
/// `SpecKey::OffsetBaseAxes` tests (`texture::OffsetBase`).
pub fn snapped_on(
cx: &mut EmitCx<'_>,
@@ -1019,12 +796,7 @@ pub fn snapped_on(
let size_lanes = image.plane + u8::from(image.arrayed);
let kind = match snap.kind {
SnapKind::Axes(kind) => kind,
SnapKind::Cube(routines) => {
let routines = routines.declared();
let n = lane(fb, size, size_lanes, 0)?;
return super::face::snapped(fb, coord, n, (routines, snap.face_wrap()));
}
SnapKind::Word { .. } | SnapKind::WordGather { .. } | SnapKind::WordCell { .. } => {
SnapKind::WordGather | SnapKind::WordCell { .. } => {
return Err(cx.fail("a word snap without its sampler's word"))
}
};
@@ -1036,7 +808,7 @@ pub fn snapped_on(
let n = lane(fb, size, size_lanes, a)?;
let offset = offsets.get(a as usize).copied().flatten();
let parent = OffsetBase::axis(parent, a);
snapped_axis(fb, (kind, snap.pixel), u, n, (*address, offset, parent))?
snapped_axis(fb, kind, u, n, (*address, offset, parent))?
}
None => u,
});
@@ -1052,84 +824,6 @@ pub fn snapped_on(
fb.composite_construct(ty, &parts)
}
/// The coordinate `coord` (`lanes` normalized floats) of a runtime or argument buffer's sampler's
/// nearest sample, its sampler's word `word`, snapped by [`SnapKind::Word`] on the size `size`
/// (`size_lanes` components) of the level it reads: where the word masked by
/// `SamplerWord::NEAREST_BASE` is 0 (normalized coordinates, nearest filters, no mip filter, no
/// anisotropy: one texel of the base level, whatever the sampler's LOD clamps), or, for a sample at
/// a level the function knows (`leveled`), the word masked by `SamplerWord::NEAREST_LEVEL` is (no
/// mip filter or a nearest one: one texel of the level `level::snap_level` names), each plane axis
/// whose mode the word states as `Repeat`, `MirrorRepeat` or `MirrorClampToEdge` takes the centre
/// `(floor(X) + 1/2) / N` of the texel at Metal's position `X` ([`position_by_mode`]; a
/// mirror-clamped axis's taps the device mirrors once and clamps as Metal does); every other axis,
/// and every axis of any other sampler, keeps its coordinate, the device's as before. A snapped
/// axis whose size drops a constant texel offset (`offsets`, per plane axis an `f32` or `None`;
/// [`offset_dropped`]) moves the centre back by it, as [`snapped_axis`] does: a leveled snap's by
/// the level's size and the base level's, `base` (`size_lanes` components; `None`: the level is the
/// base level), a mirror-clamped axis's as a repeating one's, and by the slot's
/// `SpecKey::OffsetBaseAxes` tests `parent` (`texture::OffsetBase`).
pub fn snapped_by_word(
fb: &mut FunctionBuilder<'_>,
(word, leveled): (SValue, bool),
(coord, offsets, parent): (SValue, &[Option<SValue>], Option<OffsetBase>),
lanes: u8,
(size, base, size_lanes): (SValue, Option<SValue>, u8),
) -> BResult<SValue> {
use crate::metal::sampler::SamplerWord;
let zero = u32_const(fb, 0)?;
let reach = if leveled {
SamplerWord::NEAREST_LEVEL
} else {
SamplerWord::NEAREST_BASE
};
let mask = u32_const(fb, reach)?;
let masked = fb.binary(BinOp::BitwiseAnd, word, mask)?;
let reach = fb.binary(BinOp::IEqual, masked, zero)?;
let modes = u32_const(fb, 0b111)?;
let repeat = u32_const(fb, SamplerAddressMode::Repeat.as_raw())?;
let mirror = u32_const(fb, SamplerAddressMode::MirrorRepeat.as_raw())?;
let mirror_clamp = u32_const(fb, SamplerAddressMode::MirrorClampToEdge.as_raw())?;
let half = f32_const(fb, 0.5)?;
let mut parts = Vec::with_capacity(usize::from(lanes));
for (a, shift) in (0u32..)
.zip(SamplerWord::ADDRESS_SHIFT)
.take(usize::from(lanes))
{
let u = lane(fb, coord, lanes, a)?;
let n = lane(fb, size, size_lanes, a)?;
let sh = u32_const(fb, shift)?;
let mode = fb.binary(BinOp::ShiftRightLogical, word, sh)?;
let mode = fb.binary(BinOp::BitwiseAnd, mode, modes)?;
let (x, nf) = position_by_mode(fb, u, n, mode)?;
let i = fb.glsl(GlslOp::Floor, &[x])?;
let centre = fb.binary(BinOp::FAdd, i, half)?;
// Only a repeating, mirrored or mirror-clamped axis is snapped, so the sizes' rule alone
// decides.
let centre = match offsets.get(a as usize).copied().flatten() {
Some(o) => {
let nb = match base {
Some(b) => Some(lane(fb, b, size_lanes, a)?),
None => None,
};
let dropped = offset_dropped(fb, n, nb, OffsetBase::axis(parent, a))?;
let none = f32_const(fb, 0.0)?;
let back = fb.select(dropped, o, none)?;
fb.binary(BinOp::FSub, centre, back)?
}
None => centre,
};
let centre = fb.binary(BinOp::FDiv, centre, nf)?;
let repeats = fb.binary(BinOp::IEqual, mode, repeat)?;
let mirrors = fb.binary(BinOp::IEqual, mode, mirror)?;
let clamps_once = fb.binary(BinOp::IEqual, mode, mirror_clamp)?;
let wraps = fb.binary(BinOp::LogicalOr, repeats, mirrors)?;
let wraps = fb.binary(BinOp::LogicalOr, wraps, clamps_once)?;
let snaps = fb.binary(BinOp::LogicalAnd, reach, wraps)?;
parts.push(fb.select(snaps, centre, u)?);
}
composite(fb, parts)
}
/// The plane coordinate of `parts` (one `f32` per plane axis).
fn composite(fb: &mut FunctionBuilder<'_>, parts: Vec<SValue>) -> BResult<SValue> {
if let [x] = parts[..] {
@@ -1150,100 +844,56 @@ fn word_holds(fb: &mut FunctionBuilder<'_>, word: SValue, mask: u32) -> BResult<
fb.binary(BinOp::IEqual, have, m)
}
/// The coordinate of a runtime or argument buffer's sampler's gather of a 2D texture or array,
/// its sampler's word `word`, snapped by [`SnapKind::WordGather`] on the base level's size `size`
/// (`size_lanes` components): per plane axis the centre `(i0 + 1) / N` of the 2x2 block Metal reads
/// ([`AxisSnap::Gather`]), its base texel `i0` at Metal's position `X`, the coordinate as given
/// (`given`, `lanes` floats) where the word states pixel coordinates, else [`position_by_mode`]'s
/// by the axis's mode: a `MirrorClampToEdge` axis's is a clamping axis's, `u N` unwrapped, whose
/// taps the device mirrors once and clamps as Metal does (Apple M3 Max and M4). `i0` is clamped
/// into `[-2N - 10, 2N + 8]`, which holds every position of a repeating or mirrored axis, and past
/// which, with any offset in Metal's gather range `[-8, 7]`, both texels of a clamping or
/// mirror-clamped axis read the same edge texel or border, as the exact `i0`'s do. A repeating,
/// mirrored or mirror-clamped axis whose size drops a constant texel offset (`offsets`, per plane
/// axis an `f32` or `None`; [`offset_dropped`]) moves the centre back by it, as [`snapped_axis`]
/// does, a pixel word's mirror-clamped axis's too. On a device that samples through
/// Metal's own sampler (`metal`) only a pixel coordinate is snapped, and no offset moves it:
/// Metal's own sampler drops an offset of the normalized centre where it drops the pixel
/// coordinate's; a normalized one is the coordinate the device reads otherwise (`scaled`, `lanes`
/// floats), which Metal's own gather reads at Metal's position.
/// The coordinate of a runtime or argument buffer's sampler's 2D gather, its sampler's word
/// `word`, snapped by [`SnapKind::WordGather`] on the base level's size `size` (`size_lanes`
/// components): where the word states pixel coordinates, per plane axis the centre `(i0 + 1) / N`
/// of the 2x2 block Metal reads ([`AxisSnap::Gather`]), its base texel `i0` at Metal's position,
/// the coordinate as given (`given`, `lanes` floats); for a normalized word the coordinate the
/// device reads otherwise (`scaled`, `lanes` floats). `i0` is clamped into `[-2N - 10, 2N + 8]`,
/// past which, with any offset in Metal's gather range `[-8, 7]`, both texels of a clamping or
/// mirror-clamped axis read the same edge texel or border, as the exact `i0`'s do. The device's
/// sampler places an offset of the normalized centre (Metal's own drops it where it drops the
/// pixel coordinate's), so no offset moves it.
pub fn gathered_by_word(
fb: &mut FunctionBuilder<'_>,
(word, metal): (SValue, bool),
(given, scaled, offsets, parent): (SValue, SValue, &[Option<SValue>], Option<OffsetBase>),
word: SValue,
(given, scaled): (SValue, SValue),
lanes: u8,
(size, size_lanes): (SValue, u8),
) -> BResult<SValue> {
use crate::metal::sampler::SamplerWord;
let zero = u32_const(fb, 0)?;
let mask = u32_const(fb, SamplerWord::PIXEL_COORDINATES)?;
let p = fb.binary(BinOp::BitwiseAnd, word, mask)?;
let pixel = fb.binary(BinOp::INotEqual, p, zero)?;
let modes = u32_const(fb, 0b111)?;
let repeat = u32_const(fb, SamplerAddressMode::Repeat.as_raw())?;
let mirror = u32_const(fb, SamplerAddressMode::MirrorRepeat.as_raw())?;
let mirror_clamp = u32_const(fb, SamplerAddressMode::MirrorClampToEdge.as_raw())?;
let pixel = word_holds(fb, word, SamplerWord::PIXEL_COORDINATES)?;
let f = fb.module().ty(SType::Float { width: 32 })?;
let lo = f32_const(fb, -10.0)?;
let eight = f32_const(fb, 8.0)?;
let one = f32_const(fb, 1.0)?;
let mut parts = Vec::with_capacity(usize::from(lanes));
for (a, shift) in (0u32..)
.zip(SamplerWord::ADDRESS_SHIFT)
.take(usize::from(lanes))
{
let u = lane(fb, given, lanes, a)?;
for a in 0..u32::from(lanes) {
let x = lane(fb, given, lanes, a)?;
let device = lane(fb, scaled, lanes, a)?;
let n = lane(fb, size, size_lanes, a)?;
let sh = u32_const(fb, shift)?;
let mode = fb.binary(BinOp::ShiftRightLogical, word, sh)?;
let mode = fb.binary(BinOp::BitwiseAnd, mode, modes)?;
let (x, nf) = position_by_mode(fb, u, n, mode)?;
let x = fb.select(pixel, u, x)?;
let nf = fb.convert(ConvOp::ConvertUToF, n, f)?;
let i0 = gather_base(fb, x)?;
let twice = fb.binary(BinOp::FAdd, nf, nf)?;
let hi = fb.binary(BinOp::FAdd, twice, eight)?;
let low = fb.binary(BinOp::FSub, lo, twice)?;
let i0 = fb.glsl(GlslOp::FClamp, &[i0, low, hi])?;
let at = fb.binary(BinOp::FAdd, i0, one)?;
let at = match offsets.get(a as usize).copied().flatten() {
// Metal's own sampler places the offset of the normalized coordinate it is handed as
// Metal places a pixel coordinate's (a pixel word's axis clamps, or mirrors once and
// clamps, which drops the offset at the sizes a normalized one does).
Some(_) if metal => at,
Some(o) => {
// Metal drops the offset on a repeating, mirrored, or mirror-clamped axis whose
// size drops it (the mirror clamp's and a pixel word's measured by our probes).
let repeats = fb.binary(BinOp::IEqual, mode, repeat)?;
let mirrors = fb.binary(BinOp::IEqual, mode, mirror)?;
let clamps = fb.binary(BinOp::IEqual, mode, mirror_clamp)?;
let wraps = fb.binary(BinOp::LogicalOr, repeats, mirrors)?;
let wraps = fb.binary(BinOp::LogicalOr, wraps, clamps)?;
let dropped = offset_dropped(fb, n, None, OffsetBase::axis(parent, a))?;
let dropped = fb.binary(BinOp::LogicalAnd, dropped, wraps)?;
let none = f32_const(fb, 0.0)?;
let back = fb.select(dropped, o, none)?;
fb.binary(BinOp::FSub, at, back)?
}
None => at,
};
let centre = fb.binary(BinOp::FDiv, at, nf)?;
parts.push(match metal {
true => fb.select(pixel, centre, device)?,
false => centre,
});
parts.push(fb.select(pixel, centre, device)?);
}
composite(fb, parts)
}
/// The coordinate of a runtime or argument buffer's sampler's sample on a device that samples
/// through Metal's own sampler, its sampler's word `word`, snapped by [`SnapKind::WordCell`] on the
/// The coordinate of a runtime or argument buffer's sampler's sample, its sampler's word `word`,
/// snapped by [`SnapKind::WordCell`] on the
/// base level's size `size` (`size_lanes` components): where the word states pixel coordinates and
/// linear min and mag filters, each plane axis of the coordinate as given (`given`, `lanes` floats)
/// onto the centre of its footprint step ([`AxisSnap::Cell`]); for every other word the coordinate
/// the device reads otherwise (`scaled`). A pixel sampler clamps every axis or mirrors it once and
/// clamps it (`runtime::sampler`'s rule), and Metal's own sampler places a texel offset of the
/// normalized cell as Metal places the pixel coordinate's (kept on a clamping axis, dropped by a
/// mirror-clamped one's sizes alike), so no offset moves the cell.
/// clamps it (`runtime::sampler`'s rule), and the device's sampler places a texel offset of the
/// normalized cell (Metal's own as Metal places the pixel coordinate's: kept on a clamping axis,
/// dropped by a mirror-clamped one's sizes alike), so no offset moves the cell.
pub fn celled_by_word(
fb: &mut FunctionBuilder<'_>,
word: SValue,
@@ -1262,65 +912,11 @@ pub fn celled_by_word(
let x = lane(fb, given, lanes, a)?;
let device = lane(fb, scaled, lanes, a)?;
let n = lane(fb, size, size_lanes, a)?;
let cell = snapped_axis(
fb,
(AxisSnap::Cell, true),
x,
n,
(TapAddress::Edge, None, None),
)?;
let cell = snapped_axis(fb, AxisSnap::Cell, x, n, (TapAddress::Edge, None, None))?;
parts.push(fb.select(reach, cell, device)?);
}
composite(fb, parts)
}
/// The texel-space centre `centre` (`lanes` floats: `floor(x) + 1/2` of the pixel coordinate `x`)
/// of a runtime or argument buffer's pixel sampler's nearest sample, its sampler's word `word`, on
/// a device that adds a texel offset to the texel it reads before addressing it, moved back by each
/// texel offset (`offsets`, per plane axis an `f32` or `None`) that Metal drops: on an axis the
/// word states `MirrorClampToEdge` whose base level's size `size` (`size_lanes` components) drops
/// it ([`offset_dropped`]; Metal mirrors a pixel coordinate's taps once and clamps them, placing
/// its offset as a repeating axis does). Every other axis keeps its centre: a pixel
/// sampler's other axes clamp, where Metal keeps the offset.
pub fn pixel_centre_by_word(
fb: &mut FunctionBuilder<'_>,
word: SValue,
(centre, offsets, parent): (SValue, &[Option<SValue>], Option<OffsetBase>),
lanes: u8,
(size, size_lanes): (SValue, u8),
) -> BResult<SValue> {
use crate::metal::sampler::SamplerWord;
let modes = u32_const(fb, 0b111)?;
let mirror_clamp = u32_const(fb, SamplerAddressMode::MirrorClampToEdge.as_raw())?;
let mut parts = Vec::with_capacity(usize::from(lanes));
for (a, shift) in (0u32..)
.zip(SamplerWord::ADDRESS_SHIFT)
.take(usize::from(lanes))
{
let c = lane(fb, centre, lanes, a)?;
parts.push(match offsets.get(a as usize).copied().flatten() {
Some(o) => {
let n = lane(fb, size, size_lanes, a)?;
let sh = u32_const(fb, shift)?;
let mode = fb.binary(BinOp::ShiftRightLogical, word, sh)?;
let mode = fb.binary(BinOp::BitwiseAnd, mode, modes)?;
let clamps_once = fb.binary(BinOp::IEqual, mode, mirror_clamp)?;
let dropped = offset_dropped(fb, n, None, OffsetBase::axis(parent, a))?;
let dropped = fb.binary(BinOp::LogicalAnd, dropped, clamps_once)?;
let none = f32_const(fb, 0.0)?;
let back = fb.select(dropped, o, none)?;
fb.binary(BinOp::FSub, c, back)?
}
None => c,
});
}
composite(fb, parts)
}
/// The census words [`pixel_centre_by_word`] adds per plane axis that a texel offset moves: the
/// extractions, the mode's shift, mask and test, the offset rule ([`OFFSET_RULE_WORDS`]), the
/// conjunction, the select and the subtraction, and their constants.
pub const PIXEL_OFFSET_WORDS: u32 = OFFSET_RULE_WORDS + 72;
#[cfg(test)]
mod tests;
@@ -1,16 +1,13 @@
//! Metal's position and the snapped coordinates, run on the interpreter against the rule computed
//! exactly. Each kernel reads `(bits(u), n)` per invocation and writes the bits of [`position`]'s
//! `X` and of [`snapped_axis`]'s gather and nearest coordinates, for one addressing, and of its
//! gather and footprint-cell coordinates reading `u` as a pixel coordinate.
//! `X`, for one addressing, and of [`snapped_axis`]'s gather and footprint-cell coordinates reading
//! `u` as a pixel coordinate.
//!
//! The reference wraps `u` with the same `f32` operations Metal's rule names (they are exact or
//! rounded once, as on the device), forms the product `u' n` exactly in `f64` (at most 46
//! significant bits), and rounds it to `f32` with ties away from zero.
use super::{
celled_by_word, gathered_by_word, offset_dropped, pixel_centre_by_word, position, snapped_axis,
snapped_by_word, AxisSnap,
};
use super::{celled_by_word, gathered_by_word, offset_dropped, position, snapped_axis, AxisSnap};
use crate::air::abi::Coordinates;
use crate::air::intrinsics::ImageDim;
use crate::lower::sampler::bicubic::TapAddress;
@@ -61,10 +58,10 @@ fn word(f: &mut FunctionBuilder<'_>, buf: GlobalId, i: Value, per: u32, k: u32)
f.access_chain(base, &[zero, at])
}
/// A kernel whose invocation `i` reads `(bits(u), n)` from buffer 0 and writes `X`, the gather's
/// coordinate, the nearest sample's, and, reading `u` as a pixel coordinate, the gather's and the
/// footprint cell's, as bits, to buffer 1, for an axis addressed by `address` whose access the
/// device moves by the constant texel offset `offset` (0: none).
/// A kernel whose invocation `i` reads `(bits(u), n)` from buffer 0 and writes `X` and, reading `u`
/// as a pixel coordinate, the gather's and the footprint cell's coordinates, as bits, to buffer 1,
/// for an axis addressed by `address` whose access the device moves by the constant texel offset
/// `offset` (0: none).
fn kernel(address: TapAddress, offset: i32) -> BResult<TypedModule> {
let mut b = ModuleBuilder::new();
let f32_ = b.ty(Type::Float { width: 32 })?;
@@ -94,13 +91,11 @@ fn kernel(address: TapAddress, offset: i32) -> BResult<TypedModule> {
Some(super::f32_const(&mut f, offset as f32)?)
};
let at = (address, o, None);
let g = snapped_axis(&mut f, (AxisSnap::Gather, false), u, n, at)?;
let near = snapped_axis(&mut f, (AxisSnap::Nearest, false), u, n, at)?;
let pg = snapped_axis(&mut f, (AxisSnap::Gather, true), u, n, at)?;
let cell = snapped_axis(&mut f, (AxisSnap::Cell, true), u, n, at)?;
for (k, v) in [x, g, near, pg, cell].into_iter().enumerate() {
let pg = snapped_axis(&mut f, AxisSnap::Gather, u, n, at)?;
let cell = snapped_axis(&mut f, AxisSnap::Cell, u, n, at)?;
for (k, v) in [x, pg, cell].into_iter().enumerate() {
let bits = f.convert(ConvOp::Bitcast, v, u32_)?;
let at = word(&mut f, output, i, 5, k as u32)?;
let at = word(&mut f, output, i, 3, k as u32)?;
f.store(at, bits, MemAccess::default())?;
}
f.ret(None)?;
@@ -113,13 +108,13 @@ fn kernel(address: TapAddress, offset: i32) -> BResult<TypedModule> {
b.finalize()
}
/// The kernel's five words per lane `(u, n)`.
fn run(address: TapAddress, lanes: &[(f32, u32)]) -> Vec<[u32; 5]> {
/// The kernel's three words per lane `(u, n)`.
fn run(address: TapAddress, lanes: &[(f32, u32)]) -> Vec<[u32; 3]> {
run_offset(address, 0, lanes)
}
/// The kernel's five words per lane `(u, n)`, under the constant texel offset `offset`.
fn run_offset(address: TapAddress, offset: i32, lanes: &[(f32, u32)]) -> Vec<[u32; 5]> {
/// The kernel's three words per lane `(u, n)`, under the constant texel offset `offset`.
fn run_offset(address: TapAddress, offset: i32, lanes: &[(f32, u32)]) -> Vec<[u32; 3]> {
let m = kernel(address, offset).expect("kernel");
let bytes: Vec<u8> = lanes
.iter()
@@ -136,7 +131,7 @@ fn run_offset(address: TapAddress, offset: i32, lanes: &[(f32, u32)]) -> Vec<[u3
Buffer {
slot: Some(slot(1)),
address: None,
bytes: vec![0xAB; lanes.len() * 20],
bytes: vec![0xAB; lanes.len() * 12],
},
],
..Resources::default()
@@ -147,7 +142,7 @@ fn run_offset(address: TapAddress, offset: i32, lanes: &[(f32, u32)]) -> Vec<[u3
};
let (out, _) = interp::run_with_images(&m, &cfg, res, Vec::new()).expect("run");
out.buffers[1]
.as_chunks::<20>()
.as_chunks::<12>()
.0
.iter()
.map(|c| {
@@ -264,11 +259,6 @@ fn gather_coordinate(x: f32, n: u32, address: TapAddress) -> f32 {
(i0 as f32 + 1.0) / n as f32
}
/// The nearest sample's snapped coordinate.
fn nearest_coordinate(x: f32, n: u32) -> f32 {
(x.floor() + 0.5) / n as f32
}
const ADDRESSES: [TapAddress; 4] = [
TapAddress::Edge,
TapAddress::Border,
@@ -483,74 +473,6 @@ fn the_ties_hold_up_to_the_size_bound() {
}
}
/// The snapped coordinates, against `i0` and `floor(X)` computed exactly, on every lane of Metal's
/// sizes; each lies within `2^-7` of a texel of its target (the block's centre, the texel's
/// centre), half a texel from every edge the device's rounding could cross.
#[test]
fn the_snapped_coordinates_centre_metals_texels() {
let sizes = [1u32, 2, 3, 7, 12, 13, 255, 1000, 16383, 16384];
for address in ADDRESSES {
for n in sizes {
let all = lanes(n);
let step = (all.len() / 1500).max(1);
let picked: Vec<(f32, u32)> = all.into_iter().step_by(step).collect();
let out = run(address, &picked);
for (&(u, n), got) in picked.iter().zip(&out) {
let x = metal_x(u, n, address);
let g = gather_coordinate(x, n, address);
assert_eq!(
got[1],
g.to_bits(),
"{address:?} n {n} u {u:e}: gather {:e} vs {g:e}",
f32::from_bits(got[1])
);
let target = (g as f64 * f64::from(n)).round();
assert!((f64::from(g) * f64::from(n) - target).abs() <= 2f64.powi(-7));
if matches!(address, TapAddress::Repeat | TapAddress::Mirror) {
let c = nearest_coordinate(x, n);
assert_eq!(
got[2],
c.to_bits(),
"{address:?} n {n} u {u:e}: nearest {:e} vs {c:e}",
f32::from_bits(got[2])
);
let centre = f64::from(x.floor()) + 0.5;
assert!((f64::from(c) * f64::from(n) - centre).abs() <= 2f64.powi(-7));
}
}
}
}
}
/// The gather's `i0` in `f32` is exact below `|X| = 2^15`, which bounds every position of a
/// mirrored axis of Metal's largest size (`N = 2^14`, a power of two, whose wrap rounds down, so a
/// mirrored `u` a ulp below 0 lies at `X = 2^15 - 2^-9`): positions at and just below
/// each step of `i0` near the bound, and that largest position.
#[test]
fn the_gather_base_holds_up_to_the_position_bound() {
let n = 1u32 << 14;
let mut us = vec![-f32::from_bits(1 << 23)];
for i0 in [32_760i64, 32_765, 32_766, 32_767] {
// `i0` steps where `X` crosses `i0 + 1/2 - 1/512`.
let edge = i0 as f64 + 0.5 - 1.0 / 512.0;
for d in [-2.0, -1.0, 0.0, 1.0] {
let x = edge + d / 512.0;
us.push((x / f64::from(n)) as f32);
}
}
let lanes: Vec<(f32, u32)> = us.iter().map(|u| (*u, n)).collect();
let out = run(TapAddress::Mirror, &lanes);
let mut top = false;
for (&(u, n), got) in lanes.iter().zip(&out) {
let x = metal_x(u, n, TapAddress::Mirror);
assert!(f64::from(x) < 32_768.0);
top |= f64::from(x) == 32_768.0 - 1.0 / 512.0;
let g = gather_coordinate(x, n, TapAddress::Mirror);
assert_eq!(got[1], g.to_bits(), "u {u:e} X {x}");
}
assert!(top, "no lane at X = 2^15 - 2^-9");
}
/// A pixel coordinate `x` is Metal's position as given. Its gather's snapped coordinate is the
/// gather's at `X = x`, and its footprint cell's, `(q + 128) / 256 / n` for `q = floor(256 x -
/// 127.5)`, reads as a normalized coordinate (Metal's own sampler's position of it, ties away from
@@ -580,8 +502,8 @@ fn pixel_coordinate_snaps_read_metals_footprint() {
let out = run(address, &lanes);
for (&(x, n), got) in lanes.iter().zip(&out) {
let g = gather_coordinate(x, n, address);
assert_eq!(got[3], g.to_bits(), "{address:?} n {n} x {x:e}: gather");
let c = f32::from_bits(got[4]);
assert_eq!(got[1], g.to_bits(), "{address:?} n {n} x {x:e}: gather");
let c = f32::from_bits(got[2]);
assert_eq!(
q(metal_x(c, n, address)),
q(x),
@@ -855,11 +777,10 @@ fn the_offset_rule_reads_the_parent_s_base_through_the_view_bit() {
}
/// On a repeating or mirrored axis whose size is 3, 5, 6 or 7, Metal drops a texel offset the
/// device adds, so each snapped coordinate moves back by the offset there: the device's index at it
/// (`floor(c n - 1/2)` for a gather, `floor(c n)` for a nearest sample), plus the offset, is the
/// unmoved snap's. On every other size, and on every clamping axis, the offset leaves the snap as
/// it is (Metal adds it as the device does). Reading `u` as a pixel coordinate, the gather and the
/// footprint cell move back the same way.
/// device adds, so each snapped coordinate (reading `u` as a pixel coordinate) moves back by the
/// offset there: the device's index at a gather's (`floor(c n - 1/2)`), plus the offset, is the
/// unmoved snap's, and the footprint cell moves back the same way. On every other size, and on
/// every clamping axis, the offset leaves the snap as it is (Metal adds it as the device does).
#[test]
fn a_snap_moves_back_by_the_offset_metal_drops() {
let mut moved = 0usize;
@@ -882,34 +803,20 @@ fn a_snap_moves_back_by_the_offset_metal_drops() {
continue;
}
assert_eq!(got[0], was[0], "{at}: X");
let x = metal_x(u, n, address);
let g = (gather_i0(x) as f32 + 1.0 - back) / nf;
assert_eq!(got[1], g.to_bits(), "{at}: gather");
let c = (x.floor() + 0.5 - back) / nf;
assert_eq!(got[2], c.to_bits(), "{at}: nearest");
let pg = (gather_i0(u) as f32 + 1.0 - back) / nf;
assert_eq!(got[3], pg.to_bits(), "{at}: pixel gather");
assert_eq!(got[1], pg.to_bits(), "{at}: pixel gather");
let y = 256.0 * u;
let fl = y.floor();
let cell = (fl + if y - fl >= 0.5 { 1.0 } else { 0.0 }) * (1.0 / 256.0);
let cell = (cell - back) / nf;
assert_eq!(got[4], cell.to_bits(), "{at}: cell");
assert_eq!(got[2], cell.to_bits(), "{at}: cell");
// The device's index at the moved coordinate, plus the offset, is the
// unmoved one's.
let index = |bits: u32, gather: bool| {
let index = |bits: u32| {
let y = f64::from(f32::from_bits(bits)) * f64::from(n);
(if gather { y - 0.5 } else { y }).floor() as i64
(y - 0.5).floor() as i64
};
assert_eq!(
index(got[1], true) + i64::from(o),
index(was[1], true),
"{at}"
);
assert_eq!(
index(got[2], false) + i64::from(o),
index(was[2], false),
"{at}"
);
assert_eq!(index(got[1]) + i64::from(o), index(was[1]), "{at}");
moved += 1;
}
}
@@ -918,181 +825,15 @@ fn a_snap_moves_back_by_the_offset_metal_drops() {
assert!(moved > 0, "no lane moved back");
}
/// A kernel whose invocation `i` reads `(bits(u), n, word)` from buffer 0 and writes the bits of
/// [`snapped_by_word`]'s coordinate of a one-axis sample of size `n` (the size of the level it
/// reads) through a runtime sampler of word `word`, at a level the function knows or not
/// (`leveled`), to buffer 1.
fn word_kernel(leveled: bool) -> BResult<TypedModule> {
let mut b = ModuleBuilder::new();
let f32_ = b.ty(Type::Float { width: 32 })?;
let u32_ = b.ty(Type::Int {
width: 32,
signed: false,
})?;
let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?;
let input = storage_buffer(&mut b, 0, u32_)?;
let output = storage_buffer(&mut b, 1, u32_)?;
let id = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?;
let void = b.ty(Type::Void)?;
let mut f = b.function(void)?;
let gid = f.module().global_value(id)?;
let gid = f.load(gid, MemAccess::default())?;
let i = f.composite_extract(gid, &[0])?;
let at = word(&mut f, input, i, 3, 0)?;
let ub = f.load(at, MemAccess::default())?;
let u = f.convert(ConvOp::Bitcast, ub, f32_)?;
let at = word(&mut f, input, i, 3, 1)?;
let n = f.load(at, MemAccess::default())?;
let at = word(&mut f, input, i, 3, 2)?;
let w = f.load(at, MemAccess::default())?;
let c = snapped_by_word(&mut f, (w, leveled), (u, &[], None), 1, (n, None, 1))?;
let bits = f.convert(ConvOp::Bitcast, c, u32_)?;
let at = word(&mut f, output, i, 1, 0)?;
f.store(at, bits, MemAccess::default())?;
f.ret(None)?;
let main = f.finish()?;
b.entry(
ExecModel::GLCompute,
main,
vec![ExecMode::LocalSize { x: 1, y: 1, z: 1 }],
)?;
b.finalize()
}
/// The word kernel's coordinate bits per lane `(u, n, word)`, at a level the function knows or
/// not (`leveled`).
fn run_word(lanes: &[(f32, u32, u32)], leveled: bool) -> Vec<u32> {
let m = word_kernel(leveled).expect("kernel");
let bytes: Vec<u8> = lanes
.iter()
.flat_map(|(u, n, w)| [u.to_bits().to_le_bytes(), n.to_le_bytes(), w.to_le_bytes()])
.flatten()
.collect();
let res = Resources {
buffers: vec![
Buffer {
slot: Some(slot(0)),
address: None,
bytes,
},
Buffer {
slot: Some(slot(1)),
address: None,
bytes: vec![0xAB; lanes.len() * 4],
},
],
..Resources::default()
};
let cfg = Config {
workgroups: [u32::try_from(lanes.len()).expect("lanes"), 1, 1],
..Config::default()
};
let (out, _) = interp::run_with_images(&m, &cfg, res, Vec::new()).expect("run");
out.buffers[1]
.as_chunks::<4>()
.0
.iter()
.map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]))
.collect()
}
/// A runtime sampler's word snap hands the device the centre of Metal's texel, bit for bit as the
/// constexpr nearest snap does, on an axis whose word repeats or mirrors, or mirrors once and
/// clamps (a clamping axis's position), where the word reads the base level (normalized, nearest,
/// no mip filter, isotropic, whatever else it states); the coordinate as given on a clamping axis,
/// and for any word that filters linearly, takes pixel coordinates, a mip filter, or anisotropy.
#[test]
fn the_word_snap_centres_metals_texels_where_the_word_reads_the_base_level() {
word_snap_reaches(false);
}
/// At a level the function knows, a runtime sampler's word snap reaches a nearest mip filter's
/// sample too (the size is that level's, `level::snap_level`), and nothing else more: a linear mip
/// filter's two levels keep the coordinate.
#[test]
fn a_leveled_word_snap_centres_metals_texels_where_the_word_reads_one_level() {
word_snap_reaches(true);
}
/// The word snap's coordinates against the host's, for words that reach it and words that do not,
/// at a level the function knows or not (`leveled`).
fn word_snap_reaches(leveled: bool) {
use crate::metal::sampler::SamplerWord;
use crate::metal::SamplerAddressMode as M;
let modes = [
(M::ClampToEdge, None),
(M::MirrorClampToEdge, Some(TapAddress::Edge)),
(M::Repeat, Some(TapAddress::Repeat)),
(M::MirrorRepeat, Some(TapAddress::Mirror)),
(M::ClampToZero, None),
(M::ClampToBorderColor, None),
];
// Base-level words: the default, and one with every field the reach ignores set.
let ignored = SamplerWord::ADDRESS[1]
| SamplerWord::ADDRESS[2]
| SamplerWord::BORDER
| SamplerWord::COMPARE
| SamplerWord::REDUCTION;
let nearest_mip = 1 << SamplerWord::MIP_FILTER_SHIFT;
let others = [
SamplerWord::PIXEL_COORDINATES,
SamplerWord::MIN_LINEAR,
SamplerWord::MAG_LINEAR,
nearest_mip,
2 << SamplerWord::MIP_FILTER_SHIFT,
SamplerWord::ANISOTROPIC,
nearest_mip | SamplerWord::MIN_LINEAR,
SamplerWord::LEVEL_MIN | SamplerWord::LEVEL_MAX,
];
let mut checked = 0;
for n in [3u32, 13, 16, 255] {
let all = lanes(n);
let step = (all.len() / 300).max(1);
let us: Vec<f32> = all.into_iter().step_by(step).map(|(u, _)| u).collect();
for (mode, address) in modes {
let m = mode.as_raw() << SamplerWord::ADDRESS_SHIFT[0];
let mut words: Vec<(u32, bool)> = vec![(m, true), (m | ignored, true)];
words.extend(others.iter().map(|&o| {
// A clamp's levels are ignored; a nearest mip filter's one level reaches a
// leveled snap alone.
let reach = o == SamplerWord::LEVEL_MIN | SamplerWord::LEVEL_MAX
|| (leveled && o == nearest_mip);
(m | o, reach)
}));
let picked: Vec<(f32, u32, u32)> = words
.iter()
.flat_map(|&(w, _)| us.iter().map(move |&u| (u, n, w)))
.collect();
let out = run_word(&picked, leveled);
for (&(u, n, w), &got) in picked.iter().zip(&out) {
let base = words.iter().any(|&(x, b)| x == w && b);
let want = match (address, base) {
(Some(a), true) => nearest_coordinate(metal_x(u, n, a), n),
_ => u,
};
assert_eq!(
got,
want.to_bits(),
"{mode:?} n {n} word {w:#x} u {u:e}: {:e} vs {want:e}",
f32::from_bits(got)
);
checked += 1;
}
}
}
assert!(checked > 10_000, "{checked}");
}
/// The coordinate the word kernels hand the device where their snap does not reach a lane: a
/// marker no snap yields.
const DEVICE: f32 = -12345.0;
/// A kernel whose invocation `i` reads `(bits(u), n, word)` from buffer 0 and writes the bits of
/// [`gathered_by_word`]'s coordinate of a one-axis gather of size `n` through a runtime sampler of
/// word `word`, on a device with Metal's own sampler or not (`metal`), whose access the device
/// moves by the constant texel offset `offset` (0: none), and of [`celled_by_word`]'s, each
/// handing [`DEVICE`] as the coordinate the device reads otherwise, to buffer 1.
fn word_gather_kernel(metal: bool, offset: i32) -> BResult<TypedModule> {
/// word `word`, and of [`celled_by_word`]'s, each handing [`DEVICE`] as the coordinate the device
/// reads otherwise, to buffer 1.
fn word_gather_kernel() -> BResult<TypedModule> {
let mut b = ModuleBuilder::new();
let f32_ = b.ty(Type::Float { width: 32 })?;
let u32_ = b.ty(Type::Int {
@@ -1116,11 +857,7 @@ fn word_gather_kernel(metal: bool, offset: i32) -> BResult<TypedModule> {
let at = word(&mut f, input, i, 3, 2)?;
let w = f.load(at, MemAccess::default())?;
let device = super::f32_const(&mut f, DEVICE)?;
let o = match offset {
0 => None,
o => Some(super::f32_const(&mut f, o as f32)?),
};
let g = gathered_by_word(&mut f, (w, metal), (u, device, &[o], None), 1, (n, 1))?;
let g = gathered_by_word(&mut f, w, (u, device), 1, (n, 1))?;
let c = celled_by_word(&mut f, w, (u, device), 1, (n, 1))?;
for (k, v) in [g, c].into_iter().enumerate() {
let bits = f.convert(ConvOp::Bitcast, v, u32_)?;
@@ -1138,8 +875,8 @@ fn word_gather_kernel(metal: bool, offset: i32) -> BResult<TypedModule> {
}
/// The word gather kernel's two coordinates' bits per lane `(u, n, word)`.
fn run_word_gather(lanes: &[(f32, u32, u32)], metal: bool, offset: i32) -> Vec<[u32; 2]> {
let m = word_gather_kernel(metal, offset).expect("kernel");
fn run_word_gather(lanes: &[(f32, u32, u32)]) -> Vec<[u32; 2]> {
let m = word_gather_kernel().expect("kernel");
let bytes: Vec<u8> = lanes
.iter()
.flat_map(|(u, n, w)| [u.to_bits().to_le_bytes(), n.to_le_bytes(), w.to_le_bytes()])
@@ -1177,28 +914,22 @@ fn run_word_gather(lanes: &[(f32, u32, u32)], metal: bool, offset: i32) -> Vec<[
.collect()
}
/// A runtime sampler's gather hands the device the centre of the 2x2 block Metal reads, by its
/// word: at Metal's position by the axis's mode for a normalized word (the constexpr gather's snap,
/// bit for bit, but for its wider clamp of `i0`, which reads the same edge texels or border; a
/// `MirrorClampToEdge` axis's a clamping axis's), at the coordinate as given for a
/// pixel word, its index moved back by an offset where a repeating, mirrored or mirror-clamped
/// axis's size drops it; on a device with Metal's own sampler it snaps a pixel word alone, never
/// moved by an offset, which that sampler places as Metal places a pixel coordinate's. A word's
/// other fields leave it as it is. The footprint-cell snap takes the centre of the step Metal reads
/// the coordinate as given at where the word states a linear pixel sampler, and the device's
/// coordinate for every other word.
/// A runtime sampler's gather hands the device the centre of the 2x2 block Metal reads at the
/// coordinate as given where its word states pixel coordinates, and the device's coordinate for a
/// normalized word; a word's other fields leave it as it is. The footprint-cell snap takes the
/// centre of the step Metal reads the coordinate as given at where the word states a linear pixel
/// sampler, and the device's coordinate for every other word.
#[test]
fn a_runtime_samplers_gather_centres_metals_block_by_its_word() {
use crate::metal::sampler::SamplerWord;
use crate::metal::SamplerAddressMode as M;
let modes = [
(M::ClampToEdge, Some(TapAddress::Edge)),
// Its position is a clamping axis's.
(M::MirrorClampToEdge, Some(TapAddress::Edge)),
(M::Repeat, Some(TapAddress::Repeat)),
(M::MirrorRepeat, Some(TapAddress::Mirror)),
(M::ClampToZero, Some(TapAddress::Border)),
(M::ClampToBorderColor, Some(TapAddress::Border)),
M::ClampToEdge,
M::MirrorClampToEdge,
M::Repeat,
M::MirrorRepeat,
M::ClampToZero,
M::ClampToBorderColor,
];
// Fields the gather ignores: the filters, the mip filter, the `t` and `r` modes, the border,
// the comparison, the reduction, anisotropy and the level clamps.
@@ -1216,214 +947,75 @@ fn a_runtime_samplers_gather_centres_metals_block_by_its_word() {
let linear_pixel =
SamplerWord::PIXEL_COORDINATES | SamplerWord::MIN_LINEAR | SamplerWord::MAG_LINEAR;
let mut checked = 0usize;
for (metal, offset) in [
(false, 0i32),
(false, -3),
(false, 2),
(true, 0),
(true, -3),
] {
for n in [1u32, 3, 7, 13, 16, 255, 16383] {
let all = lanes(n);
let step = (all.len() / 60).max(1);
let us: Vec<f32> = all.into_iter().step_by(step).map(|(u, _)| u).collect();
let mut picked = Vec::new();
for (mode, _) in modes {
let m = mode.as_raw() << SamplerWord::ADDRESS_SHIFT[0];
for w in [
m,
m | ignored,
m | SamplerWord::PIXEL_COORDINATES,
m | linear_pixel,
m | SamplerWord::PIXEL_COORDINATES | SamplerWord::MIN_LINEAR,
] {
picked.extend(us.iter().map(|&u| (u, n, w)));
}
}
// Pixel coordinates around the steps and edges of the texels near the level.
for k in -12i64..=i64::from(n.min(40)) + 12 {
for base in [k as f32, k as f32 + 0.5 - 1.0 / 512.0, k as f32 + 0.25] {
for x in [base, base.next_down(), base.next_up()] {
for w in [SamplerWord::PIXEL_COORDINATES, linear_pixel] {
picked.push((x, n, w));
}
}
}
}
let out = run_word_gather(&picked, metal, offset);
let nf = n as f32;
for (&(u, n, w), got) in picked.iter().zip(&out) {
let at = format!("metal {metal} offset {offset} n {n} word {w:#x} u {u:e}");
let pixel = w & SamplerWord::PIXEL_COORDINATES != 0;
let raw = (w >> SamplerWord::ADDRESS_SHIFT[0]) & 0b111;
let address = modes
.iter()
.find(|(m, _)| m.as_raw() == raw)
.and_then(|&(_, a)| a);
let snapped = match (pixel, address) {
(true, _) => Some(u),
(false, Some(a)) if !metal => Some(metal_x(u, n, a)),
(false, _) => None,
};
let want = match snapped {
Some(x) => {
let i0 = gather_i0(x).clamp(-2 * i64::from(n) - 10, 2 * i64::from(n) + 8);
let wraps =
matches!(address, Some(TapAddress::Repeat | TapAddress::Mirror))
|| raw == M::MirrorClampToEdge.as_raw();
// Metal's own sampler places the offset itself.
let back = if offset != 0 && wraps && !metal && matches!(n, 3 | 5 | 6 | 7) {
offset as f32
} else {
0.0
};
(i0 as f32 + 1.0 - back) / nf
}
None => DEVICE,
};
assert_eq!(
got[0],
want.to_bits(),
"{at}: gather {:e} vs {want:e}",
f32::from_bits(got[0])
);
if let Some(x) = snapped {
// The device reads the block at `i0`, as Metal does.
let c = f64::from(f32::from_bits(got[0])) * f64::from(n);
let i0 = gather_i0(x).clamp(-2 * i64::from(n) - 10, 2 * i64::from(n) + 8);
assert!((c - (i0 + 1) as f64).abs() <= 2f64.powi(-7) + 8.0, "{at}");
}
let cell = if w & linear_pixel == linear_pixel {
let y = 256.0 * u;
let fl = y.floor();
((fl + if y - fl >= 0.5 { 1.0 } else { 0.0 }) * (1.0 / 256.0)) / nf
} else {
DEVICE
};
assert_eq!(
got[1],
cell.to_bits(),
"{at}: cell {:e} vs {cell:e}",
f32::from_bits(got[1])
);
checked += 1;
}
}
}
assert!(checked > 30_000, "{checked}");
}
/// A kernel whose invocation `i` reads `(bits(c), n, word)` from buffer 0 and writes the bits of
/// [`pixel_centre_by_word`]'s centre of a one-axis texel centre `c` on a level of `n` texels
/// through a runtime pixel sampler of word `word`, whose access the device moves by the constant
/// texel offset `offset`, to buffer 1.
fn pixel_centre_kernel(offset: i32) -> BResult<TypedModule> {
let mut b = ModuleBuilder::new();
let f32_ = b.ty(Type::Float { width: 32 })?;
let u32_ = b.ty(Type::Int {
width: 32,
signed: false,
})?;
let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?;
let input = storage_buffer(&mut b, 0, u32_)?;
let output = storage_buffer(&mut b, 1, u32_)?;
let id = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?;
let void = b.ty(Type::Void)?;
let mut f = b.function(void)?;
let gid = f.module().global_value(id)?;
let gid = f.load(gid, MemAccess::default())?;
let i = f.composite_extract(gid, &[0])?;
let at = word(&mut f, input, i, 3, 0)?;
let cb = f.load(at, MemAccess::default())?;
let c = f.convert(ConvOp::Bitcast, cb, f32_)?;
let at = word(&mut f, input, i, 3, 1)?;
let n = f.load(at, MemAccess::default())?;
let at = word(&mut f, input, i, 3, 2)?;
let w = f.load(at, MemAccess::default())?;
let o = match offset {
0 => None,
o => Some(super::f32_const(&mut f, o as f32)?),
};
let moved = pixel_centre_by_word(&mut f, w, (c, &[o], None), 1, (n, 1))?;
let bits = f.convert(ConvOp::Bitcast, moved, u32_)?;
let at = word(&mut f, output, i, 1, 0)?;
f.store(at, bits, MemAccess::default())?;
f.ret(None)?;
let main = f.finish()?;
b.entry(
ExecModel::GLCompute,
main,
vec![ExecMode::LocalSize { x: 1, y: 1, z: 1 }],
)?;
b.finalize()
}
/// A runtime pixel sampler's nearest texel centre moves back by a texel offset Metal drops, which
/// the device adds: on an axis the word states `MirrorClampToEdge` whose size is 3, 5, 6 or 7;
/// every other axis, size, offset and mode keeps its centre.
#[test]
fn a_pixel_centre_moves_back_by_an_offset_metal_drops_on_a_mirror_clamped_axis() {
use crate::metal::sampler::SamplerWord;
use crate::metal::SamplerAddressMode as M;
let modes = [
M::ClampToEdge,
M::MirrorClampToEdge,
M::ClampToZero,
M::ClampToBorderColor,
];
let mut checked = 0usize;
for offset in [0i32, -3, 2, -7, 5] {
for n in [1u32, 3, 7, 13, 16, 255, 16383] {
let all = lanes(n);
let step = (all.len() / 60).max(1);
let us: Vec<f32> = all.into_iter().step_by(step).map(|(u, _)| u).collect();
let mut picked = Vec::new();
for n in [1u32, 2, 3, 4, 5, 6, 7, 8, 13, 255] {
for mode in modes {
let w = SamplerWord::PIXEL_COORDINATES
| mode.as_raw() << SamplerWord::ADDRESS_SHIFT[0]
| M::MirrorClampToEdge.as_raw() << SamplerWord::ADDRESS_SHIFT[1];
for k in -20i32..=20 {
picked.push((k as f32 + 0.5, n, w));
for mode in modes {
let m = mode.as_raw() << SamplerWord::ADDRESS_SHIFT[0];
for w in [
m,
m | ignored,
m | SamplerWord::PIXEL_COORDINATES,
m | linear_pixel,
m | SamplerWord::PIXEL_COORDINATES | SamplerWord::MIN_LINEAR,
] {
picked.extend(us.iter().map(|&u| (u, n, w)));
}
}
// Pixel coordinates around the steps and edges of the texels near the level.
for k in -12i64..=i64::from(n.min(40)) + 12 {
for base in [k as f32, k as f32 + 0.5 - 1.0 / 512.0, k as f32 + 0.25] {
for x in [base, base.next_down(), base.next_up()] {
for w in [SamplerWord::PIXEL_COORDINATES, linear_pixel] {
picked.push((x, n, w));
}
}
}
}
let m = pixel_centre_kernel(offset).expect("kernel");
let bytes: Vec<u8> = picked
.iter()
.flat_map(|(c, n, w)| [c.to_bits().to_le_bytes(), n.to_le_bytes(), w.to_le_bytes()])
.flatten()
.collect();
let res = Resources {
buffers: vec![
Buffer {
slot: Some(slot(0)),
address: None,
bytes,
},
Buffer {
slot: Some(slot(1)),
address: None,
bytes: vec![0xAB; picked.len() * 4],
},
],
..Resources::default()
};
let cfg = Config {
workgroups: [u32::try_from(picked.len()).expect("lanes"), 1, 1],
..Config::default()
};
let (out, _) = interp::run_with_images(&m, &cfg, res, Vec::new()).expect("run");
for (&(c, n, w), got) in picked.iter().zip(out.buffers[1].as_chunks::<4>().0.iter()) {
let got = f32::from_le_bytes([got[0], got[1], got[2], got[3]]);
let raw = (w >> SamplerWord::ADDRESS_SHIFT[0]) & 0b111;
let dropped = raw == M::MirrorClampToEdge.as_raw() && matches!(n, 3 | 5 | 6 | 7);
let want = if dropped { c - offset as f32 } else { c };
let out = run_word_gather(&picked);
let nf = n as f32;
for (&(u, n, w), got) in picked.iter().zip(&out) {
let at = format!("n {n} word {w:#x} u {u:e}");
let pixel = w & SamplerWord::PIXEL_COORDINATES != 0;
let snapped = pixel.then_some(u);
let want = match snapped {
Some(x) => {
let i0 = gather_i0(x).clamp(-2 * i64::from(n) - 10, 2 * i64::from(n) + 8);
(i0 as f32 + 1.0) / nf
}
None => DEVICE,
};
assert_eq!(
got.to_bits(),
got[0],
want.to_bits(),
"offset {offset} n {n} word {w:#x} c {c}: {got} vs {want}"
"{at}: gather {:e} vs {want:e}",
f32::from_bits(got[0])
);
if let Some(x) = snapped {
// The device reads the block at `i0`, as Metal does.
let c = f64::from(f32::from_bits(got[0])) * f64::from(n);
let i0 = gather_i0(x).clamp(-2 * i64::from(n) - 10, 2 * i64::from(n) + 8);
assert!((c - (i0 + 1) as f64).abs() <= 2f64.powi(-7) + 8.0, "{at}");
}
let cell = if w & linear_pixel == linear_pixel {
let y = 256.0 * u;
let fl = y.floor();
((fl + if y - fl >= 0.5 { 1.0 } else { 0.0 }) * (1.0 / 256.0)) / nf
} else {
DEVICE
};
assert_eq!(
got[1],
cell.to_bits(),
"{at}: cell {:e} vs {cell:e}",
f32::from_bits(got[1])
);
checked += 1;
}
}
assert!(checked > 5_000, "{checked}");
assert!(checked > 15_000, "{checked}");
}
/// A kernel whose invocation `i` reads the bits of a two-lane coordinate from buffer 0 and writes
+14 -214
View File
@@ -1,22 +1,14 @@
//! The sampling routines: the emulation a combined binding's sample shape takes, defined once in
//! the module and called by every sample of that shape with its plain data.
//!
//! **Why.** On a device without `VkProperty::MetalSampler` each linear sample of a measured
//! format is Metal's filter emulated by fetches (`linear`), and a nearest sample of a 32-bit float
//! texture through a runtime sampler fetches its texel (`fetched`). Written at every site, that
//! code made the consumer's CoreAnimation fragment `Xgc` 246,000 instructions from 15,800 AIR
//! instructions, about 574 instructions a sample site and 78% of the module; NVIDIA's driver
//! compiled every copy, 13 to 26 s a pipeline on the RTX 5080. The same emulation as one routine
//! that 256 sites call, declared `DontInline`, made in 0.39 s on the RTX 3090 where the 256 inlined
//! copies took 10.2 s.
//! **Why.** An emulation written at every sample site is compiled again at every site: the
//! consumer's CoreAnimation fragment `Xgc`, a linear filter emulated at each of its 256 sample
//! sites, was 246,000 instructions from 15,800 AIR instructions, about 574 instructions a sample
//! site; NVIDIA's driver compiled every copy, 13 to 26 s a pipeline on the RTX 5080. The same
//! emulation as one routine that 256 sites call, declared `DontInline`, made in 0.39 s on the RTX
//! 3090 where the 256 inlined copies took 10.2 s.
//!
//! **What a routine holds.** One per shape ([`Shape`]):
//! - [`Emulation`]: a linear sample's emulated arm (`linear::emit`): Metal's position of the
//! coordinate and its quantization, each tap's addressing (a runtime sampler's under every mode
//! its word may state), the border, the fetches, and the sums' calls (`linear::sum`), a cube's
//! face position and fold, and a comparison's tap tests.
//! - [`Fetched`]: a sample's nearest-exact fetch arm (`fetched::branch`): the level its sampler
//! reads, the texel's position and addressing, the border, and the fetch.
//! - [`Filter`]: Metal's anisotropic filter emulated (`anisotropic`): the level-0 size and level
//! count, the sampler's degree and mip filter, the footprint, and the taps' samples at explicit
//! levels and their sum.
@@ -26,15 +18,9 @@
//!
//! The routine reads its binding's image and sampler variables and its slots' specialization
//! constants (the runtime sampler's word, the offset tests) itself, so no image handle crosses a
//! call, and a device's specialization folds its arithmetic as it folded each site's. The call
//! passes what the site computes in its own position: the coordinate, the array layer, a cube's
//! direction (its ties broken), a comparison's reference, and a fetch's level operand; a constant
//! texel offset with a lane off zero, whose every lane the routine places by Metal's rule, where a
//! 0 lane adds nothing, so the sites of one binding at different offsets call one routine; and the
//! bound format's class, which a function reads as data (`SpecKey::TexelFormat`), as the sums'
//! routines take it. The site keeps the class and word tests, the branch, the device's sample with
//! its level, bias or gradients, and the texel's conversion: no implicit level crosses a call, and
//! each arm is the code it was, so every answer is the one the inline code gave.
//! call, and a device's specialization folds its arithmetic as it folded each site's. The site
//! keeps the word's tests, the device's sample with its level, bias or gradients, and the texel's
//! conversion: no implicit level crosses a call, so every answer is the one the inline code gave.
//!
//! An anisotropic sample's call passes its coordinate (a cube's direction, its ties broken), its
//! gradients (a cube's on its face) and a cube's face steps, the array layer and the
@@ -64,25 +50,20 @@
//! default, whose code and answers are the same. Mesa's drivers inline every function whatever it
//! states, so there the module is smaller and the pipeline the same.
//!
//! **Census**. A routine's words are counted once per shape the plan notes ([`note`],
//! `sampler::routine_words`), under `sampler.linear.routine` and `sampler.fetch.routine`; the
//! site counts its call ([`CALL_WORDS`]) where it counted the code; an extended-range sample's
//! routine is counted under `sampler.extended_range.routine` (`extended::Sample::words` its
//! site's). The census counts no anisotropic emulation, at its sites or in a routine.
//! **Census**. An extended-range sample's routine is counted once per shape the plan notes
//! ([`note_extended`], `sampler::routine_words`), under `sampler.extended_range.routine`
//! (`extended::Sample::words` its site's). The census counts no anisotropic emulation, at its
//! sites or in a routine.
use std::collections::HashMap;
use crate::lower::texture::TexelConv;
use crate::metal::format::ExtendedRange;
use crate::spirv::ids::{FuncId, TypeId};
use super::anisotropic::Anisotropic;
use super::bicubic::Bicubic;
use super::extended;
use super::fetched::{Fetch, FetchAddress, FetchLevel};
use super::level::{LevelRule, LevelSnap};
use super::linear::{Linear, LinearState};
use super::{BindingKey, SampleOp, SamplerPlan, Sampling, Source};
use super::{BindingKey, SamplerPlan};
/// The estimated words a routine adds besides its body: `OpFunction`, its parameters, the entry
/// label, the return, and `OpFunctionEnd`.
@@ -96,10 +77,6 @@ pub const CALL_WORDS: u32 = 32;
/// argument types.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Shape {
/// A linear sample's emulated arm (`linear::emit`).
Emulation(Emulation),
/// A sample's nearest-exact fetch arm (`fetched::branch`).
Fetched(Fetched),
/// Metal's anisotropic filter emulated (`anisotropic`).
Anisotropic(Filter),
/// An extended-range texture's sample (`extended`).
@@ -110,8 +87,6 @@ impl Shape {
/// The census name of the shape's routines.
pub fn census_name(&self) -> &'static str {
match self {
Shape::Emulation(_) => "sampler.linear.routine",
Shape::Fetched(_) => "sampler.fetch.routine",
Shape::Anisotropic(_) => "sampler.anisotropic.routine",
Shape::Extended(_) => "sampler.extended_range.routine",
}
@@ -121,63 +96,12 @@ impl Shape {
/// the function's own.
pub fn words(&self) -> u32 {
match self {
Shape::Emulation(e) => e.linear.words() + offset_words(e.offset) + ROUTINE_WORDS,
Shape::Fetched(f) => f.words + offset_words(f.offset) + ROUTINE_WORDS,
Shape::Anisotropic(_) => FILTER_WORDS + ROUTINE_WORDS,
Shape::Extended(e) => e.words + ROUTINE_WORDS,
}
}
}
/// A linear sample's emulated arm (`linear::emit`).
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Emulation {
/// The sample's own combined binding, whose image facts the footprint reads.
pub own: BindingKey,
/// The binding the taps are fetched through: a comparison's without comparison, a runtime
/// sampler's raw view (`Linear::fetch`), else the sample's own.
pub taps: BindingKey,
/// The emulation's plan, without its constant texel offset, which the call passes.
pub linear: Linear,
/// The lanes of the texel offset the call passes, where the sample's has a lane off zero.
pub offset: Option<u8>,
/// The result is `half`.
pub half: bool,
/// The emulation places a texel offset by its slot's `OffsetBaseAxes` tests.
pub parent: bool,
/// The sample reads an array's layer.
pub layer: bool,
}
impl Emulation {
/// The emulated arm sample `s` calls: a linear sample of a texture slot through its combined
/// binding that Metal's filter answers by fetches (`Sampling::linear`); `None` for any other.
pub(super) fn of(s: &Sampling) -> Option<Emulation> {
let (Source::Combined(own), Some(l)) = (s.source, s.linear.as_ref()) else {
return None;
};
l.image.slot()?;
let half = s.texel?.conv == TexelConv::F16;
// A constexpr sampler's raw emulation reads the sample's own binding, the raw view.
let taps = match (l.raw, &l.state, l.fetch) {
(true, LinearState::Constant { .. }, _) | (_, _, None) => own,
(_, _, Some(k)) => k,
};
Some(Emulation {
own,
taps,
linear: Linear {
offset: None,
..l.clone()
},
offset: passed(l.offset.as_deref()),
half,
parent: s.offset_base,
layer: s.layer.is_some(),
})
}
}
/// The estimated words of an anisotropic emulation's body (`anisotropic`), its taps past the first
/// in one loop: about 2,100 measured on a runtime slot's.
pub const FILTER_WORDS: u32 = 2_400;
@@ -276,130 +200,6 @@ pub(super) fn note_extended(plan: &mut SamplerPlan, e: &extended::Sample) {
}
}
/// A sample's nearest-exact fetch arm (`fetched::branch`): one texel of the level its sampler
/// reads.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Fetched {
/// The combined binding whose image the texel is fetched from.
pub binding: BindingKey,
/// The texture slot whose `TexelFormat` specialization its border texel reads.
pub texture: u32,
/// How the tap is addressed.
pub address: FetchAddress,
/// The lanes of Metal's constant texel offset, which the call passes, where it has a lane off
/// zero.
pub offset: Option<u8>,
/// The level read.
pub level: Level,
/// The fetch places a texel offset by its slot's `OffsetBaseAxes` tests.
pub parent: bool,
/// The sample reads an array's layer.
pub layer: bool,
/// The fetch's estimated words without its offset (`Fetch::words`).
pub words: u32,
}
/// The level a [`Fetched`] routine reads: `fetched::FetchLevel` without the call's operand,
/// which the call passes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Level {
/// A level known when the function compiles.
Fixed(u32),
/// `floor` of the level a constexpr sampler's snap hands the device for the operand.
Snapped(LevelSnap),
/// The level a runtime sampler's word reads at the operand, or at level 0 without one.
Word { operand: bool },
}
impl Fetched {
/// The fetch arm of sample `s` fetching as `f` from texture slot `texture` through combined
/// binding `binding`; `None` for a gather (four texels) or a blend of two levels.
pub(super) fn of(
s: &Sampling,
binding: BindingKey,
texture: u32,
f: &Fetch,
) -> Option<Fetched> {
if !matches!(s.op, SampleOp::Sample { .. }) {
return None;
}
let level = match f.level {
FetchLevel::Fixed(n) => Level::Fixed(n),
FetchLevel::Snapped(_) => match s.level {
Some(LevelRule::Stated(snap)) => Level::Snapped(snap),
_ => return None,
},
FetchLevel::Word(v) => Level::Word {
operand: v.is_some(),
},
FetchLevel::Blend(..) => return None,
};
let words = Fetch {
offset: None,
..f.clone()
}
.words(&s.op);
Some(Fetched {
binding,
texture,
address: f.address.clone(),
offset: passed(f.offset.as_deref()),
level,
parent: s.offset_base,
layer: s.layer.is_some(),
words,
})
}
/// The fetch arm a plain nearest sample `s` calls (`Sampling::fetched` on its slot, through
/// its own combined binding), which a linear sample's device arm calls too.
pub(super) fn plain(s: &Sampling) -> Option<Fetched> {
let (Source::Combined(key), Some(p)) = (s.source, s.fetched.as_ref()) else {
return None;
};
let texture = p.image.slot()?;
Fetched::of(s, key, texture, &p.fetch)
}
}
/// The lanes of constant texel offset `offset` a routine's call passes: `None` where no lane is off
/// zero, which places nothing.
fn passed(offset: Option<&[i32]>) -> Option<u8> {
let o = offset.filter(|o| o.iter().any(|o| *o != 0))?;
u8::try_from(o.len()).ok()
}
/// The estimated words of placing a routine's offset of `lanes` lanes: Metal's offset rule on
/// each (`position::OFFSET_RULE_WORDS`).
fn offset_words(lanes: Option<u8>) -> u32 {
lanes.map_or(0, u32::from) * super::position::OFFSET_RULE_WORDS
}
/// Note the routines sampling `s` calls in `plan`, each shape once, for the census.
pub(super) fn note(plan: &mut SamplerPlan, s: &Sampling) {
let shapes = [
Emulation::of(s).map(Shape::Emulation),
Fetched::plain(s).map(Shape::Fetched),
];
for shape in shapes.into_iter().flatten() {
if !plan.routines.contains(&shape) {
plan.routines.push(shape);
}
}
}
/// The census words routed sampling `s` saves at its site: the bodies of the routines it calls,
/// which [`note`] counts once in the module, less the calls ([`CALL_WORDS`]).
pub(super) fn routed_words(s: &Sampling) -> u32 {
let emulation = Emulation::of(s)
.and(s.linear.as_ref())
.map_or(0, |l| l.words().saturating_sub(CALL_WORDS));
let fetch = Fetched::plain(s)
.and(s.fetched.as_ref())
.map_or(0, |p| p.fetch.words(&s.op).saturating_sub(CALL_WORDS));
emulation + fetch
}
/// The sampling routines one function's emission has defined, by shape and by the types of their
/// call's arguments: each defined at its first call.
#[derive(Debug, Default)]
+125 -543
View File
@@ -61,38 +61,34 @@ pub(super) fn konst<'a>(cx: &'a SelectCx<'_>, v: Value) -> Option<&'a Const> {
}
/// How nonzero fragment bias `v`, sampled through `sampler` on a texture of `plane` coordinate
/// components, reaches the level. Through Metal's own sampler, the `Bias` operand as given. Else by
/// Metal's `B` of the bias: through an anisotropic constexpr sampler of a 2D plane, the axis
/// gradients; through a runtime or argument buffer's sampler of a 2D plane, whose word states its
/// anisotropy, decided per invocation; otherwise a constant `B` decides at compile time, by its
/// `f32` sum with a constexpr sampler's own bias as the device forms it, and a dynamic bias per
/// invocation. A NaN constant stays on the `Bias` operand, as before.
/// components, reaches the level. Through a sampler without a bias of its own, the `Bias` operand
/// as given, the device's sampler's reading of it. Else (a constexpr sampler with a bias of its
/// own) by Metal's `B` of the bias: through an anisotropic sampler of a 2D plane, the axis
/// gradients; otherwise a constant `B` decides at compile time, by its `f32` sum with the
/// sampler's own bias as the device forms it, and a dynamic bias per invocation. A NaN constant
/// stays on the `Bias` operand, as before.
fn bias_reach(
cx: &SelectCx<'_>,
v: Value,
sampler: SamplerArg,
plane: u8,
) -> Result<BiasReach, Error> {
if bias_to_metal(cx, sampler)? {
if bias_to_metal(sampler)? {
return Ok(BiasReach::Metal);
}
let max_bias_bits = cx.profile.fields().limits.max_sampler_lod_bias_bits;
let own = own_bias(sampler)?;
// The sampler's anisotropy: a constexpr sampler's state, a runtime one's word.
let anisotropic = match sampler {
SamplerArg::Static(SamplerRef::Constexpr(words), _) => {
Some(super::state_of(words)?.max_anisotropy > 1)
}
SamplerArg::Static(SamplerRef::Slot(_), _) | SamplerArg::Heap(_) => None,
// A sampler with a bias of its own is a constexpr one, whose state states its anisotropy.
let SamplerArg::Static(SamplerRef::Constexpr(words), _) = sampler else {
return Err(cx.invariant("a runtime sampler's own bias"));
};
let either = |word| BiasReach::Either {
let anisotropic = super::state_of(words)?.max_anisotropy > 1;
let either = BiasReach::Either {
max_bias_bits,
sampler_bias_bits: own.to_bits(),
word,
};
Ok(match (anisotropic, plane == 2) {
(Some(true), true) => BiasReach::Axes,
(None, true) => either(true),
(true, true) => BiasReach::Axes,
_ => match konst(cx, v) {
Some(Const::Float(bits)) => {
let sum = super::emit::metal_bias_of(f32::from_bits(*bits as u32)) + own;
@@ -102,7 +98,7 @@ fn bias_reach(
BiasReach::Within
}
}
_ => either(false),
_ => either,
},
})
}
@@ -118,19 +114,18 @@ fn own_bias(sampler: SamplerArg) -> Result<f32, Error> {
})
}
/// Whether fragment bias sampled through `sampler` goes to Metal whole: the profile's device
/// samples through Metal's own sampler (`VkProperty::MetalSampler`, MoltenVK), which hands the
/// `Bias` operand to Metal's `bias()` as Metal applies it, and the sampler has no bias of its own,
/// whose sum with the operand's no measurement has read.
fn bias_to_metal(cx: &SelectCx<'_>, sampler: SamplerArg) -> Result<bool, Error> {
let metal = cx.profile.device_samples();
Ok(metal && own_bias(sampler)? == 0.0)
/// Whether fragment bias sampled through `sampler` goes to the device's sampler whole (on
/// MoltenVK, `VkProperty::MetalSampler`, the `Bias` operand reaches Metal's `bias()` as Metal
/// applies it): the sampler has no bias of its own, whose sum with the operand's no measurement
/// has read.
fn bias_to_metal(sampler: SamplerArg) -> Result<bool, Error> {
Ok(own_bias(sampler)? == 0.0)
}
/// Whether a rule-2 sample's hoisted derivatives give Metal's own sample: a sample of a 2D color
/// texture, not an array, without a bias, a `min_lod_clamp` or a nonzero offset, through samplers
/// whose fragment bias goes to Metal whole ([`bias_to_metal`]: a device that samples through
/// Metal's own sampler, MoltenVK, and samplers without a bias of their own). The device hands the
/// whose fragment bias goes to the device's sampler whole ([`bias_to_metal`]: samplers without a
/// bias of their own). The device hands the
/// derivatives to Metal's `gradient2d`, and Metal's implicit sample of a texture chosen per
/// fragment is its sample through `gradient2d` of the coordinate's own derivatives, bit for bit,
/// through constexpr samplers and runtime sampler states of five filter settings, anisotropic among
@@ -155,7 +150,7 @@ fn hoist_is_metals(
return Ok(false);
}
for &c in samplers {
if c != Candidate::Absent && !bias_to_metal(cx, sampler_of(cx, c)?)? {
if c != Candidate::Absent && !bias_to_metal(sampler_of(cx, c)?)? {
return Ok(false);
}
}
@@ -1909,10 +1904,7 @@ fn select_one(
}
_ => return Err(cx.invariant("a non-sampling texture operation routed to sampling")),
};
// A 2D depth comparison of one texel per tap made in the shader: the device reads the texels
// without comparison, a heap texture's beside its own comparison.
let (mut op, compared) =
super::compared::select(cx, op, stat, (image, shape), ops.get(TexRole::LodValue))?;
let mut op = op;
let coord = ops
.get(TexRole::Coord)
.ok_or_else(|| cx.invariant("a sampling call without a coordinate"))?;
@@ -2011,16 +2003,11 @@ fn select_one(
s.compare |= compare;
s.coordinates |= pixel != Pixel::None;
s.nearest |= centred;
// A cube's gradients whose footprint the word chooses read its anisotropy, and so does a
// bias whose route the word chooses.
// A cube's gradients whose footprint the word chooses read its anisotropy.
s.anisotropy |= matches!(
op,
SampleOp::Sample {
lod: Lod::CubeGrad(_, _, CubeFootprint::Word { .. })
| Lod::Implicit {
reach: BiasReach::Either { word: true, .. },
..
},
lod: Lod::CubeGrad(_, _, CubeFootprint::Word { .. }),
..
}
);
@@ -2107,34 +2094,12 @@ fn select_one(
}
}
let residency = observed && !fetches;
// An observed residency's word is the device's access's, so the device reads such a
// comparison's texels, and a comparison that keeps its reference (a runtime sampler's sample, a
// heap texture's) compares on the device.
let compared = match compared {
Some(c) if observed && c.keeps_reference(&op) => None,
Some(c) if observed => Some(super::compared::Compared { fetch: None, ..c }),
c => c,
};
// A filtered sample: Metal's linear filter emulated where it reaches it, the device's
// elsewhere.
let argument = match sampler {
SamplerArg::Heap(h) => Some(h),
SamplerArg::Static(..) => None,
};
let linear = super::linear::select(
cx,
&op,
form,
(stat.map(|(r, _)| r), image, shape),
(argument, observed),
)?;
// A cube gather Metal's footprint answers by fetches.
let cube_gather = super::linear::select_gather(cx, &op, form, (stat, image, shape), observed)?;
// Whether the device samples through Metal's own sampler (`VkProperty::MetalSampler`:
// MoltenVK on Apple's GPU), whose decode, filters, and comparisons are Metal's.
// Or natively (`VkProperty::DeviceSampling`), whose are the device's: every sample and
// gather is then the device's answer, which the module records.
let metal_sampler = cx.profile.device_samples();
// Every sample and gather goes to the device's sampler: Metal's own on MoltenVK
// (`VkProperty::MetalSampler`), whose decode, filters, and comparisons are Metal's, and the
// device's own elsewhere (`VkProperty::DeviceSampling`), whose answers the module records.
if matches!(op, SampleOp::Sample { .. } | SampleOp::Gather { .. }) {
cx.families.sampler.device_sampling = true;
}
// Whether the device's sampler is Metal's own (`VkProperty::MetalSampler` alone), whose sRGB
// decode is Metal's table.
let metal_unit = cx
@@ -2143,167 +2108,66 @@ fn select_one(
.enabled
.properties
.contains(&crate::device::requirements::VkProperty::MetalSampler);
if metal_sampler && matches!(op, SampleOp::Sample { .. } | SampleOp::Gather { .. }) {
cx.families.sampler.device_sampling = true;
}
// An 8-bit sRGB texel Metal decodes from its raw code: a nearest sample's, a pixel fetch's, a
// `half` gather's, an emulated cube gather's (a `float` one's too), a `float` gather's on a
// device whose sampler is not Metal's own, whatever the sampling policy (Metal's own sampler
// gathers the table's decode; a gather reads one texel per lane, so the
// table's decode is exact and cheap), a bicubic sample's, and an emulated linear sample's
// through a constexpr sampler, through the slot's raw view under its variant, decoded exactly
// (the filters sum the table's steps). A runtime sampler's emulated linear sample reads the raw
// codes where its word reaches the emulation or reads one texel (not a cube's there), and the
// device's decoding view elsewhere (`word_raw`). Under the slot's twin variant (a bound format the device cannot sample) the
// device's view reads the codes, so an access the raw codes do not serve decodes what the
// device samples there (`srgb_codes`). An LOD query reads no texel.
let constant = linear
.as_ref()
.is_some_and(|l| matches!(l.state, super::linear::LinearState::Constant { .. }));
let (raw, word_raw, srgb_codes) = match form {
// `half` gather's, a `float` gather's on a device whose sampler is not Metal's own (Metal's own
// sampler gathers the table's decode; a gather reads one texel per lane, so the table's decode
// is exact and cheap), and a bicubic sample's. Under the slot's twin variant (a bound format the
// device cannot sample) the device's view reads the codes, so an access the raw codes do not
// serve decodes what the device samples there (`srgb_codes`). An LOD query reads no texel.
let (raw, srgb_codes) = match form {
Some(f) if matches!(f.conv, TexelConv::F16 | TexelConv::F32) => {
use crate::lower::texture::SrgbReach;
let reach = match &op {
SampleOp::PixelFetch { .. } | SampleOp::Bicubic(_) => SrgbReach::Raw,
SampleOp::Sample { dref: None, .. } => match stat {
Some((r, _)) if nearest_texel(r)? || constant => SrgbReach::Raw,
Some(_) if linear.is_some() => SrgbReach::Word,
Some((r, _)) if nearest_texel(r)? => SrgbReach::Raw,
_ => SrgbReach::Device,
},
SampleOp::Gather { .. }
if f.conv == TexelConv::F16 || cube_gather.is_some() || !metal_unit =>
{
SampleOp::Gather { .. } if f.conv == TexelConv::F16 || !metal_unit => {
SrgbReach::Raw
}
_ => SrgbReach::Device,
};
let read = crate::lower::texture::srgb_texels(cx, image, shape, reach)?;
let codes = reach != SrgbReach::Raw && crate::lower::texture::srgb_twin(cx, image)?;
(
read && reach == SrgbReach::Raw,
read && reach == SrgbReach::Word,
codes,
)
(read && reach == SrgbReach::Raw, codes)
}
_ => (false, false, false),
_ => (false, false),
};
let cube_gather = cube_gather.map(|g| super::linear::CubeGather { raw, ..g });
// A cube gather's corner rule, where the bound format's class states none, is the device's
// footprint.
if let Some(g) = &cube_gather {
cx.note_when(PrecisionNote::DeviceGatherFootprint, g.footprint_when(), m)?;
}
// A runtime sampler's emulation of a slot under its sRGB variant sums the raw codes where
// the word reaches it, its device arm sampling the slot's decoding view, whose decode is the
// device's.
let linear = linear.map(|l| super::linear::Linear {
raw: raw || word_raw,
..l
});
if let Some(l) = &linear {
cx.note_when(
PrecisionNote::SrgbTexelDecode,
super::linear::decode_when(l),
m,
)?;
}
// A filtered sample's note, where the specialized module runs an arm that is not Metal's
// filter: a blend of two levels' comparisons where the device compares
// (`Compared::blend_device_when`).
// A filtered sample's note, where Metal's own sampler filters the slot and a two-plane YCbCr
// format bound there takes another filter than Metal's: the clauses test the bound format
// alone, which the runtime reads at each draw, whatever a runtime sampler's word states (no key
// carries it there).
let by = stat.map(|(r, _)| r);
let filter = super::linear::filter_note(cx, &op, form, (by, image))?;
if let Some(note) = filter {
let when = match &compared {
Some(c) if c.blends() => c.blend_device_when(),
_ => super::linear::filter_when(linear.as_ref(), by),
};
// Where Metal's own sampler filters the slot, only a two-plane YCbCr format bound there
// takes another filter than Metal's: the clauses test the bound format alone, which the
// runtime reads at each draw, whatever a runtime sampler's word states (no key carries it
// there).
let when = super::linear::metal_filtered_ycbcr(cx, image).unwrap_or(when);
if let Some((note, when)) = super::linear::filter_note(cx, &op, form, (by, image))? {
cx.note_when(note, when, m)?;
}
// A native class's sample, the device's filter at Metal's footprint step, within one code
// of Metal's on the devices measured (`native`).
if let Some(l) = &linear {
cx.note_when(
PrecisionNote::DeviceUnorm8LinearFilter,
super::native::when(l),
m,
)?;
}
// A runtime sampler slot an emulated sample reads states its filter, addressing, border, and
// coordinates to the function.
if let Some(super::linear::Linear {
state: super::linear::LinearState::Slot { sampler, .. },
..
}) = &linear
{
if let Some(s) = cx.families.sampler.slots.get_mut(sampler) {
s.linear = true;
}
}
// A cube's emulation fetches its faces through the slot's 2D-array view, or its raw view
// where it reads the raw codes.
let faces = matches!(linear, Some(super::linear::Linear { cube: Some(_), .. }))
|| cube_gather.is_some();
if let (true, ImageRef::Slot(index)) = (faces, image) {
if let Some(s) = cx.families.texture.slots.get_mut(&index) {
s.uses.faces = true;
s.raw |= raw || word_raw;
}
}
// A gather's or a repeating nearest sample's coordinate snapped onto Metal's texels; an
// emulated cube gather takes none.
let snap = match cube_gather {
Some(_) => None,
None => super::position::plan(cx, &op, stat, (shape, integer))?,
};
// A pixel sampler's gather (or a runtime sampler's, behind its word) and a linear pixel
// sample's footprint cell, snapped onto Metal's texels.
let snap = super::position::plan(cx, &op, stat, (shape, integer))?;
// Metal's texture unit reads a subnormal normalized coordinate as the zero of its sign before
// the address mode decides: the border axes of a constexpr sampler flush it, so the sample
// reads the texel Metal reads there (`position::subnormal_flush`).
let flush_subnormals = super::position::subnormal_flush(stat, shape)?;
// A level or a kernel's bias handed to the device on Metal's grid, a runtime or argument
// buffer's sampler's by its word.
let level = super::level::select(cx, &op, stat, (ops.get(TexRole::LodValue), integer))?;
// A level the device's arithmetic takes (from derivatives or gradients, or a level the rule
// does not reach), where it chooses what the sample reads and no other note records it.
let when = super::level::device_when(
cx,
&op,
by,
(cube, filter.is_some()),
(level.is_some(), ops.get(TexRole::LodValue), integer),
)?;
cx.note_when(PrecisionNote::DeviceSampleLevel, when, m)?;
if let SamplerArg::Static(SamplerRef::Slot(n), _) = sampler {
if let Some(s) = cx.families.sampler.slots.get_mut(&n) {
match snap.as_ref().map(|p| p.kind) {
Some(super::position::SnapKind::Word { leveled, .. }) => {
s.snap = true;
s.levels |= leveled;
}
Some(super::position::SnapKind::WordGather { .. }) => s.gathers = true,
Some(super::position::SnapKind::WordGather) => s.gathers = true,
Some(super::position::SnapKind::WordCell { .. }) => s.cells = true,
_ => {}
}
s.level |= matches!(level, Some(super::level::LevelRule::Word));
}
}
// A pixel sampler's coordinate, scaled for the device, reads Metal's texels where Metal's
// position, the coordinate as given, decides them: a centred texel, a snapped gather
// or footprint cell, or the linear emulation, which reads the coordinate as given (a runtime
// pixel sampler's linear sample measured so). The note holds where none of them runs and the
// device's filter reads the scaled coordinate, as `pixel_note` says. An argument buffer's
// sampler records a note of its own, which the runtime announces only while a bound state can
// need it.
let when = pixel_note(
&op,
(pixel, metal_sampler),
(centred, integer),
(linear.as_ref(), snap.as_ref()),
);
// position, the coordinate as given, decides them: a centred texel, a snapped gather or
// footprint cell. The note holds where none of them runs and the device's filter reads the
// scaled coordinate, as `pixel_note` says. An argument buffer's sampler records a note of its
// own, which the runtime announces only while a bound state can need it.
let argument = match sampler {
SamplerArg::Heap(h) => Some(h),
SamplerArg::Static(..) => None,
};
let when = pixel_note(&op, pixel, (centred, integer), snap.as_ref());
let note = match pixel {
Pixel::Heap(_) => PrecisionNote::ArgumentPixelSamplerScaling,
_ => PrecisionNote::PixelSamplerScaling,
@@ -2313,33 +2177,24 @@ fn select_one(
b.raw = raw;
}
// A bicubic sample rounds its `half` result exactly, keeping denormals, as a raw texel's decode
// does; another converts its texel by the bound format's class. A raw linear sample reads the
// bound format's channels from the class (its border color), and a linear sample with a `float`
// result the format's treatment; so does a cube gather of a `float` or `half` result its corner
// rule. A plain gather's or nearest sample's texels fetched where Metal's footprint and level
// are known, for a slot bound in a 32-bit float format. A comparison's gather or sample, whose
// reference `compared` took out, fetches as `compared` says.
let fetched = match (observed, raw, &compared) {
(false, false, None) => super::fetched::select(
cx,
&op,
form,
(stat, argument.is_some()),
(image, shape),
ops.get(TexRole::LodValue),
)?
.filter(|p| {
arm.is_none() || matches!(p.fetch.address, super::fetched::FetchAddress::Modes { .. })
}),
// does; another converts its texel by the bound format's class. A `half` gather's texels
// fetched where Metal's footprint is known (`fetched::select`).
let fetched = match (observed, raw) {
(false, false) => {
super::fetched::select(cx, &op, form, (stat, argument.is_some()), (image, shape))?
.filter(|p| {
arm.is_none()
|| matches!(p.fetch.address, super::fetched::FetchAddress::Modes { .. })
})
}
_ => None,
};
// A runtime sampler's word addresses the fetch: the function reads its coordinates, address
// modes and border color, a sample's filter, and the levels a stated level's word reads.
// modes and border color.
if let Some(super::fetched::Plain {
fetch:
super::fetched::Fetch {
address: super::fetched::FetchAddress::Word { sampler: n, axes },
level,
address: super::fetched::FetchAddress::Word { sampler: n, .. },
..
},
..
@@ -2347,9 +2202,6 @@ fn select_one(
{
if let Some(s) = cx.families.sampler.slots.get_mut(n) {
s.fetched = true;
s.fetched_depth |= *axes == 3;
s.filters |= matches!(op, SampleOp::Sample { .. });
s.fetch_levels |= matches!(level, super::fetched::FetchLevel::Word(_));
}
}
// Whether the access reads one texel of one level, whose `half` or `float` texel a packed or
@@ -2357,19 +2209,16 @@ fn select_one(
// slot's specialization then reads.
let one_texel = one_texel(&op, sampler, shape.dim == ImageDim::Cube)?;
// On a device that samples through Metal's own texture unit, the `half` routine reads an
// access's lanes only for a YCbCr field's one texel (`half::HalfFamilies::MetalSampler`),
// which a runtime sampler slot's texture holds only under the slot's YCbCr variant
// (`texture::ycbcr_texture`): elsewhere no sampler word decides them. A slot's texture of a
// YCbCr format on the grid `8192` (`TexelFormat::YCBCR_8192`) bound there without the variant
// (`YCbCrFilterPolicy::Device`) then rounds a sample of its one texel to nearest even, where
// access's lanes only for a YCbCr field's one texel (`half::HalfFamilies::MetalSampler`): no
// sampler word decides them. A slot's texture of a YCbCr format on the grid `8192`
// (`TexelFormat::YCBCR_8192`) then rounds a sample of its one texel to nearest even, where
// Metal rounds it with ties away, noted where it is bound.
let one_texel = match one_texel {
crate::lower::texture::OneTexel::Word(_)
if half
&& !raw
&& crate::lower::texture::half_families(cx)
== crate::lower::texture::half::HalfFamilies::MetalSampler
&& !crate::lower::texture::ycbcr_texture(cx, image, shape)? =>
== crate::lower::texture::half::HalfFamilies::MetalSampler =>
{
if let ImageRef::Slot(index) = image {
use crate::metal::texel_format::TexelFormat;
@@ -2384,15 +2233,11 @@ fn select_one(
}
other => other,
};
// A heap comparison reads its handle's depth class, and a heap texture's emulated linear
// sample its handle's texel class, no slot's format.
let by_format = linear.as_ref().is_some_and(|l| l.image.slot().is_some())
|| cube_gather.as_ref().is_some_and(|g| !g.integer)
|| compared.as_ref().is_some_and(|c| !c.on_heap())
|| fetched.as_ref().is_some_and(|p| p.image.slot().is_some());
// A heap texture's fetches read its handle's texel class, no slot's format.
let by_format = fetched.as_ref().is_some_and(|p| p.image.slot().is_some());
// Where a sample's `half` texel is the device's, no conversion declares the slot's class: the
// emulation that reads it declares it itself.
let device = crate::lower::texture::device_texels(cx, true);
let device = crate::lower::texture::device_texels(cx);
if by_format && !raw && half && device {
crate::lower::texture::texel_format_spec(cx, image)?;
}
@@ -2409,44 +2254,34 @@ fn select_one(
cx.families.access.heap_class = true;
cx.families.texture.half_families = crate::lower::texture::half_families(cx);
}
let arm = linear
.as_ref()
.filter(|_| word_raw)
.map(super::linear::decode_when);
crate::lower::texture::half_texels(
cx,
image,
shape,
(one_texel, arm.as_deref()),
device,
m,
)?
crate::lower::texture::half_texels(cx, image, shape, (one_texel, None), device, m)?
}
_ => {}
}
// A `float` texel that may be one texel's converts by the bound format's class: not an sRGB raw
// texel's (decoded exactly), a bicubic sample's, or an LOD query's; nor a depth comparison's,
// whose result is no texel.
// A `float` texel that may be one texel's is the device's conversion of its codes: not an sRGB
// raw texel's (decoded exactly), a bicubic sample's, or an LOD query's; nor a depth
// comparison's, whose result is no texel.
let comparison = matches!(
op,
SampleOp::Sample { dref: Some(_), .. } | SampleOp::Gather { dref: Some(_), .. }
) || compared.is_some();
let float_texel = form.is_some_and(|f| f.conv == TexelConv::F32)
);
if form.is_some_and(|f| f.conv == TexelConv::F32)
&& !raw
&& !comparison
&& !matches!(
op,
SampleOp::Bicubic(_) | SampleOp::Lod { .. } | SampleOp::QueryLevel { .. }
)
&& crate::lower::texture::float_texels(cx, image, shape, one_texel, device)?;
// The conversion's lanes read a runtime sampler's filter fields where its word decides: a
// `half` texel's on every profile, a `float` one's where it converts.
let half_converts = half && !raw && !matches!(op, SampleOp::Bicubic(_)) && !device;
let converts = half_converts || float_texel;
if let (crate::lower::texture::OneTexel::Word(n), true, ImageRef::Slot(_)) =
(one_texel, converts, image)
{
if !shape.depth || float_texel {
crate::lower::texture::float_texel_notes(cx, image, shape, one_texel);
}
// The conversion's lanes read a runtime sampler's filter fields where its word decides: a
// `half` texel's on every profile.
let half_converts = half && !raw && !matches!(op, SampleOp::Bicubic(_)) && !device;
if let (crate::lower::texture::OneTexel::Word(n), true, ImageRef::Slot(_)) =
(one_texel, half_converts, image)
{
if !shape.depth {
if let Some(s) = cx.families.sampler.slots.get_mut(&n) {
s.texels = true;
}
@@ -2517,206 +2352,17 @@ fn select_one(
return Err(Unsupported::not_implemented(Feature::ArgumentBufferTextures).into())
}
};
// An emulated 2D linear comparison fetches its taps through the slot's binding without
// comparison: through its own, a `Depth32Float` texture held with a twin reads the twin. A
// runtime sampler's emulation of raw codes fetches them through the slot's raw view, its own
// binding the decoding view its device arm samples.
let linear = match (linear, source) {
(Some(l), Source::Combined(key))
if (l.compare.is_some() || word_raw) && l.cube.is_none() =>
{
let fetch = BindingKey {
compare: false,
raw: key.raw || word_raw,
..key
};
cx.families.sampler.combined.insert(fetch);
Some(super::linear::Linear {
fetch: Some(fetch),
..l
})
}
(linear, _) => linear,
};
// A runtime sampler's sample the shader compares where it reads one texel samples through
// the slot's binding without comparison there; the comparison reads the slot's word. A heap
// texture's comparison reads its element through its use's sampler without comparison too, in
// the float class of its shape, and its handle carries the element's depth class.
if let (Some(_), ImageRef::Heap { group, .. }) = (&compared, image) {
if let Some(h) = cx.families.texture.heap.get_mut(&group) {
h.compares_plain = true;
}
}
let plain = match (&compared, source) {
(Some(c), Source::Combined(key)) if c.keeps_reference(&op) => {
let plain = BindingKey {
compare: false,
..key
};
cx.families.sampler.combined.insert(plain);
Some(Source::Combined(plain))
}
(Some(_), Source::Heap { handle, key }) => {
let plain = HeapKey {
compare: false,
..key
};
cx.families.sampler.heap.insert(plain);
cx.families.access.heap_depth = true;
Some(Source::Heap { handle, key: plain })
}
(
Some(_),
Source::HeapSampler {
handle,
sampler,
key,
},
) => {
let plain = HeapSamplerKey {
compare: false,
..key
};
cx.families.sampler.heap_samplers.insert(plain);
cx.families.access.heap_depth = true;
Some(Source::HeapSampler {
handle,
sampler,
key: plain,
})
}
_ => None,
};
let compared = compared.map(|c| super::compared::Compared { plain, ..c });
if let (Some(c), SamplerArg::Static(SamplerRef::Slot(n), _)) = (&compared, sampler) {
if let Some(s) = cx.families.sampler.slots.get_mut(&n) {
s.compared |= c.function == super::linear::Comparison::Word;
// A sample that keeps its reference tests the word's filter.
s.filters |= c.keeps_reference(&op)
&& c.function == super::linear::Comparison::Word
&& matches!(op, SampleOp::Sample { .. });
s.fetched |= c
.fetch
.as_ref()
.is_some_and(|f| matches!(f.address, super::fetched::FetchAddress::Word { .. }));
s.fetch_levels |= c.fetch.as_ref().is_some_and(|f| {
matches!(f.address, super::fetched::FetchAddress::Word { .. })
&& matches!(f.level, super::fetched::FetchLevel::Word(_))
});
}
}
// A depth comparison the device makes, on a device that does not sample through Metal's own
// sampler: a runtime sampler slot's `sample_compare` of a slot where its word reaches the
// device's comparison (`Compared::device_when`), a blend of two levels' comparisons where the
// slot's format names no measured class (`Compared::blend_device_when`), any other always. The
// shader's own comparison of texels the device reads is exact but for that read, which
// `DeviceTexelDenormals` names below.
let fetched_linear = linear
.as_ref()
.is_some_and(|l| matches!(l.state, super::linear::LinearState::Constant { .. }));
let device_compares = compare && !fetched_linear && cube_gather.is_none();
if shape.depth && !metal_sampler && device_compares {
let when = match (&compared, sampler) {
(Some(c), _) if c.blends() => c.blend_device_when(),
(Some(c), SamplerArg::Static(SamplerRef::Slot(n), _))
if !c.on_heap() && c.keeps_reference(&op) =>
{
c.device_when(n, linear.as_ref())
}
_ => vec![crate::lower::select::NoteClause::new()],
};
cx.note_when(PrecisionNote::DeviceDepthComparison, when, m)?;
}
// A depth comparison the device makes reads a depth image (the texture's own, or its twin),
// which a device without `VK_EXT_depth_range_unrestricted` may hold clamped; the shader's own
// comparisons read the texels without comparison, which a twinned texture holds in colour.
if shape.depth && device_compares {
// A depth comparison, the device's, reads a depth image (the texture's own, or its twin),
// which a device without `VK_EXT_depth_range_unrestricted` may hold clamped.
if shape.depth && compare {
crate::lower::texture::depth_comparison(cx);
}
// A `float` sample or gather, a comparison's included, whose texels the device reads, on a
// device that does not sample through Metal's own sampler: a 32-bit float texel the device
// reads as zero where it is denormal. Not where the shader fetches that class's texels: a plain
// fetch, a fetched comparison (but a runtime or argument buffer's sampler's `sample_compare`,
// whose filtered arm or nearest mip filter the device may read,
// `Compared::fetches_every_texel`), a constexpr sampler's linear emulation, and a cube
// gather's.
let float_texels = matches!(op, SampleOp::Sample { .. } | SampleOp::Gather { .. })
&& form.is_some_and(|f| f.conv == TexelConv::F32);
let fetches_float = fetched.as_ref().is_some_and(|p| p.fetches_every_texel(&op))
|| compared
.as_ref()
.is_some_and(|c| c.fetches_every_texel(&op))
|| fetched_linear
|| cube_gather.is_some();
// Only a format of `float` texels holds a denormal one: a slot that declares its class takes
// the note where the class is neither normalized nor half-float.
if float_texels && !metal_sampler && !fetches_float {
match image {
ImageRef::Slot(index) => {
use crate::metal::bicubic::BicubicTexels as B;
// No packed format holds a `float` denormal either.
let on = crate::lower::select::NoteOn::Texel(index);
let class: Vec<crate::lower::select::NoteClause> = vec![[
crate::lower::select::NoteTest::equal(
on,
B::EXACT | B::UNORM | B::SNORM | B::HALF,
0,
),
crate::lower::select::NoteTest::equal(
on,
crate::metal::texel_format::TexelFormat::PACKED_MASK,
0,
),
]
.into()];
// A sample a runtime sampler's word addresses fetches its texel where the word
// states one texel (`fetched::word_reach`): the device reads it where the word
// filters, or, at an implicit level or gradients, has a mip filter.
let when = match fetched.as_ref().map(|p| (&p.fetch.address, p.fetch.level)) {
Some((super::fetched::FetchAddress::Word { sampler, .. }, level)) => {
let mut word = super::linear::word_filters(*sampler);
if !matches!(level, super::fetched::FetchLevel::Word(_)) {
word.push(
[crate::lower::select::NoteTest::differ(
crate::lower::select::NoteOn::Sampler(*sampler),
SamplerWord::MIP_FILTER,
0,
)]
.into(),
);
}
crate::lower::select::both(&word, &class)
}
_ => class,
};
cx.note_when(PrecisionNote::DeviceTexelDenormals, when, m)?;
}
_ => {
cx.precision.insert(PrecisionNote::DeviceTexelDenormals);
}
}
}
// A runtime or argument buffer's pixel sampler's texel centre moves back by a texel offset
// Metal drops on a mirror-clamped axis, which a device without Metal's own sampler adds.
let centre_offset = centred
&& matches!(pixel, Pixel::Spec(_) | Pixel::Heap(_))
&& !metal_sampler
&& matches!(
op,
SampleOp::Sample {
offset: Some(_),
..
}
);
// A texel offset the module places by Metal's rule on an axis that may repeat or mirror
// reads the base-level size of a view's parent: a slot's access through the slot's
// `OffsetBaseAxes` specialization, which states where the parent's and the bound view's
// differ; a heap element's reads the bound view's alone (the residue). A bicubic filter is
// emulated on every device, Metal's own sampler's among them.
let placed = (snap.as_ref(), linear.as_ref(), fetched.as_ref());
let bicubic = matches!(op, SampleOp::Bicubic(_));
let offset_base =
(!metal_sampler || bicubic) && (centre_offset || places_wrapped_offset(&op, placed));
// differ; a heap element's reads the bound view's alone (the residue). A bicubic filter's
// footprint is the one the module places so.
let offset_base = places_wrapped_offset(&op);
let offset_base = match image {
ImageRef::Slot(index) if offset_base => {
if let Some(s) = cx.families.texture.slots.get_mut(&index) {
@@ -2749,7 +2395,7 @@ fn select_one(
// Metal's anisotropic filter emulated by the device's samples at explicit levels, where it
// reaches the sample; the device's anisotropic filter, recorded, where it does not. An
// isotropic cube's level too, where no exact path of its own answers it.
let answered = linear.is_some() || snap.is_some() || fetched.is_some() || centred;
let answered = snap.is_some() || fetched.is_some() || centred;
let anisotropic = super::anisotropic::select(
cx,
&op,
@@ -2787,13 +2433,7 @@ fn select_one(
if tangled {
cx.tangled.insert(value);
}
// A comparison the shader makes alone has left the op (`compared::select`).
let compares = compared.is_some()
|| matches!(
op,
SampleOp::Sample { dref: Some(_), .. } | SampleOp::Gather { dref: Some(_), .. }
);
let clamp_reference = clamps_reference(cx, compares, sampler)?;
let clamp_reference = clamps_reference(cx, comparison, sampler)?;
let sampling = Sampling {
source,
op,
@@ -2806,20 +2446,14 @@ fn select_one(
pixel,
residency,
footprint,
linear,
snap,
flush_subnormals,
level,
compared,
fetched,
cube_gather,
cube,
centred,
centre_word,
one_texel,
half_texel: half_converts && !shape.depth,
float_texel,
centre_offset,
unmapped,
heap_raw: None,
declared,
@@ -2829,8 +2463,6 @@ fn select_one(
srgb_codes,
clamp_reference,
};
// The sampling routines it calls, for the census.
super::routine::note(&mut cx.families.sampler, &sampling);
Ok(sampling)
}
@@ -2880,44 +2512,37 @@ fn clamps_reference(
/// coordinate scaled by the texture's size whose texels the device's filter decides
/// (`PrecisionNote::PixelSamplerScaling`): the clauses of the arms that do (empty: none).
///
/// - A constexpr pixel sampler: never where the sample is `centred`, snapped onto Metal's texels,
/// or, at its sum's class, emulated (`linear::device_when`); always otherwise.
/// - A constexpr pixel sampler: never where the sample is `centred` or snapped onto Metal's
/// texels; always otherwise.
/// - A runtime sampler slot: where its word states pixel coordinates and the sample's arm is the
/// device's. A 2D gather snaps behind the word on every device. A sample (a comparison's
/// included) reads the texel's centre where the word states one texel ([`Sampling::centre_word`]:
/// every pixel word for an integer texture); otherwise, on a device with Metal's own sampler, it
/// snaps onto its footprint cell where the word's two filters are linear, leaving a word of mixed
/// filters to the device, and elsewhere the emulation, where it is planned, answers whatever
/// `linear::device_when` leaves; without it the device filters. Metal admits a pixel sampler only
/// every pixel word for an integer texture); otherwise it snaps onto its footprint cell where the
/// word's two filters are linear and Metal's own sampler filters it, leaving a word of mixed
/// filters to the device; without the cell the device filters. Metal admits a pixel sampler only
/// without a mip filter and isotropic (`runtime::sampler::check_descriptor`), so its word filters
/// exactly where a min or mag filter is linear. Any other sampling (an LOD query) is the
/// device's.
/// - An argument buffer's sampler ([`PrecisionNote::ArgumentPixelSamplerScaling`]): never for a 2D
/// gather (snapped behind its word), nor, on a device with Metal's own sampler (`metal_sampler`),
/// for a sample without a comparison, which reads Metal's texels there (a nearest word's flagged
/// fetch, a linear word's footprint cell); always otherwise, since its word, which the
/// specialized module cannot read, may filter where no emulation reaches it.
/// gather (snapped behind its word), nor for a sample without a comparison, which reads the
/// device sampler's texels there (a nearest word's flagged fetch, a linear word's footprint
/// cell); always otherwise, since its word, which the specialized module cannot read, may filter.
fn pixel_note(
op: &SampleOp,
(pixel, metal_sampler): (Pixel, bool),
pixel: Pixel,
(centred, integer): (bool, bool),
(linear, snap): (
Option<&super::linear::Linear>,
Option<&super::position::Snap>,
),
snap: Option<&super::position::Snap>,
) -> Vec<crate::lower::select::NoteClause> {
use super::position::SnapKind;
use crate::lower::select::{both, NoteClause};
let always = || vec![NoteClause::new()];
let gathered = snap.is_some_and(|s| matches!(s.kind, SnapKind::WordGather { .. }));
let gathered = snap.is_some_and(|s| matches!(s.kind, SnapKind::WordGather));
match pixel {
Pixel::None => Vec::new(),
Pixel::Always if centred || snap.is_some_and(|s| s.pixel) => Vec::new(),
Pixel::Always => linear.map_or_else(always, super::linear::device_when),
Pixel::Always if centred || snap.is_some_and(|s| !s.by_word()) => Vec::new(),
Pixel::Always => always(),
Pixel::Heap(_) if gathered => Vec::new(),
Pixel::Heap(_) if metal_sampler && matches!(op, SampleOp::Sample { dref: None, .. }) => {
Vec::new()
}
Pixel::Heap(_) if matches!(op, SampleOp::Sample { dref: None, .. }) => Vec::new(),
Pixel::Heap(_) => always(),
Pixel::Spec(_) if gathered => Vec::new(),
Pixel::Spec(n) => {
@@ -2925,9 +2550,9 @@ fn pixel_note(
let coordinates = NoteTest::differ(on, SamplerWord::PIXEL_COORDINATES, 0);
let filter = |bit| NoteTest::differ(on, bit, 0);
let filters = [SamplerWord::MIN_LINEAR, SamplerWord::MAG_LINEAR].map(filter);
let device = match (op, linear) {
(SampleOp::Sample { .. }, _) if centred && integer => Vec::new(),
(SampleOp::Sample { .. }, _)
let device = match op {
SampleOp::Sample { .. } if centred && integer => Vec::new(),
SampleOp::Sample { .. }
if snap.is_some_and(|s| matches!(s.kind, SnapKind::WordCell { .. })) =>
{
// Mixed filters: one linear, the other not.
@@ -2937,10 +2562,7 @@ fn pixel_note(
[nearest(SamplerWord::MIN_LINEAR), filters[1]].into(),
]
}
(SampleOp::Sample { .. }, Some(l)) => super::linear::device_when(l),
(SampleOp::Sample { .. }, None) if centred => {
filters.map(|t| NoteClause::from([t])).into()
}
SampleOp::Sample { .. } if centred => filters.map(|t| NoteClause::from([t])).into(),
_ => always(),
};
both(&[[coordinates].into()], &device)
@@ -2978,58 +2600,18 @@ fn one_texel(
}
/// Whether the module places a texel offset of `op` by Metal's rule (`position::offset_dropped`) on
/// an axis that may repeat or mirror: a snapped coordinate's (`snap`), an emulated linear filter's
/// (`linear`), fetched texels' (`fetched`), or a bicubic filter's footprint, each on a constexpr
/// sampler's repeating or mirrored axis or any axis of a runtime or argument buffer's sampler,
/// whose mode its word states.
fn places_wrapped_offset(
op: &SampleOp,
(snap, linear, fetched): (
Option<&super::position::Snap>,
Option<&super::linear::Linear>,
Option<&super::fetched::Plain>,
),
) -> bool {
/// an axis that may repeat or mirror: a bicubic filter's footprint, on a constexpr sampler's
/// repeating or mirrored axis.
fn places_wrapped_offset(op: &SampleOp) -> bool {
use super::bicubic::TapAddress;
let wraps = |a: &TapAddress| matches!(a, TapAddress::Repeat | TapAddress::Mirror);
let moved = |o: &[i32]| o.iter().any(|o| *o != 0);
let offset = match op {
SampleOp::Sample { offset, .. } | SampleOp::Gather { offset, .. } => match offset {
Some(Offset::Const(k)) => moved(k),
Some(Offset::Dynamic(..)) => true,
None => false,
},
match op {
SampleOp::Bicubic(b) => {
return b.offset.as_deref().is_some_and(moved) && b.address.iter().any(wraps)
b.offset.as_deref().is_some_and(moved) && b.address.iter().any(wraps)
}
_ => false,
};
if !offset {
return false;
}
let snapped = snap.is_some_and(|s| match s.kind {
super::position::SnapKind::Axes(_) => s.axes.iter().flatten().any(wraps),
super::position::SnapKind::Word { .. } | super::position::SnapKind::WordGather { .. } => {
true
}
// A cube's access takes no offset; Metal's own sampler places a pixel cell's.
super::position::SnapKind::Cube(_) | super::position::SnapKind::WordCell { .. } => false,
});
let filtered = linear.is_some_and(|l| {
l.cube.is_none()
&& match &l.state {
super::linear::LinearState::Constant { address, .. } => address.iter().any(wraps),
super::linear::LinearState::Slot { .. }
| super::linear::LinearState::Argument { .. } => true,
}
});
let fetches = fetched.is_some_and(|p| match &p.fetch.address {
super::fetched::FetchAddress::Modes { address, .. } => address.iter().any(wraps),
super::fetched::FetchAddress::Word { .. } | super::fetched::FetchAddress::Entry { .. } => {
true
}
});
snapped || filtered || fetches
}
/// An operation through an argument buffer's sampler tests the sampler's table entry for a cubic
+56 -263
View File
@@ -1,10 +1,9 @@
//! The shared emulation of a switch-at-use (SEMANTICS 1012).
//!
//! A switch-at-use whose every arm takes the same emulated sampling on its own texture slot
//! ([`Sampling::shared_shape`]): a bicubic sample, a linear sample Metal's filter answers, a
//! snapped gather or nearest sample, or a plain gather or nearest sample whose base-level texels
//! the shader fetches. Emitted per arm, each arm repeats the whole emulation (its position,
//! weights, sums, and routine calls), so the switch's words grow with arms × emulation, and so does
//! ([`Sampling::shared_shape`]): a bicubic sample, a snapped gather or sample, or a `half` gather
//! whose base-level texels the shader fetches. Emitted per arm, each arm repeats the whole
//! emulation (its position, weights, sums, and routine calls), so the switch's words grow with arms × emulation, and so does
//! the driver's work once the bound formats make every arm's emulation live (an Intel ANV pipeline
//! of 32 such arms took 6 s to create).
//!
@@ -16,12 +15,10 @@
//! whose null arm yields a size of ones, bits 0 and `false`;
//! - the emulation on those facts (its footprint, weights and routine calls once), whose taps a
//! dispatch reads from each arm's image (the null arm's are zero);
//! - a linear sample's device sample, where the named format is not measured, dispatched the same
//! way, converted for a `half` result by the named format's class;
//! - a snapped sample's coordinate snapped once on the named size, and the device's access and
//! texel conversion in each arm, the null arm yielding the switch's null value;
//! - a plain fetch's taps on the named size, fetched in one dispatch where the named format is of
//! the 32-bit float class, else the device's access (its coordinate snapped once) in another.
//! the class the fetch names, else the device's access (its coordinate snapped once) in another.
//!
//! Where a handle names a candidate the facts are that candidate's, so every value is the one its
//! own arm computed; elsewhere the switch's null value is selected. The emulation of a null handle
@@ -36,9 +33,8 @@ use crate::spirv::ids::{ConstId, Value as SValue};
use crate::spirv::ir::{ConstBits, Constant, ImageOperands, ImageQuery, Type as SType};
use super::emit::{
device_access, held_value, layered, offset_operands, op_offset, pixel_coordinates,
plane_and_gradients, sample_access, sample_operands, sampler_word, scaled, snap_offsets,
texel_value, word_level, word_level_size,
held_value, layered, offset_operands, op_offset, pixel_coordinates, plane_and_gradients,
sample_access, sample_operands, scaled, snap_offsets, texel_value,
};
use super::{Binding, CombinedImage, SampleOp, Sampling, Source, Unmapped};
@@ -74,27 +70,14 @@ impl Candidates<'_> {
binding(cx, a)?.0.sampled_image(fb)
}
/// The sampled image of arm sampling `a`'s binding its linear taps are fetched through
/// (`Linear::fetch`; its own binding where it names none), made in the open block: a raw
/// emulation's raw view, through the arm's runtime sampler.
pub(super) fn fetch_sampled_image(
&self,
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
a: &Sampling,
) -> BResult<SValue> {
fetch_binding(cx, a)?.sampled_image(fb)
}
/// The image of arm sampling `a`'s binding, loaded in the open block: for an emulated linear
/// comparison the binding its taps are fetched through (`Linear::fetch`).
/// The image of arm sampling `a`'s binding, loaded in the open block.
pub(super) fn image(
&self,
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
a: &Sampling,
) -> BResult<SValue> {
fetch_binding(cx, a)?.image(fb)
binding(cx, a)?.0.image(fb)
}
}
@@ -109,24 +92,10 @@ fn binding(cx: &mut EmitCx<'_>, a: &Sampling) -> BResult<(Binding, CombinedImage
}
}
/// The binding arm sampling `a`'s linear taps are fetched through (`Linear::fetch`), else its own.
fn fetch_binding(cx: &mut EmitCx<'_>, a: &Sampling) -> BResult<Binding> {
let key = match (&a.linear, a.source) {
(Some(super::linear::Linear { fetch: Some(k), .. }), _) => *k,
(_, Source::Combined(key)) => key,
_ => return Err(cx.fail("a shared sampling of a heap element")),
};
match cx.decl.families.sampler.combined.get(&key) {
Some(&(b, _)) => Ok(b),
None => Err(cx.fail(format!("combined binding {key:?} is not declared"))),
}
}
/// The emulation every arm of a shared switch takes.
#[derive(Clone, Copy)]
enum Emulation<'a> {
Bicubic(&'a super::bicubic::Bicubic),
Linear(&'a super::linear::Linear),
Snap(&'a super::position::Snap),
/// A plain fetch of the base level, its device arm snapped where it has a snap.
Fetched(&'a super::fetched::Plain),
@@ -137,14 +106,9 @@ impl<'a> Emulation<'a> {
if let Some(p) = &s.fetched {
return Some(Emulation::Fetched(p));
}
match (&s.op, &s.linear, &s.snap) {
(SampleOp::Bicubic(b), None, None) => Some(Emulation::Bicubic(b)),
(SampleOp::Sample { .. }, Some(l), snap)
if snap.as_ref().is_none_or(super::position::Snap::by_word) =>
{
Some(Emulation::Linear(l))
}
(SampleOp::Sample { .. } | SampleOp::Gather { .. }, None, Some(p)) if !p.by_word() => {
match (&s.op, &s.snap) {
(SampleOp::Bicubic(b), None) => Some(Emulation::Bicubic(b)),
(SampleOp::Sample { .. } | SampleOp::Gather { .. }, Some(p)) if !p.by_word() => {
Some(Emulation::Snap(p))
}
_ => None,
@@ -152,16 +116,12 @@ impl<'a> Emulation<'a> {
}
/// The specialization holding the bound format's bits of arm sampling `a`'s slot, where the
/// emulation reads them: a bicubic sample's `BicubicTexels`, a linear one's `TexelFormat`.
/// emulation reads them: a bicubic sample's `BicubicTexels`, a fetch's `TexelFormat`.
fn bits(self, cx: &mut EmitCx<'_>, a: &Sampling) -> BResult<Option<ConstId>> {
let spec = match (self, Emulation::of(a)) {
(Emulation::Bicubic(_), Some(Emulation::Bicubic(b))) => {
cx.decl.families.sampler.bicubic.get(&b.texture).copied()
}
(Emulation::Linear(_), Some(Emulation::Linear(l))) => l
.image
.slot()
.and_then(|t| crate::lower::texture::texel_format_const(cx, t)),
(Emulation::Fetched(_), Some(Emulation::Fetched(p))) => p
.image
.slot()
@@ -197,31 +157,17 @@ pub(crate) fn shared_value(
return Err(cx.fail("a shared switch's candidates of different images"));
}
}
// A runtime sampler's level by its word: the level handed to the device, and the one a
// leveled snap reads, whose size each arm's facts give.
let (lambda, nearest) = word_level(cx, fb, first)?;
let leveled = match nearest {
Some(nearest) => Some((sampler_word(cx, fb, first.pixel)?, nearest)),
None => None,
};
// A leveled snap of an access with a texel offset reads the base level's size after its
// level's: Metal's offset rule reads both.
let based = leveled.is_some() && op_offset(&first.op).is_some();
let facts = facts(cx, fb, c, kind, (image, leveled, based))?;
let (size, base, rest) = match (based, &facts[..]) {
(true, [size, base, rest @ ..]) => (*size, Some(*base), rest),
(false, [size, rest @ ..]) => (*size, None, rest),
let facts = facts(cx, fb, c, kind, image)?;
let (size, rest) = match &facts[..] {
[size, rest @ ..] => (*size, rest),
_ => return Err(cx.fail("a shared switch's facts without their sizes")),
};
let (bits, named, lanes) = match (kind, rest) {
(Emulation::Snap(_), &[]) => (None, None, None),
(Emulation::Bicubic(_) | Emulation::Linear(_) | Emulation::Fetched(_), &[bits, named]) => {
(Emulation::Bicubic(_) | Emulation::Fetched(_), &[bits, named]) => {
(Some(bits), Some(named), None)
}
(
Emulation::Linear(_) | Emulation::Fetched(_),
&[bits, named, c0, c1, c2, c3, o0, o1, o2, o3],
) => (
(Emulation::Fetched(_), &[bits, named, c0, c1, c2, c3, o0, o1, o2, o3]) => (
Some(bits),
Some(named),
Some(crate::lower::texture::LaneConstants {
@@ -241,84 +187,11 @@ pub(crate) fn shared_value(
(Emulation::Bicubic(b), Some(bits)) => {
super::bicubic::emit_shared(cx, fb, first, (size, image), b, bits, c)?
}
(Emulation::Linear(l), Some(bits)) => {
let SampleOp::Sample {
lod,
dref,
min_lod,
offset,
} = &first.op
else {
return Err(cx.fail("a shared linear sample without its sample"));
};
// The device's sample, which a runtime sampler's word snap snaps.
let (coord, grad) = device_coordinate(
cx,
fb,
first,
grads,
((size, base), image),
first.snap.as_ref(),
)?;
let (ops, dref, beyond) = sample_operands(
cx,
fb,
first,
(coord.0, grad, lambda, false),
(lod, *min_lod, offset, *dref),
)?;
// A native class's device sample reads Metal's footprint step on the named
// candidate's size and bits (`native`).
let facts = (size, super::bicubic::Bits::Value(bits));
let (at, native) = match super::native::coordinate(cx, fb, first, l, coord, facts)? {
Some((at, native)) => (at, Some(native)),
None => (coord.1, None),
};
let device = device_access(at, dref, ops, beyond);
let x = super::linear::emit_shared(
cx,
fb,
first,
(size, image, dref),
l,
(bits, c),
&device,
native,
)?;
// A depth sample without comparison reads the first component.
if first.depth && dref.is_none() {
fb.composite_extract(x, &[0])?
} else {
x
}
}
(Emulation::Snap(p), _) => {
return snapped(
cx,
fb,
c,
(first, p),
grads,
((size, base), image, lambda),
null,
);
return snapped(cx, fb, c, (first, p), grads, (size, image), null);
}
(Emulation::Fetched(p), Some(bits)) => {
let x = fetched(
cx,
fb,
c,
(first, p),
grads,
((size, base), image, lambda),
bits,
)?;
// A depth sample without comparison reads the first component.
let x = if first.depth && matches!(first.op, SampleOp::Sample { .. }) {
fb.composite_extract(x, &[0])?
} else {
x
};
let x = fetched(cx, fb, c, (first, p), grads, (size, image), bits)?;
// The conversion, then the lanes Metal reads as constants by the merged tests, not
// the named candidate's own.
let x = held_value(
@@ -354,10 +227,8 @@ pub(crate) fn shared_value(
fb.select(named, x, n)
}
/// The facts dispatch (module docs): each arm's level-0 size, or where a runtime sampler's
/// leveled snap reads another level (`leveled`: its word and `level::by_word`'s level) that level's
/// size, then where `based` the level-0 size (Metal's offset rule reads both), and where `kind`
/// reads them its format's bits and `true`, then where the shared value takes the lanes Metal reads
/// The facts dispatch (module docs): each arm's level-0 size, and where `kind` reads them its
/// format's bits and `true`, then where the shared value takes the lanes Metal reads
/// as constants (`shared_constants`) its slot's eight lane tests (`LaneConstants`); the null arm's
/// ones, 0, and `false`.
fn facts(
@@ -365,7 +236,7 @@ fn facts(
fb: &mut FunctionBuilder<'_>,
c: &Candidates<'_>,
kind: Emulation<'_>,
(image, leveled, based): (CombinedImage, Option<(SValue, SValue)>, bool),
image: CombinedImage,
) -> BResult<Vec<SValue>> {
let u32_ = fb.module().ty(SType::Int {
width: 32,
@@ -397,17 +268,8 @@ fn facts(
let lanes_read = shared_constants(kind, c);
let read = |cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, a: &Sampling| {
let img = c.image(cx, fb, a)?;
let level0 = |fb: &mut FunctionBuilder<'_>| {
let level = fb.module().const_value(zero)?;
fb.query(ImageQuery::SizeLod(level), img)
};
let mut v = match leveled {
Some((word, nearest)) => vec![word_level_size(fb, word, nearest, img)?],
None => vec![level0(fb)?],
};
if based {
v.push(level0(fb)?);
}
let level = fb.module().const_value(zero)?;
let mut v = vec![fb.query(ImageQuery::SizeLod(level), img)?];
if let Some(bits) = kind.bits(cx, a)? {
v.push(fb.module().const_value(bits)?);
v.push(fb.module().const_value(yes)?);
@@ -421,9 +283,6 @@ fn facts(
};
let null_facts = |_: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>| {
let mut v = vec![fb.module().const_value(ones)?];
if based {
v.push(fb.module().const_value(ones)?);
}
if with_bits {
v.push(fb.module().const_value(zero)?);
v.push(fb.module().const_value(no)?);
@@ -437,10 +296,9 @@ fn facts(
c.each(cx, fb, &read, &null_facts)
}
/// The plane coordinate of sampling `s` as the device reads it, on the named candidate's size
/// `size` (image facts `image`; the level-0 size, or a leveled word snap's level's, `facts`, with
/// the level-0 size `base`): the plane coordinate scaled from pixel coordinates over the level-0
/// size, then snapped by `snap` (a pixel sampler's snap from the coordinate as given), and
/// The plane coordinate of sampling `s` as the device reads it, on the named candidate's level-0
/// size `size` (image facts `image`): the plane coordinate scaled from pixel coordinates over the
/// level-0 size, then snapped by `snap` (a pixel sampler's snap from the coordinate as given), and
/// with the layer appended; and its gradients. The first of the pair is the plane coordinate before
/// the snap, which a bias past the device's limit differentiates.
fn device_coordinate(
@@ -448,39 +306,24 @@ fn device_coordinate(
fb: &mut FunctionBuilder<'_>,
s: &Sampling,
grads: Option<(SValue, SValue)>,
((size, base), image): ((SValue, Option<SValue>), CombinedImage),
(size, image): (SValue, CombinedImage),
snap: Option<&super::position::Snap>,
) -> BResult<((SValue, SValue), Option<(SValue, SValue)>)> {
let (mut coord, mut grad) = plane_and_gradients(cx, fb, s, grads)?;
// A pixel sampler's snap reads the coordinate as given.
let given = coord;
if let Some(spec) = pixel_coordinates(cx, fb, s)? {
// Pixel coordinates scale by the level-0 size, a leveled snap's included.
// Pixel coordinates scale by the level-0 size.
let size_lanes = image.plane + u8::from(image.arrayed);
let level0 = base.unwrap_or(size);
(coord, grad) = scaled(fb, s.lanes, (level0, size_lanes), spec, (coord, grad))?;
(coord, grad) = scaled(fb, s.lanes, (size, size_lanes), spec, (coord, grad))?;
}
let plane = coord;
if let Some(snap) = snap {
// The device adds the texel offset to the snapped coordinate; each snap moves its index
// back where Metal drops it.
let offsets = snap_offsets(cx, fb, op_offset(&s.op), s.lanes)?;
coord = if let super::position::SnapKind::Word { leveled, .. } = snap.kind {
let word = sampler_word(cx, fb, s.pixel)?;
let size_lanes = image.plane + u8::from(image.arrayed);
// A shared access reads no slot's `OffsetBaseAxes` (`Sampling::shared_shape`).
super::position::snapped_by_word(
fb,
(word, leveled),
(coord, &offsets, None),
s.lanes,
(size, base, size_lanes),
)?
} else {
let from = if snap.pixel { given } else { coord };
let at = (from, offsets.as_slice(), None);
super::position::snapped_on(cx, fb, snap, at, s.lanes, (size, image))?
};
let at = (given, offsets.as_slice(), None);
coord = super::position::snapped_on(cx, fb, snap, at, s.lanes, (size, image))?;
}
let (coord, _) = layered(cx, fb, s, coord)?;
Ok(((plane, coord), grad))
@@ -495,7 +338,7 @@ fn snapped(
c: &Candidates<'_>,
(first, snap): (&Sampling, &super::position::Snap),
grads: Option<(SValue, SValue)>,
(size, image, lambda): ((SValue, Option<SValue>), CombinedImage, Option<SValue>),
(size, image): (SValue, CombinedImage),
null: &NullLeaf<'_>,
) -> BResult<SValue> {
let ((plane, coord), grad) =
@@ -511,7 +354,7 @@ fn snapped(
cx,
fb,
first,
(plane, grad, lambda, false),
(plane, grad, false),
(lod, *min_lod, offset, *dref),
)?;
let read = |cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, a: &Sampling| {
@@ -594,92 +437,42 @@ fn snapped(
}
}
/// A shared plain fetch of the base level (module docs): the device's coordinate snapped once on
/// the named size where the sampling has a snap, and `fetched::emit_shared`'s fetches of each arm's
/// texels where the named format `bits` is of the 32-bit float class, else each arm's device
/// access: a sample's one texel, or a gather's component `component` of its four.
/// A shared `half` gather's fetch (module docs): the device's coordinate snapped once on the named
/// size where the sampling has a snap, and `fetched::emit_shared`'s fetches of each arm's texels
/// where the named format `bits` is of the half-float class, else each arm's device gather of
/// component `component`.
fn fetched(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
c: &Candidates<'_>,
(first, p): (&Sampling, &super::fetched::Plain),
grads: Option<(SValue, SValue)>,
((size, base), image, lambda): ((SValue, Option<SValue>), CombinedImage, Option<SValue>),
(size, image): (SValue, CombinedImage),
bits: SValue,
) -> BResult<SValue> {
let ((plane, coord), grad) = device_coordinate(
cx,
fb,
first,
grads,
((size, base), image),
first.snap.as_ref(),
)?;
match &first.op {
SampleOp::Sample {
lod,
dref: None,
min_lod,
offset,
} => {
let (ops, dref, beyond) = sample_operands(
cx,
fb,
first,
(plane, grad, lambda, false),
(lod, *min_lod, offset, None),
)?;
let device = device_access(coord, dref, ops, beyond);
super::fetched::emit_shared(
cx,
fb,
first,
(size, image),
p,
(bits, c),
&super::fetched::one,
&device,
)
}
SampleOp::Gather {
component,
dref: None,
offset,
} => {
let mut ops = ImageOperands::default();
offset_operands(cx, fb, offset, first.lanes, &mut ops)?;
let component = *component;
let vec4 = super::bicubic::Tys::new(fb)?.vec4;
let gathered = move |fb: &mut FunctionBuilder<'_>, texels: &[SValue]| {
let mut parts = Vec::with_capacity(texels.len());
for &x in texels {
parts.push(fb.composite_extract(x, &[component])?);
}
fb.composite_construct(vec4, &parts)
};
let device =
|fb: &mut FunctionBuilder<'_>, si: SValue| fb.gather(si, coord, component, &ops);
super::fetched::emit_shared(
cx,
fb,
first,
(size, image),
p,
(bits, c),
&gathered,
&device,
)
}
_ => Err(cx.fail("a shared fetch without its plain sample or gather")),
}
let ((_, coord), _) =
device_coordinate(cx, fb, first, grads, (size, image), first.snap.as_ref())?;
let SampleOp::Gather {
component,
dref: None,
offset,
} = &first.op
else {
return Err(cx.fail("a shared fetch without its gather"));
};
let mut ops = ImageOperands::default();
offset_operands(cx, fb, offset, first.lanes, &mut ops)?;
let component = *component;
let device = |fb: &mut FunctionBuilder<'_>, si: SValue| fb.gather(si, coord, component, &ops);
super::fetched::emit_shared(cx, fb, first, (size, image), p, (bits, c), &device)
}
/// Whether the shared value of `kind` over `c` sets the lanes Metal reads as constants by its
/// arms' merged lane tests: a linear sample's or a plain fetch's, whose arms take them
/// arms' merged lane tests: a plain fetch's, whose arms take them
/// ([`Unmapped`]). A snapped access converts each arm's texel in its arm, with its own slot's; a
/// bicubic sample's fetches take none.
fn shared_constants(kind: Emulation<'_>, c: &Candidates<'_>) -> bool {
matches!(kind, Emulation::Linear(_) | Emulation::Fetched(_))
matches!(kind, Emulation::Fetched(_))
&& c.arms.iter().any(|(_, a)| a.unmapped != Unmapped::Device)
}
+7 -156
View File
@@ -886,7 +886,7 @@ fn from_image(
decl: &ImageDecl,
form: TexelForm,
x: SValue,
(half, float): (Option<HalfClass>, Option<FloatClass>),
half: Option<HalfClass>,
) -> BResult<SValue> {
if r64(decl) {
return ulong_texel(fb, x);
@@ -921,18 +921,14 @@ fn from_image(
true => x_channel_read(fb, decl, x)?,
false => x,
};
// A `half` texel of a slot that converts by the bound format's class, and a `float` one: a
// read's lanes are one texel's.
let x = match (half, float) {
(Some(h), _) => {
// A `half` texel of a slot that converts by the bound format's class: a read's lanes are one
// texel's.
let x = match half {
Some(h) => {
let lanes = TexelLanes::Texel.value(fb)?;
h.convert(fb, x, (HalfForm::Read, lanes), TexelOrigin::Image)?
}
(None, Some(f)) => {
let lanes = TexelLanes::Texel.value(fb)?;
f.convert(fb, x, lanes)?
}
(None, None) => x,
None => x,
};
let x = if form.lanes == 1 {
fb.composite_extract(x, &[0])?
@@ -1046,40 +1042,6 @@ pub(crate) fn srgb_filtered_texel(
}
}
/// A raw cube gather's held texel (`form`, a `half` or `float` result): the four taps' raw codes
/// `codes` (a `vec4` of `f32`, gather order, channel `component`) decoded as [`srgb_raw_texel`]
/// decodes a gather's, but for each lane `corner` names, the tap past both edges of its face, which
/// takes the made-up corner `made` (the corner routine's channel, an `f32`: a color channel's step
/// over 4095, alpha's code over 255, each correctly rounded, so that rounding `made · 4095` or
/// `made · 255` to nearest recovers the step or code exactly).
pub(crate) fn srgb_raw_gather(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
form: TexelForm,
(codes, component): (SValue, u32),
(made, corner): (SValue, [SValue; 4]),
) -> BResult<SValue> {
let color = component != 3;
let (k, d) = srgb_raw_steps(cx, fb, codes, [color; 4])?;
let u = u32_ty(fb)?;
let vu = vec(fb, u, 4)?;
let grid = match color {
true => 4095.0,
false => 255.0,
};
let scale = f32s(fb, 1, grid)?;
let m = fb.binary(BinOp::FMul, made, scale)?;
let m = fb.glsl(GlslOp::RoundEven, &[m])?;
let m = fb.convert(ConvOp::ConvertFToU, m, u)?;
let mut lanes = Vec::with_capacity(4);
for (i, here) in (0u32..).zip(corner) {
let lane = fb.composite_extract(k, &[i])?;
lanes.push(fb.select(here, m, lane)?);
}
let k = fb.composite_construct(vu, &lanes)?;
srgb_ratio(fb, form, (k, d))
}
/// The steps of raw view texel `x` ([`srgb_raw_texel`]): per lane the code `c` recovered by
/// rounding `x · 255` to nearest, a color lane's table step `k` with its grid 4095, an alpha
/// lane's `c` with 255, as a `uvec4` of numerators and one of denominators.
@@ -1263,105 +1225,6 @@ impl HalfClass {
}
}
/// The held `half` texel of image texel `x` (a `vec4` of `f32`) under access form `form`, by the
/// bound format's class `class` (a `TexelFormat` specialization's bits as a value): the shared
/// emulation of a switch-at-use converts its candidates' samples by the named candidate's class
/// (SEMANTICS 1012), as [`HalfClass::convert`] converts a slot's by its constant. Its value may be
/// filtered. Where the module defines no routine, the texel is the device's: its `half` rounded to
/// nearest even (`narrow::round_texel`), as every access's under native device sampling.
pub(crate) fn half_by_class(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
x: SValue,
class: SValue,
form: HalfForm,
) -> BResult<SValue> {
let Some(routine) = cx.decl.families.texture.half_routine else {
let half = crate::lower::arith::legal::Form {
held: crate::lower::arith::legal::Held::Float(
crate::lower::arith::legal::FloatFmt::Half,
),
lanes: 4,
};
return narrow::round_texel(fb, half, x);
};
let lanes = TexelLanes::Filtered.value(fb)?;
super::half::convert(fb, routine, x, class, (form, lanes))
}
/// The conversion of a slot's `float` texels by the bound format's class: the module's routine and
/// the slot's `TexelFormat` specialization constant; or of a heap color texture's by the class its
/// handle carries, read from the handle.
#[derive(Clone, Copy, Debug)]
pub(crate) struct FloatClass {
routine: FuncId,
class: ClassOf,
}
impl FloatClass {
/// The `float` texel of image texel `x` (a `vec4` of `f32`), its lanes `lanes`
/// (`half::TexelLanes::code`).
pub(crate) fn convert(
self,
fb: &mut FunctionBuilder<'_>,
x: SValue,
lanes: SValue,
) -> BResult<SValue> {
let class = match self.class {
ClassOf::Slot(c) => fb.module().const_value(c)?,
ClassOf::Heap(v) => v,
};
super::float_texel::convert(fb, self.routine, x, class, lanes)
}
}
/// How the `float` texels of a read, gather, or sample of `image` in form `texel` convert, where
/// the access converts them (its `float_texel`): the module's routine and the slot's `TexelFormat`
/// constant.
pub(crate) fn float_class(
cx: &EmitCx<'_>,
image: &ImageRef,
texel: TexelForm,
) -> Option<FloatClass> {
if texel.conv != TexelConv::F32 {
return None;
}
let ImageRef::Slot(index) = *image else {
return None;
};
let t = &cx.decl.families.texture;
Some(FloatClass {
routine: t.float_routine?,
class: ClassOf::Slot(t.half_format.get(&index).copied()?),
})
}
/// How the `float` texels of a read, gather, or sample of the heap color texture of handle
/// `handle` convert, in form `texel`, where the access converts them (its `float_texel`): by the
/// class the handle carries, read from it, where the module defines the routine and the class table
/// (`TexturePlan::heap_float`), else `None`.
pub(crate) fn heap_float_class(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
handle: ValueId,
texel: TexelForm,
) -> BResult<Option<FloatClass>> {
let t = &cx.decl.families.texture;
let (true, Some(routine), Some(_)) = (
texel.conv == TexelConv::F32,
t.float_routine,
t.heap_classes,
) else {
return Ok(None);
};
let h = cx.operand(fb, handle)?;
let class = super::heap_texel_class(cx, fb, h)?;
Ok(Some(FloatClass {
routine,
class: ClassOf::Heap(class),
}))
}
/// Texture slot `index`'s `TexelFormat` specialization constant, where it declares one.
pub(crate) fn texel_format_const(cx: &EmitCx<'_>, index: u32) -> Option<ConstId> {
cx.decl.families.texture.half_format.get(&index).copied()
@@ -3026,19 +2889,7 @@ fn read(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BResult<
Some(_) => srgb_raw_texel(cx, fb, r.texel, texel, SRGB_TEXEL)?,
None => {
let half = half_class(cx, &r.image, r.texel);
let float = match (r.float_texel, r.image) {
(false, _) => None,
// A heap texture's by the class its handle carries.
(true, ImageRef::Heap { handle, .. }) => heap_float_class(cx, fb, handle, r.texel)?,
(true, image) => float_class(cx, &image, r.texel),
};
let float = match (r.float_texel, float) {
(true, None) => {
return Err(cx.fail("a `float` read without its conversion routine"));
}
(_, float) => float,
};
from_image(cx, fb, &decl, r.texel, texel, (half, float))?
from_image(cx, fb, &decl, r.texel, texel, half)?
}
};
// A swizzled texture's swizzle at a storage slot, on the converted texel.
@@ -1,188 +0,0 @@
//! Metal's `float` value of one texel of a normalized or packed format.
//!
//! A read, a 2D gather, or a sample whose sampler reads one texel of one level, with a `float`
//! result, of a color texture slot (or, a depth texture slot, a comparison's never) returns the
//! device's conversion of each channel's code `c`, which Vulkan bounds only loosely: lavapipe
//! multiplies by the reciprocal (some 8-bit codes one ulp high, a 16-bit code one ulp low), and ANV
//! and NVIDIA widen a 5- or 6-bit channel by replicating its bits. Metal answers `c / (2^b - 1)`
//! correctly rounded (measured on an Apple M3 Max, every read and nearest word of the and the
//! committed rows), and reads `RG11B10Float`'s NaN codes, and a half-float texel's NaNs, as
//! `0x7fc00000`.
//!
//! The slot's `SpecKey::TexelFormat` specialization (`metal::texel_format`) names the bound
//! format's class, and one module routine, [`define`]: `fn(x: vec4, flags: u32, channel: u32) ->
//! vec4`, converts the device's value by it, called with the slot's constant and the access's
//! lanes (`half::TexelLanes`), so once a device specializes the module and inlines the call, the
//! other arms fold away:
//!
//! - **The normalized families** (`BicubicTexels::EXACT` without a packed field): the value's
//! step on the `half` routine's grid (`1/4080`, `1/2032`, `1/65535`, `1/32767`, each a multiple
//! of its code scale, so the step is the code's), then `n / D` correctly rounded
//! (`ratio_to_f32`).
//! - **A packed normalized class** (`TexelFormat::PACKED` with scales): each channel's code on
//! its scale `2^b - 1`, then `c / (2^b - 1)` correctly rounded; a gather's lanes take the
//! gathered channel's scale.
//! - **A small float** (`PackedTexels::SmallFloat`): the device's value, exact, a NaN Metal's
//! `0x7fc00000`.
//! - **A half float** (`BicubicTexels::HALF`: `R16Float`, `RG16Float`, `RGBA16Float`,
//! `RGBX16Float`, and a swizzled small float, whose class keeps the family without the field):
//! the device's value, the half's exact widening, a NaN Metal's `0x7fc00000`. Metal hands back
//! every NaN of a half-float texel so in a `float` result, whatever its sign and payload, by a
//! read through `access::read` or `access::read_write`, of a 2D, 3D or array texture or a texture
//! buffer, a nearest sample and a gather; where the device widens it with its sign and payload
//! (NVIDIA, RADV), as `0xffc00000` (ANV) or quieted (lavapipe).
//! - **A YCbCr format** (`PackedTexels::YCbCr2048`, a field without scales): the device's value,
//! which its view holds as Metal's read exactly.
//! - **Any other class**, and any value that may be filtered (`TexelLanes::Filtered`: a 16-bit
//! format's filtered value is finer than its code, and Metal's filter of a packed format is not
//! modelled): the device's value.
//!
//! On a device that samples through Metal's own sampler (`VkProperty::MetalSampler`) the device's
//! value is Metal's, so no module defines the routine there.
use crate::lower::arith::legal::{FloatFmt, Form, Held};
use crate::lower::arith::ops::{splat, ty};
use crate::lower::arith::texel_round;
use crate::metal::bicubic::BicubicTexels;
use crate::metal::texel_format::TexelFormat;
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::{BResult, BuildError, OperandRule};
use crate::spirv::ids::{FuncId, TypeId, Value as SValue};
use crate::spirv::ir::{BinOp, ConvOp, Type as SType, UnOp};
use super::half::{packed_scales, TEXEL_LANES};
/// An upper estimate of the routine's words, counted once per module that defines it
/// (`the_float_texel_routine_words_bound_its_emission`).
pub const ROUTINE_WORDS: u64 = 1200;
/// An upper estimate of one call's words: the call and its two constant arguments.
pub const CALL_WORDS: u32 = 16;
/// The census name of the routine.
pub const CENSUS_NAME: &str = "texture.float_texel";
/// Metal's `float` NaN (`RG11B10Float`'s NaN codes and a half-float texel's NaNs).
const METAL_NAN: u32 = 0x7fc0_0000;
fn fform() -> Form {
Form {
held: Held::Float(FloatFmt::F32),
lanes: 4,
}
}
fn uform(lanes: u8) -> Form {
Form {
held: Held::Int {
bits: 32,
container: 32,
},
lanes,
}
}
/// Define the routine `fn(x: vec4, flags: u32, channel: u32) -> vec4` in `mb` (module docs;
/// `channel` is `half::TexelLanes::code`).
pub fn define(mb: &mut ModuleBuilder) -> BResult<FuncId> {
let f32_ = mb.ty(SType::Float { width: 32 })?;
let u32_ = mb.ty(SType::Int {
width: 32,
signed: false,
})?;
let vf = mb.ty(SType::Vector { elem: f32_, len: 4 })?;
let vu = mb.ty(SType::Vector { elem: u32_, len: 4 })?;
let mut fb = mb.routine(vf)?;
let x = fb.param(vf)?;
let flags = fb.param(u32_)?;
let channel = fb.param(u32_)?;
let r = body(&mut fb, x, flags, channel, (f32_, vu))?;
fb.ret(Some(r))?;
fb.finish()
}
fn body(
fb: &mut FunctionBuilder<'_>,
x: SValue,
flags: SValue,
channel: SValue,
(f32_, vu): (TypeId, TypeId),
) -> BResult<SValue> {
let f = fform();
let u1 = |fb: &mut FunctionBuilder<'_>, v: u32| splat(fb, uform(1), u64::from(v));
let has = |fb: &mut FunctionBuilder<'_>, bit: u32| -> BResult<SValue> {
let m = u1(fb, bit)?;
let z = u1(fb, 0)?;
let and = fb.binary(BinOp::BitwiseAnd, flags, m)?;
fb.binary(BinOp::INotEqual, and, z)
};
let texel_lanes = u1(fb, TEXEL_LANES)?;
let single = fb.binary(BinOp::ULessThanEqual, channel, texel_lanes)?;
let ft = ty(fb, f)?;
// The normalized families: the value onto the format's grid `D`, then `n / D` to nearest
// even. A treatment without `EXACT` takes the 16-bit unsigned grid, which keeps every
// operation of the arm (selected away) within its operands' range.
let wide = has(fb, BicubicTexels::WIDE16)?;
let signed = has(fb, BicubicTexels::SNORM)?;
let (g8, g8s) = (u1(fb, TexelFormat::GRID8)?, u1(fb, TexelFormat::GRID8S)?);
let (g16, g16s) = (u1(fb, TexelFormat::GRID16)?, u1(fb, TexelFormat::GRID16S)?);
let narrow = fb.select(signed, g8s, g8)?;
let broad = fb.select(signed, g16s, g16)?;
let d = fb.select(wide, broad, narrow)?;
let exact = has(fb, BicubicTexels::EXACT)?;
let d = fb.select(exact, d, g16)?;
let df = fb.convert(ConvOp::ConvertUToF, d, f32_)?;
let df = fb.composite_construct(ft, &[df; 4])?;
let neg_df = fb.unary(UnOp::FNegate, df)?;
let dv = fb.composite_construct(vu, &[d; 4])?;
let n = texel_round::grid_step(fb, f, x, df, neg_df)?;
let norm = texel_round::grid_value(fb, uform(4), n, dv, |fb, m, d| {
texel_round::ratio_to_f32(fb, uform(4), m, d)
})?;
// A packed class: each channel's code on its scale, then `c / S` to nearest even; a small
// or half float's NaN Metal's.
let (scales, coded, small) = packed_scales(fb, flags, channel)?;
let sf = fb.convert(ConvOp::ConvertUToF, scales, ft)?;
let neg_sf = fb.unary(UnOp::FNegate, sf)?;
let codes = texel_round::grid_step(fb, f, x, sf, neg_sf)?;
let packed = texel_round::grid_value(fb, uform(4), codes, scales, |fb, m, d| {
texel_round::ratio_to_f32(fb, uform(4), m, d)
})?;
let nan = fb.unary(UnOp::IsNan, x)?;
let metal_nan = splat(fb, uform(4), u64::from(METAL_NAN))?;
let metal_nan = fb.convert(ConvOp::Bitcast, metal_nan, ft)?;
let canonical = fb.select(nan, metal_nan, x)?;
// The normalized families' grids are a class's own: a packed class's `EXACT` family sums on
// its field's grids (`half::body`'s `norm_arm`), so a field without scales (a YCbCr format's,
// whose view holds Metal's value exactly) keeps the device's value.
let in_field = has(fb, TexelFormat::PACKED_MASK)?;
let own_grid = fb.unary(UnOp::LogicalNot, in_field)?;
let exact = fb.binary(BinOp::LogicalAnd, exact, own_grid)?;
let exact = fb.binary(BinOp::LogicalAnd, exact, single)?;
let coded = fb.binary(BinOp::LogicalAnd, coded, single)?;
let half = has(fb, BicubicTexels::HALF)?;
let small = fb.binary(BinOp::LogicalOr, small, half)?;
let small = fb.binary(BinOp::LogicalAnd, small, single)?;
let r = fb.select(exact, norm, x)?;
let r = fb.select(coded, packed, r)?;
fb.select(small, canonical, r)
}
/// The `float` texel of image texel `x` (a `vec4` of `f32`), converted by `routine` under the
/// slot's treatment constant `flags` (its `TexelFormat` specialization) and `lanes`, the access's
/// `half::TexelLanes::code` (a constant, or the shader's choice where a runtime sampler's word
/// decides whether a sample reads one texel).
pub fn convert(
fb: &mut FunctionBuilder<'_>,
routine: FuncId,
x: SValue,
flags: SValue,
lanes: SValue,
) -> BResult<SValue> {
// Every call of the routine returns its texel.
fb.call(routine, &[x, flags, lanes])?
.ok_or(BuildError::Operand {
op: crate::spv::Op::FunctionCall,
rule: OperandRule::Callee,
})
}
@@ -273,8 +273,6 @@ struct PackedField {
fields: Vec<([u32; 4], SValue)>,
/// Whether the field states coded channels (a field with scales).
coded: SValue,
/// Whether the field is `PackedTexels::SmallFloat`.
small: SValue,
/// Whether the field's one texel rounds with ties away from zero, a two-plane YCbCr format's
/// or `RGB10A2Unorm_sRGB`'s (`PackedTexels::ties_away`).
ycbcr: SValue,
@@ -316,15 +314,12 @@ impl PackedField {
coded = fb.binary(BinOp::LogicalOr, coded, is)?;
fields.push((s, is));
}
let small = u1(fb, PackedTexels::SmallFloat as u32)?;
let small = fb.binary(BinOp::IEqual, field, small)?;
let three = u1(fb, 3)?;
let gathered = fb.binary(BinOp::ULessThanEqual, channel, three)?;
let channel = fb.glsl(GlslOp::UMin, &[channel, three])?;
Ok(PackedField {
fields,
coded,
small,
ycbcr,
gathered,
channel,
@@ -347,22 +342,6 @@ impl PackedField {
}
}
/// The code scales `S` of a packed class's channels (`TexelFormat::PACKED`) as `u32` lanes, a
/// gather's lanes each its channel's (`channel` below 4), 1 in every lane for any other field;
/// whether the field states coded channels (a field with scales); and whether it is
/// `PackedTexels::SmallFloat`. Shared with the `float` routine (`float_texel`).
pub(crate) fn packed_scales(
fb: &mut FunctionBuilder<'_>,
flags: SValue,
channel: SValue,
) -> BResult<(SValue, SValue, SValue)> {
let p = PackedField::read(fb, flags, channel)?;
let scales = p.lanes(fb, &|fb, s| {
lanes_of(fb, uform(4), s.unwrap_or([1; 4]).map(u64::from))
})?;
Ok((scales, p.coded, p.small))
}
/// The `f32` bits of `v` and of `RN(1 / v)`, the reciprocal correctly rounded to `f32`.
fn grid_bits(v: u32) -> (u64, u64) {
let d = v as f32;
+62 -211
View File
@@ -123,7 +123,6 @@ mod alpha;
mod atomic;
mod cooperative;
mod emit;
pub mod float_texel;
pub mod half;
pub(crate) mod heap_raw;
mod slice;
@@ -134,13 +133,12 @@ pub(crate) use absent::absent_arm;
pub use absent::ABSENT_ARM;
pub use atomic::TexAtomic;
pub(crate) use emit::{
constant_lanes, constant_lanes_by, dispatch, extended_table, float_class, half_by_class,
half_class, heap_element, heap_float_class, heap_half_class, heap_raw_form, heap_raw_image,
live_or_zero, reinterpret, resident_access, rgb9e5_word, slot_image, sparse_spec,
srgb_filtered_texel, srgb_raw_gather, srgb_raw_tap, srgb_raw_texel, swizzled_float,
swizzled_gather, swizzled_held, texel_format_const, tile_map, tiled_word, with_word, HalfClass,
NullLeaf, TileLevel, RGB9E5_WORDS, SRGB_FILTERED_WORDS, SRGB_RAW_WORDS, SRGB_TAP_WORDS,
SRGB_TEXEL,
constant_lanes, constant_lanes_by, dispatch, extended_table, half_class, heap_element,
heap_half_class, heap_raw_form, heap_raw_image, live_or_zero, reinterpret, resident_access,
rgb9e5_word, slot_image, sparse_spec, srgb_filtered_texel, srgb_raw_tap, srgb_raw_texel,
swizzled_float, swizzled_gather, swizzled_held, texel_format_const, tile_map, tiled_word,
with_word, NullLeaf, TileLevel, RGB9E5_WORDS, SRGB_FILTERED_WORDS, SRGB_RAW_WORDS,
SRGB_TAP_WORDS, SRGB_TEXEL,
};
pub use emit::{emit, held_texel, to_image};
pub(crate) use slot::depth_comparison;
@@ -317,9 +315,6 @@ pub struct Read {
/// where the handle's class index is `A8Unorm`'s, on a device that holds such a texture's alpha
/// in red ([`heap_alpha_in_red`]).
pub heap_alpha_red: bool,
/// A `float` texel of the slot converts by the bound format's class (`float_texel`): its
/// code recovered from the device's value and divided exactly.
pub float_texel: bool,
/// The read, of a slot's color texture on a profile whose sparse textures are sparse images
/// (it enables `shaderResourceResidency`), sets the lanes Metal reads as constants (a channel
/// the format lacks, through the swizzle) after it, from the slot's `ConstantLanes`
@@ -381,11 +376,6 @@ fn read_words(r: &Read) -> u32 {
crate::lower::arith::extended_range::DECODE_WORDS + r.texel.read_words()
} else if r.texel.conv == TexelConv::F16 {
half::CALL_WORDS.max(r.texel.read_words())
} else if r.float_texel {
// A heap texture's call reads the class its handle carries first.
float_texel::CALL_WORDS
+ r.texel.read_words()
+ if r.image.heap() { HEAP_CLASS_WORDS } else { 0 }
} else {
r.texel.read_words()
};
@@ -707,9 +697,9 @@ impl Switch {
};
// The shared form (SEMANTICS 1012): the emulation once, and per arm its image's reads.
if let Some(arms) = self.shared() {
let (once, per_arm) = arms.first().map_or((0, 0), |(_, s)| {
(s.words() + s.routed_words(), s.shared_arm_words())
});
let (once, per_arm) = arms
.first()
.map_or((0, 0), |(_, s)| (s.words(), s.shared_arm_words()));
return once
.saturating_add(per_arm.saturating_mul(arms.len() as u32))
.saturating_add(crate::lower::sampler::SHARED_WORDS)
@@ -743,22 +733,15 @@ impl FamilyStrategy for TextureStrategy {
impl TextureStrategy {
/// The sampled images of combined bindings this strategy makes: its own sampling's, or its
/// switch's arms' (each the static sampling of one binding). Under the separate form each is
/// made from the separate texture and sampler. A sampling makes one in its open block, and
/// Metal's emulated linear filter one more in each block that reads the binding: the
/// emulation's and the device's sample's, or the raw emulation's alone; an emulated cube
/// gather's device arm one more, where it has one; a plain fetch one in each arm of its branch,
/// the fetch's and the device's access's. A switch that emulates once ([`Switch::shared`],
/// made from the separate texture and sampler. A sampling makes one in its open block, and a
/// plain fetch one in each arm of its branch, the fetch's and the device's access's. A switch that emulates once ([`Switch::shared`],
/// SEMANTICS 1012) makes them only for its arms' device accesses
/// ([`Sampling::shared_sampled_images`]).
pub fn combined_samplings(&self) -> u32 {
match self {
TextureStrategy::Sampling(s) => match s.source {
crate::lower::sampler::Source::Combined(_) => {
1 + s.linear.as_ref().map_or(0, |l| if l.raw { 1 } else { 2 })
+ s.cube_gather
.as_ref()
.map_or(0, |g| u32::from(!g.raw && !g.integer))
+ 2 * u32::from(s.fetched.is_some())
1 + 2 * u32::from(s.fetched.is_some())
}
_ => 0,
},
@@ -912,10 +895,6 @@ pub struct TexturePlan {
/// Some heap color texture's sample or gather has a `half` result, which converts by the
/// class its handle carries (`emit::heap_half_class`): the module defines the `half` routine.
pub heap_half: bool,
/// Some heap color texture's read, gather or sample with a `float` result may read one
/// texel, which converts by the class its handle carries (`emit::heap_float_class`): the module
/// defines the `float` routine.
pub heap_float: bool,
/// The results of the heap reads that decode a member of a form a heap reads
/// (`ExtendedRange::HEAP_READ`): `false` a `float` one, `true` a `half` one. The module
/// defines that decode's routine for each ([`heap_raw::define`]).
@@ -1013,9 +992,6 @@ pub struct Declared {
/// The `PlainHalfTexels` specialization constant of each slot of those on a device whose
/// routine tells apart Metal's sampler's families alone (`half::HalfFamilies::MetalSampler`).
pub plain_half: BTreeMap<u32, SValue>,
/// The module's routine converting one texel to a `float` result by the class
/// ([`float_texel::define`]), defined once where a slot takes it.
pub float_routine: Option<FuncId>,
/// The `TextureSwizzle` specialization constant of each texture buffer slot whose reads
/// apply the bound texture buffer's swizzle, and of each storage slot of
/// `LoweringInputs::swizzled_storage` whose reads and writes apply the bound texture's, or
@@ -1257,9 +1233,6 @@ pub fn declare(
)?;
d.plain_half.insert(*index, mb.const_value(c)?);
}
if s.float_format && d.float_routine.is_none() {
d.float_routine = Some(float_texel::define(mb)?);
}
if s.swizzle {
let u32_ = mb.ty(SType::Int {
width: 32,
@@ -1353,9 +1326,6 @@ pub fn declare(
if plan.families.texture.heap_half && d.half_routine.is_none() {
d.half_routine = Some(half::define(mb, plan.families.texture.half_families)?);
}
if plan.families.texture.heap_float && d.float_routine.is_none() {
d.float_routine = Some(float_texel::define(mb)?);
}
Ok(d)
}
@@ -1679,88 +1649,37 @@ pub(crate) fn half_texel_nans(
}
}
/// A read, gather, or sample of `image`, of shape `shape`, with a `float` result that may read
/// one texel (`one` not [`OneTexel::Never`]): on a color texture slot, a texture buffer's included,
/// on a profile without Metal's own sampler (`VkProperty::MetalSampler`, whose device value is
/// Metal's), its texel converts by the bound format's class (`float_texel`), which the slot's
/// `TexelFormat` specialization gives (`RuntimeFact::TexelFormat`); a heap color texture's (not a
/// texture buffer's) by the class its handle carries, which the module reads from the handle
/// (`AccessPlan::heap_class`). Whether it does. Nothing is noted: the conversion is exact where the
/// class names a normalized family, a packed one or a half-float one, and the device's value
/// elsewhere, as before. A heap's texture buffer carries no class, so it is not converted, and a
/// half-float texel's NaN there stays the device's: `PrecisionNote::DeviceNanEncoding`.
///
/// A depth texture's too, a comparison's never (its caller's test): Metal reads and samples one
/// texel of `Depth16Unorm` as `c / 65535` correctly rounded (every code), its
/// class `R16Unorm`'s, where a device may multiply by the reciprocal (lavapipe: 512 codes one ulp
/// off); a 32-bit float depth's class keeps the device's value. A heap's depth texture's handle
/// carries that class as a colour one's does (`metal::texel_format::heap_class` of its format), so
/// it converts by it alike.
pub(crate) fn float_texels(
/// Record what a read, gather, or sample of `image`, of shape `shape`, with a `float` result that
/// may read one texel (`one` not [`OneTexel::Never`]) answers on a profile without Metal's own
/// sampler (`VkProperty::MetalSampler`, whose device value is Metal's): the device's conversion of
/// the texel's codes, `PrecisionNote::DeviceTexelConversion`; of a heap's texture buffer, which no
/// class reaches, a half-float texel's NaN the device's decode, `PrecisionNote::DeviceNanEncoding`.
pub(crate) fn float_texel_notes(
cx: &mut SelectCx<'_>,
image: ImageRef,
shape: ImageShape,
one: OneTexel,
device: bool,
) -> Result<bool, Error> {
if one == OneTexel::Never {
return Ok(false);
) {
if one == OneTexel::Never || !device_texels(cx) {
return;
}
let metal_sampler = cx
.profile
.fields()
.enabled
.properties
.contains(&crate::device::requirements::VkProperty::MetalSampler);
if metal_sampler {
return Ok(false);
}
// Native device sampling: the device's value, but where a heap's texture buffer notes its
// NaN below (it carries no class to convert by under either policy).
let heap_buffer = image.heap() && shape.dim == ImageDim::Buffer;
if device && !heap_buffer {
cx.precision.insert(PrecisionNote::DeviceTexelConversion);
return Ok(false);
}
let index = match image {
ImageRef::Slot(index) => index,
ImageRef::Heap { .. } if shape.dim != ImageDim::Buffer => {
cx.families.texture.heap_float = true;
cx.families.access.heap_class = true;
return Ok(true);
}
// A heap's texture buffer carries no class: a half-float texel's NaN stays the device's.
ImageRef::Heap { .. } => {
cx.precision.insert(PrecisionNote::DeviceNanEncoding);
return Ok(false);
}
let note = match image.heap() && shape.dim == ImageDim::Buffer {
true => PrecisionNote::DeviceNanEncoding,
false => PrecisionNote::DeviceTexelConversion,
};
let slot = slot_of(cx, index)?.slot;
if let Some(s) = cx.families.texture.slots.get_mut(&index) {
s.float_format = true;
}
cx.facts
.insert(crate::pipeline::facts::RuntimeFact::TexelFormat { slot });
Ok(true)
cx.precision.insert(note);
}
/// Whether an access's `float` or `half` texel is the device's conversion: on a profile whose
/// device does not sample through Metal's own texture unit (`VkProperty::MetalSampler`, whose value
/// is Metal's and keeps the conversion), where the policy says so (`TexelConversionPolicy::Device`,
/// the default), and for a sample or gather (`sampled`) also where the device's sampler answers it
/// (`DeviceProfile::device_samples`, `SamplingPolicy::NativeDevice`), whose conversion of a
/// sample's one texel would read the runtime sampler's filter and split the pipeline by it. A
/// read's texel under `TexelConversionPolicy::Exact` is Metal's conversion on every sampling
/// policy. Every access of a kind agrees: the selection states a sample's `half` conversion on the
/// access (`Sampling::half_texel`), which the emission follows.
pub(crate) fn device_texels(cx: &SelectCx<'_>, sampled: bool) -> bool {
let fields = cx.profile.fields();
let metal = fields
/// is Metal's and keeps the conversion). Every access of a kind agrees: the selection states a
/// sample's `half` conversion on the access (`Sampling::half_texel`), which the emission follows.
pub(crate) fn device_texels(cx: &SelectCx<'_>) -> bool {
!cx.profile
.fields()
.enabled
.properties
.contains(&crate::device::requirements::VkProperty::MetalSampler);
let policy = fields.texel_conversion == crate::device::TexelConversionPolicy::Device;
!metal && (policy || (sampled && cx.profile.device_samples()))
.contains(&crate::device::requirements::VkProperty::MetalSampler)
}
/// The families the module's `half` routine tells apart (`half::HalfFamilies`): on a device whose
@@ -1832,15 +1751,14 @@ fn unconverted_class(cx: &mut SelectCx<'_>, index: u32) -> Result<NoteClause, Er
.into())
}
/// An emulated linear sample of `image` that converts no texel to `half` by the class: a raw
/// sample, whose emulation reads the `UNORM`, `SRGB`, and channel bits, or a sample with a `float`
/// result, whose emulation reads the format's treatment; or an emulated cube gather, a depth cube's
/// included, whose corner rule the class states. The slot's `TexelFormat` specialization
/// An access of texture slot `image` that reads its class without converting a texel to `half` by
/// it: a raw sRGB access, whose decode reads the `UNORM`, `SRGB`, and channel bits, a fetched
/// gather and a NaN texel's rule. The slot's `TexelFormat` specialization
/// (`RuntimeFact::TexelFormat`), without the conversion routine. Nothing is noted here: a raw
/// sample's decode is exact, and the sample's selection records its filter's note.
/// access's decode is exact, and the access's selection records its own notes.
pub(crate) fn texel_format_spec(cx: &mut SelectCx<'_>, image: ImageRef) -> Result<(), Error> {
let ImageRef::Slot(index) = image else {
return Err(cx.invariant("an emulated linear sample of a heap element"));
return Err(cx.invariant("a slot's class of a heap element"));
};
let slot = slot_of(cx, index)?.slot;
if let Some(s) = cx.families.texture.slots.get_mut(&index) {
@@ -1851,42 +1769,6 @@ pub(crate) fn texel_format_spec(cx: &mut SelectCx<'_>, image: ImageRef) -> Resul
Ok(())
}
/// Whether a linear sample of `image` (shape `shape`) on a device whose sampler answers it
/// (`DeviceProfile::device_samples`) takes the emulation of Metal's filter: at a sampled color
/// texture slot under its YCbCr variant (`LoweringInputs::ycbcr_textures`), whose bound format's
/// view holds converted texels Metal filters on its own grid. Such a slot of any such sample
/// records `RuntimeFact::YCbCrTexture`, which puts it in the variant where the binder binds a
/// YCbCr format there, on a profile that takes the variant (`ProfileFields::ycbcr_variant`: under
/// `YCbCrFilterPolicy::Exact`, and on a device that samples through Metal's own sampler also under
/// `SamplingPolicy::Exact`). On any other profile the slot records nothing and the device filters
/// such a texture as any other (`YCbCrFilterPolicy::Device`), which the module's
/// `PrecisionNote::DeviceSampling` states, or, through Metal's own sampler, its filter note under
/// the bound format (`lower::sampler::linear::metal_filtered_ycbcr`).
pub(crate) fn ycbcr_texture(
cx: &mut SelectCx<'_>,
image: ImageRef,
shape: ImageShape,
) -> Result<bool, Error> {
let ImageRef::Slot(index) = image else {
return Ok(false);
};
if shape.dim == ImageDim::Buffer
|| shape.depth
|| shape.ms
|| !cx.profile.fields().ycbcr_variant
{
return Ok(false);
}
let s = slot_of(cx, index)?;
if s.storage() {
return Ok(false);
}
let slot = s.slot;
cx.facts
.insert(crate::pipeline::facts::RuntimeFact::YCbCrTexture { slot });
Ok(cx.inputs.ycbcr_textures.contains(&slot))
}
/// The address-mode map constexpr sampler `words` samples texture slot `index` under: the map
/// of the texture the slot's variant binds there (`LoweringInputs::address_maps`), `None` for
/// the identity. The slot records `RuntimeFact::ConstexprSampled` with the sampler's modes,
@@ -1904,16 +1786,6 @@ pub(crate) fn constexpr_address_map(
Ok(cx.inputs.address_maps.get(&slot).copied())
}
/// Whether `image` is a slot under its YCbCr variant ([`ycbcr_texture`]), on a profile that takes
/// the variant.
pub(crate) fn ycbcr_slot(cx: &SelectCx<'_>, image: ImageRef) -> Result<bool, Error> {
match image {
ImageRef::Slot(_) if !cx.profile.fields().ycbcr_variant => Ok(false),
ImageRef::Slot(index) => Ok(cx.inputs.ycbcr_textures.contains(&slot_of(cx, index)?.slot)),
ImageRef::Heap { .. } => Ok(false),
}
}
/// How an access of a texture an 8-bit sRGB format may be bound to reads its texels under the
/// slot's variant ([`srgb_texels`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -1922,28 +1794,21 @@ pub(crate) enum SrgbReach {
Device,
/// From the raw codes alone, decoded or summed exactly as Metal does.
Raw,
/// From the raw codes where a runtime sampler's word states a sampler its emulation reaches,
/// through the device's decode elsewhere (a runtime sampler's linear emulation): the caller
/// notes the device's decode where the word does not reach it.
Word,
}
/// A read, sample, or gather of `image` (shape `shape`) with a `half` or `float` result, which
/// an 8-bit sRGB format bound to it would decode (`metal::texel_format`). `reach` says where the
/// module can answer as Metal does from the raw codes: a read, a nearest sample, a pixel-coordinate
/// fetch, and a gather with a `half` result decode the code through Metal's twelve-bit table, and a
/// bicubic sample and an emulated linear sample sum the table steps exactly (the exact routines'
/// `BicubicTexels::SRGB` grids), a runtime sampler's where its word reaches the emulation
/// ([`SrgbReach::Word`]); the caller decides. On a sampled color texture slot (not a texture
/// bicubic sample sums the table steps exactly (the exact routines' `BicubicTexels::SRGB` grids);
/// the caller decides. On a sampled color texture slot (not a texture
/// buffer, a depth texture, or a storage slot) the module records `RuntimeFact::SrgbTexture`, and
/// where the slot is one of `LoweringInputs::srgb_textures` (its variant: bound in such a format)
/// an access the raw codes serve reads them, returning `true` and declaring Metal's table
/// (`arith::srgb`, shared with `air.unpack`'s `unorm4x8_srgb`, whose census name it is charged to),
/// and any other access keeps the device's decode, recording `PrecisionNote::SrgbTexelDecode` and
/// `RuntimeFact::SrgbDeviceDecode` (a device that cannot sample the bound format has no view to
/// decode it through, so the planner refuses the texture there). An access served by the raw codes
/// where a word reaches it records the fact too, for its device arm, and leaves the note to the
/// caller. A heap element's format is not known, so a heap element's access records the note. On a
/// decode it through, so the planner refuses the texture there). A heap element's format is not known, so a heap element's access records the note. On a
/// device that decodes through Metal's own texture unit (`VkProperty::MetalSampler`: MoltenVK on
/// Apple's GPU) the device's decode is Metal's, so the module requires the property there instead
/// of the note.
@@ -1970,30 +1835,28 @@ pub(crate) fn srgb_texels(
if !cx.inputs.srgb_textures.contains(&slot) {
return Ok(false);
}
// A form the raw codes do not serve everywhere decodes through the device's view, which a
// device that cannot sample the bound format does not have: under the slot's twin variant it
// decodes the device's filtered codes instead, through Metal's table.
if reach != SrgbReach::Raw {
// A form the raw codes do not serve decodes through the device's view, which a device that
// cannot sample the bound format does not have: under the slot's twin variant it decodes the
// device's filtered codes instead, through Metal's table.
let device = reach == SrgbReach::Device;
if device {
cx.facts
.insert(crate::pipeline::facts::RuntimeFact::SrgbDeviceDecode { slot });
}
let twin = reach != SrgbReach::Raw && cx.inputs.srgb_twins.contains(&slot);
if reach == SrgbReach::Device && !twin {
device_decode(cx);
return Ok(false);
}
if reach == SrgbReach::Device {
if !cx.inputs.srgb_twins.contains(&slot) {
device_decode(cx);
return Ok(false);
}
cx.precision.insert(PrecisionNote::SrgbTexelDecode);
}
cx.families
.arith
.srgb
.get_or_insert(crate::air::intrinsics::PackDir::Unpack);
Ok(reach != SrgbReach::Device)
Ok(!device)
}
/// Whether an access of `image` that keeps the device's decode of an 8-bit sRGB texture
/// ([`srgb_texels`] with a reach other than [`SrgbReach::Raw`]) samples the bound format's UNORM
/// ([`srgb_texels`] with [`SrgbReach::Device`]) samples the bound format's UNORM
/// twin instead (`LoweringInputs::srgb_twins`: a format the device cannot sample), whose view reads
/// the codes, so the access decodes the device's filtered codes through Metal's table
/// (`texture::srgb_filtered_texel`), Metal's value exactly where the filter reads one texel.
@@ -2290,36 +2153,31 @@ fn heap_group(cx: &mut SelectCx<'_>, tex: Value, m: &mut Meter) -> Result<u32, E
/// heap operation masks its handle to its element (an `OpBitwiseAnd`), and a read that selects the
/// out-of-bounds alpha also tests that flag (an `OpBitwiseAnd` and an `OpINotEqual`), with their
/// constants once; the census's for the strategy that asks for them, `texture.read_clamped.heap`
/// where the alpha is carried, else
/// [`DEPTH_CLASS_CENSUS`](crate::lower::sampler::compared::DEPTH_CLASS_CENSUS) where the depth
/// class is, else [`HEAP_CLASS_CENSUS`]; with the module's table of heap texel classes
/// where the alpha is carried, else [`HEAP_CLASS_CENSUS`]; with the module's table of heap texel classes
/// ([`heap_classes_words`]) under [`HEAP_CLASS_CENSUS`] where a sample reads it. And the words of
/// the `half` conversion routine (`half`), the census's for [`half::CENSUS_NAME`], where a slot
/// takes it, and the `float` one's (`float_texel`).
/// takes it.
pub fn routine_words(
texture: &TexturePlan,
access: &crate::lower::access::AccessPlan,
) -> impl Iterator<Item = (&'static str, u64)> {
let flags = (access.heap_alpha || access.heap_depth || access.carries_class()).then(|| {
let flags = (access.heap_alpha || access.carries_class()).then(|| {
let words = 16 + 16 * u64::from(texture.heap_uses);
let name = match (access.heap_alpha, access.heap_depth) {
(true, _) => "texture.read_clamped.heap",
(false, true) => crate::lower::sampler::compared::DEPTH_CLASS_CENSUS,
(false, false) => HEAP_CLASS_CENSUS,
let name = match access.heap_alpha {
true => "texture.read_clamped.heap",
false => HEAP_CLASS_CENSUS,
};
(name, words)
});
let classes = access
.heap_class
.then(|| (HEAP_CLASS_CENSUS, heap_classes_words()));
// The `half` conversion routine, once per module that defines it, and the `float` one.
// The `half` conversion routine, once per module that defines it.
let half = texture
.slots
.values()
.any(|s| s.half_format)
.then_some((half::CENSUS_NAME, half::ROUTINE_WORDS));
let float = (texture.heap_float || texture.slots.values().any(|s| s.float_format))
.then_some((float_texel::CENSUS_NAME, float_texel::ROUTINE_WORDS));
// The heap's raw decode, once per result type.
let raw = (!texture.heap_raw.is_empty()).then(|| {
(
@@ -2327,12 +2185,7 @@ pub fn routine_words(
heap_raw::ROUTINE_WORDS * texture.heap_raw.len() as u64,
)
});
flags
.into_iter()
.chain(classes)
.chain(half)
.chain(float)
.chain(raw)
flags.into_iter().chain(classes).chain(half).chain(raw)
}
/// The census name of the words a heap texel class costs: the module's table of classes and, where
@@ -3297,15 +3150,14 @@ fn select_read_as(
image,
shape,
(OneTexel::Always, None),
device_texels(cx, false),
device_texels(cx),
m,
)?;
half_texel_nans(cx, image, shape, m)?;
}
let float_texel = texel.conv == TexelConv::F32
&& !exact
&& extended.is_none()
&& float_texels(cx, image, shape, OneTexel::Always, device_texels(cx, false))?;
if texel.conv == TexelConv::F32 && !exact && extended.is_none() {
float_texel_notes(cx, image, shape, OneTexel::Always);
}
// A float read of a sampled heap group of one sample decodes a member of a form a heap reads
// where its handle names one, from the group's unsigned integer class.
let heap_raw = match image {
@@ -3380,7 +3232,6 @@ fn select_read_as(
extended,
heap_raw,
heap_alpha_red,
float_texel,
constant_lanes,
declared,
heap_class: as_class,
@@ -225,10 +225,6 @@ pub struct SlotPlan {
/// (`TexelFormat::unmeasured_on_metal_sampler`): the slot declares its `UnmeasuredTexels`
/// specialization, which the note's clause tests.
pub unmeasured: bool,
/// A read, gather, or sample reading one texel of the slot with a `float` result converts its
/// texel by the bound format's class (`float_texel`): the slot declares its `TexelFormat`
/// specialization and the module the `float` routine.
pub float_format: bool,
/// A read of the slot, or an emulated linear sample of its cube's faces, takes an 8-bit sRGB
/// texel's raw code from the slot's raw view (`ResourceKind::RawTexture`), the slot being one
/// of `LoweringInputs::srgb_textures` (`RuntimeFact::SrgbTexture`).
@@ -275,7 +271,6 @@ impl SlotPlan {
texel_format: false,
half_filtered: false,
unmeasured: false,
float_format: false,
raw: false,
swizzle: false,
constant_lanes: false,
@@ -288,7 +283,7 @@ impl SlotPlan {
/// Whether the slot declares its `TexelFormat` specialization: a conversion by the bound
/// format's class takes it.
pub fn declares_texel_format(&self) -> bool {
self.half_format || self.texel_format || self.float_format
self.half_format || self.texel_format
}
/// Whether the slot is a storage image or storage texel buffer.
+23 -91
View File
@@ -48,13 +48,6 @@
//! read selects its out-of-bounds alpha by. An element is below [`TABLE_CAPACITY`], so the bit is
//! never an element's.
//!
//! **The depth class**. A texture entry's flags carry [`FLAG_DEPTH_CODES`] when the resident
//! texture's pixel format is `Depth16Unorm`, and [`FLAG_DEPTH_VALUES`] when it is `Depth32Float` or
//! `Depth32Float_Stencil8`: how Metal compares its texels against a reference. A module whose heap
//! depth comparison the shader makes carries them in the handle's bits 29 and 30
//! ([`HANDLE_DEPTH_CODES`], [`HANDLE_DEPTH_VALUES`]), beside the alpha where it reads that too, and
//! compares in the shader where one is set. Every other module's handle is the element alone.
//!
//! **Heap samplers** (the sampler half). A sampler handle loaded from an argument buffer is the
//! guest's resource id of an `MTLSamplerState`, searched in the stage's **sampler table**
//! (`Synthetic(SamplerTable)`), the handle table's layout over the argument buffers' samplers: a
@@ -389,27 +382,18 @@ pub const ENTRY_ID_HI: u32 = 1;
pub const ENTRY_ELEMENT: u32 = 2;
/// Word of an entry holding the flags: for a sampler, its
/// [`SamplerWord`](crate::metal::sampler::SamplerWord); for a texture,
/// [`FLAG_OUT_OF_BOUNDS_ALPHA_ONE`], [`FLAG_DEPTH_CODES`] or [`FLAG_DEPTH_VALUES`], and the index
/// of its texel class in [`FLAG_TEXEL_CLASS`], every other bit 0.
/// [`FLAG_OUT_OF_BOUNDS_ALPHA_ONE`], and the index of its texel class in [`FLAG_TEXEL_CLASS`], every other bit 0.
pub const ENTRY_FLAGS: u32 = 3;
/// The flag of a texture entry whose pixel format has no alpha
/// (`metal::format::out_of_bounds_alpha_one`): Metal's out-of-bounds read of such a texture
/// bound to a slot returns alpha 1 (MSL 4.1 section 2.9.1), which a read through the table takes
/// too; no heap texture was measured.
pub const FLAG_OUT_OF_BOUNDS_ALPHA_ONE: u32 = 1 << 1;
/// The flag of a texture entry whose pixel format a depth comparison compares as codes,
/// `Depth16Unorm`: Metal compares the texel's code against the code of the reference clamped
/// into `[0, 1]`, which the shader compares where the module reads the flag.
pub const FLAG_DEPTH_CODES: u32 = 1 << 2;
/// The flag of a texture entry whose pixel format a depth comparison compares as values,
/// `Depth32Float` and `Depth32Float_Stencil8`: Metal compares the texel and the reference as
/// given, which the shader compares where the module reads the flag. A depth format with neither
/// flag (`Depth24Unorm_Stencil8`) is compared by the device.
pub const FLAG_DEPTH_VALUES: u32 = 1 << 3;
/// The field of a texture entry's flags holding the index of its texel class in
/// `metal::texel_format::heap_classes`: the class a slot bound to the texture would state in its
/// `TexelFormat` specialization, `OTHER` (index 0) for a swizzled texture, by which a function
/// emulates Metal's linear filter of the texture's texels where the module reads it. A heap handle
/// converts or reads the texture's texels where the module reads it (a `half` conversion on Metal's
/// own sampler, a fetched gather, a NaN texel's rule, a raw-held form's emulation). A heap handle
/// carries it in place, in a module whose search carries it ([`Lookup::Flagged`]'s `class`), so
/// [`HANDLE_TEXEL_CLASS`] is this field.
pub const FLAG_TEXEL_CLASS: u32 = 0x1fff << 16;
@@ -419,23 +403,11 @@ pub const HANDLE_TEXEL_CLASS: u32 = FLAG_TEXEL_CLASS;
/// The bit of a heap handle that carries its entry's [`FLAG_OUT_OF_BOUNDS_ALPHA_ONE`], in a
/// module whose search carries it ([`Lookup::Flagged`]'s `alpha`).
pub const HANDLE_ALPHA_ONE: u32 = 1 << 31;
/// The bit of a heap handle that carries its entry's [`FLAG_DEPTH_CODES`], in a module whose
/// search carries the depth flags ([`Lookup::Flagged`]'s `depth`).
pub const HANDLE_DEPTH_CODES: u32 = FLAG_DEPTH_CODES << DEPTH_SHIFT;
/// The bit of a heap handle that carries its entry's [`FLAG_DEPTH_VALUES`], in a module whose
/// search carries the depth flags ([`Lookup::Flagged`]'s `depth`).
pub const HANDLE_DEPTH_VALUES: u32 = FLAG_DEPTH_VALUES << DEPTH_SHIFT;
/// The left shift that moves a texture entry's depth flags into the handle's bits 29 and 30.
const DEPTH_SHIFT: u32 = 27;
// Every element is below the table's capacity, so no carried bit is an element's, and the
// carried fields do not overlap.
const _: () = assert!(TABLE_CAPACITY <= 1 << HANDLE_TEXEL_CLASS.trailing_zeros());
const _: () = assert!(
HANDLE_TEXEL_CLASS & (HANDLE_DEPTH_CODES | HANDLE_DEPTH_VALUES | HANDLE_ALPHA_ONE) == 0
);
const _: () = assert!(
FLAG_TEXEL_CLASS & (FLAG_OUT_OF_BOUNDS_ALPHA_ONE | FLAG_DEPTH_CODES | FLAG_DEPTH_VALUES) == 0
);
const _: () = assert!(HANDLE_TEXEL_CLASS & HANDLE_ALPHA_ONE == 0);
const _: () = assert!(FLAG_TEXEL_CLASS & FLAG_OUT_OF_BOUNDS_ALPHA_ONE == 0);
/// Unrolled steps of the handle-table search.
pub const SEARCH_STEPS: u32 = 16;
@@ -1327,16 +1299,9 @@ pub enum Lookup {
Element,
/// The entry's element with flags of its entry beside it: where `alpha`, its
/// [`FLAG_OUT_OF_BOUNDS_ALPHA_ONE`] in [`HANDLE_ALPHA_ONE`], the handle of a module whose
/// shader-checked heap read observes the alpha; where `depth`, its [`FLAG_DEPTH_CODES`] and
/// [`FLAG_DEPTH_VALUES`] in [`HANDLE_DEPTH_CODES`] and [`HANDLE_DEPTH_VALUES`], the handle of a
/// module whose heap depth comparison the shader makes; where `class`, its [`FLAG_TEXEL_CLASS`]
/// in [`HANDLE_TEXEL_CLASS`], the handle of a module that emulates Metal's linear filter of a
/// heap texture. Every heap access masks them off ([`Lookup::element_mask`]).
Flagged {
alpha: bool,
depth: bool,
class: bool,
},
/// shader-checked heap read observes the alpha; where `class`, its [`FLAG_TEXEL_CLASS`] in
/// [`HANDLE_TEXEL_CLASS`], the handle of a module that reads a heap texture's texel class. Every heap access masks them off ([`Lookup::element_mask`]).
Flagged { alpha: bool, class: bool },
/// The index of the entry found, 0 (the null entry) for a miss: the handle of an argument
/// buffer's sampler, whose uses read the entry's element and word ([`entry_field`]).
Entry,
@@ -1346,21 +1311,15 @@ impl Lookup {
/// The entry flags this form carries into the handle, each with the left shift that moves it
/// there.
fn carried(self) -> Vec<(u32, u32)> {
let Lookup::Flagged {
alpha,
depth,
class,
} = self
else {
let Lookup::Flagged { alpha, class } = self else {
return Vec::new();
};
let alpha = alpha.then_some((
FLAG_OUT_OF_BOUNDS_ALPHA_ONE,
HANDLE_ALPHA_ONE.trailing_zeros() - FLAG_OUT_OF_BOUNDS_ALPHA_ONE.trailing_zeros(),
));
let depth = depth.then_some((FLAG_DEPTH_CODES | FLAG_DEPTH_VALUES, DEPTH_SHIFT));
let class = class.then_some((FLAG_TEXEL_CLASS, 0));
alpha.into_iter().chain(depth).chain(class).collect()
alpha.into_iter().chain(class).collect()
}
/// The bits of a handle this form yields that are its element, where it carries flags beside
@@ -1798,25 +1757,18 @@ mod tests {
/// several sizes up to [`TABLE_CAPACITY`] entries (the null id, present ids, absent ids between
/// and beyond them) gets [`lookup_host`]'s element, through an entry array (`u64` ids) and a
/// word view. [`Lookup::Flagged`] also carries a found entry's [`FLAG_OUT_OF_BOUNDS_ALPHA_ONE`]
/// in [`HANDLE_ALPHA_ONE`] where it carries the alpha, and its [`FLAG_DEPTH_CODES`] and
/// [`FLAG_DEPTH_VALUES`] in [`HANDLE_DEPTH_CODES`] and [`HANDLE_DEPTH_VALUES`] where it carries
/// the depth class, carrying no other bit of the entry, and [`Lookup::Entry`] yields the index
/// in [`HANDLE_ALPHA_ONE`] where it carries the alpha, and its texel class where it carries
/// that, carrying no other bit of the entry, and [`Lookup::Entry`] yields the index
/// of the last entry of the key's id, 0 for a miss.
#[test]
fn the_emitted_search_matches_the_host_model() {
for int64 in [true, false] {
let flagged = |alpha, depth, class| Lookup::Flagged {
alpha,
depth,
class,
};
let flagged = |alpha, class| Lookup::Flagged { alpha, class };
for form in [
Lookup::Element,
flagged(true, false, false),
flagged(false, true, false),
flagged(true, true, false),
flagged(false, false, true),
flagged(true, true, true),
flagged(true, false),
flagged(false, true),
flagged(true, true),
Lookup::Entry,
] {
emitted_search_matches_the_host_model(int64, form);
@@ -1827,30 +1779,16 @@ mod tests {
/// Each flagged form's element mask clears exactly the bits it carries.
#[test]
fn a_flagged_handle_masks_off_the_bits_it_carries() {
let flagged = |alpha, depth, class| {
Lookup::Flagged {
alpha,
depth,
class,
}
.element_mask()
};
let flagged = |alpha, class| Lookup::Flagged { alpha, class }.element_mask();
assert_eq!(Lookup::Element.element_mask(), None);
assert_eq!(Lookup::Entry.element_mask(), None);
assert_eq!(flagged(false, false, false), None);
assert_eq!(flagged(true, false, false), Some(!HANDLE_ALPHA_ONE));
let depth = HANDLE_DEPTH_CODES | HANDLE_DEPTH_VALUES;
assert_eq!(depth, 0b11 << 29);
assert_eq!(flagged(false, true, false), Some(!depth));
assert_eq!(
flagged(true, true, false),
Some(!(HANDLE_ALPHA_ONE | depth))
);
assert_eq!(flagged(false, false), None);
assert_eq!(flagged(true, false), Some(!HANDLE_ALPHA_ONE));
assert_eq!(HANDLE_TEXEL_CLASS, 0x1fff << 16);
assert_eq!(flagged(false, false, true), Some(!HANDLE_TEXEL_CLASS));
assert_eq!(flagged(false, true), Some(!HANDLE_TEXEL_CLASS));
assert_eq!(
flagged(true, true, true),
Some(!(HANDLE_ALPHA_ONE | depth | HANDLE_TEXEL_CLASS)),
flagged(true, true),
Some(!(HANDLE_ALPHA_ONE | HANDLE_TEXEL_CLASS)),
"every carried field is masked off, and the element's 16 bits stay"
);
}
@@ -1930,14 +1868,8 @@ mod tests {
};
let want = match form {
Lookup::Element => e,
Lookup::Flagged {
alpha,
depth,
class,
} => {
Lookup::Flagged { alpha, class } => {
e | carried(alpha, FLAG_OUT_OF_BOUNDS_ALPHA_ONE, HANDLE_ALPHA_ONE)
| carried(depth, FLAG_DEPTH_CODES, HANDLE_DEPTH_CODES)
| carried(depth, FLAG_DEPTH_VALUES, HANDLE_DEPTH_VALUES)
| match class {
true => flags(e) & FLAG_TEXEL_CLASS,
false => 0,
+8 -4
View File
@@ -388,9 +388,13 @@ mod tests {
#[test]
fn a_word_view_serves_where_the_device_holds_but_cannot_render_the_format() {
use crate::pipeline::testing::{profile, EXACT_SAMPLING};
let nvidia = profile("nvidia-rtx5080-laptop", EXACT_SAMPLING).unwrap();
let lavapipe = profile("lavapipe", EXACT_SAMPLING).unwrap();
use crate::pipeline::testing::profile;
let nvidia = profile(
"nvidia-rtx5080-laptop",
crate::device::DevicePolicy::default(),
)
.unwrap();
let lavapipe = profile("lavapipe", crate::device::DevicePolicy::default()).unwrap();
for pf in [
PixelFormat::A1BGR5Unorm,
PixelFormat::ABGR4Unorm,
@@ -416,7 +420,7 @@ mod tests {
WordAttachment::of(PixelFormat::RGB9E5Float, &nvidia),
Some(WordAttachment::Rgb9e5)
);
let radv = profile("amd-rdna3-radv", EXACT_SAMPLING).unwrap();
let radv = profile("amd-rdna3-radv", crate::device::DevicePolicy::default()).unwrap();
assert_eq!(WordAttachment::of(PixelFormat::RGB9E5Float, &radv), None);
// Vulkan makes `R5G6B5` and `A1R5G5B5` attachments mandatory.
for pf in [PixelFormat::B5G6R5Unorm, PixelFormat::BGR5A1Unorm] {
+40 -119
View File
@@ -218,7 +218,6 @@ pub(crate) fn query_min_level(desc: &SamplerDescriptor) -> u32 {
/// on that grid handed to it reads Metal's level and weight: a sampler of a texture whose texels
/// are filtered (not an integer one), with a nearest or linear mip filter, one filter for
/// minification and magnification (so the level's sign chooses nothing), and no anisotropy.
/// [`SamplerWord::LEVEL_RULE`] states it to the shader.
pub(crate) fn clamps_on_grid(desc: &SamplerDescriptor, use_: SamplerUse) -> bool {
!use_.integer_texture
&& desc.mip_filter != SamplerMipFilter::NotMipmapped
@@ -336,9 +335,8 @@ pub(crate) fn vk_filtering(
/// every such sampler, with one exception where the min and mag filters differ or the sampler is
/// anisotropic (`clamps_on_grid` false): a bound above 0 whose grid value is 0 stays as given,
/// since Vulkan reads the mag filter at a clamped level of 0 where Metal reads the min filter at a
/// level above 0. Only `clamps_on_grid`'s samplers also take a level the function hands on the grid
/// (`SamplerWord::LEVEL_RULE`); the others' samples keep the device's level, so their bounds on the
/// grid are expected to read closer to Metal's level, unmeasured. An integer texture's sampler
/// level above 0. Every sample keeps the device's level, so the bounds on the grid are expected to
/// read closer to Metal's level, unmeasured. An integer texture's sampler
/// keeps the descriptor's clamp, its lower bound at least 0.
///
/// Refusals are [`check_sampler`]'s, for the descriptor's shape and the use.
@@ -461,13 +459,9 @@ pub fn vk_sampler(
/// (`anisotropyEnable`, its `max_anisotropy` set).
///
/// Anisotropy is a quality bound in both APIs; Vulkan requires it within the limit. It is a
/// filter, so an integer texture has none. Off Metal's own sampler a sampler with a nearest min or
/// mag filter is handed none: Vulkan leaves the anisotropic scheme to the implementation, and
/// ANV's turns a nearest filter into its anisotropic one, which filters linearly even at an
/// explicit level, where Metal's anisotropic filter takes nearest taps (18 codes
/// off on average); the emulation's taps, which are Metal's anisotropy there, read each level
/// through the sampler's own nearest filter. A device that samples natively filters it too: no
/// emulation's taps read it there. A use with explicit cube gradients in the isotropic form
/// filter, so an integer texture has none. A sampler with a nearest min or mag filter is handed
/// its degree too: Vulkan leaves the anisotropic scheme to the implementation (ANV's filters a
/// nearest one linearly). A use with explicit cube gradients in the isotropic form
/// ([`SamplerUse::cube_gradient`]) is handed none, and so is every sampler on a device without
/// `samplerAnisotropy`, where the emulation's taps read the isotropic sampler
/// (`VUID-VkSamplerCreateInfo-anisotropyEnable-01070`: "If the samplerAnisotropy feature is not
@@ -477,11 +471,8 @@ pub(crate) fn device_anisotropy(
use_: SamplerUse,
profile: &DeviceProfile,
) -> bool {
let nearest = desc.min_filter == SamplerMinMagFilter::Nearest
|| desc.mag_filter == SamplerMinMagFilter::Nearest;
desc.max_anisotropy > 1
&& profile.fields().images.sampler_anisotropy
&& (profile.device_samples() || !nearest)
&& !use_.cube_gradient
&& !use_.integer_texture
}
@@ -1020,37 +1011,6 @@ impl SamplerWord {
| Self::ADDRESS[1]
| Self::ADDRESS[2]
| Self::BORDER;
/// The bits of a sampler whose nearest sample reads one texel of the base level at Metal's
/// position: the word masked by them is 0 exactly for a sampler with normalized coordinates,
/// nearest min and mag filters, no mip filter, and no anisotropy (whose `VkSampler` reads the
/// base level whatever its LOD clamps, `vk_sampler`).
pub const NEAREST_BASE: u32 = Self::PIXEL_COORDINATES
| Self::MIN_LINEAR
| Self::MAG_LINEAR
| Self::MIP_FILTER
| Self::ANISOTROPIC;
/// The fields a snapped nearest sample reads of a runtime sampler: whether it reads the base
/// level ([`NEAREST_BASE`](Self::NEAREST_BASE)) and its address modes.
pub const NEAREST_SNAP: u32 =
Self::NEAREST_BASE | Self::ADDRESS[0] | Self::ADDRESS[1] | Self::ADDRESS[2];
/// The bits of a sampler whose nearest sample at a level the shader knows reads one texel of
/// one level: the word masked by them is 0 exactly for a sampler with normalized coordinates,
/// nearest min and mag filters, no anisotropy, and no mip filter or a nearest one
/// (`MTLSamplerMipFilter`'s values 0 and 1).
pub const NEAREST_LEVEL: u32 = Self::NEAREST_BASE & !(1 << Self::MIP_FILTER_SHIFT);
/// The fields a snapped nearest sample at a level the shader knows reads of a runtime sampler:
/// [`NEAREST_SNAP`](Self::NEAREST_SNAP)'s, and the levels its clamp leaves.
pub const LEVELED_SNAP: u32 = Self::NEAREST_SNAP | Self::LEVEL_MIN | Self::LEVEL_MAX;
/// The fields a sample's level reads of a runtime sampler: whether the sampler takes its level
/// clamp on Metal's grid (normalized coordinates, one filter for minification and
/// magnification, no anisotropy, and a mip filter: [`vk_sampler`] then holds the clamp on that
/// grid for a texture whose texels it filters), and its mip filter.
pub const LEVEL_RULE: u32 = Self::PIXEL_COORDINATES
| Self::MIN_LINEAR
| Self::MAG_LINEAR
| Self::MIP_FILTER
| Self::ANISOTROPIC;
/// The word of `desc`.
pub fn of(desc: &SamplerDescriptor) -> SamplerWord {
let mut w = 0;
@@ -1474,48 +1434,45 @@ mod tests {
}
}
/// Off Metal's own sampler a sampler with a nearest min or mag filter is handed no anisotropy
/// where the module emulates Metal's sampler (ANV's anisotropic scheme filters a nearest one
/// linearly); through Metal's sampler, natively, and with linear filters, the degree is handed
/// as before.
/// A sampler with a nearest min or mag filter is handed its degree, through Metal's sampler and
/// natively alike, as one with linear filters is.
#[test]
fn a_nearest_filter_is_handed_no_anisotropy_off_metals_sampler() {
use crate::device::SamplingPolicy::{Exact, NativeDevice};
fn a_nearest_filter_is_handed_its_anisotropy() {
use SamplerMinMagFilter::{Linear, Nearest};
let with = |metal_sampler: bool, sampling| {
let with = |metal_sampler: bool| {
let (_, mut desc) = committed_descriptions()
.into_iter()
.find(|(s, _)| s == "vk12-floor")
.unwrap();
desc.features.insert(VkFeature::SamplerAnisotropy);
desc.limits.max_sampler_anisotropy_bits = 16f32.to_bits();
let policy = DevicePolicy {
sampling,
..DevicePolicy::default()
};
Device::with_deviation(desc, policy, DriverDeviation::MetalSampler, metal_sampler)
.unwrap()
Device::with_deviation(
desc,
DevicePolicy::default(),
DriverDeviation::MetalSampler,
metal_sampler,
)
.unwrap()
};
for (metal_sampler, sampling, min, mag, handed) in [
(false, Exact, Linear, Linear, Some(8.0)),
(false, Exact, Nearest, Nearest, None),
(false, Exact, Nearest, Linear, None),
(false, Exact, Linear, Nearest, None),
(false, NativeDevice, Nearest, Nearest, Some(8.0)),
(false, NativeDevice, Linear, Nearest, Some(8.0)),
(true, Exact, Nearest, Nearest, Some(8.0)),
(true, Exact, Linear, Nearest, Some(8.0)),
] {
let dev = with(metal_sampler, sampling);
let mut d = metal_default();
d.min_filter = min;
d.mag_filter = mag;
d.max_anisotropy = 5;
let s = vk_sampler(&d, SamplerUse::default(), dev.profile()).unwrap();
assert_eq!(
s.max_anisotropy, handed,
"{min:?} {mag:?}, Metal's sampler {metal_sampler}"
);
for metal_sampler in [false, true] {
let dev = with(metal_sampler);
for (min, mag) in [
(Linear, Linear),
(Nearest, Nearest),
(Nearest, Linear),
(Linear, Nearest),
] {
let mut d = metal_default();
d.min_filter = min;
d.mag_filter = mag;
d.max_anisotropy = 5;
let s = vk_sampler(&d, SamplerUse::default(), dev.profile()).unwrap();
assert_eq!(
s.max_anisotropy,
Some(8.0),
"{min:?} {mag:?}, Metal's sampler {metal_sampler}"
);
}
}
}
@@ -2255,13 +2212,11 @@ mod tests {
);
}
/// A word masked by `NEAREST_BASE` is 0 exactly for a normalized, nearest, unmipmapped,
/// isotropic sampler, whatever its address modes, border, comparison, reduction, and LOD
/// clamps; `NEAREST_SNAP` adds the address modes. A sampler's word holds the levels a nearest
/// mip filter reads at its clamp (the default clamp's are the word 0's), and a sampler taking
/// one filter both ways, isotropic, of a filtered texture, takes its clamp on Metal's grid: a
/// nearest mip filter's those levels, a linear one's the bounds truncated onto sixty-fourths.
/// Every other sampler keeps its clamp as given.
/// A sampler's word holds the levels a nearest mip filter reads at its clamp (the default
/// clamp's are the word 0's), and a sampler taking one filter both ways, isotropic, of a
/// filtered texture, takes its clamp on Metal's grid: a nearest mip filter's those levels, a
/// linear one's the bounds truncated onto sixty-fourths. Every other sampler keeps its clamp as
/// given.
#[test]
fn a_samplers_clamp_is_metals_on_its_level_grid() {
let levels = SamplerWord::LEVEL_MIN | SamplerWord::LEVEL_MAX;
@@ -2375,40 +2330,6 @@ mod tests {
}
}
#[test]
fn a_sampler_word_answers_whether_a_nearest_sample_reads_the_base_level() {
use SamplerMinMagFilter as F;
let base = |d: &SamplerDescriptor| SamplerWord::of(d).0 & SamplerWord::NEAREST_BASE == 0;
let mut d = metal_default();
assert!(base(&d));
d.s_address_mode = SamplerAddressMode::Repeat;
d.t_address_mode = SamplerAddressMode::MirrorRepeat;
d.border_color = SamplerBorderColor::OpaqueWhite;
d.compare_function = CompareFunction::Less;
d.reduction_mode = SamplerReductionMode::Minimum;
d.lod_min_clamp = 2.0;
d.lod_max_clamp = 3.0;
assert!(base(&d));
let mode = |d: &SamplerDescriptor, axis: usize| {
(SamplerWord::of(d).0 & SamplerWord::NEAREST_SNAP) >> SamplerWord::ADDRESS_SHIFT[axis]
& 0b111
};
assert_eq!(mode(&d, 0), SamplerAddressMode::Repeat.as_raw());
assert_eq!(mode(&d, 1), SamplerAddressMode::MirrorRepeat.as_raw());
let not_base: [&dyn Fn(&mut SamplerDescriptor); 5] = [
&|d| d.normalized_coordinates = false,
&|d| d.min_filter = F::Linear,
&|d| d.mag_filter = F::Linear,
&|d| d.mip_filter = SamplerMipFilter::Nearest,
&|d| d.max_anisotropy = 2,
];
for (k, edit) in not_base.iter().enumerate() {
let mut d = metal_default();
edit(&mut d);
assert!(!base(&d), "edit {k}");
}
}
#[test]
fn a_sampler_word_answers_the_pixel_predicates() {
use SamplerMinMagFilter as F;
+12 -48
View File
@@ -113,8 +113,7 @@
//! UNORM view of the same image ([`srgb_raw_view`]): the `RuntimeFact::SrgbTexture` variant of a
//! function. Its [`texel_format`] is [`UNORM`](BicubicTexels::UNORM) and
//! [`SRGB`](BicubicTexels::SRGB) with its channels, never [`EXACT`](BicubicTexels::EXACT): a
//! conversion of the device's value keeps its rounding, and the emulated linear filter reads the
//! raw codes under the variant alone, adding `EXACT` there. A gather's `float` value is not
//! conversion of the device's value keeps its rounding. A gather's `float` value is not
//! measured, so it keeps the device's decode (`PrecisionNote::SrgbTexelDecode`). `RGBA8Unorm_sRGB`
//! was read, and so were `BGRA8Unorm_sRGB`, `R8Unorm_sRGB`, and `RG8Unorm_sRGB` (the probe): they
//! take its rule ([`srgb_raw`]). So do the sRGB forms of BC1 to BC3 and BC7 (an Apple M4: every
@@ -303,18 +302,6 @@ pub enum CubeCorner {
}
impl CubeCorner {
/// Every corner, in field order.
pub const ALL: [CubeCorner; 8] = [
CubeCorner::XFace,
CubeCorner::Grid255,
CubeCorner::Grid1023,
CubeCorner::Grid565,
CubeCorner::Grid2047,
CubeCorner::Signed1023,
CubeCorner::Grid16320,
CubeCorner::Signed8128,
];
/// The corner of `pf`'s cube gather, where it is measured outside the families (the
/// probes, Apple M4 on macOS 27.0.1). ASTC's HDR formats were read
/// through `ASTC_4x4_HDR`'s void-extent blocks; the other block sizes and blocks take its
@@ -361,21 +348,6 @@ impl CubeCorner {
})
}
/// The made-up texel's grid `D` per channel (red to alpha), or `None` for the `x` face's
/// texel. A signed grid's codes read from `-D`.
pub fn grids(self) -> Option<[u32; 4]> {
Some(match self {
CubeCorner::XFace => return None,
CubeCorner::Grid255 => [255; 4],
CubeCorner::Grid1023 => [1023, 1023, 1023, 255],
CubeCorner::Grid565 => [1023, 4095, 1023, 255],
CubeCorner::Grid2047 => [2047; 4],
CubeCorner::Signed1023 => [1023; 4],
CubeCorner::Grid16320 => [16320; 4],
CubeCorner::Signed8128 => [8128; 4],
})
}
/// The class of a format of this corner: the field alone.
pub fn class(self) -> TexelFormat {
TexelFormat((self as u32) << TexelFormat::CORNER)
@@ -580,17 +552,6 @@ impl PackedTexels {
)
}
/// Whether every texture of the field's formats has one level: the two-plane YCbCr fields'
/// ([`ycbcr`](Self::ycbcr)), whose formats Metal makes a texture of only over an IOSurface
/// plane, which takes one level, as do its views. Metal's linear sample of such a texture
/// through a mip filter is its sample through none, bit for bit, whatever the level, bias or
/// gradient (an Apple M4 on macOS 27.0.1 and an Apple M3 Max on macOS
/// 26.7): the emulation of a runtime sampler's linear sample reaches its mip filter on such a
/// class (`lower::sampler::linear`).
pub fn one_level(self) -> bool {
self.ycbcr()
}
/// Whether the filter's codes and steps are signed and reach `±2D`
/// ([`YCbCrExtended8192`](Self::YCbCrExtended8192)): each step divided by `2D` and doubled,
/// exactly.
@@ -1197,19 +1158,22 @@ mod tests {
assert!(!alone.has_channels(), "{pf:?}");
seen.insert(corner as u32);
}
for (k, corner) in CubeCorner::ALL.into_iter().enumerate() {
let every = [
CubeCorner::XFace,
CubeCorner::Grid255,
CubeCorner::Grid1023,
CubeCorner::Grid565,
CubeCorner::Grid2047,
CubeCorner::Signed1023,
CubeCorner::Grid16320,
CubeCorner::Signed8128,
];
for (k, corner) in every.into_iter().enumerate() {
assert_eq!(corner as u32, k as u32 + 1);
assert_eq!(corner.class().0 >> TexelFormat::CORNER, corner as u32);
assert!(corner.class().0 & TexelFormat::CORNER_MASK == corner.class().0);
for d in corner.grids().into_iter().flatten() {
assert!((1..1 << 16).contains(&d), "{corner:?}");
}
assert!(seen.contains(&(corner as u32)), "{corner:?} has no format");
}
// The emission takes every field after `XFace` for a corner with grids.
for corner in CubeCorner::ALL {
assert_eq!(corner.grids().is_none(), corner == CubeCorner::XFace);
}
// The measured families keep no corner field.
for pf in [
PixelFormat::RGBA8Unorm,
@@ -197,7 +197,6 @@ mod serde_round_trips {
storage_view_slots: BTreeSet::from([buffer(3)]),
srgb_textures: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 4)]),
srgb_twins: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 4)]),
ycbcr_textures: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 6)]),
ycbcr_in_place: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 7)]),
flat_grid: true,
replay_bindings: true,
@@ -330,7 +329,6 @@ mod serde_round_trips {
slot(Stage::Fragment, SlotClass::Texture, 3),
crate::pipeline::SnapshotForm::Half,
)]),
ycbcr_textures: BTreeSet::from([slot(Stage::Fragment, SlotClass::Texture, 8)]),
ycbcr_in_place: BTreeSet::from([slot(Stage::Fragment, SlotClass::Texture, 9)]),
viewport_index_varying: true,
// An emulated post-tessellation vertex function's state.
+72 -273
View File
@@ -901,8 +901,8 @@ pub enum PrecisionNote {
/// texel to `half` by the bound format: measured for the 32-bit float, half-float, and 8- and
/// 16-bit normalized formats, which a texture slot converts exactly by its `TexelFormat`
/// specialization (`metal::texel_format`); a read, nearest sample, or gather of a slot bound in
/// an 8-bit sRGB format decodes the raw code exactly instead, and an emulated linear or a
/// bicubic sample sums the raw codes' steps exactly, under the slot's `SrgbTexture` variant,
/// an 8-bit sRGB format decodes the raw code exactly instead, and a bicubic sample sums the
/// raw codes' steps exactly, under the slot's `SrgbTexture` variant,
/// and records nothing. A texture buffer converts by its bound format the same way (Metal reads
/// a texture buffer's texels as a texture's: the P2a probe). A texture bound in another format
/// (sRGB otherwise, packed, depth, and the rest) and a heap element keep the exact rounding of
@@ -912,11 +912,9 @@ pub enum PrecisionNote {
/// ([`PrecisionNote::HalfSampleFilter`]). Recorded wherever such an access is lowered;
/// validation derives no tolerance from it.
///
/// Native device sampling (a texel conversion): under the default
/// `TexelConversionPolicy::Device`, off Apple's GPUs (`VkProperty::MetalSampler` keeps the
/// conversion), every slot's access with a `half` result takes that rounding too, and records
/// this note; under `TexelConversionPolicy::Exact` a sample or gather that native device
/// sampling (`SamplingPolicy::NativeDevice`) answers does. The recorded bound: the device's
/// Native device sampling (a texel conversion): off Apple's GPUs (`VkProperty::MetalSampler`
/// keeps the conversion), every slot's access with a `half` result takes that rounding too,
/// and records this note. The recorded bound: the device's
/// `float` texel (within [`PrecisionNote::DeviceTexelConversion`]'s bound of Metal's) rounded
/// to nearest even is within one `half` ulp of Metal's `half` result (Metal rounds a 32-bit
/// float sample toward zero, a half-float linear sum with ties away from zero, and a normalized
@@ -924,59 +922,28 @@ pub enum PrecisionNote {
/// saturates to `±65504` and the rounding takes to the infinity of its sign; a NaN is the
/// device's decode ([`PrecisionNote::DeviceNanEncoding`]).
///
/// On a device that samples through Metal's own sampler under
/// [`YCbCrFilterPolicy::Device`](crate::device::YCbCrFilterPolicy), a sample with a `half`
/// result through a runtime sampler slot bound to a two-plane YCbCr texture on the grid `8192`
/// On a device that samples through Metal's own sampler, a sample with a `half` result
/// through a runtime sampler slot bound to a two-plane YCbCr texture on the grid `8192`
/// (the `_sRGB` twins, the unpacked 12-bit and the extended-range formats): where its word
/// reads one texel, the texel's step rounds to nearest even, where Metal rounds it with ties
/// away from zero, one `half` unit in the last place apart at a tie. The runtime announces it
/// at a draw or dispatch that binds such a texture there.
HalfTexelConversion,
/// The module samples a texture with a `half` result through a filter (linear minification
/// or magnification, or a runtime sampler) on a device that does not sample through Metal's
/// own sampler (one that does, `VkProperty::MetalSampler`, filters as Metal does: the module
/// requires it instead). Metal's linear filter (the footprint's 1/256 fraction rounded half up,
/// the taps weighed `(256 - k) / 256` and `k / 256`, each format's sum rounded as
/// `metal::texel_format` states, a 32-bit float or half-float format's through Metal's linear
/// accumulator: each term truncated toward zero onto a grid 38 or 17 bits below the largest
/// term's tap and weight exponents, then summed exactly) is emulated by fetches of the base
/// level (`lower::sampler::linear`) for a constexpr sampler with linear minification and
/// magnification, no mip filter, no anisotropy, and weighted-average reduction, sampling a 1D
/// or 2D texture slot (an array or not), or a 3D one (Metal's 3D weights, rounded to 16 bits,
/// and its truncated normalized terms), with a constant texel offset or none, no
/// `min_lod_clamp`, and no observed residency, under every address mode. It is exact for a
/// bound format whose conversion is measured (`metal::texel_format`; the accumulator on every
/// lane of the P2a and P2c probes; a normalized format's 2D sum truncates each term first, onto
/// `2^-8` of a 16-bit code and `2^-4` of an sRGB step) but where it is known not to be:
/// - a constant offset on a repeating or mirrored axis of a view whose first level lies above
/// its parent texture's base level: Metal drops the offset on such an axis of level size 2
/// to 7 where the parent's base-level size is not a power of two, and the emulation reads
/// the view's own base level, so at a view size of 2 or 4 it adds the offset Metal drops
/// (on every other texture the emulation places it as Metal does);
/// - in 3D, a half-float format's result, half a `half` ulp off on about 0.3% of channels, and
/// a 32-bit float format's on about one lane in 180,000 (a cancellation).
///
/// A slot bound in an 8-bit sRGB format takes the emulation under its `SrgbTexture` variant: it
/// fetches the raw codes and sums their table steps exactly on the grids `1/4095` (color) and
/// `1/(16 · 255)` (alpha), rounded half up, then to `half` to nearest even.
///
/// Every other filtered `half` sample is the device's filter, then Metal's conversion of its
/// value: through a runtime sampler; with a mip filter, anisotropy above 1, min or max
/// reduction, or minification and magnification filters that differ; of a cube texture or an
/// argument-buffer (heap) element; with a `min_lod_clamp` or a dynamic texel offset;
/// with an observed residency; with one axis clamping to zero beside another clamping to a
/// colored border; and of a slot bound in a format whose conversion is not measured
/// (`TexelFormat::OTHER`: the packed and other formats, and an sRGB one outside the
/// emulation's reach, which also records [`PrecisionNote::SrgbTexelDecode`]). There the
/// device's footprint,
/// weights, and sum (Vulkan bounds them only by its precision rules, such as
/// `subTexelPrecisionBits`) may differ from Metal's, and the conversion rounds another value.
/// A sample through a constexpr sampler with nearest minification and magnification, no mip
/// filter or a nearest one, no anisotropy, and weighted-average reduction, and a gather, are
/// not filtered and do not carry it (a linear mip filter, anisotropy, or a min or max
/// reduction filters even with nearest minification and magnification). The `float` result's
/// counterpart is [`PrecisionNote::FloatSampleFilter`]. Validation derives no tolerance from
/// it: the class is unbounded.
/// or magnification, a linear mip filter, anisotropy, or a runtime sampler) that Metal's own
/// sampler (`VkProperty::MetalSampler`, MoltenVK) answers otherwise than Metal filters the
/// format bound there: a two-plane YCbCr texture's (`YCBCR8_420_2P` and its kin), whose view
/// holds Metal's reads exactly but which Metal's sampler filters as an `RGBA16Float` or
/// `RGBA32Float` texture's texels, within one step of the format's grid, where Metal sums the
/// steps on the grid, each term truncated (`lower::sampler::linear`). Recorded under the slot's
/// bound format, which the runtime reads at each draw or dispatch and announces as
/// `ycbcr-filter-not-exact`, through a runtime sampler whatever its word states. A sample
/// through a constexpr sampler that reads one texel of one level (nearest minification and
/// magnification, no mip filter or a nearest one, no anisotropy) and a gather are not filtered
/// and do not carry it. A device that samples natively records
/// [`PrecisionNote::DeviceSampling`] instead. The `float` result's counterpart is
/// [`PrecisionNote::FloatSampleFilter`]. Validation derives no tolerance from it: the class is
/// unbounded.
HalfSampleFilter,
/// The module reads, samples, or gathers a texture with a `half` or `float` result through
/// the device's sRGB decode, or decodes the device's filter of its codes, where the texture may
@@ -989,14 +956,11 @@ pub enum PrecisionNote {
/// with nearest filters, no mip filter or a nearest one, no anisotropy, and weighted-average
/// reduction), pixel-coordinate fetches, and gathers (a `float` one's where the device does not
/// sample through Metal's own sampler) decode the raw code exactly as Metal does, and its
/// bicubic samples, and its linear samples with a `half` result that the emulation reaches
/// ([`PrecisionNote::HalfSampleFilter`]), sum the raw codes' steps exactly as Metal does, as do
/// its linear samples with a `float` result that the emulation reaches
/// ([`PrecisionNote::FloatSampleFilter`]). Recorded where an access keeps the device's decode
/// on a device that does not sample through Metal's own sampler: under that variant, a sample
/// of the slot through a runtime sampler or another filter (a runtime sampler's filter is not
/// known when the function compiles); and any such access of an argument-buffer (heap) element,
/// whose format is never known. On a device that does (`VkProperty::MetalSampler`: MoltenVK on
/// bicubic samples sum the raw codes' steps exactly as Metal does. Recorded where an access
/// keeps the device's decode on a device that does not sample through Metal's own sampler:
/// under that variant, a filtered sample of the slot (a linear filter, a linear mip filter,
/// anisotropy, or a runtime sampler, whose filter is not known when the function compiles);
/// and any such access of an argument-buffer (heap) element, whose format is never known. On a device that does (`VkProperty::MetalSampler`: MoltenVK on
/// Apple's GPU) the device's decode is Metal's, and the module requires the property instead.
/// Where the device cannot sample the bound format, whose texture it holds as the format's
/// UNORM twin (`LoweringInputs::srgb_twins`), such an access samples the twin's codes and
@@ -1005,62 +969,17 @@ pub enum PrecisionNote {
/// the decode of the codes' blend, where Metal blends the decoded texels; recorded on every
/// device under that variant. Validation derives no tolerance from it: the class is unbounded.
SrgbTexelDecode,
/// The module samples a texture with a `float` result through a filter on a device that does
/// not sample through Metal's own sampler (one that does, `VkProperty::MetalSampler`, filters
/// as Metal does: the module requires it instead). A sample is filtered unless it goes through
/// a constexpr sampler with nearest minification and magnification, no mip filter or a nearest
/// one, and no anisotropy (a minimum or maximum reduction reads the weighted average, as
/// Metal's does on Apple's GPU): linear minification or magnification, a linear mip filter,
/// The module samples a texture with a `float` result through a filter that Metal's own
/// sampler (`VkProperty::MetalSampler`, MoltenVK) answers otherwise than Metal filters the
/// format bound there: a two-plane YCbCr texture's, as for [`PrecisionNote::HalfSampleFilter`]
/// (a depth texture's sample and a comparison's included). A sample is filtered unless it goes
/// through a constexpr sampler with nearest minification and magnification, no mip filter or a
/// nearest one, and no anisotropy: linear minification or magnification, a linear mip filter,
/// anisotropy, and a runtime sampler (whose filter is not known when the function compiles) all
/// filter, a depth texture's sample and a comparison's included. Metal's linear filter (the
/// footprint's 1/256 fraction rounded half up, the taps weighed `(256 - k) / 256` and `k /
/// 256`, each format's sum rounded as `metal::texel_format` states: an 8- or 16-bit normalized
/// or 8-bit sRGB format's exactly (a 16-bit format's 2D terms truncated onto `2^-8` of a code
/// and an sRGB format's onto `2^-4` of a step first), rounded half up onto its grid, then `n /
/// D` to `f32`; a 32-bit float format's rounded to `f32` with ties away from zero; a half-float
/// format's to `half` with ties away from zero, widened; both through Metal's linear
/// accumulator) is emulated by fetches where the `half` result's is
/// ([`PrecisionNote::HalfSampleFilter`]), for every measured format, with the same exceptions:
/// a constant offset on a repeating or mirrored axis of a view whose first level lies above its
/// parent's base level, and in 3D a half-float format's half-ulp residue and a rare 32-bit
/// float cancellation. Every other filtered sample is the device's filter, whose footprint,
/// weights, and sum Vulkan bounds only by its precision rules (such as
/// `subTexelPrecisionBits`): a device whose weights or sum differ answers another value, even
/// for a blend at weight 1/2. Validation derives no tolerance from it: the class is unbounded.
/// filter. Recorded under the slot's bound format, announced as `ycbcr-filter-not-exact`. A
/// device that samples natively records [`PrecisionNote::DeviceSampling`] instead. Validation
/// derives no tolerance from it: the class is unbounded.
FloatSampleFilter,
/// The module leaves a gather to the device's footprint on a device that does not sample
/// through Metal's own sampler (one that does, `VkProperty::MetalSampler`, gathers as Metal
/// does: the module requires it instead). Metal's 2D footprint (per axis the position `u * n`
/// rounded once to `f32` with ties away from zero, a repeat or mirrored-repeat coordinate
/// wrapped into its period first, then `q = floor(256 x - 127.5)` and the texels `q >> 8` and
/// the one after it), measured at odd sizes on Apple M3 Max and M4 alike, is read by gathering
/// at the footprint's corner, where every device reads Metal's 2x2 block, for a 2D or 2D-array
/// gather (a comparison's included) through a constexpr sampler with normalized coordinates,
/// and emulated by fetches for a cube gather (a depth cube's comparison included) through such
/// a sampler. A 2D or 2D-array gather through a runtime or argument-buffer sampler snaps behind
/// the sampler's word onto Metal's block by the address mode the word states on each axis,
/// every mode measured, and records nothing. Recorded for every other gather: of a cube texture
/// bound in a format whose corner rule is not measured (the module's gather branches to the
/// device's there; its face at a tie of major axes is handed to the device). Such a
/// gather is the device's, which Vulkan bounds only by `subTexelPrecisionBits`: a lane a few
/// ulps from a texel edge can read the next 2x2 block. Validation derives no tolerance from it:
/// the class is unbounded.
DeviceGatherFootprint,
/// The module hands a nearest cube sample the centre of the texel Metal reads, on a device
/// that does not sample through Metal's own sampler (one that does, `VkProperty::MetalSampler`,
/// is Metal's texture unit itself). Metal's position on a face axis of size `n` is
/// `floor(RN(RN(1 + sc * r) / 2 * n))` (the cube rounding probes, Apple M3 Max and M4 alike),
/// with `r` its texture unit's reciprocal of the major magnitude, which is not correctly
/// rounded: on about 10% of majors (208 of 2,001 measured), those whose reciprocal lies within
/// about 0.2 ulp of a rounding midpoint, it lies one or two ulps from `RN(1 / |ma|)`, and no
/// exact form of it is known. The module computes the position with the correctly rounded
/// reciprocal, so where the position lies within about `n * 2^-23` of a texel edge on such a
/// major, the sample reads the next texel on that axis. A linear cube sample the module
/// emulates by fetches takes the same position, so where it lies within about `n * 2^-23` of a
/// 1/256 quantization step on such a major, the sample's fraction is one step off. Recorded for
/// every nearest cube sample the module hands its texel and every linear cube sample it
/// emulates. Validation derives no tolerance from it: the class is unbounded.
CubeFaceReciprocal,
/// A vertex or fragment function keeps more private memory (its `alloca`s, a call stack among
/// them, or constants held as `Private` variables) than the floor, 16 KiB a thread, on a device
/// whose Function storage was not measured, up to the 192 KiB a thread Metal was measured to
@@ -1088,76 +1007,9 @@ pub enum PrecisionNote {
/// Validation keeps the row open (C3): the moved lanes move whatever later words read the
/// operation's result.
QuadsCountedBeforeDiscard,
/// The module leaves a depth comparison (a sample or gather with comparison) to the device, on
/// a device that does not sample through Metal's own sampler (one that does,
/// `VkProperty::MetalSampler`, compares as Metal does: the module requires it instead). Metal
/// compares a `Depth16Unorm` texel's code with the reference's (the reference clamped into
/// `[0, 1]`, its exact product with 65535 rounded to nearest), and a float format's texel and
/// reference as given, denormals and values outside `[0, 1]` included, `-0` equal to `+0`; a
/// NaN fails every ordered test and passes `not_equal`. The module makes that comparison
/// itself, on texels it fetches exactly for a bound `Depth16Unorm` or `Depth32Float` texture: a
/// linear comparison through a constexpr sampler the emulation reaches, a cube's comparison
/// gather, and a 2D comparison gather or nearest comparison through a constexpr sampler at a
/// level the function knows, and a runtime sampler's comparison gather and nearest comparison
/// without a mip filter. Elsewhere it compares texels the device reads: that read is
/// [`PrecisionNote::DeviceTexelDenormals`]'s (a device's sample or gather may read a denormal
/// as zero), and the comparison is Metal's.
///
/// Recorded where the device compares (a heap texture, an argument buffer's sampler, a filter
/// the emulation does not reach, a runtime sampler's sample whose bound sampler filters
/// otherwise): Vulkan pins only a normalized format's clamp of the reference. Of 9,024
/// `Depth16Unorm` comparisons the device made (`depth_compares`), RADV (Radeon 780M) differed
/// from Metal on 71 (a NaN reference compares as 0), ANV (Iris Xe) on 584 (its rounding of the
/// reference to a code), the RTX 3090 on 474, x86 lavapipe on 1,203 and arm64 lavapipe on 1,191
/// (both compare the clamped reference with the texel as floats); x86 lavapipe's float
/// comparison also flushes a denormal `Depth32Float` value.
///
/// Not this note's: a depth image that answers a denormal as zero (RADV's and ANV's), which
/// the runtime replaces by a colour image wherever the driver is not measured to keep one; the
/// device's read of the texels the module compares ([`PrecisionNote::DeviceTexelDenormals`]);
/// and [`PrecisionNote::RestrictedDepthRange`]'s values outside `[0, 1]`.
///
/// Validation keeps the row open (C3): no exact path replaces the device's comparison there
/// yet.
DeviceDepthComparison,
/// A `float` sample or gather, a comparison's included, whose texels the device reads, on a
/// device that does not sample through Metal's own sampler. Metal's sample and gather hand back
/// a denormal 32-bit float texel (`R32Float`, `RG32Float`, `RGBA32Float`, `Depth32Float`) as it
/// is. A device's sample or gather may read it as the zero of its sign
/// (`runtime_lane::depth_compares`):
/// - RADV (Radeon 780M): gathers and nearest samples;
/// - NVIDIA (RTX 3090): gathers;
/// - ANV (Iris Xe): nearest samples;
/// - lavapipe: x86's float comparison.
///
/// Each device's `OpImageFetch` and `OpImageRead` keep it. The module fetches the texels
/// itself, behind the slot's `TexelFormat` specialization, where Metal's footprint and level
/// are known:
/// - a plain gather, or a nearest sample at a level the function knows, through a constexpr
/// sampler;
/// - a comparison's;
/// - a linear sample the emulation reaches;
/// - a cube gather's.
///
/// Recorded for every other such sample or gather:
/// - an implicit level under a nearest mip filter in a fragment function;
/// - a filtered sample no emulation reaches;
/// - a `min_lod_clamp`, a dynamic offset, or axes clamping to zero and to a colored border;
/// - an observed residency;
/// - a cube's sample;
/// - a heap texture;
/// - a runtime or argument buffer's sampler.
///
/// Not this note's: a `Depth32Float` texture's depth image that a device's comparison reads,
/// which RADV holds a denormal in as zero ([`PrecisionNote::DeviceDepthComparison`]).
///
/// Validation derives no tolerance and no explanation from it, as for `DeviceDenormals`.
DeviceTexelDenormals,
/// The module places a texel offset on an axis that may repeat or mirror as Metal does in an
/// access of an argument buffer's texture: on a device that does not sample through Metal's
/// own sampler (one that does, `VkProperty::MetalSampler`, is Metal's texture unit itself), in
/// a snapped gather or nearest sample, fetched texels, or an emulated linear filter, and on
/// every device in an emulated raw sample (`heap_raw`). Metal drops the offset on a repeating
/// access of an argument buffer's texture: in an emulated raw sample (`heap_raw`) or a bicubic
/// filter's footprint, on every device. Metal drops the offset on a repeating
/// or mirrored axis whose level size lies in `[2, 7]` and whose texture's base-level size is
/// not a power of two, reading the base-level size of the texture a view was made from; a heap
/// element's access can read only the bound view's. So on a view whose first level lies above
@@ -1453,16 +1305,15 @@ pub enum PrecisionNote {
/// mismatch for review, deferred in C3 until an exact path exists.
ExtendedRangeFloatBlendSource,
/// The module samples a texture through an anisotropic sampler with Metal's anisotropic
/// filter emulated by the device's samples at explicit levels, on a device that does not
/// sample through Metal's own sampler (`lower::sampler::anisotropic`): a sample without
/// comparison of a 2D texture or 2D array at the fragment's implicit level or with explicit
/// gradients, or of a cube or cube array with explicit gradients, through a constexpr sampler
/// of `maxAnisotropy` above 1, or through a runtime sampler slot whose word states anisotropy
/// (under that word alone). A cube's sample is emulated on Metal's own sampler too where the
/// stage's cube-gradient route is not measured (`CubeGradientRoute::Unmeasured`), its taps
/// Metal's own samples at explicit levels; and so is an anisotropic sampler's on a device
/// without `samplerAnisotropy` whatever its sampling, every Vulkan sampler being isotropic
/// there, each tap the device's isotropic filter. Metal's footprint (its gradient lengths,
/// filter emulated by the device's samples at explicit levels (`lower::sampler::anisotropic`),
/// on a device without `samplerAnisotropy`, every Vulkan sampler being isotropic there, each
/// tap the device's isotropic filter: a sample without comparison of a 2D texture or 2D array
/// at the fragment's implicit level or with explicit gradients, or of a cube or cube array with
/// explicit gradients, through a constexpr sampler of `maxAnisotropy` above 1, or through a
/// runtime sampler slot whose word states anisotropy (under that word alone). A cube's sample
/// is emulated on Metal's own sampler too where the stage's cube-gradient route is not measured
/// (`CubeGradientRoute::Unmeasured`), its taps Metal's own samples at explicit levels. A device
/// with the feature samples with its own anisotropic filter. Metal's footprint (its gradient lengths,
/// piecewise-linear `log2`, level, tap count, tap weights and direction) is reproduced as
/// measured on an Apple M4 (the M3 Max answering identically), with this residue:
/// - the level is off by `1/256` of a level on about 1% of anisotropic samples;
@@ -1472,7 +1323,8 @@ pub enum PrecisionNote {
/// 1,021 of 1,674 measured windows; up to about 18/256 of a texel at the outer tap of 10 or
/// more taps);
/// - each tap is the device's own filter at the level the shader hands it, so its footprint
/// and sum are the device's (`HalfSampleFilter`, `FloatSampleFilter`);
/// and sum are the device's (Metal's own on MoltenVK; elsewhere
/// [`PrecisionNote::DeviceSampling`]);
/// - a cube's taps step across the direction's face by Metal's face gradients (Metal under
/// macOS 27 samples a cube as the face's 2D plane, measured on the Apple M3 Max), the
/// direction moved and projected onto the face again by the device, and a tap past the
@@ -1491,20 +1343,13 @@ pub enum PrecisionNote {
AnisotropicFilter,
/// The module samples a texture through a sampler whose anisotropy is known where Metal's
/// anisotropic filter is not emulated ([`PrecisionNote::AnisotropicFilter`]'s reach), on a
/// device that does not sample through Metal's own sampler: a cube, a 3D texture, a
/// comparison, a sample whose residency the function observes, or a texture of another
/// class than its declared one, at an implicit level or with explicit gradients, through a
/// constexpr sampler of `maxAnisotropy` above 1 or a runtime sampler slot whose word states
/// anisotropy (under that word alone). The device filters with its own anisotropic rule,
/// whose footprint, level, tap count and weights Vulkan leaves to the implementation: on
/// `rgba8Unorm` 2D textures at `maxAnisotropy` 8 with a linear filter, ANV (Iris Xe), RADV
/// (Radeon 780M) and an RTX 3090 miss Metal by up to 28, 60 and 62 codes (mean 6.6, 6.2 and
/// 12.4); other shapes are not measured. A sampler with a nearest min or mag filter is handed
/// no anisotropy off Metal's sampler, so there the device filters isotropically, and so does
/// every sampler on a device without `samplerAnisotropy`, whatever its sampling (the device's
/// own sampling recording it there too). An argument buffer's sampler, whose anisotropy the
/// function does not know, records `HalfSampleFilter` or `FloatSampleFilter` alone, and is
/// refused anisotropic without `samplerAnisotropy`. Validation derives no tolerance from it.
/// device without `samplerAnisotropy`, which filters it isotropically: a cube, a 3D texture, a
/// comparison, a sample whose residency the function observes, or a texture of another class
/// than its declared one, at an implicit level or with explicit gradients, through a constexpr
/// sampler of `maxAnisotropy` above 1 or a runtime sampler slot whose word states anisotropy
/// (under that word alone). An argument buffer's anisotropic sampler, whose anisotropy the
/// function does not know, is refused there (`SamplerAnisotropy`). Validation derives no
/// tolerance from it.
DeviceAnisotropicFilter,
/// A vertex function writes `[[point_size]]`, or a mesh function `set_point_size`, on a device
/// whose `pointSizeRange` ends below Metal's largest point, 511 pixels
@@ -1547,25 +1392,6 @@ pub enum PrecisionNote {
/// Validation derives no tolerance and no explanation from it: a difference stays a
/// mismatch for review.
LoopedSampleOutputs,
/// The module hands an 8-bit unsigned normalized texture's linear sample to the device's
/// filter, at the coordinate of Metal's footprint step (`lower::sampler::native`), on a
/// device measured to filter that class within one code of Metal
/// (`DriverDeviation::Unorm8LinearFilter`, which the module requires as
/// `VkProperty::Unorm8LinearFilter`): a sample with a `float` or `half` result of a 2D texture
/// or 2D array slot bound in `R8Unorm`, `RG8Unorm`, `RGBA8Unorm` or `BGRA8Unorm`, without
/// comparison, offset or pixel coordinates, through a constexpr sampler Metal's linear rule
/// answers or a runtime sampler slot whose word states one (under that class and word
/// alone). Elsewhere the sample keeps Metal's filter, emulated exactly
/// ([`PrecisionNote::FloatSampleFilter`]). The device reads Metal's taps and weights there;
/// its blend of them is its own. Measured against an Apple M4 (the deviation probe: 4,096
/// coordinates, a third near the 1/256 grid, under clamp to edge, repeat, mirrored repeat and
/// clamp to zero), the largest difference of any channel is 0.849 of a code (1/255) on
/// NVIDIA's 615.71.09 (RTX 3090, RTX 5080 Laptop GPU), 0.031 on RADV and ANV (Mesa 26.2.4,
/// Radeon 780M, Iris Xe of RPL-P, UHD 770 of RPL-S), and just under 1 on lavapipe (Mesa
/// 26.2.4, whose filter answers whole codes), for a `float` result; for a `half` one, 0.809,
/// 0.125 and 0.996. The owner accepted the one-code bound
/// (2026-10-10). Validation derives no tolerance from it.
DeviceUnorm8LinearFilter,
/// A fragment function of a module compiled with fast math (`air.compile.fast_math_enable`)
/// returns a `half` color output to an attachment the pipeline has that stores some channel
/// (its write mask names one of its format's channels; `StageIo::half_fast_colors`, which the
@@ -1626,11 +1452,9 @@ pub enum PrecisionNote {
/// the fast-math regrouping cause.
HalfOutputFastMathBlend,
/// Native device sampling: the module hands a sample, gather or comparison to the device's
/// own sampler where a device whose sampler is not Metal's would emulate Metal's
/// (`SamplingPolicy::NativeDevice`, the default; the module requires
/// own sampler on a device whose sampler is not Metal's (the module requires
/// `VkProperty::DeviceSampling`). Its filter, footprint, level selection, anisotropy, decode
/// and comparison are the device's. [`SamplingPolicy::Exact`](crate::device::SamplingPolicy)
/// keeps Metal's, emulated exactly; a device that samples through Metal's own sampler
/// and comparison are the device's. A device that samples through Metal's own sampler
/// (MoltenVK on Apple's GPU) never records it.
///
/// The recorded bound, measured against an Apple M4 on 2D textures of one level (the deviation
@@ -1645,11 +1469,9 @@ pub enum PrecisionNote {
/// the probe's coordinates on NVIDIA and ANV, 0.02% on RADV, none on lavapipe. Level selection,
/// anisotropy, cube maps, 3D textures, gathers, comparisons and offsets are not measured.
///
/// A linear sample of a two-plane YCbCr texture is the device's filter of its converted texels
/// under [`YCbCrFilterPolicy::Device`](crate::device::YCbCrFilterPolicy), the default: the
/// texels hold Metal's reads exactly, but Metal sums their steps on the format's grid at its own
/// weights, each term truncated. Against that sum (the slot's emulation under
/// `YCbCrFilterPolicy::Exact`, which keeps it), at 65,536 random coordinates on each of five
/// A linear sample of a two-plane YCbCr texture is the device's filter of its converted
/// texels: the texels hold Metal's reads exactly, but Metal sums their steps on the format's
/// grid at its own weights, each term truncated. Against that sum, at 65,536 random coordinates on each of five
/// `YCBCR8_420_2P` surfaces of both ranges and three matrices, `float` and `half` results, the
/// largest difference of any channel, in codes of 1/255, is 1.183 on NVIDIA's 615.71.09 (RTX
/// 3090), 0.877 on RADV (Mesa 26.0.8, Radeon 780M and RX 7900 XTX), 1.058 on ANV (Mesa 26.2.4,
@@ -1693,9 +1515,7 @@ pub enum PrecisionNote {
/// sum). Validation derives no tolerance from it.
NativeFma,
/// Native device sampling (a texel conversion): the module hands a read, sample or gather
/// with a `float` result the device's own conversion of the texel's codes, where Metal's is
/// emulated exactly: a read's under `TexelConversionPolicy::Exact`, a sample's or gather's
/// under it with `SamplingPolicy::Exact`. The default off Apple's GPUs
/// with a `float` result the device's own conversion of the texel's codes, off Apple's GPUs
/// (`VkProperty::MetalSampler` keeps Metal's value). Recorded for every such access of a
/// texture slot or a heap texture (not a heap's texture buffer,
/// [`PrecisionNote::DeviceNanEncoding`]). The recorded bound, of a texel whose access reads
@@ -1709,10 +1529,9 @@ pub enum PrecisionNote {
/// bits; a 4-bit channel's replication is exact;
/// - a half-float or small-float texel's NaN: the device's encoding, where Metal answers
/// `0x7fc00000`;
/// - every other class: the device's value, as under either policy.
/// - every other class: the device's value, which Metal's matches.
///
/// A filtered sample's value is the filter's under either policy. Validation derives no
/// tolerance from it.
/// A filtered sample's value is the filter's. Validation derives no tolerance from it.
DeviceTexelConversion,
/// Native half rounding (a conversion): the module rounds a `half` result it computes in
/// `float` (a `half` operation's, a function's, a conversion from `float`'s, a texel's) by
@@ -1861,35 +1680,15 @@ pub enum PrecisionNote {
/// anisotropic footprint than Metal's. A sampler state the runtime makes of that shape is
/// announced as it is made instead. Validation derives no tolerance from it.
NotMipmappedAnisotropicFilter,
/// A sample whose level the device's level arithmetic chooses, on a device that samples neither
/// through Metal's own sampler nor natively (which records [`PrecisionNote::DeviceSampling`]),
/// of a texture other than a cube (whose level [`PrecisionNote::CubeGradientFootprint`]
/// records), without comparison (whose level [`PrecisionNote::DeviceDepthComparison`] records
/// where the device compares): a fragment function's implicit-level sample, its bias Metal's
/// own reading `B` within the device's `maxSamplerLodBias` (the `Bias` operand), a sample with
/// explicit gradients, a fragment function's LOD query, and a sample at an explicit level (or a
/// kernel's bias) that Metal's level rule is not handed on (`lower::sampler::level`: an integer
/// texture's, and a constexpr sampler's with a level bias of its own or a clamp the rule does
/// not take), but a constant level the device reads as Metal does (a whole level a constexpr
/// sampler without a level bias of its own clamps to a whole level, a float texture's whole
/// level through a runtime sampler, or one a constexpr sampler's snap hands on unchanged). The
/// device takes the level of detail by Vulkan's rules, whose scale factor may be approximated,
/// and a nearest mip filter reads its level `ceil(λ + 1/2) - 1`, where Metal reads the level
/// rounded to `half` with its fraction truncated onto sixty-fourths (measured for explicit
/// levels); Metal's level of detail from derivatives is not measured. Recorded for an LOD
/// query, and for a sample through a sampler that chooses a level or a filter by it (a mip
/// filter, or minification and magnification filters that differ) where no sample-filter note
/// records the sample: through a constexpr sampler with nearest filters and a nearest mip
/// filter, through a runtime sampler where its word states those, and through any such sampler
/// of an integer texture (an argument buffer's sampler, whose state the function does not know,
/// always). An extended-range texture's fragment sample at an implicit level and its sample
/// with explicit gradients (`BGR10_XR`, `BGRA10_XR` and their sRGB twins), which read texels
/// in the shader on every device, take Vulkan's level of detail computed in the shader and
/// then Metal's level rule: recorded through a constexpr sampler with a mip filter, and through
/// a runtime sampler where its word states one. A bias past the limit and hoisted derivatives
/// record [`PrecisionNote::GradFromBias`] instead. **Residual:** the sample may read another level, or
/// another filter, than Metal's near a boundary, and the query answers the device's level.
/// Validation derives no tolerance from it.
/// An extended-range texture's fragment sample at an implicit level and its sample with
/// explicit gradients (`BGR10_XR`, `BGRA10_XR` and their sRGB twins), which read texels in the
/// shader on every device: they take Vulkan's level of detail computed in the shader and then
/// Metal's level rule (`lower::sampler::level`). Vulkan's level of detail, whose scale factor
/// may be approximated, is not Metal's, which is not measured from derivatives. Recorded through
/// a constexpr sampler with a mip filter, and through a runtime sampler where its word states
/// one. A bias past the limit and hoisted derivatives record [`PrecisionNote::GradFromBias`]
/// instead. **Residual:** the sample may read another level, or another filter, than Metal's
/// near a boundary. Validation derives no tolerance from it.
DeviceSampleLevel,
/// A render pipeline covers by alpha (`alphaToCoverageEnabled`) under
/// `TextureWriteRoundingMode::NearestEven`, and its fragment function writes a `float` alpha
+7 -15
View File
@@ -2754,9 +2754,9 @@ fn compile_kept<K>(
.properties
.insert(crate::device::requirements::VkProperty::SimdgroupLockstep);
}
// A filtered `half` sample left to the device's filter because it is Metal's. On a device that
// samples natively, every sample left to the device's sampler requires that instead, and the
// stage records it.
// Every sample, gather and comparison is the device's sampler's: Metal's own on a device
// that samples through it, whose answers the stage claims as Metal's, else the device's own,
// which the stage records. The module requires whichever it is.
let sampling = &plan.families.sampler;
if sampling.metal_sampler || sampling.device_sampling {
use crate::device::requirements::VkProperty;
@@ -2765,18 +2765,10 @@ fn compile_kept<K>(
.enabled
.properties
.contains(&VkProperty::DeviceSampling);
if native {
requirements.properties.insert(VkProperty::DeviceSampling);
} else if sampling.metal_sampler {
requirements.properties.insert(VkProperty::MetalSampler);
}
}
// An 8-bit unsigned normalized linear sample left to the device's filter because it lands
// within one code of Metal's at Metal's footprint step.
if plan.families.sampler.native_filter {
requirements
.properties
.insert(crate::device::requirements::VkProperty::Unorm8LinearFilter);
requirements.properties.insert(match native {
true => VkProperty::DeviceSampling,
false => VkProperty::MetalSampler,
});
}
// A `half` fused multiply-add left to the device's 16-bit `Fma` because it is Metal's.
if plan.families.arith.f16_fma {
+29 -64
View File
@@ -1,7 +1,7 @@
//! The compiler-word-bound fit: a pipeline whose largest stage module passes the device's
//! compiler word bound ([`DeviceProfile::module_word_bound`], where the driver faults compiling a
//! module past it), translated again from its functions with the device policy's exact forms
//! dropped until the largest fits, recording the forms dropped
//! module past it), translated again from its functions with the device policy's module-growing
//! exact forms made native, recording the forms dropped
//! (`RuntimeFact::ExactFormsOverCompilerLimit`). Every pipeline kind is fitted by the one rule: a
//! render pipeline of vertex and fragment stages, a mesh render pipeline (object, mesh and
//! fragment stages, or the compute and synthesized vertex stages of an emulated mesh), a compute
@@ -13,7 +13,7 @@
use crate::budget::{Budget, Meter};
use crate::cache::VariantKey;
use crate::device::policy::{
DevicePolicy, SamplingPolicy, TexelConversionPolicy, YCbCrFilterPolicy,
DevicePolicy,
};
use crate::device::{mechanism, Device, DeviceProfile};
use crate::error::Error;
@@ -34,8 +34,7 @@ impl Device {
/// be `Compiled`), held to the device's compiler word bound
/// ([`DeviceProfile::module_word_bound`]): where the driver faults compiling a module past it
/// and `pipeline`'s largest stage passes it, `d`'s stages translated again with the device
/// policy's exact forms dropped until the largest fits, in at most two steps (native sampling,
/// then every exact answer that grows a module native), recording the forms dropped
/// policy's module-growing exact answers made native, recording the forms dropped
/// (`RuntimeFact::ExactFormsOverCompilerLimit`) and keeping `pipeline`'s key and profile
/// fingerprint, so a cache finds it where it would find `pipeline`. The stages carry the
/// reduced forms' own precision notes. `pipeline` itself where the device has no bound, it
@@ -169,10 +168,9 @@ impl Device {
/// `pipeline` held to `bound`, every kind by the one rule: where its stages can be translated
/// again (`translatable`) and its largest stage passes `bound`, `again` (the pipeline's compile
/// on a device of a reduced policy) under native sampling, then under every module-growing
/// exact answer native, stopping at the first that fits (the last where none does), with the
/// forms it dropped recorded and `pipeline`'s key and profile fingerprint kept. A step that
/// changes nothing of the policy is skipped.
/// on a device of a reduced policy) under every module-growing exact answer native, with the
/// forms it dropped recorded and `pipeline`'s key and profile fingerprint kept. A reduction
/// that changes nothing of the policy is skipped.
fn held_to<P: Fitted>(
&self,
pipeline: P,
@@ -180,34 +178,22 @@ impl Device {
translatable: bool,
again: impl Fn(&Device) -> Result<P, Error>,
) -> Result<P, Error> {
let Some(bound) = bound.filter(|&w| translatable && pipeline.largest_stage_words() > w)
else {
if !bound.is_some_and(|w| translatable && pipeline.largest_stage_words() > w) {
return Ok(pipeline);
};
let base = *self.policy();
let mut best: Option<P> = None;
for step in [ReducedForms::NativeSampling, ReducedForms::AllNative] {
let policy = step.of(base);
if policy == base {
continue;
}
// The lowering reads the profile, never the policy, and `Device::new` is the profile's
// one producer: the description kept, the policy reduced.
let device = Device::new(self.description().clone(), policy)?;
let mut reduced = again(&device)?;
reduced
.dependencies_mut()
.push(dropped_forms(base, &policy, device.profile()));
let fits = reduced.largest_stage_words() <= bound;
best = Some(reduced);
if fits {
break;
}
}
Ok(match best {
Some(reduced) => reduced.named_as(&pipeline),
None => pipeline,
})
let base = *self.policy();
let policy = native_forms(base);
if policy == base {
return Ok(pipeline);
}
// The lowering reads the profile, never the policy, and `Device::new` is the profile's
// one producer: the description kept, the policy reduced.
let device = Device::new(self.description().clone(), policy)?;
let mut reduced = again(&device)?;
reduced
.dependencies_mut()
.push(dropped_forms(base, &policy, device.profile()));
Ok(reduced.named_as(&pipeline))
}
}
@@ -274,33 +260,14 @@ fn words(spirv: &[u32]) -> u32 {
u32::try_from(spirv.len()).unwrap_or(u32::MAX)
}
/// A step of the compiler-word-bound fallback: the exact forms to drop from the consumer's policy.
/// `NativeSampling` drops exact sampling, the single largest exact form, with Metal's filter of a
/// two-plane YCbCr texture (`YCbCrFilterPolicy::Exact`, reported with it); `AllNative` drops every
/// module-growing exact answer (the fast default's forms). Neither touches the policy's other
/// choices (pointer and handle domains, containment, isolation, framebuffer fetch, the 8-bit
/// filter, or the runtime's choices, which change no module), so a reduced device keeps them.
#[derive(Clone, Copy)]
enum ReducedForms {
NativeSampling,
AllNative,
}
impl ReducedForms {
/// `base` with this step's exact forms set to their native, module-smaller answers.
fn of(self, base: DevicePolicy) -> DevicePolicy {
let sampled = DevicePolicy {
sampling: SamplingPolicy::NativeDevice,
ycbcr_filter: YCbCrFilterPolicy::Device,
..base
};
match self {
ReducedForms::NativeSampling => sampled,
ReducedForms::AllNative => DevicePolicy {
texel_conversion: TexelConversionPolicy::Device,
..sampled
},
}
/// The compiler-word-bound fallback's policy: `base` with every module-growing exact answer (the
/// fast default's forms) set to its native, module-smaller answer. It does not touch the policy's
/// other choices (pointer and handle domains, containment, isolation, framebuffer fetch, or the
/// runtime's choices, which change no module), so a reduced device keeps them.
fn native_forms(base: DevicePolicy) -> DevicePolicy {
DevicePolicy {
nan_and_min_max: NanMinMaxPolicy::Native,
..base
}
}
@@ -313,8 +280,6 @@ fn dropped_forms(
reduced: &DeviceProfile,
) -> RuntimeDependency {
let fact = RuntimeFact::ExactFormsOverCompilerLimit {
sampling: base.sampling != policy.sampling || base.ycbcr_filter != policy.ycbcr_filter,
texel_conversion: base.texel_conversion != policy.texel_conversion,
};
RuntimeDependency {
fact,
@@ -11,10 +11,9 @@
use std::collections::BTreeMap;
use std::path::Path;
use super::{Fitted, ReducedForms};
use super::{native_forms, Fitted};
use crate::budget::{Budget, Meter};
use crate::cache::VariantKey;
use crate::device::policy::SamplingPolicy;
use crate::device::{Device, DeviceDescription, DevicePolicy};
use crate::library::Library;
use crate::metal;
@@ -50,12 +49,9 @@ fn description(stem: &str) -> DeviceDescription {
DeviceDescription::from_khronos_json(&text, None).expect("description")
}
/// Every exact form, Metal's sampler emulated among them.
/// Every exact form.
fn exact() -> DevicePolicy {
DevicePolicy {
sampling: SamplingPolicy::Exact,
..DevicePolicy::default().exact_answers()
}
DevicePolicy::default().exact_answers()
}
/// Committed profile `stem` as a device under `policy`.
@@ -65,12 +61,9 @@ fn device(stem: &str, policy: DevicePolicy) -> Device {
/// The forms a fitted pipeline's `dependencies` record it dropped, in the fact's field order;
/// `None` where it records none.
fn dropped(dependencies: &[RuntimeDependency]) -> Option<[bool; 2]> {
fn dropped(dependencies: &[RuntimeDependency]) -> Option<[bool; 1]> {
dependencies.iter().find_map(|d| match d.fact {
RuntimeFact::ExactFormsOverCompilerLimit {
sampling,
texel_conversion,
} => Some([sampling, texel_conversion]),
RuntimeFact::ExactFormsOverCompilerLimit { nan_and_min_max } => Some([nan_and_min_max]),
_ => None,
})
}
@@ -80,8 +73,6 @@ fn dropped(dependencies: &[RuntimeDependency]) -> Option<[bool; 2]> {
/// bound gives it: recording that it dropped every exact form, named as `compiled` is.
fn fitted_as<P: Fitted>(reduced: P, compiled: &P) -> P {
let fact = RuntimeFact::ExactFormsOverCompilerLimit {
sampling: true,
texel_conversion: true,
};
let mut reduced = reduced;
reduced
@@ -91,8 +82,8 @@ fn fitted_as<P: Fitted>(reduced: P, compiled: &P) -> P {
}
/// A render pipeline whose largest stage module passes a device's compiler word bound is
/// translated again with the device policy's exact forms dropped until it fits: native sampling
/// first, then every exact answer that grows a module native, recording which forms it dropped
/// translated again with every exact answer that grows a module native, recording which forms it
/// dropped
/// (`RuntimeFact::ExactFormsOverCompilerLimit`) and keeping the compile's key and profile
/// fingerprint. A pipeline compiled from stages compiled ahead (the runtime's shape) is fitted from
/// its functions' descriptor ([`Device::fit_render_variant`]), and is left as it is from its
@@ -132,12 +123,8 @@ fn a_module_over_the_compiler_bound_drops_its_exact_forms_to_fit() {
}
let w_exact = words(exact());
let w_sampling_native = words(DevicePolicy::default().exact_answers());
let w_fast = words(DevicePolicy::default());
assert!(
w_fast <= w_sampling_native && w_sampling_native <= w_exact,
"fast {w_fast} <= sampling-native {w_sampling_native} <= exact {w_exact}"
);
assert!(w_fast <= w_exact, "fast {w_fast} <= exact {w_exact}");
let dev = device(stem, exact());
let first = || {
@@ -161,22 +148,10 @@ fn a_module_over_the_compiler_bound_drops_its_exact_forms_to_fit() {
assert_eq!(largest(&pipe), w_fast, "reduced to the fast default");
assert_eq!(
dropped(&pipe.dependencies),
Some([true; 2]),
Some([true; 1]),
"every exact form dropped"
);
// Over the bound by exact sampling alone (where it grows the module): sampling is dropped
// first, and nothing more, because native sampling already fits.
if w_sampling_native < w_exact {
let pipe = fit(w_sampling_native);
assert_eq!(largest(&pipe), w_sampling_native);
assert_eq!(
dropped(&pipe.dependencies),
Some([true, false]),
"only sampling dropped"
);
}
// Within the bound, or on a device without one: no fallback, no fact, the exact forms kept.
for pipe in [
fit(u32::MAX),
@@ -224,7 +199,7 @@ fn a_module_over_the_compiler_bound_drops_its_exact_forms_to_fit() {
.expect("fitted from the functions");
assert_eq!(fitted.key, keys.pipeline);
assert_eq!(largest(&fitted), w_fast);
assert_eq!(dropped(&fitted.dependencies), Some([true; 2]));
assert_eq!(dropped(&fitted.dependencies), Some([true; 1]));
}
/// A mesh render pipeline is fitted as a vertex and fragment pipeline is: past the bound, its
@@ -285,7 +260,7 @@ fn a_mesh_pipeline_over_the_compiler_bound_drops_its_exact_forms_to_fit() {
let stages: Vec<ShaderStage> = compiled.stages.iter().map(|s| s.stage).collect();
assert_eq!(stages, kinds, "{stem}");
let fast = device(stem, ReducedForms::AllNative.of(exact()));
let fast = device(stem, native_forms(exact()));
let reduced = fast
.mesh_pipeline(&descriptor(), &v, &mut Meter::new(&b))
.expect(stem);
@@ -378,7 +353,7 @@ fn a_tile_pipeline_over_the_compiler_bound_drops_its_exact_forms_to_fit() {
assert_eq!(compiled, unfitted, "{stem}: within the device's own bound");
assert_eq!(dropped(&compiled.dependencies), None, "{stem}");
let fast = device(stem, ReducedForms::AllNative.of(exact()));
let fast = device(stem, native_forms(exact()));
let reduced = fast
.tile_pipeline(&d, &inputs, &mut Meter::new(&b))
.expect(stem);
@@ -436,8 +411,7 @@ fn a_tile_pipeline_over_the_compiler_bound_drops_its_exact_forms_to_fit() {
/// inputs it was compiled under, and one within the bound translates exactly as before the fit:
/// on ANV's UHD 770 profile, whose own bound the kernel fits, and on a device without a bound,
/// under every exact form and under the fast default, `compile_compute_pipeline` is the unfitted
/// compile, word for word. Past the bound every exact form is dropped; past it by exact sampling
/// alone, sampling alone. In the runtime's shape (the kernel compiled ahead and linked from the
/// compile, word for word. Past the bound every exact form is dropped. In the runtime's shape (the kernel compiled ahead and linked from the
/// `Compiled` stage) it is fitted from the function's descriptor and left as it is from the
/// `Compiled` one. Uses the owned `a2_kernel_lod_filter` fixture, a kernel that samples.
#[test]
@@ -473,9 +447,7 @@ fn a_compute_pipeline_over_the_compiler_bound_drops_its_exact_forms_to_fit() {
let dev = device(stem, exact());
let compiled = dev.compile_compute_pipeline(&d, &b).expect(stem);
let w_exact = compiled.largest_stage_words();
let sampled = unfitted(&device(stem, ReducedForms::NativeSampling.of(exact())));
let w_sampling_native = sampled.largest_stage_words();
let reduced = unfitted(&device(stem, ReducedForms::AllNative.of(exact())));
let reduced = unfitted(&device(stem, native_forms(exact())));
let w_fast = device(stem, DevicePolicy::default())
.compile_compute_pipeline(&d, &b)
.expect(stem)
@@ -486,8 +458,8 @@ fn a_compute_pipeline_over_the_compiler_bound_drops_its_exact_forms_to_fit() {
"{stem}: the fast forms"
);
assert!(
w_fast <= w_sampling_native && w_sampling_native < w_exact,
"{stem}: fast {w_fast} <= sampling-native {w_sampling_native} < exact {w_exact}"
w_fast <= w_exact,
"{stem}: fast {w_fast} <= exact {w_exact}"
);
let expected = fitted_as(reduced, &compiled);
let fit = |d: &ComputePipelineDescriptor, pipeline, bound| {
@@ -499,19 +471,6 @@ fn a_compute_pipeline_over_the_compiler_bound_drops_its_exact_forms_to_fit() {
expected,
"{stem}: past the bound"
);
// Over the bound by exact sampling alone: sampling alone dropped.
let pipe = fit(&d, compiled.clone(), Some(w_sampling_native));
assert_eq!(pipe.stage, sampled.stage, "{stem}: native sampling");
assert_eq!(
dropped(&pipe.dependencies),
Some([true, false]),
"{stem}: only sampling dropped"
);
assert_eq!(
(pipe.key, pipe.profile),
(compiled.key, compiled.profile),
"{stem}"
);
for bound in [Some(w_exact), Some(u32::MAX), None] {
assert_eq!(fit(&d, compiled.clone(), bound), compiled, "{stem}: within");
}
@@ -214,11 +214,6 @@ pub fn function_key(
.bytes(format!("{:?}", inputs.snapshot_textures).as_bytes());
}
// Appended only when set, as `storage_view_slots`.
if !inputs.ycbcr_textures.is_empty() {
h.bytes(b"ycbcr-textures")
.bytes(format!("{:?}", inputs.ycbcr_textures).as_bytes());
}
// Appended only when set, as `storage_view_slots`.
if !inputs.ycbcr_in_place.is_empty() {
h.bytes(b"ycbcr-in-place")
.bytes(format!("{:?}", inputs.ycbcr_in_place).as_bytes());
@@ -708,7 +708,6 @@ fn the_inputs_encoding_is_the_earlier_derived_debug() {
.replace(", srgb_textures: {}", "")
.replace(", srgb_twins: {}", "")
.replace(", snapshot_textures: {}", "")
.replace(", ycbcr_textures: {}", "")
.replace(", ycbcr_in_place: {}", "")
.replace(", viewport_index_varying: false", "")
.replace(", max_call_stack_depth: None", "")
@@ -2604,10 +2603,7 @@ fn the_interface_states_the_textures_read_at_the_fragments_own_pixel() {
/// writes no memory of the function's. A profile without the interlock refuses it, naming the
/// feature. A variant asked for `tob_sample`'s slot, which the fact does not list, would sample the
/// texture beside the copy: refused, never compiled so. All of it holds under the exact answers
/// too, and there each snapshot variant names Metal's conversion routine
/// (`lower::texture::float_texel`) exactly where the direct read does: the read decodes the
/// snapshot's codes and converts the value by the bound format's class, so what a program reads
/// back through a snapshot is what it reads without one.
/// too.
#[test]
fn a_snapshot_variant_reads_its_texture_in_the_copy_alone() {
use crate::device::requirements::VkFeature;
@@ -2628,12 +2624,11 @@ fn a_snapshot_variant_reads_its_texture_in_the_copy_alone() {
inputs
};
let mut interlocked = 0;
let mut converted = 0;
let policies = [
DevicePolicy::default(),
DevicePolicy::default().exact_answers(),
("default", DevicePolicy::default()),
("exact", DevicePolicy::default().exact_answers()),
];
for (stem, policy) in [
for (stem, name, policy) in [
"intel-irisxe-anv",
"nvidia-rtx5080-laptop",
"amd-780m-radv",
@@ -2642,23 +2637,13 @@ fn a_snapshot_variant_reads_its_texture_in_the_copy_alone() {
"vk12-floor",
]
.into_iter()
.flat_map(|stem| policies.map(|policy| (stem, policy)))
.flat_map(|stem| policies.map(|(name, policy)| (stem, name, policy)))
{
let p = crate::pipeline::testing::profile(stem, policy).expect("profile");
let stem = format!("{stem} {:?}", policy.texel_conversion);
let stem = format!("{stem} {name}");
let base = crate::pipeline::testing::compile(&bc, "tob_read", &p)
.unwrap_or_else(|e| panic!("{stem}: {e}"));
assert_eq!(base.interface.snapshot_textures, [0u32], "{stem}");
let routine = crate::lower::texture::float_texel::CENSUS_NAME;
let converts = base.strategies.entries.contains_key(routine);
if converts {
assert_eq!(
policy.texel_conversion,
crate::device::TexelConversionPolicy::Exact,
"{stem}"
);
converted += 1;
}
let sampled = crate::pipeline::testing::compile(&bc, "tob_sample", &p)
.unwrap_or_else(|e| panic!("{stem}: {e}"));
assert!(sampled.interface.snapshot_textures.is_empty(), "{stem}");
@@ -2695,22 +2680,9 @@ fn a_snapshot_variant_reads_its_texture_in_the_copy_alone() {
[0u32],
"{stem} {form:?}"
);
// The snapshot's codes reach the output through the same conversion the direct read
// takes: the read decodes them and converts the value by the bound format's class,
// so the value a program reads back is the one it reads without a snapshot.
assert_eq!(
narrow.strategies.entries.contains_key(routine),
converts,
"{stem} {form:?}: the conversion routine"
);
}
let a = variant.unwrap_or_else(|e| panic!("{stem}: {e}"));
assert_eq!(a.interface.snapshot_textures, [0u32], "{stem}");
assert_eq!(
a.strategies.entries.contains_key(routine),
converts,
"{stem}: the conversion routine"
);
assert_eq!(a.interface.own_pixel_textures, [0u32], "{stem}");
assert!(!a.interface.writes_memory, "{stem}");
assert!(
@@ -2748,7 +2720,6 @@ fn a_snapshot_variant_reads_its_texture_in_the_copy_alone() {
interlocked >= 8,
"the interlocked profiles, under both policies"
);
assert!(converted >= 4, "the exact conversion's calls");
}
/// The interface states whether the function writes memory another invocation or a later command
+9 -25
View File
@@ -284,13 +284,14 @@ pub enum RuntimeFact {
/// kernel in the emulated tier votes in its scratch instead
/// (`RuntimeFact::SimdgroupEmulation`).
PredicationVote,
/// The function reads or samples the texture (or texture buffer) bound to the slot with a
/// `half` result, or samples it through an emulated linear filter, and Metal's conversion of
/// a texel to `half`, or its linear filter's sum, depends on the bound pixel format (a read
/// of a 32-bit float texel rounds to nearest even, a sample of one toward zero; a normalized
/// texel's value is rounded onto its format's grid first): the slot's `SpecKey::TexelFormat`
/// specialization (`metal::texel_format::texel_format`), which the binder sets from the
/// bound format.
/// The function reads the class of the texture (or texture buffer) bound to the slot, which
/// the binder sets from the bound format: the slot's `SpecKey::TexelFormat` specialization
/// (`metal::texel_format::texel_format`). A read, gather or sample with a `half` result on a
/// device that samples through Metal's own sampler converts its texel by it, Metal's conversion
/// depending on the format (a read of a 32-bit float texel rounds to nearest even, a sample of
/// one toward zero; a normalized texel's value is rounded onto its format's grid first); an
/// 8-bit sRGB slot's raw read, a fetched gather and a NaN texel's rule (the NaN switch) read
/// it too.
TexelFormat { slot: SlotRef },
/// The function reads, samples, or gathers the texture bound to the slot in a form whose
/// result Metal takes from the raw code of an 8-bit sRGB texel, decoded through its
@@ -525,19 +526,6 @@ pub enum RuntimeFact {
/// serve (tests the draw does not state) is refused, as any draw whose variant is refused: the
/// runtime keeps the color out of the storage form there (the pass splits, or the shadow ends).
MovableStorageWrites { early_variant: bool },
/// On a device that samples through Metal's own sampler (`VkProperty::MetalSampler`:
/// MoltenVK on Apple's GPU), the function samples the texture bound to the slot through a
/// linear filter, which the device's filter answers as Metal does for every format but the
/// two-plane YCbCr ones, whose view holds texels Metal filters by the YCbCr format's own rule
/// (`metal::format::ycbcr_format`): bound in such a format, the slot joins the plan's variant
/// (`VariantKey::ycbcr_textures`, `LoweringInputs::ycbcr_textures`), under which the function
/// emulates Metal's filter of the slot's samples as a device without the property does, and
/// notes the samples the emulation does not reach. Bound in any other format, or unbound, the
/// slot leaves the variant. Recorded only under `YCbCrFilterPolicy::Exact`, and through Metal's
/// own sampler also under `SamplingPolicy::Exact`, as is the same fact on a device that samples
/// natively (`VkProperty::DeviceSampling`; `ProfileFields::ycbcr_variant`); under the default
/// the device's filter answers the slot as any other's, noted, and no draw makes the variant.
YCbCrTexture { slot: SlotRef },
/// The tile function reads a builtin whose answer depends on its pipeline's
/// `threadgroupSizeMatchesTileSize` (its threads per threadgroup, simdgroups or quadgroups
/// per threadgroup or their `dispatch_` forms, its position in the grid, the threads per
@@ -753,15 +741,11 @@ pub enum RuntimeFact {
/// device's compiler word bound and that driver faults compiling a module past it
/// ([`DriverWorkaround::RegisterAllocatorOverflowsLargeModules`](crate::device::DriverWorkaround::RegisterAllocatorOverflowsLargeModules):
/// ANV's register allocator). Each `true` field is an exact form the pipeline would carry under
/// the consumer's policy that the fitting translation gave up to fit the bound (`sampling`
/// also for Metal's filter of a two-plane YCbCr texture, `YCbCrFilterPolicy::Exact`, which is
/// dropped with it); the stages carry
/// the consumer's policy that the fitting translation gave up to fit the bound; the stages carry
/// the reduced policy's own precision notes besides. The consumer announces it once per device
/// (the runtime's `Degradation::ExactFormsOverCompilerLimit`), naming the pipeline and the forms
/// dropped. Nothing binds it.
ExactFormsOverCompilerLimit {
sampling: bool,
texel_conversion: bool,
},
/// The render pipeline was compiled under `VariantKey::quad_primitive_ids`, and its fragment
/// function reads `[[primitive_id]]` from Vulkan's `PrimitiveId` shifted right by one
Loaded 100 of 142 files, more files were not shown because too many files have changed in this diff. Show more