Files
metal2vulkan/crates/metal2vulkan-runtime/src/astc.rs
T
Anees Iqbal 930d746df7 Read ASTC, ETC2/EAC, PVRTC and 4:2:2 textures the device lacks through twins of Metal's decode
On a device without a texture's compressed or chroma format, the runtime now makes the texture and
reads it as Metal does. Before, such a texture was refused at its making (ASTC, ETC2/EAC) or at its
first read (PVRTC, 4:2:2, held for copies alone). The consumer's guest on the RTX 5080 stopped at
ASTC_8x8_LDR, PVRTC_RGB_2BPP and EAC_R11Unorm. NVIDIA, RADV and lavapipe have none of these formats,
and Vulkan's 4:2:2 formats need a sampler Y'CbCr conversion whose chroma reconstruction is the
implementation's.

What changes:
- The store. The blocks lie in a carrier image of the same block bytes and shape (a compressed
  format the device copies: BC1, BC4, BC7, BC3, BC2, BC5, ETC2, EAC or ASTC 4x4; R8G8 for 4:2:2).
  replace_region, get_bytes, blits, fills and texture copies move Metal's blocks unchanged.
- The twin. Reads go to a decoded twin holding Metal's decode, kept in step on the GPU as a BC
  texture's twin is: a decode pass after a blit, a texture copy or a submitted CPU copy, and a CPU
  decode on the device's decode thread after a host write. No write costs a GPU-to-CPU round trip.
  A write's decode covers whole levels for PVRTC and whole rows for 4:2:2, whose texels read their
  neighbours. A new texture's twin starts at the decode of zero blocks (magenta for ASTC's error
  block), not at zeros.
- The decoders, our own, written from the Khronos ASTC specification, the Khronos Data Format
  Specification's ETC2 and EAC chapters, and Metal's measured answers for PVRTC1 and 4:2:2:
  bind::AstcDecode, EtcDecode, PvrtcDecode and ChromaDecode, with their GPU kernels
  astc_decode_module, etc_decode_module, pvrtc_decode_module and chroma_decode_module on the block
  decode's bindings (new api_surface rows, with AstcTexels, EtcTexels and DecodedTexelsPolicy).
- Metal's decode, matched: an ASTC LDR channel is (C >> 4) / 4095 of the 16-bit interpolated C;
  an 8-bit ETC2/EAC channel c / 255, an 11-bit one c / 2047 (signed c / 1023); PVRTC upscales
  colours A and B from the four block centres around a texel and blends them by its index; a 4:2:2
  texel takes its own green, and red and blue (3c + n + 2) >> 2 of its pair and the pair beside it.
- sRGB forms. The ASTC, PVRTC and ETC2/EAC sRGB formats read their twin's codes raw through an
  R8G8B8A8_UNORM view and decode them through Metal's table, as the 8-bit and BC sRGB formats do:
  reads, nearest samples and gathers exact, with no precision notice. Linear samples keep the
  device's sRGB filter (the exact sum under SamplingPolicy::Exact). A device that has the ASTC
  block keeps its own sRGB decode. The linear PVRTC and 8-bit linear ETC2/EAC formats take BC1 to
  BC3's Argb8 texel class, so under TexelConversionPolicy::Exact their reads are Metal's c / 255.
- The switch: DevicePolicy::decoded_texels, DecodedTexelsPolicy { Compact (default), Exact };
  exact_answers() selects Exact. Compact holds an ASTC LDR twin in 8-bit codes nearest Metal's
  12-bit value (at most 1/510 off) and an EAC 11-bit twin in the nearest 16-bit codes, announced
  decoded-texel-precision. Exact holds their floats. PVRTC, the 8-bit ETC2/EAC formats, the ASTC
  sRGB formats and 4:2:2 are exact under both. Tested by fast_paths; a FAST-PATHS row.
