use std::path::Path;
use crate::error::Error;
use crate::extras::to_half_float;
use crate::math::ColorSpace;
use crate::textures::{MinFilter, Texture, TextureFilter, TextureType};
#[derive(Debug, Clone)]
pub struct HdrTexData {
pub width: u32,
pub height: u32,
pub header: String,
pub gamma: f64,
pub exposure: f64,
pub data: HdrData,
}
#[derive(Debug, Clone)]
pub enum HdrData {
HalfFloat(Vec<u16>),
Float(Vec<f32>),
}
impl HdrData {
pub fn len(&self) -> usize {
match self {
HdrData::HalfFloat(data) => data.len() / 4,
HdrData::Float(data) => data.len() / 4,
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
#[derive(Debug, Clone)]
pub struct HdrLoader {
texture_type: TextureType,
}
impl Default for HdrLoader {
fn default() -> Self {
Self::new()
}
}
impl HdrLoader {
pub fn new() -> Self {
Self {
texture_type: TextureType::HalfFloat,
}
}
pub fn set_data_type(&mut self, texture_type: TextureType) -> Result<&mut Self, Error> {
if !matches!(texture_type, TextureType::HalfFloat | TextureType::Float) {
return Err(Error::UnsupportedTextureType {
what: "HDR",
texture_type,
});
}
self.texture_type = texture_type;
Ok(self)
}
pub fn data_type(&self) -> TextureType {
self.texture_type
}
pub fn load<P: AsRef<Path>>(&self, path: P) -> Result<Texture, Error> {
let path = path.as_ref();
let bytes = crate::io::read(path)?;
let tex_data = self.parse(&bytes)?;
let texture = match &tex_data.data {
HdrData::HalfFloat(data) => {
Texture::data_rgba16float(tex_data.width, tex_data.height, data)
}
HdrData::Float(data) => {
Texture::data_rgba32float(tex_data.width, tex_data.height, data)
}
};
texture.set_color_space(ColorSpace::LinearSrgb);
texture.set_flip_y(true);
texture.set_generate_mipmaps(false);
texture.set_min_filter(MinFilter::Linear);
texture.set_mag_filter(TextureFilter::Linear);
Ok(texture)
}
pub fn parse(&self, buffer: &[u8]) -> Result<HdrTexData, Error> {
let header = read_header(buffer)?;
let (width, height) = (header.width, header.height);
let rgba = read_pixels_rle(&buffer[header.body..], width, height)?;
let texels = rgba.len() / 4;
let data = match self.texture_type {
TextureType::HalfFloat => {
let mut out = vec![0u16; texels * 4];
for j in 0..texels {
rgbe_to_rgb_half(&rgba[j * 4..j * 4 + 4], &mut out[j * 4..j * 4 + 4]);
}
HdrData::HalfFloat(out)
}
TextureType::Float => {
let mut out = vec![0f32; texels * 4];
for j in 0..texels {
rgbe_to_rgb_float(&rgba[j * 4..j * 4 + 4], &mut out[j * 4..j * 4 + 4]);
}
HdrData::Float(out)
}
texture_type => {
return Err(Error::UnsupportedTextureType {
what: "HDR",
texture_type,
})
}
};
Ok(HdrTexData {
width,
height,
header: header.string,
gamma: header.gamma,
exposure: header.exposure,
data,
})
}
}
fn rgbe_to_rgb_float(rgbe: &[u8], out: &mut [f32]) {
let scale = scale_of(rgbe[3]);
out[0] = (rgbe[0] as f64 * scale) as f32;
out[1] = (rgbe[1] as f64 * scale) as f32;
out[2] = (rgbe[2] as f64 * scale) as f32;
out[3] = 1.0;
}
fn rgbe_to_rgb_half(rgbe: &[u8], out: &mut [u16]) {
let scale = scale_of(rgbe[3]);
out[0] = to_half_float((rgbe[0] as f64 * scale).min(65504.0));
out[1] = to_half_float((rgbe[1] as f64 * scale).min(65504.0));
out[2] = to_half_float((rgbe[2] as f64 * scale).min(65504.0));
out[3] = to_half_float(1.0);
}
fn scale_of(exponent: u8) -> f64 {
(2.0f64).powf(exponent as f64 - 128.0) / 255.0
}
struct Header {
string: String,
gamma: f64,
exposure: f64,
width: u32,
height: u32,
body: usize,
}
fn read_header(buffer: &[u8]) -> Result<Header, Error> {
let mut pos = 0usize;
let mut line = fgets(buffer, &mut pos).ok_or_else(|| rgbe("Read Error: no header found"))?;
if !(line.starts_with("#?") && line[2..].chars().next().is_some_and(|c| !c.is_whitespace())) {
return Err(rgbe("Bad File Format: bad initial token"));
}
let mut string = String::new();
let mut gamma = 1.0f64;
let mut exposure = 1.0f64;
let mut width = 0u32;
let mut height = 0u32;
let mut have_format = false;
let mut have_dimensions = false;
string.push_str(&line);
string.push('\n');
loop {
line = match fgets(buffer, &mut pos) {
Some(line) => line,
None => break,
};
string.push_str(&line);
string.push('\n');
if line.starts_with('#') {
continue; }
if let Some(value) = key_value(&line, "GAMMA") {
if let Ok(value) = value.parse::<f64>() {
gamma = value;
}
}
if let Some(value) = key_value(&line, "EXPOSURE") {
if let Ok(value) = value.parse::<f64>() {
exposure = value;
}
}
if let Some(rest) = line.trim_start().strip_prefix("FORMAT=") {
let value = rest.trim_end();
if !value.is_empty() && !value.contains(char::is_whitespace) {
have_format = true;
}
}
if let Some((h, w)) = dimensions(&line) {
have_dimensions = true;
height = h;
width = w;
}
if have_format && have_dimensions {
break;
}
}
if !have_format {
return Err(rgbe("Bad File Format: missing format specifier"));
}
if !have_dimensions {
return Err(rgbe("Bad File Format: missing image size specifier"));
}
Ok(Header {
string,
gamma,
exposure,
width,
height,
body: pos,
})
}
fn fgets(buffer: &[u8], pos: &mut usize) -> Option<String> {
if *pos >= buffer.len() {
return None;
}
let newline = buffer[*pos..].iter().position(|&b| b == b'\n')?;
let line = buffer[*pos..*pos + newline]
.iter()
.map(|&b| b as char)
.collect();
*pos += newline + 1;
Some(line)
}
fn key_value<'a>(line: &'a str, key: &str) -> Option<&'a str> {
let rest = line.trim_start().strip_prefix(key)?;
let rest = rest.trim_start().strip_prefix('=')?.trim();
let mut parts = rest.splitn(2, '.');
let integer = parts.next()?;
if integer.is_empty() || !integer.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
if let Some(fraction) = parts.next() {
if fraction.is_empty() || !fraction.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
}
Some(rest)
}
fn dimensions(line: &str) -> Option<(u32, u32)> {
let mut fields = line.split_whitespace();
if fields.next()? != "-Y" {
return None;
}
let height = fields.next()?.parse().ok()?;
if fields.next()? != "+X" {
return None;
}
let width = fields.next()?.parse().ok()?;
if fields.next().is_some() {
return None;
}
Some((height, width))
}
fn read_pixels_rle(buffer: &[u8], w: u32, h: u32) -> Result<Vec<u8>, Error> {
let scanline_width = w as usize;
if !(8..=0x7fff).contains(&scanline_width)
|| buffer.len() < 4
|| buffer[0] != 2
|| buffer[1] != 2
|| buffer[2] & 0x80 != 0
{
return Ok(buffer.to_vec());
}
if scanline_width != (((buffer[2] as usize) << 8) | buffer[3] as usize) {
return Err(rgbe("Bad File Format: wrong scanline width"));
}
let mut data_rgba = vec![0u8; 4 * w as usize * h as usize];
if data_rgba.is_empty() {
return Err(rgbe("Memory Error: unable to allocate buffer space"));
}
let mut offset = 0usize;
let mut pos = 0usize;
let ptr_end = 4 * scanline_width;
let mut scanline_buffer = vec![0u8; ptr_end];
let mut num_scanlines = h;
while num_scanlines > 0 && pos < buffer.len() {
if pos + 4 > buffer.len() {
return Err(rgbe("Read Error: "));
}
let start = [
buffer[pos],
buffer[pos + 1],
buffer[pos + 2],
buffer[pos + 3],
];
pos += 4;
if start[0] != 2
|| start[1] != 2
|| (((start[2] as usize) << 8) | start[3] as usize) != scanline_width
{
return Err(rgbe("Bad File Format: bad rgbe scanline format"));
}
let mut ptr = 0usize;
while ptr < ptr_end && pos < buffer.len() {
let mut count = buffer[pos] as usize;
pos += 1;
let is_encoded_run = count > 128;
if is_encoded_run {
count -= 128;
}
if count == 0 || ptr + count > ptr_end {
return Err(rgbe("Bad File Format: bad scanline data"));
}
if is_encoded_run {
let byte_value = buffer[pos];
pos += 1;
scanline_buffer[ptr..ptr + count].fill(byte_value);
ptr += count;
} else {
let end = (pos + count).min(buffer.len());
let run = &buffer[pos..end];
scanline_buffer[ptr..ptr + run.len()].copy_from_slice(run);
ptr += count;
pos += count;
}
}
for i in 0..scanline_width {
data_rgba[offset] = scanline_buffer[i];
data_rgba[offset + 1] = scanline_buffer[i + scanline_width];
data_rgba[offset + 2] = scanline_buffer[i + 2 * scanline_width];
data_rgba[offset + 3] = scanline_buffer[i + 3 * scanline_width];
offset += 4;
}
num_scanlines -= 1;
}
Ok(data_rgba)
}
fn rgbe(reason: &str) -> Error {
Error::Rgbe {
reason: reason.to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn flat_hdr(body: &[u8], w: u32, h: u32) -> Vec<u8> {
let mut file =
format!("#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n\n-Y {h} +X {w}\n").into_bytes();
file.extend_from_slice(body);
file
}
#[test]
fn the_header_carries_the_dimensions_gamma_and_exposure() {
let file = b"#?RADIANCE\n# a comment\nGAMMA=2.2\nEXPOSURE= 0.5 \nFORMAT=32-bit_rle_rgbe\n\n-Y 3 +X 4\n\
\x00\x00\x00\x00".to_vec();
let parsed = HdrLoader::new().parse(&file).unwrap();
assert_eq!((parsed.width, parsed.height), (4, 3));
assert_eq!(parsed.gamma, 2.2);
assert_eq!(parsed.exposure, 0.5);
assert!(parsed.header.starts_with("#?RADIANCE\n"));
}
#[test]
fn a_file_without_the_magic_token_is_rejected() {
let error = HdrLoader::new().parse(b"RADIANCE\nFORMAT=32-bit_rle_rgbe\n\n-Y 1 +X 1\n");
assert!(matches!(error, Err(Error::Rgbe { .. })));
}
#[test]
fn a_file_without_a_format_line_is_rejected() {
let error = HdrLoader::new().parse(b"#?RADIANCE\n\n-Y 1 +X 1\n");
assert!(matches!(error, Err(Error::Rgbe { .. })));
}
#[test]
fn the_exponent_scale_is_the_rgbe_one() {
let file = flat_hdr(&[128, 128, 128, 129], 1, 1);
let mut loader = HdrLoader::new();
loader.set_data_type(TextureType::Float).unwrap();
let HdrData::Float(data) = loader.parse(&file).unwrap().data else {
panic!("the loader was set to FloatType");
};
assert_eq!(data.len(), 4);
let expected = (128.0f64 * 2.0f64.powf(1.0) / 255.0) as f32;
assert_eq!(data[0], expected);
assert_eq!(data[3], 1.0);
let HdrData::HalfFloat(data) = HdrLoader::new().parse(&file).unwrap().data else {
panic!("the loader defaults to HalfFloatType");
};
assert_eq!(data[0], to_half_float(128.0 * 2.0 / 255.0));
assert_eq!(data[3], 0x3c00);
}
#[test]
fn a_zero_texel_decodes_to_zero() {
let file = flat_hdr(&[0, 0, 0, 0], 1, 1);
let HdrData::HalfFloat(data) = HdrLoader::new().parse(&file).unwrap().data else {
unreachable!()
};
assert_eq!(data, vec![0, 0, 0, 0x3c00]);
}
#[test]
fn an_rle_scanline_de_interleaves_into_texels() {
let width = 8u32;
let mut body = vec![2u8, 2, (width >> 8) as u8, width as u8];
for channel in [10u8, 20, 30, 129] {
body.push(0x80 | width as u8);
body.push(channel);
}
let file = flat_hdr(&body, width, 1);
let mut loader = HdrLoader::new();
loader.set_data_type(TextureType::Float).unwrap();
let HdrData::Float(data) = loader.parse(&file).unwrap().data else {
unreachable!()
};
assert_eq!(data.len(), 8 * 4);
let scale = 2.0f64.powf(1.0) / 255.0;
for texel in data.chunks(4) {
assert_eq!(texel[0], (10.0 * scale) as f32);
assert_eq!(texel[1], (20.0 * scale) as f32);
assert_eq!(texel[2], (30.0 * scale) as f32);
assert_eq!(texel[3], 1.0);
}
}
#[test]
fn a_literal_run_is_copied_verbatim() {
let width = 8u32;
let mut body = vec![2u8, 2, 0, 8];
for channel in 0..4u8 {
body.push(width as u8); for i in 0..width as u8 {
body.push(if channel == 3 { 129 } else { i * 8 + channel });
}
}
let file = flat_hdr(&body, width, 1);
let HdrData::HalfFloat(data) = HdrLoader::new().parse(&file).unwrap().data else {
unreachable!()
};
let scale = 2.0f64.powf(1.0) / 255.0;
for (i, texel) in data.chunks(4).enumerate() {
assert_eq!(texel[0], to_half_float((i as u8 * 8) as f64 * scale));
assert_eq!(texel[1], to_half_float((i as u8 * 8 + 1) as f64 * scale));
}
}
#[test]
fn only_the_two_float_types_are_legal() {
assert!(HdrLoader::new()
.set_data_type(TextureType::UnsignedByte)
.is_err());
assert!(HdrLoader::new().set_data_type(TextureType::Float).is_ok());
}
}