From 78ed264c902c5de63b258459f5442fe780ee2f81 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Tue, 27 Oct 2026 18:34:00 +0200 Subject: [PATCH] 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). --- CONTRIBUTING.md | 4 +- .../src/bin/render-pipeline-split.rs | 1 - .../src/bin/stage-input-split.rs | 1 - .../src/bin/tile-pipeline-split.rs | 1 - .../src/bin/translate-split.rs | 1 - .../src/cases/argument_encoders.rs | 14 +- .../src/cases/astc_textures.rs | 40 +- .../src/cases/border_swizzles.rs | 25 +- .../src/cases/compressed_decode.rs | 21 +- .../src/cases/etc_textures.rs | 88 +- .../src/cases/pixel_downscales.rs | 6 +- .../src/cases/pixel_samplers.rs | 6 +- .../src/cases/sampler_crossings.rs | 9 +- .../src/cases/sampler_filtering.rs | 10 +- crates/metal2vulkan-conformance/src/device.rs | 3 +- crates/metal2vulkan-runtime/src/astc.rs | 6 +- .../metal2vulkan-runtime/src/degradation.rs | 60 +- crates/metal2vulkan-runtime/src/etc.rs | 7 +- .../src/tests/fitted_variant_notice.rs | 10 +- .../src/tests/image_plan.rs | 4 +- .../src/texture/decoded_twin.rs | 81 +- .../src/bin/corpus-draw-ab.rs | 12 +- crates/metal2vulkan-validation/src/c3.rs | 24 +- .../metal2vulkan-validation/src/c3/tests.rs | 10 - .../metal2vulkan-validation/src/candidate.rs | 11 +- .../src/candidate/runtime_case.rs | 12 +- .../src/observation_contract/comparison.rs | 17 - .../observation_contract/comparison/tests.rs | 4 - .../src/runtime_lane/anisotropic_filter.rs | 85 +- .../runtime_lane/argument_linear_samples.rs | 87 +- .../src/runtime_lane/astc_textures.rs | 70 +- .../src/runtime_lane/cubic_samplers.rs | 7 +- .../src/runtime_lane/degrade_notices.rs | 10 +- .../src/runtime_lane/depth_denormals.rs | 13 +- .../src/runtime_lane/etc_textures.rs | 47 +- .../src/runtime_lane/nearest_positions.rs | 60 +- .../src/runtime_lane/runtime_data.rs | 18 +- .../src/runtime_lane/ycbcr_textures.rs | 61 +- crates/metal2vulkan/src/bind/graphics.rs | 3 +- crates/metal2vulkan/src/bind/heap.rs | 36 +- crates/metal2vulkan/src/bind/plan/compute.rs | 3 +- crates/metal2vulkan/src/bind/plan/slots.rs | 26 - .../metal2vulkan/src/bind/plan/slots/tests.rs | 15 +- crates/metal2vulkan/src/cache/codec.rs | 11 +- crates/metal2vulkan/src/cache/mod.rs | 19 +- crates/metal2vulkan/src/cache/tests.rs | 33 +- crates/metal2vulkan/src/device/derive.rs | 44 +- crates/metal2vulkan/src/device/mechanism.rs | 3 - crates/metal2vulkan/src/device/mod.rs | 5 +- crates/metal2vulkan/src/device/policy.rs | 236 +- crates/metal2vulkan/src/device/profile.rs | 34 +- .../metal2vulkan/src/device/requirements.rs | 5 +- .../src/device/tests/driver_facts.rs | 27 +- .../src/device/tests/mechanism.rs | 11 +- .../metal2vulkan/src/device/tests/profile.rs | 92 - crates/metal2vulkan/src/lower/access/mod.rs | 11 +- crates/metal2vulkan/src/lower/arith/tests.rs | 1 - .../src/lower/arith/tests/bicubic.rs | 185 +- .../src/lower/arith/tests/float_texel.rs | 384 -- .../src/lower/sampler/anisotropic.rs | 24 +- .../src/lower/sampler/anisotropic/tests.rs | 216 +- .../metal2vulkan/src/lower/sampler/bicubic.rs | 20 +- .../src/lower/sampler/bicubic/routines.rs | 174 +- .../src/lower/sampler/compared.rs | 878 --- crates/metal2vulkan/src/lower/sampler/emit.rs | 444 +- crates/metal2vulkan/src/lower/sampler/face.rs | 570 +- .../src/lower/sampler/face/tests.rs | 8 +- .../src/lower/sampler/face/tests/fold.rs | 151 - .../src/lower/sampler/face/tests/routines.rs | 22 +- .../src/lower/sampler/face/tests/snap.rs | 341 -- .../metal2vulkan/src/lower/sampler/fetched.rs | 1044 +--- .../metal2vulkan/src/lower/sampler/level.rs | 401 +- .../src/lower/sampler/level/tests.rs | 421 +- .../metal2vulkan/src/lower/sampler/linear.rs | 1817 +----- .../src/lower/sampler/linear/compare.rs | 344 -- .../src/lower/sampler/linear/cube.rs | 714 --- crates/metal2vulkan/src/lower/sampler/mod.rs | 446 +- .../metal2vulkan/src/lower/sampler/native.rs | 343 -- .../src/lower/sampler/position.rs | 682 +-- .../src/lower/sampler/position/tests.rs | 616 +-- .../metal2vulkan/src/lower/sampler/routine.rs | 228 +- .../metal2vulkan/src/lower/sampler/select.rs | 668 +-- .../metal2vulkan/src/lower/sampler/shared.rs | 319 +- crates/metal2vulkan/src/lower/texture/emit.rs | 163 +- .../src/lower/texture/float_texel.rs | 188 - crates/metal2vulkan/src/lower/texture/half.rs | 21 - crates/metal2vulkan/src/lower/texture/mod.rs | 273 +- crates/metal2vulkan/src/lower/texture/slot.rs | 7 +- crates/metal2vulkan/src/memory/handles.rs | 114 +- crates/metal2vulkan/src/metal/format/word.rs | 12 +- crates/metal2vulkan/src/metal/sampler.rs | 159 +- crates/metal2vulkan/src/metal/texel_format.rs | 60 +- crates/metal2vulkan/src/pipeline/api_tests.rs | 2 - crates/metal2vulkan/src/pipeline/artifact.rs | 345 +- crates/metal2vulkan/src/pipeline/compile.rs | 22 +- .../metal2vulkan/src/pipeline/compile/fit.rs | 93 +- .../src/pipeline/compile/fit/tests.rs | 73 +- .../metal2vulkan/src/pipeline/compile/key.rs | 5 - .../src/pipeline/compile/tests.rs | 41 +- crates/metal2vulkan/src/pipeline/facts.rs | 34 +- .../metal2vulkan/src/pipeline/link/vertex.rs | 32 - .../metal2vulkan/src/pipeline/lower_inputs.rs | 7 - crates/metal2vulkan/src/pipeline/testing.rs | 19 +- .../src/spirv/requirements/snapshot.rs | 4 +- crates/metal2vulkan/src/spirv/testing.rs | 8 - .../src/tests/engine_bias_reach.rs | 346 +- .../metal2vulkan/src/tests/engine_bicubic.rs | 113 +- .../src/tests/engine_cross_class.rs | 23 +- .../src/tests/engine_cube_gather.rs | 1656 ------ .../src/tests/engine_depth_range.rs | 72 +- .../src/tests/engine_device_level.rs | 102 - .../src/tests/engine_extended_range/heap.rs | 39 - .../metal2vulkan/src/tests/engine_fragment.rs | 78 +- .../metal2vulkan/src/tests/engine_handles.rs | 560 +- .../src/tests/engine_heap_binder.rs | 55 +- .../src/tests/engine_linear_cube.rs | 1652 ------ .../src/tests/engine_linear_half.rs | 4899 ----------------- .../tests/engine_linear_half/edge_samples.tsv | 94 - .../src/tests/engine_linear_half/levels.rs | 382 -- .../src/tests/engine_linear_half/packed.rs | 664 --- .../engine_linear_half/packed_samples.tsv | 432 -- .../src/tests/engine_linear_half/ycbcr.rs | 879 --- .../src/tests/engine_private_render_state.rs | 7 +- .../metal2vulkan/src/tests/engine_sampler.rs | 178 +- .../src/tests/engine_sampler_fetched.rs | 648 --- .../src/tests/engine_sampler_unk.rs | 144 +- .../src/tests/engine_separate_samplers.rs | 4 +- .../src/tests/engine_shared_switch.rs | 197 +- .../metal2vulkan/src/tests/engine_snapped.rs | 293 +- .../metal2vulkan/src/tests/engine_srgb_raw.rs | 837 +-- .../src/tests/engine_swizzled_storage.rs | 32 +- .../src/tests/engine_texture_interp.rs | 107 +- .../src/tests/engine_vertex_variants.rs | 94 +- .../in_place.rs => engine_ycbcr_in_place.rs} | 352 +- crates/metal2vulkan/src/tests/fast_paths.rs | 80 +- .../metal2vulkan/src/tests/golden_hashes.rs | 32 +- crates/metal2vulkan/src/tests/mod.rs | 6 +- crates/metal2vulkan/tests/api_surface.rs | 6 - docs/API.md | 177 +- docs/ARCHITECTURE.md | 6 +- docs/FAST-PATHS.md | 38 +- docs/VALIDATION.md | 3 +- 142 files changed, 2894 insertions(+), 27096 deletions(-) delete mode 100644 crates/metal2vulkan/src/lower/arith/tests/float_texel.rs delete mode 100644 crates/metal2vulkan/src/lower/sampler/compared.rs delete mode 100644 crates/metal2vulkan/src/lower/sampler/face/tests/fold.rs delete mode 100644 crates/metal2vulkan/src/lower/sampler/face/tests/snap.rs delete mode 100644 crates/metal2vulkan/src/lower/sampler/linear/compare.rs delete mode 100644 crates/metal2vulkan/src/lower/sampler/linear/cube.rs delete mode 100644 crates/metal2vulkan/src/lower/sampler/native.rs delete mode 100644 crates/metal2vulkan/src/lower/texture/float_texel.rs delete mode 100644 crates/metal2vulkan/src/tests/engine_cube_gather.rs delete mode 100644 crates/metal2vulkan/src/tests/engine_device_level.rs delete mode 100644 crates/metal2vulkan/src/tests/engine_linear_cube.rs delete mode 100644 crates/metal2vulkan/src/tests/engine_linear_half.rs delete mode 100644 crates/metal2vulkan/src/tests/engine_linear_half/edge_samples.tsv delete mode 100644 crates/metal2vulkan/src/tests/engine_linear_half/levels.rs delete mode 100644 crates/metal2vulkan/src/tests/engine_linear_half/packed.rs delete mode 100644 crates/metal2vulkan/src/tests/engine_linear_half/packed_samples.tsv delete mode 100644 crates/metal2vulkan/src/tests/engine_linear_half/ycbcr.rs delete mode 100644 crates/metal2vulkan/src/tests/engine_sampler_fetched.rs rename crates/metal2vulkan/src/tests/{engine_linear_half/in_place.rs => engine_ycbcr_in_place.rs} (54%) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9e202730a..1b835a481 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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 diff --git a/crates/metal2vulkan-conformance/src/bin/render-pipeline-split.rs b/crates/metal2vulkan-conformance/src/bin/render-pipeline-split.rs index 21085f9b8..f6ab28d64 100644 --- a/crates/metal2vulkan-conformance/src/bin/render-pipeline-split.rs +++ b/crates/metal2vulkan-conformance/src/bin/render-pipeline-split.rs @@ -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 { diff --git a/crates/metal2vulkan-conformance/src/bin/stage-input-split.rs b/crates/metal2vulkan-conformance/src/bin/stage-input-split.rs index a68687a3c..56f48b538 100644 --- a/crates/metal2vulkan-conformance/src/bin/stage-input-split.rs +++ b/crates/metal2vulkan-conformance/src/bin/stage-input-split.rs @@ -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()); diff --git a/crates/metal2vulkan-conformance/src/bin/tile-pipeline-split.rs b/crates/metal2vulkan-conformance/src/bin/tile-pipeline-split.rs index 271d23e8b..041d3ff7d 100644 --- a/crates/metal2vulkan-conformance/src/bin/tile-pipeline-split.rs +++ b/crates/metal2vulkan-conformance/src/bin/tile-pipeline-split.rs @@ -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 { diff --git a/crates/metal2vulkan-conformance/src/bin/translate-split.rs b/crates/metal2vulkan-conformance/src/bin/translate-split.rs index cc2474ef0..6c2d576d9 100644 --- a/crates/metal2vulkan-conformance/src/bin/translate-split.rs +++ b/crates/metal2vulkan-conformance/src/bin/translate-split.rs @@ -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()); diff --git a/crates/metal2vulkan-conformance/src/cases/argument_encoders.rs b/crates/metal2vulkan-conformance/src/cases/argument_encoders.rs index fb7f1f972..97408c64c 100644 --- a/crates/metal2vulkan-conformance/src/cases/argument_encoders.rs +++ b/crates/metal2vulkan-conformance/src/cases/argument_encoders.rs @@ -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 { @@ -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 diff --git a/crates/metal2vulkan-conformance/src/cases/astc_textures.rs b/crates/metal2vulkan-conformance/src/cases/astc_textures.rs index c061524ee..89aebe4eb 100644 --- a/crates/metal2vulkan-conformance/src/cases/astc_textures.rs +++ b/crates/metal2vulkan-conformance/src/cases/astc_textures.rs @@ -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; diff --git a/crates/metal2vulkan-conformance/src/cases/border_swizzles.rs b/crates/metal2vulkan-conformance/src/cases/border_swizzles.rs index eb531b90a..00d4520f9 100644 --- a/crates/metal2vulkan-conformance/src/cases/border_swizzles.rs +++ b/crates/metal2vulkan-conformance/src/cases/border_swizzles.rs @@ -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. /// diff --git a/crates/metal2vulkan-conformance/src/cases/compressed_decode.rs b/crates/metal2vulkan-conformance/src/cases/compressed_decode.rs index 3ba0d6472..20e16ac3a 100644 --- a/crates/metal2vulkan-conformance/src/cases/compressed_decode.rs +++ b/crates/metal2vulkan-conformance/src/cases/compressed_decode.rs @@ -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 diff --git a/crates/metal2vulkan-conformance/src/cases/etc_textures.rs b/crates/metal2vulkan-conformance/src/cases/etc_textures.rs index db52f5d8e..699de7165 100644 --- a/crates/metal2vulkan-conformance/src/cases/etc_textures.rs +++ b/crates/metal2vulkan-conformance/src/cases/etc_textures.rs @@ -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. diff --git a/crates/metal2vulkan-conformance/src/cases/pixel_downscales.rs b/crates/metal2vulkan-conformance/src/cases/pixel_downscales.rs index 12a62f83c..929db8a26 100644 --- a/crates/metal2vulkan-conformance/src/cases/pixel_downscales.rs +++ b/crates/metal2vulkan-conformance/src/cases/pixel_downscales.rs @@ -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() diff --git a/crates/metal2vulkan-conformance/src/cases/pixel_samplers.rs b/crates/metal2vulkan-conformance/src/cases/pixel_samplers.rs index 9fd20137a..7a4a8f290 100644 --- a/crates/metal2vulkan-conformance/src/cases/pixel_samplers.rs +++ b/crates/metal2vulkan-conformance/src/cases/pixel_samplers.rs @@ -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() diff --git a/crates/metal2vulkan-conformance/src/cases/sampler_crossings.rs b/crates/metal2vulkan-conformance/src/cases/sampler_crossings.rs index 07073a350..54c82ce27 100644 --- a/crates/metal2vulkan-conformance/src/cases/sampler_crossings.rs +++ b/crates/metal2vulkan-conformance/src/cases/sampler_crossings.rs @@ -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 } diff --git a/crates/metal2vulkan-conformance/src/cases/sampler_filtering.rs b/crates/metal2vulkan-conformance/src/cases/sampler_filtering.rs index df89665d5..14250605f 100644 --- a/crates/metal2vulkan-conformance/src/cases/sampler_filtering.rs +++ b/crates/metal2vulkan-conformance/src/cases/sampler_filtering.rs @@ -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 } diff --git a/crates/metal2vulkan-conformance/src/device.rs b/crates/metal2vulkan-conformance/src/device.rs index f1d1aa1f6..06cd35c73 100644 --- a/crates/metal2vulkan-conformance/src/device.rs +++ b/crates/metal2vulkan-conformance/src/device.rs @@ -256,7 +256,7 @@ fn loader() -> Option { /// 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()); diff --git a/crates/metal2vulkan-runtime/src/astc.rs b/crates/metal2vulkan-runtime/src/astc.rs index c8678cf09..b1044e03a 100644 --- a/crates/metal2vulkan-runtime/src/astc.rs +++ b/crates/metal2vulkan-runtime/src/astc.rs @@ -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 diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 8bd74b3ec..825c0ae2d 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -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> { 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)) diff --git a/crates/metal2vulkan-runtime/src/etc.rs b/crates/metal2vulkan-runtime/src/etc.rs index 9ed9a9426..238b88b32 100644 --- a/crates/metal2vulkan-runtime/src/etc.rs +++ b/crates/metal2vulkan-runtime/src/etc.rs @@ -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 diff --git a/crates/metal2vulkan-runtime/src/tests/fitted_variant_notice.rs b/crates/metal2vulkan-runtime/src/tests/fitted_variant_notice.rs index c8709c912..3270b2ca5 100644 --- a/crates/metal2vulkan-runtime/src/tests/fitted_variant_notice.rs +++ b/crates/metal2vulkan-runtime/src/tests/fitted_variant_notice.rs @@ -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) { 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:?}" ); diff --git a/crates/metal2vulkan-runtime/src/tests/image_plan.rs b/crates/metal2vulkan-runtime/src/tests/image_plan.rs index 1f7df0e3c..bd92e501b 100644 --- a/crates/metal2vulkan-runtime/src/tests/image_plan.rs +++ b/crates/metal2vulkan-runtime/src/tests/image_plan.rs @@ -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")), diff --git a/crates/metal2vulkan-runtime/src/texture/decoded_twin.rs b/crates/metal2vulkan-runtime/src/texture/decoded_twin.rs index af7dc0644..3fa24a1be 100644 --- a/crates/metal2vulkan-runtime/src/texture/decoded_twin.rs +++ b/crates/metal2vulkan-runtime/src/texture/decoded_twin.rs @@ -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 { 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 { 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)) diff --git a/crates/metal2vulkan-validation/src/bin/corpus-draw-ab.rs b/crates/metal2vulkan-validation/src/bin/corpus-draw-ab.rs index 113995edf..89618b842 100644 --- a/crates/metal2vulkan-validation/src/bin/corpus-draw-ab.rs +++ b/crates/metal2vulkan-validation/src/bin/corpus-draw-ab.rs @@ -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) -> Result { 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" )) } } diff --git a/crates/metal2vulkan-validation/src/c3.rs b/crates/metal2vulkan-validation/src/c3.rs index 809d929d5..63a70d1ec 100644 --- a/crates/metal2vulkan-validation/src/c3.rs +++ b/crates/metal2vulkan-validation/src/c3.rs @@ -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 \ diff --git a/crates/metal2vulkan-validation/src/c3/tests.rs b/crates/metal2vulkan-validation/src/c3/tests.rs index 698170bd4..dac4d4b41 100644 --- a/crates/metal2vulkan-validation/src/c3/tests.rs +++ b/crates/metal2vulkan-validation/src/c3/tests.rs @@ -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] diff --git a/crates/metal2vulkan-validation/src/candidate.rs b/crates/metal2vulkan-validation/src/candidate.rs index e6d776b1f..f9523f8ad 100644 --- a/crates/metal2vulkan-validation/src/candidate.rs +++ b/crates/metal2vulkan-validation/src/candidate.rs @@ -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 diff --git a/crates/metal2vulkan-validation/src/candidate/runtime_case.rs b/crates/metal2vulkan-validation/src/candidate/runtime_case.rs index e3d4d0a04..4b6eb1743 100644 --- a/crates/metal2vulkan-validation/src/candidate/runtime_case.rs +++ b/crates/metal2vulkan-validation/src/candidate/runtime_case.rs @@ -628,12 +628,11 @@ pub fn executor_layer_settings() -> Vec { } /// 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 { 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()); diff --git a/crates/metal2vulkan-validation/src/observation_contract/comparison.rs b/crates/metal2vulkan-validation/src/observation_contract/comparison.rs index 9285856f4..14fc7cd6f 100644 --- a/crates/metal2vulkan-validation/src/observation_contract/comparison.rs +++ b/crates/metal2vulkan-validation/src/observation_contract/comparison.rs @@ -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 diff --git a/crates/metal2vulkan-validation/src/observation_contract/comparison/tests.rs b/crates/metal2vulkan-validation/src/observation_contract/comparison/tests.rs index c7f702964..8e37aab73 100644 --- a/crates/metal2vulkan-validation/src/observation_contract/comparison/tests.rs +++ b/crates/metal2vulkan-validation/src/observation_contract/comparison/tests.rs @@ -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, ] { diff --git a/crates/metal2vulkan-validation/src/runtime_lane/anisotropic_filter.rs b/crates/metal2vulkan-validation/src/runtime_lane/anisotropic_filter.rs index 0076d6bfb..e86db3f03 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/anisotropic_filter.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/anisotropic_filter.rs @@ -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 = 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), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/argument_linear_samples.rs b/crates/metal2vulkan-validation/src/runtime_lane/argument_linear_samples.rs index a6d66b7f3..a8bc728ab 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/argument_linear_samples.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/argument_linear_samples.rs @@ -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, diff --git a/crates/metal2vulkan-validation/src/runtime_lane/astc_textures.rs b/crates/metal2vulkan-validation/src/runtime_lane/astc_textures.rs index 8c2d41638..882fc335a 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/astc_textures.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/astc_textures.rs @@ -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 {}", diff --git a/crates/metal2vulkan-validation/src/runtime_lane/cubic_samplers.rs b/crates/metal2vulkan-validation/src/runtime_lane/cubic_samplers.rs index f3b66c9e4..f77513e79 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/cubic_samplers.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/cubic_samplers.rs @@ -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(); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs index 3081ab73d..92ed5a6c0 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs @@ -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, ] } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/depth_denormals.rs b/crates/metal2vulkan-validation/src/runtime_lane/depth_denormals.rs index 956a5cdcc..91908de23 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/depth_denormals.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/depth_denormals.rs @@ -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( diff --git a/crates/metal2vulkan-validation/src/runtime_lane/etc_textures.rs b/crates/metal2vulkan-validation/src/runtime_lane/etc_textures.rs index 3b51a6be5..43cd087c4 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/etc_textures.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/etc_textures.rs @@ -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); -} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/nearest_positions.rs b/crates/metal2vulkan-validation/src/runtime_lane/nearest_positions.rs index 15113aece..58f492ee3 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/nearest_positions.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/nearest_positions.rs @@ -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()); + }); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/runtime_data.rs b/crates/metal2vulkan-validation/src/runtime_lane/runtime_data.rs index 8353a98e1..5fd1a8aa6 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/runtime_data.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/runtime_data.rs @@ -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 { 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 ); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/ycbcr_textures.rs b/crates/metal2vulkan-validation/src/runtime_lane/ycbcr_textures.rs index 672b0f0bc..fc9d30453 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/ycbcr_textures.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/ycbcr_textures.rs @@ -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 diff --git a/crates/metal2vulkan/src/bind/graphics.rs b/crates/metal2vulkan/src/bind/graphics.rs index 7a9863b0c..044d0fc7b 100644 --- a/crates/metal2vulkan/src/bind/graphics.rs +++ b/crates/metal2vulkan/src/bind/graphics.rs @@ -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 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 = 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 diff --git a/crates/metal2vulkan/src/bind/plan/compute.rs b/crates/metal2vulkan/src/bind/plan/compute.rs index 4ca8b6b10..38de59853 100644 --- a/crates/metal2vulkan/src/bind/plan/compute.rs +++ b/crates/metal2vulkan/src/bind/plan/compute.rs @@ -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, -) -> std::collections::BTreeSet { - 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 diff --git a/crates/metal2vulkan/src/bind/plan/slots/tests.rs b/crates/metal2vulkan/src/bind/plan/slots/tests.rs index db29b8033..b7f1ce1b1 100644 --- a/crates/metal2vulkan/src/bind/plan/slots/tests.rs +++ b/crates/metal2vulkan/src/bind/plan/slots/tests.rs @@ -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 diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index d676b4d8d..d0c2eea3f 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -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, diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 7ed2a879b..a5f345ddf 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -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, - /// 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, /// 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() diff --git a/crates/metal2vulkan/src/cache/tests.rs b/crates/metal2vulkan/src/cache/tests.rs index 3c8a87cbf..500814cb3 100644 --- a/crates/metal2vulkan/src/cache/tests.rs +++ b/crates/metal2vulkan/src/cache/tests.rs @@ -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::(&encode(&feature)), Ok(feature)); for limit in [ @@ -469,8 +467,6 @@ fn the_version_178_members_round_trip() { ] { assert_eq!(decode::(&encode(&limit)), Ok(limit)); } - let note = PrecisionNote::DeviceGatherFootprint; - assert_eq!(decode::(&encode(¬e)), 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::(&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::(&encode(¬e)), 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::(&encode(¬e)), 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::(&encode(¬e)), 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::(&encode(¬e)), Ok(note)); -} - /// The member format version 219 appends encodes and decodes as itself: /// `PrecisionNote::ViewBaseTexelOffset`. #[test] diff --git a/crates/metal2vulkan/src/device/derive.rs b/crates/metal2vulkan/src/device/derive.rs index 3e36907d5..4889306ad 100644 --- a/crates/metal2vulkan/src/device/derive.rs +++ b/crates/metal2vulkan/src/device/derive.rs @@ -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, - policy: &DevicePolicy, -) -> BTreeSet { - 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, - policy: &DevicePolicy, -) -> EnabledCaps { +fn enabled_caps(desc: &DeviceDescription, deviations: &BTreeSet) -> 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) { diff --git a/crates/metal2vulkan/src/device/mechanism.rs b/crates/metal2vulkan/src/device/mechanism.rs index a79460c21..79e0db6e1 100644 --- a/crates/metal2vulkan/src/device/mechanism.rs +++ b/crates/metal2vulkan/src/device/mechanism.rs @@ -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, diff --git a/crates/metal2vulkan/src/device/mod.rs b/crates/metal2vulkan/src/device/mod.rs index e6bc4e1f7..a492e406a 100644 --- a/crates/metal2vulkan/src/device/mod.rs +++ b/crates/metal2vulkan/src/device/mod.rs @@ -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}; diff --git a/crates/metal2vulkan/src/device/policy.rs b/crates/metal2vulkan/src/device/policy.rs index 6cba750c4..5a9be03b9 100644 --- a/crates/metal2vulkan/src/device/policy.rs +++ b/crates/metal2vulkan/src/device/policy.rs @@ -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 diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index f739e912b..8aa0d28ee 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -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 diff --git a/crates/metal2vulkan/src/device/requirements.rs b/crates/metal2vulkan/src/device/requirements.rs index 0cc9769a3..d89882897 100644 --- a/crates/metal2vulkan/src/device/requirements.rs +++ b/crates/metal2vulkan/src/device/requirements.rs @@ -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, diff --git a/crates/metal2vulkan/src/device/tests/driver_facts.rs b/crates/metal2vulkan/src/device/tests/driver_facts.rs index c2b8cf251..41dca5590 100644 --- a/crates/metal2vulkan/src/device/tests/driver_facts.rs +++ b/crates/metal2vulkan/src/device/tests/driver_facts.rs @@ -189,15 +189,14 @@ fn taken(p: &crate::device::DeviceProfile) -> Vec /// 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 = 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!( diff --git a/crates/metal2vulkan/src/device/tests/mechanism.rs b/crates/metal2vulkan/src/device/tests/mechanism.rs index 935b944ba..9571c59d9 100644 --- a/crates/metal2vulkan/src/device/tests/mechanism.rs +++ b/crates/metal2vulkan/src/device/tests/mechanism.rs @@ -174,7 +174,6 @@ fn every_fact() -> Vec { 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 { 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 = 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 { .. } diff --git a/crates/metal2vulkan/src/device/tests/profile.rs b/crates/metal2vulkan/src/device/tests/profile.rs index 075d3690d..13f4e0924 100644 --- a/crates/metal2vulkan/src/device/tests/profile.rs +++ b/crates/metal2vulkan/src/device/tests/profile.rs @@ -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); diff --git a/crates/metal2vulkan/src/lower/access/mod.rs b/crates/metal2vulkan/src/lower/access/mod.rs index 716a83b81..ce213786e 100644 --- a/crates/metal2vulkan/src/lower/access/mod.rs +++ b/crates/metal2vulkan/src/lower/access/mod.rs @@ -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, - /// 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 { diff --git a/crates/metal2vulkan/src/lower/arith/tests.rs b/crates/metal2vulkan/src/lower/arith/tests.rs index c8cda8785..8be954862 100644 --- a/crates/metal2vulkan/src/lower/arith/tests.rs +++ b/crates/metal2vulkan/src/lower/arith/tests.rs @@ -3760,7 +3760,6 @@ mod blend_packed; mod color_write; mod divide; mod fast; -mod float_texel; mod fused; mod half_texel; mod libm; diff --git a/crates/metal2vulkan/src/lower/arith/tests/bicubic.rs b/crates/metal2vulkan/src/lower/arith/tests/bicubic.rs index dbb23aa43..28a1cca4f 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/bicubic.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/bicubic.rs @@ -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 { - 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 = 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 { - (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 { - 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 = 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 { - 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 = 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 diff --git a/crates/metal2vulkan/src/lower/arith/tests/float_texel.rs b/crates/metal2vulkan/src/lower/arith/tests/float_texel.rs deleted file mode 100644 index 6802b1b62..000000000 --- a/crates/metal2vulkan/src/lower/arith/tests/float_texel.rs +++ /dev/null @@ -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 { - 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 = 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 { - 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 = (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 = pairs.iter().copied().collect(); - let texels = quads(&pairs.iter().map(|p| p.0).collect::>()); - 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> = (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::(|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> = (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 = pairs.iter().copied().collect(); - run( - &format!("{p:?} channel {ch}"), - class, - TexelLanes::Gathered(ch), - &quads(&pairs.iter().map(|p| p.0).collect::>()), - &|_, 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 = (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 = (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}"); -} diff --git a/crates/metal2vulkan/src/lower/sampler/anisotropic.rs b/crates/metal2vulkan/src/lower/sampler/anisotropic.rs index 0f78ad5e1..adbd19d77 100644 --- a/crates/metal2vulkan/src/lower/sampler/anisotropic.rs +++ b/crates/metal2vulkan/src/lower/sampler/anisotropic.rs @@ -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, 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 { diff --git a/crates/metal2vulkan/src/lower/sampler/anisotropic/tests.rs b/crates/metal2vulkan/src/lower/sampler/anisotropic/tests.rs index 21e72889f..696c4d236 100644 --- a/crates/metal2vulkan/src/lower/sampler/anisotropic/tests.rs +++ b/crates/metal2vulkan/src/lower/sampler/anisotropic/tests.rs @@ -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 { @@ -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(¬e), "{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(¬e), - "{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 + ); + } } } } diff --git a/crates/metal2vulkan/src/lower/sampler/bicubic.rs b/crates/metal2vulkan/src/lower/sampler/bicubic.rs index 998d60a78..f3b23258a 100644 --- a/crates/metal2vulkan/src/lower/sampler/bicubic.rs +++ b/crates/metal2vulkan/src/lower/sampler/bicubic.rs @@ -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<'_>, diff --git a/crates/metal2vulkan/src/lower/sampler/bicubic/routines.rs b/crates/metal2vulkan/src/lower/sampler/bicubic/routines.rs index 400354bc9..a3404d709 100644 --- a/crates/metal2vulkan/src/lower/sampler/bicubic/routines.rs +++ b/crates/metal2vulkan/src/lower/sampler/bicubic/routines.rs @@ -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 { }) } -/// 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 { - 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 { /// [`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 { - 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 { /// (`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, 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 { - 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 { 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 { - 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) -} diff --git a/crates/metal2vulkan/src/lower/sampler/compared.rs b/crates/metal2vulkan/src/lower/sampler/compared.rs deleted file mode 100644 index 2c1e30924..000000000 --- a/crates/metal2vulkan/src/lower/sampler/compared.rs +++ /dev/null @@ -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, - /// 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, -} - -/// 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 { - 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 { - 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 { - 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, -) -> Result<(SampleOp, Option), 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, -) -> BResult { - 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 { - 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, - filtered: ArmFn<'a, EmitCx<'e>>, -) -> BResult { - 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 { - 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, -) -> BResult { - 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 { - 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 { - 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, -) -> BResult { - 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 { - 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 { - 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), - bits: Bits, -) -> BResult { - 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 { - 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) -} diff --git a/crates/metal2vulkan/src/lower/sampler/emit.rs b/crates/metal2vulkan/src/lower/sampler/emit.rs index 16a47c2a2..54ab3db11 100644 --- a/crates/metal2vulkan/src/lower/sampler/emit.rs +++ b/crates/metal2vulkan/src/lower/sampler/emit.rs @@ -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, bool), + (plane, grad, unshared): (SValue, Option<(SValue, SValue)>, bool), (lod, min_lod, offset, dref): (&Lod, Option, &Option, Option), ) -> BResult<(ImageOperands, Option, 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, - ops: ImageOperands, - beyond: Beyond, -) -> impl Fn(&mut FunctionBuilder<'_>, SValue) -> BResult { - 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, Option)> { - 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 { @@ -2324,23 +1990,6 @@ pub(super) fn word_pixel(s: &Sampling) -> Option { } } -/// 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 { - 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)?, }) } diff --git a/crates/metal2vulkan/src/lower/sampler/face.rs b/crates/metal2vulkan/src/lower/sampler/face.rs index 3417b2fba..d8fa019c1 100644 --- a/crates/metal2vulkan/src/lower/sampler/face.rs +++ b/crates/metal2vulkan/src/lower/sampler/face.rs @@ -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 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, t: Option) -> 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, Option)> { - if let Wraps::Axes(FaceWrap { s: false, t: false }) = wrap { - return Ok((None, None)); - } - let u = |fb: &mut FunctionBuilder<'_>, v: u32| -> BResult { - 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 { - // 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 { - 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 { - 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| - -> BResult { - 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 { - 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 { - 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 { - 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 { - 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), -) -> BResult { - 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 { - 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 { - let c = fb.u32_const(v)?; - fb.module().const_value(c) - }; - let ic = |fb: &mut FunctionBuilder<'_>, v: i32| -> BResult { - 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 { - 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 { - 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 { - 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; diff --git a/crates/metal2vulkan/src/lower/sampler/face/tests.rs b/crates/metal2vulkan/src/lower/sampler/face/tests.rs index 01141faad..6aedd41c8 100644 --- a/crates/metal2vulkan/src/lower/sampler/face/tests.rs +++ b/crates/metal2vulkan/src/lower/sampler/face/tests.rs @@ -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; diff --git a/crates/metal2vulkan/src/lower/sampler/face/tests/fold.rs b/crates/metal2vulkan/src/lower/sampler/face/tests/fold.rs deleted file mode 100644 index 88e5f1f01..000000000 --- a/crates/metal2vulkan/src/lower/sampler/face/tests/fold.rs +++ /dev/null @@ -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" - ); -} diff --git a/crates/metal2vulkan/src/lower/sampler/face/tests/routines.rs b/crates/metal2vulkan/src/lower/sampler/face/tests/routines.rs index 4543c5019..2141f7d3d 100644 --- a/crates/metal2vulkan/src/lower/sampler/face/tests/routines.rs +++ b/crates/metal2vulkan/src/lower/sampler/face/tests/routines.rs @@ -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 { 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!( diff --git a/crates/metal2vulkan/src/lower/sampler/face/tests/snap.rs b/crates/metal2vulkan/src/lower/sampler/face/tests/snap.rs deleted file mode 100644 index 7dd58af6b..000000000 --- a/crates/metal2vulkan/src/lower/sampler/face/tests/snap.rs +++ /dev/null @@ -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 { - 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 = 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 = (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"), - } - } - } -} diff --git a/crates/metal2vulkan/src/lower/sampler/fetched.rs b/crates/metal2vulkan/src/lower/sampler/fetched.rs index 8286c19cb..46c8c09d6 100644 --- a/crates/metal2vulkan/src/lower/sampler/fetched.rs +++ b/crates/metal2vulkan/src/lower/sampler/fetched.rs @@ -1,94 +1,52 @@ -//! Texels the shader fetches itself where Metal's footprint and level are known: the one path for a -//! comparison's depths ([`super::compared`]) and for a plain gather's or nearest sample's texels +//! A `half` gather's texels the shader fetches itself, where Metal's footprint is known //! ([`Plain`]). //! -//! **Why.** A device's sample or gather may read a texel otherwise than its fetch does: a denormal -//! `R32_SFLOAT` texel (a 32-bit float format's) reads as zero of its sign in -//! - RADV's gathers and nearest samples; -//! - NVIDIA's gathers; -//! - ANV's nearest samples; +//! **Why.** Under the NaN switch Metal's gather hands back a 16-bit float texel's own NaN; a +//! device's gather need not (NVIDIA's hands back every NaN as `0x7fffffff`), and its fetch does +//! where its read does ([`half_gather`]). //! -//! and `OpImageFetch` and `OpImageRead` keep it on RADV, ANV, NVIDIA and lavapipe -//! (`runtime_lane::depth_compares`). Metal's sample and gather keep it. +//! **How.** The shader fetches a gather's four taps at Metal's quantized position +//! (`TapBase::Quantized`) of the base level, in gather order (`texels`), through +//! `bicubic::footprint`. Each tap is addressed as the sampler's axes say, and a border axis's +//! outside tap reads the border color as the bound format holds it: a constexpr sampler's +//! addressing is the function's own ([`FetchAddress::Modes`]), a runtime sampler's its slot's +//! word's, read in the function ([`FetchAddress::Word`]), and an argument buffer's sampler's its +//! table entry's word's ([`FetchAddress::Entry`]). The fetch sits behind the slot's `TexelFormat` +//! specialization (`branch`): the half-float class takes the fetches, and any other the device's +//! own gather. A heap texture's gather fetches where the class its handle carries is the +//! half-float one ([`heap`]), after the device's access. An arm of a switch-at-use keeps the +//! device's read through a word, so its arms share one emulation. //! -//! **How.** Where Metal's footprint and level are known (`plan`), the shader fetches the texels -//! through `bicubic::footprint`: -//! - a gather's four taps at Metal's quantized position (`TapBase::Quantized`) of the base level, -//! in gather order (`texels`); -//! - a nearest sample's texel `floor(x)` (`TapBase::Floor`) of the level Metal reads, on each of -//! its one, two or three plane axes. -//! -//! Each tap is addressed as the sampler's axes say, and a border axis's outside tap reads the -//! border color as the bound format holds it: a constexpr sampler's addressing is the function's -//! own ([`FetchAddress::Modes`]), a runtime sampler's its slot's word's, read in the function -//! ([`FetchAddress::Word`]), and an argument buffer's sampler's its table entry's word's -//! ([`FetchAddress::Entry`]). The fetch sits behind the slot's `TexelFormat` specialization -//! (`branch`): the format classes the caller names take the fetches, and any other the device's own -//! read. A comparison names every class whose border texel is measured; a plain sample or gather -//! the 32-bit float class alone, the only one whose texels a device's sample reads otherwise than -//! its fetch. A heap texture's comparison fetches by the depth class its handle carries instead -//! (`compared::heap`). A sample's fetch arm of a 32-bit float texture through a combined binding is -//! its shape's sampling routine (`sampler::routine`), defined once in the module and called by -//! every sample of the shape with the coordinate, the layer, and the level's operand; a gather's -//! fetches and a blend of two levels stay inline. -//! -//! **The level** is known for: -//! - a gather (the base level); -//! - a sampler without a mip filter (level 0), an implicit level's in a fragment function -//! included; -//! - under a nearest mip filter, a kernel's level or bias that snaps, or a level known when the -//! function compiles: `floor` of the level handed to the device, clamped into the texture's -//! levels; -//! - through a runtime or argument buffer's sampler, a level or a kernel's bias (or neither, level -//! 0): the level its word reads ([`FetchLevel::Word`]), which the caller fetches where the word -//! states a sampler that reads one texel (`compared::runtime_sample`, `compared::heap`). -//! -//! **Through a word, and of a heap texture**: a plain gather or sample through a runtime sampler -//! slot is addressed by the slot's word ([`FetchAddress::Word`]), and a sample fetches only where -//! the word states one texel ([`word_reach`]), the device's sample elsewhere. A heap texture's -//! gather and sample, through a word ([`FetchAddress::Entry`] for an argument buffer's sampler) or -//! a constexpr sampler, fetch where the class its handle carries is the 32-bit float one -//! ([`heap`]), after the device's access. An arm of a switch-at-use keeps the device's read through -//! a word, so its arms share one emulation. -//! -//! **The device reads the texels** elsewhere, and the module records -//! `PrecisionNote::DeviceTexelDenormals` for them (`sampler::select`): -//! - an implicit level or gradients under a nearest mip filter in a fragment function; -//! - a filtered sample that no emulation reaches, a word's that filters included; -//! - a `min_lod_clamp` or a dynamic offset; -//! - an observed residency, a raw sRGB view, a cube, a switch-at-use's arm through a word. +//! **The device reads the texels** elsewhere: a dynamic offset, an observed residency, a raw sRGB +//! view. -use crate::air::abi::{AddressMode, Coordinates, Filter, MipFilter}; +use crate::air::abi::Coordinates; use crate::air::intrinsics::{ImageDim, ImageShape}; -use crate::air::ir::{Const, ValueId}; use crate::error::Error; use crate::lower::emit::EmitCx; use crate::lower::select::SelectCx; -use crate::lower::texture::{ImageRef, OffsetBase, TexelClass, TexelConv, TexelForm}; +use crate::lower::texture::{ImageRef, TexelConv, TexelForm}; use crate::metal::bicubic::BicubicTexels; use crate::pipeline::sym::SamplerRef; use crate::spirv::builder::constructs::{ArmEnd, ArmFn, Merged}; -use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; +use crate::spirv::builder::FunctionBuilder; use crate::spirv::error::BResult; -use crate::spirv::ids::{ConstId, FuncId, TypeId, Value as SValue}; -use crate::spirv::ir::{BinOp, Constant, ConvOp, GlslOp, ImageQuery, Type as SType}; +use crate::spirv::ids::Value as SValue; +use crate::spirv::ir::Constant; use super::bicubic::{ - flag, footprint_from, footprint_on, missing_routine, scalar, value, Addressing, At, Bits, - Footprint, Tap, TapAddress, TapBase, Taps, Texels, Tys, + flag, footprint_from, footprint_on, value, Addressing, At, Bits, Footprint, Tap, TapAddress, + TapBase, Taps, Texels, Tys, }; -use super::level::LevelSnap; use super::linear::LinearImage; -use super::routine::{Fetched, Level, Shape}; -use super::{BindingKey, CombinedImage, Lod, Offset, Pixel, SampleOp, Sampling, Source}; +use super::{BindingKey, CombinedImage, Offset, Pixel, SampleOp, Sampling, Source}; -/// How the shader fetches the texels of a sample or gather (module docs): how its taps are -/// addressed, Metal's constant texel offset, and the level. +/// How the shader fetches the texels of a gather (module docs): how its taps are addressed, and +/// Metal's constant texel offset. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct Fetch { pub address: FetchAddress, pub offset: Option>, - pub level: FetchLevel, } /// How a fetch addresses its taps (`bicubic::Addressing`). @@ -111,31 +69,9 @@ pub enum FetchAddress { Entry { axes: u8 }, } -/// The level the texels are fetched from. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum FetchLevel { - /// A level known when the function compiles, clamped into the texture's levels. - Fixed(u32), - /// `floor` of the level the sample's level snap hands the device (`Sampling::level`), for the - /// sample's level or bias operand, clamped into the texture's levels. - Snapped(ValueId), - /// The level a runtime or argument buffer's sampler's word reads at the sample's level or a - /// kernel's bias (`None`: level 0), clamped into the texture's levels (`level::word_level`): - /// under a nearest mip filter the level Metal's rule reads, clamped into the levels the word's - /// level clamp leaves; level 0 without a mip filter. Metal reads a comparison's level through - /// such a sampler as a sample's. - Word(Option), - /// A linear mip filter's two levels (`compared::blended`): of the level the constexpr sampler's - /// snap hands the device for the sample's level or a kernel's bias (`None`: level 0), clamped - /// into the texture's levels, `L + q`, levels `L` and `L + 1`, whose comparisons blend by `1 - - /// q` and `q`. - Blend(LevelSnap, Option), -} - /// The estimated words of a fetch's footprint beyond its taps: the size query, each of two axes' /// position ([`super::position::POSITION_WORDS`]) and base, the layer's clamp, the border texel, -/// the format's branch and the device's arm, and the level (the levels query, a snapped level's -/// floor and clamp). +/// and the format's branch and the device's arm. pub(super) const FETCH_WORDS: u32 = 2 * super::position::POSITION_WORDS + 320; /// The estimated words of one fetched tap: its index under its addressing on each axis, the fetch, @@ -143,23 +79,17 @@ pub(super) const FETCH_WORDS: u32 = 2 * super::position::POSITION_WORDS + 320; pub(super) const FETCH_TAP_WORDS: u32 = 96; impl Fetch { - /// The estimated words of fetching the texels of `op`: the footprint and each tap (a snapped - /// level's own words are its snap's, `level::LEVEL_WORDS`; a word's level is counted here, - /// within as many), and for a runtime sampler's word the word's tests and each axis's position - /// and taps under every mode, as a linear emulation's (`linear::WORD_WORDS`), and Metal's - /// offset rule on each axis a constant offset moves (`position::OFFSET_RULE_WORDS`). - pub fn words(&self, op: &SampleOp) -> u32 { - let (taps, span) = match op { - SampleOp::Gather { .. } => (4, 2), - _ => (1, 1), - }; + /// The estimated words of fetching a gather's four texels: the footprint and each tap, and for + /// a runtime sampler's word the word's tests and each axis's position and taps under every + /// mode (`linear::WORD_WORDS`), and Metal's offset rule on each axis a constant offset moves + /// (`position::OFFSET_RULE_WORDS`). + pub fn words(&self) -> u32 { let word = match &self.address { FetchAddress::Modes { .. } => 0, FetchAddress::Word { axes, .. } | FetchAddress::Entry { axes } => { super::linear::WORD_WORDS + u32::from(*axes) - * (super::position::MODE_POSITION_WORDS - + span * super::linear::WORD_TAP_WORDS) + * (super::position::MODE_POSITION_WORDS + 2 * super::linear::WORD_TAP_WORDS) } }; let offset = self @@ -167,454 +97,13 @@ impl Fetch { .as_deref() .map_or(0, |o| o.iter().filter(|o| **o != 0).count() as u32) * super::position::OFFSET_RULE_WORDS; - let level = match self.level { - FetchLevel::Word(_) => super::level::LEVEL_WORDS, - // The second level's taps and the blend's arithmetic. - FetchLevel::Blend(..) => super::level::LEVEL_WORDS + taps * FETCH_TAP_WORDS + 64, - FetchLevel::Fixed(_) | FetchLevel::Snapped(_) => 0, - }; - FETCH_WORDS + taps * FETCH_TAP_WORDS + word + offset + level - } -} - -/// A plain gather or nearest sample whose texels the shader fetches (module docs): where its -/// texel class is read (a texture slot's `TexelFormat` specialization, or the class a heap -/// texture's handle carries), and how the fetches are made. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub struct Plain { - pub image: LinearImage, - pub fetch: Fetch, -} - -/// The estimated words of a sample's test that its word states one texel ([`word_reach`]): the -/// filter mask and test, the mip filter's field and its tests, with their constants. -const REACH_WORDS: u32 = 64; - -impl Plain { - /// The estimated words of fetching the texels of `op` ([`Fetch::words`]), a sample's test of - /// its word ([`word_reach`]), and a heap texture's class from its handle, its element loaded - /// again in the fetch's arm, an argument buffer's sampler's word from its entry, and the branch - /// (`linear::HEAP_WORDS`). - pub fn words(&self, op: &SampleOp) -> u32 { - let reach = match (&self.fetch.address, op) { - (FetchAddress::Modes { .. }, _) | (_, SampleOp::Gather { .. }) => 0, - _ => REACH_WORDS, - }; - let heap = match (self.image, &self.fetch.address) { - (LinearImage::Slot(_), _) => 0, - (LinearImage::Heap, FetchAddress::Entry { .. }) => { - super::linear::HEAP_WORDS + crate::memory::handles::ENTRY_FIELD_WORDS - } - (LinearImage::Heap, _) => super::linear::HEAP_WORDS, - }; - self.fetch.words(op) + reach + heap + FETCH_WORDS + 4 * FETCH_TAP_WORDS + word + offset } - /// Whether the shader fetches every texel of `op` the device would read where the class is a - /// 32-bit float one: a gather's, and a sample's through a constexpr sampler, always; a - /// sample's through a runtime or argument buffer's sampler only where its word states one - /// texel ([`word_reach`]), the device's sample elsewhere. - pub fn fetches_every_texel(&self, op: &SampleOp) -> bool { - matches!(op, SampleOp::Gather { .. }) - || matches!(self.fetch.address, FetchAddress::Modes { .. }) - } -} - -/// The fetch of `op`, a gather or a sample without comparison with texel form `form`, of `image` -/// (shape `shape`) through `stat` (or, where `argument`, its argument buffer's sampler), on a -/// device without `VkProperty::MetalSampler` (module docs): a `float` result, a gather of a 2D -/// texture or array, or a sample of a 1D, 2D or 3D texture or array, where its footprint is -/// known: through a constexpr sampler that reads one texel, where [`plan`] knows its level; -/// through a runtime or argument buffer's sampler, addressed by its word ([`plan_word`]), the -/// shader fetching a sample's texel only where the word states one texel ([`word_reach`]). A -/// heap texture's fetch reads the class its handle carries. `operand` is the call's level or bias -/// operand. A device with the property reads the texels by Metal's own sampler, as an unfiltered -/// sample requires nothing of it (`linear::select`) and a gather's snap none (`position::plan`). -pub(super) fn select( - cx: &mut SelectCx<'_>, - op: &SampleOp, - form: Option, - (stat, argument): (Option<(SamplerRef, Coordinates)>, bool), - (image, shape): (ImageRef, ImageShape), - operand: Option, -) -> Result, Error> { - if form.map(|f| f.conv) != Some(TexelConv::F32) { - return Ok(None); - } - let gather = match op { - SampleOp::Gather { dref: None, .. } => true, - SampleOp::Sample { dref: None, .. } => false, - _ => return Ok(None), - }; - let axes: u8 = match shape.dim { - _ if shape.ms => return Ok(None), - ImageDim::D2 => 2, - ImageDim::D1 if !gather => 1, - ImageDim::D3 if !gather => 3, - _ => return Ok(None), - }; - if cx.profile.device_samples() { - cx.families.sampler.device_sampling = true; - return Ok(None); - } - let fetch = match (stat.map(|(r, _)| r), argument) { - (Some(SamplerRef::Constexpr(words)), _) => { - let s = super::state_of(words)?; - if !gather && !super::linear::unfiltered(&s) { - return Ok(None); - } - let modes: Vec = [s.address_s, s.address_t, s.address_r] - .into_iter() - .take(usize::from(axes)) - .collect(); - plan(cx, op, &s, &modes, operand)? - } - (Some(SamplerRef::Slot(sampler)), _) => plan_word(op, FetchAddress::Word { sampler, axes }), - (None, true) => plan_word(op, FetchAddress::Entry { axes }), - (None, false) => None, - }; - let image = match image { - ImageRef::Slot(n) => LinearImage::Slot(n), - ImageRef::Heap { .. } => LinearImage::Heap, - }; - cx.families.access.heap_class |= fetch.is_some() && image == LinearImage::Heap; - Ok(fetch.map(|fetch| Plain { image, fetch })) -} - -/// The format classes (`BicubicTexels` bits) whose texels the shader fetches for a plain access: -/// the 32-bit float class. -pub(super) const CLASSES: u32 = BicubicTexels::LINEAR; - -/// How the shader fetches the texels of `op` (a gather, a sample through a sampler that reads one -/// texel, its comparison taken out, or a comparison through nearest filters under a linear mip -/// filter, [`FetchLevel::Blend`]) through constexpr sampler `s` on the plane axes of `modes`, or -/// `None` where the device reads them (module docs). `operand` is the call's level or bias -/// operand. -pub(super) fn plan( - cx: &mut SelectCx<'_>, - op: &SampleOp, - s: &crate::air::abi::SamplerState, - modes: &[crate::air::abi::AddressMode], - operand: Option, -) -> Result, Error> { - let border = s.border_color; - let constant = |offset: &Option| match offset { - None => Some(None), - Some(Offset::Const(k)) => Some(Some(k.clone())), - Some(Offset::Dynamic(..)) => None, - }; - let (offset, level) = match op { - SampleOp::Gather { offset, .. } => match constant(offset) { - Some(o) => (o, FetchLevel::Fixed(0)), - None => return Ok(None), - }, - SampleOp::Sample { - lod, - min_lod: None, - offset, - .. - } => { - let Some(o) = constant(offset) else { - return Ok(None); - }; - let level = match (s.mip_filter, lod) { - (MipFilter::None, _) => FetchLevel::Fixed(0), - // A linear mip filter's two levels, read by a comparison through nearest filters - // (`compared::blended`). - (MipFilter::Linear, Lod::Level(v) | Lod::Base { bias: v, min: None }) - if s.min_filter == Filter::Nearest - && s.mag_filter == Filter::Nearest - && s.max_anisotropy <= 1 => - { - match LevelSnap::plan(s) { - Some(snap) => FetchLevel::Blend(snap, *v), - None => return Ok(None), - } - } - (MipFilter::Nearest, Lod::Level(None)) => match LevelSnap::plan(s) { - Some(snap) => FetchLevel::Fixed(snap.of(0.0) as u32), - None => return Ok(None), - }, - ( - MipFilter::Nearest, - Lod::Level(Some(v)) - | Lod::Base { - bias: Some(v), - min: None, - }, - ) => { - let Some(snap) = LevelSnap::plan(s) else { - return Ok(None); - }; - match operand.and_then(|o| super::select::konst(cx, o)) { - Some(Const::Null) => FetchLevel::Fixed(snap.of(0.0) as u32), - Some(Const::Float(bits)) => { - FetchLevel::Fixed(snap.of(f32::from_bits(*bits as u32)) as u32) - } - _ => FetchLevel::Snapped(*v), - } - } - _ => return Ok(None), - }; - (o, level) - } - _ => return Ok(None), - }; - Ok(Some(Fetch { - address: FetchAddress::Modes { - address: modes - .iter() - .copied() - .map(super::position::address) - .collect(), - border, - pixel: s.coordinates == Coordinates::Pixel, - }, - offset, - level, - })) -} - -/// How the shader fetches the texels of `op` addressed by a sampler's word (`address`, a -/// [`FetchAddress::Word`] or [`FetchAddress::Entry`]): a gather's four taps of the base level; a -/// sample's one texel of the level the word reads at its level or a kernel's bias, or at level 0 -/// without either ([`FetchLevel::Word`]), which the caller fetches where the word states a sampler -/// that reads one texel; else (an implicit level or gradients) of level 0, which the caller fetches -/// only where the word states no mip filter (`compared::runtime_sample`, `compared::heap`). `None` -/// for a dynamic offset or a `min_lod_clamp`, whose texels the device reads. -pub(super) fn plan_word(op: &SampleOp, address: FetchAddress) -> Option { - let (offset, level) = match op { - SampleOp::Gather { offset, .. } => (offset, FetchLevel::Fixed(0)), - SampleOp::Sample { - lod, - min_lod: None, - offset, - .. - } => match lod { - Lod::Level(v) | Lod::Base { bias: v, min: None } => (offset, FetchLevel::Word(*v)), - _ => (offset, FetchLevel::Fixed(0)), - }, - _ => return None, - }; - let offset = match offset { - None => None, - Some(Offset::Const(k)) => Some(k.clone()), - Some(Offset::Dynamic(..)) => return None, - }; - Some(Fetch { - address, - offset, - level, - }) -} - -/// The value of `s` from the texels fetched as `f` says through combined binding `key` (one -/// without comparison), where the slot `texture`'s `TexelFormat` specialization states one of the -/// format classes `classes` (`BicubicTexels` bits) and, where `reached`, a runtime sampler's word -/// states a sampler whose sample reads the texel fetched ([`word_reach`]): `fetched` makes it of -/// [`texels`]' texels. Elsewhere `device`'s access of the binding's sampled image makes it. Each -/// arm makes the sampled image it reads, so once a device specializes the module the other arm -/// is dead. -pub(super) fn branch( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - (s, key): (&Sampling, BindingKey), - (texture, f, classes, reached): (u32, &Fetch, u32, bool), - image: CombinedImage, - fetched: &dyn Fn(&mut FunctionBuilder<'_>, &[SValue]) -> BResult, - device: &dyn Fn(&mut FunctionBuilder<'_>, SValue) -> BResult, -) -> BResult { - 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"))); - }; - // A runtime sampler's word, which addresses its taps. - let word = match &f.address { - FetchAddress::Word { sampler, .. } => { - Some(super::emit::sampler_word(cx, fb, Pixel::Spec(*sampler))?) - } - FetchAddress::Modes { .. } => None, - FetchAddress::Entry { .. } => { - return Err(cx.fail("a slot's fetch addressed by an argument buffer's sampler")) - } - }; - let t = Tys::new(fb)?; - let measured = flag(fb, &t, spec, classes)?; - let measured = match (reached, word) { - (true, Some(w)) => match word_reach(fb, &t, s, f, w)? { - Some(r) => fb.binary(BinOp::LogicalAnd, measured, r)?, - None => measured, - }, - _ => measured, - }; - // A sample's one texel is fetched by its shape's routine, called with the sample's plain - // data (`routine::Fetched`); a gather's four, and a blend's two levels, inline. - let routed = match (Fetched::of(s, key, texture, f), image.texel) { - (Some(shape), TexelClass::Float) => { - Some(fetch_routine(cx, fb, s, shape, f, (image, spec))?) - } - _ => None, - }; - let t = &t; - let fetch: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| { - let x = match &routed { - Some((r, args)) => { - let x = fb.call(*r, args)?.ok_or_else(missing_routine)?; - fetched(fb, &[x])? - } - None => { - let si = binding.sampled_image(fb)?; - let level = 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 fetch without its word")); - }; - let x = texels(cx, fb, t, s, (si, image), Bits::Spec(spec), &taps)?; - fetched(fb, &x)? - } - }; - Ok(ArmEnd::FallThrough(vec![x])) - }); - let read: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, _| { - let si = binding.sampled_image(fb)?; - let x = device(fb, si)?; - Ok(ArmEnd::FallThrough(vec![x])) - }); - let Merged(merged) = fb.if_(cx, measured, fetch, Some(read))?; - match merged[..] { - [x] => Ok(x), - _ => Err(cx.fail("fetched texels' branch without its value")), - } -} - -/// Where a sample's fetch addressed by sampler word `word` (a `u32`) reads the texel Metal's -/// sample reads (a `bool`): the word states a sampler that reads one texel (nearest minification -/// and magnification, no linear mip filter, not anisotropic) and, but where the fetch reads the -/// level the word reads ([`FetchLevel::Word`]: a level or a kernel's bias), no mip filter. `None` -/// for a gather, whose four taps are Metal's whatever the word's filters. -fn word_reach( - fb: &mut FunctionBuilder<'_>, - t: &Tys, - s: &Sampling, - f: &Fetch, - word: SValue, -) -> BResult> { - if !matches!(s.op, SampleOp::Sample { .. }) { - return Ok(None); - } - let (one, mip) = super::compared::one_texel(fb, t, word)?; - if matches!(f.level, FetchLevel::Word(_)) { - return Ok(Some(one)); - } - let zero = scalar(fb, t.u32_, 0)?; - let zero = value(fb, zero)?; - let unmipped = fb.binary(BinOp::IEqual, mip, zero)?; - Ok(Some(fb.binary(BinOp::LogicalAnd, one, unmipped)?)) -} - -/// The value of plain fetch `p` of heap texture sampling `s` (image facts `image`): `device`, the -/// device's access already made, in uniform control flow; and where the class the texture's handle -/// carries is the 32-bit float one and, for a sample through a runtime or argument buffer's -/// sampler, its word states one texel ([`word_reach`]), the texel or a gather's component of the -/// four the shader fetches from the element as a slot of that class would ([`texels`]). The fetch -/// arm holds fetches alone, so a divergent handle puts no sample in divergent flow. -pub(super) fn heap( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - s: &Sampling, - image: CombinedImage, - p: &Plain, - device: SValue, -) -> BResult { - let handle = match s.source { - Source::Heap { handle, .. } | Source::HeapSampler { handle, .. } => handle, - Source::Combined(_) => return Err(cx.fail("a heap texture's fetch of a slot")), - }; - let t = Tys::new(fb)?; - let h = cx.operand(fb, handle)?; - let bits = Bits::Value(crate::lower::texture::heap_texel_class(cx, fb, h)?); - let word = match (&p.fetch.address, super::emit::word_pixel(s)) { - (FetchAddress::Modes { .. }, _) => None, - (_, Some(pixel)) => Some(super::emit::sampler_word(cx, fb, pixel)?), - (_, None) => return Err(cx.fail("a word-addressed heap fetch without its word")), - }; - let take = bits.test(fb, &t, CLASSES)?; - let take = match word { - Some(w) => match word_reach(fb, &t, s, &p.fetch, w)? { - Some(r) => fb.binary(BinOp::LogicalAnd, take, r)?, - None => take, - }, - None => take, - }; - let t = &t; - let fetch: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| { - let (si, _, _) = super::emit::sampled_image(cx, fb, s.source)?; - let level = level(cx, fb, t, s, (p.fetch.level, word), si)?; - let Some(taps) = p.fetch.taps(s, level, word) else { - return Err(cx.fail("a word-addressed heap fetch without its word")); - }; - let x = texels(cx, fb, t, s, (si, image), bits, &taps)?; - Ok(ArmEnd::FallThrough(vec![plain_value(fb, s, &x)?])) - }); - let kept: ArmFn<'_, EmitCx<'_>> = Box::new(move |_, _| Ok(ArmEnd::FallThrough(vec![device]))); - let Merged(merged) = fb.if_(cx, take, fetch, Some(kept))?; - match merged[..] { - [x] => Ok(x), - _ => Err(cx.fail("a heap texture's fetch without its texel")), - } -} - -/// The value of plain access `s` of its fetched `texels`, as the device's access returns it: a -/// gather's component of each of its four (a `vec4`), a sample's one texel, a depth texture's its -/// first component. -pub(super) fn plain_value( - fb: &mut FunctionBuilder<'_>, - s: &Sampling, - texels: &[SValue], -) -> BResult { - match s.op { - SampleOp::Gather { component, .. } => { - let vec4 = Tys::new(fb)?.vec4; - let mut parts = Vec::with_capacity(texels.len()); - for &texel in texels { - parts.push(fb.composite_extract(texel, &[component])?); - } - fb.composite_construct(vec4, &parts) - } - _ => { - let x = one(fb, texels)?; - match s.depth { - true => fb.composite_extract(x, &[0]), - false => Ok(x), - } - } - } -} - -impl Fetch { - /// The taps of `s` fetched as `self` says from level `level` (`None`: the base level), a - /// runtime sampler's addressed by its word `word` (a `u32`): a gather's footprint of two taps - /// per axis from Metal's quantized position, or a nearest sample's one from `floor` of its - /// position. `None` for a word-addressed fetch without its word. - pub(super) fn taps<'a>( - &'a self, - s: &Sampling, - level: Option, - word: Option, - ) -> Option> { - self.taps_of(matches!(s.op, SampleOp::Gather { .. }), level, word) - } - - /// [`taps`](Self::taps) of a gather where `gather`, else of a sample. - fn taps_of( - &self, - gather: bool, - level: Option, - word: Option, - ) -> Option> { + /// The taps of a gather fetched as `self` says from the base level, a runtime sampler's + /// addressed by its word `word` (a `u32`): a footprint of two taps per axis from Metal's + /// quantized position. `None` for a word-addressed fetch without its word. + pub(super) fn taps(&self, word: Option) -> Option> { let addressing = match (&self.address, word) { ( FetchAddress::Modes { @@ -639,17 +128,223 @@ impl Fetch { Some(Taps { addressing, offset: self.offset.as_deref(), - span: if gather { &[0, 1] } else { &[0] }, - base: if gather { - TapBase::Quantized - } else { - TapBase::Floor - }, - level, + span: &[0, 1], + base: TapBase::Quantized, + level: None, }) } } +/// A `half` gather whose texels the shader fetches (module docs): where its texel class is read +/// (a texture slot's `TexelFormat` specialization, or the class a heap texture's handle carries), +/// and how the fetches are made. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Plain { + pub image: LinearImage, + pub fetch: Fetch, +} + +impl Plain { + /// The estimated words of fetching the texels ([`Fetch::words`]), and a heap texture's class + /// from its handle, its element loaded again in the fetch's arm, an argument buffer's sampler's + /// word from its entry, and the branch (`linear::HEAP_WORDS`). + pub fn words(&self) -> u32 { + let heap = match (self.image, &self.fetch.address) { + (LinearImage::Slot(_), _) => 0, + (LinearImage::Heap, FetchAddress::Entry { .. }) => { + super::linear::HEAP_WORDS + crate::memory::handles::ENTRY_FIELD_WORDS + } + (LinearImage::Heap, _) => super::linear::HEAP_WORDS, + }; + self.fetch.words() + heap + } +} + +/// The fetch of `op`, a gather without comparison of a 2D texture or array with texel form `form` +/// (module docs, [`half_gather`]), of `image` (shape `shape`) through `stat` (or, where +/// `argument`, its argument buffer's sampler): through a constexpr sampler addressed by its modes, +/// through a runtime or argument buffer's sampler by its word. A heap texture's fetch reads the +/// class its handle carries. +pub(super) fn select( + cx: &mut SelectCx<'_>, + op: &SampleOp, + form: Option, + (stat, argument): (Option<(SamplerRef, Coordinates)>, bool), + (image, shape): (ImageRef, ImageShape), +) -> Result, Error> { + if !half_gather(cx, op, form) || shape.dim != ImageDim::D2 || shape.ms { + return Ok(None); + } + let SampleOp::Gather { offset, .. } = op else { + return Ok(None); + }; + let offset = match offset { + None => None, + Some(Offset::Const(k)) => Some(k.clone()), + Some(Offset::Dynamic(..)) => return Ok(None), + }; + let address = match (stat.map(|(r, _)| r), argument) { + (Some(SamplerRef::Constexpr(words)), _) => { + let s = super::state_of(words)?; + FetchAddress::Modes { + address: [s.address_s, s.address_t] + .into_iter() + .map(super::position::address) + .collect(), + border: s.border_color, + pixel: s.coordinates == Coordinates::Pixel, + } + } + (Some(SamplerRef::Slot(sampler)), _) => FetchAddress::Word { sampler, axes: 2 }, + (None, true) => FetchAddress::Entry { axes: 2 }, + (None, false) => return Ok(None), + }; + let image = match image { + ImageRef::Slot(n) => LinearImage::Slot(n), + ImageRef::Heap { .. } => LinearImage::Heap, + }; + cx.families.access.heap_class |= image == LinearImage::Heap; + Ok(Some(Plain { + image, + fetch: Fetch { address, offset }, + })) +} + +/// Whether `op` is a gather with a `half` result whose texels the shader fetches where the bound +/// class is a 16-bit float one: where the NaN switch asks for Metal's NaN +/// (`NanMinMaxPolicy::Exact`, the profile's `TexelNanRoute::Metal`) on a device without Metal's +/// own sampler. Metal's gather hands back a 16-bit float texel's own NaN; a device's gather need +/// not (NVIDIA's hands back every NaN as `0x7fffffff`), and its fetch does +/// where its read does. +fn half_gather(cx: &SelectCx<'_>, op: &SampleOp, form: Option) -> bool { + use crate::device::profile::TexelNanRoute; + use crate::device::requirements::VkProperty; + matches!(op, SampleOp::Gather { dref: None, .. }) + && form.map(|f| f.conv) == Some(TexelConv::F16) + && cx.profile.fields().texel_nans == TexelNanRoute::Metal + && !cx + .profile + .fields() + .enabled + .properties + .contains(&VkProperty::MetalSampler) +} + +/// The value of gather `s` from the texels fetched as `f` says through combined binding `key` (one +/// without comparison), where the slot `texture`'s `TexelFormat` specialization states the +/// half-float class: [`plain_value`] of [`texels`]' texels. Elsewhere `device`'s access of the +/// binding's sampled image makes it. Each arm makes the sampled image it reads, so once a device +/// specializes the module the other arm is dead. +pub(super) fn branch( + cx: &mut EmitCx<'_>, + fb: &mut FunctionBuilder<'_>, + (s, key): (&Sampling, BindingKey), + (texture, f): (u32, &Fetch), + image: CombinedImage, + device: &dyn Fn(&mut FunctionBuilder<'_>, SValue) -> BResult, +) -> BResult { + 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"))); + }; + // A runtime sampler's word, which addresses its taps. + let word = match &f.address { + FetchAddress::Word { sampler, .. } => { + Some(super::emit::sampler_word(cx, fb, Pixel::Spec(*sampler))?) + } + FetchAddress::Modes { .. } => None, + FetchAddress::Entry { .. } => { + return Err(cx.fail("a slot's fetch addressed by an argument buffer's sampler")) + } + }; + let t = Tys::new(fb)?; + let measured = flag(fb, &t, spec, BicubicTexels::HALF)?; + let t = &t; + let fetch: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| { + let si = binding.sampled_image(fb)?; + let Some(taps) = f.taps(word) else { + return Err(cx.fail("a word-addressed fetch without its word")); + }; + let x = texels(cx, fb, t, s, (si, image), Bits::Spec(spec), &taps)?; + Ok(ArmEnd::FallThrough(vec![plain_value(fb, s, &x)?])) + }); + let read: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, _| { + let si = binding.sampled_image(fb)?; + let x = device(fb, si)?; + Ok(ArmEnd::FallThrough(vec![x])) + }); + let Merged(merged) = fb.if_(cx, measured, fetch, Some(read))?; + match merged[..] { + [x] => Ok(x), + _ => Err(cx.fail("fetched texels' branch without its value")), + } +} + +/// The value of fetch `p` of heap texture gather `s` (image facts `image`): `device`, the device's +/// gather already made, in uniform control flow; and where the class the texture's handle carries +/// is the half-float one, a component of the four texels the shader fetches from the element as a +/// slot of that class would ([`texels`]). The fetch arm holds fetches alone, so a divergent handle +/// puts no gather in divergent flow. +pub(super) fn heap( + cx: &mut EmitCx<'_>, + fb: &mut FunctionBuilder<'_>, + s: &Sampling, + image: CombinedImage, + p: &Plain, + device: SValue, +) -> BResult { + let handle = match s.source { + Source::Heap { handle, .. } | Source::HeapSampler { handle, .. } => handle, + Source::Combined(_) => return Err(cx.fail("a heap texture's fetch of a slot")), + }; + let t = Tys::new(fb)?; + let h = cx.operand(fb, handle)?; + let bits = Bits::Value(crate::lower::texture::heap_texel_class(cx, fb, h)?); + let word = match (&p.fetch.address, super::emit::word_pixel(s)) { + (FetchAddress::Modes { .. }, _) => None, + (_, Some(pixel)) => Some(super::emit::sampler_word(cx, fb, pixel)?), + (_, None) => return Err(cx.fail("a word-addressed heap fetch without its word")), + }; + let take = bits.test(fb, &t, BicubicTexels::HALF)?; + let t = &t; + let fetch: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| { + let (si, _, _) = super::emit::sampled_image(cx, fb, s.source)?; + let Some(taps) = p.fetch.taps(word) else { + return Err(cx.fail("a word-addressed heap fetch without its word")); + }; + let x = texels(cx, fb, t, s, (si, image), bits, &taps)?; + Ok(ArmEnd::FallThrough(vec![plain_value(fb, s, &x)?])) + }); + let kept: ArmFn<'_, EmitCx<'_>> = Box::new(move |_, _| Ok(ArmEnd::FallThrough(vec![device]))); + let Merged(merged) = fb.if_(cx, take, fetch, Some(kept))?; + match merged[..] { + [x] => Ok(x), + _ => Err(cx.fail("a heap texture's fetch without its texel")), + } +} + +/// The value of gather `s` of its fetched `texels`, as the device's gather returns it: its +/// component of each of its four (a `vec4`). +pub(super) fn plain_value( + fb: &mut FunctionBuilder<'_>, + s: &Sampling, + texels: &[SValue], +) -> BResult { + let SampleOp::Gather { component, .. } = s.op else { + return Err(super::bicubic::missing_tap()); + }; + let vec4 = Tys::new(fb)?.vec4; + let mut parts = Vec::with_capacity(texels.len()); + for &texel in texels { + parts.push(fb.composite_extract(texel, &[component])?); + } + fb.composite_construct(vec4, &parts) +} + /// The `vec4` texels of `s` at `taps` (any [`Addressing`]: a constexpr sampler's, or a runtime /// sampler's word) from sampled image `si` (image facts `image`), a border tap's texel the border /// color seen through format bits `bits` (the slot's `TexelFormat` specialization, or a heap @@ -710,12 +405,11 @@ fn sites(fp: &Footprint) -> Option>> { } } -/// The shared form of plain fetch `p` of sampling `s` in a switch-at-use (SEMANTICS 1012; +/// The shared form of fetch `p` of gather `s` in a switch-at-use (SEMANTICS 1012; /// `shared::shared_value`): the taps once on the named candidate's level-0 size `size` (image facts /// `image`), fetched in one dispatch over the candidates `c` from each arm's image where the named -/// format's bits `bits` are of the 32-bit float class, and `fetched` makes the value of their -/// texels; elsewhere `device`'s access, dispatched the same way from each arm's sampled image. Only -/// a fetch of the base level is shared (`Sampling::shared_shape`). +/// format's bits `bits` are of the half-float class, and [`plain_value`] of their texels; +/// elsewhere `device`'s access, dispatched the same way from each arm's sampled image. pub(super) fn emit_shared( cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, @@ -723,15 +417,14 @@ pub(super) fn emit_shared( (size, image): (SValue, CombinedImage), p: &Plain, (bits, c): (SValue, &super::Candidates<'_>), - fetched: &dyn Fn(&mut FunctionBuilder<'_>, &[SValue]) -> BResult, device: &dyn Fn(&mut FunctionBuilder<'_>, SValue) -> BResult, ) -> BResult { let t = Tys::new(fb)?; let bits = Bits::Value(bits); - let measured = bits.test(fb, &t, BicubicTexels::LINEAR)?; + let measured = bits.test(fb, &t, BicubicTexels::HALF)?; let t = &t; let fetch: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| { - let Some(taps) = p.fetch.taps(s, None, None) else { + let Some(taps) = p.fetch.taps(None) else { return Err(cx.fail("a shared fetch without its taps")); }; let fp = footprint_on(cx, fb, t, s, (size, image), bits, &taps)?; @@ -739,7 +432,7 @@ pub(super) fn emit_shared( return Err(cx.fail("a shared fetch's footprint without its taps")); }; let x = Texels::Candidates(c).fetch(cx, fb, (t, &fp), &sites, &|_, _, v| Ok(v))?; - Ok(ArmEnd::FallThrough(vec![fetched(fb, &x)?])) + Ok(ArmEnd::FallThrough(vec![plain_value(fb, s, &x)?])) }); let read: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| { let read = |cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, a: &Sampling| { @@ -761,224 +454,3 @@ pub(super) fn emit_shared( _ => Err(cx.fail("a shared fetch's branch without its texel")), } } - -/// The one texel [`texels`] fetched for a sample. -pub(super) fn one(_: &mut FunctionBuilder<'_>, texels: &[SValue]) -> BResult { - match texels { - [x] => Ok(*x), - _ => Err(super::bicubic::missing_tap()), - } -} - -/// The level the texels of `s` are fetched from (a `u32`), or `None` for the base level: a level -/// known when the function compiles, `floor` of the level the sample's snap hands the device, or -/// the level a runtime or argument buffer's sampler's word `word` (a `u32`) reads, clamped into -/// the levels of `si`'s image. -pub(super) fn level( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - t: &Tys, - s: &Sampling, - (level, word): (FetchLevel, Option), - si: SValue, -) -> BResult> { - let (level, operand) = match level { - FetchLevel::Fixed(n) => (Level::Fixed(n), None), - FetchLevel::Snapped(v) => { - let Some(super::level::LevelRule::Stated(snap)) = s.level else { - return Err(cx.fail("a snapped fetch level without its snap")); - }; - (Level::Snapped(snap), Some(cx.operand(fb, v)?)) - } - FetchLevel::Word(v) => { - let x = match v { - Some(v) => Some(cx.operand(fb, v)?), - None => None, - }; - ( - Level::Word { - operand: x.is_some(), - }, - x, - ) - } - FetchLevel::Blend(..) => return Err(cx.fail("a blended fetch level outside its blend")), - }; - level_at(cx, fb, t, (level, operand), word, si) -} - -/// [`level`] of level `level` at its operand `operand` (the sample's level or bias, where it -/// reads one), a runtime sampler's by its word `word`. -fn level_at( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - t: &Tys, - (level, operand): (Level, Option), - word: Option, - si: SValue, -) -> BResult> { - let level = match (level, operand) { - (Level::Fixed(0), _) => return Ok(None), - (Level::Fixed(n), _) => { - let c = scalar(fb, t.u32_, u64::from(n))?; - value(fb, c)? - } - (Level::Snapped(snap), Some(x)) => { - let l = snap.emit(fb, x)?; - let l = fb.glsl(GlslOp::Floor, &[l])?; - fb.convert(ConvOp::ConvertFToU, l, t.u32_)? - } - (Level::Snapped(_), None) => { - return Err(cx.fail("a snapped fetch level without its operand")) - } - (Level::Word { .. }, x) => { - let Some(word) = word else { - return Err(cx.fail("a word's fetch level without its word")); - }; - super::level::word_level(fb, word, 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)?; - Ok(Some(fb.glsl(GlslOp::UMin, &[level, last])?)) -} - -/// The routine of sample `s`'s fetch arm `shape` (`routine::Fetched`, fetching as `f` from a -/// combined binding of image facts `image` under the slot's `TexelFormat` specialization `spec`), -/// defined at its shape's first call, and its call's arguments: the coordinate and the array -/// layer as the sample states them, and the sample's level or bias where the level reads one, -/// each computed in the sample's own position, and the constant texel offset where a lane is off -/// zero. -fn fetch_routine( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - s: &Sampling, - shape: Fetched, - f: &Fetch, - (image, spec): (CombinedImage, ConstId), -) -> BResult<(FuncId, Vec)> { - let at = At::of(cx, fb, s)?; - let operand = match f.level { - FetchLevel::Snapped(v) | FetchLevel::Word(Some(v)) => Some(cx.operand(fb, v)?), - _ => None, - }; - let mut args = vec![at.coord]; - args.extend(at.layer); - args.extend(operand); - if shape.offset.is_some() { - let Some(o) = f.offset.as_deref() else { - return Err(cx.fail("a fetch's routine without its offset")); - }; - args.push(super::emit::const_offset(fb, o)?); - } - // The slot's format class, which a function reads as data. - args.push(fb.module().const_value(spec)?); - let mut tys = Vec::with_capacity(args.len()); - for &a in &args { - tys.push(fb.value_ty(a)?); - } - let shape = Shape::Fetched(shape); - if let Some(r) = cx.sampling.get(&shape, &tys) { - return Ok((r, args)); - } - let Shape::Fetched(fetched) = &shape else { - return Err(cx.fail("a fetch's routine of another shape")); - }; - let mut rcx = cx.for_new_function(); - let made = define( - &mut rcx, - fb.module(), - (fetched, f), - (&tys, at.parent), - image, - ); - cx.adopt(rcx); - let r = made?; - cx.sampling.insert(shape, tys, r); - Ok((r, args)) -} - -/// Define the routine of fetch arm `shape` (fetching as `f`) in `mb`, its parameters of types -/// `tys` in [`fetch_routine`]'s order, its offset placed by the slot's tests `parent` where `shape` -/// reads them, of a combined binding of image facts `image`: the one texel the arm's code fetched -/// inline, read from `shape`'s binding and specializations and the bound format's bits its last -/// parameter carries. -fn define( - cx: &mut EmitCx<'_>, - mb: &mut ModuleBuilder, - (shape, f): (&Fetched, &Fetch), - (tys, parent): (&[TypeId], Option), - image: CombinedImage, -) -> BResult { - let Some(&(binding, _)) = cx.decl.families.sampler.combined.get(&shape.binding) else { - return Err(cx.fail(format!( - "combined binding {:?} is not declared", - shape.binding - ))); - }; - let f32_ = mb.ty(SType::Float { width: 32 })?; - let ret = mb.ty(SType::Vector { elem: f32_, len: 4 })?; - let mut fb = mb.sampling_routine(ret)?; - let mut params = Vec::with_capacity(tys.len()); - for &ty in tys { - params.push(fb.param(ty)?); - } - // The coordinate, then the layer, the level's operand and the offset, each where the shape - // takes it, and the format's bits. - let operand = matches!( - shape.level, - Level::Snapped(_) | Level::Word { operand: true } - ); - let want = - 2 + usize::from(shape.layer) + usize::from(operand) + usize::from(shape.offset.is_some()); - let mut params = params.into_iter(); - let (Some(coord), true) = (params.next(), tys.len() == want) else { - return Err(cx.fail("a fetch's routine without its parameters")); - }; - let layer = shape.layer.then(|| params.next()).flatten(); - let operand = operand.then(|| params.next()).flatten(); - let offset = shape - .offset - .and_then(|lanes| params.next().map(|v| (v, lanes))); - let Some(bits) = params.next().map(Bits::Value) else { - return Err(cx.fail("a fetch's routine without its format's bits")); - }; - let at = At { - coord, - layer, - parent, - offset, - }; - let t = Tys::new(&mut fb)?; - // A runtime sampler's word, which addresses its tap. - let word = match &shape.address { - FetchAddress::Word { sampler, .. } => Some(super::emit::sampler_word( - cx, - &mut fb, - Pixel::Spec(*sampler), - )?), - FetchAddress::Modes { .. } => None, - FetchAddress::Entry { .. } => { - return Err(cx.fail("a slot's fetch addressed by an argument buffer's sampler")) - } - }; - let si = binding.sampled_image(&mut fb)?; - let level = level_at(cx, &mut fb, &t, (shape.level, operand), word, si)?; - // The offset is the call's (`at.offset`), not the first caller's constant. - let Some(taps) = f.taps_of(false, level, word) else { - return Err(cx.fail("a word-addressed fetch without its word")); - }; - let taps = Taps { - offset: None, - ..taps - }; - let x = texels_at(cx, &mut fb, &t, &at, (si, image), bits, &taps)?; - let [x] = x[..] else { - return Err(cx.fail("a sample's fetch without its one texel")); - }; - fb.ret(Some(x))?; - fb.finish() -} diff --git a/crates/metal2vulkan/src/lower/sampler/level.rs b/crates/metal2vulkan/src/lower/sampler/level.rs index 809ef41f0..fde1b3f24 100644 --- a/crates/metal2vulkan/src/lower/sampler/level.rs +++ b/crates/metal2vulkan/src/lower/sampler/level.rs @@ -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 { - 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 { - 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 { 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 { - 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, bool), -) -> Result, 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, - (cube, filtered): (bool, bool), - (snapped, value, integer): (bool, Option, bool), -) -> Result, 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) -> Option { - 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 { let c = fb.u32_const(v)?; diff --git a/crates/metal2vulkan/src/lower/sampler/level/tests.rs b/crates/metal2vulkan/src/lower/sampler/level/tests.rs index e960bed03..6d22f1dde 100644 --- a/crates/metal2vulkan/src/lower/sampler/level/tests.rs +++ b/crates/metal2vulkan/src/lower/sampler/level/tests.rs @@ -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 { +/// 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 { 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 { 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 { 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 { let mut out: Vec = MEASURED.iter().map(|m| m.0).collect(); @@ -247,91 +160,7 @@ fn levels() -> Vec { 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 = 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 { - 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}" )); } } diff --git a/crates/metal2vulkan/src/lower/sampler/linear.rs b/crates/metal2vulkan/src/lower/sampler/linear.rs index 416ee472a..36166cf80 100644 --- a/crates/metal2vulkan/src/lower/sampler/linear.rs +++ b/crates/metal2vulkan/src/lower/sampler/linear.rs @@ -1,293 +1,43 @@ -//! Metal's linear filter for a sample with a `half` or `float` result, emulated by fetches. +//! What the device-sampled filters share with the emulated ones the device has no form for +//! (`extended`, `heap_raw`, `in_place`, `bicubic`): the texture whose bound format's class a +//! filter reads ([`LinearImage`]), the census words of a filter's footprint and of a runtime +//! sampler's word, the rule of an axis whose two taps read one texel ([`merged`]), the samplers +//! that read one texel of one level ([`unfiltered`], [`word_filters`]), and the note of a filtered +//! sample that Metal's own sampler answers otherwise than Metal filters the format bound there +//! ([`filter_note`]). //! -//! **The filter Metal applies** (Apple M3 Max, macOS 26.7; the probe cases and `f8f81b81`). Per -//! plane axis of a sample through a sampler with linear minification and magnification and no mip -//! filter, the texel-space coordinate `x` (Metal's position of the normalized coordinate on the -//! level-0 size: wrapped into one period first on a repeating or mirrored axis, then scaled with -//! ties away from zero, `position`; or the pixel coordinate) is read as the bicubic filter reads it -//! (`bicubic`): `q = floor(256 (x - 1/2) + 1/2)`, the base texel `i = q >> 8` (plus any constant -//! texel offset) and the fraction's 1/256 steps `k = q & 255`. The taps `i` and `i + 1` weigh -//! `(256 - k) / 256` and `k / 256`, the 2D filter is their product, and each tap is addressed on -//! its own: `clamp_to_edge` clamps its index into the level, `repeat` wraps it, `mirrored_repeat` -//! reflects it ([`TapAddress::Mirror`]), and `clamp_to_zero` and `clamp_to_border` replace an -//! out-of-range tap by the sampler's border color seen through the bound format's channels -//! (`clamp_to_zero` reads the border color too; AIR codes the two as one mode, its border color -//! deciding). The level is the base level (no mip filter: Metal reads level 0 whatever the level, -//! bias, gradients, or derivatives), and a 2D array's layer is clamped into the array. The sum is -//! the bound format's, as `metal::texel_format` states: an 8- or 16-bit normalized format's -//! weighted codes (an 8-bit sRGB format's table steps) summed exactly and rounded half up onto its -//! grid, then `n / D` rounded to nearest even, to `f32` for a `float` result or to `half`; a 32-bit -//! float or half-float format's taps summed through Metal's linear accumulator: each term truncated -//! toward zero onto a grid 38 bits (17 for a half-float format) below the largest present term's -//! tap and weight exponents (`e(v) + e(w)`; a tap of zero weight is absent), the truncated terms -//! summed exactly, and the sum rounded once with ties away from zero, a 32-bit float format's to -//! `f32` (a denormal sum `+0`), then for a `half` result toward zero saturating, and a half-float -//! format's to `half`, which a `float` result widens. A result that is zero is `+0`, whatever its -//! taps' signs (a `-0` texel at a texel centre, and a half-float sum that rounds to zero, -//! included). A normalized format's 2D sum truncates its terms first (below). +//! Every filtered sample of a format the device samples is the device's: Metal's own filter 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`). //! -//! **A normalized format's 2D sum** (Apple M4 and Apple M3 Max, byte-identical; the 2D and cube -//! probes) weighs an axis whose two taps address one texel `(256, 0)`, as a 3D sample does (below), -//! each tap `w = wx · wy` in units of `2^-16`, and truncates each term onto its grid first, as a 3D -//! sum does: `T = Σ ⌊c · w / 2^s⌋` for the codes `c` on the grid (`s` 4 for an 8-bit format's `16 · -//! code` and an sRGB step, 8 for a 16-bit format's code, toward negative infinity for a signed -//! format), then the grid step `⌊(T + 2^(15 - s)) / 2^(16 - s)⌋`. The truncation moves an sRGB -//! color lane's sum and a 16-bit format's; an 8-bit format's `16 · code` terms lose nothing, so its -//! sum is the exact one. A float format's 2D sum merges such an axis too, before its accumulator -//! (every 2D channel past the edges of `RGBA16Float`, `RGBA32Float`, `RG11B10Float`, and -//! `RGB9E5Float`). -//! -//! **A 3D texture's filter** (Apple M4, macOS 27.0.1, and Apple M3 Max, macOS 26.7, byte-identical; -//! the 3D probes) reads each of the three axes as above and weighs its eight taps differently from -//! the 2D product: -//! - An axis whose two taps address one texel (clamped onto each other at an edge, reflected onto -//! each other at a mirrored boundary, a level one texel wide, or both outside a border axis) -//! weighs them `(256, 0)`. -//! - Each tap's weight is `wx · wy · wz / 256` rounded to nearest, in units of `2^-16`. A tie (a -//! remainder of 128) rounds up on the `t` axis's first tap in Metal's frame and down on its -//! partner: the first is tap `j`, but tap `j + 1` where the axis mirrors and its taps run -//! backwards (the reflected half of the period). The weights sum to `2^16`. -//! - A normalized format's sum truncates each term onto its grid first: `T = Σ ⌊c · w / 2^s⌋` for -//! the codes `c` on the grid (`s` 4 for an 8-bit format's `16 · code` and an sRGB step, 8 for a -//! 16-bit format's code, toward negative infinity for a signed one), then the grid step `⌊(T + -//! 2^(15 - s)) / 2^(16 - s)⌋`. A float format's sum is the accumulator's under the 16-bit -//! weights, its non-finite taps those of nonzero product weight `wx · wy · wz`, a tap whose -//! weight rounds to zero among them (`RG11B10Float`'s infinities). -//! -//! **A cube's filter** (`cube`; the cube probes, Apple M4 and Apple M3 Max, byte-identical) reads -//! the face of the direction's major axis at Metal's face position (`face::position`), quantized as -//! in 2D, its four taps unmerged; a tap past one edge of the face reads the adjacent face's texel, -//! and a tap past both edges a texel that depends on the format (a float format's `x` face's corner -//! texel, a normalized one's made-up texel). It ignores the address modes and the border color, and -//! sums as the 2D filter does. The emulation fetches the taps from the slot's 2D-array view of the -//! faces. -//! -//! **The emulation** reads the slot's `SpecKey::TexelFormat` specialization (the bound format's -//! `BicubicTexels` bits where its conversion is measured, else `0`), fetches the footprint's taps -//! of the base level, and sums them through module routines called with the format's bits and -//! the result type: the linear 1D routines (`bicubic::routines::Span`), 2D ones -//! (`bicubic::routines::Quad`, whose exact routine takes the axes' fractions with a merged axis's -//! at 0, and a cube's taps beside `bicubic::routines::Cube`'s fold and corner), and 3D ones -//! (`bicubic::routines::Block`, which take the merged fractions, and whether the `t` axis's taps -//! run backwards). An `EXACT` format takes the exact -//! routine (the codes' sum in integers, rounded onto the grid and divided exactly). A 32-bit float -//! or half-float format takes the accumulated routine, Metal's accumulator in integer operations -//! on the taps' bits. Either routine's value is the result. A format whose conversion is not -//! measured (`TexelFormat::OTHER`) takes the device's sample instead, which the slot's conversion -//! routine (`texture::half`) converts for a `half` result: the emulation and the device's sample -//! are selected on the specialization, so once a device specializes the module the other is dead. -//! The emulated arm of a sample through a texture slot's combined binding is its shape's sampling -//! routine (`sampler::routine`), defined once in the module and called by every sample of the shape -//! with the coordinate, the layer, a cube's direction, and a comparison's reference; the site keeps -//! the branch and the device's sample. A heap image's emulation is the site's own code. -//! -//! **A runtime sampler**. Metal filters a sample through a sampler bound to a slot or held in an -//! argument buffer exactly as through a constexpr sampler of the same state (Apple M4, macOS -//! 27.0.1: 24 cases, 2D linear under every address mode with normalized and pixel coordinates, 2D -//! nearest, 3D, 1D, and cube, on `RGBA8Unorm` and `RGBA32Float`, every lane bit for bit). So a -//! sample through a runtime sampler slot of the shapes the emulation reaches is planned for it too -//! ([`LinearState::Slot`]), and the slot's `SamplerState` specialization carries the word's -//! [`SamplerWord::LINEAR_STATE`] fields: the branch also tests that the word states the measured -//! filter (`reaches_word`), and the taps follow the word's address modes, border color, and -//! coordinates, computed in the function from the specialization (each tap's index under every -//! mode, selected by the axis's mode; a cube's face wrap by its `s` and `t` modes), so once a -//! device specializes the module the arithmetic folds to the bound sampler's. A `MirrorClampToEdge` -//! axis, which only a runtime sampler states, reflects each tap's index once, `-1 - i` for a -//! negative `i`, and clamps it into the level, under pixel and normalized coordinates alike, its -//! constant texel offset placed as on a repeating axis (Apple M4: every lane of nearest and linear -//! samples, gathers and depth comparisons of textures 1 to 8 texels wide); the emulation reaches it -//! on a 1D or 2D texture, and the device filters it on a 3D texture or a cube, where no probe -//! measured it ([`Linear::mirror_clamp_reached`]). Argument-buffer samplers are not reached: their -//! textures are heap elements, whose format no specialization states; the device filters them, -//! under the notes. A slot under its 8-bit sRGB variant is (Metal's samples of `RGBA8Unorm_sRGB` -//! and `BGRA8Unorm_sRGB` through a runtime sampler are its constexpr sampler's of the same state, -//! bit for bit, in 1D, 2D, and 3D): the emulation sums the raw codes fetched through the slot's raw -//! view (`Linear::fetch`) where the word reaches it; where the word reads one texel the device -//! samples the raw view through the same sampler, and Metal's table decodes the code, as a -//! constexpr nearest sample's raw read does; elsewhere the device samples the slot's own binding, -//! the decoding view, under `PrecisionNote::SrgbTexelDecode` ([`decode_when`]). A cube's is -//! inferred from the same equality on the other formats and from its constexpr sampler's raw -//! emulation; its word that reads one texel samples the decoding view too. -//! -//! **Where it is exact**, on the probes: in 1D and 2D for every measured format (a 16-bit -//! normalized format's 2D sum on every channel of probes, under `clamp_to_edge`, `repeat`, -//! `mirrored_repeat`, and `clamp_to_zero`, with `float` and `half` results, and an 8-bit sRGB -//! format's under `clamp_to_edge`). The accumulator is Metal's on every lane of P2a and -//! P2c, both Metal passes, under `clamp_to_edge` and `clamp_to_zero`, with `float` and `half` -//! results, in 1D and 2D, for the 32-bit float and half-float formats (`R32Float`, `RGBA32Float`, -//! `R16Float`, `RGBA16Float`); the other address modes, an array's layer, an offset, and pixel -//! coordinates move the taps only. An offset on a repeating or mirrored axis moves them as Metal -//! places it, which depends on the axis's size (`position::offset_dropped`, dropped at a base-level -//! size of 3, 5, 6, or 7, added before the wrap at every other). In 3D the emulation is exact on -//! every lane of the probes for the 8- and 16-bit normalized, 8-bit sRGB, and 32-bit float formats, -//! under every address mode, a white border, offsets on clamping axes, and non-finite taps, but for -//! one 32-bit float lane in about 180,000 (a cancellation the accumulator's truncation misses), and -//! a half-float format's result is half a `half` ulp off on about 0.3% of channels; an offset on a -//! repeating or mirrored axis is placed by the same rule per axis (the offset probes measured it on -//! 3D textures), and pixel coordinates are inferred to move the taps only, as in 2D. A cube's is -//! exact on every channel of the cube probes where the major magnitude is 1; elsewhere Apple's -//! approximate reciprocal of the major magnitude can move a position by a 1/256 step -//! (`PrecisionNote::CubeFaceReciprocal`, `cube`). These residues are recorded -//! (`PrecisionNote::HalfSampleFilter`, `PrecisionNote::FloatSampleFilter`), with every sample the -//! emulation does not reach (its selection, `select`). -//! -//! **The packed formats** (an Apple M3 Max on macOS 26.7 and an Apple -//! M4 on macOS 27.0.1, byte-identical; `metal::texel_format`). A packed normalized format sums as -//! an 8-bit format does, each channel on its own 12-bit grid (`16 · 255`, `4 · 1023`, or `4095`, -//! the code widened by replicating its bits), its terms truncated onto `2^-4` of a step: the exact -//! routine, every 1D, 2D, and 3D sample of the probes. A small float sums as a half-float format -//! does, a `float` result the `half` sum widened: every 1D and 2D sample, and in 3D the half-float -//! residue above. A packed normalized format's cube sample is not measured and keeps the device's -//! filter (`TexelFormat::packed_exact`). -//! -//! **The 8-bit 4:2:0 YCbCr format** (byte-identical) sums its converted color's steps `k / 2048` on -//! the grid `2048`, each 2D term truncated by `2^7` -//! (`metal::texel_format::PackedTexels::YCbCr2048`): the exact routine, every channel of the -//! probes. Such a texture has one level (Metal makes it only over an IOSurface plane), and Metal's -//! sample of it through a mip filter is its sample through none, whatever the level, bias or -//! gradient: the emulation reaches a runtime sampler's mip filter on its -//! class (`PackedTexels::one_level`, `reaches_word`). A constexpr sampler with a mip filter keeps -//! the device's filter, noted. -//! -//! On a device whose sampler answers the module's samples such a slot's emulation is its YCbCr -//! variant's alone ([`Linear::exact_only`]), 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`; elsewhere the device filters -//! the slot as any other, `YCbCrFilterPolicy::Device`, noted): the binder binds a two-plane YCbCr -//! format there, whose class is `EXACT` or measured by no family, so only an `EXACT` class takes -//! the emulation, through the exact routine alone, and every other class the device's sample, -//! which is Metal's own filter on that device. -//! -//! **Depth textures and comparisons** (the probe, px3 and px4 probes, Apple M4 on macOS 27.0.1). -//! A depth texture's linear sample is its color class's (`metal::texel_format`: `Depth32Float` an -//! `R32Float`'s, `Depth16Unorm` an `R16Unorm`'s), so the emulation answers it by the class, its -//! value the sum's first channel. A linear comparison is an `r8Unorm` sample of the taps' passes as -//! codes 0 and 255, each tap's depth (a border's included) compared with the reference (`compare`): -//! the emulation compares each tap in the shader and sums the passes through the exact routine -//! under `r8Unorm`'s bits, through a constexpr sampler of a 2D texture or array or a cube or cube -//! array (a cube's corner tap the format's: `Depth32Float`'s the `x` face's texel, `Depth16Unorm`'s -//! the made-up code, compared as a texel). -//! -//! **On a device that samples through Metal's own sampler** (`VkProperty::MetalSampler`: MoltenVK -//! on Apple's GPU) the device's filter is Metal's, so no sample is emulated: the module leaves -//! every filtered sample to the device and requires the property. +//! **Two-plane YCbCr textures** (`YCBCR8_420_2P` and its kin). A format's view holds each channel +//! of the converted color as Metal reads it, a step `k / D` (alpha 1) on its field's grid: `2048` +//! (`PackedTexels::YCbCr2048`), `8192` (`PackedTexels::YCbCr8192`), or `8192` signed within +//! `[-2, 2]` (`PackedTexels::YCbCrExtended8192`). Metal's 2D linear sample sums the steps on the +//! grid, each term truncated; Metal's own sampler filters the view's texels as an `RGBA16Float` or +//! `RGBA32Float` texture's, within one step of the grid, so a filtered sample of such a slot there +//! records `PrecisionNote::HalfSampleFilter` or `PrecisionNote::FloatSampleFilter` where the bound +//! format is two-plane YCbCr ([`metal_filtered_ycbcr`]). A device whose memory is the host's reads +//! the planes in place, Metal's filter exactly (`in_place`). -use crate::air::abi::{ - AddressMode, BorderColor, CompareFunction, Coordinates, Filter, MipFilter, SamplerState, -}; -use crate::air::intrinsics::{ImageDim, ImageShape}; -use crate::air::ir::ValueId; +use crate::air::abi::{Filter, MipFilter, SamplerState}; use crate::error::Error; -use crate::lower::emit::EmitCx; -use crate::lower::select::{any_of, both, NoteClause, NoteOn, NoteTest, SelectCx}; -use crate::lower::texture::half::HalfForm; -use crate::lower::texture::OffsetBase; -use crate::lower::texture::{half_class, ImageRef, TexelConv, TexelForm}; -use crate::metal::bicubic::BicubicTexels; +use crate::lower::select::{any_of, NoteClause, NoteOn, NoteTest, SelectCx}; +use crate::lower::texture::{ImageRef, TexelConv, TexelForm}; use crate::metal::sampler::SamplerWord; -use crate::metal::texel_format::{texel_format, PackedTexels, TexelFormat}; -use crate::metal::SamplerAddressMode; +use crate::metal::texel_format::{PackedTexels, TexelFormat}; use crate::pipeline::artifact::PrecisionNote; use crate::pipeline::sym::SamplerRef; -use crate::spirv::builder::constructs::{ArmEnd, ArmFn, Merged}; -use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; +use crate::spirv::builder::FunctionBuilder; use crate::spirv::error::BResult; -use crate::spirv::ids::{ConstId, FuncId, TypeId, Value as SValue}; -use crate::spirv::ir::{BinOp, ConstBits, Constant, Type as SType, UnOp}; +use crate::spirv::ids::Value as SValue; +use crate::spirv::ir::BinOp; -use super::bicubic::routines::Routine; -use super::bicubic::{ - self, flag, footprint, footprint_from, footprint_on, scalar, value, Addressing, At, Bits, - Footprint, Tap, TapAddress, TapBase, Taps, Texels, Tys, -}; -use super::face::{FaceRoutines, FaceWrap}; -use super::routine::{Emulation, Shape}; -use super::{CombinedImage, Lod, Offset, SampleOp, Sampling, Source}; -pub use compare::Comparison; -use compare::TapCompare; +use super::bicubic::{scalar, value, Tap, Tys}; +use super::SampleOp; -pub(super) mod compare; -mod cube; - -pub(super) use cube::select_gather; -pub use cube::CubeGather; - -/// A linear sample with a `half` result emulated by fetches (module docs). -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub struct Linear { - /// The texture whose bound format's treatment the emulation reads: a slot's `TexelFormat` - /// specialization, or a heap texture's class, which its handle carries. - pub image: LinearImage, - /// The sampler's state the taps follow. - pub state: LinearState, - /// The constant texel offset Metal applies, per plane axis. - pub offset: Option>, - /// The sample reads an 8-bit sRGB texture's raw codes, its slot in the `SrgbTexture` - /// variant: each tap's color lanes become the table's steps (`srgb_raw_tap`), and the exact - /// routine sums them on the sRGB grids (`BicubicTexels::SRGB`), whatever the device. Through a - /// runtime sampler slot it does so where the word reaches the emulation, its taps fetched - /// through [`fetch`](Self::fetch), the slot's raw view, which its device arm samples where the - /// word reads one texel; the sample's own binding is the decoding view, which its device arm - /// samples elsewhere. - pub raw: bool, - /// A cube's sample (`cube`), with its face position's routines: its taps are fetched from the - /// faces of the slot's 2D-array view (its raw view where `raw`), its state's addressing is its - /// face's `s` and `t` axes' (a constexpr sampler's `address`, or a runtime sampler's word's), - /// of which a repeating one wraps a face coordinate of 1 (`face::FaceWrap`), and its border, - /// coordinates, and `offset` are not read (Metal reads a cube's other address modes as - /// clamping, and a cube sample has no offset). - pub cube: Option, - /// A depth texture's comparison (`compare`): its sampler's compare function (a runtime - /// sampler's its word's), under which each tap's depth (a border's included) is compared with - /// the reference, the passes summed as an `r8Unorm` sample's codes 0 and 255, the result a - /// scalar. - pub compare: Option, - /// The binding a 2D comparison's taps are fetched through, the slot's without comparison - /// (`BindingKey::compare` false, set by `sampler::select`): the sample's own binding compares, - /// and through it a `Depth32Float` texture held with a twin reads the twin, whose depth view - /// ANV clamps into `[0, 1]` (runtime lane `depth_compares`: 30 of 3,392 comparisons of texels - /// outside it differed). A runtime sampler's raw emulation fetches its taps through the slot's - /// raw view (`BindingKey::raw`). `None`: the taps are fetched through the sample's binding (a - /// cube's through its faces' view). - pub fetch: Option, - /// The emulation of a slot under its YCbCr variant on a device whose sampler answers the - /// module's samples (`DeviceProfile::device_samples`): only an `EXACT` class takes it, through - /// the exact routine alone, and every other class the device's sample, Metal's own filter. The - /// binder puts a slot in the variant only where it binds a two-plane YCbCr format there - /// (`bind::plan::slots::ycbcr_variant`), whose class is `EXACT` or measured by no family - /// (`metal::texel_format`'s `two_plane_family`), never the accumulated routine's: so the - /// emulated routine, which no such class reads, is not called. - pub exact_only: bool, - /// The device's filter answers the native classes (`native`): on a profile that takes - /// `DriverDeviation::Unorm8LinearFilter`, a 2D slot's sample through a constexpr or runtime - /// sampler slot hands an 8-bit unsigned normalized class to the device at Metal's footprint - /// step (`native::coordinate`) where it would otherwise take the emulation. - pub native: bool, -} - -/// The state of the sampler a linear sample's emulation follows (module docs). -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub enum LinearState { - /// A constexpr sampler's, known at translation. - Constant { - /// The addressing of each plane axis (`s`, then `t` for a 2D texture, then `r` for a 3D - /// one); none for a cube. - address: Vec, - /// The sampler's border color, which every axis clamping to zero or to the border reads. - border: BorderColor, - /// Pixel coordinates: the plane coordinate is already in texels. - pixel: bool, - }, - /// The runtime sampler in slot `sampler`, on `axes` plane axes: its `SamplerState` - /// specialization's word states whether Metal's measured filter applies, and each axis's - /// address mode, the border color, and the coordinates the emulation reads. - Slot { sampler: u32, axes: u8 }, - /// An argument buffer's sampler, whose handle `sampler` is the index of its sampler table - /// entry, on `axes` plane axes: the entry's word states what a slot's does. - Argument { sampler: ValueId, axes: u8 }, -} - -/// The texture whose bound format's treatment a linear sample's emulation reads. +/// The texture whose bound format's treatment a sample reads. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum LinearImage { /// Texture slot `n`, whose `TexelFormat` specialization states the bound format's class. @@ -307,142 +57,6 @@ impl LinearImage { } } -impl Linear { - /// Whether a runtime or argument buffer's sampler's word states the sampler - /// ([`LinearState::Slot`], [`LinearState::Argument`]). - pub(super) fn word_state(&self) -> bool { - matches!( - self.state, - LinearState::Slot { .. } | LinearState::Argument { .. } - ) - } - - /// Whether the emulation reaches a runtime sampler whose word states `MirrorClampToEdge` on a - /// plane axis: a 1D or 2D texture's, an array's or not (Metal reflects each tap's index once, - /// `-1 - i` for a negative `i`, then clamps it into the level, under pixel and normalized - /// coordinates alike, its constant texel offset placed as on a repeating axis); not a 3D - /// texture's, whose mirrored `t` axis's tie rule no probe measured - /// under the mode, nor a cube's. - pub(super) fn mirror_clamp_reached(&self) -> bool { - self.cube.is_none() && self.plane_axes() <= 2 - } - - /// The class bits of which one names a family the emulation takes: `EXACT`, `LINEAR`, or - /// `HALF`; only `EXACT` under [`exact_only`](Self::exact_only). - pub(super) fn measured(&self) -> u32 { - match self.exact_only { - true => BicubicTexels::EXACT, - false => BicubicTexels::EXACT | BicubicTexels::LINEAR | BicubicTexels::HALF, - } - } - - /// The plane axes: 1, 2 (a cube's face's included), or 3. - pub(super) fn plane_axes(&self) -> usize { - match &self.state { - LinearState::Constant { address, .. } if self.cube.is_none() => address.len(), - LinearState::Constant { .. } => 2, - LinearState::Slot { axes, .. } | LinearState::Argument { axes, .. } => { - usize::from(*axes) - } - } - } - - /// The routines the emulation calls, by dimension: the linear 1D, 2D, or 3D routines, or a - /// cube's 2D ones and its fold and corner. - pub(super) fn routines(&self) -> &'static [Routine] { - match (self.cube, self.plane_axes()) { - (Some(_), _) => &[Routine::Quad, Routine::Cube], - (None, 1) => &[Routine::Span], - (None, 2) => &[Routine::Quad], - (None, _) => &[Routine::Block], - } - } - - /// The census words beyond the device's sample: the footprint (each axis's position, which a - /// pixel coordinate does not take), per tap its addressing and fetch, the calls of the - /// routines, whose own words the module counts once ([`Routine::words`]), the branch, the - /// conversion's call, and the select, and a raw sample's tap conversions; for a runtime sampler - /// the word's tests ([`WORD_WORDS`]), each axis's position under its mode - /// ([`super::position::MODE_POSITION_WORDS`]), and each axis's taps under every mode - /// ([`WORD_TAP_WORDS`]); and Metal's offset rule on each axis a constant offset moves - /// (`position::OFFSET_RULE_WORDS`). The estimate bounds every emitted form - /// (`the_linear_estimate_bounds_its_emission`, `the_raw_estimate_bounds_its_emission`). - pub(super) fn words(&self) -> u32 { - if let Some(face) = self.cube { - let wrap = match &self.state { - LinearState::Constant { address, .. } => { - FaceWrap::of(address.first().copied(), address.get(1).copied()).words() - } - LinearState::Slot { .. } | LinearState::Argument { .. } => { - WORD_WORDS + super::face::WORD_WRAP_WORDS - } - }; - let compare = self.compare.map_or(0, |c| c.words(4)); - return cube::WORDS - + face.use_words() - + wrap - + compare - + if self.raw { - cube::TAPS * crate::lower::texture::SRGB_TAP_WORDS - } else { - 0 - }; - } - let axes = self.plane_axes() as u32; - let (base, taps) = match axes { - 1 => (LINE_WORDS, 2), - 2 => (PLANE_WORDS, 4), - _ => (BLOCK_WORDS, 8), - }; - let position = match &self.state { - LinearState::Constant { pixel: true, .. } => 0, - LinearState::Constant { .. } => axes * super::position::POSITION_WORDS, - LinearState::Slot { .. } | LinearState::Argument { .. } => { - WORD_WORDS - + axes - * (super::position::POSITION_WORDS - + super::position::MODE_POSITION_WORDS - + 2 * WORD_TAP_WORDS) - } - }; - // A heap texture's class from its handle, its sampled image loaded again in the - // emulation's arm, an argument buffer's sampler's word from its entry, and the branch. - let heap = match (self.image, &self.state) { - (LinearImage::Slot(_), _) => 0, - (LinearImage::Heap, LinearState::Argument { .. }) => { - HEAP_WORDS + crate::memory::handles::ENTRY_FIELD_WORDS - } - (LinearImage::Heap, _) => HEAP_WORDS, - }; - let compare = self.compare.map_or(0, |c| c.words(taps)); - // Metal's offset rule on each axis an offset moves. - let offset = self - .offset - .as_deref() - .map_or(0, |o| o.iter().filter(|o| **o != 0).count() as u32) - * super::position::OFFSET_RULE_WORDS; - base + position - + compare - + offset - + heap - + if self.raw { - taps * crate::lower::texture::SRGB_TAP_WORDS - } else { - 0 - } - } - - /// The census words a native class's test and snapped coordinate add at the sample's own site - /// (`native`): its code is the site's, not its emulation's routine's, so - /// [`words`](Self::words), which the routine counts, leaves it out. - pub(super) fn native_words(&self) -> u32 { - match self.native { - true => super::native::WORDS, - false => 0, - } - } -} - /// The census words a runtime sampler's emulation adds once per sample: the word's filter test and /// each axis's mode test (`reaches_word`), each axis's mode and the coordinates' extraction, the /// border color's selection, and a 3D sample's reflected-axis test, with their constants. @@ -458,231 +72,23 @@ pub(super) const WORD_TAP_WORDS: u32 = 160; /// emulation's arm, and the branch and its merge, with their constants. pub(super) const HEAP_WORDS: u32 = crate::lower::texture::HEAP_CLASS_WORDS + 64; -/// [`Linear::words`] of a 1D sample. -pub(super) const LINE_WORDS: u32 = 320; /// [`Linear::words`] of a 2D sample. pub(super) const PLANE_WORDS: u32 = 576; -/// [`Linear::words`] of a 3D sample. -pub(super) const BLOCK_WORDS: u32 = 1152; - -/// The plan of sample `op` of `image` (shape `shape`) through `sampler` (`None`: an argument -/// buffer's, chosen at run time, whose handle is `argument`), with texel form `form` (`observed`: -/// the function observes its residency), on a device without `VkProperty::MetalSampler`: the -/// emulation where it reaches the sample, else `None`, the device's filter. The filtered sample's -/// note ([`filter_note`]) is the caller's, once it has settled the plan ([`filter_when`]). On a -/// device with the property the module requires it for each such sample instead -/// ([`super::SamplerPlan::metal_sampler`]). -/// -/// The emulation reaches a sample through a constexpr sampler with linear minification and -/// magnification, no mip filter, and no anisotropy, of a 1D, 2D or 3D texture slot (an array -/// or not, a depth texture's included), or a cube or cube array, with a `half` or `float` result, a -/// comparison only of a 2D or cube depth texture or array (each tap compared in the shader, -/// `TapCompare`), a constant texel offset or none, no `min_lod_clamp`, and no observed residency, -/// whose axes do not clamp one to zero and another to a colored border. A sample through a -/// constexpr sampler that reads one texel of one level ([`unfiltered`]) is not filtered: the -/// device's texel is converted exactly, so it neither records a note nor requires the property. -/// -/// A sample of the same shapes through a runtime sampler slot is planned for the emulation too -/// ([`LinearState::Slot`]): Metal filters through a runtime sampler as through a constexpr sampler -/// of the same state, and whether the bound sampler's state is the one the -/// emulation reaches (its filter, and for a 3D texture or a cube on each plane axis an address mode -/// other than `MirrorClampToEdge`) is read from the slot's `SamplerState` specialization in the -/// function (`reaches_word`). Under a slot's 8-bit sRGB variant the caller makes the emulation raw, -/// its taps fetched through the slot's raw view (`Linear::fetch`). -/// -/// A heap texture's sample of those shapes but a cube's, without comparison, through a -/// constexpr sampler, a runtime sampler slot, or an argument buffer's sampler -/// ([`LinearState::Argument`], whose entry's word states what a slot's does) is planned for the -/// emulation too ([`LinearImage::Heap`]): Metal filters a texture bound through an argument buffer -/// as one bound to a slot (our probe sampled heap textures through its argument buffers' -/// samplers), and the class the emulation reads is the one the handle carries -/// (`AccessPlan::heap_class`): a slot's class for a texture without a swizzle, else -/// `TexelFormat::OTHER`, which the device filters. -pub(super) fn select( - cx: &mut SelectCx<'_>, - op: &SampleOp, - form: Option, - (sampler, image, shape): (Option, ImageRef, ImageShape), - (argument, observed): (Option, bool), -) -> Result, Error> { - let SampleOp::Sample { - lod, - dref, - min_lod, - offset, - } = op - else { - return Ok(None); - }; - if !matches!(form.map(|f| f.conv), Some(TexelConv::F16 | TexelConv::F32)) { - return Ok(None); - } - let state = match sampler { - Some(SamplerRef::Constexpr(words)) => Some(super::state_of(words)?), - Some(SamplerRef::Slot(_)) | None => None, - }; - if state.as_ref().is_some_and(unfiltered) { - return Ok(None); - } - let slot = match sampler { - Some(SamplerRef::Slot(n)) => Some(n), - _ => None, - }; - // On a device that samples through Metal's own sampler, the device's filter is Metal's, but - // for a slot under its YCbCr variant; on one that samples natively, the device's filter is the - // answer, but for a slot under its YCbCr variant where the policy asks for Metal's filter of - // the format (`ProfileFields::ycbcr_variant`). - let metal_sampler = cx.profile.device_samples(); - if metal_sampler && !crate::lower::texture::ycbcr_texture(cx, image, shape)? { - cx.families.sampler.metal_sampler = true; - return Ok(None); - } - // A depth texture's sample is its color class's; its comparison compares each tap in the - // shader, through a constexpr sampler of a 2D texture or array or a cube or cube array (the - // frontend writes an unspecified compare function as `never`, and no `None`), or through a - // runtime sampler slot by its word's function, of a 2D texture or array. - let compare = match (dref, &state, slot) { - (None, _, _) => None, - (Some(_), Some(s), _) - if matches!(shape.dim, ImageDim::D2 | ImageDim::Cube) && shape.depth => - { - match s.compare { - CompareFunction::None => return Ok(None), - f => Some(Comparison::Function(f)), - } - } - (Some(_), None, Some(_)) if shape.dim == ImageDim::D2 && shape.depth && !shape.ms => { - Some(Comparison::Word) - } - (Some(_), _, _) => return Ok(None), - }; - // A heap texture's class is its handle's: not a cube's, whose faces no heap element views, nor - // a comparison's, which the heap's own path makes. - let texture = match image { - ImageRef::Slot(n) => LinearImage::Slot(n), - ImageRef::Heap { .. } if shape.dim != ImageDim::Cube && compare.is_none() => { - LinearImage::Heap - } - ImageRef::Heap { .. } => return Ok(None), - }; - let axes = match shape.dim { - ImageDim::D1 => 1, - ImageDim::D2 | ImageDim::Cube => 2, - ImageDim::D3 => 3, - ImageDim::Buffer => return Ok(None), - }; - let clamped = min_lod.is_some() || matches!(lod, Lod::Base { min: Some(_), .. }); - let offset = match offset { - None => None, - Some(Offset::Const(k)) => Some(k.clone()), - Some(Offset::Dynamic(..)) => return Ok(None), - }; - if clamped || observed { - return Ok(None); - } - let word = match (slot, argument) { - (Some(sampler), _) => Some(LinearState::Slot { - sampler, - axes: axes as u8, - }), - (None, Some(sampler)) => Some(LinearState::Argument { - sampler, - axes: axes as u8, - }), - (None, None) => None, - }; - let s = match (state, word) { - (Some(s), _) if reaches(&s) => s, - (None, Some(state)) => { - let l = Linear { - image: texture, - state, - offset, - raw: false, - cube: match shape.dim { - ImageDim::Cube => Some(super::face::plan(cx)?), - _ => None, - }, - compare, - fetch: None, - exact_only: metal_sampler && shape.dim != ImageDim::Cube, - native: false, - }; - let l = Linear { - native: super::native::planned(cx, &l, shape), - ..l - }; - cx.families - .sampler - .bicubic_routines - .extend(l.routines().iter().copied()); - cx.families.access.heap_class |= texture == LinearImage::Heap; - return Ok(Some(l)); - } - _ => return Ok(None), - }; - if shape.dim == ImageDim::Cube { - let LinearImage::Slot(texture) = texture else { - return Ok(None); - }; - return cube::select(cx, texture, &s, compare); - } - let modes: Vec = [s.address_s, s.address_t, s.address_r] - .into_iter() - .take(axes) - .collect(); - let border = s.border_color; - let address = modes - .iter() - .map(|m| match m { - AddressMode::ClampToEdge => TapAddress::Edge, - AddressMode::Repeat => TapAddress::Repeat, - AddressMode::MirroredRepeat => TapAddress::Mirror, - AddressMode::ClampToZero | AddressMode::ClampToBorder => TapAddress::Border, - }) - .collect(); - let l = Linear { - image: texture, - state: LinearState::Constant { - address, - border, - pixel: s.coordinates == Coordinates::Pixel, - }, - offset, - raw: false, - cube: None, - compare, - fetch: None, - exact_only: metal_sampler, - native: false, - }; - let l = Linear { - native: super::native::planned(cx, &l, shape), - ..l - }; - cx.families - .sampler - .bicubic_routines - .extend(l.routines().iter().copied()); - cx.families.access.heap_class |= texture == LinearImage::Heap; - Ok(Some(l)) -} /// The note of sample `op` of `image` through `sampler` (`None`: an argument buffer's) with -/// texel form `form`, where a device without `VkProperty::MetalSampler` filters it: -/// `PrecisionNote::HalfSampleFilter` for a `half` result, `PrecisionNote::FloatSampleFilter` for a -/// `float` one (a depth texture's and a comparison's included); `None` for a sample that is not -/// filtered (a constexpr sampler that reads one texel of one level, [`unfiltered`]), one of another -/// result, and every sample on a device with the property but a slot's under its YCbCr variant, -/// whose filter the device's is not, and a slot's whose two-plane YCbCr format the profile leaves -/// to Metal's own sampler. Where it holds is [`filter_when`]'s, for such a slot -/// [`metal_filtered_ycbcr`]'s. +/// texel form `form` where Metal's own sampler (`VkProperty::MetalSampler`) filters it otherwise +/// than Metal filters the format bound there, with the clauses under which it holds +/// ([`metal_filtered_ycbcr`]): `PrecisionNote::HalfSampleFilter` for a `half` result, +/// `PrecisionNote::FloatSampleFilter` for a `float` one (a depth texture's and a comparison's +/// included); `None` for a sample that is not filtered (a constexpr sampler that reads one texel +/// of one level, [`unfiltered`]), one of another result, a heap texture's, and every sample on a +/// device that samples natively, whose module records `PrecisionNote::DeviceSampling` instead. pub(super) fn filter_note( cx: &SelectCx<'_>, op: &SampleOp, form: Option, (sampler, image): (Option, ImageRef), -) -> Result, Error> { +) -> Result)>, Error> { if !matches!(op, SampleOp::Sample { .. }) { return Ok(None); } @@ -696,15 +102,11 @@ pub(super) fn filter_note( return Ok(None); } } - let metal = cx.profile.device_samples(); - let device_metal = metal - && !crate::lower::texture::ycbcr_slot(cx, image)? - && metal_filtered_ycbcr(cx, image).is_none(); - Ok((!device_metal).then_some(note)) + Ok(metal_filtered_ycbcr(cx, image).map(|when| (note, when))) } -/// On a device that samples through Metal's own sampler (`VkProperty::MetalSampler`) under -/// `YCbCrFilterPolicy::Device` (no `ProfileFields::ycbcr_variant`), the clauses under which a +/// On a device that samples through Metal's own sampler (`VkProperty::MetalSampler`), the clauses +/// under which a /// filtered sample of texture slot `image` is not Metal's filter of the format bound there: where /// that format is two-plane YCbCr (its class's `TexelFormat::PACKED` field one of /// [`PackedTexels::YCbCr2048`], [`PackedTexels::YCbCr8192`] and @@ -712,17 +114,18 @@ pub(super) fn filter_note( /// sampler then filters as an `RGBA16Float` or `RGBA32Float` texture's texels, not on the format's /// own grid. The runtime reads the bound format (`SpecKey::BoundTexelFormat`) and announces it as /// `ycbcr-filter-not-exact`, through a runtime sampler whatever its word states. `None` on any -/// other device or profile, and for a heap's texture, which never takes the variant. +/// other device, and for a heap's texture. pub(super) fn metal_filtered_ycbcr(cx: &SelectCx<'_>, image: ImageRef) -> Option> { let ImageRef::Slot(index) = image else { return None; }; - let fields = cx.profile.fields(); - let metal = fields + let metal = cx + .profile + .fields() .enabled .properties .contains(&crate::device::requirements::VkProperty::MetalSampler); - (metal && !fields.ycbcr_variant).then(|| { + metal.then(|| { any_of( [ PackedTexels::YCbCr2048, @@ -734,195 +137,6 @@ pub(super) fn metal_filtered_ycbcr(cx: &SelectCx<'_>, image: ImageRef) -> Option }) } -/// Where the filter note ([`filter_note`]) of a sample through `sampler` (`None`: an argument -/// buffer's) holds, its emulation `linear` as the caller settled it: the clauses under which the -/// specialized module runs an arm that is not Metal's filter. -/// -/// - No emulation: the device filters. Through a runtime sampler slot, wherever its word filters -/// ([`word_filters`]); otherwise always. -/// - A raw emulation (an 8-bit sRGB slot's variant): the raw codes' exact sums, in 1D, 2D, and 3D. -/// Through a constexpr sampler it has no device arm, so never; through a runtime sampler slot the -/// device filters the decoding view where the word filters but the emulation does not reach it. -/// - Otherwise the emulation runs where the class names a measured family (for a cube, not a -/// packed normalized format's, `TexelFormat::packed_exact`) and, through a runtime sampler, the -/// word states a filter the emulation reaches (`reaches_word`); the device's arm runs -/// elsewhere. In 3D a half-float and a 32-bit float format's emulated sums keep a residue, so the -/// note holds wherever the class is not normalized. -pub(super) fn filter_when(linear: Option<&Linear>, sampler: Option) -> Vec { - let always = || vec![NoteClause::new()]; - let Some(l) = linear else { - return match sampler { - Some(SamplerRef::Slot(n)) => word_filters(n), - _ => always(), - }; - }; - // A heap texture's class is its handle's, which no specialization states. - let LinearImage::Slot(texture) = l.image else { - return always(); - }; - if l.raw { - return device_arm(l, texture, None); - } - let class: NoteClause = match l.cube.is_none() && l.plane_axes() == 3 { - true => [NoteTest::equal( - NoteOn::Texel(texture), - BicubicTexels::EXACT, - 0, - )] - .into(), - false => crate::lower::texture::unmeasured_class(texture), - }; - device_arm(l, texture, Some(class)) -} - -/// Where the device's arm of emulation `l` runs: the clauses under which the specialized module -/// hands the sample to the device's filter, at the device's position of the coordinate, rather than -/// summing Metal's taps (whose sums [`filter_when`] says where may keep a residue). A raw emulation -/// (an 8-bit sRGB slot's variant) runs it, through a runtime sampler slot, where the word filters -/// but the emulation does not reach it, and through a constexpr sampler never; another runs it -/// where the class names no measured family (for a cube, also a packed normalized format's, -/// `TexelFormat::packed_exact`; under [`Linear::exact_only`], wherever the class is not `EXACT`) -/// and, through a runtime sampler slot, where the word filters but states a filter or an address -/// mode the emulation does not reach (`reaches_word`). A heap texture's runs wherever it is -/// sampled: its class is its handle's, which no specialization states. -pub(super) fn device_when(l: &Linear) -> Vec { - let LinearImage::Slot(texture) = l.image else { - return vec![NoteClause::new()]; - }; - let class = (!l.raw).then(|| match l.exact_only { - true => [NoteTest::equal( - NoteOn::Texel(texture), - BicubicTexels::EXACT, - 0, - )] - .into(), - false => crate::lower::texture::unmeasured_class(texture), - }); - device_arm(l, texture, class) -} - -/// Where a raw emulation `l` through a runtime sampler slot hands its sample to the device's -/// decoding view (`PrecisionNote::SrgbTexelDecode`): where the word does not reach the emulation -/// and filters, since a word that reads one texel samples the slot's raw view ([`Linear::fetch`]); -/// a cube's (no such view) wherever the word does not reach it. Never for another emulation. -pub(super) fn decode_when(l: &Linear) -> Vec { - match (&l.state, l.raw, &l.cube) { - // A word that reads one texel samples the raw view ([`emit`], [`emit_shared`]): the - // device decodes only where the word filters too. - (LinearState::Slot { sampler, .. }, true, None) => { - both(&unreached(l, *sampler), &word_filters(*sampler)) - } - (LinearState::Slot { sampler, .. }, true, Some(_)) => unreached(l, *sampler), - _ => Vec::new(), - } -} - -/// The clauses of emulation `l`'s device arm of texture slot `texture`, `class` the clause of the -/// classes it hands the device (none for a raw emulation, whose class the variant fixes; -/// [`filter_when`], [`device_when`]). A runtime sampler's word that does not reach the emulation -/// hands it the classes it takes, so each such clause also tests the texture's class outside -/// `class` (the same condition: the classes `class` names hold anyway): every clause names the -/// texture slot it holds for, which the runtime's announcement names by the format bound there -/// (`ycbcr-filter-not-exact` for a two-plane YCbCr one). -fn device_arm(l: &Linear, texture: u32, class: Option) -> Vec { - let taken: Option = match class.as_ref().map(|c| c.iter().collect::>()) { - Some(tests) => match tests[..] { - [&test] => Some( - [NoteTest { - equal: !test.equal, - ..test - }] - .into(), - ), - _ => None, - }, - None => None, - }; - let mut classes: Vec = class.into_iter().collect(); - // A cube's device arm also runs on a packed normalized format (`TexelFormat::packed_exact`). - if l.cube.is_some() && !l.raw { - let on = NoteOn::Texel(texture); - classes.push( - [ - NoteTest::differ(on, BicubicTexels::EXACT, 0), - NoteTest::differ(on, TexelFormat::PACKED_MASK, 0), - ] - .into(), - ); - } - match &l.state { - LinearState::Constant { .. } => classes, - LinearState::Slot { sampler, .. } => { - let unreached = unreached(l, *sampler); - let mut device = match taken { - Some(taken) => both(&unreached, &[taken]), - None => unreached, - }; - device.extend(classes); - both(&word_filters(*sampler), &device) - } - // An argument buffer's sampler samples only heap textures, whose notes hold always. - LinearState::Argument { .. } => vec![NoteClause::new()], - } -} - -/// Where runtime sampler slot `sampler`'s word does not reach emulation `l` (`reaches_word`): a -/// filter other than Metal's linear one (for a cube, or pixel coordinates); a mip filter, but on -/// a texture slot's class whose textures have one level (`PackedTexels::one_level`; not for a raw -/// emulation, whose class is an sRGB format's, nor a cube); or, where the emulation does not reach -/// it ([`Linear::mirror_clamp_reached`]), `MirrorClampToEdge` on a plane axis. -fn unreached(l: &Linear, sampler: u32) -> Vec { - let on = NoteOn::Sampler(sampler); - let mask = match l.cube { - Some(_) => SamplerWord::LINEAR_FILTER | SamplerWord::PIXEL_COORDINATES, - None => SamplerWord::LINEAR_FILTER, - }; - let mut mipped: NoteClause = [NoteTest::differ(on, SamplerWord::MIP_FILTER, 0)].into(); - if let Some(texture) = one_level_slot(l) { - mipped.extend(one_level_fields().map(|field| { - NoteTest::differ(NoteOn::Texel(texture), TexelFormat::PACKED_MASK, field) - })); - } - let mut clauses = vec![ - [NoteTest::differ( - on, - mask & !SamplerWord::MIP_FILTER, - SamplerWord::LINEAR, - )] - .into(), - mipped, - ]; - if !l.mirror_clamp_reached() { - let unmeasured = SamplerAddressMode::MirrorClampToEdge.as_raw(); - clauses.extend(any_of( - SamplerWord::ADDRESS_SHIFT - .into_iter() - .take(l.plane_axes()) - .map(|shift| NoteTest::equal(on, 0b111 << shift, unmeasured << shift)), - )); - } - clauses -} - -/// The texture slot whose class states whether emulation `l` reaches a runtime sampler's mip -/// filter (`PackedTexels::one_level`): a slot's, but not a raw emulation's, whose class is an 8-bit -/// sRGB format's, nor a cube's. -fn one_level_slot(l: &Linear) -> Option { - match (l.image, l.raw, &l.cube) { - (LinearImage::Slot(texture), false, None) => Some(texture), - _ => None, - } -} - -/// The values of the [`TexelFormat::PACKED`] field, in place, of the classes whose textures have -/// one level (`PackedTexels::one_level`). -fn one_level_fields() -> impl Iterator { - PackedTexels::ALL - .into_iter() - .filter(|p| p.one_level()) - .map(|p| p.class().0) -} - /// Where runtime sampler slot `n`'s word states a sampler that filters: a linear minification or /// magnification filter, a linear mip filter, or anisotropy, any of which [`unfiltered`]'s single /// texel of one level excludes. @@ -951,936 +165,6 @@ pub(crate) fn unfiltered(s: &SamplerState) -> bool { && s.max_anisotropy <= 1 } -/// Whether sampler `s`'s filter is the one measured: linear minification and magnification, no -/// mip filter, and no anisotropy. -fn reaches(s: &SamplerState) -> bool { - s.min_filter == Filter::Linear - && s.mag_filter == Filter::Linear - && s.mip_filter == MipFilter::None - && s.max_anisotropy <= 1 -} - -/// The texel of the linear sample `s` (image facts `image`, a combined binding), emulated by `l` -/// (module docs) where the slot's bound format is measured, else `device`'s sample of the -/// binding's sampled image (a `vec4` of `f32`), converted as a sample's for a `half` result: a -/// branch on the slot's `TexelFormat` specialization, so only one of them runs, and once a device -/// specializes the module the other is dead. A raw emulation runs alone through a constexpr -/// sampler, and through a runtime sampler where its word reaches it; elsewhere the device samples -/// the slot's raw view where the word reads one texel, decoded through Metal's table, and the -/// binding's decoding view otherwise. Each arm loads the binding's sampled image, which is consumed -/// in the block that loads it, or a cube's emulation the slot's 2D-array view at `plane`, the -/// direction the device's sample reads (its ties broken as Metal breaks them). A `half` result is -/// the held `half` texel. -pub(super) fn emit( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - s: &Sampling, - (plane, image, dref): (SValue, CombinedImage, Option), - l: &Linear, - device: &dyn Fn(&mut FunctionBuilder<'_>, SValue) -> BResult, - native: Option, -) -> BResult { - let half = half_result(cx, s)?; - let LinearImage::Slot(texture) = l.image else { - return Err(cx.fail("a heap texture's linear sample 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 Source::Combined(key) = s.source else { - return Err(cx.fail("a linear sample of a heap element")); - }; - // The combined binding, or its separate texture and sampler: each arm makes the sampled image - // in its own block, where it is consumed. - let Some(&(binding, _)) = cx.decl.families.sampler.combined.get(&key) else { - return Err(cx.fail(format!("combined binding {key:?} is not declared"))); - }; - let t = Tys::new(fb)?; - let word = state_word(cx, fb, l)?; - // The emulation is its shape's routine, called with the sample's plain data (`routine`). - let (routine, args) = emulation(cx, fb, s, (plane, dref), spec)?; - // A constexpr sampler's raw emulation has no device arm. - if let (true, None) = (l.raw, word) { - return fb - .call(routine, &args)? - .ok_or_else(bicubic::missing_routine); - } - let h = match (half, s.half_texel) { - (true, true) => match s - .texel - .and_then(|form| half_class(cx, &ImageRef::Slot(texture), form)) - { - Some(h) => Some(HalfArm::Class(h)), - None => return Err(cx.fail(format!("texture slot {texture} has no `half` conversion"))), - }, - (true, false) => Some(HalfArm::Device), - (false, _) => None, - }; - // A raw emulation's class is its variant's, an 8-bit sRGB format's, whose sum is measured: - // a runtime sampler's runs where its word reaches it. - let measured = match (l.raw, word) { - (true, Some(word)) => reaches_word(fb, &t, l, word, None)?, - _ => { - let measured = flag(fb, &t, spec, l.measured())?; - // A packed normalized format's cube sample is not measured - // (`TexelFormat::packed_exact`). - let measured = match l.cube { - Some(_) => { - let exact = flag(fb, &t, spec, BicubicTexels::EXACT)?; - let packed = flag(fb, &t, spec, TexelFormat::PACKED_MASK)?; - let packed = fb.binary(BinOp::LogicalAnd, exact, packed)?; - let other = fb.unary(UnOp::LogicalNot, packed)?; - fb.binary(BinOp::LogicalAnd, measured, other)? - } - None => measured, - }; - reached(fb, &t, l, word, (measured, Bits::Spec(spec)))? - } - }; - // A native class's sample is the device's, at Metal's footprint step (`native`). - let measured = without_native(fb, measured, native)?; - // The emulation: its routine's call. - let emulated: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, _| { - let x = fb - .call(routine, &args)? - .ok_or_else(bicubic::missing_routine)?; - Ok(ArmEnd::FallThrough(vec![x])) - }); - // The device's sample, which reads one texel where a runtime sampler's word states nearest - // filters: its `half` or `float` texel converts by the class with the sample's lanes. There a - // 32-bit float texel the shader fetches instead. - let nearest = s - .fetched - .as_ref() - .filter(|p| p.image.slot() == Some(texture)); - let float = match s.float_texel { - true => match s - .texel - .and_then(|form| crate::lower::texture::float_class(cx, &ImageRef::Slot(texture), form)) - { - Some(f) => Some(f), - None => return Err(cx.fail("a `float` sample without its conversion routine")), - }, - false => None, - }; - let filtered: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| { - let x = match nearest { - Some(p) => super::fetched::branch( - cx, - fb, - (s, key), - (texture, &p.fetch, BicubicTexels::LINEAR, true), - image, - &super::fetched::one, - device, - )?, - None => { - let si = binding.sampled_image(fb)?; - device(fb, si)? - } - }; - // Under the slot's twin variant the device sampled the codes: decoded through the table, - // exactly where the sampler read one texel. - let x = match s.srgb_codes { - true => { - let four = crate::lower::texture::TexelForm { - lanes: 4, - conv: crate::lower::texture::TexelConv::F32, - }; - let color = crate::lower::texture::SRGB_TEXEL; - crate::lower::texture::srgb_filtered_texel(cx, fb, four, x, color)? - } - false => x, - }; - let x = match (h, float) { - (Some(HalfArm::Class(h)), _) => { - let lanes = super::emit::sample_lanes(cx, fb, s)?; - h.convert( - fb, - x, - (HalfForm::Sample, lanes), - crate::lower::texture::half::TexelOrigin::Computed, - )? - } - // The device's texel rounded to nearest even. - (Some(HalfArm::Device), _) => { - use crate::lower::arith::legal::{FloatFmt, Form, Held}; - let half = Form { - held: Held::Float(FloatFmt::Half), - lanes: 4, - }; - crate::lower::arith::narrow::round_texel(fb, half, x)? - } - (None, Some(f)) => { - let lanes = super::emit::sample_lanes(cx, fb, s)?; - f.convert(fb, x, lanes)? - } - (None, None) => x, - }; - Ok(ArmEnd::FallThrough(vec![x])) - }); - // A raw emulation's device arm, where the runtime sampler's word reads one texel (nearest - // minification and magnification, no linear mip filter, isotropic): the device's sample of the - // slot's raw view, through the same sampler, reads that texel's code, which Metal's table - // decodes exactly, as a constexpr nearest sample's raw read does. Every other word samples the - // decoding view ([`decode_when`]). Under the slot's twin variant the decoding view holds the - // codes already. - let device_arm: ArmFn<'_, EmitCx<'_>> = match (l.raw, word, &l.cube, s.srgb_codes) { - (true, Some(word), None, false) => { - let (Some(raw_key), Some(form)) = (l.fetch, s.texel) else { - return Err(cx.fail("a raw sample's device arm without its raw view")); - }; - let Some(&(raw_binding, _)) = cx.decl.families.sampler.combined.get(&raw_key) else { - return Err(cx.fail(format!("raw binding {raw_key:?} is not declared"))); - }; - let raw: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| { - let si = raw_binding.sampled_image(fb)?; - let x = device(fb, si)?; - let color = crate::lower::texture::SRGB_TEXEL; - let x = crate::lower::texture::srgb_raw_texel(cx, fb, form, x, color)?; - Ok(ArmEnd::FallThrough(vec![x])) - }); - one_texel_arm(word, raw, filtered) - } - _ => filtered, - }; - let Merged(merged) = fb.if_(cx, measured, emulated, Some(device_arm))?; - match merged[..] { - [x] => Ok(x), - _ => Err(cx.fail("a linear sample's branch without its texel")), - } -} - -/// A raw emulation's device arm through runtime sampler word `word`: `raw`'s texel (the device's -/// sample of the slot's raw view, decoded through Metal's table) where the word reads one texel -/// (`compared::one_texel`), else `filtered`'s (the device's sample of the decoding view). -fn one_texel_arm<'a, 'c: 'a>( - word: SValue, - raw: ArmFn<'a, EmitCx<'c>>, - filtered: ArmFn<'a, EmitCx<'c>>, -) -> ArmFn<'a, EmitCx<'c>> { - Box::new(move |fb, cx| { - let t = Tys::new(fb)?; - let (one, _) = super::compared::one_texel(fb, &t, word)?; - let Merged(merged) = fb.if_(cx, one, raw, Some(filtered))?; - match merged[..] { - [x] => Ok(ArmEnd::FallThrough(vec![x])), - _ => Err(cx.fail("a raw sample's device arm without its texel")), - } - }) -} - -/// The gathered texel of cube gather `s` by `g` (`cube`) of channel `component`, along `plane` (the -/// direction, its ties broken as Metal breaks them), a comparison's against reference `dref`. An -/// integer result's and a raw gather's are the emulation's alone. A `float` or `half` result's, a -/// depth texture's and a comparison's included, branch on the slot's `TexelFormat` specialization: -/// the emulation where the bound format's corner rule is measured (`BicubicTexels::EXACT`, -/// `LINEAR`, or `HALF`, or a `TexelFormat::CORNER` field), else `device`'s gather of the combined -/// binding's sampled image, which each arm makes in its own block; once a device specializes the -/// module the other arm is dead. A raw gather's value is its held texel; any other's is the texel a -/// device gather returns (a `vec4` of the view's sampled type), which the caller converts. -pub(super) fn gather( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - s: &Sampling, - (plane, component, dref): (SValue, u32, Option), - g: &CubeGather, - device: &dyn Fn(&mut FunctionBuilder<'_>, SValue) -> BResult, -) -> BResult { - let t = Tys::new(fb)?; - let at = (plane, component, dref); - if g.integer { - return cube::gather(cx, fb, &t, s, g, at, None); - } - let Some(spec) = crate::lower::texture::texel_format_const(cx, g.texture) else { - return Err(cx.fail(format!( - "texture slot {} has no `TexelFormat` specialization", - g.texture - ))); - }; - if g.raw { - return cube::gather(cx, fb, &t, s, g, at, Some(spec)); - } - let Source::Combined(key) = s.source else { - return Err(cx.fail("a cube gather of a heap element")); - }; - let Some(&(binding, _)) = cx.decl.families.sampler.combined.get(&key) else { - return Err(cx.fail(format!("combined binding {key:?} is not declared"))); - }; - let measured = flag( - fb, - &t, - spec, - BicubicTexels::EXACT - | BicubicTexels::LINEAR - | BicubicTexels::HALF - | TexelFormat::CORNER_MASK, - )?; - let t = &t; - let emulated: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| { - let x = cube::gather(cx, fb, t, s, g, at, Some(spec))?; - Ok(ArmEnd::FallThrough(vec![x])) - }); - let gathered: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, _| { - let si = binding.sampled_image(fb)?; - Ok(ArmEnd::FallThrough(vec![device(fb, si)?])) - }); - let Merged(merged) = fb.if_(cx, measured, emulated, Some(gathered))?; - match merged[..] { - [x] => Ok(x), - _ => Err(cx.fail("a cube gather's branch without its texel")), - } -} - -/// The texel of the linear sample `s` shared by the arms of a switch-at-use (SEMANTICS 1012): -/// [`emit`]'s branch on the named candidate's format bits `bits` (its `TexelFormat` -/// specialization, which `c`'s arms yield), the emulation on its level-0 size `size` (image facts -/// `image`) with its taps read by `c`'s arms, or `device`'s sample of its sampled image read by -/// `c`'s arms (the null arm's a zero), converted as a sample's for a `half` result by the bits. -pub(super) fn emit_shared( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - s: &Sampling, - (size, image, dref): (SValue, CombinedImage, Option), - l: &Linear, - (bits, c): (SValue, &super::Candidates<'_>), - device: &dyn Fn(&mut FunctionBuilder<'_>, SValue) -> BResult, - native: Option, -) -> BResult { - let half = half_result(cx, s)?; - let t = Tys::new(fb)?; - let bits = Bits::Value(bits); - let word = state_word(cx, fb, l)?; - let shared = |cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, t: &Tys| { - let Some(taps) = l.taps(word) else { - return Err(cx.fail("a runtime sampler's linear sample without its word")); - }; - let fp = footprint_on(cx, fb, t, s, (size, image), bits, &taps)?; - sum( - cx, - fb, - (t, &fp), - (l, word), - (bits, half, dref), - Texels::Candidates(c), - ) - }; - // A raw emulation's class is its variant's: a constexpr sampler's has no device arm, and a - // runtime sampler's runs where its word reaches it. - let measured = match (l.raw, word) { - (true, None) => return shared(cx, fb, &t), - (true, Some(word)) => reaches_word(fb, &t, l, word, None)?, - (false, _) => { - let measured = bits.test(fb, &t, l.measured())?; - reached(fb, &t, l, word, (measured, bits))? - } - }; - let measured = without_native(fb, measured, native)?; - let t = &t; - let shared = &shared; - let emulated: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| { - let x = shared(cx, fb, t)?; - Ok(ArmEnd::FallThrough(vec![x])) - }); - let filtered: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| { - let read = |cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, a: &Sampling| { - let si = c.sampled_image(cx, fb, a)?; - Ok(vec![device(fb, si)?]) - }; - // A comparison's device sample is a scalar. - let null = |_: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>| { - let ty = match dref { - Some(_) => fb.module().ty(SType::Float { width: 32 })?, - None => t.vec4, - }; - let z = fb.module().constant(Constant::Null { ty })?; - Ok(vec![value(fb, z)?]) - }; - let [x] = c.each(cx, fb, &read, &null)?[..] else { - return Err(cx.fail("a shared linear sample's device texel")); - }; - let x = match (half, bits) { - (true, Bits::Value(class)) => { - crate::lower::texture::half_by_class(cx, fb, x, class, HalfForm::Sample)? - } - _ => x, - }; - Ok(ArmEnd::FallThrough(vec![x])) - }); - // A raw emulation's device arm reads each arm's raw view where the word reads one texel, as - // [`emit`]'s does; a null arm's zero decodes to zero. - let device_arm: ArmFn<'_, EmitCx<'_>> = match (l.raw, word, &l.cube, s.srgb_codes) { - (true, Some(word), None, false) => { - let (Some(_), Some(form)) = (l.fetch, s.texel) else { - return Err(cx.fail("a shared raw sample's device arm without its raw view")); - }; - let raw: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| { - let read = |cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, a: &Sampling| { - let si = c.fetch_sampled_image(cx, fb, a)?; - Ok(vec![device(fb, si)?]) - }; - let null = |_: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>| { - let z = fb.module().constant(Constant::Null { ty: t.vec4 })?; - Ok(vec![value(fb, z)?]) - }; - let [x] = c.each(cx, fb, &read, &null)?[..] else { - return Err(cx.fail("a shared raw sample's device texel")); - }; - let color = crate::lower::texture::SRGB_TEXEL; - let x = crate::lower::texture::srgb_raw_texel(cx, fb, form, x, color)?; - Ok(ArmEnd::FallThrough(vec![x])) - }); - one_texel_arm(word, raw, filtered) - } - _ => filtered, - }; - let Merged(merged) = fb.if_(cx, measured, emulated, Some(device_arm))?; - match merged[..] { - [x] => Ok(x), - _ => Err(cx.fail("a linear sample's branch without its texel")), - } -} - -/// The texel of the linear sample `s` of a heap texture (image facts `image`), emulated by `l` -/// (module docs) where the class its handle carries names a measured family and, through a runtime -/// or argument buffer's sampler, the word states a filter the emulation reaches, else `device`: the -/// device's sample as the function converts it (its held texel; a depth texture's first component). -/// The device's sample runs before the branch, in the function's own control flow; the emulation's -/// arm loads the heap element again, whose sampled image it consumes in its own block, and fetches -/// its taps from the element's image. -pub(super) fn emit_heap( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - s: &Sampling, - image: CombinedImage, - l: &Linear, - device: SValue, -) -> BResult { - let half = half_result(cx, s)?; - let handle = match s.source { - Source::Heap { handle, .. } | Source::HeapSampler { handle, .. } => handle, - Source::Combined(_) => return Err(cx.fail("a heap texture's linear sample of a slot")), - }; - let t = Tys::new(fb)?; - let h = cx.operand(fb, handle)?; - let bits = Bits::Value(crate::lower::texture::heap_texel_class(cx, fb, h)?); - let word = state_word(cx, fb, l)?; - let measured = bits.test( - fb, - &t, - BicubicTexels::EXACT | BicubicTexels::LINEAR | BicubicTexels::HALF, - )?; - let measured = reached(fb, &t, l, word, (measured, bits))?; - let t = &t; - let emulated: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| { - let Some(taps) = l.taps(word) else { - return Err(cx.fail("a runtime sampler's linear sample without its word")); - }; - let (si, _, _) = super::emit::sampled_image(cx, fb, s.source)?; - let (fp, img) = footprint(cx, fb, t, s, (si, image), bits, &taps)?; - let x = sum( - cx, - fb, - (t, &fp), - (l, word), - (bits, half, None), - Texels::Own(img), - )?; - // A depth texture's sample reads the first component. - let x = match s.depth { - true => fb.composite_extract(x, &[0])?, - false => x, - }; - Ok(ArmEnd::FallThrough(vec![x])) - }); - let kept: ArmFn<'_, EmitCx<'_>> = Box::new(move |_, _| Ok(ArmEnd::FallThrough(vec![device]))); - let Merged(merged) = fb.if_(cx, measured, emulated, Some(kept))?; - match merged[..] { - [x] => Ok(x), - _ => Err(cx.fail("a heap texture's linear sample without its texel")), - } -} - -/// The routine of linear sample `s`'s emulated arm (`routine::Emulation`), defined at its shape's -/// first call, and its call's arguments: the coordinate and the array layer as the sample states -/// them, a cube's direction `plane` (its ties broken as Metal breaks them), a comparison's -/// reference `dref`, each computed in the sample's own position, the constant texel offset where a -/// lane is off zero, and the value of the slot's `TexelFormat` specialization `spec`, which a -/// function reads as data, so a routine takes it as its other routines do. -fn emulation( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - s: &Sampling, - (plane, dref): (SValue, Option), - spec: ConstId, -) -> BResult<(FuncId, Vec)> { - let Some(e) = Emulation::of(s) else { - return Err(cx.fail("a linear sample without its emulation's shape")); - }; - if e.linear.compare.is_some() != dref.is_some() { - return Err(cx.fail("a linear comparison without its reference")); - } - let at = At::of(cx, fb, s)?; - let mut args = vec![at.coord]; - args.extend(at.layer); - if e.linear.cube.is_some() { - args.push(plane); - } - args.extend(dref); - if e.offset.is_some() { - let Some(o) = s.linear.as_ref().and_then(|l| l.offset.as_deref()) else { - return Err(cx.fail("a linear sample's routine without its offset")); - }; - args.push(super::emit::const_offset(fb, o)?); - } - args.push(fb.module().const_value(spec)?); - let mut tys = Vec::with_capacity(args.len()); - for &a in &args { - tys.push(fb.value_ty(a)?); - } - let shape = Shape::Emulation(e); - if let Some(f) = cx.sampling.get(&shape, &tys) { - return Ok((f, args)); - } - let Shape::Emulation(e) = &shape else { - return Err(cx.fail("a linear sample's routine of another shape")); - }; - let mut rcx = cx.for_new_function(); - let made = define_emulation(&mut rcx, fb.module(), e, (&tys, at.parent)); - cx.adopt(rcx); - let f = made?; - cx.sampling.insert(shape, tys, f); - Ok((f, args)) -} - -/// Define the routine of emulated arm `e` (`routine::Emulation`) in `mb`, its parameters of -/// types `tys` in [`emulation`]'s order, its offset placed by the slot's tests `parent` where `e` -/// reads them: the texel the arm's code gave inline, read from `e`'s bindings and specializations -/// and the bound format's bits its last parameter carries. -fn define_emulation( - cx: &mut EmitCx<'_>, - mb: &mut ModuleBuilder, - e: &Emulation, - (tys, parent): (&[TypeId], Option), -) -> BResult { - let l = &e.linear; - let Some(&(_, image)) = cx.decl.families.sampler.combined.get(&e.own) else { - return Err(cx.fail(format!("combined binding {:?} is not declared", e.own))); - }; - // The taps' binding: a comparison's without comparison, a runtime sampler's raw view, else - // the sample's own. - let Some(&(taps, _)) = cx.decl.families.sampler.combined.get(&e.taps) else { - return Err(cx.fail(format!("combined binding {:?} is not declared", e.taps))); - }; - // A comparison's value is a scalar, every other the held texel (a `vec4`). - let f32_ = mb.ty(SType::Float { width: 32 })?; - let ret = match l.compare { - Some(_) => f32_, - None => mb.ty(SType::Vector { elem: f32_, len: 4 })?, - }; - let mut fb = mb.sampling_routine(ret)?; - let mut params = Vec::with_capacity(tys.len()); - for &ty in tys { - params.push(fb.param(ty)?); - } - // The coordinate, then the layer, a cube's direction, a comparison's reference and the - // offset, each where the shape takes it, and the format's bits. - let want = 2 - + usize::from(e.layer) - + usize::from(l.cube.is_some()) - + usize::from(l.compare.is_some()) - + usize::from(e.offset.is_some()); - let mut params = params.into_iter(); - let (Some(coord), true) = (params.next(), tys.len() == want) else { - return Err(cx.fail("a linear sample's routine without its parameters")); - }; - let layer = e.layer.then(|| params.next()).flatten(); - let plane = l.cube.and_then(|_| params.next()); - let dref = l.compare.and_then(|_| params.next()); - let offset = e.offset.and_then(|lanes| params.next().map(|v| (v, lanes))); - let Some(bits) = params.next().map(Bits::Value) else { - return Err(cx.fail("a linear sample's routine without its format's bits")); - }; - let at = At { - coord, - layer, - parent, - offset, - }; - let t = Tys::new(&mut fb)?; - let word = state_word(cx, &mut fb, l)?; - let x = match (l.cube, plane) { - (Some(face), Some(p)) => cube::emulate( - cx, - &mut fb, - &t, - layer, - (l, word), - (face, p), - (bits, e.half, dref), - )?, - _ => { - let si = taps.sampled_image(&mut fb)?; - emulate( - cx, - &mut fb, - &t, - &at, - (si, image), - (l, word), - (bits, e.half, dref), - )? - } - }; - fb.ret(Some(x))?; - fb.finish() -} - -/// `measured` (a `bool`: the emulation runs) where the native condition `native` (a `bool`, -/// `native::coordinate`'s) does not hold: a native class's sample is the device's. -fn without_native( - fb: &mut FunctionBuilder<'_>, - measured: SValue, - native: Option, -) -> BResult { - match native { - Some(n) => { - let other = fb.unary(UnOp::LogicalNot, n)?; - fb.binary(BinOp::LogicalAnd, measured, other) - } - None => Ok(measured), - } -} - -/// How the device arm of a linear sample with a `half` result converts the device's texel: by -/// the bound format's class, or, where the texel is the device's, its rounding to nearest even. -#[derive(Clone, Copy)] -enum HalfArm { - Class(crate::lower::texture::HalfClass), - Device, -} - -/// Whether the linear sample `s` has a `half` result. -fn half_result(cx: &mut EmitCx<'_>, s: &Sampling) -> BResult { - match s.texel { - Some(form) => Ok(form.conv == TexelConv::F16), - None => Err(cx.fail("a linear sample without a texel form")), - } -} - -impl Linear { - /// The taps the emulation reads: `i` and `i + 1` of each axis, addressed as a constexpr - /// sampler's state states, or as a runtime sampler's `word` does (`None` without one). - fn taps(&self, word: Option) -> Option> { - let addressing = match (&self.state, word) { - ( - LinearState::Constant { - address, - border, - pixel, - }, - _, - ) => Addressing::Modes { - address, - border: *border, - pixel: *pixel, - }, - (LinearState::Slot { axes, .. } | LinearState::Argument { axes, .. }, Some(word)) => { - Addressing::Word { - word, - axes: usize::from(*axes), - } - } - (LinearState::Slot { .. } | LinearState::Argument { .. }, None) => return None, - }; - Some(Taps { - addressing, - offset: self.offset.as_deref(), - span: &[0, 1], - base: TapBase::Quantized, - level: None, - }) - } -} - -/// The word of the runtime sampler `l`'s emulation follows (a `u32`, its slot's `SamplerState` -/// specialization, or an argument buffer's sampler's table entry's), or `None` for a constexpr -/// sampler's. -fn state_word( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - l: &Linear, -) -> BResult> { - match l.state { - LinearState::Constant { .. } => Ok(None), - LinearState::Slot { sampler, .. } => Ok(Some(super::emit::sampler_word( - cx, - fb, - super::Pixel::Spec(sampler), - )?)), - LinearState::Argument { sampler, .. } => Ok(Some(super::emit::sampler_word( - cx, - fb, - super::Pixel::Heap(sampler), - )?)), - } -} - -/// `measured` (a `bool`: the bound format's conversion is measured, its class `bits`), and for a -/// runtime sampler whether its `word` states a sampler the emulation `l` reaches on that class -/// (`reaches_word`). -fn reached( - fb: &mut FunctionBuilder<'_>, - t: &Tys, - l: &Linear, - word: Option, - (measured, bits): (SValue, Bits), -) -> BResult { - match word { - Some(word) => { - let reach = reaches_word(fb, t, l, word, Some(bits))?; - fb.binary(BinOp::LogicalAnd, measured, reach) - } - None => Ok(measured), - } -} - -/// Whether runtime sampler word `word` (a `u32`) states a sampler whose sample `l` the emulation -/// reaches on the bound format's class `bits` (a `bool`): the filter Metal's linear rule answers -/// ([`SamplerWord::LINEAR_FILTER`]), for a cube with normalized coordinates, but with any mip -/// filter on a class whose textures have one level, which Metal's mip filter leaves as it is -/// (`PackedTexels::one_level`; `None` for a raw emulation's, an sRGB format's); and for a cube or a -/// 3D texture, on each plane axis (a cube's face's `s` and `t`) an address mode other than -/// `MirrorClampToEdge`, which no probe measured there ([`Linear::mirror_clamp_reached`]). -fn reaches_word( - fb: &mut FunctionBuilder<'_>, - t: &Tys, - l: &Linear, - word: SValue, - bits: Option, -) -> BResult { - let u32_value = |fb: &mut FunctionBuilder<'_>, x: u32| -> BResult { - let c = scalar(fb, t.u32_, u64::from(x))?; - value(fb, c) - }; - let mask = match l.cube { - Some(_) => SamplerWord::LINEAR_FILTER | SamplerWord::PIXEL_COORDINATES, - None => SamplerWord::LINEAR_FILTER, - }; - let m = u32_value(fb, mask & !SamplerWord::MIP_FILTER)?; - let want = u32_value(fb, SamplerWord::LINEAR)?; - let have = fb.binary(BinOp::BitwiseAnd, word, m)?; - let mut reach = fb.binary(BinOp::IEqual, have, want)?; - let mip = u32_value(fb, SamplerWord::MIP_FILTER)?; - let mip = fb.binary(BinOp::BitwiseAnd, word, mip)?; - let zero = u32_value(fb, 0)?; - let mut levels = fb.binary(BinOp::IEqual, mip, zero)?; - if let (Some(bits), Some(_)) = (bits, one_level_slot(l)) { - let class = bits.value(fb)?; - let packed = u32_value(fb, TexelFormat::PACKED_MASK)?; - let field = fb.binary(BinOp::BitwiseAnd, class, packed)?; - for f in one_level_fields() { - let f = u32_value(fb, f)?; - let one = fb.binary(BinOp::IEqual, field, f)?; - levels = fb.binary(BinOp::LogicalOr, levels, one)?; - } - } - reach = fb.binary(BinOp::LogicalAnd, reach, levels)?; - if l.mirror_clamp_reached() { - return Ok(reach); - } - let unmeasured = u32_value(fb, SamplerAddressMode::MirrorClampToEdge.as_raw())?; - for shift in SamplerWord::ADDRESS_SHIFT.into_iter().take(l.plane_axes()) { - let mode = super::bicubic::word_field(fb, t, word, shift, 0b111)?; - let measured = fb.binary(BinOp::INotEqual, mode, unmeasured)?; - reach = fb.binary(BinOp::LogicalAnd, reach, measured)?; - } - Ok(reach) -} - -/// The emulation's texel (module docs) of sampled image `si` under the bound format's bits `bits`, -/// a `half` result when `half` ([`sum`]), its taps addressed by `l`'s state, a runtime sampler's -/// by its `word`, at the sample's plain data `at`. -fn emulate( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - t: &Tys, - at: &At, - (si, image): (SValue, CombinedImage), - (l, word): (&Linear, Option), - (bits, half, dref): (Bits, bool, Option), -) -> BResult { - let Some(taps) = l.taps(word) else { - return Err(cx.fail("a runtime sampler's linear sample without its word")); - }; - let (fp, img) = footprint_from(fb, t, at, (si, image), bits, &taps)?; - sum( - cx, - fb, - (t, &fp), - (l, word), - (bits, half, dref), - Texels::Own(img), - ) -} - -/// The emulation's texel (module docs) over footprint `fp` under the bound format's treatment -/// `bits`, a `half` result when `half`, its taps read from `texels`: the exact routine's for an -/// `EXACT` format, else the emulated routine's, both called with the -/// format's bits, which are the result for every format the emulation answers. A raw sample -/// (`l.raw`) reads an 8-bit sRGB format's raw codes: each tap's color lanes become the table's -/// steps (`srgb_raw_tap`), and the exact routine sums them on the sRGB grids, its flags the -/// specialization's (`UNORM`, `SRGB`, and the format's channels, which its border color reads) with -/// `EXACT`. A comparison (`l.compare`, against reference `dref`) compares each tap's depth -/// (`TapCompare`, a border's included) and sums the passes through the exact routine as -/// `compare::PASS_FORMAT`'s codes 0 and 255, whatever the bound format: its value is the sum's -/// first channel, a scalar. -fn sum( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - (t, fp): (&Tys, &Footprint), - (l, word): (&Linear, Option), - (bits, half, dref): (Bits, bool, Option), - texels: Texels<'_>, -) -> BResult { - // Each axis's taps `i` and `i + 1`. - let mut pairs: Vec<(SValue, [Tap; 2])> = Vec::with_capacity(fp.axes.len()); - for (k, row) in &fp.axes { - let &[a, b] = row.as_slice() else { - return Err(cx.fail("a linear footprint axis without two taps")); - }; - pairs.push((*k, [a, b])); - } - let compare = match (l.compare, dref) { - (Some(c), Some(r)) => Some(TapCompare::of(cx, fb, t, (c, word), (r, bits))?), - (None, None) => None, - _ => return Err(cx.fail("a linear comparison without its reference")), - }; - let flags = match (&compare, l.raw) { - (Some(_), _) => { - let pass = texel_format(compare::PASS_FORMAT).0; - let pass = scalar(fb, t.u32_, u64::from(pass))?; - value(fb, pass)? - } - (None, true) => { - let flags = bits.value(fb)?; - let exact = scalar(fb, t.u32_, u64::from(BicubicTexels::EXACT))?; - let exact = value(fb, exact)?; - fb.binary(BinOp::BitwiseOr, flags, exact)? - } - (None, false) => bits.value(fb)?, - }; - let h = bool_value(fb, t, half)?; - let vec4 = t.vec4; - let post = - |cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, v: SValue| match (&compare, l.raw) { - (Some(c), _) => { - let depth = fb.composite_extract(v, &[0])?; - let pass = c.pass(fb, depth)?; - fb.composite_construct(vec4, &[pass; 4]) - } - (None, true) => crate::lower::texture::srgb_raw_tap(cx, fb, v), - (None, false) => Ok(v), - }; - let call = |fb: &mut FunctionBuilder<'_>, f, args: &[SValue]| -> BResult { - fb.call(f, args)?.ok_or_else(bicubic::missing_routine) - }; - // The routines' arguments: a merged axis's fraction 0 (in 2D a float format's too). - let (exact, float, args) = match pairs.as_slice() { - [(k, [x0, x1])] => { - let Some(line) = cx.decl.families.sampler.linear_span else { - return Err(cx.fail("a 1D linear sample without its routines")); - }; - let mut args = texels.fetch(cx, fb, (t, fp), &[[*x0], [*x1]], &post)?; - args.extend([*k, flags, h]); - (line.exact, line.float, args) - } - [(kx, [x0, x1]), (ky, [y0, y1])] => { - let Some(quad) = cx.decl.families.sampler.linear_quad else { - return Err(cx.fail("a 2D linear sample without its routines")); - }; - let sites = [[*x0, *y0], [*x1, *y0], [*x0, *y1], [*x1, *y1]]; - let mut args = texels.fetch(cx, fb, (t, fp), &sites, &post)?; - args.extend([ - merged(fb, t, *kx, [*x0, *x1])?, - merged(fb, t, *ky, [*y0, *y1])?, - flags, - h, - ]); - (quad.exact, quad.float, args) - } - [(kx, [x0, x1]), (ky, [y0, y1]), (kz, [z0, z1])] => { - let Some(block) = cx.decl.families.sampler.linear_block else { - return Err(cx.fail("a 3D linear sample without its routines")); - }; - let mut sites = Vec::with_capacity(8); - for z in [*z0, *z1] { - for y in [*y0, *y1] { - for x in [*x0, *x1] { - sites.push([x, y, z]); - } - } - } - let mut args = texels.fetch(cx, fb, (t, fp), &sites, &post)?; - let kx = merged(fb, t, *kx, [*x0, *x1])?; - let ky = merged(fb, t, *ky, [*y0, *y1])?; - let kz = merged(fb, t, *kz, [*z0, *z1])?; - // A mirrored `t` axis's taps in the reflected half of its period run backwards: - // there Metal's first tap is the second; a runtime sampler's `t` axis mirrors where its - // word's mode does. - let flip = match (&l.state, fp.modes.get(1)) { - (LinearState::Constant { address, .. }, _) - if address.get(1) == Some(&TapAddress::Mirror) => - { - fb.binary(BinOp::UGreaterThan, y0.0, y1.0)? - } - (LinearState::Slot { .. } | LinearState::Argument { .. }, Some(&mode)) => { - let mirror = scalar(fb, t.u32_, super::bicubic::MIRROR_REPEAT)?; - let mirror = value(fb, mirror)?; - let mirrors = fb.binary(BinOp::IEqual, mode, mirror)?; - let back = fb.binary(BinOp::UGreaterThan, y0.0, y1.0)?; - fb.binary(BinOp::LogicalAnd, mirrors, back)? - } - _ => bool_value(fb, t, false)?, - }; - args.extend([kx, ky, kz, flip, flags, h]); - (block.exact, block.float, args) - } - _ => return Err(cx.fail("a linear sample without one, two, or three plane axes")), - }; - if compare.is_some() { - let e = call(fb, exact, &args)?; - return fb.composite_extract(e, &[0]); - } - if l.raw || l.exact_only { - return call(fb, exact, &args); - } - // One routine runs, by a branch on the class, where both ran and a select took one: a - // driver that keeps the routines as calls runs only the one the class takes, and one that - // inlines them folds the branch on the specialization as it folded the select. - 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(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(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 sum's branch without its texel")), - } -} - /// The fraction's steps `k` of an axis whose taps are `a` and `b`, or `0` where both are one /// texel (an index clamped or reflected onto its partner's, a level one texel wide, or both taps /// outside a border axis): Metal weighs such a pair `(256, 0)` before it rounds a 3D sample's @@ -1900,12 +184,3 @@ pub(super) fn merged( let zero = value(fb, zero)?; fb.select(same, zero, k) } - -/// The `bool` constant `b`. -fn bool_value(fb: &mut FunctionBuilder<'_>, t: &Tys, b: bool) -> BResult { - let c = fb.module().constant(Constant::Scalar { - ty: t.bool_, - bits: ConstBits(u64::from(b)), - })?; - value(fb, c) -} diff --git a/crates/metal2vulkan/src/lower/sampler/linear/compare.rs b/crates/metal2vulkan/src/lower/sampler/linear/compare.rs deleted file mode 100644 index 98deb9ec4..000000000 --- a/crates/metal2vulkan/src/lower/sampler/linear/compare.rs +++ /dev/null @@ -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), - (dref, bits): (SValue, Bits), - ) -> BResult { - 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 { - 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 { - 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 { - 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 { - 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 { - 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 { - 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 { - 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) -} diff --git a/crates/metal2vulkan/src/lower/sampler/linear/cube.rs b/crates/metal2vulkan/src/lower/sampler/linear/cube.rs deleted file mode 100644 index ec86e33de..000000000 --- a/crates/metal2vulkan/src/lower/sampler/linear/cube.rs +++ /dev/null @@ -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, -) -> Result, 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, - (l, word): (&Linear, Option), - (routines, p): (FaceRoutines, SValue), - (bits, half, dref): (Bits, bool, Option), -) -> BResult { - 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, - site: &Site, - (faces, post): (bool, &Post<'_>), -) -> BResult { - 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 { - 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 { - 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 { - 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 + '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, -} - -/// 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 { - 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, - (stat, image, shape): (Option<(SamplerRef, Coordinates)>, ImageRef, ImageShape), - observed: bool, -) -> Result, 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), - spec: Option, -) -> BResult { - // 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)) -} diff --git a/crates/metal2vulkan/src/lower/sampler/mod.rs b/crates/metal2vulkan/src/lower/sampler/mod.rs index aeb8ae2d1..dfb5cceca 100644 --- a/crates/metal2vulkan/src/lower/sampler/mod.rs +++ b/crates/metal2vulkan/src/lower/sampler/mod.rs @@ -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, - /// 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, /// A gather or nearest sample whose plane coordinate is snapped onto the texels Metal reads /// ([`position`]). pub snap: Option, @@ -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, - /// 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, - /// 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, - /// 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, /// 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 { 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, /// The texture slots a bicubic sample reads, each with its `BicubicTexels` specialization. pub bicubic: BTreeSet, - /// 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, - /// 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, @@ -1639,12 +1392,8 @@ pub struct Declared { pub bicubic_line: Option, /// The emulated linear 2D samples' routines, when the module has one. pub linear_quad: Option, - /// The emulated linear 1D samples' routines, when the module has one. - pub linear_span: Option, /// The emulated linear 3D samples' routines, when the module has one. pub linear_block: Option, - /// The emulated linear cube samples' fold and corner routines, when the module has one. - pub linear_cube: Option, /// 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, @@ -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, diff --git a/crates/metal2vulkan/src/lower/sampler/native.rs b/crates/metal2vulkan/src/lower/sampler/native.rs deleted file mode 100644 index bf4592537..000000000 --- a/crates/metal2vulkan/src/lower/sampler/native.rs +++ /dev/null @@ -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 { - let LinearImage::Slot(texture) = l.image else { - return Vec::new(); - }; - if !l.native || l.raw { - return Vec::new(); - } - let class: Vec = 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> { - 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> { - if !l.native || l.raw { - return Ok(None); - } - let t = Tys::new(fb)?; - let u32_value = |fb: &mut FunctionBuilder<'_>, x: u32| -> BResult { - 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 { - 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, -) -> BResult { - 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 { - let f = fb.module().ty(SType::Float { width: 32 })?; - let c = scalar(fb, f, u64::from(x.to_bits()))?; - value(fb, c) -} diff --git a/crates/metal2vulkan/src/lower/sampler/position.rs b/crates/metal2vulkan/src/lower/sampler/position.rs index 3afae328d..075b53f79 100644 --- a/crates/metal2vulkan/src/lower/sampler/position.rs +++ b/crates/metal2vulkan/src/lower/sampler/position.rs @@ -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>, - /// 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, 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 { - 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 { 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, - (kind, pixel): (AxisSnap, bool), - u: SValue, + kind: AxisSnap, + x: SValue, n: SValue, (address, offset, parent): (TapAddress, Option, Option), ) -> BResult { - 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], Option), - lanes: u8, - (size, base, size_lanes): (SValue, Option, u8), -) -> BResult { - 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) -> BResult { 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], Option), + word: SValue, + (given, scaled): (SValue, SValue), lanes: u8, (size, size_lanes): (SValue, u8), ) -> BResult { 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], Option), - lanes: u8, - (size, size_lanes): (SValue, u8), -) -> BResult { - 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; diff --git a/crates/metal2vulkan/src/lower/sampler/position/tests.rs b/crates/metal2vulkan/src/lower/sampler/position/tests.rs index 79ebdab26..9214d60dd 100644 --- a/crates/metal2vulkan/src/lower/sampler/position/tests.rs +++ b/crates/metal2vulkan/src/lower/sampler/position/tests.rs @@ -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 { let mut b = ModuleBuilder::new(); let f32_ = b.ty(Type::Float { width: 32 })?; @@ -94,13 +91,11 @@ fn kernel(address: TapAddress, offset: i32) -> BResult { 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 { 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 = 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 { - 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 { - let m = word_kernel(leveled).expect("kernel"); - let bytes: Vec = 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 = 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 { +/// 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 { 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 { 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 { } /// 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 = 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 = 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 { - 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 = 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 = 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 diff --git a/crates/metal2vulkan/src/lower/sampler/routine.rs b/crates/metal2vulkan/src/lower/sampler/routine.rs index 65c6e5fda..fe0560754 100644 --- a/crates/metal2vulkan/src/lower/sampler/routine.rs +++ b/crates/metal2vulkan/src/lower/sampler/routine.rs @@ -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, - /// 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 { - 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, - /// 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 { - 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 { - 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 { - 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) -> 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)] diff --git a/crates/metal2vulkan/src/lower/sampler/select.rs b/crates/metal2vulkan/src/lower/sampler/select.rs index b5dd52677..980ee5189 100644 --- a/crates/metal2vulkan/src/lower/sampler/select.rs +++ b/crates/metal2vulkan/src/lower/sampler/select.rs @@ -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 { - 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 { }) } -/// 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 { - 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 { + 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 = 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 { 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 diff --git a/crates/metal2vulkan/src/lower/sampler/shared.rs b/crates/metal2vulkan/src/lower/sampler/shared.rs index 94eb2c462..dc5f223eb 100644 --- a/crates/metal2vulkan/src/lower/sampler/shared.rs +++ b/crates/metal2vulkan/src/lower/sampler/shared.rs @@ -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 { - 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 { - 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 { - 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> { 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> { 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), 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), CombinedImage, Option), + (size, image): (SValue, CombinedImage), null: &NullLeaf<'_>, ) -> BResult { 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), CombinedImage, Option), + (size, image): (SValue, CombinedImage), bits: SValue, ) -> BResult { - 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) } diff --git a/crates/metal2vulkan/src/lower/texture/emit.rs b/crates/metal2vulkan/src/lower/texture/emit.rs index f5679a51a..94ae9860c 100644 --- a/crates/metal2vulkan/src/lower/texture/emit.rs +++ b/crates/metal2vulkan/src/lower/texture/emit.rs @@ -886,7 +886,7 @@ fn from_image( decl: &ImageDecl, form: TexelForm, x: SValue, - (half, float): (Option, Option), + half: Option, ) -> BResult { 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 { - 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 { - 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 { - 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 { - 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> { - 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 { 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. diff --git a/crates/metal2vulkan/src/lower/texture/float_texel.rs b/crates/metal2vulkan/src/lower/texture/float_texel.rs deleted file mode 100644 index e4d5c4e37..000000000 --- a/crates/metal2vulkan/src/lower/texture/float_texel.rs +++ /dev/null @@ -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 { - 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 { - 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 { - 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 { - // 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, - }) -} diff --git a/crates/metal2vulkan/src/lower/texture/half.rs b/crates/metal2vulkan/src/lower/texture/half.rs index 7c51e198c..8aa41ca78 100644 --- a/crates/metal2vulkan/src/lower/texture/half.rs +++ b/crates/metal2vulkan/src/lower/texture/half.rs @@ -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; diff --git a/crates/metal2vulkan/src/lower/texture/mod.rs b/crates/metal2vulkan/src/lower/texture/mod.rs index 4dc5f5cda..73220dd9f 100644 --- a/crates/metal2vulkan/src/lower/texture/mod.rs +++ b/crates/metal2vulkan/src/lower/texture/mod.rs @@ -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, - /// 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, /// 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 { - 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, 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 { - 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 { - 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 impl Iterator { - 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, diff --git a/crates/metal2vulkan/src/lower/texture/slot.rs b/crates/metal2vulkan/src/lower/texture/slot.rs index 9a8b0c653..c9f8953b0 100644 --- a/crates/metal2vulkan/src/lower/texture/slot.rs +++ b/crates/metal2vulkan/src/lower/texture/slot.rs @@ -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. diff --git a/crates/metal2vulkan/src/memory/handles.rs b/crates/metal2vulkan/src/memory/handles.rs index f204e28c7..25426208e 100644 --- a/crates/metal2vulkan/src/memory/handles.rs +++ b/crates/metal2vulkan/src/memory/handles.rs @@ -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, diff --git a/crates/metal2vulkan/src/metal/format/word.rs b/crates/metal2vulkan/src/metal/format/word.rs index bab4863b6..fcb73f9f9 100644 --- a/crates/metal2vulkan/src/metal/format/word.rs +++ b/crates/metal2vulkan/src/metal/format/word.rs @@ -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] { diff --git a/crates/metal2vulkan/src/metal/sampler.rs b/crates/metal2vulkan/src/metal/sampler.rs index 115f96e55..886408b35 100644 --- a/crates/metal2vulkan/src/metal/sampler.rs +++ b/crates/metal2vulkan/src/metal/sampler.rs @@ -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; diff --git a/crates/metal2vulkan/src/metal/texel_format.rs b/crates/metal2vulkan/src/metal/texel_format.rs index 421f8a5d4..726383af4 100644 --- a/crates/metal2vulkan/src/metal/texel_format.rs +++ b/crates/metal2vulkan/src/metal/texel_format.rs @@ -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, diff --git a/crates/metal2vulkan/src/pipeline/api_tests.rs b/crates/metal2vulkan/src/pipeline/api_tests.rs index 04b7ebbf3..c28325493 100644 --- a/crates/metal2vulkan/src/pipeline/api_tests.rs +++ b/crates/metal2vulkan/src/pipeline/api_tests.rs @@ -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. diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index cc110cb6d..6c7917b30 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -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 diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 392dc2dd2..dc0ce326e 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -2754,9 +2754,9 @@ fn compile_kept( .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( .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 { diff --git a/crates/metal2vulkan/src/pipeline/compile/fit.rs b/crates/metal2vulkan/src/pipeline/compile/fit.rs index d077cb0ad..0da7c7caa 100644 --- a/crates/metal2vulkan/src/pipeline/compile/fit.rs +++ b/crates/metal2vulkan/src/pipeline/compile/fit.rs @@ -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( &self, pipeline: P, @@ -180,34 +178,22 @@ impl Device { translatable: bool, again: impl Fn(&Device) -> Result, ) -> Result { - 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

= 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, diff --git a/crates/metal2vulkan/src/pipeline/compile/fit/tests.rs b/crates/metal2vulkan/src/pipeline/compile/fit/tests.rs index bea72f08c..6a2bcf050 100644 --- a/crates/metal2vulkan/src/pipeline/compile/fit/tests.rs +++ b/crates/metal2vulkan/src/pipeline/compile/fit/tests.rs @@ -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(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(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 = 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"); } diff --git a/crates/metal2vulkan/src/pipeline/compile/key.rs b/crates/metal2vulkan/src/pipeline/compile/key.rs index 4f6def1b8..08f06ce11 100644 --- a/crates/metal2vulkan/src/pipeline/compile/key.rs +++ b/crates/metal2vulkan/src/pipeline/compile/key.rs @@ -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()); diff --git a/crates/metal2vulkan/src/pipeline/compile/tests.rs b/crates/metal2vulkan/src/pipeline/compile/tests.rs index 11a7aacd3..5cd88d60a 100644 --- a/crates/metal2vulkan/src/pipeline/compile/tests.rs +++ b/crates/metal2vulkan/src/pipeline/compile/tests.rs @@ -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 diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index e1ea4f3c8..a1e7210e7 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -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 diff --git a/crates/metal2vulkan/src/pipeline/link/vertex.rs b/crates/metal2vulkan/src/pipeline/link/vertex.rs index e0b17f28d..e71c829b7 100644 --- a/crates/metal2vulkan/src/pipeline/link/vertex.rs +++ b/crates/metal2vulkan/src/pipeline/link/vertex.rs @@ -58,16 +58,6 @@ //! position, where the function reads the vertex its index names. The layouts it pulls are not a //! pulled-vertex-buffer variant's (`variant_pulled` keeps item 7's). //! -//! 9. a **normalized** format (the 8- and 16-bit `Normalized` formats of either sign, -//! `UChar4Normalized_BGRA`, `Int1010102Normalized`, `UInt1010102Normalized`) is pulled where -//! the profile asks for Metal's own division (`VertexNormalizedPolicy::Exact`, -//! [`normalized_exactly`]): Metal divides a code by its own maximum, correctly rounded, and -//! `lower::stage_io::fetch`'s `div_exact` computes that in integer arithmetic, while a driver -//! that multiplies by the reciprocal in fixed-function input is one `f32` ulp off at some -//! codes. Under the default the device's `UNORM` or `SNORM` conversion delivers it, which is -//! the conversion Vulkan states and Metal states, and every such format then shares the one -//! fixed-function module (`docs/FAST-PATHS.md`). -//! //! A fixed-function entry then keeps of the format only what the module's own instructions depend //! on, which is `narrow_float` and nothing else, and that bit only for an attribute the function //! reads as a 32-bit `float` ([`narrow_float_of_f32_reads`]): every other format the device @@ -80,7 +70,6 @@ use std::collections::{BTreeMap, BTreeSet}; -use crate::device::policy::VertexNormalizedPolicy; use crate::device::requirements::VkFeature; use crate::device::DeviceProfile; use crate::error::{DescriptorError, Error, InternalError, InternalKind}; @@ -141,26 +130,6 @@ fn class_format( } } -/// Whether `format` is a normalized format whose conversion the shader must compute (item 9 of -/// the module docs): the profile asks for Metal's normalized vertex conversion -/// (`VertexNormalizedPolicy::Exact`) and the format's codes are divided by their own maximum -- -/// the 8- and 16-bit `Normalized` formats of either sign, `UChar4Normalized_BGRA`, and the two -/// `1010102Normalized` words. Under the default the device's fixed-function `UNORM` or `SNORM` -/// conversion delivers it, which Vulkan states as Metal states it. -fn normalized_exactly(format: VertexFormat, p: &DeviceProfile) -> Result { - if p.fields().vertex_normalized != VertexNormalizedPolicy::Exact { - return Ok(false); - } - Ok(matches!( - encoding(format)?, - Encoding::Int { - normalized: true, - .. - } | Encoding::Bgra8Unorm - | Encoding::Rgb10A2 { .. } - )) -} - /// The stride the Vulkan binding of `fetch` on `layout` is emitted with (`None`: set per bind, a /// runtime fact the binder owns): **0** for Metal's constant step, which `metal::vertex::fetch_as` /// answers with a divisor of 0 and no other step can, and `layout`'s own otherwise. @@ -230,7 +199,6 @@ fn resolve<'a>( _ => false, }; let pulled = !fits - || normalized_exactly(attr.format, p)? || (beyond_stride && p.fields() .enabled diff --git a/crates/metal2vulkan/src/pipeline/lower_inputs.rs b/crates/metal2vulkan/src/pipeline/lower_inputs.rs index 4d844c7a1..e54a5f34a 100644 --- a/crates/metal2vulkan/src/pipeline/lower_inputs.rs +++ b/crates/metal2vulkan/src/pipeline/lower_inputs.rs @@ -172,13 +172,6 @@ pub struct LoweringInputs { serde(default, with = "crate::pipeline::serde_pairs") )] pub snapshot_textures: BTreeMap, - /// Texture slots bound in a YCbCr format (`VariantKey::ycbcr_textures`, - /// `RuntimeFact::YCbCrTexture`): on a profile that takes the variant - /// (`ProfileFields::ycbcr_variant`), each such slot's linear samples take the emulation of - /// Metal's filter a device without it takes, and the samples it does not reach are noted. - /// Ignored on any other profile, and for a slot of no such sample. - #[cfg_attr(feature = "serde", serde(default))] - pub ycbcr_textures: BTreeSet, /// Texture slots bound to a two-plane YCbCr texture whose planes are read in place /// (`VariantKey::ycbcr_in_place`, `RuntimeFact::YCbCrInPlace`): each is declared as the /// planes' uniform texel buffer, and its samples, reads and size queries read the codes and diff --git a/crates/metal2vulkan/src/pipeline/testing.rs b/crates/metal2vulkan/src/pipeline/testing.rs index 6ce616dcd..cfe6cf336 100644 --- a/crates/metal2vulkan/src/pipeline/testing.rs +++ b/crates/metal2vulkan/src/pipeline/testing.rs @@ -66,17 +66,6 @@ impl Drop for Scratch { } } -/// The default policy with Metal's sampler emulated exactly (`SamplingPolicy::Exact`): the policy -/// of a test of the sampler's emulation, which native device sampling, the default, skips on a -/// device whose sampler is not Metal's. Every other answer is Metal's too -/// (`DevicePolicy::exact_answers`): the emulation's arithmetic (its cube face reciprocal and fused -/// multiply-adds), its texels and a read's, its `half` roundings, and its NaNs, minimum and maximum -/// and rounding order. -pub const EXACT_SAMPLING: DevicePolicy = DevicePolicy { - sampling: crate::device::SamplingPolicy::Exact, - ..DevicePolicy::UNTRUSTED.exact_answers() -}; - /// The description of committed profile `stem` (`validation/profiles/.json`). pub fn description(stem: &str) -> Result { let path = Path::new(env!("CARGO_MANIFEST_DIR")) @@ -161,13 +150,9 @@ pub fn storage_buffers(a: &FunctionArtifact) -> u32 { } /// The default policy with Metal's answers wherever a choice still offers them -/// ([`DevicePolicy::exact_answers`]) but the texel conversions, which are the default's. +/// ([`DevicePolicy::exact_answers`]). pub fn exact_maths() -> DevicePolicy { - let native = DevicePolicy::default(); - DevicePolicy { - texel_conversion: native.texel_conversion, - ..native.exact_answers() - } + DevicePolicy::default().exact_answers() } /// A fresh per-attempt meter with the standard caps and no deadline. diff --git a/crates/metal2vulkan/src/spirv/requirements/snapshot.rs b/crates/metal2vulkan/src/spirv/requirements/snapshot.rs index 75d73007d..997a8cb51 100644 --- a/crates/metal2vulkan/src/spirv/requirements/snapshot.rs +++ b/crates/metal2vulkan/src/spirv/requirements/snapshot.rs @@ -40,8 +40,8 @@ //! memory is its parameter's (what either side stores through it the other may load), and the //! values the callee returns reach the call's result. The callee's instructions are the module's, //! judged as any other; a callee called from several sites takes the reach of them all. Lowering's -//! texel routines (Metal's exact conversion of a texel, `lower::texture::float_texel`) are such -//! calls, whose selects carry the texel to the result alone. +//! texel routines (Metal's conversion of a `half` texel, `lower::texture::half`) are such calls, +//! whose selects carry the texel to the result alone. //! //! A module that already holds an interlock critical section has none: the variant's entry opens //! its own. Nor has one with a `Coherent` resource or under the Vulkan memory model: the variant diff --git a/crates/metal2vulkan/src/spirv/testing.rs b/crates/metal2vulkan/src/spirv/testing.rs index 9aa045e67..bb63f55b7 100644 --- a/crates/metal2vulkan/src/spirv/testing.rs +++ b/crates/metal2vulkan/src/spirv/testing.rs @@ -240,14 +240,6 @@ pub fn committed_profiles() -> Result, String> { committed_profiles_under(DevicePolicy::default()) } -/// Every committed device profile, as [`committed_profiles`], with Metal's sampler emulated -/// exactly (`crate::pipeline::testing::EXACT_SAMPLING`): the profiles of a test of the sampler's -/// emulation, which native device sampling, the default, skips on a device whose sampler is not -/// Metal's. -pub fn committed_exact_profiles() -> Result, String> { - committed_profiles_under(crate::pipeline::testing::EXACT_SAMPLING) -} - /// [`committed_profiles`] under `policy` (the tests of Metal's NaN and `half` rounding take /// [`crate::pipeline::testing::exact_maths`]). pub fn committed_profiles_with( diff --git a/crates/metal2vulkan/src/tests/engine_bias_reach.rs b/crates/metal2vulkan/src/tests/engine_bias_reach.rs index 9d766baac..a6ff61357 100644 --- a/crates/metal2vulkan/src/tests/engine_bias_reach.rs +++ b/crates/metal2vulkan/src/tests/engine_bias_reach.rs @@ -3,7 +3,10 @@ //! Vulkan clamps an implicit sample's `Bias` operand (with the sampler's own `mipLodBias`) into //! `±maxSamplerLodBias`; Metal applies the whole bias: an Apple M3 Max magnifies with biases of //! -17.5, -100, and -1000 at a level of 17 before the bias (authored case `3ec31bc4`, -//! `a2_fragment_bias_clamp`), where RADV, clamping at 16, minifies. So: +//! `a2_fragment_bias_clamp`), where RADV, clamping at 16, minifies. Through a sampler without a +//! bias of its own every bias is the `Bias` operand, the device's sampler's answer (MoltenVK hands +//! it to Metal whole). Through a constexpr sampler with its own bias, whose sum with the operand's +//! no measurement has read: //! //! - a constant bias whose sum with the sampler's is within the limit stays the `Bias` operand of //! an implicit sample, unchanged; @@ -26,9 +29,9 @@ use std::collections::BTreeMap; use std::sync::atomic::{AtomicU64, Ordering}; use crate::device::profile::DeviceProfile; +use crate::device::DevicePolicy; use crate::library::FunctionArtifact; use crate::pipeline::artifact::PrecisionNote; -use crate::pipeline::testing::EXACT_SAMPLING; use crate::pipeline::testing::{ compile, engine_dir, link_and_validate, llvm_assemble, profile, AssembleError, }; @@ -45,8 +48,6 @@ const OP_IMAGE_SAMPLE_EXPLICIT_LOD: u16 = 88; const OP_F_ORD_GREATER_THAN: u16 = 186; const OP_DPDX: u16 = 207; const OP_DPDY: u16 = 208; -const OP_BRANCH_CONDITIONAL: u16 = 250; -const OP_IMAGE_QUERY_SIZE_LOD: u16 = 103; const GLSL_EXP2: u32 = 29; const GLSL_FCLAMP: u32 = 43; const GLSL_FREXP_STRUCT: u32 = 52; @@ -121,33 +122,8 @@ declare {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32(ptr addrspace(1), ptr ) } -/// [`biased_fragment`] through runtime sampler slot 0. -fn runtime_biased_fragment(bias: &str) -> String { - format!( - r#"define <4 x float> @k(<4 x float> %pos, ptr addrspace(1) %t, ptr addrspace(2) %s) {{ - %xy = shufflevector <4 x float> %pos, <4 x float> poison, <2 x i32> - %uv = fmul <2 x float> %xy, - %r = call {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32(ptr addrspace(1) %t, ptr addrspace(2) %s, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float {bias}, float 0.000000e+00, i32 0) - %v = extractvalue {{ <4 x float>, i8 }} %r, 0 - ret <4 x float> %v -}} - -declare {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32) - -!air.fragment = !{{!0}} -!0 = !{{ptr @k, !1, !3}} -!1 = !{{!2}} -!2 = !{{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"}} -!3 = !{{!4, !5, !6}} -!4 = !{{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"}} -!5 = !{{i32 1, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"}} -!6 = !{{i32 2, !"air.sampler", !"air.location_index", i32 0, i32 1, !"air.arg_type_name", !"sampler", !"air.arg_name", !"s"}} -"# - ) -} - fn p(stem: &str) -> DeviceProfile { - profile(stem, EXACT_SAMPLING).expect(stem) + profile(stem, DevicePolicy::default()).expect(stem) } fn max_bias(p: &DeviceProfile) -> f32 { @@ -335,60 +311,15 @@ impl Shape { } } -/// The dynamic bias of `a2_fragment_bias_clamp` samples implicitly with `Bias` and, where `|bias| > -/// maxSamplerLodBias` (the profile's own limit), with the derivatives scaled by `2^bias`: on every -/// profile that does not sample through Metal's own sampler, whatever its limit (2 to 16). +/// Through a sampler without a bias of its own every fragment bias is the `Bias` operand alone, the +/// device's sampler's: on MoltenVK (`VkProperty::MetalSampler`) the device hands it to Metal whole, +/// so Metal applies its own rule (the bias rounded to `half`, floored onto `1/64` and clamped into +/// `[-32, 31.984375]`); elsewhere the device clamps it into `±maxSamplerLodBias` +/// (`VkProperty::DeviceSampling`). A dynamic bias and a constant past the limit alike take no +/// derivatives and no branch, record no `PrecisionNote::GradFromBias`, and require the property. #[test] -fn a_dynamic_bias_takes_scaled_derivatives_past_the_limit() { - let Some(bc) = assemble_file("a2_fragment_bias_clamp.ll") else { - return; - }; - for stem in ["amd-rdna3-radv", "lavapipe", "vk12-floor"] { - let prof = p(stem); - let a = ok(&bc, "a2_fragment_bias_clamp", &prof); - let s = shape(&a); - assert_eq!( - a.strategies - .entries - .get("sampler.sample_implicit.bias_gradients") - .map(|u| u.uses), - Some(1), - "{stem}: {:?}", - a.strategies - ); - assert!(!a.strategies.entries.contains_key("sampler.sample_implicit")); - assert_eq!(s.count(OP_IMAGE_SAMPLE_IMPLICIT_LOD), 1, "{stem}"); - assert_eq!(s.count(OP_IMAGE_SAMPLE_EXPLICIT_LOD), 1, "{stem}"); - assert_eq!((s.count(OP_DPDX), s.count(OP_DPDY)), (1, 1), "{stem}"); - assert!(s.count(OP_BRANCH_CONDITIONAL) >= 1, "{stem}"); - s.scales_finitely(1, 0, stem); - s.reads_metals_bias(1, stem); - // The test is `|bias| > maxSamplerLodBias` (the sampler carries no bias of its own). - assert!( - s.greater - .iter() - .any(|(_, y)| s.constant(*y) == Some(max_bias(&prof))), - "{stem}: no `> {}` test", - max_bias(&prof) - ); - assert!(a.precision.contains(&PrecisionNote::GradFromBias), "{stem}"); - } -} - -/// On a device that samples through Metal's own sampler (`VkProperty::MetalSampler`, MoltenVK), -/// every fragment bias is the `Bias` operand alone, which the device hands to Metal whole, so Metal -/// applies its own rule (the bias rounded to `half`, floored onto `1/64` and clamped into `[-32, -/// 31.984375]`): a dynamic bias and a constant past `maxSamplerLodBias` alike take no derivatives -/// and no branch, record no `PrecisionNote::GradFromBias`, and require the property. A device -/// without it keeps the scaled derivatives past its limit (above, and the constant test below). -#[test] -fn on_metals_own_sampler_every_bias_is_the_bias_operand() { - let prof = p("moltenvk-m3"); - assert!(prof - .fields() - .enabled - .properties - .contains(&crate::device::requirements::VkProperty::MetalSampler)); +fn a_bias_without_the_samplers_own_is_the_bias_operand() { + use crate::device::requirements::VkProperty; let mut fixtures = Vec::new(); if let Some(bc) = assemble_file("a2_fragment_bias_clamp.ll") { fixtures.push(("dynamic", bc, "a2_fragment_bias_clamp")); @@ -401,40 +332,48 @@ fn on_metals_own_sampler_every_bias_is_the_bias_operand() { fixtures.push((what, bc, "k")); } } - for (what, bc, entry) in fixtures { - let a = ok(&bc, entry, &prof); - let s = shape(&a); - let uses = |name: &str| a.strategies.entries.get(name).map_or(0, |u| u.uses); - assert_eq!( - uses("sampler.sample_implicit"), - 1, - "{what}: {:?}", - a.strategies - ); - assert_eq!(uses("sampler.sample_implicit.bias_gradients"), 0, "{what}"); - assert_eq!(uses("sampler.sample_bias_gradients"), 0, "{what}"); - assert_eq!(s.count(OP_IMAGE_SAMPLE_IMPLICIT_LOD), 1, "{what}"); - assert_eq!(s.count(OP_IMAGE_SAMPLE_EXPLICIT_LOD), 0, "{what}"); - assert_eq!((s.count(OP_DPDX), s.count(OP_DPDY)), (0, 0), "{what}"); - assert_eq!(s.glsl_count(GLSL_EXP2), 0, "{what}"); - s.reads_metals_bias(0, what); - assert!( - !a.precision.contains(&PrecisionNote::GradFromBias), - "{what}" - ); - assert!( - a.requirements - .properties - .contains(&crate::device::requirements::VkProperty::MetalSampler), - "{what}" - ); + for stem in ["moltenvk-m3", "amd-rdna3-radv", "lavapipe", "vk12-floor"] { + let prof = p(stem); + let property = match prof + .fields() + .enabled + .properties + .contains(&VkProperty::MetalSampler) + { + true => VkProperty::MetalSampler, + false => VkProperty::DeviceSampling, + }; + for (what, bc, entry) in &fixtures { + let what = format!("{stem}, {what}"); + let a = ok(bc, entry, &prof); + let s = shape(&a); + let uses = |name: &str| a.strategies.entries.get(name).map_or(0, |u| u.uses); + assert_eq!( + uses("sampler.sample_implicit"), + 1, + "{what}: {:?}", + a.strategies + ); + assert_eq!(uses("sampler.sample_implicit.bias_gradients"), 0, "{what}"); + assert_eq!(uses("sampler.sample_bias_gradients"), 0, "{what}"); + assert_eq!(s.count(OP_IMAGE_SAMPLE_IMPLICIT_LOD), 1, "{what}"); + assert_eq!(s.count(OP_IMAGE_SAMPLE_EXPLICIT_LOD), 0, "{what}"); + assert_eq!((s.count(OP_DPDX), s.count(OP_DPDY)), (0, 0), "{what}"); + assert_eq!(s.glsl_count(GLSL_EXP2), 0, "{what}"); + s.reads_metals_bias(0, &what); + assert!( + !a.precision.contains(&PrecisionNote::GradFromBias), + "{what}" + ); + assert!(a.requirements.properties.contains(&property), "{what}"); + } } } -/// A constant bias whose sum with the sampler's own bias is within the limit is the `Bias` operand -/// alone (no derivatives, no note); past it, the scaled derivatives alone. The sampler's own bias -/// counts: on amd-rdna3-radv (limit 16) a constexpr sampler bias of 10 with a shader bias of 4 is -/// within, with 8 past. (MoltenVK's portability subset withholds a sampler bias, so it refuses such +/// Through a constexpr sampler with a bias of its own, a constant bias whose sum with the +/// sampler's is within the limit is the `Bias` operand alone (no derivatives, no note); past it, +/// the scaled derivatives alone. The sampler's own bias counts: on amd-rdna3-radv (limit 16) a +/// constexpr sampler bias of 10 with a shader bias of 4 is within, with 8 or -30 past. (MoltenVK's portability subset withholds a sampler bias, so it refuses such /// a sampler.) #[test] fn a_constant_bias_is_decided_at_compile_time_with_the_samplers_own() { @@ -442,11 +381,19 @@ fn a_constant_bias_is_decided_at_compile_time_with_the_samplers_own() { assert_eq!(max_bias(&radv), 16.0); // Half 10.0 is 0x4900. for (what, bias, half_bias, past) in [ - ("within", "2.000000e+00", 0u16, false), - ("past", "-2.000000e+01", 0, true), - ("past, positive", "1.000000e+03", 0, true), - ("within with the sampler's", "4.000000e+00", 0x4900, false), + ( + "within with the sampler's", + "4.000000e+00", + 0x4900u16, + false, + ), ("past with the sampler's", "8.000000e+00", 0x4900, true), + ( + "past below with the sampler's", + "-3.000000e+01", + 0x4900, + true, + ), ] { let Some(bc) = assemble(what, &biased_fragment(bias, half_bias)) else { return; @@ -538,125 +485,58 @@ const ANISOTROPIC_WORDS: u64 = (SAMPLER_WORDS & !(0xf << 20)) | (15 << 20); /// and its loop's one (two explicit-level samples each under a linear mip filter). const WRITTEN_TAPS: u32 = 2; -/// Through an anisotropic constexpr sampler of a 2D texture, Metal's bias shifts the footprint's -/// minor axis alone, which neither the `Bias` operand nor `2^B` derivatives give: a fragment bias, -/// within the device's limit or past it, samples with the axis gradients alone (the coordinate's -/// derivatives, their lengths in texels of the level-0 size, and `Exp2` of Metal's reading of the -/// bias), with `PrecisionNote::GradFromBias`. Off Metal's own sampler they are the footprint of -/// Metal's anisotropic filter, emulated: its taps' samples at explicit levels, two a tap under the -/// sampler's linear mip filter, in the emulation's routine, which queries the level-0 size the -/// site's axis gradients read again (one query each). +/// Through an anisotropic constexpr sampler of a 2D texture with a bias of its own, Metal's bias +/// shifts the footprint's minor axis alone, which neither the `Bias` operand nor `2^B` derivatives +/// give: a fragment bias, within the device's limit or past it, samples with the axis gradients +/// alone (the coordinate's derivatives, their lengths in texels of the level-0 size, and `Exp2` of +/// Metal's reading of the bias), with `PrecisionNote::GradFromBias`. With `samplerAnisotropy` the +/// device's anisotropic filter samples at them; without it they are the footprint of Metal's +/// anisotropic filter, emulated: its taps' samples at explicit levels, two a tap under the +/// sampler's linear mip filter, `AnisotropicFilter` recorded. #[test] fn an_anisotropic_sampler_takes_the_axis_gradients() { for stem in ["amd-rdna3-radv", "lavapipe"] { - let prof = p(stem); - for (what, bias) in [("within", "2.000000e+00"), ("past", "-2.000000e+01")] { - let what = format!("{stem}, {what}"); - let Some(bc) = assemble(&what, &biased_fragment_of(ANISOTROPIC_WORDS, bias, 0)) else { - return; + for withheld in [false, true] { + let prof = { + let mut desc = crate::pipeline::testing::description(stem).expect(stem); + if withheld { + assert!(desc + .features + .remove(&crate::device::requirements::VkFeature::SamplerAnisotropy)); + } + crate::device::Device::new(desc, DevicePolicy::default()) + .expect(stem) + .profile() + .clone() }; - let a = ok(&bc, "k", &prof); - let s = shape(&a); - let uses = |name: &str| a.strategies.entries.get(name).map_or(0, |u| u.uses); - assert_eq!(uses("sampler.sample_bias_gradients"), 1, "{what}"); - assert_eq!(s.count(OP_IMAGE_SAMPLE_IMPLICIT_LOD), 0, "{what}"); - assert_eq!( - s.count(OP_IMAGE_SAMPLE_EXPLICIT_LOD), - 2 * WRITTEN_TAPS as usize, - "{what}" - ); - assert_eq!((s.count(OP_DPDX), s.count(OP_DPDY)), (1, 1), "{what}"); - assert_eq!(s.count(OP_IMAGE_QUERY_SIZE_LOD), 2, "{what}"); - assert_eq!(s.glsl_count(GLSL_LENGTH), 2, "{what}"); - s.scales_finitely_beside(0, 1, 1, &what); - s.reads_metals_bias(1, &what); - assert!(a.precision.contains(&PrecisionNote::GradFromBias), "{what}"); - assert!( - a.precision.contains(&PrecisionNote::AnisotropicFilter), - "{what}" - ); - } - } -} - -/// Through a runtime sampler slot, whose anisotropy is its bound sampler's, a fragment bias, -/// constant or not, is decided per invocation: the implicit sample with the `Bias` operand `B`, -/// replaced where `|B|` passes the device's limit by the sample with `2^B` derivatives, and -/// wherever the slot's word (its `SamplerState` specialization, which reads -/// `SamplerWord::ANISOTROPIC`) states anisotropy, by the sample with the axis gradients. Off -/// Metal's own sampler, where the word states anisotropy, Metal's anisotropic filter, emulated, -/// replaces all of that: its footprint of the axis gradients (the bias read once more), and its -/// taps' samples at explicit levels, two a tap under the word's linear mip filter. -#[test] -fn a_runtime_samplers_word_chooses_the_axis_gradients() { - use crate::metal::sampler::SamplerWord; - use crate::pipeline::sym::SpecKey; - for stem in ["amd-rdna3-radv", "lavapipe", "vk12-floor"] { - let prof = p(stem); - for (what, bias) in [("within", "2.000000e+00"), ("past", "-2.000000e+01")] { - let what = format!("{stem}, {what}"); - let Some(bc) = assemble(&what, &runtime_biased_fragment(bias)) else { - return; - }; - // Compiled without the slot named, the function is the variant's other arm alone. - let base = shape(&ok(&bc, "k", &prof)); - let a = ok_with(&bc, "k", &prof, &anisotropic_slot_0()); - let s = shape(&a); - // The same sample without a bias: the slot's linear sample, which Metal's filter - // emulated by fetches answers where the word states no mip filter, names the sample - // `sampler.linear` and queries the texture's size for its taps; the device's sample in - // its other arm is the one the bias reaches. - let Some(plain) = assemble(&what, &runtime_biased_fragment("0.000000e+00")) else { - return; - }; - let plain_base = shape(&ok(&plain, "k", &prof)); - let plain = shape(&ok_with(&plain, "k", &prof, &anisotropic_slot_0())); - let taps = 2 * WRITTEN_TAPS as usize; - assert_eq!(plain_base.count(OP_IMAGE_SAMPLE_IMPLICIT_LOD), 1, "{what}"); - assert_eq!(plain_base.count(OP_IMAGE_SAMPLE_EXPLICIT_LOD), 0, "{what}"); - assert_eq!(base.count(OP_IMAGE_SAMPLE_IMPLICIT_LOD), 1, "{what}"); - assert_eq!( - base.count(OP_IMAGE_SAMPLE_EXPLICIT_LOD) + taps, - s.count(OP_IMAGE_SAMPLE_EXPLICIT_LOD), - "{what}" - ); - assert_eq!(plain.count(OP_IMAGE_SAMPLE_IMPLICIT_LOD), 1, "{what}"); - assert_eq!(plain.count(OP_IMAGE_SAMPLE_EXPLICIT_LOD), taps, "{what}"); - // The device's sample keeps its `Bias` operand, and where the word's test holds the - // sample with the gradients replaces it; the axis gradients of each arm query the - // level-0 size once more (the emulation's routine queries its own). - assert_eq!( - s.count(OP_IMAGE_SAMPLE_IMPLICIT_LOD), - 1, - "{what}: {:?} {:?}", - s.ops, - s.glsl - ); - assert_eq!(s.count(OP_IMAGE_SAMPLE_EXPLICIT_LOD), taps + 1, "{what}"); - assert_eq!( - s.count(OP_IMAGE_QUERY_SIZE_LOD), - plain.count(OP_IMAGE_QUERY_SIZE_LOD) + 2, - "{what}" - ); - // The axis gradients of both arms, and the emulation's spacing. - assert_eq!(s.glsl_count(GLSL_LENGTH), 4, "{what}"); - s.scales_finitely_beside(1, 2, 1, &what); - s.reads_metals_bias(2, &what); - let fields = a.interface.read_keys().into_iter().find_map(|k| match k { - SpecKey::SamplerState { fields, .. } => Some(fields), - _ => None, - }); - assert!( - fields.is_some_and(|f| f & SamplerWord::ANISOTROPIC != 0), - "{what}: {fields:?}" - ); - assert!(a.precision.contains(&PrecisionNote::GradFromBias), "{what}"); - assert!( - a.specialized - .iter() - .any(|n| n.note == PrecisionNote::AnisotropicFilter), - "{what}" - ); + // Half 10.0 is 0x4900: the sampler's own bias. + for (what, bias) in [("within", "2.000000e+00"), ("past", "-3.000000e+01")] { + let what = format!("{stem}, samplerAnisotropy withheld {withheld}, {what}"); + let Some(bc) = + assemble(&what, &biased_fragment_of(ANISOTROPIC_WORDS, bias, 0x4900)) + else { + return; + }; + let a = ok(&bc, "k", &prof); + let s = shape(&a); + let uses = |name: &str| a.strategies.entries.get(name).map_or(0, |u| u.uses); + assert_eq!(uses("sampler.sample_bias_gradients"), 1, "{what}"); + assert_eq!(s.count(OP_IMAGE_SAMPLE_IMPLICIT_LOD), 0, "{what}"); + let explicit = match withheld { + true => 2 * WRITTEN_TAPS as usize, + false => 1, + }; + assert_eq!(s.count(OP_IMAGE_SAMPLE_EXPLICIT_LOD), explicit, "{what}"); + assert_eq!((s.count(OP_DPDX), s.count(OP_DPDY)), (1, 1), "{what}"); + assert_eq!(s.glsl_count(GLSL_LENGTH), 2, "{what}"); + s.reads_metals_bias(1, &what); + assert!(a.precision.contains(&PrecisionNote::GradFromBias), "{what}"); + assert_eq!( + a.precision.contains(&PrecisionNote::AnisotropicFilter), + withheld, + "{what}" + ); + } } } } diff --git a/crates/metal2vulkan/src/tests/engine_bicubic.rs b/crates/metal2vulkan/src/tests/engine_bicubic.rs index a37e790a2..1809fea02 100644 --- a/crates/metal2vulkan/src/tests/engine_bicubic.rs +++ b/crates/metal2vulkan/src/tests/engine_bicubic.rs @@ -22,16 +22,15 @@ use std::collections::BTreeMap; use std::sync::atomic::{AtomicU64, Ordering}; use crate::device::profile::{DeviceProfile, FloatFunctions}; +use crate::device::DevicePolicy; use crate::error::{Error, Feature, Needs, Unsupported}; use crate::lower::select::Plan; use crate::metal::bicubic::{texels, weights, BicubicTexels}; -use crate::metal::texel_format::texel_format; use crate::metal::PixelFormat; use crate::pipeline::interface::PushLoc; use crate::pipeline::sym::{ Axis, PushField, ResourceKind, ResourceSlot, SlotClass, SlotRef, SpecKey, Stage, }; -use crate::pipeline::testing::EXACT_SAMPLING; use crate::pipeline::testing::{ compile, compile_with, engine_dir, link_and_validate, llvm_assemble, profile, typed_module, typed_module_with, AssembleError, @@ -71,12 +70,7 @@ fn assemble_module(name: &str, text: &str) -> Option> { } fn m3() -> DeviceProfile { - profile("moltenvk-m3", EXACT_SAMPLING).expect("profile") -} - -/// A profile without Metal's own sampler, where a linear sample is the emulation. -fn lavapipe() -> DeviceProfile { - profile("lavapipe", EXACT_SAMPLING).expect("profile") + profile("moltenvk-m3", DevicePolicy::default()).expect("profile") } /// The words of `constexpr sampler(filter::bicubic, ...)` with every axis addressed by `address` @@ -88,12 +82,6 @@ fn bicubic_words(address: u64, pixel: bool, border: u64) -> u64 { BASE | address | address << 3 | address << 6 | u64::from(pixel) << 15 | border << 56 } -/// The words of `constexpr sampler(filter::linear, ...)` with the fields of -/// `bicubic_words(address, false, 0)` but the filters: Metal's linear filter beside it. -fn linear_words(address: u64) -> u64 { - bicubic_words(address, false, 0) & !(0xf << 9) | 1 << 9 | 1 << 11 -} - /// `words` with its `s` axis (`axis` 0) or its `t` axis (1) addressed by AIR code `address`. fn with_axis(words: u64, axis: u32, address: u64) -> u64 { words & !(7 << (3 * axis)) | address << (3 * axis) @@ -1001,17 +989,14 @@ fn an_offset_on_a_repeating_axis_takes_metals_placement() { } } -/// Metal's bicubic filter on small levels and mirrored axes (`lower::sampler::bicubic`'s module -/// docs; the probes probes on the M3 Max, the primary): +/// Metal's bicubic filter on mirrored axes (`lower::sampler::bicubic`'s module docs; the probes on +/// the M3 Max, the primary): /// - On a 12x10 level, a mirrored axis of a format Metal filters bicubically reads texel 1 at /// fraction 0 whatever the coordinate (with both axes mirrored, texel `(1, 1)`), while the other /// axis filters as it is addressed; a 32-bit float format's mirrored sample is the linear /// filter's, its taps reflected about the mirrored position. -/// - On a level below four texels on either axis (3x13, 13x3, and 2x2, beside the 4x4 that is -/// not small), the sample is the linear sampler's with the same address modes, bit for bit -/// (the emulation, on a profile without Metal's own sampler), under every mode. #[test] -fn mirrored_axes_and_small_levels() { +fn mirrored_axes() { let (w, h) = (12i64, 10i64); let points = coordinates(w, h); let scale = (w as f64, h as f64); @@ -1089,80 +1074,6 @@ fn mirrored_axes_and_small_levels() { } } } - // Small levels: the bicubic sample is the linear sample with the same address modes. - let p = lavapipe(); - let modes = [("zero", 0), ("edge", 1), ("repeat", 2), ("mirror", 3)]; - let sizes = [(3i64, 13i64), (13, 3), (2, 2), (4, 4)]; - let formats = [ - PixelFormat::RGBA8Unorm, - PixelFormat::RGBA16Float, - PixelFormat::RGBA32Float, - ]; - for (name, address) in modes { - let (Some(cubic), Some(lin)) = ( - assemble( - &format!("small {name}"), - &kernel( - bicubic_words(address, false, 0), - Form::Plain { offset: (0, 0) }, - ), - ), - assemble( - &format!("small {name} linear"), - &kernel(linear_words(address), Form::Plain { offset: (0, 0) }), - ), - ) else { - return; - }; - let a = compile(&lin, "k", &p).expect("compile linear"); - assert_eq!( - a.strategies.entries.get("sampler.linear").map(|u| u.uses), - Some(1), - "{name}: the linear sample is not the emulation" - ); - let (cubic_plan, cubic_m) = typed_module(&cubic, "k", &p).expect("typed module"); - let (lin_plan, lin_m) = typed_module(&lin, "k", &p).expect("typed module"); - for (w, h) in sizes { - let points = coordinates(w, h); - let scale = (w as f64, h as f64); - let mut differ = 0; - for (seed, pf) in formats.iter().enumerate() { - let class = texels(*pf).expect("measured"); - let tex = Texels::random(class, w, h, seed as u64 + 21); - let init = [coord_bytes(&points, scale), vec![0xab; 16 * points.len()]]; - let sample = |plan: &Plan, m: &TypedModule| { - let mut res = resources(plan, &init, class); - res.spec.insert( - SpecKey::TexelFormat(TEXTURE), - u64::from(texel_format(*pf).0), - ); - res.spec.insert( - SpecKey::PlainHalfTexels(TEXTURE), - u64::from(texel_format(*pf).plain_on_metal_sampler()), - ); - let image = tex.image(combined_slot(m), 2, 1); - run(m, &res, &image, points.len() as u32) - }; - let (got, want) = (sample(&cubic_plan, &cubic_m), sample(&lin_plan, &lin_m)); - for (lane, (g, l)) in got.iter().zip(&want).enumerate() { - let same = g.iter().zip(l).all(|(a, b)| a.to_bits() == b.to_bits()); - if w.min(h) < 4 { - assert!( - same, - "{name} {w}x{h} {pf:?} lane {lane} {:?}: {g:?} vs linear {l:?}", - points[lane] - ); - } - differ += usize::from(!same); - } - } - // A 4x4 level is filtered bicubically: some lane tells it from the linear filter. - assert!( - w.min(h) < 4 || differ > 0, - "{name} {w}x{h}: every lane is the linear filter's" - ); - } - } } fn refused(e: &Error) -> bool { @@ -1180,7 +1091,7 @@ fn refused(e: &Error) -> bool { /// lowered through the binding's nearest-filtered immutable sampler: /// - `min_lod_clamp` (Apple's device compiler fails to build the pipeline) and a dynamic offset; /// - `mirrored_repeat` on a 1D texture, with pixel coordinates, or beside a constant offset on -/// the mirrored axis (a 2D sample's mirrored axis is in `mirrored_axes_and_small_levels`); +/// the mirrored axis (a 2D sample's mirrored axis is in `mirrored_axes`); /// - a depth comparison (refused by `check`'s depth term: AIR compares only depth textures) and /// an LOD query; /// - a 3D, cube, depth, or integer texture; @@ -1276,7 +1187,7 @@ fn bicubic_forms_without_a_metal_reference_are_refused() { } cases.push(("lod query", lod_fragment(edge))); // Every committed profile: a capability one device lacks must not be what refuses the form. - let profiles = crate::spirv::testing::committed_exact_profiles().expect("profiles"); + let profiles = crate::spirv::testing::committed_profiles().expect("profiles"); for (name, text) in &cases { let Some(bc) = assemble(name, text) else { return; @@ -1337,7 +1248,7 @@ fn a_heap_texture_through_a_bicubic_sampler_is_refused() { linear, &state("@__air_sampler_state", bicubic_words(1, false, 0)), ); - let profiles = crate::spirv::testing::committed_exact_profiles().expect("profiles"); + let profiles = crate::spirv::testing::committed_profiles().expect("profiles"); for (name, plain, bicubic) in [ ("sample", &text, &bicubic_sample), ("gather", &gather, &bicubic_gather), @@ -1376,7 +1287,7 @@ fn the_emulation_validates_on_every_committed_profile() { let Some(bc) = assemble(name, &kernel(edge, form)) else { return; }; - for (stem, p) in crate::spirv::testing::committed_exact_profiles().expect("profiles") { + for (stem, p) in crate::spirv::testing::committed_profiles().expect("profiles") { let a = compile(&bc, "k", &p).unwrap_or_else(|e| panic!("{name} on {stem}: {e}")); link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name} on {stem}: {e}")); } @@ -1507,7 +1418,7 @@ fn the_footprint_arithmetic_is_no_contraction() { let Some(bc) = assemble(name, &kernel(words, Form::Plain { offset: (0, 0) })) else { return; }; - for (stem, p) in crate::spirv::testing::committed_exact_profiles().expect("profiles") { + for (stem, p) in crate::spirv::testing::committed_profiles().expect("profiles") { let a = compile(&bc, "k", &p).unwrap_or_else(|e| panic!("{name} on {stem}: {e}")); let (_, spv) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name} on {stem}: {e}")); @@ -1551,7 +1462,7 @@ fn the_estimate_bounds_the_bicubic_fixtures() { eprintln!("SKIPPED: llvm-as"); return; }; - for (stem, p) in crate::spirv::testing::committed_exact_profiles().expect("profiles") { + for (stem, p) in crate::spirv::testing::committed_profiles().expect("profiles") { let what = format!("{name} on {stem}"); let (entry, consts) = (EntryRef::Name(name), FunctionConstantValues::defaults()); let inputs = LowerInputs::new(); @@ -1587,7 +1498,7 @@ fn a_bicubic_samples_small_level_shares_the_planes_accumulated_call() { } Err(AssembleError::Rejected(e)) => panic!("llvm-as rejected bcx_rules: {e}"), }; - let p = profile("intel-irisxe-rplp-anv", EXACT_SAMPLING).expect("profile"); + let p = profile("intel-irisxe-rplp-anv", DevicePolicy::default()).expect("profile"); let (_, m) = typed_module(&bc, "bcx_rules", &p).expect("typed module"); let functions = m.functions(); let entry = functions.get(m.entry().func.index()).expect("entry"); diff --git a/crates/metal2vulkan/src/tests/engine_cross_class.rs b/crates/metal2vulkan/src/tests/engine_cross_class.rs index e952db955..643775f41 100644 --- a/crates/metal2vulkan/src/tests/engine_cross_class.rs +++ b/crates/metal2vulkan/src/tests/engine_cross_class.rs @@ -24,6 +24,7 @@ use crate::bind::{ WriteSource, }; use crate::budget::{Budget, SPIRV_WORDS}; +use crate::device::DevicePolicy; use crate::device::{Device, DeviceDescription}; use crate::library::{FunctionConstantValues, Library}; use crate::lower::select::{LowerInputs, Plan}; @@ -33,7 +34,6 @@ use crate::pipeline::facts::RuntimeFact; use crate::pipeline::sym::{ Axis, ResourceKind, ResourceSlot, SampledType, SlotClass, SlotRef, SpecKey, Stage, }; -use crate::pipeline::testing::EXACT_SAMPLING; use crate::pipeline::testing::{ link_and_validate, llvm_assemble, meter, profile, typed_module_with, AssembleError, }; @@ -357,7 +357,12 @@ fn accesses_through_another_class_are_the_native_words() { ]; let profiles: Vec<_> = ["lavapipe", "moltenvk-m3"] .into_iter() - .map(|stem| (stem, profile(stem, EXACT_SAMPLING).expect("profile"))) + .map(|stem| { + ( + stem, + profile(stem, DevicePolicy::default()).expect("profile"), + ) + }) .collect(); let mut checked = 0; // The interpreter models no sample or gather: theirs compile and validate in @@ -417,7 +422,10 @@ fn devices() -> Vec<(String, Device)> { .unwrap_or_default(); let text = std::fs::read_to_string(&path).expect("profile"); let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - out.push((stem, Device::new(desc, EXACT_SAMPLING).expect("device"))); + out.push(( + stem, + Device::new(desc, DevicePolicy::default()).expect("device"), + )); } out.sort_by(|a, b| a.0.cmp(&b.0)); out @@ -767,7 +775,7 @@ fn a_texture_an_argument_buffer_holds_is_read_in_its_own_class() { let Some(bc) = assemble(&name, &held_kernel(held, ty)) else { return; }; - for (stem, p) in crate::spirv::testing::committed_exact_profiles().expect("profiles") { + for (stem, p) in crate::spirv::testing::committed_profiles().expect("profiles") { let what = format!("{name} on {stem}"); let a = match compile_bitcode( &bc, @@ -945,7 +953,12 @@ fn integer_writes_saturate_to_the_bound_formats_channels() { ]; let profiles: Vec<_> = ["lavapipe", "moltenvk-m3"] .into_iter() - .map(|stem| (stem, profile(stem, EXACT_SAMPLING).expect("profile"))) + .map(|stem| { + ( + stem, + profile(stem, DevicePolicy::default()).expect("profile"), + ) + }) .collect(); let mut checked = 0; for (ty, pf, format, cross) in cases { diff --git a/crates/metal2vulkan/src/tests/engine_cube_gather.rs b/crates/metal2vulkan/src/tests/engine_cube_gather.rs deleted file mode 100644 index f8777de50..000000000 --- a/crates/metal2vulkan/src/tests/engine_cube_gather.rs +++ /dev/null @@ -1,1656 +0,0 @@ -//! Metal's gather of a cube texture, emulated by fetches on a device that does not sample through -//! Metal's own sampler, on the CPU interpreter: -//! -//! - Metal's own answers: eight lanes of a probe (Apple M4, macOS 27.0.1; its `gs` -//! run on the identity cube of 3x3 faces, `lanes-3.bin`), bit for bit: channel `w` through a -//! nearest sampler clamping to the edge and through one repeating, and channel `x` through the -//! first. Five lanes read across a face's edge and past both edges, and three wrap a face -//! coordinate of 1. -//! - The rule: random texels of every format family on faces of 1, 2, 3, and 5 texels and a cube -//! array's cubes, every channel, `float` and `half` results, bit for bit against the reference -//! of the linear cube emulation's tests (`engine_linear_cube`): the four taps of the linear -//! filter's footprint in gather order, a tap past both edges a normalized format's made-up texel -//! and a float format's `x` face's, a `half` result the texel rounded to nearest even. Integer -//! results, the tap past both edges the `x` face's texel. An 8-bit sRGB format through the -//! slot's raw view under its variant: each tap's table step, the corner's made-up step. -//! - A repeating face axis wraps a face coordinate of 1 on faces of 3 and 5 texels: the sampler's -//! `s` address the face's `s` axis and its `t` address the `t` axis, its `r` address neither. -//! - The selection and the interface: an emulated gather is `sampler.gather.cube`, records -//! `CubeFaceReciprocal` (and a `float` or `half` one `DeviceGatherFootprint`, for a format whose -//! corner rule is not measured), and declares the slot's 2D-array view of its faces; a device -//! with `VkProperty::MetalSampler` keeps every gather. -//! - The word estimate bounds the emission, which validates, on every committed profile. -//! -//! `llvm-as` assembles the kernels; without it the tests skip visibly. - -use crate::budget::SPIRV_WORDS; -use crate::device::requirements::{VkFeature, VkProperty}; -use crate::library::{FunctionArtifact, FunctionConstantValues}; -use crate::metal::texel_format::{texel_format, CubeCorner, TexelFormat}; -use crate::metal::PixelFormat; -use crate::pipeline::compile::{compile_bitcode, plan_bitcode, EntryRef}; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::sym::{ResourceKind, SpecKey}; -use crate::pipeline::testing::{compile, link_and_validate, meter, typed_module_with}; -use crate::pipeline::PrecisionNote; -use crate::spirv::testing::committed_exact_profiles; - -use super::engine_linear_cube::{ - assemble, directions, edge_directions, footprint, images, inputs, lavapipe, m3, norm, resource, - resources, run, sampler_words, Rng, FORMATS, TEXTURE, -}; -use super::engine_linear_half::{to_half, Rounding, Stored, Texels}; -use super::engine_srgb_raw::{f32_bits, half_bits, step}; - -/// A gather's result type. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Texel { - Float, - Half, - Int, - Uint, -} - -impl Texel { - /// The MSL scalar, the AIR vector, the intrinsic's suffix, and the output's MSL type. - fn air(self) -> (&'static str, &'static str, &'static str, &'static str) { - match self { - Texel::Float => ("float", "<4 x float>", "v4f32", "float4"), - Texel::Half => ("half", "<4 x half>", "v4f16", "half4"), - Texel::Int => ("int", "<4 x i32>", "s.v4i32", "int4"), - Texel::Uint => ("uint", "<4 x i32>", "u.v4i32", "uint4"), - } - } - - fn half(self) -> bool { - self == Texel::Half - } - - /// The result's bytes per lane. - fn bytes(self) -> usize { - match self { - Texel::Half => 8, - _ => 16, - } - } - - fn integer(self) -> bool { - matches!(self, Texel::Int | Texel::Uint) - } -} - -/// The words of a constexpr nearest sampler without a mip filter addressing the `s`, `t`, and `r` -/// axes by `s`, `t`, and `r` (0 zero, 1 edge, 2 repeat, 3 mirrored repeat). -fn axes(s: u64, t: u64, r: u64) -> u64 { - sampler_words(0, 0, 0, 0) | s | t << 3 | r << 6 -} - -/// A nearest sampler clamping to the edge. -fn near() -> u64 { - sampler_words(0, 0, 1, 0) -} - -/// What a kernel gathers. -#[derive(Clone, Copy, Debug)] -enum Gather { - /// Channel `component` of a color texture, with `texel` results. - Color(Texel, u32), - /// A depth texture. - Depth, - /// A depth texture's comparison, against the lane's `w` (an array's: 0.5). - Compare, -} - -/// A kernel gathering channel `component` of `texturecube` slot 0 (`texturecube_array` where -/// `array`) through constexpr sampler `words` along `float4` buffer 0's lane `tid` (its `xyz`; its -/// `w`'s bits the array index), storing the four taps (`texel`) to buffer 1. -fn kernel(words: u64, texel: Texel, array: bool, component: u32) -> String { - kernel_of(words, Gather::Color(texel, component), array) -} - -/// A kernel making gather `g` of slot 0, a cube (a cube array where `array`), through constexpr -/// sampler `words` along `float4` buffer 0's lane `tid` (its `xyz`; its `w`'s bits the array -/// index, or a non-array comparison's reference), storing the four taps to buffer 1. -fn kernel_of(words: u64, g: Gather, array: bool) -> String { - let (texel, depth) = match g { - Gather::Color(texel, _) => (texel, false), - Gather::Depth | Gather::Compare => (Texel::Float, true), - }; - let (scalar, vec4, suffix, out_ty) = texel.air(); - let size = texel.bytes(); - let (dim, layer, layer_ty) = match array { - true => ("cube_array", "i32 %a, ", "i32, "), - false => ("cube", "", ""), - }; - let tex_ty = match depth { - true => format!("depth{dim}"), - false => format!("texture{dim}<{scalar}, sample>"), - }; - let reference = match array { - true => "float 5.000000e-01, ", - false => "float %wf, ", - }; - let (name, args, tys) = match g { - Gather::Color(_, component) => ( - format!("gather_texture_{dim}.{suffix}"), - format!("<3 x float> %d, {layer}i32 {component}, i32 0"), - format!("<3 x float>, {layer_ty}i32, i32"), - ), - Gather::Depth => ( - format!("gather_depth_{dim}.v4f32"), - format!("i32 1, <3 x float> %d, {layer}i32 0"), - format!("i32, <3 x float>, {layer_ty}i32"), - ), - Gather::Compare => ( - format!("gather_compare_depth_{dim}.f32"), - format!("i32 1, <3 x float> %d, {layer}{reference}i32 0"), - format!("i32, <3 x float>, {layer_ty}float, i32"), - ), - }; - format!( - r#"@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 {words}, i64 0], align 8 - -define void @k(ptr addrspace(1) %t, ptr addrspace(1) %c, ptr addrspace(1) %out, i32 %tid) {{ - %i = zext i32 %tid to i64 - %p = getelementptr inbounds <4 x float>, ptr addrspace(1) %c, i64 %i - %c4 = load <4 x float>, ptr addrspace(1) %p, align 16 - %d = shufflevector <4 x float> %c4, <4 x float> zeroinitializer, <3 x i32> - %wf = extractelement <4 x float> %c4, i64 3 - %a = bitcast float %wf to i32 - %r = call {{ {vec4}, i8 }} @air.{name}(ptr addrspace(1) %t, ptr addrspace(2) @__air_sampler_state, {args}) - %v = extractvalue {{ {vec4}, i8 }} %r, 0 - %q = getelementptr inbounds {vec4}, ptr addrspace(1) %out, i64 %i - store {vec4} %v, ptr addrspace(1) %q, align {size} - ret void -}} - -declare {{ {vec4}, i8 }} @air.{name}(ptr addrspace(1), ptr addrspace(2), {tys}) - -!air.kernel = !{{!0}} -!air.sampler_states = !{{!7}} -!0 = !{{ptr @k, !1, !2}} -!1 = !{{}} -!2 = !{{!3, !4, !5, !6}} -!3 = !{{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"{tex_ty}", !"air.arg_name", !"t"}} -!4 = !{{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"c"}} -!5 = !{{i32 2, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 {size}, !"air.arg_type_align_size", i32 {size}, !"air.arg_type_name", !"{out_ty}", !"air.arg_name", !"out"}} -!6 = !{{i32 3, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"tid"}} -!7 = !{{!"air.sampler_state", ptr addrspace(2) @__air_sampler_state}} -"# - ) -} - -// ---- The reference ---------------------------------------------------------------------------- - -/// Gather order as indices into a footprint's taps (`footprint`'s `(i, j)`, `(i + 1, j)`, `(i, j + -/// 1)`, `(i + 1, j + 1)`): `x` `(i, j + 1)`, `y` `(i + 1, j + 1)`, `z` `(i + 1, j)`, `w` `(i, j)`. -const ORDER: [usize; 4] = [2, 3, 1, 0]; - -/// The stored channel `c` Metal gathers at a tap reading texels `at` (`footprint`'s) of cube -/// texels `stored(face, i, j)` of format class `class`: the texel, or past both edges a normalized -/// format's made-up code `⌊(6 X + 5 Y + 5 Z + 8) / 16⌋` (codes read from `-scale` up) and any -/// other format's `x` face's texel. -fn gathered( - class: u32, - at: &[(usize, i64, i64)], - stored: &dyn Fn(usize, i64, i64) -> [Stored; 4], - c: usize, -) -> Stored { - let v = |k: usize| stored(at[k].0, at[k].1, at[k].2)[c]; - match (at.len(), norm(class)) { - (3, Some((scale, _))) => { - let code = |k: usize| match v(k) { - Stored::Code(x) => x.max(-scale), - Stored::Value(_) => unreachable!("a float texel of a normalized format"), - }; - Stored::Code((6 * code(0) + 5 * code(1) + 5 * code(2) + 8).div_euclid(16)) - } - _ => v(0), - } -} - -/// An 8-bit sRGB format's gathered bits of channel `c` at a tap reading texels `at` of codes -/// `codes(face, i, j)`: a color channel's table step `k` as `k / 4095`, alpha's code as -/// `code / 255`, past both edges the made-up step or code, each correctly rounded (`half`). -fn srgb_gathered( - at: &[(usize, i64, i64)], - codes: &dyn Fn(usize, i64, i64) -> [u32; 4], - (c, half): (usize, bool), -) -> u32 { - let color = c < 3; - let unit = |code: u32| match color { - true => step(code), - false => u64::from(code), - }; - let v = |k: usize| unit(codes(at[k].0, at[k].1, at[k].2)[c]); - let n = match at.len() { - 3 => (6 * v(0) + 5 * v(1) + 5 * v(2) + 8) >> 4, - _ => v(0), - }; - let grid = if color { 4095 } else { 255 }; - match half { - true => u32::from(half_bits(n, grid)), - false => f32_bits(n, grid), - } -} - -/// The bits of a gathered `f32` texel `v` as a `float` result, or rounded to nearest even as a -/// `half` one. -fn result_bits(v: f32, half: bool) -> u32 { - match half { - true => u32::from(to_half(f64::from(v), Rounding::NearestEven)), - false => v.to_bits(), - } -} - -/// Every lane of random cubes of every format family (faces of 1 texel and of 2, 3, or 5; three -/// cubes of an array) gathers Metal's taps, every channel, with `texel` results (`float` or -/// `half`), through a nearest or a linear sampler alike; some lanes of each read a corner tap. -fn check_formats(texel: Texel) { - let p = lavapipe(); - for array in [false, true] { - for component in 0..4u32 { - // A gather reads no filter: nearest and linear samplers alike. - let words = sampler_words(u64::from(component % 2), 0, 1, 0); - let name = format!("{texel:?} array={array} component={component}"); - let Some(bc) = assemble(&name, &kernel(words, texel, array, component)) else { - return; - }; - let (plan, m) = typed_module_with(&bc, "k", &p, &inputs(false)) - .unwrap_or_else(|e| panic!("{name}: {e}")); - let cubes = if array { 3 } else { 1 }; - for (seed, pf) in FORMATS.iter().enumerate() { - let class = texel_format(*pf).0; - let other = [2u32, 3, 5][(seed + component as usize) % 3]; - let sizes = if array { vec![other] } else { vec![1, other] }; - for n in sizes { - let mut rng = Rng(0x0c6a_7e23_0000 - + u64::from(component) * 4096 - + seed as u64 * 64 - + u64::from(n)); - let layers = 6 * cubes; - let tex = - Texels::random(class, i64::from(n), i64::from(n * layers), rng.next()); - let stored = |l: u32, i: i64, j: i64| -> [Stored; 4] { - tex.t[((i64::from(l * n) + j) * i64::from(n) + i) as usize] - }; - let imgs = images(&m, (n, layers), false, &|l, i, j| { - stored(l, i64::from(i), i64::from(j)).map(|s| tex.fetched(s).to_bits()) - }); - let lanes = directions(n, 64, cubes, &mut rng); - let res = resources(&plan, &lanes, texel.bytes(), class); - let out = run(&m, &res, &imgs, texel.half()); - let mut corners = 0; - for (lane, (d, got)) in lanes.iter().zip(&out).enumerate() { - let dir = [d[0], d[1], d[2]].map(f32::from_bits); - let fp = footprint(dir, n, (false, false)); - let base = 6 * if array { d[3].min(cubes - 1) } else { 0 }; - let at = |g: usize, i: i64, j: i64| stored(base + g as u32, i, j); - corners += usize::from(fp.iter().any(|(_, t)| t.len() == 3)); - let want: [u32; 4] = std::array::from_fn(|k| { - let s = gathered(class, &fp[ORDER[k]].1, &at, component as usize); - result_bits(tex.fetched(s), texel.half()) - }); - assert_eq!( - *got, want, - "{name} {pf:?} n={n} lane {lane} {dir:?} [{}]: {got:08x?} vs \ - {want:08x?}", - d[3] - ); - } - assert!(corners > 0, "{name} {pf:?} n={n}: no lane reads a corner"); - } - } - } - } -} - -/// `float` gathers of every format family are Metal's taps, bit for bit. -#[test] -fn float_cube_gathers_take_metals_taps() { - check_formats(Texel::Float); -} - -/// `half` gathers of every format family are Metal's taps rounded to nearest even, bit for bit. -#[test] -fn half_cube_gathers_take_metals_taps() { - check_formats(Texel::Half); -} - -/// A channel of a `CubeCorner` format as the device fetches it: a step `k / D` of its stored grid -/// `D` (`k` from `-D` where signed), a float value, or a missing channel's. -#[derive(Clone, Copy, Debug, PartialEq)] -enum Chan { - Step(i64, bool), - Float, - Missing, -} - -/// The fetched channels of `pf`, a format of a `CubeCorner`: its stored grids, which divide the -/// corner's grids. -fn corner_channels(pf: PixelFormat) -> [Chan; 4] { - use Chan::{Float, Missing, Step}; - use PixelFormat as P; - let u = |bits: u32| Step((1 << bits) - 1, false); - match pf { - P::RG11B10Float | P::RGB9E5Float | P::BC6HRGBFloat | P::BC6HRGBUfloat => { - [Float, Float, Float, Missing] - } - P::ASTC4x4HDR - | P::ASTC5x4HDR - | P::ASTC5x5HDR - | P::ASTC6x5HDR - | P::ASTC6x6HDR - | P::ASTC8x5HDR - | P::ASTC8x6HDR - | P::ASTC8x8HDR - | P::ASTC10x5HDR - | P::ASTC10x6HDR - | P::ASTC10x8HDR - | P::ASTC10x10HDR - | P::ASTC12x10HDR - | P::ASTC12x12HDR => [Float; 4], - P::ABGR4Unorm => [u(4); 4], - P::BC1RGBA | P::BC2RGBA | P::BC3RGBA | P::BC7RGBAUnorm | P::ETC2RGB8A1 | P::EACRGBA8 => { - [u(8); 4] - } - P::ETC2RGB8 => [u(8), u(8), u(8), Missing], - P::RGB10A2Unorm | P::BGR10A2Unorm => [u(10), u(10), u(10), u(2)], - P::A1BGR5Unorm | P::BGR5A1Unorm => [u(5), u(5), u(5), u(1)], - P::B5G6R5Unorm => [u(5), u(6), u(5), Missing], - P::EACR11Unorm => [u(11), Missing, Missing, Missing], - P::EACRG11Unorm => [u(11), u(11), Missing, Missing], - P::EACR11Snorm => [Step(1023, true), Missing, Missing, Missing], - P::EACRG11Snorm => [Step(1023, true), Step(1023, true), Missing, Missing], - P::BC4RUnorm => [Step(16320, false), Missing, Missing, Missing], - P::BC5RGUnorm => [Step(16320, false), Step(16320, false), Missing, Missing], - P::BC4RSnorm => [Step(8128, true), Missing, Missing, Missing], - P::BC5RGSnorm => [Step(8128, true), Step(8128, true), Missing, Missing], - _ => panic!("{pf:?} is not a corner format"), - } -} - -/// A cube gather of a format of a `CubeCorner` (its `TexelFormat::CORNER` field alone) is emulated, -/// its taps the fetched texels in gather order and the tap past both edges the `x` face's texel -/// (the float formats) or the texel made up of the three faces' codes on each channel's grid, `⌊(6 -/// X + 5 Y + 5 Z + 8) / 16⌋` correctly rounded, bit for bit with `float` and `half` results, every -/// channel, on random texels of each format's stored grids (fetched as their steps `k / D` -/// correctly rounded) on faces of 2, 3, and 5 texels: one color format of each class and channel -/// layout, which the others share. -#[test] -fn a_cube_corner_class_gathers_its_corner() { - let p = lavapipe(); - let mut formats: Vec = Vec::new(); - for &pf in PixelFormat::ALL { - if CubeCorner::of(pf).is_none() || pf == PixelFormat::Depth32FloatStencil8 { - continue; - } - // The corner's class: the field alone (a packed format's family and field, are no - // corner's). - let corner = |q: PixelFormat| texel_format(q).0 & TexelFormat::CORNER_MASK; - let shared = |q: &PixelFormat| { - corner(*q) == corner(pf) && corner_channels(*q) == corner_channels(pf) - }; - if !formats.iter().any(shared) { - formats.push(pf); - } - } - assert_eq!(formats.len(), 16, "{formats:?}"); - for texel in [Texel::Float, Texel::Half] { - for component in 0..4u32 { - let words = sampler_words(u64::from(component % 2), 0, 1, 0); - let name = format!("{texel:?} component={component}"); - let Some(bc) = assemble(&name, &kernel(words, texel, false, component)) else { - return; - }; - let (plan, m) = typed_module_with(&bc, "k", &p, &inputs(false)) - .unwrap_or_else(|e| panic!("{name}: {e}")); - for (seed, pf) in formats.iter().enumerate() { - let Some(corner) = CubeCorner::of(*pf) else { - continue; - }; - let class = texel_format(*pf).0; - let chans = corner_channels(*pf); - let c = component as usize; - for n in [2u32, 3, 5] { - let mut rng = Rng(0x0c0e_4150_0000 - + u64::from(component) * 4096 - + seed as u64 * 64 - + u64::from(n)); - // Each texel's fetched channels, and its codes on their stored grids. - let texels: Vec<[(f32, i64); 4]> = (0..6 * n * n) - .map(|_| { - std::array::from_fn(|k| match chans[k] { - Chan::Step(d, signed) => { - let lo = if signed { -d } else { 0 }; - let code = lo + rng.below((d - lo + 1) as u64) as i64; - ((code as f64 / d as f64) as f32, code) - } - Chan::Float => { - let m = rng.below(4096) as f64; - ((m * 2f64.powi(-10)) as f32, 0) - } - Chan::Missing => (if k == 3 { 1.0 } else { 0.0 }, 0), - }) - }) - .collect(); - let at = |l: usize, i: i64, j: i64| { - texels[((l as i64 * i64::from(n) + j) * i64::from(n) + i) as usize] - }; - let imgs = images(&m, (n, 6), false, &|l, i, j| { - at(l as usize, i64::from(i), i64::from(j)).map(|(v, _)| v.to_bits()) - }); - let lanes = directions(n, 64, 1, &mut rng); - let out = run( - &m, - &resources(&plan, &lanes, texel.bytes(), class), - &imgs, - texel.half(), - ); - let mut corners = 0; - for (lane, (d, got)) in lanes.iter().zip(&out).enumerate() { - let dir = [d[0], d[1], d[2]].map(f32::from_bits); - let fp = footprint(dir, n, (false, false)); - corners += usize::from(fp.iter().any(|(_, t)| t.len() == 3)); - let want: [u32; 4] = std::array::from_fn(|k| { - let tap = &fp[ORDER[k]].1; - let read = |q: usize| at(tap[q].0, tap[q].1, tap[q].2)[c]; - let v = match (tap.len(), corner.grids(), chans[c]) { - (3, Some(grids), Chan::Step(stored, _)) => { - // The codes on the corner's grid, which the stored grid - // divides. - let grid = i64::from(grids[c]); - let code = |q: usize| read(q).1 * (grid / stored); - let made = (6 * code(0) + 5 * code(1) + 5 * code(2) + 8) - .div_euclid(16); - (made as f64 / grid as f64) as f32 - } - _ => read(0).0, - }; - result_bits(v, texel.half()) - }); - assert_eq!( - *got, want, - "{name} {pf:?} n={n} lane {lane} {dir:?}: {got:08x?} vs {want:08x?}" - ); - } - assert!(corners > 0, "{name} {pf:?} n={n}: no lane reads a corner"); - } - } - } - } -} - -/// Integer gathers (`int` and `uint`, a cube and a cube array, channels `x` and `w`) are the -/// fetched texels in gather order, the tap past both edges the `x` face's texel, on random words. -#[test] -fn integer_cube_gathers_take_metals_taps() { - let p = lavapipe(); - for texel in [Texel::Int, Texel::Uint] { - for array in [false, true] { - for component in [0u32, 3] { - let name = format!("{texel:?} array={array} component={component}"); - let Some(bc) = assemble(&name, &kernel(near(), texel, array, component)) else { - return; - }; - let (plan, m) = typed_module_with(&bc, "k", &p, &inputs(false)) - .unwrap_or_else(|e| panic!("{name}: {e}")); - let cubes = if array { 2 } else { 1 }; - for n in [1u32, 2, 3, 5] { - let mut rng = Rng(0x01a7_e623_0000 + u64::from(component) * 64 + u64::from(n)); - let layers = 6 * cubes; - let words: Vec<[u32; 4]> = (0..layers * n * n) - .map(|_| std::array::from_fn(|_| rng.next() as u32)) - .collect(); - let word = |l: u32, i: i64, j: i64| -> [u32; 4] { - words[((i64::from(l * n) + j) * i64::from(n) + i) as usize] - }; - let imgs = images(&m, (n, layers), false, &|l, i, j| { - word(l, i64::from(i), i64::from(j)) - }); - let lanes = directions(n, 64, cubes, &mut rng); - let out = run(&m, &resources(&plan, &lanes, 16, 0), &imgs, false); - let mut corners = 0; - for (lane, (d, got)) in lanes.iter().zip(&out).enumerate() { - let dir = [d[0], d[1], d[2]].map(f32::from_bits); - let fp = footprint(dir, n, (false, false)); - let base = 6 * if array { d[3].min(cubes - 1) } else { 0 }; - corners += usize::from(fp.iter().any(|(_, t)| t.len() == 3)); - let want: [u32; 4] = std::array::from_fn(|k| { - let (g, i, j) = fp[ORDER[k]].1[0]; - word(base + g as u32, i, j)[component as usize] - }); - assert_eq!( - *got, want, - "{name} n={n} lane {lane} {dir:?}: {got:08x?} vs {want:08x?}" - ); - } - assert!(corners > 0, "{name} n={n}: no lane reads a corner"); - } - } - } - } -} - -/// An 8-bit sRGB format's gather (through the slot's raw view, under its variant) is each tap's -/// table step, the corner's made-up step, bit for bit with `half` and `float` results, every -/// channel, on random codes. -#[test] -fn a_raw_cube_gather_takes_metals_steps() { - let p = lavapipe(); - let class = texel_format(PixelFormat::RGBA8UnormSRGB).0; - for texel in [Texel::Half, Texel::Float] { - for component in 0..4u32 { - let name = format!("srgb {texel:?} component={component}"); - let Some(bc) = assemble(&name, &kernel(near(), texel, false, component)) else { - return; - }; - let (plan, m) = typed_module_with(&bc, "k", &p, &inputs(true)) - .unwrap_or_else(|e| panic!("{name}: {e}")); - assert!( - !plan.precision.contains(&PrecisionNote::SrgbTexelDecode), - "{name}" - ); - for n in [1u32, 2, 3] { - let mut rng = Rng(0x05ee_d023_0000 + u64::from(component) * 64 + u64::from(n)); - let codes: Vec<[u32; 4]> = (0..6 * n * n) - .map(|_| std::array::from_fn(|_| rng.below(256) as u32)) - .collect(); - let code = |l: usize, i: i64, j: i64| { - codes[((l as i64 * i64::from(n) + j) * i64::from(n) + i) as usize] - }; - let imgs = images(&m, (n, 6), true, &|l, i, j| { - code(l as usize, i64::from(i), i64::from(j)) - .map(|c| f32_bits(u64::from(c), 255)) - }); - let lanes = directions(n, 96, 0, &mut rng); - let res = resources(&plan, &lanes, texel.bytes(), class); - let out = run(&m, &res, &imgs, texel.half()); - for (lane, (d, got)) in lanes.iter().zip(&out).enumerate() { - let dir = [d[0], d[1], d[2]].map(f32::from_bits); - let fp = footprint(dir, n, (false, false)); - let want: [u32; 4] = std::array::from_fn(|k| { - srgb_gathered(&fp[ORDER[k]].1, &code, (component as usize, texel.half())) - }); - assert_eq!( - *got, want, - "{name} n={n} lane {lane} {dir:?}: {got:08x?} vs {want:08x?}" - ); - } - } - } - } -} - -/// A gather through a sampler repeating on a face axis wraps a face coordinate of exactly 1 to 0 on -/// faces of 3 and 5 texels and stays on the last texel on faces of 4, the sampler's `s` address -/// governing the face's `s` axis and its `t` address the `t` axis, its `r` address neither: every -/// lane of [`edge_directions`] is the rule, bit for bit (each axis alone on faces of 3 texels), and -/// some lanes of each wrapping case on a size that is not a power of two gather other taps than a -/// clamping sampler's. -#[test] -fn a_repeating_face_axis_wraps_a_gather() { - let p = lavapipe(); - let pf = PixelFormat::RGBA32Float; - let class = texel_format(pf).0; - let lanes = edge_directions(); - // (name, sampler, the face's `s` and `t` axes wrap) - let cases = [ - ("repeat", axes(2, 2, 2), (true, true)), - ("s repeat", axes(2, 1, 1), (true, false)), - ("t repeat", axes(1, 2, 1), (false, true)), - ("r repeat", axes(1, 1, 2), (false, false)), - ]; - for (name, words, wrap) in cases { - let Some(bc) = assemble(name, &kernel(words, Texel::Float, false, 3)) else { - return; - }; - let (plan, m) = typed_module_with(&bc, "k", &p, &inputs(false)) - .unwrap_or_else(|e| panic!("{name}: {e}")); - let sizes: &[u32] = match wrap { - (true, true) => &[3, 5, 4], - _ => &[3], - }; - for &n in sizes { - let mut rng = Rng(0x0e0d_9e23_0000 + u64::from(n)); - let tex = Texels::random(class, i64::from(n), i64::from(6 * n), rng.next()); - let stored = |l: usize, i: i64, j: i64| -> [Stored; 4] { - tex.t[((l as i64 * i64::from(n) + j) * i64::from(n) + i) as usize] - }; - let imgs = images(&m, (n, 6), false, &|l, i, j| { - stored(l as usize, i64::from(i), i64::from(j)).map(|s| tex.fetched(s).to_bits()) - }); - let out = run(&m, &resources(&plan, &lanes, 16, class), &imgs, false); - let mut moved = 0; - for (lane, (d, got)) in lanes.iter().zip(&out).enumerate() { - let dir = [d[0], d[1], d[2]].map(f32::from_bits); - let fp = footprint(dir, n, wrap); - moved += usize::from(fp != footprint(dir, n, (false, false))); - let want: [u32; 4] = std::array::from_fn(|k| { - tex.fetched(gathered(class, &fp[ORDER[k]].1, &stored, 3)) - .to_bits() - }); - assert_eq!( - *got, want, - "{name} n={n} lane {lane} {dir:?}: {got:08x?} vs {want:08x?}" - ); - } - match n.is_power_of_two() || wrap == (false, false) { - true => assert_eq!(moved, 0, "{name} n={n}"), - false => assert!(moved > 0, "{name} n={n}: no lane wraps"), - } - } - } -} - -// ---- Runtime samplers --------------------------------------------------------------------------- - -/// [`kernel_of`]'s kernel of a cube (not an array) through runtime sampler slot 0, argument 3, -/// in place of a constexpr sampler. -fn runtime_kernel_of(g: Gather) -> String { - let constexpr = kernel_of(0, g, false); - let first = constexpr - .find("define void") - .expect("the kernel's definition"); - let sampler = "!7 = !{i32 3, !\"air.sampler\", !\"air.location_index\", i32 0, i32 1, \ - !\"air.arg_type_name\", !\"sampler\", !\"air.arg_name\", !\"s\"}\n"; - // The sampler-state metadata first: it names the constexpr sampler's global too. - constexpr[first..] - .replace( - "!7 = !{!\"air.sampler_state\", ptr addrspace(2) @__air_sampler_state}\n", - sampler, - ) - .replace( - "ptr addrspace(1) %out, i32 %tid)", - "ptr addrspace(1) %out, ptr addrspace(2) %s, i32 %tid)", - ) - .replace( - "ptr addrspace(2) @__air_sampler_state", - "ptr addrspace(2) %s", - ) - .replace("!air.sampler_states = !{!7}\n", "") - .replace("!2 = !{!3, !4, !5, !6}", "!2 = !{!3, !4, !5, !7, !6}") - .replace( - "!6 = !{i32 3, !\"air.thread_position_in_grid\"", - "!6 = !{i32 4, !\"air.thread_position_in_grid\"", - ) -} - -/// The `SamplerState` specialization of compiled `a`: its key and the fields of the word the -/// function reads. -fn sampler_state(a: &FunctionArtifact, name: &str) -> (SpecKey, u32) { - let state = a.interface.read_keys().into_iter().find_map(|k| match k { - SpecKey::SamplerState { fields, .. } => Some((k, fields)), - _ => None, - }); - state.unwrap_or_else(|| panic!("{name}: no `SamplerState` specialization")) -} - -/// A cube gather through a runtime sampler slot takes Metal's footprint by fetches -/// (`sampler.gather.cube`), its face axes wrapped by the bound sampler's word: a face axis whose -/// word's mode is `repeat` wraps a face coordinate of 1 on faces of 3 and 5 texels and not of 4, -/// each axis by its own mode, and `clamp_to_edge` and `mirrored_repeat` read as clamping, every -/// lane of [`edge_directions`] bit for bit on the interpreter. -#[test] -fn a_runtime_sampler_wraps_a_cube_gather_by_its_word() { - use crate::metal::sampler::SamplerWord; - use crate::metal::SamplerAddressMode as M; - let p = lavapipe(); - let name = "runtime cube gather"; - let Some(bc) = assemble(name, &runtime_kernel_of(Gather::Color(Texel::Float, 3))) else { - return; - }; - let a = compile(&bc, "k", &p).unwrap_or_else(|e| panic!("{name}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name}: {e}")); - assert!(emulated(&a, "sampler.gather"), "{name}: not emulated"); - let (key, fields) = sampler_state(&a, name); - let address = SamplerWord::ADDRESS[0] | SamplerWord::ADDRESS[1]; - assert_eq!( - fields & address, - address, - "{name}: the word's fields {fields:#x}" - ); - let (plan, m) = - typed_module_with(&bc, "k", &p, &inputs(false)).unwrap_or_else(|e| panic!("{name}: {e}")); - let pf = PixelFormat::RGBA32Float; - let class = texel_format(pf).0; - let lanes = edge_directions(); - // (the `s` and `t` modes, faces' sizes) - let cases: [((M, M), &[u32]); 5] = [ - ((M::Repeat, M::Repeat), &[3, 5, 4]), - ((M::Repeat, M::ClampToEdge), &[3]), - ((M::ClampToEdge, M::Repeat), &[3]), - ((M::ClampToEdge, M::ClampToEdge), &[3]), - ((M::MirrorRepeat, M::MirrorRepeat), &[3]), - ]; - for ((ms, mt), sizes) in cases { - let word = ms.as_raw() << SamplerWord::ADDRESS_SHIFT[0] - | mt.as_raw() << SamplerWord::ADDRESS_SHIFT[1] - | M::Repeat.as_raw() << SamplerWord::ADDRESS_SHIFT[2]; - let wrap = (ms == M::Repeat, mt == M::Repeat); - for &n in sizes { - let mut rng = Rng(0x0e0d_9e24_0000 + u64::from(n)); - let tex = Texels::random(class, i64::from(n), i64::from(6 * n), rng.next()); - let stored = |l: usize, i: i64, j: i64| -> [Stored; 4] { - tex.t[((l as i64 * i64::from(n) + j) * i64::from(n) + i) as usize] - }; - let imgs = images(&m, (n, 6), false, &|l, i, j| { - stored(l as usize, i64::from(i), i64::from(j)).map(|s| tex.fetched(s).to_bits()) - }); - let mut res = resources(&plan, &lanes, 16, class); - res.spec.insert(key, u64::from(word & fields)); - let out = run(&m, &res, &imgs, false); - let mut moved = 0; - for (lane, (d, got)) in lanes.iter().zip(&out).enumerate() { - let dir = [d[0], d[1], d[2]].map(f32::from_bits); - let fp = footprint(dir, n, wrap); - moved += usize::from(fp != footprint(dir, n, (false, false))); - let want: [u32; 4] = std::array::from_fn(|k| { - tex.fetched(gathered(class, &fp[ORDER[k]].1, &stored, 3)) - .to_bits() - }); - assert_eq!( - *got, want, - "{name} {ms:?} {mt:?} n={n} lane {lane} {dir:?}: {got:08x?} vs {want:08x?}" - ); - } - match n.is_power_of_two() || wrap == (false, false) { - true => assert_eq!(moved, 0, "{name} {ms:?} {mt:?} n={n}"), - false => assert!(moved > 0, "{name} {ms:?} {mt:?} n={n}: no lane wraps"), - } - } - } -} - -/// A depth cube's comparison gather through a runtime sampler slot compares each of Metal's taps -/// (`sampler.gather_compare.cube`) under the compare function the bound sampler's word states, -/// every `MTLCompareFunction`, on `Depth32Float` and `Depth16Unorm` faces of 1 and 3 texels with -/// random references, bit for bit on the interpreter. -#[test] -fn a_runtime_sampler_compares_a_cube_gather_by_its_word() { - use crate::metal::sampler::SamplerWord; - use crate::metal::CompareFunction as F; - let p = lavapipe(); - let name = "runtime cube comparison gather"; - let Some(bc) = assemble(name, &runtime_kernel_of(Gather::Compare)) else { - return; - }; - let a = compile(&bc, "k", &p).unwrap_or_else(|e| panic!("{name}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name}: {e}")); - assert!( - emulated(&a, "sampler.gather_compare"), - "{name}: not emulated" - ); - let (key, fields) = sampler_state(&a, name); - assert_eq!( - fields & SamplerWord::COMPARE, - SamplerWord::COMPARE, - "{name}: the word's fields {fields:#x}" - ); - let (plan, m) = - typed_module_with(&bc, "k", &p, &inputs(false)).unwrap_or_else(|e| panic!("{name}: {e}")); - // Each function and [`passes`]' code for it. - let functions = [ - (F::Never, 8), - (F::Less, 1), - (F::Equal, 5), - (F::LessEqual, 2), - (F::Greater, 3), - (F::NotEqual, 6), - (F::GreaterEqual, 4), - (F::Always, 7), - ]; - for (f, op) in functions { - let word = f.as_raw() << SamplerWord::COMPARE_SHIFT; - for (seed, pf) in DEPTHS.iter().enumerate() { - let class = texel_format(*pf).0; - for n in [1u32, 3] { - let mut rng = Rng(0x0c09_9a24_0000 + op * 4096 + seed as u64 * 64 + u64::from(n)); - let tex = Texels::random( - depth_values(*pf), - i64::from(n), - i64::from(6 * n), - rng.next(), - ); - let stored = |l: u32, i: i64, j: i64| -> [Stored; 4] { - tex.t[((i64::from(l * n) + j) * i64::from(n) + i) as usize] - }; - let imgs = images(&m, (n, 6), false, &|l, i, j| { - stored(l, i64::from(i), i64::from(j)).map(|s| tex.fetched(s).to_bits()) - }); - let mut lanes = directions(n, 64, 1, &mut rng); - for lane in lanes.iter_mut() { - let r = match rng.below(2) { - 0 => tex.fetched(tex.t[rng.below(tex.t.len() as u64) as usize][0]), - _ => -0.5 + 2.0 * (rng.below(1 << 20) as f32 / (1 << 20) as f32), - }; - lane[3] = r.to_bits(); - } - let mut res = resources(&plan, &lanes, 16, class); - res.spec.insert(key, u64::from(word & fields)); - let out = run(&m, &res, &imgs, false); - for (lane, (d, got)) in lanes.iter().zip(&out).enumerate() { - let dir = [d[0], d[1], d[2]].map(f32::from_bits); - let fp = footprint(dir, n, (false, false)); - let r = f32::from_bits(d[3]); - let at = |g: usize, i: i64, j: i64| stored(g as u32, i, j); - let want: [u32; 4] = std::array::from_fn(|k| { - let s = gathered(class, &fp[ORDER[k]].1, &at, 0); - f32::from(u8::from(passes(op, r, s))).to_bits() - }); - assert_eq!( - *got, want, - "{name} {f:?} {pf:?} n={n} lane {lane} {dir:?} reference {r:?}: \ - {got:08x?} vs {want:08x?}" - ); - } - } - } - } -} - -// ---- Depth ------------------------------------------------------------------------------------ - -/// The depth formats whose cube gather is measured (`metal::texel_format`): -/// `Depth32Float_Stencil8`'s by its `CubeCorner`. -const DEPTHS: [PixelFormat; 3] = [ - PixelFormat::Depth32Float, - PixelFormat::Depth16Unorm, - PixelFormat::Depth32FloatStencil8, -]; - -/// The class whose random texels a depth format's tests store: its own, but -/// `Depth32Float_Stencil8`'s depth, which holds `Depth32Float`'s values. -fn depth_values(pf: PixelFormat) -> u32 { - match pf { - PixelFormat::Depth32FloatStencil8 => texel_format(PixelFormat::Depth32Float).0, - _ => texel_format(pf).0, - } -} - -/// A nearest comparison sampler clamping to the edge with compare function `op` (the sampler -/// word's code: 1 `less`, 2 `less_equal`, 3 `greater`, 4 `greater_equal`, 5 `equal`, 6 -/// `not_equal`, 7 `always`, 8 `never`). -fn compare_sampler(op: u64) -> u64 { - near() & !(0xf << 16) | op << 16 -} - -/// Whether Metal's comparison `op` ([`compare_sampler`]'s code) of reference `r` passes against a -/// tap's stored texel `s`: a float format's texel against the reference as given, in `f32`; a -/// `Depth16Unorm` code against the reference's, `r` clamped into `[0, 1]` and its exact product -/// with 65535 rounded to nearest (0.5 up), a NaN failing every ordered comparison. -fn passes(op: u64, r: f32, s: Stored) -> bool { - let (r, t) = match s { - Stored::Code(c) => { - let k = match r.is_nan() { - true => f64::NAN, - false => (f64::from(r.clamp(0.0, 1.0)) * 65535.0).round_ties_even(), - }; - (k, c as f64) - } - Stored::Value(v) => (f64::from(r), f64::from(v)), - }; - match op { - 1 => r < t, - 2 => r <= t, - 3 => r > t, - 4 => r >= t, - 5 => r == t, - 6 => r != t, - 7 => true, - _ => false, - } -} - -/// A depth cube's gather (`Depth32Float` and `Depth16Unorm`, a cube and a cube array, faces of 1, -/// 2, 3, and 5 texels) is Metal's taps in gather order, the tap past both edges `Depth32Float`'s -/// `x` face texel and `Depth16Unorm`'s made-up texel, bit for bit on random texels. -#[test] -fn depth_cube_gathers_take_metals_taps() { - let p = lavapipe(); - for array in [false, true] { - let name = format!("depth array={array}"); - let Some(bc) = assemble(&name, &kernel_of(near(), Gather::Depth, array)) else { - return; - }; - let (plan, m) = typed_module_with(&bc, "k", &p, &inputs(false)) - .unwrap_or_else(|e| panic!("{name}: {e}")); - let cubes = if array { 2 } else { 1 }; - for (seed, pf) in DEPTHS.iter().enumerate() { - let class = texel_format(*pf).0; - for n in [1u32, 2, 3, 5] { - let mut rng = Rng(0x0de9_7423_0000 + seed as u64 * 64 + u64::from(n)); - let layers = 6 * cubes; - let tex = Texels::random( - depth_values(*pf), - i64::from(n), - i64::from(n * layers), - rng.next(), - ); - let stored = |l: u32, i: i64, j: i64| -> [Stored; 4] { - tex.t[((i64::from(l * n) + j) * i64::from(n) + i) as usize] - }; - let imgs = images(&m, (n, layers), false, &|l, i, j| { - stored(l, i64::from(i), i64::from(j)).map(|s| tex.fetched(s).to_bits()) - }); - let lanes = directions(n, 64, cubes, &mut rng); - let out = run(&m, &resources(&plan, &lanes, 16, class), &imgs, false); - let mut corners = 0; - for (lane, (d, got)) in lanes.iter().zip(&out).enumerate() { - let dir = [d[0], d[1], d[2]].map(f32::from_bits); - let fp = footprint(dir, n, (false, false)); - let base = 6 * if array { d[3].min(cubes - 1) } else { 0 }; - let at = |g: usize, i: i64, j: i64| stored(base + g as u32, i, j); - corners += usize::from(fp.iter().any(|(_, t)| t.len() == 3)); - let want: [u32; 4] = std::array::from_fn(|k| { - tex.fetched(gathered(class, &fp[ORDER[k]].1, &at, 0)) - .to_bits() - }); - assert_eq!( - *got, want, - "{name} {pf:?} n={n} lane {lane} {dir:?}: {got:08x?} vs {want:08x?}" - ); - } - assert!(corners > 0, "{name} {pf:?} n={n}: no lane reads a corner"); - } - } - } -} - -/// A depth cube's comparison gather under every compare function is Metal's comparison of each tap -/// (the corner's by the format's rule) with the lane's reference, on random texels -/// (`Depth32Float`'s outside `[0, 1]` too) and references: special values (NaN, the infinities, -/// subnormals, `-0`, values beside 1), the texels' own values, references near a `Depth16Unorm` -/// code's half-way point, and random ones; and a cube array's against 0.5. -#[test] -fn depth_cube_comparison_gathers_take_metals_taps() { - let p = lavapipe(); - let specials = [ - -1.0, - -0.0, - 0.0, - 1.0, - 1.5, - 2.0, - f32::NAN, - f32::INFINITY, - f32::NEG_INFINITY, - f32::from_bits(1), - -f32::from_bits(1), - 0.5, - -0.25, - f32::from_bits(0x3f80_0001), - f32::from_bits(0x3f7f_ffff), - ]; - for array in [false, true] { - for op in 1..=8u64 { - let name = format!("compare {op} array={array}"); - let words = compare_sampler(op); - let Some(bc) = assemble(&name, &kernel_of(words, Gather::Compare, array)) else { - return; - }; - let (plan, m) = typed_module_with(&bc, "k", &p, &inputs(false)) - .unwrap_or_else(|e| panic!("{name}: {e}")); - let cubes = if array { 2 } else { 1 }; - for (seed, pf) in DEPTHS.iter().enumerate() { - let class = texel_format(*pf).0; - for n in [1u32, 3] { - let mut rng = - Rng(0x0c09_9a23_0000 + op * 4096 + seed as u64 * 64 + u64::from(n)); - let layers = 6 * cubes; - let tex = Texels::random( - depth_values(*pf), - i64::from(n), - i64::from(n * layers), - rng.next(), - ); - let stored = |l: u32, i: i64, j: i64| -> [Stored; 4] { - tex.t[((i64::from(l * n) + j) * i64::from(n) + i) as usize] - }; - let imgs = images(&m, (n, layers), false, &|l, i, j| { - stored(l, i64::from(i), i64::from(j)).map(|s| tex.fetched(s).to_bits()) - }); - let mut lanes = directions(n, 64, cubes, &mut rng); - if !array { - for (k, lane) in lanes.iter_mut().enumerate() { - let r = match rng.below(4) { - 0 => specials[k % specials.len()], - 1 => tex.fetched(tex.t[rng.below(tex.t.len() as u64) as usize][0]), - 2 => -0.5 + 2.0 * (rng.below(1 << 20) as f32 / (1 << 20) as f32), - _ => { - let half = (rng.below(65535) as f64 + 0.5) / 65535.0; - let r = half as f32; - f32::from_bits( - (r.to_bits() as i64 + rng.below(5) as i64 - 2) as u32, - ) - } - }; - lane[3] = r.to_bits(); - } - } - let out = run(&m, &resources(&plan, &lanes, 16, class), &imgs, false); - for (lane, (d, got)) in lanes.iter().zip(&out).enumerate() { - let dir = [d[0], d[1], d[2]].map(f32::from_bits); - let fp = footprint(dir, n, (false, false)); - let (base, r) = match array { - true => (6 * d[3].min(cubes - 1), 0.5), - false => (0, f32::from_bits(d[3])), - }; - let at = |g: usize, i: i64, j: i64| stored(base + g as u32, i, j); - let want: [u32; 4] = std::array::from_fn(|k| { - let s = gathered(class, &fp[ORDER[k]].1, &at, 0); - let pass = passes(op, r, s); - f32::from(u8::from(pass)).to_bits() - }); - assert_eq!( - *got, want, - "{name} {pf:?} n={n} lane {lane} {dir:?} reference {r:?}: \ - {got:08x?} vs {want:08x?}" - ); - } - } - } - } - } -} - -// ---- Metal's own lanes -------------------------------------------------------------------------- - -/// Eight lanes of our probe's `gs` run on the identity cube of 3x3 faces, by their index in -/// `lanes-3.bin`: the direction's bits, and Metal's gathers there of channel `w` through a nearest -/// sampler clamping to the edge (`s_ne`) and one repeating (`s_nr`), and of channel `x` through -/// the first. Lanes 0 to 5 read across an edge and past both edges; lanes 5130, 5132, and 5135 -/// wrap a face coordinate of 1 (a tie of `y` and `z`, a tie of all three, and a minor component -/// equal to the major). -const PROBE_LANES: [(u32, [u32; 3], [[f32; 4]; 3]); 8] = [ - ( - 0, - [0x3f49_0000, 0x3f80_0000, 0xbf74_7e6e], - [ - [21.0, 3.0, 3.0, 46.0], - [21.0, 3.0, 3.0, 46.0], - [3.0, 1.0, 1.0, 6.0], - ], - ), - ( - 1, - [0x3f4b_aaab, 0xbf31_0000, 0xbf80_0000], - [ - [9.0, 36.0, 52.0, 9.0], - [9.0, 36.0, 52.0, 9.0], - [1.0, 4.0, 6.0, 1.0], - ], - ), - ( - 2, - [0x3f80_0000, 0x3f73_0000, 0x3f0b_c625], - [ - [1.0, 2.0, 24.0, 27.0], - [1.0, 2.0, 24.0, 27.0], - [1.0, 1.0, 3.0, 3.0], - ], - ), - ( - 3, - [0xbf48_5555, 0x3e86_fd85, 0x3f80_0000], - [ - [15.0, 40.0, 37.0, 12.0], - [15.0, 40.0, 37.0, 12.0], - [2.0, 5.0, 5.0, 2.0], - ], - ), - ( - 5, - [0x3f67_0000, 0xbf80_0000, 0x3f4b_aaab], - [ - [30.0, 7.0, 7.0, 45.0], - [30.0, 7.0, 7.0, 45.0], - [4.0, 1.0, 1.0, 5.0], - ], - ), - ( - 5130, - [0x3e80_0000, 0x3f80_0000, 0x3f80_0000], - [ - [38.0, 39.0, 27.0, 26.0], - [20.0, 21.0, 46.0, 47.0], - [5.0, 5.0, 3.0, 3.0], - ], - ), - ( - 5132, - [0x3f80_0000, 0x3f80_0000, 0xbf80_0000], - [ - [3.0, 46.0, 3.0, 21.0], - [39.0, 1.0, 27.0, 1.0], - [1.0, 6.0, 1.0, 3.0], - ], - ), - ( - 5135, - [0x3f80_0000, 0x3e80_0000, 0xbf80_0000], - [ - [6.0, 49.0, 46.0, 3.0], - [42.0, 4.0, 1.0, 39.0], - [1.0, 6.0, 6.0, 1.0], - ], - ), -]; - -/// The emulation answers Metal's own lanes ([`PROBE_LANES`]) on the probe's identity cube -/// (`rgba32Float`, face `f`'s texel `(i, j)` holding `(f + 1, i + 1, j + 1, 1 + 9 f -/// + 3 j + i)`), bit for bit. -#[test] -fn a_cube_gather_answers_metals_probe_lanes() { - let p = lavapipe(); - let class = texel_format(PixelFormat::RGBA32Float).0; - let lanes: Vec<[u32; 4]> = PROBE_LANES - .iter() - .map(|(_, d, _)| [d[0], d[1], d[2], 0]) - .collect(); - let identity = |l: u32, i: u32, j: u32| -> [u32; 4] { - [l + 1, i + 1, j + 1, 1 + 9 * l + 3 * j + i].map(|v| (v as f32).to_bits()) - }; - // (name, sampler, channel, Metal's result by lane) - let runs = [ - ("w edge", near(), 3, 0), - ("w repeat", axes(2, 2, 2), 3, 1), - ("x edge", near(), 0, 2), - ]; - for (name, words, component, at) in runs { - let Some(bc) = assemble(name, &kernel(words, Texel::Float, false, component)) else { - return; - }; - let (plan, m) = typed_module_with(&bc, "k", &p, &inputs(false)) - .unwrap_or_else(|e| panic!("{name}: {e}")); - let imgs = images(&m, (3, 6), false, &identity); - let out = run(&m, &resources(&plan, &lanes, 16, class), &imgs, false); - for ((index, _, metal), got) in PROBE_LANES.iter().zip(&out) { - let want = metal[at].map(f32::to_bits); - assert_eq!( - *got, want, - "{name} probe lane {index}: {got:08x?} vs Metal's {want:08x?}" - ); - } - } -} - -/// Our probe's references, in each face's order (`refs-cc.bin`): every lane reads its -/// face's centre, the face's four texels of a cube of 2x2 faces. -const CG3_REFS: [u32; 19] = [ - 0xbf80_0000, - 0x8000_0000, - 0x0000_0000, - 0x3f80_0000, - 0x3fc0_0000, - 0x4000_0000, - 0x7fc0_0000, - 0x7f80_0000, - 0xff80_0000, - 0x0000_0001, - 0x8000_0001, - 0x3f00_0000, - 0xbe80_0000, - 0x447a_0000, - 0x4040_0000, - 0x3f80_0001, - 0x3f7f_ffff, - 0x3780_0080, - 0x3f7f_ff00, -]; - -/// Our probe's `Depth32Float` cube (`tex-depth32float.bin`, face after face, rows of the -/// face): texels outside `[0, 1]`, NaN, the infinities, `-0`, and subnormals. -const CG3_FLOATS: [u32; 24] = [ - 0xbf80_0000, - 0x4000_0000, - 0x447a_0000, - 0x8000_0000, - 0x0000_0000, - 0x3f80_0000, - 0x7fc0_0000, - 0x7f80_0000, - 0xff80_0000, - 0x0000_0001, - 0x3f00_0000, - 0x3fc0_0000, - 0x8000_0001, - 0xbe80_0000, - 0x4040_0000, - 0x7149_f2ca, - 0x3f80_0000, - 0x0000_0000, - 0xbf80_0000, - 0x4000_0000, - 0x3f80_0001, - 0x3f7f_ffff, - 0x8000_0000, - 0x0000_0000, -]; - -/// Our probe's `Depth16Unorm` cube's codes (`tex-depth16unorm.bin`): 0, 1, 65534, 65535, -/// and the codes beside 0.5. -const CG3_CODES: [u64; 24] = [ - 0, 65535, 0, 65535, 65535, 0, 1, 65534, 0, 0, 65535, 65535, 1, 65534, 32768, 32767, 65535, - 65535, 0, 1, 0, 32768, 65535, 65534, -]; - -/// Metal's comparison gathers on our probe's cubes: per format and compare code -/// ([`compare_sampler`]), per face, per reference of [`CG3_REFS`], the taps that pass (bit `k` -/// the gather-order tap `k`; `out-cc-.bin`). -type Cg3 = (PixelFormat, u64, [[u8; 19]; 6]); - -const CG3: [Cg3; 4] = [ - ( - PixelFormat::Depth32Float, - 2, - [ - [15, 7, 7, 5, 5, 5, 0, 0, 15, 5, 7, 5, 7, 1, 1, 5, 5, 5, 5], - [ - 14, 14, 14, 6, 2, 2, 0, 2, 14, 6, 14, 6, 14, 2, 2, 2, 6, 6, 6, - ], - [7, 7, 7, 2, 2, 0, 0, 0, 15, 7, 7, 3, 7, 0, 0, 2, 2, 3, 2], - [15, 3, 3, 3, 3, 3, 0, 0, 15, 3, 11, 3, 15, 2, 3, 3, 3, 3, 3], - [ - 15, 14, 14, 10, 2, 2, 0, 0, 15, 10, 14, 10, 14, 0, 0, 2, 10, 10, 10, - ], - [ - 15, 15, 15, 8, 0, 0, 0, 0, 15, 12, 15, 12, 15, 0, 0, 8, 12, 12, 12, - ], - ], - ), - ( - PixelFormat::Depth32Float, - 6, - [ - [ - 7, 13, 13, 15, 15, 11, 15, 15, 15, 15, 15, 15, 15, 14, 15, 15, 15, 15, 15, - ], - [ - 15, 7, 7, 11, 15, 15, 15, 13, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, - ], - [ - 15, 15, 15, 15, 13, 15, 15, 15, 7, 11, 15, 14, 15, 15, 15, 15, 15, 15, 15, - ], - [ - 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 7, 15, 11, 15, 14, 15, 15, 15, 15, - ], - [ - 14, 11, 11, 7, 15, 13, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, - ], - [ - 15, 12, 12, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 7, 11, 15, 15, - ], - ], - ), - ( - PixelFormat::Depth16Unorm, - 2, - [ - [ - 15, 15, 15, 6, 6, 6, 0, 6, 15, 15, 15, 6, 15, 6, 6, 6, 6, 6, 6, - ], - [ - 15, 15, 15, 8, 8, 8, 0, 8, 15, 15, 15, 10, 15, 8, 8, 8, 8, 11, 10, - ], - [ - 15, 15, 15, 3, 3, 3, 0, 3, 15, 15, 15, 3, 15, 3, 3, 3, 3, 3, 3, - ], - [ - 15, 15, 15, 0, 0, 0, 0, 0, 15, 15, 15, 5, 15, 0, 0, 0, 0, 15, 4, - ], - [ - 15, 15, 15, 12, 12, 12, 0, 12, 15, 15, 15, 12, 15, 12, 12, 12, 12, 14, 12, - ], - [ - 15, 15, 15, 1, 1, 1, 0, 1, 15, 15, 15, 7, 15, 1, 1, 1, 1, 7, 3, - ], - ], - ), - ( - PixelFormat::Depth16Unorm, - 6, - [ - [6, 6, 6, 9, 9, 9, 15, 9, 6, 6, 6, 15, 6, 9, 9, 9, 9, 15, 15], - [ - 11, 11, 11, 7, 7, 7, 15, 7, 11, 11, 11, 15, 11, 7, 7, 7, 7, 14, 13, - ], - [ - 3, 3, 3, 12, 12, 12, 15, 12, 3, 3, 3, 15, 3, 12, 12, 12, 12, 15, 15, - ], - [ - 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 14, 15, 15, 15, 15, 15, 7, 11, - ], - [ - 14, 14, 14, 3, 3, 3, 15, 3, 14, 14, 14, 15, 14, 3, 3, 3, 3, 13, 15, - ], - [ - 7, 7, 7, 14, 14, 14, 15, 14, 7, 7, 7, 11, 7, 14, 14, 14, 14, 15, 13, - ], - ], - ), -]; - -/// The emulation answers Metal's own comparison gathers of our probe ([`CG3`]) under -/// `less_equal` and `not_equal`, bit for bit: `Depth32Float` texels outside `[0, 1]`, NaN, and the -/// infinities compared as held, and `Depth16Unorm`'s reference clamped and rounded to its code. -#[test] -fn a_cube_comparison_answers_metals_probe_lanes() { - let p = lavapipe(); - let dirs = [ - [1.0f32, 0.0, 0.0], - [-1.0, 0.0, 0.0], - [0.0, 1.0, 0.0], - [0.0, -1.0, 0.0], - [0.0, 0.0, 1.0], - [0.0, 0.0, -1.0], - ]; - let lanes: Vec<[u32; 4]> = dirs - .iter() - .flat_map(|d| CG3_REFS.map(|r| [d[0].to_bits(), d[1].to_bits(), d[2].to_bits(), r])) - .collect(); - for (pf, op, metal) in CG3 { - let name = format!("{pf:?} compare {op}"); - let Some(bc) = assemble( - &name, - &kernel_of(compare_sampler(op), Gather::Compare, false), - ) else { - return; - }; - let (plan, m) = typed_module_with(&bc, "k", &p, &inputs(false)) - .unwrap_or_else(|e| panic!("{name}: {e}")); - let class = texel_format(pf).0; - let texel = |l: u32, i: u32, j: u32| -> [u32; 4] { - let at = (4 * l + 2 * j + i) as usize; - let d = match pf { - PixelFormat::Depth16Unorm => f32_bits(CG3_CODES[at], 65535), - _ => CG3_FLOATS[at], - }; - [d, 0, 0, 1f32.to_bits()] - }; - let imgs = images(&m, (2, 6), false, &texel); - let out = run(&m, &resources(&plan, &lanes, 16, class), &imgs, false); - for (k, got) in out.iter().enumerate() { - let want: [u32; 4] = std::array::from_fn(|t| { - let pass = metal[k / CG3_REFS.len()][k % CG3_REFS.len()] >> t & 1; - f32::from(pass).to_bits() - }); - assert_eq!( - *got, - want, - "{name} face {} reference {:#010x}: {got:08x?} vs Metal's {want:08x?}", - k / CG3_REFS.len(), - CG3_REFS[k % CG3_REFS.len()] - ); - } - } -} - -/// 24 of our probe's references (`refs-q.bin`): per reference `m` the code `k` beside -/// it, and the code Metal compared it as, the exact product `m · 65535` rounded, where rounding -/// its `f32` rounding (`k + 1/2` exactly) to even picks the other code. -const CG4: [(u64, u32, u64); 24] = [ - (9247, 0x3e10_7e90, 9247), - (54674, 0x3f55_9356, 54675), - (44434, 0x3f2d_932e, 44435), - (30830, 0x3ef0_ddf1, 30831), - (58165, 0x3f63_3663, 58165), - (39539, 0x3f1a_741a, 39539), - (12344, 0x3e40_e2c1, 12345), - (63470, 0x3f77_ef78, 63471), - (24497, 0x3ebf_63bf, 24497), - (57772, 0x3f61_ad62, 57773), - (47514, 0x3f39_9b3a, 47515), - (62446, 0x3f73_ef74, 62447), - (30899, 0x3ef1_67f1, 30899), - (36012, 0x3f0c_ad0d, 36013), - (49600, 0x3f41_c142, 49601), - (21216, 0x3ea5_c1a6, 21217), - (65248, 0x3f7e_e17f, 65249), - (59417, 0x3f68_1a68, 59417), - (40787, 0x3f1f_541f, 40787), - (48076, 0x3f3b_cd3c, 48077), - (3111, 0x3d42_78c2, 3111), - (18979, 0x3e94_4794, 18979), - (45306, 0x3f30_fb31, 45307), - (56534, 0x3f5c_d75d, 56535), -]; - -/// A `Depth16Unorm` comparison compares the code of its reference's exact product with 65535, as -/// Metal does on [`CG4`]'s references: on cubes of 2x2 faces, each face holding -/// the codes `k` and `k + 1` on either side of a reference's half-way point, `equal` passes on the -/// taps holding Metal's code. -#[test] -fn a_depth16_reference_takes_its_exact_code() { - let p = lavapipe(); - let name = "depth16 equal"; - let Some(bc) = assemble(name, &kernel_of(compare_sampler(5), Gather::Compare, false)) else { - return; - }; - let (plan, m) = - typed_module_with(&bc, "k", &p, &inputs(false)).unwrap_or_else(|e| panic!("{name}: {e}")); - let class = texel_format(PixelFormat::Depth16Unorm).0; - let dirs = [ - [1.0f32, 0.0, 0.0], - [-1.0, 0.0, 0.0], - [0.0, 1.0, 0.0], - [0.0, -1.0, 0.0], - [0.0, 0.0, 1.0], - [0.0, 0.0, -1.0], - ]; - for run6 in CG4.as_chunks::<6>().0.iter() { - let lanes: Vec<[u32; 4]> = dirs - .iter() - .zip(run6) - .map(|(d, (_, r, _))| [d[0].to_bits(), d[1].to_bits(), d[2].to_bits(), *r]) - .collect(); - // Face `l`'s texels: `k` in its first column, `k + 1` in its second. - let texel = |l: u32, i: u32, _: u32| -> [u32; 4] { - let code = run6[l as usize].0 + u64::from(i); - [f32_bits(code, 65535), 0, 0, 1f32.to_bits()] - }; - let imgs = images(&m, (2, 6), false, &texel); - let out = run(&m, &resources(&plan, &lanes, 16, class), &imgs, false); - for ((k, r, metal), got) in run6.iter().zip(&out) { - // Gather order: `x` (0, 1) and `w` (0, 0) hold `k`, `y` and `z` `k + 1`. - let held = [*k, k + 1, k + 1, *k]; - let want = held.map(|c| f32::from(u8::from(c == *metal)).to_bits()); - assert_eq!( - *got, want, - "{name} reference {r:#010x} beside {k}: {got:08x?} vs Metal's {want:08x?}" - ); - } - } -} - -// ---- Selection, interface, and size ------------------------------------------------------------- - -/// Whether artifact `a` emulates its one gather, whose census name is `census` (`.cube` where it -/// is emulated). -fn emulated(a: &FunctionArtifact, census: &str) -> bool { - let cube = a - .strategies - .entries - .get(&format!("{census}.cube")) - .map(|u| u.uses); - let plain = a.strategies.entries.get(census).map(|u| u.uses); - assert_eq!( - cube.is_some(), - plain.is_none(), - "the census of {:?}", - a.strategies - ); - cube == Some(1) -} - -/// On lavapipe a cube gather through a constexpr sampler is emulated whatever its filters, mip -/// filter, and address modes, a cube array's, an integer result's, a depth cube's, and a depth -/// cube's comparison too (`sampler.gather_compare.cube`), and records `CubeFaceReciprocal` (and for -/// a `float` or `half` result `DeviceGatherFootprint` and the slot's `TexelFormat` specialization), -/// declaring the slot's 2D-array view of its faces. On MoltenVK nothing is emulated, and every -/// gather requires `VkProperty::MetalSampler`. -#[test] -fn the_cube_gather_emulation_reaches_what_metal_measured() { - let color = |texel, component| Gather::Color(texel, component); - // (name, sampler, gather, array) - let cases = [ - ("float", near(), color(Texel::Float, 1), false), - ( - "half linear", - sampler_words(1, 0, 1, 0), - color(Texel::Half, 1), - false, - ), - ( - "float mip", - sampler_words(1, 2, 2, 0), - color(Texel::Float, 1), - false, - ), - ( - "half zero", - sampler_words(0, 0, 0, 2), - color(Texel::Half, 1), - false, - ), - ("int", near(), color(Texel::Int, 1), false), - ("uint array", near(), color(Texel::Uint, 1), true), - ("float array", axes(2, 1, 3), color(Texel::Float, 1), true), - ("depth", sampler_words(1, 0, 1, 0), Gather::Depth, false), - ("depth array", near(), Gather::Depth, true), - ("compare", compare_sampler(2), Gather::Compare, false), - ("compare array", compare_sampler(6), Gather::Compare, true), - ]; - let (lvp, m3) = (lavapipe(), m3()); - let faces = RuntimeFact::ImageViewShape { slot: TEXTURE }; - let format = RuntimeFact::TexelFormat { slot: TEXTURE }; - for (name, words, gather, array) in cases { - let Some(bc) = assemble(name, &kernel_of(words, gather, array)) else { - return; - }; - let integer = matches!(gather, Gather::Color(t, _) if t.integer()); - let census = match gather { - Gather::Compare => "sampler.gather_compare", - _ => "sampler.gather", - }; - let a = compile(&bc, "k", &lvp).unwrap_or_else(|e| panic!("{name} on lavapipe: {e}")); - link_and_validate(&a, &lvp).unwrap_or_else(|e| panic!("{name} on lavapipe: {e}")); - let what = format!("{name} on lavapipe"); - assert!(emulated(&a, census), "{what}"); - assert!( - a.precision.contains(&PrecisionNote::CubeFaceReciprocal), - "{what}" - ); - assert_eq!( - a.precision.contains(&PrecisionNote::DeviceGatherFootprint), - !integer, - "{what}" - ); - assert!(a.facts.contains(&faces), "{what}"); - assert_eq!(a.facts.contains(&format), !integer, "{what}"); - assert!( - !a.requirements - .properties - .contains(&VkProperty::MetalSampler), - "{what}" - ); - let (_, m) = typed_module_with(&bc, "k", &lvp, &inputs(false)) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let view = resource(&m, |k| *k == ResourceKind::Texture); - assert!(view.is_some(), "{what}: the view of the faces"); - let b = compile(&bc, "k", &m3).unwrap_or_else(|e| panic!("{name} on moltenvk-m3: {e}")); - link_and_validate(&b, &m3).unwrap_or_else(|e| panic!("{name} on moltenvk-m3: {e}")); - let what = format!("{name} on moltenvk-m3"); - assert!(!emulated(&b, census), "{what}"); - assert!( - !b.precision.contains(&PrecisionNote::CubeFaceReciprocal), - "{what}" - ); - assert!(!b.facts.contains(&faces), "{what}"); - assert!( - b.requirements - .properties - .contains(&VkProperty::MetalSampler), - "{what}" - ); - } -} - -/// The plan's word estimate bounds the emitted module of every cube gather form (`float`, `half`, -/// and integer results, a cube array, an sRGB variant's raw view, a repeating sampler's wrap, a -/// depth cube's gather and comparison), which validates, on every committed profile. -#[test] -fn the_cube_gather_estimate_bounds_its_emission() { - let mut modules = Vec::new(); - let repeat = axes(2, 2, 2); - for (name, words, texel, array, srgb, component) in [ - ("float", near(), Texel::Float, false, false, 0), - ("half", near(), Texel::Half, false, false, 1), - ("int", near(), Texel::Int, false, false, 2), - ("uint array", near(), Texel::Uint, true, false, 3), - ("float array", near(), Texel::Float, true, false, 3), - ("raw half", near(), Texel::Half, false, true, 0), - ("raw float array", near(), Texel::Float, true, true, 3), - ("repeat half", repeat, Texel::Half, false, false, 2), - ( - "repeat raw float array", - repeat, - Texel::Float, - true, - true, - 1, - ), - ] { - let Some(bc) = assemble(name, &kernel(words, texel, array, component)) else { - return; - }; - modules.push((name, bc, srgb)); - } - for (name, words, gather, array) in [ - ("depth", near(), Gather::Depth, false), - ("depth array", repeat, Gather::Depth, true), - ("compare", compare_sampler(1), Gather::Compare, false), - ("compare array", compare_sampler(6), Gather::Compare, true), - ( - "repeat compare", - axes(2, 2, 2) & !(0xf << 16) | 4 << 16, - Gather::Compare, - false, - ), - ] { - let Some(bc) = assemble(name, &kernel_of(words, gather, array)) else { - return; - }; - modules.push((name, bc, false)); - } - let consts = FunctionConstantValues::defaults(); - for (name, bc, srgb) in &modules { - for (stem, p) in committed_exact_profiles().expect("profiles") { - let what = format!("{name} on {stem}"); - // A profile without cube arrays refuses a cube array's gather, whose combined binding - // stays declared. - let cube_arrays = p - .fields() - .enabled - .features - .contains(&VkFeature::ImageCubeArray); - if name.contains("array") && !cube_arrays { - continue; - } - let inputs = inputs(*srgb); - let entry = EntryRef::Name("k"); - let plan = plan_bitcode(bc, entry, &consts, &p, &inputs, &mut meter()) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let a = compile_bitcode(bc, entry, &consts, &p, &inputs, &mut meter(), SPIRV_WORDS) - .unwrap_or_else(|e| panic!("{what}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: {e}")); - let words = a.module.words.len() as u64; - eprintln!("{what}: estimate {} emitted {words}", plan.estimate.words); - assert!( - plan.estimate.words >= words, - "{what}: estimate {} < emitted {words}", - plan.estimate.words - ); - } - } -} diff --git a/crates/metal2vulkan/src/tests/engine_depth_range.rs b/crates/metal2vulkan/src/tests/engine_depth_range.rs index baaf0e5c8..e18400717 100644 --- a/crates/metal2vulkan/src/tests/engine_depth_range.rs +++ b/crates/metal2vulkan/src/tests/engine_depth_range.rs @@ -9,8 +9,8 @@ //! keep such values without it (`VkProperty::DepthImageKeepsValuesOutsideUnitRange`, MoltenVK's), //! which the module then requires instead: a read, a sample and a gather read the //! texels the consumer holds, which a colour image keeps, and record nothing, their use stated by -//! the interface's `TextureSlot::access`, as do the comparisons the shader makes of such texels. A -//! size query reads no texel, and a color texture's read is not a depth texel. +//! the interface's `TextureSlot::access`. A size query reads no texel, and a color texture's read +//! is not a depth texel. //! //! `llvm-as` assembles the kernels; without it the tests skip visibly. @@ -22,9 +22,9 @@ use crate::device::requirements::{VkExtension, VkProperty}; /// The property a depth comparison the device makes requires on a device without the extension /// whose depth images keep values outside `[0, 1]`. const KEPT: VkProperty = VkProperty::DepthImageKeepsValuesOutsideUnitRange; +use crate::device::DevicePolicy; use crate::pipeline::artifact::PrecisionNote; use crate::pipeline::interface::SlotInterface; -use crate::pipeline::testing::EXACT_SAMPLING; use crate::pipeline::testing::{compile, 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"; @@ -187,7 +187,7 @@ fn the_extension_is_read_from_the_device_description() { ("intel-irisxe-anv", false), ("vk12-floor", false), ] { - let p = profile(stem, EXACT_SAMPLING).expect(stem); + let p = profile(stem, DevicePolicy::default()).expect(stem); assert_eq!(unrestricted(&p), listed, "{stem}"); } } @@ -196,39 +196,32 @@ fn the_extension_is_read_from_the_device_description() { /// profile lacks the extension and its driver is not measured to keep depth values outside /// `[0, 1]` (MoltenVK's is, and the module requires that property there instead); a read, a sample and a gather never do, their use stated by the /// texture slot's access (read or sample) on every profile, as a color read's is; a size query -/// reads no texel. The nearest comparison through a constexpr sampler is the device's only on a -/// device with `VkProperty::MetalSampler` (MoltenVK's); elsewhere the shader compares the texels a -/// sample without comparison reads, so the slot does not compare and nothing is recorded, with the -/// extension (RADV) or without it (ANV). +/// reads no texel. Every comparison is the device's, a constexpr sampler's nearest one included. #[test] fn depth_comparisons_record_the_restricted_range_without_the_extension() { let profiles = [ ( "radv", - profile("amd-rdna3-radv", EXACT_SAMPLING).expect("radv"), + profile("amd-rdna3-radv", DevicePolicy::default()).expect("radv"), ), ( "anv", - profile("intel-irisxe-anv", EXACT_SAMPLING).expect("anv"), + profile("intel-irisxe-anv", DevicePolicy::default()).expect("anv"), + ), + ( + "m3", + profile("moltenvk-m3", DevicePolicy::default()).expect("m3"), ), - ("m3", profile("moltenvk-m3", EXACT_SAMPLING).expect("m3")), ]; - let metal = |p: &DeviceProfile| { - p.fields() - .enabled - .properties - .contains(&VkProperty::MetalSampler) - }; let [(_, radv), (_, anv), (_, m3)] = &profiles; assert!(unrestricted(radv) && !unrestricted(anv) && !unrestricted(m3)); assert!(!kept(anv) && kept(m3)); - assert!(!metal(radv) && !metal(anv) && metal(m3)); for (form, text, texels, compares) in depth_kernels() { let Some(bc) = assemble(form, &text) else { return; }; for (device, p) in &profiles { - let device_compares = compares && metal(p); + let device_compares = compares; let expected = device_compares && !unrestricted(p) && !kept(p); let requires = device_compares && !unrestricted(p) && kept(p); let a = compile(&bc, "k", p).unwrap_or_else(|e| panic!("{form}: compile: {e}")); @@ -262,44 +255,3 @@ fn depth_comparisons_record_the_restricted_range_without_the_extension() { } } } - -/// A linear comparison through a constexpr sampler that the emulation reaches compares in the -/// shader the taps it fetched without comparison, which a twinned texture holds in colour, so it -/// records no `RestrictedDepthRange` without the extension (ANV), nor with it (RADV); on MoltenVK, -/// whose device comparison is Metal's own (`VkProperty::MetalSampler`), the device compares, -/// without the extension, over a depth image that keeps values outside `[0, 1]`, and requires -/// that property in place of the note. -#[test] -fn a_linear_comparison_the_shader_makes_records_no_restricted_range() { - // Linear minification and magnification, compare function `less`. - let words = SAMPLER_WORDS & !(0xf << 16) | 1 << 16 | 1 << 9 | 1 << 11; - let text = kernel_with( - words, - "depth2d", - "%r = call { float, i8 } @air.sample_compare_depth_2d.f32(ptr addrspace(1) %t, ptr addrspace(2) @__air_sampler_state, i32 1, <2 x float> , float 0.5, i1 true, <2 x i32> zeroinitializer, i1 true, float 0.0, float 0.0, i32 0) - %v = extractvalue { float, i8 } %r, 0", - "declare { float, i8 } @air.sample_compare_depth_2d.f32(ptr addrspace(1), ptr addrspace(2), i32, <2 x float>, float, i1, <2 x i32>, i1, float, float, i32)", - ); - let Some(bc) = assemble("linear compare", &text) else { - return; - }; - for (stem, requires) in [ - ("intel-irisxe-anv", false), - ("amd-rdna3-radv", false), - ("moltenvk-m3", true), - ] { - let p = profile(stem, EXACT_SAMPLING).expect(stem); - let a = compile(&bc, "k", &p).unwrap_or_else(|e| panic!("{stem}: compile: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); - assert!( - !a.precision.contains(&PrecisionNote::RestrictedDepthRange), - "{stem}: {:?}", - a.precision - ); - assert_eq!( - a.requirements.properties.contains(&KEPT), - requires, - "{stem}" - ); - } -} diff --git a/crates/metal2vulkan/src/tests/engine_device_level.rs b/crates/metal2vulkan/src/tests/engine_device_level.rs deleted file mode 100644 index 8228fe347..000000000 --- a/crates/metal2vulkan/src/tests/engine_device_level.rs +++ /dev/null @@ -1,102 +0,0 @@ -//! A sample whose level the device's level arithmetic takes (`lower::sampler::level::device_when`): -//! the owned fixture `device_level`. Under exact sampling, on every committed profile that samples -//! neither through Metal's own sampler nor natively, the pipeline records -//! `PrecisionNote::DeviceSampleLevel` for an implicit-level sample through nearest filters and a -//! nearest mip filter (with a bias within the limit or without), an integer texture's, one with -//! explicit gradients, an LOD query, and an integer texture's explicit level of `1.5` (which -//! Metal's level rule is not handed on); for a runtime sampler's, only where its word states -//! nearest filters and a nearest mip filter. It records none for a sample whose level chooses -//! nothing (nearest filters without a mip filter), a filtered one (its filter note records it), a -//! cube's (`CubeGradientFootprint`), one at an explicit level the rule snaps, or an integer -//! texture's whole level of `2`. A profile that samples through Metal's own sampler or natively -//! records none, nor does any profile under native sampling. `llvm-as` assembles the fixture; -//! without it the test skips visibly. - -use crate::device::{DevicePolicy, SamplingPolicy}; -use crate::metal::sampler::SamplerWord; -use crate::pipeline::testing::{compile, link_and_validate, llvm_assemble, AssembleError}; -use crate::pipeline::PrecisionNote::DeviceSampleLevel; -use crate::spirv::testing::committed_profiles_with; - -/// Fixture `name` assembled, or `None` (skipped visibly) without `llvm-as`. -fn assemble(name: &str) -> Option> { - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/fixtures/public/engine") - .join(format!("{name}.ll")); - match llvm_assemble(&path) { - Ok(b) => Some(b), - Err(AssembleError::Missing(t)) => { - eprintln!("SKIPPED: {t}"); - None - } - Err(AssembleError::Rejected(e)) => panic!("llvm-as rejected {name}: {e}"), - } -} - -/// Where an entry's pipeline holds the note. -#[derive(Clone, Copy, Debug)] -enum Held { - Never, - Always, - /// Where the runtime sampler's word states nearest filters and a nearest mip filter. - NearestMips, -} - -#[test] -fn a_device_level_is_noted_where_it_chooses_and_no_other_note_records_it() { - let Some(bc) = assemble("device_level") else { - return; - }; - let entries = [ - ("dl_nearest_mips", Held::Always), - ("dl_nearest_mips_bias", Held::Always), - ("dl_nearest_base", Held::Never), - ("dl_linear_mips", Held::Never), - ("dl_uint_mips", Held::Always), - ("dl_runtime", Held::NearestMips), - ("dl_query", Held::Always), - ("dl_cube", Held::Never), - ("dl_gradients", Held::Always), - ("dl_level", Held::Never), - ("dl_uint_level", Held::Always), - ("dl_uint_whole_level", Held::Never), - ]; - let exact = DevicePolicy { - sampling: SamplingPolicy::Exact, - ..DevicePolicy::default() - }; - let mut reached = 0; - for (policy, name) in [(exact, "exact"), (DevicePolicy::default(), "native")] { - for (stem, p) in committed_profiles_with(policy).expect("profiles") { - let device = p.device_samples(); - reached += usize::from(!device); - for (entry, held) in entries { - let what = format!("{entry} on {stem} under {name} sampling"); - let a = compile(&bc, entry, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let noted = a.precision.contains(&DeviceSampleLevel); - let when = a.specialized.iter().find(|s| s.note == DeviceSampleLevel); - match (device, held) { - (true, _) | (false, Held::Never) => assert!(!noted, "{what}"), - (false, Held::Always) => assert!(noted && when.is_none(), "{what}: {when:?}"), - (false, Held::NearestMips) => { - assert!(noted, "{what}"); - let when = when.unwrap_or_else(|| panic!("{what}: unconditional")); - assert!( - when.when.iter().all(|c| c.all.iter().any(|t| { - t.mask == SamplerWord::LINEAR_FILTER - && t.bits == 1 << SamplerWord::MIP_FILTER_SHIFT - && t.equal - })), - "{what}: {when:?}" - ); - } - } - } - } - } - assert!( - reached > 0, - "no profile under exact sampling takes the device's level arithmetic" - ); -} diff --git a/crates/metal2vulkan/src/tests/engine_extended_range/heap.rs b/crates/metal2vulkan/src/tests/engine_extended_range/heap.rs index df7a5684d..ffdb8b8e8 100644 --- a/crates/metal2vulkan/src/tests/engine_extended_range/heap.rs +++ b/crates/metal2vulkan/src/tests/engine_extended_range/heap.rs @@ -188,45 +188,6 @@ fn heap_reads_reach_a_raw_member_through_the_unsigned_twin() { } } -/// A heap texture's `float` read converts its texel by the class its handle carries, as a slot's -/// does by its bound format's: on every committed profile with a sampled heap but Metal's own -/// sampler (`VkProperty::MetalSampler`, whose device value is Metal's), the module defines the -/// `float` routine, which it calls with the class read from the handle, and passes L3; there it -/// does not. -#[test] -fn a_heap_float_read_converts_by_its_handle_s_class() { - use crate::device::requirements::VkProperty; - use crate::lower::texture::float_texel; - let consts = FunctionConstantValues::defaults(); - let entry = EntryRef::Name("k"); - let inputs = LowerInputs::new(); - let Some(bc) = assemble("heap", &kernel(Use::Float)) else { - return; - }; - let mut converted = 0; - let profiles = crate::spirv::testing::committed_exact_profiles(); - for (stem, p) in profiles.expect("profiles") { - let a = match compile_bitcode(&bc, entry, &consts, &p, &inputs, &mut meter(), SPIRV_WORDS) { - Ok(a) => a, - Err(Error::Unsupported(Unsupported { - feature: Feature::ArgumentBufferTextures, - .. - })) => continue, - Err(e) => panic!("{stem}: {e}"), - }; - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); - let metal = p - .fields() - .enabled - .properties - .contains(&VkProperty::MetalSampler); - let routine = a.strategies.entries.contains_key(float_texel::CENSUS_NAME); - assert_eq!(routine, !metal, "{stem}"); - converted += usize::from(!metal); - } - assert!(converted > 0, "no committed profile converts a heap read"); -} - /// How [`sampling_kernel`] samples. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Sampling { diff --git a/crates/metal2vulkan/src/tests/engine_fragment.rs b/crates/metal2vulkan/src/tests/engine_fragment.rs index 351beb69e..6cb13062b 100644 --- a/crates/metal2vulkan/src/tests/engine_fragment.rs +++ b/crates/metal2vulkan/src/tests/engine_fragment.rs @@ -5226,63 +5226,39 @@ fn helper_invocations_skip_an_optnone_branch_on_a_driver_that_drops_a_simdgroups } } -/// A selection whose condition every invocation of a draw computes alike (a constant block's flag, -/// or a sampler's specialization constants) holds no branch only helper invocations take, so an -/// `optnone` call in its arm is neither guarded nor noted. The owned fixture `rch_uniform_branch` -/// samples a `half` texture through a runtime sampler after a branch on a constant block's flag and -/// writes a buffer; under the sampler's YCbCr variant the emulated linear filter branches on the -/// sampler's specialization constants, and its device-sample arm converts the texel through a -/// rounded add, which SPIRV-Cross writes as an `optnone` call. On `moltenvk-m3` under Metal's -/// filter of the format (`YCbCrFilterPolicy::Exact`), with and without the variant: no helper -/// census entry, no guard, no `HelperBranchDropsSimdgroupStores`, the emulated filter only under -/// the variant, and L3. +/// A selection whose condition every invocation of a draw computes alike (a constant block's flag) +/// holds no branch only helper invocations take, so an `optnone` call in its arm is neither guarded +/// nor noted. The owned fixture `rch_uniform_branch` samples a `half` texture through a runtime +/// sampler after a branch on a constant block's flag and writes a buffer. On `moltenvk-m3`: no +/// helper census entry, no guard, no `HelperBranchDropsSimdgroupStores`, no emulated filter, and +/// L3. #[test] fn a_branch_every_invocation_takes_alike_leaves_no_helper_alone() { - use crate::pipeline::sym::{SlotClass, SlotRef, Stage}; let Some(bc) = fixture("rch_uniform_branch") else { return; }; - let policy = DevicePolicy { - ycbcr_filter: crate::device::YCbCrFilterPolicy::Exact, - ..DevicePolicy::default() - }; - let p = profile("moltenvk-m3", policy).expect("profile"); + let p = profile("moltenvk-m3", DevicePolicy::default()).expect("profile"); let noted = PrecisionNote::HelperBranchDropsSimdgroupStores; - for ycbcr in [false, true] { - let what = format!("rch_uniform_branch on moltenvk-m3, YCbCr variant {ycbcr}"); - let mut inputs = LoweringInputs::new(); - if ycbcr { - inputs.ycbcr_textures.insert(SlotRef { - stage: Stage::Fragment, - class: SlotClass::Texture, - index: 0, - }); - } - let (_, m) = typed_module_with(&bc, "rch_uniform_branch", &p, &inputs) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let a = compile_with(&bc, "rch_uniform_branch", &p, &inputs) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let helper: Vec<_> = a - .strategies - .entries - .keys() - .filter(|k| k.starts_with("fragment.helper")) - .collect(); - eprintln!( - "observed: {what}: {helper:?}, note {}, linear emulation {}", - a.precision.contains(¬ed), - a.strategies.entries.contains_key("sampler.linear") - ); - assert_eq!( - a.strategies.entries.contains_key("sampler.linear"), - ycbcr, - "{what}: the emulated filter" - ); - assert!(helper.is_empty(), "{what}: {helper:?}"); - assert_eq!(helper_guards(&m), 0, "{what}"); - assert!(!a.precision.contains(¬ed), "{what}: the note"); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - } + let what = "rch_uniform_branch on moltenvk-m3"; + let inputs = LoweringInputs::new(); + let (_, m) = typed_module_with(&bc, "rch_uniform_branch", &p, &inputs) + .unwrap_or_else(|e| panic!("{what}: {e}")); + let a = compile_with(&bc, "rch_uniform_branch", &p, &inputs) + .unwrap_or_else(|e| panic!("{what}: {e}")); + let helper: Vec<_> = a + .strategies + .entries + .keys() + .filter(|k| k.starts_with("fragment.helper")) + .collect(); + assert!( + !a.strategies.entries.contains_key("sampler.linear"), + "{what}: the emulated filter" + ); + assert!(helper.is_empty(), "{what}: {helper:?}"); + assert_eq!(helper_guards(&m), 0, "{what}"); + assert!(!a.precision.contains(¬ed), "{what}: the note"); + link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); } /// Apple's compiler loses nothing after an `optnone` call only helper invocations make where they diff --git a/crates/metal2vulkan/src/tests/engine_handles.rs b/crates/metal2vulkan/src/tests/engine_handles.rs index 7cb131191..cafbe75d8 100644 --- a/crates/metal2vulkan/src/tests/engine_handles.rs +++ b/crates/metal2vulkan/src/tests/engine_handles.rs @@ -31,6 +31,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use crate::bind::{heap_classes, BindState, BindingPlan, WriteSource}; use crate::budget::Budget; use crate::device::profile::DeviceProfile; +use crate::device::DevicePolicy; use crate::device::{Device, DeviceDescription, Requirements, VkFeature}; use crate::error::{ AbiError, Error, Feature, InputErrorKind, LowerFamily, Needs, RuntimeInput, Unsupported, @@ -47,7 +48,6 @@ use crate::pipeline::sym::{ CombinedSampler, HandleClass, ImageAccess, ImageDim, ImageHandleClass, ResourceKind, ResourceSlot, SampledType, SamplerRef, SlotClass, Stage, SyntheticBinding, }; -use crate::pipeline::testing::EXACT_SAMPLING; use crate::pipeline::testing::{ compile, compile_given_storage_format, engine_dir, fixtures_dir, link_and_validate, llvm_assemble, profile, profile_with_storage_buffers, status_reach, status_reach_on, @@ -57,7 +57,7 @@ use crate::pipeline::{ ComputePipelineDescriptor, FunctionDescriptor, RenderPipelineDescriptor, StageSource, }; use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Resources}; -use crate::spirv::testing::committed_exact_profiles; +use crate::spirv::testing::committed_profiles; use crate::vk; const DATALAYOUT: &str = "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"; @@ -110,7 +110,7 @@ fn assemble(name: &str, body: &str) -> Option> { } fn m3() -> DeviceProfile { - profile("moltenvk-m3", EXACT_SAMPLING).expect("profile") + profile("moltenvk-m3", DevicePolicy::default()).expect("profile") } fn ok(bc: &[u8], entry: &str, p: &DeviceProfile) -> std::sync::Arc { @@ -213,7 +213,7 @@ const OP_IMAGE_QUERY_LOD: u16 = 105; #[test] fn handle_entries_compile_on_every_profile() { let Some(bc) = fixture() else { return }; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { for entry in OK { let a = match compile(&bc, entry, &p) { Ok(a) => a, @@ -341,7 +341,7 @@ fn tangled_samples_hoist_their_gradients_out_of_the_switch() { #[test] fn a_selected_lod_query_queries_every_candidate_before_its_switch() { let Some(bc) = fixture() else { return }; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { let a = ok(&bc, "fragment_select_lod", &p); assert_eq!(uses(&a, "sampler.query_lod.switch"), 1, "{stem}"); assert_eq!(count(&a, OP_IMAGE_QUERY_LOD), 2, "{stem}"); @@ -390,14 +390,14 @@ declare {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32(ptr addrspace(1), ptr ) } -/// On a profile that samples through Metal's own sampler (MoltenVK), the hoisted derivatives of a -/// texture chosen per fragment are Metal's own sample for a 2D color sample without a bias, an -/// offset or a `min_lod_clamp`, through a runtime or a constexpr sampler without a bias of its own, -/// record no `PrecisionNote::GradFromBias`, and require the property; a bias, a nonzero offset or a -/// clamp keeps the note, as every profile without that sampler does. Every case still hoists its -/// derivatives out of the one switch-at-use. +/// The hoisted derivatives of a texture chosen per fragment are the device's own sample for a 2D +/// color sample without a bias, an offset or a `min_lod_clamp`, through a runtime or a constexpr +/// sampler without a bias of its own: they record no `PrecisionNote::GradFromBias` and require the +/// device's sampler (`VkProperty::MetalSampler` on a profile that samples through Metal's own, +/// MoltenVK, `VkProperty::DeviceSampling` on any other). A bias, a nonzero offset or a clamp keeps +/// the note. Every case still hoists its derivatives out of the one switch-at-use. #[test] -fn an_unbiased_chosen_sample_is_metals_own_on_metals_sampler() { +fn an_unbiased_chosen_sample_is_the_device_s_own() { let zero = "0.000000e+00"; let cases = [ ("%s", zero, "zeroinitializer", zero, true), @@ -411,7 +411,7 @@ fn an_unbiased_chosen_sample_is_metals_own_on_metals_sampler() { let Some(bc) = chosen_sample(sampler, bias, offset, clamp) else { return; }; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { let what = format!("{stem}: {sampler} bias {bias} offset {offset} clamp {clamp}"); let a = match compile(&bc, "chosen_sample", &p) { Ok(a) => a, @@ -426,19 +426,22 @@ fn an_unbiased_chosen_sample_is_metals_own_on_metals_sampler() { assert_eq!(uses(&a, "sampler.sample_hoisted_grad.switch"), 1, "{what}"); assert_eq!((count(&a, OP_DPDX), count(&a, OP_DPDY)), (1, 1), "{what}"); assert_no_tangled_in_a_switch(&a); + use crate::device::requirements::VkProperty; let metal = metal_sampler(&p); saw_metal_sampler |= metal; assert_eq!( a.precision.contains(&PrecisionNote::GradFromBias), - !(metal && exact), + !exact, "{what}" ); - if metal && exact { + if exact { + let sampler = match metal { + true => VkProperty::MetalSampler, + false => VkProperty::DeviceSampling, + }; assert!( - a.requirements - .properties - .contains(&crate::device::requirements::VkProperty::MetalSampler), - "{what}: the module requires Metal's sampler" + a.requirements.properties.contains(&sampler), + "{what}: the module requires the device's sampler" ); } } @@ -492,7 +495,7 @@ fn lod_query_candidates_are_bounded() { let (Some(at), Some(past)) = (lod_query_array(16), lod_query_array(17)) else { return; }; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { let a = ok(&at, "lod_query_array", &p); assert_eq!(uses(&a, "sampler.query_lod.switch"), 1, "{stem}"); assert_eq!(count(&a, OP_IMAGE_QUERY_LOD), 16, "{stem}"); @@ -622,7 +625,7 @@ fn a_switch_is_named_by_the_check_its_arms_take() { .map(|(name, u)| (name.clone(), u.uses)) .collect() }; - let floor = profile("vk12-floor", EXACT_SAMPLING).expect("profile"); + let floor = profile("vk12-floor", DevicePolicy::default()).expect("profile"); for (op, on_floor, on_m3) in [ ( TexelRead, @@ -689,7 +692,7 @@ fn without_robust_images(stem: &str) -> DeviceProfile { let mut desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); desc.features.remove(&VkFeature::RobustImageAccess); desc.features.remove(&VkFeature::RobustImageAccess2); - Device::new(desc, EXACT_SAMPLING) + Device::new(desc, DevicePolicy::default()) .expect("device") .profile() .clone() @@ -1036,7 +1039,7 @@ declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1), ptr add return; }; let mut compiled = 0; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { match compile(&bc, "lookup_psb", &p) { Ok(a) => { assert!(has_sampled_heap(&p), "{stem}"); @@ -1151,7 +1154,7 @@ fn nested_argument_buffer_handles_are_heap_lookups() { return; }; let mut compiled = Vec::new(); - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { match compile(&bc, "nested_handles", &p) { Ok(a) => { assert!(has_sampled_heap(&p), "{stem}"); @@ -1210,7 +1213,7 @@ fn the_reflection_fixture_samples_its_nested_argument_buffer_s_texture() { }; let entry = "reflection_argument_buffers"; let mut compiled = Vec::new(); - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { match compile(&bc, entry, &p) { Ok(a) => { link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem} {entry}: L3: {e}")); @@ -1336,7 +1339,7 @@ fn one_heap(a: &FunctionArtifact) -> Vec<(u32, u32)> { fn an_argument_buffer_texture_is_a_heap_lookup() { let Some(bc) = fixture() else { return }; let mut compiled = 0; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { match compile(&bc, "argument_buffer_read", &p) { Ok(a) => { assert!(has_sampled_heap(&p), "{stem}"); @@ -1487,7 +1490,7 @@ fn m3_device() -> Device { .join("../metal2vulkan-validation/profiles/moltenvk-m3.json"); let text = std::fs::read_to_string(path).expect("profile"); let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - Device::new(desc, EXACT_SAMPLING).expect("device") + Device::new(desc, DevicePolicy::default()).expect("device") } /// A render pipeline whose vertex and fragment functions both read a texture from an argument @@ -1633,7 +1636,7 @@ declare i32 @air.get_width_texture_2d(ptr addrspace(1), i32) return; }; let mut compiled = 0; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { let d = &p.fields().descriptors; let heap = d.runtime_descriptor_array && d.partially_bound @@ -1756,7 +1759,7 @@ fn a_heap_texel_write_stores_half_bits_through_the_unsigned_twin() { return; }; let mut twins = 0; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { let what = format!("{stem} float {float}"); let a = match compile(&bc, "heap_texel_write", &p) { Ok(a) => a, @@ -1873,7 +1876,7 @@ fn a_selected_member_resource_id_is_a_heap_lookup() { return; }; let mut compiled = 0; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { match compile(&bc, "heap_word", &p) { Ok(a) => { assert!(has_sampled_heap(&p), "{stem}"); @@ -1961,7 +1964,7 @@ fn dynamic_argument_buffer_elements_are_heap_lookups() { ]; for (entry, has_heap, strategies) in cases { let mut compiled = 0; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { match compile(&bc, entry, &p) { Ok(a) => { assert!(has_heap(&p), "{stem} {entry}"); @@ -2010,7 +2013,7 @@ fn image_types(a: &FunctionArtifact) -> Vec<(u32, u32, u32)> { fn an_argument_buffer_depth_texture_reads_through_the_float_class() { let Some(bc) = fixture() else { return }; let mut compiled = 0; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { let heap = has_sampled_heap(&p) && has_storage_heap(&p); match compile(&bc, "argument_buffer_depth_read", &p) { Ok(a) => { @@ -2113,7 +2116,7 @@ declare i32 @air.get_array_size_texture_cube_array(ptr addrspace(1)) return; }; let mut compiled = 0; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { let a = match compile(&bc, "heap_cube_queries", &p) { Ok(a) => a, Err(e) => { @@ -2226,7 +2229,7 @@ fn a_heap_texture_samples_through_a_runtime_sampler() { let Some(bc) = fixture() else { return }; let entry = "argument_buffer_runtime_sampler"; let mut compiled = 0; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { let a = match compile(&bc, entry, &p) { Ok(a) => a, Err(e) => { @@ -2256,13 +2259,10 @@ fn a_heap_texture_samples_through_a_runtime_sampler() { )), "{stem}" ); - // The device's sampled image, and (Metal's linear filter emulated; a nearest sample's texel - // fetched) the emulation's and the fetch's of the element loaded again. On every profile, - // the raw-held emulation's four filtered taps and its nearest one, fetched from the - // unsigned twin. - let emulated = usize::from(!metal_sampler(&p)); - assert_eq!(count(&a, OP_SAMPLED_IMAGE), 1 + 2 * emulated, "{stem}"); - assert_eq!(count(&a, OP_IMAGE_FETCH), 5 * emulated + 5, "{stem}"); + // The device's sampled image, and the raw-held emulation's four filtered taps and its + // nearest one, fetched from the unsigned twin. + assert_eq!(count(&a, OP_SAMPLED_IMAGE), 1, "{stem}"); + assert_eq!(count(&a, OP_IMAGE_FETCH), 5, "{stem}"); compiled += 1; } assert!(compiled > 0, "no committed profile has the heaps"); @@ -2312,7 +2312,7 @@ declare { <4 x float>, i8 } @air.sample_texture_cube_grad.v4f32(ptr addrspace(1) return; }; let mut compiled = 0; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { let a = match compile(&bc, "argument_sampler_cube_grad", &p) { Ok(a) => a, Err(e) => { @@ -2462,7 +2462,7 @@ fn an_imageblock_slice_writes_an_argument_buffer_texture() { let Some(bc) = heap_slice_module(name, "f16", ty, lanes, "half") else { return; }; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { let a = match compile(&bc, "heap_slice", &p) { Ok(a) => a, Err(e) => { @@ -2618,25 +2618,14 @@ define void @k(ptr addrspace(2) %m, ptr addrspace(1) %out{param}, i32 %gid) {{ ) } -/// A heap depth comparison the shader can make (a nearest `sample_compare` through a constexpr -/// sampler, any `sample_compare` through a runtime or argument buffer's sampler, and any -/// `gather_compare`) keeps the device's comparison and adds the shader's of the element's depths, -/// which it fetches (a gather's four, a sample's one, a runtime or argument buffer's sampler's from -/// the level its word reads) from the element through a second heap sampler of the same sampler -/// without comparison (or the sampler array of that use): one `Dref` access and no plain one. The -/// handle carries its entry's depth class (the search's flagged form, whose masks the census counts -/// under `DEPTH_CLASS_CENSUS`), and the module records the device's comparison, for a format -/// without a class, and no device read of the texels (`DeviceTexelDenormals`) beside it. A runtime -/// sampler's word states its compare function, and a sample's its filter. On a profile with -/// `VkProperty::MetalSampler` the device's comparison is Metal's own: one `Dref` access, one -/// sampler, no depth class, nothing recorded. Each validates; a profile without the sampled heap -/// refuses each. (The interpreter models no sample; the runtime lane's `depth_compares` runs -/// these comparisons through argument buffers on each device.) +/// A heap depth comparison (a `sample_compare` or a `gather_compare` through a constexpr sampler, +/// a runtime sampler or the sampler its argument buffer holds) is the device's: one `Dref` access, +/// no plain one and no fetch, through one comparison sampler and the depth-comparison class of its +/// shape. Each validates; a profile without the sampled heap refuses each. (The interpreter models +/// no sample; the runtime lane's `depth_compares` runs these comparisons through argument buffers +/// on each device.) #[test] -fn heap_depth_comparisons_compare_by_the_class() { - use crate::lower::sampler::compared::DEPTH_CLASS_CENSUS; - use crate::memory::handles::{HANDLE_DEPTH_CODES, HANDLE_DEPTH_VALUES}; - use crate::pipeline::sym::SpecKey; +fn heap_depth_comparisons_are_the_device_s() { let cases = [ (CompareThrough::Constexpr(NEAREST_LESS), false), (CompareThrough::Constexpr(NEAREST_LESS), true), @@ -2650,7 +2639,7 @@ fn heap_depth_comparisons_compare_by_the_class() { return; }; let mut compiled = 0; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { let what = format!("{name} on {stem}"); let a = match compile(&bc, "k", &p) { Ok(a) => a, @@ -2662,7 +2651,6 @@ fn heap_depth_comparisons_compare_by_the_class() { } }; link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let shader = !metal_sampler(&p); let (dref, plain) = match gather { true => (OP_IMAGE_DREF_GATHER, OP_IMAGE_GATHER), false => ( @@ -2672,79 +2660,18 @@ fn heap_depth_comparisons_compare_by_the_class() { }; assert_eq!(count(&a, dref), 1, "{what}"); assert_eq!(count(&a, plain), 0, "{what}"); - let taps = if gather { 4 } else { 1 }; - assert_eq!( - count(&a, OP_IMAGE_FETCH), - taps * usize::from(shader), - "{what}" - ); - assert_eq!( - count(&a, OP_SAMPLED_IMAGE), - 1 + usize::from(shader), - "{what}" - ); - // The uses of the sampler: with comparison, and (the shader's) without. - let mut compares: Vec = match through { + assert_eq!(count(&a, OP_IMAGE_FETCH), 0, "{what}"); + assert_eq!(count(&a, OP_SAMPLED_IMAGE), 1, "{what}"); + let compares: Vec = match through { CompareThrough::Argument => sampler_arrays(&a).iter().map(|u| u.0).collect(), _ => heap_samplers(&a).iter().map(|u| u.compare).collect(), }; - compares.sort(); - let want = match shader { - true => vec![false, true], - false => vec![true], - }; - assert_eq!(compares, want, "{what}"); - // The element's arrays: the depth-comparison class, and (the shader's read) the float - // class of its shape, where the binder holds a twinned `Depth32Float` member through - // its colour image. - let mut classes: Vec = heap_image_classes(&a) + assert_eq!(compares, [true], "{what}"); + let classes: Vec = heap_image_classes(&a) .iter() .map(|c| c.depth_compare) .collect(); - classes.sort(); - assert_eq!(classes, want, "{what}"); - // The handle's depth class, and the masks of a handle that carries it. - assert_eq!( - a.strategies.entries.contains_key(DEPTH_CLASS_CENSUS), - shader, - "{what}" - ); - let constants = mask_constants(&a); - for bit in [HANDLE_DEPTH_CODES, HANDLE_DEPTH_VALUES] { - assert_eq!(constants.contains(&bit), shader, "{what}: {bit:#x}"); - } - assert_eq!( - constants.contains(&!(HANDLE_DEPTH_CODES | HANDLE_DEPTH_VALUES)), - shader, - "{what}" - ); - assert_eq!( - a.precision.contains(&PrecisionNote::DeviceDepthComparison), - shader, - "{what}" - ); - assert!( - !a.precision.contains(&PrecisionNote::DeviceTexelDenormals), - "{what}" - ); - if let (CompareThrough::Runtime, true) = (through, shader) { - let fields = a - .interface - .read_keys() - .into_iter() - .find_map(|k| match k { - SpecKey::SamplerState { fields, .. } => Some(fields), - _ => None, - }) - .unwrap_or_else(|| panic!("{what}: no sampler word")); - assert_eq!( - fields & SamplerWord::COMPARE, - SamplerWord::COMPARE, - "{what}" - ); - let filters = SamplerWord::MIN_LINEAR | SamplerWord::MIP_FILTER; - assert_eq!(fields & filters == filters, !gather, "{what}"); - } + assert_eq!(classes, [true], "{what}"); compiled += 1; } assert!( @@ -2763,7 +2690,7 @@ fn an_argument_buffer_depth_texture_compares_through_the_depth_comparison_class( let Some(bc) = fixture() else { return }; let entry = "argument_buffer_sample_compare"; let mut compiled = 0; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { let a = match compile(&bc, entry, &p) { Ok(a) => a, Err(e) => { @@ -2818,7 +2745,7 @@ const OP_SAMPLED_IMAGE: u16 = 86; const OP_IMAGE_FETCH: u16 = 95; /// 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. const LINEAR_EDGE: u64 = 0x007b_ff00_0008_0a49; /// A kernel sampling the `texture2d` (a `texture3d` where `three`) its argument @@ -2898,17 +2825,15 @@ define void @k(ptr addrspace(2) %m, ptr addrspace(1) %out{param}, i32 %gid) {{ } /// A heap texture's linear sample, through a constexpr sampler of linear filters (2D and 3D), a -/// runtime sampler slot, or the sampler its argument buffer holds, keeps the device's sample and -/// adds Metal's filter emulated by fetches (four taps in 2D, eight in 3D) from the element, in a -/// branch on the class the handle carries (the search's flagged form, whose masks and table the -/// census counts under `HEAP_CLASS_CENSUS`): the module holds the table of heap classes; the census -/// names the sample by its source. A heap texture's class is no specialization, so the filter note -/// holds always, and the module states no `TexelFormat` specialization. On a profile with -/// `VkProperty::MetalSampler` the device's filter is Metal's own: no fetch, no class. Each -/// validates; a profile without the sampled heap refuses each. (The interpreter models no -/// sample; the runtime lane `argument_linear_samples` reads the values on each device.) +/// runtime sampler slot, or the sampler its argument buffer holds, is the device's sample, with no +/// filter note; the census names the sample by its source, and the module states no `TexelFormat` +/// specialization. A 2D sample through a constexpr or runtime sampler also emulates a raw-held +/// texture's, in a branch on the class the handle carries (the search's flagged form, whose masks +/// and table the census counts under `HEAP_CLASS_CENSUS`). Each validates; a profile without the +/// sampled heap refuses each. (The interpreter models no sample; the runtime lane +/// `argument_linear_samples` reads the values on each device.) #[test] -fn heap_linear_samples_are_emulated_by_the_handle_s_class() { +fn heap_linear_samples_are_the_device_s() { use crate::lower::texture::HEAP_CLASS_CENSUS; use crate::memory::handles::HANDLE_TEXEL_CLASS; use crate::pipeline::sym::SpecKey; @@ -2925,7 +2850,7 @@ fn heap_linear_samples_are_emulated_by_the_handle_s_class() { return; }; let mut compiled = 0; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { let what = format!("{name} on {stem}"); let a = match compile(&bc, "k", &p) { Ok(a) => a, @@ -2937,33 +2862,21 @@ fn heap_linear_samples_are_emulated_by_the_handle_s_class() { } }; link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let shader = !metal_sampler(&p); assert_eq!(count(&a, OP_IMAGE_SAMPLE_EXPLICIT_LOD), 1, "{what}"); // An argument buffer's sampler also fetches the texel where its word states an exact - // fetch; a runtime or argument buffer's sampler's nearest sample fetches its texel - // where the word states one, in an arm of its own. + // fetch. let argument = matches!(through, CompareThrough::Argument); - let word = usize::from(!matches!(through, CompareThrough::Constexpr(_))); - let taps = if three { 8 } else { 4 }; - // A 2D sample through a constexpr or runtime sampler also emulates a raw-held - // texture's, on every profile: four filtered taps and a nearest one from the twin. + // The raw-held emulation: four filtered taps and a nearest one from the twin. let raw = !three && !argument; assert_eq!( count(&a, OP_IMAGE_FETCH), - (taps + word) * usize::from(shader) + usize::from(argument) + 5 * usize::from(raw), + usize::from(argument) + 5 * usize::from(raw), "{what}" ); - // The device's sampled image, and the emulation's (and the nearest fetch's) of the - // element loaded again. - assert_eq!( - count(&a, OP_SAMPLED_IMAGE), - 1 + (1 + word) * usize::from(shader), - "{what}" - ); - // The raw-held emulation reads the handle's class on every profile. + assert_eq!(count(&a, OP_SAMPLED_IMAGE), 1, "{what}"); assert_eq!( a.strategies.entries.contains_key(HEAP_CLASS_CENSUS), - shader || raw, + raw, "{what}" ); let census = match argument { @@ -2974,19 +2887,12 @@ fn heap_linear_samples_are_emulated_by_the_handle_s_class() { assert_eq!(uses(&a, "sampler.linear"), 0, "{what}"); assert_eq!( mask_constants(&a).contains(&!HANDLE_TEXEL_CLASS), - shader || raw, - "{what}" - ); - assert_eq!( - a.precision.contains(&PrecisionNote::FloatSampleFilter), - shader, + raw, "{what}" ); assert!( - a.specialized - .iter() - .all(|n| n.note != PrecisionNote::FloatSampleFilter), - "{what}: a heap texture's filter note holds always" + !a.precision.contains(&PrecisionNote::FloatSampleFilter), + "{what}" ); assert!( !a.interface @@ -3056,12 +2962,12 @@ fn heap_plain_half_kernel(through: CompareThrough, gather: bool) -> String { } /// A heap color texture's sample or gather with a `half` result converts the device's texel (or the -/// fetched one) by the class its handle carries, as a slot's converts by its bound format's: the -/// module calls the `half` routine once, with the class read from the handle's table, on every -/// profile, Metal's own sampler included (whose `float` result the class's rule rounds as Metal -/// does), where the same access with a `float` result calls the `float` routine once on a profile -/// without Metal's own sampler and no routine on one with it (the rounding the class replaced was -/// inline). The note stays: the class may be one whose conversion is not measured. +/// fetched one) by the class its handle carries, as a slot's converts by its bound format's, on a +/// profile that samples through Metal's own sampler (`VkProperty::MetalSampler`, whose `float` +/// result the class's rule rounds as Metal does): the module calls the `half` routine once, with +/// the class read from the handle's table, where the same access with a `float` result calls no +/// routine. On any other profile the `half` texel is the device's conversion: no routine. The note +/// stays: the class may be one whose conversion is not measured. #[test] fn heap_half_texels_convert_by_the_handle_s_class() { let cases = [ @@ -3077,7 +2983,7 @@ fn heap_half_texels_convert_by_the_handle_s_class() { }; let float = assemble("heap_float", &heap_plain_kernel(through, gather)).expect("float"); let mut compiled = 0; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { let what = format!("{name} on {stem}"); let a = match compile(&bc, "k", &p) { Ok(a) => a, @@ -3088,18 +2994,14 @@ fn heap_half_texels_convert_by_the_handle_s_class() { }; link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); let f = compile(&float, "k", &p).unwrap_or_else(|e| panic!("{what}: float: {e}")); - let metal = p - .fields() - .enabled - .properties - .contains(&crate::device::requirements::VkProperty::MetalSampler); // A sample's raw-held emulation through a constexpr or runtime sampler decodes its // nearest tap both ways for a `half` result (a bfloat form's toward zero, another's // rounded): one call more than the `float` result's. let twin = usize::from(!gather && !matches!(through, CompareThrough::Argument)); + let routine = usize::from(metal_sampler(&p)); assert_eq!( - count(&a, OP_FUNCTION_CALL) + usize::from(!metal), - count(&f, OP_FUNCTION_CALL) + 1 + twin, + count(&a, OP_FUNCTION_CALL), + count(&f, OP_FUNCTION_CALL) + routine + twin, "{what}: the half routine is called once, the float one where it converts" ); let notes = &a.precision; @@ -3113,17 +3015,13 @@ fn heap_half_texels_convert_by_the_handle_s_class() { } } -/// A heap texture's plain gather, and its sample through a constexpr sampler that reads one texel -/// or through a runtime or argument buffer's sampler, fetch their texels from the element (four -/// taps, or one) where the class the handle carries is the 32-bit float one and, for a sample -/// through a word, the word states one texel; the device's access is made first, in uniform control -/// flow. A sample through a word also keeps the linear emulation's four taps, and an argument -/// buffer's sampler's fetch. A gather's and a constexpr sampler's fetches read every texel, so they -/// record no `DeviceTexelDenormals`; a sample through a word records it always, a heap texture's -/// class being no specialization. On a profile with `VkProperty::MetalSampler` Metal's own sampler -/// reads them, with no fetch. +/// A heap texture's plain gather, and its nearest sample through a constexpr sampler, a runtime +/// sampler or an argument buffer's sampler, are the device's access, made once; an argument +/// buffer's sampler's sample keeps its fetch. Through a constexpr or runtime sampler the raw-held +/// emulation fetches from the twin in a branch on the class the handle carries. The module states +/// no `TexelFormat` specialization. #[test] -fn heap_gathers_and_nearest_samples_fetch_by_the_handle_s_class() { +fn heap_gathers_and_nearest_samples_are_the_device_s() { use crate::lower::texture::HEAP_CLASS_CENSUS; use crate::memory::handles::HANDLE_TEXEL_CLASS; use crate::pipeline::sym::SpecKey; @@ -3141,7 +3039,7 @@ fn heap_gathers_and_nearest_samples_fetch_by_the_handle_s_class() { return; }; let mut compiled = 0; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { let what = format!("{name} on {stem}"); let a = match compile(&bc, "k", &p) { Ok(a) => a, @@ -3153,7 +3051,6 @@ fn heap_gathers_and_nearest_samples_fetch_by_the_handle_s_class() { } }; link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let shader = !metal_sampler(&p); let word = !matches!(through, CompareThrough::Constexpr(_)); let argument = matches!(through, CompareThrough::Argument); let device = if gather { @@ -3162,15 +3059,11 @@ fn heap_gathers_and_nearest_samples_fetch_by_the_handle_s_class() { OP_IMAGE_SAMPLE_EXPLICIT_LOD }; assert_eq!(count(&a, device), 1, "{what}"); - // The fetched taps, a word's linear emulation's, and the fetch of an argument buffer's - // sampler's sample. - let (taps, linear, exact) = match gather { - true => (4, 0, 0), - false => (1, 4 * usize::from(word), usize::from(argument)), - }; + // The fetch of an argument buffer's sampler's sample. + let exact = usize::from(argument && !gather); // Through a constexpr or runtime sampler, the raw-held emulation's fetches from the - // twin on every profile: a gather's four, a nearest sample's one, a runtime sampler's - // four filtered and one nearest. + // twin: a gather's four, a nearest sample's one, a runtime sampler's four filtered and + // one nearest. let raw = !argument; let twin = match (raw, gather, word) { (false, _, _) => 0, @@ -3178,40 +3071,18 @@ fn heap_gathers_and_nearest_samples_fetch_by_the_handle_s_class() { (true, false, false) => 1, (true, false, true) => 5, }; - assert_eq!( - count(&a, OP_IMAGE_FETCH), - (taps + linear) * usize::from(shader) + exact + twin, - "{what}" - ); - // The device's sampled image, and the fetches' and the emulation's of the element - // loaded again. - assert_eq!( - count(&a, OP_SAMPLED_IMAGE), - 1 + (1 + usize::from(linear > 0)) * usize::from(shader), - "{what}" - ); - // The raw-held emulation reads the handle's class on every profile. + assert_eq!(count(&a, OP_IMAGE_FETCH), exact + twin, "{what}"); + assert_eq!(count(&a, OP_SAMPLED_IMAGE), 1, "{what}"); assert_eq!( a.strategies.entries.contains_key(HEAP_CLASS_CENSUS), - shader || raw, + raw, "{what}" ); assert_eq!( mask_constants(&a).contains(&!HANDLE_TEXEL_CLASS), - shader || raw, + raw, "{what}" ); - assert_eq!( - a.precision.contains(&PrecisionNote::DeviceTexelDenormals), - shader && word && !gather, - "{what}" - ); - assert!( - a.specialized - .iter() - .all(|n| n.note != PrecisionNote::DeviceTexelDenormals), - "{what}: a heap texture's note holds always" - ); assert!( !a.interface .read_keys() @@ -3313,7 +3184,7 @@ fn argument_buffer_textures_sample_through_heap_samplers() { ]; for (entry, has_heap, strategies, classes, samplers) in cases { let mut compiled = 0; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { let a = match compile(&bc, entry, &p) { Ok(a) => a, Err(e) => { @@ -3361,18 +3232,9 @@ fn argument_buffer_textures_sample_through_heap_samplers() { .filter(|(n, _)| n.starts_with("sampler.heap.")) .map(|(_, n)| n) .sum(); - // Each linear sample of a 2D float texture Metal's filter is emulated for loads its - // element again in the emulation's arm: the kernel's one, and the fragment's three (the - // cube's is the device's). - let emulated = match (entry, metal_sampler(&p)) { - (_, true) => 0, - ("argument_buffer_sample", false) => 1, - ("argument_buffer_fragment_sample", false) => 3, - _ => 0, - }; assert_eq!( count(&a, OP_SAMPLED_IMAGE) as u32, - samples + emulated, + samples, "{stem} {entry}" ); compiled += 1; @@ -3478,7 +3340,7 @@ fn a_command_set_to_an_argument_buffer_pipeline_state_is_its_family_refusal() { ) else { return; }; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { match compile(&bc, "set_pipeline", &p) { Ok(a) => { assert_eq!( @@ -3700,7 +3562,7 @@ type Case = (String, String, Option<(Refusal, u32)>); /// Compile `entry` on every committed profile: `None` must link and validate, `Some((refusal, /// at))` must be that refusal at instruction `at` of block 0. fn expect_everywhere(bc: &[u8], entry: &str, want: Option<(Refusal, u32)>) { - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { match want { None => { ok(bc, entry, &p); @@ -3991,7 +3853,7 @@ fn a_plain_buffer_layout_with_argument_buffer_members_is_malformed() { let Some(bc) = assemble(entry, &pointer_member_kernel_as(entry, "air.buffer", body)) else { return; }; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { match compile(&bc, entry, &p).expect_err(entry) { Error::InvalidInput(i) => { assert_eq!(i.kind, InputErrorKind::Abi(AbiError::UnknownKey), "{stem}") @@ -4070,7 +3932,7 @@ sample: let Some(bc) = assemble("agg_sample", &body) else { return; }; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { let a = compile(&bc, "agg_sample", &p).unwrap_or_else(|e| panic!("{stem}: {e}")); link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); // Two insertions and the nested extraction are no value; the three handle extractions @@ -4129,7 +3991,7 @@ declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1), ptr add return; }; let mut compiled = 0; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { match compile(&bc, "agg_heap", &p) { Ok(a) => { assert!(has_sampled_heap(&p), "{stem}"); @@ -4227,7 +4089,7 @@ y: Image::new(tex(0), [5, 3, 1], 1, 1, 1), Image::new(tex(1), [9, 3, 1], 1, 1, 1), ]; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { let a = ok(&bc, "agg_two", &p); assert_eq!(uses(&a, "arith.aggregate.member"), 1, "{stem}"); assert_eq!(uses(&a, "texture.query.switch"), 1, "{stem}"); @@ -4305,7 +4167,7 @@ fn check_array_width(bc: &[u8], entry: &str, widths: &[u32], runs: &[(u32, u32)] Image::new(slot, [*w, 2, 1], 1, 1, 1) }) .collect(); - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { ok(bc, entry, &p); let (plan, m) = typed_module(bc, entry, &p).expect("module"); for &(k, width) in runs { @@ -4427,20 +4289,15 @@ fn is_sampler_table(k: &ResourceKind) -> bool { /// own domain: a lookup in the stage's sampler table (set 0) whose element indexes the set-1 /// sampler array of the sample's use (comparison, integer texel), non-uniformly, and /// `OpSampledImage` of the heap image and that sampler. Each entry declares one sampler array of -/// its use; a sample in the sampler's coordinates carries the argument buffer's pixel-coordinate -/// near-equivalent (`ArgumentPixelSamplerScaling`, but a sample without comparison on a profile -/// with `VkProperty::MetalSampler`, which reads Metal's texels; never `PixelSamplerScaling`), a -/// comparison or an integer texel samples through its own use, and a fragment samples at its -/// implicit level. A sample without comparison also fetches the texel the rule names, which the -/// sampler's word selects; a sample, a comparison's included, tests the word for a nearest pixel -/// sampler (`SamplerWord::PIXEL_NEAREST`; of an integer texture, for pixel coordinates), which -/// selects the centre of the texel Metal floors its coordinate to. A comparison on a profile -/// without `VkProperty::MetalSampler` also reads the element through the sampler array of its use -/// without comparison, fetching the texel from the level the word reads, which the shader compares -/// where the handle states the texture's depth class -/// (`heap_depth_comparisons_compare_by_the_class`). A linear sample of a float texture there also -/// loads the element and the sampler again, in the arm of Metal's filter emulated by fetches. A -/// profile without the heap's features refuses each naming them. +/// its use; a comparison in the sampler's coordinates carries the argument buffer's +/// pixel-coordinate near-equivalent (`ArgumentPixelSamplerScaling`; a sample without comparison +/// reads the device sampler's texels; never `PixelSamplerScaling`), a comparison or an integer +/// texel samples through its own use, and a fragment samples at its implicit level. A sample +/// without comparison also fetches the texel the rule names, which the sampler's word selects; a +/// sample, a comparison's included, tests the word for a nearest pixel sampler +/// (`SamplerWord::PIXEL_NEAREST`; of an integer texture, for pixel coordinates), which selects the +/// centre of the texel Metal floors its coordinate to. A profile without the heap's features +/// refuses each naming them. #[test] fn argument_buffer_samplers_are_heap_lookups() { let Some(bc) = argument_samplers_fixture() else { @@ -4481,7 +4338,7 @@ fn argument_buffer_samplers_are_heap_lookups() { ]; for (entry, strategy, use_, op) in cases { let mut compiled = 0; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { let a = match compile(&bc, entry, &p) { Ok(a) => a, Err(e) => { @@ -4504,40 +4361,22 @@ fn argument_buffer_samplers_are_heap_lookups() { ); assert!(texture_slots(&a).is_empty(), "{stem} {entry}"); assert!(heap_samplers(&a).is_empty(), "{stem} {entry}"); - // A comparison the shader makes reads the element without comparison too. let compare = use_.0; - let shader = compare && !metal_sampler(&p); - let mut arrays = vec![use_]; - if shader { - arrays.insert(0, (false, use_.1)); - } - assert_eq!(sampler_arrays(&a), arrays, "{stem} {entry}"); + assert_eq!(sampler_arrays(&a), [use_], "{stem} {entry}"); let tables = bindings_of(&t, is_sampler_table); assert_eq!(tables.len(), 1, "{stem} {entry}"); assert_eq!(tables[0].0, 0, "{stem} {entry}"); - // The image's arrays (its class's, and the float class of its shape a comparison the - // shader makes reads it through) and the sampler's, all in set 1. + // The image's array (its class's) and the sampler's, both in set 1. let heap = bindings_of(&t, is_heap); - assert_eq!( - heap.len(), - 1 + usize::from(shader) + arrays.len(), - "{stem} {entry}" - ); + assert_eq!(heap.len(), 2, "{stem} {entry}"); assert!(heap.iter().all(|(set, _)| *set == 1), "{stem} {entry}"); for d in &a.interface.descriptors { if let ResourceKind::Heap(c) = d.slot.kind { assert!(heap_classes(&p).contains(&c), "{stem} {entry}: {c:?}"); } } - // A linear sample of a float texture Metal's filter is emulated for reads its element - // and sampler again in the emulation's arm, and fetches four taps; its nearest sample's - // texel is fetched in an arm of its own. - let emulated = !compare && !use_.1 && !metal_sampler(&p); - let reads = 1 + usize::from(shader) + 2 * usize::from(emulated); - assert_eq!(count(&a, OP_SAMPLED_IMAGE), reads, "{stem} {entry}"); + assert_eq!(count(&a, OP_SAMPLED_IMAGE), 1, "{stem} {entry}"); assert_eq!(count(&a, op), 1, "{stem} {entry}"); - // The shader's comparison fetches its texel from the level the word reads: no sample - // without comparison. assert_eq!( count(&a, OP_IMAGE_SAMPLE_EXPLICIT_LOD), usize::from(op == OP_IMAGE_SAMPLE_EXPLICIT_LOD), @@ -4545,31 +4384,18 @@ fn argument_buffer_samplers_are_heap_lookups() { ); assert_eq!(count(&a, OP_SWITCH), 0, "{stem} {entry}"); // Non-uniform: the image's element and the sampler's (chain and load each), their - // sampled image, the image the pixel-coordinate scaling queries, (without - // comparison) the image the flagged fetch reads, (a comparison the shader makes) - // the element and the sampler without comparison, their sampled image, the image - // whose levels clamp the word's level, and the image the shader's comparison fetches - // its texel from, addressed by the word, and (Metal's filter emulated) the element and - // the sampler loaded again, their sampled image, and the image the taps are fetched - // from; and (a nearest sample's texel fetched) those again, and in a kernel the image - // whose levels clamp the word's level. - let leveled = usize::from(op == OP_IMAGE_SAMPLE_EXPLICIT_LOD); + // sampled image, the image the pixel-coordinate scaling queries, and (without + // comparison) the image the flagged fetch reads. assert_eq!( count(&a, OP_IMAGE_FETCH), - usize::from(!compare) + usize::from(shader) + 5 * usize::from(emulated), - "{stem} {entry}" - ); - assert_eq!( - non_uniform(&a), - 6 + usize::from(!compare) - + 7 * usize::from(shader) - + (12 + leveled) * usize::from(emulated), + usize::from(!compare), "{stem} {entry}" ); + assert_eq!(non_uniform(&a), 6 + usize::from(!compare), "{stem} {entry}"); assert_eq!( a.precision .contains(&PrecisionNote::ArgumentPixelSamplerScaling), - compare || !metal_sampler(&p), + compare, "{stem} {entry}" ); assert!( @@ -4604,7 +4430,7 @@ fn only_non_fragment_stages_test_argument_samplers_for_a_cubic_filter() { return; }; let (mut compiled, mut bound) = (0, 0); - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { let (Ok(kernel), Ok(fragment)) = ( compile(&bc, "argument_sampler_sample", &p), compile(&bc, "argument_sampler_fragment", &p), @@ -4647,14 +4473,15 @@ fn the_cubic_tests_binding_gives_way_to_the_storage_buffer_limit() { return; }; let stem = "lunarg-desktop-baseline-2023"; - let full = profile(stem, EXACT_SAMPLING).expect("profile"); + let full = profile(stem, DevicePolicy::default()).expect("profile"); assert!(has_sampled_heap(&full), "{stem}"); let kernel = compile(&bc, "argument_sampler_sample", &full).expect("kernel"); assert_eq!(status_reach(&kernel), StatusReach::Binding); let with = storage_buffers(&kernel); let mut given_back = None; for limit in (0..=with).rev() { - let p = profile_with_storage_buffers(stem, EXACT_SAMPLING, limit).expect("profile"); + let p = + profile_with_storage_buffers(stem, DevicePolicy::default(), limit).expect("profile"); let a = match compile(&bc, "argument_sampler_sample", &p) { Ok(a) => a, Err(Error::Unsupported(u)) if u.feature == Feature::DescriptorCount => break, @@ -4757,7 +4584,7 @@ fn a_block_tests_an_argument_sampler_for_a_cubic_filter_once() { return; }; let mut compiled = 0; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { let Ok(a1) = compile(&one, "k", &p) else { continue; }; @@ -4781,122 +4608,3 @@ fn a_block_tests_an_argument_sampler_for_a_cubic_filter_once() { "no committed profile tests its argument samplers" ); } - -/// What [`heap_depth_plain_kernel`] does with its depth texture: a `read`, a `sample`, or a -/// `gather` (the last two through a constexpr nearest sampler clamped to the edge). -#[derive(Clone, Copy, Debug)] -enum DepthPlain { - Read, - Sample, - Gather, -} - -/// A kernel reading, sampling at `(0.25, 0.25)`, or gathering there, without comparison, the -/// `depth2d` its argument buffer (buffer 0) holds, written to buffer 1's lane `gid` (a -/// `float4`, a read's or sample's depth in `x`). -fn heap_depth_plain_kernel(op: DepthPlain) -> String { - let w = NEAREST_EDGE; - let sampler = format!( - "@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 {w}, i64 0], align 8\n" - ); - let states = "!air.sampler_states = !{!10}\n!10 = !{!\"air.sampler_state\", ptr addrspace(2) @__air_sampler_state}\n"; - let (global, states, access, ty, call, declare) = match op { - DepthPlain::Read => ( - String::new(), - "", - "air.read", - "depth2d", - " %rs = call ptr addrspace(2) @air.get_read_sampler()\n %r = call { float, i8 } @air.read_depth_2d.f32(ptr addrspace(1) %t, ptr addrspace(2) %rs, i32 1, <2 x i32> zeroinitializer, <2 x i32> zeroinitializer, i32 0, i32 1)\n %x = extractvalue { float, i8 } %r, 0\n %v = insertelement <4 x float> zeroinitializer, float %x, i64 0\n", - "declare ptr addrspace(2) @air.get_read_sampler()\ndeclare { float, i8 } @air.read_depth_2d.f32(ptr addrspace(1), ptr addrspace(2), i32, <2 x i32>, <2 x i32>, i32, i32)", - ), - DepthPlain::Sample => ( - sampler, - states, - "air.sample", - "depth2d", - " %r = call { float, i8 } @air.sample_depth_2d.f32(ptr addrspace(1) %t, ptr addrspace(2) @__air_sampler_state, i32 1, <2 x float> , i1 true, <2 x i32> zeroinitializer, i1 false, float 0.0, float 0.0, i32 0)\n %x = extractvalue { float, i8 } %r, 0\n %v = insertelement <4 x float> zeroinitializer, float %x, i64 0\n", - "declare { float, i8 } @air.sample_depth_2d.f32(ptr addrspace(1), ptr addrspace(2), i32, <2 x float>, i1, <2 x i32>, i1, float, float, i32)", - ), - DepthPlain::Gather => ( - sampler, - states, - "air.sample", - "depth2d", - " %r = call { <4 x float>, i8 } @air.gather_depth_2d.v4f32(ptr addrspace(1) %t, ptr addrspace(2) @__air_sampler_state, i32 1, <2 x float> , i1 true, <2 x i32> zeroinitializer, i32 0)\n %v = extractvalue { <4 x float>, i8 } %r, 0\n", - "declare { <4 x float>, i8 } @air.gather_depth_2d.v4f32(ptr addrspace(1), ptr addrspace(2), i32, <2 x float>, i1, <2 x i32>, i32)", - ), - }; - format!( - r#"%struct.M = type {{ ptr addrspace(1) }} -{global} -define void @k(ptr addrspace(2) %m, ptr addrspace(1) %out, i32 %gid) {{ - %pt = getelementptr inbounds %struct.M, ptr addrspace(2) %m, i64 0, i32 0 - %t = load ptr addrspace(1), ptr addrspace(2) %pt, align 8 -{call} %o = getelementptr inbounds <4 x float>, ptr addrspace(1) %out, i32 %gid - store <4 x float> %v, ptr addrspace(1) %o, align 16 - ret void -}} -{declare} -!air.kernel = !{{!0}} -!air.version = !{{!11}} -!air.language_version = !{{!12}} -{states}!0 = !{{ptr @k, !1, !2}} -!1 = !{{}} -!2 = !{{!3, !6, !8}} -!3 = !{{i32 0, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !4, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"M", !"air.arg_name", !"m"}} -!4 = !{{i32 0, i32 8, i32 0, !"{ty}", !"d", !"air.indirect_argument", !5}} -!5 = !{{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"{access}", !"air.arg_type_name", !"{ty}", !"air.arg_name", !"d"}} -!6 = !{{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"}} -!8 = !{{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"gid"}} -!11 = !{{i32 2, i32 8, i32 0}} -!12 = !{{!"Metal", i32 4, i32 0, i32 0}} -"# - ) -} - -/// A heap depth texture's read, nearest sample, or gather without comparison, with a `float` -/// result, converts the device's texel by the class its handle carries, as a slot's converts by its -/// bound format's: a `Depth16Unorm` member's class is `R16Unorm`'s, whose conversion is Metal's `c -/// / 65535` correctly rounded where a device multiplies by the reciprocal (lavapipe), and a -/// `Depth32Float` member's keeps the device's value. On every profile with a sampled heap but -/// Metal's own sampler (`VkProperty::MetalSampler`, whose device value is Metal's) the module -/// defines the `float` routine and carries the handle's class; there it defines no routine. Each -/// validates. (The interpreter models no heap sample; the runtime lane's `depth_texel_reads` reads -/// and samples a `Depth16Unorm` texture through an argument buffer on each device.) -#[test] -fn heap_depth_texels_convert_by_the_handle_s_class() { - use crate::lower::texture::float_texel; - use crate::lower::texture::HEAP_CLASS_CENSUS; - for op in [DepthPlain::Read, DepthPlain::Sample, DepthPlain::Gather] { - let name = format!("{op:?}"); - let Some(bc) = assemble("heap_depth_plain", &heap_depth_plain_kernel(op)) else { - return; - }; - let mut converted = 0; - for (stem, p) in committed_exact_profiles().expect("profiles") { - let what = format!("{name} on {stem}"); - let a = match compile(&bc, "k", &p) { - Ok(a) => a, - Err(e) => { - assert!(!has_sampled_heap(&p), "{what}: {e}"); - let u = unsupported(e); - assert_eq!(u.feature, Feature::ArgumentBufferTextures, "{what}"); - continue; - } - }; - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let shader = !metal_sampler(&p); - assert_eq!( - a.strategies.entries.contains_key(float_texel::CENSUS_NAME), - shader, - "{what}: the float routine" - ); - assert!( - !shader || a.strategies.entries.contains_key(HEAP_CLASS_CENSUS), - "{what}: the handle's class" - ); - converted += usize::from(shader); - } - assert!(converted > 0, "{name}: no committed profile converts it"); - } -} diff --git a/crates/metal2vulkan/src/tests/engine_heap_binder.rs b/crates/metal2vulkan/src/tests/engine_heap_binder.rs index 566450436..0108962cd 100644 --- a/crates/metal2vulkan/src/tests/engine_heap_binder.rs +++ b/crates/metal2vulkan/src/tests/engine_heap_binder.rs @@ -51,9 +51,8 @@ use crate::device::{Device, DeviceDescription, DevicePolicy}; use crate::error::{BindError, Capability, Feature, Needs, Unsupported}; use crate::library::{FunctionArtifact, Library}; use crate::memory::handles::{ - declare_table, define_lookup, lookup_host, Lookup, FLAG_DEPTH_CODES, FLAG_DEPTH_VALUES, - FLAG_OUT_OF_BOUNDS_ALPHA_ONE, FLAG_TEXEL_CLASS, HANDLE_ALPHA_ONE, HANDLE_DEPTH_CODES, - HANDLE_DEPTH_VALUES, TABLE_ENTRY_BYTES, + declare_table, define_lookup, lookup_host, Lookup, FLAG_OUT_OF_BOUNDS_ALPHA_ONE, + FLAG_TEXEL_CLASS, HANDLE_ALPHA_ONE, TABLE_ENTRY_BYTES, }; use crate::memory::leaf::k32; use crate::memory::views; @@ -249,8 +248,8 @@ fn table(bytes: &[DescriptorBytes], set: u32, binding: u32) -> Vec<(u64, u32)> { } /// The entries `(id, element, flags)` of the table bytes at `(set, binding)`: a texture entry's -/// flags hold its out-of-bounds-alpha flag, its depth class, and its texel class's index alone, and -/// the null entry's none. +/// flags hold its out-of-bounds-alpha flag and its texel class's index alone, and the null entry's +/// none. fn entries(bytes: &[DescriptorBytes], set: u32, binding: u32) -> Vec<(u64, u32, u32)> { let b = &bytes .iter() @@ -263,10 +262,7 @@ fn entries(bytes: &[DescriptorBytes], set: u32, binding: u32) -> Vec<(u64, u32, let w = |i: usize| u32::from_le_bytes(e[4 * i..4 * i + 4].try_into().expect("word")); let id = u64::from(w(0)) | (u64::from(w(1)) << 32); assert_eq!( - w(3) & !(FLAG_OUT_OF_BOUNDS_ALPHA_ONE - | FLAG_DEPTH_CODES - | FLAG_DEPTH_VALUES - | FLAG_TEXEL_CLASS), + w(3) & !(FLAG_OUT_OF_BOUNDS_ALPHA_ONE | FLAG_TEXEL_CLASS), 0, "other flags are reserved" ); @@ -577,7 +573,7 @@ fn a_sampled_heap_writes_each_member_and_its_table() { assert_eq!(emitted_lookup(bytes, &keys), want.to_vec()); // Each entry's flags are its member's out-of-bounds alpha: token 2's `R32Uint` has no alpha, // every other member's format has one, and the null entries have none (beside its texel class, - // which `table_entries_state_each_members_depth_class` reads). + // which `table_entries_state_each_members_texel_class` reads). let flag = FLAG_OUT_OF_BOUNDS_ALPHA_ONE; let flags: Vec = entries(&cmds.descriptor_bytes, set, binding) .iter() @@ -592,7 +588,6 @@ fn a_sampled_heap_writes_each_member_and_its_table() { .collect(); let flagged = Lookup::Flagged { alpha: true, - depth: false, class: false, }; assert_eq!(emitted_lookup_in(bytes, &keys, flagged), alpha); @@ -1057,15 +1052,12 @@ fn a_compared_depth_member_is_held_by_the_depth_comparison_class() { .any(|d| d.set == 0 && d.binding == samplers[0].binding)); } -/// Each member's table entry states its depth class beside its out-of-bounds alpha, by its pixel -/// format: `Depth16Unorm` compares codes ([`FLAG_DEPTH_CODES`]), `Depth32Float` and -/// `Depth32Float_Stencil8` values ([`FLAG_DEPTH_VALUES`]), and a color format neither (a depth -/// format has no alpha). The search's flagged form carries the class into the handle's bits 29 and -/// 30, beside the alpha in bit 31 where it carries that too; a miss carries nothing. Each entry -/// also states its texel class's index (`heap_class_index`, in [`FLAG_TEXEL_CLASS`]), which the -/// flagged form carries in place where it carries the class. +/// Each member's table entry states its texel class's index (`heap_class_index`, in +/// [`FLAG_TEXEL_CLASS`]) beside its out-of-bounds alpha (a depth format has no alpha). The +/// search's flagged form carries the alpha in the handle's bit 31 and the class in place where it +/// carries them; a miss carries nothing. #[test] -fn table_entries_state_each_members_depth_class() { +fn table_entries_state_each_members_texel_class() { let dev = m3(); let Some(bc) = assembled("handles", llvm_assemble(&engine_dir().join("handles.ll"))) else { return; @@ -1128,9 +1120,9 @@ fn table_entries_state_each_members_depth_class() { vec![ (0, 0, 0), (D, 4, rgba8), - (A, 1, alpha | FLAG_DEPTH_CODES | d16), - (B, 2, alpha | FLAG_DEPTH_VALUES | d32), - (C, 3, alpha | FLAG_DEPTH_VALUES | d32s8), + (A, 1, alpha | d16), + (B, 2, alpha | d32), + (C, 3, alpha | d32s8), ] ); let bytes = &cmds @@ -1140,30 +1132,17 @@ fn table_entries_state_each_members_depth_class() { .expect("bytes") .bytes; let keys = [D, A, B, C, 0, E]; - let depth = Lookup::Flagged { - alpha: false, - depth: true, - class: false, - }; - let codes = HANDLE_DEPTH_CODES; - let values = HANDLE_DEPTH_VALUES; - assert_eq!( - emitted_lookup_in(bytes, &keys, depth), - vec![4, 1 | codes, 2 | values, 3 | values, 0, 0] - ); - let both = Lookup::Flagged { + let flagged = Lookup::Flagged { alpha: true, - depth: true, class: false, }; let one = HANDLE_ALPHA_ONE; assert_eq!( - emitted_lookup_in(bytes, &keys, both), - vec![4, 1 | one | codes, 2 | one | values, 3 | one | values, 0, 0] + emitted_lookup_in(bytes, &keys, flagged), + vec![4, 1 | one, 2 | one, 3 | one, 0, 0] ); let classes = Lookup::Flagged { alpha: false, - depth: false, class: true, }; assert_eq!( diff --git a/crates/metal2vulkan/src/tests/engine_linear_cube.rs b/crates/metal2vulkan/src/tests/engine_linear_cube.rs deleted file mode 100644 index 811ad05e6..000000000 --- a/crates/metal2vulkan/src/tests/engine_linear_cube.rs +++ /dev/null @@ -1,1652 +0,0 @@ -//! Metal's linear filter of a cube texture, emulated by fetches on a device that does not sample -//! through Metal's own sampler, on the CPU interpreter: -//! -//! - Metal's own answers: seven lanes per format family of a probe (its `cl` run -//! on 1x1 cubes, `lanes-cube-1.bin`; Apple M4 on macOS 27.0.1 and Apple M3 Max on macOS 26.7, -//! byte-identical), bit for bit, with `float` and `half` results: 8-bit unorm and snorm, -//! `R8Unorm`, 8-bit sRGB (through the raw view), 16-bit unorm and snorm, half-float, and 32-bit -//! float. On a 1x1 cube each lane reads one tap on its face, two across its edges, and one past -//! both edges, whose texel is the format's corner rule: a normalized format's made-up texel, a -//! float format's `x` face's. -//! - The rule: random texels of every family on faces of 1, 2, 3, and 5 texels and a cube array's -//! cubes, directions near the faces' edges and corners and at random, majors of 1 and scaled, -//! `half` and `float` results, bit for bit against a reference that finds an edge tap's texel -//! as the texel whose centre on the cube is nearest the tap's. -//! - The selection and the interface: an emulated sample records its filter note and -//! `CubeFaceReciprocal` and declares the slot's 2D-array view of its faces -//! (`RuntimeFact::ImageViewShape`) beside its combined binding; every address mode reaches it; -//! a device with `VkProperty::MetalSampler` keeps every one. -//! - The word estimate bounds the emission, which validates, on every committed profile. -//! -//! `llvm-as` assembles the kernels; without it the tests skip visibly. - -use std::collections::BTreeMap; -use std::sync::atomic::{AtomicU64, Ordering}; - -use crate::budget::SPIRV_WORDS; -use crate::device::profile::DeviceProfile; -use crate::device::requirements::{VkFeature, VkProperty}; -use crate::library::{FunctionArtifact, FunctionConstantValues}; -use crate::lower::select::{LowerInputs, Plan}; -use crate::metal::bicubic::BicubicTexels; -use crate::metal::texel_format::texel_format; -use crate::metal::PixelFormat; -use crate::pipeline::compile::{compile_bitcode, plan_bitcode, EntryRef}; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::interface::PushLoc; -use crate::pipeline::sym::{ - Axis, PushField, ResourceKind, ResourceSlot, SlotClass, SlotRef, SpecKey, Stage, -}; -use crate::pipeline::testing::EXACT_SAMPLING; -use crate::pipeline::testing::{ - compile, link_and_validate, llvm_assemble, meter, profile, typed_module_with, AssembleError, -}; -use crate::pipeline::PrecisionNote; -use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Order, Resources}; -use crate::spirv::ir::{GlobalKind, TypedModule}; -use crate::spirv::testing::committed_exact_profiles; - -use super::engine_linear_half::{depth_passes, plane_sum, Stored, Tap, Texels}; -use super::engine_srgb_raw::{f32_bits, half_bits, step}; - -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"; - -pub(super) const TEXTURE: SlotRef = SlotRef { - stage: Stage::Kernel, - class: SlotClass::Texture, - index: 0, -}; - -/// Bitcode of the module `body` (after the AIR header), or `None` without `llvm-as`. -pub(super) fn assemble(name: &str, body: &str) -> Option> { - static NEXT: AtomicU64 = AtomicU64::new(0); - let dir = std::env::temp_dir().join(format!( - "m2v-linear-cube-{}-{}-{}", - std::process::id(), - NEXT.fetch_add(1, Ordering::Relaxed), - name.replace(' ', "-") - )); - std::fs::create_dir_all(&dir).expect("scratch"); - let ll = dir.join("k.ll"); - std::fs::write(&ll, format!("{HEADER}{body}")).expect("write"); - let r = llvm_assemble(&ll); - let _ = std::fs::remove_dir_all(&dir); - match r { - Ok(x) => Some(x), - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - None - } - Err(AssembleError::Rejected(why)) => panic!("{name}: {why}"), - } -} - -pub(super) fn lavapipe() -> DeviceProfile { - profile("lavapipe", EXACT_SAMPLING).expect("profile") -} - -pub(super) fn m3() -> DeviceProfile { - profile("moltenvk-m3", EXACT_SAMPLING).expect("profile") -} - -/// The words of a constexpr sampler (the `hlf_half_address` fixture's fields): minification and -/// magnification `filter` (0 nearest, 1 linear), mip filter `mip` (0 none, 2 linear), every axis -/// addressed by `address` (0 zero or border, 1 edge, 2 repeat, 3 mirrored repeat), and border -/// color code `border` (0 transparent black, 2 opaque white). -pub(super) fn sampler_words(filter: u64, mip: u64, address: u64, border: u64) -> u64 { - const BASE: u64 = 0x007b_ff00_0008_0000; - BASE | address - | address << 3 - | address << 6 - | filter << 9 - | filter << 11 - | mip << 13 - | border << 56 -} - -/// A linear sampler clamping to the edge, without a mip filter: the probes'. -pub(super) fn edge() -> u64 { - sampler_words(1, 0, 1, 0) -} - -/// A kernel sampling `texturecube` slot 0 (`texturecube_array` where `array`) through constexpr -/// sampler `words` along `float4` buffer 0's lane `tid` (its `xyz`; its `w`'s bits the array -/// index), storing the `half4` (`float4` unless `half`) to buffer 1. -fn kernel(words: u64, half: bool, array: bool) -> String { - let (texel, vec4, size, out_ty, suffix) = if half { - ("half", "<4 x half>", 8, "half4", "v4f16") - } else { - ("float", "<4 x float>", 16, "float4", "v4f32") - }; - let (dim, tex_ty, layer, layer_ty) = if array { - ( - "cube_array", - format!("texturecube_array<{texel}, sample>"), - "i32 %a, ", - "i32, ", - ) - } else { - ("cube", format!("texturecube<{texel}, sample>"), "", "") - }; - format!( - r#"@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 {words}, i64 0], align 8 - -define void @k(ptr addrspace(1) %t, ptr addrspace(1) %c, ptr addrspace(1) %out, i32 %tid) {{ - %i = zext i32 %tid to i64 - %p = getelementptr inbounds <4 x float>, ptr addrspace(1) %c, i64 %i - %c4 = load <4 x float>, ptr addrspace(1) %p, align 16 - %d = shufflevector <4 x float> %c4, <4 x float> zeroinitializer, <3 x i32> - %wf = extractelement <4 x float> %c4, i64 3 - %a = bitcast float %wf to i32 - %r = call {{ {vec4}, i8 }} @air.sample_texture_{dim}.{suffix}(ptr addrspace(1) %t, ptr addrspace(2) @__air_sampler_state, <3 x float> %d, {layer}i1 false, float 0.0, float 0.0, i32 0) - %v = extractvalue {{ {vec4}, i8 }} %r, 0 - %q = getelementptr inbounds {vec4}, ptr addrspace(1) %out, i64 %i - store {vec4} %v, ptr addrspace(1) %q, align {size} - ret void -}} - -declare {{ {vec4}, i8 }} @air.sample_texture_{dim}.{suffix}(ptr addrspace(1), ptr addrspace(2), <3 x float>, {layer_ty}i1, float, float, i32) - -!air.kernel = !{{!0}} -!air.sampler_states = !{{!7}} -!0 = !{{ptr @k, !1, !2}} -!1 = !{{}} -!2 = !{{!3, !4, !5, !6}} -!3 = !{{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"{tex_ty}", !"air.arg_name", !"t"}} -!4 = !{{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"c"}} -!5 = !{{i32 2, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 {size}, !"air.arg_type_align_size", i32 {size}, !"air.arg_type_name", !"{out_ty}", !"air.arg_name", !"out"}} -!6 = !{{i32 3, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"tid"}} -!7 = !{{!"air.sampler_state", ptr addrspace(2) @__air_sampler_state}} -"# - ) -} - -/// The lowering inputs: the slot bound in an 8-bit sRGB format where `srgb` (its variant). -pub(super) fn inputs(srgb: bool) -> LowerInputs { - let mut i = LowerInputs::new(); - if srgb { - i.srgb_textures.insert(TEXTURE); - } - i -} - -/// The module's resource of texture slot 0 whose kind `kind` accepts. -pub(super) fn resource( - m: &TypedModule, - kind: impl Fn(&ResourceKind) -> bool, -) -> Option { - m.globals().iter().find_map(|g| match g.kind { - GlobalKind::Resource(s) if s.index == 0 && kind(&s.kind) => Some(s), - _ => None, - }) -} - -/// Resources of a dispatch of one-thread threadgroups over `lanes` (buffer 0, a direction and an -/// array index each), the result's `bytes` per lane (buffer 1), and the slot's `TexelFormat` -/// specialization `class`. -pub(super) fn resources(plan: &Plan, lanes: &[[u32; 4]], bytes: usize, class: u32) -> Resources { - let mut spec = BTreeMap::new(); - for axis in [Axis::X, Axis::Y, Axis::Z] { - spec.insert(SpecKey::LocalSize(axis), 1); - } - spec.insert(SpecKey::FlatLocalSize, 1); - spec.insert(SpecKey::TexelFormat(TEXTURE), u64::from(class)); - spec.insert( - SpecKey::PlainHalfTexels(TEXTURE), - u64::from(crate::metal::texel_format::TexelFormat(class).plain_on_metal_sampler()), - ); - let push = vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)]; - for f in &plan.push.fields { - match (f.field, f.loc) { - (PushField::SlotBindOffset(_) | PushField::DispatchRegion, PushLoc::Push { .. }) => {} - // A bound value read as data, which the interpreter writes from `spec`. - (PushField::Specialized(_), PushLoc::Push { .. }) => {} - // No slot's writes dropped: the word stays 0. - (PushField::Specialized(crate::pipeline::sym::SpecKey::DroppedStoreSlots(_)), _) => {} - other => panic!("unexpected push field {other:?}"), - } - } - let buffer = |index: u32, bytes: Vec| Buffer { - slot: Some(ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index, - }), - address: None, - bytes, - }; - let input = lanes - .iter() - .flatten() - .flat_map(|w| w.to_le_bytes()) - .collect(); - Resources { - buffers: vec![buffer(0, input), buffer(1, vec![0xab; bytes * lanes.len()])], - push, - spec, - } -} - -/// The run of `m` over `lanes` in both scheduling orders, which must agree: per lane the result's -/// four channels' bits (a `half`'s when `half`). -pub(super) fn run(m: &TypedModule, res: &Resources, images: &[Image], half: bool) -> Vec<[u32; 4]> { - let lanes = res.buffers[0].bytes.len() / 16; - let mut outs = Vec::new(); - for order in [Order::Forward, Order::Reverse] { - let cfg = Config { - workgroups: [lanes as u32, 1, 1], - order, - ..Config::default() - }; - let (o, _) = run_with_images(m, &cfg, res.clone(), images.to_vec()) - .unwrap_or_else(|e| panic!("interpreter: {e:?}")); - outs.push(o.buffers); - } - assert_eq!(outs[0], outs[1], "the scheduling orders disagree"); - let size = if half { 2 } else { 4 }; - outs[0][1] - .chunks_exact(4 * size) - .map(|c| { - std::array::from_fn(|k| { - let mut b = [0u8; 4]; - b[..size].copy_from_slice(&c[size * k..size * (k + 1)]); - u32::from_le_bytes(b) - }) - }) - .collect() -} - -/// The images of every texture binding of slot 0, of faces `n` texels wide in `layers` layers (6 -/// per cube): the slot's view of its faces (its raw view where `raw`) holds `texel(layer, i, j)` -/// (each channel's `f32` bits as a fetch reads them), and every other binding (the combined -/// binding's cube, the plain view beside a raw one) a NaN no emulated sample may read. -pub(super) fn images( - m: &TypedModule, - (n, layers): (u32, u32), - raw: bool, - texel: &dyn Fn(u32, u32, u32) -> [u32; 4], -) -> Vec { - let faces = match raw { - true => ResourceKind::RawTexture, - false => ResourceKind::Texture, - }; - assert!( - resource(m, |k| *k == faces).is_some(), - "no view of the slot's faces" - ); - let bindings = m.globals().iter().filter_map(|g| match g.kind { - GlobalKind::Resource(s) - if s.index == 0 - && matches!( - s.kind, - ResourceKind::Texture - | ResourceKind::RawTexture - | ResourceKind::CombinedTextureSampler(_) - ) => - { - Some(s) - } - _ => None, - }); - bindings - .map(|slot| { - let mut img = Image::new(slot, [n, n, 1], layers, 1, 1); - if slot.kind != faces { - img.texels.fill([0x7fc0_0001; 4]); - return img; - } - for l in 0..layers { - for j in 0..n { - for i in 0..n { - let at = img.index(0, l, 0, [i, j, 0]).expect("texel"); - img.texels[at] = texel(l, i, j); - } - } - } - img - }) - .collect() -} - -// ---- The reference ---------------------------------------------------------------------------- - -/// Metal's face of direction `d` (ties `x` over `y` over `z`; the lanes hold none), its minor -/// components as Vulkan's face table orients them, and the major magnitude. -fn select(d: [f32; 3]) -> (usize, f32, f32, f32) { - let a = d.map(f32::abs); - if a[0] >= a[1] && a[0] >= a[2] { - match d[0] >= 0.0 { - true => (0, -d[2], -d[1], a[0]), - false => (1, d[2], -d[1], a[0]), - } - } else if a[1] >= a[2] { - match d[1] >= 0.0 { - true => (2, d[0], d[2], a[1]), - false => (3, d[0], -d[2], a[1]), - } - } else { - match d[2] >= 0.0 { - true => (4, d[0], -d[1], a[2]), - false => (5, -d[0], -d[1], a[2]), - } - } -} - -/// Metal's base texel and 1/256 steps on a face axis of `n` texels of minor component `c` beside -/// major magnitude `ma`: `X = RN(RN(1 + c r) / 2 n)` with `r` the device's reciprocal of `ma` (the -/// interpreter's `RN(1 / ma)`), the sum fused, then `q = floor(256 X + 1/2) - 128`; 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 axis(c: f32, ma: f32, n: u32, wraps: bool) -> (i64, i64) { - let r = 1.0 / ma; - let f = c.mul_add(r, 1.0); - let u = f * 0.5; - let u = match wraps && !n.is_power_of_two() && u >= 1.0 { - true => u - 1.0, - false => u, - }; - let x = u * n as f32; - let q = (f64::from(x) * 256.0 + 0.5).floor() as i64 - 128; - (q >> 8, q & 255) -} - -/// The direction of tap `(i, j)` of face `face` in the doubled frame where a face spans `[-n, n]` -/// (Vulkan's face table at `sc = 2 i + 1 - n`, `tc = 2 j + 1 - n`, the major `±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], - } -} - -/// The texels a tap reads: one (its own, or across one edge the texel whose centre is nearest the -/// tap's), or past both edges of its face the corner texels of the `x`, `y`, and `z` faces there. -fn texels(face: usize, (i, j): (i64, i64), n: i64) -> Vec<(usize, i64, i64)> { - let d = direction(face, i, j, n); - let mut all = Vec::new(); - for g in 0..6 { - for b in 0..n { - for a in 0..n { - all.push((g, a, b, direction(g, a, b, n))); - } - } - } - let past = |v: i64| !(0..n).contains(&v); - if past(i) && past(j) { - return (0..3) - .map(|pick| { - let mut c = d.map(|v| v.signum() * (n - 1)); - c[pick] = d[pick].signum() * n; - let t = all.iter().find(|t| t.3 == c).expect("a corner texel"); - (t.0, t.1, t.2) - }) - .collect(); - } - 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 near: Vec<_> = all.iter().filter(|t| distance(&t.3) == least).collect(); - assert_eq!(near.len(), 1, "one nearest texel to {d:?}"); - vec![(near[0].0, near[0].1, near[0].2)] -} - -/// The four taps of direction `d` on faces of `n` texels, each with its weight `wx · wy` in units -/// of `2^-16` and its texels ([`texels`]), the face's `s` and `t` axes wrapped where `wrap` says -/// ([`axis`]). -pub(super) type Footprint = Vec<(i64, Vec<(usize, i64, i64)>)>; - -pub(super) fn footprint(d: [f32; 3], n: u32, wrap: (bool, bool)) -> Footprint { - let (face, sc, tc, ma) = select(d); - let (i, kx) = axis(sc, ma, n, wrap.0); - let (j, ky) = axis(tc, ma, n, wrap.1); - let n = i64::from(n); - [ - (i, j, (256 - kx) * (256 - ky)), - (i + 1, j, kx * (256 - ky)), - (i, j + 1, (256 - kx) * ky), - (i + 1, j + 1, kx * ky), - ] - .into_iter() - .map(|(a, b, w)| (w, texels(face, (a, b), n))) - .collect() -} - -/// A normalized format's code scale and whether it is signed, by its texel class. -pub(super) fn norm(class: u32) -> Option<(i64, bool)> { - let has = |b: u32| class & b != 0; - if !has(BicubicTexels::EXACT) { - return None; - } - let signed = has(BicubicTexels::SNORM); - Some(match (has(BicubicTexels::WIDE16), signed) { - (false, false) => (255, false), - (false, true) => (127, true), - (true, false) => (65535, false), - (true, true) => (32767, true), - }) -} - -/// Metal's result bits of channel `c` over footprint `fp` of a cube of stored texels `stored(layer, -/// i, j)` of format class `class` (`tex` its texels, whose class the sums read), the cube's first -/// layer `base`: the 2D sums ([`plane_sum`]) of the taps, a tap at the cube's corner a normalized -/// format's made-up code `⌊(6 X + 5 Y + 5 Z + 8) / 16⌋` (codes read from `-scale` up) and a float -/// format's `x` face's texel. -fn expected( - tex: &Texels, - class: u32, - fp: &Footprint, - stored: &dyn Fn(usize, i64, i64) -> [Stored; 4], - (c, half): (usize, bool), -) -> u32 { - let taps: Vec<(Tap, i64)> = fp - .iter() - .map(|(w, at)| { - let v = |k: usize| stored(at[k].0, at[k].1, at[k].2)[c]; - let tap = match (at.len(), norm(class)) { - (3, Some((scale, _))) => { - let code = |k: usize| match v(k) { - Stored::Code(x) => x.max(-scale), - Stored::Value(_) => unreachable!("a float texel of a normalized format"), - }; - Stored::Code((6 * code(0) + 5 * code(1) + 5 * code(2) + 8).div_euclid(16)) - } - _ => v(0), - }; - (Tap::Stored(tap), *w) - }) - .collect(); - plane_sum(tex, &taps, half) -} - -/// An 8-bit sRGB format's result bits of channel `c` over footprint `fp` of codes `codes(layer, i, -/// j)`: a color channel's table steps (grid 4095), alpha's `16 · code` (grid 4080), a corner's -/// made-up step or code, each term truncated onto `2^-4`, then `⌊(T + 2^11) / 2^12⌋` divided by the -/// grid. -fn expected_srgb( - fp: &Footprint, - codes: &dyn Fn(usize, i64, i64) -> [u32; 4], - (c, half): (usize, bool), -) -> u32 { - let unit = |code: u32| -> i64 { - match c < 3 { - true => step(code) as i64, - false => i64::from(code), - } - }; - let (scale, grid) = if c < 3 { (1, 4095) } else { (16, 4080) }; - let mut t = 0i64; - for (w, at) in fp { - let v = |k: usize| unit(codes(at[k].0, at[k].1, at[k].2)[c]); - let g = match at.len() { - 3 => (6 * v(0) + 5 * v(1) + 5 * v(2) + 8) >> 4, - _ => v(0), - } * scale; - t += (g * w) >> 4; - } - let n = ((t + (1 << 11)) >> 12).clamp(0, grid) as u64; - match half { - true => u32::from(half_bits(n, grid as u64)), - false => f32_bits(n, grid as u64), - } -} - -/// A deterministic source: SplitMix64. -pub(super) struct Rng(pub(super) u64); - -impl Rng { - pub(super) fn next(&mut self) -> u64 { - self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15); - let mut z = self.0; - z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); - z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); - z ^ (z >> 31) - } - - pub(super) fn below(&mut self, n: u64) -> u64 { - self.next() % n - } -} - -/// Directions on faces of `n` texels as the probes made them: per face axis a position within -/// half a texel of either edge or on a 1/256 step, or anywhere, moved up to two ulps, on a random -/// face, its major `±1`, or (one lane in two) the direction scaled by a factor in `[0.3, 3)`; the -/// `w` lane holds an array index in `[0, cubes]` (one past the last cube) or `-1`. -pub(super) fn directions(n: u32, count: usize, cubes: u32, rng: &mut Rng) -> Vec<[u32; 4]> { - let n64 = f64::from(n); - let position = |rng: &mut Rng| -> f32 { - let x = match rng.below(4) { - 0 => (rng.below(128) as f64 + 0.5) / 256.0, - 1 => n64 - (rng.below(128) as f64 + 0.5) / 256.0, - 2 => (rng.below(u64::from(n)) as f64 + 0.5 + (rng.below(256) as f64 + 0.5) / 256.0) - .min(n64 - 1.0 / 512.0), - _ => n64 * (0.001 + 0.998 * (rng.below(1 << 20) as f64 / f64::from(1 << 20))), - }; - let c0 = (2.0 * x / n64 - 1.0) as f32; - let moved = f32::from_bits((c0.to_bits() as i64 + rng.below(5) as i64 - 2) as u32); - if c0 == 0.0 || moved.abs() >= 1.0 { - c0 - } else { - moved - } - }; - (0..count) - .map(|k| { - let face = rng.below(6); - let (s, t) = (position(rng), position(rng)); - 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], - }; - let m = match k % 2 { - 0 => 1.0, - _ => 0.3 + 2.7 * (rng.below(1 << 20) as f32 / (1 << 20) as f32), - }; - // Metal clamps the index as an unsigned integer: `-1` reads the last cube. - let index = match rng.below(8) { - 0 => u32::MAX, - _ => rng.below(u64::from(cubes) + 1) as u32, - }; - [ - (d[0] * m).to_bits(), - (d[1] * m).to_bits(), - (d[2] * m).to_bits(), - index, - ] - }) - .collect() -} - -/// The formats whose stored texels [`Texels::random`] makes: every non-sRGB family. -pub(super) const FORMATS: [PixelFormat; 7] = [ - PixelFormat::RGBA8Unorm, - PixelFormat::RGBA8Snorm, - PixelFormat::R8Unorm, - PixelFormat::RGBA16Unorm, - PixelFormat::RGBA16Snorm, - PixelFormat::RGBA16Float, - PixelFormat::RGBA32Float, -]; - -/// Every lane of random cubes of every format family (faces of 1 texel and of 2, 3, or 5 by -/// format; three cubes of an array) is Metal's rule, bit for bit, with `half` and `float` results; -/// and some lanes of each format read a corner tap. -#[test] -fn linear_cube_samples_take_metals_filter() { - let p = lavapipe(); - for half in [true, false] { - for array in [false, true] { - let name = format!("cube half={half} array={array}"); - let Some(bc) = assemble(&name, &kernel(edge(), half, array)) else { - return; - }; - let (plan, m) = typed_module_with(&bc, "k", &p, &inputs(false)) - .unwrap_or_else(|e| panic!("{name}: {e}")); - let cubes = if array { 3 } else { 1 }; - for (seed, pf) in FORMATS.iter().enumerate() { - let class = texel_format(*pf).0; - // Faces of one texel, where every lane reads past the edges, and one more size - // per format. - let other = [2u32, 3, 5][seed % 3]; - let sizes = if array { vec![other] } else { vec![1, other] }; - for n in sizes { - let mut rng = Rng(0x00c0_be22_0000 + seed as u64 * 64 + u64::from(n)); - let layers = 6 * cubes; - let tex = - Texels::random(class, i64::from(n), i64::from(n * layers), rng.next()); - let stored = |l: u32, i: i64, j: i64| -> [Stored; 4] { - tex.t[((i64::from(l * n) + j) * i64::from(n) + i) as usize] - }; - let imgs = images(&m, (n, layers), false, &|l, i, j| { - stored(l, i64::from(i), i64::from(j)).map(|s| tex.fetched(s).to_bits()) - }); - let lanes = directions(n, 96, cubes, &mut rng); - let bytes = if half { 8 } else { 16 }; - let out = run(&m, &resources(&plan, &lanes, bytes, class), &imgs, half); - let mut corners = 0; - for (lane, (d, got)) in lanes.iter().zip(&out).enumerate() { - let dir = [d[0], d[1], d[2]].map(f32::from_bits); - let fp = footprint(dir, n, (false, false)); - let base = 6 * if array { d[3].min(cubes - 1) } else { 0 }; - let at = |g: usize, i: i64, j: i64| stored(base + g as u32, i, j); - corners += usize::from(fp.iter().any(|(w, t)| *w > 0 && t.len() == 3)); - for (c, got) in got.iter().enumerate() { - let want = expected(&tex, class, &fp, &at, (c, half)); - assert_eq!( - *got, want, - "{name} {pf:?} n={n} lane {lane} {dir:?} [{}] channel {c}: \ - {got:#010x} vs {want:#010x}", - d[3] - ); - } - } - assert!(corners > 0, "{name} {pf:?} n={n}: no lane reads a corner"); - } - } - } - } -} - -/// An 8-bit sRGB format's cube (through the slot's raw view, under its variant) is Metal's sum of -/// the table's steps, its corner tap the made-up step, bit for bit with `half` and `float` -/// results, on random codes in every channel. -#[test] -fn a_raw_cube_sums_the_steps_as_metal_does() { - let p = lavapipe(); - let class = texel_format(PixelFormat::RGBA8UnormSRGB).0; - for half in [true, false] { - let name = format!("srgb cube half={half}"); - let Some(bc) = assemble(&name, &kernel(edge(), half, false)) else { - return; - }; - let (plan, m) = typed_module_with(&bc, "k", &p, &inputs(true)) - .unwrap_or_else(|e| panic!("{name}: {e}")); - assert!( - !plan.precision.contains(&PrecisionNote::SrgbTexelDecode), - "{name}" - ); - for n in [1u32, 2, 3] { - let mut rng = Rng(0x05ee_d022_0000 + u64::from(n)); - let codes: Vec<[u32; 4]> = (0..6 * n * n) - .map(|_| std::array::from_fn(|_| rng.below(256) as u32)) - .collect(); - let code = |l: usize, i: i64, j: i64| { - codes[((l as i64 * i64::from(n) + j) * i64::from(n) + i) as usize] - }; - let imgs = images(&m, (n, 6), true, &|l, i, j| { - code(l as usize, i64::from(i), i64::from(j)).map(|c| f32_bits(u64::from(c), 255)) - }); - let lanes = directions(n, 160, 0, &mut rng); - let bytes = if half { 8 } else { 16 }; - let out = run(&m, &resources(&plan, &lanes, bytes, class), &imgs, half); - for (lane, (d, got)) in lanes.iter().zip(&out).enumerate() { - let dir = [d[0], d[1], d[2]].map(f32::from_bits); - let fp = footprint(dir, n, (false, false)); - for (c, got) in got.iter().enumerate() { - let want = expected_srgb(&fp, &code, (c, half)); - assert_eq!( - *got, want, - "{name} n={n} lane {lane} {dir:?} channel {c}: {got:#x} vs {want:#x}" - ); - } - } - } - } -} - -/// Directions whose face coordinate on either axis of every face is exactly `±1`, an ulp or two -/// inside, or half way, beside a major magnitude of 1, 3, or 0.75 (ties among them): where a -/// repeating face axis wraps. -pub(super) fn edge_directions() -> Vec<[u32; 4]> { - 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 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], - }; - let d = d.map(|c| (c * m).to_bits()); - out.push([d[0], d[1], d[2], 0]); - } - } - } - } - out -} - -/// Through a linear sampler that repeats on every axis, a face coordinate of exactly 1 wraps to 0 -/// on faces of 3 and 5 texels and stays on the last texel on faces of 4: every lane of -/// [`edge_directions`] is the rule, bit for bit, and some lanes of each size that is not a power of -/// two read another footprint than a clamping sampler's. -#[test] -fn a_repeating_face_axis_wraps_a_coordinate_of_one() { - let p = lavapipe(); - let repeat = sampler_words(1, 0, 2, 0); - let name = "cube repeat"; - let Some(bc) = assemble(name, &kernel(repeat, false, false)) else { - return; - }; - let (plan, m) = - typed_module_with(&bc, "k", &p, &inputs(false)).unwrap_or_else(|e| panic!("{name}: {e}")); - let pf = PixelFormat::RGBA32Float; - let class = texel_format(pf).0; - let lanes = edge_directions(); - for n in [3u32, 5, 4] { - let mut rng = Rng(0x0e0d_9e22_0000 + u64::from(n)); - let tex = Texels::random(class, i64::from(n), i64::from(6 * n), rng.next()); - let stored = |l: usize, i: i64, j: i64| -> [Stored; 4] { - tex.t[((l as i64 * i64::from(n) + j) * i64::from(n) + i) as usize] - }; - let imgs = images(&m, (n, 6), false, &|l, i, j| { - stored(l as usize, i64::from(i), i64::from(j)).map(|s| tex.fetched(s).to_bits()) - }); - let out = run(&m, &resources(&plan, &lanes, 16, class), &imgs, false); - let mut moved = 0; - for (lane, (d, got)) in lanes.iter().zip(&out).enumerate() { - let dir = [d[0], d[1], d[2]].map(f32::from_bits); - let fp = footprint(dir, n, (true, true)); - let clamped = footprint(dir, n, (false, false)); - moved += usize::from(fp != clamped); - for (c, got) in got.iter().enumerate() { - let want = expected(&tex, class, &fp, &stored, (c, false)); - assert_eq!( - *got, want, - "{name} n={n} lane {lane} {dir:?} channel {c}: {got:#010x} vs {want:#010x}" - ); - } - } - match n.is_power_of_two() { - true => assert_eq!(moved, 0, "{name} n={n}"), - false => assert!(moved > 0, "{name} n={n}: no lane wraps"), - } - } -} - -/// A kernel sampling `texturecube` slot 0 through runtime sampler slot 0 along `float4` -/// buffer 0's lane `tid` (its `xyz`), storing the `float4` to buffer 1. -fn runtime_kernel() -> String { - r#"define void @k(ptr addrspace(1) %t, ptr addrspace(1) %c, ptr addrspace(1) %out, ptr addrspace(2) %s, i32 %tid) { - %i = zext i32 %tid to i64 - %p = getelementptr inbounds <4 x float>, ptr addrspace(1) %c, i64 %i - %c4 = load <4 x float>, ptr addrspace(1) %p, align 16 - %d = shufflevector <4 x float> %c4, <4 x float> zeroinitializer, <3 x i32> - %r = call { <4 x float>, i8 } @air.sample_texture_cube.v4f32(ptr addrspace(1) %t, ptr addrspace(2) %s, <3 x float> %d, i1 false, float 0.0, float 0.0, i32 0) - %v = extractvalue { <4 x float>, i8 } %r, 0 - %q = getelementptr inbounds <4 x float>, ptr addrspace(1) %out, i64 %i - store <4 x float> %v, ptr addrspace(1) %q, align 16 - ret void -} - -declare { <4 x float>, i8 } @air.sample_texture_cube.v4f32(ptr addrspace(1), ptr addrspace(2), <3 x float>, i1, float, float, i32) - -!air.kernel = !{!0} -!0 = !{ptr @k, !1, !2} -!1 = !{} -!2 = !{!3, !4, !5, !6, !7} -!3 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texturecube", !"air.arg_name", !"t"} -!4 = !{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"c"} -!5 = !{i32 2, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"} -!6 = !{i32 3, !"air.sampler", !"air.location_index", i32 0, i32 1, !"air.arg_type_name", !"sampler", !"air.arg_name", !"s"} -!7 = !{i32 4, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"tid"} -"# - .to_string() -} - -/// A cube sample through a runtime sampler slot takes Metal's cube filter by the bound sampler's -/// word: a face axis whose word's mode is `repeat` wraps a face coordinate of 1 on a face of 3 -/// texels and not of 4, and `clamp_to_edge` and `mirrored_repeat` read as clamping, every lane of -/// [`edge_directions`] bit for bit on the interpreter. -#[test] -fn a_runtime_sampler_wraps_a_cube_face_by_its_word() { - use crate::metal::sampler::SamplerWord; - use crate::metal::SamplerAddressMode as M; - let p = lavapipe(); - let name = "runtime cube"; - let Some(bc) = assemble(name, &runtime_kernel()) else { - return; - }; - let a = compile(&bc, "k", &p).unwrap_or_else(|e| panic!("{name}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name}: {e}")); - let state = a.interface.read_keys().into_iter().find_map(|k| match k { - SpecKey::SamplerState { fields, .. } => Some((k, fields)), - _ => None, - }); - let Some((key, fields)) = state else { - panic!("{name}: no `SamplerState` specialization"); - }; - let (plan, m) = - typed_module_with(&bc, "k", &p, &inputs(false)).unwrap_or_else(|e| panic!("{name}: {e}")); - let pf = PixelFormat::RGBA32Float; - let class = texel_format(pf).0; - let lanes = edge_directions(); - for (mode, wraps, n) in [ - (M::Repeat, true, 3u32), - (M::Repeat, true, 4), - (M::ClampToEdge, false, 5), - (M::MirrorRepeat, false, 3), - ] { - let mut word = SamplerWord::LINEAR; - for shift in SamplerWord::ADDRESS_SHIFT { - word |= mode.as_raw() << shift; - } - { - let mut rng = Rng(0x0e0d_9e22_0000 + u64::from(n)); - let tex = Texels::random(class, i64::from(n), i64::from(6 * n), rng.next()); - let stored = |l: usize, i: i64, j: i64| -> [Stored; 4] { - tex.t[((l as i64 * i64::from(n) + j) * i64::from(n) + i) as usize] - }; - let imgs = images(&m, (n, 6), false, &|l, i, j| { - stored(l as usize, i64::from(i), i64::from(j)).map(|s| tex.fetched(s).to_bits()) - }); - let mut res = resources(&plan, &lanes, 16, class); - res.spec.insert(key, u64::from(word & fields)); - let out = run(&m, &res, &imgs, false); - for (lane, (d, got)) in lanes.iter().zip(&out).enumerate() { - let dir = [d[0], d[1], d[2]].map(f32::from_bits); - let fp = footprint(dir, n, (wraps, wraps)); - for (c, got) in got.iter().enumerate() { - let want = expected(&tex, class, &fp, &stored, (c, false)); - assert_eq!( - *got, want, - "{name} {mode:?} n={n} lane {lane} {dir:?} channel {c}: {got:#010x} vs \ - {want:#010x}" - ); - } - } - } - } -} - -// ---- Depth comparisons ------------------------------------------------------------------------ - -/// A kernel comparing `depthcube` slot 0 (`depthcube_array` at cube 1 where `array`) through -/// constexpr sampler `words` along `float4` buffer 0's lane `tid` (its `xyz`) against its `w`, -/// storing the `float` result in the `x` of buffer 1's `float4`. -fn compare_kernel(words: u64, array: bool) -> String { - let (dim, tex_ty, layer, layer_ty) = match array { - true => ( - "cube_array", - "depthcube_array", - "i32 1, ", - "i32, ", - ), - false => ("cube", "depthcube", "", ""), - }; - format!( - r#"@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 {words}, i64 0], align 8 - -define void @k(ptr addrspace(1) %t, ptr addrspace(1) %c, ptr addrspace(1) %out, i32 %tid) {{ - %i = zext i32 %tid to i64 - %p = getelementptr inbounds <4 x float>, ptr addrspace(1) %c, i64 %i - %c4 = load <4 x float>, ptr addrspace(1) %p, align 16 - %d = shufflevector <4 x float> %c4, <4 x float> zeroinitializer, <3 x i32> - %ref = extractelement <4 x float> %c4, i64 3 - %r = call {{ float, i8 }} @air.sample_compare_depth_{dim}.f32(ptr addrspace(1) %t, ptr addrspace(2) @__air_sampler_state, i32 1, <3 x float> %d, {layer}float %ref, i1 true, float 0.0, float 0.0, i32 0) - %v = extractvalue {{ float, i8 }} %r, 0 - %v4 = insertelement <4 x float> zeroinitializer, float %v, i64 0 - %q = getelementptr inbounds <4 x float>, ptr addrspace(1) %out, i64 %i - store <4 x float> %v4, ptr addrspace(1) %q, align 16 - ret void -}} - -declare {{ float, i8 }} @air.sample_compare_depth_{dim}.f32(ptr addrspace(1), ptr addrspace(2), i32, <3 x float>, {layer_ty}float, i1, float, float, i32) - -!air.kernel = !{{!0}} -!air.sampler_states = !{{!7}} -!0 = !{{ptr @k, !1, !2}} -!1 = !{{}} -!2 = !{{!3, !4, !5, !6}} -!3 = !{{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"{tex_ty}", !"air.arg_name", !"t"}} -!4 = !{{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"c"}} -!5 = !{{i32 2, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"}} -!6 = !{{i32 3, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"tid"}} -!7 = !{{!"air.sampler_state", ptr addrspace(2) @__air_sampler_state}} -"# - ) -} - -/// The depth formats whose cube comparison the emulation answers (`metal::texel_format`). -const DEPTHS: [PixelFormat; 2] = [PixelFormat::Depth32Float, PixelFormat::Depth16Unorm]; - -/// Metal's linear cube comparison over footprint `fp` of depths `stored(layer, i, j)` (channel 0 of -/// a cube of `Depth16Unorm` codes where `d16`, else `Depth32Float` values) against reference `r` -/// under AIR compare function code `f`: each tap's depth compared (a tap at the cube's corner -/// `Depth16Unorm`'s made-up code `⌊(6 X + 5 Y + 5 Z + 8) / 16⌋`, else the `x` face's texel), and -/// the passes summed as an `r8Unorm` texture's codes 0 and 255 (`r8` its texels, whose class the -/// sum reads). -fn compared( - fp: &Footprint, - stored: &dyn Fn(usize, i64, i64) -> Stored, - (fetched, d16): (&dyn Fn(Stored) -> f32, bool), - (f, r): (u64, f32), - r8: &Texels, -) -> u32 { - let taps: Vec<(Tap, i64)> = fp - .iter() - .map(|(w, at)| { - let code = |s: Stored| match s { - Stored::Code(c) => Some(c), - Stored::Value(_) => None, - }; - let depth = match (at.len(), d16) { - (3, true) => { - let c = |k: usize| code(stored(at[k].0, at[k].1, at[k].2)).expect("a code"); - let m = (6 * c(0) + 5 * c(1) + 5 * c(2) + 8).div_euclid(16); - ((m as f64 / 65535.0) as f32, Some(m)) - } - _ => { - let s = stored(at[0].0, at[0].1, at[0].2); - (fetched(s), code(s)) - } - }; - let pass = i64::from(depth_passes(f, r, depth)); - (Tap::Stored(Stored::Code(255 * pass)), *w) - }) - .collect(); - plane_sum(r8, &taps, false) -} - -/// A depth cube's linear comparison compares each tap, the corner's by the format's rule -/// (`Depth32Float`'s `x` face's texel, `Depth16Unorm`'s made-up code), and sums the passes as -/// `r8Unorm` codes 0 and 255 (3,072 directions of two cubes and a cube array, -/// every lane): every lane of random depth cubes (faces of 1 and 3 texels; a cube array's second -/// cube) under `less`, `greater_equal` and `not_equal`, references equal to a texel's depth and NaN -/// included, and some lanes reading a corner tap. -#[test] -fn linear_cube_comparisons_sum_their_passes() { - let p = lavapipe(); - let r8 = Texels::random(texel_format(PixelFormat::R8Unorm).0, 1, 1, 0); - let refs = [0.5f32, 0.0, 1.0, -0.25, f32::NAN, 0.75]; - for (f, array) in [(1, false), (4, false), (6, false), (1, true)] { - let name = format!("cube compare {f} array={array}"); - let words = edge() & !(0xf << 16) | f << 16; - let Some(bc) = assemble(&name, &compare_kernel(words, array)) else { - return; - }; - let a = compile(&bc, "k", &p).unwrap_or_else(|e| panic!("{name}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name}: {e}")); - let (plan, m) = typed_module_with(&bc, "k", &p, &inputs(false)) - .unwrap_or_else(|e| panic!("{name}: {e}")); - let cubes = if array { 2 } else { 1 }; - for (seed, pf) in DEPTHS.iter().enumerate() { - let class = texel_format(*pf).0; - let d16 = *pf == PixelFormat::Depth16Unorm; - for n in [1u32, 3] { - let mut rng = Rng(0x00c0_c0de_0000 + seed as u64 * 64 + u64::from(n) + f * 4096); - let layers = 6 * cubes; - let tex = Texels::random(class, i64::from(n), i64::from(n * layers), rng.next()); - let stored = |l: u32, i: i64, j: i64| -> Stored { - tex.t[((i64::from(l * n) + j) * i64::from(n) + i) as usize][0] - }; - let imgs = images(&m, (n, layers), false, &|l, i, j| { - let v = tex.fetched(stored(l, i64::from(i), i64::from(j))); - [v.to_bits(), 0, 0, 1f32.to_bits()] - }); - let lanes: Vec<[u32; 4]> = directions(n, 96, 0, &mut rng) - .into_iter() - .enumerate() - .map(|(k, d)| { - let r = match k % 3 { - 0 => tex.fetched(tex.t[(7 * k) % tex.t.len()][0]), - _ => refs[k % refs.len()], - }; - [d[0], d[1], d[2], r.to_bits()] - }) - .collect(); - let out = run(&m, &resources(&plan, &lanes, 16, class), &imgs, false); - let mut corners = 0; - for (lane, (d, got)) in lanes.iter().zip(&out).enumerate() { - let dir = [d[0], d[1], d[2]].map(f32::from_bits); - let fp = footprint(dir, n, (false, false)); - let base = if array { 6 } else { 0 }; - let at = |g: usize, i: i64, j: i64| stored(base + g as u32, i, j); - corners += usize::from(fp.iter().any(|(w, t)| *w > 0 && t.len() == 3)); - let fetched = |s: Stored| tex.fetched(s); - let r = f32::from_bits(d[3]); - let want = compared(&fp, &at, (&fetched, d16), (f, r), &r8); - assert_eq!( - got[0], - want, - "{name} {pf:?} n={n} lane {lane} {dir:?} reference {r}: {:?} vs {:?}", - f32::from_bits(got[0]), - f32::from_bits(want) - ); - } - assert!(corners > 0, "{name} {pf:?} n={n}: no lane reads a corner"); - } - } - } -} - -/// Our probe's 5x5 pattern cube (faces in order, rows of five): each texel's depth 0 or -/// 1 (`Depth32Float`), or code 0 or 65535 (`Depth16Unorm`). -const PX5_PATTERN: &str = "000010111100010001001100011010010101001011001011101000010000001011111111001000101000000010000111100101100000111111001101111011101011001101101110111001"; - -/// Lanes of our probe's `cc` run (Apple M4, macOS 27.0.1): the lane, its direction's -/// bits, and Metal's `less` comparison against 0.5 of [`PX5_PATTERN`] as `Depth32Float` and as -/// `Depth16Unorm`. The first ten differ between the formats (284 of 3,072 lanes do, all at the -/// corner tap); the rest read the same value from both. -const PX5_LANES: [(u32, [u32; 3], [u32; 2]); 16] = [ - ( - 65, - [0x4065_694a, 0xc071_6dc6, 0xc052_fc0a], - [0x3f20_0000, 0x3f31_a1a2], - ), - ( - 94, - [0xc04d_bb16, 0xc050_13c2, 0xc06c_e404], - [0x3f54_0404, 0x3f5c_9c9d], - ), - ( - 119, - [0xc025_c94a, 0xc031_0dbe, 0xc013_0704], - [0x3f28_f8f9, 0x3f2f_6f6f], - ), - ( - 175, - [0x4035_b662, 0xc058_b412, 0xc044_ebdc], - [0x3f67_0707, 0x3f6d_ddde], - ), - ( - 198, - [0x4006_6fcc, 0xc007_cfc0, 0xc022_861a], - [0x3f6e_feff, 0x3f70_8081], - ), - ( - 212, - [0xc04f_09b2, 0xc065_6868, 0xc073_9272], - [0x3f60_0000, 0x3f6b_5b5b], - ), - ( - 2051, - [0x4053_0af7, 0xc05c_411d, 0xc072_160e], - [0x3f52_0202, 0x3f5e_8e8f], - ), - ( - 2054, - [0xbfaa_f637, 0xbfb4_f003, 0xbfb6_2560], - [0x3f27_0707, 0x3f52_2222], - ), - ( - 2056, - [0xc034_b744, 0xc054_702c, 0xc038_494b], - [0x3f60_0000, 0x3f65_6565], - ), - ( - 2060, - [0xbf9d_b6d7, 0xbf97_bc33, 0xbfb4_5647], - [0x3f50_0000, 0x3f54_e4e5], - ), - ( - 0, - [0x3f9a_0f34, 0x3f1a_6150, 0x3ded_9d80], - [0x3f3e_feff, 0x3f3e_feff], - ), - ( - 1, - [0x404c_3ebc, 0x403a_4578, 0x404d_673e], - [0x3e0c_4c4c, 0x3e0c_4c4c], - ), - ( - 4, - [0x4072_fb9a, 0xbfe3_f9f0, 0xbfc1_f110], - [0x3b50_d0d1, 0x3b50_d0d1], - ), - ( - 5, - [0xc071_289c, 0x3fe4_afb4, 0x4017_adfe], - [0x3ed9_f9fa, 0x3ed9_f9fa], - ), - ( - 6, - [0x3e9d_fe30, 0xc071_da30, 0xbffd_17fc], - [0x3e0f_cfd0, 0x3e0f_cfd0], - ), - ( - 7, - [0xc015_c014, 0xc02b_cc7a, 0xbe5d_9e80], - [0x3e37_f7f8, 0x3e37_f7f8], - ), -]; - -/// The emulation answers [`PX5_LANES`] as Metal did, bit for bit, on both formats: the -/// `Depth16Unorm` corner's made-up code, compared as a texel, is what tells the formats apart. -#[test] -fn a_cube_comparison_answers_metals_px5_lanes() { - let p = lavapipe(); - let name = "px5 cube compare"; - let words = edge() & !(0xf << 16) | 1 << 16; - let Some(bc) = assemble(name, &compare_kernel(words, false)) else { - return; - }; - let (plan, m) = - typed_module_with(&bc, "k", &p, &inputs(false)).unwrap_or_else(|e| panic!("{name}: {e}")); - let pattern: Vec = PX5_PATTERN - .bytes() - .map(|b| f32::from(u8::from(b == b'1'))) - .collect(); - assert_eq!(pattern.len(), 150); - let imgs = images(&m, (5, 6), false, &|l, i, j| { - let v = pattern[(l * 25 + j * 5 + i) as usize]; - [v.to_bits(), 0, 0, 1f32.to_bits()] - }); - let lanes: Vec<[u32; 4]> = PX5_LANES - .iter() - .map(|(_, d, _)| [d[0], d[1], d[2], 0.5f32.to_bits()]) - .collect(); - for (k, pf) in DEPTHS.iter().enumerate() { - let class = texel_format(*pf).0; - let out = run(&m, &resources(&plan, &lanes, 16, class), &imgs, false); - for ((lane, _, metal), got) in PX5_LANES.iter().zip(&out) { - assert_eq!( - got[0], - metal[k], - "{pf:?} lane {lane}: {:?} vs Metal's {:?}", - f32::from_bits(got[0]), - f32::from_bits(metal[k]) - ); - } - } -} - -// ---- Metal's own lanes -------------------------------------------------------------------------- - -/// The directions (bits) of seven lanes of our probe's `cl` run on 1x1 cubes, by their -/// index in `lanes-cube-1.bin`: six with a major of `±1`, one on each face, and one scaled. -const PROBE_LANES: [(u32, [u32; 3]); 7] = [ - (0, [0xbf16_af84, 0xbf7e_fffe, 0x3f80_0000]), - (1, [0x3e73_662d, 0xbf80_0000, 0xbf35_0001]), - (2, [0x3f80_0000, 0x3eaa_8d6b, 0x3df8_0000]), - (4, [0xbde7_ffff, 0x3da3_0c36, 0xbf80_0000]), - (6, [0xbf0b_0000, 0x3f80_0000, 0xbe74_0002]), - (11, [0xbf80_0000, 0x3f70_ffff, 0xbed5_fffe]), - (2048, [0xbfa5_864c, 0xbf8d_f4ca, 0x3fbf_0898]), -]; - -/// One format's run of the probe on a 1x1 cube: the six faces' texel bytes as uploaded -/// (`tex--cube-1.bin`, face after face), and Metal's `float` and `half` samples' bits at -/// [`PROBE_LANES`] (`out--cube-1.bin`), Apple M4 and M3 Max alike. -struct Probe { - format: PixelFormat, - texels: &'static [u8], - float: [[u32; 4]; 7], - half: [[u16; 4]; 7], -} - -fn probes() -> Vec { - vec![ - Probe { - format: PixelFormat::RGBA8Unorm, - texels: &[ - 0x02, 0xf8, 0xe9, 0xfe, 0x2d, 0xf8, 0x7b, 0x44, 0x5d, 0xd3, 0x41, 0x81, 0x38, 0xc0, - 0x55, 0x88, 0x42, 0x8b, 0x2d, 0xbc, 0x51, 0x51, 0x22, 0x64, - ], - float: [ - [0x3e68_2828, 0x3f36_a6a7, 0x3e99_d9da, 0x3f0f_bfc0], - [0x3e6d_edee, 0x3f21_7171, 0x3ea4_4444, 0x3f07_8788], - [0x3da0_a0a1, 0x3f6d_4d4d, 0x3f44_f4f5, 0x3f67_5757], - [0x3e9f_5f5f, 0x3ebf_9fa0, 0x3e21_a1a2, 0x3ec7_4747], - [0x3ea0_6060, 0x3f50_a0a1, 0x3e99_999a, 0x3ede_dedf], - [0x3e8b_2b2b, 0x3f52_8283, 0x3eaf_0f0f, 0x3ec2_c2c3], - [0x3e62_6262, 0x3f3d_cdce, 0x3ea3_8384, 0x3f07_1717], - ], - half: [ - [0x3341, 0x39b5, 0x34cf, 0x387e], - [0x336f, 0x390c, 0x3522, 0x383c], - [0x2d05, 0x3b6a, 0x3a28, 0x3b3b], - [0x34fb, 0x35fd, 0x310d, 0x363a], - [0x3503, 0x3a85, 0x34cd, 0x36f7], - [0x3459, 0x3a94, 0x3578, 0x3616], - [0x3313, 0x39ee, 0x351c, 0x3839], - ], - }, - Probe { - format: PixelFormat::RGBA8Snorm, - texels: &[ - 0x89, 0x91, 0x79, 0xb3, 0xb6, 0x62, 0xb5, 0x63, 0x04, 0x3a, 0x5b, 0x4b, 0xae, 0x42, - 0x3c, 0x78, 0xfe, 0xc9, 0xea, 0x79, 0x62, 0x12, 0x2c, 0xc2, - ], - float: [ - [0xbec2_850a, 0x3e40_0000, 0xbac1_8306, 0x3f69_f3e8], - [0xbe56_2c59, 0x3e89_d3a7, 0x3ef3_264d, 0x3eab_972e], - [0xbf3b_b76f, 0xbf23_060c, 0x3f5b_366d, 0xbeaa_54a9], - [0x3f2a_952a, 0x3e42_0408, 0x3e9c_f9f4, 0xbec0_4081], - [0xbd51_a347, 0x3f01_62c6, 0x3eb5_ab57, 0x3f08_f1e4], - [0xbe15_2a55, 0x3f0e_9d3a, 0x3d88_1020, 0x3f06_8d1a], - [0xbebc_b973, 0x3e5d_3a75, 0xbe13_264d, 0x3f64_68d2], - ], - half: [ - [0xb614, 0x3200, 0x960c, 0x3b50], - [0xb2b1, 0x344f, 0x3799, 0x355d], - [0xb9de, 0xb918, 0x3ada, 0xb553], - [0x3955, 0x3210, 0x34e8, 0xb602], - [0xaa8d, 0x380b, 0x35ad, 0x3848], - [0xb0a9, 0x3875, 0x2c41, 0x3834], - [0xb5e6, 0x32ea, 0xb099, 0x3b23], - ], - }, - Probe { - format: PixelFormat::R8Unorm, - texels: &[0x48, 0x6b, 0xb4, 0xfe, 0x7a, 0xda], - float: [ - [0x3f2b_fbfc, 0, 0, 0x3f80_0000], - [0x3f62_9293, 0, 0, 0x3f80_0000], - [0x3eb8_b8b9, 0, 0, 0x3f80_0000], - [0x3f53_1313, 0, 0, 0x3f80_0000], - [0x3f26_1616, 0, 0, 0x3f80_0000], - [0x3f18_9899, 0, 0, 0x3f80_0000], - [0x3f18_0808, 0, 0, 0x3f80_0000], - ], - half: [ - [0x3960, 0, 0, 0x3c00], - [0x3b15, 0, 0, 0x3c00], - [0x35c6, 0, 0, 0x3c00], - [0x3a99, 0, 0, 0x3c00], - [0x3931, 0, 0, 0x3c00], - [0x38c5, 0, 0, 0x3c00], - [0x38c0, 0, 0, 0x3c00], - ], - }, - Probe { - format: PixelFormat::RGBA8UnormSRGB, - texels: &[ - 0x2b, 0xc5, 0xb0, 0xcc, 0x2e, 0x51, 0xba, 0xab, 0xe6, 0x08, 0x6b, 0xb8, 0x90, 0xed, - 0xc1, 0xdf, 0xa2, 0xf2, 0x41, 0x7e, 0x1f, 0xb9, 0xf7, 0xc2, - ], - float: [ - [0x3e85_c85d, 0x3f35_7b58, 0x3ea9_ca9d, 0x3f2e_2e2e], - [0x3e2d_0ad1, 0x3f33_cb3d, 0x3f27_6a77, 0x3f54_a4a5], - [0x3e29_4a95, 0x3ef8_af8b, 0x3ebc_6bc7, 0x3f45_8586], - [0x3d33_0b31, 0x3ee3_6e37, 0x3f60_2e03, 0x3f41_1111], - [0x3f06_b86c, 0x3d8c_08c1, 0x3e9d_89d9, 0x3f36_6666], - [0x3eaa_4aa5, 0x3dda_8da9, 0x3ed4_2d43, 0x3f34_2424], - [0x3e6a_0ea1, 0x3f1b_e9bf, 0x3ea5_ca5d, 0x3f26_e6e7], - ], - half: [ - [0x342e, 0x39ac, 0x354e, 0x3971], - [0x3168, 0x399e, 0x393b, 0x3aa5], - [0x314a, 0x37c5, 0x35e3, 0x3a2c], - [0x2998, 0x371b, 0x3b01, 0x3a09], - [0x3836, 0x2c60, 0x34ec, 0x39b3], - [0x3552, 0x2ed4, 0x36a1, 0x39a1], - [0x3350, 0x38df, 0x352e, 0x3937], - ], - }, - Probe { - format: PixelFormat::RGBA16Unorm, - texels: &[ - 0xed, 0x82, 0xfa, 0x74, 0xc9, 0xf9, 0x61, 0x63, 0x2d, 0x6c, 0x36, 0xfa, 0x9c, 0xe7, - 0xe8, 0x5e, 0x82, 0x86, 0xb6, 0xbb, 0x59, 0x7b, 0x28, 0x60, 0x59, 0x42, 0x94, 0x71, - 0x69, 0xbe, 0x18, 0x65, 0x41, 0xf1, 0x69, 0x7d, 0x53, 0x28, 0x4a, 0x7a, 0x14, 0x77, - 0x0d, 0xe8, 0x08, 0xf5, 0x62, 0x03, - ], - float: [ - [0x3f11_1091, 0x3f11_f392, 0x3f0a_738a, 0x3ed8_b6d9], - [0x3eb2_f0b3, 0x3f18_9c99, 0x3f55_add6, 0x3e8a_028a], - [0x3f09_3989, 0x3f00_d181, 0x3f5a_8cdb, 0x3ec8_18c8], - [0x3eee_12ee, 0x3f67_6de7, 0x3f6f_b4f0, 0x3d41_80c2], - [0x3efc_eafd, 0x3f4f_8ed0, 0x3f22_02a2, 0x3ead_faae], - [0x3ef0_96f1, 0x3f5e_89df, 0x3f3d_f8be, 0x3ea5_22a5], - [0x3f17_6097, 0x3f23_e4a4, 0x3f0f_1f8f, 0x3ed7_4cd7], - ], - half: [ - [0x3889, 0x3890, 0x3854, 0x36c6], - [0x3598, 0x38c5, 0x3aad, 0x3450], - [0x384a, 0x3807, 0x3ad4, 0x3641], - [0x3771, 0x3b3b, 0x3b7e, 0x2a0c], - [0x37e7, 0x3a7c, 0x3910, 0x3570], - [0x3785, 0x3af4, 0x39f0, 0x3529], - [0x38bb, 0x391f, 0x3879, 0x36ba], - ], - }, - Probe { - format: PixelFormat::RGBA16Snorm, - texels: &[ - 0x0a, 0xb8, 0x15, 0xab, 0xff, 0x7f, 0x1a, 0x84, 0x0c, 0xa7, 0x7c, 0x8f, 0x78, 0xad, - 0xff, 0x7f, 0x5d, 0x8a, 0xff, 0x7f, 0xe1, 0xb5, 0x01, 0x80, 0x0b, 0x57, 0xda, 0x70, - 0x25, 0x0b, 0xaf, 0xfc, 0xff, 0x7f, 0xdf, 0xeb, 0x00, 0x80, 0x01, 0x80, 0x01, 0x80, - 0x01, 0x80, 0xa2, 0x78, 0x00, 0x80, - ], - float: [ - [0x3f07_d710, 0x3dde_11bc, 0xbefe_bdfd, 0xbe56_d9ae], - [0x3c91_4123, 0x3e00_e102, 0x3ee6_51cd, 0xbedc_3db8], - [0xbf09_ed14, 0xbebc_f57a, 0x3f24_4d49, 0xbf79_8bf3], - [0xbf7a_c1f6, 0xbf6b_09d6, 0x3f4b_7197, 0xbf62_bbc5], - [0xbf5e_edbe, 0x3ead_e95c, 0xbee6_85cd, 0xbf00_1b00], - [0xbf53_efa8, 0xbe0f_f920, 0xbeca_9595, 0xbdad_715b], - [0x3eb4_5169, 0xbe02_1104, 0xbf19_3b32, 0xbda4_4149], - ], - half: [ - [0x383f, 0x2ef1, 0xb7f6, 0xb2b7], - [0x248a, 0x3007, 0x3733, 0xb6e2], - [0xb84f, 0xb5e8, 0x3922, 0xbbcc], - [0xbbd6, 0xbb58, 0x3a5c, 0xbb16], - [0xbaf7, 0x356f, 0xb734, 0xb801], - [0xba9f, 0xb080, 0xb655, 0xad6c], - [0x35a3, 0xb011, 0xb8ca, 0xad22], - ], - }, - Probe { - format: PixelFormat::RGBA16Float, - texels: &[ - 0xcb, 0x61, 0x5f, 0x2d, 0xd6, 0x6f, 0xdb, 0xbf, 0x2e, 0x35, 0xf8, 0xa3, 0xd9, 0x03, - 0x53, 0xc7, 0x88, 0x44, 0xe3, 0x2a, 0x0b, 0xc4, 0xfe, 0x51, 0xca, 0xb1, 0xa2, 0xba, - 0xa4, 0xbf, 0x92, 0x0e, 0x29, 0x70, 0xc9, 0x80, 0xa3, 0x85, 0x89, 0x03, 0xfa, 0x6e, - 0xc4, 0xab, 0x42, 0x42, 0x3c, 0xa8, - ], - float: [ - [0x453d_c000, 0xbe97_4000, 0xbf2b_8000, 0xc009_6000], - [0x4511_8000, 0xbef6_4000, 0x446b_0000, 0xbe76_0000], - [0x447b_0000, 0x3d99_c000, 0x45c6_e000, 0x40c0_c000], - [0x45ca_0000, 0xbd5c_6000, 0x402b_a000, 0x3fa6_e000], - [0x4419_a000, 0x3ccf_6000, 0xc015_c000, 0x41e7_8000], - [0x4444_e000, 0x3bac_6000, 0xbf94_4000, 0x4160_4000], - [0x453d_c000, 0xbe39_6000, 0xbecd_a000, 0xc04b_4000], - ], - half: [ - [0x69ee, 0xb4ba, 0xb95c, 0xc04b], - [0x688c, 0xb7b2, 0x6358, 0xb3b0], - [0x63d8, 0x2cce, 0x6e37, 0x4606], - [0x6e50, 0xaae3, 0x415d, 0x3d37], - [0x60cd, 0x267b, 0xc0ae, 0x4f3c], - [0x6227, 0x1d63, 0xbca2, 0x4b02], - [0x69ee, 0xb1cb, 0xb66d, 0xc25a], - ], - }, - Probe { - format: PixelFormat::RGBA32Float, - texels: &[ - 0xfd, 0x2f, 0x42, 0x8f, 0xe0, 0xdd, 0x3e, 0xcc, 0xde, 0x9e, 0x7b, 0x48, 0x25, 0x9d, - 0x16, 0x3e, 0xd1, 0xd5, 0xcd, 0xb9, 0x81, 0xf4, 0xb9, 0x49, 0xd2, 0x03, 0x47, 0x4b, - 0xf3, 0xba, 0x33, 0x3f, 0x95, 0xb3, 0x23, 0xba, 0x29, 0xf2, 0xb5, 0xc6, 0xd7, 0x30, - 0x48, 0x36, 0x7d, 0x82, 0xe7, 0xb9, 0x8d, 0x8f, 0xfd, 0xb7, 0x68, 0xa4, 0x69, 0xc1, - 0x31, 0x05, 0x48, 0xc5, 0xc7, 0x13, 0xe7, 0x40, 0x6a, 0x13, 0xf7, 0x3a, 0xd4, 0xdd, - 0xb5, 0xb6, 0xa8, 0xac, 0x57, 0x3e, 0xa3, 0x7a, 0x2a, 0xba, 0x69, 0xd0, 0x6f, 0xc1, - 0x04, 0x00, 0x1f, 0xb9, 0xe6, 0xcd, 0xee, 0x64, 0xa0, 0xb7, 0xb7, 0xb9, - ], - float: [ - [0x3a0f_1fca, 0x48d9_e9e3, 0x4a69_26f0, 0x402f_405f], - [0xc096_8386, 0xcab2_f013, 0x6415_e122, 0x4084_07f4], - [0xb6e5_bbfc, 0xcc17_64fe, 0x4847_90cf, 0x3dee_b3c2], - [0xc158_f1c3, 0x47ac_a902, 0x64d8_07b7, 0x3d27_21d8], - [0xbfa4_4b13, 0x48c1_2650, 0x6323_8961, 0x3e41_730b], - [0xbfd3_1067, 0x493e_a6cb, 0x6352_1eab, 0x3eba_355b], - [0x3a01_bc2a, 0x4921_41d7, 0x4aac_900f, 0x3fe9_3735], - ], - half: [ - [0x1078, 0x7bff, 0x7bff, 0x417a], - [0xc4b4, 0xfbff, 0x7bff, 0x4420], - [0x8072, 0xfbff, 0x7bff, 0x2f75], - [0xcac7, 0x7bff, 0x7bff, 0x2939], - [0xbd22, 0x7bff, 0x7bff, 0x320b], - [0xbe98, 0x7bff, 0x7bff, 0x35d1], - [0x100d, 0x7bff, 0x7bff, 0x3f49], - ], - }, - ] -} - -/// The `f32` value of `half` bits `h`, exactly. -fn half_value(h: u16) -> f32 { - let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 }; - let (e, m) = (i32::from(h >> 10 & 0x1f), f64::from(h & 0x3ff)); - let a = match e { - 0 => m * 2f64.powi(-24), - 31 if m == 0.0 => f64::INFINITY, - 31 => f64::NAN, - _ => (1024.0 + m) * 2f64.powi(e - 25), - }; - (sign * a) as f32 -} - -/// Texel `k`'s channels as a fetch of format `pf` reads its bytes `b` (`f32` bits; a raw view -/// reads an sRGB format's codes as UNORM): a code `c / scale` correctly rounded (`-1` for a signed -/// format's least code), a float as it is, a missing channel `0` (`1` for alpha). -fn fetched(pf: PixelFormat, b: &[u8], k: usize) -> [u32; 4] { - let unsigned = |c: u64, scale: u64| f32_bits(c, scale); - let signed = |c: i64, scale: i64| { - let c = c.max(-scale); - let m = f32::from_bits(f32_bits(c.unsigned_abs(), scale as u64)); - if c < 0 { -m } else { m }.to_bits() - }; - match pf { - PixelFormat::R8Unorm => [unsigned(u64::from(b[k]), 255), 0, 0, 1f32.to_bits()], - PixelFormat::RGBA8Unorm | PixelFormat::RGBA8UnormSRGB => { - std::array::from_fn(|c| unsigned(u64::from(b[4 * k + c]), 255)) - } - PixelFormat::RGBA8Snorm => { - std::array::from_fn(|c| signed(i64::from(b[4 * k + c] as i8), 127)) - } - PixelFormat::RGBA16Unorm | PixelFormat::RGBA16Snorm | PixelFormat::RGBA16Float => { - std::array::from_fn(|c| { - let h = u16::from_le_bytes([b[8 * k + 2 * c], b[8 * k + 2 * c + 1]]); - match pf { - PixelFormat::RGBA16Unorm => unsigned(u64::from(h), 65535), - PixelFormat::RGBA16Snorm => signed(i64::from(h as i16), 32767), - _ => half_value(h).to_bits(), - } - }) - } - PixelFormat::RGBA32Float => std::array::from_fn(|c| { - let at = 16 * k + 4 * c; - u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]) - }), - other => unreachable!("no probe of {other:?}"), - } -} - -/// The emulation answers Metal's own lanes of every format family, bit for bit, with `float` and -/// `half` results (`PROBE_LANES`, `probes`): an 8-bit sRGB format's through the raw view, under its -/// variant. -#[test] -fn a_cube_sample_answers_metals_probe_lanes() { - let p = lavapipe(); - let lanes: Vec<[u32; 4]> = PROBE_LANES - .iter() - .map(|(_, d)| [d[0], d[1], d[2], 0]) - .collect(); - for half in [false, true] { - let name = format!("probe half={half}"); - let Some(bc) = assemble(&name, &kernel(edge(), half, false)) else { - return; - }; - for probe in probes() { - let srgb = probe.format == PixelFormat::RGBA8UnormSRGB; - let (plan, m) = typed_module_with(&bc, "k", &p, &inputs(srgb)) - .unwrap_or_else(|e| panic!("{name}: {e}")); - let class = texel_format(probe.format).0; - let imgs = images(&m, (1, 6), srgb, &|l, _, _| { - fetched(probe.format, probe.texels, l as usize) - }); - let bytes = if half { 8 } else { 16 }; - let out = run(&m, &resources(&plan, &lanes, bytes, class), &imgs, half); - for (k, got) in out.iter().enumerate() { - let want = match half { - true => probe.half[k].map(u32::from), - false => probe.float[k], - }; - assert_eq!( - *got, want, - "{name} {:?} probe lane {}: {got:08x?} vs Metal's {want:08x?}", - probe.format, PROBE_LANES[k].0 - ); - } - } - } -} - -// ---- Selection, interface, and size ------------------------------------------------------------- - -/// Whether artifact `a` emulates its one sample (`sampler.linear` and the cube's routines). -fn emulated(a: &FunctionArtifact) -> bool { - let linear = a.strategies.entries.get("sampler.linear").map(|u| u.uses); - let routines = a.strategies.entries.contains_key("sampler.linear.cube"); - assert_eq!( - linear.is_some(), - routines, - "the census of {:?}", - a.strategies - ); - linear == Some(1) -} - -/// On lavapipe a linear cube sample through a constexpr sampler without a mip filter is emulated -/// whatever its address modes and border, a cube array's too, and records its filter note and -/// `CubeFaceReciprocal`, declaring the slot's 2D-array view of its faces beside its combined -/// binding; a linear mip filter or a nearest sampler keeps the device's sample. On MoltenVK nothing -/// is emulated, and every sample requires `VkProperty::MetalSampler`. -#[test] -fn the_cube_emulation_reaches_what_metal_measured() { - // (name, sampler, half, array, emulated on lavapipe, filtered) - let cases = [ - ("edge", edge(), true, false, true, true), - ("repeat", sampler_words(1, 0, 2, 0), true, false, true, true), - ("mirror", sampler_words(1, 0, 3, 0), true, false, true, true), - ("zero", sampler_words(1, 0, 0, 0), true, false, true, true), - ("white", sampler_words(1, 0, 0, 2), true, false, true, true), - ("array", edge(), true, true, true, true), - ("float", edge(), false, false, true, true), - ("float array", edge(), false, true, true, true), - ("mip", sampler_words(1, 2, 1, 0), true, false, false, true), - ( - "nearest", - sampler_words(0, 0, 1, 0), - true, - false, - false, - false, - ), - ]; - let (lvp, m3) = (lavapipe(), m3()); - for (name, words, half, array, reached, filtered) in cases { - let Some(bc) = assemble(name, &kernel(words, half, array)) else { - return; - }; - let note = match half { - true => PrecisionNote::HalfSampleFilter, - false => PrecisionNote::FloatSampleFilter, - }; - let faces = RuntimeFact::ImageViewShape { slot: TEXTURE }; - let a = compile(&bc, "k", &lvp).unwrap_or_else(|e| panic!("{name} on lavapipe: {e}")); - link_and_validate(&a, &lvp).unwrap_or_else(|e| panic!("{name} on lavapipe: {e}")); - assert_eq!(emulated(&a), reached, "{name} on lavapipe"); - assert_eq!(a.precision.contains(¬e), filtered, "{name} on lavapipe"); - let reciprocal = a.precision.contains(&PrecisionNote::CubeFaceReciprocal); - // A nearest cube sample is snapped onto Metal's texel, under the same note. - assert_eq!(reciprocal, reached || !filtered, "{name} on lavapipe"); - assert_eq!(a.facts.contains(&faces), reached, "{name} on lavapipe"); - assert!( - !a.requirements - .properties - .contains(&VkProperty::MetalSampler), - "{name} on lavapipe" - ); - let (_, m) = typed_module_with(&bc, "k", &lvp, &inputs(false)) - .unwrap_or_else(|e| panic!("{name} on lavapipe: {e}")); - let view = resource(&m, |k| *k == ResourceKind::Texture); - let combined = resource(&m, |k| matches!(k, ResourceKind::CombinedTextureSampler(_))); - assert_eq!(view.is_some(), reached, "{name}: the view of the faces"); - assert!(combined.is_some(), "{name}: the combined binding"); - let b = compile(&bc, "k", &m3).unwrap_or_else(|e| panic!("{name} on moltenvk-m3: {e}")); - link_and_validate(&b, &m3).unwrap_or_else(|e| panic!("{name} on moltenvk-m3: {e}")); - assert!(!emulated(&b), "{name} on moltenvk-m3"); - assert!(!b.precision.contains(¬e), "{name} on moltenvk-m3"); - assert!( - !b.precision.contains(&PrecisionNote::CubeFaceReciprocal), - "{name} on moltenvk-m3" - ); - assert!(!b.facts.contains(&faces), "{name} on moltenvk-m3"); - // A nearest one is Metal's own too, where lavapipe snaps it. - assert!( - b.requirements - .properties - .contains(&VkProperty::MetalSampler), - "{name} on moltenvk-m3" - ); - } -} - -/// A packed normalized format's cube sample is not measured, so its emulation is not reached there: -/// bound to a `B5G6R5Unorm` or `RGB10A2Unorm` cube, a linear cube sample's specialized pipeline on -/// lavapipe keeps its filter note, where an `RGBA8Unorm` or a small float one (the half-float -/// family's emulation) does not. -#[test] -fn a_packed_normalized_cube_keeps_the_devices_filter() { - use super::engine_linear_half::{device_of, notes_bound, notes_pipeline}; - use crate::metal::TextureType; - let Some(bc) = assemble("cube notes", &kernel(edge(), true, false)) else { - return; - }; - let lvp = device_of("lavapipe"); - let p = notes_pipeline(&lvp, &bc); - for (pf, noted) in [ - (PixelFormat::B5G6R5Unorm, true), - (PixelFormat::RGB10A2Unorm, true), - (PixelFormat::RGBA8Unorm, false), - (PixelFormat::RG11B10Float, false), - ] { - let notes = notes_bound(&p, &lvp, (TextureType::Cube, pf), None); - assert_eq!( - notes.contains(&PrecisionNote::HalfSampleFilter), - noted, - "{pf:?}: {notes:?}" - ); - } -} - -/// The plan's word estimate bounds the emitted module of every cube form (`half` and `float`, a -/// cube array, an sRGB variant's raw view, a repeating sampler's wrap), which validates, on every -/// committed profile. -#[test] -fn the_cube_estimate_bounds_its_emission() { - let mut modules = Vec::new(); - let repeat = sampler_words(1, 0, 2, 0); - for (name, words, half, array, srgb) in [ - ("half", edge(), true, false, false), - ("float", edge(), false, false, false), - ("half array", edge(), true, true, false), - ("float array", edge(), false, true, false), - ("raw half", edge(), true, false, true), - ("raw float array", edge(), false, true, true), - ("repeat half", repeat, true, false, false), - ("repeat raw float array", repeat, false, true, true), - ] { - let Some(bc) = assemble(name, &kernel(words, half, array)) else { - return; - }; - modules.push((name, bc, srgb)); - } - // Depth cubes' comparisons. - let less = edge() & !(0xf << 16) | 1 << 16; - for (name, array) in [("compare", false), ("compare array", true)] { - let Some(bc) = assemble(name, &compare_kernel(less, array)) else { - return; - }; - modules.push((name, bc, false)); - } - let consts = FunctionConstantValues::defaults(); - for (name, bc, srgb) in &modules { - for (stem, p) in committed_exact_profiles().expect("profiles") { - let what = format!("{name} on {stem}"); - // A profile without cube arrays refuses a cube array's sample, whose combined binding - // stays declared. - let cube_arrays = p - .fields() - .enabled - .features - .contains(&VkFeature::ImageCubeArray); - if name.contains("array") && !cube_arrays { - continue; - } - let inputs = inputs(*srgb); - let entry = EntryRef::Name("k"); - let plan = plan_bitcode(bc, entry, &consts, &p, &inputs, &mut meter()) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let a = compile_bitcode(bc, entry, &consts, &p, &inputs, &mut meter(), SPIRV_WORDS) - .unwrap_or_else(|e| panic!("{what}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: {e}")); - let words = a.module.words.len() as u64; - eprintln!("{what}: estimate {} emitted {words}", plan.estimate.words); - assert!( - plan.estimate.words >= words, - "{what}: estimate {} < emitted {words}", - plan.estimate.words - ); - } - } -} diff --git a/crates/metal2vulkan/src/tests/engine_linear_half.rs b/crates/metal2vulkan/src/tests/engine_linear_half.rs deleted file mode 100644 index 8f9818dfc..000000000 --- a/crates/metal2vulkan/src/tests/engine_linear_half.rs +++ /dev/null @@ -1,4899 +0,0 @@ -//! Metal's linear filter for a sample with a `half` or `float` result, emulated by fetches on a -//! device that does not sample through Metal's own sampler, run on the CPU interpreter against -//! Metal's rule itself, bit for bit, for an 8- or 16-bit normalized format and a 32-bit float or -//! half-float format, in 1D and 2D: the footprint's 1/256 fraction rounded half up, the taps' -//! weights `(256 - k)` and `k` per axis; the codes' exact sum rounded half up onto the format's -//! grid and then to nearest even, to `f32` or `half`; Metal's linear accumulator for a float format -//! (each term truncated toward zero onto a grid 38 bits, or 17 for a half-float format, below the -//! largest present term's tap and weight exponents, summed exactly), its sum rounded with ties away -//! from zero, a 32-bit float format's to `f32` (a denormal `+0`), and for a `half` result then -//! toward zero saturating, a half-float format's to `half` (a zero `+0`), widened for a `float` -//! result. -//! -//! A float texture's texels include `-0`, at the texel a centre sample reads alone among them. -//! -//! The selection tests pin which samples the emulation reaches, which the device filters under -//! the notes (`HalfSampleFilter`, and `FloatSampleFilter` for every filtered `float` sample, a -//! depth comparison's included), and that a device sampling through Metal's own sampler keeps -//! every one and requires `VkProperty::MetalSampler`. -//! -//! `llvm-as` assembles the kernels; without it the tests skip visibly. - -use std::collections::BTreeMap; -use std::sync::atomic::{AtomicU64, Ordering}; - -use crate::device::profile::DeviceProfile; -use crate::device::requirements::VkProperty; -use crate::device::DevicePolicy; -use crate::lower::select::Plan; -use crate::metal::bicubic::BicubicTexels; -use crate::metal::sampler::SamplerWord; -use crate::metal::texel_format::texel_format; -use crate::metal::{PixelFormat, SamplerAddressMode, SamplerBorderColor}; -use crate::pipeline::interface::PushLoc; -use crate::pipeline::sym::{ - Axis, PushField, ResourceKind, ResourceSlot, SlotClass, SlotRef, SpecKey, Stage, -}; -use crate::pipeline::testing::EXACT_SAMPLING; -use crate::pipeline::testing::{ - compile, link_and_validate, llvm_assemble, profile, typed_module, AssembleError, -}; -use crate::pipeline::PrecisionNote; -use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Order, Resources}; -use crate::spirv::ir::{GlobalKind, TypedModule}; - -mod in_place; -mod levels; -mod packed; -mod ycbcr; - -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"; - -/// Bitcode of the module `body` (after the AIR header), or `None` without `llvm-as`. -fn assemble(name: &str, body: &str) -> Option> { - static NEXT: AtomicU64 = AtomicU64::new(0); - let dir = std::env::temp_dir().join(format!( - "m2v-linear-half-{}-{}-{}", - std::process::id(), - NEXT.fetch_add(1, Ordering::Relaxed), - name.replace(' ', "-") - )); - std::fs::create_dir_all(&dir).expect("scratch"); - let ll = dir.join("k.ll"); - std::fs::write(&ll, format!("{HEADER}{body}")).expect("write"); - let r = llvm_assemble(&ll); - let _ = std::fs::remove_dir_all(&dir); - match r { - Ok(x) => Some(x), - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - None - } - Err(AssembleError::Rejected(why)) => panic!("{name}: {why}"), - } -} - -fn lavapipe() -> DeviceProfile { - profile("lavapipe", EXACT_SAMPLING).expect("profile") -} - -fn m3() -> DeviceProfile { - profile("moltenvk-m3", EXACT_SAMPLING).expect("profile") -} - -/// The words of `constexpr sampler(filter::linear, ...)`: minification and magnification -/// `filter` (AIR code: 0 nearest, 1 linear), mip filter `mip` (0 none, 2 linear), every axis -/// addressed by `address` (0 zero or border, 1 edge, 2 repeat, 3 mirrored repeat), `pixel` -/// coordinates, and border color code `border` (0 transparent black, 2 opaque white), with the -/// fields Apple's compiler writes for the rest (the `hlf_half_address` fixture's sampler). -fn sampler_words(filter: u64, mip: u64, address: u64, pixel: bool, border: u64) -> u64 { - const BASE: u64 = 0x007b_ff00_0008_0000; - BASE | address - | address << 3 - | address << 6 - | filter << 9 - | filter << 11 - | mip << 13 - | u64::from(pixel) << 15 - | border << 56 -} - -fn linear(address: u64, pixel: bool, border: u64) -> u64 { - sampler_words(1, 0, address, pixel, border) -} - -/// How a test kernel samples its `half` texture. -#[derive(Clone, Copy, Debug)] -enum Form { - /// `texture2d`: `t.sample(s, coord[tid], offset)` with constant `offset`. - Plain { offset: (i32, i32) }, - /// `texture2d_array`: layer `layer`. - Array { layer: i32 }, - /// `texture1d`: `coord[tid].x`. - OneD, - /// `texture2d` with `min_lod_clamp(1)`. - MinLodClamp, - /// `texture2d` with lane `tid`'s dynamic `int2` offset (buffer 2). - DynamicOffset, - /// `texture3d` at `float4` buffer 0's lane `tid`'s `xyz`, with constant `offset`. - ThreeD { offset: (i32, i32, i32) }, - /// `texture2d`: a `float` result. - Float, -} - -/// A kernel sampling texture slot 0 through sampler `sampler` (a constexpr sampler's words, or -/// `None` for the runtime `[[sampler(0)]]`) at `float2` buffer 0's lane `tid`, storing the -/// `half4` (`float4` for [`Form::Float`]) to buffer 1. -fn kernel(sampler: Option, form: Form) -> String { - kernel_of(sampler, form, matches!(form, Form::Float)) -} - -/// [`kernel`] with a `float` result when `float`, whatever the form. -fn kernel_of(sampler: Option, form: Form, float: bool) -> String { - let half = !float; - let (texel, vec4, size) = if half { - ("half", "<4 x half>", 8) - } else { - ("float", "<4 x float>", 16) - }; - let suffix = if half { "v4f16" } else { "v4f32" }; - let s = if sampler.is_some() { - "@__air_sampler_state" - } else { - "%s" - }; - let (tex_ty, name, args, call_args) = match form { - Form::Plain { offset: (ox, oy) } => ( - format!("texture2d<{texel}, sample>"), - "2d", - "ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32", - format!("<2 x float> %uv, i1 true, <2 x i32> , i1 false, float 0.0, float 0.0, i32 0"), - ), - Form::Float => ( - format!("texture2d<{texel}, sample>"), - "2d", - "ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32", - "<2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.0, float 0.0, i32 0".to_string(), - ), - Form::Array { layer } => ( - format!("texture2d_array<{texel}, sample>"), - "2d_array", - "ptr addrspace(1), ptr addrspace(2), <2 x float>, i32, i1, <2 x i32>, i1, float, float, i32", - format!("<2 x float> %uv, i32 {layer}, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.0, float 0.0, i32 0"), - ), - Form::OneD => ( - format!("texture1d<{texel}, sample>"), - "1d", - "ptr addrspace(1), ptr addrspace(2), float, i1, i32, i1, float, float, i32", - "float %u, i1 false, i32 0, i1 false, float 0.0, float 0.0, i32 0".to_string(), - ), - Form::MinLodClamp => ( - format!("texture2d<{texel}, sample>"), - "2d", - "ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32", - "<2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.0, float 1.0, i32 0".to_string(), - ), - Form::DynamicOffset => ( - format!("texture2d<{texel}, sample>"), - "2d", - "ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32", - "<2 x float> %uv, i1 true, <2 x i32> %o, i1 false, float 0.0, float 0.0, i32 0".to_string(), - ), - Form::ThreeD { offset: (ox, oy, oz) } => ( - format!("texture3d<{texel}, sample>"), - "3d", - "ptr addrspace(1), ptr addrspace(2), <3 x float>, i1, <3 x i32>, i1, float, float, i32", - format!("<3 x float> %uvw, i1 true, <3 x i32> , i1 false, float 0.0, float 0.0, i32 0"), - ), - }; - let dynamic = matches!(form, Form::DynamicOffset); - let runtime = sampler.is_none(); - // Parameters after `out`: the offsets buffer, then the runtime sampler. - let mut params = String::new(); - let mut mds = Vec::new(); - let mut next = 3; - if dynamic { - params.push_str(", ptr addrspace(1) %offs"); - mds.push(format!("!{{i32 {next}, !\"air.buffer\", !\"air.location_index\", i32 2, i32 1, !\"air.read\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 8, !\"air.arg_type_align_size\", i32 8, !\"air.arg_type_name\", !\"int2\", !\"air.arg_name\", !\"offs\"}}")); - next += 1; - } - if runtime { - params.push_str(", ptr addrspace(2) %s"); - mds.push(format!("!{{i32 {next}, !\"air.sampler\", !\"air.location_index\", i32 0, i32 1, !\"air.arg_type_name\", !\"sampler\", !\"air.arg_name\", !\"s\"}}")); - next += 1; - } - mds.push(format!("!{{i32 {next}, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"tid\"}}")); - let first = 7; - let arg_mds: Vec = (0..mds.len()).map(|i| format!("!{}", first + i)).collect(); - let tail: String = mds - .iter() - .enumerate() - .map(|(i, m)| format!("!{} = {m}\n", first + i)) - .collect(); - let load_offset = if dynamic { - " %po = getelementptr inbounds <2 x i32>, ptr addrspace(1) %offs, i64 %i\n %o = load <2 x i32>, ptr addrspace(1) %po, align 8\n" - } else { - "" - }; - let state = match sampler { - Some(w) => format!( - "@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 {w}, i64 0], align 8\n\n" - ), - None => String::new(), - }; - let (states, state_md) = if sampler.is_some() { - ( - "!air.sampler_states = !{!6}\n", - "!6 = !{!\"air.sampler_state\", ptr addrspace(2) @__air_sampler_state}\n", - ) - } else { - ("", "") - }; - let half_name = if half { "half4" } else { "float4" }; - // A 3D sample's coordinates are a `float4`'s `xyz`, every other's a `float2`. - let (load_coord, coord_size, coord_name) = if matches!(form, Form::ThreeD { .. }) { - ( - " %p = getelementptr inbounds <4 x float>, ptr addrspace(1) %c, i64 %i\n %c4 = load <4 x float>, ptr addrspace(1) %p, align 16\n %uvw = shufflevector <4 x float> %c4, <4 x float> zeroinitializer, <3 x i32> \n", - 16, - "float4", - ) - } else { - ( - " %p = getelementptr inbounds <2 x float>, ptr addrspace(1) %c, i64 %i\n %uv = load <2 x float>, ptr addrspace(1) %p, align 8\n %u = extractelement <2 x float> %uv, i64 0\n", - 8, - "float2", - ) - }; - format!( - r#"{state}define void @k(ptr addrspace(1) %t, ptr addrspace(1) %c, ptr addrspace(1) %out{params}, i32 %tid) {{ - %i = zext i32 %tid to i64 -{load_coord}{load_offset} %r = call {{ {vec4}, i8 }} @air.sample_texture_{name}.{suffix}(ptr addrspace(1) %t, ptr addrspace(2) {s}, {call_args}) - %v = extractvalue {{ {vec4}, i8 }} %r, 0 - %q = getelementptr inbounds {vec4}, ptr addrspace(1) %out, i64 %i - store {vec4} %v, ptr addrspace(1) %q, align {size} - ret void -}} - -declare {{ {vec4}, i8 }} @air.sample_texture_{name}.{suffix}({args}) - -!air.kernel = !{{!0}} -{states}!0 = !{{ptr @k, !1, !2}} -!1 = !{{}} -!2 = !{{!3, !4, !5, {arg_mds}}} -!3 = !{{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"{tex_ty}", !"air.arg_name", !"t"}} -!4 = !{{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 {coord_size}, !"air.arg_type_align_size", i32 {coord_size}, !"air.arg_type_name", !"{coord_name}", !"air.arg_name", !"c"}} -!5 = !{{i32 2, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 {size}, !"air.arg_type_align_size", i32 {size}, !"air.arg_type_name", !"{half_name}", !"air.arg_name", !"out"}} -{state_md}{tail}"#, - arg_mds = arg_mds.join(", "), - ) -} - -/// The combined image-sampler bindings a module declares, and whether each compares. -fn combined_slots(m: &TypedModule) -> Vec<(ResourceSlot, bool)> { - m.globals() - .iter() - .filter_map(|g| match g.kind { - GlobalKind::Resource( - s @ ResourceSlot { - kind: ResourceKind::CombinedTextureSampler(c), - .. - }, - ) => Some((s, c.compare)), - _ => None, - }) - .collect() -} - -/// The combined image-sampler binding a module declares for texture slot 0. -fn combined_slot(m: &TypedModule) -> ResourceSlot { - m.globals() - .iter() - .find_map(|g| match g.kind { - GlobalKind::Resource( - s @ ResourceSlot { - kind: ResourceKind::CombinedTextureSampler(_), - .. - }, - ) => Some(s), - _ => None, - }) - .expect("a combined binding") -} - -const TEXTURE: SlotRef = SlotRef { - stage: Stage::Kernel, - class: SlotClass::Texture, - index: 0, -}; - -/// Resources of a dispatch of one-thread threadgroups: `[[buffer(i)]]` holding `init[i]`, and -/// the texture slot's `TexelFormat` specialization `class`. -fn resources(plan: &Plan, init: &[Vec], class: u32) -> Resources { - let mut spec = BTreeMap::new(); - for axis in [Axis::X, Axis::Y, Axis::Z] { - spec.insert(SpecKey::LocalSize(axis), 1); - } - spec.insert(SpecKey::FlatLocalSize, 1); - spec.insert(SpecKey::TexelFormat(TEXTURE), u64::from(class)); - spec.insert( - SpecKey::PlainHalfTexels(TEXTURE), - u64::from(crate::metal::texel_format::TexelFormat(class).plain_on_metal_sampler()), - ); - let push = vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)]; - for f in &plan.push.fields { - match (f.field, f.loc) { - (PushField::SlotBindOffset(_) | PushField::DispatchRegion, PushLoc::Push { .. }) => {} - // A bound value read as data, which the interpreter writes from `spec`. - (PushField::Specialized(_), PushLoc::Push { .. }) => {} - // No slot's writes dropped: the word stays 0. - (PushField::Specialized(crate::pipeline::sym::SpecKey::DroppedStoreSlots(_)), _) => {} - other => panic!("unexpected push field {other:?}"), - } - } - let buffers = init - .iter() - .enumerate() - .map(|(i, b)| Buffer { - slot: Some(ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: i as u32, - }), - address: None, - bytes: b.clone(), - }) - .collect(); - Resources { - buffers, - push, - spec, - } -} - -/// `res` with each `SamplerState` specialization artifact `a` declares valued by runtime sampler -/// word `word`, masked by its fields; unchanged without a word. -fn with_word( - mut res: Resources, - a: &crate::library::FunctionArtifact, - word: Option, -) -> Resources { - let Some(word) = word else { - return res; - }; - let mut declared = 0; - for key in a.interface.read_keys() { - if let SpecKey::SamplerState { fields, .. } = key { - res.spec.insert(key, u64::from(word & fields)); - declared += 1; - } - } - assert_eq!( - declared, 1, - "the runtime sampler's `SamplerState` specialization" - ); - res -} - -/// The word of a runtime sampler with linear minification and magnification, no mip filter, address -/// mode `mode` on every axis, pixel coordinates when `pixel`, and border color `border`. -fn runtime_word(mode: SamplerAddressMode, pixel: bool, border: SamplerBorderColor) -> u32 { - let mut w = SamplerWord::LINEAR | (border.as_raw() << SamplerWord::BORDER_SHIFT); - if pixel { - w |= SamplerWord::PIXEL_COORDINATES; - } - for shift in SamplerWord::ADDRESS_SHIFT { - w |= mode.as_raw() << shift; - } - w -} - -/// `m` over `groups` one-thread threadgroups with `image` bound, in both scheduling orders, which -/// must agree: buffer 1's `half4`s (`float4`s unless `half`), as bits. -fn run(m: &TypedModule, res: &Resources, image: &Image, groups: u32, half: bool) -> Vec<[u32; 4]> { - run_images(m, res, std::slice::from_ref(image), groups, half) -} - -/// [`run`] with `images` bound. -fn run_images( - m: &TypedModule, - res: &Resources, - images: &[Image], - groups: u32, - half: bool, -) -> Vec<[u32; 4]> { - let mut outs = Vec::new(); - for order in [Order::Forward, Order::Reverse] { - let cfg = Config { - workgroups: [groups, 1, 1], - order, - ..Config::default() - }; - let (o, _) = run_with_images(m, &cfg, res.clone(), images.to_vec()) - .unwrap_or_else(|e| panic!("interpreter: {e:?}")); - outs.push(o.buffers); - } - assert_eq!(outs[0], outs[1], "the scheduling orders disagree"); - let size = if half { 2 } else { 4 }; - outs[0][1] - .chunks_exact(4 * size) - .map(|c| { - std::array::from_fn(|k| { - let mut b = [0u8; 4]; - b[..size].copy_from_slice(&c[size * k..size * (k + 1)]); - u32::from_le_bytes(b) - }) - }) - .collect() -} - -/// A deterministic source: a 64-bit LCG. -struct Lcg(u64); - -impl Lcg { - fn next(&mut self) -> u64 { - self.0 = self - .0 - .wrapping_mul(6_364_136_223_846_793_005) - .wrapping_add(1_442_695_040_888_963_407); - self.0 >> 11 - } -} - -/// The family of a format's treatment. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Family { - /// A normalized format: its code scale `2^b - 1` (`2^(b-1) - 1` signed), signedness, and grid - /// factor (16 for 8 bits, else 1). - Norm { - scale: i64, - signed: bool, - g: i64, - }, - Float32, - Float16, -} - -fn family(class: u32) -> Family { - let has = |b: u32| class & b != 0; - if has(BicubicTexels::LINEAR) { - return Family::Float32; - } - if has(BicubicTexels::HALF) { - return Family::Float16; - } - assert!(has(BicubicTexels::EXACT), "a measured class"); - let signed = has(BicubicTexels::SNORM); - let wide = has(BicubicTexels::WIDE16); - let scale = match (wide, signed) { - (false, false) => 255, - (false, true) => 127, - (true, false) => 65535, - (true, true) => 32767, - }; - Family::Norm { - scale, - signed, - g: if wide { 1 } else { 16 }, - } -} - -/// A texel as the bound format stores it, per channel: a normalized code, or a float value (a -/// half-float format's a `half`). -#[derive(Clone, Copy, Debug)] -pub(super) enum Stored { - Code(i64), - Value(f32), -} - -/// A texture's stored texels (one layer, `w` by `h`), with the format's missing channels as a -/// fetch reads them (0 for red, green, blue; 1 for alpha). -pub(super) struct Texels { - class: u32, - w: i64, - h: i64, - pub(super) t: Vec<[Stored; 4]>, -} - -impl Texels { - pub(super) fn random(class: u32, w: i64, h: i64, seed: u64) -> Texels { - let mut rng = Lcg(seed); - let fam = family(class); - let present = |c: u32| class & (1 << (BicubicTexels::PRESENT + c)) != 0; - let t = (0..w * h) - .map(|_| { - std::array::from_fn(|c| { - let missing = if c == 3 { 1.0 } else { 0.0 }; - match fam { - Family::Norm { scale, signed, .. } if present(c as u32) => { - let lo = if signed { -scale - 1 } else { 0 }; - Stored::Code(lo + (rng.next() % (scale - lo + 1) as u64) as i64) - } - Family::Norm { scale, .. } => Stored::Code(if c == 3 { scale } else { 0 }), - // Values with at most 12 significant bits in `[-2, 2)` (one in eight - // scaled by `2^-10`, one in sixteen `-0`), so every reference sum below - // is exact in `f64`. - Family::Float32 | Family::Float16 if present(c as u32) => { - let m = (rng.next() % 4096) as f64 - 2048.0; - let e = if rng.next() & 7 == 0 { -20 } else { -10 }; - if rng.next() & 15 == 0 { - Stored::Value(-0.0) - } else { - Stored::Value((m * 2f64.powi(e)) as f32) - } - } - _ => Stored::Value(missing), - } - }) - }) - .collect::>(); - // `-0` in the first three texels of rows 0 and 2 (a layer reads the texel as many places - // on), which the samples at `(0.5, 2.5)` and `0.5` read alone (`coordinates`). - let mut t = t; - if matches!(fam, Family::Float32 | Family::Float16) { - for row in [0, 2.min(h - 1)] { - for x in 0..3 { - for (c, v) in t[(row * w + x) as usize].iter_mut().enumerate() { - if present(c as u32) { - *v = Stored::Value(-0.0); - } - } - } - } - } - Texels { class, w, h, t } - } - - /// A stored channel's value as the device fetches it: `c / scale` correctly rounded to - /// `f32` (`-1` for the least signed code), or the float itself. - pub(super) fn fetched(&self, s: Stored) -> f32 { - match (s, family(self.class)) { - (Stored::Code(c), Family::Norm { scale, .. }) => { - (c.max(-scale) as f64 / scale as f64) as f32 - } - (Stored::Value(v), _) => v, - (Stored::Code(_), _) => unreachable!("a code of a float format"), - } - } - - /// The interpreter image of these texels in slot `slot`, as `layers` copies (layer `k`'s - /// codes or values replaced by layer 0's of the texel `k` places on, so a wrong layer shows). - fn image(&self, slot: ResourceSlot, dims: u32, layers: u32) -> Image { - let h = if dims == 1 { 1 } else { self.h as u32 }; - let mut image = Image::new(slot, [self.w as u32, h, 1], layers, 1, 1); - for l in 0..layers { - for y in 0..h { - for x in 0..self.w as u32 { - let at = image.index(0, l, 0, [x, y, 0]).expect("texel"); - let v = self.texel(l, x as i64, y as i64); - image.texels[at] = v.map(|c| self.fetched(c).to_bits()); - } - } - } - image - } - - /// Layer `l`'s stored texel at `(x, y)` within the level. - fn texel(&self, l: u32, x: i64, y: i64) -> [Stored; 4] { - let n = self.w * self.h; - self.t[((y * self.w + x + i64::from(l)) % n) as usize] - } -} - -/// How a tap outside the level is addressed. -#[derive(Clone, Copy, Debug)] -enum Address { - Edge, - Repeat, - Mirror, - /// The border color's channels. - Border([f64; 4]), -} - -/// A tap's channel value: a stored channel, or the border's. -#[derive(Clone, Copy, Debug)] -pub(super) enum Tap { - Stored(Stored), - Border(f64), -} - -/// The tap of layer `l` at `(i, j)` (`j` 0 for a 1D texture), channel `c`, under `address`. -fn tap(tex: &Texels, address: Address, l: u32, (i, j): (i64, i64), c: usize) -> Tap { - let mirror = |v: i64, n: i64| { - let m = if v >= 0 { v } else { -1 - v }; - let r = m % (2 * n); - if r < n { - r - } else { - 2 * n - 1 - r - } - }; - let fix = |v: i64, n: i64| match address { - Address::Edge | Address::Border(_) => v.clamp(0, n - 1), - Address::Repeat => v.rem_euclid(n), - Address::Mirror => mirror(v, n), - }; - if let Address::Border(b) = address { - if i < 0 || i >= tex.w || j < 0 || j >= tex.h { - let present = tex.class & (1 << (BicubicTexels::PRESENT + c as u32)) != 0; - let missing = if c == 3 { 1.0 } else { 0.0 }; - return Tap::Border(if present { b[c] } else { missing }); - } - } - Tap::Stored(tex.texel(l, fix(i, tex.w), fix(j, tex.h))[c]) -} - -/// Metal's split of axis coordinate `x` (texels): the base tap and the fraction's 1/256 steps. -fn split(x: f64) -> (i64, i64) { - let q = ((x - 0.5) * 256.0 + 0.5).floor() as i64; - (q >> 8, q & 255) -} - -/// The `half` bits of `v`, which must be a `half` value (or an infinity). -fn half_bits_of(v: f64) -> u16 { - let sign = if v.is_sign_negative() { 0x8000 } else { 0 }; - let a = v.abs(); - if a.is_infinite() { - return sign | 0x7C00; - } - if a < 2f64.powi(-14) { - let m = a / 2f64.powi(-24); - assert_eq!(m.fract(), 0.0, "{v} is no half"); - return sign | m as u16; - } - let e = a.log2().floor() as i32; - let e = if 2f64.powi(e) > a { e - 1 } else { e }; - let e = if 2f64.powi(e + 1) <= a { e + 1 } else { e }; - let m = a / 2f64.powi(e - 10); - assert_eq!(m.fract(), 0.0, "{v} is no half"); - sign | ((e + 15) as u16) << 10 | (m as u16 - 1024) -} - -/// The spacing of `half` values at magnitude `a`. -fn half_ulp(a: f64) -> f64 { - if a < 2f64.powi(-14) { - return 2f64.powi(-24); - } - let e = a.log2().floor() as i32; - let e = if 2f64.powi(e) > a { e - 1 } else { e }; - let e = if 2f64.powi(e + 1) <= a { e + 1 } else { e }; - 2f64.powi(e - 10) -} - -#[derive(Clone, Copy)] -pub(super) enum Rounding { - NearestEven, - NearestAway, - TowardZeroSaturating, -} - -/// The `half` bits of exact value `v` (exact in `f64`) rounded by `mode`. -pub(super) fn to_half(v: f64, mode: Rounding) -> u16 { - if v == 0.0 { - return if v.is_sign_negative() { 0x8000 } else { 0 }; - } - let a = v.abs(); - let q = half_ulp(a); - let n = a / q; - let (fl, fr) = (n.floor(), n - n.floor()); - let m = match mode { - Rounding::TowardZeroSaturating => fl, - Rounding::NearestAway => { - if fr >= 0.5 { - fl + 1.0 - } else { - fl - } - } - Rounding::NearestEven => { - if fr > 0.5 || (fr == 0.5 && fl % 2.0 == 1.0) { - fl + 1.0 - } else { - fl - } - } - }; - let r = m * q; - let r = match mode { - Rounding::TowardZeroSaturating => r.min(65504.0), - _ if r > 65504.0 => f64::INFINITY, - _ => r, - }; - half_bits_of(r.copysign(v)) -} - -/// `x` (exact in `f64`) rounded to `f32` with ties away from zero, a denormal result `+0`. -fn f32_away(x: f64) -> f32 { - let r = x as f32; - let d = x - f64::from(r); - let r = if d == 0.0 { - r - } else { - let other = if d > 0.0 { - f32::from_bits(if r >= 0.0 { - r.to_bits() + 1 - } else { - r.to_bits() - 1 - }) - } else { - f32::from_bits(if r > 0.0 { - r.to_bits() - 1 - } else { - r.to_bits() + 1 - }) - }; - if (f64::from(other) - x).abs() == d.abs() && other.abs() > r.abs() { - other - } else { - r - } - }; - if r != 0.0 && r.abs() < f32::MIN_POSITIVE { - 0.0 - } else { - r - } -} - -/// The `f32` value of `half` bits `h`. -fn half_value(h: u16) -> f32 { - let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 }; - let (e, m) = (i32::from(h >> 10 & 0x1F), f64::from(h & 0x3FF)); - let a = match e { - 0 => m * 2f64.powi(-24), - 31 if m == 0.0 => f64::INFINITY, - 31 => f64::NAN, - _ => (1024.0 + m) * 2f64.powi(e - 25), - }; - (sign * a) as f32 -} - -/// `n / d` (`|n| <= d`, `d < 2^16`) correctly rounded to `f32` (nearest even), in integers. -fn ratio_f32(n: i64, d: i64) -> f32 { - if n == 0 { - return 0.0; - } - let (a, d) = (u128::from(n.unsigned_abs()), d as u128); - // `a / d` lies in `[2^e, 2^(e+1))`. - let mut e = 0i32; - while a << ((-e) as u32) < d { - e -= 1; - } - let num = a << (23 - e) as u32; - let (q, r) = (num / d, num % d); - let up = 2 * r > d || (2 * r == d && q & 1 == 1); - let m = (q + u128::from(up)) as f64 * 2f64.powi(e - 23); - (m.copysign(n as f64)) as f32 -} - -/// A half-float format's `half` result `h`, `+0` where it is a zero of either sign (Metal's, -/// measured on the P2a probe). -fn unsigned_half(h: u16) -> u16 { - if h & 0x7FFF == 0 { - 0 - } else { - h - } -} - -/// The result bits of `half` bits `h`: themselves for a `half` result, else the value's `f32`. -fn widened(h: u16, half: bool) -> u32 { - if half { - u32::from(h) - } else { - half_value(h).to_bits() - } -} - -/// Metal's result for the taps `taps` with integer weights `w` (summing to `total`) of a format of -/// family `fam`, read exactly, as `half` bits when `half`, else `f32` bits: a normalized format's -/// codes summed exactly and rounded half up onto its grid, then to nearest even; a float format's -/// taps through Metal's linear accumulator ([`accumulated`]), a 32-bit float sum rounded to `f32` -/// with ties away from zero, then for a `half` result toward zero saturating, a half-float sum to -/// `half` with ties away from zero (a zero `+0`), which a `float` result widens. -fn metal(tex: &Texels, taps: &[(Tap, i64)], total: i64, half: bool) -> u32 { - match family(tex.class) { - Family::Norm { scale, signed, g } => { - let d = g * scale; - let s: i64 = taps - .iter() - .map(|(t, w)| { - let n = match t { - Tap::Stored(Stored::Code(c)) => c.max(&-scale) * g, - Tap::Border(b) => (b * d as f64) as i64, - Tap::Stored(Stored::Value(_)) => unreachable!("a float tap"), - }; - n * w - }) - .sum(); - let lo = if signed { -d } else { 0 }; - let n = (s + total / 2).div_euclid(total).clamp(lo, d); - if n == 0 { - 0 - } else if half { - u32::from(to_half(n as f64 / d as f64, Rounding::NearestEven)) - } else { - ratio_f32(n, d).to_bits() - } - } - fam => { - let terms: Vec<(f64, f64)> = taps - .iter() - .map(|(t, w)| { - let v = match t { - Tap::Stored(Stored::Value(v)) => f64::from(*v), - Tap::Border(b) => *b, - Tap::Stored(Stored::Code(_)) => unreachable!("a code tap"), - }; - (v, *w as f64 / total as f64) - }) - .collect(); - let bits = if fam == Family::Float16 { 17 } else { 38 }; - // Zero is `+0`, whatever the taps' signs. - let s = accumulated(&terms, bits); - let s = if s == 0.0 { 0.0 } else { s }; - match (fam, half) { - (Family::Float32, true) => u32::from(to_half( - f64::from(f32_away(s)), - Rounding::TowardZeroSaturating, - )), - (Family::Float32, false) => f32_away(s).to_bits(), - _ => widened(unsigned_half(to_half(s, Rounding::NearestAway)), half), - } - } - } -} - -/// Metal's linear accumulator over the terms `terms` (each a tap's value and its weight, exact in -/// `f64`): each present term (a nonzero tap of nonzero weight) `v · w` truncated toward zero onto -/// the grid `2^(E - bits)`, `E` the largest present `e(v) + e(w)` (`e` the exponent), and the -/// truncated terms summed. Exact in `f64`: the texels carry at most 12 significant bits and the -/// weights 16, and each truncated term is an integer below `2^(bits + 2)` grid units. -fn accumulated(terms: &[(f64, f64)], bits: i32) -> f64 { - let exp = |x: f64| ((x.abs().to_bits() >> 52) as i32) - 1023; - let present: Vec<&(f64, f64)> = terms - .iter() - .filter(|(v, w)| *v != 0.0 && *w != 0.0) - .collect(); - let Some(top) = present.iter().map(|(v, w)| exp(*v) + exp(*w)).max() else { - return 0.0; - }; - let unit = 2f64.powi(top - bits); - present - .iter() - .map(|(v, w)| ((v * w) / unit).trunc() * unit) - .sum() -} - -/// How the 2D reference reads a 16-bit normalized format's sum: Metal's, or with one rule dropped, -/// to show a lane depends on it. -#[derive(Clone, Copy, PartialEq, Eq)] -enum PlaneRule { - Metal, - /// The exact sum, the terms untruncated (the earlier reading). - Exact, - /// An axis whose two taps are one texel keeps its fraction. - Unmerged, -} - -/// The expected bits of channel `c` of a sample at texel-space `(x, y)` (`y` ignored in 1D) of -/// layer `l`, constant offset `offset`, read by `rule` in 2D: a `half`'s when `half`, else an -/// `f32`'s. A 2D sample's axis whose two taps are one texel (or both outside a border axis) -/// weighs them `(256, 0)`, the taps weigh `wx · wy` in units of `2^-16`, and a normalized format's -/// terms are truncated onto its grid as a 3D sample's are ([`metal_terms`], a 16-bit format's onto -/// `2^-8` of its codes; an 8-bit format's `16 · code` terms lose nothing). -fn expected( - tex: &Texels, - address: Address, - (x, y): (f64, f64), - (one_d, half, rule): (bool, bool, PlaneRule), - offset: (i32, i32), - l: u32, - c: usize, -) -> u32 { - let (i, kx) = split(x); - let i = i + i64::from(offset.0); - if one_d { - let t0 = tap(tex, address, l, (i, 0), c); - let t1 = tap(tex, address, l, (i + 1, 0), c); - return metal(tex, &[(t0, 256 - kx), (t1, kx)], 256, half); - } - let (j, ky) = split(y); - let j = j + i64::from(offset.1); - let t = [ - [ - tap(tex, address, l, (i, j), c), - tap(tex, address, l, (i + 1, j), c), - ], - [ - tap(tex, address, l, (i, j + 1), c), - tap(tex, address, l, (i + 1, j + 1), c), - ], - ]; - // A float format's sum merges such an axis too, through the accumulator. - let merged = |i: i64, n: i64, k: i64| { - let one = volume_index(i, n, address) == volume_index(i + 1, n, address); - if one && rule == PlaneRule::Metal { - 0 - } else { - k - } - }; - let (kx, ky) = (merged(i, tex.w, kx), merged(j, tex.h, ky)); - let w = |a: i64, b: i64| a * b; - let taps = [ - (t[0][0], w(256 - kx, 256 - ky)), - (t[0][1], w(kx, 256 - ky)), - (t[1][0], w(256 - kx, ky)), - (t[1][1], w(kx, ky)), - ]; - let s: fn(i64) -> u32 = match rule { - PlaneRule::Exact => |_| 0, - _ => |g| if g == 16 { 4 } else { 8 }, - }; - metal_terms(tex, &taps, half, s) -} - -/// Coordinates (texels) from outside one edge to outside the other on both axes, with fractions -/// on and off Metal's 1/256 grid (halfway between two steps included), and far outside the -/// level, where repeat and mirror wrap several periods. Four sit within a few ulps of a -/// footprint's step several periods out (at a width of 12): there the coordinate wrapped first and -/// the product of the unwrapped one read different taps, under repeat and mirror alike. One `y` -/// lies a ulp of its `f32` coordinate below a footprint's step one period below the level (at a -/// height of 8, a power of two): there the wrap rounded up reads the step's other side, under -/// repeat and mirror alike, and Metal's, exact, does not. -fn coordinates(w: i64, h: i64) -> Vec<(f64, f64)> { - let xs = [ - -34.501954078674316, - -21.501953601837158, - 64.49804306030273, - 71.49804496765137, - -25.3, - -2.25, - -0.75, - 0.0, - 0.5, - 1.0 + 1.0 / 512.0, - 2.0 + 3.0 / 512.0, - 3.3, - w as f64 / 2.0 + 0.123, - w as f64 - 0.75, - w as f64 + 0.25, - w as f64 + 2.25, - 3.0 * w as f64 + 0.7, - ]; - let ys = [ - -1.5, - 0.25, - 2.5, - 1.75, - h as f64 / 2.0 + 0.6, - h as f64 - 0.1, - h as f64 + 1.5, - -2.0 * h as f64 - 0.3, - // `u = (4.5 - 1/512) / 8 - 1` less a ulp (`2^-25`): `u + 1` (or `u + 2`) needs a bit more - // than an `f32` holds, and the position lies `2^-22` below the step `4.5 - 1/512` (or - // `12.5 - 1/512` mirrored). - -3.501953125 - 2f64.powi(-22), - ]; - ys.iter() - .flat_map(|y| xs.iter().map(move |x| (*x, *y))) - .collect() -} - -/// The exact real `x` (an `f64` holding it exactly) rounded to `f32` with ties away from zero. -fn ties_away(x: f64) -> f32 { - let r = x as f32; - let d = x - f64::from(r); - if d == 0.0 || !r.is_finite() || r == 0.0 { - return r; - } - let other = if (d > 0.0) == (r > 0.0) { - f32::from_bits(r.to_bits() + 1) - } else { - f32::from_bits(r.to_bits() - 1) - }; - if (f64::from(other) - x).abs() == d.abs() && other.abs() > r.abs() { - other - } else { - r - } -} - -/// The texel-space coordinate a kernel reads for `x` (texels) under `scale` (the extent, or 1 -/// for pixel coordinates, `pixel`) on an axis addressed by `address`: Metal's position, the `f32` -/// coordinate it is given wrapped into one period first on a repeating or mirrored axis (rounded -/// up, or down, which reads the exact wrap's footprints, where the extent is a power of two, item -/// 19), then times the extent rounded to `f32` with ties away from zero; a pixel coordinate as -/// given. -fn seen(x: f64, scale: f64, address: Address, pixel: bool) -> f64 { - seen_rounded(x, scale, address, pixel, !(scale as u32).is_power_of_two()) -} - -/// [`seen`] with the wrap rounded up (`up`) or down on every extent. -fn seen_rounded(x: f64, scale: f64, address: Address, pixel: bool, up: bool) -> f64 { - let u = (x / scale) as f32; - if pixel { - return f64::from(u); - } - let u = match address { - Address::Repeat => wrap(u, u.floor(), up), - Address::Mirror => { - let fl = (u * 0.5).floor(); - wrap(u, fl + fl, up) - } - Address::Edge | Address::Border(_) => u, - }; - f64::from(ties_away(f64::from(u) * scale)) -} - -/// `u - k` (`k` the integer start of `u`'s period) rounded toward positive infinity (`up`) or -/// negative infinity, as Metal's wrap rounds. Exact in `f64` but where `|u| < 2^-29`, where it lies -/// just below `-k` and rounds to `-k` (to nearest) either way, so `s` is a neighbour of the exact -/// difference, which `s + k` (exact in `f64`) against `u` places on one side of it or on it. -fn wrap(u: f32, k: f32, up: bool) -> f32 { - let s = (f64::from(u) - f64::from(k)) as f32; - let z = f64::from(s) + f64::from(k); - if up && z < f64::from(u) { - f32::from_bits(s.to_bits() + 1) - } else if !up && z > f64::from(u) { - f32::from_bits(s.to_bits() - 1) - } else { - s - } -} - -/// The texel-space coordinate the emulation read previously for `x` (texels) under `scale`: the -/// `f32` coordinate times the extent, rounded to `f32` to nearest even, unwrapped. -fn product(x: f64, scale: f64) -> f64 { - f64::from(((x / scale) as f32) * scale as f32) -} - -fn coord_bytes(points: &[(f64, f64)], scale: (f64, f64)) -> Vec { - points - .iter() - .flat_map(|(x, y)| { - [ - ((x / scale.0) as f32).to_le_bytes(), - ((y / scale.1) as f32).to_le_bytes(), - ] - }) - .flatten() - .collect() -} - -const FORMATS: [PixelFormat; 8] = [ - PixelFormat::RGBA8Unorm, - PixelFormat::R8Unorm, - PixelFormat::RGBA8Snorm, - PixelFormat::RGBA16Unorm, - PixelFormat::RG16Snorm, - PixelFormat::RGBA32Float, - PixelFormat::R32Float, - PixelFormat::RGBA16Float, -]; - -/// Run the kernel `bc` (sampling through an `address` sampler with `pixel` coordinates, in -/// `form`, a `half` result) on a `w` by `h` texture of every format of [`FORMATS`] on lavapipe, -/// against [`expected`]. -fn check(name: &str, bc: &[u8], address: Address, pixel: bool, form: Form) { - check_result(name, bc, address, pixel, form, true); -} - -/// [`check`] of a kernel with a `half` result when `half`, else a `float` one; returns how many -/// channels of a 16-bit normalized format each dropped 2D rule changes (the exact sum, the unmerged -/// fractions). -fn check_result( - name: &str, - bc: &[u8], - address: Address, - pixel: bool, - form: Form, - half: bool, -) -> (usize, usize) { - check_with(name, bc, (address, pixel, None), form, half) -} - -/// [`check_result`] of a kernel sampling through runtime sampler slot 0 whose bound sampler's -/// word is `word` (its `SamplerState` specialization), or through its constexpr sampler. -fn check_with( - name: &str, - bc: &[u8], - (address, pixel, word): (Address, bool, Option), - form: Form, - half: bool, -) -> (usize, usize) { - check_sized(name, bc, (address, pixel, word), form, half, (12, 0)).0 -} - -/// The offset Metal moves an axis's taps by (`position::offset_dropped`): none on a repeating or -/// mirrored axis whose base-level size `n` is 3, 5, 6 or 7, else `o`, added before the wrap as -/// Vulkan adds it. -fn placed(o: i32, n: i64, address: Address) -> i32 { - placed_under(o, n, address, false) -} - -/// [`placed`] on an axis of a view whose parent's base-level size, which Metal's rule reads, is not -/// a power of two where the view's `n` is, where `parent` holds: none at `n` of 2 and 4 too. -fn placed_under(o: i32, n: i64, address: Address, parent: bool) -> i32 { - let small = matches!(n, 3 | 5 | 6 | 7) || (parent && matches!(n, 2 | 4)); - if matches!(address, Address::Repeat | Address::Mirror) && small { - 0 - } else { - o - } -} - -/// [`check_with`] on a texture `w` texels wide (and 8 high); also returns how many channels the -/// offset added on every axis (Vulkan's placement) changes. The texture's `OffsetBaseAxes` -/// specialization is `parent`, the axes on which it is a view whose parent's base-level size is not -/// a power of two where its own is. -fn check_sized( - name: &str, - bc: &[u8], - (address, pixel, word): (Address, bool, Option), - form: Form, - half: bool, - (w, parent): (i64, u64), -) -> ((usize, usize), usize) { - let p = lavapipe(); - let a = compile(bc, "k", &p).expect("compile"); - let note = if half { - PrecisionNote::HalfSampleFilter - } else { - PrecisionNote::FloatSampleFilter - }; - assert!(a.precision.contains(¬e), "{name}"); - assert!( - !a.requirements - .properties - .contains(&VkProperty::MetalSampler), - "{name}" - ); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name}: {e}")); - let (plan, m) = typed_module(bc, "k", &p).expect("typed module"); - let h = 8i64; - let one_d = matches!(form, Form::OneD); - let points = coordinates(w, h); - let scale = if pixel { - (1.0, 1.0) - } else { - (w as f64, h as f64) - }; - let (layers, layer) = match form { - Form::Array { layer } => (3u32, layer.clamp(0, 2) as u32), - _ => (1, 0), - }; - let added = match form { - Form::Plain { offset } => offset, - _ => (0, 0), - }; - // Metal's placement of the offset, by a view's parent's base. - let offset = ( - placed_under(added.0, w, address, parent & 1 != 0), - placed_under(added.1, h, address, parent & 2 != 0), - ); - // The channels whose answer the exact sum changes, and those the unmerged fractions change, - // and those the offset added on every axis changes. - let mut told_rules = (0, 0); - let mut told_added = 0; - for (seed, pf) in FORMATS.iter().enumerate() { - let class = texel_format(*pf).0; - let tex = Texels::random(class, w, if one_d { 1 } else { h }, seed as u64 + 11); - let image = tex.image(combined_slot(&m), if one_d { 1 } else { 2 }, layers); - let size = if half { 8 } else { 16 }; - let res = resources( - &plan, - &[coord_bytes(&points, scale), vec![0xab; size * points.len()]], - class, - ); - let mut res = with_word(res, &a, word); - if parent != 0 { - let key = SpecKey::OffsetBaseAxes(TEXTURE); - assert!(a.interface.reads_key(key), "{name}"); - res.spec.insert(key, parent); - } - let out = run(&m, &res, &image, points.len() as u32, half); - // The lanes whose answer the position previously (the unwrapped product) changes, and those - // the wrap rounded up on the power-of-two height changes. - let (mut told, mut told_up) = (0, 0); - for (lane, ((x, y), got)) in points.iter().zip(&out).enumerate() { - let at = ( - seen(*x, scale.0, address, pixel), - seen(*y, scale.1, address, pixel), - ); - let before = (product(*x, scale.0), product(*y, scale.1)); - let up = (at.0, seen_rounded(*y, scale.1, address, pixel, true)); - let metal = (one_d, half, PlaneRule::Metal); - let differ = |p: (f64, f64)| { - (0..got.len()).any(|c| { - expected(&tex, address, p, metal, offset, layer, c) - != expected(&tex, address, at, metal, offset, layer, c) - }) - }; - told += usize::from(!pixel && differ(before)); - told_up += usize::from(!pixel && !one_d && up != at && differ(up)); - for (c, got) in got.iter().enumerate() { - let want = expected(&tex, address, at, metal, offset, layer, c); - let other = - |rule| expected(&tex, address, at, (one_d, half, rule), offset, layer, c); - told_rules.0 += usize::from(other(PlaneRule::Exact) != want); - told_rules.1 += usize::from(other(PlaneRule::Unmerged) != want); - told_added += - usize::from(expected(&tex, address, at, metal, added, layer, c) != want); - assert_eq!( - *got, want, - "{name} {pf:?} lane {lane} ({x}, {y}) channel {c}: {got:#010x} vs {want:#010x}" - ); - } - } - // A repeating or mirrored sampler's lanes tell Metal's position from the unwrapped - // product, so the emulation previously fails them ([`coordinates`] chooses such lanes for - // the 12-texel width). - let wraps = w == 12 && matches!(address, Address::Repeat | Address::Mirror); - assert!( - pixel || !wraps || told > 0, - "{name} {pf:?}: no lane tells the wrapped position from the unwrapped product" - ); - // And, in 2D, from the wrap rounded up on the power-of-two axis, so the emulation before - // item 19 fails them. - assert!( - pixel || one_d || !wraps || told_up > 0, - "{name} {pf:?}: no lane tells the exact wrap from the wrap rounded up" - ); - } - (told_rules, told_added) -} - -/// Every address mode, normalized and pixel coordinates, and each format family on a 12x8 -/// texture: every lane is Metal's, on the interpreter. -#[test] -fn linear_half_samples_take_metals_filter() { - const WHITE: [f64; 4] = [1.0; 4]; - let samplers = [ - ("edge", 1, false, 0, Address::Edge), - ("zero", 0, false, 0, Address::Border([0.0; 4])), - ("white", 0, false, 2, Address::Border(WHITE)), - ("repeat", 2, false, 0, Address::Repeat), - ("mirror", 3, false, 0, Address::Mirror), - ("pixel edge", 1, true, 0, Address::Edge), - ("pixel mirror", 3, true, 0, Address::Mirror), - ]; - for (name, code, pixel, border, address) in samplers { - let form = Form::Plain { offset: (0, 0) }; - let Some(bc) = assemble(name, &kernel(Some(linear(code, pixel, border)), form)) else { - return; - }; - check(name, &bc, address, pixel, form); - } -} - -/// A 1D texture's two taps, a 2D array's layer (clamped into the array), and a constant offset -/// shifting the base taps, under edge and repeat addressing. -#[test] -fn a_1d_texture_an_array_layer_and_an_offset() { - let cases = [ - ("1d edge", 1, Address::Edge, Form::OneD), - ("1d mirror", 3, Address::Mirror, Form::OneD), - ("layer 1", 1, Address::Edge, Form::Array { layer: 1 }), - ("layer 9", 1, Address::Edge, Form::Array { layer: 9 }), - ("offset", 1, Address::Edge, Form::Plain { offset: (2, -1) }), - ( - "repeat offset", - 2, - Address::Repeat, - Form::Plain { offset: (-3, 5) }, - ), - ]; - for (name, code, address, form) in cases { - let Some(bc) = assemble(name, &kernel(Some(linear(code, false, 0)), form)) else { - return; - }; - check(name, &bc, address, false, form); - } -} - -/// A constant offset on a repeating or mirrored axis, on textures 3, 5, 6, 7 (where Metal drops -/// it), 4 and 9 (where it adds it before the wrap) texels wide and 8 high (added): every lane is -/// Metal's, on the interpreter, and where Metal drops it some channel tells its placement from the -/// offset added on every axis. -#[test] -fn an_offset_on_a_wrapped_axis_takes_metals_placement() { - for (code, address) in [(2, Address::Repeat), (3, Address::Mirror)] { - // Neither `s` offset is a multiple of a dropping size's period, so each moves the taps. - for (ox, oy) in [(2, 5), (-1, -1)] { - let form = Form::Plain { offset: (ox, oy) }; - for half in [true, false] { - let name = format!("{address:?} offset ({ox}, {oy}) half {half}"); - let k = kernel_of(Some(linear(code, false, 0)), form, !half); - let Some(bc) = assemble(&name, &k) else { - return; - }; - for w in [3, 4, 5, 6, 7, 9] { - let name = format!("{name} {w}x8"); - let at = (address, false, None); - let (_, told) = check_sized(&name, &bc, at, form, half, (w, 0)); - let dropped = matches!(w, 3 | 5 | 6 | 7); - assert_eq!( - told > 0, - dropped, - "{name}: {told} channels tell Metal's placement from the added offset" - ); - } - } - } - } -} - -/// The residue: a view whose first level lies above its parent's base reads Metal's rule by its -/// parent's base-level size. Under the slot's `OffsetBaseAxes` bit on `s` (a parent whose width is -/// not a power of two), a constant offset on a repeating or mirrored axis 2 or 4 texels wide drops, -/// and 8 wide adds; every lane is Metal's, on the interpreter, and at 2 and 4 some channel tells -/// the drop from the offset added; without the bit, 2, 4 and 8 add it, as before. A runtime -/// sampler's word reads the same bit; a `float` result's filter the same placement. -#[test] -fn an_offset_on_a_view_s_wrapped_axis_takes_its_parent_s_placement() { - let runtime = runtime_word( - SamplerAddressMode::Repeat, - false, - SamplerBorderColor::TransparentBlack, - ); - for (code, address, word, halves) in [ - (Some(2), Address::Repeat, None, &[true, false][..]), - (Some(3), Address::Mirror, None, &[true][..]), - (None, Address::Repeat, Some(runtime), &[true][..]), - ] { - let form = Form::Plain { offset: (-1, 5) }; - for &half in halves { - let name = format!("{address:?} runtime {} half {half}", word.is_some()); - let k = kernel_of(code.map(|c| linear(c, false, 0)), form, !half); - let Some(bc) = assemble(&name, &k) else { - return; - }; - for w in [2, 4, 8] { - for parent in [0, 1] { - let name = format!("{name} {w}x8 parent {parent}"); - let at = (address, false, word); - let (_, told) = check_sized(&name, &bc, at, form, half, (w, parent)); - let dropped = parent == 1 && w != 8; - assert_eq!( - told > 0, - dropped, - "{name}: {told} channels tell Metal's placement from the added offset" - ); - } - } - } - } -} - -/// A sample whose texel offset the emulation places on a repeating or mirrored axis, constexpr or -/// runtime, reads Metal's base-level size, a view's parent's: a slot's through its `OffsetBaseAxes` -/// specialization, which the stage declares, recording no `ViewBaseTexelOffset`. No offset, an -/// offset on clamping axes only, and MoltenVK (Metal's own sampler) declare none, and nothing -/// records the note. -#[test] -fn a_wrapped_offset_reads_the_parent_base_specialization() { - let (lvp, m3) = (lavapipe(), m3()); - let note = PrecisionNote::ViewBaseTexelOffset; - let offset = Form::Plain { offset: (2, -1) }; - let plain = Form::Plain { offset: (0, 0) }; - let cases = [ - ("repeat offset", Some(linear(2, false, 0)), offset, true), - ("mirror offset", Some(linear(3, false, 0)), offset, true), - ("runtime offset", None, offset, true), - ( - "3d repeat offset", - Some(linear(2, false, 0)), - Form::ThreeD { offset: (0, 1, 0) }, - true, - ), - ("edge offset", Some(linear(1, false, 0)), offset, false), - ("repeat", Some(linear(2, false, 0)), plain, false), - ]; - let declares = |a: &crate::library::FunctionArtifact| { - a.interface - .read_keys() - .into_iter() - .any(|k| matches!(k, SpecKey::OffsetBaseAxes(_))) - }; - for (name, words, form, placed) in cases { - let Some(bc) = assemble(name, &kernel_of(words, form, false)) else { - return; - }; - let a = compile(&bc, "k", &lvp).unwrap_or_else(|e| panic!("{name}: {e}")); - assert!(!a.precision.contains(¬e), "{name} on lavapipe"); - assert_eq!(declares(&a), placed, "{name} on lavapipe"); - let b = compile(&bc, "k", &m3).unwrap_or_else(|e| panic!("{name} on moltenvk-m3: {e}")); - assert!(!b.precision.contains(¬e), "{name} on moltenvk-m3"); - assert!(!declares(&b), "{name} on moltenvk-m3"); - } -} - -/// A `float` result through the same filter, under each address mode, normalized and pixel -/// coordinates, a constant offset, 1D, and an array layer, on each format family: Metal's rule (a -/// normalized format's `n / D` to `f32`, a 16-bit one's 2D terms truncated; a 32-bit float or -/// half-float format's accumulated sum, the half-float's `half` widened). -#[test] -fn linear_float_samples_take_metals_filter() { - const WHITE: [f64; 4] = [1.0; 4]; - let plain = Form::Plain { offset: (0, 0) }; - let cases = [ - ("float edge", 1, false, 0, Address::Edge, plain), - ("float zero", 0, false, 0, Address::Border([0.0; 4]), plain), - ("float white", 0, false, 2, Address::Border(WHITE), plain), - ("float mirror", 3, false, 0, Address::Mirror, plain), - ( - "float repeat offset", - 2, - false, - 0, - Address::Repeat, - Form::Plain { offset: (-3, 5) }, - ), - ("float pixel edge", 1, true, 0, Address::Edge, plain), - ( - "float 1d zero", - 0, - false, - 0, - Address::Border([0.0; 4]), - Form::OneD, - ), - ("float 1d mirror", 3, false, 0, Address::Mirror, Form::OneD), - ( - "float layer 9", - 1, - false, - 0, - Address::Edge, - Form::Array { layer: 9 }, - ), - ]; - let mut told = (0, 0); - for (name, code, pixel, border, address, form) in cases { - let k = kernel_of(Some(linear(code, pixel, border)), form, true); - let Some(bc) = assemble(name, &k) else { - return; - }; - let (sum, merge) = check_result(name, &bc, address, pixel, form, false); - told = (told.0 + sum, told.1 + merge); - } - // Channels of the 16-bit formats tell Metal's 2D sum from the exact one and from the - // unmerged fractions, so the emulation before it fails them. A `half` result rounds most such - // differences away. - assert!( - told.0 > 0, - "no channel tells the truncated terms from the exact sum" - ); - assert!( - told.1 > 0, - "no channel tells the merged fractions from the unmerged ones" - ); -} - -/// The extent of the 3D test texture: the position (the coordinate wrapped into one period first, -/// rounded up) is Metal's on its `s` and `r` axes, and the exact wrap on its `t` axis, a power of -/// two (the 3D probes, per axis). -const VOLUME: (i64, i64, i64) = (5, 8, 3); - -/// The texel of a 3D texture's axis of extent `n` at index `v` under `address`, or `None` outside -/// a border axis. -fn volume_index(v: i64, n: i64, address: Address) -> Option { - match address { - Address::Edge => Some(v.clamp(0, n - 1)), - Address::Repeat => Some(v.rem_euclid(n)), - Address::Mirror => { - let m = if v >= 0 { v } else { -1 - v }; - let r = m % (2 * n); - Some(if r < n { r } else { 2 * n - 1 - r }) - } - Address::Border(_) => (0..n).contains(&v).then_some(v), - } -} - -/// How the 3D reference reads Metal's rule: Metal's own, or with one rule dropped, to show a lane -/// depends on it. -#[derive(Clone, Copy, PartialEq, Eq)] -enum Rule { - Metal, - /// A tie rounds up on the `t` axis's other tap. - OtherTie, - /// An axis whose two taps are one texel keeps its fraction. - Unmerged, -} - -/// Metal's 2D result of the taps `taps` (each with its 16-bit weight) of these texels' format -/// ([`metal_terms`]): a normalized format's terms truncated onto `2^-s` of its grid, `s` 4 for an -/// 8-bit format's `16 · code` and 8 for a 16-bit one's code. A linear cube sample's sum. -pub(super) fn plane_sum(tex: &Texels, taps: &[(Tap, i64)], half: bool) -> u32 { - metal_terms(tex, taps, half, |g| if g == 16 { 4 } else { 8 }) -} - -/// Metal's 3D result of the taps `taps` (each with its 16-bit weight): a normalized format's terms -/// truncated onto `2^-s` of its grid, `s` 4 for an 8-bit format's `16 · code` and 8 for a 16-bit -/// one's code ([`metal_terms`]). -fn metal_3d(tex: &Texels, taps: &[(Tap, i64)], half: bool) -> u32 { - metal_terms(tex, taps, half, |g| if g == 16 { 4 } else { 8 }) -} - -/// Metal's 2D or 3D result of the taps `taps` (each with its 16-bit weight) of a format of family -/// `fam`, as `half` bits when `half`, else `f32` bits: a normalized format's terms `code · w` each -/// truncated onto `2^-s` of its grid toward negative infinity (`s` of the family's grid factor -/// `g`), summed, then `⌊(T + 2^(15 - s)) / 2^(16 - s)⌋` and to nearest even; a float format's -/// through Metal's linear accumulator ([`metal`]). -fn metal_terms(tex: &Texels, taps: &[(Tap, i64)], half: bool, s: fn(i64) -> u32) -> u32 { - let Family::Norm { scale, signed, g } = family(tex.class) else { - return metal(tex, taps, 1 << 16, half); - }; - let d = g * scale; - let s = s(g); - let t: i64 = taps - .iter() - .map(|(t, w)| { - let n = match t { - Tap::Stored(Stored::Code(c)) => c.max(&-scale) * g, - Tap::Border(b) => (b * d as f64) as i64, - Tap::Stored(Stored::Value(_)) => unreachable!("a float tap"), - }; - (n * w) >> s - }) - .sum(); - let lo = if signed { -d } else { 0 }; - let n = ((t + (1 << (15 - s))) >> (16 - s)).clamp(lo, d); - if n == 0 { - 0 - } else if half { - u32::from(to_half(n as f64 / d as f64, Rounding::NearestEven)) - } else { - ratio_f32(n, d).to_bits() - } -} - -/// The expected bits of channel `c` of a 3D sample at texel-space `at` with constant `offset` -/// on a texture of extent [`VOLUME`] (`tex` holds its slices' rows in turn), read by `rule`: per -/// axis the base tap and fraction ([`split`]), each tap addressed, an axis whose two taps are one -/// texel (or both outside a border axis) weighed `(256, 0)`, the eight taps' weights -/// `round(wx · wy · wz / 256)` with a tie up on the `t` axis's first tap in Metal's frame (its -/// second where a mirrored axis's taps run backwards), and [`metal_3d`]'s sum. -fn expected_3d( - tex: &Texels, - address: Address, - at: (f64, f64, f64), - (offset, half, rule): ((i32, i32, i32), bool, Rule), - c: usize, -) -> u32 { - let (w, h, d) = VOLUME; - let axis = |x: f64, o: i32, n: i64| { - let (i, k) = split(x); - let i = i + i64::from(o); - let taps = [volume_index(i, n, address), volume_index(i + 1, n, address)]; - let k = if taps[0] == taps[1] && rule != Rule::Unmerged { - 0 - } else { - k - }; - (taps, [256 - k, k]) - }; - let (xs, wx) = axis(at.0, offset.0, w); - let (ys, wy) = axis(at.1, offset.1, h); - let (zs, wz) = axis(at.2, offset.2, d); - let flip = matches!(address, Address::Mirror) && ys[0] > ys[1]; - let first = usize::from(flip != (rule == Rule::OtherTie)); - let mut taps = Vec::with_capacity(8); - for n in 0..8 { - let (a, b, e) = (n & 1, (n >> 1) & 1, n >> 2); - let p = wx[a] * wy[b] * wz[e]; - let (q, r) = (p >> 8, p & 255); - let weight = q + i64::from(r > 128 || (r == 128 && b == first)); - let tap = match (xs[a], ys[b], zs[e], address) { - (Some(x), Some(y), Some(z), _) => Tap::Stored(tex.texel(0, x, y + h * z)[c]), - (_, _, _, Address::Border(color)) => { - let present = tex.class & (1 << (BicubicTexels::PRESENT + c as u32)) != 0; - let missing = if c == 3 { 1.0 } else { 0.0 }; - Tap::Border(if present { color[c] } else { missing }) - } - _ => unreachable!("only a border axis leaves the level"), - }; - taps.push((tap, weight)); - } - metal_3d(tex, &taps, half) -} - -/// Texel-space coordinates of a 3D sample: [`coordinates`]' `(x, y)` on the plane, each at a depth -/// in turn from outside one end of the `r` axis to outside the other (several periods out -/// included), and lanes that make the rules show: the `s` fraction at `1/2` with odd `t` and `r` -/// fractions (every weight a rounding tie), in both halves of a mirrored `t` axis's period. -fn volume_coordinates() -> Vec<(f64, f64, f64)> { - let (w, h, d) = VOLUME; - let zs = [ - -1.25, - 0.0, - 0.5 + 1.0 / 512.0, - 1.3, - d as f64 / 2.0 + 0.127, - d as f64 - 0.6, - d as f64 + 0.75, - -2.0 * d as f64 - 0.4, - ]; - let mut out: Vec<(f64, f64, f64)> = coordinates(w, h) - .into_iter() - .enumerate() - .map(|(n, (x, y))| (x, y, zs[(3 * n + 1) % zs.len()])) - .collect(); - for y in [3.0 + 5.0 / 256.0, -3.0 + 5.0 / 256.0, 2.0 + 77.0 / 256.0] { - for x in [2.0, 1.0, 4.0] { - out.push((x, y, 1.0 + 3.0 / 256.0)); - } - } - out -} - -/// Run the 3D kernel `bc` (through an `address` sampler, constant `offset`, a `half` result when -/// `half`) on a [`VOLUME`] texture of every format of [`FORMATS`] on the interpreter, against -/// [`expected_3d`]; returns how many lanes each dropped rule changes (the other tie, unmerged), -/// how many the wrap rounded up on the power-of-two `t` axis changes, and how many the offset -/// added on every axis (Vulkan's placement) changes. -fn check_3d( - name: &str, - bc: &[u8], - address: Address, - offset: (i32, i32, i32), - half: bool, -) -> (usize, usize, usize, usize) { - check_3d_with(name, bc, (address, None), offset, half) -} - -/// [`check_3d`] of a kernel sampling through runtime sampler slot 0 whose bound sampler's word is -/// `word`, or through its constexpr sampler. -fn check_3d_with( - name: &str, - bc: &[u8], - (address, word): (Address, Option), - added: (i32, i32, i32), - half: bool, -) -> (usize, usize, usize, usize) { - let p = lavapipe(); - let a = compile(bc, "k", &p).expect("compile"); - let note = if half { - PrecisionNote::HalfSampleFilter - } else { - PrecisionNote::FloatSampleFilter - }; - assert!(a.precision.contains(¬e), "{name}"); - assert!( - a.strategies.entries.contains_key("sampler.linear.block"), - "{name}: not emulated" - ); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name}: {e}")); - let (plan, m) = typed_module(bc, "k", &p).expect("typed module"); - let (w, h, d) = VOLUME; - // Metal's placement of the offset, per axis. - let offset = ( - placed(added.0, w, address), - placed(added.1, h, address), - placed(added.2, d, address), - ); - let points = volume_coordinates(); - let bytes: Vec = points - .iter() - .flat_map(|(x, y, z)| { - [ - ((x / w as f64) as f32).to_le_bytes(), - ((y / h as f64) as f32).to_le_bytes(), - ((z / d as f64) as f32).to_le_bytes(), - 0f32.to_le_bytes(), - ] - }) - .flatten() - .collect(); - let mut shown = (0, 0, 0, 0); - for (seed, pf) in FORMATS.iter().enumerate() { - let class = texel_format(*pf).0; - let tex = Texels::random(class, w, h * d, seed as u64 + 23); - let mut image = Image::new(combined_slot(&m), [w as u32, h as u32, d as u32], 1, 1, 1); - for z in 0..d { - for y in 0..h { - for x in 0..w { - let at = image - .index(0, 0, 0, [x as u32, y as u32, z as u32]) - .expect("texel"); - let v = tex.texel(0, x, y + h * z); - image.texels[at] = v.map(|c| tex.fetched(c).to_bits()); - } - } - } - let size = if half { 8 } else { 16 }; - let res = resources( - &plan, - &[bytes.clone(), vec![0xab; size * points.len()]], - class, - ); - let res = with_word(res, &a, word); - let out = run(&m, &res, &image, points.len() as u32, half); - for (lane, ((x, y, z), got)) in points.iter().zip(&out).enumerate() { - let at = ( - seen(*x, w as f64, address, false), - seen(*y, h as f64, address, false), - seen(*z, d as f64, address, false), - ); - let want = - |c: usize, rule: Rule| expected_3d(&tex, address, at, (offset, half, rule), c); - shown.0 += usize::from((0..4).any(|c| want(c, Rule::OtherTie) != want(c, Rule::Metal))); - shown.1 += usize::from((0..4).any(|c| want(c, Rule::Unmerged) != want(c, Rule::Metal))); - shown.3 += usize::from((0..4).any(|c| { - expected_3d(&tex, address, at, (added, half, Rule::Metal), c) - != want(c, Rule::Metal) - })); - let up = (at.0, seen_rounded(*y, h as f64, address, false, true), at.2); - shown.2 += usize::from( - up != at - && (0..4).any(|c| { - expected_3d(&tex, address, up, (offset, half, Rule::Metal), c) - != want(c, Rule::Metal) - }), - ); - for (c, got) in got.iter().enumerate() { - let want = want(c, Rule::Metal); - assert_eq!( - *got, want, - "{name} {pf:?} lane {lane} ({x}, {y}, {z}) channel {c}: {got:#010x} vs \ - {want:#010x}" - ); - } - } - } - shown -} - -/// A 3D linear sample under every address mode, a constant offset on clamping axes and on repeating -/// and mirrored ones ([`VOLUME`]'s `s` and `r` axes, 5 and 3 texels, drop it, and its `t` axis, 8, -/// adds it), each format family, and a `half` or `float` result: every lane is Metal's 3D rule, on -/// the interpreter. The lanes include ties of the 16-bit weights (in both frames of a mirrored -/// axis) and axes whose two taps are one texel, which the dropped rules answer differently, and -/// lanes where the offset added on every axis reads other taps. -#[test] -fn linear_3d_samples_take_metals_filter() { - const WHITE: [f64; 4] = [1.0; 4]; - let cases = [ - ("3d edge", 1, 0, Address::Edge, (0, 0, 0), true), - ("3d zero", 0, 0, Address::Border([0.0; 4]), (0, 0, 0), true), - ("3d white", 0, 2, Address::Border(WHITE), (0, 0, 0), true), - ("3d repeat", 2, 0, Address::Repeat, (0, 0, 0), true), - ("3d mirror", 3, 0, Address::Mirror, (0, 0, 0), true), - ("3d edge offset", 1, 0, Address::Edge, (1, -2, 1), true), - ("3d repeat offset", 2, 0, Address::Repeat, (2, -3, 1), true), - ("3d mirror offset", 3, 0, Address::Mirror, (-1, 1, 2), true), - ("3d float edge", 1, 0, Address::Edge, (0, 0, 0), false), - ( - "3d float repeat offset", - 2, - 0, - Address::Repeat, - (-4, 5, -2), - false, - ), - ("3d float mirror", 3, 0, Address::Mirror, (0, 0, 0), false), - ( - "3d float white offset", - 0, - 2, - Address::Border(WHITE), - (-1, 0, 2), - false, - ), - ]; - for (name, code, border, address, offset, half) in cases { - let k = kernel_of( - Some(linear(code, false, border)), - Form::ThreeD { offset }, - !half, - ); - let Some(bc) = assemble(name, &k) else { - return; - }; - let (tie, merge, up, added) = check_3d(name, &bc, address, offset, half); - assert!(tie > 0, "{name}: no lane shows the tie rule"); - if matches!(address, Address::Repeat | Address::Mirror) && offset != (0, 0, 0) { - assert!( - added > 0, - "{name}: no lane shows Metal's placement of the offset" - ); - } - if matches!(address, Address::Edge | Address::Mirror) { - assert!(merge > 0, "{name}: no lane shows the merged taps"); - } - if matches!(address, Address::Repeat | Address::Mirror) { - assert!( - up > 0, - "{name}: no lane shows the exact wrap on the power-of-two axis" - ); - } - } -} - -/// A sample through a runtime sampler slot takes Metal's filter by the bound sampler's word, as a -/// constexpr sampler of the same state does: every lane is Metal's rule on the -/// interpreter under each address mode, a transparent, opaque-black, and white border (and -/// `clamp_to_zero` beside a white and an opaque-black border color, which it reads as -/// `clamp_to_border` does), pixel coordinates, 1D, a constant offset, 3D, and a `half` or `float` -/// result, with the word's state read only in the function. -#[test] -fn runtime_sampler_samples_take_metals_filter() { - use SamplerAddressMode as M; - use SamplerBorderColor as B; - const WHITE: [f64; 4] = [1.0; 4]; - const BLACK: [f64; 4] = [0.0, 0.0, 0.0, 1.0]; - let plain = Form::Plain { offset: (0, 0) }; - let cases = [ - ( - "runtime edge", - M::ClampToEdge, - B::TransparentBlack, - Address::Edge, - false, - plain, - ), - ( - "runtime zero", - M::ClampToZero, - B::OpaqueWhite, - Address::Border(WHITE), - false, - plain, - ), - ( - "runtime zero black", - M::ClampToZero, - B::OpaqueBlack, - Address::Border(BLACK), - false, - plain, - ), - ( - "runtime white", - M::ClampToBorderColor, - B::OpaqueWhite, - Address::Border(WHITE), - false, - plain, - ), - ( - "runtime black", - M::ClampToBorderColor, - B::OpaqueBlack, - Address::Border(BLACK), - false, - plain, - ), - ( - "runtime repeat", - M::Repeat, - B::TransparentBlack, - Address::Repeat, - false, - plain, - ), - ( - "runtime mirror", - M::MirrorRepeat, - B::TransparentBlack, - Address::Mirror, - false, - plain, - ), - ( - "runtime pixel zero", - M::ClampToZero, - B::TransparentBlack, - Address::Border([0.0; 4]), - true, - plain, - ), - ( - "runtime 1d mirror", - M::MirrorRepeat, - B::TransparentBlack, - Address::Mirror, - false, - Form::OneD, - ), - ( - "runtime repeat offset", - M::Repeat, - B::TransparentBlack, - Address::Repeat, - false, - Form::Plain { offset: (-3, 5) }, - ), - ]; - for (name, mode, border, address, pixel, form) in cases { - let Some(bc) = assemble(name, &kernel(None, form)) else { - return; - }; - let word = runtime_word(mode, pixel, border); - check_with(name, &bc, (address, pixel, Some(word)), form, true); - } - for (name, mode, border, address) in [ - ( - "runtime float mirror", - M::MirrorRepeat, - B::TransparentBlack, - Address::Mirror, - ), - ( - "runtime float white", - M::ClampToBorderColor, - B::OpaqueWhite, - Address::Border(WHITE), - ), - ] { - let Some(bc) = assemble(name, &kernel_of(None, plain, true)) else { - return; - }; - let word = runtime_word(mode, false, border); - check_with(name, &bc, (address, false, Some(word)), plain, false); - } - for (name, mode, border, address, offset, half) in [ - ( - "runtime 3d zero", - M::ClampToZero, - B::TransparentBlack, - Address::Border([0.0; 4]), - (0, 0, 0), - true, - ), - ( - "runtime 3d mirror", - M::MirrorRepeat, - B::TransparentBlack, - Address::Mirror, - (0, 0, 0), - true, - ), - ( - "runtime 3d repeat", - M::Repeat, - B::TransparentBlack, - Address::Repeat, - (0, 0, 0), - false, - ), - ( - "runtime 3d white offset", - M::ClampToBorderColor, - B::OpaqueWhite, - Address::Border(WHITE), - (-1, 0, 2), - false, - ), - ( - "runtime 3d repeat offset", - M::Repeat, - B::TransparentBlack, - Address::Repeat, - (1, -2, 2), - true, - ), - ] { - let k = kernel_of(None, Form::ThreeD { offset }, !half); - let Some(bc) = assemble(name, &k) else { - return; - }; - let word = runtime_word(mode, false, border); - check_3d_with(name, &bc, (address, Some(word)), offset, half); - } -} - -/// What the emulation reaches, what the device filters under the note, and what neither touches. On -/// lavapipe a linear sample of a 1D, 2D, or 3D slot is emulated, with a `half` or `float` result -/// (it calls the linear routines and fetches), through a constexpr sampler or a runtime one (whose -/// word selects the emulation in the function), a minimum or maximum reduction too (read as the -/// weighted average); the device filters a mip filter (a linear one with nearest minification and -/// magnification included), anisotropy, differing filters, `min_lod_clamp`, and a dynamic offset (a -/// 3D sample's offset on a repeating or mirrored axis is emulated). Every filtered sample is noted, -/// emulated or not (`PrecisionNote::HalfSampleFilter` for a `half` result, -/// `PrecisionNote::FloatSampleFilter` for a `float` one); a nearest sample carries no note. On -/// MoltenVK no sample is emulated, and every filtered sample of either result type requires -/// `VkProperty::MetalSampler`, as does every `half` sample, whose texel's rounding to `half` there -/// is Metal's only through Metal's own texture unit. -#[test] -fn the_emulation_reaches_what_metal_measured() { - let edge = linear(1, false, 0); - let plain = Form::Plain { offset: (0, 0) }; - // The census names an emulated sample (and counts its words once per call site, the routines - // once per module). - let emulated = |a: &crate::library::FunctionArtifact| { - let linear = a.strategies.entries.get("sampler.linear").map(|u| u.uses); - let routines = ["quad", "span", "block"].iter().any(|r| { - a.strategies - .entries - .contains_key(&format!("sampler.linear.{r}")) - }); - assert_eq!( - linear.is_some(), - routines, - "the census of {:?}", - a.strategies - ); - linear == Some(1) - }; - // The note of a filtered sample of `form`'s result type, and the other type's, which it never - // records. - let notes = |form: Form| { - if matches!(form, Form::Float) { - ( - PrecisionNote::FloatSampleFilter, - PrecisionNote::HalfSampleFilter, - ) - } else { - ( - PrecisionNote::HalfSampleFilter, - PrecisionNote::FloatSampleFilter, - ) - } - }; - let metal = |a: &crate::library::FunctionArtifact| { - a.requirements - .properties - .contains(&VkProperty::MetalSampler) - }; - // (name, sampler, form, emulated on lavapipe, filtered) - let cases: Vec<(&str, Option, Form, bool, bool)> = vec![ - ("2d", Some(edge), plain, true, true), - ("1d", Some(edge), Form::OneD, true, true), - ("array", Some(edge), Form::Array { layer: 1 }, true, true), - ("runtime", None, plain, true, true), - ( - "mip", - Some(sampler_words(1, 2, 1, false, 0)), - plain, - false, - true, - ), - ("anisotropy", Some(edge | 1 << 20), plain, false, true), - // A minimum reduction reads the weighted average, as on Apple's GPU. - ("min reduction", Some(edge | 1 << 58), plain, true, true), - ("max reduction", Some(edge | 2 << 58), plain, true, true), - ( - "linear min nearest mag", - Some(edge & !(1 << 9)), - plain, - false, - true, - ), - ( - "3d", - Some(edge), - Form::ThreeD { offset: (0, 0, 0) }, - true, - true, - ), - ( - "3d edge offset", - Some(edge), - Form::ThreeD { offset: (1, -2, 3) }, - true, - true, - ), - ( - "3d repeat offset", - Some(linear(2, false, 0)), - Form::ThreeD { offset: (0, 1, 0) }, - true, - true, - ), - ( - "3d mirror offset", - Some(linear(3, false, 0)), - Form::ThreeD { offset: (0, 0, -1) }, - true, - true, - ), - ( - "3d repeat", - Some(linear(2, false, 0)), - Form::ThreeD { offset: (0, 0, 0) }, - true, - true, - ), - ("min_lod_clamp", Some(edge), Form::MinLodClamp, false, true), - ( - "dynamic offset", - Some(edge), - Form::DynamicOffset, - false, - true, - ), - ( - "nearest", - Some(sampler_words(0, 0, 1, false, 0)), - plain, - false, - false, - ), - ( - "nearest with a linear mip filter", - Some(sampler_words(0, 2, 1, false, 0)), - plain, - false, - true, - ), - ("float", Some(edge), Form::Float, true, true), - ("float runtime", None, Form::Float, true, true), - ( - "float nearest", - Some(sampler_words(0, 0, 1, false, 0)), - Form::Float, - false, - false, - ), - ( - "float nearest with a linear mip filter", - Some(sampler_words(0, 2, 1, false, 0)), - Form::Float, - false, - true, - ), - ]; - let (lvp, m3) = (lavapipe(), m3()); - for (name, sampler, form, reached, filtered) in cases { - let Some(bc) = assemble(name, &kernel(sampler, form)) else { - return; - }; - let a = compile(&bc, "k", &lvp).unwrap_or_else(|e| panic!("{name} on lavapipe: {e}")); - link_and_validate(&a, &lvp).unwrap_or_else(|e| panic!("{name} on lavapipe: {e}")); - let (note, other) = notes(form); - assert_eq!(emulated(&a), reached, "{name} on lavapipe"); - assert_eq!(a.precision.contains(¬e), filtered, "{name} on lavapipe"); - assert!(!a.precision.contains(&other), "{name} on lavapipe"); - assert!(!metal(&a), "{name} on lavapipe"); - let b = compile(&bc, "k", &m3).unwrap_or_else(|e| panic!("{name} on moltenvk-m3: {e}")); - link_and_validate(&b, &m3).unwrap_or_else(|e| panic!("{name} on moltenvk-m3: {e}")); - assert!(!emulated(&b), "{name} on moltenvk-m3"); - assert!(!b.precision.contains(¬e), "{name} on moltenvk-m3"); - assert!(!b.precision.contains(&other), "{name} on moltenvk-m3"); - let half = !matches!(form, Form::Float); - assert_eq!(metal(&b), filtered || half, "{name} on moltenvk-m3"); - } -} - -/// A kernel comparing `depth2d` slot 0 at buffer 0's lane `tid` against `0.5` through a -/// constexpr sampler with comparison `less`, minification and magnification `filter` (0 nearest, -/// 1 linear), and mip filter `mip` (0 none, 2 linear), at level 0, storing the `float` result to -/// buffer 1. -fn compare_kernel(filter: u64, mip: u64) -> String { - let w = sampler_words(filter, mip, 1, false, 0) & !(0xf << 16) | 1 << 16; - format!( - r#"@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 {w}, i64 0], align 8 - -define void @k(ptr addrspace(1) %d, ptr addrspace(1) %c, ptr addrspace(1) %out, i32 %tid) {{ - %i = zext i32 %tid to i64 - %p = getelementptr inbounds <2 x float>, ptr addrspace(1) %c, i64 %i - %uv = load <2 x float>, ptr addrspace(1) %p, align 8 - %r = call {{ float, i8 }} @air.sample_compare_depth_2d.f32(ptr addrspace(1) %d, ptr addrspace(2) @__air_sampler_state, i32 1, <2 x float> %uv, float 0.5, i1 true, <2 x i32> zeroinitializer, i1 true, float 0.0, float 0.0, i32 0) - %v = extractvalue {{ float, i8 }} %r, 0 - %q = getelementptr inbounds float, ptr addrspace(1) %out, i64 %i - store float %v, ptr addrspace(1) %q, align 4 - ret void -}} - -declare {{ float, i8 }} @air.sample_compare_depth_2d.f32(ptr addrspace(1), ptr addrspace(2), i32, <2 x float>, float, i1, <2 x i32>, i1, float, float, i32) - -!air.kernel = !{{!0}} -!air.sampler_states = !{{!6}} -!0 = !{{ptr @k, !1, !2}} -!1 = !{{}} -!2 = !{{!3, !4, !5, !7}} -!3 = !{{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"depth2d", !"air.arg_name", !"d"}} -!4 = !{{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"float2", !"air.arg_name", !"c"}} -!5 = !{{i32 2, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"float", !"air.arg_name", !"out"}} -!6 = !{{!"air.sampler_state", ptr addrspace(2) @__air_sampler_state}} -!7 = !{{i32 3, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"tid"}} -"# - ) -} - -/// A depth texture's comparison through a linear sampler, or a nearest one with a linear mip -/// filter, is a filtered `float` sample: noted `PrecisionNote::FloatSampleFilter` on lavapipe -/// (where the linear one is emulated, and the other blends two levels' comparisons where the slot's -/// format is measured and keeps the device's filter elsewhere) and requiring -/// `VkProperty::MetalSampler` on MoltenVK; through a nearest sampler it is not noted, and requires -/// the property on MoltenVK too: the device's comparison is Metal's there, and elsewhere the shader -/// compares. Only the comparison the device may make on lavapipe, the nearest one with a linear mip -/// filter (where the format's class is not measured), notes `PrecisionNote::DeviceDepthComparison`: -/// the shader compares the others' fetched texels. -#[test] -fn a_depth_comparison_through_a_filter_is_a_filtered_float_sample() { - let (lvp, m3) = (lavapipe(), m3()); - for (name, filter, mip, filtered, device) in [ - ("linear", 1, 0, true, false), - ("nearest with a linear mip filter", 0, 2, true, true), - ("nearest", 0, 0, false, false), - ] { - let Some(bc) = assemble(name, &compare_kernel(filter, mip)) else { - return; - }; - let a = compile(&bc, "k", &lvp).unwrap_or_else(|e| panic!("{name} on lavapipe: {e}")); - link_and_validate(&a, &lvp).unwrap_or_else(|e| panic!("{name} on lavapipe: {e}")); - assert_eq!( - a.precision.contains(&PrecisionNote::FloatSampleFilter), - filtered, - "{name} on lavapipe" - ); - assert!(!a.precision.contains(&PrecisionNote::HalfSampleFilter)); - assert_eq!( - a.precision.contains(&PrecisionNote::DeviceDepthComparison), - device, - "{name} on lavapipe" - ); - assert!(!a - .requirements - .properties - .contains(&VkProperty::MetalSampler)); - let b = compile(&bc, "k", &m3).unwrap_or_else(|e| panic!("{name} on moltenvk-m3: {e}")); - link_and_validate(&b, &m3).unwrap_or_else(|e| panic!("{name} on moltenvk-m3: {e}")); - assert!(!b.precision.contains(&PrecisionNote::FloatSampleFilter)); - assert!(!b.precision.contains(&PrecisionNote::DeviceDepthComparison)); - assert!( - b.requirements - .properties - .contains(&VkProperty::MetalSampler), - "{name} on moltenvk-m3" - ); - } -} - -/// The depth formats whose linear sample and comparison Metal answers through their color class -/// (`metal::texel_format`). -const DEPTHS: [PixelFormat; 2] = [PixelFormat::Depth32Float, PixelFormat::Depth16Unorm]; - -/// The words of a linear constexpr sampler addressed by AIR code `address` with border code -/// `border`, pixel coordinates where `pixel`, under AIR compare function code `compare` (1 -/// `less` to 7 `always`, 8 `never`). -fn depth_words(address: u64, pixel: bool, border: u64, compare: u64) -> u64 { - linear(address, pixel, border) & !(0xf << 16) | compare << 16 -} - -/// The text of a depth kernel that names its sampler: the constexpr sampler of `words`, or -/// (`None`) runtime sampler slot 0, the parameter after `out`. Its fields are the global, the -/// parameter, the call's operand, the module's sampler-state list, the kernel's argument list, -/// the sampler's metadata node `!6`, and the thread position's argument index. -struct SamplerText { - global: String, - param: &'static str, - operand: &'static str, - states: &'static str, - args: &'static str, - node: &'static str, - tid: u32, -} - -fn sampler_text(words: Option) -> SamplerText { - match words { - Some(w) => SamplerText { - global: format!( - "@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 {w}, i64 0], align 8\n\n" - ), - param: "", - operand: "@__air_sampler_state", - states: "!air.sampler_states = !{!6}\n", - args: "!3, !4, !5, !7", - node: r#"!{!"air.sampler_state", ptr addrspace(2) @__air_sampler_state}"#, - tid: 3, - }, - None => SamplerText { - global: String::new(), - param: ", ptr addrspace(2) %s", - operand: "%s", - states: "", - args: "!3, !4, !5, !6, !7", - node: r#"!{i32 3, !"air.sampler", !"air.location_index", i32 0, i32 1, !"air.arg_type_name", !"sampler", !"air.arg_name", !"s"}"#, - tid: 4, - }, - } -} - -/// A kernel reading `depth2d` slot 0 (`depth2d_array` at layer `layer`) through -/// the constexpr sampler of `words` (runtime sampler slot 0 for `None`, [`sampler_text`]) at level 0 at buffer 0's lane `tid` (a `float4`: the -/// coordinate, and the reference in `z`) with constant offset `offset`: a sample, or where -/// `compare` a comparison against the reference. Buffer 1's lane `tid` is a `float4` whose `x` is -/// the result. -fn depth_kernel( - words: Option, - compare: bool, - layer: Option, - (ox, oy): (i32, i32), -) -> String { - let SamplerText { - global, - param, - operand, - states, - args, - node, - tid, - } = sampler_text(words); - let (dim, tex_ty, layer_arg, layer_ty) = match layer { - Some(l) => ( - "2d_array", - "depth2d_array", - format!("i32 {l}, "), - "i32, ", - ), - None => ("2d", "depth2d", String::new(), ""), - }; - let (name, ref_arg, ref_ty) = match compare { - true => ( - format!("sample_compare_depth_{dim}"), - "float %ref, ", - "float, ", - ), - false => (format!("sample_depth_{dim}"), "", ""), - }; - format!( - r#"{global}define void @k(ptr addrspace(1) %t, ptr addrspace(1) %c, ptr addrspace(1) %out{param}, i32 %tid) {{ - %i = zext i32 %tid to i64 - %p = getelementptr inbounds <4 x float>, ptr addrspace(1) %c, i64 %i - %c4 = load <4 x float>, ptr addrspace(1) %p, align 16 - %uv = shufflevector <4 x float> %c4, <4 x float> zeroinitializer, <2 x i32> - %ref = extractelement <4 x float> %c4, i64 2 - %r = call {{ float, i8 }} @air.{name}.f32(ptr addrspace(1) %t, ptr addrspace(2) {operand}, i32 1, <2 x float> %uv, {layer_arg}{ref_arg}i1 true, <2 x i32> , i1 true, float 0.0, float 0.0, i32 0) - %v = extractvalue {{ float, i8 }} %r, 0 - %v4 = insertelement <4 x float> zeroinitializer, float %v, i64 0 - %q = getelementptr inbounds <4 x float>, ptr addrspace(1) %out, i64 %i - store <4 x float> %v4, ptr addrspace(1) %q, align 16 - ret void -}} - -declare {{ float, i8 }} @air.{name}.f32(ptr addrspace(1), ptr addrspace(2), i32, <2 x float>, {layer_ty}{ref_ty}i1, <2 x i32>, i1, float, float, i32) - -!air.kernel = !{{!0}} -{states}!0 = !{{ptr @k, !1, !2}} -!1 = !{{}} -!2 = !{{{args}}} -!3 = !{{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"{tex_ty}", !"air.arg_name", !"t"}} -!4 = !{{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"c"}} -!5 = !{{i32 2, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"}} -!6 = {node} -!7 = !{{i32 {tid}, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"tid"}} -"# - ) -} - -/// Whether reference `r` passes AIR compare function code `f` against depth `x`, as Metal -/// compares them: a `Depth16Unorm` texture's (`code`, the texel's code) as codes, the reference's -/// the code of its exact product with 65535 (clamped into `[0, 1]`, half up, a NaN kept); a -/// `Depth32Float` texture's as `f32`s. A NaN fails every ordered test and passes `not_equal`. -pub(super) fn depth_passes(f: u64, r: f32, (x, code): (f32, Option)) -> bool { - let (r, x) = match code { - Some(c) if !r.is_nan() => { - let m = f64::from(r.clamp(0.0, 1.0)); - ((m * 65535.0 + 0.5).floor(), c as f64) - } - Some(c) => (f64::NAN, c as f64), - None => (f64::from(r), f64::from(x)), - }; - match f { - 1 => r < x, - 2 => r <= x, - 3 => r > x, - 4 => r >= x, - 5 => r == x, - 6 => r != x, - 7 => true, - 8 => false, - _ => unreachable!("compare code {f}"), - } -} - -/// Runs depth kernel `bc` (through a sampler addressed by `address`, with `pixel` coordinates, -/// constant offset `offset`; on an array of `layers` read at `layer`) on lavapipe for each of -/// [`DEPTHS`] on a 12x8 texture at [`coordinates`]' lanes, each with a reference (a texel's -/// depth on every third lane), against Metal's rule: a sample is the color class's channel 0; a -/// comparison under AIR code `compare` is an `r8Unorm` linear sample of each tap's pass as codes 0 -/// and 255, the border's depth compared as a texel's. A comparison declares a binding with -/// comparison, which a format whose comparison is measured never reads, and one without, through -/// which the emulation fetches its taps (`Linear::fetch`): the texels are bound through the latter -/// alone, the former holding zeros. A kernel sampling through runtime sampler slot 0 reads `word` -/// as the bound sampler's word ([`with_word`]). -fn check_depth( - name: &str, - bc: &[u8], - (address, pixel): (Address, bool), - (offset, layers, layer): ((i32, i32), u32, u32), - (compare, word): (Option, Option), -) { - let p = lavapipe(); - let a = compile(bc, "k", &p).unwrap_or_else(|e| panic!("{name}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name}: {e}")); - assert!(a.precision.contains(&PrecisionNote::FloatSampleFilter)); - assert!( - a.strategies.entries.contains_key("sampler.linear"), - "{name}: {:?}", - a.strategies - ); - let (plan, m) = typed_module(bc, "k", &p).expect("typed module"); - let (w, h) = (12i64, 8i64); - let points = coordinates(w, h); - let scale = if pixel { - (1.0, 1.0) - } else { - (w as f64, h as f64) - }; - let refs = [0.0f32, 0.5, 1.0, -0.25, 0.75, f32::NAN, 1.5, 0.375]; - for (seed, pf) in DEPTHS.iter().enumerate() { - let class = texel_format(*pf).0; - let d16 = *pf == PixelFormat::Depth16Unorm; - let tex = Texels::random(class, w, h, seed as u64 + 31); - let slots = combined_slots(&m); - let mut compares: Vec = slots.iter().map(|(_, c)| *c).collect(); - compares.sort(); - assert_eq!( - compares, - match compare { - Some(_) => vec![false, true], - None => vec![false], - }, - "{name}: the combined bindings' comparisons" - ); - let images: Vec = slots - .iter() - .map(|&(slot, compares)| match compares { - true => Image::new(slot, [w as u32, h as u32, 1], layers, 1, 1), - false => tex.image(slot, 2, layers), - }) - .collect(); - let n = tex.t.len(); - let lanes: Vec<(f64, f64, f32)> = points - .iter() - .enumerate() - .map(|(k, (x, y))| { - let r = match k % 3 { - 0 => tex.fetched(tex.t[(7 * k) % n][0]), - _ => refs[k % refs.len()], - }; - (*x, *y, r) - }) - .collect(); - let bytes: Vec = lanes - .iter() - .flat_map(|(x, y, r)| { - [(x / scale.0) as f32, (y / scale.1) as f32, *r, 0.0].map(f32::to_le_bytes) - }) - .flatten() - .collect(); - let res = resources(&plan, &[bytes, vec![0xab; 16 * lanes.len()]], class); - let res = with_word(res, &a, word); - let out = run_images(&m, &res, &images, lanes.len() as u32, false); - for (lane, ((x, y, r), got)) in lanes.iter().zip(&out).enumerate() { - let at = ( - seen(*x, scale.0, address, pixel), - seen(*y, scale.1, address, pixel), - ); - let rule = (false, false, PlaneRule::Metal); - let want = match compare { - None => expected(&tex, address, at, rule, offset, layer, 0), - Some(f) => { - let pass = |s: Stored| { - let code = match s { - Stored::Code(c) => Some(c), - Stored::Value(_) => None, - }; - i64::from(depth_passes(f, *r, (tex.fetched(s), code))) - }; - let t = tex - .t - .iter() - .map(|s| { - let p = Stored::Code(255 * pass(s[0])); - [p, Stored::Code(0), Stored::Code(0), Stored::Code(255)] - }) - .collect(); - let passes = Texels { - class: texel_format(PixelFormat::R8Unorm).0, - w, - h, - t, - }; - let address = match address { - Address::Border(b) => { - let depth = match d16 { - true => Stored::Code((b[0] * 65535.0) as i64), - false => Stored::Value(b[0] as f32), - }; - Address::Border([pass(depth) as f64, 0.0, 0.0, 1.0]) - } - other => other, - }; - expected(&passes, address, at, rule, offset, layer, 0) - } - }; - assert_eq!( - got[0], - want, - "{name} {pf:?} lane {lane} ({x}, {y}) reference {r}: {:?} vs {:?}", - f32::from_bits(got[0]), - f32::from_bits(want) - ); - } - } -} - -/// A depth texture's linear sample is its color class's (`Depth32Float`'s `R32Float`'s, -/// `Depth16Unorm`'s `R16Unorm`'s; 2,191 lanes), emulated on lavapipe and Metal's on every lane of -/// the interpreter: clamping to the edge, to zero, and to a white border, pixel coordinates, an -/// offset, and an array's layer. -#[test] -fn depth_linear_samples_take_their_color_class() { - const WHITE: [f64; 4] = [1.0; 4]; - let cases = [ - ("edge", (1, false, 0), Address::Edge, (0, 0), None), - ( - "zero", - (0, false, 0), - Address::Border([0.0; 4]), - (0, 0), - None, - ), - ("white", (0, false, 2), Address::Border(WHITE), (0, 0), None), - ("pixel edge", (1, true, 0), Address::Edge, (0, 0), None), - ("offset", (1, false, 0), Address::Edge, (2, -1), None), - ("layer 9", (1, false, 0), Address::Edge, (0, 0), Some(9)), - ]; - for (name, (code, pixel, border), address, offset, layer) in cases { - let words = depth_words(code, pixel, border, 8); - let Some(bc) = assemble(name, &depth_kernel(Some(words), false, layer, offset)) else { - return; - }; - let (layers, at) = layer.map_or((1, 0), |l| (3, l.clamp(0, 2) as u32)); - check_depth( - name, - &bc, - (address, pixel), - (offset, layers, at), - (None, None), - ); - } -} - -/// A linear comparison is an `r8Unorm` linear sample of the taps' passes as codes 0 and 255 -/// (our probes, 8,640 lanes; our probe compares the border's depth as a -/// texel's), on `Depth32Float` and `Depth16Unorm` (whose reference and texels compare as codes): -/// every compare function clamping to the edge, `less` and `greater` against zero and white -/// borders, `less` with an offset, and `less_equal` at an array's layer, on every lane of the -/// interpreter, references equal to a texel's depth and NaN included. (Apple's compiler rejects a -/// constexpr pixel sampler that compares.) -#[test] -fn linear_comparisons_sum_their_passes_as_r8unorm_codes() { - const WHITE: [f64; 4] = [1.0; 4]; - let mut cases = Vec::new(); - for f in 1..=8 { - cases.push((f, (1, false, 0), Address::Edge, (0, 0), None)); - } - for f in [1, 3] { - cases.push((f, (0, false, 0), Address::Border([0.0; 4]), (0, 0), None)); - cases.push((f, (0, false, 2), Address::Border(WHITE), (0, 0), None)); - } - cases.push((1, (1, false, 0), Address::Edge, (2, -1), None)); - cases.push((2, (1, false, 0), Address::Edge, (0, 0), Some(9))); - for (f, (code, pixel, border), address, offset, layer) in cases { - let name = format!( - "compare {f} address {code} border {border} pixel {pixel} {offset:?} {layer:?}" - ); - let words = depth_words(code, pixel, border, f); - let Some(bc) = assemble(&name, &depth_kernel(Some(words), true, layer, offset)) else { - return; - }; - let (layers, at) = layer.map_or((1, 0), |l| (3, l.clamp(0, 2) as u32)); - check_depth( - &name, - &bc, - (address, pixel), - (offset, layers, at), - (Some(f), None), - ); - } -} - -/// `MTLCompareFunction`'s raw values (a runtime sampler word's `COMPARE` field) with the AIR codes -/// of the same functions ([`depth_passes`]). -const RUNTIME_FUNCTIONS: [(u32, u64); 8] = [ - (0, 8), - (1, 1), - (2, 5), - (3, 2), - (4, 3), - (5, 6), - (6, 4), - (7, 7), -]; - -/// A linear comparison through a runtime sampler slot compares each tap under the function its -/// word's `COMPARE` field states, as a constexpr sampler's does under its own, on every lane of the -/// interpreter: every function, clamping to the edge, to zero (beside a transparent and a white -/// border color, which it reads) and to a white border, pixel coordinates, and an array's layer. -#[test] -fn runtime_linear_comparisons_compare_by_the_words_function() { - use SamplerAddressMode as M; - use SamplerBorderColor as B; - let mut cases = Vec::new(); - for (raw, code) in RUNTIME_FUNCTIONS { - cases.push(( - raw, - code, - (M::ClampToEdge, B::TransparentBlack), - false, - None, - )); - } - cases.push((3, 2, (M::ClampToZero, B::TransparentBlack), false, None)); - cases.push((4, 3, (M::ClampToZero, B::OpaqueWhite), false, None)); - cases.push((1, 1, (M::ClampToBorderColor, B::OpaqueWhite), false, None)); - cases.push((5, 6, (M::ClampToEdge, B::TransparentBlack), true, None)); - cases.push((2, 5, (M::ClampToEdge, B::TransparentBlack), false, Some(9))); - for (raw, code, (mode, border), pixel, layer) in cases { - let name = format!("runtime compare {raw} {mode:?} {border:?} pixel {pixel} {layer:?}"); - let Some(bc) = assemble(&name, &depth_kernel(None, true, layer, (0, 0))) else { - return; - }; - let word = runtime_word(mode, pixel, border) | raw << SamplerWord::COMPARE_SHIFT; - // `ClampToZero` reads the border color as `ClampToBorderColor` does. - let address = match (mode, border) { - (M::ClampToEdge, _) => Address::Edge, - (_, B::TransparentBlack) => Address::Border([0.0; 4]), - _ => Address::Border([1.0; 4]), - }; - let (layers, at) = layer.map_or((1, 0), |l: i32| (3, l.clamp(0, 2) as u32)); - check_depth( - &name, - &bc, - (address, pixel), - ((0, 0), layers, at), - (Some(code), Some(word)), - ); - } -} - -/// A runtime sampler's `sample_compare` and `gather_compare` of a 2D depth texture or array compare -/// in the shader by the word's function on every committed profile without -/// `VkProperty::MetalSampler`. A gather fetches its texels, addressed by the word, where the -/// slot's format is measured, and gathers them without comparison elsewhere (no `Dref` -/// instruction, a texture slot that no comparison reads); a sample branches on the word's filter -/// between the one texel, fetched where the word states no mip filter and sampled without -/// comparison through the slot's second binding without comparison otherwise, and the filtered -/// comparison, whose device arm keeps its `Dref` sample. Both read the word's compare function, -/// coordinates, address modes and border color, and a sample its filter; only the sample notes -/// `DeviceDepthComparison`. On a profile with the property the device's comparison is Metal's -/// own: the module keeps its `Dref` instructions and requires the property. Each validates. (The -/// interpreter models no sample or gather; the runtime lane's `depth_compares` runs these -/// comparisons on each device against Metal's measured rule.) -#[test] -fn runtime_nearest_comparisons_and_comparison_gathers_compare_in_the_shader() { - let profiles = crate::spirv::testing::committed_exact_profiles().expect("profiles"); - for (gather, layer) in [ - (false, None), - (true, None), - (false, Some(1)), - (true, Some(1)), - ] { - let name = format!("runtime gather {gather} layer {layer:?}"); - let text = match gather { - true => gather_compare_kernel(None, layer), - false => depth_kernel(None, true, layer, (0, 0)), - }; - let Some(bc) = assemble(&name, &text) else { - return; - }; - for (stem, p) in &profiles { - let what = format!("{name} on {stem}"); - let a = compile(&bc, "k", p).unwrap_or_else(|e| panic!("{what}: {e}")); - link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: {e}")); - let metal = p - .fields() - .enabled - .properties - .contains(&VkProperty::MetalSampler); - let ops = opcodes(&a.module.words); - let dref = ops.iter().any(|o| DREF_OPS.contains(o)); - let required = a - .requirements - .properties - .contains(&VkProperty::MetalSampler); - let compares = a.interface.slots.values().any(|slot| { - matches!(slot, crate::pipeline::interface::SlotInterface::Texture(t) if t.depth_compare) - }); - let fields = a.interface.read_keys().into_iter().find_map(|k| match k { - SpecKey::SamplerState { fields, .. } => Some(fields), - _ => None, - }); - // A sample's filtered arm may compare on the device; its nearest mip filter's texel is - // the device's read, which `DeviceTexelDenormals` names; a gather's texels - // are fetched. - assert_eq!( - a.precision.contains(&PrecisionNote::DeviceDepthComparison), - !metal && !gather, - "{what}" - ); - if metal { - assert_eq!((dref, required, compares), (true, true, true), "{what}"); - continue; - } - assert_eq!( - (dref, required, compares), - (!gather, false, !gather), - "{what}" - ); - let fields = fields.unwrap_or_else(|| panic!("{what}: no sampler word")); - assert_eq!( - fields & SamplerWord::COMPARE, - SamplerWord::COMPARE, - "{what}" - ); - let filters = SamplerWord::MIN_LINEAR | SamplerWord::MIP_FILTER; - assert_eq!(fields & filters == filters, !gather, "{what}"); - // The fetch's addressing by the word, and its `OpImageFetch`. - let addressing = SamplerWord::PIXEL_COORDINATES - | SamplerWord::ADDRESS[0] - | SamplerWord::ADDRESS[1] - | SamplerWord::BORDER; - assert_eq!(fields & addressing, addressing, "{what}"); - assert!(ops.contains(&95), "{what}"); - // The one-texel arm's sample without comparison: `OpImageSampleExplicitLod`. - assert_eq!(ops.contains(&88), !gather, "{what}"); - } - // A sample's two bindings of the slot: the filtered arm's with comparison, and the - // one-texel arm's without. - let (_, m) = typed_module(&bc, "k", &lavapipe()).expect("typed module"); - let mut compares: Vec = combined_slots(&m).iter().map(|(_, c)| *c).collect(); - compares.sort(); - let want = match gather { - true => vec![false], - false => vec![false, true], - }; - assert_eq!(compares, want, "{name}"); - } -} - -/// The words of a constexpr sampler with nearest filters and no mip filter, every axis addressed -/// by `address` (AIR codes, as [`sampler_words`]) with border color code `border`, comparing -/// under AIR code `compare`. -fn nearest_depth_words(address: u64, border: u64, compare: u64) -> u64 { - sampler_words(0, 0, address, false, border) & !(0xf << 16) | compare << 16 -} - -/// A kernel gathering `depth2d` slot 0 (`depth2d_array` at layer `layer`) with -/// comparison through the constexpr sampler of `words` (runtime sampler slot 0 for `None`, -/// [`sampler_text`]) at buffer 0's lane `tid` (a `float4`: the coordinate, and the reference in -/// `z`), the four passes to buffer 1's lane `tid`. -fn gather_compare_kernel(words: Option, layer: Option) -> String { - let SamplerText { - global, - param, - operand, - states, - args, - node, - tid, - } = sampler_text(words); - let (dim, tex_ty, layer_arg, layer_ty) = match layer { - Some(l) => ( - "2d_array", - "depth2d_array", - format!("i32 {l}, "), - "i32, ", - ), - None => ("2d", "depth2d", String::new(), ""), - }; - format!( - r#"{global}define void @k(ptr addrspace(1) %t, ptr addrspace(1) %c, ptr addrspace(1) %out{param}, i32 %tid) {{ - %i = zext i32 %tid to i64 - %p = getelementptr inbounds <4 x float>, ptr addrspace(1) %c, i64 %i - %c4 = load <4 x float>, ptr addrspace(1) %p, align 16 - %uv = shufflevector <4 x float> %c4, <4 x float> zeroinitializer, <2 x i32> - %ref = extractelement <4 x float> %c4, i64 2 - %r = call {{ <4 x float>, i8 }} @air.gather_compare_depth_{dim}.f32(ptr addrspace(1) %t, ptr addrspace(2) {operand}, i32 1, <2 x float> %uv, {layer_arg}float %ref, i1 true, <2 x i32> zeroinitializer, i32 0) - %v = extractvalue {{ <4 x float>, i8 }} %r, 0 - %q = getelementptr inbounds <4 x float>, ptr addrspace(1) %out, i64 %i - store <4 x float> %v, ptr addrspace(1) %q, align 16 - ret void -}} - -declare {{ <4 x float>, i8 }} @air.gather_compare_depth_{dim}.f32(ptr addrspace(1), ptr addrspace(2), i32, <2 x float>, {layer_ty}float, i1, <2 x i32>, i32) - -!air.kernel = !{{!0}} -{states}!0 = !{{ptr @k, !1, !2}} -!1 = !{{}} -!2 = !{{{args}}} -!3 = !{{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"{tex_ty}", !"air.arg_name", !"t"}} -!4 = !{{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"c"}} -!5 = !{{i32 2, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"}} -!6 = {node} -!7 = !{{i32 {tid}, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"tid"}} -"# - ) -} - -/// The opcodes of a SPIR-V module's instructions. -fn opcodes(words: &[u32]) -> Vec { - let mut out = Vec::new(); - let mut i = 5; - while i < words.len() { - out.push((words[i] & 0xffff) as u16); - i += ((words[i] >> 16) as usize).max(1); - } - out -} - -/// A nearest comparison through a constexpr sampler with a nearest mip filter and a -/// `min_lod_clamp`, whose texels the device reads (the exceptions: the shader does not fetch beside -/// the clamp), is the shader's own comparison on every committed profile without -/// `VkProperty::MetalSampler` (no `Dref` instruction): it records the device's read, -/// `PrecisionNote::DeviceTexelDenormals`, and not `PrecisionNote::DeviceDepthComparison`, which -/// names the device's comparisons alone. On a profile with the property the device's comparison is -/// Metal's own, and neither is recorded. Each validates. (Without a mip filter Metal reads level 0 -/// whatever the clamp, so the shader fetches that texel itself and records neither.) -#[test] -fn a_comparison_of_texels_the_device_reads_notes_the_read_alone() { - let name = "a nearest comparison with a min_lod_clamp"; - let words = sampler_words(0, 1, 1, false, 0) & !(0xf << 16) | 2 << 16; - let text = depth_kernel(Some(words), true, None, (0, 0)).replace( - "i1 true, float 0.0, float 0.0, i32 0)", - "i1 false, float 0.0, float 1.0, i32 0)", - ); - assert!(text.contains("float 1.0, i32 0)"), "{name}"); - let Some(bc) = assemble(name, &text) else { - return; - }; - let profiles = crate::spirv::testing::committed_exact_profiles().expect("profiles"); - for (stem, p) in &profiles { - let what = format!("{name} on {stem}"); - let a = compile(&bc, "k", p).unwrap_or_else(|e| panic!("{what}: {e}")); - link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: {e}")); - let metal = p - .fields() - .enabled - .properties - .contains(&VkProperty::MetalSampler); - let dref = opcodes(&a.module.words) - .iter() - .any(|o| DREF_OPS.contains(o)); - assert_eq!(dref, metal, "{what}"); - assert!( - !a.precision.contains(&PrecisionNote::DeviceDepthComparison), - "{what}" - ); - assert_eq!( - a.precision.contains(&PrecisionNote::DeviceTexelDenormals), - !metal, - "{what}" - ); - } -} - -/// `OpImageSampleDrefImplicitLod`, `OpImageSampleDrefExplicitLod`, and `OpImageDrefGather`. -const DREF_OPS: [u16; 3] = [89, 90, 97]; - -/// The shader's own comparisons: a nearest `sample_compare` and a `gather_compare` of a 2D depth -/// texture or array through a constexpr sampler read their texels without comparison on every -/// committed profile without `VkProperty::MetalSampler`: no `Dref` instruction, a texture slot that -/// no comparison reads (so a `Depth32Float` texture held with a twin is read through its -/// `R32_SFLOAT` image), and no `RestrictedDepthRange`; every compare function, clamping to the -/// edge, repeating, mirroring, and to a white border, and at an array's layer. On a profile with -/// the property the device's comparison is Metal's own: the module keeps its `Dref` instruction and -/// requires the property. Each validates. (The interpreter models no sample or gather; the runtime -/// lane's `depth_compares` runs these comparisons on each device against Metal's measured rule.) -#[test] -fn nearest_comparisons_and_comparison_gathers_compare_in_the_shader() { - let mut cases = Vec::new(); - for f in 1..=8 { - cases.push((f, false, (1, 0), None)); - cases.push((f, true, (1, 0), None)); - } - for gather in [false, true] { - for (address, border) in [(0, 2), (2, 0), (3, 0)] { - cases.push((2, gather, (address, border), None)); - } - cases.push((5, gather, (1, 0), Some(1))); - } - let profiles = crate::spirv::testing::committed_exact_profiles().expect("profiles"); - for (f, gather, (address, border), layer) in cases { - let name = format!("compare {f} gather {gather} address {address} layer {layer:?}"); - let words = nearest_depth_words(address, border, f); - let text = match gather { - true => gather_compare_kernel(Some(words), layer), - false => depth_kernel(Some(words), true, layer, (0, 0)), - }; - let Some(bc) = assemble(&name, &text) else { - return; - }; - for (stem, p) in &profiles { - let what = format!("{name} on {stem}"); - let a = compile(&bc, "k", p).unwrap_or_else(|e| panic!("{what}: {e}")); - link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: {e}")); - let metal = p - .fields() - .enabled - .properties - .contains(&VkProperty::MetalSampler); - let dref = opcodes(&a.module.words) - .iter() - .any(|o| DREF_OPS.contains(o)); - let required = a - .requirements - .properties - .contains(&VkProperty::MetalSampler); - let compares = a.interface.slots.values().any(|slot| { - matches!(slot, crate::pipeline::interface::SlotInterface::Texture(t) if t.depth_compare) - }); - assert_eq!((dref, required, compares), (metal, metal, metal), "{what}"); - if !metal { - assert!( - !a.precision.contains(&PrecisionNote::RestrictedDepthRange), - "{what}" - ); - } - // Its texels are fetched at a level the function knows. - assert!( - !a.precision.contains(&PrecisionNote::DeviceDepthComparison), - "{what}" - ); - } - } -} - -/// A kernel comparing `depth2d` slot 0 through the constexpr sampler of `words` at buffer -/// 0's lane `tid` (a `float4`: the coordinate, the reference in `z`, and the level in `w`) at that -/// level; buffer 1's lane `tid` is a `float4` whose `x` is the pass. -fn level_compare_kernel(words: u64) -> String { - format!( - r#"@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 {words}, i64 0], align 8 - -define void @k(ptr addrspace(1) %t, ptr addrspace(1) %c, ptr addrspace(1) %out, i32 %tid) {{ - %i = zext i32 %tid to i64 - %p = getelementptr inbounds <4 x float>, ptr addrspace(1) %c, i64 %i - %c4 = load <4 x float>, ptr addrspace(1) %p, align 16 - %uv = shufflevector <4 x float> %c4, <4 x float> zeroinitializer, <2 x i32> - %ref = extractelement <4 x float> %c4, i64 2 - %lod = extractelement <4 x float> %c4, i64 3 - %r = call {{ float, i8 }} @air.sample_compare_depth_2d.f32(ptr addrspace(1) %t, ptr addrspace(2) @__air_sampler_state, i32 1, <2 x float> %uv, float %ref, i1 true, <2 x i32> zeroinitializer, i1 true, float %lod, float 0.0, i32 0) - %v = extractvalue {{ float, i8 }} %r, 0 - %v4 = insertelement <4 x float> zeroinitializer, float %v, i64 0 - %q = getelementptr inbounds <4 x float>, ptr addrspace(1) %out, i64 %i - store <4 x float> %v4, ptr addrspace(1) %q, align 16 - ret void -}} - -declare {{ float, i8 }} @air.sample_compare_depth_2d.f32(ptr addrspace(1), ptr addrspace(2), i32, <2 x float>, float, i1, <2 x i32>, i1, float, float, i32) - -!air.kernel = !{{!0}} -!air.sampler_states = !{{!6}} -!0 = !{{ptr @k, !1, !2}} -!1 = !{{}} -!2 = !{{!3, !4, !5, !7}} -!3 = !{{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"depth2d", !"air.arg_name", !"t"}} -!4 = !{{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"c"}} -!5 = !{{i32 2, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"}} -!6 = !{{!"air.sampler_state", ptr addrspace(2) @__air_sampler_state}} -!7 = !{{i32 3, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"tid"}} -"# - ) -} - -/// The pass bits (`1.0` or `0.0`) of reference `r` against depth tap `x` of `tex` under AIR -/// compare function code `f` ([`depth_passes`]): a stored texel's, or the border's depth, which -/// Metal compares as a texel's. -fn tap_pass(tex: &Texels, f: u64, r: f32, x: Tap) -> u32 { - let d16 = matches!(family(tex.class), Family::Norm { .. }); - let (depth, code) = match x { - Tap::Stored(s @ Stored::Code(c)) => (tex.fetched(s), Some(c)), - Tap::Stored(s @ Stored::Value(_)) => (tex.fetched(s), None), - Tap::Border(b) => (b as f32, d16.then_some((b * 65535.0) as i64)), - }; - match depth_passes(f, r, (depth, code)) { - true => 1.0f32.to_bits(), - false => 0.0f32.to_bits(), - } -} - -/// The lanes of a comparison check on a `w`x`h` texture `tex`: [`coordinates`]', each with a -/// reference (a texel's depth on every third lane), and level `levels[k % levels.len()]`. -fn compare_lanes(tex: &Texels, w: i64, h: i64, levels: &[f32]) -> Vec<(f64, f64, f32, f32)> { - let refs = [0.0f32, 0.5, 1.0, -0.25, 0.75, f32::NAN, 1.5, 0.375]; - let n = tex.t.len(); - coordinates(w, h) - .iter() - .enumerate() - .map(|(k, (x, y))| { - let r = match k % 3 { - 0 => tex.fetched(tex.t[(7 * k) % n][0]), - _ => refs[k % refs.len()], - }; - (*x, *y, r, levels[k % levels.len()]) - }) - .collect() -} - -/// Runs comparison kernel `bc` (a nearest `sample_compare` at level 0, or a `gather_compare` -/// where `gather`) through a sampler addressed by `address`, comparing under AIR code `f`, with -/// constant offset `offset`, on an array of `layers` read at `layer`, on lavapipe for each of -/// [`DEPTHS`] on a 12x8 texture at [`compare_lanes`], against Metal's rule: the texel at `floor` of -/// Metal's position, or the gather's four at its quantized position in gather order, each compared -/// as a texel, the border's depth included. The shader fetches them through the one binding the -/// comparison declares, which does not compare; the interpreter models no device sample or gather, -/// so every lane reads the fetches. -fn check_compared( - name: &str, - bc: &[u8], - (address, gather, f): (Address, bool, u64), - (offset, layers, layer): ((i32, i32), u32, u32), -) { - let p = lavapipe(); - let a = compile(bc, "k", &p).unwrap_or_else(|e| panic!("{name}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name}: {e}")); - let dref = opcodes(&a.module.words) - .iter() - .any(|o| DREF_OPS.contains(o)); - assert!(!dref, "{name}: a Dref instruction"); - let (plan, m) = typed_module(bc, "k", &p).expect("typed module"); - let (w, h) = (12i64, 8i64); - for (seed, pf) in DEPTHS.iter().enumerate() { - let class = texel_format(*pf).0; - let tex = Texels::random(class, w, h, seed as u64 + 47); - let slots = combined_slots(&m); - let compares: Vec = slots.iter().map(|(_, c)| *c).collect(); - assert_eq!(compares, [false], "{name}: the combined bindings"); - let images: Vec = slots - .iter() - .map(|&(slot, _)| tex.image(slot, 2, layers)) - .collect(); - let lanes = compare_lanes(&tex, w, h, &[0.0]); - let bytes: Vec = lanes - .iter() - .flat_map(|(x, y, r, _)| { - [(x / w as f64) as f32, (y / h as f64) as f32, *r, 0.0].map(f32::to_le_bytes) - }) - .flatten() - .collect(); - let res = resources(&plan, &[bytes, vec![0xab; 16 * lanes.len()]], class); - let out = run_images(&m, &res, &images, lanes.len() as u32, false); - let (ox, oy) = (i64::from(offset.0), i64::from(offset.1)); - for (lane, ((x, y, r, _), got)) in lanes.iter().zip(&out).enumerate() { - let (sx, sy) = ( - seen(*x, w as f64, address, false), - seen(*y, h as f64, address, false), - ); - let want: Vec = match gather { - true => { - let (i, j) = (split(sx).0 + ox, split(sy).0 + oy); - [(i, j + 1), (i + 1, j + 1), (i + 1, j), (i, j)] - .iter() - .map(|&at| tap_pass(&tex, f, *r, tap(&tex, address, layer, at, 0))) - .collect() - } - false => { - let at = (sx.floor() as i64 + ox, sy.floor() as i64 + oy); - vec![tap_pass(&tex, f, *r, tap(&tex, address, layer, at, 0))] - } - }; - assert_eq!( - got[..want.len()], - want[..], - "{name} {pf:?} lane {lane} ({x}, {y}) reference {r}" - ); - } - } -} - -/// A nearest `sample_compare` and a `gather_compare` of a 2D depth texture or array through a -/// constexpr sampler fetch their texels on a device without `VkProperty::MetalSampler`, so a -/// denormal texel is compared as Metal compares it, and compare as Metal does on every lane of the -/// interpreter: every compare function clamping to the edge, repeating, mirroring, to zero and to a -/// white border, an offset (a sample's), and an array's layer, on `Depth32Float` and -/// `Depth16Unorm`, references equal to a texel's depth and NaN included. -#[test] -fn fetched_comparisons_take_metals_texels() { - const WHITE: [f64; 4] = [1.0; 4]; - let mut cases = Vec::new(); - for gather in [false, true] { - for f in 1..=8 { - cases.push((gather, f, (1, 0), Address::Edge, (0, 0), None)); - } - cases.push((gather, 2, (2, 0), Address::Repeat, (0, 0), None)); - cases.push((gather, 4, (3, 0), Address::Mirror, (0, 0), None)); - cases.push((gather, 1, (0, 0), Address::Border([0.0; 4]), (0, 0), None)); - cases.push((gather, 3, (0, 2), Address::Border(WHITE), (0, 0), None)); - cases.push((gather, 2, (1, 0), Address::Edge, (0, 0), Some(9))); - } - cases.push((false, 5, (1, 0), Address::Edge, (2, -1), None)); - cases.push((false, 2, (2, 0), Address::Repeat, (-3, 1), None)); - for (gather, f, (code, border), address, offset, layer) in cases { - let name = format!( - "gather {gather} compare {f} address {code} border {border} {offset:?} {layer:?}" - ); - let words = nearest_depth_words(code, border, f); - let text = match gather { - true => gather_compare_kernel(Some(words), layer), - false => depth_kernel(Some(words), true, layer, offset), - }; - let Some(bc) = assemble(&name, &text) else { - return; - }; - let (layers, at) = layer.map_or((1, 0), |l| (3, l.clamp(0, 2) as u32)); - check_compared(&name, &bc, (address, gather, f), (offset, layers, at)); - } -} - -/// A nearest comparison under a nearest mip filter at a dynamic level fetches its texel from the -/// level Metal reads (`L + 1` where the level's fraction on sixty-fourths passes one half), clamped -/// into the texture's three levels, at Metal's position on that level, on every lane of the -/// interpreter. -#[test] -fn a_fetched_comparison_reads_metals_level() { - let words = sampler_words(0, 1, 1, false, 0) & !(0xf << 16) | 2 << 16; - let Some(bc) = assemble("levels", &level_compare_kernel(words)) else { - return; - }; - let p = lavapipe(); - let a = compile(&bc, "k", &p).unwrap_or_else(|e| panic!("levels: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("levels: {e}")); - let (plan, m) = typed_module(&bc, "k", &p).expect("typed module"); - let snap = crate::lower::sampler::level::LevelSnap { - mip: crate::air::abi::MipFilter::Nearest, - min: 0.0f32.to_bits(), - max: 65504.0f32.to_bits(), - }; - let levels = [ - -1.0f32, - 0.0, - 0.25, - 0.5, - 0.5078125, - 0.515625, - 0.75, - 1.0, - 1.4, - 1.53125, - 2.0, - 2.6, - 7.0, - f32::NAN, - f32::INFINITY, - ]; - let (w, h) = (12i64, 8i64); - for (seed, pf) in DEPTHS.iter().enumerate() { - let class = texel_format(*pf).0; - let texs: Vec = (0..3) - .map(|l| Texels::random(class, w >> l, h >> l, seed as u64 + 61 + l as u64)) - .collect(); - let slot = combined_slot(&m); - let mut image = Image::new(slot, [w as u32, h as u32, 1], 1, 3, 1); - for (l, tex) in texs.iter().enumerate() { - for y in 0..tex.h as u32 { - for x in 0..tex.w as u32 { - let at = image.index(l as u32, 0, 0, [x, y, 0]).expect("texel"); - let v = tex.texel(0, i64::from(x), i64::from(y)); - image.texels[at] = v.map(|c| tex.fetched(c).to_bits()); - } - } - } - let lanes = compare_lanes(&texs[0], w, h, &levels); - let bytes: Vec = lanes - .iter() - .flat_map(|(x, y, r, l)| { - [(x / w as f64) as f32, (y / h as f64) as f32, *r, *l].map(f32::to_le_bytes) - }) - .flatten() - .collect(); - let res = resources(&plan, &[bytes, vec![0xab; 16 * lanes.len()]], class); - let out = run_images(&m, &res, &[image], lanes.len() as u32, false); - for (lane, ((x, y, r, l), got)) in lanes.iter().zip(&out).enumerate() { - let level = (snap.of(*l) as usize).min(2); - let tex = &texs[level]; - let (u, v) = ( - f64::from((x / w as f64) as f32), - f64::from((y / h as f64) as f32), - ); - let (lw, lh) = (tex.w as f64, tex.h as f64); - let (sx, sy) = ( - seen(u * lw, lw, Address::Edge, false), - seen(v * lh, lh, Address::Edge, false), - ); - let at = (sx.floor() as i64, sy.floor() as i64); - let want = tap_pass(tex, 2, *r, tap(tex, Address::Edge, 0, at, 0)); - assert_eq!( - got[0], want, - "{pf:?} lane {lane} ({x}, {y}) level {l} (Metal's {level}) reference {r}" - ); - } - } -} - -/// The emulation is fetches, integer and float arithmetic, and a branch on a specialization -/// constant, which every Vulkan 1.2 device runs: a 2D, a 1D, and a 3D linear `half` sample -/// compile and pass L3 on every committed profile. -#[test] -fn the_emulation_validates_on_every_committed_profile() { - let white = linear(0, false, 2); - let forms = [ - ("2d", Form::Plain { offset: (1, -1) }), - ("1d", Form::OneD), - ("3d", Form::ThreeD { offset: (1, 0, -1) }), - ]; - for (name, form) in forms { - let Some(bc) = assemble(name, &kernel(Some(white), form)) else { - return; - }; - for (stem, p) in crate::spirv::testing::committed_exact_profiles().expect("profiles") { - let a = compile(&bc, "k", &p).unwrap_or_else(|e| panic!("{name} on {stem}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name} on {stem}: {e}")); - } - } -} - -/// The plan's word estimate bounds the emitted module of every linear sample form, with a `half` or -/// `float` result, through a constexpr sampler or a runtime one, of the comparisons whose texels -/// the shader fetches, and of the public linear `half` fixtures and the runtime-sampler fixture on -/// every committed profile. -#[test] -fn the_linear_estimate_bounds_its_emission() { - use crate::budget::SPIRV_WORDS; - use crate::library::FunctionConstantValues; - use crate::lower::select::LowerInputs; - use crate::pipeline::compile::{compile_bitcode, plan_bitcode, EntryRef}; - use crate::pipeline::testing::{engine_dir, meter}; - let mut modules: Vec<(String, Vec, String)> = Vec::new(); - for (name, code, form, float) in [ - ("2d white offset", 0, Form::Plain { offset: (1, -1) }, false), - ("2d mirror", 3, Form::Plain { offset: (0, 0) }, false), - ("array", 1, Form::Array { layer: 1 }, false), - ("1d white", 0, Form::OneD, false), - ( - "2d float white offset", - 0, - Form::Plain { offset: (1, -1) }, - true, - ), - ("1d float white", 0, Form::OneD, true), - ( - "3d white offset", - 0, - Form::ThreeD { offset: (1, -1, 2) }, - false, - ), - ("3d mirror", 3, Form::ThreeD { offset: (0, 0, 0) }, false), - ( - "3d float white offset", - 0, - Form::ThreeD { offset: (1, -1, 2) }, - true, - ), - ] { - let k = kernel_of(Some(linear(code, false, 2)), form, float); - let Some(bc) = assemble(name, &k) else { - return; - }; - modules.push((name.to_string(), bc, "k".to_string())); - } - for (name, form, float) in [ - ("2d runtime offset", Form::Plain { offset: (1, -1) }, false), - ("array runtime", Form::Array { layer: 1 }, false), - ("1d runtime", Form::OneD, false), - ("2d float runtime", Form::Plain { offset: (0, 0) }, true), - ( - "3d runtime offset", - Form::ThreeD { offset: (1, -1, 2) }, - false, - ), - ("3d float runtime", Form::ThreeD { offset: (0, 0, 0) }, true), - ] { - let Some(bc) = assemble(name, &kernel_of(None, form, float)) else { - return; - }; - modules.push((name.to_string(), bc, "k".to_string())); - } - // Depth samples and comparisons. - for (name, compare, layer) in [ - ("depth white offset", false, None), - ("depth array", false, Some(1)), - ("comparison white offset", true, None), - ("comparison array", true, Some(1)), - ] { - let words = depth_words(0, false, 2, 1); - let Some(bc) = assemble(name, &depth_kernel(Some(words), compare, layer, (1, -1))) else { - return; - }; - modules.push((name.to_string(), bc, "k".to_string())); - } - // Comparisons whose texels the shader fetches. - let level_words = sampler_words(0, 1, 3, false, 2) & !(0xf << 16) | 2 << 16; - for (name, text) in [ - ( - "fetched gather white", - gather_compare_kernel(Some(nearest_depth_words(0, 2, 2)), None), - ), - ( - "fetched gather array mirror", - gather_compare_kernel(Some(nearest_depth_words(3, 0, 2)), Some(1)), - ), - ( - "fetched nearest white offset", - depth_kernel(Some(nearest_depth_words(0, 2, 2)), true, None, (1, -1)), - ), - ("fetched nearest level", level_compare_kernel(level_words)), - // A runtime sampler's comparisons. - ( - "runtime comparison offset", - depth_kernel(None, true, None, (1, -1)), - ), - ( - "runtime comparison array", - depth_kernel(None, true, Some(1), (0, 0)), - ), - ("runtime gather", gather_compare_kernel(None, None)), - // A runtime sampler's comparison at the level its word reads, and a blend of two levels' - // comparisons under a linear mip filter. - ( - "runtime comparison level", - levels::runtime_level_kernel(levels::Stated::Level), - ), - ( - "blended comparison level", - level_compare_kernel(sampler_words(0, 2, 1, false, 0) & !(0xf << 16) | 2 << 16), - ), - ] { - let Some(bc) = assemble(name, &text) else { - return; - }; - modules.push((name.to_string(), bc, "k".to_string())); - } - let Ok(bc) = llvm_assemble(&engine_dir().join("msf_runtime_samplers.ll")) else { - eprintln!("SKIPPED: llvm-as"); - return; - }; - for entry in [ - "msf_slot2d_linear_edge", - "msf_slot2d_linear_zero_pixel", - "msf_slot2d_linear_repeat_half", - "msf_slot3d_linear_mirror", - "msf_slot1d_linear_mirror", - "msf_slotcube_linear", - ] { - modules.push((entry.to_string(), bc.clone(), entry.to_string())); - } - for name in [ - "hlf_half_forms", - "hlf_half_address", - "hlf_half_dims", - "hlf_float_linear", - ] { - let Ok(bc) = llvm_assemble(&engine_dir().join(format!("{name}.ll"))) else { - eprintln!("SKIPPED: llvm-as"); - return; - }; - modules.push((name.to_string(), bc, name.to_string())); - } - for (name, bc, entry) in &modules { - for (stem, p) in crate::spirv::testing::committed_exact_profiles().expect("profiles") { - let what = format!("{name} on {stem}"); - let (entry, consts) = ( - EntryRef::Name(entry.as_str()), - FunctionConstantValues::defaults(), - ); - let inputs = LowerInputs::new(); - let plan = plan_bitcode(bc, entry, &consts, &p, &inputs, &mut meter()) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let a = compile_bitcode(bc, entry, &consts, &p, &inputs, &mut meter(), SPIRV_WORDS) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let words = a.module.words.len() as u64; - eprintln!("{what}: estimate {} emitted {words}", plan.estimate.words); - assert!( - plan.estimate.words >= words, - "{what}: estimate {} < emitted {words}", - plan.estimate.words - ); - } - } -} - -/// The device of committed profile `stem`. -pub(super) fn device_of(stem: &str) -> crate::device::Device { - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles") - .join(format!("{stem}.json")); - let text = std::fs::read_to_string(&path).expect("profile"); - let desc = - crate::device::DeviceDescription::from_khronos_json(&text, None).expect("description"); - crate::device::Device::new(desc, EXACT_SAMPLING).expect("device") -} - -/// The kernel of bitcode `bc` compiled into a compute pipeline on `dev`. -pub(super) fn notes_pipeline( - dev: &crate::device::Device, - bc: &[u8], -) -> crate::pipeline::ComputePipeline { - use crate::pipeline::{ComputePipelineDescriptor, FunctionDescriptor, StageSource}; - let lib = crate::library::Library::from_air(bc).expect("library"); - let f = lib.function("k").expect("function"); - let compiled = dev - .compile_function( - &FunctionDescriptor::new(f), - &crate::lower::select::LowerInputs::new(), - &crate::budget::Budget::standard(), - ) - .expect("compile"); - dev.compile_compute_pipeline( - &ComputePipelineDescriptor::new(StageSource::Compiled(compiled)), - &crate::budget::Budget::standard(), - ) - .expect("pipeline") -} - -/// The notes of pipeline `p` on `dev` planned for texture slot 0 bound as a `ty` texture in `pf`, -/// buffers 0 to 2 bound, and sampler slot 0 bound to `sampler` (or nothing): its stage's notes -/// under the plan's specialization, where a test of the format bound at texture slot 0 -/// (`SpecKey::BoundTexelFormat`), which no pipeline's key carries, reads `pf`'s class -/// (`metal::format::bound_texel_format`), as a runtime reads it at each draw or dispatch. -pub(super) fn notes_bound( - p: &crate::pipeline::ComputePipeline, - dev: &crate::device::Device, - texture: (crate::metal::TextureType, PixelFormat), - sampler: Option, -) -> Vec { - let pf = texture.1; - let plan = plan_bound(p, dev, texture, sampler); - p.stage - .precision_notes_bound(&plan.specialization, &|k| match k { - SpecKey::BoundTexelFormat(SlotRef { - class: SlotClass::Texture, - index: 0, - .. - }) => Some(u64::from(crate::metal::format::bound_texel_format(pf))), - k => plan.specialized_value(k), - }) -} - -/// The plan of pipeline `p` on `dev` for texture slot 0 bound as a `ty` texture in `pf`, buffers -/// 0 to 2 bound, and sampler slot 0 bound to `sampler` (or nothing). -fn plan_bound( - p: &crate::pipeline::ComputePipeline, - dev: &crate::device::Device, - (ty, pf): (crate::metal::TextureType, PixelFormat), - sampler: Option, -) -> crate::bind::BindingPlan { - let mut facts = crate::bind::TextureFacts::new(ty, pf); - facts.usage = crate::metal::TextureUsage::SHADER_READ; - plan_facts(p, dev, facts, sampler) -} - -/// [`plan_bound`] with texture slot 0 bound to a texture of `facts`. -fn plan_facts( - p: &crate::pipeline::ComputePipeline, - dev: &crate::device::Device, - facts: crate::bind::TextureFacts, - sampler: Option, -) -> crate::bind::BindingPlan { - use crate::bind::{BindState, BoundBuffer, BoundSampler, BoundTexture, StageTable}; - let pf = facts.pixel_format; - let mut t = StageTable::default(); - t.textures.insert( - 0, - BoundTexture::Texture { - facts, - resource_id: None, - }, - ); - for (slot, address) in [(0u32, 0x1_0000u64), (1, 0x2_0000), (2, 0x3_0000)] { - t.buffers.insert( - slot, - BoundBuffer::Buffer { - length: 4096, - offset: 0, - gpu_address: address, - device_address: None, - attribute_stride: None, - }, - ); - } - if let Some(d) = sampler { - t.samplers.insert(0, BoundSampler::new(d)); - } - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, t); - p.plan(dev, &s.shape()) - .unwrap_or_else(|e| panic!("plan {pf:?}: {e}")) -} - -/// A texture slot's format class is data the function reads from its push field, so no format -/// splits a pipeline but by its kind of `half` conversion: on lavapipe every format gives one -/// specialization, and on MoltenVK every format of the plain arm (`SpecKey::PlainHalfTexels`) -/// gives one, a 16-bit normalized one another that differs only in that bit; through any sampler, -/// and the binder pushes each format's class. -#[test] -fn formats_share_a_specialization_since_the_class_is_data() { - use crate::metal::TextureType; - let formats = [ - PixelFormat::RG8Unorm, - PixelFormat::RGBA8Unorm, - PixelFormat::A8Unorm, - PixelFormat::RGBA16Float, - PixelFormat::RGBA16Unorm, - ]; - for (stem, sampler) in [ - ("moltenvk-m3", linear(1, false, 0)), - ("lavapipe", linear(0, false, 2)), - ] { - let dev = device_of(stem); - let Some(bc) = assemble(stem, &kernel(Some(sampler), Form::Plain { offset: (0, 0) })) - else { - return; - }; - let p = notes_pipeline(&dev, &bc); - assert!( - !p.stage - .specialization - .constants - .iter() - .any(|c| matches!(c.key, SpecKey::TexelFormat(_))), - "{stem}" - ); - // Where the device samples through Metal's own texture unit, the kind of conversion is a - // constant of its own. - assert_eq!( - p.stage - .specialization - .constants - .iter() - .any(|c| matches!(c.key, SpecKey::PlainHalfTexels(_))), - stem == "moltenvk-m3", - "{stem}" - ); - let plan = |pf| plan_bound(&p, &dev, (TextureType::Type2D, pf), None); - let base = plan(formats[0]).specialization; - for pf in formats { - let plan = plan(pf); - let plain = texel_format(pf).plain_on_metal_sampler(); - assert_eq!( - plan.specialization == base, - plain || stem != "moltenvk-m3", - "{stem} {pf:?}" - ); - assert!( - plan.specialized_value(SpecKey::TexelFormat(TEXTURE)) - .is_some(), - "{stem} {pf:?}" - ); - } - } -} - -/// On MoltenVK, a device that samples through Metal's own texture unit and rounds to `half` as -/// Metal does, a `half` sample through a runtime sampler reads of the sampler word only what the -/// pixel-centre test reads, which the binder keys as 0 for a sampler of normalized coordinates; its -/// slot's class it reads as data: every measured format of the plain arm (`PlainHalfTexels`) -/// specializes alike through any sampler of normalized coordinates, as through none, and through -/// each pixel sampler, and so does every one of the routine's arms among themselves; an unmeasured -/// format apart, through the slot's `UnmeasuredTexels` specialization, under which alone its -/// `half` conversion is noted. On lavapipe every format specializes alike too, and the samplers -/// apart. -#[test] -fn metal_s_half_of_its_float_specializes_measured_formats_alike() { - use crate::bind::SamplerDescriptor; - use crate::metal::{SamplerMinMagFilter, SamplerMipFilter, TextureType}; - use PixelFormat as F; - let m3 = device_of("moltenvk-m3"); - let Some(bc) = assemble( - "metal sampler fold", - &kernel(None, Form::Plain { offset: (0, 0) }), - ) else { - return; - }; - let p = notes_pipeline(&m3, &bc); - let constants = &p.stage.specialization.constants; - // The slot's class is a push field, no constant. - assert!( - !constants - .iter() - .any(|c| matches!(c.key, SpecKey::TexelFormat(_))), - "{constants:?}" - ); - assert!(p - .interface - .push - .iter() - .flat_map(|pl| &pl.fields) - .any(|f| matches!(f.field, PushField::Specialized(SpecKey::TexelFormat(_))))); - // The pixel-centre test reads whether the word states a nearest pixel sampler, and nothing else - // reads it: its fields are gated by the coordinates bit; nothing reads its mip filter or - // anisotropy. - let word = constants - .iter() - .find(|c| matches!(c.key, SpecKey::SamplerState { .. })) - .expect("the sampler's word"); - let SpecKey::SamplerState { fields, .. } = word.key else { - unreachable!("a sampler word") - }; - assert_ne!(fields & SamplerWord::PIXEL_GATED, 0, "{word:?}"); - let read = fields & !(word.unread_bits as u32) & !SamplerWord::PIXEL_GATED; - assert_eq!(read & !SamplerWord::PIXEL_NEAREST, 0, "{word:?}"); - assert!( - constants - .iter() - .any(|c| matches!(c.key, SpecKey::UnmeasuredTexels(_))), - "{constants:?}" - ); - let nearest = SamplerDescriptor::new(); - let mut linear = nearest; - linear.min_filter = SamplerMinMagFilter::Linear; - linear.mag_filter = SamplerMinMagFilter::Linear; - let mut mipped = linear; - mipped.mip_filter = SamplerMipFilter::Linear; - mipped.max_anisotropy = 4; - let mut pixel = nearest; - pixel.normalized_coordinates = false; - let mut pixel_linear = linear; - pixel_linear.normalized_coordinates = false; - let spec = |pf, s| plan_bound(&p, &m3, (TextureType::Type2D, pf), Some(s)).specialization; - // Every sampler of normalized coordinates keys as no sampler does; a pixel sampler apart, - // a nearest one from a linear one. - let base = spec(F::RGBA8Unorm, nearest); - assert_eq!(spec(F::RGBA8Unorm, linear), base); - assert_eq!(spec(F::RGBA8Unorm, mipped), base); - assert_ne!(spec(F::RGBA8Unorm, pixel), base); - assert_ne!(spec(F::RGBA8Unorm, pixel_linear), base); - assert_ne!( - spec(F::RGBA8Unorm, pixel_linear), - spec(F::RGBA8Unorm, pixel) - ); - // The classes whose `half` is their `float` texel rounded to nearest even take the plain arm - // (`SpecKey::PlainHalfTexels`): they key alike; the 16-bit normalized and 32-bit float ones - // take the routine, and key alike among themselves. - let plain = [ - F::RGBA8Unorm, - F::BGRA8Unorm, - F::R8Unorm, - F::A8Unorm, - F::RGBA16Float, - F::RGB10A2Unorm, - F::B5G6R5Unorm, - F::RG11B10Float, - F::RGBA8Snorm, - F::RG8Snorm, - ]; - let routine = [F::RGBA16Unorm, F::RGBA16Snorm, F::RGBA32Float]; - assert!( - constants - .iter() - .any(|c| matches!(c.key, SpecKey::PlainHalfTexels(_))), - "{constants:?}" - ); - for pf in plain { - for s in [nearest, linear, mipped] { - assert_eq!(spec(pf, s), base, "{pf:?} {s:?}"); - } - assert_eq!(spec(pf, pixel), spec(F::RGBA8Unorm, pixel), "{pf:?}"); - } - let routine_base = spec(F::RGBA32Float, nearest); - assert_ne!(routine_base, base); - for pf in routine { - for s in [nearest, linear, mipped] { - assert_eq!(spec(pf, s), routine_base, "{pf:?} {s:?}"); - } - assert_eq!(spec(pf, pixel), spec(F::RGBA32Float, pixel), "{pf:?}"); - } - let alike = plain.iter().chain(&routine).copied(); - assert_ne!(spec(F::BC7RGBAUnorm, nearest), base); - let converts = |pf, s| { - notes_bound(&p, &m3, (TextureType::Type2D, pf), Some(s)) - .contains(&PrecisionNote::HalfTexelConversion) - }; - for s in [nearest, linear] { - assert!(converts(F::BC7RGBAUnorm, s), "{s:?}"); - for pf in alike.clone() { - assert!(!converts(pf, s), "{pf:?} {s:?}"); - } - } - // On lavapipe the emulated linear filter reads the word's filter for normalized coordinates - // too: no gate, and the samplers stay apart; the formats, read as data, key alike. - let lvp = device_of("lavapipe"); - let p = notes_pipeline(&lvp, &bc); - assert!(p - .stage - .specialization - .constants - .iter() - .all(|c| match c.key { - SpecKey::SamplerState { fields, .. } => fields & SamplerWord::PIXEL_GATED == 0, - _ => true, - })); - let spec = |pf, s| plan_bound(&p, &lvp, (TextureType::Type2D, pf), Some(s)).specialization; - assert_eq!(spec(F::RGBA8Unorm, nearest), spec(F::RGBA16Float, nearest)); - assert_ne!(spec(F::RGBA8Unorm, nearest), spec(F::RGBA8Unorm, linear)); -} - -/// A texture access's notes are the specialized pipeline's. A `half` linear 2D sample through a -/// constexpr sampler on lavapipe records `HalfSampleFilter` and `HalfTexelConversion` only where -/// the bound format's class names no measured family (a compressed format), the arms its -/// specialization selects: none of them under an 8-bit, 16-bit, half-float, 32-bit float, or packed -/// format. In 3D a half-float, small-float, or 32-bit float format keeps the filter note (the -/// residue), a normalized or packed normalized one does not. Through a runtime sampler slot the -/// filter note holds where the bound sampler filters and its state is not the emulation's (in 2D a -/// mirror-clamped axis is) or its format is not measured, `PixelSamplerScaling` where it reads -/// pixel coordinates and that arm is the device's filter (a nearest pixel word reads its texel's -/// centre, a linear one the emulation where it reaches the format, both at Metal's position), and -/// `HalfTexelConversion` for a format of no family where it filters, and for one of neither family -/// nor packed field also where it does not (a packed format's one texel converts from its codes). -/// The module's notes are the union, every one of them conditional. On MoltenVK the filter is -/// Metal's own and takes no note at all. -#[test] -fn a_pipelines_texture_notes_follow_its_bound_format_and_sampler() { - use crate::bind::SamplerDescriptor; - use crate::metal::{SamplerMinMagFilter, TextureType}; - use PrecisionNote::{HalfSampleFilter, HalfTexelConversion, PixelSamplerScaling}; - let lvp = device_of("lavapipe"); - let plane = (TextureType::Type2D, PixelFormat::RGBA8Unorm); - let measured = [ - PixelFormat::RGBA8Unorm, - PixelFormat::RG16Snorm, - PixelFormat::RGBA16Float, - PixelFormat::RGBA32Float, - PixelFormat::RGB10A2Unorm, - PixelFormat::B5G6R5Unorm, - PixelFormat::RG11B10Float, - ]; - let conversion = [HalfSampleFilter, HalfTexelConversion]; - // A constexpr linear sampler. - let Some(bc) = assemble( - "notes plane", - &kernel(Some(linear(1, false, 0)), Form::Plain { offset: (0, 0) }), - ) else { - return; - }; - let p = notes_pipeline(&lvp, &bc); - for note in conversion { - assert!(p.stage.precision_notes.contains(¬e), "{note:?}"); - assert!( - p.stage.specialized_notes.iter().any(|s| s.note == note), - "{note:?}: {:?}", - p.stage.specialized_notes - ); - } - for pf in measured { - let notes = notes_bound(&p, &lvp, (TextureType::Type2D, pf), None); - for note in conversion { - assert!(!notes.contains(¬e), "{pf:?}: {notes:?}"); - } - } - let unmeasured = notes_bound( - &p, - &lvp, - (TextureType::Type2D, PixelFormat::BC7RGBAUnorm), - None, - ); - for note in conversion { - assert!(unmeasured.contains(¬e), "{note:?}: {unmeasured:?}"); - } - // In 3D the emulation's half-float and 32-bit float sums keep a residue. - let Some(bc) = assemble( - "notes solid", - &kernel( - Some(linear(1, false, 0)), - Form::ThreeD { offset: (0, 0, 0) }, - ), - ) else { - return; - }; - let solid = notes_pipeline(&lvp, &bc); - for (pf, noted) in [ - (PixelFormat::RGBA8Unorm, false), - (PixelFormat::RGBA16Unorm, false), - (PixelFormat::RGB10A2Unorm, false), - (PixelFormat::RGBA16Float, true), - (PixelFormat::RGBA32Float, true), - (PixelFormat::RG11B10Float, true), - ] { - let notes = notes_bound(&solid, &lvp, (TextureType::Type3D, pf), None); - assert_eq!(notes.contains(&HalfSampleFilter), noted, "3D {pf:?}"); - assert!(!notes.contains(&HalfTexelConversion), "3D {pf:?}"); - } - // A runtime sampler slot: the bound sampler's word decides. - let Some(bc) = assemble( - "notes runtime", - &kernel(None, Form::Plain { offset: (0, 0) }), - ) else { - return; - }; - let runtime = notes_pipeline(&lvp, &bc); - for note in [HalfSampleFilter, PixelSamplerScaling] { - assert!( - runtime - .stage - .specialized_notes - .iter() - .any(|s| s.note == note), - "{note:?}: {:?}", - runtime.stage.specialized_notes - ); - } - let nearest = SamplerDescriptor::new(); - let mut filtered = SamplerDescriptor::new(); - filtered.min_filter = SamplerMinMagFilter::Linear; - filtered.mag_filter = SamplerMinMagFilter::Linear; - let mut mirrored = filtered; - mirrored.s_address_mode = SamplerAddressMode::MirrorClampToEdge; - let mut pixels = filtered; - pixels.normalized_coordinates = false; - let mut pixels_nearest = nearest; - pixels_nearest.normalized_coordinates = false; - let mut pixels_mixed = pixels; - pixels_mixed.mag_filter = SamplerMinMagFilter::Nearest; - for (name, sampler, pf, filter, scaled) in [ - ("nearest", nearest, PixelFormat::RGBA8Unorm, false, false), - ( - "nearest packed", - nearest, - PixelFormat::RGB10A2Unorm, - false, - false, - ), - ("linear", filtered, PixelFormat::RGBA8Unorm, false, false), - ( - "linear packed", - filtered, - PixelFormat::RGB10A2Unorm, - false, - false, - ), - ( - "nearest unmeasured", - nearest, - PixelFormat::BC7RGBAUnorm, - false, - false, - ), - ( - "linear unmeasured", - filtered, - PixelFormat::BC7RGBAUnorm, - true, - false, - ), - ( - "mirror-clamped", - mirrored, - PixelFormat::RGBA8Unorm, - false, - false, - ), - ("pixels", pixels, PixelFormat::RGBA8Unorm, false, false), - ( - "pixels unmeasured", - pixels, - PixelFormat::BC7RGBAUnorm, - true, - true, - ), - ( - "pixels nearest", - pixels_nearest, - PixelFormat::RGBA8Unorm, - false, - false, - ), - ( - "pixels mixed", - pixels_mixed, - PixelFormat::RGBA8Unorm, - true, - true, - ), - ] { - let notes = notes_bound(&runtime, &lvp, (TextureType::Type2D, pf), Some(sampler)); - assert_eq!( - notes.contains(&HalfSampleFilter), - filter, - "{name}: {notes:?}" - ); - assert_eq!( - notes.contains(&PixelSamplerScaling), - scaled, - "{name}: {notes:?}" - ); - // A packed format's one texel converts from its codes, and Metal's filter of it is - // measured: the conversion note holds for a format of neither. - assert_eq!( - notes.contains(&HalfTexelConversion), - pf == PixelFormat::BC7RGBAUnorm, - "{name}: {notes:?}" - ); - } - // MoltenVK filters through Metal's own sampler: no filter note to decide. - let Some(bc) = assemble( - "notes plane m3", - &kernel(Some(linear(1, false, 0)), Form::Plain { offset: (0, 0) }), - ) else { - return; - }; - let m3 = device_of("moltenvk-m3"); - let q = notes_pipeline(&m3, &bc); - assert!(!q.stage.precision_notes.contains(&HalfSampleFilter)); - let notes = notes_bound(&q, &m3, plane, None); - assert!( - !notes.contains(&HalfTexelConversion) && !notes.contains(&HalfSampleFilter), - "{notes:?}" - ); - // A runtime pixel sampler there: a nearest word reads its texel's centre and a linear one - // snaps onto its footprint cell, both Metal's position; a word of mixed filters is the - // device's. - let Some(bc) = assemble( - "notes runtime m3", - &kernel(None, Form::Plain { offset: (0, 0) }), - ) else { - return; - }; - let q = notes_pipeline(&m3, &bc); - for (name, sampler, scaled) in [ - ("pixels", pixels, false), - ("pixels nearest", pixels_nearest, false), - ("pixels mixed", pixels_mixed, true), - ("normalized", filtered, false), - ] { - let notes = notes_bound(&q, &m3, plane, Some(sampler)); - assert_eq!( - notes.contains(&PixelSamplerScaling), - scaled, - "m3 {name}: {notes:?}" - ); - } -} - -/// An access that reads one texel converts its texel from its codes. Through a nearest constexpr -/// sampler on lavapipe a `half` sample of a packed format takes no `HalfTexelConversion` (its -/// class's packed arm), and neither does a normalized one; through a linear sampler neither does a -/// packed format (Metal's filter of it is emulated), and a compressed one keeps it. A `float` read -/// or nearest sample declares the slot's `TexelFormat` and the module's `float` routine where the -/// device's sampler is not Metal's own, and not on MoltenVK. -#[test] -fn a_texel_read_as_one_texel_converts_from_its_codes() { - use crate::metal::TextureType; - use crate::pipeline::sym::SpecKey; - use PrecisionNote::HalfTexelConversion; - let lvp = device_of("lavapipe"); - let m3 = device_of("moltenvk-m3"); - let nearest = sampler_words(0, 0, 1, false, 0); - let plane = Form::Plain { offset: (0, 0) }; - let Some(bc) = assemble("one texel half", &kernel(Some(nearest), plane)) else { - return; - }; - let p = notes_pipeline(&lvp, &bc); - for pf in [ - PixelFormat::RGB10A2Unorm, - PixelFormat::B5G6R5Unorm, - PixelFormat::RG11B10Float, - PixelFormat::RGBA8Unorm, - ] { - let notes = notes_bound(&p, &lvp, (TextureType::Type2D, pf), None); - assert!( - !notes.contains(&HalfTexelConversion), - "nearest {pf:?}: {notes:?}" - ); - } - let Some(bc) = assemble("filtered half", &kernel(Some(linear(1, false, 0)), plane)) else { - return; - }; - let p = notes_pipeline(&lvp, &bc); - for (pf, noted) in [ - (PixelFormat::RGB10A2Unorm, false), - (PixelFormat::RG11B10Float, false), - (PixelFormat::BC7RGBAUnorm, true), - ] { - let notes = notes_bound(&p, &lvp, (TextureType::Type2D, pf), None); - assert_eq!( - notes.contains(&HalfTexelConversion), - noted, - "linear {pf:?}: {notes:?}" - ); - } - let Some(bc) = assemble("one texel float", &kernel_of(Some(nearest), plane, true)) else { - return; - }; - for (stem, dev, converts) in [("lavapipe", &lvp, true), ("moltenvk-m3", &m3, false)] { - let p = notes_pipeline(dev, &bc); - // The class, which the function reads from its push field. - let class = p - .interface - .push - .iter() - .flat_map(|placement| &placement.fields) - .any(|f| matches!(f.field, PushField::Specialized(SpecKey::TexelFormat(_)))); - let routine = p - .stage - .strategies - .entries - .contains_key(crate::lower::texture::float_texel::CENSUS_NAME); - assert_eq!((class, routine), (converts, converts), "{stem}"); - } -} - -/// Each function of SPIR-V module `words`: its result id, its function control, and the callees -/// of its `OpFunctionCall`s, with the result ids of those calls an `OpSelect` reads. -struct ModuleFunctions { - controls: BTreeMap, - calls: BTreeMap>, - selected_calls: usize, -} - -fn module_functions(words: &[u32]) -> ModuleFunctions { - let (op_function, op_end, op_call, op_select) = ( - crate::spv::Op::Function as u32, - crate::spv::Op::FunctionEnd as u32, - crate::spv::Op::FunctionCall as u32, - crate::spv::Op::Select as u32, - ); - let mut out = ModuleFunctions { - controls: BTreeMap::new(), - calls: BTreeMap::new(), - selected_calls: 0, - }; - let mut current = None; - let mut call_results = std::collections::BTreeSet::new(); - let mut i = 5; - while i < words.len() { - let (len, opcode) = ((words[i] >> 16) as usize, words[i] & 0xffff); - assert!(len > 0 && i + len <= words.len(), "malformed module"); - let w = &words[i..i + len]; - if opcode == op_function { - current = Some(w[2]); - out.controls.insert(w[2], w[3]); - } else if opcode == op_end { - current = None; - } else if opcode == op_call { - let f = current.expect("a call outside a function"); - out.calls.entry(f).or_default().push(w[3]); - call_results.insert(w[2]); - } else if opcode == op_select && w[4..].iter().any(|v| call_results.contains(v)) { - out.selected_calls += 1; - } - i += len; - } - out -} - -impl ModuleFunctions { - /// The entry point: the one function no other function calls. - fn entry(&self, what: &str) -> u32 { - let called: std::collections::BTreeSet = - self.calls.values().flatten().copied().collect(); - let entries: Vec = self - .controls - .keys() - .copied() - .filter(|f| !called.contains(f)) - .collect(); - let [entry] = entries[..] else { - panic!("{what}: one entry, {entries:?}"); - }; - entry - } -} - -/// A linear `half` sample through a runtime sampler, emulated on a device that does not sample -/// through Metal's own sampler, reaches its exact and accumulated sums from the two arms of a -/// branch on the class, so one of them runs: no `OpSelect` reads a call's result. The emulation is -/// its shape's sampling routine, which the entry calls; the routine calls the two sums, which are -/// declared `DontInline` on every such profile. The routine states `DontInline` where the driver is -/// measured to keep such a call a call (`DriverWorkaround::DontInlineKeepsCalls`, NVIDIA's -/// 615.71.09 on the RTX 3090 and the RTX 5080 Laptop GPU) and no control elsewhere: on Mesa's -/// drivers, which inline every function whatever it states, and on a GPU not measured (the desktop -/// RTX 5080's profile, `nvidia-rtx50-linux`, on the same release). The -/// texel conversion the device's sample calls, which its class specialization folds where it is -/// inlined, and the entry take no control. -#[test] -fn the_linear_sums_run_one_by_a_branch_and_stay_calls() { - let Some(bc) = assemble("kept sums", &kernel(None, Form::Plain { offset: (0, 0) })) else { - return; - }; - let profiles = [ - ("rtx3090", rtx3090(), true), - ( - "nvidia-rtx5080-laptop", - profile("nvidia-rtx5080-laptop", EXACT_SAMPLING).expect("profile"), - true, - ), - ( - "nvidia-rtx50-linux", - profile("nvidia-rtx50-linux", EXACT_SAMPLING).expect("profile"), - false, - ), - ( - "lavapipe", - profile("lavapipe", EXACT_SAMPLING).expect("profile"), - false, - ), - ( - "amd-rdna3-radv", - profile("amd-rdna3-radv", EXACT_SAMPLING).expect("profile"), - false, - ), - ]; - for (stem, p, keeps) in profiles { - let a = compile(&bc, "k", &p).unwrap_or_else(|e| panic!("{stem}: {e}")); - let fs = module_functions(&a.module.words); - let entry = fs.entry(stem); - let from_entry: std::collections::BTreeSet = fs - .calls - .get(&entry) - .map(|c| c.iter().copied().collect()) - .unwrap_or_default(); - assert_eq!( - from_entry.len(), - 2, - "{stem}: the entry calls the emulation's routine and the conversion" - ); - // The emulation's routine is the one the entry calls that calls the sums. - let routines: Vec = from_entry - .iter() - .copied() - .filter(|f| fs.calls.contains_key(f)) - .collect(); - let [routine] = routines[..] else { - panic!("{stem}: one routine that calls, {routines:?}"); - }; - let sums: std::collections::BTreeSet = fs.calls[&routine].iter().copied().collect(); - assert_eq!( - sums.len(), - 2, - "{stem}: the routine calls the exact sum and the accumulated sum" - ); - for f in &sums { - assert_eq!(fs.controls.get(f), Some(&0x2), "{stem}: a sum stays a call"); - } - assert_eq!( - fs.controls.get(&routine), - Some(&if keeps { 0x2 } else { 0 }), - "{stem}: the sampling routine's control is the driver's fact" - ); - for f in from_entry.iter().filter(|f| **f != routine) { - assert_eq!( - fs.controls.get(f), - Some(&0), - "{stem}: the conversion takes no control" - ); - } - assert_eq!( - fs.controls.get(&entry), - Some(&0), - "{stem}: the entry takes no control" - ); - assert_eq!( - fs.selected_calls, 0, - "{stem}: no select reads a sum's result" - ); - } -} - -/// The profile of the RTX 5080 Laptop GPU's committed description with the RTX 3090's `deviceID`: -/// NVIDIA's 615.71.09 on the RTX 3090, a GPU `DriverWorkaround::DontInlineKeepsCalls` is measured -/// on. -fn rtx3090() -> DeviceProfile { - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles/nvidia-rtx5080-laptop.json"); - let text = std::fs::read_to_string(&path).expect("the RTX 5080 Laptop GPU's profile"); - let mut desc = crate::device::DeviceDescription::from_khronos_json(&text, None) - .expect("the RTX 5080 Laptop GPU's description"); - desc.device_id = crate::device::driver_facts::NVIDIA_RTX_3090; - let device = crate::device::Device::new(desc, EXACT_SAMPLING).expect("device"); - device.profile().clone() -} - -/// [`kernel_of`] through the runtime `[[sampler(0)]]` with `n` samples of texture slot 0 at the -/// coordinate plus `k / 8` for sample `k`, their texels summed; where `offsets`, sample `k` at -/// the constant texel offset `(k % 4 + 1, -k)`, each other sample's. -fn sites_kernel(n: usize, float: bool, offsets: bool) -> String { - let k = kernel_of(None, Form::Plain { offset: (0, 0) }, float); - let vec4 = if float { "<4 x float>" } else { "<4 x half>" }; - let call = k - .lines() - .find(|l| l.starts_with(" %r = call")) - .expect("the sample's call") - .to_string(); - let extract = format!(" %v = extractvalue {{ {vec4}, i8 }} %r, 0"); - assert!(k.contains(&extract), "the sample's texel"); - let mut body = String::new(); - for i in 0..n { - let d = i as f32 / 8.0; - body.push_str(&format!( - " %uv{i} = fadd <2 x float> %uv, \n" - )); - let (ox, oy) = match offsets { - true => ((i % 4) as i32 + 1, -(i as i32)), - false => (0, 0), - }; - body.push_str( - &call - .replacen("%r =", &format!("%r{i} ="), 1) - .replacen("<2 x float> %uv,", &format!("<2 x float> %uv{i},"), 1) - .replacen( - "<2 x i32> ", - &format!("<2 x i32> "), - 1, - ), - ); - body.push('\n'); - body.push_str(&format!( - " %v{i} = extractvalue {{ {vec4}, i8 }} %r{i}, 0\n" - )); - } - let mut sum = "%v0".to_string(); - for i in 1..n { - body.push_str(&format!(" %s{i} = fadd {vec4} {sum}, %v{i}\n")); - sum = format!("%s{i}"); - } - body.push_str(&format!(" %v = fadd {vec4} {sum}, zeroinitializer")); - k.replacen(&format!("{call}\n{extract}"), &body, 1) -} - -/// The `OpImageFetch` instructions of each function of SPIR-V module `words`, by result id. -fn fetches_by_function(words: &[u32]) -> BTreeMap { - let (op_function, op_end, op_fetch) = ( - crate::spv::Op::Function as u32, - crate::spv::Op::FunctionEnd as u32, - crate::spv::Op::ImageFetch as u32, - ); - let mut out = BTreeMap::new(); - let mut current = None; - let mut i = 5; - while i < words.len() { - let (len, opcode) = ((words[i] >> 16) as usize, words[i] & 0xffff); - assert!(len > 0 && i + len <= words.len(), "malformed module"); - if opcode == op_function { - current = Some(words[i + 2]); - out.insert(words[i + 2], 0); - } else if opcode == op_end { - current = None; - } else if opcode == op_fetch { - *out.entry(current.expect("a fetch outside a function")) - .or_default() += 1; - } - i += len; - } - out -} - -/// The emulation of one combined binding's sample shape is one sampling routine, which each of the -/// binding's sites calls. A kernel of `n` linear samples of one texture through one runtime -/// sampler, emulated on a device that does not sample through Metal's own sampler, holds one -/// emulation routine that the entry calls `n` times (a `float` result's nearest-exact fetch arm one -/// more routine, called `n` times too), and every fetch is the routines': the entry fetches -/// nothing. The census counts each routine once, as one sample's module counts it. Sites at -/// different constant texel offsets call one routine too, which takes the offset as its call's -/// argument. -#[test] -fn the_samples_of_one_binding_call_one_routine() { - const N: usize = 5; - for (float, offsets) in [(false, false), (true, false), (false, true), (true, true)] { - let what = match (float, offsets) { - (false, false) => "half", - (true, false) => "float", - (false, true) => "half at offsets", - (true, true) => "float at offsets", - }; - let Some(bc) = assemble(&format!("sites {what}"), &sites_kernel(N, float, offsets)) else { - return; - }; - let Some(one) = assemble(&format!("site {what}"), &sites_kernel(1, float, offsets)) else { - return; - }; - let profiles = [ - ("rtx3090", rtx3090()), - ( - "lavapipe", - profile("lavapipe", EXACT_SAMPLING).expect("profile"), - ), - ]; - for (stem, p) in profiles { - let a = compile(&bc, "k", &p).unwrap_or_else(|e| panic!("{stem} {what}: {e}")); - let fs = module_functions(&a.module.words); - let entry = fs.entry(stem); - let calls = fs.calls.get(&entry).cloned().unwrap_or_default(); - let fetches = fetches_by_function(&a.module.words); - // The routines that fetch: the emulation's, and a `float` sample's fetch arm. - let fetching: Vec = fetches - .iter() - .filter(|(f, n)| **n > 0 && **f != entry) - .map(|(f, _)| *f) - .collect(); - assert_eq!( - fetching.len(), - 1 + usize::from(float), - "{stem} {what}: the sampling routines, {fetching:?}" - ); - for f in &fetching { - assert_eq!( - calls.iter().filter(|c| *c == f).count(), - N, - "{stem} {what}: each site calls routine {f}" - ); - } - assert_eq!( - fetches.get(&entry), - Some(&0), - "{stem} {what}: the sites fetch nothing themselves" - ); - // The census counts each routine once. - let b = compile(&one, "k", &p).unwrap_or_else(|e| panic!("{stem} {what}: {e}")); - for name in ["sampler.linear.routine", "sampler.fetch.routine"] { - assert_eq!( - a.strategies.entries.get(name).map(|e| e.words), - b.strategies.entries.get(name).map(|e| e.words), - "{stem} {what}: {name} counted once" - ); - } - assert!( - a.strategies.entries.contains_key("sampler.linear.routine"), - "{stem} {what}: the census names the routine" - ); - } - } -} - -/// A kernel reading `texture2d` slot 0 at its thread's position and storing the texel, -/// a `float4` or a `half4`, to buffer 0. -fn read_kernel_of(float: bool) -> String { - let (texel, vec4, suffix, size) = match float { - true => ("float", "<4 x float>", "v4f32", 16), - false => ("half", "<4 x half>", "v4f16", 8), - }; - format!( - r#"define void @k(ptr addrspace(1) %t, ptr addrspace(1) %out, i32 %tid) {{ - %i = zext i32 %tid to i64 - %xy = insertelement <2 x i32> zeroinitializer, i32 %tid, i64 0 - %s = call ptr addrspace(2) @air.get_read_sampler() - %r = call {{ {vec4}, i8 }} @air.read_texture_2d.{suffix}(ptr addrspace(1) %t, ptr addrspace(2) %s, <2 x i32> %xy, <2 x i32> zeroinitializer, i32 0, i32 1) - %v = extractvalue {{ {vec4}, i8 }} %r, 0 - %q = getelementptr inbounds {vec4}, ptr addrspace(1) %out, i64 %i - store {vec4} %v, ptr addrspace(1) %q, align {size} - ret void -}} - -declare ptr addrspace(2) @air.get_read_sampler() -declare {{ {vec4}, i8 }} @air.read_texture_2d.{suffix}(ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32) - -!air.kernel = !{{!0}} -!0 = !{{ptr @k, !1, !2}} -!1 = !{{}} -!2 = !{{!3, !4, !5}} -!3 = !{{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d<{texel}, read>", !"air.arg_name", !"t"}} -!4 = !{{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 {size}, !"air.arg_type_align_size", i32 {size}, !"air.arg_type_name", !"{texel}4", !"air.arg_name", !"out"}} -!5 = !{{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"tid"}} -"# - ) -} - -/// Under the default policies, on a device that does not sample through Metal's own texture unit, a -/// texel's `float` or `half` value is the device's conversion (native device sampling): a sample's -/// and a read's module defines neither conversion routine and records `DeviceTexelConversion` -/// (`float`) or `HalfTexelConversion` (`half`), and the sample reads no field of a runtime -/// sampler's word for it, so a sampler of normalized coordinates keys no pipeline (what still reads -/// the word is a pixel sampler's, gated on its pixel bit). `TexelConversionPolicy::Exact` alone -/// makes a read Metal's conversion by the bound format's class through the routine, recording no -/// `DeviceTexelConversion`, and leaves a natively sampled texel the device's; under -/// `SamplingPolicy::Exact` the emulation converts a sample's by the class only where -/// `TexelConversionPolicy::Exact` says. On MoltenVK, which samples through Metal's own sampler, the -/// default keeps that device's form. -#[test] -fn texel_conversions_are_the_device_s_by_default() { - use crate::device::{SamplingPolicy, TexelConversionPolicy}; - use crate::lower::texture::{float_texel, half}; - let policy = |sampling, texel_conversion| DevicePolicy { - sampling, - texel_conversion, - ..DevicePolicy::default() - }; - // (the policy, whether a sample's conversion is the routine's, whether a read's is) - let policies = [ - (DevicePolicy::default(), false, false), - ( - policy(SamplingPolicy::NativeDevice, TexelConversionPolicy::Exact), - false, - true, - ), - ( - policy(SamplingPolicy::Exact, TexelConversionPolicy::Device), - false, - false, - ), - (EXACT_SAMPLING, true, true), - ]; - for float in [false, true] { - let what = if float { "float" } else { "half" }; - let kernel = kernel_of(None, Form::Plain { offset: (0, 0) }, float); - let Some(bc) = assemble(&format!("conversion {what}"), &kernel) else { - return; - }; - let Some(read) = assemble(&format!("read {what}"), &read_kernel_of(float)) else { - return; - }; - let (routine, note) = match float { - true => ( - float_texel::CENSUS_NAME, - PrecisionNote::DeviceTexelConversion, - ), - false => (half::CENSUS_NAME, PrecisionNote::HalfTexelConversion), - }; - for stem in ["lavapipe", "nvidia-rtx5080-laptop", "amd-780m-radv"] { - for (p, exact, exact_read) in policies { - let what = format!("{stem} {what} {:?} {:?}", p.sampling, p.texel_conversion); - let device = profile(stem, p).expect("profile"); - let a = compile(&bc, "k", &device).unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!( - a.strategies.entries.contains_key(routine), - exact, - "{what}: Metal's conversion is the routine's" - ); - if !exact || float { - assert_eq!(a.precision.contains(¬e), !exact, "{what}: {note:?}"); - } - // A read: Metal's conversion where the policy alone says so. - let r = compile(&read, "k", &device).unwrap_or_else(|e| panic!("{what} read: {e}")); - link_and_validate(&r, &device).unwrap_or_else(|e| panic!("{what} read: L3: {e}")); - assert_eq!( - r.strategies.entries.contains_key(routine), - exact_read, - "{what} read: Metal's conversion is the routine's" - ); - if !exact_read || float { - assert_eq!( - r.precision.contains(¬e), - !exact_read, - "{what} read: {note:?} in {:?}", - r.precision - ); - } - if p.sampling != SamplingPolicy::NativeDevice { - continue; - } - for key in a.interface.read_keys() { - let SpecKey::SamplerState { fields, .. } = key else { - continue; - }; - let read = match fields & SamplerWord::PIXEL_GATED { - 0 => SamplerWord::PIXEL_COORDINATES, - _ => SamplerWord::PIXEL_NEAREST | SamplerWord::PIXEL_GATED, - }; - assert_eq!(fields & !read, 0, "{what}: {key:?}"); - } - } - } - let m = profile("moltenvk-m3", DevicePolicy::default()).expect("profile"); - let c = compile(&bc, "k", &m).unwrap_or_else(|e| panic!("moltenvk-m3 {what}: {e}")); - assert!( - !c.precision.contains(&PrecisionNote::DeviceTexelConversion), - "moltenvk-m3 {what}: Metal's own sampler" - ); - } -} - -/// A kernel that reads `texture2d` slot 0 at its thread's position and samples it -/// through runtime sampler 0, storing both `half4`s to buffer 0. -const READ_AND_SAMPLE: &str = r#"define void @k(ptr addrspace(1) %t, ptr addrspace(1) %out, ptr addrspace(2) %s, i32 %tid) { - %i = zext i32 %tid to i64 - %xy = insertelement <2 x i32> zeroinitializer, i32 %tid, i64 0 - %rs = call ptr addrspace(2) @air.get_read_sampler() - %r = call { <4 x half>, i8 } @air.read_texture_2d.v4f16(ptr addrspace(1) %t, ptr addrspace(2) %rs, <2 x i32> %xy, <2 x i32> zeroinitializer, i32 0, i32 1) - %rv = extractvalue { <4 x half>, i8 } %r, 0 - %u = uitofp i32 %tid to float - %uv = insertelement <2 x float> , float %u, i64 0 - %q = call { <4 x half>, i8 } @air.sample_texture_2d.v4f16(ptr addrspace(1) %t, ptr addrspace(2) %s, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.0, float 0.0, i32 0) - %qv = extractvalue { <4 x half>, i8 } %q, 0 - %j = shl i64 %i, 1 - %pr = getelementptr inbounds <4 x half>, ptr addrspace(1) %out, i64 %j - store <4 x half> %rv, ptr addrspace(1) %pr, align 8 - %k1 = or i64 %j, 1 - %pq = getelementptr inbounds <4 x half>, ptr addrspace(1) %out, i64 %k1 - store <4 x half> %qv, ptr addrspace(1) %pq, align 8 - ret void -} - -declare ptr addrspace(2) @air.get_read_sampler() -declare { <4 x half>, i8 } @air.read_texture_2d.v4f16(ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32) -declare { <4 x half>, i8 } @air.sample_texture_2d.v4f16(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32) - -!air.kernel = !{!0} -!0 = !{ptr @k, !1, !2} -!1 = !{} -!2 = !{!3, !4, !5, !6} -!3 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} -!4 = !{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"half4", !"air.arg_name", !"out"} -!5 = !{i32 2, !"air.sampler", !"air.location_index", i32 0, i32 1, !"air.arg_type_name", !"sampler", !"air.arg_name", !"s"} -!6 = !{i32 3, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"tid"} -"#; - -/// The `OpFunctionCall`s of a module. -fn calls(words: &[u32]) -> usize { - const OP_FUNCTION_CALL: u32 = 57; - let mut n = 0; - let mut i = 5; - while i < words.len() { - n += usize::from(words[i] & 0xFFFF == OP_FUNCTION_CALL); - i += ((words[i] >> 16) as usize).max(1); - } - n -} - -/// A `half` texel the read converts by the class and the sample leaves to the device, in one -/// function of one slot: under `TexelConversionPolicy::Exact` with native device sampling, the slot -/// declares its class and the module the routine for the read, and the sample (whose texel the -/// device's sampler answers, `Sampling::half_texel`) calls nothing more than the read alone does, -/// records `HalfTexelConversion`, and the module passes L3. Under `SamplingPolicy::Exact` both -/// convert, the sample through the routine too. -#[test] -fn a_read_converts_by_the_class_beside_a_natively_sampled_texel() { - use crate::device::{SamplingPolicy, TexelConversionPolicy}; - use crate::lower::texture::half; - let (Some(mixed), Some(read)) = ( - assemble("read and sample", READ_AND_SAMPLE), - assemble("read half", &read_kernel_of(false)), - ) else { - return; - }; - let native = DevicePolicy { - texel_conversion: TexelConversionPolicy::Exact, - ..DevicePolicy::default() - }; - for stem in ["lavapipe", "nvidia-rtx5080-laptop"] { - let device = profile(stem, native).expect("profile"); - let a = compile(&mixed, "k", &device).unwrap_or_else(|e| panic!("{stem}: {e}")); - link_and_validate(&a, &device).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); - let r = compile(&read, "k", &device).unwrap_or_else(|e| panic!("{stem} read: {e}")); - assert!( - a.strategies.entries.contains_key(half::CENSUS_NAME), - "{stem}" - ); - assert!( - a.precision.contains(&PrecisionNote::HalfTexelConversion), - "{stem}: {:?}", - a.precision - ); - assert_eq!( - calls(&a.module.words), - calls(&r.module.words), - "{stem}: the sample calls no conversion" - ); - let exact = profile(stem, EXACT_SAMPLING).expect("profile"); - let e = compile(&mixed, "k", &exact).unwrap_or_else(|e| panic!("{stem} exact: {e}")); - link_and_validate(&e, &exact).unwrap_or_else(|e| panic!("{stem} exact: L3: {e}")); - assert!( - calls(&e.module.words) > calls(&a.module.words), - "{stem}: the emulated sample converts through the routine" - ); - assert_eq!( - SamplingPolicy::NativeDevice, - native.sampling, - "the default samples natively" - ); - } -} - -/// The residue: the binder sets a slot's `OffsetBaseAxes` from the bound texture's -/// `TextureFacts::offset_base_axes`: the axes of a view whose first level lies above its parent's -/// base level on which the parent's base-level size is not a power of two and the view's own is, -/// and some level of the view is 2 or 4 wide; 0 for a texture that is not a view, a view at the -/// parent's base, an axis whose own size is not a power of two either, and a view whose levels -/// stay above 4. -#[test] -fn the_binder_states_a_view_s_parent_base_axes() { - use crate::metal::TextureType; - let Some(bc) = assemble( - "view parent base", - &kernel_of( - Some(linear(2, false, 0)), - Form::Plain { offset: (2, -1) }, - false, - ), - ) else { - return; - }; - let lvp = device_of("lavapipe"); - let p = notes_pipeline(&lvp, &bc); - let id = p - .stage - .specialization - .constants - .iter() - .find(|c| c.key == SpecKey::OffsetBaseAxes(TEXTURE)) - .map(|c| c.id) - .expect("the slot's OffsetBaseAxes"); - let cases = [ - // (parent size, level, view levels, axes) - ([18, 16], 2, 3, 0b01), - ([16, 18], 2, 3, 0b10), - ([17, 9], 2, 1, 0b11), - ([20, 12], 2, 3, 0b00), - ([16, 16], 2, 3, 0b00), - ([18, 16], 0, 5, 0b00), - ([1025, 16], 1, 1, 0b00), - ([1025, 16], 1, 10, 0b01), - ]; - for ([w, h], level, levels, want) in cases { - let mut facts = - crate::bind::TextureFacts::new(TextureType::Type2D, PixelFormat::RGBA8Unorm); - facts.usage = crate::metal::TextureUsage::SHADER_READ; - facts.parent_relative_level = level; - facts.parent_base_size = [w, h, 1]; - facts.mipmap_level_count = levels; - assert_eq!(facts.offset_base_axes(), want, "{w}x{h} at {level}"); - let plan = plan_facts(&p, &lvp, facts, None); - let e = plan - .specialization - .entries - .iter() - .find(|e| e.constant_id == id) - .expect("specialized"); - let at = e.offset as usize; - let value = u32::from_le_bytes( - plan.specialization.data[at..at + 4] - .try_into() - .expect("a word"), - ); - assert_eq!( - value, - u32::from(want), - "{w}x{h} at {level} of {levels} levels" - ); - } - // A 3D view's depth, a 1D one's width; a cube's none. - let mut facts = crate::bind::TextureFacts::new(TextureType::Type3D, PixelFormat::RGBA8Unorm); - facts.parent_relative_level = 1; - facts.parent_base_size = [16, 16, 9]; - facts.mipmap_level_count = 3; - assert_eq!(facts.offset_base_axes(), 0b100); - facts.texture_type = TextureType::Type1D; - facts.parent_base_size = [9, 1, 1]; - assert_eq!(facts.offset_base_axes(), 0b1); - facts.texture_type = TextureType::Cube; - facts.parent_base_size = [9, 9, 1]; - assert_eq!(facts.offset_base_axes(), 0); -} - -/// On a profile that takes `DriverDeviation::Unorm8LinearFilter` (the RTX 5080 Laptop GPU's -/// capture, NVIDIA's 615.71.09, under a policy of `Unorm8LinearFilterPolicy::DeviceWithinOneCode`; -/// the default policy takes it nowhere), a 2D texture's or 2D array's linear sample through -/// a constexpr sampler with normalized coordinates or a runtime sampler slot, with a `half` or -/// `float` result and no offset, hands the 8-bit unsigned normalized classes to the device's -/// filter: it records `DeviceUnorm8LinearFilter` under the slot's class (and a runtime slot's -/// word), requires `VkProperty::Unorm8LinearFilter`, and validates. A texel offset, pixel -/// coordinates, a 1D or 3D texture, every sample under the default policy, and every sample on -/// an unmeasured profile (the RTX 50 desktop GPU's capture, a GPU no row names) keep Metal's -/// filter emulated: no note, no requirement. The plan's word estimate bounds each. -#[test] -fn a_measured_device_filters_the_eight_bit_classes_itself() { - let edge = linear(1, false, 0); - let mirror = linear(3, false, 0); - let plain = Form::Plain { offset: (0, 0) }; - // (name, sampler, form, `float`, native on a measured profile) - let cases: Vec<(&str, Option, Form, bool, bool)> = vec![ - ("2d edge", Some(edge), plain, false, true), - ("2d mirror float", Some(mirror), plain, true, true), - ("array", Some(edge), Form::Array { layer: 1 }, false, true), - ("runtime", None, plain, false, true), - ("runtime float", None, plain, true, true), - ("runtime array", None, Form::Array { layer: 1 }, true, true), - ( - "offset", - Some(edge), - Form::Plain { offset: (1, 0) }, - false, - false, - ), - ( - "runtime offset", - None, - Form::Plain { offset: (0, -1) }, - false, - false, - ), - ("pixel", Some(linear(1, true, 0)), plain, false, false), - ("1d", Some(edge), Form::OneD, false, false), - ( - "3d", - Some(edge), - Form::ThreeD { offset: (0, 0, 0) }, - false, - false, - ), - ]; - use crate::budget::SPIRV_WORDS; - use crate::device::Unorm8LinearFilterPolicy; - use crate::error::DriverDeviation as D; - use crate::library::FunctionConstantValues; - use crate::lower::select::LowerInputs; - use crate::pipeline::compile::{compile_bitcode, plan_bitcode, EntryRef}; - use crate::pipeline::testing::meter; - // Under Metal's sampler emulated exactly: native device sampling, the default, hands every - // such sample to the device's sampler before the 8-bit filter's choice. - let emulated = EXACT_SAMPLING; - let accepting = DevicePolicy { - unorm8_linear_filter: Unorm8LinearFilterPolicy::DeviceWithinOneCode, - ..emulated - }; - let measured = profile("nvidia-rtx5080-laptop", accepting).expect("profile"); - assert!(measured.takes_driver_deviation(D::Unorm8LinearFilter)); - let exact = profile("nvidia-rtx5080-laptop", emulated).expect("profile"); - assert!(!exact.takes_driver_deviation(D::Unorm8LinearFilter)); - let unmeasured = profile("nvidia-rtx50-linux", accepting).expect("profile"); - assert!(!unmeasured.takes_driver_deviation(D::Unorm8LinearFilter)); - for (name, sampler, form, float, native) in cases { - let Some(bc) = assemble(name, &kernel_of(sampler, form, float)) else { - return; - }; - for (stem, p, want) in [ - ("nvidia-rtx5080-laptop accepting", &measured, native), - ("nvidia-rtx5080-laptop by default", &exact, false), - ("nvidia-rtx50-linux accepting", &unmeasured, false), - ] { - let what = format!("{name} on {stem}"); - let a = compile(&bc, "k", p).unwrap_or_else(|e| panic!("{what}: {e}")); - link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: {e}")); - // The plan's word estimate bounds the native snap's site too: the estimate test's - // committed profiles take the default policy. - let (entry, consts, inputs) = ( - EntryRef::Name("k"), - FunctionConstantValues::defaults(), - LowerInputs::new(), - ); - let plan = plan_bitcode(&bc, entry, &consts, p, &inputs, &mut meter()) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let emitted = - compile_bitcode(&bc, entry, &consts, p, &inputs, &mut meter(), SPIRV_WORDS) - .unwrap_or_else(|e| panic!("{what}: {e}")) - .module - .words - .len() as u64; - assert!( - plan.estimate.words >= emitted, - "{what}: estimate {} < emitted {emitted}", - plan.estimate.words - ); - assert_eq!( - a.precision - .contains(&PrecisionNote::DeviceUnorm8LinearFilter), - want, - "{what}" - ); - assert_eq!( - a.specialized - .iter() - .any(|n| n.note == PrecisionNote::DeviceUnorm8LinearFilter), - want, - "{what}: {:?}", - a.specialized - ); - assert_eq!( - a.requirements - .properties - .contains(&VkProperty::Unorm8LinearFilter), - want, - "{what}" - ); - // The emulation stays for every other class, and the filtered note with it. - let filtered = match float { - true => PrecisionNote::FloatSampleFilter, - false => PrecisionNote::HalfSampleFilter, - }; - assert!(a.precision.contains(&filtered), "{what}"); - } - } -} - -/// Native device sampling, the default policy, hands a linear sample through a constexpr sampler or -/// a runtime sampler slot, of a 2D texture, a 2D array or a 3D texture, to the device's sampler on -/// a device whose sampler is not Metal's (the RTX 5080 Laptop GPU's capture and lavapipe's): the -/// artifact requires `VkProperty::DeviceSampling` and records `PrecisionNote::DeviceSampling` and -/// no filter note, its module is smaller than the emulation's, it validates, and its module reads -/// none of the emulation's fields of a sampler word (`SpecKey::SamplerState`): a constexpr -/// sampler's module reads no word, and a runtime sampler's reads only what a device whose sampler -/// is Metal's reads (its texel conversion is the device's too), where the emulation's reads its -/// address modes and border too. Under `SamplingPolicy::Exact` Metal's filter stays emulated, with -/// its note, and nothing records the native sampling. -#[test] -fn native_device_sampling_hands_samples_to_the_device() { - use crate::library::FunctionArtifact; - let exact = EXACT_SAMPLING; - let plain = Form::Plain { offset: (0, 0) }; - let cases: Vec<(&str, Option, Form, bool)> = vec![ - ("2d edge", Some(linear(1, false, 0)), plain, false), - ("2d mirror float", Some(linear(3, false, 0)), plain, true), - ("runtime", None, plain, false), - ("runtime array float", None, Form::Array { layer: 1 }, true), - ( - "3d", - Some(linear(1, false, 0)), - Form::ThreeD { offset: (0, 0, 0) }, - false, - ), - ]; - let sampler_keys = |a: &FunctionArtifact| { - a.interface - .read_keys() - .into_iter() - .filter(|k| matches!(k, SpecKey::SamplerState { .. })) - .collect::>() - }; - let noted = |a: &FunctionArtifact, note: PrecisionNote| { - a.precision.contains(¬e) || a.specialized.iter().any(|s| s.note == note) - }; - for (name, sampler, form, float) in cases { - let Some(bc) = assemble(name, &kernel_of(sampler, form, float)) else { - return; - }; - let filtered = match float { - true => PrecisionNote::FloatSampleFilter, - false => PrecisionNote::HalfSampleFilter, - }; - for stem in ["nvidia-rtx5080-laptop", "lavapipe"] { - let what = format!("{name} on {stem}"); - let native = profile(stem, DevicePolicy::default()).expect("profile"); - let emulated = profile(stem, exact).expect("profile"); - let n = compile(&bc, "k", &native).unwrap_or_else(|e| panic!("{what}: {e}")); - link_and_validate(&n, &native).unwrap_or_else(|e| panic!("{what}: {e}")); - let e = compile(&bc, "k", &emulated).unwrap_or_else(|e| panic!("{what} exact: {e}")); - link_and_validate(&e, &emulated).unwrap_or_else(|e| panic!("{what} exact: {e}")); - assert!( - n.requirements - .properties - .contains(&VkProperty::DeviceSampling), - "{what}" - ); - assert!( - n.precision.contains(&PrecisionNote::DeviceSampling), - "{what}" - ); - assert!(!noted(&n, filtered), "{what}"); - // The emulation's address modes and border are read nowhere natively; what a native - // module may still read of a runtime sampler's word is the texel conversion's - // (`texture::OneTexel::Word`): its coordinates and filter. - let conversion = SamplerWord::PIXEL_COORDINATES - | SamplerWord::LINEAR_FILTER - | SamplerWord::PIXEL_GATED; - // Natively the conversion is the device's too: what remains is what a device whose - // sampler is Metal's reads, a pixel sampler's coordinates and the footprint cells' - // filter through its pixel tests alone. - for key in sampler_keys(&n) { - let SpecKey::SamplerState { fields, .. } = key else { - unreachable!() - }; - let read = match fields & SamplerWord::PIXEL_GATED { - 0 => SamplerWord::PIXEL_COORDINATES, - _ => SamplerWord::PIXEL_NEAREST | SamplerWord::PIXEL_GATED, - }; - assert_eq!(fields & !read, 0, "{what}: {key:?}"); - } - if sampler.is_none() { - let reads = |a: &FunctionArtifact| { - sampler_keys(a).iter().fold(0, |m, k| match k { - SpecKey::SamplerState { fields, .. } => m | fields, - _ => m, - }) - }; - assert_ne!(reads(&e) & !conversion, 0, "{what} exact"); - } else { - assert_eq!(sampler_keys(&n), Vec::new(), "{what}"); - } - let words = |a: &FunctionArtifact| a.module.words.len(); - assert!( - words(&n) < words(&e), - "{what}: {} words natively, {} emulated", - words(&n), - words(&e) - ); - assert!( - !e.requirements - .properties - .contains(&VkProperty::DeviceSampling), - "{what} exact" - ); - assert!(!noted(&e, PrecisionNote::DeviceSampling), "{what} exact"); - assert!(noted(&e, filtered), "{what} exact"); - } - } -} diff --git a/crates/metal2vulkan/src/tests/engine_linear_half/edge_samples.tsv b/crates/metal2vulkan/src/tests/engine_linear_half/edge_samples.tsv deleted file mode 100644 index 0559d4eda..000000000 --- a/crates/metal2vulkan/src/tests/engine_linear_half/edge_samples.tsv +++ /dev/null @@ -1,94 +0,0 @@ -115 x f 217 124 980bdba7,9af31e44 69b069a6,40d11574 449f6000,44b06000,3b790000,3f952000 -115 x f 20 187 bda3a98c,db0bfb06 26d3713a,ecf9b694 45f46000,beb88000,c6726000,c56c4000 -115 x f 197 88 ce306f82,26af118 d22bfac1,806a26c8 c65a6000,c204e000,c5d60000,37b88000 -115 x f 129 124 69b069a6,40d11574 3f5d19,fa8e499d 44ce2000,44bbc000,40ae0000,c6cb2000 -115 x f 243 16 86ec8b68,204fed18 5850c856,da638552 bf0ac000,410a0000,c598e000,c14c4000 -115 x f 246 176 f2293745,6e76fb1e 8bc3c477,9482f7ac c03b6000,c5766000,c71ba000,45014000 -115 y f 24 205 b50bed6,f62aa291 32ff268a,28395a74 bfc5e000,3ca9a000,419ac000,c6b2c000 -115 y f 76 21 21f5f197,ef2a3046 c42e39be,772c3453 c5fb8000,bf9dc000,3e326000,455ea000 -115 y f 142 245 98bcfa26,21eab83a 4557f08f,c96e3009 c6d7c000,403d8000,be294000,c0c0a000 -115 y f 126 233 71e165ba,8c1bebf0 b1ab7adf,8f08addf 46de4000,45bf2000,c5010000,b9b18000 -115 y f 212 202 68040e38,186a5a4f be0a2662,7844f927 3ca9a000,43b02000,c7086000,46e22000 -115 y f 107 87 c42e39be,772c3453 b81d123,60c6bb74 c1862000,c01bc000,be6da000,4687a000 -115 x h 217 124 980bdba7,9af31e44 69b069a6,40d11574 64fb,6583,1bc8,3ca9 -115 x h 20 187 bda3a98c,db0bfb06 26d3713a,ecf9b694 6fa3,b5c4,f393,eb62 -115 x h 197 88 ce306f82,26af118 d22bfac1,806a26c8 f2d3,d027,eeb0,171 -115 x h 129 124 69b069a6,40d11574 3f5d19,fa8e499d 6671,65de,4570,f659 -115 x h 243 16 86ec8b68,204fed18 5850c856,da638552 b856,4850,ecc7,ca62 -115 x h 246 176 f2293745,6e76fb1e 8bc3c477,9482f7ac c1db,ebb3,f8dd,680a -115 y h 24 205 b50bed6,f62aa291 32ff268a,28395a74 be2f,254d,4cd6,f596 -115 y h 76 21 21f5f197,ef2a3046 c42e39be,772c3453 efdc,bcee,3193,6af5 -115 y h 142 245 98bcfa26,21eab83a 4557f08f,c96e3009 f6be,41ec,b14a,c605 -115 y h 126 233 71e165ba,8c1bebf0 b1ab7adf,8f08addf 76f2,6df9,e808,8d8c -115 y h 212 202 68040e38,186a5a4f be0a2662,7844f927 254d,5d81,f843,7711 -115 y h 107 87 c42e39be,772c3453 b81d123,60c6bb74 cc31,c0de,b36d,743d -125 y f 56 211 c783b018,3ed60b71,b9fbb213,3f2d549b 352ddd8f,4988f74f,39b51430,3bfe5a92 c74dc325,486fb0df,b99d06b4,3f07d961 -125 y f 112 76 492fd83c,3cc482c6,345b3afc,33fd0f58 b5d09ee6,4ce90d07,4d74b6d3,4960922b 48c5d344,4c4beb66,4cd61ff9,48c47fe6 -125 x h 37 240 b5d881b3,b83567d9,b7c3388e,4b8450be 33b57014,b7578b7d,c555e4da,b3030aab 8000,80f7,ea44,7bff -125 x h 169 219 ba8aa4e9,3260a51d,3f756c9e,b89700ec 35eef1c0,b2da2389,c957c771,44ffd446 88f5,8000,fbff,66d6 -125 x h 59 58 b26c81a4,c06cc0a3,407d11a3,cc5c1f38 b435c3da,bf2b9e24,3806dd46,c07074ac 8000,c206,421d,fbff -125 x h 250 255 ba8aa4e9,3260a51d,3f756c9e,b89700ec 35eef1c0,b2da2389,c957c771,44ffd446 8027,8000,fbff,67f6 -125 x h 6 92 ba8aa4e9,3260a51d,3f756c9e,b89700ec 35eef1c0,b2da2389,c957c771,44ffd446 918b,8000,fbff,61bf -125 x h 68 12 b26c81a4,c06cc0a3,407d11a3,cc5c1f38 b435c3da,bf2b9e24,3806dd46,c07074ac 8000,c31d,4389,fbff -125 x h 152 11 c49845a5,34043672,b4b04b11,c05e9007 3e655936,b674aae8,b2950c6d,3f371baf e48d,8000,8005,c298 -125 x h 42 53 3518e32d,bf2186cd,b37e68de,c03af222 36e6a7cd,c2d46525,344289ac,baa0ff86 1f,cd9f,8000,c0a2 -125 x h 239 41 3518e32d,bf2186cd,b37e68de,c03af222 36e6a7cd,c2d46525,344289ac,baa0ff86 1a,cc62,8000,c0e8 -125 x h 60 133 b3f03bf3,b9510907,c1315077,c6f88a9e 32949cc3,bcd94b36,4a7c7707,42bac752 8000,a31a,7bff,f370 -125 y h 191 203 4308f078,b4f291d5,350c1da4,425d2c91 46bc602d,33fcd350,b8584e79,c96bd4d6 7466,8000,8283,fbff -125 y h 2 227 cd1c448e,b5eae764,3a9a6cae,b32ae66d c9a874cf,c4e6b066,cc038b8e,33d8bc81 fbff,cb35,fbff,8000 -125 y h 53 65 cd1c448e,b5eae764,3a9a6cae,b32ae66d c9a874cf,c4e6b066,cc038b8e,33d8bc81 fbff,ddf8,fbff,8000 -125 y h 219 80 cbe02a67,3b18703d,b4cf1405,4154c10d 37faba44,cc979cd2,322e8d14,c8d0ada9 fbff,fbff,8000,fbff -125 y h 194 246 4308f078,b4f291d5,350c1da4,425d2c91 46bc602d,33fcd350,b8584e79,c96bd4d6 7478,8000,828d,fbff -125 y h 224 34 bb58f537,3f866c90,b5a2595a,b93633d4 477f344d,bf4e03cd,33ec2b7a,bc6a7c14 7afa,b895,8000,a26c -125 y h 166 207 c68e81f9,c89d552a,44728059,337707d4 c8962d54,b25625bf,47e0046c,b31df995 fbff,fbff,7bff,8000 -125 y h 188 182 4308f078,b4f291d5,350c1da4,425d2c91 46bc602d,33fcd350,b8584e79,c96bd4d6 7454,8000,8279,fbff -125 y h 14 142 cd1c448e,b5eae764,3a9a6cae,b32ae66d c9a874cf,c4e6b066,cc038b8e,33d8bc81 fbff,d64e,fbff,8000 -125 y h 209 210 357ca2d3,b92d55d5,47ec78ed,400ad25e b478f680,362be8c7,b5d2d3e4,37303cfe 8000,81da,756d,365f -92 x f 181 62 b9c7a10f 2d2647c 3ff04000,3b9e4000,436c8000,3f800000 -92 x f 139 250 47abf6d3 3485259c 43982000,403d0000,3b5aa000,3f800000 -92 x f 131 69 d63dd147 9e218f96 46398000,47324000,45242000,3f800000 -92 x f 70 95 4fc0a161 e1d958d8 3a8a6000,3d9ee000,4567a000,3f800000 -92 x f 139 41 91029fad 123a0b28 47372000,4526a000,40f1e000,3f800000 -92 x f 9 36 70705b2b 800a4431 3f2d2000,4400e000,3f398000,3f800000 -92 y f 80 30 58e110b3 241ef4c8 40b40000,40242000,3d418000,3f800000 -92 y f 71 173 124b75a8 e3373137 43166000,44e26000,45434000,3f800000 -92 y f 230 41 a72ba45f a7a59c6f 40dac000,41c5a000,42774000,3f800000 -92 y f 131 171 e6b46a3b 1594c782 46872000,44966000,45e2a000,3f800000 -92 y f 167 1 4543011a 896a26ea 458a4000,42318000,40416000,3f800000 -92 y f 81 5 813a1ecc 9e9c081d 454fe000,46374000,412b6000,3f800000 -92 x h 181 62 b9c7a10f 2d2647c 3f82,1cf2,5b64,3c00 -92 x h 139 250 47abf6d3 3485259c 5cc1,41e8,1ad5,3c00 -92 x h 131 69 d63dd147 9e218f96 71cc,7992,6921,3c00 -92 x h 70 95 4fc0a161 e1d958d8 1453,2cf7,6b3d,3c00 -92 x h 139 41 91029fad 123a0b28 79b9,6935,478f,3c00 -92 x h 9 36 70705b2b 800a4431 3969,6007,39cc,3c00 -92 y h 80 30 58e110b3 241ef4c8 45a0,4121,2a0c,3c00 -92 y h 71 173 124b75a8 e3373137 58b3,6713,6a1a,3c00 -92 y h 230 41 a72ba45f a7a59c6f 46d6,4e2d,53ba,3c00 -92 y h 131 171 e6b46a3b 1594c782 7439,64b3,6f15,3c00 -92 y h 167 1 4543011a 896a26ea 6c52,518c,420b,3c00 -92 y h 81 5 813a1ecc 9e9c081d 6a7f,71ba,495b,3c00 -93 x f 81 72 44a68c22 4395ce71 3a60e000,3b95a000,3b8b0000,3f800000 -93 x f 231 80 b8bcc36f 30d0dc42 42fc6000,42056000,41814000,3f800000 -93 x f 239 223 b34bfada 36ac3f6 40e0e000,41834000,40d8a000,3f800000 -93 x f 153 128 7cde7b6 3ba77839 3971c000,3adf0000,3a6ce000,3f800000 -93 x f 181 81 36ac3f6 e93ae291 44b78000,45698000,44458000,3f800000 -93 x f 39 136 d1626cc6 3af753e7 43b9a000,44116000,43250000,3f800000 -93 y f 164 53 d76ef900 19159c7 43b80000,4408a000,442ac000,3f800000 -93 y f 64 185 e6f01c7 24a54b6c 3905a000,389a8000,38e1a000,3f800000 -93 y f 252 76 29c5a3ec 2ab5cb30 3a198000,39e4c000,39ac2000,3f800000 -93 y f 112 149 30ddd2a5 dbafcbc1 44c48000,44d44000,444da000,3f800000 -93 y f 44 209 cfe5d752 d4fa1775 444c2000,440f4000,4483e000,3f800000 -93 y f 180 17 18b6d0f7 97a265c3 409e8000,40572000,40aba000,3f800000 -93 x h 81 72 44a68c22 4395ce71 1307,1cad,1c58,3c00 -93 x h 231 80 b8bcc36f 30d0dc42 57e3,502b,4c0a,3c00 -93 x h 239 223 b34bfada 36ac3f6 4707,4c1a,46c5,3c00 -93 x h 153 128 7cde7b6 3ba77839 b8e,16f8,1367,3c00 -93 x h 181 81 36ac3f6 e93ae291 65bc,6b4c,622c,3c00 -93 x h 39 136 d1626cc6 3af753e7 5dcd,608b,5928,3c00 -93 y h 164 53 d76ef900 19159c7 5dc0,6045,6156,3c00 -93 y h 64 185 e6f01c7 24a54b6c 82d,4d4,70d,3c00 -93 y h 252 76 29c5a3ec 2ab5cb30 10cc,f26,d61,3c00 -93 y h 112 149 30ddd2a5 dbafcbc1 6624,66a2,626d,3c00 -93 y h 44 209 cfe5d752 d4fa1775 6261,607a,641f,3c00 -93 y h 180 17 18b6d0f7 97a265c3 44f4,42b9,455d,3c00 diff --git a/crates/metal2vulkan/src/tests/engine_linear_half/levels.rs b/crates/metal2vulkan/src/tests/engine_linear_half/levels.rs deleted file mode 100644 index 4f9dde330..000000000 --- a/crates/metal2vulkan/src/tests/engine_linear_half/levels.rs +++ /dev/null @@ -1,382 +0,0 @@ -//! The level a depth comparison through a runtime sampler reads: where the sampler's word reads one -//! texel, the shader fetches it from the level the word reads at the sample's level or a kernel's -//! bias (`fetched::FetchLevel::Word`), on the CPU interpreter against Metal's rule, which our probe -//! measured through runtime and argument buffer's samplers: the level rounded to -//! `half` (a NaN read as 0), clamped into the sampler's level clamp as `f32`s and into the -//! texture's levels, and under a nearest mip filter `L + 1` where its fraction truncated onto -//! sixty-fourths passes one half; level 0 without a mip filter. - -use super::*; -use crate::bind::SamplerDescriptor; -use crate::float16::{f16_bits_to_f32, f32_to_f16_bits}; -use crate::metal::{CompareFunction, SamplerMipFilter}; -use crate::pipeline::artifact::SpecializedNote; - -/// How a kernel's `sample_compare` states its level: `level(x)`, a kernel's `bias(x)` (the -/// explicit level `x`), or neither (level 0). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum Stated { - Level, - Bias, - Neither, -} - -/// A kernel comparing `depth2d` slot 0 through runtime sampler slot 0 at buffer 0's lane -/// `tid` (a `float4`: the coordinate, the reference in `z`, and the level in `w`) at the level -/// `stated` names; buffer 1's lane `tid` is a `float4` whose `x` is the pass. -pub(super) fn runtime_level_kernel(stated: Stated) -> String { - let (level, lod) = match stated { - Stated::Level => ("true", "%lod"), - Stated::Bias => ("false", "%lod"), - Stated::Neither => ("false", "0.0"), - }; - format!( - r#"define void @k(ptr addrspace(1) %t, ptr addrspace(1) %c, ptr addrspace(1) %out, ptr addrspace(2) %s, i32 %tid) {{ - %i = zext i32 %tid to i64 - %p = getelementptr inbounds <4 x float>, ptr addrspace(1) %c, i64 %i - %c4 = load <4 x float>, ptr addrspace(1) %p, align 16 - %uv = shufflevector <4 x float> %c4, <4 x float> zeroinitializer, <2 x i32> - %ref = extractelement <4 x float> %c4, i64 2 - %lod = extractelement <4 x float> %c4, i64 3 - %r = call {{ float, i8 }} @air.sample_compare_depth_2d.f32(ptr addrspace(1) %t, ptr addrspace(2) %s, i32 1, <2 x float> %uv, float %ref, i1 true, <2 x i32> zeroinitializer, i1 {level}, float {lod}, float 0.0, i32 0) - %v = extractvalue {{ float, i8 }} %r, 0 - %v4 = insertelement <4 x float> zeroinitializer, float %v, i64 0 - %q = getelementptr inbounds <4 x float>, ptr addrspace(1) %out, i64 %i - store <4 x float> %v4, ptr addrspace(1) %q, align 16 - ret void -}} - -declare {{ float, i8 }} @air.sample_compare_depth_2d.f32(ptr addrspace(1), ptr addrspace(2), i32, <2 x float>, float, i1, <2 x i32>, i1, float, float, i32) - -!air.kernel = !{{!0}} -!0 = !{{ptr @k, !1, !2}} -!1 = !{{}} -!2 = !{{!3, !4, !5, !6, !7}} -!3 = !{{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"depth2d", !"air.arg_name", !"t"}} -!4 = !{{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"c"}} -!5 = !{{i32 2, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"}} -!6 = !{{i32 3, !"air.sampler", !"air.location_index", i32 0, i32 1, !"air.arg_type_name", !"sampler", !"air.arg_name", !"s"}} -!7 = !{{i32 4, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"tid"}} -"# - ) -} - -/// The level Metal reads at level `x` (`None`: level 0) through a sampler of nearest filters and -/// mip filter `mip` whose level clamp is `(min, max)` (`f32`s, a runtime sampler's), of a texture -/// of `levels` levels (module docs). -fn metal_level(x: Option, mip: SamplerMipFilter, (min, max): (f32, f32), levels: u32) -> u32 { - if mip == SamplerMipFilter::NotMipmapped { - return 0; - } - let x = match x { - Some(x) if !x.is_nan() => f16_bits_to_f32(f32_to_f16_bits(x)), - _ => 0.0, - }; - let x = x.max(min).min(max).clamp(0.0, (levels - 1) as f32); - let whole = x.floor(); - let q = ((x - whole) * 64.0).floor() / 64.0; - whole as u32 + u32::from(q > 0.5) -} - -/// Whether specialized note `n` holds where the runtime sampler's word is `word` and the texture -/// slot's `TexelFormat` is `class` (a `SamplerState` specialization is the word masked by its -/// fields). -fn holds(n: &SpecializedNote, word: u32, class: u32) -> bool { - n.when.iter().any(|clause| { - clause.all.iter().all(|t| { - let v = match t.key { - SpecKey::SamplerState { fields, .. } => word & fields, - SpecKey::TexelFormat(_) => class, - other => panic!("a test of {other:?}"), - }; - ((v & t.mask) == t.bits) == t.equal - }) - }) -} - -/// A runtime sampler's `sample_compare` with a level, a kernel's bias, or neither, fetches its -/// texel from the level its word reads where the word reads one texel, on every lane of the -/// interpreter: nearest filters under a nearest mip filter through level clamps of whole, half-way, -/// and sixty-fourth bounds (and an empty range of levels), and without a mip filter; levels below -/// 0, past the texture's three, at and around the half-way points, the infinities, and a NaN, on -/// `Depth32Float` and `Depth16Unorm`. The module reads the word's mip filter and level clamp, and -/// records `DeviceDepthComparison` only where the word filters. -#[test] -fn a_runtime_comparison_reads_the_level_its_word_reads() { - let levels = [ - -1.0f32, - 0.0, - 0.25, - 0.5, - 0.5078125, - 0.515625, - 0.75, - 1.0, - 1.4, - 1.5, - 1.53125, - 2.0, - 2.6, - 7.0, - f32::NAN, - f32::INFINITY, - f32::NEG_INFINITY, - ]; - let clamps = [ - (0.0f32, f32::MAX), - (0.75, 2.5), - (1.515625, 1.75), - (0.5, 0.5), - (0.0, 0.0), - (2.0, 100.0), - (0.3, 1.49), - ]; - let p = lavapipe(); - let (w, h) = (12i64, 8i64); - for stated in [Stated::Level, Stated::Bias, Stated::Neither] { - let name = format!("{stated:?}"); - let Some(bc) = assemble(&name, &runtime_level_kernel(stated)) else { - return; - }; - let a = compile(&bc, "k", &p).unwrap_or_else(|e| panic!("{name}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name}: {e}")); - let fields = a - .interface - .read_keys() - .into_iter() - .find_map(|k| match k { - SpecKey::SamplerState { fields, .. } => Some(fields), - _ => None, - }) - .unwrap_or_else(|| panic!("{name}: no sampler word")); - let levels_read = SamplerWord::MIP_FILTER | SamplerWord::LEVEL_MIN | SamplerWord::LEVEL_MAX; - assert_eq!(fields & levels_read, levels_read, "{name}"); - let notes: Vec<&SpecializedNote> = a - .specialized - .iter() - .filter(|n| n.note == PrecisionNote::DeviceDepthComparison) - .collect(); - let [note] = notes[..] else { - panic!("{name}: the device comparison's note is not specialized: {notes:?}"); - }; - let (plan, m) = typed_module(&bc, "k", &p).expect("typed module"); - for (mip, clamp) in clamps - .iter() - .map(|&c| (SamplerMipFilter::Nearest, c)) - .chain([(SamplerMipFilter::NotMipmapped, (0.0, f32::MAX))]) - { - let mut desc = SamplerDescriptor::new(); - desc.mip_filter = mip; - (desc.lod_min_clamp, desc.lod_max_clamp) = clamp; - desc.compare_function = CompareFunction::LessEqual; - let word = SamplerWord::of(&desc).0; - for (seed, pf) in DEPTHS.iter().enumerate() { - let what = format!("{name} {mip:?} {clamp:?} {pf:?}"); - let class = texel_format(*pf).0; - assert!(!holds(note, word, class), "{what}: noted"); - for linear in [SamplerWord::MIN_LINEAR, 2 << SamplerWord::MIP_FILTER_SHIFT] { - let filtered = word & !SamplerWord::MIP_FILTER | linear; - assert!(holds(note, filtered, class), "{what}: not noted"); - } - let texs: Vec = (0..3) - .map(|l| Texels::random(class, w >> l, h >> l, seed as u64 + 71 + l as u64)) - .collect(); - // The comparison's binding and the one without comparison it fetches through hold - // the same texels. - let images: Vec = combined_slots(&m) - .iter() - .map(|&(slot, _)| { - let mut image = Image::new(slot, [w as u32, h as u32, 1], 1, 3, 1); - for (l, tex) in texs.iter().enumerate() { - for y in 0..tex.h as u32 { - for x in 0..tex.w as u32 { - let at = image.index(l as u32, 0, 0, [x, y, 0]).expect("texel"); - let v = tex.texel(0, i64::from(x), i64::from(y)); - image.texels[at] = v.map(|c| tex.fetched(c).to_bits()); - } - } - } - image - }) - .collect(); - let lanes = compare_lanes(&texs[0], w, h, &levels); - let bytes: Vec = lanes - .iter() - .flat_map(|(x, y, r, l)| { - [(x / w as f64) as f32, (y / h as f64) as f32, *r, *l].map(f32::to_le_bytes) - }) - .flatten() - .collect(); - let res = resources(&plan, &[bytes, vec![0xab; 16 * lanes.len()]], class); - let res = with_word(res, &a, Some(word)); - let out = run_images(&m, &res, &images, lanes.len() as u32, false); - for (lane, ((x, y, r, l), got)) in lanes.iter().zip(&out).enumerate() { - let x_level = (stated != Stated::Neither).then_some(*l); - let level = metal_level(x_level, mip, clamp, 3) as usize; - let tex = &texs[level]; - let (u, v) = ( - f64::from((x / w as f64) as f32), - f64::from((y / h as f64) as f32), - ); - let (lw, lh) = (tex.w as f64, tex.h as f64); - let (sx, sy) = ( - seen(u * lw, lw, Address::Edge, false), - seen(v * lh, lh, Address::Edge, false), - ); - let at = (sx.floor() as i64, sy.floor() as i64); - let want = tap_pass(tex, 2, *r, tap(tex, Address::Edge, 0, at, 0)); - assert_eq!( - got[0], want, - "{what} lane {lane} ({x}, {y}) level {l} (Metal's {level}) reference {r}" - ); - } - } - } - } -} - -/// Metal's blend of two levels' passes `[p0, p1]` (each 0 or 1) by `1 - q` and `q`: the passes as -/// `r8Unorm` codes 0 and 255, their sum `255 (p0 (1 - q) + p1 q)` rounded once onto sixteenths of a -/// code, ties up, divided by 255. -fn blend([p0, p1]: [f32; 2], q: f32) -> f32 { - let m = (q * 64.0) as u32; - let s = p0 as u32 * (64 - m) + p1 as u32 * m; - let n = (255 * s + 2) / 4; - n as f32 / 4080.0 -} - -/// A `sample_compare` through a constexpr sampler of nearest filters under a linear mip filter, at -/// a dynamic level, blends two levels' comparisons in the shader where the slot's format is -/// measured, on every lane of the interpreter: with `L + q` the level Metal's rule reads (rounded -/// to `half`, clamped into the sampler's level clamp as `half`s and into the texture's three -/// levels, its fraction truncated onto sixty-fourths), the comparison of level `L`'s texel weighted -/// `1 - q` and level `L + 1`'s weighted `q` as Metal blends them ([`blend`]), through clamps of -/// none, of whole and half-way bounds, and of a sixty-fourth's fraction, on `Depth32Float` and -/// `Depth16Unorm`. The device's comparison stays in the arm a format of no measured class takes, -/// where the module notes it and the filter. -#[test] -fn a_linear_mip_filters_comparison_blends_metals_two_levels() { - use crate::lower::sampler::level::LevelSnap; - let levels = [ - -1.0f32, - 0.0, - 0.015625, - 0.25, - 0.5, - 0.5078125, - 0.75, - 0.99, - 1.0, - 1.4, - 1.53125, - 1.984375, - 2.0, - 2.6, - 7.0, - f32::NAN, - f32::INFINITY, - f32::NEG_INFINITY, - ]; - // (lod_min_clamp, lod_max_clamp) as halfs: none, whole and half-way bounds, a sixty-fourth's. - let clamps: [(u16, u16); 4] = [ - (0x0000, 0x7bff), - (0x3a00, 0x4100), - (0x3c10, 0x3e00), - (0x3e00, 0x3e00), - ]; - let p = lavapipe(); - let (w, h) = (12i64, 8i64); - for (min, max) in clamps { - let words = sampler_words(0, 2, 1, false, 0) & !(0xf << 16) & !(0xffff_ffff << 24) - | 2 << 16 - | u64::from(min) << 24 - | u64::from(max) << 40; - let name = format!("clamp {min:#06x} {max:#06x}"); - let Some(bc) = assemble(&name, &level_compare_kernel(words)) else { - return; - }; - let a = compile(&bc, "k", &p).unwrap_or_else(|e| panic!("{name}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name}: {e}")); - for note in [ - PrecisionNote::DeviceDepthComparison, - PrecisionNote::FloatSampleFilter, - ] { - let n = a - .specialized - .iter() - .find(|n| n.note == note) - .unwrap_or_else(|| panic!("{name}: {note:?} is not specialized")); - for pf in DEPTHS { - assert!( - !holds(n, 0, texel_format(pf).0), - "{name}: {note:?} on {pf:?}" - ); - } - assert!(holds(n, 0, 0), "{name}: {note:?} on an unmeasured class"); - } - let snap = LevelSnap { - mip: crate::air::abi::MipFilter::Linear, - min: f16_bits_to_f32(min).to_bits(), - max: f16_bits_to_f32(max).to_bits(), - }; - let (plan, m) = typed_module(&bc, "k", &p).expect("typed module"); - for (seed, pf) in DEPTHS.iter().enumerate() { - let what = format!("{name} {pf:?}"); - let class = texel_format(*pf).0; - let texs: Vec = (0..3) - .map(|l| Texels::random(class, w >> l, h >> l, seed as u64 + 83 + l as u64)) - .collect(); - let images: Vec = combined_slots(&m) - .iter() - .map(|&(slot, _)| { - let mut image = Image::new(slot, [w as u32, h as u32, 1], 1, 3, 1); - for (l, tex) in texs.iter().enumerate() { - for y in 0..tex.h as u32 { - for x in 0..tex.w as u32 { - let at = image.index(l as u32, 0, 0, [x, y, 0]).expect("texel"); - let v = tex.texel(0, i64::from(x), i64::from(y)); - image.texels[at] = v.map(|c| tex.fetched(c).to_bits()); - } - } - } - image - }) - .collect(); - let lanes = compare_lanes(&texs[0], w, h, &levels); - let bytes: Vec = lanes - .iter() - .flat_map(|(x, y, r, l)| { - [(x / w as f64) as f32, (y / h as f64) as f32, *r, *l].map(f32::to_le_bytes) - }) - .flatten() - .collect(); - let res = resources(&plan, &[bytes, vec![0xab; 16 * lanes.len()]], class); - let out = run_images(&m, &res, &images, lanes.len() as u32, false); - for (lane, ((x, y, r, l), got)) in lanes.iter().zip(&out).enumerate() { - let lambda = snap.of(*l).min(2.0); - let whole = lambda.floor(); - let q = lambda - whole; - let pass = |level: usize| { - let tex = &texs[level.min(2)]; - let (u, v) = ( - f64::from((x / w as f64) as f32), - f64::from((y / h as f64) as f32), - ); - let (lw, lh) = (tex.w as f64, tex.h as f64); - let (sx, sy) = ( - seen(u * lw, lw, Address::Edge, false), - seen(v * lh, lh, Address::Edge, false), - ); - let at = (sx.floor() as i64, sy.floor() as i64); - f32::from_bits(tap_pass(tex, 2, *r, tap(tex, Address::Edge, 0, at, 0))) - }; - let want = blend([pass(whole as usize), pass(whole as usize + 1)], q); - assert_eq!( - got[0], - want.to_bits(), - "{what} lane {lane} ({x}, {y}) level {l} (Metal's {lambda}) reference {r}" - ); - } - } - } -} diff --git a/crates/metal2vulkan/src/tests/engine_linear_half/packed.rs b/crates/metal2vulkan/src/tests/engine_linear_half/packed.rs deleted file mode 100644 index 086888737..000000000 --- a/crates/metal2vulkan/src/tests/engine_linear_half/packed.rs +++ /dev/null @@ -1,664 +0,0 @@ -//! Metal's linear filter of the packed formats, on the CPU interpreter against Metal's own samples, -//! bit for bit. -//! -//! `packed_samples.tsv` holds 384 of the linear samples our probes took (an Apple M3 Max on macOS -//! 26.7 and an Apple M4 on macOS 27.0.1, byte-identical; random finite texel words, clamp to edge, -//! exact 1/256 fractions): 8 per format, dimension (1D, 2D, 3D), and result (`float`, `half`), -//! chosen to tell the rule from its simpler neighbours (the sum without the terms' truncation, -//! every channel on the 8-bit grid, the exact value rounded once; for a small float the sum rounded -//! to `f32`). Then 48 of our probe's (the Apple M3 Max): `RG11B10Float` words with infinities and -//! NaNs among their channels, 8 per dimension and result: a NaN tap of nonzero weight gives Metal's -//! NaN (`0x7fc00000`, `half` `0x7e00`), else an infinity gives `+inf`, a tap of zero weight -//! neither, and in 3D a tap whose product weight rounds to zero is not of zero weight. The small -//! floats' 3D rows are among those the half-float rule answers (it misses about 0.3% of their 3D -//! channels, the residue). Each row is a sample through a constexpr sampler and through a runtime -//! one, on every device value a packed channel's code reads as: exact, lavapipe's product by the -//! reciprocal, and ANV's and NVIDIA's 5- and 6-bit codes replicated to 8 bits (a small float's -//! value is exact, its NaN's payload kept). - -use super::*; - -/// Metal's samples, one per line: the raw format (40 `B5G6R5Unorm`, 41 `A1BGR5Unorm`, 42 -/// `ABGR4Unorm`, 43 `BGR5A1Unorm`, 90 `RGB10A2Unorm`, 92 `RG11B10Float`, 93 `RGB9E5Float`, 94 -/// `BGR10A2Unorm`), the dimension (1, 2, or 3), the result (`f` `float`, `h` `half`), the -/// fractions `kx`, `ky`, and `kz` in 1/256 steps, the taps' texel words (hex; 1D `i`, `i + 1`; 2D -/// `(i, j)`, `(i + 1, j)`, `(i, j + 1)`, `(i + 1, j + 1)`; 3D those of plane `l`, then of `l + -/// 1`), and the result's lanes as bits (hex). -const SAMPLES: &str = include_str!("packed_samples.tsv"); - -/// The file's rows in runs of `ROWS`, each of one format, dimension, and result: a texture -/// `2 · ROWS` texels wide holds a run's taps. -const ROWS: usize = 8; - -/// The width of each sample's texture. -const WIDTH: u32 = 2 * ROWS as u32; - -/// One of Metal's samples. -struct Sample { - raw: u32, - dims: u32, - half: bool, - k: [u32; 3], - words: Vec, - out: [u32; 4], -} - -fn samples() -> Vec { - let hex = |s: &str| -> Vec { - s.split(',') - .map(|x| u32::from_str_radix(x, 16).expect("hex")) - .collect() - }; - SAMPLES - .lines() - .map(|l| { - let f: Vec<&str> = l.split(' ').collect(); - let num = |i: usize| -> u32 { f[i].parse().expect("number") }; - let out = hex(f[7]); - Sample { - raw: num(0), - dims: num(1), - half: f[2] == "h", - k: [num(3), num(4), num(5)], - words: hex(f[6]), - out: [out[0], out[1], out[2], out[3]], - } - }) - .collect() -} - -/// The pixel format of raw format `raw`, and its channels' fields `(lsb, bits)` red to alpha (a -/// missing alpha reads 1); `None` fields for a small float. -fn format(raw: u32) -> (PixelFormat, Option<[Option<(u32, u32)>; 4]>) { - use PixelFormat as P; - let f = |r, g, b, a| Some([Some(r), Some(g), Some(b), a]); - match raw { - 40 => (P::B5G6R5Unorm, f((11, 5), (5, 6), (0, 5), None)), - 41 => (P::A1BGR5Unorm, f((11, 5), (6, 5), (1, 5), Some((0, 1)))), - 42 => (P::ABGR4Unorm, f((12, 4), (8, 4), (4, 4), Some((0, 4)))), - 43 => (P::BGR5A1Unorm, f((10, 5), (5, 5), (0, 5), Some((15, 1)))), - 90 => ( - P::RGB10A2Unorm, - f((0, 10), (10, 10), (20, 10), Some((30, 2))), - ), - 94 => ( - P::BGR10A2Unorm, - f((20, 10), (10, 10), (0, 10), Some((30, 2))), - ), - 92 => (P::RG11B10Float, None), - 93 => (P::RGB9E5Float, None), - _ => panic!("raw format {raw}"), - } -} - -/// How a device reads a packed channel's code. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Decode { - /// `c / S` correctly rounded. - Exact, - /// lavapipe's `c · RN(1 / S)`. - Reciprocal, - /// ANV's and NVIDIA's: a 4-, 5-, or 6-bit code's bits replicated to 8, over 255. - Replicated, -} - -/// The small float `bits` of `mantissa` bits (and a 5-bit exponent above them), exactly: an -/// exponent of all ones an infinity, or a NaN keeping its payload. -fn small_float(bits: u32, mantissa: u32) -> f32 { - let (e, m) = (bits >> mantissa, bits & ((1 << mantissa) - 1)); - if e == 0x1f { - return f32::from_bits(0x7f80_0000 | m << (23 - mantissa)); - } - let m = f64::from(m) / f64::from(1u32 << mantissa); - (match e { - 0 => m * 2f64.powi(-14), - e => (1.0 + m) * 2f64.powi(e as i32 - 15), - }) as f32 -} - -/// The device's texel of word `word` in raw format `raw`, read as `decode` reads its codes. -fn texel(raw: u32, word: u32, decode: Decode) -> [u32; 4] { - let lanes: [f32; 4] = match (raw, format(raw).1) { - (92, _) => [ - small_float(word & 0x7ff, 6), - small_float(word >> 11 & 0x7ff, 6), - small_float(word >> 22, 5), - 1.0, - ], - (93, _) => { - let e = (word >> 27) as i32 - 24; - std::array::from_fn(|c| match c { - 3 => 1.0, - c => (f64::from(word >> (9 * c) & 0x1ff) * 2f64.powi(e)) as f32, - }) - } - (_, Some(fields)) => fields.map(|field| { - let Some((lsb, b)) = field else { - return 1.0; - }; - let (c, s) = (word >> lsb & ((1 << b) - 1), (1u32 << b) - 1); - match decode { - Decode::Exact => (f64::from(c) / f64::from(s)) as f32, - Decode::Reciprocal => c as f32 * (1.0 / s as f32), - Decode::Replicated if (4..=6).contains(&b) => { - let r = (c << (8 - b)) | (c >> (2 * b - 8)); - r as f32 / 255.0 - } - Decode::Replicated => (f64::from(c) / f64::from(s)) as f32, - } - }), - _ => unreachable!("raw format {raw}"), - }; - lanes.map(f32::to_bits) -} - -/// Each row's taps in texture coordinates: row `k`'s at `x` `2k` and `2k + 1`, rows and planes 0 -/// and 1, in the file's order. -fn sites(dims: u32, k: u32) -> Vec<[u32; 3]> { - let x = 2 * k; - match dims { - 1 => vec![[x, 0, 0], [x + 1, 0, 0]], - 2 => vec![[x, 0, 0], [x + 1, 0, 0], [x, 1, 0], [x + 1, 1, 0]], - _ => (0..8).map(|t| [x + (t & 1), t >> 1 & 1, t >> 2]).collect(), - } -} - -/// Each of Metal's samples of each packed format, through a constexpr linear clamp-to-edge -/// sampler and a runtime sampler of that state, in 1D, 2D, and 3D, with `float` and `half` -/// results, is Metal's bytes, whatever the device reads a packed code as (a small float's value -/// is exact on every device). The emulation is reached. -#[test] -fn packed_linear_samples_are_metals_bytes() { - let p = lavapipe(); - let all = samples(); - assert_eq!(all.len(), 432); - let runs: Vec<&[Sample]> = all.chunks(ROWS).collect(); - for run in &runs { - let s = &run[0]; - assert!( - run.iter() - .all(|r| (r.raw, r.dims, r.half) == (s.raw, s.dims, s.half)), - "a run of one format, dimension, and result" - ); - } - let word = runtime_word( - SamplerAddressMode::ClampToEdge, - false, - SamplerBorderColor::TransparentBlack, - ); - for dims in 1..=3u32 { - let (form, routine) = match dims { - 1 => (Form::OneD, "sampler.linear.span"), - 2 => (Form::Plain { offset: (0, 0) }, "sampler.linear.quad"), - _ => (Form::ThreeD { offset: (0, 0, 0) }, "sampler.linear.block"), - }; - for half in [false, true] { - for runtime in [false, true] { - let sampler = (!runtime).then(|| linear(1, false, 0)); - let name = format!("{dims}D half={half} runtime={runtime}"); - let Some(bc) = assemble(&name, &kernel_of(sampler, form, !half)) else { - return; - }; - let a = compile(&bc, "k", &p).unwrap_or_else(|e| panic!("{name}: {e}")); - assert!(a.strategies.entries.contains_key(routine), "{name}"); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name}: {e}")); - let (plan, m) = typed_module(&bc, "k", &p).expect("typed module"); - let mine = runs - .iter() - .filter(|r| r[0].dims == dims && r[0].half == half); - for rows in mine { - let rows: &[Sample] = rows; - let raw = rows[0].raw; - let pf = format(raw).0; - let class = texel_format(pf).0; - let coords: Vec = (0u32..) - .zip(rows) - .flat_map(|(k, s)| { - let u = (512 * k + 128 + s.k[0]) as f32 / (256 * WIDTH) as f32; - let v = (128 + s.k[1]) as f32 / 512.0; - let w = (128 + s.k[2]) as f32 / 512.0; - match dims { - 3 => vec![u, v, w, 0.0], - _ => vec![u, v], - } - }) - .flat_map(f32::to_le_bytes) - .collect(); - let size = if half { 8 } else { 16 }; - let res = resources(&plan, &[coords, vec![0xab; size * ROWS]], class); - let res = with_word(res, &a, runtime.then_some(word)); - for decode in [Decode::Exact, Decode::Reciprocal, Decode::Replicated] { - if format(raw).1.is_none() && decode != Decode::Exact { - continue; - } - let extent = match dims { - 1 => [WIDTH, 1, 1], - 2 => [WIDTH, 2, 1], - _ => [WIDTH, 2, 2], - }; - let mut image = Image::new(combined_slot(&m), extent, 1, 1, 1); - for (k, s) in (0u32..).zip(rows) { - for (at, w) in sites(dims, k).into_iter().zip(&s.words) { - let i = image.index(0, 0, 0, at).expect("texel"); - image.texels[i] = texel(raw, *w, decode); - } - } - let got = run(&m, &res, &image, ROWS as u32, half); - for (s, g) in rows.iter().zip(got) { - assert_eq!( - g, s.out, - "{name} {pf:?} {decode:?} k {:?} words {:x?}: {g:x?}, Metal {:x?}", - s.k, s.words, s.out - ); - } - } - } - } - } - } -} - -/// Metal's 2D samples with one axis's two taps clamped onto one texel: `edge_samples.tsv`, 94 of -/// the linear samples our probes took (an Apple M3 Max on macOS 26.7 and an Apple M4 on macOS -/// 27.0.1, byte-identical; random finite texels of 64 x 64 textures past -/// either edge, clamp to edge, exact 1/256 fractions): per format (`RGBA16Float`, `RGBA32Float`, -/// `RG11B10Float`, `RGB9E5Float`), result, and clamped axis, the rows whose answer the unmerged -/// fractions change, and `RGBA32Float`'s `half` results that are a negative zero. One per line: the -/// raw format (115, 125, 92, 93), the clamped axis (`x` or `y`), the result (`f` `float`, `h` -/// `half`), the fractions `kx` and `ky` in 1/256 steps, the two distinct taps' texel words (hex, -/// the lower one first along the other axis), and the result's lanes as bits (hex). -const EDGES: &str = include_str!("edge_samples.tsv"); - -/// One of Metal's edge samples. -struct Edge { - raw: u32, - x: bool, - half: bool, - k: [u32; 2], - taps: [Vec; 2], - out: [u32; 4], -} - -fn edges() -> Vec { - let hex = |s: &str| -> Vec { - s.split(',') - .map(|x| u32::from_str_radix(x, 16).expect("hex")) - .collect() - }; - EDGES - .lines() - .map(|l| { - let f: Vec<&str> = l.split(' ').collect(); - let num = |i: usize| -> u32 { f[i].parse().expect("number") }; - let out = hex(f[7]); - Edge { - raw: num(0), - x: f[1] == "x", - half: f[2] == "h", - k: [num(3), num(4)], - taps: [hex(f[5]), hex(f[6])], - out: [out[0], out[1], out[2], out[3]], - } - }) - .collect() -} - -/// The device's texel (`f32` bits per channel) of texel words `words` in raw format `raw`: each -/// value exact. -fn edge_texel(raw: u32, words: &[u32]) -> [u32; 4] { - let half = |h: u32| half_value(h as u16).to_bits(); - match (raw, words) { - (115, [a, b]) => [ - half(a & 0xffff), - half(a >> 16), - half(b & 0xffff), - half(b >> 16), - ], - (125, [a, b, c, d]) => [*a, *b, *c, *d], - (92 | 93, [w]) => texel(raw, *w, Decode::Exact), - _ => panic!("raw format {raw}: {words:x?}"), - } -} - -/// Each of Metal's edge samples, through a constexpr linear clamp-to-edge sampler and a runtime -/// sampler of that state, with `float` and `half` results, is Metal's bytes: the emulation's 2D -/// float sum weighs a clamped axis's taps `(256, 0)`. A run of one format, axis, and result reads -/// a texture one texel across its clamped axis, whose two taps clamp onto that texel, and two -/// texels per sample along the other. -#[test] -fn clamped_edges_of_float_formats_are_metals_bytes() { - use crate::metal::texel_format::texel_format as class_of; - let p = lavapipe(); - let all = edges(); - assert_eq!(all.len(), 94); - let word = runtime_word( - SamplerAddressMode::ClampToEdge, - false, - SamplerBorderColor::TransparentBlack, - ); - let mut runs: Vec> = Vec::new(); - for e in &all { - match runs.last_mut() { - Some(r) if (r[0].raw, r[0].x, r[0].half) == (e.raw, e.x, e.half) => r.push(e), - _ => runs.push(vec![e]), - } - } - for half in [false, true] { - for runtime in [false, true] { - let sampler = (!runtime).then(|| linear(1, false, 0)); - let name = format!("edges half={half} runtime={runtime}"); - let form = Form::Plain { offset: (0, 0) }; - let Some(bc) = assemble(&name, &kernel_of(sampler, form, !half)) else { - return; - }; - let a = compile(&bc, "k", &p).unwrap_or_else(|e| panic!("{name}: {e}")); - assert!( - a.strategies.entries.contains_key("sampler.linear.quad"), - "{name}" - ); - let (plan, m) = typed_module(&bc, "k", &p).expect("typed module"); - for rows in runs.iter().filter(|r| r[0].half == half) { - let (raw, x) = (rows[0].raw, rows[0].x); - let pf = match raw { - 115 => PixelFormat::RGBA16Float, - 125 => PixelFormat::RGBA32Float, - _ => format(raw).0, - }; - let n = rows.len() as u32; - // The clamped axis is one texel wide; the other holds two per sample. - let extent = match x { - true => [1, 2 * n, 1], - false => [2 * n, 1, 1], - }; - let coords: Vec = (0u32..) - .zip(rows) - .flat_map(|(r, e)| { - let along = |k: u32| (512 * r + 128 + k) as f32 / (512 * n) as f32; - let across = |k: u32| (128 + k) as f32 / 256.0; - match x { - true => [across(e.k[0]), along(e.k[1])], - false => [along(e.k[0]), across(e.k[1])], - } - }) - .flat_map(f32::to_le_bytes) - .collect(); - let size = if half { 8 } else { 16 }; - let res = resources( - &plan, - &[coords, vec![0xab; size * rows.len()]], - class_of(pf).0, - ); - let res = with_word(res, &a, runtime.then_some(word)); - let mut image = Image::new(combined_slot(&m), extent, 1, 1, 1); - for (r, e) in (0u32..).zip(rows) { - for (t, words) in (0u32..).zip(&e.taps) { - let at = match x { - true => [0, 2 * r + t, 0], - false => [2 * r + t, 0, 0], - }; - let i = image.index(0, 0, 0, at).expect("texel"); - image.texels[i] = edge_texel(raw, words); - } - } - let got = run(&m, &res, &image, n, half); - for (e, g) in rows.iter().zip(got) { - assert_eq!( - g, e.out, - "{name} {pf:?} x={x} k {:?} taps {:x?}: {g:x?}, Metal {:x?}", - e.k, e.taps, e.out - ); - } - } - } - } -} - -/// How a [`swizzle_kernel`] accesses its `texture2d` slot 0. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Access { - /// `t.read(uint2(tid % 16, tid / 16))` of an `access::read` texture. - Read, - /// `t.sample(s, coord[tid])` through a constexpr clamp-to-edge sampler, linear or nearest. - Sample { linear: bool }, - /// `t.gather(s, coord[tid], int2(0), component)` through a constexpr clamp-to-edge sampler. - Gather { component: u32 }, -} - -/// A kernel accessing texture slot 0 as `access` (at `float2` buffer 0's lane `tid` for a -/// sample or gather), storing the `half4` (`float4` unless `half`) to buffer 1. -fn swizzle_kernel(access: Access, half: bool) -> String { - let (texel, vec4, size, suffix) = match half { - true => ("half", "<4 x half>", 8, "v4f16"), - false => ("float", "<4 x float>", 16, "v4f32"), - }; - let state = |words: u64| { - format!( - "@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 {words}, i64 0], align 8\n\n" - ) - }; - let (state, tex_access, call, decl) = match access { - Access::Read => ( - String::new(), - "read", - format!( - "%rs = call ptr addrspace(2) @air.get_read_sampler()\n %r = call {{ {vec4}, i8 }} @air.read_texture_2d.{suffix}(ptr addrspace(1) %t, ptr addrspace(2) %rs, <2 x i32> %gid, <2 x i32> zeroinitializer, i32 0, i32 1)" - ), - format!( - "declare ptr addrspace(2) @air.get_read_sampler()\ndeclare {{ {vec4}, i8 }} @air.read_texture_2d.{suffix}(ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32)" - ), - ), - Access::Sample { linear } => ( - state(sampler_words(u64::from(linear), 0, 1, false, 0)), - "sample", - format!( - "%r = call {{ {vec4}, i8 }} @air.sample_texture_2d.{suffix}(ptr addrspace(1) %t, ptr addrspace(2) @__air_sampler_state, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.0, float 0.0, i32 0)" - ), - format!( - "declare {{ {vec4}, i8 }} @air.sample_texture_2d.{suffix}(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32)" - ), - ), - Access::Gather { component } => ( - state(sampler_words(0, 0, 1, false, 0)), - "sample", - format!( - "%r = call {{ {vec4}, i8 }} @air.gather_texture_2d.{suffix}(ptr addrspace(1) %t, ptr addrspace(2) @__air_sampler_state, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i32 {component}, i32 0)" - ), - format!( - "declare {{ {vec4}, i8 }} @air.gather_texture_2d.{suffix}(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i32, i32)" - ), - ), - }; - let (states, state_md) = match access { - Access::Read => ("", ""), - _ => ( - "!air.sampler_states = !{!7}\n", - "!7 = !{!\"air.sampler_state\", ptr addrspace(2) @__air_sampler_state}\n", - ), - }; - let out_ty = format!("{texel}4"); - format!( - r#"{state}define void @k(ptr addrspace(1) %t, ptr addrspace(1) %c, ptr addrspace(1) %out, i32 %tid) {{ - %i = zext i32 %tid to i64 - %p = getelementptr inbounds <2 x float>, ptr addrspace(1) %c, i64 %i - %uv = load <2 x float>, ptr addrspace(1) %p, align 8 - %x = and i32 %tid, 15 - %y = lshr i32 %tid, 4 - %g0 = insertelement <2 x i32> zeroinitializer, i32 %x, i64 0 - %gid = insertelement <2 x i32> %g0, i32 %y, i64 1 - {call} - %v = extractvalue {{ {vec4}, i8 }} %r, 0 - %q = getelementptr inbounds {vec4}, ptr addrspace(1) %out, i64 %i - store {vec4} %v, ptr addrspace(1) %q, align {size} - ret void -}} - -{decl} - -!air.kernel = !{{!0}} -{states}!0 = !{{ptr @k, !1, !2}} -!1 = !{{}} -!2 = !{{!3, !4, !5, !6}} -!3 = !{{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.{tex_access}", !"air.arg_type_name", !"texture2d<{texel}, {tex_access}>", !"air.arg_name", !"t"}} -!4 = !{{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"float2", !"air.arg_name", !"c"}} -!5 = !{{i32 2, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 {size}, !"air.arg_type_align_size", i32 {size}, !"air.arg_type_name", !"{out_ty}", !"air.arg_name", !"out"}} -!6 = !{{i32 3, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"tid"}} -{state_md}"# - ) -} - -/// The images of texture slot 0 module `m` binds (its sampled image, or a combined image -/// sampler), each `extent` texels holding `texels`. -fn slot_images(m: &TypedModule, extent: [u32; 3], texels: &[[u32; 4]]) -> Vec { - let images: Vec = m - .globals() - .iter() - .filter_map(|g| match g.kind { - GlobalKind::Resource( - s @ ResourceSlot { - kind: ResourceKind::Texture | ResourceKind::CombinedTextureSampler(_), - index: 0, - .. - }, - ) => { - let mut image = Image::new(s, extent, 1, 1, 1); - image.texels = texels.to_vec(); - Some(image) - } - _ => None, - }) - .collect(); - assert!(!images.is_empty(), "no image of texture slot 0"); - images -} - -/// A swizzled packed normalized texture's reads and linear samples, with `float` and `half` -/// results, are the unswizzled texture's, swizzled, on a device that does not sample through -/// Metal's own sampler, whatever it reads a packed code as (exact, lavapipe's product by the -/// reciprocal, ANV's and NVIDIA's replicated bits): under the slot's `swizzled_storage` variant -/// the function converts the unswizzled texel by the format's whole class and swizzles it -/// (`Zero` 0, `One` 1). The reference is the unswizzled module's answer for exact codes, which is -/// Metal's (`packed_linear_samples_are_metals_bytes` and the device lanes). Previously a swizzled -/// view's class dropped the packed field, and the device's replicated codes showed. A nearest -/// sample's and a gather's modules (four gathers, the one the swizzle names taken) validate, and -/// every module's words stay within the selection's estimate; the interpreter models no device -/// sample or gather, so their answers are the device lane's (`runtime_lane::extended_swizzles`). -#[test] -fn swizzled_packed_texels_are_the_unswizzled_swizzled() { - use crate::lower::select::LowerInputs; - use crate::metal::{TextureSwizzle as S, TextureSwizzleChannels as C}; - use crate::pipeline::testing::{compile_with, typed_module_with}; - const THREADS: u32 = 2 * WIDTH; - let p = lavapipe(); - let swizzles = [ - C::new(S::Green, S::Blue, S::Alpha, S::Red), - C::new(S::Blue, S::Green, S::Red, S::Alpha), - C::new(S::Alpha, S::Red, S::One, S::Zero), - C::new(S::Zero, S::Alpha, S::Green, S::One), - C::new(S::Green, S::Green, S::Green, S::Green), - ]; - let mut rng = Lcg(0xd793); - // Positions inside the texture and past its edges (clamped), at 1/256 steps. - let coords: Vec = (0..THREADS) - .flat_map(|_| { - let u = (rng.next() % (256 * u64::from(WIDTH) + 256)) as f32 - 128.0; - let v = (rng.next() % (256 * 2 + 256)) as f32 - 128.0; - [u / (256 * WIDTH) as f32, v / 512.0] - }) - .flat_map(f32::to_le_bytes) - .collect(); - let mut accesses = vec![ - Access::Read, - Access::Sample { linear: false }, - Access::Sample { linear: true }, - ]; - accesses.extend((0..4).map(|component| Access::Gather { component })); - // The accesses the interpreter runs: a read, and a linear sample, which fetches its taps. - let runs = |access: &Access| matches!(access, Access::Read | Access::Sample { linear: true }); - let mut swizzled_inputs = LowerInputs::new(); - swizzled_inputs.swizzled_storage.insert(TEXTURE); - for half in [false, true] { - let one = if half { 0x3c00 } else { 1.0f32.to_bits() }; - // Each access's module, unswizzled and swizzled. - let mut modules = Vec::new(); - for access in &accesses { - let name = format!("{access:?} half={half}"); - let Some(bc) = assemble(&name, &swizzle_kernel(*access, half)) else { - return; - }; - let (plain, m) = typed_module(&bc, "k", &p).unwrap_or_else(|e| panic!("{name}: {e}")); - let (plan, s) = typed_module_with(&bc, "k", &p, &swizzled_inputs) - .unwrap_or_else(|e| panic!("{name} swizzled: {e}")); - let a = compile_with(&bc, "k", &p, &swizzled_inputs) - .unwrap_or_else(|e| panic!("{name} swizzled: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name} swizzled: {e}")); - let words = a.module.words.len() as u64; - assert!( - plan.estimate.words >= words, - "{name}: estimate {} < emitted {words}", - plan.estimate.words - ); - modules.push((name, (plain, m), (plan, s))); - } - for raw in [40, 41, 42, 43] { - let (pf, _) = format(raw); - let class = texel_format(pf).0; - let words: Vec = (0..THREADS).map(|_| rng.next() as u32 & 0xffff).collect(); - let texels = |decode: Decode| -> Vec<[u32; 4]> { - words.iter().map(|w| texel(raw, *w, decode)).collect() - }; - let extent = [WIDTH, 2, 1]; - let size = if half { 8 } else { 16 }; - let init = [coords.clone(), vec![0xab; size * THREADS as usize]]; - // The unswizzled answers of exact codes: each access's the interpreter runs. - let reference: Vec> = accesses - .iter() - .zip(&modules) - .map(|(access, (_, (plan, m), _))| { - if !runs(access) { - return Vec::new(); - } - let res = resources(plan, &init, class); - let images = slot_images(m, extent, &texels(Decode::Exact)); - run_images(m, &res, &images, THREADS, half) - }) - .collect(); - for swizzle in swizzles { - let sources = [swizzle.red, swizzle.green, swizzle.blue, swizzle.alpha]; - // A lane's source: 0, 1, or channel `c` of the unswizzled texel. - let pick = |source: S, x: [u32; 4]| match source { - S::Zero => 0, - S::One => one, - S::Red => x[0], - S::Green => x[1], - S::Blue => x[2], - _ => x[3], - }; - for (k, (access, (name, _, (plan, m)))) in accesses.iter().zip(&modules).enumerate() - { - if !runs(access) { - continue; - } - let mut res = resources(plan, &init, class); - res.spec - .insert(SpecKey::TextureSwizzle(TEXTURE), u64::from(swizzle.word())); - let expected: Vec<[u32; 4]> = reference[k] - .iter() - .map(|x| sources.map(|s| pick(s, *x))) - .collect(); - for decode in [Decode::Exact, Decode::Reciprocal, Decode::Replicated] { - let images = slot_images(m, extent, &texels(decode)); - let got = run_images(m, &res, &images, THREADS, half); - for (t, (g, e)) in got.iter().zip(&expected).enumerate() { - assert_eq!( - g, e, - "{name} {pf:?} {swizzle:?} {decode:?} thread {t} word {:#06x}: \ - {g:x?}, expected {e:x?}", - words[t] - ); - } - } - } - } - } - } -} diff --git a/crates/metal2vulkan/src/tests/engine_linear_half/packed_samples.tsv b/crates/metal2vulkan/src/tests/engine_linear_half/packed_samples.tsv deleted file mode 100644 index 615c92808..000000000 --- a/crates/metal2vulkan/src/tests/engine_linear_half/packed_samples.tsv +++ /dev/null @@ -1,432 +0,0 @@ -40 1 h 201 0 0 4f8a,4b88 34a5,386e,345a,3c00 -40 1 h 87 0 0 4b88,5603 34d2,386b,3282,3c00 -40 1 h 135 0 0 842b,eb5e 39e6,3771,396d,3c00 -40 1 h 249 0 0 8d8,cd9c 3a48,3974,3b33,3c00 -40 1 h 231 0 0 95d2,9559 38a5,3962,3a47,3c00 -40 1 h 133 0 0 575d,895e 370a,3833,3b9e,3c00 -40 1 h 10 0 0 3e8e,60a2 336e,3a5f,36fc,3c00 -40 1 h 9 0 0 f8ae,a66b 3be6,2eb8,372c,3c00 -40 1 f 201 0 0 4f8a,4b88 3e94a529,3f0db8dc,3e8b42d1,3f800000 -40 1 f 87 0 0 4b88,5603 3e9a4692,3f0d68d7,3e50340d,3f800000 -40 1 f 135 0 0 842b,eb5e 3f3cbf30,3eee2ee3,3f2d9b67,3f800000 -40 1 f 249 0 0 8d8,cd9c 3f490241,3f2e8ae9,3f665996,3f800000 -40 1 f 78 0 0 b4db,9265 3f2b9ae7,3f02e82f,3f2799e6,3f800000 -40 1 f 251 0 0 fd31,ea1e 3f6fcbf3,3e860861,3f759d67,3f800000 -40 1 f 231 0 0 95d2,9559 3f14a529,3f2c3ac4,3f48d235,3f800000 -40 1 f 133 0 0 575d,895e 3ee1384e,3f065866,3f73ccf3,3f800000 -40 2 h 73 31 0 c9c7,6b0e,bac0,beae 399d,34b5,3454,3c00 -40 2 h 151 125 0 900a,e61f,a6df,f552 3a6b,38c0,39e5,3c00 -40 2 h 63 247 0 bde2,f501,6793,fcbf 3861,3adc,397b,3c00 -40 2 h 190 100 0 41c4,cdf4,2a2f,723e 386c,37a4,3921,3c00 -40 2 h 121 77 0 b6d,998e,958f,7082 35ee,3574,363d,3c00 -40 2 h 153 144 0 638e,ddfa,75fa,d6e3 3971,39e2,382c,3c00 -40 2 h 121 191 0 91fc,faa8,f66,97db 36a5,3a4c,3848,3c00 -40 2 h 68 58 0 be00,6f46,2b9e,fe74 38c2,39f5,33aa,3c00 -40 2 f 73 31 0 c9c7,6b0e,bac0,beae 3f339ce7,3e96a96b,3e8a82a1,3f800000 -40 2 f 151 125 0 900a,e61f,a6df,f552 3f4d6359,3f17f980,3f3caf2c,3f800000 -40 2 f 93 151 0 449d,8fe0,fc1,d4ef 3eae8ba3,3f4ceccf,3eb86e1c,3f800000 -40 2 f 63 247 0 bde2,f501,6793,fcbf 3f0c1305,3f5b7db8,3f2f6bdb,3f800000 -40 2 f 39 73 0 8cbc,6c9d,4f3a,d28d 3ef81e08,3f268a69,3f5ec7b2,3f800000 -40 2 f 58 133 0 d76d,6fe0,24ed,924c 3ef47d1f,3f3d3bd4,3ebd6f5c,3f800000 -40 2 f 121 191 0 91fc,faa8,f66,97db 3ed49525,3f498c99,3f090241,3f800000 -40 2 f 190 100 0 41c4,cdf4,2a2f,723e 3f0d735d,3ef48f49,3f24290a,3f800000 -40 3 h 254 184 62 7fc7,8275,79e3,4265,9a7e,1549,51e9,ae88 35fa,36ae,34bd,3c00 -40 3 h 207 32 180 fbb,3867,9db9,3c3,1ab2,10e7,f746,5cf0 306d,3368,351e,3c00 -40 3 h 42 202 75 f00b,3f71,8bb5,6925,25ad,c1af,fd2f,50b9 391f,36b1,3850,3c00 -40 3 h 214 86 117 6d52,ebdb,228e,d3cc,fc6f,e072,21bf,76ce 3a3b,36b8,38fe,3c00 -40 3 h 43 54 99 22a8,b46d,8087,eed0,dcd3,4cab,e10e,8bac 37d8,3672,3622,3c00 -40 3 h 32 163 206 a5a6,6c36,b41e,2808,f962,b2fb,ad43,5e2f 39da,3816,3401,3c00 -40 3 h 223 69 214 1e2a,9062,5c9f,35de,34b1,d740,8d01,a380 3967,3985,2e52,3c00 -40 3 h 49 67 230 bd1c,4856,9646,27dd,ffa7,e011,aee4,a80b 3afb,39f8,34e1,3c00 -40 3 f 254 184 62 7fc7,8275,79e3,4265,9a7e,1549,51e9,ae88 3ebf4fd4,3ed5cd5d,3e97a5e9,3f800000 -40 3 f 207 32 180 fbb,3867,9db9,3c3,1ab2,10e7,f746,5cf0 3e0da369,3e6d0ed1,3ea3c8f2,3f800000 -40 3 f 236 163 2 f668,8759,10e6,8d74,fcad,aa66,b86c,4254 3f065194,3f3bdbbe,3f2a0a83,3f800000 -40 3 f 97 43 84 529,ed31,a55a,a55d,e47d,5720,fb10,e9de 3f02e0b8,3f24fa50,3f0320c8,3f800000 -40 3 f 214 86 117 6d52,ebdb,228e,d3cc,fc6f,e072,21bf,76ce 3f4751d4,3ed70d71,3f1fb7ee,3f800000 -40 3 f 43 54 99 22a8,b46d,8087,eed0,dcd3,4cab,e10e,8bac 3efafec0,3ece4ce5,3ec4310c,3f800000 -40 3 f 223 69 214 1e2a,9062,5c9f,35de,34b1,d740,8d01,a380 3f2ceb3b,3f309b0a,3dca328d,3f800000 -40 3 f 32 163 206 a5a6,6c36,b41e,2808,f962,b2fb,ad43,5e2f 3f3b4ed4,3f02c82d,3e802008,3f800000 -41 1 h 121 0 0 28a4,46ff 32a0,3722,3a3b,3790 -41 1 h 29 0 0 fe86,e183 3be9,3a20,2db9,2f3f -41 1 h 75 0 0 7fee,9a0c 382d,3a43,38a7,0 -41 1 h 254 0 0 ea23,dec1 3af9,3aee,1c81,3c00 -41 1 h 42 0 0 d1af,1fcb 39bc,3536,392c,3c00 -41 1 h 85 0 0 7fee,9a0c 3837,3a08,387b,0 -41 1 h 151 0 0 6802,84b1 37a0,357a,3785,38b8 -41 1 h 202 0 0 cc6f,fbe4 3bac,37f6,38eb,32c1 -41 1 f 121 0 0 28a4,46ff 3e53f4fd,3ee4390e,3f4761d8,3ef1f1f2 -41 1 f 29 0 0 fe86,e183 3f7d2f4c,3f440100,3db72dcb,3de7e7e8 -41 1 f 75 0 0 7fee,9a0c 3f059164,3f486219,3f14d535,0 -41 1 f 104 0 0 d915,cc6f 3f584612,3e994652,3efc5f18,3f800000 -41 1 f 46 0 0 9ce7,6802 3f140501,3f00b02c,3f02308c,3f520202 -41 1 f 254 0 0 ea23,dec1 3f5f17c6,3f5db76e,3b902409,3f800000 -41 1 f 42 0 0 d1af,1fcb 3f378de3,3ea6c9b2,3f258962,3f800000 -41 1 f 85 0 0 7fee,9a0c 3f06d1b4,3f40f03c,3f0f53d5,0 -41 2 h 99 10 0 9042,ad74,3ae9,f7de 38e9,34b5,35a7,2626 -41 2 h 40 67 0 a189,3224,df59,8638 391a,3638,3451,3ac0 -41 2 h 109 134 0 6c22,a1aa,526f,ffb4 3886,37bc,3994,34cf -41 2 h 92 98 0 910d,631e,b915,91bc 389e,3240,3657,3920 -41 2 h 179 16 0 39ea,33e1,a852,d40f 33ae,3677,385c,3998 -41 2 h 194 243 0 3038,566c,ee46,1067 346b,33ac,3803,39c1 -41 2 h 249 58 0 5a3c,5a68,21fb,e295 3797,34be,38a9,333f -41 2 h 146 81 0 8197,60bb,9ec,a9f9 36de,30e9,39d4,3ae9 -41 2 f 99 10 0 9042,ad74,3ae9,f7de 3f1d274a,3e96a5a9,3eb4ed3b,3cc4c4c5 -41 2 f 165 103 0 ef02,443d,cea8,37b9 3eed5b57,3f4300c0,3f34bd2f,3f250505 -41 2 f 40 67 0 a189,3224,df59,8638 3f2338ce,3ec6f1bc,3e8a2289,3f580808 -41 2 f 109 134 0 6c22,a1aa,526f,ffb4 3f10c431,3ef77ddf,3f328ca3,3e99d9da -41 2 f 92 98 0 910d,631e,b915,91bc 3f13c4f1,3e47f1fc,3ecad2b5,3f240404 -41 2 f 249 58 0 5a3c,5a68,21fb,e295 3ef2dcb7,3e97c5f1,3f152549,3e67e7e8 -41 2 f 179 16 0 39ea,33e1,a852,d40f 3e75bd6f,3eced3b5,3f0b72dd,3f330303 -41 2 f 227 167 0 5242,3f95,23ca,5cb6 3e98260a,3f2e6b9b,3f1dc772,3e9dddde -41 3 h 241 206 8 9148,3c69,dc46,fe02,f0f,6236,f129,ec 3a98,3993,3159,31c2 -41 3 h 242 175 240 1a1d,6141,1aab,faa,a310,3b53,4d93,9d71 376d,38d1,38c1,3b8c -41 3 h 67 232 10 f388,301b,66c1,be54,2e23,53ff,a0ff,48ef 380f,3a3d,3013,39a5 -41 3 h 217 171 172 f07a,76d4,5eb8,53c2,79d8,273,dd0c,c851 3819,3516,35bc,388f -41 3 h 114 236 43 88e1,d715,e9fa,395,2184,dd91,1cc4,9b6d 37fb,35df,38be,37b4 -41 3 h 148 25 131 15dd,bcdd,621b,351d,b953,591d,467b,16aa 375f,36c9,36fb,3bc5 -41 3 h 208 15 137 3618,93f2,5c40,18e5,ef6e,8b38,bf88,db39 3887,3806,3a5c,2a16 -41 3 h 221 231 204 bf88,db39,a6ef,ee44,9715,88e6,841a,3446 3652,3887,321a,2abf -41 3 f 241 206 8 9148,3c69,dc46,fe02,f0f,6236,f129,ec 3f52f4bd,3f326c9b,3e2b2acb,3e383838 -41 3 f 242 175 240 1a1d,6141,1aab,faa,a310,3b53,4d93,9d71 3eed9b67,3f1a268a,3f18260a,3f718182 -41 3 f 67 232 10 f388,301b,66c1,be54,2e23,53ff,a0ff,48ef 3f01d074,3f47a1e8,3e026098,3f34a4a5 -41 3 f 217 171 172 f07a,76d4,5eb8,53c2,79d8,273,dd0c,c851 3f0320c8,3ea2c8b2,3eb78de3,3f11d1d2 -41 3 f 208 15 137 3618,93f2,5c40,18e5,ef6e,8b38,bf88,db39 3f10d435,3f00c030,3f4b82e1,3d42c2c3 -41 3 f 114 236 43 88e1,d715,e9fa,395,2184,dd91,1cc4,9b6d 3eff5fd8,3ebbeefc,3f17b5ed,3ef67676 -41 3 f 148 25 131 15dd,bcdd,621b,351d,b953,591d,467b,16aa 3eebdaf7,3ed91646,3edf57d6,3f789899 -41 3 f 221 231 204 bf88,db39,a6ef,ee44,9715,88e6,841a,3446 3eca328d,3f10e439,3e4330cc,3d57d7d8 -42 1 h 249 0 0 cc4c,7bfb 379d,39e1,3bd7,39e1 -42 1 h 1 0 0 884b,21be 3841,3841,344b,39df -42 1 h 138 0 0 100f,5bc7 32bd,3653,36e7,39b3 -42 1 h 125 0 0 884b,21be 3568,34e3,37ea,3aa6 -42 1 h 83 0 0 1d36,46f9 3036,39b9,3759,3770 -42 1 h 33 0 0 2833,eec2 3392,38ae,3470,3220 -42 1 h 216 0 0 7ab9,f130 3b55,3123,3489,2e02 -42 1 h 250 0 0 ef0a,5754 358f,37ab,3535,346a -42 1 f 249 0 0 cc4c,7bfb 3ef39394,3f3c2c2c,3f7adadb,3f3c2c2c -42 1 f 1 0 0 884b,21be 3f082828,3f081818,3e896969,3f3bebec -42 1 f 10 0 0 8cf5,ce6f 3f0b3b3b,3f4e1e1e,3f79f9fa,3eb7f7f8 -42 1 f 138 0 0 100f,5bc7 3e579798,3eca6a6a,3edcdcdd,3f366666 -42 1 f 125 0 0 884b,21be 3ead0d0d,3e9c5c5c,3efd3d3d,3f54b4b5 -42 1 f 83 0 0 1d36,46f9 3e06c6c7,3f372727,3eeb2b2b,3eee0e0e -42 1 f 33 0 0 2833,eec2 3e723232,3f15b5b6,3e8e0e0e,3e440404 -42 1 f 42 0 0 d52c,405c 3f44a4a5,3e8eaeaf,3e2a2a2a,3f4ccccd -42 2 h 182 172 0 6e1f,e474,dd06,9edc 39af,3a1f,383c,38ef -42 2 h 48 5 0 c390,4185,df37,6ae3 399d,3214,38a9,2c70 -42 2 h 172 243 0 a9b5,77b2,37ab,fafe 39d1,38c5,3b10,3aac -42 2 h 205 246 0 a658,f78f,6ce5,79aa 378e,3910,39b0,38e6 -42 2 h 203 21 0 a03a,2e14,e864,fd7d 34e0,39f5,2fec,361b -42 2 h 187 46 0 3aa5,ead4,8667,80f8 3998,3888,3a8a,3537 -42 2 h 80 235 0 6463,8773,b87c,d885 39fb,3822,37b7,38ef -42 2 h 192 224 0 11f4,93d6,5e26,64a5 364d,3666,38a2,35a3 -42 2 f 52 129 0 deac,aec2,1ad9,e1f 3edf7f7f,3f538384,3f32f2f3,3f2c4c4c -42 2 f 182 172 0 6e1f,e474,dd06,9edc 3f35e5e6,3f43d3d4,3f077777,3f1dedee -42 2 f 48 5 0 c390,4185,df37,6ae3 3f339394,3e428283,3f152525,3d8e0e0e -42 2 f 239 111 0 4011,42f9,b47c,ca15 3efdfdfe,3eb23232,3f126262,3ef49495 -42 2 f 117 93 0 511e,7dfd,575d,94a2 3ed53535,3ed2b2b3,3efb1b1b,3f449495 -42 2 f 113 143 0 c34c,a872,19d9,1bb5 3eba9a9b,3f057575,3f1b9b9c,3efc3c3c -42 2 f 172 243 0 a9b5,77b2,37ab,fafe 3f3a1a1a,3f18a8a9,3f61f1f2,3f557575 -42 2 f 205 246 0 a658,f78f,6ce5,79aa 3ef1b1b2,3f21f1f2,3f360606,3f1cbcbd -42 3 h 72 36 191 766f,513c,e37e,357e,64fd,2172,6889,8f18 35fb,347a,396e,39ca -42 3 h 207 95 207 9b65,35d9,c3ef,118a,8b42,d902,42b1,df5a 3974,38fe,3493,35a0 -42 3 h 39 227 72 72d7,d118,3017,c2f5,c0cc,a44e,625a,37f0 3588,2c7c,3533,37d9 -42 3 h 249 89 39 3d59,b2c5,3ac9,bf0e,8f89,95ec,89ee,a36a 39a2,36c5,3871,389b -42 3 h 231 61 166 f32d,1df6,625,a6c9,3aee,fa5a,c4ba,5a9 387b,3906,38d5,38d3 -42 3 h 202 34 231 ab22,606a,3c19,52ef,152,60d8,cccb,7343 35aa,2c48,3965,3729 -42 3 h 84 206 232 f688,f06d,c5c5,12d,dbd3,45,1756,1a95 32bd,37fb,37a7,35e8 -42 3 h 18 244 169 ffb0,a7a4,6c5a,7dcd,8e68,9248,9760,e0dc 3872,389c,36a3,345d -42 3 f 72 36 191 766f,513c,e37e,357e,64fd,2172,6889,8f18 3ebf5f5f,3e8f4f4f,3f2dcdce,3f394949 -42 3 f 248 221 119 d6d8,5078,545e,b73e,802d,cd75,ad6b,71d7 3f194949,3e9b7b7b,3f001010,3f2ededf -42 3 f 207 95 207 9b65,35d9,c3ef,118a,8b42,d902,42b1,df5a 3f2e8e8f,3f1fcfd0,3e925252,3eb3f3f4 -42 3 f 39 227 72 72d7,d118,3017,c2f5,c0cc,a44e,625a,37f0 3eb0f0f1,3d8f8f90,3ea66666,3efb1b1b -42 3 f 249 89 39 3d59,b2c5,3ac9,bf0e,8f89,95ec,89ee,a36a 3f343434,3ed89899,3f0e2e2e,3f135353 -42 3 f 231 61 166 f32d,1df6,625,a6c9,3aee,fa5a,c4ba,5a9 3f0f5f5f,3f20c0c1,3f1aaaab,3f1a6a6a -42 3 f 202 34 231 ab22,606a,3c19,52ef,152,60d8,cccb,7343 3eb53535,3d890909,3f2cacad,3ee52525 -42 3 f 84 206 232 f688,f06d,c5c5,12d,dbd3,45,1756,1a95 3e579798,3eff5f5f,3ef4d4d5,3ebcfcfd -43 1 h 73 0 0 8452,e33f 33ce,346b,399a,3c00 -43 1 h 75 0 0 2d01,414a 366f,346e,2f82,0 -43 1 h 198 0 0 547a,f3a6 3ad1,39f6,356f,3a30 -43 1 h 176 0 0 9cc7,1a29 3284,3700,3453,3500 -43 1 h 131 0 0 d7d2,ce22 3928,3a07,3510,3c00 -43 1 h 96 0 0 cc9f,891d 3685,31ad,3bce,3c00 -43 1 h 102 0 0 845f,5d62 350a,31c3,3905,38d0 -43 1 h 151 0 0 b485,2bf1 35cb,3924,363c,3690 -43 1 f 73 0 0 8452,e33f 3e79be70,3e8d6359,3f333ccf,3f800000 -43 1 f 75 0 0 2d01,414a 3ecdd375,3e8dc371,3df03c0f,0 -43 1 f 198 0 0 547a,f3a6 3f5a268a,3f3ecfb4,3eadeb7b,3f460606 -43 1 f 27 0 0 f631,e842 3f6cdb37,3efe9fa8,3efe9fa8,3f800000 -43 1 f 176 0 0 202b,7ddf 3f44a128,3ea4290a,3f4c6319,0 -43 1 f 197 0 0 3dfb,5ba3 3f285a17,3f54d535,3e8ce339,0 -43 1 f 176 0 0 9cc7,1a29 3e50741d,3edff7fe,3e8a6299,3ea00000 -43 1 f 131 0 0 d7d2,ce22 3f24f93e,3f40d034,3ea20882,3f800000 -43 2 h 133 83 0 b1a4,2e93,494d,ba90 36ab,382c,368d,37e4 -43 2 h 65 85 0 2ae9,1a0a,89f1,a335 3368,3929,3648,3550 -43 2 h 228 221 0 87b5,fa91,63ce,c21a 38b5,38a5,3a1e,3b3f -43 2 h 75 46 0 dfe,632c,34f9,45b4 3530,3834,3a54,0 -43 2 h 44 76 0 f9f,e244,21d8,a8b6 335a,39b9,3a99,317f -43 2 h 71 239 0 73f0,944c,f891,bd83 3a99,3392,36d5,3b9e -43 2 h 191 242 0 8058,6949,4f07,a68d 362e,393d,35f6,39c1 -43 2 h 96 73 0 d389,f491,e000,f9e9 3a3f,37d7,34ec,3c00 -43 2 f 133 83 0 b1a4,2e93,494d,ba90 3ed55555,3f058160,3ed19465,3efc7c7c -43 2 f 65 85 0 2ae9,1a0a,89f1,a335 3e6cfb3f,3f25294a,3ec8f23d,3eaa0a0a -43 2 f 228 221 0 87b5,fa91,63ce,c21a 3f1695a5,3f14a529,3f43b0ec,3f67d7d8 -43 2 f 75 46 0 dfe,632c,34f9,45b4 3ea60982,3f06719c,3f4a729d,0 -43 2 f 44 208 0 7189,4e76,e948,7406 3f5ae6ba,3e980602,3e898261,3f2c3c3c -43 2 f 191 242 0 8058,6949,4f07,a68d 3ec5b16c,3f27a9ea,3ebecfb4,3f381818 -43 2 f 44 76 0 f9f,e244,21d8,a8b6 3e6b3acf,3f371dc7,3f5314c5,3e2feff0 -43 2 f 71 239 0 73f0,944c,f891,bd83 3f5314c5,3e723c8f,3eda96a6,3f73b3b4 -43 3 h 218 249 199 9dcb,2a0d,86d7,2090,6c0c,8865,a8a0,ad26 351b,341a,3401,3a75 -43 3 h 207 85 165 1eb2,393d,60a3,5ba1,6fd5,147f,adb1,1d00 35d1,35ac,391a,293d -43 3 h 114 192 243 9e82,ce6c,9f80,b647,cbf6,560f,8203,5c04 3667,36d5,335e,389e -43 3 h 240 164 71 f9b4,e6b3,1b33,bb3,a4f3,f22b,90af,d383 370e,3a73,3804,384c -43 3 h 254 132 139 a97e,81ac,fede,6df0,a999,cf95,fe4c,5040 3863,3768,3637,37d1 -43 3 h 150 133 135 e4a0,79a8,f46e,ca74,5f58,b9a2,e080,931e 3918,3755,36b6,3a19 -43 3 h 108 191 29 8b3a,13ae,12a7,3d8e,72ec,e42c,6e77,6e23 34db,38fc,36a5,308f -43 3 h 192 125 56 7156,ee6e,a1cb,28df,8b3d,843f,b39,8da5 37b8,3652,395e,38b3 -43 3 f 21 121 238 6c22,71c4,2b40,d746,fd08,2dfd,3570,66a8 3f34dd37,3eaacab3,3ebfafec,3ee7c7c8 -43 3 f 218 249 199 9dcb,2a0d,86d7,2090,6c0c,8865,a8a0,ad26 3ea368da,3e8340d0,3e802008,3f4eaeaf -43 3 f 244 255 91 c42c,2b58,6cf6,575c,7e26,5bee,ee7e,771b 3f45d174,3f4b72dd,3f62f8be,3c888889 -43 3 f 240 164 71 f9b4,e6b3,1b33,bb3,a4f3,f22b,90af,d383 3ee1b86e,3f4e5395,3f008020,3f097979 -43 3 f 254 132 139 a97e,81ac,fede,6df0,a999,cf95,fe4c,5040 3f0c5315,3eecfb3f,3ec6d1b4,3efa1a1a -43 3 f 150 133 135 e4a0,79a8,f46e,ca74,5f58,b9a2,e080,931e 3f22f8be,3eea9aa7,3ed6b5ad,3f431313 -43 3 f 108 191 29 8b3a,13ae,12a7,3d8e,72ec,e42c,6e77,6e23 3e9b66da,3f1f87e2,3ed49525,3e11d1d2 -43 3 f 4 29 37 a7cc,82df,95bb,8c62,6df0,69d0,ee80,2535 3eb74dd3,3f57f5fd,3ee699a6,3f5f1f1f -90 1 h 0 0 0 c426c245,91a3e232 388b,36c2,2c21,3c00 -90 1 h 121 0 0 1711f73d,173e3b06 3a48,37c2,35c9,0 -90 1 h 27 0 0 86fb111a,7fdc4db6 34ab,399a,327a,390e -90 1 h 46 0 0 1711f73d,173e3b06 3a68,3429,35c6,0 -90 1 h 122 0 0 73834bc7,458f71fa 39d8,388b,3767,3555 -90 1 h 251 0 0 12cf9dd4,cfd8c0ae 319f,3872,33f2,3bd8 -90 1 h 244 0 0 ddbce062,77a097fa 3ba0,2ca1,3acf,35d6 -90 1 h 36 0 0 a02504c3,1711f73d 3472,3497,37b8,3896 -90 1 f 0 0 0 c426c245,91a3e232 3f116459,3ed8360e,3d842108,3f800000 -90 1 f 244 0 0 ddbce062,77a097fa 3f73fcff,3d942509,3f59d676,3ebababb -90 1 f 170 0 0 64230bb5,afe08aff 3f4f43d1,3dafabeb,3f2fdbf7,3f0dfdfe -90 1 f 121 0 0 1711f73d,173e3b06 3f48f23d,3ef83e10,3eb92e4c,0 -90 1 f 27 0 0 86fb111a,7fdc4db6 3e956559,3f333ccf,3e4f33cd,3f21b1b2 -90 1 f 46 0 0 1711f73d,173e3b06 3f4cf33d,3e852148,3eb8ce34,0 -90 1 f 122 0 0 73834bc7,458f71fa 3f3afec0,3f115455,3eecdb37,3eaaaaab -90 1 f 251 0 0 12cf9dd4,cfd8c0ae 3e33ecfb,3f0e4391,3e7e3f90,3f7afafb -90 2 h 17 2 0 a7cbf8f9,c24226f3,64dfa5b6,9d4c9dc2 3470,39ae,38a9,397d -90 2 h 242 251 0 ca4e1325,d7c5130,c3dde07a,85816df3 3770,309d,2d91,3961 -90 2 h 93 164 0 9d911366,404c1f98,86131ca5,557e02a6 3842,365c,3324,385d -90 2 h 232 30 0 d4915970,85bf34f,2ed86178,7c197063 39a7,3962,33a2,2f90 -90 2 h 101 65 0 3cfeb4a3,a73e9356,b529225e,bd37f70f 37c4,3a92,3aad,35d9 -90 2 h 31 53 0 c10a61b8,2a99c3e6,cde35583,4d3fa36a 37bd,3896,2fa6,3b19 -90 2 h 32 177 0 5da0ef0d,486c8a8d,eab78078,4da929a4 3565,3612,386c,39e5 -90 2 h 134 226 0 d5623ff6,c10a61b8,d9908df4,cde35583 3765,310f,349c,3c00 -90 2 f 191 245 0 c34c051a,3e03f94d,471f26c6,db315385 3f4f93e5,3e9c270a,3eb96e5c,3f4e4e4e -90 2 f 17 2 0 a7cbf8f9,c24226f3,64dfa5b6,9d4c9dc2 3e8e0381,3f35bd6f,3f152549,3f2fafb0 -90 2 f 242 251 0 ca4e1325,d7c5130,c3dde07a,85816df3 3eedfb7f,3e13a4e9,3db22c8b,3f2c2c2c -90 2 f 93 164 0 9d911366,404c1f98,86131ca5,557e02a6 3f08320d,3ecb72dd,3e64791e,3f0babac -90 2 f 109 209 0 ac01a736,840243e5,9efae8b0,be7da186 3ebf8fe4,3f2358d6,3f24c932,3f2aaaab -90 2 f 232 30 0 d4915970,85bf34f,2ed86178,7c197063 3f34dd37,3f2c4b13,3e743d0f,3df1f1f2 -90 2 f 101 65 0 3cfeb4a3,a73e9356,b529225e,bd37f70f 3ef87e20,3f524491,3f55a569,3ebb1b1b -90 2 f 31 53 0 c10a61b8,2a99c3e6,cde35583,4d3fa36a 3ef79de7,3f12c4b1,3df4bd2f,3f632323 -90 3 h 71 98 51 cba4dc16,54e0b4a5,59ea9822,573577f5,a81c3b0e,c0c07ab0,c1ef7064,d39f1535 332a,36ec,34b5,3966 -90 3 h 104 186 120 70059b97,ad945fac,b215827c,491a6971,dc2ff5bf,71989a93,fa63fc09,39b141f8 377b,3648,3989,388d -90 3 h 211 75 6 26d4b2b2,a0d7f493,f678aa7b,85c0c7e0,fba6eeb5,e87bec2d,b5e1b7dd,e0509c50 36d8,35e7,371f,38e1 -90 3 h 232 241 223 75b2c2b8,915f5d0a,40574789,bc60489a,231a1106,4666d2fb,e7523261,82d61f2e 399d,354c,3232,395b -90 3 h 8 243 86 7d345b43,3dd44dcd,fbba1fe,b0fdbbc,99c450ce,686ebd20,630e140,590565cc 3746,37f8,333e,2687 -90 3 h 159 36 246 bd1e7787,e3b6070,cbf2d3f9,a03adcdf,cc25b40a,2e3de258,aeb0ad08,d92fe080 3580,395f,3827,371a -90 3 h 126 19 85 1353821c,1164114,348225d9,771e8565,87fe0685,a2fe2752,fdcc577c,935e714d 380f,380a,3426,3379 -90 3 h 138 94 22 bb2222bb,11d29d21,aa381ed4,95bb8e85,96e9e166,f26bf484,4952effc,8101d0ea 3833,3566,3840,376b -90 3 f 71 98 51 cba4dc16,54e0b4a5,59ea9822,573577f5,a81c3b0e,c0c07ab0,c1ef7064,d39f1535 3e65394e,3edd775e,3e96a5a9,3f2cbcbd -90 3 f 104 186 120 70059b97,ad945fac,b215827c,491a6971,dc2ff5bf,71989a93,fa63fc09,39b141f8 3eef5bd7,3ec8f23d,3f311c47,3f11a1a2 -90 3 f 97 223 128 cef0c273,167ecac,30383fa4,ce582c02,493e1f78,d0fa1810,f8dc2238,eff892d5 3f13e4f9,3f150541,3f208822,3f2dadae -90 3 f 211 75 6 26d4b2b2,a0d7f493,f678aa7b,85c0c7e0,fba6eeb5,e87bec2d,b5e1b7dd,e0509c50 3edaf6be,3ebcef3c,3ee3d8f6,3f1c2c2c -90 3 f 232 241 223 75b2c2b8,915f5d0a,40574789,bc60489a,231a1106,4666d2fb,e7523261,82d61f2e 3f339ce7,3ea98a63,3e46318c,3f2b6b6b -90 3 f 8 243 86 7d345b43,3dd44dcd,fbba1fe,b0fdbbc,99c450ce,686ebd20,630e140,590565cc 3ee8ba2f,3efeffc0,3e67b9ee,3cd0d0d1 -90 3 f 236 199 184 cba4dc16,54e0b4a5,59ea9822,573577f5,a81c3b0e,c0c07ab0,c1ef7064,d39f1535 3ef4dd37,3f204812,3e894251,3f4fbfc0 -90 3 f 159 36 246 bd1e7787,e3b6070,cbf2d3f9,a03adcdf,cc25b40a,2e3de258,aeb0ad08,d92fe080 3eb00c03,3f2bdaf7,3f04e138,3ee34343 -92 1 h 136 0 0 55b38334,9f772a1e 2f30,6c2d,4c0f,3c00 -92 1 h 58 0 0 a8c403ee,3f8321f2 3d53,79b,52c5,3c00 -92 1 h 225 0 0 8017c4d2,693aaa14 40fc,74ab,37d5,3c00 -92 1 h 10 0 0 db530c9e,e2d2ae3e 5255,2609,6dd3,3c00 -92 1 h 140 0 0 3e202a33,57aca780 7460,55ce,28a3,3c00 -92 1 h 30 0 0 86e3d1dc,67ddd9b0 1d7d,46d8,4292,3c00 -92 1 h 16 0 0 524f6887,54a53228 138a,3a6d,2932,3c00 -92 1 h 212 0 0 9f772a1e,3cae3784 770a,653f,453f,3c00 -92 1 f 16 0 0 524f6887,54a53228 3a714000,3f4da000,3d264000,3f800000 -92 1 f 212 0 0 9f772a1e,3cae3784 46e14000,44a7e000,40a7e000,3f800000 -92 1 f 212 0 0 ec00e0f7,3aef058f 4302e000,439f0000,45840000,3f800000 -92 1 f 230 0 0 ec00e0f7,3aef058f 430e0000,43ac8000,451c0000,3f800000 -92 1 f 77 0 0 7b2d275c,271fdf5f 46b9c000,430c6000,3f764000,3f800000 -92 1 f 34 0 0 e642f0fd,b3fc96b3 43f46000,45ae4000,46462000,3f800000 -92 1 f 42 0 0 3aef058f,918f9ca0 43060000,43a08000,3fc80000,3f800000 -92 1 f 128 0 0 d6aec009,db530c9e 40bc0000,43300000,45940000,3f800000 -92 2 h 177 20 0 6ab4ce3d,9d11e704,b8de85be,654740ca 6db4,6254,4ddb,3c00 -92 2 h 67 227 0 c1070dd3,3712cc2d,5bae2280,6033c29f 4ef9,60df,5208,3c00 -92 2 h 77 9 0 2b17cf5,88d68622,3ef47e81,95a4c473 5caa,612b,3da6,3c00 -92 2 h 30 10 0 62687c51,d1af3ea0,2f32d2f9,d8d4c1af 5d79,580c,5c9a,3c00 -92 2 h 114 78 0 d9844799,7f9eab62,989ef474,841ab8fc 744a,39a5,6758,3c00 -92 2 h 243 106 0 a434d81a,d9c777a1,b16dc205,2c81b4f3 76bf,55bb,696e,3c00 -92 2 h 171 122 0 e7d9c309,28a91675,8760aa62,d7b8cdf4 6245,6b1e,6bf1,3c00 -92 2 h 98 145 0 f6a5bc22,651a4af2,7f99c41c,a45695b1 525b,4421,73c4,3c00 -92 2 f 171 122 0 e7d9c309,28a91675,8760aa62,d7b8cdf4 4448a000,4563c000,457e2000,3f800000 -92 2 f 98 145 0 f6a5bc22,651a4af2,7f99c41c,a45695b1 424b6000,40842000,46788000,3f800000 -92 2 f 38 105 0 8fcdd009,8c51b70f,2aaca465,7a2b35d5 44632000,4281c000,40922000,3f800000 -92 2 f 96 163 0 9ec8edf4,edb3a5af,71327753,c4d91f5f 46610000,443b6000,45780000,3f800000 -92 2 f 255 108 0 caae5204,1d349c13,84d5b920,4dc5bbd8 4004a000,44bf4000,40436000,3f800000 -92 2 f 180 123 0 1daba0f6,5f1fd1ac,779848a5,af162b83 3e366000,41950000,4222e000,3f800000 -92 2 f 237 46 0 a648452c,735fd91a,f2c2fa21,1d5710a2 40528000,3fbce000,4413c000,3f800000 -92 2 f 122 9 0 1b19f5a,79020897,11ae84f7,e730898f 4635e000,43f0c000,4380e000,3f800000 -92 3 h 216 6 205 4a3439cb,6caad6ed,2444e036,b00dfef7,8cd6bc5f,782129f5,7e9cfc8a,c0b44d8c 649a,57af,4950,3c00 -92 3 h 102 242 178 aa984aea,db6e3a08,d64e266f,42fa2aee,9caeb911,3a1b2637,491e93a8,f6101dbd 5e10,67f5,73a9,3c00 -92 3 h 247 37 214 7db85417,906b7eca,58bd9ebb,863beace,497aa4e7,a12f0894,9fd5e32e,55b66c36 610b,6859,4e8c,3c00 -92 3 h 113 197 90 a69c933a,ab82e1a7,3adeebb6,12a35422,67162d63,f5f99bfe,82eee59a,95ecdc34 5024,60bb,67eb,3c00 -92 3 h 225 41 205 7f1951e3,f1867551,a597efb1,545d93a1,5ab8d978,38c1c9da,dca2d800,73f1e1f1 5b5a,6424,6daf,3c00 -92 3 h 75 101 55 b393cf44,851e6559,749fa122,97cf8e9f,7e852dbc,bd6ac485,a505e789,276da513 701a,48d8,5535,3c00 -92 3 h 130 218 110 4cee7bc6,f149bbad,b9e8dc21,ef69674,4337cbfb,f3562d3f,ab87b107,e9488554 5f71,6619,6e93,3c00 -92 3 h 16 29 40 95e1542c,53f5f85e,345ee9bd,c44e9c29,dac36aed,444cb562,311550ea,6d82605 43b7,5a04,61b3,3c00 -92 3 f 130 218 110 4cee7bc6,f149bbad,b9e8dc21,ef69674,4337cbfb,f3562d3f,ab87b107,e9488554 43ee2000,44c32000,45d26000,3f800000 -92 3 f 16 29 40 95e1542c,53f5f85e,345ee9bd,c44e9c29,dac36aed,444cb562,311550ea,6d82605 4076e000,43408000,44366000,3f800000 -92 3 f 133 15 10 99960a99,4065d99b,db56b827,9e0a2fe,b3a50150,626e1a77,cd91803d,4f5d8036 3cc7a000,414aa000,43294000,3f800000 -92 3 f 152 214 76 e7bff9c,4080ac58,200e0fad,de803550,1809d206,6b696762,cef7e708,70c93e63 46886000,45116000,452de000,3f800000 -92 3 f 92 94 28 e1346826,ea2359fe,a69c933a,ab82e1a7,ccbeb9d,46b61b61,67162d63,f5f99bfe 402ac000,44974000,4601e000,3f800000 -92 3 f 167 102 64 93321c8f,c4d10f1e,bed74478,9d5585d4,2d50525a,c47b3b37,21e79304,a3682227 4561a000,452c6000,43bc0000,3f800000 -92 3 f 123 232 235 bac922a4,4d2050aa,88ef8916,4063cbf0,d1b87772,359d43f9,cb0f7a94,b3e31955 44a32000,43e94000,44468000,3f800000 -92 3 f 93 193 183 b4ef2a76,65999666,f582617e,8c1248a8,4a68ef6e,a725912c,3ab921a4,cf3872a2 4547c000,45c72000,45f8c000,3f800000 -93 1 h 177 0 0 33ae6672,136b6182 a7c,f17,d1f,3c00 -93 1 h 157 0 0 a75596a9,a5973149 4c2d,4d23,4e41,3c00 -93 1 h 162 0 0 33ae6672,136b6182 b24,100f,def,3c00 -93 1 h 112 0 0 f177b773,f4a3435f 75a9,7707,71af,3c00 -93 1 h 185 0 0 a75596a9,a5973149 4c73,4d7d,4e10,3c00 -93 1 h 56 0 0 f177b773,f4a3435f 75bb,7739,704b,3c00 -93 1 h 187 0 0 63d5dfb1,dc51e7a0 68c0,658c,664d,3c00 -93 1 h 150 0 0 86e7f1fd,63d5dfb1 3b15,3acc,39fd,3c00 -93 1 f 187 0 0 63d5dfb1,dc51e7a0 45180000,44b18000,44c9a000,3f800000 -93 1 f 150 0 0 86e7f1fd,63d5dfb1 3f62a000,3f598000,3f3fa000,3f800000 -93 1 f 161 0 0 15f66e3a,de190662 43f68000,4424c000,44f54000,3f800000 -93 1 f 101 0 0 67b6659d,cbb793ff 43c9a000,43b46000,433b2000,3f800000 -93 1 f 119 0 0 162fc4a3,39c1ac3e 397c6000,3a572000,39eaa000,3f800000 -93 1 f 19 0 0 33ae6672,136b6182 39d6a000,3a8f2000,3a5aa000,3f800000 -93 1 f 93 0 0 a5973149,34782256 41518000,4181e000,41636000,3f800000 -93 1 f 63 0 0 831a67c3,33ae6672 3faa0000,3f678000,3f156000,3f800000 -93 2 h 253 130 0 1f149a37,615bfde,e690c651,3509b6fc 47b6,48b7,5100,3c00 -93 2 h 188 167 0 1f40dc67,9d4bfe21,98b63465,996dd478 4137,488e,444d,3c00 -93 2 h 127 199 0 78fa1ef1,5fa04f03,6eb9e434,15d6e84b 2c3e,2ecc,2e8e,3c00 -93 2 h 141 89 0 f10ffb19,c3f759cf,601c2e5f,5f202a34 6d4f,70bc,6543,3c00 -93 2 h 73 211 0 956e1066,bb3d8137,84032819,c10f6bb9 56fb,56cf,4d8d,3c00 -93 2 h 115 135 0 9f3f7177,5324961f,595b5a00,717322ad 422f,4360,4396,3c00 -93 2 h 229 89 0 7b145744,ce6958fa,9e58f97d,af942106 5cba,5a4c,5fc7,3c00 -93 2 h 214 228 0 535a68fc,d6f91c1e,e180c06f,c826c989 62af,624d,5e44,3c00 -93 2 f 229 89 0 7b145744,ce6958fa,9e58f97d,af942106 43974000,43498000,43f8e000,3f800000 -93 2 f 214 228 0 535a68fc,d6f91c1e,e180c06f,c826c989 4455e000,4449a000,43c88000,3f800000 -93 2 f 109 125 0 4ecb7360,344b0553,317250d3,1669a187 3b716000,3b96c000,3b8ae000,3f800000 -93 2 f 11 51 0 e9c846,5c38276,46deda3c,2ebb8af0 393ec000,3a8da000,3aa8c000,3f800000 -93 2 f 18 113 0 31d2412c,47084737,13327a6d,d3817e12 400f2000,41bdc000,41de8000,3f800000 -93 2 f 253 130 0 1f149a37,615bfde,e690c651,3509b6fc 40f6c000,4116e000,42200000,3f800000 -93 2 f 247 242 0 d7de37e2,356d9113,862f3e08,5c2fd11f 406f6000,40124000,407cc000,3f800000 -93 2 f 96 170 0 dca044da,5356b627,d445866b,f59251cf 45f7a000,459f6000,45cf0000,3f800000 -93 3 h 152 155 2 2c594887,ac7cee43,8c632451,f5c77485,fb4ee771,d3ba4081,9ecf635c,263f9bce 6a0d,70f5,7022,3c00 -93 3 h 84 12 14 c0150913,47dc6888,ba151eea,20c213ce,71c334b9,fdd7fd73,6658ad90,eb818c5 63ac,64af,626b,3c00 -93 3 h 7 222 50 5fce24d3,f1d52659,b79026be,dbb05cbd,8eb3ef5f,9856a893,5d2d145c,b7b9a6f 54dd,50bd,5861,3c00 -93 3 h 70 118 243 aa465ae7,424bc72a,5a89e1b9,b160ae26,9729af83,f9ea430f,b0ab309c,1a3a3c0 6cc1,6d16,6848,3c00 -93 3 h 14 49 219 6198bc7,db4f7e97,35190282,bc604ce6,dac0c572,8fb26ce5,26ad11f2,16f164db 6797,602f,6348,3c00 -93 3 h 95 254 125 a186fd96,b8b4530c,ed9e1756,c1ecdd6c,5aeca8ec,31d8ad94,15c7f75c,8eac5b8a 6af6,695e,6b36,3c00 -93 3 h 200 79 198 758e3aa6,e98edaab,6cf5ee93,f5db2600,7ce245fc,bfe62592,aa161067,6b42492a 61e5,69a9,670a,3c00 -93 3 h 12 227 173 e8cf8bea,2fea2153,d69b2fcf,df3059be,25440f94,326d642f,952cd735,f6846ad0 65c9,641e,652a,3c00 -93 3 f 200 79 198 758e3aa6,e98edaab,6cf5ee93,f5db2600,7ce245fc,bfe62592,aa161067,6b42492a 443ca000,45352000,44e14000,3f800000 -93 3 f 12 227 173 e8cf8bea,2fea2153,d69b2fcf,df3059be,25440f94,326d642f,952cd735,f6846ad0 44b92000,4483c000,44a54000,3f800000 -93 3 f 39 183 192 27b4d9df,2d639498,8994121,37135e9f,87160a8,a8ea21da,29a570fc,70ecd701 3ff9c000,3f8ee000,3e76e000,3f800000 -93 3 f 96 226 27 5b4ee082,6c82868d,36f049c3,c6cef2c7,67c3eaf9,49043157,32f34410,145c4c28 426bc000,42df4000,4300e000,3f800000 -93 3 f 97 59 171 655fa7f3,a5906b43,84238958,5416885c,82883abf,3e2c9250,1ef30d1b,955a04d3 401e0000,3f31e000,402ec000,3f800000 -93 3 f 100 93 53 e3bbd553,bb2ec2bb,88692791,3ff16a5c,47399e33,eb074dcc,cf86a3be,65dca686 451b6000,45466000,44c24000,3f800000 -93 3 f 165 149 166 3d5f66f1,e1a4e811,ab24dffd,2bb79590,9e8c7f28,3c47841c,e5b3586d,59695972 4384a000,44890000,446be000,3f800000 -93 3 f 82 30 198 da4d8ecb,190fbb21,7131d262,24cb4c5c,70802a8,ecfd21c6,c9fe8361,2bc75aa8 45572000,449e0000,45168000,3f800000 -94 1 h 224 0 0 91d586be,14891df 2aaa,3819,37ee,2d55 -94 1 h 137 0 0 dda6735e,6a7aedb8 3891,386c,38fa,3925 -94 1 h 57 0 0 ce733d9e,91d586be 339a,337e,377b,3b68 -94 1 h 202 0 0 4ff93787,48358363 30eb,364a,3ad7,3555 -94 1 h 210 0 0 f5199225,2cf760eb 39ce,37c7,348f,31c0 -94 1 h 156 0 0 2cf760eb,dda6735e 3875,36d0,38d3,38e0 -94 1 h 10 0 0 2a74197d,822657d0 391d,342f,3653,26a7 -94 1 h 54 0 0 839d49b4,7fd040c1 3412,3945,3605,38c5 -94 1 f 59 0 0 f36a76af,a46c670 3f27b9ee,3f19c672,3f284a13,3f450505 -94 1 f 138 0 0 5ac2ad06,e32f3c57 3efa5e98,3f1745d1,3e27e9fa,3f315151 -94 1 f 224 0 0 91d586be,14891df 3d55354d,3f0310c4,3efdbf70,3daaaaab -94 1 f 135 0 0 dda6735e,6a7aedb8 3f11a469,3f0cf33d,3f200802,3f260606 -94 1 f 137 0 0 dda6735e,6a7aedb8 3f121485,3f0d8361,3f1f37ce,3f24a4a5 -94 1 f 45 0 0 34a651c5,2d4f5fca 3f4d8361,3efd1f48,3f082209,0 -94 1 f 10 0 0 2a74197d,822657d0 3f2398e6,3e85e178,3eca5295,3cd4d4d5 -94 1 f 57 0 0 ce733d9e,91d586be 3e733ccf,3e6fbbef,3eef5bd7,3f6cfcfd -94 2 h 249 155 0 294f3688,3c5479a7,55970bd5,2953c5c3 3a0b,3438,370f,1dc6 -94 2 h 13 206 0 41e1bc93,b80f12ea,674c1311,40e67146 37bd,38fb,3910,3562 -94 2 h 1 26 0 70c9eb4f,f9a59e7f,f67154e8,416b695e 3a2d,3884,3a21,3673 -94 2 h 212 60 0 5b212b83,b47fe1cb,b739f410,becda96d 3a69,3aa4,3785,38fb -94 2 h 111 170 0 b45d02a1,952c3c05,8517c7d5,c0467d43 3382,3887,389f,3a1a -94 2 h 201 80 0 a8f63a31,99b590c9,a302196a,e5ca06dd 37e4,3687,3630,39fd -94 2 h 29 102 0 2b8bf89f,c79e68b3,3fcb198e,c3a40993 39ce,39bd,3400,2f3f -94 2 h 111 175 0 1412dd19,b98a82e1,18567585,a316036 35fc,34dd,34f9,2dda -94 2 f 107 217 0 a08c9ade,493f2595,a15f579a,3e2a7bcc 3f27c9f2,3f55d575,3f5eb7ae,3ed19192 -94 2 f 249 155 0 294f3688,3c5479a7,55970bd5,2953c5c3 3f415054,3e8701c0,3ee1d876,3bb8b8b9 -94 2 f 13 206 0 41e1bc93,b80f12ea,674c1311,40e67146 3ef79de7,3f1f57d6,3f220882,3eac4c4c -94 2 f 1 26 0 70c9eb4f,f9a59e7f,f67154e8,416b695e 3f459164,3f108421,3f442108,3ece6e6e -94 2 f 29 102 0 2b8bf89f,c79e68b3,3fcb198e,c3a40993 3f39ce74,3f37adeb,3e800000,3de7e7e8 -94 2 f 212 60 0 5b212b83,b47fe1cb,b739f410,becda96d 3f4d1345,3f548521,3ef09c27,3f1f6f6f -94 2 f 111 170 0 b45d02a1,952c3c05,8517c7d5,c0467d43 3e703c0f,3f10d435,3f13d4f5,3f434343 -94 2 f 201 80 0 a8f63a31,99b590c9,a302196a,e5ca06dd 3efc7f20,3ed0d435,3ec5f17c,3f3f9fa0 -94 3 h 158 234 40 bced60e9,ef95ab1,51ad68dc,6a644667,fa5b9bae,acedf819,8f69ff1e,a1c68c3b 3808,380b,3705,361a -94 3 h 63 230 199 40a0defd,34953b02,6e1f04d1,5e2911f3,5f97f60c,8b92f247,85fedd49,94ad9e22 3461,3abb,35fd,3891 -94 3 h 64 249 252 7dae076c,1538e06d,27d1ebda,4ffe776f,f390309b,45e6611a,ff2f51c2,b7f47269 3b8c,3a1a,37ad,3b36 -94 3 h 89 192 213 d07f2bfb,950a7e1b,fa3ef24c,aa9b6e97,6deba9d5,2f1b21d,184b7867,9fb3db44 37a8,38c2,36df,356a -94 3 h 36 49 83 80d24d8c,e5168e9d,3322d556,588c13d2,4f035d3,4b00ca36,6f5ef773,87a93acb 32be,3224,3764,36e9 -94 3 h 69 133 64 43c8d1fb,67043d00,a8de10a5,339a3dc0,b8b50ea6,355980d6,1c5672ca,93e4226d 37fb,38a9,3663,3644 -94 3 h 211 24 208 da29446c,a6331afe,bc60eac6,8637311a,d4c5d82a,97d5568a,a7849e4a,bdf549ec 36ff,3534,3858,39c2 -94 3 h 149 99 235 25d07fae,6e90fd3c,8942a45d,64e43d99,476fc3a8,5c491885,656a88e8,ba85c8b3 37e8,38cd,35d5,3664 -94 3 f 158 234 40 bced60e9,ef95ab1,51ad68dc,6a644667,fa5b9bae,acedf819,8f69ff1e,a1c68c3b 3f010040,3f016058,3ee09826,3ec34343 -94 3 f 63 230 199 40a0defd,34953b02,6e1f04d1,5e2911f3,5f97f60c,8b92f247,85fedd49,94ad9e22 3e8c2309,3f5765d9,3ebfafec,3f122222 -94 3 f 64 249 252 7dae076c,1538e06d,27d1ebda,4ffe776f,f390309b,45e6611a,ff2f51c2,b7f47269 3f718c63,3f4330cc,3ef59d67,3f66c6c7 -94 3 f 89 192 213 d07f2bfb,950a7e1b,fa3ef24c,aa9b6e97,6deba9d5,2f1b21d,184b7867,9fb3db44 3ef4fd3f,3f18360e,3edbd6f6,3ead4d4d -94 3 f 36 49 83 80d24d8c,e5168e9d,3322d556,588c13d2,4f035d3,4b00ca36,6f5ef773,87a93acb 3e57b5ed,3e44711c,3eec7b1f,3edd1d1d -94 3 f 154 4 36 13f6d23a,ff8f2aa2,30bfcbc2,f13a0b01,2c17169c,165ace3e,5816aaf,32474665 3f305c17,3f37cdf3,3f1e4792,3f045454 -94 3 f 211 24 208 da29446c,a6331afe,bc60eac6,8637311a,d4c5d82a,97d5568a,a7849e4a,bdf549ec 3edfd7f6,3ea689a2,3f0b02c1,3f384848 -94 3 f 69 133 64 43c8d1fb,67043d00,a8de10a5,339a3dc0,b8b50ea6,355980d6,1c5672ca,93e4226d 3eff5fd8,3f152549,3ecc5315,3ec88889 -92 1 h 0 0 0 f8148156,b2be9618 1560,2900,7c00,3c00 -92 1 h 0 0 0 ee1377c0,f80347c0 7c00,26e0,7700,3c00 -92 1 h 219 0 0 151cefa2,f3fe07f8 7e00,7c00,7907,3c00 -92 1 h 170 0 0 fea46b90,58be7132 32bd,7e00,7e00,3c00 -92 1 h 85 0 0 48fb9fc0,77973fc0 7c00,74cd,3554,3c00 -92 1 h 105 0 0 ee1377c0,f80347c0 7c00,2411,7c00,3c00 -92 1 h 194 0 0 c024160f,eabff889 58c9,7e00,7402,3c00 -92 1 h 134 0 0 2caa1d82,f801bace 53de,4ffc,7c00,3c00 -92 1 f 0 0 0 f8148156,b2be9618 3aac0000,3d200000,7f800000,3f800000 -92 1 f 0 0 0 ee1377c0,f80347c0 7f800000,3cdc0000,46e00000,3f800000 -92 1 f 219 0 0 151cefa2,f3fe07f8 7fc00000,7f800000,4720e000,3f800000 -92 1 f 170 0 0 fea46b90,58be7132 3e57a000,7fc00000,7fc00000,3f800000 -92 1 f 85 0 0 48fb9fc0,77973fc0 7f800000,4699a000,3eaa8000,3f800000 -92 1 f 105 0 0 ee1377c0,f80347c0 7f800000,3c822000,7f800000,3f800000 -92 1 f 194 0 0 c024160f,eabff889 43192000,7fc00000,46804000,3f800000 -92 1 f 134 0 0 2caa1d82,f801bace 427bc000,41ff8000,7f800000,3f800000 -92 2 h 0 35 0 8d75dc59,47bfffc0,fd7bf73d,657e07b8 6848,6fa0,7e00,3c00 -92 2 h 0 239 0 f83e00be,fd1bdfc9,fc3e00f6,bd6e27a f26,7c00,7e00,3c00 -92 2 h 251 211 0 f87e07c0,13fcf7c2,f81b541b,19c35a7 7e00,7c00,7e00,3c00 -92 2 h 49 172 0 b1cefd3,2506d7c0,b497e504,fb271ed5 7e00,42e2,7e00,3c00 -92 2 h 85 69 0 e8098c01,f90d67c0,fd62281e,7074bff1 7e00,5bcf,7e00,3c00 -92 2 h 54 124 0 6e7e0513,eac40aaa,56fe1009,8aeca7e0 7e00,7e00,68ae,3c00 -92 2 h 46 88 0 13bc4ae3,3a4f38e8,9b3d9fa3,243dd7c0 7c00,78f4,4634,3c00 -92 2 h 192 87 0 ff7f8ff8,a556b950,2878fa0d,70602a74 7e00,7e00,7e00,3c00 -92 2 f 0 35 0 8d75dc59,47bfffc0,fd7bf73d,657e07b8 45090000,45f40000,7fc00000,3f800000 -92 2 f 0 239 0 f83e00be,fd1bdfc9,fc3e00f6,bd6e27a 39e4c000,7f800000,7fc00000,3f800000 -92 2 f 251 211 0 f87e07c0,13fcf7c2,f81b541b,19c35a7 7fc00000,7f800000,7fc00000,3f800000 -92 2 f 49 172 0 b1cefd3,2506d7c0,b497e504,fb271ed5 7fc00000,405c4000,7fc00000,3f800000 -92 2 f 85 69 0 e8098c01,f90d67c0,fd62281e,7074bff1 7fc00000,4379e000,7fc00000,3f800000 -92 2 f 54 124 0 6e7e0513,eac40aaa,56fe1009,8aeca7e0 7fc00000,7fc00000,4515c000,3f800000 -92 2 f 46 88 0 13bc4ae3,3a4f38e8,9b3d9fa3,243dd7c0 7f800000,471e8000,40c68000,3f800000 -92 2 f 192 87 0 ff7f8ff8,a556b950,2878fa0d,70602a74 7fc00000,7fc00000,7fc00000,3f800000 -92 3 h 5 254 4 f83cdecd,213e8711,a4c74c62,204888ac,b00d3556,b0c2afc0,2750254e,f82057a0 7c00,7e00,7c00,3c00 -92 3 h 5 9 2 61314a75,647e0146,ddbdb51d,f83e98a4,d8423221,fb129f11,f825d638,203e07c0 7c00,7e00,7e00,3c00 -92 3 h 128 0 234 fd116b5e,f82618f9,8ec93fc0,6a997d4d,26bf3c64,f814c83a,578068bc,f97fa2fc 41bf,7e00,7e00,3c00 -92 3 h 243 38 0 8f22c7c0,b359d823,82ff5ff2,e46afb24,1e1cd083,f83e04b0,c0d92c57,583e038d 7e00,7e00,6779,3c00 -92 3 h 16 109 68 fae761dc,893e07c0,c2ac3fdb,ffeb2352,9d13eea4,f826c15f,15df07c0,103fba16 7e00,7e00,7e00,3c00 -92 3 h 250 207 140 a6f990e1,4a027947,ec62cef,1f806f13,f83e014f,622bc49f,334771d8,b8fe0390 6b6e,7c00,7c00,3c00 -92 3 h 186 123 121 d643ac9d,217e05d4,4b0c7c0,313f09ef,5b3e04e6,aabf17f5,907e072c,a204e648 7e00,7e00,5c9e,3c00 -92 3 h 96 250 89 d76f61a7,7dfb50a0,d0d69f5c,7a7e0329,fdfe0496,18d70fbf,ffff51c6,61c9aa38 70ad,7e00,7e00,3c00 -92 3 f 5 254 4 f83cdecd,213e8711,a4c74c62,204888ac,b00d3556,b0c2afc0,2750254e,f82057a0 7f800000,7fc00000,7f800000,3f800000 -92 3 f 5 9 2 61314a75,647e0146,ddbdb51d,f83e98a4,d8423221,fb129f11,f825d638,203e07c0 7f800000,7fc00000,7fc00000,3f800000 -92 3 f 128 0 234 fd116b5e,f82618f9,8ec93fc0,6a997d4d,26bf3c64,f814c83a,578068bc,f97fa2fc 4037e000,7fc00000,7fc00000,3f800000 -92 3 f 243 38 0 8f22c7c0,b359d823,82ff5ff2,e46afb24,1e1cd083,f83e04b0,c0d92c57,583e038d 7fc00000,7fc00000,44ef2000,3f800000 -92 3 f 16 109 68 fae761dc,893e07c0,c2ac3fdb,ffeb2352,9d13eea4,f826c15f,15df07c0,103fba16 7fc00000,7fc00000,7fc00000,3f800000 -92 3 f 250 207 140 a6f990e1,4a027947,ec62cef,1f806f13,f83e014f,622bc49f,334771d8,b8fe0390 456dc000,7f800000,7f800000,3f800000 -92 3 f 186 123 121 d643ac9d,217e05d4,4b0c7c0,313f09ef,5b3e04e6,aabf17f5,907e072c,a204e648 7fc00000,7fc00000,4393c000,3f800000 -92 3 f 96 250 89 d76f61a7,7dfb50a0,d0d69f5c,7a7e0329,fdfe0496,18d70fbf,ffff51c6,61c9aa38 4615a000,7fc00000,7fc00000,3f800000 diff --git a/crates/metal2vulkan/src/tests/engine_linear_half/ycbcr.rs b/crates/metal2vulkan/src/tests/engine_linear_half/ycbcr.rs deleted file mode 100644 index 9ed2430d9..000000000 --- a/crates/metal2vulkan/src/tests/engine_linear_half/ycbcr.rs +++ /dev/null @@ -1,879 +0,0 @@ -//! Metal's linear filter of the two-plane YCbCr formats, on the CPU interpreter against Metal's own -//! samples and its rule, bit for bit. -//! -//! A format's view holds each channel of the converted color as Metal reads it, a step `k / D` -//! (alpha 1) on its field's grid: `2048` (`PackedTexels::YCbCr2048`), `8192` -//! (`PackedTexels::YCbCr8192`), or `8192` signed within `[-2, 2]` -//! (`PackedTexels::YCbCrExtended8192`). Metal's 2D linear sample sums the steps on the grid under -//! the weights `w = wx · wy` in units of `2^-16` (an axis whose two taps address one texel weighs -//! `(256, 0)`), each term truncated: `T = Σ ⌊k · w / 2^7⌋`, then the step `⌊(T + 2^8) / 2^9⌋`, -//! and a `half` result the step's value rounded with ties away from zero (an Apple M3 Max on macOS -//! 26.7 and an Apple M4 on macOS 27.0.1, byte-identical; our probe over the family; and our probe's -//! samples past a texture's edges). The class is the normalized family with `EXACT` -//! (signed for the signed grid) and the field. On MoltenVK, whose sampler is Metal's for every -//! other format, the slot's YCbCr variant (`LoweringInputs::ycbcr_textures`) takes the same -//! emulation. - -use super::*; -use crate::lower::select::LowerInputs; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::testing::{compile_with, typed_module_with}; - -/// A format of each YCbCr field: the format, its grid `D`, and its steps' bounds. -#[derive(Clone, Copy, Debug)] -struct Family { - pf: PixelFormat, - d: i64, - lo: i64, - hi: i64, -} - -/// `YCBCR8_420_2P`, on the grid `2048`. -const G2048: Family = Family { - pf: PixelFormat::YCBCR84202P, - d: 2048, - lo: 0, - hi: 2048, -}; - -/// `YCBCR12_420_2P`, on the grid `8192`. -const G8192: Family = Family { - pf: PixelFormat::YCBCR124202P, - d: 8192, - lo: 0, - hi: 8192, -}; - -/// `YCBCR10_420_2P_XR`, on the signed grid `8192` within `[-2, 2]`. -const X8192: Family = Family { - pf: PixelFormat::YCBCR104202PXR, - d: 8192, - lo: -16384, - hi: 16384, -}; - -/// The format's class. -fn class_of(f: Family) -> u32 { - texel_format(f.pf).0 -} - -/// Lowering inputs with texture slot 0 in its YCbCr variant, or none. -fn inputs(variant: bool) -> LowerInputs { - let mut i = LowerInputs::new(); - if variant { - i.ycbcr_textures.insert(TEXTURE); - } - i -} - -/// Metal's step of a 2D linear sample of a YCbCr format: the taps' steps `k` (`(i, j)`, `(i + 1, -/// j)`, `(i, j + 1)`, `(i + 1, j + 1)`) under the fractions `a` and `b` in 1/256 steps, a merged -/// axis's 0; a signed term and sum floored. -pub(super) fn metal_step(taps: [i64; 4], a: i64, b: i64) -> i64 { - let w = [(256 - a) * (256 - b), a * (256 - b), (256 - a) * b, a * b]; - let t: i64 = taps.iter().zip(w).map(|(k, w)| (k * w) >> 7).sum(); - (t + 256) >> 9 -} - -/// The `half` bits of `k / d` (`d` a power of two, `1 <= |k| / d`'s binade above `2^-14`, or `k -/// = 0`), rounded with ties away from zero. -fn half_away(k: i64, d: i64) -> u16 { - if k == 0 { - return 0; - } - let sign = if k < 0 { 0x8000 } else { 0 }; - let m = k.unsigned_abs(); - let lead = i64::from(63 - m.leading_zeros()); - let e = lead - i64::from(d.trailing_zeros()); - assert!(e >= -14, "{k} / {d} is below the normal halves"); - // The significand's 11 bits: the magnitude rounded half up there, a carry raising `e`. - let shift = lead - 10; - let q = match shift > 0 { - true => (m + (1 << (shift - 1))) >> shift, - false => m << -shift, - }; - let (q, e) = if q == 2048 { (1024, e + 1) } else { (q, e) }; - sign | ((e + 15) as u16) << 10 | (q as u16 - 1024) -} - -/// The result lanes of steps `steps` on grid `d` (alpha 1): `k / d` as `f32` bits (exact), or as -/// `half` bits rounded with ties away from zero when `half`. -pub(super) fn result_bits(steps: [i64; 3], half: bool, d: i64) -> [u32; 4] { - let lanes = [steps[0], steps[1], steps[2], d]; - lanes.map(|k| match half { - true => u32::from(half_away(k, d)), - false => (k as f32 / d as f32).to_bits(), - }) -} - -/// The device's texel of steps `steps` on grid `d` (alpha 1), as the view holds it: each `k / d` -/// exactly. -fn texel(steps: [i64; 3], d: i64) -> [u32; 4] { - [steps[0], steps[1], steps[2], d].map(|k| (k as f32 / d as f32).to_bits()) -} - -/// One of Metal's samples: the fractions `kx` and `ky` in 1/256 steps, the four taps' steps -/// (red, green, and blue; `(i, j)`, `(i + 1, j)`, `(i, j + 1)`, `(i + 1, j + 1)`), Metal's steps, -/// and Metal's `half` result's bits where the probe read it. -type Row = (i64, i64, [[i64; 3]; 4], [i64; 3], Option<[u16; 3]>); - -/// Ten of our probes' samples of `YCBCR8_420_2P` away from the edges (64 x 64 -/// textures, clamp to edge, exact 1/256 fractions), chosen so that each of the rule's neighbours -/// misses some: the exact sum rounded once, and the terms truncated by `2^4`, `2^6`, or `2^8` -/// (the first two rows all four). -const INTERIOR: [Row; 10] = [ - ( - 199, - 180, - [ - [208, 1950, 1471], - [0, 1149, 593], - [0, 1048, 609], - [1165, 2048, 1816], - ], - [651, 1677, 1322], - None, - ), - ( - 126, - 167, - [ - [1247, 994, 1537], - [0, 244, 0], - [238, 111, 446], - [26, 721, 157], - ], - [307, 485, 470], - None, - ), - ( - 207, - 135, - [ - [314, 100, 630], - [406, 890, 836], - [403, 2016, 867], - [0, 1008, 0], - ], - [224, 982, 464], - None, - ), - ( - 50, - 74, - [ - [208, 1950, 1471], - [0, 1149, 593], - [0, 1048, 609], - [1165, 2048, 1816], - ], - [185, 1634, 1168], - None, - ), - ( - 107, - 37, - [ - [314, 100, 630], - [406, 890, 836], - [403, 2016, 867], - [0, 1008, 0], - ], - [335, 598, 686], - None, - ), - ( - 19, - 209, - [[1313, 115, 0], [850, 1053, 143], [763, 0, 852], [0, 0, 538]], - [811, 34, 678], - None, - ), - ( - 234, - 186, - [[1169; 3], [973; 3], [1599; 3], [393; 3]], - [631; 3], - None, - ), - ( - 45, - 205, - [ - [1247, 994, 1537], - [0, 244, 0], - [238, 111, 446], - [26, 721, 157], - ], - [365, 347, 569], - None, - ), - ( - 46, - 167, - [[252; 3], [636; 3], [1496; 3], [1496; 3]], - [1088; 3], - None, - ), - ( - 11, - 117, - [[252; 3], [636; 3], [1496; 3], [1496; 3]], - [830; 3], - None, - ), -]; - -/// Four of our probe's interior samples on the grid `8192` (`YCBCR12_420_2P`'s video -/// range, two; `YCBCR10_420_2P_sRGB`'s, two), each a `half` tie that rounding to nearest even -/// misses, and each missed by the terms truncated by `2^6` or by `2^8`. -const FINE: [Row; 4] = [ - ( - 179, - 1, - [ - [0, 2347, 5566], - [5646, 3359, 7657], - [0, 2403, 3884], - [1218, 0, 3742], - ], - [3936, 3045, 7015], - Some([0x37b0, 0x35f3, 0x3ada]), - ), - ( - 155, - 200, - [ - [0, 1580, 0], - [5414, 7117, 4813], - [923, 4740, 3276], - [5919, 8191, 7290], - ], - [3801, 6415, 5096], - Some([0x376d, 0x3a44, 0x38fa]), - ), - ( - 227, - 91, - [ - [272, 0, 0], - [1366, 6118, 1560], - [698, 147, 0], - [3883, 5660, 184], - ], - [2053, 5286, 950], - Some([0x3403, 0x392a, 0x2f6c]), - ), - ( - 202, - 168, - [ - [1329, 7168, 929], - [8192, 6439, 1506], - [0, 3286, 0], - [3795, 4112, 111], - ], - [4284, 4850, 533], - Some([0x382f, 0x38bd, 0x2c2a]), - ), -]; - -/// Six of our probe's interior samples on the signed grid `8192` (`YCBCR12_420_2P_XR`'s, -/// three; `YCBCR10_420_2P_XR`'s, three): negative steps, steps past `8192`, `half` ties, and -/// each of the rule's neighbours missing some. -const EXTENDED: [Row; 6] = [ - ( - 145, - 243, - [ - [-3312, 501, 4446], - [-2852, 2437, 6496], - [359, 3997, 6571], - [-546, 3427, 6304], - ], - [-301, 3569, 6378], - Some([0xa8b4, 0x36f9, 0x3a3b]), - ), - ( - 127, - 158, - [ - [3214, 5328, 4412], - [6673, 3136, 3042], - [3383, 7503, 5832], - [3286, 2551, 1666], - ], - [3946, 4738, 3753], - Some([0x37b5, 0x38a1, 0x3755]), - ), - ( - 203, - 69, - [ - [-4637, 2482, 1205], - [-3569, 2421, -664], - [-1307, 5280, 2263], - [3023, 8928, 3462], - ], - [-2195, 3980, 664], - Some([0xb44a, 0x37c6, 0x2d30]), - ), - ( - 71, - 49, - [ - [2134, 6376, 4112], - [2666, 5585, 8194], - [3919, 2879, 1990], - [1118, 39, 676], - ], - [2446, 5378, 4552], - Some([0x34c7, 0x3941, 0x3872]), - ), - ( - 93, - 132, - [ - [3796, 5019, 11274], - [1131, 1004, 8300], - [5669, 6740, 13647], - [1172, 684, 10343], - ], - [3450, 4065, 11355], - Some([0x36bd, 0x37f1, 0x3d8b]), - ), - ( - 31, - 144, - [ - [-36, 521, 1296], - [794, 823, 351], - [-444, 146, 347], - [1186, 3088, 905], - ], - [-111, 526, 750], - Some([0xa2f0, 0x2c1c, 0x2ddc]), - ), -]; - -/// Two of our probe's samples of `YCBCR8_420_2P` (an Apple M4; a 40 x 24 texture, clamp to -/// edge) whose `y` taps clamp onto one row, at the top and the bottom edge: the unmerged -/// fraction (8 and 216 here) answers one step low on red chroma. Each row's taps are `(i, j)` -/// and `(i + 1, j)`. -const EDGES: [(i64, i64, [[i64; 3]; 2], [i64; 3]); 2] = [ - ( - 72, - 8, - [[373, 2048, 957], [239, 2048, 333]], - [335, 2048, 782], - ), - ( - 184, - 216, - [[1216, 497, 649], [1539, 2048, 1849]], - [1448, 1612, 1512], - ), -]; - -/// A compiled kernel sampling a YCbCr texture through a constexpr linear clamp-to-edge sampler or -/// a runtime sampler of that state, with a `half` or `float` result: its plan, module, and the -/// runtime sampler's word. -struct Kernel { - plan: Plan, - m: TypedModule, - word: Option, - a: std::sync::Arc, -} - -/// The kernel of `half` and `runtime` (module docs) on lavapipe, or on MoltenVK under the slot's -/// YCbCr variant when `metal`; `None` without `llvm-as`. -fn kernel_for(half: bool, runtime: bool, metal: bool) -> Option { - let p = if metal { m3() } else { lavapipe() }; - let sampler = (!runtime).then(|| linear(1, false, 0)); - let name = format!("ycbcr half={half} runtime={runtime} metal={metal}"); - let bc = assemble( - &name, - &kernel_of(sampler, Form::Plain { offset: (0, 0) }, !half), - )?; - let a = compile_with(&bc, "k", &p, &inputs(metal)).unwrap_or_else(|e| panic!("{name}: {e}")); - assert!( - a.strategies.entries.contains_key("sampler.linear.quad"), - "{name}" - ); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name}: {e}")); - let (plan, m) = typed_module_with(&bc, "k", &p, &inputs(metal)).expect("typed module"); - let word = runtime.then(|| { - runtime_word( - SamplerAddressMode::ClampToEdge, - false, - SamplerBorderColor::TransparentBlack, - ) - }); - Some(Kernel { plan, m, word, a }) -} - -/// `k`'s results at normalized `coords` over `image`, bound in `f`'s format. -fn sample( - k: &Kernel, - image: &Image, - coords: &[(f32, f32)], - half: bool, - f: Family, -) -> Vec<[u32; 4]> { - let bytes: Vec = coords - .iter() - .flat_map(|(u, v)| [u.to_le_bytes(), v.to_le_bytes()]) - .flatten() - .collect(); - let size = if half { 8 } else { 16 }; - let n = coords.len(); - let res = resources(&k.plan, &[bytes, vec![0xab; size * n]], class_of(f)); - let res = with_word(res, &k.a, k.word); - run(&k.m, &res, image, n as u32, half) -} - -/// Each result, sampler, and device (lavapipe, and MoltenVK under the variant). -fn combinations() -> Vec<(bool, bool, bool)> { - let flags = [false, true]; - flags - .iter() - .flat_map(|&h| flags.iter().flat_map(move |&r| flags.map(|m| (h, r, m)))) - .collect() -} - -/// `rows`' samples of `f`'s format through `k`, away from the edges: row `r`'s taps at `x` `2r` -/// and `2r + 1`, rows 0 and 1; each Metal's steps (and, where read, its `half` bits). -fn check_rows(k: &Kernel, half: bool, f: Family, rows: &[Row], name: &str) { - let n = rows.len() as u32; - let mut image = Image::new(combined_slot(&k.m), [2 * n, 2, 1], 1, 1, 1); - for (r, (_, _, taps, _, _)) in (0u32..).zip(rows) { - let sites = [ - [2 * r, 0, 0], - [2 * r + 1, 0, 0], - [2 * r, 1, 0], - [2 * r + 1, 1, 0], - ]; - for (at, t) in sites.into_iter().zip(taps) { - let i = image.index(0, 0, 0, at).expect("texel"); - image.texels[i] = texel(*t, f.d); - } - } - let coords: Vec<(f32, f32)> = (0u32..) - .zip(rows) - .map(|(r, (a, b, _, _, _))| { - let u = (512 * i64::from(r) + 128 + a) as f32 / (512 * n) as f32; - (u, (128 + b) as f32 / 512.0) - }) - .collect(); - let got = sample(k, &image, &coords, half, f); - for ((a, b, taps, want, metal_half), g) in rows.iter().zip(got) { - assert_eq!( - g, - result_bits(*want, half, f.d), - "{name} {f:?} k {a} {b} taps {taps:?}: {g:x?}" - ); - if let (true, Some(h)) = (half, metal_half) { - assert_eq!(g[..3], h.map(u32::from), "{name} {f:?} Metal's half bits"); - } - } -} - -/// Metal's samples (module docs) through a constexpr sampler and a runtime one, with `float` and -/// `half` results, on lavapipe and on MoltenVK under the variant, are Metal's bytes: on the grid -/// `2048` (each step exact in `half`; our probe's `half` samples of the format are its -/// `float` ones), `8192`, and the signed `8192`; and the rule answers each of them. -#[test] -fn ycbcr_linear_samples_are_metals_bytes() { - for (f, rows) in [ - (G2048, &INTERIOR[..]), - (G8192, &FINE[..]), - (X8192, &EXTENDED[..]), - ] { - for (a, b, taps, want, metal_half) in rows { - let steps = std::array::from_fn(|c| metal_step(taps.map(|t| t[c]), *a, *b)); - assert_eq!(steps, *want, "the rule at {a} {b} on {f:?}"); - if let Some(h) = metal_half { - let away = std::array::from_fn(|c| half_away(want[c], f.d)); - assert_eq!(away, *h, "ties away at {a} {b} on {f:?}"); - } - } - } - for (a, _, taps, want) in EDGES { - let [lo, hi] = taps; - let steps = std::array::from_fn(|c| metal_step([lo[c], hi[c], lo[c], hi[c]], a, 0)); - assert_eq!(steps, want, "the rule at {a}, merged"); - } - for (half, runtime, metal) in combinations() { - let Some(k) = kernel_for(half, runtime, metal) else { - return; - }; - let name = format!("half={half} runtime={runtime} metal={metal}"); - check_rows(&k, half, G2048, &INTERIOR, &name); - check_rows(&k, half, G8192, &FINE, &name); - check_rows(&k, half, X8192, &EXTENDED, &name); - // Past the edges: a texture one row tall, whose `y` taps clamp onto that row. - let n = EDGES.len() as u32; - let mut image = Image::new(combined_slot(&k.m), [2 * n, 1, 1], 1, 1, 1); - for (r, (_, _, taps, _)) in (0u32..).zip(EDGES) { - for (x, t) in [2 * r, 2 * r + 1].into_iter().zip(taps) { - let i = image.index(0, 0, 0, [x, 0, 0]).expect("texel"); - image.texels[i] = texel(t, G2048.d); - } - } - let coords: Vec<(f32, f32)> = (0u32..) - .zip(EDGES) - .map(|(r, (a, b, _, _))| { - let u = (512 * i64::from(r) + 128 + a) as f32 / (512 * n) as f32; - (u, (128 + b) as f32 / 256.0) - }) - .collect(); - let got = sample(&k, &image, &coords, half, G2048); - for ((a, b, taps, want), g) in EDGES.into_iter().zip(got) { - assert_eq!( - g, - result_bits(want, half, G2048.d), - "{name} edge k {a} {b} taps {taps:?}: {g:x?}" - ); - } - } -} - -/// The emulation is the rule (module docs) at random steps and positions over an 8 x 4 texture -/// of each field's format, a quarter of them past an edge on one axis or both (each axis's -/// positions within one and a half texels of the texture), through both samplers, both results, -/// and both devices. -#[test] -fn ycbcr_linear_samples_take_metals_rule() { - const W: i64 = 8; - const H: i64 = 4; - let mut rng = Lcg(0x0059_3593); - // Footprint positions `q = 256 (x - 1/2)`, exact: `x = (q + 128) / 256` texels. - let positions: Vec<(i64, i64)> = (0..96) - .map(|_| { - let mut q = |n: i64| (rng.next() % (256 * n as u64 + 768)) as i64 - 384; - (q(W), q(H)) - }) - .collect(); - let edges = positions - .iter() - .filter(|&&(qx, qy)| { - let out = |q: i64, n: i64| q < 0 || q >= 256 * (n - 1); - out(qx, W) || out(qy, H) - }) - .count(); - assert!(edges >= positions.len() / 4, "{edges} past an edge"); - let coords: Vec<(f32, f32)> = positions - .iter() - .map(|&(qx, qy)| { - let n = |q: i64, n: i64| (q + 128) as f32 / (256 * n) as f32; - (n(qx, W), n(qy, H)) - }) - .collect(); - let clamped = |i: i64, n: i64| i.clamp(0, n - 1); - let mut rng = Lcg(0x5935_5a62_d593); - let families = [G2048, G8192, X8192].map(|f| { - let span = (f.hi - f.lo + 1) as u64; - let mut step = || f.lo + (rng.next() % span) as i64; - let steps: Vec<[i64; 3]> = (0..W * H).map(|_| [step(), step(), step()]).collect(); - let want: Vec<[i64; 3]> = positions - .iter() - .map(|&(qx, qy)| { - let (i, j, a, b) = (qx >> 8, qy >> 8, qx & 255, qy & 255); - let (i0, i1) = (clamped(i, W), clamped(i + 1, W)); - let (j0, j1) = (clamped(j, H), clamped(j + 1, H)); - let a = if i0 == i1 { 0 } else { a }; - let b = if j0 == j1 { 0 } else { b }; - let at = |x: i64, y: i64| steps[(y * W + x) as usize]; - let taps = [at(i0, j0), at(i1, j0), at(i0, j1), at(i1, j1)]; - std::array::from_fn(|c| metal_step(taps.map(|t| t[c]), a, b)) - }) - .collect(); - (f, steps, want) - }); - for (half, runtime, metal) in combinations() { - let Some(k) = kernel_for(half, runtime, metal) else { - return; - }; - for (f, steps, want) in &families { - let mut image = Image::new(combined_slot(&k.m), [W as u32, H as u32, 1], 1, 1, 1); - for y in 0..H { - for x in 0..W { - let i = image - .index(0, 0, 0, [x as u32, y as u32, 0]) - .expect("texel"); - image.texels[i] = texel(steps[(y * W + x) as usize], f.d); - } - } - let got = sample(&k, &image, &coords, half, *f); - for ((p, w), g) in positions.iter().zip(want).zip(got) { - assert_eq!( - g, - result_bits(*w, half, f.d), - "half={half} runtime={runtime} metal={metal} {f:?} q {p:?}: {g:x?}" - ); - } - } - } -} - -/// On MoltenVK a filtered sample records `RuntimeFact::YCbCrTexture`, and outside the variant the -/// device filters it, Metal's sampler, unnoted; under the variant a sample the emulation reaches -/// takes it, noted where its device arm runs (a class of no measured family), and one it does -/// not reach (a linear mip filter) is the device's, noted. Every one of these `half` samples -/// requires `VkProperty::MetalSampler` there, whose texel's rounding to `half` is Metal's only -/// through Metal's own texture unit. A nearest sample records nothing. On lavapipe the variant -/// changes nothing. -#[test] -fn moltenvk_emulates_a_ycbcr_slot_under_its_variant() { - let plain = Form::Plain { offset: (0, 0) }; - // (name, sampler, emulated under the variant, filtered) - let cases = [ - ("linear", Some(linear(1, false, 0)), true, true), - ("runtime", None, true, true), - ("mip", Some(sampler_words(1, 2, 1, false, 0)), false, true), - ( - "nearest", - Some(sampler_words(0, 0, 1, false, 0)), - false, - false, - ), - ]; - let emulated = |a: &crate::library::FunctionArtifact| { - a.strategies.entries.contains_key("sampler.linear.quad") - }; - let metal_sampler = |a: &crate::library::FunctionArtifact| { - a.requirements - .properties - .contains(&VkProperty::MetalSampler) - }; - let fact = RuntimeFact::YCbCrTexture { slot: TEXTURE }; - for (name, sampler, reached, filtered) in cases { - let Some(bc) = assemble(name, &kernel(sampler, plain)) else { - return; - }; - for (stem, p) in [("moltenvk-m3", m3()), ("lavapipe", lavapipe())] { - let metal = stem == "moltenvk-m3"; - for variant in [false, true] { - let what = format!("{name} on {stem}, variant {variant}"); - let a = compile_with(&bc, "k", &p, &inputs(variant)) - .unwrap_or_else(|e| panic!("{what}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: {e}")); - let (plan, _) = typed_module_with(&bc, "k", &p, &inputs(variant)) - .unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!(plan.facts.contains(&fact), metal && filtered, "{what}"); - let takes = !metal || variant; - assert_eq!(emulated(&a), reached && takes, "{what}"); - assert_eq!( - a.precision.contains(&PrecisionNote::HalfSampleFilter), - filtered && takes, - "{what}" - ); - assert_eq!(metal_sampler(&a), metal, "{what}"); - } - } - } -} - -/// Under native sampling (the default), a filtered sample of a texture slot records -/// `RuntimeFact::YCbCrTexture` only under `YCbCrFilterPolicy::Exact`, whose variant emulates -/// Metal's filter of a two-plane YCbCr format bound there, on lavapipe and on MoltenVK. Under the -/// default, `YCbCrFilterPolicy::Device`, it records none, so a draw binding such a texture makes no -/// variant, and the device filters the slot whatever the inputs name: on lavapipe the module records -/// `DeviceSampling` (its note of the device's filter) and no filter note; on MoltenVK, whose -/// sampler is Metal's own, the filter note, which holds only where the format bound at the slot is -/// two-plane YCbCr (`SpecKey::BoundTexelFormat`, the runtime's `ycbcr-filter-not-exact`), and no -/// `DeviceSampling`. -#[test] -fn a_device_takes_the_ycbcr_variant_only_under_the_exact_filter() { - use crate::device::YCbCrFilterPolicy; - use crate::metal::texel_format::{PackedTexels, TexelFormat}; - use crate::pipeline::sym::SpecKey; - let Some(bc) = assemble( - "ycbcr policy", - &kernel(Some(linear(1, false, 0)), Form::Plain { offset: (0, 0) }), - ) else { - return; - }; - let fact = RuntimeFact::YCbCrTexture { slot: TEXTURE }; - let ycbcr_fields: Vec = [ - PackedTexels::YCbCr2048, - PackedTexels::YCbCr8192, - PackedTexels::YCbCrExtended8192, - ] - .map(|p| p.class().0) - .into(); - for stem in ["lavapipe", "moltenvk-m3"] { - for ycbcr in [YCbCrFilterPolicy::Device, YCbCrFilterPolicy::Exact] { - let policy = DevicePolicy { - ycbcr_filter: ycbcr, - ..DevicePolicy::UNTRUSTED - }; - let p = profile(stem, policy).expect("profile"); - let native = stem == "lavapipe"; - let takes = ycbcr == YCbCrFilterPolicy::Exact; - assert_eq!(p.fields().ycbcr_variant, takes, "{stem} {ycbcr:?}"); - for variant in [false, true] { - let what = format!("{stem} {ycbcr:?}, variant {variant}"); - let a = compile_with(&bc, "k", &p, &inputs(variant)) - .unwrap_or_else(|e| panic!("{what}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: {e}")); - let (plan, _) = typed_module_with(&bc, "k", &p, &inputs(variant)) - .unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!(plan.facts.contains(&fact), takes, "{what}"); - assert_eq!( - a.strategies.entries.contains_key("sampler.linear.quad"), - takes && variant, - "{what}" - ); - // Metal's own sampler without the variant: the filter note, under a two-plane - // YCbCr format bound at the slot alone. - let bound = !native && !takes; - assert_eq!( - a.precision.contains(&PrecisionNote::HalfSampleFilter), - (takes && variant) || bound, - "{what}" - ); - if bound { - let s = a - .specialized - .iter() - .find(|s| s.note == PrecisionNote::HalfSampleFilter) - .unwrap_or_else(|| panic!("{what}: the filter note's clauses")); - let mut tested: Vec = s - .when - .iter() - .map(|c| match c.all[..] { - [t] if matches!(t.key, SpecKey::BoundTexelFormat(_)) - && t.mask == TexelFormat::PACKED_MASK - && t.equal => - { - t.bits - } - _ => panic!("{what}: {c:?}"), - }) - .collect(); - tested.sort_unstable(); - assert_eq!(tested, ycbcr_fields, "{what}"); - } - // The device's sample, wherever the emulation is not taken: noted on lavapipe. - if !(takes && variant) { - assert_eq!( - a.precision.contains(&PrecisionNote::DeviceSampling), - native, - "{what}" - ); - } - } - } - } -} - -/// A YCbCr texture has one level, which Metal's mip filter leaves as it is: through a runtime -/// sampler whose word states a nearest or a linear mip filter, the emulation answers each field's -/// samples as through none, on lavapipe and on MoltenVK under the variant; and the filter note -/// holds under such a word for a format of another class (`RGBA8Unorm`, whose textures may have -/// levels) and not for `YCBCR8_420_2P`, the one the binder binds yet. -#[test] -fn a_runtime_mip_filter_takes_metals_filter_of_one_level() { - use crate::bind::SamplerDescriptor; - use crate::metal::{SamplerMinMagFilter, SamplerMipFilter}; - for (half, metal) in [(false, false), (true, false), (false, true), (true, true)] { - for mip in [1u32, 2] { - let Some(k) = kernel_for(half, true, metal) else { - return; - }; - let k = Kernel { - word: k.word.map(|w| w | mip << SamplerWord::MIP_FILTER_SHIFT), - ..k - }; - let name = format!("half={half} metal={metal} mip={mip}"); - check_rows(&k, half, G2048, &INTERIOR, &name); - check_rows(&k, half, G8192, &FINE, &name); - check_rows(&k, half, X8192, &EXTENDED, &name); - } - } - let Some(bc) = assemble( - "notes runtime mip", - &kernel(None, Form::Plain { offset: (0, 0) }), - ) else { - return; - }; - let lvp = device_of("lavapipe"); - let runtime = notes_pipeline(&lvp, &bc); - for mip in [SamplerMipFilter::Nearest, SamplerMipFilter::Linear] { - let mut sampler = SamplerDescriptor::new(); - sampler.min_filter = SamplerMinMagFilter::Linear; - sampler.mag_filter = SamplerMinMagFilter::Linear; - sampler.mip_filter = mip; - for (pf, noted) in [(PixelFormat::RGBA8Unorm, true), (G2048.pf, false)] { - let plane = (crate::metal::TextureType::Type2D, pf); - let notes = notes_bound(&runtime, &lvp, plane, Some(sampler)); - assert_eq!( - notes.contains(&PrecisionNote::HalfSampleFilter), - noted, - "{mip:?} {pf:?}: {notes:?}" - ); - } - } -} - -/// On MoltenVK the slot's YCbCr variant emulates an `EXACT` class alone, through the exact -/// routine: every other class, a two-plane format's unmeasured one (its class made with a swizzle, -/// or none) and the float families no two-plane format has, takes the device's sample (Metal's own -/// filter there), which the interpreter does not model, through a constexpr sampler and a runtime -/// one, with `float` and `half` results. On lavapipe the float families keep their emulation. An -/// `EXACT` class's samples stay Metal's (`ycbcr_linear_samples_are_metals_bytes`). -#[test] -fn the_ycbcr_variant_emulates_only_an_exact_class() { - use crate::metal::texel_format::TexelFormat; - use crate::spirv::interp::{InterpError, Unmodelled}; - let unmeasured = [0, TexelFormat(class_of(G2048)).swizzled().0]; - let float = [ - texel_format(PixelFormat::RGBA32Float).0, - texel_format(PixelFormat::RGBA16Float).0, - ]; - for class in unmeasured { - assert_eq!(class & BicubicTexels::EXACT, 0, "{class:#x}"); - } - for (half, runtime, metal) in combinations() { - let Some(k) = kernel_for(half, runtime, metal) else { - return; - }; - let name = format!("half={half} runtime={runtime} metal={metal}"); - let mut image = Image::new(combined_slot(&k.m), [4, 4, 1], 1, 1, 1); - for t in image.texels.iter_mut() { - *t = texel([512, 1024, 1536], G2048.d); - } - let coords = [(0.3f32, 0.6f32), (0.55, 0.45)]; - let bytes: Vec = coords - .iter() - .flat_map(|(u, v)| [u.to_le_bytes(), v.to_le_bytes()]) - .flatten() - .collect(); - let size = if half { 8 } else { 16 }; - let classes = unmeasured.iter().map(|c| (*c, false)); - let classes = classes.chain(float.iter().map(|c| (*c, !metal))); - let classes = classes.chain([(class_of(G2048), true)]); - for (class, emulated) in classes { - let init = [bytes.clone(), vec![0xab; size * coords.len()]]; - let res = with_word(resources(&k.plan, &init, class), &k.a, k.word); - let cfg = Config { - workgroups: [coords.len() as u32, 1, 1], - ..Config::default() - }; - let r = run_with_images(&k.m, &cfg, res, vec![image.clone()]); - let device = matches!( - r, - Err(InterpError::Unmodelled(Unmodelled::Opcode( - crate::spv::Op::ImageSampleExplicitLod | crate::spv::Op::ImageSampleImplicitLod - ))) - ); - assert_eq!( - (r.is_ok(), device), - (emulated, !emulated), - "{name} class {class:#x}: {:?}", - r.err() - ); - } - } -} diff --git a/crates/metal2vulkan/src/tests/engine_private_render_state.rs b/crates/metal2vulkan/src/tests/engine_private_render_state.rs index c02d82980..f1bf56dbf 100644 --- a/crates/metal2vulkan/src/tests/engine_private_render_state.rs +++ b/crates/metal2vulkan/src/tests/engine_private_render_state.rs @@ -761,12 +761,7 @@ fn the_depth_compare_clamp_mask_clamps_its_samplers_references() { ], ), ]; - // Under exact sampling lavapipe's shader makes the constexpr comparison and the slot's gather - // itself (`compared::select`), which clamp alike. - let devices = STEMS.map(|stem| (stem, device(stem))).into_iter().chain([( - "lavapipe exact sampling", - device_with("lavapipe", crate::pipeline::testing::EXACT_SAMPLING), - )]); + let devices = STEMS.map(|stem| (stem, device(stem))); for (stem, dev) in devices { for (fragment, samplers, masks) in cases { let base = compile(&dev, &pipeline(fragment, 0), stem); diff --git a/crates/metal2vulkan/src/tests/engine_sampler.rs b/crates/metal2vulkan/src/tests/engine_sampler.rs index 0f9fce61a..f5bcb32de 100644 --- a/crates/metal2vulkan/src/tests/engine_sampler.rs +++ b/crates/metal2vulkan/src/tests/engine_sampler.rs @@ -23,6 +23,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use crate::device::profile::DeviceProfile; use crate::device::requirements::{VkFeature, VkLimit, VkProperty}; +use crate::device::DevicePolicy; use crate::device::{Device, DeviceDescription}; use crate::error::{Capability, Error, Feature, LowerFamily, Needs, Unsupported}; use crate::library::FunctionArtifact; @@ -33,11 +34,10 @@ use crate::pipeline::interface::{NumberedSampler, SlotInterface}; use crate::pipeline::layout::BindingSource; use crate::pipeline::link::{link, LinkInputs}; use crate::pipeline::sym::{ResourceKind, SamplerRef, SlotClass, SlotRef, SpecKey, Stage}; -use crate::pipeline::testing::EXACT_SAMPLING; use crate::pipeline::testing::{ compile, engine_dir, link_and_validate, llvm_assemble, profile, AssembleError, }; -use crate::spirv::testing::committed_exact_profiles; +use crate::spirv::testing::committed_profiles; const DATALAYOUT: &str = "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"; @@ -91,7 +91,7 @@ fn assemble(name: &str, body: &str) -> Option> { } fn m3() -> DeviceProfile { - profile("moltenvk-m3", EXACT_SAMPLING).expect("profile") + profile("moltenvk-m3", DevicePolicy::default()).expect("profile") } fn ok(bc: &[u8], entry: &str, p: &DeviceProfile) -> std::sync::Arc { @@ -224,7 +224,7 @@ fn every_sampling_entry_compiles_or_refuses_on_every_profile() { let Some(bc) = fixture() else { return; }; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { for entry in ENTRIES { match compile(&bc, entry, &p) { Ok(a) => { @@ -298,58 +298,52 @@ fn runtime_samplers_select_pixel_coordinates_by_specialization() { .all(|d| d.slot.kind != ResourceKind::Texture)); } -/// Off MoltenVK a sample through a runtime sampler slot that Metal's linear filter may answer is -/// planned for the emulation, which the slot's word selects in the function: its `SamplerState` -/// fields add `SamplerWord::LINEAR_STATE` (the filter, coordinates, address modes, and border -/// color) to the pixel fields, the census names the emulation, and the module validates on every -/// committed profile. +/// A sample through a runtime sampler slot is the device's on every committed profile: the +/// function reads only the pixel fields of the slot's word (`SamplerWord::PIXEL_NEAREST`, gated by +/// the coordinates bit), never its filter, address modes or levels, and the module requires the +/// device's own sampler (`VkProperty::MetalSampler` on MoltenVK, `VkProperty::DeviceSampling` +/// elsewhere) and validates. #[test] -fn a_runtime_sampler_reads_its_linear_state_by_specialization() { +fn a_runtime_samplers_sample_is_the_device_s() { let Some(bc) = fixture() else { return; }; let s = slot(Stage::Kernel, SlotClass::Sampler, 0); - for (stem, p) in committed_exact_profiles().expect("profiles") { + let (mut metal, mut device) = (0, 0); + for (stem, p) in committed_profiles().expect("profiles") { let a = ok(&bc, "sample_level", &p); - let fields = sampler_fields(&a, s); - // A device sampling through Metal's own sampler filters every sample. - if a.requirements + assert_eq!( + sampler_fields(&a, s), + Some(SamplerWord::PIXEL_NEAREST | SamplerWord::PIXEL_GATED), + "{stem}" + ); + assert_eq!(uses(&a, "sampler.sample"), 1, "{stem}"); + assert_eq!(uses(&a, "sampler.linear"), 0, "{stem}"); + let property = match p + .fields() + .enabled .properties .contains(&VkProperty::MetalSampler) { - let gated = SamplerWord::PIXEL_NEAREST | SamplerWord::PIXEL_GATED; - assert_eq!(fields, Some(gated), "{stem}"); - assert_eq!(uses(&a, "sampler.sample"), 1, "{stem}"); - continue; - } - // Its level is known, so its nearest snap reads the levels its clamp leaves. - assert_eq!( - fields, - Some( - SamplerWord::PIXEL_NEAREST - | SamplerWord::LINEAR_STATE - | SamplerWord::LEVEL_MIN - | SamplerWord::LEVEL_MAX - ), - "{stem}" - ); - assert_eq!(uses(&a, "sampler.linear"), 1, "{stem}"); - assert!( - a.precision.contains(&PrecisionNote::FloatSampleFilter), - "{stem}" - ); + true => { + metal += 1; + VkProperty::MetalSampler + } + false => { + device += 1; + VkProperty::DeviceSampling + } + }; + assert!(a.requirements.properties.contains(&property), "{stem}"); } + assert!(metal > 0 && device > 0, "metal {metal}, device {device}"); } -/// A runtime sampler's sample at a level the function knows reads, off MoltenVK, the levels its -/// sampler's clamp leaves (`SamplerWord::LEVELED_SNAP`) for its snap, and a level off every rule's -/// grid (a dynamic level, `1.5`, a kernel's dynamic bias) the word's level rule -/// (`SamplerWord::LEVEL_RULE`); each validates on every committed profile, and a leveled snap -/// queries the texture's levels. On a device sampling through Metal's own sampler none is read, -/// and the module requires the property. +/// A runtime sampler's sample at a level (a dynamic level, `1.5`, `1.0`, a kernel's dynamic bias) +/// reads none of the level fields of the slot's word on any committed profile: the device's +/// sampler takes the level, the `VkSampler` holding the sampler's clamp. #[test] -fn a_runtime_samples_level_reads_its_word_by_specialization() { - const OP_IMAGE_QUERY_LEVELS: u16 = 106; +fn a_runtime_samples_level_is_the_device_s() { let kernels = [ ("dynamic_level", true, "%l"), ("half_level", true, "1.5"), @@ -357,8 +351,7 @@ fn a_runtime_samples_level_reads_its_word_by_specialization() { ("dynamic_bias", false, "%l"), ]; let s = slot(Stage::Kernel, SlotClass::Sampler, 0); - let levels = SamplerWord::LEVEL_MIN | SamplerWord::LEVEL_MAX; - let (mut ruled, mut metal) = (0, 0); + let levels = SamplerWord::LEVEL_MIN | SamplerWord::LEVEL_MAX | SamplerWord::MIP_FILTER; for (name, level, value) in kernels { let text = sample_kernel( "%s", @@ -372,83 +365,12 @@ fn a_runtime_samples_level_reads_its_word_by_specialization() { let Some(bc) = assemble(name, &text) else { return; }; - for (stem, p) in committed_exact_profiles().expect("profiles") { + for (stem, p) in committed_profiles().expect("profiles") { let a = ok(&bc, "k", &p); let fields = sampler_fields(&a, s).unwrap_or(0); - if p.fields() - .enabled - .properties - .contains(&VkProperty::MetalSampler) - { - assert!( - a.requirements - .properties - .contains(&VkProperty::MetalSampler), - "{name} {stem}" - ); - assert_eq!(fields & levels, 0, "{name} {stem}"); - metal += 1; - continue; - } - assert_eq!( - fields & SamplerWord::LEVELED_SNAP, - SamplerWord::LEVELED_SNAP, - "{name} {stem}" - ); - assert!(count(&a, OP_IMAGE_QUERY_LEVELS) > 0, "{name} {stem}"); - if name != "whole_level" { - assert_eq!( - fields & SamplerWord::LEVEL_RULE, - SamplerWord::LEVEL_RULE, - "{name} {stem}" - ); - ruled += 1; - } + assert_eq!(fields & levels, 0, "{name} {stem}"); } } - assert!(ruled > 0 && metal > 0, "ruled {ruled}, metal {metal}"); -} - -/// A sample through a runtime sampler slot reads, off MoltenVK, the word's fields that decide its -/// nearest snap (`SamplerWord::NEAREST_SNAP`: whether it reads one texel of the base level, and its -/// address modes) beside the others, and validates on every committed profile; on a device sampling -/// through Metal's own sampler it takes no snap and requires the property. -#[test] -fn a_runtime_nearest_sample_reads_its_snap_by_specialization() { - let Some(bc) = fixture() else { - return; - }; - let s = slot(Stage::Kernel, SlotClass::Sampler, 0); - let (mut snapped, mut metal) = (0, 0); - for (stem, p) in committed_exact_profiles().expect("profiles") { - let a = ok(&bc, "sample_level", &p); - let fields = sampler_fields(&a, s).unwrap_or(0); - if p.fields() - .enabled - .properties - .contains(&VkProperty::MetalSampler) - { - assert!( - a.requirements - .properties - .contains(&VkProperty::MetalSampler), - "{stem}" - ); - assert_eq!( - fields & SamplerWord::NEAREST_SNAP, - fields & SamplerWord::PIXEL_NEAREST - ); - metal += 1; - } else { - assert_eq!( - fields & SamplerWord::NEAREST_SNAP, - SamplerWord::NEAREST_SNAP, - "{stem}" - ); - snapped += 1; - } - } - assert!(snapped > 0 && metal > 0, "snapped {snapped}, metal {metal}"); } /// A sample through a runtime sampler slot reads the slot's word for a nearest pixel sampler beside @@ -588,7 +510,7 @@ fn a_constexpr_pixel_sampler_with_a_compare_function_is_refused() { return; }; ok(&normalized, "k", &m3()); - for (stem, p) in &committed_exact_profiles().expect("profiles") { + for (stem, p) in &committed_profiles().expect("profiles") { match compile(&pixels, "k", p) { Err(Error::Unsupported(u)) => assert_eq!( (u.feature, u.needs), @@ -639,7 +561,7 @@ fn a_constexpr_reduction_compiles_as_the_weighted_average() { let Some(bc) = assemble(name, &kernel(reduction)) else { return; }; - for (stem, p) in &committed_exact_profiles().expect("profiles") { + for (stem, p) in &committed_profiles().expect("profiles") { match (compile(&average, "k", p), compile(&bc, "k", p)) { (Ok(a), Ok(b)) => { let at = format!("{name} {reduction} on {stem}"); @@ -1135,20 +1057,18 @@ const OP_SWITCH: u16 = 251; /// the sample needs `maintenance8`. Without `shaderImageGatherExtended` (the floor) a dynamic gather /// offset is taken as `ConstOffset` arms: one switch on its dynamic lane's low four bits, 16 gathers /// each with a `ConstOffset` and none with `Offset`, and the module needs neither feature. A -/// runtime sampler's gather reads the offset a second time for its snap behind -/// the word, which moves the centre back where Metal drops it, on a device without Metal's own -/// sampler (lavapipe). On one with it (MoltenVK) only a pixel word's gather snaps, and Metal's own -/// sampler drops the offset of the normalized centre it is handed where Metal drops the pixel -/// coordinate's, so the snap moves nothing by the offset and reads it once. +/// runtime sampler's gather snaps a pixel word's coordinate behind the word and moves nothing by +/// the offset, which the device's sampler places, so it reads the offset once on every device +/// (lavapipe, MoltenVK). #[test] fn dynamic_offsets_are_offset_operands_of_their_low_four_bits() { let Some(bc) = assemble("gather_dynamic_offset", &dynamic_offset_kernel(true)) else { return; }; - let lavapipe = profile("lavapipe", EXACT_SAMPLING).expect("profile"); + let lavapipe = profile("lavapipe", DevicePolicy::default()).expect("profile"); let a = ok(&bc, "k", &lavapipe); assert_eq!(operand_masks(&a, OP_IMAGE_GATHER, 6), [MASK_OFFSET]); - assert_eq!(sign_extracts(&a), 2); + assert_eq!(sign_extracts(&a), 1); let p = m3(); let a = ok(&bc, "k", &p); assert_eq!(uses(&a, "sampler.gather"), 1); @@ -1159,7 +1079,7 @@ fn dynamic_offsets_are_offset_operands_of_their_low_four_bits() { .features .contains(&VkFeature::ShaderImageGatherExtended)); assert!(!a.requirements.features.contains(&VkFeature::Maintenance8)); - let floor = profile("vk12-floor", EXACT_SAMPLING).expect("profile"); + let floor = profile("vk12-floor", DevicePolicy::default()).expect("profile"); let a = ok(&bc, "k", &floor); assert_eq!(count(&a, OP_SWITCH), 1); assert_eq!( @@ -1193,7 +1113,7 @@ fn m3_with(edit: impl FnOnce(&mut crate::device::profile::Limits)) -> DeviceProf let text = std::fs::read_to_string(path).expect("profile"); let mut desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); edit(&mut desc.limits); - Device::new(desc, EXACT_SAMPLING) + Device::new(desc, DevicePolicy::default()) .expect("device") .profile() .clone() diff --git a/crates/metal2vulkan/src/tests/engine_sampler_fetched.rs b/crates/metal2vulkan/src/tests/engine_sampler_fetched.rs deleted file mode 100644 index 8b9a7fbd8..000000000 --- a/crates/metal2vulkan/src/tests/engine_sampler_fetched.rs +++ /dev/null @@ -1,648 +0,0 @@ -//! A plain gather's or nearest sample's `float` texels, fetched by the shader where Metal's -//! footprint and level are known (`lower::sampler:: fetched`), and -//! `PrecisionNote::DeviceTexelDenormals` where the device reads them. -//! -//! A device's sample or gather may read a denormal 32-bit float texel as zero (RADV, NVIDIA and -//! ANV); its `OpImageFetch` keeps it. The selection tests pin which samples and -//! gathers fetch on every committed profile, and which record the note. The interpreter runs the -//! fetches of an `R32Float` texture whose texels include denormals and signed zeros: every lane -//! is the texel Metal reads, bit for bit. (The interpreter models no device sample or gather, so -//! the other arm is not run.) -//! -//! `llvm-as` assembles the kernels; without it the tests skip visibly. - -use std::collections::BTreeMap; -use std::sync::atomic::{AtomicU64, Ordering}; - -use crate::bind::SamplerDescriptor; -use crate::device::requirements::VkProperty; -use crate::metal::sampler::SamplerWord; -use crate::metal::texel_format::texel_format; -use crate::metal::PixelFormat; -use crate::pipeline::sym::{Axis, ResourceKind, ResourceSlot, SpecKey, Stage}; -use crate::pipeline::testing::EXACT_SAMPLING; -use crate::pipeline::testing::{ - compile, link_and_validate, llvm_assemble, profile, typed_module, AssembleError, -}; -use crate::pipeline::PrecisionNote; -use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Order, Resources}; -use crate::spirv::ir::{GlobalKind, TypedModule}; - -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"; - -/// Bitcode of the module `body` (after the AIR header), or `None` without `llvm-as`. -fn assemble(name: &str, body: &str) -> Option> { - static NEXT: AtomicU64 = AtomicU64::new(0); - let dir = std::env::temp_dir().join(format!( - "m2v-sampler-fetched-{}-{}", - std::process::id(), - NEXT.fetch_add(1, Ordering::Relaxed), - )); - std::fs::create_dir_all(&dir).expect("scratch"); - let ll = dir.join("k.ll"); - std::fs::write(&ll, format!("{HEADER}{body}")).expect("write"); - let r = llvm_assemble(&ll); - let _ = std::fs::remove_dir_all(&dir); - match r { - Ok(x) => Some(x), - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - None - } - Err(AssembleError::Rejected(why)) => panic!("{name}: {why}"), - } -} - -/// The words of a constexpr sampler: minification and magnification `filter` (AIR code: 0 -/// nearest, 1 linear), mip filter `mip` (0 none, 1 nearest, 2 linear), every axis addressed by -/// `address` (0 zero or border, 1 edge, 2 repeat, 3 mirrored repeat), and border color code -/// `border`, with the fields Apple's compiler writes for the rest (as `engine_linear_half`'s). -fn sampler_words(filter: u64, mip: u64, address: u64, border: u64) -> u64 { - const BASE: u64 = 0x007b_ff00_0008_0000; - BASE | address - | address << 3 - | address << 6 - | filter << 9 - | filter << 11 - | mip << 13 - | border << 56 -} - -/// A nearest, clamp-to-edge sampler without a mip filter. -const NEAREST: u64 = 0x007b_ff00_0008_0000 | 1 | 1 << 3 | 1 << 6; - -/// How a test kernel reads texture slot 0 at buffer 0's lane `tid` (a `float4`: the coordinate -/// in `x`, `y` (and `z` for a 3D texture), and a level in `w`). -#[derive(Clone, Copy, Debug)] -enum Read { - /// `texture2d::gather(s, uv, int2(0), component)`. - Gather { component: u32 }, - /// `texture2d::sample(s, uv)`, at bias 0. - Sample, - /// `texture2d::sample(s, uv, level(w))`. - Level, - /// `texture2d::sample(s, uv, level(2))`. - ConstLevel, - /// `texture2d::sample(s, uv, min_lod_clamp(1))`. - MinLodClamp, - /// `texture2d_array::sample(s, uv, 1)`. - Array, - /// `texture1d::sample(s, u)`. - OneD, - /// `texture3d::sample(s, uvw)`. - ThreeD, - /// `depth2d::sample(s, uv)`. - Depth, - /// `texture2d::sample(s, uv)`. - Half, -} - -/// A kernel reading texture slot 0 through the constexpr sampler of `words` as `read` says, -/// storing the `float4` (a `half4` for [`Read::Half`]; a depth sample's in `x`) to buffer 1. -fn kernel(words: u64, read: Read) -> String { - let uv = "%uv = shufflevector <4 x float> %c4, <4 x float> zeroinitializer, <2 x i32> "; - let s = "ptr addrspace(1) %t, ptr addrspace(2) @__air_sampler_state"; - let sample2 = - "ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32"; - let (tex_ty, ty, call, decl, store_ty, size) = match read { - Read::Gather { component } => ( - "texture2d", - "<4 x float>", - format!("{uv}\n %r = call {{ <4 x float>, i8 }} @air.gather_texture_2d.v4f32({s}, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i32 {component}, i32 0)"), - "declare { <4 x float>, i8 } @air.gather_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i32, i32)".to_string(), - "<4 x float>", - 16, - ), - Read::Sample | Read::Level | Read::ConstLevel | Read::MinLodClamp => { - let (level, lod, min) = match read { - Read::Level => ("true", "%lod", "0.0"), - Read::ConstLevel => ("true", "2.0", "0.0"), - Read::MinLodClamp => ("false", "0.0", "1.0"), - _ => ("false", "0.0", "0.0"), - }; - ( - "texture2d", - "<4 x float>", - format!("{uv}\n %r = call {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32({s}, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 {level}, float {lod}, float {min}, i32 0)"), - format!("declare {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32({sample2})"), - "<4 x float>", - 16, - ) - } - Read::Array => ( - "texture2d_array", - "<4 x float>", - format!("{uv}\n %r = call {{ <4 x float>, i8 }} @air.sample_texture_2d_array.v4f32({s}, <2 x float> %uv, i32 1, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.0, float 0.0, i32 0)"), - "declare { <4 x float>, i8 } @air.sample_texture_2d_array.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x float>, i32, i1, <2 x i32>, i1, float, float, i32)".to_string(), - "<4 x float>", - 16, - ), - Read::OneD => ( - "texture1d", - "<4 x float>", - format!("%u = extractelement <4 x float> %c4, i64 0\n %r = call {{ <4 x float>, i8 }} @air.sample_texture_1d.v4f32({s}, float %u, i1 false, i32 0, i1 false, float 0.0, float 0.0, i32 0)"), - "declare { <4 x float>, i8 } @air.sample_texture_1d.v4f32(ptr addrspace(1), ptr addrspace(2), float, i1, i32, i1, float, float, i32)".to_string(), - "<4 x float>", - 16, - ), - Read::ThreeD => ( - "texture3d", - "<4 x float>", - format!("%uvw = shufflevector <4 x float> %c4, <4 x float> zeroinitializer, <3 x i32> \n %r = call {{ <4 x float>, i8 }} @air.sample_texture_3d.v4f32({s}, <3 x float> %uvw, i1 true, <3 x i32> zeroinitializer, i1 false, float 0.0, float 0.0, i32 0)"), - "declare { <4 x float>, i8 } @air.sample_texture_3d.v4f32(ptr addrspace(1), ptr addrspace(2), <3 x float>, i1, <3 x i32>, i1, float, float, i32)".to_string(), - "<4 x float>", - 16, - ), - Read::Depth => ( - "depth2d", - "float", - format!("{uv}\n %r = call {{ float, i8 }} @air.sample_depth_2d.f32({s}, i32 1, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.0, float 0.0, i32 0)"), - "declare { float, i8 } @air.sample_depth_2d.f32(ptr addrspace(1), ptr addrspace(2), i32, <2 x float>, i1, <2 x i32>, i1, float, float, i32)".to_string(), - "<4 x float>", - 16, - ), - Read::Half => ( - "texture2d", - "<4 x half>", - format!("{uv}\n %r = call {{ <4 x half>, i8 }} @air.sample_texture_2d.v4f16({s}, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.0, float 0.0, i32 0)"), - "declare { <4 x half>, i8 } @air.sample_texture_2d.v4f16(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32)".to_string(), - "<4 x half>", - 8, - ), - }; - let value = match read { - Read::Depth => "%d = extractvalue { float, i8 } %r, 0\n %v = insertelement <4 x float> zeroinitializer, float %d, i64 0".to_string(), - _ => format!("%v = extractvalue {{ {ty}, i8 }} %r, 0"), - }; - let out_name = if size == 8 { "half4" } else { "float4" }; - format!( - r#"@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 {words}, i64 0], align 8 - -define void @k(ptr addrspace(1) %t, ptr addrspace(1) %c, ptr addrspace(1) %out, i32 %tid) {{ - %i = zext i32 %tid to i64 - %p = getelementptr inbounds <4 x float>, ptr addrspace(1) %c, i64 %i - %c4 = load <4 x float>, ptr addrspace(1) %p, align 16 - %lod = extractelement <4 x float> %c4, i64 3 - {call} - {value} - %q = getelementptr inbounds {store_ty}, ptr addrspace(1) %out, i64 %i - store {store_ty} %v, ptr addrspace(1) %q, align {size} - ret void -}} - -{decl} - -!air.kernel = !{{!0}} -!air.sampler_states = !{{!6}} -!0 = !{{ptr @k, !1, !2}} -!1 = !{{}} -!2 = !{{!3, !4, !5, !7}} -!3 = !{{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"{tex_ty}", !"air.arg_name", !"t"}} -!4 = !{{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"c"}} -!5 = !{{i32 2, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 {size}, !"air.arg_type_align_size", i32 {size}, !"air.arg_type_name", !"{out_name}", !"air.arg_name", !"out"}} -!6 = !{{!"air.sampler_state", ptr addrspace(2) @__air_sampler_state}} -!7 = !{{i32 3, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"tid"}} -"# - ) -} - -/// [`kernel`]'s kernel reading texture slot 0 through runtime sampler slot 0 (parameter `s`) -/// instead of a constexpr sampler. -fn runtime_kernel(read: Read) -> String { - let text = kernel(NEAREST, read); - let mut out: String = text - .lines() - .filter(|l| !l.starts_with("@__air_sampler_state") && *l != "!air.sampler_states = !{!6}") - .map(|l| format!("{l}\n")) - .collect(); - for (from, to) in [ - ( - "!6 = !{!\"air.sampler_state\", ptr addrspace(2) @__air_sampler_state}", - "!6 = !{i32 3, !\"air.sampler\", !\"air.location_index\", i32 0, i32 1, !\"air.arg_type_name\", !\"sampler\", !\"air.arg_name\", !\"s\"}", - ), - ("ptr addrspace(2) @__air_sampler_state", "ptr addrspace(2) %s"), - ( - "ptr addrspace(1) %out, i32 %tid)", - "ptr addrspace(1) %out, ptr addrspace(2) %s, i32 %tid)", - ), - ("!2 = !{!3, !4, !5, !7}", "!2 = !{!3, !4, !5, !6, !7}"), - ( - "!7 = !{i32 3, !\"air.thread_position_in_grid\"", - "!7 = !{i32 4, !\"air.thread_position_in_grid\"", - ), - ] { - assert!(out.contains(from), "{read:?}: no {from}"); - out = out.replace(from, to); - } - out -} - -/// The opcodes of a SPIR-V module's instructions. -fn opcodes(words: &[u32]) -> Vec { - let mut out = Vec::new(); - let mut i = 5; - while i < words.len() { - out.push((words[i] & 0xffff) as u16); - i += ((words[i] >> 16) as usize).max(1); - } - out -} - -/// `OpImageFetch`. -const FETCH: u16 = 95; - -/// `OpImageSampleImplicitLod`, `OpImageSampleExplicitLod`, and `OpImageGather`. -const DEVICE_READS: [u16; 3] = [87, 88, 96]; - -/// A plain gather, and a sample through a nearest sampler at a level the function knows (no mip -/// filter, a nearest mip filter's constant or kernel level), of a 1D, 2D, 2D array or 3D texture -/// slot or a depth texture, through a constexpr sampler, fetches its texels behind the slot's -/// `TexelFormat` specialization on every committed profile without `VkProperty::MetalSampler`, -/// beside the device's read for the other formats, and records no `DeviceTexelDenormals`. On a -/// profile with the property Metal's own sampler reads them, with no fetch. Each validates. -#[test] -fn plain_gathers_and_nearest_samples_fetch_their_float_texels() { - let mip_nearest = sampler_words(0, 1, 1, 0); - let cases = [ - (NEAREST, Read::Gather { component: 0 }), - (sampler_words(1, 2, 2, 0), Read::Gather { component: 2 }), - (sampler_words(0, 0, 0, 2), Read::Gather { component: 1 }), - (NEAREST, Read::Sample), - (sampler_words(0, 0, 3, 0), Read::Sample), - (mip_nearest, Read::Level), - (mip_nearest, Read::ConstLevel), - (NEAREST, Read::Array), - (NEAREST, Read::OneD), - (sampler_words(0, 0, 2, 0), Read::ThreeD), - (NEAREST, Read::Depth), - ]; - let profiles = crate::spirv::testing::committed_exact_profiles().expect("profiles"); - for (words, read) in cases { - let name = format!("{read:?} through {words:#x}"); - let Some(bc) = assemble(&name, &kernel(words, read)) else { - return; - }; - for (stem, p) in &profiles { - let what = format!("{name} on {stem}"); - let a = compile(&bc, "k", p).unwrap_or_else(|e| panic!("{what}: {e}")); - link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: {e}")); - let metal = p - .fields() - .enabled - .properties - .contains(&VkProperty::MetalSampler); - let ops = opcodes(&a.module.words); - let fetches = ops.contains(&FETCH); - let device = ops.iter().any(|o| DEVICE_READS.contains(o)); - let format = a - .interface - .read_keys() - .into_iter() - .any(|k| matches!(k, SpecKey::TexelFormat(_))); - assert_eq!((fetches, device, format), (!metal, true, !metal), "{what}"); - assert!( - !a.precision.contains(&PrecisionNote::DeviceTexelDenormals), - "{what}" - ); - } - } -} - -/// A `float` sample whose texels the device reads records `DeviceTexelDenormals` on every committed -/// profile without `VkProperty::MetalSampler`: a filtered sample no emulation reaches (a linear mip -/// filter), and a nearest one under a nearest mip filter with a `min_lod_clamp`, whose level the -/// function does not know. A linear sample the emulation reaches fetches its texels and records -/// none, and so does a `half` result, which holds no 32-bit denormal. A profile with the property -/// records none. -#[test] -fn device_reads_of_float_texels_record_the_note() { - let cases = [ - (sampler_words(1, 2, 1, 0), Read::Sample, true), - (sampler_words(0, 1, 1, 0), Read::MinLodClamp, true), - (sampler_words(1, 0, 1, 0), Read::Sample, false), - (NEAREST, Read::Half, false), - ]; - let profiles = crate::spirv::testing::committed_exact_profiles().expect("profiles"); - for (words, read, noted) in cases { - let name = format!("{read:?} through {words:#x}"); - let Some(bc) = assemble(&name, &kernel(words, read)) else { - return; - }; - for (stem, p) in &profiles { - let what = format!("{name} on {stem}"); - let a = compile(&bc, "k", p).unwrap_or_else(|e| panic!("{what}: {e}")); - let metal = p - .fields() - .enabled - .properties - .contains(&VkProperty::MetalSampler); - assert_eq!( - a.precision.contains(&PrecisionNote::DeviceTexelDenormals), - noted && !metal, - "{what}" - ); - } - } -} - -/// The texels of a 4x4 `R32Float` texture: denormals of both signs, signed zeros, the smallest -/// normal, and ordinary values. -const TEXELS: [u32; 16] = [ - 0x0000_0001, - 0x8000_0002, - 0x007f_ffff, - 0x807f_ffff, - 0x0040_0000, - 0x8000_0000, - 0x0000_0000, - 0x0080_0000, - 0x3f80_0000, - 0xbf00_0000, - 0x0012_3456, - 0x8065_4321, - 0x4120_0000, - 0x0000_0100, - 0x8000_0001, - 0x3e80_0000, -]; - -/// The combined image-sampler binding a module declares for texture slot 0. -fn combined_slot(m: &TypedModule) -> ResourceSlot { - m.globals() - .iter() - .find_map(|g| match g.kind { - GlobalKind::Resource( - s @ ResourceSlot { - kind: ResourceKind::CombinedTextureSampler(_), - .. - }, - ) => Some(s), - _ => None, - }) - .expect("a combined binding") -} - -/// Buffer 1's `float4`s, as bits, after `bc` runs one thread per coordinate of `points` (buffer -/// 0's `float4`s) on lavapipe's profile with the [`TEXELS`] texture bound and its -/// `TexelFormat` specialization `R32Float`'s. -fn run(name: &str, bc: &[u8], points: &[[f32; 4]]) -> Vec<[u32; 4]> { - let p = profile("lavapipe", EXACT_SAMPLING).expect("profile"); - let a = compile(bc, "k", &p).expect("compile"); - // The note holds nowhere, or (a runtime sampler's sample) only where the word filters. - let note = PrecisionNote::DeviceTexelDenormals; - assert!( - !a.precision.contains(¬e) || a.specialized.iter().any(|n| n.note == note), - "{name}" - ); - let (plan, m) = typed_module(bc, "k", &p).expect("typed module"); - let slot = combined_slot(&m); - let mut image = Image::new(slot, [4, 4, 1], 1, 1, 1); - for y in 0..4u32 { - for x in 0..4u32 { - let at = image.index(0, 0, 0, [x, y, 0]).expect("texel"); - image.texels[at] = [TEXELS[(4 * y + x) as usize], 0, 0, 1f32.to_bits()]; - } - } - let mut spec = BTreeMap::new(); - for axis in [Axis::X, Axis::Y, Axis::Z] { - spec.insert(SpecKey::LocalSize(axis), 1); - } - spec.insert(SpecKey::FlatLocalSize, 1); - let texture = a - .interface - .read_keys() - .into_iter() - .find_map(|k| match k { - k @ SpecKey::TexelFormat(_) => Some(k), - _ => None, - }) - .expect("the texture slot's `TexelFormat` specialization"); - spec.insert(texture, u64::from(texel_format(PixelFormat::R32Float).0)); - // A runtime sampler slot's word: `MTLSamplerDescriptor`'s defaults (nearest filters, no mip - // filter, clamped to the edge, normalized coordinates), masked by the fields the function - // reads. - for k in a.interface.read_keys() { - if let SpecKey::SamplerState { fields, .. } = k { - let word = SamplerWord::of(&SamplerDescriptor::new()).0 & fields; - spec.insert(k, u64::from(word)); - } - } - let coords: Vec = points - .iter() - .flat_map(|c| c.iter().flat_map(|v| v.to_le_bytes())) - .collect(); - let buffers = [coords, vec![0xab; 16 * points.len()]] - .into_iter() - .enumerate() - .map(|(i, bytes)| Buffer { - slot: Some(ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: i as u32, - }), - address: None, - bytes, - }) - .collect(); - let res = Resources { - buffers, - push: vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)], - spec, - }; - let mut outs = Vec::new(); - for order in [Order::Forward, Order::Reverse] { - let cfg = Config { - workgroups: [points.len() as u32, 1, 1], - order, - ..Config::default() - }; - let (o, _) = run_with_images(&m, &cfg, res.clone(), vec![image.clone()]) - .unwrap_or_else(|e| panic!("{name}: interpreter: {e:?}")); - outs.push(o.buffers); - } - assert_eq!(outs[0], outs[1], "{name}: the scheduling orders disagree"); - outs[0][1] - .as_chunks::<16>() - .0 - .iter() - .map(|c| { - std::array::from_fn(|k| { - u32::from_le_bytes([c[4 * k], c[4 * k + 1], c[4 * k + 2], c[4 * k + 3]]) - }) - }) - .collect() -} - -/// On the interpreter: a gather at each interior texel corner reads Metal's 2x2 footprint, `x` `(i, -/// j + 1)`, `y` `(i + 1, j + 1)`, `z` `(i + 1, j)` and `w` `(i, j)`, and a nearest sample at each -/// texel centre that texel, every denormal and signed zero kept, through the fetches the `R32Float` -/// specialization selects. -#[test] -fn fetched_float_texels_keep_their_denormals() { - let texel = |x: u32, y: u32| TEXELS[(4 * y + x) as usize]; - let Some(gather) = assemble("gather", &kernel(NEAREST, Read::Gather { component: 0 })) else { - return; - }; - let corners: Vec<(u32, u32)> = (0..3).flat_map(|j| (0..3).map(move |i| (i, j))).collect(); - let points: Vec<[f32; 4]> = corners - .iter() - .map(|&(i, j)| [(i + 1) as f32 / 4.0, (j + 1) as f32 / 4.0, 0.0, 0.0]) - .collect(); - for ((i, j), got) in corners.iter().zip(run("gather", &gather, &points)) { - let want = [ - texel(*i, j + 1), - texel(i + 1, j + 1), - texel(i + 1, *j), - texel(*i, *j), - ]; - assert_eq!(got, want, "gather at corner ({i}, {j})"); - } - let Some(sample) = assemble("sample", &kernel(NEAREST, Read::Sample)) else { - return; - }; - let centres: Vec<(u32, u32)> = (0..4).flat_map(|y| (0..4).map(move |x| (x, y))).collect(); - let points: Vec<[f32; 4]> = centres - .iter() - .map(|&(x, y)| [(x as f32 + 0.5) / 4.0, (y as f32 + 0.5) / 4.0, 0.0, 0.0]) - .collect(); - for ((x, y), got) in centres.iter().zip(run("sample", &sample, &points)) { - assert_eq!( - got, - [texel(*x, *y), 0, 0, 1f32.to_bits()], - "sample at ({x}, {y})" - ); - } -} - -/// A plain gather, and a sample of a 1D, 2D, 2D array or 3D texture slot or a depth texture, -/// through a runtime sampler slot fetches its texels addressed by the slot's word -/// (`fetched::FetchAddress::Word`), behind the slot's `TexelFormat` specialization, on every -/// committed profile without `VkProperty::MetalSampler`, beside the device's read; the word -/// carries the coordinates, the plane axes' address modes and the border color, a sample's its -/// filter, and a stated level's its mip filter and level clamp. A sample fetches only where the -/// word states one texel (`fetched::word_reach`), so `DeviceTexelDenormals` holds only under the -/// specializations where the word filters (and, without a stated level, has a mip filter); a -/// gather's taps are fetched whatever the word's filters, so it records none. A profile with the -/// property reads them by Metal's own sampler. Each validates. -#[test] -fn runtime_sampler_gathers_and_nearest_samples_fetch_by_their_word() { - let cases = [ - Read::Gather { component: 0 }, - Read::Gather { component: 3 }, - Read::Sample, - Read::Level, - Read::MinLodClamp, - Read::Array, - Read::OneD, - Read::ThreeD, - Read::Depth, - ]; - let profiles = crate::spirv::testing::committed_exact_profiles().expect("profiles"); - for read in cases { - let name = format!("{read:?} through a runtime sampler"); - let Some(bc) = assemble(&name, &runtime_kernel(read)) else { - return; - }; - let gather = matches!(read, Read::Gather { .. }); - for (stem, p) in &profiles { - let what = format!("{name} on {stem}"); - let a = compile(&bc, "k", p).unwrap_or_else(|e| panic!("{what}: {e}")); - link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: {e}")); - let metal = p - .fields() - .enabled - .properties - .contains(&VkProperty::MetalSampler); - let ops = opcodes(&a.module.words); - let fetches = ops.contains(&FETCH); - let device = ops.iter().any(|o| DEVICE_READS.contains(o)); - let format = a - .interface - .read_keys() - .into_iter() - .any(|k| matches!(k, SpecKey::TexelFormat(_))); - assert_eq!((fetches, device, format), (!metal, true, !metal), "{what}"); - // A specialized note is among the module's notes. - let noted = a.precision.contains(&PrecisionNote::DeviceTexelDenormals); - let specialized = a - .specialized - .iter() - .any(|n| n.note == PrecisionNote::DeviceTexelDenormals); - assert_eq!( - (noted, specialized), - (!metal && !gather, !metal && !gather), - "{what}" - ); - if metal { - continue; - } - let fields = a - .interface - .read_keys() - .into_iter() - .find_map(|k| match k { - SpecKey::SamplerState { fields, .. } => Some(fields), - _ => None, - }) - .unwrap_or_else(|| panic!("{what}: no sampler word")); - let mut want = SamplerWord::PIXEL_COORDINATES - | SamplerWord::ADDRESS[0] - | SamplerWord::ADDRESS[1] - | SamplerWord::BORDER; - if !gather { - want |= SamplerWord::LINEAR_FILTER; - } - if matches!(read, Read::ThreeD) { - want |= SamplerWord::ADDRESS[2]; - } - if matches!(read, Read::Level) { - want |= SamplerWord::LEVEL_MIN | SamplerWord::LEVEL_MAX; - } - assert_eq!(fields & want, want, "{what}: word fields {fields:#x}"); - } - } -} - -/// On the interpreter: through a runtime sampler slot whose word states `MTLSamplerDescriptor`'s -/// defaults (nearest, no mip filter, clamped to the edge), a gather at each interior texel corner -/// reads Metal's 2x2 footprint and a sample at each texel centre that texel, every denormal and -/// signed zero kept, through the fetches the word addresses. -#[test] -fn runtime_sampler_fetches_keep_their_denormals() { - let texel = |x: u32, y: u32| TEXELS[(4 * y + x) as usize]; - let Some(gather) = assemble( - "runtime gather", - &runtime_kernel(Read::Gather { component: 0 }), - ) else { - return; - }; - let corners: Vec<(u32, u32)> = (0..3).flat_map(|j| (0..3).map(move |i| (i, j))).collect(); - let points: Vec<[f32; 4]> = corners - .iter() - .map(|&(i, j)| [(i + 1) as f32 / 4.0, (j + 1) as f32 / 4.0, 0.0, 0.0]) - .collect(); - for ((i, j), got) in corners.iter().zip(run("runtime gather", &gather, &points)) { - let want = [ - texel(*i, j + 1), - texel(i + 1, j + 1), - texel(i + 1, *j), - texel(*i, *j), - ]; - assert_eq!(got, want, "gather at corner ({i}, {j})"); - } - let Some(sample) = assemble("runtime sample", &runtime_kernel(Read::Sample)) else { - return; - }; - let centres: Vec<(u32, u32)> = (0..4).flat_map(|y| (0..4).map(move |x| (x, y))).collect(); - let points: Vec<[f32; 4]> = centres - .iter() - .map(|&(x, y)| [(x as f32 + 0.5) / 4.0, (y as f32 + 0.5) / 4.0, 0.0, 0.0]) - .collect(); - for ((x, y), got) in centres.iter().zip(run("runtime sample", &sample, &points)) { - assert_eq!( - got, - [texel(*x, *y), 0, 0, 1f32.to_bits()], - "sample at ({x}, {y})" - ); - } -} diff --git a/crates/metal2vulkan/src/tests/engine_sampler_unk.rs b/crates/metal2vulkan/src/tests/engine_sampler_unk.rs index 558a6bb2a..59342dd61 100644 --- a/crates/metal2vulkan/src/tests/engine_sampler_unk.rs +++ b/crates/metal2vulkan/src/tests/engine_sampler_unk.rs @@ -6,14 +6,10 @@ //! //! - gradient samples of 3D, cube, and cube array textures and of depth 2D, 2D array, cube, and //! cube array textures, with and without comparison, are explicit-LOD samples with the `Grad` -//! operand (a comparison's with its reference, but a depth 2D or 2D array texture's through a -//! nearest sampler on a device without `VkProperty::MetalSampler`, which the shader compares); a -//! depth cube array's sample and a depth cube and cube array's comparison at level 0 are +//! operand (a comparison's with its reference); a depth cube array's sample and a depth cube and cube array's comparison at level 0 are //! explicit-LOD samples with the `Lod` operand; //! - gathers of cube and cube array textures read their component, depth gathers component 0, and -//! comparison gathers are `OpImageDrefGather`, none with an offset (a cube takes none), except a -//! depth 2D or 2D array texture's on a device without `VkProperty::MetalSampler`, which reads -//! component 0 for the shader to compare; +//! comparison gathers are `OpImageDrefGather`, none with an offset (a cube takes none); //! - the clamped and unclamped LOD queries of 2D array, 3D, cube, and cube array textures and of //! depth 2D, 2D array, cube, and cube array textures are `OpImageQueryLod`; //! - a cube's explicit gradients take Metal's footprint (`sampler.sample_cube_grad`, with @@ -30,16 +26,16 @@ use std::sync::atomic::{AtomicU64, Ordering}; use crate::device::profile::{CubeGradientRoute, DeviceProfile}; -use crate::device::requirements::{VkFeature, VkProperty}; +use crate::device::requirements::VkFeature; +use crate::device::DevicePolicy; use crate::device::{Device, DeviceDescription}; use crate::error::{Error, Needs}; use crate::library::FunctionArtifact; -use crate::pipeline::testing::EXACT_SAMPLING; use crate::pipeline::testing::{ compile, engine_dir, link_and_validate, llvm_assemble, AssembleError, }; use crate::pipeline::PrecisionNote; -use crate::spirv::testing::{committed_descriptions, committed_exact_profiles}; +use crate::spirv::testing::{committed_descriptions, committed_profiles}; const OP_EXT_INST: u16 = 12; const OP_CONSTANT: u16 = 43; @@ -110,7 +106,7 @@ fn unrobust(stem: &str) -> DeviceProfile { ] { desc.features.remove(&f); } - Device::new(desc, EXACT_SAMPLING) + Device::new(desc, DevicePolicy::default()) .expect("device") .profile() .clone() @@ -118,7 +114,7 @@ fn unrobust(stem: &str) -> DeviceProfile { /// Every committed profile, and `moltenvk-m3` and `lavapipe` without robustness. fn profiles() -> Vec<(String, DeviceProfile)> { - let mut out = committed_exact_profiles().expect("profiles"); + let mut out = committed_profiles().expect("profiles"); for stem in ["moltenvk-m3", "lavapipe"] { out.push((format!("{stem} unrobust"), unrobust(stem))); } @@ -191,25 +187,7 @@ fn each(name: &str, entry: &str, check: impl Fn(&str, &FunctionArtifact)) -> Opt #[test] fn gradient_and_level_samples_of_3d_cube_and_depth_textures() { - let metal: Vec = profiles() - .into_iter() - .filter(|(_, p)| { - p.fields() - .enabled - .properties - .contains(&VkProperty::MetalSampler) - }) - .map(|(stem, _)| stem) - .collect(); let Some((compiled, _)) = each("unk_sample_grad", "unk_sample_grad", |stem, a| { - // The depth 2D and 2D array gradient comparisons through the nearest sampler compare in - // the shader off `VkProperty::MetalSampler`: the device reads their texel by a plain - // gradient sample, as it would compare it, at the device's level. - let compared = if metal.iter().any(|m| m == stem) { - 0 - } else { - 2 - }; // A kernel samples nothing implicitly. for op in [ OP_IMAGE_SAMPLE_IMPLICIT_LOD, @@ -218,26 +196,23 @@ fn gradient_and_level_samples_of_3d_cube_and_depth_textures() { assert_eq!(count(a, op), 0, "{stem}: {op}"); } let lod = |m: &u32| m & (LOD | GRAD); - // Three color and four depth gradient samples, and the compared ones; the depth cube - // array's at level 0, twice. Off `VkProperty::MetalSampler` the color cube and cube - // array take Metal's level in the shader: each its one tap's two explicit levels. - let emulated = 2 * compared; + // Three color and four depth gradient samples; the depth cube array's at level 0, twice. let mut plain: Vec = masks(a, OP_IMAGE_SAMPLE_EXPLICIT_LOD, 5) .iter() .map(lod) .collect(); plain.sort(); - let mut expected = vec![LOD; 2 + emulated]; - expected.extend(vec![GRAD; 7 + compared - emulated / 2]); + let mut expected = vec![LOD; 2]; + expected.extend(vec![GRAD; 7]); assert_eq!(plain, expected, "{stem}"); - // Four gradient comparisons, less the compared ones, and two at level 0. + // Four gradient comparisons and two at level 0. let mut dref: Vec = masks(a, OP_IMAGE_SAMPLE_DREF_EXPLICIT_LOD, 6) .iter() .map(lod) .collect(); dref.sort(); let mut expected = vec![LOD, LOD]; - expected.extend(vec![GRAD; 4 - compared]); + expected.extend(vec![GRAD; 4]); assert_eq!(dref, expected, "{stem}"); }) else { return; @@ -247,23 +222,7 @@ fn gradient_and_level_samples_of_3d_cube_and_depth_textures() { #[test] fn cube_depth_and_comparison_gathers() { - let metal: Vec = profiles() - .into_iter() - .filter(|(_, p)| { - p.fields() - .enabled - .properties - .contains(&VkProperty::MetalSampler) - }) - .map(|(stem, _)| stem) - .collect(); let Some((compiled, _)) = each("unk_gather", "unk_gather", |stem, a| { - // The 2D and 2D array comparison gathers the shader compares. - let compared = if metal.iter().any(|m| m == stem) { - 0 - } else { - 2 - }; let words = &a.module.words; // The component operand is a constant id: its value. let constant = |id: u32| { @@ -280,11 +239,11 @@ fn cube_depth_and_comparison_gathers() { .collect(); let mut components: Vec = gathers.iter().map(|w| constant(w[5])).collect(); components.sort(); - // Cube x and w, cube array z, the two depth gathers' component 0, and the compared ones'. - let mut expected = vec![0; 3 + compared]; + // Cube x and w, cube array z, and the two depth gathers' component 0. + let mut expected = vec![0; 3]; expected.extend([2, 3]); assert_eq!(components, expected, "{stem}"); - assert_eq!(count(a, OP_IMAGE_DREF_GATHER), 4 - compared, "{stem}"); + assert_eq!(count(a, OP_IMAGE_DREF_GATHER), 4, "{stem}"); for (op, at) in [(OP_IMAGE_GATHER, 6), (OP_IMAGE_DREF_GATHER, 6)] { for m in masks(a, op, at) { assert_eq!(m & (CONST_OFFSET | OFFSET), 0, "{stem}: an offset on {op}"); @@ -320,33 +279,18 @@ fn glsl(a: &FunctionArtifact, number: u32) -> usize { /// Each of the fixture's six explicit cube gradient samples (color, depth, and comparison; cube and /// cube array) takes Metal's footprint: its gradients are Metal's length of the two tangent -/// components on one tangent (two `GLSL.std.450` `FMax` per gradient, no `Length`), or off -/// `VkProperty::MetalSampler` the color samples' Metal's level in the shader of the same lengths, -/// its census name is `sampler.sample_cube_grad`, and the module records `CubeGradientFootprint` -/// (for the depth and comparison samples, which the shader's level does not reach). The 3D and +/// components on one tangent (two `GLSL.std.450` `FMax` per gradient, no `Length`), its census +/// name is `sampler.sample_cube_grad`, and the module records `CubeGradientFootprint`. The 3D and /// depth 2D and 2D array gradient samples pass their gradients unchanged (`sampler.sample_grad`), -/// and a module whose gradients are all 2D records no such note. The depth samples without -/// comparison read through a sampler that filters nearest with no mip filter, so on a device -/// without `VkProperty::MetalSampler` their directions are snapped onto Metal's texel instead -/// (`sampler.cube.snapped`): the two gradient samples and the two at level 0. The 2D fixture's -/// gradient sample reads a runtime sampler, so on a device without the property the linear -/// emulation plans it (`sampler.linear`, its word selecting the device's sample). On a driver that +/// and a module whose gradients are all 2D (the 2D fixture's, through a runtime sampler) records no +/// such note. On a driver that /// hands a compute pipeline's cube gradients to Metal's `gradientcube` /// (`CubeGradientRoute::Metal`), the kernel hands Metal's own gradients, exactly: no note. #[test] fn explicit_cube_gradients_take_metals_footprint() { let handed = handed_metal(); let Some((compiled, _)) = each("unk_sample_grad", "unk_sample_grad", |stem, a| { - let snapped = match a - .requirements - .properties - .contains(&VkProperty::MetalSampler) - { - true => 0, - false => 2, - }; - assert_eq!(uses(a, "sampler.sample_cube_grad"), 6 - snapped, "{stem}"); - assert_eq!(uses(a, "sampler.cube.snapped"), 2 * snapped, "{stem}"); + assert_eq!(uses(a, "sampler.sample_cube_grad"), 6, "{stem}"); assert_eq!(uses(a, "sampler.sample_grad"), 5, "{stem}"); let metal = handed.iter().any(|m| m == stem); assert_eq!(glsl(a, GLSL_LENGTH), 0, "{stem}"); @@ -367,15 +311,7 @@ fn explicit_cube_gradients_take_metals_footprint() { assert!(!handed.is_empty(), "no profile hands Metal's gradients"); let Some((compiled, _)) = each("a4_sample_grad", "a4_sample_grad", |stem, a| { assert_eq!(uses(a, "sampler.sample_cube_grad"), 0, "{stem}"); - let census = match a - .requirements - .properties - .contains(&VkProperty::MetalSampler) - { - true => "sampler.sample_grad", - false => "sampler.linear", - }; - assert!(uses(a, census) > 0, "{stem}"); + assert!(uses(a, "sampler.sample_grad") > 0, "{stem}"); assert_eq!(glsl(a, GLSL_LENGTH), 0, "{stem}"); assert!( !a.precision.contains(&PrecisionNote::CubeGradientFootprint), @@ -394,13 +330,13 @@ const CUBE_GRAD_TEXTURES: usize = 2; /// An anisotropic constexpr sampler (`max_anisotropy(2)`, bits 20-23 of the state's first word) on /// a cube's explicit gradients takes Metal's footprint on every profile that compiles the isotropic -/// fixture, with `samplerAnisotropy` or without it (whose Vulkan sampler is isotropic, the taps -/// the emulation's). Off `VkProperty::MetalSampler` the shader takes Metal's level and taps: each -/// texture's routine, which its samples call, queries the level count and loops over its taps, -/// `AnisotropicFilter` is recorded and `CubeGradientFootprint` is not; through the isotropic -/// sampler, Metal's level and one tap: no loop, neither note. On a driver that hands a compute pipeline's cube gradients to -/// Metal's `gradientcube`, the kernel hands Metal's own through either sampler: no level query, no -/// note. Neither module has a `Length`. +/// fixture. Without `samplerAnisotropy`, whose Vulkan sampler is isotropic, the shader takes +/// Metal's level and taps: each texture's routine, which its samples call, queries the level count +/// and loops over its taps, `AnisotropicFilter` is recorded and `CubeGradientFootprint` is not; +/// with the feature, and through the isotropic sampler on every profile, the device's sample at +/// Metal's footprint: no loop, no level query, `CubeGradientFootprint` recorded. On a driver that +/// hands a compute pipeline's cube gradients to Metal's `gradientcube`, the kernel hands Metal's +/// own through either sampler: no note. Neither module has a `Length`. #[test] fn an_anisotropic_constexpr_sampler_takes_metals_cube_gradient_footprint() { let path = engine_dir().join("unk_cube_grad_lod.ll"); @@ -430,23 +366,15 @@ fn an_anisotropic_constexpr_sampler_takes_metals_cube_gradient_footprint() { continue; }; let metal = handed.contains(&stem); - let shader = !p - .fields() - .enabled - .properties - .contains(&VkProperty::MetalSampler); + let shader = !p.fields().images.sampler_anisotropy; assert_eq!(glsl(&i, GLSL_LENGTH), 0, "{stem}"); let samples = uses(&i, "sampler.sample_cube_grad") as usize; assert!(samples > 0, "{stem}"); - assert_eq!( - count(&i, OP_IMAGE_QUERY_LEVELS), - if shader { CUBE_GRAD_TEXTURES } else { 0 }, - "{stem}" - ); + assert_eq!(count(&i, OP_IMAGE_QUERY_LEVELS), 0, "{stem}"); assert_eq!(count(&i, OP_LOOP_MERGE), 0, "{stem}"); assert_eq!( i.precision.contains(&PrecisionNote::CubeGradientFootprint), - !metal && !shader, + !metal, "{stem}" ); assert!( @@ -518,7 +446,7 @@ fn an_unmeasured_cube_gradient_route_takes_metals_footprint_in_the_shader() { let measured = DeviceDescription::from_khronos_json(&profile_text, None).expect("description"); let profile = |d: DeviceDescription, taken: bool| { let route = DriverDeviation::CubeGradientRoute; - Device::with_deviation(d, EXACT_SAMPLING, route, taken) + Device::with_deviation(d, DevicePolicy::default(), route, taken) .expect("device") .profile() .clone() @@ -589,7 +517,7 @@ fn the_graphics_cube_route_is_measured_per_macos_identity() { else { return; }; - let all = committed_exact_profiles().expect("profiles"); + let all = committed_profiles().expect("profiles"); let of = |stem: &str| { all.iter() .find(|(s, _)| s == stem) @@ -605,7 +533,7 @@ fn the_graphics_cube_route_is_measured_per_macos_identity() { .expect("moltenvk-m3"); let mut m3_macos26 = m3_macos27.clone(); m3_macos26.device_id = crate::device::driver_facts::APPLE_M3_MAX; - let m3 = Device::new(m3_macos26, EXACT_SAMPLING) + let m3 = Device::new(m3_macos26, DevicePolicy::default()) .expect("device") .profile() .clone(); @@ -624,7 +552,7 @@ fn the_graphics_cube_route_is_measured_per_macos_identity() { (CubeGradientRoute::AppleProjected, CubeGradientRoute::Metal) ); let tangents = DriverDeviation::GraphicsCubeGradientTangents; - let unmeasured = Device::with_deviation(m3_macos27, EXACT_SAMPLING, tangents, false) + let unmeasured = Device::with_deviation(m3_macos27, DevicePolicy::default(), tangents, false) .expect("device") .profile() .clone(); @@ -716,7 +644,7 @@ fn a_runtime_samplers_cube_gradients_take_their_footprint_by_its_word() { let unmeasured = DeviceDescription::from_khronos_json(&profile_text, None).expect("description"); let route = crate::error::DriverDeviation::CubeGradientRoute; - let unmeasured = Device::with_deviation(unmeasured, EXACT_SAMPLING, route, false) + let unmeasured = Device::with_deviation(unmeasured, DevicePolicy::default(), route, false) .expect("device") .profile() .clone(); diff --git a/crates/metal2vulkan/src/tests/engine_separate_samplers.rs b/crates/metal2vulkan/src/tests/engine_separate_samplers.rs index b089b9b7e..5a39300b1 100644 --- a/crates/metal2vulkan/src/tests/engine_separate_samplers.rs +++ b/crates/metal2vulkan/src/tests/engine_separate_samplers.rs @@ -169,9 +169,7 @@ fn the_stage_takes_its_combined_bindings_apart_past_the_sampler_limit() { runtime, "{what}: {separate:?}" ); - // One sampled image per pair: its sample's, or where Metal's linear filter is - // emulated, or a plain sample's texels are fetched, the device sample's in the shared - // emulation's dispatch, whose facts and taps read the texture alone (SEMANTICS 1012). + // One sampled image per pair: its sample's. let made = count(&a, OP_SAMPLED_IMAGE); assert_eq!(made, 32, "{what}"); assert_eq!(uses(&a, "sampler.separate_binding"), made as u32, "{what}"); diff --git a/crates/metal2vulkan/src/tests/engine_shared_switch.rs b/crates/metal2vulkan/src/tests/engine_shared_switch.rs index 474d478d8..933a1d803 100644 --- a/crates/metal2vulkan/src/tests/engine_shared_switch.rs +++ b/crates/metal2vulkan/src/tests/engine_shared_switch.rs @@ -1,7 +1,6 @@ //! A switch-at-use whose every arm takes the same emulation emulates once (SEMANTICS 1012): a //! kernel samples one element of an array of `n` textures, chosen per lane, through one constexpr -//! sampler whose sampling the translation emulates on a profile without `metalSampler` (lavapipe): -//! Metal's linear filter, Metal's bicubic filter, or a snapped gather or nearest sample. +//! sampler whose sampling the translation emulates on lavapipe: Metal's bicubic filter. //! //! - **The words do not scale with arms × emulation.** Each arm adds the same words whatever the //! emulation's size (a repeating sampler's position against a pixel sampler's none), and less @@ -18,15 +17,14 @@ use std::collections::BTreeMap; use std::sync::atomic::{AtomicU64, Ordering}; use crate::device::profile::DeviceProfile; +use crate::device::DevicePolicy; use crate::lower::select::Plan; use crate::metal::bicubic::BicubicTexels; -use crate::metal::texel_format::texel_format; use crate::metal::PixelFormat; use crate::pipeline::interface::PushLoc; use crate::pipeline::sym::{ Axis, PushField, ResourceKind, ResourceSlot, SlotClass, SlotRef, SpecKey, Stage, }; -use crate::pipeline::testing::EXACT_SAMPLING; use crate::pipeline::testing::{ compile, link_and_validate, llvm_assemble, profile, typed_module, AssembleError, }; @@ -60,7 +58,7 @@ fn assemble(name: &str, body: &str) -> Option> { } fn lavapipe() -> DeviceProfile { - profile("lavapipe", EXACT_SAMPLING).expect("profile") + profile("lavapipe", DevicePolicy::default()).expect("profile") } const EDGE: u64 = 1; @@ -87,74 +85,32 @@ fn bicubic(address: u64, pixel: bool) -> u64 { BASE | address | address << 3 | address << 6 | u64::from(pixel) << 15 } -/// What a kernel does with its texture. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Op { - /// `texture2d::sample`: a `half4` result. - SampleHalf, - /// `texture2d::sample`. - Sample, - /// `texture2d::gather(s, uv, int2(0), component::y)`. - Gather, -} - -/// A form of the tests: its operation through the constexpr sampler `words`. +/// A form of the tests: a `texture2d::sample` through the constexpr sampler `words`. #[derive(Clone, Copy, Debug)] struct Form { name: &'static str, - op: Op, words: u64, } -/// Each emulation twice, as a pair whose emulations differ in size: through a repeating sampler, -/// which reads Metal's position, and through a pixel sampler (a clamping one for the gather), -/// which reads none (or a shorter one). -fn forms() -> [(Form, Form); 3] { +/// The emulation twice, as a pair whose emulations differ in size: through a repeating sampler, +/// which reads Metal's position, and through a pixel sampler, which reads none. +fn forms() -> [Form; 2] { [ - ( - Form { - name: "linear repeat", - op: Op::SampleHalf, - words: sampler(1, REPEAT, false), - }, - Form { - name: "linear pixel edge", - op: Op::SampleHalf, - words: sampler(1, EDGE, true), - }, - ), - ( - Form { - name: "bicubic repeat", - op: Op::Sample, - words: bicubic(REPEAT, false), - }, - Form { - name: "bicubic pixel edge", - op: Op::Sample, - words: bicubic(EDGE, true), - }, - ), - ( - Form { - name: "gather repeat", - op: Op::Gather, - words: sampler(1, REPEAT, false), - }, - Form { - name: "gather edge", - op: Op::Gather, - words: sampler(1, EDGE, false), - }, - ), + Form { + name: "bicubic repeat", + words: bicubic(REPEAT, false), + }, + Form { + name: "bicubic pixel edge", + words: bicubic(EDGE, true), + }, ] } -/// The same operation without an emulation: a nearest sample or gather in pixel coordinates. -fn plain(op: Op) -> Form { +/// The same sample without an emulation: a nearest sample in pixel coordinates. +fn plain() -> Form { Form { name: "plain", - op, words: sampler(0, EDGE, true), } } @@ -163,20 +119,9 @@ fn plain(op: Op) -> Form { /// on element `ks[tid]` (`uint` buffer 2) of an array of `n` textures (the null texture where /// `ks[tid]` is past the array), or on one texture where `n` is `None`. fn kernel(n: Option, form: Form) -> String { - let (texel, vec4, suffix, size, vec_name) = match form.op { - Op::SampleHalf => ("half", "<4 x half>", "v4f16", 8, "half4"), - Op::Sample | Op::Gather => ("float", "<4 x float>", "v4f32", 16, "float4"), - }; - let (call, decl) = match form.op { - Op::SampleHalf | Op::Sample => ( - format!("@air.sample_texture_2d.{suffix}(ptr addrspace(1) %h, ptr addrspace(2) @__air_sampler_state, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.0, float 0.0, i32 0)"), - format!("@air.sample_texture_2d.{suffix}(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32)"), - ), - Op::Gather => ( - format!("@air.gather_texture_2d.{suffix}(ptr addrspace(1) %h, ptr addrspace(2) @__air_sampler_state, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i32 1, i32 0)"), - format!("@air.gather_texture_2d.{suffix}(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i32, i32)"), - ), - }; + let (texel, vec4, suffix, size, vec_name) = ("float", "<4 x float>", "v4f32", 16, "float4"); + let call = format!("@air.sample_texture_2d.{suffix}(ptr addrspace(1) %h, ptr addrspace(2) @__air_sampler_state, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.0, float 0.0, i32 0)"); + let decl = format!("@air.sample_texture_2d.{suffix}(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32)"); let (param, pick, count, tex_ty) = match n { // An index past the array names the null texture (the switch's null arm). Some(n) => ( @@ -240,45 +185,44 @@ fn words(n: Option, form: Form) -> Option { /// An arm of a switch-at-use whose arms take one emulation costs its image's reads, not the /// emulation. Between 16 and 32 candidates each arm adds the same words whether the emulation reads -/// Metal's position (a repeating sampler) or not (a pixel or clamping one), and an arm's words past -/// the plain sample's or gather's are less than a quarter of the emulation's own. +/// Metal's position (a repeating sampler) or not (a pixel one), and an arm's words past the plain +/// sample's are less than a quarter of the emulation's own. #[test] fn the_switch_words_do_not_scale_with_arms_times_emulation() { - for (big, small) in forms() { - let mut slopes = Vec::new(); - // The 16 arms from 16 to 32 candidates (and one more interned constant at most, the - // same for both forms of a pair). - for form in [big, small] { - let (Some(w16), Some(w32)) = (words(Some(16), form), words(Some(32), form)) else { - return; - }; - slopes.push((w32 - w16) / 16); - } - let plain = plain(big.op); - let (Some(p16), Some(p32)) = (words(Some(16), plain), words(Some(32), plain)) else { + let [big, small] = forms(); + let mut slopes = Vec::new(); + // The 16 arms from 16 to 32 candidates (and one more interned constant at most, the same + // for both forms). + for form in [big, small] { + let (Some(w16), Some(w32)) = (words(Some(16), form), words(Some(32), form)) else { return; }; - let plain_slope = (p32 - p16) / 16; - let (Some(one), Some(one_plain)) = (words(None, big), words(None, plain)) else { - return; - }; - let emulation = one - one_plain; - eprintln!( - "{}: per arm {} ({}: {}), plain {plain_slope}, emulation {emulation}", - big.name, slopes[0], small.name, slopes[1] - ); - assert_eq!( - slopes[0], slopes[1], - "{} and {}: an arm's words depend on the emulation's", - big.name, small.name - ); - assert!( - 4 * slopes[0].saturating_sub(plain_slope) < emulation, - "{}: an arm adds {} words past the plain {plain_slope}, against an emulation of {emulation}", - big.name, - slopes[0] - ); + slopes.push((w32 - w16) / 16); } + let plain = plain(); + let (Some(p16), Some(p32)) = (words(Some(16), plain), words(Some(32), plain)) else { + return; + }; + let plain_slope = (p32 - p16) / 16; + let (Some(one), Some(one_plain)) = (words(None, big), words(None, plain)) else { + return; + }; + let emulation = one - one_plain; + eprintln!( + "{}: per arm {} ({}: {}), plain {plain_slope}, emulation {emulation}", + big.name, slopes[0], small.name, slopes[1] + ); + assert_eq!( + slopes[0], slopes[1], + "{} and {}: an arm's words depend on the emulation's", + big.name, small.name + ); + assert!( + 4 * slopes[0].saturating_sub(plain_slope) < emulation, + "{}: an arm adds {} words past the plain {plain_slope}, against an emulation of {emulation}", + big.name, + slopes[0] + ); } /// The combined image-sampler bindings of `m`, by texture slot. @@ -423,21 +367,12 @@ fn image(slot: ResourceSlot, k: u32, class: u32) -> Image { } /// Every lane of the shared emulation over `n` candidates of different sizes and formats is its -/// candidate's own lane, and the null texture reads zero, for Metal's linear and bicubic filters on -/// the interpreter. +/// candidate's own lane, and the null texture reads zero, for Metal's bicubic filter on the +/// interpreter. #[test] fn the_shared_emulation_answers_each_candidates_own_lane() { let p = lavapipe(); - let linear: Vec = [ - PixelFormat::RGBA8Unorm, - PixelFormat::RGBA16Float, - PixelFormat::RGBA32Float, - PixelFormat::RGBA16Unorm, - ] - .iter() - .map(|pf| texel_format(*pf).0) - .collect(); - let bicubic_classes: Vec = [ + let classes: Vec = [ PixelFormat::RGBA8Unorm, PixelFormat::RGBA32Float, PixelFormat::R8Unorm, @@ -449,13 +384,7 @@ fn the_shared_emulation_answers_each_candidates_own_lane() { .0 }) .collect(); - let cases = [ - (forms()[0].0, &linear, true), - (forms()[0].1, &linear, true), - (forms()[1].0, &bicubic_classes, false), - (forms()[1].1, &bicubic_classes, false), - ]; - for (form, classes, half) in cases { + for form in forms() { for n in [3u32, 4] { let what = format!("{} n={n}", form.name); let Some(one) = assemble(&what, &kernel(None, form)) else { @@ -479,12 +408,9 @@ fn the_shared_emulation_answers_each_candidates_own_lane() { } let index: Vec = (0..lanes).map(|l| l % (n + 1)).collect(); let ks: Vec = index.iter().flat_map(|k| k.to_le_bytes()).collect(); - let size = if half { 8 } else { 16 }; + let size = 16; let out = vec![0xabu8; size * lanes as usize]; - let key = |slot: u32| match half { - true => SpecKey::TexelFormat(texture(slot)), - false => SpecKey::BicubicTexels(texture(slot)), - }; + let key = |slot: u32| SpecKey::BicubicTexels(texture(slot)); let class_of = |k: u32| classes[k as usize % classes.len()]; // Each candidate alone. let (plan, m) = typed_module(&one, "k", &p).expect("typed module"); @@ -535,13 +461,12 @@ fn the_shared_estimate_bounds_its_emission() { use crate::lower::select::LowerInputs; use crate::pipeline::compile::{compile_bitcode, plan_bitcode, EntryRef}; use crate::pipeline::testing::meter; - let profiles = crate::spirv::testing::committed_exact_profiles().expect("profiles"); + let profiles = crate::spirv::testing::committed_profiles().expect("profiles"); let nearest = Form { name: "nearest repeat", - op: Op::Sample, words: sampler(0, REPEAT, false), }; - let mut all: Vec

= forms().iter().flat_map(|(a, b)| [*a, *b]).collect(); + let mut all = forms().to_vec(); all.push(nearest); for form in all { for n in [2u32, 8, 32] { diff --git a/crates/metal2vulkan/src/tests/engine_snapped.rs b/crates/metal2vulkan/src/tests/engine_snapped.rs index f9c0daefb..990db6f1f 100644 --- a/crates/metal2vulkan/src/tests/engine_snapped.rs +++ b/crates/metal2vulkan/src/tests/engine_snapped.rs @@ -1,22 +1,15 @@ -//! The coordinates a device's gathers and repeating nearest samples read. On a device without -//! `VkProperty::MetalSampler`, a gather through a constexpr normalized sampler of a 2D texture or -//! array (with or without a comparison or an offset) hands the device a coordinate snapped onto -//! Metal's 2x2 block (`sampler.gather.snapped`, `sampler.gather_compare.snapped`), and a runtime -//! sampler's behind its word; every other gather (a cube's) keeps the device's footprint under -//! `PrecisionNote::DeviceGatherFootprint`; a nearest sample through a constexpr normalized sampler -//! with a repeating or mirrored axis that reads the base level snaps those axes -//! (`sampler.nearest.snapped`), and such a nearest sample of a cube its direction onto the centre -//! of Metal's texel (`sampler.cube.snapped`) under `PrecisionNote::CubeFaceReciprocal`. On a device -//! with the property all are the device's, Metal's own sampler, and the module requires it. A -//! constexpr pixel sampler's position is the coordinate as given, on every device: its gather snaps -//! from it, and its linear sample is emulated from it or, with the property, snapped onto its -//! footprint cell (`sampler.linear.snapped`), none of them noted `PixelSamplerScaling`; and a cube -//! reads it as a normalized sampler. Every module validates on every committed profile, and the -//! plan's word estimate bounds what it emits. +//! The coordinates a device's gathers and samples read. A gather and a sample through a constexpr +//! normalized sampler are the device's sampler's on every device (Metal's own on MoltenVK). A +//! constexpr pixel sampler's position is the coordinate as given, on every device: its gather +//! snaps from it (`sampler.gather.snapped`), and its linear sample snaps onto its footprint cell +//! (`sampler.linear.snapped`), none of them noted `PixelSamplerScaling`; and a cube reads it as a +//! normalized sampler. A runtime sampler's gather snaps behind its word where the word states pixel +//! coordinates. Every module requires the device's sampler (`VkProperty::MetalSampler` or +//! `VkProperty::DeviceSampling`) and validates on every committed profile, and the plan's word +//! estimate bounds what it emits. //! //! The snapped coordinate's arithmetic is checked bit for bit on the interpreter by -//! `lower::sampler::position`'s and `lower::sampler::face`'s tests (the interpreter has no gather -//! or sample). +//! `lower::sampler::position`'s tests (the interpreter has no gather or sample). //! //! `llvm-as` assembles the kernels; without it the tests skip visibly. @@ -209,261 +202,150 @@ fn uses(a: &FunctionArtifact, name: &str) -> u32 { a.strategies.entries.get(name).map_or(0, |u| u.uses) } -fn metal_sampler(p: &DeviceProfile) -> bool { - p.fields() +/// Whether compiled `a` requires the device's sampler: `VkProperty::MetalSampler` on a profile +/// that samples through Metal's own sampler, `VkProperty::DeviceSampling` on any other. +fn requires_the_sampler(a: &FunctionArtifact, p: &DeviceProfile) -> bool { + let property = match p + .fields() .enabled .properties .contains(&VkProperty::MetalSampler) + { + true => VkProperty::MetalSampler, + false => VkProperty::DeviceSampling, + }; + a.requirements.properties.contains(&property) } -/// How a kernel's one access compiles on a device without `VkProperty::MetalSampler`: its census -/// name, and which of the notes `NOTES` the module records. -struct Expect { - name: &'static str, - note: Option, -} - -/// The notes of an access the module leaves to the device's position, or snaps near Metal's. -const NOTES: [PrecisionNote; 2] = [ - PrecisionNote::DeviceGatherFootprint, - PrecisionNote::CubeFaceReciprocal, -]; - -/// The kernels of the selection tests, with what each compiles to on a device without the -/// property; on one with it, each `*.snapped` or noted access is the device's (`plain`) and the -/// module requires the property. -fn cases() -> Vec<(&'static str, Op, Option, Expect, &'static str)> { +/// The kernels of the selection test, each with its access's census name. +fn cases() -> Vec<(&'static str, Op, Option, &'static str)> { let near = |a: [u64; 3]| Some(sampler(0, 0, a, false)); let gather = Op::Gather { offset: (0, 0) }; - let snapped = |name| Expect { name, note: None }; vec![ - ( - "gather edge", - gather, - near([EDGE; 3]), - snapped("sampler.gather.snapped"), - "sampler.gather", - ), - ( - "gather zero", - gather, - near([ZERO; 3]), - snapped("sampler.gather.snapped"), - "sampler.gather", - ), + ("gather edge", gather, near([EDGE; 3]), "sampler.gather"), + ("gather zero", gather, near([ZERO; 3]), "sampler.gather"), ( "gather repeat offset", Op::Gather { offset: (1, -1) }, near([REPEAT; 3]), - snapped("sampler.gather.snapped"), - "sampler.gather", - ), - ( - "gather mirror", - gather, - near([MIRROR; 3]), - snapped("sampler.gather.snapped"), "sampler.gather", ), + ("gather mirror", gather, near([MIRROR; 3]), "sampler.gather"), ( "gather linear sampler", gather, Some(sampler(1, 0, [EDGE; 3], false)), - snapped("sampler.gather.snapped"), "sampler.gather", ), ( "gather array", Op::GatherArray, near([EDGE; 3]), - snapped("sampler.gather.snapped"), - "sampler.gather", - ), - ( - // Snapped behind its word, under the operation's own name. - "gather runtime sampler", - gather, - None, - snapped("sampler.gather"), "sampler.gather", ), + // Snapped behind its word, under the operation's own name. + ("gather runtime sampler", gather, None, "sampler.gather"), ( "nearest repeat 2d", Op::Sample2D, near([REPEAT; 3]), - snapped("sampler.nearest.snapped"), "sampler.sample", ), ( "nearest mirror s, edge t", Op::Sample2D, near([MIRROR, EDGE, EDGE]), - snapped("sampler.nearest.snapped"), "sampler.sample", ), ( "nearest repeat 1d", Op::Sample1D, near([REPEAT; 3]), - snapped("sampler.nearest.snapped"), "sampler.sample", ), ( "nearest repeat r only 3d", Op::Sample3D, near([EDGE, EDGE, REPEAT]), - snapped("sampler.nearest.snapped"), "sampler.sample", ), ( "nearest repeat, nearest mip filter, level 0", Op::Sample2D, Some(sampler(0, 1, [REPEAT; 3], false)), - snapped("sampler.nearest.snapped"), - "sampler.sample", - ), - ( - "nearest repeat, linear mip filter, level 0", - Op::Sample2D, - Some(sampler(0, 2, [REPEAT; 3], false)), - snapped("sampler.sample"), "sampler.sample", ), ( "nearest edge", Op::Sample2D, near([EDGE; 3]), - snapped("sampler.sample"), "sampler.sample", ), ( "nearest repeat, nearest mip filter, dynamic level", Op::SampleLevel, Some(sampler(0, 1, [REPEAT; 3], false)), - snapped("sampler.sample"), "sampler.sample", ), + // A runtime sampler's sample snaps onto its footprint cell where its word states a + // linear pixel sampler, under the operation's own name. ( - // A runtime sampler's sample is planned for the linear emulation, which its word - // selects; a nearest word selects the device's sample. "nearest repeat runtime sampler", Op::Sample2D, None, - snapped("sampler.linear"), "sampler.sample", ), ( "nearest cube", Op::SampleCube, near([EDGE; 3]), - Expect { - name: "sampler.cube.snapped", - note: Some(PrecisionNote::CubeFaceReciprocal), - }, "sampler.sample", ), ( - "nearest cube, nearest mip filter, level 0", - Op::SampleCube, - Some(sampler(0, 1, [REPEAT; 3], false)), - Expect { - name: "sampler.cube.snapped", - note: Some(PrecisionNote::CubeFaceReciprocal), - }, - "sampler.sample", - ), - ( - "nearest cube, linear mip filter, level 0", - Op::SampleCube, - Some(sampler(0, 2, [EDGE; 3], false)), - snapped("sampler.sample"), - "sampler.sample", - ), - ( - // Emulated on Metal's position. "linear cube", Op::SampleCube, Some(sampler(1, 0, [EDGE; 3], false)), - Expect { - name: "sampler.linear", - note: Some(PrecisionNote::CubeFaceReciprocal), - }, "sampler.sample", ), ( "nearest cube runtime sampler", Op::SampleCube, None, - Expect { - name: "sampler.linear", - note: Some(PrecisionNote::CubeFaceReciprocal), - }, "sampler.sample", ), ] } -/// On every committed profile, each kernel compiles to its expected access and notes, and -/// validates; on a device with `VkProperty::MetalSampler` every gather and every snapped nearest -/// sample through a constexpr normalized sampler requires the property instead, as does a sample at -/// a dynamic level through one, whose level is Metal's there. +/// On every committed profile, each kernel's gather or sample through a normalized or runtime +/// sampler is the device's sampler's, under its census name, requires the device's sampler, and +/// validates. #[test] -fn gathers_and_repeating_nearest_samples_snap_where_metal_reads_them() { - let profiles = crate::spirv::testing::committed_exact_profiles().expect("profiles"); - for (name, op, words, expect, plain) in cases() { +fn normalized_gathers_and_samples_are_the_device_s_sampler_s() { + let profiles = crate::spirv::testing::committed_profiles().expect("profiles"); + for (name, op, words, census) in cases() { let Some(bc) = assemble(name, &kernel(op, words)) else { return; }; - let snapped = expect.name.ends_with(".snapped"); for (stem, p) in &profiles { let what = format!("{name} on {stem}"); let a = compile(&bc, "k", p).unwrap_or_else(|e| panic!("{what}: {e}")); link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: {e}")); - let noted = |n: &PrecisionNote| a.precision.contains(n); - let required = a - .requirements - .properties - .contains(&VkProperty::MetalSampler); - if metal_sampler(p) { - assert_eq!(uses(&a, plain), 1, "{what}"); - assert!(!NOTES.iter().any(noted), "{what}"); - // A runtime sampler's or a pixel sampler's gather requires it too: every gather - // is Metal's own there; and so does a sample that filters or may, a linear mip - // filter's and a runtime sampler's included. - let gathers = matches!(op, Op::Gather { .. } | Op::GatherArray); - let filtered = words.is_none_or(|w| (w >> 9) & 0xf != 0 || (w >> 13) & 3 == 2); - // A sample at a dynamic level through a constexpr normalized sampler reads Metal's - // level, the device's own there. - let leveled = - matches!(op, Op::SampleLevel) && words.is_some_and(|w| w >> 15 & 1 == 0); - assert_eq!( - required, - snapped || gathers || filtered || leveled, - "{what}" - ); - } else { - assert_eq!(uses(&a, expect.name), 1, "{what}"); - for n in &NOTES { - assert_eq!(noted(n), expect.note == Some(*n), "{what}: {n:?}"); - } - assert!(!required, "{what}"); - } + assert_eq!(uses(&a, census), 1, "{what}"); + assert!(requires_the_sampler(&a, p), "{what}"); } } } -/// Over an owned fixture: `unk_gather`'s comparison gathers of a depth 2D texture and array through -/// a constexpr sampler snap; its five gathers of cubes (three color, two depth) and two comparison -/// gathers of cubes take Metal's footprint by fetches (`sampler.gather.cube` and -/// `sampler.gather_compare.cube`), and keep the device's under the note where the bound format's -/// rule is not measured. +/// Over an owned fixture: `unk_gather`'s five gathers of cubes (three color, two depth) and its +/// four comparison gathers (of cubes, and of a depth 2D texture and array) are the device's +/// sampler's on every committed profile that compiles it. #[test] -fn the_fixture_cube_gathers_take_metals_footprint() { +fn the_fixture_cube_gathers_are_the_device_s() { let Ok(bc) = llvm_assemble(&engine_dir().join("unk_gather.ll")) else { eprintln!("SKIPPED: llvm-as"); return; }; - for (stem, p) in crate::spirv::testing::committed_exact_profiles().expect("profiles") { + for (stem, p) in crate::spirv::testing::committed_profiles().expect("profiles") { let a = match compile(&bc, "unk_gather", &p) { Ok(a) => a, // A profile without cube arrays refuses the fixture. @@ -473,29 +355,19 @@ fn the_fixture_cube_gathers_take_metals_footprint() { } }; link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: {e}")); - let noted = a.precision.contains(&PrecisionNote::DeviceGatherFootprint); - if metal_sampler(&p) { - assert!(!noted, "{stem}"); - assert_eq!(uses(&a, "sampler.gather"), 5, "{stem}"); - assert_eq!(uses(&a, "sampler.gather_compare"), 4, "{stem}"); - } else { - assert!(noted, "{stem}"); - assert_eq!(uses(&a, "sampler.gather"), 0, "{stem}"); - assert_eq!(uses(&a, "sampler.gather.cube"), 5, "{stem}"); - assert_eq!(uses(&a, "sampler.gather_compare"), 0, "{stem}"); - assert_eq!(uses(&a, "sampler.gather_compare.cube"), 2, "{stem}"); - assert_eq!(uses(&a, "sampler.gather_compare.snapped"), 2, "{stem}"); - } + assert_eq!(uses(&a, "sampler.gather"), 5, "{stem}"); + assert_eq!(uses(&a, "sampler.gather_compare"), 4, "{stem}"); + assert!(requires_the_sampler(&a, &p), "{stem}"); } } /// The kernels of the pixel sampler test: each through a constexpr pixel sampler, with its census -/// name on a device without `VkProperty::MetalSampler` and on one with it (`None`: a cube's, -/// which compiles as through the same sampler with normalized coordinates). -fn pixel_cases() -> Vec<(&'static str, Op, u64, Option<(&'static str, &'static str)>)> { +/// name (`None`: a cube's, which compiles as through the same sampler with normalized +/// coordinates). +fn pixel_cases() -> Vec<(&'static str, Op, u64, Option<&'static str>)> { let pixel = |filter, address| sampler(filter, 0, address, true); - let snapped = Some(("sampler.gather.snapped", "sampler.gather.snapped")); - let linear = Some(("sampler.linear", "sampler.linear.snapped")); + let snapped = Some("sampler.gather.snapped"); + let linear = Some("sampler.linear.snapped"); vec![ ( "pixel gather edge", @@ -545,14 +417,12 @@ fn pixel_cases() -> Vec<(&'static str, Op, u64, Option<(&'static str, &'static s } /// On every committed profile, a constexpr pixel sampler's gather and linear sample compile to -/// their census names (a linear one requiring `VkProperty::MetalSampler` where it snaps), validate, -/// and record neither `PixelSamplerScaling` nor `DeviceGatherFootprint`, but a linear sample's -/// `PixelSamplerScaling` where the bound format's class hands it to the device's filter at the -/// scaled coordinate (a specialized note); a cube through a pixel sampler compiles as through the -/// same sampler with normalized coordinates, to the same census, notes, and requirements. +/// their census names, require the device's sampler, validate, and record no +/// `PixelSamplerScaling`; a cube through a pixel sampler compiles as through the same sampler with +/// normalized coordinates, to the same census, notes, and requirements. #[test] fn pixel_samplers_read_metals_position_on_every_device() { - let profiles = crate::spirv::testing::committed_exact_profiles().expect("profiles"); + let profiles = crate::spirv::testing::committed_profiles().expect("profiles"); for (name, op, words, expect) in pixel_cases() { let Some(bc) = assemble(name, &kernel(op, Some(words))) else { return; @@ -565,26 +435,14 @@ fn pixel_samplers_read_metals_position_on_every_device() { let what = format!("{name} on {stem}"); let a = compile(&bc, "k", p).unwrap_or_else(|e| panic!("{what}: {e}")); link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: {e}")); - let required = a - .requirements - .properties - .contains(&VkProperty::MetalSampler); match (expect, &normalized) { - (Some((without, with)), _) => { - let census = if metal_sampler(p) { with } else { without }; + (Some(census), _) => { assert_eq!(uses(&a, census), 1, "{what}"); - let gather = matches!(op, Op::Gather { .. } | Op::GatherArray); - for n in [ - PrecisionNote::PixelSamplerScaling, - PrecisionNote::DeviceGatherFootprint, - ] { - let device_arm = n == PrecisionNote::PixelSamplerScaling - && !gather - && !metal_sampler(p) - && a.specialized.iter().any(|s| s.note == n); - assert!(!a.precision.contains(&n) || device_arm, "{what}: {n:?}"); - } - assert_eq!(required, metal_sampler(p) && !gather, "{what}"); + assert!( + !a.precision.contains(&PrecisionNote::PixelSamplerScaling), + "{what}" + ); + assert!(requires_the_sampler(&a, p), "{what}"); } (None, Some(nbc)) => { let b = compile(nbc, "k", p).unwrap_or_else(|e| panic!("{what}: {e}")); @@ -613,16 +471,14 @@ fn sampler_fields(a: &FunctionArtifact) -> u32 { /// On every committed profile, a runtime sampler's gather of a 2D texture or array snaps behind its /// word (`position::SnapKind::WordGather`): the function reads the word's coordinates and its `s` -/// and `t` modes, and records neither `PixelSamplerScaling` nor `DeviceGatherFootprint`, every -/// word's gather reading Metal's block. On a device with `VkProperty::MetalSampler` it requires the -/// property (a normalized word's gather is Metal's own). A runtime sampler's 2D sample on a device -/// with the property reads whether the word states a linear pixel sampler -/// (`position::SnapKind::WordCell`; elsewhere the linear emulation reads it), and keeps -/// `PixelSamplerScaling`. +/// and `t` modes, and records no `PixelSamplerScaling`, every word's gather reading Metal's block. +/// A runtime sampler's 2D sample reads whether the word states a linear pixel sampler +/// (`position::SnapKind::WordCell`), and keeps `PixelSamplerScaling`. Each requires the device's +/// sampler. #[test] fn a_runtime_samplers_gather_snaps_behind_its_word() { use crate::metal::sampler::SamplerWord; - let profiles = crate::spirv::testing::committed_exact_profiles().expect("profiles"); + let profiles = crate::spirv::testing::committed_profiles().expect("profiles"); let gather = SamplerWord::PIXEL_COORDINATES | SamplerWord::ADDRESS[0] | SamplerWord::ADDRESS[1]; let cell = SamplerWord::PIXEL_COORDINATES | SamplerWord::MIN_LINEAR | SamplerWord::MAG_LINEAR; for (name, op) in [ @@ -639,22 +495,15 @@ fn a_runtime_samplers_gather_snaps_behind_its_word() { let a = compile(&bc, "k", p).unwrap_or_else(|e| panic!("{what}: {e}")); link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: {e}")); let fields = sampler_fields(&a); - let noted = |n: PrecisionNote| a.precision.contains(&n); - let metal = metal_sampler(p); + let scaled = a.precision.contains(&PrecisionNote::PixelSamplerScaling); + assert!(requires_the_sampler(&a, p), "{what}"); if matches!(op, Op::Sample2D) { - // Elsewhere the linear emulation reads those fields and more. assert_eq!(fields & cell, cell, "{what}: {fields:#x}"); - assert!(noted(PrecisionNote::PixelSamplerScaling), "{what}"); + assert!(scaled, "{what}"); continue; } assert_eq!(fields & gather, gather, "{what}: {fields:#x}"); - assert!(!noted(PrecisionNote::PixelSamplerScaling), "{what}"); - assert!(!noted(PrecisionNote::DeviceGatherFootprint), "{what}"); - let required = a - .requirements - .properties - .contains(&VkProperty::MetalSampler); - assert_eq!(required, metal, "{what}"); + assert!(!scaled, "{what}"); } } } @@ -668,13 +517,13 @@ fn the_snapped_estimate_bounds_its_emission() { use crate::lower::select::LowerInputs; use crate::pipeline::compile::{compile_bitcode, plan_bitcode, EntryRef}; use crate::pipeline::testing::meter; - let profiles = crate::spirv::testing::committed_exact_profiles().expect("profiles"); + let profiles = crate::spirv::testing::committed_profiles().expect("profiles"); let pixel = pixel_cases() .into_iter() .map(|(n, o, w, _)| (n, o, Some(w))); for (name, op, words) in cases() .into_iter() - .map(|(n, o, w, _, _)| (n, o, w)) + .map(|(n, o, w, _)| (n, o, w)) .chain(pixel) { let Some(bc) = assemble(name, &kernel(op, words)) else { diff --git a/crates/metal2vulkan/src/tests/engine_srgb_raw.rs b/crates/metal2vulkan/src/tests/engine_srgb_raw.rs index bd3d164e1..9091af893 100644 --- a/crates/metal2vulkan/src/tests/engine_srgb_raw.rs +++ b/crates/metal2vulkan/src/tests/engine_srgb_raw.rs @@ -9,12 +9,9 @@ //! `k = round(decode(c / 255) · 4095)` (the MSL transfer, which A1's every-byte reading matches) //! and its value `k / 4095`, alpha's `c / 255`, each correctly rounded to the result's type. //! - The selection pins which accesses read the raw view under the variant, which keep the -//! device's decode there and record `PrecisionNote::SrgbTexelDecode` (a runtime sampler's -//! sample both, its note conditional on the bound sampler's word), and that without the -//! variant every access records the fact and nothing else. -//! - On the CPU interpreter, a linear sample through a runtime sampler under the variant is the -//! raw emulation's sum where the word reaches it, as a constexpr sampler's is; where the word -//! reads one texel the device samples the raw view, and the decode note does not hold there. +//! device's decode there and record `PrecisionNote::SrgbTexelDecode` (a filtered sample, a +//! runtime sampler's included), and that without the variant every access records the fact and +//! nothing else. //! - The binder joins a slot bound in an 8-bit sRGB format to the plan's variant, the variant's //! plan states the same key, and its raw bindings view the image in the UNORM format of the //! same channels, on every committed profile. @@ -29,7 +26,7 @@ use crate::bind::{ BindState, BoundBuffer, BoundTexture, ImageSource, StageTable, TextureFacts, WriteSource, }; use crate::budget::{Budget, SPIRV_WORDS}; -use crate::device::{Device, DeviceDescription, FormatUsage}; +use crate::device::{Device, DeviceDescription, DevicePolicy, FormatUsage}; use crate::library::{FunctionConstantValues, Library}; use crate::lower::select::{LowerInputs, Plan}; use crate::metal::texel_format::srgb_raw_view; @@ -41,7 +38,6 @@ use crate::pipeline::layout::BindingSource; use crate::pipeline::sym::{ Axis, PushField, ResourceKind, ResourceSlot, SlotClass, SlotRef, SpecKey, Stage, }; -use crate::pipeline::testing::EXACT_SAMPLING; use crate::pipeline::testing::{ link_and_validate, llvm_assemble, meter, profile, typed_module_with, AssembleError, }; @@ -50,7 +46,7 @@ use crate::pipeline::{ }; use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Order, Resources}; use crate::spirv::ir::{GlobalKind, TypedModule}; -use crate::spirv::testing::committed_exact_profiles; +use crate::spirv::testing::committed_profiles; 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"; @@ -244,11 +240,11 @@ fn twin_inputs() -> LowerInputs { } fn lavapipe() -> crate::device::profile::DeviceProfile { - profile("lavapipe", EXACT_SAMPLING).expect("profile") + profile("lavapipe", DevicePolicy::default()).expect("profile") } fn m3() -> crate::device::profile::DeviceProfile { - profile("moltenvk-m3", EXACT_SAMPLING).expect("profile") + profile("moltenvk-m3", DevicePolicy::default()).expect("profile") } // ---- The reference ---------------------------------------------------------------------------- @@ -574,12 +570,9 @@ fn an_srgb_swizzle_across_alpha_swizzles_in_the_function() { enum Raw { /// On every device. Always, - /// Where the device does not sample through Metal's own sampler: the emulated linear filter, - /// and a `float` gather, which Metal's own sampler gathers as the table decodes. - Emulated, - /// Where the device does not sample through Metal's own sampler, beside the device's decode: - /// a runtime sampler's emulated linear filter, which the bound sampler's word selects. - Word, + /// Where the device does not sample through Metal's own sampler: a `float` gather, which + /// Metal's own sampler gathers as the table decodes. + Unmetal, /// Nowhere: the device's decode. Never, } @@ -587,14 +580,14 @@ enum Raw { /// Which accesses read the raw view under the variant, and which keep the device's decode there: /// recording `PrecisionNote::SrgbTexelDecode` on lavapipe, and on MoltenVK, whose decode is /// Metal's own, requiring `VkProperty::MetalSampler` instead, and stating -/// `RuntimeFact::SrgbDeviceDecode` on both. A runtime sampler's sample does both on lavapipe: its -/// emulation reads the raw view where the bound sampler's word reaches it, and its device arm -/// decodes elsewhere, the note conditional on the word. Without the variant every access records -/// `RuntimeFact::SrgbTexture` and none of them, and on MoltenVK a filtered sample, a gather and a -/// `half` access require the property. A filtered `float` sample records -/// `PrecisionNote::FloatSampleFilter` on lavapipe, but an emulated linear one under the variant -/// through a constexpr sampler, which sums the raw codes exactly with no device arm. Every form -/// validates on both devices. +/// `RuntimeFact::SrgbDeviceDecode` on both. A filtered sample (a linear filter, a linear mip filter +/// or a runtime sampler) is the device's, and keeps its decode. Without the variant every access +/// records `RuntimeFact::SrgbTexture` and none of them. On MoltenVK every sample and gather the +/// device makes requires the property, and so does a `half` access that converts its texel by the +/// bound format's class (`RuntimeFact::TexelFormat`) outside the raw view; a filtered sample +/// records `PrecisionNote::HalfSampleFilter` or `PrecisionNote::FloatSampleFilter` under the bound +/// format (`lower::sampler::linear::metal_filtered_ycbcr`). On lavapipe the texel is the device's +/// conversion: no class, no filter note. Every form validates on both devices. #[test] fn the_raw_view_serves_what_metal_measured() { use crate::device::requirements::VkProperty; @@ -628,17 +621,17 @@ fn the_raw_view_serves_what_metal_measured() { ("gather alpha half", Access::Gather(3), true, Raw::Always), ("bicubic half", Access::Sample(bicubic), true, Raw::Always), ("bicubic float", Access::Sample(bicubic), false, Raw::Always), - ("linear half", Access::Sample(linear), true, Raw::Emulated), - ("gather float", Access::Gather(0), false, Raw::Emulated), - ("linear float", Access::Sample(linear), false, Raw::Emulated), + ("gather float", Access::Gather(0), false, Raw::Unmetal), + ("linear half", Access::Sample(linear), true, Raw::Never), + ("linear float", Access::Sample(linear), false, Raw::Never), ( "mip linear", Access::Sample(sampler_words(0, 2, false)), false, Raw::Never, ), - ("runtime half", Access::Runtime, true, Raw::Word), - ("runtime float", Access::Runtime, false, Raw::Word), + ("runtime half", Access::Runtime, true, Raw::Never), + ("runtime float", Access::Runtime, false, Raw::Never), ]; let consts = FunctionConstantValues::defaults(); for (name, access, half, raw) in cases { @@ -647,11 +640,10 @@ fn the_raw_view_serves_what_metal_measured() { }; for (stem, p) in [("lavapipe", lavapipe()), ("moltenvk-m3", m3())] { let metal = stem == "moltenvk-m3"; - let word = raw == Raw::Word && !metal; let raw = match raw { Raw::Always => true, - Raw::Emulated => !metal, - Raw::Word | Raw::Never => false, + Raw::Unmetal => !metal, + Raw::Never => false, }; for variant in [false, true] { let what = format!("{name} on {stem}, variant {variant}"); @@ -664,19 +656,17 @@ fn the_raw_view_serves_what_metal_measured() { ); let reads_raw = resource(&m, |k| *k == ResourceKind::RawTexture).is_some() || resource(&m, raw_combined).is_some(); - assert_eq!(reads_raw, variant && (raw || word), "{what}"); + assert_eq!(reads_raw, variant && raw, "{what}"); assert_eq!( plan.precision.contains(&PrecisionNote::SrgbTexelDecode), variant && !raw && !metal, "{what}" ); - // A runtime sampler's device decode holds where its word does not reach the - // emulation. - assert_eq!( - plan.specialized + assert!( + !plan + .specialized .iter() .any(|s| s.note == PrecisionNote::SrgbTexelDecode), - variant && word, "{what}" ); // A form that keeps the device's decode under the variant states it, so the @@ -687,43 +677,16 @@ fn the_raw_view_serves_what_metal_measured() { variant && !raw, "{what}" ); - // A raw `half` access converts nothing by the format's class; a raw linear one - // reads the class's channels. A `float` access reads the class for an emulated - // linear sample: a constexpr sampler's, and a runtime sampler's, whose device arm - // converts by it. It reads it too for a plain read the shader fetches where the - // bound format is a 32-bit float one, and the device reads otherwise: a nearest - // sample at a level the function knows and a gather, through a constexpr sampler, - // outside the raw view; and for any access that may read one texel, whose `float` - // texel converts by the class. - let linear_half = name == "linear half"; - let has_class = plan - .facts - .contains(&RuntimeFact::TexelFormat { slot: TEXTURE }); - if half && name != "bicubic half" { - assert_eq!(has_class, !(variant && raw) || linear_half, "{what}"); - } - if !half { - let emulated = matches!(name, "linear float" | "runtime float"); - let fetched = - matches!(name, "nearest float" | "nearest level" | "gather float") - && !(variant && raw); - // A `float` access that may read one texel converts it by the class where - // the device's sampler is not Metal's, outside the raw view. - let one_texel = matches!( - name, - "read float" - | "fetch float" - | "nearest float" - | "nearest level" - | "gather float" - | "runtime float" - ) && !(variant && raw); - assert_eq!( - has_class, - (emulated || fetched || one_texel) && !metal, - "{what}" - ); - } + // On MoltenVK a `half` access outside the raw view converts its texel by the + // format's class, whose rounding to `half` is Metal's there only through Metal's + // own texture unit; a bicubic sample's taps are fetched. + let converts = metal && half && !(variant && raw) && name != "bicubic half"; + assert_eq!( + plan.facts + .contains(&RuntimeFact::TexelFormat { slot: TEXTURE }), + converts, + "{what}" + ); let a = compile_bitcode( &bc, EntryRef::Name("k"), @@ -734,11 +697,6 @@ fn the_raw_view_serves_what_metal_measured() { SPIRV_WORDS, ) .unwrap_or_else(|e| panic!("{what}: {e}")); - // A filtered sample of either result type needs Metal's sampler on MoltenVK - // anyway, and elsewhere a `float` one records `FloatSampleFilter`; so does a gather - // through a constexpr normalized sampler, which is Metal's own there and reads a - // snapped coordinate elsewhere. The variant adds every access that keeps the - // device's decode. let filtered = matches!( name, "linear half" @@ -747,23 +705,32 @@ fn the_raw_view_serves_what_metal_measured() { | "runtime half" | "runtime float" ); - let gather = matches!(access, Access::Gather(_)); - // The raw emulation has no device arm. - let raw_linear = variant && raw && matches!(name, "linear half" | "linear float"); assert_eq!( plan.precision.contains(&PrecisionNote::FloatSampleFilter), - filtered && !half && !metal && !raw_linear, + filtered && !half && metal, "{what}" ); - // And on MoltenVK a `half` access that converts its texel by the class, outside - // the raw view, whose rounding to `half` is Metal's there only through Metal's - // own texture unit; a bicubic sample's taps are fetched. - let converts = half && !(variant && raw) && name != "bicubic half"; + assert_eq!( + plan.precision.contains(&PrecisionNote::HalfSampleFilter), + filtered && half && metal, + "{what}" + ); + // Every sample and gather the device makes (not a read, a pixel fetch or a + // bicubic sample's fetched taps). + let sampled = !matches!( + name, + "read half" + | "read float" + | "fetch half" + | "fetch float" + | "bicubic half" + | "bicubic float" + ); assert_eq!( a.requirements .properties .contains(&VkProperty::MetalSampler), - metal && (filtered || gather || (variant && !raw) || converts), + metal && (sampled || converts), "{what}" ); link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: {e}")); @@ -863,649 +830,9 @@ declare {{ {vec4}, i8 }} @air.sample_texture_{name}.{suffix}({args}) ) } -/// A deterministic source: a 64-bit LCG. -struct Lcg(u64); - -impl Lcg { - fn next(&mut self) -> u64 { - self.0 = self - .0 - .wrapping_mul(6_364_136_223_846_793_005) - .wrapping_add(1_442_695_040_888_963_407); - self.0 >> 11 - } -} - -/// The base tap and 1/256 fraction of texel-space coordinate `x` (Metal's footprint). -fn split(x: f64) -> (i64, i64) { - let q = (256.0 * (x - 0.5) + 0.5).floor() as i64; - (q >> 8, q & 255) -} - -/// Channel `c`'s grid code of code `code` on the sRGB grids: a color step (grid 4095), alpha's -/// `16 c` (grid 4080). -fn grid_code(c: usize, code: u32) -> (i128, u64) { - if c < 3 { - (i128::from(step(code)), 4095) - } else { - (i128::from(16 * code), 4080) - } -} - -/// A raw filter form: its sampler's filter code (1 linear, 2 bicubic), the texture's dimensions -/// (1, 2, or 3), and a `half` result. -#[derive(Clone, Copy, Debug)] -struct Form { - filter: u64, - dims: u8, - half: bool, -} - -/// Metal's filtered value (a `half` or `f32` result, as bits) of channel `c` of texels `codes` -/// (`w × h × d`, row-major, slice by slice) at texel-space `(x, y, z)` (`y` unused for 1D, `z` -/// unused below 3D) in form `f`, clamped to the edge: the footprint's weights (`(256 - k, k)` -/// linear, Metal's table bicubic, a 1D texture bilinear either way), the grid codes summed -/// exactly, rounded half up, clamped into the grid, and the quotient correctly rounded. A 2D or 3D -/// linear sample's is Metal's sum of truncated terms: an axis whose two taps clamp onto one texel -/// weighs `(256, 0)`, each tap's weight is `wx · wy` (2D) or `wx · wy · wz / 256` rounded to -/// nearest (3D, a tie up on the `t` axis's first tap), and each term `code · w` is truncated onto -/// `2^-4` of the grid before the sum's step `⌊(T + 2^11) / 2^12⌋`. -fn filtered( - codes: &[[u32; 4]], - (w, h, d): (i64, i64, i64), - (x, y, z): (f64, f64, f64), - f: Form, - c: usize, -) -> u32 { - let Form { filter, dims, half } = f; - let at3 = |i: i64, j: i64, l: i64| { - let (i, j, l) = (i.clamp(0, w - 1), j.clamp(0, h - 1), l.clamp(0, d - 1)); - codes[((l * h + j) * w + i) as usize][c] - }; - let at = |i: i64, j: i64| at3(i, j, 0); - let (i, kx) = split(x); - let grid = grid_code(c, 0).1; - // An axis's weights, `(256, 0)` where its two taps clamp onto one texel. - let axis = |i: i64, k: i64, n: i64| { - let k = if i.clamp(0, n - 1) == (i + 1).clamp(0, n - 1) { - 0 - } else { - k - }; - [256 - k, k] - }; - let n: i128 = match dims { - 1 => { - let a = grid_code(c, at(i, 0)).0; - let b = grid_code(c, at(i + 1, 0)).0; - (a * i128::from(256 - kx) + b * i128::from(kx) + 128) >> 8 - } - 3 => { - let (j, ky) = split(y); - let (l, kz) = split(z); - let (wx, wy, wz) = (axis(i, kx, w), axis(j, ky, h), axis(l, kz, d)); - let mut t = 0i128; - for n in 0..8 { - let (a, b, e) = (n & 1, (n >> 1) & 1, n >> 2); - let p = wx[a] * wy[b] * wz[e]; - let wt = (p >> 8) + i64::from(p & 255 > 128 || (p & 255 == 128 && b == 0)); - let code = grid_code(c, at3(i + a as i64, j + b as i64, l + e as i64)).0; - t += (code * i128::from(wt)) >> 4; - } - (t + (1 << 11)) >> 12 - } - _ if filter == 1 => { - let (j, ky) = split(y); - let (wx, wy) = (axis(i, kx, w), axis(j, ky, h)); - let mut t = 0i128; - for n in 0..4 { - let (a, b) = (n & 1, n >> 1); - let code = grid_code(c, at(i + a as i64, j + b as i64)).0; - t += (code * i128::from(wx[a] * wy[b])) >> 4; - } - (t + (1 << 11)) >> 12 - } - _ => { - let (j, ky) = split(y); - let cubic = |k: i64| -> Vec { - crate::metal::bicubic::weights(k as u32) - .iter() - .map(|v| i128::from(*v)) - .collect() - }; - let (wx, wy) = (cubic(kx), cubic(ky)); - let mut sum = 0i128; - for (b, wb) in (-1..=2).zip(&wy) { - for (a, wa) in (-1..=2).zip(&wx) { - sum += wa * wb * grid_code(c, at(i + a, j + b)).0; - } - } - (sum + (1 << 31)) >> 32 - } - }; - let n = n.clamp(0, i128::from(grid)) as u64; - if half { - u32::from(half_bits(n, grid)) - } else { - f32_bits(n, grid) - } -} - -/// Under the variant a linear sample (3D, 2D, and 1D, `half` and `float`) and a bicubic sample -/// (2D and 1D, `half` and `float`) of an 8-bit sRGB texture are Metal's sums of the table's -/// steps, bit for bit, on the interpreter (lavapipe): random codes in every channel, coordinates -/// on a 1/512 grid inside and past each edge. -#[test] -fn raw_filters_sum_the_steps_as_metal_does() { - let (w, h, depth) = (7i64, 5i64, 3i64); - let n = 96u32; - let mut rng = Lcg(0x5eed_0251_5267_0000); - let mut codes: Vec<[u32; 4]> = (0..w * h) - .map(|_| std::array::from_fn(|_| (rng.next() % 256) as u32)) - .collect(); - let points: Vec<(f64, f64)> = (0..n) - .map(|_| { - let x = (rng.next() % ((w as u64 + 2) * 512)) as f64 / 512.0 - 1.0; - let y = (rng.next() % ((h as u64 + 2) * 512)) as f64 / 512.0 - 1.0; - (x, y) - }) - .collect(); - // A 3D texture's further slices, and each lane's depth. - let mut deep = Lcg(0x5eed_0307_0017_0000); - codes.extend( - (0..w * h * (depth - 1)).map(|_| std::array::from_fn(|_| (deep.next() % 256) as u32)), - ); - let points: Vec<(f64, f64, f64)> = points - .into_iter() - .map(|(x, y)| { - let z = (deep.next() % ((depth as u64 + 2) * 512)) as f64 / 512.0 - 1.0; - (x, y, z) - }) - .collect(); - let p = lavapipe(); - let form = |filter, dims, half| Form { filter, dims, half }; - let forms = [ - ("linear 2d half", form(1, 2, true)), - ("linear 1d half", form(1, 1, true)), - ("linear 2d float", form(1, 2, false)), - ("linear 1d float", form(1, 1, false)), - ("linear 3d half", form(1, 3, true)), - ("linear 3d float", form(1, 3, false)), - ("bicubic 2d half", form(2, 2, true)), - ("bicubic 2d float", form(2, 2, false)), - ("bicubic 1d float", form(2, 1, false)), - ]; - for (name, f) in forms { - let Form { filter, dims, half } = f; - let words = sampler_words(filter, 0, true); - let Some(bc) = assemble(name, &filter_kernel(words, dims, half)) else { - return; - }; - let (plan, m) = typed_module_with(&bc, "k", &p, &inputs(true)) - .unwrap_or_else(|e| panic!("{name}: {e}")); - let raw = resource(&m, raw_combined).unwrap_or_else(|| panic!("{name}: no raw binding")); - let rows = if dims == 1 { 1 } else { h }; - let slices = if dims == 3 { depth } else { 1 }; - let mut img = Image::new(raw, [w as u32, rows as u32, slices as u32], 1, 1, 1); - for l in 0..slices { - for j in 0..rows { - for i in 0..w { - let at = img - .index(0, 0, 0, [i as u32, j as u32, l as u32]) - .expect("texel"); - img.texels[at] = - codes[((l * h + j) * w + i) as usize].map(|c| f32_bits(u64::from(c), 255)); - } - } - } - let coords: Vec = points - .iter() - .flat_map(|(x, y, z)| { - let mut v = vec![(*x as f32).to_le_bytes(), (*y as f32).to_le_bytes()]; - if dims == 3 { - v.extend([(*z as f32).to_le_bytes(), 0f32.to_le_bytes()]); - } - v - }) - .flatten() - .collect(); - let bytes = if half { 8 } else { 16 }; - let mut res = resources(&plan, bytes); - res.buffers.push(Buffer { - slot: Some(ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: 1, - }), - address: None, - bytes: coords, - }); - // The class the binder gives an `RGBA8Unorm_sRGB` texture. - let class = crate::metal::texel_format::texel_format(PixelFormat::RGBA8UnormSRGB); - res.spec - .insert(SpecKey::TexelFormat(TEXTURE), u64::from(class.0)); - res.spec.insert( - SpecKey::PlainHalfTexels(TEXTURE), - u64::from(class.plain_on_metal_sampler()), - ); - let bicubic = crate::metal::bicubic::texels(PixelFormat::RGBA8UnormSRGB).expect("measured"); - res.spec - .insert(SpecKey::BicubicTexels(TEXTURE), u64::from(bicubic.0)); - let mut outs = Vec::new(); - for order in [Order::Forward, Order::Reverse] { - let cfg = Config { - workgroups: [n, 1, 1], - order, - ..Config::default() - }; - let (o, _) = run_with_images(&m, &cfg, res.clone(), vec![img.clone()]) - .unwrap_or_else(|e| panic!("{name}: interpreter: {e:?}")); - outs.push(o.buffers); - } - assert_eq!(outs[0], outs[1], "{name}: the scheduling orders disagree"); - let out = &outs[0][0]; - for (lane, (x, y, z)) in points.iter().enumerate() { - for c in 0..4 { - let want = filtered(&codes, (w, rows, slices), (*x, *y, *z), f, c); - let at = lane * bytes; - let got = if half { - let i = at + 2 * c; - u32::from(u16::from_le_bytes([out[i], out[i + 1]])) - } else { - let i = at + 4 * c; - u32::from_le_bytes([out[i], out[i + 1], out[i + 2], out[i + 3]]) - }; - assert_eq!( - got, want, - "{name} lane {lane} ({x}, {y}, {z}) channel {c}: {got:#x} vs {want:#x}" - ); - } - } - } -} - -/// Under the variant a linear sample through a runtime sampler (3D, 2D, and 1D, `half` and -/// `float`) of an 8-bit sRGB texture is its constexpr sampler's raw emulation where the bound -/// sampler's word reaches it (Metal's runtime sampler answers as its constexpr sampler of the same -/// state, bit for bit), on the interpreter (lavapipe): random codes in every channel, coordinates -/// on a 1/512 grid inside and past each edge, through the raw view alone (the texture's own view -/// holds NaNs, and the interpreter samples nothing, so the device's arm would fail the run). The -/// device's decode is noted only where the word does not reach the emulation. -#[test] -fn runtime_raw_filters_sum_the_steps_where_the_word_reaches() { - use crate::metal::sampler::SamplerWord; - use crate::metal::SamplerAddressMode; - let (w, h, depth) = (7i64, 5i64, 3i64); - let n = 96u32; - let mut rng = Lcg(0x5eed_0251_4220_0000); - let codes: Vec<[u32; 4]> = (0..w * h * depth) - .map(|_| std::array::from_fn(|_| (rng.next() % 256) as u32)) - .collect(); - let points: Vec<(f64, f64, f64)> = (0..n) - .map(|_| { - let mut at = |n: i64| (rng.next() % ((n as u64 + 2) * 512)) as f64 / 512.0 - 1.0; - (at(w), at(h), at(depth)) - }) - .collect(); - // Linear filters, every axis clamped to its edge, pixel coordinates. - let mut word = SamplerWord::LINEAR | SamplerWord::PIXEL_COORDINATES; - for shift in SamplerWord::ADDRESS_SHIFT { - word |= SamplerAddressMode::ClampToEdge.as_raw() << shift; - } - let p = lavapipe(); - let consts = FunctionConstantValues::defaults(); - for (dims, half) in [ - (3, true), - (3, false), - (2, true), - (2, false), - (1, true), - (1, false), - ] { - let name = format!( - "runtime linear {dims}d {}", - if half { "half" } else { "float" } - ); - let Some(bc) = assemble(&name, &filter_kernel_through(None, dims, half)) else { - return; - }; - let a = compile_bitcode( - &bc, - EntryRef::Name("k"), - &consts, - &p, - &inputs(true), - &mut meter(), - SPIRV_WORDS, - ) - .unwrap_or_else(|e| panic!("{name}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name}: {e}")); - assert!( - a.specialized - .iter() - .any(|s| s.note == PrecisionNote::SrgbTexelDecode), - "{name}: {:?}", - a.specialized - ); - let (plan, m) = typed_module_with(&bc, "k", &p, &inputs(true)) - .unwrap_or_else(|e| panic!("{name}: {e}")); - let raw = resource(&m, raw_combined).unwrap_or_else(|| panic!("{name}: no raw binding")); - let own = resource( - &m, - |k| matches!(k, ResourceKind::CombinedTextureSampler(c) if !c.raw), - ) - .unwrap_or_else(|| panic!("{name}: no decoding binding")); - let rows = if dims == 1 { 1 } else { h }; - let slices = if dims == 3 { depth } else { 1 }; - let extent = [w as u32, rows as u32, slices as u32]; - let mut img = Image::new(raw, extent, 1, 1, 1); - let mut nan = Image::new(own, extent, 1, 1, 1); - for l in 0..slices { - for j in 0..rows { - for i in 0..w { - let at = img - .index(0, 0, 0, [i as u32, j as u32, l as u32]) - .expect("texel"); - img.texels[at] = - codes[((l * h + j) * w + i) as usize].map(|c| f32_bits(u64::from(c), 255)); - nan.texels[at] = [f32::NAN.to_bits(); 4]; - } - } - } - let coords: Vec = points - .iter() - .flat_map(|(x, y, z)| { - let mut v = vec![(*x as f32).to_le_bytes(), (*y as f32).to_le_bytes()]; - if dims == 3 { - v.extend([(*z as f32).to_le_bytes(), 0f32.to_le_bytes()]); - } - v - }) - .flatten() - .collect(); - let bytes = if half { 8 } else { 16 }; - let mut res = resources(&plan, bytes); - res.buffers.push(Buffer { - slot: Some(ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: 1, - }), - address: None, - bytes: coords, - }); - // The class the binder gives an `RGBA8Unorm_sRGB` texture, and the bound sampler's word - // masked by the fields the function reads. - let class = crate::metal::texel_format::texel_format(PixelFormat::RGBA8UnormSRGB); - res.spec - .insert(SpecKey::TexelFormat(TEXTURE), u64::from(class.0)); - res.spec.insert( - SpecKey::PlainHalfTexels(TEXTURE), - u64::from(class.plain_on_metal_sampler()), - ); - let mut words = 0; - for k in a.interface.read_keys() { - if let SpecKey::SamplerState { fields, .. } = k { - res.spec.insert(k, u64::from(word & fields)); - words += 1; - } - } - assert_eq!( - words, 1, - "{name}: the sampler's `SamplerState` specialization" - ); - let mut outs = Vec::new(); - for order in [Order::Forward, Order::Reverse] { - let cfg = Config { - workgroups: [n, 1, 1], - order, - ..Config::default() - }; - let (o, _) = run_with_images(&m, &cfg, res.clone(), vec![img.clone(), nan.clone()]) - .unwrap_or_else(|e| panic!("{name}: interpreter: {e:?}")); - outs.push(o.buffers); - } - assert_eq!(outs[0], outs[1], "{name}: the scheduling orders disagree"); - let out = &outs[0][0]; - let f = Form { - filter: 1, - dims, - half, - }; - for (lane, (x, y, z)) in points.iter().enumerate() { - for c in 0..4 { - let want = filtered(&codes, (w, rows, slices), (*x, *y, *z), f, c); - let at = lane * bytes; - let got = if half { - let i = at + 2 * c; - u32::from(u16::from_le_bytes([out[i], out[i + 1]])) - } else { - let i = at + 4 * c; - u32::from_le_bytes([out[i], out[i + 1], out[i + 2], out[i + 3]]) - }; - assert_eq!( - got, want, - "{name} lane {lane} ({x}, {y}, {z}) channel {c}: {got:#x} vs {want:#x}" - ); - } - } - } -} - -/// How many device samples (`OpImageSample*`) of `m` read the combined binding at `slot`: their -/// sampled image loaded from the slot's variable. -fn samples_of(m: &TypedModule, slot: ResourceSlot) -> usize { - use crate::spirv::ir::Inst; - let Some(var) = m.globals().iter().find_map(|g| match g.kind { - GlobalKind::Resource(s) if s == slot => Some(g.value), - _ => None, - }) else { - return 0; - }; - let insts = || m.blocks().iter().flat_map(|b| &b.insts); - let loads: BTreeSet = insts() - .filter_map(|n| match (&n.inst, n.result) { - (Inst::Load { ptr, .. }, Some(r)) if *ptr == var => Some(r.0), - _ => None, - }) - .collect(); - insts() - .filter(|n| { - matches!(&n.inst, Inst::ImageSample { sampled_image, .. } - if loads.contains(&sampled_image.0)) - }) - .count() -} - -/// Under the variant a runtime sampler's sample (2D `half` and `float`, 3D, and 1D) whose bound -/// word reads one texel (nearest minification and magnification, no linear mip filter, isotropic) -/// samples the slot's raw view through the same sampler and decodes the code through Metal's table, -/// as a constexpr nearest sample's raw read does: the module samples the raw binding as well as the -/// decoding one, and `PrecisionNote::SrgbTexelDecode` holds only where the word filters but does -/// not reach the emulation, not under a nearest word with or without a nearest mip filter. On -/// lavapipe; every form validates. -#[test] -fn a_runtime_raw_sample_reads_one_texel_through_the_raw_view() { - use crate::metal::sampler::SamplerWord; - use crate::metal::SamplerAddressMode; - let mut clamp = 0; - for shift in SamplerWord::ADDRESS_SHIFT { - clamp |= SamplerAddressMode::ClampToEdge.as_raw() << shift; - } - let mip = |m: u32| m << SamplerWord::MIP_FILTER_SHIFT; - // A word and whether the device decodes under it. - let words = [ - ("nearest", 0, false), - ("nearest, nearest mip", mip(1), false), - ("nearest, linear mip", mip(2), true), - ("linear minification", SamplerWord::MIN_LINEAR, true), - ("linear", SamplerWord::LINEAR, false), - ("linear, linear mip", SamplerWord::LINEAR | mip(2), true), - ]; - let class = crate::metal::texel_format::texel_format(PixelFormat::RGBA8UnormSRGB); - let p = lavapipe(); - let consts = FunctionConstantValues::defaults(); - let kernels = [ - ("runtime 2d half", kernel(Access::Runtime, true)), - ("runtime 2d float", kernel(Access::Runtime, false)), - ("runtime 3d float", filter_kernel_through(None, 3, false)), - ("runtime 1d half", filter_kernel_through(None, 1, true)), - ]; - for (name, k) in kernels { - let Some(bc) = assemble(name, &k) else { - return; - }; - let a = compile_bitcode( - &bc, - EntryRef::Name("k"), - &consts, - &p, - &inputs(true), - &mut meter(), - SPIRV_WORDS, - ) - .unwrap_or_else(|e| panic!("{name}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name}: {e}")); - let (_, m) = typed_module_with(&bc, "k", &p, &inputs(true)) - .unwrap_or_else(|e| panic!("{name}: {e}")); - let raw = resource(&m, raw_combined).unwrap_or_else(|| panic!("{name}: no raw binding")); - let own = resource( - &m, - |k| matches!(k, ResourceKind::CombinedTextureSampler(c) if !c.raw), - ) - .unwrap_or_else(|| panic!("{name}: no decoding binding")); - assert!(samples_of(&m, raw) >= 1, "{name}: the raw view's sample"); - assert!( - samples_of(&m, own) >= 1, - "{name}: the decoding view's sample" - ); - let Some(note) = a - .specialized - .iter() - .find(|s| s.note == PrecisionNote::SrgbTexelDecode) - else { - panic!("{name}: no conditional decode note: {:?}", a.specialized); - }; - let fields: Vec<(SpecKey, u32)> = a - .interface - .read_keys() - .into_iter() - .filter_map(|k| match k { - SpecKey::SamplerState { fields, .. } => Some((k, fields)), - _ => None, - }) - .collect(); - let [(sampler, fields)] = fields[..] else { - panic!("{name}: the sampler's `SamplerState` specialization: {fields:?}"); - }; - for (what, filter, decodes) in words { - let word = (clamp | filter) & fields; - let holds = note.when.iter().any(|clause| { - clause.all.iter().all(|t| { - let v = match t.key { - k if k == sampler => word, - SpecKey::TexelFormat(_) | SpecKey::BoundTexelFormat(_) => class.0, - k => panic!("{name}: a decode note's test of {k:?}"), - }; - (v & t.mask == t.bits) == t.equal - }) - }); - assert_eq!(holds, decodes, "{name} under a {what} word"); - } - } -} - -/// A kernel sampling element `ks[tid]` (`uint` buffer 2) of an array of `n` `texture2d` -/// slots through the runtime `[[sampler(0)]]` at `float2` buffer 0's lane `tid`, storing the -/// `half4` to buffer 1 (the null texture where `ks[tid]` is past the array): a switch-at-use. -fn switch_kernel(n: u32) -> String { - format!( - r#"%"struct.metal::texture2d" = type {{ ptr addrspace(1) }} - -define void @k(ptr readonly byval([{n} x ptr addrspace(1)]) %t, ptr addrspace(1) %c, ptr addrspace(1) %out, ptr addrspace(1) %ks, ptr addrspace(2) %s, i32 %tid) {{ - %i = zext i32 %tid to i64 - %p = getelementptr inbounds <2 x float>, ptr addrspace(1) %c, i64 %i - %uv = load <2 x float>, ptr addrspace(1) %p, align 8 - %pk = getelementptr inbounds i32, ptr addrspace(1) %ks, i64 %i - %k = load i32, ptr addrspace(1) %pk, align 4 - %past = icmp uge i32 %k, {n} - %kc = select i1 %past, i32 0, i32 %k - %kk = zext i32 %kc to i64 - %e = getelementptr inbounds [{n} x %"struct.metal::texture2d"], ptr %t, i64 0, i64 %kk, i32 0 - %elem = load ptr addrspace(1), ptr %e, align 8 - %h = select i1 %past, ptr addrspace(1) null, ptr addrspace(1) %elem - %r = call {{ <4 x half>, i8 }} @air.sample_texture_2d.v4f16(ptr addrspace(1) %h, ptr addrspace(2) %s, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.0, float 0.0, i32 0) - %v = extractvalue {{ <4 x half>, i8 }} %r, 0 - %q = getelementptr inbounds <4 x half>, ptr addrspace(1) %out, i64 %i - store <4 x half> %v, ptr addrspace(1) %q, align 8 - ret void -}} - -declare {{ <4 x half>, i8 }} @air.sample_texture_2d.v4f16(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32) - -!air.kernel = !{{!0}} -!0 = !{{ptr @k, !1, !2}} -!1 = !{{}} -!2 = !{{!3, !4, !5, !6, !7, !8}} -!3 = !{{i32 0, !"air.texture", !"air.location_index", i32 0, i32 {n}, !"air.sample", !"air.arg_type_name", !"array, {n}>", !"air.arg_name", !"t"}} -!4 = !{{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"float2", !"air.arg_name", !"c"}} -!5 = !{{i32 2, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"half4", !"air.arg_name", !"out"}} -!6 = !{{i32 3, !"air.buffer", !"air.location_index", i32 2, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"ks"}} -!7 = !{{i32 4, !"air.sampler", !"air.location_index", i32 0, i32 1, !"air.arg_type_name", !"sampler", !"air.arg_name", !"s"}} -!8 = !{{i32 5, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"tid"}} -"# - ) -} - -/// A switch-at-use over texture slots under the variant, sampled through a runtime sampler, reads -/// each slot's raw view where the word reads one texel, as one slot's sample does: on lavapipe the -/// module samples every slot's raw binding, its estimate bounds its emission, and it validates. -#[test] -fn a_switch_of_raw_slots_reads_one_texel_through_each_raw_view() { - let p = lavapipe(); - let consts = FunctionConstantValues::defaults(); - for n in [2u32, 4] { - let name = format!("switch of {n}"); - let Some(bc) = assemble(&name, &switch_kernel(n)) else { - return; - }; - let mut under = LowerInputs::new(); - for index in 0..n { - under.srgb_textures.insert(SlotRef { index, ..TEXTURE }); - } - let entry = EntryRef::Name("k"); - let plan = plan_bitcode(&bc, entry, &consts, &p, &under, &mut meter()) - .unwrap_or_else(|e| panic!("{name}: {e}")); - let a = compile_bitcode(&bc, entry, &consts, &p, &under, &mut meter(), SPIRV_WORDS) - .unwrap_or_else(|e| panic!("{name}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name}: {e}")); - let words = a.module.words.len() as u64; - assert!( - plan.estimate.words >= words, - "{name}: estimate {} < emitted {words}", - plan.estimate.words - ); - let (_, m) = - typed_module_with(&bc, "k", &p, &under).unwrap_or_else(|e| panic!("{name}: {e}")); - let raw: Vec = m - .globals() - .iter() - .filter_map(|g| match g.kind { - GlobalKind::Resource(s) if raw_combined(&s.kind) => Some(s), - _ => None, - }) - .collect(); - assert_eq!(raw.len(), n as usize, "{name}: the raw bindings {raw:?}"); - for slot in raw { - assert!(samples_of(&m, slot) >= 1, "{name}: {slot:?} is not sampled"); - } - } -} - -/// The plan's word estimate bounds the emitted module of every raw form under the variant (a -/// runtime sampler's emulation beside its device arm included), with the slot bound to a twin -/// (whose device arm decodes the filtered codes) and without, on every committed profile, and -/// every form validates there. +/// The plan's word estimate bounds the emitted module of every raw form under the variant (and of +/// the device's samples beside them), with the slot bound to a twin (whose device sample decodes +/// the filtered codes) and without, on every committed profile, and every form validates there. #[test] fn the_raw_estimate_bounds_its_emission() { let consts = FunctionConstantValues::defaults(); @@ -1562,16 +889,9 @@ fn the_raw_estimate_bounds_its_emission() { let Some(bc) = assemble(name, &k) else { return; }; - // Native sampling's profiles too: a runtime sampler's sample there keeps the device's - // arm alone, which decodes a twin's filtered codes. - let native = crate::spirv::testing::committed_profiles() + for ((stem, p), (twin, under)) in committed_profiles() .expect("profiles") .into_iter() - .map(|(stem, p)| (format!("{stem} native"), p)); - for ((stem, p), (twin, under)) in committed_exact_profiles() - .expect("profiles") - .into_iter() - .chain(native) .flat_map(|sp| { [ (sp.clone(), ("", inputs(true))), @@ -1614,7 +934,10 @@ fn devices() -> Vec<(String, Device)> { .unwrap_or_default(); let text = std::fs::read_to_string(&path).expect("profile"); let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - out.push((stem, Device::new(desc, EXACT_SAMPLING).expect("device"))); + out.push(( + stem, + Device::new(desc, DevicePolicy::default()).expect("device"), + )); } out.sort_by(|a, b| a.0.cmp(&b.0)); out @@ -1915,9 +1238,9 @@ fn an_astc_srgb_slot_reads_raw_codes_only_where_its_twin_holds_them() { /// decode and filter are Metal's own texture unit's, that `f32` is Metal's `float` value, whose /// rounding to `half` is Metal's (`metals_srgb_float_steps_round_to_their_half_steps`): the /// pipeline takes no `PrecisionNote::HalfTexelConversion` under the format and requires -/// `VkProperty::MetalSampler`. On lavapipe, whose decode is not Metal's, the note holds under it; -/// on both it holds under a format of no measured family, which the variant leaves for another -/// bound format. +/// `VkProperty::MetalSampler`, and the note holds under a format of no measured family, which the +/// variant leaves for another bound format. On lavapipe, whose decode and conversion are the +/// device's, the note holds under every format. #[test] fn metals_own_srgb_decode_converts_to_half_as_metal_does() { use crate::device::requirements::VkProperty; @@ -1953,8 +1276,26 @@ fn metals_own_srgb_decode_converts_to_half_as_metal_does() { "{stem} {pf:?}: {notes:?}" ); } - // The variant's module keeps the note for a format of no measured family: its class, - // or on MoltenVK its slot's `UnmeasuredTexels` specialization, 1 for such a format. + if !metal { + assert!( + p.stage + .precision_notes + .contains(&PrecisionNote::HalfTexelConversion), + "{stem}: {:?}", + p.stage.precision_notes + ); + assert!( + !p.stage + .specialized_notes + .iter() + .any(|s| s.note == PrecisionNote::HalfTexelConversion), + "{stem}: {:?}", + p.stage.specialized_notes + ); + continue; + } + // The variant's module keeps the note for a format of no measured family: its slot's + // `UnmeasuredTexels` specialization, 1 for such a format. let other = crate::metal::texel_format::TexelFormat::OTHER.0; let value = |key: &crate::pipeline::sym::SpecKey| match key { crate::pipeline::sym::SpecKey::UnmeasuredTexels(_) => 1, @@ -2273,7 +1614,7 @@ fn a_raw_view_past_the_sampler_limit_is_its_own_separate_texture() { let text = std::fs::read_to_string(path).expect("profile"); let mut desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); desc.limits.max_per_stage_descriptor_samplers = 1; - let dev = Device::new(desc, EXACT_SAMPLING).expect("device"); + let dev = Device::new(desc, DevicePolicy::default()).expect("device"); let (_, m) = typed_module_with(&bc, "k", dev.profile(), &inputs(true)).expect("module"); let (mut textures, mut samplers) = (Vec::new(), Vec::new()); for g in m.globals() { diff --git a/crates/metal2vulkan/src/tests/engine_swizzled_storage.rs b/crates/metal2vulkan/src/tests/engine_swizzled_storage.rs index c5d0468b2..798beb89c 100644 --- a/crates/metal2vulkan/src/tests/engine_swizzled_storage.rs +++ b/crates/metal2vulkan/src/tests/engine_swizzled_storage.rs @@ -300,7 +300,7 @@ declare void @air.write_texture_2d.{suffix}(ptr addrspace(1), <2 x i32>, {vec4}, /// Every committed profile, and `moltenvk-m3` and `lavapipe` without robustness, whose shader /// checks its reads and guards its writes. fn profiles() -> Vec<(String, DeviceProfile)> { - let mut out = crate::spirv::testing::committed_exact_profiles().expect("profiles"); + let mut out = crate::spirv::testing::committed_profiles().expect("profiles"); let all = [ VkFeature::RobustImageAccess, VkFeature::RobustImageAccess2, @@ -705,7 +705,7 @@ fn devices() -> Vec<(String, Device)> { let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); out.push(( stem, - Device::new(desc, crate::pipeline::testing::EXACT_SAMPLING).expect("device"), + Device::new(desc, crate::device::DevicePolicy::default()).expect("device"), )); } out.sort_by(|a, b| a.0.cmp(&b.0)); @@ -865,14 +865,6 @@ fn a_storage_slot_bound_to_a_swizzled_texture_joins_the_variant() { ); } -/// The value `plan` binds for `key`, which the function reads from its push field. -fn pushed_word(plan: &crate::bind::BindingPlan, key: SpecKey) -> u32 { - let v = plan - .specialized_value(key) - .unwrap_or_else(|| panic!("no {key:?} value")); - u32::try_from(v).expect("a u32") -} - /// The value `plan` specializes `pipeline`'s constant `key` to. fn spec_word(pipeline: &ComputePipeline, plan: &crate::bind::BindingPlan, key: SpecKey) -> u32 { let id = pipeline @@ -901,14 +893,13 @@ fn spec_word(pipeline: &ComputePipeline, plan: &crate::bind::BindingPlan, key: S /// view's swizzle would move a channel's code onto another channel's lane before the function /// converts it by its own code scale: the variant's pipeline plans the same key for the same /// shape, binds the view unswizzled for the function to swizzle (`shader_swizzle`, the -/// unswizzled texture's mapping), specializes the slot's `TextureSwizzle` to the swizzle's word, and keeps the class's -/// packed field (`TexelFormat`, which a swizzled view's class drops). A swizzle that reads every +/// unswizzled texture's mapping) and specializes the slot's `TextureSwizzle` to the swizzle's word. +/// A swizzle that reads every /// texel as none does (`RGB1` of `B5G6R5Unorm`, whose alpha reads 1) leaves the variant, and a /// device with Metal's own sampler keeps the view's swizzle. On every committed profile that /// holds the format. #[test] fn a_sampled_slot_bound_to_a_swizzled_packed_texture_swizzles_in_its_function() { - use crate::metal::texel_format::TexelFormat; let gbar = C::new(S::Green, S::Blue, S::Alpha, S::Red); let rgb1 = C::new(S::Red, S::Green, S::Blue, S::One); let Some(bc) = assemble("packed read", &read_kernel(Texel::Float, "read", 0)) else { @@ -982,11 +973,6 @@ fn a_sampled_slot_bound_to_a_swizzled_packed_texture_swizzles_in_its_function() assert_eq!(v.components, view(&own).components, "{what}"); let word = spec_word(&variant, &again, SpecKey::TextureSwizzle(SLOT)); assert_eq!(word, gbar.word(), "{what}"); - let class = pushed_word(&again, SpecKey::TexelFormat(SLOT)); - assert!( - TexelFormat(class).packed_exact(), - "{what}: class {class:#x}" - ); if pf == PixelFormat::B5G6R5Unorm { let own = plain .plan(&dev, &state(facts(pf, rgb1)).shape()) @@ -1003,13 +989,10 @@ fn a_sampled_slot_bound_to_a_swizzled_packed_texture_swizzles_in_its_function() /// sampler) of a swizzled packed normalized texture joins the variant as a read does, on every /// committed profile without Metal's own sampler: its combined image's view takes no swizzle /// (`shader_swizzle`, the unswizzled texture's mapping), the variant plans the same key again and -/// specializes the slot's swizzle and a class with the packed field. With Metal's own sampler the -/// view keeps the swizzle. (The device lane `extended_swizzles` found the samples and gathers -/// keeping the device's widening before this.) +/// specializes the slot's swizzle. With Metal's own sampler the view keeps the swizzle. #[test] fn a_combined_sampler_of_a_swizzled_packed_texture_swizzles_in_its_function() { use crate::bind::{BoundSampler, ImageSource, SamplerDescriptor}; - use crate::metal::texel_format::TexelFormat; let gbar = C::new(S::Green, S::Blue, S::Alpha, S::Red); let Some(bc) = (match llvm_assemble(&engine_dir().join("fpv_swizzled_reads.ll")) { Ok(b) => Some(b), @@ -1108,11 +1091,6 @@ fn a_combined_sampler_of_a_swizzled_packed_texture_swizzles_in_its_function() { assert_eq!(v.components, view(&own).components, "{what}"); let word = spec_word(&variant, &again, SpecKey::TextureSwizzle(SLOT)); assert_eq!(word, gbar.word(), "{what}"); - let class = pushed_word(&again, SpecKey::TexelFormat(SLOT)); - assert!( - TexelFormat(class).packed_exact(), - "{what}: class {class:#x}" - ); joined += 1; } } diff --git a/crates/metal2vulkan/src/tests/engine_texture_interp.rs b/crates/metal2vulkan/src/tests/engine_texture_interp.rs index 4845d7f03..ceee2b2ea 100644 --- a/crates/metal2vulkan/src/tests/engine_texture_interp.rs +++ b/crates/metal2vulkan/src/tests/engine_texture_interp.rs @@ -56,7 +56,7 @@ fn without(stem: &str, drop: &[VkFeature]) -> DeviceProfile { for f in drop { desc.features.remove(f); } - Device::new(desc, crate::pipeline::testing::EXACT_SAMPLING) + Device::new(desc, crate::device::DevicePolicy::default()) .expect("device") .profile() .clone() @@ -64,7 +64,7 @@ fn without(stem: &str, drop: &[VkFeature]) -> DeviceProfile { /// Every committed profile, and two without any robustness (so the shader contains itself). fn profiles() -> Vec<(String, DeviceProfile)> { - let mut out = crate::spirv::testing::committed_exact_profiles().expect("profiles"); + let mut out = crate::spirv::testing::committed_profiles().expect("profiles"); let all = [ VkFeature::RobustImageAccess, VkFeature::RobustImageAccess2, @@ -533,13 +533,17 @@ fn short_texels_sign_extend_and_half_reads_round() { assert!(ran > 0); } -/// A `half` read converts its texel by the bound format's class, the slot's `TexelFormat` -/// specialization: a 32-bit float texel to nearest even, half denormals kept; a 16-bit normalized -/// texel's code value `c / 65535` correctly rounded, where rounding the `f32` value would round -/// twice (`65455` and `65519`); a format whose conversion is not measured (the default) takes every -/// other `half` texel's exact rounding, which keeps a half denormal. +/// A `half` read on a profile with Metal's own sampler (`VkProperty::MetalSampler`) converts its +/// texel by the bound format's class, the slot's `TexelFormat` specialization: a 32-bit float +/// texel to nearest even, half denormals kept; a 16-bit normalized texel's code value `c / 65535` +/// correctly rounded, where rounding the `f32` value would round twice (`65455` and `65519`); a +/// format whose conversion is not measured (the default) takes every other `half` texel's exact +/// rounding, which keeps a half denormal. On any other profile the read is the device's conversion +/// of its `f32` texel, to nearest even here, with no class. Both record +/// `PrecisionNote::HalfTexelConversion`. #[test] fn half_reads_convert_by_the_bound_format() { + use crate::device::requirements::VkProperty; use crate::metal::texel_format::texel_format; use crate::metal::PixelFormat; use crate::pipeline::artifact::PrecisionNote; @@ -573,8 +577,14 @@ fn half_reads_convert_by_the_bound_format() { let Some((plan, m)) = module(&bc, "short_texels", &stem, &p) else { continue; }; - assert!( + let metal = p + .fields() + .enabled + .properties + .contains(&VkProperty::MetalSampler); + assert_eq!( plan.facts.contains(&RuntimeFact::TexelFormat { slot }), + metal, "{stem}" ); assert!( @@ -582,6 +592,9 @@ fn half_reads_convert_by_the_bound_format() { "{stem}" ); for (class, texel, want) in cases { + if class.is_some() && !metal { + continue; + } let s = Image::new(texture(0), [2, 2, 1], 1, 1, 1); let d = Image::new(texture(1), [2, 2, 1], 1, 1, 1); let mut h = Image::new(texture(2), [4, 4, 2], 1, 2, 1); @@ -686,9 +699,11 @@ fn half_reads_keep_subnormals_zeros_infinities_and_nans() { assert!(ran > 0); } -/// A depth read is the texel's first component; a multisampled read reads its sample. +/// A depth read is the texel's first component, the device's value with no class of the bound +/// format; a multisampled read reads its sample. #[test] fn depth_and_multisample_reads_read_their_texel() { + use crate::pipeline::facts::RuntimeFact; let Some(bc) = fixture() else { return; }; @@ -697,6 +712,13 @@ fn depth_and_multisample_reads_read_their_texel() { let Some((plan, m)) = module(&bc, "depth_ms", &stem, &p) else { continue; }; + assert!( + !plan + .facts + .iter() + .any(|f| matches!(f, RuntimeFact::TexelFormat { .. })), + "{stem}" + ); let mut dp = Image::new(texture(0), [2, 2, 1], 1, 1, 1); dp.texels[0] = [fl(0.75), fl(9.0), fl(9.0), fl(9.0)]; let mut ms = Image::new(texture(1), [2, 2, 1], 1, 1, 4); @@ -713,73 +735,6 @@ fn depth_and_multisample_reads_read_their_texel() { assert!(ran > 0); } -/// A depth read with a `float` result converts its texel by the bound format's class, the slot's -/// `TexelFormat` specialization, on a profile without Metal's own sampler: a `Depth16Unorm` -/// texel the device gives as its code times the reciprocal (lavapipe) reads `c / 65535` -/// correctly rounded, Metal's, and a `Depth32Float` texel reads as given. On -/// a profile with Metal's own sampler the device's value is Metal's, and the read takes no class. -#[test] -fn a_depth_read_converts_by_the_bound_format() { - use crate::device::requirements::VkProperty; - use crate::metal::texel_format::texel_format; - use crate::metal::PixelFormat; - use crate::pipeline::facts::RuntimeFact; - use crate::pipeline::sym::{SlotClass, SlotRef}; - let Some(bc) = fixture() else { - return; - }; - let slot = SlotRef { - stage: Stage::Kernel, - class: SlotClass::Texture, - index: 0, - }; - // A code whose reciprocal product is not its quotient. - let code = (1..65535u16) - .find(|&c| f32::from(c) * (1.0 / 65535.0) != f32::from(c) / 65535.0) - .expect("a code the reciprocal misses"); - let reciprocal = f32::from(code) * (1.0 / 65535.0); - let metal = f32::from(code) / 65535.0; - let mut ran = 0; - for (stem, p) in profiles() { - let Some((plan, m)) = module(&bc, "depth_ms", &stem, &p) else { - continue; - }; - let metal_sampler = p - .fields() - .enabled - .properties - .contains(&VkProperty::MetalSampler); - assert_eq!( - plan.facts.contains(&RuntimeFact::TexelFormat { slot }), - !metal_sampler, - "{stem}" - ); - if metal_sampler { - continue; - } - for (pf, texel, want) in [ - (PixelFormat::Depth16Unorm, reciprocal, metal), - (PixelFormat::Depth32Float, reciprocal, reciprocal), - ] { - let mut dp = Image::new(texture(0), [2, 2, 1], 1, 1, 1); - dp.texels[0] = [fl(texel), fl(9.0), fl(9.0), fl(9.0)]; - let ms = Image::new(texture(1), [2, 2, 1], 1, 1, 4); - let mut res = resources(&plan, &[vec![0; 8]]); - res.spec - .insert(SpecKey::TexelFormat(slot), u64::from(texel_format(pf).0)); - res.spec.insert( - SpecKey::PlainHalfTexels(slot), - u64::from(texel_format(pf).plain_on_metal_sampler()), - ); - let (bufs, _) = run_both(&m, &res, &[dp, ms], [1, 1, 1]) - .unwrap_or_else(|e| panic!("{stem}: {e:?}")); - assert_eq!(words(&bufs[0])[0], fl(want), "{stem} {pf:?} code {code}"); - } - ran += 1; - } - assert!(ran > 0); -} - /// Without containment of its own, an access outside the image is the interpreter's trap, never a /// neighbouring texel: a robust profile leaves out-of-range accesses to the device. #[test] diff --git a/crates/metal2vulkan/src/tests/engine_vertex_variants.rs b/crates/metal2vulkan/src/tests/engine_vertex_variants.rs index 092dfcc6b..b735a1fa7 100644 --- a/crates/metal2vulkan/src/tests/engine_vertex_variants.rs +++ b/crates/metal2vulkan/src/tests/engine_vertex_variants.rs @@ -21,10 +21,9 @@ //! attribute's stage. `link::vertex::narrow_float_of_f32_reads` keeps it out of the projection //! there, and `a_half_read_compiles_one_module_for_the_whole_sweep` holds the projections and //! the modules at the same count. -//! - **one module per pulled format.** A format the fixed-function path cannot fetch, or one the -//! profile asks the shader to convert (`VertexNormalizedPolicy::Exact`), is decoded in the -//! shader, and each decode is its own code. Necessary, and the count of it is what the exact -//! form costs: 2 modules against 21 over the 45-format sweep. +//! - **one module per pulled format.** A format the fixed-function path cannot fetch is decoded in +//! the shader, and each decode is its own code. Necessary: no format of the 45-format sweep is +//! pulled on the suite's venue. //! - **the step function: nothing, where the device fetches it.** Metal's constant step is a //! Vulkan binding of divisor 0 and stride 0 (`metal::vertex::attribute_fetch`, //! `link::vertex::binding_stride`), which is `VertexAttribute` and `VertexBinding` state and @@ -39,7 +38,7 @@ use std::collections::{BTreeMap, BTreeSet}; use crate::budget::SPIRV_WORDS; -use crate::device::{DevicePolicy, DeviceProfile, VertexNormalizedPolicy}; +use crate::device::{DevicePolicy, DeviceProfile}; use crate::library::FunctionConstantValues; use crate::metal::{VertexFormat, VertexStepFunction}; use crate::pipeline::compile::{compile_bitcode, EntryRef}; @@ -81,16 +80,6 @@ fn prof() -> DeviceProfile { profile(PROFILE, DevicePolicy::default()).expect("committed profile") } -/// The same profile under Metal's own normalized vertex conversion -/// (`VertexNormalizedPolicy::Exact`, which `DevicePolicy::exact_answers` selects). -fn exact_prof() -> DeviceProfile { - let policy = DevicePolicy { - vertex_normalized: VertexNormalizedPolicy::Exact, - ..DevicePolicy::default() - }; - profile(PROFILE, policy).expect("committed profile") -} - /// Every format of the SDK table a float-class attribute can read, as `cases::vertex_formats` /// selects them: all but `Invalid` and the eight 32-bit integer formats, which reach the shader as /// integers and need an integer-declared attribute. @@ -203,31 +192,6 @@ fn count(bc: &[u8], p: &DeviceProfile, entry: &str, step: VertexStepFunction) -> } } -/// The normalized formats, whose conversion `VertexNormalizedPolicy::Exact` moves into the -/// shader and the default leaves to fixed-function vertex input: the 8- and 16-bit `Normalized` -/// formats of either sign, the BGRA one, and the two packed words. -const NORMALIZED: [&str; 19] = [ - "MTLVertexFormatUCharNormalized", - "MTLVertexFormatUChar2Normalized", - "MTLVertexFormatUChar3Normalized", - "MTLVertexFormatUChar4Normalized", - "MTLVertexFormatUChar4Normalized_BGRA", - "MTLVertexFormatCharNormalized", - "MTLVertexFormatChar2Normalized", - "MTLVertexFormatChar3Normalized", - "MTLVertexFormatChar4Normalized", - "MTLVertexFormatUShortNormalized", - "MTLVertexFormatUShort2Normalized", - "MTLVertexFormatUShort3Normalized", - "MTLVertexFormatUShort4Normalized", - "MTLVertexFormatShortNormalized", - "MTLVertexFormatShort2Normalized", - "MTLVertexFormatShort3Normalized", - "MTLVertexFormatShort4Normalized", - "MTLVertexFormatInt1010102Normalized", - "MTLVertexFormatUInt1010102Normalized", -]; - /// `vertex-format-float4`'s own sweep under the default: the device fetches every one of the 45 /// formats in fixed function, and the whole sweep is **two** modules -- one per `narrow_float`, /// which is the only thing of the format the module's instructions name. @@ -264,56 +228,6 @@ fn a_half_read_compiles_one_module_for_the_whole_sweep() { ); } -/// Under `VertexNormalizedPolicy::Exact` every normalized format is pulled and divided in the -/// shader, one module each: both forms are kept and the switch is what picks between them. The -/// count is the exact form's cost, and `NORMALIZED` is exactly what moves. -#[test] -fn metals_own_normalized_conversion_pulls_every_normalized_format() { - let Some(bc) = fixture() else { return }; - let p = exact_prof(); - let float4 = count(&bc, &p, TO_FLOAT4, VertexStepFunction::PerVertex); - let mut pulled = float4.pulled.clone(); - pulled.sort_unstable(); - let mut expected = NORMALIZED; - expected.sort_unstable(); - assert_eq!( - pulled, expected, - "the formats the shader pulls under VertexNormalizedPolicy::Exact" - ); - assert_eq!( - (float4.projections, float4.modules), - (2 + NORMALIZED.len(), 2 + NORMALIZED.len()), - "projections and modules of {} creations", - float4.creations - ); - let half4 = count(&bc, &p, TO_HALF4, VertexStepFunction::PerVertex); - assert_eq!( - (half4.projections, half4.modules), - (1 + NORMALIZED.len(), 1 + NORMALIZED.len()), - "the `half` read keeps its one fixed-function module beside them" - ); - assert_eq!( - count(&bc, &prof(), TO_FLOAT4, VertexStepFunction::PerVertex).pulled, - Vec::<&str>::new(), - "the default fetches every format of the sweep in fixed function" - ); -} - -/// `DevicePolicy::exact_answers` selects Metal's normalized vertex conversion, so the exact form -/// is reached by the one switch the owner's rule names and not field by field alone. -#[test] -fn exact_answers_selects_metals_normalized_vertex_conversion() { - assert_eq!( - DevicePolicy::default().exact_answers().vertex_normalized, - VertexNormalizedPolicy::Exact - ); - assert_eq!( - DevicePolicy::default().vertex_normalized, - VertexNormalizedPolicy::Device, - "the fast form is the default" - ); -} - /// `narrow_float` is not key data of a `half`-declared attribute: the module compiled with the bit /// set is the module compiled without it, word for word, for every narrow-float format the device /// fetches in fixed function. The `float4` entry is the control: there the two differ. diff --git a/crates/metal2vulkan/src/tests/engine_linear_half/in_place.rs b/crates/metal2vulkan/src/tests/engine_ycbcr_in_place.rs similarity index 54% rename from crates/metal2vulkan/src/tests/engine_linear_half/in_place.rs rename to crates/metal2vulkan/src/tests/engine_ycbcr_in_place.rs index 432a3e839..e8ec7fe6a 100644 --- a/crates/metal2vulkan/src/tests/engine_linear_half/in_place.rs +++ b/crates/metal2vulkan/src/tests/engine_ycbcr_in_place.rs @@ -8,17 +8,357 @@ //! (`bind::YCbCrInPlace::words`). Each texel the samples read is Metal's (`ycbcr_convert`'s module //! docs: the luma code, the chroma pairs' 9/3/3/1 filter, the range's and the matrix's //! conversion), and a linear sample is Metal's filter of those steps on the grid `2048` -//! (`super::ycbcr`'s rule); a nearest sample is the texel at Metal's position. The texel buffer +//! (`metal_step`); a nearest sample is the texel at Metal's position. The texel buffer //! traps every fetch outside it, so each tap's elements lie within the planes. -use super::ycbcr::{metal_step, result_bits}; -use super::*; +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicU64, Ordering}; + use crate::bind::ycbcr_convert::{ycbcr_read, YCbCrCodes, YCbCrMatrix, YCbCrPlanes, YCbCrRange}; use crate::bind::YCbCrInPlace; -use crate::lower::select::LowerInputs; +use crate::device::profile::DeviceProfile; +use crate::device::DevicePolicy; +use crate::lower::select::{LowerInputs, Plan}; use crate::metal::format::ycbcr_format; +use crate::metal::sampler::SamplerWord; +use crate::metal::{PixelFormat, SamplerAddressMode}; use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::testing::{compile_with, typed_module_with}; +use crate::pipeline::interface::PushLoc; +use crate::pipeline::sym::{ + Axis, PushField, ResourceKind, ResourceSlot, SlotClass, SlotRef, SpecKey, Stage, +}; +use crate::pipeline::testing::{ + compile_with, link_and_validate, llvm_assemble, profile, typed_module_with, AssembleError, +}; +use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Order, Resources}; +use crate::spirv::ir::{GlobalKind, TypedModule}; + +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"; + +/// Bitcode of the module `body` (after the AIR header), or `None` without `llvm-as`. +fn assemble(name: &str, body: &str) -> Option> { + static NEXT: AtomicU64 = AtomicU64::new(0); + let dir = std::env::temp_dir().join(format!( + "m2v-linear-half-{}-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed), + name.replace(' ', "-") + )); + std::fs::create_dir_all(&dir).expect("scratch"); + let ll = dir.join("k.ll"); + std::fs::write(&ll, format!("{HEADER}{body}")).expect("write"); + let r = llvm_assemble(&ll); + let _ = std::fs::remove_dir_all(&dir); + match r { + Ok(x) => Some(x), + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + None + } + Err(AssembleError::Rejected(why)) => panic!("{name}: {why}"), + } +} + +fn lavapipe() -> DeviceProfile { + profile("lavapipe", DevicePolicy::default()).expect("profile") +} + +fn m3() -> DeviceProfile { + profile("moltenvk-m3", DevicePolicy::default()).expect("profile") +} + +/// The words of `constexpr sampler(filter::linear, ...)`: minification and magnification +/// `filter` (AIR code: 0 nearest, 1 linear), mip filter `mip` (0 none, 2 linear), every axis +/// addressed by `address` (0 zero or border, 1 edge, 2 repeat, 3 mirrored repeat), `pixel` +/// coordinates, and border color code `border` (0 transparent black, 2 opaque white), with the +/// fields Apple's compiler writes for the rest (the `hlf_half_address` fixture's sampler). +fn sampler_words(filter: u64, mip: u64, address: u64, pixel: bool, border: u64) -> u64 { + const BASE: u64 = 0x007b_ff00_0008_0000; + BASE | address + | address << 3 + | address << 6 + | filter << 9 + | filter << 11 + | mip << 13 + | u64::from(pixel) << 15 + | border << 56 +} + +fn linear(address: u64, pixel: bool, border: u64) -> u64 { + sampler_words(1, 0, address, pixel, border) +} + +/// How a test kernel samples its `half` texture. +#[derive(Clone, Copy, Debug)] +enum Form { + /// `texture2d`: `t.sample(s, coord[tid], offset)` with constant `offset`. + Plain { offset: (i32, i32) }, + /// `texture2d` with `min_lod_clamp(1)`. + MinLodClamp, + /// `texture2d` with lane `tid`'s dynamic `int2` offset (buffer 2). + DynamicOffset, + /// `texture3d` at `float4` buffer 0's lane `tid`'s `xyz`, with constant `offset`. + ThreeD { offset: (i32, i32, i32) }, + /// `texture2d`: a `float` result. + Float, +} + +/// A kernel sampling texture slot 0 through sampler `sampler` (a constexpr sampler's words, or +/// `None` for the runtime `[[sampler(0)]]`) at `float2` buffer 0's lane `tid`, storing the +/// `half4` (`float4` for [`Form::Float`]) to buffer 1. +fn kernel(sampler: Option, form: Form) -> String { + kernel_of(sampler, form, matches!(form, Form::Float)) +} + +/// [`kernel`] with a `float` result when `float`, whatever the form. +fn kernel_of(sampler: Option, form: Form, float: bool) -> String { + let half = !float; + let (texel, vec4, size) = if half { + ("half", "<4 x half>", 8) + } else { + ("float", "<4 x float>", 16) + }; + let suffix = if half { "v4f16" } else { "v4f32" }; + let s = if sampler.is_some() { + "@__air_sampler_state" + } else { + "%s" + }; + let (tex_ty, name, args, call_args) = match form { + Form::Plain { offset: (ox, oy) } => ( + format!("texture2d<{texel}, sample>"), + "2d", + "ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32", + format!("<2 x float> %uv, i1 true, <2 x i32> , i1 false, float 0.0, float 0.0, i32 0"), + ), + Form::Float => ( + format!("texture2d<{texel}, sample>"), + "2d", + "ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32", + "<2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.0, float 0.0, i32 0".to_string(), + ), + Form::MinLodClamp => ( + format!("texture2d<{texel}, sample>"), + "2d", + "ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32", + "<2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.0, float 1.0, i32 0".to_string(), + ), + Form::DynamicOffset => ( + format!("texture2d<{texel}, sample>"), + "2d", + "ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32", + "<2 x float> %uv, i1 true, <2 x i32> %o, i1 false, float 0.0, float 0.0, i32 0".to_string(), + ), + Form::ThreeD { offset: (ox, oy, oz) } => ( + format!("texture3d<{texel}, sample>"), + "3d", + "ptr addrspace(1), ptr addrspace(2), <3 x float>, i1, <3 x i32>, i1, float, float, i32", + format!("<3 x float> %uvw, i1 true, <3 x i32> , i1 false, float 0.0, float 0.0, i32 0"), + ), + }; + let dynamic = matches!(form, Form::DynamicOffset); + let runtime = sampler.is_none(); + // Parameters after `out`: the offsets buffer, then the runtime sampler. + let mut params = String::new(); + let mut mds = Vec::new(); + let mut next = 3; + if dynamic { + params.push_str(", ptr addrspace(1) %offs"); + mds.push(format!("!{{i32 {next}, !\"air.buffer\", !\"air.location_index\", i32 2, i32 1, !\"air.read\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 8, !\"air.arg_type_align_size\", i32 8, !\"air.arg_type_name\", !\"int2\", !\"air.arg_name\", !\"offs\"}}")); + next += 1; + } + if runtime { + params.push_str(", ptr addrspace(2) %s"); + mds.push(format!("!{{i32 {next}, !\"air.sampler\", !\"air.location_index\", i32 0, i32 1, !\"air.arg_type_name\", !\"sampler\", !\"air.arg_name\", !\"s\"}}")); + next += 1; + } + mds.push(format!("!{{i32 {next}, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"tid\"}}")); + let first = 7; + let arg_mds: Vec = (0..mds.len()).map(|i| format!("!{}", first + i)).collect(); + let tail: String = mds + .iter() + .enumerate() + .map(|(i, m)| format!("!{} = {m}\n", first + i)) + .collect(); + let load_offset = if dynamic { + " %po = getelementptr inbounds <2 x i32>, ptr addrspace(1) %offs, i64 %i\n %o = load <2 x i32>, ptr addrspace(1) %po, align 8\n" + } else { + "" + }; + let state = match sampler { + Some(w) => format!( + "@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 {w}, i64 0], align 8\n\n" + ), + None => String::new(), + }; + let (states, state_md) = if sampler.is_some() { + ( + "!air.sampler_states = !{!6}\n", + "!6 = !{!\"air.sampler_state\", ptr addrspace(2) @__air_sampler_state}\n", + ) + } else { + ("", "") + }; + let half_name = if half { "half4" } else { "float4" }; + // A 3D sample's coordinates are a `float4`'s `xyz`, every other's a `float2`. + let (load_coord, coord_size, coord_name) = if matches!(form, Form::ThreeD { .. }) { + ( + " %p = getelementptr inbounds <4 x float>, ptr addrspace(1) %c, i64 %i\n %c4 = load <4 x float>, ptr addrspace(1) %p, align 16\n %uvw = shufflevector <4 x float> %c4, <4 x float> zeroinitializer, <3 x i32> \n", + 16, + "float4", + ) + } else { + ( + " %p = getelementptr inbounds <2 x float>, ptr addrspace(1) %c, i64 %i\n %uv = load <2 x float>, ptr addrspace(1) %p, align 8\n", + 8, + "float2", + ) + }; + format!( + r#"{state}define void @k(ptr addrspace(1) %t, ptr addrspace(1) %c, ptr addrspace(1) %out{params}, i32 %tid) {{ + %i = zext i32 %tid to i64 +{load_coord}{load_offset} %r = call {{ {vec4}, i8 }} @air.sample_texture_{name}.{suffix}(ptr addrspace(1) %t, ptr addrspace(2) {s}, {call_args}) + %v = extractvalue {{ {vec4}, i8 }} %r, 0 + %q = getelementptr inbounds {vec4}, ptr addrspace(1) %out, i64 %i + store {vec4} %v, ptr addrspace(1) %q, align {size} + ret void +}} + +declare {{ {vec4}, i8 }} @air.sample_texture_{name}.{suffix}({args}) + +!air.kernel = !{{!0}} +{states}!0 = !{{ptr @k, !1, !2}} +!1 = !{{}} +!2 = !{{!3, !4, !5, {arg_mds}}} +!3 = !{{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"{tex_ty}", !"air.arg_name", !"t"}} +!4 = !{{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 {coord_size}, !"air.arg_type_align_size", i32 {coord_size}, !"air.arg_type_name", !"{coord_name}", !"air.arg_name", !"c"}} +!5 = !{{i32 2, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 {size}, !"air.arg_type_align_size", i32 {size}, !"air.arg_type_name", !"{half_name}", !"air.arg_name", !"out"}} +{state_md}{tail}"#, + arg_mds = arg_mds.join(", "), + ) +} + +const TEXTURE: SlotRef = SlotRef { + stage: Stage::Kernel, + class: SlotClass::Texture, + index: 0, +}; + +/// `res` with each `SamplerState` specialization artifact `a` declares valued by runtime sampler +/// word `word`, masked by its fields; unchanged without a word. +fn with_word( + mut res: Resources, + a: &crate::library::FunctionArtifact, + word: Option, +) -> Resources { + let Some(word) = word else { + return res; + }; + let mut declared = 0; + for key in a.interface.read_keys() { + if let SpecKey::SamplerState { fields, .. } = key { + res.spec.insert(key, u64::from(word & fields)); + declared += 1; + } + } + assert_eq!( + declared, 1, + "the runtime sampler's `SamplerState` specialization" + ); + res +} + +/// `m` over `groups` one-thread threadgroups with `image` bound, in both scheduling orders, which +/// must agree: buffer 1's `half4`s (`float4`s unless `half`), as bits. +fn run(m: &TypedModule, res: &Resources, image: &Image, groups: u32, half: bool) -> Vec<[u32; 4]> { + run_images(m, res, std::slice::from_ref(image), groups, half) +} + +/// [`run`] with `images` bound. +fn run_images( + m: &TypedModule, + res: &Resources, + images: &[Image], + groups: u32, + half: bool, +) -> Vec<[u32; 4]> { + let mut outs = Vec::new(); + for order in [Order::Forward, Order::Reverse] { + let cfg = Config { + workgroups: [groups, 1, 1], + order, + ..Config::default() + }; + let (o, _) = run_with_images(m, &cfg, res.clone(), images.to_vec()) + .unwrap_or_else(|e| panic!("interpreter: {e:?}")); + outs.push(o.buffers); + } + assert_eq!(outs[0], outs[1], "the scheduling orders disagree"); + let size = if half { 2 } else { 4 }; + outs[0][1] + .chunks_exact(4 * size) + .map(|c| { + std::array::from_fn(|k| { + let mut b = [0u8; 4]; + b[..size].copy_from_slice(&c[size * k..size * (k + 1)]); + u32::from_le_bytes(b) + }) + }) + .collect() +} + +/// A deterministic source: a 64-bit LCG. +struct Lcg(u64); + +impl Lcg { + fn next(&mut self) -> u64 { + self.0 = self + .0 + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + self.0 >> 11 + } +} + +/// Metal's step of a 2D linear sample of a YCbCr format: the taps' steps `k` (`(i, j)`, `(i + 1, +/// j)`, `(i, j + 1)`, `(i + 1, j + 1)`) under the fractions `a` and `b` in 1/256 steps, a merged +/// axis's 0; a signed term and sum floored. +fn metal_step(taps: [i64; 4], a: i64, b: i64) -> i64 { + let w = [(256 - a) * (256 - b), a * (256 - b), (256 - a) * b, a * b]; + let t: i64 = taps.iter().zip(w).map(|(k, w)| (k * w) >> 7).sum(); + (t + 256) >> 9 +} + +/// The `half` bits of `k / d` (`d` a power of two, `1 <= |k| / d`'s binade above `2^-14`, or `k +/// = 0`), rounded with ties away from zero. +fn half_away(k: i64, d: i64) -> u16 { + if k == 0 { + return 0; + } + let sign = if k < 0 { 0x8000 } else { 0 }; + let m = k.unsigned_abs(); + let lead = i64::from(63 - m.leading_zeros()); + let e = lead - i64::from(d.trailing_zeros()); + assert!(e >= -14, "{k} / {d} is below the normal halves"); + // The significand's 11 bits: the magnitude rounded half up there, a carry raising `e`. + let shift = lead - 10; + let q = match shift > 0 { + true => (m + (1 << (shift - 1))) >> shift, + false => m << -shift, + }; + let (q, e) = if q == 2048 { (1024, e + 1) } else { (q, e) }; + sign | ((e + 15) as u16) << 10 | (q as u16 - 1024) +} + +/// The result lanes of steps `steps` on grid `d` (alpha 1): `k / d` as `f32` bits (exact), or as +/// `half` bits rounded with ties away from zero when `half`. +fn result_bits(steps: [i64; 3], half: bool, d: i64) -> [u32; 4] { + let lanes = [steps[0], steps[1], steps[2], d]; + lanes.map(|k| match half { + true => u32::from(half_away(k, d)), + false => (k as f32 / d as f32).to_bits(), + }) +} /// The texture's width and height: odd, so the chroma plane's last pair serves one column and one /// row alone. @@ -426,7 +766,7 @@ fn a_slot_states_the_in_place_form_where_it_reads_only_it() { ("moltenvk-m3", true), ("nvidia-rtx5080-laptop", false), ] { - let p = profile(stem, EXACT_SAMPLING).expect("profile"); + let p = profile(stem, DevicePolicy::default()).expect("profile"); assert_eq!(p.fields().ycbcr_in_place, takes, "{stem}"); let what = format!("{name} on {stem}"); let (plan, _) = typed_module_with(&bc, "k", &p, &inputs(false)) diff --git a/crates/metal2vulkan/src/tests/fast_paths.rs b/crates/metal2vulkan/src/tests/fast_paths.rs index 71c4d8404..7d199b78c 100644 --- a/crates/metal2vulkan/src/tests/fast_paths.rs +++ b/crates/metal2vulkan/src/tests/fast_paths.rs @@ -1,15 +1,14 @@ //! docs/FAST-PATHS.md, the ledger of the defaults that trade exactness against Metal for making //! time, stays accurate by construction: it names every accuracy choice of `DevicePolicy` with each //! of its values, as `field = Type::Value`, and every precision note a fast default, a -//! not-yet-built accurate form, an opt-in or a listed device gap records, with its degrade code; +//! not-yet-built accurate form or a listed device gap records, with its degrade code; //! and it names no policy value that no longer exists. The lists below are exhaustive matches: a //! field, a policy value or a precision note added to the crate fails to compile here until it is //! classed, and so reaches the ledger. use crate::device::{ - BatchOrderPolicy, CompletionPolicy, DecodedTexelsPolicy, DevicePolicy, HeapCompressionPolicy, - HostPageTexturePolicy, RenderLoweringPolicy, SamplingPolicy, TexelConversionPolicy, - Unorm8LinearFilterPolicy, VertexNormalizedPolicy, YCbCrFilterPolicy, + BatchOrderPolicy, CompletionPolicy, DevicePolicy, HeapCompressionPolicy, HostPageTexturePolicy, + RenderLoweringPolicy, }; use crate::pipeline::PrecisionNote; use std::collections::BTreeSet; @@ -59,16 +58,9 @@ fn choices() -> Vec { containment: _, isolation: _, // The accuracy choices, below. - unorm8_linear_filter: _, - sampling: _, - ycbcr_filter: _, - texel_conversion: _, - vertex_normalized: _, - // The runtime's: 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. - decoded_texels: _, + // The runtime's: 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. heap_compression: _, completion: _, batch_order: _, @@ -76,12 +68,6 @@ fn choices() -> Vec { host_page_textures: _, } = p; vec![ - choice!(p.unorm8_linear_filter: Unorm8LinearFilterPolicy { Exact, DeviceWithinOneCode }), - choice!(p.sampling: SamplingPolicy { NativeDevice, Exact }), - choice!(p.ycbcr_filter: YCbCrFilterPolicy { Device, Exact }), - choice!(p.texel_conversion: TexelConversionPolicy { Device, Exact }), - choice!(p.vertex_normalized: VertexNormalizedPolicy { Device, Exact }), - choice!(p.decoded_texels: DecodedTexelsPolicy { Compact, Exact }), choice!(p.heap_compression: HeapCompressionPolicy { Compressed, Uncompressed }), choice!(p.completion: CompletionPolicy { Grouped, Exact }), choice!(p.batch_order: BatchOrderPolicy { Ends, Exact }), @@ -97,8 +83,6 @@ enum Ledger { FastDefault, /// The default's form where the accurate one is not built yet: a row of the first table. NotBuilt, - /// Recorded only under a non-default opt-in: the list of switches whose default is Metal's. - OptIn, /// A device gap, no speed choice: a row of the second table. DeviceGap, /// None of these: docs/API.md section 9 states it. @@ -121,16 +105,12 @@ macro_rules! notes { fn notes() -> Vec<(&'static str, Ledger)> { notes! { FastDefault: [ - DeviceSampling, - DeviceTexelConversion, - HalfTexelConversion, ], NotBuilt: [ ExtendedRangeBlendSource, ExtendedRangeFloatBlendSource, BicubicFilterArithmetic, ], - OptIn: [DeviceUnorm8LinearFilter], DeviceGap: [ NativeTranscendentals, NativeDivision, @@ -138,7 +118,6 @@ fn notes() -> Vec<(&'static str, Ledger)> { NativeDot, NativeMix, DeviceDenormals, - DeviceTexelDenormals, RestrictedDepthRange, DeviceSignedZeroInfNan, DeviceInterpolation, @@ -152,6 +131,9 @@ fn notes() -> Vec<(&'static str, Ledger)> { HalfOutputPrecision, NativeHalfConversion, NativeHalfQuantize, + DeviceSampling, + DeviceTexelConversion, + HalfTexelConversion, F16FmaDoubleRounding, F16IntConvDoubleRounding, GradFromBias, @@ -173,10 +155,7 @@ fn notes() -> Vec<(&'static str, Ledger)> { HalfSampleFilter, SrgbTexelDecode, FloatSampleFilter, - DeviceGatherFootprint, - CubeFaceReciprocal, QuadsCountedBeforeDiscard, - DeviceDepthComparison, ViewBaseTexelOffset, DeviceColorConversion, QuadsSplitByClipping, @@ -326,9 +305,8 @@ fn the_ledger_names_only_choices_the_policy_has() { } } -/// The ledger names every precision note a fast default, a not-yet-built accurate form, an -/// opt-in or a listed device gap records, each with its degrade code, which docs/API.md's -/// catalogue lists. +/// The ledger names every precision note a fast default, a not-yet-built accurate form or a +/// listed device gap records, each with its degrade code, which docs/API.md's catalogue lists. #[test] fn the_ledger_names_every_note_of_its_rows_with_its_code() { let ledger = text("../../docs/FAST-PATHS.md"); @@ -364,23 +342,23 @@ fn the_ledger_names_every_note_of_its_rows_with_its_code() { #[test] fn the_ledger_readers_read_names_and_switches() { assert_eq!(code("NativeHalfConversion"), "native-half-conversion"); - assert_eq!( - code("DeviceUnorm8LinearFilter"), - "device-unorm8-linear-filter" - ); + assert_eq!(code("F16FmaDoubleRounding"), "f16-fma-double-rounding"); assert_eq!(code("DeviceSignedZeroInfNan"), "device-signed-zero-inf-nan"); - let text = "`sampling = SamplingPolicy::Exact` and `DevicePolicy::exact_answers()`, \ - `CompletionPolicy::Exact`."; + let text = "`completion = CompletionPolicy::Exact` and `DevicePolicy::exact_answers()`, \ + `BatchOrderPolicy::Ends`."; assert_eq!( policy_values(text), BTreeSet::from([ - "SamplingPolicy::Exact".to_owned(), - "CompletionPolicy::Exact".to_owned() + "CompletionPolicy::Exact".to_owned(), + "BatchOrderPolicy::Ends".to_owned() ]) ); assert_eq!( assignments(text), - BTreeSet::from([("sampling".to_owned(), "SamplingPolicy::Exact".to_owned())]) + BTreeSet::from([( + "completion".to_owned(), + "CompletionPolicy::Exact".to_owned() + )]) ); } @@ -457,24 +435,6 @@ fn the_runtime_s_render_lowering_choice_keys_no_profile() { } } -/// The runtime's choice of a carried texture's decoded twin (`decoded_texels`) moves no committed -/// profile's fingerprint: no profile carries it, so no translation follows it. -#[test] -fn the_runtime_s_decoded_texels_choice_keys_no_profile() { - use crate::spirv::testing::committed_profiles_with; - let codes = committed_profiles_with(DevicePolicy::UNTRUSTED).expect("profiles"); - let exact = committed_profiles_with(DevicePolicy { - decoded_texels: DecodedTexelsPolicy::Exact, - ..DevicePolicy::UNTRUSTED - }) - .expect("profiles"); - assert_eq!(codes.len(), exact.len()); - for ((stem, a), (other, e)) in codes.iter().zip(&exact) { - assert_eq!(stem, other); - assert_eq!(a.fingerprint(), e.fingerprint(), "{stem}"); - } -} - /// The runtime's choice of what holds a sampled texture over host pages (`host_page_textures`) /// moves no committed profile's fingerprint: no profile carries it, so no translation follows it. #[test] diff --git a/crates/metal2vulkan/src/tests/golden_hashes.rs b/crates/metal2vulkan/src/tests/golden_hashes.rs index e5643f1e2..76aafd693 100644 --- a/crates/metal2vulkan/src/tests/golden_hashes.rs +++ b/crates/metal2vulkan/src/tests/golden_hashes.rs @@ -47,10 +47,8 @@ //! A second table, `golden_hashes_exact.tsv`, pins the same cells of the fixtures that sample, //! gather or compute a level of detail (their source declares an `air.sample_texture*`, //! `air.gather_texture*` or `air.calculate_*` intrinsic) under every exact form -//! (`pipeline::testing::EXACT_SAMPLING`: Metal's sampler emulated, `SamplingPolicy::Exact`, and -//! `DevicePolicy::exact_answers`), whose output the default policy's native device sampling never -//! reaches. Its profiles' fingerprints are those of that policy. The bless writes both tables, -//! under the same rule. +//! (`DevicePolicy::exact_answers`). Its profiles' fingerprints are those of that policy. The bless +//! writes both tables, under the same rule. use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; @@ -65,7 +63,6 @@ use crate::metal::format::storage_image_choice; use crate::metal::{PixelFormat, VertexFormat}; use crate::pipeline::testing::{ engine_dir, fixtures_dir, link_standalone, llvm_assemble, metal_assemble, AssembleError, - EXACT_SAMPLING, }; use crate::pipeline::{ ColorAttachmentDescriptor, ComputePipelineDescriptor, FramebufferFetchInputs, @@ -101,9 +98,9 @@ const DEFAULT: Golden = Golden { const EXACT: Golden = Golden { table: "tests/golden_hashes_exact.tsv", title: "# Golden output hashes of the engine over the public fixtures that sample x the\n\ - # committed profiles under EXACT_SAMPLING, every exact form\n\ + # committed profiles under every exact form\n\ # (src/tests/golden_hashes.rs). Written by the bless; do not edit:\n", - policy: EXACT_SAMPLING, + policy: DevicePolicy::UNTRUSTED.exact_answers(), takes: samples, }; @@ -111,8 +108,7 @@ fn every(_: &str) -> bool { true } -/// Whether a fixture's source declares a sample, a gather or a level-of-detail query: the -/// intrinsics whose lowering `SamplingPolicy` chooses. +/// Whether a fixture's source declares a sample, a gather or a level-of-detail query. fn samples(text: &str) -> bool { [ "@air.sample_texture", @@ -1001,8 +997,7 @@ fn golden_hashes_match_the_table() { matches_the_table(DEFAULT, &devices, &observed); } -/// The fixtures that sample, under every exact form: the sampler's emulation, which the default -/// table's native device sampling does not reach. +/// The fixtures that sample, under every exact form. #[test] fn exact_golden_hashes_match_the_table() { let devices = devices(EXACT.policy); @@ -1137,18 +1132,11 @@ fn a_stale_cell_names_the_key_that_moved_and_not_an_unmoved_cell() { assert_eq!(d.changed, ["f.ll | main | a-gpu: was -> now"]); } -/// The exact table takes the fixtures whose sampling the policy changes, under the sampler's -/// emulation and Metal's other answers: its fingerprints are not the default table's. +/// The exact table takes the fixtures that sample, under Metal's exact answers: its fingerprints +/// are not the default table's. #[test] -fn the_exact_table_takes_the_sampling_fixtures_under_the_emulation() { - assert_eq!(EXACT.policy.sampling, crate::device::SamplingPolicy::Exact); - assert_eq!( - EXACT.policy, - DevicePolicy { - sampling: crate::device::SamplingPolicy::Exact, - ..DevicePolicy::default().exact_answers() - } - ); +fn the_exact_table_takes_the_sampling_fixtures_under_the_exact_answers() { + assert_eq!(EXACT.policy, DevicePolicy::default().exact_answers()); assert_eq!(DEFAULT.policy, DevicePolicy::default()); let all = fixture_paths(DEFAULT); let taken = fixture_paths(EXACT); diff --git a/crates/metal2vulkan/src/tests/mod.rs b/crates/metal2vulkan/src/tests/mod.rs index 71612cc8a..45681721d 100644 --- a/crates/metal2vulkan/src/tests/mod.rs +++ b/crates/metal2vulkan/src/tests/mod.rs @@ -34,10 +34,8 @@ mod engine_color_groups; mod engine_copy; mod engine_coverage_loop; mod engine_cross_class; -mod engine_cube_gather; mod engine_declared_varyings; mod engine_depth_range; -mod engine_device_level; mod engine_device_replay; mod engine_dispatch; mod engine_divergent_barriers; @@ -75,8 +73,6 @@ mod engine_indirect_commands; mod engine_kernel_lod; mod engine_kernel_stage_in; mod engine_lazy_operands; -mod engine_linear_cube; -mod engine_linear_half; mod engine_link; mod engine_linking; mod engine_matmul2d; @@ -119,7 +115,6 @@ mod engine_rotated_colors; mod engine_rotated_weights; mod engine_sampler; mod engine_sampler_completion; -mod engine_sampler_fetched; mod engine_sampler_tail; mod engine_sampler_unk; mod engine_selected_indices; @@ -172,6 +167,7 @@ mod engine_viewport_compensation; mod engine_volatile; mod engine_wide; mod engine_word_attachments; +mod engine_ycbcr_in_place; mod engine_zeroed_colors; mod env_registry; mod fast_paths; diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index 79d0467dd..622959b42 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -224,12 +224,6 @@ surface! { struct StageSimd N; enum ContainmentPolicy N; struct DevicePolicy N; - enum Unorm8LinearFilterPolicy N; - enum SamplingPolicy N; - enum YCbCrFilterPolicy N; - enum TexelConversionPolicy N; - enum VertexNormalizedPolicy N; - enum DecodedTexelsPolicy N; enum HeapCompressionPolicy N; enum CompletionPolicy N; enum BatchOrderPolicy N; diff --git a/docs/API.md b/docs/API.md index bbb2e5af1..ad9954446 100644 --- a/docs/API.md +++ b/docs/API.md @@ -90,13 +90,12 @@ compile does. `DevicePolicy::default()` is `DevicePolicy::UNTRUSTED`: Each records a precision note with its bound; on MoltenVK on an Apple GPU, whose `float` functions are Metal's own, they are Metal's answers, but for a NaN's bits where the device is not measured to answer Metal's. -- **Fast native forms off Apple's GPUs.** The device's own sampler (its filter of a two-plane - YCbCr texture among them) and texel conversions. Each records a precision note with its bound, - and each has an exact switch. The device's own `half` rounding and its blend of a `half` color - have none: each records its note. - `DevicePolicy::exact_answers()` turns on every exact form but sampling's, Metal's filter of a - two-plane YCbCr texture (`YCbCrFilterPolicy::Exact`) included; `sampling = - SamplingPolicy::Exact` emulates Metal's sampler too. +- **Fast native forms off Apple's GPUs.** The device's own sampler (its filter, footprint, level, + anisotropy, texel conversion and comparison, a two-plane YCbCr texture's filter among them), + with no switch: the device's answer is the contract, recorded as `PrecisionNote::DeviceSampling` + with its measured bound. The device's own `half` rounding and its blend of a `half` color have + no switch either: each records its note. + `DevicePolicy::exact_answers()` turns on every exact form the runtime offers. [FAST-PATHS.md](FAST-PATHS.md) lists every choice, its bound and the measured cost of its exact form. On MoltenVK on an Apple GPU, whose sampler and `float` functions are Metal's own, most of these choices change nothing. @@ -2085,15 +2084,13 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. record the GPU wrote while another state held the ID Metal runs that state (nothing, for a state of the other kind). - `metal2vulkan-degrade-ycbcr-filter-not-exact` (precision). `YCbCrFilterNotExact`: A pipeline - stage's filtered sample of a texture slot bound to a two-plane YCbCr texture does not take Metal's - exact filter of the format: the stage records `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). - Cost: the texels hold Metal's reads exactly, but the sample filters them as the device does, off + stage's filtered sample of a texture slot bound to a two-plane YCbCr texture, through Metal's own + sampler (MoltenVK), does not take Metal's exact filter of the format: the stage records + `PrecisionNote::HalfSampleFilter` or `FloatSampleFilter` under the slot's bound format. Cost: + the texels hold Metal's reads exactly, but the sample filters them as the device does, off the grid Metal sums the format's steps on, so a filtered result can miss Metal's by a step of that - grid or more. The slot takes Metal's filter only under `YCbCrFilterPolicy::Exact` (on MoltenVK - also under `SamplingPolicy::Exact`). Under the default a device that samples natively answers - the device's filter, `metal2vulkan-degrade-device-sampling`; on MoltenVK, Metal's own sampler + grid or more. A device that samples natively answers the device's filter, + `metal2vulkan-degrade-device-sampling`; on MoltenVK, Metal's own sampler filters the converted texels as an `RGBA16Float` or `RGBA32Float` texture's, within one step of the grid (a `half` result within one `half` ulp, measured in plain Metal on an Apple M3 Max under macOS 27.0.1 for `YCBCR8_420_2P` and its sRGB twin against such a texture of the same texels), @@ -2323,10 +2320,11 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. lavapipe): 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 in - the texels `DecodedTexelsPolicy` names (a PVRTC texture's, and an 8-bit ETC2 or EAC texture's, - 8-bit codes, exact under either: its sRGB form's slots decode them through Metal's table, and one - twin serves the views of the linear and sRGB forms; an ASTC sRGB texture's, its own 8-bit codes, - read the same way), decoded after each write into it as a BC + codes: an ASTC LDR texture's and an EAC 11-bit texture's each nearest Metal's value + (`decoded-texel-precision`); a PVRTC texture's, and an 8-bit ETC2 or EAC texture's, 8-bit codes, + exact (its sRGB form's slots decode them through Metal's table, and one twin serves the views of + the linear and sRGB forms); an ASTC sRGB texture's, its own 8-bit codes, read the same way. + It is decoded after each write into it as a BC texture's twin is (`decoded-block-twin`; a PVRTC texture's whole levels, since each texel's colors come from the blocks around it). An ASTC texture's first view in its other colour space (its sRGB form as LDR, or the other way) gives it a second twin of that form's decode, kept @@ -2335,20 +2333,20 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. implementation's rules: its texels' bytes lie in an `R8G8_UNORM` carrier, and its twin holds Metal's texels as 8-bit codes, exact (each texel's own green, its red and blue interpolated with the pair beside it), decoded in whole rows. Cost: 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 + 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; 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. - `metal2vulkan-degrade-decoded-texel-precision` (precision). `DecodedTexelPrecision`: A texture with an ASTC LDR decoded twin of 8-bit codes, or an EAC 11-bit one (`R11`, `RG11`) of 16-bit - normalized codes, under `DecodedTexelsPolicy::Compact`. Cost: a read, sample or gather of its + normalized codes. Cost: 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 normalized code to Metal's 11-bit value, at most half a 16-bit step - off it (Metal reads an EAC 11-bit channel as `c / 2047`, signed `c / 1023`). - `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, under either. + off it (Metal reads an EAC 11-bit channel as `c / 2047`, signed `c / 1023`). An ASTC sRGB + texture's twin holds Metal's own 8-bit codes, which its slots decode through Metal's table: + exact. - `metal2vulkan-degrade-shared-present-queue` (performance). `SharedPresentQueue`: A command queue made for presenting (`Device::new_command_queue_for_presenting`) on a device that reserved no `VkQueue` for presenting: its queue family has no queue past the ones the round robin takes @@ -2645,25 +2643,13 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. magnification filters, on a device that samples through Metal's own sampler (MoltenVK on Apple's GPU): no level clamp the device's sampler takes reads Metal's `NotMipmapped` footprint at `maxAnisotropy` 2 to 16, so the sample filters another anisotropic footprint than Metal's. -- `metal2vulkan-degrade-device-sample-level` (precision). `PrecisionNote::DeviceSampleLevel`: A - sample whose level the device's level arithmetic chooses, on a device that samples neither through - Metal's own sampler nor natively, of a texture other than a cube, without comparison: a fragment - function's implicit-level sample (its bias Metal's own reading within the device's - `maxSamplerLodBias`), a sample with explicit gradients, a fragment function's LOD query, and a - sample at an explicit level Metal's level rule is not handed on (an integer texture's, or 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. The device takes the level of detail by Vulkan's - rules, whose scale factor may be approximated, and rounds a level its own way; 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 where no sample-filter note records the sample: - nearest filters with a nearest mip filter (a constexpr sampler's, or a runtime sampler's where its - word states them), or an integer texture's sampler with a mip filter or filters that differ (an - argument buffer's sampler always). An extended-range texture's (`BGR10_XR`, `BGRA10_XR` and their - sRGB twins) fragment sample at an implicit level, or with explicit gradients, records it on every - device: its texels are read in the shader, at Vulkan's level of detail computed there and Metal's - level rule, where a constexpr sampler states a mip filter or a runtime sampler's word does. The - sample may read another level or filter than Metal's near a boundary, and the query answers the - device's level. +- `metal2vulkan-degrade-device-sample-level` (precision). `PrecisionNote::DeviceSampleLevel`: An + extended-range texture's (`BGR10_XR`, `BGRA10_XR` and their sRGB twins) fragment sample at an + implicit level, or with explicit gradients, on every device: its texels are read in the shader, at + Vulkan's level of detail computed there and Metal's level rule, where a constexpr sampler states a + mip filter or a runtime sampler's word does. The device takes the level of detail by Vulkan's + rules, whose scale factor may be approximated; Metal's level of detail from derivatives is not + measured. The sample may read another level or filter than Metal's near a boundary. - `metal2vulkan-degrade-unmeasured-fetch-blend` (precision). `PrecisionNote::UnmeasuredFetchBlend`: A fragment function reads a color attachment the pipeline blends, on a device that orders framebuffer fetch only through the pixel interlock (MoltenVK, RADV, ANV), of a format whose Metal @@ -2736,11 +2722,10 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. - `metal2vulkan-degrade-cube-gradient-footprint` (precision). `PrecisionNote::CubeGradientFootprint`: An explicit-gradient sample of a cube texture takes Metal's footprint in a form a Vulkan device reads alike, but for what is not reproduced. Cost: - off MoltenVK a sample the shader's emulation does not reach (a depth or comparison sample, an - argument buffer's texture or sampler, a runtime sampler outside its anisotropic variant) takes - the device's logarithm of Metal's footprint and, if anisotropic, the device's taps, so a level - or blend near a boundary can differ from Metal's. Where the shader takes Metal's level and taps - itself (`PrecisionNote::AnisotropicFilter`) this note is not recorded. On a MoltenVK release or + off MoltenVK the sample takes the device's logarithm of Metal's footprint and, if anisotropic, + the device's taps, so a level or blend near a boundary can differ from Metal's. Where the shader + takes Metal's level and taps itself (`PrecisionNote::AnisotropicFilter`) this note is not + recorded. On a MoltenVK release or GPU whose cube-gradient route is not measured, such an out-of-reach anisotropic sample is filtered isotropically, at Metal's major axis. Through MoltenVK's vertex and fragment stages under macOS 27, an isotropic sample is Metal's, but an anisotropic sample on a cube's `+Y` or @@ -2748,26 +2733,22 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. lies on the face's diagonal (docs/FAST-PATHS.md's known gaps). A kernel's samples through MoltenVK are Metal's own, with no note. - `metal2vulkan-degrade-half-texel-conversion` (precision). `PrecisionNote::HalfTexelConversion`: - The module reads, gathers, or samples a texture with a `half` result. On MoltenVK under - `YCbCrFilterPolicy::Device`, also announced at a draw that binds a two-plane YCbCr texture on + The module reads, gathers, or samples a texture with a `half` result. On MoltenVK, also + announced at a draw that binds a two-plane YCbCr texture on the grid `8192` at a slot sampled through a runtime sampler: a sample of one texel rounds to nearest even, one `half` ulp from Metal's ties-away rounding at a tie. - `metal2vulkan-degrade-half-sample-filter` (precision). `PrecisionNote::HalfSampleFilter`: 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. + magnification, or a runtime sampler) that Metal's own sampler (MoltenVK) answers otherwise than + Metal filters the format bound there: a two-plane YCbCr texture's. - `metal2vulkan-degrade-srgb-texel-decode` (precision). `PrecisionNote::SrgbTexelDecode`: 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 be bound in an 8-bit sRGB format. - `metal2vulkan-degrade-float-sample-filter` (precision). `PrecisionNote::FloatSampleFilter`: The - module samples a texture with a `float` result through a filter on a device that does not sample - through Metal's own sampler. -- `metal2vulkan-degrade-device-gather-footprint` (precision). - `PrecisionNote::DeviceGatherFootprint`: The module leaves a gather to the device's footprint on a - device that does not sample through Metal's own sampler. -- `metal2vulkan-degrade-cube-face-reciprocal` (precision). `PrecisionNote::CubeFaceReciprocal`: 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. + module samples a texture with a `float` result through a filter that Metal's own sampler + (MoltenVK) answers otherwise than Metal filters the format bound there: a two-plane YCbCr + texture's. - `metal2vulkan-degrade-function-storage-assumed` (precision). `PrecisionNote::FunctionStorageAssumed`: 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, @@ -2778,19 +2759,10 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. `PrecisionNote::QuadsCountedBeforeDiscard`: A fragment function runs a non-quad simdgroup operation (a reduction, scan, ballot, broadcast, shuffle, vote, or simdgroup matrix) before a discard on a path to it, in a shape where Metal's placement of it is not known. -- `metal2vulkan-degrade-device-depth-comparison` (precision). - `PrecisionNote::DeviceDepthComparison`: 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). -- `metal2vulkan-degrade-device-texel-denormals` (precision). `PrecisionNote::DeviceTexelDenormals`: - 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. - `metal2vulkan-degrade-view-base-texel-offset` (precision). `PrecisionNote::ViewBaseTexelOffset`: 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`). + of an argument buffer's texture: in an emulated raw sample (`heap_raw`) or a bicubic filter's + footprint. - `metal2vulkan-degrade-device-color-conversion` (precision). `PrecisionNote::DeviceColorConversion`: A fragment function writes a float to a color channel whose conversion the device makes where it is not measured to make Metal's: a normalized, sRGB or @@ -2868,12 +2840,9 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. sample's depth from its vertex function's window depth read at the sample, plus `FragCoord.z` less that depth read at the centre, which carries the depth bias. - `metal2vulkan-degrade-argument-pixel-sampler-scaling` (precision). - `PrecisionNote::ArgumentPixelSamplerScaling`: An access through an argument buffer's sampler (not - a 2D gather, which snaps behind the sampler's word) whose word the specialized module cannot read - may hand the device a pixel coordinate scaled by the texture's size: where the sampler states - pixel coordinates and a linear filter or a comparison, on a device without - `VkProperty::MetalSampler` (a filtered sample of a class the emulation does not reach), or a - comparison on one with it. + `PrecisionNote::ArgumentPixelSamplerScaling`: A comparison through an argument buffer's sampler + whose word the specialized module cannot read may hand the device a pixel coordinate scaled by + the texture's size, where the sampler states pixel coordinates. - `metal2vulkan-degrade-half-output-precision` (precision). `PrecisionNote::HalfOutputPrecision`: A fragment function returns a `half` color output (a scalar or vector of AIR's `half`) to an attachment the pipeline has, and either its module is compiled without fast math @@ -2911,25 +2880,24 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. under fast math a lane of the output that is not a load, or in a module that names no math mode. - `metal2vulkan-degrade-anisotropic-filter` (precision). `PrecisionNote::AnisotropicFilter`: 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 also through - MoltenVK where its cube-gradient route is not measured; and 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 (a device with the feature samples as before). Cost: a + 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, and for a cube's explicit gradients through MoltenVK where its cube-gradient route is not + measured: 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 device with the feature samples with its own anisotropic + filter. Cost: a cube's taps step across its face by Metal's face gradients, and a tap past the face's edge reads the next face as the device projects it, which Metal's own is not measured against. - `metal2vulkan-degrade-device-anisotropic-filter` (precision). `PrecisionNote::DeviceAnisotropicFilter`: 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). On a device without `samplerAnisotropy` the device filters - such a sample isotropically, recorded whatever the device's sampling; an argument buffer's + (`PrecisionNote::AnisotropicFilter`'s reach), on a 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, which the function cannot record, is refused there (`SamplerAnisotropy`). - `metal2vulkan-degrade-device-point-size` (precision). `PrecisionNote::DevicePointSize`: A vertex function writes `[[point_size]]`, or a mesh function `set_point_size`, on a device whose @@ -2949,15 +2917,6 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. pass's outputs, where Metal writes each sample's from that sample's run: equal where every pass computes the same outputs. Vulkan hands an invocation under sample shading only its own sample's bit of the coverage. -- `metal2vulkan-degrade-device-unorm8-linear-filter` (precision). - `PrecisionNote::DeviceUnorm8LinearFilter`: 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). - `metal2vulkan-degrade-half-output-fast-math-blend` (precision). `PrecisionNote::HalfOutputFastMathBlend`: 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 @@ -2973,12 +2932,11 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. (every factor, operation, write mask and blend color it builds), which Metal reads the output into clamped, folding none of it. - `metal2vulkan-degrade-device-sampling` (precision). `PrecisionNote::DeviceSampling`: 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 `VkProperty::DeviceSampling`). Under `YCbCrFilterPolicy::Device` - (the default) that includes a linear sample of a two-plane YCbCr texture, whose texels hold - Metal's reads exactly: the device's filter of them lands within 1.183 codes (1/255) of Metal's - sum on the format's grid, so a draw binding such a texture makes no pipeline of its own. + sampling: the module hands a sample, gather or comparison to the device's own sampler on a device + whose sampler is not Metal's (the module requires `VkProperty::DeviceSampling`). That includes a + linear sample of a two-plane YCbCr texture, whose texels hold Metal's reads exactly: the device's + filter of them lands within 1.183 codes (1/255) of Metal's sum on the format's grid, so a draw + binding such a texture makes no pipeline of its own. - `metal2vulkan-degrade-native-transcendentals` (precision). `PrecisionNote::NativeTranscendentals`: Native device maths: the module computes a `float` or `half` math-library function by the device's own `GLSL.std.450` instruction (or Metal's composition of the device's `Exp2` and `Log2`) where @@ -2996,8 +2954,7 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. - `metal2vulkan-degrade-device-texel-conversion` (precision). `PrecisionNote::DeviceTexelConversion`: 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`. + codes, off Apple's GPUs (`VkProperty::MetalSampler` keeps Metal's value). - `metal2vulkan-degrade-native-half-conversion` (precision). `PrecisionNote::NativeHalfConversion`: 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 the device's diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index c46d206d4..972c5df1c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -93,9 +93,9 @@ needs an internal item is one of the crate's own tests (`src/tests/`). policy. Every device-dependent choice (subgroup tier, buffer views, storage widths, robustness, push-constant room, limits, measured driver deviations) reads it, and its fingerprint is part of every cache key. -- **The policy's accuracy choices.** The maths are the device's own on every device. Off Apple's - GPUs the default policy takes the device's own sampler, texel conversions, `half` rounding, NaNs - and blends where they are faster; each has an exact switch ([FAST-PATHS.md](FAST-PATHS.md)). +- **The policy's accuracy choices.** The maths, the sampler and the texel conversions are the + device's own on every device. Off Apple's GPUs the default policy also takes the device's own + `half` rounding, NaNs and blends where they are faster ([FAST-PATHS.md](FAST-PATHS.md)). - **Structure, not names.** Families decide from IR types, address spaces, the metadata ABI and the `air.*` and `llvm.*` intrinsic contract. No branch keys on a function, type or variable name. - **Typed refusals.** An input the device cannot run exactly is `Error::Unsupported`, naming the diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 318e9e45c..52429ce75 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -27,22 +27,16 @@ three consumer pipelines: A2X (`a2x-s4`, `a2x-s96`), Xgc14 (`xgc14-bgra8`) and X | What it is | Default (fast) | Accurate switch | Recorded bound (note, code) | Cost of the accurate form (5080) | |---|---|---|---|---| -| Samples, gathers and depth comparisons go to the device's own sampler: its filter, footprint, level, anisotropy, sRGB decode and comparison. An 8-bit sRGB format the device cannot sample (`R8G8_SRGB` on NVIDIA) is held as its UNORM twin: a sample the raw codes do not serve is the device's filter of the codes, decoded through Metal's table. | `sampling = SamplingPolicy::NativeDevice` | `sampling = SamplingPolicy::Exact`: Metal's sampler emulated by fetches, a pipeline per bound sampler state | Linear filter within one code (1/255) on the measured devices, sRGB within 1.83; levels, anisotropy, cubes, 3D, gathers and comparisons unmeasured. A twin's filtered sample: exact for one texel and for a blend of two adjacent codes, up to 0.286 off for a blend of codes 0 and 255 (`SrgbTexelDecode`). `DeviceSampling` (`device-sampling`) | A2X under the four exact switches of the consumer's exact boot (sampling, texel conversion, half blend, NaN and min/max) on the RTX 5080 Laptop GPU (615.71.09): its function 572,061 words, made in 11.5-12.8 s; its anisotropic sampler's variant 659,590 words, 20.9-26.1 s on a loaded host where the function took 16.7-22.3 s; at the defaults 260,153 words, 1.1 s. On ANV both pass its compiler word bound, so it drops exact sampling for them (the row of that bound). At the switch (maths and texel conversions still exact): Xgc15 making 24.2-24.8 s exact against 12.5-13.9 s native | -| A two-plane YCbCr texture's linear sample (`YCBCR8_420_2P` and its kin, over a surface's planes) is the device's filter of its texels, which hold Metal's reads exactly, as any other texture's is under native sampling: a draw binding one takes the pipeline a draw binding any other texture takes. Metal sums the texels' steps on the format's grid (`1/2048`, `1/8192`), each term truncated. Under native sampling, MoltenVK's included (Metal's own sampler filters the texels as an `RGBA16Float` or `RGBA32Float` texture's); with `sampling = SamplingPolicy::Exact` every module answers Metal's filter, MoltenVK's through the slot's variant. On a device whose memory is the host's, a sample that reads the planes in place is Metal's filter exactly under either value (the two-plane YCbCr bullet under **Costs of matching Metal**), so the row applies there only to the samples that form does not read. | `ycbcr_filter = YCbCrFilterPolicy::Device` | `ycbcr_filter = YCbCrFilterPolicy::Exact`: Metal's filter emulated in the slot's YCbCr variant, a pipeline the first draw binding such a texture makes | Linear filter within 1.183 codes (1/255) of Metal's filter of the format on NVIDIA (RTX 3090), 0.877 on RADV, 1.058 on ANV, 0.872 on lavapipe; within 0.498 at coordinates on the 1/256 grid. `DeviceSampling` (`device-sampling`). On MoltenVK within one step of the grid (0.125 codes on `1/2048`, 0.016 on `1/8192`), a `half` result within one `half` ulp; a `half` sample of one texel on the grid `8192` through a runtime sampler rounds to nearest even where Metal rounds ties away. `ycbcr-filter-not-exact`, `HalfTexelConversion` (`half-texel-conversion`), announced where a draw binds such a texture | One pipeline more, made at the first draw binding such a texture. A2X (`a2x-s96` with a `YCBCR8_420_2P` texture at fragment slot 3, on ANV, Iris Xe): 2 pipelines, 13.9 s at the state's creation and 37.8 s at the draw (52.3 s wall), against the creation's one drawn as made (14.3 s) | -| A texel's `float` value is the device's conversion of its codes; a `half` result is the device's `float` texel rounded to nearest even. | `texel_conversion = TexelConversionPolicy::Device` | `texel_conversion = TexelConversionPolicy::Exact`: Metal's conversion by the bound format's class of every read; a sample's or gather's also with `sampling = SamplingPolicy::Exact` (under native sampling the device's sampler decodes it) | One `f32` ulp for 8- and 16-bit codes, 0.18 of a code for 5- and 6-bit packed channels; `half` within one ulp; NaN bits the device's. `DeviceTexelConversion` (`device-texel-conversion`), `HalfTexelConversion` (`half-texel-conversion`, also recorded for heap textures and unmeasured formats) | Exact reads (the same reads): Xgc14 0.88-0.89 → 0.90-0.93 s, GPU 0.039 → 0.046 ms; Xgc15 0.65-0.66 → 0.68 s, 0.090 → 0.094 ms; A2X unchanged (no affected read). Samples: with the sampling row | -| A normalized vertex attribute (`UCharNormalized` through `Short4Normalized` of either sign, `UChar4Normalized_BGRA`, `Int1010102Normalized`, `UInt1010102Normalized`) is converted by fixed-function vertex input, through the attribute's own Vulkan `UNORM` or `SNORM` format, not pulled from its vertex buffer and divided in the shader. Vulkan states that conversion as Metal states it (`c / (2^b - 1)` unsigned, `max(c / (2^(b-1) - 1), -1)` signed, correctly rounded), so it is the driver's implementation of it that can differ, and nothing in the attribute's Vulkan format asks for a correction after the load. The whole format is then `VertexAttribute` state that no instruction of the module names, so every format the device fetches shares one module (`pipeline::link::vertex`, item 9). | `vertex_normalized = VertexNormalizedPolicy::Device` | `vertex_normalized = VertexNormalizedPolicy::Exact`: every such attribute is pulled and its codes divided by `lower::stage_io::fetch`'s integer sequence, one module per format | One `f32` ulp at some codes on a driver that multiplies by the reciprocal: measured on llvmpipe (Mesa 26.2.4), which reads 127/255 as `0x3EFEFF00` where Metal reads `0x3EFEFEFF`, over the five 8-bit unsigned sites of `vertex-format-float4` and four of `-instance-step` (`known-gaps.tsv`); the 16-bit and packed normalized formats are exact there, and the unsigned ones are exact on RADV. Every normalized format of `vertex-format-float4`, `-half4` and `-instance-step` is Metal's on MoltenVK (Apple M3 Max, macOS 27.0.1) under both values of this switch, each case `exact` at every site. The signed formats are **unaudited** off MoltenVK under the default: they were pulled on every device until this row existed, so llvmpipe's 8-bit sites are expected to read one ulp as their unsigned twins do, and no run has taken them. Not announced: no note names the device's normalized vertex conversion. `tests::engine_vertex_variants` tests both values | Not timed. The variant count is the cost, measured on an Apple M3 Max over `cases::vertex_formats`' 45-format sweep (`tests::engine_vertex_variants`): the `float4` entry compiles 2 modules under the default and 21 under the switch, the `half4` entry 1 against 20. Each extra module is a translation of ours and a shader the driver converts once more | | A computed `half` or `float` color blended into an extended-range attachment (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10`) rounds the blend's source as a loaded one; Metal's compiler rounds it by how it computed it. Every device. | The in-shader blend's loaded rounding (no switch) | **Not built yet:** Metal's rounding per shape is probed, not modelled | One code. `ExtendedRangeBlendSource` (`extended-range-blend-source`), `ExtendedRangeFloatBlendSource` (`extended-range-float-blend-source`) | Not measured | | A blend into a packed 16-bit attachment the device renders through its word view (`A1BGR5Unorm`, `ABGR4Unorm` on the RTX 5080; `WordAttachment`), which the function computes in the interlocked storage form, reads the attachment's codes, where Metal's tile holds the pass's clear and each earlier blend's result as a `half`, finer; under fast math it also sums a few states otherwise than Metal. Every device rendering such an attachment. | The in-shader blend over the codes (no switch) | **Not built yet:** the extended-range attachments' `half` shadow (`render/extended_shadow.rs`, `VariantKey::extended_shadows`) taken by word attachments: the runtime's shadow start and end, its load of the codes and the clear's halves, and the word's shadowed variant in `lower::fragment::fetch`, for a single-sampled pass (a multisampled one keeps the codes, as an extended-range one does). Fast math's regrouped sums have no model | One code: without fast math exact over a loaded attachment (the 2,891 states of the M3 sweep, every channel), under fast math 3,527 of 94,732,288 channels a code apart; after a clear or an earlier blend in the pass, a code apart where the two readings store different codes. `DeviceColorConversion` (`device-color-conversion`) | Not measured. Expected from the shadow's form: an `R16G16B16A16_SFLOAT` image of the pass's extent per such color (8 bytes a pixel, 16.6 MB at 1920x1080), set at the draw it starts by a fill or a load dispatch, and an 8-byte storage read and write per blended fragment inside the interlock beside the word's | | A bicubic sample of an 8- or 16-bit normalized texture sums its taps exactly and rounds half up; Metal truncates its row terms, row sums and column terms first. Every device. | The exact sum (no switch) | **Not built yet:** Metal's datapath is pinned (17.75M lanes measured, no miss); its emitter is not written | One grid step (1/4080 at 8 bits) within about 2^-21 of a tie. `BicubicFilterArithmetic` (`bicubic-filter-arithmetic`) | Not measured (Metal's form is expected no larger) | | A bicubic sample of an extended-range texture (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10` and their sRGB twins) sums its taps' steps exactly, rounds half up and clamps into the format's decoded endpoints; within 0.014 of a grid step of a rounding tie Metal may round the other way. Every device. | The exact sum (no switch) | **None known:** no model of Metal's datapath tried fits; 3,317,760 lanes measured on the M3 Max (macOS 26.7) | One grid step (1/8160 a color lane, 1/8192 an sRGB color lane, 1/4080 alpha), 4,050 of the lanes measured, each within 0.014 of a step of a tie. `BicubicFilterArithmetic` (`bicubic-filter-arithmetic`) | No accurate form | -| A texture of an ASTC LDR format on a device without that ASTC format reads a decoded twin of 8-bit codes, each channel the code nearest Metal's 12-bit value (`C >> 4` over 4095). (An sRGB form's twin holds Metal's own 8-bit codes under either value, which its slots decode through Metal's table: exact.) A texture of an EAC 11-bit format (`R11`, `RG11`, unsigned and signed) on a device without ETC2 reads one of 16-bit normalized codes, each nearest Metal's value (`c / 2047`, signed `c / 1023`). The runtime's choice: no pipeline differs. | `decoded_texels = DecodedTexelsPolicy::Compact` | `decoded_texels = DecodedTexelsPolicy::Exact`: Metal's values in an `R32G32B32A32_SFLOAT` twin (an EAC 11-bit one's in `R32_SFLOAT` or `R32G32_SFLOAT`) | Within 1/510 of Metal's value. An EAC 11-bit channel within half a 16-bit step (1/131070, signed 1/65534). `decoded-texel-precision`, announced where such a texture is made; `runtime_lane::astc_textures`, `runtime_lane::etc_textures` | The twin's memory, 16 bytes a texel against 4 (a 2048 x 2048 texture's chain: 85 MiB against 21 MiB), and as much again for a second twin once the texture is viewed in its other colour space; an EAC 11-bit twin's 4 bytes a channel against 2. The CPU decode of that chain of 8 x 8 blocks on one core of the Iris Xe host: 79 ms against 68 ms. Sampling not measured | | A heap's colour texture that Metal keeps losslessly compressed (`allowGPUOptimizedContents`, no `ShaderWrite`, `PixelFormatView` or `ShaderAtomic` usage, 16 texels or more a side), on a driver whose compressed images may keep their texels apart from the memory they are bound to (`DriverFact::CompressedImagesHideAliasedWrites`: ANV), is the driver's compressed optimal image, its compression and fast clears kept. A texture Metal keeps uncompressed takes the uncompressed image under either value. The runtime's choice: no pipeline differs. | `heap_compression = HeapCompressionPolicy::Compressed` | `heap_compression = HeapCompressionPolicy::Uncompressed`: an image the driver keeps uncompressed in the heap's bytes, as for a texture Metal keeps uncompressed: host-transfer usage where the device enabled `hostImageCopy` (`heap-texture-host-transfer`), else a linear image (`heap-texture-linear`), else the optimal one (`heap-texture-hides-aliased-writes`) | A write through a buffer or another texture over the texture's bytes may leave its texels as they were or change them otherwise than as written, where Metal's texture reads opaque magenta (`0xffff00ff`) in every texel of drawn content the write covers and the written bytes where it held only a clear; the texture's own writes may show in those bytes compressed. Within Metal's contract: Metal documents such a texture's layout as its own (`allowGPUOptimizedContents` lets it "adjust the private layout"), so no write through another view over its bytes has a defined result there either. `HeapTextureCompressed` (`heap-texture-compressed`), announced once per device where such a texture is made; `runtime_lane::heap_textures` | ANV (Iris Xe of RPL-P; `heap_textures::heap_compression_costs`), a 2048x2048 `RGBA8Unorm` render target in a `Private` placement heap: a pass that clears it 26.9 us against 676.2-676.5 us; a copy into another such texture 647.7-649.1 us against 673.9-693.2 us | | Batches of command buffers committed on one queue that the scheduler finds ready together (a backlog) go to the driver in one `vkQueueSubmit`, at most four, only the last signalling the queue's timeline, on a driver measured to merge a submission that signals nothing into the next (`DriverFact::SubmissionsWithoutSignalsMerge`: Mesa 26.2.4's ANV on the Iris Xe of RPL-P and the UHD 770 of RPL-S, RADV on the Radeon 780M and the RX 7900 XTX, and llvmpipe; every other driver, measured or not, takes the ungrouped form under either value of the switch): one kernel submission, where ANV on i915 lists every `VkDeviceMemory` in each (the consumer's guest drag on the Iris Xe: about 300 entries per execbuffer, 260 of them its host imports, at 112 to 128 execbuffers a frame). A batch's event signals ride to the group's end, which signals each event's semaphore to the highest index the batches held signal it to (an event's indices rise in commit order). A batch that signals a binary semaphore, takes a fence, binds a sparse update, does first work, names the caller's wrapped image, or waits for anything not seen complete (an event, another queue's work) goes alone, after the batches held: a batch with a wait leads a group, never joins one. So that checked command buffers (the consumer checks each) are found ready together, the submission checks of up to three batches right behind a line's head that goes run with the head's, in commit order, none committed after another queue's batch: such a check runs before the previous batch's `vkQueueSubmit` rather than after it, in the scheduler pass that submits its own batch. A pass that finds no batch ready sends the batches held, unless two or more earlier submissions of their `VkQueue` are not seen complete: the GPU runs those first in any case, so the batches stay held, and those committed meanwhile join them, until one submission is left in flight (a completion turn wakes the scheduler at its value), the group fills, a later batch sends it, a head waits for the GPU, or a thread waits for one of their command buffers' completion, which sends them at once; a batch that ends a command buffer with a switch of storage forms riding on it, which settles by its submission's outcome, is never kept so. A held batch that ends its command buffer is `Scheduled` as it is held, its submission handlers run first, then its scheduled handlers, and its kernel end time set, as an M3 Max schedules a command buffer committed behind running work 0.04 to 0.18 ms after its commit. The runtime's: no pipeline differs. | `completion = CompletionPolicy::Grouped` | `completion = CompletionPolicy::Exact`: one submission per batch, each signalling its own values; each line's head checked alone | Each command buffer of a submission but the last is seen complete (status, completed handlers, waits), and the event values it signals are reached (by the GPU waits on other queues, the host's waits, value reads and listeners), once the last completed: late by the GPU time of at most three later batches (about 0.1 to 0.2 ms each in the consumer's compositor frames on the Iris Xe; about 20 ms behind a 20 ms batch), never early, in commit order. Metal's contract states no bound on when completion is seen (an M3 Max reports a command buffer complete, its handlers, status, waits and event listeners alike, 0.04 to 0.10 ms after its GPU end), and no member but the first waits, so no wait holds a member back: a valid program sees only later completion, as of slower GPU work. A batch kept while earlier work runs is seen complete within the same bound, and, where the one submission left in flight ends before its group reaches the GPU, late besides by that gap: at most a completion turn's reaction and the group's `vkQueueSubmit`. Commands, barriers and GPU times are unchanged. `GroupedCompletion` (`grouped-completion`), announced once per device at its first such submission; `runtime_lane::grouped_submissions` | ANV (Iris Xe of RPL-P; `frame_costs::frame_costs_over_imports`, the checked device, 67 command buffers a frame, GPU at 467-783 MHz), with 520 host imports live, where the Exact form's submissions fall behind the commits as the guest's do: 32.0-33.2 kernel submissions a frame against 67.0, 3.4-3.5 ms of execbuffer ioctl a frame against 6.9-7.9 ms, the scheduler thread's CPU 61-63 us a command buffer against 121-136 us, a frame through completion 4.7-5.9 ms against 8.6-9.7 ms; in the guest's shape with 520 (a second queue taking every 20th command buffer, each signalling a shared event, every 10th waiting for one): 26.2-26.7 kernel submissions a frame against 67.0, 2.8 ms of ioctl a frame against 6.9-7.0 ms, the scheduler 52-53 us a command buffer against 122-123 us, a frame through completion 6.0 ms against 8.7 ms; with 260, where it keeps up, 64.9-66.3 kernel submissions a frame against 67.0, the CPU and wall times alike. The cost (`grouped_submissions::grouped_completion_delays`, 8 command buffers of 0.3-0.5 ms of GPU work ready together): the host saw each but a group's last complete later by the later ones' GPU time, the last 0.1-0.3 ms later than alone (the completion turn's per-command-buffer work for the group, done at its end). Keeping a group while earlier work runs (UHD 770 of RPL-S, ANV, the guest's shape with 520 host imports, a submission handler on every command buffer and a 16 MiB fill ahead of each, about 1.3 ms of GPU each; the kept form against the batches sent as found): committed every 1 ms, 18.1-18.2 groups kept a frame, 24.9-25.0 kernel submissions a frame against 57.9, 2.18-2.90 ms of execbuffer ioctl a frame against 4.64-5.43 ms, the scheduler thread's CPU 67-82 us a command buffer against 113-118 us, the GPU idle within a frame's span 0.61 ms against 0.68-0.69 ms, a frame through completion 89.5-89.6 ms alike, completion seen later (GPU end to completed handler: mean 1.82-1.86 ms against 0.43-0.46 ms, p50 1.57-1.60 against 0.11-0.13, p99 4.35-4.37 against 4.09-4.11, max 4.52-4.55 against 4.18-4.23); committed at once, 18.0 kernel submissions a frame against 23.4; with no fill, 18.0 against 20.6, the GPU idle 0.59 ms against 0.58-0.66 ms. In the consumer's guest drag on the Iris Xe (i9-13900H; three passes each way): 24.4-27.5 kernel submissions a frame against 42.4-43.8, the scheduler thread 0.4-1.7 ms of CPU a frame less, 15.7-17.3 frames a second against 16.4-17.6: the frame rate alike within noise, as the scheduler thread does not bound that frame | | Batches of command buffers on one `VkQueue`, on a driver measured to start no kernel submission of a queue before the one before it completed (ANV, RADV and NVIDIA's; `batch_order.rs`), are ordered by their ends: each ends with a barrier ordering its work before every later command of its `VkQueue` (the exact form's end orders it before the host's reads and writes alone), so a batch that depends on an earlier one there begins with no barrier of its own, often no command buffer of barriers, and its first encoder's GPU start is written at the bottom of the pipe, once everything before it completed. Metal starts an independent command buffer committed behind running work while that work runs (an M3 Max under macOS 27.0.1, probe `gpustart`); those drivers ran two batches of independent work one after the other under every shape measured (no end barrier, the host's or the widened one; in one `vkQueueSubmit` or two, merged into one kernel submission or not), where two dispatches of one command buffer ran side by side. The runtime's: no pipeline differs. | `batch_order = BatchOrderPolicy::Ends` | `batch_order = BatchOrderPolicy::Exact`: a barrier for each dependency of a batch's work on an earlier batch's of its `VkQueue`, the end's barrier to the host's reads and writes alone, the GPU start written at the top of the pipe; every other driver takes it under either value | None: on those drivers each batch starts once the one before it completed under either value, so the work's order, its results and its GPU times are the same, and a batch's GPU start is the end of the work before it, when such a driver starts it. Not announced; `runtime_lane::commit_work` and `runtime_lane::gpu_times` test both values | UHD 770 (ANV, RPL-S), the consumer's frame shape over 520 host imports, 67 command buffers a frame, Grouped completion, the widened end barrier against the exact form (a probe build of each): with no fill ahead of each command buffer, 67.0 command buffers submitted a frame against 129.3-129.7, the GPU's span a frame 1.84-1.90 ms against 1.99-2.06 ms, a frame through completion 2.13-2.22 ms against 2.27-2.38 ms; with a 1 MiB fill ahead of each, 134.0 against 262.9, 8.03-8.22 ms against 8.32-8.42 ms, 9.00-9.15 ms against 9.25-9.36 ms. Radeon 780M (RADV, Mesa 26.0.8), this switch: with no fill, 67.0 against 128.9-129.0, a frame through completion 48.3-48.6 ms against 42.6-47.0 ms; with a 16 MiB fill committed at once, 134.0 against 251.0-251.1, 50.6-50.8 ms against 50.8-57.3 ms; committed every 1 ms, 134.0 against 249.7-250.2, 71.3-83.6 ms against 106.3-113.6 ms (each kernel submission there leaves about 2.5 ms of the GPU idle over 520 host imports, which sets these frames) | | A texture that only samples or reads (no `RenderTarget`, `ShaderWrite` or `ShaderAtomic` usage) over host pages (a no-copy buffer's, or a no-copy heap's buffer's, imported by their pointer or as dma-bufs; or a buffer in fresh pages) is a linear image aliasing the pages in place, where the device's own check shows that the image's first move, which Vulkan lets read and write every byte bound to it (`VUID-VkImageCreateInfo-pNext-01443` makes such an image start `UNDEFINED`), leaves every byte alone while the CPU writes beside it: a deliberate, scoped exception to relying on documented Vulkan behaviour alone, the owner's ruling (`in_place.rs`). The check runs once per driver, release and runtime, per class of pages, on a thread of its own, its verdict kept in the shader cache's directory; a texture made before its class's verdict is a shadow. A texture whose usage renders or writes, a check that failed or made no image, and a pitch no image takes keep the shadow (`shadowed-texture`, its reason named, `WorkCounts::host_texture_shadows_*`). | `host_page_textures = HostPageTexturePolicy::InPlace` | `host_page_textures = HostPageTexturePolicy::Shadow`: every texture over host pages a shadow, its texels copied in before each command buffer that uses it and merged back after each write (the host-pages bullet under **Costs of matching Metal**) | Exact where the driver keeps what its check showed: the check covers texels, the bytes between rows and those after the image, of 1, 2, 4, 8 and 16-byte texels and a 3840x2160 surface, three rounds each; a driver whose first move changed a byte outside every round's window would undo a CPU write made meanwhile. Not announced where the check passed. A CPU write reaches the image's reads as it reaches the buffer's (Host Write Ordering Guarantees) | See **Costs of matching Metal** (host pages): the shadow copies a sampled 3840x2160 surface in whole each command buffer | -All at once: `DevicePolicy::exact_answers()` sets every switch above but sampling's (validation -adds `sampling = SamplingPolicy::Exact`). Its measured cost: A2X 0.99-1.04 → 17.5 s, +All at once: `DevicePolicy::exact_answers()` sets every switch above. Its measured cost: A2X 0.99-1.04 → 17.5 s, GPU 0.098 → 0.267 ms; Xgc14 0.86-0.87 → 4.95-5.01 s, 0.039 → 0.105-0.110 ms; Xgc15 0.63-0.66 → 3.06-3.15 s, 0.090 → 0.194-0.197 ms. @@ -60,7 +54,6 @@ known. The rest of the differences are docs/API.md section 9's precision notes. | `dot`, `mix` and `fast::sqrt` are the device's `OpDot`, `FMix` and `Sqrt`, not Metal's fused chain, its two fused multiply-adds and `x · rsqrt(x)`, on every device but MoltenVK, which takes Metal's order; a `dot` of other than two to four lanes sums the `OpDot` of each chunk of up to four lanes. | The device's order is the contract. | `float` `dot` of n lanes within (3n − 1)·2^-24·Σ\|aᵢbᵢ\|, `mix` within 2^-21 of its two terms, `fast::sqrt` 4.5 ulp. `NativeDot` (`native-dot`), `NativeMix` (`native-mix`), `NativeTranscendentals` (`native-transcendentals`); a `dot` of other than two to four lanes within Vulkan's precision of its chunks' `OpDot` and sum, `DeviceArithmetic` (`device-arithmetic`) | | Off MoltenVK a `float` multiply, and a fused multiply-add by `OpFmaKHR`, round before Metal's flush: Metal flushes a result whose exact value lies below `2^-126` before rounding it, so a result whose exact value lies within half a unit below `2^-126` answers `2^-126` of its sign where Metal answers the zero of its sign. | Every device measured off MoltenVK (RADV, ANV, NVIDIA, lavapipe) rounds first; its multiply is the contract. | Announced once per device as it is made: `float-tininess-after-rounding` | | `f32` denormals in a `float` operation on a device not measured to read them as Metal does (`DriverDeviation::MetalFloatDenormals`: lavapipe, and every unmeasured device), in `floor` and `ceil` on every device, in the maths functions and the device's order of the rows above, and in a conversion to or from `double`. Metal reads them as zero and flushes a denormal result. | The device's reading is the contract: Vulkan lets each device keep or flush them, and Metal runs no `double`, so its reading of a conversion is not measured. | `DeviceDenormals` (`device-denormals`) | -| A denormal 32-bit float texel the device's sample or gather reads as zero (RADV's gathers and nearest samples, NVIDIA's gathers, ANV's nearest samples), where the module cannot fetch the texels itself. | The device's filter decides; no fetch form reaches filtered, cube, heap or runtime-sampler samples. | `DeviceTexelDenormals` (`device-texel-denormals`) | | Depth values outside [0, 1] stored clamped (RADV, ANV) on a device without `VK_EXT_depth_range_unrestricted`. | Vulkan leaves them undefined without the extension: enable it. | `RestrictedDepthRange` (`restricted-depth-range`) | | A multisampled 32-bit float depth written by a blit copy from a buffer or a colour texture, or a separate depth texture's copies to and from its pass's scratch image, on a device whose depth/colour copies are missing or wrong (lavapipe, MoltenVK, NVIDIA's GA10x, a device without `VK_KHR_maintenance8`): the values its driver's fragment depth changes (MoltenVK's, NVIDIA's), or on a driver not measured may change (outside [0, 1], denormals, -0), land changed. | Vulkan writes a multisampled depth image's samples by no other means there but a clear; a driver measured to store every fragment depth unchanged (lavapipe's measured releases) is exact. | `DrawnDepthCopy` (`drawn-depth-copy`) | | Signed zeros, infinities and NaNs where the device lacks `SignedZeroInfNanPreserve` at the operation's width. | A device capability. | `DeviceSignedZeroInfNan` (`device-signed-zero-inf-nan`) | @@ -75,17 +68,11 @@ known. The rest of the differences are docs/API.md section 9's precision notes. | A `Counting` visibility result of a draw writing more than one color attachment, on ANV (Mesa 26.2.4): Metal's count multiplied by the colors written, not divided back. `Boolean` results stay exact. | The driver counts each sample once per color output (`RuntimeDriverDefect::OcclusionCountPerColorOutput`), no documented Vulkan form counts it once, and a refusal would withhold the Mac2 and Metal3 families. | `VisibilityCountPerColor` (`visibility-count-per-color`) | | On MoltenVK a no-copy buffer or heap released with no keep-alive while batches are in flight runs its deallocator once the batches submitted before its release completed, and the program's own submissions through `CommandQueue::with_vk_queue` before it, where Metal runs it at the release. | MoltenVK 1.4.1 fails pending work that reads device addresses where memory a device-address buffer lay in is freed (`RuntimeDriverDefect::FreedAddressMemoryFailsPendingWork`), so freed memory waits for the batches in flight (`WorkCounts::freed_memory_parked`). | `HostDeallocatorDelayed` (`host-deallocator-delayed`) | | On MoltenVK a `Shared` or `Managed` texture whose format packs more than one texel into a block (every block-compressed family) keeps its image out of host-transfer memory, so its CPU copies take submissions where another driver's take none. The stored texels are Metal's either way; what changes is the work, in `WorkCounts::command_buffers_begun_batch_work` and the `command_buffers_begun` and `command_buffers_submitted` that carry it (`bc1-rgba`, four 16 x 16 `BC1_RGBA` levels: `command_buffers_begun` 8 on the bind-time path and 15 off it; `fresh-texture-bc1-rgba-managed`: 3 and 5). A `replaceRegion` of such a texture stages its bytes for the device's next submission and waits for none (`texture/first_move.rs`). Its CPU **reads** come out of a host shadow of the image's texels, made at the first read of the texture by the submission that read waits for either way and read from by every read after it: exact (it holds the image's own bytes, and a CPU write writes both), bounded (`host_shadow::SHADOW_BYTES`, past which a read takes the submission path), and lazy, so a texture nobody reads back holds nothing. It is dropped wherever anything but a CPU write may have written the texels: every commit of the program's, its own Vulkan submissions, another `VkImage`, a detach, or the program taking the image's handle (`texture/host_shadow.rs`; `WorkCounts::texel_shadows_made`, `texel_shadow_reads`, `texel_shadows_dropped`). Measured on an M3 Max: `compressed-moves-bc1-rgba` reads `internal_submissions` 5 where it read 56 and `command_buffers_begun` 30 where it read 81, for 1,168 bytes of shadow over its five textures and 56 reads out of them. | MoltenVK 1.4.2 binds such an image through a `flushToDevice` that `replaceRegion:`s every subresource at one block's bytes a row instead of the row of blocks, tripping AGX's `bytes_per_row >= used_bytes_per_row` assertion (`RuntimeDriverDefect::HostTransferImagesCopiedAtBind`). The copy is the driver's own and no call of the program's asks for it, so the only way not to provoke it is not to ask for the image; every other driver keeps the host-transfer path, as does a device without `VK_EXT_host_image_copy`. A write cannot leave the GPU's copy of the texels unwritten, so only reads come off the host shadow. | None (cost only, and exact) | -| On ANV (Mesa 26.2.4) a pipeline whose largest stage module, under the consumer's exact forms, passes 400,000 words is retranslated with those forms dropped until it fits: native sampling first, then every module-growing exact answer native. Every kind is fitted: render (vertex and fragment), mesh render (object, mesh and fragment, or the stages that emulate them), compute and tile render; the notice names the state's kind. On a large enough module the driver's register allocator reads past its interference bitset and the process faults at pipeline creation. | ANV's `brw` register allocator faults on such modules (`DriverWorkaround::RegisterAllocatorOverflowsLargeModules`), no documented Vulkan form bounds a module's register pressure, and a refusal would withhold the consumer's large shaders. | `ExactFormsOverCompilerLimit` (`exact-forms-over-compiler-limit`) | +| On ANV (Mesa 26.2.4) a pipeline whose largest stage module, under the consumer's exact forms, passes 400,000 words is retranslated with every module-growing exact answer native. Every kind is fitted: render (vertex and fragment), mesh render (object, mesh and fragment, or the stages that emulate them), compute and tile render; the notice names the state's kind. On a large enough module the driver's register allocator reads past its interference bitset and the process faults at pipeline creation. | ANV's `brw` register allocator faults on such modules (`DriverWorkaround::RegisterAllocatorOverflowsLargeModules`), no documented Vulkan form bounds a module's register pressure, and a refusal would withhold the consumer's large shaders. | `ExactFormsOverCompilerLimit` (`exact-forms-over-compiler-limit`) | | On a driver that does not take a set-0 buffer binding whose entry point uses it through several variables as a **dynamic** descriptor, every draw or dispatch of such a variant allocates and writes a descriptor set of its own, where one dynamic binding would let them share one set, bound again at each command's own offset. Such a binding is a slot or store sink reached through its word view and a narrow or `uvec4` unit view (`memory::views`): of the 1,378 store sinks the public fixtures plan on this profile, 20 entries have one (`record_stride_not_a_multiple_of_four`, `encoders_plain`, `encoder_types_*`, `hwd_half_reads`, `kernel_copy_runtime_ulong_length`, `kernel_simdgroup_matrix_block`). The stored values are the same either way; what changes is the set a command allocates and writes (`WorkCounts::set_zero_sets_reused` counts none of them). The device answers for itself, by creating one pipeline of exactly that shape and destroying it (`pipeline::objects::takes_multi_variable_dynamic`, `bind::DynamicViewsModule`, asked once and only where a layout has such a binding), so a driver without the defect pays nothing. A binding the device takes still turns dynamic only while the layout's dynamic-buffer budget lasts (`maxDescriptorSetUniformBuffersDynamic`, `maxDescriptorSetStorageBuffersDynamic`), spent in binding order: on a Radeon 780M (RADV, Mesa 26.2.4, eight dynamic storage buffers) `encoders_plain`'s sink is its twenty-seventh binding and gets none, so that entry keeps a set per dispatch wherever its set 0 is not pushed. A device whose set 0 is pushed (`VK_KHR_push_descriptor` with an eligible layout) never reaches the choice. | Nothing in Vulkan bounds the variables at a binding, dynamic or not, so there is no exact form to switch to: the driver either compiles the shape or does not. MoltenVK's SPIRV-Cross declares one variable's local alone -- read in 1.4.1's source and measured on 1.4.2 (`driverVersion` 10402) on an Apple M3 Max, where `vkCreateComputePipelines` answers `VK_ERROR_INITIALIZATION_FAILED` for a kernel of three and of four variables at one dynamic binding. The check proves the driver compiles the shape, not that it applies the dynamic offset to every variable at it; no device is measured to get that wrong, and RADV (Mesa 26.2.4, Radeon 780M) is measured to get it right, `record_stride_not_a_multiple_of_four` answering Metal's `sizeof` and both its narrow stores with its two-variable and three-variable bindings dynamic. | None (cost only, and exact) | ## Accuracy switches whose default is Metal's -- `unorm8_linear_filter = Unorm8LinearFilterPolicy::Exact` (the default) keeps Metal's filter for - an 8-bit unsigned normalized texture's linear sample where Metal's sampler is emulated - (`sampling = SamplingPolicy::Exact`). `unorm8_linear_filter = - Unorm8LinearFilterPolicy::DeviceWithinOneCode` hands it to a device measured within one code - (`DeviceUnorm8LinearFilter`, `device-unorm8-linear-filter`): it bought no GPU time on the - consumer's fragments and cost module size and making time. - `render_lowering = RenderLoweringPolicy::AtCall` (the default) lowers each render encoder call inside the call, which returns every refusal. `render_lowering = RenderLoweringPolicy::Worker` logs the call once its checks at the call pass, and lowers it later: in batches of 32 calls on @@ -516,12 +503,10 @@ driver's. Each is open work. compute encoder its unit of command predication reaches past, which is one whose unit laid a step before it opened or one of its own that the unit's later encoders read, and one whose unit laid a loop or left work out; work on the GPU alone) fail `EncodedUseRebound` (announced). -- **A runtime sampler's nearest sample of an 8-bit sRGB texture under native sampling.** On a - device that samples the format, the sample keeps the device's sRGB decode (announced as - `SrgbTexelDecode`), where the table's exact decode of the one texel it reads would cost little: - the function does not know the bound sampler's filter, and a variant keyed on a nearest - sampler's word is not built. Under `SamplingPolicy::Exact` a sample the linear emulation takes - (not a cube's) reads the code through the slot's raw view there and decodes it exactly. +- **A runtime sampler's nearest sample of an 8-bit sRGB texture.** On a device that samples the + format, the sample keeps the device's sRGB decode (announced as `SrgbTexelDecode`), where the + table's exact decode of the one texel it reads would cost little: the function does not know the + bound sampler's filter, and a variant keyed on a nearest sampler's word is not built. - **A fetched or resolved packed 16-bit attachment on a device that does not render the format** (`A1BGR5Unorm`, `ABGR4Unorm` on the RTX 5080). Its word view (`WordAttachment`) takes writes (blended and partly masked ones through the pixel interlock, the row above); a color input or @@ -600,14 +585,9 @@ driver's. Each is open work. signedness) are refused; one without a decoded twin (a heap's over the caller's host pages or laid out apart from its bytes) holds its blocks for copies alone, and a command that reads it is refused. -- **A level the device's arithmetic chooses.** Off MoltenVK under exact sampling, a fragment's - implicit-level sample (its bias Metal's `B` within the device's limit), a sample with explicit - gradients and a fragment's LOD query take the device's level of detail, where Metal's is not - measured, and an explicit level Metal's rule is not handed on (an integer texture's, a constexpr - sampler's with its own bias or an unmeasured clamp) takes the device's rounding. Where the level - chooses what a sample reads and no sample-filter note records it, and for every LOD query, it is - announced as `DeviceSampleLevel`. An extended-range texture's such sample takes Vulkan's level of - detail computed in the shader on every device, with the same note. +- **A level the shader computes from derivatives.** An extended-range texture's fragment sample at + an implicit level or with explicit gradients takes Vulkan's level of detail computed in the + shader on every device, where Metal's is not measured, announced as `DeviceSampleLevel`. - **An anisotropic cube sample on a `y` face through MoltenVK's vertex and fragment stages under macOS 27.** SPIRV-Cross's `spvGradientCube`, which MoltenVK 1.4.1 and 1.4.2 apply, writes a `+Y` or `-Y` face's gradients as `(d_x, d_z, d_x)`, so Metal loses the `z` gradient. The module hands such a diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index b300db007..9f8521dcf 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -302,8 +302,7 @@ cargo run -p metal2vulkan-validation --bin corpus-status `crates/metal2vulkan/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, and, in a second table, of -every fixture that samples under every exact form (Metal's sampler emulated and -`DevicePolicy::exact_answers`). A behavior-preserving change keeps every cell; a change that moves +every fixture that samples under every exact form (`DevicePolicy::exact_answers`). A behavior-preserving change keeps every cell; a change that moves one bumps `SEMANTICS_VERSION` and re-blesses ([CONTRIBUTING.md](../CONTRIBUTING.md#golden-output-hashes-and-semantics_version)). The fixture inventory (`crates/metal2vulkan/tests/public_fixture_expectations_engine.tsv`) pins which