- Views in the other colour space. An ASTC texture viewed in its other colour space reads a second
  twin, made at the first such view: Metal reads that view exactly as a texture of the view's
  format over the same blocks, and the two forms widen endpoints apart, so one twin cannot serve
  both. Its decodes are queued on the device and recorded by the next batch with work. Counted by
  WorkCounts::second_twins, second_twin_checks and second_twin_decodes. PVRTC and 8-bit ETC2/EAC
  views of the other colour space share the one twin.
- Copies between a compressed texture and an uncompressed one whose texel is the block's bytes
  (BC1 or ETC2 with RG32Uint, BC7 or ASTC with RGBA32Uint) run with Metal's rule: every coordinate
  in the destination's texels, a block per texel. They were refused as formats of different units.
- Notices: carried-decoded-twin (Performance) on every twinned texture; decoded-texel-precision
  (Precision) only for an ASTC LDR or EAC 11-bit twin under Compact.
- Typed refusals: RuntimeGap::DecodedHeapTexture (a heap's ASTC texture, a sparse heap's carried
  texture; the heap size query refuses alike); views of the ASTC HDR form, of another footprint or
  PVRTC block, and of an EAC 11-bit format as its other signedness (Unsupported(TextureView));
  copies between PVRTC and an uncompressed format, between two compressed formats of one block size
  and different extents, and level or slice copies between compressed and uncompressed formats
  (NotImplemented(Format)). A device with the native format keeps the direct path.
- Docs: the API.md catalogue entries, the FAST-PATHS decoded_texels row and known gaps, and the
  module docs of astc.rs, etc.rs, pvrtc.rs, chroma_pairs.rs and decoded_twin.rs.

Why: Metal makes, reads and samples these textures on Apple GPUs, and the consumer's guest uses
them; the desktop Vulkan drivers have no such formats.

Verified:
- Metal's answers, probed on an M3 Max under macOS 27.0.1: ASTC (seeded random blocks, all 14
  footprints, linear and sRGB, read as float and half) bit for bit, digests pinned by
  seeded_blocks_read_as_metal_read_them; ETC2/EAC (4096 random blocks of each of the ten formats)
  digests equal; PVRTC (all eight formats) every digest equal; 4:2:2 every read, sample and gather
  bit for bit what an RGBA8Unorm texture of the decoded codes answers; the copy rule on every listed
  pair both ways.
- On the CPU SPIR-V interpreter each GPU kernel writes the CPU decode on every texel: ASTC on every
  footprint, linear and sRGB, Float and Unorm8, with blocks covering all 16 endpoint modes, every
  partition count, dual plane and void extent; ETC on every decode and both texel forms; PVRTC on
  every format. The kernels are valid on every committed profile.
