diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..9f0f747 --- /dev/null +++ b/build.rs @@ -0,0 +1,27 @@ +use std::{ + env, fs, + path::Path +}; + +/// Writes the sRGB → linear table for every `u8` channel value to `OUT_DIR`, +/// so `color::transfer` can include it as a plain array. +fn main() +{ + println!("cargo::rerun-if-changed=NULL"); + + // `{:?}` prints the shortest literal that parses back to the exact same f32. + let values: Vec = (0..=255u8).map( + |c| format!("{:?}", srgb_to_linear(c as f32 / 255.0)) + ).collect(); + + let table = format!("[{}]", values.join(", ")); + let out = Path::new(&env::var_os("OUT_DIR").unwrap()).join("srgb_lut.rs"); + + fs::write(out, table).unwrap(); +} + +/// A copy of `color::transfer::srgb_to_linear`. +fn srgb_to_linear(c: f32) -> f32 +{ + if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) } +} diff --git a/src/color/mod.rs b/src/color/mod.rs new file mode 100644 index 0000000..591cf3e --- /dev/null +++ b/src/color/mod.rs @@ -0,0 +1 @@ +mod transfer; diff --git a/src/color/transfer.rs b/src/color/transfer.rs new file mode 100644 index 0000000..0ec7258 --- /dev/null +++ b/src/color/transfer.rs @@ -0,0 +1,31 @@ +/// `srgb_to_linear` of every `u8` channel value, generated by `build.rs`. +static LUT: [f32; 256] = include!(concat!(env!("OUT_DIR"), "/srgb_lut.rs")); + +/// Decodes one sRGB-encoded channel to linear light. +/// +/// sRGB (IEC 61966-2-1) stores values gamma-compressed, so more of the 0..=255 range +/// goes to dark tones, where the eye is most sensitive. The curve has two pieces: +/// - Near black it is a straight line with slope 1 / 12.92. A pure power curve has slope 0 +/// at black, and its inverse an infinite slope, which makes both directions unstable there. +/// - Everywhere else it is a power curve with exponent 2.4. The 0.055 offset shifts it +/// so it meets the line at 0.04045, and overall it behaves like a plain gamma of about 2.2. +pub(super) fn srgb_to_linear(c: f32) -> f32 +{ + if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) } +} + +/// Encodes one linear-light channel to sRGB. +/// +/// The exact inverse of `srgb_to_linear`: the same line and power curve, solved for the +/// other side. 0.0031308 is the old threshold 0.04045 mapped into linear light (0.04045 / 12.92). +pub(super) fn linear_to_srgb(l: f32) -> f32 +{ + if l <= 0.0031308 { 12.92 * l } else { 1.055 * l.powf(1.0 / 2.4) - 0.055 } +} + +/// Decodes one `u8` sRGB channel to linear light through a lookup table. +pub(super) fn srgb_u8_to_linear(c: u8) -> f32 { LUT[c as usize] } + +/// Encodes one linear-light channel to a `u8` sRGB channel. +/// Out-of-range input clamps, and NaN gives 0. +pub(super) fn linear_to_srgb_u8(l: f32) -> u8 { (linear_to_srgb(l).clamp(0.0, 1.0) * 255.0).round() as u8 } diff --git a/src/lib.rs b/src/lib.rs index e69de29..2c53cf0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -0,0 +1 @@ +pub mod color;