craft-dds: expose shared BC1-7, ETC1/EAC, and packed pixel decoders (#778) (#2460)

* craft-dds: expose shared BC1-7, ETC1/EAC, and packed pixel decoders (#778)

* fix(dds): qualify super::anchor in bptc test

* craft-dds: add independent known-answer test vectors for BC6H, BC7, ETC1, and EAC

* fix(dds): remove unused partition/anchor imports in bptc test
This commit is contained in:
Dylan M. Taylor
2026-11-19 20:03:14 -05:00
committed by GitHub
parent 1546550b0d
commit 429937ad72
6 changed files with 1821 additions and 0 deletions
File diff suppressed because it is too large Load Diff
+107
View File
@@ -0,0 +1,107 @@
//! ETC1 and EAC 4×4 block decoders.
//!
//! EAC's 11-bit channel blocks are reduced to display bytes after reconstruction and clamping.
//! The signed layouts map -1..1 to 0..255 so negative values remain visible; zero is 128.
//! Layout and modifier tables: <https://registry.khronos.org/DataFormat/specs/1.4/dataformat.1.4.html>.
// Positive halves of the Khronos EAC modifier tables. Negative entries are -positive - 1.
const MODIFIERS: [[i16; 4]; 16] = [
[2, 5, 8, 14],
[2, 6, 9, 12],
[1, 4, 7, 12],
[1, 3, 5, 12],
[2, 5, 7, 11],
[2, 6, 8, 10],
[3, 6, 7, 10],
[2, 4, 7, 10],
[1, 5, 7, 9],
[1, 4, 7, 9],
[1, 3, 7, 9],
[1, 4, 6, 9],
[2, 3, 6, 9],
[0, 1, 2, 9],
[3, 5, 7, 8],
[2, 4, 6, 8],
];
fn split_halves(block: &[u8; 16]) -> ([u8; 8], [u8; 8]) {
let mut first = [0u8; 8];
let mut second = [0u8; 8];
for (i, x) in block.iter().enumerate() {
if i < 8 {
first[i] = *x;
} else {
second[i - 8] = *x;
}
}
(first, second)
}
/// ETC1 uses big-endian blocks and column-major selector bits, independently of the split.
/// Differential bases outside RGB555 are undefined by the format and are refused.
pub(crate) fn etc1(block: &[u8; 8]) -> Option<[[u8; 4]; 16]> {
const ETC1_MODIFIERS: [[i16; 2]; 8] = [[2, 8], [5, 17], [9, 29], [13, 42], [18, 60], [24, 80], [33, 106], [47, 183]];
let bits = u64::from_be_bytes(*block);
let differential = bits & (1 << 33) != 0;
let horizontal = bits & (1 << 32) != 0;
let mut bases = [[0i16; 3]; 2];
for (channel, shift) in [56, 48, 40].into_iter().enumerate() {
let value = ((bits >> shift) & 255) as i16;
let (first, second) = if differential {
let first = value >> 3;
let delta = ((value & 7) ^ 4) - 4;
let second = first + delta;
if !(0..=31).contains(&second) {
return None;
}
((first << 3) | (first >> 2), (second << 3) | (second >> 2))
} else {
((value >> 4) * 17, (value & 15) * 17)
};
bases[0][channel] = first;
bases[1][channel] = second;
}
let first_table = ETC1_MODIFIERS.get(((bits >> 37) & 7) as usize)?;
let second_table = ETC1_MODIFIERS.get(((bits >> 34) & 7) as usize)?;
Some(std::array::from_fn(|pixel| {
let (x, y) = (pixel % 4, pixel / 4);
let second = if horizontal { y >= 2 } else { x >= 2 };
let (base, table) = if second { (bases[1], second_table) } else { (bases[0], first_table) };
let selector = x * 4 + y;
let magnitude = if bits & (1 << selector) == 0 { table[0] } else { table[1] };
let delta = if bits & (1 << (selector + 16)) == 0 { magnitude } else { -magnitude };
let rgb = base.map(|channel| (channel + delta).clamp(0, 255) as u8);
[rgb[0], rgb[1], rgb[2], 255]
}))
}
fn channel(block: &[u8; 8], signed: bool) -> [u8; 16] {
let bits = u64::from_be_bytes(*block);
let base = if signed { i16::from((block[0] as i8).max(-127)) * 8 } else { i16::from(block[0]) * 8 + 4 };
let scale = (i16::from(block[1] >> 4) * 8).max(1);
let table = MODIFIERS.get(usize::from(block[1] & 15)).copied().unwrap_or_default();
std::array::from_fn(|pixel| {
let (x, y) = (pixel % 4, pixel / 4);
let selector = ((bits >> (45 - 3 * (x * 4 + y))) & 7) as usize;
let magnitude = table.get(selector & 3).copied().unwrap_or_default();
let modifier = if selector < 4 { -magnitude - 1 } else { magnitude };
let value = base + modifier * scale;
if signed {
let value = u32::try_from(value.clamp(-1023, 1023) + 1023).unwrap_or_default();
((value * 255 + 1023) / 2046) as u8
} else {
let value = u32::try_from(value.clamp(0, 2047)).unwrap_or_default();
((value * 255 + 1023) / 2047) as u8
}
})
}
pub(crate) fn scalar(block: &[u8; 8], signed: bool) -> [[u8; 4]; 16] {
channel(block, signed).map(|value| [value, value, value, 255])
}
pub(crate) fn dual(block: &[u8; 16], signed: bool) -> [[u8; 4]; 16] {
let (red, green) = split_halves(block);
let (red, green) = (channel(&red, signed), channel(&green, signed));
std::array::from_fn(|pixel| [red[pixel], green[pixel], 0, 255])
}
+7
View File
@@ -39,6 +39,10 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod bc;
pub mod bptc;
mod eac;
mod packed;
pub mod pixels;
use std::borrow::Cow;
use std::fmt;
@@ -84,6 +88,8 @@ pub enum DdsError {
Alloc(usize),
/// The decoded output exceeds the caller-selected per-buffer byte limit.
LimitExceeded { required: usize, limit: u64 },
/// Input pixel data ended before the declared dimensions or block count.
Truncated(String),
}
impl fmt::Display for DdsError {
@@ -94,6 +100,7 @@ impl fmt::Display for DdsError {
DdsError::Encode(reason) => write!(f, "DDS encode failed: {reason}"),
DdsError::Alloc(len) => write!(f, "cannot allocate {len} bytes for the texture"),
DdsError::LimitExceeded { required, limit } => write!(f, "decoded texture requires {required} bytes, exceeding limit {limit}"),
DdsError::Truncated(reason) => write!(f, "truncated pixel data: {reason}"),
}
}
}
+51
View File
@@ -0,0 +1,51 @@
//! Four-byte packed RGB layouts. Words are little-endian, with red in the low bits.
//! Unsigned floats: <https://registry.khronos.org/DataFormat/specs/1.4/dataformat.1.4.html>, sections 10.2 and 10.3.
use crate::bptc;
pub(crate) fn rgba1010102(bytes: &[u8; 4]) -> [u8; 4] {
let word = u32::from_le_bytes(*bytes);
let channel = |shift: u32| (((word >> shift) & 1023) * 255 + 511) / 1023;
[channel(0) as u8, channel(10) as u8, channel(20) as u8, (word >> 30) as u8 * 85]
}
// These unsigned formats share binary16's five-bit exponent and bias. Padding the
// six- or five-bit fraction with zeroes produces the same value in a positive half.
fn unsigned_float(bits: u16, padding: u32) -> f32 {
bptc::half(bits << padding)
}
pub(crate) fn rgb111110(bytes: &[u8; 4]) -> [u8; 4] {
let word = u32::from_le_bytes(*bytes);
let channel = |shift: u32, mask: u32, padding: u32| bptc::srgb8(unsigned_float(((word >> shift) & mask) as u16, padding));
[channel(0, 0x7ff, 4), channel(11, 0x7ff, 4), channel(22, 0x3ff, 5), 255]
}
pub(crate) fn rgb9e5(bytes: &[u8; 4]) -> [u8; 4] {
let packed = u32::from_le_bytes(*bytes);
let scale = 2.0f32.powi((packed >> 27) as i32 - 24);
let channel = |shift: u32| bptc::srgb8(((packed >> shift) & 0x1ff) as f32 * scale);
[channel(0), channel(9), channel(18), 255]
}
#[cfg(test)]
mod tests {
use super::unsigned_float;
#[test]
fn unsigned_float_boundaries_are_preserved_before_display_quantization() {
for (fraction_bits, padding, smallest, largest_subnormal, maximum) in
[(6, 4, 0x3580_0000, 0x387c_0000, 65024.0), (5, 5, 0x3600_0000, 0x3878_0000, 64512.0)]
{
let fractions = 1u16 << fraction_bits;
assert_eq!(unsigned_float(0, padding).to_bits(), 0);
assert_eq!(unsigned_float(1, padding).to_bits(), smallest);
assert_eq!(unsigned_float(fractions - 1, padding).to_bits(), largest_subnormal);
assert_eq!(unsigned_float(fractions, padding).to_bits(), 0x3880_0000);
assert_eq!(unsigned_float(31 * fractions - 1, padding), maximum);
assert_eq!(unsigned_float(31 * fractions, padding), f32::INFINITY);
assert!(unsigned_float(31 * fractions + 1, padding).is_nan());
assert!(unsigned_float(32 * fractions - 1, padding).is_nan());
}
}
}
+390
View File
@@ -0,0 +1,390 @@
//! Turning GPU textures' stored pixels into RGBA: uncompressed layouts, packed 32-bit layouts,
//! and 4×4 block formats (BC1–BC7, ETC1, and EAC). Rows come out in the order they're stored.
use crate::{DdsError, alloc_zeroed, bc, bptc, eac, packed, with_alpha};
/// Default RGBA output budget: 256 MiB, matching an 8192×8192 RGBA8 texture.
pub const DEFAULT_MAX_RGBA_BYTES: u64 = 256 << 20;
/// How a texture's pixels are laid out.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PixelLayout {
/// Alpha only (shown as white with that alpha).
Alpha8,
/// One grey channel.
R8,
/// One unsigned 16-bit channel, shown as grey.
R16,
/// Two unsigned 8-bit channels; blue is zero and alpha is opaque.
Rg8,
/// Two unsigned 16-bit channels; blue is zero and alpha is opaque.
Rg16,
/// Three unsigned 16-bit channels; alpha is opaque.
Rgb16,
/// Four unsigned 16-bit channels, including alpha.
Rgba16,
RHalf,
RgHalf,
RgbaHalf,
RFloat,
RgFloat,
RgbaFloat,
/// Nine-bit RGB mantissas with a shared five-bit exponent, displayed as opaque sRGB.
Rgb9e5,
/// Packed unsigned 10-bit RGB with two-bit alpha, low bits first.
Rgba1010102,
/// Packed unsigned 11/11/10-bit floating-point RGB, displayed as opaque sRGB.
Rgb111110Float,
Rgb24,
Rgba32,
Argb32,
Bgra32,
Rgb565,
Rgba4444,
Argb4444,
/// BC1 / DXT1.
Dxt1,
/// BC2 / DXT3: four-colour blocks with one explicit four-bit alpha value per texel.
Dxt3,
/// BC3 / DXT5.
Dxt5,
/// One channel in blocks (shown as grey).
Bc4,
/// Two channels in blocks, usually a normal map (blue is rebuilt from red and green).
Bc5,
/// High dynamic range RGB in blocks (unsigned half floats), tone-mapped to 8-bit sRGB.
Bc6h,
/// BC6H with signed half floats.
Bc6hSigned,
Bc7,
/// ETC1 RGB, with individual or differential base colours.
Etc1,
/// One EAC channel, shown as grey.
EacR,
/// One signed EAC channel; -1..1 maps to 0..255.
EacRSigned,
/// Two EAC channels; blue is zero and alpha is opaque.
EacRg,
/// Two signed EAC channels; -1..1 maps to 0..255.
EacRgSigned,
}
/// Bytes of a `width`×`height` picture in `layout`.
pub fn size(layout: PixelLayout, width: u32, height: u32) -> Option<usize> {
let (w, h) = (width as usize, height as usize);
let blocks = w.div_ceil(4).checked_mul(h.div_ceil(4))?;
match layout {
PixelLayout::Alpha8 | PixelLayout::R8 => w.checked_mul(h),
PixelLayout::Rgb565 | PixelLayout::Rgba4444 | PixelLayout::Argb4444 | PixelLayout::RHalf | PixelLayout::R16 | PixelLayout::Rg8 => {
w.checked_mul(h)?.checked_mul(2)
}
PixelLayout::Rgb24 => w.checked_mul(h)?.checked_mul(3),
PixelLayout::Rg16 => w.checked_mul(h)?.checked_mul(4),
PixelLayout::Rgb16 => w.checked_mul(h)?.checked_mul(6),
PixelLayout::Rgba16 => w.checked_mul(h)?.checked_mul(8),
PixelLayout::Rgba32
| PixelLayout::Argb32
| PixelLayout::Bgra32
| PixelLayout::RgHalf
| PixelLayout::RFloat
| PixelLayout::Rgb9e5
| PixelLayout::Rgba1010102
| PixelLayout::Rgb111110Float => w.checked_mul(h)?.checked_mul(4),
PixelLayout::RgbaHalf | PixelLayout::RgFloat => w.checked_mul(h)?.checked_mul(8),
PixelLayout::RgbaFloat => w.checked_mul(h)?.checked_mul(16),
PixelLayout::Dxt1 | PixelLayout::Bc4 | PixelLayout::Etc1 | PixelLayout::EacR | PixelLayout::EacRSigned => blocks.checked_mul(8),
PixelLayout::Dxt3
| PixelLayout::Dxt5
| PixelLayout::Bc5
| PixelLayout::Bc6h
| PixelLayout::Bc6hSigned
| PixelLayout::Bc7
| PixelLayout::EacRg
| PixelLayout::EacRgSigned => blocks.checked_mul(16),
}
}
/// Convert an IEEE 754 binary16 half-float's bits to `f32`.
pub fn half_to_f32(h: u16) -> f32 {
bptc::half(h)
}
/// Convert a linear-light value to 8-bit sRGB; 0..1 is kept, brighter and negative values clip.
pub fn linear_to_srgb8(v: f32) -> u8 {
bptc::srgb8(v)
}
/// Decode one BC1 (DXT1) 8-byte block into 16 RGBA8 texels (row by row).
pub fn decode_bc1_block(block: &[u8; 8]) -> [[u8; 4]; 16] {
bc::decode_colour(block, true)
}
/// Decode one BC2 (DXT3) 16-byte block into 16 RGBA8 texels (row by row).
pub fn decode_bc2_block(block: &[u8; 16]) -> [[u8; 4]; 16] {
with_alpha(bc::decode_colour(block.get(8..).unwrap_or_default(), false), bc::decode_bc2_alpha(block.get(..8).unwrap_or_default()))
}
/// Decode one BC3 (DXT5) 16-byte block into 16 RGBA8 texels (row by row).
pub fn decode_bc3_block(block: &[u8; 16]) -> [[u8; 4]; 16] {
with_alpha(bc::decode_colour(block.get(8..).unwrap_or_default(), false), bc::decode_values(block.get(..8).unwrap_or_default()))
}
/// Decode one BC4 8-byte block into 16 greyscale RGBA8 texels (`[r, r, r, 255]`, row by row).
pub fn decode_bc4_block(block: &[u8; 8]) -> [[u8; 4]; 16] {
bc::decode_values(block).map(|r| [r, r, r, 255])
}
/// Decode one BC5 16-byte normal-map block into 16 RGBA8 texels with reconstructed Z (row by row).
pub fn decode_bc5_block(block: &[u8; 16]) -> [[u8; 4]; 16] {
let (r, g) = (bc::decode_values(block.get(..8).unwrap_or_default()), bc::decode_values(block.get(8..).unwrap_or_default()));
std::array::from_fn(|k| {
let (x, y) = (f32::from(r[k]) / 127.5 - 1.0, f32::from(g[k]) / 127.5 - 1.0);
let z = (1.0 - x * x - y * y).max(0.0).sqrt();
[r[k], g[k], ((z + 1.0) * 127.5) as u8, 255]
})
}
/// Decode one BC6H 16-byte block into 16 sRGB8 RGBA texels (opaque).
pub fn decode_bc6h_block(block: &[u8; 16], signed: bool) -> [[u8; 4]; 16] {
bptc::bc6h(block, signed)
}
/// Decode one BC7 16-byte block into 16 RGBA8 texels (row by row).
pub fn decode_bc7_block(block: &[u8; 16]) -> [[u8; 4]; 16] {
bptc::bc7(block)
}
/// Decode one ETC1 8-byte block into 16 RGBA8 texels; returns `None` if differential colours overflow 5 bits.
pub fn decode_etc1_block(block: &[u8; 8]) -> Option<[[u8; 4]; 16]> {
eac::etc1(block)
}
/// Decode one single-channel EAC 8-byte block into 16 greyscale RGBA8 texels.
pub fn decode_eac_r_block(block: &[u8; 8], signed: bool) -> [[u8; 4]; 16] {
eac::scalar(block, signed)
}
/// Decode one dual-channel EAC 16-byte block into 16 RGBA8 texels (blue 0, alpha 255).
pub fn decode_eac_rg_block(block: &[u8; 16], signed: bool) -> [[u8; 4]; 16] {
eac::dual(block, signed)
}
/// Decode one little-endian `RGB9E5` 4-byte pixel into opaque sRGB8 RGBA.
pub fn decode_rgb9e5(bytes: &[u8; 4]) -> [u8; 4] {
packed::rgb9e5(bytes)
}
/// Decode one little-endian `RGBA1010102` 4-byte pixel into RGBA8.
pub fn decode_rgba1010102(bytes: &[u8; 4]) -> [u8; 4] {
packed::rgba1010102(bytes)
}
/// Decode one little-endian `R11G11B10_FLOAT` 4-byte pixel into opaque sRGB8 RGBA.
pub fn decode_rgb111110_float(bytes: &[u8; 4]) -> [u8; 4] {
packed::rgb111110(bytes)
}
fn unorm8(value: u16) -> u8 {
((u32::from(value) * 255 + 32767) / 65535) as u8
}
fn unorm16_pixels(samples: impl Iterator<Item = u16>, channels: usize) -> impl Iterator<Item = [u8; 4]> {
let mut samples = samples.map(unorm8);
std::iter::from_fn(move || {
let (r, g) = (samples.next()?, samples.next()?);
let b = if channels > 2 { samples.next()? } else { 0 };
let a = if channels > 3 { samples.next()? } else { 255 };
Some([r, g, b, a])
})
}
fn float_pixels(mut samples: impl Iterator<Item = f32>, channels: usize) -> impl Iterator<Item = [u8; 4]> {
std::iter::from_fn(move || {
let r = bptc::srgb8(samples.next()?);
if channels == 1 {
return Some([r, r, r, 255]);
}
let g = bptc::srgb8(samples.next()?);
if channels == 2 {
return Some([r, g, 0, 255]);
}
let b = bptc::srgb8(samples.next()?);
let a = (samples.next()?.clamp(0.0, 1.0) * 255.0).round() as u8;
Some([r, g, b, a])
})
}
fn expand5(v: u16) -> u8 {
let v = (v & 31) as u8;
(v << 3) | (v >> 2)
}
fn expand6(v: u16) -> u8 {
let v = (v & 63) as u8;
(v << 2) | (v >> 4)
}
fn rgb565(v: u16) -> [u8; 4] {
[expand5(v >> 11), expand6(v >> 5), expand5(v), 255]
}
fn nibbles(v: u16, order: [u32; 4]) -> [u8; 4] {
order.map(|shift| ((v >> shift) & 15) as u8 * 17)
}
fn place_blocks(out: &mut [u8], w: usize, h: usize, texels: impl Iterator<Item = [[u8; 4]; 16]>) {
let across = w.div_ceil(4);
for (i, block) in texels.enumerate() {
let (bx, by) = (i % across, i / across);
for (k, p) in block.iter().enumerate() {
let (x, y) = (bx * 4 + k % 4, by * 4 + k / 4);
if x < w && y < h {
let at = (y * w + x) * 4;
if let Some(dst) = out.get_mut(at..at + 4) {
dst.copy_from_slice(p);
}
}
}
}
}
/// Decode a `width`×`height` picture (`data` starts with it) into RGBA8, rows in stored order.
///
/// Caps the output at [`DEFAULT_MAX_RGBA_BYTES`]; use [`decode_with_limit`] for a different budget.
pub fn decode(layout: PixelLayout, width: u32, height: u32, data: &[u8]) -> Result<Vec<u8>, DdsError> {
decode_with_limit(layout, width, height, data, DEFAULT_MAX_RGBA_BYTES)
}
/// Decode into RGBA8, allowing at most `max_bytes` of output.
///
/// The budget applies to RGBA bytes, not the encoded input, and is checked before reading pixels
/// or reserving the output.
pub fn decode_with_limit(layout: PixelLayout, width: u32, height: u32, data: &[u8], max_bytes: u64) -> Result<Vec<u8>, DdsError> {
let need = size(layout, width, height).ok_or(DdsError::Alloc(usize::MAX))?;
let (w, h) = (width as usize, height as usize);
let out_len =
w.checked_mul(h).and_then(|pixels| pixels.checked_mul(4)).filter(|bytes| *bytes <= isize::MAX as usize).ok_or(DdsError::Alloc(usize::MAX))?;
if out_len as u64 > max_bytes {
return Err(DdsError::LimitExceeded { required: out_len, limit: max_bytes });
}
let data = data.get(..need).ok_or_else(|| DdsError::Truncated(format!("{} bytes of pixels, {need} needed", data.len())))?;
if w == 0 || h == 0 {
return Err(DdsError::Malformed("an empty picture".into()));
}
let mut out: Vec<u8> = alloc_zeroed(out_len)?;
let mut put = |px: &mut dyn Iterator<Item = [u8; 4]>| {
for (dst, p) in out.as_chunks_mut::<4>().0.iter_mut().zip(px) {
*dst = p;
}
};
let u16s = data.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b));
let floats = data.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b));
match layout {
PixelLayout::RHalf => put(&mut float_pixels(u16s.map(bptc::half), 1)),
PixelLayout::RgHalf => put(&mut float_pixels(u16s.map(bptc::half), 2)),
PixelLayout::RgbaHalf => put(&mut float_pixels(u16s.map(bptc::half), 4)),
PixelLayout::RFloat => put(&mut float_pixels(floats, 1)),
PixelLayout::RgFloat => put(&mut float_pixels(floats, 2)),
PixelLayout::RgbaFloat => put(&mut float_pixels(floats, 4)),
PixelLayout::Rgba1010102 => put(&mut data.as_chunks::<4>().0.iter().map(packed::rgba1010102)),
PixelLayout::Rgb111110Float => put(&mut data.as_chunks::<4>().0.iter().map(packed::rgb111110)),
PixelLayout::Rgb9e5 => put(&mut data.as_chunks::<4>().0.iter().map(packed::rgb9e5)),
PixelLayout::Alpha8 => put(&mut data.iter().map(|a| [255, 255, 255, *a])),
PixelLayout::R8 => put(&mut data.iter().map(|r| [*r, *r, *r, 255])),
PixelLayout::R16 => put(&mut u16s.map(|value| {
let grey = unorm8(value);
[grey, grey, grey, 255]
})),
PixelLayout::Rg8 => put(&mut data.as_chunks::<2>().0.iter().map(|[r, g]| [*r, *g, 0, 255])),
PixelLayout::Rg16 => put(&mut unorm16_pixels(u16s, 2)),
PixelLayout::Rgb16 => put(&mut unorm16_pixels(u16s, 3)),
PixelLayout::Rgba16 => put(&mut unorm16_pixels(u16s, 4)),
PixelLayout::Rgb24 => put(&mut data.as_chunks::<3>().0.iter().map(|[r, g, b]| [*r, *g, *b, 255])),
PixelLayout::Rgba32 => put(&mut data.as_chunks::<4>().0.iter().copied()),
PixelLayout::Argb32 => put(&mut data.as_chunks::<4>().0.iter().map(|[a, r, g, b]| [*r, *g, *b, *a])),
PixelLayout::Bgra32 => put(&mut data.as_chunks::<4>().0.iter().map(|[b, g, r, a]| [*r, *g, *b, *a])),
PixelLayout::Rgb565 => put(&mut u16s.map(rgb565)),
PixelLayout::Rgba4444 => put(&mut u16s.map(|v| nibbles(v, [12, 8, 4, 0]))),
PixelLayout::Argb4444 => put(&mut u16s.map(|v| nibbles(v, [8, 4, 0, 12]))),
PixelLayout::Dxt1 => place_blocks(&mut out, w, h, data.as_chunks::<8>().0.iter().map(decode_bc1_block)),
PixelLayout::Dxt3 => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(decode_bc2_block)),
PixelLayout::Dxt5 => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(decode_bc3_block)),
PixelLayout::Bc4 => place_blocks(&mut out, w, h, data.as_chunks::<8>().0.iter().map(decode_bc4_block)),
PixelLayout::Bc5 => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(decode_bc5_block)),
PixelLayout::Bc6h => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(|b| bptc::bc6h(b, false))),
PixelLayout::Bc6hSigned => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(|b| bptc::bc6h(b, true))),
PixelLayout::Bc7 => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(bptc::bc7)),
PixelLayout::EacR | PixelLayout::EacRSigned => {
place_blocks(&mut out, w, h, data.as_chunks::<8>().0.iter().map(|block| eac::scalar(block, layout == PixelLayout::EacRSigned)))
}
PixelLayout::EacRg | PixelLayout::EacRgSigned => {
place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(|block| eac::dual(block, layout == PixelLayout::EacRgSigned)))
}
PixelLayout::Etc1 => {
let mut valid = true;
let texels = data.as_chunks::<8>().0.iter().map_while(|block| {
let pixels = eac::etc1(block);
valid &= pixels.is_some();
pixels
});
place_blocks(&mut out, w, h, texels);
if !valid {
return Err(DdsError::Malformed("ETC1 differential colour is outside its five-bit range".into()));
}
}
}
Ok(out)
}
/// Flip a `width`-wide RGBA8 picture upside down.
pub fn flip_rows(rgba: &[u8], width: u32) -> Vec<u8> {
let row = (width as usize).saturating_mul(4).max(1);
rgba.chunks(row).rev().flatten().copied().collect()
}
#[cfg(test)]
mod tests {
use super::{PixelLayout, decode, decode_with_limit, flip_rows, size};
use crate::DdsError;
#[test]
fn uncompressed_and_swizzled_layouts() {
assert_eq!(decode(PixelLayout::Rgba32, 1, 2, &[1, 2, 3, 4, 5, 6, 7, 8]).unwrap(), [1, 2, 3, 4, 5, 6, 7, 8]);
assert_eq!(decode(PixelLayout::Argb32, 1, 1, &[9, 1, 2, 3]).unwrap(), [1, 2, 3, 9]);
assert_eq!(decode(PixelLayout::Bgra32, 1, 1, &[3, 2, 1, 9]).unwrap(), [1, 2, 3, 9]);
assert_eq!(decode(PixelLayout::Rgb24, 1, 1, &[1, 2, 3]).unwrap(), [1, 2, 3, 255]);
assert_eq!(decode(PixelLayout::Alpha8, 1, 1, &[7]).unwrap(), [255, 255, 255, 7]);
assert_eq!(decode(PixelLayout::R8, 1, 1, &[7]).unwrap(), [7, 7, 7, 255]);
assert_eq!(decode(PixelLayout::Rgb565, 1, 1, &0xf800u16.to_le_bytes()).unwrap(), [255, 0, 0, 255]);
assert_eq!(decode(PixelLayout::Rgba4444, 1, 1, &0xf00fu16.to_le_bytes()).unwrap(), [255, 0, 0, 255]);
assert_eq!(decode(PixelLayout::Argb4444, 1, 1, &0xff00u16.to_le_bytes()).unwrap(), [255, 0, 0, 255]);
assert_eq!(flip_rows(&[1, 1, 1, 1, 2, 2, 2, 2], 1), [2, 2, 2, 2, 1, 1, 1, 1]);
assert!(matches!(decode(PixelLayout::Rgba32, 2, 2, &[0; 15]), Err(DdsError::Truncated(_))));
assert!(matches!(decode(PixelLayout::Rgba32, 0, 1, &[]), Err(DdsError::Malformed(_))));
assert!(matches!(decode_with_limit(PixelLayout::R8, 2, 2, &[0; 4], 15), Err(DdsError::LimitExceeded { .. })));
}
#[test]
fn block_and_packed_layouts_crop_partial_blocks() {
assert_eq!(size(PixelLayout::Dxt1, 5, 5), Some(32));
assert_eq!(decode(PixelLayout::Dxt1, 5, 5, &[0; 32]).unwrap().len(), 100);
// DXT1: colour 0 red, colour 1 blue; the first texel uses index 1, the rest index 0.
let px = decode(PixelLayout::Dxt1, 4, 4, &[0x00, 0xf8, 0x1f, 0x00, 0b01, 0, 0, 0]).unwrap();
assert_eq!((&px[..4], &px[4..8]), (&[0, 0, 255, 255][..], &[255, 0, 0, 255][..]));
// DXT5: alpha 255 -> 0; first texel index 1 (0), rest index 0 (255).
let mut b = vec![255, 0, 1, 0, 0, 0, 0, 0];
b.extend_from_slice(&[0x00, 0xf8, 0x1f, 0x00, 0, 0, 0, 0]);
let px = decode(PixelLayout::Dxt5, 4, 4, &b).unwrap();
assert_eq!((px[3], px[7]), (0, 255));
// BC4 & BC5.
assert_eq!(&decode(PixelLayout::Bc4, 4, 4, &[200, 10, 0, 0, 0, 0, 0, 0]).unwrap()[..4], &[200, 200, 200, 255]);
let mut n = vec![128, 128, 0, 0, 0, 0, 0, 0];
n.extend_from_slice(&[128, 128, 0, 0, 0, 0, 0, 0]);
assert_eq!(&decode(PixelLayout::Bc5, 4, 4, &n).unwrap()[..4], &[128, 128, 254, 255]);
// Packed RGB9E5 & RGBA1010102.
let rgb9e5 = (256u32 | (128 << 9) | (64 << 18) | (15 << 27)).to_le_bytes();
assert_eq!(decode(PixelLayout::Rgb9e5, 1, 1, &rgb9e5).unwrap(), [188, 137, 99, 255]);
let rgba10 = (1023u32 | (512 << 10) | (2 << 30)).to_le_bytes();
assert_eq!(decode(PixelLayout::Rgba1010102, 1, 1, &rgba10).unwrap(), [255, 128, 0, 170]);
}
}
+114
View File
@@ -0,0 +1,114 @@
//! Independent known-answer test vectors (raw bitstreams and hand-verified spec outputs)
//! for BC6H (unsigned/signed), BC7, ETC1, and EAC R/RG (unsigned/signed).
use craft_dds::DdsError;
use craft_dds::pixels::{self, PixelLayout};
#[test]
fn bc7_mode6_known_bitstream() {
// Raw 128-bit BC7 Mode 6 block (7-bit RGBA endpoints + per-endpoint P-bits, 4-bit indices):
// e0 = (241, 121, 21, 255), e1 = (40, 200, 254, 128); texels 0..3 use indices 0, 15, 8, 4.
let block: [u8; 16] = [0x40, 0x3c, 0x85, 0x47, 0x56, 0xfc, 0xff, 0xc0, 0xf0, 0x48, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44];
let texels = pixels::decode_bc7_block(&block);
assert_eq!(texels[0], [241, 121, 21, 255]);
assert_eq!(texels[1], [40, 200, 254, 128]);
assert_eq!(texels[2], [134, 163, 145, 188]);
assert_eq!(texels[3], [188, 142, 83, 221]);
// Reserved mode (low byte 0x00) decodes to all zeroes.
assert_eq!(pixels::decode_bc7_block(&[0; 16]), [[0, 0, 0, 0]; 16]);
// Cropped 3x2 image keeps the top-left 3x2 texels in row-major order.
let rgba = pixels::decode(PixelLayout::Bc7, 3, 2, &block).unwrap();
assert_eq!(rgba.len(), 3 * 2 * 4);
assert_eq!(&rgba[..4], &[241, 121, 21, 255]);
assert_eq!(&rgba[4..8], &[40, 200, 254, 128]);
assert_eq!(&rgba[8..12], &[134, 163, 145, 188]);
}
#[test]
fn bc6h_unsigned_and_signed_known_bitstreams() {
// Mode 11 (untransformed 10-bit endpoints, 1 subset, 4-bit indices):
// e0 = (480, 400, 200), e1 = (200, 480, 400); texels 0..2 use indices 0, 15, 8.
let block: [u8; 16] = [0x03, 0x3c, 0xc8, 0x90, 0x41, 0x06, 0x3c, 0xc8, 0xf0, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
let unsigned = pixels::decode_bc6h_block(&block, false);
assert_eq!(unsigned[0], [228, 105, 7, 255]);
assert_eq!(unsigned[1], [7, 228, 105, 255]);
assert_eq!(unsigned[2], [51, 160, 39, 255]);
let signed_pos = pixels::decode_bc6h_block(&block, true);
assert_eq!(signed_pos[0], [255, 255, 105, 255]);
assert_eq!(signed_pos[1], [105, 255, 255, 255]);
assert_eq!(signed_pos[2], [255, 255, 255, 255]);
// Signed Mode 11 with negative 10-bit endpoints: R0 = -200 (0x338), G1 = -200 (0x338).
// Negative linear values clip to 0 in sRGB8 output.
let neg_block: [u8; 16] = [0x03, 0x67, 0x64, 0x20, 0x43, 0x06, 0x67, 0xc8, 0xf0, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
let signed_neg = pixels::decode_bc6h_block(&neg_block, true);
assert_eq!(signed_neg[0], [0, 105, 255, 255]);
assert_eq!(signed_neg[1], [105, 0, 255, 255]);
assert_eq!(signed_neg[2], [0, 0, 255, 255]);
let rgba = pixels::decode(PixelLayout::Bc6h, 2, 1, &block).unwrap();
assert_eq!(rgba, [228, 105, 7, 255, 7, 228, 105, 255]);
let rgba_signed = pixels::decode(PixelLayout::Bc6hSigned, 2, 1, &neg_block).unwrap();
assert_eq!(rgba_signed, [0, 105, 255, 255, 105, 0, 255, 255]);
}
#[test]
fn etc1_known_bitstreams_and_invalid_differential() {
// Individual mode (diff=0, flip=0): left half (x<2) RGB4=(15,0,8) + 2, right half (x>=2) RGB4=(0,15,4) + 5.
let individual: [u8; 8] = [0xf0, 0x0f, 0x84, 0x04, 0x00, 0x00, 0x00, 0x00];
let texels = pixels::decode_etc1_block(&individual).unwrap();
for y in 0..4 {
for x in 0..4 {
let expected = if x < 2 { [255, 2, 138, 255] } else { [5, 255, 73, 255] };
assert_eq!(texels[y * 4 + x], expected);
}
}
// Differential mode (diff=1, flip=1 horizontal): base0=(20,10,4), delta=(+2,-2,+1), tables=(2,3).
let differential: [u8; 8] = [0xa2, 0x56, 0x21, 0x4f, 0x00, 0x00, 0x00, 0x00];
let texels = pixels::decode_etc1_block(&differential).unwrap();
for y in 0..4 {
for x in 0..4 {
let expected = if y < 2 { [174, 91, 42, 255] } else { [194, 79, 54, 255] };
assert_eq!(texels[y * 4 + x], expected);
}
}
// Differential base + delta outside 0..=31 must be rejected.
let invalid: [u8; 8] = [0x04, 0x40, 0x40, 0x02, 0x00, 0x00, 0x00, 0x00];
assert!(pixels::decode_etc1_block(&invalid).is_none());
assert!(matches!(pixels::decode(PixelLayout::Etc1, 4, 4, &invalid), Err(DdsError::Malformed(_))));
}
#[test]
fn eac_r_and_rg_unsigned_and_signed_known_bitstreams() {
// Unsigned EAC_R: base=100, mult=2, table=0, all selectors=7 (+14) -> 1028/2047 -> 128.
let eac_r_u: [u8; 8] = [0x64, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
assert_eq!(pixels::decode_eac_r_block(&eac_r_u, false), [[128, 128, 128, 255]; 16]);
// Signed EAC_R: base=-64 (0xc0), mult=2, table=0, all selectors=0 (-3) -> (-560+1023)/2046 -> 58.
let eac_r_s: [u8; 8] = [0xc0, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
assert_eq!(pixels::decode_eac_r_block(&eac_r_s, true), [[58, 58, 58, 255]; 16]);
// Column-major selector order: texel (x=1, y=0) has selector 7 (+14 -> 142), others selector 0 (-3 -> 125).
let eac_col: [u8; 8] = [0x80, 0x10, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00];
let col_texels = pixels::decode_eac_r_block(&eac_col, false);
assert_eq!(col_texels[1], [142, 142, 142, 255]);
assert_eq!(col_texels[0], [125, 125, 125, 255]);
assert_eq!(col_texels[4], [125, 125, 125, 255]);
// Dual-channel EAC_RG (unsigned and signed): R then G.
let mut eac_rg_u = [0u8; 16];
eac_rg_u[..8].copy_from_slice(&eac_r_u);
eac_rg_u[8..].copy_from_slice(&[0xff, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]);
assert_eq!(pixels::decode(PixelLayout::EacRg, 2, 2, &eac_rg_u).unwrap(), [128, 255, 0, 255].repeat(4));
let mut eac_rg_s = [0u8; 16];
eac_rg_s[..8].copy_from_slice(&eac_r_s);
eac_rg_s[8..].copy_from_slice(&[0x7f, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]);
assert_eq!(pixels::decode(PixelLayout::EacRgSigned, 2, 2, &eac_rg_s).unwrap(), [58, 255, 0, 255].repeat(4));
}