- Runtime unit filters 63 passed and translator unit filters 183 passed (ETC2/EAC); the runtime's
  unit suite 952 of 953 (the one failure the recorder's module-list test, fixed with the recorder).
- On lavapipe: chroma_pairs, pvrtc_textures, the mipmap, fill, buffer-texture and degrade-notice
  lanes, 45 passed; format_copies, the whole module. A lavapipe batch caught PVRTC codes read one
  ulp high under exact answers, fixed by the Argb8 class.
- clippy -D warnings (plain, m2v_gpu, m2v_cpu_icd) and rustdoc on ms01 and gem10.
2026-10-19 00:15:59 +03:00

183 lines
8.8 KiB
Rust

//! ASTC LDR textures on a device without their ASTC block: their blocks held as raw bytes in a
//! carrier, which copies move, and their samples read a decoded twin.
//!
//! - **Metal's answers** (an Apple M3 Max under macOS 27.0.1, our own probe): every ASTC LDR
//! format makes a texture, `Shared`, `Private` and memoryless, of every type but 1D and
//! multisampled, of `ShaderWrite` and `RenderTarget` usage too, and views as its sRGB or HDR
//! form. `getBytes` and a blit out of the texture hand back the blocks a write put there; a new
//! texture's blocks are zeros, which read magenta (an error block). Its reads and samples are
//! `bind::AstcDecode`'s.
//! - **The store.** Vulkan copies a compressed image's blocks as bytes. Such a texture holds its
//! blocks in an image of a *carrier*: a compressed format whose blocks are also 16 bytes, over
//! 4 x 4 texels, the first of [`CARRIERS`] the device copies (every Vulkan device has BC or ETC2,
//! which hold one). Each of the texture's blocks lies over 4 x 4 carrier texels, so a region of
//! the texture's blocks is a region of the carrier's ([`image_region`]). A level of the carrier
//! holds at least the blocks the texture's level holds ([`carrier_side`]): the carrier's side is
//! the least whose every level, halved as Vulkan halves it, keeps them (at most about the
//! texture's side in texels, 1 byte a texel), and a copy addresses the first of them.
//! - **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'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
//! texture (`RuntimeGap::DecodedHeapTexture`) and a view of another decode (the texture's HDR
//! form, or another footprint; `Feature::TextureView`). A shader write and
//! an attachment take no such image: Metal's functions write no compressed texture, and no pass
//! renders into one.
use super::copy_plan::ImageRegion;
use super::image_plan::{sample_count, ImageFacts, ImagePlan};
use super::texture_descriptor::{effective_usage, TextureLayout};
use metal2vulkan::bind::AstcDecode;
use metal2vulkan::device::FormatUsage;
use metal2vulkan::metal::format::{image_type, vk_format, FormatEmulation, FormatMapping};
use metal2vulkan::metal::TextureUsage;
use metal2vulkan::vk::{
Format, FormatFeatureFlags2, ImageAspectFlags, ImageCreateFlags, ImageUsageFlags,
};
/// The compressed formats whose blocks are 16 bytes over 4 x 4 texels, in the order an ASTC
/// texture's blocks take the first the device copies: BC7, BC3, BC2 and BC5 (desktop GPUs), then
/// ETC2's and EAC's (mobile GPUs).
pub(super) const CARRIERS: [Format; 6] = [
Format::BC7_UNORM_BLOCK,
Format::BC3_UNORM_BLOCK,
Format::BC2_UNORM_BLOCK,
Format::BC5_UNORM_BLOCK,
Format::ETC2_R8G8B8A8_UNORM_BLOCK,
Format::EAC_R11G11_UNORM_BLOCK,
];
/// The decode of the ASTC texture whose blocks `plan` holds in a carrier; `None` for any other
/// image.
pub(super) fn decode_of(plan: &ImagePlan) -> Option<AstcDecode> {
AstcDecode::of(plan.pixel_format).filter(|_| CARRIERS.contains(&plan.format))
}
/// The least carrier side, in carrier texels, whose `levels` levels each hold the blocks of
/// `block` texels a side that a texture of `side` texels holds at that level: the carrier's level
/// `l`, `max(1, c >> l)` wide, holds `ceil(max(1, c >> l) / 4)` blocks, at least `n` where
/// `c >= (4 n - 3) << l`. The last level's term is at least `2^(levels - 1)`, so the carrier takes
/// every level.
pub(super) fn carrier_side(side: u32, block: u32, levels: u32) -> u32 {
(0..levels)
.map(|l| {
let blocks = (side >> l).max(1).div_ceil(block);
(4 * blocks - 3) << l
})
.max()
.unwrap_or(1)
}
/// The image of an ASTC texture of `layout` with Metal `usage` on a device with `facts` that
/// holds its blocks in a carrier (the module docs): `None` for a texture of another format, or of
/// an ASTC format the device holds (its block, or no decoded twin: its refusal stands), or where
/// no carrier is copied (the device's refusal of the format stands).
pub(super) fn plan_blocks(
layout: &TextureLayout,
usage: TextureUsage,
facts: &ImageFacts<'_>,
) -> Option<ImagePlan> {
let pf = layout.pixel_format;
let decode = AstcDecode::of(pf)?;
let sampled = vk_format(pf, &[FormatUsage::SampledImage].into(), facts.profile).ok()?;
if sampled.emulation != FormatEmulation::Decoded {
return None;
}
let copies = FormatFeatureFlags2::TRANSFER_SRC | FormatFeatureFlags2::TRANSFER_DST;
let carrier = CARRIERS
.into_iter()
.find(|&f| facts.optimal(f).contains(copies))?;
// No create flags, never cube compatible: copies alone reach the carrier and no view of it is
// made, so a cube texture's faces are its layers.
let (image_type, _) = image_type(layout.texture_type)?;
let [width, height, depth] = layout.extent;
let [bw, bh] = decode.block_extent();
Some(ImagePlan {
pixel_format: pf,
flags: ImageCreateFlags::empty(),
image_type,
format: carrier,
extent: [
carrier_side(width, bw, layout.levels),
carrier_side(height, bh, layout.levels),
depth,
],
levels: layout.levels,
layers: layout.layers,
samples: sample_count(layout.samples)?,
usage: ImageUsageFlags::TRANSFER_SRC | ImageUsageFlags::TRANSFER_DST,
view_formats: Vec::new(),
mapping: FormatMapping::direct(carrier, ImageAspectFlags::COLOR),
// Its decoded twin serves its samples and reads. (`BlockWritesOnly` plans as
// `ShaderWrite` does, which Metal's functions never use on a compressed texture.)
unavailable: effective_usage(usage).intersection(
TextureUsage::SHADER_WRITE | TextureUsage::SHADER_ATOMIC | TextureUsage::RENDER_TARGET,
),
})
}
/// `region`, in the texels of the ASTC texture whose carrier `plan` plans (a region of whole
/// blocks, or ending at the level's edge), in the carrier's texels: each block 4 x 4 of them, the
/// region's last block's ending at the carrier level's edge where that comes first. `None` for an
/// image of another kind.
pub(super) fn image_region(plan: &ImagePlan, region: ImageRegion) -> Option<ImageRegion> {
let decode = decode_of(plan)?;
let [bw, bh] = decode.block_extent();
let [x, y, z] = region.origin;
let [width, height, depth] = region.size;
let level = |axis: usize| (plan.extent[axis] >> region.level.min(31)).max(1);
let span = |at: u32, size: u32, block: u32, axis: usize| {
let first = at / block;
let end = (at + size).div_ceil(block);
(4 * first, (4 * end).min(level(axis)) - 4 * first)
};
let (x, width) = span(x, width, bw, 0);
let (y, height) = span(y, height, bh, 1);
Some(ImageRegion {
origin: [x, y, z],
size: [width, height, depth],
..region
})
}
/// [`image_region`]'s inverse: `region` of the carrier `plan` plans, in the texture's texels, its
/// last block's ending at the texture level's edge (`extent`, the texture's level 0). `None` for
/// an image of another kind.
pub(super) fn texture_region(
plan: &ImagePlan,
extent: [u32; 3],
region: ImageRegion,
) -> Option<ImageRegion> {
let decode = decode_of(plan)?;
let [bw, bh] = decode.block_extent();
let [x, y, z] = region.origin;
let [width, height, depth] = region.size;
let level = |axis: usize| (extent[axis] >> region.level.min(31)).max(1);
let span = |at: u32, size: u32, block: u32, axis: usize| {
let first = at / 4;
let end = (at + size).div_ceil(4);
(
block * first,
(block * end).min(level(axis)) - block * first,
)
};
let (x, width) = span(x, width, bw, 0);
let (y, height) = span(y, height, bh, 1);
Some(ImageRegion {
origin: [x, y, z],
size: [width, height, depth],
..region
})
}
/// A buffer row length or image height of `texels` texture texels in carrier texels: its blocks
/// of `block` texels, 4 carrier texels each (0, tightly packed, stays 0).
pub(super) fn carrier_texels(texels: u32, block: u32) -> u32 {
texels / block * 4
}