use crate::colour::ColourSpace;
use crate::error::{ViewportError, ViewportResult};
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum TextureRole {
Image,
NormalMap,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct TextureRequirement {
field: &'static str,
colour_space: ColourSpace,
role: TextureRole,
}
impl TextureRequirement {
pub const fn colour(field: &'static str) -> Self {
Self {
field,
colour_space: ColourSpace::Srgb,
role: TextureRole::Image,
}
}
pub const fn linear(field: &'static str) -> Self {
Self {
field,
colour_space: ColourSpace::Linear,
role: TextureRole::Image,
}
}
pub const fn normal_map(field: &'static str) -> Self {
Self {
field,
colour_space: ColourSpace::Linear,
role: TextureRole::NormalMap,
}
}
pub const fn field_name(self) -> &'static str {
self.field
}
pub const fn colour_space(self) -> ColourSpace {
self.colour_space
}
pub const fn role(self) -> TextureRole {
self.role
}
pub const fn constructor(self) -> &'static str {
match (self.role, self.colour_space) {
(TextureRole::NormalMap, _) => "TextureData::normal_map",
(_, ColourSpace::Srgb) => "TextureData::srgb",
(_, ColourSpace::Linear) => "TextureData::linear",
}
}
pub fn texture(self, width: u32, height: u32, rgba: Vec<u8>) -> TextureData {
match (self.role, self.colour_space) {
(TextureRole::NormalMap, _) => TextureData::normal_map(width, height, rgba),
(_, ColourSpace::Srgb) => TextureData::srgb(width, height, rgba),
(_, ColourSpace::Linear) => TextureData::linear(width, height, rgba),
}
}
}
#[derive(Clone, PartialEq)]
pub enum TexturePayload {
Rgba8(Vec<u8>),
Rgba32F(Vec<f32>),
Compressed {
format: CompressedFormat,
mip_levels: Vec<Vec<u8>>,
},
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum CompressedFormat {
Bc1Rgba,
Bc2Rgba,
Bc3Rgba,
Bc4R,
Bc4RSigned,
Bc5Rg,
Bc5RgSigned,
Bc6hRgb,
Bc6hRgbSigned,
Bc7Rgba,
Etc2Rgb8,
Etc2Rgb8A1,
Etc2Rgba8,
EacR11,
EacR11Signed,
EacRg11,
EacRg11Signed,
Astc {
block: AstcBlock,
hdr: bool,
},
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[allow(missing_docs)]
pub enum AstcBlock {
B4x4,
B5x4,
B5x5,
B6x5,
B6x6,
B8x5,
B8x6,
B8x8,
B10x5,
B10x6,
B10x8,
B10x10,
B12x10,
B12x12,
}
impl AstcBlock {
fn dimensions(self) -> (u32, u32) {
match self {
AstcBlock::B4x4 => (4, 4),
AstcBlock::B5x4 => (5, 4),
AstcBlock::B5x5 => (5, 5),
AstcBlock::B6x5 => (6, 5),
AstcBlock::B6x6 => (6, 6),
AstcBlock::B8x5 => (8, 5),
AstcBlock::B8x6 => (8, 6),
AstcBlock::B8x8 => (8, 8),
AstcBlock::B10x5 => (10, 5),
AstcBlock::B10x6 => (10, 6),
AstcBlock::B10x8 => (10, 8),
AstcBlock::B10x10 => (10, 10),
AstcBlock::B12x10 => (12, 10),
AstcBlock::B12x12 => (12, 12),
}
}
}
impl CompressedFormat {
pub fn block_dimensions(self) -> (u32, u32) {
match self {
CompressedFormat::Astc { block, .. } => block.dimensions(),
_ => (4, 4),
}
}
pub fn block_bytes(self) -> usize {
match self {
CompressedFormat::Bc1Rgba
| CompressedFormat::Bc4R
| CompressedFormat::Bc4RSigned
| CompressedFormat::Etc2Rgb8
| CompressedFormat::Etc2Rgb8A1
| CompressedFormat::EacR11
| CompressedFormat::EacR11Signed => 8,
CompressedFormat::Bc2Rgba
| CompressedFormat::Bc3Rgba
| CompressedFormat::Bc5Rg
| CompressedFormat::Bc5RgSigned
| CompressedFormat::Bc6hRgb
| CompressedFormat::Bc6hRgbSigned
| CompressedFormat::Bc7Rgba
| CompressedFormat::Etc2Rgba8
| CompressedFormat::EacRg11
| CompressedFormat::EacRg11Signed
| CompressedFormat::Astc { .. } => 16,
}
}
pub fn holds_colour(self) -> bool {
match self {
CompressedFormat::Bc1Rgba
| CompressedFormat::Bc2Rgba
| CompressedFormat::Bc3Rgba
| CompressedFormat::Bc7Rgba
| CompressedFormat::Etc2Rgb8
| CompressedFormat::Etc2Rgb8A1
| CompressedFormat::Etc2Rgba8 => true,
CompressedFormat::Astc { hdr, .. } => !hdr,
CompressedFormat::Bc4R
| CompressedFormat::Bc4RSigned
| CompressedFormat::Bc5Rg
| CompressedFormat::Bc5RgSigned
| CompressedFormat::Bc6hRgb
| CompressedFormat::Bc6hRgbSigned
| CompressedFormat::EacR11
| CompressedFormat::EacR11Signed
| CompressedFormat::EacRg11
| CompressedFormat::EacRg11Signed => false,
}
}
pub fn level_bytes(self, width: u32, height: u32) -> usize {
let (bw, bh) = self.block_dimensions();
let blocks_x = width.div_ceil(bw) as usize;
let blocks_y = height.div_ceil(bh) as usize;
blocks_x * blocks_y * self.block_bytes()
}
}
impl TexturePayload {
pub fn texel_count(&self) -> usize {
match self {
TexturePayload::Rgba8(v) => v.len() / 4,
TexturePayload::Rgba32F(v) => v.len() / 4,
TexturePayload::Compressed { format, mip_levels } => {
let (bw, bh) = format.block_dimensions();
let base = mip_levels.first().map_or(0, Vec::len);
base / format.block_bytes() * (bw * bh) as usize
}
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub enum UploadSlot {
Overlay,
OverlayStreaming,
Matcap,
Environment,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub enum TextureRejection {
WrongColourSpace,
WrongSize,
UnsupportedPayload,
NormalMap,
}
impl std::fmt::Display for UploadSlot {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
UploadSlot::Overlay => "an overlay texture",
UploadSlot::OverlayStreaming => "a streaming overlay texture",
UploadSlot::Matcap => "a matcap",
UploadSlot::Environment => "an environment",
})
}
}
impl std::fmt::Display for TextureRejection {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
TextureRejection::WrongColourSpace => "it needs the other colour space",
TextureRejection::WrongSize => "it needs a different size",
TextureRejection::UnsupportedPayload => "it cannot take this kind of payload",
TextureRejection::NormalMap => "it cannot take a normal map",
})
}
}
#[derive(Clone, PartialEq)]
#[non_exhaustive]
pub struct TextureData {
width: u32,
height: u32,
colour_space: ColourSpace,
role: TextureRole,
payload: TexturePayload,
}
impl TextureData {
pub fn srgb(width: u32, height: u32, rgba: Vec<u8>) -> Self {
Self {
width,
height,
colour_space: ColourSpace::Srgb,
role: TextureRole::Image,
payload: TexturePayload::Rgba8(rgba),
}
}
pub fn linear(width: u32, height: u32, rgba: Vec<u8>) -> Self {
Self {
width,
height,
colour_space: ColourSpace::Linear,
role: TextureRole::Image,
payload: TexturePayload::Rgba8(rgba),
}
}
pub fn normal_map(width: u32, height: u32, rgba: Vec<u8>) -> Self {
Self {
width,
height,
colour_space: ColourSpace::Linear,
role: TextureRole::NormalMap,
payload: TexturePayload::Rgba8(rgba),
}
}
pub fn for_slot(
width: u32,
height: u32,
rgba: Vec<u8>,
slot: crate::material::TextureSlot,
) -> Self {
slot.requirement().texture(width, height, rgba)
}
pub fn compressed(
width: u32,
height: u32,
format: CompressedFormat,
colour_space: ColourSpace,
mip_levels: Vec<Vec<u8>>,
) -> Self {
Self {
width,
height,
colour_space,
role: TextureRole::Image,
payload: TexturePayload::Compressed { format, mip_levels },
}
}
pub fn compressed_normal_map(
width: u32,
height: u32,
format: CompressedFormat,
mip_levels: Vec<Vec<u8>>,
) -> Self {
Self {
width,
height,
colour_space: ColourSpace::Linear,
role: TextureRole::NormalMap,
payload: TexturePayload::Compressed { format, mip_levels },
}
}
pub fn with_colour_space(mut self, colour_space: ColourSpace) -> Self {
self.colour_space = colour_space;
self
}
pub fn hdr(width: u32, height: u32, rgba: Vec<f32>) -> Self {
Self {
width,
height,
colour_space: ColourSpace::Linear,
role: TextureRole::Image,
payload: TexturePayload::Rgba32F(rgba),
}
}
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
pub fn colour_space(&self) -> ColourSpace {
self.colour_space
}
pub fn role(&self) -> TextureRole {
self.role
}
pub fn payload(&self) -> &TexturePayload {
&self.payload
}
pub fn validate(&self) -> ViewportResult<()> {
let expected = (self.width as usize)
.saturating_mul(self.height as usize)
.saturating_mul(4);
let srgb = self.colour_space == ColourSpace::Srgb;
if srgb && self.role == TextureRole::NormalMap {
return Err(ViewportError::InvalidTextureColourSpace {
reason: "a normal map holds directions, not colour, so it must be linear",
});
}
match &self.payload {
TexturePayload::Rgba8(v) => {
if v.len() != expected {
return Err(ViewportError::InvalidTextureData {
expected,
actual: v.len(),
});
}
}
TexturePayload::Rgba32F(v) => {
if v.len() != expected {
return Err(ViewportError::InvalidTextureData {
expected,
actual: v.len(),
});
}
if srgb {
return Err(ViewportError::InvalidTextureColourSpace {
reason: "float pixels are always linear",
});
}
}
TexturePayload::Compressed { format, mip_levels } => {
if srgb && !format.holds_colour() {
return Err(ViewportError::InvalidTextureColourSpace {
reason: "this compressed format holds data, not colour, so it must be linear",
});
}
let (bw, bh) = format.block_dimensions();
if self.width % bw != 0 || self.height % bh != 0 {
return Err(ViewportError::CompressedTextureNotBlockAligned {
width: self.width,
height: self.height,
block_width: bw,
block_height: bh,
});
}
if mip_levels.is_empty() {
return Err(ViewportError::InvalidCompressedTextureData {
level: 0,
expected: format.level_bytes(self.width, self.height),
actual: 0,
});
}
for (level, data) in mip_levels.iter().enumerate() {
let w = (self.width >> level).max(1);
let h = (self.height >> level).max(1);
let expected = format.level_bytes(w, h);
if data.len() != expected {
return Err(ViewportError::InvalidCompressedTextureData {
level: level as u32,
expected,
actual: data.len(),
});
}
}
}
}
Ok(())
}
pub fn into_payload(self) -> TexturePayload {
self.payload
}
}
impl std::fmt::Debug for TextureData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let (kind, len) = match &self.payload {
TexturePayload::Rgba8(v) => ("Rgba8", v.len()),
TexturePayload::Rgba32F(v) => ("Rgba32F", v.len()),
TexturePayload::Compressed { mip_levels, .. } => {
("Compressed", mip_levels.iter().map(Vec::len).sum())
}
};
f.debug_struct("TextureData")
.field("width", &self.width)
.field("height", &self.height)
.field("colour_space", &self.colour_space)
.field("role", &self.role)
.field("payload", &format_args!("{kind}({len})"))
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn constructors_record_the_space_they_name() {
let px = vec![0u8; 4 * 4 * 4];
assert_eq!(
TextureData::srgb(4, 4, px.clone()).colour_space(),
ColourSpace::Srgb
);
assert_eq!(
TextureData::linear(4, 4, px.clone()).colour_space(),
ColourSpace::Linear
);
assert_eq!(
TextureData::normal_map(4, 4, px).colour_space(),
ColourSpace::Linear
);
}
#[test]
fn a_normal_map_is_linear_but_not_a_plain_data_image() {
let px = vec![0u8; 4 * 4 * 4];
let data = TextureData::linear(4, 4, px.clone());
let normal = TextureData::normal_map(4, 4, px);
assert_eq!(data.colour_space(), normal.colour_space());
assert_eq!(data.role(), TextureRole::Image);
assert_eq!(normal.role(), TextureRole::NormalMap);
}
#[test]
fn float_payloads_are_always_linear() {
let texels = vec![0.0f32; 2 * 2 * 4];
assert_eq!(
TextureData::hdr(2, 2, texels).colour_space(),
ColourSpace::Linear
);
}
#[test]
fn pixels_are_passed_through_untouched() {
let px: Vec<u8> = (0..64).map(|i| i as u8).collect();
let data = TextureData::srgb(4, 4, px.clone());
match data.payload() {
TexturePayload::Rgba8(v) => assert_eq!(v, &px),
_ => panic!("expected an 8-bit payload"),
}
}
#[test]
fn validate_checks_the_length_against_the_dimensions() {
assert!(TextureData::srgb(4, 4, vec![0u8; 64]).validate().is_ok());
let err = TextureData::srgb(4, 4, vec![0u8; 10])
.validate()
.unwrap_err();
match err {
ViewportError::InvalidTextureData { expected, actual } => {
assert_eq!(expected, 64);
assert_eq!(actual, 10);
}
other => panic!("expected InvalidTextureData, got {other:?}"),
}
}
#[test]
fn float_payloads_are_measured_in_floats_not_bytes() {
assert!(TextureData::hdr(2, 2, vec![0.0f32; 16]).validate().is_ok());
assert!(TextureData::hdr(2, 2, vec![0.0f32; 64]).validate().is_err());
}
#[test]
fn building_is_infallible_so_call_sites_carry_one_result() {
let data = TextureData::linear(2, 3, vec![7u8; 2 * 3 * 4]);
assert_eq!(data.width(), 2);
assert_eq!(data.height(), 3);
assert_eq!(data.into_payload().texel_count(), 6);
}
#[test]
fn relabelling_changes_only_the_space() {
let px: Vec<u8> = (0..64).map(|i| i as u8).collect();
let data = TextureData::srgb(4, 4, px.clone()).with_colour_space(ColourSpace::Linear);
assert_eq!(data.colour_space(), ColourSpace::Linear);
assert_eq!(data.role(), TextureRole::Image);
assert!(data.validate().is_ok());
assert!(data.payload() == &TexturePayload::Rgba8(px));
}
#[test]
fn labels_that_cannot_be_right_fail_validation() {
let srgb_normal =
TextureData::normal_map(4, 4, vec![0u8; 64]).with_colour_space(ColourSpace::Srgb);
let srgb_float = TextureData::hdr(2, 2, vec![0.0; 16]).with_colour_space(ColourSpace::Srgb);
let srgb_bc5 = TextureData::compressed(
4,
4,
CompressedFormat::Bc5Rg,
ColourSpace::Srgb,
vec![vec![0u8; 16]],
);
for data in [srgb_normal, srgb_float, srgb_bc5] {
assert!(
matches!(
data.validate(),
Err(ViewportError::InvalidTextureColourSpace { .. })
),
"{data:?} should be rejected"
);
}
let srgb_bc7 = TextureData::compressed(
4,
4,
CompressedFormat::Bc7Rgba,
ColourSpace::Srgb,
vec![vec![0u8; 16]],
);
assert!(srgb_bc7.validate().is_ok());
}
#[test]
fn compressed_levels_are_measured_in_blocks() {
let levels = vec![vec![0u8; 32], vec![0u8; 8], vec![0u8; 8], vec![0u8; 8]];
let data =
TextureData::compressed(8, 8, CompressedFormat::Bc1Rgba, ColourSpace::Srgb, levels);
assert!(data.validate().is_ok());
assert_eq!(data.into_payload().texel_count(), 64);
let short = TextureData::compressed(
8,
8,
CompressedFormat::Bc1Rgba,
ColourSpace::Srgb,
vec![vec![0u8; 32], vec![0u8; 4]],
);
assert!(matches!(
short.validate(),
Err(ViewportError::InvalidCompressedTextureData {
level: 1,
expected: 8,
actual: 4
})
));
let ragged = TextureData::compressed(
6,
8,
CompressedFormat::Bc7Rgba,
ColourSpace::Srgb,
vec![vec![0u8; 64]],
);
assert!(matches!(
ragged.validate(),
Err(ViewportError::CompressedTextureNotBlockAligned { .. })
));
let empty = TextureData::compressed(
4,
4,
CompressedFormat::Bc7Rgba,
ColourSpace::Srgb,
Vec::new(),
);
assert!(matches!(
empty.validate(),
Err(ViewportError::InvalidCompressedTextureData { actual: 0, .. })
));
}
#[test]
fn astc_blocks_follow_their_footprint() {
let format = CompressedFormat::Astc {
block: AstcBlock::B6x5,
hdr: false,
};
assert_eq!(format.block_dimensions(), (6, 5));
assert_eq!(format.level_bytes(12, 10), 64);
assert!(format.holds_colour());
assert!(
!CompressedFormat::Astc {
block: AstcBlock::B4x4,
hdr: true
}
.holds_colour()
);
}
#[test]
fn debug_summarises_the_payload_rather_than_printing_it() {
let data = TextureData::srgb(4, 4, vec![0u8; 64]);
let shown = format!("{data:?}");
assert!(shown.contains("Rgba8(64)"), "got {shown}");
assert!(shown.contains("Srgb"), "got {shown}");
}
}