Share bounded DDS float surface decoding

Adapt MaterialCraft DDS backend integration from cc052aeaa8c61fbe6975674b6d5e28bb3c597b9d; retain float precision and first-surface behavior, keep transfer policy app-local.
This commit is contained in:
chasse20
2026-11-15 13:54:31 -05:00
committed by Dylan M. Taylor
parent 3f4de9ca11
commit eeaa77c081
4 changed files with 135 additions and 0 deletions
Generated
+36
View File
@@ -340,6 +340,12 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "astc-decode"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d6058e6202e20b7fa445692ec4b77ca8eb02508091fcd479ea753d9f60e376b"
[[package]]
name = "async-broadcast"
version = "0.7.2"
@@ -2758,6 +2764,8 @@ dependencies = [
name = "craft-texture"
version = "0.1.0"
dependencies = [
"bytemuck",
"dds",
"rayon",
"thiserror 2.0.21",
]
@@ -3295,6 +3303,19 @@ dependencies = [
"generic-array",
]
[[package]]
name = "dds"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e917a58e17b27d2f15626c490754ccced7f46592dc5b5f39a3013b89cba5f068"
dependencies = [
"astc-decode",
"bitflags 2.13.2",
"glam",
"resize",
"zerocopy",
]
[[package]]
name = "der"
version = "0.7.10"
@@ -4543,6 +4564,12 @@ dependencies = [
"xml-rs",
]
[[package]]
name = "glam"
version = "0.25.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "151665d9be52f9bb40fc7966565d39666f2d1e69233571b71b87791c7e0528b3"
[[package]]
name = "glifo"
version = "0.1.1"
@@ -8136,6 +8163,15 @@ dependencies = [
"web-sys",
]
[[package]]
name = "resize"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71725ecd5e0197b54fe859055b108688472ab6a358f8fbe5cee4a556b1b5bfea"
dependencies = [
"rgb",
]
[[package]]
name = "resvg"
version = "0.45.1"
+9
View File
@@ -9,6 +9,7 @@ repository.workspace = true
[features]
default = []
dds = ["dep:dds", "dep:bytemuck"]
parallel = ["dep:rayon"]
[lints]
@@ -17,3 +18,11 @@ workspace = true
[dependencies]
rayon = { workspace = true, optional = true }
thiserror = { workspace = true }
# Same decoder used by MaterialCraft; no parallel backend enabled.
dds = { version = "0.2.0", default-features = false, optional = true }
bytemuck = { workspace = true, optional = true }
[dev-dependencies]
dds = { version = "0.2.0", default-features = false }
bytemuck = { workspace = true }
+87
View File
@@ -0,0 +1,87 @@
//! First-surface DDS decoding to unmodified RGBA floats.
//!
//! Adapted from MaterialCraft `dds_image.rs` (originally chasse20, cc052aeaa8c61fbe6975674b6d5e28bb3c597b9d).
//! Uses the same `dds` backend and first-surface semantics, including the first cube face or
//! volume slice. This is not a whole-resource decoder. Transfer functions and image policy
//! belong to callers. [`Limits`] bounds the output float plane, not backend scratch buffers.
use crate::{ImageError, Kind, Limits};
#[derive(Debug, thiserror::Error)]
pub enum DecodeError {
#[error(transparent)]
Image(#[from] ImageError),
#[error("DDS decode failed: {0}")]
Decode(String),
}
/// Unmodified backend output. Alpha and out-of-range float values are not clamped.
#[derive(Debug)]
pub struct Surface {
pub width: u32,
pub height: u32,
pub rgba: Vec<f32>,
/// Exactly the backend's `Precision::F32` classification, as used by MaterialCraft.
pub source_precision_is_f32: bool,
}
/// Decode the first surface after validating dimensions, pixels and output-byte limits.
/// The output reservation is fallible; no second full-sized float plane is created.
pub fn decode_first(bytes: &[u8], limits: &Limits) -> Result<Surface, DecodeError> {
let error = |e: ::dds::DecodingError| DecodeError::Decode(e.to_string());
let mut decoder = ::dds::Decoder::new(std::io::Cursor::new(bytes)).map_err(error)?;
let size = decoder.main_size();
let len = limits.check(size.width, size.height, Kind::Color)?;
let mut rgba = Vec::new();
rgba.try_reserve_exact(len).map_err(|_| ImageError::OutOfMemory(size.width, size.height))?;
rgba.resize(len, 0.0_f32);
let view = ::dds::ImageViewMut::new(bytemuck::cast_slice_mut(&mut rgba), size, ::dds::ColorFormat::RGBA_F32)
.ok_or_else(|| DecodeError::Decode("invalid DDS output dimensions".into()))?;
decoder.read_surface(view).map_err(error)?;
Ok(Surface { width: size.width, height: size.height, rgba, source_precision_is_f32: decoder.format().precision() == ::dds::Precision::F32 })
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
fn bytes(format: ::dds::Format, payload: &[u8]) -> Vec<u8> {
let mut bytes = Vec::new();
::dds::Header::new_image(1, 1, format).write(&mut bytes).unwrap();
bytes.extend_from_slice(payload);
bytes
}
#[test]
fn rgba8_keeps_transfer_and_alpha_unmodified() {
let data = bytes(::dds::Format::R8G8B8A8_UNORM, &[128, 64, 255, 32]);
let image = decode_first(&data, &Limits::default()).unwrap();
assert_eq!((image.width, image.height), (1, 1));
assert!(!image.source_precision_is_f32);
for (actual, expected) in image.rgba.iter().zip([128.0 / 255.0, 64.0 / 255.0, 1.0, 32.0 / 255.0]) {
assert!((actual - expected).abs() < 1e-6);
}
}
#[test]
fn float_hdr_and_negative_values_survive() {
let values = [-0.5_f32, 2.0, 0.25, 0.75];
let payload: Vec<u8> = values.iter().flat_map(|v| v.to_le_bytes()).collect();
let image = decode_first(&bytes(::dds::Format::R32G32B32A32_FLOAT, &payload), &Limits::default()).unwrap();
assert!(image.source_precision_is_f32);
assert_eq!(image.rgba, values);
}
#[test]
fn checks_output_budget_and_truncation() {
let data = bytes(::dds::Format::R8G8B8A8_UNORM, &[1, 2, 3, 4]);
let mut limits = Limits::default();
limits.max_bytes = 15;
assert!(matches!(decode_first(&data, &limits), Err(DecodeError::Image(ImageError::TooLarge(1, 1)))));
limits.max_bytes = 16;
assert!(decode_first(&data, &limits).is_ok());
assert!(decode_first(&data[..data.len() - 1], &limits).is_err());
assert!(decode_first(&[], &limits).is_err());
}
}
+3
View File
@@ -29,6 +29,9 @@
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#[cfg(any(feature = "dds", test))]
pub mod dds;
use std::sync::Arc;
#[cfg(feature = "parallel")]