Compare commits

...
Author SHA1 Message Date
elforeign 6d7523f5d1 Merge upstream main into test/metal-bc2-bc3
Resolves the CHANGELOG.md conflict with the claim-rules entry; both
entries are kept.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:55:23 -06:00
Ranveer Soni e86eedf583 Merge pull request #213 from elforeign/docs/claim-before-work
docs: require claiming an issue before starting work
2026-11-24 12:20:55 +05:30
elforeign 59ee786a12 metal: upload and read BC2 and BC3 blocks natively
BC2 and BC3 had CPU decoders (#167) but no native Metal path, so nothing
showed that the original 16-byte blocks reach the GPU and decode as the
specifications describe. This adds a pitched BcAlphaUpload with the BC1
upload's validation (shared, now measured in 16-byte blocks) and
NativeCompute::read_bc_alpha_upload, which places the blocks in BC2_RGBA
or BC3_RGBA textures behind the existing BC capability check.

The GPU tests cover explicit 4-bit alpha, six- and eight-value
interpolated alpha (equal endpoints included), descending, ascending and
equal colour endpoints, padded row and slice pitches, two layers and two
mips. Texels are compared with the CPU decoders and hand-derived anchors.
On an Apple M5 Pro interpolated values lie within 1.14 codes of the exact
values, two codes at most from the truncating CPU reference, which sets
the tolerance. Uploading BC3 as BC2, BC2 as BC1, or ignoring the row
pitch each fails the tests.

Refs #168

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:49:17 -06:00
elforeign 5df1f9146f docs: require claiming an issue before starting work
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:48:25 -06:00
Ranveer Soni 48e42d6d4b Merge pull request #182 from atesahmet0/fix/75-static-probe-c7
Fix C7 instruction boundaries and trusted fixture probe reporting
2026-11-24 12:12:44 +05:30
Ranveer Soni 951189c61b Merge pull request #167 from elforeign/feat/texture-bc-formats
texture: BC2, BC3, BC4 and BC5 CPU block decoders
2026-11-24 11:58:17 +05:30
elforeign 7c89ed62a2 changelog: record BC2-BC5 CPU block decoders
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:11:35 -06:00
elforeign f19d57967d Merge remote-tracking branch 'origin/main' into feat/texture-bc-formats 2026-11-24 00:11:08 -06:00
elforeign ef1a94ce71 texture: add BC2, BC3, BC4 and BC5 block decoders
Adds spec-derived CPU decoders (UNORM and SNORM for BC4/BC5) with
truncating integer interpolation and hand-computed tests, so later
texture work has verified references for these formats.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:01:14 -06:00
11 changed files with 953 additions and 60 deletions

No files matched your search

+4 -1
View File
@@ -1,6 +1,8 @@
## Summary
<!-- What changes, and why? Link an issue if relevant. -->
<!-- What changes, and why? -->
Closes #<!-- the issue you claimed -->
## Implementation and evidence
@@ -23,6 +25,7 @@
## Checklist
- [ ] I claimed the linked issue before starting, and the claim was still mine when I opened this pull request.
- [ ] I reviewed the changes and disclosed material AI assistance below, if applicable.
- [ ] The change preserves native ARM64 and Metal-first requirements.
- [ ] I added relevant tests or explained why they are not applicable.
+13
View File
@@ -45,6 +45,19 @@ No AI slop (section 29).
Read docs/interfaces.md and docs/progress.md before implementation.
## Claiming work before you start
Several people and coding agents work on this repository at the same time. An issue with no visible claim is the only signal that a task is free, so claim before you edit anything.
1. **Check.** Read the issue's comments, assignees and labels, its linked pull requests, and open pull requests that touch the same files. If someone holds a live claim, pick another task. Do not start parallel work on a claimed task.
2. **Claim.** Comment `/claim` on the issue (or run `scripts/agent-queue.sh claim <n>`). Where the claim workflow is enabled, wait for its grant comment and the `claimed-by:<login>` label; a refusal names the reason. Where it is not enabled yet, your comment is the claim and the earliest valid claim comment wins. One issue per claim; claim follow-up tasks separately.
3. **Respect file ownership.** Two claimed tasks never edit the same files at the same time. If the issue lists files, edit only those; ask the maintainer before widening the list.
4. **Keep it alive.** A claim lapses 24 hours after the latest grant, `/progress <what changed>` comment, or push to the linked pull request. Post `/progress` at least once a day while you work. Lapsed tasks return to the queue and may be claimed by anyone.
5. **Release.** If you stop, comment `/release` so the task returns to the queue. Use `/blocked <reason>` instead if you are waiting on another task.
6. **Link.** Open the pull request from a branch named `task/<n>-<slug>` with `Closes #<n>` in its description.
An agent acting for a contributor claims in that contributor's name and must not claim work for areas that contributor may not claim (`.github/agent-queue.json`). Never remove, overwrite or ignore another person's claim; ask the maintainer to `/reassign` instead. See `docs/coordination/agent-tasks.md` when present.
## Changelog maintenance
- At the start of every engineering task, read `CHANGELOG.md` alongside the relevant project documentation. Review the existing `[Unreleased]` entries before implementation to avoid duplicating completed work.
+9
View File
@@ -11,6 +11,15 @@ remains unsupported.
### Added
- Added explicit claim-before-work rules for contributors and coding agents to `AGENTS.md`, `CONTRIBUTING.md` and the pull request template: check for existing claims, claim with `/claim`, keep a 24-hour lease alive with `/progress`, `/release` when stopping, and link the claimed issue. Without the claim workflow, the earliest valid claim comment wins.
- Added native Metal upload and readback of BC2 and BC3 textures: `xenora-texture` gains a
pitched `BcAlphaUpload` for 16-byte blocks, and `NativeCompute::read_bc_alpha_upload` sends
the original blocks to `BC2_RGBA` or `BC3_RGBA` textures when the device reports BC support.
GPU tests cover explicit and interpolated (six- and eight-value) alpha, both colour endpoint
orders, padded row and slice pitches, two layers and two mips against the CPU decoders and
hand-derived anchors. On an Apple M5 Pro the native decoder's interpolated values were within
1.14 codes of the exact values, so up to two codes from the truncating CPU reference.
- Added CPU block decoders for BC2, BC3, BC4 and BC5 (UNORM and SNORM) in `xenora-texture`, with tests whose expected texels were derived by hand from the Microsoft and Khronos block-compression specifications. Interpolated values truncate toward zero, as the existing BC1 decoder does; GPU upload and sampling of these formats are not implemented yet.
- Added `dbt::tests::sib_store_executes_through_the_native_dbt`, an independent DBT execution
test that runs the SIB store form `mov [rsp + 0x20], rbx` through the native ARM64 DBT and
verifies the value lands in guest memory.
+1
View File
@@ -6,6 +6,7 @@ Xenora is an experimental Xbox Series X|S recompilation framework for Apple Sili
- Read `README.md` and, when present, `AGENTS.md`, `docs/interfaces.md`, `docs/status.toml` and the relevant architecture decisions.
- Discuss substantial changes in an issue before implementing them; small fixes do not require prior approval.
- Claim an issue before working on it by commenting `/claim`, and check that nobody else holds a live claim first. Claims lapse after 24 hours without a `/progress` comment or a push; comment `/release` if you stop. Coding agents follow the same rules; see "Claiming work before you start" in `AGENTS.md`.
- Use a native ARM64 macOS environment with Rust and the appropriate Xcode/Metal tools. LLVM AMDGPU tools are needed for ISA fixture generation; extra tooling depends on the subsystem.
- Keep changes focused and preserve existing public interfaces unless a change is justified and documented.
+66 -21
View File
@@ -16,7 +16,7 @@ use objc2_metal::{
MTLResourceOptions, MTLShaderValidation, MTLSize, MTLStorageMode, MTLTexture,
MTLTextureDescriptor, MTLTextureUsage,
};
use xenora_texture::{Bc1Upload, TiledBc1};
use xenora_texture::{Bc1Upload, BcAlphaFormat, BcAlphaUpload, TiledBc1};
#[path = "render.rs"]
mod render;
@@ -26,12 +26,12 @@ const MAX_GROUPS: usize = 64;
const MAX_GRID_WORDS: usize = MAX_GROUPS * MAX_THREADS_PER_GROUP;
const MAX_SOURCE_BYTES: usize = 64 * 1024;
const BC1_READBACK: &str = r"
const BC_READBACK: &str = r"
#include <metal_stdlib>
using namespace metal;
kernel void read_bc1(texture2d<float, access::read> image [[texture(0)]],
device uint *output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
kernel void read_bc(texture2d<float, access::read> image [[texture(0)]],
device uint *output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
uint width = image.get_width();
uint4 channels = uint4(round(image.read(uint2(index % width, index / width)) * 255.0f));
output[index] = channels.r | (channels.g << 8u) | (channels.b << 16u) | (channels.a << 24u);
@@ -184,11 +184,18 @@ impl NativeCompute {
let (width, height) = tiled
.mip_extent(mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
let pixels = self.validate_bc1_extent(width, height)?;
let pixels = self.validate_bc_extent(width, height, "BC1")?;
let blocks = tiled
.linearize(layer, mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
self.read_bc1_blocks(&blocks, width.div_ceil(4) * 8, width, height, pixels)
self.read_bc_blocks(
MTLPixelFormat::BC1_RGBA,
&blocks,
width.div_ceil(4) * 8,
width,
height,
pixels,
)
}
/// Sample a native Metal RGBA8 texture using a native Metal sampler on Apple Silicon GPU.
@@ -269,8 +276,9 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
let level = upload
.subresource(layer, mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
let pixels = self.validate_bc1_extent(level.width, level.height)?;
self.read_bc1_blocks(
let pixels = self.validate_bc_extent(level.width, level.height, "BC1")?;
self.read_bc_blocks(
MTLPixelFormat::BC1_RGBA,
level.bytes,
level.row_pitch,
level.width,
@@ -279,7 +287,45 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
)
}
fn validate_bc1_extent(&self, width: usize, height: usize) -> Result<usize, MetalError> {
/// Read a selected subresource from a validated pitched BC2 or BC3 upload.
///
/// The original 16-byte blocks go to a native `BC2_RGBA` or `BC3_RGBA`
/// texture, and the output has the layout of [`Self::read_bc1_upload`].
///
/// # Errors
///
/// Returns an error for an invalid layer or mip, out-of-policy size,
/// unavailable BC compression, or Metal setup or execution failure.
pub fn read_bc_alpha_upload(
&self,
upload: &BcAlphaUpload<'_>,
layer: usize,
mip: u32,
) -> Result<Vec<u32>, MetalError> {
let level = upload
.subresource(layer, mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
let (format, name) = match upload.format() {
BcAlphaFormat::Bc2 => (MTLPixelFormat::BC2_RGBA, "BC2"),
BcAlphaFormat::Bc3 => (MTLPixelFormat::BC3_RGBA, "BC3"),
};
let pixels = self.validate_bc_extent(level.width, level.height, name)?;
self.read_bc_blocks(
format,
level.bytes,
level.row_pitch,
level.width,
level.height,
pixels,
)
}
fn validate_bc_extent(
&self,
width: usize,
height: usize,
name: &str,
) -> Result<usize, MetalError> {
let pixels = width
.checked_mul(height)
.filter(|pixels| (1..=MAX_GRID_WORDS).contains(pixels))
@@ -287,14 +333,15 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
if !self.device.supportsBCTextureCompression() {
return Err(MetalError::new(
"supportsBCTextureCompression",
"BC1 is unavailable",
format!("{name} is unavailable"),
));
}
Ok(pixels)
}
fn read_bc1_blocks(
fn read_bc_blocks(
&self,
format: MTLPixelFormat,
blocks: &[u8],
row_pitch: usize,
width: usize,
@@ -302,14 +349,11 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
pixels: usize,
) -> Result<Vec<u32>, MetalError> {
autoreleasepool(|_| {
// SAFETY: The positive bounded dimensions and supported BC1 format
// SAFETY: The positive bounded dimensions and supported BC format
// describe a 2D texture with just its base level.
let descriptor = unsafe {
MTLTextureDescriptor::texture2DDescriptorWithPixelFormat_width_height_mipmapped(
MTLPixelFormat::BC1_RGBA,
width,
height,
false,
format, width, height, false,
)
};
descriptor.setStorageMode(MTLStorageMode::Shared);
@@ -318,7 +362,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
.device
.newTextureWithDescriptor(&descriptor)
.ok_or_else(|| {
MetalError::new("newTextureWithDescriptor", "BC1 allocation failed")
MetalError::new("newTextureWithDescriptor", "BC allocation failed")
})?;
let region = MTLRegion {
origin: MTLOrigin { x: 0, y: 0, z: 0 },
@@ -332,7 +376,8 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
let bytes_per_row = if height <= 4 { 0 } else { row_pitch };
// SAFETY: The region spans the whole level, including any partial
// edge block. Both callers validate that the input holds all rows
// of complete BC1 blocks at the supplied, block-aligned stride.
// of complete blocks of this format at the supplied, block-aligned
// stride.
unsafe {
texture.replaceRegion_mipmapLevel_withBytes_bytesPerRow(
region,
@@ -342,8 +387,8 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
);
}
self.run(
BC1_READBACK,
"read_bc1",
BC_READBACK,
"read_bc",
ComputeInput::Texture(&texture, pixels),
)
.map(|profile| profile.output)
@@ -0,0 +1,287 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Native Metal upload and readback of original BC2 and BC3 blocks.
//!
//! Every block below was written for this test. The full-texel reference is
//! the `xenora-texture` CPU decoder; the anchor texels are worked by hand from
//! the Microsoft Direct3D 11 block-compression documentation (BC2, BC3) and
//! the Khronos Data Format Specification 1.3 (S3TC DXT3/DXT5). Apple's GPU
//! decoder is the value under test, so expected and actual values come from
//! different decoders.
use super::context;
use xenora_texture::{BcAlphaFormat, BcAlphaUpload, BcAlphaUploadDesc, decode_bc2, decode_bc3};
/// The specifications define colour and BC3 alpha interpolation in real
/// numbers, and the CPU reference truncates them. On an Apple M5 Pro the
/// native decoder's interpolated values lie within 1.14 codes of the real
/// value (they match 6-bit fixed-point weights), so they can sit two codes
/// above the truncated reference: 124 against 122 for BC3 alpha
/// (4 * 200 + 3 * 20) / 7 = 122.86. Endpoints, BC2 alpha and BC3's fixed
/// 0 and 255 are exact and are pinned by the anchor checks.
const TOLERANCE: u8 = 2;
/// Bound for anchors against the real-number value of an interpolated code.
const REAL_TOLERANCE: f64 = 1.5;
fn assert_near(label: &str, actual: u8, real: f64) {
assert!(
(f64::from(actual) - real).abs() <= REAL_TOLERANCE,
"{label}: got {actual}, real value {real:.2}"
);
}
const WIDTH: usize = 5;
const HEIGHT: usize = 5;
const ROW_PITCH: usize = 48;
const SLICE_PITCH: usize = 112;
/// Colour half: two little-endian RGB565 endpoints, then 2-bit indices.
/// Every row of 0xe4 selects palette entries 0, 1, 2, 3 from left to right.
fn colour((first, second): (u16, u16)) -> [u8; 8] {
let [a, b] = first.to_le_bytes();
let [c, d] = second.to_le_bytes();
[a, b, c, d, 0xe4, 0xe4, 0xe4, 0xe4]
}
/// BC3 alpha half whose texel `t` selects palette entry `(t + 6) % 8`, so
/// every row starts with the indices 6 and 7 and a full block uses all eight.
fn bc3_alpha(first: u8, second: u8) -> [u8; 8] {
let bits = (0..16u64).fold(0, |bits, texel| bits | (((texel + 6) % 8) << (3 * texel)));
let i = bits.to_le_bytes();
[first, second, i[0], i[1], i[2], i[3], i[4], i[5]]
}
fn block(alpha: [u8; 8], colour: [u8; 8]) -> [u8; 16] {
let mut block = [0; 16];
block[..8].copy_from_slice(&alpha);
block[8..].copy_from_slice(&colour);
block
}
// First endpoint greater: red over blue.
const DESCENDING: (u16, u16) = (0xf800, 0x001f);
// First endpoint smaller, with odd channel values that exercise rounding.
const ASCENDING: (u16, u16) = (0x52aa, 0xad55);
// Equal endpoints: BC1 would decode index 3 as transparent black.
const EQUAL: (u16, u16) = (0x07e0, 0x07e0);
/// White with zero alpha (BC2 nibbles 0; BC3 endpoints 0 and 0) in every
/// padding slot, so a wrong row or slice pitch reads visibly wrong texels.
const PAD: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0];
/// Logical blocks of one layer: the 2×2 base-level grid, then mip 1.
type Layer = [[u8; 16]; 5];
/// Two layers of a 5×5 texture with two mips. Each subresource has seven
/// physical blocks: rows of two logical blocks plus one padding block, a
/// padding block that closes the slice, and mip 1 uses only its block zero.
fn upload_bytes(layers: [Layer; 2]) -> Vec<u8> {
let mut bytes = Vec::new();
for [b0, b1, b2, b3, small] in layers {
for slot in [b0, b1, PAD, b2, b3, PAD, PAD] {
bytes.extend_from_slice(&slot);
}
for slot in [small, PAD, PAD, PAD, PAD, PAD, PAD] {
bytes.extend_from_slice(&slot);
}
}
assert_eq!(bytes.len(), 2 * 2 * SLICE_PITCH);
bytes
}
/// Crops decoded blocks (a row-major block grid) to a `width`×`height` level
/// of words with red in the lowest byte, as the readback kernel writes them.
fn reference(blocks: &[[[u8; 4]; 16]], blocks_x: usize, width: usize, height: usize) -> Vec<u32> {
let mut texels = Vec::new();
for y in 0..height {
for x in 0..width {
let decoded = blocks[(y / 4) * blocks_x + x / 4];
texels.push(u32::from_le_bytes(decoded[(y % 4) * 4 + x % 4]));
}
}
texels
}
fn alpha(word: u32) -> u8 {
word.to_le_bytes()[3]
}
/// Returns the largest per-channel difference, failing on any texel above the
/// tolerance with its index and both values.
fn assert_close(label: &str, actual: &[u32], expected: &[u32]) -> u8 {
assert_eq!(actual.len(), expected.len(), "{label}: texel count");
let mut worst = 0;
for (texel, (&got, &want)) in actual.iter().zip(expected).enumerate() {
let diff = got
.to_le_bytes()
.iter()
.zip(want.to_le_bytes())
.map(|(g, w)| g.abs_diff(w))
.max()
.unwrap();
assert!(
diff <= TOLERANCE,
"{label}: texel {texel} got {got:#010x}, want {want:#010x}"
);
worst = worst.max(diff);
}
worst
}
/// GPU reads of both layers: `[layer][mip]`.
type Reads = [[Vec<u32>; 2]; 2];
/// Uploads both layers, reads all four subresources on the GPU, compares
/// them with the CPU decoder and returns the reads with the worst difference.
fn read_and_compare(
format: BcAlphaFormat,
decode: fn([u8; 16]) -> [[u8; 4]; 16],
layers: [Layer; 2],
) -> (Reads, u8) {
let bytes = upload_bytes(layers);
let upload = BcAlphaUpload::new(
&bytes,
BcAlphaUploadDesc {
width: WIDTH,
height: HEIGHT,
mips: 2,
layers: 2,
format,
row_pitch: ROW_PITCH,
slice_pitch: SLICE_PITCH,
},
)
.unwrap();
let gpu = context();
let mut worst = 0;
let reads = std::array::from_fn(|layer| {
let decoded = layers[layer].map(decode);
let base = gpu.read_bc_alpha_upload(&upload, layer, 0).unwrap();
let expected = reference(&decoded[..4], 2, WIDTH, HEIGHT);
let label = format!("{format:?} layer {layer}");
worst = worst.max(assert_close(&format!("{label} mip 0"), &base, &expected));
let small = gpu.read_bc_alpha_upload(&upload, layer, 1).unwrap();
let expected = reference(&decoded[4..], 1, 2, 2);
worst = worst.max(assert_close(&format!("{label} mip 1"), &small, &expected));
[base, small]
});
for (layer, mip) in [(2, 0), (0, 2)] {
assert_eq!(
gpu.read_bc_alpha_upload(&upload, layer, mip)
.unwrap_err()
.operation,
"texture subresource"
);
}
(reads, worst)
}
#[test]
fn reads_pitched_bc2_explicit_alpha_across_mips_and_layers() {
// Nibble t in texel t, low nibble first: alpha t * 17.
let ramp = [0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe];
let reverse = ramp.map(|byte: u8| !byte);
let opaque = [0xff; 8];
let [descending, ascending, equal] = [DESCENDING, ASCENDING, EQUAL].map(colour);
let (reads, worst) = read_and_compare(
BcAlphaFormat::Bc2,
decode_bc2,
[
[
block(ramp, descending),
block(reverse, ascending),
block(opaque, equal),
block(ramp, ascending),
block(reverse, descending),
],
[
block(opaque, ascending),
block(ramp, equal),
block(reverse, descending),
block(opaque, descending),
block(ramp, equal),
],
],
);
// Hand-derived anchors, independent of the CPU decoder.
let base = &reads[0][0];
// (0, 0): red endpoint, nibble 0. (1, 0): blue endpoint, nibble 1.
assert_eq!(base[0], 0x0000_00ff);
assert_eq!(base[1], 0x11ff_0000);
// (0, 2) is texel 8 of block 0: red endpoint, nibble 8 -> 0x88.
assert_eq!(base[2 * WIDTH], 0x8800_00ff);
// (3, 3) is texel 15 of block 0: nibble 15 -> opaque.
assert_eq!(alpha(base[3 * WIDTH + 3]), 0xff);
// (4, 0) is texel 0 of block 1: reversed ramp, nibble 15.
assert_eq!(alpha(base[4]), 0xff);
// (3, 4) is index 3 of block 2's equal green endpoints: opaque green,
// not BC1's transparent black.
assert_eq!(base[4 * WIDTH + 3], 0xff00_ff00);
// Layer 1 mip 1: green endpoints, ramp nibbles 0, 1, 4, 5.
assert_eq!(
reads[1][1],
[0x0000_ff00, 0x1100_ff00, 0x4400_ff00, 0x5500_ff00]
);
println!("checked 58 BC2 texels from four subresources, worst channel difference {worst}");
}
#[test]
fn reads_pitched_bc3_interpolated_alpha_across_mips_and_layers() {
// First endpoint greater: eight-value palette.
let eight = bc3_alpha(200, 20);
// First endpoint smaller: six-value palette with fixed 0 and 255.
let six = bc3_alpha(20, 200);
// Equal endpoints also select the six-value palette.
let level = bc3_alpha(128, 128);
let [descending, ascending, equal] = [DESCENDING, ASCENDING, EQUAL].map(colour);
let (reads, worst) = read_and_compare(
BcAlphaFormat::Bc3,
decode_bc3,
[
[
block(eight, descending),
block(six, ascending),
block(level, equal),
block(eight, ascending),
block(six, descending),
],
[
block(six, equal),
block(eight, ascending),
block(level, descending),
block(six, ascending),
block(eight, equal),
],
],
);
// Hand-derived anchors, independent of the CPU decoder.
let base = &reads[0][0];
let a = |x: usize, y: usize| alpha(base[y * WIDTH + x]);
// Block 0, eight-value: row 0 holds indices 6, 7, 0, 1, and row 1
// indices 2, 3, 4, 5, each (k = index - 1) ((7 - k) * 200 + k * 20) / 7.
assert_near("index 6", a(0, 0), (2.0 * 200.0 + 5.0 * 20.0) / 7.0);
assert_near("index 7", a(1, 0), (200.0 + 6.0 * 20.0) / 7.0);
for (x, k) in (0..4).zip(1..) {
let real = f64::from((7 - k) * 200 + k * 20) / 7.0;
assert_near(&format!("index {}", k + 1), a(x, 1), real);
}
// Then the endpoints themselves, exactly; texel (0, 0) is the red endpoint.
assert_eq!([a(2, 0), a(3, 0)], [200, 20]);
assert_eq!(base[0] & 0x00ff_ffff, 0x0000_00ff);
// Block 1, six-value: column 4 holds indices 6, 2, 6, 2. Index 6 is the
// fixed 0 and index 2 is (4 * 20 + 200) / 5 = 56.
assert_eq!([a(4, 0), a(4, 2)], [0, 0]);
assert_near("six-value index 2", a(4, 1), 56.0);
assert_near("six-value index 2", a(4, 3), 56.0);
// Block 2, equal endpoints of 128: row 4 holds indices 6, 7, 0, 1, so the
// six-value mode shows as the fixed 0 and 255.
assert_eq!([a(0, 4), a(1, 4), a(2, 4), a(3, 4)], [0, 255, 128, 128]);
// Mip 1, six-value: indices 6, 7, 2, 3 -> 0, 255, 56, (3 * 20 + 2 * 200) / 5 = 92.
let small: Vec<_> = reads[0][1].iter().copied().map(alpha).collect();
assert_eq!(small[..2], [0, 255]);
assert_near("six-value index 2", small[2], 56.0);
assert_near("six-value index 3", small[3], 92.0);
println!("checked 58 BC3 texels from four subresources, worst channel difference {worst}");
}
+2
View File
@@ -6,6 +6,8 @@ mod guest_buffer;
mod offscreen;
#[path = "native/texture.rs"]
mod texture;
#[path = "native/texture_bc_alpha.rs"]
mod texture_bc_alpha;
#[path = "native/texture_sampling.rs"]
mod texture_sampling;
#[path = "native/translated_render.rs"]
+138
View File
@@ -0,0 +1,138 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! CPU block decoders for BC2, BC3, BC4 and BC5.
//!
//! Sources (public): Microsoft, "Texture Block Compression in Direct3D 11"
//! (sections BC2, BC3, BC4, BC5) and "Block Compression (Direct3D 10)"; Khronos
//! Data Format Specification 1.3, sections "S3TC compressed texture image
//! formats" and "RGTC compressed texture image formats".
//!
//! Colour blocks of BC2 and BC3 always use the four-colour interpolation,
//! whatever the order of their endpoints (Khronos, "S3TC compressed texture
//! image formats", DXT3/DXT5 subsections; the BC1 three-colour/alpha mode does
//! not apply). Texels are row-major, texel 0 at the top-left.
//!
//! Rounding: every interpolated value uses integer division that truncates
//! toward zero (the same rule `decode_bc1` uses). For unsigned values that is
//! floor. BC2 alpha nibbles expand as `v * 17`. The specifications define the
//! interpolation in real numbers; truncation is this crate's integer choice.
//!
//! SNORM: the specification maps both -128 and -127 to -1.0. Endpoints are
//! compared as the stored signed bytes; for interpolation -128 is treated as
//! -127. Output bytes are the stored endpoint bytes for indices 0 and 1 (so
//! -128 is preserved, not rewritten) and -127 / 127 for the fixed values.
use super::rgb565;
/// Reads texel `n` of a packed little-endian 48-bit array of 3-bit indices.
fn index3(bytes: &[u8; 6], n: usize) -> usize {
let mut bits = 0u64;
for (i, b) in bytes.iter().enumerate() {
bits |= u64::from(*b) << (8 * i);
}
((bits >> (3 * n)) & 7) as usize
}
fn unorm_palette(a0: u8, a1: u8) -> [u8; 8] {
let (x, y) = (u16::from(a0), u16::from(a1));
let mut p = [a0, a1, 0, 0, 0, 0, 0, 255];
if a0 > a1 {
for k in 1..=6u16 {
p[(k + 1) as usize] = (((7 - k) * x + k * y) / 7) as u8;
}
} else {
for k in 1..=4u16 {
p[(k + 1) as usize] = (((5 - k) * x + k * y) / 5) as u8;
}
p[6] = 0;
}
p
}
fn snorm_palette(a0: i8, a1: i8) -> [i8; 8] {
let x = i16::from(a0).max(-127);
let y = i16::from(a1).max(-127);
let mut p = [a0, a1, 0, 0, 0, 0, 0, 0];
if a0 > a1 {
for k in 1..=6i16 {
p[(k + 1) as usize] = (((7 - k) * x + k * y) / 7) as i8;
}
} else {
for k in 1..=4i16 {
p[(k + 1) as usize] = (((5 - k) * x + k * y) / 5) as i8;
}
p[6] = -127;
p[7] = 127;
}
p
}
fn unorm_block(block: &[u8]) -> [u8; 16] {
let p = unorm_palette(block[0], block[1]);
let idx: [u8; 6] = block[2..8].try_into().unwrap();
std::array::from_fn(|t| p[index3(&idx, t)])
}
fn snorm_block(block: &[u8]) -> [i8; 16] {
let p = snorm_palette(block[0] as i8, block[1] as i8);
let idx: [u8; 6] = block[2..8].try_into().unwrap();
std::array::from_fn(|t| p[index3(&idx, t)])
}
/// Decodes a BC4 UNORM block to 16 row-major red values.
pub fn decode_bc4_unorm(block: [u8; 8]) -> [u8; 16] {
unorm_block(&block)
}
/// Decodes a BC4 SNORM block to 16 row-major signed red values.
pub fn decode_bc4_snorm(block: [u8; 8]) -> [i8; 16] {
snorm_block(&block)
}
/// Decodes a BC5 UNORM block; each texel is `[red, green]` (first 8 bytes red).
pub fn decode_bc5_unorm(block: [u8; 16]) -> [[u8; 2]; 16] {
let r = unorm_block(&block[..8]);
let g = unorm_block(&block[8..]);
std::array::from_fn(|t| [r[t], g[t]])
}
/// Decodes a BC5 SNORM block; each texel is `[red, green]`.
pub fn decode_bc5_snorm(block: [u8; 16]) -> [[i8; 2]; 16] {
let r = snorm_block(&block[..8]);
let g = snorm_block(&block[8..]);
std::array::from_fn(|t| [r[t], g[t]])
}
/// Four-colour BC1-style palette, forced regardless of endpoint order.
fn colour_block(block: &[u8]) -> [[u8; 4]; 16] {
let first = u16::from_le_bytes([block[0], block[1]]);
let second = u16::from_le_bytes([block[2], block[3]]);
let mut p = [rgb565(first), rgb565(second), [255; 4], [255; 4]];
for c in 0..3 {
let a = u16::from(p[0][c]);
let b = u16::from(p[1][c]);
p[2][c] = ((2 * a + b) / 3) as u8;
p[3][c] = ((a + 2 * b) / 3) as u8;
}
let bits = u32::from_le_bytes([block[4], block[5], block[6], block[7]]);
std::array::from_fn(|t| p[((bits >> (2 * t)) & 3) as usize])
}
/// Decodes a BC2 block to 16 row-major RGBA8 texels (explicit 4-bit alpha).
pub fn decode_bc2(block: [u8; 16]) -> [[u8; 4]; 16] {
let mut out = colour_block(&block[8..]);
for (t, px) in out.iter_mut().enumerate() {
// Two texels per byte, low nibble first.
px[3] = ((block[t / 2] >> (4 * (t % 2))) & 15) * 17;
}
out
}
/// Decodes a BC3 block to 16 row-major RGBA8 texels (interpolated alpha).
pub fn decode_bc3(block: [u8; 16]) -> [[u8; 4]; 16] {
let mut out = colour_block(&block[8..]);
let alpha = unorm_block(&block[..8]);
for (px, a) in out.iter_mut().zip(alpha) {
px[3] = a;
}
out
}
+7 -1
View File
@@ -7,10 +7,16 @@
#![forbid(unsafe_code)]
mod bc;
pub mod sampler;
mod upload;
pub use bc::{
decode_bc2, decode_bc3, decode_bc4_snorm, decode_bc4_unorm, decode_bc5_snorm, decode_bc5_unorm,
};
pub use sampler::{AddressMode, FilterMode, SamplerDesc, SamplerError, TextureMetadata};
pub use upload::{Bc1Subresource, Bc1Upload, Bc1UploadDesc};
pub use upload::{
Bc1Subresource, Bc1Upload, Bc1UploadDesc, BcAlphaFormat, BcAlphaUpload, BcAlphaUploadDesc,
};
const BLOCK_BYTES: usize = 8;
const TILE_BLOCKS: usize = 2;
+207 -37
View File
@@ -32,56 +32,153 @@ pub struct Bc1Subresource<'a> {
impl<'a> Bc1Upload<'a> {
pub fn new(bytes: &'a [u8], desc: Bc1UploadDesc) -> Result<Self, TextureError> {
let max_mips = usize::BITS - desc.width.max(desc.height).leading_zeros();
if desc.format != 1
|| desc.usage != 1
|| desc.width == 0
|| desc.height == 0
|| desc.layers == 0
|| desc.mips == 0
|| desc.mips > max_mips
{
if desc.format != 1 || desc.usage != 1 {
return Err(TextureError::InvalidLayout);
}
let (blocks_x, blocks_y) = mip_blocks(desc.width, desc.height, 0);
let tight_row = blocks_x
.checked_mul(BLOCK_BYTES)
.ok_or(TextureError::SizeOverflow)?;
if desc.row_pitch < tight_row || !desc.row_pitch.is_multiple_of(BLOCK_BYTES) {
return Err(TextureError::InvalidLayout);
}
let minimum_slice = desc
.row_pitch
.checked_mul(blocks_y)
.ok_or(TextureError::SizeOverflow)?;
if desc.slice_pitch < minimum_slice || !desc.slice_pitch.is_multiple_of(BLOCK_BYTES) {
return Err(TextureError::InvalidLayout);
}
let size = desc
.slice_pitch
.checked_mul(desc.mips as usize)
.and_then(|size| size.checked_mul(desc.layers))
.ok_or(TextureError::SizeOverflow)?;
if bytes.len() != size {
return Err(TextureError::InvalidByteLength);
}
Self::layout(desc).validate(bytes.len(), BLOCK_BYTES)?;
Ok(Self { bytes, desc })
}
pub fn subresource(&self, layer: usize, mip: u32) -> Result<Bc1Subresource<'a>, TextureError> {
if layer >= self.desc.layers || mip >= self.desc.mips {
Self::layout(self.desc).subresource(self.bytes, layer, mip)
}
fn layout(desc: Bc1UploadDesc) -> PitchedLayout {
PitchedLayout {
width: desc.width,
height: desc.height,
mips: desc.mips,
layers: desc.layers,
row_pitch: desc.row_pitch,
slice_pitch: desc.slice_pitch,
}
}
}
/// A block-compressed format whose 16-byte block holds an alpha half followed
/// by a BC1-style colour half.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BcAlphaFormat {
/// Explicit 4-bit alpha per texel.
Bc2,
/// Interpolated alpha from two 8-bit endpoints and 3-bit indices.
Bc3,
}
/// A layer-major BC2 or BC3 upload with the same pitch rules as
/// [`Bc1UploadDesc`], measured in 16-byte blocks.
#[derive(Clone, Copy, Debug)]
pub struct BcAlphaUploadDesc {
pub width: usize,
pub height: usize,
pub mips: u32,
pub layers: usize,
pub format: BcAlphaFormat,
pub row_pitch: usize,
pub slice_pitch: usize,
}
#[derive(Debug)]
pub struct BcAlphaUpload<'a> {
bytes: &'a [u8],
desc: BcAlphaUploadDesc,
}
impl<'a> BcAlphaUpload<'a> {
/// Size of one BC2 or BC3 block in bytes.
pub const BLOCK_BYTES: usize = 16;
pub fn new(bytes: &'a [u8], desc: BcAlphaUploadDesc) -> Result<Self, TextureError> {
Self::layout(desc).validate(bytes.len(), Self::BLOCK_BYTES)?;
Ok(Self { bytes, desc })
}
pub fn format(&self) -> BcAlphaFormat {
self.desc.format
}
/// Selects one level; the returned rows hold 16-byte blocks.
pub fn subresource(&self, layer: usize, mip: u32) -> Result<Bc1Subresource<'a>, TextureError> {
Self::layout(self.desc).subresource(self.bytes, layer, mip)
}
fn layout(desc: BcAlphaUploadDesc) -> PitchedLayout {
PitchedLayout {
width: desc.width,
height: desc.height,
mips: desc.mips,
layers: desc.layers,
row_pitch: desc.row_pitch,
slice_pitch: desc.slice_pitch,
}
}
}
/// Format-independent pitch rules shared by the pitched uploads.
struct PitchedLayout {
width: usize,
height: usize,
mips: u32,
layers: usize,
row_pitch: usize,
slice_pitch: usize,
}
impl PitchedLayout {
fn validate(&self, len: usize, block_bytes: usize) -> Result<(), TextureError> {
let max_mips = usize::BITS - self.width.max(self.height).leading_zeros();
if self.width == 0
|| self.height == 0
|| self.layers == 0
|| self.mips == 0
|| self.mips > max_mips
{
return Err(TextureError::InvalidLayout);
}
let (blocks_x, blocks_y) = mip_blocks(self.width, self.height, 0);
let tight_row = blocks_x
.checked_mul(block_bytes)
.ok_or(TextureError::SizeOverflow)?;
if self.row_pitch < tight_row || !self.row_pitch.is_multiple_of(block_bytes) {
return Err(TextureError::InvalidLayout);
}
let minimum_slice = self
.row_pitch
.checked_mul(blocks_y)
.ok_or(TextureError::SizeOverflow)?;
if self.slice_pitch < minimum_slice || !self.slice_pitch.is_multiple_of(block_bytes) {
return Err(TextureError::InvalidLayout);
}
let size = self
.slice_pitch
.checked_mul(self.mips as usize)
.and_then(|size| size.checked_mul(self.layers))
.ok_or(TextureError::SizeOverflow)?;
if len != size {
return Err(TextureError::InvalidByteLength);
}
Ok(())
}
fn subresource<'a>(
&self,
bytes: &'a [u8],
layer: usize,
mip: u32,
) -> Result<Bc1Subresource<'a>, TextureError> {
if layer >= self.layers || mip >= self.mips {
return Err(TextureError::OutOfBounds);
}
// Construction proved that the complete array fits in the source span.
let offset = (layer * self.desc.mips as usize + mip as usize) * self.desc.slice_pitch;
let width = (self.desc.width >> mip).max(1);
let height = (self.desc.height >> mip).max(1);
let offset = (layer * self.mips as usize + mip as usize) * self.slice_pitch;
let width = (self.width >> mip).max(1);
let height = (self.height >> mip).max(1);
let rows = height.div_ceil(4);
Ok(Bc1Subresource {
bytes: &self.bytes[offset..offset + rows * self.desc.row_pitch],
bytes: &bytes[offset..offset + rows * self.row_pitch],
width,
height,
row_pitch: self.desc.row_pitch,
row_pitch: self.row_pitch,
})
}
}
@@ -182,4 +279,77 @@ mod tests {
);
}
}
const ALPHA_DESC: BcAlphaUploadDesc = BcAlphaUploadDesc {
width: 5,
height: 5,
mips: 2,
layers: 2,
format: BcAlphaFormat::Bc3,
row_pitch: 48,
slice_pitch: 112,
};
#[test]
fn selects_bc_alpha_subresources_in_sixteen_byte_blocks() {
let mut bytes = [0; 448];
// Layer 1 starts at 224; its base row 1, block 1 is at 224 + 48 + 16.
bytes[288..304].fill(0x5c);
bytes[336] = 0xa7; // Layer 1, mip 1, block 0.
let upload = BcAlphaUpload::new(&bytes, ALPHA_DESC).unwrap();
assert_eq!(upload.format(), BcAlphaFormat::Bc3);
let base = upload.subresource(1, 0).unwrap();
assert_eq!((base.width, base.height, base.row_pitch), (5, 5, 48));
assert_eq!(base.bytes.len(), 96);
assert_eq!(base.bytes[64..80], [0x5c; 16]);
let small = upload.subresource(1, 1).unwrap();
assert_eq!((small.width, small.height, small.bytes.len()), (2, 2, 48));
assert_eq!(small.bytes[0], 0xa7);
assert_eq!(
upload.subresource(2, 0).unwrap_err(),
TextureError::OutOfBounds
);
assert_eq!(
upload.subresource(0, 2).unwrap_err(),
TextureError::OutOfBounds
);
}
#[test]
fn rejects_bc1_pitches_for_sixteen_byte_blocks() {
let bytes = [0; 448];
// Each pitch is a valid BC1 multiple of 8 but not of 16, or is
// shorter than two 16-byte blocks.
for desc in [
BcAlphaUploadDesc {
row_pitch: 24,
..ALPHA_DESC
},
BcAlphaUploadDesc {
row_pitch: 40,
..ALPHA_DESC
},
BcAlphaUploadDesc {
slice_pitch: 104,
..ALPHA_DESC
},
BcAlphaUploadDesc {
slice_pitch: 80,
..ALPHA_DESC
},
BcAlphaUploadDesc {
mips: 4,
..ALPHA_DESC
},
] {
assert_eq!(
BcAlphaUpload::new(&bytes, desc).unwrap_err(),
TextureError::InvalidLayout
);
}
assert_eq!(
BcAlphaUpload::new(&bytes[..447], ALPHA_DESC).unwrap_err(),
TextureError::InvalidByteLength
);
}
}
+219
View File
@@ -0,0 +1,219 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Expected values are worked by hand from the Microsoft BC2-BC5 and Khronos
//! S3TC/RGTC formulas (truncating integer division); the production decoder is
//! never used to produce them.
use xenora_texture::{
decode_bc2, decode_bc3, decode_bc4_snorm, decode_bc4_unorm, decode_bc5_snorm, decode_bc5_unorm,
};
/// Packs sixteen 3-bit indices bit by bit, texel 0 in the lowest bit.
fn pack3(indices: [u8; 16]) -> [u8; 6] {
let mut out = [0u8; 6];
for (t, idx) in indices.iter().enumerate() {
for bit in 0..3 {
if (idx >> bit) & 1 == 1 {
let pos = 3 * t + bit;
out[pos / 8] |= 1 << (pos % 8);
}
}
}
out
}
fn bc4(a0: u8, a1: u8, indices: [u8; 16]) -> [u8; 8] {
let i = pack3(indices);
[a0, a1, i[0], i[1], i[2], i[3], i[4], i[5]]
}
const SEQ: [u8; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7];
fn expect(palette: [u8; 8]) -> [u8; 16] {
std::array::from_fn(|t| palette[t % 8])
}
#[test]
fn packing_helper_matches_hand_bytes() {
// 111 110 101 100 011 010 001 000 = 0xFAC688, twice.
assert_eq!(pack3(SEQ), [0x88, 0xC6, 0xFA, 0x88, 0xC6, 0xFA]);
}
#[test]
fn bc4_unorm_eight_value_mode() {
// a0 > a1: p[k+1] = ((7-k)*200 + k*100) / 7 for k = 1..6.
// 1300/7=185, 1200/7=171, 1100/7=157, 1000/7=142, 900/7=128, 800/7=114.
let out = decode_bc4_unorm(bc4(200, 100, SEQ));
assert_eq!(out, expect([200, 100, 185, 171, 157, 142, 128, 114]));
}
#[test]
fn bc4_unorm_six_value_mode_with_zero_and_255() {
// a0 <= a1: ((5-k)*100 + k*200) / 5: 600/5=120, 700/5=140, 800/5=160,
// 900/5=180, then 0 and 255.
let out = decode_bc4_unorm(bc4(100, 200, SEQ));
assert_eq!(out, expect([100, 200, 120, 140, 160, 180, 0, 255]));
// Equal endpoints also take the six-value mode.
let out = decode_bc4_unorm(bc4(50, 50, SEQ));
assert_eq!(out, expect([50, 50, 50, 50, 50, 50, 0, 255]));
}
#[test]
fn bc4_snorm_eight_value_mode_truncates_toward_zero() {
// a0=100 > a1=-100: 500/7=71, 300/7=42, 100/7=14, -100/7=-14,
// -300/7=-42, -500/7=-71.
let b = bc4(100, 0x9C, SEQ); // 0x9C = -100
let out = decode_bc4_snorm(b);
let e: [i8; 8] = [100, -100, 71, 42, 14, -14, -42, -71];
assert_eq!(out, std::array::from_fn(|t| e[t % 8]));
}
#[test]
fn bc4_snorm_six_value_mode_with_fixed_extremes() {
// a0=-100 <= a1=100: (-400+100)/5=-60, (-300+200)/5=-20, 20, 60, -127, 127.
let out = decode_bc4_snorm(bc4(0x9C, 100, SEQ));
let e: [i8; 8] = [-100, 100, -60, -20, 20, 60, -127, 127];
assert_eq!(out, std::array::from_fn(|t| e[t % 8]));
}
#[test]
fn bc4_snorm_minus_128_is_kept_for_endpoints_and_acts_as_minus_127() {
// a0=-128 < a1=127: six-value mode, x=-127: p2=(4*-127+127)/5=-381/5=-76.
let out = decode_bc4_snorm(bc4(0x80, 127, SEQ));
assert_eq!(out[0], -128);
assert_eq!(out[1], 127);
assert_eq!(out[2], -76);
// a0=127 > a1=-128: eight-value mode, y=-127: p2=(6*127-127)/7=635/7=90.
let out = decode_bc4_snorm(bc4(127, 0x80, SEQ));
assert_eq!(out[1], -128);
assert_eq!(out[2], 90);
}
#[test]
fn every_index_position_is_read_from_its_own_bits() {
// Texel n alone uses index 1 (value 100); all others index 0 (value 200).
// Texels 2, 5, 10 and 13 span byte boundaries.
for n in 0..16 {
let mut idx = [0u8; 16];
idx[n] = 1;
let out = decode_bc4_unorm(bc4(200, 100, idx));
for (t, v) in out.iter().enumerate() {
assert_eq!(*v, if t == n { 100 } else { 200 }, "texel {t}, set {n}");
}
}
}
#[test]
fn wrong_index_bit_order_would_fail() {
// Texel 5 occupies bits 15..17 (byte 1 bit 7, byte 2 bits 0-1); texel 10
// occupies bits 30..32 (byte 3 bits 6-7, byte 4 bit 0).
let mut idx = [0u8; 16];
idx[5] = 1;
idx[10] = 2;
let b = bc4(200, 100, idx);
// Hand-checked bytes: bit 15 set; bit 31 set.
assert_eq!(&b[2..], &[0x00, 0x80, 0x00, 0x80, 0x00, 0x00]);
let out = decode_bc4_unorm(b);
assert_eq!(out[5], 100);
assert_eq!(out[10], 185);
assert_ne!(out[5], out[10]);
// A decoder reading the 48 bits most-significant first (wrong order)
// lands on different texels; show that this block tells them apart.
let bits = b[2..8]
.iter()
.rev()
.fold(0u64, |a, x| (a << 8) | u64::from(*x));
let wrong = |t: usize| ((bits >> (45 - 3 * t)) & 7) as u8;
assert_ne!(wrong(5), 1);
assert_ne!(wrong(10), 2);
}
fn colour_bytes(c0: u16, c1: u16, indices: u32) -> [u8; 8] {
let (a, b, i) = (c0.to_le_bytes(), c1.to_le_bytes(), indices.to_le_bytes());
[a[0], a[1], b[0], b[1], i[0], i[1], i[2], i[3]]
}
#[test]
fn bc2_expands_four_bit_alpha_and_always_uses_four_colours() {
// Red 0xF800 = (255,0,0), blue 0x001F = (0,0,255).
// p2 = (170,0,85), p3 = (85,0,170). Texels 0..3 use indices 0..3.
let alpha = [0x10, 0x32, 0x54, 0x76, 0x98, 0xBA, 0xDC, 0xFE];
for (c0, c1, mid) in [
(0xF800, 0x001F, [[170, 0, 85], [85, 0, 170]]),
// Endpoints swapped: still four-colour mode, no transparent index.
(0x001F, 0xF800, [[85, 0, 170], [170, 0, 85]]),
] {
let mut block = [0u8; 16];
block[..8].copy_from_slice(&alpha);
block[8..].copy_from_slice(&colour_bytes(c0, c1, 0b11_10_01_00));
let out = decode_bc2(block);
let first = if c0 == 0xF800 {
[255, 0, 0]
} else {
[0, 0, 255]
};
let second = if c0 == 0xF800 {
[0, 0, 255]
} else {
[255, 0, 0]
};
let rgb = [first, second, mid[0], mid[1]];
for t in 0..16 {
assert_eq!(out[t][3], t as u8 * 17, "alpha texel {t}");
if t < 4 {
assert_eq!(out[t][..3], rgb[t], "colour texel {t}");
} else {
assert_eq!(out[t][..3], first, "colour texel {t}");
}
}
}
}
#[test]
fn bc3_uses_bc4_style_alpha_and_four_colour_block() {
let mut block = [0u8; 16];
block[..8].copy_from_slice(&bc4(200, 100, SEQ));
// c0 < c1 would be 3-colour in BC1; index 3 must stay interpolated.
block[8..].copy_from_slice(&colour_bytes(0x001F, 0xF800, 0xFFFF_FFFF));
let out = decode_bc3(block);
let alpha = expect([200, 100, 185, 171, 157, 142, 128, 114]);
for t in 0..16 {
assert_eq!(out[t][3], alpha[t]);
assert_eq!(out[t][..3], [170, 0, 85]);
}
// Six-value alpha mode.
block[..8].copy_from_slice(&bc4(100, 200, SEQ));
let alpha = expect([100, 200, 120, 140, 160, 180, 0, 255]);
let out = decode_bc3(block);
for t in 0..16 {
assert_eq!(out[t][3], alpha[t]);
}
}
#[test]
fn bc5_channel_order_is_red_then_green() {
// All texels index 1 = 0b001 repeated: bytes 0x49 0x92 0x24 twice.
let ones = [0x49, 0x92, 0x24, 0x49, 0x92, 0x24];
let mut block = [0u8; 16];
block[..2].copy_from_slice(&[200, 100]);
block[2..8].copy_from_slice(&ones);
block[8..10].copy_from_slice(&[100, 200]);
block[10..].copy_from_slice(&ones);
for texel in decode_bc5_unorm(block) {
assert_eq!(texel, [100, 200]);
}
}
#[test]
fn bc5_snorm_channels_and_fixed_values() {
// Index 6 = 0b110 repeated: bytes 0xB6 0x6D 0xDB twice.
let sixes = [0xB6, 0x6D, 0xDB, 0xB6, 0x6D, 0xDB];
let mut block = [0u8; 16];
// Red: a0=100 > a1=-100, index 6 = -42. Green: a0=-100 <= a1=100, index 6 = -127.
block[..2].copy_from_slice(&[100, 0x9C]);
block[2..8].copy_from_slice(&sixes);
block[8..10].copy_from_slice(&[0x9C, 100]);
block[10..].copy_from_slice(&sixes);
for texel in decode_bc5_snorm(block) {
assert_eq!(texel, [-42, -127]);
}
}